From be967624886ef89d743b1ef1a3b00f2949e68e6b Mon Sep 17 00:00:00 2001 From: skatef <2338212189@qq.com> Date: Thu, 11 Jun 2026 21:36:10 +0800 Subject: [PATCH 01/70] docs: add docker server migration plan --- .../plans/2026-06-11-docker-server.md | 1495 +++++++++++++++++ .../specs/2026-06-11-docker-server-design.md | 231 +++ 2 files changed, 1726 insertions(+) create mode 100644 docs/superpowers/plans/2026-06-11-docker-server.md create mode 100644 docs/superpowers/specs/2026-06-11-docker-server-design.md diff --git a/docs/superpowers/plans/2026-06-11-docker-server.md b/docs/superpowers/plans/2026-06-11-docker-server.md new file mode 100644 index 00000000..469b4ddc --- /dev/null +++ b/docs/superpowers/plans/2026-06-11-docker-server.md @@ -0,0 +1,1495 @@ +# Chat2API Docker Server Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add a Docker/server runtime for Chat2API that runs the existing OpenAI-compatible proxy and management API without Electron. + +**Architecture:** Keep the desktop app intact and add a separate Node server entrypoint. Introduce small runtime and storage boundaries so server-only behavior lives in isolated files, which keeps future upstream pulls easier to merge. + +**Tech Stack:** Node.js, TypeScript, Koa, existing Chat2API proxy modules, JSON storage, Vite/Rollup server build, Docker, Docker Compose, Node test runner. + +--- + +## Upstream Sync Policy + +This implementation must preserve a small Docker-specific patch surface. + +Docker-specific code should live in: + +```text +src/server/ +src/main/runtime/ +src/main/store/storage/ +docs/docker.md +Dockerfile +docker-compose.yml +.dockerignore +tests/server/ +``` + +When a file from upstream changes, prefer upstream behavior first. Reapply only these minimal compatibility edits: + +- Replace direct Electron calls in shared server paths with `runtime`. +- Keep provider behavior unchanged unless the provider imports Electron directly. +- Keep Docker boot configuration in `src/server/bootstrapConfig.ts`. +- Keep server build config in root-level build files. + +After pulling upstream, run: + +```bash +npm install +npm run test:server-compat +npm run build:server +docker build -t chat2api:server . +``` + +--- + +## File Structure + +Create: + +```text +src/server/index.ts +src/server/bootstrapConfig.ts +src/main/runtime/types.ts +src/main/runtime/index.ts +src/main/runtime/electronRuntime.ts +src/main/runtime/nodeRuntime.ts +src/main/store/storage/types.ts +src/main/store/storage/electronJsonStore.ts +src/main/store/storage/nodeJsonStore.ts +tests/server/server-imports.test.mjs +tests/server/bootstrap-config.test.mjs +tests/server/node-json-store.test.mjs +Dockerfile +.dockerignore +docker-compose.yml +docs/docker.md +vite.server.config.ts +``` + +Modify: + +```text +package.json +src/main/store/store.ts +src/main/lib/challenge.ts +src/main/oauth/adapters/base.ts +src/main/oauth/adapters/deepseek.ts +src/main/oauth/adapters/glm.ts +src/main/oauth/adapters/kimi.ts +src/main/oauth/adapters/minimax.ts +src/main/oauth/adapters/qwen.ts +src/main/proxy/adapters/perplexity.ts +``` + +Keep desktop-only files unchanged unless TypeScript imports require type-only adjustments: + +```text +src/main/index.ts +src/preload/index.ts +src/main/ipc/handlers.ts +src/main/window/ +src/main/tray/ +src/main/updater/ +src/renderer/ +``` + +--- + +### Task 1: Server Import Guard + +**Files:** +- Create: `tests/server/server-imports.test.mjs` + +- [ ] **Step 1: Write failing import guard test** + +Create `tests/server/server-imports.test.mjs`: + +```js +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import test from 'node:test' + +const repoRoot = process.cwd() + +const serverAllowedElectronFiles = new Set([ + path.normalize('src/main/runtime/electronRuntime.ts'), +]) + +function walk(dir) { + const entries = fs.readdirSync(dir, { withFileTypes: true }) + const files = [] + + for (const entry of entries) { + const fullPath = path.join(dir, entry.name) + if (entry.isDirectory()) { + files.push(...walk(fullPath)) + } else if (entry.isFile() && fullPath.endsWith('.ts')) { + files.push(fullPath) + } + } + + return files +} + +test('server runtime files do not import electron directly', () => { + const checkedRoots = [ + path.join(repoRoot, 'src/server'), + path.join(repoRoot, 'src/main/runtime'), + path.join(repoRoot, 'src/main/store/storage'), + ] + + const violations = [] + + for (const root of checkedRoots) { + if (!fs.existsSync(root)) continue + + for (const file of walk(root)) { + const relative = path.normalize(path.relative(repoRoot, file)) + if (serverAllowedElectronFiles.has(relative)) continue + + const source = fs.readFileSync(file, 'utf8') + if (source.includes("from 'electron'") || source.includes('from "electron"')) { + violations.push(relative) + } + } + } + + assert.deepEqual(violations, []) +}) +``` + +- [ ] **Step 2: Run test to verify it fails before files exist** + +Run: + +```bash +node --test tests/server/server-imports.test.mjs +``` + +Expected: PASS initially because the new server paths do not exist yet. This test becomes protective after later tasks create files. + +- [ ] **Step 3: Commit guard test** + +```bash +git add tests/server/server-imports.test.mjs +git commit -m "test: guard server runtime against electron imports" +``` + +--- + +### Task 2: Runtime Boundary + +**Files:** +- Create: `src/main/runtime/types.ts` +- Create: `src/main/runtime/nodeRuntime.ts` +- Create: `src/main/runtime/electronRuntime.ts` +- Create: `src/main/runtime/index.ts` + +- [ ] **Step 1: Create runtime types** + +Create `src/main/runtime/types.ts`: + +```ts +export interface RuntimeAdapter { + kind: 'electron' | 'node' + getDataDir(): string + isEncryptionAvailable(): boolean + encryptString(value: string): string + decryptString(value: string): string + getResourcePath(fileName: string): string + openExternal(url: string): Promise + notify(channel: string, payload: unknown): void +} +``` + +- [ ] **Step 2: Create Node runtime implementation** + +Create `src/main/runtime/nodeRuntime.ts`: + +```ts +import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto' +import { existsSync } from 'fs' +import { homedir } from 'os' +import { join, resolve } from 'path' +import type { RuntimeAdapter } from './types' + +const ENCRYPTION_PREFIX = 'c2a:v1:' + +function getKey(): Buffer | null { + const secret = process.env.CHAT2API_STORAGE_ENCRYPTION_KEY + if (!secret) return null + return createHash('sha256').update(secret).digest() +} + +function getDefaultDataDir(): string { + if (process.env.CHAT2API_DATA_DIR) { + return resolve(process.env.CHAT2API_DATA_DIR) + } + + if (process.env.NODE_ENV === 'production') { + return '/data' + } + + return join(homedir(), '.chat2api') +} + +export const nodeRuntime: RuntimeAdapter = { + kind: 'node', + + getDataDir(): string { + return getDefaultDataDir() + }, + + isEncryptionAvailable(): boolean { + return getKey() !== null + }, + + encryptString(value: string): string { + const key = getKey() + if (!key) return value + + const iv = randomBytes(12) + const cipher = createCipheriv('aes-256-gcm', key, iv) + const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]) + const tag = cipher.getAuthTag() + + return `${ENCRYPTION_PREFIX}${Buffer.concat([iv, tag, encrypted]).toString('base64')}` + }, + + decryptString(value: string): string { + const key = getKey() + if (!key || !value.startsWith(ENCRYPTION_PREFIX)) return value + + const payload = Buffer.from(value.slice(ENCRYPTION_PREFIX.length), 'base64') + const iv = payload.subarray(0, 12) + const tag = payload.subarray(12, 28) + const encrypted = payload.subarray(28) + const decipher = createDecipheriv('aes-256-gcm', key, iv) + decipher.setAuthTag(tag) + + return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8') + }, + + getResourcePath(fileName: string): string { + const candidates = [ + resolve(process.cwd(), fileName), + resolve(process.cwd(), 'resources', fileName), + resolve(__dirname, '..', '..', '..', fileName), + ] + + const found = candidates.find(candidate => existsSync(candidate)) + return found || candidates[0] + }, + + async openExternal(url: string): Promise { + console.log(`[Runtime] Open this URL manually: ${url}`) + }, + + notify(): void { + }, +} +``` + +- [ ] **Step 3: Create Electron runtime implementation** + +Create `src/main/runtime/electronRuntime.ts`: + +```ts +import { app, BrowserWindow, safeStorage, shell } from 'electron' +import { homedir } from 'os' +import { join } from 'path' +import type { RuntimeAdapter } from './types' + +export const electronRuntime: RuntimeAdapter = { + kind: 'electron', + + getDataDir(): string { + return join(homedir(), '.chat2api') + }, + + isEncryptionAvailable(): boolean { + try { + return safeStorage.isEncryptionAvailable() + } catch { + return false + } + }, + + encryptString(value: string): string { + return Buffer.from(safeStorage.encryptString(value)).toString('base64') + }, + + decryptString(value: string): string { + return safeStorage.decryptString(Buffer.from(value, 'base64')) + }, + + getResourcePath(fileName: string): string { + if (app.isPackaged) { + return join(process.resourcesPath, fileName) + } + + return join(app.getAppPath(), fileName) + }, + + async openExternal(url: string): Promise { + await shell.openExternal(url) + }, + + notify(channel: string, payload: unknown): void { + BrowserWindow.getAllWindows().forEach((win) => { + win.webContents.send(channel, payload) + }) + }, +} +``` + +- [ ] **Step 4: Create runtime selector** + +Create `src/main/runtime/index.ts`: + +```ts +import type { RuntimeAdapter } from './types' +import { nodeRuntime } from './nodeRuntime' + +let runtime: RuntimeAdapter = nodeRuntime + +export function setRuntime(nextRuntime: RuntimeAdapter): void { + runtime = nextRuntime +} + +export function getRuntime(): RuntimeAdapter { + return runtime +} + +export type { RuntimeAdapter } +``` + +- [ ] **Step 5: Run import guard** + +Run: + +```bash +node --test tests/server/server-imports.test.mjs +``` + +Expected: PASS. Only `src/main/runtime/electronRuntime.ts` may import Electron. + +- [ ] **Step 6: Commit runtime boundary** + +```bash +git add src/main/runtime tests/server/server-imports.test.mjs +git commit -m "feat: add runtime boundary for server mode" +``` + +--- + +### Task 3: Node JSON Store Adapter + +**Files:** +- Create: `src/main/store/storage/types.ts` +- Create: `src/main/store/storage/nodeJsonStore.ts` +- Create: `src/main/store/storage/electronJsonStore.ts` +- Create: `tests/server/node-json-store.test.mjs` +- Modify: `src/main/store/store.ts` + +- [ ] **Step 1: Write Node JSON store test** + +Create `tests/server/node-json-store.test.mjs`: + +```js +import assert from 'node:assert/strict' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import test from 'node:test' + +test('node json store persists values under configured directory', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'chat2api-store-')) + process.env.CHAT2API_DATA_DIR = tempDir + + const { NodeJsonStore } = await import('../../out-server/main/store/storage/nodeJsonStore.js') + + const store = new NodeJsonStore({ + name: 'data', + cwd: tempDir, + defaults: { + providers: [], + accounts: [], + config: { proxyPort: 8080 }, + }, + }) + + store.set('config', { proxyPort: 18080 }) + + const secondStore = new NodeJsonStore({ + name: 'data', + cwd: tempDir, + defaults: {}, + }) + + assert.equal(secondStore.get('config').proxyPort, 18080) + assert.ok(fs.existsSync(path.join(tempDir, 'data.json'))) +}) +``` + +- [ ] **Step 2: Create storage interface** + +Create `src/main/store/storage/types.ts`: + +```ts +export interface JsonStoreOptions> { + name: string + cwd: string + defaults: T + encryptionKey?: string +} + +export interface JsonStore> { + get(key: K): T[K] + get(key: string): unknown + set(key: K, value: T[K]): void + set(key: string, value: unknown): void + delete(key: string): void + clear(): void +} +``` + +- [ ] **Step 3: Create Node JSON store** + +Create `src/main/store/storage/nodeJsonStore.ts`: + +```ts +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs' +import { join } from 'path' +import type { JsonStore, JsonStoreOptions } from './types' + +export class NodeJsonStore> implements JsonStore { + private readonly filePath: string + private data: Record + + constructor(options: JsonStoreOptions) { + mkdirSync(options.cwd, { recursive: true }) + this.filePath = join(options.cwd, `${options.name}.json`) + this.data = { ...options.defaults } + + if (existsSync(this.filePath)) { + try { + const parsed = JSON.parse(readFileSync(this.filePath, 'utf8')) + this.data = { ...this.data, ...parsed } + } catch { + renameSync(this.filePath, join(options.cwd, `${options.name}.corrupted.${Date.now()}.json`)) + this.persist() + } + } else { + this.persist() + } + } + + get(key: string): unknown { + return this.data[key] + } + + set(key: string, value: unknown): void { + this.data = { + ...this.data, + [key]: value, + } + this.persist() + } + + delete(key: string): void { + const next = { ...this.data } + delete next[key] + this.data = next + this.persist() + } + + clear(): void { + this.data = {} + this.persist() + } + + private persist(): void { + writeFileSync(this.filePath, `${JSON.stringify(this.data, null, 2)}\n`, 'utf8') + } +} +``` + +- [ ] **Step 4: Create Electron JSON store wrapper** + +Create `src/main/store/storage/electronJsonStore.ts`: + +```ts +import type { JsonStoreOptions } from './types' + +export async function createElectronJsonStore>( + options: JsonStoreOptions +): Promise { + const module = await import('electron-store') + const Store = module.default + return new Store(options) +} +``` + +- [ ] **Step 5: Modify store manager to use runtime and storage adapter** + +In `src/main/store/store.ts`, replace the Electron import: + +```ts +import type { BrowserWindow } from 'electron' +import { getRuntime } from '../runtime' +import { NodeJsonStore } from './storage/nodeJsonStore' +import { createElectronJsonStore } from './storage/electronJsonStore' +``` + +Replace dynamic `electron-store` initialization with: + +```ts +const runtime = getRuntime() + +if (runtime.kind === 'electron') { + this.store = await createElectronJsonStore({ + name: 'data', + cwd: storagePath, + defaults: this.getDefaultData() as unknown as Record, + encryptionKey: this.getEncryptionKey(), + }) +} else { + this.store = new NodeJsonStore({ + name: 'data', + cwd: storagePath, + defaults: this.getDefaultData() as unknown as Record, + }) +} +``` + +Replace `getStoragePath()` body with: + +```ts +private getStoragePath(): string { + return getRuntime().getDataDir() +} +``` + +Replace `getEncryptionKey()` body with: + +```ts +private getEncryptionKey(): string | undefined { + return getRuntime().isEncryptionAvailable() + ? 'chat2api-fixed-encryption-key-v1' + : undefined +} +``` + +Replace `encryptData()` body with: + +```ts +encryptData(data: string): string { + try { + const runtime = getRuntime() + if (runtime.isEncryptionAvailable()) { + return runtime.encryptString(data) + } + } catch (error) { + console.error('Failed to encrypt data:', error) + } + return data +} +``` + +Replace `decryptData()` body with: + +```ts +decryptData(encryptedData: string): string { + try { + const runtime = getRuntime() + if (runtime.isEncryptionAvailable()) { + return runtime.decryptString(encryptedData) + } + } catch (error) { + console.error('Failed to decrypt data:', error) + } + return encryptedData +} +``` + +- [ ] **Step 6: Build server once storage adapter exists** + +Run: + +```bash +npm run build:server +``` + +Expected before Task 7 script exists: command missing. Continue to Task 7 before treating this as a failure. + +- [ ] **Step 7: Commit storage adapter** + +```bash +git add src/main/store/store.ts src/main/store/storage tests/server/node-json-store.test.mjs +git commit -m "feat: add node json storage for server mode" +``` + +--- + +### Task 4: Server Bootstrap Configuration + +**Files:** +- Create: `src/server/bootstrapConfig.ts` +- Create: `tests/server/bootstrap-config.test.mjs` + +- [ ] **Step 1: Write bootstrap config test** + +Create `tests/server/bootstrap-config.test.mjs`: + +```js +import assert from 'node:assert/strict' +import test from 'node:test' + +test('server env produces config overrides', async () => { + process.env.CHAT2API_HOST = '0.0.0.0' + process.env.CHAT2API_PORT = '18080' + process.env.CHAT2API_ENABLE_MANAGEMENT_API = 'true' + process.env.CHAT2API_MANAGEMENT_SECRET = 'mgmt_test_secret' + process.env.CHAT2API_LOAD_BALANCE_STRATEGY = 'fill-first' + + const { createServerConfigOverrides } = await import('../../out-server/server/bootstrapConfig.js') + const overrides = createServerConfigOverrides() + + assert.equal(overrides.proxyHost, '0.0.0.0') + assert.equal(overrides.proxyPort, 18080) + assert.equal(overrides.loadBalanceStrategy, 'fill-first') + assert.deepEqual(overrides.managementApi, { + enableManagementApi: true, + managementApiSecret: 'mgmt_test_secret', + }) +}) +``` + +- [ ] **Step 2: Create bootstrap config module** + +Create `src/server/bootstrapConfig.ts`: + +```ts +import type { AppConfig, LoadBalanceStrategy } from '../main/store/types' +import { storeManager } from '../main/store/store' + +const VALID_STRATEGIES = new Set([ + 'round-robin', + 'fill-first', + 'failover', +]) + +function parsePort(value: string | undefined): number | undefined { + if (!value) return undefined + const parsed = Number.parseInt(value, 10) + if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) { + throw new Error(`Invalid CHAT2API_PORT: ${value}`) + } + return parsed +} + +function parseBoolean(value: string | undefined): boolean | undefined { + if (value === undefined) return undefined + return ['1', 'true', 'yes', 'on'].includes(value.toLowerCase()) +} + +export function createServerConfigOverrides(): Partial { + const overrides: Partial = {} + const port = parsePort(process.env.CHAT2API_PORT) + const host = process.env.CHAT2API_HOST + const strategy = process.env.CHAT2API_LOAD_BALANCE_STRATEGY as LoadBalanceStrategy | undefined + const enableManagementApi = parseBoolean(process.env.CHAT2API_ENABLE_MANAGEMENT_API) + const managementSecret = process.env.CHAT2API_MANAGEMENT_SECRET + const enableApiKey = parseBoolean(process.env.CHAT2API_ENABLE_API_KEY) + const logLevel = process.env.CHAT2API_LOG_LEVEL as AppConfig['logLevel'] | undefined + + if (port !== undefined) overrides.proxyPort = port + if (host) overrides.proxyHost = host + + if (strategy) { + if (!VALID_STRATEGIES.has(strategy)) { + throw new Error(`Invalid CHAT2API_LOAD_BALANCE_STRATEGY: ${strategy}`) + } + overrides.loadBalanceStrategy = strategy + } + + if (logLevel) { + if (!['debug', 'info', 'warn', 'error'].includes(logLevel)) { + throw new Error(`Invalid CHAT2API_LOG_LEVEL: ${logLevel}`) + } + overrides.logLevel = logLevel + } + + if (enableApiKey !== undefined) { + overrides.enableApiKey = enableApiKey + } + + if (enableManagementApi !== undefined || managementSecret) { + overrides.managementApi = { + enableManagementApi: enableManagementApi ?? Boolean(managementSecret), + managementApiSecret: managementSecret || '', + } + } + + return overrides +} + +export function applyServerConfigOverrides(): AppConfig { + const overrides = createServerConfigOverrides() + if (Object.keys(overrides).length === 0) { + return storeManager.getConfig() + } + return storeManager.updateConfig(overrides) +} +``` + +- [ ] **Step 3: Commit bootstrap config** + +```bash +git add src/server/bootstrapConfig.ts tests/server/bootstrap-config.test.mjs +git commit -m "feat: add server env bootstrap config" +``` + +--- + +### Task 5: Server Entrypoint + +**Files:** +- Create: `src/server/index.ts` + +- [ ] **Step 1: Create server entrypoint** + +Create `src/server/index.ts`: + +```ts +import { setRuntime } from '../main/runtime' +import { nodeRuntime } from '../main/runtime/nodeRuntime' +import { proxyServer } from '../main/proxy/server' +import { storeManager } from '../main/store/store' +import { applyServerConfigOverrides } from './bootstrapConfig' + +setRuntime(nodeRuntime) + +async function shutdown(signal: string): Promise { + console.log(`[Server] Received ${signal}, shutting down`) + try { + await proxyServer.stop() + } finally { + storeManager.flushPendingWrites() + process.exit(0) + } +} + +async function main(): Promise { + process.on('SIGINT', () => void shutdown('SIGINT')) + process.on('SIGTERM', () => void shutdown('SIGTERM')) + + process.on('uncaughtException', (error) => { + console.error('[Server] Uncaught exception:', error) + }) + + process.on('unhandledRejection', (reason) => { + console.error('[Server] Unhandled rejection:', reason) + }) + + await storeManager.initialize() + const config = applyServerConfigOverrides() + + const started = await proxyServer.start(config.proxyPort, config.proxyHost) + if (!started) { + throw new Error(`Failed to start server on ${config.proxyHost}:${config.proxyPort}`) + } + + console.log(`[Server] Chat2API listening on ${config.proxyHost}:${config.proxyPort}`) +} + +void main().catch((error) => { + console.error('[Server] Startup failed:', error) + process.exit(1) +}) +``` + +- [ ] **Step 2: Commit server entrypoint** + +```bash +git add src/server/index.ts +git commit -m "feat: add node server entrypoint" +``` + +--- + +### Task 6: Replace Resource and Browser Runtime Calls + +**Files:** +- Modify: `src/main/lib/challenge.ts` +- Modify: `src/main/oauth/adapters/base.ts` +- Modify: `src/main/oauth/adapters/deepseek.ts` +- Modify: `src/main/oauth/adapters/glm.ts` +- Modify: `src/main/oauth/adapters/kimi.ts` +- Modify: `src/main/oauth/adapters/minimax.ts` +- Modify: `src/main/oauth/adapters/qwen.ts` + +- [ ] **Step 1: Replace DeepSeek WASM path** + +In `src/main/lib/challenge.ts`, replace: + +```ts +import { app } from 'electron' +``` + +with: + +```ts +import { getRuntime } from '../runtime' +``` + +Replace WASM path selection with: + +```ts +const wasmPath = getRuntime().getResourcePath('sha3_wasm_bg.7b9ca65ddd.wasm') +``` + +- [ ] **Step 2: Replace base OAuth browser opening** + +In `src/main/oauth/adapters/base.ts`, keep `BrowserWindow` as a type-only import if required: + +```ts +import type { BrowserWindow } from 'electron' +import { getRuntime } from '../../runtime' +``` + +Replace `shell.openExternal(url)` calls with: + +```ts +await getRuntime().openExternal(url) +``` + +- [ ] **Step 3: Replace provider manual login browser opening** + +For each OAuth adapter listed in this task, replace: + +```ts +import { shell } from 'electron' +``` + +with: + +```ts +import { getRuntime } from '../../runtime' +``` + +Replace: + +```ts +await shell.openExternal(loginUrl) +``` + +with: + +```ts +await getRuntime().openExternal(loginUrl) +``` + +Use the provider's existing login URL variable for each file. + +- [ ] **Step 4: Run Electron import scan** + +Run: + +```bash +Get-ChildItem -Path src/main -Recurse -Filter *.ts | Select-String -Pattern "from 'electron'" +``` + +Expected remaining server-relevant Electron imports: + +```text +src/main/runtime/electronRuntime.ts +src/main/proxy/adapters/perplexity.ts +``` + +Desktop-only imports may remain in `src/main/index.ts`, `src/main/ipc`, `src/main/window`, `src/main/tray`, `src/main/updater`, `src/main/oauth/inAppLogin.ts`, and `src/main/oauth/manager.ts`. + +- [ ] **Step 5: Commit runtime call replacements** + +```bash +git add src/main/lib/challenge.ts src/main/oauth/adapters/base.ts src/main/oauth/adapters/deepseek.ts src/main/oauth/adapters/glm.ts src/main/oauth/adapters/kimi.ts src/main/oauth/adapters/minimax.ts src/main/oauth/adapters/qwen.ts +git commit -m "refactor: route shared runtime calls through adapter" +``` + +--- + +### Task 7: Server Build Configuration + +**Files:** +- Create: `vite.server.config.ts` +- Modify: `package.json` + +- [ ] **Step 1: Create server Vite config** + +Create `vite.server.config.ts`: + +```ts +import { builtinModules } from 'module' +import { resolve } from 'path' +import { defineConfig } from 'vite' + +const external = [ + ...builtinModules, + ...builtinModules.map(moduleName => `node:${moduleName}`), + 'electron', + 'electron-store', +] + +export default defineConfig({ + build: { + outDir: 'out-server', + emptyOutDir: true, + target: 'node20', + ssr: true, + lib: { + entry: resolve(__dirname, 'src/server/index.ts'), + formats: ['cjs'], + fileName: () => 'server/index.js', + }, + rollupOptions: { + external, + output: { + format: 'cjs', + entryFileNames: '[name].js', + chunkFileNames: 'chunks/[name]-[hash].js', + }, + }, + }, + resolve: { + alias: { + '@shared': resolve(__dirname, 'src/shared'), + }, + }, +}) +``` + +- [ ] **Step 2: Add package scripts** + +In `package.json`, add scripts: + +```json +"build:server": "vite build --config vite.server.config.ts", +"start:server": "node out-server/server/index.js", +"test:server-compat": "npm run build:server && node --test tests/server/*.test.mjs" +``` + +- [ ] **Step 3: Build server** + +Run: + +```bash +npm run build:server +``` + +Expected: build succeeds and writes `out-server/server/index.js`. + +- [ ] **Step 4: Run server compatibility tests** + +Run: + +```bash +npm run test:server-compat +``` + +Expected: all `tests/server/*.test.mjs` tests pass. + +- [ ] **Step 5: Commit build config** + +```bash +git add package.json vite.server.config.ts tests/server +git commit -m "build: add server build and compatibility tests" +``` + +--- + +### Task 8: Perplexity Node Compatibility + +**Files:** +- Modify: `src/main/proxy/adapters/perplexity.ts` + +- [ ] **Step 1: Replace Electron net import** + +In `src/main/proxy/adapters/perplexity.ts`, replace: + +```ts +import { net } from 'electron' +``` + +with: + +```ts +import axios from 'axios' +``` + +- [ ] **Step 2: Replace Electron request implementation** + +Find the method that calls `net.request`. Replace that request path with an axios streaming request: + +```ts +const response = await axios.post(QUERY_ENDPOINT, requestData, { + headers, + responseType: 'stream', + timeout: 120000, + validateStatus: () => true, +}) + +if (response.status < 200 || response.status >= 300) { + throw new Error(`Perplexity request failed: HTTP ${response.status}`) +} + +return response.data +``` + +Preserve existing headers, cookie handling, request body shape, and stream parser code. + +- [ ] **Step 3: Build server** + +Run: + +```bash +npm run build:server +``` + +Expected: build succeeds without requiring Electron for server entrypoint. + +- [ ] **Step 4: Commit Perplexity compatibility** + +```bash +git add src/main/proxy/adapters/perplexity.ts +git commit -m "refactor: replace electron net in perplexity adapter" +``` + +--- + +### Task 9: Docker Packaging + +**Files:** +- Create: `Dockerfile` +- Create: `.dockerignore` +- Create: `docker-compose.yml` +- Create: `docs/docker.md` + +- [ ] **Step 1: Create Dockerfile** + +Create `Dockerfile`: + +```dockerfile +FROM node:22-bookworm-slim AS deps +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci + +FROM node:22-bookworm-slim AS build +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY . . +RUN npm run build:server + +FROM node:22-bookworm-slim AS runtime +WORKDIR /app +ENV NODE_ENV=production +ENV CHAT2API_HOST=0.0.0.0 +ENV CHAT2API_PORT=8080 +ENV CHAT2API_DATA_DIR=/data +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev && npm cache clean --force +COPY --from=build /app/out-server ./out-server +COPY --from=build /app/sha3_wasm_bg.7b9ca65ddd.wasm ./sha3_wasm_bg.7b9ca65ddd.wasm +RUN mkdir -p /data +VOLUME ["/data"] +EXPOSE 8080 +CMD ["node", "out-server/server/index.js"] +``` + +- [ ] **Step 2: Create dockerignore** + +Create `.dockerignore`: + +```text +.git +dist +out +out-server +node_modules +npm-debug.log +docs/screenshots +backup +*.log +``` + +- [ ] **Step 3: Create Docker Compose file** + +Create `docker-compose.yml`: + +```yaml +services: + chat2api: + build: + context: . + dockerfile: Dockerfile + image: chat2api:server + container_name: chat2api + restart: unless-stopped + ports: + - "8080:8080" + environment: + CHAT2API_HOST: 0.0.0.0 + CHAT2API_PORT: 8080 + CHAT2API_DATA_DIR: /data + CHAT2API_ENABLE_MANAGEMENT_API: "true" + CHAT2API_MANAGEMENT_SECRET: ${CHAT2API_MANAGEMENT_SECRET} + CHAT2API_LOG_LEVEL: info + CHAT2API_LOAD_BALANCE_STRATEGY: round-robin + volumes: + - chat2api-data:/data + +volumes: + chat2api-data: +``` + +- [ ] **Step 4: Create Docker docs** + +Create `docs/docker.md`: + +```md +# Chat2API Docker Server + +## Build + +```bash +docker build -t chat2api:server . +``` + +## Run + +```bash +docker run -d \ + --name chat2api \ + -p 8080:8080 \ + -v chat2api-data:/data \ + -e CHAT2API_HOST=0.0.0.0 \ + -e CHAT2API_PORT=8080 \ + -e CHAT2API_ENABLE_MANAGEMENT_API=true \ + -e CHAT2API_MANAGEMENT_SECRET=mgmt_change_me \ + chat2api:server +``` + +## Health Check + +```bash +curl http://localhost:8080/health +``` + +## Add A Qwen Account + +```bash +curl -X POST http://localhost:8080/v0/management/accounts \ + -H "Authorization: Bearer mgmt_change_me" \ + -H "Content-Type: application/json" \ + -d '{ + "providerId": "qwen", + "name": "qwen-account-1", + "credentials": { + "ticket": "tongyi_sso_ticket_value" + } + }' +``` + +## Add A Second Qwen Account + +```bash +curl -X POST http://localhost:8080/v0/management/accounts \ + -H "Authorization: Bearer mgmt_change_me" \ + -H "Content-Type: application/json" \ + -d '{ + "providerId": "qwen", + "name": "qwen-account-2", + "credentials": { + "ticket": "another_tongyi_sso_ticket_value" + } + }' +``` + +## Pin A Model To One Account + +Use `preferredAccountId` from the account list: + +```bash +curl http://localhost:8080/v0/management/providers/qwen/accounts \ + -H "Authorization: Bearer mgmt_change_me" +``` + +```bash +curl -X POST http://localhost:8080/v0/management/model-mappings \ + -H "Authorization: Bearer mgmt_change_me" \ + -H "Content-Type: application/json" \ + -d '{ + "requestModel": "qwen-primary", + "actualModel": "Qwen3.7-Max", + "preferredProviderId": "qwen", + "preferredAccountId": "account_id_from_previous_response" + }' +``` + +## Upstream Update Flow + +```bash +git fetch upstream +git merge upstream/main +npm install +npm run test:server-compat +npm run build:server +docker build -t chat2api:server . +``` + +If conflicts occur, keep upstream provider logic first, then reapply the runtime boundary and server entrypoint. Docker-specific files are intentionally isolated under `src/server`, `src/main/runtime`, `src/main/store/storage`, and root Docker files. +``` + +- [ ] **Step 5: Build Docker image** + +Run: + +```bash +docker build -t chat2api:server . +``` + +Expected: image builds successfully. + +- [ ] **Step 6: Commit Docker packaging** + +```bash +git add Dockerfile .dockerignore docker-compose.yml docs/docker.md +git commit -m "build: add docker server packaging" +``` + +--- + +### Task 10: Local Server Smoke Test + +**Files:** +- No source files + +- [ ] **Step 1: Build server** + +Run: + +```bash +npm run build:server +``` + +Expected: build succeeds. + +- [ ] **Step 2: Start server locally** + +Run: + +```bash +$env:CHAT2API_HOST='127.0.0.1' +$env:CHAT2API_PORT='18080' +$env:CHAT2API_ENABLE_MANAGEMENT_API='true' +$env:CHAT2API_MANAGEMENT_SECRET='mgmt_test_secret' +npm run start:server +``` + +Expected: server logs: + +```text +[Server] Chat2API listening on 127.0.0.1:18080 +``` + +- [ ] **Step 3: Check health** + +In another shell: + +```bash +curl http://127.0.0.1:18080/health +``` + +Expected response includes: + +```json +{ + "status": "running" +} +``` + +- [ ] **Step 4: Check management API authentication** + +Run: + +```bash +curl http://127.0.0.1:18080/v0/management/accounts +``` + +Expected: HTTP 401. + +Run: + +```bash +curl http://127.0.0.1:18080/v0/management/accounts -H "Authorization: Bearer mgmt_test_secret" +``` + +Expected: HTTP 200 with: + +```json +{ + "success": true, + "data": [] +} +``` + +- [ ] **Step 5: Commit smoke-test documentation update if command details changed** + +If the verified command differs from `docs/docker.md`, update `docs/docker.md` and commit: + +```bash +git add docs/docker.md +git commit -m "docs: update docker smoke test commands" +``` + +--- + +### Task 11: Docker Smoke Test + +**Files:** +- No source files + +- [ ] **Step 1: Build image** + +Run: + +```bash +docker build -t chat2api:server . +``` + +Expected: image builds successfully. + +- [ ] **Step 2: Run container** + +Run: + +```bash +docker rm -f chat2api-test +docker run -d \ + --name chat2api-test \ + -p 18081:8080 \ + -e CHAT2API_ENABLE_MANAGEMENT_API=true \ + -e CHAT2API_MANAGEMENT_SECRET=mgmt_test_secret \ + chat2api:server +``` + +Expected: container stays running. + +- [ ] **Step 3: Check health** + +Run: + +```bash +curl http://127.0.0.1:18081/health +``` + +Expected: response includes: + +```json +{ + "status": "running" +} +``` + +- [ ] **Step 4: Check management API** + +Run: + +```bash +curl http://127.0.0.1:18081/v0/management/providers \ + -H "Authorization: Bearer mgmt_test_secret" +``` + +Expected: response includes built-in providers. + +- [ ] **Step 5: Clean up container** + +Run: + +```bash +docker rm -f chat2api-test +``` + +Expected: container removed. + +--- + +### Task 12: Final Verification + +**Files:** +- No source files + +- [ ] **Step 1: Run existing source artifact check** + +Run: + +```bash +npm run check:source-artifacts +``` + +Expected: PASS. + +- [ ] **Step 2: Run desktop build** + +Run: + +```bash +npm run build +``` + +Expected: existing Electron build still succeeds. + +- [ ] **Step 3: Run server compatibility tests** + +Run: + +```bash +npm run test:server-compat +``` + +Expected: server build and server tests pass. + +- [ ] **Step 4: Run Docker build** + +Run: + +```bash +docker build -t chat2api:server . +``` + +Expected: image builds successfully. + +- [ ] **Step 5: Commit final fixes** + +If verification required fixes, commit them: + +```bash +git add . +git commit -m "fix: complete docker server verification" +``` + +--- + +## Completion Criteria + +- `npm run build` still builds the Electron app. +- `npm run build:server` builds the Node server. +- `npm run test:server-compat` passes. +- Docker image starts and responds to `/health`. +- Management API can create Qwen accounts in Docker. +- The Docker-specific patch surface remains isolated for future upstream pulls. diff --git a/docs/superpowers/specs/2026-06-11-docker-server-design.md b/docs/superpowers/specs/2026-06-11-docker-server-design.md new file mode 100644 index 00000000..21edf7b2 --- /dev/null +++ b/docs/superpowers/specs/2026-06-11-docker-server-design.md @@ -0,0 +1,231 @@ +# Chat2API Docker Server Design + +## Background + +Chat2API is currently packaged as an Electron desktop application. The proxy itself is already a Koa service under `src/main/proxy`, and the project already has a management API under `src/main/proxy/routes/management`. That makes a server deployment realistic without rewriting provider forwarding logic. + +The blocking issue is not the proxy architecture. The blocking issue is that several shared modules import Electron APIs directly: + +- `src/main/index.ts` starts the Electron app. +- `src/preload/index.ts` exposes IPC to the renderer. +- `src/main/ipc/handlers.ts` bridges the desktop UI to store, proxy, OAuth, logs, and settings. +- `src/main/store/store.ts` imports `app`, `safeStorage`, and `BrowserWindow` from Electron. +- `src/main/lib/challenge.ts` uses `app.isPackaged` and `app.getAppPath()` to locate the DeepSeek WASM file. +- `src/main/proxy/adapters/perplexity.ts` imports `net` from Electron. +- `src/main/oauth/*` contains browser-window and `shell.openExternal` flows. +- `src/main/window`, `src/main/tray`, and `src/main/updater` are desktop-only. + +The Docker version should reuse the proxy and provider code while keeping all server-specific changes isolated. This is important because upstream source updates should remain easy to pull and rebase. + +## Goals + +1. Add a Docker/server runtime that runs without Electron. +2. Preserve the existing Electron desktop application. +3. Reuse the existing Koa proxy, management API, provider configs, adapters, account model, load balancer, sessions, request logs, and statistics. +4. Support Qwen multi-account management through the existing management API. +5. Make future upstream updates easy by isolating Docker-specific code and minimizing edits to upstream-owned provider logic. +6. Provide clear Docker usage documentation and a repeatable verification command set. + +## Non-Goals + +- Do not rewrite the React renderer into a web management UI in the first server version. +- Do not replace JSON storage with a database in the first server version. +- Do not remove Electron, IPC, tray, updater, or desktop login flows. +- Do not require browser automation inside the Docker image. +- Do not guarantee Perplexity parity until its Electron `net` usage is replaced and verified under Node. + +## Recommended Approach + +Build a server-only runtime beside the desktop runtime. + +The server entrypoint lives under `src/server`. Electron-specific runtime functions are hidden behind small adapters under `src/main/runtime`. Server code imports the proxy server and store manager through the same business-layer APIs used today, but the runtime adapter supplies Node-compatible behavior for storage paths, encryption availability, browser opening, and resource lookup. + +This approach is preferable to placing Electron in Docker because the image stays smaller, the runtime is easier to operate on a server, and upstream desktop code remains intact. It is also preferable to immediately converting the React renderer to a web UI because the management API already covers the operations needed for headless server use. + +## Architecture + +### Runtime Boundary + +Add a runtime boundary: + +```text +src/main/runtime/ + index.ts + types.ts + nodeRuntime.ts + electronRuntime.ts +``` + +Responsibilities: + +- Return the data directory. +- Report whether secure string encryption is available. +- Encrypt and decrypt strings. +- Resolve bundled resources such as `sha3_wasm_bg.7b9ca65ddd.wasm`. +- Open external URLs when a desktop runtime exists, or log/return the URL under server runtime. +- Provide a desktop window notification hook that is a no-op under server runtime. + +The boundary keeps most future upstream changes away from Docker-specific code. If upstream changes provider behavior, the Docker version can usually pull those changes without touching `src/server` or `src/main/runtime`. + +### Server Entrypoint + +Add `src/server/index.ts`. + +Responsibilities: + +- Initialize the store. +- Apply server environment overrides. +- Ensure the management API can be enabled from environment variables. +- Start the proxy server on `CHAT2API_HOST` and `CHAT2API_PORT`. +- Flush logs and stop the proxy on `SIGINT` and `SIGTERM`. + +The server entrypoint should not import Electron, renderer, preload, IPC, tray, updater, or window modules. + +### Storage + +Keep the existing data shape and default `StoreSchema`. In Docker, default storage path should be `/data`, configurable with `CHAT2API_DATA_DIR`. + +The existing store uses `electron-store`. For the server version, use a Node-compatible store adapter. The first version can continue using the same JSON file structure through a small storage abstraction, rather than introducing SQLite or another database. + +Recommended files: + +```text +src/main/store/storage/ + types.ts + electronJsonStore.ts + nodeJsonStore.ts +``` + +The `StoreManager` should depend on this local interface instead of constructing `electron-store` directly. The Electron implementation can keep using `electron-store`; the Node implementation can persist `data.json` under `CHAT2API_DATA_DIR`. + +### Environment Configuration + +Server runtime should support: + +```text +CHAT2API_HOST=0.0.0.0 +CHAT2API_PORT=8080 +CHAT2API_DATA_DIR=/data +CHAT2API_MANAGEMENT_SECRET=mgmt_change_me +CHAT2API_ENABLE_MANAGEMENT_API=true +CHAT2API_ENABLE_API_KEY=false +CHAT2API_API_KEYS= +CHAT2API_LOG_LEVEL=info +CHAT2API_LOAD_BALANCE_STRATEGY=round-robin +CHAT2API_STORAGE_ENCRYPTION_KEY= +``` + +If `CHAT2API_ENABLE_MANAGEMENT_API=true` and `CHAT2API_MANAGEMENT_SECRET` is set, the server should update config on boot so `/v0/management/*` is usable immediately. + +### Provider Compatibility + +Most adapters already use `axios` and should work in Node once store and runtime imports are fixed. + +Known provider-specific work: + +- DeepSeek: resolve WASM path without `electron.app`. +- Perplexity: replace `electron.net` with Node-compatible request code. +- OAuth manual adapters: replace `shell.openExternal` with runtime `openExternal`. Under Docker, return a login URL and require manual credentials. +- In-app OAuth: remain desktop-only. Server version should expose manual credential management through management API. + +### Management API + +The existing management API is the primary server administration surface. It already supports: + +- provider listing and updates; +- account CRUD and validation; +- API key CRUD; +- model mappings with `preferredAccountId`; +- sessions; +- statistics; +- proxy status. + +Docker documentation should show how to add multiple Qwen accounts: + +```bash +curl -X POST http://localhost:8080/v0/management/accounts \ + -H "Authorization: Bearer $CHAT2API_MANAGEMENT_SECRET" \ + -H "Content-Type: application/json" \ + -d '{ + "providerId": "qwen", + "name": "qwen-account-1", + "credentials": { + "ticket": "tongyi_sso_ticket_value" + } + }' +``` + +### Docker Packaging + +Add: + +```text +Dockerfile +.dockerignore +docker-compose.yml +docs/docker.md +``` + +The image should run the Node server entrypoint, expose port `8080`, and mount `/data`. + +### Upstream Sync Strategy + +The Docker layer must be easy to reapply after pulling upstream source updates. + +Rules: + +1. Keep server-only code in `src/server`. +2. Keep runtime shims in `src/main/runtime`. +3. Keep storage abstraction files under `src/main/store/storage`. +4. Avoid changing provider adapter behavior unless an adapter imports Electron directly. +5. Avoid changing Electron UI, IPC, tray, updater, and renderer files unless a shared type or build script requires it. +6. Keep Docker files at repository root and docs under `docs/docker.md`. +7. Add tests that fail if the server entrypoint or server bundle imports Electron. +8. Use environment bootstrapping instead of editing default provider definitions for server-only defaults. +9. When upstream changes providers, pull the upstream change first, then rerun the server compatibility tests before touching Docker code. + +Future update flow: + +```bash +git fetch upstream +git merge upstream/main +npm install +npm run test:server-compat +npm run build:server +docker build -t chat2api:server . +docker run --rm -p 8080:8080 -e CHAT2API_ENABLE_MANAGEMENT_API=true -e CHAT2API_MANAGEMENT_SECRET=mgmt_test chat2api:server +``` + +If conflicts occur, resolve them in this order: + +1. Keep upstream provider logic. +2. Reapply runtime boundary imports only where Electron imports block Node. +3. Reapply server entrypoint and Docker scripts. +4. Run provider smoke tests through `/v1/models` and `/v1/chat/completions`. + +## Testing Strategy + +Add tests for: + +- server entrypoint does not import Electron; +- server runtime resolves `/data` from environment; +- environment bootstrap enables management API and sets host/port; +- Node storage reads and writes provider, account, config, sessions, logs, and statistics data; +- Qwen account CRUD works through management API; +- model mapping can target a specific account; +- `/v1/models` returns models when accounts exist; +- `/health` reports running status; +- Docker image starts and responds to `/health`. + +Live provider tests should remain opt-in because they require real credentials. + +## Acceptance Criteria + +1. `npm run build:server` produces a runnable Node server artifact without Electron. +2. `npm run start:server` starts the proxy service locally. +3. Docker image starts with `/data` mounted. +4. `/health` responds without authentication. +5. `/v0/management/accounts` works with `Authorization: Bearer `. +6. Multiple Qwen accounts can be added and selected by the load balancer. +7. Existing Electron build commands still work. +8. Server compatibility tests protect the Docker layer from accidental Electron imports. From 0a20bef9ec6cac40b17b349aef2352d0042f3ec5 Mon Sep 17 00:00:00 2001 From: skatef <2338212189@qq.com> Date: Sat, 13 Jun 2026 02:15:00 +0800 Subject: [PATCH 02/70] feat: implement Docker support with server configuration and multimodal input for Qwen AI --- .dockerignore | 16 + .gitignore | 2 + Dockerfile | 28 + docker-compose.yml | 23 + docs/docker-browser-import-plan.md | 38 + docs/docker.md | 213 +++++ docs/qwen-ai-multimodal-plan.md | 182 ++++ package.json | 4 + src/main/index.ts | 4 + src/main/ipc/handlers.ts | 34 +- src/main/lib/challenge.ts | 8 +- src/main/oauth/adapters/base.ts | 5 +- src/main/oauth/adapters/deepseek.ts | 4 +- src/main/oauth/adapters/glm.ts | 4 +- src/main/oauth/adapters/kimi.ts | 4 +- src/main/oauth/adapters/minimax.ts | 4 +- src/main/oauth/adapters/qwen.ts | 4 +- src/main/providers/builtin/qwen-ai.ts | 26 +- src/main/providers/checker.ts | 12 +- src/main/providers/custom.ts | 8 + src/main/providers/modelSync.ts | 62 ++ src/main/proxy/adapters/perplexity.ts | 210 +--- src/main/proxy/adapters/qwen-ai-files.ts | 544 +++++++++++ .../proxy/adapters/qwen-ai-token-refresh.ts | 113 +++ src/main/proxy/adapters/qwen-ai.ts | 104 +- src/main/proxy/loadbalancer.ts | 15 +- src/main/proxy/routes/management/accounts.ts | 108 ++- src/main/proxy/routes/management/config.ts | 10 +- src/main/proxy/routes/management/providers.ts | 303 ++++++ src/main/proxy/routes/management/sessions.ts | 72 ++ .../proxy/routes/management/statistics.ts | 579 ++++++++++++ src/main/proxy/server.ts | 7 +- src/main/proxy/types.ts | 14 +- src/main/runtime/electronRuntime.ts | 46 + src/main/runtime/index.ts | 14 + src/main/runtime/nodeRuntime.ts | 82 ++ src/main/runtime/types.ts | 10 + src/main/store/providers.ts | 7 + src/main/store/storage/electronJsonStore.ts | 9 + src/main/store/storage/nodeJsonStore.ts | 54 ++ src/main/store/storage/types.ts | 15 + src/main/store/store.ts | 208 ++-- src/main/store/types.ts | 4 + src/main/types/ali-oss.d.ts | 4 +- src/preload/index.ts | 6 + src/renderer/admin.html | 13 + .../src/components/dashboard/QuickActions.tsx | 10 +- src/renderer/src/components/layout/Header.tsx | 6 +- .../components/providers/AddAccountDialog.tsx | 255 ++++- .../providers/AddProviderDialog.tsx | 223 ++++- .../src/components/providers/ProviderCard.tsx | 2 +- .../src/components/proxy/ProxyConfigForm.tsx | 10 + .../src/components/proxy/ProxyStatus.tsx | 14 + src/renderer/src/i18n/locales/en-US.json | 35 +- src/renderer/src/i18n/locales/zh-CN.json | 35 +- src/renderer/src/pages/Dashboard.tsx | 3 + src/renderer/src/pages/Providers.tsx | 5 + src/renderer/src/types/electron.d.ts | 22 + src/renderer/src/web-admin-api.ts | 894 ++++++++++++++++++ src/renderer/src/web-main.tsx | 122 +++ src/server/admin/app.css | 370 ++++++++ src/server/admin/assets.ts | 68 ++ src/server/admin/index.html | 110 +++ src/server/bootstrapConfig.ts | 84 ++ src/server/index.ts | 45 + src/shared/types.ts | 6 + tests/providers/provider-flow.test.ts | 11 +- tests/providers/qwen-ai-model-sync.test.mjs | 121 +++ tests/server/admin-page-assets.test.mjs | 19 + tests/server/bootstrap-config.test.mjs | 23 + tests/server/browser-import-routes.test.mjs | 48 + tests/server/builtin-providers-api.test.mjs | 33 + tests/server/node-json-store.test.mjs | 31 + tests/server/node-runtime.test.mjs | 22 + tests/server/qwen-ai-auto-refresh.test.mjs | 44 + tests/server/qwen-ai-multimodal.test.mjs | 87 ++ .../qwen-ai-thinking-model-selection.test.mjs | 12 + tests/server/run-server-tests.mjs | 15 + tests/server/server-imports.test.mjs | 56 ++ tests/server/store-immutability.test.mjs | 12 + .../web-admin-electron-api-contract.test.mjs | 197 ++++ vite.admin.config.ts | 24 + vite.server.config.ts | 38 + 83 files changed, 5920 insertions(+), 428 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 docker-compose.yml create mode 100644 docs/docker-browser-import-plan.md create mode 100644 docs/docker.md create mode 100644 docs/qwen-ai-multimodal-plan.md create mode 100644 src/main/providers/modelSync.ts create mode 100644 src/main/proxy/adapters/qwen-ai-files.ts create mode 100644 src/main/proxy/adapters/qwen-ai-token-refresh.ts create mode 100644 src/main/runtime/electronRuntime.ts create mode 100644 src/main/runtime/index.ts create mode 100644 src/main/runtime/nodeRuntime.ts create mode 100644 src/main/runtime/types.ts create mode 100644 src/main/store/storage/electronJsonStore.ts create mode 100644 src/main/store/storage/nodeJsonStore.ts create mode 100644 src/main/store/storage/types.ts create mode 100644 src/renderer/admin.html create mode 100644 src/renderer/src/web-admin-api.ts create mode 100644 src/renderer/src/web-main.tsx create mode 100644 src/server/admin/app.css create mode 100644 src/server/admin/assets.ts create mode 100644 src/server/admin/index.html create mode 100644 src/server/bootstrapConfig.ts create mode 100644 src/server/index.ts create mode 100644 tests/providers/qwen-ai-model-sync.test.mjs create mode 100644 tests/server/admin-page-assets.test.mjs create mode 100644 tests/server/bootstrap-config.test.mjs create mode 100644 tests/server/browser-import-routes.test.mjs create mode 100644 tests/server/builtin-providers-api.test.mjs create mode 100644 tests/server/node-json-store.test.mjs create mode 100644 tests/server/node-runtime.test.mjs create mode 100644 tests/server/qwen-ai-auto-refresh.test.mjs create mode 100644 tests/server/qwen-ai-multimodal.test.mjs create mode 100644 tests/server/qwen-ai-thinking-model-selection.test.mjs create mode 100644 tests/server/run-server-tests.mjs create mode 100644 tests/server/server-imports.test.mjs create mode 100644 tests/server/store-immutability.test.mjs create mode 100644 tests/server/web-admin-electron-api-contract.test.mjs create mode 100644 vite.admin.config.ts create mode 100644 vite.server.config.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..4b6d3f0f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +.git +.codex +.config +node_modules +out +out-server +out-admin +dist +coverage +backup +logs +npm-debug.log* +yarn-debug.log* +yarn-error.log* +*.log +docs/screenshots diff --git a/.gitignore b/.gitignore index d98ffcd5..1182161c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ node_modules/ # Build outputs out/ +out-server/ +out-admin/ dist/ build/entitlements.mac.plist diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..ef07a33d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +ARG NODE_IMAGE=node:22.21.1 + +FROM ${NODE_IMAGE} AS deps +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci --ignore-scripts + +FROM ${NODE_IMAGE} AS build +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY . . +RUN npm run build:server + +FROM ${NODE_IMAGE} AS runtime +WORKDIR /app +ENV NODE_ENV=production +ENV CHAT2API_HOST=0.0.0.0 +ENV CHAT2API_PORT=8080 +ENV CHAT2API_DATA_DIR=/data +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev --ignore-scripts && npm cache clean --force +COPY --from=build /app/out-server ./out-server +COPY --from=build /app/out-admin ./out-admin +COPY --from=build /app/sha3_wasm_bg.7b9ca65ddd.wasm ./sha3_wasm_bg.7b9ca65ddd.wasm +RUN mkdir -p /data +VOLUME ["/data"] +EXPOSE 8080 +CMD ["node", "out-server/server/index.js"] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..27ee5fe3 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,23 @@ +services: + chat2api: + build: + context: . + dockerfile: Dockerfile + image: chat2api:server + container_name: chat2api + restart: unless-stopped + ports: + - "8080:8080" + environment: + CHAT2API_HOST: 0.0.0.0 + CHAT2API_PORT: 8080 + CHAT2API_DATA_DIR: /data + CHAT2API_ENABLE_MANAGEMENT_API: "true" + CHAT2API_MANAGEMENT_SECRET: ${CHAT2API_MANAGEMENT_SECRET} + CHAT2API_LOG_LEVEL: info + CHAT2API_LOAD_BALANCE_STRATEGY: round-robin + volumes: + - chat2api-data:/data + +volumes: + chat2api-data: diff --git a/docs/docker-browser-import-plan.md b/docs/docker-browser-import-plan.md new file mode 100644 index 00000000..a770dd24 --- /dev/null +++ b/docs/docker-browser-import-plan.md @@ -0,0 +1,38 @@ +# Docker Browser-Assisted Account Import Plan + +Goal: add a Docker-friendly account import flow that avoids DevTools token copying for web-admin users. + +Scope: +- Keep Electron automatic in-app login unchanged. +- Do not add Playwright, Chromium, VNC, or a heavier Docker runtime. +- Add a browser-assisted flow for providers whose credentials are readable by page JavaScript after login, starting with Qwen AI international (`chat.qwen.ai`). +- Show clear limitations for domestic Qwen when the `tongyi_sso_ticket` cookie is not readable by JavaScript. + +Architecture: +- Web admin creates a short-lived import session in the browser adapter. +- The add-account dialog generates a JavaScript snippet that the user runs on the already logged-in provider page. +- The snippet reads provider-side storage/cookies and posts the credentials back to `/v0/management/browser-import/complete`. +- The add-account dialog polls `/v0/management/browser-import/:id` and fills the existing credential form when credentials arrive. +- Credentials are still validated and saved by the existing account APIs. + +Files: +- `src/renderer/src/web-admin-api.ts`: expose `browserImport` methods and maintain browser-side session IDs. +- `src/renderer/src/types/electron.d.ts`: type the new web-admin-only API. +- `src/renderer/src/components/providers/AddAccountDialog.tsx`: replace misleading Docker OAuth pane with browser-assisted import. +- `src/main/proxy/routes/management/statistics.ts`: add provider-scoped import completion endpoint. +- `tests/server/web-admin-electron-api-contract.test.mjs`: assert the API contract and generated script markers. +- `tests/server/browser-import-routes.test.mjs`: assert route shape and provider validation. +- `docs/docker.md`: document the new Qwen AI browser import flow. + +Behavior: +- For `qwen-ai`, generated script collects `localStorage.token` and `document.cookie`, then posts `{ providerId: "qwen-ai", credentials: { token, cookies } }`. +- For `qwen`, generated script attempts to read `tongyi_sso_ticket` from `document.cookie`; if it cannot, it reports a clear error that the cookie is likely HttpOnly and manual cookie extraction is still required. +- The Docker UI labels this as browser-assisted import, not OAuth automatic login. +- Electron UI keeps the current OAuth tab and automatic login behavior. + +Verification: +- Run the targeted server tests. +- Run `npm run build:server`. +- Rebuild Docker image. +- Restart `chat2api` container. +- Smoke-test `/admin/` and `/v0/management/health`. diff --git a/docs/docker.md b/docs/docker.md new file mode 100644 index 00000000..7cf13745 --- /dev/null +++ b/docs/docker.md @@ -0,0 +1,213 @@ +# Chat2API Docker Server + +The Docker image runs the existing Koa proxy and management API without Electron. Data is stored under `/data`, so mount it as a volume. + +## Build + +```bash +docker build -t chat2api:server . +``` + +If Docker Hub access is restricted or you already have a preferred Node base image locally: + +```bash +docker build --build-arg NODE_IMAGE=node:22.21.1 -t chat2api:server . +``` + +## Run + +```bash +docker run -d \ + --name chat2api \ + -p 8080:8080 \ + -v chat2api-data:/data \ + -e CHAT2API_HOST=0.0.0.0 \ + -e CHAT2API_PORT=8080 \ + -e CHAT2API_ENABLE_MANAGEMENT_API=true \ + -e CHAT2API_MANAGEMENT_SECRET=mgmt_change_me \ + chat2api:server +``` + +## Docker Compose + +```bash +$env:CHAT2API_MANAGEMENT_SECRET='mgmt_change_me' +docker compose up -d --build +``` + +## Health Check + +```bash +curl http://localhost:8080/health +``` + +## Web Admin + +Open the browser admin page: + +```text +http://localhost:8080/admin/ +``` + +If `localhost` does not resolve correctly on Windows, use: + +```text +http://127.0.0.1:8080/admin/ +``` + +Enter `CHAT2API_MANAGEMENT_SECRET` on the login screen. The Docker build serves the existing React management UI from the Electron app, backed by `/v0/management/*` endpoints. The main pages are available in the browser: + +- Dashboard +- Providers and accounts +- Proxy settings +- Models and model mapping +- Session settings +- API keys +- Logs +- Settings +- About + +Provider account management supports the same manual credential forms used by the Electron UI. For Qwen, add accounts with the `SSO Ticket` field, which maps to the stored credential key `ticket`. + +The Docker web admin and proxy run in the same Koa process. Start, stop, restart, and port publishing are therefore managed by Docker or Docker Compose, not by the in-app Stop Proxy button. If you change the listening port or bind address in the UI, restart the container and update your `-p`/Compose port mapping accordingly. + +Electron-only automatic in-app login cannot run in Docker because it depends on an Electron `BrowserWindow`. The Docker web admin provides a browser-assisted import flow for Qwen providers so you do not have to manually search DevTools storage fields. + +## Browser-Assisted Qwen AI Import + +For `Qwen AI (International)` (`chat.qwen.ai`): + +1. Open `http://localhost:8080/admin/#/providers`. +2. Open the `Qwen AI (International)` account dialog. +3. Switch to the OAuth tab. In Docker this tab becomes `Docker Browser-Assisted Import`. +4. Click `Open Provider Website` and log in at `https://chat.qwen.ai`. +5. Click `Generate Import Script`, then `Copy Import Script`. +6. On the logged-in `chat.qwen.ai` page, open the browser console, paste the script, and run it. +7. Return to Chat2API. The token is filled automatically; click `Validate Credentials`, then `Add Account`. + +The script reads `localStorage.token` and readable cookies from the already logged-in `chat.qwen.ai` page, then posts them to the local Docker admin import endpoint using a short-lived random import ID. It does not receive or need the management secret. + +For domestic `Qwen` (`www.qianwen.com`), the same flow attempts to read `tongyi_sso_ticket` from `document.cookie`. If the site marks that cookie as `HttpOnly`, browser JavaScript cannot read it and the UI will show a clear failure. In that case, use the manual `SSO Ticket` field. + +## Add Qwen Accounts + +Add the first Qwen account: + +```bash +curl -X POST http://localhost:8080/v0/management/accounts \ + -H "Authorization: Bearer mgmt_change_me" \ + -H "Content-Type: application/json" \ + -d '{ + "providerId": "qwen", + "name": "qwen-account-1", + "credentials": { + "ticket": "tongyi_sso_ticket_value" + } + }' +``` + +Add another Qwen account: + +```bash +curl -X POST http://localhost:8080/v0/management/accounts \ + -H "Authorization: Bearer mgmt_change_me" \ + -H "Content-Type: application/json" \ + -d '{ + "providerId": "qwen", + "name": "qwen-account-2", + "credentials": { + "ticket": "another_tongyi_sso_ticket_value" + } + }' +``` + +The proxy load balancer will select among active Qwen accounts according to `CHAT2API_LOAD_BALANCE_STRATEGY` or the persisted config. + +Built-in provider records are created lazily when the first account is added for that provider. A fresh container can therefore return an empty provider list until you add an account or otherwise create a provider record. + +## Pin A Model To One Account + +List accounts: + +```bash +curl http://localhost:8080/v0/management/providers/qwen/accounts \ + -H "Authorization: Bearer mgmt_change_me" +``` + +Create a model mapping with `preferredAccountId`: + +```bash +curl -X POST http://localhost:8080/v0/management/model-mappings \ + -H "Authorization: Bearer mgmt_change_me" \ + -H "Content-Type: application/json" \ + -d '{ + "requestModel": "qwen-primary", + "actualModel": "Qwen3.7-Max", + "preferredProviderId": "qwen", + "preferredAccountId": "account_id_from_previous_response" + }' +``` + +## Environment Variables + +```text +CHAT2API_HOST=0.0.0.0 +CHAT2API_PORT=8080 +CHAT2API_DATA_DIR=/data +CHAT2API_ENABLE_MANAGEMENT_API=true +CHAT2API_MANAGEMENT_SECRET=mgmt_change_me +CHAT2API_ENABLE_API_KEY=false +CHAT2API_LOG_LEVEL=info +CHAT2API_LOAD_BALANCE_STRATEGY=round-robin +CHAT2API_STORAGE_ENCRYPTION_KEY= +``` + +Set `CHAT2API_STORAGE_ENCRYPTION_KEY` if you want server-side credential encryption. If it is omitted, credentials are stored in the mounted data directory without the extra runtime encryption layer. + +## Upstream Update Flow + +The Docker-specific patch surface is intentionally small: + +```text +src/server/ +src/main/runtime/ +src/main/store/storage/ +src/renderer/admin.html +src/renderer/src/web-main.tsx +src/renderer/src/web-admin-api.ts +tests/server/ +Dockerfile +docker-compose.yml +.dockerignore +docs/docker.md +vite.admin.config.ts +vite.server.config.ts +``` + +When pulling upstream: + +```bash +git fetch upstream +git merge upstream/main +npm install +npm run test:server-compat +npm run build:server +docker build -t chat2api:server . +``` + +Resolve conflicts by keeping upstream provider, OAuth, adapter, and React UI logic first. Then reapply the Docker runtime boundary, server entrypoint, management API coverage, and web `window.electronAPI` adapter where direct Electron IPC or `BrowserWindow` usage blocks the Node server build. + +After every upstream merge, verify the real container, not just the local build: + +```bash +docker rm -f chat2api +docker run -d --name chat2api -p 8080:8080 \ + -v chat2api-data:/data \ + -e CHAT2API_ENABLE_MANAGEMENT_API=true \ + -e CHAT2API_MANAGEMENT_SECRET=mgmt_change_me \ + chat2api:server + +curl http://127.0.0.1:8080/admin/ +curl -H "Authorization: Bearer mgmt_change_me" \ + http://127.0.0.1:8080/v0/management/providers/builtin +``` diff --git a/docs/qwen-ai-multimodal-plan.md b/docs/qwen-ai-multimodal-plan.md new file mode 100644 index 00000000..d5425bf0 --- /dev/null +++ b/docs/qwen-ai-multimodal-plan.md @@ -0,0 +1,182 @@ +# Qwen AI Multimodal Input Plan + +## Goal + +Add Docker/server-compatible multimodal input support for the `qwen-ai` provider while keeping the OpenAI-compatible `/v1/chat/completions` surface stable. + +The current Docker/server implementation supports image, document/file, audio, and video inputs for ordinary Qwen AI chat completions. Image generation and video generation are intentionally deferred because the Qwen web client routes them through feature/tool-specific chat modes that need separate request captures. + +## Current State + +`src/main/proxy/adapters/qwen-ai.ts` currently sends only text: + +- OpenAI message content is flattened into `userContent`. +- Qwen chat creation uses `chat_type: 't2t'`. +- The outbound Qwen message always uses `files: []`. +- The adapter type accepts `content: string`, so array content parts are not modeled at the Qwen AI adapter boundary. + +Qwen web has a file pipeline. The current `qwen-chat-fe` bundle references: + +- `/api/v2/files/getstsToken` +- `/api/v2/files/getfilelink` +- `/api/v2/files/parse` +- `/api/v2/files/parse/status` +- `/api/v2/chat/completions` + +That means file/image support requires an upload/reference phase before `/api/v2/chat/completions`. + +## Scope + +### Supported in current Docker chat mode + +- OpenAI `messages[].content[]` parts: + - `{ "type": "text", "text": "..." }` + - `{ "type": "image_url", "image_url": { "url": "..." } }` + - `{ "type": "file", "file_url": { "url": "..." }, "filename": "..." }` + - `{ "type": "input_audio", "input_audio": { "data": "...", "format": "wav" } }` + - `{ "type": "video_url", "video_url": { "url": "..." }, "filename": "..." }` +- `image_url.url` and `file_url.url` can be: + - `data:;base64,...` + - `http://...` or `https://...` +- `input_audio.data` is an OpenAI-compatible base64 payload. A `data:;base64,...` payload is also accepted. +- `video_url.url` can be `data:;base64,...`, `http://...`, or `https://...`. +- Multiple images/files in the latest user request. +- Text-only behavior remains unchanged. + +### Deferred + +- Voice/RTC chat. +- Qwen image generation and video generation menu actions. +- Long-running parse polling beyond a bounded initial parse request. + +## API Compatibility + +Clients can send requests like: + +```json +{ + "model": "Qwen3.7-Plus", + "messages": [ + { + "role": "user", + "content": [ + { "type": "text", "text": "这张图里有什么?" }, + { "type": "image_url", "image_url": { "url": "data:image/png;base64,..." } } + ] + } + ], + "stream": false +} +``` + +For generic files: + +```json +{ + "role": "user", + "content": [ + { "type": "text", "text": "总结这个文件" }, + { + "type": "file", + "filename": "report.pdf", + "file_url": { "url": "https://example.com/report.pdf" } + } + ] +} +``` + +## Design + +### 1. Extend proxy content types + +Update `src/main/proxy/types.ts` so `ChatMessageContent` supports `file`, `input_audio`, and `video_url` parts. Keep this compatible with the existing loose usage in GLM by adding optional `file_url`, `input_audio`, `video_url`, `filename`, and `mime_type` fields. + +### 2. Add Qwen AI multimodal helper + +Create `src/main/proxy/adapters/qwen-ai-files.ts` with focused responsibilities: + +- Extract text, image, file, audio, and video parts from OpenAI messages. +- Download or decode part URLs into buffers. +- Infer filename and MIME type. +- Request Qwen STS metadata with `/api/v2/files/getstsToken`. +- Upload to the returned OSS location when the STS response is available. +- Convert the upload result into Qwen `messages[].files[]` entries. +- Fall back to a URL-backed file entry only when the input is already an HTTP(S) URL and Qwen returns enough metadata from `/api/v2/files/getfilelink`. + +The helper must not log tokens, cookies, raw file contents, or base64 payloads. + +### 3. Integrate with `QwenAiAdapter` + +Change the adapter boundary to accept the shared `ChatMessage[]` shape instead of the current string-only `QwenAiMessage`. + +In `chatCompletion()`: + +- Call the helper before building the Qwen payload. +- Preserve existing text-only logic. +- Put extracted text in `content`. +- Put Qwen file refs in `files`. +- Select `chat_type`/`sub_chat_type` based on uploaded file types: + - only text: `t2t` + - any image: keep `chat_type: 't2t'` but set file show/type metadata as Qwen expects for vision inputs + - any document/audio/video: keep `t2t` unless captured evidence shows a required media-specific chat type + +### 4. Error handling + +- Reject unsupported content part types with a clear error. +- Reject unsupported URL schemes. +- Enforce a conservative max file size before upload. +- If Qwen returns 401 during upload or chat, reuse the existing token refresh retry path. +- If Qwen returns a captcha/risk page, surface the upstream HTTP status and short message without credentials. + +### 5. Testing + +Add tests that do not require live Qwen network: + +- Text extraction keeps existing text-only payload unchanged. +- Image data URL becomes a Qwen file entry and is not included as raw base64 text. +- Generic file URL becomes a Qwen file entry. +- OpenAI `input_audio` becomes a Qwen audio file entry. +- OpenAI `video_url` becomes a Qwen video file entry. +- Unsupported content part types fail clearly. +- `QwenAiAdapter` payload builder uses `files` from the helper instead of `[]`. + +Run existing server compatibility tests after implementation: + +```bash +npm run test:server-compat +``` + +Then rebuild and restart Docker: + +```bash +docker build --pull=false --build-arg NODE_IMAGE=docker.m.daocloud.io/library/node:22.21.1 -t chat2api:server . +docker stop chat2api +docker rm chat2api +docker run -d --name chat2api --restart unless-stopped -p 8080:8080 \ + -e CHAT2API_HOST=0.0.0.0 \ + -e CHAT2API_PORT=8080 \ + -e CHAT2API_DATA_DIR=/data \ + -e CHAT2API_ENABLE_MANAGEMENT_API=true \ + -e CHAT2API_MANAGEMENT_SECRET=mgmt_change_me \ + -e CHAT2API_LOG_LEVEL=info \ + -e CHAT2API_LOAD_BALANCE_STRATEGY=round-robin \ + -v chat2api-data:/data \ + chat2api:server +``` + +## Upstream Update Notes + +When upstream source updates are pulled, compare these files first: + +- `src/main/proxy/types.ts` +- `src/main/proxy/adapters/qwen-ai.ts` +- `src/main/proxy/adapters/qwen-ai-files.ts` +- `src/main/proxy/forwarder.ts` +- `docs/providers/qwen-ai.md` + +If Qwen changes its web upload endpoints, recapture the web requests for: + +- STS token request. +- OSS upload request. +- File link/parse request. +- Final `/api/v2/chat/completions` message with `files`. diff --git a/package.json b/package.json index e16f13be..5f286bec 100644 --- a/package.json +++ b/package.json @@ -14,8 +14,12 @@ "dev:win": "electron-vite dev", "check:source-artifacts": "node scripts/check-source-artifacts.js", "build": "npm run check:source-artifacts && electron-vite build", + "build:admin": "vite build --config vite.admin.config.ts", + "build:server": "npm run build:admin && vite build --config vite.server.config.ts", "preview": "electron-vite preview", "start": "electron-vite preview", + "start:server": "node out-server/server/index.js", + "test:server-compat": "npm run build:server && node tests/server/run-server-tests.mjs", "start:sandbox": "electron . --no-sandbox", "postinstall": "electron-builder install-app-deps", "prebuild:check": "node scripts/prebuild-check.js", diff --git a/src/main/index.ts b/src/main/index.ts index 50666586..b7349b0c 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -5,6 +5,10 @@ import { createTrayManager, TrayManager } from './tray/TrayManager' import { registerIpcHandlers } from './ipc/handlers' import { UpdaterManager } from './updater' import { storeManager } from './store/store' +import { setRuntime } from './runtime' +import { electronRuntime } from './runtime/electronRuntime' + +setRuntime(electronRuntime) // Prevent uncaught exceptions from crashing the app process.on('uncaughtException', (error) => { diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.ts index 17f844db..0da2a8e4 100644 --- a/src/main/ipc/handlers.ts +++ b/src/main/ipc/handlers.ts @@ -7,6 +7,7 @@ import { AccountManager } from '../store/accounts' import { ProviderChecker } from '../providers/checker' import { CustomProviderManager } from '../providers/custom' import { getBuiltinProviders, getBuiltinProvider } from '../providers/builtin' +import { parseProviderModelsResponse } from '../providers/modelSync' import { oauthManager } from '../oauth/manager' import { ProxyServer } from '../proxy/server' import { proxyStatusManager } from '../proxy/status' @@ -271,9 +272,13 @@ export async function registerIpcHandlers(mainWindow: BrowserWindow | null): Pro type?: 'builtin' | 'custom' authType: AuthType apiEndpoint: string + chatPath?: string headers?: Record description?: string supportedModels?: string[] + modelMappings?: Record + modelsApiEndpoint?: string + modelsApiHeaders?: Record credentialFields?: CredentialField[] }): Promise => { return CustomProviderManager.create(data) @@ -434,37 +439,12 @@ export async function registerIpcHandlers(mainWindow: BrowserWindow | null): Pro } } - const models = response.data.data || response.data - - if (!Array.isArray(models) || models.length === 0) { - return { - success: false, - error: 'No models found in the response', - } - } - - const supportedModels: string[] = [] - const modelMappings: Record = {} - - models.forEach((model: any) => { - if (typeof model === 'string') { - supportedModels.push(model) - modelMappings[model] = model - } else if (model && typeof model === 'object') { - const modelId = model.id || model.model_id || model.name - const modelName = model.name || model.display_name || modelId - - if (modelId) { - supportedModels.push(modelName || modelId) - modelMappings[modelName || modelId] = modelId - } - } - }) + const { supportedModels, modelMappings } = parseProviderModelsResponse(response.data) if (supportedModels.length === 0) { return { success: false, - error: 'Failed to parse models from the response', + error: 'No models found in the response', } } diff --git a/src/main/lib/challenge.ts b/src/main/lib/challenge.ts index a25565bd..8318a5d2 100644 --- a/src/main/lib/challenge.ts +++ b/src/main/lib/challenge.ts @@ -1,6 +1,5 @@ import fs from 'fs' -import path from 'path' -import { app } from 'electron' +import { getRuntime } from '../runtime' export class DeepSeekHash { private wasmInstance: any @@ -120,10 +119,7 @@ let deepSeekHashInstance: DeepSeekHash | null = null export async function getDeepSeekHash(): Promise { if (!deepSeekHashInstance) { deepSeekHashInstance = new DeepSeekHash() - // Use different paths for development and production environments - const wasmPath = app.isPackaged - ? path.join(process.resourcesPath, 'sha3_wasm_bg.7b9ca65ddd.wasm') - : path.join(app.getAppPath(), 'sha3_wasm_bg.7b9ca65ddd.wasm') + const wasmPath = getRuntime().getResourcePath('sha3_wasm_bg.7b9ca65ddd.wasm') console.log('[DeepSeekHash] WASM path:', wasmPath) console.log('[DeepSeekHash] File exists:', fs.existsSync(wasmPath)) try { diff --git a/src/main/oauth/adapters/base.ts b/src/main/oauth/adapters/base.ts index 53d4d1cc..d754d1d0 100644 --- a/src/main/oauth/adapters/base.ts +++ b/src/main/oauth/adapters/base.ts @@ -3,9 +3,10 @@ * Defines common interface and base implementation for all provider authentication adapters */ -import { BrowserWindow, shell } from 'electron' +import type { BrowserWindow } from 'electron' import http from 'http' import crypto from 'crypto' +import { getRuntime } from '../../runtime' import { ProviderType, AuthMethod, @@ -187,7 +188,7 @@ export abstract class BaseOAuthAdapter { * Open URL in system browser */ protected async openBrowser(url: string): Promise { - await shell.openExternal(url) + await getRuntime().openExternal(url) } /** diff --git a/src/main/oauth/adapters/deepseek.ts b/src/main/oauth/adapters/deepseek.ts index 6f52c6a1..d749bdb6 100644 --- a/src/main/oauth/adapters/deepseek.ts +++ b/src/main/oauth/adapters/deepseek.ts @@ -4,8 +4,8 @@ */ import axios from 'axios' -import { shell } from 'electron' import { BaseOAuthAdapter } from './base' +import { getRuntime } from '../../runtime' import { OAuthResult, OAuthOptions, @@ -56,7 +56,7 @@ export class DeepSeekAdapter extends BaseOAuthAdapter { this.emitProgress('pending', 'Opening browser...') try { - await shell.openExternal(DEEPSEEK_API_BASE) + await getRuntime().openExternal(DEEPSEEK_API_BASE) this.emitProgress('pending', 'Please log in via browser and enter Token manually') return { diff --git a/src/main/oauth/adapters/glm.ts b/src/main/oauth/adapters/glm.ts index 4150f77c..10d70499 100644 --- a/src/main/oauth/adapters/glm.ts +++ b/src/main/oauth/adapters/glm.ts @@ -4,8 +4,8 @@ */ import axios from 'axios' -import { shell } from 'electron' import { BaseOAuthAdapter } from './base' +import { getRuntime } from '../../runtime' import { OAuthResult, OAuthOptions, @@ -82,7 +82,7 @@ export class GLMAdapter extends BaseOAuthAdapter { this.emitProgress('pending', 'Opening browser...') try { - await shell.openExternal(GLM_API_BASE) + await getRuntime().openExternal(GLM_API_BASE) this.emitProgress('pending', 'Please log in via browser and enter Token manually') return { diff --git a/src/main/oauth/adapters/kimi.ts b/src/main/oauth/adapters/kimi.ts index 988a6eb9..467391ed 100644 --- a/src/main/oauth/adapters/kimi.ts +++ b/src/main/oauth/adapters/kimi.ts @@ -4,8 +4,8 @@ */ import axios from 'axios' -import { shell } from 'electron' import { BaseOAuthAdapter } from './base' +import { getRuntime } from '../../runtime' import { OAuthResult, OAuthOptions, @@ -157,7 +157,7 @@ export class KimiAdapter extends BaseOAuthAdapter { this.emitProgress('pending', 'Opening browser...') try { - await shell.openExternal(KIMI_API_BASE) + await getRuntime().openExternal(KIMI_API_BASE) this.emitProgress('pending', 'Please log in via browser and enter Token manually') return { diff --git a/src/main/oauth/adapters/minimax.ts b/src/main/oauth/adapters/minimax.ts index 31ef2776..dc4c593d 100644 --- a/src/main/oauth/adapters/minimax.ts +++ b/src/main/oauth/adapters/minimax.ts @@ -4,9 +4,9 @@ */ import axios from 'axios' -import { shell } from 'electron' import crypto from 'crypto' import { BaseOAuthAdapter } from './base' +import { getRuntime } from '../../runtime' import { OAuthResult, OAuthOptions, @@ -81,7 +81,7 @@ export class MiniMaxAdapter extends BaseOAuthAdapter { this.emitProgress('pending', 'Opening browser...') try { - await shell.openExternal(MINIMAX_API_BASE) + await getRuntime().openExternal(MINIMAX_API_BASE) this.emitProgress('pending', 'Please log in via browser and enter Token manually') return { diff --git a/src/main/oauth/adapters/qwen.ts b/src/main/oauth/adapters/qwen.ts index 9458d912..6cda9c71 100644 --- a/src/main/oauth/adapters/qwen.ts +++ b/src/main/oauth/adapters/qwen.ts @@ -4,8 +4,8 @@ */ import axios from 'axios' -import { shell } from 'electron' import { BaseOAuthAdapter } from './base' +import { getRuntime } from '../../runtime' import { OAuthResult, OAuthOptions, @@ -54,7 +54,7 @@ export class QwenAdapter extends BaseOAuthAdapter { this.emitProgress('pending', 'Opening browser...') try { - await shell.openExternal(QWEN_WEB_BASE) + await getRuntime().openExternal(QWEN_WEB_BASE) this.emitProgress('pending', 'Please log in via browser and enter Ticket manually') return { diff --git a/src/main/providers/builtin/qwen-ai.ts b/src/main/providers/builtin/qwen-ai.ts index 772cf672..d53b6c13 100644 --- a/src/main/providers/builtin/qwen-ai.ts +++ b/src/main/providers/builtin/qwen-ai.ts @@ -14,7 +14,7 @@ export const qwenAiConfig: BuiltinProviderConfig = { }, enabled: true, description: 'Qwen AI international version (chat.qwen.ai)', - modelsApiEndpoint: 'https://chat.qwen.ai/api/models', + modelsApiEndpoint: 'https://chat.qwen.ai/api/v2/models/', modelsApiHeaders: { Accept: 'application/json, text/plain, */*', Referer: 'https://chat.qwen.ai/', @@ -22,18 +22,14 @@ export const qwenAiConfig: BuiltinProviderConfig = { Version: '0.2.35', }, supportedModels: [ + 'Qwen3.7-Plus', 'Qwen3.7-Max', 'Qwen3.6-Plus', - 'Qwen3.6-35B-A3B', - 'Qwen3.6-27B', - 'Qwen3-Coder', ], modelMappings: { + 'Qwen3.7-Plus': 'qwen3.7-plus', 'Qwen3.7-Max': 'qwen3.7-max', 'Qwen3.6-Plus': 'qwen3.6-plus', - 'Qwen3.6-35B-A3B': 'qwen3.6-35b-a3b', - 'Qwen3.6-27B': 'qwen3.6-27b', - 'Qwen3-Coder': 'qwen3-coder-plus', }, credentialFields: [ { @@ -52,6 +48,22 @@ export const qwenAiConfig: BuiltinProviderConfig = { placeholder: 'Optional cookies for enhanced compatibility', helpText: 'Full cookie string from browser DevTools (optional but recommended)', }, + { + name: 'email', + label: 'Login Email (Optional)', + type: 'text', + required: false, + placeholder: 'Optional account email for automatic token refresh', + helpText: 'Used with password to refresh the chat.qwen.ai web token before it expires', + }, + { + name: 'password', + label: 'Login Password (Optional)', + type: 'password', + required: false, + placeholder: 'Optional account password for automatic token refresh', + helpText: 'Stored in encrypted credentials when encryption is available; automatic refresh can fail if Qwen requires captcha, MFA, or risk verification', + }, ], } diff --git a/src/main/providers/checker.ts b/src/main/providers/checker.ts index bd0ba2f2..f733cb9f 100644 --- a/src/main/providers/checker.ts +++ b/src/main/providers/checker.ts @@ -1,5 +1,6 @@ import axios, { AxiosError } from 'axios' import { getBuiltinProvider } from './builtin' +import { parseProviderModelsResponse } from './modelSync' import type { Provider, ProviderCheckResult, Account } from '../../shared/types' import type { BuiltinProviderConfig } from '../store/types' @@ -726,16 +727,7 @@ export class ProviderChecker { throw new Error(`Failed to fetch models: HTTP ${response.status}`) } - const models = response.data.data || [] - const supportedModels: string[] = [] - const modelMappings: Record = {} - - for (const model of models) { - if (model.name && model.id) { - supportedModels.push(model.name) - modelMappings[model.name] = model.id - } - } + const { supportedModels, modelMappings } = parseProviderModelsResponse(response.data) return { supportedModels, modelMappings } } catch (error) { diff --git a/src/main/providers/custom.ts b/src/main/providers/custom.ts index 3f856d1e..69ea45d7 100644 --- a/src/main/providers/custom.ts +++ b/src/main/providers/custom.ts @@ -8,10 +8,14 @@ export interface CustomProviderData { type?: 'builtin' | 'custom' authType: AuthType apiEndpoint: string + chatPath?: string headers?: Record description?: string icon?: string supportedModels?: string[] + modelMappings?: Record + modelsApiEndpoint?: string + modelsApiHeaders?: Record credentialFields?: CredentialField[] } @@ -175,6 +179,7 @@ export class CustomProviderManager { type: data.type || 'custom', authType: data.authType, apiEndpoint: data.apiEndpoint.trim(), + chatPath: data.chatPath, headers: data.headers || {}, enabled: true, createdAt: now, @@ -182,6 +187,9 @@ export class CustomProviderManager { description: data.description?.trim(), icon: data.icon?.trim(), supportedModels: data.supportedModels || [], + modelMappings: data.modelMappings, + modelsApiEndpoint: data.modelsApiEndpoint, + modelsApiHeaders: data.modelsApiHeaders, credentialFields: data.credentialFields, } diff --git a/src/main/providers/modelSync.ts b/src/main/providers/modelSync.ts new file mode 100644 index 00000000..35f236b9 --- /dev/null +++ b/src/main/providers/modelSync.ts @@ -0,0 +1,62 @@ +export interface ParsedProviderModels { + supportedModels: string[] + modelMappings: Record +} + +function extractModelsPayload(responseData: unknown): unknown[] { + if (Array.isArray(responseData)) { + return responseData + } + + if (!responseData || typeof responseData !== 'object') { + return [] + } + + const data = (responseData as { data?: unknown }).data + if (Array.isArray(data)) { + return data + } + + if (data && typeof data === 'object') { + const nestedData = (data as { data?: unknown }).data + if (Array.isArray(nestedData)) { + return nestedData + } + } + + return [] +} + +export function parseProviderModelsResponse(responseData: unknown): ParsedProviderModels { + const models = extractModelsPayload(responseData) + const supportedModels: string[] = [] + const modelMappings: Record = {} + + for (const model of models) { + if (typeof model === 'string') { + supportedModels.push(model) + modelMappings[model] = model + continue + } + + if (!model || typeof model !== 'object') { + continue + } + + const candidate = model as { + id?: unknown + model_id?: unknown + name?: unknown + display_name?: unknown + } + const modelId = String(candidate.id || candidate.model_id || candidate.name || '') + const modelName = String(candidate.name || candidate.display_name || modelId) + + if (modelId) { + supportedModels.push(modelName) + modelMappings[modelName] = modelId + } + } + + return { supportedModels, modelMappings } +} diff --git a/src/main/proxy/adapters/perplexity.ts b/src/main/proxy/adapters/perplexity.ts index d981c615..a3542f0c 100644 --- a/src/main/proxy/adapters/perplexity.ts +++ b/src/main/proxy/adapters/perplexity.ts @@ -1,4 +1,4 @@ -import { net } from 'electron' +import axios from 'axios' import { Readable } from 'stream' import { Account, Provider } from '../store/types' @@ -312,93 +312,42 @@ export class PerplexityAdapter { const data = this.buildRequestData(query, model) - // Use Electron's net API which uses Chromium's network stack - // This bypasses Cloudflare's TLS fingerprint detection - const request_ = net.request({ - method: 'POST', - url: QUERY_ENDPOINT, + const response = await axios.post(QUERY_ENDPOINT, data, { + headers, + responseType: 'stream', + timeout: 120000, + validateStatus: () => true, }) - for (const [key, value] of Object.entries(headers)) { - request_.setHeader(key, value) + if (response.status === 403) { + throw new Error('Cloudflare challenge detected') } - const stream = new Readable({ - read() {} - }) + if (response.status === 429) { + throw new Error('Rate limit exceeded') + } - return new Promise((resolve, reject) => { - const chunks: Buffer[] = [] - let errorBodyRead = false - - request_.on('response', (response) => { - const statusCode = response.statusCode - - if (statusCode === 403) { - // Cloudflare challenge - need to handle this - stream.emit('error', new Error('Cloudflare challenge detected. Please try again later.')) - reject(new Error('Cloudflare challenge detected')) - return - } - - if (statusCode === 429) { - // Rate limit exceeded - stream.emit('error', new Error('Rate limit exceeded. Please wait a moment and try again.')) - reject(new Error('Rate limit exceeded')) - return - } - - if (statusCode && statusCode >= 400) { - // Error response - read full body before rejecting - errorBodyRead = true - let errorBody = '' - response.on('data', (chunk: Buffer) => { - errorBody += chunk.toString() - }) - response.on('end', () => { - const errorMsg = `HTTP ${statusCode}: ${errorBody.substring(0, 200)}` - console.error('[Perplexity] Server error:', errorMsg) - stream.emit('error', new Error(errorMsg)) - reject(new Error(errorMsg)) - }) - response.on('error', (error) => { - console.error('[Perplexity] Error response stream error:', error) - const errorMsg = `HTTP ${statusCode}: Failed to read error response` - stream.emit('error', new Error(errorMsg)) - reject(new Error(errorMsg)) - }) - return - } - - // Success response - stream the data - response.on('data', (chunk) => { - stream.push(chunk) - chunks.push(Buffer.from(chunk)) - }) - - response.on('end', () => { - stream.push(null) - }) - - response.on('error', (error) => { - console.error('[Perplexity] Response error:', error) - const errorMessage = this.formatNetworkError(error) - stream.emit('error', new Error(errorMessage)) - }) - - resolve({ stream, sessionId: requestId }) + if (response.status >= 400) { + const errorBody = await this.readErrorBody(response.data) + throw new Error(`HTTP ${response.status}: ${errorBody.substring(0, 200)}`) + } + + return { stream: response.data, sessionId: requestId } + } + + private async readErrorBody(stream: NodeJS.ReadableStream): Promise { + const chunks: Buffer[] = [] + + return new Promise((resolve) => { + stream.on('data', (chunk: Buffer) => { + chunks.push(Buffer.from(chunk)) }) - - request_.on('error', (error) => { - console.error('[Perplexity] Request error:', error) - const errorMessage = this.formatNetworkError(error) - const wrappedError = new Error(errorMessage) - stream.emit('error', wrappedError) - reject(wrappedError) + stream.on('end', () => { + resolve(Buffer.concat(chunks).toString('utf8')) + }) + stream.on('error', () => { + resolve('') }) - - request_.write(JSON.stringify(data)) - request_.end() }) } @@ -457,43 +406,15 @@ export class PerplexityAdapter { read_write_token: sessionData.read_write_token || '', } - return new Promise((resolve) => { - const request_ = net.request({ - method: 'DELETE', - url: deleteUrl, - }) - - for (const [key, value] of Object.entries(headers)) { - request_.setHeader(key, value) - } - - request_.on('response', (response) => { - const statusCode = response.statusCode - - // Read response body - let responseBody = '' - response.on('data', (chunk: Buffer) => { - responseBody += chunk.toString() - }) - - if (statusCode && statusCode >= 200 && statusCode < 300) { - sessionCache.delete(cacheKey) - resolve(true) - } else { - sessionCache.delete(cacheKey) - resolve(false) - } - }) - - request_.on('error', (error) => { - console.error('[Perplexity] Delete request error:', error) - sessionCache.delete(cacheKey) - resolve(false) - }) - - request_.write(JSON.stringify(requestBody)) - request_.end() + const response = await axios.delete(deleteUrl, { + headers, + data: requestBody, + timeout: 30000, + validateStatus: () => true, }) + + sessionCache.delete(cacheKey) + return response.status >= 200 && response.status < 300 } catch (error) { console.error('[Perplexity] Delete session error:', error) sessionCache.delete(cacheKey) @@ -526,51 +447,24 @@ export class PerplexityAdapter { 'x-perplexity-request-try-number': '1', } - return new Promise((resolve) => { - const request_ = net.request({ - method: 'DELETE', - url: deleteUrl, + try { + const response = await axios.delete(deleteUrl, { + headers, + data: { delete_all: true }, + timeout: 30000, + validateStatus: () => true, }) - for (const [key, value] of Object.entries(headers)) { - request_.setHeader(key, value) + if (response.status >= 200 && response.status < 300 && response.data?.status === 'success') { + sessionCache.delete(this.account.id) + return true } - request_.on('response', (response) => { - const statusCode = response.statusCode - - let responseBody = '' - response.on('data', (chunk: Buffer) => { - responseBody += chunk.toString() - }) - - response.on('end', () => { - if (statusCode && statusCode >= 200 && statusCode < 300) { - try { - const data = JSON.parse(responseBody) - if (data.status === 'success') { - sessionCache.delete(this.account.id) - resolve(true) - } else { - resolve(false) - } - } catch { - resolve(false) - } - } else { - resolve(false) - } - }) - }) - - request_.on('error', (error) => { - console.error('[Perplexity] Delete all chats error:', error) - resolve(false) - }) - - request_.write(JSON.stringify({ delete_all: true })) - request_.end() - }) + return false + } catch (error) { + console.error('[Perplexity] Delete all chats error:', error) + return false + } } static isPerplexityProvider(provider: Provider): boolean { diff --git a/src/main/proxy/adapters/qwen-ai-files.ts b/src/main/proxy/adapters/qwen-ai-files.ts new file mode 100644 index 00000000..a7a85375 --- /dev/null +++ b/src/main/proxy/adapters/qwen-ai-files.ts @@ -0,0 +1,544 @@ +import axios, { AxiosInstance, AxiosResponse } from 'axios' +import OSS from 'ali-oss' +import mime from 'mime-types' +import path from 'path' +import type { ChatMessage, ChatMessageContent } from '../types' + +const QWEN_AI_BASE = 'https://chat.qwen.ai' +const MAX_FILE_SIZE = 2000 * 1024 * 1024 +const PARSE_POLL_INTERVAL_MS = 1000 +const PARSE_POLL_ATTEMPTS = 5 + +type HeaderFactory = () => Record +type QwenPostWithRetry = ( + url: string, + payload: unknown, + createOptions: () => Record, +) => Promise + +type QwenFileClass = 'vision' | 'document' | 'audio' | 'video' +type QwenCoarseFileType = 'image' | 'file' | 'audio' | 'video' + +interface NormalizedInputFile { + data: Buffer + filename: string + mimeType: string + sourceUrl?: string + coarseType: QwenCoarseFileType + fileClass: QwenFileClass +} + +interface QwenStsInfo { + accessKeyId: string + accessKeySecret: string + securityToken?: string + bucket: string + region: string + endpoint: string + fileId: string + filePath: string + fileUrl: string +} + +export interface PreparedQwenAiMessage { + content: string + files: any[] +} + +function uuid(): string { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0 + const v = c === 'x' ? r : (r & 0x3) | 0x8 + return v.toString(16) + }) +} + +function delay(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)) +} + +function isDataUrl(url: string): boolean { + return /^data:[^;,]+;base64,/i.test(url) +} + +function isHttpUrl(url: string): boolean { + return /^https?:\/\//i.test(url) +} + +function sanitizeFilename(filename: string): string { + const cleaned = filename + .replace(/[\\/:*?"<>|]/g, '_') + .replace(/\s+/g, ' ') + .trim() + + return cleaned || `upload-${uuid()}` +} + +function filenameFromUrl(url: string): string { + try { + const parsed = new URL(url) + const base = path.posix.basename(decodeURIComponent(parsed.pathname)) + return sanitizeFilename(base || `upload-${uuid()}`) + } catch { + return `upload-${uuid()}` + } +} + +function filenameFromContentDisposition(header?: string): string | undefined { + if (!header) { + return undefined + } + + const utf8Match = header.match(/filename\*=UTF-8''([^;]+)/i) + if (utf8Match?.[1]) { + return sanitizeFilename(decodeURIComponent(utf8Match[1])) + } + + const asciiMatch = header.match(/filename="?([^";]+)"?/i) + if (asciiMatch?.[1]) { + return sanitizeFilename(asciiMatch[1]) + } + + return undefined +} + +function ensureExtension(filename: string, mimeType: string): string { + if (path.extname(filename)) { + return filename + } + + const ext = mime.extension(mimeType) + return ext ? `${filename}.${ext}` : filename +} + +function normalizeAudioMimeType(format?: string, explicitMimeType?: string): string { + if (explicitMimeType) { + return explicitMimeType + } + + const normalizedFormat = format?.toLowerCase().replace(/^\./, '') + if (!normalizedFormat) { + return 'audio/wav' + } + + if (normalizedFormat === 'mp3') { + return 'audio/mpeg' + } + + if (normalizedFormat === 'm4a') { + return 'audio/x-m4a' + } + + return mime.lookup(normalizedFormat) || `audio/${normalizedFormat}` +} + +function parseDataUrlPayload(value: string): { mimeType?: string; base64: string } { + const match = value.match(/^data:([^;,]+);base64,(.*)$/is) + if (!match) { + return { base64: value } + } + + return { + mimeType: match[1], + base64: match[2], + } +} + +function classifyFile(mimeType: string, explicitType: ChatMessageContent['type']): Pick { + if (explicitType === 'image_url' || mimeType.startsWith('image/')) { + return { coarseType: 'image', fileClass: 'vision' } + } + + if (mimeType.startsWith('audio/')) { + return { coarseType: 'audio', fileClass: 'audio' } + } + + if (mimeType.startsWith('video/')) { + return { coarseType: 'video', fileClass: 'video' } + } + + return { coarseType: 'file', fileClass: 'document' } +} + +function extractDataUrl( + url: string, + filename?: string, + explicitMimeType?: string, + explicitType?: ChatMessageContent['type'], +): NormalizedInputFile { + const match = url.match(/^data:([^;,]+);base64,(.*)$/is) + if (!match) { + throw new Error('Unsupported data URL. Expected data:;base64,.') + } + + const mimeType = explicitMimeType || match[1] || 'application/octet-stream' + const data = Buffer.from(match[2], 'base64') + const rawFilename = filename || `upload-${uuid()}` + const safeFilename = ensureExtension(sanitizeFilename(rawFilename), mimeType) + const classification = classifyFile(mimeType, explicitType || (mimeType.startsWith('image/') ? 'image_url' : 'file')) + + return { + data, + filename: safeFilename, + mimeType, + ...classification, + } +} + +function extractInputAudio(part: ChatMessageContent): NormalizedInputFile { + const data = part.input_audio?.data + if (!data) { + throw new Error('Missing data for input_audio content part') + } + + const parsedData = parseDataUrlPayload(data) + const mimeType = normalizeAudioMimeType(part.input_audio?.format, part.mime_type || parsedData.mimeType) + const filename = ensureExtension( + sanitizeFilename(part.filename || `input-audio-${uuid()}`), + mimeType, + ) + + return { + data: Buffer.from(parsedData.base64, 'base64'), + filename, + mimeType, + coarseType: 'audio', + fileClass: 'audio', + } +} + +function textFromContent(content: ChatMessage['content']): string { + if (typeof content === 'string') { + return content + } + + if (Array.isArray(content)) { + validateSupportedParts(content) + return content + .filter(part => part.type === 'text' && typeof part.text === 'string') + .map(part => part.text) + .join('') + } + + return '' +} + +function collectFileParts(content: ChatMessage['content']): ChatMessageContent[] { + if (!Array.isArray(content)) { + return [] + } + + validateSupportedParts(content) + return content.filter(part => ['image_url', 'file', 'input_audio', 'video_url'].includes(part.type)) +} + +function validateSupportedParts(content: ChatMessageContent[]): void { + for (const part of content) { + if (!['text', 'image_url', 'file', 'input_audio', 'video_url'].includes(part.type)) { + throw new Error(`Unsupported Qwen AI message content part type: ${part.type}`) + } + } +} + +function extractPartUrl(part: ChatMessageContent): string { + if (part.type === 'image_url' && part.image_url?.url) { + return part.image_url.url + } + + if (part.type === 'file' && part.file_url?.url) { + return part.file_url.url + } + + if (part.type === 'video_url' && part.video_url?.url) { + return part.video_url.url + } + + throw new Error(`Missing URL for ${part.type} content part`) +} + +function normalizeStsResponse(data: any): QwenStsInfo { + const source = data?.data || data || {} + + const filePath = source.file_path || source.filePath || source.path || '' + const fileId = source.file_id || source.fileId || source.id || '' + const fileUrl = source.file_url || source.fileUrl || source.url || source.cdn_url || '' + + const sts: QwenStsInfo = { + accessKeyId: source.access_key_id || source.accessKeyId || source.AccessKeyId || '', + accessKeySecret: source.access_key_secret || source.accessKeySecret || source.AccessKeySecret || '', + securityToken: source.security_token || source.securityToken || source.SecurityToken, + bucket: source.bucketname || source.bucket || source.bucketName || '', + region: source.region || '', + endpoint: source.endpoint || '', + fileId, + filePath, + fileUrl, + } + + if (!sts.accessKeyId || !sts.accessKeySecret || !sts.bucket || !sts.endpoint || !sts.filePath || !sts.fileId) { + throw new Error('Qwen AI upload STS response is missing required fields') + } + + return sts +} + +function createQwenFileItem(file: NormalizedInputFile, sts: QwenStsInfo): any { + const now = Date.now() + const fileUrl = sts.fileUrl || file.sourceUrl || '' + const type = file.coarseType + + return { + id: sts.fileId, + itemId: uuid(), + type, + url: fileUrl, + name: file.filename, + collection_name: '', + progress: 100, + status: 'uploaded', + greenNet: 'success', + size: file.data.length, + error: '', + filetype: file.coarseType, + file_type: file.mimeType, + showType: type, + file_class: file.fileClass, + uploadStatus: 'success', + meta: { + name: file.filename, + size: file.data.length, + content_type: file.mimeType, + }, + file: { + created_at: now, + data: {}, + filename: file.filename, + hash: null, + id: sts.fileId, + user_id: '', + meta: { + name: file.filename, + size: file.data.length, + content_type: file.mimeType, + }, + update_at: now, + name: file.filename, + size: file.data.length, + type: file.mimeType, + url: fileUrl, + }, + } +} + +export class QwenAiFileUploader { + constructor( + private readonly axiosInstance: AxiosInstance, + private readonly getHeaders: HeaderFactory, + private readonly postWithRefreshRetry?: QwenPostWithRetry, + ) {} + + async uploadPart(part: ChatMessageContent): Promise { + const file = await this.resolveFile(part) + + if (file.data.length > MAX_FILE_SIZE) { + throw new Error(`Qwen AI file upload exceeds ${MAX_FILE_SIZE} bytes: ${file.filename}`) + } + + const sts = await this.requestSts(file) + await this.uploadToOss(file, sts) + + if (file.fileClass === 'document') { + await this.parseDocument(sts.fileId) + } + + return createQwenFileItem(file, sts) + } + + private async resolveFile(part: ChatMessageContent): Promise { + if (part.type === 'input_audio') { + return extractInputAudio(part) + } + + const url = extractPartUrl(part) + const explicitFilename = part.filename + const explicitMimeType = part.mime_type + + if (isDataUrl(url)) { + return extractDataUrl(url, explicitFilename, explicitMimeType, part.type) + } + + if (!isHttpUrl(url)) { + throw new Error(`Unsupported Qwen AI file URL scheme for ${part.type}`) + } + + const response = await this.axiosInstance.get(url, { + responseType: 'arraybuffer', + maxContentLength: MAX_FILE_SIZE, + maxBodyLength: MAX_FILE_SIZE, + timeout: 60000, + validateStatus: () => true, + }) + + if (response.status >= 400) { + throw new Error(`Failed to download Qwen AI input file: HTTP ${response.status}`) + } + + const headerFilename = filenameFromContentDisposition(response.headers?.['content-disposition']) + const filename = sanitizeFilename(explicitFilename || headerFilename || filenameFromUrl(url)) + const mimeType = explicitMimeType || response.headers?.['content-type'] || mime.lookup(filename) || 'application/octet-stream' + const safeFilename = ensureExtension(filename, mimeType) + const classification = classifyFile(String(mimeType), part.type) + + return { + data: Buffer.from(response.data), + filename: safeFilename, + mimeType: String(mimeType), + sourceUrl: url, + ...classification, + } + } + + private async requestSts(file: NormalizedInputFile): Promise { + const response = await this.postJson( + `${QWEN_AI_BASE}/api/v2/files/getstsToken`, + { + filename: file.filename, + filesize: String(file.data.length), + filetype: file.coarseType, + }, + () => ({ + headers: this.getHeaders(), + timeout: 30000, + validateStatus: () => true, + }), + ) + + if (response.status >= 400) { + throw new Error(`Qwen AI upload STS request failed: HTTP ${response.status}`) + } + + return normalizeStsResponse(response.data) + } + + private async uploadToOss(file: NormalizedInputFile, sts: QwenStsInfo): Promise { + const client = new OSS({ + accessKeyId: sts.accessKeyId, + accessKeySecret: sts.accessKeySecret, + stsToken: sts.securityToken, + bucket: sts.bucket, + region: sts.region, + endpoint: sts.endpoint, + authorizationV4: true, + } as any) + + await client.put(sts.filePath, file.data, { + headers: { + 'Content-Type': file.mimeType, + }, + } as any) + } + + private async parseDocument(fileId: string): Promise { + const parseResponse = await this.postJson( + `${QWEN_AI_BASE}/api/v2/files/parse`, + { file_id: fileId }, + () => ({ + headers: this.getHeaders(), + timeout: 30000, + validateStatus: () => true, + }), + ) + + if (parseResponse.status >= 400) { + console.warn('[QwenAI] File parse request failed:', parseResponse.status) + return + } + + await this.waitForParse(fileId) + } + + private async waitForParse(fileId: string): Promise { + for (let attempt = 0; attempt < PARSE_POLL_ATTEMPTS; attempt++) { + await delay(PARSE_POLL_INTERVAL_MS) + + const response: AxiosResponse = await this.postJson( + `${QWEN_AI_BASE}/api/v2/files/parse/status`, + { file_id_list: [fileId] }, + () => ({ + headers: this.getHeaders(), + timeout: 30000, + validateStatus: () => true, + }), + ) + + if (response.status >= 400) { + console.warn('[QwenAI] File parse status request failed:', response.status) + return + } + + const status = response.data?.data?.[fileId]?.status + || response.data?.data?.[0]?.status + || response.data?.[fileId]?.status + || response.data?.status + + if (!status || ['success', 'finished', 'done', 'parsed'].includes(String(status).toLowerCase())) { + return + } + + if (['failed', 'error'].includes(String(status).toLowerCase())) { + console.warn('[QwenAI] File parse failed for uploaded document') + return + } + } + } + + private async postJson( + url: string, + payload: unknown, + createOptions: () => Record, + ): Promise { + if (this.postWithRefreshRetry) { + return this.postWithRefreshRetry(url, payload, createOptions) + } + + return this.axiosInstance.post(url, payload, createOptions()) + } +} + +export async function prepareQwenAiMultimodalMessage( + messages: ChatMessage[], + uploader: QwenAiFileUploader, +): Promise { + let systemContent = '' + let userContent = '' + const fileParts: ChatMessageContent[] = [] + + for (const msg of messages) { + if (msg.role === 'system') { + const text = textFromContent(msg.content) + if (text) { + systemContent += (systemContent ? '\n\n' : '') + text + } + continue + } + + if (msg.role === 'user') { + userContent = textFromContent(msg.content) + fileParts.splice(0, fileParts.length, ...collectFileParts(msg.content)) + } + } + + if (systemContent) { + userContent = `${systemContent}\n\nUser: ${userContent}` + } + + const files: any[] = [] + for (const part of fileParts) { + files.push(await uploader.uploadPart(part)) + } + + return { + content: userContent, + files, + } +} diff --git a/src/main/proxy/adapters/qwen-ai-token-refresh.ts b/src/main/proxy/adapters/qwen-ai-token-refresh.ts new file mode 100644 index 00000000..6683899d --- /dev/null +++ b/src/main/proxy/adapters/qwen-ai-token-refresh.ts @@ -0,0 +1,113 @@ +import axios from 'axios' +import { createHash } from 'crypto' +import type { Account } from '../../store/types' +import { storeManager } from '../../store/store' + +const QWEN_AI_BASE = 'https://chat.qwen.ai' +const REFRESH_THRESHOLD_MS = 6 * 60 * 60 * 1000 + +function decodeJwtPayload(token: string): Record | null { + try { + const parts = token.split('.') + if (parts.length !== 3) { + return null + } + + const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/') + const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, '=') + return JSON.parse(Buffer.from(padded, 'base64').toString('utf8')) + } catch { + return null + } +} + +function sha256Hex(value: string): string { + return createHash('sha256').update(value, 'utf8').digest('hex') +} + +export class QwenAiTokenRefresher { + isTokenExpiringSoon(token: string, now: number = Date.now()): boolean { + const payload = decodeJwtPayload(token) + if (!payload?.exp || typeof payload.exp !== 'number') { + return true + } + + return payload.exp * 1000 - now <= REFRESH_THRESHOLD_MS + } + + async refreshIfNeeded(account: Account): Promise { + if (!this.canRefresh(account) || !this.isTokenExpiringSoon(account.credentials.token || '')) { + return account + } + + return this.refresh(account) + } + + async refreshAfterUnauthorized(account: Account): Promise { + if (!this.canRefresh(account)) { + return account + } + + return this.refresh(account) + } + + private canRefresh(account: Account): boolean { + return Boolean(account.credentials.email && account.credentials.password) + } + + private async refresh(account: Account): Promise { + const response = await axios.post( + `${QWEN_AI_BASE}/api/v1/auths/signin`, + { + email: account.credentials.email, + password: sha256Hex(account.credentials.password), + }, + { + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + Origin: QWEN_AI_BASE, + Referer: `${QWEN_AI_BASE}/`, + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', + }, + timeout: 15000, + validateStatus: () => true, + }, + ) + + const token = response.data?.token + if (response.status !== 200 || !token || typeof token !== 'string') { + throw new Error(`Qwen AI token refresh failed: HTTP ${response.status}`) + } + + const updated = storeManager.updateAccount(account.id, { + email: account.credentials.email, + credentials: { + ...account.credentials, + token, + }, + status: 'active', + errorMessage: undefined, + }) + + return updated ? { + ...updated, + credentials: { + ...account.credentials, + token, + }, + } : { + ...account, + email: account.credentials.email, + credentials: { + ...account.credentials, + token, + }, + status: 'active', + errorMessage: undefined, + updatedAt: Date.now(), + } + } +} + +export const qwenAiTokenRefresher = new QwenAiTokenRefresher() diff --git a/src/main/proxy/adapters/qwen-ai.ts b/src/main/proxy/adapters/qwen-ai.ts index 549a4051..6e51e67b 100644 --- a/src/main/proxy/adapters/qwen-ai.ts +++ b/src/main/proxy/adapters/qwen-ai.ts @@ -8,7 +8,10 @@ import axios, { AxiosResponse } from 'axios' import { PassThrough } from 'stream' import { createParser } from 'eventsource-parser' import { Account, Provider } from '../../store/types' +import type { ChatMessage } from '../types' import { hasToolUse, parseToolUse, ToolCall } from '../promptToolUse' +import { QwenAiTokenRefresher } from './qwen-ai-token-refresh' +import { QwenAiFileUploader, prepareQwenAiMultimodalMessage } from './qwen-ai-files' const QWEN_AI_BASE = 'https://chat.qwen.ai' @@ -36,16 +39,14 @@ const MODEL_ALIASES: Record = { qwen: 'qwen3.7-max', qwen3: 'qwen3.7-max', 'qwen3.7': 'qwen3.7-max', + 'qwen3.7-plus': 'qwen3.7-plus', 'qwen3.6': 'qwen3.6-plus', 'qwen3.6-35b': 'qwen3.6-35b-a3b', 'qwen3.6-27b': 'qwen3.6-27b', 'qwen3-coder': 'qwen3-coder-plus', } -interface QwenAiMessage { - role: 'user' | 'assistant' | 'system' - content: string -} +type QwenAiMessage = ChatMessage interface ChatCompletionRequest { model: string @@ -74,6 +75,7 @@ function timestamp(): number { export class QwenAiAdapter { private provider: Provider private account: Account + private tokenRefresher = new QwenAiTokenRefresher() private axiosInstance = axios.create({ timeout: 120000, maxBodyLength: Infinity, @@ -85,6 +87,25 @@ export class QwenAiAdapter { this.account = account } + private async refreshTokenIfNeeded(): Promise { + this.account = await this.tokenRefresher.refreshIfNeeded(this.account) + } + + private async postWithRefreshRetry( + url: string, + payload: unknown, + createOptions: () => Record, + ): Promise { + let response = await this.axiosInstance.post(url, payload, createOptions()) + + if (response.status === 401) { + this.account = await this.tokenRefresher.refreshAfterUnauthorized(this.account) + response = await this.axiosInstance.post(url, payload, createOptions()) + } + + return response + } + private getToken(): string { const credentials = this.account.credentials return credentials.token || credentials.accessToken || credentials.apiKey || '' @@ -117,6 +138,34 @@ export class QwenAiAdapter { return headers } + private sanitizeHeadersForLog(headers: Record): Record { + const sensitiveHeaders = new Set(['authorization', 'cookie', 'bx-ua', 'bx-umidtoken']) + + return Object.fromEntries( + Object.entries(headers).map(([key, value]) => [ + key, + sensitiveHeaders.has(key.toLowerCase()) ? '[REDACTED]' : value, + ]), + ) + } + + private sanitizePayloadForLog(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(item => this.sanitizePayloadForLog(item)) + } + + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.entries(value as Record).map(([key, item]) => [ + key, + key === 'url' ? '[REDACTED_URL]' : this.sanitizePayloadForLog(item), + ]), + ) + } + + return value + } + mapModel(openaiModel: string): string { let model = openaiModel let forceThinking: boolean | undefined @@ -149,6 +198,8 @@ export class QwenAiAdapter { } async createChat(modelId: string, title: string = 'New Chat'): Promise { + await this.refreshTokenIfNeeded() + const url = `${QWEN_AI_BASE}/api/v2/chats/new` const payload = { title, @@ -160,9 +211,10 @@ export class QwenAiAdapter { } try { - const response = await this.axiosInstance.post(url, payload, { + const response = await this.postWithRefreshRetry(url, payload, () => ({ headers: this.getHeaders(), - }) + validateStatus: () => true, + })) console.log('[QwenAI] Create chat response:', JSON.stringify(response.data, null, 2)) @@ -231,6 +283,8 @@ export class QwenAiAdapter { chatId: string parentId: string | null }> { + await this.refreshTokenIfNeeded() + const token = this.getToken() if (!token) { throw new Error('Qwen AI token not configured, please add token in account settings') @@ -261,24 +315,13 @@ export class QwenAiAdapter { console.log('[QwenAI] Created new chat:', chatId) const messages = request.messages - - // Extract system message and user message - let systemContent = '' - let userContent = '' - - // Single-turn mode: extract all messages - for (const msg of messages) { - if (msg.role === 'system') { - systemContent += (systemContent ? '\n\n' : '') + msg.content - } else if (msg.role === 'user') { - userContent = msg.content - } - } - - // If system prompt exists, prepend it to user content - if (systemContent) { - userContent = `${systemContent}\n\nUser: ${userContent}` - } + const uploader = new QwenAiFileUploader( + this.axiosInstance, + () => this.getHeaders(chatId), + this.postWithRefreshRetry.bind(this), + ) + const preparedUserMessage = await prepareQwenAiMultimodalMessage(messages, uploader) + const qwenFiles = preparedUserMessage.files const fid = uuid() const childId = uuid() @@ -320,9 +363,9 @@ export class QwenAiAdapter { parentId: null, childrenIds: [childId], role: 'user', - content: userContent, + content: preparedUserMessage.content, user_action: 'chat', - files: [], + files: qwenFiles, timestamp: ts, models: [modelId], chat_type: 't2t', @@ -339,17 +382,18 @@ export class QwenAiAdapter { console.log('[QwenAI] Sending request to /api/v2/chat/completions...') console.log('[QwenAI] Request URL:', url) - console.log('[QwenAI] Request payload:', JSON.stringify(payload, null, 2)) - console.log('[QwenAI] Request headers:', JSON.stringify(this.getHeaders(chatId), null, 2)) + console.log('[QwenAI] Request payload:', JSON.stringify(this.sanitizePayloadForLog(payload), null, 2)) + console.log('[QwenAI] Request headers:', JSON.stringify(this.sanitizeHeadersForLog(this.getHeaders(chatId)), null, 2)) - const response = await this.axiosInstance.post(url, payload, { + const response = await this.postWithRefreshRetry(url, payload, () => ({ headers: { ...this.getHeaders(chatId), 'x-accel-buffering': 'no', }, responseType: 'stream', timeout: 120000, - }) + validateStatus: () => true, + })) console.log('[QwenAI] Response status:', response.status) console.log('[QwenAI] Response headers:', JSON.stringify(response.headers, null, 2)) diff --git a/src/main/proxy/loadbalancer.ts b/src/main/proxy/loadbalancer.ts index 9124cd3f..005fdf48 100644 --- a/src/main/proxy/loadbalancer.ts +++ b/src/main/proxy/loadbalancer.ts @@ -113,7 +113,7 @@ export class LoadBalancer { console.log(`[LoadBalancer] Provider ${provider.name} (${provider.id}) has ${accounts.length} available accounts`) for (const account of accounts) { - console.log(`[LoadBalancer] Account ${account.name} (${account.id}) Token: ${(account.credentials.token || '').substring(0, 20)}...`) + console.log(`[LoadBalancer] Account ${account.name} (${account.id}) selected as candidate`) candidates.push({ account, provider, @@ -134,7 +134,7 @@ export class LoadBalancer { return true } - const normalizedModel = model.toLowerCase() + const normalizedModel = this.normalizeModelForProviderMatch(model).toLowerCase() const supported = effectiveModels.some(m => { const normalizedSupported = m.displayName.toLowerCase() if (normalizedSupported.endsWith('*')) { @@ -159,7 +159,7 @@ export class LoadBalancer { } const actualModel = globalMapping.actualModel - const normalizedActualModel = actualModel.toLowerCase() + const normalizedActualModel = this.normalizeModelForProviderMatch(actualModel).toLowerCase() const actualSupported = effectiveModels.some(m => { const normalizedSupported = m.displayName.toLowerCase() if (normalizedSupported.endsWith('*')) { @@ -173,11 +173,15 @@ export class LoadBalancer { return true } } - + console.log(`[LoadBalancer] Provider ${provider.name} does not support model ${model}`) return false } + private normalizeModelForProviderMatch(model: string): string { + return model.replace(/-(thinking|fast)$/i, '') + } + /** * Check if account is available */ @@ -200,8 +204,9 @@ export class LoadBalancer { console.log(`[LoadBalancer] mapModel called with model="${model}", provider="${provider.name}"`) const effectiveModels = storeManager.getEffectiveModels(provider.id) + const normalizedModel = this.normalizeModelForProviderMatch(model).toLowerCase() const effectiveModel = effectiveModels.find(m => - m.displayName.toLowerCase() === model.toLowerCase() + m.displayName.toLowerCase() === normalizedModel ) if (effectiveModel) { diff --git a/src/main/proxy/routes/management/accounts.ts b/src/main/proxy/routes/management/accounts.ts index 1ddfd87b..0ff19424 100644 --- a/src/main/proxy/routes/management/accounts.ts +++ b/src/main/proxy/routes/management/accounts.ts @@ -7,6 +7,16 @@ import Router from '@koa/router' import type { Context } from 'koa' import { managementAuthMiddleware } from '../../middleware/managementAuth' import AccountManager from '../../../store/accounts' +import ProviderManager from '../../../store/providers' +import { KimiAdapter } from '../../adapters/kimi' +import { QwenAdapter } from '../../adapters/qwen' +import { QwenAiAdapter } from '../../adapters/qwen-ai' +import { MiniMaxAdapter } from '../../adapters/minimax' +import { ZaiAdapter } from '../../adapters/zai' +import { PerplexityAdapter } from '../../adapters/perplexity' +import { DeepSeekAdapter } from '../../adapters/deepseek' +import { GLMAdapter } from '../../adapters/glm' +import { MimoAdapter } from '../../adapters/mimo' import type { Account, CreateAccountRequest, @@ -33,6 +43,14 @@ function maskCredentials(account: Account): Account { } } +function shouldIncludeCredentials(ctx: Context): boolean { + return ctx.query.includeCredentials === 'true' || ctx.query.includeCredentials === '1' +} + +function maybeMask(account: Account, includeCredentials: boolean): Account { + return includeCredentials ? account : maskCredentials(account) +} + /** * Create error response */ @@ -62,11 +80,12 @@ function createSuccessResponse(data: T): ManagementApiResponse { */ router.get('/accounts', managementAuthMiddleware, async (ctx: Context) => { try { - const accounts = AccountManager.getAll(false) - const maskedAccounts = accounts.map(maskCredentials) + const includeCredentials = shouldIncludeCredentials(ctx) + const accounts = AccountManager.getAll(includeCredentials) + const responseAccounts = accounts.map((account) => maybeMask(account, includeCredentials)) ctx.set('Content-Type', 'application/json') - ctx.body = createSuccessResponse(maskedAccounts) + ctx.body = createSuccessResponse(responseAccounts) } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Failed to get accounts' ctx.status = 500 @@ -81,11 +100,12 @@ router.get('/accounts', managementAuthMiddleware, async (ctx: Context) => { router.get('/providers/:providerId/accounts', managementAuthMiddleware, async (ctx: Context) => { try { const providerId = ctx.params.providerId - const accounts = AccountManager.getByProviderId(providerId, false) - const maskedAccounts = accounts.map(maskCredentials) + const includeCredentials = shouldIncludeCredentials(ctx) + const accounts = AccountManager.getByProviderId(providerId, includeCredentials) + const responseAccounts = accounts.map((account) => maybeMask(account, includeCredentials)) ctx.set('Content-Type', 'application/json') - ctx.body = createSuccessResponse(maskedAccounts) + ctx.body = createSuccessResponse(responseAccounts) } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Failed to get accounts by provider' ctx.status = 500 @@ -101,7 +121,8 @@ router.get('/providers/:providerId/accounts', managementAuthMiddleware, async (c router.get('/accounts/:id', managementAuthMiddleware, async (ctx: Context) => { try { const id = ctx.params.id - const account = AccountManager.getById(id, false) + const includeCredentials = shouldIncludeCredentials(ctx) + const account = AccountManager.getById(id, includeCredentials) if (!account) { ctx.status = 404 @@ -109,9 +130,8 @@ router.get('/accounts/:id', managementAuthMiddleware, async (ctx: Context) => { return } - const maskedAccount = maskCredentials(account) ctx.set('Content-Type', 'application/json') - ctx.body = createSuccessResponse(maskedAccount) + ctx.body = createSuccessResponse(maybeMask(account, includeCredentials)) } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Failed to get account' ctx.status = 500 @@ -273,4 +293,74 @@ router.post('/accounts/:id/validate', managementAuthMiddleware, async (ctx: Cont } }) +router.get('/accounts/:id/credits', managementAuthMiddleware, async (ctx: Context) => { + try { + const account = AccountManager.getById(ctx.params.id, true) + if (!account) { + ctx.status = 404 + ctx.body = createErrorResponse('account_not_found', `Account not found: ${ctx.params.id}`) + return + } + + const provider = ProviderManager.getById(account.providerId) + if (!provider || provider.id !== 'minimax') { + ctx.body = createSuccessResponse(null) + return + } + + const adapter = new MiniMaxAdapter(provider, account) + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(await adapter.getCredits()) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to get account credits' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.post('/accounts/:id/clear-chats', managementAuthMiddleware, async (ctx: Context) => { + try { + const account = AccountManager.getById(ctx.params.id, true) + if (!account) { + ctx.status = 404 + ctx.body = createErrorResponse('account_not_found', `Account not found: ${ctx.params.id}`) + return + } + + const provider = ProviderManager.getById(account.providerId) + if (!provider) { + ctx.status = 404 + ctx.body = createErrorResponse('provider_not_found', `Provider not found: ${account.providerId}`) + return + } + + const clearChatsHandlers: Record Promise> = { + kimi: () => new KimiAdapter(provider, account).deleteAllChats(), + qwen: () => new QwenAdapter(provider, account).deleteAllChats(), + 'qwen-ai': () => new QwenAiAdapter(provider, account).deleteAllChats(), + minimax: () => new MiniMaxAdapter(provider, account).deleteAllChats(), + zai: () => new ZaiAdapter(provider, account).deleteAllChats(), + perplexity: () => new PerplexityAdapter(provider, account).deleteAllChats(), + deepseek: () => new DeepSeekAdapter(provider, account).deleteAllChats(), + glm: () => new GLMAdapter(provider, account).deleteAllChats(), + mimo: () => new MimoAdapter(provider, account).deleteAllChats(), + } + + const handler = clearChatsHandlers[provider.id] + if (!handler) { + ctx.body = createSuccessResponse({ + success: false, + error: 'This feature is not available for this provider', + }) + return + } + + ctx.body = createSuccessResponse({ success: await handler() }) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to clear chats' + ctx.status = 500 + ctx.body = createSuccessResponse({ success: false, error: errorMessage }) + } +}) + export default router diff --git a/src/main/proxy/routes/management/config.ts b/src/main/proxy/routes/management/config.ts index daf274af..1dc2b8f8 100644 --- a/src/main/proxy/routes/management/config.ts +++ b/src/main/proxy/routes/management/config.ts @@ -86,12 +86,11 @@ function maskConfig(config: AppConfig): Record { router.get('/', async (ctx: Context) => { try { const config = ConfigManager.get() - const maskedConfig = maskConfig(config) ctx.body = { success: true, - data: maskedConfig, - } as ManagementApiResponse> + data: config, + } as ManagementApiResponse } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error' ctx.status = 500 @@ -137,12 +136,11 @@ router.put('/', async (ctx: Context) => { } const updatedConfig = ConfigManager.update(updates as Partial) - const maskedConfig = maskConfig(updatedConfig) ctx.body = { success: true, - data: maskedConfig, - } as ManagementApiResponse> + data: updatedConfig, + } as ManagementApiResponse } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error' ctx.status = 500 diff --git a/src/main/proxy/routes/management/providers.ts b/src/main/proxy/routes/management/providers.ts index 4324b797..a511d403 100644 --- a/src/main/proxy/routes/management/providers.ts +++ b/src/main/proxy/routes/management/providers.ts @@ -7,6 +7,14 @@ import Router from '@koa/router' import type { Context } from 'koa' import { managementAuthMiddleware } from '../../middleware/managementAuth' import ProviderManager from '../../../store/providers' +import { BUILTIN_PROVIDERS } from '../../../store/types' +import { CustomProviderManager } from '../../../providers/custom' +import { ProviderChecker } from '../../../providers/checker' +import { getBuiltinProvider } from '../../../providers/builtin' +import { parseProviderModelsResponse } from '../../../providers/modelSync' +import AccountManager from '../../../store/accounts' +import { storeManager } from '../../../store/store' +import axios from 'axios' import type { Provider, CreateProviderRequest, @@ -49,6 +57,65 @@ router.get('/', async (ctx: Context) => { } }) +router.get('/builtin', async (ctx: Context) => { + try { + const builtinProviders = BUILTIN_PROVIDERS.map((provider) => ({ + ...provider, + credentialFields: provider.credentialFields, + })) + + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(builtinProviders) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to get built-in providers' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.post('/check-all', async (ctx: Context) => { + try { + const providers = ProviderManager.getAll() + const results: Record = {} + + await Promise.all(providers.map(async (provider) => { + const result = await ProviderChecker.checkProviderStatus(provider) + results[provider.id] = result + ProviderManager.update(provider.id, { + status: result.status, + lastStatusCheck: Date.now(), + }) + })) + + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(results) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to check provider status' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.post('/import', async (ctx: Context) => { + try { + const body = ctx.request.body as { jsonData?: string } + if (!body.jsonData) { + ctx.status = 400 + ctx.body = createErrorResponse('invalid_request', 'Missing required field: jsonData') + return + } + + const provider = CustomProviderManager.importProvider(body.jsonData) + ctx.status = 201 + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(provider) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to import provider' + ctx.status = 400 + ctx.body = createErrorResponse('import_failed', errorMessage) + } +}) + router.get('/:id', async (ctx: Context) => { try { const id = ctx.params.id @@ -69,6 +136,237 @@ router.get('/:id', async (ctx: Context) => { } }) +router.post('/:id/check', async (ctx: Context) => { + try { + const id = ctx.params.id + const provider = ProviderManager.getById(id) + + if (!provider) { + ctx.status = 404 + ctx.body = createErrorResponse('not_found', 'Provider not found') + return + } + + const result = await ProviderChecker.checkProviderStatus(provider) + ProviderManager.update(id, { + status: result.status, + lastStatusCheck: Date.now(), + }) + + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(result) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to check provider status' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.post('/:id/validate-token', async (ctx: Context) => { + try { + const providerId = ctx.params.id + const body = ctx.request.body as { credentials?: Record } + const credentials = body.credentials || {} + + let provider = ProviderManager.getById(providerId) + const builtinConfig = getBuiltinProvider(providerId) + + if (!provider && builtinConfig) { + provider = { + id: builtinConfig.id, + name: builtinConfig.name, + type: 'builtin', + authType: builtinConfig.authType, + apiEndpoint: builtinConfig.apiEndpoint, + chatPath: builtinConfig.chatPath, + headers: builtinConfig.headers, + enabled: true, + description: builtinConfig.description, + supportedModels: builtinConfig.supportedModels || [], + modelMappings: builtinConfig.modelMappings || {}, + createdAt: Date.now(), + updatedAt: Date.now(), + } + } + + if (!provider) { + ctx.status = 404 + ctx.body = createErrorResponse('not_found', 'Provider not found') + return + } + + const result = await ProviderChecker.checkAccountToken(provider, { + id: 'temp', + providerId, + name: 'temp', + credentials, + status: 'active', + createdAt: Date.now(), + updatedAt: Date.now(), + }) + + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(result) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to validate token' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.post('/:id/duplicate', async (ctx: Context) => { + try { + const provider = CustomProviderManager.duplicate(ctx.params.id) + ctx.status = 201 + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(provider) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to duplicate provider' + ctx.status = errorMessage.includes('not found') ? 404 : 500 + ctx.body = createErrorResponse('duplicate_failed', errorMessage) + } +}) + +router.get('/:id/export', async (ctx: Context) => { + try { + const json = CustomProviderManager.exportProvider(ctx.params.id) + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(json) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to export provider' + ctx.status = errorMessage.includes('not found') ? 404 : 500 + ctx.body = createErrorResponse('export_failed', errorMessage) + } +}) + +router.post('/:id/models/update', async (ctx: Context) => { + try { + const providerId = ctx.params.id + const provider = ProviderManager.getById(providerId) + + if (!provider) { + ctx.status = 404 + ctx.body = createErrorResponse('not_found', 'Provider not found') + return + } + + let modelsApiEndpoint: string | undefined + let modelsApiHeaders: Record | undefined + + if (provider.type === 'builtin') { + const builtinConfig = getBuiltinProvider(providerId) + modelsApiEndpoint = builtinConfig?.modelsApiEndpoint + modelsApiHeaders = builtinConfig?.modelsApiHeaders + } + + if (!modelsApiEndpoint) { + ctx.body = createSuccessResponse({ + success: false, + error: 'This provider does not support dynamic model updates', + }) + return + } + + const activeAccount = AccountManager.getByProviderId(providerId, true) + .find(account => account.status === 'active') + + const headers: Record = { + 'Content-Type': 'application/json', + Accept: 'application/json', + ...modelsApiHeaders, + } + + if (activeAccount?.credentials?.token) { + headers.Authorization = `Bearer ${activeAccount.credentials.token}` + } + if (activeAccount?.credentials?.cookies) { + headers.Cookie = activeAccount.credentials.cookies + } + + const response = await axios.get(modelsApiEndpoint, { + headers, + timeout: 15000, + validateStatus: () => true, + }) + + if (response.status !== 200) { + ctx.body = createSuccessResponse({ + success: false, + error: `Failed to fetch models: HTTP ${response.status}`, + }) + return + } + + const { supportedModels, modelMappings } = parseProviderModelsResponse(response.data) + if (supportedModels.length === 0) { + ctx.body = createSuccessResponse({ + success: false, + error: 'No models found in the response', + }) + return + } + + ProviderManager.update(providerId, { supportedModels, modelMappings }) + + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse({ + success: true, + modelsCount: supportedModels.length, + }) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to update models' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.get('/:id/models/effective', async (ctx: Context) => { + try { + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(storeManager.getEffectiveModels(ctx.params.id)) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to get effective models' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.post('/:id/models/custom', async (ctx: Context) => { + try { + const models = storeManager.addCustomModel(ctx.params.id, ctx.request.body as { displayName: string; actualModelId: string }) + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse({ success: true, models }) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to add custom model' + ctx.status = 400 + ctx.body = createSuccessResponse({ success: false, error: errorMessage, models: [] }) + } +}) + +router.delete('/:id/models/:modelName', async (ctx: Context) => { + try { + const models = storeManager.removeModel(ctx.params.id, decodeURIComponent(ctx.params.modelName)) + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse({ success: true, models }) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to remove model' + ctx.status = 400 + ctx.body = createSuccessResponse({ success: false, error: errorMessage, models: [] }) + } +}) + +router.post('/:id/models/reset', async (ctx: Context) => { + try { + const models = storeManager.resetModels(ctx.params.id) + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse({ success: true, models }) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to reset models' + ctx.status = 400 + ctx.body = createSuccessResponse({ success: false, error: errorMessage, models: [] }) + } +}) + router.post('/', async (ctx: Context) => { try { const request = ctx.request.body as CreateProviderRequest @@ -92,6 +390,7 @@ router.post('/', async (ctx: Context) => { } const provider = ProviderManager.create({ + id: request.id, name: request.name, type: request.type || 'custom', authType: request.authType, @@ -101,6 +400,10 @@ router.post('/', async (ctx: Context) => { description: request.description, icon: request.icon, supportedModels: request.supportedModels, + modelMappings: request.modelMappings, + modelsApiEndpoint: request.modelsApiEndpoint, + modelsApiHeaders: request.modelsApiHeaders, + credentialFields: request.credentialFields, }) ctx.status = 201 diff --git a/src/main/proxy/routes/management/sessions.ts b/src/main/proxy/routes/management/sessions.ts index b20414e0..51827595 100644 --- a/src/main/proxy/routes/management/sessions.ts +++ b/src/main/proxy/routes/management/sessions.ts @@ -65,6 +65,78 @@ router.get('/sessions', managementAuthMiddleware, async (ctx: Context) => { } }) +router.get('/sessions/all', managementAuthMiddleware, async (ctx: Context) => { + try { + const sessions = sessionManager.getAllSessions() + const transformedSessions = sessions.map(transformSession) + + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(transformedSessions) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to get sessions' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.get('/sessions/config', managementAuthMiddleware, async (ctx: Context) => { + try { + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(sessionManager.getSessionConfig()) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to get session config' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.put('/sessions/config', managementAuthMiddleware, async (ctx: Context) => { + try { + const updates = ctx.request.body as Record + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(sessionManager.updateSessionConfig(updates)) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to update session config' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.get('/accounts/:accountId/sessions', managementAuthMiddleware, async (ctx: Context) => { + try { + const sessions = sessionManager.getSessionsByAccount(ctx.params.accountId) + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(sessions.map(transformSession)) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to get sessions by account' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.get('/providers/:providerId/sessions', managementAuthMiddleware, async (ctx: Context) => { + try { + const sessions = sessionManager.getSessionsByProvider(ctx.params.providerId) + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(sessions.map(transformSession)) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to get sessions by provider' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + +router.post('/sessions/clean-expired', managementAuthMiddleware, async (ctx: Context) => { + try { + ctx.set('Content-Type', 'application/json') + ctx.body = createSuccessResponse(sessionManager.cleanExpiredSessions()) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to clean expired sessions' + ctx.status = 500 + ctx.body = createErrorResponse('internal_error', errorMessage) + } +}) + /** * GET /v0/management/sessions/:id * Get session by ID with message history diff --git a/src/main/proxy/routes/management/statistics.ts b/src/main/proxy/routes/management/statistics.ts index f1380023..72a99fcf 100644 --- a/src/main/proxy/routes/management/statistics.ts +++ b/src/main/proxy/routes/management/statistics.ts @@ -8,6 +8,9 @@ import type { Context } from 'koa' import { managementAuthMiddleware } from '../../middleware/managementAuth' import { proxyStatusManager } from '../../status' import { storeManager } from '../../../store/store' +import { createAdapter } from '../../../oauth/adapters' +import { getRuntime } from '../../../runtime' +import { generateManagementSecret } from '../../middleware/managementAuth' import type { ManagementApiResponse, StatisticsResponse, @@ -15,13 +18,157 @@ import type { ProxyStatusResponse, LogEntry, LogLevel, + SystemPrompt, } from '../../../../shared/types' import type { RequestLogEntry } from '../../../store/types' +import type { ProviderType } from '../../../oauth/types' const router = new Router({ prefix: '/v0/management' }) +const BROWSER_IMPORT_RESULT_TTL_MS = 10 * 60 * 1000 +const BROWSER_IMPORT_RESULT_LIMIT = 128 + +type BrowserImportProviderId = 'qwen' | 'qwen-ai' + +type BrowserImportResult = { + importId: string + providerId: BrowserImportProviderId + status: 'success' | 'error' + credentials: Record + error?: string + createdAt: number + expiresAt: number +} + +const browserImportResults = new Map() + +function cleanupBrowserImportResults(): void { + const now = Date.now() + for (const [id, result] of browserImportResults.entries()) { + if (result.expiresAt <= now) { + browserImportResults.delete(id) + } + } + + if (browserImportResults.size > BROWSER_IMPORT_RESULT_LIMIT) { + const overflow = browserImportResults.size - BROWSER_IMPORT_RESULT_LIMIT + const oldestIds = [...browserImportResults.entries()] + .sort(([, left], [, right]) => left.createdAt - right.createdAt) + .slice(0, overflow) + .map(([id]) => id) + + oldestIds.forEach((id) => browserImportResults.delete(id)) + } +} + +function parseBrowserImportBody(body: unknown): Record { + if (typeof body === 'string') { + try { + return JSON.parse(body) as Record + } catch { + return {} + } + } + return body && typeof body === 'object' ? body as Record : {} +} + +function normalizeBrowserImportCredentials( + providerId: BrowserImportProviderId, + credentials: Record, +): Record { + if (providerId === 'qwen-ai') { + return { + token: String(credentials.token || ''), + cookies: String(credentials.cookies || ''), + } + } + + const ticket = String(credentials.ticket || credentials.tongyi_sso_ticket || '') + return { + ticket, + tongyi_sso_ticket: ticket, + } +} + +function setBrowserImportResult(input: { + importId: string + providerId: string + credentials?: Record + error?: string +}): BrowserImportResult { + cleanupBrowserImportResults() + + if (!input.importId || input.importId.length < 16) { + throw new Error('importId is required') + } + + if (input.providerId !== 'qwen' && input.providerId !== 'qwen-ai') { + throw new Error('Unsupported browser import provider') + } + + const credentials = normalizeBrowserImportCredentials( + input.providerId, + input.credentials || {}, + ) + const error = String(input.error || '') + const now = Date.now() + const result: BrowserImportResult = { + importId: input.importId, + providerId: input.providerId, + status: error ? 'error' : 'success', + credentials, + error: error || undefined, + createdAt: now, + expiresAt: now + BROWSER_IMPORT_RESULT_TTL_MS, + } + + browserImportResults.set(input.importId, result) + return result +} + +router.post('/browser-import/complete', async (ctx: Context) => { + const body = parseBrowserImportBody(ctx.request.body) + + try { + const result = setBrowserImportResult({ + importId: String(body.importId || ''), + providerId: String(body.providerId || ''), + credentials: parseBrowserImportBody(body.credentials) as Record, + error: String(body.error || ''), + }) + + ctx.body = { + success: true, + data: { + status: result.status, + providerId: result.providerId, + }, + } as ManagementApiResponse + } catch (error) { + ctx.status = 400 + ctx.body = { + success: false, + error: { + code: 'invalid_browser_import', + message: error instanceof Error ? error.message : 'Invalid browser import payload', + }, + } as ManagementApiResponse + } +}) + router.use(managementAuthMiddleware) +router.get('/browser-import/:importId', async (ctx: Context) => { + cleanupBrowserImportResults() + const importId = String(ctx.params.importId || '') + const result = browserImportResults.get(importId) + + ctx.body = { + success: true, + data: result || null, + } as ManagementApiResponse +}) + router.get('/statistics', async (ctx: Context) => { try { const proxyStats = proxyStatusManager.getStatistics() @@ -67,6 +214,65 @@ router.get('/statistics', async (ctx: Context) => { } }) +router.get('/statistics/persistent', async (ctx: Context) => { + try { + ctx.body = { + success: true, + data: storeManager.getStatistics(), + } as ManagementApiResponse + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error' + ctx.status = 500 + ctx.body = { + success: false, + error: { code: 'internal_error', message: errorMessage }, + } as ManagementApiResponse + } +}) + +router.get('/statistics/today', async (ctx: Context) => { + try { + ctx.body = { + success: true, + data: storeManager.getTodayStatistics(), + } as ManagementApiResponse + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error' + ctx.status = 500 + ctx.body = { + success: false, + error: { code: 'internal_error', message: errorMessage }, + } as ManagementApiResponse + } +}) + +router.get('/proxy/statistics', async (ctx: Context) => { + try { + const stats = proxyStatusManager.getStatistics() + ctx.body = { + success: true, + data: { + totalRequests: stats.totalRequests, + successRequests: stats.successRequests, + failedRequests: stats.failedRequests, + avgLatency: stats.avgLatency, + requestsPerMinute: stats.requestsPerMinute, + activeConnections: stats.activeConnections, + modelUsage: stats.modelUsage, + providerUsage: stats.providerUsage, + accountUsage: stats.accountUsage, + }, + } as ManagementApiResponse + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error' + ctx.status = 500 + ctx.body = { + success: false, + error: { code: 'internal_error', message: errorMessage }, + } as ManagementApiResponse + } +}) + router.get('/health', async (ctx: Context) => { try { const runningStatus = proxyStatusManager.getRunningStatus() @@ -207,4 +413,377 @@ router.get('/logs', async (ctx: Context) => { } }) +router.get('/app-logs', async (ctx: Context) => { + try { + const level = ctx.query.level as LogLevel | 'all' | undefined + const keyword = ctx.query.keyword as string | undefined + const startTime = ctx.query.startTime ? Number(ctx.query.startTime) : undefined + const endTime = ctx.query.endTime ? Number(ctx.query.endTime) : undefined + const limit = ctx.query.limit ? Number(ctx.query.limit) : undefined + const offset = ctx.query.offset ? Number(ctx.query.offset) : undefined + + ctx.body = { + success: true, + data: storeManager.getLogs({ level, keyword, startTime, endTime, limit, offset }), + } as ManagementApiResponse + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error' + ctx.status = 500 + ctx.body = { + success: false, + error: { code: 'internal_error', message: errorMessage }, + } as ManagementApiResponse + } +}) + +router.put('/app-logs', async (ctx: Context) => { + try { + storeManager.replaceLogs(Array.isArray(ctx.request.body) ? ctx.request.body as LogEntry[] : []) + ctx.body = { success: true, data: null } as ManagementApiResponse + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error' + ctx.status = 500 + ctx.body = { + success: false, + error: { code: 'internal_error', message: errorMessage }, + } as ManagementApiResponse + } +}) + +router.delete('/app-logs', async (ctx: Context) => { + try { + storeManager.clearLogs() + ctx.body = { success: true, data: null } as ManagementApiResponse + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error' + ctx.status = 500 + ctx.body = { + success: false, + error: { code: 'internal_error', message: errorMessage }, + } as ManagementApiResponse + } +}) + +router.get('/app-logs/stats', async (ctx: Context) => { + ctx.body = { success: true, data: storeManager.getLogStats() } as ManagementApiResponse +}) + +router.get('/app-logs/trend', async (ctx: Context) => { + const days = ctx.query.days ? Number(ctx.query.days) : undefined + ctx.body = { success: true, data: storeManager.getLogTrend(days) } as ManagementApiResponse +}) + +router.get('/accounts/:accountId/logs/trend', async (ctx: Context) => { + const days = ctx.query.days ? Number(ctx.query.days) : undefined + ctx.body = { + success: true, + data: storeManager.getAccountLogTrend(ctx.params.accountId, days), + } as ManagementApiResponse +}) + +router.get('/app-logs/export', async (ctx: Context) => { + const format = ctx.query.format === 'txt' ? 'txt' : 'json' + ctx.body = { + success: true, + data: storeManager.exportLogs(format), + } as ManagementApiResponse +}) + +router.get('/app-logs/:id', async (ctx: Context) => { + const log = storeManager.getLogById(ctx.params.id) + if (!log) { + ctx.status = 404 + ctx.body = { + success: false, + error: { code: 'not_found', message: 'Log not found' }, + } as ManagementApiResponse + return + } + + ctx.body = { success: true, data: log } as ManagementApiResponse +}) + +router.get('/request-logs', async (ctx: Context) => { + const limit = ctx.query.limit ? Number(ctx.query.limit) : undefined + const filter = { + status: ctx.query.status as 'success' | 'error' | undefined, + providerId: ctx.query.providerId as string | undefined, + } + ctx.body = { + success: true, + data: storeManager.getRequestLogs(limit, filter), + } as ManagementApiResponse +}) + +router.get('/request-logs/stats', async (ctx: Context) => { + ctx.body = { success: true, data: storeManager.getRequestLogStats() } as ManagementApiResponse +}) + +router.get('/request-logs/trend', async (ctx: Context) => { + const days = ctx.query.days ? Number(ctx.query.days) : undefined + ctx.body = { success: true, data: storeManager.getRequestLogTrend(days) } as ManagementApiResponse +}) + +router.delete('/request-logs', async (ctx: Context) => { + storeManager.clearRequestLogs() + ctx.body = { success: true, data: null } as ManagementApiResponse +}) + +router.get('/request-logs/:id', async (ctx: Context) => { + const log = storeManager.getRequestLogById(ctx.params.id) + if (!log) { + ctx.status = 404 + ctx.body = { + success: false, + error: { code: 'not_found', message: 'Request log not found' }, + } as ManagementApiResponse + return + } + ctx.body = { success: true, data: log } as ManagementApiResponse +}) + +router.get('/prompts', async (ctx: Context) => { + ctx.body = { success: true, data: storeManager.getSystemPrompts() } as ManagementApiResponse +}) + +router.get('/prompts/builtin', async (ctx: Context) => { + ctx.body = { success: true, data: storeManager.getBuiltinPrompts() } as ManagementApiResponse +}) + +router.get('/prompts/custom', async (ctx: Context) => { + ctx.body = { success: true, data: storeManager.getCustomPrompts() } as ManagementApiResponse +}) + +router.get('/prompts/type/:type', async (ctx: Context) => { + ctx.body = { + success: true, + data: storeManager.getSystemPromptsByType(ctx.params.type as SystemPrompt['type']), + } as ManagementApiResponse +}) + +router.get('/prompts/:id', async (ctx: Context) => { + const prompt = storeManager.getSystemPromptById(ctx.params.id) + if (!prompt) { + ctx.status = 404 + ctx.body = { + success: false, + error: { code: 'not_found', message: 'Prompt not found' }, + } as ManagementApiResponse + return + } + ctx.body = { success: true, data: prompt } as ManagementApiResponse +}) + +router.post('/prompts', async (ctx: Context) => { + ctx.status = 201 + ctx.body = { + success: true, + data: storeManager.addSystemPrompt(ctx.request.body as Omit), + } as ManagementApiResponse +}) + +router.put('/prompts/:id', async (ctx: Context) => { + ctx.body = { + success: true, + data: storeManager.updateSystemPrompt(ctx.params.id, ctx.request.body as Partial), + } as ManagementApiResponse +}) + +router.delete('/prompts/:id', async (ctx: Context) => { + ctx.body = { + success: true, + data: storeManager.deleteSystemPrompt(ctx.params.id), + } as ManagementApiResponse +}) + +router.get('/store/:key', async (ctx: Context) => { + const key = ctx.params.key as 'providers' | 'accounts' | 'config' | 'logs' + ctx.body = { + success: true, + data: storeManager.getStore()?.get(key), + } as ManagementApiResponse +}) + +router.put('/store/:key', async (ctx: Context) => { + const key = ctx.params.key as 'providers' | 'accounts' | 'config' | 'logs' + const body = ctx.request.body as { value?: unknown } + storeManager.getStore()?.set(key, body.value as never) + ctx.body = { success: true, data: null } as ManagementApiResponse +}) + +router.delete('/store/:key', async (ctx: Context) => { + const key = ctx.params.key as 'providers' | 'accounts' | 'config' | 'logs' + storeManager.getStore()?.delete(key) + ctx.body = { success: true, data: null } as ManagementApiResponse +}) + +router.delete('/store', async (ctx: Context) => { + const body = ctx.request.body as { confirm?: boolean } | undefined + if (!body || body.confirm !== true) { + ctx.status = 400 + ctx.body = { + success: false, + error: { code: 'confirmation_required', message: 'Request body must include { confirm: true }' }, + } as ManagementApiResponse + return + } + + storeManager.clearAll() + ctx.body = { success: true, data: null } as ManagementApiResponse +}) + +router.get('/oauth/status', async (ctx: Context) => { + ctx.body = { success: true, data: 'idle' } as ManagementApiResponse +}) + +router.post('/oauth/start-login', async (ctx: Context) => { + const body = ctx.request.body as { providerId?: string; providerType?: ProviderType } + if (!body.providerId || !body.providerType) { + ctx.status = 400 + ctx.body = { + success: false, + error: { code: 'invalid_request', message: 'providerId and providerType are required' }, + } as ManagementApiResponse + return + } + + const adapter = createAdapter(body.providerType, { + providerId: body.providerId, + providerType: body.providerType, + authMethods: [], + callbackPort: 8311, + }) + ctx.body = { success: true, data: await adapter.startLogin({ providerId: body.providerId, providerType: body.providerType }) } as ManagementApiResponse +}) + +router.post('/oauth/cancel-login', async (ctx: Context) => { + ctx.body = { success: true, data: null } as ManagementApiResponse +}) + +router.post('/oauth/login-with-token', async (ctx: Context) => { + const body = ctx.request.body as { + providerId?: string + providerType?: ProviderType + token?: string + realUserID?: string + mimoUserId?: string + mimoPhToken?: string + } + + if (!body.providerId || !body.providerType || !body.token) { + ctx.status = 400 + ctx.body = { + success: false, + error: { code: 'invalid_request', message: 'providerId, providerType and token are required' }, + } as ManagementApiResponse + return + } + + const adapter = createAdapter(body.providerType, { + providerId: body.providerId, + providerType: body.providerType, + authMethods: [], + callbackPort: 8311, + }) as any + + if (typeof adapter.loginWithToken === 'function') { + ctx.body = { + success: true, + data: await adapter.loginWithToken(body.providerId, body.token, body.realUserID, body.mimoUserId, body.mimoPhToken), + } as ManagementApiResponse + return + } + + const validationCredentials = body.providerType === 'mimo' + ? { service_token: body.token, user_id: body.mimoUserId || '', ph_token: body.mimoPhToken || '' } + : { token: body.token } + const validation = await adapter.validateToken(validationCredentials) + + ctx.body = { + success: true, + data: validation.valid + ? { + success: true, + providerId: body.providerId, + providerType: body.providerType, + credentials: validationCredentials, + accountInfo: validation.accountInfo, + } + : { + success: false, + providerId: body.providerId, + providerType: body.providerType, + error: validation.error || 'Token validation failed', + }, + } as ManagementApiResponse +}) + +router.post('/oauth/validate-token', async (ctx: Context) => { + const body = ctx.request.body as { providerId?: string; providerType?: ProviderType; credentials?: Record } + if (!body.providerId || !body.providerType) { + ctx.status = 400 + ctx.body = { + success: false, + error: { code: 'invalid_request', message: 'providerId and providerType are required' }, + } as ManagementApiResponse + return + } + + const adapter = createAdapter(body.providerType, { + providerId: body.providerId, + providerType: body.providerType, + authMethods: [], + callbackPort: 8311, + }) + + ctx.body = { + success: true, + data: await adapter.validateToken(body.credentials || {}), + } as ManagementApiResponse +}) + +router.post('/oauth/refresh-token', async (ctx: Context) => { + const body = ctx.request.body as { providerId?: string; providerType?: ProviderType; credentials?: Record } + if (!body.providerId || !body.providerType) { + ctx.status = 400 + ctx.body = { + success: false, + error: { code: 'invalid_request', message: 'providerId and providerType are required' }, + } as ManagementApiResponse + return + } + + const adapter = createAdapter(body.providerType, { + providerId: body.providerId, + providerType: body.providerType, + authMethods: [], + callbackPort: 8311, + }) + + ctx.body = { + success: true, + data: await adapter.refreshToken(body.credentials || {}), + } as ManagementApiResponse +}) + +router.post('/management-api/generate-secret', async (ctx: Context) => { + const secret = generateManagementSecret() + const config = storeManager.getConfig() + storeManager.updateConfig({ + managementApi: { + ...config.managementApi, + managementApiSecret: secret, + }, + }) + ctx.body = { success: true, data: secret } as ManagementApiResponse +}) + +router.post('/app/open-external', async (ctx: Context) => { + const body = ctx.request.body as { url?: string } + if (body.url) { + await getRuntime().openExternal(body.url) + } + ctx.body = { success: true, data: null } as ManagementApiResponse +}) + export default router diff --git a/src/main/proxy/server.ts b/src/main/proxy/server.ts index d11c7708..b7543239 100644 --- a/src/main/proxy/server.ts +++ b/src/main/proxy/server.ts @@ -12,6 +12,7 @@ import managementRoutes from './routes/management' import { proxyStatusManager } from './status' import { storeManager } from '../store/store' import { sessionManager } from './sessionManager' +import { mountWebAdminAssets } from '../../server/admin/assets' const SLOW_REQUEST_THRESHOLD_MS = 1500 @@ -42,6 +43,7 @@ export class ProxyServer { ctx.set('Access-Control-Allow-Origin', '*') ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With') + ctx.set('Access-Control-Allow-Private-Network', 'true') ctx.set('Access-Control-Max-Age', '86400') if (ctx.method === 'OPTIONS') { @@ -53,6 +55,7 @@ export class ProxyServer { }) this.app.use(bodyParser({ + enableTypes: ['json', 'form', 'text'], jsonLimit: '50mb', formLimit: '50mb', textLimit: '50mb', @@ -62,7 +65,7 @@ export class ProxyServer { this.app.use(async (ctx, next) => { // Skip paths that don't require authentication const publicPaths = ['/', '/health', '/stats'] - if (publicPaths.includes(ctx.path)) { + if (publicPaths.includes(ctx.path) || ctx.path.startsWith('/admin')) { await next() return } @@ -154,6 +157,8 @@ export class ProxyServer { * Setup routes */ private setupRoutes(): void { + mountWebAdminAssets(this.app) + // Register OpenAI API routes for (const route of routes) { this.router.use(route.routes()) diff --git a/src/main/proxy/types.ts b/src/main/proxy/types.ts index 2320b96b..80dd5f06 100644 --- a/src/main/proxy/types.ts +++ b/src/main/proxy/types.ts @@ -50,12 +50,24 @@ export type ChatCompletionToolChoice = 'none' | 'auto' | 'required' | { * Message Content (supports multimodal) */ export interface ChatMessageContent { - type: 'text' | 'image_url' + type: 'text' | 'image_url' | 'file' | 'input_audio' | 'video_url' text?: string image_url?: { url: string detail?: 'auto' | 'low' | 'high' } + file_url?: { + url: string + } + input_audio?: { + data: string + format?: string + } + video_url?: { + url: string + } + filename?: string + mime_type?: string } /** diff --git a/src/main/runtime/electronRuntime.ts b/src/main/runtime/electronRuntime.ts new file mode 100644 index 00000000..e9d756e8 --- /dev/null +++ b/src/main/runtime/electronRuntime.ts @@ -0,0 +1,46 @@ +import { app, BrowserWindow, safeStorage, shell } from 'electron' +import { homedir } from 'os' +import { join } from 'path' +import type { RuntimeAdapter } from './types' + +export const electronRuntime: RuntimeAdapter = { + kind: 'electron', + + getDataDir(): string { + return join(homedir(), '.chat2api') + }, + + isEncryptionAvailable(): boolean { + try { + return safeStorage.isEncryptionAvailable() + } catch { + return false + } + }, + + encryptString(value: string): string { + return Buffer.from(safeStorage.encryptString(value)).toString('base64') + }, + + decryptString(value: string): string { + return safeStorage.decryptString(Buffer.from(value, 'base64')) + }, + + getResourcePath(fileName: string): string { + if (app.isPackaged) { + return join(process.resourcesPath, fileName) + } + + return join(app.getAppPath(), fileName) + }, + + async openExternal(url: string): Promise { + await shell.openExternal(url) + }, + + notify(channel: string, payload: unknown): void { + BrowserWindow.getAllWindows().forEach((win) => { + win.webContents.send(channel, payload) + }) + }, +} diff --git a/src/main/runtime/index.ts b/src/main/runtime/index.ts new file mode 100644 index 00000000..e10fdf2c --- /dev/null +++ b/src/main/runtime/index.ts @@ -0,0 +1,14 @@ +import type { RuntimeAdapter } from './types' +import { nodeRuntime } from './nodeRuntime' + +let runtime: RuntimeAdapter = nodeRuntime + +export function setRuntime(nextRuntime: RuntimeAdapter): void { + runtime = nextRuntime +} + +export function getRuntime(): RuntimeAdapter { + return runtime +} + +export type { RuntimeAdapter } diff --git a/src/main/runtime/nodeRuntime.ts b/src/main/runtime/nodeRuntime.ts new file mode 100644 index 00000000..cc74170f --- /dev/null +++ b/src/main/runtime/nodeRuntime.ts @@ -0,0 +1,82 @@ +import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto' +import { existsSync } from 'fs' +import { homedir } from 'os' +import { join, resolve } from 'path' +import type { RuntimeAdapter } from './types' + +const ENCRYPTION_PREFIX = 'c2a:v1:' + +function getEncryptionKey(): Buffer | null { + const secret = process.env.CHAT2API_STORAGE_ENCRYPTION_KEY + if (!secret) { + return null + } + return createHash('sha256').update(secret).digest() +} + +export const nodeRuntime: RuntimeAdapter = { + kind: 'node', + + getDataDir(): string { + if (process.env.CHAT2API_DATA_DIR) { + return resolve(process.env.CHAT2API_DATA_DIR) + } + + if (process.env.NODE_ENV === 'production') { + return '/data' + } + + return join(homedir(), '.chat2api') + }, + + isEncryptionAvailable(): boolean { + return getEncryptionKey() !== null + }, + + encryptString(value: string): string { + const key = getEncryptionKey() + if (!key) { + return value + } + + const iv = randomBytes(12) + const cipher = createCipheriv('aes-256-gcm', key, iv) + const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]) + const tag = cipher.getAuthTag() + + return `${ENCRYPTION_PREFIX}${Buffer.concat([iv, tag, encrypted]).toString('base64')}` + }, + + decryptString(value: string): string { + const key = getEncryptionKey() + if (!key || !value.startsWith(ENCRYPTION_PREFIX)) { + return value + } + + const payload = Buffer.from(value.slice(ENCRYPTION_PREFIX.length), 'base64') + const iv = payload.subarray(0, 12) + const tag = payload.subarray(12, 28) + const encrypted = payload.subarray(28) + const decipher = createDecipheriv('aes-256-gcm', key, iv) + decipher.setAuthTag(tag) + + return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8') + }, + + getResourcePath(fileName: string): string { + const candidates = [ + resolve(process.cwd(), fileName), + resolve(process.cwd(), 'resources', fileName), + resolve(__dirname, '..', '..', '..', fileName), + ] + + return candidates.find((candidate) => existsSync(candidate)) || candidates[0] + }, + + async openExternal(url: string): Promise { + console.log(`[Runtime] Open this URL manually: ${url}`) + }, + + notify(): void { + }, +} diff --git a/src/main/runtime/types.ts b/src/main/runtime/types.ts new file mode 100644 index 00000000..0d8d9b4a --- /dev/null +++ b/src/main/runtime/types.ts @@ -0,0 +1,10 @@ +export interface RuntimeAdapter { + kind: 'electron' | 'node' + getDataDir(): string + isEncryptionAvailable(): boolean + encryptString(value: string): string + decryptString(value: string): string + getResourcePath(fileName: string): string + openExternal(url: string): Promise + notify(channel: string, payload: unknown): void +} diff --git a/src/main/store/providers.ts b/src/main/store/providers.ts index e247a557..bbd0b5d1 100644 --- a/src/main/store/providers.ts +++ b/src/main/store/providers.ts @@ -62,9 +62,13 @@ export class ProviderManager { authType: AuthType apiEndpoint: string headers?: Record + chatPath?: string description?: string icon?: string supportedModels?: string[] + modelMappings?: Record + modelsApiEndpoint?: string + modelsApiHeaders?: Record credentialFields?: Array<{ name: string label: string @@ -115,6 +119,9 @@ export class ProviderManager { description: data.description, icon: data.icon, supportedModels: data.supportedModels, + modelMappings: data.modelMappings, + modelsApiEndpoint: data.modelsApiEndpoint, + modelsApiHeaders: data.modelsApiHeaders, credentialFields: data.credentialFields, } diff --git a/src/main/store/storage/electronJsonStore.ts b/src/main/store/storage/electronJsonStore.ts new file mode 100644 index 00000000..51e3f76e --- /dev/null +++ b/src/main/store/storage/electronJsonStore.ts @@ -0,0 +1,9 @@ +import type { JsonStoreOptions } from './types' + +export async function createElectronJsonStore>( + options: JsonStoreOptions +): Promise { + const module = await import('electron-store') + const Store = module.default + return new Store(options) +} diff --git a/src/main/store/storage/nodeJsonStore.ts b/src/main/store/storage/nodeJsonStore.ts new file mode 100644 index 00000000..102eddac --- /dev/null +++ b/src/main/store/storage/nodeJsonStore.ts @@ -0,0 +1,54 @@ +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs' +import { join } from 'path' +import type { JsonStore, JsonStoreOptions } from './types' + +export class NodeJsonStore> implements JsonStore { + private readonly filePath: string + private data: Record + + constructor(options: JsonStoreOptions) { + mkdirSync(options.cwd, { recursive: true }) + this.filePath = join(options.cwd, `${options.name}.json`) + this.data = { ...options.defaults } + + if (existsSync(this.filePath)) { + try { + const parsed = JSON.parse(readFileSync(this.filePath, 'utf8')) + this.data = { ...this.data, ...parsed } + } catch { + renameSync(this.filePath, join(options.cwd, `${options.name}.corrupted.${Date.now()}.json`)) + this.persist() + } + } else { + this.persist() + } + } + + get(key: string): unknown { + return this.data[key] + } + + set(key: string, value: unknown): void { + this.data = { + ...this.data, + [key]: value, + } + this.persist() + } + + delete(key: string): void { + const next = { ...this.data } + delete next[key] + this.data = next + this.persist() + } + + clear(): void { + this.data = {} + this.persist() + } + + private persist(): void { + writeFileSync(this.filePath, `${JSON.stringify(this.data, null, 2)}\n`, 'utf8') + } +} diff --git a/src/main/store/storage/types.ts b/src/main/store/storage/types.ts new file mode 100644 index 00000000..e83f5e62 --- /dev/null +++ b/src/main/store/storage/types.ts @@ -0,0 +1,15 @@ +export interface JsonStoreOptions> { + name: string + cwd: string + defaults: T + encryptionKey?: string +} + +export interface JsonStore> { + get(key: K): T[K] + get(key: string): unknown + set(key: K, value: T[K]): void + set(key: string, value: unknown): void + delete(key: string): void + clear(): void +} diff --git a/src/main/store/store.ts b/src/main/store/store.ts index 44a1532f..7d9c1ae5 100644 --- a/src/main/store/store.ts +++ b/src/main/store/store.ts @@ -1,11 +1,10 @@ /** * Credential Storage Module - Core Storage Implementation - * Uses electron-store for persistent storage - * Uses Electron's safeStorage API for sensitive data encryption + * Uses runtime-specific storage for persistent data + * Uses runtime-specific encryption for sensitive data when available */ -import { app, safeStorage, BrowserWindow } from 'electron' -import { homedir } from 'os' +import type { BrowserWindow } from 'electron' import { join } from 'path' import { StoreSchema, @@ -42,9 +41,9 @@ import { normalizeRequestLogConfig } from '../requestLogs/types' import { normalizeToolCallingConfig } from '../../shared/toolCalling' import { AppLogManager } from '../appLogs/manager' import type { AppLogFilter } from '../appLogs/types' - -// Dynamically import electron-store (ESM module) -let Store: any = null +import { getRuntime } from '../runtime' +import { NodeJsonStore } from './storage/nodeJsonStore' +import { createElectronJsonStore } from './storage/electronJsonStore' /** * Storage Instance Type Definition @@ -90,21 +89,10 @@ class StoreManager { return } - // Dynamically import electron-store (ESM module) - if (!Store) { - const module = await import('electron-store') - Store = module.default - } - const storagePath = this.getStoragePath() try { - this.store = new Store({ - name: 'data', - cwd: storagePath, - defaults: this.getDefaultData(), - encryptionKey: this.getEncryptionKey(), - }) + this.store = await this.createStore(storagePath) await this.initializeAppLogManager(storagePath) await this.initializeRequestLogManager(storagePath) @@ -119,15 +107,11 @@ class StoreManager { // Try to recover by backing up corrupted data and reinitializing try { await this.recoverFromCorruptedData(storagePath) - this.store = new Store({ - name: 'data', - cwd: storagePath, - defaults: this.getDefaultData(), - encryptionKey: this.getEncryptionKey(), - }) + this.store = await this.createStore(storagePath) await this.initializeAppLogManager(storagePath) await this.initializeRequestLogManager(storagePath) this.initializeDefaultModelMappings() + await this.initializeDefaultProviders() this.isInitialized = true this.initializationError = null console.log('[Store] Successfully recovered from corrupted data') @@ -138,6 +122,22 @@ class StoreManager { } } + private async createStore(storagePath: string): Promise { + const runtime = getRuntime() + const options = { + name: 'data', + cwd: storagePath, + defaults: this.getDefaultData() as unknown as Record, + encryptionKey: this.getEncryptionKey(), + } + + if (runtime.kind === 'electron') { + return createElectronJsonStore(options) + } + + return new NodeJsonStore(options) + } + /** * Recover from corrupted data file * Backup the corrupted file and create a new one @@ -166,7 +166,7 @@ class StoreManager { * Storage path: ~/.chat2api/ */ private getStoragePath(): string { - return join(homedir(), '.chat2api') + return getRuntime().getDataDir() } /** @@ -176,16 +176,9 @@ class StoreManager { * so it must be stable across app restarts */ private getEncryptionKey(): string | undefined { - try { - if (safeStorage.isEncryptionAvailable()) { - // Use a fixed key - electron-store will use this to encrypt/decrypt data - // The key itself is not stored in the data file, only used for encryption - return 'chat2api-fixed-encryption-key-v1' - } - } catch (error) { - console.warn('Encryption unavailable, using unencrypted storage:', error) - } - return undefined + return getRuntime().isEncryptionAvailable() + ? 'chat2api-fixed-encryption-key-v1' + : undefined } /** @@ -282,7 +275,15 @@ class StoreManager { */ private async initializeDefaultProviders(): Promise { const providers = this.store?.get('providers') || [] + const accounts = this.store?.get('accounts') || [] const builtinIds = BUILTIN_PROVIDERS.map(p => p.id) + const qwenAiAliasIds = providers + .filter((provider: Provider) => this.isQwenAiProviderAlias(provider)) + .map((provider: Provider) => provider.id) + const hasQwenAiAliasAccounts = accounts.some((account: Account) => { + const providerExists = providers.some((provider: Provider) => account.providerId === provider.id) + return qwenAiAliasIds.includes(account.providerId) || (!providerExists && this.isLikelyQwenAiAccount(account)) + }) const validProviders = providers.filter((p: Provider) => { if (p.type === 'builtin') { @@ -296,7 +297,7 @@ class StoreManager { } let userModelOverridesChanged = false - const updatedProviders = validProviders.map((p: Provider) => { + let updatedProviders = validProviders.map((p: Provider) => { if (p.type === 'builtin') { const builtinConfig = BUILTIN_PROVIDERS.find(bp => bp.id === p.id) if (builtinConfig) { @@ -317,16 +318,96 @@ class StoreManager { headers: builtinConfig.headers, credentialFields: builtinConfig.credentialFields, description: builtinConfig.description, + modelsApiEndpoint: builtinConfig.modelsApiEndpoint, + modelsApiHeaders: builtinConfig.modelsApiHeaders, } } } return p }) + + if (hasQwenAiAliasAccounts && !updatedProviders.some((provider: Provider) => provider.id === 'qwen-ai')) { + const qwenAiBuiltin = BUILTIN_PROVIDERS.find(provider => provider.id === 'qwen-ai') + if (qwenAiBuiltin) { + const now = Date.now() + updatedProviders = [ + ...updatedProviders, + { + ...qwenAiBuiltin, + createdAt: now, + updatedAt: now, + }, + ] + } + } if (userModelOverridesChanged) { this.store?.set('userModelOverrides', userModelOverrides) } this.store?.set('providers', updatedProviders) + this.migrateQwenAiProviderAliases(providers, updatedProviders) + } + + private isQwenAiProviderAlias(provider: Provider): boolean { + if (provider.type !== 'builtin' || provider.id === 'qwen-ai') { + return false + } + + const endpoint = provider.apiEndpoint || '' + const description = provider.description || '' + + return provider.name === 'Qwen AI (International)' + || endpoint.includes('chat.qwen.ai') + || description.includes('chat.qwen.ai') + } + + private isLikelyQwenAiAccount(account: Account): boolean { + const name = (account.name || '').toLowerCase() + const credentials = account.credentials || {} + const hasBrowserImportCredentials = Boolean( + credentials.token && Object.prototype.hasOwnProperty.call(credentials, 'cookies'), + ) + + return name.includes('qwen ai') + || name.includes('qwen-ai') + || name.includes('chat.qwen.ai') + || (name.includes('qwen') && hasBrowserImportCredentials) + } + + private migrateQwenAiProviderAliases(originalProviders: Provider[], currentProviders: Provider[]): void { + const accounts = this.store?.get('accounts') || [] + if (accounts.length === 0) { + return + } + + const qwenAiAliasIds = new Set( + originalProviders + .filter((provider: Provider) => this.isQwenAiProviderAlias(provider)) + .map((provider: Provider) => provider.id), + ) + const now = Date.now() + let changed = false + + const migratedAccounts = accounts.map((account: Account) => { + const providerExists = currentProviders.some((provider: Provider) => account.providerId === provider.id) + const shouldMigrate = account.providerId !== 'qwen-ai' + && (qwenAiAliasIds.has(account.providerId) || (!providerExists && this.isLikelyQwenAiAccount(account))) + + if (!shouldMigrate) { + return account + } + + changed = true + return { + ...account, + providerId: 'qwen-ai', + updatedAt: now, + } + }) + + if (changed) { + this.store?.set('accounts', migratedAccounts) + } } /** @@ -334,7 +415,7 @@ class StoreManager { */ ensureProviderExists(providerId: string): void { this.ensureInitialized() - const providers = this.store!.get('providers') || [] + const providers = this.store!.get('providers') as Provider[] || [] const exists = providers.some((p: Provider) => p.id === providerId) if (!exists) { @@ -355,9 +436,10 @@ class StoreManager { description: builtinConfig.description, supportedModels: builtinConfig.supportedModels, modelMappings: builtinConfig.modelMappings, + modelsApiEndpoint: builtinConfig.modelsApiEndpoint, + modelsApiHeaders: builtinConfig.modelsApiHeaders, } - providers.push(newProvider) - this.store!.set('providers', providers) + this.store!.set('providers', [...providers, newProvider]) console.log('[Store] Created missing provider:', providerId) } } @@ -411,18 +493,9 @@ class StoreManager { */ encryptData(data: string): string { try { - console.log('[Store] encryptData input length:', data.length, 'content:', data.substring(0, 20) + '...') - if (safeStorage.isEncryptionAvailable()) { - // Create new Buffer to store encryption result - const encrypted = Buffer.from(safeStorage.encryptString(data)) - const result = encrypted.toString('base64') - console.log('[Store] encryptData output length:', result.length, 'content:', result.substring(0, 20) + '...') - // Verify encryption is correct - const decrypted = safeStorage.decryptString(encrypted) - console.log('[Store] encryptData verify decryption:', decrypted.substring(0, 20) + '...', 'match:', decrypted === data) - return result - } else { - console.log('[Store] Encryption unavailable, returning original data') + const runtime = getRuntime() + if (runtime.isEncryptionAvailable()) { + return runtime.encryptString(data) } } catch (error) { console.error('Failed to encrypt data:', error) @@ -437,9 +510,9 @@ class StoreManager { */ decryptData(encryptedData: string): string { try { - if (safeStorage.isEncryptionAvailable()) { - const buffer = Buffer.from(encryptedData, 'base64') - return safeStorage.decryptString(buffer) + const runtime = getRuntime() + if (runtime.isEncryptionAvailable()) { + return runtime.decryptString(encryptedData) } } catch (error) { console.error('Failed to decrypt data:', error) @@ -502,8 +575,7 @@ class StoreManager { addProvider(provider: Provider): void { this.ensureInitialized() const providers = this.store!.get('providers') as Provider[] || [] - providers.push(provider) - this.store!.set('providers', providers) + this.store!.set('providers', [...providers, provider]) } /** @@ -662,13 +734,6 @@ class StoreManager { return null } - console.log('[Store] Update account:', { - id, - updatesCredentials: updates.credentials, - oldCredentials: accounts[index].credentials, - oldCredentialsDecrypted: this.decryptCredentials(accounts[index].credentials), - }) - const updatedAccount: Account = { ...accounts[index], ...updates, @@ -677,22 +742,11 @@ class StoreManager { if (updates.credentials) { updatedAccount.credentials = this.encryptCredentials(updates.credentials) - console.log('[Store] Encrypted credentials:', updatedAccount.credentials) - console.log('[Store] Old credentials:', accounts[index].credentials) - console.log('[Store] Credentials match:', JSON.stringify(updatedAccount.credentials) === JSON.stringify(accounts[index].credentials)) } accounts[index] = updatedAccount this.store!.set('accounts', accounts) - - // Verify save was successful - const savedAccounts = this.store!.get('accounts') as Account[] - const savedAccount = savedAccounts.find(a => a.id === id) - console.log('[Store] Verify after save:', { - id, - savedCredentials: savedAccount?.credentials, - }) - + return { ...updatedAccount, credentials: updates.credentials || this.decryptCredentials(accounts[index].credentials), @@ -1665,6 +1719,8 @@ class StoreManager { headers: builtinConfig.headers, credentialFields: builtinConfig.credentialFields, description: builtinConfig.description, + modelsApiEndpoint: builtinConfig.modelsApiEndpoint, + modelsApiHeaders: builtinConfig.modelsApiHeaders, updatedAt: Date.now(), } }) diff --git a/src/main/store/types.ts b/src/main/store/types.ts index 0bcc41b5..d4412442 100644 --- a/src/main/store/types.ts +++ b/src/main/store/types.ts @@ -150,6 +150,10 @@ export interface Provider { supportedModels?: string[] /** Model name mapping */ modelMappings?: Record + /** Models list API endpoint for dynamic model fetching */ + modelsApiEndpoint?: string + /** Additional headers for models API request */ + modelsApiHeaders?: Record /** Provider status */ status?: ProviderStatus /** Last status check time */ diff --git a/src/main/types/ali-oss.d.ts b/src/main/types/ali-oss.d.ts index 1e28c812..5f4ad4de 100644 --- a/src/main/types/ali-oss.d.ts +++ b/src/main/types/ali-oss.d.ts @@ -4,7 +4,9 @@ declare module 'ali-oss' { accessKeySecret: string bucket: string endpoint: string + region?: string stsToken?: string + authorizationV4?: boolean } interface PutResult { @@ -15,7 +17,7 @@ declare module 'ali-oss' { class OSS { constructor(options: OSSOptions) - put(name: string, data: Buffer | string): Promise + put(name: string, data: Buffer | string, options?: any): Promise } export default OSS diff --git a/src/preload/index.ts b/src/preload/index.ts index 982dffde..ada36649 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -66,11 +66,17 @@ const providersAPI = { add: (data: { name: string + id?: string + type?: 'builtin' | 'custom' authType: AuthType apiEndpoint: string + chatPath?: string headers?: Record description?: string supportedModels?: string[] + modelMappings?: Record + modelsApiEndpoint?: string + modelsApiHeaders?: Record credentialFields?: CredentialField[] }): Promise => ipcRenderer.invoke(IpcChannels.PROVIDERS_ADD, data), diff --git a/src/renderer/admin.html b/src/renderer/admin.html new file mode 100644 index 00000000..269638c9 --- /dev/null +++ b/src/renderer/admin.html @@ -0,0 +1,13 @@ + + + + + + + Chat2API Admin + + +
+ + + diff --git a/src/renderer/src/components/dashboard/QuickActions.tsx b/src/renderer/src/components/dashboard/QuickActions.tsx index 66bbabca..63cf3434 100644 --- a/src/renderer/src/components/dashboard/QuickActions.tsx +++ b/src/renderer/src/components/dashboard/QuickActions.tsx @@ -7,6 +7,7 @@ import { Play, Square, Plus, FileText, Zap, Loader2, Wrench } from 'lucide-react export interface QuickActionsProps { proxyRunning: boolean + proxyManagedExternally?: boolean onToggleProxy: () => void onAddAccount: () => void onToolCalling: () => void @@ -17,6 +18,7 @@ export interface QuickActionsProps { export function QuickActions({ proxyRunning, + proxyManagedExternally = false, onToggleProxy, onAddAccount, onToolCalling, @@ -46,17 +48,21 @@ export function QuickActions({ )} variant={proxyRunning ? 'secondary' : 'default'} onClick={onToggleProxy} - disabled={isLoading} + disabled={isLoading || (proxyManagedExternally && proxyRunning)} > {isLoading ? ( - ) : proxyRunning ? ( + ) : proxyRunning && !proxyManagedExternally ? ( + ) : proxyRunning ? ( + ) : ( )} {isLoading ? t('common.loading') + : proxyManagedExternally && proxyRunning + ? t('quickActions.proxyManagedExternally') : proxyRunning ? t('quickActions.stopProxy') : t('quickActions.startProxy')} diff --git a/src/renderer/src/components/layout/Header.tsx b/src/renderer/src/components/layout/Header.tsx index f048fbce..f6fc5b28 100644 --- a/src/renderer/src/components/layout/Header.tsx +++ b/src/renderer/src/components/layout/Header.tsx @@ -14,6 +14,7 @@ export function Header() { const [proxyLoading, setProxyLoading] = useState(false) const [port, setPort] = useState(8080) const [host, setHost] = useState('127.0.0.1') + const isDockerWebAdmin = window.__CHAT2API_WEB_ADMIN__ === true useEffect(() => { if (!window.electronAPI?.proxy?.onStatusChanged) return @@ -52,6 +53,7 @@ export function Header() { setProxyLoading(true) try { if (proxyEnabled) { + if (isDockerWebAdmin) return await window.electronAPI.proxy.stop() setProxyEnabled(false) } else { @@ -137,7 +139,7 @@ export function Header() { + + + {browserImportScript && ( +
+ +
Fast
+ + + + + + + + + + + + + + + + + diff --git a/.qwen-main.js b/.qwen-main.js new file mode 100644 index 00000000..a4d23c42 --- /dev/null +++ b/.qwen-main.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["js/react-vendor.js","js/index28.js","js/react-dom-vendor.js","js/dayjs-vendor.js","css/index14.css","js/vite-helpers.js","css/monaco-vendor.css","js/core.js","js/index12.js","js/index13.js","js/wardley-L42UT6IY.js","js/dompurify-vendor.js","js/es-toolkit-vendor.js","js/marked-vendor.js","css/wardley-L42UT6IY.css","js/mhchem.js","js/katex.js","js/index53.js","css/index40.css","js/index47.js","js/index45.js","js/community.js","js/useSticky.js","js/useCommunityLike.js","js/useLatest.js","css/community.css","css/index34.css","css/index31.css","js/index44.js","css/index29.css","js/PPTViewer.js","css/PPTViewer.css","js/PDFViewer.js","css/PDFViewer.css","js/index29.js","js/index15.js","js/index.js","js/index2.js","js/index.esm.js","js/index3.js","js/index50.js","css/index35.css","js/index38.js","css/index23.css","js/index48.js","js/Radio.js","js/index6.js","js/index8.js","js/index16.js","css/Radio.css","css/index.css","css/index2.css","css/index3.css","css/index32.css","js/index30.js","css/index15.css","js/index31.js","css/index16.css","js/index4.js","js/index5.js","js/index7.js","js/index17.js","css/index4.css","js/index32.js","css/index17.css","js/index33.js","css/index18.css","js/index9.js","js/index.h5.js","css/index5.css","js/index34.js","css/index19.css","js/index41.js","css/index27.css","js/index36.js","js/languages.js","js/index18.js","js/useAudioSpeaker.hook.js","css/index6.css","css/index21.css","js/index51.js","css/index38.css","js/index19.js","css/index7.css","js/index20.js","js/index21.js","css/index9.css","css/index8.css","js/index22.js","js/useDynamicHeight.js","css/index10.css","js/index39.js","css/index24.css","js/index46.js","css/index30.css","js/index37.js","js/index.type.js","js/index25.js","css/index37.css","css/index22.css","js/index23.js","css/index11.css","js/index35.js","css/index20.css","js/index42.js","js/index43.js","css/index36.css","css/index28.css","js/index40.js","js/index27.js","css/index26.css","css/index25.css","js/ModelsContainer.js","css/ModelsContainer.css","js/AccountContainer.js","css/AccountContainer.css","js/index10.js","js/index24.js","css/index12.css","js/index26.js","css/index13.css","js/index49.js","css/index33.css","js/index11.js","js/index52.js","css/index39.css"])))=>i.map(i=>d[i]); +var e,t,n,s,i,a,o,r,l,c,d,u=Object.defineProperty,h=Object.defineProperties,m=Object.getOwnPropertyDescriptors,p=Object.getOwnPropertySymbols,g=Object.getPrototypeOf,f=Object.prototype.hasOwnProperty,v=Object.prototype.propertyIsEnumerable,y=Reflect.get,b=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),x=e=>{throw TypeError(e)},w=Math.pow,_=(e,t,n)=>t in e?u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,C=(e,t)=>{for(var n in t||(t={}))f.call(t,n)&&_(e,n,t[n]);if(p)for(var n of p(t))v.call(t,n)&&_(e,n,t[n]);return e},S=(e,t)=>h(e,m(t)),k=(e,t)=>{var n={};for(var s in e)f.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&p)for(var s of p(e))t.indexOf(s)<0&&v.call(e,s)&&(n[s]=e[s]);return n},j=(e,t,n)=>_(e,"symbol"!=typeof t?t+"":t,n),T=(e,t,n)=>t.has(e)||x("Cannot "+n),E=(e,t,n)=>(T(e,t,"read from private field"),n?n.call(e):t.get(e)),N=(e,t,n)=>t.has(e)?x("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),I=(e,t,n,s)=>(T(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n),A=(e,t,n)=>new Promise((s,i)=>{var a=e=>{try{r(n.next(e))}catch(t){i(t)}},o=e=>{try{r(n.throw(e))}catch(t){i(t)}},r=e=>e.done?s(e.value):Promise.resolve(e.value).then(a,o);r((n=n.apply(e,t)).next())}),M=function(e,t){this[0]=e,this[1]=t},R=(e,t,n)=>{var s,i=(e,t,s,a)=>{try{var o=n[e](t),r=(t=o.value)instanceof M,l=o.done;Promise.resolve(r?t[0]:t).then(n=>r?i("return"===e?e:"next",t[1]?{done:n.done,value:n.value}:n,s,a):s({value:n,done:l})).catch(e=>i("throw",e,s,a))}catch(c){a(c)}},a=(e,t,n,a)=>o[e]=o=>(t=new Promise((t,n,a)=>(a=()=>i(e,o,t,n),s?s.then(a):a())),a=()=>s===n&&(s=0),s=n=t.then(a,a),t),o={};return n=n.apply(e,t),o[b("asyncIterator")]=()=>o,a("next"),a("throw"),a("return"),o},P=e=>{var t,n=e[b("asyncIterator")],s=!1,i={};return null==n?(n=e[b("iterator")](),t=e=>i[e]=t=>n[e](t)):(n=n.call(e),t=e=>i[e]=t=>{if(s){if(s=!1,"throw"===e)throw t;return t}return s=!0,{done:!1,value:new M(new Promise(s=>{var i=n[e](t);i instanceof Object||x("Object expected"),s(i)}),1)}}),i[b("iterator")]=()=>i,t("next"),"throw"in n?t("throw"):i.throw=e=>{throw e},"return"in n&&t("return"),i},L=(e,t,n)=>(t=e[b("asyncIterator")])?t.call(e):(e=e[b("iterator")](),t={},(n=(n,s)=>(s=e[n])&&(t[n]=t=>new Promise((n,i,a)=>(t=s.call(e,t),a=t.done,Promise.resolve(t.value).then(e=>n({value:e,done:a}),i)))))("next"),n("return"),t);import{b as O,a as D,j as F,d as q,g as U,R as H}from"./react-vendor.js";import{R as B,b as z,c as G,r as $}from"./react-dom-vendor.js";import{i as W,j as V,d as Q,k as K,D as Y,h as J,l as X,n as Z,o as ee,I as te,p as ne,q as se,F as ie,r as ae,t as oe,u as re,P as le,v as ce,w as de,x as ue,y as he,e as me,g as pe,z as ge}from"./antd-vendor.js";import{c as fe,g as ve,u as ye,T as be,i as xe,r as we,B as _e,a as Ce}from"./i18next-vendor.js";import{_ as Se}from"./vite-helpers.js";import{O as ke,F as je,x as Te,P as Ee,d as Ne,Q as Ie,I as Ae,y as Me,R as Re,S as Pe,G as Le,T as Oe,U as De}from"./lodash-vendor.js";import{v as Fe}from"./qwen-chat-omni-sdk-vendor.js";import{d as qe}from"./dayjs-vendor.js";import{u as Ue,b as He,O as Be,c as ze,a as Ge,R as $e,d as We,N as Ve,B as Qe}from"./router-vendor.js";import{u as Ke,a as Ye,D as Je,H as Xe}from"./dnd-vendor.js";import{p as Ze}from"./dompurify-vendor.js";import{B as et,L as tt}from"./marked-vendor.js";function nt(e,t){for(var n=0;ns[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}let st=null;const it=()=>(st||(st=fe()),st),at="",ot="/api/v1",rt="/api/v2",lt="DPO_qwenlm-intl@service.alibaba.com";var ct=(e=>(e.SIDEBAR_NEW_CHAT_BUTTON="sidebar-new-chat-button",e.CHAT_INPUT="chat-input",e.COPY_CODE_BUTTON="copy-code-button",e.COPY_RESPONSE_BUTTON="copy-response-button",e.SIDEBAR_TOGGLE_BUTTON="sidebar-toggle-button",e.DELETE_CHAT_BUTTON="delete-chat-button",e.SETTING_TOGGLE_BUTTON="setting-toggle-button",e.SHOW_SHORTCUTS_BUTTON="show-shortcuts-button",e))(ct||{});const dt="DPO_qwenlm-intl@service.alibaba.com",ut="manually_close_sidebar";var ht=(e=>(e.IOS="ios",e.ANDROID="android",e.WEB="web",e.DESKTOP="desktop",e.UNKNOWN="unknown",e))(ht||{}),mt=(e=>(e.RECCOMMAND="recommendation",e.CHAT="chat",e.RETRY="retry",e.EDIT="edit",e.ASK="ask",e.EXPLAIN="explain",e.TRANSLATE="translate",e))(mt||{}),pt=(e=>(e.SETAPP="setapp",e.DESKTOP="desktop",e))(pt||{}),gt=(e=>(e.CODE_INTERPRETER="code_interpreter_http",e.WEB_SEARCH="web_search",e.BIO="bio",e))(gt||{}),ft=(e=>(e.TIMEOUT="timeout",e.NETWORK="network",e.VALIDATION="validation",e.UNKNOWN="unknown",e))(ft||{});class vt extends Error{constructor(e,t="unknown",n="error",s,i){super(e),j(this,"type"),j(this,"messageId"),j(this,"details"),j(this,"priority"),this.name="ChatError",this.type=t,this.messageId=s,this.details=i,this.priority=n}}var yt=(e=>(e.DeepResearch="deep_research",e.DeepThinking="deep_thinking",e.Artifacts="artifacts",e.WebSearch="search",e.ImageGeneration="t2i",e.VideoGeneration="t2v",e.Image2Video="i2v",e.Txt2Txt="t2t",e.WebDev="web_dev",e.TRANSLATE="translate",e.Thinking="thinking",e.Mcp="mcp",e.ImageEdit="image_edit",e.DeepResearchWebDev="deep_research_webdev",e.Podcast="aipodcast",e.TRAVEL_FEEDBACK="travel_feedback",e.Travel="travel",e.TRAVEL_RESEARCH="travel_research",e.LEARN="learn",e.INTERRUPT="interrupt",e.Slides="slides",e))(yt||{}),bt=(e=>(e.OmniAudio="omni_audio",e.OmniVideo="omni_video",e))(bt||{}),xt=(e=>(e.PdfViewer="pdf_viewer",e.DeepResearch="deep_research",e.Artifacts="artifacts",e.Overview="overview",e.Settings="settings",e.Feedback="feedback",e.None="none",e.DeepResearchLinkSource="DeepResearchLinkSource",e.WebDev="web_dev",e.WebSearch="search",e.Thinking="thinking",e.ThinkingAndSearch="thinking_and_search",e.ImageReason="imageReason",e.DeepResearchDetail="deep_research_detail",e.ImageGeneration="t2i",e.VideoGeneration="t2v",e.ThinkingAndSources="thinking_and_sources",e.Slides="slides",e))(xt||{}),wt=(e=>(e.THINK="think",e.TOOL="tool",e.ANSWER="answer",e.DEEPTHINKING="DeepThinking",e.RESEARCHPLANNING="ResearchPlanning",e.PdfMdGen="PdfMdGen",e.ReportGeneration="ReportGeneration",e.KEEPALIVE="KeepAlive",e.LOCAL_TOOL="local_tool",e.IMAGE_GEN_THINK="image_gen_think",e.IMAGE_GEN_WEB_SEARCH="image_gen_websearch",e.IMAGE_GEN="image_gen",e.IMAGE_EDIT="image_edit",e.IMAGE_GEN_TOOL="image_gen_tool",e.IMAGE_EDIT_TOOL="image_edit_tool",e.WEB_SEARCH="web_search",e.WEB_SEARCH_IMAGE="web_search_image",e.IMAGE_SEARCH="image_search",e.IMAGE="image",e.IMAGE_ZOOM_IN_TOOL="image_zoom_in_tool",e.CODE_INTERPRETER="code_interpreter",e.THINKING_SUMMARY="thinking_summary",e.WEB_EXTRACTOR="web_extractor",e.HISTORY_RETRIEVER="history_retriever",e.BIO="bio",e.INTERRUPT="interrupt",e.INTERRUPTRECEIVED="InterruptReceived",e.RESEARCHNOTICE="ResearchNotice",e.SLIDES="slides",e.FINISHED="finished",e))(wt||{}),_t=(e=>(e.TYPING="typing",e.FINISHED="finished",e.ERROR="error",e.PAUSE="pause",e))(_t||{}),Ct=(e=>(e.text="text",e.url="url",e))(Ct||{}),St=(e=>(e.SUCCESS="success",e.FAIL="failed",e.OUT_OF_LIMIT="out_of_limit",e.PARSING="parsing",e))(St||{});const kt=131072,jt={"1:1":"1:1","4:3":"4:3","3:4":"3:4","16:9":"16:9","9:16":"9:16"};var Tt=(e=>(e.DeepResearch="deep_research",e.Artifacts="artifacts",e.WebSearch="search",e.ImageGeneration="t2i",e.VideoGeneration="t2v",e.Image2Video="i2v",e.Txt2Txt="t2t",e.Travel="travel",e.Slides="slides",e.LEARN="learn",e.MCP="mcp",e))(Tt||{});const Et={deep_research:["deep_thinking","deep_research","t2t"],artifacts:["artifacts","web_dev"],search:["search"],t2i:["t2i"],t2v:["t2v"],i2v:["i2v"],t2t:["t2t"],travel:["travel_feedback","travel_research"],slides:["slides"],learn:["learn"],mcp:["t2t"]},Nt={deep_research:{_default:"deep_thinking",deep_thinking:"deep_research",deep_research:"deep_thinking"},travel:{_default:"travel_feedback",travel_feedback:"travel_research",travel_research:"travel_feedback"}};var It=(e=>(e.ReportGeneration="ReportGeneration",e.ResearchPlanning="ResearchPlanning",e.PdfMdGen="PdfMdGen",e))(It||{});const At=[{title:"Model issue",content:[{label:"Inconsistent with the facts",value:"Inconsistent with the facts"},{label:"Inconsistent with the instruction",value:"Inconsistent with the instruction"},{label:"Offensive/Unsafe",value:"Offensive/Unsafe"},{label:"Language error",value:"Language error"},{label:"Unreasonable format",value:"Unreasonable format"},{label:"The content is mediocre/boring",value:"The content is mediocre/boring"},{label:"Output lagging",value:"Output lagging"},{label:"Other",value:"Other"}]},{title:"UI issue",content:[{label:"Laggy UI",value:"Laggy UI"},{label:"Poor readability",value:"Poor readability"},{label:"Hard-to-find features",value:"Hard-to-find features"},{label:"Inconsistent interactions",value:"Inconsistent interactions"},{label:"Missing guidance",value:"Missing guidance"}]}],Mt="Cherry",Rt=[xt.PdfViewer,xt.DeepResearchDetail,xt.DeepResearch],Pt=e=>[yt.DeepResearch,yt.TRAVEL_RESEARCH].includes(e),Lt="chat-messages-scroll-container",Ot="NATIVE_NEW_BRANCH",Dt=["text/plain"],Ft=["image/gif","image/webp","image/jpeg","image/png","image/bmp","image/x-bmp","image/x-ms-bmp","image/icns","image/jp2","image/sgi","image/tiff","image/x-icon"],qt=["video/mp4","video/avi","video/x-ms-wmv","video/x-flv","video/x-matroska","video/quicktime"],Ut=["audio/amr","audio/wav","audio/x-wav","audio/aac","audio/mpeg","audio/x-m4a"],Ht=["text/x-java-source","text/x-kotlin","text/x-scala","text/x-groovy","application/javascript","text/javascript","application/typescript","text/jsx","text/tsx","application/javascript","text/x-vue","text/x-python","application/x-ipynb+json","text/html","text/css","text/x-sass","text/x-less","text/x-stylus","image/svg+xml","application/x-shellscript","text/x-powershell","application/x-msdownload","text/x-dockerfile-config","text/x-go","text/x-rust","text/x-swift","application/x-httpd-php","application/x-ruby","text/x-csharp","text/x-vb","text/x-fsharp","application/sql","text/x-lua","text/x-r","text/x-perl","application/x-tcl","text/x-awk","application/x-fish-script","application/xml","application/json","application/x-yaml","application/toml","text/x-groovy","text/x-kotlin","text/x-markdown","text/x-matlab","text/x-julia","text/x-sas","text/x-gdscript","text/x-glsl","text/x-hlsl","text/x-asm","text/x-verilog","text/x-vhdl","application/x-ipynb+json","text/x-quarto","text/markdown","text/x-protobuf","text/x-thrift","application/graphql","application/wasm","application/json","text/x-c","text/x-c++src","text/x-c++hdr","text/x-arduino","text/x-csrc","application/x-tex","text/x-tex","application/x-latex"],Bt=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","text/csv","text/comma-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","text/markdown","text/plain",...Ht],zt=["txt","TXT"],Gt=["gif","webp","jpg","jpeg","png","bmp","icns","jp2","sgi","tif","tiff","dib","ico","jfif","j2c","j2k","jpc","jpf","jpx","apng","bw","rgb","rgba"],$t=["mp4","avi","wmv","flv","mkv","mov"],Wt=["amr","wav","aac","mp3","m4a"],Vt=["c","h","cc","cxx","hpp","hh","hxx","ino","java","kt","kts","scala","groovy","js","ts","jsx","tsx","vue","mjs","cjs","py","pyi","ipynb","html","htm","css","scss","sass","less","styl","svg","sh","bash","zsh","ps1","bat","cmd","dockerfile","containerfile","go","rs","swift","php","rb","cs","vb","fs","csproj","sln","sql","lua","r","pl","tcl","awk","fish","xml","json","jsonc","yaml","yml","toml","ini","env","gradle","kts","pom","mk","cmake","lock","rmd","m","jl","sas","asm","s","v","sv","vhd","vhdl","gd","shader","glsl","hlsl","proto","thrift","graphql","gql","wasm","asmdef","qmd","cpp","lock","smali","tex","ofd"],Qt=["pdf","doc","docx","csv","xlsx","xls","md",...Vt],Kt=1/0,Yt="qwen2.5-omni-7b",Jt=1/0;var Xt=(e=>(e.DEFAULT="default",e.IMAGE="vision",e.VIDEO="video",e.AUDIO="audio",e.DOC="document",e.CAMERA="camera",e))(Xt||{}),Zt=(e=>(e.FILE="file",e.IMAGE="image",e.VIDEO="video",e.AUDIO="audio",e))(Zt||{});const en={default:{max_count:Kt,max_size:20,accept_extension:zt,accept_type:Dt},document:{max_count:5,max_size:20,accept_extension:Qt,accept_type:Bt},vision:{max_count:5,max_size:20,accept_extension:Gt,accept_type:Ft},video:{max_count:1,max_size:500,accept_extension:$t,accept_type:qt,max_duration:600},audio:{max_count:1,max_size:100,accept_extension:Wt,accept_type:Ut,max_duration:180}},tn=C({"application/epub+zip":{icon:"iconepub1",bg:"#9BC751"},"application/pdf":{icon:"iconpdf1",bg:"#DE5A5E"},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{icon:"iconppt1",bg:"#E4785F"},"text/plain":{icon:"icontxt1",bg:"#61B6ED"},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{icon:"iconexcel1",bg:"#6BBF6D"},others:{icon:"iconothers1",bg:"#A0A3BA"},"text/html":{icon:"iconhtml1",bg:"#F1B94A"},"text/htm":{icon:"iconhtml1",bg:"#F1B94A"},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{icon:"iconword1",bg:"#4B8EF7"},"text/md":{icon:"iconmd1",bg:"#7BC8C3"},"text/markdown":{icon:"iconmd1",bg:"#7BC8C3"},"video/mp4":{icon:"iconvideo1",bg:"#407FFD"},"video/avi":{icon:"iconvideo1",bg:"#407FFD"},"video/quicktime":{icon:"iconvideo1",bg:"#407FFD"},"video/x-flv":{icon:"iconvideo1",bg:"#407FFD"},"video/x-matroska":{icon:"iconvideo1",bg:"#407FFD"},"video/x-ms-wmv":{icon:"iconvideo1",bg:"#407FFD"}},[...Ut].reduce((e,t)=>(e[t]={icon:"iconaudio",bg:"#FFAB19"},e),{})),nn=["internal-qwenlm.alibaba-inc.com","qwenlm.io","chat.qwenlm.ai","qwenlm.ai","qwen.ai","chat.qwen.ai","qwenchat.com"].some(e=>location.host===e)?"prod":"pre",sn="/api/v2",an="prod"===nn?"https://qwenlm.io/":"https://pre-qwenlm-box.alibaba-inc.com/",on="memory",rn="chat",ln="system_notification";yt.ImageEdit,yt.ImageEdit,yt.LEARN,yt.LEARN,yt.DeepResearch,yt.ImageGeneration,yt.ImageGeneration,yt.VideoGeneration,yt.Travel,yt.Artifacts,yt.Artifacts,yt.Artifacts,yt.WebDev,yt.ImageEdit,yt.ImageEdit,yt.LEARN,yt.LEARN,yt.DeepResearch,yt.ImageGeneration,yt.ImageGeneration,yt.VideoGeneration,yt.Artifacts,yt.WebDev,yt.ImageEdit,yt.ImageEdit,yt.ImageGeneration,yt.ImageGeneration,yt.VideoGeneration,yt.Artifacts,yt.Artifacts,yt.Artifacts,yt.WebDev,yt.Artifacts,yt.Artifacts,yt.Travel,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.VideoGeneration,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt,yt.Txt2Txt;const cn=["model","thinking","search","t2v","t2i","deep_research_deep_research","artifacts_deploy_artifacts","artifacts_deploy_web_dev","artifacts_deploy_deep_research","audio_chat_AudioOnly","audio_chat_AudioAndVideo","deep_research_aipodcast","code","image_edit","deep_research_deep_research_advanced"],dn=[{key:"upload",icon:"icon-line-upload-03",value:"Upload attachment"},{key:yt.DeepResearch,icon:"icon-line-deepresearch-02",value:"Deep Research",chatType:yt.DeepResearch,subChatType:yt.DeepResearch},{key:yt.ImageGeneration,icon:"icon-line-image-generation-01",value:"Create image",chatType:yt.ImageGeneration,subChatType:yt.ImageGeneration},{key:yt.VideoGeneration,icon:"icon-line-video-generation-01",value:"Create video",chatType:yt.VideoGeneration,subChatType:yt.VideoGeneration},{key:yt.WebDev,icon:"icon-a-line-webdev",value:"Web Dev",chatType:yt.Artifacts,subChatType:yt.WebDev},{key:"mcp",icon:"icon-line-star-02",value:"MCP"},{key:yt.Slides,icon:"icon-line-presentation-01",value:"Slides",chatType:yt.Slides,subChatType:yt.Slides},{key:yt.WebSearch,icon:"icon-line-globe-01",value:"Web search",chatType:yt.WebSearch,subChatType:yt.WebSearch},{key:yt.Artifacts,icon:"icon-a-line-package-0211",value:"Artifacts",chatType:yt.Artifacts,subChatType:yt.Artifacts},{key:yt.LEARN,icon:"icon-line-homework",value:"Learn",chatType:yt.LEARN,subChatType:yt.LEARN},{key:yt.Travel,icon:"icon-line-Travel",value:"Travel Planner",chatType:yt.Travel,subChatType:yt.Travel}],un="NATIVE_NEW_PROJECT_ID",hn=["😀","😊","🥰","🥲","🤯","😎","🤓","🏅","⚽","🏀","🌍","🏖️","🚘","✈️","✏️","🎨","📝","📚","🔖","🥗","🍝","💖","🌈","☘️","💰","💻","🎧","🗓️","⚫","🔴","🟠","🟡","🟢","🔵","🟣"],mn=["😀","😊","🥰","😥","🤯","😎","🤓","🏅","⚽","🏀","🌍","🏖️","🚘","✈️","✏️","🎨","📝","📚","🔖","🥗","🍝","💖","🌈","☘️","💰","💻","🎧","🗓️","⚫","🔴","🟠","🟡","🟢","🔵","🟣"],pn={"😀":"😀","😊":"😊","🥰":"🥰","😥":navigator.userAgent.includes("Windows")?"😥":"🥲","🥲":navigator.userAgent.includes("Windows")?"😥":"🥲","🤯":"🤯","😎":"😎","🤓":"🤓","🏅":"🏅","⚽":"⚽","🏀":"🏀","🌍":"🌍","🏖️":"🏖️","🚘":"🚘","✈️":"✈️","✏️":"✏️","🎨":"🎨","📝":"📝","📚":"📚","🔖":"🔖","🥗":"🥗","🍝":"🍝","💖":"💖","🌈":"🌈","☘️":"☘️","💰":"💰","💻":"💻","🎧":"🎧","🗓️":"🗓️","⚫":"⚫","🔴":"🔴","🟠":"🟠","🟡":"🟡","🟢":"🟢","🔵":"🔵","🟣":"🟣"},gn="qwen-thinking_mode",fn=e=>{const t=new Date,n=new Date(1e3*e),s=(t.getTime()-n.getTime())/864e5,i=t.getDate(),a=t.getMonth(),o=t.getFullYear(),r=n.getDate(),l=n.getMonth(),c=n.getFullYear();return o===c&&a===l&&i===r?"Today":o===c&&a===l&&i-r===1?"Yesterday":s<=7?"Previous 7 days":s<=30?"Previous 30 days":o===c?n.toLocaleString("default",{month:"long"}):n.getFullYear().toString()},vn=(e="",t="subscript")=>{let n=e;switch(t){case"subscript":n=e.replace(/\[\[\d+\]\]/g,"");break;case"numberAndEntry":n=e.replace(/(\d+)[\r\n]+/g,"")}return n},yn=(e,t,n)=>{const s=e.map(e=>e.code);if(!t||0===t.length)return n;const i=t[0],a=s.find(e=>e===i);return a||n},bn=(e,t)=>{const n=C({},e);return Object.keys(t).forEach(e=>{const s=t[e],i=n[e];s&&"object"==typeof s&&!Array.isArray(s)&&i&&"object"==typeof i&&!Array.isArray(i)?n[e]=bn(i,s):n[e]=s}),n};const xn=e=>{let t;const n=new Set,s=(e,s)=>{const i="function"==typeof e?e(t):e;if(!Object.is(i,t)){const e=t;t=(null!=s?s:"object"!=typeof i||null===i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:s,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(s,i,a);return a},wn=e=>e?xn(e):xn,_n=e=>e;const Cn=e=>{const t=wn(e),n=e=>function(e,t=_n){const n=O.useSyncExternalStore(e.subscribe,O.useCallback(()=>t(e.getState()),[e,t]),O.useCallback(()=>t(e.getInitialState()),[e,t]));return O.useDebugValue(n),n}(t,e);return Object.assign(n,t),n},Sn=e=>Cn;var kn=Symbol.for("immer-nothing"),jn=Symbol.for("immer-draftable"),Tn=Symbol.for("immer-state");function En(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Nn=Object.getPrototypeOf;function In(e){return!!e&&!!e[Tn]}function An(e){var t;return!!e&&(Pn(e)||Array.isArray(e)||!!e[jn]||!!(null==(t=e.constructor)?void 0:t[jn])||qn(e)||Un(e))}var Mn=Object.prototype.constructor.toString(),Rn=new WeakMap;function Pn(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);if(null===t||t===Object.prototype)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(n===Object)return!0;if("function"!=typeof n)return!1;let s=Rn.get(n);return void 0===s&&(s=Function.toString.call(n),Rn.set(n,s)),s===Mn}function Ln(e,t,n=!0){if(0===On(e)){(n?Reflect.ownKeys(e):Object.keys(e)).forEach(n=>{t(n,e[n],e)})}else e.forEach((n,s)=>t(s,n,e))}function On(e){const t=e[Tn];return t?t.type_:Array.isArray(e)?1:qn(e)?2:Un(e)?3:0}function Dn(e,t){return 2===On(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Fn(e,t,n){const s=On(e);2===s?e.set(t,n):3===s?e.add(n):e[t]=n}function qn(e){return e instanceof Map}function Un(e){return e instanceof Set}function Hn(e){return e.copy_||e.base_}function Bn(e,t){if(qn(e))return new Map(e);if(Un(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=Pn(e);if(!0===t||"class_only"===t&&!n){const t=Object.getOwnPropertyDescriptors(e);delete t[Tn];let n=Reflect.ownKeys(t);for(let s=0;s1&&Object.defineProperties(e,{set:Gn,add:Gn,clear:Gn,delete:Gn}),Object.freeze(e),t&&Object.values(e).forEach(e=>zn(e,!0))),e}var Gn={value:function(){En(2)}};function $n(e){return null===e||"object"!=typeof e||Object.isFrozen(e)}var Wn,Vn={};function Qn(e){const t=Vn[e];return t||En(0),t}function Kn(){return Wn}function Yn(e,t){t&&(Qn("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Jn(e){Xn(e),e.drafts_.forEach(es),e.drafts_=null}function Xn(e){e===Wn&&(Wn=e.parent_)}function Zn(e){return Wn={drafts_:[],parent_:Wn,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function es(e){const t=e[Tn];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ts(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return void 0!==e&&e!==n?(n[Tn].modified_&&(Jn(t),En(4)),An(e)&&(e=ns(t,e),t.parent_||is(t,e)),t.patches_&&Qn("Patches").generateReplacementPatches_(n[Tn].base_,e,t.patches_,t.inversePatches_)):e=ns(t,n,[]),Jn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==kn?e:void 0}function ns(e,t,n){if($n(t))return t;const s=e.immer_.shouldUseStrictIteration(),i=t[Tn];if(!i)return Ln(t,(s,a)=>ss(e,i,t,s,a,n),s),t;if(i.scope_!==e)return t;if(!i.modified_)return is(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;const t=i.copy_;let a=t,o=!1;3===i.type_&&(a=new Set(t),t.clear(),o=!0),Ln(a,(s,a)=>ss(e,i,t,s,a,n,o),s),is(e,t,!1),n&&e.patches_&&Qn("Patches").generatePatches_(i,n,e.patches_,e.inversePatches_)}return i.copy_}function ss(e,t,n,s,i,a,o){if(null==i)return;if("object"!=typeof i&&!o)return;const r=$n(i);if(!r||o){if(In(i)){const o=ns(e,i,a&&t&&3!==t.type_&&!Dn(t.assigned_,s)?a.concat(s):void 0);if(Fn(n,s,o),!In(o))return;e.canAutoFreeze_=!1}else o&&n.add(i);if(An(i)&&!r){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;if(t&&t.base_&&t.base_[s]===i&&r)return;ns(e,i),t&&t.scope_.parent_||"symbol"==typeof s||!(qn(n)?n.has(s):Object.prototype.propertyIsEnumerable.call(n,s))||is(e,i)}}}function is(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&zn(t,n)}var as={get(e,t){if(t===Tn)return e;const n=Hn(e);if(!Dn(n,t))return function(e,t,n){var s;const i=ls(t,n);return i?"value"in i?i.value:null==(s=i.get)?void 0:s.call(e.draft_):void 0}(e,n,t);const s=n[t];return e.finalized_||!An(s)?s:s===rs(e.base_,t)?(ds(e),e.copy_[t]=us(s,e)):s},has:(e,t)=>t in Hn(e),ownKeys:e=>Reflect.ownKeys(Hn(e)),set(e,t,n){const s=ls(Hn(e),t);if(null==s?void 0:s.set)return s.set.call(e.draft_,n),!0;if(!e.modified_){const s=rs(Hn(e),t),o=null==s?void 0:s[Tn];if(o&&o.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(((i=n)===(a=s)?0!==i||1/i==1/a:i!=i&&a!=a)&&(void 0!==n||Dn(e.base_,t)))return!0;ds(e),cs(e)}var i,a;return e.copy_[t]===n&&(void 0!==n||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==rs(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,ds(e),cs(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Hn(e),s=Reflect.getOwnPropertyDescriptor(n,t);return s?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:s.enumerable,value:n[t]}:s},defineProperty(){En(11)},getPrototypeOf:e=>Nn(e.base_),setPrototypeOf(){En(12)}},os={};function rs(e,t){const n=e[Tn];return(n?Hn(n):e)[t]}function ls(e,t){if(!(t in e))return;let n=Nn(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=Nn(n)}}function cs(e){e.modified_||(e.modified_=!0,e.parent_&&cs(e.parent_))}function ds(e){e.copy_||(e.copy_=Bn(e.base_,e.scope_.immer_.useStrictShallowCopy_))}Ln(as,(e,t)=>{os[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),os.deleteProperty=function(e,t){return os.set.call(this,e,t,void 0)},os.set=function(e,t,n){return as.set.call(this,e[0],t,n,e[0])};function us(e,t){const n=qn(e)?Qn("MapSet").proxyMap_(e,t):Un(e)?Qn("MapSet").proxySet_(e,t):function(e,t){const n=Array.isArray(e),s={type_:n?1:0,scope_:t?t.scope_:Kn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=s,a=as;n&&(i=[s],a=os);const{revoke:o,proxy:r}=Proxy.revocable(i,a);return s.draft_=r,s.revoke_=o,r}(e,t);return(t?t.scope_:Kn()).drafts_.push(n),n}function hs(e){if(!An(e)||$n(e))return e;const t=e[Tn];let n,s=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Bn(e,t.scope_.immer_.useStrictShallowCopy_),s=t.scope_.immer_.shouldUseStrictIteration()}else n=Bn(e,!0);return Ln(n,(e,t)=>{Fn(n,e,hs(t))},s),t&&(t.finalized_=!1),n}var ms=(new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,t,n)=>{if("function"==typeof e&&"function"!=typeof t){const n=t;t=e;const s=this;return function(e=n,...i){return s.produce(e,e=>t.call(this,e,...i))}}let s;if("function"!=typeof t&&En(6),void 0!==n&&"function"!=typeof n&&En(7),An(e)){const i=Zn(this),a=us(e,void 0);let o=!0;try{s=t(a),o=!1}finally{o?Jn(i):Xn(i)}return Yn(i,n),ts(s,i)}if(!e||"object"!=typeof e){if(s=t(e),void 0===s&&(s=e),s===kn&&(s=void 0),this.autoFreeze_&&zn(s,!0),n){const t=[],i=[];Qn("Patches").generateReplacementPatches_(e,s,t,i),n(t,i)}return s}En(1)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,s;return[this.produce(e,t,(e,t)=>{n=e,s=t}),n,s]},"boolean"==typeof(null==e?void 0:e.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof(null==e?void 0:e.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),"boolean"==typeof(null==e?void 0:e.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){An(e)||En(8),In(e)&&(e=function(e){In(e)||En(10);return hs(e)}(e));const t=Zn(this),n=us(e,void 0);return n[Tn].isManual_=!0,Xn(t),n}finishDraft(e,t){const n=e&&e[Tn];n&&n.isManual_||En(9);const{scope_:s}=n;return Yn(s,t),ts(void 0,s)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const s=t[n];if(0===s.path.length&&"replace"===s.op){e=s.value;break}}n>-1&&(t=t.slice(n+1));const s=Qn("Patches").applyPatches_;return In(e)?s(e,t):this.produce(e,e=>s(e,t))}}).produce;const ps=e=>(t,n,s)=>(s.setState=(e,n,...s)=>{const i="function"==typeof e?ms(e):e;return t(i,n,...s)},e(s.setState,n,s)),gs={BASE_URL:"//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.2.67/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},fs=e=>!!e.dispatchFromDevtools&&"function"==typeof e.dispatch,vs=new Map,ys=e=>{const t=vs.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([e,t])=>[e,t.getState()])):{}},bs=/.+ (.+) .+/,xs=/^([^@]+)@/;function ws(e){var t,n,s;if(!e)return;const i=e.split("\n"),a=i.findIndex(e=>e.includes("api.setState"));if(a<0)return;const o=(null==(t=i[a+1])?void 0:t.trim())||"";return(null==(n=bs.exec(o))?void 0:n[1])||(null==(s=xs.exec(o))?void 0:s[1])}const _s=(e,t={})=>(n,s,i)=>{const a=t,{enabled:o,anonymousActionType:r,store:l}=a,c=k(a,["enabled","anonymousActionType","store"]);let d;try{d=(null!=o?o:"production"!==(gs?"production":void 0))&&window.__REDUX_DEVTOOLS_EXTENSION__}catch(v){}if(!d)return e(n,s,i);const u=((e,t,n)=>{if(void 0===e)return{type:"untracked",connection:t.connect(n)};const s=vs.get(n.name);if(s)return C({type:"tracked",store:e},s);const i={connection:t.connect(n),stores:{}};return vs.set(n.name,i),C({type:"tracked",store:e},i)})(l,d,c),{connection:h}=u,m=k(u,["connection"]);let p=!0;i.setState=(e,t,a)=>{const o=n(e,t);if(!p)return o;const d=void 0===a?{type:r||ws((new Error).stack)||"anonymous"}:"string"==typeof a?{type:a}:a;return void 0===l?(null==h||h.send(d,s()),o):(null==h||h.send(S(C({},d),{type:`${l}/${d.type}`}),S(C({},ys(c.name)),{[l]:i.getState()})),o)},i.devtools={cleanup:()=>{h&&"function"==typeof h.unsubscribe&&h.unsubscribe(),((e,t)=>{if(void 0===t)return;const n=vs.get(e);n&&(delete n.stores[t],0===Object.keys(n.stores).length&&vs.delete(e))})(c.name,l)}};const g=(...e)=>{const t=p;p=!1,n(...e),p=t},f=e(i.setState,s,i);if("untracked"===m.type?null==h||h.init(f):(m.stores[m.store]=i,null==h||h.init(Object.fromEntries(Object.entries(m.stores).map(([e,t])=>[e,e===m.store?f:t.getState()])))),fs(i)){let e=!1;const t=i.dispatch;i.dispatch=(...n)=>{"production"===(gs?"production":void 0)||"__setState"!==n[0].type||e||(e=!0),t(...n)}}return h.subscribe(e=>{var t;switch(e.type){case"ACTION":if("string"!=typeof e.payload)return;return Cs(e.payload,e=>{if("__setState"===e.type){if(void 0===l)return void g(e.state);Object.keys(e.state).length;const t=e.state[l];if(null==t)return;return void(JSON.stringify(i.getState())!==JSON.stringify(t)&&g(t))}fs(i)&&i.dispatch(e)});case"DISPATCH":switch(e.payload.type){case"RESET":return g(f),void 0===l?null==h?void 0:h.init(i.getState()):null==h?void 0:h.init(ys(c.name));case"COMMIT":return void 0===l?void(null==h||h.init(i.getState())):null==h?void 0:h.init(ys(c.name));case"ROLLBACK":return Cs(e.state,e=>{if(void 0===l)return g(e),void(null==h||h.init(i.getState()));g(e[l]),null==h||h.init(ys(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Cs(e.state,e=>{void 0!==l?JSON.stringify(i.getState())!==JSON.stringify(e[l])&&g(e[l]):g(e)});case"IMPORT_STATE":{const{nextLiftedState:n}=e.payload,s=null==(t=n.computedStates.slice(-1)[0])?void 0:t.state;if(!s)return;return g(void 0===l?s:s[l]),void(null==h||h.send(null,n))}case"PAUSE_RECORDING":return p=!p}return}}),f},Cs=(e,t)=>{let n;try{n=JSON.parse(e)}catch(s){}void 0!==n&&t(n)},Ss=e=>(t,n,s)=>{const i=s.subscribe;s.subscribe=(e,t,n)=>{let a=e;if(t){const i=(null==n?void 0:n.equalityFn)||Object.is;let o=e(s.getState());a=n=>{const s=e(n);if(!i(o,s)){const e=o;t(o=s,e)}},(null==n?void 0:n.fireImmediately)&&t(o,o)}return i(a)};return e(t,n,s)},ks=()=>({isStopDisabled:!1,currentChatPage:1,chatLoaded:!1,isChat:!1,chatPermission:{local_mcp:"prompt"},chatId:"",chatTitle:"",chatCreatedAt:0,chatShareType:"",emitSendPromptType:"chat",chatParams:null,history:{messages:{},currentId:null,currentResponseIds:[]},historyCurrentId:"",projectId:"",currentInputFeature:Tt.Txt2Txt,currentInputSubType:void 0,currentCitationInfo:{messageId:"",citationIndex:0},currentSearchSource:{},currentSearchLists:{},allSearchAndThinkLists:{},temporarySource:{},shareChatError:"",chatMode:"normal",imageReasonData:{status:"",imageUrl:""},branchInfo:null,callBackInfo:null,isCompareVersion:!0,badFeedbackVisible:!1}),js=Sn()(ps(_s((e,t)=>C(C({},ks()),(e=>({setIsStopDisabled:t=>e({isStopDisabled:t}),setCurrentChatPage:t=>e({currentChatPage:t}),setChatLoaded:t=>e({chatLoaded:t}),setIsChat:t=>e({isChat:t}),setChatPermission:t=>e({chatPermission:t}),setChatId:t=>e({chatId:t}),setChatTitle:t=>e({chatTitle:t}),setChatCreatedAt:t=>e({chatCreatedAt:t}),setChatShareType:t=>e({chatShareType:t}),setProjectId:t=>e({projectId:t}),setEmitSendPromptType:t=>e({emitSendPromptType:t}),setChatParams:t=>e({chatParams:t}),setHistory:t=>e({history:t}),updateHistoryByImmer:t=>{e("function"==typeof t?e=>{t(e.history)}:{history:t})},setHistoryCurrentId:t=>e({historyCurrentId:t}),setAllSearchAndThinkLists:t=>e({allSearchAndThinkLists:t}),setCurrentInputFeature:t=>e({currentInputFeature:t}),setCurrentInputSubType:t=>e({currentInputSubType:t}),setCurrentCitationInfo:t=>e({currentCitationInfo:t}),setCurrentSearchSource:t=>e({currentSearchSource:t}),setTemporarySource:t=>e({temporarySource:t}),setCurrentArtifactsMessage:t=>e({currentArtifactsMessage:t}),resetChatState:()=>e(ks()),setCurrentSearchLists:t=>e({currentSearchLists:t}),setShareChatError:t=>e({shareChatError:t}),setChatMode:t=>e({chatMode:t}),setImageReasonData:t=>e({imageReasonData:t}),setBranchInfo:t=>e({branchInfo:t}),setCallBackInfo:t=>e({callBackInfo:t}),setIsCompareVersion:t=>e({isCompareVersion:t}),setBadFeedbackVisible:t=>e({badFeedbackVisible:t})}))(e)),{name:"chatStore",store:"chatStore",enabled:!1})));function Ts(e){return D.useSyncExternalStore(js.subscribe,()=>e(js.getState()),()=>e(js.getState()))}const Es={chats:[],pinnedChats:[]},Ns=Sn()(_s(e=>C(C({},Es),(e=>({setChats:t=>e({chats:t}),setPinnedChats:t=>e({pinnedChats:t})}))(e)),{name:"chatConfigStore",store:"chatConfigStore",enabled:!1})),Is={"zh-cht":"zh-TW",zh:"zh-CN",en:"en-US",fr:"fr-FR",de:"de-DE",it:"it-IT",ja:"ja-JP",ko:"ko-KR",pt:"pt-PT",ar:"ar-BH",ru:"ru-RU",es:"es-ES"},As=(e=!1,t="light")=>"dark"===t?e?"https://img.alicdn.com/imgextra/i2/O1CN01J8AmJN1cZGSJ5xFjV_!!6000000003614-54-tps-60-60.apng":"https://img.alicdn.com/imgextra/i1/O1CN01lSOiPA1VfwvV2cZw6_!!6000000002681-54-tps-60-60.apng":"light"===t?e?"https://img.alicdn.com/imgextra/i4/O1CN01Jwyf191eaIa5xowFe_!!6000000003887-54-tps-60-60.apng":"https://img.alicdn.com/imgextra/i1/O1CN01pNHavt1CykU9z9sPI_!!6000000000150-54-tps-60-60.apng":void 0,Ms={showDeleteDeployConfirm:!1,reUpdateFolders:!1,taskRunning:!1,hasChatIsRunning:!1,visionGenerating:!1,showArchivedChats:!1,showChangelog:!1,showModelSelect:!1,showMCPconfig:!1,showUserLongPressChat:!1,showResLongPressChat:!1,showMcpServerModal:!1,showMcpJsonNewModal:!1,showMcpDetailModal:!1,showMcpDeleteModal:!1,thinkingEnabled:!1,thinkingMode:void 0,searchEnabled:!1,researchMode:"normal",featureConfig:"",imageGenerateEnabled:!1,mcpEnabled:!1,videoGenerateEnabled:!1,disableOtherFeature:!1,currentShowControl:xt.None,temporaryChatEnabled:!1,reUpdateMessagesScroll:!1,selectedArtifactsMessageId:"",historyCurrentId:"",welcomeModalShow:!1,isHongkong:!1,isRussia:!1,isShowGetTheApp:!1,isPdfVisible:!1,isSourcesVisible:!1,pdfViewInfo:null,isPdfCardVisible:!1,selectedModels:[],folders:{},currentDPLanguageCode:Is.en,podcastCount:0,deepResearchVersion:"",omniType:"",pdfCardType:"",selectedText:"",selectedTextPosition:null,selectedTextId:null,selectedTextIndex:null,currentActionMessageId:"",locateTheSearchSource:!1,currentControlsId:"",currentSlidesInfo:null,currentPhaseContentId:"",thinkingStatus:null,featureStatuses:[],fileTypeStatuses:[]},Rs=Sn()(Ss(_s(e=>C(C({},Ms),(e=>({setShowDeleteDeployConfirm:t=>e({showDeleteDeployConfirm:t}),setReUpdateFolders:t=>e({reUpdateFolders:t}),setTaskRunning:t=>e({taskRunning:t}),setHasChatIsRunning:t=>e({hasChatIsRunning:t}),setVisionGenerating:t=>e({visionGenerating:t}),setShowArchivedChats:t=>e({showArchivedChats:t}),setShowChangelog:t=>e({showChangelog:t}),setShowModelSelect:t=>e({showModelSelect:t}),setShowMCPconfig:t=>e({showMCPconfig:t}),setShowUserLongPressChat:t=>e({showUserLongPressChat:t}),setShowResLongPressChat:t=>e({showResLongPressChat:t}),setShowMcpServerModal:t=>e({showMcpServerModal:t}),setShowMcpJsonNewModal:t=>e({showMcpJsonNewModal:t}),setShowMcpDetailModal:t=>e({showMcpDetailModal:t}),setShowMcpDeleteModal:t=>e({showMcpDeleteModal:t}),setThinkingEnabled:t=>e({thinkingEnabled:t}),setSearchEnabled:t=>e({searchEnabled:t}),setResearchMode:t=>e({researchMode:t}),setFeatureConfig:t=>e({featureConfig:t}),setImageGenerateEnabled:t=>e({imageGenerateEnabled:t}),setMcpEnabled:t=>e({mcpEnabled:t}),setVideoGenerateEnabled:t=>e({videoGenerateEnabled:t}),setDisableOtherFeature:t=>e({disableOtherFeature:t}),setCurrentShowControl:t=>e({currentShowControl:t}),setTemporaryChatEnabled:t=>e({temporaryChatEnabled:t}),setReUpdateMessagesScroll:t=>e({reUpdateMessagesScroll:t}),setSelectedArtifactsMessageId:t=>e({selectedArtifactsMessageId:t}),setHistoryCurrentId:t=>e({historyCurrentId:t}),setWelcomeModalShow:t=>e({welcomeModalShow:t}),setIsHongkong:t=>e({isHongkong:t}),setIsRussia:t=>e({isRussia:t}),setIsShowGetTheApp:t=>e({isShowGetTheApp:t}),setIsPdfVisible:t=>e({isPdfVisible:t}),setIsSourcesVisible:t=>e({isSourcesVisible:t}),setPDFViewInfo:t=>e({pdfViewInfo:t}),setIsPdfCardVisible:t=>e({isPdfCardVisible:t}),setSelectedModels:t=>e({selectedModels:t}),setCurrentDPLanguageCode:t=>e({currentDPLanguageCode:t}),setPodcastCount:t=>e({podcastCount:t}),setDeepResearchVersion:t=>e({deepResearchVersion:t}),setOmniType:t=>e({omniType:t}),setPdfCardType:t=>e({pdfCardType:t}),setCurrentActionMessageId:t=>e({currentActionMessageId:t}),setCurrentPhaseContentId:t=>e({currentPhaseContentId:t}),resetFeatureState:(t={})=>e(C(C({},Ms),t)),setFolders:t=>e({folders:t}),setSelectedText:t=>e({selectedText:t}),setSelectedTextPosition:t=>e({selectedTextPosition:t}),setSelectedTextId:t=>e({selectedTextId:t}),setSelectedTextIndex:t=>e({selectedTextIndex:t}),setLocateTheSearchSource:t=>e({locateTheSearchSource:t}),setCurrentControlsId:t=>e({currentControlsId:t}),setCurrentSlidesInfo:t=>e({currentSlidesInfo:t}),setThinkingStatus:t=>e({thinkingStatus:t}),setFeatureStatuses:t=>e({featureStatuses:t}),setFileTypeStatuses:t=>e({fileTypeStatuses:t}),setThinkingMode:t=>{switch(t){case"Auto":case"Thinking":e({thinkingEnabled:!0});break;case"Fast":e({thinkingEnabled:!1})}e({thinkingMode:t})}}))(e)),{name:"featureStore",store:"featureStore",enabled:!1}))),Ps=e=>D.useSyncExternalStore(Rs.subscribe,()=>e(Rs.getState()),()=>e(Rs.getState()));function Ls(){if("undefined"==typeof navigator)return!1;const e=navigator.userAgent||navigator.vendor||window.opera||"";return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}let Os=null;const Ds=(e,t)=>{Os&&Os(e,t)},Fs=Ds,qs=class e{constructor(){j(this,"platform","node")}static getInstance(){return e.instance||(e.instance=new e),e.instance}navigate(e){Ds(e)}openWindow(e,t){"undefined"!=typeof window&&window.open(e,"_blank","noopener,noreferrer")}get navigator(){return"undefined"!=typeof window?window.navigator:null}};j(qs,"instance");let Us=qs;const Hs=Us.getInstance(),Bs=e=>"number"==typeof e&&!Number.isNaN(e);function zs(){const e=Hs.navigator;if(!e)return!1;const{userAgent:t}=e;return Boolean(t.match(/iPad Simulator|iPhone Simulator|iPod Simulator|iPad|iPhone|iPod/)||t.includes("Mac")&&"ontouchend"in document)}const Gs=()=>{const e=Hs.navigator;if(!e)return!1;const t=e.userAgent.toLowerCase();return/iphone/.test(t)},$s=()=>{const e=Hs.navigator;if(!e)return!1;return-1!==e.userAgent.toLowerCase().indexOf("android")},Ws=()=>{const e=Hs.navigator;if(!e)return"pc";const t=e.userAgent,n=/(iPad|Macintosh.*AppleWebKit(?!.*Chrome))/.test(t)&&!/iPhone|iPod/.test(t)&&zs(),s=/Android/.test(t)&&!/Mobile/.test(t),i=/Windows/.test(t)&&/Touch/.test(t);return n?"iPad":s||i?"tablet":/iPhone|Android/.test(t)?"mobile":"pc"},Vs=()=>{const e=Hs.navigator;if(!e)return!1;return-1!==e.userAgent.toLowerCase().indexOf("micromessenger")},Qs=()=>$s()&&Vs(),Ks=()=>{const e=Ws();return["iPad","mobile","tablet"].includes(e)},Ys=()=>"pc"===Ws(),Js=()=>{const e=Hs.navigator;return!!e&&/AliApp\(QWENCHAT\/[^)]*\)/.test(e.userAgent)},Xs=()=>!Ys()&&!Js(),Zs=()=>{const e=Hs.navigator;return!!e&&/^((?!chrome|android).)*safari/i.test(e.userAgent)},ei=()=>{const e=Hs.navigator;if(!e)return"1.0.0";const t=e.userAgent.match(/AliApp\(QWENCHAT\/([\d.]+)\)/);return t?t[1]:"1.0.0"},ti=()=>{const e=Hs.navigator;if(!e)return!1;const t=e.userAgent.match(/AliApp\(QWENCHAT\/(\d+\.\d+\.\d+)/),n=t?t[1]:null;return n&&!(e=>{const t=e.split(".").map(e=>parseInt(e,10));for(;t.length<3;)t.push(0);return t[0]<1||!(t[0]>1)&&t[1]<2})(n)},ni=()=>!Ys()&&!ti(),si=()=>{const e=Hs.navigator;return!!e&&(!!window.electronAPI&&/AliDesktop\(QWENCHAT\/\d+\.\d+\.\d+\)/.test(e.userAgent))},ii=()=>zs()&&Js()||$s()&&Js(),ai=()=>{const e=Hs.navigator;if(!e)return"";const t=e.userAgent,n=e.platform;let s="";return-1!==["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(n)?s="MACOS":-1!==["iPhone","iPad","iPod"].indexOf(n)?s="IOS":-1!==["Win32","Win64","Windows","WinCE"].indexOf(n)?s="WINDOWS":/Android/.test(t)?s="ANDROID":!s&&/Linux/.test(n)&&(s="LINUX"),s},oi=()=>{var e;if(!Hs.navigator)return"0px";if(!Js()||ti())return"0px";const t=null==(e=null==window?void 0:window.QwenChat)?void 0:e.safeAreaInsetTop;return Gs()?Bs(t)?`${t}px`:"env(safe-area-inset-top)":Bs(t)?`${t}px`:"33px"},ri=()=>{var e;if(!Hs.navigator)return"0px";if(!Js()||ti())return"0px";const t=null==(e=null==window?void 0:window.QwenChat)?void 0:e.safeAreaInsetBottom;return Gs()?Bs(t)?`${t}px`:"env(safe-area-inset-bottom)":Bs(t)?`${t}px`:"38px"},li=(e,t=!1)=>{const n=ei(),s=e.split(".").map(Number),i=n.split(".").map(Number);for(let a=0;a<3;a++){const e=s[a]||0,t=i[a]||0;if(te)return!1}return t},ci=()=>{const e=Hs.navigator;if(!e)return{};const t=e.userAgent;let n,s;if(t.indexOf("Firefox")>-1){n="Firefox";const e=t.match(/Firefox\/([\d.]+)/);s=e?e[1]:"Unknown"}else if(t.indexOf("Opera")>-1||t.indexOf("OPR")>-1){n="Opera";const e=t.match(/(Opera|OPR)\/([\d.]+)/);s=e?e[2]:"Unknown"}else if(t.indexOf("Edge")>-1){n="Edge";const e=t.match(/Edge\/([\d.]+)/);s=e?e[1]:"Unknown"}else if(t.indexOf("Chrome")>-1){n="Chrome";const e=t.match(/Chrome\/([\d.]+)/);s=e?e[1]:"Unknown"}else if(t.indexOf("Safari")>-1&&!t.match("Chrome")){n="Safari";const e=t.match(/Version\/([\d.]+)/);s=e?e[1]:"Unknown"}return{name:n,version:s}},di=(e,t)=>{var n;si()&&(null==(n=window.electronAPI)?void 0:n.open_external_link)&&(e.preventDefault(),window.electronAPI.open_external_link(t))},ui=new Set;function hi(e,t=0){const n=e[t];if(function(e){return!("string"!=typeof e||!e.length||ui.has(e))}(n)){const s=document.createElement("script");s.setAttribute("src",n),s.setAttribute("data-namespace",n),e.length>t+1&&(s.onload=()=>{hi(e,t+1)},s.onerror=()=>{hi(e,t+1)}),ui.add(n),document.body.appendChild(s)}}const mi=["//at.alicdn.com/t/a/font_4811585_tqx3gp42qn.js","//at.alicdn.com/t/a/font_4808287_gegfilxvlip.js"],pi=e=>{var t=e,{type:n,scriptUrl:s=mi}=t,i=k(t,["type","scriptUrl"]);const a=D.useMemo(()=>e=>F.jsx("svg",S(C({width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",focusable:"false"},e),{children:F.jsx("use",{xlinkHref:`#${n}`})})),[n]);return D.useEffect(()=>{s.length>0&&!window.QWEN_EXTENSION_SCENE&&hi(s.reverse())},[s]),F.jsx(W,C({component:a},i))},gi=e=>{let t=null;switch(e){case"loading":t=F.jsx(pi,{type:"icon-jiazaizhong",className:"qwen-message-icon"});break;case"error":t=F.jsx(pi,{type:"icon-line-x-circle-contained",className:"qwen-message-icon"});break;case"caution":case"info":case"warning":t=F.jsx(pi,{type:"icon-line-alert-circle",className:"qwen-message-icon"});break;case"success":t=F.jsx(pi,{type:"icon-line-check-contained1",className:"qwen-message-icon"});break;default:t=F.jsx(F.Fragment,{})}return t},fi=({type:e="info",content:t,duration:n=3e3,onCancel:s,closable:i=!0,hideIcon:a,className:o="",style:r={}})=>{const l=`qwen-message-${Date.now()}`,c=C({},r),d=`qwen-design-message qwen-design-message-${e} ${o}`,u=F.jsxs("div",{className:"qwen-message-content",children:[F.jsxs("div",{className:"qwen-message-content-text",children:[t," "]}),i&&F.jsx(pi,{type:"icon-close-4",className:"qwen-message-content-close-icon",onClick:()=>{V.destroy(l),s&&s()}})]});(V[e]||V.info)({content:u,icon:a?F.jsx(F.Fragment,{}):gi(e),duration:n/1e3,key:l,className:d,style:c})},vi={open:fi,openOnce:e=>{V.destroy(),fi(e)}},yi=({value:e,operations:t,onChange:n,className:s,placeholder:i,maxLength:a,minLength:o,minRows:r=1,maxRows:l=5,error:c,footerOperations:d,style:u})=>{const h=D.useRef(null),m=void 0!==e,[p,g]=D.useState(e||""),f=m?e:p,v=()=>{const e=h.current;if(!e)return;const t=window.getComputedStyle(e),n=parseInt(t.lineHeight,10)||20,s=n*l,i=n*r;e.style.height="auto";const a=e.scrollHeight;e.style.height=`${Math.max(i,Math.min(a,s))}px`};return D.useEffect(()=>{v()},[]),D.useEffect(()=>{if(m){const e=setTimeout(v,0);return()=>clearTimeout(e)}},[m,e]),F.jsxs(F.Fragment,{children:[F.jsxs("div",{className:`qwen-textarea-container ${s||""}`,style:u,children:[F.jsx("textarea",{ref:h,value:f,onChange:e=>{const t=e.target.value;m||g(t),null==n||n(t),requestAnimationFrame(v)},placeholder:i,className:"qwen-textarea",maxLength:a,style:{overflow:"hidden",resize:"none"}}),(void 0!==a||t)&&F.jsxs("div",{className:Q("qwen-textarea-counter",{"qwen-textarea-counter-error":void 0!==a&&f.length>=a}),children:[void 0!==a&&F.jsxs("div",{className:o>f.length&&f.length>0?"qwen-textarea-counter-error":"",children:[f.length," / ",a]}),t]})]}),d&&F.jsx("div",{className:"qwen-textarea-footer",children:d}),c&&F.jsx("div",{className:"qwen-textarea-error",children:c})]})},bi=({className:e="",color:t="currentColor",style:n=""})=>F.jsxs("div",{className:"qwen-chat-loading",style:"string"==typeof n?void 0:n,children:["string"==typeof n?F.jsx("style",{children:n}):null,F.jsxs("svg",{className:e,viewBox:"0 0 24 24",width:24,fill:t,xmlns:"http://www.w3.org/2000/svg",children:[F.jsx("style",{children:"\n .spinner_ajPY {\n transform-origin: center;\n -webkit-transform-origin: center;\n animation: spinner_AtaB 0.75s infinite linear;\n -webkit-animation: spinner_AtaB 0.75s infinite linear;\n }\n @keyframes spinner_AtaB {\n 100% {\n transform: rotate(360deg);\n }\n }\n @-webkit-keyframes spinner_AtaB {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n }\n "}),F.jsx("path",{d:"M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z",opacity:"0.25",fill:t}),F.jsx("path",{d:"M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z",className:"spinner_ajPY",fill:t})]})]}),xi=e=>{var t=e,{type:n="brandprimary",shape:s="round",size:i="middle",buttonClass:a="",buttonStyle:o={},iconFontType:r="",iconFontStyle:l={},disabled:c=!1,loading:d=!1,loadingStyle:u={},block:h=!1,htmlType:m="button",isLeft:p=!0,showText:g=!0,rounded:f="",theme:v="",onClick:y,children:b,className:x}=t,w=k(t,["type","shape","size","buttonClass","buttonStyle","iconFontType","iconFontStyle","disabled","loading","loadingStyle","block","htmlType","isLeft","showText","rounded","theme","onClick","children","className"]);const _=()=>r?F.jsx("span",{className:`qwen-chat-button-icon ${p?"qwen-chat-margin-left":"qwen-chat-margin-right"} ${g?"":"qwen-chat-margin-none"}`,children:F.jsx(pi,{style:l,className:`icon-${i}`,type:r})}):null;return F.jsxs("button",S(C({className:["qwen-chat-btn",a,n,s,i,v,f,c?"disabled":"",d?"loading":"",h?"block":"",x].filter(Boolean).join(" "),type:m,onClick:e=>{!c&&!d&&y&&y(e)},disabled:c,style:C({},o)},w),{children:[r&&p&&_(),d?F.jsx("span",{className:`qwen-chat-loading-icon qwen-chat-loading-icon-${i}`,style:u,children:F.jsx(bi,{})}):null,g?F.jsx("span",{className:"qwen-chat-button-content",children:b}):null,r&&!p&&_()]}))},wi=({visible:e,title:t="",okText:n="OK",cancelText:s="Cancel",footer:i=!0,header:a=!0,centered:o=!1,className:r="",closable:l=!0,width:c=null,zIndex:d=1e3,size:u="medium",headerBorderNone:h=!1,bodyPaddingNone:m=!1,actions:p=[],btnDirection:g="row",maskClosable:f=!0,getPopupContainer:v=()=>document.body,onOk:y=()=>{},onCancel:b=()=>{},okButtonProps:x,cancelButtonProps:w,children:_,footerRender:j,type:T="default"})=>{const[E,N]=D.useState(!1),I=D.useRef(null),A=()=>{b()};D.useEffect(()=>{if(document.body)return document.body.style.overflow=e?"hidden":"",()=>{document.body&&(document.body.style.overflow="")}},[e]);const M=D.useRef(null);return D.useEffect(()=>(M.current=v(I.current),()=>{M.current=null}),[v]),e&&(M.current||document.body)?B.createPortal(F.jsx("div",{ref:I,className:"qwen-modal-overlay",style:{zIndex:d},onMouseDown:e=>{f&&e.target===I.current&&N(!0)},onMouseUp:e=>{E&&f&&e.target===I.current&&(b(),N(!1))},children:F.jsxs("div",{className:Q("qwen-modal-content",o&&"qwen-modal-centered",u,r),style:c?{width:`${c}px`}:{},children:[a&&F.jsxs("div",{className:Q("qwen-modal-header",h&&"qwen-modal-header-border-none","confirm"===T&&"qwen-modal-header-confirm"),children:[F.jsx("div",{className:"qwen-modal-title",children:t}),l&&F.jsx("button",{type:"button",className:"qwen-modal-close-btn",onClick:A,children:F.jsx(pi,{type:"icon-line-x-02"})})]}),F.jsx("div",{className:Q("qwen-modal-body",h&&"qwen-modal-body-border-none",m&&"qwen-modal-body-padding-none",!i&&"qwen-modal-body-footer-none"),children:_}),i&&!j&&F.jsx("div",{className:Q("qwen-modal-footer","column"===g&&"qwen-modal-btn-column"),children:p.length>0?p.map((e,t)=>{var n=e,{text:s,buttonClass:i,size:a}=n,o=k(n,["text","buttonClass","size"]);return F.jsx(xi,S(C({buttonClass:Q("qwen-modal-btn-actions",i),size:a||"large"},o),{children:s}),t)}):F.jsxs(F.Fragment,{children:[F.jsx(xi,S(C({type:"tertiary"},w),{buttonClass:Q("qwen-modal-btn","qwen-modal-cancel-btn",null==w?void 0:w.buttonClass,{"qwen-modal-cancel-btn-hidden":null==w?void 0:w.hidden}),onClick:A,children:s})),F.jsx(xi,S(C({type:"brandprimary"},x),{buttonClass:Q("qwen-modal-btn","qwen-modal-ok-btn",null==x?void 0:x.buttonClass,{"qwen-modal-ok-btn-hidden":null==x?void 0:x.hidden}),onClick:()=>{y()},children:n}))]})}),!!j&&F.jsx("div",{className:Q("qwen-modal-footer-render"),children:j})]})}),M.current||document.body):null},_i=e=>{var t=e,{clear:n=!1,allowClear:s,className:i,noBorder:a,withOtherClose:o=!1,onClear:r,onFocus:l,onBlur:c,onChange:d,value:u,setValue:h,onPressEnter:m,clearIconSize:p=20}=t,g=k(t,["clear","allowClear","className","noBorder","withOtherClose","onClear","onFocus","onBlur","onChange","value","setValue","onPressEnter","clearIconSize"]);const f=void 0!==u&&(void 0!==h||d),[v,y]=D.useState(!1),[b,x]=D.useState(String(u)),w=f?String(null!=u?u:""):b,_=void 0!==h?h:x,j=()=>{_&&_(""),d&&(null==d||d("")),null==r||r()},T=(n||s)&&w&&""!==w||o,E=["qwen-input",a?"qwen-input-no-border":"",v?"qwen-input-focused":"",i].filter(Boolean).join(" ");return F.jsx(K,S(C({},g),{className:E,value:w,suffix:F.jsxs(F.Fragment,{children:[T&&F.jsx("span",{className:"qwen-input-icon-clear",style:{width:`${p}px`,height:`${p}px`},onClick:j,children:F.jsx(pi,{type:"icon-line-x-02",style:{fontSize:p}})}),g.suffix]}),onFocus:e=>{y(!0),null==l||l(e)},onBlur:e=>{y(!1),null==c||c(e)},onChange:e=>{const t=e.target.value;_(t),null==d||d(t)},onPressEnter:m,allowClear:!1,prefix:g.prefixicon?F.jsx(pi,{type:g.prefixicon,style:{fontSize:20}}):g.prefix}))},Ci=e=>{var t=e,{children:n,menu:s,trigger:i=["click"],destroyOnHidden:a=!0,placement:o="bottomRight"}=t,r=k(t,["children","menu","trigger","destroyOnHidden","placement"]);const l=C({className:"qwen-dropdown-menu"},s);return F.jsx(Y,S(C({menu:l,trigger:i,destroyOnHidden:a,placement:o},r),{children:F.jsx("span",{style:{cursor:"pointer"},children:n})}))},Si=e=>{const t=e,{classNames:n,show:s=!0}=t,i=k(t,["classNames","show"]);return s?F.jsx(J,S(C({arrow:!1,classNames:{root:`qwen-tooltip ${(null==n?void 0:n.root)||""}`.trim()}},i),{children:e.children})):e.children},ki=e=>{var t=e,{rounded:n="round",popupClassName:s,selectorClassName:i,selectAntdRef:a}=t,o=k(t,["rounded","popupClassName","selectorClassName","selectAntdRef"]);const r=D.useRef(null);return D.useEffect(()=>{r.current&&a&&(a.current=r.current)},[null==a?void 0:a.current,r.current]),F.jsx(X,C({ref:r,suffixIcon:F.jsx(pi,{type:"icon-line-chevron-down",className:"qwen-select-down-icon"}),classNames:{popup:{root:`qwen-select-dropdown ${s}`},root:`qwen-select qwen-select-${n} ${i||""}`.trim()},optionRender:(e,t)=>F.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%",alignItems:"center"},children:[F.jsx("span",{className:"qwen-select-option-selected-label",children:e.label}),e.value===o.value||(null==t?void 0:t.value)===o.value?F.jsx(pi,{type:"icon-line-check-02",className:"qwen-select-option-selected-icon"}):null]})},o))},ji=e=>F.jsx(Z,C({className:"qwen-segmented"},e)),Ti=e=>{var t=e,{heightType:n="half",backgroundColor:s="container-primary-bgapp",children:i,title:a,header:o=!0,closable:r=!0,onClose:l,leftFirstIcon:c,leftFirstIconCallback:d,leftSecondeIcon:u,leftSecondeIconCallback:h,rightFirstIcon:m,rightFirstIconCallback:p,className:g}=t,f=k(t,["heightType","backgroundColor","children","title","header","closable","onClose","leftFirstIcon","leftFirstIconCallback","leftSecondeIcon","leftSecondeIconCallback","rightFirstIcon","rightFirstIconCallback","className"]);return F.jsxs(ee,S(C({height:"auto",className:`${g||""} qwen-chat-packages-design-popup qwen-chat-packages-design-popup-${s} qwen-chat-packages-design-popup-height-${n}`,placement:"bottom"},f),{onClose:l,title:null,styles:{header:{display:"none"},footer:{display:"none"}},children:[o&&F.jsxs("div",{className:"qwen-chat-packages-design-popup-header",children:[F.jsx("div",{className:"qwen-chat-packages-design-popup-header-icon-container "+(c?"":"qwen-chat-packages-design-popup-header-icon-container-invisible"),onClick:d,children:F.jsx(pi,{type:c||"",className:"qwen-chat-packages-design-popup-header-icon"})}),F.jsx("div",{className:"qwen-chat-packages-design-popup-header-icon-container "+(u?"":"qwen-chat-packages-design-popup-header-icon-container-invisible"),onClick:h,children:F.jsx(pi,{type:u||"",className:"qwen-chat-packages-design-popup-header-icon"})}),F.jsx("div",{className:"qwen-chat-packages-design-popup-header-title",children:a}),F.jsx("div",{className:"qwen-chat-packages-design-popup-header-icon-container "+(m?"":"qwen-chat-packages-design-popup-header-icon-container-invisible"),onClick:p,children:F.jsx(pi,{type:m||"",className:"qwen-chat-packages-design-popup-header-icon"})}),F.jsx("div",{className:"qwen-chat-packages-design-popup-header-icon-container "+(r?"":"qwen-chat-packages-design-popup-header-icon-container-invisible"),onClick:l,children:F.jsx(pi,{type:"icon-line-x-01",className:"qwen-chat-packages-design-popup-header-icon"})})]}),i]}))},Ei=()=>{},Ni=e=>{const{id:t,url:n,updateOssCacheWhenLoadError:s,getFileNewUrlWhenLoadError:i,onAudioLoad:a=Ei,onAudioLoadMetadata:o=Ei,onAudioPlay:r=Ei,onAudioPause:l=Ei,onAudioEnd:c=Ei,onAudioTimeupdate:d=Ei,onAudioError:u=Ei,onAudioWaiting:h=Ei,onAudioCanplay:m=Ei,onAudioCanplayThrough:p=Ei}=e,g=D.useRef(null),f=D.useRef(1),v=D.useRef(!1),[y,b]=D.useState(n);return F.jsx("audio",{id:Q("qwen-audio-core",{[`qwen-audio-core-${t}`]:t}),className:"qwen-audio-core",ref:g,src:y,onLoadedMetadata:()=>{o(g.current)},onLoadedData:()=>{a(g.current)},onPlay:()=>{document.querySelectorAll("audio").forEach(e=>{e.id!==g.current.id&&e.pause()}),r(g.current)},onPause:()=>{l(g.current)},onEnded:()=>{c(g.current)},onTimeUpdate:()=>{d(g.current)},onError:()=>A(null,null,function*(){if(!v.current){v.current=!0;const e=yield null==i?void 0:i(n);return void(e&&(b(e),null==s||s(e)))}if(f.current>0)return f.current--,void setTimeout(()=>{g.current&&(g.current.src=`${y}×tamp=${Date.now()}`)},200);u(g.current)}),onWaiting:()=>{h(g.current)},onCanPlay:()=>{m(g.current)},onCanPlayThrough:()=>{p(g.current)}})},Ii=e=>{const t=Math.floor(e/1e3);let n=0;t>=3600&&(n=Math.floor(t/3600));const s=Math.floor(t/60),i=Math.floor(t%60),a=e=>`${e<10?`0${e}`:e}`;return`${n>0?`${a(n)}:`:""}${a(s)}:${a(i)}`};function Ai(e,t=3){const n=Math.pow(10,t);return Math.round(e*n)/n}const Mi=({min:e=0,max:t=100,step:n=1,disabled:s,currentValue:i=0,onChange:a})=>{const[o,r]=D.useState(i),l=D.useRef(!1),[c,d]=D.useState(!1),[u,h]=D.useState(0),m=D.useRef(null),p=Math.floor((o-e)/(t-e)*100),g=s=>{if(!m.current)return;const i=m.current.getBoundingClientRect(),o=(s=>{const i=Math.max(0,Math.min(1,s/u)),a=t-e;return Math.floor(i*a/n)*n+e})((s.type.startsWith("touch")?s.touches[0].clientX:s.clientX)-i.left);"number"==typeof o&&isFinite(o)&&(r(o),a(o))},f=function(e,t){let n=null,s=0;return function(...i){const a=Date.now();a-s>=t?(e.apply(this,i),s=a):(n&&clearTimeout(n),n=setTimeout(()=>{e.apply(this,i),s=Date.now(),n=null},t-(a-s)))}}(e=>{l.current&&(d(!0),g(e))},48),v=()=>{l.current=!1,d(!1),document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",v),document.removeEventListener("touchmove",f),document.removeEventListener("touchend",v)},y=e=>{s||(e.preventDefault(),l.current=!0,document.addEventListener("mousemove",f),document.addEventListener("mouseup",v),document.addEventListener("touchmove",f),document.addEventListener("touchend",v),g(e.nativeEvent))};return D.useEffect(()=>{s||r(i)},[i,s]),D.useEffect(()=>{const e=()=>{m.current&&h(m.current.offsetWidth)};e();const t=new window.ResizeObserver(()=>{e()});return m.current&&t.observe(m.current),()=>{t.disconnect()}},[]),F.jsxs("div",{className:Q("qwen-audio-slider-root",{"qwen-audio-slider-root-dragging":l.current,"qwen-audio-slider-root-disabled":s,"qwen-audio-slider-root-hover":c}),onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),onMouseDown:y,onTouchStart:y,onClick:e=>{e.stopPropagation()},children:[F.jsx("div",{className:"qwen-audio-slider-rail",ref:m}),F.jsx("div",{className:"qwen-audio-slider-track",style:{width:`${p}%`}})]})},Ri={paused:!0,play:()=>{},pause:()=>{},toggle:()=>{},fastForward:()=>{},fastRewind:()=>{}},Pi=e=>{var t=e,{ref:n,disabled:s,onPlay:i,onPause:a,onLoaded:o,getPlayingDuration:r}=t,l=k(t,["ref","disabled","onPlay","onPause","onLoaded","getPlayingDuration"]);const[c,d]=D.useState(!1),[u,h]=D.useState(0),m=D.useRef({currTime:Ii(0),duration:Ii(0)}),p=D.useRef(null),g=D.useRef(0),f=D.useRef(0),v=e=>{var t;p.current||(p.current=e),m.current={currTime:Ii(0),duration:Ii(Math.round(1e3*e.duration))},null==r||r(m.current),null==o||o(!0),d(!0),p.current&&0===(null==(t=p.current)?void 0:t.duration)&&g.current<40&&(f.current=setTimeout(()=>{p.current&&(g.current=g.current+1,v(p.current))},300))},y=(e,t)=>{h(t),m.current={currTime:Ii(1e3*Math.floor(e)),duration:Ii(Math.floor(1e3*p.current.duration))},null==r||r(m.current)},b=e=>{p.current.currentTime+=e},x=e=>{p.current.currentTime-=e},w=e=>{p.current.playbackRate=e};return D.useImperativeHandle(n,()=>c?{paused:p.current.paused,play:()=>{var e;return null==(e=p.current)?void 0:e.play()},pause:()=>{var e;return null==(e=p.current)?void 0:e.pause()},toggle:()=>{var e,t,n;(null==(e=p.current)?void 0:e.paused)?null==(t=p.current)||t.play():null==(n=p.current)||n.pause()},fastForward:b,fastRewind:x,playbackRate:w,audioElemRef:p}:S(C({},Ri),{audioElemRef:p}),[c]),D.useEffect(()=>{if(!l.url||!function(){const{userAgent:e}=navigator;return!!(e.match(/iPad Simulator|iPhone Simulator|iPod Simulator|iPad|iPhone|iPod/)||e.includes("Mac")&&"ontouchend"in document)}())return;let e=0;const t=()=>{setTimeout(()=>{const n=document.getElementById(l.id?`qwen-audio-core-${l.id}`:"qwen-audio-core");if(!n)return e++,void(e<3&&t());n.load()},1e3)};t()},[l.url,l.id]),F.jsxs("div",{className:"qwen-audio",children:[F.jsx(Ni,C({onAudioLoad:v,onAudioPlay:()=>{null==i||i(!1)},onAudioPause:()=>{null==a||a(!0)},onAudioTimeupdate:e=>{if(isNaN(e.duration))return;const t=Math.floor(e.currentTime/e.duration*100);y(Ai(e.currentTime),t)},onAudioCanplay:()=>{}},l),l.id),F.jsx(Mi,{currentValue:u,onChange:e=>{const t=Ai(e/100*p.current.duration);p.current.currentTime=t,y(t,e)},disabled:s||!c})]})},Li=({className:e="",style:t={},width:n=100,height:s=24})=>F.jsx("div",{className:`${e} qwen-skeleton-node`,style:C({width:n,height:s},t)}),Oi=({className:e="",style:t={},size:n="small",indeterminate:s=!1,checked:i,disabled:a=!1,onChange:o,children:r,isRound:l=!1})=>{const[c,d]=D.useState(i);D.useEffect(()=>{void 0!==i&&d(i)},[i]);const u=void 0!==i?i:c;return F.jsxs("button",{type:"button",className:`qwen-chat-checkbox-container ${e}`,style:t,onClick:()=>{if(a)return;const e=!c;d(e),null==o||o(e)},disabled:a,children:[F.jsxs("span",{className:`qwen-chat-checkbox-container__icon\n ${l?"qwen-chat-checkbox-container__icon--round":""}\n ${"small"===n?"qwen-chat-checkbox-container__icon--small":""}\n ${"middle"===n?"qwen-chat-checkbox-container__icon--large":""}\n ${u&&!s?"qwen-chat-checkbox-container__icon--checked":""}\n ${a&&u?"qwen-chat-checkbox-container__icon--disabled":""}\n ${a&&!u?"qwen-chat-checkbox-container__icon--disabled--nochecked":""}\n `,children:[u&&!s&&F.jsx(pi,{className:"checked-Icon "+(a?"checked-Icon--disabled":""),type:"icon-line-check-03"}),u&&s&&F.jsx("div",{className:"circle"})]}),r&&F.jsx("span",{className:"qwen-chat-checkbox-container__label",children:r})]})},Di=e=>{const{className:t}=e;return F.jsx(te,C({className:Q("qwen-image",t)},e))},Fi=e=>F.jsx(ne,C({},e)),qi=e=>F.jsx(se,C({},e)),Ui=({className:e="",styles:t={},fontSize:n=14,type:s="default",borderWidth:i})=>F.jsx("div",{className:`${e} qwen-spinner-wrapper qwen-spinner-wrapper-${s}`,style:C({width:n,height:n,minWidth:n,minHeight:n,borderWidth:i||n/10,borderTopWidth:i||n/10},t)}),Hi=({className:e="",style:t={},size:n="small",checked:s,disabled:i=!1,checkedChildren:a,unCheckedChildren:o,loading:r,onChange:l})=>{const[c,d]=D.useState(s),[u,h]=D.useState(0),[m,p]=D.useState(0),[g,f]=D.useState(!1),v=D.useRef(null),y=D.useRef(null),b=void 0!==s?s:c;D.useEffect(()=>{void 0!==s&&d(s)},[s]),D.useEffect(()=>{const e=()=>{v.current&&h(v.current.offsetWidth),y.current&&p(y.current.offsetWidth)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[v.current,y.current]);const x=D.useCallback(()=>{if(i||r)return;const e=!b;f(!0),d(e),null==l||l(e)},[i,b,r,l]),w=D.useCallback(e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),x())},[x]);return F.jsxs("div",{className:`qwen-chat-ui-packages-design-switch ${e}\n qwen-chat-ui-packages-design-switch-size-${n}\n ${b?"qwen-chat-ui-packages-design-switch-checked":""}\n ${r?"qwen-chat-ui-packages-design-switch-loading":""}\n ${i?"qwen-chat-ui-packages-design-switch-disabled":""}`,ref:v,style:t,onClick:x,role:"switch","aria-checked":b,tabIndex:0,onKeyDown:w,children:[F.jsx("div",{className:"qwen-chat-ui-packages-design-switch-handle "+(g?"qwen-chat-ui-packages-design-switch-transition":""),ref:y,style:{transform:`translateX(${b?u-m-4:0}px)`},children:r&&F.jsx(Ui,{className:"qwen-chat-ui-packages-design-switch-spinner"})}),F.jsx("div",{className:"qwen-chat-ui-packages-design-switch-content",children:b?a:o})]})};function Bi(e,t){return function(){return e.apply(t,arguments)}}const{toString:zi}=Object.prototype,{getPrototypeOf:Gi}=Object,{iterator:$i,toStringTag:Wi}=Symbol,Vi=(e=>t=>{const n=zi.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Qi=e=>(e=e.toLowerCase(),t=>Vi(t)===e),Ki=e=>t=>typeof t===e,{isArray:Yi}=Array,Ji=Ki("undefined");const Xi=Qi("ArrayBuffer");const Zi=Ki("string"),ea=Ki("function"),ta=Ki("number"),na=e=>null!==e&&"object"==typeof e,sa=e=>{if("object"!==Vi(e))return!1;const t=Gi(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Wi in e||$i in e)},ia=Qi("Date"),aa=Qi("File"),oa=Qi("Blob"),ra=Qi("FileList"),la=Qi("URLSearchParams"),[ca,da,ua,ha]=["ReadableStream","Request","Response","Headers"].map(Qi);function ma(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let s,i;if("object"!=typeof e&&(e=[e]),Yi(e))for(s=0,i=e.length;s0;)if(s=n[i],t===s.toLowerCase())return s;return null}const ga="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,fa=e=>!Ji(e)&&e!==ga;const va=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Gi(Uint8Array)),ya=Qi("HTMLFormElement"),ba=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),xa=Qi("RegExp"),wa=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),s={};ma(n,(n,i)=>{let a;!1!==(a=t(n,i,e))&&(s[i]=a||n)}),Object.defineProperties(e,s)};const _a=Qi("AsyncFunction"),Ca=(Sa="function"==typeof setImmediate,ka=ea(ga.postMessage),Sa?setImmediate:ka?(ja=`axios@${Math.random()}`,Ta=[],ga.addEventListener("message",({source:e,data:t})=>{e===ga&&t===ja&&Ta.length&&Ta.shift()()},!1),e=>{Ta.push(e),ga.postMessage(ja,"*")}):e=>setTimeout(e));var Sa,ka,ja,Ta;const Ea="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ga):"undefined"!=typeof process&&process.nextTick||Ca,Na={isArray:Yi,isArrayBuffer:Xi,isBuffer:function(e){return null!==e&&!Ji(e)&&null!==e.constructor&&!Ji(e.constructor)&&ea(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||ea(e.append)&&("formdata"===(t=Vi(e))||"object"===t&&ea(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Xi(e.buffer),t},isString:Zi,isNumber:ta,isBoolean:e=>!0===e||!1===e,isObject:na,isPlainObject:sa,isReadableStream:ca,isRequest:da,isResponse:ua,isHeaders:ha,isUndefined:Ji,isDate:ia,isFile:aa,isBlob:oa,isRegExp:xa,isFunction:ea,isStream:e=>na(e)&&ea(e.pipe),isURLSearchParams:la,isTypedArray:va,isFileList:ra,forEach:ma,merge:function e(){const{caseless:t}=fa(this)&&this||{},n={},s=(s,i)=>{const a=t&&pa(n,i)||i;sa(n[a])&&sa(s)?n[a]=e(n[a],s):sa(s)?n[a]=e({},s):Yi(s)?n[a]=s.slice():n[a]=s};for(let i=0,a=arguments.length;i(ma(t,(t,s)=>{n&&ea(t)?e[s]=Bi(t,n):e[s]=t},{allOwnKeys:s}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,s)=>{e.prototype=Object.create(t.prototype,s),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,s)=>{let i,a,o;const r={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)o=i[a],s&&!s(o,e,t)||r[o]||(t[o]=e[o],r[o]=!0);e=!1!==n&&Gi(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Vi,kindOfTest:Qi,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const s=e.indexOf(t,n);return-1!==s&&s===n},toArray:e=>{if(!e)return null;if(Yi(e))return e;let t=e.length;if(!ta(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[$i]).call(e);let s;for(;(s=n.next())&&!s.done;){const n=s.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const s=[];for(;null!==(n=e.exec(t));)s.push(n);return s},isHTMLForm:ya,hasOwnProperty:ba,hasOwnProp:ba,reduceDescriptors:wa,freezeMethods:e=>{wa(e,(t,n)=>{if(ea(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const s=e[n];ea(s)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(e,t)=>{const n={},s=e=>{e.forEach(e=>{n[e]=!0})};return Yi(e)?s(e):s(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:pa,global:ga,isContextDefined:fa,isSpecCompliantForm:function(e){return!!(e&&ea(e.append)&&"FormData"===e[Wi]&&e[$i])},toJSONObject:e=>{const t=new Array(10),n=(e,s)=>{if(na(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[s]=e;const i=Yi(e)?[]:{};return ma(e,(e,t)=>{const a=n(e,s+1);!Ji(a)&&(i[t]=a)}),t[s]=void 0,i}}return e};return n(e,0)},isAsyncFn:_a,isThenable:e=>e&&(na(e)||ea(e))&&ea(e.then)&&ea(e.catch),setImmediate:Ca,asap:Ea,isIterable:e=>null!=e&&ea(e[$i])};function Ia(e,t,n,s,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),s&&(this.request=s),i&&(this.response=i,this.status=i.status?i.status:null)}Na.inherits(Ia,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Na.toJSONObject(this.config),code:this.code,status:this.status}}});const Aa=Ia.prototype,Ma={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Ma[e]={value:e}}),Object.defineProperties(Ia,Ma),Object.defineProperty(Aa,"isAxiosError",{value:!0}),Ia.from=(e,t,n,s,i,a)=>{const o=Object.create(Aa);return Na.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Ia.call(o,e.message,t,n,s,i),o.cause=e,o.name=e.name,a&&Object.assign(o,a),o};function Ra(e){return Na.isPlainObject(e)||Na.isArray(e)}function Pa(e){return Na.endsWith(e,"[]")?e.slice(0,-2):e}function La(e,t,n){return e?e.concat(t).map(function(e,t){return e=Pa(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Oa=Na.toFlatObject(Na,{},null,function(e){return/^is[A-Z]/.test(e)});function Da(e,t,n){if(!Na.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const s=(n=Na.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!Na.isUndefined(t[e])})).metaTokens,i=n.visitor||c,a=n.dots,o=n.indexes,r=(n.Blob||"undefined"!=typeof Blob&&Blob)&&Na.isSpecCompliantForm(t);if(!Na.isFunction(i))throw new TypeError("visitor must be a function");function l(e){if(null===e)return"";if(Na.isDate(e))return e.toISOString();if(Na.isBoolean(e))return e.toString();if(!r&&Na.isBlob(e))throw new Ia("Blob is not supported. Use a Buffer instead.");return Na.isArrayBuffer(e)||Na.isTypedArray(e)?r&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function c(e,n,i){let r=e;if(e&&!i&&"object"==typeof e)if(Na.endsWith(n,"{}"))n=s?n:n.slice(0,-2),e=JSON.stringify(e);else if(Na.isArray(e)&&function(e){return Na.isArray(e)&&!e.some(Ra)}(e)||(Na.isFileList(e)||Na.endsWith(n,"[]"))&&(r=Na.toArray(e)))return n=Pa(n),r.forEach(function(e,s){!Na.isUndefined(e)&&null!==e&&t.append(!0===o?La([n],s,a):null===o?n:n+"[]",l(e))}),!1;return!!Ra(e)||(t.append(La(i,n,a),l(e)),!1)}const d=[],u=Object.assign(Oa,{defaultVisitor:c,convertValue:l,isVisitable:Ra});if(!Na.isObject(e))throw new TypeError("data must be an object");return function e(n,s){if(!Na.isUndefined(n)){if(-1!==d.indexOf(n))throw Error("Circular reference detected in "+s.join("."));d.push(n),Na.forEach(n,function(n,a){!0===(!(Na.isUndefined(n)||null===n)&&i.call(t,n,Na.isString(a)?a.trim():a,s,u))&&e(n,s?s.concat(a):[a])}),d.pop()}}(e),t}function Fa(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function qa(e,t){this._pairs=[],e&&Da(e,this,t)}const Ua=qa.prototype;function Ha(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ba(e,t,n){if(!t)return e;const s=n&&n.encode||Ha;Na.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let a;if(a=i?i(t,n):Na.isURLSearchParams(t)?t.toString():new qa(t,n).toString(s),a){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+a}return e}Ua.append=function(e,t){this._pairs.push([e,t])},Ua.toString=function(e){const t=e?function(t){return e.call(this,t,Fa)}:Fa;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class za{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Na.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Ga={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},$a={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:qa,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Wa="undefined"!=typeof window&&"undefined"!=typeof document,Va="object"==typeof navigator&&navigator||void 0,Qa=Wa&&(!Va||["ReactNative","NativeScript","NS"].indexOf(Va.product)<0),Ka="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Ya=Wa&&window.location.href||"http://localhost",Ja=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Wa,hasStandardBrowserEnv:Qa,hasStandardBrowserWebWorkerEnv:Ka,navigator:Va,origin:Ya},Symbol.toStringTag,{value:"Module"})),Xa=C(C({},Ja),$a);function Za(e){function t(e,n,s,i){let a=e[i++];if("__proto__"===a)return!0;const o=Number.isFinite(+a),r=i>=e.length;if(a=!a&&Na.isArray(s)?s.length:a,r)return Na.hasOwnProp(s,a)?s[a]=[s[a],n]:s[a]=n,!o;s[a]&&Na.isObject(s[a])||(s[a]=[]);return t(e,n,s[a],i)&&Na.isArray(s[a])&&(s[a]=function(e){const t={},n=Object.keys(e);let s;const i=n.length;let a;for(s=0;s{t(function(e){return Na.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),s,n,0)}),n}return null}const eo={transitional:Ga,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",s=n.indexOf("application/json")>-1,i=Na.isObject(e);i&&Na.isHTMLForm(e)&&(e=new FormData(e));if(Na.isFormData(e))return s?JSON.stringify(Za(e)):e;if(Na.isArrayBuffer(e)||Na.isBuffer(e)||Na.isStream(e)||Na.isFile(e)||Na.isBlob(e)||Na.isReadableStream(e))return e;if(Na.isArrayBufferView(e))return e.buffer;if(Na.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Da(e,new Xa.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,s){return Xa.isNode&&Na.isBuffer(e)?(this.append(t,e.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((a=Na.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Da(a?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||s?(t.setContentType("application/json",!1),function(e,t,n){if(Na.isString(e))try{return(t||JSON.parse)(e),Na.trim(e)}catch(s){if("SyntaxError"!==s.name)throw s}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||eo.transitional,n=t&&t.forcedJSONParsing,s="json"===this.responseType;if(Na.isResponse(e)||Na.isReadableStream(e))return e;if(e&&Na.isString(e)&&(n&&!this.responseType||s)){const n=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(i){if(n){if("SyntaxError"===i.name)throw Ia.from(i,Ia.ERR_BAD_RESPONSE,this,null,this.response);throw i}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Xa.classes.FormData,Blob:Xa.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Na.forEach(["delete","get","head","post","put","patch"],e=>{eo.headers[e]={}});const to=Na.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),no=Symbol("internals");function so(e){return e&&String(e).trim().toLowerCase()}function io(e){return!1===e||null==e?e:Na.isArray(e)?e.map(io):String(e)}function ao(e,t,n,s,i){return Na.isFunction(s)?s.call(this,t,n):(i&&(t=n),Na.isString(t)?Na.isString(s)?-1!==t.indexOf(s):Na.isRegExp(s)?s.test(t):void 0:void 0)}let oo=class{constructor(e){e&&this.set(e)}set(e,t,n){const s=this;function i(e,t,n){const i=so(t);if(!i)throw new Error("header name must be a non-empty string");const a=Na.findKey(s,i);(!a||void 0===s[a]||!0===n||void 0===n&&!1!==s[a])&&(s[a||t]=io(e))}const a=(e,t)=>Na.forEach(e,(e,n)=>i(e,n,t));if(Na.isPlainObject(e)||e instanceof this.constructor)a(e,t);else if(Na.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))a((e=>{const t={};let n,s,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),n=e.substring(0,i).trim().toLowerCase(),s=e.substring(i+1).trim(),!n||t[n]&&to[n]||("set-cookie"===n?t[n]?t[n].push(s):t[n]=[s]:t[n]=t[n]?t[n]+", "+s:s)}),t})(e),t);else if(Na.isObject(e)&&Na.isIterable(e)){let n,s,i={};for(const t of e){if(!Na.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[s=t[0]]=(n=i[s])?Na.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}a(i,t)}else null!=e&&i(t,e,n);return this}get(e,t){if(e=so(e)){const n=Na.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=n.exec(e);)t[s[1]]=s[2];return t}(e);if(Na.isFunction(t))return t.call(this,e,n);if(Na.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=so(e)){const n=Na.findKey(this,e);return!(!n||void 0===this[n]||t&&!ao(0,this[n],n,t))}return!1}delete(e,t){const n=this;let s=!1;function i(e){if(e=so(e)){const i=Na.findKey(n,e);!i||t&&!ao(0,n[i],i,t)||(delete n[i],s=!0)}}return Na.isArray(e)?e.forEach(i):i(e),s}clear(e){const t=Object.keys(this);let n=t.length,s=!1;for(;n--;){const i=t[n];e&&!ao(0,this[i],i,e,!0)||(delete this[i],s=!0)}return s}normalize(e){const t=this,n={};return Na.forEach(this,(s,i)=>{const a=Na.findKey(n,i);if(a)return t[a]=io(s),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(i):String(i).trim();o!==i&&delete t[i],t[o]=io(s),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Na.forEach(this,(n,s)=>{null!=n&&!1!==n&&(t[s]=e&&Na.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){const t=(this[no]=this[no]={accessors:{}}).accessors,n=this.prototype;function s(e){const s=so(e);t[s]||(!function(e,t){const n=Na.toCamelCase(" "+t);["get","set","has"].forEach(s=>{Object.defineProperty(e,s+n,{value:function(e,n,i){return this[s].call(this,t,e,n,i)},configurable:!0})})}(n,e),t[s]=!0)}return Na.isArray(e)?e.forEach(s):s(e),this}};function ro(e,t){const n=this||eo,s=t||n,i=oo.from(s.headers);let a=s.data;return Na.forEach(e,function(e){a=e.call(n,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function lo(e){return!(!e||!e.__CANCEL__)}function co(e,t,n){Ia.call(this,null==e?"canceled":e,Ia.ERR_CANCELED,t,n),this.name="CanceledError"}function uo(e,t,n){const s=n.config.validateStatus;n.status&&s&&!s(n.status)?t(new Ia("Request failed with status code "+n.status,[Ia.ERR_BAD_REQUEST,Ia.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}oo.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Na.reduceDescriptors(oo.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),Na.freezeMethods(oo),Na.inherits(co,Ia,{__CANCEL__:!0});const ho=(e,t,n=3)=>{let s=0;const i=function(e,t){e=e||10;const n=new Array(e),s=new Array(e);let i,a=0,o=0;return t=void 0!==t?t:1e3,function(r){const l=Date.now(),c=s[o];i||(i=l),n[a]=r,s[a]=l;let d=o,u=0;for(;d!==a;)u+=n[d++],d%=e;if(a=(a+1)%e,a===o&&(o=(o+1)%e),l-i{i=a,n=null,s&&(clearTimeout(s),s=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),r=t-i;r>=a?o(e,t):(n=e,s||(s=setTimeout(()=>{s=null,o(n)},a-r)))},()=>n&&o(n)]}(n=>{const a=n.loaded,o=n.lengthComputable?n.total:void 0,r=a-s,l=i(r);s=a;e({loaded:a,total:o,progress:o?a/o:void 0,bytes:r,rate:l||void 0,estimated:l&&o&&a<=o?(o-a)/l:void 0,event:n,lengthComputable:null!=o,[t?"download":"upload"]:!0})},n)},mo=(e,t)=>{const n=null!=e;return[s=>t[0]({lengthComputable:n,total:e,loaded:s}),t[1]]},po=e=>(...t)=>Na.asap(()=>e(...t)),go=Xa.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Xa.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Xa.origin),Xa.navigator&&/(msie|trident)/i.test(Xa.navigator.userAgent)):()=>!0,fo=Xa.hasStandardBrowserEnv?{write(e,t,n,s,i,a){const o=[e+"="+encodeURIComponent(t)];Na.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),Na.isString(s)&&o.push("path="+s),Na.isString(i)&&o.push("domain="+i),!0===a&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function vo(e,t,n){let s=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(s||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const yo=e=>e instanceof oo?C({},e):e;function bo(e,t){t=t||{};const n={};function s(e,t,n,s){return Na.isPlainObject(e)&&Na.isPlainObject(t)?Na.merge.call({caseless:s},e,t):Na.isPlainObject(t)?Na.merge({},t):Na.isArray(t)?t.slice():t}function i(e,t,n,i){return Na.isUndefined(t)?Na.isUndefined(e)?void 0:s(void 0,e,0,i):s(e,t,0,i)}function a(e,t){if(!Na.isUndefined(t))return s(void 0,t)}function o(e,t){return Na.isUndefined(t)?Na.isUndefined(e)?void 0:s(void 0,e):s(void 0,t)}function r(n,i,a){return a in t?s(n,i):a in e?s(void 0,n):void 0}const l={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:r,headers:(e,t,n)=>i(yo(e),yo(t),0,!0)};return Na.forEach(Object.keys(Object.assign({},e,t)),function(s){const a=l[s]||i,o=a(e[s],t[s],s);Na.isUndefined(o)&&a!==r||(n[s]=o)}),n}const xo=e=>{const t=bo({},e);let n,{data:s,withXSRFToken:i,xsrfHeaderName:a,xsrfCookieName:o,headers:r,auth:l}=t;if(t.headers=r=oo.from(r),t.url=Ba(vo(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),l&&r.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):""))),Na.isFormData(s))if(Xa.hasStandardBrowserEnv||Xa.hasStandardBrowserWebWorkerEnv)r.setContentType(void 0);else if(!1!==(n=r.getContentType())){const[e,...t]=n?n.split(";").map(e=>e.trim()).filter(Boolean):[];r.setContentType([e||"multipart/form-data",...t].join("; "))}if(Xa.hasStandardBrowserEnv&&(i&&Na.isFunction(i)&&(i=i(t)),i||!1!==i&&go(t.url))){const e=a&&o&&fo.read(o);e&&r.set(a,e)}return t},wo="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const s=xo(e);let i=s.data;const a=oo.from(s.headers).normalize();let o,r,l,c,d,{responseType:u,onUploadProgress:h,onDownloadProgress:m}=s;function p(){c&&c(),d&&d(),s.cancelToken&&s.cancelToken.unsubscribe(o),s.signal&&s.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function f(){if(!g)return;const s=oo.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());uo(function(e){t(e),p()},function(e){n(e),p()},{data:u&&"text"!==u&&"json"!==u?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:s,config:e,request:g}),g=null}g.open(s.method.toUpperCase(),s.url,!0),g.timeout=s.timeout,"onloadend"in g?g.onloadend=f:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(f)},g.onabort=function(){g&&(n(new Ia("Request aborted",Ia.ECONNABORTED,e,g)),g=null)},g.onerror=function(){n(new Ia("Network Error",Ia.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const i=s.transitional||Ga;s.timeoutErrorMessage&&(t=s.timeoutErrorMessage),n(new Ia(t,i.clarifyTimeoutError?Ia.ETIMEDOUT:Ia.ECONNABORTED,e,g)),g=null},void 0===i&&a.setContentType(null),"setRequestHeader"in g&&Na.forEach(a.toJSON(),function(e,t){g.setRequestHeader(t,e)}),Na.isUndefined(s.withCredentials)||(g.withCredentials=!!s.withCredentials),u&&"json"!==u&&(g.responseType=s.responseType),m&&([l,d]=ho(m,!0),g.addEventListener("progress",l)),h&&g.upload&&([r,c]=ho(h),g.upload.addEventListener("progress",r),g.upload.addEventListener("loadend",c)),(s.cancelToken||s.signal)&&(o=t=>{g&&(n(!t||t.type?new co(null,e,g):t),g.abort(),g=null)},s.cancelToken&&s.cancelToken.subscribe(o),s.signal&&(s.signal.aborted?o():s.signal.addEventListener("abort",o)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(s.url);v&&-1===Xa.protocols.indexOf(v)?n(new Ia("Unsupported protocol "+v+":",Ia.ERR_BAD_REQUEST,e)):g.send(i||null)})},_o=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,s=new AbortController;const i=function(e){if(!n){n=!0,o();const t=e instanceof Error?e:this.reason;s.abort(t instanceof Ia?t:new co(t instanceof Error?t.message:t))}};let a=t&&setTimeout(()=>{a=null,i(new Ia(`timeout ${t} of ms exceeded`,Ia.ETIMEDOUT))},t);const o=()=>{e&&(a&&clearTimeout(a),a=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:r}=s;return r.unsubscribe=()=>Na.asap(o),r}},Co=function*(e,t){let n=e.byteLength;if(n{const i=function(e,t){return R(this,null,function*(){try{for(var n,s,i,a=L(So(e));n=!(s=yield new M(a.next())).done;n=!1){const e=s.value;yield*P(Co(e,t))}}catch(s){i=[s]}finally{try{n&&(s=a.return)&&(yield new M(s.call(a)))}finally{if(i)throw i[0]}}})}(e,t);let a,o=0,r=e=>{a||(a=!0,s&&s(e))};return new ReadableStream({pull(e){return A(this,null,function*(){try{const{done:t,value:s}=yield i.next();if(t)return r(),void e.close();let a=s.byteLength;if(n){let e=o+=a;n(e)}e.enqueue(new Uint8Array(s))}catch(t){throw r(t),t}})},cancel:e=>(r(e),i.return())},{highWaterMark:2})},jo="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,To=jo&&"function"==typeof ReadableStream,Eo=jo&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):e=>A(null,null,function*(){return new Uint8Array(yield new Response(e).arrayBuffer())})),No=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},Io=To&&No(()=>{let e=!1;const t=new Request(Xa.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Ao=To&&No(()=>Na.isReadableStream(new Response("").body)),Mo={stream:Ao&&(e=>e.body)};var Ro;jo&&(Ro=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Mo[e]&&(Mo[e]=Na.isFunction(Ro[e])?t=>t[e]():(t,n)=>{throw new Ia(`Response type '${e}' is not supported`,Ia.ERR_NOT_SUPPORT,n)})}));const Po=(e,t)=>A(null,null,function*(){const n=Na.toFiniteNumber(e.getContentLength());return null==n?(e=>A(null,null,function*(){if(null==e)return 0;if(Na.isBlob(e))return e.size;if(Na.isSpecCompliantForm(e)){const t=new Request(Xa.origin,{method:"POST",body:e});return(yield t.arrayBuffer()).byteLength}return Na.isArrayBufferView(e)||Na.isArrayBuffer(e)?e.byteLength:(Na.isURLSearchParams(e)&&(e+=""),Na.isString(e)?(yield Eo(e)).byteLength:void 0)}))(t):n}),Lo={http:null,xhr:wo,fetch:jo&&(e=>A(null,null,function*(){let{url:t,method:n,data:s,signal:i,cancelToken:a,timeout:o,onDownloadProgress:r,onUploadProgress:l,responseType:c,headers:d,withCredentials:u="same-origin",fetchOptions:h}=xo(e);c=c?(c+"").toLowerCase():"text";let m,p=_o([i,a&&a.toAbortSignal()],o);const g=p&&p.unsubscribe&&(()=>{p.unsubscribe()});let f;try{if(l&&Io&&"get"!==n&&"head"!==n&&0!==(f=yield Po(d,s))){let e,n=new Request(t,{method:"POST",body:s,duplex:"half"});if(Na.isFormData(s)&&(e=n.headers.get("content-type"))&&d.setContentType(e),n.body){const[e,t]=mo(f,ho(po(l)));s=ko(n.body,65536,e,t)}}Na.isString(u)||(u=u?"include":"omit");const i="credentials"in Request.prototype;m=new Request(t,S(C({},h),{signal:p,method:n.toUpperCase(),headers:d.normalize().toJSON(),body:s,duplex:"half",credentials:i?u:void 0}));let a=yield fetch(m,h);const o=Ao&&("stream"===c||"response"===c);if(Ao&&(r||o&&g)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=a[t]});const t=Na.toFiniteNumber(a.headers.get("content-length")),[n,s]=r&&mo(t,ho(po(r),!0))||[];a=new Response(ko(a.body,65536,n,()=>{s&&s(),g&&g()}),e)}c=c||"text";let v=yield Mo[Na.findKey(Mo,c)||"text"](a,e);return!o&&g&&g(),yield new Promise((t,n)=>{uo(t,n,{data:v,headers:oo.from(a.headers),status:a.status,statusText:a.statusText,config:e,request:m})})}catch(v){if(g&&g(),v&&"TypeError"===v.name&&/Load failed|fetch/i.test(v.message))throw Object.assign(new Ia("Network Error",Ia.ERR_NETWORK,e,m),{cause:v.cause||v});throw Ia.from(v,v&&v.code,e,m)}}))};Na.forEach(Lo,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const Oo=e=>`- ${e}`,Do=e=>Na.isFunction(e)||null===e||!1===e,Fo=e=>{e=Na.isArray(e)?e:[e];const{length:t}=e;let n,s;const i={};for(let a=0;a`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new Ia("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Oo).join("\n"):" "+Oo(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return s};function qo(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new co(null,e)}function Uo(e){qo(e),e.headers=oo.from(e.headers),e.data=ro.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Fo(e.adapter||eo.adapter)(e).then(function(t){return qo(e),t.data=ro.call(e,e.transformResponse,t),t.headers=oo.from(t.headers),t},function(t){return lo(t)||(qo(e),t&&t.response&&(t.response.data=ro.call(e,e.transformResponse,t.response),t.response.headers=oo.from(t.response.headers))),Promise.reject(t)})}const Ho="1.10.0",Bo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Bo[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const zo={};Bo.transitional=function(e,t,n){return(s,i,a)=>{if(!1===e)throw new Ia(function(e,t){return"[Axios v"+Ho+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}(i," has been removed"+(t?" in "+t:"")),Ia.ERR_DEPRECATED);return t&&!zo[i]&&(zo[i]=!0),!e||e(s,i,a)}},Bo.spelling=function(e){return(e,t)=>!0};const Go={assertOptions:function(e,t,n){if("object"!=typeof e)throw new Ia("options must be an object",Ia.ERR_BAD_OPTION_VALUE);const s=Object.keys(e);let i=s.length;for(;i-- >0;){const a=s[i],o=t[a];if(o){const t=e[a],n=void 0===t||o(t,a,e);if(!0!==n)throw new Ia("option "+a+" must be "+n,Ia.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Ia("Unknown option "+a,Ia.ERR_BAD_OPTION)}},validators:Bo},$o=Go.validators;let Wo=class{constructor(e){this.defaults=e||{},this.interceptors={request:new za,response:new za}}request(e,t){return A(this,null,function*(){try{return yield this._request(e,t)}catch(n){if(n instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{n.stack?t&&!String(n.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(n.stack+="\n"+t):n.stack=t}catch(s){}}throw n}})}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=bo(this.defaults,t);const{transitional:n,paramsSerializer:s,headers:i}=t;void 0!==n&&Go.assertOptions(n,{silentJSONParsing:$o.transitional($o.boolean),forcedJSONParsing:$o.transitional($o.boolean),clarifyTimeoutError:$o.transitional($o.boolean)},!1),null!=s&&(Na.isFunction(s)?t.paramsSerializer={serialize:s}:Go.assertOptions(s,{encode:$o.function,serialize:$o.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Go.assertOptions(t,{baseUrl:$o.spelling("baseURL"),withXsrfToken:$o.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let a=i&&Na.merge(i.common,i[t.method]);i&&Na.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=oo.concat(a,i);const o=[];let r=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(r=r&&e.synchronous,o.unshift(e.fulfilled,e.rejected))});const l=[];let c;this.interceptors.response.forEach(function(e){l.push(e.fulfilled,e.rejected)});let d,u=0;if(!r){const e=[Uo.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,l),d=e.length,c=Promise.resolve(t);u{Vo[t]=e});const Qo=function e(t){const n=new Wo(t),s=Bi(Wo.prototype.request,n);return Na.extend(s,Wo.prototype,n,{allOwnKeys:!0}),Na.extend(s,n,null,{allOwnKeys:!0}),s.create=function(n){return e(bo(t,n))},s}(eo);Qo.Axios=Wo,Qo.CanceledError=co,Qo.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;const s=new Promise(e=>{n.subscribe(e),t=e}).then(e);return s.cancel=function(){n.unsubscribe(t)},s},e(function(e,s,i){n.reason||(n.reason=new co(e,s,i),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},Qo.isCancel=lo,Qo.VERSION=Ho,Qo.toFormData=Da,Qo.AxiosError=Ia,Qo.Cancel=Qo.CanceledError,Qo.all=function(e){return Promise.all(e)},Qo.spread=function(e){return function(t){return e.apply(null,t)}},Qo.isAxiosError=function(e){return Na.isObject(e)&&!0===e.isAxiosError},Qo.mergeConfig=bo,Qo.AxiosHeaders=oo,Qo.formToJSON=e=>Za(Na.isHTMLForm(e)?new FormData(e):e),Qo.getAdapter=Fo,Qo.HttpStatusCode=Vo,Qo.default=Qo;const{Axios:Ko,AxiosError:Yo,CanceledError:Jo,isCancel:Xo,CancelToken:Zo,VERSION:er,all:tr,Cancel:nr,isAxiosError:sr,spread:ir,toFormData:ar,AxiosHeaders:or,HttpStatusCode:rr,formToJSON:lr,getAdapter:cr,mergeConfig:dr}=Qo,ur=e=>{const t=(e=>{const{url:t,headers:n}=e;null==t||t.indexOf(an),n.getAccept()||n.set("Accept","application/json"),n.getContentType()||n.set("Content-Type","application/json"),n.set("Version","0.2.67");let s="h5";Ys()&&(s="web"),Js()&&(s="app"),si()&&(s="desktop"),n.set("source",s);const i=localStorage.getItem("token");return i&&!["web","h5"].includes(s)&&n.set("Authorization",`Bearer ${i}`),n.get("X-Request-Id")||n.set("X-Request-Id",Fe()),["web","h5"].includes(s)&&n.has("Authorization")&&n.delete("Authorization"),!xR()||["web","h5"].includes(s)||n.has("Authorization")||n.set("Authorization",`Bearer ${xR()}`),n.set("Timezone",(new Date).toString().replace(/\s*\(.+\)$/,"")),C({},e)})(e);return C({},t)},hr=e=>{var t,n;if(!e.currentId)return!1;const s=e.messages[e.currentId];if("assistant"!==(null==s?void 0:s.role))return!1;const i=null==s?void 0:s.content_list;if(!Array.isArray(i))return!1;const a=null==(t=i.slice(-1))?void 0:t[0];return(null==a?void 0:a.phase)===wt.LOCAL_TOOL&&(null==(n=null==a?void 0:a.extra)?void 0:n.local_mcp)},mr=[{name:"Fetch",type:"stdio",params:{command:"uvx",args:["mcp-server-fetch"]},description:"This server enables large language models to retrieve and process content from web pages, and convert HTML to markdown for easier use."},{name:"Filesystem",type:"stdio",params:{command:"npx",args:["-y","@modelcontextprotocol/server-filesystem@latest","/Users"]},description:"A model context protocol (MCP) implemented for file system operations."},{name:"Sequential-Thinking",type:"stdio",params:{command:"npx",args:["-y","@modelcontextprotocol/server-sequential-thinking"]},description:"An MCP server implementation that provides tools for dynamic and reflective problem-solving through a structured thinking process."}],pr=()=>mr.map(({name:e,type:t,params:n,description:s})=>({id:Fe(),name:e,description:s,type:t,params:n,enabled:!1,default:!0,connectionStatus:"failed",errorMessage:"",tools:[]})),gr=it(),fr="LOCAL_MCP_SERVER",vr={initDefaultMCPServers:()=>{const e=vr.getMCPServers(),t=e.filter(e=>!!e.default),n=e.filter(e=>!e.default),s=pr();return s.forEach(e=>{t.find(t=>{t.name===e.name&&(e.id=t.id,e.enabled=t.enabled,e.connectionStatus=t.connectionStatus,e.tools=t.tools)})}),window.localStorage.setItem(fr,JSON.stringify([...s,...n])),s},getMCPServer:e=>{const t=vr.getMCPServers(),n=t.findIndex(t=>t.name===e);return t[n]},getMCPServerById:e=>{const t=vr.getMCPServers(),n=t.findIndex(t=>t.id===e);return t[n]},getMCPServers:()=>JSON.parse(window.localStorage.getItem(fr)||"[]"),getEnabledServers:()=>vr.getMCPServers().filter(e=>e.enabled),getFormatAvailableServerMap:()=>vr.getEnabledServers().filter(e=>"available"===e.connectionStatus).reduce((e,t)=>{const n=t.tools.reduce((e,t)=>t?S(C({},e),{[t.name]:{description:t.description,input_schema:t.inputSchema}}):e,{});return S(C({},e),{[t.name]:n})},{}),addMCPServer:e=>{const t=vr.getMCPServers();t.push(e),window.localStorage.setItem(fr,JSON.stringify(t))},removeMCPServer:e=>{const t=vr.getMCPServers(),n=t.findIndex(t=>t.id===e);n>-1&&t.splice(n,1),window.localStorage.setItem(fr,JSON.stringify(t))},updateMCPServer:(e,t)=>{const n=vr.getMCPServers(),s=n.findIndex(t=>t.id===e);s>-1&&(Object.assign(n[s],t),window.localStorage.setItem(fr,JSON.stringify(n)))}},yr=e=>{const t=e.match(/Error invoking remote method '.+': (.*)/);let n=(null==t?void 0:t[1])||e||"Tool call failed";return vr.getMCPServers().forEach(e=>{n.includes(e.id)&&(n=n.replace(e.id,e.name))}),n},br={connect:(...e)=>A(null,[...e],function*(e=[]){const t=[];if(!si())return t;const n=vr.getEnabledServers(),s=[];e.length?s.push(...n.filter(t=>e.includes(t.name))):s.push(...n.filter(e=>"failed"!==e.connectionStatus));const i=s.reduce((e,t)=>{const{type:n,name:s,params:i}=t;return S(C({},e),{[s]:S(C({name:s},i),{transportType:n})})},{});try{yield window.electronAPI.mcp_client_update_config(i);const e=[],n=[];s.forEach(t=>{e.push(t.id),n.push(window.electronAPI.mcp_client_tool_list(t.name))});(yield Promise.allSettled(n)).forEach((n,s)=>{var i;const{status:a}=n;if("fulfilled"===a&&n.value.tools&&Array.isArray(n.value.tools))vr.updateMCPServer(e[s],{tools:n.value.tools,connectionStatus:"available"});else{const o=vr.getMCPServerById(e[s]);if(o){const r="rejected"===a?null==(i=n.reason)?void 0:i.message:gr.t("Failed to connect to the MCP server.");vr.updateMCPServer(e[s],{connectionStatus:"failed",errorMessage:yr(r||"")}),t.push(o)}}})}catch(a){t.push(...s)}return t}),isAvailable:e=>A(null,null,function*(){if(!si())return;const{id:t,type:n,name:s,params:i}=e,a={connectionStatus:"connecting",errorMessage:""};try{const e={[s]:S(C({},i),{transportType:n})};yield window.electronAPI.mcp_client_update_config(e);const{tools:o}=yield window.electronAPI.mcp_client_tool_list(s),r=Array.isArray(o)?"available":"failed";a.connectionStatus=r,"available"===r?vr.updateMCPServer(t,{tools:o}):a.errorMessage=gr.t("Failed to connect to the MCP server.")}catch(o){a.connectionStatus="failed",a.errorMessage=yr((null==o?void 0:o.message)||"")}vr.updateMCPServer(t,a)}),callTool:e=>A(null,null,function*(){if(si())try{return yield window.electronAPI.mcp_client_tool_call(e)}catch(t){return{content:yr((null==t?void 0:t.message)||"")}}})},xr=C(C({},vr),br),wr=e=>A(null,null,function*(){if(wR())return;const{onlyLocal:t,updateData:n}=e||{},s=Jh.getState().settings,i=Jh.getState().mcpSettingList,a=Jh.getState().setMcpSettingList,o=Jh.getState().setSettings;if(t){const e=i.filter(e=>!e.type);a([...xr.getMCPServers(),...e])}else if(n){const e=i.findIndex(e=>e.id===n.id),t=ke({},i[e],n),r=[...i];if(r[e]=t,a(r),!t.type&&"enabled"in n){const{success:e,data:t}=yield UM(S(C({},s),{mcp:S(C({},s.mcp),{[n.id]:n.enabled})}));e&&o(t)}}else{const e=xr.initDefaultMCPServers();if(location.pathname.includes("settings"))for(let n=0;n{var n,i,a,o;return{id:e,name:(null==(n=t.data[e])?void 0:n.name)||"",description:(null==(i=t.data[e])?void 0:i.description)||"",tools:((null==(a=t.data[e])?void 0:a.tools)||[]).map(e=>Object.keys(e).map(t=>{var n;return{name:t,description:(null==(n=e[t])?void 0:n.description)||""}})[0]),enabled:(null==(o=null==s?void 0:s.mcp)?void 0:o[e])||!1,connectionStatus:"available"}});a([...xr.getMCPServers(),...e])}}}),_r=(e,t,n)=>{var s;if(null===e)return[];const i=null!=n?n:new Set;if(i.has(e))return[];i.add(e);const a=null==(s=null==t?void 0:t.messages)?void 0:s[e];return a?(null==a?void 0:a.parentId)?[..._r(a.parentId,t,i),a]:[a]:[]},Cr=e=>[wt.IMAGE_EDIT_TOOL,wt.IMAGE_GEN_TOOL].includes(e),Sr=e=>{const t=e.content_list;if(!t)return e;const n=[wt.ANSWER,wt.SLIDES],s=[wt.THINK,wt.THINKING_SUMMARY];let i=0;return t.forEach((e,a)=>{var o,r,l;const c=t[a-1],d="function"===e.role||!!e.function_id;(0!==a&&(n.includes(e.phase)||n.includes(null==(o=t[a-1])?void 0:o.phase))||d&&"answer"===(null==(r=e.extra)?void 0:r.display_position)&&!Cr(e.phase)||"answer"===(null==(l=null==c?void 0:c.extra)?void 0:l.display_position)&&!Cr(c.phase)&&s.includes(e.phase))&&i++,e.groupIndex=i}),e},kr=e=>{const t=Object.values(e.messages||{}),n=t.find(t=>t.id===e.currentId);let s=(null==n?void 0:n.chat_type)||yt.Txt2Txt;return t.forEach(e=>{e.fid=e.fid||e.id||"",e.parentId=e.parentId||e.parent_id||null}),t.forEach(e=>{e.childrenIds=t.filter(t=>t.parentId===e.id).map(e=>e.id||"")}),t.forEach(e=>{if(e.parentId){const n=t.find(t=>t.id===e.parentId);n&&(!e.extra&&n.extra&&(e.extra=n.extra),!e.feature_config&&n.feature_config&&(e.feature_config=n.feature_config))}}),t.forEach(e=>{var t,n,s,i,a,o;(null==(s=null==(n=null==(t=e.content_list)?void 0:t[0])?void 0:n.extra)?void 0:s.web_search_info)&&(e.webSearchInfo=null==(o=null==(a=null==(i=e.content_list)?void 0:i[0])?void 0:a.extra)?void 0:o.web_search_info)}),s===yt.Image2Video&&(s=yt.VideoGeneration),t.forEach(e=>{e.chat_type&&e.chat_type===yt.Image2Video&&(e.chat_type=yt.VideoGeneration,"assistant"===e.role&&(e.sub_chat_type=yt.VideoGeneration))}),(s===yt.VideoGeneration&&!(null==n?void 0:n.content)&&!(null==n?void 0:n.error)||hr(e))&&(n.done=!1),t.forEach(e=>{"assistant"===e.role&&Sr(e)}),S(C({},e),{messages:t.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{})})},jr=e=>{var t,n,s,i;const a=js.getState().history,o=a.messages[e||""];if(!o)return[];return(null!==(null==o?void 0:o.parentId)?null!=(s=null==(n=a.messages[null!=(t=o.parentId)?t:""])?void 0:n.childrenIds)?s:[]:null!=(i=Object.values(a.messages).filter(e=>null===e.parentId&&"user"===e.role).map(e=>e.id||e.fid))?i:[]).filter(e=>void 0!==e)},Tr=e=>{var t;const n=js.getState().history.messages[e];return(null==(t=null==n?void 0:n.models)?void 0:t.length)>1};var Er,Nr={exports:{}};var Ir,Ar=(Er||(Er=1,Ir=Nr,function(){function e(e,t){return void 0===t?t={autoBom:!1}:"object"!=typeof t&&(t={autoBom:!t}),t.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\ufeff",e],{type:e.type}):e}function t(e,t,n){var s=new XMLHttpRequest;s.open("GET",e),s.responseType="blob",s.onload=function(){o(s.response,t,n)},s.onerror=function(){},s.send()}function n(e){var t=new XMLHttpRequest;t.open("HEAD",e,!1);try{t.send()}catch(n){}return 200<=t.status&&299>=t.status}function s(e){try{e.dispatchEvent(new MouseEvent("click"))}catch(n){var t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),e.dispatchEvent(t)}}var i="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof q&&q.global===q?q:void 0,a=i.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),o=i.saveAs||("object"!=typeof window||window!==i?function(){}:"download"in HTMLAnchorElement.prototype&&!a?function(e,a,o){var r=i.URL||i.webkitURL,l=document.createElement("a");a=a||e.name||"download",l.download=a,l.rel="noopener","string"==typeof e?(l.href=e,l.origin===location.origin?s(l):n(l.href)?t(e,a,o):s(l,l.target="_blank")):(l.href=r.createObjectURL(e),setTimeout(function(){r.revokeObjectURL(l.href)},4e4),setTimeout(function(){s(l)},0))}:"msSaveOrOpenBlob"in navigator?function(i,a,o){if(a=a||i.name||"download","string"!=typeof i)navigator.msSaveOrOpenBlob(e(i,o),a);else if(n(i))t(i,a,o);else{var r=document.createElement("a");r.href=i,r.target="_blank",setTimeout(function(){s(r)})}}:function(e,n,s,o){if((o=o||open("","_blank"))&&(o.document.title=o.document.body.innerText="downloading..."),"string"==typeof e)return t(e,n,s);var r="application/octet-stream"===e.type,l=/constructor/i.test(i.HTMLElement)||i.safari,c=/CriOS\/[\d]+/.test(navigator.userAgent);if((c||r&&l||a)&&"undefined"!=typeof FileReader){var d=new FileReader;d.onloadend=function(){var e=d.result;e=c?e:e.replace(/^data:[^;]*;/,"data:attachment/file;"),o?o.location.href=e:location=e,o=null},d.readAsDataURL(e)}else{var u=i.URL||i.webkitURL,h=u.createObjectURL(e);o?o.location=h:location.href=h,o=null,setTimeout(function(){u.revokeObjectURL(h)},4e4)}});i.saveAs=o.saveAs=o,Ir.exports=o}()),Nr.exports);const Mr=U(Ar),Rr=nt({__proto__:null,default:Mr},[Ar]),Pr=(e,t)=>A(null,null,function*(){var n;const s=new File([e],t,{lastModified:(new Date).getTime()}),i=yield(e=>A(null,null,function*(){const t=new FormData;t.append("file",e);let n=null;const s=yield TM(`${ot}/files/`,{method:"POST",data:t}).then(e=>A(null,null,function*(){if(!e.ok)throw yield e.json();return e.json()})).catch(e=>(n=e.detail,null));if(n)throw n;return s}))(s);if(i.error)throw i.error;const a=`${ot}/files/${i.id}/content`;null==(n=window.open(a,"_self"))||n.focus()}),Lr=e=>{if(null==e)return"Unknown size";if("number"!=typeof e||e<0)return"Invalid size";if(0===e)return"0 B";const t=["B","KB","MB","GB","TB"];let n=0;for(;e>=1024&&n`.${e}`);return e.push(...this.fileTypes),e}}class Dr extends Or{constructor(){super([...Qt,...zt],[...Bt,...Dt])}}class Fr extends Or{constructor(){super(Gt,Ft)}getAcceptSuffix(){let e=super.getAcceptSuffix();const t=["image/tiff",".tif",".tiff",".dib"],n=[".dib"];return zs()&&(e=e.filter(e=>!n.includes(e))),$s()&&(e=e.filter(e=>!t.includes(e))),e}}class qr extends Or{constructor(){super($t,qt)}}class Ur extends Or{constructor(){super(Wt,Ut)}}const Hr=e=>{let t,n=[];switch(e){case"document":t=new Dr,n=t.getAcceptSuffix();break;case"vision":t=new Fr,n=t.getAcceptSuffix();break;case"video":t=new qr,n=t.getAcceptSuffix();break;case"audio":t=new Ur,n=t.getAcceptSuffix();break;case"camera":n=["image/*"]}return n},Br=(e,t)=>{if("web"===e||!e)return"web";const n=LR(t||"");return n?zt.includes(n)?"txt":Qt.includes(n)?"doc":Wt.includes(n)?"audio":$t.includes(n)?"video":Gt.includes(n)?"vision":n:"web"},zr=e=>A(null,null,function*(){const t=e.chat.history;return _r(t.currentId,t).reduce((e,t)=>{var n;if("assistant"===t.role)if(t.content_list&&Array.isArray(t.content_list)){const e=null==(n=t.content_list)?void 0:n.find(e=>(null==e?void 0:e.phase)===wt.ANSWER||(null==e?void 0:e.phase)===wt.DEEPTHINKING);t.content=(null==e?void 0:e.content.replace(/\[\[\d+\]\]/g,""))||""}else t.content=t.content.replace(/\[\[\d+\]\]/g,"")||"";return`${e}### ${t.role.toUpperCase()}\n${t.content}\n\n`},"").trim()});function Gr(e,t,n=""){if(Ne(n))return e;if(Array.isArray(null==e?void 0:e.sortKeys)||(e.sortKeys=[]),t in e){if("string"==typeof n){const s="string"==typeof e[t]?e[t]:"";e[t]=s+n}else if(Ie(n)){const s=e[t]||{};e[t]=function(e,t){const n={};for(const s in C(C({},e),t))Object.prototype.hasOwnProperty.call(e,s)&&Object.prototype.hasOwnProperty.call(t,s)?n[s]=e[s]+t[s]:Object.prototype.hasOwnProperty.call(e,s)?n[s]=e[s]:n[s]=t[s];return n}(s,n)}}else e[t]=n,e.sortKeys.push(t);return e}const $r=(e=[],t)=>{const n=new Set(e.map(e=>e.url)),s=(null==t?void 0:t.filter(e=>!n.has(e.url)))||[];return[...e,...s]},Wr=(e,t)=>{const{query:n,index:s,status:i,phase:a}=t,o=Te(e);if(!s||s-1<0)return e;let r,l=o.findIndex(e=>e.index===s);const{id:c,query:d,learnings:u,researchGoal:h,webSites:m,pageContent:p,codeContent:g,searchContent:f}=n||{};-1===l?(r=S(C({},n),{index:s,status:i,phase:a}),l=o.length,o.push(r)):(r=o[l],Gr(r,"searchContent",f),Gr(r,"codeContent",g),Gr(r,"pageContent",p),Gr(r,"learnings",u),Gr(r,"researchGoal",h),Gr(r,"query","string"==typeof d?d:"")),(null==r?void 0:r.id)||(r.id=c),Ee(null==r?void 0:r.query)&&(r.query="");const v=Array.isArray(m)?m:null==m?void 0:m.webSites;return(null==r?void 0:r.webSites)?r.webSites=$r(r.webSites,v||[]):r.webSites=v,o[l]=S(C({},r),{status:i,phase:a}),o},Vr=(e,t)=>{const n=Te(e);return t.forEach(e=>{const{query:t,index:s,status:i,phase:a}=e;if(!s||s<1)return;const o=n.findIndex(e=>(null==e?void 0:e.index)===s);if(-1===o)return void n.push(e);const r=n[o];if("finished"===(null==r?void 0:r.status)||"WebResultFinished"===(null==r?void 0:r.status))return;const{id:l,query:c,learnings:d,researchGoal:u,webSites:h,pageContent:m,codeContent:p,searchContent:g}="object"==typeof t?t:e||{};Gr(r,"searchContent",g),Gr(r,"codeContent",p),Gr(r,"pageContent",m),Gr(r,"learnings",d),Gr(r,"researchGoal",u),Gr(r,"query","string"==typeof c?c:""),!(null==r?void 0:r.id)&&l&&(r.id=l);const f=Array.isArray(h)?h:null==h?void 0:h.webSites;f&&((null==r?void 0:r.webSites)?r.webSites=$r(r.webSites,f||[]):r.webSites=f),n[o]=S(C({},r),{status:i,phase:a})}),n},Qr=e=>{let t=e;return t===yt.Image2Video&&(t=yt.VideoGeneration),t};function Kr(){const e=document.getElementById("app-container");e&&!Js()&&(e.style.height=window.innerHeight+"px")}const Yr=()=>A(null,null,function*(){const{setCurrentChatPage:e}=js.getState();e(1),yield A(null,null,function*(){try{const e=js.getState().currentChatPage,t=ud.getState().sideBarSearchText,n=e,s=t,{data:i}=s?yield cg({text:s,page:n}):yield rg({page:n,exclude_project:!0});"ERR_NETWORK"!==(null==i?void 0:i.code)&&Ns.setState({chats:i})}catch(e){}})}),Jr=()=>A(null,null,function*(){const e=pw.getState().activeProjectId,t=pw.getState().setProjectExpandChats;if(!e)return;const n=yield dw(e,1);n&&n.success&&Array.isArray(n.data)&&t(n.data)}),Xr=e=>e.filter(e=>e.phase===wt.WEB_SEARCH).reduce((e,t)=>{var n;return e.push(...(null==(n=t.extra)?void 0:n.web_search_info)||[]),e},[]).map(e=>S(C({},e),{icon:e.hostlogo||e.icon,description:e.description||e.snippet})),Zr=e=>{var t,n,s;return null==(s=null==(n=null==(t=e.find(e=>e.phase===wt.ANSWER))?void 0:t.extra)?void 0:n.deep_research)?void 0:s.references},el=()=>{const e=location.pathname,t={[String("/"===e)]:{spmB:"29997169",pageId:`//${window.location.host}/`},[String("/c/new-chat"===e)]:{spmB:"29997170",pageId:`//${window.location.host}/c/new-chat`},[String("/c/new-branch"===e)]:{spmB:"29997171",pageId:`//${window.location.host}/c/new-branch`},[String("/c/guest"===e)]:{spmB:"29997172",pageId:`//${window.location.host}/c/guest`},[String(e.startsWith("/c/")&&"/c/new-branch"!==e&&"/c/new-chat"!==e&&"/c/guest"!==e)]:{spmB:"29997173",pageId:`//${window.location.host}/c/`},[String(e.startsWith("/s/deploy/"))]:{spmB:"26050403",pageId:`//${window.location.host}/s/deploy/`},[String(e.startsWith("/s/")&&!e.startsWith("/s/deploy/"))]:{spmB:"29997178",pageId:`//${window.location.host}/s/`},[String(e.startsWith("/p/"))]:{spmB:"41591450",pageId:`//${window.location.host}/p/`},[String("/community"===e)]:{spmB:"35530621",pageId:`//${window.location.host}/community`},[String("/library"===e)]:{spmB:"45702160",pageId:`//${window.location.host}/library`},[String("/community/"===e)]:{spmB:"35530621",pageId:`//${window.location.host}/community`},[String(e.startsWith("/community/t2v/"))]:{spmB:"35530766",pageId:`//${window.location.host}/community/t2v/`,community_type:"t2v"},[String(e.startsWith("/community/podcast/"))]:{spmB:"35530766",pageId:`//${window.location.host}/community/podcast/`,community_type:"podcast"},[String(e.startsWith("/community/webdev/"))]:{spmB:"35530766",pageId:`//${window.location.host}/community/webdev/`,community_type:"webdev"},[String(e.startsWith("/community/report/"))]:{spmB:"35530766",pageId:`//${window.location.host}/community/report/`,community_type:"pdf"},[String(e.startsWith("/community/t2i/"))]:{spmB:"35530766",pageId:`//${window.location.host}/community/t2i/`,community_type:"image"},[String(e.startsWith("/community/collections"))]:{spmB:"35530783",pageId:`//${window.location.host}/community/collections`},[String("/auth"===e)]:{spmB:"29997180",pageId:`//${window.location.host}/auth`},[String("/authorize"===e)]:{spmB:"30620387",pageId:`//${window.location.host}/authorize`},[String("/error"===e||e.startsWith("/error"))]:{spmB:"29997183",pageId:`//${window.location.host}/error`},[String("/legal-agreement/privacy-policy"===e||e.startsWith("/legal-agreement/privacy-policy"))]:{spmB:"29997187",pageId:`//${window.location.host}/legal-agreement/privacy-policy`},[String("/legal-agreement/terms-of-service"===e||e.startsWith("/legal-agreement/terms-of-service"))]:{spmB:"29997190",pageId:`//${window.location.host}/legal-agreement/terms-of-service`},[String("/forget"===e||e.startsWith("/forget"))]:{spmB:"29997194",pageId:`//${window.location.host}/forget`},[String("/reset"===e||e.startsWith("/reset"))]:{spmB:"29997199",pageId:`//${window.location.host}/reset`},[String(e.startsWith("/mobile/chat"))]:{spmB:"29997173",pageId:`//${window.location.host}/mobile/chat`},[String(e.startsWith("/settings/cookie-notice"))]:{spmB:"30233040",pageId:`//${window.location.host}/settings/cookie-notice`},[String(e.startsWith("/settings/general"))]:{spmB:"30233031",pageId:`//${window.location.host}/settings/general`},[String(e.startsWith("/settings/interface"))]:{spmB:"30233032",pageId:`//${window.location.host}/settings/interface`},[String(e.startsWith("/settings/privacy-policy"))]:{spmB:"29997187",pageId:`//${window.location.host}/settings/privacy-policy`},[String(e.startsWith("/settings/terms-of-service"))]:{spmB:"29997190",pageId:`//${window.location.host}/settings/terms-of-service`},[String(e.startsWith("/settings/model"))]:{spmB:"30233033",pageId:`//${window.location.host}/settings/model`},[String(e.startsWith("/settings/chats"))]:{spmB:"30233034",pageId:`//${window.location.host}/settings/chats`},[String(e.startsWith("/settings/personalization/memory"))]:{spmB:"30233038",pageId:`//${window.location.host}/settings/personalization/memory`},[String(e.startsWith("/settings/personalization/custom-instr"))]:{spmB:"30233039",pageId:`//${window.location.host}/settings/personalization/custom-instr`},[String("/settings/personalization"===e)]:{spmB:"30233035",pageId:`//${window.location.host}/settings/personalization`},[String(e.startsWith("/settings/account"))]:{spmB:"30233036",pageId:`//${window.location.host}/settings/account`},[String(e.startsWith("/settings/about"))]:{spmB:"30233037",pageId:`//${window.location.host}/settings/about`},[String(e.startsWith("/settings/languages"))]:{spmB:"30233051",pageId:`//${window.location.host}/settings/languages`},[String(e.startsWith("/settings/theme"))]:{spmB:"30233052",pageId:`//${window.location.host}/settings/theme`},[String(e.startsWith("/settings/voice"))]:{spmB:"30233053",pageId:`//${window.location.host}/settings/voice`},[String(e.startsWith("/settings/contact-us"))]:{spmB:"30233054",pageId:`//${window.location.host}/settings/contact-us`},[String(e.startsWith("/settings/change-password"))]:{spmB:"30233055",pageId:`//${window.location.host}/settings/change-password`},[String("/settings"===e)]:{spmB:"30233050",pageId:`//${window.location.host}/settings`}};return t.true||{spmB:"not exist",pageId:"not exist"}},tl=e=>{const t=window.location.search.slice(1);if(!t)return null;return new URLSearchParams(t).get(e)||null},nl=()=>window.userId||"";let sl=window.aes||null;const il=window.location.host;let al=[],ol=[],rl=null,ll=null,cl=null;const dl={"internal-qwenlm.alibaba-inc.com":"prod","chat.qwenlm.ai":"prod","qwenlm.ai":"prod","qwen.ai":"prod","chat.qwen.ai":"prod","qwenchat.com":"prod","pre-chat.qwenlm.ai":"pre","pre-qwenlm.alibaba-inc.com":"pre","pre-chat.qwen.ai":"pre","pre2-chat.qwen.ai":"pre","pre2-chat.qwenlm.ai":"pre","dev.aliyun.com":"dev"}[il]||"dev";rl=setInterval(()=>{if(sl){clearInterval(rl),ll=sl.use(window.AESPluginEvent),cl=sl.use(window.AESPluginPV,{autoPV:!1,enableHistory:!0});for(let e=0;e{const{params:n,aesParams:s}=t||{};sl&&ll?ll(e,S(C(C({c1:nl()},n),s),{c10:"0.2.67"})):al.push({eventId:e,params:C({c1:nl()},n)})},hl=e=>{var t,n,s,i;const a=window.aplus_queue||(window.aplus_queue=[]),o={};if(o.typarm1=Js()?"app":si()?"desktop":"pc"===Ws()?"web":"h5",o.typarm2=e||nl(),a.push({action:"aplus.setUserProfile",arguments:[{uidaplus:e||nl()}]}),o.typarm3=dl,o.typarm4="qwen_chat",o.typarm5=location.pathname.startsWith("/s/")?"share":"product",o.typarm6=location.pathname.startsWith("/community")?"community":"",o.orgid="tongyi",(null==(t=el())?void 0:t.pageId)===`//${window.location.host}/s/`){const e=location.pathname.replace(/\/s\//g,"");o.share_id=e.replace(/\//g,"")}else o.share_id="";if((null==(n=el())?void 0:n.pageId)===`//${window.location.host}/p/`){const e=location.pathname.replace(/\/p\//g,"");o.project_id=e.replace(/\//g,"")}else o.project_id="";return tl("qsrc")?o.channel_type=tl("qsrc"):o.channel_type="",(null==(s=el())?void 0:s.community_type)?o.community_type=null==(i=el())?void 0:i.community_type:o.community_type="","share"===tl("qsrc")&&tl("share_id")?o.from_id=tl("share_id"):o.from_id="",o.cdn_version="0.2.67",o},ml=(e,t)=>{const{params:n,paramsExtend:s}=t,{et:i}=n,a=hl(),o=C(C(C({},a),n),s);let r="";for(const c in o){const e=o[c];"et"!==c&&e&&(r+=`&${c}=${e}`)}let l=i;"OTHER"===i&&(l="self_define"),(window.aplus_queue||(window.aplus_queue=[])).push({action:"aplus.record",arguments:[`/tongyi-sg.qwen_chat.${e}`,l,r]})},pl=(e,t)=>{ml(e,t),ul(e,t)},gl=e=>{var t,n;if(((e="a2ty_o01")=>{const{spmB:t}=el()||{};if(!t)return;(window.aplus_queue||(window.aplus_queue=[])).push({action:"aplus.setPageSPM",arguments:[e,`${t}`]})})(),ti())return;(e=>{let t=hl(e);t=C({},t),(window.aplus_queue||(window.aplus_queue=[])).push({action:"aplus.appendMetaInfo",arguments:["aplus-cpvdata",t]})})(e||""),(window.aplus_queue||(window.aplus_queue=[])).push({action:"aplus.sendPV",arguments:[{is_auto:!1},{}]});const{spmB:s,pageId:i}=el()||{};var a;a=S(C({},hl(e)),{spmId:`a2ty_o01.${s}`,aemPageId:i,domain:il}),A(null,null,function*(){return yield TM("/users/status",{method:"POST",data:{typarms:a}})}),sl&&cl?cl.switchPage({page_id:null==(n=el())?void 0:n.pageId,dim1:e||""}):ol.push({userId:e||"",page_id:null==(t=el())?void 0:t.pageId})},fl=(e,t)=>{pl("reportDownload",{params:{et:"CLK"},aesParams:{c5:e||"",c6:t},paramsExtend:{msg_id:e||"",fileType:t}})},vl=["/api/chat/completions","/api/chats/new","/api/chat/completed","/api/v1/chats","/api/v1/chats/all/tags","/api/task/suggestions/completions","/api/v1/tasks/status","/api/v1/files/getstsToken","/api/task/title/completions","/api/task/tags/completions","/api/parse_url","/api/v2/chats","/api/v2/chat/completions","/api/v2/task/suggestions/completions","/api/v2/files/getstsToken","/api/v2/community","/api/v2/tts/completions","/api/v2/files/getfilelink","/api/v2/files/parse","/api/v2/files/parse/status"],yl=e=>new Promise(t=>{setTimeout(t,e)}),bl=()=>{var e,t,n;return null==(n=null==(t=null==(e=window.__baxia__)?void 0:e.getFYModule)?void 0:t.getUidToken)?void 0:n.call(t)},xl=()=>{var e;return window.baxiaCommon&&(null==(e=window.__baxia__)?void 0:e.baxiaPromptInit)&&window.baxiaInitialized&&!!bl()},wl=()=>A(null,null,function*(){var e;window.baxiaCommon&&(null==(e=window.__baxia__)?void 0:e.baxiaPromptInit)&&(UR("111-initBaixa begin"),window.baxiaCommon.init({appendTo:"header",uabOptions:{location:"sea"},checkApiPath:function(e){return vl.some(t=>e.indexOf(t)>-1)},showCallback:function(){pl("showBaxiaCaptchaModal",{params:{et:"EXP"}})},hideCallback:function(e){pl("hideBaxiaCaptchaModal",{params:{et:"OTHER"},aesParams:{c4:e?"success":"fail"},paramsExtend:{validateStatus:e?"success":"fail"}})},paramstype:["uab","umid"],autoSize:!0}),ti()&&(window.baxiaNeedDelay=!0,yield yl(1500),window.baxiaNeedDelay=!1),window.baxiaInitialized=!0,UR("111-initBaixa end"))}),_l=()=>A(null,null,function*(){var e;if(window.baxiaCommon&&(null==(e=window.__baxia__)?void 0:e.baxiaPromptInit))return window.baxiaInitialized||(yield wl()),!0;{UR("111-loadBaxiaJS start");const e=new Promise(e=>{try{!function(e,t){var n;const s="script",i=document.getElementsByTagName(s)[0],a=document.createElement(s);if(a.async=!0,a.src=e,a.crossOrigin="anonymous",t){let e=!1;a.onload=function(){e||(a.onload=null,e=!0,t("success"))}}a.onerror=function(){t("error")},null==(n=i.parentNode)||n.insertBefore(a,i)}("https://assets.alicdn.com/g/??/AWSC/AWSC/awsc.js,/sd/baxia-entry/baxiaCommon.js",t=>{UR("111-load Baxia JS callback",t),e(!0)})}catch(t){UR("111-loadJS threw",String(t)),e(!0)}}),t=yl(3e3).then(()=>(UR("111-loadBaxiaJS timeout"),!0));return yield Promise.race([e,t])}});let Cl=null;const Sl=()=>xl()?Promise.resolve(!0):Cl||(Cl=kl().finally(()=>{Cl=null}),Cl),kl=()=>A(null,null,function*(){let e=0;const t=()=>A(null,null,function*(){var n,s;return e++,UR("111-poll",String(e),String(!!window.baxiaCommon),String(!!(null==(n=window.__baxia__)?void 0:n.baxiaPromptInit)),String(!!window.baxiaInitialized),String(!!bl())),!!xl()||(window.baxiaCommon&&(null==(s=window.__baxia__)?void 0:s.baxiaPromptInit)&&!window.baxiaInitialized?window.baxiaNeedDelay?(yield yl(1500),yield t()):(UR("111-initBaxiaConfig"),yield wl(),yield t()):e>15&&e<30&&!window.baxiaCommon?(UR("111-loadBaxiaJS attempt",String(e)),yield _l(),yield t()):e>=30?(UR("111-poll give up",String(e)),!0):(yield yl(200),yield t()))});return t()}),jl=(e,t,n)=>A(null,null,function*(){try{return yield TM("/files/share_url",{method:"POST",headers:{"Content-Type":"application/json",authorization:localStorage.token?`Bearer ${localStorage.token}`:"Bearer"},data:{file_source:e,cdn_url:t,file_id:n},baseURL:ot})}catch(s){}return null}),Tl=e=>!!e.includes("/api/v1/files"),El=e=>!!e.includes("?key="),Nl=e=>!!e.includes("x-oss-expires"),Il=(e,t,n)=>A(null,null,function*(){let s;if("user"===e){if(!Tl(t))return t;s=yield jl("upload","",n)}else{if(El(t))return t;s=yield jl("generate",t,"")}return(null==s?void 0:s.url)||""}),Al=(e,t)=>{e.forEach(e=>{const t=e.substring(e.lastIndexOf("/")+1);try{const n=document.createElement("a");n.href=e,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),e.startsWith("blob:")&&window.URL.revokeObjectURL(e)}catch(n){}})},Ml=e=>A(null,null,function*(){return yield fetch(e).then(e=>e.blob()).then(e=>{const t=window.URL.createObjectURL(e);try{return Al([t]),!0}catch(n){return!1}}).catch(e=>!1)});let Rl=!1;const Pl=e=>A(null,[e],function*({role:e="",url:t,isFile:n=!1,errorTexts:s}){if(!t&&s)return vi.openOnce({type:"error",content:(null==s?void 0:s.urlError)||KR("Download failed: url error")}),!1;try{if(Tl(t))t.startsWith("https://")||(t=`${t}/content`);else if(Nl(t)){const{success:e,data:n}=yield RM({fileUrl:t});if(!e||!(null==n?void 0:n.fileUrl))return!1;t=n.fileUrl}else{El(t)||(t=yield Il(e,t));const n=new URL(t);n.searchParams.append("download","true"),n.searchParams.append("timestamp",Date.now().toString()),t=n.toString()}if(!Rl&&Js()){if(n)return!1;Rl=!0}if(!(yield(e=>A(null,null,function*(){try{const t=yield fetch(e);if(!t.ok)throw new Error(t.statusText);return!0}catch(t){return!1}}))(t)))return vi.openOnce({type:"error",content:KR("Download failed")}),!1;const s=document.createElement("a");s.href=t;const i=null==t?void 0:t.toString().match(/[^/\\?]+(?=\?|$)/),a=i?decodeURIComponent(i[0]):null;return a&&(s.download=a),document.body.appendChild(s),s.click(),t.startsWith("blob:")&&window.URL.revokeObjectURL(t),document.body.removeChild(s),!0}catch(i){return s&&vi.openOnce({type:"error",content:(null==s?void 0:s.downloadError)||KR("Download failed")}),!1}}),Ll=(e,t="web")=>{if(e){if(ti()){if("web"!==t){if(!e){const e=it();return void vi.openOnce({type:"error",content:e.t("Download failed: url error")})}try{Pl({url:e,errorTexts:!0})}catch(n){const e=it();vi.openOnce({type:"error",content:e.t("Download failed")})}return}const s=`qwen://web?url=${encodeURIComponent(e)}`;bM.adapter.invoke({method:"openWindow",params:{uri:s}})}si()?bM.adapter.openWindow(e):window.open(e,"_blank")}},Ol=(e,t)=>wR()?e:t?"temporary":e,Dl=e=>{var t;return(null==(t=(e?Object.values(e||{}):[]).filter(e=>"assistant"===e.role&&e.sub_chat_type===yt.Podcast))?void 0:t.length)||0},Fl=e=>{var t,n;const{currentResponseIds:s,messages:i,currentId:a}=e,o=(null!=s?s:[]).filter(e=>{const t=i[e];return"assistant"===(null==t?void 0:t.role)&&!t.done}),r=null!=(n=null==(t=_r(a,e))?void 0:t.filter(e=>"assistant"===e.role&&!e.done).map(e=>e.id).filter(Boolean))?n:[];return[...new Set([...o,...r])]},ql=e=>Fl(e).length>0;let Ul=!1;const Hl=(e,t={})=>{var n,s;const i="system"===(a=e)?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":a;var a;Ul="system"===e,si()&&(null==(n=null==window?void 0:window.electronAPI)?void 0:n.switch_theme)&&(null==(s=null==window?void 0:window.electronAPI)||s.switch_theme(e)),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(i);let o=e;"system"===e&&(o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),ud.setState({theme:e,realTheme:o});const{isPersistence:r=!0}=t;localStorage&&r&&(localStorage.theme=e),i&&yR("qwen-theme",i)};window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",()=>{Ul&&Hl("system")});const Bl=e=>{let t=null;switch(e){case"loading":t=F.jsx(pi,{type:"icon-jiazaizhong",className:"qwen-message-icon"});break;case"error":t=F.jsx(pi,{type:"icon-line-x-circle-contained",className:"qwen-message-icon"});break;case"caution":case"info":case"warning":t=F.jsx(pi,{type:"icon-line-alert-circle",className:"qwen-message-icon"});break;case"success":t=F.jsx(pi,{type:"icon-line-check-contained1",className:"qwen-message-icon"});break;default:t=F.jsx(F.Fragment,{})}return t},zl=({type:e="info",content:t,duration:n=3e3,onCancel:s,hideIcon:i,className:a="",style:o=""})=>{const r=`qwen-message-${Date.now()}`,l=`${o}`,c=`qwen-design-message qwen-design-message-${e} ${a}`,d=F.jsxs("div",{className:"qwen-message-content",children:[F.jsxs("div",{className:"qwen-message-content-text",children:[t," "]}),s&&F.jsx(pi,{type:"icon-close-4",className:"qwen-message-content-close-icon",onClick:()=>{V.destroy(r),s&&s()}})]});(V[e]||V.info)({content:d,icon:i?F.jsx(F.Fragment,{}):Bl(e),duration:n/1e3,key:r,className:c,style:l})},Gl={open:zl,openOnce:e=>{V.destroy(),zl(e)}};const $l=e=>new Promise(t=>{setTimeout(t,e)});function Wl(e,t,n){return e().then(e=>(function(e){if(!e||void 0===e.default)throw new Error("Chunk loaded but default export is missing — possible CDN or cache issue")}(e),e)).catch(s=>{if(t<=0)throw s;return new Promise(s=>setTimeout(()=>s(Wl(e,t-1,n)),n))})}function Vl(e,t=2,n=1500){return D.lazy(()=>Wl(e,t,n))}var Ql={d:(e,t)=>{for(var n in t)Ql.o(t,n)&&!Ql.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},Kl={};Ql.d(Kl,{A:()=>Zl,k:()=>Xl});var Yl=function(e,t,n,s){return new(n||(n=Promise))(function(t,i){function a(e){try{r(s.next(e))}catch(t){i(t)}}function o(e){try{r(s.throw(e))}catch(t){i(t)}}function r(e){var s;e.done?t(e.value):(s=e.value,s instanceof n?s:new n(function(e){e(s)})).then(a,o)}r((s=s.apply(e,[])).next())})},Jl=function(e,t){var n,s,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:r(0),throw:r(1),return:r(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function r(r){return function(l){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,r[0]&&(o=0)),o;)try{if(n=1,s&&(i=2&r[0]?s.return:r[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,r[1])).done)return i;switch(s=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return o.label++,{value:r[1],done:!1};case 5:o.label++,s=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]{try{const r=await navigator.storage.getDirectory(),f=await(await r.getFileHandle('_',{create:true})).createSyncAccessHandle(),b=new Uint8Array(1);let m=1/0;for(let i=0;i<3;i++){f.write(b,{at:0});const s=performance.now();f.flush();const dt=performance.now()-s;if(dt>>3,c=-1===s?3:0;for(i=0;i>>2,r.length<=a&&r.push(0),r[a]|=e[i]<<8*(c+s*(o%4));return{value:r,binLen:8*e.length+n}}function ac(e,t,n){switch(t){case"UTF8":case"UTF16BE":case"UTF16LE":break;default:throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE")}switch(e){case"HEX":return function(e,t,s){return function(e,t,n,s){let i,a,o,r;if(0!=e.length%2)throw new Error("String of HEX type must be in byte increments");const l=t||[0],c=(n=n||0)>>>3,d=-1===s?3:0;for(i=0;i>>1)+c,o=r>>>2;l.length<=o;)l.push(0);l[o]|=a<<8*(d+s*(r%4))}return{value:l,binLen:4*e.length+n}}(e,t,s,n)};case"TEXT":return function(e,s,i){return function(e,t,n,s,i){let a,o,r,l,c,d,u,h,m=0;const p=n||[0],g=(s=s||0)>>>3;if("UTF8"===t)for(u=-1===i?3:0,r=0;ra?o.push(a):2048>a?(o.push(192|a>>>6),o.push(128|63&a)):55296>a||57344<=a?o.push(224|a>>>12,128|a>>>6&63,128|63&a):(r+=1,a=65536+((1023&a)<<10|1023&e.charCodeAt(r)),o.push(240|a>>>18,128|a>>>12&63,128|a>>>6&63,128|63&a)),l=0;l>>2;p.length<=c;)p.push(0);p[c]|=o[l]<<8*(u+i*(d%4)),m+=1}else for(u=-1===i?2:0,h="UTF16LE"===t&&1!==i||"UTF16LE"!==t&&1===i,r=0;r>>8),d=m+g,c=d>>>2;p.length<=c;)p.push(0);p[c]|=a<<8*(u+i*(d%4)),m+=2}return{value:p,binLen:8*m+s}}(e,t,s,i,n)};case"B64":return function(e,t,s){return function(e,t,n,s){let i,a,o,r,l,c,d,u=0;const h=t||[0],m=(n=n||0)>>>3,p=-1===s?3:0,g=e.indexOf("=");if(-1===e.search(/^[a-zA-Z0-9=+/]+$/))throw new Error("Invalid character in base-64 string");if(e=e.replace(/=/g,""),-1!==g&&g\n
${s.t("{{ capability }}",{capability:s.t(e)})}\n
\n
${cu(t,n,s)}
\n
`)(n,e,t,i):cu(e,t,i),uu=e=>{if(!e||"{}"===JSON.stringify(e))return{};const{image_max_count:t,video_max_count:n,audio_max_count:s,doc_max_count:i,image_max_size:a,video_max_size:o,audio_max_size:r,doc_max_size:l,default_max_size:c,audio_max_duration:d,video_max_duration:u}=e;return{[Xt.DEFAULT]:{max_size:c},[Xt.DOC]:{max_count:i,max_size:l},[Xt.VIDEO]:{max_count:n,max_size:o,max_duration:u},[Xt.IMAGE]:{max_count:t,max_size:a},[Xt.AUDIO]:{max_count:s,max_size:r,max_duration:d}}},hu=(e,t)=>new Promise(n=>{const s=new Image;s.onload=()=>{t||setTimeout(()=>{hu(e,320)},100),n(!0)},s.onerror=s.onabort=()=>n(!1);const i=t||100,a=`x-oss-process=image/resize,m_mfit,w_${i},h_${i}`;e.includes("qwen-webui")?s.src=e:e.includes("?")?s.src=e+`&${a}`:s.src=e+`?${a}`}),mu={mp4:"video/mp4",avi:"video/avi",wmv:"video/x-ms-wmv",flv:"video/x-flv",mkv:"video/x-matroska",mov:"video/quicktime",md:"text/markdown"};let pu=null;const gu=2097152;const fu=new class{constructor(){j(this,"uploadTask",{}),j(this,"execUpload",e=>A(this,null,function*(){var t,n,s,i;const a=this.uploadTask[e];if(a)try{this.uploadTask[e].status="uploading";const{file:i,client:o,checkPoint:r,parallel:l,partSize:c,ossToken:d}=a,{filePath:u}=d,h=r?{checkpoint:r}:{parallel:l,partSize:c};i.size{var s;if(this.uploadTask[e]){const i=Math.round(100*t);this.uploadTask[e].progress=i,null==(s=a.onUploadProgress)||s.call(a,i),this.uploadTask[e].checkPoint=n}}})).catch(e=>{if(!(null==e?void 0:e.name)||"cancel"!==e.name)throw e});const m=null!=(n=null!=(t=a.resumeTime)?t:a.startTime)?n:0,p=a.resumeTime?"resume":"start",g=qR();if(a.successTime=g,this.sendTrackEvent("finishUpload",{c4:m||0,c5:g,c6:(g||0)-(m||0),c7:p,taskId:e}),yield null==(s=a.onUploadSuccess)?void 0:s.call(a,d.fileId,d.fileCDNUrl),!a.onGreenNetFinish)return void delete this.uploadTask[e];this.uploadTask[e].status="uploadSuccess",this.execGreenNetCheck(e)}catch(o){const t=o instanceof Error?o:new Error(String(o));null==(i=a.onUploadFailed)||i.call(a,t),pl("uploadFileError",{params:{et:"OTHER",c5:e,c6:o instanceof Error?o.message:String(o),c7:String(o)}}),this.uploadTask[e].status="uploadError"}})),j(this,"execGreenNetCheck",e=>A(null,null,function*(){})),j(this,"getParallelParams",e=>e<5242880?{parallel:2,partSize:gu}:e<10485760?{parallel:4,partSize:gu}:e<52428800?{parallel:6,partSize:6291456}:e<104857600?{parallel:8,partSize:8388608}:{parallel:10,partSize:10485760}),j(this,"getFileType",e=>{const{type:t}=e;let n="file";return t.startsWith("video")&&(n="video"),t.startsWith("image")&&(n="image"),t.startsWith("audio")&&(n="audio"),n}),j(this,"sendTrackEvent",(e,t={})=>{try{const n=t,{taskId:s=""}=n,i=k(n,["taskId"]);let a;if(s&&this.uploadTask[s]){const{file:e}=this.uploadTask[s],{name:t,size:n,type:i}=e;a={filename:t,filesize:n,filetype:i}}ul(`FileUpload-${e}`,{params:C(C({et:"OTHER"},i),a?{c8:a}:{})})}catch(n){}}),j(this,"getTaskItem",e=>this.uploadTask[e])}uploadFileToOss(e,t){const n=Fe(),{name:s,size:i,type:a}=e,o=this.getFileType(e);return(e=>A(null,null,function*(){var t,n;try{const s=ve();yield Sl();const i=yield TM("/files/getstsToken",{method:"POST",headers:C({"Content-Type":"application/json","Accept-Language":`${s.language},${s.language.split("-")[0]};q=0.9`},localStorage.token&&{Authorization:`Bearer ${localStorage.token}`}),data:e||{}});if(!i)return{errorCode:"ERR_EMPTY_RESPONSE",info:"Empty response from server"};if(!i.success||!i.data)return{errorCode:(null==(t=i.data)?void 0:t.code)||"",info:(null==(n=i.data)?void 0:n.message)||""};const a=i.data;return{accessKeyId:a.access_key_id,accessKeySecret:a.access_key_secret,stsToken:a.security_token,bucket:a.bucketname,region:a.region,endpoint:a.endpoint,fileId:a.file_id,filePath:a.file_path,fileCDNUrl:a.file_url}}catch(s){return{errorCode:"",info:""}}}))({filename:s,filesize:String(i),filetype:o}).then(o=>A(this,null,function*(){var r;if(!o||function(e){return"errorCode"in e}(o))return this.sendTrackEvent("ossTokenNetworkError",{c8:{filename:s,filesize:i,filetype:a}}),null==(r=null==t?void 0:t.onUploadFailed)||r.call(t,new Error(o?o.info:"empty response")),o;const l=o,c=qR(),d=qR();this.sendTrackEvent("ossTokenTime",{c4:d,c5:c,c6:c-d,c8:{filename:s,filesize:i,filetype:a}});const u=yield function(){return A(this,null,function*(){var e;if(!pu){const t=yield Se(()=>import("./ali-oss-vendor.js").then(e=>e.a),__vite__mapDeps([0]));pu=null!=(e=t.default)?e:t}return pu})}(),h=new u({authorizationV4:!0,region:l.region,endpoint:l.endpoint,accessKeyId:l.accessKeyId,accessKeySecret:l.accessKeySecret,stsToken:l.stsToken,bucket:l.bucket}),m=this.getParallelParams(i),p=C(S(C({taskId:n,file:e,client:h,progress:0},m),{status:"uploading",startTime:d,ossToken:l}),t||{});return this.uploadTask[n]=p,p.startTime=qR(),this.sendTrackEvent("startUpload",{c4:p.startTime,taskId:n}),this.execUpload(n),n})).catch(e=>{var n;throw null==(n=null==t?void 0:t.onUploadFailed)||n.call(t,e),e})}resumeUpload(e){return A(this,null,function*(){var t;const n=this.uploadTask[e];if(n&&"uploadError"===n.status)try{n.resumeTime=qR(),this.sendTrackEvent("resumeUpload",{c4:n.resumeTime,taskId:e}),null==(t=n.onResumeUpload)||t.call(n),yield this.execUpload(e)}catch(s){}})}stopAndRemoveTask(e){return A(this,null,function*(){const t=this.uploadTask[e];if(t){this.sendTrackEvent("stopUpload",{c4:qR(),taskId:e});try{const{client:n,status:s,checkPoint:i}=t;"uploading"===s&&i&&n.abortMultipartUpload(i.name,i.uploadId).catch(e=>{!e.name||e.name}),delete this.uploadTask[e]}catch(n){}}})}getPromise(){let e=()=>{},t=()=>{};const n=new Promise((n,s)=>{e=n,t=s});return{promise:n,resolve:e,reject:t}}};let vu=ve();function yu(e){var t,n,s;return`${null==(s=null==(n=null==(t=null==e?void 0:e.name)?void 0:t.split("."))?void 0:n.at(-1))?void 0:s.toLowerCase()}`||""}function bu(e){return!!e&&Object.values(Xt).includes(e)}function xu(e,t,n){const s=n[t];if(0==e.size)return vu.t("You cannot upload an empty file."),!1;if(e.size>1024*s.max_size*1024){const e={[Xt.IMAGE]:"Images",[Xt.AUDIO]:"Audio",[Xt.VIDEO]:"Video",[Xt.DOC]:"Document",[Xt.DEFAULT]:"TXT",[Xt.CAMERA]:"Images"};return Gl.openOnce({type:"error",content:vu.t("{{type}} files are not allowed to exceed {{size}}",{type:vu.t(e[t]),size:s.max_size>=1024?`${Number((s.max_size/1024).toFixed(1))}G`:`${s.max_size}M`})}),!1}return!0}function wu(e,t,n){return A(this,null,function*(){if(t!==Xt.VIDEO&&t!==Xt.AUDIO)return!0;const s=n[t];if(t===Xt.VIDEO){const t=yield(e=>new Promise(t=>{const n=document.createElement("video");n.style.display="none",n.style.width="0%",n.style.height="0%",Object.assign(n,{controls:!1,autoplay:!1,muted:!0});const s=URL.createObjectURL(e);let i=!1;n.onloadedmetadata=()=>{if(!i){i=!0;const e=Math.round(1e3*n.duration);t(e),URL.revokeObjectURL(s),document.body.removeChild(n)}},n.onload=()=>{if(!i){i=!0;const e=Math.round(1e3*n.duration);t(e),URL.revokeObjectURL(s),document.body.removeChild(n)}},n.onerror=()=>{i||(i=!0,t(0),URL.revokeObjectURL(s),document.body.removeChild(n))},n.src=s,document.body.appendChild(n)}))(e);if(t>1e3*s.max_duration)return s.max_duration<60?Gl.openOnce({type:"error",content:vu.t("Video duration should not exceed {{maxSeconds}} seconds",{maxSeconds:s.max_duration})}):Gl.openOnce({type:"error",content:vu.t("Video duration should not exceed {{maxMins}} mins.",{maxMins:(s.max_duration/60).toFixed(0)})}),!1}if(t===Xt.AUDIO){const t=yield(e=>new Promise(t=>{const n=document.createElement("audio");n.style.display="none",n.style.width="0%",n.style.height="0%",Object.assign(n,{controls:!1,autoplay:!1,muted:!0});const s=URL.createObjectURL(e);let i=!1;n.onloadedmetadata=()=>{if(!i){i=!0;const e=Math.round(1e3*n.duration);t(e),URL.revokeObjectURL(s),document.body.removeChild(n)}},n.onload=()=>{if(!i){i=!0;const e=Math.round(1e3*n.duration);t(e),URL.revokeObjectURL(s),document.body.removeChild(n)}},n.onerror=()=>{i||(i=!0,t(0),URL.revokeObjectURL(s),document.body.removeChild(n))},n.src=s,document.body.appendChild(n)}))(e);if(t>1e3*s.max_duration)return Gl.openOnce({type:"error",content:vu.t("Audio duration should not exceed {{maxMins}} minutes.",{maxMins:s.max_duration/60})}),!1}return!0})}class _u{constructor({onAddProcess:e=()=>{},onAddSuccess:t=()=>{},onAddFail:n=()=>{},onPaseSuccess:s=()=>{},onPaseFail:i=()=>{},parsedFileTypes:a=[],userId:o}){j(this,"parseTaskIds",[]),j(this,"loopParse",null),j(this,"fileItems",[]),j(this,"limitTypes",Object.values(Xt)),j(this,"defaultLimitRules",en),j(this,"limitRules",en),j(this,"totalMaxCount",Jt),j(this,"onAddProcess",()=>{}),j(this,"onAddSuccess",()=>{}),j(this,"onAddFail",()=>{}),j(this,"onPaseSuccess",()=>{}),j(this,"onPaseFail",()=>{}),j(this,"userId"),j(this,"parsedFileTypes",[]),j(this,"beforeFileUpload",(e,t=!1,n)=>{const s=Fe(),i=n===Xt.VIDEO,a=(e=>{switch(e){case"vision":return"image";case"document":case"default":return"file";default:return e}})(n);return C({type:a,file:e,id:null,url:"",name:e.name,collection_name:"",progress:0,status:"uploading",greenNet:i?"greening":"success",size:e.size,error:"",itemId:s,file_type:e.type,showType:a,file_class:n},t||n===Xt.DEFAULT?{context:"full"}:{})}),j(this,"updateFile",e=>{const t=this.fileItems.findIndex(t=>t.itemId===e.itemId);t>-1&&this.fileItems.splice(t,1,e)}),j(this,"pushFile",e=>{Array.isArray(e)?this.fileItems=[...this.fileItems,...e]:this.fileItems.push(e)}),j(this,"setFiles",e=>{this.fileItems=e}),this.onAddProcess=e,this.onAddSuccess=t,this.onAddFail=n,this.onPaseSuccess=s,this.onPaseFail=i,this.userId=o,this.parsedFileTypes=a,vu=ve()}updateLimitTypes(e){e&&(this.limitTypes=e)}getLimitTypes(){return this.limitTypes}updateLimitRules(e,t="custom"){"default"===t?(this.defaultLimitRules=Me(Te(en),e),this.limitRules=this.defaultLimitRules):this.limitRules=Me(Te(this.defaultLimitRules),e);const n=["image/tiff"],s=[".tif",".tiff",".dib"],i=[".dib"],a=this.limitRules[Xt.IMAGE].accept_type,o=this.limitRules[Xt.IMAGE].accept_extension;zs()&&(this.limitRules[Xt.IMAGE].accept_extension=o.filter(e=>!i.includes(e))),$s()&&(this.limitRules[Xt.IMAGE].accept_type=a.filter(e=>!n.includes(e)),this.limitRules[Xt.IMAGE].accept_extension=o.filter(e=>!s.includes(e)))}getLimitRules(){return this.limitRules}validateFile(e,t){return A(this,null,function*(){const n=this.validateFileType(e,t);if(!n||!bu(n))return!1;if(!this.validateFileCount(n))return!1;if(!xu(e,n,this.limitRules))return!1;return!!(yield wu(e,n,this.limitRules))&&n})}getFileExtensions(e){return yu(e)}isValidFileType(e){return bu(e)}validateFileType(e,t){return function(e,t,n,s){const i=e.type,a=yu(e);if(s){if(Array.isArray(s)){for(let e of s){e===Xt.CAMERA&&(e=Xt.IMAGE);const s=t[e];if(n.includes(e)&&(s.accept_type.includes(i)||s.accept_extension.includes(a)))return e}return void Gl.openOnce({type:"error",content:vu.t("The selected model or feature does not support the file type you uploaded.")})}const e=t[s];return n.includes(s)&&(e.accept_type.includes(i)||e.accept_extension.includes(a))?s:void Gl.openOnce({type:"error",content:vu.t("The selected model or feature does not support the file type you uploaded.")})}let o;if(Object.entries(t).forEach(([e,t])=>{(t.accept_type.includes(i)||t.accept_extension.includes(a))&&(o=e)}),o&&n.includes(o))return o;Gl.openOnce({type:"error",content:vu.t("The selected model or feature does not support the file type you uploaded.")})}(e,this.limitRules,this.limitTypes,t)}validateFileSize(e,t){return xu(e,t,this.limitRules)}validateFileDuration(e,t){return A(this,null,function*(){return wu(e,t,this.limitRules)})}validateFileCount(e){return function(e,t,n,s){var i;const a={[Xt.IMAGE]:"In a single-turn conversation, up to {{number}} images can be uploaded.",[Xt.AUDIO]:"In a single-turn conversation, up to {{number}} audio files can be uploaded.",[Xt.VIDEO]:"In a single-turn conversation, up to {{number}} video can be uploaded.",[Xt.DOC]:"In a single-turn conversation, up to {{number}} documents can be uploaded.",[Xt.DEFAULT]:"In a single-turn conversation, up to {{number}} documents can be uploaded.",[Xt.CAMERA]:"In a single-turn conversation, up to {{number}} images can be uploaded."},o=t[e],r=((null==(i=n.filter(t=>t.file_class===e))?void 0:i.length)||0)+1,l=o.max_count;return r>l?(Gl.openOnce({type:"error",content:vu.t(a[e],{number:l})}),!1):n.length>s?(Gl.openOnce({type:"error",content:vu.t("You can only chat with a maximum of {{maxCount}} file(s) at a time.",{maxCount:s})}),!1):e}(e,this.limitRules,this.fileItems,this.totalMaxCount)}removeFile(e){this.fileItems=this.fileItems.filter(t=>t.itemId!==e.itemId)}clearFiles(){this.fileItems=[]}getFiles(){return this.fileItems}}let Cu=ve();function Su(e,t,n){var s;t.id&&(s={file_id:t.id},A(null,null,function*(){const e=it();return yield TM("/files/parse",{method:"POST",headers:{"Accept-Language":`${e.language},${e.language.split("-")[0]};q=0.9`},data:s})})).then(s=>{var i,a,o,r,l;if(s&&s.success&&(null==(i=s.data)?void 0:i.file_id)&&(null==(a=s.data)?void 0:a.file_id)===t.id){if(t.file&&(t.file=S(C({},t.file),{meta:S(C({},null==(o=t.file)?void 0:o.meta),{parse_meta:{parse_status:"running"}})}),e.parseTaskIds.push(null==(r=s.data)?void 0:r.file_id)),n){const n=e.getFiles().find(e=>e.id===t.id);(null==n?void 0:n.file)&&(n.file=t.file)}e.loopParse||e.loopGetParseStatus(),e.onAddSuccess(e.getFiles(),t)}else t.file&&(e.parseTaskIds=e.getFiles().filter(e=>e.id&&e.id!==t.id).map(e=>e.id||""),t.file=S(C({},t.file),{meta:S(C({},null==(l=t.file)?void 0:l.meta),{parse_meta:{parse_status:"failed",retry:!0}})}),e.onPaseFail(e.getFiles(),t))})}function ku(e){try{e.loopParse=setTimeout(()=>{const t=e.parseTaskIds.filter(t=>e.getFiles().find(e=>e.id===t));var n;t.length?(n={file_id_list:t},A(null,null,function*(){const e=it();return yield TM("/files/parse/status",{method:"POST",headers:{"Accept-Language":`${e.language},${e.language.split("-")[0]};q=0.9`},data:n})})).then(t=>{var n;if(t&&t.success){const s=[];null==(n=null==t?void 0:t.data)||n.map(t=>{var n,i,a,o,r,l,c,d;const u=e.getFiles().find(e=>e.id===t.file_id);"running"===t.status&&u?s.push(t.file_id):"success"===t.status&&u&&"running"===(null==(a=null==(i=null==(n=null==u?void 0:u.file)?void 0:n.meta)?void 0:i.parse_meta)?void 0:a.parse_status)?u.file&&(u.file=S(C({},u.file),{meta:S(C({},null==(o=u.file)?void 0:o.meta),{parse_meta:{parse_status:"success"}})}),e.onPaseSuccess(e.getFiles(),u)):"failed"===t.status&&u&&"running"===(null==(c=null==(l=null==(r=null==u?void 0:u.file)?void 0:r.meta)?void 0:l.parse_meta)?void 0:c.parse_status)&&u.file&&(u.file=S(C({},u.file),{meta:S(C({},null==(d=u.file)?void 0:d.meta),{parse_meta:{parse_status:"failed",error_msg:t.error_msg,error_code:t.error_code,retry:t.retry}})}),Gl.openOnce({type:"error",content:Cu.t(t.error_msg)}),e.onPaseFail(e.getFiles(),u))}),s.length?(e.parseTaskIds=s,e.loopGetParseStatus()):(clearTimeout(e.loopParse),e.loopParse=null,e.parseTaskIds=[])}else e.parseTaskIds=[],e.loopParse=null,e.getFiles().length&&e.getFiles().map(t=>{var n,s,i,a;t.file&&"running"===(null==(i=null==(s=null==(n=t.file)?void 0:n.meta)?void 0:s.parse_meta)?void 0:i.parse_status)&&(t.file=S(C({},t.file),{meta:S(C({},null==(a=t.file)?void 0:a.meta),{parse_meta:{parse_status:"failed",retry:!0}})}),e.onPaseFail(e.getFiles(),t))})}):(clearTimeout(e.loopParse),e.loopParse=null,e.parseTaskIds=[])},2e3)}catch(t){clearTimeout(e.loopParse),e.loopParse=null,e.parseTaskIds=[]}}let ju=ve();class Tu extends _u{constructor(e){super(e),j(this,"startParse",(e,t)=>A(this,null,function*(){Su(this,e,t)})),j(this,"loopGetParseStatus",()=>{ku(this)}),j(this,"uploadFile",e=>A(this,null,function*(){const{file:t,fullContext:n=!1,uploadType:s,retryFile:i}=e;if(!this.validateFileCount(s))return!1;const a=i||this.beforeFileUpload(t,n,s);this.pushFile(a),i&&(a.status="uploading",this.onAddProcess(this.getFiles(),a));const o=s===Xt.VIDEO,r=s===Xt.AUDIO,l=s===Xt.IMAGE;try{const e=qR(),n=yield fu.uploadFileToOss(t,{onUploadProgress:e=>{a.progress=e,this.updateFile(a),this.onAddProcess(this.getFiles(),a)},onUploadFailed:e=>{let t="Upload failed. Please try again after your network connection is restored.";(null==e?void 0:e.errorCode)&&(t=e.info),Gl.openOnce({type:"error",content:ju.t(t)}),a.status="upload_error","data_inspection_failed"===(null==e?void 0:e.errorCode)&&(a.greenNet="green_error"),this.updateFile(a),this.onAddFail(this.getFiles(),a)},onResumeUpload:()=>{a.status="uploading",this.updateFile(a),this.onAddProcess(this.getFiles(),a)},onUploadSuccess:(s,i)=>A(this,null,function*(){var c,d;const u=qR();let h=qR();var m;a.id=s,a.url=i,a.file=((e,t,n)=>{const{name:s,size:i,type:a}=e,o=(new Date).getTime();return{created_at:o,data:{},filename:s,hash:null,id:t,user_id:n,meta:{name:s,size:i,content_type:a},update_at:o,lastModified:e.lastModified,name:e.name,webkitRelativePath:e.webkitRelativePath,size:e.size,type:e.type,arrayBuffer:()=>e.arrayBuffer(),slice:(t,n,s)=>e.slice(t,n,s),stream:()=>e.stream(),text:()=>e.text()}})(t,s,this.userId),o||l||r||(a.status="uploaded"),o&&(a.type="video",(yield(m=i,new Promise(e=>{const t=document.createElement("video");t.style.display="none",t.style.width="0%",t.style.height="0%",Object.assign(t,{controls:!1,autoplay:!1,muted:!0});let n=!1;t.onloadedmetadata=()=>{n||(n=!0,e(!0),document.body.removeChild(t))},t.onload=()=>{n||(n=!0,e(!0),document.body.removeChild(t))},t.onerror=()=>{n||(n=!0,e(!1),document.body.removeChild(t))},t.src=m,document.body.appendChild(t)})))?(h=qR(),a.showType="video"):a.showType="file",a.status="uploaded"),r&&(a.type="audio",(yield(e=>new Promise(t=>{const n=document.createElement("audio");n.style.display="none",n.style.width="0%",n.style.height="0%",Object.assign(n,{controls:!1,autoplay:!1,muted:!0});let s=!1;n.onloadedmetadata=()=>{s||(s=!0,t(!0),document.body.removeChild(n))},n.onload=()=>{s||(s=!0,t(!0),document.body.removeChild(n))},n.onerror=()=>{s||(s=!0,t(!1),document.body.removeChild(n))},n.src=e,document.body.appendChild(n)}))(i))?(h=qR(),a.showType="audio"):a.showType="file",a.status="uploaded"),l&&(a.type="image",(yield hu(i))?(h=qR(),a.showType="image"):a.showType="file",a.status="uploaded");let p=0;try{p=function(e,t,n=2){if("number"!=typeof e||"number"!=typeof t)throw new Error("参数必须是数字类型");if(e<=0)throw new Error("文件大小必须大于0");if(t<=0)throw new Error("上传时间必须大于0");return Number((e/1048576/(t/1e3)).toFixed(n))}(t.size,Math.round(u-e),3)}catch(g){}pl("FileUpload-AllTime",{params:{et:"OTHER",c1:null==(c=null==a?void 0:a.file)?void 0:c.user_id,c4:a.type,c5:t.size,c6:Math.round(h-e),c7:Math.round(h-u),c8:Math.round(u-e),c9:p}}),n&&"string"==typeof n&&!fu.getTaskItem(n)||((null==(d=this.parsedFileTypes)?void 0:d.length)&&this.parsedFileTypes.includes(a.type)?this.startParse(a):this.onAddSuccess(this.getFiles(),a))})});n&&"string"==typeof n?(a.uploadTaskId=n,this.onAddProcess(this.getFiles(),a)):n||(this.removeFile(a),this.onAddFail(this.getFiles(),a))}catch(c){"ossTokenError"!==c.code&&Gl.openOnce({type:"error",content:ju.t("Failed to upload file.")}),this.removeFile(a),this.onAddFail(this.getFiles(),a)}})),ju=ve(),Cu=ve()}addFile(e,t){return A(this,null,function*(){const n=(e=>{var t,n,s;if(e.type)return e;const i=null==(s=null==(n=null==(t=null==e?void 0:e.name)?void 0:t.split("."))?void 0:n.at(-1))?void 0:s.toLowerCase();return i&&!(i in mu)||!i?e:new File([e],e.name,{type:mu[i]})})(e),s=yield this.validateFile(n,t);return!!s&&(yield this.uploadFile({file:n,fullContext:!1,uploadType:s}),!0)})}retryFile(e){return A(this,null,function*(){e.file&&(yield this.uploadFile({file:e.file,fullContext:!1,uploadType:e.file_class,retryFile:e}))})}addFiles(e,t){return A(this,null,function*(){var n;if(0===(null==(n=e.filter(e=>!!e))?void 0:n.length))return Gl.openOnce({type:"error",content:ju.t("File not found.")}),!1;const s=(yield Promise.allSettled(e.map(e=>this.addFile(e,t)))).filter(e=>"rejected"===e.status).map(e=>e.reason.message);return!(s.length>0&&s.length===e.length)&&this.getFiles()})}}yt.ImageGeneration,yt.VideoGeneration,yt.ImageEdit;const Eu={[yt.VideoGeneration]:{fileType:["JPG","JPEG","PNG","BMP","WEBP"],mineType:["image/png","image/jpeg","image/bmp","image/webp"],extensions:[".png",".jpg",".jpeg",".bmp",".webp"]}},Nu=e=>{const{type:t="",file_type:n="",name:s=""}=e||{};return["image/png","image/jpeg","image/bmp","image/tiff","image/webp"].includes(n||t)&&(s.toLowerCase().endsWith(".png")||s.toLowerCase().endsWith(".jpg")||s.toLowerCase().endsWith(".jpeg")||s.toLowerCase().endsWith(".bmp")||s.toLowerCase().endsWith(".tif")||s.toLowerCase().endsWith(".tiff")||s.toLowerCase().endsWith(".webp"))},Iu=(e,t)=>{const{theme:n}=ud.getState();return"dark"===n?t:e},Au=()=>(new Date).toString().replace(/\s*\(.+\)$/,""),Mu=(e,t=!0)=>{var n;if(window.location.host.includes("pre"))try{const s=document.getElementById("OMNI_TEST_BUTTON_ID");s&&t&&(null==(n=s.parentElement)||n.removeChild(s),window.testInfo={}),window.testInfo=C(C({},window.testInfo||{}),e);const i=document.createElement("button");i.id="OMNI_TEST_BUTTON_ID",i.style.position="fixed",i.style.left="0px",i.style.top="50px",i.style.zIndex="99999999",i.style.background="blue",i.style.color="white",i.style.padding="0 10px",i.textContent="Copy reqs",document.body.appendChild(i),i.addEventListener("click",()=>{SR(JSON.stringify(window.testInfo,null,2)),i.textContent="Copied"},!1)}catch(s){}},Ru=(e,t,n)=>{if(!t)return e;if("zh-CN"===n){let n=t.split(" ").filter(Boolean).map(e=>{return`\\b${t=e,t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`;var t}).join("|");const s=[...t].filter(e=>/[\u4e00-\u9fff]/.test(e));if(s.length>0){n+=(n?"|":"")+s.map(e=>`(${e})`).join("|")}const i=new RegExp(n,"gi");return e.replace(i,e=>`${e}`)}if(e.includes(t)){const n=new RegExp(t.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"g");return e.replace(n,e=>`${e}`)}return e},Pu=(e,t=null)=>{const n=[...e],s=n.length,i=null==t||t<0?s:Math.min(t,s);for(let a=s-1;a>0;a--){const e=Math.floor(Math.random()*(a+1));[n[a],n[e]]=[n[e],n[a]]}return n.slice(0,i)},Lu=(e,t)=>{const n=null==e?void 0:e[t||""];return n?(null==n?void 0:n.chat_type)===yt.DeepResearch&&(null==n?void 0:n.sub_chat_type)===yt.DeepResearch?n:(null==n?void 0:n.parentId)?Lu(e,null==n?void 0:n.parentId):null:null},Ou=(e,t="assistant")=>e.findLastIndex(e=>e.chat_type===yt.DeepResearch&&e.sub_chat_type===yt.DeepResearch&&e.role===t);const Du=(e,t,n)=>{pl("chatGeneration",{params:{et:"CLK"},aesParams:{c4:t,c5:n,c6:e},paramsExtend:{chat_id:t,msg_type:n,send_type:e}})},Fu=(e,t,n,s)=>{var i;if(t||n)for(const a of e)if(a.key||(null==(i=a.childrens)?void 0:i.length)){if(a.key===n||a.key===t||"mcp"===a.key&&s)return a;if(a.childrens){const e=Fu(a.childrens,t,n);if(e)return e}}};var qu,Uu={exports:{}};var Hu=(qu||(qu=1,function(e){!function(t){var n=Object.hasOwnProperty,s=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},i="object"==typeof process&&"function"==typeof process.nextTick,a="function"==typeof Symbol,o="object"==typeof Reflect,r="function"==typeof setImmediate?setImmediate:setTimeout,l=a?o&&"function"==typeof Reflect.ownKeys?Reflect.ownKeys:function(e){var t=Object.getOwnPropertyNames(e);return t.push.apply(t,Object.getOwnPropertySymbols(e)),t}:Object.keys;function c(){this._events={},this._conf&&d.call(this,this._conf)}function d(e){e&&(this._conf=e,e.delimiter&&(this.delimiter=e.delimiter),e.maxListeners!==t&&(this._maxListeners=e.maxListeners),e.wildcard&&(this.wildcard=e.wildcard),e.newListener&&(this._newListener=e.newListener),e.removeListener&&(this._removeListener=e.removeListener),e.verboseMemoryLeak&&(this.verboseMemoryLeak=e.verboseMemoryLeak),e.ignoreErrors&&(this.ignoreErrors=e.ignoreErrors),this.wildcard&&(this.listenerTree={}))}function u(e,t){var n="(node) warning: possible EventEmitter memory leak detected. "+e+" listeners added. Use emitter.setMaxListeners() to increase limit.";if(this.verboseMemoryLeak&&(n+=" Event name: "+t+"."),"undefined"!=typeof process&&process.emitWarning){var s=new Error(n);s.name="MaxListenersExceededWarning",s.emitter=this,s.count=e,process.emitWarning(s)}else console.trace}var h=function(e,t,n){var s=arguments.length;switch(s){case 0:return[];case 1:return[e];case 2:return[e,t];case 3:return[e,t,n];default:for(var i=new Array(s);s--;)i[s]=arguments[s];return i}};function m(e,n){for(var s={},i=e.length,a=0;a0;)if(a===e[o])return s;i(t)}}Object.assign(p.prototype,{subscribe:function(e,t,n){var s=this,i=this._target,a=this._emitter,o=this._listeners,r=function(){var s=h.apply(null,arguments),o={data:s,name:t,original:e};n?!1!==n.call(i,o)&&a.emit.apply(a,[o.name].concat(s)):a.emit.apply(a,[t].concat(s))};if(o[e])throw Error("Event '"+e+"' is already listening");this._listenersCount++,a._newListener&&a._removeListener&&!s._onNewListener?(this._onNewListener=function(n){n===t&&null===o[e]&&(o[e]=r,s._on.call(i,e,r))},a.on("newListener",this._onNewListener),this._onRemoveListener=function(n){n===t&&!a.hasListeners(n)&&o[e]&&(o[e]=null,s._off.call(i,e,r))},o[e]=null,a.on("removeListener",this._onRemoveListener)):(o[e]=r,s._on.call(i,e,r))},unsubscribe:function(e){var t,n,s,i=this,a=this._listeners,o=this._emitter,r=this._off,c=this._target;if(e&&"string"!=typeof e)throw TypeError("event must be a string");function d(){i._onNewListener&&(o.off("newListener",i._onNewListener),o.off("removeListener",i._onRemoveListener),i._onNewListener=null,i._onRemoveListener=null);var e=w.call(o,i);o._observers.splice(e,1)}if(e){if(!(t=a[e]))return;r.call(c,e,t),delete a[e],--this._listenersCount||d()}else{for(s=(n=l(a)).length;s-- >0;)e=n[s],r.call(c,e,a[e]);this._listeners={},this._listenersCount=0,d()}}});var y=v(["function"]),b=v(["object","function"]);function x(e,t,n){var s,i,a,o=0,r=new e(function(l,c,d){function u(){i&&(i=null),o&&(clearTimeout(o),o=0)}n=g(n,{timeout:0,overload:!1},{timeout:function(e,t){return("number"!=typeof(e*=1)||e<0||!Number.isFinite(e))&&t("timeout must be a positive number"),e}}),s=!n.overload&&"function"==typeof e.prototype.cancel&&"function"==typeof d;var h=function(e){u(),l(e)},m=function(e){u(),c(e)};s?t(h,m,d):(i=[function(e){m(e||Error("canceled"))}],t(h,m,function(e){if(a)throw Error("Unable to subscribe on cancel event asynchronously");if("function"!=typeof e)throw TypeError("onCancel callback must be a function");i.push(e)}),a=!0),n.timeout>0&&(o=setTimeout(function(){var e=Error("timeout");e.code="ETIMEDOUT",o=0,r.cancel(e),c(e)},n.timeout))});return s||(r.cancel=function(e){if(i){for(var t=i.length,n=1;n0;)"_listeners"!==(m=y[r])&&(b=_(e,t,n[m],s+1,i))&&(x?x.push.apply(x,b):x=b);return x}if("**"===w){for((v=s+1===i||s+2===i&&"*"===C)&&n._listeners&&(x=_(e,t,n,i,i)),r=(y=l(n)).length;r-- >0;)"_listeners"!==(m=y[r])&&("*"===m||"**"===m?(n[m]._listeners&&!v&&(b=_(e,t,n[m],i,i))&&(x?x.push.apply(x,b):x=b),b=_(e,t,n[m],s,i)):b=_(e,t,n[m],m===C?s+2:s,i),b&&(x?x.push.apply(x,b):x=b));return x}n[w]&&(x=_(e,t,n[w],s+1,i))}if((p=n["*"])&&_(e,t,p,s+1,i),g=n["**"])if(s0;)"_listeners"!==(m=y[r])&&(m===C?_(e,t,g[m],s+2,i):m===w?_(e,t,g[m],s+1,i):((f={})[m]=g[m],_(e,t,{"**":f},s+1,i)));else g._listeners?_(e,t,g,i,i):g["*"]&&g["*"]._listeners&&_(e,t,g["*"],i,i);return x}function C(e,t,n){var s,i,a=0,o=0,r=this.delimiter,l=r.length;if("string"==typeof e)if(-1!==(s=e.indexOf(r))){i=new Array(5);do{i[a++]=e.slice(o,s),o=s+l}while(-1!==(s=e.indexOf(r,o)));i[a++]=e.slice(o)}else i=[e],a=1;else i=e,a=e.length;if(a>1)for(s=0;s+10&&d._listeners.length>this._maxListeners&&(d._listeners.warned=!0,u.call(this,d._listeners.length,c))):d._listeners=t,!0;return!0}function S(e,t,n,s){for(var i,a,o,r,c=l(e),d=c.length,u=e._listeners;d-- >0;)i=e[a=c[d]],o="_listeners"===a?n:n?n.concat(a):[a],r=s||"symbol"==typeof a,u&&t.push(r?o:o.join(this.delimiter)),"object"==typeof i&&S.call(this,i,t,o,r);return t}function k(e){for(var t,n,s,i=l(e),a=i.length;a-- >0;)(t=e[n=i[a]])&&(s=!0,"_listeners"===n||k(t)||delete e[n]);return s}function j(e,t,n){this.emitter=e,this.event=t,this.listener=n}function T(e,n,s){if(!0===s)o=!0;else if(!1===s)a=!0;else{if(!s||"object"!=typeof s)throw TypeError("options should be an object or true");var a=s.async,o=s.promisify,l=s.nextTick,c=s.objectify}if(a||l||o){var d=n,u=n._origin||n;if(l&&!i)throw Error("process.nextTick is not supported");o===t&&(o="AsyncFunction"===n.constructor.name),n=function(){var e=arguments,t=this,n=this.event;return o?l?Promise.resolve():new Promise(function(e){r(e)}).then(function(){return t.event=n,d.apply(t,e)}):(l?process.nextTick:r)(function(){t.event=n,d.apply(t,e)})},n._async=!0,n._origin=u}return[n,c?new j(this,e,n):this]}function E(e){this._events={},this._newListener=!1,this._removeListener=!1,this.verboseMemoryLeak=!1,d.call(this,e)}j.prototype.off=function(){return this.emitter.off(this.event,this.listener),this},E.EventEmitter2=E,E.prototype.listenTo=function(e,n,i){if("object"!=typeof e)throw TypeError("target musts be an object");var a=this;function o(t){if("object"!=typeof t)throw TypeError("events must be an object");var n,s=i.reducers,o=w.call(a,e);n=-1===o?new p(a,e,i):a._observers[o];for(var r,c=l(t),d=c.length,u="function"==typeof s,h=0;h0;)s=n[i],e&&s._target!==e||(s.unsubscribe(t),a=!0);return a},E.prototype.delimiter=".",E.prototype.setMaxListeners=function(e){e!==t&&(this._maxListeners=e,this._conf||(this._conf={}),this._conf.maxListeners=e)},E.prototype.getMaxListeners=function(){return this._maxListeners},E.prototype.event="",E.prototype.once=function(e,t,n){return this._once(e,t,!1,n)},E.prototype.prependOnceListener=function(e,t,n){return this._once(e,t,!0,n)},E.prototype._once=function(e,t,n,s){return this._many(e,1,t,n,s)},E.prototype.many=function(e,t,n,s){return this._many(e,t,n,!1,s)},E.prototype.prependMany=function(e,t,n,s){return this._many(e,t,n,!0,s)},E.prototype._many=function(e,t,n,s,i){var a=this;if("function"!=typeof n)throw new Error("many only accepts instances of Function");function o(){return 0===--t&&a.off(e,o),n.apply(this,arguments)}return o._origin=n,this._on(e,o,s,i)},E.prototype.emit=function(){if(!this._events&&!this._all)return!1;this._events||c.call(this);var e,t,n,s,i,o,r=arguments[0],l=this.wildcard;if("newListener"===r&&!this._newListener&&!this._events.newListener)return!1;if(l&&(e=r,"newListener"!==r&&"removeListener"!==r&&"object"==typeof r)){if(n=r.length,a)for(s=0;s3)for(t=new Array(u-1),i=1;i3)for(n=new Array(h-1),o=1;o0&&this._events[e].length>this._maxListeners&&(this._events[e].warned=!0,u.call(this,this._events[e].length,e))):this._events[e]=n,o)},E.prototype.off=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var n,i=[];if(this.wildcard){var a="string"==typeof e?e.split(this.delimiter):e.slice();if(!(i=_.call(this,null,a,this.listenerTree,0)))return this}else{if(!this._events[e])return this;n=this._events[e],i.push({_listeners:n})}for(var o=0;o0){for(n=0,s=(t=this._all).length;n0;)"function"==typeof(s=r[n[a]])?i.push(s):i.push.apply(i,s);return i}if(this.wildcard){if(!(o=this.listenerTree))return[];var c=[],d="string"==typeof e?e.split(this.delimiter):e.slice();return _.call(this,c,d,o,0),c}return r&&(s=r[e])?"function"==typeof s?[s]:s:[]},E.prototype.eventNames=function(e){var t=this._events;return this.wildcard?S.call(this,this.listenerTree,[],null,e):t?l(t):[]},E.prototype.listenerCount=function(e){return this.listeners(e).length},E.prototype.hasListeners=function(e){if(this.wildcard){var n=[],s="string"==typeof e?e.split(this.delimiter):e.slice();return _.call(this,n,s,this.listenerTree,0),n.length>0}var i=this._events,a=this._all;return!!(a&&a.length||i&&(e===t?l(i).length:i[e]))},E.prototype.listenersAny=function(){return this._all?this._all:[]},E.prototype.waitFor=function(e,n){var s=this,i=typeof n;return"number"===i?n={timeout:n}:"function"===i&&(n={filter:n}),x((n=g(n,{timeout:0,filter:t,handleError:!1,Promise:Promise,overload:!1},{filter:y,Promise:f})).Promise,function(t,i,a){function o(){var a=n.filter;if(!a||a.apply(s,arguments))if(s.off(e,o),n.handleError){var r=arguments[0];r?i(r):t(h.apply(null,arguments).slice(1))}else t(h.apply(null,arguments))}a(function(){s.off(e,o)}),s._on(e,o,!1)},{timeout:n.timeout,overload:n.overload})};var N=E.prototype;Object.defineProperties(E,{defaultMaxListeners:{get:function(){return N._maxListeners},set:function(e){if("number"!=typeof e||e<0||Number.isNaN(e))throw TypeError("n must be a non-negative number");N._maxListeners=e},enumerable:!0},once:{value:function(e,t,n){return x((n=g(n,{Promise:Promise,timeout:0,overload:!1},{Promise:f})).Promise,function(n,s,i){var a;if("function"==typeof e.addEventListener)return a=function(){n(h.apply(null,arguments))},i(function(){e.removeEventListener(t,a)}),void e.addEventListener(t,a,{once:!0});var o,r=function(){o&&e.removeListener("error",o),n(h.apply(null,arguments))};"error"!==t&&(o=function(n){e.removeListener(t,r),s(n)},e.once("error",o)),i(function(){o&&e.removeListener("error",o),e.removeListener(t,r)}),e.once(t,r)},{timeout:n.timeout,overload:n.overload})},writable:!0,configurable:!0}}),Object.defineProperties(N,{_maxListeners:{value:10,writable:!0,configurable:!0},_observers:{value:null,writable:!0,configurable:!0}}),e.exports=E}()}(Uu)),Uu.exports);const Bu=U(Hu);var zu=(e=>(e.CHAT_INITIALIZED="chat.initialized",e.CHAT_HISTORY_LOADED="chat.historyLoaded",e.CHAT_INIT_NEWCHAT="chat.init.newChat",e.CHAT_BEGIN="chat.begin",e.CHAT_MESSAGE_SENT_REGENERATE="chat.message.sent.regenerate",e.CHAT_MESSAGE_EDIT_BEGIN="chat.message.sent.begin",e.CHAT_MESSAGE_EDIT_END="chat.message.sent.end",e.CHAT_MESSAGE_UPDATE="chat.message.update",e.CHAT_CREATE_NEW_CHAT="chat.create.new.chat",e.CHAT_SSE_ID_CHANGE="chat.sse.id.change",e.CHAT_SSE_BEGIN="chat.sse.begin",e.CHAT_SSE_ERROR="chat.sse.error",e.CHAT_SSE_PROCESS="chat.sse.process",e.CHAT_SSE_FIRST_RECEIVE_MESSAGE="chat.sse.first.receive.message",e.CHAT_SSE_END="chat.sse.end",e.CHAT_MESSAGE_FAILED="chat.message.failed",e.CHAT_MESSAGE_END="chat.message.end",e.CHAT_MESSAGE_END_PROCESS="chat.message.end.process",e.CHAT_END="chat.end",e.CHAT_MERGE_BEGIN="chat.merge.begin",e.CHAT_MERGE_MESSAGE_PROCESS="chat.merge.message.process",e.CHAT_MERGE_END="chat.merge.end",e.CHAR_HANDLE_DELETE_SOURCE="chat.message.delete.source",e.CHAT_ERROR="chat.error",e.CHAT_MESSAGE_DELETED="chat.message.deleted",e.CHAT_CLOSE_ROTE_COMMENT_PANEL="chat.close.rote.comment.panel",e.CHAT_RESET_INPUT_TEXTAREA="chat_reset_input_textarea",e.CHAR_REGENERATE_RESPONSE="chat.regenerate.response",e.CHAT_PARSE_URL_BEGIN="chat.message.parse.url",e.CHAT_PARSE_URL_END="chat.message.parse.url.end",e.CHAT_PARSE_URL_ERROR="chat.message.parse.url.error",e.CHAT_SCROLL_TO_BOTTOM="chat.message.scroll.to.bottom",e.CHAT_SELECTED_MODEL_ONMOUNT="chat.selected.model.onmount",e.FILE_PASE_REMOVE="file.pase.remove",e.CHAT_AUDIO_DESTROY="chat.audio.destroy",e.CHAT_EXPAND_ALL_MESSAGES="chat.expand.all.messages",e))(zu||{}),Gu=(e=>(e.MESSAGE_SENT_BEFORE="message.sent.before",e.MESSAGE_SENT="message.sent",e.MESSAGE_VALIDATE_ERROR="message.validate.error",e.MESSAGE_EDIT_SAVE="message.edit.save",e.MESSAGE_FEEDBACK_SUBMIT="message.feedback.submit",e.MESSAGE_STOP_RESPONSE="message.stop.Response",e.MESSAGE_OPEN_TEMPORARY="message.open.temporary",e.MESSAGE_CLEAR_ALL="chear.all.messages",e.MESSAGE_INPUT_PANEL_ACTIVE="message.input.panel.active",e.MESSAGE_LEAVE_CONFIRM="message.leave.confirm",e.MESSAGE_ARTIFACT_SHOW="message.artifact.show",e.MESSAGE_ARTIFACT_DEPLOY_CHANGE="message.artifact.deploy.change",e.MESSAGE_PODCAST_AUDIO_PLAY_START="message.podcast.audio.play.start",e.MESSAGE_STOP_SCROLL_TO_BOTTOM="message.stop.scroll.to.bottom",e.MESSAGE_DEEP_RESEARCH_CLOSE_DETAIL="message.close.deepResearch.detail",e.MESSAGE_EDIT_ARTIFACTS="message.edit.artifacts",e.MESSAGE_STOP_ARTIFACTS_LOOP="message.stop.artifacts.loop",e))(Gu||{}),$u=(e=>(e.SOURCE_CILCK="dp.source.messsage",e))($u||{}),Wu=(e=>(e.QWEN_SEND_MESSAGE="QwenEvent.onSendMessage",e.QWEN_REMOVE_SOURCE="QwenEvent.onRemoveSearchReference",e.QWEN_WEBLOAD="QwenEvent.onWebLoaded",e.QWEN_EVENT_ON_EDIT_MESSAGE="QwenEvent.onEditMessage",e.QWEN_EVENT_ON_CLICK_STOP_BUTTON="QwenEvent.onClickStopButton",e.QWEN_EVENT_ON_OPEN_CHAT="QwenEvent.onOpenChat",e.QWEN_EVENT_ON_DISLIKE_FEEDBACK="QwenEvent.onDislikeFeedback",e.QWEN_EVENT_ON_THEME_CHANGED="QwenEvent.onThemeChanged",e.QWEN_EVENT_ON_LANG_CHANGED="QwenEvent.onLangChanged",e.QWEN_EVENT_ON_CLEAR_ALL_CHATS="QwenEvent.onClearAllChats",e.QWEN_EVENT_ON_LOGOUT="QwenEvent.onLogout",e.QWEN_EVENT_ON_INPUT_PANEL_ACTIVE="QwenEvent.onInputPanelActive",e.QWEN_EVENT_ON_SELECT_MODEL="QwenEvent.onSelectModel",e.QWEN_EVENT_ON_ALERTPOSITIVE_BUTTON_CLICK="QwenEvent.onAlertPositiveButtonClick",e.QWEN_EVENT_ON_CHATCONFIG_CHANGE="QwenEvent.onChatConfigChange",e.QWEN_EVENT_ON_DEPLOY_STATUS_CHANGE="QwenEvent.onDeployStatusChange",e.QWEN_EVENT_ON_USER_PROFILE_UPDATE="QwenEvent.onUserProfileUpdate",e.QWEN_EVENT_ON_USER_PASSWORD_CHANGE="QwenEvent.onUserPasswordChange",e.QWEN_EVENT_ON_PAGE_PAUSE="QwenEvent.onPagePause",e.QWEN_EVENT_ON_PAGE_RESUME="QwenEvent.onPageResume",e.QWEN_EVENT_ON_TSS_SPEAKER_CHANGE="QwenEvent.onTTSSpeakerChange",e.QWEN_EVENT_ON_CALL_ENDED="QwenEvent.onCallEnded",e.QWEN_EVENT_ON_CALL_CONNECTED="QwenEvent.onCallConnected",e.QWEN_EVENT_ON_CALL_COMING="QwenEvent.onCallComing",e.QWEN_EVENT_ON_AUDIO_FOCUS_CHANGE="QwenEvent.onAudioFocusChange",e.QWEN_EVENT_ON_PLAYBACK_STATE_CHANGED="QwenEvent.onPlaybackStateChanged",e.QWEN_EVENT_ON_MEDIA_RATE_CHANGED="QwenEvent.onMediaRateChanged",e.QWEN_EVENT_ON_POST_CONTENT_TO_MAIN_CHAT="QwenEvent.onPostContentToMainChat",e.QWEN_EVENT_ON_SEND_PODCAST="QwenEvent.onSendPodcast",e.QWEN_EVENT_ON_PROMPT_SETTINGS_UPDATE="QwenEvent.onPromptSettingsUpdate",e))(Wu||{}),Vu=(e=>(e.QWEN_CHAT_ONDOWNLOADSTART="QwenChat.onDownloadStart",e.QWEN_CHAT_ONDOWNLOADCOMPLETE="QwenChat.onDownloadComplete",e))(Vu||{}),Qu=(e=>(e.COPY_MESSAGE="navbar.copy.messsage",e.NAVBAR_MODEL_SELECT_CHANGE="navbar.model.select.change",e.MESSAGE_AUDIO_PLAYBACK_CHANGED="message.audio.playback.changed",e.MESSAGE_AUDIO_PLAYBACK_RATE_CHANGED="message.audio.playback.rate.changed",e))(Qu||{}),Ku=(e=>(e.VIEWPORT_RESIZE="viewport.resize",e))(Ku||{}),Yu=(e=>(e.MESSAGE_INPUT_ON_BLUR="message.input.on.blur",e.MESSAGE_INPUT_TRIGGER_FOCUS="message.input.trigger.focus",e.MESSAGE_INPUT_RECOMMEND_WORDS_CLICK="message.input.recommend.words.click",e.MESSAGE_INPUT_RECOMMEND_WORDS_INIT="message.input.recommend.words.init",e))(Yu||{});const Ju=new Bu({wildcard:!0,delimiter:".",newListener:!1,removeListener:!1,maxListeners:30,verboseMemoryLeak:!1,ignoreErrors:!1}),Xu=({filesManager:e,appLayoutEmit:t})=>{const n=ye(),s=cR(e=>e.mobile),i=Kh(e=>e.setFiles),a=yd(e=>e.models),o=yd(e=>e.selectedModelIds),r=js(e=>e.history),l=Kh(e=>e.setVisionSize),c=Kh(e=>e.setInputValue),d=Rs(e=>e.setResearchMode),u=Rs(e=>e.setThinkingEnabled),h=Rs(e=>e.setThinkingMode),m=fR(e=>e.shareDetailData),p=new URLSearchParams(window.location.search),g=p.get("shareId"),f=p.get("lang"),v=Ue(),[y,b]=D.useState(),[x,w]=D.useState(),[_,k]=D.useState({visible:!1}),j=D.useCallback(e=>A(null,null,function*(){var t;const{messageList:n=[],context:s,parentId:i}=e;let a=e.chat_type,o=e.sub_chat_type;if(a===yt.ImageEdit&&o===yt.ImageEdit&&(a=yt.ImageGeneration,o=yt.ImageGeneration),!Ne(s)&&n.length){let e=i,r=s;if(a===yt.DeepResearch&&o===yt.INTERRUPT){const s=Ou(n,"user"),i=n.slice(0,s);r=i.reduce((e,t)=>S(C({},e),{[t.id]:t}),{}),e=null==(t=i[i.length-1])?void 0:t.id,o=yt.DeepResearch}const l=kr({shareId:g,currentId:e,messages:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,S(C({},t),{isShare:!0,fid:e})])),currentResponseIds:[e],chatType:a,subChatType:o});bM.createShareChat(l),bM.shareHistory=l,Promise.resolve().then(()=>{Ju.emit(zu.CHAT_SCROLL_TO_BOTTOM)})}else{const e={shareId:g,chatType:a,subChatType:o};bM.shareHistory=e}}),[g]),T=D.useCallback((e,t,n)=>{const s=yd.getState().models,i=yd.getState().selectedModelIds,{availableModelId:a,availableModelName:o}=(e=>{var t,n,s;const{modelName:i="",selectedModels:a=[],chatType:o,models:r=[],thinking:l}=e,c=r.find(e=>e.name===i),d=a.map(e=>{const{name:t}=r.find(t=>t.id===e)||{};return t});if(d.includes(i)||c){if(!l)return{availableModelId:(null==c?void 0:c.id)||a[0],availableModelName:(null==c?void 0:c.name)||d[0]||""};if(null==(s=null==(n=null==(t=null==c?void 0:c.info)?void 0:t.meta)?void 0:n.capabilities)?void 0:s.thinking)return{availableModelId:c.id,availableModelName:c.name}}const u=r.find(e=>{var t,n,s,i,a,r;return l?(null==(n=null==(t=e.info)?void 0:t.meta.chat_type)?void 0:n.includes(o))&&(null==(i=null==(s=e.info)?void 0:s.meta.capabilities)?void 0:i.thinking):null==(r=null==(a=e.info)?void 0:a.meta.chat_type)?void 0:r.includes(o)});return{availableModelId:(null==u?void 0:u.id)||r[0].id,availableModelName:(null==u?void 0:u.name)||r[0].name}})({modelName:e,selectedModels:i,models:s,chatType:t,thinking:n});return xM.setSingleModel(a),k({visible:o!==e,type:"model"}),a},[]),E=D.useCallback((e,t)=>{var n,s,i,a,o,r;const{shareMessage:c,sharedContent:d}=t;if(e===yt.ImageGeneration){const[e,t]=(null==(a=null==(i=null==(s=null==(n=null==c?void 0:c.content_list)?void 0:n[0])?void 0:s.extra)?void 0:i.output_image_hw)?void 0:a[0])||[];let o=jt["1:1"];Object.values(jt).forEach(n=>{const[s,i]=n.split(":");Math.abs(Number(t)/Number(e)-Number(s)/Number(i))<.1&&(o=n)}),l(o)}else if(e===yt.VideoGeneration){const e=`${(null==(o=null==d?void 0:d[0])?void 0:o.size[0])||16}:${(null==(r=null==d?void 0:d[0])?void 0:r.size[1])||9}`;l(e)}},[l]),N=D.useCallback(t=>{const n=[...t||[]].map(e=>{var t,n,s,i;if("image"===e.showType){const a=null==(s=null==(n=null==(t=e.url.split("?"))?void 0:t[0])?void 0:n.split("/"))?void 0:s.at(-1);e.name=e.name||a,e.file_type=e.file_type||`image/${null==(i=a.split("."))?void 0:i.at(-1)}`}return e});null==e||e.pushFile(n),i([...n])},[e,i]),I=D.useCallback(()=>{const{feature_config:e,sub_chat_type:t}=y||{},n=![yt.DeepResearch,yt.Podcast,yt.DeepResearchWebDev].includes(t)&&Boolean(null==e?void 0:e.thinking_enabled);u(n),(null==e?void 0:e.auto_thinking)?h("Auto"):h(n?"Thinking":"Fast")},[u,h,y]),M=D.useCallback(e=>{"advance"===(null==e?void 0:e.research_mode)&&d("advance")},[d]),R=D.useCallback(e=>{const{chat_type:t,sub_chat_type:n,messageList:s,content:i,files:a}=e;if(t===yt.DeepResearch&&n===yt.INTERRUPT){const e=Ou(s,"user"),t=null==s?void 0:s[e];null==c||c((null==t?void 0:t.content)||""),N(null==t?void 0:t.files)}else null==c||c(i),N(a)},[N,c]),P=D.useCallback((e,t)=>{t===yt.Image2Video?t=yt.VideoGeneration:t===yt.INTERRUPT?t=yt.DeepResearch:t===yt.ImageEdit&&(t=yt.ImageGeneration),e===yt.Image2Video?e=yt.VideoGeneration:e===yt.ImageEdit&&(e=yt.ImageGeneration),bM.emit(Yu.MESSAGE_INPUT_RECOMMEND_WORDS_CLICK,{suggestItem:{chatType:e,subChatType:t},active:e!==yt.Txt2Txt})},[]),L=D.useCallback(e=>{ti()&&bM.adapter.invoke({method:"setSendButtonEnabled",params:{value:e}})},[]),O=D.useCallback(()=>A(null,null,function*(){var e,t,n,s,i,a,o,l,c;if(!r.currentId&&g){L(!1);try{let r;if(r=Ne(m)?yield Sg({shareId:g}):{success:!0,data:m},(null==r?void 0:r.success)&&!(null==r?void 0:r.data))return AR(),void k({visible:!0,type:"deleted"});if(ti()&&!Ne(null==(e=null==r?void 0:r.data)?void 0:e.context)&&"/"===location.pathname)return void v(`/c/new-chat?shareId=${g}&lang=${f}`);if(r.success&&r.data){const e=(null==(t=null==r?void 0:r.data)?void 0:t.shared_message)||{},d=(null==(n=null==r?void 0:r.data)?void 0:n.shared_content)||{},{chat_type:u,sub_chat_type:h,files:m,content:p="",parentId:g,feature_config:f={},id:v}=(null==(s=null==r?void 0:r.data)?void 0:s.last_user_message)||{};let y=[];if(Ne(null==(i=null==r?void 0:r.data)?void 0:i.context)||(y=_r(null==e?void 0:e.id,{messages:S(C({},null==(a=null==r?void 0:r.data)?void 0:a.context),{[v]:null==(o=null==r?void 0:r.data)?void 0:o.last_user_message,[e.id]:e})})),yield j({messageList:y,context:null==(l=null==r?void 0:r.data)?void 0:l.context,parentId:g,chat_type:u,sub_chat_type:h}),ti())return;R({chat_type:u,sub_chat_type:h,messageList:y,content:p,files:m}),P(u,h),M(f),E(u,{shareMessage:e,sharedContent:d}),b(C({},null==(c=null==r?void 0:r.data)?void 0:c.last_user_message)),w(e)}}catch(d){}finally{L(!0),NR()}}else L(!0)}),[r.currentId,g,L,m,v,f,j,R,P,M,E]),q=D.useMemo(()=>{var e;return F.jsxs(wi,{visible:_.visible,title:n.t("Tips"),onCancel:()=>k({visible:!1}),headerBorderNone:!0,maskClosable:!0,closable:!s,type:"confirm",actions:[{text:n.t("Got it"),type:s?"brandprimary":"tertiary",rounded:"circle",onClick:()=>k({visible:!1})}],children:["model"===(null==_?void 0:_.type)?n.t("The model originally used to generate this work is no longer available. We’ve automatically switched you to: {{modelName}}.",{modelName:null==(e=a.find(e=>e.id===o[0]))?void 0:e.name}):"","deleted"===(null==_?void 0:_.type)?n.t("This creation’s original full chat has been deleted and is no longer viewable."):""]})},[n,s,a,o,null==_?void 0:_.type,_.visible]);return D.useEffect(()=>{t&&!ti()||O()},[]),D.useEffect(()=>{var e;Ne(x)||Ne(y)||T(null==x?void 0:x.modelName,null==y?void 0:y.chat_type,!!(null==(e=null==y?void 0:y.feature_config)?void 0:e.thinking_enabled)),Ne(y)||I()},[I,y,x,T]),{renderTipsModels:q}},Zu={memoryBaseModalTitle:"index-module__memory-base-modal-title___z63ib",mainTitle:"index-module__main-title___XZulu",subTitle:"index-module__sub-title___GF6HB"},eh=e=>{var t=e,{visible:n,title:s,subTitle:i,children:a}=t,o=k(t,["visible","title","subTitle","children"]);const r=D.useMemo(()=>F.jsxs("div",{className:Zu.memoryBaseModalTitle,children:[F.jsx("div",{className:Zu.mainTitle,children:s}),F.jsx("div",{className:Zu.subTitle,children:i})]}),[s,i]);return F.jsx(wi,S(C({className:Q(Zu.memoryBaseModal,"memory-base-modal"),visible:n,title:r},o),{children:a}))},th={confirmModalTitle:"index-module__confirm-modal-title___c73V2",mainTitle:"index-module__main-title___j9M1z",subTitle:"index-module__sub-title___Py2WI",confirmModalContent:"index-module__confirm-modal-content___Brxsa"},nh=e=>{const t=ye(),n=e,{title:s,subTitle:i,children:a,className:o,content:r,cancelButtonProps:l,okButtonProps:c,cancelText:d=t.t("Cancel"),okText:u=t.t("Confirm")}=n,h=k(n,["title","subTitle","children","className","content","cancelButtonProps","okButtonProps","cancelText","okText"]);return F.jsx(wi,S(C({className:Q("confirm-modal",th.confirmModal,o),title:F.jsxs("div",{className:th.confirmModalTitle,children:[!!s&&F.jsx("div",{className:th.mainTitle,children:s}),!!i&&F.jsx("div",{className:th.subTitle,children:i})]}),closable:!1,headerBorderNone:!0,width:537,okText:u,cancelText:d,cancelButtonProps:C({type:"ghost",rounded:"circle"},l),okButtonProps:C({type:"brandprimary",rounded:"circle"},c)},h),{children:F.jsx("div",{className:th.confirmModalContent,children:r||a})}))},sh=({loaded:e=!1,fixed:t=!0,absolute:n=!1,center:s=!1})=>{const i=ye();return F.jsx("div",{className:Q("page-loading",{"page-loading-fixed":t&&!n,"page-loading-absolute":n&&!t,"page-loading-center":s&&!t&&!n}),style:{display:"flex",opacity:e?0:1,transition:"opacity 0.2s ease-in-out",pointerEvents:e?"none":"auto"},"aria-hidden":e,children:F.jsx("img",{width:40,src:"https://img.alicdn.com/imgextra/i3/O1CN01zaxxvj1p4f0VrY17j_!!6000000005307-54-tps-180-180.apng",alt:i.t("Loading...")})})},ih=(...e)=>A(null,[...e],function*(e={page_size:50,page_num:1}){return yield TM(`memories/?page_size=${e.page_size}&page_num=${e.page_num}`,{method:"GET"})}),ah=e=>A(null,null,function*(){return yield TM("/memories/delete",{method:"POST",data:e})}),oh="index-module__memory-saved-modal___vGmiq",rh="index-module__memory-saved-modal-content___snbNP",lh="index-module__memory-item___YX7Ga",ch="index-module__memory-item-text___JWfoB",dh="index-module__memory-item-remove___eL0aS",uh="index-module__memory-item-remove-icon___u8luD",hh="index-module__memory-item-operation-area___-1Bb-",mh="index-module__cancel-button___yGuG7",ph="index-module__forget-button___Avzkf",gh="index-module__memory-item-pending-confirmed___RTKVH",fh="index-module__memory-saved-modal-empty___ePDs5",vh=()=>{const e=ye(),[t,n]=D.useState(!0),[s,i]=D.useState(!1),[a,o]=D.useState(!1),[r,l]=D.useState(!1),[c,d]=D.useState(void 0),[u,h]=D.useState(!1),[m,p]=D.useState([]),g=ud(e=>e.showMemorySavedModal),f=ud(e=>e.setShowMemorySavedModal),v=e.t("Saved Memory"),y=e.t("Memory storage can hold up to {{num}} items. If this limit is exceeded, the oldest memories will be removed.",{num:50}),b=()=>{l(!1),o(!1)},x=()=>A(null,null,function*(){i(!0);const t=yield ah({forget_all:a,memory_node_id:c});t&&t.success?(p(a?[]:m.filter(e=>e.memory_node_id!==c)),b(),vi.open({type:"success",content:e.t("Memory cleared.")})):vi.open({type:"error",content:"Memory clear failure, please try again."}),i(!1)}),w=e=>A(null,null,function*(){o(e),e?(d(void 0),l(!0)):yield x()});return D.useEffect(()=>{g&&(n(!0),ih().then(e=>{e&&e.success&&e.data&&p(e.data.memory_nodes),n(!1)}).catch(()=>{n(!1)}))},[g]),F.jsxs(eh,{visible:g,title:v,subTitle:y,width:900,cancelButtonProps:{hidden:!0},okButtonProps:{type:"dangertertiary",rounded:"circle"},cancelText:e.t("Cancel"),okText:e.t("Forget All"),onOk:()=>w(!0),onCancel:()=>{f(!1),n(!0)},footer:!!m.length,children:[F.jsx(nh,{visible:r,title:e.t("Clear Memory"),content:e.t("Forgetting your saved memory means the system will not respond based on recent memory. If you no longer wish to receive personalized responses, you can turn off Saved Memory. Please note: this action cannot be undone."),okText:e.t("Forget"),cancelText:e.t("Cancel"),okButtonProps:{type:"dangerprimary",loading:s},cancelButtonProps:{disabled:s},onCancel:b,onOk:x}),F.jsxs("div",{className:oh,children:[t&&F.jsx(sh,{fixed:!1,absolute:!1,center:!0}),!t&&m.length>0&&F.jsx("div",{className:rh,children:m.map(t=>F.jsx("div",{className:rh,children:F.jsxs("div",{className:Q(lh,{[gh]:c===t.memory_node_id}),children:[F.jsx("div",{className:ch,children:t.content}),c===t.memory_node_id&&u?F.jsxs("div",{className:hh,children:[!s&&F.jsx(xi,{type:"ghost",rounded:"circle",size:"small",className:mh,onClick:()=>{d(void 0),h(!1)},children:e.t("Cancel")}),F.jsx(Si,{title:s?"":e.t("This can't be undone."),placement:"bottom",children:F.jsx(xi,{type:"dangerprimary",rounded:"circle",size:"small",loading:s,className:ph,onClick:()=>w(!1),children:e.t("Forget")})})]}):F.jsx("div",{className:dh,onClick:()=>{d(t.memory_node_id),h(!0)},children:F.jsx(Si,{title:e.t("Forget"),placement:"bottom",children:F.jsx(pi,{type:"icon-delete",className:uh})})})]})},t.memory_node_id))}),!t&&0===m.length&&F.jsx("div",{className:fh,children:e.t("Provide specific details and preferences for personalized responses from Qwen")})]})]})},yh="index-module__memory-notification___Xamem",bh="index-module__close-icon___rawxi",xh="index-module__message___rU90y",wh="index-module__desc___ByPjl",_h="index-module__view-details___tVX6L",Ch=({id:e,message:t,description:n,onClickButton:s})=>{const i=ye(),a=zp(e=>e.clearNotificationById);return F.jsxs("div",{className:yh,children:[F.jsx("div",{className:bh,onClick:()=>{a(e)},children:F.jsx(pi,{type:"icon-close-4"})}),F.jsxs("div",{children:[F.jsx("div",{className:xh,children:t}),F.jsx("div",{className:wh,children:n})]}),F.jsx(xi,{buttonClass:_h,type:"ghost",rounded:"circle",size:"small",onClick:()=>{null==s||s(e)},children:i.t("View Details")})]})},Sh="index-module__qwen-notification___OAErp",kh="index-module__qwen-notification-wrapper___pfYI8",jh="index-module__notification-item___ryoR-",Th="index-module__notification-item-inner___JMxlr",Eh=({children:e,index:t})=>F.jsx("div",{className:jh,style:{transform:`translateY(calc(${100*t}% + ${16*t}px))`},children:F.jsx("div",{className:Th,children:e})}),Nh=()=>{const e=zp(e=>e.notification);return e.length?F.jsx("div",{className:Sh,children:F.jsx("div",{className:kh,children:e.map((e,t)=>e.type===on?F.jsx(Eh,{index:t,children:F.jsx(Ch,C({},e))},e.id):null)})}):null},Ih=e=>{var t,n;const{clearAllNotification:s,setNotification:i,clearNotificationById:a}=zp.getState();s(),i({type:"memory",message:KR("Update Saved Memory"),description:KR("Added {{latest}} new memories. Updated {{existing}} existing memories with new details.",{latest:null==(t=e.detail.new_memories)?void 0:t.length,existing:null==(n=e.detail.updated_memories)?void 0:n.length}),duration:1e4,onClickButton:e=>{a(e),ud.getState().setShowMemoryUpdatedModal(!0)},props:e}),cR.getState().mobile&&Ph()},Ah=class d{constructor(){if(N(this,t,!1),N(this,n,null),N(this,s,0),N(this,i,12),N(this,a,()=>{E(this,t)||(I(this,t,!0),document.addEventListener("visibilitychange",E(this,o)))}),j(this,"destroy",()=>{E(this,l).call(this),document.removeEventListener("visibilitychange",E(this,o))}),N(this,o,()=>{document.hidden?E(this,l).call(this):this.subscribePolling()}),N(this,r,()=>{E(this,l).call(this),I(this,s,0),E(this,n)||I(this,n,window.setInterval(()=>A(this,null,function*(){var e,t;if(E(this,s)>=E(this,i))return void E(this,l).call(this);const n=yield((e="memory")=>A(null,null,function*(){return yield TM(`notifications/latest?type=${e}`,{method:"GET"})}))("memory");if((null==n?void 0:n.success)&&(null==(t=null==(e=n.data)?void 0:e.notifications)?void 0:t.length)>0){const e=n.data.notifications[0];Ih(e)}var a,o,r,c;(a=this,o=s,{set _(e){I(a,o,e,r)},get _(){return E(a,o,c)}})._++,E(this,s)>=E(this,i)&&E(this,l).call(this)}),1e4))}),N(this,l,()=>{E(this,n)&&(window.clearInterval(E(this,n)),I(this,n,null)),I(this,s,0)}),N(this,c,e=>{e?E(this,r).call(this):E(this,l).call(this)}),j(this,"subscribePolling",()=>{var e,t,n;const s=null==(e=cR.getState().config)?void 0:e.memory_version,i=s&&"disable"!==s;wR()||Js()&&li("1.7.0")||!i||((null==(n=null==(t=Jh.getState().settings)?void 0:t.memory)?void 0:n.enable_memory)&&!Rs.getState().temporaryChatEnabled&&E(this,c).call(this,!0),Rs.subscribe(e=>e.temporaryChatEnabled,e=>{var t,n;const s=null==(n=null==(t=Jh.getState().settings)?void 0:t.memory)?void 0:n.enable_memory;E(this,c).call(this,s&&!e)}),Jh.subscribe(e=>{var t,n;return null==(n=null==(t=e.settings)?void 0:t.memory)?void 0:n.enable_memory},e=>{const t=Rs.getState().temporaryChatEnabled;E(this,c).call(this,e&&!t)}))}),E(d,e))return E(d,e);I(d,e,this),E(this,a).call(this)}static getInstance(){return E(this,e)||I(this,e,new d),E(this,e)}};e=new WeakMap,t=new WeakMap,n=new WeakMap,s=new WeakMap,i=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakMap,l=new WeakMap,c=new WeakMap,N(Ah,e,null);const Mh=Ah.getInstance(),Rh=()=>{var e,t,n,s,i,a;const{i18n:o}=ye(),r=Ue(),l=ud(e=>e.showMemoryUpdatedModal),c=ud(e=>e.setShowMemoryUpdatedModal),d=zp(e=>e.memoryNotification);return F.jsx(Ti,{className:"memory-updated-detail-popup-container",open:l,onClose:()=>c(!1),children:F.jsxs("div",{className:"memory-updated-detail-popup",style:{paddingBottom:ri()},onClick:e=>e.stopPropagation(),children:[F.jsxs("div",{className:"memory-updated-detail-popup-header",children:[F.jsx("div",{children:o.t("Update Saved Memory")}),F.jsx("div",{onClick:()=>c(!1),children:F.jsx(pi,{type:"icon-line-x-01"})})]}),F.jsxs("div",{className:"memory-updated-detail-popup-content",style:{minHeight:172-parseInt(ri())+"px",maxHeight:380-parseInt(ri())+"px"},children:[null==(t=null==(e=null==d?void 0:d.detail)?void 0:e.new_memories)?void 0:t.map(e=>F.jsxs("div",{className:"memory-updated-detail-popup-content-item",children:[F.jsx("div",{className:"memory-updated-detail-popup-content-item-type new",children:o.t("New Memory")}),F.jsx("div",{className:"memory-updated-detail-popup-content-item-content",children:e.content})]},e.memory_nodes_id)),null==(s=null==(n=null==d?void 0:d.detail)?void 0:n.updated_memories)?void 0:s.map(e=>F.jsxs("div",{className:"memory-updated-detail-popup-content-item",children:[F.jsx("div",{className:"memory-updated-detail-popup-content-item-type updated",children:o.t("Updated Memory")}),F.jsx("div",{className:"memory-updated-detail-popup-content-item-content",children:e.content})]},e.memory_nodes_id)),null==(a=null==(i=null==d?void 0:d.detail)?void 0:i.cleared_memories)?void 0:a.map(e=>F.jsxs("div",{className:"memory-updated-detail-popup-content-item",children:[F.jsx("div",{className:"memory-updated-detail-popup-content-item-type cleared",children:o.t("Cleared Memory")}),F.jsx("div",{className:"memory-updated-detail-popup-content-item-content line-through",children:e.content})]},e.memory_nodes_id))]}),F.jsx("div",{className:"memory-updated-detail-popup-footer",children:F.jsxs("div",{className:"memory-updated-detail-popup-footer-button",onClick:()=>{c(!1),r("/settings/personalization/memory")},children:[F.jsx(pi,{type:"icon-line-manage",className:"memory-updated-detail-popup-footer-button-icon"}),F.jsx("div",{children:o.t("Manage Memory")})]})})]})})},Ph=()=>{vi.openOnce({type:"message",closable:!1,className:"memory-updated-saved-toast",duration:1e4,content:F.jsxs(F.Fragment,{children:[F.jsxs("div",{className:"memory-updated-saved-toast-content",children:[F.jsx("div",{className:"memory-updated-saved-toast-icon",children:F.jsx(pi,{type:"icon-line-information-circle"})}),F.jsx("div",{className:"memory-updated-saved-toast-text",children:it().t("Update Saved Memory")})]}),F.jsx("div",{className:"memory-updated-saved-toast-btn",onClick:()=>{const e=zp.getState().memoryNotification,t=ud.getState().setShowMemoryUpdatedModal,n={items:[...Re(e,"detail.new_memories",[]).map(e=>({type:"new",markdown:e.content})),...Re(e,"detail.updated_memories",[]).map(e=>({type:"updated",markdown:e.content})),...Re(e,"detail.cleared_memories",[]).map(e=>({type:"cleared",markdown:e.content}))]};ti()?bM.adapter.invoke({method:"openMemoryWindow",params:zs()?n:JSON.stringify(n)}):t(!0),V.destroy()},children:it().t("View")})]})})};yt.Artifacts,yt.DeepResearch,yt.ImageGeneration,yt.VideoGeneration,yt.WebDev,yt.Travel,yt.Thinking,yt.WebSearch,yt.LEARN,yt.Slides;var Lh=(e=>(e.DeepResearch="deep_research",e.Artifacts="artifacts",e.WebSearch="search",e.ImageGeneration="t2i",e.VideoGeneration="t2v",e.Image2Video="i2v",e.Txt2Txt="t2t",e.WebDev="web_dev",e.Thinking="thinking",e.Mcp="mcp",e.ImageEdit="image_edit",e.Travel="travel",e.LEARN="learn",e.Slides="slides",e))(Lh||{}),Oh=(e=>(e.File="file",e.Image="image",e.Video="video",e.Audio="audio",e))(Oh||{}),Dh=(e=>(e[e.Unavailable=0]="Unavailable",e[e.Available=1]="Available",e[e.Hidden=2]="Hidden",e[e.ActiveCancellable=3]="ActiveCancellable",e[e.ActiveUncancellable=4]="ActiveUncancellable",e[e.GuestUnavailable=5]="GuestUnavailable",e))(Dh||{}),Fh=(e=>(e.Enabled="enabled",e.Disabled="disabled",e.Hidden="hidden",e.ActiveCancellable="active_cancellable",e.ActiveUncancellable="active_uncancellable",e.ComingSoon="coming_soon",e.NeedLogin="need_login",e.EquityExhausted="equity_exhausted",e))(Fh||{});const qh={file:"file",image:"image",video:"video",audio:"audio"},Uh=new Set(["thinking","mcp"]),Hh={document:"file",web_search:"search",vision:"image"},Bh={file:"document",search:"web_search",image:"vision"};function zh(e){return Hh[e]||e}function Gh(e){return Bh[e]||e}function $h(e){const t={};for(const[n,s]of Object.entries(e))t[zh(n)]=s;return t}function Wh(e){const t=null==e?void 0:e.chat_type;return t?Array.isArray(t)?t:[t]:[]}function Vh(e){return e.map(zh)}const Qh={mobileRecommendDetailVisible:!1,designStyle:"Minimalist",visionSize:"16:9",messageInputPermissions:{enableSizeSelector:{enable:!1,disabled:!1},enableUpload:{enable:!1,disabled:!1},enableAdvanced:{enable:!1,disabled:!1},enableDesignStyle:{enable:!1,disabled:!1}},inputValue:"",messageType:yt.Txt2Txt,files:[],fileDragging:!1,isFocus:!1,showDetail:!1,wordsShowMore:!1,selectedSuggest:""},Kh=Sn()(_s((e,t)=>C(C({},Qh),((e,t)=>({setMobileRecommendDetailVisible:t=>e({mobileRecommendDetailVisible:t}),setVisionSize:t=>e({visionSize:t}),setDesignStyle:t=>e({designStyle:t}),setInputValue:t=>e({inputValue:t}),setFiles:t=>e({files:t}),setMessageType:({subChatType:t,chatType:n})=>{let s=n;t===yt.WebDev&&(s=yt.WebDev),e({messageType:s})},updateFeatureType:({subChatType:e,chatType:t})=>{const n={};e&&(n.currentInputSubType=e),t&&(n.currentInputFeature=t),js.setState(n)},setMessageInputPermissions:t=>e({messageInputPermissions:t}),onPromptSend:e=>{const{inputValue:n,files:s}=t();bM.beforeSendMessage(C({inputText:n,files:s},e))},resetMessageInput:t=>{if(t&&t.length>0){const n={};t.forEach(e=>{n[e]=Qh[e]}),e(n)}else e(Qh)},setFileDragging:t=>{e({fileDragging:t})},setIsFocus:t=>{e({isFocus:t})},setShowDetail:t=>{e({showDetail:t})},setWordsShowMore:t=>{e({wordsShowMore:t})},setSelectedSuggest:t=>{e({selectedSuggest:t})}}))(e,t)),{name:"messageInputStore",store:"messageInputStore",enabled:!1})),Yh={ui:{chatBubble:!0,autoTags:!0,largeTextAsFile:!0,scrollOnBranchChange:!0,landingPageMode:"",chatDirection:"LTR",params:{},models:[]},model_config:{},manage_cookies:{},memory:{enable_memory:!0,enable_history_memory:!0,memory_version_reminder:!1},settingsToolsDefaultConfig:{},personalization:{name:"",description:"",style:void 0,instruction:"",enable_for_new_chat:!0}},Jh=Sn()(Ss(ps(_s((e,t)=>({isSettingLoading:!0,settings:Yh,mcpSettingList:[],getSettings:()=>A(null,null,function*(){var n;e({isSettingLoading:!0});const s=yield qM();if(!s)return e({isSettingLoading:!1}),Yh;if(s.success&&s.data){const n=s.data||Yh;return ti()?e({settings:S(C({},t().settings),{tts_speaker:n.tts_speaker,tts_speaker_v2:n.tts_speaker_v2,ui:{language:n.ui.language,scrollOnBranchChange:n.ui.scrollOnBranchChange},personalization:n.personalization||Yh.personalization,tools_enabled:n.tools_enabled}),isSettingLoading:!1}):e({settings:S(C({},n),{personalization:n.personalization||Yh.personalization}),isSettingLoading:!1}),n}return vi.open({type:"error",content:(null==(n=s.data)?void 0:n.message)||"获取设置失败"}),e({isSettingLoading:!1}),Yh}),setSettings:t=>A(null,null,function*(){var n;const s=yield UM(t);return s&&s.success?e(e=>{e.settings=s.data}):vi.openOnce({type:"error",content:KR(null==(n=null==s?void 0:s.data)?void 0:n.message)}),s}),setMcpSettingList:t=>e({mcpSettingList:t}),updateLocalUiSettings:t=>A(null,null,function*(){e(e=>{e.settings.ui=C(C({},e.settings.ui),t)})}),updateModelConfig:t=>e(e=>{e.settings.model_config=C(C({},e.settings.model_config),t)}),updateQwenChatSettingsbyNative:e=>A(null,null,function*(){yield UM(e)}),updateQwenChatSettings:n=>A(null,null,function*(){var s;const i=t(),a=bn(i.settings,n);e({settings:a,isSettingLoading:!1});const o=yield UM(n);o&&o.success&&o.data?e({settings:S(C({},o.data),{personalization:o.data.personalization||Yh.personalization}),isSettingLoading:!1}):vi.openOnce({type:"error",content:KR(null==(s=null==o?void 0:o.data)?void 0:s.message)})}),getSettingConfig:()=>A(null,null,function*(){var t,n;const s=yield HM();if(s&&s.success&&s.data){const n=(null==(t=s.data)?void 0:t.tools_enabled)||{};return e({settingsToolsDefaultConfig:C({},n)}),n}return vi.open({type:"error",content:(null==(n=null==s?void 0:s.data)?void 0:n.message)||"获取设置失败"}),{}})}),{name:"settingsStore",store:"settingsStore",enabled:!1}))));let Xh=C({},{enabled:!0,level:"debug",prefix:"[ChatFeatureController]"});const Zh={debug:0,info:1,warn:2,error:3};function em(e){return!!Xh.enabled&&Zh[e]>=Zh[Xh.level]}function tm(e){return 0===e.length?"[]":`[${e.join(", ")}]`}function nm(e){em("info")}function sm(e){em("debug")}function im(e,t,n,s){if(!em("debug"))return}function am(e,t){if(!em("debug"))return;const n=[];t.added&&t.added.length>0&&n.push(`+${tm(t.added)}`),t.removed&&t.removed.length>0&&n.push(`-${tm(t.removed)}`),t.modelSwitched&&n.push("模型已切换"),n.length}function om(e){if(!em("info"))return;e.success;const t=["result="+(e.success?"success":"failed")];e.removedFeatures.length>0&&t.push(`removed=${tm(e.removedFeatures)}`),e.modelSwitched&&t.push(`modelSwitched=true (${e.switchedModelName||"unknown"})`),e.warnings.length>0&&t.push(`warnings=${e.warnings.length}`),!e.success&&e.errorMessage&&t.push(`error="${e.errorMessage}"`)}function rm(e){em("info")}function lm(e,t,n){em("warn")}function cm(e){if(!em("debug"))return}function dm(e,t,n){if(!em("debug"))return;let s=`互斥处理: 选中 ${e}`;t.length>0&&(s+=`, 移除 ${tm(t)}`),n&&(s+=" (Thinking 受保护)")}function um(e){em("warn")}function hm(e){em("info")}function mm(){em("info")}const pm={[Lh.ImageGeneration]:"t2i",[Lh.VideoGeneration]:"t2v",[Lh.ImageEdit]:"image_edit",[Lh.DeepResearch]:"deep_research_deep_research",[Lh.WebSearch]:"search",[Lh.Thinking]:"thinking"},gm={},fm=new Set([...Object.values(Lh),"tts"]),vm={},ym={},bm={[Lh.Thinking]:"thinkingEnabled",[Lh.WebSearch]:"searchEnabled",[Lh.Mcp]:"mcpEnabled",[Lh.ImageGeneration]:"imageGenerateEnabled",[Lh.VideoGeneration]:"videoGenerateEnabled"},xm={[Lh.DeepResearch]:Tt.DeepResearch,[Lh.Artifacts]:Tt.Artifacts,[Lh.WebSearch]:Tt.WebSearch,[Lh.ImageGeneration]:Tt.ImageGeneration,[Lh.VideoGeneration]:Tt.VideoGeneration,[Lh.Image2Video]:Tt.Image2Video,[Lh.Txt2Txt]:Tt.Txt2Txt,[Lh.Travel]:Tt.Travel,[Lh.Slides]:Tt.Slides,[Lh.LEARN]:Tt.LEARN};class wm{constructor(){j(this,"currentSelection"),j(this,"configOverrides",{}),this.currentSelection=this.createEmptySelection()}createEmptySelection(){return{selectedFeatures:[],selectedModels:[],uploadedFileTypes:[],thinkingMode:void 0}}initializeDefaultSelections(){}getStoreSnapshot(){var e,t,n,s,i,a,o,r;const l=null!=(e=this.configOverrides.globalPermissions)?e:this.getGlobalPermissions(),c=null!=(t=this.configOverrides.featureFeatureConfig)?t:this.getFeatureFeatureConfig(),d=null!=(n=this.configOverrides.featureFileConfig)?n:this.getFeatureFileConfig(),u=null!=(s=this.configOverrides.modelList)?s:this.getModelList(),h=null!=(i=this.configOverrides.isLoggedIn)?i:this.getIsLoggedIn(),m=null!=(a=this.configOverrides.featureEquities)?a:this.getFeatureEquities(),p=null!=(o=this.configOverrides.modelEquities)?o:this.getModelEquities(),g=null!=(r=this.configOverrides.defaultModelIds)?r:this.getDefaultModelIds(),f=yd.getState().selectedModelIds||[],v=Kh.getState(),y=this.extractFileTypesFromStore(v.files||[]),b=js.getState(),x={globalPermissions:l,featureFeatureConfig:c,featureFileConfig:d,modelList:u,selectedModelIds:f,defaultModelIds:g,featureEquities:m,modelEquities:p,uploadedFileTypes:y,isLoggedIn:h,prevSubChatType:this.getPrevSubChatTypeFromHistory(b.history)};return sm(),x}getPrevSubChatTypeFromHistory(e){if(!(null==e?void 0:e.currentId)||!(null==e?void 0:e.messages))return;const t=e.messages[e.currentId];if(t){if(t.sub_chat_type)return t.sub_chat_type;if(t.parentId){const n=e.messages[t.parentId];if(null==n?void 0:n.sub_chat_type)return n.sub_chat_type}}}extractFileTypesFromStore(e){if(!e||0===e.length)return[];const t=new Set;for(const n of e){const e="default"===n.file_class?"document":n.file_class;"image"===e?t.add("image"):"video"===e?t.add("video"):"audio"===e?t.add("audio"):"document"!==e&&"file"!==e||t.add("file")}return Array.from(t)}commitToStore(e){rm();const{selectedFeatures:t,selectedModels:n,uploadedFileTypes:s}=e,i=Rs.getState(),a=js.getState(),o=yd.getState();for(const[c,d]of Object.entries(bm)){const e=t.includes(c);if(e!==i[d]){const t=i[`set${d.charAt(0).toUpperCase()}${d.slice(1)}`];"function"==typeof t&&t(e)}}let r=Tt.Txt2Txt;for(const c of t){if(Uh.has(c))continue;const e=xm[c];if(e&&e!==Tt.Txt2Txt){r=e;break}}if(a.currentInputFeature!==r&&a.setCurrentInputFeature(r),e.subChatType){const t=a.currentInputSubType;e.subChatType!==t&&a.setCurrentInputSubType(e.subChatType)}const l=o.selectedModelIds;if(n.length===l.length&&n.every(e=>l.includes(e))||o.setSelectedModelIds(n),e.thinkingMode){const t=i.thinkingMode;e.thinkingMode!==t&&i.setThinkingMode(e.thinkingMode)}this.currentSelection={selectedFeatures:[...t],selectedModels:[...n],uploadedFileTypes:[...s],thinkingMode:e.thinkingMode},this.updateVisibleModels(e)}updateVisibleModels(e){const{modelList:t}=this.config,n=yd.getState(),{selectedFeatures:s}=e,i=this.getMainFeature(s),a=i&&xm[i]||Tt.Txt2Txt,o=Kh.getState().files||[],r=t.filter(e=>{var t,n;if(e.id.includes("qwen3-max")||"Qwen3-Max"===e.name)return!0;const s=a;if(s&&"thinking"!==s&&"mcp"!==s&&"t2t"!==s){if(!((null==(n=null==(t=e.info)?void 0:t.meta)?void 0:n.chat_type)||[]).includes(s))return!1}if(o.length>0){if(!o.every(t=>{var n,s,i;const a="default"===t.file_class?"document":t.file_class;return 1===(null==(i=null==(s=null==(n=e.info)?void 0:n.meta)?void 0:s.abilities)?void 0:i[a])}))return!1}return!0});n.setVisibleModels(r)}getMainFeature(e){for(const t of e)if(!Uh.has(t)&&t!==Lh.Txt2Txt)return t;return null}get config(){var e,t,n,s,i,a,o,r;return{globalPermissions:null!=(e=this.configOverrides.globalPermissions)?e:this.getGlobalPermissions(),featureFeatureConfig:null!=(t=this.configOverrides.featureFeatureConfig)?t:this.getFeatureFeatureConfig(),featureFileConfig:null!=(n=this.configOverrides.featureFileConfig)?n:this.getFeatureFileConfig(),modelList:null!=(s=this.configOverrides.modelList)?s:this.getModelList(),isLoggedIn:null!=(i=this.configOverrides.isLoggedIn)?i:this.getIsLoggedIn(),featureEquities:null!=(a=this.configOverrides.featureEquities)?a:this.getFeatureEquities(),modelEquities:null!=(o=this.configOverrides.modelEquities)?o:this.getModelEquities(),defaultModelIds:null!=(r=this.configOverrides.defaultModelIds)?r:this.getDefaultModelIds()}}getGlobalPermissions(){var e,t;const n=null==(t=null==(e=cR.getState().config)?void 0:e.permissions)?void 0:t.chat;if(!n)return gm;const s={};for(const[i,a]of Object.entries(n))fm.has(i)&&"number"==typeof a&&(s[i]=a);return s}getFeatureFeatureConfig(){var e,t;return(null==(t=null==(e=cR.getState().config)?void 0:e.features)?void 0:t.feature_feature)||vm}getFeatureFileConfig(){var e,t;return(null==(t=null==(e=cR.getState().config)?void 0:e.features)?void 0:t.feature_file)||ym}getModelList(){return yd.getState().models||[]}getIsLoggedIn(){const e=Pd.getState();return void 0!==e.user&&null!==e.user}getFeatureEquities(){const e=Bd.getState(),t={};for(const[n,s]of Object.entries(pm)){const i=e.getFeatureEquity(s);i&&(t[n]={remains:i.remains,unit:i.unit})}return t}getModelEquities(){const e=Bd.getState(),t=this.getModelList(),n={};for(const s of t){const t=e.getModelEquity(s.id);t&&(n[s.id]={remains:t.remains,unit:t.unit,amount:t.amount})}return n}getDefaultModelIds(){var e,t;return(null==(t=null==(e=Jh.getState().settings)?void 0:e.ui)?void 0:t.models)||[]}updateConfig(e){this.configOverrides=C(C({},this.configOverrides),e)}setGlobalPermissions(e){this.configOverrides.globalPermissions=e}setFeatureFeatureConfig(e){this.configOverrides.featureFeatureConfig=e}setFeatureFileConfig(e){this.configOverrides.featureFileConfig=e}setModelList(e){this.configOverrides.modelList=e}setLoggedIn(e){this.configOverrides.isLoggedIn=e}clearConfigOverrides(){this.configOverrides={}}getConfigSnapshot(){return C({},this.config)}getConfigOverrides(){return C({},this.configOverrides)}destroy(){this.configOverrides={}}}function _m(e){return e===Dh.Available||e===Dh.ActiveCancellable||e===Dh.ActiveUncancellable}function Cm(e){return e===Dh.Unavailable||e===Dh.Hidden||e===Dh.GuestUnavailable}function Sm(e,t){var n;if(0===t.length)return null;let s=null;for(const i of t){const t=e.find(e=>e.id===i);if(!(null==(n=null==t?void 0:t.info)?void 0:n.meta))continue;const a=Vh(Wh(t.info.meta)),o=new Set(a.map(e=>e)),r=$h(t.info.meta.abilities||{});for(const[e,n]of Object.entries(r))_m(n)&&o.add(e);if(null===s)s=o;else{const e=new Set;s.forEach(t=>{o.has(t)&&e.add(t)}),s=e}}return s}function km(e,t,n){var s,i;const a=e.find(e=>e.id===t);if(!(null==(s=null==a?void 0:a.info)?void 0:s.meta))return!0;const o=Vh(Wh(a.info.meta)),r=$h(a.info.meta.abilities||{});if(n===Lh.Txt2Txt)return!0;const l=Gh(n),c=null!=(i=r[n])?i:r[l];return void 0!==c?!Cm(c):!(o.length>0&&!o.includes(n)&&!o.includes(l))}function jm(e){return!e||null!==e.remains&&0!==e.remains}function Tm(e,t,n,s){if(!jm(n[t]))return!1;const i=e.find(e=>e.id===t);return!(i&&function(e){var t,n,s;return(null==(s=null==(n=null==(t=null==e?void 0:e.info)?void 0:t.meta)?void 0:n.abilities)?void 0:s.thinking)===Dh.ActiveUncancellable}(i)&&!jm(s))}function Em(e,t,n,s){const i=[],a=[];for(const o of t){Tm(e,o,n,s)?i.push(o):a.push(o)}return{hasEquity:i.length>0,availableModelIds:i,unavailableModelIds:a}}function Nm(e,t,n){for(const s of e){if(Tm(e,s.id,t,n))return s.id}}function Im(e){var t,n,s,i,a;if(!e)return["Thinking","Fast"];const o=!!(null==(n=null==(t=e.info)?void 0:t.meta)?void 0:n.auto_thinking),r=null==(a=null==(i=null==(s=e.info)?void 0:s.meta)?void 0:i.abilities)?void 0:a.thinking;if(o)return 4===r?["Auto","Thinking"]:["Auto","Thinking","Fast"];switch(r){case 1:case 3:default:return["Thinking","Fast"];case 2:return[];case 4:return["Thinking"]}}function Am(e,t){return Im(e).includes(t)}function Mm(e){var t,n,s,i,a;if(!e)return;const o=!!(null==(n=null==(t=e.info)?void 0:t.meta)?void 0:n.auto_thinking),r=null==(a=null==(i=null==(s=e.info)?void 0:s.meta)?void 0:i.abilities)?void 0:a.thinking;if(o)return"Auto";switch(r){case 1:default:return"Fast";case 2:return;case 3:case 4:return"Thinking"}}function Rm(e,t){var n,s;const i=t.filter(e=>e!==Lh.Txt2Txt);if(0===i.length)return null;let a=null;for(const o of i){const t=null!=(s=null!=(n=e[o])?n:e[Gh(o)])?s:[],i=new Set(t.map(e=>zh(e)));if(i.add(o),null===a)a=i;else{const e=new Set;a.forEach(t=>{i.has(t)&&e.add(t)}),a=e}}return a}function Pm(e,t,n){var s,i;const a=[];for(const o of t){if(o===Lh.Txt2Txt)continue;const t=null!=(i=null!=(s=e[o])?s:e[Gh(o)])?i:[],r=new Set(t.map(e=>zh(e)));r.add(o),r.has(n)||a.push(o)}return a}function Lm(e,t,n){const s=e.filter(e=>e!==Lh.Txt2Txt&&!Uh.has(e));if(0===s.length)return Lh.Txt2Txt;const i=s[0],a=function(e,t,n){const s=Nt[e];if(s){const n=Et[e];return t&&(null==n?void 0:n.includes(t))&&s[t]?s[t]:s._default}if(n){const t=Et[e];if(null==t?void 0:t.includes(n))return n}return null}(i,n,t);return a||i}function Om(e,t){if(0===t.length)return null;const n=new Set;for(const[s,i]of Object.entries(e)){const e=zh(s),a=i.map(e=>zh(e));t.every(e=>a.includes(e))&&n.add(e)}return n.add(Lh.Txt2Txt),n}class Dm{constructor(){j(this,"snapshot"),this.snapshot={}}resolve(e,t,n){this.snapshot=e;const s={success:!0,draft:this.createInitialDraft(e,t,n),removedFeatures:[],modelSwitched:!1,warnings:[]},i=this.applyAction(s.draft,t);if(!i.success)return S(C({},s),{success:!1,errorMessage:i.message});s.draft=i.draft;const a=this.applyModelEquitySwitch(s.draft);s.draft=a.draft,s.modelSwitched=a.switched,s.switchedModelName=a.switchedModelName,a.warning&&s.warnings.push(a.warning);let o=0,r=!0;for(;r&&o<10;){const e=this.cloneDraft(s.draft),n=this.applyAutoAddConstraints(s.draft);s.draft=n.draft;const i=this.applyMutexConstraints(s.draft);s.draft=i.draft,s.removedFeatures.push(...i.removed);const a=this.applyDynamicConstraints(s.draft);if(s.draft=a.draft,s.removedFeatures.push(...a.removed),r=!this.isDraftEqual(e,s.draft),o++,"RESET_TO_T2T"===t.type)s.draft.subChatType="t2t";else if("TOGGLE_FEATURE"===t.type){const e=t.payload.subChatType;s.draft.subChatType=Lm(s.draft.selectedFeatures,e,this.snapshot.prevSubChatType)}im(0,0,s.draft)}return o>=10&&um(),delete s.draft.lastActionFeature,delete s.draft.lastDeselectedFeature,delete s.draft.lastActionModel,s.removedFeatures=[...new Set(s.removedFeatures)],s}createInitialDraft(e,t,n){var s,i,a,o,r,l,c;if("INIT"===t.type){const d=(null==(s=null==t?void 0:t.payload)?void 0:s.models)&&(null==(a=null==(i=null==t?void 0:t.payload)?void 0:i.models)?void 0:a.length)>0?[...t.payload.models]:e.defaultModelIds.length>0?[e.defaultModelIds[0]]:(null==(o=e.modelList[0])?void 0:o.id)?[e.modelList[0].id]:[],u=null!=(r=null==n?void 0:n.thinkingMode)?r:this.getDefaultThinkingMode(d),h=function(e,t,n,s){var i,a,o,r;const l=[...e],c=l.includes(Lh.Thinking);let d=s;const u=t[0],h=n.find(e=>e.id===u);if(d&&h){const e=localStorage.getItem(gn),t=Im(h);e&&t.includes(e)&&(d=e),t.includes(d)||(d=null!=(i=Mm(h))?i:"Fast")}c&&"Fast"===s&&h&&1===(null==(r=null==(o=null==(a=h.info)?void 0:a.meta)?void 0:o.abilities)?void 0:r.thinking)&&(d="Thinking");return c||"Auto"!==d&&"Thinking"!==d||l.push(Lh.Thinking),{initFeatures:l,balanceModel:d}}(null!=(c=null==(l=t.payload)?void 0:l.features)?c:[],d,e.modelList,u);return{selectedFeatures:null==h?void 0:h.initFeatures,selectedModels:d,uploadedFileTypes:[...e.uploadedFileTypes],thinkingMode:null==h?void 0:h.balanceModel}}return n?{selectedFeatures:[...n.selectedFeatures],selectedModels:[...n.selectedModels],uploadedFileTypes:[...n.uploadedFileTypes],thinkingMode:n.thinkingMode}:{selectedFeatures:[],selectedModels:[...e.selectedModelIds],uploadedFileTypes:[...e.uploadedFileTypes],thinkingMode:"Fast"}}getDefaultThinkingMode(e){if(0===e.length)return;const t=this.snapshot.modelList.find(t=>t.id===e[0]);if(!t)return;const n=localStorage.getItem(gn);return n&&Am(t,n)?n:Mm(t)}applyAction(e,t){var n,s;const i=it();switch(t.type){case"INIT":{const t=[],i=[];for(const s of e.selectedFeatures){const a=this.canSelectFeature(s,S(C({},e),{selectedFeatures:t}));a.success?t.push(s):i.push({feature:s,reason:null!=(n=a.message)?n:"Unknown reason"})}e.selectedFeatures=t,i.length;const a=[],o=[];for(const n of e.selectedModels){const t=this.canSelectModel(n,S(C({},e),{selectedModels:a}));t.success?a.push(n):o.push({modelId:n,reason:null!=(s=t.message)?s:"Unknown reason"})}if(0===a.length&&this.snapshot.modelList.length>0){const t=S(C({},e),{selectedModels:[]}),n=[...this.snapshot.defaultModelIds,...this.snapshot.modelList.map(e=>e.id)],s=new Set;for(const e of n)if(!s.has(e)&&(s.add(e),this.canSelectModel(e,t).success)){a.push(e);break}}return e.selectedModels=a,o.length,{success:!0,draft:e}}case"TOGGLE_FEATURE":{const{feature:n}=t.payload;if(e.selectedFeatures.includes(n)){const t=this.canDeselectFeature(n,e.selectedModels);if(!t.success)return{success:!1,draft:e,message:t.message};e.selectedFeatures=e.selectedFeatures.filter(e=>e!==n),e.lastDeselectedFeature=n}else{const t=this.canSelectFeature(n,e);if(!t.success)return{success:!1,draft:e,message:t.message};e.selectedFeatures.push(n),e.lastActionFeature=n}return{success:!0,draft:e}}case"SELECT_FEATURE":{const{feature:n}=t.payload;if(e.selectedFeatures.includes(n))return{success:!0,draft:e};const s=this.canSelectFeature(n,e);return s.success?(e.selectedFeatures.push(n),e.lastActionFeature=n,{success:!0,draft:e}):{success:!1,draft:e,message:s.message}}case"DESELECT_FEATURE":{const{feature:n}=t.payload,s=this.canDeselectFeature(n,e.selectedModels);return s.success?(e.selectedFeatures=e.selectedFeatures.filter(e=>e!==n),e.lastDeselectedFeature=n,{success:!0,draft:e}):{success:!1,draft:e,message:s.message}}case"RESET_TO_T2T":{const t=e.selectedFeatures.filter(e=>e!==Lh.Thinking);if((null==t?void 0:t.length)>0){const n=t[0],s=this.canDeselectFeature(n,e.selectedModels);if(!s.success)return{success:!1,draft:e,message:s.message};e.selectedFeatures=e.selectedFeatures.filter(e=>e!==n),e.lastDeselectedFeature=n}return{success:!0,draft:e}}case"SELECT_MODEL":{const{modelId:n}=t.payload;if(e.selectedModels.includes(n))return{success:!0,draft:e};const s=this.canSelectModel(n,e);return s.success?(e.selectedModels.push(n),e.lastActionModel=n,{success:!0,draft:e}):{success:!1,draft:e,message:s.message}}case"DESELECT_MODEL":{const{modelId:n}=t.payload;return e.selectedModels.includes(n)?e.selectedModels.length<=1?{success:!1,draft:e,message:i.t("At least one model must be selected")}:(e.selectedModels=e.selectedModels.filter(e=>e!==n),{success:!0,draft:e}):{success:!0,draft:e}}case"SET_SINGLE_MODEL":{const{modelId:n}=t.payload;if(!this.snapshot.modelList.find(e=>e.id===n))return{success:!1,draft:e,message:i.t("Model does not exist")};return this.checkModelHasEquity(n)?(e.selectedModels=[n],e.lastActionModel=n,{success:!0,draft:e}):{success:!1,draft:e,message:i.t("Model quota exhausted")}}case"SET_MODELS":{const{modelIds:n}=t.payload;if(0===n.length)return{success:!1,draft:e,message:i.t("Model list cannot be empty")};const s=n.filter(e=>this.snapshot.modelList.some(t=>t.id===e));if(0===s.length)return{success:!1,draft:e,message:i.t("No valid models")};const a=e.selectedModels.length!==s.length||e.selectedModels.some((e,t)=>e!==s[t]);return e.selectedModels=s,1===s.length&&a&&(e.lastActionModel=s[0]),{success:!0,draft:e}}case"UPDATE_FILE_TYPES":return e.uploadedFileTypes=[...t.payload.fileTypes],{success:!0,draft:e};case"SET_THINKING_MODE":{const{mode:n}=t.payload;e.thinkingMode=n;const s=e.selectedFeatures.includes(Lh.Thinking);if("Fast"===n){if(s){this.canDeselectFeature(Lh.Thinking,e.selectedModels).success&&(e.selectedFeatures=e.selectedFeatures.filter(e=>e!==Lh.Thinking))}}else if(!s){this.canSelectFeature(Lh.Thinking,e).success&&(e.selectedFeatures.push(Lh.Thinking),e.lastActionFeature=Lh.Thinking)}return{success:!0,draft:e}}default:return{success:!1,draft:e,message:"未知操作类型"}}}canSelectFeature(e,t){const n=it(),{featureEquities:s,isLoggedIn:i}=this.snapshot,a=this.getFeatureDisplayName(e),o=this.getGlobalPermission(e);if(o===Dh.Unavailable)return{success:!1,message:n.t("Coming soon")};if(o===Dh.Hidden)return{success:!1,message:n.t("Feature not available")};if(o===Dh.GuestUnavailable&&!i)return{success:!1,message:n.t("{{capability}} is not supported in guest mode.",{capability:a})};const r=s[e];return!r||-1===r.remains||null!==r.remains&&0!==r.remains?t.selectedModels.length>1&&e!==Lh.Txt2Txt?{success:!1,message:n.t("The function {{capability}} is not supported in battle mode.",{capability:a})}:{success:!0}:{success:!1,message:n.t("Feature quota exhausted")}}canDeselectFeature(e,t){const n=it(),s=this.getEffectiveThinkingPermission(t);return e===Lh.Thinking&&s===Dh.ActiveUncancellable?{success:!1,message:n.t("This feature cannot be disabled")}:{success:!0}}canSelectModel(e,t){const n=it(),{modelList:s}=this.snapshot;if(!s.find(t=>t.id===e))return{success:!1,message:n.t("Model does not exist")};if(!this.checkModelHasEquity(e))return{success:!1,message:n.t("Model quota exhausted")};if(t.selectedModels.length>=3)return{success:!1,message:n.t("You can select up to 3 models")};return t.selectedFeatures.some(e=>e!==Lh.Txt2Txt)&&t.selectedModels.length>=1?{success:!1,message:n.t("Multi-model comparison is not supported when special features are selected. Please use single model selection.")}:{success:!0}}applyModelEquitySwitch(e){var t,n;const{modelEquities:s,featureEquities:i,modelList:a,defaultModelIds:o}=this.snapshot;if(e.selectedModels.every(e=>this.checkModelHasEquity(e)))return{draft:e,switched:!1};e.selectedModels;for(const l of o)if(this.checkModelHasEquity(l)){const n=(null==(t=a.find(e=>e.id===l))?void 0:t.name)||l;return lm(),{draft:S(C({},e),{selectedModels:[l]}),switched:!0,switchedModelName:n,warning:`模型权益已用尽,已自动切换到 ${n}`}}const r=Nm(a,s,i[Lh.Thinking]);if(r){const t=(null==(n=a.find(e=>e.id===r))?void 0:n.name)||r;return lm(),{draft:S(C({},e),{selectedModels:[r]}),switched:!0,switchedModelName:t,warning:`模型权益已用尽,已自动切换到 ${t}`}}return um(),{draft:e,switched:!1,warning:"所有模型权益已用尽"}}applyAutoAddConstraints(e){const t=[],n=this.getEffectiveThinkingPermission(e.selectedModels),s=e.selectedModels.length>0?this.snapshot.modelList.find(t=>t.id===e.selectedModels[0]):void 0,i=()=>{const e=localStorage.getItem(gn);if(e&&Am(s,e))return e},a=()=>{var t;const n=i();e.thinkingMode=null!=(t=null!=n?n:Mm(s))?t:"Fast"};if(n===Dh.ActiveUncancellable)e.selectedFeatures.includes(Lh.Thinking)||(e.selectedFeatures.push(Lh.Thinking),t.push(Lh.Thinking),a(),cm(),am(0,{added:[Lh.Thinking]}));else if(n===Dh.ActiveCancellable||n===Dh.Available){const n=this.getAllowedFeaturesFor(Lh.Thinking),s=!!e.lastDeselectedFeature&&!n.has(e.lastDeselectedFeature),o=!e.selectedFeatures.some(e=>e!==Lh.Txt2Txt&&!n.has(e)),r=i();void 0!==r&&"Fast"!==r&&(s&&o||e.lastActionModel)&&!e.selectedFeatures.includes(Lh.Thinking)&&(e.selectedFeatures.push(Lh.Thinking),t.push(Lh.Thinking),a(),cm(),am(0,{added:[Lh.Thinking]}))}if(e.lastActionModel&&e.thinkingMode){const t=Im(s),n=e.thinkingMode,a=e.selectedFeatures.includes(Lh.Thinking);if(0===t.length)e.thinkingMode="Fast",a&&(e.selectedFeatures=e.selectedFeatures.filter(e=>e!==Lh.Thinking)),am(0,{});else if(t.includes(n)){if("Thinking"===n&&t.includes("Auto")&&a){const t=i();e.thinkingMode=t||"Auto",am(0,{})}}else a?t.includes("Thinking")?(e.thinkingMode="Thinking",am(0,{})):t.includes("Fast")&&(e.thinkingMode="Fast",e.selectedFeatures=e.selectedFeatures.filter(e=>e!==Lh.Thinking),am(0,{})):t.includes("Fast")?e.thinkingMode="Fast":t.includes("Thinking")&&(e.thinkingMode="Thinking")}return{draft:e,added:t}}applyMutexConstraints(e){const{featureFeatureConfig:t}=this.snapshot,{selectedFeatures:n,lastActionFeature:s}=e,i=[],a=this.getEffectiveThinkingPermission(e.selectedModels)===Dh.ActiveUncancellable;if(a&&n.includes(Lh.Thinking)){const o=this.getAllowedFeaturesFor(Lh.Thinking),r=n.filter(e=>e!==Lh.Thinking&&e!==Lh.Txt2Txt&&!o.has(e));r.length>0&&(e.selectedFeatures=n.filter(e=>!r.includes(e)),i.push(...r),dm(Lh.Thinking,r,!0),am(0,{removed:r}));const l=e.selectedFeatures,c=s&&l.includes(s)?s:null;if(c&&c!==Lh.Thinking){const n=Pm(t,l,c).filter(e=>e!==Lh.Thinking);n.length>0&&(e.selectedFeatures=l.filter(e=>!n.includes(e)),i.push(...n),dm(c,n,a),am(0,{removed:n}),n.includes(Lh.Thinking)&&(e.thinkingMode="Fast"),e.lastDeselectedFeature=n[n.length-1])}}else{const o=s&&n.includes(s)?s:n.length>1&&n.includes(Lh.Thinking)?n.find(e=>e!==Lh.Thinking):null;if(o){const s=Pm(t,n,o).filter(e=>!(e===Lh.Thinking&&a));s.length>0&&(e.selectedFeatures=n.filter(e=>!s.includes(e)),i.push(...s),dm(o,s,a),am(0,{removed:s}),s.includes(Lh.Thinking)&&(e.thinkingMode="Fast"),e.lastDeselectedFeature=s[s.length-1])}}return{draft:e,removed:i}}applyDynamicConstraints(e){const{modelList:t,featureFileConfig:n}=this.snapshot,{selectedModels:s,selectedFeatures:i,uploadedFileTypes:a}=e,o=[];let r=[...i];const l=this.getEffectiveThinkingPermission(s)===Dh.ActiveUncancellable;if(s.length>1){const t=r.filter(e=>e!==Lh.Txt2Txt);if(t.length>0){const e=t.filter(e=>e!==Lh.Thinking||!l);o.push(...e),r=r.filter(t=>!e.includes(t)),e.length>0&&am(0,{removed:e})}r.includes(Lh.Thinking)||"Fast"===e.thinkingMode||(e.thinkingMode="Fast")}const c=Sm(t,s);if(null!==c){const e=r.filter(e=>e!==Lh.Txt2Txt&&((e!==Lh.Thinking||!l)&&!c.has(e)));e.length>0&&(o.push(...e),r=r.filter(t=>!e.includes(t)),am(0,{removed:e}))}const d=Om(n,a);if(null!==d){const e=r.filter(e=>e!==Lh.Txt2Txt&&((e!==Lh.Thinking||!l)&&!d.has(e)));e.length>0&&(o.push(...e),r=r.filter(t=>!e.includes(t)),am(0,{removed:e}))}return o.includes(Lh.Thinking)&&"Fast"!==e.thinkingMode&&(e.thinkingMode="Fast"),{draft:S(C({},e),{selectedFeatures:r}),removed:o}}getGlobalPermission(e){var t,n;const{globalPermissions:s}=this.snapshot,i=e,a=Gh(e);return null!=(n=null!=(t=s[i])?t:s[a])?n:Dh.Available}getEffectiveThinkingPermission(e){var t,n,s,i,a;const{globalPermissions:o,modelList:r}=this.snapshot,l=e||this.snapshot.selectedModelIds;let c=null!=(n=null!=(t=o[Lh.Thinking])?t:o.thinking)?n:Dh.Available;if(1===l.length){const e=r.find(e=>e.id===l[0]);void 0!==(null==(a=null==(i=null==(s=null==e?void 0:e.info)?void 0:s.meta)?void 0:i.abilities)?void 0:a.thinking)&&(c=e.info.meta.abilities.thinking)}return c}getAllowedFeaturesFor(e){var t,n;const{featureFeatureConfig:s}=this.snapshot,i=null!=(n=null!=(t=s[e])?t:s[Gh(e)])?n:[],a=new Set(i.map(e=>zh(e)));return a.add(e),a.add(Lh.Txt2Txt),a}checkModelHasEquity(e){const{modelEquities:t,featureEquities:n,modelList:s}=this.snapshot;return Tm(s,e,t,n[Lh.Thinking])}getFeatureDisplayName(e){const t=it();return{[Lh.DeepResearch]:t.t("Deep Research"),[Lh.Artifacts]:t.t("Artifacts"),[Lh.WebSearch]:t.t("Search"),[Lh.ImageGeneration]:t.t("Image Generation"),[Lh.VideoGeneration]:t.t("Video Generation"),[Lh.Image2Video]:t.t("Image-to-Video"),[Lh.Txt2Txt]:t.t("Text Chat"),[Lh.WebDev]:t.t("Web Dev"),[Lh.Thinking]:t.t("Thinking"),[Lh.Mcp]:t.t("MCP"),[Lh.ImageEdit]:t.t("Image Edit"),[Lh.Travel]:t.t("Travel"),[Lh.LEARN]:t.t("Learn"),[Lh.Slides]:t.t("Slides")}[e]||e}cloneDraft(e){return{selectedFeatures:[...e.selectedFeatures],selectedModels:[...e.selectedModels],uploadedFileTypes:[...e.uploadedFileTypes],lastActionFeature:e.lastActionFeature,lastDeselectedFeature:e.lastDeselectedFeature,lastActionModel:e.lastActionModel}}isDraftEqual(e,t){if(e.selectedFeatures.length!==t.selectedFeatures.length)return!1;if(e.selectedModels.length!==t.selectedModels.length)return!1;if(e.uploadedFileTypes.length!==t.uploadedFileTypes.length)return!1;const n=[...e.selectedFeatures].sort(),s=[...t.selectedFeatures].sort();if(!n.every((e,t)=>e===s[t]))return!1;const i=[...e.selectedModels].sort(),a=[...t.selectedModels].sort();if(!i.every((e,t)=>e===a[t]))return!1;const o=[...e.uploadedFileTypes].sort(),r=[...t.uploadedFileTypes].sort();return!!o.every((e,t)=>e===r[t])}}const Fm={[Lh.DeepResearch]:{displayNameKey:"Deep Research",subtypes:["deep_thinking","deep_research","t2t"],mapToInputFeature:!0},[Lh.Artifacts]:{displayNameKey:"Artifacts",subtypes:["artifacts","web_dev"],mapToInputFeature:!0},[Lh.WebSearch]:{displayNameKey:"Search",subtypes:["search"],mapToInputFeature:!0},[Lh.ImageGeneration]:{displayNameKey:"Image Generation",subtypes:["t2i"],mapToInputFeature:!0},[Lh.VideoGeneration]:{displayNameKey:"Video Generation",subtypes:["t2v"],mapToInputFeature:!0},[Lh.Image2Video]:{displayNameKey:"Image-to-Video",subtypes:["i2v"],mapToInputFeature:!0},[Lh.Txt2Txt]:{displayNameKey:"Text Chat",subtypes:["t2t"],mapToInputFeature:!0},[Lh.WebDev]:{displayNameKey:"Web Dev",subtypes:["web_dev"],mapToInputFeature:!1},[Lh.Thinking]:{displayNameKey:"Thinking",subtypes:["thinking"],isAuxiliary:!0,mapToInputFeature:!1},[Lh.Mcp]:{displayNameKey:"MCP",subtypes:["mcp"],isAuxiliary:!0,mapToInputFeature:!1},[Lh.ImageEdit]:{displayNameKey:"Image Edit",subtypes:["image_edit"],mapToInputFeature:!1},[Lh.Travel]:{displayNameKey:"Travel",subtypes:["travel","travel_feedback","travel_research"],mapToInputFeature:!0},[Lh.LEARN]:{displayNameKey:"Learn",subtypes:["learn"],mapToInputFeature:!0},[Lh.Slides]:{displayNameKey:"Slides",subtypes:["slides"],mapToInputFeature:!0}};function qm(e,t){const n=Fm[e];return(null==n?void 0:n.displayNameKey)?t.t(n.displayNameKey):e}function Um(e){return qm(e,it())}function Hm(e,t,n){var s,i,a,o,r;const{globalPermissions:l,modelList:c}=e,d=t,u=Gh(t);let h=null!=(i=null!=(s=l[d])?s:l[u])?i:Dh.Available;if(n){const e=c.find(e=>e.id===n);if(null==(o=null==(a=null==e?void 0:e.info)?void 0:a.meta)?void 0:o.abilities){const t=$h(e.info.meta.abilities),n=null!=(r=t[d])?r:t[u];void 0!==n&&(h=n)}}return h}function Bm(e,t,n,s,i,a,o){var r,l;const{currentSelection:c,featureEquities:d,modelList:u,featureFeatureConfig:h}=e,{selectedModels:m}=c,p=Hm(e,t),g=it(),f=Um(t);if(p===Dh.Unavailable){const e=g.t("Coming soon");return{feature:t,status:Fh.ComingSoon,selected:!1,toggleable:!1,tooltip:e,disabledInfo:{disabled:!0,msg:e}}}if(p===Dh.Hidden)return null;if(p===Dh.GuestUnavailable&&!e.isLoggedIn){const e=g.t("{{capability}} is not supported in guest mode.",{capability:f});return{feature:t,status:Fh.NeedLogin,selected:!1,toggleable:!1,tooltip:e,disabledInfo:{disabled:!0,msg:e}}}if(p===Dh.ActiveUncancellable)return{feature:t,status:Fh.ActiveUncancellable,selected:!0,toggleable:!1,tooltip:g.t("This feature is enabled by default and cannot be disabled"),disabledInfo:{disabled:!1,msg:""}};const v=d[t];if(v&&-1!==v.remains&&(null===v.remains||0===v.remains)){const e=du({remains:v.remains,unit:v.unit||"day",capability:f,allowHtml:!0,currentI18n:g});return{feature:t,status:Fh.EquityExhausted,selected:!1,toggleable:!1,tooltip:e,equityInfo:v,disabledInfo:{disabled:!0,msg:e}}}if(s){const e=g.t("The function {{capability}} is not supported in battle mode.",{capability:f});return{feature:t,status:Fh.Disabled,selected:!1,toggleable:!1,disabledReason:e,equityInfo:v,disabledInfo:{disabled:!0,msg:e}}}if(null!==o&&o.has(t)){if(Hm(e,Lh.Thinking,m[0])===Dh.ActiveUncancellable){const e=null!=(l=null!=(r=h[Lh.Thinking])?r:h[Gh(Lh.Thinking)])?l:[];if(!e.includes(t)&&!e.includes(Gh(t))){const e=m.map(e=>{var t;return(null==(t=u.find(t=>t.id===e))?void 0:t.name)||e}).join("、"),n=g.t("{{model}} does not support {{capability}}",{model:e,capability:f});return{feature:t,status:Fh.Disabled,selected:!1,toggleable:!1,disabledReason:n,equityInfo:v,disabledInfo:{disabled:!0,msg:n}}}}}if(null!==a&&!a.has(t)){const e=g.t("The selected model or feature does not support the file type you uploaded.");return{feature:t,status:Fh.Disabled,selected:!1,toggleable:!1,disabledReason:e,equityInfo:v,disabledInfo:{disabled:!0,msg:e}}}if(null!==o&&!o.has(t)){const e=m.map(e=>{var t;return(null==(t=u.find(t=>t.id===e))?void 0:t.name)||e}).join("、"),n=g.t("{{model}} does not support {{capability}}",{model:e,capability:f});return{feature:t,status:Fh.Disabled,selected:!1,toggleable:!1,disabledReason:n,equityInfo:v,disabledInfo:{disabled:!0,msg:n}}}if(1===m.length){const s=function(e,t,n,s){var i;const a=it(),o=Hm(e,t,n),r=(null==(i=e.modelList.find(e=>e.id===n))?void 0:i.name)||n,l=Um(t);if(o===Dh.Unavailable){const e=a.t("{{model}} does not support {{capability}}",{model:r,capability:l});return{feature:t,status:Fh.Disabled,selected:!1,toggleable:!1,disabledReason:e,disabledInfo:{disabled:!0,msg:e}}}return o===Dh.Hidden?null:o===Dh.ActiveUncancellable?{feature:t,status:Fh.ActiveUncancellable,selected:!0,toggleable:!1,tooltip:a.t("Model ({{model}}) requires this feature to be enabled",{model:r}),disabledInfo:{disabled:!1,msg:""}}:o!==Dh.ActiveCancellable||s?null:{feature:t,status:Fh.Enabled,selected:!1,toggleable:!0,tooltip:a.t("This feature is enabled by default for this model"),disabledInfo:{disabled:!1,msg:""}}}(e,t,m[0],n);if(s)return s}return{feature:t,status:n?Fh.ActiveCancellable:Fh.Enabled,selected:n,toggleable:!0,equityInfo:v,disabledInfo:{disabled:!1,msg:""}}}function zm(e,t){const{currentSelection:n,featureFeatureConfig:s,featureFileConfig:i,modelList:a}=e,{selectedFeatures:o,selectedModels:r,uploadedFileTypes:l}=n,c=r.length>1,d=(Rm(s,o),Om(i,l)),u=Sm(a,r);return Bm(e,t,o.includes(t),c,0,d,u)}function Gm(e){const t=it(),{currentSelection:n,featureFeatureConfig:s,featureEquities:i}=e,{selectedFeatures:a}=n,o=zm(e,Lh.Thinking),r=function(e,t){var n,s;const i=t.filter(e=>e!==Lh.Txt2Txt&&!Uh.has(e));if(0===i.length)return!0;for(const a of i){const t=null!=(s=null!=(n=e[a])?n:e[Gh(a)])?s:[];if(!new Set(t.map(e=>zh(e))).has(Lh.Thinking))return!1}return!0}(s,a);if(!r)return{feature:Lh.Thinking,status:Fh.Hidden,selected:!1,toggleable:!1,disabledInfo:{disabled:!0,msg:""},tooltipText:"",enabled:!1};if(!o)return{feature:Lh.Thinking,status:Fh.Hidden,selected:!1,toggleable:!1,disabledInfo:{disabled:!0,msg:""},tooltipText:"",enabled:!1};let l="";const c=Um(Lh.Thinking),d=o.equityInfo||i[Lh.Thinking];l=o.disabledInfo.disabled&&o.disabledInfo.msg?o.disabledInfo.msg:o.tooltip?o.tooltip:d&&-1!==d.remains&&null!==d.remains?du({remains:d.remains||0,unit:d.unit||"day",capability:c,allowHtml:!0,currentI18n:t}):o.selected?t.t("Thinking: on"):t.t("Thinking: off");const u=o.status!==Fh.Hidden;return S(C({},o),{tooltipText:l,enabled:u})}function $m(e,t,n,s,i,a){const{modelList:o,modelEquities:r,featureEquities:l}=e,c=n.includes(t.id),d=l[Lh.Thinking];if(!Tm(o,t.id,r,d)&&!c)return{model:t,status:Fh.EquityExhausted,selected:!1,selectable:!1,disabledReason:"此模型权益已用尽"};if(a&&!c&&!function(e,t,n){for(const s of n)if(!Uh.has(s)&&!km(e,t,s))return!1;return!0}(o,t.id,s)){const e=s.filter(e=>e!==Lh.Txt2Txt).join("、");return{model:t,status:Fh.Disabled,selected:!1,selectable:!1,disabledReason:`此模型不支持当前选中的功能(${e})`}}if(i.length>0&&!c&&!function(e,t,n){var s,i;if(0===n.length)return!0;const a=e.find(e=>e.id===t);if(!(null==(i=null==(s=null==a?void 0:a.info)?void 0:s.meta)?void 0:i.abilities)){const e=[Oh.Audio,Oh.Video];for(const t of n)if(e.includes(t))return!1;return!0}const o=$h(a.info.meta.abilities);for(const r of n){const e=o[qh[r]];if(void 0!==e){if(Cm(e))return!1}else if(r!==Oh.File&&r!==Oh.Image)return!1}return!0}(o,t.id,i))return{model:t,status:Fh.Disabled,selected:!1,selectable:!1,disabledReason:`此模型不支持当前上传的文件类型(${i.join("、")})`};let u;return a&&n.length>=1&&!c&&(u="切换模型将保持当前功能选中状态"),{model:t,status:c?Fh.ActiveCancellable:Fh.Enabled,selected:c,selectable:!0,tooltip:u}}function Wm(e){const{currentSelection:t,modelList:n}=e,{selectedModels:s,selectedFeatures:i,uploadedFileTypes:a}=t,o=function(e){return e.some(e=>e!==Lh.Txt2Txt)}(i);return n.map(t=>$m(e,t,s,i,a,o)).filter(e=>null!==e)}function Vm(e){const{currentSelection:t,modelList:n,modelEquities:s,featureEquities:i,defaultModelIds:a}=e,{selectedModels:o}=t,r=i[Lh.Thinking];if(Em(n,o,s,r).hasEquity)return{needSwitch:!1,suggestedModelIds:o};if(a.length>0){if(Em(n,a,s,r).hasEquity)return{needSwitch:!0,suggestedModelIds:a,reason:"当前选中模型权益已用尽,已切换至默认模型"}}const l=Nm(n,s,r);return l?{needSwitch:!0,suggestedModelIds:[l],reason:"当前选中模型权益已用尽,已切换至可用模型"}:{needSwitch:!0,suggestedModelIds:[],reason:"所有模型权益已用尽"}}function Qm(e,t,n,s,i){var a;const{currentSelection:o,modelList:r}=e,{selectedModels:l,selectedFeatures:c}=o;if(null!==s&&!s.has(t)){const e=c.filter(e=>e!==Lh.Txt2Txt).join("、");return{fileType:t,status:Fh.Disabled,disabled:!0,disabledReason:`当前选中的功能(${e})不支持上传此类型文件`}}if(null!==i&&!i.has(t)){const e=l.map(e=>{var t;return(null==(t=r.find(t=>t.id===e))?void 0:t.name)||e}).join("、");return{fileType:t,status:Fh.Disabled,disabled:!0,disabledReason:n?"多模型对比模式下,所选模型不全支持此类型文件":`当前模型(${e})不支持此类型文件`}}if(1===l.length){const n=function(e,t,n){var s,i,a,o;const{globalPermissions:r,modelList:l}=e,c=t,d=Gh(t);let u=null!=(i=null!=(s=r[c])?s:r[d])?i:Dh.Available;if(n){const e=l.find(e=>e.id===n);if(null==(o=null==(a=null==e?void 0:e.info)?void 0:a.meta)?void 0:o.abilities){const n=$h(e.info.meta.abilities)[qh[t]];void 0!==n&&(u=n)}}return u}(e,t,l[0]);if(Cm(n)){const e=(null==(a=r.find(e=>e.id===l[0]))?void 0:a.name)||l[0];return{fileType:t,status:Fh.Disabled,disabled:!0,disabledReason:`模型(${e})不支持上传此类型文件`}}}return{fileType:t,status:Fh.Enabled,disabled:!1}}function Km(e){const{currentSelection:t,featureFileConfig:n,modelList:s}=e,{selectedModels:i,selectedFeatures:a}=t,o=i.length>1,r=function(e,t){var n,s;const i=t.filter(e=>e!==Lh.Txt2Txt);if(0===i.length)return null;let a=null;for(const o of i){const t=null!=(s=null!=(n=e[o])?n:e[Gh(o)])?s:[],i=new Set(t.map(e=>zh(e)));if(null===a)a=i;else{const e=new Set;a.forEach(t=>{i.has(t)&&e.add(t)}),a=e}}return a}(n,a),l=function(e,t){var n,s;if(0===t.length)return null;const i=Object.values(Oh);let a=new Set(i);for(const o of t){const t=e.find(e=>e.id===o);if(!(null==(s=null==(n=null==t?void 0:t.info)?void 0:n.meta)?void 0:s.abilities))continue;const r=$h(t.info.meta.abilities),l=new Set;for(const e of i)_m(r[qh[e]])&&l.add(e);a=new Set([...a].filter(e=>l.has(e)))}return a}(s,i);return Object.values(Oh).map(t=>Qm(e,t,o,r,l))}const Ym=class e extends wm{constructor(){super(),j(this,"onStateChangeCallback"),j(this,"resolver"),this.resolver=new Dm}commitToStore(e){super.commitToStore(e),this.updateFeatureStatuses(),this.updateThinkingStatus(),this.updateFileTypeStatuses()}updateFeatureStatuses(){const e=this.getFeatureStatuses();Rs.getState().setFeatureStatuses(e)}updateThinkingStatus(){const e=this.getThinkingStatus();Rs.getState().setThinkingStatus(e)}updateFileTypeStatuses(){const e=this.getFileTypeStatuses();Rs.getState().setFileTypeStatuses(e)}static getInstance(){return e.instance||(e.instance=new e),e.instance}static resetInstance(){e.instance&&(e.instance.destroy(),e.instance=null)}init(e){var t;hm();const n={type:"INIT",payload:e};nm();const s=this.getStoreSnapshot(),i=this.resolver.resolve(s,n,this.currentSelection);return om(i),i.success?(this.commitToStore(i.draft),null==(t=this.onStateChangeCallback)||t.call(this),mm(),{success:!0,autoFixed:i.removedFeatures.length>0||i.modelSwitched,warnings:i.warnings,removedFeatures:i.removedFeatures,modelSwitched:i.modelSwitched,draft:i.draft}):(mm(),{success:!1,autoFixed:!1,warnings:i.warnings,removedFeatures:[],modelSwitched:!1,draft:i.draft})}refresh(){var e;const t=this.getStoreSnapshot();this.currentSelection={selectedFeatures:this.extractSelectedFeaturesFromSnapshot(t),selectedModels:[...t.selectedModelIds],uploadedFileTypes:[...t.uploadedFileTypes]},null==(e=this.onStateChangeCallback)||e.call(this)}extractSelectedFeaturesFromSnapshot(e){var t,n,s,i,a,o;const r=[],{globalPermissions:l,modelList:c,selectedModelIds:d}=e;let u={};if(1===d.length){const e=c.find(e=>e.id===d[0]);(null==(n=null==(t=null==e?void 0:e.info)?void 0:t.meta)?void 0:n.abilities)&&(u=$h(e.info.meta.abilities))}for(const h of Object.values(Lh)){if(h===Lh.Txt2Txt)continue;const e=h,t=Gh(h),n=null!=(o=null!=(a=null!=(i=null!=(s=u[e])?s:u[t])?i:l[e])?a:l[t])?o:Dh.Available;n!==Dh.ActiveCancellable&&n!==Dh.ActiveUncancellable||r.push(h)}return r}setOnStateChangeCallback(e){this.onStateChangeCallback=e}forceRefresh(){this.refresh()}refreshAndSyncToStore(){this.refresh(),this.updateFeatureStatuses(),this.updateThinkingStatus(),this.updateFileTypeStatuses()}toggleFeature(e,t){var n;if(this.currentSelection.selectedFeatures.includes(e)&&t)return this.commitToStore({selectedFeatures:[...this.currentSelection.selectedFeatures],selectedModels:[...this.currentSelection.selectedModels],uploadedFileTypes:[...this.currentSelection.uploadedFileTypes],thinkingMode:this.currentSelection.thinkingMode}),{success:!0};const s={type:"TOGGLE_FEATURE",payload:{feature:e,subChatType:t}};nm();const i=this.getStoreSnapshot(),a=this.resolver.resolve(i,s,this.currentSelection);if(om(a),!a.success)return{success:!1,message:a.errorMessage};this.commitToStore(a.draft),null==(n=this.onStateChangeCallback)||n.call(this);const o={success:!0};if(a.removedFeatures.length>0){const e=a.removedFeatures.map(e=>Um(e)).join("、");o.message=`已自动取消与其冲突的功能:${e}`,o.removedFeatures=a.removedFeatures}return a.modelSwitched&&(o.modelSwitched=!0,o.switchedModelName=a.switchedModelName),a.warnings.length>0&&(o.warnings=a.warnings),o}selectFeature(e){var t;if(this.currentSelection.selectedFeatures.includes(e))return{success:!0};const n={type:"SELECT_FEATURE",payload:{feature:e}};nm();const s=this.getStoreSnapshot(),i=this.resolver.resolve(s,n,this.currentSelection);return om(i),i.success?(this.commitToStore(i.draft),null==(t=this.onStateChangeCallback)||t.call(this),{success:!0,removedFeatures:i.removedFeatures,warnings:i.warnings}):{success:!1,message:i.errorMessage}}deselectFeature(e){var t;const n={type:"DESELECT_FEATURE",payload:{feature:e}};nm();const s=this.getStoreSnapshot(),i=this.resolver.resolve(s,n,this.currentSelection);return om(i),i.success?(this.commitToStore(i.draft),null==(t=this.onStateChangeCallback)||t.call(this),{success:!0}):{success:!1,message:i.errorMessage}}resetToTxt2Txt(){var e;const t={type:"RESET_TO_T2T"};nm();const n=this.getStoreSnapshot(),s=this.resolver.resolve(n,t,this.currentSelection);return om(s),s.success?(this.commitToStore(s.draft),null==(e=this.onStateChangeCallback)||e.call(this),{success:!0}):{success:!1,message:s.errorMessage}}toggleModelSelection(e){return this.currentSelection.selectedModels.includes(e)?this.deselectModel(e):this.selectModel(e)}selectModel(e){var t;const n={type:"SELECT_MODEL",payload:{modelId:e}};nm();const s=this.getStoreSnapshot(),i=this.resolver.resolve(s,n,this.currentSelection);return om(i),i.success?(this.commitToStore(i.draft),null==(t=this.onStateChangeCallback)||t.call(this),{success:!0,removedFeatures:i.removedFeatures,warnings:i.warnings,modelSwitched:i.modelSwitched,switchedModelName:i.switchedModelName}):{success:!1,message:i.errorMessage}}deselectModel(e){var t;const n={type:"DESELECT_MODEL",payload:{modelId:e}};nm();const s=this.getStoreSnapshot(),i=this.resolver.resolve(s,n,this.currentSelection);return om(i),i.success?(this.commitToStore(i.draft),null==(t=this.onStateChangeCallback)||t.call(this),{success:!0,removedFeatures:i.removedFeatures,warnings:i.warnings}):{success:!1,message:i.errorMessage}}setSingleModel(e){var t;const n={type:"SET_SINGLE_MODEL",payload:{modelId:e}};nm();const s=this.getStoreSnapshot(),i=this.resolver.resolve(s,n,this.currentSelection);return om(i),i.success?(this.commitToStore(i.draft),null==(t=this.onStateChangeCallback)||t.call(this),{success:!0,removedFeatures:i.removedFeatures,warnings:i.warnings,modelSwitched:i.modelSwitched,switchedModelName:i.switchedModelName}):{success:!1,message:i.errorMessage}}setModels(e){var t;const n={type:"SET_MODELS",payload:{modelIds:e}};nm();const s=this.getStoreSnapshot(),i=this.resolver.resolve(s,n,this.currentSelection);return om(i),i.success?(this.commitToStore(i.draft),null==(t=this.onStateChangeCallback)||t.call(this),{success:!0,removedFeatures:i.removedFeatures,warnings:i.warnings,modelSwitched:i.modelSwitched,switchedModelName:i.switchedModelName}):{success:!1,message:i.errorMessage}}getModelSwitchSuggestion(){return Vm(this.buildDomainState())}getModelSwitchSuggestionFor(e){const t=this.buildDomainState(),n=t.currentSelection.selectedModels;t.currentSelection.selectedModels=e;const s=Vm(t);return t.currentSelection.selectedModels=n,s}updateUploadedFileTypes(e){var t;const n={type:"UPDATE_FILE_TYPES",payload:{fileTypes:e}};nm();const s=this.getStoreSnapshot(),i=this.resolver.resolve(s,n,this.currentSelection);if(om(i),!i.success)return{success:!1,message:i.errorMessage};this.commitToStore(i.draft),null==(t=this.onStateChangeCallback)||t.call(this);const a={success:!0};if(i.removedFeatures.length>0){const e=i.removedFeatures.map(e=>Um(e)).join("、");a.message=`由于上传的文件类型限制,已自动取消:${e}`,a.removedFeatures=i.removedFeatures}return a}addUploadedFileType(e){const t=this.currentSelection.uploadedFileTypes;return t.includes(e)?{success:!0}:this.updateUploadedFileTypes([...t,e])}removeUploadedFileType(e){const t=this.currentSelection.uploadedFileTypes;return this.updateUploadedFileTypes(t.filter(t=>t!==e))}clearUploadedFileTypes(){return this.updateUploadedFileTypes([])}setThinkingMode(e){var t;const n={type:"SET_THINKING_MODE",payload:{mode:e}};nm();const s=this.getStoreSnapshot(),i=this.resolver.resolve(s,n,this.currentSelection);if(om(i),!i.success)return{success:!1,message:i.errorMessage};this.commitToStore(i.draft),null==(t=this.onStateChangeCallback)||t.call(this);const a={success:!0};if(i.removedFeatures.length>0){const e=i.removedFeatures.map(e=>Um(e)).join("、");a.message=`已自动取消与其冲突的功能:${e}`,a.removedFeatures=i.removedFeatures}return i.warnings.length>0&&(a.warnings=i.warnings),a}getThinkingMode(){return this.currentSelection.thinkingMode}getSupportedThinkingModes(){var e,t,n,s,i;const a=this.currentSelection.selectedModels;if(0===a.length)return["Thinking","Fast"];const o=a[0],r=this.config.modelList.find(e=>e.id===o);if(!r)return["Thinking","Fast"];const l=!!(null==(t=null==(e=r.info)?void 0:e.meta)?void 0:t.auto_thinking),c=null==(i=null==(s=null==(n=r.info)?void 0:n.meta)?void 0:s.abilities)?void 0:i.thinking;if(l)return 4===c?["Auto","Thinking"]:["Auto","Thinking","Fast"];switch(c){case 1:case 3:default:return["Thinking","Fast"];case 2:return[];case 4:return["Thinking"]}}validateFileUpload(e){const t=it(),n=this.getFileTypeStatuses().find(t=>t.fileType===e);return n?n.disabled?{canUpload:!1,reason:n.disabledReason}:{canUpload:!0}:{canUpload:!1,reason:t.t("Unknown file type")}}getFeatureStatuses(){return function(e){const{currentSelection:t,featureFeatureConfig:n,featureFileConfig:s,modelList:i}=e,{selectedFeatures:a,selectedModels:o,uploadedFileTypes:r}=t,l=o.length>1,c=(Rm(n,a),Om(s,r)),d=Sm(i,o),u=[],h=Object.values(Lh);for(const m of h){if(m===Lh.Txt2Txt)continue;const t=Bm(e,m,a.includes(m),l,0,c,d);t&&u.push(t)}return u}(this.buildDomainState())}getFeatureStatus(e){return zm(this.buildDomainState(),e)}getThinkingStatus(){const e=Gm(this.buildDomainState()),t=this.getSupportedThinkingModes();return S(C({},e),{supportedModes:t,enabled:t.length>0&&e.status!==Fh.Hidden})}getFileTypeStatuses(){return Km(this.buildDomainState())}getModelStatuses(){return Wm(this.buildDomainState())}getStateSnapshot(){return{features:this.getFeatureStatuses(),fileTypes:this.getFileTypeStatuses(),models:this.getModelStatuses(),currentSelection:C({},this.currentSelection),isMultiModelMode:this.currentSelection.selectedModels.length>1}}getCurrentSelection(){return C({},this.currentSelection)}isMultiModelMode(){return this.currentSelection.selectedModels.length>1}getSelectedModels(){return this.currentSelection.selectedModels.map(e=>this.config.modelList.find(t=>t.id===e)).filter(e=>void 0!==e)}getFeatureTooltip(e){const t=this.getFeatureStatuses().find(t=>t.feature===e);return(null==t?void 0:t.tooltip)||(null==t?void 0:t.disabledReason)}checkFeaturesAvailability(e){const t=this.getFeatureStatuses(),n={};for(const s of e){const e=t.find(e=>e.feature===s);n[s]=(null==e?void 0:e.status)===Fh.Enabled||(null==e?void 0:e.status)===Fh.ActiveCancellable}return n}getSuggestionToEnableFeature(e){const t=this.getFeatureStatuses().find(t=>t.feature===e);if(!t||t.status!==Fh.Disabled)return null;const n={deselect:{}},s=this.buildDomainState(),i=Rm(s.featureFeatureConfig,s.currentSelection.selectedFeatures);if(null!==i&&!i.has(e)){const t=s.currentSelection.selectedFeatures.filter(t=>{var n,i;if(t===Lh.Txt2Txt)return!1;return!(null!=(i=null!=(n=s.featureFeatureConfig[t])?n:s.featureFeatureConfig[Gh(t)])?i:[]).map(zh).includes(e)});t.length>0&&(n.deselect.features=t)}const a=Sm(s.modelList,s.currentSelection.selectedModels);return null===a||a.has(e)||(n.deselect.models=[...s.currentSelection.selectedModels]),this.isMultiModelMode()&&(n.deselect.models=s.currentSelection.selectedModels.slice(1)),n}reset(){this.currentSelection=this.createEmptySelection(),this.init()}buildDomainState(){return{currentSelection:C({},this.currentSelection),globalPermissions:this.config.globalPermissions,featureFeatureConfig:this.config.featureFeatureConfig,featureFileConfig:this.config.featureFileConfig,modelList:this.config.modelList,isLoggedIn:this.config.isLoggedIn,featureEquities:this.config.featureEquities,modelEquities:this.config.modelEquities,defaultModelIds:this.config.defaultModelIds}}initializeDefaultSelections(){}};j(Ym,"instance",null);let Jm=Ym;const Xm=()=>{var e,t,n,s;const i=Rs(e=>e.fileTypeStatuses),a=D.useMemo(()=>i.find(e=>e.fileType===Oh.Image),[i]),o=D.useMemo(()=>i.find(e=>e.fileType===Oh.File),[i]),r=D.useMemo(()=>i.find(e=>e.fileType===Oh.Audio),[i]),l=D.useMemo(()=>i.find(e=>e.fileType===Oh.Video),[i]),c=null==(e=null==a?void 0:a.disabled)||e,d=null==(t=null==o?void 0:o.disabled)||t,u=null==(n=null==r?void 0:r.disabled)||n,h=null==(s=null==l?void 0:l.disabled)||s,m=c&&d&&u&&h;return{fileTypeStatuses:i,imageStatus:a,fileStatus:o,audioStatus:r,videoStatus:l,isImageDisabled:c,isDocumentDisabled:d,isAudioDisabled:u,isVideoDisabled:h,isAllDisabled:m,hasAnyEnabled:!m}},Zm=e=>{const t=Pd(e=>e.user),n=cR(e=>e.config),s=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.limits}),i=yd(e=>e.selectedModels),a=Kh(e=>e.files),o=Kh(e=>e.setFiles),r=js(e=>e.currentInputFeature),{isImageDisabled:l,isDocumentDisabled:c,isAudioDisabled:d,isVideoDisabled:u}=Xm(),h=D.useCallback(e=>{o(e);const t=(()=>{if(!e||0===e.length)return[];const t=new Set;for(const n of e){const e="default"===n.file_class?"document":n.file_class;"image"===e||"vision"===e?t.add(Oh.Image):"video"===e?t.add(Oh.Video):"audio"===e?t.add(Oh.Audio):"document"!==e&&"file"!==e||t.add(Oh.File)}return Array.from(t)})();xM.updateUploadedFileTypes(t)},[o]),m=D.useMemo(()=>yM.createFilesManager({onAddProcess:(e,t)=>{const n=Kh.getState().files;if(t&&Array.isArray(n)){const e=[...n.filter(e=>e.itemId!==t.itemId),Te(t)];h(e)}},onAddSuccess:(e,t)=>{var n,s,i;const a=Kh.getState().files;if(!a.length||!a.some(e=>e.itemId===t.itemId))return;const o=[...a.filter(e=>e.itemId!==t.itemId),Te(t)];h(o),pl("uploadedFileData",{params:{et:"OTHER",c1:null==(n=null==t?void 0:t.file)?void 0:n.user_id,c4:null==t?void 0:t.id,c5:null==t?void 0:t.name,c6:t.file_type,c7:(null==(s=null==t?void 0:t.file)?void 0:s.meta)?JSON.stringify(null==(i=null==t?void 0:t.file)?void 0:i.meta):"",c8:t.status}})},onAddFail:(e,t)=>{t&&h([...e.filter(e=>e.itemId!==t.itemId),Te(t)]),pl("uploadedFileErr",{params:{et:"OTHER"}})},onPaseSuccess:(e,n)=>{var s,i,a;const o=Kh.getState().files;if(o.length&&o.some(e=>e.itemId===n.itemId)&&n){const e=S(C({},n),{file:Te(n.file)});h([...o.filter(e=>e.id!==n.id),Te(e)]),pl("filePaseSuccess",{params:{et:"OTHER",c1:(null==t?void 0:t.id)||(null==(s=null==n?void 0:n.file)?void 0:s.user_id)||"",c4:null==n?void 0:n.id,c5:null==n?void 0:n.name,c6:n.file_type,c7:(null==(i=null==n?void 0:n.file)?void 0:i.meta)?JSON.stringify(null==(a=null==n?void 0:n.file)?void 0:a.meta):""}})}},onPaseFail:(e,n)=>{var s,i,a,o,r,l,c;if(e.length&&e.some(e=>e.itemId===n.itemId)&&n){const d=S(C({},n),{file:Te(n.file)});h([...e.filter(e=>e.id!==n.id),Te(d)]),pl("filePaseFail",{params:{et:"OTHER",c1:(null==t?void 0:t.id)||(null==(s=null==n?void 0:n.file)?void 0:s.user_id)||"",c4:null==n?void 0:n.id,c5:null==n?void 0:n.name,c6:n.file_type,c7:(null==(i=null==n?void 0:n.file)?void 0:i.meta)?JSON.stringify(null==(a=null==n?void 0:n.file)?void 0:a.meta):"",c8:(null==(r=null==(o=n.file)?void 0:o.meta)?void 0:r.parse_meta)?JSON.stringify(null==(c=null==(l=n.file)?void 0:l.meta)?void 0:c.parse_meta):""}})}},userId:null==t?void 0:t.id,parsedFileTypes:[Zt.FILE]}),[h,null==t?void 0:t.id]),p=D.useCallback(e=>{let t=e;return t=((e,{currentInputFeature:t,config:n,files:s})=>{var i,a;if(t===yt.ImageGeneration){const t=e.filter(e=>Nu(e)),o=e.filter(e=>!Nu(e)&&!e.type.includes("image")),r=(null==(a=null==(i=null==n?void 0:n.features.limits)?void 0:i.image_edit)?void 0:a.image_max_count)||1;s.length+t.length+o.length>r&&vi.openOnce({type:"warning",content:it().t("In a single-turn conversation, up to {{number}} images can be uploaded.",{number:r})}),e.length>r&&e.splice(r-s.length,s.length+e.length-r)}return e})(t,{currentInputFeature:r,config:n,files:a}),t=((e,{currentInputFeature:t,config:n,files:s})=>{var i,a,o;if(t===yt.VideoGeneration&&e){const t=Eu[yt.VideoGeneration];if(t){const r=e.filter(e=>e.type.startsWith("image")),l=e.filter(e=>!e.type.startsWith("image")),c=r.filter(e=>{const{type:n="",name:s=""}=e||{};return t.mineType.includes(n)&&t.extensions.find(e=>s.toLowerCase().endsWith(e))}),d=(null==(o=null==(a=null==(i=null==n?void 0:n.features)?void 0:i.limits)?void 0:a.video_generation)?void 0:o.image_max_count)||1;c.length"image"===e.type).length+c.length>d&&vi.openOnce({type:"warning",content:it().t("In a single-turn conversation, up to {{number}} images can be uploaded.",{number:d})});const u=s.filter(e=>"image"===e.type);return u.length+c.length>d&&c.splice(d-u.length,u.length+c.length-d),[...l,...c]}}return e||[]})(t,{currentInputFeature:r,config:n,files:a}),t},[n,r,a]),g=D.useCallback(e=>{const{files:t,type:n}=e,s=p(t);s.length>0&&m.addFiles(s,n)},[m,p]),f=D.useCallback(e=>A(null,null,function*(){const t=a[e];t&&"uploading"===t.status&&t.uploadTaskId&&(yield fu.stopAndRemoveTask(t.uploadTaskId)),m.removeFile(t),h(null==a?void 0:a.filter(e=>t.itemId!==e.itemId))}),[a,m,h]),{fileDragging:v}=(e=>{const{filesManager:t,uploadFilePreCheck:n}=e,[s,i]=D.useState(!1),a=js(e=>e.currentInputFeature),o=D.useCallback(e=>{var t,n;e.preventDefault(),a!==yt.ImageGeneration&&((null==(n=null==(t=e.dataTransfer)?void 0:t.types)?void 0:n.includes("Files"))?i(!0):i(!1))},[a]),r=D.useCallback(e=>A(null,null,function*(){var s,o;if(e.preventDefault(),a!==yt.ImageGeneration){if(null==(s=e.dataTransfer)?void 0:s.files){const s=Array.from(null==(o=e.dataTransfer)?void 0:o.files),i=n(s);i.length>0&&t.addFiles(i)}i(!1)}}),[a,t,n]),l=()=>{i(!1)};return D.useEffect(()=>{const e=document.getElementById("dropzone-container");return null==e||e.addEventListener("dragover",o),null==e||e.addEventListener("drop",r),null==e||e.addEventListener("dragleave",l),()=>{null==e||e.removeEventListener("dragover",o),null==e||e.removeEventListener("drop",r),null==e||e.removeEventListener("dragleave",l)}},[o,r]),{fileDragging:s}})({filesManager:m,uploadFilePreCheck:p});return D.useEffect(()=>{const e=[];d||e.push(Xt.AUDIO),c||e.push(Xt.DEFAULT,Xt.DOC),u||e.push(Xt.VIDEO),l||e.push(Xt.IMAGE),m.updateLimitTypes(e)},[m,d,c,u,l]),D.useEffect(()=>{s&&m.updateLimitRules(uu(s))},[m,s]),D.useEffect(()=>{var e,t;if(i.length){let n;if(n=i.map(e=>e.id).includes(Yt)?i.find(e=>e.id===Yt):i[0],n){const s=null==(t=null==(e=n.info)?void 0:e.meta)?void 0:t.file_limits;s&&m.updateLimitRules(uu(s))}}},[m,i]),{filesManager:m,fileDragging:v,uploadHandler:g,handleCloseFileCard:f}};const ep={feature:yt.Thinking,status:Fh.Hidden,selected:!1,supportedModes:[],enabled:!0,tooltipText:"",disabledInfo:{disabled:!1}},tp=()=>{var e;const t=null!=(e=Ps(e=>e.thinkingStatus))?e:ep,n=Ps(e=>e.thinkingEnabled),s=Ps(e=>e.thinkingMode),i=t.disabledInfo.disabled,a=t.tooltipText,o=t.enabled,r=t.supportedModes,l=t.status===Fh.ActiveUncancellable,c=t.status===Fh.EquityExhausted;D.useEffect(()=>{c&&n&&xM.deselectFeature(yt.Thinking)},[c,n]);const d=r.includes("Auto"),u=D.useCallback(e=>{pl("clkGenerateMode",{params:{et:"CLK"},aesParams:{c4:"thinking"},paramsExtend:{msg_type:e.toLowerCase()}});const t=xM.setThinkingMode(e);t.success&&function(e,t,n){var s;if("undefined"!=typeof window){try{window.localStorage.setItem(e,t)}catch(i){}try{yR(e,t,null!=(s=null==n?void 0:n.maxAge)?s:31536e3)}catch(i){}}}(gn,e),t.success},[]);return{tooltipText:a,disabled:i,enabled:o,thinkingEnabled:t.selected,thinkingMode:s,autoThinkingEnabled:d,supportThinkingModes:r,isForceActive:l,onThinkingChange:u}},np={image:[{src:"https://img.alicdn.com/imgextra/i1/O1CN01NdWLo81xvnvVAFPLO_!!6000000006506-0-tps-2688-1536.jpg",description:'Close-up of a fair-skinned Western woman with blonde hair and blue eyes, focusing on the eye area. Her skin displays a natural glow and clearly visible, fine pore texture without excessive retouching. The makeup is meticulously executed: the upper eyelid features a precise, fluid line drawn with a matte black liquid eyeliner, subtly upturned 15 degrees at the outer corner; the lower waterline is delicately filled in with deep gray-brown to enhance depth; lashes are dense, long, and distinctly separated with a natural curl, showing no obvious signs of false lashes; eyebrows are full "feathered" brows with defined hair strokes and soft edges, perfectly matching her hair color. Cinematic three-point lighting is used—the key light is a softbox positioned 45 degrees to the front side for even highlights, the fill light is a low-intensity reflector on the left to brighten shadows, and the rim light is a narrow-beam spotlight from the rear right to accentuate cheekbones and hair strands. Shot with an 85mm f/1.2 prime lens, the extremely shallow depth of field renders the background into a creamy bokeh of faint color blocks and light flares, ensuring zero distraction from the subject. The entire image is sharp and crystal-clear, with the texture of the periorbital skin, lash roots, and eyeliner edges rendered in stunning 4K ultra-high-definition detail, exemplifying professional high-end beauty studio photography.'},{src:"https://img.alicdn.com/imgextra/i1/O1CN01tCFNKB1IgmguoHC1Z_!!6000000000923-0-tps-2688-1536.jpg",description:"A Caucasian man in his early seventies, with slightly tousled short gray-white hair and deep-set, vivid light blue eyes. His face is marked by pronounced, natural wrinkles: three deep horizontal lines across the forehead, radiating crow’s feet at the corners of the eyes, and clearly defined nasolabial folds and marionette lines flanking the mouth. His skin displays a warm, natural tone with subtle age spots, faint reddish capillaries, and short, coarse gray-black stubble. He wears a coarse-textured, beige wool turtleneck sweater, its yarn fibers distinctly visible, showing slight pilling and soft creases. Seated upright yet relaxed in a dark brown vintage leather armchair, his hands rest naturally folded on his knees. His expression is calm and reserved, his gaze turned slightly aside, conveying quiet wisdom and gentle resolve shaped by time. The background is a softly blurred, warmly lit study: extremely shallow depth of field reveals only indistinct outlines of oak bookshelves, a row of gilded book spines, and the edges of green plant leaves. Soft natural light streams diagonally through a tall window on the left, casting finely graded chiaroscuro along his right cheek and nose bridge, accentuating the texture of his skin, the direction of his wrinkles, and the three-dimensional quality of the sweater’s fibers. Rendered in ultra-high-definition photorealistic style, the image captures extreme detail: the subtle depressions of each wrinkle, the slight skin elevations at the base of stubble hairs, the precise curl and light reflection of individual wool fibers, the fine cracks and gradual sheen variations on the leather armchair, and even dust particles suspended visibly within the Tyndall-effect light beams."},{src:"https://img.alicdn.com/imgextra/i3/O1CN01GAGbbu1Ip1ow3vKmv_!!6000000000941-0-tps-2688-1536.jpg",description:"Three green tree frogs perch side by side on a moss-covered rock glistening with moisture: the left frog has its eyes slightly closed and relaxed lips, its smooth-textured skin conveying calmness; the middle frog’s eyelids are half-lowered, its gaze distant and mouth straight, its body faintly shimmering with a misty sheen that suggests aloofness; the right frog’s eyes are wide open, encircled by a soft golden glow, its lips curved into a gentle smile, a pink tongue extending about 3 millimeters, limbs naturally outstretched with clearly visible toe pads, radiating joy. The rock is blanketed in thick, lush green moss, wet and reflective, dotted with tiny water droplets and minute fragments of decaying leaves. In the softly blurred background, a tropical rainforest stream winds through the scene, morning mist drifting like gauze through the mid- and far distance, layers of ferns and banana leaves overlapping, their edges and veins adorned with crystal-clear dewdrops, some slowly sliding down. A slanted ray of morning light pierces through the forest canopy, forming a soft Tyndall beam in the mist that illuminates the frogs’ backs and nearby foliage. The image exhibits a realistic style with ultra-high-definition 8K natural photography quality, precisely controlled depth of field rendering the frogs sharply crisp while the background transitions smoothly into natural bokeh. Colors are richly saturated yet true to life—emerald frogs, deep green moss, warm gray mist, translucent dewdrops, and a delicate golden halo harmoniously unified."},{src:"https://img.alicdn.com/imgextra/i4/O1CN01D5BCtm1l1fzxQsLqt_!!6000000004759-0-tps-2528-1446.jpg",description:"A realistic-style summer forest scene. At the center of the composition lies a secluded, tranquil woodland clearing. Tall, upright oaks and beeches form the main canopy layer; their dense crowns appear a deep, weighty ink green, with subtle waxy highlights on the leaf surfaces. Soft yet intense sunlight filters through gaps in the canopy, forming clearly visible Tyndall beams in the air. The edges of the beams carry a slightly warm golden tone, creating a delicate contrast with the cool green shadows. In the midground, a cluster of newly sprouted maple branches spreads bright, vivid emerald-green leaves. The veins are distinct, the leaves semi-translucent, with gently curled edges, as if freshly washed by morning dew. In the left foreground, low holly and viburnum shrubs are covered in a soft, matte olive green; their interlaced branches and leaves show fine textures, with some leaf undersides reflecting a pale gray-green sheen. The ground is covered by a thick, moist layer of moss composed of multiple species: up close are plush, tassel-like mosses in a full, lustrous green, their surfaces beaded with tiny dew droplets; slightly farther away, scale moss and sphagnum intertwine, showing transitions from bluish gray-green to brownish green; beneath them, the decaying leaf litter is faintly visible, blending dark brown and deep green into an organic texture. All vegetation surfaces carry a natural, slightly damp sheen, and extremely fine suspended particles drift within the light beams. The background forest gradually softens into blur, retaining depth without competing with the main subject, while the distance merges into a thin layer of blue-green mist. The overall lighting is slanting sunlight from around 10 a.m., with moderate contrast between light and shadow. The green palette is precisely differentiated through more than 23 variations of brightness, saturation, temperature, and material qualities (such as waxy, velvety, leathery, and gelatinous), with no sense of repetition, creating a lush, breathing, detail-rich, and ecologically authentic secret summer forest."},{src:"https://img.alicdn.com/imgextra/i3/O1CN01L3M9El1DWdqE9Vjxk_!!6000000000224-0-tps-2688-1536.jpg",description:'A photograph of a large, white dry-erase board with handwritten content using blue, red, green, purple, and black markers, matching the style and layout of the provided image. At the top, the title "THE RISE OF SUBAGENTS" is prominently written in large blue uppercase letters. Below it, in smaller black text, is "Based on Philschmid\'s blog post (© 2025)".\n\nThe left side has a section titled "PROBLEM: MONOLITHIC AGENT" in red. Below it, a rectangular box labeled "BIG AGENT (Monolithic)" contains hand-drawn squiggles and text like "Many Tasks", "Huge Context Window", "Too Many Tools", "CLUTTERED & LESS RELIABLE". A red arrow points to a box labeled "CONTEXT POLLUTION". Below this is a green title "SOLUTION: SUBAGENTS (Specialized)".\n\nThe center features a detailed flowchart titled "SUBAGENT ARCHITECTURE" in black. All boxes and connecting lines are drawn in blue marker, with black text inside. A top box "USER REQUEST" leads down to "ORCHESTRATOR AGENT" (with sub-points box, which has a blue underline and contains the handwritten black text: "- Analyzes Request", "- Decomposes Task", "- Delegates to Subagents"). This splits into three arrows leading into a dashed-line box labeled "ISOLATED EXECUTION (Focused Context)". Inside this dashed box are three "SUBAGENT" boxes (1, 2, n...) with their own sub-points, sub-points containing the handwritten black text: "- Own Context", "- Own Tools", "- Solves Task A/B/C". Three blue arrows emerge and converge into another "ORCHESTRATOR AGENT" box (with "Synthesizes Results"), leading down to a final "FINAL ANSWER" box.\n\nThe right side is divided into two sections. Top: blue title "EXPLICIT, USER-DEFINED SUBAGENTS", with a flow from "STATIC FILE / CODE" to "Reusable Specialists Team". A blue box contains sample code, inside the box, handwritten black text reads exactly: "--- name: \'Code-Reviewer\' description: \'MUST BE USED...\' tools: [\'file_read\', \'search_code\']. Below this are two lists. On the left, written in green marker: "PROS: Full control, Predictable, Reusable". On the right, written in red marker: "CONS: Rigid, State Management, Hard to Scale". Bottom: green title "IMPLICIT, ON-THE-FLY SUBAGENTS", with a flow from "DYNAMIC CREATION" to "Temporary, Task-Specific". A green box contains sample code, inside the box, handwritten black text shows a Python function call: "# Orchestrator calls tool send_message_to_agent( agent_name=\'q3_report...\', description=\'...\', message=\'Draft email...\') )". Below this are two lists. Written in green marker: "PROS: Flexible, No Setup, Multi-step context". Directly beneath it, written in red marker: "CONS: Less predictable, Debugging difficult".\n\nAt the bottom center, a purple title "CONCLUSION & TAKEAWAYS" introduces four bullet points written in black marker: "CONTEXT ENGINEERING IS EVERYTHING!", "Focused Environment = Better Performance, Lower Cost", "Reliability via Isolation", and "Don\'t Over-engineer!". Red and blue markers and a black eraser rest in the tray below. The whiteboard surface shows slight wear and overhead reflections.'},{sourceImageList:["https://img.alicdn.com/imgextra/i2/O1CN01Uexit1206ulXCGBZv_!!6000000006801-2-tps-1328-1328.png"],src:"https://img.alicdn.com/imgextra/i3/O1CN0192DFe51RpKclEnurK_!!6000000002160-2-tps-1328-1328.png",description:"Ultra-detailed 3D graphite pencil sketch of a person actively drawing, rendered on textured white notebook paper. The subject’s hand is holding a pencil, mid-stroke, as the sketch dynamically emerges from the page. Surrounding the drawing area: realistic pencil shavings, a pink eraser, and a metal pencil sharpener resting naturally on the paper. Emphasize high-fidelity paper texture—visible grain, subtle fibers, and minor imperfections like slight creases or soft folds. Include authentic graphite effects: soft smudges, fine residue, and nuanced tonal gradients. Cast realistic ambient shadows under objects and around the hand to enhance depth and tactile presence. Style: photorealistic hand-drawn aesthetic, monochrome graphite tones, macro-level detail."},{sourceImageList:["https://img.alicdn.com/imgextra/i2/O1CN01Uexit1206ulXCGBZv_!!6000000006801-2-tps-1328-1328.png"],src:"https://img.alicdn.com/imgextra/i2/O1CN01kUdRxi1kVcH5C8ISv_!!6000000004689-2-tps-1328-1328.png",description:"Create a high-quality 3D avatar of the person in the uploaded image with a cheerful, expressive face. The character should have a warm smile, bright eyes, and soft facial features that feel friendly and approachable. Render in a Pixar-style aesthetic with smooth textures, subtle skin shading, and slightly exaggerated proportions for a cute, animated look. Lighting should be soft and even, creating a clean studio look with gentle shadows for depth."},{sourceImageList:["https://img.alicdn.com/imgextra/i2/O1CN01Uexit1206ulXCGBZv_!!6000000006801-2-tps-1328-1328.png"],src:"https://img.alicdn.com/imgextra/i4/O1CN01xLPQIH1V9Qr0ExqVI_!!6000000002610-2-tps-1328-1328.png",description:"A close-up, professionally composed photograph of a hand-crocheted yarn doll gently cradled in two hands. The doll has a soft, rounded chibi form, faithfully reimagining the character from the uploaded image with vivid contrasting colors and intricate, tactile details. The hands are natural and expressive—fingers relaxed yet clearly defined, with realistic skin texture, subtle veins, and gentle light-to-shadow transitions that convey warmth and human presence. The background is softly blurred, revealing a cozy indoor setting: a warm-toned wooden tabletop bathed in diffused daylight streaming through a nearby window. The overall atmosphere is intimate, serene, and tender, celebrating both the artistry of handmade craft and the quiet affection of holding something cherished."},{sourceImageList:["https://img.alicdn.com/imgextra/i2/O1CN01Uexit1206ulXCGBZv_!!6000000006801-2-tps-1328-1328.png"],src:"https://img.alicdn.com/imgextra/i3/O1CN016vFiI81beTOMAEFwM_!!6000000003490-2-tps-1328-1328.png",description:"Create a stylized 3D chibi character based on the attached photo, faithfully preserving the subject’s distinctive facial features and key clothing details. The character strikes a playful pose—sitting on the edge of a giant Instagram-style frame with both legs dangling outside—and forms a finger heart with their left hand, topped by a glowing red heart icon. The frame’s top edge displays the username “Beauty” in clean, modern typography. Floating around the scene are subtle, semi-transparent social media UI elements: like, comment, and share icons, rendered in a cohesive, non-distracting style. The overall aesthetic is vibrant, cute, and digitally native—blending kawaii chibi charm with contemporary social media visual language."},{sourceImageList:["https://img.alicdn.com/imgextra/i1/O1CN01VG3zkx1zC7eZzY97Q_!!6000000006677-2-tps-512-512.png","https://img.alicdn.com/imgextra/i2/O1CN01AQ50gZ1SsMrjmaeBw_!!6000000002302-2-tps-736-736.png"],src:"https://img.alicdn.com/imgextra/i1/O1CN01Ma8xRN1xB5Wl7L2Gn_!!6000000006404-2-tps-1024-1024.png",description:"Please generate high-definition Christmas photos for my couple, ensuring accurate reproduction of facial features and identities from the uploaded images. Clothing: The girl wears a white lace slip dress with a white fluffy shawl, her long dark brown hair styled in a single side braid adorned with a small green Christmas tree ornament. The boy wears a white knitted cardigan over a white shirt and white trousers. Makeup: The girl’s makeup is light and shimmery; the boy’s is light and natural, only brightening his skin tone. Background: A green Christmas tree decorated with gold and silver ornaments, a white wall, green and white balloons, and gift boxes wrapped in green paper with silver ribbons. Pose: Expressive and natural movements. Atmosphere: Soft, bright lighting; a fresh, gentle mood; rich detail; and a film-like texture with strong grain. Style: Christmas theme in Kodak Portra 400 film style."},{sourceImageList:["https://img.alicdn.com/imgextra/i2/O1CN01Uexit1206ulXCGBZv_!!6000000006801-2-tps-1328-1328.png"],src:"https://img.alicdn.com/imgextra/i3/O1CN01JfrYlp1O8KajeDs4B_!!6000000001660-2-tps-1024-1024.png",description:"Please generate a Christmas-themed studio photo of a person and pet, preserving the subject's facial features and expression while maintaining consistent proportions. The composition should be vertical, featuring a frontal, eye-level, mid-range shot leaning toward full-body framing. On the right side of the image, a woman sits on the floor wearing a dark green knitted off-the-shoulder sweater (with cutout/off-the-shoulder design), paired with a long red scarf and a green Christmas tree-shaped headband decorated with small red balls. Her makeup is fresh and natural, creating a gentle, sweet overall mood. She cradles a light brown teddy bear plush toy—wearing a red-and-green plaid knitted scarf—in her left arm, while her right index finger points upward toward decorative English text at the top of the image. To her left sits a golden retriever with fluffy, golden fur, an excited expression, tongue lolling in a happy smile, and a red bow tie around its neck. The dog tilts its head slightly back, gazing in the direction the woman is pointing, establishing an interactive connection. On the left side of the frame stands a snow-dusted white Christmas tree adorned with red, green, and gold baubles, gold star ornaments, and snowflake decorations. Neatly stacked beneath the tree are several colorful gift boxes—green boxes tied with red ribbons and red boxes with green ribbons. The background is a seamless, pure white studio setting encompassing both walls and floor. Centered at the top is a large, handwritten “Merry Christmas” in dark green calligraphy, surrounded by floating red, green, and gold confetti, stars, and snowflakes that create a festive, gently falling effect. The overall color palette emphasizes Christmas red, pine green, and gold accents, rendered with bright, high-key highlights, soft even lighting, and subtle shadows. Textures are crisp and refined, clearly showcasing hair strands and knitwear details, resulting in a clean, luminous, warm, and celebratory commercial poster aesthetic. All details are sharp and high-resolution."},{sourceImageList:["https://img.alicdn.com/imgextra/i2/O1CN01xfDuPp1QDwg7NCM1l_!!6000000001943-2-tps-1600-2133.png"],src:"https://img.alicdn.com/imgextra/i2/O1CN019msx361dXGO8i0Rh3_!!6000000003745-2-tps-896-1184.png",description:"Please ensure the animal’s facial features and species in the reference image are reproduced with 100% accuracy and no deviation. Generate a nine-grid Christmas-themed photo for me with the following requirements: Subject: Cat with a round face and big round eyes. Style: 3x3 Christmas-themed nine-grid photo, bright, cute, soothing, high-resolution adorable pet photo with soft lighting and a clean light-colored (off-white/white) background featuring soft shadows. Elements in each grid: \n1. Cat in a Christmas tree-shaped pet bed, sticking out its tongue. \n2. Wearing a red and green snowflake-patterned knitted scarf, head slightly tilted. \n3. Wearing a classic plush Santa hat. \n4. Wearing a large red bow headband, holding a gift box decorated with red ribbons. \n5. Middle grid: Hand-drawn style “Merry Christmas” text. \n6. Wearing a Christmas tree hat adorned with stars and a red plaid scarf. \n7. Gingerbread man plush toy wearing a green bow tie, sticking out its tongue. \n8. Wearing a red plush Santa hat with yellow stars, yawning (paired with a snowflake-patterned sweater). \n9. Sitting on a red and white plaid cushion in a well-behaved posture. \nThe image should be bright with high color saturation."},{sourceImageList:["https://img.alicdn.com/imgextra/i4/O1CN01qXsgc01PWtRp4laGI_!!6000000001849-2-tps-1138-1362.png"],src:"https://img.alicdn.com/imgextra/i1/O1CN01QVEMzK1cxztKSiT76_!!6000000003668-2-tps-928-1120.png",description:"Based on the uploaded images, please create a four-panel Christmas animal photo collage, each featuring a different pose while preserving the original facial features and aiming for a realistic, natural appearance:\n\nFirst panel: The dog wears a red knitted Christmas outfit, a matching red knitted Santa hat, and a Christmas-themed knitted scarf, smiling and tilting its head.\n\nSecond panel: The dog is surrounded by Christmas elements—it lies on a white plush chair, holding a gingerbread man plush toy. The gingerbread man wears a scarf that matches the dog’s, creating a cute, coordinated look.\n\nThird panel: The dog rests relaxed on a soft plush rug or blanket, chin gently resting on its front paws, gazing at the camera with a gentle or curious expression. It wears a red Christmas knitted sweater and scarf; the hat is optional. Several small gingerbread man plush toys are arranged in front of or beside the dog—either neatly lined up or scattered—to give the impression of being surrounded by gingerbread men. The background includes soft Christmas tree lights and subtle gift box outlines, evoking a warm, playful atmosphere.\n\nFourth panel: The dog stands facing away but turns its body slightly (about 45 degrees) and looks back toward the camera with its tail held naturally upright, lightly holding a mini Christmas gift box (wrapped in red-and-green checkered paper with a gold ribbon) in its mouth. The background is a clean, solid red Christmas-themed backdrop with light, simple accents, featuring the words “MERRY CHRISTMAS” and “She has many gingerbread man toys” in English, along with minimal gingerbread man illustrations. The overall design stays true to the Christmas theme, radiating warmth and playfulness through the presence of gingerbread man toys."}],webSearch:[{query:"Best pizza places near me"},{query:"How to fix a leaky faucet"},{query:"Cheap flights to New York"},{query:"Yoga for beginners at home"},{query:"Quick healthy dinner recipes"},{query:"Top-rated movies this year"},{query:"Learn Spanish online for free"},{query:"DIY home decor ideas"},{query:"Best budget laptops"},{query:"Cute dog names suggestions"}],guidance:{imageGeneration:[{imageUrl:"https://img.alicdn.com/imgextra/i1/O1CN01NdWLo81xvnvVAFPLO_!!6000000006506-0-tps-2688-1536.jpg",prompt:'Close-up of a fair-skinned Western woman with blonde hair and blue eyes, focusing on the eye area. Her skin displays a natural glow and clearly visible, fine pore texture without excessive retouching. The makeup is meticulously executed: the upper eyelid features a precise, fluid line drawn with a matte black liquid eyeliner, subtly upturned 15 degrees at the outer corner; the lower waterline is delicately filled in with deep gray-brown to enhance depth; lashes are dense, long, and distinctly separated with a natural curl, showing no obvious signs of false lashes; eyebrows are full "feathered" brows with defined hair strokes and soft edges, perfectly matching her hair color. Cinematic three-point lighting is used—the key light is a softbox positioned 45 degrees to the front side for even highlights, the fill light is a low-intensity reflector on the left to brighten shadows, and the rim light is a narrow-beam spotlight from the rear right to accentuate cheekbones and hair strands. Shot with an 85mm f/1.2 prime lens, the extremely shallow depth of field renders the background into a creamy bokeh of faint color blocks and light flares, ensuring zero distraction from the subject. The entire image is sharp and crystal-clear, with the texture of the periorbital skin, lash roots, and eyeliner edges rendered in stunning 4K ultra-high-definition detail, exemplifying professional high-end beauty studio photography.'},{imageUrl:"https://img.alicdn.com/imgextra/i1/O1CN01tCFNKB1IgmguoHC1Z_!!6000000000923-0-tps-2688-1536.jpg",prompt:"A Caucasian man in his early seventies, with slightly tousled short gray-white hair and deep-set, vivid light blue eyes. His face is marked by pronounced, natural wrinkles: three deep horizontal lines across the forehead, radiating crow’s feet at the corners of the eyes, and clearly defined nasolabial folds and marionette lines flanking the mouth. His skin displays a warm, natural tone with subtle age spots, faint reddish capillaries, and short, coarse gray-black stubble. He wears a coarse-textured, beige wool turtleneck sweater, its yarn fibers distinctly visible, showing slight pilling and soft creases. Seated upright yet relaxed in a dark brown vintage leather armchair, his hands rest naturally folded on his knees. His expression is calm and reserved, his gaze turned slightly aside, conveying quiet wisdom and gentle resolve shaped by time. The background is a softly blurred, warmly lit study: extremely shallow depth of field reveals only indistinct outlines of oak bookshelves, a row of gilded book spines, and the edges of green plant leaves. Soft natural light streams diagonally through a tall window on the left, casting finely graded chiaroscuro along his right cheek and nose bridge, accentuating the texture of his skin, the direction of his wrinkles, and the three-dimensional quality of the sweater’s fibers. Rendered in ultra-high-definition photorealistic style, the image captures extreme detail: the subtle depressions of each wrinkle, the slight skin elevations at the base of stubble hairs, the precise curl and light reflection of individual wool fibers, the fine cracks and gradual sheen variations on the leather armchair, and even dust particles suspended visibly within the Tyndall-effect light beams."},{imageUrl:"https://img.alicdn.com/imgextra/i3/O1CN01GAGbbu1Ip1ow3vKmv_!!6000000000941-0-tps-2688-1536.jpg",prompt:"Three green tree frogs perch side by side on a moss-covered rock glistening with moisture: the left frog has its eyes slightly closed and relaxed lips, its smooth-textured skin conveying calmness; the middle frog’s eyelids are half-lowered, its gaze distant and mouth straight, its body faintly shimmering with a misty sheen that suggests aloofness; the right frog’s eyes are wide open, encircled by a soft golden glow, its lips curved into a gentle smile, a pink tongue extending about 3 millimeters, limbs naturally outstretched with clearly visible toe pads, radiating joy. The rock is blanketed in thick, lush green moss, wet and reflective, dotted with tiny water droplets and minute fragments of decaying leaves. In the softly blurred background, a tropical rainforest stream winds through the scene, morning mist drifting like gauze through the mid- and far distance, layers of ferns and banana leaves overlapping, their edges and veins adorned with crystal-clear dewdrops, some slowly sliding down. A slanted ray of morning light pierces through the forest canopy, forming a soft Tyndall beam in the mist that illuminates the frogs’ backs and nearby foliage. The image exhibits a realistic style with ultra-high-definition 8K natural photography quality, precisely controlled depth of field rendering the frogs sharply crisp while the background transitions smoothly into natural bokeh. Colors are richly saturated yet true to life—emerald frogs, deep green moss, warm gray mist, translucent dewdrops, and a delicate golden halo harmoniously unified."},{imageUrl:"https://img.alicdn.com/imgextra/i4/O1CN01D5BCtm1l1fzxQsLqt_!!6000000004759-0-tps-2528-1446.jpg",prompt:"A realistic-style summer forest scene. At the center of the composition lies a secluded, tranquil woodland clearing. Tall, upright oaks and beeches form the main canopy layer; their dense crowns appear a deep, weighty ink green, with subtle waxy highlights on the leaf surfaces. Soft yet intense sunlight filters through gaps in the canopy, forming clearly visible Tyndall beams in the air. The edges of the beams carry a slightly warm golden tone, creating a delicate contrast with the cool green shadows. In the midground, a cluster of newly sprouted maple branches spreads bright, vivid emerald-green leaves. The veins are distinct, the leaves semi-translucent, with gently curled edges, as if freshly washed by morning dew. In the left foreground, low holly and viburnum shrubs are covered in a soft, matte olive green; their interlaced branches and leaves show fine textures, with some leaf undersides reflecting a pale gray-green sheen. The ground is covered by a thick, moist layer of moss composed of multiple species: up close are plush, tassel-like mosses in a full, lustrous green, their surfaces beaded with tiny dew droplets; slightly farther away, scale moss and sphagnum intertwine, showing transitions from bluish gray-green to brownish green; beneath them, the decaying leaf litter is faintly visible, blending dark brown and deep green into an organic texture. All vegetation surfaces carry a natural, slightly damp sheen, and extremely fine suspended particles drift within the light beams. The background forest gradually softens into blur, retaining depth without competing with the main subject, while the distance merges into a thin layer of blue-green mist. The overall lighting is slanting sunlight from around 10 a.m., with moderate contrast between light and shadow. The green palette is precisely differentiated through more than 23 variations of brightness, saturation, temperature, and material qualities (such as waxy, velvety, leathery, and gelatinous), with no sense of repetition, creating a lush, breathing, detail-rich, and ecologically authentic secret summer forest."},{imageUrl:"https://img.alicdn.com/imgextra/i3/O1CN01L3M9El1DWdqE9Vjxk_!!6000000000224-0-tps-2688-1536.jpg",prompt:'A photograph of a large, white dry-erase board with handwritten content using blue, red, green, purple, and black markers, matching the style and layout of the provided image. At the top, the title "THE RISE OF SUBAGENTS" is prominently written in large blue uppercase letters. Below it, in smaller black text, is "Based on Philschmid\'s blog post (© 2025)".\n\nThe left side has a section titled "PROBLEM: MONOLITHIC AGENT" in red. Below it, a rectangular box labeled "BIG AGENT (Monolithic)" contains hand-drawn squiggles and text like "Many Tasks", "Huge Context Window", "Too Many Tools", "CLUTTERED & LESS RELIABLE". A red arrow points to a box labeled "CONTEXT POLLUTION". Below this is a green title "SOLUTION: SUBAGENTS (Specialized)".\n\nThe center features a detailed flowchart titled "SUBAGENT ARCHITECTURE" in black. All boxes and connecting lines are drawn in blue marker, with black text inside. A top box "USER REQUEST" leads down to "ORCHESTRATOR AGENT" (with sub-points box, which has a blue underline and contains the handwritten black text: "- Analyzes Request", "- Decomposes Task", "- Delegates to Subagents"). This splits into three arrows leading into a dashed-line box labeled "ISOLATED EXECUTION (Focused Context)". Inside this dashed box are three "SUBAGENT" boxes (1, 2, n...) with their own sub-points, sub-points containing the handwritten black text: "- Own Context", "- Own Tools", "- Solves Task A/B/C". Three blue arrows emerge and converge into another "ORCHESTRATOR AGENT" box (with "Synthesizes Results"), leading down to a final "FINAL ANSWER" box.\n\nThe right side is divided into two sections. Top: blue title "EXPLICIT, USER-DEFINED SUBAGENTS", with a flow from "STATIC FILE / CODE" to "Reusable Specialists Team". A blue box contains sample code, inside the box, handwritten black text reads exactly: "--- name: \'Code-Reviewer\' description: \'MUST BE USED...\' tools: [\'file_read\', \'search_code\']. Below this are two lists. On the left, written in green marker: "PROS: Full control, Predictable, Reusable". On the right, written in red marker: "CONS: Rigid, State Management, Hard to Scale". Bottom: green title "IMPLICIT, ON-THE-FLY SUBAGENTS", with a flow from "DYNAMIC CREATION" to "Temporary, Task-Specific". A green box contains sample code, inside the box, handwritten black text shows a Python function call: "# Orchestrator calls tool send_message_to_agent( agent_name=\'q3_report...\', description=\'...\', message=\'Draft email...\') )". Below this are two lists. Written in green marker: "PROS: Flexible, No Setup, Multi-step context". Directly beneath it, written in red marker: "CONS: Less predictable, Debugging difficult".\n\nAt the bottom center, a purple title "CONCLUSION & TAKEAWAYS" introduces four bullet points written in black marker: "CONTEXT ENGINEERING IS EVERYTHING!", "Focused Environment = Better Performance, Lower Cost", "Reliability via Isolation", and "Don\'t Over-engineer!". Red and blue markers and a black eraser rest in the tray below. The whiteboard surface shows slight wear and overhead reflections.'}],imageEdit:[{originImageUrl:"https://img.alicdn.com/imgextra/i4/O1CN01D1as1J1L65nt2fHdQ_!!6000000001249-2-tps-1328-1328.png",prompt:"Ultra-detailed 3D graphite pencil sketch of a person actively drawing, rendered on textured white notebook paper. The subject’s hand is holding a pencil, mid-stroke, as the sketch dynamically emerges from the page. Surrounding the drawing area: realistic pencil shavings, a pink eraser, and a metal pencil sharpener resting naturally on the paper. Emphasize high-fidelity paper texture—visible grain, subtle fibers, and minor imperfections like slight creases or soft folds. Include authentic graphite effects: soft smudges, fine residue, and nuanced tonal gradients. Cast realistic ambient shadows under objects and around the hand to enhance depth and tactile presence. Style: photorealistic hand-drawn aesthetic, monochrome graphite tones, macro-level detail.",ratio:"1:1",newImageUrl:"https://img.alicdn.com/imgextra/i2/O1CN01Zz1Vkw1wqThW3tPiv_!!6000000006359-2-tps-1328-1328.png"},{originImageUrl:"https://img.alicdn.com/imgextra/i4/O1CN01D1as1J1L65nt2fHdQ_!!6000000001249-2-tps-1328-1328.png",prompt:"A close-up, professionally composed photograph of a hand-crocheted yarn doll gently cradled in two hands. The doll has a soft, rounded chibi form, faithfully reimagining the character from the uploaded image with vivid contrasting colors and intricate, tactile details. The hands are natural and expressive—fingers relaxed yet clearly defined, with realistic skin texture, subtle veins, and gentle light-to-shadow transitions that convey warmth and human presence. The background is softly blurred, revealing a cozy indoor setting: a warm-toned wooden tabletop bathed in diffused daylight streaming through a nearby window. The overall atmosphere is intimate, serene, and tender, celebrating both the artistry of handmade craft and the quiet affection of holding something cherished.",ratio:"1:1",newImageUrl:"https://img.alicdn.com/imgextra/i1/O1CN01934VZ31nXr3QuT52K_!!6000000005100-2-tps-1328-1328.png"},{originImageUrl:"https://img.alicdn.com/imgextra/i4/O1CN01D1as1J1L65nt2fHdQ_!!6000000001249-2-tps-1328-1328.png",prompt:"Create a stylized 3D chibi character based on the attached photo, faithfully preserving the subject’s distinctive facial features and key clothing details. The character strikes a playful pose—sitting on the edge of a giant Instagram-style frame with both legs dangling outside—and forms a finger heart with their left hand, topped by a glowing red heart icon. The frame’s top edge displays the username “Beauty” in clean, modern typography. Floating around the scene are subtle, semi-transparent social media UI elements: like, comment, and share icons, rendered in a cohesive, non-distracting style. The overall aesthetic is vibrant, cute, and digitally native—blending kawaii chibi charm with contemporary social media visual language.",ratio:"1:1",newImageUrl:"https://img.alicdn.com/imgextra/i1/O1CN01jODjPc1MpGU6MJ166_!!6000000001483-2-tps-1328-1328.png"}]},learn:[{image:"icon-line-explain",title:"Explain a confusing topic to me"},{image:"icon-line-homework",title:"Help me with my homework"},{image:"icon-line-quiz",title:"Create a practice quiz for me"},{image:"icon-line-plan",title:"Draw up a study plan for me"},{image:"icon-line-analysis",title:"Analyze the incorrect answer for me"}],t2t:["Create an image of a serene mountain lake.","Create an image of a bustling city skyline.","Create an image of a vibrant flower field.","Create an image of a tranquil forest path.","Create an image of a majestic sunset over ocean.","Create an image of a cozy rustic cabin.","Create an image of a futuristic cityscape at night.","Create an image of a colorful hot air balloon.","Create an image of a peaceful countryside morning.","Create an image of an ancient castle ruins.","Help me create a to-do list app in JavaScript.","Help me build a weather API integration with Python.","Help me design a responsive portfolio site using HTML/CSS.","Help me implement a sorting algorithm in Java.","Help me set up a basic Flask server in Python.","Help me write a script to automate file backups.","Help me with a plan to start a business.","Help me with a plan for saving money.","Help me with a plan to learn a new skill.","Help me with a plan for a healthy lifestyle.","Help me with a plan to organize my home.","Help me with a plan for a successful interview.","Help me with a plan to improve my time management.","Help me with a plan for a family vacation.","Help me with a plan to achieve my goals.","Help me with a plan for a productive day.","Tell me the latest news from New York.","Tell me about today's weather updates.","Tell me what's happening in technology now.","Tell me the top sports headlines today.","Tell me recent developments in climate change.","Tell me about global financial markets today.","Tell me updates on the latest space missions.","Tell me breaking news from around the world.","Tell me health news related to new discoveries.","Create a video of a dog surfing on waves.","Create a video of flowers blooming in fast motion.","Create a video of a chef making pizza art.","Create a video of stars twinkling in the night sky.","Create a video of a robot dancing to jazz.","Create a video of autumn leaves swirling in the wind.","Create a video of a painter creating a mural.","Create a video of dolphins playing with a ball.","Create a video of fireworks lighting up the city.","Create a video of a violinist performing in the rain.","Describe the landscape and its prominent features.","Describe the people and their activities in the image.","Describe the colors and mood of the scene.","Describe the architecture and building materials used.","Describe the interaction between the subjects.","Describe the weather and environmental conditions shown.","Describe the textures and patterns visible.","Describe the lighting and shadows in the image.","Describe the main subject and its surroundings.","Describe the composition and framing of the shot.","Summarize the article on climate change.","Summarize the book's main themes.","Summarize the podcast episode highlights.","Summarize the project's key objectives.","Summarize the lecture on economics.","Summarize the movie plot briefly.","Summarize the report's findings concisely.","Summarize the interview with the expert.","Summarize the research paper's methodology.","Summarize the discussion in the forum.","Give me advice about managing stress.","Give me advice about saving money.","Give me advice about making friends.","Give me advice about staying healthy.","Give me advice about time management.","Give me advice about public speaking.","Give me advice about setting goals.","Give me advice about overcoming fear.","Give me advice about being kind.","Give me advice about finding purpose.","Help me write a poem about autumn leaves.","Help me write an essay on climate change.","Help me write a letter to my future self.","Help me write a story with a twist ending.","Help me write a review of a new book.","Help me write a speech for a graduation ceremony.","Help me write a blog post on mental health.","Help me write a descriptive paragraph about the ocean.","Help me write a character sketch for a novel.","Help me write a persuasive argument for recycling.","Give me an idea for a new eco-friendly product.","Give me an idea to improve mental health support.","Give me an idea for a unique restaurant concept.","Give me an idea to enhance online education tools.","Give me an idea for a sustainable fashion line.","Give me an idea to simplify daily household chores.","Give me an idea for a tech-free entertainment option.","Give me an idea to boost community engagement locally.","Give me an idea for a creative marketing campaign.","Give me an idea to reduce urban traffic congestion.","Create a web page for a personal blog with HTML.","Create a web page showcasing your portfolio with HTML.","Create a web page for a local restaurant with HTML.","Create a web page with a photo gallery using HTML.","Create a web page for a travel guide with HTML.","Create a web page for a simple calculator app with HTML.","Create a web page featuring a quiz game with HTML.","Create a web page for a book club with HTML.","Create a web page for a fitness tracker with HTML.","Create a web page for a weather forecast with HTML."],video:[{src:"https://assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.38/static/video/video_squirrel.mp4",description:"A squirrel wearing a little vest is driving a small car made of hazelnut shells for the body and twigs for the wheels, bumping along a leaf-covered forest path."},{src:"https://assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.38/static/video/video_couple.mp4",description:"The scene opens with a medium shot of a man and a woman walking side by side across a bridge at sunset. Captured with a handheld camera, the shot features slightly softened depth of field, creating a gentle bokeh effect. The background glows in warm pink-orange hues, softly illuminating their faces, while streetlights emit a gentle glow. They stroll leisurely—the man in a white shirt with a mustard-yellow tie, a brown jacket draped over his arm; the woman in a coral-pink sleeveless dress, holding a beige clutch. A light breeze tousles her hair as the man glances at her: “What do you want to say?” She nods playfully and replies, “You first.” The camera moves steadily alongside them, with subtle handheld sway, cutting between expressive close-ups and wider shots to capture the rhythm of their interaction. The overall visuals feel cinematic and intimate, with realistic lighting, soft motion blur, and fluid, immersive handheld tracking that heighten the natural warmth and authenticity of the moment."},{src:"https://assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.38/static/video/video_panda.mp4",description:"The video shows a panda showing off its skills at an urban skate park, riding a skateboard with remarkable agility and executing multiple high-difficulty tricks in succession. The camera closely follows, precisely capturing every flip and spin, showcasing the panda's extreme sports prowess."},{src:"https://assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.38/static/video/video_flower.mp4",description:"Using time-lapse photography techniques, the entire process of a flower blooming—from bud to full bloom—is condensed into just a few seconds, accompanied by soothing background music."},{src:"https://assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.38/static/video/video_man.mp4",description:'Hard light, side lighting, medium shot, low saturation, high contrast, medium focal length, eye-level close-up of a man. He\'s wearing a striped shirt, sitting at a wooden table with folders and a red telephone on it. His arms are crossed over his chest, and his head rests against the wall. His eyes are closed, mouth slightly open, saying, "I really like it here." A blurred figure appears in the foreground. The background is a dark wooden wall adorned with a painting and other decorations. The entire scene evokes a quiet, contemplative mood.'},{image:"https://qwen-chat.oss-ap-southeast-1.aliyuncs.com/resources/i2v/1762487167.png",src:"https://assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.38/static/video/video_deer.mp4",description:"On a lawn in Nara, a girl attentively feeds a fawn, gazing at it, with a Japanese ambiance and bright sunshine."},{image:"https://qwen-chat.oss-ap-southeast-1.aliyuncs.com/resources/i2v/1762076628.png",src:"https://assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.38/static/video/video_bear.mp4",description:'The light flickered above his head as he softly asked, "Why does 1 + 1 equal 2?"'},{image:"https://qwen-chat.oss-ap-southeast-1.aliyuncs.com/resources/i2v/1762498392.png",src:"https://assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.38/static/video/video_sea.mp4",description:"A diver in a diving suit explores the secrets of a sunken ship in the deep sea, holding a searchlight that illuminates the dark underwater world."}],travel:[{query:"I plan to go to Shanghai alone for three days the day after tomorrow, departing from Hangzhou. Can you help me arrange the itinerary?",title:"Shanghai 3-day cultural tour: an in-depth exploration of museums, gardens, and urban memories"},{query:"Plan a 7-day itinerary for the Northern Xinjiang small loop, departing from Beijing next Monday, for one person",title:"7-Day Self-Drive Tour of Northern Xinjiang's Natural Wonders: A Journey Through Autumn Landscapes"},{query:"Next weekend, the three of us in my family will depart from Shanghai and head to Qiandao Lake for a two-day trip. Please arrange an itinerary for us.",title:"Qiandao Lake family slow tour: a two-day lakeside and mountain scenery trip from Shanghai on September 20-21, 2025"},{query:"Next Saturday, my family of three will leave from Beijing to Nanjing for a three-day trip. Please arrange the itinerary for me.",title:"3-Day Relaxing Family Trip to Nanjing: A Journey of Cultural Strolls and Natural Adventures"}],deepResearch:[{query:"Using Ne Zha 2 as an entry point to analyze the development of Chinese cinema",title:"Ne Zha 2: A milestone in the industrialization and cultural export of Chinese cinema"},{query:"Please introduce and compare the advantages and disadvantages of the three algorithms PPO, GRPO, and DAPO respectively",title:"Comparative analysis of the advantages and disadvantages of PPO, GRPO, and DAPO algorithms"},{query:"I want to go to Hong Kong for a week. Can you help me plan the itinerary, departing from Beijing?",title:"Research Report on a One-Week Travel Itinerary from Beijing to Hong Kong"},{query:"Research the 5 vitamins most needed by Chinese people, describing their functions, the scientific research behind them, the principles of how they work in the body, and methods and recommendations for supplementing vitamins for the general public.",title:"The 5 Most Essential Vitamins for Chinese People: Their Functions and Supplementation Recommendations"},{query:"Analysis and prediction of the men's singles professional tennis landscape in the next three years",title:"Research Report on the Development Trends of Men's Professional Singles Tennis over the Next Three Years"}],webdev:[{darkSrc:"https://img.alicdn.com/imgextra/i1/O1CN017XBwc120EhQlYC19P_!!6000000006818-2-tps-948-543.png",src:"https://img.alicdn.com/imgextra/i4/O1CN01xlhSky1GuPAf4eFrK_!!6000000000682-2-tps-948-543.png",title:"Create a personal website for a software engineer, including sections such as personal introduction, education background, project experience, etc."},{darkSrc:"https://img.alicdn.com/imgextra/i2/O1CN012BqDoa1Pa69W0BdH8_!!6000000001856-2-tps-948-543.png",src:"https://img.alicdn.com/imgextra/i1/O1CN011dEWtw1rpx6TbxdQj_!!6000000005681-2-tps-948-543.png",title:'Create a semantic "Contact Support" form with fields for the user\'s name, email, issue type, and message. Arrange the form elements vertically within a card.'},{darkSrc:"https://img.alicdn.com/imgextra/i2/O1CN01Ytn7DF1CaTTG0gSei_!!6000000000097-2-tps-948-543.png",src:"https://img.alicdn.com/imgextra/i1/O1CN01iVUvAq1i3YiGagDmD_!!6000000004357-2-tps-948-543.png",title:"Write a fruit e-commerce website."},{darkSrc:"https://img.alicdn.com/imgextra/i4/O1CN01ihIvuO1yioEnAH8u1_!!6000000006613-2-tps-948-543.png",src:"https://img.alicdn.com/imgextra/i1/O1CN01ywIpzR1Xgz24H0Ncl_!!6000000002954-2-tps-948-543.png",title:'How many "r"s are in the word "strawberrrrry"? Make a cute little card!'},{darkSrc:"https://img.alicdn.com/imgextra/i2/O1CN01uhXGeZ1ZKexWGzZlM_!!6000000003176-2-tps-948-543.png",src:"https://img.alicdn.com/imgextra/i1/O1CN01PIcmRB1PEZXN1OKaN_!!6000000001809-2-tps-948-543.png",title:"Create a social networking website with a RedNote-style design."},{darkSrc:"https://img.alicdn.com/imgextra/i2/O1CN01kArlys1wCAma0newZ_!!6000000006271-2-tps-948-543.png",src:"https://img.alicdn.com/imgextra/i2/O1CN01s5jfll1uOsXTRizNd_!!6000000006028-2-tps-948-543.png",title:"Create a sunscreen product introduction website."}],artifacts:[{darkSrc:"https://gw.alicdn.com/imgextra/i4/O1CN01ZdJIjT1fF3sUKjTNr_!!6000000003976-2-tps-428-428.png",src:"https://img.alicdn.com/imgextra/i1/O1CN01AgbiQ71yFUxO3h4xH_!!6000000006549-2-tps-428-428.png",title:"Make a Snake game"},{darkSrc:"https://gw.alicdn.com/imgextra/i1/O1CN01S9mOFg1evMqfRtvET_!!6000000003933-2-tps-428-428.png",src:"https://gw.alicdn.com/imgextra/i3/O1CN017K0DcV1POBvESFfa3_!!6000000001830-2-tps-428-428.png",title:"Make a small Gomoku game."},{darkSrc:"https://gw.alicdn.com/imgextra/i4/O1CN01I5THsV1qZdRbRF9iD_!!6000000005510-2-tps-428-428.png",src:"https://img.alicdn.com/imgextra/i4/O1CN01a6ENqb1r0CPqXgVxK_!!6000000005568-2-tps-428-428.png",title:"Make a Minesweeper mini-game."},{darkSrc:"https://gw.alicdn.com/imgextra/i4/O1CN01wn4g301Bzpr3kSh1k_!!6000000000017-2-tps-428-428.png",src:"https://gw.alicdn.com/imgextra/i4/O1CN01d56W5Z1OHwuMXAODJ_!!6000000001681-2-tps-428-428.png",title:'How many "r" in strawberry? Make a cute card.'},{darkSrc:"https://gw.alicdn.com/imgextra/i4/O1CN01667lYe1Vmoumn8WcH_!!6000000002696-2-tps-428-428.png",src:"https://gw.alicdn.com/imgextra/i3/O1CN01xtY5q81p0559MmbeU_!!6000000005297-2-tps-428-428.png",title:"Create a simple calculator web application"},{darkSrc:"https://gw.alicdn.com/imgextra/i4/O1CN01Ep3Zzc1utZ8uDdQgj_!!6000000006095-2-tps-428-428.png",src:"https://gw.alicdn.com/imgextra/i2/O1CN01uv8VjV1KmOmEpjYIP_!!6000000001206-2-tps-428-428.png",title:"Create a personal portfolio website with sections for an 'About Me' page, a 'Projects' gallery, a 'Blog' for sharing articles, and a 'Contact' form."},{darkSrc:"https://gw.alicdn.com/imgextra/i4/O1CN01wyU3f627u6c9sX6S6_!!6000000007856-2-tps-428-428.png",src:"https://gw.alicdn.com/imgextra/i4/O1CN01ZeTokW1jyBMTnpBRD_!!6000000004616-2-tps-428-428.png",title:"Create a graphical workflow overview HTML of RAGs"},{darkSrc:"https://gw.alicdn.com/imgextra/i1/O1CN01c9hWwo1CNC3KoT7tt_!!6000000000068-2-tps-428-428.png",src:"https://gw.alicdn.com/imgextra/i2/O1CN01naKo021scxY6NHkBf_!!6000000005788-2-tps-428-428.png",title:"Create a presentation deck for a startup pitch, including slides for the company overview, market analysis, product features, business model, and financial projections. The presentation should be visually appealing, and have multiple slides that user can switch to next and previous slides by clicking the arrow keys."},{darkSrc:"https://gw.alicdn.com/imgextra/i4/O1CN01gDjcpE25kMxmi0uFY_!!6000000007564-2-tps-428-428.png",src:"https://gw.alicdn.com/imgextra/i3/O1CN01CY0TRf1k00wg7XDr1_!!6000000004620-2-tps-428-428.png",title:"Check the weather in London and make a weather card including temperature, weather, and emoji expressions."}]},sp={thumbSrcArr:[{src:"https://img.alicdn.com/imgextra/i1/O1CN017XBwc120EhQlYC19P_!!6000000006818-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01oCnNjp1xBXvmYeKEG_!!6000000006405-49-tps-400-229.webp"},{src:"https://gw.alicdn.com/imgextra/i4/O1CN01ZdJIjT1fF3sUKjTNr_!!6000000003976-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01pi0Uyx1JVAGWmnXeG_!!6000000001033-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i2/O1CN01Zz1Vkw1wqThW3tPiv_!!6000000006359-2-tps-1328-1328.png",thumbSrc:"https://img.alicdn.com/imgextra/i2/O1CN01wOjTM81VeZnHjc1qq_!!6000000002678-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i4/O1CN01D1as1J1L65nt2fHdQ_!!6000000001249-2-tps-1328-1328.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01MoTge41SXl3B4u2kF_!!6000000002257-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01AgbiQ71yFUxO3h4xH_!!6000000006549-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01lZe6zn1a6IE2jkaRx_!!6000000003280-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01NdWLo81xvnvVAFPLO_!!6000000006506-0-tps-2688-1536.jpg",thumbSrc:"https://img.alicdn.com/imgextra/i1/O1CN01miayeI23uKLociabU_!!6000000007315-49-tps-400-229.webp"},{src:"https://img.alicdn.com/imgextra/i4/O1CN01xlhSky1GuPAf4eFrK_!!6000000000682-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01YStbCr284djRQmahh_!!6000000007879-49-tps-400-229.webp"},{src:"https://img.alicdn.com/imgextra/i2/O1CN019msx361dXGO8i0Rh3_!!6000000003745-2-tps-896-1184.png",thumbSrc:"https://img.alicdn.com/imgextra/i1/O1CN01fnyWCA1vTI2ng1pql_!!6000000006173-49-tps-400-529.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01QVEMzK1cxztKSiT76_!!6000000003668-2-tps-928-1120.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01TsTBlD1c8F8t1bP1D_!!6000000003555-49-tps-400-483.webp"},{src:"https://img.alicdn.com/imgextra/i3/O1CN01L3M9El1DWdqE9Vjxk_!!6000000000224-0-tps-2688-1536.jpg",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01iCFidR1wRHvdCJZ3Z_!!6000000006304-49-tps-400-229.webp"},{src:"https://img.alicdn.com/imgextra/i2/O1CN012BqDoa1Pa69W0BdH8_!!6000000001856-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01tPKJMN1OfJ7F3btFS_!!6000000001732-49-tps-400-229.webp"},{src:"https://gw.alicdn.com/imgextra/i1/O1CN01S9mOFg1evMqfRtvET_!!6000000003933-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01ws9XXv1FjaGwFRm1G_!!6000000000523-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01934VZ31nXr3QuT52K_!!6000000005100-2-tps-1328-1328.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01Ej2qlI1KnlyPjG9zZ_!!6000000001209-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN011dEWtw1rpx6TbxdQj_!!6000000005681-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01GNBZaW1U5TpOz9yDd_!!6000000002466-49-tps-400-229.webp"},{src:"https://gw.alicdn.com/imgextra/i3/O1CN017K0DcV1POBvESFfa3_!!6000000001830-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01OgBkHn283GXmSr6FS_!!6000000007876-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01tCFNKB1IgmguoHC1Z_!!6000000000923-0-tps-2688-1536.jpg",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN019UtYFb1cECICVur4y_!!6000000003568-49-tps-400-229.webp"},{src:"https://gw.alicdn.com/imgextra/i4/O1CN01I5THsV1qZdRbRF9iD_!!6000000005510-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01oqp09C1xMXR8cKZ6o_!!6000000006429-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i2/O1CN01Ytn7DF1CaTTG0gSei_!!6000000000097-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01Aub8v61kSruEEmeHS_!!6000000004683-49-tps-400-229.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01jODjPc1MpGU6MJ166_!!6000000001483-2-tps-1328-1328.png",thumbSrc:"https://img.alicdn.com/imgextra/i2/O1CN01zzoogg1S86s2Z4jmW_!!6000000002201-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i3/O1CN01GAGbbu1Ip1ow3vKmv_!!6000000000941-0-tps-2688-1536.jpg",thumbSrc:"https://img.alicdn.com/imgextra/i2/O1CN016huzZe29SkBzsR4cA_!!6000000008067-49-tps-400-229.webp"},{src:"https://img.alicdn.com/imgextra/i4/O1CN01a6ENqb1r0CPqXgVxK_!!6000000005568-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01YR3SOu1QuXWHxZxRR_!!6000000002036-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01iVUvAq1i3YiGagDmD_!!6000000004357-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01teeSge1JyTc8HueNE_!!6000000001097-49-tps-400-229.webp"},{src:"https://img.alicdn.com/imgextra/i4/O1CN01ihIvuO1yioEnAH8u1_!!6000000006613-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01kGrS5K1idk4tO5mhV_!!6000000004436-49-tps-400-229.webp"},{src:"https://gw.alicdn.com/imgextra/i4/O1CN01wn4g301Bzpr3kSh1k_!!6000000000017-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN018IvhTR1pBzO7Q73qn_!!6000000005323-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i4/O1CN01D5BCtm1l1fzxQsLqt_!!6000000004759-0-tps-2528-1446.jpg",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01KNl3Vg1KUzjbsqFmt_!!6000000001168-49-tps-400-229.webp"},{src:"https://gw.alicdn.com/imgextra/i4/O1CN01d56W5Z1OHwuMXAODJ_!!6000000001681-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01JktKN31QaqUNXtPQN_!!6000000001993-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01ywIpzR1Xgz24H0Ncl_!!6000000002954-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i2/O1CN01Yk0fyX20aE7aWdLq5_!!6000000006865-49-tps-400-229.webp"},{src:"https://gw.alicdn.com/imgextra/i4/O1CN01667lYe1Vmoumn8WcH_!!6000000002696-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i2/O1CN01QMOX3X26eFI89U7HP_!!6000000007686-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i2/O1CN01uhXGeZ1ZKexWGzZlM_!!6000000003176-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i2/O1CN01ATQvT91iAQjHkCz4i_!!6000000004372-49-tps-400-229.webp"},{src:"https://img.alicdn.com/imgextra/i3/O1CN0192DFe51RpKclEnurK_!!6000000002160-2-tps-1328-1328.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN010P9Vt11QvSJOIkxmh_!!6000000002038-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01PIcmRB1PEZXN1OKaN_!!6000000001809-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01w3soE21NBFVSa8QG6_!!6000000001531-49-tps-400-229.webp"},{src:"https://gw.alicdn.com/imgextra/i3/O1CN01xtY5q81p0559MmbeU_!!6000000005297-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i2/O1CN01lcLsSq1rxHW587QSf_!!6000000005697-49-tps-400-400.webp"},{src:"https://gw.alicdn.com/imgextra/i4/O1CN01Ep3Zzc1utZ8uDdQgj_!!6000000006095-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN011WxHSg1DxfDTd8jfi_!!6000000000283-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i2/O1CN01kArlys1wCAma0newZ_!!6000000006271-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN0120IgkM1kaedg2ycg3_!!6000000004700-49-tps-400-229.webp"},{src:"https://qwen-chat.oss-ap-southeast-1.aliyuncs.com/resources/i2v/1762487167.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01j20eSA1XDflAlyEPg_!!6000000002890-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i2/O1CN01kUdRxi1kVcH5C8ISv_!!6000000004689-2-tps-1328-1328.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01D9OcTa1NOzO9EyLBM_!!6000000001561-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i2/O1CN01s5jfll1uOsXTRizNd_!!6000000006028-2-tps-948-543.png",thumbSrc:"https://img.alicdn.com/imgextra/i1/O1CN01TgvTDc2A9nQGPwNHd_!!6000000008161-49-tps-400-229.webp"},{src:"https://gw.alicdn.com/imgextra/i2/O1CN01uv8VjV1KmOmEpjYIP_!!6000000001206-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01vY70TY1juWCWOkeqN_!!6000000004608-49-tps-400-400.webp"},{src:"https://gw.alicdn.com/imgextra/i4/O1CN01wyU3f627u6c9sX6S6_!!6000000007856-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01j8CKVK1yYHCew7qxV_!!6000000006590-49-tps-400-400.webp"},{src:"https://qwen-chat.oss-ap-southeast-1.aliyuncs.com/resources/i2v/1762076628.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01J2kHS01vg78Lts3j2_!!6000000006201-49-tps-400-400.webp"},{src:"https://gw.alicdn.com/imgextra/i4/O1CN01ZeTokW1jyBMTnpBRD_!!6000000004616-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01OMXHmI1Z7pwdpDjcg_!!6000000003148-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i4/O1CN01xLPQIH1V9Qr0ExqVI_!!6000000002610-2-tps-1328-1328.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01a6ZYxR2ABAbvmCTZZ_!!6000000008164-49-tps-400-400.webp"},{src:"https://gw.alicdn.com/imgextra/i1/O1CN01c9hWwo1CNC3KoT7tt_!!6000000000068-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN018hs5Kc1XBqAx9OSkW_!!6000000002886-49-tps-400-400.webp"},{src:"https://qwen-chat.oss-ap-southeast-1.aliyuncs.com/resources/i2v/1762498392.png",thumbSrc:"https://img.alicdn.com/imgextra/i1/O1CN01tVNSDy1iQuzJ8S6Zk_!!6000000004408-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i3/O1CN016vFiI81beTOMAEFwM_!!6000000003490-2-tps-1328-1328.png",thumbSrc:"https://img.alicdn.com/imgextra/i1/O1CN01MDAH8B1m7ScmyIPJL_!!6000000004907-49-tps-400-400.webp"},{src:"https://gw.alicdn.com/imgextra/i2/O1CN01naKo021scxY6NHkBf_!!6000000005788-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i4/O1CN01RC3mSc1uC3WZnMMQJ_!!6000000006000-49-tps-400-400.webp"},{src:"https://gw.alicdn.com/imgextra/i4/O1CN01gDjcpE25kMxmi0uFY_!!6000000007564-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i1/O1CN01Btt5mr1xbeVUGvUHo_!!6000000006462-49-tps-400-400.webp"},{src:"https://gw.alicdn.com/imgextra/i3/O1CN01CY0TRf1k00wg7XDr1_!!6000000004620-2-tps-428-428.png",thumbSrc:"https://img.alicdn.com/imgextra/i1/O1CN01GW65nD1MUefkoJTi4_!!6000000001438-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i1/O1CN01Ma8xRN1xB5Wl7L2Gn_!!6000000006404-2-tps-1024-1024.png",thumbSrc:"https://img.alicdn.com/imgextra/i1/O1CN0137HZlL1kOkLDtD0Dg_!!6000000004674-49-tps-400-400.webp"},{src:"https://img.alicdn.com/imgextra/i3/O1CN01JfrYlp1O8KajeDs4B_!!6000000001660-2-tps-1024-1024.png",thumbSrc:"https://img.alicdn.com/imgextra/i3/O1CN01YtLxUq1sx6z4o8bb1_!!6000000005832-49-tps-400-400.webp"}]},ip=()=>{var e;const t=cR(e=>e.config),n=cR(e=>e.fetchConfig),s=Jh(e=>e.getSettingConfig),i=hR(e=>e.setOmniSpeakers),a=hR(e=>e.setTTSAudioTTSSpeakers),o=hR(e=>e.setAudioTTSLanguage),r=hR(e=>e.setOmniLanguage),l=Pd(e=>e.fetchUser),c=dR(e=>e.mobile),d=Jh(e=>e.getSettings),u=Pd(e=>e.user),h=Ue(),m=D.useRef(!1),p=yd(e=>e.getModels),g=yd(e=>e.fetchModels),f=ud(e=>e.setTheme),v=ud(e=>e.setLanguage),y=Jh(e=>e.settings)||{},b=Jh(e=>e.updateLocalUiSettings),x=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_manage_cookies}),w=cR(e=>e.setConfigLoaded),_=cR(e=>e.setShowCookieConfirm),{i18n:C}=ye(),[S]=He(),k=ud(e=>e.isSharePage),{ui:j}=y,T=null==j?void 0:j.theme,E=null!=(e=null==j?void 0:j.language)?e:C.language;let N=!1;const I=S.get("shareId");Xu({appLayoutEmit:!0}),tp(),D.useEffect(()=>{Os=h},[h]),Yd();const M=()=>A(null,null,function*(){let e=null;try{e=yield n()}catch(t){e=null}return setTimeout($d,0),Ud(),s(),!0});D.useEffect(()=>{const e=Wd("theme");T&&!e&&(f(T),Hl(T))},[T,f]);const R=D.useCallback(()=>{const e=((e=Jd,t=!1)=>{if(t)return!0;const n=window.navigator.userAgent,s=n.match(/Chrome\/(\d+)/),i=n.match(/Firefox\/(\d+)/),a=n.match(/Edg\/(\d+)/),o=n.includes("Safari")&&!n.includes("Chrome"),r=n.match(/Version\/(\d+)/);if(s){const t=Number.parseInt(s[1],10);return!!(t&&t>=e.chrome)}if(i){const t=Number.parseInt(i[1],10);return!!(t&&t>=e.firefox)}if(a){const t=Number.parseInt(a[1],10);return!!(t&&t>=e.edge)}if(o&&r){const t=Number.parseInt(r[1],10);return!!(t&&t>=e.safari)}return!0})(void 0,c),t=document.getElementById("low-version-browser");e&&(null==t||t.remove()),!e&&t&&(t.style.display="flex",NR(),w(!0))},[c]),P=D.useCallback((e,t)=>{var n,s,i,a,o,r;if(!y.tts_speaker_v2)return;if(wR()||"pending"===(null==(n=Pd.getState().user)?void 0:n.role)||0===(null==e?void 0:e.length)||void 0!==(null==(i=null==(s=Jh.getState().settings)?void 0:s.tts_speaker_v2)?void 0:i.speaker))return;const l=Xd(e||[],{languages:au(e,t),genders:"female"});if(0===l.length)return;const c=l[0];(null==y?void 0:y.tts_speaker_v2)&&e.every(e=>{var t;return e.speaker!==(null==(t=y.tts_speaker_v2)?void 0:t.speaker)})?(null==(a=null==y?void 0:y.tts_speaker_v2)?void 0:a.is_personal)||bM.onUpdateVoice(c.speaker):((null==y?void 0:y.tts_speaker_v2)||(null==(o=null==y?void 0:y.tts_speaker_v2)?void 0:o.is_personal))&&(null==(r=y.tts_speaker_v2)?void 0:r.speaker)||bM.onUpdateVoice(c.speaker)},[y.tts_speaker_v2]),L=D.useRef(""),O=D.useCallback(e=>A(null,null,function*(){if(L.current!==e){L.current=e;try{const{data:{audio_tts_speakers:t,omni_speakers:n,omni_language:s,audio_tts_language:l}}=yield k_(e);a(t),o(l),i(n||[]),r(s),P(t,e)}catch(t){}}else P(hR.getState().ttsAudioTTSSpeakers,e)}),[P,a,o,i,r]);D.useEffect(()=>{A(null,null,function*(){const e=S.get("lang"),n=yield VR(),s=(null==t?void 0:t.default_locale)||"en-US";let i="";if(e)i=yn(n,[e],s);else if(E)Js()||(i=E);else if(localStorage.getItem("locale"))i=localStorage.getItem("locale")||"";else{const e=navigator.languages||[navigator.language||navigator.userLanguage];i=yn(n,e,s)}C.changeLanguage(i),v(i),yR("qwen-locale",i),O(i)}),ti()&&localStorage.locale&&""===j.language&&b({language:localStorage.locale});const e=bR("qwen-locale");e&&e!==j.language&&g(!0,j.language)},[j.language]),D.useEffect(()=>{ti()&&localStorage.theme&&(Hl(localStorage.theme),b({theme:localStorage.theme}))},[b]),D.useEffect(()=>{x&&u&&_(!0)},[x,_,u]);D.useEffect(()=>{m.current&&gl(null==u?void 0:u.id)},[location.pathname]);const q=["/auth","/reset","/s/","/legal-agreement/terms-of-service","/legal-agreement/privacy-policy","/legal-agreement/usage-policy","/legal-agreement/contact-us","/legal-agreement/models","/legal-agreement/about","/mobile/chatcontrols/","/extension","/community"],U=D.useCallback(()=>A(null,null,function*(){var e;const t=yield l(!1);if(N)return void h("/auth");if(!t){if(!u){if(!q.some(e=>location.pathname.startsWith(e))&&"/"!==location.pathname){if(I)return;h("/",{replace:!0})}return}return location.pathname.length>=36&&!k?void h("/c/guest"):(null==(e=bM.adapter)||e.clearCookie(pt.SETAPP),void(Js()?bM.adapter.routeTologin():h("/auth")))}if("user"!==t.role)return;yield d(),yield p(),Mh.subscribePolling(),Js()&&bM.adapter.saveCookie(localStorage.token,pt.SETAPP),ti()&&bM.adapter.invoke({method:"storeInfo",params:{key:Vd("chatNativeToken"),value:JSON.stringify({token:localStorage.token}),needPersist:!0}});const n=t.id;n&&(ul("setUid",{params:{et:"OTHER",c1:n}}),Object.defineProperty(window,"userId",{value:n,writable:!0})),Js()||ti()||(yield A(null,null,function*(){const e=new URLSearchParams(window.location.search).get("temporary-chat");wR()||"true"!==e||(yield bM.updateTemporaryChat(!0))}))}),[l,u,k,h]),H=()=>A(null,null,function*(){var e;(()=>{const e=Wd("qsrc");e&&ul("reportingSource",{params:{et:"OTHER",c2:e}})})();const t=Wd("theme");Hl(null!=(e=null!=t?t:null==localStorage?void 0:localStorage.theme)?e:"system");if(!(yield M()))return;yield A(null,null,function*(){var e;let t=xR();if(ti()){let s={};try{(null==window?void 0:window.QwenChat)||(yield HR(1e3));let t={};li("1.2.10")||(t=yield bM.adapter.invoke({method:"getStoredInfo",params:{key:"chatNativeToken"}})),s=JSON.parse(null==(e=null==t?void 0:t.result)?void 0:e.value)}catch(n){}t=bR("token")||(null==s?void 0:s.token),localStorage.token=t||""}return t}),yield p(),yield U(),m.current=!0,gl(null==u?void 0:u.id);new URLSearchParams(window.location.search).get("shareId")||NR(),w(!0),A(null,null,function*(){var e;ec().then(e=>{e.isPrivate&&cR.getState().setIsDisableGuestAccess(!0)}),Js()&&(document.body.style.setProperty("padding-top",oi()),document.body.style.setProperty("padding-bottom",ri()),document.getElementById("splash-screen")||(bM.adapter.invoke({method:"onPageReady"}),bM.adapter.resetNativeState())),si()&&(null==(e=window.electronAPI)||e.on_event("set_cookie",e=>A(null,null,function*(){e&&(localStorage.token=e),window.location.replace("/")})))})});return D.useEffect(()=>(N="/c/guest"===location.pathname,R(),Sl(),H(),()=>{var e;null==(e=window.electronAPI)||e.on_event(void 0),gM.destroyInstance()}),[]),D.useEffect(()=>{E&&O(E)},[O,E]),F.jsx("div",{className:"app",children:F.jsx(Be,{})})},ap=e=>{const{onClose:t,icon:n,title:s,children:i}=e;return F.jsxs("div",{className:"head-container",style:{top:oi()},children:[!!n&&F.jsx(pi,{onClick:()=>{t()},type:n,className:"head-close-icon"}),!!s&&F.jsx("div",{className:"head-title",children:s}),i&&F.jsx("div",{className:"head-children",children:i})]})},op=()=>{const e=cR(e=>e.mobile),t=cR(e=>e.pad),{i18n:n}=ye(),s=Pd(e=>e.user),[i,a]=D.useState(!0),[o,r]=D.useState(0),[l,c]=D.useState(!1),d=Pd(e=>e.fetchUser),u=D.useCallback(()=>A(null,null,function*(){window.location.reload()}),[]),h=D.useCallback(()=>{Bd.getState().resetAllEquity(),vR("token"),vR("settings"),vR("resendEmailTimer"),vR("active_token"),sessionStorage.removeItem("Auth_Source"),u()},[u]),m=D.useCallback(()=>A(null,null,function*(){yield Nd(),h()}),[h]),p=D.useCallback(()=>{switch(null==s?void 0:s.role){case"pending":return n.t("Please Verify Your Email");case"disabled":return n.t("Account Deactivation Notice");default:return""}},[n,null==s?void 0:s.role]),g=D.useCallback(()=>{switch(null==s?void 0:s.role){case"pending":return n.t("The account is pending activation. Please activate your account through the verification email in your inbox.");case"disabled":return n.t("Your account has been suspended due to suspected violation of platform rules. If you have any questions, please contact DPO_qwenlm-intl@service.alibaba.com to apply for reinstatement.");default:return""}},[n,null==s?void 0:s.role]),f=D.useCallback(()=>A(null,null,function*(){(null==s?void 0:s.id)&&!(null==s?void 0:s.role)&&(yield d(!1))}),[d,null==s?void 0:s.id,null==s?void 0:s.role]);D.useEffect(()=>{f()},[f,null==s?void 0:s.id]);const v=D.useCallback(()=>A(null,null,function*(){var e;a(!1);const t={id:null==s?void 0:s.id,token:localStorage.getItem("active_token"),email:null==s?void 0:s.email},i=yield(o=t,A(null,null,function*(){return yield TM("/auths/resendactivationemail",{method:"POST",data:o})}));var o;i&&i.success?vi.openOnce({type:"success",content:n.t("Email sent successfully")}):vi.openOnce({type:"error",content:n.t(null==(e=null==i?void 0:i.data)?void 0:e.message)}),a(!0)}),[n,s]),y=({isMobile:e})=>{const t=e?"account-pending-mobile-button":"account-pending-desktop-button",a=e?"account-pending-mobile-button cancel":"account-pending-desktop-button-cancel",d=D.useCallback(e=>{if(!e)return 0;const t=60-Math.floor((Date.now()-e)/1e3);return t>0?t:0},[]);D.useEffect(()=>{const e=localStorage.getItem("resendEmailTimer");if(e){const t=parseInt(e,10),n=d(t);n>0?(r(n),c(!0)):localStorage.removeItem("resendEmailTimer")}},[d]),D.useEffect(()=>{let e=null;return l&&o>0&&(e=setInterval(()=>{r(e=>e<=1?(localStorage.removeItem("resendEmailTimer"),c(!1),0):e-1)},1e3)),()=>{e&&clearInterval(e)}},[l,o]);const h=D.useCallback(()=>{if(!i||l)return;v();const e=Date.now();localStorage.setItem("resendEmailTimer",e.toString()),r(60),c(!0)},[i,l,v]),p=!i||l,g=l?`${n.t("Resend Email")} (${o}s)`:n.t("Resend Email");return F.jsxs(F.Fragment,{children:["disabled"!==(null==s?void 0:s.role)&&F.jsxs(F.Fragment,{children:[F.jsx("button",{className:t,onClick:()=>{u()},children:n.t("Check Again")}),F.jsx("button",{className:t,disabled:p,onClick:h,children:g})]}),F.jsx("button",{className:a,onClick:()=>{m()},children:n.t("Log out")})]})};return F.jsx("div",{className:"account-pending-overlay",children:F.jsxs("div",{className:"account-pending-backdrop "+(e?"mobile-backdrop":"desktop-backdrop"),children:[e&&F.jsx(ap,{icon:"icon-line-chevron-left",onClose:h}),F.jsxs("div",{className:"account-pending-container "+(e?"mobile-container":"desktop-container"),children:[e&&F.jsx("h2",{className:"account-pending-title",children:p()}),F.jsx("div",{className:"account-pending-description "+(e?"mobile-description":"desktop-description"),children:g()}),(e||t)&&F.jsx("div",{className:"account-pending-mobile-button-wrapper",children:F.jsx(y,{isMobile:!0})}),!e&&!t&&F.jsx("div",{className:"account-pending-desktop-button-wrapper",children:F.jsx(y,{isMobile:!1})})]})]})})},rp=({children:e})=>{const t=Pd(e=>e.user),n=js(e=>e.history),s=!!(_r(n.currentId,n).length>0||Object.keys(n.messages).length>0);return Xu({}),wR()||!t||["user","admin"].includes(t.role)||s?F.jsx("div",{className:"main-layout native-layout",children:e||F.jsx(Be,{})}):F.jsx(op,{})},lp=e=>Symbol.iterator in e,cp=e=>"entries"in e,dp=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),s=t instanceof Map?t:new Map(t.entries());if(n.size!==s.size)return!1;for(const[i,a]of n)if(!s.has(i)||!Object.is(a,s.get(i)))return!1;return!0};function up(e,t){return!!Object.is(e,t)||"object"==typeof e&&null!==e&&"object"==typeof t&&null!==t&&(Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&(lp(e)&&lp(t)?cp(e)&&cp(t)?dp(e,t):((e,t)=>{const n=e[Symbol.iterator](),s=t[Symbol.iterator]();let i=n.next(),a=s.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=s.next()}return!!i.done&&!!a.done})(e,t):dp({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})))}function hp(e){const t=O.useRef(void 0);return n=>{const s=e(n);return up(t.current,s)?t.current:t.current=s}}const mp=({className:e="size-5",color:t="currentColor",style:n,containerClassName:s=""})=>F.jsx("div",{className:s,style:n,children:F.jsxs("svg",{className:Q("circle-spinner",e),viewBox:"0 0 24 24",fill:t,xmlns:"http://www.w3.org/2000/svg",children:[F.jsx("path",{d:"M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z",opacity:".25",fill:t}),F.jsx("path",{d:"M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z",className:"spinner_ajPY",fill:t})]})}),pp="index-module__model-selector-loading___mkq-P",gp="index-module__model-selector-loading-text___Klahu",fp=()=>{const e=ye();return F.jsxs(ie,{className:pp,align:"center",gap:8,children:[F.jsx(mp,{containerClassName:"spinner"}),F.jsx("div",{className:gp,children:e.t("Model loading...")})]})},vp=D.memo(({showRegister:e=!1,size:t="small",rounded:n,buttonClass:s})=>{const{t:i}=ye(),a=e=>{Us.getInstance().navigate(e)},o=D.useMemo(()=>location.pathname.includes("/community")?`/auth?from=${window.location.pathname.slice(1)}`:"/auth",[]),r=D.useMemo(()=>location.pathname.includes("/community")?`/auth?mode=register&from=${window.location.pathname.slice(1)}`:"/auth?mode=register",[]);return F.jsxs("div",{className:"auth-buttons",children:[F.jsx(xi,{size:t,rounded:n,buttonClass:s,onClick:e=>{si()?(e.preventDefault(),bM.adapter.openWindow(`${window.location.origin}/auth?callback=qwen://open`)):a(o),pl("clkLogOn",{params:{et:"CLK"}})},children:i("Log in")}),e&&F.jsx(xi,{type:"ghost",size:t,rounded:n,buttonClass:s,onClick:e=>{si()?(e.preventDefault(),bM.adapter.openWindow(`${window.location.origin}/auth?mode=register&callback=qwen://open`)):a(r),pl("clkRegister",{params:{et:"CLK"}})},children:i("Sign up")})]})}),yp=({equity:e,onUpdate:t})=>{const{i18n:n}=ye(),s=cR(e=>e.mobile),i=Fd(e=>e.subscriptionPlus);return F.jsxs("div",{className:"qwen-chat-equity-message-content",children:[F.jsx("div",{className:"qwen-chat-equity-message-text",children:du({remains:null==e?void 0:e.remains,unit:null==e?void 0:e.unit,currentI18n:n})}),s&&!Js()&&!i&&F.jsx("div",{className:"qwen-chat-equity-message-btn",onClick:t,children:n.t("Upgrade")})]})},bp=()=>{const e=ud(e=>e.setSettingActionMenuItemId),t=ud(e=>e.setCloseSubscriptionPopupToSetting),n=Ue();return{updateEquityHandlerByMessage:D.useCallback(()=>A(null,null,function*(){V.destroy(),yield t(!1),yield e("subscription"),n("/settings")}),[n,t,e])}},xp={mobileModelSelectorContent:"index-module__mobile-model-selector-content___PFEdq",modelSelectorName:"index-module__model-selector-name___zc6Lm",modelSelectorPlus:"index-module__model-selector-plus___qJZrZ",text:"index-module__text___M-u73",modelSelectorIcon:"index-module__model-selector-icon___K91li",mobileModelSelectorPopupWrapper:"index-module__mobile-model-selector-popup-wrapper___RJ8rs",mobileModelSelectorPopup:"index-module__mobile-model-selector-popup___Qe6C-",modelList:"index-module__model-list___7F09n",modelListPb24:"index-module__model-list-pb24___zQIso",modelItem:"index-module__model-item___8rK-g",modelItemName:"index-module__model-item-name___admtE",modelItemDesc:"index-module__model-item-desc___hQkXJ",modelItemSelected:"index-module__model-item-selected___V53cX",modelListViewMore:"index-module__model-list-view-more___zxWR7",authButtons:"index-module__auth-buttons___UJdJJ"},wp=()=>{var e,t;const n=ye(),s=Fd(e=>e.subscriptionPlus),i=dR(e=>e.mobile),a=cR(e=>e.config),o=yd(e=>e.isLoading),r=bd(e=>e.selectedModels),l=bd(e=>e.selectedModelIds),c=yd(e=>e.visibleModels),{updateEquityHandlerByMessage:d}=bp(),[u,h]=D.useState(!1),[m,p]=D.useState(!1),g=r,f=o||0===g.length,v=D.useMemo(()=>{var e,t;return(null==(t=null==(e=null==a?void 0:a.features)?void 0:e.limits)?void 0:t.model_display_count)||3},[a]),y=()=>{h(!1),p(!1)},b=e=>{if(l.includes(e.id))return;const{disabled:t,content:n}=(e=>{const t=Bd.getState().getModelEquity(e);let n=!1,s="";return null!==t.remains&&0!==t.remains||(n=!0,s=F.jsx(yp,{equity:t,onUpdate:d})),{disabled:n,content:s}})(e.id);t?vi.open({type:"warning",content:n,closable:s}):(xM.setSingleModel(e.id),y())};return f?F.jsx(fp,{}):F.jsxs("div",{className:xp.mobileModelSelector,children:[F.jsxs("div",{className:xp.mobileModelSelectorContent,onClick:()=>{h(!0)},ref:e=>{e&&e.style&&(e.style.animation="none",e.style.webkitTextFillColor="unset")},children:[F.jsx("div",{className:xp.modelSelectorName,children:null==(e=g[0])?void 0:e.name}),i&&s&&F.jsx("div",{className:xp.modelSelectorPlus,children:F.jsx("div",{className:xp.text,children:"Plus"})}),F.jsx(pi,{className:xp.modelSelectorIcon,type:"icon-fill-triangle-down-01"})]}),F.jsxs(Ti,{open:u,heightType:m?"full":"auto",onClose:y,leftFirstIcon:"icon-line-chevron-left-02",title:n.t("Models"),destroyOnHidden:!0,className:xp.mobileModelSelectorPopup,style:{paddingBottom:ri()},rootClassName:xp.mobileModelSelectorPopupWrapper,children:[F.jsxs("div",{className:Q(xp.modelList,{[xp.modelListPb24]:m}),children:[null==(t=m?c:c.slice(0,v))?void 0:t.map(e=>{var t,s,i,a;return F.jsxs("div",{className:xp.modelItem,onClick:()=>b(e),children:[F.jsxs(ie,{vertical:!0,gap:2,flex:1,children:[F.jsx("div",{className:xp.modelItemName,children:e.name}),F.jsx("div",{className:xp.modelItemDesc,children:(null==(s=null==(t=null==e?void 0:e.info)?void 0:t.meta)?void 0:s.short_description)?null==(a=null==(i=null==e?void 0:e.info)?void 0:i.meta)?void 0:a.short_description:n.t("No model description available")})]}),l.includes(e.id)&&F.jsx(pi,{className:xp.modelItemSelected,type:"icon-line-check-02"})]},e.id)}),!wR()&&!m&&F.jsx("div",{className:xp.modelListViewMore,onClick:()=>p(!0),children:n.t("Expand more models")})]}),wR()&&F.jsx("div",{className:xp.authButtons,children:F.jsx(vp,{rounded:"circle",size:"large",showRegister:!0})})]})]})},_p=({isPro:e=!1,showUpgrade:t=!1,showTopBorder:n=!1,onClick:s})=>{const i=ye(),a=Fd(e=>e.fetchPaymentSubscriptionInfo),o=Fd(e=>e.paymentSubscriptionInfo),r=D.useMemo(()=>e?{title:i.t("Qwen Plus"),iconType:"icon-line-star-02",desc:null==o?void 0:o.plus.description}:{title:i.t("Qwen"),iconType:"icon-line-free",desc:null==o?void 0:o.normal.description},[i,e,null==o?void 0:o.normal.description,null==o?void 0:o.plus.description]);return D.useEffect(()=>{a()},[]),F.jsxs("div",{className:Q("chat-model-selector-pro-info",{"chat-model-selector-pro-info-top-border":n}),children:[F.jsx("div",{className:"chat-model-selector-pro-info-avatar",children:F.jsx(pi,{type:r.iconType,className:"chat-model-selector-pro-info-avatar-icon"})}),F.jsxs("div",{className:"chat-model-selector-pro-info-middle",children:[F.jsx("div",{className:"chat-model-selector-pro-info-title",children:r.title}),F.jsx("div",{className:"chat-model-selector-pro-info-des",children:r.desc})]}),t&&F.jsx(xi,{type:"tertiary",rounded:"circle",onClick:s,children:i.t("Upgrade")})]})},Cp=()=>{},Sp=D.createContext({open:!1,onOpenChange:Cp,battle:!1,onBattleChange:Cp,disabledBattle:!1}),kp={modelIntro:"index-module__model-intro___Jg3XY",introText:"index-module__intro-text___qZWCH",introIcon:"index-module__intro-icon___wumYu",battleText:"index-module__battle-text___gRTDg"},jp=()=>{const e=ye(),t=Ue(),n=cR(e=>e.mobile),{battle:s,onBattleChange:i,disabledBattle:a}=D.useContext(Sp);return F.jsxs(ie,{className:kp.modelIntro,align:"center",justify:"space-between",children:[F.jsxs(ie,{className:kp.intro,gap:4,children:[F.jsx("div",{className:kp.introText,children:e.t("Model")}),!wR()&&F.jsx(Si,{title:!n&&e.t("Model description"),children:F.jsx(pi,{className:kp.introIcon,type:"icon-line-information-circle",onClick:()=>{t("/settings/model")}})})]}),!wR()&&F.jsx(Si,{title:a&&e.t("Model comparison is not supported under the current settings"),children:F.jsxs(ie,{className:kp.battle,gap:8,align:"center",children:[F.jsx("div",{className:kp.battleText,children:e.t("Model Comparison")}),F.jsx(Hi,{disabled:a,checked:s,onChange:i})]})})]})},Tp="index-module__model-list___-NnN5",Ep="index-module__model-item___MkLlj",Np="index-module__model-item-not-allowed___nYbxz",Ip="index-module__model-item-selected___0WMb1",Ap="index-module__model-item-name___X8Hec",Mp="index-module__model-set-default-icon-hidden___SzTEt",Rp="index-module__model-item-content___ydaoe",Pp="index-module__model-set-default-icon___Ibwo2",Lp="index-module__model-item-desc___sIEVp",Op="index-module__model-item-operation___nMq-D",Dp="index-module__radio___4fhLr",Fp="index-module__checkbox___cSlSd",qp=({models:e,className:t,renderSubscribePrefix:n})=>{const s=ye(),i=yd(e=>e.selectedModelIds),a=yd(e=>e.selectedModels),o=Jh(e=>{var t,n;return null==(n=null==(t=e.settings)?void 0:t.ui)?void 0:n.models}),r=Jh(e=>e.updateQwenChatSettings),{battle:l,onOpenChange:c}=D.useContext(Sp),d=js(e=>e.currentInputFeature),u=e=>{l?xM.toggleModelSelection(e.id):((e=>{var t,n;d===yt.WebSearch&&(null==(n=null==(t=null==e?void 0:e.info)?void 0:t.meta)?void 0:n.auto_search)&&xM.resetToTxt2Txt()})(e),xM.setSingleModel(e.id)),l||c(!1)};return F.jsx("div",{className:Q(Tp,t),children:null==e?void 0:e.map((e,t)=>{var c,d,h,m;const p=i.includes(e.id),g=!!l&&(!p&&a.length>=3),f=null==o?void 0:o.includes(e.id);return F.jsxs(ie,{className:Q(Ep,{[Ip]:p,[Np]:g}),align:"center",gap:8,onClick:()=>u(e),children:[null==n?void 0:n(0===t),F.jsxs(ie,{flex:1,vertical:!0,className:Rp,children:[F.jsxs(ie,{className:Ap,gap:8,align:"center",children:[F.jsx("span",{children:e.name}),F.jsx(Si,{title:f?s.t("Cancel default"):s.t("Set as default"),children:F.jsx(pi,{className:Q(Pp,{[Mp]:!f}),type:f?"icon-fill-pin-01":"icon-line-pin-01",onClick:t=>{var n,i;t.stopPropagation(),n=e.id,i=f?"remove":"add",A(null,null,function*(){"add"===i?(yield r({ui:{models:[n]}}),vi.open({type:"success",content:s.t("Default model updated"),closable:!1})):(yield r({ui:{models:[]}}),vi.open({type:"success",closable:!1,content:s.t("The default model has been cleared.")}))})}})})]}),F.jsx("div",{className:Lp,children:(null==(d=null==(c=null==e?void 0:e.info)?void 0:c.meta)?void 0:d.short_description)?null==(m=null==(h=null==e?void 0:e.info)?void 0:h.meta)?void 0:m.short_description:s.t("No model description available")})]}),F.jsx("div",{className:Op,children:l?F.jsx(Oi,{className:Fp,disabled:!p&&a.length>=3,checked:p,style:{}}):p&&F.jsx(pi,{className:Dp,type:"icon-line-check-02"})})]},e.id)})})},Up={modelSelector:"index-module__model-selector___rdCim",modelSelectorText:"index-module__model-selector-text___XvWe0",modelSelectorIcon:"index-module__model-selector-icon___-po5j",subscribePrefix:"index-module__subscribe-prefix___O3z8I",subscribePrefixNobg:"index-module__subscribe-prefix-nobg___gpBRA",modelSelectorPopup:"index-module__model-selector-popup___TGWn8",modelSelectorPopupSecondary:"index-module__model-selector-popup-secondary___Ukrgv",moreModelList:"index-module__more-model-list___5IZ7S",viewMore:"index-module__view-more___iP0nb",viewMoreText:"index-module__view-more-text___DlmZJ",viewMoreIcon:"index-module__view-more-icon___45kdG",divider:"index-module__divider___fFhyz",upgradeSubscribe:"index-module__upgrade-subscribe___-q1Bl"},Hp=({disabled:e})=>{var t;const n=ye(),s=yd(e=>e.isLoading),i=bd(e=>e.selectedModels),a=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_payment_and_quota}),o=cR(e=>{var t,n,s,i;return(null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_payment)&&(null==(i=null==(s=null==e?void 0:e.config)?void 0:s.features)?void 0:i.enable_payment_and_quota)}),r=Fd(e=>e.subscriptionPlus),l=Fd(e=>e.setShowSubscriptionDetail),c=cR(e=>e.config),d=D.useMemo(()=>{var e,t;return(null==(t=null==(e=null==c?void 0:c.features)?void 0:e.limits)?void 0:t.model_display_count)||3},[c]),u=D.useRef(null),[h,m]=D.useState(!1),[p,g]=D.useState(!1),f=s||0===i.length,v=yd(e=>e.visibleModels),y=D.useMemo(()=>p?null==v?void 0:v.filter(e=>{var t,n,s;return 4!==(null==(s=null==(n=null==(t=e.info)?void 0:t.meta)?void 0:n.abilities)?void 0:s.thinking)}):v,[p,v]),b=(null==y?void 0:y.slice(0,d))||[],x=(null==y?void 0:y.slice(d))||[],w=e=>{e&&pl("clkSelectModelBtn",{params:{et:"CLK"}}),m(e)},_=e=>wR()||!a?null:e?F.jsx("div",{className:Up.subscribePrefix,children:F.jsx(pi,{type:"icon-line-free"})}):F.jsx("div",{className:Q(Up.subscribePrefix,Up.subscribePrefixNobg)});return D.useEffect(()=>{e?g(!1):h||g(i.length>1)},[e,i,h]),f?F.jsx(fp,{}):F.jsx(Sp.Provider,{value:{open:h,onOpenChange:w,battle:p,onBattleChange:e=>{if(!e&&i.length>1)for(let t=i.length-1;t>=1;t--)xM.deselectModel(i[t].id);g(e)},disabledBattle:e},children:F.jsx(Ci,{open:h,onOpenChange:w,placement:"bottomLeft",menu:null,popupRender:()=>F.jsxs("div",{className:Up.modelSelectorPopup,children:[F.jsx(jp,{}),F.jsx(qp,{models:b,renderSubscribePrefix:_}),wR()?F.jsxs(F.Fragment,{children:[F.jsx("div",{className:Up.divider}),F.jsx(vp,{showRegister:!0,size:"middle",rounded:"circle",buttonClass:Up.authButtons})]}):F.jsxs(F.Fragment,{children:[F.jsx("div",{ref:u,style:{position:"relative"},children:F.jsx(Ci,{trigger:["hover"],menu:null,overlayStyle:{left:"100%",top:"0",right:"0",bottom:"0"},getPopupContainer:e=>e,popupRender:()=>F.jsx("div",{className:Q(Up.modelSelectorPopup,Up.modelSelectorPopupSecondary),children:F.jsx(qp,{models:x,className:Up.moreModelList})}),children:F.jsxs(ie,{className:Up.viewMore,align:"center",justify:"space-between",gap:8,children:[_(!1),F.jsx(ie,{className:Up.viewMoreText,flex:1,children:n.t("Expand more models")}),F.jsx(pi,{className:Up.viewMoreIcon,type:"icon-line-chevron-right"})]})})}),o&&!r&&F.jsxs("div",{className:Up.upgradeSubscribe,children:[F.jsx("div",{className:Up.divider}),F.jsx(_p,{isPro:!0,showUpgrade:!0,onClick:()=>{w(!1),l(!0)}})]})]})]}),children:F.jsxs("div",{className:Up.modelSelector,children:[F.jsx("div",{className:Up.modelSelectorText,children:(null==i?void 0:i.length)>1?`${i.length} ${n.t("Models")}`:null==(t=i[0])?void 0:t.name}),F.jsx(pi,{className:Up.modelSelectorIcon,type:"icon-line-chevron-down"})]})})})},Bp={notification:[],memoryNotification:void 0,wsNotifications:[],wsStatus:"disconnected",unreadCount:0,dismissedNotifications:[],isInitialized:!1,isInitializing:!1,isPullComplete:!1,prePullCompleteNotificationIds:[]},zp=Sn()(ps(_s((e,t)=>C(C({},Bp),((e,t)=>({setNotification:n=>{const{clearNotificationById:s}=t(),i=Fe(),a=n,{duration:o=1e4,id:r=i,props:l}=a,c=k(a,["duration","id","props"]),d=setTimeout(()=>{0!==o&&s(r)},o),u=C({id:r,timer:d,duration:o},c);e(e=>{e.notification=[u,...e.notification],e.memoryNotification=l})},clearNotificationById:n=>{const{notification:s}=t(),i=s.find(e=>e.id===n);i&&clearTimeout(i.timer),e(e=>{e.notification=e.notification.filter(e=>e.id!==n)})},clearAllNotification:()=>{e(e=>{e.notification=[]})},addWSNotification:t=>{e(e=>{e.wsNotifications.some(e=>e.id===t.id)||(e.wsNotifications=[t,...e.wsNotifications],e.unreadCount+=1)})},removeWSNotification:t=>{e(e=>{e.wsNotifications.find(e=>e.id===t)&&(e.wsNotifications=e.wsNotifications.filter(e=>e.id!==t),e.prePullCompleteNotificationIds=e.prePullCompleteNotificationIds.filter(e=>e!==t),e.unreadCount=Math.max(0,e.unreadCount-1))})},removeBatchWSNotifications:t=>{e(e=>{e.wsNotifications=e.wsNotifications.filter(e=>!t.includes(e.id)),e.prePullCompleteNotificationIds=e.prePullCompleteNotificationIds.filter(e=>!t.includes(e)),e.unreadCount=Math.max(0,e.unreadCount-t.length)})},clearWSNotifications:()=>{e(e=>{e.wsNotifications=[],e.unreadCount=0,e.isPullComplete=!1,e.prePullCompleteNotificationIds=[]})},setWSStatus:t=>{e(e=>{e.wsStatus=t})},setUnreadCount:t=>{e(e=>{e.unreadCount=t})},markAsRead:t=>{e(e=>{e.wsNotifications.find(e=>e.id===t)&&e.unreadCount>0&&(e.unreadCount-=1)})},markAllAsRead:()=>{e(e=>{e.unreadCount=0})},addDismissNotification:t=>{e(e=>{e.dismissedNotifications.push(...t)})},setMemoryNotification:t=>{e(e=>{e.memoryNotification=t})},setIsInitialized:t=>{e(e=>{e.isInitialized=t})},setIsInitializing:t=>{e(e=>{e.isInitializing=t})},setIsPullComplete:t=>{e(e=>{e.isPullComplete=t,e.prePullCompleteNotificationIds=t?e.wsNotifications.map(e=>e.id):[]})}}))(e,t)),{name:"notificationStore",store:"notificationStore",enabled:!1})));const Gp="qwen_chat_device_id";function $p(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const Wp=new class{constructor(){j(this,"xid",null),j(this,"token",null),j(this,"ws",null),j(this,"sharedWorker",null),j(this,"sharedWorkerPort",null),j(this,"usingSharedWorker",!1),j(this,"sharedWorkerFailed",!1),j(this,"sharedConnectionKey",null),j(this,"sharedWorkerInitTimer",null),j(this,"sharedWorkerInitTimeout",1e3),j(this,"status","disconnected"),j(this,"reconnectTimer",null),j(this,"heartbeatTimer",null),j(this,"activeTabTimer",null),j(this,"reconnectAttempts",0),j(this,"maxReconnectAttempts",5),j(this,"reconnectDelay",3e3),j(this,"heartbeatInterval",3e4),j(this,"callbacks",{}),j(this,"userId",null),j(this,"deviceType",null),j(this,"deviceId",null),j(this,"isActiveTab",!1),j(this,"receivedMessageIds",new Set),j(this,"visibilityChangeHandler",null)}resolveSharedWorkerScriptUrl(){const e=new URL("//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.2.67/assets/notification.shared-worker.js",window.location.origin);return e.origin===window.location.origin?e.toString():`${window.location.origin}/scripts/qwen-chat-cdn/0.0.5/public/worker/notification.shared-worker.js`}createSharedWorker(){const e=this.resolveSharedWorkerScriptUrl();return new SharedWorker(e,{name:"notification-worker"})}startSharedWorkerInitTimeout(){this.clearSharedWorkerInitTimeout(),this.sharedWorkerInitTimer=setTimeout(()=>{this.usingSharedWorker&&"connecting"===this.status&&this.fallbackToPerTabWebSocket(`shared worker init timeout (${this.sharedWorkerInitTimeout}ms)`)},this.sharedWorkerInitTimeout)}clearSharedWorkerInitTimeout(){this.sharedWorkerInitTimer&&(clearTimeout(this.sharedWorkerInitTimer),this.sharedWorkerInitTimer=null)}getDeviceType(){if(si())return"desktop";if(Js()){if(zs())return"ios";if($s())return"android"}return"web"}buildWebSocketUrl(e,t,n,s,i){let a=ot;if(a.startsWith("https://"))a=a.replace("https://","wss://");else if(a.startsWith("http://"))a=a.replace("http://","ws://");else{const e="https:"===window.location.protocol?"wss:":"ws:",t=window.location.host;a=a&&""!==a?a.startsWith("/")?`${e}//${t}${a}`:`${e}//${a.replace(/^\/\//,"")}`:`${e}//${t}/api/v1`}return`${a}/notifications/ws?${[`user_id=${encodeURIComponent(e)}`,`device_type=${encodeURIComponent(t)}`,`device_id=${encodeURIComponent(n)}`,`xid=${encodeURIComponent(s)}`,`token=${encodeURIComponent(i)}`].join("&")}`}connect(e,t){"connected"!==this.status&&"connecting"!==this.status?(this.userId=e,this.deviceType=this.getDeviceType(),this.deviceId=function(){try{const e=localStorage.getItem(Gp);if(e)return e;const t=$p();return localStorage.setItem(Gp,t),t}catch(e){try{const e=sessionStorage.getItem(Gp);if(e)return e;const t=$p();return sessionStorage.setItem(Gp,t),t}catch(t){return $p()}}}(),this.xid=(e=>{const t=e.replace(/-/g,"");let n="",s=BigInt("0x"+t);const i=BigInt(62);for(;n.length<8;)n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(s%i)]+n,s/=i;for(;n.length<8;)n="0"+n;return n})(e),this.token=localStorage.getItem("token"),this.callbacks=t||{},this.sharedConnectionKey=`${this.userId}:${this.deviceType}:${this.deviceId}:${this.token||""}`,this.sharedWorkerFailed=!1,this.isActiveTab=!document.hidden,this.setupVisibilityListeners(),this.status="connecting",this.connectBySharedWorker()||this.connectWebSocket()):this.callbacks=C(C({},this.callbacks),t||{})}setupVisibilityListeners(){this.visibilityChangeHandler||(this.visibilityChangeHandler=()=>{this.isActiveTab=!document.hidden,this.isActiveTab&&"connected"===this.status&&!this.usingSharedWorker&&this.sendActiveMessage(),this.usingSharedWorker&&this.sharedWorkerPort&&this.sharedConnectionKey&&this.sharedWorkerPort.postMessage({type:"active",key:this.sharedConnectionKey,active:this.isActiveTab})},document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.addEventListener("beforeunload",()=>{this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null)}))}connectBySharedWorker(){if("undefined"==typeof window||"undefined"==typeof SharedWorker)return!1;if(!(this.sharedConnectionKey&&this.userId&&this.deviceType&&this.deviceId))return!1;try{this.sharedWorker=this.createSharedWorker();const e=this.sharedWorker.port;return this.sharedWorkerPort=e,this.usingSharedWorker=!0,this.startSharedWorkerInitTimeout(),this.sharedWorker.onerror=e=>{this.fallbackToPerTabWebSocket("shared worker script load error")},e.onmessage=e=>{var t,n,s,i,a,o,r,l,c,d;const u=e.data;if(this.sharedConnectionKey&&u.key===this.sharedConnectionKey){if(this.clearSharedWorkerInitTimeout(),"status"===u.type){const e=this.status;return this.status=u.status,"connected"===u.status&&"connected"!==e&&(null==(n=(t=this.callbacks).onOpen)||n.call(t)),"disconnected"===u.status&&"connected"===e&&(null==(i=(s=this.callbacks).onClose)||i.call(s)),"connecting"!==u.status||"disconnected"!==e&&"error"!==e||null==(o=(a=this.callbacks).onReconnect)||o.call(a),void("error"===u.status&&this.fallbackToPerTabWebSocket("shared worker status error"))}"notification"!==u.type?"pull_complete"!==u.type?"error"===u.type&&(this.status="error",this.fallbackToPerTabWebSocket(u.message||"shared worker runtime error")):null==(d=(c=this.callbacks).onPullComplete)||d.call(c):null==(l=(r=this.callbacks).onMessage)||l.call(r,u.notification)}},e.start(),e.postMessage({type:"init",payload:{key:this.sharedConnectionKey,userId:this.userId,deviceType:this.deviceType,deviceId:this.deviceId,xid:this.xid,token:this.token||""}}),e.postMessage({type:"active",key:this.sharedConnectionKey,active:this.isActiveTab}),!0}catch(e){return this.clearSharedWorkerInitTimeout(),this.usingSharedWorker=!1,this.sharedWorker=null,this.sharedWorkerPort=null,!1}}fallbackToPerTabWebSocket(e){this.sharedWorkerFailed||(this.sharedWorkerFailed=!0,this.clearSharedWorkerInitTimeout(),this.sharedWorkerPort&&this.sharedConnectionKey&&(this.sharedWorkerPort.postMessage({type:"disconnect",key:this.sharedConnectionKey}),this.sharedWorkerPort.close()),this.sharedWorkerPort=null,this.sharedWorker=null,this.usingSharedWorker=!1,this.status="disconnected",this.connectWebSocket())}connectWebSocket(){if(this.userId&&this.deviceType&&this.deviceId)try{const e=this.buildWebSocketUrl(this.userId,this.deviceType,this.deviceId,this.xid,this.token||"");this.ws=new WebSocket(e),this.ws.onopen=()=>{var e,t;this.status="connected",this.reconnectAttempts=0,this.receivedMessageIds.clear(),null==(t=(e=this.callbacks).onOpen)||t.call(e),this.startHeartbeat()},this.ws.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleMessage(t)}catch(t){}},this.ws.onerror=e=>{var t,n;this.status="error",null==(n=(t=this.callbacks).onError)||n.call(t,e)},this.ws.onclose=()=>{var e,t;this.status="disconnected",this.stopHeartbeat(),this.stopActiveTabHeartbeat(),null==(t=(e=this.callbacks).onClose)||t.call(e),this.scheduleReconnect()}}catch(e){this.status="error",this.scheduleReconnect()}else this.status="error"}handleMessage(e){var t,n,s,i;if("heartbeat"!==e.type&&"active"!==e.type)if("pull_complete"!==e.type){if(e.id&&e.payload){if(this.receivedMessageIds.has(e.id))return;this.receivedMessageIds.add(e.id);const t={id:e.id,type:e.type,event_type:e.event_type,payload:e.payload,send_time:e.send_time||1e3*Date.now()};null==(i=(s=this.callbacks).onMessage)||i.call(s,t)}}else null==(n=(t=this.callbacks).onPullComplete)||n.call(t)}sendHeartbeat(){var e;if((null==(e=this.ws)?void 0:e.readyState)===WebSocket.OPEN){const e={type:"heartbeat",ts:1e3*Math.floor(Date.now())};this.send(e)}}sendActiveMessage(){var e;if((null==(e=this.ws)?void 0:e.readyState)===WebSocket.OPEN&&this.isActiveTab){const e={type:"active",ts:1e3*Math.floor(Date.now())};this.send(e)}}startHeartbeat(){this.stopHeartbeat(),this.sendHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}stopActiveTabHeartbeat(){this.activeTabTimer&&(clearInterval(this.activeTabTimer),this.activeTabTimer=null)}send(e){var t;if((null==(t=this.ws)?void 0:t.readyState)===WebSocket.OPEN)try{this.ws.send(JSON.stringify(e))}catch(n){}}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return;this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectAttempts++;const e=this.reconnectDelay*this.reconnectAttempts;this.reconnectTimer=setTimeout(()=>{var e,t;this.userId&&(this.status="disconnected",this.connectWebSocket(),null==(t=(e=this.callbacks).onReconnect)||t.call(e))},e)}disconnect(){if(this.clearSharedWorkerInitTimeout(),this.usingSharedWorker&&this.sharedWorkerPort&&this.sharedConnectionKey)return this.sharedWorkerPort.postMessage({type:"disconnect",key:this.sharedConnectionKey}),this.sharedWorkerPort.close(),this.sharedWorkerPort=null,this.sharedWorker=null,this.usingSharedWorker=!1,this.status="disconnected",void(this.reconnectAttempts=0);this.stopHeartbeat(),this.stopActiveTabHeartbeat(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.status="disconnected",this.reconnectAttempts=0}getStatus(){return this.status}updateCallbacks(e){this.callbacks=C(C({},this.callbacks),e)}sendMessage(e){this.usingSharedWorker&&this.sharedWorkerPort&&this.sharedConnectionKey?this.sharedWorkerPort.postMessage({type:"send",key:this.sharedConnectionKey,payload:e}):this.send(e)}clearReceivedMessageIds(){this.receivedMessageIds.clear()}},Vp=()=>({markNotificationAsRead:D.useCallback(e=>{var t;if(!e)return;if(null==(t=Pd.getState().user)?void 0:t.id)try{Wp.sendMessage({type:"notification_status_update",notifications:[{notification_id:e}]}),zp.getState().removeWSNotification(e)}catch(n){}},[]),markBatchNotificationsAsRead:D.useCallback(e=>{var t;if(0===e.length)return;if(null==(t=Pd.getState().user)?void 0:t.id)try{Wp.sendMessage({type:"notification_status_update",notifications:e.map(e=>({notification_id:e}))}),zp.getState().removeBatchWSNotifications(e)}catch(n){}},[])}),Qp=O.lazy(()=>Se(()=>import("./index28.js"),__vite__mapDeps([1,0,2,3,4]))),Kp="notification_update_popover",Yp=()=>{const e=js(e=>e.currentInputFeature),{thinkingEnabled:t,mcpEnabled:n}=Rs(hp(e=>({thinkingEnabled:e.thinkingEnabled,mcpEnabled:e.mcpEnabled}))),s=dR(e=>e.mobile),i=D.useMemo(()=>F.jsx("div",{className:"model-selector-blank-space",children:F.jsx("div",{id:`${Kp}_model_selector`,className:"notification-update-popover-model-selector"})}),[]);return s?F.jsxs(F.Fragment,{children:[i,F.jsx(wp,{disabled:e!==yt.Txt2Txt||t||n})]}):F.jsxs(F.Fragment,{children:[i,F.jsx(Hp,{disabled:e!==yt.Txt2Txt||t||n})]})},Jp=D.memo(()=>{const{t:e}=ye(),t=D.useRef(null),n=dR(e=>e.mobile),s=Kh(e=>e.setMobileRecommendDetailVisible);return D.useEffect(()=>{t.current&&(t.current.style.opacity="1",t.current.style.cursor="pointer")},[]),F.jsx("div",{onClick:()=>{n&&"/"!==window.location.pathname&&s(!1),bM.openNewChat(),pl("clkCreateChat",{params:{et:"CLK"}})},className:"new-chat",ref:t,style:{opacity:.4,cursor:"not-allowed"},children:F.jsx(Si,{title:e("New Chat"),show:!n,children:F.jsx(pi,{type:n?"icon-line-message-alert-plus":"icon-line-edit-contained"})})})}),Xp=({isSetting:e=!1})=>{const t=dR(e=>e.mobile),n=hd(e=>e.showSidebar),s=ud(e=>e.setShowSidebar),i=ud(e=>e.setUserActiveSidebar),a=ud(e=>e.setSettingSidebar),o=ud(e=>e.showSettingSidebar),r=D.useRef(null);return D.useEffect(()=>{r.current&&(r.current.style.opacity="1",r.current.style.cursor="pointer")},[]),wR()||!e&&n?null:F.jsx("div",{id:ct.SIDEBAR_TOGGLE_BUTTON,className:"sidebar-toggle-button",onClick:()=>{e?a(!o):(s(!n),i(!0))},ref:r,style:{opacity:.4,cursor:"not-allowed"},children:F.jsx(pi,{type:t?"icon-line-menu-04":"icon-line-sidePanel",className:"sidebar-toggle-icon"})})},Zp="fev",eg="0.2.67",tg=()=>eg,ng=(e=((e=Zp)=>{const t=new URL(window.location.href);return new URLSearchParams(t.search).get(e)||"0.0.0"})(),t=eg)=>{var n,s;const i=e.split(".").map(Number),a=t.split(".").map(Number),o=Math.max(i.length,a.length);for(let r=0;rt)return"greater";if(e{const{chatId:t,show:n,onClose:s}=e,i=ye(),[a,o]=D.useState(null),r=D.useRef(!1),l=cR(e=>e.mobile),c=Rs(e=>e.taskRunning),d=D.useCallback(()=>A(null,null,function*(){var e;let n;try{if(n=yield xg(t),!n.success)return vi.open({type:"error",content:i.t(null==(e=n.data)?void 0:e.message)}),s(),""}catch(r){}if(!n)throw s(),new Error("sharedChat is null");const a=yield dg({chat_id:t});return a&&o(a.data),`${window.location.origin}/s/${n.data.id}`}),[t,i,s]),u=D.useCallback(e=>!a||!!e&&((null==a?void 0:a.id)!==e.id||(null==a?void 0:a.share_id)!==e.share_id),[a]),h=D.useCallback(()=>A(null,null,function*(){if(c)return void vi.openOnce({type:"error",content:i.t("The current chat is not yet complete, please wait for a while and retry.")});if(r.current)return;r.current=!0;const e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);try{if(Vs()||e||zs())yield navigator.clipboard.write([new ClipboardItem({"text/plain":new Promise((e,n)=>A(null,null,function*(){try{let n=yield d();n+=`?${Zp}=${tg()}`,e(new Blob([n],{type:"text/plain"})),pl("clkShareCopyLink",{params:{et:"CLK",c6:n},paramsExtend:{chat_id:t}})}catch(s){n(s)}}))})]);else{let e=yield d();if(!e)return;e+=`?${Zp}=${tg()}`,pl("clkShareCopyLink",{params:{et:"CLK",c6:e},paramsExtend:{chat_id:t}}),setTimeout(()=>{SR(e)},0)}vi.open({type:"success",content:i.t("Copied shared chat URL to clipboard!")}),s()}catch(n){}r.current=!1}),[t,i,s,d,c]);return D.useEffect(()=>{A(null,null,function*(){if(t&&n){const e=yield dg({chat_id:t});e&&u(e)&&o(e.data)}else o(null)})},[t,n]),a?l?F.jsx(wi,{visible:n,header:!1,footer:!1,closable:!1,size:"small",maskClosable:!0,onCancel:s,children:F.jsxs("div",{className:"mobile-share-modal",children:[F.jsx("div",{className:"mobile-share-modal-title",children:i.t("Share Chat")}),F.jsxs("div",{className:"mobile-share-modal-content",children:[F.jsx("div",{className:"mobile-share-modal-content-main",children:(null==a?void 0:a.share_id)?F.jsxs(F.Fragment,{children:[Js()&&!li("1.0.0")?F.jsxs(F.Fragment,{children:[i.t("You have shared this chat"),F.jsx("span",{children:i.t("before")}),"."]}):F.jsx(F.Fragment,{children:F.jsxs("a",{href:`/s/${a.share_id}`,target:"_blank",children:[i.t("You have shared this chat"),F.jsxs("span",{children:[i.t("before"),"."]})]})}),i.t("Click here to"),F.jsx("button",{onClick:()=>A(null,null,function*(){if(yield wg(t).catch(e=>(vi.open({type:"error",content:i.t(e.message)}),null))){const e=yield dg({chat_id:t});e&&o(e.data)}}),children:i.t("delete this link")}),i.t("and create a new shared link.")]}):i.t("Messages you send after creating your link won't be shared. Users with the URL will be able to view the shared chat.")}),F.jsx("div",{className:"mobile-share-modal-content-end",children:F.jsx("div",{className:"mobile-share-modal-content-end-content",children:F.jsx("div",{})})})]}),F.jsxs("div",{className:"mobile-share-modal-footer",children:[F.jsx(xi,{onClick:h,children:(null==a?void 0:a.share_id)?i.t("Update and Copy Link"):i.t("Copy Link")}),F.jsx(xi,{type:"link",onClick:s,children:i.t("Cancel")})]})]})}):F.jsx(wi,{className:"web-share-modal",size:"small",title:i.t("Share Chat"),onCancel:s,visible:n,headerBorderNone:!0,onOk:h,okText:a.share_id?i.t("Update and Copy Link"):i.t("Copy Link"),cancelButtonProps:{hidden:!0},okButtonProps:{iconFontType:"icon-Link1",iconFontStyle:{fontSize:12},type:"brandprimary",size:"middle",buttonStyle:{height:"36px"},rounded:"circle"},children:F.jsx("div",{children:F.jsx("div",{className:"share-modal-main",children:F.jsx("div",{className:"share-modal-main-content",children:a.share_id?F.jsxs(F.Fragment,{children:[si()?F.jsxs("a",{className:"share-modal-main-conten-link",children:[i.t("You have shared this chat"),F.jsx("span",{onClick:e=>di(e,`${window.location.origin}/s/${a.share_id}`),children:i.t("before")}),"."]}):F.jsxs("a",{href:`/s/${a.share_id}`,className:"share-modal-main-conten-link",target:"_blank",children:[i.t("You have shared this chat"),F.jsxs("span",{children:[i.t("before"),"."]})]}),i.t("Click here to"),F.jsx("button",{onClick:()=>A(null,null,function*(){if(yield wg(t).catch(e=>(vi.open({type:"error",content:i.t(e.message)}),null))){const e=yield dg({chat_id:t});e&&o(e.data)}}),children:i.t("delete this link")}),i.t("and create a new shared link.")]}):i.t("Messages you send after creating your link won't be shared. Users with the URL will be able to view the shared chat.")})})})}):null},ig=()=>{const e=pw(e=>e.setOperationProjectFiles),t=pw(e=>e.setProjectArr),n=()=>A(null,null,function*(){try{const e=yield cw();if(e&&e.success){const n=Array.isArray(null==e?void 0:e.data)?e.data:[];return t(n),n}return[]}catch(e){return[]}});return{getNewProjectList:n,getProjectFilesList:t=>A(null,null,function*(){try{const{data:s,success:i}=yield lw(t);if(!i)return void("Not_Found"===s.code&&n());if(!(null==s?void 0:s.files)||!Array.isArray(s.files))return;const a=s.files.map(e=>S(C({},e),{uploadStatus:"success"}));return yield e(a),a}catch(s){}}),getProjectChatList:(e,t=1)=>A(null,null,function*(){try{const{data:n,success:s}=yield dw(e,t);if(!s)return;return n}catch(n){}}),extractProjectId:e=>{const t=e.match(/^\/p\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i);return t?t[1]:null}}},ag=()=>A(null,null,function*(){return yield TM("/chats/",{method:"DELETE"})}),og=()=>A(null,null,function*(){return yield TM("/chats/all")}),rg=e=>A(null,null,function*(){return yield Sl(),yield TM("/chats/",{params:e})}),lg=()=>A(null,null,function*(){return yield TM("/chats/pinned")}),cg=e=>A(null,null,function*(){return yield TM("/chats/search",{params:e})}),dg=(e,t)=>A(null,null,function*(){var n;const s=S(C({},t),{toast:null!=(n=null==t?void 0:t.toast)?n:!ti()});return yield Sl(),yield TM(`/chats/${e.chat_id}`,s)}),ug=e=>A(null,null,function*(){const{chat_id:t,chat:n}=e,{title:s,tags:i,history:a,permission:o}=n||{},{currentId:r,currentResponseIds:l}=a||{},c={};return s&&(c.title=s),r&&(c.currentId=r),l&&(c.currentResponseIds=l),i&&(c.tags=i),o&&(c.permission=o),yield TM(`/chats/${t}`,{method:"POST",data:c})}),hg=e=>A(null,null,function*(){return yield TM(`/chats/${e.chat_id}/messages/${e.message_id}`,{method:"POST",data:{content:e.content,content_list:e.content_list}})}),mg=e=>A(null,null,function*(){const t=new FormData;return t.append("file",e.file),yield TM("/chats/import",{method:"POST",headers:{"Content-Type":"multipart/form-data"},transformRequest:[e=>e],data:t})}),pg=()=>A(null,null,function*(){return yield TM("/chats/archive/all",{method:"POST"})}),gg=()=>A(null,null,function*(){return yield TM("/chats/archived")}),fg=e=>A(null,null,function*(){return yield TM(`/chats/${e||"all"}/archive`,{method:"POST"})}),vg=e=>A(null,null,function*(){return yield TM(`/chats/${e}`,{method:"DELETE"})}),yg=e=>A(null,null,function*(){return yield TM(`/chats/${e}/pin`,{method:"POST"})}),bg=e=>A(null,null,function*(){return yield TM(`/chats/${e}/clone`,{method:"POST"})}),xg=e=>A(null,null,function*(){return yield TM(`/chats/${e}/share`,{method:"POST"})}),wg=e=>A(null,null,function*(){return yield TM(`/chats/${e}/share`,{method:"DELETE"})}),_g=e=>A(null,null,function*(){return yield TM("/filter/content",{baseURL:"/api",method:"POST",data:e})}),Cg=e=>A(null,null,function*(){return yield Sl(),yield TM("/community/share",{method:"POST",data:C({},e),toast:!1})}),Sg=e=>A(null,null,function*(){return yield Sl(),yield TM(`/community/share/${e.shareId}`,{toast:!1})}),kg=e=>A(null,null,function*(){return yield TM("/share/message/cancel",{method:"POST",data:{share_id:e.id}})}),jg=e=>A(null,null,function*(){return yield Sl(),yield TM(`/chats/${e.chatId}/check`,{method:"GET"})}),Tg=()=>{const e=js(e=>e.currentChatPage),t=Rs(e=>e.setFolders),n=ye(),s=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_project}),i=()=>A(null,null,function*(){const{data:e}=yield wf(s);return Array.isArray(e)?e:[]});return{getChatListData:e=>A(null,null,function*(){const{data:t}=yield rg({page:e,exclude_project:!0});return t||[]}),getAllTagsData:()=>A(null,null,function*(){const{data:e}=yield A(null,null,function*(){return yield Sl(),yield TM("/chats/all/tags")});return e}),getChatListBySearchTextData:(t,...n)=>A(null,[t,...n],function*(t,n=e){const{data:s}=yield cg({text:t,page:n});return s}),getPinnedChatListData:()=>A(null,null,function*(){const{data:e,success:t}=yield lg();return t?e:[]}),getFoldersData:i,initFolders:()=>A(null,null,function*(){const e=yield i().catch(e=>(vi.open({type:"error",content:n.t(e.message)}),[])),s={};for(const t of e)s[t.id]=C(C({},s[t.id]||{}),t);for(const t of e)t.parent_id&&(s[t.parent_id]||(s[t.parent_id]={}),s[t.parent_id].childrenIds=s[t.parent_id].childrenIds?[...s[t.parent_id].childrenIds,t.id]:[t.id],s[t.parent_id].childrenIds.sort((e,t)=>s[t].updated_at-s[e].updated_at));t(s)})}},Eg=e=>{const t=new URLSearchParams(e||"");return{icon:t.get("icon")||"",style:t.get("style")||""}},Ng=({styleTop:e=0,styleLeft:t=0,isAdd:n=!1,chatId:s="",projectId:i,onClose:a=()=>{}})=>{const{i18n:o}=ye(),r=Ue(),{getNewProjectList:l,getProjectChatList:c}=ig(),{getChatListData:d,initFolders:u,getPinnedChatListData:h}=Tg(),m=cR(e=>e.mobile),p=pw(e=>e.projectArr),g=Ns(e=>e.setChats),f=Ns(e=>e.setPinnedChats),v=pw(e=>e.setOperationProject),y=pw(e=>e.setProjectSettingOpen),b=pw(e=>e.setOperationProjectFiles),x=pw(e=>e.setShowEditModal),w=pw(e=>e.setMoveNewProjectId),_=pw(e=>e.setProjectExpandChats),C=pw(e=>e.activeProjectId),S=pw(e=>e.setProjectChats),k=ud(e=>e.setActiveChatMenuId),[j,T]=D.useState(null),E=p.length>=20;return D.useEffect(()=>{if(!n){if(document.querySelector(".project-panel-container")){let n={top:e,left:t};e+308>window.innerHeight&&(n={top:window.innerHeight-414,left:t}),T(n)}}},[n,e,t]),F.jsx("div",{className:"project-panel",style:n?{}:{position:"fixed",top:`${null==j?void 0:j.top}px`,left:`${null==j?void 0:j.left}px`,display:(null==j?void 0:j.top)?"block":"none"},children:F.jsxs("div",{className:"project-panel-container "+(m?"project-panel-container-mobile":""),children:[n&&!E&&F.jsxs(ae.Item,{className:"project-panel-add "+(E?"project-panel-add-disabled":""),onClick:()=>{E||(v({}),y(!1),b([]),x(!0),w(s),a())},children:[F.jsx(pi,{type:"icon-line-folder-plus",className:"project-panel-add-icon"}),F.jsx("div",{className:"project-panel-add-text",children:o.t("New Project")})]},"project-panel-add"),F.jsx("div",{className:"project-panel-list",children:p.slice(n?0:5,p.length).filter(e=>!i||e.id!==i).map(e=>{const t=Eg(e.icon);return F.jsxs("div",{className:"project-panel-item",onClick:()=>A(null,null,function*(){if(s){const t=yield uw(e.id,[s]).catch(e=>(vi.open({type:"error",content:o.t(e.message)}),null));if(t&&t.success){k(null);const t=yield d(1);if(g(t),l(),!m){const e=yield h();Array.isArray(e)&&f(e)}if(yield u(),C){const e=yield c(String(C));Array.isArray(e)&&_(e)}const n=yield c(String(e.id));Array.isArray(n)&&S(n),r(`/p/${e.id}`),a()}else"Not_Found"===(null==t?void 0:t.data.code)&&(l(),a())}else r(`/p/${e.id}`)}),children:[e.icon?t.icon.includes("icon-")?F.jsx(pi,{type:t.icon,className:`project-panel-item-icon ${t.style}`}):F.jsx("div",{className:"project-panel-item-icon",children:pn[t.icon]}):F.jsx(pi,{type:"icon-line-folder-01",className:`project-panel-item-icon ${t.style}`}),F.jsx("div",{className:"project-panel-item-text",children:e.name})]},e.id)})})]})})},{saveAs:Ig}=Mr,Ag=({shareHandler:e=()=>{},cloneChatHandler:t=()=>{},archiveChatHandler:n=()=>{},renameHandler:s=()=>{},deleteHandler:i=()=>{},chatId:a,show:o,onClose:r=()=>{},children:l,onChange:c=()=>{},projectChat:d=!1,projectChatPined:u=!1,projectId:h,isMobileClickOpen:m=!1})=>{const p=ye(),g=Ue(),{getNewProjectList:f,getProjectChatList:v,extractProjectId:y}=ig(),{getChatListData:b}=Tg(),x=cR(e=>e.mobile),w=Ns(e=>e.pinnedChats),_=Rs(e=>e.taskRunning),C=Rs(e=>e.visionGenerating),S=ud(e=>e.setShowSidebar),k=pw(e=>e.activeProjectId),j=pw(e=>e.setProjectExpandChats),T=pw(e=>e.setProjectChats),E=Ns(e=>e.setChats),N=Ns(e=>e.setPinnedChats),I=js(e=>e.chatId),M=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_project}),[R,P]=D.useState(!1),[L,O]=D.useState(!1),q=D.useCallback(()=>A(null,null,function*(){pl("clkStickyChat",{params:{et:"CLK"},aesParams:{c4:a},paramsExtend:{chat_id:a}}),O(!0),yield yg(a).catch(e=>(vi.open({type:"error",content:p.t(e.message)}),null)),c(),O(!1)}),[a,p,c]),U=D.useCallback(e=>A(null,null,function*(){const t=e.chat.history;return _r(t.currentId,t).reduce((e,t)=>{if("assistant"===t.role){if(t.content_list&&Array.isArray(t.content_list)){const e=(e=>{var t,n,s;return(null==e?void 0:e.content_list)&&(null==(t=null==e?void 0:e.content_list)?void 0:t.length)?null==(s=null==(n=null==e?void 0:e.content_list)?void 0:n.filter(e=>(null==e?void 0:e.phase)===wt.ANSWER))?void 0:s.map(e=>e.content).join("\n"):""})(t);t.content=e.replace(/\[\[\d+\]\]/g,"")||""}else t.content=t.content.replace(/\[\[\d+\]\]/g,"")||"";t.content=t.content.replace(/\[\[\d+\]\]/g,"")}return`${e}### ${t.role.toUpperCase()}\n${t.content}\n\n`},"").trim()}),[]),H=D.useCallback((e="clkdownloadBtn")=>{pl(e,{params:{et:"CLK",c5:"chatList"},aesParams:{c4:a},paramsExtend:{chat_id:a}})},[a]),B=D.useCallback(()=>{r(),x&&S(!1)},[x,r,S]),z=D.useCallback(()=>A(null,null,function*(){try{const e=yield uw("",[a]).catch(e=>(vi.open({type:"error",content:p.t(e.message)}),null));if(null==e?void 0:e.success){f();const e=yield lg();e&&Array.isArray(e.data)&&N(e.data);const t=yield b(1);if(E(t),k){const e=yield v(String(k));Array.isArray(e)&&j(e)}if(location.pathname.includes("/p/")){const e=y(location.pathname);if(e){const t=yield v(String(e));Array.isArray(t)&&T(t)}}a===I&&g(`/p/${h}`,{replace:!0})}else"Not_Found"===(null==e?void 0:e.data.code)&&f()}catch(e){}}),[k,a,I,y,b,f,v,p,g,h,E,N,T,j]),G=D.useCallback(()=>{pl("clkShareBtn",{params:{et:"CLK",c5:"chatList"},aesParams:{c4:a},paramsExtend:{chat_id:a}}),e()},[e,a]),$=D.useCallback(()=>A(null,null,function*(){const e=yield dg({chat_id:a}),t=null==e?void 0:e.data;if(!t)return;H();const n=yield U(t),s=new Blob([n],{type:"text/plain;charset=utf-8"}),i=`chat-${t.title}.txt`;if(Qs())try{yield Pr(s,i)}catch(o){vi.open({type:"warning",content:o})}else Ig(s,i)}),[a,H,U]),W=D.useCallback(()=>A(null,null,function*(){var e,t;const n=yield dg({chat_id:a}),s=null==n?void 0:n.data;if(s){H();const n={};for(const a in s.chat.history.messages)(null==(e=s.chat.history.messages)?void 0:e.hasOwnProperty(a))&&(n[a]=je(s.chat.history.messages[a],["webSearchInfo","extra.web_search_info"]),"assistant"===n[a].role&&(null==(t=n[a])?void 0:t.content)&&(n[a].content=n[a].content.replace(/\[\[\d+\]\]/g,"")));s.chat.history.messages=n,s.chat.messages&&s.chat.messages.length&&(s.chat.messages=s.chat.messages.map(e=>{const t=je(e,["webSearchInfo","extra.web_search_info"]);return"assistant"===t.role&&(null==n?void 0:n.content)&&(t.content=t.content.replace(/\[\[\d+\]\]/g,"")),t}));const i=new Blob([JSON.stringify([s])],{type:"application/json;charset=utf-8"});Ig(i,`chat-export-${Date.now()}.json`)}}),[a,H]),V=D.useCallback(()=>F.jsx(ae,{mode:"inline",className:"chat-menu-content",id:"menu-content",children:x?F.jsxs(F.Fragment,{children:[F.jsxs(ae.Item,{className:"chat-menu-item",onClick:e=>{null==e||e.domEvent.stopPropagation(),null==e||e.domEvent.preventDefault(),s()},children:[p.t("Rename"),F.jsx(pi,{type:"icon-line-edit-contained",className:"chat-menu-item-icon-20"})]},"rename-mobile"),F.jsxs(ae.Item,{className:"chat-menu-item",disabled:_||C,onClick:e=>{null==e||e.domEvent.stopPropagation(),null==e||e.domEvent.preventDefault(),C||_||t()},children:[p.t("Clone"),F.jsx(pi,{type:"icon-line-clone-01",className:"chat-menu-item-icon-18"})]},"clone-mobile"),F.jsxs(ae.Item,{className:"chat-menu-item",onClick:t=>{null==t||t.domEvent.stopPropagation(),null==t||t.domEvent.preventDefault(),e()},children:[p.t("Share"),F.jsx(pi,{type:"icon-line-share-01",className:"chat-menu-item-icon-18"})]},"share-mobile"),F.jsx(ae.Divider,{className:"chat-menu-hr"}),M&&F.jsx(oe,{className:"chat-menu-submenu chat-menu-submenu-move",popupClassName:"chat-menu-submenu-project",title:p.t("Move to Project"),icon:F.jsx(pi,{type:"icon-line-folder-01"}),popupOffset:[-280,0],onClick:e=>{null==e||e.domEvent.stopPropagation(),null==e||e.domEvent.preventDefault()},children:F.jsx(Ng,{isAdd:!0,chatId:a,projectId:h,onClose:B})},"moveToProject"),d&&M&&F.jsxs(ae.Item,{className:"chat-menu-item ",onClick:e=>{null==e||e.domEvent.stopPropagation(),null==e||e.domEvent.preventDefault(),z()},children:[p.t("Move from Project"),F.jsx(pi,{type:"icon-line-arrow-curve-left-right"})]},"SwapProject"),F.jsx(ae.Divider,{className:"chat-menu-hr"}),F.jsxs(ae.Item,{className:"chat-menu-item chat-menu-delete-item",danger:!0,onClick:e=>{null==e||e.domEvent.stopPropagation(),null==e||e.domEvent.preventDefault(),i()},children:[p.t("Delete"),F.jsx(pi,{type:"icon-line-trash-01",className:"chat-menu-item-icon-18"})]},"delete-mobile")]}):F.jsxs(F.Fragment,{children:[F.jsx(ae.Item,{onClick:q,className:"chat-menu-item",children:L?F.jsx("div",{className:"chat-menu-item-pin-loading",children:F.jsx(Ui,{})}):R?F.jsxs(F.Fragment,{children:[F.jsx(pi,{type:"icon-line-unpin-01"}),F.jsx("span",{className:"chat-menu-item-icon-text",children:p.t("Unpin")})]}):F.jsxs(F.Fragment,{children:[F.jsx(pi,{type:"icon-line-pin-01"}),F.jsx("span",{className:"chat-menu-item-icon-text",children:p.t("Pin")})]})},"pin"),F.jsxs(ae.Item,{className:"chat-menu-item",onClick:s,children:[F.jsx(pi,{type:"icon-line-edit-contained"}),F.jsx("span",{className:"chat-menu-item-icon-text",children:p.t("Rename")})]},"rename"),F.jsxs(ae.Item,{className:"chat-menu-item "+(_?"chat-menu-item-task-running":""),disabled:_||C,onClick:()=>{C||_||t()},children:[F.jsx(pi,{type:"icon-line-clone-01"}),F.jsx("span",{className:"chat-menu-item-icon-text",children:p.t("Clone")})]},"clone"),F.jsxs(ae.Item,{className:"chat-menu-item",onClick:n,children:[F.jsx(pi,{type:"icon-line-archive-02"}),F.jsx("span",{className:"chat-menu-item-icon-text",children:p.t("Archive")})]},"archive"),F.jsxs(ae.Item,{className:"chat-menu-item",onClick:G,children:[F.jsx(pi,{type:"icon-a-share20"}),F.jsx("span",{className:"chat-menu-item-icon-text",children:p.t("Share")})]},"share"),F.jsxs(oe,{className:"chat-menu-submenu",title:p.t("Download"),icon:F.jsx(pi,{type:"icon-line-download-02"}),children:[F.jsx(ae.Item,{className:"chat-menu-item",onClick:W,children:p.t("Export chat (.json)")},"json"),F.jsx(ae.Item,{className:"chat-menu-item",onClick:$,children:p.t("Plain text (.txt)")},"txt")]},"download"),M&&F.jsx(oe,{className:"chat-menu-submenu",popupClassName:"chat-menu-submenu-project",title:p.t("Move to Project"),icon:F.jsx(pi,{type:"icon-line-folder-01"}),children:F.jsx(Ng,{isAdd:!0,chatId:a,projectId:h,onClose:B})},"moveToProject"),d&&M&&F.jsxs(ae.Item,{className:"chat-menu-item",onClick:z,children:[F.jsx(pi,{type:"icon-line-arrow-curve-left-right"}),F.jsx("span",{className:"chat-menu-item-icon-text",children:p.t("Move from Project")})]},"SwapProject"),F.jsxs(ae.Item,{className:"chat-menu-item chat-menu-item-error",onClick:i,children:[F.jsx(pi,{type:"icon-line-trash-01"}),F.jsx("span",{className:"chat-menu-item-icon-text",children:p.t("Delete")})]},"delete")]})}),[x,q,L,R,p,s,_,C,n,G,W,$,a,h,B,d,z,i,c,t,e]);return D.useEffect(()=>{o&&P(u||w.find(e=>e.id===a))},[a,w,o,u]),D.useEffect(()=>{const e=document.getElementById("menu-content");if(!m&&e&&x){const t=t=>{if(o){(null==e?void 0:e.contains(t.target))||r()}};return document.addEventListener("click",t),()=>{document.removeEventListener("click",t)}}},[o,x,r]),F.jsx(Y,{open:o,onOpenChange:e=>{e||r()},trigger:m?["click"]:x?[]:["click"],popupRender:V,placement:"bottomLeft",children:F.jsx("div",{className:"chat-menu-trigger",children:l})})},Mg=D.memo(e=>{const{placeholder:t="",rows:n=1,maxLength:s=1e3,maxRows:i,isMcp:a=!1,showMaxLength:o=!0,autoFocus:r=!1,className:l="",minShowCount:c=0,onKeyDown:d}=e,[u,h]=D.useState(""),[m,p]=D.useState(n>1),g=D.useRef(null),f=D.useRef(null),v=D.useCallback(t=>{var n;h(t.target.value),null==(n=e.onChange)||n.call(e,t.target.value)},[e]),y=()=>{var e,t,s,i,a,o,r,l,c,d;if(!(null==(t=null==(e=g.current)?void 0:e.resizableTextArea)?void 0:t.textArea)||n>1)return;const u=null==(i=null==(s=g.current)?void 0:s.resizableTextArea)?void 0:i.textArea.getBoundingClientRect(),h=null==(a=f.current)?void 0:a.getBoundingClientRect(),m=null==(l=null==(r=null==(o=g.current)?void 0:o.resizableTextArea)?void 0:r.textArea)?void 0:l.value,v=document.createElement("span");v.style.font=window.getComputedStyle(null==(d=null==(c=g.current)?void 0:c.resizableTextArea)?void 0:d.textArea).font,v.style.visibility="hidden",v.style.position="absolute",v.textContent=m,document.body.appendChild(v);const y=v.offsetWidth;document.body.removeChild(v);const b=u.left+y,x=(null==h?void 0:h.left)||0;p(b>x)};return D.useEffect(()=>{var t;h(null!=(t=e.value)?t:"")},[e.value]),D.useEffect(()=>{setTimeout(()=>{y()},0)},[]),F.jsxs("div",{className:`comment-textarea ${l}`,children:[F.jsx(K.TextArea,{ref:g,rows:i?void 0:n,maxLength:s,placeholder:t,value:u,onChange:v,onInput:y,autoSize:!!i&&{maxRows:i||4},onKeyDown:d,autoFocus:r,className:""+(a?"comment-textarea-mcp":"")}),o&&c<=u.length&&F.jsx("div",{className:Q("comment-textarea-count",{"comment-textarea-count-position":!m,"comment-textarea-count-error":u.length>=s}),children:F.jsxs("div",{ref:f,children:[u.length,"/",s]})})]})}),Rg=({isShow:e})=>{const t=Ue(),n=ye(),s=ni(),i=Rs(e=>e.temporaryChatEnabled),a=js(e=>e.chatId),o=js(e=>e.projectId),[r,l]=D.useState(!1),c=ud(e=>e.setActiveChatMenuId),d=Ns(e=>e.setPinnedChats),u=Rs(e=>e.setTaskRunning),h=ud(e=>e.setShowSidebar),m=cR(e=>e.mobile),[p,g]=D.useState(""),[f,v]=D.useState(!1),y=D.useRef(null),b=js(e=>e.chatTitle),[x,w]=D.useState(!1),_=js(e=>e.setChatTitle),C=Ns(e=>e.chats),S=Ns(e=>e.pinnedChats),[k]=D.useState(!1),[j]=D.useState([]),T=pw(e=>e.setChatProjectId),[E,N]=D.useState(!1),{getPinnedChatListData:I}=Tg(),M=D.useCallback(()=>A(null,null,function*(){Jr(),Yr();const e=yield I();Array.isArray(e)&&d(e)}),[I,d]),R=D.useCallback(()=>{N(!1)},[]),P=D.useCallback(()=>A(null,null,function*(){m&&h(!1),bM.openNewChat(),T("")}),[m,T,h]),L=D.useCallback(e=>A(null,null,function*(){const s=yield bg(e).catch(e=>(vi.open({type:"error",content:n.t(e.message)}),null));if(null==s?void 0:s.success){bM.shareHistory=null,t(`/c/${s.data.id}`),yield Yr();const e=yield lg();e&&Array.isArray(e.data)&&d(e.data),Jr()}else vi.open({type:"error",content:n.t(null==s?void 0:s.data.message)})}),[n,t,d]),O=D.useCallback(e=>A(null,null,function*(){(yield fg(e).catch(e=>{vi.open({type:"error",content:n.t(e.message)})}))&&a===e&&(u(!1),M(),o?t(`/p/${o}`,{replace:!0}):yield P())}),[a,o,P,n,t,M,u]),q=D.useCallback(()=>A(null,null,function*(){var e;c(null),g(b||""),v(!0),null==(e=y.current)||e.focus()}),[c,b]),U=D.useCallback(e=>A(null,null,function*(){w(!1),e===a&&u(!1);(yield vg(e).catch(e=>(vi.open({type:"error",content:n.t(e.message)}),null)))&&(M(),a===e&&o?t(`/p/${o}`,{replace:!0}):P())}),[a,o,C,P,n,t,M,S,u]),H=D.useMemo(()=>F.jsxs(wi,{visible:x,title:n.t("Delete chat"),className:"chat-item-delete-confirm",closable:!1,headerBorderNone:!0,maskClosable:!0,onCancel:()=>w(!1),size:"small",actions:[{text:n.t("Cancel"),type:"tertiary",size:"large",rounded:"circle",onClick:()=>{w(!1)}},{text:n.t("Delete"),type:"dangerprimary",size:"large",rounded:"circle",onClick:()=>{U(a)}}],children:[!(k||!j.length)&&F.jsxs(F.Fragment,{children:[n.t("The chat contains the following deployed content. Once the chat is deleted, the associated links will no longer be accessible. Please confirm to proceed."),F.jsx("div",{className:"deploy-url-container",children:j.map(e=>F.jsx("div",{className:"deploy-url-item",children:e},e))})]}),!k&&n.t("This action will permanently delete all the chats you've created and cannot be undone. Please confirm to proceed.")]}),[U,k,j,n,a,x]),B=D.useMemo(()=>!(!o||""===o),[o]),z=D.useMemo(()=>F.jsx(Ag,{show:r,chatId:a,projectChat:B,projectId:o,cloneChatHandler:()=>{c(null),L(a),pl("clkCloneChat",{params:{et:"CLK"},aesParams:{c4:a},paramsExtend:{chat_id:a}})},shareHandler:()=>{c(null),N(!0)},archiveChatHandler:()=>{O(a)},renameHandler:q,deleteHandler:()=>{c(null),w(!0)},onClose:()=>{l(!1)},onChange:M,children:null,isMobileClickOpen:m,tagsDropdownOffsetAuto:!0}),[r,a,B,o,q,M,m,c,L,O]),G=D.useCallback((e,t)=>A(null,null,function*(){if(0!==t.trim().length)if(""===t)vi.open({type:"error",content:n.t("Title cannot be an empty string.")});else{if(!(yield ug({chat_id:e,chat:{title:t}}).catch(e=>{vi.open({type:"error",content:n.t(e.message)})})).success)return void _(b||"");e===a&&_(t),M()}else _(b||"")}),[a,n,M,b,_]),$=D.useMemo(()=>F.jsx(wi,{visible:f,className:"qwen-chat-comp-item-rename-modal",title:n.t("Rename Chat"),headerBorderNone:!0,closable:!m,size:"small",cancelText:n.t("Cancel"),onCancel:()=>{v(!1),g("")},okText:n.t("Confirm"),actions:[{text:n.t("Cancel"),type:"tertiary",rounded:"circle",onClick:()=>{v(!1),g("")}},{text:n.t("Confirm"),rounded:"circle",disabled:!p.trim(),onClick:()=>A(null,null,function*(){yield G(a,p),M(),v(!1)})}],children:F.jsx("div",{className:"rename-confirm",children:F.jsx("div",{className:"rename-confirm-content",children:F.jsx(Mg,{showMaxLength:!1,value:p,onChange:g,maxLength:100,maxRows:4,placeholder:n.t("Enter your message"),autoFocus:!0})})})}),[G,n,a,m,M,p,f]);return!e&&s||wR()||!a||!a&&!i||i?null:F.jsxs("div",{className:"chat-extension-modal",children:[F.jsxs(ie,{className:"chat-extension-modal-icon",align:"center",justify:"center",onClick:()=>{r||l(!r)},children:[F.jsx(pi,{type:"icon-line-more-01"}),z]}),$,H,F.jsx(sg,{show:E,chatId:a,onClose:R})]})},Pg=({center:e=!1})=>{const t=ye(),n=cR(e=>e.mobile),s=Fd(e=>e.paymentReminderNotification),i=Fd(e=>e.fetchPaymentUserNotifications),[a,o]=D.useState({visible:!1,icon:"icon-line-star-02",text:"",onClose:void 0}),r=D.useCallback(()=>A(null,null,function*(){if(null==s?void 0:s.type)try{const{data:{code:e}}=yield sR([null==s?void 0:s.type]);e||i()}catch(e){}}),[i,null==s?void 0:s.type]);return D.useEffect(()=>{s&&!a.visible?o({visible:Boolean(s),icon:"icon-line-star-02",text:t.t(n?"{{number}} days":"Your Plus subscription will end in {{number}} days. Renew soon!",{number:qe(1e3*Number(s.detail.subscription_expired_at)).diff(qe(),"days")+1}),onClose:r}):!s&&a.visible&&o({visible:!1,icon:"icon-line-star-02",text:"",onClose:void 0})},[t,n,r,s,a.visible]),a.visible&&F.jsxs("div",{className:Q("qwen-chat-nav-bar-warning-info",{"qwen-chat-nav-bar-warning-info-center":e}),children:[F.jsx(pi,{type:a.icon,className:"qwen-chat-nav-bar-warning-info-icon"}),F.jsx("div",{className:"qwen-chat-nav-bar-warning-info-text",children:a.text}),a.onClose&&F.jsx("div",{className:"qwen-chat-nav-bar-warning-info-close",onClick:a.onClose,children:F.jsx(pi,{type:"icon-line-x-02",className:"qwen-chat-nav-bar-warning-info-icon"})})]})},Lg=()=>{const e=ye(),t=D.useRef(null),n=dR(e=>e.mobile),s=Rs(e=>e.temporaryChatEnabled);return D.useEffect(()=>{t.current&&(t.current.style.opacity="1",t.current.style.cursor="pointer")},[]),F.jsx(Si,{title:e.t("Temporary Chat"),show:!n,placement:"bottomLeft",children:F.jsxs("div",{className:Q("temporary-chat-entry",{"temporary-chat-entry-out":s&&!n}),ref:t,onClick:()=>A(null,null,function*(){yield bM.updateTemporaryChat(!s)}),style:{opacity:.4,cursor:"not-allowed"},children:[F.jsx(pi,{type:s?"icon-line-privateon-chat-01":"icon-line-private-chat-01",className:s&&!n?"temporary-chat-entry-out-icon":"temporary-chat-entry-icon"}),s&&!n&&F.jsxs(F.Fragment,{children:[F.jsx("span",{className:"temporary-chat-entry-text",children:e.t("Temporary Chat")}),F.jsx(pi,{type:"icon-line-x-02",className:"temporary-chat-entry-out-close"})]})]})})},Og=({show:e,onClose:t=()=>{},editHandler:n=()=>{},deleteHandler:s=()=>{}})=>{const{i18n:i}=ye(),a=cR(e=>e.mobile);return D.useEffect(()=>{const n=document.getElementById("menu-content");if(n&&a){const s=s=>{if(e){(null==n?void 0:n.contains(s.target))||t()}};return document.addEventListener("click",s),()=>{document.removeEventListener("click",s)}}},[e,a,t]),F.jsx(Y,{open:e,onOpenChange:e=>{e||t()},trigger:["click"],popupRender:()=>F.jsxs(ae,{mode:"inline",className:"project-operation-menu-content",children:[F.jsxs(ae.Item,{className:"project-operation-menu-item",onClick:n,children:[F.jsx(pi,{type:"icon-line-edit-contained",className:"project-operation-menu-item-icon"}),F.jsx("div",{className:"project-operation-menu-item-text",children:i.t("Edit Project")})]},"edit"),F.jsxs(ae.Item,{className:"project-operation-menu-item project-item-delete",onClick:s,children:[F.jsx(pi,{type:"icon-line-trash-01",className:"project-operation-menu-item-icon"}),F.jsx("div",{className:"project-operation-menu-item-text",children:i.t("Delete Project")})]},"delete")]}),placement:"bottomLeft",children:F.jsx("div",{className:"project-operation-menu-trigger"})})},Dg=()=>{const{getProjectFilesList:e}=ig(),[t,n]=O.useState(!1),s=pw(e=>e.setShowEditModal),i=pw(e=>e.projectInfo),a=pw(e=>e.setOperationProject),o=pw(e=>e.setShowDeleteConfirm),r=ud(e=>e.setActiveChatMenuId),l=ud(e=>e.activeChatMenuId),c=D.useCallback(()=>A(null,null,function*(){n(!1),(yield e(i.id))&&(yield a(JSON.parse(JSON.stringify(i))),s(!0))}),[e,i,a,s]),d=D.useCallback(()=>{n(!1),a(JSON.parse(JSON.stringify(i))),o(!0)},[i,a,o]);return F.jsxs("div",{className:"herder-project-edit-btn",children:[F.jsx("div",{onClick:e=>{e.stopPropagation(),n(!0),l&&r("")},children:F.jsx(pi,{type:"icon-line-more-01",className:"chat-item-drag-web-default-btn-icon"})}),t&&F.jsx(Og,{show:t,onClose:()=>{n(!1)},editHandler:c,deleteHandler:d})]})},Fg=()=>{const{pathname:e}=ze(),t=Ue(),n=Ld(hp(e=>e.user)),s=Ts(e=>e.projectId),i=D.useMemo(()=>n&&e.includes("/p/")?F.jsx(Dg,{}):n&&s&&""!==s?F.jsx(Rg,{isShow:!0}):n?n&&"/"===e?F.jsx(Lg,{}):!n||s||e.includes("/p/")?null:F.jsx(Jp,{}):F.jsxs(F.Fragment,{children:[F.jsx(Jp,{}),F.jsx(vp,{rounded:"circle"})]}),[e,s,n]),a=D.useMemo(()=>n&&s&&""!==s?F.jsx(pi,{type:"icon-line-chevron-left",onClick:()=>{t(`/p/${s}`)},className:"header-left-project-back"}):n&&!s?F.jsx(Xp,{}):void 0,[t,s,n]);return F.jsx("header",{className:"header-mobile",children:F.jsxs("div",{className:"header-content",children:[F.jsxs("div",{className:"header-left",children:[a,F.jsx(Yp,{})]}),F.jsxs("div",{className:"header-right",children:[F.jsx(Pg,{}),i]})]})})},qg=D.memo(()=>{const e=Ue(),t=js(e=>e.projectId),n=pw(e=>e.projectIcon),s=pw(e=>e.projectName),i=pw(e=>e.setProjectIcon),a=pw(e=>e.setProjectName),o=n?Eg(n):{icon:"icon-line-folder-01",style:""};return D.useEffect(()=>{var e;t&&(e=t,A(null,null,function*(){const t=yield hw(e);t&&t.success&&(a(t.data.name),i(t.data.icon))}))},[t,i,a]),F.jsxs(F.Fragment,{children:[t&&""!==t&&F.jsxs("div",{className:"herder-project",onClick:()=>{e(`/p/${t}`)},children:[n?o.icon.includes("icon-")?F.jsx(pi,{type:o.icon,className:`herder-project-icon ${o.style}`}):F.jsx("div",{className:"herder-project-icon",children:o.icon}):F.jsx(pi,{type:"icon-line-folder-01",className:`herder-project-icon ${o.style}`}),F.jsx("div",{className:"project-name",children:s})]}),t&&""!==t&&F.jsx(pi,{type:"icon-line-Slash",className:"herder-project-piont"})]})}),Ug=D.memo(()=>{const e=pw(e=>e.projectInfo),t=pw(e=>e.setOperationProject),n=pw(e=>e.setShowEditModal),s=pw(e=>e.setShowDeleteConfirm),{getProjectFilesList:i}=ig(),[a,o]=D.useState(!1);return F.jsxs("div",{className:"herder-project-edit-btn",children:[F.jsx("div",{onClick:e=>{e.stopPropagation(),o(!0)},children:F.jsx(pi,{type:"icon-line-more-01",className:"chat-item-drag-web-default-btn-icon"})}),a&&F.jsx(Og,{show:a,onClose:()=>{o(!1)},editHandler:()=>A(null,null,function*(){yield o(!1),(yield i(e.id))&&(yield t(JSON.parse(JSON.stringify(e))),n(!0))}),deleteHandler:()=>{o(!1),t(JSON.parse(JSON.stringify(e))),s(!0)}})]})}),Hg=()=>{const{pathname:e}=ze(),t=Ld(hp(e=>e.user)),n=ud(e=>e.showHeaderBorder),s=Ps(e=>e.temporaryChatEnabled),i=D.useMemo(()=>t?"/"===e||s?F.jsx(Lg,{}):null:F.jsx(vp,{showRegister:!0,size:"small",rounded:"circle",buttonClass:"header-right-auth-button"}),[e,s,t]);return F.jsx("header",{className:Q("header-desktop",{"header-desktop-border":n&&"/"!==e}),children:F.jsxs("div",{className:"header-content",id:"qwen-chat-header-content",children:[F.jsxs("div",{className:"header-left",id:"qwen-chat-header-left",children:[F.jsx(qg,{}),!t&&F.jsx(Jp,{}),F.jsx(Yp,{})]}),F.jsx(Pg,{}),F.jsx("div",{className:"header-right",id:"qwen-chat-header-right",children:e.includes("/p/")?F.jsx(Ug,{}):F.jsxs(F.Fragment,{children:[F.jsx(Rg,{}),i]})})]})})},Bg=()=>{const e=dR(e=>e.mobile),{pathname:t}=ze();return e&&["/library"].some(e=>t.includes(e))?null:F.jsx(F.Fragment,{children:e?F.jsx(Fg,{}):F.jsx(Hg,{})})},zg=({searchValue:e="",list:t=[],unarchiveChatHandler:n=()=>{},onDelete:s=()=>{}})=>{const i=ye(),a=pw(e=>e.projectArr);return F.jsx("div",{className:"archive-container",children:t.filter(t=>""===e||t.title.toLowerCase().includes(e.toLowerCase())).map((e,t)=>{var o;const r=null==(o=a.find(t=>t.id===e.project_id))?void 0:o.name;return F.jsxs("div",{className:"archive-item",onClick:()=>{window.open(`${location.origin}/c/${e.id}`,"_blank")},children:[F.jsxs("div",{className:"archive-item-left",children:[F.jsx("div",{className:"archive-item-name",children:e.title}),F.jsx("div",{className:"archive-item-time",children:F.jsxs("div",{className:"archive-item-time",children:[r&&F.jsxs("div",{className:"archive-item-time-name-container",children:[F.jsx("div",{className:"archive-item-time-name",children:r||""}),F.jsx("div",{className:"archive-item-time-ponit",children:"·"})]}),F.jsx("div",{className:"archive-item-time-text",children:qe(1e3*e.created_at).format(i.t("MMMM DD, YYYY HH:mm"))})]})})]}),F.jsxs("div",{className:"archive-item-right",children:[F.jsx(Si,{title:i.t("Unarchive Chat"),children:F.jsx("div",{className:"archive-tbody-right-btn-unarchive",onClick:t=>{n(e.id),t.preventDefault(),t.stopPropagation()},children:F.jsx(pi,{type:"icon-line-unarchive-02",className:"archive-tbody-right-btn-icon"})})}),F.jsx(Si,{title:i.t("Delete Chat"),children:F.jsx("div",{className:"archive-tbody-right-btn",onClick:t=>{t.preventDefault(),t.stopPropagation(),s(e)},children:F.jsx(pi,{type:"icon-line-trash-01",className:"archive-tbody-right-btn-icon"})})})]})]},e.id)})})},Gg=({unarchiveHandler:e=()=>{}})=>{const[t,n]=D.useState([]),[s,i]=D.useState(""),[a,o]=D.useState(!1),[r,l]=D.useState(!1),[c,d]=D.useState(void 0),u=ye(),h=cR(e=>e.mobile),m=Rs(e=>e.showArchivedChats),p=Rs(e=>e.setShowArchivedChats),{extractProjectId:g}=ig(),f=pw(e=>e.activeProjectId),v=pw(e=>e.setProjectExpandChats),y=pw(e=>e.setProjectChats),b=D.useCallback(e=>A(null,null,function*(){const t=e.some(e=>e===f);let n=!1;if(location.pathname.includes("/p/")){const t=g(location.pathname);n=e.some(e=>e===t)}if(t)try{const e=yield dw(String(f),1);if(e&&Array.isArray(e.data)&&v(e.data),location.pathname.includes("/p/")){const t=g(location.pathname);if(t===f)e&&Array.isArray(e.data)&&y(e.data);else{const e=yield dw(String(t),1);e&&Array.isArray(e.data)&&y(e.data)}}}catch(s){}else if(n)try{const e=g(location.pathname),t=yield dw(String(e),1);t&&Array.isArray(t.data)&&y(t.data)}catch(s){}}),[f,g,y,v]),x=D.useCallback(s=>A(null,null,function*(){try{yield fg(s).catch(e=>{vi.open({type:"error",content:e})});const i=yield gg();i&&Array.isArray(i.data)&&n(i.data),e();const a=t.find(e=>e.id===s);a&&a.project_id&&b([a.project_id])}catch(i){}}),[b,t,e]),w=D.useCallback(()=>A(null,null,function*(){if(c)try{yield vg(c).catch(e=>{vi.open({type:"error",content:u.t(e.message)})}),d(void 0);const e=yield gg();l(!1),e&&Array.isArray(e.data)&&n(e.data)}catch(e){}}),[c,u]),_=D.useCallback(()=>A(null,null,function*(){try{const{saveAs:e}=Mr,t=yield A(null,null,function*(){return yield TM("/chats/all/archived")}).catch(e=>(vi.open({type:"error",content:u.t(e.message)}),null));e(new Blob([JSON.stringify(t)],{type:"application/json;charset=utf-8"}),`${u.t("archived-chat-export")}-${Date.now()}.json`)}catch(e){}}),[u]),C=D.useCallback(()=>A(null,null,function*(){try{for(const e of t)yield fg(e.id);b(t.map(e=>e.project_id||""));const s=yield gg();s&&Array.isArray(s.data)&&n(s.data),o(!1),e()}catch(s){}}),[b,t,e]),S=D.useCallback(()=>A(null,null,function*(){try{const e=yield gg();e&&Array.isArray(e.data)&&n(e.data)}catch(e){}}),[]);D.useEffect(()=>{m&&S()},[m]);const k=[{text:u.t("Cancel"),type:"tertiary",rounded:"circle",onClick:()=>{o(!1)}},{text:u.t("Confirm"),type:"brandprimary",rounded:"circle",onClick:()=>{C()}}],j=[{text:u.t("Cancel"),type:"tertiary",rounded:"circle",onClick:()=>{l(!1)}},{text:u.t("Confirm"),type:"dangerprimary",rounded:"circle",onClick:()=>{w()}}];return F.jsxs(F.Fragment,{children:[F.jsx(wi,{headerBorderNone:!0,size:"small",title:u.t("Confirm your action"),visible:a,actions:k,onCancel:()=>o(!1),children:u.t("Are you sure you want to unarchive all archived chats?")}),F.jsxs(wi,{visible:m,headerBorderNone:!0,footer:!1,className:"archived-chats",maskClosable:!0,size:"large",onCancel:()=>p(!1),title:u.t("Archived Chats"),children:[F.jsx("div",{children:F.jsxs("div",{className:"archived-chats-modal-content ",children:[F.jsx("div",{className:"archived-chats-modal-content-top ",children:F.jsx("div",{className:"archived-chats-modal-content-top-box ",children:F.jsx(_i,{className:"archived-chats-modal-content-top-input",value:s,noBorder:!0,clear:!0,setValue:e=>i(String(e)),prefixicon:"icon-line-search-01",placeholder:u.t("Search Chats"),clearIconSize:16})})}),F.jsx("div",{className:"archived-chats-modal-content-bottom",children:(null==t?void 0:t.filter(e=>""===s||e.title.toLowerCase().includes(s.toLowerCase())).length)>0?F.jsxs("div",{className:"archived-chats-modal-chats",children:[F.jsx("div",{className:"archived-chats-modal-chats-box",children:F.jsx("div",{className:"archived-chats-modal-chats-table",children:F.jsx(zg,{list:t,searchValue:s,unarchiveChatHandler:x,onDelete:e=>{l(!0),d(e.id)}})})}),F.jsxs("div",{className:"archived-chats-modal-chats-btn",children:[F.jsx(xi,{type:"tertiary",rounded:"circle",onClick:()=>{o(!0)},children:u.t("Unarchive All")}),!h&&F.jsx(xi,{type:"tertiary",rounded:"circle",onClick:()=>{_()},children:u.t("Export All")})]})]}):F.jsx("div",{className:"archived-chats-modal-not-chats",children:u.t("No archived tasks")})})]})}),F.jsx(wi,{headerBorderNone:!0,size:"small",visible:r,title:u.t("Delete Chat"),actions:j,onCancel:()=>l(!1),children:F.jsx("div",{className:"archived-delete-confirm-dialog",children:u.t("This operation will delete all conversation records under the directory. Please confirm to continue.")})})]})]})},$g=D.memo(()=>{const e=hd(e=>e.showSidebar),t=ud(e=>e.setShowSidebar),n=dR(e=>e.mobile),s=e=>{e&&e.style&&(e.style.opacity="1",e.style.cursor="pointer")};return n?null:F.jsxs("div",{className:Q("sidebar-header-wrapper",{"sidebar-header-wrapper-small-sidebar":!e}),children:[F.jsx("img",{crossOrigin:"anonymous",src:"https://img.alicdn.com/imgextra/i1/O1CN013ltlI61OTOnTStXfj_!!6000000001706-55-tps-330-327.svg",className:Q("logo-img",{"logo-img-hidden":!e}),alt:"logo"}),e?F.jsx("button",{id:ct.SIDEBAR_TOGGLE_BUTTON,className:"slide-switch",onClick:()=>{n||localStorage.setItem(ut,"true"),t(!e)},"aria-label":"切换侧边栏",children:F.jsx(pi,{type:"icon-line-sidePanel",className:"slide-switch-icon",style:{opacity:.4,cursor:"not-allowed"},ref:s})}):F.jsx("button",{className:"sidebar-side-fold-container-open",onClick:()=>{n||localStorage.setItem(ut,"false"),t(!0)},children:F.jsx(pi,{type:"icon-line-sidePanel",className:"sidebar-side-fold-container-open-icon",style:{opacity:.4,cursor:"not-allowed"},ref:s})})]})}),Wg=()=>{const e=cR(e=>e.mobile),t=ud(e=>e.theme);return e?F.jsx("img",{crossOrigin:"anonymous",src:`//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.2.67/static/share/${"dark"===t?"app-dark":"app"}.png`,style:{width:"100%"},alt:"logo"}):F.jsx("img",{crossOrigin:"anonymous",src:`//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.2.67/static/share/${"dark"===t?"web-dark":"web"}.png`,style:{width:320,height:460},alt:"logo"})},Vg=({type:e="",className:t=""})=>{const n=ud(e=>e.theme);return F.jsx("div",{className:`share-qr-code ${t}`,children:"ios"===e?F.jsx("img",{crossOrigin:"anonymous",src:`//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.2.67/static/share/${"dark"===n?"ios-dark":"ios"}.png`,alt:"logo"}):F.jsx("img",{crossOrigin:"anonymous",src:`//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.2.67/static/share/${"dark"===n?"android-dark":"android"}.png`,alt:"logo"})})},Qg=({show:e,onClose:t})=>{const n=ye();return F.jsx(wi,{visible:e,className:"get-app-modal",header:!1,footer:!1,children:F.jsxs("div",{className:"get-app-modal-main",children:[F.jsx("div",{className:"get-app-modal-close",style:{backgroundColor:Iu("rgba(0, 0, 0, 0.5)","rgba(255, 255, 255, 0.2)")},onClick:t,children:F.jsx(pi,{type:"icon-line-x-01",className:"get-app-modal-close-icon"})}),F.jsxs("div",{className:"get-app-modal-main-content",children:[F.jsxs("div",{className:"get-app-modal-main-content-box",style:{color:Iu("#2C2C36","#FAFAFC")},children:[F.jsxs("div",{className:"get-app-modal-header",children:[F.jsx("div",{className:"header-title",children:n.t("Download App")}),F.jsx("div",{className:"header-content",children:n.t("Designed for mobile devices, offering better experience and more features")})]}),F.jsxs("div",{className:"get-app-modal-footer",children:[F.jsxs("div",{className:"footer-top",children:[F.jsx(Vg,{type:"ios",className:"footer-top-code"}),F.jsxs("div",{className:"footer-top-content",onClick:()=>{window.open("https://apps.apple.com/app/id6743778442")},children:[n.t("Download for iOS"),F.jsx(pi,{type:"icon-line-arrow-down-right-sm",className:"footer-top-content-icon"})]})]}),F.jsxs("div",{className:"footer-top",children:[F.jsx(Vg,{type:"android",className:"footer-top-code"}),F.jsxs("div",{className:"footer-top-content",onClick:()=>{window.open("https://play.google.com/store/apps/details?id=ai.qwenlm.chat.android")},children:[n.t("Download for Android"),F.jsx(pi,{type:"icon-line-arrow-down-right-sm",className:"footer-top-content-icon"})]})]})]})]}),F.jsx("div",{className:"get-app-modal-main-content-view",children:F.jsx(Wg,{})})]})]})})},Kg="setting",Yg="email",Jg="subscription",Xg="archive",Zg="download",ef="logout",tf=({icon:e,text:t,warningType:n,type:s})=>F.jsxs(ie,{className:"user-menu-dropdown-item",gap:8,children:[e&&F.jsx(pi,{className:"user-menu-dropdown-item-icon "+("email"===s?"setting-panel-email-icon":""),type:e}),F.jsx("div",{className:"user-menu-dropdown-item-text",children:t}),n&&F.jsx(pi,{className:`user-menu-dropdown-item-icon-${n}`,type:"icon-line-alert-circle"})]}),nf=({children:e,placement:t})=>{const{i18n:n}=ye(),s=ud(e=>e.setUserMenuDropdownOpen),i=Ue(),a=Pd(e=>e.setUser),o=Pd(e=>e.user),r=ud(e=>e.setShowSidebar),l=Fd(e=>e.subscriptionPlus),c=Fd(e=>e.setShowSubscriptionDetail),{isShowGetTheApp:d,setShowArchivedChats:u,setTaskRunning:h}=Rs(hp(e=>({isShowGetTheApp:e.isShowGetTheApp,setShowArchivedChats:e.setShowArchivedChats,setTaskRunning:e.setTaskRunning}))),m=cR(e=>{var t,n;return null==(n=null==(t=e.config)?void 0:t.features)?void 0:n.enable_app_download}),p=cR(e=>e.mobile),g=cR(e=>{var t,n,s,i;return(null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_payment)&&(null==(i=null==(s=null==e?void 0:e.config)?void 0:s.features)?void 0:i.enable_payment_and_quota)}),[f,v]=D.useState(!1),y=Fd(e=>e.paymentExpiredNotification),b=Fd(e=>e.paymentIssueNotification),x=hR(e=>e.setEntrySettingsRouter),w=D.useMemo(()=>{const e=m&&!p&&d;return[{label:F.jsx(tf,{icon:"icon-line-user-profile-circle",type:"email",text:F.jsx("span",{className:"setting-panel-email",children:null==o?void 0:o.email}),warningType:y?"warning":b?"caution":void 0}),key:Yg,disabled:!0,className:"setting-panel-email-menu"},{label:F.jsx(tf,{icon:"icon-line-settings",text:n.t("Settings"),warningType:y?"warning":b?"caution":void 0}),key:Kg},g&&!l?{label:F.jsx(tf,{icon:"icon-line-star-02",text:n.t("Upgrade Plan")}),key:Jg}:null,p?null:{label:F.jsx(tf,{icon:"icon-line-archive-02",text:n.t("Archived Chats")}),key:Xg},e?{type:"divider"}:null,e?{label:F.jsx(tf,{icon:"icon-line-app-download-01",text:n.t("Download the App")}),key:Zg}:null,{type:"divider"},{label:F.jsx(tf,{icon:"icon-line-logout-03",text:n.t("Log out")}),key:ef}]},[g,m,n.language,p,d,y,b,l]);return F.jsxs(F.Fragment,{children:[F.jsx(Ci,{placement:t,overlayClassName:"user-menu-dropdown",menu:{items:w,onClick:e=>A(null,[e],function*({key:e}){switch(e){case Kg:(location.pathname.includes("/p/")||location.pathname.includes("/community"))&&x(location.pathname),i("/settings/general"),p&&r(!1);break;case Jg:return void c(!0);case Xg:u(!0),p&&r(!1);break;case Zg:v(!0);break;case ef:h(!1),yield Nd(),vR("token"),vR("settings"),Mh.destroy(),sessionStorage.removeItem("Auth_Source"),Js()&&bM.adapter.clearCookie(pt.SETAPP),a(),i(location.pathname.includes("/community")?"/community":"/",{replace:!0}),xM.reset()}})},onOpenChange:e=>{null==s||s(e)},children:e}),F.jsx(Qg,{show:f,onClose:()=>{v(!1)}})]})},sf="//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.2.67/static/user.png",af=e=>{if(!e)return;if("undefined"==typeof ImageData)return sf;const t=document.createElement("canvas"),n=t.getContext("2d");if(t.width=100,t.height=100,!(()=>{if("undefined"==typeof ImageData)return!1;const e=document.createElement("canvas"),t=e.getContext("2d");e.height=1,e.width=1;const n=new ImageData(e.width,e.height),s=n.data;for(let a=0;a{if(!e||0===e.length)return"";const t=e.normalize("NFC");return Array.from(t)[0]||""})(null==e?void 0:e.trim());n.fillText(s.toUpperCase(),t.width/2,t.height/2)}return t.toDataURL()},of=D.memo(()=>{const e=ye(),t=Ue(),n=Ld(e=>e.user),s=hd(e=>e.showSidebar),i=hd(e=>e.userMenuDropdownOpen),a=ud(e=>e.setShowSidebar),o=ud(e=>e.setShowSettings),r=dR(e=>e.mobile),l=dR(e=>e.pad),c=Fd(e=>e.subscriptionPlus),d=hR(e=>e.setEntrySettingsRouter),u=cR(e=>{var t,n,s,i;return(null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_payment)&&(null==(i=null==(s=null==e?void 0:e.config)?void 0:s.features)?void 0:i.enable_payment_and_quota)}),h=Fd(e=>e.setShowSubscriptionDetail);return F.jsx("div",{className:Q({"sidebar-user":s,"sidebar-user sidebar-user-collapse":!s,"sidebar-user-small":!s}),children:F.jsxs("div",{className:"user-content",children:[void 0!==n&&!r&&F.jsx(nf,{placement:"topLeft",children:F.jsxs("div",{className:"user-menu-container",children:[F.jsx("button",{className:"user-menu-btn",style:{opacity:.4,cursor:"not-allowed"},ref:e=>{e&&e.style&&(e.style.opacity="1",e.style.cursor="pointer")},children:F.jsxs("div",{className:"user-menu-btn-content",children:[F.jsxs("div",{className:Q("user-menu-btn-content-left",{"plus-user":c}),children:[F.jsx("div",{id:`${Kp}_account`}),F.jsx("img",{src:(null==n?void 0:n.profile_image_url)||af((null==n?void 0:n.name)||""),className:"user-img",alt:"User profile"}),c&&F.jsx("div",{className:"plus-user-sign",children:F.jsx("div",{className:"plus-user-sign-text",children:"Plus"})})]}),l?F.jsx("div",{className:"user-menu-btn-text-pad",children:n.name}):i?F.jsx("div",{className:"user-menu-btn-text",children:n.name}):F.jsx(Si,{className:"user-menu-btn-content-right",title:n.name,placement:"top",children:F.jsx("div",{className:"user-menu-btn-text",children:n.name})})]})}),u&&!c&&s&&F.jsx(xi,{type:"ghost",onClick:e=>{e.stopPropagation(),h(!0)},size:"small",rounded:"circle",className:"sidebar-user-upgrade-plan-button",children:e.t("Upgrade")})]})}),r&&F.jsxs("button",{className:"user-menu-btn-mobile",onClick:()=>A(null,null,function*(){o(!0),r&&((location.pathname.includes("/p/")||location.pathname.includes("/community"))&&d(location.pathname),a(!1),t("/settings"))}),children:[F.jsxs("div",{className:"user-menu-btn-content",children:[F.jsxs("div",{className:Q("user-menu-btn-content-left",{"mobile-plus-user":c}),children:[F.jsx("div",{id:`${Kp}_account`}),F.jsx("img",{src:(null==n?void 0:n.profile_image_url)||af((null==n?void 0:n.name)||""),className:"user-img",alt:"User profile"}),c&&F.jsx("div",{className:"mobile-plus-user-sign",children:F.jsx("div",{className:"mobile-plus-user-sign-text",children:"Plus"})})]}),r||l?F.jsx("div",{className:"user-menu-btn-text-pad",children:null==n?void 0:n.name}):F.jsx("div",{className:"user-menu-btn-content-right",children:F.jsx(Si,{className:"user-menu-btn-content-right",title:i?"":null==n?void 0:n.name,placement:"top",children:F.jsx("div",{className:"user-menu-btn-text",children:null==n?void 0:n.name})})})]}),r&&F.jsx("div",{children:F.jsx(pi,{type:"icon-line-chevron-right",className:"user-menu-btn-icon"})})]})]})})}),rf=({open:e,className:t,buttonClassName:n,title:s,grow:i,disabled:a,hide:o,children:r,contentChildren:l,onChange:c})=>{const[d,u]=D.useState(e);D.useEffect(()=>{u(e)},[e]);const h=()=>{a||(u(e=>!e),c(!d))};return F.jsxs("div",{className:t,children:[s?F.jsx("div",{className:`${n}`,onClick:h,children:F.jsx("div",{className:"collapsible-header",children:F.jsx("div",{children:s})})}):F.jsx("div",{className:`${n}`,onClick:h,children:F.jsxs("div",{children:[r,i&&d&&!o&&F.jsx("div",{children:l})]})}),!i&&d&&!o&&F.jsx("div",{children:l})]})},lf=({id:e="",name:t,collapsible:n=!0,defaultOpen:s=!0,className:i,onChange:a=()=>{},onDrop:o=()=>{},children:r,folders:l})=>{const[c,d]=D.useState(s),{mobile:u}=cR(),h=Rs(e=>e.temporaryChatEnabled),[{isOver:m},p]=Ke(()=>({accept:"pinned"===e?["chat"]:["chat","folder"],drop:t=>{a(!0),d(!0);const n=l&&l[t.id];o(S(C({},t),{parent_id:null==n?void 0:n.parent_id}),e)},collect:e=>({isOver:!!e.isOver()})}),[l]);return F.jsx("div",{ref:p,className:`${i}`,children:n?F.jsx(rf,{open:!!c,disabled:h,className:"collapsible-full",buttonClassName:"collapsible-full",onChange:e=>a(e),contentChildren:F.jsx("div",{className:"folder-content",children:r}),children:!u&&F.jsx("div",{className:"collapsible-full",children:F.jsxs("div",{className:Q("folder-button",{"folder-button-disabled":h}),onClick:()=>!h&&d(!c),children:[F.jsx("div",{className:"folder-name",children:t}),F.jsx("div",{className:"folder-button-icon-container",children:c?F.jsx(pi,{type:"icon-line-chevron-down",className:"folder-button-icon-container-icon"}):F.jsx(pi,{type:"icon-line-chevron-up",className:"folder-button-icon-container-icon"})})]})})}):F.jsx("div",{className:"folder-content",children:r})})};function cf(e){const{id:t,pinned:n,title:s,folders:i,selected:a=!1,onEditChatChange:o=()=>{},onChange:r=()=>{},onSelect:l=()=>{},onUnSelect:c=()=>{},isProjectDetailChat:d=!1,projectDetailChat:u=null,projectChatPined:h,projectChat:m=!1,projectId:p,chatStatus:g="normal"}=e,f=ye(),v=Ue(),[y,b]=D.useState(!1),[x,w]=D.useState(!1),[_,C]=D.useState(!1),[S,k]=D.useState(!1),[j,T]=D.useState(s||""),[E,N]=D.useState(""),[I,M]=D.useState([]),[R,P]=D.useState(!1),L=D.useRef(null),O=D.useRef(0),F=D.useRef(0),q=D.useRef(null),U=pw(e=>e.setActiveChatDetails),H=ud(e=>e.activeChatMenuId),B=ud(e=>e.setActiveChatMenuId),z=pw(e=>e.setActiveProjectId),G=cR(e=>e.mobile),$=js(e=>e.chatId),W=js(e=>e.setChatTitle),V=Ns(e=>e.chats),Q=Ns(e=>e.pinnedChats),K=Ns(e=>e.setPinnedChats),Y=ud(e=>e.setShowSidebar),J=Rs(e=>e.setTaskRunning),X=Rs(e=>e.setTemporaryChatEnabled),Z=Rs(e=>e.temporaryChatEnabled),[{isDragging:ee},te]=Ye(()=>({type:"chat",item:{id:t,type:"chat"},collect:e=>({isDragging:!!e.isDragging()})})),ne=D.useMemo(()=>G?H===t:d?H===`${t}_project_detail_chat`:H===t,[H,d,t,G]),se=D.useCallback((t,n)=>A(null,null,function*(){if(0!==n.trim().length)if(""===n)vi.open({type:"error",content:f.t("Title cannot be an empty string.")});else{if(!(yield ug({chat_id:t,chat:{title:n}}).catch(e=>{vi.open({type:"error",content:f.t(e.message)})})).success)return void T(e.title||"");t===$&&W(n),r()}else T(e.title||"")}),[$,f,r,e.title,W]),ie=D.useCallback(e=>A(null,null,function*(){const t=yield bg(e).catch(e=>(vi.open({type:"error",content:f.t(e.message)}),null));if(null==t?void 0:t.success){bM.shareHistory=null,v(`/c/${t.data.id}`),yield Yr();const e=yield lg();e&&Array.isArray(e.data)&&K(e.data),Jr()}else vi.open({type:"error",content:f.t(null==t?void 0:t.data.message)})}),[f,v,K]),ae=D.useCallback(()=>A(null,null,function*(){G&&Y(!1),bM.openNewChat()}),[G,Y]),oe=D.useCallback(e=>A(null,null,function*(){var t,n,s;C(!1),e===$&&J(!1);const a=yield vg(e).catch(e=>(vi.open({type:"error",content:f.t(e.message)}),null)),o=1===(null==(t=null==V?void 0:V.filter(e=>e.id===$))?void 0:t.length),l=1===(null==(n=null==Q?void 0:Q.filter(e=>e.id===$))?void 0:n.length),c=function(e){let t=[];if(e)for(const n in e)e[n].items&&Array.isArray(e[n].items.chats)&&(t=t.concat(e[n].items.chats));return t}(i),u=1===(null==(s=null==c?void 0:c.filter(e=>e.id===$))?void 0:s.length);a&&($!==e&&(o||u||l)||d||($===e&&p?v(`/p/${p}`,{replace:!0}):yield ae()),r())}),[$,V,i,ae,f,d,v,r,Q,p,J]),re=D.useCallback(e=>A(null,null,function*(){(yield fg(e).catch(e=>{vi.open({type:"error",content:f.t(e.message)})}))&&($===e&&(J(!1),p?v(`/p/${p}`,{replace:!0}):yield ae()),r())}),[$,ae,f,v,r,p,J]),le=D.useCallback(()=>{t!==$&&(J(!1),l(),bM.closeShowControls(),G&&(Y(!1),B(null)),yM.reset(["inputValue","files"]),bM.shareHistory=null,d&&U(u),c(),v(`/c/${t}`))},[t,$,J,l,G,d,c,v,Y,B,U,u]),ce=D.useCallback(()=>A(null,null,function*(){var e;B(null),N(s||""),w(!0),null==(e=L.current)||e.focus()}),[B,s]),de=D.useCallback(e=>A(null,null,function*(){const t=yield(n=e,A(null,null,function*(){return yield TM("/share/artifacts/query",{method:"POST",data:{chat_id:n}})}));var n;k(!1),t&&M(t.data.share_list.map(e=>e.share_url))}),[]);return D.useEffect(()=>{_&&de(t)},[_,de,t]),{id:t,pinned:n,title:s,folders:i,selected:a,onEditChatChange:o,onChange:r,onSelect:l,onUnSelect:c,isProjectDetailChat:d,projectDetailChat:u,projectChatPined:h,projectChat:m,projectId:p,chatStatus:g,showShareChatModal:y,setShowShareChatModal:b,showRenameConfirm:x,setShowRenameConfirm:w,showDeleteConfirm:_,setShowDeleteConfirm:C,deleteLoading:S,chatTitle:j,renameChatTitle:E,setRenameChatTitle:N,deployUrlList:I,isOver:R,setIsOver:P,mobile:G,chatId:$,temporaryChatEnabled:Z,showOperationMenu:ne,isDragging:ee,drag:te,editChatTitle:se,cloneChatHandler:ie,deleteChatHandler:oe,archiveChatHandler:re,gotoNewChat:le,handleTouchStart:e=>{if(!G)return;e.stopPropagation(),e.preventDefault();const n=e.touches[0];O.current=n.clientX,F.current=n.clientY,clearTimeout(q.current),q.current=setTimeout(()=>{B(ne?null:t),z(null)},500)},handleTouchEnd:()=>{G&&clearTimeout(q.current)},handleDoubleClick:()=>{G||(N(s||""),null==o||o(t),w(!0))},exitTemporaryChat:()=>{X(!1),le()},showRenameConfirmHandler:ce,setActiveChatMenuId:B,i18n:f}}const df=({chatStatus:e,id:t,chatId:n,isOver:s,pinned:i,selected:a})=>"end"!==e||t===n||s?"processing"!==e||t===n||s?!i||s||t===n||a?null:F.jsx(pi,{type:"icon-line-pin-01",className:"chat-item-title-pined-icon"}):F.jsx(Ui,{styles:{color:"#615CED",marginTop:"auto",marginBottom:"auto"},type:"primary",fontSize:10.5}):F.jsx("div",{className:"chat-item-title-end-icon"}),uf=D.memo(({id:e,chatId:t,title:n,time:s,pinned:i,selected:a,isProjectDetailChat:o,projectChatPined:r,chatStatus:l,mobile:c,temporaryChatEnabled:d,chatTitle:u,showOperationMenu:h,isOver:m,gotoNewChat:p,handleDoubleClick:g,handleTouchStart:f,handleTouchEnd:v,exitTemporaryChat:y})=>{const b=ye(),x=D.useCallback(()=>{vi.openOnce({type:"caution",content:F.jsxs("div",{className:"temporary-chat-close-toast-content",children:[b.t("You are now in temporary chat"),F.jsx("span",{onClick:y,children:b.t("Exit")})]}),className:"temporary-chat-close-toast"})},[y,b]);return o?F.jsxs(F.Fragment,{children:[d&&c&&F.jsx("div",{className:"chat-item-drag-main",onClick:x}),F.jsx("div",{className:"project-chat-item",onClick:p,onDoubleClick:g,onTouchStart:f,onTouchEnd:v,onTouchCancel:v,children:F.jsxs("div",{className:"project-chat-item-content",children:[F.jsxs("div",{className:"project-chat-item-content-top",children:[F.jsx("div",{className:"project-chat-item-title",children:n}),r&&F.jsx(pi,{type:"icon-line-pin-01",className:"project-chat-item-title-pined-icon"})]}),F.jsx("div",{className:"project-chat-item-time",children:s})]})})]}):F.jsxs(F.Fragment,{children:[d&&c&&F.jsx("div",{className:"chat-item-drag-main",onClick:x}),F.jsx("a",{"aria-label":"chat-item",className:`chat-item-drag-link ${e===t&&location.pathname.includes("/c/")?"chat-item-drag-active":a&&location.pathname.includes("/c/")||d&&c?"chat-item-drag-selected "+(c?d?"chat-item-mobile-temporary":"chat-item-mobile-not-temporary":""):""} ${d?"chat-item-temporary":""} ${c?"chat-item-drag-link-mobile":""}\n `,onClick:p,onDoubleClick:g,onTouchStart:f,onTouchEnd:v,onTouchCancel:v,children:F.jsxs("div",{className:"chat-item-drag-link-content",children:[F.jsx(Si,{open:!d&&!c&&void 0,title:u,placement:"bottom",className:"chat-item-drag-link-content-tip",children:F.jsx("div",{className:"chat-item-drag-link-content-tip-text",style:h?{paddingRight:"16px"}:{},children:(w=u||"",_=100,w.length>_?w.slice(0,_-3)+"...":w)})}),F.jsx(df,{chatStatus:l,id:e,chatId:t,isOver:m,pinned:i,selected:a})]})})]});var w,_});var hf=(e=>(e.PDF="pdf",e.VIDEO="video",e.PODCAST="podcast",e.WEB_DEV="web_dev",e.IMAGE="image",e.ALL="all",e))(hf||{});const mf=new Map,pf=e=>A(null,null,function*(){const t=`${e.type||""}_${e.cursor||""}`;if(mf.has(t))return mf.get(t);const n=A(null,null,function*(){return yield Sl(),yield TM("/library/list",{method:"GET",params:e})});mf.set(t,n);try{return yield n}finally{mf.delete(t)}}),gf=()=>{const e=pR(e=>e.setSidebarLibraryList),t=ud(e=>e.realTheme),n=Pd(e=>e.user),s=D.useCallback(e=>(null==e?void 0:e.length)?e.map(e=>{const s=hf.ALL;let i=null==e?void 0:e.url,a=null==e?void 0:e.url,o="",r=null==e?void 0:e.name;return e.type===hf.PDF?(i="dark"===t?"https://img.alicdn.com/imgextra/i1/O1CN01ciHTYd26QVNRcYyGM_!!6000000007656-55-tps-276-276.svg":"https://img.alicdn.com/imgextra/i4/O1CN01YNjILU1qE6nxtWgv6_!!6000000005463-55-tps-276-276.svg",a="dark"===t?"https://img.alicdn.com/imgextra/i4/O1CN01AkYfol21Obg3uAWIk_!!6000000006975-55-tps-68-68.svg":"https://img.alicdn.com/imgextra/i4/O1CN01Vi1YUp1Wdwr65fIuO_!!6000000002812-55-tps-68-68.svg"):e.type===hf.WEB_DEV?(i="dark"===t?"https://img.alicdn.com/imgextra/i4/O1CN014rPKuM2AEpkO3CBOd_!!6000000008172-55-tps-276-276.svg":"https://img.alicdn.com/imgextra/i4/O1CN01KTkLVK1SSif2GxIkw_!!6000000002246-55-tps-276-276.svg",o=e.url):e.type===hf.PODCAST?(a="dark"===t?"https://img.alicdn.com/imgextra/i3/O1CN01kDDUIR1Iu4Anz04xi_!!6000000000952-55-tps-68-68.svg":"https://img.alicdn.com/imgextra/i1/O1CN01pjJsNy1H5Ok12wHNt_!!6000000000706-55-tps-68-68.svg",i="dark"===t?"https://img.alicdn.com/imgextra/i1/O1CN01pgfxiO1QN6awp1DJi_!!6000000001963-55-tps-276-276.svg":"https://img.alicdn.com/imgextra/i2/O1CN01fjKKAC1tQQK0mHDIg_!!6000000005896-55-tps-276-276.svg"):e.type===hf.IMAGE&&(r=""),S(C({},e),{id:e.id,type:e.type,title:r,tag:s,cover:i,sharkCover:o,sideBarCover:a,author:e.user_name||(null==n?void 0:n.name)||"",isGood:Boolean(e.like)})}):[],[t,null==n?void 0:n.name]);return{getLibraryList:()=>A(null,null,function*(){const{success:t,data:{items:n}={}}=yield pf({type:hf.ALL});if(t){const t=s(n);e(t)}})}},ff=D.memo(({id:e,chatId:t,mobile:n,isActive:s,showRenameConfirm:i,showOperationMenu:a,isProjectDetailChat:o,projectChat:r,projectId:l,projectChatPined:c,onChange:d,onSelect:u,onUnSelect:h,setActiveChatMenuId:m,setShowShareChatModal:p,setShowDeleteConfirm:g,cloneChatHandler:f,archiveChatHandler:v,showRenameConfirmHandler:y,i18n:b})=>{const{getLibraryList:x}=gf(),w=D.useCallback(()=>{m(null),f(e),pl("clkCloneChat",{params:{et:"CLK"},aesParams:{c4:e},paramsExtend:{chat_id:e}})},[m,f,e]),_=D.useCallback(()=>{m(null),p(!0)},[m,p]),C=D.useCallback(()=>{setTimeout(()=>{x()},2e3),m(null),g(!0)},[x,m,g]),S=D.useCallback(()=>{m(null),h()},[m,h]),k=D.useCallback(()=>{m(o?`${e}_project_detail_chat`:e),u()},[m,o,e,u]),j=!(n||i&&s),T=e===t||a||o;return F.jsxs("div",{className:"chat-item-drag-web "+(T?"chat-item-drag-web-active":""),children:[j&&F.jsx(Si,{title:b.t("More"),placement:"top",arrow:!1,children:F.jsx("button",{"aria-label":"Chat Menu",className:"chat-item-drag-web-default-btn",onClick:k,children:F.jsx(pi,{type:"icon-line-more-01",className:"chat-item-drag-web-default-btn-icon"})})}),F.jsx(Ag,{show:a,chatId:e,projectChat:r,projectId:l,cloneChatHandler:w,shareHandler:_,archiveChatHandler:()=>v(e),renameHandler:y,deleteHandler:C,onClose:S,onChange:d,children:null,projectChatPined:c,tagsDropdownOffsetAuto:o})]})}),vf=D.memo(({visible:e,deleteLoading:t,deployUrlList:n,onCancel:s,onDelete:i})=>{const a=ye();return F.jsxs(wi,{visible:e,title:a.t("Delete chat"),className:"chat-item-delete-confirm",closable:!1,headerBorderNone:!0,maskClosable:!0,onCancel:s,size:"small",actions:[{text:a.t("Cancel"),type:"tertiary",size:"large",rounded:"circle",onClick:s},{text:a.t("Delete"),type:"dangerprimary",size:"large",rounded:"circle",onClick:i}],children:[!(t||!n.length)&&F.jsxs(F.Fragment,{children:[a.t("The chat contains the following deployed content. Once the chat is deleted, the associated links will no longer be accessible. Please confirm to proceed."),F.jsx("div",{className:"deploy-url-container",children:n.map(e=>F.jsx("div",{className:"deploy-url-item",children:e},e))})]}),!t&&a.t("This action will permanently delete all the chats you've created and cannot be undone. Please confirm to proceed.")]})});vf.displayName="DeleteConfirmModal";const yf=D.memo(({visible:e,mobile:t,renameChatTitle:n,onRenameChatTitleChange:s,onCancel:i,onConfirm:a})=>{const o=ye();return F.jsx(wi,{visible:e,className:"qwen-chat-comp-item-rename-modal",title:o.t("Rename Chat"),headerBorderNone:!0,closable:!t,size:"small",cancelText:o.t("Cancel"),onCancel:i,okText:o.t("Confirm"),actions:[{text:o.t("Cancel"),type:"tertiary",rounded:"circle",onClick:i},{text:o.t("Confirm"),rounded:"circle",disabled:!n.trim(),onClick:a}],children:F.jsx("div",{className:"rename-confirm",children:F.jsx("div",{className:"rename-confirm-content",children:F.jsx(Mg,{showMaxLength:!1,value:n,onChange:s,maxLength:100,maxRows:4,placeholder:o.t("Enter your message"),autoFocus:!0})})})})});yf.displayName="RenameConfirmModal";const bf=D.memo(e=>{const{className:t,isActive:n=!1}=e,{id:s,pinned:i,title:a,selected:o,onChange:r,onSelect:l,onUnSelect:c,isProjectDetailChat:d,projectChatPined:u,projectChat:h,projectId:m,chatStatus:p,showShareChatModal:g,setShowShareChatModal:f,showRenameConfirm:v,setShowRenameConfirm:y,showDeleteConfirm:b,setShowDeleteConfirm:x,deleteLoading:w,chatTitle:_,renameChatTitle:C,setRenameChatTitle:S,deployUrlList:k,isOver:j,setIsOver:T,mobile:E,chatId:N,temporaryChatEnabled:I,showOperationMenu:M,isDragging:R,drag:P,editChatTitle:L,cloneChatHandler:O,deleteChatHandler:q,archiveChatHandler:U,gotoNewChat:H,handleTouchStart:B,handleTouchEnd:z,handleDoubleClick:G,exitTemporaryChat:$,showRenameConfirmHandler:W,setActiveChatMenuId:V,i18n:Q}=cf(e),K=D.useCallback(()=>{y(!1),S("")},[y,S]),Y=D.useCallback(()=>A(null,null,function*(){yield L(s,C),r(),y(!1)}),[L,s,C,r,y]);return F.jsxs(F.Fragment,{children:[F.jsx(sg,{show:g,chatId:s,onClose:()=>f(!1)}),F.jsx(vf,{visible:b,deleteLoading:w,deployUrlList:k,onCancel:()=>x(!1),onDelete:()=>q(s)}),F.jsx(yf,{visible:v,mobile:E,renameChatTitle:C,onRenameChatTitleChange:S,onCancel:K,onConfirm:Y}),F.jsxs("div",{ref:E||d?null:P,draggable:!E&&!d,className:`chat-item-drag ${t}`,style:{opacity:R?.5:1},onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),children:[F.jsx(uf,{id:s,chatId:N,title:a,time:e.time,pinned:i,selected:o,isProjectDetailChat:d,projectChatPined:u,chatStatus:p,mobile:E,temporaryChatEnabled:I,chatTitle:_,showOperationMenu:M,isOver:j,gotoNewChat:H,handleDoubleClick:G,handleTouchStart:B,handleTouchEnd:z,exitTemporaryChat:$}),!I&&F.jsx(ff,{id:s,chatId:N,mobile:E,isActive:n,showRenameConfirm:v,showOperationMenu:M,isProjectDetailChat:d,projectChat:h,projectId:m,projectChatPined:u,onChange:r,onSelect:l,onUnSelect:c,setActiveChatMenuId:V,setShowShareChatModal:f,setShowDeleteConfirm:x,cloneChatHandler:O,archiveChatHandler:U,showRenameConfirmHandler:W,i18n:Q})]})]})}),xf=({onRename:e,onExport:t,onDelete:n,onClose:s,children:i})=>{const{i18n:a}=ye(),[o,r]=D.useState(!1),l=D.useCallback(()=>F.jsx(ae,{className:"folder-menu-content",onClick:s=>{s.domEvent.stopPropagation(),r(!1),"rename"===s.key&&e(),"export"===s.key&&t(),"delete"===s.key&&n()},items:[{key:"rename",label:F.jsxs("div",{className:"folder-menu-item-text",children:[F.jsx(pi,{type:"icon-line-edit-contained",className:"folder-menu-item-icon"}),a.t("Rename")]})},{key:"export",label:F.jsxs("div",{className:"folder-menu-item-text",children:[F.jsx(pi,{type:"icon-line-download-02",className:"folder-menu-item-icon"}),a.t("Export")]})},{key:"delete",label:F.jsxs("div",{className:"folder-menu-item-text folder-menu-item-text-error",children:[F.jsx(pi,{type:"icon-line-trash-01",className:"folder-menu-item-icon"}),a.t("Delete")]})}]}),[a,n,t,e]);return F.jsx(Y,{popupRender:l,trigger:["click"],open:o,onOpenChange:e=>{r(e),e||s()},children:F.jsx("div",{className:"folder-menu-trigger",onClick:e=>e.stopPropagation(),children:i})})},wf=e=>A(null,null,function*(){return yield TM("/folders/"+(e?"?exclude_project=true":""))}),_f=({folders:e,folderId:t,className:n="",isNoncollapsible:s,folderEditing:i,onDrop:a=()=>{},onUpdate:o,onChange:r,onEditChange:l})=>{var c,d,u;const{i18n:h}=ye(),[m,p]=D.useState(!1),[g,f]=D.useState(!1),[v,y]=D.useState(""),b=D.useRef(""),[x,w]=D.useState(!1),[_,C]=D.useState(!1),[S,k]=D.useState(!1),[j,T]=D.useState(""),E=D.useRef(null),N=D.useRef(!1),I=e=>A(null,null,function*(){var n;yield(n={id:t,is_expanded:e},A(null,null,function*(){return yield TM(`/folders/${n.id}/update/expanded`,{method:"POST",data:{is_expanded:n.is_expanded}})})).catch(()=>null)}),M=e=>{N.current&&(clearTimeout(E.current),E.current=setTimeout(()=>{I(e)},500))},R=()=>{var n;b.current=(null==(n=e[t])?void 0:n.name)||"",y(b.current),f(!0)},P=D.useCallback(()=>A(null,null,function*(){var n,s,i,a,r,l;if(!v.trim())return y((null==(n=e[t])?void 0:n.name)||""),void vi.openOnce({type:"error",content:h.t("Folder name cannot be empty")});if(v!==(null==(s=e[t])?void 0:s.name)){try{const n=yield(c={id:t,name:v},A(null,null,function*(){return yield TM(`/folders/${c.id}/update`,{method:"POST",data:{name:c.name}})}));n&&n.success?(vi.openOnce({type:"success",content:h.t("Folder name updated successfully")}),o()):"[ERROR: Folder already exists]"===(null==(i=null==n?void 0:n.data)?void 0:i.message)&&(y((null==(a=e[t])?void 0:a.name)||""),vi.open({type:"error",content:h.t("The folder already exists.")})),y((null==(r=e[t])?void 0:r.name)||"")}catch(d){return y((null==(l=e[t])?void 0:l.name)||""),vi.open({type:"error",content:h.t(d.message)}),null}var c;f(!1)}else f(!1)}),[t,e,h,v,o]),L=D.useCallback(()=>A(null,null,function*(){k(!0);var e;(yield(e={id:t},A(null,null,function*(){return yield TM(`/folders/${e.id}`,{method:"DELETE"})})).catch(e=>(vi.open({type:"error",content:h.t(e.message)}),k(!1),null)))&&(vi.open({type:"success",content:h.t("Folder deleted successfully")}),o())}),[t,h,o]),O=D.useCallback((t,n=1)=>e[t]&&e[t].parent_id?O(e[t].parent_id,n+1):n,[e]),q=D.useMemo(()=>{var n;return((null==(n=e[t])?void 0:n.childrenIds)||[]).map(t=>e[t]).sort((e,t)=>e.name.localeCompare(t.name,void 0,{numeric:!0,sensitivity:"base"}))},[e,t]),U=D.useMemo(()=>{var n,s,c,d,u;return F.jsx("div",{className:"collapsible-content",children:((null==(n=e[t])?void 0:n.childrenIds)||[]).length>0||((null==(c=null==(s=e[t])?void 0:s.items)?void 0:c.chats)||[]).length>0?F.jsxs("div",{className:"collapsible-content-list",children:[q.map(n=>F.jsx(_f,{folders:e,folderId:n.id,folderEditing:i,onUpdate:o,onChange:r,onEditChange:l,onDrop:a},`${t}-${n.id}`)),((null==(u=null==(d=e[t])?void 0:d.items)?void 0:u.chats)||[]).map(t=>F.jsx(bf,{folders:e,id:t.id,title:t.title,isActive:j===t.id,onChange:r,onEditChatChange:()=>T(t.id)},`${t.id}_${t.title}`))]}):null})},[j,q,i,t,e,r,l,o,a]),[{isOver:H},B]=Ke(()=>({accept:["chat","folder"],drop:(e,n)=>{n.didDrop()||(M(!0),a(e,t))},collect:e=>({isOver:!!e.isOver()})})),[{isDragging:z},G]=Ye(()=>({type:"folder",item:{id:t,type:"folder"},collect:e=>({isDragging:!!e.isDragging()})}));D.useEffect(()=>{N.current=!0},[]),D.useEffect(()=>{var n;y((null==(n=e[t])?void 0:n.name)||""),p(!!e[t].is_expanded)},[e,t]),D.useEffect(()=>{const e=O(t);C(e>5)},[e,t,O]),D.useEffect(()=>{l(g)},[g,l]);const $=D.useMemo(()=>F.jsx(wi,{visible:x,title:h.t("Delete the folder?"),onOk:L,onCancel:()=>w(!1),actions:[{text:h.t("Cancel"),type:"tertiary",onClick:()=>{w(!1)}},{text:h.t("Confirm"),type:"dangerprimary",onClick:L}],headerBorderNone:!0,closable:!1,maskClosable:!0,className:"delete-dialog-modal",size:"small",children:F.jsx("div",{className:"delete-dialog-content",dangerouslySetInnerHTML:{__html:Ze.sanitize(h.t("This operation will delete {{name}} and all its contents.",{name:`${e[t].name}`}))}})}),[L,t,e,h,x]),W=D.useMemo(()=>F.jsx(wi,{visible:g,className:"qwen-chat-comp-recursive-folder-rename-modal",title:h.t("Rename"),headerBorderNone:!0,closable:!0,size:"small",cancelText:h.t("Cancel"),onCancel:()=>{y(b.current),f(!1)},okText:h.t("Confirm"),actions:[{text:h.t("Cancel"),type:"tertiary",rounded:"circle",onClick:()=>{y(b.current),f(!1)}},{text:h.t("Confirm"),rounded:"circle",disabled:!v.trim(),onClick:P}],children:F.jsx("div",{className:"rename-confirm",children:F.jsx("div",{className:"rename-confirm-content",children:F.jsx(Mg,{showMaxLength:!1,value:v,onChange:y,maxLength:100,maxRows:4,placeholder:h.t("Enter your message")})})})}),[g,h,v,P]);return F.jsxs(F.Fragment,{children:[$,W,F.jsx("div",{ref:e=>{g||(G(e),B(e))},className:`recursive-folder-dragge ${n}`,style:{background:H&&!z?"rgba(101, 31, 255, .1)":"transparent",opacity:z?.5:1},children:F.jsx(rf,{open:m,disabled:s,className:"recursive-folder-collapsible",buttonClassName:"recursive-folder-collapsible-btn",hide:0===((null==(c=e[t])?void 0:c.childrenIds)||[]).length&&0===((null==(u=null==(d=e[t])?void 0:d.items)?void 0:u.chats)||[]).length,onChange:e=>{S||(p(e),M(e))},contentChildren:U,children:F.jsx("div",{className:"collapsible-group group",children:F.jsxs("div",{id:`folder-${t}-button`,className:"collapsible-group-btn "+(s||_?"recursive-folder-disabled-cursor":""),onDoubleClick:e=>{e.stopPropagation(),_||R()},children:[F.jsx("div",{className:"collapsible-group-btn-text",children:F.jsx(Si,{title:v,placement:"bottom",arrow:!1,children:F.jsx("div",{className:"collapsible-group-btn-tip",children:(V=(g?b.current:v)||"",Q=100,V.length>Q?V.slice(0,Q-3)+"...":V)})})}),(!_||S)&&F.jsx("div",{className:"collapsible-group-btn-deleting",children:F.jsx(xf,{onRename:R,onDelete:()=>{w(!0)},onExport:()=>A(null,null,function*(){var n;const s=yield(i={folder_id:t},A(null,null,function*(){return yield TM(`/chats/folder/${i.folder_id}`)})).catch(e=>(vi.open({type:"error",content:h.t(e.message)}),null));var i;if(!(null==(n=null==s?void 0:s.data)?void 0:n.length))return;const a=new Blob([JSON.stringify(null==s?void 0:s.data)],{type:"application/json"});Mr(a,`folder-${e[t].name}-export-${Date.now()}.json`)}),onClose:()=>{},children:F.jsx("div",{className:"collapsible-folder-menu",children:F.jsx(pi,{type:"icon-line-more-01",className:"collapsible-folder-menu-icon"})})})}),F.jsx("div",{className:"collapsible-group-btn-icon",children:m?F.jsx(pi,{type:"icon-line-chevron-down"}):F.jsx(pi,{type:"icon-line-chevron-up"})})]})})})})]});var V,Q},Cf=D.memo(_f),Sf=D.memo(({folders:e,onUpdate:t,onChange:n,onDrop:s,isNoncollapsible:i})=>{const[a,o]=D.useState(!1),r=D.useMemo(()=>Object.keys(e).filter(t=>null===e[t].parent_id).sort((t,n)=>e[t].name.localeCompare(e[n].name,void 0,{numeric:!0,sensitivity:"base"})),[e]);return F.jsx(F.Fragment,{children:r.map(r=>F.jsx(Cf,{className:"folder-list",isNoncollapsible:i,folders:e,folderId:r,folderEditing:a,onUpdate:t,onChange:n,onEditChange:e=>o(e),onDrop:s},r))})}),kf=({children:e,onVisible:t=()=>{}})=>{const n=D.useRef(null),s=D.useRef(null),i=D.useRef(null);return D.useEffect(()=>{const e=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?i.current=setInterval(()=>{t()},1e3):i.current&&(clearInterval(i.current),i.current=null)})},{root:null,rootMargin:"0px",threshold:.1});return s.current=e,n.current&&e.observe(n.current),()=>{s.current&&s.current.disconnect(),i.current&&clearInterval(i.current)}},[]),F.jsx("div",{ref:n,children:e})},jf=({pinnedChats:e,folders:t,finshChats:n,initChatList:s})=>{const i=D.useRef({}),a=ye(),{getNewProjectList:o}=ig(),r=D.useCallback(e=>A(null,null,function*(){try{return void(yield yg(e.id).catch(e=>{vi.open({type:"error",content:a.t(e.message)})}))}catch(t){}}),[a]),l=D.useCallback((e,t)=>A(null,null,function*(){try{const s=["finsh","pinned"].includes(t)?void 0:t;return void(yield(n={chat_id:e.id,folder_id:s},A(null,null,function*(){return yield TM(`/chats/${n.chat_id}/folder`,{method:"POST",data:{folder_id:n.folder_id}})})).catch(e=>{vi.open({type:"error",content:a.t(e.message)})}))}catch(s){}var n}),[a]),c=D.useCallback((e,t)=>A(null,null,function*(){try{const s="finsh"===t?void 0:t;return void(yield(n={id:e.id,parent_id:s},A(null,null,function*(){return yield TM(`/folders/${n.id}/update/parent`,{method:"POST",data:{parent_id:n.parent_id}})})).catch(e=>{vi.open({type:"error",content:a.t(e.message)})}))}catch(s){}var n}),[a]),d=D.useCallback((e,t)=>A(null,null,function*(){var n,d;if("project"===e.type){const n=yield uw(t,[e.id]).catch(e=>(vi.open({type:"error",content:a.t(e.message)}),null));(null==n?void 0:n.success)?yield s(t):"Not_Found"===(null==n?void 0:n.data.code)&&o()}const u=null==(n=i.current[e.id])?void 0:n.parent_id;if(u!==t&&e.id!==t){if("pinned"===t)return yield l(e,t),yield r(e),void(yield s());if("pinned"===u&&"finsh"===t)return yield r(e),void(yield s());if("chat"===e.type)return yield l(e,t),void(yield s());if("folder"===e.type){if(((null==(d=i.current[t])?void 0:d.level)||0)>=4)return void vi.openOnce({type:"warning",content:a.t("The folder dimension cannot exceed {{value}} levels.",{value:5})});if(!e.parent_id&&"finsh"===t)return;return yield c(e,t),void(yield s())}}}),[l,c,r,a,s]);return D.useEffect(()=>{null==e||e.forEach(e=>{i.current[e.id]={parent_id:"pinned"}});const s=zR(t);Object.keys(s).forEach(e=>{var t,n,a;i.current[e]={parent_id:s[e].parent_id||null,level:s[e].level},(null==(a=null==(n=null==(t=s[e])?void 0:t.items)?void 0:n.chats)?void 0:a.length)&&s[e].items.chats.forEach(t=>{i.current[t.id]={parent_id:e}})}),n.forEach(e=>{i.current[e.id]={parent_id:"finsh"}})},[n,t,e]),{handleDrop:d}};O.lazy(()=>Se(()=>import("./index28.js"),__vite__mapDeps([1,0,2,3,4]))),O.lazy(()=>Se(()=>Promise.resolve().then(()=>wC),void 0));const Tf=({showOperation:e=!1,project:t,disabled:n=!1,isMore:s=!1})=>{const{i18n:i}=ye(),{getProjectFilesList:a,extractProjectId:o}=ig(),{getChatListData:r,initFolders:l,getPinnedChatListData:c}=Tg(),d=Ue(),u=cR(e=>e.mobile),h=ud(e=>e.setShowSidebar),m=ud(e=>e.showSidebar),p=Ns(e=>e.setPinnedChats),g=js(e=>e.setChatId),f=pw(e=>e.setOperationProject),v=pw(e=>e.setProjectChats),y=Rs(e=>e.temporaryChatEnabled),b=pw(e=>e.setShowDeleteConfirm),x=pw(e=>e.showAllList),w=pw(e=>e.setShowAllList),_=pw(e=>e.setProjectSettingOpen),k=pw(e=>e.setOperationProjectFiles),j=pw(e=>e.activeProjectId),T=pw(e=>e.setActiveProjectId),E=pw(e=>e.setShowEditModal),N=Ns(e=>e.setChats),I=Rs(e=>e.folders),M=pw(e=>e.projectExpandChats),R=pw(e=>e.setProjectExpandChats),P=pw(e=>e.showPanelList),L=pw(e=>e.setShowPanelList),[O,q]=D.useState(!1),[U,H]=D.useState(!1),[B,z]=D.useState(0),[G,$]=D.useState(0),[W,V]=D.useState(!1),[K,Y]=D.useState(null),[J,X]=D.useState(""),Z=Ns(e=>e.pinnedChats),ee=ud(e=>e.setActiveChatMenuId),te=pw(e=>e.activeChatDetails),ne=pw(e=>e.setActiveChatDetails),se=D.useRef(0),ie=D.useRef(void 0),ae=()=>{clearTimeout(ie.current),u&&L(!1)},oe=D.useCallback(e=>A(null,null,function*(){const t=yield c();Array.isArray(t)&&p(t),yield l();const n=yield r(1);N(n);const s=yield dw(String(j),1);if(s&&Array.isArray(s.data)&&R(s.data),e)if(location.pathname.includes("/p/")){if(o(location.pathname)===e){const t=yield dw(String(e),1);t&&Array.isArray(t.data)&&v(t.data)}else d(`/p/${e}`)}else d(`/p/${e}`);else if(location.pathname.includes("/p/")){o(location.pathname)===j&&s&&Array.isArray(s.data)&&v(s.data)}}),[j,o,r,c,l,d,N,p,v,R]),{handleDrop:re}=jf({pinnedChats:Z,folders:I,finshChats:[],initChatList:oe}),[{isOver:le},ce]=Ke(()=>({accept:["chat"],drop:(e,n)=>{y||n.didDrop()||t.id&&re(S(C({},e),{type:"project"}),t.id)},collect:e=>({isOver:!!e.isOver()})}),[j]),[{isDragging:de}]=Ye(()=>({type:"project",item:{id:t.id,type:"project"},collect:e=>({isDragging:!!e.isDragging()})})),ue=()=>A(null,null,function*(){y||(yield q(!1),yield H(!1),(yield a(t.id))&&(yield f(JSON.parse(JSON.stringify(t))),E(!0)))}),he=()=>{y||(q(!1),H(!1),f(JSON.parse(JSON.stringify(t))),b(!0))},me=D.useRef(null);D.useEffect(()=>{const e=e=>{P&&me.current&&!me.current.contains(e.target)&&L(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[P]);const pe=D.useMemo(()=>M.length<=5?M||[]:j===t.id&&te&&te.project_id===j&&location.pathname.includes("/c/")&&M.slice(0,5).every(e=>e.id!==te.id)?[...M.slice(0,4),te]:M.slice(0,5),[te,j,t.id,M]),ge=D.useCallback(()=>A(null,null,function*(){if(!te)return;if((null==te?void 0:te.project_id)!==t.id)return;T(t.id);const e=yield dw(String(t.id),1);e&&Array.isArray(e.data)&&R(e.data)}),[te,t.id,T,R]);D.useEffect(()=>{te&&location.pathname.includes("/c/")&&ge()},[te]),D.useEffect(()=>{!m&&u&&H(!1)},[u,H,m]);const fe=Eg(t.icon);return F.jsxs(F.Fragment,{children:[F.jsxs("div",{ref:ce,className:"project-item",onTouchStart:e=>{var n;u&&t.id&&(n=e,u&&!s&&(n.stopPropagation(),n.preventDefault(),se.current=Date.now(),clearTimeout(ie.current),ie.current=setTimeout(()=>{Date.now()-se.current>=500&&(H(!0),T(t.id),ee(null))},500)))},onTouchEnd:ae,onTouchCancel:ae,onMouseLeave:ae,onClick:e=>A(null,null,function*(){if(!y&&(clearTimeout(ie.current),e.stopPropagation(),!n)){if(Y(null),X(""),!s&&!t.id)return yield f({}),yield _(!1),yield k([]),void E(!0);if(f(JSON.parse(JSON.stringify(t))),u){if(s)return void w(!x);h(!1)}else{Y(null);const t=e.currentTarget.getBoundingClientRect();s&&(L(!P),z(t.top),$(t.left+t.width))}}}),onDragOver:e=>e.preventDefault(),style:{background:le&&!de?"rgba(101, 31, 255, .1)":"transparent",opacity:de?.5:1},children:[F.jsx(Si,{title:`${n?i.t("Limit reached"):""}`,children:F.jsxs("div",{className:Q("project-item-header",{"project-item-selected":location.pathname.includes("/p/")&&o(location.pathname)===t.id,"project-item-header-disabled":n,"project-item-header-mobile":u}),children:[F.jsx("div",{id:"notification_update_popover_project"}),F.jsxs("div",{className:"project-item-left",children:[F.jsx("div",{className:"project-item-icon-content",onClick:()=>A(null,null,function*(){if(!y&&t.id)if(u)g(""),ne(null),d(`/p/${t.id}`);else if(j!==t.id){Y(null),X("");try{const e=yield dw(t.id,1);if(T(t.id),e&&Array.isArray(e.data)&&R(e.data),!e||!e.data||0===e.data.length)return g(""),ne(null),void d(`/p/${t.id}`)}catch(e){return void vi.open({type:"error",content:i.t("Failed to load project chats")})}}else M&&M.length>0?T(null):(g(""),ne(null),d(`/p/${t.id}`))}),children:t.id&&t.icon?fe.icon.includes("icon-")?F.jsx(pi,{type:fe.icon,className:`project-item-icon ${fe.style}`}):F.jsx("div",{className:"project-item-icon-emoji",children:pn[fe.icon]}):F.jsx(pi,{type:t.projectIcon,className:`project-item-icon ${fe.style}`})}),F.jsx("div",{className:"project-item-text",onClick:()=>{y||(Y(null),X(""),g(""),ne(null),t.id&&d(`/p/${t.id}`))},children:t.name})]}),e&&!u&&!y&&F.jsxs("div",{className:"project-item-right-btn",children:[F.jsx("div",{onClick:e=>{e.stopPropagation(),q(!0),V(!0)},children:F.jsx(pi,{type:"icon-line-more-01",className:"chat-item-drag-web-default-btn-icon "})}),O&&F.jsx(Og,{show:O,onClose:()=>{q(!1),V(!1)},editHandler:ue,deleteHandler:he})]}),P&&s&&F.jsx("div",{ref:me,children:F.jsx(Ng,{styleTop:B,styleLeft:G})})]})}),j===t.id&&!u&&F.jsxs("div",{className:"project-item-chat-list",children:[pe.map(e=>F.jsx("div",{className:"project-item-chat",onClick:e=>e.stopPropagation(),children:F.jsx(bf,{id:e.id,projectId:e.project_id,title:e.title,selected:K===e.id,onSelect:()=>{Y(e.id)},onUnSelect:()=>{Y(null)},onChange:oe,isActive:J===e.id,onEditChatChange:()=>X(e.id),pinned:e.pinned,projectChatPined:e.pinned,projectChat:!0},e.id)},`${e.id}_${e.title}`)),M.length>5&&F.jsx("div",{className:"project-item-chat-see-all",onClick:()=>{g(""),ne(null),d(`/p/${t.id}`)},children:i.t("View All")})]})]}),U&&u&&!y&&F.jsx("div",{className:"project-menu-mobile h-0 w-full",children:F.jsx(Og,{show:U&&j===t.id,onClose:()=>q(!1),editHandler:ue,deleteHandler:he})})]})},Ef=()=>{const{i18n:e}=ye(),t=cR(e=>e.mobile),n=pw(e=>e.showAllList),s=pw(e=>e.projectArr),i=Rs(e=>e.temporaryChatEnabled),[a,o]=D.useState(!0),[r,l]=D.useState([]);return D.useEffect(()=>{l(n?null!=s?s:[]:(null!=s?s:[]).slice(0,5))},[n,s]),F.jsx(F.Fragment,{children:F.jsxs("div",{className:"project-container "+(i?"project-container-temporary-chat":""),children:[!t&&F.jsxs("div",{className:"project-list-title",onClick:()=>{o(!a)},children:[F.jsx("div",{className:"project-list-title-left",children:F.jsxs("div",{className:"project-list-title-text",children:[F.jsx("div",{id:`${Kp}_project`}),e.t("Projects")]})}),F.jsx("div",{className:"project-list-title-right",children:F.jsx(pi,{type:a?"icon-line-chevron-down":"icon-line-chevron-up",className:"project-title-right-icon"})})]}),F.jsxs("div",{className:"project-list "+(a?"":"project-list-hidden"),children:[F.jsx(Tf,{project:{name:e.t("New Project"),projectIcon:"icon-line-folder-plus"},disabled:s.length>=20}),r.map(e=>F.jsx(Tf,{project:S(C({},e),{projectIcon:"icon-line-folder-01"}),showOperation:!0},e.id)),s.length>5&&F.jsx(Tf,{project:{name:e.t(n&&t?"Show less":"Show more"),projectIcon:"icon-line-more-01"},isMore:!0})]})]})})},Nf=e=>{const{mobile:t,searchInputFocused:n,searchCurrent:s,pinnedChats:i,folders:a,temporaryChatEnabled:o,finshChats:r,selectedChatId:l,todayActiveChatId:c,pinnedActiveChatId:d,prevChatListLength:u,chatListLoading:h,searchLoading:m,showSidebar:p,enableProjectEntry:g,activeChatMenuId:f,PAGE_SIZE:v,onSelectedChatIdChange:y,onPinnedActiveChatIdChange:b,onTodayActiveChatIdChange:x,onLoadMore:w,onInitChatList:_,onSetActiveChatMenuId:C,getChatStatus:S}=e,k=ye(),{handleDrop:j}=jf({pinnedChats:i,folders:a,finshChats:r,initChatList:_}),T=D.useMemo(()=>!t&&!s&&!n&&(i||[]).filter(e=>!e.project_id).length>0?(i||[]).filter(e=>!e.project_id).map(e=>F.jsx(bf,{id:e.id,title:e.title,selected:l===e.id,onSelect:()=>y(e.id),onUnSelect:()=>y(null),pinned:e.pinned,onChange:_,isActive:d===e.id,onEditChatChange:()=>b(e.id),chatStatus:S(e.id)},`${e.id}_${e.title}`)):null,[t,s,n,i,l,_,d,S,y,b]),E=D.useMemo(()=>s||n||!a||t?null:F.jsx(Sf,{isNoncollapsible:o,folders:a,onUpdate:_,onChange:_,onDrop:j}),[n,a,t,o,_,j,s]),N=D.useMemo(()=>m?F.jsx("div",{className:"sidebar-side-loading-wrapper",children:F.jsxs("div",{className:"sidebar-side-loading",children:[F.jsx(Ui,{fontSize:15,borderWidth:2,className:"sidebar-side-loading-icon"}),F.jsx("span",{children:k.t(s?"Searching...":"Loading...")})]})}):F.jsxs(lf,{id:"finsh",collapsible:!(s||n),className:"list-folder",name:k.t("All chats"),onDrop:j,folders:a,children:[T,F.jsx("div",{className:"list-folder-pt "+(s||n?"list-folder-pt-search":""),children:r?F.jsxs(F.Fragment,{children:[!r.length&&(s||n)&&F.jsx("div",{className:"task-list-search-not-task",children:k.t("No Task")}),(n&&!s?[]:r).map((e,n)=>{var s;return F.jsxs(O.Fragment,{children:[(0===n||n>0&&e.time_range!==(null==(s=r[n-1])?void 0:s.time_range))&&F.jsx("div",{className:Q("list-folder-chats",{"list-folder-chats-mobile":t}),children:k.t(e.time_range)}),F.jsx(bf,{folders:a,id:e.id,title:e.title,selected:l===e.id,onSelect:()=>y(e.id),onUnSelect:()=>y(null),onChange:_,isActive:c===e.id,onEditChatChange:()=>x(e.id),chatStatus:e.status})]},`${e.id}-${n}-${e.title}`)}),u>=v&&(!n||n&&s)&&F.jsx(kf,{onVisible:()=>!h&&w(),children:F.jsxs("div",{className:"list-folder-loading-skeleton",children:[F.jsx("div",{className:"list-folder-loading-skeleton-item",children:F.jsx(Li,{style:{width:"100%",height:"20px"}})}),F.jsx("div",{className:"list-folder-loading-skeleton-item",children:F.jsx(Li,{style:{width:"100%",height:"20px"}})}),F.jsx("div",{className:"list-folder-loading-skeleton-item",children:F.jsx(Li,{style:{width:"100%",height:"20px"}})})]})})]}):F.jsxs("div",{className:"list-folder-loading",children:[F.jsx(Ui,{className:"loading-size"}),F.jsx("div",{children:k.t("Loading...")})]})})]}),[m,n,k,j,a,T,r,t,l,c,h,w,_,y,x,s,u,v]);return F.jsxs(F.Fragment,{children:[g&&!s&&!n&&F.jsx("div",{className:Q("project-list-wrapper",{"project-list-hidden":!p}),children:F.jsx(Ef,{})}),F.jsx("div",{className:Q("session-list-wrapper",{"has-temporary-chat":o,"session-list-wrapper-small":!p}),children:F.jsxs("div",{className:"session-list",onScroll:()=>{f&&C(null)},children:[E,N]})})]})},If=()=>{const e=ye(),t=Ue(),n=cR(e=>e.mobile),s=Pd(e=>e.fetchUser),i=Fd(e=>e.paymentSubscriptionInfo),a=Fd(e=>e.fetchPaymentSubscriptionStatus),o=Fd(e=>e.fetchPaymentUserNotifications),r=Fd(e=>e.subscriptionPlus),l=Fd(e=>e.paymentSubscriptionStatus),c=Fd(e=>e.setShowSubscriptionDetail),d=cR(e=>e.fetchConfig),[u,h]=D.useState(!1),m=hR(e=>e.setShowRegionUnenablePayment),p=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_payment}),g=D.useMemo(()=>!p&&!r&&!(null==l?void 0:l.subscribed),[null==l?void 0:l.subscribed,p,r]),f=D.useMemo(()=>!p&&r&&!(null==l?void 0:l.subscribed),[null==l?void 0:l.subscribed,p,r]),v=D.useMemo(()=>{const t={upgradeTitle:e.t("Unlock Qwen advanced Capabilities"),info:{key:"free",title:"Free",dollar:"0",cycle:e.t("month"),btnText:e.t("Your current plan"),btnDisabled:!0,description:"",features:[],mobile:{title:"",subTitle:""}}};if(i){const{normal:{description:e,features:n,mobile:s}}=i;t.info.mobile=s,t.info.description=e,t.info.features=n.map(e=>S(C({},e),{text:e.text}))}return t},[e,i]),y=D.useMemo(()=>{const t={upgradeTitle:e.t("Unlock Qwen advanced Capabilities"),info:{key:"Plus",title:"Plus",tag:e.t("POPULAR"),dollar:"9.9",cycle:e.t("month"),btnText:e.t("Upgrade to Plus"),btnDisabled:!1,description:"",features:[],mobile:{title:"",subTitle:""}}};if(i){const{plus:{description:e,features:n,mobile:s}}=i;t.info.mobile=s,t.info.description=e,t.info.features=n.map(e=>S(C({},e),{text:e.text}))}return t},[e,i]),b=D.useCallback(()=>A(null,null,function*(){m(!0),c(!1),t("/")}),[t,m,c]),x=D.useCallback(t=>n||p?e.t(t):"",[e,n,p]),w=D.useCallback((t="",n=!1)=>{t&&vi.open({type:"warning",content:e.t("{{ service }} is not available in your region.",{service:t})}),n&&b()},[e,b]),_=D.useCallback((t="",n=!1)=>A(null,null,function*(){if(!p)return w(t,n),!1;try{const e=yield d();if(!e)throw new Error("Failed to fetch backend config");const s=e.features.enable_payment;return s||w(t,n),s}catch(s){return vi.open({type:"error",content:e.t("Failed to verify region support status")}),!1}}),[w,d,e,p]),k=D.useCallback(t=>A(null,null,function*(){const n=yield s();if(!n)throw new Error("verifyIsPlusHandle error");return"subscription-plus"===(null==n?void 0:n.tier)&&(vi.open({type:"success",content:e.t("You are already a Plus user, and the page is about to refresh.")}),setTimeout(()=>{null==t||t(),location.reload()},3e3),!0)}),[s,e]),j=D.useCallback(e=>A(null,[e],function*({callback:e,toolTipServiceName:t="",redirection:n=!1}){try{if(!(yield _(t,n)))return;if(yield k(e))return;const s=yield GM();s&&s.data.normal_url&&(window.location.href=s.data.normal_url)}catch(s){h(!1)}finally{h(!1)}}),[k,_]),T=D.useCallback(()=>A(null,null,function*(){try{const e=yield $M();e&&e.data.normal_url&&(window.location.href=e.data.normal_url)}catch(e){}}),[]),E=D.useCallback((e="")=>A(null,null,function*(){try{if(!(yield _(e,!1)))return;const{data:{code:t}}=yield KM();t||(yield a())}catch(t){}finally{h(!1)}}),[a,_]),N=D.useCallback(()=>A(null,null,function*(){try{const{data:{code:e}}=yield VM();if(!e){(yield a())&&(yield o())}}catch(e){}finally{h(!1)}}),[a,o]),I=D.useCallback((e,t)=>{const n=C(C({},{hasSure:!1,showSubscriptionDetail:!1,toolTipServiceName:""}),t);n.hasSure||!(null==l?void 0:l.subscribed)?(null==l?void 0:l.subscribed)?(h(!0),N()):r?(h(!0),E(n.toolTipServiceName)):n.showSubscriptionDetail?c(!0):(h(!0),j({toolTipServiceName:n.toolTipServiceName,redirection:!1})):null==e||e()},[N,null==l?void 0:l.subscribed,E,j,c,r]),M=D.useCallback(()=>A(null,null,function*(){try{yield aR(),vi.open({type:"success",content:"清除会员状态成功! 页面即将重新加载"}),setTimeout(()=>{location.reload()},1e3)}catch(e){}}),[]),R=D.useCallback(()=>A(null,null,function*(){try{yield oR(),vi.open({type:"success",content:"默认支付工具失效完成! 页面即将重新加载"}),setTimeout(()=>{location.reload()},1e3)}catch(e){}}),[]);return{disabledUpgradePlan:g,disabledReSubscribe:f,freeUpgradeInfo:v,plusUpgradeInfo:y,subscriptionLoading:u,verifyIsPlusHandle:k,postPaymentSubscribeHandle:j,postCompensationSubscriptionHandle:T,onChangeUpgrade:I,postPaymentClearHandle:M,postDisableDefaultPaymentMethodHandle:R,verifyIsSupportSubscriptionFromRegion:_,getTooltipServeName:x}},Af=D.memo(()=>{const e=ye(),t=Ue(),n=cR(e=>{var t,n,s,i;return(null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_payment)&&(null==(i=null==(s=null==e?void 0:e.config)?void 0:s.features)?void 0:i.enable_payment_and_quota)}),s=cR(e=>e.mobile),i=Fd(e=>e.subscriptionPlus),a=ud(e=>e.setSettingActionMenuItemId),{plusUpgradeInfo:o}=If();return s&&n&&!i?F.jsxs("div",{className:"sidebar-upgrade-plan",children:[F.jsxs("div",{className:"sidebar-upgrade-plan-l",children:[F.jsxs("div",{className:"sidebar-upgrade-plan-title-container",children:[F.jsx("div",{className:"sidebar-upgrade-plan-title",children:"Qwen"}),F.jsx("div",{className:"sidebar-upgrade-plan-label",children:F.jsx("div",{className:"sidebar-upgrade-plan-label-text",children:"Plus"})})]}),F.jsx("div",{className:"sidebar-upgrade-plan-desc",children:o.info.description})]}),F.jsx("div",{className:"sidebar-upgrade-plan-r",children:F.jsx(xi,{type:"brandprimary",rounded:"circle",size:"small",onClick:()=>{a("subscription"),t("/settings")},children:e.t("Upgrade")})})]}):null}),Mf=({mobile:e,showSidebar:t,enablePaymentEntry:n,subscriptionPlus:s,onShowSubscriptionDetail:i})=>F.jsxs(F.Fragment,{children:[F.jsx(Af,{}),n&&!s&&!e&&!t&&F.jsx("div",{className:"sidebar-side-fold-container-upgrade",onClick:i,children:F.jsx(pi,{type:"icon-a-lianji8",className:"sidebar-side-fold-container-upgrade-icon"})}),!e&&F.jsx(of,{})]}),Rf=D.forwardRef((e,t)=>{const{placeholder:n="",externalValue:s="",inputChange:i,onlyIcon:a=!1,onOpen:o=()=>{}}=e,{mobile:r}=cR(),l=ud(e=>e.searchInputFocused),c=ud(e=>e.setSearchInputFocused),d=ye(),u=D.useRef(null),[h,m]=D.useState(s),[p,g]=D.useState(0),[f,v]=D.useState([]),[y,b]=D.useState(!1),{getAllTagsData:x}=Tg(),w=h&&h.split(" ").at(-1)||"",_=h.split(" "),C=0!==h.split(" ").length&&f.every(e=>_.some(t=>`tag:${e.id}`===t)),S=[{name:"tag:",description:d.t(C?"Untagged":"search for tags")}].filter(e=>e.name.startsWith(w)),k=(null==w?void 0:w.startsWith("tag:"))?f.filter(e=>{const t=`tag:${e.id}`;return h.split(" ").every(e=>e!==t)}):[];D.useImperativeHandle(t,()=>({searchInputFocus:()=>{var e;null==(e=u.current)||e.focus()}}));const j=D.useCallback(e=>{const t=document.getElementById("search-container"),n=document.getElementById("chat-search");if(t&&n&&!t.contains(e.target)&&!n.contains(e.target)){if(e.target.id.startsWith("search-tag-")||e.target.id.startsWith("search-option-"))return;c(!1)}},[]);D.useEffect(()=>(document.addEventListener("click",j),()=>{document.removeEventListener("click",j),c(!1)}),[j]);return F.jsx("div",{className:"search-container "+(r?"search-container-mobile":""),id:"search-container",children:F.jsxs("div",{className:`chat-search ${l?"chat-search-focused":""} ${r?"chat-search-mobile":""}`,id:"chat-search",style:{opacity:.4,cursor:"not-allowed"},ref:e=>{e&&e.style&&(e.style.opacity="1",e.style.cursor="pointer",u.current&&(u.current.disabled=!1))},children:[F.jsx("div",{className:`chat-search-icon ${r?"chat-search-icon-mobile":""} ${a?"chat-search-icon-only-icon":""}`,onClick:()=>{o(),c(!0)},children:F.jsx(pi,{type:"icon-line-search-01",className:"chat-search-icon-other"})}),F.jsx("input",{className:`chat-search-input ${r?"chat-search-input-mobile":""} ${a?"chat-search-input-only-icon":""}`,placeholder:n||d.t("Search Chats"),maxLength:1e3,value:h,ref:u,onChange:e=>{i(e.target.value),m(e.target.value)},onFocus:()=>{c(!0),A(null,null,function*(){if(!y)try{const e=yield x();v([...e,{id:"none",name:d.t("Untagged")}]),b(!0)}finally{b(!1)}})},onKeyDown:e=>{if("Enter"===e.key){if(k.length>0){const e=document.getElementById(`search-tag-${p}`);return void(e&&e.click())}if(S.length>0){const e=document.getElementById(`search-option-${p}`);return void(e&&e.click())}}"ArrowUp"===e.key?(e.preventDefault(),g(Math.max(0,p-1))):"ArrowDown"===e.key?(e.preventDefault(),g(Math.min(p+1,k.length>0?k.length-1:S.length-1))):g(0)},style:{cursor:"inherit"},disabled:!0}),l&&F.jsx("div",{className:"chat-search-close-container",onClick:()=>{i(""),m(""),c(!1)},children:F.jsx(pi,{type:"icon-close-4",className:"chat-search-close-icon"})})]})})}),Pf=()=>{const e=Ue(),t=ye(),n=cR(e=>e.mobile),s=ud(e=>e.showSidebar),i=ud(e=>e.setShowSidebar),a=js(e=>e.setChatId),o=pR(e=>e.myLibraryExpand),r=pR(e=>e.setMyLibraryExpand);return F.jsxs("div",{className:"my-library-head "+(s?"":"my-library-head-only"),onClick:()=>{a(""),e("/library"),n&&i(!1)},children:[F.jsxs("div",{className:"my-library-head-left",children:[F.jsx(pi,{type:"icon-line-library2",className:"my-library-head-left-icon "+(s?"":"my-library-head-left-only-icon"),onClick:e=>{s&&e.stopPropagation(),r(!o)}}),F.jsx("div",{className:"my-library-head-left-text",children:t.t("My Library")})]}),F.jsx("div",{className:"my-library-head-right",children:F.jsx(pi,{type:"icon-line-chevron-right",className:"my-library-head-right-icon"})})]})},Lf=D.memo(({searchInputChange:e})=>{const t=ye(),n=dR(e=>e.mobile),s=hd(e=>e.showSidebar),i=ud(e=>e.searchInputFocused),a=ud(e=>e.sideBarSearchText),o=Rs(e=>e.temporaryChatEnabled),r=ud(e=>e.setShowSidebar),l=D.useRef(null),c=cR(e=>{var t;return null==(t=null==e?void 0:e.config)?void 0:t.function_entry.mylibrary}),d=pR(e=>e.sidebarLibraryList),u=!(!a&&!i),h=e=>{e&&e.style&&(e.style.opacity="1",e.style.cursor="pointer")},m=D.useCallback(()=>A(null,null,function*(){const e=pw.getState().setChatProjectId,t=pw.getState().setProjectName;e(null),t(""),yield bM.openNewChat(),pl("clkCreateChat",{params:{et:"CLK"}}),n&&r(!1)}),[n,r]),p=D.useCallback(()=>{r(!0),setTimeout(()=>{var e;null==(e=l.current)||e.searchInputFocus()},300)},[r]),g=D.useMemo(()=>F.jsxs("div",{className:Q("sidebar-temporary",{"opacity-temporary":o,"sidebar-temporary-only-icon":!s,"sidebar-temporary-focus":i}),children:[o&&F.jsx("div",{className:"temporary-chat"}),F.jsx(Rf,{ref:l,externalValue:a,inputChange:e,placeholder:t.t(n?"Search":"Search Chats"),onlyIcon:!s,onOpen:p})]}),[t,n,p,e,i,s,a,o]),f=!s,v=D.useMemo(()=>[{icon:n?"icon-line-message-alert-plus":"icon-line-plus-01",text:t.t("New Chat"),type:"button",visible:!0,mobileVisible:!0,onClick:m,isNew:!0},{icon:"icon-line-search-01",text:t.t("Search"),type:"search",visible:!0,mobileVisible:!1},{icon:"icon-line-folder-01",text:t.t("My Library"),type:"library",visible:!0,mobileVisible:!0}],[m,t,n]);return F.jsx("div",{className:Q("sidebar-entry-fixed-list",{"sidebar-entry-fixed-list-only-icon":f}),children:v.map((e,t)=>{const{icon:s="",text:i="",type:a="",visible:o,mobileVisible:r,isNew:l=!1,onClick:m=()=>{},hideIcon:p=!1,id:v=""}=e,y=`${a}_${s}_${t}`;return o||n?!r&&n?F.jsx(D.Fragment,{},y):"search"===a?F.jsx(D.Fragment,{children:g},y):u&&!l?null:"library"===a?c&&d.length?F.jsx(D.Fragment,{children:F.jsx(Pf,{})},y):null:F.jsxs("div",{onClick:m,className:Q("sidebar-entry-fixed-list-content",{"sidebar-entry-list-content-hide-icon":p&&f,"sidebar-entry-list-content-mobile":n}),style:{opacity:.4,cursor:"not-allowed"},ref:h,children:[F.jsx(pi,{type:s,className:"sidebar-entry-fixed-list-icon"}),F.jsxs("div",{className:Q("sidebar-entry-fixed-list-text",{"sidebar-entry-fixed-list-text-hidden":f}),children:[F.jsx("div",{id:`${Kp}_${v}`}),i]})]},y):F.jsx(D.Fragment,{},y)})})}),Of=e=>{const t="x-oss-process=image/resize,m_mfit,w_320,h_320";return e.includes("qwen-webui")||"ico"===LR(e)?e:e.includes("?")?`${e}&${t}`:`${e}?${t}`},Df=(e,t=!1)=>{let n="x-oss-process=video/snapshot,t_0,w_0,h_500,f_jpg";t&&(n="x-oss-process=video/snapshot,t_0,w_0,h_0,f_jpg,m_fast");return e.includes("cdn.qwenlm.ai")?`${e}${e.includes("?")?"&":"?"}${n}`:""};var Ff=(e=>(e.PDF="pdf",e.WEBPAGE="web_page",e.PODCAST="podcast",e.SLIDES="slides",e))(Ff||{}),qf=(e=>(e.FINISH="finish",e.GEN_PROCESS="generation_process",e.GEN_ERROR="generation_failed",e.GEN_PAUSE="generation_pause",e.PLAY_FAIl="play_failed",e))(qf||{});const Uf=()=>document.documentElement.classList.contains("mobile"),Hf=()=>{const[e,t]=D.useState(Uf());return D.useEffect(()=>{const e=new MutationObserver(()=>{t(Uf())});return e.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>{e.disconnect()}},[]),{mobile:e}},Bf=1e3,zf=D.memo(e=>{const{placeholder:t="",maxRows:n=4,minRows:s=1}=e,{mobile:i}=Hf(),[a,o]=D.useState(""),[r,l]=D.useState(1===s),c=D.useRef(null),d=D.useRef(null),u=D.useRef(null),h=D.useRef(0),m=D.useCallback(t=>{var n;const s=t.target.value;o(s),null==(n=e.onChange)||n.call(e,t.target.value)},[e]);return D.useEffect(()=>{var t;o(null!=(t=e.value)?t:"")},[e.value]),D.useEffect(()=>{var e,t,n,a;if(!(null==(t=null==(e=c.current)?void 0:e.resizableTextArea)?void 0:t.textArea)||!d.current||!u.current||i)return;d.current.style.font=window.getComputedStyle(null==(a=null==(n=c.current)?void 0:n.resizableTextArea)?void 0:a.textArea).font,h.current=c.current.resizableTextArea.textArea.getBoundingClientRect().width-u.current.getBoundingClientRect().width,d.current.style.width=h.current-6+"px";const o=new ResizeObserver(e=>{for(const t of e){const{height:e}=t.contentRect;l(!(e<25&&1===s))}});return o.observe(d.current),()=>{o.disconnect()}},[i]),D.useEffect(()=>{d.current&&(d.current.innerText=a)},[a,d.current]),F.jsxs("div",{className:"bad-feedback-textarea "+(r?"bad-feedback-textarea-overlapping":""),children:[F.jsx(K.TextArea,{ref:c,maxLength:Bf,placeholder:t,value:a,onChange:m,autoSize:{maxRows:n,minRows:s}}),F.jsxs("div",{className:Q("bad-feedback-textarea-count",{"bad-feedback-textarea-count-position":!r&&!i,"bad-feedback-textarea-count-error":a.length>=Bf}),children:[i?null:F.jsx("span",{ref:d,className:"bad-feedback-textarea-count-text"}),F.jsxs("div",{ref:u,children:[a.length,"/",Bf]})]})]})}),Gf=({className:e,header:t=!0,title:n,defaultContents:s,contents:i=[],contentsWithGroup:a=[],placeholder:o,submitBtnText:r,defaultText:l,onCancel:c,onSubmit:d,feedbackAreaProps:u,submitButtonProps:h})=>{const[m,p]=D.useState(s),[g,f]=D.useState(l),v=D.useMemo(()=>i.length>0?[{title:"",content:i}]:a,[i,a]);D.useEffect(()=>{},[v]);const y=D.useCallback(e=>{p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),b=D.useCallback((e,t)=>F.jsxs("div",{className:"qwen-chat-package-comp-bad-feedback-content-group",children:[t&&F.jsx("div",{className:"qwen-chat-package-comp-bad-feedback-content-item-title",children:t}),F.jsx("div",{className:"qwen-chat-package-comp-bad-feedback-contents",children:null==e?void 0:e.map(e=>F.jsx("div",{className:"qwen-chat-package-comp-bad-feedback-content-item "+(m.includes(e.value)?"qwen-chat-package-comp-bad-feedback-content-item-active":""),onClick:()=>{y(e.value)},children:e.label},e.value))})]}),[y,m]);return F.jsxs("div",{className:`qwen-chat-package-comp-bad-feedback ${e||""}`,children:[t&&F.jsxs("div",{className:"qwen-chat-package-comp-bad-feedback-top",children:[F.jsx("div",{className:"qwen-chat-package-comp-bad-feedback-title",children:n}),F.jsx("div",{className:"qwen-chat-package-comp-bad-feedback-close",onClick:c,children:F.jsx(pi,{type:"icon-line-x-03",className:"qwen-chat-package-comp-bad-feedback-close-icon"})})]}),F.jsx("div",{className:"qwen-chat-package-comp-bad-feedback-content",children:(null==v?void 0:v.length)>0&&v.map(e=>b(e.content||[],e.title))}),F.jsxs("div",{className:"qwen-chat-package-comp-bad-feedback-foot",children:[F.jsx(zf,C({placeholder:o,onChange:f,value:g},u)),F.jsx(xi,S(C({type:"brandprimary",rounded:"circle",size:"small",disabled:0===m.length&&0===g.trim().length,buttonClass:"qwen-chat-package-comp-bad-feedback-submit",onClick:()=>{d(m,g)}},h),{children:r}))]})]})};var $f=(e=>(e.step="step",e.sources="sources",e))($f||{}),Wf=(e=>(e.deep_research="deep_research",e.image_tool="image_zoom_in_tool",e.code_interpreter="code_interpreter",e))(Wf||{}),Vf=(e=>(e.text="cardStepText",e.markdown="cardStepMarkdown",e.list="cardStepList",e.custom="custom",e))(Vf||{}),Qf=(e=>(e.process="process",e.finish="finish",e))(Qf||{}),Kf=(e=>(e.large="large",e.medium="medium",e.small="small",e))(Kf||{});const Yf=(e=[],t)=>e.map(e=>{let n=e.type;return n="function"==typeof t?t(n,e.url):"web",{url:e.url,title:e.title,snippet:e.description,hostlogo:e.icon,index_number:e.index_number,fileType:n}}),Jf={browser_take_screenshot:"browser_take_screenshot",browser_snapshot:"browser_snapshot"};var Xf=(e=>(e.normal="normal",e.simple="simple",e))(Xf||{}),Zf=(e=>(e.pdf="pdf",e.md="markdown",e.image="image",e))(Zf||{}),ev=(e=>(e.content="content",e.container="container",e))(ev||{}),tv=(e=>(e.translate="translate",e.copy="copy",e.ask="ask",e.explain="explain",e))(tv||{});const nv=({onNextClick:e,onPreviousClick:t,curSiblingsIndex:n,maxSiblings:s})=>{const i=null!=n?n:0,a=null!=s?s:0;return F.jsxs("div",{className:"qwen-chat-ui-packages-siblings",children:[F.jsx(pi,{type:"icon-line-chevron-left",className:"qwen-chat-ui-packages-siblings-active-icon "+(i<=1?"qwen-chat-ui-packages-siblings-disable-icon":""),onClick:t}),F.jsxs("div",{className:"qwen-chat-ui-packages-siblings-text",children:[i,"/",a]}),F.jsx(pi,{type:"icon-line-chevron-right",className:"qwen-chat-ui-packages-siblings-active-icon "+(i>=a?"qwen-chat-ui-packages-siblings-disabled-icon":""),onClick:e})]})},sv=e=>{const{src:t,shrinkSrc:n,cardId:s,itemType:i,isMyPublished:a=!1,ratioDefault:o=!1,onError:r,size:l,reloadLayout:c,mobile:d=!1,isAndroid:u,onClick:h}=e,m=l?l[1]/l[0]:null,[p,g]=D.useState(!0),[f,v]=D.useState("1 / 1"),[y,b]=D.useState("1 / 1"),x=D.useMemo(()=>m?m>2?"2 / 1":m<.5?"1 / 2":`${m}`:"1 / 1",[m]),w=D.useCallback((e,t)=>o?"1 / 1":m?m>2?"2 / 1":m<.5?"1 / 2":`${m}`:e>2*t?"2 / 1":t>2*e?"1 / 2":`${e} / ${t}`,[m,o]);return D.useEffect(()=>{A(null,null,function*(){try{const e=(e,t)=>new Promise((n,s)=>{const i=new window.Image;i.src=e,i.onload=()=>{null==t||t(w(i.width,i.height)),n(i),c&&c()},i.onerror=e=>s(e)});yield Promise.all([e(t,v),n&&e(n,b)]),g(!1)}catch(e){g(!1),r&&r()}})},[t,n,w,c,r]),p?F.jsx("div",{className:"item-card-loading",children:F.jsx("div",{className:"item-card-loading-img",style:{aspectRatio:l?x:"1 / 1"}})}):F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"qwen-chat-water-fall-image-container qwen-chat-community-exp-item",style:{aspectRatio:f,backgroundImage:`url(${t})`},"data-id":s,"data-type":i,"data-isMyPublished":a?"yes":"not",onClick:t=>{t.stopPropagation(),null==h||h(e)}}),n&&F.jsx("div",{className:Q("qwen-chat-water-fall-image-shrink-entry-container",{"qwen-chat-water-fall-image-shrink-entry-container-android":u&&u()&&d}),onClick:()=>{null==h||h(e)},style:{aspectRatio:y,backgroundImage:`url(${n})`}})]})},iv=e=>{const{description:t,icon:n,type:s="alert"}=e,{mobile:i}=Hf(),a=`qwen-${s}`,o=i?"qwen-messsage-status-mobile":"qwen-messsage-status",r=Q(o,a),l=n||F.jsx(pi,{type:"icon-line-information-circle"});return F.jsxs("div",{className:r,children:[F.jsx("div",{className:`${o}-icon ${a}-icon`,children:l}),F.jsx("div",{className:`${o}-content ${a}-content`,children:F.jsx("div",{className:`${o}-description ${a}-description`,children:t})})]})},av=e=>{const{isMobile:t=!1,failedText:n="Preview failed",emptyText:s="No HTML, CSS, or JavaScript content found."}=e;return F.jsx(F.Fragment,{children:t?F.jsxs("div",{className:"artifact-error-container",children:[F.jsx("div",{className:"artifact-error-icon-wrap",children:F.jsx(pi,{type:"icon-line-package-fail-02",className:"artifact-error-icon"})}),F.jsx("div",{className:"artifact-error-title",children:n}),F.jsx("div",{className:"artifact-error-text",children:s})]}):F.jsx("div",{className:"artifact-error-container",children:F.jsx("div",{className:"artifact-error-content",children:F.jsx("div",{className:"error-message",children:s})})})})},ov=({loadingText:e})=>F.jsxs("div",{className:"native-drawer-content-layout-loading",children:[F.jsx("div",{className:"native-drawer-content-layout-icon",children:F.jsx(Ui,{className:"loading-icon",type:"primary",borderWidth:3})}),F.jsx("span",{className:"loading-text",children:e})]}),rv=e=>{const{loadingText:t="Loading..."}=e,{mobile:n}=Hf();return n?F.jsx(ov,{loadingText:t}):F.jsx("div",{className:"artifact-loading-container",children:F.jsx("img",{width:40,src:"https://img.alicdn.com/imgextra/i3/O1CN01zaxxvj1p4f0VrY17j_!!6000000005307-54-tps-180-180.apng",alt:"Loading..."})})},lv=()=>document.documentElement.classList.contains("dark")?"dark":"light",cv=()=>{const[e,t]=D.useState(lv()),n=D.useRef(e);return D.useEffect(()=>{const e=new MutationObserver(()=>{const e=lv();e!==n.current&&t(e),n.current=e});return e.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>{e.disconnect()}},[]),{theme:e}},dv=({imgUrl:e,type:t,status:n,theme:s})=>{const i=D.useCallback(e=>{switch(e){case Ff.PDF:return"dark"===s?"https://img.alicdn.com/imgextra/i2/O1CN01LFIH8Y1MjlicfDy3C_!!6000000001471-2-tps-552-552.png":"https://img.alicdn.com/imgextra/i4/O1CN01Ivqk3o23lAPDpFToE_!!6000000007295-2-tps-552-552.png";case Ff.WEBPAGE:return"dark"===s?"https://img.alicdn.com/imgextra/i3/O1CN01s4sL9m1jTxCnIJJ6l_!!6000000004550-2-tps-552-552.png":"https://img.alicdn.com/imgextra/i1/O1CN015pfFXZ1nSogVW1rjh_!!6000000005089-2-tps-552-552.png";case Ff.PODCAST:return"dark"===s?"https://img.alicdn.com/imgextra/i2/O1CN0185O7jh1JB0obPfl81_!!6000000000989-2-tps-552-552.png":"https://img.alicdn.com/imgextra/i4/O1CN01PbZ8bx1SaxnaQvWyq_!!6000000002264-2-tps-552-552.png";case Ff.SLIDES:return"dark"===s?"https://img.alicdn.com/imgextra/i2/O1CN01pwr1XK28H0PtMJdL8_!!6000000007906-2-tps-552-552.png":"https://img.alicdn.com/imgextra/i3/O1CN01zu0a191qLRAIldTzS_!!6000000005479-2-tps-552-552.png";default:return""}},[s]),a=D.useMemo(()=>{const e={[qf.FINISH]:"",[qf.GEN_PROCESS]:"",[qf.GEN_PAUSE]:"",[qf.GEN_ERROR]:"",[qf.PLAY_FAIl]:""};switch(e[qf.FINISH]=i(t),t){case Ff.WEBPAGE:e[qf.GEN_PROCESS]="https://img.alicdn.com/imgextra/i2/O1CN01DL5Pcb1HGODERKCSf_!!6000000000730-2-tps-176-176.png",e[qf.GEN_PAUSE]="https://img.alicdn.com/imgextra/i4/O1CN01lla8Lz24Ce9FXziKw_!!6000000007355-2-tps-176-176.png",e[qf.GEN_ERROR]="https://img.alicdn.com/imgextra/i4/O1CN01RYk0vW1RW5wzwaneq_!!6000000002118-2-tps-176-176.png";break;case Ff.PODCAST:e[qf.GEN_PROCESS]="https://img.alicdn.com/imgextra/i3/O1CN01KAHTZi27xlkIHJZu0_!!6000000007864-2-tps-176-176.png",e[qf.GEN_PAUSE]="https://img.alicdn.com/imgextra/i3/O1CN01HXJev01UK8SNVvCZR_!!6000000002498-2-tps-192-192.png",e[qf.GEN_ERROR]="https://img.alicdn.com/imgextra/i1/O1CN01rnlC1b1gpzOObSpc4_!!6000000004192-2-tps-192-192.png";break;case Ff.SLIDES:e[qf.GEN_PROCESS]="https://img.alicdn.com/imgextra/i3/O1CN01d95JbO1n8CsORZwak_!!6000000005044-2-tps-176-176.png",e[qf.GEN_PAUSE]="https://img.alicdn.com/imgextra/i1/O1CN01dre1fc1fWSvci4jvZ_!!6000000004014-2-tps-176-176.png",e[qf.GEN_ERROR]="https://img.alicdn.com/imgextra/i2/O1CN01QgkVBy1QhG1ZygQCB_!!6000000002007-2-tps-176-176.png"}return e[n]},[t,n,i]);return F.jsx("div",{className:"attachment-card-illustration",children:F.jsx("img",{src:e||a})})},uv=({name:e,size:t,skeletonLoading:n,skeletonActive:s,type:i})=>F.jsxs("div",{className:"attachment-card-info",children:[F.jsx(re,{active:s,title:!1,paragraph:{rows:2,width:"100%"},loading:n,children:F.jsx("div",{className:"attachment-card-title",children:e})}),i!==Ff.WEBPAGE&&F.jsx(re,{active:s,title:!1,paragraph:{rows:1,width:"88px"},loading:n,children:F.jsx("div",{className:"attachment-card-size",children:t})})]}),hv=({disabled:e,play:t,onPlayChange:n})=>{const[s,i]=D.useState(!1);D.useEffect(()=>{void 0!==t&&i(t)},[t]);return F.jsx("div",{className:Q("attachment-card-play-button",{"attachment-card-play-button-disabled":e}),onClick:()=>{i(!s),null==n||n(!s)},children:s?F.jsx(pi,{type:"icon-zanting-pause-fill",className:"attachment-card-play-button-icon-play"}):F.jsx(pi,{type:"icon-fill-play-03"})})},mv=({disabled:e,skipValue:t,onValueChange:n})=>{const{mobile:s}=Hf(),[i,a]=D.useState(0);D.useEffect(()=>{void 0!==t&&t!==i&&a(t)},[t]);const[o,r]=D.useState(!1);return F.jsx("div",{className:Q("attachment-card-audio",{"attachment-card-audio-pc":!s,"attachment-card-audio-touch":o}),onTouchStartCapture:()=>{r(!0)},onTouchEndCapture:()=>{r(!1)},children:F.jsx(se,{tooltip:{open:!1},disabled:e,classNames:{root:"attachment-card-audio-slider",handle:"attachment-card-audio-handle",track:"attachment-card-audio-track",rail:"attachment-card-audio-rail"},value:i,onChange:e=>{a(e),null==n||n(e)}})})},pv=({time:e,skeletonActive:t,skeletonLoading:n})=>F.jsx(re,{active:t,title:!1,paragraph:{rows:1,width:"88px"},loading:n,children:F.jsx("div",{className:"attachment-card-time",children:Pe(e)?qe(e).format("HH:mm"):e})}),gv=({status:e,tipTexts:t})=>{const n=D.useMemo(()=>e===qf.GEN_ERROR,[e]),s=D.useMemo(()=>e===qf.GEN_PROCESS,[e]),i=D.useMemo(()=>e===qf.PLAY_FAIl,[e]);return n||s||i?F.jsxs("div",{className:"attachment-card-tips",children:[i&&(null==t?void 0:t.palyErrorText)&&F.jsx("div",{className:"attachment-card-tips-error",children:t.palyErrorText}),n&&t.errorText&&F.jsx("div",{className:"attachment-card-tips-error",children:t.errorText}),s&&t.loadingText&&F.jsx("div",{className:"attachment-card-tips-loading",children:t.loadingText})]}):null},fv=({iconClass:e,menu:t,downLoadIcon:n,onSelect:s})=>F.jsx(Ci,{menu:{items:t,onClick:({key:e})=>{s&&s(e)}},trigger:["click"],children:n||F.jsx(pi,{type:"icon-download",className:e})}),vv=e=>{var t=e,{onDownload:n,dType:s=Xf.simple,downloadMenu:i,downLoadIcon:a,iconClass:o}=t,r=k(t,["onDownload","dType","downloadMenu","downLoadIcon","iconClass"]);return s===Xf.simple?F.jsx("span",S(C({onClick:(l=Zf.pdf,e=>{e.stopPropagation(),n&&n(l)})},r),{children:a||F.jsx(pi,{type:"icon-download",className:o})})):s===Xf.normal&&i?F.jsx("span",S(C({onClick:e=>e.stopPropagation()},r),{children:F.jsx(fv,{downLoadIcon:a,menu:i,iconClass:o,onSelect:n})})):null;var l},yv=({speeds:e,currentSpeed:t,onChange:n,disabled:s})=>{const[i,a]=D.useState(t);D.useEffect(()=>{void 0!==t&&a(t)},[t]);const o=D.useMemo(()=>F.jsx("div",{className:"attachment-card-speed-dropdown",children:null==e?void 0:e.map(e=>F.jsxs("div",{className:"attachment-card-speed-menu "+(i===e?"attachment-card-speed-menu-active":""),onClick:()=>{a(e),null==n||n(e)},children:[e.toFixed(1),"x"]},e))}),[e,i,n]),r=D.useMemo(()=>F.jsxs("span",{className:Q("attachment-card-icon attachment-card-icon-speed",{"attachment-card-icon-disabled":s}),children:[F.jsx("span",{className:"attachment-card-icon-speed-text",children:i}),"x"]}),[i,e]);return s?r:F.jsx(le,{trigger:["click"],classNames:{root:"language-menu-popover"},placement:"top",title:null,content:o,arrow:!1,children:r})},bv=({toolsOption:e,disabled:t,downloadInfo:n})=>{var s,i,a,o,r,l,c,d,u,h,m;const{loofOver:p,download:g,media:f,beforeExtras:v,afterExtras:y}=e,b=D.useCallback(()=>{var e,t;null==(t=null==(e=null==f?void 0:f.audioButtonConfig)?void 0:e.onForward)||t.call(e,15)},[null==(s=null==f?void 0:f.audioButtonConfig)?void 0:s.onForward]),x=D.useCallback(()=>{var e,t;null==(t=null==(e=null==f?void 0:f.audioButtonConfig)?void 0:e.onRewind)||t.call(e,15)},[null==(i=null==f?void 0:f.audioButtonConfig)?void 0:i.onRewind]),w=D.useCallback(e=>{var t;null==(t=null==g?void 0:g.onDownload)||t.call(g,e,n)},[null==g?void 0:g.onDownload,n]);return F.jsxs("div",{className:"attachment-card-buttons",onClick:e=>{e.stopPropagation()},children:[v,f?F.jsxs(F.Fragment,{children:[F.jsx("span",{className:"attachment-card-botton",onClick:t?void 0:x,children:(null==(a=f.icons)?void 0:a.forward)?null==(o=f.icons)?void 0:o.forward:F.jsx(pi,{type:"icon-speed1",className:Q("attachment-card-icon",{"attachment-card-icon-disabled":t})})}),F.jsx("span",{className:"attachment-card-botton",onClick:t?void 0:b,children:(null==(r=f.icons)?void 0:r.rewind)?null==(l=f.icons)?void 0:l.rewind:F.jsx(pi,{type:"icon-speed",className:Q("attachment-card-icon",{"attachment-card-icon-disabled":t})})}),F.jsx("span",{className:"attachment-card-botton",children:(null==(c=f.icons)?void 0:c.speed)?null==(d=f.icons)?void 0:d.speed:F.jsx(yv,{speeds:null==(u=f.audioSpeedConfig)?void 0:u.speeds,currentSpeed:null==(h=f.audioSpeedConfig)?void 0:h.currentSpeed,onChange:null==(m=f.audioSpeedConfig)?void 0:m.onSpeedChange,disabled:t})})]}):null,p?F.jsx("span",{className:"attachment-card-botton",onClick:!(null==p?void 0:p.visible)&&t?void 0:p.onLookOver,children:p.icon?p.icon:F.jsx(pi,{type:"icon-eye-open",className:Q("attachment-card-icon",{"attachment-card-icon-disabled":!(null==p?void 0:p.visible)&&t})})}):null,g?F.jsx("span",{className:"attachment-card-botton",children:F.jsx(vv,{downLoadIcon:g.icon,dType:Xf.simple,iconClass:Q("attachment-card-icon",{"attachment-card-icon-disabled":t}),onDownload:w})}):null,y]})},xv=e=>{const{info:t,toolsOption:n,type:s,status:i=qf.FINISH,tipTexts:a,className:o}=e,{name:r,size:l,time:c,imgUrl:d,extra:u}=t,{theme:h}=cv(),m=D.useMemo(()=>i!==qf.FINISH,[i]),p=D.useMemo(()=>i===qf.GEN_PROCESS||i===qf.GEN_ERROR||i===qf.GEN_PAUSE,[i]),g=D.useMemo(()=>i===qf.GEN_PROCESS,[i]),f=D.useMemo(()=>{var e,t;if(n.media)return F.jsx("div",{className:"attachment-card-content-tools",children:F.jsx(hv,{disabled:m,onPlayChange:null==(t=null==(e=n.media)?void 0:e.audioButtonConfig)?void 0:t.onPlayChange})})},[n.media,m]),v=D.useCallback(e=>{const t=Math.floor(e/1048576*100)/100;return t>1?`${t}M`:Math.floor(e/1024*100)/100+"KB"},[]),y=D.useMemo(()=>{if(s===Ff.PODCAST&&n.media){const{currentSecondTime:e,secondDuration:t}=n.media;return`${e>=3600?qe(1e3*e).format("hh:mm:ss"):qe(1e3*e).format("mm:ss")} / ${t>=3600?qe(1e3*t).format("hh:mm:ss"):qe(1e3*t).format("mm:ss")}`}return l?v(l):""},[s,n.media,l,v]),b=D.useMemo(()=>F.jsxs("div",{className:"attachment-card-content",children:[F.jsx(dv,{imgUrl:d,type:s,status:i,theme:h}),F.jsx(uv,{name:r,type:s,size:y,skeletonLoading:p,skeletonActive:g}),f]}),[h,r,y,d,s,f,i,p,g]),x=D.useMemo(()=>Pe(c)&&s===Ff.SLIDES?qe(c).format("MMMM DD HH:mm"):c,[c,s]),w=D.useMemo(()=>F.jsxs("div",{className:"attachment-card-footer",children:[F.jsx(pv,{time:x,skeletonLoading:p,skeletonActive:g}),n&&F.jsx(bv,{toolsOption:n,disabled:m,downloadInfo:u})]}),[u,x,n,g,m,p]),_=D.useMemo(()=>{const{media:e}=n||{};if(s!==Ff.PODCAST||!e)return null;const{audioSliderConfig:t}=e||{},{skipValue:i,onAudioSliderValueChange:a}=t||{};return F.jsx(mv,{disabled:m,skipValue:i,onValueChange:a})},[s,n,m]),C=D.useMemo(()=>a?F.jsx(gv,{status:i,tipTexts:a}):null,[a,i]),S=D.useMemo(()=>({components:{Skeleton:{gradientFromColor:""+("dark"===h?"rgba(95,96,108,0.6)":"rgba(241,242,248,0.6)"),gradientToColor:""+("dark"===h?"rgba(95,96,108,1)":"rgba(241,242,248,1)"),paragraphLiHeight:20,blockRadius:4},Slider:{handleSize:10,dotSize:10,handleLineWidth:0,handleLineWidthHover:0,handleSizeHover:0,railSize:3,handleActiveOutlineColor:"rgba(22,119,255,0)",railBg:"#F1F2F8",railHoverBg:"#F1F2F8",trackBg:""+("dark"===h?"#8583F6":"#615CED"),trackHoverBg:""+("dark"===h?"#8583F6":"#615CED"),handleColor:""+("dark"===h?"#8583F6":"#615CED"),trackBgDisabled:""+("dark"===h?"#5F606C":"#F1F2F8")}}}),[h]);return F.jsx(ce,{theme:S,children:F.jsxs("div",{className:Q("attachment-card-container",o,{"attachment-card-container-click":!!e.onCardClick}),onMouseDown:e=>e.preventDefault(),onClick:t=>{var n;t.stopPropagation(),null==(n=e.onCardClick)||n.call(e,t)},children:[b,C,_,w]})})},wv=D.memo(({endTime:e,timestamp:t,loading:n})=>{const[s,i]=D.useState(""),[a,o]=D.useState(0),r=D.useRef(null),l=D.useCallback(()=>{const e=Date.now()/1e3;o(e),window._currentTime=e,r.current=setInterval(()=>{const e=Date.now()/1e3;window._currentTime=e,o(e)},1e3)},[]),c=D.useCallback(()=>{r.current&&(clearInterval(r.current),r.current=null)},[]);D.useEffect(()=>(n?r.current||l():c(),()=>{c()}),[n,l,c]);const d=D.useCallback(e=>{let t=e;const n=Math.floor(t/36e5);t-=36e5*n;const s=Math.floor(t/6e4);t-=6e4*s;const i=Math.floor(t/1e3);return`${n?JSON.stringify(n)+"h":""}${s?JSON.stringify(s)+"m":""}${i?JSON.stringify(i)+"s":""}`},[]);return D.useEffect(()=>{if(n){if(void 0!==t){const e=d(1e3*Math.abs(a-t));i(e)}}else if(void 0!==e&&void 0!==t){const n=d(1e3*Math.abs(e-t));i(n)}},[e,t,n,a,d]),e||a?F.jsx("span",{children:s}):null}),_v=({endTime:e,timestamp:t,loading:n,searchTitle:s,className:i,showTime:a=!1})=>{const{mobile:o}=Hf();return F.jsxs("div",{className:Q("deep-research-top-left",i),children:[!o&&F.jsx("span",{className:"deep-research-top-left-icon",children:F.jsx(pi,{type:"icon-line-deepresearch-02",className:"deep-research-top-left-icon deep-research-top-left-icon-20"})}),F.jsx("span",{className:"deep-research-text "+(n?"text-shine-loading":""),children:s}),a&&F.jsxs("div",{className:"deep-research-text-time",children:[F.jsx("div",{className:"deep-research-text-time-dot"}),F.jsx("div",{className:"deep-research-text-time-content",children:F.jsx(wv,{endTime:e,timestamp:t,loading:n})})]})]})},Cv=({icon:e="",style:t={},className:n=""})=>{const[s,i]=D.useState(!!e);return D.useEffect(()=>{i(!!e)},[e]),F.jsx("div",{className:`sources-icon ${n}`,style:t,children:s?F.jsx("img",{src:e,alt:"",onError:()=>{i(!1)}}):F.jsx(pi,{type:"icon-line-paperclip-01"})})},Sv=e=>{var t=e,{webSites:n=[],lastIndex:s=3,className:i="",onLinkCard:a}=t,o=k(t,["webSites","lastIndex","className","onLinkCard"]);const r=D.useMemo(()=>n.slice(0,s),[n,s]),{mobile:l}=Hf(),c=D.useMemo(()=>n.slice(s).map(e=>e.icon),[n,s]);return l?n.length>0?F.jsx("div",S(C({className:`link-card-container-mobile${i}`},o),{children:n.map((e,t)=>F.jsxs("div",{className:"link-card-item-mobile",onClick:()=>a&&a(e),children:[F.jsx("div",{className:"link-card-item-title-mobile",children:e.title}),F.jsxs("div",{className:"link-card-item-footer-mobile",children:[F.jsx(Cv,{icon:e.icon}),e.iconDesc&&F.jsx("span",{className:"sources-desc",children:e.iconDesc||""})]})]},t))})):null:F.jsxs("div",S(C({className:`link-card-container ${i}`},o),{children:[r.map((e,t)=>F.jsxs("div",{className:"link-card-item",onClick:()=>a&&a(e),children:[F.jsx(Cv,{icon:e.icon}),F.jsx("div",{className:"link-card-item-title",children:e.title})]},t)),n.length>s&&F.jsxs("div",{className:"total-card",onClick:()=>a&&a(n),children:[F.jsx("div",{className:"icon-list",children:c.map((e,t)=>F.jsx(Cv,{icon:e,style:t>1?{marginTop:"4px"}:{}},t))}),F.jsxs("div",{children:["+",n.length-r.length]})]})]}))},kv=({icon:e="",style:t="",className:n=""})=>{const{mobile:s}=Hf();return F.jsx("div",{className:`${s?"sources-icon-mobile":"sources-icon"} ${n}`,style:C({},t||{}),children:e?F.jsx("img",{src:e,alt:""}):F.jsx(pi,{type:"icon-line-paperclip-01"})})},jv=({site:e,onLinkCard:t})=>F.jsxs("div",{className:"link-list-item",onClick:()=>{null==t||t(e)},children:[F.jsx("div",{className:"link-list-item-source",children:F.jsx(kv,{icon:e.icon})}),F.jsx("div",{className:"link-list-item-title",children:e.title}),F.jsx("div",{className:"link-list-item-right",children:F.jsx(pi,{type:"icon-line-arrow-up-right-dp",className:"link-list-item-icon"})})]},e.url),Tv=({webSites:e=[],onLinkCard:t})=>{const{mobile:n}=Hf();return n?F.jsx("div",{className:"link-list-container",children:F.jsx("div",{className:"link-list-items",children:e.map((e,n)=>F.jsx(jv,{site:e,onLinkCard:t},`${e.url}+ ${e.title} + ${n}`))})}):F.jsxs("div",{className:"link-list-container",children:[F.jsx("div",{className:"link-list-items",children:e.filter((e,t)=>t%2==0).map((e,n)=>F.jsx(jv,{site:e,onLinkCard:t},`${e.url}+ ${e.title} + ${n}`))}),F.jsx("div",{className:"link-list-items-right"}),F.jsx("div",{className:"link-list-items",children:e.filter((e,t)=>t%2==1).map((e,n)=>F.jsx(jv,{site:e,onLinkCard:t},`${e.url}+ ${e.title} + ${n}`))})]})};let Ev=class{constructor(){j(this,"taskId",null),j(this,"taskTime",null),j(this,"isRunning",!1),j(this,"executor"),j(this,"clearExecutor"),j(this,"addTask",e=>{if(this.isRunning)return this.taskId&&this.removeTask(this.taskId),this.taskTime=this.getTime(),this.taskId=this.executor(()=>{(()=>{A(this,null,function*(){return this.taskId=null,yield e()})})()}),this.taskId}),j(this,"removeTask",e=>this.clearExecutor(e)),j(this,"getTime",()=>{var e,t;return(null==(t=null==(e=window.performance)?void 0:e.now)?void 0:t.call(e))||Date.now()}),j(this,"stopScheduler",()=>{this.isRunning=!1,this.taskId&&(this.removeTask(this.taskId),this.taskId=null)}),this.taskId=null,this.isRunning=!0,"function"==typeof requestAnimationFrame&&"function"==typeof cancelAnimationFrame?(this.executor=requestAnimationFrame.bind(window),this.clearExecutor=cancelAnimationFrame.bind(window)):(this.executor=e=>setTimeout(e,17),this.clearExecutor=clearTimeout)}};const Nv=(e,t)=>{e.forEach(e=>{var n,s,i,a;const o=e;o.status=t,(null==(n=o.tokens)?void 0:n.length)&&Nv(o.tokens,t),(null==(s=o.items)?void 0:s.length)&&o.items.forEach(e=>{var n;(null==(n=e.tokens)?void 0:n.length)&&Nv(e.tokens,t)}),(null==(i=o.header)?void 0:i.length)&&o.header.forEach(e=>{var n;(null==(n=e.tokens)?void 0:n.length)&&Nv(e.tokens,t)}),(null==(a=o.rows)?void 0:a.length)&&o.rows.forEach(e=>{e.forEach(e=>{var n;(null==(n=e.tokens)?void 0:n.length)&&Nv(e.tokens,t)})})})};let Iv=class{constructor(e){j(this,"scheduler"),j(this,"parser"),j(this,"options"),j(this,"isRunning",!1),j(this,"tokens",[]),j(this,"unConfirmedTokens",[]),j(this,"content",""),j(this,"allParsedContent",""),j(this,"executeParse",()=>A(this,null,function*(){const e=this.getParsedTokensString(),t=this.getUnConfirmedTokensString();if(`${e}${t}`===this.content)return;const n=t.length{this.options.debug}),this.parser=e.parser,this.scheduler=new Ev,this.isRunning=!0,this.options={parser:e.parser,singleChunkSize:e.singleChunkSize||200,debug:e.debug||!1,onTokenUpdate:e.onTokenUpdate||(()=>A(this,null,function*(){}))}}updateContent(e){this.log("StreamMDParser.updateContent:content",e);const t=this.getParsedTokensString();e.includes(t)?this.content=e:(this.content=e,this.tokens=[],this.unConfirmedTokens=[],this.allParsedContent=""),this.scheduleParse()}destroy(){this.isRunning=!1,this.scheduler.stopScheduler()}scheduleParse(){this.isRunning&&this.content!==this.allParsedContent&&this.scheduler.addTask(this.executeParse)}getParsedTokensString(){return this.tokens.reduce((e,t)=>e+t.raw,"")}getUnConfirmedTokensString(){return this.unConfirmedTokens.reduce((e,t)=>e+t.raw,"")}updateResult(e){return A(this,null,function*(){let t=3,n=e.slice(-t);for(;t-n.filter(e=>"space"===e.type).length<3;)t++,n=e.slice(-t);this.unConfirmedTokens=n;const s=e.filter(e=>!this.unConfirmedTokens.includes(e));this.tokens.push(...s),Nv(this.unConfirmedTokens,"animation"),this.log("StreamMDParser.tokens:tokens,unConfirmedTokens",JSON.parse(JSON.stringify(this.tokens)),this.unConfirmedTokens);try{const e=[...this.tokens,...this.unConfirmedTokens];if(!this.isRunning)return;yield this.options.onTokenUpdate(e,this.content)}catch(i){}})}},Av=class{constructor(e){var t,n,s,i;if(j(this,"options"),j(this,"parallelData",[]),this.options={parser:e.parser,singleChunkSize:null!=(t=e.singleChunkSize)?t:1e3,onTokenUpdate:null!=(n=e.onTokenUpdate)?n:()=>A(this,null,function*(){}),debug:null!=(s=e.debug)&&s,separator:null!=(i=e.separator)?i:""},!this.options.separator)throw new Error("ParallelStreamParser: separator is required")}updateContent(e){if(!e.includes(this.options.separator))throw new Error("ParallelStreamParser: content must include separator");const t=e.split(this.options.separator).filter(e=>!!e).map((e,t)=>({index:t,content:e}));this.parallelData.length>t.length&&(this.parallelData=this.parallelData.slice(0,t.length)),t.forEach(e=>{const t=e.index,n=this.parallelData[t];if(n&&e.content.includes(n.content))return n.content=e.content,void n.parser.updateContent(e.content);n&&n.parser.destroy();const s=new Iv(S(C({},this.options),{onTokenUpdate:this.getUpdateTokenCallback(e.index)}));this.parallelData[t]={index:e.index,content:e.content,parser:s,tokens:[]},s.updateContent(e.content)})}destroy(){this.parallelData.forEach(e=>e.parser.destroy()),this.parallelData=[]}getUpdateTokenCallback(e){return(t,n,s)=>A(this,null,function*(){const i=this.parallelData.find(t=>t.index===e);i&&i.content===s&&(i.tokens=t,i.html=n),this.updateResult()})}updateResult(){return A(this,null,function*(){const e=this.parallelData.map(e=>e.tokens).flat(),t=this.parallelData.map(e=>e.html).join("");try{yield this.options.onTokenUpdate(e,t)}catch(n){}})}};const Mv="\\[\\[(\\s*\\d+\\s*(?:,\\s*\\d+\\s*)*)\\]\\]",Rv=[{left:"$$",right:"$$",display:!0},{left:"\\[",right:"\\]",display:!0},{left:"\\begin{equation}",right:"\\end{equation}",display:!0},{left:"$",right:"$",display:!1},{left:"\\(",right:"\\)",display:!1},{left:"\\pu{",right:"}",display:!1},{left:"\\ce{",right:"}",display:!1}],Pv=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),{inlineRuleTokenizer:Lv,blockRuleTokenizer:Ov,inlineRuleStart:Dv,blockRuleStart:Fv}=(e=>{const t=[],n=[];e.forEach(e=>{const{left:s,right:i,display:a}=e,o=Pv(s),r=Pv(i);a?(t.push(`${o}(?!\\n)((?:\\\\[^]|[^\\\\])+?)(?!\\n)${r}(?=\\s|\\W|$)`),n.push(`\\s*${o}\\n((?:\\\\[^]|[^\\\\])+?)\\n\\s*${r}`)):t.push(`${o}((?:\\\\[^]|[^\\\\])+?)${r}(?=\\s|\\W|$)`)});return{inlineRuleTokenizer:new RegExp(`^(${t.join("|")})`,"u"),blockRuleTokenizer:new RegExp(`^(${n.join("|")})`,"u"),inlineRuleStart:new RegExp(`(${t.join("|")})`,"u"),blockRuleStart:new RegExp(`(\\n${n.join("|")})`,"u")}})(Rv),qv=(e,t)=>{var n;const s=t?Fv:Dv;return null==(n=e.match(s))?void 0:n.index},Uv=(e,t,n)=>{const s=n?Ov:Lv,i=n?"blockLatex":"inlineLatex",a=e.match(s);if(a){let n=a[0],s=a.slice(2).filter(e=>e).find(e=>e.trim());const o=Rv.find(({left:e})=>n.indexOf(e)>-1);if(o){let t=n.indexOf(o.left,n.indexOf(o.left)+1),i=n.lastIndexOf(o.right);for(;t>-1&&tqv(e,!1),tokenizer:(e,t)=>Uv(e,t,!1)},{name:"blockLatex",level:"block",start:e=>qv(e,!0),tokenizer(e,t){const n=Uv(e,t,!0);if(!n){const n=qv(e,!0),s=e.slice(0,n),i=e.slice(n);if(!s.includes("\n")&&"number"==typeof n){const e=this.lexer.blockTokens(s);if(e){const n=Uv(i,[...t,...e],!0);if(n)return S(C({},n),{raw:s+n.raw,tokens:e})}}}return n}}],tokenizer:{del(){},url(){}}});const Bv=D.createContext({}),zv=Bv.Provider,Gv=()=>D.useContext(Bv),$v=e=>{var t,n,s;const{token:i,renderTokens:a}=e,{styleProps:o}=Gv(),r=null!=(t=null==o?void 0:o.showAnimation)&&t,[l,c]=D.useState([]),d=D.useRef(""),u=null!=(n=i.text)?n:"",h=null!=(s=null==i?void 0:i.status)?s:"",m=!!i.tokens;D.useEffect(()=>{if(!u||m||!r)return c([]),void(d.current=u||"");d.current!==u&&(c(e=>{let t=u,n=[...e];for(let s=0;s{if(!p)return null;let e=0;return l.map((t,n)=>{const s=e;return e+=t.length,F.jsx("span",{className:"animation-text",children:t},`animation-${s}-${n}`)})},[l,p]);return i.tokens?a(i.tokens):F.jsx("span",{className:"qwen-markdown-text",children:p?g:i.text})},Wv=e=>{const{token:t,renderTokens:n,headerActionsRender:s}=e;return F.jsxs("div",{className:"qwen-markdown-table-wrapper",children:[s&&F.jsx("div",{className:"qwen-markdown-table-header",children:s(t)}),F.jsx("div",{className:"qwen-markdown-table-scroll-wrapper",children:F.jsxs("table",{className:"qwen-markdown-table",children:[F.jsx("thead",{className:"qwen-markdown-table-thead",children:F.jsx("tr",{className:"qwen-markdown-table-thead-tr",children:t.header.map((e,s)=>F.jsx("th",{scope:"col",className:"qwen-markdown-table-thead-tr-th",style:{textAlign:t.align[s]},children:F.jsx("div",{className:"qwen-markdown-table-thead-tr-th-col",children:n(e.tokens)})},s))})}),F.jsx("tbody",{className:"qwen-markdown-table-tbody",children:t.rows.map((e,s)=>F.jsx("tr",{className:"qwen-markdown-table-tbody-tr",children:e.map((e,s)=>F.jsx("td",{className:"qwen-markdown-table-tbody-tr-td",style:{textAlign:t.align[s]},children:F.jsx("div",{className:"qwen-markdown-table-tbody-tr-td-col",children:n(e.tokens)})},s))},s))})]})})]})},Vv=e=>{const{token:t,renderTokens:n}=e;return F.jsx("strong",{className:"qwen-markdown-strong",children:t.tokens?n(t.tokens):t.text})},Qv=()=>F.jsx("div",{className:"qwen-markdown-space"}),Kv=e=>{const{token:t,renderTokens:n}=e;return F.jsx("div",{className:"qwen-markdown-paragraph",children:t.tokens?n(t.tokens):t.text})},Yv=e=>{const{token:t,renderTokens:n}=e,s=D.useMemo(()=>t.items.map((e,t)=>F.jsx("li",{children:n(e.tokens)},`${e.type}${t}`)),[t,n]);return t.ordered?F.jsx("ol",{className:"qwen-markdown-list",start:t.start||1,dir:"auto",children:s}):F.jsx("ul",{className:"qwen-markdown-list",dir:"auto",children:s})},Jv=/[\x00-\x1F\x7F-\x9F]/g,Xv=/^([a-z][a-z0-9+.-]*):/i,Zv=e=>e.replace(Jv,"").trim().toLowerCase(),ey=e=>e.startsWith("/")||e.startsWith("#")||e.startsWith("?")||e.startsWith("./")||e.startsWith("../"),ty=e=>{var t;if(!e)return!1;const n=Zv(e);if(!n)return!1;if(ey(n))return!0;const s=null==(t=n.match(Xv))?void 0:t[1];return!(!["http","https"].includes(s||"")&&!/^blob:https?:\/\//.test(n))||/^data:image\/(?:png|jpe?g|gif|webp|bmp);base64,[a-z0-9+/]+=*$/i.test(n)},ny=e=>Ze.sanitize(e,{USE_PROFILES:{svg:!0,svgFilters:!0},FORBID_TAGS:["foreignObject","script"],FORBID_ATTR:["href","xlink:href"]}),sy=e=>{const{token:t,renderTokens:n,onClick:s}=e,i=(e=>{var t;if(!e)return!1;const n=Zv(e);if(!n)return!1;if(ey(n))return!0;const s=null==(t=n.match(Xv))?void 0:t[1];return["http","https","mailto","tel","ftp"].includes(s||"")})(t.href)?t.href:void 0;return F.jsxs("a",{className:"qwen-markdown-link",href:i,target:"_blank",rel:"noreferrer",onClick:e=>{s&&(e.preventDefault(),s(t))},children:[t.tokens?n(t.tokens):t.text,F.jsx(pi,{className:"qwen-markdown-link-icon",type:"icon-line-arrow-up-right"})]})},iy=({width:e,height:t,sizeScope:n})=>{if(!n)return{width:e,height:t};const s=Array.isArray(n),i=s?[...n]:[...n.width],a=s?[...n]:[...n.height],o=e||i[1],r=t||a[1];let l=1;l=o>=r?o/i[1]:r/a[1];const c=(e,[t,n])=>e>n?n:e{const t=e,{skeletonUrl:n,iconUrl:s,percent:i,children:a,mode:o="generating"}=t,r=k(t,["skeletonUrl","iconUrl","percent","children","mode"]),l=D.useMemo(()=>n?S(C({},r.style),{backgroundImage:`url(${n})`}):r.style,[n,r.style]);return F.jsx("div",S(C({className:Q("qwen-media-skeleton",r.className,{default:!n})},r),{style:l,children:"generating"===o?F.jsxs(F.Fragment,{children:[s&&F.jsx("img",{className:"qwen-media-skeleton-icon",src:s,alt:""}),"number"==typeof i&&F.jsx("div",{className:"qwen-media-skeleton-progress",children:F.jsx(Fi,{percent:i,percentPosition:{type:"outer",align:"center"},trailColor:"rgba(255,255,255, 0.48)",strokeColor:"#fff"})})]}):a}))};let oy=1;const ry=D.memo(D.forwardRef((e,t)=>{const{url:n,thumbnailUrl:s="",defaultWidth:i=0,defaultHeight:a=0,width:o,height:r,loading:l=!0,error:c=!1,isStop:d=!1,preview:u,sizeScope:h,onLoad:m,onError:p,onSizeChange:g,onClick:f,controls:v={},widthPadding:y,heightPadding:b,hideImageClose:x,imageRenderStyle:w,imageRenderHeaderNode:_,currentPreviewUrl:k="",previewRootClassName:j=""}=e,{mobile:T}=Hf(),E=D.useMemo(()=>{const e=iy({width:o||i,height:r||a,sizeScope:h});return null==g||g(e),e},[o,i,r,a,h,g]),N=D.useMemo(()=>ty(n)?n:"",[n]),I=D.useMemo(()=>ty(s)?s:"",[s]),[A,M]=D.useState(I||N),[R,P]=D.useState(E.width),[L,q]=D.useState(E.height),[U,H]=D.useState(!0),[B,z]=D.useState(""),[G,$]=D.useState(!1),[W,V]=D.useState(!1),K=D.useRef(null),Y=D.useRef(R),J=D.useRef(L),X=D.useCallback(e=>{Y.current=e,P(e)},[]),Z=D.useCallback(e=>{J.current=e,q(e)},[]),ee=D.useCallback(()=>{try{const e=new URL(A,window.location.href);e.searchParams.delete("timestamp"),e.searchParams.append("timestamp",`${Date.now()}`),M(e.toString())}catch(e){H(!1),z(!0)}},[A]),te=D.useCallback(()=>{if(oy>0)return oy--,void setTimeout(()=>{ee()},500);if(oy=1,H(!1),p){const e=p();z((null==e?void 0:e.errorMessage)||!0)}else z(!0)},[p,ee]);D.useEffect(()=>{if(d){if(p){const e=p();z((null==e?void 0:e.errorMessage)||!0)}else z(!0);H(!1),null==m||m()}},[d]),D.useEffect(()=>{if(!(o||r||i||a))return;const e=iy({width:o||i,height:r||a,sizeScope:h});(Y.current!==e.width||J.current!==e.height)&&(X(e.width),Z(e.height),null==g||g(e))},[o,i,r,a,h,X,Z,g]);const ne=D.useCallback((e,t)=>{if(void 0!==t)return 2*t;if("width"===e){if(window.innerWidth>1440)return 496;if(window.innerWidth<=1440&&window.innerWidth>1024)return 324;if(window.innerWidth<=1024&&window.innerWidth>=768)return 216;if(window.innerWidth<768)return 0}return"height"===e?window.innerWidth<768?136:280:void 0},[]);D.useEffect(()=>{if(!N)return M(""),H(!1),void(l&&z(!0));H(!0),z(""),V(!1),M(I||N)},[l,I,N]),D.useEffect(()=>{c&&te()},[c,te]),D.useEffect(()=>{$((null==u?void 0:u.visible)&&N===k)},[k,null==u?void 0:u.visible,N]);const se=D.useMemo(()=>{if(!h)return{minWidth:0,minHeight:0};const e=Array.isArray(h),t=e?[...h]:[...h.width],n=e?[...h]:[...h.height];return{minWidth:`${t[0]}px`,minHeight:`${n[0]}px`}},[h]),ie="number"==typeof R?`${R}px`:R,ae="number"==typeof L?`${L}px`:L,oe=D.useMemo(()=>{if(i&&a)return{width:ie,height:ae};const e=C({maxWidth:ie,maxHeight:ae},se);return e.maxWidth===e.minWidth?C(C({width:ie},e),se):e.maxHeight===e.minHeight?C(C({height:ae},e),se):e},[ie,ae,i,a,se]),re=D.useMemo(()=>U||B||!N||!v.download?null:F.jsx("div",{className:"qwen-markdown-image-controls",children:F.jsx("div",{className:"qwen-markdown-image-controls-top",children:F.jsx("div",{className:"qwen-markdown-image-controls-button",onClick:()=>{var e,t;return null==(t=null==(e=v.download)?void 0:e.onDownload)?void 0:t.call(e,N)},children:F.jsx(pi,{type:"icon-line-download-02",className:"qwen-markdown-image-controls-icon"})})})}),[v.download,B,U,N]),le=D.useCallback(e=>{e.stopPropagation(),$(!1)},[]);return D.useImperativeHandle(t,()=>({closePreview:()=>{$(!1)}}),[]),F.jsxs("div",{className:"qwen-markdown-image",style:S(C({},oe),{cursor:!u||B||U?"default":"pointer"}),onClick:()=>N&&(null==f?void 0:f({url:N})),children:[B&&F.jsxs("span",{className:"qwen-markdown-image-error",children:[F.jsx(pi,{type:"icon-line-image-x-2"}),F.jsx("span",{className:"qwen-markdown-image-error-text",children:B})]}),!!A&&F.jsxs("div",{ref:K,className:Q("qwen-markdown-image-content",{loading:U,error:!!B}),children:[F.jsx(Di,{src:A,width:"100%",height:"100%",placeholder:l?F.jsx(ay,{style:{width:ie,height:ae}}):void 0,preview:!(!u||U||B)&&S(C({rootClassName:"qwen-markdown-image-preview"+(j?` ${j}`:""),src:N,mask:null,movable:!1,minScale:1,maxScale:1},u),{visible:G,imageRender(e,t){var n,s;const i=(null==(n=null==u?void 0:u.imageRender)?void 0:n.call(u,e,t))||e,a=(null==(s=null==u?void 0:u.toolbarRender)?void 0:s.call(u,e,t))||null;let o=i;try{o=O.cloneElement(i,{onError:t=>{var n;V(!0),(null==(n=e.props)?void 0:n.onError)&&e.props.onError(t)}})}catch(d){o=i}const r=R/L,l=ne("width",y),c=ne("height",b);return F.jsxs("div",{className:"qwen-markdown-image-preview-content",style:C({width:`calc(100% - ${l}px)`,height:`calc(100% - ${c}px)`,position:"relative"},w),onClick:()=>{(null==u?void 0:u.maskClosable)&&T&&$(!1)},children:[_,F.jsxs("div",{className:"qwen-image-preview-wrapper",style:{width:r>3?"100%":"auto",height:r>3?"auto":"100%"},children:[W?F.jsx("img",{src:"https://img.alicdn.com/imgextra/i3/O1CN01XtWomH1IJQUZbDdzw_!!6000000000872-2-tps-160-160.png",alt:""}):F.jsxs(F.Fragment,{children:[o,a]}),!x&&F.jsx("div",{className:"qwen-image-preview-close",onClick:le,children:F.jsx(pi,{type:"icon-close-4"})})]})]})},toolbarRender:()=>null,onVisibleChange:e=>{var t;$(e),null==(t=null==u?void 0:u.onVisibleChange)||t.call(u,e,{url:N})}}),onClick:()=>{N&&u&&!U&&!B&&$(!0)},draggable:!1,onLoad:e=>{if((!o||!r)&&e.currentTarget){let t=e.currentTarget;if("img"!==t.tagName.toLowerCase()&&(t=t.querySelector("img")),t){const{naturalWidth:e,naturalHeight:n}=t,s=iy({width:e,height:n,sizeScope:h});X(s.width),Z(s.height),null==g||g(s)}}oy=1,H(!1),z(""),null==m||m()},onError:te}),re]})]})})),ly=e=>{const{token:t}=e;return["
","
"].includes(t.raw.replaceAll(" ",""))?F.jsx("br",{}):F.jsx("span",{children:t.raw})},cy=()=>F.jsx("div",{className:"qwen-markdown-hr",children:F.jsx("hr",{})}),dy=e=>{const{token:t,renderTokens:n}=e;return O.createElement(`h${t.depth}`,{className:"qwen-markdown-heading"},t.tokens?n(t.tokens):t.text)},uy=e=>{const{token:t}=e,n=D.useMemo(()=>(new DOMParser).parseFromString(t.text,"text/html").documentElement.textContent,[t.text]);return F.jsx("span",{children:n})},hy=e=>{const{token:t,renderTokens:n}=e;return F.jsx("em",{children:t.tokens?n(t.tokens):t.text})},my=e=>{const{token:t,renderTokens:n}=e;return F.jsx("del",{children:t.tokens?n(t.tokens):t.text})},py=e=>{const{token:t,onClick:n}=e;return F.jsx("code",{className:"qwen-markdown-codespan",style:{cursor:n?"pointer":"auto"},onClick:()=>{null==n||n(t)},children:t.text})},gy=["jsx","tsx","mermaid","json"];let fy=null;let vy=null;const yy=()=>(vy||(vy=Promise.all([Promise.all([Se(()=>import("./monaco-vendor.js").then(e=>e.i),__vite__mapDeps([0,5,6])).then(e=>e.loader),Se(()=>import("./monaco-vendor.js").then(e=>e.m),__vite__mapDeps([0,5,6]))]).then(([e,t])=>{e.config({monaco:t})}),A(null,null,function*(){const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t},{shikiToMonaco:n},s,i,a,o,r,l]=yield Promise.all([Se(()=>import("./core.js"),__vite__mapDeps([7,8])),Se(()=>import("./engine-javascript.js"),[]),Se(()=>import("./index13.js"),__vite__mapDeps([9,8])),Se(()=>import("./one-light.js"),[]).then(e=>e.default),Se(()=>import("./one-dark-pro.js"),[]).then(e=>e.default),Se(()=>import("./jsx.js"),[]),Se(()=>import("./tsx.js"),[]),Se(()=>import("./mermaid.js"),[]).then(e=>e.default),Se(()=>import("./json.js"),[]).then(e=>e.default)]),c=S(C({},s),{name:"light",colors:S(C({},s.colors),{"editor.background":"#ffffff","editor.lineHighlightBackground":"#ffffff"})}),d=S(C({},i),{name:"dark",colors:S(C({},i.colors),{"editor.background":"#232326","editor.lineHighlightBackground":"#232326"})}),u=r.map(e=>S(C({},e),{injectionSelector:void 0,scopeName:"source.mermaid",patterns:[{include:"#mermaid"}]}));return fy={highlighter:yield e({themes:[c,d],langs:[a,o,u,l],engine:t()}),shikiToMonaco:n},fy})])),vy),by=new WeakSet,xy=e=>{if(fy&&!by.has(e)){by.add(e),gy.forEach(t=>{e.languages.register({id:t})});const t=new Map,n=e.editor.defineTheme.bind(e.editor);e.editor.defineTheme=(e,s)=>{t.set(e,s),n(e,s)},fy.shikiToMonaco(fy.highlighter,e),e.editor.defineTheme=n;for(const[s,i]of t)e.editor.defineTheme(s,S(C({},i),{inherit:!0}))}},wy=D.lazy(()=>Se(()=>import("./wardley-L42UT6IY.js").then(e=>e.i),__vite__mapDeps([10,0,2,3,5,11,12,13,14])).then(e=>({default:e.MermaidCode}))),_y=D.lazy(()=>Se(()=>import("./monaco-vendor.js").then(e=>e.i),__vite__mapDeps([0,5,6])).then(e=>({default:e.default}))),Cy=e=>{const{token:t,theme:n="light",headerSticky:s,extraOptions:i,stickyTop:a=0,headerActionsRender:o}=e,{mobile:r}=Hf(),l=D.useRef(null),[c,d]=D.useState(!1);D.useEffect(()=>{yy().then(()=>d(!0))},[]);const u=D.useMemo(()=>"dark"===n?"dark":"light",[n]),h=D.useMemo(()=>C({readOnly:!0,domReadOnly:!0,automaticLayout:!0,scrollBeyondLastLine:!1,scrollbar:{alwaysConsumeMouseWheel:!1,vertical:"hidden",horizontal:r?"hidden":"auto",horizontalScrollbarSize:6},overviewRulerLanes:0,lineNumbersMinChars:0,lineDecorationsWidth:0,minimap:{enabled:!1},contextmenu:!1,fontSize:14,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',letterSpacing:r?0:-.56,unicodeHighlight:{ambiguousCharacters:!1,nonBasicASCII:!1,invisibleCharacters:!0}},i),[i,r]),m=D.useCallback(e=>{xy(e),e.editor.addKeybindingRule({keybinding:e.KeyMod.CtrlCmd|e.KeyCode.KeyF,command:null})},[]),p=D.useCallback(e=>{var t;const n=()=>{requestAnimationFrame(()=>{if(l.current){const t=e.getContentHeight()+14;l.current.style.height=`${t+18}px`,e.layout()}})};if((e=>{let t=0,n=0,s=!1,i=!1,a=null;const o=e.getDomNode();o.addEventListener("touchstart",o=>{const r=o.changedTouches.item(0);if(null===r)return;o.preventDefault=()=>{},t=r.clientX,n=r.clientY;const l=e.getLayoutInfo();s=e.getScrollTop()<=0,i=e.getScrollTop()>=e.getContentHeight()-l.height,a=null}),o.addEventListener("touchmove",e=>{const o=e.changedTouches.item(0);if(null!==o){if(null===a){const e=o.clientX-t,r=o.clientY-n;Math.abs(e)<=Math.abs(r)&&(a=r<0&&i||r>0&&s)}a&&e.stopPropagation()}}),o.addEventListener("touchend",e=>{null!=a&&a&&e.stopPropagation()})})(e),e.onDidContentSizeChange(n),l.current&&(l.current.style.overflow="hidden"),n(),r){const n=null==(t=e.getDomNode())?void 0:t.querySelector("textarea");n&&(n.setAttribute("inputmode","none"),n.setAttribute("readonly","readonly"))}},[r]),g=D.useMemo(()=>F.jsx(D.Suspense,{fallback:null,children:F.jsx(_y,{value:t.text,language:t.lang,theme:u,options:h,beforeMount:m,onMount:p,loading:null})}),[u,m,p,h,t.lang,t.text]);return F.jsx("pre",{className:"qwen-markdown-code",children:c?"mermaid"===t.lang?F.jsx(D.Suspense,{fallback:null,children:F.jsx(wy,{token:t,codeBodyRef:l,codeRender:g})}):F.jsxs(F.Fragment,{children:[F.jsx("div",{className:Q("qwen-markdown-code-header-wrapper",{"qwen-markdown-code-header-wrapper-sticky":s}),style:a?{top:a}:{},children:F.jsxs("div",{className:"qwen-markdown-code-header",style:{height:"36px"},children:[F.jsx("div",{children:t.lang}),F.jsx("div",{className:"qwen-markdown-code-header-actions",children:(null==o?void 0:o(t))||null})]})}),F.jsx("div",{ref:l,className:Q("qwen-markdown-code-body",t.lang),children:g})]}):null})},Sy=()=>F.jsx("br",{}),ky=e=>{const{token:t,renderTokens:n}=e;return F.jsx("blockquote",{className:"qwen-markdown-blockquote",children:t.tokens?n(t.tokens):t.text})},jy=e=>{const{token:t,onClick:n,contentRender:s,visible:i=!0}=e;return i?s?F.jsx("span",{className:"qwen-markdown-citation",children:s(t.text.split(","))}):t.text.split(",").map(e=>F.jsx("span",{className:"qwen-markdown-citation",onClick:()=>(e=>{null==n||n(e)})(e),children:e},e)):null};let Ty=null,Ey=null;const Ny=e=>{const{token:t,renderTokens:n}=e,[s,i]=D.useState(!!Ey);D.useEffect(()=>{(Ty||(Ty=A(null,null,function*(){const[e]=yield Promise.all([Se(()=>import("./katex.js"),[]).then(e=>e.default),Se(()=>import("./mhchem.js"),__vite__mapDeps([15,16]))]);return Ey=e,{katex:e}})),Ty).then(()=>{i(!0)})},[]);const a=D.useMemo(()=>"blockLatex"===t.type,[t.type]),o=D.useMemo(()=>{if(!s)return{latexRenderHtml:"",isRenderError:!1};let e=!1,n="";try{n=(e=>Ze.sanitize(e))((null==Ey?void 0:Ey.renderToString((null==t?void 0:t.text)||"",{displayMode:a,throwOnError:!1}))||"")}catch(i){e=!0}return{latexRenderHtml:n,isRenderError:e}},[t.text,a,s]);return F.jsxs(F.Fragment,{children:[t.tokens&&n(t.tokens),O.createElement(a?"div":"span",C({className:Q("qwen-markdown-latex",{"qwen-markdown-latex-error":o.isRenderError}),translate:"no",style:{overflowX:a?"auto":void 0}},o.latexRenderHtml?{dangerouslySetInnerHTML:{__html:o.latexRenderHtml}}:{}),o.latexRenderHtml?void 0:(null==t?void 0:t.text)||"")]})},Iy=e=>{const{tokens:t}=e,{tokenProps:n}=Gv(),{mobile:s}=Hf(),i=D.useCallback(e=>F.jsx(Iy,{tokens:e}),[]);return t.map((e,t)=>{const a=e.type+t,o=e,r=e;switch(o.type){case"blockquote":return F.jsx(ky,{token:o,renderTokens:i},a);case"br":return F.jsx(Sy,{},a);case"code":return F.jsx(Cy,C({token:o},null==n?void 0:n.code),a);case"codespan":return F.jsx(py,C({token:o},null==n?void 0:n.codespan),a);case"del":return F.jsx(my,{token:o,renderTokens:i},a);case"em":return F.jsx(hy,{token:o,renderTokens:i},a);case"escape":return F.jsx(uy,{token:o},a);case"heading":return F.jsx(dy,{token:o,renderTokens:i},a);case"hr":return F.jsx(cy,{},a);case"html":return F.jsx(ly,{token:o},a);case"image":return F.jsx(ry,S(C({url:o.href},null==n?void 0:n.image),{sizeScope:s?[112,200]:[152,280]}),a);case"link":return F.jsx(sy,{token:o,renderTokens:i},a);case"list":return F.jsx(Yv,{token:o,renderTokens:i},a);case"paragraph":return F.jsx(Kv,{token:o,renderTokens:i},a);case"space":return F.jsx(Qv,{},a);case"strong":return F.jsx(Vv,{token:o,renderTokens:i},a);case"table":return F.jsx(Wv,C({token:o,renderTokens:i},null==n?void 0:n.table),a);case"text":return F.jsx($v,{token:o,renderTokens:i},a)}switch(r.type){case"inlineLatex":case"blockLatex":return F.jsx(Ny,{token:r,renderTokens:i},a);case"citation":return F.jsx(jy,C({token:r},null==n?void 0:n.citation),a)}return null})},Ay=D.memo(e=>{var t;const n=e,{content:s,increment:i}=n,a=k(n,["content","increment"]),[o,r]=D.useState([]),l=D.useRef(null),c=D.useRef({});return D.useEffect(()=>()=>{var e;null==(e=l.current)||e.destroy()},[]),D.useEffect(()=>{if(Ae(c.current,i))return;c.current=i||{};const{chunkSize:e=1/0,separator:t=""}=i||{},n={parser:Hv,singleChunkSize:e,onTokenUpdate:e=>A(null,null,function*(){r(e)})};l.current=t?new Av(S(C({},n),{separator:t})):new Iv(n)},[i]),D.useEffect(()=>{var e;null==(e=l.current)||e.updateContent(s)},[s]),F.jsx(zv,{value:a,children:F.jsx("div",{className:Q("qwen-markdown",{"qwen-markdown-loose":null==(t=e.loose)||t,"qwen-markdown-small":"small"===e.type}),children:F.jsx(Iy,{tokens:o})})})}),My=D.memo(({linkCardTitle:e,item:t,type:n="list",onLinkCard:s})=>{const[i,a]=D.useState(!1);return"card"===n?F.jsxs(O.Fragment,{children:[F.jsx("h3",{className:"steps-time-solt-title-mobile",children:e}),F.jsx(Sv,{webSites:t,onLinkCard:s})]}):F.jsxs(O.Fragment,{children:[F.jsxs("h3",{onClick:()=>a(!i),className:"steps-time-solt-title-mobile steps_time_solt_title_mobile_link",children:[e,F.jsx(pi,{type:"icon-line-chevron-down",className:Q("steps_time_solt_title_arrow",{steps_time_solt_title_arrow_close:!i}),onClick:e=>{e.stopPropagation(),a(!i)}})]}),i&&F.jsx(Tv,{webSites:t,onLinkCard:s})]})}),Ry=({content:e,id:t="",linkCardTitle:n,errorMessage:s="",linkCardType:i="card",onLinkCard:a,onCitationClick:o})=>e&&"string"==typeof e?F.jsx(Ay,{content:e,tokenProps:{image:{preview:{mask:null},onError:()=>({errorMessage:s})},citation:{onClick:e=>null==o?void 0:o(e)}}}):Array.isArray(e)?F.jsx(F.Fragment,{children:e.map((e,s)=>{const r=s+t;return e&&"string"==typeof e?F.jsx(Ay,{content:e,tokenProps:{image:{preview:{mask:null},onError:()=>({errorMessage:"加载失败"})},citation:{onClick:e=>null==o?void 0:o(e)}}},r):Array.isArray(e)?F.jsx("div",{children:F.jsx(My,{linkCardTitle:n,item:e,type:i,onLinkCard:a})},r):null})}):null,Py=e=>{const{value:t,open:n,onCancel:s,onOk:i}=e,a="qwen-edit-content-mobile",o=D.useRef(null),[r,l]=D.useState(t);return D.useEffect(()=>{var e;n&&(null==(e=o.current)||e.focus({cursor:"end"}))},[n]),F.jsx(Ti,{className:`${a}-popup`,open:n,onClose:s,closable:!1,heightType:"auto",children:F.jsxs("div",{className:a,children:[F.jsx(K.TextArea,{className:`${a}-textarea`,autoSize:{minRows:4,maxRows:4},ref:o,value:r,autoFocus:!0,onChange:e=>{l(e.target.value)}}),F.jsxs("div",{className:`${a}-control`,children:[F.jsx("div",{className:`${a}-control-cancel`,onClick:s,children:F.jsx(pi,{className:"cancel-icon",type:"icon-line-x-03"})}),F.jsx("div",{className:`${a}-control-ok`,onClick:()=>{null==i||i(r)},children:F.jsx(pi,{className:"ok-icon",type:"icon-line-check-01"})})]})]})})},Ly=e=>{const{value:t,cancelText:n="取消",okText:s="保存",extraText:i="另存为副本",onCancel:a,onOk:o,onExtra:r,showExtra:l=!0}=e,c=D.useRef(null),[d,u]=D.useState(t);return D.useEffect(()=>{var e;null==(e=c.current)||e.focus({cursor:"end"})},[]),F.jsxs("div",{className:"qwen-edit-content",children:[F.jsx(K.TextArea,{className:"qwen-edit-content-textarea",ref:c,autoSize:{minRows:2,maxRows:10},value:d,onChange:e=>{u(e.target.value)}}),F.jsxs("div",{className:"qwen-edit-content-control",children:[l?F.jsx(xi,{type:"ghost",size:"small",onClick:()=>{null==r||r(d)},children:i}):F.jsx("div",{}),F.jsxs("div",{className:"qwen-edit-content-control-basic",children:[F.jsx(xi,{type:"tertiary",size:"small",onClick:a,children:n}),F.jsx(xi,{type:"brandprimary",size:"small",onClick:()=>{null==o||o(d)},children:s})]})]})]})},Oy=e=>{const t=e,{open:n,value:s,onOk:i,onCancel:a}=t,o=k(t,["open","value","onOk","onCancel"]),{mobile:r}=Hf();return r?F.jsx(Py,{open:n,value:s,onOk:i,onCancel:a}):n?F.jsx(Ly,C({value:s,onOk:i,onCancel:a},o)):null},Dy=D.memo(({languages:e,languageCode:t,selectLanguage:n})=>F.jsx("div",{className:"select-language-container",children:e.map(e=>F.jsxs("div",{className:Q("select-language-item",{"select-language-item-choose":e.code===t}),onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:t=>{t.stopPropagation(),n(e)},children:[F.jsx("div",{className:"select-language-item-text",children:(null==e?void 0:e.title)?e.title:`${e.code}(${e.translate})`}),e.code===t&&F.jsx("div",{className:"select-language-item-icon",children:F.jsx(pi,{type:"icon-line-check-02"})})]},e.code))})),Fy=e=>{var t=e,{children:n,languages:s,languageCode:i,selectLanguage:a}=t,o=k(t,["children","languages","languageCode","selectLanguage"]);const r=D.useMemo(()=>F.jsx("div",{className:"language-dropdown",children:F.jsx(Dy,{languages:s,languageCode:i,selectLanguage:a})}),[s,i,a]);return F.jsx(le,S(C({trigger:["click"],classNames:{root:"language-menu-popover"},placement:"right",title:null,content:r,arrow:!1},o),{children:n}))};var qy=(e=>(e.Running="running",e.Stop="stop",e.Finish="finish",e.Error="error",e))(qy||{});const Uy=({status:e,isCurrent:t,cardStatus:n,iconTypes:s})=>{const{finishType:i,errorType:a,stopType:o,loadingType:r}=s||{},{mobile:l}=Hf(),c=D.useMemo(()=>n===qy.Running&&e===Qf.process?"loading":n===qy.Stop&&e===Qf.process?"stop":n===qy.Finish&&e===Qf.process?"error":"finish",[n,e]),d=D.useMemo(()=>r?"string"==typeof r?F.jsx(pi,{type:r,className:"steps-time-des-icon-h5 steps-time-des-icon-current-h5"}):r:l?F.jsx("span",{className:"steps-time-des-icon-h5 steps-time-des-icon-current-h5",children:F.jsx(Ui,{type:"primary"})}):F.jsx("span",{className:"steps-time-des-icon steps-time-des-icon-current",style:{width:"14px",height:"14px",display:"flex"},children:F.jsx(Ui,{type:"primary"})}),[l,r]),u=D.useMemo(()=>{if(o&&"string"!=typeof o)return o;const e="string"==typeof o?o:"icon-fill-stop";return l?F.jsx(pi,{type:e,className:"steps-time-des-icon-h5 steps-time-des-icon-h5-14 steps-time-des-icon-stop"+(t?" steps-time-des-icon-current-h5":"")}):F.jsx(pi,{type:e,className:"steps-time-des-icon steps-time-des-icon-14 steps-time-des-icon-stop"+(t?" steps-time-des-icon-current":"")})},[l,t,o]),h=D.useMemo(()=>{if(a&&"string"!=typeof a)return a;const e="string"==typeof a?a:"icon-fill-x-circle-contained";return l?F.jsx(pi,{type:e,className:"steps-time-des-icon steps-time-des-icon-14 steps-time-des-icon-error"+(t?" steps-time-des-icon-current-h5":"")}):F.jsx(pi,{type:e,className:"steps-time-des-icon steps-time-des-icon-14 steps-time-des-icon-error"+(t?" steps-time-des-icon-current":"")})},[l,t,a]),m=D.useMemo(()=>{if(i&&"string"!=typeof i)return i;const e="string"==typeof i?i:"icon-fill-check-contained";return l?F.jsx(pi,{type:e,className:"steps-time-des-icon-h5"+(t?" steps-time-des-icon-current-h5":"")}):F.jsx(pi,{type:e,className:"steps-time-des-icon"+(t?" steps-time-des-icon-current":"")})},[l,t,i]);return"loading"===c?d:"stop"===c?u:"error"===c?h:"finish"===c?m:null},Hy=D.memo(e=>{const{info:t,index:n,cardStatus:s,stepIdPrefix:i,onClickChange:a}=e;return F.jsxs("div",{onClick:()=>{null==a||a(n,t)},className:"list-card-step-item",children:[t.icon?t.icon:F.jsx(Uy,{status:t.status,cardStatus:s,isCurrent:!0}),F.jsx("span",{className:"list-card-step-item-text",id:`${i}_${t.id}`,children:t.title})]})}),By=D.memo(e=>{const{stepList:t,cardStatus:n,stepIdPrefix:s,type:i=Vf.list,onClickChange:a}=e;return F.jsx("div",{className:"list-card-steps",children:t.map((e,t)=>F.jsx(Hy,{stepIdPrefix:`${i}_${s}`,info:e,cardStatus:n,index:t,onClickChange:a},`${e.title}_${e.id}_${t}`))})}),zy=D.memo(({imageUrl:e})=>{const[t,n]=D.useState(!1),[s,i]=D.useState(0),a=D.useCallback(e=>new Promise((t,n)=>{const s=new Image;s.crossOrigin="Anonymous",s.src=e,s.onload=function(){const e=s.width,n=s.height;t({width:e,height:n})},s.onerror=function(e){n(new Error("图片加载失败:"+e))}}),[]),o=D.useCallback(e=>A(null,null,function*(){n(!0);try{const{width:t,height:n}=yield a(e);t>n?i(264):t{e&&o(e)},[e]);const r=D.useMemo(()=>["card-image-info-icon-left-top","card-image-info-icon-right-top","card-image-info-icon-left-bottom","card-image-info-icon-right-bottom"],[]);return e?F.jsx("div",{className:"card-image-info",style:{background:t?"linear-gradient(90deg, rgba(216, 218, 227, 0.2) 20%, rgba(160, 162, 177, 0.32) 42%, rgba(216, 218, 227, 0.2) 67%)":`url(${e}) no-repeat center center / cover`,animation:t?"gradient-shift 3s ease infinite":"none",backgroundSize:t?"400% 400%":"cover"},children:F.jsx("div",{className:"card-image-info-wrapper",children:t?null:F.jsxs(F.Fragment,{children:[r.map(e=>F.jsx(pi,{className:Q("card-image-info-icon",`${e}`),type:"icon-image-bl"},e)),F.jsx("div",{style:{width:s,background:`url(${e}) no-repeat center center / cover`},className:"card-image-info-content"})]})})}):null}),Gy=({info:e,cardStatus:t,linkCardType:n,isCurrent:s=!1,researchRenderOption:i,customPlugings:a,stepIdPrefix:o,onLinkCard:r})=>{var l;const c=D.useMemo(()=>{let t;return"image_zoom_in_tool"===e.phase&&(t={finishType:"icon-image-icon"}),"code_interpreter"===e.phase&&(t={finishType:"icon-line-code-01"}),t},[e]),d=D.useMemo(()=>{let t=Wf.deep_research;return"image_zoom_in_tool"===e.phase&&(t=Wf.image_tool),e.contentTemplate&&(t=e.contentTemplate),t},[e]),u=D.useMemo(()=>{var t,n,s;return[Jf.browser_take_screenshot,Jf.browser_snapshot].includes((null==e?void 0:e.extensionAction)||"")?F.jsx(F.Fragment,{children:null==(t=e.extensionUrl)?void 0:t.filter(e=>!!e).map((e,t)=>F.jsx("div",{className:"steps-time-title-link",children:F.jsx("div",{className:"steps-time-title-screenshot",children:F.jsx(le,{rootClassName:"steps-time-title-screenshot-popover",arrow:!1,placement:"bottom",align:{offset:[-30,8]},content:F.jsx("img",{className:"steps-time-title-screenshot-display-image",src:e,alt:""}),children:F.jsx("img",{className:"steps-time-title-screenshot-thumbnail",src:e,alt:""})})})},`${e}_${t}`))}):e.isExtension&&(null==(n=null==e?void 0:e.extensionUrl)?void 0:n.length)?F.jsx(F.Fragment,{children:null==(s=e.extensionUrl)?void 0:s.filter(e=>!!e).map(e=>F.jsx("div",{className:"steps-time-title-link",onClick:()=>{window.open(e,"_blank")},children:e},e))}):null},[null==e?void 0:e.extensionAction,null==(l=e.extensionUrl)?void 0:l.length]),h=D.useMemo(()=>void 0!==e.title?F.jsxs("div",{className:"steps-time steps-time-h5-navigation steps-time-h5-navigation-all",children:[F.jsx("div",{className:"steps-time-schedule-outer",children:F.jsx("div",{className:"steps-time-schedule",children:e.icon?e.icon:F.jsx(Uy,{status:e.status,cardStatus:t,isCurrent:s,iconTypes:c})})}),F.jsx("div",{className:"steps-time-des",id:`${o}_${e.id}`,children:F.jsxs("div",{className:"steps-time-title steps-time-title-line",children:[e.title,e.isExtension?F.jsx(F.Fragment,{children:u}):null]})})]}):null,[e,t,s,o,c,u]),m=D.useMemo(()=>{const n=e.content||d===Wf.image_tool||d===Wf.code_interpreter;return n&&void 0===e.title?F.jsxs("div",{className:"steps-time-content-left",children:[F.jsx("div",{className:"steps-time-content-left-icon",children:F.jsx(Uy,{status:e.status,cardStatus:t,isCurrent:s,iconTypes:c})}),F.jsx("div",{className:"steps-time-line"})]}):n&&void 0!==e.title||e.isExtension&&!e.isLast?F.jsx("div",{className:"steps-time-line "+(e.isExtension&&!e.content?"no-content-display-line":"")}):null},[e,t,s,c,d]),p=D.useCallback(e=>{var t,n,s;return(null==(s=null==(n=null==(t=e.extra)?void 0:t.image_zoom_in_tool_info)?void 0:n[0])?void 0:s.image)||""},[]),g=D.useMemo(()=>{var t;return(null==a?void 0:a[null==e?void 0:e.phase])?null==(t=null==a?void 0:a[null==e?void 0:e.phase])?void 0:t.call(a,e):d===Wf.image_tool?F.jsx("div",{children:F.jsx(zy,{imageUrl:p(e)})}):d!==Wf.deep_research||"string"!=typeof e.content&&!Array.isArray(e.content)?e.content:F.jsx(Ry,{content:e.content,id:e.id,linkCardTitle:e.linkCardTitle,errorMessage:(null==i?void 0:i.errorMessage)||"error",onLinkCard:r,linkCardType:n})},[e,i,n,a]);return F.jsxs(F.Fragment,{children:[h,F.jsxs("div",{className:"steps-time-content "+(e.isLast&&!e.content?"steps-time-content-none":""),children:[m,F.jsx("div",{className:"steps-time-slot",children:g})]})]})},$y=({stepList:e=[],className:t,cardStatus:n,linkCardType:s,isCurrent:i,onLinkCard:a,type:o=Vf.markdown,customPlugings:r,stepIdPrefix:l})=>F.jsx("div",{className:Q("deep-research-content",t),children:F.jsx("div",{className:"deep-research-times",children:F.jsx("div",{className:"steps-items steps-items-h5-navigation",children:e.map((t,c)=>{const d=`research-list-${c}-${t.id}`;return F.jsx(Gy,{stepIdPrefix:`${o}_${l}`,info:S(C({},t),{isLast:c===e.length-1}),cardStatus:n,isCurrent:i,onLinkCard:a,linkCardType:s,customPlugings:r},d)})})})}),Wy=()=>F.jsx("div",{className:"web-search-skeleton",children:F.jsx("div",{className:"web-search-skeleton-main",children:F.jsxs("div",{className:"web-search-skeleton-main-content",children:[F.jsx("div",{className:"web-search-skeleton-main-content-list-1 web-search-skeleton-main-content-list-bg"}),F.jsx("div",{className:"web-search-skeleton-main-content-list-2 web-search-skeleton-main-content-list-bg"}),F.jsx("div",{className:"web-search-skeleton-main-content-list-3 web-search-skeleton-main-content-list-bg"}),F.jsx("div",{className:"web-search-skeleton-main-content-list-4 web-search-skeleton-main-content-list-bg"}),F.jsx("div",{className:"web-search-skeleton-main-content-list-5 web-search-skeleton-main-content-list-bg"}),F.jsx("div",{className:"web-search-skeleton-main-content-list-6 web-search-skeleton-main-content-list-bg"}),F.jsx("div",{className:"web-search-skeleton-main-content-list-7 web-search-skeleton-main-content-list-bg"})]})})}),Vy=e=>{var t=e,{src:n,alt:s,size:i,fallbackComponent:a,loadingComponent:o}=t,r=k(t,["src","alt","size","fallbackComponent","loadingComponent"]);const[l,c]=D.useState(!1),[d,u]=D.useState(!0);return l?a:F.jsxs(F.Fragment,{children:[d&&o,F.jsx("img",C({width:i,height:i,src:n,alt:s,onLoad:()=>{u(!1)},onError:()=>{u(!1),c(!0)},style:{display:d?"none":"block"}},r))]})},Qy="https://img.alicdn.com/imgextra/i4/O1CN01XFV3QG1XsQyyaWqLS_!!6000000002979-55-tps-20-20.svg",Ky="https://img.alicdn.com/imgextra/i3/O1CN01VEjCND1WAdUW23ZML_!!6000000002748-55-tps-20-20.svg",Yy="https://img.alicdn.com/imgextra/i4/O1CN016bqlLa23NoCdx8Q06_!!6000000007244-55-tps-20-20.svg",Jy="https://img.alicdn.com/imgextra/i2/O1CN01LKZmDT1eWB2u31TnV_!!6000000003878-55-tps-20-20.svg",Xy="https://img.alicdn.com/imgextra/i3/O1CN01NEEWHV1nysPE7DHcJ_!!6000000005159-55-tps-20-20.svg",Zy="https://img.alicdn.com/imgextra/i1/O1CN010tEY0e1uRcxnebwGz_!!6000000006034-55-tps-20-20.svg",eb="https://img.alicdn.com/imgextra/i2/O1CN01yMiryC1qg2yCYljWz_!!6000000005524-55-tps-20-20.svg",tb="https://img.alicdn.com/imgextra/i4/O1CN01QSVe5u1wUUfpRdhYZ_!!6000000006311-55-tps-20-20.svg";function nb(e){try{const t=new URL(e).pathname.split("/").pop(),n=null==t?void 0:t.split(".").pop();return n===t?"":null==n?void 0:n.toLowerCase()}catch(t){return""}}const sb=(e,t,n)=>{if(n)return"File Source";if("vision"===t)return"Image Source";if("txt"===t)return"TXT Source";if("doc"===t)switch(nb(e)){case"pdf":return"PDF Source";case"doc":case"docx":default:return"File Source";case"xlsx":case"xls":return"EXCEL Source";case"md":return"MD Source"}return"audio"===t?"Audio Source":"video"===t?"Video Source":void 0},ib=(e,t)=>{const n=nb(e);let s=e;if("vision"===t)return s=e,s;if(n)switch(t){case"audio":s=Qy;break;case"video":s=Ky;break;case"txt":s=Jy;break;case"doc":s=(e=>{switch(nb(e)){case"pdf":return Yy;case"doc":case"docx":return tb;case"xlsx":case"xls":return Zy;case"md":return eb;default:return Xy}})(e);break;default:s=Xy}return s},ab=D.memo(e=>{const{isLoading:t,listData:n,citationIndex:s,webSourceOption:i}=e,{headerTitle:a="",noSourceText:o="",showHeader:r=!0,id:l="",style:c={},highlightClassName:d,theme:u,onClickItem:h=()=>{},onClose:m,triggerTimestamp:p}=i,[g,f]=D.useState(!1),v=D.useRef(g),y=D.useRef(null),b=D.useRef(null),x=D.useRef(null),w=D.useRef(null),{mobile:_}=Hf(),[C,S]=D.useState(!1),k=D.useCallback(e=>{const t=document.getElementById(`${e}-content`);if(t)if(void 0!==u)t.style.backgroundColor="";else{const e=d||"sources-item-highlight-bg";t.classList.remove(e)}},[u,d]),j=D.useCallback(e=>{x.current&&x.current!==e&&(k(x.current),b.current&&(clearTimeout(b.current),b.current=null));const t=document.getElementById(e);if(t){t.scrollIntoView({behavior:"smooth"});const n=document.getElementById(`${e}-content`);if(n){if(void 0!==u)n.style.backgroundColor="dark"===u?"#21204A":"#F3F2FF",b.current&&clearTimeout(b.current),b.current=setTimeout(function(){n.style.backgroundColor="",x.current=null},2e3);else{const e=d||"sources-item-highlight-bg";n.classList.add(e),b.current&&clearTimeout(b.current),b.current=setTimeout(function(){n.classList.remove(e),x.current=null},2e3)}x.current=e}}},[u,d,k]),T=D.useCallback(e=>{try{return decodeURIComponent(e)}catch(t){return e}},[]),E=D.useMemo(()=>t&&!_?F.jsx(Wy,{}):null,[t,_]),N=D.useMemo(()=>{if(r)return F.jsxs("div",{className:"content-header "+(g?"content-header-border":""),children:[F.jsxs("div",{className:"content-title",children:[!_&&F.jsx(pi,{type:"icon-line-globe-01",className:"title-icon"}),a]}),F.jsx("div",{className:"content-close",onClick:m,children:F.jsx(pi,{type:""+(_?"icon-close":"icon-line-x-02"),className:"close-icon"})})]})},[r,g,_,a,m]),I=D.useMemo(()=>0!==(null==n?void 0:n.length)&&(null==n?void 0:n.length)?null:F.jsx("div",{className:"no-sources-wrap",children:F.jsx("span",{className:"no-sources text-center",children:o})}),[o,null==n?void 0:n.length]),A=D.useCallback(e=>{const t=e.target;if(!t)return;const n=v.current;!n&&t.scrollTop>45?f(!0):n&&t.scrollTop<=45&&f(!1)},[]);D.useEffect(()=>{v.current=g},[g]);const M=D.useMemo(()=>F.jsx("div",{className:"content-list",ref:w,onScroll:A,children:null==n?void 0:n.map((e,t)=>F.jsxs(O.Fragment,{children:[t>0&&!_&&F.jsx("div",{className:"content-list-divider"}),F.jsx("div",{className:"sources-item-wrap",id:`${l}-${t+1}`,onClick:()=>{h(e)},children:F.jsx("div",{className:"sources-item content-list-item",id:`${l}-${t+1}-content`,children:F.jsxs("div",{className:"content-list-item-box",children:[F.jsx("div",{className:"content-list-item-title",children:e.fileType&&"web"!==e.fileType?F.jsxs("span",{className:"host-name-text",children:[F.jsxs("span",{children:[t+1,"."]}),F.jsx("span",{className:"host-name-text host-name-text-deep-research",children:sb(e.url,e.fileType,C)})]}):F.jsxs("span",{className:"sources-item-index",children:[F.jsxs("span",{children:[t+1,"."]}),e.hostlogo&&F.jsx(Vy,{size:12,src:e.hostlogo,alt:"",className:"imgIcon ml-1.5 w-3",loadingComponent:F.jsx(pi,{className:"search-icon",type:"icon-line-globe-01"}),fallbackComponent:F.jsx(pi,{className:"search-icon",type:"icon-line-globe-01"})}),!e.hostlogo&&F.jsx(pi,{className:"search-icon",type:"icon-line-globe-01"}),F.jsx("span",{className:"host-name-text",children:e.hostname?e.hostname:T(e.url)}),!_&&e.date&&F.jsxs(F.Fragment,{children:[F.jsx("span",{className:"dot-separator",children:"·"}),_?F.jsx("span",{className:"date-text",children:e.date.replace(/[()\s]/g,"").replace(/[-]/g,"/")}):F.jsx("span",{className:"date-text",children:e.date})]})]})}),e.fileType&&"web"!==e.fileType&&F.jsxs("div",{className:"deep-research-origins-item-file",children:[F.jsxs("div",{className:"deep-research-origins-item-icon",children:[F.jsx("img",{src:T(ib(e.url,e.fileType)),alt:"",onError:()=>{S(!0)}}),"vision"===e.fileType&&!C&&!_&&F.jsx("div",{onClick:e=>{e.stopPropagation()},className:"deep-research-origins-item-img",style:{backgroundImage:`url(${e.url})`}})]}),F.jsx("div",{className:"deep-research-origins-item-link",children:e.url})]}),e.title&&("web"===e.fileType||!e.fileType)&&F.jsx("div",{className:"content-text content-item-des-title",children:e.title}),e.snippet&&("web"===e.fileType||!e.fileType)&&F.jsx("div",{className:"snippet-text content-item-des",children:e.snippet}),_&&e.date&&F.jsx("div",{className:"content-item-date",children:e.date.replace(/[()\s]/g,"").replace(/[-]/g,"/")})]})})})]},e.url))}),[l,n,_,C,S,h,T]),R=D.useMemo(()=>t&&!_||!n?null:F.jsxs(F.Fragment,{children:[N,I,M]}),[t,n,_,N,I,M]);return D.useEffect(()=>{s&&l&&(clearTimeout(y.current),y.current=setTimeout(()=>{j(`${l}-${s}`)},300))},[p,l,s,j]),D.useEffect(()=>()=>{clearTimeout(y.current)},[]),F.jsxs("div",{className:"web-search-origins",style:c,children:[E,R]})}),ob=({index:e,isCurrent:t,cardStatus:n,stepIdPrefix:s,info:i,onClickChange:a})=>F.jsxs("div",{className:"steps-time"+(e>0?" steps-time-mr-top":""),onClick:()=>{a&&a(e,C({},i))},children:[F.jsx("div",{children:F.jsx("div",{className:"steps-time-schedule",children:F.jsx(Uy,{status:i.status,isCurrent:t,cardStatus:n})})}),F.jsx("div",{className:"steps-time-des "+(t?"steps-time-des-current":""),id:`${s}_${i.id}`,children:F.jsx("div",{className:"steps-time-title",children:i.title})})]}),rb=D.memo(({className:e,stepList:t,cardStatus:n,isCurrent:s,type:i,stepCurrent:a,stepIdPrefix:o,onClickChange:r})=>F.jsx("div",{className:Q("steps-items steps-items-navigation",e),children:t.map((e,t)=>{const l=s||"process"===e.status&&"running"===n||a===t,c=`research-list-${t}-${e.id}`;return F.jsx(ob,{stepIdPrefix:`${i}_${o}`,index:t,info:e,isCurrent:l,onClickChange:r,cardStatus:n},c)})})),lb=({className:e,stepList:t,cardStatus:n,isCurrent:s,stepCurrent:i,stepIdPrefix:a,onLinkCard:o,onStepClickChange:r,type:l=Vf.text,customPlugings:c})=>l===Vf.list?F.jsx(By,{type:Vf.list,stepIdPrefix:a,stepList:t,cardStatus:n||qy.Finish,onClickChange:r,stepCurrent:i,isCurrent:s}):l===Vf.markdown?F.jsx($y,{className:e,type:Vf.markdown,stepList:t,stepIdPrefix:a,linkCardType:"list",onLinkCard:o,isCurrent:s,cardStatus:n,customPlugings:c}):l===Vf.text?F.jsx(rb,{className:e,type:Vf.text,stepList:t,stepIdPrefix:a,cardStatus:n||qy.Finish,onClickChange:r,stepCurrent:i,isCurrent:s}):null,cb=e=>{var t=e,{citationIndex:n=0,currentTab:s=$f.step,onClose:i,cardStatus:a,tabs:o,isCurrent:r,sourceList:l,stepList:c,onLinkCard:d,webSourceOption:u,className:h="",cardStepType:m=Vf.markdown,customPlugings:p}=t,g=k(t,["citationIndex","currentTab","onClose","cardStatus","tabs","isCurrent","sourceList","stepList","onLinkCard","webSourceOption","className","cardStepType","customPlugings"]);const{mobile:f}=Hf(),[v,y]=D.useState($f.step),[b,x]=D.useState(!1),w=D.useRef(0),_=D.useRef(null),j=D.useCallback(e=>{y(e),x(!1)},[y,x]);D.useEffect(()=>{y(s)},[s]);const T=D.useCallback(e=>{v===$f.step&&(b||null==e||e.scrollTo({top:e.scrollHeight,behavior:"smooth"}))},[v,b]);D.useEffect(()=>{const e=_.current;if(!e)return;const t=e=>{1===e.touches.length&&(w.current=e.touches[0].clientY)},n=e=>{if(1===e.touches.length){const t=e.touches[0].clientY;Math.abs(t-w.current)>10&&x(!0)}},s=()=>{const{scrollTop:t,scrollHeight:n,clientHeight:s}=e;t+s>=n-5&&x(!1)};return e.addEventListener("touchstart",t,{passive:!0}),e.addEventListener("touchmove",n,{passive:!0}),e.addEventListener("touchend",s,{passive:!0}),()=>{e.removeEventListener("touchstart",t),e.removeEventListener("touchmove",n),e.removeEventListener("touchend",s)}},[]),D.useEffect(()=>{(null==o?void 0:o.length)&&1===o.length&&y(o[0].key)},[v,o]),D.useEffect(()=>{const e=setTimeout(()=>{a===qy.Running&&T(_.current)},100);return()=>clearTimeout(e)},[a,c,T]);const E=D.useMemo(()=>(null==o?void 0:o.length)?1===o.length?F.jsx("div",{className:"deep-research-h5-content-only-tab",children:o[0].text}):F.jsx("div",{className:"deep-research-h5-content-tabs",children:null==o?void 0:o.map(e=>F.jsxs("div",{className:"deep-research-h5-content-tab "+(v===e.key?"deep-research-h5-content-tab-choose":""),onClick:()=>j(e.key),children:[e.text,e.key===$f.sources&&F.jsxs(F.Fragment,{children:[F.jsx("span",{className:"deep-research-h5-content-tab-dot"}),(null==l?void 0:l.length)||0]})]},e.key))}):null,[o,l,j,v]),N=D.useMemo(()=>v===$f.step?F.jsx(lb,{stepList:c,cardStatus:a,onLinkCard:d,isCurrent:r,type:m,customPlugings:p}):F.jsx(ab,{listData:l,citationIndex:n,webSourceOption:C({showHeader:!1,onClose:i},u)}),[v,c,a,d,r,l,n,i,u,m]);return F.jsxs("div",S(C({className:`deep-research-h5-content-container markdown-prose-dp markdown-small-prose ${f?"markdown-small-prose-mobile":""} ${h}`,id:"deep-research-h5-content-container"},g),{children:[F.jsxs("div",{className:"deep-research-h5-content-header",children:[E,F.jsx("div",{className:"deep-research-h5-content-close",onClick:i,children:F.jsx(pi,{type:"icon-close-4"})})]}),F.jsx("div",{className:"deep-research-h5-content",id:"h5-research-panel-content",ref:_,children:N})]}))},db=e=>{const{prompts:t=[],onClick:n}=e,{mobile:s}=Hf();return t&&0!==t.length&&Array.isArray(t)?F.jsx("div",{className:Q("qwen-recommend-prompt",{"qwen-recommend-prompt-mobile":s}),children:t.map(e=>F.jsx("div",{className:"qwen-recommend-prompt-item",onClick:()=>null==n?void 0:n(e),children:F.jsx("span",{children:e})},e))}):null},{TextArea:ub}=K,hb=e=>{var t=e,{askInputPlaceholder:n,onAskHandler:s,onClose:i}=t,a=k(t,["askInputPlaceholder","onAskHandler","onClose"]);const[o,r]=D.useState(""),l=D.useRef(null),c=D.useCallback(()=>{null==i||i()},[i]),d=D.useCallback(()=>{l.current&&clearTimeout(l.current),o&&(null==s||s(o)),c()},[o,s,i]);return F.jsxs("div",S(C({className:"ask-input-container",onClick:e=>{e.stopPropagation()}},a),{children:[F.jsx("div",{className:"ask-input-content",children:F.jsx(ub,{autoSize:!0,autoFocus:!0,placeholder:n,variant:"borderless",value:o,onChange:e=>r(e.target.value),onPressEnter:d,onBlur:()=>{try{l.current=setTimeout(()=>{c()},500)}catch(e){}}})}),F.jsx("div",{className:Q("ask-input-button",{"ask-input-button-placeholder":""===o}),onClick:d,children:F.jsx(pi,{type:"icon-ArrowUp"})})]}))},mb=({menuList:e,onCopyHandler:t,onAskHandler:n,onExplainHandler:s,onTranslateHandler:i,languageCode:a,languages:o,askInputPlaceholder:r,showAskInputChange:l})=>{var c;const[d,u]=D.useState(!1),h=D.useRef(null),m=D.useRef({width:0,height:0}),{theme:p}=cv();D.useEffect(()=>{h.current&&(m.current={width:h.current.offsetWidth,height:h.current.offsetHeight})},[]);const[g,f]=D.useState(!1);return d?F.jsx(hb,{style:{width:null==(c=m.current)?void 0:c.width},askInputPlaceholder:r,onClose:()=>{u(!1),null==l||l(!1)},onAskHandler:n}):F.jsx("div",{className:Q("select-tools-menu",{"select-tools-menu-gray":"dark"===p}),id:"select-tools-menu",ref:h,children:null==e?void 0:e.map(e=>e.key===tv.copy?F.jsxs("div",{className:"select-tools-menu-item",onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),null==t||t()},children:[F.jsx(pi,{type:"icon-line-copy-right",className:"select-tools-menu-icon"}),F.jsx("div",{className:"select-tools-menu-text",children:e.text})]},e.key):e.key===tv.ask?F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"select-tools-menu-item-line"}),F.jsxs("div",{className:"select-tools-menu-item",onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),n("")},children:[F.jsx(pi,{type:"icon-line-message-circle-02",className:"select-tools-menu-icon"}),F.jsx("div",{className:"select-tools-menu-text",children:e.text})]},e.key)]}):e.key===tv.explain?F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"select-tools-menu-item-line"}),F.jsxs("div",{className:"select-tools-menu-item",onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),null==s||s()},children:[F.jsx(pi,{type:"icon-line-chat-explain",className:"select-tools-menu-icon"}),F.jsx("div",{className:"select-tools-menu-text",children:e.text})]},e.key)]}):e.key===tv.translate&&o&&a?F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"select-tools-menu-item-line"}),F.jsx(Fy,{destroyOnHidden:!0,placement:"bottom",trigger:["click"],languageCode:a,open:g,languages:o,selectLanguage:e=>{null==i||i(e.code)},children:F.jsxs("div",{className:"select-tools-menu-item",onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),null==i||i(a)},children:[F.jsx(pi,{type:"icon-fanyi-translate",className:"select-tools-menu-icon"}),F.jsxs("div",{className:"select-tools-menu-text",children:[e.text,"("+a+")"]}),F.jsxs("span",{className:"seletected-text-button-icon",onClick:e=>{e.stopPropagation(),f(!g)},children:[F.jsx("div",{className:"select-tools-menu-arrow-button",onClick:e=>{e.stopPropagation(),f(!g)}}),F.jsx(pi,{type:"icon-line-chevron-down",className:Q("select-tools-menu-icon select-tools-menu-icon-arrow",{"select-tools-menu-icon-open":g})})]})]})})]}):null)})},pb=({onTranslate:e,languages:t,languageCode:n,popover:s})=>{const[i,a]=D.useState(!1),o=()=>{a(!1)};return D.useEffect(()=>(i?(document.addEventListener("click",o,!0),window.addEventListener("click",o,!0),window.addEventListener("touchStart",o,!0),window.addEventListener("touchmove",o,!0)):(document.removeEventListener("click",o,!0),window.removeEventListener("scroll",o,!0),window.removeEventListener("touchStart",o,!0),window.removeEventListener("touchmove",o,!0)),()=>{document.removeEventListener("click",o,!0),window.removeEventListener("scroll",o,!0),window.removeEventListener("touchStart",o,!0),window.removeEventListener("touchmove",o,!0)}),[i]),F.jsx(Fy,S(C({destroyOnHidden:!0,trigger:["click"],languageCode:n,open:i,languages:t,selectLanguage:t=>{a(!1),null==e||e(t.code)}},s),{children:F.jsxs("div",{className:"select-message-button-language",style:{height:31},id:"select-message-button-language",onClick:e=>{e.stopPropagation(),a(!i)},children:[F.jsx("span",{children:n}),F.jsx("div",{className:"select-message-button-language-icons",children:F.jsx(pi,{type:"icon-language_item_icon"})})]})}))},gb=({menuList:e,onCopyHandler:t,onTranslateHandler:n,languageCode:s,languages:i})=>F.jsx(F.Fragment,{children:null==e?void 0:e.map((a,o)=>a.key===tv.copy?F.jsxs("div",{className:"selece-content-menu-item"+(o{null==n||n(s)},children:[F.jsx("span",{style:{fontWeight:600},children:a.text}),F.jsx(pb,{languageCode:s,languages:i,onTranslate:n})]},a.key):null)}),fb=e=>{var t=e,{type:n,showAskInputChange:s}=t,i=k(t,["type","showAskInputChange"]);return"horizontal"===n?F.jsx(mb,C({showAskInputChange:s},i)):F.jsx(gb,C({},i))},vb={width:420,height:36},yb=D.memo(e=>{var t=e,{children:n,className:s,style:i,menuId:a,disabledContainer:o,offset:r,id:l="container-response-message-content",boxId:c="chat-message-container",offsetTopRef:d,quoteIndex:u}=t,h=k(t,["children","className","style","menuId","disabledContainer","offset","id","boxId","offsetTopRef","quoteIndex"]);const m=D.useRef({x:0,y:0}),p=D.useRef(null),g=D.useRef(null),f=D.useRef(vb),v=D.useRef(!1),y=D.useRef(""),b=D.useRef({show:!1}),x=D.useRef([]),w=D.useMemo(()=>`${a}_select-range-menu-root`,[a]),_=D.useMemo(()=>r||10,[r]),j=D.useCallback(()=>{x.current.forEach(e=>{e.removeEventListener("scroll",()=>{})}),x.current=[]},[]),T=D.useCallback(()=>{try{if(j(),g.current&&p.current)g.current.unmount(),p.current.parentNode&&p.current.parentNode.removeChild(p.current);else{const e=document.getElementById(w);e&&e.parentNode&&e.parentNode.removeChild(e)}}catch(e){}finally{p.current=null,g.current=null}},[w,j]),E=D.useCallback(()=>{var e;null==(e=window.getSelection())||e.removeAllRanges(),T()},[T]),N=D.useCallback(e=>{var t;b.current={show:e},!(null==(t=window.getSelection())?void 0:t.toString())&&!b.current.show&&T()},[T]),I=D.useMemo(()=>{const{onCopyHandler:e,onAskHandler:t,onExplainHandler:n,onTranslateHandler:s}=h;return F.jsx(fb,S(C({type:"horizontal"},h),{onCopyHandler:()=>{null==e||e(y.current),E()},showAskInputChange:N,onAskHandler:e=>{null==t||t(y.current,e,a,null==d?void 0:d.current,(null==u?void 0:u.current)||void 0),d&&(d.current=null),u&&(u.current=null),E()},onExplainHandler:()=>{null==n||n(y.current),E()},onTranslateHandler:e=>{null==s||s(e,y.current),E()}}))},[h,N,E,a]),M=()=>A(null,null,function*(){const{x:e,y:t}=m.current;if(f.current.width===vb.width&&f.current.height===vb.height)try{yield v.current?Promise.resolve(f.current):(v.current=!0,new Promise(e=>{const t=document.createElement("div");Object.assign(t.style,{position:"absolute",visibility:"hidden",pointerEvents:"none",zIndex:"-1",left:"-9999px",top:"-9999px"}),document.body.appendChild(t);const n=G.createRoot(t);n.render(I),requestAnimationFrame(()=>{try{const n=t.getBoundingClientRect(),s={width:n.width||vb.width,height:n.height||vb.height};f.current=s,e(s)}catch(s){e(vb)}finally{n.unmount(),document.body.removeChild(t),v.current=!1}})}))}catch(r){}const{width:n,height:s}=f.current,i=document.getElementById(c);let a=0,o=0;if(i){const r=i.getBoundingClientRect(),l=window.getSelection();if(l&&l.rangeCount>0){const i=l.getRangeAt(0).getBoundingClientRect();(t=>{var n,s,i,a;if(!t||0===t.rangeCount)return!1;try{const e=t.getRangeAt(0).commonAncestorContainer,o=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;if(!o)return!1;let r=o;for(;r;){if((null==(n=r.classList)?void 0:n.contains("monaco-editor"))||(null==(s=r.classList)?void 0:s.contains("overflow-guard"))||(null==(i=r.querySelector)?void 0:i.call(r,".monaco-editor"))||(null==(a=r.querySelector)?void 0:a.call(r,".overflow-guard")))return!0;r=r.parentElement}return!1}catch(e){return!1}})(l)?(a=e-r.left,o=t-r.top+20):(a=i.left-r.left,o=i.bottom-r.top+_);const c=r.width,d=r.height;a+n>c&&(a=Math.max(_,c-n-_)),o+s>d&&(o=Math.max(_,i.top-r.top-s-_)),a<0&&(a=_),o<0&&(o=_)}else{a=e-r.left,o=t-r.top+20;const i=r.width,l=r.height;a+n>i&&(a=Math.max(_,i-n-_)),o+s>l&&(o=Math.max(_,t-r.top-s-_)),a<0&&(a=_),o<0&&(o=_)}}else{const i=window.innerWidth,r=window.innerHeight;a=e,o=t+20,a+n>i&&(a=Math.max(_,i-n-_)),o+s>r&&(o=Math.max(_,t-s-_)),a<0&&(a=_),o<0&&(o=_)}return{x:a,y:o}}),R=D.useCallback(()=>{if(!p.current)return;const e=document.getElementById(l);if(!e)return;const t=document.getElementById(c);if(!t)return;const n=p.current.getBoundingClientRect();let s=e.parentElement,i=!1;for(;s&&s!==t;){const e=window.getComputedStyle(s);if("auto"===e.overflowY||"scroll"===e.overflowY||"auto"===e.overflow||"scroll"===e.overflow){const e=s.getBoundingClientRect(),t=n.bottom<=e.top,a=n.top>=e.bottom;if(t||a){i=!0;break}}s=s.parentElement}p.current.style.opacity=i?"0":"1"},[l,c]),P=D.useCallback(()=>{j();const e=document.getElementById(c);if(!e)return;const t=()=>A(null,null,function*(){if(p.current&&g.current)try{const e=yield M();p.current.style.left=`${e.x}px`,p.current.style.top=`${e.y}px`,R()}catch(e){}}),n=[];n.push(e),e.querySelectorAll("*").forEach(e=>{const t=e,s=window.getComputedStyle(t);("auto"===s.overflow||"scroll"===s.overflow||"auto"===s.overflowY||"scroll"===s.overflowY||"auto"===s.overflowX||"scroll"===s.overflowX)&&n.push(t)}),n.forEach(e=>{e.addEventListener("scroll",t,{passive:!0})}),x.current=n},[c,M,j]);return D.useEffect(()=>{const e=()=>{var e;!(null==(e=window.getSelection())?void 0:e.toString())&&!b.current.show&&T()};return document.addEventListener("selectionchange",e),()=>{document.removeEventListener("selectionchange",e),T()}},[T]),F.jsx("div",{className:s,style:C({},i),onMouseMove:e=>{o||(m.current={x:e.clientX,y:e.clientY})},onMouseUp:()=>{if(o)return;const e=window.getSelection();if(e&&e.toString()){y.current=e.toString();const t=e.anchorNode;if(!t)return;let n=null;if(t.nodeType===Node.TEXT_NODE&&t.parentElement?n=t.parentElement.closest(".chat-response-message"):t instanceof Element&&(n=t.closest(".chat-response-message")),n){let e=t;t.nodeType===Node.TEXT_NODE&&(e=t.parentElement);let s=0,i=e;for(;i&&i!==n;)s+=i.offsetTop,i=i.offsetParent;const a=document.getElementById("chat-message-container");if(a){const t=n.getBoundingClientRect(),i=a.getBoundingClientRect();if(d){const e=t.top-i.top;d.current=s-e-96}if(u){const t=n.querySelector(".qwen-markdown");u.current=((e,t)=>{if(e===t)return 0;if(!e.contains(t))return null;const n=Array.from(e.children);for(let s=0;s{A(null,null,function*(){try{T();const e=yield M();if(!document.getElementById(l))return;const t=document.getElementById(c);if(!t)return;const n=document.createElement("div");n.className=w,n.id=w,Object.assign(n.style,{position:"absolute",left:"0px",top:"0px",zIndex:"10000",opacity:"1"}),t.appendChild(n),p.current=n,g.current=G.createRoot(n),g.current&&p.current&&(p.current.style.left=`${e.x}px`,p.current.style.top=`${e.y}px`,g.current.render(I),R()),P()}catch(e){}})},0)}},children:n})}),bb=({style:e=null,idString:t=""})=>F.jsxs("div",{id:t,className:"joystick",style:e||void 0,children:[F.jsx("div",{className:"joystick-line"}),F.jsx("div",{className:"joystick-dot"}),F.jsx("div",{className:"joystick-dot-shadow"})]}),xb=({contentText:e="",show:t=!1,className:n,style:s,languageCode:i="",menuList:a,languages:o,onCopyHandler:r,onTranslateHandler:l})=>{const[c,d]=D.useState(!1),[u,h]=D.useState(-1e4),[m,p]=D.useState(-1e4),g=D.useRef(null),f=D.useRef(null),v=D.useRef(null),y=D.useRef(null),b=D.useRef(null),x=D.useRef(null),w=D.useRef(null),_=D.useRef(null),S=D.useRef(null),k=D.useRef(null),j=D.useRef(void 0),T=D.useRef({startX:0,startY:0}),E=D.useRef({endX:0,endY:0}),N=D.useRef(!1),I=D.useRef(!0),A=D.useRef(!1),M=D.useRef(!1),R=D.useCallback(()=>{if(g.current){const e=g.current.getBoundingClientRect();j.current=e,v.current&&(v.current.style.maxWidth=`${e.width}px`)}},[]),P=D.useCallback(()=>{w.current&&(clearTimeout(w.current),w.current=null),I.current=!1},[]),L=D.useCallback(()=>{d(!1),h(-1e5),p(-1e5)},[]),O=D.useCallback(()=>{L(),P(),I.current=!1,k.current=null,S.current=null,v.current&&(v.current.style.left="-1000px",v.current.style.top="-1000px",y.current&&(y.current.innerHTML=""))},[L,P]),q=D.useCallback((e,t)=>{const n=document.createRange();n.setStart(e.startContainer,e.startOffset),n.setEnd(t.endContainer,t.endOffset);const s=e.getBoundingClientRect();return{startOffset:n.startOffset,endOffset:n.endOffset,text:n.toString(),rangeX:s.x,rangeY:s.y}},[]),U=D.useCallback((e,t)=>{let n=null;if(document.caretPositionFromPoint){const s=document.caretPositionFromPoint(e,t);s&&(n=document.createRange(),n.setStart(s.offsetNode,s.offset),n.setEnd(s.offsetNode,s.offset))}else document.caretRangeFromPoint?n=document.caretRangeFromPoint(e,t):document.body.createTextRange&&(n=document.body.createTextRange(),n.moveToPoint(e,t));return n},[]),H=D.useCallback((e,t,n,s)=>{if(M.current){const e=j.current?j.current.y:60;t=t{if(!n||!s)return null!=i?i:null;if(!i)return null;if(s{R(),N.current=!1},[R]),G=D.useCallback(Le(z,100),[z]),$=D.useCallback(Oe(e=>{if(!f.current)return;const{scrollTop:t,scrollHeight:n,clientHeight:s}=f.current;e.clientY<85&&t>10&&(N.current=!0,f.current.scrollBy({top:-200,behavior:"smooth"})),e.clientY>window.innerHeight-40&&t+s&&n-20&&(N.current=!0,f.current.scrollBy({top:200,behavior:"smooth"}))},300),[]),W=D.useCallback((t,n)=>{if(!N.current){if(t){let{startOffset:s,endOffset:i,text:a,rangeX:o,rangeY:r}=t;o&&r&&j.current&&y.current&&v.current&&(n&&(i=s+4,a=null==e?void 0:e.substring(s,i)),v.current.style.left=`${j.current.x}px`,v.current.style.top=r-j.current.y+"px",y.current.innerHTML=`${a}`,v.current.style.textIndent=o-j.current.x+"px")}A.current=!1}},[e]),V=D.useCallback(()=>{var e;if(!x.current)return null;const t=x.current.getBoundingClientRect(),n=null==(e=x.current.getElementsByClassName("joystick-dot-shadow")[0])?void 0:e.getBoundingClientRect();return t&&n?(E.current={endX:t.x,endY:t.y},{y:[n.y,n.y+n.height],x:[n.x,n.x+n.width]}):null},[]),K=D.useCallback(()=>{var e;if(!b.current)return null;const t=b.current.getBoundingClientRect(),n=null==(e=b.current.getElementsByClassName("joystick-dot-shadow")[0])?void 0:e.getBoundingClientRect();return n&&t?(T.current={startX:t.x,startY:t.y},{y:[n.y,n.y+n.height],x:[n.x,n.x+n.width]}):null},[]),Y=D.useCallback(()=>{if(j.current&&g.current){if(M.current){if(b.current){const e=b.current.getBoundingClientRect();if(e)return{y:e.y-j.current.y+(g.current.scrollTop||0),x:e.x-j.current.x}}}else if(x.current){const e=x.current.getBoundingClientRect();if(e)return{y:e.y-j.current.y+(g.current.scrollTop||0),x:e.x-j.current.x}}return null}},[]),J=D.useCallback(e=>{const t=V(),n=K();if(t&&n){if(e.clientX>t.x[0]&&e.clientXt.y[0]&&e.clientYn.x[0]&&e.clientXn.y[0]&&e.clientY{if(_.current&&clearTimeout(_.current),!j.current||!g.current)return;const e=Y();e&&(d(!0),_.current=setTimeout(()=>{const t=document.getElementById("selece-content-menu");if(!t||!j.current||!g.current)return;const n=t.offsetWidth,s=t.offsetHeight;let i=e.y+40,a=e.x;a+n+10>j.current.x+j.current.width?a=j.current.x+j.current.width-n-10:awindow.innerHeight?i=e.y-s-40+20:i-g.current.scrollTop+j.current.y<40&&(i=40-j.current.y+g.current.scrollTop),h(i),p(a)},100))},[Y]),Z=D.useCallback(()=>y.current&&y.current.textContent||"",[]);D.useEffect(()=>{const e=f.current,t=e=>{e.preventDefault()};return I.current&&e?null==e||e.addEventListener("touchmove",t,{passive:!1}):null==e||e.removeEventListener("touchmove",t),()=>{null==e||e.removeEventListener("touchmove",t)}},[f.current,I.current]);const ee=D.useCallback(e=>{if(_.current&&clearTimeout(_.current),L(),P(),!e.touches.length||e.touches.length>1)return;const t=e.touches[0];R();const n=J(t);if(n)return M.current="start"===n,void(I.current=!0);O(),w.current=setTimeout(()=>{I.current=!0,T.current={startX:t.clientX,startY:t.clientY},A.current=!0;const e=H(t.clientX,t.clientY);W(e,!0)},500)},[L,P,R,J,O,H,W]),te=D.useCallback(Oe(e=>{if(!e.touches.length||e.touches.length>1)return P(),void L();if(I.current){const t=e.touches[0];if($(t),N.current||A.current)return;let n;A.current=!0,M.current?(n=H(t.clientX,t.clientY,E.current.endX,E.current.endY),n=B(t.clientX,t.clientY,E.current.endX,E.current.endY,n)):(n=H(T.current.startX,T.current.startY,t.clientX,t.clientY),n=B(T.current.startX,T.current.startY,t.clientX,t.clientY,n)),W(n)}else P()},50),[P,L,$,H,B,W]),ne=D.useCallback(()=>{I.current&&(Z()?X():O()),P()},[Z,X,O,P]),se=D.useCallback(e=>{e.stopPropagation()},[]),ie=D.useCallback(e=>{var t;e.preventDefault(),null==(t=window.getSelection())||t.removeAllRanges()},[]);D.useEffect(()=>(t?(document.addEventListener("selectionchange",ie),document.addEventListener("contextmenu",ie),document.addEventListener("click",O)):(document.removeEventListener("selectionchange",ie),document.removeEventListener("contextmenu",ie),document.removeEventListener("click",O)),()=>{document.removeEventListener("selectionchange",ie),document.removeEventListener("contextmenu",ie),document.removeEventListener("click",O),_.current&&clearTimeout(_.current),w.current&&clearTimeout(w.current)}),[t,ie,O]);const ae=D.useCallback(()=>{null==r||r(Z()),O()},[Z,O]),oe=D.useCallback(e=>{null==l||l(e,Z()),O()},[Z,l]);return F.jsxs("div",{ref:f,className:Q("selectContent-outer-container",{},n),style:C({},s),id:"selectContent-outer-container",onTouchStart:ee,onTouchMove:te,onTouchEnd:ne,onScroll:G,onClick:se,children:[F.jsx("div",{ref:g,id:"selectContent-container",className:"selectContent-container",children:e}),F.jsxs("div",{ref:v,className:"anchor-point",id:"anchor-point",children:[F.jsx("span",{ref:b,id:"select-point-start",className:"joystick-container",children:F.jsx(bb,{style:{transform:"rotate(180deg)"},idString:"joystick-start"})}),F.jsx("span",{ref:y,id:"select-range-content",className:"select-range-content"}),F.jsx("span",{ref:x,id:"select-point-end",className:"joystick-container",children:F.jsx(bb,{idString:"joystick-start"})})]}),c&&a&&o&&F.jsx("div",{id:"selece-content-menu",className:"selece-content-menu",style:{top:`${u}px`,left:`${m}px`},onClick:se,onTouchStart:se,onTouchMove:se,onTouchEnd:se,children:F.jsx(fb,{menuList:a,type:"vertical",onCopyHandler:ae,onTranslateHandler:oe,languageCode:i,languages:o})})]})},wb=D.memo(e=>{const t=e,{type:n=ev.container,className:s,style:i,children:a,disabledContainer:o,askInputPlaceholder:r,contentText:l,show:c,languageCode:d,menuList:u,languages:h,menuId:m,offset:p,boxId:g,onCopyHandler:f,onAskHandler:v,onExplainHandler:y,onTranslateHandler:b}=t,x=k(t,["type","className","style","children","disabledContainer","askInputPlaceholder","contentText","show","languageCode","menuList","languages","menuId","offset","boxId","onCopyHandler","onAskHandler","onExplainHandler","onTranslateHandler"]),w=D.useRef(null),_=D.useRef(null),j={children:a,disabledContainer:o,askInputPlaceholder:r,contentText:l,show:c,languageCode:d,menuList:u,languages:h,offset:p,onCopyHandler:f,onAskHandler:v,onExplainHandler:y,onTranslateHandler:b},{mobile:T}=Hf();return n===ev.container&&T?F.jsx("div",S(C({className:s,style:C({},i)},x),{children:a})):n===ev.container?F.jsx(yb,C({className:s,menuId:m,id:x.id,boxId:g,style:i,offsetTopRef:w,quoteIndex:_},j)):n===ev.content?F.jsx(xb,C({className:s,style:i},j)):null}),_b=e=>{var t=e,{drawer:n,title:s,useSystemSelect:i,onClose:a}=t,o=k(t,["drawer","title","useSystemSelect","onClose"]);return o.show?F.jsx(ee,C({placement:"bottom",closable:!1,onClose:a,size:"large",height:window.innerHeight,open:o.show,drawerRender:()=>F.jsxs("div",{className:"contentCopy-container",children:[F.jsxs("div",{className:"contentCopy-header",children:[F.jsx("div",{className:"contentCopy-header-title",children:s}),F.jsx("div",{className:"contentCopy-header-close",children:F.jsx(pi,{type:"icon-line-x-01"})}),F.jsx("div",{className:"contentCopy-header-close-button",onClick:a})]}),i?F.jsx("div",{className:"contentCopy-content",children:o.contentText}):F.jsx(wb,S(C({menuId:"select-range-provider-content"},o),{type:ev.content}))]})},n),"bottom"):null},Cb=({isLoading:e=!1,showCode:t,tabsTitles:n,setShowCode:s,size:i="middle",isAbsoluteCenter:a=!0,className:o})=>F.jsxs("div",{className:`artifacts-body-header-switch header-switch-${i} ${a?"header-switch-absolute-center":""} ${o}`,children:[F.jsx("div",{className:`artifacts-body-header-switch-${t?"active":"unactive"} header-switch-status-${i}`,onClick:()=>{e||s(!0)},children:(null==n?void 0:n.code)||"Code"}),F.jsx("div",{className:`artifacts-body-header-switch-${t?"unactive":"active"} ${e?"artifacts-body-header-switch-disabled":""} header-switch-status-${i}`,onClick:()=>{e||s(!1)},children:e?F.jsx(J,{title:(null==n?void 0:n.disabledPreview)||"Please wait until the generation is complete.",children:F.jsx("span",{children:(null==n?void 0:n.preview)||"Preview"})}):(null==n?void 0:n.preview)||"Preview"})]}),Sb=({pageScalePercent:e=1,onZoomIn:t,onZoomOut:n})=>{const s=`${Math.round(100*e)}%`;return F.jsx("div",{className:"web-viewer-tool-bar",children:F.jsxs("div",{className:"web-viewer-tool-bar-zoom",children:[F.jsx("div",{onClick:()=>{n&&n()},className:"web-viewer-tool-bar-zoom-button web-viewer-tool-bar-button",children:F.jsx(pi,{type:"icon-line-zoom-out"})}),F.jsx("span",{children:s}),F.jsx("div",{onClick:()=>{t&&t()},className:"web-viewer-tool-bar-zoom-button web-viewer-tool-bar-button",children:F.jsx(pi,{type:"icon-line-zoom-in"})})]})})},kb=D.forwardRef(({activeTab:e,previewUrl:t,refreshKey:n,onIframeLoad:s,onIframeError:i,sandbox:a="allow-scripts allow-same-origin allow-forms allow-popups",loadingRender:o,errorRender:r,showToolbar:l=!1,iframeClassName:c,iframeKey:d},u)=>{const h=D.useRef(null),m=D.useRef(null),[p,g]=D.useState(!0),[f,v]=D.useState(!1),[y,b]=D.useState(0),[x,w]=D.useState(1),_=D.useCallback(()=>{w(e=>Math.min(+(e+.1).toFixed(1),2))},[]),C=D.useCallback(()=>{w(e=>Math.max(+(e-.1).toFixed(1),.5))},[]);D.useImperativeHandle(u,()=>h.current,[d]),D.useEffect(()=>{const t=m.current;if(!t||"mobile"!==e)return;const n=new ResizeObserver(()=>{b(t.offsetHeight)});return n.observe(t),()=>n.disconnect()},[e]);const S=x>1?y*(x-1):0;D.useEffect(()=>{h.current&&t&&(g(!0),v(!1),h.current.src=t)},[n]);const k=D.useCallback(()=>{g(!1),null==s||s()},[s]),j=D.useCallback(()=>{g(!1),v(!0),null==i||i()},[i]),T=["web-viewer-iframe",c].filter(Boolean).join(" ");return F.jsxs(F.Fragment,{children:[F.jsxs("div",{className:"web-viewer-iframe-container "+("mobile"===e?"mobile-mode":"pc-mode"),style:"mobile"===e&&x>1?{alignItems:"flex-start",paddingTop:24}:void 0,children:[p&&null!==o&&F.jsx("div",{className:"web-viewer-loading",children:o?o():"Loading preview..."}),f&&null!==r&&F.jsx("div",{className:"web-viewer-error",children:r?r():F.jsxs(F.Fragment,{children:[F.jsx(pi,{type:"icon-line-alert-circle",className:"web-viewer-error-icon"}),F.jsx("span",{className:"web-viewer-error-text",children:"Failed to load preview"})]})}),F.jsx("div",{ref:m,className:"iframe-wrapper",style:"mobile"===e?{transform:`scale(${x})`,transformOrigin:"top center",marginBottom:S||void 0}:void 0,children:F.jsx("iframe",{ref:h,className:T,src:t,sandbox:a,onLoad:k,onError:j,style:{display:p||f?"none":"block"}},d)})]}),l&&"mobile"===e&&F.jsx(Sb,{pageScalePercent:x,onZoomIn:_,onZoomOut:C})]})});var jb,Tb={exports:{}};var Eb,Nb,Ib,Ab,Mb,Rb,Pb,Lb,Ob,Db,Fb,qb={exports:{}};function Ub(){if(Nb)return Eb;Nb=1;var e=.1,t="function"==typeof Float32Array;function n(e,t){return 1-3*t+3*e}function s(e,t){return 3*t-6*e}function i(e){return 3*e}function a(e,t,a){return((n(t,a)*e+s(t,a))*e+i(t))*e}function o(e,t,a){return 3*n(t,a)*e*e+2*s(t,a)*e+i(t)}function r(e){return e}return Eb=function(n,s,i,l){if(!(0<=n&&n<=1&&0<=i&&i<=1))throw new Error("bezier x values must be in [0, 1] range");if(n===s&&i===l)return r;for(var c=t?new Float32Array(11):new Array(11),d=0;d<11;++d)c[d]=a(d*e,n,i);function u(t){for(var s=0,r=1;10!==r&&c[r]<=t;++r)s+=e;--r;var l=s+(t-c[r])/(c[r+1]-c[r])*e,d=o(l,n,i);return d>=.001?function(e,t,n,s){for(var i=0;i<4;++i){var r=o(t,n,s);if(0===r)return t;t-=(a(t,n,s)-e)/r}return t}(t,l,n,i):0===d?l:function(e,t,n,s,i){var o,r,l=0;do{(o=a(r=t+(n-t)/2,s,i)-e)>0?n=r:t=r}while(Math.abs(o)>1e-7&&++l<10);return r}(t,s,s+e,n,i)}return function(e){return 0===e?0:1===e?1:a(u(e),s,l)}}}function Hb(){if(Ib)return qb.exports;Ib=1;var e=Ub(),t={ease:e(.25,.1,.25,1),easeIn:e(.42,0,1,1),easeOut:e(0,0,.58,1),easeInOut:e(.42,0,.58,1),linear:e(0,0,1,1)};function n(){}function s(){var e=new Set,t=new Set,n=0;return{next:s,cancel:s,clearAll:function(){e.clear(),t.clear(),cancelAnimationFrame(n),n=0}};function s(e){t.add(e),n||(n=requestAnimationFrame(i))}function i(){n=0;var s=t;t=e,(e=s).forEach(function(e){e()}),e.clear()}}return qb.exports=function(e,s,i){var a=Object.create(null),o=Object.create(null),r="function"==typeof(i=i||{}).easing?i.easing:t[i.easing];r||(i.easing,r=t.ease);var l="function"==typeof i.step?i.step:n,c="function"==typeof i.done?i.done:n,d=function(e){if(!e){return"undefined"!=typeof window&&window.requestAnimationFrame?{next:window.requestAnimationFrame.bind(window),cancel:window.cancelAnimationFrame.bind(window)}:{next:function(e){return setTimeout(e,1e3/60)},cancel:function(e){return clearTimeout(e)}}}if("function"!=typeof e.next)throw new Error("Scheduler is supposed to have next(cb) function");if("function"!=typeof e.cancel)throw new Error("Scheduler is supposed to have cancel(handle) function");return e}(i.scheduler),u=Object.keys(s);u.forEach(function(t){a[t]=e[t],o[t]=s[t]-e[t]});var h,m="number"==typeof i.duration?i.duration:400,p=Math.max(1,.06*m),g=0;return h=d.next(function t(){var n=r(g/p);g+=1,f(n),g<=p?(h=d.next(t),l(e)):(h=0,setTimeout(function(){c(e)},0))}),{cancel:function(){d.cancel(h),h=0}};function f(t){u.forEach(function(n){e[n]=o[n]*t+a[n]})}},qb.exports.makeAggregateRaf=s,qb.exports.sharedScheduler=s(),qb.exports}function Bb(){if(Mb)return Ab;return Mb=1,Ab=function(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");const t=["on","fire","off"];for(let n=0;n"u")return t=Object.create(null),e;if(t[n])if("function"!=typeof s)delete t[n];else{const e=t[n];for(let t=0;t1&&(i=Array.prototype.slice.call(arguments,1));for(let e=0;em)&&(r+=l=p*o);(c<-m||c>m)&&(d+=u=p*c);h=f(y)},cancel:function(){g(a),g(h)}};function v(){var t=Date.now(),n=t-i;i=t;var r=e(),l=r.x-s.x,d=r.y-s.y;s=r;var u=1e3/(1+n);o=.8*l*u+.2*o,c=.8*d*u+.2*c,a=f(v)}function y(){var e=Date.now()-i,n=!1,s=0,a=0;l&&((s=-l*Math.exp(-e/342))>.5||s<-.5?n=!0:s=l=0),u&&((a=-u*Math.exp(-e/342))>.5||a<-.5?n=!0:a=u=0),n&&(t(r+s,d+a),h=f(y))}}}var Gb,$b={exports:{}};var Wb,Vb,Qb,Kb={exports:{}};const Yb=U(function(){if(Qb)return Vb;Qb=1;var e=function(){if(jb)return Tb.exports;function e(e,t,n){e.addEventListener("wheel",t,n)}return jb=1,Tb.exports=e,Tb.exports.addWheelListener=e,Tb.exports.removeWheelListener=function(e,t,n){e.removeEventListener("wheel",t,n)},Tb.exports}(),t=Hb(),n=Bb(),s=zb(),i=function(){if(Ob)return Lb;function e(e){return e.stopPropagation(),!1}function t(){}return Ob=1,Lb=function(n){if(n)return{capture:t,release:t};var s,i,a,o=!1;return{capture:function(t){o=!0,i=window.document.onselectstart,a=window.document.ondragstart,window.document.onselectstart=e,(s=t).ondragstart=e},release:function(){o&&(o=!1,window.document.onselectstart=i,s&&(s.ondragstart=a))}}}}(),a=i(),o=i(!0),r=Fb?Db:(Fb=1,Db=function(){this.x=0,this.y=0,this.scale=1}),l=function(){if(Gb)return $b.exports;function e(e){return e&&e.ownerSVGElement&&e.getCTM}return Gb=1,$b.exports=function(t,n){if(!e(t))throw new Error("svg element is required for svg.panzoom to work");var s=t.ownerSVGElement;if(!s)throw new Error("Do not apply panzoom to the root element. Use its child instead (e.g. ). As of March 2016 only FireFox supported transform on the root element");return n.disableKeyboardInteraction||s.setAttribute("tabindex",0),{getBBox:function(){var e=t.getBBox();return{left:e.x,top:e.y,width:e.width,height:e.height}},getScreenCTM:function(){var e=s.getCTM();return e||s.getScreenCTM()},getOwner:function(){return s},applyTransform:function(e){t.setAttribute("transform","matrix("+e.scale+" 0 0 "+e.scale+" "+e.x+" "+e.y+")")},initTransform:function(e){var n=t.getCTM();null===n&&(n=document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGMatrix()),e.x=n.e,e.y=n.f,e.scale=n.a,s.removeAttributeNS(null,"viewBox")}}},$b.exports.canAttach=e,$b.exports}(),c=function(){if(Wb)return Kb.exports;function e(e){return e&&e.parentElement&&e.style}return Wb=1,Kb.exports=function(t,n){if(!e(t))throw new Error("panzoom requires DOM element to be attached to the DOM tree");var s=t.parentElement;return t.scrollTop=0,n.disableKeyboardInteraction||s.setAttribute("tabindex",0),{getBBox:function(){return{left:0,top:0,width:t.clientWidth,height:t.clientHeight}},getOwner:function(){return s},applyTransform:function(e){t.style.transformOrigin="0 0 0",t.style.transform="matrix("+e.scale+", 0, 0, "+e.scale+", "+e.x+", "+e.y+")"}}},Kb.exports.canAttach=e,Kb.exports}();function d(i,d){var h=(d=d||{}).controller;if(h||(l.canAttach(i)?h=l(i,d):c.canAttach(i)&&(h=c(i,d))),!h)throw new Error("Cannot create panzoom for the current type of dom element");var f=h.getOwner(),v={x:0,y:0},y=!1,b=new r;h.initTransform&&h.initTransform(b);var x,w="function"==typeof d.filterKey?d.filterKey:m,_="number"==typeof d.pinchSpeed?d.pinchSpeed:1,C=d.bounds,S="number"==typeof d.maxZoom?d.maxZoom:Number.POSITIVE_INFINITY,k="number"==typeof d.minZoom?d.minZoom:0,j="number"==typeof d.boundsPadding?d.boundsPadding:.05,T="number"==typeof d.zoomDoubleClickSpeed?d.zoomDoubleClickSpeed:1.75,E=d.beforeWheel||m,N=d.beforeMouseDown||m,I="number"==typeof d.zoomSpeed?d.zoomSpeed:1,A=u(d.transformOrigin),M=d.enableTextSelection?o:a;!function(e){var t=typeof e;if("undefined"===t||"boolean"===t)return;var n=p(e.left)&&p(e.top)&&p(e.bottom)&&p(e.right);if(!n)throw new Error("Bounds object is not valid. It can be: undefined, boolean (true|false) or an object {left, top, right, bottom}")}(C),d.autocenter&&function(){var e,t,n=0,s=0,i=ae();if(i)n=i.left,s=i.top,e=i.right-i.left,t=i.bottom-i.top;else{var a=f.getBoundingClientRect();e=a.width,t=a.height}var o=h.getBBox();if(0===o.width||0===o.height)return;var r=t/o.height,l=e/o.width,c=Math.min(l,r);b.x=-(o.left+o.width/2)*c+e/2+n,b.y=-(o.top+o.height/2)*c+t/2+s,b.scale=c}();var R,P,L,O,D,F,q,U,H,B,z=0,G=0,$=0,W=null,V=new Date,Q=!1,K=!1;q="smoothScroll"in d&&!d.smoothScroll?{start:m,stop:m,cancel:m}:s(function(){return{x:b.x,y:b.y}},function(e,t){Me(),ne(e,t)},d.smoothScroll);var Y=!1;de();var J={dispose:function(){ue()},moveBy:ce,moveTo:ne,smoothMoveTo:function(e,t){ce(e-b.x,t-b.y,!0)},centerOn:function(e){var t=e.ownerSVGElement;if(!t)throw new Error("ui element is required to be within the scene");var n=e.getBoundingClientRect(),s=n.left+n.width/2,i=n.top+n.height/2,a=t.getBoundingClientRect(),o=a.width/2-s,r=a.height/2-i;ce(o,r,!0)},zoomTo:Ae,zoomAbs:le,smoothZoom:Ne,smoothZoomAbs:function(e,n,s){var i={scale:b.scale},a={scale:s};q.cancel(),Me(),H=t(i,a,{step:function(t){le(e,n,t.scale)},done:Oe})},showRectangle:function(e){var t=f.getBoundingClientRect(),n=te(t.width,t.height),s=e.right-e.left,i=e.bottom-e.top;if(!Number.isFinite(s)||!Number.isFinite(i))throw new Error("Invalid rectangle");var a=n.x/s,o=n.y/i,r=Math.min(a,o);b.x=-(e.left+s/2)*r+n.x/2,b.y=-(e.top+i/2)*r+n.y/2,b.scale=r},pause:function(){ue(),Y=!0},resume:function(){Y&&(de(),Y=!1)},isPaused:function(){return Y},getTransform:function(){return b},getMinZoom:function(){return k},setMinZoom:function(e){k=e},getMaxZoom:function(){return S},setMaxZoom:function(e){S=e},getTransformOrigin:function(){return A},setTransformOrigin:function(e){A=u(e)},getZoomSpeed:function(){return I},setZoomSpeed:function(e){if(!Number.isFinite(e))throw new Error("Zoom speed should be a number");I=e}};n(J);var X="number"==typeof d.initialX?d.initialX:b.x,Z="number"==typeof d.initialY?d.initialY:b.y,ee="number"==typeof d.initialZoom?d.initialZoom:b.scale;return X==b.x&&Z==b.y&&ee==b.scale||le(X,Z,ee),J;function te(e,t){if(h.getScreenCTM){var n=h.getScreenCTM(),s=n.a,i=n.d,a=n.e,o=n.f;v.x=e*s-a,v.y=t*i-o}else v.x=e,v.y=t;return v}function ne(e,t){b.x=e,b.y=t,ie(),De("pan"),oe()}function se(e,t){ne(b.x+e,b.y+t)}function ie(){var e=ae();if(e){var t,n,s,i,a=!1,o=(t=h.getBBox(),s=t.left,i=t.top,{left:(n={x:s*b.scale+b.x,y:i*b.scale+b.y}).x,top:n.y,right:t.width*b.scale+n.x,bottom:t.height*b.scale+n.y}),r=e.left-o.right;return r>0&&(b.x+=r,a=!0),(r=e.right-o.left)<0&&(b.x+=r,a=!0),(r=e.top-o.bottom)>0&&(b.y+=r,a=!0),(r=e.bottom-o.top)<0&&(b.y+=r,a=!0),a}}function ae(){if(C){if("boolean"==typeof C){var e=f.getBoundingClientRect(),t=e.width,n=e.height;return{left:t*j,top:n*j,right:t*(1-j),bottom:n*(1-j)}}return C}}function oe(){y=!0,x=window.requestAnimationFrame(he)}function re(e,t,n){if(g(e)||g(t)||g(n))throw new Error("zoom requires valid numbers");var s=b.scale*n;if(sS){if(b.scale===S)return;n=S/b.scale}var i=te(e,t);(b.x=i.x-n*(i.x-b.x),b.y=i.y-n*(i.y-b.y),C&&1===j&&1===k)?(b.scale*=n,ie()):ie()||(b.scale*=n);De("zoom"),oe()}function le(e,t,n){re(e,t,n/b.scale)}function ce(e,n,s){if(!s)return se(e,n);U&&U.cancel();var i=0,a=0;U=t({x:0,y:0},{x:e,y:n},{step:function(e){se(e.x-i,e.y-a),i=e.x,a=e.y}})}function de(){f.addEventListener("mousedown",_e,{passive:!1}),f.addEventListener("dblclick",we,{passive:!1}),f.addEventListener("touchstart",pe,{passive:!1}),f.addEventListener("keydown",me,{passive:!1}),e.addWheelListener(f,Te,{passive:!1}),oe()}function ue(){e.removeWheelListener(f,Te),f.removeEventListener("mousedown",_e),f.removeEventListener("keydown",me),f.removeEventListener("dblclick",we),f.removeEventListener("touchstart",pe),x&&(window.cancelAnimationFrame(x),x=0),q.cancel(),ke(),je(),M.release(),Le()}function he(){y&&(y=!1,h.applyTransform(b),De("transform"),x=0)}function me(e){var t=0,n=0,s=0;if(38===e.keyCode?n=1:40===e.keyCode?n=-1:37===e.keyCode?t=1:39===e.keyCode?t=-1:189===e.keyCode||109===e.keyCode?s=1:187!==e.keyCode&&107!==e.keyCode||(s=-1),!w(e,t,n,s)){if(t||n){e.preventDefault(),e.stopPropagation();var i=f.getBoundingClientRect();ce(.05*(a=Math.min(i.width,i.height))*t,.05*a*n)}if(s){var a,o=Re(100*s);Ae((a=A?Ie():{x:(r=f.getBoundingClientRect()).width/2,y:r.height/2}).x,a.y,o)}var r}}function pe(e){if(function(e){if(d.onTouch&&!d.onTouch(e))return;e.stopPropagation(),e.preventDefault()}(e),ve(),1===e.touches.length)return function(e){G=new Date;var t=e.touches[0],n=Ee(t);R=n;var s=te(n.x,n.y);P=s.x,L=s.y,O=P,D=L,q.cancel(),ge()}(e,e.touches[0]);2===e.touches.length&&(F=xe(e.touches[0],e.touches[1]),B=!0,ge())}function ge(){Q||(Q=!0,document.addEventListener("touchmove",fe),document.addEventListener("touchend",be),document.addEventListener("touchcancel",be))}function fe(e){if(1===e.touches.length){e.stopPropagation();var t=te((d=Ee(e.touches[0])).x,d.y),n=t.x-P,s=t.y-L;0!==n&&0!==s&&Pe(),P=t.x,L=t.y,ce(n,s)}else if(2===e.touches.length){B=!0;var i=e.touches[0],a=e.touches[1],o=xe(i,a),r=1+(o/F-1)*_,l=Ee(i),c=Ee(a);if(P=(l.x+c.x)/2,L=(l.y+c.y)/2,A){var d=Ie();P=d.x,L=d.y}Ae(P,L,r),F=o,e.stopPropagation(),e.preventDefault()}}function ve(){$&&(clearTimeout($),$=0)}function ye(e){if(d.onClick){ve();var t=P-O,n=L-D;Math.sqrt(t*t+n*n)>5||($=setTimeout(function(){$=0,d.onClick(e)},300))}}function be(e){if(ve(),e.touches.length>0){var t=te((n=Ee(e.touches[0])).x,n.y);P=t.x,L=t.y}else{var n,s=new Date;if(s-z<300)if(A)Ne((n=Ie()).x,n.y,T);else Ne(R.x,R.y,T);else s-G<200&&ye(e);z=s,Le(),je()}}function xe(e,t){var n=e.clientX-t.clientX,s=e.clientY-t.clientY;return Math.sqrt(n*n+s*s)}function we(e){!function(e){ve(),d.onDoubleClick&&!d.onDoubleClick(e)||(e.preventDefault(),e.stopPropagation())}(e);var t=Ee(e);A&&(t=Ie()),Ne(t.x,t.y,T)}function _e(e){if(ve(),!N(e)){if(W=e,V=new Date,Q)return e.stopPropagation(),!1;if(1===e.button&&null!==window.event||0===e.button){q.cancel();var t=Ee(e),n=te(t.x,t.y);return O=P=n.x,D=L=n.y,document.addEventListener("mousemove",Ce),document.addEventListener("mouseup",Se),M.capture(e.target||e.srcElement),!1}}}function Ce(e){if(!Q){Pe();var t=Ee(e),n=te(t.x,t.y),s=n.x-P,i=n.y-L;P=n.x,L=n.y,ce(s,i)}}function Se(){new Date-V<200&&ye(W),M.release(),Le(),ke()}function ke(){document.removeEventListener("mousemove",Ce),document.removeEventListener("mouseup",Se),K=!1}function je(){document.removeEventListener("touchmove",fe),document.removeEventListener("touchend",be),document.removeEventListener("touchcancel",be),K=!1,B=!1,Q=!1}function Te(e){if(!E(e)){q.cancel();var t=e.deltaY;e.deltaMode>0&&(t*=100);var n=Re(t);if(1!==n){var s=A?Ie():Ee(e);Ae(s.x,s.y,n),e.preventDefault()}}}function Ee(e){var t=f.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function Ne(e,n,s){var i=b.scale,a={scale:i},o={scale:s*i};q.cancel(),Me(),H=t(a,o,{step:function(t){le(e,n,t.scale)},done:Oe})}function Ie(){var e=f.getBoundingClientRect();return{x:e.width*A.x,y:e.height*A.y}}function Ae(e,t,n){return q.cancel(),Me(),re(e,t,n)}function Me(){H&&(H.cancel(),H=null)}function Re(e){return 1-Math.sign(e)*Math.min(.25,Math.abs(I*e/128))}function Pe(){K||(De("panstart"),K=!0,q.start())}function Le(){K&&(B||q.stop(),De("panend"))}function Oe(){De("zoomend")}function De(e){J.fire(e,J)}}function u(e){if(e)return"object"==typeof e?(p(e.x)&&p(e.y)||h(e),e):void h()}function h(e){throw new Error(["Cannot parse transform origin.","Some good examples:",' "center center" can be achieved with {x: 0.5, y: 0.5}',' "top center" can be achieved with {x: 0.5, y: 0}',' "bottom right" can be achieved with {x: 1, y: 1}'].join("\n"))}function m(){}function p(e){return Number.isFinite(e)}function g(e){return Number.isNaN?Number.isNaN(e):e!=e}return Vb=d,function(){if("undefined"!=typeof document){var e=document.getElementsByTagName("script");if(e){for(var t,n=0;n{const{className:t,svg:n}=e,s=D.useRef(null),i=D.useRef(null),a=D.useRef(null);return D.useEffect(()=>{if(i.current)return a.current=Yb(i.current,{bounds:!0,boundsPadding:.1,zoomSpeed:.065}),()=>{a.current&&a.current.dispose()}},[]),F.jsx("div",{ref:s,className:`svg-panzoom-container ${t}`,children:F.jsx("div",{ref:i,className:"svg-container",children:F.jsx("img",{src:`data:image/svg+xml;utf8,${encodeURIComponent(n)}`,className:"svg-content",alt:"SVG content"})})})},Xb=[{value:"pc",icon:"icon-line-computer1"},{value:"mobile",icon:"icon-line-phone-011"}],Zb=({activeTab:e,onTabChange:t})=>F.jsx("div",{className:"web-viewer-switch-tab",children:F.jsx(ji,{value:e,options:Xb.map(e=>({label:F.jsx(pi,{type:e.icon,className:"web-viewer-switch-tab-icon"}),value:e.value})),onChange:e=>{t(e)},size:"small"})}),ex=e=>{var t,n;const{currentContent:s,theme:i="light",failedText:a="Preview failed",emptyText:o="No HTML, CSS, or JavaScript content found.",previewIframeOrigin:r="https://qwenlm.io/",showSwitchTab:l=!1,showToolbar:c=!1,onIframeFull:d,onPreviewStatusChange:u,loadingText:h}=e,[m,p]=D.useState(null==(t=e.isIframeLoading)||t),[g,f]=D.useState("pc"),{mobile:v}=Hf(),y=D.useRef(null),b=D.useRef(s);D.useEffect(()=>{b.current=s},[s]);const x=D.useCallback(e=>{y.current&&y.current.contentWindow&&y.current.contentWindow.postMessage(e,r)},[r]),w=D.useCallback(({type:e="html",code:t="",isRetry:n=!1})=>{setTimeout(()=>{x({type:e,code:t,theme:i,i18nText:a,mobile:v,isRetry:n})},50)},[x,i,a,v]),_=D.useCallback(e=>{var t,n,s,i,a;switch(e.data.type){case"codeOnload":null==u||u(!1),p(!1);break;case"codeError":null==u||u(!0),p(!1);break;case"codeRetry":null==u||u(!1),p(!0),w({type:null==(t=b.current)?void 0:t.iframeType,code:null==(n=b.current)?void 0:n.content,isRetry:!0});break;case"codeIframeReady":(null==(s=b.current)?void 0:s.content)&&w({type:null==(i=b.current)?void 0:i.iframeType,code:null==(a=b.current)?void 0:a.content})}},[u,w]);return D.useEffect(()=>{d&&d({requestFullscreen:()=>{var e,t,n,s,i,a;(null==(e=y.current)?void 0:e.requestFullscreen)?null==(t=y.current)||t.requestFullscreen():(null==(n=y.current)?void 0:n.webkitRequestFullscreen)?null==(s=y.current)||s.webkitRequestFullscreen():(null==(i=y.current)?void 0:i.msRequestFullscreen)&&(null==(a=y.current)||a.msRequestFullscreen())}})},[d]),D.useEffect(()=>{var t;p(null==(t=e.isIframeLoading)||t)},[e.isIframeLoading]),D.useEffect(()=>(window.addEventListener("message",_),()=>{window.removeEventListener("message",_)}),[_]),D.useEffect(()=>{var e;"iframe"===s.type&&s.content&&(null==(e=y.current)?void 0:e.contentWindow)&&w({type:s.iframeType,code:s.content})},[s,w]),F.jsxs("div",{className:"artifact-container",children:["iframe"===s.type&&F.jsxs(F.Fragment,{children:[m&&F.jsx(rv,{loadingText:h}),F.jsx(kb,{ref:y,activeTab:g,previewUrl:r,refreshKey:0,sandbox:"allow-scripts allow-same-origin",loadingRender:null,errorRender:null,showToolbar:c,iframeClassName:"artifact-iframe-render "+(m?"artifact-iframe-loading":""),iframeKey:`${s.id}-${(null==(n=s.content)?void 0:n.length)||0}`,onIframeLoad:()=>{var e,t;w({type:null==(e=b.current)?void 0:e.iframeType,code:null==(t=b.current)?void 0:t.content})}}),l&&!m&&!v&&F.jsx(Zb,{activeTab:g,onTabChange:f})]}),"svg"===s.type&&F.jsx(Jb,{className:"artifact-svg-render",svg:s.content}),("error"===s.type||!s.type)&&F.jsx(av,{isMobile:v,failedText:a,emptyText:o})]})},tx=({deepResearchList:e,onStepsChange:t,onAllChange:n,onDetailClick:s,timestamp:i,endTime:a,loading:o,searchTitle:r,cardStatus:l,stepCurrent:c,showAll:d,texts:u,className:h})=>{const[m,p]=D.useState(0);D.useEffect(()=>{c!==m&&void 0!==c&&p(c)},[m,c]);const g=D.useCallback((e,n,s)=>{m!==e&&p(e),null==t||t(e,n,s)},[m,t]);return F.jsxs("div",{className:Q("deep-research-list-container",h),children:[F.jsxs("div",{className:Q("deep-research-list-top",{"deep-research-list-top-click":[null==e?void 0:e.length]}),onClick:t=>{t.stopPropagation(),(null==e?void 0:e.length)&&(null==n||n(!d))},children:[F.jsx("div",{className:"deep-research-list-top-left",children:F.jsx(_v,{endTime:a,timestamp:i,loading:o,searchTitle:r,showTime:!0})}),F.jsxs("div",{className:"deep-research-list-top-right",children:[F.jsxs("div",{className:"deep-research-list-top-right-detail",onClick:e=>{e.stopPropagation(),null==s||s()},children:[F.jsx("span",{children:(null==u?void 0:u.detail)||"Detail"}),F.jsx(pi,{type:"icon-line-arrow-right",style:{marginLeft:4,fontSize:16}})]}),!!(null==e?void 0:e.length)&&F.jsx("div",{className:Q("deep-research-list-top-right-arrow",{"deep-research-list-top-right-arrow-show":d}),onClick:e=>{e.stopPropagation(),null==n||n(!d)},children:F.jsx(pi,{type:"icon-line-chevron-down",style:{fontSize:24}})})]})]}),d&&F.jsx(lb,{stepList:e,onStepClickChange:g,cardStatus:l,stepCurrent:m,type:Vf.list})]})},nx=D.memo(e=>{const t=e,{src:n}=t,s=k(t,["src"]),[i,a]=D.useState(!!n);return D.useEffect(()=>{a(!!n)},[n]),F.jsx("div",S(C({className:"sources-icon-item"},s),{children:i?F.jsx("img",{src:n,alt:"",className:"sources-icon-content-img",onError:()=>{a(!1)}}):F.jsx(pi,{type:"icon-line-paperclip-01"})}))}),sx=({sources:e=[],showNum:t=3})=>F.jsx("div",{className:"sources-icon-content",children:e.slice(0,t).map((e,t)=>{const n=t+"-"+JSON.stringify("string"==typeof e?e:null==e?void 0:e.hostlogo)+"-sources-icon",s="string"==typeof e?e:null==e?void 0:e.hostlogo;return F.jsx(nx,{src:s},n)})}),ix=e=>{var t=e,{sources:n=[],className:s="",onCilck:i=()=>{}}=t,a=k(t,["sources","className","onCilck"]);return F.jsxs("div",S(C({className:`sources-container ${s}`},a),{onClick:i,children:[F.jsx(sx,{sources:n}),F.jsxs("div",{className:"sources-des",children:[n.length," Sources"]})]}))},ax=({deepResearchList:e,onStepsChange:t,onAllChange:n,sourceList:s=[],onSourcesCilck:i,onLinkCard:a,timestamp:o,disableAlls:r=!0,endTime:l,loading:c,searchTitle:d,cardStatus:u,stepCurrent:h,contentId:m="pc-research-panel-content",showAll:p,researchRenderOption:g,className:f})=>{const[v,y]=D.useState(!0),b=D.useRef(null),x=D.useRef(null),[w,_]=D.useState(0);D.useEffect(()=>{h!==w&&void 0!==h&&_(h)},[w,h]);const C=D.useCallback((e,t,n=0)=>{if(!e||!t)return;const s=t.getBoundingClientRect(),i=e.getBoundingClientRect(),a=s.top-i.top+e.scrollTop-n;null==e||e.scrollTo({top:a,behavior:"smooth"})},[]),S=D.useCallback((e,n,s)=>{var i;w!==e&&_(e),t&&t(e,n,s),"answer"!==n.id||"scrollTo"===s?C(document.getElementById(m),document.getElementById(`${n.id}`),0):null==(i=document.getElementById(`${n.id}`))||i.scrollIntoView({behavior:"smooth",block:"start"})},[m,w,C,t]);D.useEffect(()=>{void 0!==p&&v!==p&&y(p)},[p,v]);const k=D.useCallback((e,t,n=0)=>{const s=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=s.top-i.top-i.height+n;t.scrollTo({top:a})},[]),j=D.useCallback(()=>{y(e=>!e),n&&n(!v),v&&setTimeout(()=>{const t=document.querySelector(".steps-time-des-current"),n=document.getElementById("deep-research-times");t&&n&&(k(t,n,55),S&&e&&void 0!==w&&S(w,e[w],"scrollTo"))},0)},[v,e,w,S,n,k]),T=D.useRef(0),E=D.useCallback(e=>{if(e&&e.length!==T.current){const t=x.current,n=b.current;t&&n&&setTimeout(()=>{k(t,n,55);const s=e.length-1;S&&S(s,e[s],"scrollTo")},0)}},[S,k]);D.useEffect(()=>{E(e),T.current=e.length},[e,E]);const N=D.useMemo(()=>!r||!c,[r,c]),I=D.useRef(null),[A,M]=D.useState(Kf.large);D.useEffect(()=>{const e=I.current;if(!e)return;const t=new ResizeObserver(e=>{for(let t of e)t.contentRect.width<=260?M(Kf.small):t.contentRect.width>260&&t.contentRect.width<350?M(Kf.medium):M(Kf.large)});return t.observe(e),()=>{t.unobserve(e),t.disconnect()}},[]);const R=D.useMemo(()=>!(c||!l||!o),[c,l,o]);return F.jsxs("div",{ref:I,className:Q("deep-research-container",{"deep-research-container-medium":A===Kf.medium,"deep-research-container-small":A===Kf.small},f),style:v?{minHeight:"442px"}:{},children:[F.jsxs("div",{className:"deep-research-top",children:[F.jsx(_v,{endTime:l,timestamp:o,loading:c,searchTitle:d,showTime:R}),F.jsxs("div",{className:"deep-research-top-right",children:[void 0!==o&&c&&!N&&F.jsx("div",{className:"deep-research-top-time",children:F.jsx(wv,{timestamp:o,endTime:l,loading:c})}),s.length>0&&!c&&F.jsx(ix,{sources:s,onCilck:i}),N&&F.jsx("div",{className:"deep-research-_alls",style:v?{transform:"rotate(180deg)"}:{},onClick:j,children:F.jsx("span",{className:"deep-research-alls-icon",children:F.jsx(pi,{type:"icon-line-chevron-down",style:{fontSize:"24px"}})})})]})]}),v&&F.jsxs("div",{className:"deep-research-content",children:[F.jsxs("div",{className:"deep-research-times",id:"deep-research-times",ref:b,children:[F.jsx(lb,{stepList:e,onStepClickChange:S,cardStatus:u,stepCurrent:w,type:Vf.text}),F.jsx("div",{id:"deep-research-times-tag",ref:x})]}),F.jsx("div",{className:"deep-research-time-content",id:m,children:F.jsx("div",{style:{maxWidth:"max-content"},className:"markdown-prose-dp markdown-small-prose",children:e.map((e,t)=>{const n=`research-list-${t}`;if("string"==typeof e.content){const t="Summary"!==e.title;return F.jsxs(O.Fragment,{children:[t?F.jsx("h1",{id:e.id,children:e.title}):F.jsx("div",{id:e.id,style:{height:"1px"}}),F.jsx(Ry,{content:e.content,id:e.id,linkCardTitle:e.linkCardTitle,onLinkCard:a,errorMessage:(null==g?void 0:g.errorMessage)||"error"})]},n)}return Array.isArray(e.content)?F.jsxs(O.Fragment,{children:[F.jsx("h1",{id:e.id,children:e.title}),F.jsx(Ry,{content:e.content,id:e.id,linkCardTitle:e.linkCardTitle,errorMessage:(null==g?void 0:g.errorMessage)||"error",onLinkCard:a})]},n):null})})})]})]})},ox=({sourceList:e=[],deepResearchList:t=[],mobileTabs:n,drawer:s,displayDrawer:i,onSourcesCilck:a,onLinkCard:o,openChange:r,onCardClick:l,timestamp:c,endTime:d,loading:u,searchTitle:h,webSourceOption:m,className:p})=>{const g=D.useMemo(()=>Array.isArray(e)&&e.length>0||void 0!==c,[e,c]),[f,v]=D.useState(!1),y=()=>{r&&r(!1),v(!1)};return F.jsxs(F.Fragment,{children:[F.jsxs("div",{className:Q("deep-research-h5-container",p),id:"deep-research-h5-container",onClick:e=>{l&&l(e),i||(r&&r(!0),v(!0))},children:[F.jsxs("div",{className:"deep-research-top",children:[F.jsx(_v,{timestamp:c,endTime:d,loading:u,searchTitle:h}),F.jsx("div",{className:"deep-research-alls",children:F.jsx("span",{className:"deep-research-alls-icon",children:F.jsx(pi,{type:"icon-line-chevron-down"})})})]}),F.jsxs("div",{className:"deep-research-sources-content bottom-line "+(g?"":"deep-research-sources-content-hidden"),children:[Array.isArray(e)&&e.length>0&&F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"deep-research-sources-h5",children:e.length>0&&F.jsx(ix,{sources:e,onCilck:e=>{e.stopPropagation(),a&&a()}})}),F.jsx("div",{className:"dot"})]}),void 0!==c&&F.jsx("div",{className:"deep-research-top-time"+(u?" deep-research-top-time-loading":""),children:F.jsx(wv,{timestamp:c,endTime:d,loading:u})})]})]}),!i&&F.jsx(ee,C({placement:"bottom",closable:!1,onClose:y,size:"large",height:window.innerHeight-50,open:f,drawerRender:()=>F.jsx(cb,{cardStatus:qy.Finish,tabs:n,sourceList:e,stepList:t,onClose:y,onLinkCard:o,webSourceOption:m})},s),"bottom")]})},rx=D.memo(e=>{const{className:t,loading:n,sourceList:s,timestamp:i,endTime:a,searchTitle:o,disableAlls:r,showAll:l,deepResearchList:c,onAllChange:d,onCardClick:u,cardStatus:h,stepCurrent:m,contentId:p,onDetailClick:g,onSourcesCilck:f,onStepsChange:v,onLinkCard:y,drawerOpenChange:b,mobileDrawer:x,mobileTabs:w,webSourceOption:_,researchRenderOption:C,displayDrawer:S,cardType:k="markdown",texts:j}=e,{mobile:T}=Hf(),E=D.useMemo(()=>"list"===k?F.jsx(tx,{className:t,deepResearchList:c,onStepsChange:v,timestamp:i,onAllChange:d,onDetailClick:g,showAll:l,endTime:a,loading:n,searchTitle:o,cardStatus:h,stepCurrent:m,texts:j}):"markdown"===k?F.jsx(ax,{className:t,deepResearchList:c,onStepsChange:v,sourceList:Yf(s),timestamp:i,onSourcesCilck:f,onLinkCard:y,onAllChange:d,showAll:l,disableAlls:r,endTime:a,loading:n,searchTitle:o,cardStatus:h,stepCurrent:m,contentId:p,researchRenderOption:C}):null,[k,c,v,s,i,f,y,d,g,l,r,a,n,o,h,m,p,C,j]),N=D.useMemo(()=>F.jsx(ox,{className:t,sourceList:Yf(s),deepResearchList:c,onSourcesCilck:f,openChange:b,onLinkCard:y,onCardClick:u,drawer:x,displayDrawer:S,timestamp:i,endTime:a,searchTitle:o,loading:n,mobileTabs:w,webSourceOption:_}),[s,c,f,b,y,u,x,S,i,a,o,n,w,_]);return T?N:E}),lx=({videoSrc:e,poster:t="",errorMessage:n="",onLoad:s=()=>{},onMetadataLoaded:i=()=>{},style:a={}})=>{const o=D.useRef(null),[r,l]=D.useState(!1),[c,d]=D.useState(!0);return D.useEffect(()=>{var t;const n=o.current;if(!n)return;const s=()=>{l(!0),null==i||i(o.current)},a=()=>{var e;n.currentTime=0,null==(e=n.play())||e.catch(()=>d(!1))},r=()=>{l(!1)};return n.src=e,n.load(),n.addEventListener("loadedmetadata",s),n.addEventListener("loadeddata",s),n.addEventListener("load",s),n.addEventListener("canplay",s),n.addEventListener("loadstart",r),n.addEventListener("ended",a),null==(t=n.play())||t.catch(()=>d(!1)),()=>{n.removeEventListener("loadedmetadata",s),n.removeEventListener("loadeddata",s),n.removeEventListener("load",s),n.removeEventListener("canplay",s),n.removeEventListener("loadstart",r),n.removeEventListener("ended",a),n.pause(),n.currentTime=0,n.src="",n.load()}},[e]),D.useEffect(()=>{s(o.current)},[o.current]),F.jsx("div",{className:"video-bg-card-container",style:a,children:F.jsxs("video",{ref:o,className:"video-bg-card",autoPlay:!0,loop:!0,muted:!0,playsInline:!0,controls:!1,poster:t,preload:"metadata",crossOrigin:"anonymous",children:[F.jsx("source",{src:`${e}`,type:"video/mp4"}),n]})})},cx=({url:e,poster:t,onLoadEnd:n})=>{const s=D.useCallback(e=>{if(t)return void e.setAttribute("poster",t);const n=document.createElement("canvas");n.width=e.videoWidth,n.height=e.videoHeight;const s=n.getContext("2d"),i=n.width,a=n.height;s&&i>0&&a>0&&i<=32767&&a<=32767&&(s.drawImage(e,0,0,i,a),e.setAttribute("poster",n.toDataURL("image/png")))},[t]);return F.jsx(lx,{videoSrc:e,poster:t,errorMessage:"",onMetadataLoaded:e=>{((e,t,n,s={})=>{const{maxQueryCount:i=12,queryInterval:a=60}=s;let o=0,r=performance.now(),l=null;const c=s=>{if(!(s-r0?(t(e),void(null!==l&&cancelAnimationFrame(l))):void(o{null==e||e.pause(),n({duration:(null==e?void 0:e.duration)||0,width:(null==e?void 0:e.videoWidth)||0,height:(null==e?void 0:e.videoHeight)||0})},e=>{null==e||e.pause(),n({duration:(null==e?void 0:e.duration)||0,width:(null==e?void 0:e.videoWidth)||0,height:(null==e?void 0:e.videoHeight)||0})},{maxQueryCount:12,queryInterval:60})},onLoad:e=>{s(e)},style:{background:"transparent"}})},dx=e=>{const t=e,{generation:n,onImageSizeChange:s,id:i,imageWrapperRef:a}=t,o=k(t,["generation","onImageSizeChange","id","imageWrapperRef"]),[r,l]=D.useState(0),[c,d]=D.useState(0),u=D.useCallback(e=>{l(e.width),d(e.height),null==s||s(e)},[s]);return F.jsxs("div",{id:i,className:"qwen-image",children:[n&&!o.error&&F.jsx("div",{className:"qwen-image-generating",style:r&&c?{width:`${r}px`,height:`${c}px`}:{},children:F.jsx(ay,S(C({},n),{percent:void 0}))}),F.jsx("div",{className:"qwen-image-content",style:"number"!=typeof(null==n?void 0:n.percent)||o.error?{}:{maxHeight:.01*n.percent+"%"},children:F.jsx(ry,C({ref:a,loading:!n,onSizeChange:u},o))})]})},ux=e=>{const{failedMcpNames:t,failedText:n="connecting failed."}=e;return F.jsxs("div",{className:"qwen-mcp-connect-failed-panel",children:[F.jsx("div",{className:"qwen-mcp-connect-failed-panel-icon",children:F.jsx(pi,{type:"icon-line-x-circle-contained"})}),F.jsxs("div",{className:"qwen-mcp-connect-failed-panel-text",children:[t.map(e=>F.jsx("div",{className:"qwen-mcp-connect-failed-panel-text-tag",children:e},e)),F.jsx("div",{children:n})]})]})},hx=e=>{const t=e,{type:n,onButtonClick:s,title:i="Allow toolName (local) running?",content:a="Malicious MCP servers or content may lead Qwen to perform harmful actions through your installed tools. Review all actions carefully before approval.",buttonTextDeny:o="Deny",buttonTextGrantedOnce:r="Allow once",buttonTextGranted:l="Allow in this chat",deniedContent:c="Permission request denied, tool execution stopped.",className:d}=t,u=k(t,["type","onButtonClick","title","content","buttonTextDeny","buttonTextGrantedOnce","buttonTextGranted","deniedContent","className"]);return F.jsxs("div",S(C({className:Q("qwen-mcp-permission-panel",d)},u),{children:["prompt"===n&&F.jsxs("div",{className:"qwen-mcp-permission-panel-prompt",children:[F.jsx("div",{className:"qwen-mcp-permission-panel-prompt-title",children:i}),F.jsx("div",{className:"qwen-mcp-permission-panel-prompt-content",children:a}),F.jsxs("div",{className:"qwen-mcp-permission-panel-prompt-buttons",children:[F.jsx(xi,{type:"ghost",shape:"circle",onClick:()=>null==s?void 0:s("denied"),children:o}),F.jsxs("div",{className:"qwen-mcp-permission-panel-prompt-buttons-right-group",children:[F.jsx(xi,{type:"ghost",shape:"circle",onClick:()=>null==s?void 0:s("grantedOnce"),children:r}),F.jsx(xi,{type:"brandprimary",shape:"circle",onClick:()=>null==s?void 0:s("granted"),children:l})]})]})]}),"denied"===n&&F.jsxs("div",{className:"qwen-mcp-permission-panel-denied",children:[F.jsx(pi,{type:"icon-line-alert-circle",style:{width:"font-size: 1.25rem; margin-right: 0.5rem;"}}),F.jsx("div",{className:"qwen-mcp-permission-panel-denied-content",children:c})]})]}))},mx=e=>{const{loading:t,mcpName:n="mcpName",toolName:s="toolName",callingText:i="Call toolName from mcpName",detailParamsTitle:a="Start calling tool toolName",detailParamsContent:o="detailParamsContent",detailResultTitle:r="Finished tool calling",detailResultContent:l="detailResultContent"}=e,[c,d]=D.useState(!1),[u,h]=D.useState([]),m=D.useCallback((e,t)=>{if(!t)return[e];const i=t===n?s:n,a=e.indexOf(t);return a>-1?[...m(e.slice(0,a),i),t,...m(e.slice(a+t.length),i)]:[e]},[n,s]);return D.useEffect(()=>{const e=n.includes(s)?n:s;h(m(i,e))},[i,m,n,s]),F.jsxs("div",{className:"qwen-mcp-tool-call-panel",children:[F.jsxs("div",{className:"qwen-mcp-tool-call-panel-info",children:[F.jsx("div",{className:"qwen-mcp-tool-call-panel-info-icon",children:t?F.jsx("img",{src:"https://img.alicdn.com/imgextra/i4/O1CN01I24l4b1UL3Daed4DL_!!6000000002500-54-tps-80-80.apng",alt:""}):F.jsx(pi,{type:"icon-line-star-01"})}),F.jsxs("span",{className:"qwen-mcp-tool-call-panel-info-content",children:[u.map(e=>e===n||e===s?F.jsx("span",{className:"qwen-mcp-tool-call-name",children:e},e):e?F.jsx("span",{children:e},e):null),t&&F.jsx("span",{className:"qwen-dot"}),!!o&&F.jsx("div",{className:Q("qwen-mcp-tool-call-detail-switch",{active:c}),onClick:()=>{d(e=>!e)},children:F.jsx(pi,{type:"icon-line-chevron-down"})})]})]}),!!o&&F.jsxs("div",{className:"qwen-mcp-tool-call-panel-detail",style:{display:c?"flex":"none"},children:[F.jsx("div",{className:"qwen-mcp-tool-call-panel-detail-prefix"}),F.jsxs("div",{className:"qwen-mcp-tool-call-panel-detail-content",children:[F.jsx("div",{className:"qwen-mcp-tool-call-panel-detail-content-title",children:a}),F.jsx("div",{className:"qwen-mcp-tool-call-panel-detail-content-description",children:o}),!!r&&F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"qwen-mcp-tool-call-panel-detail-content-title",children:r}),F.jsx("div",{className:"qwen-mcp-tool-call-panel-detail-content-description",children:l})]})]})]})]})},px=({onClick:e})=>F.jsx("div",{className:"qwen-video-play-button",onClick:e,children:F.jsx(pi,{type:"icon-fill-play-03"})});const gx=e=>{const t=Math.round(Math.floor(e)),n=Math.floor(t/3600),s=t%3600,i=Math.floor(s/60),a=s%60,o=e=>e.toString().padStart(2,"0");return`${n?`${o(n)}:`:""}${o(i)}:${o(a)}`};const fx=()=>{const e=navigator.userAgent,t=/(iPad|Macintosh.*AppleWebKit(?!.*Chrome))/.test(e)&&!/iPhone|iPod/.test(e)&&function(){const{userAgent:e}=navigator;return!!(e.match(/iPad Simulator|iPhone Simulator|iPod Simulator|iPad|iPhone|iPod/)||e.includes("Mac")&&"ontouchend"in document)}(),n=/Android/.test(e)&&!/Mobile/.test(e),s=/Windows/.test(e)&&/Touch/.test(e);return t?"iPad":n||s?"tablet":/iPhone|Android/.test(e)?"mobile":"pc"},vx=()=>{const e=fx();return["iPad","mobile","tablet"].includes(e)};const yx=e=>vx()?e/16+"rem":`${e}px`,bx=e=>{const{url:t,autoPlay:n=!1,controls:s=!0,mute:i=!1,loop:a=!1,type:o="video/mp4",poster:r,videoPlayerRef:l,unSupportMessage:c,style:d,showVolumnAndFullScreen:u=!1,preload:h="metadata",onLoad:m,onError:p,onStateChange:g,onUserClick:f}=e,[v,y]=D.useState(0),[b,x]=D.useState(!1),[w,_]=D.useState(1),[C,S]=D.useState(!1),[k,j]=D.useState(0),[T,E]=D.useState(!1),N=D.useRef(null),I=D.useRef(1),M=D.useRef(void 0),R=D.useRef(!1),P=D.useCallback(e=>{x(e),null==f||f(e?"playing":"paused")},[]),L=D.useCallback(e=>A(null,null,function*(){if(!N.current)return;const t=N.current;if((!t.duration||0===t.duration)&&(0===t.readyState&&t.load(),yield new Promise(e=>{const n=()=>{t.duration&&t.duration>0?(y(t.duration),null==m||m({duration:t.duration}),e()):setTimeout(()=>{t.duration&&t.duration>0&&(y(t.duration),null==m||m({duration:t.duration})),e()},500)};t.readyState>=1?n():t.addEventListener("loadedmetadata",n,{once:!0})})),t.paused){t.readyState<3&&(yield new Promise(e=>{let n=!1;const s=()=>{n||(n=!0,e())};t.addEventListener("canplaythrough",s,{once:!0}),t.addEventListener("canplay",s,{once:!0}),setTimeout(()=>{n||(n=!0,e())},2e3)}));const e=t.play();void 0!==e&&e.catch(e=>{}),P(!0)}else t.pause(),P(!1);"number"==typeof e&&(t.currentTime=e)}),[m]),O=D.useCallback(e=>{v&&(E(!0),j(e/100*v))},[v]),q=D.useCallback(e=>{if(!N.current||!isFinite(v)||v<=0)return;E(!1);const t=e/100*v;j(t),N.current.currentTime=t},[v]),U=D.useCallback(()=>{if(!N.current)return;I.current=1;const e=N.current.duration;!isFinite(e)||e<=0||R.current&&v===e||(y(e),R.current=!0,null==m||m({duration:e}))},[m]),H=D.useCallback(()=>{var e;if(!N.current)return;null==(e=N.current)||e.error;null==p||p()},[p]),B=D.useCallback(()=>{N.current&&(x(!N.current.paused),T||j(N.current.currentTime))},[T]),z=D.useCallback(()=>{x(!0)},[]),G=D.useCallback(()=>{x(!1)},[]),$=D.useCallback(()=>{!document.fullscreenElement&&N.current?N.current.requestFullscreen&&N.current.requestFullscreen():document.exitFullscreen&&document.exitFullscreen()},[]),W=D.useCallback(()=>{N.current&&(N.current.muted=!N.current.muted,S(N.current.muted))},[]),V=D.useCallback(e=>{N.current&&(N.current.volume=e,N.current.muted=0===e,_(e),S(0===e))},[]);D.useEffect(()=>{if(!N.current)return;const e=N.current;e.addEventListener("loadedmetadata",U),e.addEventListener("loadeddata",U),e.addEventListener("durationchange",U);const t=()=>{e.duration&&e.duration>0&&!R.current&&U()};return e.addEventListener("canplay",t),e.addEventListener("error",H),e.addEventListener("timeupdate",B),e.addEventListener("play",z),e.addEventListener("pause",G),()=>{e&&(e.removeEventListener("loadedmetadata",U),e.removeEventListener("loadeddata",U),e.removeEventListener("durationchange",U),e.removeEventListener("canplay",t),e.removeEventListener("error",H),e.removeEventListener("timeupdate",B),e.removeEventListener("play",z),e.removeEventListener("pause",G))}},[H,U,B]),D.useEffect(()=>{null==g||g(b?"playing":"paused")},[b]),D.useEffect(()=>{l&&(l.current={toggleVideoPlaying:L})},[l,L]),D.useEffect(()=>{if(N.current&&!v)return M.current=window.setInterval(()=>{var e;(null==(e=N.current)?void 0:e.duration)&&(y(N.current.duration),void 0!==M.current&&(window.clearInterval(M.current),M.current=void 0))},100),()=>{void 0!==M.current&&(window.clearInterval(M.current),M.current=void 0)}},[v]),D.useEffect(()=>{y(0),j(0),x(!1),E(!1),R.current=!1},[t]),D.useEffect(()=>()=>{const e=N.current;e&&(e.pause(),e.currentTime=0,e.src="",e.load())},[]);const K=`${gx(k||0)} / ${gx(v||0)}`,Y=v>0?Math.min(Math.max(k/v*100,0),100):0;return F.jsxs("div",{className:"qwen-video-player",style:d,children:[F.jsx("div",{className:Q("qwen-video-player-content"),children:F.jsxs("video",{ref:N,loop:a,autoPlay:n,muted:i,crossOrigin:"anonymous",poster:r,playsInline:!0,preload:h,"webkit-playsinline":"true","x5-playsinline":"true",children:[F.jsx("source",{src:t,type:o}),c]})}),s&&!b?F.jsx(ie,{justify:"center",align:"center",className:"qwen-video-player-pause-container",onClick:()=>L(),children:F.jsx(pi,{type:"icon-pause"})}):null,s&&F.jsxs("div",{className:"qwen-video-player-control",onClick:e=>{e.stopPropagation()},children:[F.jsxs("div",{className:Q("qwen-video-player-control-slider",{moving:T}),children:[F.jsx("div",{className:"qwen-video-player-control-slider-time",style:T?void 0:{opacity:0,pointerEvents:"none"},children:K}),F.jsx(qi,{value:Y,min:0,max:100,tooltip:{open:!1},onChange:O,onChangeComplete:q,className:Q("video-slider-container",{"video-slider-loading":v<=0})})]}),F.jsxs("div",{className:"qwen-video-player-control-operations",children:[F.jsxs("div",{className:"qwen-video-player-control-operations-left",children:[F.jsx("div",{className:"qwen-video-player-control-operations-icon",onClick:()=>L(),children:F.jsx(pi,{type:b?"icon-play":"icon-pause"})}),F.jsx("div",{className:"qwen-video-player-control-operations-time",children:K})]}),u&&F.jsxs("div",{className:"qwen-video-player-control-operations-right",children:[F.jsx(le,{content:F.jsx("div",{className:"volume-slider-popup",children:F.jsx(qi,{vertical:!0,min:0,max:100,step:1,value:C?0:Math.round(100*w),onChange:e=>V(e/100),tooltip:{open:!1},className:"volume-slider"})}),trigger:"hover",placement:"top",arrow:!1,rootClassName:"qwen-video-player-control-operations-right-volume-popover",children:F.jsx("div",{className:"control-btn mute-btn",onClick:W,children:F.jsx(pi,{type:C?"icon-line-Silent":"icon-line-Volume"})})}),F.jsx("div",{className:"control-btn fullscreen-btn",onClick:$,children:F.jsx(pi,{type:"icon-a-line-Fullscreen1"})})]})]})]})]})},xx=vx(),wx=function(){const e=navigator.userAgent.includes("Quark"),t=navigator.userAgent.includes("UCBrowser"),n=navigator.userAgent.includes("MiuiBrowser"),s=e||t||n;return vx()?{mute:s,autoPlay:!0}:{mute:!1}}(),_x=D.forwardRef((e,t)=>{const{videoPlayerRef:n,url:s,open:i,visible:a=!0,hideCloseButton:o,headerNode:r,showVolumnAndFullScreen:l,toolbarRender:c,setOpen:d,onVisibleChange:u,onStateChange:h,getSize:m}=e,[p,g]=D.useState(null),[f,v]=D.useState(!1),y=D.useCallback(()=>{d(!1),null==u||u(!1,{url:s})},[u,d,s]);D.useImperativeHandle(t,()=>({closePreview:y}),[y]);const b=D.useCallback(e=>{var t;e.stopPropagation(),xx&&(null==(t=null==n?void 0:n.current)||t.toggleVideoPlaying())},[xx,n]),x=D.useCallback(e=>{v("playing"===e)},[]),w=D.useMemo(()=>{const{width:e,height:t,maxWidth:d,maxHeight:u}=p||{},m=!i||!a;return F.jsxs("div",{className:"qwen-video-viewer "+(m?"qwen-video-viewer-hidden":""),onClick:xx?void 0:y,children:[r,F.jsxs("div",{className:"qwen-video-viewer-content",style:p&&!xx?{width:`${e}px`,height:`${t}px`,maxWidth:`${d}px`,maxHeight:`${u}px`}:void 0,onClick:b,children:[F.jsx(bx,S(C({videoPlayerRef:n,url:s},wx),{onStateChange:x,onUserClick:h,preload:"auto",mute:!!m||wx.mute,showVolumnAndFullScreen:l})),!o&&F.jsx("div",{className:"qwen-video-viewer-content-close",onClick:y,children:F.jsx(pi,{type:"icon-line-x-01"})}),!!c&&F.jsx("div",{className:"qwen-video-viewer-content-operations",children:c(F.jsx(F.Fragment,{}),{video:{url:s}})}),xx&&!f&&F.jsx(px,{onClick:b})]})]})},[p,xx,y,b,n,s,c,f,i,a]);return D.useEffect(()=>{const e=new ResizeObserver(()=>{const{width:e,height:t,maxWidth:n,maxHeight:s}=m?m():(()=>{const{width:e,height:t}=document.body.getBoundingClientRect();return{width:1024*e/1440,height:576*e/1440,maxWidth:1024/576*(t-120),maxHeight:t-120}})();g({width:e,height:t,maxWidth:n,maxHeight:s})});return e.observe(document.body),()=>{e.disconnect()}},[m]),D.useEffect(()=>{document.body&&a&&(document.body.style.overflow=i?"hidden":"auto")},[i,a]),$.createPortal(w,document.body)}),Cx=D.memo(D.forwardRef((e,t)=>{const{url:n,defaultWidth:s=0,defaultHeight:i=0,width:a=0,height:o=0,preview:r,generation:l,hoverPlay:c,error:d=!1,sizeScope:u,style:h,poster:m,videoPreviewRef:p,onLoad:g,onError:f,onClick:v}=e,[y,b]=D.useState(!1),[x,w]=D.useState(""),[_,k]=D.useState(0),[j,T]=D.useState(a),[E,N]=D.useState(o),[I,M]=D.useState(!1),[R,P]=D.useState(0),L=D.useRef(!1),O=D.useRef(null),q=D.useRef(1),U=D.useRef(null),H=D.useRef(null),B=D.useRef(null),z=D.useRef(null),G=D.useCallback((e,t)=>{var n;if(!u||!U.current||!O.current)return;const s=U.current.querySelector("video");if(!s)return;const{width:i=0}=(null==(n=O.current.parentElement)?void 0:n.getBoundingClientRect())||{},{width:a,height:o}=(e=>Array.isArray(e)?{width:[...e],height:[...e]}:{width:[...e.width],height:[...e.height]})(u),r=[...a],l=[...o];i&&(r[1]=Math.min(r[1],i),r[0]=Math.min(r[0],r[1]));const c=e||s.videoWidth,d=t||s.videoHeight;if(!c||!d)return;const h=c/d,m=(e,[t,n])=>Math.min(Math.max(e,t),n),p=e=>{const t=m(e,l),n=m(t*h,r);return{width:n,height:n/h}};let g=(e=>{const t=m(e,r);return{width:t,height:t/h}})(c);g.heightl[1]&&(g=p(l[1])),T(g.width),N(g.height)},[u]),$=D.useCallback(({duration:e})=>{b(!0),w(""),k(e),P(2),L.current||(L.current=!0,null==g||g({duration:e}))},[G,o,g,a,m]),W=D.useCallback(()=>{if(!m)if(f){const e=f();w((null==e?void 0:e.errorMessage)||!0)}else w(!0)},[f,m]),V=D.useRef(null),Q=D.useCallback(e=>A(null,null,function*(){try{yield fetch(e,{headers:{Range:"bytes=0-100"}}).then(e=>{if(![206,200].includes(e.status))throw e;q.current=1})}catch(t){if(q.current>0)return q.current--,void(V.current=setTimeout(()=>{Q((t=>{try{const{origin:e,pathname:n,search:s}=new URL(t),i=new URLSearchParams(s);i.set("timestamp",`${Date.now()}`);const a=i.toString();return a?`${e}${n}?${a}`:`${e}${n}`}catch(e){return t}})(e))},500));W()}}),[W]);D.useEffect(()=>{V.current&&(clearTimeout(V.current),V.current=null),b(!1)},[n]),D.useEffect(()=>{w(""),Q(n)},[n,Q]);const K=D.useCallback(e=>A(null,null,function*(){let t=a||s,n=o||i;if(e){const{width:s,height:i}=yield function(e){return new Promise((t,n)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{t({width:s.naturalWidth,height:s.naturalHeight})},s.onerror=()=>{n(new Error("Failed to load image"))},s.src=e})}(e);s&&i&&(t=s,n=i)}return{resolvedWidth:t,resolvedHeight:n}}),[s,i,o,a,m]);return D.useEffect(()=>{u&&A(null,null,function*(){const{resolvedWidth:e,resolvedHeight:t}=yield K(m||"");if(!e||!t)return;const n=JSON.stringify(u),s=z.current;s&&s.width===e&&s.height===t&&s.sizeScopeKey===n||(z.current={width:e,height:t,sizeScopeKey:n},G(e,t))})},[G,i,s,o,u,a,m]),D.useEffect(()=>{d&&W()},[d,W]),D.useImperativeHandle(t,()=>({toggleVideoPlaying:()=>{var e,t;I?null==(e=B.current)||e.toggleVideoPlaying():null==(t=H.current)||t.toggleVideoPlaying()}}),[I]),F.jsxs("div",{ref:O,className:"qwen-video",style:C({width:yx(j),height:yx(E)},h),onClick:()=>null==v?void 0:v({url:n}),children:[F.jsxs("div",{ref:U,className:"qwen-video-content",style:{display:x?"none":"block"},onMouseEnter:()=>{c&&H.current&&H.current.toggleVideoPlaying()},onMouseLeave:()=>{c&&H.current&&H.current.toggleVideoPlaying(0)},children:[!l&&F.jsx(cx,{url:n,poster:m,onLoadEnd:e=>{$({duration:e.duration}),G(e.width,e.height)}}),!l&&R>0&&F.jsxs("div",{className:"qwen-video-control",onClick:()=>{var e;M(!0),null==(e=null==r?void 0:r.onVisibleChange)||e.call(r,!0,{url:n})},children:[m&&F.jsx("img",{className:"video-cover",src:m,alt:""}),F.jsx(px,{}),_?F.jsx("div",{className:"qwen-video-control-time",children:gx(_)}):null]}),0===R&&F.jsx(ay,{mode:"default"})]}),l&&F.jsx("div",{className:"qwen-video-generating",children:F.jsx(ay,S(C({},l),{mode:"generating"}))}),x&&F.jsxs("div",{className:"qwen-video-error",children:[F.jsx(pi,{type:"icon-line-video-x-2",className:"qwen-video-error-icon"}),F.jsx("div",{className:"qwen-video-error-text",children:x})]}),!!r&&!l&&(y||m)&&F.jsx(_x,C({ref:p,videoPlayerRef:B,url:n,open:I,setOpen:M},r))]})})),Sx=({cardClassName:e,libraryItem:t})=>{const n=Ue(),[s,i]=D.useState(!1),a=ud(e=>e.realTheme);return F.jsxs("div",{className:`my-library-content-item ${e} ${s?"item-card-img-error":""}`,style:{pointerEvents:"auto"},onClick:()=>{n(`/c/${t.chat_id}?resId=${t.message_id}`)},children:[s?F.jsx("div",{className:"item-card-loading-img",children:F.jsx("img",{src:(e=>{switch(e){case hf.IMAGE:return"light"===a?"https://img.alicdn.com/imgextra/i3/O1CN015RU99x1OEk8zRnb9U_!!6000000001674-2-tps-204-204.png":"https://img.alicdn.com/imgextra/i2/O1CN01OqVzZO1RdsjLH4Jxf_!!6000000002135-2-tps-204-204.png";case hf.VIDEO:return"light"===a?"https://img.alicdn.com/imgextra/i4/O1CN01P7FFgE1j5DqE78f3u_!!6000000004496-2-tps-204-204.png":"https://img.alicdn.com/imgextra/i4/O1CN01ZxXGnJ1iaXIyAxTgZ_!!6000000004429-2-tps-204-204.png";case hf.WEB_DEV:return"light"===a?"https://img.alicdn.com/imgextra/i2/O1CN01UMu9C91ZlgP0b07IJ_!!6000000003235-2-tps-204-204.png":"https://img.alicdn.com/imgextra/i3/O1CN015b5FKe1OCSAC4orDb_!!6000000001669-2-tps-204-204.png";case hf.PDF:return"light"===a?"https://img.alicdn.com/imgextra/i4/O1CN01wEWVtk26MqEz8b9Vh_!!6000000007648-2-tps-204-204.png":"https://img.alicdn.com/imgextra/i1/O1CN01FMnIBt1egFmnKmWQ7_!!6000000003900-2-tps-204-204.png";case hf.PODCAST:return"light"===a?"https://img.alicdn.com/imgextra/i3/O1CN01NfHF6n1lUWxVICOTA_!!6000000004822-2-tps-204-204.png":"https://img.alicdn.com/imgextra/i3/O1CN01qn84d41KExs8GJGzQ_!!6000000001133-2-tps-204-204.png";default:return"light"===a?"https://img.alicdn.com/imgextra/i3/O1CN015RU99x1OEk8zRnb9U_!!6000000001674-2-tps-204-204.png":"https://img.alicdn.com/imgextra/i2/O1CN01OqVzZO1RdsjLH4Jxf_!!6000000002135-2-tps-204-204.png"}})(t.type),alt:""})}):F.jsx(sv,{src:Of(t.type===hf.VIDEO?Df(t.cover):t.sideBarCover),shrinkSrc:t.sharkCover?Of(t.sharkCover):void 0,cardId:t.id,itemType:t.type,isMyPublished:!1,ratioDefault:!0,visible:!0,onClick:()=>{t.type===hf.IMAGE&&n(`/c/${t.chat_id}?resId=${t.message_id}`)},onError:()=>{i(!0)}}),!s&&t.type!==hf.VIDEO&&t.title&&F.jsx("div",{className:"item-card-text",children:t.title}),t.type===hf.VIDEO&&F.jsx("div",{className:"item-card-tag item-card-tag-video",children:F.jsx(pi,{type:"icon-fill-play-03"})})]},t.id)},kx=()=>{const e=ud(e=>e.showSidebar),t=pR(e=>e.myLibraryExpand),n=pR(e=>e.myLibraryLoading),s=pR(e=>e.setMyLibraryLoading),i=js(e=>e.isChat),a=pR(e=>e.sidebarLibraryList),o=Pd(e=>e.user),{getLibraryList:r}=gf(),l=D.useRef(o);l.current=o,D.useEffect(()=>{setTimeout(()=>{s(!1)},1e3)},[s]);const c=D.useRef(i);return D.useEffect(()=>{const e=c.current;c.current=i,e&&!i&&l.current&&setTimeout(()=>{r()},5e3)},[i,o]),D.useEffect(()=>{l.current&&r()},[o]),F.jsx("div",{className:"my-library-content "+(!t||!e||a.length<1?"my-library-content-hidden":""),children:n?F.jsxs(F.Fragment,{children:[F.jsx(Li,{style:{width:"68px",height:"68px"}}),F.jsx(Li,{style:{width:"68px",height:"68px"}}),F.jsx(Li,{style:{width:"68px",height:"68px"}})]}):a.slice(0,3).map(e=>{let t="";switch(e.type){case hf.PDF:t="item-card-pdf";break;case hf.WEB_DEV:t="item-card-web-dev"}return F.jsx(Sx,{cardClassName:t,libraryItem:e},e)})})},jx=D.memo(()=>{var e,t;const n=ye(),s=dR(e=>e.mobile),i=hd(e=>e.showSidebar),a=ud(e=>e.searchInputFocused),o=ud(e=>e.sideBarSearchText),r=ud(e=>e.setShowSidebar),l=dR(e=>e.config),c=cR(e=>{var t;return null==(t=e.config)?void 0:t.function_entry.mylibrary}),d=!i,u=D.useCallback(()=>A(null,null,function*(){yield bM.openCommunity(),s&&r(!1)}),[s,r]),h=D.useCallback(()=>{const e=`${location.origin.replace("chat","coder")}`;si()?bM.openWindow(e):window.open(e,"_self")},[]),m=e=>{e&&e.style&&(e.style.opacity="1",e.style.cursor="pointer")},p=D.useMemo(()=>{var e,t,i,a;return[{icon:"icon-line-folder-01",text:n.t("My Library"),type:"library",visible:!0,mobileVisible:!0,onClick:()=>{}},{icon:"icon-line-community",text:n.t("Community"),id:"Community",type:"button",visible:!!(null==(e=null==l?void 0:l.function_entry)?void 0:e.community),mobileVisible:!!(null==(t=null==l?void 0:l.function_entry)?void 0:t.community),onClick:u,hideIcon:!0},{icon:"icon-line-code-circle",text:n.t("Coder"),id:"Coder",type:"button",visible:!(si()||s||!(null==(i=null==l?void 0:l.function_entry)?void 0:i.coder)),mobileVisible:!(si()||s||!(null==(a=null==l?void 0:l.function_entry)?void 0:a.coder)),onClick:h,hideIcon:!0}]},[null==(e=null==l?void 0:l.function_entry)?void 0:e.coder,null==(t=null==l?void 0:l.function_entry)?void 0:t.community,n,s,h,u]),g=Boolean(o)||a;return F.jsx("div",{className:Q("sidebar-entry-list",{"sidebar-entry-list-only-icon":d}),children:p.map(e=>{const{icon:t="",text:n="",type:i="",visible:a,mobileVisible:o,isNew:r=!1,onClick:l=()=>{},hideIcon:u=!1}=e;return a||s?!o&&s?F.jsx(O.Fragment,{},t):g&&!r?null:"library"===i?c?F.jsx(O.Fragment,{children:F.jsx(kx,{})},t):null:F.jsxs("div",{onClick:l,className:Q("sidebar-entry-list-content",{"sidebar-entry-list-content-hide-icon":u&&d,"sidebar-entry-list-content-mobile":s}),style:{opacity:.4,cursor:"not-allowed"},ref:m,children:[F.jsx(pi,{type:t,className:"sidebar-entry-list-icon"}),F.jsx("div",{className:Q("sidebar-entry-list-text",{"sidebar-entry-list-text-hidden":d}),children:n})]},t):F.jsx(O.Fragment,{},t)})})});function Tx({children:e=null,fallback:t=null}){const[n,s]=D.useState(!1);return D.useEffect(()=>{s(!0)},[]),n?F.jsx(D.Suspense,{fallback:null,children:e}):"function"==typeof t?t():F.jsx(F.Fragment,{children:t})}const Ex=D.memo(()=>{const{todayActiveChatId:e,setTodayActiveChatId:t,pinnedActiveChatId:n,setPinnedActiveChatId:s,selectedChatId:i,setSelectedChatId:a,chatListLoading:o,searchLoading:r,chatId:l,sidebarFloatingPlaceholder:c,searchInputFocused:d,showSidebar:u,setShowSidebar:h,mobile:m,pinnedChats:p,folders:g,temporaryChatEnabled:f,finshChats:v,prevChatListLength:y,enableProjectEntry:b,showPanelList:x,setShowPanelList:w,activeChatMenuId:_,setActiveChatMenuId:k,enablePaymentEntry:j,subscriptionPlus:T,setShowSubscriptionDetail:E,search:N,getChatStatus:I,initChatList:M,loadMoreChats:R,searchDebounceHandler:P,__initSidebarEffect:L,__handleUserAndConfigEffect:O,PAGE_SIZE:q}=(()=>{const[e,t]=D.useState(""),[n,s]=D.useState(""),[i,a]=D.useState(null),[o,r]=D.useState(!1),l=D.useRef(""),[c,d]=D.useState(!1),{id:u}=Ge(),h=Pd(e=>e.user),m=ud(e=>e.sidebarFloatingPlaceholder),p=ud(e=>e.searchInputFocused),g=ud(e=>e.setSideBarSearchText),f=hd(e=>e.showSidebar),v=ud(e=>e.setShowSidebar),y=dR(e=>e.mobile),b=Ns(e=>e.chats),x=Ns(e=>e.setChats),w=Ns(e=>e.pinnedChats),_=Ns(e=>e.setPinnedChats),k=js(e=>e.setCurrentChatPage),j=Rs(e=>e.temporaryChatEnabled),T=Rs(e=>e.reUpdateFolders),E=Rs(e=>e.setReUpdateFolders),N=Rs(e=>e.folders),I=pw(e=>e.showPanelList),M=pw(e=>e.setShowPanelList),R=ud(e=>e.activeChatMenuId),P=ud(e=>e.setActiveChatMenuId),L=Fd(e=>e.subscriptionPlus),O=Fd(e=>e.setShowSubscriptionDetail),F=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_project}),q=cR(e=>{var t,n,s,i;return(null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_payment)&&(null==(i=null==(s=null==e?void 0:e.config)?void 0:s.features)?void 0:i.enable_payment_and_quota)}),U=zp(e=>e.wsNotifications),H=D.useRef(0),{getNewProjectList:B}=ig(),{getChatListData:z,getChatListBySearchTextData:G,getPinnedChatListData:$,initFolders:W}=Tg(),V=D.useMemo(()=>U.filter(e=>e.event_type===rn),[U]),Q=D.useCallback(e=>{const t=V.find(t=>t.payload.chatId===e);return t?t.payload.status:"normal"},[V]),K=D.useMemo(()=>{var e;return(null==(e=null==b?void 0:b.map)?void 0:e.call(b,e=>S(C({},e),{time_range:fn(e.updated_at)})))||[]},[b]),Y=D.useCallback(()=>A(null,null,function*(){const e=yield $();if(_(e),yield W(),F&&B(),k(1),l.current){const e=yield G(l.current,1);H.current=e.length,x(e)}else{const e=yield z(1);H.current=e.length,x(e)}}),[F,G,z,B,$,W,x,k,_]),J=D.useCallback(()=>A(null,null,function*(){if(H.current<60)return;r(!0);const e=js.getState().currentChatPage+1;k(e);let t=[],n=null;n=l.current?yield G(l.current,e):yield z(e),"ERR_NETWORK"!==(null==n?void 0:n.code)&&(t=n);const s=Ns.getState().chats;x([...s||[],...t]),H.current=t.length,r(!1)}),[G,z,l,x,k]),X=D.useCallback(e=>{const t=new RegExp("tag:$");return e.replace(t,"")},[]),Z=D.useMemo(()=>Le(e=>A(null,null,function*(){if(l.current=e,g(e),""===e)return void(yield Y());const t=X(e);if(!(null==t?void 0:t.length))return;d(!0),k(1);const n=yield G(t,1);x([...n]),H.current=[...n].length,d(!1)}),500),[X,Y,G,x,k,g]),{handleDrop:ee}=jf({pinnedChats:w,folders:N,finshChats:K,initChatList:Y}),te=D.useCallback(()=>{"boolean"==typeof T&&T&&(E(!1),Y())},[T,E,Y]),ne=D.useCallback(()=>{const e=_R()&&!y;wR()||v(!e&&window.innerWidth>=760)},[y,v]);return{todayActiveChatId:e,setTodayActiveChatId:t,pinnedActiveChatId:n,setPinnedActiveChatId:s,selectedChatId:i,setSelectedChatId:a,chatListLoading:o,searchLoading:c,chatId:u,user:h,sidebarFloatingPlaceholder:m,searchInputFocused:p,showSidebar:f,setShowSidebar:v,mobile:y,pinnedChats:w,folders:N,temporaryChatEnabled:j,finshChats:K,prevChatListLength:H,enableProjectEntry:F,showPanelList:I,setShowPanelList:M,activeChatMenuId:R,setActiveChatMenuId:P,enablePaymentEntry:q,subscriptionPlus:L,setShowSubscriptionDetail:O,search:l,getChatStatus:Q,initChatList:Y,loadMoreChats:J,searchDebounceHandler:Z,handleDrop:ee,__initSidebarEffect:te,__handleUserAndConfigEffect:ne,PAGE_SIZE:60}})();D.useEffect(()=>{a(l||"")},[l,a]),D.useEffect(()=>{"function"==typeof L&&L()},[]),D.useEffect(()=>{O()},[]);const U=D.useRef(!1),H=Pd(e=>e.user),B=cR(e=>e.config);return D.useEffect(()=>{H&&B&&!U.current&&(U.current=!0,M())},[H,B]),F.jsxs("div",{className:Q("sidebar-wrapper",{"sidebar-wrapper-mask":u&&(m||c)}),children:[F.jsx("div",{className:"mask",onClick:()=>h(!u)}),F.jsx(Gg,{unarchiveHandler:M}),c&&F.jsx("div",{className:"sidebar-float-placeholder"}),F.jsx("div",{id:"sidebar",className:Q("sidebar",{"sidebar-floating":c,[c?"sidebar-floating-collapse":"sidebar-collapse"]:!u,"sidebar-side-fold-container":!m&&!u}),"data-state":u,onClick:e=>e.stopPropagation(),children:F.jsxs("div",{className:Q("sidebar-side side-mobile-width",{"sidebar-hide-side":!u}),children:[F.jsx($g,{}),m&&F.jsx(of,{}),F.jsx(Lf,{searchInputChange:P}),F.jsxs("div",{className:"sidebar-new-list-content",onScroll:()=>x&&w(!1),children:[F.jsx(jx,{}),F.jsx(Tx,{fallback:null,children:F.jsx(Nf,{mobile:m,searchInputFocused:d,searchCurrent:N.current,pinnedChats:p,folders:g,temporaryChatEnabled:!!f,finshChats:v,selectedChatId:i,todayActiveChatId:e,pinnedActiveChatId:n,prevChatListLength:y.current,chatListLoading:o,searchLoading:r,showSidebar:!!u,enableProjectEntry:!!b,activeChatMenuId:_,PAGE_SIZE:q,onSelectedChatIdChange:a,onPinnedActiveChatIdChange:s,onTodayActiveChatIdChange:t,onLoadMore:R,onInitChatList:M,onSetActiveChatMenuId:k,getChatStatus:I})})]}),F.jsx(Mf,{mobile:m,showSidebar:!!u,enablePaymentEntry:!!j,subscriptionPlus:T,onShowSubscriptionDetail:()=>E(!0)})]})})]})}),Nx=({showReport:e})=>{const{i18n:t}=ye();return D.useEffect(()=>{const t=document.getElementById("deploy-report");return null==t||t.addEventListener("click",e),()=>{null==t||t.removeEventListener("click",e)}},[e]),F.jsx("div",{dangerouslySetInnerHTML:{__html:t.t("You’re viewing user-generated AI content that may be unverified or unsafe. Report unsafe content [{{here}}].",{here:``})},onClick:e})};function Ix(e){var t;const n=new URLSearchParams(window.location.search),s=n.get("inputFeature");let i,a=[];if(s){const e=function(e){if(dn.find(t=>t.chatType&&t.chatType===e))return{chatType:e};const t=dn.find(t=>t.chatType&&(t.key===e||t.subChatType===e)&&t.chatType!==e);return(null==t?void 0:t.chatType)?{chatType:t.chatType,subChatType:e}:{chatType:e}}(s);a=[e.chatType],i=e.subChatType}const o=null==(t=n.get("model")||n.get("models"))?void 0:t.split(","),r=function(e,t){return t&&0!==t.length?t.map(t=>{const n=e.find(e=>e.id===t);if(n)return n.id;const s=e.find(e=>e.name===t);return s?s.id:null}).filter(e=>null!==e):[]}(e,o&&0!==(null==o?void 0:o.length)?o:[]),l=n.get("text");return"true"===n.get("thinking")&&a.push(Lh.Thinking),{features:a,models:r,subChatType:i,textStr:l}}const Ax=D.memo(e=>{const{deployType:t="default",showReport:n=()=>{}}=e,{i18n:s}=ye(),i=Ue(),[a,o]=D.useState(!1),[r,l]=D.useState(!0),c=D.useRef(null),d=dR(e=>e.mobile),u=js(e=>e.chatId),h=ud(e=>e.theme),m=D.useCallback(e=>{if(!e)return!1;const t=e.clientHeight,n=document.createElement("div");n.style.position="absolute",n.style.visibility="hidden",n.style.whiteSpace="nowrap",n.style.width="auto",n.style.height="auto",n.style.fontSize=window.getComputedStyle(e).fontSize,n.style.lineHeight=window.getComputedStyle(e).lineHeight,n.innerText=e.innerText,document.body.appendChild(n);const s=n.clientHeight;return document.body.removeChild(n),t>=s},[]),p=D.useCallback(()=>{pl("clkShareVisitQwenBtn",{params:{et:"CLK"},aesParams:{c4:u},paramsExtend:{share_id:u}}),bM.updateChatHistory({messages:{},currentId:null,currentResponseIds:[]}),(()=>{const{currentInputFeature:e,currentInputSubType:t}=js.getState();localStorage.setItem("userChatState",JSON.stringify({currentInputFeature:e,currentInputSubType:t}))})(),bM.closeShowControls(),yM.reset(["inputValue","files","showDetail","wordsShowMore"]),js.getState().resetChatState(),d?Us.getInstance().openWindow("https://qwen.ai/download"):i("artifacts"===t?"/?inputFeature=artifacts":"web_dev"===t?"/?inputFeature=web_dev":"deep_research"===t?"/?inputFeature=deep_research":`/?qsrc=share&share_id=${u}`)},[u,t,d,i]),g=D.useMemo(()=>"artifacts"===t?s.t("Try {{capability}} in Qwen",{capability:"Artifacts"}):"web_dev"===t?s.t("Try {{capability}} in Qwen",{capability:"Web Dev"}):"deep_research"===t?s.t("Try {{capability}} in Qwen",{capability:"Deep Research"}):d?s.t("Download App"):s.t("Go to Qwen"),[t,s,d]),f=D.useMemo(()=>d?F.jsx(ee,{open:a,placement:"bottom",height:"100%",drawerRender:()=>F.jsxs("div",{className:"download-page",children:[F.jsx("div",{className:"download-page-back",onClick:()=>o(!1),children:F.jsx(pi,{type:"icon-line-chevron-left",className:"download-page-back-icon"})}),F.jsxs("div",{className:"download-page-content",children:[F.jsx("div",{className:"page-title",children:s.t("Download App")}),F.jsx("div",{className:"page-des",children:s.t("Designed for mobile devices, offering better experience and more features")}),F.jsx(Wg,{}),F.jsxs("div",{className:"download-page-qr-code",children:[F.jsx(Vg,{type:"ios"}),F.jsx(Vg,{type:"android"})]}),F.jsx("div",{className:"page-bottom",children:s.t("Press and hold to scan the QR code for download")})]})]})}):null,[s,d,a]);return D.useEffect(()=>{l(m(c.current))},[c,m]),F.jsxs("div",{className:"share-logo",children:[d?F.jsxs("div",{className:"share-logo-mobile",children:[F.jsx("div",{className:"share-logo-mobile-img",children:F.jsx("img",{crossOrigin:"anonymous",src:"//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.18/static/app_logo_angle_rounded.png",alt:"logo"})}),F.jsxs("div",{children:[F.jsx("div",{className:"share-logo-mobile-tip",children:"Qwen"}),r&&F.jsx("div",{ref:c,className:"share-logo-mobile-desc",children:s.t("Official App provided by Qwen")})]})]}):F.jsxs("div",{className:"share-logo-pc",children:[F.jsx("img",{crossOrigin:"anonymous",src:`//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.1.18/static/${"dark"===h?"qwen_row_text_icon_dark_540":"qwen_row_text_icon_light_540"}.png`,className:"h-7",alt:"logo"}),["artifacts","web_dev","deep_research"].includes(t)&&F.jsx("div",{className:"powered-text",children:F.jsx(Si,{title:s.t("This content was generated by a Qwen user using AI. We disclaim any responsibility for errors or inaccuracies. If you find any unsafe content, please report it."),children:F.jsx(Nx,{showReport:n})})})]}),F.jsxs("button",{className:"share-logo-button",onClick:p,children:[g,["artifacts","web_dev","deep_research"].includes(t)&&F.jsx(pi,{type:"icon-line-arrow-up-right",className:"deploy-icon"})]}),f]})}),Mx={welcomeModal:"index-module__welcome-modal___JaI7D",welcomeModalTitle:"index-module__welcome-modal-title___zaeeB",welcomeModalDescription:"index-module__welcome-modal-description___EpSov",welcomeModalFooter:"index-module__welcome-modal-footer___iRg5y"},Rx={welcomeModal:"index-h5-module__welcome-modal___bkT-Q",welcomeModalTitle:"index-h5-module__welcome-modal-title___IYxl5",welcomeModalDescription:"index-h5-module__welcome-modal-description___Nw11O",welcomeModalFooter:"index-h5-module__welcome-modal-footer___xpzCn"},Px=D.memo(()=>{const{t:e}=ye(),t=Rs(e=>e.welcomeModalShow),n=Rs(e=>e.setWelcomeModalShow),s=cR(e=>e.mobile),i=Ue(),a=D.useMemo(()=>s?Rx:Mx,[s]),o=D.useCallback(()=>{pl("clkLogOn",{params:{et:"CLK"}}),si()?bM.openWindow(`${window.location.origin}/auth?callback=qwen://open`):i("/auth?action=signin")},[]),r=D.useCallback(()=>{pl("clkRegister",{params:{et:"CLK"}}),si()?bM.openWindow(`${window.location.origin}/auth?mode=register&callback=qwen://open`):i("/auth?action=signup")},[]),l=D.useCallback(()=>{pl("clkKeepcancel",{params:{et:"CLK"}}),n(!1)},[n]);return F.jsxs(wi,{visible:t,footer:!1,header:!1,size:"small",className:a.welcomeModal,children:[F.jsx("div",{className:a.welcomeModalTitle,children:e("Welcome")}),F.jsx("div",{className:a.welcomeModalDescription,children:e("Login or sign up to chat with Qwen, upload file and image, generation image or video, and more.")}),F.jsxs("div",{className:a.welcomeModalFooter,children:[F.jsx(xi,{size:"large",rounded:"circle",onClick:o,children:e("Log in")}),F.jsx(xi,{size:"large",type:"ghost",rounded:"circle",onClick:r,children:e("Sign up")}),F.jsx(xi,{size:"large",type:"link",onClick:l,children:e("Stay logged out")})]})]})}),Lx="index-module__whats-new-modal-container___aZLQL",Ox="index-module__whats-new-modal___5Qs0C",Dx="index-module__whats-new-modal-close___qtIuL",Fx="index-module__whats-new-modal-left___JqTaa",qx="index-module__whats-new-modal-left-title___EIBYL",Ux="index-module__whats-new-modal-left-content___eccMV",Hx="index-module__content-title___UHTLe",Bx="index-module__content-title-icon___yx95v",zx="index-module__content-title-text___TJoKL",Gx="index-module__content-desc___QCbCs",$x="index-module__whats-new-modal-right___-tPFE",Wx=()=>{const e=ye(),t=Jh(e=>e.settings.memory),n=Jh(e=>e.setSettings),s=cR(e=>{var t;return null==(t=e.config)?void 0:t.memory_version}),i=()=>A(null,null,function*(){yield n({memory:{memory_version_reminder:!1}})});return"disable"!==s&&s?F.jsx(wi,{visible:!!(null==t?void 0:t.memory_version_reminder),width:753,header:!1,footer:!1,closable:!1,maskClosable:!1,headerBorderNone:!1,className:Lx,onCancel:i,children:F.jsxs("div",{className:Ox,children:[F.jsx(pi,{className:Dx,type:"icon-close-4",onClick:i}),F.jsxs("div",{className:Fx,children:[F.jsx("div",{className:qx,children:e.t("What's New?")}),F.jsxs("div",{className:Ux,children:[F.jsxs("div",{className:Hx,children:[F.jsx(pi,{className:Bx,type:"icon-line-brain-02"}),F.jsx("span",{className:zx,children:e.t("Memory")})]}),F.jsx("div",{className:Gx,children:e.t("Qwen will remember useful details and preferences across all conversations to provide more personalized and consistent responses.")})]})]}),F.jsx("div",{className:$x,children:F.jsx("img",{src:"https://img.alicdn.com/imgextra/i4/O1CN01DgUq3R23SqYBvpo6V_!!6000000007255-2-tps-1200-1500.png",alt:"memory"})})]})}):null},Vx="index-module__whats-new-modal___X2s-A",Qx="index-module__whats-new-modal-header___uVPrO",Kx="index-module__img___EZc5C",Yx="index-module__close___QXYrx",Jx="index-module__whats-new-modal-body___epNR7",Xx="index-module__title___JVzy9",Zx="index-module__content___C-abQ",ew="index-module__content-icon___O5ytX",tw="index-module__content-info___6CQfZ",nw="index-module__content-info-title___xp-qz",sw="index-module__content-info-desc___8W-b5",iw="index-module__whats-new-modal-footer___To7mP",aw="index-module__btn___3ZIut",ow=()=>{const e=ye(),t=Jh(e=>e.settings.memory),n=Jh(e=>e.setSettings),s=cR(e=>{var t;return null==(t=e.config)?void 0:t.memory_version}),i=()=>A(null,null,function*(){yield n({memory:{memory_version_reminder:!1}})});return"disable"!==s&&s?F.jsxs(Ti,{open:!!(null==t?void 0:t.memory_version_reminder),className:Vx,heightType:"auto",children:[F.jsxs("div",{className:Qx,children:[F.jsx("img",{src:"https://img.alicdn.com/imgextra/i2/O1CN01QYf8FN1ZFAEwFIWK3_!!6000000003164-2-tps-375-160.png",alt:"",className:Kx}),F.jsx(pi,{className:Yx,type:"icon-close-4",onClick:i})]}),F.jsxs(ie,{className:Jx,vertical:!0,gap:16,children:[F.jsx("div",{className:Xx,children:e.t("What's New?")}),F.jsxs(ie,{className:Zx,gap:16,justify:"space-between",children:[F.jsx(pi,{className:ew,type:"icon-line-brain-02"}),F.jsxs("div",{className:tw,children:[F.jsx("div",{className:nw,children:e.t("Memory")}),F.jsx("div",{className:sw,children:e.t("Qwen will remember useful details and preferences across all conversations to provide more personalized and consistent responses.")})]})]})]}),F.jsx("div",{className:iw,children:F.jsx(xi,{className:aw,type:"brandprimary",rounded:"circle",onClick:i,children:e.t("Got it")})})]}):null},rw=(e,t)=>A(null,null,function*(){return yield TM(`/projects/${t}`,{method:"PUT",data:e})}),lw=e=>A(null,null,function*(){return yield TM(`/projects/${e}/files`)}),cw=()=>A(null,null,function*(){return yield TM("/projects/")}),dw=(e,t)=>A(null,null,function*(){return yield TM(`/chats/?project_id=${e}&page=${t}`)}),uw=(e,t)=>A(null,null,function*(){return yield TM("/projects/add_chat",{method:"POST",data:JSON.stringify({chat_ids:t,project_id:e})})}),hw=e=>A(null,null,function*(){return yield TM(`/projects/${e}`)}),mw={projectSettingOpen:!1,projectName:"",projectIcon:"",instructionValue:"",showDeleteConfirm:!1,showEditModal:!1,operationProject:{},operationProjectFiles:[],deleteFiles:[],projectInfo:{},projectInfoFiles:[],showAllList:!1,activeProjectId:null,projectChats:[],projectArr:[],chatProjectId:null,moveNewProjectId:"",projectExpandChats:[],activeChatDetails:null,showPanelList:!1},pw=Sn()(_s(e=>C(C({},mw),(e=>({setProjectSettingOpen:t=>e({projectSettingOpen:t}),setProjectName:t=>e({projectName:t}),setProjectIcon:t=>e({projectIcon:t}),setInstructionValue:t=>e({instructionValue:t}),setShowDeleteConfirm:t=>e({showDeleteConfirm:t}),setShowEditModal:t=>e({showEditModal:t}),setOperationProject:t=>e({operationProject:t}),setOperationProjectFiles:t=>e({operationProjectFiles:t}),setDeleteFiles:t=>e({deleteFiles:t}),setProjectInfo:t=>e({projectInfo:t}),setProjectInfoFiles:t=>e({projectInfoFiles:t}),setShowAllList:t=>e({showAllList:t}),setActiveProjectId:t=>e({activeProjectId:t}),setProjectChats:t=>e({projectChats:t}),setProjectArr:t=>e({projectArr:t}),setChatProjectId:t=>e({chatProjectId:t}),setMoveNewProjectId:t=>e({moveNewProjectId:t}),resetProjectState:()=>e(mw),setProjectExpandChats:t=>e({projectExpandChats:t}),setActiveChatDetails:t=>e({activeChatDetails:t}),setShowPanelList:t=>e({showPanelList:t})}))(e)),{name:"projectStore",store:"projectStore",enabled:!1})),gw=({title:e,tooltip:t="",props:n})=>{const s=cR(e=>e.mobile);return F.jsxs("div",{className:"project-instruction-container",children:[F.jsxs("div",{className:"project-instruction-label",children:[e&&F.jsx("div",{className:"project-instruction-label-text",children:e}),t&&!s&&F.jsx(Si,{title:t,children:F.jsx(pi,{type:"icon-line-information-circle",className:"project-instruction-label-tooltip"})})]}),F.jsx("div",{className:"project-instruction-textarea",children:F.jsx(yi,C({},n))})]})},fw=({showProjectChatInsModal:e,onCloseModal:t,inputValue:n})=>{const{getNewProjectList:s}=ig(),i=ye(),a=cR(e=>e.mobile),[o,r]=O.useState(n||""),[l,c]=O.useState(!1),d=pw(e=>e.projectInfo),u=pw(e=>e.setProjectInfo),h=()=>A(null,null,function*(){try{const e=yield rw({custom_instruction:o},d.id);e&&e.data.status&&(s(),u(S(C({},d),{custom_instruction:o})),vi.openOnce({type:"success",content:i.t("Instruction saved successfully.")}),t(),c(!1))}catch(e){}}),m=()=>{t(),c(!1)},p=()=>F.jsx(gw,{props:{value:o||"",onChange:e=>{r(e),l||c(!0)},minRows:a?10:1,maxRows:10,maxLength:1e3,placeholder:i.t("What should the AI know about this project? (e.g., specific rules, tone, or formatting)")}});return a?F.jsx(Ti,{open:e,title:i.t("Instructions"),heightType:"auto",onClose:t,size:"large",className:"mobile-project-ins-popup",children:F.jsx("div",{className:"qwen-chat-comp-project-ins-popup",children:F.jsxs("div",{className:"qwen-chat-comp-project-ins-popup-content",children:[p(),F.jsxs("div",{className:"qwen-chat-comp-project-ins-popup-footer",children:[F.jsx(xi,{type:"tertiary",size:"large",rounded:"circle",className:"qwen-chat-comp-project-ins-popup-footer-btn",onClick:m,children:i.t("Cancel")}),F.jsx(xi,{type:"brandprimary",size:"large",rounded:"circle",className:"qwen-chat-comp-project-ins-popup-footer-btn",disabled:o===n,onClick:h,children:i.t("Save")})]})]})})}):F.jsxs(wi,{size:"medium",visible:e,className:"qwen-chat-comp-project-ins-modal",title:i.t("Instructions"),headerBorderNone:!0,onCancel:m,onOk:h,footer:!1,okText:i.t("Save"),cancelText:i.t("Cancel"),children:[p(),F.jsxs("div",{className:"qwen-chat-comp-project-ins-modal-footer",children:[F.jsx(xi,{type:"ghost",rounded:"circle",className:"qwen-chat-comp-project-ins-modal-footer-btn",onClick:m,children:i.t("Cancel")}),F.jsx(xi,{type:"brandprimary",rounded:"circle",className:"qwen-chat-comp-project-ins-modal-footer-btn",onClick:h,disabled:o===n,children:i.t("Save")})]})]})},vw=({file:e,actions:t=["delete"],onReUpload:n,onDownload:s,onDelete:i,isMobileProjectDetail:a})=>{var o,r,l;const[c,d]=D.useState(!1),u=cR(e=>e.mobile),{i18n:h}=ye(),m={download:{icon:"icon-download",text:"Download"},delete:{icon:"icon-line-trash-01",text:"Delete"}},p=D.useMemo(()=>{var t,n;const s=(null==(t=e.name)?void 0:t.lastIndexOf("."))||-1;return(null==(n=null==e?void 0:e.name)?void 0:n.slice(s+1))||""},[e.name]),g=(()=>{var t,n,s,i,a,o,r,l,c;const d=tn[e.file_type||e.type]||tn.others;let u=d.bg,h=d.icon;if(Vt.includes(p)&&(h="icon-playground",u="#3F3F47"),null==(s=null==(n=null==(t=null==e?void 0:e.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)switch(null==(o=null==(a=null==(i=null==e?void 0:e.file)?void 0:i.meta)?void 0:a.parse_meta)?void 0:o.parse_status){case"success":return{icon:h,bg:u};case"failed":return(null==(c=null==(l=null==(r=null==e?void 0:e.file)?void 0:r.meta)?void 0:l.parse_meta)?void 0:c.retry)?{icon:"icon-regenerate",bg:u}:d;case"running":return{icon:"icon-loading-icon",bg:u};default:return""}switch(e.uploadStatus){case"success":return{icon:h,bg:u};case"uploading":default:return{icon:"icon-loading-icon",bg:u};case"error":return{icon:"icon-regenerate",bg:u}}})(),f=D.useMemo(()=>{var t,n,s,i,a,o,r,l;if(null==(s=null==(n=null==(t=null==e?void 0:e.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)switch(null==(o=null==(a=null==(i=null==e?void 0:e.file)?void 0:i.meta)?void 0:a.parse_meta)?void 0:o.parse_status){case"success":default:return"parsed";case"failed":return"parsed_error";case"running":return"parsing"}switch(e.uploadStatus){case"success":return(null==(l=null==(r=null==e?void 0:e.file)?void 0:r.meta)?void 0:l.parse_meta)?"success":"parsed";case"uploading":return"uploading";case"error":return"error";default:return"success"}},[e.uploadStatus,null==(l=null==(r=null==(o=e.file)?void 0:o.meta)?void 0:r.parse_meta)?void 0:l.parse_status]),v=t=>{switch(t){case"download":s(e);break;case"delete":i(e)}},y=D.useMemo(()=>"green_error"===e.greenNet,[e.greenNet]);return F.jsxs("div",{className:Q("project-file-card",{"project-file-card-greening":y}),children:[F.jsxs("div",{className:"project-file-card-left",children:[F.jsx("div",{className:"project-file-card-left-icon",onClick:()=>{"error"===e.uploadStatus&&n(e)},style:y?{}:{backgroundColor:g.bg},children:y?F.jsx(pi,{type:"icon-line-file-none",className:"fileitem-icon"}):F.jsx(pi,{type:g.icon,className:e.uploadStatus})}),F.jsxs("div",{className:"project-file-card-left-info",children:[F.jsx("div",{className:"project-file-card-left-info-name",children:F.jsx("div",{className:"project-file-card-left-info-text",children:e.name})}),F.jsx("div",{className:"project-file-card-left-info-size",children:F.jsxs("div",{className:"project-file-card-left-info-text",children:[F.jsx("span",{children:((e,t=1)=>{if(0===e)return"0 B";const n=["B","K","M"],s=Math.floor(Math.log(e)/Math.log(1024)),i=n[Math.min(s,n.length-1)];return`${(e/Math.pow(1024,s)).toFixed(t)}${i}`})(e.size)}),"parsing"===f&&F.jsx("span",{children:h.t("Parsing...")}),"parsed_error"===f&&!y&&F.jsx("span",{className:"project-file-error",children:h.t("Parsing failed")}),"error"===f&&!y&&F.jsx("span",{className:"project-file-error",children:h.t("Upload failed")}),y&&F.jsx("span",{className:"fileitem-file-error",children:h.t("Invalid File")})]})})]})]}),F.jsx("div",{className:"project-file-card-right",children:F.jsx("div",{className:"project-file-card-right-actions",children:u&&a?F.jsx(Y,{open:c,onOpenChange:e=>{e||d(!1)},trigger:["click"],popupRender:()=>F.jsx(ae,{mode:"inline",className:"project-file-operation-menu-content",children:t.map(e=>"download"===e&&"parsed"===f||"delete"===e?F.jsxs(ae.Item,{className:"project-file-operation-menu-item "+("delete"===e?"project-file-item-delete":""),onClick:()=>v(e),children:[F.jsx("div",{className:"project-file-operation-menu-item-text",children:h.t(m[e].text)}),F.jsx(pi,{className:"project-file-operation-menu-item-icon",type:m[e].icon})]},e):null)}),placement:"bottomLeft",children:F.jsx("div",{onClick:()=>{d(!0)},children:F.jsx(pi,{type:"icon-line-more-01",className:"project-file-card-right-actions-icon "})})}):F.jsx(F.Fragment,{children:t.map(e=>"download"===e&&"parsed"===f||"delete"===e?F.jsx("div",{className:"project-file-card-right-actions-icon",onClick:()=>v(e),children:F.jsx(pi,{type:m[e].icon})},e):null)})})})]})},yw=({files:e=[],actions:t=["delete"],onReUpload:n,onDownload:s,onDelete:i,isMobileProjectDetail:a})=>{const o=pw(e=>e.deleteFiles),r=e.filter(e=>!o.includes(e.file_id||e.itemId));return F.jsx(F.Fragment,{children:r.length?F.jsx("div",{className:"project-file-list",children:r.map(e=>F.jsx(vw,{file:e,actions:t,onReUpload:n,onDownload:s,onDelete:i,isMobileProjectDetail:a},e.file_id||e.itemId))}):null})},bw=ve();class xw{constructor(e){if(j(this,"input"),j(this,"options"),this.input=e,!this.input)throw new Error("无法找到指定的 input 元素");this.input.addEventListener("change",this.handleFileSelect.bind(this)),this.input.addEventListener("error",this.handleError)}setInputAcceptAttribute(){var e,t;const n=null==(t=null==(e=this.options)?void 0:e.acceptedTypes)?void 0:t.join(","),s="image/*"===n?"image":"file";Qs()&&"file"===s?this.input.removeAttribute("accept"):(this.input.setAttribute("accept",n||""),this.input.setAttribute("data-type",s))}setCapture(){var e,t;(null==(e=this.options)?void 0:e.capture)?this.input.setAttribute("capture",null==(t=this.options)?void 0:t.capture):this.input.removeAttribute("capture")}handleError(){}updateOptions(e){this.options=e,this.setInputAcceptAttribute(),this.setCapture()}triggerUpload(){this.input.click()}handleFileSelect(e){var t,n;const s=null==(t=e.target)?void 0:t.files,i=Array.from(s||[]);0!==i.length&&(null==(n=this.options)||n.callBack(i),this.input.value="")}static validateFile(e,t){var n,s,i;if(!e)throw new Error("未选择任何文件。");let a=e;"md"===(null==(i=null==(s=null==(n=null==e?void 0:e.name)?void 0:n.split("."))?void 0:s.at(-1))?void 0:i.toLowerCase())&&""===e.type&&(a=new File([e],e.name,{type:"text/markdown"}));const{maxSize:o=0,acceptType:r="*"}=t||{};if(o){const e=a.size<=o,t=bw.t("File size should not exceed {{maxSize}} MB.",{maxSize:o/1024/1024});if(!e)throw Gl.openOnce({type:"error",message:t}),new Error(t)}const l=e.type,c=l.startsWith("image/")?"image":l.startsWith("video/")?"video":l.startsWith("audio/")?"audio":"file";if("file"===r)if(["image","video","audio"].includes(c))throw new Error(`文件类型 ${e.type} 不被接受。请上传 ${r} 类型的文件。`);return a}clearSelectedFiles(){this.input.value=""}destroy(){this.input.removeEventListener("change",this.handleFileSelect),this.input.removeEventListener("error",this.handleError)}}const ww=({styles:e,ref:t})=>{var n,s,i;const a=Fd(e=>e.subscriptionPlus),o=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_payment_and_quota}),r=Fd(e=>e.setShowSubscriptionDetail),l=Pd(e=>e.user),c=cR(e=>e.mobile),d=cR(e=>e.config),u=pw(e=>e.operationProjectFiles),h=pw(e=>e.setOperationProjectFiles),m=pw(e=>e.deleteFiles),p=D.useRef(null),g=D.useRef(null),{i18n:f}=ye(),v=D.useMemo(()=>new Tu({onAddProcess:(e,t)=>{if(t){const e=S(C({},t),{uploadStatus:"uploading"}),n=pw.getState().operationProjectFiles;h([Te(S(C({},e),{uploadStatus:"uploading"})),...n.filter(t=>t.itemId!==e.itemId)])}},onAddSuccess:(e,t)=>{var n,s,i,a;const o=S(C({},t),{uploadStatus:"success"}),r=pw.getState().operationProjectFiles;e.length&&e.some(e=>e.itemId===t.itemId)&&!m.includes(o.itemId)&&(h([Te(o),...r.filter(e=>e.itemId!==o.itemId)]),pl("uploadedFileData",{params:{et:"OTHER",c1:null!=(s=null==(n=null==t?void 0:t.file)?void 0:n.user_id)?s:void 0,c4:null==t?void 0:t.id,c5:null==t?void 0:t.name,c6:t.file_type,c7:(null==(i=null==t?void 0:t.file)?void 0:i.meta)?JSON.stringify(null==(a=null==t?void 0:t.file)?void 0:a.meta):"",c8:t.status}}))},onAddFail:(e,t)=>{if(t){const e=S(C({},t),{uploadStatus:"uploading"===t.status?"uploading":"error"}),n=pw.getState().operationProjectFiles;h([Te(e),...n.filter(t=>t.itemId!==e.itemId)])}pl("uploadedFileErr",{params:{et:"OTHER"}})},onPaseSuccess:(e,t)=>{const n=S(C({},t),{uploadStatus:"success"}),s=pw.getState().operationProjectFiles;e.length&&e.some(e=>e.itemId===t.itemId)&&!m.includes(n.itemId)&&h([Te(n),...s.filter(e=>e.itemId!==n.itemId)])},onPaseFail:(e,t)=>{if(t){const e=S(C({},t),{uploadStatus:"uploading"===t.status?"uploading":"error"}),n=pw.getState().operationProjectFiles;h([Te(e),...n.filter(t=>t.itemId!==e.itemId)])}},userId:null==l?void 0:l.id,parsedFileTypes:[Zt.FILE]}),[m,h,null==l?void 0:l.id]);D.useEffect(()=>{t&&(t.current=v)},[t,v]);D.useEffect(()=>{var e;const t=null==(e=null==d?void 0:d.features)?void 0:e.limits;t&&v.updateLimitRules(uu(t))},[v,null==(n=null==d?void 0:d.features)?void 0:n.limits]),D.useEffect(()=>{p.current&&(g.current=new xw(p.current))},[]);const y=D.useMemo(()=>{var e,t,n;return(null==(n=null==(t=null==(e=null==d?void 0:d.features)?void 0:e.limits)?void 0:t.project)?void 0:n.project_file_max_count)||5},[null==(s=null==d?void 0:d.features)?void 0:s.limits]),b=D.useMemo(()=>{var e,t,n;return(null==(n=null==(t=null==(e=null==d?void 0:d.features)?void 0:e.limits)?void 0:t.project)?void 0:n.project_max_count)||20},[null==(i=null==d?void 0:d.features)?void 0:i.limits]),x=D.useMemo(()=>o&&a?b:y,[o,y,b,a]),w=D.useMemo(()=>{if(!x)return!0;return pw.getState().operationProjectFiles.length-m.length>=x},[u.length,m.length,x]),_=D.useMemo(()=>o?a?f.t(w?"File limit reached. Maximum {{number}} files allowed.":"Upload up to {{number}} files.",{number:b}):F.jsx(be,{i18nKey:w?"File limit reached. {{upgrade}} to increase your limit to {{filesNumber}} files.":"Free plan includes {{fileNumber}} files. {{upgrade}} to add up to {{filesNumber}} files.",values:{fileNumber:y,filesNumber:b,upgrade:""},components:{a:F.jsx("span",{className:"qwen-chat-project-file-list-tooltip-enable-link",onClick:()=>{r(!0)},children:f.t("Upgrade to plus")})}}):f.t(w?"File limit reached. Maximum {{number}} files allowed.":"Upload up to {{number}} files.",{number:x}),[o,w,f,x,a,y,b,r]);return D.useEffect(()=>{v.updateLimitRules(Me(Te(en),{[Xt.DOC]:{max_count:x}}))},[x,v]),F.jsxs(F.Fragment,{children:[F.jsx(Si,{show:Boolean(_),rootClassName:"qwen-chat-project-file-list-tooltip",title:_,children:F.jsx(xi,{type:"tertiary",rounded:"circle",buttonClass:"project-file-list-add",disabled:w,size:"small",onClick:()=>{return e="document",A(null,null,function*(){var t,n;null==(t=g.current)||t.updateOptions({acceptedTypes:Hr(e),type:e,callBack:t=>{const n=u.length-m.length,s=a?b:y;if(n+t.length>s){const i=t.slice(0,s-n);return Gl.open({type:"error",content:f.t("In a single-turn conversation, up to {{number}} documents can be uploaded.",{number:s})}),void v.addFiles(i,e)}v.addFiles(t,e)}}),null==(n=g.current)||n.triggerUpload()});var e},buttonStyle:C({},e),children:f.t("Add Files")})}),F.jsx("input",{ref:p,type:"file",id:"filesUpload",multiple:!c,style:{display:"none"}})]})},_w=e=>A(null,null,function*(){const t=pw.getState().projectInfo,n=pw.getState().setProjectInfo;if(e)try{const{data:s,success:i}=yield lw(e);if(!i)return void s.code;if(!(null==s?void 0:s.files)||!Array.isArray(s.files))return;const a=s.files.map(e=>S(C({},e),{uploadStatus:"success"}));n(S(C({},t),{fileLength:a.length}))}catch(s){}}),Cw=({onCancel:e,onConfirm:t})=>{const n=ye(),s=cR(e=>e.mobile);return F.jsx(wi,{visible:!0,title:n.t("Discard this project?"),closable:!0,headerBorderNone:!0,onCancel:e,className:"project-delete-modal",actions:[{text:n.t("Cancel"),type:"tertiary",onClick:e,rounded:"circle",size:s?"large":"middle"},{text:n.t("Confirm"),type:"dangerprimary",onClick:t,rounded:"circle",size:s?"large":"middle"}],size:"small",children:n.t("Your project hasn't been saved yet—closing this window will discard all your input, including any ongoing work.")})},Sw=({showProjectChatFileModal:e,onCloseModal:t,projectId:n})=>{const{getProjectFilesList:s}=ig(),i=ye(),a=cR(e=>e.mobile),o=pw(e=>e.operationProjectFiles),r=pw(e=>e.deleteFiles),l=pw(e=>e.setDeleteFiles),c=pw(e=>e.setOperationProjectFiles),[d,u]=D.useState(!1),h=D.useRef(null),m=e=>A(null,null,function*(){var t,n,s,i;e&&"failed"===(null==(s=null==(n=null==(t=e.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)?null==(i=null==h?void 0:h.current)||i.startParse(e,!0):e&&e.uploadTaskId&&(yield fu.resumeUpload(e.uploadTaskId))}),p=D.useMemo(()=>o.filter(e=>!r.includes(e.itemId)).some(e=>{var t,n,s;return"uploading"===e.status||"running"===(null==(s=null==(n=null==(t=null==e?void 0:e.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)}),[r,o]);D.useEffect(()=>{n&&s(n)},[n]);const g=e=>{var t;null==(t=null==h?void 0:h.current)||t.removeFile(e),l([...r,e.file_id||e.itemId])},f=()=>{u(!1),A(null,null,function*(){const e=o.filter(e=>"uploading"===e.uploadStatus).map(e=>e.itemId);if(p)return o.forEach(e=>{var t,n,s,i;"running"===(null==(s=null==(n=null==(t=e.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)&&(null==(i=null==h?void 0:h.current)||i.removeFile(e))}),void l(e);const t=o.filter(e=>!e.file_id&&"success"===e.uploadStatus&&"success"===e.greenNet).filter(e=>!r.includes(e.itemId)),s=yield rw({add_files:t,delete_files:r},n);s&&s.success&&(l(e),_w(n))}),t(),c([])},v=()=>{p?u(!0):f()},y=()=>F.jsx(yw,{files:o,actions:["download","delete"],onReUpload:m,onDownload:e=>{const{path:t,url:n}=e,s=t||n;s.includes("img.alicdn.com")?Ml(s):Pl({role:"user",url:s})},onDelete:g,isMobileProjectDetail:a});return F.jsxs(F.Fragment,{children:[a?F.jsxs(Ti,{open:e,title:i.t("Files"),heightType:"full",onClose:v,className:"mobile-project-ins-popup",children:[F.jsx("div",{className:"qwen-chat-comp-project-file-popup-list",children:y()}),F.jsx(ww,{styles:{width:"calc(100% - 30px)",height:"48px",margin:"0 15px"},ref:h})]}):F.jsxs(wi,{size:"medium",visible:e,className:"qwen-chat-comp-project-file-modal",footer:!1,header:!1,bodyPaddingNone:!0,onCancel:v,children:[F.jsxs("div",{className:"qwen-chat-comp-project-file-modal-herder",children:[F.jsx("div",{className:"qwen-chat-comp-project-file-modal-title",children:i.t("Files")}),F.jsxs("div",{className:"qwen-chat-comp-project-file-modal-action",children:[F.jsx(ww,{ref:h}),F.jsx("button",{onClick:v,className:"qwen-chat-comp-project-file-modal-close",children:F.jsx(pi,{type:"icon-line-x-01"})})]})]}),F.jsx("div",{className:"qwen-chat-comp-project-file-modal-list",children:y()})]}),d&&F.jsx(Cw,{onCancel:()=>{u(!1)},onConfirm:()=>{f()}})]})},kw=({showEditProjectNameModal:e,onCloseModal:t,projectTitle:n})=>{const{getNewProjectList:s}=ig(),i=ye(),a=cR(e=>e.mobile),[o,r]=O.useState(n||""),l=pw(e=>e.projectInfo),c=pw(e=>e.setProjectInfo),d=()=>A(null,null,function*(){if(localStorage.getItem("token")&&(null==l?void 0:l.id))try{const e=yield rw({name:o},l.id);e&&e.data.status&&(s(),c(S(C({},l),{name:o})),t())}catch(e){}}),u=()=>{t()},h=()=>a?F.jsx(gw,{props:{value:o||"",onChange:e=>{r(e)},minRows:3,maxRows:3,maxLength:150,placeholder:i.t("Project Name")}}):F.jsx(_i,{value:o,onChange:e=>{r(e)},maxLength:150,placeholder:i.t("Project Name"),className:"project-new-name-edit-input"});return a?F.jsx(Ti,{open:e,title:i.t("Edit Project Name"),heightType:"auto",onClose:t,size:"large",className:"mobile-project-name-popup",children:F.jsx("div",{className:"qwen-chat-comp-project-name-popup",children:F.jsxs("div",{className:"qwen-chat-comp-project-name-popup-content",children:[h(),F.jsx("div",{className:"qwen-chat-comp-project-name-popup-footer",children:F.jsx(xi,{type:"brandprimary",size:"large",rounded:"circle",className:"qwen-chat-comp-project-name-popup-footer-btn",onClick:d,disabled:!o.trim()||o===n,children:i.t("Save")})})]})})}):F.jsxs(wi,{size:"small",visible:e,className:"qwen-chat-comp-project-name-modal",title:i.t("Edit Project Name"),headerBorderNone:!0,onCancel:u,onOk:d,footer:!1,children:[h(),F.jsxs("div",{className:"qwen-chat-comp-project-name-modal-footer",children:[F.jsx(xi,{type:"ghost",rounded:"circle",className:"qwen-chat-comp-project-name-modal-footer-btn",onClick:u,children:i.t("Cancel")}),F.jsx(xi,{type:"brandprimary",rounded:"circle",className:"qwen-chat-comp-project-name-modal-footer-btn",onClick:d,disabled:!o.trim()||o===n,children:i.t("Save")})]})]})},jw=["icon-line-folder-01","icon-line-Investing","icon-line-lightbulb-03","icon-image-icon","icon-line-video-01","icon-line-audio","icon-line-star-02","icon-line-rename-01","icon-line-Travel","icon-line-globe-07","icon-line-deepresearch-02","icon-line-Wallet","icon-line-like-unselected","icon-line-Exercise","icon-line-Food-02","icon-line-coffee","icon-line-markdown","icon-line-Plants","icon-line-cat","icon-line-dog","icon-line-Transportation-02","icon-line-book-02","icon-line-Vacation","icon-line-calendar","icon-line-computer","icon-line-Volume","icon-line-Data","icon-line-email-01"],Tw=["character-primary-text","red-500","yellow-400","green-600","blue-500","violet-500","electricviolet-500"],Ew=({icon:e=jw[0],style:t=Tw[0],onIconChange:n=()=>{},onIconClose:s=()=>{}})=>{const{t:i}=ye(),a=cR(e=>e.mobile),[o,r]=D.useState(()=>e.startsWith("icon-")||!e?"icon":"emoji"),[l,c]=D.useState(e),[d,u]=D.useState(Tw.find(e=>e===t)||Tw[0]);D.useEffect(()=>{c(e),u(Tw.find(e=>e===t)||Tw[0]),r(e.startsWith("icon-")||!e?"icon":"emoji")},[e,t]);const h=e=>{const t={icon:e,style:d};t.style="emoji"===o?"":d,c(e),u(t.style),n(t)};return F.jsxs("div",{className:"project-icon-picker",children:[F.jsxs("div",{className:"project-icon-picker-tab",children:[[{key:"icon",label:"Icon"},{key:"emoji",label:"Emoji"}].map(e=>F.jsx("div",{className:"project-icon-picker-tab-item "+(e.key===o?"active":""),onClick:()=>(e=>{r(e)})(e.key),children:i(e.label)},e.key)),a&&F.jsx("div",{className:"project-icon-picker-close",onClick:s,children:F.jsx(pi,{type:"icon-line-x-01",className:"project-icon-picker-close-icon"})})]}),a&&F.jsx("div",{className:"project-icon-picker-icon",children:l.startsWith("icon-")?F.jsx(pi,{type:l,className:`${d} `}):l||F.jsx(pi,{type:"icon-line-folder-01",className:"character-primary-text"})}),F.jsx("div",{className:"project-icon-picker-icons",children:"icon"===o?F.jsx(F.Fragment,{children:jw.map(e=>F.jsx("div",{className:`project-icon-picker-icons-item ${a?"":d} ${l===e?"active":""}`,onClick:()=>h(e),children:F.jsx(pi,{type:e})},e))}):"emoji"===o?F.jsx(F.Fragment,{children:(navigator.userAgent.includes("Windows")?mn:hn).map(e=>F.jsx("div",{className:"project-icon-picker-icons-item project-icon-picker-icons-emoji "+(l===e?"active":""),onClick:()=>h(e),children:e},e))}):null}),"icon"===o&&F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"project-icon-picker-divider"}),F.jsx("div",{className:"project-icon-picker-style icon",children:Tw.map(e=>F.jsx("div",{className:`project-icon-picker-style-color ${e} ${e===d?"active":""}`,onClick:()=>u(e),children:e===d&&F.jsx("div",{className:`project-icon-picker-style-color-circle ${e}`})},e))})]})]})},Nw=({data:e,setData:t,isProjectDetail:n})=>{const{t:s}=ye(),i=cR(e=>e.mobile),[a,o]=D.useState(!1),[r,l]=D.useState(""),[c,d]=D.useState({icon:"",style:""});D.useEffect(()=>{d(Eg(null==e?void 0:e.icon))},[null==e?void 0:e.icon]);const u=n=>{let s=`icon=${n.icon}`;if(n.style&&(s+=`&style=${n.style}`),!i)return t(S(C({},e),{icon:s})),d(Eg(s)),void o(!1);l(s)},h=()=>F.jsx("div",{className:"project-new-name-edit-icon-picker-popover",children:F.jsx(Ew,{icon:c.icon,style:c.style,onIconChange:u})}),m=()=>{var t;return F.jsx("div",{className:"project-new-name-edit-icon "+(n?"project-new-name-edit-project":""),onClick:()=>{o(!0)},children:!(null==e?void 0:e.icon)||(null==(t=c.icon)?void 0:t.startsWith("icon-"))?F.jsx(pi,{type:c.icon||"icon-line-plus-01",className:`project-new-name-edit-icon-default ${c.style}`}):F.jsx("div",{className:"project-new-name-edit-emoji",children:pn[c.icon]})})};return i?F.jsxs(F.Fragment,{children:[F.jsx(Ti,{open:a,onClose:()=>{o(!1)},push:!1,heightType:"full",className:"project-new-name-edit-icon-mobile-container",children:F.jsxs("div",{className:"project-new-name-edit-icon-mobile",children:[F.jsx(Ew,{icon:c.icon,style:c.style,onIconChange:u,onIconClose:()=>{o(!1)}}),F.jsx(xi,{type:"brandprimary",rounded:"circle",buttonClass:"project-new-name-edit-icon-done",size:"large",onClick:()=>{t(S(C({},e),{icon:r})),d(Eg(r)),o(!1)},children:s("Done")})]})}),m()]}):F.jsx(le,{open:a,arrow:!1,onOpenChange:e=>o(e),content:h,trigger:["click"],placement:"bottomLeft",classNames:{root:"project-icon-trigger-popover-shell "},children:m()})},Iw=({projectTitle:e,projectIns:t})=>{const n=pw(e=>e.projectInfo),s=pw(e=>e.projectChats),i=pw(e=>e.setInstructionValue),a=ye(),o=cR(e=>e.mobile),[r,l]=D.useState(!1),[c,d]=D.useState(!1),[u,h]=D.useState(!1),m=pw(e=>e.setProjectInfo),{getNewProjectList:p}=ig();return F.jsxs("div",{className:"project-title "+(o&&s.length<1?"project-title-full-center":""),children:[F.jsxs("div",{className:"project-title-left",children:[F.jsx(Nw,{data:n,setData:e=>A(null,null,function*(){const t=yield rw({icon:e.icon},n.id);t&&t.data.status&&(p(),m(S(C({},n),{icon:e.icon})))}),isProjectDetail:!0}),F.jsx("div",{className:"project-title-text",onClick:()=>{l(!r)},children:e})]}),F.jsxs("div",{className:"project-title-right",children:[((null==n?void 0:n.fileLength)||0)>0&&F.jsx(Si,{title:a.t("{{count}} Files",{count:(null==n?void 0:n.fileLength)||0}),children:F.jsxs("button",{className:"project-title-button",style:o?{}:{transform:(null==t?void 0:t.length)>0?"translateX(10px)":""},onClick:()=>{h(!u)},children:[F.jsx(pi,{type:"icon-line-file-02",className:"project-title-action-icon"}),o?a.t("{{count}} Files",{count:(null==n?void 0:n.fileLength)||0}):""]})}),t&&(null==t?void 0:t.length)>0&&F.jsx(Si,{title:a.t("Projects Instructions"),children:F.jsxs("button",{className:"project-title-button",onClick:()=>{d(!c),i(n.custom_instruction)},children:[F.jsx(pi,{type:"icon-line-customize",className:"project-title-action-icon"}),o?a.t("Projects Instructions"):""]})})]}),o&&s.length<1&&F.jsxs("div",{className:"project-placeholder",children:[F.jsx(pi,{type:"icon-line-package-empty",className:"project-placeholder-icon"}),F.jsx("div",{className:"project-placeholder-text",children:a.t("All project-related chats will be displayed here.")})]}),c&&F.jsx(fw,{showProjectChatInsModal:c,onCloseModal:()=>{d(!1)},inputValue:t}),u&&F.jsx(Sw,{projectId:n.id,showProjectChatFileModal:u,onCloseModal:()=>{h(!1)}}),r&&F.jsx(kw,{showEditProjectNameModal:r,onCloseModal:()=>{l(!1)},projectTitle:e})]})},Aw=D.memo(({scrollDownBtnVisible:e,onScrollDown:t,onScrollTop:n})=>F.jsx("div",{className:"chat-message-input-fixed",style:e?void 0:{opacity:0,pointerEvents:"none",display:"none"},children:F.jsx("div",{className:"chat-message-input-fixed-container",id:"message-input-container",children:F.jsx("div",{className:"scroll-down-button",onClick:e?t:n,children:F.jsx(pi,{type:"icon-line-arrow-down",className:"scroll-down-button-icon "+(e?"":"up-button-icon")})})})})),Mw=D.forwardRef(({uploadHandler:e=()=>{}},t)=>{const n=cR(e=>e.mobile),s=D.useRef(null),i=D.useRef(null),a=t=>{var n,s;const a=[];t.forEach(e=>{const t=Hr(e);a.push(...t)}),null==(n=i.current)||n.updateOptions({acceptedTypes:a,capture:t.includes(Xt.CAMERA)?"environment":void 0,callBack:n=>{e({files:n,type:t})}}),null==(s=i.current)||s.triggerUpload()};return D.useImperativeHandle(t,()=>({onClickUpload:a})),D.useEffect(()=>{s.current&&(i.current=new xw(s.current))},[]),F.jsx("input",{type:"file",id:"filesUpload",ref:s,multiple:!n,style:{display:"none"}})}),Rw=D.memo(Mw),Pw=({value:e,onChange:t,offset:n,disabled:s=!1})=>{const[i,a]=D.useState(!1),o=cR(e=>e.mobile),r=D.useMemo(()=>o?i?"icon-fill-triangle-up":"icon-fill-triangle-down":i?"icon-line-chevron-up":"icon-line-chevron-down",[o,i]);return F.jsx(ce,{theme:{token:{colorPrimary:"#615CED",controlItemBgActive:"#E1E1FE",borderRadiusLG:12,borderRadiusSM:12}},children:F.jsx(Ci,{open:i,disabled:s,overlayClassName:"size-selector-popup",onOpenChange:e=>{a(e)},placement:"bottomLeft",trigger:["click"],menu:{items:(l=e[0],[{label:"1:1",key:"1:1",icon:F.jsx(pi,{type:"icon-line-size-11-01"}),extra:"1:1"===l?F.jsx(pi,{type:"icon-line-check-02",className:"ratio-active-icon"}):void 0},{label:"3:4",key:"3:4",icon:F.jsx(pi,{type:"icon-line-size-34-01"}),extra:"3:4"===l?F.jsx(pi,{type:"icon-line-check-02",className:"ratio-active-icon"}):void 0},{label:"4:3",key:"4:3",icon:F.jsx(pi,{type:"icon-line-size-43-01"}),extra:"4:3"===l?F.jsx(pi,{type:"icon-line-check-02",className:"ratio-active-icon"}):void 0},{label:"16:9",key:"16:9",icon:F.jsx(pi,{type:"icon-line-size-169-01"}),extra:"16:9"===l?F.jsx(pi,{type:"icon-line-check-02",className:"ratio-active-icon"}):void 0},{label:"9:16",key:"9:16",icon:F.jsx(pi,{type:"icon-line-size-916-01"}),extra:"9:16"===l?F.jsx(pi,{type:"icon-line-check-02",className:"ratio-active-icon"}):void 0}]),selectable:!0,onSelect:e=>{t(e.key),pl("selectImageScale",{params:{et:"CLK",c4:e.key}})},selectedKeys:e},align:n?{offset:n}:void 0,children:F.jsxs(de,{className:Q("selector-text",{"selector-text-disabled":s}),size:o?0:4,children:[e[0],F.jsx(pi,{type:r,className:"selector-icon"})]})})});var l},Lw=()=>{const e=Kh(e=>e.visionSize),t=Kh(e=>e.setVisionSize),n=cR(e=>e.mobile);return F.jsx("div",{className:Q("size-selector"),children:F.jsx(Pw,{value:[e],onChange:t,offset:n?[-25,10]:[-35,20]})})},Ow=()=>{const{i18n:e}=ye(),t=Ue(),[n,s]=D.useState(!1),i=Jh(e=>e.mcpSettingList),a=D.useMemo(()=>i.filter(e=>e.enabled).length,[i]),o=D.useMemo(()=>({items:[{key:"mcpEnabledList",label:F.jsxs(F.Fragment,{children:[F.jsxs("div",{className:"mcp-button-menu-title",onClick:e=>e.stopPropagation(),onMouseEnter:e=>e.stopPropagation(),children:[e.t("Enabled MCP · {{number}}",{number:a}),F.jsx(pi,{type:"icon-line-settings",onClick:()=>{t("/settings/mcp")}})]}),F.jsx("div",{className:"mcp-button-menu-list",onClick:e=>e.stopPropagation(),children:i.filter(e=>e.enabled).map(t=>{let n="";switch(t.connectionStatus){case"available":n=e.t("MCP available");break;case"connecting":n=e.t("Connecting to the MCP server: Once connected, it can be used in chat.");break;case"failed":n=e.t("Connection to the MCP server failed: It is not available for use in chat.");break;default:n=""}return F.jsxs("div",{className:"mcp-button-menu-item-wrapper",children:[F.jsxs("div",{className:"mcp-button-menu-item",children:[F.jsx("div",{className:"mcp-button-menu-item-header",children:F.jsx("div",{className:"mcp-button-menu-item-header-name",children:t.name})}),F.jsx("div",{className:"mcp-button-menu-item-content",children:e.t(t.description)})]}),F.jsx(Si,{title:n,children:F.jsx("div",{className:Q("mcp-button-menu-item-header-status",{[t.connectionStatus]:!0})})})]},t.id)})})]})}]}),[a,e,i,t]);return a<=0?null:F.jsx("div",{id:"mcp-button",className:"mcp-button",children:F.jsx("div",{onClick:e=>{e.stopPropagation()},children:F.jsx(Ci,{open:n,onOpenChange:s,rootClassName:"mcp-button-dropdown",menu:o,trigger:["click"],placement:"bottom",children:F.jsxs("div",{className:"mcp-button-num",children:[F.jsx("div",{children:e.t("{{number}} tools",{number:a})}),F.jsx(pi,{type:n?"icon-line-chevron-down":"icon-line-chevron-up"})]})})})})},Dw={thinking:"thinking",search:"search",deep_research:"deep_research_deep_research",t2i:"t2i",t2v:"t2v",artifacts_deploy_artifacts:"artifacts_deploy_artifacts",artifacts_deploy_web_dev:"artifacts_deploy_web_dev",artifacts_deploy_deep_research:"artifacts_deploy_deep_research",audio_chat_audio_only:"audio_chat_AudioOnly",audio_chat_audio_and_video:"audio_chat_AudioAndVideo",deep_research_aipodcast:"deep_research_aipodcast",image_edit:"image_edit",deep_research_advanced:"deep_research_deep_research_advanced"},Fw=()=>{const{i18n:e}=ye(),t=cR(e=>e.mobile),n=Fd(e=>e.subscriptionPlus),{updateEquityHandlerByMessage:s}=bp(),[i,a]=D.useState(()=>{const e={},t=Bd.getState();for(const[n,s]of Object.entries(Dw))e[n]=t.getFeatureEquity(s);return e}),o=D.useMemo(()=>[...dn,{key:yt.Thinking,value:"Think"}],[]);D.useEffect(()=>{const e=Bd.subscribe(e=>{const t={};for(const[n,s]of Object.entries(Dw))t[n]=e.getFeatureEquity(s);a(t)});return()=>{e()}},[]);const r=D.useCallback(e=>{if(null===(null==e?void 0:e.remains)||0===(null==e?void 0:e.remains)){if(t){const t=O.createElement(yp,{equity:e,onUpdate:s});vi.openOnce({type:"warning",content:t,closable:n})}return!1}return!0},[t,n,s]),l=D.useCallback(e=>{let t=e;if(e===yt.DeepResearch&&(t="deep_research_deep_research"),cn.includes(t)){const e=Bd.getState().getFeatureEquity(t);return r(e)}return!0},[r]),c=D.useCallback(t=>{var n;const s={disabled:!1,msg:""};let i=t;if(t===yt.DeepResearch&&(i="deep_research_deep_research"),cn.includes(i)){const a=Bd.getState().getFeatureEquity(i);if(-1===a.remains)return s;const r=null==(n=o.find(e=>e.key===t))?void 0:n.value,l=du({remains:null==a?void 0:a.remains,unit:null==a?void 0:a.unit,capability:r,currentI18n:e,allowHtml:!0});return{disabled:0===(null==a?void 0:a.remains),msg:l}}return s},[o,e]);return{qThinkingEquity:i.thinking,qSearchEquity:i.search,qDeepResearchEquity:i.deep_research,qT2IEquity:i.t2i,qT2VEquity:i.t2v,qArtifactsDeployArtifacts:i.artifacts_deploy_artifacts,qArtifactsDeployWebDev:i.artifacts_deploy_web_dev,qArtifactsDeployDeepResearch:i.artifacts_deploy_deep_research,qAudioChatAudioOnly:i.audio_chat_audio_only,qAudioChatAudioAndVideo:i.audio_chat_audio_and_video,qDeepResearchAipodcast:i.deep_research_aipodcast,qImageEditEquity:i.image_edit,qDeepResearchAdvanced:i.deep_research_advanced,checkEquityPassByEquity:r,checkEquityPassByInputFeatureType:l,getEquityResultByInputFeatureType:c}},qw=({disabled:e=!1})=>{const t=ye(),[n,s]=D.useState(!1),i=cR(e=>e.mobile),a=Rs(e=>e.researchMode),o=Rs(e=>e.setResearchMode),r=Kh(e=>e.messageInputPermissions),{qDeepResearchAdvanced:l,checkEquityPassByEquity:c}=Fw(),d=D.useMemo(()=>null===(null==l?void 0:l.remains)||0===(null==l?void 0:l.remains),[l]),u=D.useMemo(()=>[{key:"advance",extra:t.t(r.enableAdvanced.msg||"Devoting extra time to a deeper analysis"),label:t.t("Advanced"),icon:i?null:F.jsx(pi,{type:"icon-line-advanced-02"})},{key:"normal",extra:t.t("Fast, reliable responses for quick tasks."),label:t.t("Normal"),icon:i?null:F.jsx(pi,{type:"icon-line-size-34-01"})}],[t,r.enableAdvanced.msg,i]),h=D.useCallback(e=>{c(l)&&!d&&e&&o(e)},[c,l,d,o]),m=D.useCallback(e=>{const{key:t,icon:n,label:s="",extra:i=""}=e;return{key:t,disabled:"advance"===t&&d,label:F.jsxs("div",{className:"advanced-dropdown-item",children:[n,F.jsxs("div",{className:"advanced-dropdown-content",children:[F.jsx("span",{className:"advanced-dropdown-content-label",children:s}),F.jsx("span",{className:"advanced-dropdown-content-description",children:i})]}),a===t&&F.jsx(pi,{type:"icon-line-check-02",className:"advanced-dropdown-item-checked"})]}),onClick:()=>{h(t)}}},[h,a,d]),p=D.useMemo(()=>{var e;return null==(e=u.find(e=>(null==e?void 0:e.key)===a))?void 0:e.label},[u,a]),g=D.useMemo(()=>i?n?"icon-fill-triangle-up":"icon-fill-triangle-down":n?"icon-line-chevron-up":"icon-line-chevron-down",[i,n]);return F.jsx(Ci,{open:n,onOpenChange:e?()=>{}:s,placement:i?"topCenter":"bottomLeft",trigger:["click"],menu:{items:u.map(m)},rootClassName:"advanced-dropdown",children:F.jsxs("div",{className:Q("advanced",{"advanced-disabled":e}),children:[p,F.jsx(pi,{type:g,className:"advanced-icon"})]})})};const Uw=O.memo(e=>{const{open:t=!1,hasNoTrueValues:n,hasTrueValues:s,onAllCheck:i=()=>{},modeItems:a=[],onClickUpload:o=()=>{},onClose:r=()=>{},ononExitMode:l=()=>{},onChangeItem:c=()=>{}}=e,{i18n:d}=ye(),[u,h]=D.useState(!1),m=js(e=>e.currentInputSubType),p=Rs(e=>e.thinkingMode),{checkEquityPassByInputFeatureType:g}=Fw(),f=D.useMemo(()=>{var e,t;if(!Array.isArray(a)||!a.length||a.every(({chatType:e})=>!e))return 204;const n=null!=(t=null==(e=document.body)?void 0:e.clientHeight)?t:window.innerHeight;return u?.94*n:458},[u,a]),v=D.useCallback(()=>{h(!0)},[]);!function(e,t,n={}){const{threshold:s=50,maxTime:i=500,preventDefault:a=!1,isFull:o=!1}=n,r=D.useRef(t),l=D.useRef({threshold:s,maxTime:i,preventDefault:a,isFull:o});D.useEffect(()=>{r.current=t,l.current={threshold:s,maxTime:i,preventDefault:a,isFull:o}},[t,s,i,a,o]);const c=D.useRef(null),d=D.useRef(null),u=D.useCallback(e=>{1===e.touches.length&&(c.current=e.touches[0].pageY,d.current=Date.now())},[]),h=D.useCallback(e=>{if(l.current.preventDefault){if(l.current.isFull)return;e.preventDefault()}},[]),m=D.useCallback(e=>{if(!c.current||1!==e.changedTouches.length)return;const t=e.changedTouches[0].pageY,n=c.current-t,s=Date.now()-(d.current||0),{threshold:i,maxTime:a}=l.current;n>i&&s{let t=null;if(e&&"current"in e?t=e.current:e instanceof HTMLElement&&(t=e),t)return t.addEventListener("touchstart",u,{passive:!0}),t.addEventListener("touchmove",h,{passive:!1}),t.addEventListener("touchend",m,{passive:!0}),()=>{null==t||t.removeEventListener("touchstart",u),null==t||t.removeEventListener("touchmove",h),null==t||t.removeEventListener("touchend",m)}},[e,u,h,m])}(document.body,v,{threshold:60,maxTime:400,preventDefault:t&&!u,isFull:u});const{disabled:y,enabled:b,supportThinkingModes:x,onThinkingChange:w}=tp(),{isImageDisabled:_,isDocumentDisabled:C,isAudioDisabled:S,isVideoDisabled:k}=Xm(),j=D.useCallback(e=>{("Thinking"!==e||g(yt.Thinking))&&w(e)},[g,w]),T=D.useMemo(()=>[{icon:"icon-line-camera-01",disabled:_,key:[Xt.CAMERA]},{icon:"icon-line-image-011",disabled:_,key:[Xt.IMAGE]},{icon:"icon-line-video-01",disabled:k,key:[Xt.VIDEO]},{icon:"icon-line-file-02",disabled:C&&S,key:[...C?[]:[Xt.DOC],...S?[]:[Xt.AUDIO]]}],[_,C,S,k]),E=D.useMemo(()=>x.map(e=>({label:d.t(e.replace("ing","")),value:e})),[d,x]),N=D.useCallback(({icon:e,key:t,disabled:n})=>F.jsx("div",{onClick:()=>{n||o([...t])},className:Q("mode-selector-drawer-control-item",{"mode-selector-drawer-control-item-disabled":n}),children:F.jsx(pi,{type:e,className:"mode-selector-drawer-control-item-icon"})},e),[o]),I=D.useMemo(()=>b&&void 0!==p?F.jsxs("div",{className:Q("mode-selector-drawer-item",{"mode-selector-drawer-item-disabled":y}),children:[F.jsxs(ie,{align:"center",gap:8,children:[F.jsx(pi,{className:"mode-selector-drawer-item-icon",type:"icon-line-deepthink-01"}),F.jsx("div",{className:"mode-selector-drawer-item-title",children:d.t("Thinking")})]}),F.jsx(ki,{className:"mode-selector-drawer-item-select",popupClassName:"mode-selector-drawer-item-select-popup",options:E,value:p,labelRender:({label:e})=>F.jsxs("div",{className:"mode-selector-drawer-item-select-label",children:[F.jsx("div",{children:e}),F.jsx(pi,{type:"icon-line-sort-vertical-01"})]}),transitionName:"",animation:"",onChange:j})]}):null,[y,b,d,j,E,p]),A=D.useMemo(()=>[{label:d.t("Enable All"),value:d.t("Enable All"),desTitle:d.t("Enable All Tools"),des:d.t("Agent Mode: Equipped with web search, code interpreter, and other tools for advanced problem-solving."),checked:s,key:"all-tools"},{label:d.t("Disable All"),value:d.t("Disable All"),desTitle:d.t("Disable All Tools"),des:d.t("Chat Mode: Direct conversation, no external tools."),checked:n,key:"disable-all-tools"}],[d,n,s]),M=D.useMemo(()=>{let e="";return e=n?d.t("Disable All"):s?d.t("Enable All"):"",e},[d,n,s]),R=D.useMemo(()=>F.jsxs("div",{className:Q("mode-selector-drawer-item"),children:[F.jsxs(ie,{align:"center",gap:8,children:[F.jsx(pi,{className:"mode-selector-drawer-item-icon",type:"icon-line-toolCalling"}),F.jsx("div",{className:"mode-selector-drawer-item-title",children:d.t("Tools")})]}),F.jsx(Hi,{size:"small",checked:!n,onChange:i})]}),[y,d,M,n,j,i,A]),P=D.useCallback(e=>{if(!e)return null;const t=m===yt.DeepThinking&&e===yt.DeepResearch;return m===e||t?F.jsx(pi,{className:"mode-selector-drawer-list-item-check",type:"icon-line-check-02"}):void 0},[m]),L=D.useCallback(e=>{const{value:t="",icon:n="",key:s,childrens:i,disabledInfo:a,chatType:o,subChatType:u}=e;if(null==i?void 0:i.length)return i.map(L);if(!o)return null;const h=null==a?void 0:a.disabled,p=(null==a?void 0:a.msg)||"";return F.jsxs("div",{onClick:()=>{if(h){if(!g(u||o))return;vi.openOnce({type:"message",content:p,closable:!1})}else r(),m===u?l():c(e)},className:Q("mode-selector-drawer-list-item",{"mode-selector-drawer-list-item-disabled":h}),children:[F.jsx(pi,{className:"mode-selector-drawer-list-item-icon",type:n}),F.jsx("div",{className:"mode-selector-drawer-list-item-title",children:d.t(t)}),P(u)]},s)},[d,m,g,r,c,P]);return F.jsxs(ee,{rootClassName:"mode-selector-drawer",className:"mode-selector-drawer-container",placement:"bottom",open:t,height:f,onClose:e=>{e.stopPropagation(),r(),h(!1)},children:[F.jsx(pi,{type:"icon-close-4",onClick:()=>{r(),h(!1)},className:"mode-selector-drawer-close"}),F.jsx("div",{className:"mode-selector-drawer-title",children:d.t("Upload")}),F.jsxs("div",{onScroll:e=>{0{const{open:t,onOk:n,onCancel:s}=e,{i18n:i}=ye();return F.jsx(wi,{className:"mcp-first-time-guide-modal",visible:t,width:700,header:!1,footer:!1,children:F.jsxs("div",{className:"mcp-first-time-guide-modal-content",children:[F.jsx("div",{className:"mcp-first-time-guide-modal-content-close",onClick:s,children:F.jsx(pi,{type:"icon-close-4"})}),F.jsxs("div",{className:"mcp-first-time-guide-modal-content-inner",children:[F.jsxs("div",{className:"mcp-first-time-guide-modal-content-inner-left",children:[F.jsxs("div",{className:"mcp-first-time-guide-modal-content-inner-left-header",children:[F.jsx("div",{className:"mcp-first-time-guide-modal-content-inner-left-header-title",children:i.t("MCP: Limitless AI")}),F.jsx("div",{className:"mcp-first-time-guide-modal-content-inner-left-header-desc",children:i.t('The Model Context Protocol (MCP), introduced by Anthropic, is an open-source standard designed to facilitate the integration of large language models (LLMs) with external data sources and tools. MCP provides a unified interface, allowing AI models to connect with external data (e.g., files, databases, APIs) and integrate various functionalities more effectively. Described as a "universal plug," MCP enables consistent context sharing between AI systems and external environments, enhancing the flexibility and utility of AI applications. In essence, MCP acts like a "super network cable" for AI, enabling seamless external connectivity.')})]}),F.jsx("div",{className:"mcp-first-time-guide-modal-content-inner-left-button",children:F.jsx(xi,{type:"brandprimary",iconFontType:"icon-line-arrow-down-right-sm",onClick:n,children:i.t("Set up MCP to start")})})]}),F.jsx("div",{className:"mcp-first-time-guide-modal-content-inner-right",children:F.jsx("img",{src:"//assets.alicdn.com/g/qwenweb/qwen-chat-fe/0.2.67/static/images/mcp-intro.png",alt:""})})]})]})})},Bw=e=>{const{open:t,onOk:n,onCancel:s}=e,{i18n:i}=ye();return F.jsx(wi,{className:"no-mcp-available-modal",visible:t,width:480,header:!1,footer:!1,children:F.jsxs("div",{className:"no-mcp-available-modal-content",children:[F.jsx("div",{className:"no-mcp-available-modal-content-close",onClick:s,children:F.jsx(pi,{type:"icon-close-4"})}),F.jsxs("div",{className:"no-mcp-available-modal-content-inner",children:[F.jsx("div",{className:"no-mcp-available-modal-content-inner-header",children:i.t("No MCP available")}),F.jsx("div",{className:"no-mcp-available-modal-content-inner-desc",children:i.t("No MCP is available, please go to Settings to enable it.")}),F.jsxs("div",{className:"no-mcp-available-modal-content-inner-button",children:[F.jsx(xi,{type:"brandprimary",shape:"circle",onClick:n,children:i.t("MCP Settings")}),F.jsx(xi,{type:"textonly",shape:"circle",onClick:s,children:i.t("Not use for now")})]})]})]})})},zw=()=>{const{i18n:e}=ye(),t=Jh(e=>{var t;return null==(t=e.settings)?void 0:t.memory}),n=Jh(e=>e.setSettings),s=Jh(e=>e.settingsToolsDefaultConfig),i=Jh(e=>e.getSettingConfig),a=Jh(e=>e.settings.tools_enabled),o=Jh(e=>e.updateQwenChatSettings),r=ud(e=>e.setShowMemorySavedModal),l=cR(e=>{var t;return null==(t=e.config)?void 0:t.memory_version}),c=Ue(),d=cR(e=>{var t;return null==(t=e.config)?void 0:t.personalization_control}),u=!(!l||"disable"===l),[h,m]=D.useState(!1),[p,g]=D.useState(!1),f=cR(e=>e.setCookieSettingModelsVisible),[v,y]=D.useState(!1),b=D.useCallback(()=>{y(!1)},[]),x=D.useCallback(()=>{c("/settings/personalization/memory")},[c]),w=D.useCallback(()=>{c("/settings/personalization/custom-instr")},[c]),[_,S]=D.useState(!0),k=D.useMemo(()=>{if(!s)return{};const e={};return Object.keys(s).forEach(t=>{const n=s[t];e[t]=void 0!==(null==a?void 0:a[t])?null==a?void 0:a[t]:n.enabled_by_default}),e},[s,a]),j=D.useMemo(()=>!Object.values(k).includes(!0),[k]),T=D.useMemo(()=>!Object.values(k).includes(!1),[k]),E=D.useCallback((e,t)=>{const n=C({},k);n[e]=t,o({tools_enabled:n})},[_,k,o]),N=D.useMemo(()=>{return t=E,n=k,(e=s)?Object.keys(e).map(s=>({id:s,title:e[s].label,desc:e[s].description,open:n[s],onChange:e=>{t(s,e)}})):[];var e,t,n},[E,s,k]),I=D.useCallback(e=>{const t=C({},k);Object.keys(t).forEach(n=>{t[n]=e}),o({tools_enabled:t})},[k]);return D.useEffect(()=>{i()},[e.language]),{i18n:e,memory:t,personalization_control:d,showMemory:u,loadingMemory:h,loadingHistoryMemory:p,showCustomInstruction:v,advancedList:N,showAdvanced:_,hasNoTrueValues:j,hasTrueValues:T,onOpenCustomInstruction:()=>{y(!0)},onCloseCustomInstruction:b,onClickManage:()=>A(null,null,function*(){r(!0)}),onChangeMemory:e=>A(null,null,function*(){m(!0),g(!0),yield n({memory:{enable_memory:e,enable_history_memory:e}}),m(!1),g(!1)}),onChangeHistoryMemory:e=>A(null,null,function*(){g(!0),yield n({memory:{enable_history_memory:e}}),g(!1)}),onOpenCookiesSettings:()=>{f(!0)},onMemoryManage:x,onCustomInstr:w,setShowAdvanced:S,onAllCheck:I}},Gw=e=>{var t,n,s,i;const{uploadGroupRef:a,onUpdateSeparationNeeds:o=()=>{}}=e||{},{i18n:r}=ye(),l=cR(e=>e.config),c=Kh(e=>e.setShowDetail),d=Kh(e=>e.messageInputPermissions),u=Kh(e=>e.files),h=js(e=>e.currentInputFeature),m=Rs(e=>e.taskRunning),p=js(e=>e.history),g=Rs(e=>e.featureStatuses),{enabledMcpList:f,renderMcpModal:v,onChangeMCP:y}=(e=>{const{onUpdateSeparationNeeds:t=()=>{}}=e||{},n=Ue(),[s,i]=D.useState(!1),[a,o]=D.useState(!1),r=Pd(e=>e.user),l=Jh(e=>e.settings.mcp),c=Rs(e=>e.setMcpEnabled),d=Jh(e=>e.mcpSettingList),u=Jh(e=>e.settings.mcp_remind),h=Rs(e=>e.featureStatuses),m=D.useMemo(()=>{const e=h.find(e=>e.feature===Lh.Mcp),t=!e||e.status===Fh.Hidden,n=(null==e?void 0:e.status)===Fh.Disabled||(null==e?void 0:e.status)===Fh.NeedLogin||(null==e?void 0:e.status)===Fh.EquityExhausted||(null==e?void 0:e.status)===Fh.ComingSoon;return{enable:si()&&!t,disabled:n,msg:null==e?void 0:e.tooltip}},[h]),p=D.useMemo(()=>{const e=d.filter(e=>!e.type);return[...xr.getMCPServers(),...e].filter(e=>e.enabled)},[d]),g=D.useCallback(()=>{m.disabled||(0===p.length?u?i(!0):o(!0):xM.toggleFeature(Lh.Mcp,yt.Txt2Txt).success&&t({mcpEnabled:!0}))},[p.length,u,m.disabled,t]),f=D.useCallback(()=>{i(!1)},[]),v=D.useCallback(()=>{n("/settings/mcp"),f()},[n,f]),y=D.useCallback(()=>{o(!1)},[]),b=D.useCallback(()=>{n("/settings/mcp"),y()},[n,y]),x=D.useMemo(()=>F.jsxs(F.Fragment,{children:[F.jsx(Hw,{open:s,onOk:v,onCancel:f}),F.jsx(Bw,{open:a,onOk:b,onCancel:y})]}),[s,a,f,v,y,b]);return D.useEffect(()=>{r&&l&&m.enable&&wr()},[r,l,m.enable]),D.useEffect(()=>{p.length<=0&&c(!1)},[p,c]),{enabledMcpList:p,renderMcpModal:x,onChangeMCP:g}})({onUpdateSeparationNeeds:o}),{isImageDisabled:b,isDocumentDisabled:x,isAudioDisabled:w,isVideoDisabled:_}=Xm(),{hasNoTrueValues:S,hasTrueValues:k,onAllCheck:j}=zw(),T=D.useMemo(()=>{const e=g.find(e=>e.feature===Lh.Mcp),t=!e||e.status===Fh.Hidden,n=(null==e?void 0:e.status)===Fh.Disabled||(null==e?void 0:e.status)===Fh.NeedLogin||(null==e?void 0:e.status)===Fh.EquityExhausted||(null==e?void 0:e.status)===Fh.ComingSoon;return{enable:si()&&!t,disabled:n,msg:null==e?void 0:e.tooltip}},[g]),E=D.useMemo(()=>[{key:Xt.DOC,disabled:x,eventID:"clkUploadFileBtn",text:r.t("file")},{key:Xt.IMAGE,disabled:b,eventID:"clkUploadImgBtn",text:r.t("image")},{key:Xt.VIDEO,disabled:_,eventID:"clkUploadVideoBtn",text:r.t("video")},{key:Xt.AUDIO,disabled:w,eventID:"clkUploadAudioBtn",text:r.t("audio")}].filter(({disabled:e})=>!e),[r,x,b,_,w]),N=D.useCallback(e=>{pl("clkGenerateMode",{params:{et:"OTHER"},paramsExtend:{msg_type:e},aesParams:{c5:e}})},[]),I=D.useCallback(e=>{const{chatType:t,subChatType:n}=e;if(c(!0),[yt.ImageGeneration,yt.VideoGeneration].includes(t)){yt.ImageGeneration;Kh.getState().setVisionSize("16:9")}xM.toggleFeature(t,n).success,js.getState().setCurrentInputSubType(n||t),N(n||t),o({manualChooseMode:!0})},[c,N,o]),A=D.useMemo(()=>{var e;const t=null==(e=null==p?void 0:p.messages)?void 0:e[(null==p?void 0:p.currentId)||""],n=(null==t?void 0:t.chat_type)===yt.DeepResearch&&(null==t?void 0:t.sub_chat_type)===yt.DeepResearch,s=(null==t?void 0:t.chat_type)===yt.DeepResearch&&(null==t?void 0:t.sub_chat_type)===yt.INTERRUPT,i=(null==t?void 0:t.chat_type)===yt.Travel&&(null==t?void 0:t.sub_chat_type)===yt.TRAVEL_RESEARCH;return(n||s||i)&&m?{disabled:!0,msg:i?"":r.t("Deep Research in progress. Please wait.")}:{disabled:!1,msg:""}},[null==p?void 0:p.currentId,null==p?void 0:p.messages,r,m]),M=D.useCallback(()=>{if(null==A?void 0:A.disabled)return;o({manualChooseMode:!1}),h&&h!==yt.Txt2Txt&&xM.deselectFeature(h);Rs.getState().mcpEnabled&&(xM.deselectFeature(Lh.Mcp),Rs.getState().setMcpEnabled(!1)),xM.resetToTxt2Txt();const e=new URL(window.location.href);e.searchParams.delete("inputFeature"),window.history.replaceState({},"",e.toString())},[null==A?void 0:A.disabled,o,h]),R=D.useCallback(e=>{xM.toggleFeature(e).success},[]),P=D.useCallback((e,t)=>["upload","all-tools","disable-all-tools"].includes(e||"")?"upload"===e?t?r.t("Not available"):E.map(e=>e.text).join(","):"all-tools"===e?r.t("Agent Mode: Equipped with web search, code interpreter, and other tools for advanced problem-solving."):"disable-all-tools"===e?r.t("Chat Mode: Direct conversation, no external tools."):void 0:"",[r,E]),L=D.useCallback((e=[])=>{var t;null==(t=null==a?void 0:a.current)||t.onClickUpload((null==e?void 0:e.length)?e:E.map(e=>e.key)),pl("clkUploadBtn",{params:{et:"CLK"}})},[E,a]),O=D.useCallback(e=>{const{key:t,uploadType:n}=e;switch(bM.emit(Yu.MESSAGE_INPUT_TRIGGER_FOCUS),t){case"tools":break;case"all-tools":j(!0);break;case"disable-all-tools":j(!1);break;case"upload":L();break;case"mcp":y();break;default:return I(e),(null==n?void 0:n.length)&&L(n),!1}},[y,I,L,j]),q=D.useCallback(e=>{if("mcp"===e){const e=f.length?r.t("{{number}} tools",{number:null==f?void 0:f.length}):r.t("No tools");return T.msg||e}return""},[f.length,r,T.msg]),U=D.useCallback(e=>{var t,n,s,i;switch(e){case"upload":{const e=h===yt.ImageGeneration&&(null==u?void 0:u.length)>=((null==(s=null==(n=null==(t=null==l?void 0:l.features)?void 0:t.limits)?void 0:n.image_edit)?void 0:s.image_max_count)||1),a=!E.length;return(null==(i=d.enableUpload)?void 0:i.disabled)||e||a}case"mcp":return T.disabled;default:return!1}},[null==(s=null==(n=null==(t=null==l?void 0:l.features)?void 0:t.limits)?void 0:n.image_edit)?void 0:s.image_max_count,h,null==u?void 0:u.length,T.disabled,null==(i=d.enableUpload)?void 0:i.disabled,E.length]);return D.useEffect(()=>{bM.firstOn(Yu.MESSAGE_INPUT_RECOMMEND_WORDS_CLICK,({suggestItem:e,active:t})=>{t&&O(C({key:e.subChatType||e.chatType},e))})},[O]),{modeDisabledInfo:A,renderMcpModal:v,hasNoTrueValues:S,hasTrueValues:k,onChangeItem:O,onAllCheck:j,onExitMode:M,onFeatureCallback:R,onTooltipHandle:q,onDisabledHandle:U,generateDescription:P}},$w=D.memo(e=>{var t,n,s,i,a;const{messageInputMode:o,isPlanning:r,uploadHandler:l,onUpdateSeparationNeeds:c}=e,{i18n:d}=ye(),[u,h]=D.useState(!1),[m,p]=D.useState(!1),[g,f]=D.useState(!1),[v,y]=D.useState(!1),[b,x]=D.useState(document.body.clientHeight),w=Rs(e=>e.mcpEnabled),_=Rs(e=>e.featureStatuses),k=dR(e=>e.mobile),j=Kh(e=>e.files),T=Kh(e=>e.messageInputPermissions),E=js(e=>e.currentInputFeature),N=js(e=>e.currentInputSubType),I=D.useRef(null),{getEquityResultByInputFeatureType:A}=Fw(),M=D.useMemo(()=>{const e=_.find(e=>e.feature===Lh.Mcp),t=!e||e.status===Fh.Hidden;return si()&&!t},[_]),{modeDisabledInfo:R,renderMcpModal:P,hasNoTrueValues:L,hasTrueValues:O,onAllCheck:q,onChangeItem:U,onExitMode:H,onDisabledHandle:B,generateDescription:z,onTooltipHandle:G}=Gw({uploadGroupRef:I,onUpdateSeparationNeeds:c}),$=D.useMemo(()=>{const e=E===yt.Image2Video?yt.VideoGeneration:E,t=N===yt.Image2Video?yt.VideoGeneration:N;return Fu(dn,e,t,w)},[E,N,w]),W=D.useMemo(()=>{var e,t,n,s,i,a;if(null==R?void 0:R.disabled)return[dn[0]];const o=[],r=dn.map(e=>{if("mcp"===e.key){const t=_.find(e=>e.feature===Lh.Mcp);return S(C({},e),{disabledInfo:(null==t?void 0:t.disabledInfo)||{disabled:!1,msg:""}})}const t=e.subChatType||e.chatType,n=_.find(e=>e.feature===t);let s={disabled:!1,msg:""};return(null==n?void 0:n.disabledInfo)&&(s=null==n?void 0:n.disabledInfo),s.disabled||(s=A(t)),S(C({},e),{disabledInfo:s})});for(const[l,c]of r.entries()){if(!1===(null==(e=c.disabledInfo)?void 0:e.enable))continue;const r=c.subChatType||c.chatType;r&&!_.find(e=>e.feature===r)||(0!==l?"mcp"!==c.key?o.length>=7?(null==(n=o.at(-1))?void 0:n.childrens)?null==(a=null==(i=null==(s=o.at(-1))?void 0:s.childrens)?void 0:i.push)||a.call(i,c):o.push({icon:"icon-line-more-01",value:d.t("More"),childrens:[c]}):o.push(c):M&&o.push(c):(null==(t=null==T?void 0:T.enableUpload)?void 0:t.enable)?o.push(c,{isDivider:!0}):o.push(S(C({},c),{disabledInfo:{disabled:!0,msg:""}}),{isDivider:!0}))}return o.push({isDivider:!0}),o.push({key:"tools",icon:"icon-line-toolCalling",value:"Tools",disabledInfo:{disabled:!1,msg:"",rightRender:F.jsx("div",{style:{display:"flex",alignItems:"center"},onClick:e=>{e.stopPropagation()},children:F.jsx(Hi,{size:"small",checked:!L,onChange:q})})}}),o},[_,d,M,null==R?void 0:R.disabled,null==(t=null==T?void 0:T.enableUpload)?void 0:t.enable,L,A]),V=D.useCallback(e=>{var t,n;const{value:s="",icon:i="",isDivider:a,key:o,childrens:r,disabledInfo:l}=e;if(a)return{type:"divider",className:"mode-select-dropdown-divider"};const c=null!=(t=null==l?void 0:l.disabled)?t:B(o),u=null!=(n=null==l?void 0:l.msg)?n:G(o),h=z(o,c),m=null==l?void 0:l.checked,p=null==l?void 0:l.rightRender;return{key:o,className:"mode-select-common-item",popupOffset:b<=850?[0,6]:[0,-4],popupClassName:"mode-select-sub-popover-container",children:null==r?void 0:r.map(V),disabled:c,onClick:(null==r?void 0:r.length)?void 0:()=>U(e),expandIcon:F.jsx(pi,{type:"icon-line-chevron-right",className:"mode-select-common-item-expand"}),label:F.jsx(Si,{show:!!u,title:u?F.jsx("span",{dangerouslySetInnerHTML:{__html:u}}):"",placement:"right",children:F.jsxs("div",{className:"mode-select-dropdown-item-wrapper",children:[F.jsxs("div",{className:"mode-select-dropdown-item",style:h&&void 0!==m?{justifyContent:"space-between"}:{},children:[i&&F.jsx(pi,{type:i,className:"mode-select-dropdown-item-icon"}),h?F.jsxs("div",{className:"mode-select-dropdown-item-content",children:[F.jsx("span",{children:d.t(s)}),F.jsx("span",{className:Q("mode-select-dropdown-item-description",{"mode-select-dropdown-item-description-disabled":c}),children:h})]}):F.jsx("span",{children:d.t(s)}),void 0!==m&&F.jsx(pi,{type:"icon-line-check-021",className:Q("mode-select-dropdown-item-icon",{"mode-select-dropdown-item-icon-checked":m,"mode-select-dropdown-item-icon-unchecked":!m})})]}),p]})})}},[z,d,U,B,G,b]),K=D.useMemo(()=>{var e,t;return"combination"===o?null:F.jsxs("div",{className:"message-input-column-footer-submode",children:[(null==(e=null==T?void 0:T.enableSizeSelector)?void 0:e.enable)&&F.jsx(Lw,{}),w&&F.jsx(Ow,{}),(null==(t=null==T?void 0:T.enableAdvanced)?void 0:t.enable)&&F.jsx(qw,{disabled:R.disabled})]})},[w,o,null==(n=null==T?void 0:T.enableAdvanced)?void 0:n.enable,null==(s=null==T?void 0:T.enableDesignStyle)?void 0:s.enable,null==(i=null==T?void 0:T.enableSizeSelector)?void 0:i.enable,R.disabled]),Y=D.useMemo(()=>(null==R?void 0:R.disabled)?null:F.jsx(pi,{type:k?"icon-line-x-03":"icon-close-4",className:"mode-select-current-mode-close",onClick:H}),[k,null==R?void 0:R.disabled,H]),J=D.useMemo(()=>F.jsxs("div",{className:"mode-select-popover-content",children:[F.jsxs("div",{className:"mode-select-popover-header",children:[F.jsx("p",{className:"mode-select-popover-title",children:d.t("Add more details")}),F.jsx("div",{className:"mode-select-popover-close-box",onClick:()=>{h(!1)},children:F.jsx(pi,{type:"icon-close-4",className:"mode-select-popover-close-icon"})})]}),F.jsx("div",{className:"mode-select-popover-body",children:d.t("You can provide extra information for better results.")})]}),[d]),X=D.useMemo(()=>{if(!$||"combination"===o)return;const{icon:e="",value:t=""}=$,{disabled:n,msg:s}=R;return F.jsx(le,{classNames:{root:"mode-select-popover-container"},trigger:"click",placement:"top",autoAdjustOverflow:!0,content:J,open:u,onOpenChange:e=>{r&&(m?h(!1):(p(!0),h(e)))},children:F.jsx(Si,{show:!!s,title:s,placement:"top",children:F.jsxs("div",{className:Q("mode-select-current-mode",{"mode-select-current-mode-disabled":n}),children:[!k&&Y,F.jsx(pi,{type:e,className:"mode-select-current-mode-icon"}),k&&Y,!k&&F.jsx("span",{children:d.t(t)})]})})})},[$,m,d,r,o,k,R,u,Y,J]),Z=e=>{e&&e.style&&(e.style.opacity="1",e.style.cursor="pointer")},ee=D.useMemo(()=>k?F.jsxs("div",{className:"mode-select-open",onClick:()=>f(!0),ref:Z,style:{opacity:.4,cursor:"not-allowed"},children:[F.jsx("div",{id:`${Kp}_mode_select`,className:"mode-select-open-mode-select"}),F.jsx(pi,{type:"icon-line-plus-01"})]}):F.jsx(Ci,{rootClassName:"mode-select-dropdown",placement:"bottomLeft",menu:{items:W.map(V)},open:v,onOpenChange:y,children:F.jsxs("div",{className:Q("mode-select-open",{"mode-select-open-active":v}),style:{opacity:.4,cursor:"not-allowed"},ref:Z,children:[F.jsx("div",{id:`${Kp}_mode_select`,className:"mode-select-open-mode-select"}),F.jsx(pi,{type:"icon-line-plus-01"})]})}),[W,k,v,V]);return D.useEffect(()=>{(null==j?void 0:j.length)&&f(!1)},[null==j?void 0:j.length]),D.useEffect(()=>{const e=()=>{const e=window.innerHeight;x(e)};return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}},[]),F.jsxs("div",{className:"mode-select",children:[ee,X,K,F.jsx(Uw,{open:g,modeItems:W,onChangeItem:U,hasNoTrueValues:L,onAllCheck:q,hasTrueValues:O,onClose:()=>f(!1),ononExitMode:H,onClickUpload:null==(a=null==I?void 0:I.current)?void 0:a.onClickUpload}),F.jsx(Rw,{ref:I,uploadHandler:l}),P]})}),Ww=e=>{const{onClick:t=()=>{},type:n,className:s}=e;return F.jsx("div",{className:`icon-h5-ui ${s}`,onClick:t,children:F.jsx("svg",{className:"icon-svg","aria-hidden":"true",children:F.jsx("use",{xlinkHref:`#${n}`})})})},Vw=e=>{const{onClick:t=()=>{},type:n,className:s}=e;return F.jsx("div",{className:`icon-web-ui ${s}`,onClick:t,children:F.jsx("svg",{className:"icon-svg","aria-hidden":"true",children:F.jsx("use",{xlinkHref:`#${n}`})})})},Qw=e=>"h5"===e.env?F.jsx(Ww,C({},e)):"web"===e.env?F.jsx(Vw,C({},e)):null,Kw=e=>{var t=e,{rounded:n="round",popupClassName:s,selectorClassName:i,selectAntdRef:a}=t,o=k(t,["rounded","popupClassName","selectorClassName","selectAntdRef"]);const r=D.useRef(null),l=cR(e=>e.mobile);return D.useEffect(()=>{r.current&&a&&(a.current=r.current)},[null==a?void 0:a.current,r.current]),D.useEffect(()=>{r.current&&r.current.nativeElement&&(r.current.nativeElement.style.opacity="1",r.current.nativeElement.style.cursor="pointer")},[]),F.jsx(X,S(C({ref:r,suffixIcon:F.jsx(Qw,{type:"icon-line-chevron-down",className:"qwen-select-down-icon",env:l?"h5":"web"}),classNames:{popup:{root:`qwen-select-dropdown qwen-select-thinking-dropdown ${s}`},root:`qwen-select-thinking qwen-select-${n} ${i||""}`.trim()},optionRender:(e,t)=>{const n=e.data;return F.jsx(Si,{show:Boolean(n.tooltip),title:F.jsx("span",{dangerouslySetInnerHTML:{__html:n.tooltip||""}}),placement:"top",children:F.jsxs("div",{className:Q("qwen-select-option-selected-label-container",{"qwen-select-option-selected-label-container-disabled":n.disabled}),onClick:e=>{n.disabled&&e.stopPropagation()},children:[F.jsx("span",{className:"qwen-select-option-selected-label",children:e.label}),e.value===o.value||(null==t?void 0:t.value)===o.value?F.jsx(pi,{type:"icon-line-check-02",className:"qwen-select-option-selected-icon"}):null]})})}},o),{style:{opacity:.4,cursor:"not-allowed"}}))},Yw=[{label:"Auto",value:"Auto"},{label:"Think",value:"Thinking"},{label:"Fast",value:"Fast"}],Jw=({value:e,onChange:t,selectAntdRef:n,disabled:s,supportThinkingModes:i})=>{const{t:a,i18n:o}=ye(),r=D.useRef(null),[l,c]=D.useState(!1),d=cR(e=>e.mobile),{getEquityResultByInputFeatureType:u}=Fw(),h=D.useMemo(()=>{const{disabled:e,msg:t}=u(yt.Thinking);return Yw.filter(e=>i.includes(e.value)).map(n=>({label:o.t(n.label),value:n.value,disabled:"Thinking"===n.value&&e,tooltip:"Thinking"===n.value?t:""}))},[u,o.language,i]),m=D.useCallback(e=>{var t;const n=(null==(t=h.find(t=>t.value===e))?void 0:t.label)||e;return F.jsx(Si,{show:!1,title:a("Thinking mode switching is not supported under the current settings"),placement:"top",children:F.jsxs("div",{className:Q("qwen-select-thinking-label",{"qwen-select-thinking-label-disabled":s}),children:[F.jsx("span",{className:"qwen-select-thinking-label-text",children:n}),F.jsx(Qw,{env:d?"h5":"web",type:"icon-line-chevron-down",className:Q("qwen-select-thinking-label-icon",{"qwen-select-down-icon-rotate180":l})})]})})},[s,a,l,h]);return D.useEffect(()=>{r.current&&n&&(n.current=r.current)},[null==n?void 0:n.current,r.current]),F.jsx("div",{className:"qwen-thinking-selector",children:F.jsx(Kw,{selectAntdRef:r,listHeight:768,disabled:s,placement:"bottomLeft",rounded:"none",popupMatchSelectWidth:240,options:h,value:e,open:l,onChange:t,onOpenChange:c,labelRender:({value:e})=>m(String(e)),suffixIcon:null})})},Xw=()=>{const{tooltipText:e,disabled:t,enabled:n,thinkingMode:s,supportThinkingModes:i,onThinkingChange:a}=tp();return n&&void 0!==s?F.jsx(Si,{show:Boolean(e),title:e?F.jsx("span",{dangerouslySetInnerHTML:{__html:e}}):"",placement:"top",children:F.jsx(Jw,{value:s,onChange:a,disabled:t,supportThinkingModes:i})}):null},Zw=()=>{const{i18n:e}=ye(),t=D.useRef(null),n=dR(e=>e.mobile),s=Rs(e=>e.setWelcomeModalShow),i=Rs(e=>e.setOmniType),a=Pd(e=>e.user),o=ud(e=>e.omniButtonBackgroundImg),{qAudioChatAudioAndVideo:r,qAudioChatAudioOnly:l,checkEquityPassByEquity:c}=Fw(),d=D.useMemo(()=>null===(null==l?void 0:l.remains)||0===(null==l?void 0:l.remains),[l]),u=D.useMemo(()=>null===(null==r?void 0:r.remains)||0===(null==r?void 0:r.remains),[r]),h=D.useCallback(e=>{c("voice"===e?l:r)},[c,r,l]),m=D.useCallback(e=>{d&&"voice"===e||u&&"video"===e?n&&h(e):wR()?s(!0):(pl("speechVoiceChatStart",{params:{et:"CLK",c1:null==a?void 0:a.id}}),i(e))},[d,u,null==a?void 0:a.id,i,n,h,s]),p=D.useMemo(()=>n?null:wR()?e.t("{{capability}} is not supported in guest mode.",{capability:e.t("Use voice and video chat")}):e.t("Use voice and video chat"),[e,null==a?void 0:a.id]),g=D.useMemo(()=>n||wR()?"":-1!==(null==l?void 0:l.remains)?du({remains:(null==l?void 0:l.remains)||0,unit:null==l?void 0:l.unit,currentI18n:e,capability:e.t("Voice Chat"),allowHtml:!0}):"",[e,n,null==l?void 0:l.remains,null==l?void 0:l.unit]),f=D.useMemo(()=>n||wR()?"":-1!==(null==r?void 0:r.remains)?du({remains:(null==r?void 0:r.remains)||0,unit:null==r?void 0:r.unit,currentI18n:e,capability:e.t("Video Chat"),allowHtml:!0}):"",[e,n,null==r?void 0:r.remains,null==r?void 0:r.unit]),v=D.useMemo(()=>[{key:"voice",label:F.jsx(Si,{title:g?F.jsx("span",{dangerouslySetInnerHTML:{__html:g}}):"",placement:"bottom",children:F.jsxs("div",{className:"omni-button-drop-item "+(d?"omni-button-drop-item-disabled":""),onClick:()=>m("voice"),children:[F.jsx(pi,{type:"icon-line-voiceChat",className:"omni-button-drop-item-icon"}),F.jsx("div",{className:"omni-button-drop-item-label",children:e.t("Voice Chat")})]})})},{key:"video",label:F.jsx(Si,{title:f?F.jsx("span",{dangerouslySetInnerHTML:{__html:f}}):"",placement:"bottom",children:F.jsxs("div",{className:"omni-button-drop-item "+(u?"omni-button-drop-item-disabled":""),onClick:()=>m("video"),children:[F.jsx(pi,{type:"icon-line-video-on",className:"omni-button-drop-item-icon"}),F.jsx("div",{className:"omni-button-drop-item-label",children:e.t("Video Chat")})]})})}],[e,m,f,g,u,d]);return D.useEffect(()=>{t.current&&(t.current.style.opacity="1",t.current.style.cursor="pointer")},[]),F.jsx("div",{className:"omni-button-content",children:F.jsx(Si,{title:p,arrow:!1,children:F.jsx(Y,{menu:{items:v},trigger:["click"],overlayClassName:"omni-button-drop",children:F.jsx("div",{className:Q("omni-button-content-btn",{"omni-button-content-btn-no-bg-color":n&&o}),ref:t,style:C(C({},n&&o?{background:`url(${o}) no-repeat center/cover`}:{}),{opacity:.4,cursor:"not-allowed"}),children:F.jsx(pi,{className:"omni-button-content-btn-icon",type:"icon-line-waveform"})})})})})},e_=({buttonDisabled:e,status:t,onClick:n,chatId:s,disabledStatusCallbackEnabled:i})=>{const a=D.useRef(null),{i18n:o}=ye(),r=Kh(e=>e.messageType);return D.useEffect(()=>{a.current&&(a.current.style.opacity="1",a.current.style.cursor="pointer")},[]),F.jsx("div",{className:"chat-prompt-send-button",ref:a,style:{opacity:.4,cursor:"not-allowed"},children:"stop"===t?F.jsx(ue,{title:e?null:o.t("Stop"),children:F.jsx("button",{className:"stop-button "+(e?"disabled":""),disabled:e,onClick:e=>{e.preventDefault(),e.stopPropagation(),n("stop")},children:F.jsx(pi,{type:"icon-fill-stop-011",className:"icon-stop"})})}):"recording"===t?F.jsx("button",{className:"send-button "+(e?"disabled":""),disabled:e,onClick:e=>{e.preventDefault(),e.stopPropagation(),n("recording")},children:"om"}):F.jsx("button",{className:`send-button ${e?"disabled":""} ${(null==i?void 0:i.includes("send"))?"disabled-pointer":""}`,disabled:e&&!(null==i?void 0:i.includes("send")),onClick:e=>{e.preventDefault(),e.stopPropagation(),n("send"),Du("click",s,r)},children:F.jsx(pi,{type:"icon-line-arrow-up",className:"icon-send"})})})},t_=e=>{const{filesManager:t,messageInputMode:n,isDeepResearchRounds:s,placeHolder:i="",readOnly:a=!1,calcInputContainerHeight:o=()=>{},handleSend:r=()=>{},onUpdateSeparationNeeds:l=()=>{}}=e,c=D.useRef(null),d=D.useRef(!1),u=D.useRef(null),h=D.useRef(0),m=D.useRef(null),p=D.useRef(!1),g=dR(e=>e.mobile),f=Rs(e=>e.taskRunning),v=Rs(e=>e.visionGenerating),y=Kh(e=>e.files),b=Kh(e=>e.inputValue),x=Kh(e=>e.isFocus),w=Kh(e=>e.setIsFocus),_=Kh(e=>e.setInputValue),C=D.useRef(b),[,S]=(e=>{const[t,n]=D.useState(!1),[s,i]=D.useState(window.innerHeight),a=D.useRef(0),o=D.useRef(null),r=!1!==(null==e?void 0:e.preventScroll),l=(null==e?void 0:e.isFocus)||!1,c=()=>{const e=navigator.userAgent;return!!/iPhone|iPad|iPod/i.test(e)&&!/CriOS/i.test(e)&&!/EdgiOS/i.test(e)&&!/FxiOS/i.test(e)&&/Safari/i.test(e)&&!/Chrome/i.test(e)};return D.useEffect(()=>{if(!c()||!l)return;i(window.innerHeight);const e=()=>{const e=window.visualViewport?window.visualViewport.height:window.innerHeight,s=screen.height;e{var e;null==(e=o.current)||e.scrollIntoView({behavior:"smooth",block:"center"})},300)):t&&(n(!1),r&&(document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,a.current)))};return window.visualViewport?window.visualViewport.addEventListener("resize",e):window.addEventListener("resize",e),setTimeout(e,100),()=>{window.visualViewport?window.visualViewport.removeEventListener("resize",e):window.removeEventListener("resize",e),r&&(document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="")}},[t,r]),D.useEffect(()=>{if(!c()||!l)return;const e=e=>{t&&r&&e.preventDefault()},n={passive:!1};return document.addEventListener("touchmove",e,n),()=>{document.removeEventListener("touchmove",e,n)}},[t,r]),[t,e=>{e&&(o.current=e)}]})({isFocus:x}),k=D.useCallback(e=>{const t=s&&(""!==(null==b?void 0:b.trim())||y.length>0);d.current||e.nativeEvent.isComposing||!!u.current||g||(t||!f&&!v)&&("Enter"!==e.key||e.shiftKey||(e.preventDefault(),r("send"),Du("enter")))},[y.length,r,b,s,g,f,v]),j=D.useCallback(e=>{e.preventDefault(),((e,t)=>{var n,s;const i=e.clipboardData||window.clipboardData;let a=!1;if(i&&i.items){const r=Jh.getState().settings;for(const l of i.items)if("text/html"!==l.type&&"text/rtf"!==l.type){if(-1!==l.type.indexOf("image")){const e=l.getAsFile();e&&t.addFile(e,Xt.IMAGE),a=!0}else if("text/plain"===l.type){const o=i.getData("text/plain");if((null==(s=null==(n=null==r?void 0:r.ui)?void 0:n.largeTextAsFile)||s)&&o.length>kt){const n=new Blob([o],{type:"text/plain"}),s=new File([n],`Pasted_Text_${Date.now()}.txt`,{type:"text/plain"});t.addFile(s,Xt.DEFAULT),e.preventDefault(),a=!0}}if(!a)try{const t=i.getData(l.type);if(t){const n=e.target,s=null==n?void 0:n.selectionStart,i=null==n?void 0:n.selectionEnd;let o=Kh.getState().inputValue;o=o.slice(0,s)+t+o.slice(i),Kh.getState().setInputValue(o),setTimeout(()=>{n.selectionStart=n.selectionEnd=s+t.length},0),a=!0}}catch(o){}}}})(e,t)},[t]),T=D.useCallback(()=>{const e=c.current;if(!e)return;e.style.height="auto";const t=e.scrollHeight,n=g?4.9:8.5,s=window.getComputedStyle(e),i=parseFloat(s.lineHeight),a=i*n;let o=t;i&&oa?(o=a,e.style.overflowY="auto"):e.style.overflowY="hidden",e.style.height=`${o}px`},[g]),E=D.useCallback(()=>{if(h.current){const e=(e=>{const t=document.createElement("span"),n=window.getComputedStyle(e);t.style.fontFamily=n.fontFamily,t.style.fontSize=n.fontSize,t.style.fontWeight=n.fontWeight,t.style.letterSpacing=n.letterSpacing,t.style.visibility="hidden",t.style.position="absolute",t.style.whiteSpace="nowrap",t.textContent=e.value,document.body.appendChild(t);const s=t.offsetWidth;return document.body.removeChild(t),s})(c.current)>h.current||C.current.includes("\n");l({textLengthEnough:e})}},[l]),N=D.useCallback(()=>{if(g)return;const e=c.current;if(e){e.focus();const t=e.value.length;e.setSelectionRange(t,t),e.scrollTop=e.scrollHeight}},[g]),I=D.useRef(null);return D.useEffect(()=>{C.current=b,I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{if("combination"===n){const e=!!(null==b?void 0:b.trim());p.current===e&&h.current||(requestAnimationFrame(()=>{const e=c.current;e&&(h.current=e.clientWidth-parseFloat(window.getComputedStyle(e).paddingLeft)-parseFloat(window.getComputedStyle(e).paddingRight))}),p.current=e)}E(),T(),o()},100)},[b,n]),D.useEffect(()=>{if(N(),bM.firstOn(Yu.MESSAGE_INPUT_TRIGGER_FOCUS,N),b){const e=c.current;if(!e)return;h.current=e.clientWidth-parseFloat(window.getComputedStyle(e).paddingLeft)-parseFloat(window.getComputedStyle(e).paddingRight),E(),T()}return()=>{bM.off(Yu.MESSAGE_INPUT_TRIGGER_FOCUS,N),clearTimeout(m.current),I.current&&clearTimeout(I.current)}},[]),D.useEffect(()=>{const e=document.querySelector(".message-input-textarea");e&&e.value&&_(e.value)},[_]),F.jsx(F.Fragment,{children:F.jsx("textarea",{ref:c,value:b,rows:1,className:Q("message-input-textarea",{"message-input-textarea-separation":"separation"===n}),placeholder:i,readOnly:a,onChange:e=>{_(e.target.value)},onFocus:()=>{S(c.current),w(!0),g&&l({mobileFocus:!0})},onBlur:()=>{w(!1),g&&(l({mobileFocus:!1}),m.current=setTimeout(()=>{window.scrollTo(0,document.body.scrollHeight)},0))},onKeyDown:k,onPaste:j,onCompositionStart:()=>{d.current=!0,u.current&&(clearTimeout(u.current),u.current=null)},onCompositionEnd:()=>{d.current=!1,u.current=setTimeout(()=>{u.current=null},100)}})})},n_=({type:e="image",fileType:t="",item:n,status:s,src:i="",alt:a,name:o="",size:r,handleClose:l,handlePreview:c,onReUpload:d})=>{const{mobile:u}=cR(),{i18n:h}=ye();let m="",p="";if(o){const e=o.lastIndexOf(".");-1===e?(m=o,p=""):(m=o.slice(0,e),p=o.slice(e+1))}const g=tn[t]||tn.others,f=Zs()||Js()&&Gs(),v=u&&(Zs()||Js()&&Gs()),y=D.useRef(null),b=D.useMemo(()=>"uploaded"===s||!!i,[i,s]),x=D.useMemo(()=>"green_error"===n.greenNet,[n,n.greenNet]);return D.useEffect(()=>{const t=y.current,n=e=>()=>{e.currentTime=.1,(e=>{if(!$s())return;const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;const n=t.getContext("2d");n&&(n.drawImage(e,0,0,t.width,t.height),e.setAttribute("poster",t.toDataURL("image/png")))})(e)};if("video"===e&&t){const e=()=>t.pause(),s=n(t);return t.addEventListener("play",e),t.addEventListener("loadedmetadata",s),()=>{t.removeEventListener("play",e),t.removeEventListener("loadedmetadata",s)}}},[e,i]),F.jsx(F.Fragment,{children:b?F.jsxs("div",{className:"vision-item-container",children:[F.jsx("div",{className:"media",children:F.jsxs("div",{className:"vision-item-content",children:["image"===e&&F.jsx("img",{src:i,alt:a,className:"vision-item-image"}),"video"===e&&F.jsxs(F.Fragment,{children:[F.jsx("video",{ref:y,className:"vision-item-video",preload:"auto",controls:!1,autoPlay:v,muted:!0,playsInline:!0,children:f?F.jsx("source",{src:i,type:t}):F.jsx("source",{src:i})}),F.jsx("div",{className:"vision-item-video-play-button",children:F.jsx("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),c&&c("video",i)},children:F.jsx(pi,{type:"iconbigPauseMore",className:"iconbig-pause-more"})})})]})]})}),F.jsx("button",{className:"close-button",type:"button",onClick:l,children:F.jsx(pi,{type:"icon-close",className:"icon-close"})})]}):F.jsxs("div",{className:Q("fileitem-btn",{"fileitem-btn-greening":x}),children:[F.jsxs("div",{className:"file-content-icon",style:x?{}:{backgroundColor:null==g?void 0:g.bg},children:["uploading"===s&&F.jsx(mp,{className:"vision-spinner"}),"upload_error"===s&&!x&&F.jsx("button",{className:"fileitem-error-icon-wrapper",onClick:e=>{e.preventDefault(),e.stopPropagation(),d&&d()},children:F.jsx(pi,{type:"icon-fill",className:"fileitem-error-icon"})}),x&&F.jsx("div",{className:"fileitem-icon-wrapper",children:F.jsx(pi,{type:"icon-line-file-none",className:"fileitem-icon"})})]}),F.jsxs("div",{className:"file-content-info",children:[F.jsxs("div",{className:"fileitem-file-name",children:[F.jsx("div",{className:"fileitem-file-name-text",children:m}),F.jsx("div",{className:"fileitem-file-name-ext",children:p?`.${p}`:""})]}),F.jsxs("div",{className:"fileitem-file-size",children:[r&&!x&&F.jsx("span",{style:{margin:0},children:Lr(r)}),x&&F.jsx("span",{className:"fileitem-file-error",children:h.t("Invalid File")})]})]}),F.jsx("div",{className:"close-button",onClick:l,children:F.jsx(pi,{type:"icon-close",className:"icon-close"})})]})})},s_=({className:e="",url:t=null,item:n=null,fileType:s="others",name:i="",size:a,role:o="user",onClick:r,handleClose:l,onReUpload:c,showClose:d=!0,isQuote:u=!1})=>{var h,m,p,g,f,v,y,b,x;const{i18n:w}=ye(),[_,C]=D.useState(!1),{fileName:S,fileExt:k}=D.useMemo(()=>{let e="",t="";const n=(null==i?void 0:i.lastIndexOf("."))||-1;return-1===n?(e=i,t=""):(e=i.slice(0,n),t=i.slice(n+1)),{fileName:e,fileExt:t}},[i]),j=D.useMemo(()=>Vt.includes(k)||Ht.includes(s)?{icon:"icon-playground",bg:"#3F3F47"}:tn[s]||tn.others,[s,n,k]),T=D.useMemo(()=>{var e,t,s,i,a,o;if(null==(s=null==(t=null==(e=null==n?void 0:n.file)?void 0:e.meta)?void 0:t.parse_meta)?void 0:s.parse_status)switch(null==(o=null==(a=null==(i=null==n?void 0:n.file)?void 0:i.meta)?void 0:a.parse_meta)?void 0:o.parse_status){case"success":return"parsed";case"failed":return"parsed_error";case"running":return"parsing";default:return""}return(null==n?void 0:n.status)||""},[null==n?void 0:n.status,null==(p=null==(m=null==(h=null==n?void 0:n.file)?void 0:h.meta)?void 0:m.parse_meta)?void 0:p.parse_status]),E=D.useMemo(()=>"green_error"===n.greenNet,[n.greenNet]);return F.jsxs(F.Fragment,{children:[u&&F.jsxs("div",{className:"quote-fileitem-btn",children:[F.jsx(pi,{type:"icon-line-arrow-curve-left-right",className:"quote-icon"}),F.jsx("img",{src:"https://img.alicdn.com/imgextra/i4/O1CN01bzNurk1Ry24T88pdJ_!!6000000002179-55-tps-20-20.svg",alt:"",className:"quote-pdf-img"}),F.jsxs("div",{className:"fileitem-file-name",children:[F.jsx("div",{className:"fileitem-file-name-text",children:S}),F.jsx("div",{className:"fileitem-file-name-ext",children:k?`.${k}`:`${N=s,{"application/pdf":".pdf","image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","image/tiff":".tiff","text/plain":".txt","text/html":".html","text/css":".css","application/json":".json","application/javascript":".js","application/xml":".xml","application/zip":".zip","application/x-zip-compressed":".zip","application/octet-stream":".bin","video/mp4":".mp4","video/quicktime":".mov","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","font/woff":".woff","font/woff2":".woff2","application/vnd.ms-excel":".xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/msword":".doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.ms-powerpoint":".ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx"}[N]||""}`})]})]}),!u&&F.jsxs("div",{className:Q(`fileitem-btn ${e}`,{"fileitem-btn-greening":E}),onClick:()=>A(null,null,function*(){var e,s;(null==(s=null==(e=null==n?void 0:n.file)?void 0:e.data)?void 0:s.content)?C(!_):t&&Pl({role:o,url:t,isFile:!0}),r&&r()}),children:[F.jsxs("div",{className:"file-content-icon",style:E?{}:{backgroundColor:null==j?void 0:j.bg},children:[(["parsed","uploaded","success"].includes(T)||!T||"parsed_error"===T&&!(null==(v=null==(f=null==(g=null==n?void 0:n.file)?void 0:g.meta)?void 0:f.parse_meta)?void 0:v.retry))&&F.jsx("div",{className:"fileitem-icon-wrapper",children:F.jsx(pi,{type:(null==j?void 0:j.icon)||"",className:"fileitem-icon"})}),E&&F.jsx("div",{className:"fileitem-icon-wrapper",children:F.jsx(pi,{type:"icon-line-file-none",className:"fileitem-icon"})}),["parsing","uploading"].includes(T)&&F.jsx(mp,{className:"vision-spinner"}),("upload_error"===T||"parsed_error"===T&&(null==(x=null==(b=null==(y=null==n?void 0:n.file)?void 0:y.meta)?void 0:b.parse_meta)?void 0:x.retry))&&!E&&F.jsx("button",{className:"fileitem-error-icon-wrapper",style:{backgroundColor:null==j?void 0:j.bg},onClick:e=>{e.preventDefault(),e.stopPropagation(),c&&c()},children:F.jsx(pi,{type:"icon-fill",className:"fileitem-error-icon"})})]}),F.jsxs("div",{className:"file-content-info",children:[F.jsxs("div",{className:"fileitem-file-name",children:[F.jsx("div",{className:"fileitem-file-name-text",children:S}),F.jsx("div",{className:"fileitem-file-name-ext",children:k?`.${k}`:""})]}),F.jsxs("div",{className:"fileitem-file-size",children:[!["parsed_error","upload_error"].includes(T)&&a&&F.jsx("span",{style:{margin:0},children:Lr(a)}),"parsing"===T&&F.jsx("span",{children:w.t("Parsing...")}),"parsed_error"===T&&!E&&F.jsx("span",{className:"fileitem-file-error",children:w.t("Parsing failed")}),"upload_error"===T&&!E&&F.jsx("span",{className:"fileitem-file-error",children:w.t("Upload failed")}),E&&F.jsx("span",{className:"fileitem-file-error",children:w.t("Invalid File")})]})]}),d&&F.jsx("div",{className:"close-button",onClick:l,children:F.jsx(pi,{type:"icon-close",className:"icon-close"})})]})]});var N},i_=({files:e,onClose:t,onReUpload:n})=>{const[s,i]=D.useState(),[a,o]=D.useState(""),r=D.useRef(null),[l,c]=D.useState(!1),d=(e,t)=>A(null,null,function*(){i(e),o(t),"video"===e&&c(!0)}),u=D.useMemo(()=>e.filter(e=>!e.isQuote),[e]);return u&&0!==u.length?F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"file-card-list",children:u.map((e,s)=>{const i=`${e.itemId||s}-${e.status}`;return["video","image"].includes(e.showType)||["video","image"].includes(e.type||"")?F.jsx(n_,{src:e.url,item:e,type:e.showType,fileType:e.file_type,alt:`${e.name}`,status:e.status,handleClose:()=>{null==t||t(s)},onReUpload:()=>{null==n||n(s)},name:e.name,size:e.size,handlePreview:d},i):F.jsx(s_,{className:"w-[17rem]",item:e,name:e.name,fileType:e.file_type,size:(null==e?void 0:e.size)||0,dismissible:!0,handleClose:()=>{null==t||t(s)},onReUpload:()=>{null==n||n(s)}},i)})}),"video"===s&&a&&F.jsx(_x,{videoPlayerRef:r,url:a,open:l,setOpen:c})]}):null},a_=({children:e})=>{const t=ye(),n=ud(e=>e.realTheme);return F.jsxs("div",{className:"add-files-placeholder",children:[F.jsx("div",{className:"emoji",children:F.jsx("img",{src:"dark"===n?"https://img.alicdn.com/imgextra/i2/O1CN01JckncR1mS4QaTKy33_!!6000000004952-55-tps-88-88.svg":"https://img.alicdn.com/imgextra/i4/O1CN01It1jQq1IsgycW9wjk_!!6000000000949-55-tps-88-88.svg",alt:""})}),F.jsx("div",{className:"title",children:t.t("Drop any files here to add to the conversation")}),e||F.jsx("div",{className:"description",children:t.t("Add file, image, video or audio to the conversation")})]})},o_=({show:e=!1})=>{const t=D.useRef(null),n=D.useMemo(()=>(t.current||(t.current=document.createElement("div")),t.current),[]);if(D.useEffect(()=>{const t=n;if(e){document.body.appendChild(t);const e=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{try{document.body.removeChild(t)}catch(n){}document.body.style.overflow=e||"unset"}}try{t.parentElement&&document.body.removeChild(t)}catch(s){}},[e,n]),!e)return null;const s=F.jsx("div",{className:"dropzone-overlay",id:"dropzone",role:"region","aria-label":"Drag and Drop Container",children:F.jsx("div",{className:"dropzone-overlay-content",children:F.jsx("div",{className:"dropzone-overlay-content-wrapper",children:F.jsx("div",{className:"dropzone-overlay-inner",children:F.jsx("div",{className:"max-w-md",children:F.jsx(a_,{})})})})})});return B.createPortal(s,n)},r_=({textLength:e})=>{const{i18n:t}=ye(),n=cR(e=>e.mobile);return e<=kt?null:F.jsx("div",{className:"pasted-limit-info",children:F.jsxs("span",{children:[!n&&t.t("If you need to input more than {{value}} characters, please convert it into a txt document and upload the file, or enable the function in `Settings-Interface-Paste large text as file` and then paste the text.",{value:kt}),n&&t.t("If you need to input more than {{value}} characters, please convert it into a txt document and upload the file, or just copy the text to the clipboard, and then paste it into the input box.",{value:kt})]})})},l_=({currentI18nRecommend:e={},onChange:t})=>{const{i18n:n,t:s}=ye(),i=Kh(e=>e.inputValue),a=D.useMemo(()=>""!==i&&(null==e?void 0:e.t2t)?Pu(null==e?void 0:e.t2t.map(e=>s(e)).filter(e=>e.includes(i)),5):[],[null==e?void 0:e.t2t,i,n.language]);return a.length?F.jsx("ul",{className:"chat-prompt-recommend-detail-inner",children:!Ne(a)&&a.map(e=>F.jsx("li",{onClick:()=>{return n=e,A(null,null,function*(){t({inputText:n})});var n},children:F.jsx(he.Text,{ellipsis:!0,children:F.jsx("span",{dangerouslySetInnerHTML:{__html:Ru(e,i,n.language)}})})},e))}):null},c_=({type:e,iconType:t,showType:n="default"})=>{var s;const{i18n:i}=ye(),a=cR(e=>e.config),o=D.useCallback(()=>{bM.openWindow(`/community?tab=${e}`)},[e]);return!(null==(s=null==a?void 0:a.function_entry)?void 0:s.community)||wR()?null:"default"===n?F.jsx("div",{className:"explore-more",children:F.jsxs("div",{className:"explore-more-content",onClick:o,children:[F.jsx("span",{children:i.t("Explore more")}),F.jsx(pi,{type:"icon-line-chevron-right",className:"explore-more-icon"})]})}):"line"===n?F.jsxs("div",{className:"recommend-dp-item-wrap",onClick:o,children:[t&&F.jsx(pi,{type:t,className:"recommend-dp-item-wrap-icon"}),F.jsxs("div",{className:"recommend-dp-item-wrap-text",children:[" ",i.t("Explore more")]}),F.jsx(pi,{type:"icon-line-chevron-right",className:"recommend-dp-item-wrap-icon recommend-dp-item-wrap-more-icon"})]}):"card"===n?F.jsx("div",{className:"explore-more-card",onClick:o,children:F.jsxs("div",{className:"explore-more-card-content",children:[F.jsx(pi,{type:"icon-line-community",className:"explore-more-card-icon"}),F.jsx("div",{className:"explore-more-card-text",children:F.jsx("span",{children:i.t("More")})})]})}):void 0},d_=()=>{const e=hR(e=>e.thumbSrcArr);return{getThumbSrc:D.useCallback(t=>{const n=e.find(e=>e.src===t);return(null==n?void 0:n.thumbSrc)||t},[e])}},u_=({onChange:e,currentI18nRecommend:t,type:n})=>{const{i18n:s,t:i}=ye(),a=cR(e=>e.mobile),o=ud(e=>e.realTheme),{getThumbSrc:r}=d_(),l=Pu(n===yt.WebDev?(null==t?void 0:t.webdev)||[]:(null==t?void 0:t.artifacts)||[],4),c=D.useMemo(()=>"dark"===o?"https://img.alicdn.com/imgextra/i4/O1CN014rPKuM2AEpkO3CBOd_!!6000000008172-55-tps-276-276.svg":"https://img.alicdn.com/imgextra/i4/O1CN01KTkLVK1SSif2GxIkw_!!6000000002246-55-tps-276-276.svg",[o]);return F.jsx("div",{className:"recommend-web-container",children:F.jsxs("div",{className:"recommend-web-list",children:[l.map((t,l)=>F.jsxs("div",{className:"recommend-web-item-wrap",children:[F.jsxs("div",{className:"recommend-web-item-wrap-content",style:{backgroundImage:a?"none":`url(${c})`},children:[!a&&F.jsx("div",{className:"recommend-web-item-title",children:i(t.query||t.title)}),F.jsx("img",{className:Q("recommend-web-item-image",{"recommend-web-item-image-artifact":n===yt.Artifacts}),src:r("light"===o?t.src:t.darkSrc||t.src),alt:""})]}),F.jsxs("button",{className:"recommend-web-item-image-button",onClick:()=>{e({inputText:i(t.query||t.title)})},children:[s.t("Use Prompt")," "]})]},l)),a&&F.jsx(c_,{type:"web_dev",showType:"card"})]})})},h_=[yt.DeepResearch,yt.Travel],m_=({onChange:e,type:t,currentI18nRecommend:n={}})=>{const s=cR(e=>e.mobile),{t:i}=ye(),a=D.useMemo(()=>t===yt.DeepResearch?(null==n?void 0:n.deepResearch)||[]:t===yt.Travel?(null==n?void 0:n.travel)||[]:t===yt.WebSearch?(null==n?void 0:n.webSearch)||[]:t===yt.LEARN&&(null==n?void 0:n.learn)||[],[null==n?void 0:n.deepResearch,null==n?void 0:n.learn,null==n?void 0:n.travel,null==n?void 0:n.webSearch,t]),o=D.useMemo(()=>t===yt.DeepResearch?"icon-line-deepresearch-02":t===yt.Travel?"icon-line-Travel":t===yt.WebSearch?"icon-line-search-01":"",[t]),r=Pu(a,s?3:5);return F.jsx("div",{className:"recommend-dp-container",children:F.jsxs("div",{className:"recommend-dp-list",children:[r.map((t,n)=>F.jsxs("div",{className:"recommend-dp-item-wrap",onClick:()=>e({inputText:i(t.query||t.title)}),children:[(o||t.image)&&F.jsx(pi,{type:o||t.image,className:"recommend-dp-item-wrap-icon"}),F.jsx("div",{className:"recommend-dp-item-wrap-text",children:i(t.query||t.title)})]},n)),h_.includes(t)&&s&&F.jsx(c_,{iconType:o,type:"pdf",showType:"line"})]})})},p_=({video:e,onChange:t,videoRefs:n,index:s})=>{const{i18n:i,t:a}=ye();return F.jsxs("div",{className:"chat-recommend-video-list-item-mobile",children:[F.jsx("div",{className:"chat-recommend-video-list-item-container aspect-ratio",children:F.jsx(lx,{videoSrc:e.src||"",errorMessage:i.t("Your browser does not support the video tag.")||"",onLoad:e=>{e&&n.current&&(n.current[s]=e)}})}),F.jsx("button",{className:"recommend-use-prompt-btn",onClick:()=>{return n=a(e.description),s=e.image,A(null,null,function*(){t({inputText:n,image:s})});var n,s},children:a("Use Prompt")})]})},g_=({data:e,onChange:t})=>{const n=D.useMemo(()=>Pu(e,2),[e]),s=navigator.userAgent.toLowerCase(),i=["VivoBrowser"].some(e=>new RegExp(e,"i").test(s)),a=D.useRef([]),o=cR(e=>e.mobile);return D.useEffect(()=>{if(i)return;const e=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?e.target.play():e.target.pause()})},{threshold:.8,rootMargin:"0px"});return a.current.forEach(t=>{t&&(t.setAttribute("playsinline","true"),t.setAttribute("webkit-playsinline","true"),t.muted=!0,e.observe(t))}),()=>{e.disconnect()}},[i]),D.useEffect(()=>{a.current.length===n.length&&setTimeout(()=>{const e=document.getElementById("chat-prompt-recommend-detail-container");e&&o&&(e.scrollLeft=e.scrollWidth)},100)},[a.current.length,n.length,o]),F.jsx("div",{className:"chat-recommend-video-mobile",children:F.jsxs("div",{className:"chat-recommend-video-list",children:[n.map((e,n)=>F.jsx(p_,{index:n,video:e,onChange:t,videoRefs:a},e.src)),F.jsx(c_,{type:"video",showType:"card"})]})})},f_=({video:e,onChange:t})=>{const n=D.useRef(null),{i18n:s,t:i}=ye();return F.jsxs("div",{className:"chat-recommend-video-list-item",onMouseEnter:()=>{var e;return null==(e=n.current)?void 0:e.play()},onMouseLeave:()=>{var e;null==(e=n.current)||e.pause(),n.current.currentTime=0},children:[F.jsx("div",{className:"chat-recommend-video-list-item-video-container aspect-ratio",children:F.jsxs("video",{className:"chat-recommend-video-list-item-video",muted:!0,loop:!0,ref:n,children:[F.jsx("source",{src:e.src,type:"video/mp4"}),s.t("Your browser does not support the video tag.")]})}),F.jsxs("div",{className:"chat-recommend-video-list-item-text-box",children:[F.jsx("div",{className:"chat-recommend-video-list-item-text-box-text",children:i(e.description)}),F.jsx("button",{className:"chat-recommend-video-list-item-text-box-use-btn",onClick:()=>{return n=i(e.description),s=e.image,A(null,null,function*(){t({inputText:n,image:s})});var n,s},children:i("Use Prompt")})]})]})},v_=({data:e,onChange:t})=>{const n=D.useMemo(()=>Pu(e,2),[e]);return F.jsx("div",{className:"chat-recommend-video",children:F.jsx("div",{className:"chat-recommend-video-list",children:n.map(e=>F.jsx(f_,{video:e,onChange:t},e.src))})})},y_=({currentI18nRecommend:e,onChange:t})=>{const n=cR(e=>e.mobile),s=Kh(e=>e.updateFeatureType),i=Kh(e=>e.setFiles),a=({inputText:e,image:n})=>{s({chatType:yt.VideoGeneration,subChatType:yt.VideoGeneration}),n&&i([{type:"image",name:"example.png",file_type:"image/png",showType:"image",status:"uploaded",file_class:"vision",url:n}]),t({inputText:e})};return n?F.jsx(g_,{data:(null==e?void 0:e.video)||[],onChange:a}):F.jsx(v_,{data:(null==e?void 0:e.video)||[],onChange:a})},b_=()=>window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",x_=({data:e,onChange:t})=>{const{t:n}=ye(),s=Kh(e=>e.setFiles),{getThumbSrc:i}=d_(),a=D.useCallback(e=>e&&(null==e?void 0:e.length)?F.jsxs("div",{className:"recommend-source-image-item",children:[e.length>1&&F.jsx("div",{className:"recommend-source-image-item-back"}),F.jsx("img",{className:"recommend-source-image-item-img",src:e[0],alt:""})]}):null,[]);return F.jsx("div",{className:"recommend-image-mobile",children:F.jsxs("div",{className:"recommend-image-list",children:[e.map((e,o)=>F.jsxs("div",{className:"recommend-image-item-wrap",children:[a(e.sourceImageList),F.jsx("div",{className:"recommend-image-item",children:F.jsx("img",{className:"recommend-image-item-picture",src:i("light"===b_()?e.src:e.darkSrc||e.src),alt:""})}),F.jsx("button",{className:"recommend-use-prompt-btn",onClick:()=>{var i,a;(null==(i=e.sourceImageList)?void 0:i.length)&&s(e.sourceImageList.map(e=>({type:"image",name:"example.png",file_type:"image/png",showType:"image",status:"uploaded",file_class:"vision",url:e}))),a=n(e.description),t({inputText:a})},children:n("Use Prompt")})]},o)),F.jsx(c_,{type:"image",showType:"card"})]})})},w_=({onChange:e,data:t})=>{const{t:n}=ye(),s=Kh(e=>e.setFiles),{getThumbSrc:i}=d_(),a=[];for(let o=0;oF.jsx("div",{className:"image-group",children:t.map((t,o)=>{var r;return F.jsxs("div",{className:"image-container",children:[F.jsx("img",{src:i(t.src),alt:t.src,className:"image"}),F.jsxs("div",{className:"chat-recommend-image-list-item-text-box",children:[(null==(r=t.sourceImageList)?void 0:r.length)&&F.jsx("div",{className:"chat-recommend-image-list-item-text-box-source",children:t.sourceImageList.map(e=>F.jsx("img",{src:e,alt:""},e))}),F.jsx("div",{className:"chat-recommend-image-list-item-text-box-text",children:n(t.description)}),F.jsx("button",{className:"chat-recommend-image-list-item-text-box-use-btn",onClick:()=>{var i;(null==(i=t.sourceImageList)?void 0:i.length)&&s(t.sourceImageList.map(e=>({type:"image",name:"example.png",file_type:"image/png",showType:"image",status:"uploaded",file_class:"vision",url:e}))),e({inputText:n(t.description)})},children:n("Use Prompt")})]})]},`${a}-${o}`)})},a))})},__=({data:e,onChange:t})=>F.jsx("div",{className:"chat-recommend-image",children:F.jsx(w_,{onChange:t,data:e})}),C_=Ks(),S_=({currentI18nRecommend:e,onChange:t})=>{const n=Pu((null==e?void 0:e.image)||[],4);return D.useEffect(()=>{},[]),C_?F.jsx(x_,{data:n,onChange:t}):F.jsx(__,{data:n,onChange:t})},k_=e=>A(null,null,function*(){return yield TM("/tts/config",{params:{omni_speakers:"v1",audio_tts_speakers:"v1",omni_language:"v1",audio_tts_language:"v1"},headers:{"Accept-Language":`${e},${e.split("-")[0]};q=0.9`}})}),j_=({onChange:e})=>{const{i18n:t}=ye(),n=ud(e=>e.realTheme),[s,i]=D.useState({}),[a,o]=D.useState([]),r=Kh(e=>e.setFiles);D.useEffect(()=>{try{A(null,null,function*(){return yield TM("/configs/?code=query-suggestion-slides")}).then(e=>{(null==e?void 0:e.success)&&i(e.data)})}catch(e){}},[]);D.useEffect(()=>{var e;s&&o(null==(e=null==s?void 0:s[t.language])?void 0:e.slides)},[s,t.language]);const l=Pu(a||[],3),c=D.useMemo(()=>"dark"===n?"https://img.alicdn.com/imgextra/i4/O1CN01jRh4L41R4cDu9WAAW_!!6000000002058-55-tps-265-200.svg":"https://img.alicdn.com/imgextra/i1/O1CN01HjVxaK1q7hHaF5ZDh_!!6000000005449-55-tps-265-200.svg",[n]);return F.jsx("div",{className:"recommend-ai-ppt-container",children:F.jsx("div",{className:"recommend-ai-ppt-list",children:l.map(n=>F.jsxs("div",{className:"recommend-ai-ppt-item-wrap",style:{backgroundImage:`url(${c})`},children:[F.jsx("div",{className:"recommend-ai-ppt-item-title",children:n.prompt}),F.jsx("img",{className:"recommend-ai-ppt-item-image",src:n.src,alt:""}),F.jsx("button",{className:"recommend-ai-ppt-item-image-button",onClick:()=>{(t=>{const{inputText:n,file:s,filename:i}=t;if(s){const e=null!=i?i:"suggested_slides.pdf",t=Fe();r([{type:"file",file:{filename:e,id:t,meta:{name:e,content_type:"application/pdf",parse_meta:{parse_status:"success"}}},id:t,url:s,name:e,status:"uploaded",greenNet:"success",file_type:"application/pdf",showType:"file",file_class:"document"}])}e({inputText:n})})({inputText:n.prompt,file:null==n?void 0:n.fileUrl,filename:null==n?void 0:n.filename})},children:t.t("Use Prompt")})]},n.prompt))})})},T_=O.memo(({currentI18nRecommend:e,messageType:t,onChange:n})=>{const s=cR(e=>e.mobile);switch(t){case yt.Travel:case yt.WebSearch:case yt.DeepResearch:case yt.LEARN:return F.jsx("div",{className:"chat-prompt-recommend-detail-content-container",children:F.jsx(m_,{currentI18nRecommend:e,onChange:n,type:t})});case yt.VideoGeneration:return F.jsxs("div",{className:"chat-prompt-recommend-detail-content-container",children:[F.jsx(y_,{currentI18nRecommend:e,onChange:n})," "]});case yt.WebDev:case yt.Artifacts:return F.jsxs("div",{className:"chat-prompt-recommend-detail-content-container",children:[" ",F.jsx(u_,{currentI18nRecommend:e,type:t,onChange:n})]});case yt.Slides:return F.jsx("div",{className:"chat-prompt-recommend-detail-content-container",children:F.jsx(j_,{onChange:n})});case yt.ImageGeneration:return F.jsx("div",{className:"chat-prompt-recommend-detail-content-container",children:F.jsx(S_,{currentI18nRecommend:e,onChange:n})});case yt.Txt2Txt:return s?F.jsx(l_,{currentI18nRecommend:e,onChange:n}):null;default:return null}},(e,t)=>e.messageType===t.messageType),E_=[{ratio:"1:1",originImageUrl:"https://img.alicdn.com/imgextra/i4/O1CN01D1as1J1L65nt2fHdQ_!!6000000001249-2-tps-1328-1328.png",newImageUrl:"https://img.alicdn.com/imgextra/i2/O1CN01Zz1Vkw1wqThW3tPiv_!!6000000006359-2-tps-1328-1328.png",prompt:"Ultra-detailed 3D graphite pencil sketch of a person actively drawing, rendered on textured white notebook paper. The subject’s hand is holding a pencil, mid-stroke, as the sketch dynamically emerges from the page. Surrounding the drawing area: realistic pencil shavings, a pink eraser, and a metal pencil sharpener resting naturally on the paper. Emphasize high-fidelity paper texture—visible grain, subtle fibers, and minor imperfections like slight creases or soft folds. Include authentic graphite effects: soft smudges, fine residue, and nuanced tonal gradients. Cast realistic ambient shadows under objects and around the hand to enhance depth and tactile presence. Style: photorealistic hand-drawn aesthetic, monochrome graphite tones, macro-level detail."},{ratio:"1:1",originImageUrl:"https://img.alicdn.com/imgextra/i4/O1CN01D1as1J1L65nt2fHdQ_!!6000000001249-2-tps-1328-1328.png",newImageUrl:"https://img.alicdn.com/imgextra/i4/O1CN01V0MSlo1UNLGJxq8Tp_!!6000000002505-2-tps-1328-1328.png",prompt:"Create a high-quality 3D avatar of the person in the uploaded image with a cheerful, expressive face. The character should have a warm smile, bright eyes, and soft facial features that feel friendly and approachable. Render in a Pixar-style aesthetic with smooth textures, subtle skin shading, and slightly exaggerated proportions for a cute, animated look. Lighting should be soft and even, creating a clean studio look with gentle shadows for depth."},{ratio:"1:1",originImageUrl:"https://img.alicdn.com/imgextra/i4/O1CN01D1as1J1L65nt2fHdQ_!!6000000001249-2-tps-1328-1328.png",newImageUrl:"https://img.alicdn.com/imgextra/i1/O1CN01934VZ31nXr3QuT52K_!!6000000005100-2-tps-1328-1328.png",prompt:"A close-up, professionally composed photograph of a hand-crocheted yarn doll gently cradled in two hands. The doll has a soft, rounded chibi form, faithfully reimagining the character from the uploaded image with vivid contrasting colors and intricate, tactile details. The hands are natural and expressive—fingers relaxed yet clearly defined, with realistic skin texture, subtle veins, and gentle light-to-shadow transitions that convey warmth and human presence. The background is softly blurred, revealing a cozy indoor setting: a warm-toned wooden tabletop bathed in diffused daylight streaming through a nearby window. The overall atmosphere is intimate, serene, and tender, celebrating both the artistry of handmade craft and the quiet affection of holding something cherished."},{ratio:"1:1",originImageUrl:"https://img.alicdn.com/imgextra/i4/O1CN01D1as1J1L65nt2fHdQ_!!6000000001249-2-tps-1328-1328.png",newImageUrl:"https://img.alicdn.com/imgextra/i1/O1CN01jODjPc1MpGU6MJ166_!!6000000001483-2-tps-1328-1328.png",prompt:"Create a stylized 3D chibi character based on the attached photo, faithfully preserving the subject’s distinctive facial features and key clothing details. The character strikes a playful pose—sitting on the edge of a giant Instagram-style frame with both legs dangling outside—and forms a finger heart with their left hand, topped by a glowing red heart icon. The frame’s top edge displays the username “Beauty” in clean, modern typography. Floating around the scene are subtle, semi-transparent social media UI elements: like, comment, and share icons, rendered in a cohesive, non-distracting style. The overall aesthetic is vibrant, cute, and digitally native—blending kawaii chibi charm with contemporary social media visual language."}],N_=({onClose:e,leftContent:t,rightContent:n,topContent:s,bottomContent:i,variant:a="pc"})=>{const o="h5"===a,r=o?"guidance-h5-card":"guidance-pc-card",l=o?"guidance-h5-close-btn":"guidance-pc-close-btn",c=o?"guidance-h5-inner":"guidance-pc-inner",d=o?"guidance-h5-left":"guidance-pc-left",u=o?"guidance-h5-right":"guidance-pc-right",h=o?"guidance-h5-top":"guidance-pc-top",m=o?"guidance-h5-bottom":"guidance-pc-bottom",[p,g]=D.useState(()=>"undefined"!=typeof window&&window.innerWidth<700);return D.useEffect(()=>{const e=()=>{g(window.innerWidth<700)};return e(),window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}},[]),F.jsxs("div",{className:r,children:[F.jsx("button",{className:l,onClick:()=>{null==e||e()},children:F.jsx(pi,{type:"icon-close"})}),F.jsx("div",{className:"guidance-pc-gradient-bg"}),F.jsx("div",{className:c,children:p&&s&&i?F.jsxs(F.Fragment,{children:[F.jsx("div",{className:h,children:s}),F.jsx("div",{className:m,children:i})]}):F.jsxs(F.Fragment,{children:[F.jsx("div",{className:d,children:t}),F.jsx("div",{className:u,children:n})]})})]})},I_=({onGetStarted:e,onClose:t,RecommendPrompt:n})=>{const{i18n:s}=ye(),i=D.useMemo(()=>Pu(n),[]),[,a]=D.useState(0),[o,r]=D.useState(()=>i[0]),[l,c]=D.useState(!1),[d,u]=D.useState(!1),{getThumbSrc:h}=d_(),m=F.jsx(F.Fragment,{children:F.jsx("div",{className:"guidance-edit-pc-text",children:s.t("Transform yourself into a 3D character.")})}),p=F.jsx(F.Fragment,{children:F.jsxs("div",{className:"guidance-pc-buttons",children:[F.jsx(xi,{type:"brandprimary",size:"small",rounded:"circle",className:"guidance-pc-get-started-btn",onClick:()=>e(!1,o),children:s.t("Get Started")}),F.jsx(xi,{type:"ghost",size:"small",rounded:"circle",className:"guidance-pc-shuffle-btn",onClick:()=>{c(!0),setTimeout(()=>{u(!0),a(e=>{const t=(e+1)%i.length;return r(i[t]),t}),c(!1),requestAnimationFrame(()=>{setTimeout(()=>{u(!1)},300)})},300)},children:F.jsx(pi,{type:"icon-line-Shuffle",className:"guidance-pc-shuffle-btn-icon"})})]})}),g=F.jsx("div",{className:"guidance-edit-pc-right-content",children:o&&F.jsxs("div",{className:"guidance-edit-pc-image-comparison",children:[F.jsxs("div",{className:`guidance-edit-pc-image-before ${l?"guidance-edit-pc-shuffle-out":""} ${d?"guidance-edit-pc-shuffle-in":""}`,children:[F.jsx("img",{src:h(o.originImageUrl),alt:"Before",className:"guidance-edit-pc-image-before-img"}),F.jsxs("div",{className:"guidance-edit-pc-image-upload-placeholder",onClick:()=>e(!0,o),children:[F.jsx(pi,{type:"icon-line-plus-02",className:"guidance-edit-pc-image-upload-icon"}),F.jsx("span",{className:"guidance-edit-pc-image-upload-text",children:s.t("Upload image")})]})]},`before-${o.prompt}`),F.jsx("div",{className:"guidance-edit-pc-image-arrow",children:F.jsx("img",{src:"https://img.alicdn.com/imgextra/i3/O1CN01T2wxFm1tFQod0lYfk_!!6000000005872-2-tps-216-144.png",alt:"Arrow"})}),F.jsx("div",{className:`guidance-edit-pc-image-after ${l?"guidance-edit-pc-shuffle-out":""} ${d?"guidance-edit-pc-shuffle-in":""}`,children:F.jsx("img",{src:h(o.newImageUrl),alt:"After"})},`after-${o.prompt}`)]})}),f=F.jsxs(F.Fragment,{children:[m,p]}),v=F.jsx(F.Fragment,{children:g}),y=F.jsx(F.Fragment,{children:m}),b=F.jsxs(F.Fragment,{children:[p,g]});return F.jsx(N_,{onClose:t,topContent:y,bottomContent:b,leftContent:f,rightContent:v})},A_=({onImageClick:e,onClose:t,RecommendPrompt:n})=>{const[s,i]=D.useState(()=>Pu(n,1)[0]||E_[0]),[a,o]=D.useState(!1),[r,l]=D.useState(!1),c=D.useRef(null),{i18n:d}=ye(),{getThumbSrc:u}=d_();D.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]);const h=F.jsxs(F.Fragment,{children:[F.jsxs("div",{className:"guidance-edit-h5-text",children:[F.jsx("div",{className:"guidance-edit-h5-text-title",children:d.t("Try this! Turn photos into 3D style.")}),F.jsx("div",{className:"guidance-edit-h5-text-subtitle",children:d.t("Select one from the sample on the right.")})]}),F.jsx(xi,{type:"ghost",size:"small",rounded:"circle",className:"guidance-edit-h5-shuffle-btn",onClick:()=>{a||r||(o(!0),c.current=setTimeout(()=>{let e,t=0;do{if(e=Pu(E_,1)[0]||E_[0],t++,t>10)break}while(e.prompt===s.prompt&&E_.length>1);i(e),o(!1),requestAnimationFrame(()=>{l(!0),setTimeout(()=>{l(!1)},300)})},300))},children:F.jsx(pi,{type:"icon-line-Shuffle",className:"guidance-edit-h5-shuffle-btn-icon"})})]}),m=F.jsx("div",{className:"guidance-edit-h5-right-content",onClick:()=>{e(!1,s)},children:s&&F.jsxs("div",{className:"guidance-edit-h5-image-comparison",children:[F.jsx("div",{className:`guidance-edit-h5-image-before ${a?"guidance-edit-h5-before-shuffle-out":""} ${r?"guidance-edit-h5-before-shuffle-in":""}`,children:F.jsx("img",{src:u(s.originImageUrl),alt:"Before",className:"guidance-edit-h5-image-before-img"})},`before-${s.prompt}`),F.jsx("div",{className:"guidance-edit-h5-image-arrow",children:F.jsx("img",{src:"https://img.alicdn.com/imgextra/i3/O1CN01z7PRcK1TITR9FpcFV_!!6000000002359-2-tps-144-108.png",alt:"Arrow"})}),F.jsx("div",{className:`guidance-edit-h5-image-after ${a?"guidance-edit-h5-after-shuffle-out":""} ${r?"guidance-edit-h5-after-shuffle-in":""}`,children:F.jsx("img",{src:u(s.newImageUrl),alt:"After"})},`after-${s.prompt}`)]})});return F.jsx(N_,{variant:"h5",onClose:t,leftContent:h,rightContent:m})},M_=({onImageClick:e,onClose:t,RecommendPrompt:n})=>{const[s,i]=D.useState([0,1,2,3]),[a,o]=D.useState(!1),r=D.useRef(null),{getThumbSrc:l}=d_(),c=D.useRef(0),{i18n:d,t:u}=ye(),h=O.useMemo(()=>Pu(n),[n]),m=O.useCallback(e=>{const t=s[0],n=s[1],i=s[2],o=s[3];return e===t?"pos-1":e===n?"pos-2":e===i?"pos-3":e===o&&a?"pos-4":"hidden"},[s,a]),p=O.useCallback(()=>{a||(o(!0),c.current+=1,r.current=setTimeout(()=>{i(e=>e.map(e=>(e+1)%h.length)),requestAnimationFrame(()=>{o(!1)})},300))},[h.length,a]);D.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const g=F.jsxs(F.Fragment,{children:[F.jsxs("div",{className:"guidance-h5-text",children:[F.jsx("div",{className:"guidance-h5-text-title",children:d.t("Create your first image")}),F.jsx("div",{className:"guidance-h5-text-subtitle",children:d.t("Select one from the sample on the right.")})]}),F.jsx(xi,{type:"ghost",size:"small",rounded:"circle",className:"guidance-h5-shuffle-btn",onClick:()=>{p()},children:F.jsx(pi,{type:"icon-line-Shuffle",className:"guidance-h5-shuffle-btn-icon"})})]}),f=F.jsx(F.Fragment,{children:h.map((t,n)=>{const s=m(n),i="hidden"===s;let o="guidance-h5-image-card";return"pos-1"===s?(o+=" guidance-h5-card-pos-1",a&&(o+=" guidance-h5-shuffle-out-1")):"pos-2"===s?(o+=" guidance-h5-card-pos-2",a&&(o+=" guidance-h5-shuffle-move-1")):"pos-3"===s?(o+=" guidance-h5-card-pos-3",a&&(o+=" guidance-h5-shuffle-move-2")):"pos-4"===s?(o+=" guidance-h5-card-pos-4",a&&(o+=" guidance-h5-shuffle-in-3")):i&&(o+=" guidance-h5-hidden"),F.jsx("div",{className:o,onClick:()=>{i||e(u(t.prompt))},children:F.jsx("img",{src:l(t.imageUrl),alt:t.tag})},`image-${n}`)})});return F.jsx(N_,{variant:"h5",onClose:t,leftContent:g,rightContent:f})},R_=({onGetStarted:e,onClose:t,RecommendPrompt:n})=>{const[s,i]=D.useState(()=>Pu(n,3)),[a,o]=D.useState(!1),[r,l]=D.useState(!1),[c,d]=D.useState(0),{i18n:u,t:h}=ye(),{getThumbSrc:m}=d_(),p=F.jsx(F.Fragment,{children:F.jsx("div",{className:"guidance-pc-text",children:u.t("Choose a style to create your first image.")})}),g=F.jsx(F.Fragment,{children:F.jsxs("div",{className:"guidance-pc-buttons",children:[F.jsx(xi,{type:"brandprimary",size:"small",rounded:"circle",className:"guidance-pc-get-started-btn",onClick:()=>{e(h(s[1].prompt))},children:u.t("Get Started")}),F.jsx(xi,{type:"ghost",size:"small",rounded:"circle",className:"guidance-pc-shuffle-btn",onClick:()=>{o(!0),setTimeout(()=>{l(!0),i(Pu(n,3)),d(e=>e+1),o(!1),requestAnimationFrame(()=>{setTimeout(()=>{l(!1)},350)})},350)},children:F.jsx(pi,{type:"icon-line-Shuffle",className:"guidance-pc-shuffle-btn-icon"})})]})}),f=F.jsx("div",{className:"guidance-pc-images",children:s.map((t,n)=>F.jsx("div",{className:`guidance-pc-image-card ${a?"guidance-pc-shuffle-out":""} ${r?"guidance-pc-shuffle-in":""}`,"data-card-index":n,onClick:()=>{return n=t.prompt,void e(h(n));var n},children:F.jsx("img",{src:m(t.imageUrl),alt:t.tag})},`${t.prompt}-${n}-${c}`))}),v=F.jsxs(F.Fragment,{children:[p,g]}),y=F.jsx(F.Fragment,{children:f}),b=F.jsx(F.Fragment,{children:p}),x=F.jsxs(F.Fragment,{children:[g,f]});return F.jsx(N_,{onClose:t,topContent:b,bottomContent:x,leftContent:v,rightContent:y})},P_="guidance_card_type",L_=({onClose:e,onAutoFillPrompt:t,RecommendData:n})=>{const s=cR(e=>e.mobile),i=Kh(e=>e.setInputValue),a=Kh(e=>e.setFiles),o=Kh(e=>e.setVisionSize),{t:r}=ye(),l=O.useMemo(()=>{const e=localStorage.getItem(P_);return e===yt.ImageGeneration?yt.ImageEdit:(yt.ImageEdit,yt.ImageGeneration)},[]);D.useEffect(()=>{localStorage.setItem(P_,l)},[l]);const c=()=>{null==e||e()},d=(e,n)=>{bM.emit(Yu.MESSAGE_INPUT_RECOMMEND_WORDS_CLICK,{suggestItem:{chatType:yt.ImageGeneration,subChatType:yt.ImageGeneration,uploadType:e?[Xt.IMAGE]:[]},active:!0}),o(n.ratio),e?i(r(n.prompt)):(i(r(n.prompt)),a([{type:"image",name:"example.png",file_type:"image/png",showType:"image",status:"uploaded",file_class:"vision",url:n.originImageUrl}])),t()},u=e=>{bM.emit(Yu.MESSAGE_INPUT_RECOMMEND_WORDS_CLICK,{suggestItem:{chatType:yt.ImageGeneration,subChatType:yt.ImageGeneration},active:!0}),o("16:9"),i(e),t()};return s?l===yt.ImageGeneration?F.jsx(M_,{onImageClick:u,onClose:c,RecommendPrompt:n.imageGeneration||[]}):F.jsx(A_,{onImageClick:d,onClose:c,RecommendPrompt:n.imageEdit||[]}):l===yt.ImageGeneration?F.jsx(R_,{onGetStarted:u,onClose:c,RecommendPrompt:n.imageGeneration||[]}):F.jsx(I_,{onGetStarted:d,onClose:c,RecommendPrompt:n.imageEdit||[]})},O_=O.memo(({currentI18nRecommend:e,resetInputHandler:t})=>{const n=dR(e=>e.mobile),s=Kh(e=>e.messageType),i=js(e=>e.currentInputFeature),a=Kh(e=>e.files),o=Pd(e=>e.user),[r,l]=D.useState(!1),[c,d]=D.useState(!1),u=()=>{d(!0)},h=D.useMemo(()=>!o&&(!r&&(!(i!==yt.ImageGeneration||!c)||i===yt.Txt2Txt&&0===a.length)),[o,r,i,a.length,c]),m=D.useMemo(()=>{switch(s){case yt.ImageGeneration:return"image";case yt.Travel:case yt.DeepResearch:return"pdf";case yt.WebDev:case yt.Artifacts:return"web_dev";case yt.VideoGeneration:return"video";default:return null}},[s]);return n?F.jsx("div",{className:"chat-prompt-recommend-detail-container",children:h?F.jsx("div",{className:"chat-prompt-recommend-detail-content-container",children:F.jsx(L_,{onClose:()=>l(!0),onAutoFillPrompt:u,RecommendData:null==e?void 0:e.guidance})}):F.jsx(T_,{currentI18nRecommend:e,messageType:s,onChange:e=>{t(e.inputText,"send")}})}):F.jsx("div",{className:Q("chat-prompt-recommend-container"),children:h?F.jsx(L_,{onClose:()=>l(!0),onAutoFillPrompt:u,RecommendData:null==e?void 0:e.guidance}):F.jsxs("div",{className:"chat-prompt-recommend-detail-container",children:[F.jsx(T_,{currentI18nRecommend:e,messageType:s,onChange:e=>{t(e.inputText,"send")}}),m&&F.jsx(c_,{type:m})]})})}),D_=()=>{var e,t,n;const s=Rs(e=>e.selectedText),i=Rs(e=>e.setSelectedText),a=Kh(e=>e.files),o=Kh(e=>e.setFiles),r=js(e=>e.chatId),{id:l}=Ge(),c=D.useCallback(()=>{o([]),i("")},[o,i]);D.useEffect(()=>{r!==l&&i("")},[r,l,i]);const d=D.useMemo(()=>{const e=a.filter(e=>e.isQuote),t={};return e.length&&(t.quoteFiles=e),s&&(t.quoteText=s),t},[a,s]);return Ne(d)?null:F.jsxs("div",{className:"quote",children:[F.jsx(pi,{type:"icon-line-arrow-curve-left-right",className:"quote-icon"}),!!(null==(e=null==d?void 0:d.quoteFiles)?void 0:e.length)&&F.jsx("div",{className:"quote-imgs",children:null==(t=null==d?void 0:d.quoteFiles)?void 0:t.map(e=>F.jsxs(F.Fragment,{children:["image"===e.type&&F.jsx("img",{src:e.url,alt:"",className:"quote-imgs-img"},e.url),"file"===e.type&&F.jsxs("div",{className:"quote-pdf",children:[F.jsx("img",{src:"https://img.alicdn.com/imgextra/i4/O1CN01bzNurk1Ry24T88pdJ_!!6000000002179-55-tps-20-20.svg",alt:"",className:"quote-pdf-img"}),F.jsx("div",{className:"quote-pdf-name",children:null==e?void 0:e.name})]})]}))}),!!(null==(n=null==d?void 0:d.quoteText)?void 0:n.length)&&F.jsx("div",{className:"quote-imgs",children:F.jsx("div",{className:"quote-text",children:null==d?void 0:d.quoteText})}),F.jsx(pi,{type:"icon-line-x-03",className:"quote-icon quote-icon-close",onClick:c})]})};class F_{constructor(e,t,n){var s;this.length_=e,this.scaleFactor_=(e-1)/t,this.interpolate=this.cubic,"point"===n.method?this.interpolate=this.point:"linear"===n.method?this.interpolate=this.linear:"sinc"===n.method&&(this.interpolate=this.sinc),this.tangentFactor_=1-Math.max(0,Math.min(1,n.tension||0)),this.sincFilterSize_=n.sincFilterSize||1,this.kernel_=(s=n.sincWindow||q_,function(e){return function(e){return 0===e?1:Math.sin(Math.PI*e)/(Math.PI*e)}(e)*s(e)})}point(e,t){return this.getClippedInput_(Math.round(this.scaleFactor_*e),t)}linear(e,t){e=this.scaleFactor_*e;let n=Math.floor(e);return(1-(e-=n))*this.getClippedInput_(n,t)+e*this.getClippedInput_(n+1,t)}cubic(e,t){e=this.scaleFactor_*e;let n=Math.floor(e),s=[this.getTangent_(n,t),this.getTangent_(n+1,t)],i=[this.getClippedInput_(n,t),this.getClippedInput_(n+1,t)],a=(e-=n)*e,o=e*a;return(2*o-3*a+1)*i[0]+(o-2*a+e)*s[0]+(-2*o+3*a)*i[1]+(o-a)*s[1]}sinc(e,t){e=this.scaleFactor_*e;let n=Math.floor(e),s=n-this.sincFilterSize_+1,i=n+this.sincFilterSize_,a=0;for(let o=s;o<=i;o++)a+=this.kernel_(e-o)*this.getClippedInput_(o,t);return a}getTangent_(e,t){return this.tangentFactor_*(this.getClippedInput_(e+1,t)-this.getClippedInput_(e-1,t))/2}getClippedInput_(e,t){return 0<=e&&et){!function(e,t,n,s){for(let i=0,a=t.length;i=0;i--)t[i]=s.filter(t[i])}(e,a,o,new i(s.LPFOrder||H_[s.LPFType],n,t/2))}else{!function(e,t,n,s){for(let i=0,a=e.length;i=0;i--)e[i]=s.filter(e[i]);G_(e,t,n)}(e,a,o,new i(s.LPFOrder||H_[s.LPFType],t,n/2))}}else G_(e,a,o);return a}function G_(e,t,n){for(let s=0,i=t.length;sA(this,null,function*(){var e;try{if(0===this.state)return;if(2===this.state&&(this.audioDataBuffers=[],this.frameData=[]),this.mediaStream&&1===this.state)return this.isCollectingData=!0,void this.setRecordState(0);"closed"===this.audioContext.state&&(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),"running"!==this.audioContext.state&&(yield this.audioContext.resume()),this.mediaStream=yield navigator.mediaDevices.getUserMedia({audio:{channelCount:1,noiseSuppression:!1,echoCancellation:!1}}),this.scriptProcessorNodeRecord(),this.isCollectingData=!0,this.setRecordState(0)}catch(t){null==(e=this.onError)||e.call(this,t)}})),j(this,"pause",()=>{0===this.state&&(this.isCollectingData=!1,this.setRecordState(1))}),j(this,"resume",()=>{1===this.state&&(this.isCollectingData=!0,this.setRecordState(0))}),j(this,"stop",()=>{var e,t,n,s,i,a,o,r;this.mediaStream&&(this.isCollectingData=!1,null==(n=null==(t=null==(e=this.mediaStream)?void 0:e.getTracks())?void 0:t.forEach)||n.call(t,e=>{e.stop()}),null==(i=null==(s=this.scriptNode)?void 0:s.disconnect)||i.call(s),null==(o=null==(a=this.mediaSourceNode)?void 0:a.disconnect)||o.call(a),this.mediaStream=null,this.mediaSourceNode=null,this.scriptNode=null,this.setRecordState(2),null==(r=this.onStop)||r.call(this))}),j(this,"destroy",()=>{this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&this.audioContext.close().catch(e=>{})}),j(this,"analyzeAudio",e=>{if(!this.mediaSourceNode)return;const{frameLength:t=50}=e||{};if(this.frameLength=t,!this.mediaStream)return;const n=this.audioContext.createAnalyser();n.fftSize=512,this.mediaSourceNode.connect(n);const s=new Uint8Array(n.frequencyBinCount);this.calculateAudioFrame(n,s)}),j(this,"onRecorderStateChange",null),j(this,"onStop",null),j(this,"onError",null),j(this,"onAudioFrame",null),j(this,"onDataAvailable",null),!window.AudioContext&&window.webkitAudioContext,this.audioContext=new(window.AudioContext||window.webkitAudioContext)}scriptProcessorNodeRecord(){this.mediaStream&&(this.mediaSourceNode=this.audioContext.createMediaStreamSource(this.mediaStream),this.scriptNode=this.audioContext.createScriptProcessor(2048,1,1),this.scriptNode.onaudioprocess=e=>{var t;if(!this.isCollectingData)return;const n=z_(e.inputBuffer.getChannelData(0).slice(0),this.audioContext.sampleRate,16e3),s=new Int16Array(n.length);for(let i=0;ie/2).sort((e,t)=>t-e))],i=s[Math.round(s.length/3)];this.frameData.push(i);const a=this.frameData.length-this.frameLength;a>0?this.frameData.splice(0,a):a<0&&this.frameData.unshift(...Array(-a).fill(0)),null==(n=this.onAudioFrame)||n.call(this,{data:this.frameData}),window.requestAnimationFrame(()=>{this.calculateAudioFrame(e,t)})}setRecordState(e){var t;this._state=e,null==(t=this.onRecorderStateChange)||t.call(this,e)}get state(){return this._state}getAudioFile(){if(this.audioDataBuffers.length){const e=(e=>{if(0===e.length)return;const t=e.reduce((e,t)=>e+t.length,0),n=new Float32Array(t);let s=0;for(let i=0;i{const{length:i}=e,a=new ArrayBuffer(44+2*i),o=new DataView(a);$_(o,0,"RIFF"),o.setUint32(4,44+2*i,!0),$_(o,8,"WAVE"),$_(o,12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,1,!0),o.setUint16(22,s,!0),o.setUint32(24,t,!0),o.setUint32(28,t*s*(n/8),!0),o.setUint16(32,s*(n/8),!0),o.setUint16(34,n,!0),$_(o,36,"data"),o.setUint32(40,2*i,!0);let r=44;for(let l=0;lA(null,null,function*(){var e;let t=!1;try{if(Js()&&window.QwenChat){const n=window.QwenChat,s=$s()?"RECORD_AUDIO":"MICROPHONE";if(null==n?void 0:n.requestPermissions){const i=yield n.requestPermissions({permissions:[s]});t="allow"===(null==(e=null==i?void 0:i.result)?void 0:e[s])}}else{const e=yield navigator.mediaDevices.getUserMedia({audio:!0});e&&(setTimeout(()=>{e.getTracks().forEach(e=>e.stop())}),t=!0)}}catch(n){}return t}));let V_=W_;const Q_=({setRecording:e,visible:t=!0})=>{const n=ye(),s=()=>A(null,null,function*(){(yield V_.isPermissionEnabled())?e(!0):Gl.open({type:"error",content:n.t("Permission denied when accessing microphone")})});return t?F.jsx("div",{className:"record-btn-container",children:F.jsx(Si,{title:n.t("Record voice"),children:F.jsx("button",{id:"voice-input-button",className:"record-btn",type:"button",onTouchStart:ii()?s:void 0,onClick:ii()?void 0:s,"aria-label":"Voice Input",style:{opacity:.4,cursor:"not-allowed"},ref:e=>{e&&e.style&&(e.style.opacity="1",e.style.cursor="pointer")},children:F.jsx(pi,{type:"icon-line-microphone-02",className:"microphone-icon"})})})}):null};var K_=function(e,t){return(K_=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function Y_(e,t){function n(){this.constructor=e}K_(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var J_=function(){return function(e,t){this.target=t,this.type=e}}(),X_=function(e){function t(t,n){var s=e.call(this,"error",n)||this;return s.message=t.message,s.error=t,s}return Y_(t,e),t}(J_),Z_=function(e){function t(t,n,s){void 0===t&&(t=1e3),void 0===n&&(n="");var i=e.call(this,"close",s)||this;return i.wasClean=!0,i.code=t,i.reason=n,i}return Y_(t,e),t}(J_),eC={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0},tC=function(){function e(e,t,n){var s=this;void 0===n&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){s._debug("open event");var t=s._options.minUptime,n=void 0===t?eC.minUptime:t;clearTimeout(s._connectTimeout),s._uptimeTimeout=setTimeout(function(){return s._acceptOpen()},n),s._ws.binaryType=s._binaryType,s._messageQueue.forEach(function(e){return s._ws.send(e)}),s._messageQueue=[],s.onopen&&s.onopen(e),s._listeners.open.forEach(function(t){return s._callEventListener(e,t)})},this._handleMessage=function(e){s._debug("message event"),s.onmessage&&s.onmessage(e),s._listeners.message.forEach(function(t){return s._callEventListener(e,t)})},this._handleError=function(e){s._debug("error event",e.message),s._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),s.onerror&&s.onerror(e),s._debug("exec error listeners"),s._listeners.error.forEach(function(t){return s._callEventListener(e,t)}),s._connect()},this._handleClose=function(e){s._debug("close event"),s._clearTimeouts(),s._shouldReconnect&&s._connect(),s.onclose&&s.onclose(e),s._listeners.close.forEach(function(t){return s._callEventListener(e,t)})},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce(function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e},0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=void 0===t?eC.maxEnqueuedMessages:t;this._messageQueue.length=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}(s),a=i.next();!a.done;a=i.next()){var o=a.value;this._callEventListener(e,o)}}catch(r){t={error:r}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(e){return e!==t}))},e.prototype._debug=function(){for(var e=[],t=0;t0&&(r=i*Math.pow(n,this._retryCount-1))>o&&(r=o),this._debug("next delay",r),r},e.prototype._wait=function(){var e=this;return new Promise(function(t){setTimeout(t,e._getNextDelay())})},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,n=t.maxRetries,s=void 0===n?eC.maxRetries:n,i=t.connectionTimeout,a=void 0===i?eC.connectionTimeout:i,o=t.WebSocket,r=void 0===o?function(){if("undefined"!=typeof WebSocket)return WebSocket}():o;if(this._retryCount>=s)this._debug("max retries reached",this._retryCount,">=",s);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),void 0===(l=r)||!l||2!==l.CLOSING)throw Error("No valid WebSocket class provided");var l;this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new r(t,e._protocols):new r(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},a))})}}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new X_(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new Z_(e,t,this))}catch(n){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();const nC={1003:[{reason:"request too fast",message:"Voice input has been used too frequently. Please try again later."}]};class sC{constructor(){j(this,"state","Stop"),j(this,"audioData",[]),j(this,"rws",null),j(this,"taskId",""),j(this,"asrResults",[]),j(this,"sentenceIndex",-1),j(this,"start",e=>{this.rws=new tC(e,"",{connectionTimeout:6e4,maxReconnectionDelay:3e3,minReconnectionDelay:1e3,maxRetries:10}),this.rws.onopen=()=>{if(!this.rws)return;this.taskId=Fe().replaceAll("-",""),this.sentenceIndex=-1;const e=(e=>{const t={header:{message_id:Fe().replaceAll("-",""),task_id:e,namespace:"SpeechTranscriber",name:"StartTranscription"},context:{},payload:{sample_rate:16e3,format:"pcm",enable_intermediate_result:!0,enable_inverse_text_normalization:!0,enable_punctuation_prediction:!0,language:xe.language}};return JSON.stringify(t)})(this.taskId);this.rws.send(e)},this.rws.onclose=e=>{var t,n,s,i;this.state="Stop";const{code:a,reason:o}=e,r=null==(t=nC[a])?void 0:t.find(e=>e.reason===o),l=!!r||!1;if([1e3].includes(a)&&(null==e?void 0:e.isTrusted)||l)return null==(n=this.rws)||n.close(),this.rws=null,null==(s=this.onClose)||s.call(this),void(l&&(null==(i=this.onError)||i.call(this,new Error((null==r?void 0:r.message)||"")),this.state="Error"));this.state="Reconnecting"},this.rws.onerror=e=>{var t,n;"Started"===this.state&&(null==(t=this.rws)||t.close(),this.rws=null,null==(n=this.onError)||n.call(this,new Error(e.message)),this.state="Error")},this.rws.onmessage=e=>{var t,n;this.handleAsrData(JSON.parse(e.data))&&(null==(t=this.onEnd)||t.call(this),null==(n=this.rws)||n.close())}}),j(this,"stop",()=>{this.rws&&"Started"===this.state&&(this.rws.send((e=>{const t={header:{message_id:Fe().replaceAll("-",""),task_id:e,namespace:"SpeechTranscriber",name:"StopTranscription"}};return JSON.stringify(t)})(this.taskId)),this.state="Stopping")}),j(this,"sendAudioData",e=>{"Started"===this.state&&this.rws?(this.audioData.forEach(e=>{var t;null==(t=this.rws)||t.send(e)}),this.audioData=[],this.rws.send(e)):this.audioData.push(e)}),j(this,"handleAsrData",e=>{var t,n,s,i,a;const{name:o=""}=(null==e?void 0:e.header)||{},{result:r=""}=(null==e?void 0:e.payload)||{};switch(o){case"TranscriptionStarted":this.state="Started";break;case"SentenceBegin":this.asrResults.push("");break;case"TranscriptionResultChanged":case"SentenceEnd":this.asrResults[this.asrResults.length-1]=r,null==(t=this.onMessage)||t.call(this,{result:this.asrResults.join("")});break;case"TranscriptionCompleted":this.state="Stop";break;case"TaskFailed":null==(n=this.onError)||n.call(this,new Error(o)),this.state="Error";break;case"TranscriptionResult":(null==(s=null==e?void 0:e.payload)?void 0:s.index)!==this.sentenceIndex&&(this.sentenceIndex=null==(i=null==e?void 0:e.payload)?void 0:i.index,this.asrResults.push("")),this.asrResults[this.asrResults.length-1]=r,null==(a=this.onMessage)||a.call(this,{result:this.asrResults.join("")})}return["TranscriptionCompleted","TaskFailed"].includes(o)}),j(this,"onError",null),j(this,"onEnd",null),j(this,"onClose",null),j(this,"onMessage",null)}}const iC=class e{constructor(){j(this,"speechRecognition",null),j(this,"start",()=>{if(!e.isSupport)return;this.speechRecognition.continuous=!0,this.speechRecognition.interimResults=!0;let t=!0;this.speechRecognition.onresult=e=>A(this,null,function*(){var n;const{results:s}=e,i=s[s.length-1],{transcript:a}=i[0],{isFinal:o}=i;null==(n=this.onMessage)||n.call(this,{result:a,begin:t}),t=o}),this.speechRecognition.onend=()=>{var e;null==(e=this.onEnd)||e.call(this)},this.speechRecognition.onerror=e=>{var t;null==(t=this.onError)||t.call(this,new Error(null==e?void 0:e.error))},this.speechRecognition.start()}),j(this,"stop",()=>{e.isSupport&&this.speechRecognition.stop()}),j(this,"onMessage",null),j(this,"onEnd",null),j(this,"onError",null),e.isSupport&&(this.speechRecognition=new(window.SpeechRecognition||window.webkitSpeechRecognition))}};j(iC,"isSupport","SpeechRecognition"in window||"webkitSpeechRecognition"in window);let aC=iC;class oC{constructor(){j(this,"currentTime",0),j(this,"intervalTimeout",null),j(this,"pausedElapsedTime",0),j(this,"isPaused",!1),j(this,"start",e=>{this.stop(),this.isPaused=!1,this.pausedElapsedTime=0;const t=e||0;this.currentTime=Date.now()-1e3*t,this.intervalTimeout=setInterval(()=>{var e;const t=Math.round((Date.now()-this.currentTime)/1e3);null==(e=this.onTimeChange)||e.call(this,{time:t,formatTime:this.format(t)})},1e3)}),j(this,"stop",()=>{this.intervalTimeout&&(clearInterval(this.intervalTimeout),this.intervalTimeout=null),this.isPaused=!1,this.pausedElapsedTime=0,this.currentTime=0}),j(this,"pause",()=>{!this.isPaused&&this.intervalTimeout&&(this.pausedElapsedTime=Math.round((Date.now()-this.currentTime)/1e3),this.intervalTimeout&&(clearInterval(this.intervalTimeout),this.intervalTimeout=null),this.isPaused=!0)}),j(this,"resume",()=>{this.isPaused&&this.start(this.pausedElapsedTime)}),j(this,"format",e=>(""+e%60).padStart(2,"0")),j(this,"onTimeChange",null)}}const rC=Ls()?43:150,lC=new V_,cC=({className:e="",onUpdateRecording:t,onCallbackAsrResult:n})=>{const s=ye(),i=dR(e=>e.mobile),[a,o]=D.useState(Array(rC).fill(0)),r=D.useRef(!1),l=D.useRef(new sC),c=D.useRef(new aC),d=D.useRef(lC),u=D.useRef(new oC),h=D.useCallback(()=>{u.current.stop(),l.current.stop(),c.current.stop(),d.current.stop()},[]),m=D.useCallback(()=>{h(),null==t||t(!1),null==n||n("")},[n,t,h]),p=D.useCallback(()=>{r.current=!0,h(),null==t||t(!1)},[t,h]),g=D.useCallback(()=>{d.current.onAudioFrame=({data:e})=>{o([...e])},d.current.start().then(()=>{u.current.onTimeChange=({time:e})=>{e>=60&&p()},u.current.start(),d.current.analyzeAudio({frameLength:rC})});const e=e=>{const{result:t}=e;null==n||n(t)},t=()=>{},i=e=>{const t=e.message?s.t(e.message):s.t("Network error");Gl.open({type:"error",content:t}),m()};try{d.current.onDataAvailable=e=>{l.current.sendAudioData(e)},l.current.onMessage=e,l.current.onClose=t,l.current.onError=i;let n="wss://chat.qwen.ai";if("prod"!==nn){let e=location.hostname;"localhost"===e&&(e="pre-chat.qwen.ai"),n=`wss://${e}`}l.current.start(`${n}/api/v1/asr/wsgu_asr?token=${localStorage.token}`)}catch(a){Gl.open({type:"error",content:(null==a?void 0:a.message)||s.t("Network error")}),m()}},[m,p,s,n]);return D.useEffect(()=>{g()},[]),i?F.jsx("div",{className:`voice-recording-root ${e}`,children:F.jsxs("div",{className:"controls-row",children:[F.jsx("button",{type:"button",className:"button",onClick:m,children:F.jsx(pi,{type:"icon-line-x-02"})}),F.jsx("div",{className:"audio-bar",children:a.map(e=>F.jsx("div",{className:"audio-bar-item",style:{height:`${Math.min(100,Math.max(12,e))}%`}},Fe()))}),F.jsx("button",{type:"button",className:"button button-confirm",onClick:p,children:F.jsx(pi,{type:"icon-line-check-02"})})]})}):F.jsx("div",{className:`pc-voice-recording ${e}`,children:F.jsxs("div",{className:"pc-voice-recording-controls",children:[F.jsx("button",{type:"button",className:"button-cancel",onClick:m,children:F.jsx(pi,{type:"icon-line-x-02"})}),F.jsx("div",{className:"audio-bar",children:a.map(e=>F.jsx("div",{className:"audio-bar-item",style:{height:`${Math.min(100,Math.max(12,e))}%`}},Fe()))}),F.jsx("button",{type:"button",className:"button-confirm",onClick:p,children:F.jsx(pi,{type:"icon-line-check-02"})})]})})},dC=({projectId:e,inDetail:t=!1,scrollDownBtnVisible:n=!1,onScrollDown:s=()=>{},onScrollTop:i=()=>{}})=>{const{i18n:a}=ye(),{id:o}=Ge(),r=Rs(e=>e.selectedText),l=Rs(e=>e.setSelectedText),c=js(e=>e.setEmitSendPromptType),d=Rs(e=>e.selectedTextPosition),u=Rs(e=>e.selectedTextId),h=Rs(e=>e.selectedTextIndex),m=dR(e=>e.mobile),p=Rs(e=>e.taskRunning),g=Rs(e=>e.visionGenerating),f=Kh(e=>e.files),v=Kh(e=>e.inputValue),y=js(e=>e.currentInputFeature),b=js(e=>e.currentInputSubType),x=js(e=>e.isStopDisabled),w=js(e=>e.history.messages),_=js(e=>e.history.currentId),{messageInputMode:k,isShowOmniButton:j,currentI18nRecommend:T,onUpdateSeparationNeeds:E}=(e=>{const{inDetail:t=!1,chatId:n,projectId:s}=e||{},i=Rs(e=>e.selectedText),[a,o]=D.useState({}),r=cR(e=>e.mobile),l=js(e=>e.currentInputFeature),c=js(e=>e.currentInputSubType),d=Rs(e=>e.thinkingEnabled),u=Rs(e=>e.mcpEnabled),h=Kh(e=>e.files),m=Kh(e=>e.inputValue),p=Kh(e=>e.setMessageType),g=hR(e=>e.setThumbSrcArr),[f,v]=D.useState("combination"),[y,b]=D.useState({}),x=D.useMemo(()=>{const e=[yt.DeepResearch,yt.DeepThinking,yt.TRAVEL_FEEDBACK,yt.TRAVEL_RESEARCH,yt.DeepResearchWebDev,yt.INTERRUPT];return d&&(void 0===c||!e.includes(c))},[d,c]),w=D.useMemo(()=>[x?"thinking":"",u?"mcp":""].filter(e=>""!==e),[x,u]),_=D.useMemo(()=>{let e=!1;return e=s?""===m&&!h.length:""===m&&!h.length&&!n,e},[s,m,h.length,n]),S=D.useMemo(()=>a||{},[a]),k=D.useCallback(e=>{b(t=>Object.keys(e).some(n=>t[n]!==e[n])?C(C({},t),e):t)},[]),j=D.useCallback(()=>{o(np),g(null==sp?void 0:sp.thumbSrcArr)},[]);return D.useEffect(()=>{j()},[]),D.useEffect(()=>{p({subChatType:c,chatType:l})},[l,c]),D.useEffect(()=>{k({filesIsNotEmpty:!r&&!!h.length})},[h,r]),D.useEffect(()=>{k({quoteTextIsNotEmpty:!!i.length})},[i]),D.useEffect(()=>{k({inDetailAndHasMode:t&&l!==yt.Txt2Txt,manualChooseMode:!t&&l!==yt.Txt2Txt})},[l,t,k]),D.useEffect(()=>{k({mcpEnabled:u&&l===yt.Txt2Txt})},[l,u,k]),D.useEffect(()=>{const e=Object.values(y).filter(Boolean);v(e.length?"separation":"combination")},[y]),{messageInputMode:f,featureSwitchList:w,isShowOmniButton:_,currentI18nRecommend:S,onUpdateSeparationNeeds:k}})({inDetail:t,chatId:o,projectId:e}),{isPlanning:N,isDeepResearchRounds:I,isDrAnswerPhase:M,prevDrDone:R}=(()=>{const e=js(e=>e.history),t=Rs(e=>e.taskRunning),n=js(e=>e.currentInputFeature),s=js(e=>e.currentInputSubType),i=js(e=>e.history.messages),a=js(e=>e.history.currentId),o=D.useMemo(()=>n===yt.DeepResearch&&s===yt.DeepResearch||n===yt.DeepResearch&&s===yt.INTERRUPT||n!==yt.DeepResearch,[n,s]);return{isDeepResearchRounds:D.useMemo(()=>{var t,n;if(o&&a){const s=(null==(n=null==(t=e.messages[a])?void 0:t.content_list)?void 0:n[0])||"";return!s||!(!s||"answer"===s.phase)}return!1},[o,a,e.messages]),isPlanning:D.useMemo(()=>{const e=n===yt.DeepResearch&&s===yt.DeepResearch,i=n===yt.DeepResearch&&s===yt.INTERRUPT;return(e||i)&&t},[n,s,t]),isDrAnswerPhase:D.useMemo(()=>{var e,t;return!!(null==(t=null==(e=i[a||""])?void 0:e.content_list)?void 0:t.some(e=>"answer"===e.phase))},[a,i]),prevDrDone:D.useMemo(()=>{const e=Lu(i,a||"");return(null==e?void 0:e.done)||!1},[a,i])}})(),{filesManager:P,fileDragging:L,uploadHandler:O,handleCloseFileCard:q}=Zm(),{sendingNotAllowed:U,sendButtonStatus:H,handleSend:B,resetInputHandler:z}=(e=>{const{chatId:t,projectId:n,isDrAnswerPhase:s,prevDrDone:i,onScrollDown:a}=e,{i18n:o}=ye(),r=cR(e=>e.mobile),l=Kh(e=>e.setInputValue),c=Kh(e=>e.messageType),d=Kh(e=>e.files),u=Kh(e=>e.inputValue),h=Kh(e=>e.onPromptSend),m=Kh(e=>e.setMobileRecommendDetailVisible),p=js(e=>e.setEmitSendPromptType),g=js(e=>e.currentInputFeature),f=js(e=>e.currentInputSubType),v=Rs(e=>e.taskRunning),y=Rs(e=>e.visionGenerating),b=Rs(e=>e.setWelcomeModalShow),x=cR(e=>e.isDisableGuestAccess),w=pw(e=>e.chatProjectId),_=pw(e=>e.setChatProjectId),C=js(e=>e.history.messages),S=js(e=>e.history.currentId),k=D.useMemo(()=>{var e;return!!(null==(e=C[S||""])?void 0:e.done)},[C,S]),j=D.useMemo(()=>{const e=""!==(null==u?void 0:u.trim())||!!d.length;switch(f){case yt.INTERRUPT:return!e&&(v||y)||s&&!i?"stop":"send";case yt.DeepResearch:return!e&&(v||y)||s&&!k?"stop":"send";default:return v||y?"stop":"send"}},[f,v,y,s,i,u,d.length,k]),T=D.useMemo(()=>f===yt.INTERRUPT&&!k,[f,k]),E=D.useCallback(e=>A(null,null,function*(){if(p(mt.CHAT),wR()&&x)b(!0);else{if((null==e?void 0:e.projectId)&&_(e.projectId),g===yt.ImageGeneration){let t="";const n=(null==e?void 0:e.inputText)||Kh.getState().inputValue||"",s=d.filter(e=>"image"===e.showType);if(""===n.trim()&&s.length&&(t=o.t("Please enter a prompt describing how you'd like to edit your image.")),t)return void vi.openOnce({type:"caution",content:t})}h(e)}}),[g,d,o,x,h,_,p,b]),N=D.useCallback((e,t)=>{switch(e){case"stop":bM.stopResponse();break;case"send":if(T||"stop"===j)return;if(S){const e=Te(C),t=C[S];(null==t?void 0:t.isMultiResponse)&&t.parentId&&(C[t.parentId].childrenIds.forEach(t=>{e[t].isMultiResponse=!1}),bM.updateChatHistory({messages:e,currentId:S}))}bM.closeShowControls(),E({inputText:null!=t?t:u,projectId:n||w}),g===yt.Travel&&r&&m(!1),setTimeout(()=>{null==a||a()},0)}},[E,w,S,g,u,C,r,n,j,a,T,m]),I=D.useCallback((e,n)=>{l(e),"send"===n&&(E({inputText:e}),Du("suggest",t,c))},[E,t,c,l]),M=D.useCallback(e=>{l(e),N("send",e)},[N,l]);return{sendingNotAllowed:T,sendButtonStatus:j,resetInputHandler:I,beforePromptSend:E,handleSend:N,onInputCallback:M}})({chatId:o,projectId:e,isDrAnswerPhase:M,prevDrDone:R,onScrollDown:s}),{recording:G,onUpdateRecording:$,onCallbackAsrResult:W}=(e=>{const{onUpdateSeparationNeeds:t=()=>{}}=e||{},[n,s]=D.useState(!1),i=Kh(e=>e.setInputValue);return{recording:n,onUpdateRecording:D.useCallback(e=>{s(e),t({recording:e})},[t]),onCallbackAsrResult:D.useCallback(e=>{i(e)},[i])}})({onUpdateSeparationNeeds:E});(()=>{const{isAllDisabled:e}=Xm(),t=Kh(e=>e.files),n=js(e=>e.currentInputFeature),s=js(e=>e.currentInputSubType),i=js(e=>e.history.messages),a=D.useMemo(()=>{const t=[yt.Podcast,yt.DeepResearchWebDev].includes(s)&&bM.shareHistory;return{enable:!e&&!t,disabled:!1}},[s,e]),o=D.useMemo(()=>{const e=Object.values(i||{});if(e.length>0&&e.find(e=>"assistant"===e.role&&[yt.ImageGeneration,yt.ImageEdit].includes(e.chat_type)))return{enable:!1,disabled:!1,msg:""};const s=[yt.ImageGeneration,yt.VideoGeneration].includes(n);return s&&(null==t?void 0:t.find(e=>"image"===e.type))?{enable:!1,disabled:!1,msg:""}:{enable:s,disabled:!1,msg:""}},[n,t,i]),r=D.useMemo(()=>({enable:n===yt.DeepResearch,disabled:!1,msg:""}),[n]),l=D.useMemo(()=>({enable:n===yt.Slides,disabled:!1,msg:""}),[n]);D.useEffect(()=>{const e=Kh.getState().messageInputPermissions;Kh.setState({messageInputPermissions:S(C({},e),{enableSizeSelector:o,enableUpload:a,enableAdvanced:r,enableDesignStyle:l})})},[o,a,r,l])})();const{renderTipsModels:V}=Xu({filesManager:P}),K=D.useMemo(()=>G?a.t("I'm listening"):N?a.t("Provide additional details..."):((e,t)=>{const n=it();switch(e){case yt.Artifacts:return t===yt.WebDev?n.t("Describe the web page you want to generate."):n.t("Describe the artifacts you want to generate.");case yt.DeepResearch:return n.t("Describe the themes you want to research.");case yt.ImageGeneration:return n.t("Describe the image you want to generate.");case yt.VideoGeneration:return n.t("Describe the video you want to generate.");default:return n.t("How can I help you today?")}})(y,b),[y,b,a.language,N,G]),Y=D.useCallback(()=>{const e={type:"ask",messageId:w[_||""].id||void 0,inputText:v,content:{text:r},extra:{meta:{position:d,quoteId:u,quoteIndex:h}}};c(mt.ASK),bM.seleteOperation(e),l("")},[_,v,w,r,u,h,d,c,l]),J=D.useMemo(()=>{const e=w[_||""];return[yt.ImageGeneration,yt.VideoGeneration].includes(null==e?void 0:e.chat_type)||x||g},[_,x,w,g]),X=D.useMemo(()=>{if(j&&!p&&!g)return F.jsx(Zw,{});const e=(""===v||""===(null==v?void 0:v.trim()))&&!f.length,t=p||g?J:e;return F.jsx(e_,{buttonDisabled:t||U,status:H,onClick:r?Y:B,disabledStatusCallbackEnabled:y===yt.ImageEdit?["send"]:[]})},[j,p,g,v,f.length,y,J,U,H,r,Y,B]),Z=D.useMemo(()=>G?null:F.jsxs("div",{className:"message-input-right-button",children:[m?F.jsx(Q_,{setRecording:$,visible:m&&!v&&!wR()}):F.jsxs(F.Fragment,{children:[F.jsx(Xw,{}),F.jsx(Q_,{setRecording:$,visible:!v&&!wR()})]}),F.jsx("div",{className:"message-input-right-button-send",children:X})]}),[G,m,$,v,X]),ee=D.useMemo(()=>G?null:F.jsx($w,{messageInputMode:k,isPlanning:!!N,uploadHandler:O,onUpdateSeparationNeeds:E}),[G,k,N,O,E]),te=D.useMemo(()=>{if(y===yt.Txt2Txt&&!t&&!e)return F.jsx(l_,{currentI18nRecommend:T||{},onChange:e=>{z(e.inputText,"send")}})},[y,T,t,e,z]),ne=D.useMemo(()=>F.jsxs(F.Fragment,{children:[F.jsx(D_,{}),!!f.length&&F.jsx("div",{className:"message-input-column-file",children:F.jsx(i_,{role:"user",files:f,onClose:q,onReUpload:e=>A(null,null,function*(){var t,n,s;const i=f[e];i&&"failed"===(null==(s=null==(n=null==(t=i.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)?P.startParse(i,!0):i&&(i.uploadTaskId?yield fu.resumeUpload(i.uploadTaskId):P.retryFile(i))})})})]}),[f,P,r,q,k]),{containerRef:se,contentRef:ie,calcHeight:ae}=(e=>{const{upadteDependences:t=[]}=e,n=D.useRef(null),s=D.useRef(null),i=D.useCallback(()=>{if(!n.current||!s.current)return;const e=s.current.clientHeight;n.current.style.height=`${e}px`},[]);return D.useEffect(()=>{i()},t),{containerRef:n,contentRef:s,calcHeight:i}})({upadteDependences:[te,ne]}),oe=D.useMemo(()=>F.jsxs("div",{className:"message-input-container-area",children:["combination"===k&&ee,F.jsx(t_,{inDetail:t,calcInputContainerHeight:ae,chatId:o,filesManager:P,handleSend:r?Y:B,messageInputMode:k,onUpdateSeparationNeeds:E,isDeepResearchRounds:I,placeHolder:K,readOnly:G}),"combination"===k&&Z]}),[k,ee,t,o,P,r,Y,B,E,I,K,G,Z]),re=D.useMemo(()=>m?null:F.jsx("div",{ref:se,className:"message-input-container",children:F.jsxs("div",{ref:ie,children:[ne,oe,"separation"===k?F.jsxs("div",{className:"message-input-column-footer",children:[ee,Z,G&&F.jsx(cC,{onUpdateRecording:$,onCallbackAsrResult:W})]}):te]})}),[m,G,se,ie,ne,oe,k,ee,Z,$,W,te]),le=D.useMemo(()=>m?F.jsx("div",{ref:se,className:Q("message-input-container",{"message-input-container-separation":"separation"===k||f.length}),children:F.jsxs("div",{ref:ie,children:[ne,oe,"separation"===k?F.jsx("div",{className:"message-input-column-footer",children:G?F.jsx(cC,{onUpdateRecording:$,onCallbackAsrResult:W}):F.jsxs(F.Fragment,{children:[ee,Z]})}):null]})}):null,[se,ie,f.length,k,m,W,$,G,oe,ne,ee,Z]),ce=D.useMemo(()=>t||e||Ne(T)?null:F.jsx(O_,{currentI18nRecommend:T,resetInputHandler:z}),[T,t,e,z]),de=D.useMemo(()=>"iPad"===Ws(),[]),ue=D.useMemo(()=>(de||!m&&!t)&&!e,[m,de,t,e]);return F.jsx("div",{className:Q({"message-input":ue}),style:{width:"100%"},children:F.jsxs("div",{className:Q("message-input-wrapper",{"message-input-wrapper-expand":"separation"===k,"message-input-wrapper-position":ue}),children:[F.jsx(Aw,{onScrollDown:s,onScrollTop:i,scrollDownBtnVisible:n}),m&&ce,re,le,!m&&F.jsx(r_,{textLength:(null==v?void 0:v.length)||0}),!m&&ce,V,F.jsx(o_,{show:L})]})})},uC=({projectId:e,projectChats:t=[]})=>{const n=ye(),s=pw(e=>e.setProjectChats),{getProjectChatList:i}=ig(),[a,o]=D.useState(null),{getPinnedChatListData:r}=Tg(),l=Ns(e=>e.setPinnedChats),c=()=>A(null,null,function*(){const t=yield i(e);Array.isArray(t)&&s(t),Jr();const n=yield r();Array.isArray(n)&&l(n)});return F.jsxs("div",{className:"project-chats",children:[(null==t?void 0:t.length)>0,F.jsx("div",{className:"project-chats-title",children:n.t("Chats")}),t.map(e=>F.jsx(bf,{id:e.id,projectId:e.project_id,time:n.t(DR(1e3*e.created_at)),title:e.title,selected:!0,onSelect:()=>{},onUnSelect:()=>{},onChange:c,isActive:a===e.id,onEditChatChange:()=>o(e.id),className:"project-chat-list",projectChatPined:e.pinned,isProjectDetailChat:!0,projectDetailChat:e,projectChat:!0},e.id+"project_detail_chat"))]})},hC=({projectId:e=""})=>{const t=Ue(),n=pw(e=>e.projectInfo),s=pw(e=>e.setChatProjectId),i=pw(e=>e.setProjectInfo),a=pw(e=>e.setProjectChats),o=pw(e=>e.setShowEditModal),r=pw(e=>e.setOperationProjectFiles),l=pw(e=>e.projectChats),c=pw(e=>e.setProjectName),d=cR(e=>e.mobile),[u,h]=D.useState(!1),{getProjectChatList:m,getNewProjectList:p}=ig(),[g,f]=D.useState(1),[v,y]=D.useState(!1),b=D.useRef(null),x=D.useCallback(n=>A(null,null,function*(){if(localStorage.getItem("token"))try{const s=yield lw(e);if(!s||!s.success&&"Not_Found"===s.data.code)return p(),o(!1),void t("/");const a=s.data.files.map(e=>S(C({},e),{uploadStatus:"success"}));i(S(C({},n),{fileLength:a.length})),r(a),h(!1)}catch(s){}}),[e,i,r,p,o,t]),w=D.useCallback(()=>A(null,null,function*(){if(localStorage.getItem("token"))try{const t=yield hw(e);t&&x(t.data)}catch(t){}}),[e,x]),_=t=>A(null,null,function*(){const n=yield m(e,t);0===n.length&&y(!0),1===t?Array.isArray(n)&&a(n):Array.isArray(n)&&a([...l,...n])});D.useEffect(()=>{e&&(h(!0),w(),_(1),s(null),c(""),f(1),y(!1))},[e]);const k=Oe(e=>{const t=e.target,{scrollTop:n,scrollHeight:s,clientHeight:i}=t;s-n-i<=50&&(f(g+1),_(g+1))},200),j=D.useMemo(()=>F.jsx(Iw,{projectTitle:n.name,projectIns:n.custom_instruction}),[n.custom_instruction,n.name]),T=D.useMemo(()=>u&&d?F.jsxs("div",{className:"project-content-chats-skeleton",children:[F.jsx(Li,{className:"project-content-chats-skeleton-item",style:{width:"100%",height:"60px"}}),F.jsx(Li,{className:"project-content-chats-skeleton-item",style:{width:"100%",height:"60px"}}),F.jsx(Li,{className:"project-content-chats-skeleton-item",style:{width:"70%",height:"60px"}})]}):F.jsx(uC,{projectChats:l,projectId:e}),[u,d,l,e]);return u&&!d?F.jsx(sh,{fixed:!1,absolute:!0}):F.jsxs("div",{className:"qwen-project-content "+(l.length>0?"":"qwen-project-content-center"),style:l.length<1&&!d?{transform:"translateY(-102px)"}:{},children:[F.jsxs("div",{className:"qwen-project-content-top "+(l.length>0&&!d?"project-content-top-sticky":""),children:[j,d&&l.length>0&&F.jsx("div",{ref:b,onScroll:e=>{v||k(e)},className:"project-content-chats",children:T}),F.jsx(dC,{projectId:e})]}),!d&&l.length>0&&F.jsx("div",{ref:b,onScroll:e=>{v||k(e)},className:"project-content-chats",children:T})]})},mC=({projectId:e})=>{const t=Rs(e=>e.setTaskRunning),n=Rs(e=>e.setVisionGenerating),s=Kh(e=>e.setShowDetail),i=cR(e=>e.configLoaded);return D.useEffect(()=>{i&&(t(!1),n(!1),s(!1),bM.createChat(),bM.resetChatState(),bM.closeShowControls())},[i]),F.jsx("div",{className:"project-layout",children:F.jsx(hC,{projectId:e})})},pC=D.memo(()=>{const e=ye(),t=Pd(e=>e.fetchUser),n=cR(e=>e.mobile),s=ud(e=>e.setSettingActionMenuItemId),i=D.useRef(""),a="payment_status",o="vaulting_request_id",[r,l]=D.useState(!1),c=D.useRef(""),d=D.useRef(0),u=1e3,h=D.useCallback(()=>A(null,null,function*(){try{const{data:n}=yield WM(c.current);if("SUCCESS"===n.payment_status&&d.current<=60){yield t(),l(!1);const n=window.location.origin+window.location.pathname;history.replaceState(null,"",n),vi.openOnce({type:"success",content:e.t("Successfully upgraded to a Plus account.")})}else"PAYMENT_IN_PROCESS"===n.payment_status&&d.current<=60?(yield HR(u),yield h(),d.current+=1):(l(!1),vi.open({type:"error",content:e.t("Failed to upgrade to a Plus account.")}))}catch(n){l(!1)}}),[u,t,e]),m=D.useCallback(()=>A(null,null,function*(){try{const{data:i}=yield XM(c.current);if("SUCCESS"===i.vaulting_status&&d.current<=60){yield t(),l(!1);const a=window.location.origin+window.location.pathname;history.replaceState(null,"",a),i.is_newly_created?vi.openOnce({type:"success",content:e.t("Card added successfully!")}):vi.openOnce({type:"warning",content:e.t("Duplicate bank card not allowed.")}),n&&s("subscription")}else"VAULTING_IN_PROCESS"===i.vaulting_status&&d.current<=60?(yield HR(u),yield m(),d.current+=1):(l(!1),vi.open({type:"error",content:e.t("Couldn't add this card!")}))}catch(i){l(!1)}}),[u,t,e,n,s]),p=D.useCallback(()=>{const e=new URL(window.location.href),t=e.searchParams.get(a);t&&(i.current="payment_status",c.current=t);const n=e.searchParams.get(o);if(n&&(i.current="vaulting_request_id",c.current=n),c.current){l(!0);const e=new URLSearchParams(window.location.search);e.delete(a),e.delete(o);const t=`${window.location.pathname}${e.size>0?`?${e.toString()}`:""}`;window.history.replaceState({},"",t)}},[]);return D.useEffect(()=>{p()},[]),D.useEffect(()=>{r&&(d.current=0,"payment_status"===i.current&&h(),"vaulting_request_id"===i.current&&m())},[r]),r&&F.jsx("div",{className:"chat-upgrade-loading",children:F.jsxs("div",{className:"chat-upgrade-loading-container",children:[F.jsx(Ui,{fontSize:32,borderWidth:3,className:"loading-size",type:"primary"}),F.jsx("div",{className:"chat-upgrade-loading-text",children:e.t("payment_status"===i.current?"Retrieving payment results...":"Retrieving results for the newly added bank card")}),F.jsx("div",{className:"chat-upgrade-loading-tip",children:e.t("This may take a moment. Please do not leave.")})]})})}),gC=D.memo(()=>{const{t:e}=ye(),t=hR(e=>e.showRegionUnenablePayment),n=hR(e=>e.setShowRegionUnenablePayment);return F.jsx(wi,{visible:t,headerBorderNone:!0,size:"small",title:e("Subscription is not available in your region"),onCancel:()=>n(!1),actions:[{text:e("Got it"),type:"brandprimary",size:"small",rounded:"circle",onClick:()=>{n(!1)}}],children:e("Sorry, Subscription is currently not available in your region. We're actively working to expand support and hope to make it available as soon as possible. Thank you for your patience!")})}),fC=({notifications:e,onClose:t})=>{const{i18n:n}=ye(),s=cR(e=>e.mobile),[i,a]=D.useState(0),o=D.useRef(null),r=Jh(e=>e.settings.ui.language),l=ud(e=>e.language),c=D.useCallback(e=>F.jsx("div",{className:"qwen-chat-comp-update-modal-top",style:{backgroundImage:`url(${e})`}}),[]),d=D.useCallback(e=>F.jsxs("div",{className:"update-dropdown-modal-content update-dropdown-modal-content-has-bottom",children:[F.jsx("div",{className:"update-dropdown-modal-header-title-container",children:e.title&&F.jsx("div",{className:"update-dropdown-modal-header-title",children:e.title})}),F.jsx("div",{className:"qwen-chat-comp-update-modal-bottom-content",children:F.jsx(Ay,{content:e.content})})]},e.title),[]),u=D.useMemo(()=>{const a=e.map(e=>e.payload);return F.jsxs("div",{className:"qwen-chat-comp-update-modal-bottom-content-footer",children:[!s&&F.jsx(xi,{className:"qwen-chat-comp-update-modal-bottom-content-footer-back-button",type:"tertiary",rounded:"circle",disabled:i<=0,buttonStyle:{visibility:i<=0?"hidden":"visible"},onClick:()=>{var e;i<=0||null==(e=o.current)||e.prev()},children:n.t("Back")}),!s&&a.length>1&&(null==a?void 0:a.length)-1!==i?F.jsx(xi,{type:"brandprimary",rounded:"circle",onClick:()=>{var e;null==(e=o.current)||e.next()},className:"qwen-chat-comp-update-modal-bottom-content-footer-continue-button",children:n.t("Continue")}):F.jsx(xi,{type:"brandprimary",rounded:"circle",size:s?"large":"middle",onClick:t,className:"qwen-chat-comp-update-modal-bottom-content-footer-sure-button",children:n.t("Try now")})]})},[i,n,s,t,e]),h=D.useMemo(()=>l||r||"en-US",[r,l]),m=D.useCallback(e=>{pl("notificationExp",{params:{et:"EXP"},paramsExtend:{notification_type:"modal",notification_id:e||""}})},[]),p=D.useMemo(()=>{const t=e.map(e=>S(C({},e.payload),{id:e.id})).map(e=>{var t;const n=null==(t=e.language)?void 0:t[h];return(null==n?void 0:n.title)&&(null==n?void 0:n.content)?{title:null==n?void 0:n.title,content:null==n?void 0:n.content,imageUrl:e.imageUrl}:e});return F.jsx("div",{className:"qwen-chat-comp-update-modal-bottom-content",children:F.jsx(me,{className:"qwen-chat-comp-update-modal-bottom-content-carousel",arrows:!1,infinite:!1,speed:300,ref:o,beforeChange:(t,n)=>{m(e[n].id),a(n)},dots:1!==t.length,children:t.map((t,n)=>{var s,i;return F.jsxs(D.Fragment,{children:[t.imageUrl&&""!==t.imageUrl&&c(t.imageUrl||""),d(t)]},null!=(i=null==(s=e[n])?void 0:s.id)?i:`update-modal-slide-${n}`)})})})},[e,c,d,m]),g=D.useMemo(()=>F.jsxs(F.Fragment,{children:[p,u]}),[u,p]);return F.jsxs("div",{className:"qwen-chat-comp-update-modal",children:[F.jsx("div",{className:"qwen-chat-comp-update-modal-close",onClick:t,children:F.jsx(pi,{type:"icon-close-4",className:"qwen-chat-comp-update-modal-close-icon"})}),g]})},vC=e=>{const{open:t,notifications:n,onClose:s}=e;return F.jsx(wi,{visible:t,width:640,size:"large",className:"update-modal-container",headerBorderNone:!1,maskClosable:!1,onCancel:s,children:F.jsx(fC,{onClose:s,notifications:n})})},yC=e=>{const{open:t,notifications:n,onClose:s}=e;return t?F.jsx(Ti,{open:t,className:"update-modal-mobile-popup-container",maskClosable:!1,heightType:"half",onClose:s,children:F.jsx(fC,{onClose:s,notifications:n})}):null},bC=[],xC=D.memo(()=>{const{markBatchNotificationsAsRead:e}=Vp(),t=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_notification}),n=zp(e=>e.wsNotifications),s=zp(e=>e.dismissedNotifications),i=zp(e=>e.prePullCompleteNotificationIds),{updateModalNotification:a,outdatedModalIds:o}=D.useMemo(()=>{const e=n.filter(e=>{const t=e.payload;return e.event_type===ln&&"modal"===(null==t?void 0:t.showType)&&i.includes(e.id)});if(e.length<=10)return{updateModalNotification:e,outdatedModalIds:[]};const t=[...e].sort((e,t)=>{const n=e.send_time||0;return(t.send_time||0)-n});return{updateModalNotification:t.slice(0,10),outdatedModalIds:t.slice(10).map(e=>e.id)}},[n,i]),r=D.useMemo(()=>n.filter(e=>{const t=e.payload;return e.event_type===ln&&"popover"===(null==t?void 0:t.showType)&&i.includes(e.id)&&!s.includes(e.id)}),[n,i,s]),{updatePopoverNotification:l,outdatedPopoverIds:c}=D.useMemo(()=>{if(0===r.length)return{updatePopoverNotification:bC,outdatedPopoverIds:[]};const e=[...r].sort((e,t)=>{const n=e.send_time||0;return(t.send_time||0)-n});return{updatePopoverNotification:[e[0]],outdatedPopoverIds:e.slice(1).map(e=>e.id)}},[r]),d=cR(e=>e.mobile),[u,h]=D.useState(!1),m=0===a.length||!u;(e=>{const t=zp(e=>e.addDismissNotification),n=Jh(e=>e.settings.ui.language),s=ud(e=>e.language),{markNotificationAsRead:i}=Vp(),a=D.useRef(new Map),o=D.useRef(new Map),r=D.useRef(new Map),l=D.useRef(e);l.current=e;const c=D.useMemo(()=>e.map(e=>e.id).join(","),[e]),d=D.useMemo(()=>s||n||"en-US",[n,s]),u=D.useCallback(e=>{const t=e.payload;return t.popoverMountId?`${Kp}_${t.popoverMountId}`:""},[]),h=D.useCallback(e=>{const t=e.language;return((e,t)=>{if(!(null==t?void 0:t.title)||!(null==t?void 0:t.content)||""!==e.btnText&&!(null==t?void 0:t.btnText))return e;const n=C({},e);return e.title&&t.title&&(n.title=t.title),e.content&&t.content&&(n.content=t.content),e.btnText&&t.btnText&&(n.btnText=t.btnText),n})(e,null==t?void 0:t[d])},[d]),m=D.useCallback(e=>{pl("notificationExp",{params:{et:"EXP"},paramsExtend:{notification_type:"popover",notification_id:e||""}})},[]),p=D.useCallback((e,t)=>{pl("notificationBtnLink",{params:{et:"CLK"},paramsExtend:{notification_type:"popover",notification_id:e||"",link:t}})},[]),g=D.useCallback(e=>{i(e.id),f(e,!1,!0);const t=e.payload;t.btnLink&&(p(e.id,t.btnLink),window.location.assign(t.btnLink))},[i]),f=D.useCallback((e,n,s=!1)=>{const l=u(e);if(!l)return;r.current.set(l,n);const c=a.current.get(l);if(c){const t=h(e.payload),s=o.current.get(l)||"",i=O.createElement(Qp,{payload:t,onClose:()=>{f(e,!1,!0)},onBtnClick:()=>g(e),open:n,children:O.createElement("div",{dangerouslySetInnerHTML:{__html:s}})});c.render(O.createElement(O.Suspense,{fallback:null},i))}n||(i(e.id),t([e.id]))},[u,h,g,i,t]),v=D.useCallback(e=>{f(e,!1,!0)},[f]),y=D.useCallback((e,t=0)=>{var n;const s=u(e);if(!s)return;const i=document.getElementById(s);if(!i)return void(t<5&&setTimeout(()=>{y(e,t+1)},100));const l=h(e.payload),c=a.current.get(s);let d;if(c)d=o.current.get(s)||"";else{const e=i.cloneNode(!0);e.removeAttribute("id"),d=e.outerHTML,o.current.set(s,d)}const p=null==(n=r.current.get(s))||n;r.current.set(s,p),p&&m(e.id);const f=O.createElement(O.Suspense,{fallback:null},(b=p,O.createElement(Qp,{payload:l,onClose:()=>v(e),onBtnClick:()=>g(e),open:b,onOpenChange:t=>{r.current.set(s,t),t||v(e)},children:O.createElement("div",{dangerouslySetInnerHTML:{__html:d}})})));var b;if(c)c.render(f);else{const e=z.createRoot(i);e.render(f),a.current.set(s,e)}},[u,h,v,g]),b=D.useCallback(()=>{a.current.forEach((e,t)=>{document.getElementById(t)||(e.unmount(),a.current.delete(t),o.current.delete(t),r.current.delete(t))})},[]);D.useEffect(()=>{b();const e=setTimeout(()=>{l.current.forEach(e=>{y(e)})},300);return()=>{clearTimeout(e)}},[c,y,b]),D.useEffect(()=>{l.current.forEach(e=>{const t=u(e);a.current.get(t)&&y(e)})},[d,y]),D.useEffect(()=>()=>{a.current.forEach(e=>{e.unmount()}),a.current.clear(),o.current.clear(),r.current.clear()},[])})(D.useMemo(()=>t&&m?l:bC,[t,m,l])),D.useEffect(()=>{t&&0!==c.length&&e(c)},[t,e,c]),D.useEffect(()=>{t&&0!==o.length&&e(o)},[t,e,o]);const p=()=>{h(!1),t&&e(a.map(e=>e.id))};return D.useEffect(()=>{t&&(null==a?void 0:a.length)>0?h(!0):h(!1)},[t,a.length]),t?d?F.jsx(yC,{open:u,onClose:p,notifications:a}):F.jsx(vC,{open:u,onClose:p,notifications:a}):null}),wC=Object.freeze(Object.defineProperty({__proto__:null,default:xC},Symbol.toStringTag,{value:"Module"})),_C={cookieConfirm:"index-module__cookie-confirm___fH7D6",cookieConfirmContainer:"index-module__cookie-confirm-container___No5ek",cookieDes:"index-module__cookie-des___bpOsX",cookieDesIcon:"index-module__cookie-des-icon___QnMbH",textUnderline:"index-module__text-underline___-0iNn",cookieConfirmBtn:"index-module__cookie-confirm-btn___TLZz-",cookieConfirmHeader:"index-module__cookie-confirm-header___7koE-",cookieConfirmCloseContainer:"index-module__cookie-confirm-close-container___954Dz",cookieConfirmHeaderTitle:"index-module__cookie-confirm-header-title___xH4v1",cookieConfirmHeaderCloseContainer:"index-module__cookie-confirm-header-close-container___325nt"};function CC(e){window.dataLayer=window.dataLayer||[],"function"==typeof window.gtag?window.gtag("consent","update",e):window.dataLayer.push(["consent","update",e])}function SC(){CC({ad_storage:"granted",ad_user_data:"granted",ad_personalization:"granted",analytics_storage:"granted"}),window.location.reload()}const kC=["_gcl_au","_ga","_gid","_gat","_gcl"];function jC(){const e=document.cookie.split(";"),t=function(){const e=location.hostname,t=e.split(".");return[e,`.${e}`,t.length>2?`.${t.slice(-2).join(".")}`:`.${e}`]}();for(const n of e){const e=n.split("=")[0].trim();if(kC.some(t=>e.startsWith(t)))for(const n of t)document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${n}`}}function TC(){CC({ad_storage:"denied",ad_user_data:"denied",ad_personalization:"denied",analytics_storage:"denied"}),jC(),window.location.reload()}const EC=()=>{const e=ye(),t=cR(e=>e.setShowCookieConfirm),n=Jh(e=>e.setSettings),s="prod"===dl?"https://qwen.ai/cookies-notice":"https://pre.qwen.ai/cookies-notice";return F.jsxs("div",{className:_C.cookieConfirm,children:[F.jsxs("div",{className:_C.cookieConfirmHeader,children:[F.jsxs("div",{className:_C.cookieConfirmHeaderTitle,children:[" ",e.t("Cookie Notice")]}),F.jsx("div",{onClick:()=>t(!1),className:_C.cookieConfirmHeaderCloseContainer,children:F.jsx(pi,{className:_C.cookieConfirmHeaderClose,type:"icon-line-x-02"})})]}),F.jsxs("div",{className:_C.cookieConfirmContainer,children:[F.jsxs("div",{className:_C.cookieDes,children:[F.jsx(pi,{className:_C.cookieDesIcon,type:"icon-line-information-circle"}),F.jsx("p",{children:F.jsx(be,{i18nKey:"We'd like to use cookies to remember your preferences and show relevant content. You can accept all cookies for a fully personalized experience, or select only the strictly necessary ones to keep Qwen Studio running securely. For more details, please read our {{Cookie Notice}}.",values:{"Cookie Notice":""},components:{a:F.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:_C.textUnderline,children:e.t("Cookie Notice")})}})})]}),F.jsx(xi,{rounded:"circle",type:"brandprimary",onClick:()=>A(null,null,function*(){yield n({manage_cookies:{strictly_necessary_cookies:!0,advertising_cookies:!0}}),t(!1),SC()}),buttonClass:_C.cookieConfirmBtn,children:e.t("Accept all cookies")}),F.jsx(xi,{rounded:"circle",type:"brandprimary",onClick:()=>A(null,null,function*(){yield n({manage_cookies:{strictly_necessary_cookies:!0,advertising_cookies:!1}}),t(!1),TC()}),buttonClass:_C.cookieConfirmBtn,children:e.t("Accept all strictly necessary cookies")})]}),F.jsx("div",{onClick:()=>t(!1),className:_C.cookieConfirmCloseContainer,children:F.jsx(pi,{className:_C.cookieConfirmClose,type:"icon-line-x-02"})})]})},NC={cookieSetingModels:"index-module__cookie-seting-models___rjPba",cookieSetingModelHerder:"index-module__cookie-seting-model-herder___2guK8",title:"index-module__title___Nbx00",cookieSetingModelDes:"index-module__cookie-seting-model-des___J3sa8",cookieSetingItem:"index-module__cookie-seting-item___29T46",itemTop:"index-module__item-top___igttM",titleDisabled:"index-module__title-disabled___tzJWu",itemBottom:"index-module__item-bottom___FsIpo",des:"index-module__des___dtSz3",desDisabled:"index-module__des-disabled___dklhS",cookieSetingFooter:"index-module__cookie-seting-footer___Co-xl",cookieConfirmBtn:"index-module__cookie-confirm-btn___WHa5N",cookieSetingPupup:"index-module__cookie-seting-pupup___y6QgE",cookieSetingPupupContent:"index-module__cookie-seting-pupup-content___GrIat",itemTopLeft:"index-module__item-top-left___B2ELg",iconChevronDown:"index-module__icon-chevron-down___nsipH"},IC=[{key:"All",title:"Strictly Necessary Cookies",des:"These essential cookies are required for Qwen Studio to function correctly, ensuring secure sessions and basic features like message delivery. Unlike other categories, these cannot be disabled as the service relies on them to operate safely and effectively.",selected:!0,disable:!0},{key:"Adv",title:"Advertising Cookies",des:"Enable these cookies to allow us to deliver personalized content based on your interests and usage patterns. While disabling them won't affect Qwen Studio's core functionality, it may result in seeing less targeted promotions.",selected:!1,disable:!1}],AC=({cookieSettingModelsVisible:e,setCookieSettingModelsVisible:t})=>{const[n,s]=D.useState(IC),i=ye(),a=cR(e=>e.setShowCookieConfirm),o=Jh(e=>e.setSettings),r=Jh(e=>e.settings),[l,c]=D.useState(IC.reduce((e,t)=>(e[t.key]=!0,e),{})),[d,u]=D.useState(!1),h=D.useCallback(()=>A(null,null,function*(){yield o({manage_cookies:{strictly_necessary_cookies:!0,advertising_cookies:!0}}),a(!1),SC()}),[o,a]),m=D.useCallback(()=>A(null,null,function*(){yield o({manage_cookies:{strictly_necessary_cookies:!0,advertising_cookies:!1}}),a(!1),TC()}),[o,a]);D.useEffect(()=>{const e=()=>{u(window.innerWidth<=768)};return e(),window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}},[]),D.useEffect(()=>{if(e){const e=r.manage_cookies,t=null!=e?IC.map(t=>{var n;return"Adv"===t.key?S(C({},t),{selected:null!=(n=e.advertising_cookies)&&n}):t}):IC;s(t),c(IC.reduce((e,t)=>(e[t.key]=!0,e),{}))}},[e,r.manage_cookies]);const p=D.useCallback(()=>{t(!1)},[t]),g=D.useCallback((e,t)=>{s(n=>n.map(n=>n.key!==e||n.disable?n:S(C({},n),{selected:t})))},[]),f=D.useCallback(e=>{c(t=>S(C({},t),{[e]:!t[e]}))},[]),v=D.useMemo(()=>n.reduce((e,t)=>(e[t.key]=t.selected,e),{}),[n]),y=D.useCallback(()=>{Object.values(v).every(e=>!0===e)?h():m(),p()},[p,v,h,m]);return d?F.jsx(Ti,{className:NC.cookieSetingPupup,open:e,onClose:p,heightType:"auto",title:i.t("Manage Cookies"),children:F.jsxs("div",{className:NC.cookieSetingPupupContent,children:[F.jsx("div",{className:NC.cookieSetingModelDes,children:i.t("Take control of your data privacy. On this page, you can manage how Qwen Studio uses cookies to enhance your experience. Review and customize your consent settings below to decide which types of data collection align with your preferences.")}),n.map(e=>F.jsxs("div",{className:NC.cookieSetingItem,children:[F.jsxs("div",{className:NC.itemTop,children:[F.jsxs("div",{className:NC.itemTopLeft,children:[F.jsx(Oi,{disabled:e.disable,checked:e.selected,onChange:t=>g(e.key,t),isRound:!0,className:"",style:{}}),F.jsx("div",{className:`${NC.title} ${e.disable?NC.titleDisabled:""}`,children:i.t(e.title)})]}),F.jsx("div",{className:NC.iconChevronDown,style:l[e.key]?{transform:"rotate(180deg)"}:{},onClick:()=>f(e.key),children:F.jsx(pi,{className:NC.iconChevronDown,type:"icon-line-chevron-down"})})]}),l[e.key]&&F.jsx("div",{className:NC.itemBottom,children:F.jsx("div",{className:`${NC.des} ${e.disable?NC.desDisabled:""}`,children:i.t(e.des)})})]},e.key)),F.jsx("div",{className:NC.cookieSetingFooter,children:F.jsx(xi,{rounded:"circle",type:"brandprimary",onClick:y,buttonClass:NC.cookieConfirmBtn,children:i.t("Save")})})]})}):F.jsxs(wi,{visible:e,headerBorderNone:!0,footer:!1,header:!1,className:NC.cookieSetingModels,onCancel:p,size:"small",children:[F.jsxs("div",{className:NC.cookieSetingModelHerder,children:[F.jsx("div",{className:NC.title,children:i.t("Manage Cookies")}),F.jsx("div",{className:NC["icon-close"],onClick:p,children:F.jsx(pi,{type:"icon-line-x-01"})})]}),F.jsx("div",{className:NC.cookieSetingModelDes,children:i.t("Take control of your data privacy. On this page, you can manage how Qwen Studio uses cookies to enhance your experience. Review and customize your consent settings below to decide which types of data collection align with your preferences.")}),n.map(e=>F.jsxs("div",{className:NC.cookieSetingItem,children:[F.jsxs("div",{className:NC.itemTop,children:[F.jsx(Oi,{disabled:e.disable,size:"small",checked:e.selected,onChange:t=>g(e.key,t),isRound:!0,className:"",style:{}}),F.jsx("div",{className:`${NC.title} ${e.disable?NC.titleDisabled:""}`,children:i.t(e.title)})]}),F.jsx("div",{className:NC.itemBottom,children:F.jsx("div",{className:`${NC.des} ${e.disable?NC.desDisabled:""}`,children:i.t(e.des)})})]},e.key)),F.jsx("div",{className:NC.cookieSetingFooter,children:F.jsx(xi,{rounded:"circle",type:"brandprimary",onClick:y,buttonClass:NC.cookieConfirmBtn,children:i.t("Save")})})]})},MC={publishToCommunityModal:"index-h5-module__publish-to-community-modal___i-q--",content:"index-h5-module__content___ahaeV",messageContent:"index-h5-module__message-content___Amkbp",messageContentGoCheck:"index-h5-module__message-content-go-check___KO8rp",messageContentGoCheckText:"index-h5-module__message-content-go-check-text___Bx9NM",messageContentGoCheckIcon:"index-h5-module__message-content-go-check-icon___K7EoM"},RC={publishToCommunityModal:"index-module__publish-to-community-modal___KVynA",content:"index-module__content___rD7ew",publishModalFooter:"index-module__publish-modal-footer___bBfJ7",publishModalButton:"index-module__publish-modal-button___zScqE",qwenModalFooter:"index-module__qwen-modal-footer___07Xz1",messageContentGoCheck:"index-module__message-content-go-check___S94Vu",messageContentGoCheckText:"index-module__message-content-go-check-text___bX-F0",messageContentGoCheckIcon:"index-module__message-content-go-check-icon___YaQNP"},PC=({open:e,onCancel:t,messageId:n})=>{const s=ye(),i=cR(e=>e.mobile),[a,o]=D.useState(!1),r=D.useMemo(()=>i?MC:RC,[i]),l=()=>{bM.openCommunity("/community/collections")},c=()=>F.jsxs(ie,{align:"center",gap:i?20:158,className:r.messageContent,children:[F.jsx("div",{children:s.t("Published successfully")}),F.jsxs(ie,{align:"center",onClick:l,className:r.messageContentGoCheck,children:[F.jsx("div",{className:r.messageContentGoCheckText,children:s.t("Go check")}),F.jsx(pi,{className:r.messageContentGoCheckIcon,type:"icon-line-chevron-right"})]})]}),d=()=>A(null,null,function*(){try{o(!0);const e=yield((e,t)=>A(null,null,function*(){var n,s;const{chatId:i}=js.getState(),a=cR.getState().mobile,o=it();let r=!1,l="";if(i&&e){try{const t=yield Cg({chat_id:i,message_id:e,scope:1});r=!!(null==(n=null==t?void 0:t.data)?void 0:n.share_id),l=(null==(s=null==t?void 0:t.data)?void 0:s.message)||""}catch(c){}return r?(vi.open({type:"success",content:t?t():o.t("Published successfully"),closable:!1,className:a?"message-publish":""}),setTimeout(()=>{V.destroy()},3e3)):vi.open({type:"error",content:l,closable:!1,className:a?"message-publish message-publish-error":"",duration:3e3}),{success:r}}}))(n,c);(null==e?void 0:e.success)&&t()}finally{t(),o(!1)}});return F.jsx(wi,{title:s.t("Publish Work"),headerBorderNone:!0,visible:e,className:r.publishToCommunityModal,closable:!i,zIndex:1e7,onCancel:t,size:"small",type:"confirm",actions:[{text:s.t("Cancel"),type:"tertiary",disabled:a,onClick:e=>{e.stopPropagation(),t()},rounded:"circle"},{text:s.t("Confirm"),disabled:a,type:"brandprimary",onClick:e=>{e.stopPropagation(),d()},rounded:"circle"}],children:F.jsx("span",{className:r.content,children:s.t("Are you sure you want to publish your work?")})})},LC=D.memo(({text:e,backTo:t,overrideBackHandler:n})=>{const s=cR(e=>e.mobile),i=Ue(),a=D.useRef(null);return F.jsxs(xi,{type:"link",className:"back-button",children:[F.jsx(pi,{type:s?"icon-line-chevron-right":"icon-line-arrow-right",onClick:()=>{n?n():i(t||-1)}}),F.jsx("div",{ref:a,className:"back-button-text",children:e})]})}),OC=()=>{const e=Ue();return F.jsx("div",{onClick:()=>e("/community/collections"),className:"my-publish-button",children:F.jsx(pi,{type:"icon-a-line-MyPublished"})})},DC=e=>{const{requiredReportMessageRows:t=1,reportMessageRows:n=1,maxReportMessageRows:s,maxRequiredReportMessageRows:i,onSubmit:a=()=>{}}=e,{i18n:o}=ye(),[r]=pe.useForm(),l=pe.useWatch([],r),[c,d]=D.useState(""),[u,h]=D.useState(""),m=[{label:o.t("Nudity & Sexual Content"),value:"Nudity & Sexual Content"},{label:o.t("Child Exploitation"),value:"Child Exploitation"},{label:o.t("Violence & Self-Harm"),value:"Violence & Self-Harm"},{label:o.t("Deceptive Behavior & Scams"),value:"Deceptive Behavior & Scams"},{label:o.t("Hate, Harassment & Spam"),value:"Hate, Harassment & Spam"},{label:o.t("Other inappropriate or illegal content"),value:"Other inappropriate or illegal content"},{label:o.t("Intellectual Property"),value:"Intellectual Property"},{label:o.t("Other"),value:"Other"}],p=D.useCallback(()=>{a(S(C({},r.getFieldsValue()),{report_reason:c,report_message:u}))},[r,a,u,c]),g=D.useMemo(()=>wR()?!((null==l?void 0:l.user_first_name)&&(null==l?void 0:l.user_last_name)&&(null==l?void 0:l.user_email)&&(null==l?void 0:l.required_report_message)&&c):!c&&!u,[u,c,l]);return F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"report-drawer-form",children:F.jsxs(pe,{form:r,className:"report-form",children:[wR()?F.jsxs(F.Fragment,{children:[F.jsxs(ie,{gap:16,children:[F.jsx(pe.Item,{layout:"vertical",className:"report-form-item",label:F.jsxs("div",{className:"name-label",children:[F.jsx("span",{className:"name-label-span",children:"*"}),o.t("First name")]}),name:"user_first_name",children:F.jsx(K,{maxLength:255,placeholder:o.t("Input your first name")})}),F.jsx(pe.Item,{layout:"vertical",className:"report-form-item",label:F.jsxs("div",{className:"name-label",children:[F.jsx("span",{className:"name-label-span",children:"*"}),o.t("Last name")]}),name:"user_last_name",children:F.jsx(K,{maxLength:255,placeholder:o.t("Input your last name")})})]}),F.jsx(pe.Item,{layout:"vertical",className:"report-form-item",label:F.jsxs("div",{className:"name-label",children:[F.jsx("span",{className:"name-label-span",children:"*"}),o.t("Email address")]}),name:"user_email",rules:[{pattern:/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,message:"Please enter a valid email"}],children:F.jsx(K,{placeholder:o.t("Input your email address"),maxLength:255})}),F.jsx(pe.Item,{layout:"vertical",className:"report-form-item",label:F.jsxs("div",{className:"name-label",children:[F.jsx("span",{className:"name-label-span",children:"*"}),o.t("What content are you reporting?")]}),name:"required_report_message",children:F.jsx(Mg,{rows:t,maxRows:i,placeholder:o.t("Please include URLs where available directly to the content you are reporting.")})})]}):null,F.jsxs(pe.Item,{layout:"vertical",className:"report-form-item",label:wR()?F.jsxs("div",{className:"name-label",children:[F.jsx("span",{className:"name-label-span",children:"*"}),o.t("Why are you reporting this content?")]}):null,children:[F.jsx("div",{className:"reason-list",children:m.map(e=>F.jsx("div",{className:"reason-list-tag "+(e.value===c?"reason-list-tag-active":""),onClick:()=>d(e.value),children:e.label},e.value))}),F.jsx(Mg,{rows:n,maxRows:s,placeholder:o.t("(Optional) Feel free to add specific details"),value:u,onChange:e=>h(e),className:"reason-input"})]})]})}),F.jsx("div",{className:"report-footer",children:F.jsx(xi,{type:"brandprimary",disabled:g,onClick:p,rounded:"circle",className:"report-form-button",children:o.t("Submit")})})]})},FC=e=>/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(e),qC=e=>A(null,null,function*(){return yield Sl(),yield TM(`/community/share/${e}/like`,{method:"POST",toast:!1})}),UC=e=>A(null,null,function*(){return yield Sl(),yield TM(`/community/share/${e}/unlike`,{method:"POST",toast:!1})}),HC=e=>A(null,null,function*(){return yield Sl(),yield TM(`/community/share/${e}`,{method:"DELETE"})}),BC=e=>A(null,null,function*(){const t=e,{user_id:n}=t,s=k(t,["user_id"]);return yield Sl(),yield TM(`/community/${n}/shares`,{method:"GET",params:s})}),zC=e=>A(null,null,function*(){return yield Sl(),yield TM("/community/contents",{method:"GET",params:e})}),GC=e=>A(null,null,function*(){return yield Sl(),yield TM("/community/host_graph",{method:"GET",params:e,internationalization:!0})}),$C=e=>A(null,null,function*(){return yield Sl(),yield TM(`/community/share/${e}`,{method:"GET"})}),WC=D.memo(e=>{const{shareId:t,show:n,onClose:s,showSourceChatModalVisible:i}=e,{i18n:a}=ye(),o=cR(e=>e.mobile),r=Ue(),l=D.useCallback(e=>""===e?(vi.openOnce({type:"warning",content:a.t("Please enter your email")}),!1):!!FC(e)||(vi.openOnce({type:"warning",content:a.t("Please enter a valid email")}),!1),[a]),c=D.useCallback(e=>A(null,null,function*(){var n,o;const{user_email:c="",user_first_name:d="",user_last_name:u="",required_report_message:h="",report_reason:m="",report_message:p=""}=e||{};if(wR()){if(!l(c))return}try{const e=yield(g={share_id:t,report_reason:m,report_message:p,user_email:c,user_first_name:d,user_last_name:u,required_report_message:h},A(null,null,function*(){const{share_id:e}=g;return yield Sl(),yield TM(`/community/share/${e}/report`,{method:"POST",data:C({},g),toast:!1})}));if("Unknown_error"===(null==(n=null==e?void 0:e.data)?void 0:n.code)&&(null==(o=null==e?void 0:e.data)?void 0:o.message)===`Share with id ${t} not found`)return void i();e&&e.success&&(vi.open({type:"success",content:a.t("Your report has been successfully submitted and will be processed as soon as possible.")}),s(),r("/community"))}catch(f){s()}var g}),[l,t,i,a,s,r]),d=D.useCallback(()=>F.jsxs("div",{className:"report-drawer",children:[F.jsxs("div",{className:"report-drawer-title",children:[wR()?a.t("Reporting content"):a.t("Report reason"),F.jsx(pi,{type:"icon-line-x-01",onClick:s})]}),F.jsx(DC,{requiredReportMessageRows:4,reportMessageRows:4,onSubmit:c})]}),[a,s,c]);return F.jsx(F.Fragment,{children:o?F.jsx(ee,{open:n,placement:"bottom",height:"auto",drawerRender:d,onClose:s}):F.jsx(wi,{visible:n,onCancel:s,headerBorderNone:!0,title:wR()?a.t("Reporting content"):a.t("Report reason"),footer:!1,className:"report-community-modal",children:F.jsx(DC,{onSubmit:c,maxRequiredReportMessageRows:3,maxReportMessageRows:3})})})}),VC={disable:[],disable_GREEN_ERROR:[],error_ALL_N:["regenerate"],error_ALL_G:["regenerate"],error_ALL_S:[],normal_TW_N:["copy","voice","edit","branch_new","good","bad","share","regenerate"],normal_TW_G:["copy","voice","regenerate"],normal_TW_S:["copy"],normal_A_N:["artifacts","copy","edit","branch_new","publish","good","bad","share","regenerate"],normal_A_G:["artifacts","copy","regenerate"],normal_A_S:["artifacts","copy"],normal_D_N:["copy","branch_new","publish","good","bad","share","regenerate"],normal_D_G:["copy","regenerate"],normal_D_S:["copy"],normal_DP_N:["download","good","bad","share","regenerate","publish"],normal_DP_G:["download","regenerate"],normal_DP_S:["download"],normal_RUPT_N:["copy","good","bad","share","branch_new"],normal_RUPT_G:["copy"],normal_RUPT_S:["copy"],normal_T2I_N:["create_video","image_edit","branch_new","publish","download","good","bad","share","regenerate"],normal_T2I_G:["create_video","image_edit","download","regenerate"],normal_T2I_S:["download"],normal_IE_N:["image_edit","create_video","branch_new","publish","download","good","bad","share","regenerate"],normal_IE_G:["image_edit","create_video","download","regenerate"],normal_IE_S:["download"],normal_VLO_N:["create_video","image_edit","branch_new","publish","download","good","bad","share","regenerate"],normal_VLO_G:["create_video","image_edit","download","regenerate"],normal_VLO_S:["download"],normal_VLO_N_STOP:["regenerate"],normal_VLO_G_STOP:["regenerate"],normal_T2V_N:["download","publish","branch_new","good","bad","share","regenerate"],normal_T2V_G:["download","regenerate"],normal_T2V_S:["download"],normal_OMNI_N:["copy","good","bad","share","branch_new","replay"],normal_OMNI_S:["copy"]},QC={normal_TW:["select","translation"],normal_A:["select","translation"],normal_D:["select"]},KC={normal:"N",guest:"G",local:"G",share:"S"},YC={t2t:"TW",search:"TW",artifacts:"A",web_dev:"A",deep_research:"D",podcast:"DP",t2i:"T2I",image_edit:"IE",t2v:"T2V",travel:"D"},JC=e=>{const t=/```html[\s\S]*?```/g,n=/```jsx[\s\S]*?```/g;try{const s=e.match(t),i=e.match(n);return null!==s&&s.length>0||null!==i&&i.length>0}catch(s){return!1}},XC=e=>/^```|```\s*$/m.test(e),ZC=new RegExp("^(.*?)<\\/think>","is"),eS=new RegExp("^(?!.*<\\/think>)","is"),tS=e=>{var t;if(eS.test(e)){let t=e.replace(/^/i,"");return t=t.replace(/^\n/,""),{status:"THINKING",content:"",thinkingQuoteText:t}}if(ZC.test(e)){let n=e.replace(ZC,"");n=n.replace(/^\n{0,2}/,"");let s=(null==(t=e.match(ZC)||[])?void 0:t[1])||"";return s=s.replace(/^\n+|\n+$/g,""),{status:"THOUGHT_COMPLETED",content:n,thinkingQuoteText:s}}return{status:"NONE_THINKING",content:e,thinkingQuoteText:""}},nS=e=>{var t,n,s;return(null==e?void 0:e.content_list)&&(null==(t=null==e?void 0:e.content_list)?void 0:t.length)&&(null==(s=null==(n=null==e?void 0:e.content_list)?void 0:n.findLast(e=>(null==e?void 0:e.phase)===wt.ANSWER))?void 0:s.content)||""},sS=e=>{var t,n;if((null==e?void 0:e.content_list)&&(null==(t=null==e?void 0:e.content_list)?void 0:t.length))return null==(n=null==e?void 0:e.content_list)?void 0:n.filter(e=>(null==e?void 0:e.phase)===wt.ANSWER||(null==e?void 0:e.phase)===wt.DEEPTHINKING).map(e=>e.content||"").join("\n");const{content:s}=tS((null==e?void 0:e.content)||"");return s},iS=e=>e.every(e=>{var t,n,s,i;return e.phase===wt.THINKING_SUMMARY?0===(null==(n=null==(t=null==e?void 0:e.extra)?void 0:t.summary_title)?void 0:n.length)&&0===(null==(i=null==(s=null==e?void 0:e.extra)?void 0:s.summary_content)?void 0:i.length):![wt.IMAGE_GEN_TOOL,wt.IMAGE_EDIT_TOOL].includes(e.phase)&&""===e.content}),aS=({className:e="",style:t={},checkSupport:n=!0,onCustomize:s})=>{var i,a,o,r,l;const c=ye(),d=Ue(),u=cR(e=>e.config),h=cR(e=>e.mobile),m=js(e=>e.history),p=js(e=>e.resetChatState),g=fR(e=>e.shareDetailData),[f,v]=D.useState(!1),[y,b]=D.useState(!1),x=D.useMemo(()=>(null==g?void 0:g.id)||"",[null==g?void 0:g.id]),w=D.useMemo(()=>(null==g?void 0:g.detailChatType)||"",[null==g?void 0:g.detailChatType]),{chat_type:_,sub_chat_type:C}=D.useMemo(()=>{var e;return(null==(e=null==g?void 0:g.shared_content)?void 0:e[0])||{}},[null==g?void 0:g.shared_content]),S=D.useMemo(()=>{var e,t;return 0==(null==(t=null==(e=null==u?void 0:u.permissions)?void 0:e.chat)?void 0:t[C||_])},[_,null==(i=null==u?void 0:u.permissions)?void 0:i.chat,C]),k=D.useMemo(()=>{var e,t,n,s;return!!(null==(t=null==(e=null==g?void 0:g.shared_message)?void 0:e.feature_config)?void 0:t.thinking_enabled)&&0==(null==(s=null==(n=null==u?void 0:u.permissions)?void 0:n.chat)?void 0:s.thinking)},[null==(o=null==(a=null==u?void 0:u.permissions)?void 0:a.chat)?void 0:o.thinking,null==(l=null==(r=null==g?void 0:g.shared_message)?void 0:r.feature_config)?void 0:l.thinking_enabled]);D.useEffect(()=>{if(b(S||k),S||k){if(!n)return;v(!0)}},[S,k]);const j=D.useCallback((e,t)=>{pl("clkCommunityItemCustomize",{params:{et:"CLK"},aesParams:{c5:e,c6:t},paramsExtend:{share_type:t,share_id:e}})},[]);return F.jsxs("div",{className:`customize ${e}`,style:t,children:[F.jsx(xi,{className:"customize-button",iconFontType:"icon-line-sync",disabled:y,onClick:()=>{if(s)s();else{if(wR()&&w===yt.VideoGeneration)return void bM.showNativeLoginPage(w);j(x,w),((e,t)=>{var n,s,i,a,o;if(ti()){const{history:t}=js.getState(),r=t.messages[t.currentId||""]||{},l=t.messages[r.parentId||""]||{},c={inputText:l.content,modelId:l.model||(null==(n=null==l?void 0:l.models)?void 0:n[0]),actionScene:{type:l.chat_type,subType:l.sub_chat_type,featureConfig:l.feature_config},shareId:e};if(l.chat_type===yt.ImageGeneration){const e=Array.isArray(r.content_list)&&(null==r?void 0:r.content_list.find(e=>{var t;return e.phase===wt.IMAGE_GEN&&(null==(t=null==e?void 0:e.extra)?void 0:t.output_image_hw)}));let t=jt["1:1"];if(e){const[n,a]=null==(i=null==(s=null==e?void 0:e.extra)?void 0:s.output_image_hw)?void 0:i[0];Object.values(jt).forEach(e=>{const[s,i]=e.split(":");Math.abs(Number(a)/Number(n)-Number(s)/Number(i))<.1&&(t=e)})}c.actionScene.ext={size:t}}if((null==(a=l.files)?void 0:a.length)&&l.files.forEach(e=>{"file"===e.type&&(c.fileList=[...c.fileList||[],{fileName:e.name,fileSize:e.size,fileUrl:e.url,fileType:e.file_type}]),"video"===e.type&&(c.videoList=[...c.videoList||[],{videoName:e.name,videoSize:e.size,videoUrl:e.url,videoType:e.file_type,videoDuration:0}]),"audio"===e.type&&(c.audioList=[...c.audioList||[],{audioName:e.name,audioSize:e.size,audioUrl:e.url,audioType:e.file_type,audioDuration:0}]),"image"===e.type&&(c.imageList=[...c.imageList||[],{imageUrl:e.url}])}),l.chat_type===yt.DeepResearch&&[yt.DeepResearchWebDev,yt.Txt2Txt].includes(null==r?void 0:r.sub_chat_type)){const e=(null==(o=_r(t.currentId,t))?void 0:o.find(e=>{var t;return null==(t=e.content_list||[])?void 0:t.some(e=>"PdfMdGen"===e.phase)}))||null,n=(e=>{var t,n,s,i;const a=null==(n=null==(t=e.content_list)?void 0:t.find(e=>"PdfMdGen"===e.phase))?void 0:n.extra;return(null==(s=null==a?void 0:a.deep_research)?void 0:s.pdf)||(null==(i=null==a?void 0:a.travel_research)?void 0:i.pdf)||null})(e);c.queryFile={fileName:(null==n?void 0:n.name)||"",fileUrl:(null==n?void 0:n.link)||"",fileType:"application/pdf"}}return void bM.adapter.invoke({method:"openMainChat",params:c})}{p();const n=ud.getState().language;d(`/${t?"c/new-chat":""}?shareId=${e}&lang=${n}`)}})(x,Object.keys(m.messages).length>2)}},children:c.t("Customize")}),F.jsx(wi,{visible:f,title:c.t("Tips"),maskClosable:!1,closable:!h,headerBorderNone:!0,type:"confirm",onCancel:()=>v(!1),zIndex:1e8,actions:[{type:h?"brandprimary":"tertiary",text:c.t("Got it"),rounded:"circle",onClick:()=>v(!1)}],children:c.t(k?"This feature has been retired — you can no longer generate the same product.We’re working on new ways to help you achieve similar results. Stay tuned!":"This feature has been removed, and it is no longer possible to recreate the same creation.")})]})},oS=D.memo(({visible:e,onClose:t=()=>{}})=>{const n=ye(),s=cR(e=>e.mobile);return F.jsx(wi,{headerBorderNone:!0,size:"small",title:n.t("Tips"),visible:e,type:"confirm",closable:!s,actions:[{text:n.t("Got it"),type:s?"brandprimary":"tertiary",rounded:"circle",onClick:t}],onCancel:t,children:n.t("This creation’s original full chat has been deleted and is no longer viewable.")})}),rS=()=>{const e=js(e=>e.history),t=D.useMemo(()=>{var t,n,s,i;if(Ne(e))return"";const a=null==(i=null==(s=null==(n=null==(t=e.messages)?void 0:t[(null==e?void 0:e.currentId)||""])?void 0:n.content_list)?void 0:s[0])?void 0:i.content;return"string"==typeof a?a:""},[e]);return t?F.jsx("div",{className:"image-generation-preview",children:F.jsx("div",{className:"image-generation-preview-card",children:F.jsx("img",{src:t,alt:"image"})})}):null};function lS(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}function cS(e,t=!1){const n=new Date(1e3*e),s=e=>e.toString().padStart(2,"0"),i=n.getFullYear(),a=s(n.getMonth()+1),o=s(n.getDate()),r=s(n.getHours()),l=s(n.getMinutes()),c=s(n.getSeconds());return t?`${i}-${a}-${o} ${r}:${l}:${c}`:`${i}-${a}-${o}`}const dS=({min:e,max:t,value:n,onChange:s})=>{const i=(n-e)/(t-e)*100;return F.jsxs("div",{className:"custom-progress-track",onClick:n=>{const i=n.currentTarget.getBoundingClientRect(),a=n.clientX-i.left,o=Math.max(0,Math.min(100,a/i.width*100));s(e+o/100*(t-e))},children:[F.jsx("div",{className:"custom-progress-filled",style:{width:`${i}%`}}),F.jsx("div",{className:"custom-progress-thumb",style:{left:`${i}%`}})]})},uS=()=>{const e=js(e=>e.history),t=D.useRef(null),[n,s]=D.useState(!1),[i,a]=D.useState(0),[o,r]=D.useState(0),[l,c]=D.useState(!0),[d,u]=D.useState(!1),{videoUrl:h,thumbnailUrl:m}=D.useMemo(()=>{var t;const n=null==(t=null==e?void 0:e.messages[(null==e?void 0:e.currentId)||""])?void 0:t.content;return{videoUrl:n,thumbnailUrl:Df(n||"",!0)}},[e]),p=D.useCallback(e=>{e.stopPropagation(),t.current&&(t.current.paused?t.current.play():t.current.pause())},[]),g=()=>{t.current&&(t.current.muted=!t.current.muted,c(t.current.muted))},f=()=>{t.current&&a(t.current.currentTime)},v=()=>{t.current&&(r(t.current.duration),u(!0))},y=e=>{t.current&&(t.current.currentTime=e)},b=()=>{!document.fullscreenElement&&t.current?t.current.requestFullscreen&&t.current.requestFullscreen():document.exitFullscreen&&document.exitFullscreen()};D.useEffect(()=>{const e=t.current;if(!e)return;const n=()=>s(!0),i=()=>s(!1),a=()=>c(e.muted);return e.addEventListener("play",n),e.addEventListener("pause",i),e.addEventListener("timeupdate",f),e.addEventListener("loadedmetadata",v),e.addEventListener("volumechange",a),()=>{e.removeEventListener("play",n),e.removeEventListener("pause",i),e.removeEventListener("timeupdate",f),e.removeEventListener("loadedmetadata",v),e.removeEventListener("volumechange",a)}},[h]);const x=D.useMemo(()=>d?F.jsxs("div",{className:"video-controls",onClick:e=>e.stopPropagation(),children:[F.jsx(dS,{min:0,max:o||100,value:i,onChange:y}),F.jsxs("div",{className:"video-controls-wrapper",children:[F.jsxs("div",{className:"video-controls-wrapper-left",children:[F.jsx("button",{className:"control-btn",onClick:p,children:F.jsx(pi,{type:n?"icon-play":"icon-pause"})}),F.jsxs("div",{className:"time-display",children:[F.jsx("span",{className:"time-display current-time",children:lS(i)}),F.jsxs("span",{className:"time-display total-time",children:[" / ",lS(o)]})]})]}),F.jsxs("div",{className:"video-controls-wrapper-right",children:[F.jsx("button",{className:"control-btn mute-btn",onClick:g,children:F.jsx(pi,{type:l?"icon-line-Silent":"icon-line-Volume"})}),F.jsx("button",{className:"control-btn fullscreen-btn",onClick:b,children:F.jsx(pi,{type:"icon-a-line-Fullscreen1"})})]})]})]}):null,[i,o,l,n,d,p]),w=D.useMemo(()=>!d||n?null:F.jsx("div",{className:"video-container-pause",children:F.jsx(pi,{type:"icon-pause"})}),[n,d]);return h?F.jsxs("div",{className:"video-preview",children:[F.jsxs("div",{className:"video-container",onClick:p,children:[F.jsx("div",{className:"video-container-wrapper",children:F.jsx("video",{ref:t,src:h,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,poster:m})}),w]}),x]}):null},hS=()=>{const e=Pd(e=>e.user),t=ye(),n=ze(),s=D.useMemo(()=>"/community/collections"===n.pathname?"collections":"home",[n]),i=D.useMemo(()=>F.jsxs("div",{className:"header-content",children:[F.jsx("div",{className:"header-left",children:e?F.jsx(Xp,{}):F.jsx(Jp,{})}),F.jsx("div",{className:"header-center",children:t.t("Community")}),F.jsx("div",{className:"header-right",children:e?F.jsx(OC,{}):F.jsx(vp,{})})]}),[t,e]),a=D.useMemo(()=>F.jsxs("div",{className:"header-content",children:[F.jsx("div",{className:"header-left",children:F.jsx(LC,{})}),F.jsx("div",{className:"header-center",children:t.t("My Published Work")}),F.jsx("div",{className:"header-right"})]}),[t]);return F.jsxs("header",{className:"community-header-mobile",children:["home"===s&&i,"collections"===s&&a]})},mS=()=>{const e=Ue(),t=ye(),n=ze(),s=Pd(e=>e.user),i=fR(e=>e.headerToAbsolute),a=fR(e=>e.headerToBottomShadow),o=D.useMemo(()=>"/community/collections"===n.pathname?"collections":"home",[n]),r=D.useMemo(()=>F.jsxs("div",{className:"header-content",children:[F.jsx("div",{className:"header-left",children:F.jsx(LC,{text:t.t("By {{username}}",{username:(null==s?void 0:s.name)||""})})}),F.jsx("div",{className:"header-right",children:!s&&F.jsx(vp,{showRegister:!0,size:"middle"})})]}),[s,t]),l=D.useMemo(()=>F.jsxs("div",{className:"header-content",children:[F.jsx("div",{className:"header-left",children:s?null:F.jsx(Jp,{})}),s?F.jsx("div",{className:"header-center",children:F.jsxs(xi,{type:"ghost",className:"header-collections-button",onClick:()=>e("/community/collections"),children:[F.jsx("span",{children:t.t("My Published")}),F.jsx(pi,{type:"icon-line-arrow-up-right"})]})}):null,F.jsx("div",{className:"header-right",children:s?null:F.jsx(vp,{showRegister:!0,size:"middle"})})]}),[t,s]);return F.jsxs("header",{className:Q("community-header-desktop",{"header-desktop-to-absolute":i,"header-desktop-to-bottom-shadow":a}),children:["home"===o&&l,"collections"===o&&r]})},pS=({isDetailPage:e})=>{const t=cR(e=>e.mobile);return e?null:t?F.jsx(hS,{}):F.jsx(mS,{})},gS=({icon:e,text:t,active:n=!1})=>cR(e=>e.mobile)?F.jsxs("div",{className:"header-extension-item-mobile",children:[F.jsx("div",{children:t}),e&&F.jsx(pi,{className:Q("header-extension-item-icon",{"header-extension-item-icon-active":n}),type:e})]}):F.jsxs(ie,{className:"header-extension-item",gap:8,children:[e&&F.jsx(pi,{className:Q("header-extension-item-icon",{"header-extension-item-icon-active":n}),type:e}),F.jsx("div",{children:t})]}),fS=D.memo(e=>{const{shareId:t,isLiked:n,likedCount:s="",userName:i="",isOwner:a,type:o="",renderTool:r=!1,onDownload:l=()=>{},onLike:c=()=>{},onViewFullChat:d=()=>{},showSourceChatModalVisible:u=()=>{}}=e,h=ye(),m=Pd(e=>e.user),p=cR(e=>e.mobile),[g,f]=D.useState(!1),[v,y]=D.useState(!1),b=D.useMemo(()=>{const e=new URLSearchParams(window.location.search).get("from");if(!m||e)return"/community"},[m]),x=D.useCallback(e=>{e&&pl("clkCommunityItemReport",{params:{et:"CLK"},aesParams:{c5:t,c6:o},paramsExtend:{share_id:t,share_type:o}}),wR()?bM.showNativeLoginPage(o):ti()?bM.adapter.invoke({method:"openCommunityReportWindow",params:{shareId:t}}):f(e)},[t,o]),w=Le(()=>{c()},300),_=D.useMemo(()=>{const e=[...p&&"webdev"!==o?[{label:F.jsx(gS,{icon:"icon-line-download-02",text:h.t("Download")}),key:"download",onClick:l}]:[],...a&&p?[{label:F.jsx(gS,{icon:"icon-a-line-fullchat",text:h.t("View Full Chat")}),key:"fullChat",onClick:d}]:[],...!1===a?[{label:F.jsx(gS,{icon:"icon-line-report1",text:h.t("Report")}),key:"report",onClick:()=>x(!0)}]:[]];return 0===e.length?null:F.jsxs("div",{children:[F.jsx(Ci,{placement:"bottomLeft",overlayClassName:"detail-header-dropdown",menu:{items:e},open:v&&e.length>0,onOpenChange:e=>{wR()?bM.showNativeLoginPage(o):y(e)},children:F.jsx(pi,{type:"icon-line-more-01"})}),F.jsx(WC,{shareId:t,onClose:()=>x(!1),show:g,showSourceChatModalVisible:u})]})},[p,o,h,l,a,d,v,t,g,u,x]);return p?F.jsx("header",{className:"header-mobile",children:F.jsxs("div",{className:"header-content",children:[F.jsx("div",{className:"header-left",children:F.jsx(LC,{backTo:b,overrideBackHandler:ti()?()=>{bM.routeBack()}:void 0,text:h.t("By {{username}}",{username:i})})}),F.jsx("div",{className:"header-center"}),r&&F.jsxs("div",{className:"header-right detail-header-right",children:[F.jsxs("div",{onClick:w,className:Q("header-like-button",{"header-like-active-button":n}),children:[F.jsx(pi,{type:n?"icon-line-like-selected":"icon-line-like-unselected"}),s]}),_]})]})}):F.jsx("header",{className:"community-header-desktop",children:F.jsxs("div",{className:"header-content",children:[F.jsx("div",{className:"header-left",children:F.jsx(LC,{text:h.t("By {{username}}",{username:i}),backTo:b})}),r&&F.jsxs("div",{className:"header-right detail-header-right",children:[F.jsxs("div",{onClick:w,className:Q("header-like-button",{"header-like-active-button":n}),children:[F.jsx(pi,{type:n?"icon-line-like-selected":"icon-line-like-unselected"}),s]}),"webdev"!==o&&F.jsx(pi,{type:"icon-line-download-02",onClick:l}),a?F.jsxs(xi,{type:"ghost",onClick:d,className:"header-view-full-chat-button",children:[h.t("View Full Chat"),F.jsx(pi,{type:"icon-line-arrow-up-right-dp"})]}):_,!m&&F.jsx(vp,{showRegister:!0,size:"middle"})]})]})})}),vS=({data:e,setData:t})=>{const{i18n:n}=ye(),[s,i]=D.useState(e.name||""),[a,o]=D.useState([]),r=ud(e=>e.language),l=pw(e=>e.setProjectSettingOpen),c=D.useMemo(()=>r||n.language,[n.language,r]),d=D.useCallback(()=>A(null,null,function*(){const e=yield A(null,null,function*(){return yield TM("/configs/?code=projectTitle")});if(e&&e.success){const{language:t,projectIcon:n,projectInstruction:s,projectTitle:i}=e.data,a=n.map((e,n)=>{const a=i[n],o=s[n];return{icon:`icon=${e}&style=${Tw[0]}`,title:t[c][a],instruction:t[c][o]}});o(a)}}),[c]);D.useEffect(()=>{d()},[d]);return D.useEffect(()=>{i(e.name||"")},[e]),F.jsxs("div",{className:"project-new-name",children:[F.jsxs("div",{className:"project-new-name-edit",children:[F.jsx(Nw,{data:e,setData:t}),F.jsx(_i,{className:"project-new-name-edit-input",value:s,onChange:n=>{i(n),t(S(C({},e),{name:n}))},placeholder:n.t("Project Name"),maxLength:150})]}),F.jsx("div",{className:"project-new-name-examples",children:a.map((n,s)=>F.jsx(xi,{iconFontType:Eg(n.icon).icon,type:"ghost",shape:"circle",onClick:()=>{return s=n,l(!0),i(s.title),void t(S(C({},e),{icon:s.icon,name:s.title,custom_instruction:s.instruction}));var s},children:n.title},s))})]})},yS=({value:e="",items:t=[{label:"",value:"default",info:""}],onChange:n,disabled:s})=>{const[i,a]=D.useState(!1),o=ye(),r=D.useRef(null);return F.jsx("div",{className:"project-memory-select-container "+(s?"project-memory-select-containe-disabled":""),onClick:()=>{s||a(!i)},children:F.jsx(Si,{title:s?o.t("Memory settings cannot be changed later."):"",children:F.jsx(X,{ref:r,open:i,value:e,disabled:s,onChange:e=>{null==n||n(e),a(!1)},rootClassName:"project-memory-selector-root",className:"project-memory-selector",popupMatchSelectWidth:!1,placement:"bottomRight",suffixIcon:F.jsx(pi,{type:i?"icon-line-chevron-up":"icon-line-chevron-down",className:"project-memory-selector-arrow"}),optionRender:t=>F.jsxs("div",{className:"project-memory-selector-item",children:[F.jsxs("div",{className:"project-memory-selector-item-text",children:[F.jsx("div",{className:"project-memory-selector-item-name",children:t.data.label}),F.jsx("div",{className:"project-memory-selector-item-info",children:t.data.info})]}),e===t.data.value&&F.jsx(pi,{type:"icon-line-check-02",className:"project-memory-selector-item-checked"})]}),options:t})})})},bS=({data:e,setData:t})=>{const{i18n:n}=ye(),s=cR(e=>e.mobile);D.useEffect(()=>{e.memory_span||t(S(C({},e),{memory_span:"default"}))},[e,t]);const i=D.useMemo(()=>[{value:"default",label:n.t("Default"),info:n.t("Chats will access and contribute to your account-wide memories.")},{value:"project_only",label:n.t("Project-only"),info:n.t("Memories are isolated to this project and won't affect your main account.")}],[n]);return F.jsxs("div",{className:"project-memory-container",children:[F.jsxs("div",{className:"project-memory-info",children:[F.jsx("div",{className:"project-memory-info-text",children:n.t("Memory")}),!s&&F.jsx(Si,{title:n.t("Choose whether this project has its own isolated memory or shares context with your global memory."),children:F.jsx(pi,{type:"icon-line-information-circle",className:"project-memory-info-tooltip"})})]}),s?F.jsx("div",{className:"project-memory-select-mobile",children:i.map(n=>F.jsxs("div",{className:"project-memory-select-mobile-item "+(e.id?"project-memory-select-mobile-item-disabled":""),onClick:()=>{e.id||t(S(C({},e),{memory_span:n.value}))},children:[F.jsxs("div",{className:"project-memory-selector-mobile-item-text",children:[F.jsx("div",{className:"project-memory-selector-mobile-item-name",children:n.label}),F.jsx("div",{className:"project-memory-selector-mobile-item-info",children:n.info})]}),e.memory_span===n.value&&F.jsx(pi,{type:"icon-line-check-02",className:"project-memory-selector-mobile-item-checked"})]},n.value))}):F.jsx(yS,{disabled:!!e.id,items:i,value:e.memory_span,onChange:n=>{t(S(C({},e),{memory_span:n}))}})]})},xS=({data:e,setData:t})=>{const{i18n:n}=ye(),s=cR(e=>e.mobile),i=pw(e=>e.projectSettingOpen),a=pw(e=>e.setProjectSettingOpen),o=pw(e=>e.operationProjectFiles),r=pw(e=>e.deleteFiles),l=pw(e=>e.setDeleteFiles),c=D.useRef(null),d=e=>{var t;null==(t=null==c?void 0:c.current)||t.removeFile(e),l([...r,e.file_id||e.itemId])},u=e=>{d(e)};return D.useEffect(()=>{bM.on(zu.FILE_PASE_REMOVE,u)},[]),F.jsxs("div",{className:"advanced-settings-container",children:[F.jsxs("div",{className:"advanced-settings-title",onClick:()=>{a(!i)},children:[F.jsx("div",{className:"advanced-settings-title-text",children:n.t("Advanced Settings")}),F.jsx(pi,{type:i?"icon-line-chevron-down":"icon-line-chevron-right",className:"advanced-settings-title-icon"})]}),i&&F.jsxs("div",{className:"advanced-settings-content",children:[F.jsx(bS,{data:e,setData:t}),F.jsx(gw,{title:n.t("Instructions"),tooltip:`${n.t("Define the specific role, tone, and response format you expect Qwen Studio to follow for this project.")}`,props:{value:e.custom_instruction||"",onChange:n=>{t(S(C({},e),{custom_instruction:n}))},minRows:2,maxRows:10,maxLength:1e3,placeholder:n.t("What should the AI know about this project? (e.g., specific rules, tone, or formatting)")}}),F.jsxs("div",{className:"project-file-list-container",children:[F.jsxs("div",{className:"project-file-list-title",children:[F.jsxs("div",{className:"project-file-list-info",children:[F.jsx("div",{className:"project-file-list-info-text",children:n.t("Files")}),!s&&F.jsx(Si,{title:n.t("Upload documents, images, or code to serve as a knowledge base for Qwen Studio within this project."),children:F.jsx(pi,{type:"icon-line-information-circle",className:"project-file-list-info-tooltip"})})]}),F.jsx(ww,{ref:c})]}),F.jsx(yw,{files:o,actions:["delete"],onReUpload:e=>A(null,null,function*(){var t,n,s,i;e&&"failed"===(null==(s=null==(n=null==(t=e.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)?null==(i=null==c?void 0:c.current)||i.startParse(e,!0):e&&e.uploadTaskId&&(yield fu.resumeUpload(e.uploadTaskId))}),onDownload:e=>{},onDelete:d})]})]})]})},wS=({editData:e,onCancel:t,operationProjectRef:n})=>{const{t:s}=ye(),{getNewProjectList:i,extractProjectId:a}=ig(),{getChatListData:o,getPinnedChatListData:r}=Tg(),l=cR(e=>e.mobile),c=pw(e=>e.deleteFiles),d=pw(e=>e.moveNewProjectId),u=pw(e=>e.operationProjectFiles),h=pw(e=>e.setProjectInfo),m=pw(e=>e.projectSettingOpen),p=pw(e=>e.setProjectSettingOpen),g=pw(e=>e.showEditModal),f=pw(e=>e.setProjectIcon),v=pw(e=>e.setProjectName),y=pw(e=>e.chatProjectId),b=Ns(e=>e.setPinnedChats),[x,w]=D.useState(e),[_,k]=D.useState(!1),j=Ue(),T=D.useRef(!1);D.useEffect(()=>{w(e)},[e]),D.useEffect(()=>{n&&(n.current=x)},[x,n]);const E=D.useMemo(()=>u.filter(e=>!c.includes(e.itemId)).some(e=>{var t,n,s;return"uploading"===e.status||"running"===(null==(s=null==(n=null==(t=null==e?void 0:e.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)}),[c,u]),N=()=>A(null,null,function*(){if(T.current)return;T.current=!0;const e=S(C({},x),{memory_span:x.memory_span||"default",icon:(null==x?void 0:x.icon)?null==x?void 0:x.icon:"icon=icon-line-folder-01&style=character-primary-text"});u.length&&m?e.files=u.filter(e=>!e.file_id&&"success"===e.uploadStatus&&"success"===e.greenNet).filter(e=>!c.includes(e.itemId)):e.files=[];const n=yield(a=C({},e),A(null,null,function*(){return yield TM("/projects/",{method:"POST",data:a})}));var a;if(n&&n.success){const{data:e}=n;if(d){const n=yield uw(e.id,[d]).catch(e=>(vi.open({type:"error",content:s(e.message)}),T.current=!1,null));if(null==n?void 0:n.success){if(o(1),i(),Jr(),Yr(),!l){const e=yield r();Array.isArray(e)&&b(e)}return t("createHandle"),void j(`/p/${e.id}`)}"Not_Found"===(null==n?void 0:n.data.code)&&i()}i(),t("createHandle"),j(`/p/${e.id}`)}T.current=!1}),I=()=>A(null,null,function*(){if(T.current)return;const e=u.filter(e=>{var t,n,s,i,a;return!e.file_id&&("success"===e.uploadStatus&&!(null==(n=null==(t=null==e?void 0:e.file)?void 0:t.meta)?void 0:n.parse_meta)||"success"===(null==(a=null==(i=null==(s=null==e?void 0:e.file)?void 0:s.meta)?void 0:i.parse_meta)?void 0:a.parse_status)||"success"===e.uploadStatus&&"success"===e.greenNet)}).filter(e=>!c.includes(e.itemId));T.current=!0;const n=yield rw(S(C({},x),{add_files:e,delete_files:c}),x.id);if(n&&n.success){if(T.current=!1,location.pathname.includes("/p/")){const e=a(location.pathname);h(C({},x)),x.id===e&&_w(x.id)}y===x.id&&(v(x.name),f(x.icon)),i(),t("updateHandle")}T.current=!1});D.useEffect(()=>{k(!(null==x?void 0:x.name)||!(null==x?void 0:x.name.trim()))},[null==x?void 0:x.custom_instruction,null==x?void 0:x.name,c.length,u.length,m]),D.useEffect(()=>{if(x.id){const e=u.length-c.length>0;(x.custom_instruction||e)&&g&&p(!0)}},[x,c.length,u.length,p,g]),D.useEffect(()=>{x.id||p(!1)},[x.id]);return l&&g?F.jsx(Ti,{open:g,onClose:()=>{t()},push:!1,heightType:"full",className:"project-edit-modal-menu-container",children:F.jsxs("div",{className:"project-edit-modal-menu-box",children:[F.jsxs("div",{className:"project-edit-modal-menu-header",children:[F.jsx("div",{className:"project-edit-modal-menu-header-text",children:s((null==x?void 0:x.id)?"Edit project":"New Project")}),F.jsx("div",{className:"project-edit-modal-menu-header-close",onClick:()=>{t()},children:F.jsx(pi,{type:"icon-line-x-01",className:"project-edit-modal-menu-header-icon"})})]}),F.jsxs("div",{className:"project-edit-modal-menu-content",children:[F.jsx(vS,{data:x,setData:w}),F.jsx(xS,{data:x,setData:w})]}),F.jsx("div",{className:"project-edit-modal-menu-buttons",children:x.id?F.jsxs(F.Fragment,{children:[F.jsx(xi,{type:"tertiary",rounded:"circle",buttonClass:"project-edit-modal-menu-button-cancel",size:"large",onClick:()=>{t()},children:s("Cancel")}),F.jsx(xi,{type:"brandprimary",rounded:"circle",buttonClass:"project-edit-modal-menu-button-save",size:"large",disabled:_,onClick:I,children:s("Save")})]}):F.jsx(xi,{type:"brandprimary",rounded:"circle",buttonClass:"project-edit-modal-menu-button-create",size:"large",disabled:_||E,onClick:N,children:s("Create project")})})]})}):F.jsxs(wi,{className:"project-edit-modal",visible:g,title:s((null==x?void 0:x.id)?"Edit project":"New Project"),headerBorderNone:!0,onCancel:()=>{t()},actions:[{text:s((null==x?void 0:x.id)?"Save":"Create project"),type:"brandprimary",rounded:"circle",buttonClass:"project-edit-modal-button",size:"middle",disabled:_||E,onClick:()=>{x.id?I():N()}}],children:[F.jsx(vS,{data:x,setData:w}),F.jsx(xS,{data:x,setData:w})]})},_S=()=>{const{i18n:e}=ye(),t=Ue(),[n,s]=D.useState(!1),i=cR(e=>e.mobile),a=pw(e=>e.operationProject),o=pw(e=>e.showEditModal),r=pw(e=>e.operationProjectFiles),l=pw(e=>e.deleteFiles),c=pw(e=>e.showDeleteConfirm),d=pw(e=>e.setShowEditModal),u=pw(e=>e.setProjectSettingOpen),h=pw(e=>e.setOperationProject),m=pw(e=>e.setDeleteFiles),p=pw(e=>e.setOperationProjectFiles),g=pw(e=>e.setMoveNewProjectId),f=pw(e=>e.setShowDeleteConfirm),v=pw(e=>e.setChatProjectId),y=js(e=>e.setProjectId),b=D.useRef(a),x=D.useRef([]),{getNewProjectList:w}=ig(),{getLibraryList:_}=gf(),C=e=>{const t=r.filter(e=>"uploading"===e.status).map(e=>e.itemId);r.forEach(e=>{var t,n,s;"running"===(null==(s=null==(n=null==(t=e.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)&&bM.emit(zu.FILE_PASE_REMOVE,e)}),s(!1),u(!1),h({}),d(!1),m(t),p([]),g("")};return D.useEffect(()=>{if(o){const e=[];r.forEach(t=>{e.push(t.itemId||t.file_id)}),x.current=e}else x.current=[]},[o]),F.jsxs(F.Fragment,{children:[F.jsx(wS,{editData:a,operationProjectRef:b,onCancel:e=>{var t,n;let i=!0;if(e||(null==(t=b.current)?void 0:t.custom_instruction)===a.custom_instruction&&(null==(n=b.current)?void 0:n.name)===a.name||(i=!1),!e&&i){const e=r.filter(e=>!(l.includes(e.itemId)||l.includes(e.file_id)));if(x.current.length!==e.length)i=!1;else{i=e.every(e=>{var t,n,s;return(x.current.includes(e.itemId)||x.current.includes(e.file_id))&&"uploading"!==e.status&&"running"!==(null==(s=null==(n=null==(t=null==e?void 0:e.file)?void 0:t.meta)?void 0:n.parse_meta)?void 0:s.parse_status)})}}i?C():s(!0)}}),F.jsx(wi,{visible:c,title:e.t("Delete this project?"),closable:!1,headerBorderNone:!0,onCancel:()=>{f(!1)},className:"project-delete-modal",actions:[{text:e.t("Cancel"),type:"tertiary",onClick:()=>{f(!1)},rounded:"circle",size:i?"large":"middle",style:i?{}:{height:"48px",fontSize:"16px"}},{text:e.t("Delete"),type:"dangerprimary",onClick:()=>A(null,null,function*(){const e=yield(n=null==a?void 0:a.id,A(null,null,function*(){return yield TM(`/projects/${n}`,{method:"DELETE"})}));var n;e&&(e.success||"Not_Found"===e.data.code)&&(w(),v(""),y(""),setTimeout(()=>{_()},2e3),t("/")),f(!1)}),rounded:"circle",size:i?"large":"middle",style:i?{}:{height:"48px",fontSize:"16px"}}],size:"small",children:e.t("This action cannot be undone. All files and chats within this project will be permanently deleted.")}),n&&F.jsx(Cw,{onCancel:()=>{s(!1)},onConfirm:()=>{C()}})]})},CS=O.lazy(()=>Se(()=>import("./index53.js"),__vite__mapDeps([17,0,2,3,5,18]))),SS=O.lazy(()=>Se(()=>import("./index47.js"),__vite__mapDeps([19,0,20,2,3,21,22,23,24,25,26,27]))),kS=O.lazy(()=>Se(()=>import("./index44.js"),__vite__mapDeps([28,0,20,2,3,21,23,24,25,26,29]))),jS=({communityType:e,children:t})=>{var n;const{pathname:s}=ze(),{id:i}=Ge(),a=Ld(e=>e.user),o=js(e=>e.history),r=cR(e=>e.config),l=cR(e=>e.mobile),c=cR(e=>e.pad),d=Rs(e=>e.omniType),u=`calc(100dvh - ${oi()} - ${ri()})`,h=cR(e=>e.cookieSettingModelsVisible),m=cR(e=>e.showCookieConfirm),p=Jh(e=>e.settings.manage_cookies),g=cR(e=>e.setCookieSettingModelsVisible),f=!!(_r(o.currentId,o).length>0||Object.keys(o.messages).length>0),v=D.useMemo(()=>s.includes("/p/"),[s]),y=D.useMemo(()=>v?i:"",[v,i]),b=D.useMemo(()=>{var e;return(null==(e=null==r?void 0:r.features)?void 0:e.enable_app_download)&&(l||c)&&!i?F.jsx("div",{className:"share-logo-content",children:F.jsx(Ax,{})}):null},[i,null==(n=null==r?void 0:r.features)?void 0:n.enable_app_download,l,c]),x=D.useMemo(()=>{const n="detailPage"===e;return F.jsxs("main",{className:"main-content",children:[F.jsxs(O.Suspense,{fallback:null,children:[F.jsx(SS,{visible:"homePage"===e}),F.jsx(kS,{visible:"collections"===e})]}),n&&t]})},[t,e]),w=D.useMemo(()=>e?F.jsx(pS,{isDetailPage:"detailPage"===e}):F.jsx(Bg,{}),[e]),_=D.useMemo(()=>v?F.jsx(mC,{projectId:y||""}):e?x:F.jsxs("main",{className:"main-content",children:[b,t||F.jsx(Be,{})]}),[t,e,y,v,x,b]);return wR()||!a||["user","admin"].includes(a.role)||f?F.jsxs("div",{className:"h5-layout",style:{maxHeight:u,minHeight:u},children:["/"!==s&&w,F.jsx(Tx,{fallback:null,children:!!a&&F.jsx(Ex,{})}),_,F.jsx(Px,{}),F.jsx(ow,{}),F.jsx(Rh,{}),F.jsx(pC,{}),F.jsx(gC,{}),F.jsx(xC,{}),m&&!p&&F.jsx(EC,{}),F.jsx(AC,{cookieSettingModelsVisible:h,setCookieSettingModelsVisible:g}),F.jsx(_S,{}),!!d&&F.jsx(O.Suspense,{fallback:null,children:F.jsx(CS,{show:d})})]}):F.jsx(op,{})};var TS=(e=>(e.CTRL="Ctrl/⌘",e.SHIFT="Shift",e.O="O",e.ESC="Esc",e.C="C",e.S="S",e.SEMICOLON=";",e.DOT=".",e.DELETE="⌫/Delete",e.SLASH="/",e))(TS||{});const ES=()=>{const e=ye(),[t,n]=D.useState(!1),s=D.useCallback(()=>A(null,null,function*(){try{yield SR(lt),vi.open({type:"success",content:e.t("Feedback email has been copied to the clipboard.")})}catch(t){vi.open({type:"error",content:e.t("Failed to copy the feedback email, please copy it manually.")})}}),[e]),[i,a]=D.useState(!1),o=D.useMemo(()=>[[{label:e.t("Open new chat"),keyboards:[TS.CTRL,TS.SHIFT,TS.O]},{label:e.t("Focus chat input"),keyboards:[TS.SHIFT,TS.ESC]},{label:e.t("Copy last code block"),keyboards:[TS.CTRL,TS.SHIFT,TS.SEMICOLON]},{label:e.t("Copy last response"),keyboards:[TS.CTRL,TS.SHIFT,TS.C]}],[{label:e.t("Toggle settings"),keyboards:[TS.CTRL,TS.DOT]},{label:e.t("Toggle sidebar"),keyboards:[TS.CTRL,TS.SHIFT,TS.S]},{label:e.t("Delete chat"),keyboards:[TS.CTRL,TS.SHIFT,TS.DELETE]},{label:e.t("Show shortcuts"),keyboards:[TS.CTRL,TS.SHIFT]}]],[e]);return F.jsxs(F.Fragment,{children:[F.jsx("div",{className:"qwen-chat-layout-help",children:F.jsx(Ci,{menu:{items:[{key:"email",icon:F.jsx(pi,{type:"icon-EmailOutLine"}),label:F.jsx("span",{className:"dropdown-item-custom",children:`${e.t("Email feedback")} ${lt}`}),onClick:s}]},trigger:["click"],open:t,onOpenChange:n,className:"qwen-chat-layout-help-drop-down",children:F.jsx(Si,{title:e.t("Help"),placement:"left",children:F.jsx(xi,{type:"textonly",rounded:"circle",className:"qwen-chat-layout-help-button",children:"?"})})})}),F.jsx("button",{id:"show-shortcuts-button",className:"qwen-chat-layout-help-hidden",onClick:()=>{a(!i)}}),F.jsx(wi,{className:"qwen-chat-layout-help-shortcuts-modal",title:e.t("Keyboard shortcuts"),visible:i,headerBorderNone:!0,footer:!1,onCancel:()=>a(!1),children:F.jsx("div",{className:"qwen-chat-layout-help-shortcuts",children:o.map((e,t)=>F.jsx("div",{className:"qwen-chat-layout-help-shortcuts-group",children:e.map(e=>F.jsxs("div",{className:"qwen-chat-layout-help-shortcuts-item",children:[F.jsx("div",{className:"qwen-chat-layout-help-shortcuts-item-label",children:e.label}),F.jsx("div",{className:"qwen-chat-layout-help-shortcuts-item-keyboards",children:e.keyboards.map(t=>F.jsx("div",{className:"qwen-chat-layout-help-shortcuts-item-keyboard",children:t},`${e.label}_${t}`))})]},e.label))},`shortcuts_group_${t}`))})})]})},NS=D.memo(()=>{const e=Fd(e=>e.showSubscriptionDetail),t=Fd(e=>e.setShowSubscriptionDetail),n=Fd(e=>e.fetchPaymentSubscriptionInfo),s=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_payment_and_quota}),{verifyIsPlusHandle:i,postPaymentSubscribeHandle:a,subscriptionLoading:o,freeUpgradeInfo:r,plusUpgradeInfo:l}=If(),c="proInfo",d=D.useCallback(()=>{const e=new URLSearchParams(window.location.search);e.delete(c);const n=`${window.location.pathname}${e.size>0?`?${e.toString()}`:""}`;window.history.replaceState({},"",n),t(!1)},[t]),u=D.useCallback(()=>(new URLSearchParams(window.location.search).get(c)||d(),!0),[d]),h=D.useCallback(()=>{const n=new URL(window.location.href).searchParams.get(c);if(s){if(n)t(!0);else if(e){const e=new URLSearchParams(window.location.search);e.set(c,"true");const t=`${window.location.pathname}?${e.toString()}`;window.history.pushState({},"",t)}}else d()},[s,d,t,e]),m=D.useCallback(()=>{a({redirection:!0,callback:d})},[d,a]);return D.useEffect(()=>{h()},[h]),D.useEffect(()=>{e?(h(),n(),i(d),window.addEventListener("popstate",u)):window.removeEventListener("popstate",u)},[e]),e&&s&&F.jsxs("div",{className:"chat-upgrade-detail",children:[F.jsx("div",{className:"chat-upgrade-detail-header",children:F.jsx(xi,{type:"textonly",iconFontType:"icon-close-4",showText:!1,onClick:d})}),F.jsxs("div",{className:"chat-upgrade-detail-container",children:[F.jsx("div",{className:"chat-upgrade-detail-title",children:r.upgradeTitle}),F.jsx("div",{className:"chat-upgrade-detail-info",children:[r,l].map(e=>{var t;return F.jsxs("div",{className:Q("chat-upgrade-detail-info-item",{"chat-upgrade-detail-info-item-plus":"Plus"===e.info.key}),children:[F.jsxs("div",{className:"chat-upgrade-detail-info-item-header",children:[F.jsx("div",{className:"chat-upgrade-detail-info-item-type",children:e.info.title}),e.info.tag&&F.jsx("div",{className:"chat-upgrade-detail-info-item-tag",children:F.jsx("div",{className:"chat-upgrade-detail-info-item-tag-text",children:e.info.tag})})]}),F.jsxs("div",{className:"chat-upgrade-detail-info-item-price-container",children:[F.jsxs("div",{className:"chat-upgrade-detail-info-item-price",children:["$",e.info.dollar]}),F.jsxs("div",{className:"chat-upgrade-detail-info-item-price-cycle",children:["/",e.info.cycle]})]}),F.jsx("div",{className:"chat-upgrade-detail-info-item-description",children:e.info.description}),F.jsx(xi,{type:"brandprimary",buttonClass:"chat-upgrade-detail-info-item-btn",disabled:(null==(t=e.info)?void 0:t.btnDisabled)||o,loading:o,onClick:m,children:e.info.btnText}),F.jsx("div",{className:"chat-upgrade-detail-info-features",children:e.info.features.map(e=>F.jsxs("div",{className:"chat-upgrade-detail-info-feature",children:[F.jsx(pi,{type:"icon-fill-check-contained",className:Q("chat-upgrade-detail-info-feature-icon",{enable:e.enable})}),F.jsx("div",{className:"chat-upgrade-detail-info-feature-label",children:e.text})]},e.text))})]},e.info.key)})})]})]})}),IS="index-module__memory-updated-modal___eTMkx",AS="index-module__memory-updated-item___S1d1j",MS="index-module__memory-updated-item-tag___j26p0",RS="index-module__new___YewIG",PS="index-module__updated___i060C",LS="index-module__cleared___LNso9",OS="index-module__memory-updated-item-text___SntJn",DS=()=>{const e=ye(),t=ud(e=>e.showMemoryUpdatedModal),n=ud(e=>e.setShowMemoryUpdatedModal),s=ud(e=>e.setShowMemorySavedModal),i=zp(e=>e.memoryNotification),{detail:{chat_id:a,new_memories:o,updated_memories:r,cleared_memories:l}={}}=i||{},[c,d]=D.useState({}),u=({tag:e,text:t,className:n,key:s})=>F.jsxs("div",{className:Q(AS,n),children:[F.jsx("div",{className:MS,children:e}),F.jsx("div",{className:OS,children:t})]},s);return D.useEffect(()=>{t&&a&&dg({chat_id:a},{toast:!1}).then(e=>{e&&e.success&&d(e.data)})},[t,a]),F.jsx(eh,{visible:t,title:e.t("Update Saved Memory Details"),subTitle:e.t('Updated saved memory in session "{{sessionName}}"',{sessionName:(null==c?void 0:c.title)||""}),cancelButtonProps:{hidden:!0},okText:e.t("Manage Memory"),okButtonProps:{type:"ghost",rounded:"circle",iconFontType:"icon-line-manage"},onOk:()=>{n(!1),s(!0)},onCancel:()=>{n(!1)},children:F.jsxs("div",{className:IS,children:[null==o?void 0:o.map(t=>u({tag:e.t("New Memory"),text:t.content,className:RS,key:t.memory_nodes_id})),null==r?void 0:r.map(t=>u({tag:e.t("Updated Memory"),text:t.content,className:PS,key:t.memory_nodes_id})),null==l?void 0:l.map(t=>u({tag:e.t("Cleared Memory"),text:t.content,className:LS,key:t.memory_nodes_id}))]})})},FS=O.lazy(()=>Se(()=>import("./index53.js"),__vite__mapDeps([17,0,2,3,5,18])));const qS=D.memo(function(){const e=Rs(e=>e.omniType),t=js(e=>e.chatMode),{pathname:n}=ze(),s=D.useMemo(()=>!n.includes("/p/")&&"community"!==t,[t,n]);return F.jsxs(F.Fragment,{children:[!!e&&F.jsx(O.Suspense,{fallback:null,children:F.jsx(FS,{show:e})}),F.jsx(Px,{}),F.jsx(vh,{}),F.jsx(DS,{}),F.jsx(Nh,{}),F.jsx(xC,{}),F.jsx(Wx,{}),s&&F.jsx(ES,{}),F.jsx(NS,{}),F.jsx(pC,{}),F.jsx(gC,{}),F.jsx(_S,{})]})}),US=O.lazy(()=>Se(()=>import("./index47.js"),__vite__mapDeps([19,0,20,2,3,21,22,23,24,25,26,27]))),HS=O.lazy(()=>Se(()=>import("./index44.js"),__vite__mapDeps([28,0,20,2,3,21,23,24,25,26,29]))),BS=({communityType:e,children:t})=>{const n=Ld(e=>e.user),s=js(e=>{const{history:t}=e;return!!(_r(t.currentId,t).length>0||Object.keys(t.messages).length>0)}),i=Ps(e=>e.temporaryChatEnabled),a=cR(e=>e.mobile),o=cR(e=>e.cookieSettingModelsVisible),r=cR(e=>e.showCookieConfirm),l=Jh(e=>e.settings.manage_cookies),c=cR(e=>e.setCookieSettingModelsVisible),d=D.useMemo(()=>{const s="detailPage"===e;return F.jsxs("div",{className:Q("layout-main",{"layout-main-none-width":!n}),children:[F.jsx(pS,{isDetailPage:s}),F.jsxs("main",{className:"main-content",children:[F.jsxs(O.Suspense,{fallback:null,children:[F.jsx(US,{visible:"homePage"===e}),F.jsx(HS,{visible:"collections"===e})]}),s&&t]})]})},[t,e,n]);return wR()||!n||["user","admin"].includes(n.role)||s?F.jsxs("div",{className:"desktop-layout",children:[r&&!l&&F.jsx(EC,{}),F.jsx(AC,{cookieSettingModelsVisible:o,setCookieSettingModelsVisible:c}),n&&!i&&F.jsx(Ex,{}),F.jsx(qS,{}),F.jsx("div",{className:"desktop-layout-content "+(i&&!a?"desktop-layout-content-temporary":""),children:e?d:t||F.jsx(Be,{})})]}):F.jsx(op,{})},zS=({children:e})=>{const{id:t,type:n}=Ge(),s=ze(),i=ti(),a=dR(e=>e.mobile);!function(){const e=Pd(e=>e.user),t=zp(e=>e.addWSNotification),n=zp(e=>e.setWSStatus),s=zp(e=>e.clearWSNotifications),i=zp(e=>e.setIsInitialized),a=zp(e=>e.setIsInitializing),o=zp(e=>e.setIsPullComplete),r=cR(e=>{var t,n;return null==(n=null==(t=null==e?void 0:e.config)?void 0:t.features)?void 0:n.enable_notification}),l=()=>A(null,null,function*(){if(!(null==e?void 0:e.id)||!r)return;const s=zp.getState();if(s.isInitialized||s.isInitializing)return;a(!0);const l=zp.getState();if(l.isInitialized)a(!1);else if(!0===l.isInitializing)try{const s=e.id;o(!1),Wp.connect(s,{onMessage:e=>{t(e)},onOpen:()=>{n("connected")},onClose:()=>{n("disconnected")},onError:e=>{n("error")},onReconnect:()=>{n("connecting")},onPullComplete:()=>{o(!0)}}),n(Wp.getStatus()),i(!0)}catch(c){n("error")}finally{a(!1)}else a(!1)}),c=D.useCallback(()=>{(null==e?void 0:e.id)&&r&&(Wp.disconnect(),i(!1),o(!1),l())},[null==e?void 0:e.id,r,i,o]);D.useEffect(()=>{if(null==e?void 0:e.id){const e=zp.getState();if(e.isInitialized){const e=Wp.getStatus();"disconnected"!==e&&"error"!==e||(i(!1),a(!1),l())}else e.isInitializing||l()}else{const e=zp.getState();(e.isInitialized||e.isInitializing)&&(Wp.disconnect(),s(),i(!1),a(!1))}},[null==e?void 0:e.id,r]),D.useEffect(()=>{if(r)return;const e=zp.getState();(e.isInitialized||e.isInitializing||"disconnected"!==e.wsStatus||e.wsNotifications.length>0)&&(Wp.disconnect(),s(),n("disconnected"),i(!1),a(!1),o(!1))},[r,s,n,i,a,o]),Wp.getStatus}();const o=D.useMemo(()=>t&&n?"detailPage":s.pathname.includes("/community/collections")?"collections":s.pathname.includes("/community")?"homePage":void 0,[t,n,s]);return i?F.jsx(rp,{children:e||F.jsx(Be,{})}):a?F.jsx(Je,{backend:Xe,children:F.jsx(jS,{communityType:o,children:e||F.jsx(Be,{})})}):F.jsx(Je,{backend:Xe,children:F.jsx(BS,{communityType:o,children:F.jsx(D.Suspense,{fallback:F.jsx(sh,{fixed:!1,center:!0}),children:e||F.jsx(Be,{})})})})},GS=D.createContext(null);GS.displayName="PanelGroupContext";const $S="data-panel-group",WS="data-panel-group-direction",VS="data-panel-group-id",QS="data-panel",KS="data-panel-collapsible",YS="data-panel-id",JS="data-panel-size",XS="data-panel-resize-handle-id",ZS=D.useLayoutEffect,ek=H["useId".toString()],tk="function"==typeof ek?ek:()=>null;let nk=0;function sk(e=null){const t=tk(),n=D.useRef(e||t||null);return null===n.current&&(n.current=""+nk++),null!=e?e:n.current}function ik(e){var t=e,{children:n,className:s="",collapsedSize:i,collapsible:a,defaultSize:o,forwardedRef:r,id:l,maxSize:c,minSize:d,onCollapse:u,onExpand:h,onResize:m,order:p,style:g,tagName:f="div"}=t,v=k(t,["children","className","collapsedSize","collapsible","defaultSize","forwardedRef","id","maxSize","minSize","onCollapse","onExpand","onResize","order","style","tagName"]);const y=D.useContext(GS);if(null===y)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:b,expandPanel:x,getPanelSize:w,getPanelStyle:_,groupId:j,isPanelCollapsed:T,reevaluatePanelConstraints:E,registerPanel:N,resizePanel:I,unregisterPanel:A}=y,M=sk(l),R=D.useRef({callbacks:{onCollapse:u,onExpand:h,onResize:m},constraints:{collapsedSize:i,collapsible:a,defaultSize:o,maxSize:c,minSize:d},id:M,idIsFromProps:void 0!==l,order:p});D.useRef({didLogMissingDefaultSizeWarning:!1}),ZS(()=>{const{callbacks:e,constraints:t}=R.current,n=C({},t);R.current.id=M,R.current.idIsFromProps=void 0!==l,R.current.order=p,e.onCollapse=u,e.onExpand=h,e.onResize=m,t.collapsedSize=i,t.collapsible=a,t.defaultSize=o,t.maxSize=c,t.minSize=d,n.collapsedSize===t.collapsedSize&&n.collapsible===t.collapsible&&n.maxSize===t.maxSize&&n.minSize===t.minSize||E(R.current,n)}),ZS(()=>{const e=R.current;return N(e),()=>{A(e)}},[p,M,N,A]),D.useImperativeHandle(r,()=>({collapse:()=>{b(R.current)},expand:e=>{x(R.current,e)},getId:()=>M,getSize:()=>w(R.current),isCollapsed:()=>T(R.current),isExpanded:()=>!T(R.current),resize:e=>{I(R.current,e)}}),[b,x,w,T,M,I]);const P=_(R.current,o);return D.createElement(f,S(C({},v),{children:n,className:s,id:M,style:C(C({},P),g),[VS]:j,[QS]:"",[KS]:a||void 0,[YS]:M,[JS]:parseFloat(""+P.flexGrow).toFixed(1)}))}const ak=D.forwardRef((e,t)=>D.createElement(ik,S(C({},e),{forwardedRef:t})));function ok(e){return"keydown"===e.type}function rk(e){return e.type.startsWith("pointer")}function lk(e){return e.type.startsWith("mouse")}ik.displayName="Panel",ak.displayName="forwardRef(Panel)";!function(){if("function"==typeof matchMedia)matchMedia("(pointer:coarse)").matches}();let ck=new Map;function dk(e,t){ck.set(e,t)}function uk(e,t){if(!e)throw Error(t)}function hk(e,t,n=10){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function mk(e,t,n=10){return 0===hk(e,t,n)}function pk(e,t,n){return 0===hk(e,t,n)}function gk({panelConstraints:e,panelIndex:t,size:n}){const s=e[t];uk(null!=s,`Panel constraints not found for index ${t}`);let{collapsedSize:i=0,collapsible:a,maxSize:o=100,minSize:r=0}=s;if(hk(n,r)<0)if(a){n=hk(n,(i+r)/2)<0?i:r}else n=r;return n=Math.min(o,n),n=parseFloat(n.toFixed(10))}function fk({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:s,prevLayout:i,trigger:a}){if(pk(e,0))return t;const o=[...t],[r,l]=s;uk(null!=r,"Invalid first pivot index"),uk(null!=l,"Invalid second pivot index");let c=0;if("keyboard"===a){{const s=e<0?l:r,i=n[s];uk(i,`Panel constraints not found for index ${s}`);const{collapsedSize:a=0,collapsible:o,minSize:c=0}=i;if(o){const n=t[s];if(uk(null!=n,`Previous layout not found for panel index ${s}`),pk(n,a)){const t=c-n;hk(t,Math.abs(e))>0&&(e=e<0?0-t:t)}}}{const s=e<0?r:l,i=n[s];uk(i,`No panel constraints found for index ${s}`);const{collapsedSize:a=0,collapsible:o,minSize:c=0}=i;if(o){const n=t[s];if(uk(null!=n,`Previous layout not found for panel index ${s}`),pk(n,c)){const t=n-a;hk(t,Math.abs(e))>0&&(e=e<0?0-t:t)}}}}{const s=e<0?1:-1;let i=e<0?l:r,a=0;for(;;){const e=t[i];uk(null!=e,`Previous layout not found for panel index ${i}`);if(a+=gk({panelConstraints:n,panelIndex:i,size:100})-e,i+=s,i<0||i>=n.length)break}const o=Math.min(Math.abs(e),Math.abs(a));e=e<0?0-o:o}{let s=e<0?r:l;for(;s>=0&&s=0))break;e<0?s--:s++}}if(function(e,t,n){if(e.length!==t.length)return!1;for(let s=0;s=0&&s0?s--:s++}}}return pk(o.reduce((e,t)=>t+e,0),100)?o:i}function vk({layout:e,panelsArray:t,pivotIndices:n}){let s=0,i=100,a=0,o=0;const r=n[0];uk(null!=r,"No pivot index found"),t.forEach((e,t)=>{const{constraints:n}=e,{maxSize:l=100,minSize:c=0}=n;t===r?(s=c,i=l):(a+=c,o+=l)});return{valueMax:Math.min(i,100-a),valueMin:Math.max(s,100-o),valueNow:e[r]}}function yk(e,t=document){return Array.from(t.querySelectorAll(`[${XS}][data-panel-group-id="${e}"]`))}function bk(e,t,n){const s=function(e,t,n=document){const s=yk(e,n).findIndex(e=>e.getAttribute(XS)===t);return null!=s?s:null}(e,t,n);return null!=s?[s,s+1]:[-1,-1]}function xk(e,t=document){if(((n=t)instanceof HTMLElement||"object"==typeof n&&null!==n&&"tagName"in n&&"getAttribute"in n)&&t.dataset.panelGroupId==e)return t;var n;const s=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return s||null}function wk(e,t=document){const n=t.querySelector(`[${XS}="${e}"]`);return n||null}function _k({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:s,panelDataArray:i,panelGroupElement:a,setLayout:o}){D.useRef({didWarnAboutMissingResizeHandle:!1}),ZS(()=>{if(!a)return;const e=yk(n,a);for(let t=0;t{e.forEach((e,t)=>{e.removeAttribute("aria-controls"),e.removeAttribute("aria-valuemax"),e.removeAttribute("aria-valuemin"),e.removeAttribute("aria-valuenow")})}},[n,s,i,a]),D.useEffect(()=>{if(!a)return;const e=t.current;uk(e,"Eager values not found");const{panelDataArray:i}=e;uk(null!=xk(n,a),`No group found for id "${n}"`);const r=yk(n,a);uk(r,`No resize handles found for group id "${n}"`);const l=r.map(e=>{const t=e.getAttribute(XS);uk(t,"Resize handle element has no handle id attribute");const[r,l]=function(e,t,n,s=document){var i,a,o,r;const l=wk(t,s),c=yk(e,s),d=l?c.indexOf(l):-1;return[null!==(i=null===(a=n[d])||void 0===a?void 0:a.id)&&void 0!==i?i:null,null!==(o=null===(r=n[d+1])||void 0===r?void 0:r.id)&&void 0!==o?o:null]}(n,t,i,a);if(null==r||null==l)return()=>{};const c=e=>{if(!e.defaultPrevented)switch(e.key){case"Enter":{e.preventDefault();const l=i.findIndex(e=>e.id===r);if(l>=0){const e=i[l];uk(e,`No panel data found for index ${l}`);const r=s[l],{collapsedSize:c=0,collapsible:d,minSize:u=0}=e.constraints;if(null!=r&&d){const e=fk({delta:pk(r,c)?u-c:c-r,initialLayout:s,panelConstraints:i.map(e=>e.constraints),pivotIndices:bk(n,t,a),prevLayout:s,trigger:"keyboard"});s!==e&&o(e)}}break}}};return e.addEventListener("keydown",c),()=>{e.removeEventListener("keydown",c)}});return()=>{l.forEach(e=>e())}},[a,e,t,n,s,i,o])}function Ck(e,t){if(e.length!==t.length)return!1;for(let n=0;n{const i=e[s];uk(i,`Panel data not found for index ${s}`);const{callbacks:a,constraints:o,id:r}=i,{collapsedSize:l=0,collapsible:c}=o,d=n[r];if(null==d||t!==d){n[r]=t;const{onCollapse:e,onExpand:s,onResize:i}=a;i&&i(t,d),c&&(e||s)&&(!s||null!=d&&!mk(d,l)||mk(t,l)||s(),!e||null!=d&&mk(d,l)||!mk(t,l)||e())}})}function Tk(e,t){if(e.length!==t.length)return!1;for(let n=0;nlocalStorage.getItem(e),e.setItem=(e,t)=>{localStorage.setItem(e,t)}}catch(t){e.getItem=()=>null,e.setItem=()=>{}}}function Nk(e){return`react-resizable-panels:${e}`}function Ik(e){return e.map(e=>{const{constraints:t,id:n,idIsFromProps:s,order:i}=e;return s?n:i?`${i}:${JSON.stringify(t)}`:JSON.stringify(t)}).sort((e,t)=>e.localeCompare(t)).join(",")}function Ak(e,t){try{const n=Nk(e),s=t.getItem(n);if(s){const e=JSON.parse(s);if("object"==typeof e&&null!=e)return e}}catch(n){}return null}function Mk(e,t,n,s,i){var a;const o=Nk(e),r=Ik(t),l=null!==(a=Ak(e,i))&&void 0!==a?a:{};l[r]={expandToSizes:Object.fromEntries(n.entries()),layout:s};try{i.setItem(o,JSON.stringify(l))}catch(c){}}function Rk({layout:e,panelConstraints:t}){const n=[...e],s=n.reduce((e,t)=>e+t,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(e=>`${e}%`).join(", ")}`);if(!pk(s,100)&&n.length>0)for(let a=0;a(Ek(Pk),Pk.getItem(e)),setItem:(e,t)=>{Ek(Pk),Pk.setItem(e,t)}},Lk={};function Ok(e){var t=e,{autoSaveId:n=null,children:s,className:i="",direction:a,forwardedRef:o,id:r=null,onLayout:l=null,keyboardResizeBy:c=null,storage:d=Pk,style:u,tagName:h="div"}=t,m=k(t,["autoSaveId","children","className","direction","forwardedRef","id","onLayout","keyboardResizeBy","storage","style","tagName"]);const p=sk(r),g=D.useRef(null),[f,v]=D.useState(null),[y,b]=D.useState([]),x=function(){const[e,t]=D.useState(0);return D.useCallback(()=>t(e=>e+1),[])}(),w=D.useRef({}),_=D.useRef(new Map),j=D.useRef(0),T=D.useRef({autoSaveId:n,direction:a,dragState:f,id:p,keyboardResizeBy:c,onLayout:l,storage:d}),E=D.useRef({layout:y,panelDataArray:[],panelDataArrayChanged:!1});D.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),D.useImperativeHandle(o,()=>({getId:()=>T.current.id,getLayout:()=>{const{layout:e}=E.current;return e},setLayout:e=>{const{onLayout:t}=T.current,{layout:n,panelDataArray:s}=E.current,i=Rk({layout:e,panelConstraints:s.map(e=>e.constraints)});Ck(n,i)||(b(i),E.current.layout=i,t&&t(i),jk(s,i,w.current))}}),[]),ZS(()=>{T.current.autoSaveId=n,T.current.direction=a,T.current.dragState=f,T.current.id=p,T.current.onLayout=l,T.current.storage=d}),_k({committedValuesRef:T,eagerValuesRef:E,groupId:p,layout:y,panelDataArray:E.current.panelDataArray,setLayout:b,panelGroupElement:g.current}),D.useEffect(()=>{const{panelDataArray:e}=E.current;if(n){if(0===y.length||y.length!==e.length)return;let t=Lk[n];null==t&&(t=function(e,t=10){let n=null;return(...s)=>{null!==n&&clearTimeout(n),n=setTimeout(()=>{e(...s)},t)}}(Mk,100),Lk[n]=t);const s=[...e],i=new Map(_.current);t(n,s,i,y,d)}},[n,y,d]),D.useEffect(()=>{});const N=D.useCallback(e=>{const{onLayout:t}=T.current,{layout:n,panelDataArray:s}=E.current;if(e.constraints.collapsible){const i=s.map(e=>e.constraints),{collapsedSize:a=0,panelSize:o,pivotIndices:r}=qk(s,e,n);if(uk(null!=o,`Panel size not found for panel "${e.id}"`),!mk(o,a)){_.current.set(e.id,o);const l=fk({delta:Fk(s,e)===s.length-1?o-a:a-o,initialLayout:n,panelConstraints:i,pivotIndices:r,prevLayout:n,trigger:"imperative-api"});Tk(n,l)||(b(l),E.current.layout=l,t&&t(l),jk(s,l,w.current))}}},[]),I=D.useCallback((e,t)=>{const{onLayout:n}=T.current,{layout:s,panelDataArray:i}=E.current;if(e.constraints.collapsible){const a=i.map(e=>e.constraints),{collapsedSize:o=0,panelSize:r=0,minSize:l=0,pivotIndices:c}=qk(i,e,s),d=null!=t?t:l;if(mk(r,o)){const t=_.current.get(e.id),o=null!=t&&t>=d?t:d,l=fk({delta:Fk(i,e)===i.length-1?r-o:o-r,initialLayout:s,panelConstraints:a,pivotIndices:c,prevLayout:s,trigger:"imperative-api"});Tk(s,l)||(b(l),E.current.layout=l,n&&n(l),jk(i,l,w.current))}}},[]),A=D.useCallback(e=>{const{layout:t,panelDataArray:n}=E.current,{panelSize:s}=qk(n,e,t);return uk(null!=s,`Panel size not found for panel "${e.id}"`),s},[]),M=D.useCallback((e,t)=>{const{panelDataArray:n}=E.current,s=Fk(n,e);return function({defaultSize:e,dragState:t,layout:n,panelData:s,panelIndex:i,precision:a=3}){const o=n[i];let r;return r=null==o?null!=e?e.toFixed(a):"1":1===s.length?"1":o.toFixed(a),{flexBasis:0,flexGrow:r,flexShrink:1,overflow:"hidden",pointerEvents:null!==t?"none":void 0}}({defaultSize:t,dragState:f,layout:y,panelData:n,panelIndex:s})},[f,y]),R=D.useCallback(e=>{const{layout:t,panelDataArray:n}=E.current,{collapsedSize:s=0,collapsible:i,panelSize:a}=qk(n,e,t);return uk(null!=a,`Panel size not found for panel "${e.id}"`),!0===i&&mk(a,s)},[]),P=D.useCallback(e=>{const{layout:t,panelDataArray:n}=E.current,{collapsedSize:s=0,collapsible:i,panelSize:a}=qk(n,e,t);return uk(null!=a,`Panel size not found for panel "${e.id}"`),!i||hk(a,s)>0},[]),L=D.useCallback(e=>{const{panelDataArray:t}=E.current;t.push(e),t.sort((e,t)=>{const n=e.order,s=t.order;return null==n&&null==s?0:null==n?-1:null==s?1:n-s}),E.current.panelDataArrayChanged=!0,x()},[x]);ZS(()=>{if(E.current.panelDataArrayChanged){E.current.panelDataArrayChanged=!1;const{autoSaveId:e,onLayout:t,storage:n}=T.current,{layout:s,panelDataArray:i}=E.current;let a=null;if(e){const t=function(e,t,n){var s,i;return null!==(i=(null!==(s=Ak(e,n))&&void 0!==s?s:{})[Ik(t)])&&void 0!==i?i:null}(e,i,n);t&&(_.current=new Map(Object.entries(t.expandToSizes)),a=t.layout)}null==a&&(a=function({panelDataArray:e}){const t=Array(e.length),n=e.map(e=>e.constraints);let s=0,i=100;for(let a=0;ae.constraints)});Ck(s,o)||(b(o),E.current.layout=o,t&&t(o),jk(i,o,w.current))}}),ZS(()=>{const e=E.current;return()=>{e.layout=[]}},[]);const O=D.useCallback(e=>{let t=!1;const n=g.current;if(n){"rtl"===window.getComputedStyle(n,null).getPropertyValue("direction")&&(t=!0)}return function(n){n.preventDefault();const s=g.current;if(!s)return()=>null;const{direction:i,dragState:a,id:o,keyboardResizeBy:r,onLayout:l}=T.current,{layout:c,panelDataArray:d}=E.current,{initialLayout:u}=null!=a?a:{},h=bk(o,e,s);let m=kk(n,e,i,a,r,s);const p="horizontal"===i;p&&t&&(m=-m);const f=fk({delta:m,initialLayout:null!=u?u:c,panelConstraints:d.map(e=>e.constraints),pivotIndices:h,prevLayout:c,trigger:ok(n)?"keyboard":"mouse-or-touch"}),v=!Tk(c,f);(rk(n)||lk(n))&&j.current!=m&&(j.current=m,dk(e,v||0===m?0:p?m<0?1:2:m<0?4:8)),v&&(b(f),E.current.layout=f,l&&l(f),jk(d,f,w.current))}},[]),F=D.useCallback((e,t)=>{const{onLayout:n}=T.current,{layout:s,panelDataArray:i}=E.current,a=i.map(e=>e.constraints),{panelSize:o,pivotIndices:r}=qk(i,e,s);uk(null!=o,`Panel size not found for panel "${e.id}"`);const l=fk({delta:Fk(i,e)===i.length-1?o-t:t-o,initialLayout:s,panelConstraints:a,pivotIndices:r,prevLayout:s,trigger:"imperative-api"});Tk(s,l)||(b(l),E.current.layout=l,n&&n(l),jk(i,l,w.current))},[]),q=D.useCallback((e,t)=>{const{layout:n,panelDataArray:s}=E.current,{collapsedSize:i=0,collapsible:a}=t,{collapsedSize:o=0,collapsible:r,maxSize:l=100,minSize:c=0}=e.constraints,{panelSize:d}=qk(s,e,n);null!=d&&(a&&r&&mk(d,i)?mk(i,o)||F(e,o):dl&&F(e,l))},[F]),U=D.useCallback((e,t)=>{const{direction:n}=T.current,{layout:s}=E.current;if(!g.current)return;const i=wk(e,g.current);uk(i,`Drag handle element not found for id "${e}"`);const a=Sk(n,t);v({dragHandleId:e,dragHandleRect:i.getBoundingClientRect(),initialCursorPosition:a,initialLayout:s})},[]),H=D.useCallback(()=>{v(null)},[]),B=D.useCallback(e=>{const{panelDataArray:t}=E.current,n=Fk(t,e);n>=0&&(t.splice(n,1),delete w.current[e.id],E.current.panelDataArrayChanged=!0,x())},[x]),z=D.useMemo(()=>({collapsePanel:N,direction:a,dragState:f,expandPanel:I,getPanelSize:A,getPanelStyle:M,groupId:p,isPanelCollapsed:R,isPanelExpanded:P,reevaluatePanelConstraints:q,registerPanel:L,registerResizeHandle:O,resizePanel:F,startDragging:U,stopDragging:H,unregisterPanel:B,panelGroupElement:g.current}),[N,f,a,I,A,M,p,R,P,q,L,O,F,U,H,B]),G={display:"flex",flexDirection:"horizontal"===a?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return D.createElement(GS.Provider,{value:z},D.createElement(h,S(C({},m),{children:s,className:i,id:r,ref:g,style:C(C({},G),u),[$S]:"",[WS]:a,[VS]:p})))}const Dk=D.forwardRef((e,t)=>D.createElement(Ok,S(C({},e),{forwardedRef:t})));function Fk(e,t){return e.findIndex(e=>e===t||e.id===t.id)}function qk(e,t,n){const s=Fk(e,t),i=s===e.length-1?[s-1,s]:[s,s+1],a=n[s];return S(C({},t.constraints),{panelSize:a,pivotIndices:i})}Ok.displayName="PanelGroup",Dk.displayName="forwardRef(PanelGroup)";const Uk=class e{constructor(){return j(this,"chats",new Map),j(this,"currentId",null),j(this,"currentChatId",null),j(this,"clearChatsStatus",()=>{this.chats.forEach(e=>{e.id!==this.currentId&&(e.setStatus({isLeave:!0}),e.destroy())})}),j(this,"forceClearAllChat",()=>{this.chats.forEach(e=>{e.forceClear()})}),E(e,d)?E(e,d):(I(e,d,this),this)}static getInstance(){return E(e,d)||I(e,d,new e),E(e,d)}getChats(){return this.chats}hasChat(e){return this.chats.has(e)}addChat(e,t){return this.chats.has(e)?(this.currentChatId=e,!1):(this.currentChatId=e,this.chats.set(e,t),!0)}getChat(e){return this.chats.get(e)}getChatByChatId(e){let t;return this.chats.forEach(n=>{n.chatId===e&&(t=n)}),t}removeChat(e){return!(!e||!this.chats.has(e))&&this.chats.delete(e)}size(){return this.chats.size}};d=new WeakMap,N(Uk,d,null);const Hk=Uk.getInstance(),Bk=D.memo(({user:e,menu:t=!0})=>{const n=()=>{var t;return(null==e?void 0:e.profile_image_url)?F.jsx("img",{src:e.profile_image_url,alt:e.name||"User"}):F.jsx("span",{className:"user-avatar-placeholder",children:(null==(t=null==e?void 0:e.name)?void 0:t.charAt(0))||"U"})};return e?t?F.jsx(nf,{placement:"bottomRight",children:F.jsx("div",{className:"user-avatar",children:n()})}):F.jsx("div",{className:"user-avatar",children:n()}):null}),zk="index-module__audio-card___lUXFC",Gk="index-module__audio-card-content___IEXg-",$k="index-module__audio-card-content-left___ictRc",Wk="index-module__qwen-left-icon___LKDGi",Vk="index-module__qwen-left-info___8Q9fA",Qk="index-module__qwen-left-info-name___gbVSI",Kk="index-module__qwen-left-info-name-text___eX1Ys",Yk="index-module__qwen-left-info-name-ext___H5xGW",Jk="index-module__qwen-left-info-time___eotBv",Xk="index-module__audio-card-content-right___gmh3w",Zk="index-module__audio-card-content-right-disabled___MlkD8",ej=({url:e,id:t,name:n})=>{const[s,i]=D.useState(""),[a,o]=D.useState(""),[r,l]=D.useState(!1),[c,d]=D.useState(!0),[u,h]=D.useState({currTime:"00:00",duration:"00:00"}),m=D.useRef(null),p=D.useCallback(e=>{h(e)},[]);return D.useEffect(()=>{const e=(null==n?void 0:n.lastIndexOf("."))||-1;i(-1===e?n:n.slice(0,n.lastIndexOf("."))),o(-1===e?"":n.slice(e+1))},[n]),e?F.jsxs("div",{className:zk,children:[F.jsxs("div",{className:Gk,children:[F.jsxs("div",{className:$k,children:[F.jsx(ie,{className:Wk,justify:"center",align:"center",children:F.jsx(pi,{type:"iconaudio"})}),F.jsxs(ie,{className:Vk,vertical:!0,justify:"space-between",flex:1,children:[F.jsxs(ie,{className:Qk,align:"center",children:[F.jsx("div",{className:Kk,children:s}),F.jsx("div",{className:Yk,children:a?`.${a}`:""})]}),F.jsxs(ie,{className:Jk,align:"center",gap:4,children:[F.jsx("span",{children:u.currTime}),F.jsx("span",{children:"/"}),F.jsx("span",{children:u.duration})]})]})]}),F.jsx("div",{className:Q(Xk,{[Zk]:!r}),onClick:()=>A(null,null,function*(){var e;null==(e=m.current)||e.toggle()}),children:F.jsx(pi,{type:c?"icon-pause":"icon-play"})})]}),F.jsx(Pi,{ref:m,url:e,id:t,showHandler:!1,onLoaded:l,onPause:d,onPlay:d,getPlayingDuration:p,getFileNewUrlWhenLoadError:e=>A(null,null,function*(){var t;const n=yield RM({fileUrl:e});if(n&&n.success)return null==(t=n.data)?void 0:t.fileUrl})})]}):null},tj=({mediaType:e,messageId:t,preview:n})=>{const{i18n:s}=ye(),i=cR(e=>e.mobile),a=js(e=>e.chatId),o=js(e=>{var t;return null==(t=e.branchInfo)?void 0:t.isTemp}),r=Rs(e=>e.setWelcomeModalShow),l=Rs(e=>e.featureStatuses),c=D.useMemo(()=>{const e=l.find(e=>e.feature===Lh.VideoGeneration);return(null==e?void 0:e.disabledInfo)||{disabled:!1,msg:""}},[l]),d=D.useMemo(()=>{const e=l.find(e=>e.feature===Lh.ImageGeneration);return(null==e?void 0:e.disabledInfo)||{disabled:!1,msg:""}},[l]),[u,h]=D.useState(!1),[m,p]=D.useState(!1),[g,f]=D.useState(""),v=D.useCallback((l,u)=>{const{image:g,video:f}=u,v=("image"===e?null==g?void 0:g.url:null==f?void 0:f.url)||"";let y=(null==n?void 0:n.actions)||["download"];return o&&(y=[]),F.jsx("div",{className:`qwen-image-preview-operations-wrapper ${!i&&(null==n?void 0:n.tip)?"qwen-image-preview-operations-wrapper-tip":""} ${1===y.length?"single-button":""}`,children:F.jsxs("div",{className:"qwen-media-preview-toolbar",children:[!i&&(null==n?void 0:n.tip)&&F.jsxs("div",{className:"qwen-media-preview-toolbar-info",children:[F.jsx(pi,{type:"icon-line-alert-circle"}),null==n?void 0:n.tip]}),F.jsx("div",{className:"qwen-media-preview-toolbar-btn",children:y.map(e=>{switch(e){case"download":return F.jsxs("div",{className:"qwen-media-preview-toolbar-item",onClick:e=>A(null,null,function*(){e.stopPropagation(),pl("clkdownloadBtn",{params:{et:"CLK",c5:"preview",c6:v},paramsExtend:{chat_id:a,msg_id:t||""}}),["img.alicdn.com","image.qwenlm.ai/public_source"].find(e=>v.includes(e))?yield Ml(v):yield Pl({role:"assistant",url:v})}),children:[F.jsx(pi,{type:"icon-line-download-02"}),i?null:F.jsx("div",{children:s.t("Download")})]},e);case"share":return F.jsxs("div",{className:"qwen-media-preview-toolbar-item",onClick:e=>A(null,null,function*(){e.stopPropagation(),pl("clkShareBtn",{params:{et:"CLK",c5:"preview",c6:v},paramsExtend:{chat_id:a,msg_id:t||""}});const n=yield Il("assistant",v);(yield SR(n))&&vi.open({type:"success",content:s.t("Copying to clipboard was successful!")})}),children:[F.jsx(pi,{type:"icon-line-share-01"}),i?null:F.jsx("div",{children:s.t("Share")})]},e);case"publish":return F.jsxs(F.Fragment,{children:[F.jsxs("div",{className:"qwen-media-preview-toolbar-item",onClick:e=>{e.stopPropagation(),ti()?bM.adapter.invoke({method:"openPublishingRightsWindow",params:{from:"chat",chatId:a,msgId:t||""}}):p(!0)},children:[F.jsx(pi,{type:"icon-line-Publish"}),i?null:F.jsx("div",{children:s.t("Publish")})]},e),F.jsx(PC,{open:m,onCancel:()=>{p(!1)},messageId:t})]});case"edit":{const t=d.disabled;return F.jsx(Si,{show:t&&!!d.msg,title:d.msg||"",children:F.jsxs("div",{className:"qwen-media-preview-toolbar-item qwen-media-preview-toolbar-item-pd-8-12",style:t?{opacity:.5,cursor:"not-allowed"}:void 0,onClick:()=>A(null,null,function*(){if(t)return;const e=[{type:"image",name:"example.png",file_type:"image/png",showType:"image",file_class:"vision",status:"uploaded",url:v}];yield bM.makeVideoOrImageByImageGen({chatType:yt.ImageGeneration,subChatType:yt.ImageGeneration,files:e}),h(!1)}),children:[F.jsx(pi,{type:"icon-line-edit-contained"}),F.jsx("div",{className:"qwen-media-preview-toolbar-item-text",children:s.t("Edit")})]})},e)}case"video":{const t=c.disabled;return F.jsx(Si,{show:t&&!!c.msg,title:c.msg||"",children:F.jsxs("div",{className:"qwen-media-preview-toolbar-item qwen-media-preview-toolbar-item-pd-8-12",style:t?{opacity:.5,cursor:"not-allowed"}:void 0,onClick:()=>A(null,null,function*(){t||(wR()?ti()?yield bM.adapter.invoke({method:"showAlert",params:{type:"login"}}):r(!0):(yield bM.makeVideoOrImageByImageGen({chatType:yt.VideoGeneration,files:[{type:"image",name:"example.png",file_type:"image/png",showType:"image",file_class:"vision",status:"uploaded",url:v}]}),h(!1)))}),children:[F.jsx(pi,{type:"icon-line-video-generation-01"}),F.jsx("div",{className:"qwen-media-preview-toolbar-item-text",children:s.t("Create video")})]})},e)}}})})]})})},[e,null==n?void 0:n.actions,null==n?void 0:n.tip,o,i,s,m,t,a,r,c,d]),y=D.useCallback(t=>{i&&(null==n?void 0:n.tip)&&t&&"image"===e&&vi.openOnce({type:"caution",content:null==n?void 0:n.tip,closable:!1}),ti()||h(t)},[e,i,null==n?void 0:n.tip]),b=D.useCallback(s=>{if(ti()){const{chatId:i,currentInputFeature:a}=js.getState();bM.adapter.invoke({method:"openMediaPreview",params:{type:e,urls:[null==s?void 0:s.url],chatId:i,msgId:t,msgType:a,tips:(null==n?void 0:n.tip)?[n.tip]:[]}})}else f(s.url)},[e,t,null==n?void 0:n.tip]);return{preview:D.useMemo(()=>ti()?void 0:{maskClosable:!0,toolbarRender:v,onVisibleChange:y,visible:u,onStateChange:e=>{}},[v,u,y]),currentPreviewUrl:g,onClick:b}},nj=({url:e,generation:t,error:n,mediaProps:s,ratio:i,containerWidth:a,onError:o,customScope:r,messageType:l})=>{const{i18n:c}=ye(),d=cR(e=>e.mobile),u=js(e=>e.chatId),h=D.useRef(0),m=D.useRef(0),p=D.useMemo(()=>r||(d?{width:[114,300],height:[126,380]}:[133,400]),[d,r]);D.useEffect(()=>{h.current=qR()});const g=D.useMemo(()=>{if(i){const[e,t]=i.split(":");return{width:Number(e),height:Number(t)}}return{width:0,height:0}},[i]),f=D.useMemo(()=>{const{width:e,height:t}=d?((e,t=0)=>{const n=[375,667],s=[307,380],i=window.screen.width,a=window.screen.height,o=Math.min(i/n[0],a/n[1]);let r=o*s[0],l=o*s[1];i-th?l=Math.round(r/u*h):u{const s=.825*(window.innerWidth||document.documentElement.clientWidth),i=.4*(window.innerHeight||document.documentElement.clientHeight);let a=Math.min(n,s),o=Math.min(n,i);if(a=o=Math.min(a,o),ai&&(o=Math.round(a/s*i)),s=t&&d&&a){const i=.9*a;n=i,s=i/e*t}return{width:n,height:s}},[d,i,a]);return F.jsx(Cx,S(C({url:e,poster:Df(e),defaultWidth:g.width||16,defaultHeight:g.height||9,controls:!1,width:null==f?void 0:f.width,height:null==f?void 0:f.height,sizeScope:p,generation:t,firstFramePoster:!0,unSupportMessage:c.t("Your browser does not support the video tag."),error:n,onError:o},s),{autoPlay:!0,onLoad:()=>{m.current=qR(),pl("messageVideoOnLoadTime",{params:{et:"OTHER",c4:u||"",c5:l,c6:e,c7:Math.round(h.current),c8:Math.round(m.current),c9:Math.round(m.current-h.current)}})},style:d?{maxWidth:"11.25rem",maxHeight:"12rem"}:{}}))},sj={greenNetError:"index-module__green-net-error___xxZRT",qwenVideoViewerContentOperations:"index-module__qwen-video-viewer-content-operations___47tr9"},ij={greenNetError:"index-h5-module__green-net-error___AKDlS",greenNetErrorIcon:"index-h5-module__green-net-error-icon___9s-Sn",qwenVideoViewerContentOperations:"index-h5-module__qwen-video-viewer-content-operations___sdzKj",qwenImagePreviewOperationsWrapper:"index-h5-module__qwen-image-preview-operations-wrapper___Tdm5X"},aj={actions:["download"]},oj=D.memo(({url:e,isImage:t,isVideo:n,isMobile:s,greenNet:i,messageId:a})=>{const o="green_error"===i,[r,l]=D.useState(0),c=js(e=>e.chatId),d=D.useRef(0),u=D.useRef(0),[h,m]=D.useState(e),p=D.useMemo(()=>s?ij:sj,[s]),g=tj({mediaType:t?"image":"video",messageId:a,preview:aj}),f=D.useMemo(()=>s?[96,180]:[112,112],[s]),v=D.useMemo(()=>s?{height:[96,192],width:[96,192]}:[320,320],[s]),y=D.useCallback(()=>A(null,null,function*(){if(Nl(h)){const{success:e,data:t}=yield RM({fileUrl:h});e&&(null==t?void 0:t.fileUrl)&&m(t.fileUrl)}}),[h]);D.useEffect(()=>{const e=document.getElementById("chat-message-container");e&&l(null==e?void 0:e.getBoundingClientRect().width),d.current=qR()},[]);const b=D.useCallback((e,t,n)=>{pl("messageImgOnLoadTime",{params:{et:"OTHER",c4:c||"",c5:"query",c6:n,c7:Math.round(e),c8:Math.round(t),c9:Math.round(t-e)}})},[c]);return o?F.jsx(ie,{className:p.greenNetError,justify:"center",align:"center",children:F.jsx(pi,{className:p.greenNetErrorIcon,type:"icon-line-image-x-2"})}):t?F.jsx(dx,S(C({url:h,defaultWidth:1,defaultHeight:1,thumbnailUrl:Of(h),sizeScope:f,onError:()=>{y()},id:a},g),{onLoad:()=>{u.current=qR(),b(d.current,u.current,h)}})):n?F.jsx(nj,{url:h,generation:void 0,error:!1,onError:()=>{y()},ratio:"1:1",containerWidth:r>192?192:r,customScope:v,mediaProps:g,messageType:"query"}):null}),rj={fileMessage:"index-module__file-message___SeOoR",fileMessageImage:"index-module__file-message-image___eDmks",fileMessageAudio:"index-module__file-message-audio___clhPw",fileMessageDocument:"index-module__file-message-document___OjWnc"},lj={fileMessage:"index-h5-module__file-message___gacd4",fileMessageImage:"index-h5-module__file-message-image___1smH3",fileMessageVideo:"index-h5-module__file-message-video___PZ8v0",fileMessageDocument:"index-h5-module__file-message-document___etdmB"};var cj=(e=>(e.INITIALIZED="initialized",e.LOADING="loading",e.READY="ready",e.PLAYING="playing",e.PAUSED="paused",e.STOPPED="stopped",e.UNSUPPORTED_LANGUAGE="unsupportedLanguage",e))(cj||{}),dj=(e=>(e.AUDIO_CONTEXT="audioContext",e.HTML_AUDIO="htmlAudio",e.SIMPLE_HTML_AUDIO="simpleHtmlAudio",e.HTML_AUDIO_CXT="htmlAudioCxt",e))(dj||{});class uj{constructor(e){j(this,"_state",cj.STOPPED),j(this,"options"),j(this,"audioContext",null),j(this,"gainNode",null),j(this,"audioCtxInitialized",!1),j(this,"isProcessingQueue",!1),j(this,"startTime",0),j(this,"currentTime",0),j(this,"audioBuffer",null),j(this,"bufferSize",8192),j(this,"minBufferSize",1024),j(this,"processedSamples",0),j(this,"isStreamPlaying",!1),j(this,"currentSource",null),j(this,"nextSource",null),j(this,"preloadThreshold",.5),j(this,"isPreloading",!1),j(this,"maxChunkSize",4096),j(this,"isFirstChunk",!0),j(this,"hasReceivedData",!1),j(this,"isDataComplete",!1),j(this,"preloadTimers",new Set),j(this,"sampleRate",24e3),j(this,"channels",1),this.options={onStateChange:e.onStateChange||(()=>{}),onError:e.onError||(()=>{})},this.initAudioContext()}initAudioContext(){return A(this,null,function*(){var e,t;try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.gainNode.gain.value=1,this.audioCtxInitialized=!0,this.setState(cj.INITIALIZED)}catch(n){throw null==(t=(e=this.options).onError)||t.call(e,n),new Error("Web Audio API 不可用,无法初始化播放器")}})}appendPCMBuffer(e,t=!1){if(this.hasReceivedData||(this.setState(cj.LOADING),this.hasReceivedData=!0),!this.audioCtxInitialized)throw new Error("Web Audio API 未初始化");this.audioBuffer||(this.audioBuffer=new Float32Array(this.bufferSize),this.processedSamples=0);const n=this.pcmBufferToFloat32(e),s=Math.floor(this.currentTime*this.sampleRate)-this.processedSamples,i=s+n.length;if(this.audioBuffer.length=this.minBufferSize||t)&&(this.isStreamPlaying||this._state===cj.PLAYING||this._state===cj.STOPPED||this.startStreamingPlayback(),this._state!==cj.PLAYING||this.isProcessingQueue||this.processAudioBuffer(t)),t&&(this.isDataComplete=!0)}startStreamingPlayback(){var e;this.audioContext&&"suspended"===this.audioContext.state&&this.audioContext.resume(),this.isStreamPlaying=!0,this.startTime=(null==(e=this.audioContext)?void 0:e.currentTime)||0,this.isFirstChunk=!0,this.setState(cj.PLAYING)}processAudioBuffer(e=!1){var t,n;if(this._state!==cj.STOPPED&&this.isStreamPlaying&&this.audioBuffer&&!this.isProcessingQueue&&this.audioContext)if(this.currentSource&&this.currentSource.buffer)this.isWaitingForNextChunk=!0;else{this.isProcessingQueue=!0;try{const t=Math.floor(this.currentTime*this.sampleRate)-this.processedSamples;if(t<=0)return(e||this.isDataComplete)&&(this.isStreamPlaying=!1,this.setState(cj.STOPPED)),void(this.isProcessingQueue=!1);let n=Math.min(t,this.audioBuffer.length-this.processedSamples);if(e)n=Math.min(t,this.audioBuffer.length-this.processedSamples);else{if(this.isFirstChunk){const e=Math.min(512,this.minBufferSize);if(!(n>=e))return void(this.isProcessingQueue=!1);this.isFirstChunk=!1}if(!this.isFirstChunk&&(n=Math.min(n,this.maxChunkSize),n{this.processedSamples+=n,this.currentSource=null;const t=Math.floor(this.currentTime*this.sampleRate);!(this.processedSamples{!this.isStreamPlaying||this.isPreloading||n||this._state!==cj.PLAYING||this.preloadNextChunk(),this.preloadTimers.delete(i)},1e3*s);this.preloadTimers.add(i);const a=e.onended;e.onended=()=>{clearTimeout(i),this.preloadTimers.delete(i),a&&a.call(e,new Event("ended"))}}preloadNextChunk(){if(this._state!==cj.STOPPED&&this.isStreamPlaying&&!this.isPreloading&&this.audioBuffer){this.isPreloading=!0;try{const e=Math.floor(this.currentTime*this.sampleRate)-this.processedSamples;if(e<=0)return void(this.isPreloading=!1);const t=Math.min(e,this.audioBuffer.length-this.processedSamples);if(t<=0)return void(this.isPreloading=!1);const n=this.audioContext.createBuffer(this.channels,t,this.sampleRate);for(let i=0;iclearTimeout(e)),this.preloadTimers.clear(),this.isStreamPlaying=!1,this.isWaitingForNextChunk=!1,this.isPreloading=!1,this.setState(cj.STOPPED)})}reset(){return A(this,null,function*(){yield this.stop(),this.hasReceivedData=!1,this.isDataComplete=!1,this.audioBuffer=null,this.currentTime=0,this.startTime=0,this.processedSamples=0,this.isStreamPlaying=!1,this.isWaitingForNextChunk=!1,this.isPreloading=!1,this.isFirstChunk=!0,this.currentSource=null,this.nextSource=null,this.preloadTimers.forEach(e=>clearTimeout(e)),this.preloadTimers.clear(),this.setState(cj.STOPPED)})}resetPlayback(){return A(this,null,function*(){yield this.stop(),this.currentTime=0,this.startTime=0,this.processedSamples=0,this.isStreamPlaying=!1,this.isWaitingForNextChunk=!1,this.isPreloading=!1,this.isFirstChunk=!0,this.currentSource=null,this.nextSource=null,this.preloadTimers.forEach(e=>clearTimeout(e)),this.preloadTimers.clear(),this.audioBuffer&&this.hasReceivedData&&(this.currentTime=this.audioBuffer.length/this.sampleRate),this.hasReceivedData?this.setState(cj.READY):this.setState(cj.STOPPED)})}destroy(){this.stop(),this.preloadTimers.forEach(e=>clearTimeout(e)),this.preloadTimers.clear(),this.audioCtxInitialized&&(this.audioContext&&"closed"!==this.audioContext.state&&this.audioContext.close(),this.gainNode=null,this.audioContext=null),this.setState(cj.STOPPED)}setState(e){var t,n;this._state!==e&&(this._state=e,null==(n=(t=this.options).onStateChange)||n.call(t,e))}get volume(){var e;if(!this.audioCtxInitialized)throw new Error("Web Audio API 未初始化");return(null==(e=this.gainNode)?void 0:e.gain.value)||0}set volume(e){if(!this.audioCtxInitialized)throw new Error("Web Audio API 未初始化");this.gainNode.gain.value=e}get state(){return this._state}get isReady(){return this._state===cj.READY}get isLoading(){return this._state===cj.LOADING}get isPlaying(){return this._state===cj.PLAYING}get isPaused(){return this._state===cj.PAUSED}get isStopped(){return this._state===cj.STOPPED}get hasData(){return this.hasReceivedData}get isComplete(){return this.isDataComplete}setAudioParams(e,t=1){this.sampleRate=e,this.channels=t}}class hj{constructor(e){j(this,"_state",cj.STOPPED),j(this,"options"),j(this,"audioElement",null),j(this,"audioCtxInitialized",!1),j(this,"minBufferSize",1024),j(this,"isStreamPlaying",!1),j(this,"isAudioCreated",!1),j(this,"audioChunks",[]),j(this,"hasReceivedData",!1),j(this,"isDataComplete",!1),j(this,"currentBlobURL",null),j(this,"playedChunksCount",0),j(this,"lastUpdateTime",0),j(this,"isUpdatingAudio",!1),j(this,"updateQueue",[]),j(this,"retryCount",0),j(this,"maxRetries",3),j(this,"isManuallyStopped",!1),j(this,"stopRequested",!1),j(this,"pendingTimeouts",new Set),j(this,"sampleRate",24e3),j(this,"channels",1),j(this,"bitsPerSample",16),j(this,"audioInitAbortHandler",()=>{}),j(this,"audioInitCanplayHandler",()=>{var e;this.setState(cj.READY),!(null==(e=this.audioElement)?void 0:e.paused)||this.isManuallyStopped||this.stopRequested||this.audioElement.play().catch(e=>{})}),j(this,"audioInitPlayHandler",()=>{this.setState(cj.PLAYING)}),j(this,"audioInitPauseHandler",()=>{this.setState(cj.PAUSED)}),j(this,"audioInitEndedHandler",()=>{if(this.isManuallyStopped||this.stopRequested)this.setState(cj.STOPPED);else if(this.setState(cj.STOPPED),this.isStreamPlaying&&!this.isDataComplete&&this.audioChunks.length>this.playedChunksCount&&!this.isManuallyStopped&&!this.stopRequested){const e=setTimeout(()=>{var t;this.pendingTimeouts.delete(e),(null==(t=this.audioElement)?void 0:t.paused)&&this.isStreamPlaying&&this.audioChunks.length>this.playedChunksCount&&!this.isManuallyStopped&&!this.stopRequested&&this.queueUpdate(()=>this.updateStreamingAudio())},100);this.pendingTimeouts.add(e)}else this.isDataComplete&&(this.isStreamPlaying=!1)}),j(this,"audioInitErrorHandler",e=>{var t,n;null==(n=(t=this.options).onError)||n.call(t,new Error("音频播放错误"))}),j(this,"audioCanPlayHandler",()=>{this.removeAudioEventListeners(),this.playAudio()}),j(this,"audioErrorHandler",()=>{var e,t;this.removeAudioEventListeners(),null==(t=(e=this.options).onError)||t.call(e,new Error("音频加载失败"))}),this.options={onStateChange:e.onStateChange||(()=>{}),onError:e.onError||(()=>{})},this.initHTMLAudio()}initHTMLAudio(){return A(this,null,function*(){var e,t;try{this.audioElement=document.createElement("audio"),this.audioElement.style.display="none",this.audioElement.preload="auto",this.audioElement.controls=!1,this.audioElement.volume=1,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("abort",this.audioInitAbortHandler),this.audioElement.addEventListener("canplay",this.audioInitCanplayHandler),this.audioElement.addEventListener("play",this.audioInitPlayHandler),this.audioElement.addEventListener("pause",this.audioInitPauseHandler),this.audioElement.addEventListener("ended",this.audioInitEndedHandler),this.audioElement.addEventListener("error",this.audioInitErrorHandler),this.audioCtxInitialized=!0,this.setState(cj.INITIALIZED)}catch(n){throw null==(t=(e=this.options).onError)||t.call(e,n),new Error("简单 HTML Audio 播放器初始化失败")}})}appendPCMBuffer(e,t=!1){var n,s;if(this.isManuallyStopped||this.stopRequested)return;if(this.hasReceivedData||(this.setState(cj.LOADING),this.hasReceivedData=!0),!this.audioCtxInitialized)throw new Error("简单 HTML Audio 播放器未初始化");this.audioChunks.push(e);if(this.audioChunks.reduce((e,t)=>e+t.length,0)>=this.minBufferSize&&!this.isStreamPlaying&&!this.isAudioCreated&&this.startStreamingPlayback(),this.isStreamPlaying&&this.isAudioCreated&&(null==(n=this.audioElement)?void 0:n.paused)){const e=Date.now();e-this.lastUpdateTime>200&&this.audioChunks.length>this.playedChunksCount&&(this.lastUpdateTime=e,this.queueUpdate(()=>this.updateStreamingAudio()))}t&&(this.isDataComplete=!0,this.isStreamPlaying?this.isAudioCreated&&(null==(s=this.audioElement)?void 0:s.paused)&&this.queueUpdate(()=>this.updateStreamingAudio()):this.startStreamingPlayback())}startStreamingPlayback(){this.isStreamPlaying||this.isManuallyStopped||this.stopRequested||(this.isStreamPlaying=!0,this.setState(cj.PLAYING),this.queueUpdate(()=>this.updateStreamingAudio()))}waitForAudioLoadAndPlay(){this.audioElement&&(this.isManuallyStopped||this.stopRequested||(this.audioElement.readyState>=2?this.playAudio():(this.audioElement.addEventListener("canplay",this.audioCanPlayHandler),this.audioElement.addEventListener("error",this.audioErrorHandler))))}queueUpdate(e){this.isManuallyStopped||this.stopRequested||(this.isUpdatingAudio?this.updateQueue.push(e):this.executeUpdate(e))}executeUpdate(e){if(this.isManuallyStopped||this.stopRequested)this.processNextUpdate();else{this.isUpdatingAudio=!0;try{e()}catch(t){this.isUpdatingAudio=!1,this.processNextUpdate()}}}processNextUpdate(){if(this.isManuallyStopped||this.stopRequested)return this.updateQueue=[],void(this.isUpdatingAudio=!1);if(this.updateQueue.length>0){const e=this.updateQueue.shift();if(e){const t=setTimeout(()=>{this.pendingTimeouts.delete(t),this.executeUpdate(e)},50);this.pendingTimeouts.add(t)}}else this.isUpdatingAudio=!1}updateStreamingAudio(){var e,t;if(this.isManuallyStopped||this.stopRequested)this.processNextUpdate();else if(this.audioElement&&0!==this.audioChunks.length)if(this.audioChunks.length<=this.playedChunksCount)this.processNextUpdate();else if(this.audioElement.paused||this.audioElement.ended)try{const e=this.audioChunks.slice(this.playedChunksCount),t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;const i=this.createWAVFile(n);this.currentBlobURL&&URL.revokeObjectURL(this.currentBlobURL);const a=new Blob([i],{type:"audio/wav"});this.currentBlobURL=URL.createObjectURL(a),this.audioElement.src=this.currentBlobURL,this.isAudioCreated=!0,this.waitForAudioLoadAndPlay()}catch(n){null==(t=(e=this.options).onError)||t.call(e,n),this.processNextUpdate()}else this.processNextUpdate();else this.processNextUpdate()}playAudio(){if(this.isManuallyStopped||this.stopRequested)this.processNextUpdate();else if(this.audioElement){if(this.audioElement.readyState<2){const e=setTimeout(()=>{this.pendingTimeouts.delete(e),this.playAudio()},100);return void this.pendingTimeouts.add(e)}this.audioElement.paused?this.audioElement.play().then(()=>{this.playedChunksCount=this.audioChunks.length,this.retryCount=0,this.processNextUpdate()}).catch(e=>{var t,n;if(this.isManuallyStopped||this.stopRequested)return this.retryCount=0,void this.processNextUpdate();if("AbortError"===e.name||e.message.includes("interrupted"))if(this.retryCount++,this.retryCount<=this.maxRetries){const e=setTimeout(()=>{this.pendingTimeouts.delete(e),this.playAudio()},200*this.retryCount);this.pendingTimeouts.add(e)}else this.retryCount=0,this.processNextUpdate();else this.retryCount=0,null==(n=(t=this.options).onError)||n.call(t,e),this.processNextUpdate()}):this.processNextUpdate()}else this.processNextUpdate()}createWAVFile(e){const t=e.length,n=36+t,s=new ArrayBuffer(44+t),i=new DataView(s);i.setUint32(0,1380533830,!1),i.setUint32(4,n,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,this.channels,!0),i.setUint32(24,this.sampleRate,!0),i.setUint32(28,this.sampleRate*this.channels*this.bitsPerSample/8,!0),i.setUint16(32,this.channels*this.bitsPerSample/8,!0),i.setUint16(34,this.bitsPerSample,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,t,!0);return new Uint8Array(s,44).set(e),s}play(){return A(this,null,function*(){var e,t;if(!this.audioCtxInitialized)throw new Error("简单 HTML Audio 播放器未初始化");if(this._state!==cj.PLAYING&&this.hasReceivedData)if(this.isStreamPlaying){if(this.audioElement)try{yield this.audioElement.play()}catch(n){null==(t=(e=this.options).onError)||t.call(e,n)}}else this.startStreamingPlayback()})}pause(){return A(this,null,function*(){if(!this.audioCtxInitialized)throw new Error("简单 HTML Audio 播放器未初始化");this.audioElement&&this.audioElement.pause(),this.setState(cj.PAUSED)})}stop(){return A(this,null,function*(){if(!this.audioCtxInitialized)throw new Error("简单 HTML Audio 播放器未初始化");if(this.stopRequested=!0,this.isManuallyStopped=!0,this.isStreamPlaying=!1,this.clearAllTimeouts(),this.updateQueue=[],this.isUpdatingAudio=!1,this.retryCount=0,this.audioElement)try{this.audioElement.pause(),this.audioElement.currentTime=0,this.audioElement.removeEventListener("ended",()=>{}),this.audioElement.removeEventListener("canplay",()=>{}),this.audioElement.removeEventListener("play",()=>{}),this.audioElement.removeEventListener("pause",()=>{}),this.audioElement.removeEventListener("error",()=>{})}catch(e){}this.setState(cj.STOPPED)})}reset(){return A(this,null,function*(){yield this.stop(),this.hasReceivedData=!1,this.isDataComplete=!1,this.audioChunks=[],this.isStreamPlaying=!1,this.isAudioCreated=!1,this.playedChunksCount=0,this.lastUpdateTime=0,this.isUpdatingAudio=!1,this.updateQueue=[],this.retryCount=0,this.stopRequested=!1,this.isManuallyStopped=!1,this.setState(cj.STOPPED)})}resetPlayback(){return A(this,null,function*(){yield this.stop(),this.isStreamPlaying=!1,this.isAudioCreated=!1,this.playedChunksCount=0,this.lastUpdateTime=0,this.isUpdatingAudio=!1,this.updateQueue=[],this.retryCount=0,this.stopRequested=!1,this.isManuallyStopped=!1,this.hasReceivedData?this.setState(cj.READY):this.setState(cj.STOPPED)})}destroy(){if(this.stop(),this.currentBlobURL&&(URL.revokeObjectURL(this.currentBlobURL),this.currentBlobURL=null),this.audioElement){try{this.audioElement.remove()}catch(e){}this.audioElement=null}this.clearAllTimeouts(),this.audioCtxInitialized=!1,this.isStreamPlaying=!1,this.isAudioCreated=!1,this.hasReceivedData=!1,this.isDataComplete=!1,this.audioChunks=[],this.playedChunksCount=0,this.lastUpdateTime=0,this.isUpdatingAudio=!1,this.updateQueue=[],this.retryCount=0,this.stopRequested=!1,this.isManuallyStopped=!1,this.setState(cj.STOPPED)}clearAllTimeouts(){this.pendingTimeouts.forEach(e=>{clearTimeout(e)}),this.pendingTimeouts.clear()}setAudioParams(e,t=1,n=16){this.sampleRate=e,this.channels=t,this.bitsPerSample=n}setState(e){var t,n;this._state!==e&&(this._state=e,null==(n=(t=this.options).onStateChange)||n.call(t,e))}get volume(){var e;if(!this.audioCtxInitialized)throw new Error("简单 HTML Audio 播放器未初始化");return(null==(e=this.audioElement)?void 0:e.volume)||0}set volume(e){if(!this.audioCtxInitialized)throw new Error("简单 HTML Audio 播放器未初始化");this.audioElement&&(this.audioElement.volume=Math.max(0,Math.min(1,e)))}get state(){return this._state}get isReady(){return this._state===cj.READY}get isLoading(){return this._state===cj.LOADING}get isPlaying(){return this._state===cj.PLAYING}get isPaused(){return this._state===cj.PAUSED}get isStopped(){return this._state===cj.STOPPED}get hasData(){return this.hasReceivedData}get isComplete(){return this.isDataComplete}removeInitAudioEventListeners(){this.audioElement&&(this.audioElement.removeEventListener("abort",this.audioInitAbortHandler),this.audioElement.removeEventListener("canplay",this.audioInitCanplayHandler),this.audioElement.removeEventListener("play",this.audioInitPlayHandler),this.audioElement.removeEventListener("pause",this.audioInitPauseHandler),this.audioElement.removeEventListener("ended",this.audioInitEndedHandler),this.audioElement.removeEventListener("error",this.audioInitErrorHandler))}removeAudioEventListeners(){this.audioElement&&(this.audioElement.removeEventListener("canplay",this.audioCanPlayHandler),this.audioElement.removeEventListener("error",this.audioErrorHandler))}removeAllAudioEventListeners(){this.removeInitAudioEventListeners(),this.removeAudioEventListeners()}}class mj{constructor(e){j(this,"_state",cj.STOPPED),j(this,"options"),j(this,"audioElement",null),j(this,"audioContext",null),j(this,"mediaStreamDestination",null),j(this,"bufferQueue",[]),j(this,"sourceNodes",[]),j(this,"nextSchedule",0),j(this,"sampleRate",24e3),j(this,"_isStreamPlaying",!1),j(this,"isUserStopped",!1),j(this,"audioCanPlayHandler",()=>{var e;this.setState(cj.READY),(null==(e=this.audioElement)?void 0:e.paused)&&!this.isUserStopped&&this.audioElement.play().catch(e=>{})}),this.options={onStateChange:e.onStateChange||(()=>{}),onError:e.onError||(()=>{})},this.initAudioContext()}initAudioContext(){var e,t;try{this.audioElement=document.createElement("audio"),this.audioElement.style.display="none",this.audioElement.preload="auto",this.audioElement.controls=!1,this.audioElement.volume=1,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("canplay",this.audioCanPlayHandler),this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.mediaStreamDestination=this.audioContext.createMediaStreamDestination(),this.audioElement.srcObject=this.mediaStreamDestination.stream,this.setState(cj.INITIALIZED)}catch(n){throw null==(t=(e=this.options).onError)||t.call(e,n),new Error("Web Audio API 不可用,无法初始化播放器")}}appendPCMBuffer(e,t=!1){if(!this.audioContext)throw new Error("Web Audio API 未初始化");this.bufferQueue.push({buffer:e,isDone:t}),t&&(this.isDataComplete=!0),this._isStreamPlaying||this.isUserStopped||this.processBufferQueue()}processBufferQueue(){if(0===this.bufferQueue.length)return void(this._isStreamPlaying=!1);const{buffer:e}=this.bufferQueue.shift(),t=this.createAudioBufferFromPCM(e),n=this.audioContext.createBufferSource();n.buffer=t,n.connect(this.mediaStreamDestination),this.sourceNodes.push(n);const s=this.audioContext.currentTime;0===this.nextSchedule&&(this.nextSchedule=s),n.start(this.nextSchedule),this.nextSchedule+=t.duration,n.onended=()=>{const e=this.sourceNodes.indexOf(n);-1!==e&&this.sourceNodes.splice(e,1),this.bufferQueue.length>0&&this.processBufferQueue()}}createAudioBufferFromPCM(e){const t=this.audioContext.createBuffer(1,e.length/2,this.sampleRate),n=t.getChannelData(0),s=new DataView(e.buffer);for(let i=0,a=0;i{}),j(this,"audioInitCanplayHandler",()=>{this.setState(cj.READY)}),j(this,"audioInitPlayHandler",()=>{this.setState(cj.PLAYING)}),j(this,"audioInitPauseHandler",()=>{[cj.PAUSED,cj.STOPPED].includes(this.state)||this.setState(cj.PAUSED)}),j(this,"audioInitEndedHandler",()=>{if(this.isUserStopped||this.audioChunks.length===this.playedChunksCount&&this.isDataComplete)return this.isStreamPlaying=!1,this.isUserStopped=!1,void(this.state!==cj.STOPPED&&this.setState(cj.STOPPED));this.isStreamPlaying&&this.audioChunks.length>this.playedChunksCount&&this.processNextUpdate()}),j(this,"audioInitErrorHandler",e=>{var t,n;null==(n=(t=this.options).onError)||n.call(t,new Error("音频播放错误"))}),j(this,"audioCanPlayHandler",()=>{this.removeAudioEventListeners(),this.isLoadingAudio=!1,this.playAudio()}),j(this,"audioErrorHandler",()=>{var e,t;this.removeAudioEventListeners(),this.isLoadingAudio=!1,null==(t=(e=this.options).onError)||t.call(e,new Error("音频加载失败"))}),this.options={onStateChange:e.onStateChange||(()=>{}),onError:e.onError||(()=>{})},this.initHTMLAudio()}initHTMLAudio(){return A(this,null,function*(){var e,t;try{this.audioElement=document.createElement("audio"),this.audioElement.style.display="none",this.audioElement.preload="auto",this.audioElement.controls=!1,this.audioElement.volume=1,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("abort",this.audioInitAbortHandler),this.audioElement.addEventListener("canplay",this.audioInitCanplayHandler),this.audioElement.addEventListener("play",this.audioInitPlayHandler),this.audioElement.addEventListener("pause",this.audioInitPauseHandler),this.audioElement.addEventListener("ended",this.audioInitEndedHandler),this.audioElement.addEventListener("error",this.audioInitErrorHandler),this.audioPlayerInitlized=!0,this.setState(cj.INITIALIZED)}catch(n){throw null==(t=(e=this.options).onError)||t.call(e,n),new Error("简单 HTML Audio 播放器初始化失败")}})}setMediaMetadata(e){var t;if(this.mediaMetadata=C({},e),this.mediaSessionInitialized&&"mediaSession"in navigator)try{const n=(null==(t=e.artwork)?void 0:t.map(e=>({src:e.src,sizes:e.sizes||"512x512",type:e.type||"image/png"})))||[];navigator.mediaSession.metadata=new MediaMetadata({title:e.title||"QwenTTS 语音播放",artist:e.artist||"QwenTTS",album:e.album||"语音合成",artwork:n})}catch(n){}}updateMediaSessionPlaybackState(e){if(this.mediaSessionInitialized&&"mediaSession"in navigator)try{let t;switch(e){case cj.PLAYING:t="playing";break;case cj.PAUSED:t="paused";break;case cj.STOPPED:case cj.INITIALIZED:case cj.READY:default:t="none"}navigator.mediaSession.playbackState=t}catch(t){}}appendPCMBuffer(e,t=!1){if(!e&&t&&!this.hasReceivedData)return void this.setState(cj.STOPPED);this.hasReceivedData||(this.setState(cj.LOADING),this.hasReceivedData=!0),e&&this.audioChunks.push(new Uint8Array(e));const n=this.audioChunks.reduce((e,t)=>e+t.length,0);this.isStreamPlaying||this.isUserStopped||(n>=this.minBufferSize||t)&&this.startStreamingPlayback(),t&&(this.isDataComplete=!0)}startStreamingPlayback(){this.isStreamPlaying||this.isUserStopped||(this.isStreamPlaying=!0,this.updateStreamingAudio())}waitForAudioLoadAndPlay(){this.isUserStopped||(this.audioElement.readyState>=2?this.playAudio():this.isLoadingAudio||(this.isLoadingAudio=!0,this.audioElement&&(this.audioElement.addEventListener("canplay",this.audioCanPlayHandler),this.audioElement.addEventListener("error",this.audioErrorHandler),this.audioElement.load())))}updateStreamingAudio(){var e,t;if(!this.isUserStopped)if(this.audioChunks.length!==this.playedChunksCount||this.isDataComplete)if(this.isLoadingAudio||this.isRequestPlaying||!this.audioElement.paused&&!this.audioElement.ended)this.processNextUpdate();else try{const e=this.audioChunks.length,t=this.audioChunks.slice(this.playedChunksCount);if(!t.length)return void(this.isDataComplete||this.processNextUpdate());const n=t.reduce((e,t)=>e+t.length,0),s=new Uint8Array(n);let i=0;for(const r of t)s.set(r,i),i+=r.length;this.currentBlobURL&&URL.revokeObjectURL(this.currentBlobURL);const a=this.createWAVFile(s),o=new Blob([a],{type:"audio/wav"});this.currentBlobURL=URL.createObjectURL(o),this.currentBlobChunkLength=e,this.audioElement.src=this.currentBlobURL,this.waitForAudioLoadAndPlay()}catch(n){null==(t=(e=this.options).onError)||t.call(e,n),this.processNextUpdate()}else this.processNextUpdate()}processNextUpdate(){this.pendingTasks.processNextUpdateTaskId&&clearTimeout(this.pendingTasks.processNextUpdateTaskId),this.pendingTasks.processNextUpdateTaskId=setTimeout(()=>{this.updateStreamingAudio()},50)}delayToPlayAudio(){this.pendingTasks.playTaskId&&clearTimeout(this.pendingTasks.playTaskId),this.pendingTasks.playTaskId=setTimeout(()=>{this.playAudio()},50)}playAudio(){this.isUserStopped||(this.audioElement.readyState<2?this.delayToPlayAudio():this.audioElement.paused&&!this.isRequestPlaying?(this.isRequestPlaying=!0,this.audioElement.play().then(()=>{this.playedChunksCount=this.currentBlobChunkLength,this.processNextUpdate()}).catch(e=>{this.isUserStopped||("AbortError"===e.name||e.message.includes("interrupted"))&&this.delayToPlayAudio()}).finally(()=>{this.isRequestPlaying=!1})):this.processNextUpdate())}createWAVFile(e){const t=e.length,n=36+t,s=new ArrayBuffer(44+t),i=new DataView(s);i.setUint32(0,1380533830,!1),i.setUint32(4,n,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,this.channels,!0),i.setUint32(24,this.sampleRate,!0),i.setUint32(28,this.sampleRate*this.channels*this.bitsPerSample/8,!0),i.setUint16(32,this.channels*this.bitsPerSample/8,!0),i.setUint16(34,this.bitsPerSample,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,t,!0);return new Uint8Array(s,44).set(e),s}play(){return A(this,null,function*(){if(!this.audioPlayerInitlized)throw new Error("HTML Audio 播放器未初始化");this._state!==cj.PLAYING&&this.hasReceivedData&&(this.isStreamPlaying||this.startStreamingPlayback())})}pause(){return A(this,null,function*(){if(!this.audioPlayerInitlized)throw new Error("HTML Audio 播放器未初始化");this.audioElement&&this.audioElement.pause(),this.setState(cj.PAUSED)})}stop(){return A(this,null,function*(){if(!this.audioPlayerInitlized)throw new Error("HTML Audio 播放器未初始化");this.clearAllTimeouts(),this.isUserStopped=!0,this.isStreamPlaying=!1;try{yield this.audioElement.pause(),this.audioElement.currentTime=0}catch(e){}this.setState(cj.STOPPED)})}reset(){return A(this,null,function*(){this.isStreamPlaying=!1,this.playedChunksCount=0,this.currentBlobChunkLength=0,this.isUserStopped=!1,this.isRequestPlaying=!1,this.isLoadingAudio=!1,this.setState(cj.STOPPED)})}resetPlayback(){return A(this,null,function*(){yield this.reset()})}destroy(){return A(this,null,function*(){if(yield this.stop(),this.cleanupMediaSession(),this.currentBlobURL&&(URL.revokeObjectURL(this.currentBlobURL),this.currentBlobURL=null,this.currentBlobChunkLength=0),this.audioElement){try{this.audioElement.remove()}catch(e){}this.audioElement=null}this.setState(cj.STOPPED)})}cleanupMediaSession(){if(this.mediaSessionInitialized&&"mediaSession"in navigator)try{navigator.mediaSession.setActionHandler("play",null),navigator.mediaSession.setActionHandler("pause",null),navigator.mediaSession.setActionHandler("stop",null),navigator.mediaSession.playbackState="none",navigator.mediaSession.metadata=null,this.mediaSessionInitialized=!1}catch(e){}}clearAllTimeouts(){this.pendingTasks.playTaskId&&(clearTimeout(this.pendingTasks.playTaskId),this.pendingTasks.playTaskId=null),this.pendingTasks.processNextUpdateTaskId&&(clearTimeout(this.pendingTasks.processNextUpdateTaskId),this.pendingTasks.processNextUpdateTaskId=null)}setAudioParams(e,t=1,n=16){this.sampleRate=e,this.channels=t,this.bitsPerSample=n}setState(e){var t,n;this._state=e,this.updateMediaSessionPlaybackState(e),null==(n=(t=this.options).onStateChange)||n.call(t,e)}get volume(){var e;if(!this.audioPlayerInitlized)throw new Error("简单 HTML Audio 播放器未初始化");return(null==(e=this.audioElement)?void 0:e.volume)||0}set volume(e){if(!this.audioPlayerInitlized)throw new Error("简单 HTML Audio 播放器未初始化");this.audioElement&&(this.audioElement.volume=Math.max(0,Math.min(1,e)))}get state(){return this._state}get isReady(){return this._state===cj.READY}get isLoading(){return this._state===cj.LOADING}get isPlaying(){return this._state===cj.PLAYING}get isPaused(){return this._state===cj.PAUSED}get isStopped(){return this._state===cj.STOPPED}get hasData(){return this.hasReceivedData}get isComplete(){return this.isDataComplete}removeInitAudioEventListeners(){this.audioElement&&(this.audioElement.removeEventListener("abort",this.audioInitAbortHandler),this.audioElement.removeEventListener("canplay",this.audioInitCanplayHandler),this.audioElement.removeEventListener("play",this.audioInitPlayHandler),this.audioElement.removeEventListener("pause",this.audioInitPauseHandler),this.audioElement.removeEventListener("ended",this.audioInitEndedHandler),this.audioElement.removeEventListener("error",this.audioInitErrorHandler))}removeAudioEventListeners(){this.audioElement&&(this.audioElement.removeEventListener("canplay",this.audioCanPlayHandler),this.audioElement.removeEventListener("error",this.audioErrorHandler))}removeAllAudioEventListeners(){this.removeInitAudioEventListeners(),this.removeAudioEventListeners()}}class gj{constructor(e){j(this,"options"),j(this,"sampleRate",24e3),j(this,"channels",1),j(this,"audioPlayer"),this.options={onStateChange:e.onStateChange||(()=>{}),onError:e.onError||(()=>{}),playerType:e.playerType||dj.HTML_AUDIO},this.options.playerType===dj.SIMPLE_HTML_AUDIO?this.audioPlayer=new hj({onStateChange:e=>{var t,n;this._state=e,null==(n=(t=this.options).onStateChange)||n.call(t,e)},onError:this.options.onError}):this.options.playerType===dj.HTML_AUDIO?this.audioPlayer=new pj({onStateChange:e=>{var t,n;this._state=e,null==(n=(t=this.options).onStateChange)||n.call(t,e)},onError:this.options.onError}):this.options.playerType===dj.HTML_AUDIO_CXT?this.audioPlayer=new mj({onStateChange:e=>{var t,n;this._state=e,null==(n=(t=this.options).onStateChange)||n.call(t,e)},onError:this.options.onError}):this.audioPlayer=new uj({onStateChange:e=>{var t,n;this._state=e,null==(n=(t=this.options).onStateChange)||n.call(t,e)},onError:this.options.onError}),this.audioPlayer.setAudioParams(this.sampleRate,this.channels)}appendBase64PCM(e,t=!1){const n=this.base64ToArrayBuffer(e);(n||t)&&this.audioPlayer.appendPCMBuffer(n,t)}base64ToArrayBuffer(e){if(!e)return null;try{const t=atob(e),n=new Uint8Array(t.length);for(let e=0;eA(null,null,function*(){return yield TM("/tts/voice/synthesis_text",{method:"POST",data:e})}),vj=e=>A(null,null,function*(){return yield TM("/tts/voice/clone",{method:"POST",data:e})}),yj=e=>A(null,null,function*(){return yield TM("/tts/voice/rename",{method:"POST",data:e})}),bj=e=>A(null,null,function*(){return yield TM(`/tts/voice/delete/${e.id}`,{method:"DELETE"})}),xj=()=>A(null,null,function*(){return yield TM("/tts/voice/list/detail",{method:"GET"})});class wj extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}const _j=32;function Cj(e){}function Sj(e){if("function"==typeof e)throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:t=Cj,onError:n=Cj,onRetry:s=Cj,onComment:i,maxBufferSize:a}=e,o=[];let r,l,c=0,d=!0,u="",h=0,m=!1;function p(){void 0!==a&&(c+u.length<=a||(m=!0,o.length=0,c=0,r=void 0,u="",h=0,l=void 0,n(new wj(`Buffered data exceeded max buffer size of ${a} characters`,{type:"max-buffer-size-exceeded"}))))}function g(e){let n=0;if(-1===e.indexOf("\r")){let s=e.indexOf("\n",n);for(;-1!==s;){if(n===s){h>0&&t({id:r,event:l,data:u}),r=void 0,u="",h=0,l=void 0,n=s+1,s=e.indexOf("\n",n);continue}const i=e.charCodeAt(n);if(kj(e,n,i)){const i=e.charCodeAt(n+5)===_j?n+6:n+5,a=e.slice(i,s);if(0===h&&10===e.charCodeAt(s+1)){t({id:r,event:l,data:a}),r=void 0,u="",l=void 0,n=s+2,s=e.indexOf("\n",n);continue}u=0===h?a:`${u}\n${a}`,h++}else jj(e,n,i)?l=e.slice(e.charCodeAt(n+6)===_j?n+7:n+6,s)||void 0:f(e,n,s);n=s+1,s=e.indexOf("\n",n)}return e.slice(n)}for(;n0&&t({id:r,event:l,data:u}),r=void 0,u="",h=0,void(l=void 0);const a=e.charCodeAt(n);if(kj(e,n,a)){const t=e.charCodeAt(n+5)===_j?n+6:n+5,i=e.slice(t,s);return u=0===h?i:`${u}\n${i}`,void h++}if(jj(e,n,a))return void(l=e.slice(e.charCodeAt(n+6)===_j?n+7:n+6,s)||void 0);if(105===a&&100===e.charCodeAt(n+1)&&58===e.charCodeAt(n+2)){const t=e.slice(e.charCodeAt(n+3)===_j?n+4:n+3,s);return void(r=t.includes("\0")?void 0:t)}if(58===a){if(i){const t=e.slice(n,s);i(t.slice(e.charCodeAt(n+1)===_j?2:1))}return}const o=e.slice(n,s),c=o.indexOf(":");if(-1===c)return void v(o,"",o);const d=o.slice(0,c),m=o.charCodeAt(c+1)===_j?2:1;v(d,o.slice(c+m),o)}function v(e,t,i){switch(e){case"event":l=t||void 0;break;case"data":u=0===h?t:`${u}\n${t}`,h++;break;case"id":r=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?s(parseInt(t,10)):n(new wj(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:i}));break;default:n(new wj(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:i}))}}return{feed:function(e){if(m)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(d&&(d=!1,239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)&&(e=e.slice(3))),0===o.length){const t=g(e);return""!==t&&(o.push(t),c=t.length),void p()}if(-1===e.indexOf("\n")&&-1===e.indexOf("\r"))return o.push(e),c+=e.length,void p();o.push(e);const t=o.join("");o.length=0,c=0;const n=g(t);""!==n&&(o.push(n),c=n.length),p()},reset:function(e={}){if(e.consume&&o.length>0){const e=o.join("");f(e,0,e.length)}d=!0,r=void 0,u="",h=0,l=void 0,o.length=0,c=0,m=!1}}}function kj(e,t,n){return 100===n&&97===e.charCodeAt(t+1)&&116===e.charCodeAt(t+2)&&97===e.charCodeAt(t+3)&&58===e.charCodeAt(t+4)}function jj(e,t,n){return 101===n&&118===e.charCodeAt(t+1)&&101===e.charCodeAt(t+2)&&110===e.charCodeAt(t+3)&&116===e.charCodeAt(t+4)&&58===e.charCodeAt(t+5)}class Tj extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:s}={}){let i;super({start(a){i=Sj({onEvent:e=>{a.enqueue(e)},onError(t){"function"==typeof e&&e(t),("terminate"===e||"max-buffer-size-exceeded"===t.type)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:s})},transform(e){i.feed(e)}})}}function Ej(e,t,n=!0){return A(this,null,function*(){let t=function(e){return R(this,null,function*(){for(var t,n,s,i,a,o,r,l,c,d,u,h,m,p,g,f,v,y,b,x,w,_,k,j,T,E,N,I,A,R,P,L,O,D,F,q,U,H,B,z,G,$,W,V,Q,K,Y,J,X,Z,ee,te,ne,se,ie,ae,oe,re,le,ce,de,ue,he,me,pe,ge,fe,ve,ye,be,xe,we,_e,Ce,Se,ke,je,Te;;){const{value:Ne,done:Ie}=yield new M(e.read());if(Ie){yield{done:!0,value:""};break}if(!Ne)continue;const Ae=Ne.data;if(Ae.startsWith("[DONE]")){yield{done:!0,value:""};break}try{let e={};try{e=JSON.parse(Ae)}catch(Ee){}const M=(null==e?void 0:e["response.created"])||void 0;if(M){yield{done:!1,value:"",chatId:M.chat_id,parentId:M.parent_id,responseId:M.response_id};continue}if(null==e?void 0:e["response.stopped"]){yield{done:!0,value:"",isStop:!0};continue}if(null==(s=null==(n=null==(t=null==e?void 0:e.choices)?void 0:t[0])?void 0:n.delta)?void 0:s.tts){const{tts:t=""}=null==(a=null==(i=null==e?void 0:e.choices)?void 0:i[0])?void 0:a.delta;yield{done:!1,value:t,tts:t,responseId:e.response_id}}if(e.error){yield{done:!0,value:"",error:e.error,responseId:e.response_id};continue}if(e.sources){yield{done:!1,value:"",sources:e.sources,role:null!=(c=null==(l=null==(r=null==(o=e.choices)?void 0:o[0])?void 0:r.delta)?void 0:l.role)?c:"",responseId:e.response_id};continue}if(e.selected_model_id){yield{done:!1,value:"",selectedModelId:e.selected_model_id,role:null!=(m=null==(h=null==(u=null==(d=e.choices)?void 0:d[0])?void 0:u.delta)?void 0:h.role)?m:"",responseId:e.response_id};continue}if("function"===(null==(f=null==(g=null==(p=e.choices)?void 0:p[0])?void 0:g.delta)?void 0:f.role)){if(null==(x=null==(b=null==(y=null==(v=e.choices)?void 0:v[0])?void 0:y.delta)?void 0:b.extra)?void 0:x.web_search_info){yield{done:!1,value:"",web_search_info:null!=(T=null==(j=null==(k=null==(_=null==(w=e.choices)?void 0:w[0])?void 0:_.delta)?void 0:k.extra)?void 0:j.web_search_info)?T:[],role:null!=(A=null==(I=null==(N=null==(E=e.choices)?void 0:E[0])?void 0:N.delta)?void 0:I.role)?A:"",responseId:e.response_id};continue}if(null==(O=null==(L=null==(P=null==(R=e.choices)?void 0:R[0])?void 0:P.delta)?void 0:L.extra)?void 0:O.code_interpreter_info){yield{done:!1,value:"",code_interpreter_info:null!=(H=null==(U=null==(q=null==(F=null==(D=e.choices)?void 0:D[0])?void 0:F.delta)?void 0:q.extra)?void 0:U.code_interpreter_info)?H:"",role:null!=($=null==(G=null==(z=null==(B=e.choices)?void 0:B[0])?void 0:z.delta)?void 0:G.role)?$:"",responseId:e.response_id};continue}}yield S(C({done:!1,value:null!=(K=null==(Q=null==(V=null==(W=e.choices)?void 0:W[0])?void 0:V.delta)?void 0:Q.content)?K:"",role:null!=(Z=null==(X=null==(J=null==(Y=e.choices)?void 0:Y[0])?void 0:J.delta)?void 0:X.role)?Z:"",phase:null==(ne=null==(te=null==(ee=e.choices)?void 0:ee[0])?void 0:te.delta)?void 0:ne.phase,status:null==(ae=null==(ie=null==(se=e.choices)?void 0:se[0])?void 0:ie.delta)?void 0:ae.status,usage:e.usage,extra:null==(le=null==(re=null==(oe=e.choices)?void 0:oe[0])?void 0:re.delta)?void 0:le.extra,lang_code:null==(ue=null==(de=null==(ce=e.choices)?void 0:ce[0])?void 0:de.delta)?void 0:ue.lang_code,function_call:null==(pe=null==(me=null==(he=e.choices)?void 0:he[0])?void 0:me.delta)?void 0:pe.function_call},(null==(ve=null==(fe=null==(ge=e.choices)?void 0:ge[0])?void 0:fe.delta)?void 0:ve.function_call)?{functionCallType:null==(we=null==(xe=null==(be=null==(ye=e.choices)?void 0:ye[0])?void 0:be.delta)?void 0:xe.function_call)?void 0:we.name}:{}),{mcp_name:null==(Se=null==(Ce=null==(_e=e.choices)?void 0:_e[0])?void 0:Ce.delta)?void 0:Se.mcp_name,tool_name:null==(Te=null==(je=null==(ke=e.choices)?void 0:ke[0])?void 0:je.delta)?void 0:Te.tool_name,responseId:e.response_id})}catch(Ee){}}})}(e.pipeThrough(new TextDecoderStream).pipeThrough(new Tj).getReader());return t=function(e){return R(this,null,function*(){let t="";try{for(var n,s,i,a=L(e);n=!(s=yield new M(a.next())).done;n=!1){const e=s.value,n=e.value,i="string"==typeof n?n.substring((null==t?void 0:t.length)||0):"";if(i.length){const e={chunk_size:i.length,chunk_time:Date.now()};yield{chunk_data:e,done:!1,value:""}}yield e,t=n}}catch(s){i=[s]}finally{try{n&&(s=a.return)&&(yield new M(s.call(a)))}finally{if(i)throw i[0]}}})}(t),t})}class Nj{constructor(e){j(this,"player"),j(this,"options"),j(this,"chatId"),j(this,"messageId"),j(this,"dataLoadFailed",!1),j(this,"isLoadingData",!1),j(this,"isStoppedByUser",!1),j(this,"isDestroyed",!1),j(this,"hasReceivedData",!1),j(this,"play",()=>A(this,null,function*(){this.dataLoadFailed?yield this.startTTSStream():yield this.player.play()})),j(this,"stop",()=>A(this,null,function*(){this.isStoppedByUser=!0,yield this.player.stop()})),this.options=e,this.initPlayer()}setStateChangeCallback(e){this.options.onStateChange=e}startTTS(e,t=!1){return A(this,null,function*(){if(this.chatId=e.chatId,this.messageId=e.messageId,this.isStoppedByUser=!1,t||!this.hasData||this.dataLoadFailed)return yield this.startTTSStream();yield this.play()})}startTTSStream(){return A(this,null,function*(){var e,t,n;if(this.isLoadingData)return;this.isLoadingData=!0,this.dataLoadFailed=!1;const s=this.getTTSRequestData();if(!s)throw this.isLoadingData=!1,new Error("chatId or messageId is required");const{success:i,data:a,isStream:o}=yield(r=s,A(null,null,function*(){return yield Sl(),yield TM(`/tts/completions?chat_id=${r.chat_id}`,{responseType:"stream",method:"POST",data:r})}));var r;if(!i)return this.handleDataLoadError(),void(this.isStoppedByUser||vi.open({type:"error",content:WR.t("Failed to play voice, please try again later.")}));if(!o){const s=a,i=(null==(e=null==s?void 0:s.data)?void 0:e.code)||"Unknown";let o=WR.t("Failed to play voice, please try again later."),r="error";return"RateLimited"===(null==(t=null==s?void 0:s.data)?void 0:t.code)&&(o=WR.t("Reached rate limited: too many requests per minute.")),"UnsupportedLanguage"===(null==(n=null==s?void 0:s.data)?void 0:n.code)&&(o=WR.t("Currently, only Chinese and English are supported. More languages are coming soon."),r="warning"),this.handleDataLoadError(i),void vi.open({type:r,content:o})}try{const e=yield Ej(a);try{for(var l,c,d,u=L(e);l=!(c=yield u.next()).done;l=!1){const e=c.value;if(this.isDestroyed)return;const{done:t,tts:n}=e;!this.hasReceivedData&&n&&(this.hasReceivedData=!0),(t||void 0!==n)&&this.player.appendBase64PCM(n,t),t&&!this.hasReceivedData&&(vi.open({type:"warning",content:WR.t("Failed to load voice, nothing can be played.")}),this.handleDataLoadError())}}catch(c){d=[c]}finally{try{l&&(c=u.return)&&(yield c.call(u))}finally{if(d)throw d[0]}}this.dataLoadFailed=!1}catch(h){this.isStoppedByUser||vi.open({type:"error",content:WR.t("Failed to load voice, please try again later.")}),yield this.player.stop(),this.handleDataLoadError()}finally{this.isLoadingData=!1}})}handleDataLoadError(e="Unknown"){return A(this,null,function*(){var t,n;this.dataLoadFailed=!0,this.isLoadingData=!1,"UnsupportedLanguage"===e&&(null==(n=null==(t=this.options)?void 0:t.onStateChange)||n.call(t,cj.UNSUPPORTED_LANGUAGE)),setTimeout(()=>A(this,null,function*(){yield this.clearCachedData()}),1e3)})}clearCachedData(){return A(this,null,function*(){yield this.player.reset()})}destroy(){this.isDestroyed=!0,this.player.destroy(),this.player=null,this.options=null,this.dataLoadFailed=!1,this.isLoadingData=!1,this.isStoppedByUser=!1}initPlayer(){this.player=new gj({onStateChange:e=>{var t;(null==(t=this.options)?void 0:t.onStateChange)&&this.options.onStateChange(e)}})}getTTSRequestData(){return this.chatId&&this.messageId?{chat_id:this.chatId,timestamp:Math.floor(Date.now()/1e3),messages:[{id:this.messageId,role:"assistant",sub_chat_type:"tts"}]}:null}resetPlayer(){this.player&&this.player.resetPlayback()}get hasData(){var e;return(null==(e=this.player)?void 0:e.hasData)||!1}get isComplete(){var e;return(null==(e=this.player)?void 0:e.isComplete)||!1}get isDataLoadFailed(){return this.dataLoadFailed}get isDataLoading(){return this.isLoadingData}get state(){return this.player.state}get volume(){return this.player.volume}set volume(e){this.player.volume=e}}const Ij=class e{constructor(e=300){j(this,"instances",new Map),j(this,"currentPlayingKey",null),j(this,"maxInstances"),this.maxInstances=e}static getInstance(t){return e.instance||(e.instance=new e(t)),e.instance}generateKey(e,t){return`${e}:${t}`}createStateChangeCallback(e,t){return n=>{[cj.STOPPED,cj.PAUSED].includes(n)&&this.currentPlayingKey===e&&(this.currentPlayingKey=null),n===cj.PLAYING&&this.currentPlayingKey!==e&&(this.currentPlayingKey=e),t&&t(n)}}getTTSInstance(e,t,n){const s=this.generateKey(e,t);if(this.instances.has(s)){const e=this.instances.get(s);return e.lastUsed=Date.now(),n&&(e.onStateChange=n,e.instance.setStateChangeCallback(this.createStateChangeCallback(s,n))),e.instance}this.cleanupLRU();const i=this.createStateChangeCallback(s,n),a=new Nj({onStateChange:i}),o=Date.now();return this.instances.set(s,{chatId:e,messageId:t,instance:a,createdAt:o,lastUsed:o,onStateChange:n}),a}startTTS(e,t,n){return A(this,null,function*(){const s=this.generateKey(e,t);if(this.currentPlayingKey===s)return;const i=this.instances.get(s);yield this.stopAllPlayer(s);const a=this.getTTSInstance(e,t,n);if(this.currentPlayingKey=s,i&&a.hasData)return yield a.resetPlayer(),void(yield a.play());const o=!i||!a.hasData;yield a.startTTS({chatId:e,messageId:t},o)})}stopAllPlayer(e){return A(this,null,function*(){const t=[];for(const[n,s]of this.instances.entries())n!==e&&t.push(s.instance.stop().catch(e=>{}));yield Promise.all(t),this.currentPlayingKey!==e&&(this.currentPlayingKey=null)})}resetAllTTS(){return A(this,null,function*(){for(const[e,t]of this.instances.entries())yield t.instance.resetPlayer()})}stopTTS(e,t){return A(this,null,function*(){const n=this.generateKey(e,t),s=this.instances.get(n);if(s)try{yield s.instance.stop(),this.currentPlayingKey===n&&(this.currentPlayingKey=null)}catch(i){}})}stopAllTTS(){return A(this,null,function*(){yield this.stopAllPlayer(""),this.currentPlayingKey=null})}destroyTTS(e,t){const n=this.generateKey(e,t),s=this.instances.get(n);if(s)try{s.instance.destroy(),this.instances.delete(n),this.currentPlayingKey===n&&(this.currentPlayingKey=null)}catch(i){}}destroyAllTTS(){for(const[t,n]of this.instances.entries())try{n.instance.destroy()}catch(e){}this.instances.clear(),this.currentPlayingKey=null}clearAllCache(){return A(this,null,function*(){yield this.stopAllTTS(),this.destroyAllTTS()})}cleanupLRU(){if(this.instances.sizee.lastUsed-t.lastUsed),t=this.instances.size-this.maxInstances+1;for(let s=0;sthis.maxInstances&&this.cleanupLRU()}forceCleanupLRU(){this.cleanupLRU()}updateInstanceStateCallback(e,t,n){const s=this.generateKey(e,t),i=this.instances.get(s);i&&(i.onStateChange=n,i.instance.setStateChangeCallback(this.createStateChangeCallback(s,n)))}};j(Ij,"instance");let Aj=Ij;const Mj=({fileList:e,isMobile:t,messageId:n})=>{const s=e.length<4?[e]:[e.slice(0,Math.ceil(e.length/2)),e.slice(Math.ceil(e.length/2),e.length)];return F.jsx("div",{className:"user-image-list",children:s.map((e,s)=>0===e.length?null:F.jsx("div",{className:Q("user-image-list-row",{"user-image-item-margin-top":s>0}),children:e.map((e,s)=>{var i,a;return F.jsxs("div",{className:Q("user-image-item",{"user-image-item-margin-left":s>0}),children:[(null==e?void 0:e.isQuote)&&F.jsxs("div",{className:"quote-image-item-btn",children:[F.jsx(pi,{type:"icon-line-arrow-curve-left-right",className:"quote-icon"}),F.jsx("div",{className:"imageItem-file-name",children:F.jsx("div",{className:"image-item-file-name-text",children:F.jsx(oj,{isImage:!0,isMobile:t,greenNet:e.greenNet,url:(null==(i=e.url)?void 0:i.startsWith("/api"))?`${e.url}/content`:e.url,messageId:n||""})})})]}),!(null==e?void 0:e.isQuote)&&F.jsx(oj,{isImage:!0,isMobile:t,greenNet:e.greenNet,url:(null==(a=e.url)?void 0:a.startsWith("/api"))?`${e.url}/content`:e.url,messageId:n||""})]},e.id)})},s))})},Rj=({messageId:e,files:t,isBubbleMode:n})=>{const s=cR(e=>e.mobile),i=D.useMemo(()=>s?lj:rj,[s]),a=D.useMemo(()=>(null==t?void 0:t.length)?s?t:OR(t):[],[t,s]);if(!Array.isArray(t)||0===t.length)return null;const o=()=>{Aj.getInstance().stopAllPlayer()};return F.jsx(ie,{className:i.fileMessage,vertical:!0,wrap:!0,gap:s?16:8,align:n?"flex-end":"flex-start",children:a.map(t=>{var n;return Array.isArray(t)?F.jsx("div",{className:i.fileMessageImage,onClick:()=>{o()},children:F.jsx(Mj,{fileList:t,isMobile:s,messageId:e})},t[0].id):"image"!==t.type||"image"!==t.showType&&t.showType?"video"===t.type&&"video"===t.showType?F.jsx("div",{className:i.fileMessageVideo,onClick:()=>{o()},children:F.jsx(oj,{isVideo:!0,isMobile:s,greenNet:t.greenNet,url:t.url,messageId:e})},t.id):"audio"===t.type&&"audio"===t.showType?F.jsx("div",{className:i.fileMessageAudio,onClick:()=>{o()},children:F.jsx(ej,{url:t.url,id:t.id,name:t.name},t.id)},t.id):"url"!==t.file_class?F.jsx(s_,{className:i.fileMessageDocument,item:t,url:t.url,name:t.name,fileType:t.file_type,size:null==t?void 0:t.size,role:"user",showClose:!1,isQuote:t.isQuote},t.id):null:F.jsx("div",{className:i.fileMessageImage,onClick:()=>{o()},children:F.jsx(oj,{isImage:!0,isMobile:s,greenNet:t.greenNet,url:(null==(n=null==t?void 0:t.url)?void 0:n.startsWith("/api"))?`${t.url}/content`:(null==t?void 0:t.url)||"",messageId:e})},t.id)})})},Pj={userMessageHeader:"index-module__user-message-header___s556a",userMessageHeaderUsername:"index-module__user-message-header-username___0ZP-x",userMessageHeaderTimestamp:"index-module__user-message-header-timestamp___Ii7Bs",userMessageHeaderTimecost:"index-module__user-message-header-timecost___gEDh7",userMessageHeaderTimecostIcon:"index-module__user-message-header-timecost-icon___wkz3L"},Lj={userMessageHeaderTimecost:"index-h5-module__user-message-header-timecost___dbbwK",userMessageHeaderTimecostIcon:"index-h5-module__user-message-header-timecost-icon___ktBGX"},Oj=D.memo(({username:e,timestamp:t,timeClassName:n,isBubbleMode:s,timecost:i})=>{const a=ye(),o=cR(e=>e.mobile),r=C(C({},Pj),o?Lj:{});return s?"string"==typeof i?F.jsxs("div",{className:r.userMessageHeaderTimecost,children:[F.jsx(pi,{type:"icon-line-microphone-02",className:r.userMessageHeaderTimecostIcon}),i]}):null:F.jsxs("div",{className:r.userMessageHeader,children:[F.jsx("span",{className:r.userMessageHeaderUsername,children:e}),F.jsx("span",{className:Q(r.userMessageHeaderTimestamp,n),children:qe(1e3*t).format(a.t("h:mm a"))})]})});function Dj(e){return D.forwardRef((t,n)=>{const s=t,{mode:i}=s,a=k(s,["mode"]),o=ud(e=>e.isSharePage),r=js(e=>e.chatMode),l=D.useMemo(()=>o||"community"===r,[r,o]);return F.jsx("div",{className:"message-hoc-container",children:F.jsx(e,S(C({ref:n},a),{mode:l?"read":null!=i?i:"edit"}))})})}const Fj=O.memo(e=>{const t=e,{errorImage:n,src:s}=t,i=k(t,["errorImage","src"]),[a,o]=D.useState(s||n||""),[r,l]=D.useState(!!s);D.useEffect(()=>{l(!!s)},[s]);const c=D.useCallback(()=>{n?o(n):l(!1)},[n]);return F.jsx(ie,S(C({justify:"center",align:"center",className:"qwen-chat-search-card-logo"},i),{children:r?F.jsx("img",{src:a,alt:"",className:"qwen-chat-search-card-logo-image",onError:c}):F.jsx(pi,{className:"qwen-chat-search-card-logo-icon",type:"icon-line-globe-01"})}))}),qj=O.memo(e=>{const{sources:t=[],maxShowNum:n=4,onClick:s=()=>{}}=e;return Array.isArray(t)&&0!==t.length?F.jsxs(ie,{justify:"center",align:"center",gap:8,onClick:s,className:"qwen-chat-search-card",children:[F.jsx(ie,{justify:"center",align:"center",children:t.slice(0,n).map(({hostlogo:e},t)=>{const n=t+"-"+e+"-sources-icon";return F.jsx("div",{style:{width:12},children:F.jsx(Fj,{src:e||""})},n)})}),F.jsxs("div",{className:"qwen-chat-fold-source-count",children:["+",t.length]})]}):null}),Uj=({sourceListLogos:e,sourceListMaxShowNumber:t=4,sourceListCallback:n,sourceListName:s,className:i})=>{const a=cR(e=>e.mobile);return F.jsx("div",{className:`qwen-chat-package-comp-source-list ${i||""}`,onClick:n,children:a?F.jsxs(F.Fragment,{children:[F.jsx(sx,{sources:(null==e?void 0:e.map(e=>e.hostlogo||""))||[],showNum:t}),F.jsxs("div",{className:"qwen-chat-package-comp-source-list-text",children:[F.jsx("span",{children:null==e?void 0:e.length}),F.jsx("span",{children:s})]})]}):F.jsx(qj,{maxShowNum:t,sources:e||[]})})},Hj="icon-line-copy-right",Bj="icon-line-edit-contained",zj="icon-line-edit-contained",Gj="icon-line-thumb-up-02",$j="icon-line-thumb-down-02",Wj="icon-line-arrow-rotate-right-02",Vj="icon-line-text-selection",Qj="icon-line-share-01",Kj="icon-line-download-02",Yj="icon-line-trash-01",Jj="icon-pause",Xj="icon-line-Volume",Zj="icon-line-Publish",eT="icon-line-video-generation-01",tT="icon-line-Branch",nT="icon-line-Volume";var sT=(e=>(e.LOADING_DARK="https://img.alicdn.com/imgextra/i2/O1CN01J8AmJN1cZGSJ5xFjV_!!6000000003614-54-tps-60-60.apng",e.LOADING_LIGHT="https://img.alicdn.com/imgextra/i4/O1CN01Jwyf191eaIa5xowFe_!!6000000003887-54-tps-60-60.apng",e.VOICE_ACTIVE_DARK="https://img.alicdn.com/imgextra/i1/O1CN01lSOiPA1VfwvV2cZw6_!!6000000002681-54-tps-60-60.apng",e.VOICE_ACTIVE_LIGHT="https://img.alicdn.com/imgextra/i1/O1CN01pNHavt1CykU9z9sPI_!!6000000000150-54-tps-60-60.apng",e))(sT||{});const iT=[{key:"copy",controlType:"only-icon",icon:Hj},{key:"edit",controlType:"only-icon",icon:Bj},{key:"publish",controlType:"only-icon",icon:Zj},{key:"regenerate",controlType:"only-icon",icon:Wj},{key:"select",controlType:"only-icon",icon:Vj},{key:"share",controlType:"only-icon",icon:Qj},{key:"download",controlType:"only-icon",icon:Kj},{key:"image_edit",controlType:"label-icon-primary",icon:zj},{key:"delete",controlType:"only-icon",icon:Yj},{key:"good",controlType:"only-icon",icon:Gj},{key:"bad",controlType:"only-icon",icon:$j},{key:"artifacts",controlType:"label-icon-secondary",icon:Jj},{key:"create_video",controlType:"label-icon-primary",icon:eT},{key:"voice",icon:Xj,activeImgs:["https://img.alicdn.com/imgextra/i1/O1CN01pNHavt1CykU9z9sPI_!!6000000000150-54-tps-60-60.apng","https://img.alicdn.com/imgextra/i1/O1CN01lSOiPA1VfwvV2cZw6_!!6000000002681-54-tps-60-60.apng"],loadingImgs:["https://img.alicdn.com/imgextra/i4/O1CN01Jwyf191eaIa5xowFe_!!6000000003887-54-tps-60-60.apng","https://img.alicdn.com/imgextra/i2/O1CN01J8AmJN1cZGSJ5xFjV_!!6000000003614-54-tps-60-60.apng"]},{key:"branch_new",controlType:"only-icon",icon:tT},{key:"replay",controlType:"only-icon",icon:nT}],aT=({className:e,type:t="normal",editedData:n,siblingsData:s,controlData:i,sourceListData:a,maxShowButtonCount:o=6,moreText:r="More actions",fullShowControl:l=!0})=>{const c=ud(e=>e.realTheme),d=cR(e=>e.mobile),[u,h]=D.useState(null),[m,p]=D.useState(!1),[g,f]=D.useState(!1),v=D.useRef(null),y=D.useMemo(()=>((null==i?void 0:i.list)||[]).map(e=>{const t=iT.find(t=>t.key===e.key)||{};return C(C({},t),e)}),[null==i?void 0:i.list]),{displayButtons:b,moreButtons:x}=D.useMemo(()=>{const e=(null==i?void 0:i.controls)||[],t=e.filter(e=>["image_edit","artifacts","create_video"].includes(e)).slice(0,1),n=e.filter(e=>["good","bad","share","regenerate"].includes(e)),s=e.filter(e=>![...t,...n].includes(e));let a=s.length+n.length>o?s.slice(-(s.length+n.length-o+1)):[],r=[...t,...s.slice(0,s.length-a.length),...n];if(d&&g){const e=["good","bad"].filter(e=>r.includes(e));e.length>0&&(a=[...a,"divider",...e],a.length<3&&(a=a.filter(e=>"divider"!==e)),r=r.filter(e=>!["good","bad"].includes(e)))}return{displayButtons:r||[],moreButtons:a}},[null==i?void 0:i.controls,o,d,g]),w=D.useMemo(()=>{var e;let t=b.map(e=>{const t=y.find(t=>t.key===e);return t&&!1!==t.visible?t:null}).filter(e=>null!=e);const n=null==(e=null==t?void 0:t[0])?void 0:e.controlType;return n&&["label-icon-primary","label-icon-secondary"].includes(n)&&(t=t.map((e,t)=>0===t?e:S(C({},e),{controlType:["label-icon-primary","label-icon-secondary"].includes(e.controlType)?"only-icon":e.controlType}))),t},[b,y]),_=D.useMemo(()=>x.map(e=>{const t=y.find(t=>t.key===e);return t&&!1!==t.visible?t:null}).filter(e=>!!e),[x,y]),k=D.useMemo(()=>[...w,..._],[w,_]),j=D.useMemo(()=>(null==n?void 0:n.visible)||(null==s?void 0:s.visible),[null==n?void 0:n.visible,null==s?void 0:s.visible]),T=D.useMemo(()=>["good","bad","publish","download"].filter(e=>k.find(({key:t})=>t===e)),[k]),E=D.useMemo(()=>["create_video","image_edit"].filter(e=>k.find(({key:t})=>t===e)),[k]);D.useLayoutEffect(()=>{if(d&&v.current){const e=v.current,t=e.querySelector(".qwen-chat-package-comp-new-action-control-container");if(t){const n=t.offsetHeight;e.offsetHeight>2*n?f(!0):f(!1)}}},[d,v]);const N=D.useMemo(()=>T.map(e=>{const t=y.find(t=>t.key===e);return!1===(null==t?void 0:t.visible)?null:t}).filter(e=>!!e),[y,T]),I=D.useMemo(()=>E.map(e=>{const t=y.find(t=>t.key===e);return!1===(null==t?void 0:t.visible)?null:t}).filter(e=>!!e),[y,E]),A=D.useMemo(()=>w.filter(({key:e})=>![...T,...E].includes(e))||[],[w,E,T]),M=D.useMemo(()=>_.filter(({key:e})=>![...T,...E].includes(e))||[],[_,E,T]),R=D.useCallback(e=>F.jsxs(xi,{type:"brandsecondary",size:"small",rounded:"circle",className:Q("qwen-chat-package-comp-new-action-control-btn",{"qwen-chat-package-comp-action-base-control-btn-visible":e.visible}),onClick:e.callback,children:[F.jsx("div",{className:"qwen-chat-package-comp-new-action-control-icon-container",children:F.jsx(pi,{className:"qwen-chat-package-comp-new-action-control-icon",type:e.icon||""})}),F.jsx("div",{className:"qwen-chat-package-comp-new-action-control-text",children:e.label})]},`renderLabelIconSecondary_${e.key}`),[]),P=D.useCallback(e=>{var t;const n=null==(t=null==i?void 0:i.disableControls)?void 0:t.some(t=>t===e.key),s=n?e.disabledTooltip:null;return F.jsx(Si,{title:s||"",show:!!s,children:F.jsx("div",{style:n?{opacity:.5,cursor:"not-allowed"}:void 0,children:F.jsx(xi,{buttonClass:Q("qwen-chat-package-comp-action-base-control-btn","qwen-chat-package-comp-action-base-control-btn-primary",{"qwen-chat-package-comp-action-base-control-btn-visible":e.visible}),type:d?"brandprimary":"brandsecondary",size:"small",rounded:"circle",iconFontType:e.icon||"",onClick:()=>{var t;n||null==(t=e.callback)||t.call(e)},children:e.label})})},`renderLabelIconPrimary_tooltip_${e.key}`)},[d,null==i?void 0:i.disableControls]),L=D.useCallback(e=>F.jsxs("div",{className:"qwen-chat-package-comp-new-action-control-guide-content",onClick:e=>e.stopPropagation(),children:[F.jsxs("div",{className:"qwen-chat-package-comp-new-action-control-guide-top",children:[F.jsx("div",{className:"qwen-chat-package-comp-new-action-control-guide-title",children:e.title}),F.jsx("div",{className:"qwen-chat-package-comp-new-action-control-guide-close-btn",onClick:()=>{e.onCloseClick&&e.onCloseClick()},children:F.jsx(pi,{type:"icon-close-4",className:"qwen-chat-package-comp-new-action-control-guide-close"})})]}),F.jsx("div",{className:"qwen-chat-package-comp-new-action-control-guide-content-text",children:e.content}),e.buttonVisible&&F.jsx(xi,{type:"brandtertiary",rounded:"circle",size:"small",onClick:e.onButtonClick,children:e.buttonText})]}),[]),q=D.useCallback((e,t)=>{var n,s,a,o,r,l,m,p,g,f,v;const y=null==(n=null==i?void 0:i.disableControls)?void 0:n.some(t=>t===e.key),b=null==(s=null==i?void 0:i.activeControls)?void 0:s.some(t=>t===e.key),x="light"===c?null==(a=e.activeImgs)?void 0:a[0]:(null==(o=e.activeImgs)?void 0:o[1])||(null==(r=e.activeImgs)?void 0:r[0]),w=null==(l=null==i?void 0:i.loadingControls)?void 0:l.some(t=>t===e.key),_="light"===c?null==(m=e.loadingImgs)?void 0:m[0]:(null==(p=e.loadingImgs)?void 0:p[1])||(null==(g=e.loadingImgs)?void 0:g[0]);let C=e.defaultToolTip||null;y?C=e.disabledTooltip||null:b&&(C=e.activeTooltip||null);const S=!t&&(null==(f=e.guideInfo)?void 0:f.visible)||!1;return C||u!==e.key||h(null),["good","bad"].includes(e.key)&&b&&(e.icon="good"===e.key?"icon-fill-thumb-up-01":"icon-fill-thumb-down-01"),F.jsx(Si,{open:u===e.key,title:d||t?null:C,placement:"bottom",onOpenChange:t=>{h(t?e.key:null)},children:F.jsx(le,{arrow:!1,classNames:{root:"qwen-chat-package-comp-new-action-control-guide "+(S?"":"qwen-chat-package-comp-new-action-control-guide-none")},content:L(e.guideInfo||{}),trigger:S?"click":[],getPopupContainer:()=>document.body,placement:d?"top":"right",onOpenChange:null==(v=e.guideInfo)?void 0:v.onOpenChange,children:F.jsx("div",{className:`qwen-chat-package-comp-new-action-control-container qwen-chat-package-comp-new-action-control-container-${e.key} ${y?"qwen-chat-package-comp-new-action-control-container-disabled":""} ${d||t?"":"qwen-chat-package-comp-new-action-control-container-enable-hover"}`,onClick:n=>{y||!e.callback||t||e.callback()},children:w||b&&x?F.jsx("img",{alt:"",className:"qwen-chat-package-comp-new-action-control-icon-img",src:w?_:x}):F.jsx(pi,{type:e.icon||"",className:"qwen-chat-package-comp-new-action-control-icon\n "+(b&&!t?"qwen-chat-package-comp-new-action-control-icon-active":"")})})})},`renderOnlyIcon_${e.key}`)},[null==i?void 0:i.activeControls,null==i?void 0:i.disableControls,null==i?void 0:i.loadingControls,d,L,c,u]),U=D.useCallback((e,t)=>{var n,s,a,o,r,l,m,p,g,f,v;const y=null==(n=null==i?void 0:i.disableControls)?void 0:n.some(t=>t===e.key),b=null==(s=null==i?void 0:i.activeControls)?void 0:s.some(t=>t===e.key),x="light"===c?null==(a=e.activeImgs)?void 0:a[0]:(null==(o=e.activeImgs)?void 0:o[1])||(null==(r=e.activeImgs)?void 0:r[0]),w=null==(l=null==i?void 0:i.loadingControls)?void 0:l.some(t=>t===e.key),_="light"===c?null==(m=e.loadingImgs)?void 0:m[0]:(null==(p=e.loadingImgs)?void 0:p[1])||(null==(g=e.loadingImgs)?void 0:g[0]);let C=e.defaultToolTip||null;y?C=e.disabledTooltip||null:b&&(C=e.activeTooltip||null);const S=!t&&(null==(f=e.guideInfo)?void 0:f.visible)||!1;return C||u!==e.key||h(null),["good","bad"].includes(e.key)&&b&&(e.icon="good"===e.key?"icon-fill-thumb-up-01":"icon-fill-thumb-down-01"),F.jsx(Si,{open:u===e.key,title:d||t?null:C,placement:"bottom",onOpenChange:t=>{h(t?e.key:null)},children:F.jsx(le,{arrow:!1,classNames:{root:"qwen-chat-package-comp-new-action-control-guide "+(S?"":"qwen-chat-package-comp-new-action-control-guide-none")},content:L(e.guideInfo||{}),trigger:S?"click":[],getPopupContainer:()=>document.body,placement:"top",onOpenChange:null==(v=e.guideInfo)?void 0:v.onOpenChange,children:F.jsx("div",{className:`upper-right-corner-item qwen-chat-package-comp-new-action-control-container qwen-chat-package-comp-new-action-control-container-${e.key} ${y?"qwen-chat-package-comp-new-action-control-container-disabled":""} ${d||t?"":"qwen-chat-package-comp-new-action-control-container-enable-hover"}`,onClick:()=>{y||!e.callback||t||e.callback()},children:w||b&&x?F.jsx("img",{alt:"",className:"qwen-chat-package-comp-new-action-control-icon-img",src:w?_:x}):F.jsx(pi,{type:e.icon||"",className:"qwen-chat-package-comp-new-action-control-icon\n "+(b&&!t?"qwen-chat-package-comp-new-action-control-icon-active":"")})})})},`renderOnlyIcon_${e.key}`)},[null==i?void 0:i.activeControls,null==i?void 0:i.disableControls,null==i?void 0:i.loadingControls,d,L,c,u]),H=D.useCallback(e=>{switch(null==e?void 0:e.controlType){case"only-icon":return q(e);case"label-icon-primary":return P(e);case"label-icon-secondary":return R(e);default:return(null==e?void 0:e.iconRender)?e.iconRender:e?q(e):null}},[P,R,q]),B=D.useMemo(()=>["upper-right-corner","lower-center"].includes(t)?null:(null==n?void 0:n.visible)||(null==s?void 0:s.visible)?F.jsxs("div",{className:"qwen-chat-package-comp-new-action-control-edited-container",children:[(null==n?void 0:n.visible)&&F.jsx("div",{className:"qwen-chat-package-comp-new-action-control-is-edited",children:n.text}),(null==s?void 0:s.visible)&&F.jsx(nv,{onPreviousClick:s.onPreviousClick,onNextClick:s.onNextClick,curSiblingsIndex:s.curSiblingsIndex,maxSiblings:s.maxSiblings})]}):null,[null==n?void 0:n.text,null==n?void 0:n.visible,null==s?void 0:s.curSiblingsIndex,null==s?void 0:s.maxSiblings,null==s?void 0:s.onNextClick,null==s?void 0:s.onPreviousClick,null==s?void 0:s.visible,t]),z=D.useCallback(e=>e?F.jsx("div",{className:"qwen-chat-package-comp-new-action-more-operation-text",children:e.label||e.defaultToolTip||""}):null,[]),G=D.useCallback(e=>{var t,n,s;const a=null==(t=null==i?void 0:i.disableControls)?void 0:t.some(t=>t===e),o=y.find(t=>t.key===e);if(!o||!1===o.visible)return null;const r=(null==(n=o.guideInfo)?void 0:n.visible)||!1;return F.jsx(le,{classNames:{root:"qwen-chat-package-comp-new-action-control-guide "+(r?"":"qwen-chat-package-comp-new-action-control-guide-none")},getPopupContainer:e=>document.body,content:L(o.guideInfo||{}),trigger:r?"click":[],placement:d?"top":"right",arrow:!d,autoAdjustOverflow:!0,onOpenChange:null==(s=o.guideInfo)?void 0:s.onOpenChange,children:F.jsxs("div",{className:"qwen-chat-package-comp-new-action-more-operation-items",onClick:()=>{!a&&o.callback&&(o.callback(),r||p(!1))},children:[q(o,!0),z(o)]},e)})},[y,null==i?void 0:i.disableControls,q,z,L,d]),$=D.useMemo(()=>{const e="simplify"===t?x.filter(e=>![...T,...E].includes(e))||[]:x;return F.jsx("div",{className:"qwen-chat-package-comp-new-action-more-operation-content",children:e.map(e=>"divider"===e?F.jsx("div",{className:"qwen-chat-package-comp-new-action-more-operation-divider"},e):G(e))})},[E,x,G,t,T]),W=D.useMemo(()=>{switch(t){case"upper-right-corner":return F.jsx(ie,{gap:12,children:N.map(e=>U(e))});case"lower-center":return F.jsx(ie,{justify:"center",align:"center",gap:8,className:"lower-center-container",children:I.map(({key:e,defaultToolTip:t,disabledTooltip:n,label:s,icon:a,callback:o},r)=>{var c;const d=null==(c=null==i?void 0:i.disableControls)?void 0:c.some(t=>t===e),u=d?n:t,h=F.jsx(Si,{title:u,children:F.jsxs(ie,{gap:4,align:"center",onClick:()=>{d||null==o||o()},className:"lower-center-item"+(d?" lower-center-item-disabled":""),style:d?{opacity:.5,cursor:"not-allowed"}:void 0,children:[F.jsx(pi,{type:a||""}),l?F.jsx("div",{className:"lower-center-item-label",children:s}):null]})},e);return r?h:F.jsxs(O.Fragment,{children:[h,F.jsx("div",{className:"lower-center-item-divider"})]},e)})});case"simplify":return F.jsxs("div",{ref:v,className:"qwen-chat-package-comp-new-action-control-icons",children:[(null==A?void 0:A.length)?null==A?void 0:A.map(e=>H(e)):null,(null==M?void 0:M.length)>0&&F.jsx(le,{arrow:!1,open:m,onOpenChange:p,classNames:{root:"qwen-chat-package-comp-new-action-more-popover"},trigger:"click",placement:"bottomLeft",autoAdjustOverflow:!0,destroyOnHidden:!0,content:$,children:F.jsx(Si,{title:r,placement:"top",children:F.jsx("div",{className:"qwen-chat-package-comp-new-action-control-container",children:F.jsx(pi,{type:"icon-line-more-01",className:"qwen-chat-package-comp-new-action-control-icon"})})},"more-button-tooltip")})]});default:return F.jsxs("div",{ref:v,className:"qwen-chat-package-comp-new-action-control-icons",children:[(null==w?void 0:w.length)?null==w?void 0:w.map(e=>H(e)):null,(null==_?void 0:_.length)>0&&F.jsx(le,{arrow:!1,open:m,onOpenChange:p,classNames:{root:"qwen-chat-package-comp-new-action-more-popover"},trigger:"click",placement:"bottomLeft",autoAdjustOverflow:!0,destroyTooltipOnHide:!0,content:$,children:F.jsx(Si,{title:r,placement:"top",children:F.jsx("div",{className:"qwen-chat-package-comp-new-action-control-container",children:F.jsx(pi,{type:"icon-line-more-01",className:"qwen-chat-package-comp-new-action-control-icon"})})},"more-button-tooltip")})]})}},[t,N,U,I,l,A,null==M?void 0:M.length,m,$,r,H,w,null==_?void 0:_.length]);return d?F.jsxs("div",{className:`qwen-chat-package-comp-new-action-control ${e}`,children:[(null==a?void 0:a.visible)&&F.jsx(Uj,C({},{sourceListLogos:a.sourceListLogos,sourceListName:a.sourceListName,sourceListCallback:a.sourceListCallback})),F.jsxs("div",{className:"qwen-chat-package-comp-new-action-control-mobile-container",children:[!!w.length&&W,B]})]}):F.jsxs("div",{className:`qwen-chat-package-comp-new-action-control ${e}`,style:"upper-right-corner"===t?{justifyContent:"flex-end"}:{},children:[j&&("left"===(null==s?void 0:s.position)||!(null==s?void 0:s.position))&&B,W,j&&"right"===(null==s?void 0:s.position)&&B,(null==a?void 0:a.visible)&&F.jsx(Uj,C({},{sourceListLogos:a.sourceListLogos,sourceListName:a.sourceListName,sourceListCallback:a.sourceListCallback}))]})},oT=[{key:"copy",controlType:"icon-label",icon:Hj},{key:"edit",controlType:"icon-label",icon:Bj},{key:"publish",controlType:"icon-label",icon:Zj},{key:"regenerate",controlType:"icon-label",icon:Wj},{key:"select",controlType:"icon-label",icon:Vj},{key:"share",controlType:"icon-label",icon:Qj},{key:"download",controlType:"icon-label",icon:Kj},{key:"image_edit",controlType:"icon-label",icon:zj},{key:"delete",controlType:"icon-label-error",icon:Yj},{key:"good",controlType:"icon-label",icon:Gj},{key:"bad",controlType:"icon-label",icon:$j},{key:"artifacts",controlType:"icon-label",icon:Jj},{key:"translation",controlType:"icon-label-select",icon:Vj},{key:"branch_new",controlType:"icon-label",icon:tT},{key:"voice",controlType:"icon-label",icon:Xj,activeImgs:[sT.VOICE_ACTIVE_LIGHT,sT.VOICE_ACTIVE_DARK],loadingImgs:[sT.LOADING_LIGHT,sT.LOADING_DARK]}],rT=({className:e,controlData:t})=>{const n=ud(e=>e.realTheme),s=D.useMemo(()=>((null==t?void 0:t.list)||[]).map(e=>{const t=oT.find(t=>t.key===e.key)||{};return C(C({},t),e)}),[null==t?void 0:t.list]),i=D.useCallback(e=>{var t,n,s;return F.jsx(pb,{languageCode:(null==(t=e.dropdown)?void 0:t.value)||"",popover:{getPopupContainer:()=>{var e;return(null==(e=document.getElementsByClassName("chat-messages"))?void 0:e[0])||document.body}},languages:((null==(n=e.dropdown)?void 0:n.options)||[]).map(e=>({code:e.key,title:e.label,translate:e.value})),onTranslate:null==(s=e.dropdown)?void 0:s.onChange})},[]),a=D.useCallback(e=>e.loading||e.active&&e.activeImg?F.jsx("img",{className:"qwen-chat-package-comp-action-control-vertical-group-base-item-img",src:e.loading?e.loadingImg:e.activeImg,alt:""}):F.jsx(pi,{type:e.icon||"",className:`qwen-chat-package-comp-action-control-vertical-group-base-item-icon\n ${e.active?"qwen-chat-package-comp-action-control-vertical-group-base-item-icon-active":""}\n ${e.disabled?"qwen-chat-package-comp-action-control-vertical-group-base-item-icon-disable":""}\n `}),[]),o=D.useCallback((e,s="normal",o=!1)=>{var r,l,c,d,u,h,m,p,g;const f=null==(r=null==t?void 0:t.disableControls)?void 0:r.some(t=>t===e.key),v=null==(l=null==t?void 0:t.activeControls)?void 0:l.some(t=>t===e.key),y="light"===n?null==(c=e.activeImgs)?void 0:c[0]:(null==(d=e.activeImgs)?void 0:d[1])||(null==(u=e.activeImgs)?void 0:u[0]),b=null==(h=null==t?void 0:t.loadingControls)?void 0:h.some(t=>t===e.key),x="light"===n?null==(m=e.loadingImgs)?void 0:m[0]:(null==(p=e.loadingImgs)?void 0:p[1])||(null==(g=e.loadingImgs)?void 0:g[0]);return F.jsxs("div",{className:`qwen-chat-package-comp-action-control-vertical-group-base-item qwen-chat-package-comp-action-control-vertical-group-base-item-${s} qwen-chat-package-comp-action-control-vertical-group-base-item-${e.key}`,onClick:()=>!b&&e.callback&&e.callback(),children:[F.jsx("div",{className:"qwen-chat-package-comp-action-control-vertical-group-base-item-icon-label",children:e.label}),o?i(e):a({loading:b,active:v,disabled:f,activeImg:y,loadingImg:x,icon:e.icon})]})},[null==t?void 0:t.activeControls,null==t?void 0:t.disableControls,null==t?void 0:t.loadingControls,a,i,n]),r=D.useCallback(e=>{const t=s.find(t=>t.key===e);switch(null==t?void 0:t.controlType){case"icon-label":return o(t);case"icon-label-error":return o(t,"error");case"icon-label-select":return o(t,"normal",!0);default:return null}},[s,o]),l=D.useMemo(()=>{var e;return(null==(e=null==t?void 0:t.controls)?void 0:e.length)?t.controls:[]},[null==t?void 0:t.controls]);return F.jsx("div",{className:`qwen-chat-package-comp-action-control-vertical ${e||""}`,children:l.map((e,t)=>F.jsx("div",{className:"qwen-chat-package-comp-action-control-vertical-group",children:r(e)},`action-control-vertical-${t}`))})},lT=Dj(e=>{const{i18n:t}=ye(),n=Pd(e=>e.user),s=js(e=>e.isChat),i=Rs(e=>e.temporaryChatEnabled),[a,o]=D.useState(!1),r=js(e=>e.currentInputFeature),l=Rs(e=>e.visionGenerating),c=Rs(e=>e.taskRunning),d=cR(e=>e.mobile),u="read"===e.mode,{message:h,isChatIntercept:m,isFirstMessage:p,isOmni:g,isNonFilterGreenNetError:f,handleEditMessage:v,handleDeleteMessage:y,showActionControl:b=!0,isOldMessageInNewBranch:x}=e,w=D.useMemo(()=>h.siblings||jr(h.id||h.fid),[h]),_=D.useMemo(()=>!!g&&!(null==h?void 0:h.content),[g,null==h?void 0:h.content]),C=D.useMemo(()=>!m&&!u&&!g&&h.id&&!x&&h.sub_chat_type!==yt.INTERRUPT,[m,u,g,h.id,h.sub_chat_type,x]),S=D.useMemo(()=>!p&&!u&&!f&&!i&&!s&&!l&&!c&&!wR()&&!x&&h.id,[p,u,f,i,s,l,c,x,h.id]),k=D.useMemo(()=>{if(h.isShare)return[];let e=["copy"];return C&&e.push("edit"),S&&e.push("delete"),_&&(e=e.filter(e=>!["copy","edit"].includes(e))),e},[S,C,_,h.isShare]),j=D.useMemo(()=>{let e=["copy"];return C&&e.push("edit"),e.push("select"),S&&e.push("delete"),_&&(e=e.filter(e=>!["copy","edit","select"].includes(e))),e},[S,C,_]),T=D.useMemo(()=>(null==w?void 0:w.indexOf(h.id||h.fid))+1,[h.fid,h.id,w]),E=D.useCallback(e=>{const t=e||h.content;kR(t)},[h.content]),N=D.useCallback(()=>{y()},[y]),I=D.useCallback(()=>{ti()?bM.adapter.invoke({method:"openHalfWindow",params:{type:"selectText",content:r===yt.WebSearch?vn(sS(h)):sS(h),ext:`{"disable_translate": ${(null==h?void 0:h.chat_type)===yt.DeepResearch||h.chat_type===yt.Travel}}`,windowSize:100}}):o(!0)},[r,h]),A=D.useMemo(()=>({visible:w.length>1,curSiblingsIndex:T,maxSiblings:w.length,position:n&&"left",onPreviousClick:()=>{bM.navigateToSiblingMessage(h,w,"previous")},onNextClick:()=>{bM.navigateToSiblingMessage(h,w,"next")}}),[T,h,w,n]),M=D.useMemo(()=>({controls:k,list:[{key:"edit",defaultToolTip:t.t("Edit"),callback:v,visible:!x&&!!h.id},{key:"copy",defaultToolTip:t.t("Copy"),callback:E},{key:"delete",defaultToolTip:t.t("Delete"),callback:N,visible:!x&&!!h.id}]}),[k,E,N,v,t,x,h.id]),R=D.useMemo(()=>({controls:j,list:[{key:"edit",label:t.t("Edit"),callback:v},{key:"copy",label:t.t("Copy"),callback:E},{key:"delete",label:t.t("Delete"),callback:N},{key:"select",label:t.t("Select text"),callback:I}]}),[E,N,v,t,I,j]);return F.jsxs(ie,{className:"user-message-footer "+(d&&!A.visible?"user-message-footer-none":""),vertical:!0,justify:"center",align:"flex-end",children:[b?!(d&&!A.visible)&&F.jsx(aT,{className:"user-message-footer-horizontal",siblingsData:A,controlData:M,moreText:t.t("More actions")}):F.jsx("div",{}),d&&F.jsx(rT,{className:"user-message-footer-vertical",controlData:R}),a&&F.jsx(_b,{contentText:r===yt.WebSearch?vn(sS(h)):sS(h),useSystemSelect:!0,title:t.t("Select text"),show:a,onClose:()=>o(!1)})]})}),cT=({children:e,onLongPress:t})=>{const[n,s]=D.useState(!1),i=D.useRef(null),a=D.useRef(null),[o,r]=D.useState(null),l=D.useRef(null),c=D.useRef(!1),d=Ks();let u=null;const h=D.useCallback(()=>{s(!1),c.current=!1,document.querySelectorAll(".user-message-footer-vertical").forEach(e=>{e.style.left="0",e.style.top="0",e.style.visibility="hidden",e.style.position="absolute",e.style.zIndex="-1"}),document.querySelectorAll(".qwen-chat-package-comp-action-control-vertical").forEach(e=>{e.style.left="0",e.style.top="0",e.style.visibility="hidden",e.style.position="absolute",e.style.zIndex="-1"})},[]),m=(e,t,n,s,a)=>{try{const o=document.querySelector(`#${Lt}`);u&&clearTimeout(u),u=setTimeout(()=>{n||m(e,o,i,s,a);const r=null==o?void 0:o.getBoundingClientRect(),l=null==t?void 0:t.getBoundingClientRect(),c=null==n?void 0:n.getBoundingClientRect();if(c&&r&&l){const{height:t,width:n}=c,{x:i,width:o,y:d,height:u}=r,{x:h}=l;let m=s+h;m+n>i+o&&(m=i+o-n-10,s=m-h);a+t>d+u&&(a=a-t);const p=e.target.closest(".chat-user-message-container").querySelector(".user-message-footer").querySelector(".user-message-footer-vertical");p&&(p.style.left=s+"px",p.style.top=a+"px",p.style.display="block",p.style.visibility="visible",p.style.position="fixed",p.style.zIndex=9)}},100)}catch(o){}},p=D.useCallback((e,n,i)=>{var a,o;s(!0),c.current=!0;const r=document.querySelector(`#${Lt}`),l=e.target.closest(".qwen-chat-message"),u=null==(o=null==(a=e.target.closest(".chat-user-message-container"))?void 0:a.querySelector(".user-message-footer"))?void 0:o.querySelector(".user-message-footer-vertical");if(u){u.style.display="block";const t=i;let s=n;s=u.offsetWidth+s+50>(null==r?void 0:r.offsetWidth)?Math.max(0,n-u.offsetWidth-50):n+50,d&&m(e,l,u,s,t)}d&&(setTimeout(()=>{window.addEventListener("click",h)},500),null==t||t())},[h,d,t]);return D.useEffect(()=>{if(!d||!n)return;const e=e=>{i.current&&!i.current.contains(e.target)&&h()},t=setTimeout(()=>{document.addEventListener("click",e)},300);window.addEventListener("click",h),window.addEventListener("touchStart",h),window.addEventListener("touchmove",h);return document.querySelectorAll(".chat-response-message-right").forEach(e=>{e.addEventListener("click",h)}),()=>{clearTimeout(t),document.removeEventListener("click",e),window.removeEventListener("click",h),window.removeEventListener("touchStart",h),window.removeEventListener("touchmove",h);document.querySelectorAll(".chat-response-message-right").forEach(e=>{e.removeEventListener("click",h)})}},[n,h,d]),F.jsx("div",{ref:a,className:d?"chat-user-message-right":"",onTouchStart:e=>{h(),document.querySelectorAll(".ant-popover").forEach(e=>{e.style.left="0",e.style.top="0",e.style.visibility="hidden",e.style.position="absolute",e.style.zIndex="-1"}),c.current&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0],n=t.clientX,s=t.clientY;r({x:n,y:s}),l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{e.target&&p(e,n,s)},500)},onTouchMove:e=>{if(!o)return;const t=e.touches[0],n=t.clientX,s=t.clientY,i=n-o.x,a=s-o.y;Math.sqrt(w(i,2)+w(a,2))>5&&(h(),l.current&&(clearTimeout(l.current),l.current=null),r(null))},onTouchEnd:()=>{l.current&&(window.clearTimeout(l.current),l.current=null),r(null)},style:{position:"relative",width:"100%"},children:e})},dT=({content:e,isMobile:t=!1,isIos:n=!1,className:s="",style:i={},hasQuoteText:a=!1})=>{const o=D.useRef(null),[,r]=D.useState(!1),l=D.useRef(""),{t:c}=ye(),d=D.useRef(0),u=D.useRef(!1),h=t?5120:10240,m=t?5120:10240,[p,g]=D.useState(()=>Math.min(e.length,h));D.useEffect(()=>{g(Math.min(e.length,h))},[e,h]);const f=D.useMemo(()=>e.slice(0,p),[e,p]),v=e.length>h,y=p>=e.length,b=(e,t)=>{if(!o.current)return;r(!0);performance.now();const s=n?1024:2048,i=n?3:5;let a=0;const l=document.createDocumentFragment(),c=()=>{if(t===d.current){for(let t=0;t{if(t!==d.current)return;o.current&&(n&&(o.current.style.transform="translateZ(0)",o.current.style.willChange="transform"),o.current.textContent="",o.current.appendChild(l),x(),n&&o.current&&(o.current.style.transform="",o.current.style.willChange="auto"));performance.now();r(!1)},0)}};u.current||!("fonts"in document)?c():document.fonts.ready.then(()=>{u.current=!0,c()})},x=()=>{const e=document.getElementById("messages-container");e&&(e.scrollTop=e.scrollHeight)};D.useEffect(()=>{if(o.current&&f!==l.current){const e=++d.current;t?b(f,e):((e,t)=>{let n=e;if(a&&e){const t=new RegExp("```[\\s\\S]*?"+String(a).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"[\\s\\S]*?```");n=e.replace(t,"").trim()}if(!o.current)return;r(!0),performance.now();const s=document.createDocumentFragment();let i=0;const l=()=>{if(t!==d.current)return;const e=Math.min(n.length,i+5120),a=n.slice(i,e);s.appendChild(document.createTextNode(a)),i=e,i{t===d.current&&(o.current&&(o.current.textContent="",o.current.appendChild(s),x()),performance.now(),r(!1))})};l()})(f,e),l.current=f}},[f,t,n,a]);const w=C({lineHeight:t?"24px":"28px"},i),_="whitespace-pre-wrap user-message-content "+(t?"":"fade-in");return F.jsxs(F.Fragment,{children:[F.jsxs("div",{className:Q("chunked-text-renderer-root",{"chunked-text-renderer-root-with-expand":v}),children:[F.jsx("p",{ref:o,className:`${_} ${s}`,style:w}),v&&F.jsx("button",{type:"button",className:Q("chat-user-message-expand-toggle",{"chat-user-message-expand-toggle-mobile":t,"chat-user-message-expand-toggle-pc":!t}),onClick:y?()=>{g(h)}:()=>{g(t=>Math.min(e.length,t+m))},"aria-label":c(y?"Collapse":"Expand"),children:F.jsx(pi,{type:y?"icon-line-chevron-up":"icon-line-chevron-down",className:"chat-user-message-expand-toggle-icon"})})]}),!y&&F.jsx("div",{className:"chunked-text-renderer-root-expand-toggle-mask"})]})},uT=({message:e,handleDeleteMessage:t,isOldMessageInNewBranch:n})=>{var s,i,a,o,r;const l=ye(),{content:c,files:d,extra:u}=e,h=Pd(e=>e.user),m=js(e=>e.chatId),p=js(e=>e.isChat),g=js(e=>e.history),f=js(e=>e.setEmitSendPromptType),v=hR(e=>e.voicePlayingMessageId),[y,b]=D.useState(""),[x,w]=D.useState(!1),[_,k]=D.useState(!1),j=D.useRef(!1),[,T]=D.useState(!1),E=cR(e=>e.mobile),N=zs(),I=ud(e=>e.isSharePage),M=yd(e=>e.models),R=D.useMemo(()=>!0,[E,I]),P=t=>{var n,s;const i=BR(JSON.stringify(t),{}),a=M.filter(t=>{var n;return null==(n=e.models)?void 0:n.includes(t.id)});if(!(a.some(e=>{var t,n,s;return 2===(null==(s=null==(n=null==(t=e.info)?void 0:t.meta)?void 0:n.abilities)?void 0:s.parse_url)})||a.some(e=>{var t,n,s;return 3===(null==(s=null==(n=null==(t=e.info)?void 0:t.meta)?void 0:n.abilities)?void 0:s.parse_url)})&&(null==(n=e.feature_config)?void 0:n.thinking_enabled))&&(o=i.content,lu(o).length>0)){T(!0);const e=ru(i.content,null==(s=i.extra)?void 0:s.url_parse_result);return S(C({},i),{parseResult:e})}return T(!1),i;var o},L=e=>e===St.SUCCESS||e===St.PARSING,O=D.useMemo(()=>P(e),[e.id]),q=D.useMemo(()=>!(!e.sub_chat_type||![bt.OmniAudio,bt.OmniVideo].includes(e.sub_chat_type)),[e.sub_chat_type]),U=D.useMemo(()=>Array.isArray(c)?"":q?c?`“${c}”`:l.t("Transcript not available"):c,[c,l,q]),H=D.useMemo(()=>{var t,n,s;let i=g.messages[g.currentId||""];for(;i&&(null==i?void 0:i.parentId)!==(e.id||e.fid);)i=g.messages[i.parentId||""];return["RateLimited","ParallelLimited","data_inspection_failed"].includes((null==(t=null==i?void 0:i.error)?void 0:t.errorCode)||(null==(s=null==(n=null==i?void 0:i.error)?void 0:n.detail)?void 0:s.code)||"")},[g.currentId,g.messages,e.fid,e.id]),B=D.useMemo(()=>{var t,n,s;let i=g.messages[g.currentId||""];for(;i&&(null==i?void 0:i.parentId)!==(e.id||e.fid);)i=g.messages[i.parentId||""];return"data_inspection_failed"!==(null==(t=null==i?void 0:i.error)?void 0:t.errorCode)&&"data_inspection_failed"!==(null==(s=null==(n=null==i?void 0:i.error)?void 0:n.detail)?void 0:s.code)&&H},[g.currentId,g.messages,e.fid,e.id,H]),z=D.useMemo(()=>{var t;return q&&(e=>{const t=Math.floor(e/1e3),n=Math.floor(t/60),s=t%60;return`${String(n).padStart(2,"0")}:${String(s).padStart(2,"0")}`})(null==(t=null==e?void 0:e.extra)?void 0:t.timecost)},[q,null==(s=null==e?void 0:e.extra)?void 0:s.timecost]),G=(t,n=!0)=>A(null,null,function*(){if(ti()&&!j.current)return;k(!1),f(mt.EDIT);const s=t.replace(/\s+/g,"");if((null==t?void 0:t.trim())&&0!==s.length)if(t.length>kt)vi.open({type:"error",content:l.t("Prompt cannot exceed {{value}} characters.",{value:kt})});else{if(!n){const n=sS(e),{success:s,data:i}=yield _g({origin_content:n,new_content:t});if(!s&&"data_inspection_passed"!==i.code)return}yield((e,t,n=!0)=>A(null,null,function*(){const s=js.getState().history;bM.editMessage({messageId:e,content:t,history:s,submit:n})}))(e.id,t,n),w(!1),b(""),e.childrenIds.includes(v)&&Aj.getInstance().stopAllPlayer()}else vi.open({type:"error",content:l.t("The content cannot be empty!")})});D.useEffect(()=>{j.current=_},[_]);let $=null;return F.jsxs(ie,{gap:10,className:"chat-user-message-container-wrapper",children:[!R&&F.jsx(Bk,{user:h,menu:!1}),F.jsxs("div",{className:Q("chat-user-message-container",{"chat-user-message-container-nobubble":!R}),children:[F.jsx(Oj,{timeClassName:"chat-user-message-header-timestamp",username:null==h?void 0:h.name,timestamp:e.timestamp,isBubbleMode:R,timecost:z||void 0}),F.jsx(Rj,{messageId:e.id,files:d,isBubbleMode:R}),(null==(i=null==u?void 0:u.meta)?void 0:i.quoteText)&&F.jsxs("div",{className:"quote-text-item-btn",onClick:()=>{var t,n,s,i,a,o;$&&(clearTimeout($),$=null);const r=e.extra,l=document.getElementById(`qwen-chat-message-user-${null==(t=null==r?void 0:r.meta)?void 0:t.quoteId}`)||document.getElementById(`qwen-chat-message-assistant-${null==(n=null==r?void 0:r.meta)?void 0:n.quoteId}`),c=document.getElementById("chat-messages-scroll-container"),d=document.getElementById("chat-message-container");if(d&&l){const e=l.getBoundingClientRect(),t=d.getBoundingClientRect(),n={top:e.top-t.top,left:e.left-t.left,bottom:e.bottom-t.bottom,right:e.right-t.right};c.scrollTo({top:(null==(s=null==r?void 0:r.meta)?void 0:s.position)+n.top+40,behavior:"smooth"});const h=document.createRange(),m=null==(i=null==l?void 0:l.querySelector(".response-message-content"))?void 0:i.querySelector(".qwen-markdown");if(!m||!(null==(a=null==r?void 0:r.meta)?void 0:a.quoteIndex))return;try{const e=(null==(o=m.textContent)?void 0:o.length)||0,t=Math.min(r.meta.quoteIndex,e),n=Math.min(r.meta.quoteIndex+1,e);h.setStart(m,t),h.setEnd(m,n);const s=window.getSelection();s.removeAllRanges(),s.addRange(h),$=setTimeout(()=>{s.removeAllRanges(),$=null},3e3)}catch(u){}}},children:[F.jsx(pi,{type:"icon-line-arrow-curve-left-right",className:"quote-icon"}),F.jsx("div",{className:"fileitem-file-name",children:F.jsx("div",{className:"fileitem-text-name-text",children:null==(a=null==u?void 0:u.meta)?void 0:a.quoteText})})]}),x?F.jsx(Oy,{value:y,open:!0,onOk:e=>{G(e||"",!0)},onCancel:()=>{b(""),w(!1)},okText:l.t("Send"),cancelText:l.t("Cancel"),showExtra:!1}):F.jsxs(F.Fragment,{children:[!!U&&F.jsx(cT,{children:F.jsx(ie,{className:"chat-user-message-wrapper",justify:R?"flex-end":"flex-start",children:(null==(o=null==O?void 0:O.parseResult)?void 0:o.length)?F.jsx("p",{className:"chat-user-message",children:O.parseResult.map(e=>"url"===e.type?F.jsx(Si,{style:{display:"inline-block"},className:"tooltip-box",title:e.title,children:F.jsx("a",{className:`url-analyze url-analyze-${e.status}`,href:L(e.status)?e.content:void 0,target:"_blank",onClick:()=>{var t;if(E&&!L(e.status)&&vi.open({type:"warning",content:null!=(t=e.title)?t:""}),ti()&&L(e.status)){const t=`qwen://web?url=${encodeURIComponent(e.content)}`;bM.adapter.invoke({method:"openWindow",params:{uri:t}})}},children:F.jsx("span",{style:{whiteSpace:"pre"},children:e.content.trim()})})},e.content):F.jsx("span",{children:e.content},e.content))}):F.jsx("div",{className:"chat-user-message",children:F.jsx(dT,{hasQuoteText:null==(r=null==u?void 0:u.meta)?void 0:r.quoteText,content:U,isMobile:E,isIos:N,className:Q({"chat-user-message-text-renderer-omni":q,"chat-user-message-text-renderer-omni-available":q&&!c})})})})}),F.jsx(lT,{showActionControl:!!U,message:e,isFirstMessage:!e.parentId,isChatIntercept:H,isNonFilterGreenNetError:B,isOmni:q,handleEditMessage:()=>{if(pl("clkReviseMsg",{params:{et:"CLK",c4:"query"},aesParams:{c5:m,c6:`${null==e?void 0:e.id}`},paramsExtend:{chat_id:m,msg_id:`${null==e?void 0:e.id}`}}),p||Rs.getState().visionGenerating)return void vi.open({type:"warning",content:l.t("In the conversation, please wait a moment.")});bM.closeShowControls();const t=e.content;ti()?(k(!0),bM.firstOn(Gu.MESSAGE_EDIT_SAVE,e=>G(e)),bM.adapter.invoke({method:"openHalfWindow",params:{type:"edit",content:t,ext:""}})):(b(t),w(!0))},isOldMessageInNewBranch:n,handleDeleteMessage:()=>{t(e.id)}})]})]})]})};Dj(uT);const hT=(e,t)=>{var n,s,i;const{phaseContentMode:a="single_answer"}={};if(!e)return"";if(null==e?void 0:e.content)return e.content;if(!Array.isArray(null==e?void 0:e.content_list))return"";if(!(null==e?void 0:e.content_list.length))return"";if("single_answer"===a){const t=null==(n=null==e?void 0:e.content_list)?void 0:n.findLast(e=>e.phase===wt.IMAGE_GEN&&e.content);return t?(null==t?void 0:t.content)||"":(null==(i=null==(s=null==e?void 0:e.content_list)?void 0:s.findLast(e=>[wt.ANSWER].includes(e.phase)))?void 0:i.content)||""}return null==e?void 0:e.content_list.filter(e=>e.phase===wt.ANSWER).map(e=>(null==e?void 0:e.content)||"").join("")},mT=e=>({meta:{subChatType:"translate",translateLanguage:e}}),pT=(e,t,n)=>`${e}\n${t}\n\n${n.title}:`,gT=(e,t)=>{var n,s,i,a,o,r,l,c,d,u,h,m,p,g,f,v,y,b,x,w,_;let C=null;if(C=t?null==(n=null==e?void 0:e.messages)?void 0:n[t]:(e?Object.values((null==e?void 0:e.messages)||{}):[]).find(e=>{var t;return"assistant"===e.role&&e.sub_chat_type===yt.INTERRUPT&&!!(null==(t=null==e?void 0:e.content_list)?void 0:t.find(e=>e.phase===wt.PdfMdGen))}),C){const e=null==(s=null==C?void 0:C.content_list)?void 0:s.find(e=>e.phase===wt.PdfMdGen),n=(null==(a=null==(i=null==e?void 0:e.extra)?void 0:i.deep_research)?void 0:a.version)||"";if(n)return n;if(t)return""}const S=e=>{var t,n;return(null==e?void 0:e.sub_chat_type)===yt.DeepResearch||(null==(n=null==(t=null==e?void 0:e.extra)?void 0:t.meta)?void 0:n.subChatType)===yt.DeepResearch},k=(e?Object.values((null==e?void 0:e.messages)||{}):[]).filter(e=>"assistant"===e.role&&S(e)&&!(null==e?void 0:e.error)),j=null==e?void 0:e.currentId;if(j){const t=_r(j,e).find(e=>"assistant"===(null==e?void 0:e.role)&&S(e)&&!(null==e?void 0:e.error));if(t)return(null==(c=null==(l=null==(r=null==(o=null==t?void 0:t.content_list)?void 0:o[0])?void 0:r.extra)?void 0:l.deep_research)?void 0:c.version)||""}return j&&(null==(u=null==(d=null==e?void 0:e.messages)?void 0:d[j])?void 0:u.sub_chat_type)===yt.DeepResearch?(null==(v=null==(f=null==(g=null==(p=null==(m=null==(h=null==e?void 0:e.messages)?void 0:h[j])?void 0:m.content_list)?void 0:p[0])?void 0:g.extra)?void 0:f.deep_research)?void 0:v.version)||"":(null==(y=null==k?void 0:k[0])?void 0:y.content_list)&&(null==(_=null==(w=null==(x=null==(b=k[0])?void 0:b.content_list[0])?void 0:x.extra)?void 0:w.deep_research)?void 0:_.version)||""},fT=(e,t,n)=>{var s,i,a,o,r,l;const{chatType:c,subChatType:d,extra:u={},userAction:h}=n;switch(c){case yt.Artifacts:case yt.ImageGeneration:case yt.VideoGeneration:case yt.Image2Video:case yt.WebSearch:case yt.Slides:case yt.Txt2Txt:{if((null==(s=null==u?void 0:u.meta)?void 0:s.user_action)&&delete u.meta.user_action,[bt.OmniAudio,bt.OmniVideo].includes(d))return S(C({},n),{subChatType:yt.Txt2Txt});let e=d||c;return t&&"translate"===t||"translate"!==d||(e=n.chatType),S(C({},n),{subChatType:e})}case yt.DeepResearch:case yt.Travel:{const s=Te(u);let m="";return(null==(i=null==u?void 0:u.meta)?void 0:i.subChatType)&&"retry"===(null==(a=null==u?void 0:u.meta)?void 0:a.user_action)&&(m=null==(o=null==u?void 0:u.meta)?void 0:o.subChatType),(null==(r=null==s?void 0:s.meta)?void 0:r.user_action)&&(delete u.meta.user_action,delete s.meta.user_action),m=m||((e,t,n)=>{var s,i;if(!n)return e;const a=null==n?void 0:n.at(-1);if(e===yt.DeepResearch){if(t===yt.DeepResearchWebDev||t===yt.Podcast)return t;const e=null==n?void 0:n.findLast(e=>{var t,n;return((null==(n=null==(t=null==e?void 0:e.extra)?void 0:t.meta)?void 0:n.subChatType)===yt.DeepResearch||(null==e?void 0:e.sub_chat_type)===yt.DeepResearch)&&"assistant"===e.role}),o=n.findLastIndex(e=>{var t;return(null==e?void 0:e.chat_type)===yt.DeepResearch&&[yt.DeepResearch,yt.INTERRUPT].includes(e.sub_chat_type)&&(null==e?void 0:e.done)&&(null==(t=null==e?void 0:e.content_list)?void 0:t.some(e=>e.phase===wt.PdfMdGen))});let r=Te(n);-1!==o&&(r=r.slice(o+1));const l=null==r?void 0:r.find(e=>{var t;return(null==e?void 0:e.sub_chat_type)===yt.INTERRUPT&&"assistant"===e.role&&(null==(t=null==e?void 0:e.content_list)?void 0:t.find(e=>e.phase===wt.ANSWER))}),c=e&&!0!==(null==e?void 0:e.done)&&!(null==e?void 0:e.error)&&!l,d=(null==a?void 0:a.sub_chat_type)||(null==(i=null==(s=null==a?void 0:a.extra)?void 0:s.meta)?void 0:i.subChatType)||"";return[yt.DeepResearch,yt.INTERRUPT].includes(d)&&c?yt.INTERRUPT:(null==a?void 0:a.sub_chat_type)===yt.DeepThinking?yt.DeepResearch:yt.DeepThinking}return e===yt.Podcast?yt.Podcast:e===yt.Travel?(null==a?void 0:a.sub_chat_type)===yt.TRAVEL_FEEDBACK?yt.TRAVEL_RESEARCH:yt.TRAVEL_FEEDBACK:t})(c,t||"",e),c===yt.DeepResearch&&m===yt.INTERRUPT&&(s.deep_research_id=null==(l=e.findLast(e=>e.sub_chat_type===yt.DeepResearch&&"assistant"===e.role))?void 0:l.id),([yt.DeepResearchWebDev,yt.Podcast].includes(d)||h===mt.EDIT)&&(m=d),S(C({},n),{subChatType:m,extra:s})}}return n},vT=(e,t)=>{var n,s,i;let a="";switch(e){case Zf.md:a=(null==(n=null==t?void 0:t.md)?void 0:n.link)||"";break;case Zf.pdf:a=(null==(s=null==t?void 0:t.pdf)?void 0:s.link)||"";break;case Zf.image:a=(null==(i=null==t?void 0:t.image)?void 0:i.link)||""}if(!a){const e=ve();return void vi.openOnce({type:"error",content:e.t("Download failed: url error")})}try{Pl({url:a,errorTexts:!0})}catch(o){const e=ve();vi.openOnce({type:"error",content:e.t("Download failed")})}},yT=e=>{const t=xM.getFeatureStatus(e),{disabledInfo:n}=t;return!n.disabled||(vi.open({type:"warning",content:n.msg}),!1)},bT=e=>{var t,n,s;const{message:i,children:a,phase:o,boxId:r,isMultiChat:l}=e,c=cR(e=>e.config),d=js(e=>e.isChat),u=js(e=>e.setEmitSendPromptType),h=ud(e=>e.isSharePage),m=js(e=>e.chatMode),p=js(e=>e.branchInfo),g=Rs(e=>e.setSelectedText),f=Rs(e=>e.setSelectedTextPosition),v=Rs(e=>e.setSelectedTextId),y=Rs(e=>e.setSelectedTextIndex),{i18n:b}=ye(),[x,w]=D.useState(""),_=D.useCallback(e=>{bM.setSelectLocalLanguageCode(e),w(e)},[]),C=D.useCallback(()=>A(null,null,function*(){if(null==c?void 0:c.language){const e=yield bM.getSelectLocalLanguageCode(c,b.language);_(e)}}),[c,b,_]),S=D.useMemo(()=>{var e,t,n,s,a;return i.chat_type===yt.DeepResearch&&(null==(t=null==(e=i.extra)?void 0:e.meta)?void 0:t.subChatType)===yt.DeepThinking||i.chat_type===yt.Travel&&(null==(s=null==(n=i.extra)?void 0:n.meta)?void 0:s.subChatType)===yt.TRAVEL_FEEDBACK||i.isMultiResponse?[{key:tv.copy,text:b.t("Copy")}]:(null==(a=null==c?void 0:c.language)?void 0:a.length)&&"deep_research"!==i.chat_type&&"travel"!==i.chat_type?[{key:tv.copy,text:b.t("Copy")},{key:tv.ask,text:b.t("Ask Qwen")},{key:tv.explain,text:b.t("Explain")},{key:tv.translate,text:b.t("Translate")}]:[{key:tv.copy,text:b.t("Copy")},{key:tv.ask,text:b.t("Ask Qwen")},{key:tv.explain,text:b.t("Explain")}]},[i.chat_type,null==(n=null==(t=i.extra)?void 0:t.meta)?void 0:n.subChatType,i.isMultiResponse,null==(s=null==c?void 0:c.language)?void 0:s.length,b]),k=D.useMemo(()=>d||h||(null==p?void 0:p.isTemp)||"community"===m,[d,p,h,m]);D.useEffect(()=>{(null==c?void 0:c.language)&&C()},[c,C]);const j=D.useCallback(e=>{kR(jR(e)),pl("selectRangeCopy",{params:{et:"CLK"}})},[]),T=D.useCallback((e,t,n,s,i)=>{g(e),u(mt.ASK),f(s),v(n),y(i),pl("selectRangeAsk",{params:{et:"CLK"}})},[i.id]),E=D.useCallback(e=>{const t={type:"explain",messageId:i.id||void 0,content:{text:e}};pl("selectRangeExplain",{params:{et:"CLK"}}),u(mt.EXPLAIN),bM.seleteOperation(t)},[i.id]),N=D.useCallback((e,t)=>{var n,s;if(_(e),!c)return;const a=c.language;pl("selectRangeTranslate",{params:{et:"CLK"}});const o={type:"translate",messageId:i.id,extra:mT(e),content:{text:pT(b.t("Translate the following text into {{lang}}.",{lang:null!=(s=null==(n=a.find(t=>t.code===e))?void 0:n.title)?s:""}),`${b.t("TextTranslate")}${t}`,a.find(t=>t.code===e))}};u(mt.TRANSLATE),bM.seleteOperation(o)},[_,c,i.id,b,u]);return F.jsx(wb,{className:`response-message-content ${i.sub_chat_type} phase-${o}`,id:`chat-response-message-${i.id||""}`,menuId:i.id||"",disabledContainer:k,offset:10,boxId:r,menuList:S,languageCode:x,languages:(null==c?void 0:c.language)||[],onAskHandler:T,onCopyHandler:j,onExplainHandler:E,onTranslateHandler:N,askInputPlaceholder:b.t("Ask a question"),children:a})},xT=e=>{const{message:t}=e,n=Rs(e=>e.taskRunning),s=D.useRef(null),i=D.useRef(t),a=D.useCallback(()=>{var e,t;return(null==(e=i.current)?void 0:e.error)?"error":(null==(t=i.current)?void 0:t.done)?"done":n?"loading":"pause"},[n]),o=D.useCallback(e=>A(null,null,function*(){var t,n,r,l,c;if(!i.current)return;const{type:d,contentIndex:u}=e,h=a(),m=!!(null==(n=null==(t=i.current)?void 0:t.feature_config)?void 0:n.thinking_enabled);let p=[];if(void 0!==u&&d===xt.WebSearch)p=(null==(c=null==(l=null==(r=i.current.content_list)?void 0:r[u])?void 0:l.extra)?void 0:c.web_search_info)||[];else{const e=bM.collectAllSearchAndThinList([i.current],!1);p=d===xt.WebSearch?e[i.current.id||""].webSearchInfo||[]:e[i.current.id||""].contentList||[]}Vd(xt.Artifacts),bM.adapter.invoke({method:"storeInfo",params:{key:Vd([xt.ThinkingAndSearch,xt.Thinking].includes(d)?xt.Thinking:xt.WebSearch),value:JSON.stringify({originsList:p,type:d,currentId:i.current.id,status:h})}}),clearTimeout(s.current),"loading"===h&&m&&(s.current=setTimeout(()=>{o(e)},1e3))}),[a]),r=D.useCallback(e=>{const{type:t,currentTab:n,citationIndex:s}=e;o(e),bM.adapter.invoke({method:"openHalfWindow",params:{type:"openUrl",content:`${Qd(t)}?tab=${n}&citation_index=${s}`}})},[o]);return D.useEffect(()=>()=>{clearTimeout(s.current)},[]),D.useEffect(()=>{i.current=t},[t]),{openNativePopup:r}},wT=e=>{switch(e.toLowerCase()){case"javascript":return".js";case"typescript":return".ts";case"java":return".java";case"python":return".py";case"c":return".c";case"c++":case"cpp":return".cpp";case"c#":case"csharp":return".cs";case"go":return".go";case"rust":return".rs";case"php":return".php";case"ruby":return".rb";case"swift":return".swift";case"kotlin":return".kt";case"scala":return".scala";case"html":return".html";case"css":return".css";case"less":return".less";case"scss":return".scss";case"json":return".json";case"markdown":case"md":return".md";case"xml":return".xml";case"yaml":return".yaml";case"sql":return".sql";case"bash":case"sh":return".sh";case"perl":return".pl";case"r":return".r";case"matlab":case"objective-c":case"objc":return".m";case"dart":return".dart";case"lua":return".lua";case"groovy":return".groovy";case"typescript-definition":case"d.ts":return".d.ts";case"vue":return".vue";case"svelte":return".svelte";case"jsx":return".jsx";case"tsx":return".tsx";case"dockerfile":return"Dockerfile";case"makefile":return"Makefile";case"gitignore":return".gitignore";case"editorconfig":return".editorconfig";case"eslintconfig":case"eslintrc":return".eslintrc";case"prettierconfig":case"prettierrc":return".prettierrc";case"babelconfig":case"babelrc":return".babelrc";case"webpackconfig":return"webpack.config.js";case"jestconfig":return"jest.config.js";case"viteconfig":return"vite.config.js";case"nextconfig":return"next.config.js";case"angularconfig":case"angularconfigts":return"angular.json";case"reactconfig":return"react.config.js";case"vueconfig":return"vue.config.js";case"svelteconfig":return"svelte.config.js";case"gulpfile":return"gulpfile.js";case"gruntfile":return"Gruntfile.js";case"npmconfig":case"package.json":return"package.json";case"yarnconfig":case"yarn.lock":return"yarn.lock";case"bowerconfig":case"bower.json":return"bower.json";case"webpackconfigts":return"webpack.config.ts";case"jestconfigts":return"jest.config.ts";case"viteconfigts":return"vite.config.ts";case"nextconfigts":return"next.config.ts";case"reactconfigts":return"react.config.ts";case"vueconfigts":return"vue.config.ts";case"svelteconfigts":return"svelte.config.ts";case"gulpfilets":return"gulpfile.ts";case"gruntfilets":return"Gruntfile.ts";default:return".txt"}},_T=(e,t,n)=>{const s=qe().format("YYYYMMDD"),i=Math.random().toString(36).substr(2,9),a=wT(n)||".txt",o=`${t}_${n}_${s}_${i}${a}`,r=new Blob([e],{type:`text/${a.replace(/^\./,"")}`}),l=window.URL.createObjectURL(r),c=document.createElement("a");c.href=l,c.download=o,document.body.appendChild(c),c.click(),document.body.removeChild(c),window.URL.revokeObjectURL(l)},CT=O.memo(e=>{var t;const{className:n="",hostList:s=[],onClick:i=()=>{},onHostNameClick:a=()=>{}}=e,o=cR(e=>e.mobile),[r,l]=D.useState(!1),c=D.useRef(null),d=D.useMemo(()=>(null==s?void 0:s.length)>1,[s]),[u,h]=D.useState(0),m=D.useCallback(e=>Kd(e),[]),p=D.useMemo(()=>{const e=s[u];return S(C({},e),{hostOriginName:m((null==e?void 0:e.url)||"")})},[u,m,s]),g=D.useCallback(e=>{let t="prev"===e?u-1:u+1;t<0&&(t=0),t>=s.length&&(t=s.length-1),h(t)},[u,s.length]),f=D.useMemo(()=>[{icon:"icon-line-chevron-left",disabled:0===u,onClick:()=>{g("prev")}},{icon:"icon-line-chevron-right",disabled:u===s.length-1,onClick:()=>{g("next")}}],[u,s.length,g]),v=D.useMemo(()=>{var e,t;return F.jsxs("div",{className:Q("qwen-chat-markdown-tokens",n),onClick:a,children:[F.jsx("div",{className:"qwen-chat-markdown-tokens-hostname ",children:(null==(e=s[0])?void 0:e.hostname)||m(null==(t=s[0])?void 0:t.url)}),d&&F.jsxs("div",{className:"qwen-chat-markdown-tokens-hostname-more",children:["+",s.length-1]})]})},[n,m,s,a,d]),y=D.useCallback(e=>{try{return decodeURIComponent(e)}catch(t){return e}},[]);return D.useEffect(()=>{if(!r)return;const e=requestAnimationFrame(()=>{setTimeout(()=>{const e=c.current.popupElement;if(e){const t=20,n=((e,t=1)=>{if(!(e instanceof HTMLElement))return"none";const n=e.getBoundingClientRect(),s=n.left<=t,i=window.innerWidth-n.right<=t;return s?"left":i?"right":"none"})(e,t);if("none"===n)return;e.style.inset=e.style.inset.replace(/(\d+)px$/,(e,s)=>`${parseInt(s,10)+t*("right"===n?-1:1)}px`)}},0)});return()=>cancelAnimationFrame(e)},[r]),o?v:F.jsx(le,{trigger:"hover",open:r,ref:c,onOpenChange:l,rootClassName:"qwen-chat-comp-markdown-tokens-container",content:F.jsxs("div",{children:[F.jsxs(ie,{vertical:!0,gap:8,onClick:()=>i(p.url),className:"qwen-chat-markdown-tokens-popover-content",children:[F.jsxs(ie,{align:"center",justify:"space-between",children:[F.jsxs(ie,{align:"center",justify:"center",gap:4,children:[F.jsx(Fj,{src:(null==(t=s[u])?void 0:t.icon)||""}),F.jsx("div",{className:"qwen-chat-markdown-tokens-container-hostname",children:p.hostname?p.hostname:y(p.url)})]}),F.jsx(pi,{className:"qwen-chat-markdown-tokens-container-icon",type:"icon-line-arrow-up-right"})]}),F.jsx("div",{className:"qwen-chat-markdown-tokens-container-title",children:p.title}),F.jsx("div",{className:"qwen-chat-markdown-tokens-container-detail",children:p.description})]}),d&&F.jsxs("div",{className:"markdown-tokens-container-switch",children:[F.jsx("div",{className:"markdown-tokens-container-switch-left",children:f.map(e=>F.jsx("div",{className:Q("markdown-tokens-container-switch-container",{"markdown-tokens-container-switch-container-disabled":e.disabled}),onClick:e.onClick,children:F.jsx(pi,{className:"markdown-tokens-container-switch-icon",type:e.icon})},e.icon))}),F.jsxs("div",{className:"markdown-tokens-container-switch-right",children:[u+1,"/",s.length]})]})]}),arrow:!1,classNames:{root:"qwen-chat-markdown-tokens-container"},placement:"bottom",children:v})}),ST=()=>{const{i18n:e}=ye(),t=ud(e=>e.realTheme),n=cR(e=>e.mobile),s=D.useCallback(t=>A(null,null,function*(){(yield SR(t))&&vi.openOnce({type:"success",content:e.t("Copying to clipboard was successful!")})}),[e]),i=D.useCallback((e,t="")=>{const n=new Date,s=`Qwen_${t}_${`${n.getFullYear()}${String(n.getMonth()+1).padStart(2,"0")}${String(n.getDate()).padStart(2,"0")}`}_${Math.random().toString(36).slice(-9)}${wT(t)}`;Mr.saveAs(new Blob([e],{type:"text/plain;charset=utf-8"}),s)},[]),a=D.useCallback(e=>{["img.alicdn.com","image.qwenlm.ai/public_source"].find(t=>e.includes(t))?Ml(e):Pl({role:"assistant",url:e})},[]),o=D.useCallback(t=>{const{showDownload:n=!0,extraActions:a,showCollapse:o,isCollapsed:r,messageId:l="",downloadType:c="code",onToggleCollapse:d}=t||{};return t=>F.jsxs(F.Fragment,{children:[F.jsx(Si,{title:e.t("Copy"),children:F.jsx("div",{className:"qwen-markdown-code-header-action-item",onClick:()=>{(e=>{pl("reportCodeCopy",{params:{et:"CLK"},aesParams:{c5:e||""},paramsExtend:{msg_id:e||""}})})(l),s(t.text)},children:F.jsx(pi,{type:"icon-line-copy-right"})})}),n&&F.jsx(Si,{title:e.t("Download"),children:F.jsx("div",{className:"qwen-markdown-code-header-action-item",onClick:()=>{fl(l,c),i(t.text,t.lang)},children:F.jsx(pi,{type:"icon-line-download-02"})})}),o&&F.jsx(Si,{title:e.t(r?"View Results":"Collapse Code"),children:F.jsx("div",{className:"qwen-markdown-code-header-action-item",onClick:d,children:F.jsx(pi,{type:"icon-line-maximise"})})}),a]})},[e,s,i]),r=D.useCallback(e=>{const{headerActionsRender:n,headerSticky:s=!0,stickyTop:i=-40}=e||{},a=C({theme:t},n?{headerActionsRender:n}:{});return s&&(a.headerSticky=!0,a.stickyTop=i),a},[t]),l=D.useCallback(()=>({onClick:e=>s((null==e?void 0:e.text)||"")}),[s]),c=D.useCallback(t=>{const{preset:s="default",mergeConfig:i={}}=t||{},o={onError:()=>({errorMessage:e.t("Image Load Error")})};return"default"===s?(o.defaultWidth=1,o.defaultHeight=1,o.sizeScope=n?{width:[114,300],height:[126,380]}:[400,448]):"search"===s?o.controls={download:{onDownload:a}}:"artifact"===s&&(o.preview={mask:null}),C(C({},o),i)},[e,n,a]),d=D.useCallback((t="")=>Js()?{}:{headerActionsRender:n=>F.jsx(F.Fragment,{children:F.jsx(Ci,{placement:"bottomRight",menu:{items:[{key:"csv",label:F.jsx("div",{className:"qwen-markdown-table-header-export-item",onClick:()=>{const e=`table-${t}.csv`;fl(t,"csv"),RR(n,e)},children:e.t("Export to CSV")})},{key:"excel",label:F.jsx("div",{className:"qwen-markdown-table-header-export-item",onClick:()=>{const e=`table-${t}.xlsx`;fl(t,"excel"),PR(n,e)},children:e.t("Export to Excel")})}]},getPopupContainer:e=>e||document.body,children:F.jsx("div",{className:"qwen-markdown-table-header-action-item",children:F.jsx(pi,{type:"icon-line-download-02"})})})})},[e]);return{getCodeHeaderActionsRender:o,getCodeConfig:r,getCodespanConfig:l,getImageConfig:c,getTableConfig:d,getCitationContentRender:D.useCallback(e=>{const{sourcesList:t,sourceListCallback:s,enableWindowOpen:i=!0}=e;return e=>{const a=e.map(e=>{if(!Array.isArray(t)||!t.length)return null;const n=t[Number(e)-1];if(!n)return null;const{snippet:s,icon:i,title:a,url:o,hostname:r}=n;return{description:s,icon:i,title:a,url:o,hostIndex:e,hostname:r}}).filter(e=>e);return n?a.map(e=>F.jsx("div",{className:"qwen-markdown-citation-item",children:F.jsx(CT,{hostList:[e],onHostNameClick:()=>{null==s||s(Number(null==e?void 0:e.hostIndex)||0)}})},null==e?void 0:e.url)):a.length?F.jsx(CT,{hostList:a,onClick:i?e=>window.open(e):void 0,onHostNameClick:()=>{var e;null==s||s(Number(null==(e=a[0])?void 0:e.hostIndex)||0)}}):null}},[n]),getCitationConfig:D.useCallback(e=>{const{onClick:t,contentRender:n,visible:s}=e||{},i={};return t&&(i.onClick=t),n&&(i.contentRender=n),void 0!==s&&(i.visible=s),i},[]),getLoose:D.useCallback(()=>!["ja-JP","ko-KR","zh-CN","zh-TW"].includes(e.language),[e.language])}},kT=e=>{var t,n;const{message:s,phaseContentIndex:i,content:a}=e,o=(null==(t=s.content_list)?void 0:t[i])||{content:a},{openNativePopup:r}=xT({message:s}),l=cR(e=>e.mobile),c=Rs(e=>e.setCurrentShowControl),d=js(e=>e.setCurrentCitationInfo),u=ud(e=>e.setShowControls),h=ud(e=>e.setShowSharePanel),m=js(e=>e.allSearchAndThinkLists),p=Rs(e=>e.setCurrentActionMessageId),g=D.useMemo(()=>!s.done,[s.done]),{t:f}=ye(),v=D.useMemo(()=>({code:f("Code"),preview:f("Preview")}),[f]),y=D.useMemo(()=>{var e,t;if(Array.isArray(null==o?void 0:o.content))return"";let n=(null==o?void 0:o.content)||"";const s=o;return Array.isArray(null==(e=null==s?void 0:s.extra)?void 0:e.prev_round_image_list)&&(n=(null==(t=null==s?void 0:s.extra)?void 0:t.prev_round_image_list.map(e=>`![](${e})`).join("\n"))+"\n"+n),n},[o]),{getCodeConfig:b,getCodeHeaderActionsRender:x,getCodespanConfig:w,getImageConfig:_,getTableConfig:C,getCitationContentRender:S,getCitationConfig:k,getLoose:j}=ST(),T=tj({mediaType:"image",messageId:s.id,preview:{actions:["download"],tip:""}}),E=D.useMemo(()=>{var e;return!!(null==(e=null==s?void 0:s.feature_config)?void 0:e.thinking_enabled)},[null==(n=null==s?void 0:s.feature_config)?void 0:n.thinking_enabled]),N=D.useCallback(e=>{var t,n,i,a,o,l;if(s.chat_type===yt.DeepResearch){const r=null==(n=null==(t=null==bM?void 0:bM.getChatOptions())?void 0:t.history)?void 0:n.messages[(null==s?void 0:s.id)||""],c=null==(l=null==(o=null==(a=null==(i=null==r?void 0:r.content_list)?void 0:i.find(e=>e.phase===wt.ANSWER))?void 0:a.extra)?void 0:o.deep_research)?void 0:l.references;h(!0),bM.emit($u.SOURCE_CILCK,{Tab:$f.sources,citationIndex:Number(e)||0,list:c})}else{if(ti())return void r({type:E?xt.ThinkingAndSearch:xt.WebSearch,currentTab:$f.sources,citationIndex:Number(e)});h(!0),u(!0),c(E?xt.ThinkingAndSearch:xt.WebSearch),d({messageId:s.id||"",citationIndex:Number(e),tab:$f.sources})}},[s.chat_type,s.id,r,d,c,u,h,E]),I=D.useCallback((e=0)=>{if(ti())return void r({type:xt.WebSearch,currentTab:$f.sources,citationIndex:e});u(!0);const t=l||s.chat_type===yt.DeepResearch?xt.WebSearch:xt.ThinkingAndSources;c(t),d({messageId:s.id||"",citationIndex:e,tab:$f.sources}),p(null==s?void 0:s.id)},[s.chat_type,s.id,l,r,p,d,c,u]),A=D.useMemo(()=>{var e;return(null==(e=null==m?void 0:m[(null==s?void 0:s.id)||""])?void 0:e.webSearchInfo)||[]},[m,null==s?void 0:s.id]),M=D.useMemo(()=>({code:b({headerActionsRender:x({showDownload:!l,messageId:s.id||""})}),codespan:w(),image:_({preset:"search",mergeConfig:T}),table:C(s.id||""),citation:k({visible:!Ne(A),onClick:e=>N(e),contentRender:S({sourcesList:A,sourceListCallback:I})})}),[b,x,w,_,C,k,S,T,s.id,N,A,I,l]);return y?F.jsx("div",{className:"custom-qwen-markdown",children:F.jsx(Ay,{content:y,loose:j(),tokenProps:M,styleProps:{showAnimation:g},locale:v})}):null},jT={"zh-cht":"研究規劃",zh:"研究规划",en:"Research Planning",fr:"Planification de la recherche",de:"Forschungsplanung",it:"Pianificazione della ricerca",ja:"リサーチプランニング",ko:"연구 계획",pt:"Planeamento da Pesquisa",ar:"تخطيطتخطيطPlanning for research",ru:"Планирование исследований",es:"Planificación de la investigación"},TT={"zh-cht":"總結",zh:"总结",en:"Summary",fr:"Résumé",de:"Zusammenfassung",it:"Riepilogo",ja:"要約する",ko:"요약",pt:"Resumo",ar:"ملخص",ru:"Подведите итог на русском языке (Россия).",es:"Resumen"},ET=(e,t,n)=>n?`${n} \n`:"";function NT(e,t){const n=[];return t.forEach(t=>{Object.prototype.hasOwnProperty.call(e,t)&&n.push(e[t])}),n}function IT(e,t){var n;return(null==(n=null==e?void 0:e.scrape)?void 0:n.map(e=>t[e]))||[]}const AT=["researchGoal","pageContent","codeContent","searchContent","webSites","learnings","learningMap"],MT=(e,t)=>{const n=[...e],s="v4"===t?"researchGoal":"searchContent",i=n.indexOf(s);return-1!==i&&n.splice(i+1,0,"webSites"),n},RT=e=>{var t,n,s,i,a,o;const r=[],l=null!=(n=null==(t=null==e?void 0:e[0])?void 0:t.lang_code)?n:"en",c=null!=(o=null==(a=null==(i=null==(s=null==e?void 0:e[0])?void 0:s.extra)?void 0:i.deep_research)?void 0:a.version)?o:"v1";for(let u=0;u{const{id:t=Fe(),query:s,learnings:i="",researchGoal:a="",pageContent:o="",codeContent:l="",searchContent:d="",runningIds:u,learningMap:h,webSites:m,status:p,sortKeys:g}=e;let f=i;if(h&&u){f=IT(u||{scrape:[]},h||{}).join("\n")}const v=NT({researchGoal:ET(0,0,a),pageContent:ET(0,0,o),codeContent:ET(0,0,l),searchContent:ET(0,0,d),webSites:m,learnings:ET(0,0,f),learningMap:ET(0,0,f)},g?MT(g,c):AT);r.push({stage:n,title:s,researchGoal:a,pageContent:o,codeContent:l,learnings:i,webSites:m,status:"finished"===p||"WebResultFinished"===p?"finish":"process",id:t,phase:n,content:v})})}}const d=[];for(const u of r){if("finish"!==u.status){d.push(u);break}d.push(u)}return d},PT={"zh-cht":"訪問過的網址",zh:"访问过的网址",en:"Visited URLs",fr:"URL visités",de:"Besuchte URLs",it:"URL visitate",ja:"訪問した网址",ko:"방문한 URL",pt:"URLs visitados",ar:"العناوين الم visited مترجة إلى اللغة العربية (عربي)",ru:"Посещенные URL-адреса",es:"URLs visitados",uk:"Відвідані URL",fa:"آدرس‌های بازدید شده",hi:"देखे गए URL",tr:"Ziyaret Edilen URL'ler"},LT=D.memo(({contentList:e,timestamp:t,endTime:n,messageId:s,isRenderError:i,subChatType:a,isRunning:o,isMessageStopped:r})=>{const l="pc-research-panel-content",[c,d]=D.useState([]),[u,h]=D.useState(!1),[m,p]=D.useState(!1),[g,f]=D.useState([]),[v,y]=D.useState([]),b=cR(e=>e.mobile),x=Rs(e=>e.setCurrentShowControl),w=Rs(e=>e.currentShowControl),_=Rs(e=>e.isPdfCardVisible),C=Rs(e=>e.setPDFViewInfo),S=Rs(e=>e.setIsSourcesVisible),k=ud(e=>e.setShowControls),j=ud(e=>e.setDeepDetailTitle),T=js(e=>e.setCurrentSearchSource),E=js(e=>e.setCurrentCitationInfo),N=js(e=>e.setCurrentSearchLists),I=Rs(e=>e.setCurrentDPLanguageCode),{i18n:A}=ye(),M=js(e=>e.chatId),R=ud(e=>e.showControls),P=D.useRef(null),L=D.useRef([]),O=D.useRef([]),q=D.useRef(!1),U=D.useRef(null),H=D.useCallback(e=>RT(e).map(t=>{var n,s;return t.title&&(t.title=A.t(t.title),t.lang_code=(null==(n=null==e?void 0:e[0])?void 0:n.lang_code)||"en",t.linkCardTitle=PT[null==(s=null==e?void 0:e[0])?void 0:s.lang_code]||"Visited URLs"),t.phase===wt.INTERRUPTRECEIVED&&(t.icon=F.jsx(pi,{type:"icon-line-message-circle-02"}),t.content=F.jsx("div",{style:{height:20}})),t}),[A]),B=D.useCallback(e=>{var t,n,i;N({[s]:H(e)});const a=null==(i=null==(n=null==(t=e.find(e=>e.phase===wt.ANSWER))?void 0:t.extra)?void 0:n.deep_research)?void 0:i.references;y(a);const o=!!e.find(e=>e.phase===wt.ANSWER&&e.content);h(o);const r=H(e);f(r);const l=!r.filter(e=>"process"===e.status);p(l)},[H]);D.useEffect(()=>{Array.isArray(c)&&B(c)},[c,B]);const z=D.useMemo(()=>{const e=bM.getCurrentChatsubChatType(),t=Pt(e)||e===yt.INTERRUPT;return!(!o||!t||i)},[o,i]),G=D.useCallback(({tab:e=$f.step,action:t="open",citationIndex:n=0})=>{var o,r;if(!Array.isArray(c))return;d(O.current);const l=(null==(r=null==(o=O.current)?void 0:o[0])?void 0:r.lang_code)||"en";I(Is[l]||Is.en);let u=z?"running":"finished";if(z||_?(!z&&_&&m||i)&&(u="error"):u="stop",!ti())return;const h={key:Vd(xt.DeepResearch),value:JSON.stringify({contentList:O.current,status:u,currentId:s,messageType:a})};bM.adapter.invoke({method:"storeInfo",params:h}),"open"===t&&bM.adapter.invoke({method:"openHalfWindow",params:{type:"openUrl",content:`${Qd(xt.DeepResearch)}?id=${M}&tab=${e}&messageId=${s}&citation_index=${n}`}})},[c,z,_,m,i,s,M,bM,a]),$=D.useCallback(e=>{const{list:t,tab:n,citationIndex:i=0}=e||{};if(ti())G({tab:n||$f.sources,citationIndex:i});else if(b){bM.closeShowControls(),E({messageId:s,citationIndex:i,tab:$f.sources});const e=Array.isArray(t)?t:v;T({[s]:e,type:xt.DeepResearchLinkSource}),k(!0),x(xt.DeepResearchLinkSource)}else{bM.closeShowControls(),E({messageId:s,citationIndex:i,tab:$f.sources});const e=Array.isArray(t)?t:v;T({[s]:e,type:xt.DeepResearch}),k(!0),x(xt.DeepResearch)}},[v,s,b,G,E,T,k,x]);D.useEffect(()=>(bM.on($u.SOURCE_CILCK,$),()=>{bM.off($u.SOURCE_CILCK,$)}),[bM,$]),D.useEffect(()=>()=>{k(!1),x(xt.None)},[]);const W=e=>{e.deltaY<0&&(U.current&&clearTimeout(U.current),q.current=!0,U.current=setTimeout(()=>{q.current=!1},5e3))},V=D.useCallback(()=>{var e;const t=document.getElementById(l),n="finished"===(null==(e=(O.current||[]).find(e=>e.phase===wt.PdfMdGen))?void 0:e.status);t&&t.addEventListener("wheel",W),n?P.current&&clearInterval(P.current):P.current=setInterval(()=>{const e=JSON.stringify(O.current);e!==L.current&&(L.current=e,G({tab:$f.step,action:"update"}),setTimeout(()=>{var e;o&&(e=t,q.current||null==e||e.scrollTo({top:e.scrollHeight,behavior:"smooth"}))},100))},100)},[l,o,G]);D.useEffect(()=>{O.current=e},[e]);const Q=D.useRef(void 0);D.useEffect(()=>{Q.current!==z&&(Q.current=z,z?(P.current&&clearInterval(P.current),V()):(P.current&&clearInterval(P.current),G({tab:$f.step,action:"update"})))},[z,G,V]),D.useEffect(()=>()=>{P.current&&clearInterval(P.current),S(!1),C(null)},[]);const K=D.useMemo(()=>!z&&r,[z,r]),Y=D.useMemo(()=>{let e="";return e=z?a===yt.DeepResearch?`${A.t("Deep Research")}...`:`${A.t("Travel Research")}...`:K?a===yt.DeepResearch?A.t("Deep Research Stopped"):A.t("Travel Research Stopped"):i?a===yt.DeepResearch?A.t("Deep Research Failed"):A.t("Travel Research Failed"):a===yt.DeepResearch?A.t("Deep Research Completed"):A.t("Travel Research Completed"),j(e),e},[z,K,i,A,a]),J=D.useMemo(()=>z?"running":!z&&_?"finished":"stop",[z,_]),[X,Z]=D.useState(!z),ee=(e=!0)=>{e&&bM.closeShowControls(),Z(!0)},te=e=>{(void 0!==e?e:!(R&&w===xt.DeepResearchDetail))?(E({messageId:s,citationIndex:0,tab:$f.step}),k(!0),Z(!1),x(xt.DeepResearchDetail),N({[s]:H(c)})):ee()};D.useEffect(()=>{z&&!b&&te(!0)},[z,b]),D.useEffect(()=>{if(bM)return bM.on(Gu.MESSAGE_DEEP_RESEARCH_CLOSE_DETAIL,ee),()=>{null==bM||bM.off(Gu.MESSAGE_DEEP_RESEARCH_CLOSE_DETAIL,ee)}},[bM]);return F.jsx(rx,{texts:{detail:A.t("Details")},loading:z,onStepsChange:(e,t,n)=>{bM.emit(Gu.MESSAGE_STOP_SCROLL_TO_BOTTOM);const s=document.getElementById("research-panel-detail-content"),i=document.getElementById(`${Vf.markdown}_deepDetail_${t.id}`);s&&i&&function(e,t,n=0){if(!e||!t)return;const s=t.getBoundingClientRect(),i=e.getBoundingClientRect(),a=s.top-i.top+e.scrollTop-n;null==e||e.scrollTo({top:a,behavior:"smooth"})}(s,i,0)},cardType:"list",sourceList:v,timestamp:t,endTime:n,searchTitle:Y,deepResearchList:g,showAll:X,disableAlls:!u,contentId:l,displayDrawer:!0,cardStatus:J,onSourcesCilck:$,onAllChange:e=>{Z(e)},onLinkCard:e=>{Array.isArray(e)?$({list:e}):window.open(e.url)},onCardClick:()=>{$({tab:$f.step}),E({messageId:s,citationIndex:0,tab:$f.step})},onDetailClick:()=>{te()},webSourceOption:{noSourceText:A.t("no sources"),headerTitle:A.t("Search Source · {{Number}}",{Number:null==v?void 0:v.length}),onClickItem:()=>{}},className:"research-panel"})}),OT=D.memo(({message:e})=>{var t,n,s,i,a;const o=(null==e?void 0:e.sub_chat_type)||(null==(n=null==(t=null==e?void 0:e.extra)?void 0:t.meta)?void 0:n.subChatType),{getImageConfig:r,getCodeConfig:l}=ST();if(Pt(o)){const t=!!(null==e?void 0:e.error),n=!(null==e?void 0:e.done)&&!t,c=(null==(i=null==(s=e.content_list)?void 0:s.find(e=>e.phase===wt.RESEARCHNOTICE))?void 0:i.content)||"";return F.jsxs("div",{className:"deep-research-panel",children:[F.jsx(Ay,{content:c,tokenProps:{image:r({preset:"artifact"}),code:l()}}),F.jsx(LT,{messageId:e.id,contentList:e.content_list,timestamp:e.timestamp,subChatType:o,endTime:(null==(a=null==e?void 0:e.extra)?void 0:a.endTime)||window._currentTime_,isRenderError:t,isRunning:n,isMessageStopped:!!e.is_stop})]})}return null}),DT=e=>{const t=e.match(/```[\s\S]*?```/g),n=[];t&&t.forEach(e=>{const t=e.split("\n")[0].replace("```","").trim().toLowerCase(),s=e.replace(/```[\s\S]*?\n/,"").replace(/```$/,"");n.push({lang:t,code:s})});let s="",i="",a="";const o=n.find(e=>"jsx"===e.lang),r=n.find(e=>"tsx"===e.lang);if(o){const{code:e}=o}else if(r){const{code:e}=r}else n.forEach(e=>{const{lang:t,code:n}=e;"html"===t?s+=n+"\n":"css"===t?i+=n+"\n":"javascript"!==t&&"js"!==t||(a+=n+"\n")});let l={type:"",iframeType:"",content:""};if(""!==s||""!==i||""!==a){let e="";e=""!==i||""!==a?`\n \n \n \n \n \n \n \n \n ${s}\n\n