π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(spa): compile StyleX from lobe-ui tokens and migrate StatisticCard (#21042)
Innei87b558620adb
diff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.mdindex 174ae9656e1..3f6c227763c 100644--- a/.agents/skills/react/SKILL.md+++ b/.agents/skills/react/SKILL.md@@ -8,11 +8,21 @@ user-invocable: false## Styling-| Scenario | Approach |-| ---------------------------------------------------------- | -------------------------------------------------------------- |-| Most cases | `createStaticStyles` + `cssVar.*` (zero-runtime, module-level) |-| Simple one-off | Inline `style` attribute |-| Truly dynamic (JS color fns like `readableColor`/`chroma`) | `createStyles` + `token` β **last resort** |+| Scenario | Approach |+| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Files already on StyleX, and new SPA styles | `stylex.create` + `@lobehub/ui/stylex/cssVar.stylex` / `@lobehub/ui/stylex/media.stylex`. The SPA compiler is `plugins/vite/stylex.ts` (`@stylexjs/unplugin`, prefix `lh`). Do not copy those token modules into the app. |+| Existing styles not yet migrated | `createStaticStyles` + `cssVar.*` (zero-runtime, module-level) |+| Simple one-off | Inline `style` attribute |+| Truly dynamic (JS color fns like `readableColor`/`chroma`) | `createStyles` + `token` β **last resort** |++### StyleX++- New code may not import `createStaticStyles` / `createStyles` / `css` / `keyframes` / `createGlobalStyle` / `injectGlobal` from `@lobehub/ui` (`stylex-migration/no-emotion-styles`). Files still on them are listed in `scripts/stylexMigration/legacyFiles.json`; after migrating one, run `bun run stylex:migration --prune-legacy`. Never add entries.+- Migrate a whole file at once. StyleX longhand rules carry raised specificity (`.x:not(#\#)`) and beat emotion classes on the same element, but StyleX shorthand rules do not, so a half-migrated element resolves by property.+- Element that also forwards a caller's `className` / `style`: `{...sx([styles.root, active && styles.active], className, style)}` from `@/styles/sx`. Spreading `stylex.props` next to `className` fails `@stylexjs/no-conflicting-props`.+- Component that lets callers restyle it: take `xstyle?: StyleXStyles` and pass it last in the `sx` / `stylex.props` array. A plain `className` from outside cannot override StyleX rules. Passing a class to `@lobehub/ui` components (`className`, `classNames`) works, because lobe-ui CSS sits in `@layer lobe-ui`.+- Values follow `@stylexjs/valid-styles`: no multi-value shorthands (`margin: '0 8px'` β `marginBlock` / `marginInline`), and string `flex` (`flex: '1'`).+- `bun run stylex:migration --list <A|B|C|D>` lists files by how hard they are to move: A flat, B self pseudo-classes, C descendant / ancestor coupling (use `stylex.defaultMarker()` + `stylex.when.ancestor()` or `xstyle`), D tag / third-party DOM selectors (scoped plain CSS).## Component Prioritydiff --git a/apps/auth/app/entry.client.tsx b/apps/auth/app/entry.client.tsxindex 1665c387ec2..b96f64a340e 100644--- a/apps/auth/app/entry.client.tsx+++ b/apps/auth/app/entry.client.tsx@@ -18,6 +18,10 @@ const loadDevServerConfig = async () => {void loadDevServerConfig();+// No index.html in this app, so the StyleX unplugin cannot inject its dev CSS;+// load it from the Vite dev server instead. Production CSS is linked by root.tsx.+if (import.meta.env.DEV) void import('virtual:lobe-stylex-dev-css');+startTransition(() => {hydrateRoot(document,diff --git a/apps/auth/app/env.d.ts b/apps/auth/app/env.d.tsindex ff90c34b425..a00a055213f 100644--- a/apps/auth/app/env.d.ts+++ b/apps/auth/app/env.d.ts@@ -1 +1,3 @@declare const __AUTH_PRERENDER_LOCALE__: string;++declare module 'virtual:lobe-stylex-dev-css' {}diff --git a/apps/auth/app/root.tsx b/apps/auth/app/root.tsxindex 2edf129ceaf..650757e5c81 100644--- a/apps/auth/app/root.tsx+++ b/apps/auth/app/root.tsx@@ -1,3 +1,5 @@+import '@/styles/stylex.css';+import type { CSSProperties, PropsWithChildren } from 'react';import { Links, Meta, Outlet, Scripts, ScrollRestoration, useRouteError } from 'react-router';import { isRtlLang } from 'rtl-detect';diff --git a/apps/auth/vite.config.shared.mts b/apps/auth/vite.config.shared.mtsindex ccadcf5174f..44a7204bffd 100644--- a/apps/auth/vite.config.shared.mts+++ b/apps/auth/vite.config.shared.mts@@ -12,6 +12,7 @@ import {sharedRendererDedupe,sharedRendererDefine,} from '../../plugins/vite/sharedRendererConfig';+import { stylexPlugin, stylexTokenModules } from '../../plugins/vite/stylex';import { DEFAULT_PRERENDER_LOCALE } from './app/lib/prerender';export interface AuthRrConfigOptions {@@ -154,8 +155,10 @@ export const createAuthRrConfig = ({ appRoot, repoRoot, resolvePlugins }: AuthRr// which rejects the extensionless directory imports some published `es/`// bundles still ship β bundle every dependency instead of externalizing.resolve: { noExternal: command === 'build' ? true : [] },+ optimizeDeps: { exclude: [...stylexTokenModules] },},},+ optimizeDeps: { exclude: [...stylexTokenModules] },plugins: [process.env.AUTH_TRACE_MODULE ? moduleTrace(process.env.AUTH_TRACE_MODULE) : undefined,authClientStubs(),@@ -164,6 +167,8 @@ export const createAuthRrConfig = ({ appRoot, repoRoot, resolvePlugins }: AuthRrviteMarkdownImport(),viteNodeModuleStub(),vitePlatformResolve('web'),+ // Both environments render StyleX components; the client build emits the CSS.+ stylexPlugin(),reactRouter(),...lobeIconImports(),...(resolvePlugins ?? []),diff --git a/apps/desktop/vite.renderer.config.ts b/apps/desktop/vite.renderer.config.tsindex ca0c5c6a7cd..e80142bc8c6 100644--- a/apps/desktop/vite.renderer.config.ts+++ b/apps/desktop/vite.renderer.config.ts@@ -260,7 +260,10 @@ export default defineConfig(async (env) => {reactDevtoolsPlugin(),excludeWebSpaBuildArtifactsPlugin(),vanillaExtractPlugin(),- ...(sharedRendererPlugins({ platform: 'desktop' }) as PluginOption[]),+ ...(sharedRendererPlugins({+ platform: 'desktop',+ stylexOverlaySrcDirs: isCloudDesktop ? [path.resolve(CLOUD_ROOT_DIR, 'src')] : undefined,+ }) as PluginOption[]),],resolve: {dedupe: sharedRendererDedupe,diff --git a/apps/share/app/entry.client.tsx b/apps/share/app/entry.client.tsxindex 452d07a8188..76bd648c890 100644--- a/apps/share/app/entry.client.tsx+++ b/apps/share/app/entry.client.tsx@@ -19,6 +19,10 @@ window.addEventListener('vite:preloadError', (event) => {}});+// No index.html in this app, so the StyleX unplugin cannot inject its dev CSS;+// load it from the Vite dev server instead. Production CSS is linked by root.tsx.+if (import.meta.env.DEV) void import('virtual:lobe-stylex-dev-css');+// The conversation route blocks its first render on this registry, whose own// dependency chain is several round trips deep. Kicking it off with the entry// β rather than when the gated chunk mounts β overlaps it with hydration.diff --git a/apps/share/app/root.tsx b/apps/share/app/root.tsxindex 3a7e66a1d63..4464cdbf2fa 100644--- a/apps/share/app/root.tsx+++ b/apps/share/app/root.tsx@@ -1,3 +1,5 @@+import '@/styles/stylex.css';+import { BRANDING_NAME } from '@lobechat/business-const';import type { PropsWithChildren } from 'react';import type { LoaderFunctionArgs, MetaFunction } from 'react-router';diff --git a/apps/share/app/virtual-modules.d.ts b/apps/share/app/virtual-modules.d.tsindex 4d6a0e24d84..e8895419f7e 100644--- a/apps/share/app/virtual-modules.d.ts+++ b/apps/share/app/virtual-modules.d.ts@@ -4,3 +4,5 @@ declare module 'virtual:react-router/server-build' {const build: ServerBuild;export = build;}++declare module 'virtual:lobe-stylex-dev-css' {}diff --git a/apps/share/vite.config.shared.mts b/apps/share/vite.config.shared.mtsindex a8186c7ffb3..39759f521c2 100644--- a/apps/share/vite.config.shared.mts+++ b/apps/share/vite.config.shared.mts@@ -13,6 +13,7 @@ import {sharedRendererDedupe,sharedRendererDefine,} from '../../plugins/vite/sharedRendererConfig';+import { stylexPlugin, stylexTokenModules } from '../../plugins/vite/stylex';export interface ShareRrConfigOptions {/** Directory holding `app/` and `src/` β the submodule copy when a host repo overlays this app. */@@ -170,8 +171,9 @@ export const createShareRrConfig = ({base: isDev ? '/' : process.env.VITE_CDN_BASE || '/',environments: {client: { define },- ssr: { define: ssrDefine },+ ssr: { define: ssrDefine, optimizeDeps: { exclude: [...stylexTokenModules] } },},+ optimizeDeps: { exclude: [...stylexTokenModules] },plugins: [process.env.SHARE_CHUNK_REPORT ? ssrChunkReport() : undefined,process.env.SHARE_TRACE_MODULE ? ssrModuleTrace(process.env.SHARE_TRACE_MODULE) : undefined,@@ -182,6 +184,8 @@ export const createShareRrConfig = ({viteNodeModuleStub(),vitePlatformResolve('web'),cloudflare({ viteEnvironment: { name: 'ssr' } }),+ // Both environments render StyleX components; the client build emits the CSS.+ stylexPlugin({ overlaySrcDirs: [path.join(repoRoot, 'src')] }),reactRouter(),...lobeIconImports(),...(resolvePlugins ?? []),diff --git a/apps/workbench/app/entry.client.tsx b/apps/workbench/app/entry.client.tsxindex e2c8867708e..1fa9dd46c01 100644--- a/apps/workbench/app/entry.client.tsx+++ b/apps/workbench/app/entry.client.tsx@@ -27,6 +27,10 @@ window.addEventListener('vite:preloadError', (event) => {}});+// No index.html in this app, so the StyleX unplugin cannot inject its dev CSS;+// load it from the Vite dev server instead. Production CSS is linked by root.tsx.+if (import.meta.env.DEV) void import('virtual:lobe-stylex-dev-css');+startTransition(() => {hydrateRoot(document,diff --git a/apps/workbench/app/root.tsx b/apps/workbench/app/root.tsxindex 31c0b76322f..42d340795e7 100644--- a/apps/workbench/app/root.tsx+++ b/apps/workbench/app/root.tsx@@ -1,3 +1,5 @@+import '@/styles/stylex.css';+import { BRANDING_NAME } from '@lobechat/business-const';import type { PropsWithChildren } from 'react';import type { LoaderFunctionArgs, MetaFunction } from 'react-router';diff --git a/apps/workbench/app/virtual-modules.d.ts b/apps/workbench/app/virtual-modules.d.tsindex 4d6a0e24d84..e8895419f7e 100644--- a/apps/workbench/app/virtual-modules.d.ts+++ b/apps/workbench/app/virtual-modules.d.ts@@ -4,3 +4,5 @@ declare module 'virtual:react-router/server-build' {const build: ServerBuild;export = build;}++declare module 'virtual:lobe-stylex-dev-css' {}diff --git a/apps/workbench/vite.config.rr.mts b/apps/workbench/vite.config.rr.mtsindex 45888a467ae..0c765140051 100644--- a/apps/workbench/vite.config.rr.mts+++ b/apps/workbench/vite.config.rr.mts@@ -10,6 +10,7 @@ import { viteMarkdownImport } from '../../plugins/vite/markdownImport';import { viteNodeModuleStub } from '../../plugins/vite/nodeModuleStub';import { vitePlatformResolve } from '../../plugins/vite/platformResolve';import { sharedRendererDefine } from '../../plugins/vite/sharedRendererConfig';+import { stylexPlugin, stylexTokenModules } from '../../plugins/vite/stylex';import { shikiCdnUrl } from './app/stubs/shikiCdn';import { isShikiSource } from './app/stubs/shikiSource';import { reportStubSurfaceGaps } from './app/stubs/surface';@@ -273,7 +274,7 @@ export default defineConfig({base: isDev ? '/' : process.env.VITE_CDN_BASE || '/',environments: {client: { define },- ssr: { define: ssrDefine },+ ssr: { define: ssrDefine, optimizeDeps: { exclude: [...stylexTokenModules] } },},plugins: [process.env.WORKBENCH_CHUNK_REPORT ? ssrChunkReport() : undefined,@@ -291,11 +292,19 @@ export default defineConfig({viteNodeModuleStub(),vitePlatformResolve('mobile'),cloudflare({ viteEnvironment: { name: 'ssr' } }),+ // Both environments render StyleX components; the client build emits the CSS.+ stylexPlugin(),reactRouter(),...lobeIconImports(),],optimizeDeps: {- exclude: ['shiki', '@shikijs/core', '@shikijs/stream', '@shikijs/transformers'],+ exclude: [+ 'shiki',+ '@shikijs/core',+ '@shikijs/stream',+ '@shikijs/transformers',+ ...stylexTokenModules,+ ],},resolve: {tsconfigPaths: true,diff --git a/eslint.config.mjs b/eslint.config.mjsindex a683cff234d..45dd9a477db 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -10,6 +10,7 @@ import {performanceRestrictedImportPaths,performanceRestrictedImportPatterns,} from './eslint.bundleBoundaries.mjs';+import { stylexMigrationConfig } from './scripts/stylexMigration/eslint.mjs';const tsconfigRootDir = fileURLToPath(new URL('.', import.meta.url));@@ -815,23 +816,13 @@ export default eslint('no-console': 0,},},- // agent-tracing CLI - console output is the primary interface+ // CLIs and debug utilities - console output is the primary interface{- files: ['packages/agent-tracing/**/*'],- rules: {- 'no-console': 0,- },- },- // lobehub-cli - console output is the primary interface- {- files: ['apps/cli/**/*'],- rules: {- 'no-console': 0,- },- },- // model-runtime debug utilities - console output is the primary interface- {- files: ['packages/model-runtime/src/utils/debugStream.ts'],+ files: [+ 'packages/agent-tracing/**/*',+ 'apps/cli/**/*',+ 'packages/model-runtime/src/utils/debugStream.ts',+ ],rules: {'no-console': 0,},@@ -851,6 +842,7 @@ export default eslint('@eslint-react/no-unnecessary-use-prefix': 0,},},+ ...stylexMigrationConfig,// CommonJS files rely on `require()` by design{files: ['**/*.cjs', 'apps/desktop/shell/**/*.js'],diff --git a/package.json b/package.jsonindex b07d0bc503d..311cd0fddbf 100644--- a/package.json+++ b/package.json@@ -123,6 +123,7 @@"self-hosting:docker-cn": "docker build -t lobehub-local --build-arg USE_CN_MIRROR=true .","start": "next start -p 3210","stylelint": "stylelint \"src/**/*.{js,jsx,ts,tsx}\" --fix",+ "stylex:migration": "tsx scripts/stylexMigration/index.ts","test": "npm run test-app && npm run test-server","test:e2e": "pnpm --filter @lobechat/e2e-tests test","test:e2e:smoke": "pnpm --filter @lobechat/e2e-tests test:smoke",@@ -339,6 +340,7 @@"@react-three/drei": "^10.7.8","@react-three/fiber": "^9.7.0","@saintno/comfyui-sdk": "^0.2.53",+ "@stylexjs/stylex": "0.19.1","@t3-oss/env-core": "^0.13.11","@t3-oss/env-nextjs": "^0.13.11","@tanstack/react-query": "^5.101.4",@@ -508,6 +510,8 @@"@prettier/sync": "^0.6.1","@rolldown/plugin-transform-imports": "0.1.1","@semantic-release/exec": "^6.0.3",+ "@stylexjs/eslint-plugin": "0.19.1",+ "@stylexjs/unplugin": "0.19.1","@testing-library/jest-dom": "^6.9.1","@testing-library/react": "^16.3.2","@testing-library/user-event": "^14.6.3",diff --git a/plugins/vite/sharedRendererConfig.test.ts b/plugins/vite/sharedRendererConfig.test.tsindex 71006abb0c3..a7c450a7576 100644--- a/plugins/vite/sharedRendererConfig.test.ts+++ b/plugins/vite/sharedRendererConfig.test.ts@@ -17,6 +17,19 @@ const getPluginNames = (platform: 'desktop' | 'web') =>.map((plugin) => plugin.name);describe('sharedRendererPlugins', () => {+ it('compiles app StyleX without taking @lobehub/ui out of pre-bundling', () => {+ const plugin = sharedRendererPlugins({ platform: 'web' })+ .flat(Number.POSITIVE_INFINITY)+ .find(+ (item): item is { config?: unknown; name: string } =>+ Boolean(item) &&+ typeof item === 'object' &&+ (item as { name?: string }).name === '@stylexjs/unplugin',+ );++ expect(plugin?.config).toBeUndefined();+ });+it('keeps the icon barrel transform out of the Electron renderer', () => {expect(getPluginNames('desktop')).not.toContain('lobe-icon-named-export-proxy');expect(getPluginNames('web')).toContain('lobe-icon-named-export-proxy');@@ -53,6 +66,10 @@ describe('lobe-dev-editor-provider', () => {describe('sharedOptimizeDeps', () => {it('pre-bundles the @lobehub/ui root entrypoint', () => {expect(sharedOptimizeDeps.include).toContain('@lobehub/ui');+ expect(sharedOptimizeDeps.exclude).toEqual([+ '@lobehub/ui/stylex/cssVar.stylex',+ '@lobehub/ui/stylex/media.stylex',+ ]);});});diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.tsindex f80614fcbf6..0d19ee033fe 100644--- a/plugins/vite/sharedRendererConfig.ts+++ b/plugins/vite/sharedRendererConfig.ts@@ -8,6 +8,7 @@ import { lobeUiImports } from './lobeUiImports';import { viteMarkdownImport } from './markdownImport';import { viteNodeModuleStub } from './nodeModuleStub';import { vitePlatformResolve } from './platformResolve';+import { stylexPlugin, stylexTokenModules } from './stylex';/*** Shared manual chunk naming β groups leaf-node modules to reduce chunk file count.@@ -483,6 +484,7 @@ const isDev = process.env.NODE_ENV !== 'production';interface SharedRendererOptions {platform: Platform;+ stylexOverlaySrcDirs?: string[];tsconfigPaths?: boolean;}@@ -521,6 +523,7 @@ export function sharedRendererPlugins(options: SharedRendererOptions) {exclude: [/\.(css|json|html)$/],hotKeys: ['altKey', 'ctrlKey'],}),+ stylexPlugin({ overlaySrcDirs: options.stylexOverlaySrcDirs }),react(),...(options.platform === 'desktop' ? [] : [...lobeIconImports(), ...lobeUiImports()]),];@@ -547,6 +550,7 @@ export function sharedRendererDefine(options: { isElectron: boolean; isMobile: b}export const sharedOptimizeDeps = {+ exclude: [...stylexTokenModules],include: ['react','react-dom',diff --git a/plugins/vite/stylex.tokens.test.ts b/plugins/vite/stylex.tokens.test.tsnew file mode 100644index 00000000000..b5c173af18b--- /dev/null+++ b/plugins/vite/stylex.tokens.test.ts@@ -0,0 +1,174 @@+// @vitest-environment node+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import os from 'node:os';+import path from 'node:path';++import { stylexAliases } from './stylex';++type TransformResult = {+ metadata?: { stylex?: unknown[] };+};++type Babel = {+ transformSync: (code: string, options: Record<string, unknown>) => TransformResult | null;+};++type StylexPlugin = ((api: unknown) => unknown) & {+ processStylexRules?: (rules: unknown[], config?: { useLayers?: boolean }) => string;+};++const root = path.resolve(import.meta.dirname, '../..');++const loadCompiler = () => {+ const rootRequire = createRequire(path.join(root, 'package.json'));+ const unpluginEntry = realpathSync(rootRequire.resolve('@stylexjs/unplugin'));+ const unpluginRoot = path.resolve(path.dirname(unpluginEntry), '..');+ const req = createRequire(path.join(unpluginRoot, 'package.json'));+ const loaded = req('@stylexjs/babel-plugin') as StylexPlugin & { default?: StylexPlugin };+ const plugin = loaded.default ?? loaded;++ return {+ babel: req('@babel/core') as Babel,+ plugin,+ processStylexRules: plugin.processStylexRules ?? loaded.processStylexRules,+ resolve: (specifier: string) => rootRequire.resolve(specifier),+ };+};++const consumerSource = `+import * as stylex from '@stylexjs/stylex';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { media } from '@lobehub/ui/stylex/media.stylex';++export const styles = stylex.create({+ title: {+ color: cssVar.colorText,+ fontSize: { default: 16, [media.sm]: 14 },+ },+});+`;++describe('@lobehub/ui StyleX tokens', () => {+ it('inlines published defineConsts into app CSS', () => {+ const { babel, plugin, processStylexRules, resolve } = loadCompiler();+ if (!processStylexRules) throw new Error('stylex babel plugin is missing processStylexRules');++ const cssVarFile = resolve('@lobehub/ui/stylex/cssVar.stylex');+ const mediaFile = resolve('@lobehub/ui/stylex/media.stylex');+ expect(readFileSync(cssVarFile, 'utf8')).toContain(+ 'export const cssVar = stylex.defineConsts(',+ );+ expect(readFileSync(mediaFile, 'utf8')).toContain('export const media = stylex.defineConsts(');++ const options = {+ classNamePrefix: 'lh',+ dev: false,+ runtimeInjection: false,+ test: false,+ unstable_moduleResolution: { rootDir: root, type: 'commonJS' },+ };+ const transform = (filename: string, code = readFileSync(filename, 'utf8')) => {+ const result = babel.transformSync(code, {+ babelrc: false,+ configFile: false,+ filename,+ plugins: [[plugin, options]],+ sourceType: 'module',+ });+ return result?.metadata?.stylex ?? [];+ };++ const css = processStylexRules(+ [+ ...transform(path.join(root, 'src/stylex-token-consumer.js'), consumerSource),+ ...transform(cssVarFile),+ ...transform(mediaFile),+ ],+ { useLayers: false },+ );++ expect(css).toContain('color:var(--lobe-color-text)');+ expect(css).toContain('@media (max-width: 575.98px)');+ expect(css).toMatch(/\.lh/);+ expect(css.match(/var\(--(?!lobe-)[^)]+\)/g)).toBeNull();+ });+});++describe('overlay StyleX aliases', () => {+ const overlayConsumer = `+import * as stylex from '@stylexjs/stylex';+import { overlay } from '@/overlay.stylex';++export const styles = stylex.create({ ring: { outline: overlay.ring } });+`;+ const overlayTokens = `+import * as stylex from '@stylexjs/stylex';++export const overlay = stylex.defineConsts({ ring: '3px solid rgb(1, 2, 3)' });+`;++ const withOverlayRepo = (run: (srcDir: string) => void) => {+ const dir = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'stylex-overlay-')));+ try {+ const srcDir = path.join(dir, 'src');+ mkdirSync(srcDir);+ writeFileSync(path.join(srcDir, 'overlay.stylex.ts'), overlayTokens);+ run(srcDir);+ } finally {+ rmSync(dir, { force: true, recursive: true });+ }+ };++ const compile = (srcDir: string, aliases: ReturnType<typeof stylexAliases>) => {+ const { babel, plugin, processStylexRules } = loadCompiler();+ if (!processStylexRules) throw new Error('stylex babel plugin is missing processStylexRules');++ const transform = (filename: string, code: string) =>+ babel.transformSync(code, {+ babelrc: false,+ configFile: false,+ filename,+ plugins: [+ [+ plugin,+ {+ aliases,+ classNamePrefix: 'lh',+ dev: false,+ runtimeInjection: false,+ test: false,+ unstable_moduleResolution: { rootDir: root, type: 'commonJS' },+ },+ ],+ ],+ sourceType: 'module',+ })?.metadata?.stylex ?? [];++ return processStylexRules(+ [+ ...transform(path.join(srcDir, 'consumer.js'), overlayConsumer),+ ...transform(path.join(srcDir, 'overlay.stylex.ts'), overlayTokens),+ ],+ { useLayers: false },+ );+ };++ it('resolves @/ token files from an overlay repo src first', () => {+ withOverlayRepo((srcDir) => {+ const aliases = stylexAliases([srcDir]);+ expect(aliases['@/*']).toEqual([path.join(srcDir, '*'), path.join(root, 'src/*')]);+ expect(compile(srcDir, aliases)).toMatch(/outline:3px solid (rgb\(1, ?2, ?3\)|#010203)/);+ });+ });++ it('cannot resolve overlay token files without the overlay src dir', () => {+ withOverlayRepo((srcDir) => {+ expect(() => compile(srcDir, stylexAliases())).toThrow(/Could not resolve/);+ });+ });++ it('does not list this repo src twice', () => {+ expect(stylexAliases([path.join(root, 'src')])['@/*']).toEqual([path.join(root, 'src/*')]);+ });+});diff --git a/plugins/vite/stylex.ts b/plugins/vite/stylex.tsnew file mode 100644index 00000000000..b241c6b3d44--- /dev/null+++ b/plugins/vite/stylex.ts@@ -0,0 +1,110 @@+import { existsSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import stylex from '@stylexjs/unplugin/vite';+import type { PluginOption, UserConfig } from 'vite';++import { stylexProxiedDevCssPlugin } from './stylexDevCss';+import { createStylexEntryCss } from './stylexEntryCss';++const findRepoRoot = (start: string) => {+ let dir = start;+ for (;;) {+ if (existsSync(path.join(dir, 'pnpm-workspace.yaml'))) return dir;+ const parent = path.dirname(dir);+ if (parent === dir) return;+ dir = parent;+ }+};++const repoRootFromMeta = () => {+ const url = import.meta.url;+ if (!url.startsWith('file:')) return;+ return path.resolve(fileURLToPath(new URL('../..', url)));+};++const repoRoot =+ [repoRootFromMeta(), findRepoRoot(process.cwd())].find(+ (dir) => dir && existsSync(path.join(dir, 'pnpm-workspace.yaml')),+ ) ?? process.cwd();++const isTest = process.env.VITEST === 'true' || process.env.NODE_ENV === 'test';++// Uncompiled defineConsts. Pre-bundling them removes the call before StyleX can+// inline var(--lobe-*) and the media queries.+export const stylexTokenModules = [+ '@lobehub/ui/stylex/cssVar.stylex',+ '@lobehub/ui/stylex/media.stylex',+] as const;++const classNamePrefix = 'lh';++export interface StylexPluginOptions {+ overlaySrcDirs?: string[];+}++// A host repo that overlays this one resolves `@/*` to its own src before ours,+// so StyleX must try the same directories in the same order to find its+// `.stylex.ts` files.+export const stylexAliases = (overlaySrcDirs: string[] = []) => {+ const srcDirs = [...new Set([...overlaySrcDirs, path.join(repoRoot, 'src')])];+ return { '@/*': srcDirs.map((dir) => path.join(dir, '*')) };+};++export function stylexPlugin({ overlaySrcDirs }: StylexPluginOptions = {}): PluginOption {+ const entryCss = createStylexEntryCss(classNamePrefix);+ const plugin = stylex({+ aliases: stylexAliases(overlaySrcDirs),+ classNamePrefix,+ cssInjectionTarget: entryCss.cssInjectionTarget,+ dev: !isTest && process.env.NODE_ENV !== 'production',+ // Keep :dir() and logical properties. lightningcss would otherwise rewrite them+ // for the default browserslist and break StyleX RTL rules.+ lightningcssOptions: {+ exclude: 4 | 524_288,+ },+ runtimeInjection: isTest,+ test: isTest,+ unstable_moduleResolution: {+ rootDir: repoRoot,+ type: 'commonJS',+ },+ });++ const plugins = (Array.isArray(plugin) ? plugin : [plugin]) as Array<{+ config?: unknown;+ configureServer?: unknown;+ }>;+ for (const item of plugins) {+ // @lobehub/ui depends on @stylexjs/stylex but ships precompiled CSS. This hook+ // would pull that package out of dependency pre-bundling.+ delete item.config;+ // The unplugin polls a shared CSS store from configureServer and keeps Vitest's+ // Vite server alive after the run.+ if (isTest) delete item.configureServer;+ }++ const [locateEntryCss, verifyEntryCss] = entryCss.plugins;+ return [locateEntryCss, ...plugins, verifyEntryCss, stylexProxiedDevCssPlugin()] as PluginOption;+}++/**+ * stylexPlugin for a package's own Vitest config. Vitest hands node_modules to+ * Node untransformed, and the token modules are uncompiled defineConsts calls+ * that throw at runtime, so they are inlined into the Vite transform instead.+ */+export function stylexPluginForVitest(): PluginOption {+ return [+ stylexPlugin(),+ {+ // `test` is declared by Vitest's augmentation of its own Vite copy, which a+ // host repo on another Vitest major does not see.+ config: () =>+ ({+ test: { server: { deps: { inline: [/@lobehub[/\\]ui[/\\]es[/\\]stylex[/\\]/] } } },+ }) as UserConfig,+ name: 'lobe-stylex-vitest-deps',+ },+ ];+}diff --git a/plugins/vite/stylexDevCss.test.ts b/plugins/vite/stylexDevCss.test.tsnew file mode 100644index 00000000000..bc385c741cc--- /dev/null+++ b/plugins/vite/stylexDevCss.test.ts@@ -0,0 +1,98 @@+import { readFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import path from 'node:path';++import type { Plugin } from 'vite';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ stylexDevCssPath,+ stylexDevRuntimeId,+ stylexProxiedDevCssModuleId,+ stylexProxiedDevCssPlugin,+} from './stylexDevCss';++const viteOrigin = 'http://localhost:9876';++const loadShim = () => {+ const plugin = stylexProxiedDevCssPlugin() as Plugin & {+ load: (id: string) => string | undefined;+ resolveId: (id: string) => string | undefined;+ };+ const code = plugin.load(String(plugin.resolveId(stylexProxiedDevCssModuleId)));+ if (!code) throw new Error('missing stylex dev css shim');+ return code;+};++// Runs the shim as the browser would after loading it from the Vite origin.+const runShim = () => {+ const meta = { url: `${viteOrigin}/@id/__x00__${stylexProxiedDevCssModuleId}` };+ new Function('__meta', loadShim().replaceAll('import.meta', '__meta'))(meta);+};++describe('stylexProxiedDevCssPlugin', () => {+ let link: HTMLLinkElement;++ beforeEach(() => {+ link = document.createElement('link');+ link.rel = 'stylesheet';+ link.href = `${viteOrigin}${stylexDevCssPath}`;+ document.head.append(link);+ });++ afterEach(() => {+ document.head.innerHTML = '';+ vi.unstubAllGlobals();+ });++ it('loads dev CSS from the Vite origin, not the proxied document origin', async () => {+ const fetchMock = vi.fn(+ async () => new Response('.lh1{color:red}', { headers: { 'content-type': 'text/css' } }),+ );+ vi.stubGlobal('fetch', fetchMock);++ runShim();++ await vi.waitFor(() => expect(link.disabled).toBe(true));+ expect(String(fetchMock.mock.calls[0][0])).toMatch(+ new RegExp(`^${viteOrigin}${stylexDevCssPath}\\?t=\\d+$`),+ );+ expect(document.querySelector('style')?.textContent).toBe('.lh1{color:red}');+ });++ it('keeps the stylesheet link when the response is not CSS', async () => {+ const fetchMock = vi.fn(+ async () => new Response('<html></html>', { headers: { 'content-type': 'text/html' } }),+ );+ vi.stubGlobal('fetch', fetchMock);++ runShim();++ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalled());+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(link.disabled).toBeFalsy();+ expect(document.querySelector('style')).toBeNull();+ });+});++describe('@stylexjs/unplugin dev internals', () => {+ const unpluginLib = path.dirname(+ createRequire(import.meta.url).resolve('@stylexjs/unplugin/vite'),+ );+ const consts = createRequire(import.meta.url)(path.join(unpluginLib, 'consts.js')) as {+ DEV_CSS_PATH: string;+ VIRTUAL_STYLEX_RUNTIME_SCRIPT: string;+ };++ it('still match what the mirrored shim relies on', () => {+ const shim = loadShim();+ const viteHooks = readFileSync(path.join(unpluginLib, 'vite.js'), 'utf8');++ expect(consts.DEV_CSS_PATH).toBe(stylexDevCssPath);+ expect(viteHooks).toContain(`'/@id/${stylexDevRuntimeId}'`);+ for (const internal of ["'__stylex_virtual__'", "'stylex:css-update'"]) {+ expect(consts.VIRTUAL_STYLEX_RUNTIME_SCRIPT).toContain(internal);+ expect(shim).toContain(internal.replaceAll("'", '"'));+ }+ });+});diff --git a/plugins/vite/stylexDevCss.ts b/plugins/vite/stylexDevCss.tsnew file mode 100644index 00000000000..58afc81594f--- /dev/null+++ b/plugins/vite/stylexDevCss.ts@@ -0,0 +1,84 @@+import type { Plugin } from 'vite';++// Private internals of @stylexjs/unplugin (lib/consts.js and lib/vite.js), pinned+// at 0.19.1. The package exports no subpath for them, so they are mirrored here and+// stylexDevCss.test.ts reads the installed unplugin to fail on drift. Re-check the+// shim below whenever the unplugin version changes.+export const stylexDevCssPath = '/virtual:stylex.css';+export const stylexDevRuntimeId = 'virtual:stylex:runtime';+const stylexDevStyleId = '__stylex_virtual__';+const stylexCssUpdateEvent = 'stylex:css-update';++// Kept dependency-free: the Next dev HTML rewriter (src/libs/spaHtml) imports it.+export const stylexProxiedDevCssModuleId = 'virtual:lobe-stylex-dev-css';++// The proxied SPA's document origin is Next. A root-relative fetch of+// /virtual:stylex.css never reaches Vite, and the unplugin runtime then disables+// the stylesheet link that does. This module is served by Vite, so import.meta.url+// stays on that origin.+const stylexProxiedDevCssShim = `+const STYLE_ID = ${JSON.stringify(stylexDevStyleId)};+const DEV_CSS_PATH = ${JSON.stringify(stylexDevCssPath)};+const AFTER_UPDATE_DELAY = 180;+let lastCSS = '';++function ensure() {+ let el = document.getElementById(STYLE_ID);+ if (!el) {+ el = document.createElement('style');+ el.id = STYLE_ID;+ document.head.appendChild(el);+ }+ return el;+}++function disableLink() {+ for (const link of document.querySelectorAll('link[rel="stylesheet"]')) {+ if (typeof link.href === 'string' && link.href.includes(DEV_CSS_PATH)) {+ link.disabled = true;+ }+ }+}++function cssHref() {+ const moduleUrl = import.meta.url;+ const origin = moduleUrl.slice(0, moduleUrl.indexOf('/', moduleUrl.indexOf('//') + 2));+ return origin + DEV_CSS_PATH;+}++async function update() {+ try {+ const response = await fetch(cssHref() + '?t=' + Date.now(), { cache: 'no-store' });+ const type = response.headers.get('content-type') || '';+ if (!response.ok || !type.includes('text/css')) return;+ const css = await response.text();+ if (!css || css === lastCSS) return;+ ensure().textContent = css;+ disableLink();+ lastCSS = css;+ } catch (error) {+ console.error(error);+ }+}++update();++if (import.meta.hot) {+ import.meta.hot.on(${JSON.stringify(stylexCssUpdateEvent)}, update);+ import.meta.hot.on('vite:afterUpdate', () => setTimeout(update, AFTER_UPDATE_DELAY));+}+`;++export function stylexProxiedDevCssPlugin(): Plugin {+ const resolvedId = `\0${stylexProxiedDevCssModuleId}`;+ return {+ apply: 'serve',+ load(id) {+ if (id === resolvedId) return stylexProxiedDevCssShim;+ },+ name: 'lobe-stylex-dev-css',+ resolveId(id) {+ if (id === stylexProxiedDevCssModuleId || id === resolvedId) return resolvedId;+ },+ };+}diff --git a/plugins/vite/stylexEntryCss.test.ts b/plugins/vite/stylexEntryCss.test.tsnew file mode 100644index 00000000000..d44d9d96fcc--- /dev/null+++ b/plugins/vite/stylexEntryCss.test.ts@@ -0,0 +1,120 @@+import type { Plugin } from 'vite';+import { describe, expect, it } from 'vitest';++import { createStylexEntryCss, stylexAnchorMarker } from './stylexEntryCss';++const chunk = (+ fileName: string,+ importedCss: string[],+ options: Partial<{ imports: string[]; isEntry: boolean }> = {},+) => ({+ fileName,+ imports: options.imports ?? [],+ isEntry: options.isEntry ?? false,+ type: 'chunk' as const,+ viteMetadata: { importedCss: new Set(importedCss) },+});+const asset = (fileName: string, source: string) => ({ fileName, source, type: 'asset' as const });+const toBundle = (...items: Array<{ fileName: string }>) =>+ Object.fromEntries(items.map((item) => [item.fileName, item]));++const anchor = `:root{${stylexAnchorMarker}:1}`;+const rule = '.lh1abcd:not(#\\#){color:red}';++const run = (plugin: Plugin, bundle: Record<string, unknown>) => {+ const hook = plugin.generateBundle as { handler: (...args: unknown[]) => void; order: string };+ hook.handler.call(+ {+ error: (message: string) => {+ throw new Error(message);+ },+ },+ {},+ bundle,+ false,+ );+};++describe('createStylexEntryCss', () => {+ it('locates the anchor before the enforce: pre unplugin reads the target', () => {+ const { plugins } = createStylexEntryCss('lh');+ expect((plugins[0].generateBundle as { order: string }).order).toBe('pre');+ expect((plugins[1].generateBundle as { order: string }).order).toBe('post');+ });++ it('runs only in client environments, not in an SSR build', () => {+ const { plugins } = createStylexEntryCss('lh');+ for (const plugin of plugins) {+ const applies = plugin.applyToEnvironment as (env: unknown) => boolean;+ expect(applies({ config: { consumer: 'client' } })).toBe(true);+ expect(applies({ config: { consumer: 'server' } })).toBe(false);+ }+ });++ it('targets the CSS carrying the stylex.css marker, not a lazy index chunk', () => {+ const { cssInjectionTarget, plugins } = createStylexEntryCss('lh');+ run(+ plugins[0],+ toBundle(+ asset('assets/index-lazy1234.css', '.lazy{}'),+ asset('assets/initial-main_popup-1.css', anchor),+ ),+ );++ expect(cssInjectionTarget('assets/initial-main_popup-1.css')).toBe(true);+ expect(cssInjectionTarget('assets/index-lazy1234.css')).toBe(false);+ });++ it('accepts rules in anchor CSS that loads through a shared initial chunk', () => {+ const { plugins } = createStylexEntryCss('lh');+ const bundle = toBundle(+ chunk('assets/main.js', [], { imports: ['assets/initial.js'], isEntry: true }),+ chunk('assets/initial.js', ['assets/initial.css']),+ asset('assets/initial.css', `${anchor}\n${rule}`),+ );++ expect(() => run(plugins[1], bundle)).not.toThrow();+ });++ it('fails when the rules land in a lazy chunk CSS', () => {+ const { plugins } = createStylexEntryCss('lh');+ const bundle = toBundle(+ chunk('assets/main.js', ['assets/main.css'], { isEntry: true }),+ asset('assets/main.css', anchor),+ asset('assets/TextLayer-1.css', rule),+ );++ expect(() => run(plugins[1], bundle)).toThrow('rules found in assets/TextLayer-1.css');+ });++ it('fails when the anchor CSS only loads with a lazy route', () => {+ const { plugins } = createStylexEntryCss('lh');+ const bundle = toBundle(+ chunk('assets/main.js', [], { isEntry: true }),+ chunk('assets/lazy.js', ['assets/lazy.css']),+ asset('assets/lazy.css', `${anchor}\n${rule}`),+ );++ expect(() => run(plugins[1], bundle)).toThrow('assets/lazy.css does not load with any entry');+ });++ it('fails when no CSS carries the marker', () => {+ const { plugins } = createStylexEntryCss('lh');+ const bundle = toBundle(+ chunk('assets/main.js', ['assets/style.css'], { isEntry: true }),+ asset('assets/style.css', rule),+ );++ expect(() => run(plugins[1], bundle)).toThrow(`no CSS asset carries ${stylexAnchorMarker}`);+ });++ it('ignores builds without StyleX rules', () => {+ const { plugins } = createStylexEntryCss('lh');+ const bundle = toBundle(+ chunk('assets/main.js', [], { isEntry: true }),+ asset('assets/style.css', '.lhs{color:red}'),+ );++ expect(() => run(plugins[1], bundle)).not.toThrow();+ });+});diff --git a/plugins/vite/stylexEntryCss.ts b/plugins/vite/stylexEntryCss.tsnew file mode 100644index 00000000000..2da7492123e--- /dev/null+++ b/plugins/vite/stylexEntryCss.ts@@ -0,0 +1,107 @@+import type { Plugin } from 'vite';++type BundleItem = {+ fileName: string;+ imports?: string[];+ isEntry?: boolean;+ source?: string | Uint8Array;+ type: 'asset' | 'chunk';+ viteMetadata?: { importedCss?: Set<string> };+};+type Bundle = Record<string, BundleItem>;++/** Declared in src/styles/stylex.css, which the SPA bootstrap imports. */+export const stylexAnchorMarker = '--lh-stylex';++const readSource = (item: BundleItem) =>+ typeof item.source === 'string' ? item.source : new TextDecoder().decode(item.source);++const cssAssets = (bundle: Bundle) =>+ Object.values(bundle).filter((item) => item.type === 'asset' && item.fileName.endsWith('.css'));++const findAnchorCss = (bundle: Bundle) =>+ cssAssets(bundle).find((item) => readSource(item).includes(stylexAnchorMarker))?.fileName;++/** CSS that loads with some entry through static imports, i.e. before any lazy route. */+const collectInitialCss = (bundle: Bundle) => {+ const css = new Set<string>();+ const seen = new Set<string>();+ const queue = Object.values(bundle).filter((item) => item.type === 'chunk' && item.isEntry);+ for (let chunk = queue.shift(); chunk; chunk = queue.shift()) {+ if (seen.has(chunk.fileName)) continue;+ seen.add(chunk.fileName);+ for (const file of chunk.viteMetadata?.importedCss ?? []) css.add(file);+ for (const file of chunk.imports ?? []) {+ const next = bundle[file];+ if (next?.type === 'chunk') queue.push(next);+ }+ }+ return css;+};++/**+ * The unplugin appends all compiled StyleX CSS to one bundle asset, picked by file+ * name (`index-*.css`, then `style-*.css`, then the first CSS asset). Neither name+ * is guaranteed to load at boot: the desktop renderer has no `index-*.css` and the+ * rules landed in the lazy PDF TextLayer CSS. This pins the target to the CSS that+ * carries the src/styles/stylex.css marker, and fails the build when the rules end+ * up anywhere else or that CSS does not load with an entry.+ */+// Only the browser loads this CSS. An SSR environment (React Router apps) emits+// its own server-side CSS asset that no page links.+const isClientEnvironment = (environment: { config: { consumer: string } }) =>+ environment.config.consumer === 'client';++export function createStylexEntryCss(classNamePrefix: string) {+ let anchorCss: string | undefined;+ const stylexRule = new RegExp(String.raw`\.${classNamePrefix}[\da-z]{4,}[\s,.:{]`);++ // The unplugin reads cssInjectionTarget in a plain generateBundle and is+ // enforce: 'pre', so plugin order cannot put this first; hook order 'pre' does.+ const locate: Plugin = {+ apply: 'build',+ applyToEnvironment: isClientEnvironment,+ generateBundle: {+ handler(_options, bundle) {+ anchorCss = findAnchorCss(bundle as unknown as Bundle);+ },+ order: 'pre',+ },+ name: 'lobe-stylex-entry-css',+ };++ const verify: Plugin = {+ apply: 'build',+ applyToEnvironment: isClientEnvironment,+ generateBundle: {+ handler(_options, output) {+ const bundle = output as unknown as Bundle;+ const withRules = cssAssets(bundle).filter((item) => stylexRule.test(readSource(item)));+ if (withRules.length === 0) return;++ // The unplugin re-emits the target under a new hash, so look it up again+ // instead of reusing the name seen before it ran.+ const finalAnchor = findAnchorCss(bundle);+ const problems: string[] = [];+ if (!finalAnchor) problems.push(`no CSS asset carries ${stylexAnchorMarker}`);+ else if (!collectInitialCss(bundle).has(finalAnchor))+ problems.push(`${finalAnchor} does not load with any entry`);+ const misplaced = withRules.filter((item) => item.fileName !== finalAnchor);+ if (misplaced.length > 0)+ problems.push(`rules found in ${misplaced.map((item) => item.fileName).join(', ')}`);++ if (problems.length > 0)+ this.error(+ `StyleX CSS must be in the boot CSS that imports src/styles/stylex.css: ${problems.join('; ')}`,+ );+ },+ order: 'post',+ },+ name: 'lobe-stylex-entry-css-verify',+ };++ return {+ cssInjectionTarget: (fileName: string) => fileName === anchorCss,+ plugins: [locate, verify],+ };+}diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex a1186620116..df109100c32 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -62,7 +62,7 @@ allowBuilds:workerd: trueoverrides:- '@lobehub/ui': ^6.0.4+ '@lobehub/ui': ^6.1.0'@lobehub/icons': ^6.0.0'@lobehub/editor': ^5.0.0'@lobehub/charts': ^6.0.0diff --git a/scripts/stylexMigration/baseline.test.ts b/scripts/stylexMigration/baseline.test.tsnew file mode 100644index 00000000000..847cacd9dd6--- /dev/null+++ b/scripts/stylexMigration/baseline.test.ts@@ -0,0 +1,46 @@+// @vitest-environment node+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { measureBuild } from './baseline';++let dir: string;++const write = (file: string, content: string) => {+ mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });+ writeFileSync(path.join(dir, file), content);+};++afterEach(() => rmSync(dir, { force: true, recursive: true }));++describe('measureBuild', () => {+ it('counts only the assets the HTML loads, under either asset base', () => {+ dir = mkdtempSync(path.join(tmpdir(), 'stylex-baseline-'));+ write('assets/entry.js', 'a'.repeat(100));+ write('vendor/react.js', 'b'.repeat(50));+ write('assets/lazy.js', 'c'.repeat(1000));+ write('assets/entry.css', ':root{--lh-stylex:1}.lh1abcd{color:red}.lh2efgh:not(#\\#){top:0}');+ write(+ 'apps/desktop/index.html',+ [+ '<script type="module" src="/assets/entry.js"></script>',+ '<link rel="modulepreload" href="/_spa/vendor/react.js">',+ '<link rel="modulepreload" href="/assets/entry.js">',+ '<link rel="stylesheet" href="/assets/entry.css">',+ ].join(''),+ );++ const build = measureBuild(dir, 'apps/desktop/index.html');++ expect(build.initialJs.map((s) => [s.file, s.raw])).toEqual([+ ['assets/entry.js', 100],+ ['vendor/react.js', 50],+ ]);+ expect(build.initialCss.map((s) => s.file)).toEqual(['assets/entry.css']);+ expect(build.allJs.raw).toBe(1150);+ expect(build.stylexRules).toBe(2);+ });+});diff --git a/scripts/stylexMigration/baseline.ts b/scripts/stylexMigration/baseline.tsnew file mode 100644index 00000000000..0d8a75fd09a--- /dev/null+++ b/scripts/stylexMigration/baseline.ts@@ -0,0 +1,107 @@+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import path from 'node:path';+import { gzipSync } from 'node:zlib';++import { type FileReport } from '.';++export interface AssetSize {+ file: string;+ gzip: number;+ raw: number;+}++export interface BuildBaseline {+ allCss: { gzip: number; raw: number };+ allJs: { gzip: number; raw: number };+ initialCss: AssetSize[];+ initialJs: AssetSize[];+ stylexRules: number;+}++const sizeOf = (file: string, buffer: Buffer): AssetSize => ({+ file,+ gzip: gzipSync(buffer).length,+ raw: buffer.length,+});++const walk = (dir: string): string[] =>+ readdirSync(dir).flatMap((name) => {+ const full = path.join(dir, name);+ return statSync(full).isDirectory() ? walk(full) : [full];+ });++const sum = (sizes: AssetSize[]) =>+ sizes.reduce((acc, s) => ({ gzip: acc.gzip + s.gzip, raw: acc.raw + s.raw }), {+ gzip: 0,+ raw: 0,+ });++/** Assets the SPA HTML loads before any lazy route: the entry, modulepreloads, CSS. */+export const measureBuild = (+ distDir: string,+ htmlFile = 'index.html',+ classNamePrefix = 'lh',+): BuildBaseline => {+ const html = readFileSync(path.join(distDir, htmlFile), 'utf8');+ // Web serves assets under its base (/_spa/assets/β¦), desktop from the root (/assets/β¦).+ const resolveRef = (ref: string) =>+ [ref.replace(/^\//, ''), ref.replace(/^\/[^/]+\//, '')].find((file) =>+ existsSync(path.join(distDir, file)),+ ) ?? ref;+ const refs = (pattern: RegExp) => [+ ...new Set([...html.matchAll(pattern)].map((match) => resolveRef(match[1]))),+ ];+ const read = (file: string) => sizeOf(file, readFileSync(path.join(distDir, file)));++ const initialJs = refs(/<(?:script|link)[^>]+(?:src|href)="([^"]+\.js)"/g).map(read);+ const initialCss = refs(/<link[^>]+rel="stylesheet"[^>]+href="([^"]+\.css)"/g).map(read);++ const files = walk(distDir);+ const measureAll = (ext: string) =>+ sum(files.filter((f) => f.endsWith(ext)).map((f) => sizeOf(f, readFileSync(f))));++ const stylexRule = new RegExp(String.raw`\.${classNamePrefix}[\da-z]{4,}[\s,.:{]`, 'g');+ const stylexRules = initialCss.reduce(+ (count, css) =>+ count + (readFileSync(path.join(distDir, css.file), 'utf8').match(stylexRule)?.length ?? 0),+ 0,+ );++ return {+ allCss: measureAll('.css'),+ allJs: measureAll('.js'),+ initialCss,+ initialJs,+ stylexRules,+ };+};++const kb = (bytes: number) => `${(bytes / 1024).toFixed(1)} KB`;++export const formatBaseline = (build: BuildBaseline, reports: FileReport[], distDir: string) => {+ const initialJs = sum(build.initialJs);+ const initialCss = sum(build.initialCss);+ const tiers = { A: 0, B: 0, C: 0, D: 0 };+ for (const r of reports) tiers[r.tier]++;+ const blocks = reports.reduce((n, r) => n + r.blocks, 0);++ return [+ `## StyleX migration baseline β ${distDir}`,+ '',+ '| metric | raw | gzip |',+ '| --- | --- | --- |',+ `| initial JS (${build.initialJs.length} files) | ${kb(initialJs.raw)} | ${kb(initialJs.gzip)} |`,+ `| initial CSS (${build.initialCss.length} files) | ${kb(initialCss.raw)} | ${kb(initialCss.gzip)} |`,+ `| all JS | ${kb(build.allJs.raw)} | ${kb(build.allJs.gzip)} |`,+ `| all CSS | ${kb(build.allCss.raw)} | ${kb(build.allCss.gzip)} |`,+ '',+ `- StyleX rules in initial CSS: ${build.stylexRules}`,+ `- Emotion style files: ${reports.length} (A ${tiers.A} Β· B ${tiers.B} Β· C ${tiers.C} Β· D ${tiers.D}), css\`\` blocks: ${blocks}`,+ '',+ '| initial JS file | raw | gzip |',+ '| --- | --- | --- |',+ ...build.initialJs+ .toSorted((a, b) => b.raw - a.raw)+ .map((s) => `| ${s.file} | ${kb(s.raw)} | ${kb(s.gzip)} |`),+ ].join('\n');+};diff --git a/scripts/stylexMigration/classify.test.ts b/scripts/stylexMigration/classify.test.tsnew file mode 100644index 00000000000..ce4914707e2--- /dev/null+++ b/scripts/stylexMigration/classify.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest';++import { classifySelector, classifySource, findLegacyImports } from './classify';++const file = (body: string) => `+import { createStaticStyles, cx, Flexbox } from '@lobehub/ui';++const styles = createStaticStyles(({ css, cssVar }) => ({+ root: css\`+${body}+ \`,+}));+`;++describe('classifySelector', () => {+ it.each([+ ['@media (max-width: 575px)', 'media'],+ ['@container (max-width: 300px)', 'media'],+ ['&:hover', 'pseudo'],+ ['&::before', 'pseudo'],+ ["&[data-active='true']:hover", 'pseudo'],+ ['&:not(:last-child)', 'pseudo'],+ ['.parent:hover &', 'ancestor'],+ ['& .child', 'descendant'],+ ['&:hover .X-action', 'descendant'],+ ['#lobe-mobile-scroll-container', 'descendant'],+ ['::-webkit-scrollbar', 'descendant'],+ ['li[aria-current="page"]', 'third-party'],+ ['& svg', 'third-party'],+ ['.ant-switch', 'third-party'],+ ['.anticon', 'third-party'],+ ['.ProseMirror p', 'third-party'],+ ['&:hover, & .child', 'descendant'],+ ['from', 'keyframe-step'],+ ])('%s β %s', (selector, kind) => {+ expect(classifySelector(selector)).toBe(kind);+ });+});++describe('classifySource', () => {+ it('puts flat declarations with cssVar and media queries in tier A', () => {+ const report = classifySource(+ file(`+ color: \${cssVar.colorText};+ \${responsive.sm} {+ font-size: 14px;+ }`),+ );+ expect(report).toMatchObject({ blocks: 1, legacyImports: ['createStaticStyles'], tier: 'A' });+ });++ it('puts self pseudo-classes in tier B', () => {+ expect(classifySource(file('&:hover { color: red; }')).tier).toBe('B');+ });++ it('puts descendant coupling in tier C', () => {+ expect(classifySource(file('&:hover .action { opacity: 1; }')).tier).toBe('C');+ });++ it('puts tag and third-party selectors in tier D, even next to simpler ones', () => {+ expect(classifySource(file('&:hover { color: red; }\n & svg { width: 12px; }')).tier).toBe(+ 'D',+ );+ });++ it('ignores selector-looking text outside css blocks', () => {+ const source = `${file('color: red;')}\nconst key = 'builtins.lobe-task.count';`;+ expect(classifySource(source).tier).toBe('A');+ });+});++describe('findLegacyImports', () => {+ it('finds emotion style imports, including aliased and multi-line ones', () => {+ const source = `+import {+ Block,+ createStaticStyles as create,+ keyframes,+} from '@lobehub/ui';+import { css } from 'other-lib';+`;+ expect(findLegacyImports(source)).toEqual(['createStaticStyles', 'keyframes']);+ });++ it('ignores files that only use cx or components', () => {+ expect(findLegacyImports("import { cx, Flexbox } from '@lobehub/ui';")).toEqual([]);+ });+});diff --git a/scripts/stylexMigration/classify.ts b/scripts/stylexMigration/classify.tsnew file mode 100644index 00000000000..d57a9ab97b4--- /dev/null+++ b/scripts/stylexMigration/classify.ts@@ -0,0 +1,109 @@+/**+ * Static classification of emotion-based style code for the StyleX migration.+ *+ * Tiers, by the hardest nested selector in a file's css`` blocks:+ * - A: flat declarations, cssVar and @media / @container only β codemod+ * - B: pseudo-classes / attributes on the element itself (`&:hover`) β codemod+ * - C: descendant or ancestor coupling (`& .child`, `.parent:hover &`) β manual,+ * stylex.defaultMarker() / stylex.when.ancestor() or an xstyle prop+ * - D: tag or third-party DOM selectors (`li`, `svg`, `.ProseMirror`) β scoped CSS+ */++import legacyImports from './legacyImports.json';++export type MigrationTier = 'A' | 'B' | 'C' | 'D';++export type SelectorKind =+ 'ancestor' | 'at-rule' | 'descendant' | 'keyframe-step' | 'media' | 'pseudo' | 'third-party';++export interface StyleFileReport {+ blocks: number;+ kinds: SelectorKind[];+ legacyImports: string[];+ tier: MigrationTier;+}++/** @lobehub/ui exports backed by the emotion runtime that new code must not use. */+export const LEGACY_STYLE_IMPORTS: readonly string[] = legacyImports;++const THIRD_PARTY =+ /\.ant(?:-|icon)|\.lobe-|:global|\.cm-|ProseMirror|\.markdown|\.katex|\.shiki|\[class|\.(?:rc|monaco|xterm|react-flow|tiptap)/;+const TAG =+ /(?:^|[\s(+,>~])(?:a|blockquote|button|canvas|code|div|em|h[1-6]|hr|iframe|img|input|label|li|ol|p|path|pre|span|strong|svg|table|tbody|td|textarea|th|thead|tr|ul|video)(?=$|[\s#),.:>[+~])/;+const SELF = /^&(?::{1,2}[\w-]+(?:\([^)]*\))?|\[[^\]]+\])*$/;+const ANCESTOR = /^[^&]+&(?::{1,2}[\w-]+|\[[^\]]+\])*$/;++const RANK: Record<SelectorKind, number> = {+ 'ancestor': 1,+ 'at-rule': 0,+ 'descendant': 2,+ 'keyframe-step': 0,+ 'media': 0,+ 'pseudo': 0,+ 'third-party': 3,+};++export const classifySelector = (selector: string): SelectorKind => {+ const sel = selector.trim();+ if (/^@(?:media|container|supports)/.test(sel)) return 'media';+ if (sel.startsWith('@')) return 'at-rule';+ if (/^(?:from|to|\d+%)/.test(sel)) return 'keyframe-step';++ let worst: SelectorKind = 'pseudo';+ for (const part of sel.split(',').map((p) => p.trim())) {+ let kind: SelectorKind;+ if (THIRD_PARTY.test(part)) kind = 'third-party';+ else if (SELF.test(part)) kind = 'pseudo';+ else if (ANCESTOR.test(part)) kind = 'ancestor';+ else kind = TAG.test(part.replaceAll('&', ' ')) ? 'third-party' : 'descendant';+ if (RANK[kind] > RANK[worst]) worst = kind;+ }+ return worst;+};++/** css`` bodies with `${responsive.*}` as @media, other interpolations as `X`, no comments. */+export const extractCssBlocks = (source: string) =>+ (source.match(/css`[\S\s]*?`/g) ?? []).map((block) =>+ block+ .slice(4, -1)+ .replaceAll(/\$\{\s*responsive\.\w+\s*\}/g, '@media X')+ .replaceAll(/\$\{[^}]*\}/g, 'X')+ .replaceAll(/\/\*[\S\s]*?\*\//g, '')+ .replaceAll(/^\s*\/\/.*$/gm, ''),+ );++export const findLegacyImports = (source: string) => {+ const names = new Set<string>();+ for (const match of source.matchAll(/import\s*\{([^}]*)\}\s*from\s*["']@lobehub\/ui["']/g)) {+ for (const spec of match[1].split(',')) {+ const name = spec+ .trim()+ .replace(/^type\s+/, '')+ .split(/\s+as\s+/)[0];+ if (LEGACY_STYLE_IMPORTS.includes(name)) names.add(name);+ }+ }+ return [...names].sort();+};++export const classifySource = (source: string): StyleFileReport => {+ const blocks = extractCssBlocks(source);+ const kinds = new Set<SelectorKind>();+ for (const block of blocks) {+ for (const match of block.matchAll(/([^;{}]+)\{/g)) {+ kinds.add(classifySelector(match[1]));+ }+ }++ let tier: MigrationTier = 'A';+ if (kinds.has('third-party')) tier = 'D';+ else if (kinds.has('descendant') || kinds.has('ancestor')) tier = 'C';+ else if (kinds.has('pseudo')) tier = 'B';++ return {+ blocks: blocks.length,+ kinds: [...kinds].sort(),+ legacyImports: findLegacyImports(source),+ tier,+ };+};diff --git a/scripts/stylexMigration/codemod/css.test.ts b/scripts/stylexMigration/codemod/css.test.tsnew file mode 100644index 00000000000..0dd12d2d6f2--- /dev/null+++ b/scripts/stylexMigration/codemod/css.test.ts@@ -0,0 +1,317 @@+import { describe, expect, it } from 'vitest';++import { convertCss, expandShorthand, isShorthandOf, UnsupportedCssError } from './css';++const names = { cssVar: new Set(['cssVar', 'cv']), responsive: new Set(['responsive']) };++/**+ * Builds a CssTemplate from a template literal, like the transform does. Not+ * named `block`: stylelint --fix would reorder the fixtures' declarations.+ */+const block = (strings: TemplateStringsArray, ...expressions: string[]) =>+ convertCss({ expressions, quasis: [...strings.raw] }, names);++const object = (code: string) =>+ new Function('cssVar', 'media', `return (${code});`)(+ new Proxy({}, { get: (_t, k) => `cssVar.${String(k)}` }),+ new Proxy({}, { get: (_t, k) => `media.${String(k)}` }),+ );++describe('convertCss', () => {+ it('converts declarations, tokens and numeric values', () => {+ const result = block`+ --local-size: 12px;++ display: flex;+ -webkit-line-clamp: 2;++ font-weight: 500;+ line-height: 1.2;+ color: ${'cssVar.colorText'};++ box-shadow: 0 0 0 1px ${'cv.colorBorder'};+ `;++ expect(result).toMatchObject({ usesCssVar: true, usesMedia: false });+ expect(object(result.code)).toEqual({+ '--local-size': '12px',+ 'WebkitLineClamp': '2',+ 'boxShadow': '0 0 0 1px cssVar.colorBorder',+ 'color': 'cssVar.colorText',+ 'display': 'flex',+ 'fontWeight': 500,+ 'lineHeight': 1.2,+ });+ });++ it('nests pseudo-classes and media queries as conditions', () => {+ const result = block`+ color: red;++ &:hover {+ color: blue;+ }+ ${'responsive.md'} {+ gap: 8px;+ }+ ${'responsive.sm'} {+ gap: 4px;+ }++ @container (max-width: 300px) {+ &:hover {+ color: green;+ }+ }+ `;++ expect(result.usesMedia).toBe(true);+ expect(object(result.code)).toEqual({+ color: {+ '@container (max-width: 300px)': { ':hover': 'green', 'default': null },+ ':hover': 'blue',+ 'default': 'red',+ },+ gap: { 'default': null, 'media.md': '8px', 'media.sm': '4px' },+ });+ });++ it('moves one pseudo-element into its own style object', () => {+ const result = block`+ position: relative;++ &::after {+ content: '';+ inset: 0;+ }+ `;+ expect(object(result.code)).toEqual({+ '::after': { content: "''", inset: '0' },+ 'position': 'relative',+ });+ });++ it('keeps references to module constants for the StyleX compiler', () => {+ expect(+ object(+ block`+ width: ${'AVATAR_SIZE'}px;+ `.code.replace('AVATAR_SIZE', '40'),+ ),+ ).toEqual({+ width: '40px',+ });+ });++ it.each<[string, () => unknown]>([+ [+ '!important',+ () => block`+ color: red !important;+ `,+ ],+ [+ 'descendant selector',+ () => block`+ & .child {+ color: red;+ }+ `,+ ],+ [+ 'attribute selector',+ () => block`+ &[data-open] {+ color: red;+ }+ `,+ ],+ [+ 'keyframes',+ () => block`+ @keyframes spin {+ from {+ opacity: 0;+ }+ }+ `,+ ],+ [+ 'call interpolation',+ () => block`+ background: ${"imageUrl('a.png')"};+ `,+ ],+ [+ 'hover before disabled',+ () => block`+ &:hover {+ color: red;+ }++ &:disabled {+ color: gray;+ }+ `,+ ],+ [+ 'media before hover',+ () => block`+ ${'responsive.sm'} {+ color: red;+ }++ &:hover {+ color: blue;+ }+ `,+ ],+ [+ 'narrow before wide media',+ () => block`+ ${'responsive.sm'} {+ gap: 1px;+ }+ ${'responsive.md'} {+ gap: 2px;+ }+ `,+ ],+ [+ 'longhand before shorthand',+ () => block`+ padding-inline: 4px;+ padding: 8px;+ `,+ ],+ [+ 'shorthand in another condition',+ () => block`+ padding-inline: 4px;++ &:hover {+ padding: 8px;+ }+ `,+ ],+ ])('rejects %s', (_label, run) => {+ expect(run).toThrow(UnsupportedCssError);+ });++ it('accepts a shorthand followed by its longhand in the same block', () => {+ expect(+ object(+ block`+ padding: 8px;+ padding-inline: 4px;+ `.code,+ ),+ ).toEqual({+ padding: '8px',+ paddingInline: '4px',+ });+ });+});++describe('expandShorthand', () => {+ it.each([+ [+ 'padding',+ '0 8px',+ [+ ['paddingBlock', '0'],+ ['paddingInline', '8px'],+ ],+ ],+ [+ 'margin',+ '1px 2px 3px',+ [+ ['marginTop', '1px'],+ ['marginRight', '2px'],+ ['marginBottom', '3px'],+ ['marginLeft', '2px'],+ ],+ ],+ [+ 'paddingInline',+ '8px 10px',+ [+ ['paddingInlineStart', '8px'],+ ['paddingInlineEnd', '10px'],+ ],+ ],+ [+ 'gap',+ '4px 8px',+ [+ ['rowGap', '4px'],+ ['columnGap', '8px'],+ ],+ ],+ [+ 'overflow',+ 'hidden auto',+ [+ ['overflowX', 'hidden'],+ ['overflowY', 'auto'],+ ],+ ],+ [+ 'flex',+ '1 1 0',+ [+ ['flexGrow', '1'],+ ['flexShrink', '1'],+ ['flexBasis', '0'],+ ],+ ],+ [+ 'flex',+ '0 0 120px',+ [+ ['flexGrow', '0'],+ ['flexShrink', '0'],+ ['flexBasis', '120px'],+ ],+ ],+ [+ 'border',+ '1px solid __lobeX0__',+ [+ ['borderWidth', '1px'],+ ['borderStyle', 'solid'],+ ['borderColor', '__lobeX0__'],+ ],+ ],+ ['borderBlockEnd', 'none', [['borderBlockEndStyle', 'none']]],+ [+ 'borderRadius',+ '4px 8px',+ [+ ['borderTopLeftRadius', '4px'],+ ['borderTopRightRadius', '8px'],+ ['borderBottomRightRadius', '4px'],+ ['borderBottomLeftRadius', '8px'],+ ],+ ],+ ['background', 'rgb(0 0 0 / 50%)', [['background', 'rgb(0 0 0 / 50%)']]],+ ])('%s: %s', (prop, value, expected) => {+ expect(expandShorthand(prop, value)).toEqual(expected);+ });+});++describe('isShorthandOf', () => {+ it.each([+ ['padding', 'paddingInline', true],+ ['paddingInline', 'paddingInlineStart', true],+ ['gap', 'rowGap', true],+ ['inset', 'top', true],+ ['font', 'lineHeight', true],+ ['borderRadius', 'borderTopLeftRadius', true],+ ['border', 'borderRadius', false],+ ['paddingInline', 'padding', false],+ ])('%s β %s: %s', (short, long, expected) => {+ expect(isShorthandOf(short, long)).toBe(expected);+ });+});diff --git a/scripts/stylexMigration/codemod/css.ts b/scripts/stylexMigration/codemod/css.tsnew file mode 100644index 00000000000..8694a862751--- /dev/null+++ b/scripts/stylexMigration/codemod/css.ts@@ -0,0 +1,400 @@+/**+ * Converts the body of one emotion css`` block into a StyleX style object literal.+ *+ * Supported: declarations, `${cssVar.*}` values, `${responsive.*}` and @media /+ * @container / @supports blocks, pseudo-classes on the element itself (`&:hover`,+ * `&:not(:disabled)`), and one pseudo-element (`&::before`). Anything else β+ * descendant or attribute selectors, `!important`, other interpolations β throws+ * an UnsupportedCssError so the caller can leave the file to manual migration.+ */+import postcss, { type ChildNode, type Container } from 'postcss';++export class UnsupportedCssError extends Error {}++export interface CssTemplate {+ /** Source text of each `${β¦}` expression, in order. */+ expressions: string[];+ /** Raw text between the expressions; one more entry than `expressions`. */+ quasis: string[];+}++export interface ConvertedStyle {+ /** JS source of the style object, e.g. `{ color: cssVar.colorText }`. */+ code: string;+ usesCssVar: boolean;+ usesMedia: boolean;+}++/** Identifiers that refer to the token objects inside the css`` callback. */+export interface TokenNames {+ cssVar: Set<string>;+ responsive: Set<string>;+}++const PLACEHOLDER = /__lobeX(\d+)__/g;+const NUMERIC_PROPS = new Set([+ 'flexGrow',+ 'flexShrink',+ 'fontWeight',+ 'lineHeight',+ 'opacity',+ 'order',+ 'zIndex',+]);+const BORDER_STYLES = new Set([+ 'dashed',+ 'dotted',+ 'double',+ 'groove',+ 'hidden',+ 'inset',+ 'none',+ 'outset',+ 'ridge',+ 'solid',+]);++// max-width of each lobe-ui breakpoint; `desktop` / `xxl` are min-width 1200px.+const BREAKPOINT_MAX: Record<string, number> = {+ laptop: 991.98,+ lg: 991.98,+ md: 767.98,+ mobile: 479.98,+ sm: 575.98,+ tablet: 767.98,+ xl: 1199.98,+ xs: 479.98,+};++// Mirrors @stylexjs/babel-plugin 0.19 getPseudoClassPriority: compound keys and+// the table's camelCase entries (`:focusVisible`) fall back to 40.+const PSEUDO_PRIORITY: Record<string, number> = {+ ':active': 170,+ ':checked': 101,+ ':disabled': 92,+ ':empty': 70,+ ':enabled': 91,+ ':first-child': 52,+ ':focus': 150,+ ':hover': 130,+ ':last-child': 54,+ ':placeholder-shown': 97,+ ':visited': 85,+};+const AT_RULE_PRIORITY: Record<string, number> = {+ '@container': 300,+ '@media': 200,+ '@supports': 30,+};++/** Priority of a rendered condition key: `":hover"`, `[media.sm]`, `"@media β¦"`. */+const conditionPriority = (key: string) => {+ if (key.startsWith('[media.')) return AT_RULE_PRIORITY['@media'];+ const raw = JSON.parse(key) as string;+ if (raw.startsWith('@')) return AT_RULE_PRIORITY[raw.split(' ')[0]] ?? 0;+ return PSEUDO_PRIORITY[raw.split('(')[0]] ?? 40;+};++const kebab = (prop: string) =>+ prop.startsWith('--')+ ? prop+ : prop.replaceAll(/[A-Z]/g, (c) => `-${c.toLowerCase()}`).replace(/^(webkit|moz|ms)-/, '-$1-');++/** Longhands a shorthand resets that do not share its name as a prefix. */+const SHORTHAND_EXTRA: [RegExp, RegExp][] = [+ [/^gap$/, /^(row|column)-gap$/],+ [/^inset$/, /^(top|right|bottom|left)$/],+ [/^border-radius$/, /^border-.+-radius$/],+ [/^border-(color|style|width)$/, /^border-.+-(color|style|width)$/],+ [/^border$/, /^border-.+$/],+ [/^font$/, /^line-height$/],+ [/^flex-flow$/, /^flex-(direction|wrap)$/],+ [/^place-(items|content|self)$/, /^(align|justify)-(items|content|self)$/],+];++export const isShorthandOf = (short: string, long: string) => {+ const [s, l] = [kebab(short), kebab(long)];+ if (s === l) return false;+ // `border` does not reset these, despite the shared prefix.+ if (s === 'border' && /-(?:radius|spacing|collapse)$|^border-collapse$/.test(l)) return false;+ if (l.startsWith(`${s}-`)) return true;+ return SHORTHAND_EXTRA.some(([a, b]) => a.test(s) && b.test(l));+};++type ValueNode = { children: Map<string, ValueNode>; value?: string };+type Rendered = { expr: string; usesCssVar: boolean };++const camelCase = (prop: string) =>+ prop.startsWith('--')+ ? prop+ : prop+ .replace(/^-(webkit|moz|ms)-/, (_m, v: string) => `${v[0].toUpperCase()}${v.slice(1)}-`)+ .replaceAll(/-([a-z])/g, (_m, c: string) => c.toUpperCase());++/** Splits on top-level whitespace, keeping parentheses and placeholders intact. */+const tokens = (value: string) => {+ const out: string[] = [];+ let depth = 0;+ let current = '';+ for (const ch of value.trim()) {+ if (ch === '(') depth++;+ if (ch === ')') depth--;+ if (/\s/.test(ch) && depth === 0) {+ if (current) out.push(current);+ current = '';+ } else current += ch;+ }+ if (current) out.push(current);+ return out;+};++const sides = (prefix: string, suffix: string, values: string[]): [string, string][] => {+ const [top, right = top, bottom = top, left = right] = values;+ return [+ [`${prefix}Top${suffix}`, top],+ [`${prefix}Right${suffix}`, right],+ [`${prefix}Bottom${suffix}`, bottom],+ [`${prefix}Left${suffix}`, left],+ ];+};++/** StyleX rejects multi-value shorthands; expand them into longhands it accepts. */+export const expandShorthand = (prop: string, value: string): [string, string][] => {+ const parts = tokens(value);++ if (['margin', 'padding', 'scrollMargin', 'scrollPadding'].includes(prop)) {+ if (parts.length === 1) return [[prop, value]];+ if (parts.length === 2)+ return [+ [`${prop}Block`, parts[0]],+ [`${prop}Inline`, parts[1]],+ ];+ return sides(prop, '', parts);+ }+ if (prop === 'inset') {+ if (parts.length === 1) return [[prop, value]];+ return sides('', '', parts).map(([p, v]) => [p.toLowerCase(), v]);+ }+ if (/^(?:margin|padding|inset|scrollMargin|scrollPadding)(?:Block|Inline)$/.test(prop)) {+ if (parts.length === 1) return [[prop, value]];+ return [+ [`${prop}Start`, parts[0]],+ [`${prop}End`, parts[1]],+ ];+ }+ if (prop === 'gap' && parts.length === 2)+ return [+ ['rowGap', parts[0]],+ ['columnGap', parts[1]],+ ];+ if (prop === 'overflow' && parts.length === 2)+ return [+ ['overflowX', parts[0]],+ ['overflowY', parts[1]],+ ];+ if (prop === 'borderRadius' && parts.length > 1) {+ if (value.includes('/')) throw new UnsupportedCssError(`border-radius: ${value}`);+ const [tl, tr = tl, br = tl, bl = tr] = parts;+ return [+ ['borderTopLeftRadius', tl],+ ['borderTopRightRadius', tr],+ ['borderBottomRightRadius', br],+ ['borderBottomLeftRadius', bl],+ ];+ }+ if (prop === 'flex' && parts.length > 1) {+ const [grow, second, third] = parts;+ const secondIsShrink = /^(?:\d+(?:\.\d+)?|\.\d+)$/.test(second);+ return [+ ['flexGrow', grow],+ ...(secondIsShrink ? [['flexShrink', second] as [string, string]] : []),+ ['flexBasis', secondIsShrink ? (third ?? '0%') : second],+ ];+ }+ if (/^(?:border|outline)(?:(?:Top|Right|Bottom|Left|Block|Inline)(?:Start|End)?)?$/.test(prop)) {+ if (parts.length === 1 && (parts[0] === 'none' || parts[0] === '0'))+ return [[`${prop}Style`, 'none']];+ const result: [string, string][] = [];+ const color: string[] = [];+ for (const part of parts) {+ if (BORDER_STYLES.has(part)) result.push([`${prop}Style`, part]);+ else if (/^(?:\d|\.\d|thin$|medium$|thick$)/.test(part)) result.push([`${prop}Width`, part]);+ else color.push(part);+ }+ if (color.length > 1) throw new UnsupportedCssError(`${prop}: ${value}`);+ if (color.length === 1) result.push([`${prop}Color`, color[0]]);+ return result;+ }+ return [[prop, value]];+};++export const convertCss = (template: CssTemplate, names: TokenNames): ConvertedStyle => {+ let usesCssVar = false;+ let usesMedia = false;++ const exprOf = (index: number) => template.expressions[index].trim();+ const tokenRef = (expr: string, kind: keyof TokenNames) => {+ const match = /^([$A-Z_][\w$]*)\.(\w+)$/i.exec(expr);+ return match && names[kind].has(match[1]) ? match[2] : undefined;+ };++ const renderValue = (prop: string, raw: string): Rendered => {+ const value = raw.trim();+ if (/!important/i.test(value)) throw new UnsupportedCssError(`!important in ${prop}`);+ let cssVarUsed = false;+ let hasInterpolation = false;+ const pieces: string[] = [];+ let last = 0;+ let onlyPlaceholder = false;+ for (const match of value.matchAll(PLACEHOLDER)) {+ const expr = exprOf(Number(match[1]));+ const token = tokenRef(expr, 'cssVar');+ // Other plain references (module constants) are kept for the StyleX+ // compiler to evaluate; the codemod's compile step rejects unresolvable ones.+ if (!token && !/^[$A-Z_][\w$]*(?:\.[\w$]+)*$/i.test(expr))+ throw new UnsupportedCssError(`interpolation \${${expr}}`);+ if (token) cssVarUsed = true;+ hasInterpolation = true;+ pieces.push(value.slice(last, match.index).replaceAll(/[$`\\]/g, String.raw`\$&`));+ pieces.push(token ? `\${cssVar.${token}}` : `\${${expr}}`);+ last = match.index + match[0].length;+ onlyPlaceholder = match.index === 0 && last === value.length;+ }+ if (hasInterpolation) {+ if (onlyPlaceholder) return { expr: pieces[1].slice(2, -1), usesCssVar: cssVarUsed };+ pieces.push(value.slice(last).replaceAll(/[$`\\]/g, String.raw`\$&`));+ return { expr: `\`${pieces.join('')}\``, usesCssVar: cssVarUsed };+ }+ if (NUMERIC_PROPS.has(prop) && /^-?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value))+ return { expr: String(Number(value)), usesCssVar: false };+ return { expr: JSON.stringify(value), usesCssVar: false };+ };++ // prop β condition tree. Pseudo-elements get their own nested style object.+ const roots = new Map<string, Map<string, ValueNode>>();+ const declared: { context: string; prop: string }[] = [];+ const setValue = (pseudoElement: string, conditions: string[], prop: string, value: string) => {+ declared.push({ context: `${pseudoElement}|${conditions.join('|')}`, prop });+ const props = roots.get(pseudoElement) ?? new Map<string, ValueNode>();+ roots.set(pseudoElement, props);+ let node: ValueNode = props.get(prop) ?? { children: new Map() };+ props.set(prop, node);+ for (const condition of conditions) {+ const child: ValueNode = node.children.get(condition) ?? { children: new Map() };+ node.children.set(condition, child);+ node = child;+ }+ node.value = value;+ };++ const walk = (container: Container, conditions: string[], pseudoElement: string) => {+ for (const node of container.nodes ?? []) visit(node, conditions, pseudoElement);+ };++ const visit = (node: ChildNode, conditions: string[], pseudoElement: string) => {+ if (node.type === 'comment') return;+ if (node.type === 'decl') {+ const prop = camelCase(node.prop);+ if (node.important) throw new UnsupportedCssError(`!important in ${node.prop}`);+ for (const [longhand, value] of expandShorthand(prop, node.value)) {+ const rendered = renderValue(longhand, value);+ usesCssVar ||= rendered.usesCssVar;+ setValue(pseudoElement, conditions, longhand, rendered.expr);+ }+ return;+ }+ if (node.type === 'atrule') {+ if (!['container', 'media', 'supports'].includes(node.name))+ throw new UnsupportedCssError(`@${node.name}`);+ if (PLACEHOLDER.test(node.params))+ throw new UnsupportedCssError(`@${node.name} interpolation`);+ PLACEHOLDER.lastIndex = 0;+ walk(node, [...conditions, JSON.stringify(`@${node.name} ${node.params}`)], pseudoElement);+ return;+ }+ if (node.type !== 'rule') return;+ for (const raw of node.selectors) {+ const selector = raw.trim();+ const placeholder = /^__lobeX(\d+)__$/.exec(selector);+ if (placeholder) {+ const breakpoint = tokenRef(exprOf(Number(placeholder[1])), 'responsive');+ if (!breakpoint)+ throw new UnsupportedCssError(`selector \${${exprOf(Number(placeholder[1]))}}`);+ usesMedia = true;+ walk(node, [...conditions, `[media.${breakpoint}]`], pseudoElement);+ continue;+ }+ const match = /^&((?::[\w-]+(?:\([^&]*\))?)*)(::[\w-]+)?$/.exec(selector);+ if (!match || (!match[1] && !match[2])) throw new UnsupportedCssError(`selector ${selector}`);+ const [, pseudoClasses, element] = match;+ if (element && pseudoElement) throw new UnsupportedCssError(`selector ${selector}`);+ const next = pseudoClasses ? [...conditions, JSON.stringify(pseudoClasses)] : conditions;+ walk(node, next, element ?? pseudoElement);+ }+ };++ let css = template.quasis[0];+ for (let i = 0; i < template.expressions.length; i++) {+ css += `__lobeX${i}__${template.quasis[i + 1]}`;+ }+ // Emotion accepts // line comments; postcss does not.+ css = css.replaceAll(/^\s*\/\/.*$/gm, '');++ let root;+ try {+ root = postcss.parse(css);+ } catch (error) {+ throw new UnsupportedCssError(`unparsable css: ${(error as Error).message.split('\n')[0]}`);+ }+ walk(root, [], '');++ // StyleX always lets a longhand beat its shorthand; emotion lets the later rule+ // win. They agree only for shorthand-then-longhand within one condition.+ for (const [i, a] of declared.entries()) {+ for (const b of declared.slice(i + 1)) {+ // a is declared before b.+ const conflict =+ (isShorthandOf(a.prop, b.prop) && a.context !== b.context) || isShorthandOf(b.prop, a.prop);+ if (conflict) throw new UnsupportedCssError(`shorthand conflict: ${a.prop} / ${b.prop}`);+ }+ }++ // StyleX orders conditions by a fixed priority, emotion by source order (later+ // wins). Keep a property only when both agree: priorities rising in source+ // order, and overlapping max-width queries going from wide to narrow.+ const checkConditionOrder = (node: ValueNode) => {+ const keys = [...node.children.keys()];+ if (keys.length < 2) return;+ const priorities = keys.map(conditionPriority);+ for (let i = 1; i < keys.length; i++) {+ const [prev, cur] = [priorities[i - 1], priorities[i]];+ const bothMedia = prev === AT_RULE_PRIORITY['@media'] && cur === prev;+ if (bothMedia) {+ const [a, b] = [keys[i - 1], keys[i]].map((k) => BREAKPOINT_MAX[k.slice(7, -1)]);+ if (a === undefined || b === undefined || b >= a)+ throw new UnsupportedCssError(`overlapping media order: ${keys[i - 1]}, ${keys[i]}`);+ } else if (cur <= prev) {+ throw new UnsupportedCssError(`condition order: ${keys[i - 1]} before ${keys[i]}`);+ }+ }+ };++ const renderNode = (node: ValueNode): string => {+ checkConditionOrder(node);+ if (node.children.size === 0) return node.value ?? 'null';+ const entries = [`default: ${node.value ?? 'null'}`];+ for (const [condition, child] of node.children)+ entries.push(`${condition}: ${renderNode(child)}`);+ return `{ ${entries.join(', ')} }`;+ };+ const key = (prop: string) => (/^[$A-Z_][\w$]*$/i.test(prop) ? prop : JSON.stringify(prop));+ const renderProps = (props: Map<string, ValueNode>) =>+ [...props].map(([prop, node]) => `${key(prop)}: ${renderNode(node)}`);++ const entries = renderProps(roots.get('') ?? new Map());+ for (const [element, props] of roots) {+ if (element) entries.push(`${JSON.stringify(element)}: { ${renderProps(props).join(', ')} }`);+ }++ return { code: `{ ${entries.join(', ')} }`, usesCssVar, usesMedia };+};diff --git a/scripts/stylexMigration/codemod/index.ts b/scripts/stylexMigration/codemod/index.tsnew file mode 100644index 00000000000..f740101c05b--- /dev/null+++ b/scripts/stylexMigration/codemod/index.ts@@ -0,0 +1,119 @@+import { execFileSync } from 'node:child_process';+import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import path from 'node:path';++import { UnsupportedCssError } from './css';+import { transformSource } from './transform';+import { compileStylex, format, lintAndFix } from './validate';++export interface CodemodReport {+ converted: string[];+ /** Converted files whose cx() puts an outside className before the StyleX classes. */+ review: string[];+ skipped: { file: string; reason: string }[];+}++const SOURCE_EXTENSIONS = ['.tsx', '.ts', '/index.tsx', '/index.ts'];++/**+ * Source files imported by tests that mock createStaticStyles to return fixed+ * class names. Converting them breaks the tests' class-based queries, so they+ * move together with their tests, by hand.+ */+export const findFilesWithMockedStyles = (root: string) => {+ const tests = execFileSync(+ 'git',+ ['grep', '-l', 'createStaticStyles:', '--', '*.test.ts', '*.test.tsx'],+ {+ cwd: root,+ encoding: 'utf8',+ },+ )+ .split('\n')+ .filter(Boolean);+ const files = new Set<string>();+ for (const test of tests) {+ const source = readFileSync(path.join(root, test), 'utf8');+ for (const [, spec] of source.matchAll(/from ['"](\.{1,2}\/[^'"]+)['"]/g)) {+ const base = path.join(path.dirname(test), spec);+ const hit = ['', ...SOURCE_EXTENSIONS]+ .map((ext) => base + ext)+ .find((f) => existsSync(path.join(root, f)) && /\.tsx?$/.test(f));+ if (hit) files.add(path.normalize(hit));+ }+ }+ return files;+};++/** Nearest vitest config above a package file that does not compile StyleX. */+export const findUncompiledTestConfig = (root: string, file: string) => {+ for (let dir = path.dirname(file); dir !== '.' && dir !== ''; dir = path.dirname(dir)) {+ for (const name of ['vitest.config.mts', 'vitest.config.ts', 'vitest.config.mjs']) {+ const config = path.join(dir, name);+ if (!existsSync(path.join(root, config))) continue;+ return readFileSync(path.join(root, config), 'utf8').includes('stylexPlugin')+ ? undefined+ : config;+ }+ }+};++/**+ * Converts each file in place. A file is written only when the transform, the+ * StyleX compiler and ESLint (with autofix) all accept it; otherwise it is left+ * untouched and the reason recorded.+ */+export const runCodemod = async (+ root: string,+ files: string[],+ { write = true }: { write?: boolean } = {},+): Promise<CodemodReport> => {+ const report: CodemodReport = { converted: [], review: [], skipped: [] };+ const mocked = findFilesWithMockedStyles(root);++ for (const file of files) {+ const filePath = path.join(root, file);+ if (mocked.has(file)) {+ report.skipped.push({ file, reason: 'tests mock createStaticStyles' });+ continue;+ }+ const uncompiled = findUncompiledTestConfig(root, file);+ if (uncompiled) {+ report.skipped.push({ file, reason: `${uncompiled} lacks stylexPlugin` });+ continue;+ }+ const source = readFileSync(filePath, 'utf8');+ try {+ const { code, mergesOutsideClassName } = transformSource(source, file);+ compileStylex(code, filePath);+ const linted = await lintAndFix(await format(code, filePath), filePath);+ if (linted.errors.length > 0) throw new UnsupportedCssError(`lint: ${linted.errors[0]}`);+ // eslint --fix merges duplicate imports without formatting them.+ if (write) writeFileSync(filePath, await format(linted.code, filePath));+ report.converted.push(file);+ if (mergesOutsideClassName > 0) report.review.push(file);+ } catch (error) {+ const reason =+ error instanceof UnsupportedCssError+ ? error.message+ : `compile: ${(error as Error).message.split('\n')[0].replace(`${filePath}: `, '')}`;+ report.skipped.push({ file, reason });+ }+ }+ return report;+};++/** Groups skip reasons by their leading phrase so the summary stays short. */+export const summarizeSkips = (skipped: CodemodReport['skipped']) => {+ const counts = new Map<string, number>();+ for (const { reason } of skipped) {+ const key = reason+ .replace(/^(selector|interpolation|style entry|cx argument|factory uses) .*/, '$1 β¦')+ .replace(/^(cx: outside class after StyleX): .*/, '$1')+ .replace(/^(lint: [^:]+):.*/, '$1')+ .replace(/^packages\/.+ lacks stylexPlugin$/, 'package vitest config lacks stylexPlugin')+ .replace(/^(compile: ).*/, '$1β¦');+ counts.set(key, (counts.get(key) ?? 0) + 1);+ }+ return [...counts].sort((a, b) => b[1] - a[1]);+};diff --git a/scripts/stylexMigration/codemod/transform.test.ts b/scripts/stylexMigration/codemod/transform.test.tsnew file mode 100644index 00000000000..85b58ccb955--- /dev/null+++ b/scripts/stylexMigration/codemod/transform.test.ts@@ -0,0 +1,161 @@+import { describe, expect, it } from 'vitest';++import { UnsupportedCssError } from './css';+import { transformSource } from './transform';++const squash = (code: string) => code.replaceAll(/\s+/g, ' ');++describe('transformSource', () => {+ it('rewrites the factory, imports and DOM className usages', () => {+ const source = `import { createStaticStyles, cx, Flexbox } from '@lobehub/ui';++const styles = createStaticStyles(({ css, cssVar }) => ({+ root: css\`+ color: \${cssVar.colorText};+ \`,+ active: css\`+ font-weight: 600;+ \`,+}));++export const A = ({ active }: { active: boolean }) => (+ <div className={cx(styles.root, active && styles.active)}>+ <span className={styles.root} />+ </div>+);+`;+ const { code, mergesOutsideClassName } = transformSource(source);+ const out = squash(code);++ expect(mergesOutsideClassName).toBe(0);+ expect(out).toContain("import { cx, Flexbox } from '@lobehub/ui';");+ expect(out).toContain("import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';");+ expect(out).toContain("import * as stylex from '@stylexjs/stylex';");+ expect(out).toContain(+ 'const styles = stylex.create({ root: { color: cssVar.colorText }, active: { fontWeight: 600 } });',+ );+ expect(out).toContain('<div {...stylex.props(styles.root, active && styles.active)}>');+ expect(out).toContain('<span {...stylex.props(styles.root)} />');+ expect(out).not.toContain('createStaticStyles');+ });++ it('passes a className string to components and to DOM elements with a style prop', () => {+ const source = `import { createStaticStyles, Flexbox } from '@lobehub/ui';+const styles = createStaticStyles(({ css }) => ({ root: css\`gap: 4px;\` }));+export const A = () => (+ <>+ <Flexbox className={styles.root} />+ <div className={styles.root} style={{ width: 1 }} />+ <Flexbox classNames={{ root: styles.root }} />+ </>+);+`;+ const out = squash(transformSource(source).code);++ expect(out).toContain('<Flexbox className={stylex.props(styles.root).className} />');+ expect(out).toContain(+ '<div className={stylex.props(styles.root).className} style={{ width: 1 }} />',+ );+ expect(out).toContain('classNames={{ root: stylex.props(styles.root).className }}');+ });++ it('keeps one stylex.props per cx call and counts outside classNames placed before it', () => {+ const source = `import { createStaticStyles, cx } from '@lobehub/ui';+const styles = createStaticStyles(({ css }) => ({ a: css\`gap: 1px;\`, b: css\`gap: 2px;\` }));+export const A = ({ className, on }: { className?: string; on: boolean }) => (+ <section className={cx(className, styles.a, on ? styles.b : undefined)} />+);+`;+ const { code, mergesOutsideClassName } = transformSource(source);++ expect(mergesOutsideClassName).toBe(1);+ expect(squash(code)).toContain(+ 'className={cx(stylex.props(styles.a, on ? styles.b : undefined).className, className)}',+ );+ });++ it('turns responsive into media consts, inside and outside the styles', () => {+ const source = `import { createStaticStyles, responsive } from '@lobehub/ui';+const styles = createStaticStyles(({ css }) => ({+ root: css\`+ gap: 8px;+ \${responsive.sm} {+ gap: 4px;+ }+ \`,+}));+export const query = responsive.sm;+export const A = () => <div className={styles.root} />;+`;+ const out = squash(transformSource(source).code);++ expect(out).toContain("import { media } from '@lobehub/ui/stylex/media.stylex';");+ expect(out).toContain('gap: { default: "8px", [media.sm]: "4px" }');+ expect(out).toContain('export const query = media.sm;');+ expect(out).not.toMatch(/import \{[^}]*responsive/);+ });++ it('accepts a factory whose block only returns the styles', () => {+ const source = `import { createStaticStyles } from '@lobehub/ui';+const styles = createStaticStyles(({ css }) => {+ return { root: css\`gap: 4px;\` };+});+export const A = () => <div className={styles.root} />;+`;+ expect(squash(transformSource(source).code)).toContain(+ 'stylex.create({ root: { gap: "4px" } })',+ );+ });++ it.each([+ [+ 'exported styles',+ `export const styles = createStaticStyles(({ css }) => ({ a: css\`gap: 1px;\` }));`,+ ],+ [+ 'styles passed around',+ `const styles = createStaticStyles(({ css }) => ({ a: css\`gap: 1px;\` }));+export const all = styles;`,+ ],+ [+ 'dynamic keys',+ `const styles = createStaticStyles(({ css }) => ({ a: css\`gap: 1px;\` }));+export const pick = (k: 'a') => styles[k];`,+ ],+ [+ 'a shadowing binding',+ `const styles = createStaticStyles(({ css }) => ({ a: css\`gap: 1px;\` }));+export const A = ({ styles }: { styles: { a: string } }) => <div className={styles.a} />;`,+ ],+ [+ 'an outside class after the styles, which StyleX would outrank',+ `const styles = createStaticStyles(({ css }) => ({ a: css\`gap: 1px;\` }));+export const A = ({ className }: { className?: string }) => <div className={cx(styles.a, className)} />;`,+ ],+ [+ 'style refs kept in a lookup object',+ `const styles = createStaticStyles(({ css }) => ({ a: css\`gap: 1px;\`, b: css\`gap: 2px;\` }));+const TONE = { b: styles.b };+export const A = ({ t }: { t: 'b' }) => <div className={cx(TONE[t])} />;`,+ ],+ [+ 'an existing stylex binding',+ `const stylex = 1;+const styles = createStaticStyles(({ css }) => ({ a: css\`gap: 1px;\` }));+export const A = () => <div className={styles.a} />;`,+ ],+ ])('rejects %s', (_label, body) => {+ const source = `import { createStaticStyles, cx } from '@lobehub/ui';\n${body}\n`;+ expect(() => transformSource(source)).toThrow(UnsupportedCssError);+ });++ it('ignores JSX attributes and keys that are also named styles', () => {+ const source = `import { createStaticStyles, Modal } from '@lobehub/ui';+const styles = createStaticStyles(({ css }) => ({ a: css\`gap: 1px;\` }));+export const A = () => <Modal className={styles.a} styles={{ body: { padding: 0 } }} />;+`;+ expect(squash(transformSource(source).code)).toContain(+ '<Modal className={stylex.props(styles.a).className} styles={{ body: { padding: 0 } }} />',+ );+ });+});diff --git a/scripts/stylexMigration/codemod/transform.ts b/scripts/stylexMigration/codemod/transform.tsnew file mode 100644index 00000000000..5b238e649c9--- /dev/null+++ b/scripts/stylexMigration/codemod/transform.ts@@ -0,0 +1,323 @@+/**+ * Rewrites one file from createStaticStyles to stylex.create.+ *+ * - `const styles = createStaticStyles(({ css, cssVar }) => ({ k: css`β¦` }))`+ * becomes `const styles = stylex.create({ k: { β¦ } })`.+ * - `className={styles.k}` / `className={cx(styles.a, on && styles.b)}` become+ * `{...stylex.props(β¦)}` when the element has no `style` attribute.+ * - Any other `styles.k` becomes `stylex.props(styles.k).className`, and each+ * `cx(β¦)` call keeps one `stylex.props(β¦)` for all of its style arguments so+ * StyleX still resolves them in argument order.+ *+ * Throws UnsupportedCssError for anything it cannot rewrite faithfully.+ */+import ts from 'typescript';++import { convertCss, type TokenNames, UnsupportedCssError } from './css';++export interface TransformResult {+ code: string;+ /** cx() calls that merge StyleX classes with an outside className. */+ mergesOutsideClassName: number;+}++interface Edit {+ end: number;+ start: number;+ text: string;+}++const applyEdits = (source: string, edits: Edit[]) => {+ const sorted = [...edits].sort((a, b) => b.start - a.start);+ for (let i = 1; i < sorted.length; i++) {+ if (sorted[i].end > sorted[i - 1].start) throw new Error('overlapping edits');+ }+ let out = source;+ for (const edit of sorted) out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);+ return out;+};++const UI = '@lobehub/ui';++export const transformSource = (source: string, fileName = 'file.tsx'): TransformResult => {+ const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const text = (node: ts.Node) => node.getText(sf);+ const edits: Edit[] = [];+ const replace = (node: ts.Node, value: string) =>+ edits.push({ end: node.getEnd(), start: node.getStart(sf), text: value });++ // Names imported from @lobehub/ui.+ const uiImports = new Map<string, string>(); // local β imported+ const uiImportDecls: ts.ImportDeclaration[] = [];+ for (const stmt of sf.statements) {+ if (!ts.isImportDeclaration(stmt) || (stmt.moduleSpecifier as ts.StringLiteral).text !== UI)+ continue;+ uiImportDecls.push(stmt);+ const bindings = stmt.importClause?.namedBindings;+ if (bindings && ts.isNamedImports(bindings)) {+ for (const el of bindings.elements) {+ uiImports.set(el.name.text, (el.propertyName ?? el.name).text);+ }+ }+ }+ const localOf = (imported: string) => [...uiImports].find(([, name]) => name === imported)?.[0];+ const createLocal = localOf('createStaticStyles');+ if (!createLocal) throw new UnsupportedCssError('no createStaticStyles import');+ const cxLocal = localOf('cx');+ const outerCssVar = localOf('cssVar');+ const outerResponsive = localOf('responsive');+ if (outerCssVar && outerCssVar !== 'cssVar')+ throw new UnsupportedCssError('aliased cssVar import');++ const identifiers = new Set<string>();+ const collect = (node: ts.Node) => {+ if (ts.isIdentifier(node)) identifiers.add(node.text);+ ts.forEachChild(node, collect);+ };+ collect(sf);+ for (const name of ['stylex', 'media']) {+ if (identifiers.has(name)) throw new UnsupportedCssError(`file already declares ${name}`);+ }++ // Locate `const <name> = createStaticStyles(...)` declarations.+ const stylesNames = new Set<string>();+ let usesCssVar = false;+ let usesMedia = false;+ for (const stmt of sf.statements) {+ if (!ts.isVariableStatement(stmt)) continue;+ for (const decl of stmt.declarationList.declarations) {+ const init = decl.initializer;+ if (!init || !ts.isCallExpression(init) || text(init.expression) !== createLocal) continue;+ if (stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword))+ throw new UnsupportedCssError('exported styles');+ if (!ts.isIdentifier(decl.name)) throw new UnsupportedCssError('destructured styles');+ stylesNames.add(decl.name.text);++ const fn = init.arguments[0];+ if (!fn || !ts.isArrowFunction(fn)) throw new UnsupportedCssError('styles factory');+ const names: TokenNames = {+ cssVar: new Set(outerCssVar ? [outerCssVar] : []),+ responsive: new Set(outerResponsive ? [outerResponsive] : []),+ };+ let cssTag: string | undefined;+ const param = fn.parameters[0];+ if (param) {+ if (!ts.isObjectBindingPattern(param.name)) throw new UnsupportedCssError('styles factory');+ for (const el of param.name.elements) {+ const key = (el.propertyName ?? el.name) as ts.Identifier;+ const local = (el.name as ts.Identifier).text;+ if (key.text === 'css') cssTag = local;+ else if (key.text === 'cssVar') names.cssVar.add(local);+ else if (key.text === 'responsive') names.responsive.add(local);+ else if (key.text !== 'cx') throw new UnsupportedCssError(`factory uses ${key.text}`);+ }+ }+ let body: ts.Node = fn.body;+ // `=> { return { β¦ }; }` with nothing else in the block.+ if (ts.isBlock(body) && body.statements.length === 1) {+ const [only] = body.statements;+ if (ts.isReturnStatement(only) && only.expression) body = only.expression;+ }+ while (ts.isParenthesizedExpression(body)) body = body.expression;+ if (!ts.isObjectLiteralExpression(body)) throw new UnsupportedCssError('styles factory body');++ const entries: string[] = [];+ for (const prop of body.properties) {+ if (!ts.isPropertyAssignment(prop) || ts.isComputedPropertyName(prop.name))+ throw new UnsupportedCssError('style entry');+ const value = prop.initializer;+ if (!ts.isTaggedTemplateExpression(value) || text(value.tag) !== cssTag)+ throw new UnsupportedCssError(`style entry ${text(prop.name)}`);+ const tpl = value.template;+ const raw = (node: ts.Node, trimStart: number, trimEnd: number) => {+ const s = text(node);+ return s.slice(trimStart, s.length - trimEnd);+ };+ const quasis = ts.isNoSubstitutionTemplateLiteral(tpl)+ ? [raw(tpl, 1, 1)]+ : [+ raw(tpl.head, 1, 2),+ ...tpl.templateSpans.map((span, i) =>+ raw(span.literal, 1, i === tpl.templateSpans.length - 1 ? 1 : 2),+ ),+ ];+ const expressions = ts.isNoSubstitutionTemplateLiteral(tpl)+ ? []+ : tpl.templateSpans.map((span) => text(span.expression));+ const converted = convertCss({ expressions, quasis }, names);+ usesCssVar ||= converted.usesCssVar;+ usesMedia ||= converted.usesMedia;+ entries.push(`${text(prop.name)}: ${converted.code}`);+ }+ replace(init, `stylex.create({ ${entries.join(', ')} })`);+ }+ }+ if (stylesNames.size === 0) throw new UnsupportedCssError('no top-level createStaticStyles');++ // Rewrite usages.+ const isStyleRef = (node: ts.Node): node is ts.PropertyAccessExpression =>+ ts.isPropertyAccessExpression(node) &&+ ts.isIdentifier(node.expression) &&+ stylesNames.has(node.expression.text);+ /** `styles.k`, `cond && styles.k`, `cond ? styles.a : styles.b` (undefined/null allowed). */+ const isStyleArg = (node: ts.Expression): boolean => {+ if (ts.isParenthesizedExpression(node)) return isStyleArg(node.expression);+ if (isStyleRef(node)) return true;+ if (+ ts.isBinaryExpression(node) &&+ node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken+ )+ return isStyleArg(node.right) && !containsStyleRef(node.left);+ if (ts.isConditionalExpression(node)) {+ const ok = (e: ts.Expression) =>+ isStyleArg(e) || e.kind === ts.SyntaxKind.NullKeyword || text(e) === 'undefined';+ return ok(node.whenTrue) && ok(node.whenFalse) && !containsStyleRef(node.condition);+ }+ return false;+ };+ const containsStyleRef = (node: ts.Node): boolean =>+ isStyleRef(node) || (ts.forEachChild(node, (c) => containsStyleRef(c) || undefined) ?? false);+ const isCx = (node: ts.Node): node is ts.CallExpression =>+ !!cxLocal && ts.isCallExpression(node) && text(node.expression) === cxLocal;++ let mergesOutsideClassName = 0;++ /** Splits cx args into StyleX ones and the rest; throws on mixed expressions. */+ const splitCx = (call: ts.CallExpression) => {+ const styleArgs: string[] = [];+ const rest: string[] = [];+ for (const arg of call.arguments) {+ if (isStyleArg(arg)) styleArgs.push(text(arg));+ else if (containsStyleRef(arg)) throw new UnsupportedCssError(`cx argument ${text(arg)}`);+ else {+ // Emotion let a later class win; StyleX rules outrank plain classes, so a+ // class placed after the styles (a caller's override, a shared emotion+ // style) would stop winning.+ if (styleArgs.length > 0)+ throw new UnsupportedCssError(`cx: outside class after StyleX: ${text(arg)}`);+ rest.push(text(arg));+ }+ }+ return { rest, styleArgs };+ };++ const visit = (node: ts.Node) => {+ if (ts.isJsxAttribute(node) && text(node.name) === 'className' && node.initializer) {+ const init = node.initializer;+ const expr = ts.isJsxExpression(init) ? init.expression : undefined;+ const element = node.parent.parent as ts.JsxOpeningLikeElement;+ const hasStyle = element.attributes.properties.some(+ (p) => ts.isJsxAttribute(p) && text(p.name) === 'style',+ );+ // Spread only onto DOM elements: a component's props may not declare `style`.+ const isIntrinsic = /^[a-z]/.test(text(element.tagName));+ if (expr && !hasStyle && isIntrinsic) {+ if (isStyleArg(expr)) {+ replace(node, `{...stylex.props(${text(expr)})}`);+ return;+ }+ if (isCx(expr)) {+ const { rest, styleArgs } = splitCx(expr);+ if (styleArgs.length > 0 && rest.length === 0) {+ replace(node, `{...stylex.props(${styleArgs.join(', ')})}`);+ return;+ }+ }+ }+ }++ if (isCx(node)) {+ const { rest, styleArgs } = splitCx(node);+ if (styleArgs.length > 0) {+ if (rest.length > 0) mergesOutsideClassName++;+ const props = `stylex.props(${styleArgs.join(', ')}).className`;+ replace(node, `${text(node.expression)}(${[props, ...rest].join(', ')})`);+ return;+ }+ }++ if (isStyleArg(node as ts.Expression) && !isStyleArg(node.parent as ts.Expression)) {+ // A ref kept in a variable or a lookup object is later combined with other+ // classes; separate stylex.props calls would resolve by CSS order, not by+ // argument order. Object values inside JSX props (classNames slots) are fine.+ const inJsxProp = (n: ts.Node): boolean =>+ !!n.parent &&+ (ts.isJsxExpression(n.parent) ||+ ((ts.isObjectLiteralExpression(n.parent) || ts.isPropertyAssignment(n.parent)) &&+ inJsxProp(n.parent)));+ if (+ ts.isVariableDeclaration(node.parent) ||+ (ts.isPropertyAssignment(node.parent) && !inJsxProp(node.parent))+ )+ throw new UnsupportedCssError('style ref stored outside JSX');+ replace(node, `stylex.props(${text(node)}).className`);+ return;+ }++ if (ts.isIdentifier(node) && stylesNames.has(node.text)) {+ const parent = node.parent;+ const isTopLevelDecl =+ ts.isVariableDeclaration(parent) &&+ parent.name === node &&+ ts.isVariableStatement(parent.parent.parent) &&+ parent.parent.parent.parent === sf;+ // A local binding with the same name would make styles.k mean something else.+ if (+ !isTopLevelDecl &&+ ((ts.isVariableDeclaration(parent) && parent.name === node) ||+ (ts.isBindingElement(parent) && parent.name === node) ||+ (ts.isParameter(parent) && parent.name === node))+ )+ throw new UnsupportedCssError('shadowed styles binding');+ // Same spelling, different meaning: JSX attribute, member and key names.+ const isName =+ isTopLevelDecl ||+ (ts.isJsxAttribute(parent) && parent.name === node) ||+ (ts.isPropertyAccessExpression(parent) && parent.name === node) ||+ (ts.isPropertyAssignment(parent) && parent.name === node) ||+ (ts.isBindingElement(parent) && parent.propertyName === node) ||+ ts.isPropertySignature(parent);+ if (!isName) throw new UnsupportedCssError(`styles used as a value: ${text(parent)}`);+ }++ // The rewritten createStaticStyles call is replaced wholesale.+ if (ts.isCallExpression(node) && text(node.expression) === createLocal) return;+ ts.forEachChild(node, visit);+ };+ visit(sf);++ // Imports: drop createStaticStyles (and cssVar / responsive when they become+ // StyleX consts), add the StyleX imports. Unused cx is left to eslint --fix.+ const dropped = new Set(['createStaticStyles']);+ if (usesCssVar || outerCssVar) dropped.add('cssVar');+ if (outerResponsive) dropped.add('responsive');+ for (const decl of uiImportDecls) {+ const bindings = decl.importClause?.namedBindings;+ if (!bindings || !ts.isNamedImports(bindings)) continue;+ const keep = bindings.elements.filter((el) => !dropped.has((el.propertyName ?? el.name).text));+ if (keep.length === bindings.elements.length) continue;+ const isTypeOnly = decl.importClause?.isTypeOnly ? 'type ' : '';+ replace(+ decl,+ keep.length === 0 && !decl.importClause?.name+ ? ''+ : `import ${isTypeOnly}{ ${keep.map((el) => text(el)).join(', ')} } from '${UI}';`,+ );+ }++ const added = [`import * as stylex from '@stylexjs/stylex';`];+ if (usesCssVar || outerCssVar)+ added.unshift(`import { cssVar } from '${UI}/stylex/cssVar.stylex';`);+ if (usesMedia || outerResponsive)+ added.unshift(`import { media } from '${UI}/stylex/media.stylex';`);+ const anchor = uiImportDecls.at(-1) ?? sf.statements.find(ts.isImportDeclaration);+ const at = anchor ? anchor.getEnd() : 0;+ edits.push({ end: at, start: at, text: `\n${added.join('\n')}\n` });++ // Outside the styles, runtime `responsive.x` was a media query string too.+ let code = applyEdits(source, edits);+ if (outerResponsive && outerResponsive !== 'media')+ code = code.replaceAll(new RegExp(String.raw`\b${outerResponsive}\.`, 'g'), 'media.');++ return { code, mergesOutsideClassName };+};diff --git a/scripts/stylexMigration/codemod/validate.ts b/scripts/stylexMigration/codemod/validate.tsnew file mode 100644index 00000000000..2c88f3dc9c9--- /dev/null+++ b/scripts/stylexMigration/codemod/validate.ts@@ -0,0 +1,66 @@+import { realpathSync } from 'node:fs';+import { createRequire } from 'node:module';+import path from 'node:path';++import { ESLint } from 'eslint';+import * as prettier from 'prettier';++type Babel = {+ transformSync: (code: string, options: Record<string, unknown>) => unknown;+};++const repoRoot = path.resolve(import.meta.dirname, '../../..');++// The compiler the SPA build runs, resolved through @stylexjs/unplugin.+const loadCompiler = () => {+ const rootRequire = createRequire(path.join(repoRoot, 'package.json'));+ const unpluginEntry = realpathSync(rootRequire.resolve('@stylexjs/unplugin'));+ const req = createRequire(+ path.join(path.resolve(path.dirname(unpluginEntry), '..'), 'package.json'),+ );+ const loaded = req('@stylexjs/babel-plugin') as { default?: unknown };+ return { babel: req('@babel/core') as Babel, plugin: loaded.default ?? loaded };+};++let compiler: ReturnType<typeof loadCompiler> | undefined;+let eslint: ESLint | undefined;++/** Throws when the StyleX compiler rejects the file. */+export const compileStylex = (code: string, filename: string) => {+ compiler ??= loadCompiler();+ compiler.babel.transformSync(code, {+ babelrc: false,+ configFile: false,+ filename,+ parserOpts: { plugins: ['jsx', 'typescript'] },+ plugins: [+ [+ compiler.plugin,+ {+ classNamePrefix: 'lh',+ dev: false,+ runtimeInjection: false,+ test: false,+ unstable_moduleResolution: { rootDir: repoRoot, type: 'commonJS' },+ },+ ],+ ],+ sourceType: 'module',+ });+};++/** Formats with the repository prettier config, as the pre-commit hook does. */+export const format = async (code: string, filePath: string) => {+ const config = await prettier.resolveConfig(filePath);+ return prettier.format(code, { ...config, filepath: filePath });+};++/** Lints with autofix; returns the fixed code and every remaining error. */+export const lintAndFix = async (code: string, filePath: string) => {+ eslint ??= new ESLint({ cwd: repoRoot, fix: true });+ const [result] = await eslint.lintText(code, { filePath });+ const errors = result.messages+ .filter((m) => m.severity === 2)+ .map((m) => `${m.ruleId ?? 'parse'}: ${m.message.split('\n')[0]}`);+ return { code: result.output ?? code, errors };+};diff --git a/scripts/stylexMigration/eslint.mjs b/scripts/stylexMigration/eslint.mjsnew file mode 100644index 00000000000..40dc70116e9--- /dev/null+++ b/scripts/stylexMigration/eslint.mjs@@ -0,0 +1,66 @@+import { readFileSync } from 'node:fs';++import stylex from '@stylexjs/eslint-plugin';+import { builtinRules } from 'eslint/use-at-your-own-risk';++const readJson = (file) => JSON.parse(readFileSync(new URL(file, import.meta.url), 'utf8'));++const legacyImports = readJson('./legacyImports.json');+// `ignores` entries are globs: route segments like `[benchmarkId]` and `(main)`+// would otherwise be read as character classes and groups.+const legacyFiles = readJson('./legacyFiles.json').map((file) =>+ file.replaceAll(/[!()*+?@[\]{}]/g, String.raw`\$&`),+);++/**+ * StyleX migration guard. New code may not import the emotion-backed style APIs+ * from @lobehub/ui; files that still do are listed in legacyFiles.json, which only+ * shrinks (`bun run stylex:migration --prune-legacy`).+ *+ * The core no-restricted-imports rule is re-registered under its own name because+ * flat config replaces a rule per file: the src/** blocks already configure+ * no-restricted-imports and would otherwise override this one, or be overridden.+ */+export const stylexMigrationConfig = [+ {+ files: ['**/*.{ts,tsx}'],+ // Tests mock @lobehub/ui, including its style factories; the guard is about+ // shipped code.+ ignores: [...legacyFiles, '**/*.test.{ts,tsx}', '**/__tests__/**'],+ plugins: {+ 'stylex-migration': {+ rules: { 'no-emotion-styles': builtinRules.get('no-restricted-imports') },+ },+ },+ rules: {+ 'stylex-migration/no-emotion-styles': [+ 'error',+ {+ paths: [+ {+ allowTypeImports: true,+ importNames: legacyImports,+ message:+ 'Emotion styles are being migrated to StyleX. Use stylex.create with @lobehub/ui/stylex/cssVar.stylex (see the react skill).',+ name: '@lobehub/ui',+ },+ ],+ },+ ],+ },+ },+ {+ // sort-keys is left to perfectionist/sort-objects, which already orders keys.+ files: ['**/*.{ts,tsx}'],+ plugins: { '@stylexjs': stylex },+ rules: {+ '@stylexjs/enforce-extension': 'error',+ '@stylexjs/no-conflicting-props': 'error',+ '@stylexjs/no-legacy-contextual-styles': 'error',+ '@stylexjs/no-lookahead-selectors': 'error',+ '@stylexjs/no-unused': 'error',+ '@stylexjs/valid-shorthands': 'error',+ '@stylexjs/valid-styles': 'error',+ },+ },+];diff --git a/scripts/stylexMigration/eslint.test.ts b/scripts/stylexMigration/eslint.test.tsnew file mode 100644index 00000000000..b5c7bb236bf--- /dev/null+++ b/scripts/stylexMigration/eslint.test.ts@@ -0,0 +1,37 @@+// @vitest-environment node+import path from 'node:path';++import { ESLint } from 'eslint';+import { describe, expect, it } from 'vitest';++import { readLegacyFiles } from '.';++const repoRoot = path.resolve(import.meta.dirname, '../..');+const rule = 'stylex-migration/no-emotion-styles';++const ruleFor = async (eslint: ESLint, file: string) => {+ const config: { rules?: Record<string, unknown> } | undefined =+ await eslint.calculateConfigForFile(path.join(repoRoot, file));+ // undefined for files ESLint ignores globally+ return config?.rules?.[rule];+};++describe('stylex-migration/no-emotion-styles config', () => {+ const eslint = new ESLint({ cwd: repoRoot });++ it('exempts every legacy file, including route segments read as glob syntax', async () => {+ const legacy = readLegacyFiles();+ const globLike = legacy.filter((file) => /[()[\]]/.test(file));+ expect(globLike.length).toBeGreaterThan(0);++ const enforced: string[] = [];+ for (const file of legacy) if (await ruleFor(eslint, file)) enforced.push(file);+ expect(enforced).toEqual([]);+ }, 120_000);++ it('applies to new source files and skips tests', async () => {+ expect(await ruleFor(eslint, 'src/features/NewFeature/index.tsx')).toBeDefined();+ expect(await ruleFor(eslint, 'src/routes/(main)/eval/bench/[id]/New.tsx')).toBeDefined();+ expect(await ruleFor(eslint, 'src/features/NewFeature/index.test.tsx')).toBeUndefined();+ }, 120_000);+});diff --git a/scripts/stylexMigration/index.ts b/scripts/stylexMigration/index.tsnew file mode 100644index 00000000000..3abcfbfa0ca--- /dev/null+++ b/scripts/stylexMigration/index.ts@@ -0,0 +1,164 @@+/**+ * StyleX migration status.+ *+ * bun run stylex:migration # tier totals and the busiest areas+ * bun run stylex:migration --list C # files in one tier+ * bun run stylex:migration --json # full per-file report+ * bun run stylex:migration --prune-legacy # drop migrated files from legacyFiles.json+ * bun run stylex:migration --baseline <distDir> [html] # sizes of a built SPA+ * bun run stylex:migration --codemod [--tier A,B] [--path <prefix>]β¦ [--dry]+ *+ * legacyFiles.json is the ESLint allowlist for emotion style imports. It only+ * shrinks: pruning keeps files that still use them and never adds new ones.+ */+import { execFileSync } from 'node:child_process';+import { readFileSync, writeFileSync } from 'node:fs';+import path from 'node:path';++import { formatBaseline, measureBuild } from './baseline';+import { classifySource, type StyleFileReport } from './classify';+import { runCodemod, summarizeSkips } from './codemod';++const repoRoot = path.resolve(import.meta.dirname, '../..');+export const legacyFilesPath = path.join(import.meta.dirname, 'legacyFiles.json');++export type FileReport = StyleFileReport & { area: string; file: string };++const areaOf = (file: string) => {+ const parts = file.split('/');+ if (parts[0] === 'packages' && parts[1]?.startsWith('builtin-tool'))+ return 'packages/builtin-tool-*';+ return parts.slice(0, parts[0] === 'src' ? 3 : 2).join('/');+};++export const scanRepo = (root = repoRoot): FileReport[] => {+ const files = execFileSync('git', ['ls-files', '--', '*.ts', '*.tsx'], {+ cwd: root,+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+ })+ .split('\n')+ // This directory's own test fixtures contain emotion imports as strings.+ .filter((file) => file && !file.startsWith('scripts/stylexMigration/'));++ const reports: FileReport[] = [];+ for (const file of files) {+ let source: string;+ try {+ source = readFileSync(path.join(root, file), 'utf8');+ } catch {+ continue; // deleted in the working tree but still in the index+ }+ if (!source.includes('@lobehub/ui')) continue;+ const report = classifySource(source);+ if (report.legacyImports.length === 0) continue;+ reports.push({ ...report, area: areaOf(file), file });+ }+ return reports;+};++export const readLegacyFiles = (): string[] =>+ JSON.parse(readFileSync(legacyFilesPath, 'utf8')) as string[];++/** Listed files that no longer use an emotion style import, or no longer exist. */+export const findStaleLegacyFiles = (reports: FileReport[], legacy = readLegacyFiles()) => {+ const current = new Set(reports.map((r) => r.file));+ return legacy.filter((file) => !current.has(file));+};++const writeLegacyFiles = (files: string[]) =>+ writeFileSync(legacyFilesPath, `${JSON.stringify([...files].sort(), null, 2)}\n`);++const printSummary = (reports: FileReport[]) => {+ const tiers = { A: 0, B: 0, C: 0, D: 0 };+ const areas = new Map<string, typeof tiers & { total: number }>();+ for (const r of reports) {+ tiers[r.tier]++;+ const area = areas.get(r.area) ?? { A: 0, B: 0, C: 0, D: 0, total: 0 };+ area[r.tier]++;+ area.total++;+ areas.set(r.area, area);+ }+ console.log(+ `${reports.length} files on emotion styles β A ${tiers.A} Β· B ${tiers.B} Β· C ${tiers.C} Β· D ${tiers.D}`,+ );+ console.log('\narea | A | B | C | D | total');+ for (const [area, t] of [...areas].sort((a, b) => b[1].total - a[1].total).slice(0, 30)) {+ console.log(`${area} | ${t.A} | ${t.B} | ${t.C} | ${t.D} | ${t.total}`);+ }+};++const optionValues = (args: string[], flag: string) =>+ args.flatMap((arg, i) => (arg === flag && args[i + 1] ? [args[i + 1]] : []));++const codemod = async (args: string[], reports: FileReport[]) => {+ const tiers = new Set((optionValues(args, '--tier')[0] ?? 'A,B').split(','));+ const prefixes = optionValues(args, '--path');+ const files = reports+ .filter((r) => tiers.has(r.tier))+ .filter((r) => prefixes.length === 0 || prefixes.some((p) => r.file.startsWith(p)))+ .map((r) => r.file);++ const report = await runCodemod(repoRoot, files, { write: !args.includes('--dry') });+ console.log(+ `converted ${report.converted.length} / ${files.length}, skipped ${report.skipped.length}`,+ );+ for (const [reason, count] of summarizeSkips(report.skipped))+ console.log(` ${count}\t${reason}`);+ if (report.review.length > 0) {+ console.log(`\nreview β cx() merges StyleX classes with an outside className:`);+ for (const file of report.review) console.log(` ${file}`);+ }+ if (args.includes('--verbose')) {+ console.log('\nskipped:');+ for (const { file, reason } of report.skipped) console.log(` ${file}: ${reason}`);+ }+};++const main = async () => {+ const args = process.argv.slice(2);+ const reports = scanRepo();++ if (args.includes('--json')) {+ console.log(JSON.stringify(reports, null, 2));+ return;+ }++ const listIndex = args.indexOf('--list');+ if (listIndex !== -1) {+ const tier = args[listIndex + 1];+ for (const r of reports.filter((item) => item.tier === tier)) console.log(r.file);+ return;+ }++ const baselineIndex = args.indexOf('--baseline');+ if (baselineIndex !== -1) {+ const distDir = args[baselineIndex + 1] ?? 'dist/desktop';+ const htmlFile = args[baselineIndex + 2] ?? 'index.html';+ const build = measureBuild(path.resolve(repoRoot, distDir), htmlFile);+ console.log(formatBaseline(build, reports, distDir));+ return;+ }++ if (args.includes('--codemod')) {+ await codemod(args, reports);+ return;+ }++ if (args.includes('--prune-legacy')) {+ const legacy = readLegacyFiles();+ const stale = new Set(findStaleLegacyFiles(reports, legacy));+ writeLegacyFiles(legacy.filter((file) => !stale.has(file)));+ console.log(`pruned ${stale.size} migrated files from legacyFiles.json`);+ return;+ }++ printSummary(reports);+};++if (process.argv[1] && path.resolve(process.argv[1]) === import.meta.filename) {+ main().catch((error) => {+ console.error(error);+ process.exit(1);+ });+}diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.jsonnew file mode 100644index 00000000000..c5ae535a968--- /dev/null+++ b/scripts/stylexMigration/legacyFiles.json@@ -0,0 +1,1357 @@+[+ ".agents/skills/lobe-design/tests/fixtures/bad-composite.tsx",+ ".agents/skills/lobe-design/tests/fixtures/bad-focus.tsx",+ ".agents/skills/lobe-design/tests/fixtures/bad-visual.tsx",+ ".agents/skills/lobe-design/tests/fixtures/good-composite.tsx",+ ".agents/skills/lobe-design/tests/fixtures/good-outline.tsx",+ ".agents/skills/lobe-design/tests/fixtures/good-visual.tsx",+ ".agents/skills/lobe-design/tests/fixtures/good.tsx",+ "apps/share/src/features/artifact/SharedArtifactView.tsx",+ "apps/share/src/features/topic/SharePortal.tsx",+ "apps/share/src/shell/ShareLayout.tsx",+ "apps/workbench/src/features/acceptance/AcceptanceDetail.tsx",+ "apps/workbench/src/features/acceptance/AcceptanceEmbed.tsx",+ "apps/workbench/src/features/verify/VerifyReportUnavailable.tsx",+ "apps/workbench/src/shell/WorkbenchBrandLink.tsx",+ "apps/workbench/src/shell/WorkbenchHeader.tsx",+ "packages/alint/fixtures/ui-content-width/bad-full-width-settings.tsx",+ "packages/alint/fixtures/ui-no-decorative-chrome/bad-boxed-section.tsx",+ "packages/alint/fixtures/ui-restrained-color/bad-colored-type-and-link.tsx",+ "packages/alint/fixtures/ui-restrained-color/good-status-and-gray-meta.tsx",+ "packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsx",+ "packages/builtin-tool-activator/src/client/Inspector/ActivateTools/index.tsx",+ "packages/builtin-tool-activator/src/client/Render/ActivateSkill/index.tsx",+ "packages/builtin-tool-agent-builder/src/client/Inspector/InstallPlugin/index.tsx",+ "packages/builtin-tool-agent-builder/src/client/Inspector/UpdateConfig/index.tsx",+ "packages/builtin-tool-agent-builder/src/client/Inspector/UpdatePrompt/index.tsx",+ "packages/builtin-tool-agent-builder/src/client/Render/components/PromptDiffView.tsx",+ "packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsx",+ "packages/builtin-tool-agent-documents/src/client/Inspector/_styles.ts",+ "packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsx",+ "packages/builtin-tool-agent-documents/src/client/Streaming/CreateDocument/index.tsx",+ "packages/builtin-tool-agent-documents/src/client/shared/DocumentRef.tsx",+ "packages/builtin-tool-agent-documents/src/client/shared/styles.ts",+ "packages/builtin-tool-agent-management/src/client/Inspector/CallAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Inspector/CreateAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Inspector/DuplicateAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Inspector/GetAgentDetail/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Inspector/InstallPlugin/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Inspector/SearchAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Inspector/UpdateAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Inspector/UpdatePrompt/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Render/CallAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Render/CreateAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Render/DuplicateAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Render/GetAgentDetail/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Render/InstallPlugin/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Render/UpdateAgent/index.tsx",+ "packages/builtin-tool-agent-management/src/client/Streaming/CreateAgent/index.tsx",+ "packages/builtin-tool-browser/src/client/Inspector/Browser.tsx",+ "packages/builtin-tool-browser/src/client/Render/PageAction.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/Agent.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/BrowserMcp.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/Monitor.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/ScheduleWakeup.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/SendMessage.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/Skill.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/TaskOutput.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/TaskStop.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/ToolSearch.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/WebFetch.tsx",+ "packages/builtin-tool-claude-code/src/client/Inspector/Worktree.tsx",+ "packages/builtin-tool-claude-code/src/client/Render/Agent/index.tsx",+ "packages/builtin-tool-claude-code/src/client/Render/BrowserMcp.tsx",+ "packages/builtin-tool-claude-code/src/client/Render/SendMessage/index.tsx",+ "packages/builtin-tool-claude-code/src/client/Render/Skill/index.tsx",+ "packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx",+ "packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx",+ "packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsx",+ "packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsx",+ "packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx",+ "packages/builtin-tool-cloud-sandbox/src/client/Render/ExecuteCode/index.tsx",+ "packages/builtin-tool-cloud-sandbox/src/client/Render/ExportFile/index.tsx",+ "packages/builtin-tool-dashboard/src/client/Inspector/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Inspector/BatchCreateAgents/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Inspector/CreateAgent/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Inspector/CreateGroup/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Inspector/GetAgentInfo/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Inspector/InviteAgent/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Inspector/RemoveAgent/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateAgentPrompt/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroup/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroupPrompt/index.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Render/BatchCreateAgents.tsx",+ "packages/builtin-tool-group-agent-builder/src/client/Streaming/BatchCreateAgents/index.tsx",+ "packages/builtin-tool-group-management/src/client/Inspector/Broadcast/index.tsx",+ "packages/builtin-tool-group-management/src/client/Inspector/ExecuteAgentTask/index.tsx",+ "packages/builtin-tool-group-management/src/client/Inspector/ExecuteAgentTasks/index.tsx",+ "packages/builtin-tool-group-management/src/client/Inspector/Speak/index.tsx",+ "packages/builtin-tool-group-management/src/client/Intervention/ExecuteTask.tsx",+ "packages/builtin-tool-group-management/src/client/Intervention/ExecuteTasks.tsx",+ "packages/builtin-tool-group-management/src/client/Render/Broadcast/index.tsx",+ "packages/builtin-tool-group-management/src/client/Render/ExecuteTask/index.tsx",+ "packages/builtin-tool-group-management/src/client/Render/ExecuteTasks/index.tsx",+ "packages/builtin-tool-group-management/src/client/Render/Speak/index.tsx",+ "packages/builtin-tool-group-management/src/client/Streaming/Broadcast/index.tsx",+ "packages/builtin-tool-group-management/src/client/Streaming/ExecuteTask/index.tsx",+ "packages/builtin-tool-group-management/src/client/Streaming/ExecuteTasks/index.tsx",+ "packages/builtin-tool-group-management/src/client/Streaming/Speak/index.tsx",+ "packages/builtin-tool-image-generation/src/client/Inspector/index.tsx",+ "packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx",+ "packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx",+ "packages/builtin-tool-image-generation/src/client/Render/GetImageModelParameters.tsx",+ "packages/builtin-tool-image-generation/src/client/Render/ListImageModels.tsx",+ "packages/builtin-tool-image-generation/src/client/components/ImageCanvas.tsx",+ "packages/builtin-tool-image-generation/src/client/components/ImageCanvasGrid.tsx",+ "packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx",+ "packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/FileCard.tsx",+ "packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/Item/style.ts",+ "packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Inspector/ClearTodos/index.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Inspector/UpdatePlan/index.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Inspector/Vent/index.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Intervention/ClearTodos.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Intervention/CreatePlan.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Render/CreatePlan/PlanCard.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Render/TodoList/index.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Streaming/CallSubAgent/index.tsx",+ "packages/builtin-tool-lobe-agent/src/client/Streaming/CreatePlan/index.tsx",+ "packages/builtin-tool-lobe-agent/src/client/components/SortableTodoList/AddItemRow.tsx",+ "packages/builtin-tool-lobe-agent/src/client/components/SortableTodoList/TodoItemRow.tsx",+ "packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx",+ "packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx",+ "packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/MoveFileItem.tsx",+ "packages/builtin-tool-local-system/src/client/Placeholder/SearchFiles.tsx",+ "packages/builtin-tool-local-system/src/client/Render/MoveLocalFiles/MoveFileItem.tsx",+ "packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileSkeleton.tsx",+ "packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsx",+ "packages/builtin-tool-local-system/src/client/Render/SearchFiles/SearchQuery/SearchView.tsx",+ "packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx",+ "packages/builtin-tool-local-system/src/client/components/FileItem.tsx",+ "packages/builtin-tool-memory/src/client/Inspector/AddActivityMemory/index.tsx",+ "packages/builtin-tool-memory/src/client/Inspector/AddContextMemory/index.tsx",+ "packages/builtin-tool-memory/src/client/Inspector/AddExperienceMemory/index.tsx",+ "packages/builtin-tool-memory/src/client/Inspector/AddIdentityMemory/index.tsx",+ "packages/builtin-tool-memory/src/client/Inspector/AddPreferenceMemory/index.tsx",+ "packages/builtin-tool-memory/src/client/Inspector/RemoveIdentityMemory/index.tsx",+ "packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx",+ "packages/builtin-tool-memory/src/client/components/ExperienceMemoryCard.tsx",+ "packages/builtin-tool-memory/src/client/components/IdentityMemoryCard.tsx",+ "packages/builtin-tool-memory/src/client/components/MemoryCardParts.tsx",+ "packages/builtin-tool-memory/src/client/components/PreferenceMemoryCard.tsx",+ "packages/builtin-tool-memory/src/client/components/RemovedIdentityCard.tsx",+ "packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsx",+ "packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx",+ "packages/builtin-tool-page-agent/src/client/Inspector/ModifyNodes/index.tsx",+ "packages/builtin-tool-page-agent/src/client/Inspector/ReplaceText/index.tsx",+ "packages/builtin-tool-page-agent/src/client/Render/ModifyNodes/index.tsx",+ "packages/builtin-tool-page-agent/src/client/Streaming/InitPage/index.tsx",+ "packages/builtin-tool-remote-device/src/client/Inspector/ActivateDevice/index.tsx",+ "packages/builtin-tool-remote-device/src/client/Inspector/ListOnlineDevices/index.tsx",+ "packages/builtin-tool-remote-device/src/client/Render/ActivateDevice/index.tsx",+ "packages/builtin-tool-remote-device/src/client/Render/DeviceCard/index.tsx",+ "packages/builtin-tool-remote-device/src/client/Render/ListDevices/index.tsx",+ "packages/builtin-tool-self-iteration/src/client/Inspector/DeclareSelfFeedbackIntent/index.tsx",+ "packages/builtin-tool-skill-store/src/client/Inspector/ImportFromMarket/index.tsx",+ "packages/builtin-tool-skill-store/src/client/Inspector/ImportSkill/index.tsx",+ "packages/builtin-tool-skill-store/src/client/Render/SearchSkill/index.tsx",+ "packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx",+ "packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx",+ "packages/builtin-tool-skills/src/client/Render/ExecScript/index.tsx",+ "packages/builtin-tool-skills/src/client/Render/ReadReference/index.tsx",+ "packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/CreateTask/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/CreateTasks/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/RunTasks/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/TaskComment/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx",+ "packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx",+ "packages/builtin-tool-task/src/client/Intervention/CreateGoal.tsx",+ "packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx",+ "packages/builtin-tool-task/src/client/Render/CreateTasks/index.tsx",+ "packages/builtin-tool-task/src/client/Render/EditTask/index.tsx",+ "packages/builtin-tool-task/src/client/Render/RunTask/index.tsx",+ "packages/builtin-tool-task/src/client/Render/RunTasks/index.tsx",+ "packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx",+ "packages/builtin-tool-task/src/client/Render/shared.tsx",+ "packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.tsx",+ "packages/builtin-tool-video-generation/src/client/Inspector/index.tsx",+ "packages/builtin-tool-video-generation/src/client/Placeholder/GenerateVideo.tsx",+ "packages/builtin-tool-video-generation/src/client/Render/GenerateVideo.tsx",+ "packages/builtin-tool-video-generation/src/client/Render/GetVideoGenerationStatus.tsx",+ "packages/builtin-tool-video-generation/src/client/Render/GetVideoModelParameters.tsx",+ "packages/builtin-tool-video-generation/src/client/Render/ListVideoModels.tsx",+ "packages/builtin-tool-web-browsing/src/client/Placeholder/Search.tsx",+ "packages/builtin-tool-web-browsing/src/client/Portal/PageContent/index.tsx",+ "packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/Video.tsx",+ "packages/builtin-tool-web-browsing/src/client/Portal/Search/ResultList/SearchItem/index.tsx",+ "packages/builtin-tool-web-browsing/src/client/Render/PageContent/Loading.tsx",+ "packages/builtin-tool-web-browsing/src/client/Render/PageContent/Result.tsx",+ "packages/builtin-tool-web-browsing/src/client/Render/Search/ConfigForm/style.tsx",+ "packages/builtin-tool-web-browsing/src/client/Render/Search/SearchQuery/SearchView.tsx",+ "packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/SearchResultItem.tsx",+ "packages/builtin-tool-web-browsing/src/client/Render/Search/SearchResult/ShowMore.tsx",+ "packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx",+ "packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Inspector/_styles.ts",+ "packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Intervention/PickAgents/style.ts",+ "packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Render/SubmitAgentPick/index.tsx",+ "packages/builtin-tool-web-onboarding/src/client/Inspector/FinishOnboarding/index.tsx",+ "packages/builtin-tool-web-onboarding/src/client/Inspector/_styles.ts",+ "packages/builtin-tool-web-onboarding/src/client/Render/SaveUserQuestion/index.tsx",+ "packages/builtin-tool-web-onboarding/src/client/Render/UpdateDocument/HunkBlock.tsx",+ "packages/builtin-tool-web-onboarding/src/client/Render/WriteDocument/DocumentCard.tsx",+ "packages/builtin-tools/src/codex/CollabToolRender.tsx",+ "packages/builtin-tools/src/codex/ErrorInspector.tsx",+ "packages/builtin-tools/src/codex/FileChangeInspector.tsx",+ "packages/builtin-tools/src/codex/FileChangeRender.tsx",+ "packages/builtin-tools/src/codex/McpToolRender.tsx",+ "packages/builtin-tools/src/codex/WebSearchRender.tsx",+ "packages/builtin-tools/src/github/RunCommandInspector.tsx",+ "packages/builtin-tools/src/github/RunCommandRender.tsx",+ "packages/builtin-tools/src/notebook/DocumentCard.tsx",+ "packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionResult.tsx",+ "packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx",+ "packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx",+ "packages/shared-tool-ui/src/Inspector/EditLocalFile/index.tsx",+ "packages/shared-tool-ui/src/Inspector/GitHub/Inspector.tsx",+ "packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsx",+ "packages/shared-tool-ui/src/Inspector/GoalCommand/index.tsx",+ "packages/shared-tool-ui/src/Inspector/GrepContent/index.tsx",+ "packages/shared-tool-ui/src/Inspector/Linear/Inspector.tsx",+ "packages/shared-tool-ui/src/Inspector/RunCommand/index.tsx",+ "packages/shared-tool-ui/src/Inspector/Twitter/Inspector.tsx",+ "packages/shared-tool-ui/src/Render/GitHub/index.tsx",+ "packages/shared-tool-ui/src/Render/Linear/index.tsx",+ "packages/shared-tool-ui/src/Render/RunCommand/AnsiOutput.tsx",+ "packages/shared-tool-ui/src/Render/RunCommand/index.tsx",+ "packages/shared-tool-ui/src/components/FileChangeStats/index.tsx",+ "packages/shared-tool-ui/src/components/FilePathDisplay.tsx",+ "packages/shared-tool-ui/src/components/OptionCard.tsx",+ "packages/shared-tool-ui/src/components/TodoProgress/index.tsx",+ "packages/shared-tool-ui/src/styles.ts",+ "src/components/AsyncError/index.tsx",+ "src/components/AvatarUpload/index.tsx",+ "src/components/BrandWatermark/index.tsx",+ "src/components/Branding/ProductLogo/Custom.tsx",+ "src/components/Cell/Divider.tsx",+ "src/components/Cell/index.tsx",+ "src/components/ChangelogModal/VersionTag.tsx",+ "src/components/ChatGroupWizard/ChatGroupWizard.tsx",+ "src/components/CodeEditorPane/StatusBar.tsx",+ "src/components/CodeEditorPane/style.ts",+ "src/components/CollapsibleContent/index.tsx",+ "src/components/CommandLine/index.tsx",+ "src/components/CommentList/CommentItem.tsx",+ "src/components/DataStyleModal/index.tsx",+ "src/components/Descriptions/index.tsx",+ "src/components/DiscreteSlider/index.tsx",+ "src/components/DotsLoading/index.tsx",+ "src/components/DragUploadZone/index.tsx",+ "src/components/FileParsingStatus/EmbeddingStatus.tsx",+ "src/components/FileParsingStatus/index.tsx",+ "src/components/FormAction/index.tsx",+ "src/components/GalleyGrid/style.ts",+ "src/components/GeneratingBorder/index.tsx",+ "src/components/GuideModal/index.tsx",+ "src/components/HtmlPreview/HtmlDocumentFrame.tsx",+ "src/components/HtmlPreview/PreviewDrawer.tsx",+ "src/components/ImageItem/index.tsx",+ "src/components/InlineTable/index.tsx",+ "src/components/KeyValueEditor/index.tsx",+ "src/components/LibIcon/Locked.tsx",+ "src/components/LiteTable/index.tsx",+ "src/components/Loading/ContentLoading/index.tsx",+ "src/components/Loading/SkeletonLoading/index.tsx",+ "src/components/MemberSelectionModal/MemberSelectionModal.tsx",+ "src/components/Menu/index.tsx",+ "src/components/ModelSelect/index.tsx",+ "src/components/Notification/index.tsx",+ "src/components/PublishedTime.tsx",+ "src/components/RatingOverview/Rate.tsx",+ "src/components/Skeleton/AgentChannel.tsx",+ "src/components/Skeleton/AgentShare.tsx",+ "src/components/Skeleton/AgentStatistics.tsx",+ "src/components/Skeleton/AgentViewAll.tsx",+ "src/components/Skeleton/CommunityList.tsx",+ "src/components/Skeleton/Conversation/AgentLayout.tsx",+ "src/components/Skeleton/Conversation/Container.tsx",+ "src/components/Skeleton/Conversation/Segment.tsx",+ "src/components/Skeleton/Goal.tsx",+ "src/components/Skeleton/Profile.tsx",+ "src/components/Skeleton/ResourceHome.tsx",+ "src/components/Skeleton/Settings/MessengerDetail.tsx",+ "src/components/Skeleton/Settings/Profile.tsx",+ "src/components/Skeleton/Settings/Section.tsx",+ "src/components/Skeleton/Settings/Sections.tsx",+ "src/components/Skeleton/SkeletonSwitch.tsx",+ "src/components/Skeleton/Surface.tsx",+ "src/components/Skeleton/Topics.tsx",+ "src/components/SpendType/index.tsx",+ "src/components/StreamingMarkdown/index.tsx",+ "src/components/TablePagination/index.tsx",+ "src/components/TailMarquee/index.tsx",+ "src/components/TipGuide/index.tsx",+ "src/components/UnreadDot/index.tsx",+ "src/components/mdx/CollapsibleSection.tsx",+ "src/features/Acceptance/CriterionList/CriterionRow.tsx",+ "src/features/Acceptance/Report/EvidenceComparisonCard.tsx",+ "src/features/Acceptance/Report/InteractionCost.tsx",+ "src/features/Acceptance/Report/MarkdownEvidence.tsx",+ "src/features/Acceptance/Report/ReportViewer.tsx",+ "src/features/Acceptance/Report/VisualizationRenderer.tsx",+ "src/features/Acceptance/Run/CheckerDock.tsx",+ "src/features/Acceptance/Run/RunResult.tsx",+ "src/features/Acceptance/Viewer/AcceptanceOverview.tsx",+ "src/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory.tsx",+ "src/features/Acceptance/Viewer/Checks/styles.ts",+ "src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx",+ "src/features/Acceptance/Viewer/Comments/CommentComposer.tsx",+ "src/features/Acceptance/Viewer/Comments/CommentReactions.tsx",+ "src/features/Acceptance/Viewer/Comments/DiscussionAside.tsx",+ "src/features/Acceptance/Viewer/Comments/DiscussionEntries.tsx",+ "src/features/Acceptance/Viewer/Comments/EvidenceCommentModal.tsx",+ "src/features/Acceptance/Viewer/Comments/ReviewerApprovalBar.tsx",+ "src/features/Acceptance/Viewer/Comments/RoundSection.tsx",+ "src/features/Acceptance/Viewer/Comments/ThreadEvidence.tsx",+ "src/features/Acceptance/Viewer/Comments/styles.ts",+ "src/features/Acceptance/Viewer/Conversation/AcceptanceOriginTopic.tsx",+ "src/features/Acceptance/Viewer/Evidence/AcceptanceResources.tsx",+ "src/features/Acceptance/Viewer/Evidence/Annotation.tsx",+ "src/features/Acceptance/Viewer/Evidence/DesktopEvidenceReview.tsx",+ "src/features/Acceptance/Viewer/Evidence/EvidenceStage.tsx",+ "src/features/Acceptance/Viewer/Evidence/FloatingCommentAction.tsx",+ "src/features/Acceptance/Viewer/Evidence/MobileEvidenceReview.tsx",+ "src/features/Acceptance/Viewer/Evidence/RegionNotes.tsx",+ "src/features/Acceptance/Viewer/Evidence/ScreenshotTiles.tsx",+ "src/features/Acceptance/Viewer/Evidence/Video/ReviewTools.tsx",+ "src/features/Acceptance/Viewer/Evidence/Video/VideoClaimList.tsx",+ "src/features/Acceptance/Viewer/Evidence/Video/VideoNotes.tsx",+ "src/features/Acceptance/Viewer/Evidence/Video/VideoReviewStage.tsx",+ "src/features/Acceptance/Viewer/Evidence/Video/styles.ts",+ "src/features/Acceptance/Viewer/Evidence/attachments.tsx",+ "src/features/Acceptance/Viewer/Evidence/styles.ts",+ "src/features/Acceptance/Viewer/Flow/AcceptanceFlow.tsx",+ "src/features/Acceptance/Viewer/Flow/FlowCanvas.tsx",+ "src/features/Acceptance/Viewer/Flow/FlowEdge.tsx",+ "src/features/Acceptance/Viewer/Flow/FlowGroup.tsx",+ "src/features/Acceptance/Viewer/Flow/FlowNode.tsx",+ "src/features/Acceptance/Viewer/Flow/FlowOutline.tsx",+ "src/features/Acceptance/Viewer/Flow/FlowResults.tsx",+ "src/features/Acceptance/Viewer/Flow/FlowVersionDiff.tsx",+ "src/features/Acceptance/Viewer/Focus/AcceptanceEnterFocus.tsx",+ "src/features/Acceptance/Viewer/Focus/AcceptanceFocusReview.tsx",+ "src/features/Acceptance/Viewer/Gate/GateReview.tsx",+ "src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx",+ "src/features/Acceptance/Viewer/Header/AcceptanceGoal.tsx",+ "src/features/Acceptance/Viewer/Header/AcceptanceIdentity.tsx",+ "src/features/Acceptance/Viewer/Header/AcceptanceStatusPill.tsx",+ "src/features/Acceptance/Viewer/Header/AcceptanceTabs.tsx",+ "src/features/Acceptance/Viewer/Header/PreviewReviewLink.tsx",+ "src/features/Acceptance/Viewer/Header/PullRequestLinks.tsx",+ "src/features/Acceptance/Viewer/History/AcceptanceInteractionCost.tsx",+ "src/features/Acceptance/Viewer/History/AcceptanceLedgerRail.tsx",+ "src/features/Acceptance/Viewer/History/AcceptanceViewReportLink.tsx",+ "src/features/Acceptance/Viewer/History/LedgerPanel.tsx",+ "src/features/Acceptance/Viewer/ReadOnly/Checks.tsx",+ "src/features/Acceptance/Viewer/Review/DecisionBar.tsx",+ "src/features/Acceptance/Viewer/Review/FeedbackDrawer.tsx",+ "src/features/Acceptance/Viewer/Review/ProposalCard.tsx",+ "src/features/Acceptance/Viewer/Review/RejectFeedbackPreview.tsx",+ "src/features/Acceptance/Viewer/Review/modals.tsx",+ "src/features/Acceptance/Viewer/Review/rejectModalShell.ts",+ "src/features/Acceptance/Viewer/index.tsx",+ "src/features/Acceptance/Workspace/AcceptanceBatchBar.tsx",+ "src/features/Acceptance/Workspace/AcceptanceDeleteConfirm.tsx",+ "src/features/Acceptance/Workspace/AcceptanceListPanel.tsx",+ "src/features/Acceptance/Workspace/AcceptanceOnboarding.tsx",+ "src/features/Acceptance/Workspace/AcceptanceRow.tsx",+ "src/features/Acceptance/Workspace/MergeAcceptanceModal.tsx",+ "src/features/Acceptance/Workspace/index.tsx",+ "src/features/AgentBreadcrumb/index.tsx",+ "src/features/AgentBuilder/TopicSelector.tsx",+ "src/features/AgentChannel/PlatformCard.tsx",+ "src/features/AgentChannel/PlatformDetail/Body.tsx",+ "src/features/AgentChannel/PlatformDetail/ComingSoon.tsx",+ "src/features/AgentChannel/PlatformDetail/Footer.tsx",+ "src/features/AgentChannel/PlatformDetail/index.tsx",+ "src/features/AgentChannel/PlatformGrid.tsx",+ "src/features/AgentChannel/platform/imessage/CredentialExtras.tsx",+ "src/features/AgentChannel/platform/wechat/ConnectedInfo.tsx",+ "src/features/AgentChannel/platform/wechat/QrCodeAuth.tsx",+ "src/features/AgentChannel/quickSetup/FeishuQuickCreate.tsx",+ "src/features/AgentChannel/quickSetup/QuickSetupSection.tsx",+ "src/features/AgentChannel/quickSetup/SetupGuide.tsx",+ "src/features/AgentDocumentPage/RightPanel/index.tsx",+ "src/features/AgentDocumentReader/index.tsx",+ "src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx",+ "src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx",+ "src/features/AgentGoals/AgentGoalsPage.tsx",+ "src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx",+ "src/features/AgentGoals/GoalAcceptanceCriteria.tsx",+ "src/features/AgentGoals/GoalAgentFilter.tsx",+ "src/features/AgentGoals/GoalAgentLabel.tsx",+ "src/features/AgentGoals/GoalCardItem.tsx",+ "src/features/AgentGoals/GoalDecision/index.tsx",+ "src/features/AgentGoals/GoalDetailPage.tsx",+ "src/features/AgentGoals/GoalEmptyState.tsx",+ "src/features/AgentGoals/GoalHeaderMetrics.tsx",+ "src/features/AgentGoals/GoalHowItWorksModal/HowItWorksContent.tsx",+ "src/features/AgentGoals/GoalListItem.tsx",+ "src/features/AgentGoals/GoalProgress.tsx",+ "src/features/AgentGoals/NorthStarMetrics/index.tsx",+ "src/features/AgentGoals/ProcessControl/Activity.tsx",+ "src/features/AgentGoals/ProcessControl/BatchGate/GateChecksHint.tsx",+ "src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx",+ "src/features/AgentGoals/ProcessControl/BatchPlan/PlanCompareModal.tsx",+ "src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx",+ "src/features/AgentGoals/ProcessControl/DeliverableReader.tsx",+ "src/features/AgentGoals/ProcessControl/Deliverables.tsx",+ "src/features/AgentGoals/ProcessControl/Findings.tsx",+ "src/features/AgentGoals/ProcessControl/Frontier.tsx",+ "src/features/AgentGoals/ProcessControl/GoalAcceptanceHierarchy.tsx",+ "src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx",+ "src/features/AgentGoals/ProcessControl/GoalFollowUpComposer.tsx",+ "src/features/AgentGoals/ProcessControl/GoalReportPage.tsx",+ "src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx",+ "src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx",+ "src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx",+ "src/features/AgentGoals/ProcessControl/Graph/ExperimentGroup.tsx",+ "src/features/AgentGoals/ProcessControl/Graph/GraphLegend.tsx",+ "src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx",+ "src/features/AgentGoals/ProcessControl/Graph/index.tsx",+ "src/features/AgentGoals/ProcessControl/ResultAnchorRail.tsx",+ "src/features/AgentGoals/ProcessControl/ResultDeliverables.tsx",+ "src/features/AgentGoals/ProcessControl/ResultTrail.tsx",+ "src/features/AgentGoals/ProcessControl/shared.tsx",+ "src/features/AgentHome/OpeningQuestions.tsx",+ "src/features/AgentHome/StagedProjectHint.tsx",+ "src/features/AgentMockDevtools/CaseTrigger.tsx",+ "src/features/AgentMockDevtools/Controls.tsx",+ "src/features/AgentMockDevtools/index.tsx",+ "src/features/AgentPermission/PermissionForm.tsx",+ "src/features/AgentProfileArtwork/index.tsx",+ "src/features/AgentProfileCard/AgentProfilePopup.tsx",+ "src/features/AgentProfileCard/index.tsx",+ "src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx",+ "src/features/AgentSetting/AgentGraphRuntime/index.tsx",+ "src/features/AgentSetting/AgentOpening/OpeningMessage.tsx",+ "src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx",+ "src/features/AgentSetting/SettingsModalLayout.tsx",+ "src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx",+ "src/features/AgentSidebar/Topic/List/Item/index.tsx",+ "src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx",+ "src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/CollapsedIndicators.tsx",+ "src/features/AgentSidebar/Topic/useDropdownMenu.tsx",+ "src/features/AgentSkillDetail/ContentViewer.tsx",+ "src/features/AgentSkillDetail/index.tsx",+ "src/features/AgentSkillEdit/SkillEditForm.tsx",+ "src/features/AgentSkillEdit/index.tsx",+ "src/features/AgentTaskManager/AgentSelectorAction.tsx",+ "src/features/AgentTasks/AgentTaskDetail/GoalRoundPopover.tsx",+ "src/features/AgentTasks/AgentTaskDetail/GoalRoundTimeline.tsx",+ "src/features/AgentTasks/AgentTaskDetail/PendingAcceptanceCheckList.tsx",+ "src/features/AgentTasks/AgentTaskDetail/RunVerifyDetail.tsx",+ "src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx",+ "src/features/AgentTasks/AgentTaskDetail/TaskDetailSkeleton.tsx",+ "src/features/AgentTasks/AgentTaskDetail/TaskScheduleConfig.tsx",+ "src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx",+ "src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx",+ "src/features/AgentTasks/AgentTaskDetail/taskDetailLayoutStyles.ts",+ "src/features/AgentTasks/AgentTaskList/EmptyState.tsx",+ "src/features/AgentTasks/AgentTaskList/HiddenColumnsPanel.tsx",+ "src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx",+ "src/features/AgentTasks/AgentTaskList/KanbanColumn.tsx",+ "src/features/AgentTasks/AgentTaskList/TaskIntentReview.tsx",+ "src/features/AgentTasks/AgentTaskList/TaskRowIndent.tsx",+ "src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx",+ "src/features/AgentTasks/CreateTaskModal/ScheduleChip.tsx",+ "src/features/AgentTasks/features/AssigneeAgentSelector.tsx",+ "src/features/AgentTasks/features/AssigneeMemberSelector.tsx",+ "src/features/AgentTasks/features/TaskPriorityTag.tsx",+ "src/features/AgentTasks/features/TaskStatusCascadeModal.tsx",+ "src/features/AgentTasks/features/TaskStatusTag.tsx",+ "src/features/AgentTasks/features/TaskVisibilityTag.tsx",+ "src/features/AgentTasks/features/taskExecutionStyles.ts",+ "src/features/AgentTasks/shared/style.ts",+ "src/features/AgentTopicManager/BulkActionBar.tsx",+ "src/features/AgentTopicManager/MoveTopicsModal/Content.tsx",+ "src/features/AgentTopicManager/Toolbar.tsx",+ "src/features/AgentTopicManager/TopicCard.tsx",+ "src/features/AgentTopicManager/TopicGrid.tsx",+ "src/features/AgentTopicManager/TopicListView.tsx",+ "src/features/AgentTransferMigration/MigrationBanner.tsx",+ "src/features/AgentViewAll/AgentCard.tsx",+ "src/features/AgentViewAll/AgentRow.tsx",+ "src/features/AgentViewAll/AgentViewAllPage.tsx",+ "src/features/AgentViewAll/LabelTags.tsx",+ "src/features/AgentViewAll/ListConfig.tsx",+ "src/features/AgentViewAll/SidebarAgentsSection.tsx",+ "src/features/AlertBanner/CloudBanner.tsx",+ "src/features/Apps/style.ts",+ "src/features/ArtworkStudio/Content.tsx",+ "src/features/AttachmentInput/AttachmentMenu.tsx",+ "src/features/AudioPlayer/index.tsx",+ "src/features/Auth/OAuthConsent/OAuthApplicationLogo.tsx",+ "src/features/Auth/SignIn/SignInEmailStep.tsx",+ "src/features/AuthShell/AuthAgreement.tsx",+ "src/features/AuthShell/AuthFooterLinks.tsx",+ "src/features/AuthShell/style.ts",+ "src/features/BackgroundActivity/ActivityTable.tsx",+ "src/features/BackgroundActivity/ProcessExplorer/style.ts",+ "src/features/BackgroundActivity/TopicSection.tsx",+ "src/features/Billboard/Carousel.tsx",+ "src/features/ChatInput/ActionBar/AgentMode/index.tsx",+ "src/features/ChatInput/ActionBar/Knowledge/useControls.tsx",+ "src/features/ChatInput/ActionBar/Memory/Controls.tsx",+ "src/features/ChatInput/ActionBar/Model/SelectorMenu.tsx",+ "src/features/ChatInput/ActionBar/Params/Controls.tsx",+ "src/features/ChatInput/ActionBar/Plus/index.tsx",+ "src/features/ChatInput/ActionBar/Search/Controls.tsx",+ "src/features/ChatInput/ActionBar/Search/FCSearchModel.tsx",+ "src/features/ChatInput/ActionBar/Search/FunctionCallingModelSelect/index.tsx",+ "src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx",+ "src/features/ChatInput/ActionBar/Tools/ToolItemDetailPopover.tsx",+ "src/features/ChatInput/ActionBar/Tools/ToolsList.tsx",+ "src/features/ChatInput/ActionBar/Tools/useControls.tsx",+ "src/features/ChatInput/ActionBar/Upload/index.tsx",+ "src/features/ChatInput/ActionBar/components/ActionDropdown.tsx",+ "src/features/ChatInput/ActionBar/components/ActionPopover.tsx",+ "src/features/ChatInput/ChatInputNotice/Content.tsx",+ "src/features/ChatInput/ControlBar/ApprovalMode.tsx",+ "src/features/ChatInput/ControlBar/BranchSwitcher.tsx",+ "src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx",+ "src/features/ChatInput/ControlBar/DeviceOptionRow.tsx",+ "src/features/ChatInput/ControlBar/GitStatus.tsx",+ "src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx",+ "src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx",+ "src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx",+ "src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx",+ "src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx",+ "src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx",+ "src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx",+ "src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx",+ "src/features/ChatInput/ControlBar/ModeSelector.tsx",+ "src/features/ChatInput/ControlBar/OptionRow.tsx",+ "src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx",+ "src/features/ChatInput/ControlBar/SandboxEnvironmentRow.tsx",+ "src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx",+ "src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx",+ "src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx",+ "src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx",+ "src/features/ChatInput/ControlBar/gitChipStyles.ts",+ "src/features/ChatInput/ControlBar/gitMenuTriggerStyles.ts",+ "src/features/ChatInput/ControlBar/index.tsx",+ "src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts",+ "src/features/ChatInput/Desktop/ContextContainer/ContextItem/Content.tsx",+ "src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx",+ "src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx",+ "src/features/ChatInput/Desktop/ContextContainer/ElementItem.tsx",+ "src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx",+ "src/features/ChatInput/Desktop/index.tsx",+ "src/features/ChatInput/Dictation/index.tsx",+ "src/features/ChatInput/InputEditor/ActionTag/style.ts",+ "src/features/ChatInput/InputEditor/InputHistoryPopup.tsx",+ "src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx",+ "src/features/ChatInput/InputEditor/index.tsx",+ "src/features/ChatInput/InputEditor/mentionStyle.ts",+ "src/features/ChatInput/Mobile/FilePreview/FileItem/File.tsx",+ "src/features/ChatInput/Mobile/FilePreview/FileItem/Image.tsx",+ "src/features/ChatInput/Mobile/FilePreview/index.tsx",+ "src/features/ChatInput/Mobile/index.tsx",+ "src/features/ChatInput/VoiceMessage/index.tsx",+ "src/features/ChatInput/components/SelectorTrigger.tsx",+ "src/features/ChatInput/components/UploadDetail/index.tsx",+ "src/features/ChatInput/components/buildSelectorSubmenu.tsx",+ "src/features/ChatMiniMap/styles.ts",+ "src/features/ChatTerminal/Content.tsx",+ "src/features/ChatTerminal/SplitView.tsx",+ "src/features/CommandMenu/styles.ts",+ "src/features/CommunitySkillDetail/Details/Info/index.tsx",+ "src/features/CommunitySkillDetail/Details/Install/Platform.tsx",+ "src/features/CommunitySkillDetail/Details/Install/index.tsx",+ "src/features/CommunitySkillDetail/Details/Nav.tsx",+ "src/features/CommunitySkillDetail/Details/Overview/RelatedSkillCard.tsx",+ "src/features/CommunitySkillDetail/Details/Overview/index.tsx",+ "src/features/CommunitySkillDetail/Header.tsx",+ "src/features/CommunityWorkspaceSettings/index.tsx",+ "src/features/ConnectAgent/index.tsx",+ "src/features/Connectors/ConnectorDetail/ToolPermissionGroup.tsx",+ "src/features/Connectors/ConnectorDetail/ToolPermissionRow.tsx",+ "src/features/Connectors/ConnectorList/ConnectorItem.tsx",+ "src/features/Conversation/AgentWelcome/ToolAuthAlert.tsx",+ "src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx",+ "src/features/Conversation/ChatInput/OpStatusTray.tsx",+ "src/features/Conversation/ChatInput/QueueTray.tsx",+ "src/features/Conversation/ChatItem/components/ErrorContent.tsx",+ "src/features/Conversation/ChatItem/components/MessageContent/index.tsx",+ "src/features/Conversation/ChatItem/style.ts",+ "src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx",+ "src/features/Conversation/ChatList/components/BackBottom/style.ts",+ "src/features/Conversation/ChatList/components/RefreshError.tsx",+ "src/features/Conversation/Error/PlanLimitCard/index.tsx",+ "src/features/Conversation/Error/style.tsx",+ "src/features/Conversation/FollowUp/style.ts",+ "src/features/Conversation/InterventionBar/UserInterventionErrorBoundary.tsx",+ "src/features/Conversation/InterventionBar/style.ts",+ "src/features/Conversation/Markdown/plugins/FileLink/Render.tsx",+ "src/features/Conversation/Markdown/plugins/GoalTurn/Render.tsx",+ "src/features/Conversation/Markdown/plugins/ImageSearchRef/Render.tsx",+ "src/features/Conversation/Markdown/plugins/LobeAgents/Render/index.tsx",+ "src/features/Conversation/Markdown/plugins/LobeArtifact/Render/index.tsx",+ "src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx",+ "src/features/Conversation/Markdown/plugins/Mention/Render.tsx",+ "src/features/Conversation/Markdown/plugins/ScmEvent/Render.tsx",+ "src/features/Conversation/Markdown/plugins/Task/Render.tsx",+ "src/features/Conversation/Markdown/plugins/UserFeedback/Render.tsx",+ "src/features/Conversation/MessageForward/ForwardModal.tsx",+ "src/features/Conversation/MessageForward/MessageSelectionWrapper.tsx",+ "src/features/Conversation/MessageForward/SelectCircle.tsx",+ "src/features/Conversation/MessageForward/SelectToHereButton.tsx",+ "src/features/Conversation/MessageForward/SelectionFooterBar.tsx",+ "src/features/Conversation/MessageForward/TopicForwardModal/Content.tsx",+ "src/features/Conversation/Messages/AgentCouncil/components/ScrollShadowWithButton.tsx",+ "src/features/Conversation/Messages/Assistant/components/InterruptedHint.tsx",+ "src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx",+ "src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx",+ "src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/KeyValueEditor.tsx",+ "src/features/Conversation/Messages/AssistantGroup/Tool/Detail/RejectedResponse.tsx",+ "src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx",+ "src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx",+ "src/features/Conversation/Messages/AssistantGroup/components/Group.tsx",+ "src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx",+ "src/features/Conversation/Messages/AssistantGroup/components/ProcessFold.tsx",+ "src/features/Conversation/Messages/AssistantGroup/components/SteerMessage.tsx",+ "src/features/Conversation/Messages/CompressedGroup/index.tsx",+ "src/features/Conversation/Messages/EditedFilesCard/index.tsx",+ "src/features/Conversation/Messages/GoalTaskCard/PlanChain.tsx",+ "src/features/Conversation/Messages/GoalTaskCard/StageTrack.tsx",+ "src/features/Conversation/Messages/GoalTaskCard/index.tsx",+ "src/features/Conversation/Messages/MessageWorks/index.tsx",+ "src/features/Conversation/Messages/SignalCallbacks/index.tsx",+ "src/features/Conversation/Messages/Task/ClientTaskDetail/InitializingState.tsx",+ "src/features/Conversation/Messages/TaskCallback/index.tsx",+ "src/features/Conversation/Messages/Tasks/shared/CompletedState.tsx",+ "src/features/Conversation/Messages/Tasks/shared/ErrorState.tsx",+ "src/features/Conversation/Messages/Tasks/shared/InitializingState.tsx",+ "src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx",+ "src/features/Conversation/Messages/Tasks/shared/TaskMessages.tsx",+ "src/features/Conversation/Messages/User/components/AgentSenderSourceLink.tsx",+ "src/features/Conversation/Messages/User/components/PageSelections.tsx",+ "src/features/Conversation/Messages/User/components/ReferencedMessage.tsx",+ "src/features/Conversation/Messages/User/components/ScmEventSender.tsx",+ "src/features/Conversation/Messages/User/components/richTextImageRenderers.tsx",+ "src/features/Conversation/Messages/Verify/index.tsx",+ "src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/ModelCard.tsx",+ "src/features/Conversation/Messages/components/Extras/Usage/index.tsx",+ "src/features/Conversation/Messages/components/FileChunks/index.tsx",+ "src/features/Conversation/Messages/components/FileChunks/style.ts",+ "src/features/Conversation/Messages/components/MessageBranch.tsx",+ "src/features/Conversation/Messages/components/SearchGrounding.tsx",+ "src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx",+ "src/features/Conversation/Messages/index.tsx",+ "src/features/Conversation/SplitDropZone/index.tsx",+ "src/features/Conversation/TodoProgress/index.tsx",+ "src/features/Conversation/WorkingSidebar/Browser/index.tsx",+ "src/features/Conversation/WorkingSidebar/Files/index.tsx",+ "src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.tsx",+ "src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx",+ "src/features/Conversation/WorkingSidebar/Overview/OverviewHeader.tsx",+ "src/features/Conversation/WorkingSidebar/Overview/OverviewRow.tsx",+ "src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx",+ "src/features/Conversation/WorkingSidebar/Overview/index.tsx",+ "src/features/Conversation/WorkingSidebar/Overview/sectionStyles.ts",+ "src/features/Conversation/WorkingSidebar/ProgressSection/index.tsx",+ "src/features/Conversation/WorkingSidebar/PullRequest/ActivityTimeline.tsx",+ "src/features/Conversation/WorkingSidebar/PullRequest/ChecksList.tsx",+ "src/features/Conversation/WorkingSidebar/PullRequest/DockActionButton.tsx",+ "src/features/Conversation/WorkingSidebar/PullRequest/Head.tsx",+ "src/features/Conversation/WorkingSidebar/PullRequest/MergeDock.tsx",+ "src/features/Conversation/WorkingSidebar/PullRequest/Sections.tsx",+ "src/features/Conversation/WorkingSidebar/PullRequest/Skeleton.tsx",+ "src/features/Conversation/WorkingSidebar/PullRequest/index.tsx",+ "src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx",+ "src/features/Conversation/WorkingSidebar/Review/FileItem.tsx",+ "src/features/Conversation/WorkingSidebar/Review/FileRow.tsx",+ "src/features/Conversation/WorkingSidebar/Review/FileTreeNav.tsx",+ "src/features/Conversation/WorkingSidebar/Review/GroupHeader.tsx",+ "src/features/Conversation/WorkingSidebar/Review/index.tsx",+ "src/features/Conversation/WorkingSidebar/WorksSection/VersionList.tsx",+ "src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx",+ "src/features/Conversation/WorkingSidebar/WorksSection/index.tsx",+ "src/features/Conversation/WorkingSidebar/WorkspaceTab.tsx",+ "src/features/Conversation/WorkingSidebar/index.tsx",+ "src/features/Conversation/Workspace/index.tsx",+ "src/features/Conversation/components/History/index.tsx",+ "src/features/Conversation/components/PortalResourceCard/index.tsx",+ "src/features/Conversation/components/Reaction/ReactionDisplay.tsx",+ "src/features/Conversation/components/Reaction/ReactionPicker.tsx",+ "src/features/Conversation/components/ShareMessageModal/style.ts",+ "src/features/Conversation/components/Thinking/index.tsx",+ "src/features/DailyBrief/BriefCardArtifacts.tsx",+ "src/features/DailyBrief/SelfReviewBriefDetails.tsx",+ "src/features/DailyBrief/SelfReviewProposalModal/ProposalContent.tsx",+ "src/features/DailyBrief/style.ts",+ "src/features/Dashboard/Board/BoardHeader.tsx",+ "src/features/Dashboard/Board/style.ts",+ "src/features/Dashboard/ErrorLine.tsx",+ "src/features/Dashboard/List/DashboardListCard.tsx",+ "src/features/Dashboard/WidgetCard/HealthDot.tsx",+ "src/features/Dashboard/WidgetCard/index.tsx",+ "src/features/Dashboard/WidgetCard/views/ListView.tsx",+ "src/features/Dashboard/WidgetCard/views/StatView.tsx",+ "src/features/Dashboard/WidgetCard/views/TableView.tsx",+ "src/features/Dashboard/WidgetDetail/RunHistory.tsx",+ "src/features/Dashboard/WidgetDetail/RunLogs.tsx",+ "src/features/Dashboard/WidgetDetail/VersionList.tsx",+ "src/features/Dashboard/WidgetDetail/index.tsx",+ "src/features/Dashboard/WidgetPreview/ReviewFacts.tsx",+ "src/features/Dashboard/WidgetPreview/index.tsx",+ "src/features/Dashboard/pageStyles.ts",+ "src/features/DataImporter/ImportDetail.tsx",+ "src/features/DataImporter/Loading.tsx",+ "src/features/DataImporter/SuccessResult.tsx",+ "src/features/DataImporter/index.tsx",+ "src/features/DesktopLayoutContainer/style.ts",+ "src/features/DesktopOnboarding/Layout/index.tsx",+ "src/features/DesktopOnboarding/Layout/style.ts",+ "src/features/DevDock/Bar.tsx",+ "src/features/DevDock/OverflowMenu.tsx",+ "src/features/DevDock/PanelHost.tsx",+ "src/features/DevDock/panelStyles.ts",+ "src/features/DevDock/widgets/BarButton.tsx",+ "src/features/DevDock/widgets/ClsWidget.tsx",+ "src/features/DevDock/widgets/CpuPressureWidget.tsx",+ "src/features/DevDock/widgets/CpuUsageWidget.tsx",+ "src/features/DevDock/widgets/FpsWidget.tsx",+ "src/features/DevDock/widgets/GpuProcessWidget.tsx",+ "src/features/DevDock/widgets/MemoryPopover/styles.ts",+ "src/features/DevDock/widgets/MemoryWidget.tsx",+ "src/features/DevDock/widgets/RoutePathWidget.tsx",+ "src/features/DevFeatureFlagPanel/Badge.tsx",+ "src/features/DevFeatureFlagPanel/FlagRow.tsx",+ "src/features/DevFeatureFlagPanel/Panel.tsx",+ "src/features/DevPanel/GpuStatus/index.tsx",+ "src/features/DevPanel/RenderGallery/ApiList.tsx",+ "src/features/DevPanel/RenderGallery/MessageList.tsx",+ "src/features/DevPanel/RenderGallery/Sidebar.tsx",+ "src/features/DevPanel/RenderGallery/ToolPage.tsx",+ "src/features/DevPanel/RenderGallery/ToolPreview.tsx",+ "src/features/DevPanel/RenderGallery/index.tsx",+ "src/features/DevPanel/RenderGallery/toolSurfaces.tsx",+ "src/features/DevPanel/Replica/styles.ts",+ "src/features/DevPanel/TabRouters/index.tsx",+ "src/features/DevPanel/inspectorStyles.ts",+ "src/features/DeviceManager/AgentRuntimes/index.tsx",+ "src/features/DeviceManager/DeviceActivity/RunningUsers.tsx",+ "src/features/DeviceManager/DeviceActivity/index.tsx",+ "src/features/DeviceManager/DeviceCard.tsx",+ "src/features/DeviceManager/DeviceConnectModal.tsx",+ "src/features/DeviceManager/DeviceDetail.tsx",+ "src/features/DeviceManager/DeviceGrid.tsx",+ "src/features/DeviceManager/DeviceHealth/UsageMeter.tsx",+ "src/features/DeviceManager/DeviceHoverPanel.tsx",+ "src/features/DeviceManager/DeviceManager.tsx",+ "src/features/DeviceManager/DeviceOverview.tsx",+ "src/features/DeviceManager/PresenceDot.tsx",+ "src/features/DeviceManager/ShareDeviceModal.tsx",+ "src/features/DeviceManager/Skeleton.tsx",+ "src/features/DocumentModal/Header.tsx",+ "src/features/EditorCanvas/DiffAllToolbar.tsx",+ "src/features/EditorCanvas/InternalEditor.tsx",+ "src/features/EditorCanvas/LinearFilePlugin.tsx",+ "src/features/Electron/HeterogeneousAgent/StatusGuide/states/OverloadedState.tsx",+ "src/features/Electron/TabHost/TabHost.tsx",+ "src/features/Electron/connection/DeviceGateway.tsx",+ "src/features/Electron/system/LinkHoverStatus/index.tsx",+ "src/features/Electron/system/ZoomHUD/index.tsx",+ "src/features/Electron/titlebar/NavigationBar.tsx",+ "src/features/Electron/titlebar/RecentlyViewed/styles.ts",+ "src/features/Electron/titlebar/TabBar/styles.ts",+ "src/features/Electron/titlebar/WinControl.tsx",+ "src/features/Electron/titlebar/WindowsAppMenu.tsx",+ "src/features/Electron/updater/UpdateNotification.tsx",+ "src/features/EntityLink/Render/InternalEntityLink.tsx",+ "src/features/EntityLink/Render/InternalEntityPreview.tsx",+ "src/features/EntityLink/Render/LinkChip.tsx",+ "src/features/EnvironmentManager/CreateEnvironmentModal.tsx",+ "src/features/EnvironmentManager/EnvironmentDetailPanel.tsx",+ "src/features/EnvironmentManager/EnvironmentForm.tsx",+ "src/features/EnvironmentManager/EnvironmentItem.tsx",+ "src/features/EnvironmentManager/EnvironmentVariables.tsx",+ "src/features/EnvironmentManager/GithubRepositoryPicker.tsx",+ "src/features/EnvironmentManager/InlineField.tsx",+ "src/features/EnvironmentManager/InstanceFileBrowser.tsx",+ "src/features/EnvironmentManager/InstanceList.tsx",+ "src/features/EnvironmentManager/PanelSection.tsx",+ "src/features/EnvironmentManager/SessionHistorySection.tsx",+ "src/features/EnvironmentManager/WorkspaceUsageMeter.tsx",+ "src/features/EnvironmentManager/index.tsx",+ "src/features/EvalCapture/CaptureContent.tsx",+ "src/features/EvalCapture/CaptureSuccess.tsx",+ "src/features/ExecutionTargetPicker/index.tsx",+ "src/features/ExplorerTree/view/NameInputHint.tsx",+ "src/features/FileTree/index.tsx",+ "src/features/FileViewer/NotSupport/index.tsx",+ "src/features/FileViewer/Renderer/Code/index.tsx",+ "src/features/FileViewer/Renderer/Document/DocxPane.tsx",+ "src/features/FileViewer/Renderer/Document/OfficeOnlinePane.tsx",+ "src/features/FileViewer/Renderer/Document/PaneFooter.tsx",+ "src/features/FileViewer/Renderer/Document/PptxPane.tsx",+ "src/features/FileViewer/Renderer/Document/index.tsx",+ "src/features/FileViewer/Renderer/Document/xlsx/SheetGrid.tsx",+ "src/features/FileViewer/Renderer/Document/xlsx/XlsxPane.tsx",+ "src/features/FileViewer/Renderer/Document/xlsx/styles.ts",+ "src/features/FileViewer/Renderer/HTML/index.tsx",+ "src/features/FileViewer/Renderer/Image/Tools/AIEdit/index.tsx",+ "src/features/FileViewer/Renderer/Image/Tools/Comment/CommentMarkers.tsx",+ "src/features/FileViewer/Renderer/Image/Tools/Comment/index.tsx",+ "src/features/FileViewer/Renderer/Image/Tools/Resize/index.tsx",+ "src/features/FileViewer/Renderer/Image/Tools/styles.ts",+ "src/features/FileViewer/Renderer/Image/TopBar.tsx",+ "src/features/FileViewer/Renderer/Image/VersionSwitcher.tsx",+ "src/features/FileViewer/Renderer/Image/index.tsx",+ "src/features/FileViewer/Renderer/Markdown/index.tsx",+ "src/features/FileViewer/Renderer/PDF/style.ts",+ "src/features/FileViewer/Renderer/Video/index.tsx",+ "src/features/FloatingChatPanel/HoverExpandBar.tsx",+ "src/features/FloatingChatPanel/InputRow.tsx",+ "src/features/FloatingChatPanel/index.tsx",+ "src/features/GlobalApprovalNotification/styles.ts",+ "src/features/GroupPermission/GroupBreadcrumb.tsx",+ "src/features/GroupPermission/PermissionForm.tsx",+ "src/features/HeteroSessionImport/Content.tsx",+ "src/features/HeteroSessionImport/SessionList.tsx",+ "src/features/HeteroSessionImport/SidebarTree.tsx",+ "src/features/HeterogeneousAgent/modelPicker.tsx",+ "src/features/Home/AgentSelect/AgentList.tsx",+ "src/features/Home/AgentSelect/index.tsx",+ "src/features/Home/CustomizeModal/Content.tsx",+ "src/features/Home/CustomizeModal/components/CountStepper.tsx",+ "src/features/Home/EmptySuggestions.tsx",+ "src/features/Home/GreetingLine.tsx",+ "src/features/Home/HomeHeader.tsx",+ "src/features/Home/HomeModeContent.tsx",+ "src/features/Home/HomeNavHeader.tsx",+ "src/features/Home/HomePortrait.tsx",+ "src/features/Home/InputArea/InputBanner.tsx",+ "src/features/Home/InputArea/InputDragUpload.tsx",+ "src/features/Home/InputArea/InputFallback.tsx",+ "src/features/Home/InputArea/MessengerBanner.tsx",+ "src/features/Home/InputArea/ModeSelect.tsx",+ "src/features/Home/InputArea/index.tsx",+ "src/features/Home/NewModelShortcuts/index.tsx",+ "src/features/Home/PortraitBubble/index.tsx",+ "src/features/Home/RailToggle.tsx",+ "src/features/Home/components/CountBadge.tsx",+ "src/features/Home/components/GroupBlock/index.tsx",+ "src/features/Home/components/RailCard/index.tsx",+ "src/features/Home/components/homeType.ts",+ "src/features/Home/index.tsx",+ "src/features/HomeInbox/AuthorChip.tsx",+ "src/features/HomeInbox/GoalsRailCard.tsx",+ "src/features/HomeInbox/InboxBriefCard.tsx",+ "src/features/HomeInbox/NeedsYouRailCard.tsx",+ "src/features/HomeInbox/NewsList.tsx",+ "src/features/HomeInbox/RunningTasksCard.tsx",+ "src/features/HomeInbox/TopicRow.tsx",+ "src/features/HomeInbox/UnreadTopicList.tsx",+ "src/features/HomeInbox/index.tsx",+ "src/features/HomeLayout/style.ts",+ "src/features/HomeSidebar/Body/Agent/CreateAgentButton.tsx",+ "src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx",+ "src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx",+ "src/features/HomeSidebar/Body/Agent/List/InboxItem.tsx",+ "src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/GroupItem.tsx",+ "src/features/HomeSidebar/Body/Agent/Modals/ConfigGroupModal/index.tsx",+ "src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx",+ "src/features/HomeSidebar/Header/components/InboxModal/Content.tsx",+ "src/features/HomeSidebar/Header/components/InboxModal/NotificationItem.tsx",+ "src/features/HomeSidebar/Header/components/InboxModal/index.tsx",+ "src/features/HomeSidebar/Header/components/User.tsx",+ "src/features/HotkeyHelperPanel/HotkeyContent.tsx",+ "src/features/Integrations/Github/Automation.tsx",+ "src/features/Integrations/Github/Connections.tsx",+ "src/features/Integrations/Github/index.tsx",+ "src/features/Integrations/IntegrationCard.tsx",+ "src/features/Integrations/Layout.tsx",+ "src/features/Integrations/Linear/Connections.tsx",+ "src/features/Integrations/Linear/index.tsx",+ "src/features/Integrations/Overview.tsx",+ "src/features/Integrations/OverviewSkeleton.tsx",+ "src/features/LibraryModal/AssignKnowledgeBase/Item/MasonryItem.tsx",+ "src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx",+ "src/features/LibraryModal/AssignKnowledgeBase/MasonrySkeleton.tsx",+ "src/features/LibraryModal/AssignKnowledgeBase/ViewSwitcher.tsx",+ "src/features/LibraryModal/AssignKnowledgeBase/VisibilityTabs.tsx",+ "src/features/LibraryModal/FilePicker/index.tsx",+ "src/features/LocalFile/LocalFile.tsx",+ "src/features/LocalFile/LocalFolder.tsx",+ "src/features/MCP/MCPInstallProgress/MCPConfigForm.tsx",+ "src/features/MCP/MCPInstallProgress/MCPDependenciesGuide.tsx",+ "src/features/MCP/MCPSettings/index.tsx",+ "src/features/MCP/Scores.tsx",+ "src/features/MCPPluginDetail/CollapseDesc.tsx",+ "src/features/MCPPluginDetail/Deployment/Platform/index.tsx",+ "src/features/MCPPluginDetail/Deployment/index.tsx",+ "src/features/MCPPluginDetail/Header.tsx",+ "src/features/MCPPluginDetail/Nav.tsx",+ "src/features/MCPPluginDetail/Overview/TagList.tsx",+ "src/features/MCPPluginDetail/Schema/style.ts",+ "src/features/MCPPluginDetail/Score/TotalScore.tsx",+ "src/features/MemoryRules/ComposeModal.tsx",+ "src/features/MemoryRules/DetailPanel.tsx",+ "src/features/MemoryRules/DistillModal.tsx",+ "src/features/MemoryRules/Field.tsx",+ "src/features/MemoryRules/GroupModal.tsx",+ "src/features/MemoryRules/RulesOnboarding.tsx",+ "src/features/MemoryRules/styles.ts",+ "src/features/Messenger/IntegrationDetail/CommandsSection.tsx",+ "src/features/Messenger/IntegrationDetail/Linq.tsx",+ "src/features/Messenger/IntegrationDetail/MessengerPushWindowState.tsx",+ "src/features/Messenger/IntegrationDetail/Wechat.tsx",+ "src/features/Messenger/IntegrationDetail/shared.tsx",+ "src/features/Messenger/IntegrationList.tsx",+ "src/features/Messenger/LinkModal/Telegram.tsx",+ "src/features/Messenger/Verify/Body/shared.tsx",+ "src/features/Messenger/index.tsx",+ "src/features/Messenger/scopeOptions.tsx",+ "src/features/MobileHome/Layout/MobileLayout/style.ts",+ "src/features/MobileHome/Layout/SessionHeader/style.ts",+ "src/features/MobileHome/SessionListContent/AgentSearchList.tsx",+ "src/features/MobileHome/SessionListContent/CollapseGroup/Actions.tsx",+ "src/features/MobileHome/SessionListContent/CollapseGroup/index.tsx",+ "src/features/MobileHome/SessionListContent/List/index.tsx",+ "src/features/MobileHome/SessionListContent/ListItem/index.tsx",+ "src/features/MobileHome/SessionListContent/ListItem/style.ts",+ "src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/GroupItem.tsx",+ "src/features/MobileHome/SessionListContent/Modals/ConfigGroupModal/index.tsx",+ "src/features/MobileHome/SkeletonList.tsx",+ "src/features/ModelSelect/index.tsx",+ "src/features/ModelSwitchPanel/components/BenchmarkModal/index.tsx",+ "src/features/ModelSwitchPanel/components/ControlsForm/LevelSlider.tsx",+ "src/features/ModelSwitchPanel/components/List/ModelRowMeta.tsx",+ "src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx",+ "src/features/ModelSwitchPanel/components/ModelRatingRadar.tsx",+ "src/features/ModelSwitchPanel/styles.ts",+ "src/features/NavPanel/SideBarDrawer.tsx",+ "src/features/NavPanel/SideBarHeaderLayout.tsx",+ "src/features/NavPanel/SidebarHeaderSelect.tsx",+ "src/features/NavPanel/components/NavItem.tsx",+ "src/features/NavPanel/components/NavPanelDraggable.tsx",+ "src/features/NavPanel/switcher/SwitcherMenu.tsx",+ "src/features/NavPanel/switcher/SwitcherRow.tsx",+ "src/features/Onboarding/Layout/style.ts",+ "src/features/Onboarding/steps/AgentPickerStep/style.ts",+ "src/features/Onboarding/steps/TelemetryStep.tsx",+ "src/features/OpenInAppButton/index.tsx",+ "src/features/PageEditor/Copilot/AgentSelector/AgentSelectorAction.tsx",+ "src/features/PageEditor/Copilot/CopilotModelSelect.tsx",+ "src/features/PageEditor/DocumentComments/anchor/HighlightStyle.tsx",+ "src/features/PageEditor/DocumentComments/styles.ts",+ "src/features/PageEditor/DocumentLikes/index.tsx",+ "src/features/PageEditor/EditorCanvas/useAddCommentItem.tsx",+ "src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx",+ "src/features/PageEditor/Header/Breadcrumb.tsx",+ "src/features/PageEditor/Header/index.tsx",+ "src/features/PageEditor/History/CompareModal/CompareContent.tsx",+ "src/features/PageEditor/History/CompareModal/HistorySidebar.tsx",+ "src/features/PageEditor/History/DocumentHistoryDiff.tsx",+ "src/features/PageEditor/History/HistoryListItem.tsx",+ "src/features/PageEditor/History/index.tsx",+ "src/features/PageEditor/PageEditor.tsx",+ "src/features/PageEditor/RightPanel/index.tsx",+ "src/features/PageExplorer/PageExplorerPlaceholder.tsx",+ "src/features/PageShell/ShellTopBar.tsx",+ "src/features/Pages/PageLayout/Body/List/Item/index.tsx",+ "src/features/Pages/PageLayout/style.ts",+ "src/features/PlanIcon/index.tsx",+ "src/features/PluginDevModal/MCPManifestForm/CollapsibleSection.tsx",+ "src/features/PluginDevModal/MCPManifestForm/MCPTypeSelect.tsx",+ "src/features/PluginDevModal/PluginPreview/ApiVisualizer.tsx",+ "src/features/PluginDevModal/PluginPreview/EmptyState.tsx",+ "src/features/PluginSettings/index.tsx",+ "src/features/Portal/AcceptanceCheck/Body.tsx",+ "src/features/Portal/Artifacts/Body/Renderer/SVG.tsx",+ "src/features/Portal/DashboardWidget/Body.tsx",+ "src/features/Portal/Document/Body.tsx",+ "src/features/Portal/Document/Header.tsx",+ "src/features/Portal/Document/SkillFrontmatterCard.tsx",+ "src/features/Portal/Document/TodoList.tsx",+ "src/features/Portal/Goal/Body.tsx",+ "src/features/Portal/GoalMetric/Body.tsx",+ "src/features/Portal/GoalMetric/Lifecycle.tsx",+ "src/features/Portal/GoalNode/Body.tsx",+ "src/features/Portal/GoalNorthStar/Body.tsx",+ "src/features/Portal/GoalReport/Body.tsx",+ "src/features/Portal/Home/Body/Files/FileList/Item.tsx",+ "src/features/Portal/Home/Body/Plugins/ArtifactList/Item/style.ts",+ "src/features/Portal/LocalFile/Body.tsx",+ "src/features/Portal/LocalFile/PathBreadcrumb.tsx",+ "src/features/Portal/LocalFile/PreviewToolbar.tsx",+ "src/features/Portal/LocalFile/TabStrip.tsx",+ "src/features/Portal/LocalFile/UnsupportedPreview.tsx",+ "src/features/Portal/MessageDetail/Body/index.tsx",+ "src/features/Portal/Mobile.tsx",+ "src/features/Portal/Notebook/DocumentItem.tsx",+ "src/features/Portal/TaskDetail/Title.tsx",+ "src/features/Portal/TopicComments/Sidebar.tsx",+ "src/features/Portal/TopicComments/styles.ts",+ "src/features/Portal/VerifyResult/Body.tsx",+ "src/features/Portal/VerifyResult/Title.tsx",+ "src/features/ProfileEditor/PluginTag.tsx",+ "src/features/ProfileEditor/PopoverContent.tsx",+ "src/features/Projects/List/index.tsx",+ "src/features/Projects/Workspace/ProjectDashboard.tsx",+ "src/features/Projects/Workspace/index.tsx",+ "src/features/ProtocolUrlHandler/InstallPlugin/ConfigDisplay.tsx",+ "src/features/RecommendTaskTemplates/style.ts",+ "src/features/Recommendations/style.ts",+ "src/features/ResourceHome/Home/Libraries.tsx",+ "src/features/ResourceHome/Home/RecentFiles.tsx",+ "src/features/ResourceHome/Home/RecentPages.tsx",+ "src/features/ResourceHome/Home/RecentWorks.tsx",+ "src/features/ResourceHome/Home/SectionTitle.tsx",+ "src/features/ResourceHome/Home/index.tsx",+ "src/features/ResourceHome/Layout/style.ts",+ "src/features/ResourceLibrary/Layout/Header/LibraryHead.tsx",+ "src/features/ResourceLibrary/Layout/style.ts",+ "src/features/ResourceManager/components/ChunkDrawer/ChunkList/ChunkItem.tsx",+ "src/features/ResourceManager/components/ChunkDrawer/SimilaritySearchList/Item.tsx",+ "src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx",+ "src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx",+ "src/features/ResourceManager/components/Explorer/ListView/ColumnResizeHandle.tsx",+ "src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx",+ "src/features/ResourceManager/components/Explorer/ListView/ListItem/styles.ts",+ "src/features/ResourceManager/components/Explorer/ListView/ListViewDropZone.tsx",+ "src/features/ResourceManager/components/Explorer/ListView/styles.ts",+ "src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/AudioFileItem.tsx",+ "src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx",+ "src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx",+ "src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/MarkdownFileItem.tsx",+ "src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/NoteFileItem.tsx",+ "src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/VideoFileItem.tsx",+ "src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/WebpageFileItem.tsx",+ "src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx",+ "src/features/ResourceManager/components/Explorer/MasonryView/Skeleton.tsx",+ "src/features/ResourceManager/components/Explorer/MasonryView/index.tsx",+ "src/features/ResourceManager/components/Explorer/ToolBar/SourceFilter.tsx",+ "src/features/ResourceManager/components/FolderTree/index.tsx",+ "src/features/ResourceManager/components/LibraryHierarchy/TreeSkeleton.tsx",+ "src/features/ResourceManager/components/LibraryHierarchy/styles.ts",+ "src/features/ResourceManager/index.tsx",+ "src/features/ResourcePermission/Collaborators/AddCollaboratorsContent.tsx",+ "src/features/ResourcePermission/Collaborators/CollaboratorList.tsx",+ "src/features/ResourcePermission/PolicySelect.tsx",+ "src/features/ResourcePermission/ResourceAccessPage.tsx",+ "src/features/SelfLearning/CreateDomainPage.tsx",+ "src/features/SelfLearning/ExperienceList/index.tsx",+ "src/features/SelfLearning/LessonDetail/index.tsx",+ "src/features/SelfLearning/Portrait/AnchorCard.tsx",+ "src/features/SelfLearning/Portrait/GrowthCharts.tsx",+ "src/features/SelfLearning/Portrait/LessonPreview.tsx",+ "src/features/SelfLearning/Portrait/WarmupCard.tsx",+ "src/features/SelfLearning/Portrait/styles.ts",+ "src/features/SelfLearning/index.tsx",+ "src/features/Setting/Footer.tsx",+ "src/features/Settings/Layout/style.ts",+ "src/features/Settings/about/features/About.tsx",+ "src/features/Settings/about/features/Version.tsx",+ "src/features/Settings/apikey/features/ApiKey.tsx",+ "src/features/Settings/apikey/features/ApiKeyDetail.tsx",+ "src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx",+ "src/features/Settings/apikey/features/ApiKeyModal/Content.tsx",+ "src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx",+ "src/features/Settings/apikey/features/EditableCell/index.tsx",+ "src/features/Settings/appearance/features/Font/FallbackFontList.tsx",+ "src/features/Settings/chat-appearance/features/ChatAppearance/LinkIconPreview.tsx",+ "src/features/Settings/common/features/Appearance/Preview.tsx",+ "src/features/Settings/creds/features/CreateCredModal/Content.tsx",+ "src/features/Settings/creds/features/CreateCredModal/CredTypeSelector.tsx",+ "src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx",+ "src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx",+ "src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx",+ "src/features/Settings/creds/features/CredsList.tsx",+ "src/features/Settings/creds/features/EditCredModal/EditKVForm.tsx",+ "src/features/Settings/creds/features/EditCredModal/EditMetaForm.tsx",+ "src/features/Settings/creds/features/ViewCredModal/Content.tsx",+ "src/features/Settings/creds/features/style.ts",+ "src/features/Settings/integrations/index.tsx",+ "src/features/Settings/oauth-apps/features/AppDetail/CredentialsCard.tsx",+ "src/features/Settings/oauth-apps/features/AppDetail/IntegrationCard.tsx",+ "src/features/Settings/oauth-apps/features/AppDetail/ManualSetupCard.tsx",+ "src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx",+ "src/features/Settings/oauth-apps/features/AppDetail/SectionCard.tsx",+ "src/features/Settings/oauth-apps/features/AppDetail/index.tsx",+ "src/features/Settings/oauth-apps/features/AppItem/index.tsx",+ "src/features/Settings/oauth-apps/features/AppListSkeleton.tsx",+ "src/features/Settings/oauth-apps/features/AppLogo/index.tsx",+ "src/features/Settings/oauth-apps/features/ClientIdDisplay/index.tsx",+ "src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx",+ "src/features/Settings/oauth-apps/features/OAuthApps.tsx",+ "src/features/Settings/oauth-apps/features/SecretModal/index.tsx",+ "src/features/Settings/profile/features/AvatarRow.tsx",+ "src/features/Settings/profile/features/ProfileRow.tsx",+ "src/features/Settings/provider/(list)/ProviderGrid/style.ts",+ "src/features/Settings/provider/ProviderMenu/SortProviderModal/index.tsx",+ "src/features/Settings/provider/_layout/Desktop/style.ts",+ "src/features/Settings/provider/detail/github/index.tsx",+ "src/features/Settings/provider/detail/ollama/Container.tsx",+ "src/features/Settings/provider/detail/vertexai/index.tsx",+ "src/features/Settings/provider/features/ModelList/EmptyModels.tsx",+ "src/features/Settings/provider/features/ModelList/ModelItem.tsx",+ "src/features/Settings/provider/features/ModelList/SkeletonList.tsx",+ "src/features/Settings/provider/features/ModelList/SortModelModal/index.tsx",+ "src/features/Settings/provider/features/ProviderConfig/Checker.tsx",+ "src/features/Settings/provider/features/ProviderConfig/EnableSwitch.tsx",+ "src/features/Settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx",+ "src/features/Settings/provider/features/ProviderConfig/index.tsx",+ "src/features/Settings/proxy/features/SaveBar.tsx",+ "src/features/Settings/skill/features/LeftPanel.tsx",+ "src/features/Settings/skill/features/SkillDetail/index.tsx",+ "src/features/Settings/skill/features/SkillList.tsx",+ "src/features/Settings/skill/features/style.ts",+ "src/features/Settings/skill/index.tsx",+ "src/features/Settings/stats/features/overview/ShareButton/Preview.tsx",+ "src/features/Settings/stats/features/usage/UsageTable.tsx",+ "src/features/Settings/trash/features/ProjectFilter.tsx",+ "src/features/Settings/trash/features/TrashList.tsx",+ "src/features/SettingsSearch/SearchResults.tsx",+ "src/features/SettingsSearch/anchor.tsx",+ "src/features/ShareModal/ShareImage/style.ts",+ "src/features/ShareModal/SharePdf/PdfPreview.tsx",+ "src/features/ShareModal/SharePdf/index.tsx",+ "src/features/ShareModal/components/OptionChips.tsx",+ "src/features/ShareModal/style.ts",+ "src/features/ShareModal/useContainerStyles.ts",+ "src/features/SharePopover/style.ts",+ "src/features/SkillStore/SkillDetail/Nav.tsx",+ "src/features/SkillStore/SkillDetail/Schema.tsx",+ "src/features/SkillStore/SkillDetail/style.ts",+ "src/features/SkillStore/SkillDetail/styles.ts",+ "src/features/SkillStore/SkillList/Community/MarketSkillItem.tsx",+ "src/features/SkillStore/SkillList/MarketSkills/MarketSkillDetail.tsx",+ "src/features/SkillStore/SkillList/style.ts",+ "src/features/SkillsList/SkillSection.tsx",+ "src/features/SkillsList/SkillsList.tsx",+ "src/features/TaskDock/Item.tsx",+ "src/features/TaskDock/index.tsx",+ "src/features/ToolSetting/ChannelItem.tsx",+ "src/features/ToolTag/index.tsx",+ "src/features/TopicComment/MessageCommentBadge.tsx",+ "src/features/TopicDoctorModal/Content.tsx",+ "src/features/TopicPopupGuard/index.tsx",+ "src/features/User/DataStatistics.tsx",+ "src/features/User/UserAvatar.tsx",+ "src/features/User/UserPanel/index.tsx",+ "src/features/VisibilityConfirmContent/index.tsx",+ "src/features/WideScreenContainer/index.tsx",+ "src/features/Work/WorkSummaryCard.tsx",+ "src/features/WorkGallery/Skeleton.tsx",+ "src/features/WorkGallery/WorkPreview.tsx",+ "src/features/WorkGallery/WorkPreviewCard.tsx",+ "src/features/WorkGallery/index.tsx",+ "src/features/WorkspaceSetting/Labels/LabelFormModal.tsx",+ "src/features/WorkspaceSetting/Labels/index.tsx",+ "src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx",+ "src/layout/GlobalProvider/AppTheme.tsx",+ "src/layout/GlobalProvider/ServerVersionOutdatedAlert.tsx",+ "src/routes/(main)/(create)/components/GenerationModelItem.tsx",+ "src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.tsx",+ "src/routes/(main)/(create)/features/GenerationInput/GenerationModelNotice/index.tsx",+ "src/routes/(main)/(create)/features/GenerationInput/GenerationPromptBlockedNotice.tsx",+ "src/routes/(main)/(create)/features/GenerationInput/GenerationPromptInput.tsx",+ "src/routes/(main)/(create)/features/GenerationInput/GenerationVisibilitySelector.tsx",+ "src/routes/(main)/(create)/features/GenerationInput/ImagePreviewHeader.tsx",+ "src/routes/(main)/(create)/features/GenerationInput/InlineImageReference.tsx",+ "src/routes/(main)/(create)/features/GenerationInput/InlineVideoFrames.tsx",+ "src/routes/(main)/(create)/features/GenerationInput/UploadCard.tsx",+ "src/routes/(main)/(create)/features/GenerationLayout/Body/List/Item/GridItem.tsx",+ "src/routes/(main)/(create)/features/GenerationLayout/style.ts",+ "src/routes/(main)/(create)/image/features/ConfigPanel/components/ImageUpload.tsx",+ "src/routes/(main)/(create)/image/features/ConfigPanel/style.ts",+ "src/routes/(main)/(create)/image/features/GenerationFeed/BatchItem.tsx",+ "src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/styles.ts",+ "src/routes/(main)/(create)/image/features/GenerationFeed/ReferenceImages.tsx",+ "src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx",+ "src/routes/(main)/(create)/video/features/GenerationFeed/EditSourceLink.tsx",+ "src/routes/(main)/(create)/video/features/GenerationFeed/VideoReferenceFrames.tsx",+ "src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx",+ "src/routes/(main)/(create)/video/features/PromptInput/EditingVideoHeader.tsx",+ "src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/index.tsx",+ "src/routes/(main)/[workspaceSlug]/settings/credential/index.tsx",+ "src/routes/(main)/_layout/style.ts",+ "src/routes/(main)/agent/_layout/style.ts",+ "src/routes/(main)/agent/channel/index.tsx",+ "src/routes/(main)/agent/features/Conversation/ConversationArea.tsx",+ "src/routes/(main)/agent/features/Conversation/Header/Tags/ThreadSwitcher.tsx",+ "src/routes/(main)/agent/features/Conversation/Header/index.tsx",+ "src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ScheduledSendChip.tsx",+ "src/routes/(main)/agent/features/Conversation/MainChatInput/AgentConfigError.tsx",+ "src/routes/(main)/agent/features/Portal/features/Body.tsx",+ "src/routes/(main)/agent/features/Portal/features/Portal.tsx",+ "src/routes/(main)/agent/features/TelemetryNotification.tsx",+ "src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx",+ "src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx",+ "src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx",+ "src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx",+ "src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx",+ "src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentPolicyCard.tsx",+ "src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx",+ "src/routes/(main)/community/(detail)/_layout/Header/style.ts",+ "src/routes/(main)/community/(detail)/_layout/style.ts",+ "src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/KnowledgeItem.tsx",+ "src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx",+ "src/routes/(main)/community/(detail)/agent/features/Details/Nav.tsx",+ "src/routes/(main)/community/(detail)/agent/features/Details/SystemRole/TagList.tsx",+ "src/routes/(main)/community/(detail)/agent/features/Header.tsx",+ "src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx",+ "src/routes/(main)/community/(detail)/agent/features/Sidebar/Related/Item.tsx",+ "src/routes/(main)/community/(detail)/features/ShareButton.tsx",+ "src/routes/(main)/community/(detail)/features/Toc/Heading.tsx",+ "src/routes/(main)/community/(detail)/features/Toc/index.tsx",+ "src/routes/(main)/community/(detail)/group_agent/features/Details/Nav.tsx",+ "src/routes/(main)/community/(detail)/group_agent/features/Details/Overview/index.tsx",+ "src/routes/(main)/community/(detail)/group_agent/features/Header.tsx",+ "src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx",+ "src/routes/(main)/community/(detail)/mcp/features/Sidebar/ActionButton/index.tsx",+ "src/routes/(main)/community/(detail)/mcp/features/Sidebar/Related/Item.tsx",+ "src/routes/(main)/community/(detail)/model/features/Details/Nav.tsx",+ "src/routes/(main)/community/(detail)/model/features/Header.tsx",+ "src/routes/(main)/community/(detail)/model/features/Sidebar/ActionButton/ChatWithModel.tsx",+ "src/routes/(main)/community/(detail)/model/features/Sidebar/Related/Item.tsx",+ "src/routes/(main)/community/(detail)/model/features/Sidebar/RelatedProviders/Item.tsx",+ "src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx",+ "src/routes/(main)/community/(detail)/provider/features/Details/Nav.tsx",+ "src/routes/(main)/community/(detail)/provider/features/Sidebar/Related/Item.tsx",+ "src/routes/(main)/community/(detail)/provider/features/Sidebar/RelatedModels/Item.tsx",+ "src/routes/(main)/community/(detail)/user/features/Header/Banner.tsx",+ "src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx",+ "src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx",+ "src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx",+ "src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx",+ "src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx",+ "src/routes/(main)/community/(list)/(home)/features/CreatorRewardBanner.tsx",+ "src/routes/(main)/community/(list)/_layout/Footer.tsx",+ "src/routes/(main)/community/(list)/_layout/Header/style.ts",+ "src/routes/(main)/community/(list)/_layout/style.ts",+ "src/routes/(main)/community/(list)/agent/_layout/style.ts",+ "src/routes/(main)/community/(list)/agent/features/List/Item.tsx",+ "src/routes/(main)/community/(list)/agent/features/List/TokenTag.tsx",+ "src/routes/(main)/community/(list)/mcp/_layout/style.ts",+ "src/routes/(main)/community/(list)/mcp/features/List/Item.tsx",+ "src/routes/(main)/community/(list)/model/_layout/style.ts",+ "src/routes/(main)/community/(list)/model/features/List/Item.tsx",+ "src/routes/(main)/community/(list)/provider/features/List/Item.tsx",+ "src/routes/(main)/community/(list)/skill/_layout/style.ts",+ "src/routes/(main)/community/(list)/skill/features/List/Item.tsx",+ "src/routes/(main)/community/_layout/style.ts",+ "src/routes/(main)/community/components/CardBanner.tsx",+ "src/routes/(main)/community/components/CategoryMenu.tsx",+ "src/routes/(main)/community/components/Statistic.tsx",+ "src/routes/(main)/community/components/Title.tsx",+ "src/routes/(main)/community/features/Search.tsx",+ "src/routes/(main)/community/features/Title.tsx",+ "src/routes/(main)/eval/_layout/style.ts",+ "src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/BenchmarkHead.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/_layout/style.ts",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/EmptyState.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCaseEmptyState.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewPanel.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCaseTable.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Footer.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/EmptyState.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/CaseBanner/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/ChatArea/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/InfoSidebar/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/Content.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/CaseResultsTable/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/Charts/BenchmarkCharts.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/Charts/ScatterPlot.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/IdleState/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/PendingState/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunningState/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/index.tsx",+ "src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx",+ "src/routes/(main)/eval/datasets/[datasetId]/index.tsx",+ "src/routes/(main)/eval/features/BenchmarkCard/index.tsx",+ "src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx",+ "src/routes/(main)/eval/features/DatasetEditModal/Content.tsx",+ "src/routes/(main)/eval/features/DatasetImportModal/UploadStep.tsx",+ "src/routes/(main)/eval/features/Experiments/BenchmarksSection.tsx",+ "src/routes/(main)/eval/features/Experiments/DatasetRow.tsx",+ "src/routes/(main)/eval/features/Experiments/ExperimentDetailPage.tsx",+ "src/routes/(main)/eval/features/Experiments/ExperimentHeader.tsx",+ "src/routes/(main)/eval/features/Experiments/ExperimentStats.tsx",+ "src/routes/(main)/eval/features/Experiments/RunRow.tsx",+ "src/routes/(main)/eval/features/Experiments/RunsSection.tsx",+ "src/routes/(main)/eval/features/Experiments/ScopedDatasetsSection.tsx",+ "src/routes/(main)/eval/features/Experiments/SummaryCard.tsx",+ "src/routes/(main)/eval/features/SegmentBar.tsx",+ "src/routes/(main)/eval/features/Sparkline.tsx",+ "src/routes/(main)/eval/features/StatusBadge.tsx",+ "src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx",+ "src/routes/(main)/eval/features/TestCaseDetail/MessageBlock.tsx",+ "src/routes/(main)/eval/features/TestCaseDetail/Transcript.tsx",+ "src/routes/(main)/eval/features/TestCaseDetail/index.tsx",+ "src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx",+ "src/routes/(main)/eval/index.tsx",+ "src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AgentItem.tsx",+ "src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/AvailableAgentList.tsx",+ "src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/SelectedAgentList.tsx",+ "src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx",+ "src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx",+ "src/routes/(main)/group/_layout/Sidebar/GroupConfig/SortMembersModal/MemberItem.tsx",+ "src/routes/(main)/group/_layout/Sidebar/GroupConfig/SortMembersModal/index.tsx",+ "src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx",+ "src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx",+ "src/routes/(main)/group/_layout/style.ts",+ "src/routes/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx",+ "src/routes/(main)/group/features/TelemetryNotification.tsx",+ "src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx",+ "src/routes/(main)/group/profile/features/Header/ChromeTabs/index.tsx",+ "src/routes/(main)/group/profile/features/Header/index.tsx",+ "src/routes/(main)/memory/(home)/features/Persona/PersonaDetail.tsx",+ "src/routes/(main)/memory/(home)/features/Persona/PersonaHeader.tsx",+ "src/routes/(main)/memory/(home)/features/Persona/PersonaSummary.tsx",+ "src/routes/(main)/memory/(home)/features/RoleTagCloud/index.tsx",+ "src/routes/(main)/memory/_layout/style.ts",+ "src/routes/(main)/memory/features/GridView/GridCard.tsx",+ "src/routes/(main)/memory/features/Loading.tsx",+ "src/routes/(main)/memory/features/TimeLineView/PeriodGroup.tsx",+ "src/routes/(main)/memory/features/TimeLineView/TimeLineCard.tsx",+ "src/routes/(main)/memory/features/TimeLineView/index.tsx",+ "src/routes/(main)/memory/preferences/features/PreferenceDetail.tsx",+ "src/routes/(mobile)/_layout/NavBar.tsx",+ "src/routes/(mobile)/chat/_layout/style.ts",+ "src/routes/(mobile)/community/(list)/_layout/Header.tsx",+ "src/routes/(mobile)/community/(list)/_layout/Nav.tsx",+ "src/routes/(mobile)/community/(list)/_layout/style.ts",+ "src/routes/(mobile)/me/settings/features/Category.tsx",+ "src/routes/(popup)/_layout/TitleBar.tsx",+ "src/routes/(popup)/_layout/index.tsx",+ "src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx",+ "src/spa/BootShell/AppShellSkeleton.tsx",+ "src/styles/electron.ts",+ "src/styles/global.ts",+ "src/styles/index.ts",+ "src/styles/loading.ts",+ "src/styles/text.ts"+]diff --git a/scripts/stylexMigration/legacyFiles.test.ts b/scripts/stylexMigration/legacyFiles.test.tsnew file mode 100644index 00000000000..96f7a9633d9--- /dev/null+++ b/scripts/stylexMigration/legacyFiles.test.ts@@ -0,0 +1,19 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { findStaleLegacyFiles, readLegacyFiles, scanRepo } from '.';++describe('legacyFiles.json', () => {+ it('lists only files that still import emotion styles', () => {+ const stale = findStaleLegacyFiles(scanRepo());++ // A migrated or deleted file is still listed. Run:+ // bun run stylex:migration --prune-legacy+ expect(stale).toEqual([]);+ });++ it('stays sorted so pruning diffs only remove lines', () => {+ const legacy = readLegacyFiles();+ expect(legacy).toEqual([...legacy].sort());+ });+});diff --git a/scripts/stylexMigration/legacyImports.json b/scripts/stylexMigration/legacyImports.jsonnew file mode 100644index 00000000000..688f33e83a9--- /dev/null+++ b/scripts/stylexMigration/legacyImports.json@@ -0,0 +1 @@+["createGlobalStyle", "createStaticStyles", "createStyles", "css", "injectGlobal", "keyframes"]diff --git a/src/components/StatisticCard/index.test.tsx b/src/components/StatisticCard/index.test.tsxindex 8eaeee7122a..3a13688c5d6 100644--- a/src/components/StatisticCard/index.test.tsx+++ b/src/components/StatisticCard/index.test.tsx@@ -33,6 +33,9 @@ describe('StatisticCard', () => {);expect(screen.getByText('Total Cost')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Total Cost' }).parentElement?.className).toContain(+ 'index__styles.title',+ );expect(screen.getByText('$')).toBeInTheDocument();expect(screen.getByText('1,234.50')).toBeInTheDocument();expect(screen.getByText('k')).toBeInTheDocument();diff --git a/src/components/StatisticCard/index.tsx b/src/components/StatisticCard/index.tsxindex e6c00edc600..415d1b16137 100644--- a/src/components/StatisticCard/index.tsx+++ b/src/components/StatisticCard/index.tsx@@ -1,39 +1,33 @@import { type BlockProps } from '@lobehub/ui';-import { Block, createStaticStyles, Flexbox, responsive, Spin, Statistic, Text } from '@lobehub/ui';+import { Block, Flexbox, Spin, Statistic, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { media } from '@lobehub/ui/stylex/media.stylex';+import * as stylex from '@stylexjs/stylex';import { type CSSProperties, type ReactNode } from 'react';import { memo } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => ({- header: css`- display: flex;- gap: 8px;- align-items: center;- justify-content: space-between;-- ${responsive.sm} {- flex-wrap: wrap;- margin-block-end: 8px;- }- `,- statistic: css`- font-weight: bold;- line-height: 1.2;- `,- title: css`- overflow: hidden;- flex: 1;-- font-size: 16px;- font-weight: 500;- line-height: 32px;- color: ${cssVar.colorText};-- ${responsive.sm} {- font-size: 14px;- line-height: 16px;- }- `,-}));+const styles = stylex.create({+ header: {+ alignItems: 'center',+ display: 'flex',+ flexWrap: { default: null, [media.sm]: 'wrap' },+ gap: 8,+ justifyContent: 'space-between',+ marginBlockEnd: { default: null, [media.sm]: 8 },+ },+ statistic: {+ fontWeight: 'bold',+ lineHeight: 1.2,+ },+ title: {+ color: cssVar.colorText,+ flex: '1',+ fontSize: { default: 16, [media.sm]: 14 },+ fontWeight: 500,+ lineHeight: { default: '32px', [media.sm]: '16px' },+ overflow: 'hidden',+ },+});export interface StatisticConfig {description?: ReactNode;@@ -80,8 +74,8 @@ const StatisticCard = memo<StatisticCardProps>(style={style}variant={variant}>- <div className={styles.header}>- <div className={styles.title}>+ <div {...stylex.props(styles.header)}>+ <div {...stylex.props(styles.title)}>{typeof title === 'string' ? (<Textas={'h2'}@@ -105,7 +99,7 @@ const StatisticCard = memo<StatisticCardProps>({statistic && (<Flexbox gap={16} style={statistic.style}><Statistic- classNames={{ value: styles.statistic }}+ classNames={{ value: stylex.props(styles.statistic).className }}precision={statistic.precision}prefix={statistic.prefix}styles={statistic.valueStyle ? { value: statistic.valueStyle } : undefined}diff --git a/src/initialize.ts b/src/initialize.tsindex a0c7992a386..5bdb468a6a6 100644--- a/src/initialize.ts+++ b/src/initialize.ts@@ -1,3 +1,5 @@+import '@/styles/stylex.css';+import dayjs from 'dayjs';import isToday from 'dayjs/plugin/isToday';import isYesterday from 'dayjs/plugin/isYesterday';diff --git a/src/libs/spaHtml/index.test.ts b/src/libs/spaHtml/index.test.tsindex 3d9ceba7abd..6eec8d61232 100644--- a/src/libs/spaHtml/index.test.ts+++ b/src/libs/spaHtml/index.test.ts@@ -1,7 +1,8 @@// @vitest-environment node-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';-import { buildAnalyticsConfig, renderSpaHtml } from '.';+import { stylexProxiedDevCssModuleId } from '../../../plugins/vite/stylexDevCss';+import { buildAnalyticsConfig, fetchViteDevTemplate, renderSpaHtml } from '.';describe('renderSpaHtml', () => {it('injects server config, seo meta and strips the analytics placeholder', async () => {@@ -37,6 +38,33 @@ describe('renderSpaHtml', () => {});});+describe('fetchViteDevTemplate', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('loads StyleX dev CSS from the Vite origin', async () => {+ const html = [+ '<html><head>',+ '<script type="module" src="/@id/virtual:stylex:runtime"></script>',+ '<link rel="stylesheet" href="/virtual:stylex.css" />',+ '<script type="module" src="/@vite/client"></script>',+ '</head><body></body></html>',+ ].join('');+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response(html, { headers: { 'content-type': 'text/html' } })),+ );++ const result = await fetchViteDevTemplate('/', 'http://localhost:9876');++ expect(result).not.toContain('virtual:stylex:runtime');+ expect(result).toContain('http://localhost:9876/virtual:stylex.css');+ expect(result).toContain(`http://localhost:9876/@id/${stylexProxiedDevCssModuleId}`);+ expect(result).toContain('http://localhost:9876/@vite/client');+ });+});+describe('buildAnalyticsConfig', () => {afterEach(() => {delete process.env.NEXT_PUBLIC_DESKTOP_PROJECT_ID;diff --git a/src/libs/spaHtml/index.ts b/src/libs/spaHtml/index.tsindex 3cb290df2f5..b5d8ca67c59 100644--- a/src/libs/spaHtml/index.ts+++ b/src/libs/spaHtml/index.ts@@ -2,6 +2,11 @@ import { analyticsEnv } from '@/envs/analytics';import { serializeForHtml } from '@/server/utils/serializeForHtml';import { type AnalyticsConfig } from '@/types/spaServerConfig';+import {+ stylexDevRuntimeId,+ stylexProxiedDevCssModuleId,+} from '../../../plugins/vite/stylexDevCss';+// VITE_DEV_PORT is injected by scripts/devStartupSequence.mts with the actual// port of the Vite dev server it spawned; 9876 matches the standalone default.export const resolveViteDevOrigin = () =>@@ -17,9 +22,19 @@ async function rewriteViteAssetUrls(const { parseHTML } = await import('linkedom');const { document } = parseHTML(html);+ let replacedStylexRuntime = false;document.querySelectorAll('script[src]').forEach((el: Element) => {const src = el.getAttribute('src');- if (src && src.startsWith('/')) {+ if (!src) return;+ // The unplugin runtime fetches its dev CSS path on the document origin.+ // Next serves that path, the fetch returns HTML, and the runtime disables the+ // link that rewrite below points at Vite.+ if (src.includes(stylexDevRuntimeId)) {+ el.remove();+ replacedStylexRuntime = true;+ return;+ }+ if (src.startsWith('/')) {el.setAttribute('src', `${origin}${src}`);}});@@ -57,6 +72,13 @@ globalThis.Worker.prototype=O.prototype;head.insertBefore(workerPatch, head.firstChild);}+ if (replacedStylexRuntime && head) {+ const stylexDevCss = document.createElement('script');+ stylexDevCss.setAttribute('type', 'module');+ stylexDevCss.setAttribute('src', `${origin}/@id/${stylexProxiedDevCssModuleId}`);+ head.appendChild(stylexDevCss);+ }+return document.toString();}diff --git a/src/styles/stylex.css b/src/styles/stylex.cssnew file mode 100644index 00000000000..ac021236a7c--- /dev/null+++ b/src/styles/stylex.css@@ -0,0 +1,5 @@+/* Gives the entry chunk a CSS asset. Production builds append the compiled StyleX+ rules to it (plugins/vite/stylexEntryCss.ts); do not remove while it is empty. */+:root {+ --lh-stylex: 1;+}diff --git a/src/styles/sx.test.ts b/src/styles/sx.test.tsnew file mode 100644index 00000000000..7755ac2f29c--- /dev/null+++ b/src/styles/sx.test.ts@@ -0,0 +1,39 @@+import * as stylex from '@stylexjs/stylex';+import { describe, expect, it } from 'vitest';++import { sx } from './sx';++const styles = stylex.create({+ active: { color: 'red' },+ root: { display: 'flex' },+ width: (width: number) => ({ width }),+});++describe('sx', () => {+ it('keeps StyleX classes and appends the caller className', () => {+ const { className = '' } = sx([styles.root, styles.active], 'caller');++ expect(className).toContain('styles.root');+ expect(className).toContain('styles.active');+ expect(className.endsWith(' caller')).toBe(true);+ });++ it('drops falsy styles', () => {+ const active = false;+ const props = sx([styles.root, active && styles.active]);++ expect(props.className).toContain('styles.root');+ expect(props.className).not.toContain('styles.active');+ });++ it('merges dynamic StyleX styles with the caller style', () => {+ const props = sx(styles.width(120), undefined, { opacity: 0.5 });++ expect(props.style).toMatchObject({ opacity: 0.5 });+ expect(Object.values(props.style ?? {})).toContain('120px');+ });++ it('returns undefined for empty className and style', () => {+ expect(sx(null)).toEqual({ className: undefined, style: undefined });+ });+});diff --git a/src/styles/sx.ts b/src/styles/sx.tsnew file mode 100644index 00000000000..16efbfd1a02--- /dev/null+++ b/src/styles/sx.ts@@ -0,0 +1,23 @@+import * as stylex from '@stylexjs/stylex';+import { type CSSProperties } from 'react';++type StyleArgs = Parameters<typeof stylex.props>;++/**+ * stylex.props for elements that also forward a caller's className / style, which+ * spreading stylex.props cannot do (@stylexjs/no-conflicting-props).+ *+ * <div {...sx([styles.root, active && styles.active], className, style)} />+ *+ * The caller's className is appended, not merged: StyleX rules carry raised+ * specificity, so a plain class cannot override them. Components that let callers+ * restyle them take an `xstyle?: StyleXStyles` prop and pass it in `styles`.+ */+export const sx = (styles: StyleArgs[number], className?: string, style?: CSSProperties) => {+ const props = stylex.props(styles);+ const mergedClassName = [props.className, className].filter(Boolean).join(' ');+ return {+ className: mergedClassName || undefined,+ style: props.style || style ? { ...props.style, ...style } : undefined,+ };+};diff --git a/vitest.config.mts b/vitest.config.mtsindex a21975a692f..0321518bdd5 100644--- a/vitest.config.mts+++ b/vitest.config.mts@@ -3,6 +3,8 @@ import { dirname, join, resolve } from 'node:path';import tsconfigPaths from 'vite-tsconfig-paths';import { defineConfig } from 'vitest/config';+import { stylexPlugin, stylexTokenModules } from './plugins/vite/stylex';+if (process.env.NODE_ENV === 'production') {Reflect.set(process.env, 'NODE_ENV', 'test');}@@ -77,6 +79,7 @@ export default defineConfig({exclude: ['crypto', 'util', 'tty'],},plugins: [+ stylexPlugin(),tsconfigPaths({ projects: ['.', './apps/share', './apps/workbench'] }),// Let `.md` imports resolve to their raw text content so Rollup/Vitest// doesn't try to parse Markdown as JavaScript.@@ -229,7 +232,14 @@ export default defineConfig({// Vitest itself excludes `react`, which externalizes every `react/*`// subpath, but vite only builds a `require()` facade for exact entries,// so CJS deps in the chunk (re-resizable) need the jsx runtimes listed.- exclude: ['crypto', 'util', 'tty', 'react/jsx-runtime', 'react/jsx-dev-runtime'],+ exclude: [+ 'crypto',+ 'util',+ 'tty',+ 'react/jsx-runtime',+ 'react/jsx-dev-runtime',+ ...stylexTokenModules,+ ],// Every imported subpath must be prebundled together: a subpath left to// vite-node loads a second copy of the library whose MotionProvider /// modal-stack contexts don't match the chunk's