🤯 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
🧪 test(styles): add component-level StyleX migration verification infra (#21963)
Inneib2c5290eaea5
diff --git a/package.json b/package.jsonindex 8746458b868..3888a491c39 100644--- a/package.json+++ b/package.json@@ -125,6 +125,8 @@"start": "next start -p 3210","stylelint": "stylelint \"src/**/*.{js,jsx,ts,tsx}\" --fix","stylex:migration": "tsx scripts/stylexMigration/index.ts",+ "stylex:verify": "bun scripts/stylexMigration/verification/run.ts",+ "stylex:verify:test": "vitest run --config scripts/stylexMigration/verification/vitest.config.ts --silent='passed-only'","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",@@ -584,6 +586,9 @@"node-gyp": "^12.4.0","openapi-typescript": "^7.13.0","p-map": "^7.0.6",+ "postcss": "8.5.23",+ "postcss-selector-parser": "7.1.7",+ "postcss-value-parser": "4.2.0","prettier": "^3.9.6","raw-loader": "^4.0.2","remark-cjk-friendly": "^2.3.1",diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.jsonindex 9cde21223af..af72863a419 100644--- a/scripts/stylexMigration/legacyFiles.json+++ b/scripts/stylexMigration/legacyFiles.json@@ -238,70 +238,6 @@"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",@@ -376,10 +312,6 @@"src/features/Acceptance/Workspace/AcceptanceRow.tsx","src/features/Acceptance/Workspace/MergeAcceptanceModal.tsx","src/features/Acceptance/Workspace/index.tsx",- "src/features/AddAgentMemberModal/AgentItem.tsx",- "src/features/AddAgentMemberModal/AvailableAgentList.tsx",- "src/features/AddAgentMemberModal/SelectedAgentList.tsx",- "src/features/AddAgentMemberModal/index.tsx","src/features/AgentBreadcrumb/index.tsx","src/features/AgentBuilder/TopicSelector.tsx","src/features/AgentChannel/PlatformCard.tsx",@@ -525,29 +457,6 @@"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/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",@@ -572,13 +481,6 @@"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",@@ -591,9 +493,6 @@"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",@@ -615,45 +514,6 @@"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/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",@@ -1134,9 +994,6 @@"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",@@ -1159,8 +1016,6 @@"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/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",@@ -1177,60 +1032,6 @@"src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.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",@@ -1306,19 +1107,6 @@"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/verification/__tests__/cliIntegration.test.ts b/scripts/stylexMigration/verification/__tests__/cliIntegration.test.tsnew file mode 100644index 00000000000..20a4511cc54--- /dev/null+++ b/scripts/stylexMigration/verification/__tests__/cliIntegration.test.ts@@ -0,0 +1,145 @@+// @vitest-environment node+import { execFile } from 'node:child_process';+import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { git } from '../source/git';+import { resolveCommit } from '../source/revisionResolver';++const runner = path.resolve(import.meta.dirname, '../run.ts');+const owned: string[] = [];+const setup = async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-cli-test-'));+ owned.push(root);+ await git(root, ['init', '-b', 'canary']);+ await git(root, ['config', 'user.name', 'Verifier test']);+ await git(root, ['config', 'user.email', '[email protected]']);+ await writeFile(path.join(root, 'component.ts'), 'export const x = 1;');+ await git(root, ['add', '.']);+ await git(root, ['commit', '-m', 'initial']);+ const base = await resolveCommit(root, 'HEAD');+ await writeFile(path.join(root, 'component.ts'), 'export const x = 2;');+ await git(root, ['commit', '-am', 'candidate']);+ return { base, root };+};+const run = (root: string, args: string[]) =>+ new Promise<{ code: number; stderr: string; stdout: string }>((resolve, reject) => {+ execFile(+ 'bun',+ [runner, '--repository', root, '--output', path.join(root, 'evidence'), ...args],+ {+ env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' },+ maxBuffer: 2 * 1024 ** 2,+ timeout: 30_000,+ },+ (error, stdout, stderr) => {+ if (!error) resolve({ code: 0, stderr, stdout });+ else if (typeof error.code === 'number') resolve({ code: error.code, stderr, stdout });+ else reject(error);+ },+ );+ });+const artifact = async (root: string, file = 'preflight.json') => {+ const parent = path.join(root, 'evidence');+ const entries = await readdir(parent);+ expect(entries).toHaveLength(1);+ return JSON.parse(await readFile(path.join(parent, entries[0], file), 'utf8'));+};++afterEach(async () => {+ for (const root of owned.splice(0)) await rm(root, { force: true, recursive: true });+});++describe('real Node CLI process exit contract', () => {+ it('returns 2 for a partial plan instead of a successful empty comparison', async () => {+ const { root, base } = await setup();+ expect((await run(root, ['--base', base, '--head', 'HEAD', '--plan-only'])).code).toBe(2);+ expect(await artifact(root)).toMatchObject({+ gateEligible: false,+ mode: 'preflight',+ status: 'NEEDS_REVIEW',+ });+ });++ it('exports isolated source snapshots but stays blocked until dependencies and binding are proven', async () => {+ const { root, base } = await setup();+ expect((await run(root, ['--base', base, '--head', 'HEAD'])).code).toBe(2);+ const result = await artifact(root);+ expect(result.snapshots.base.fileCount).toBe(1);+ expect(result.snapshots.candidate.dependencyRestore).toBe('NOT_RESTORED');+ expect(result.reasonCodes).toContain('BROWSER_VERIFICATION_NOT_RUN');+ });++ it('uses exit 4 only for a proven identical candidate tree, not a fake PASS', async () => {+ const { root } = await setup();+ expect((await run(root, ['--base', 'HEAD', '--head', 'HEAD'])).code).toBe(4);+ expect(await artifact(root)).toMatchObject({+ gateEligible: false,+ status: 'NOT_APPLICABLE',+ reasonCodes: ['NO_STYLE_IMPACT'],+ });+ });++ it('keeps even an empty plan non-gating', async () => {+ const { root } = await setup();+ expect((await run(root, ['--base', 'HEAD', '--head', 'HEAD', '--plan-only'])).code).toBe(2);+ });++ it('returns 3 and records an error when a revision cannot be resolved', async () => {+ const { root } = await setup();+ expect((await run(root, ['--base', 'missing-ref', '--head', 'HEAD'])).code).toBe(3);+ expect(await artifact(root, 'error.json')).toMatchObject({+ gateEligible: false,+ status: 'ERROR',+ });+ });++ it('rejects invalid and unsupported options without a success result', async () => {+ const { root } = await setup();+ expect((await run(root, ['--pr', '21447', '--base', 'HEAD'])).code).toBe(3);+ expect((await run(root, ['batch'])).code).toBe(3);+ expect((await run(root, ['--unknown'])).code).toBe(3);+ expect(+ (await run(root, ['--base', 'HEAD', '--head', 'HEAD', '--fixture-dependencies'])).code,+ ).toBe(3);+ expect(+ (await run(root, ['--base', 'HEAD', '--head', 'HEAD', '--dependency-network'])).code,+ ).toBe(3);+ expect(+ (await run(root, ['--base', 'HEAD', '--head', 'HEAD', '--fixture', 'LiteTable'])).code,+ ).toBe(3);+ expect(+ (+ await run(root, [+ '--base',+ 'HEAD',+ '--head',+ 'HEAD',+ '--plan-only',+ '--restore-dependencies',+ ])+ ).code,+ ).toBe(3);+ });++ it('rejects ambiguous or invalid fixture batches before source or dependency work', async () => {+ const { root } = await setup();+ for (const selection of ['', 'DotsLoading,DotsLoading', 'DotsLoading,Unknown', '../escape']) {+ const result = await run(root, [+ '--base',+ 'HEAD',+ '--head',+ 'HEAD',+ '--restore-dependencies',+ '--fixtures',+ selection,+ ]);+ expect(result.code).toBe(3);+ }+ expect((await run(root, ['--fixture', 'LiteTable', '--fixtures', 'DotsLoading'])).code).toBe(3);+ expect((await run(root, ['--fixtures', 'DotsLoading,UnreadDot'])).code).toBe(3);+ });+});diff --git a/scripts/stylexMigration/verification/__tests__/fixtureBatch.test.ts b/scripts/stylexMigration/verification/__tests__/fixtureBatch.test.tsnew file mode 100644index 00000000000..7717d01bdc5--- /dev/null+++ b/scripts/stylexMigration/verification/__tests__/fixtureBatch.test.ts@@ -0,0 +1,60 @@+// @vitest-environment node+import { mkdir, mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, expect, it } from 'vitest';++import { getStyleFixture } from '../fixtures/fixtureRegistry';+import { runFixtureBatch } from '../pipeline/fixtureBatch';+import { sha256 } from '../reporting/report';++const owned: string[] = [];+afterEach(async () => {+ for (const root of owned.splice(0)) await rm(root, { force: true, recursive: true });+});++it('retains each failed component and attempts the rest without fabricating comparisons', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-fixture-batch-test-'));+ owned.push(root);+ const options = {+ baseRoot: path.join(root, 'base'),+ candidateRoot: path.join(root, 'candidate'),+ fixtures: ['DotsLoading', 'UnreadDot'].map(getStyleFixture),+ output: path.join(root, 'evidence'),+ sourceDirectory: path.resolve(import.meta.dirname, '..'),+ };+ for (const directory of [options.baseRoot, options.candidateRoot, options.output])+ await mkdir(directory);+ // Both exported source entries are genuinely missing. No build/browser mock.+ const result = await runFixtureBatch(options);+ expect(result.summary).toMatchObject({ planned: 2, completed: 0, errors: 2, equalInSamples: 0 });+ expect(result.errors[0]).toContain('DotsLoading');+ expect(result.errors[1]).toContain('UnreadDot');+ expect(result.fixtureResults).toEqual([]);+ for (const fixture of options.fixtures) {+ const directory = path.join(options.output, 'components', fixture.id);+ const error = JSON.parse(await readFile(path.join(directory, 'fixture-error.json'), 'utf8'));+ expect(error).toMatchObject({ fixtureId: fixture.id, gateEligible: false });+ const artifacts = JSON.parse(+ await readFile(path.join(directory, 'artifacts.json'), 'utf8'),+ ) as Array<{ path: string; sha256: string }>;+ expect(artifacts.map((entry) => entry.path)).toContain('report.html');+ for (const entry of artifacts)+ expect(sha256(await readFile(path.join(directory, entry.path)))).toBe(entry.sha256);+ }+});++it('rejects untrusted fixture IDs before writing outside the component namespace', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-fixture-batch-test-'));+ owned.push(root);+ await expect(+ runFixtureBatch({+ baseRoot: root,+ candidateRoot: root,+ output: root,+ sourceDirectory: root,+ fixtures: [{ ...getStyleFixture('DotsLoading'), id: '../escape' }],+ }),+ ).rejects.toThrow();+});diff --git a/scripts/stylexMigration/verification/__tests__/revisionIntegration.test.ts b/scripts/stylexMigration/verification/__tests__/revisionIntegration.test.tsnew file mode 100644index 00000000000..f02dc9bf737--- /dev/null+++ b/scripts/stylexMigration/verification/__tests__/revisionIntegration.test.ts@@ -0,0 +1,170 @@+// @vitest-environment node+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { inventoryScope } from '../analysis/scopeInventory';+import { exportSourceTree, prepareSourceSnapshots } from '../source/buildSnapshots';+import { git } from '../source/git';+import {+ closeRevisionSession,+ createRevisionSession,+ resolveCommit,+} from '../source/revisionResolver';++const owned: string[] = [];+const sessions: Awaited<ReturnType<typeof createRevisionSession>>[] = [];+const repository = async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-verification-test-'));+ owned.push(root);+ await git(root, ['init', '-b', 'canary']);+ await git(root, ['config', 'user.name', 'Style verifier tests']);+ await git(root, ['config', 'user.email', '[email protected]']);+ await writeFile(path.join(root, 'package.json'), '{"name":"fixture"}');+ await writeFile(path.join(root, 'component.ts'), 'export const color = "red";');+ await git(root, ['add', '.']);+ await git(root, ['commit', '-m', 'base']);+ return root;+};+const commit = async (root: string, file: string, text: string) => {+ await writeFile(path.join(root, file), text);+ await git(root, ['add', file]);+ await git(root, ['commit', '-m', file]);+ return resolveCommit(root, 'HEAD');+};++afterEach(async () => {+ for (const session of sessions.splice(0)) await closeRevisionSession(session);+ for (const root of owned.splice(0)) await rm(root, { force: true, recursive: true });+});++describe('isolated B → merge-candidate source pipeline', () => {+ it('includes concurrent base changes and never borrows dirty checkout sources', async () => {+ const root = await repository();+ const ancestor = await resolveCommit(root, 'HEAD');+ await git(root, ['switch', '-c', 'migration']);+ const head = await commit(root, 'component.ts', 'export const color = "blue";');+ await git(root, ['switch', 'canary']);+ const base = await commit(root, 'host.ts', 'export const width = 600;');+ await writeFile(path.join(root, 'component.ts'), 'DIRTY_WORKTREE_MUST_NOT_LEAK');+ const status = await git(root, ['status', '--porcelain=v1']);+ const session = await createRevisionSession(root, base, head);+ sessions.push(session);+ const output = path.join(root, 'output');+ await mkdir(output);+ const snapshots = await prepareSourceSnapshots(session, output);+ expect(await readFile(path.join(snapshots.base.directory, 'component.ts'), 'utf8')).toContain(+ 'red',+ );+ expect(+ await readFile(path.join(snapshots.candidate.directory, 'component.ts'), 'utf8'),+ ).toContain('blue');+ expect(await readFile(path.join(snapshots.candidate.directory, 'host.ts'), 'utf8')).toContain(+ '600',+ );+ expect(session.identity.baseSha).not.toBe(ancestor);+ expect((await git(root, ['status', '--porcelain=v1', '--untracked-files=no'])).toString()).toBe(+ status.toString(),+ );+ // The merge object is written only to the scratch object database.+ await expect(+ git(root, ['cat-file', '-e', session.identity.candidateTreeSha]),+ ).rejects.toThrow();+ expect(snapshots.base.dependencyRestore).toBe('NOT_RESTORED');+ expect(snapshots.base.dependencyInputHash).toBe(snapshots.candidate.dependencyInputHash);+ const scope = await inventoryScope(session);+ expect(scope.changedFiles).toEqual([+ { after: 'component.ts', before: 'component.ts', status: 'M' },+ ]);+ expect(scope.units.map((unit) => unit.side)).toEqual(['base', 'candidate']);+ expect(scope.limitations).toContain('TRANSITIVE_IMPACT_UNPROVEN');+ });++ it('refuses conflicting merge candidates', async () => {+ const root = await repository();+ await git(root, ['switch', '-c', 'migration']);+ const head = await commit(root, 'component.ts', 'export const color = "blue";');+ await git(root, ['switch', 'canary']);+ const base = await commit(root, 'component.ts', 'export const color = "green";');+ await expect(createRevisionSession(root, base, head)).rejects.toThrow();+ expect(await resolveCommit(root, 'HEAD')).toBe(base);+ });++ it('keeps deletions and both source sides in the inventory', async () => {+ const root = await repository();+ const base = await resolveCommit(root, 'HEAD');+ await git(root, ['rm', 'component.ts']);+ await git(root, ['commit', '-m', 'remove']);+ const session = await createRevisionSession(root, base, 'HEAD');+ sessions.push(session);+ const scope = await inventoryScope(session);+ expect(scope.changedFiles).toContainEqual({+ after: undefined,+ before: 'component.ts',+ status: 'D',+ });+ expect(scope.units).toHaveLength(1);+ expect(scope.units[0]).toMatchObject({ file: 'component.ts', side: 'base' });+ });++ it('never overwrites an existing export directory', async () => {+ const root = await repository();+ const destination = path.join(root, 'existing');+ await mkdir(destination);+ await writeFile(path.join(destination, 'keep.txt'), 'preserve');+ await expect(+ exportSourceTree(root, await resolveCommit(root, 'HEAD'), destination),+ ).rejects.toThrow();+ expect(await readFile(path.join(destination, 'keep.txt'), 'utf8')).toBe('preserve');+ });++ it('rejects shell/option-like revisions without invoking a shell', async () => {+ const root = await repository();+ for (const ref of ['--help', 'HEAD\nHEAD', '$(touch injected)', ''])+ await expect(resolveCommit(root, ref)).rejects.toThrow('INVALID_REVISION');+ });++ it('accepts shallow history only when the complete B/H-to-merge-base region exists', async () => {+ const root = await repository();+ const base = await resolveCommit(root, 'HEAD');+ const head = await commit(root, 'component.ts', 'export const color = "blue";');+ await writeFile(path.join(root, '.git/shallow'), base + '\n');+ const session = await createRevisionSession(root, base, head);+ sessions.push(session);+ expect(session.identity.headSha).toBe(head);+ await writeFile(path.join(root, '.git/shallow'), head + '\n');+ await expect(createRevisionSession(root, base, head)).rejects.toThrow();+ });++ it('rejects external source symlinks without touching their destination', async () => {+ const root = await repository();+ const outside = await mkdtemp(path.join(tmpdir(), 'stylex-verification-test-'));+ owned.push(outside);+ await writeFile(path.join(outside, 'keep.txt'), 'preserve');+ await symlink(outside, path.join(root, 'escape'));+ await git(root, ['add', 'escape']);+ await git(root, ['commit', '-m', 'external-link']);+ await expect(+ exportSourceTree(root, await resolveCommit(root, 'HEAD'), path.join(root, 'export')),+ ).rejects.toThrow('EXTERNAL_SOURCE_SYMLINK');+ expect(await readFile(path.join(outside, 'keep.txt'), 'utf8')).toBe('preserve');+ });++ it('exports safe internal links but refuses chains that defeat lexical containment', async () => {+ const root = await repository();+ await symlink('component.ts', path.join(root, 'alias.ts'));+ await git(root, ['add', 'alias.ts']);+ await git(root, ['commit', '-m', 'internal-link']);+ const first = path.join(root, 'first-export');+ await exportSourceTree(root, await resolveCommit(root, 'HEAD'), first);+ expect(await readFile(path.join(first, 'alias.ts'), 'utf8')).toContain('red');+ await symlink('alias.ts', path.join(root, 'chain.ts'));+ await git(root, ['add', 'chain.ts']);+ await git(root, ['commit', '-m', 'link-chain']);+ await expect(+ exportSourceTree(root, await resolveCommit(root, 'HEAD'), path.join(root, 'second-export')),+ ).rejects.toThrow('SOURCE_SYMLINK_CHAIN_UNSUPPORTED');+ });+});diff --git a/scripts/stylexMigration/verification/__tests__/sxArguments.test.ts b/scripts/stylexMigration/verification/__tests__/sxArguments.test.tsnew file mode 100644index 00000000000..f7a5f113086--- /dev/null+++ b/scripts/stylexMigration/verification/__tests__/sxArguments.test.ts@@ -0,0 +1,45 @@+import { fileURLToPath } from 'node:url';++import ts from 'typescript';+import { expect, it } from 'vitest';++it('accepts compiled markers, custom properties, dynamic styles and nested conditions', () => {+ const filename = fileURLToPath(new URL('./sx-arguments.contract.ts', import.meta.url));+ const source = `+ import * as stylex from '@stylexjs/stylex';+ import { sx } from '../../../../src/styles/sx';+ const styles = stylex.create({+ root: { color: 'red' },+ custom: { '--gradient-stop': '80px' },+ dynamic: (color: string) => ({ color, '--operator-color': color }),+ });+ const marker = stylex.defineMarker();+ sx([styles.root, styles.custom, marker, stylex.defaultMarker()]);+ sx([styles.dynamic('blue'), [true, false, null, undefined, styles.root]]);+ sx(styles.root, 'caller-class', { margin: 1 });+ // @ts-expect-error Raw CSS objects are not compiled StyleX arguments.+ sx({ color: 'red' });+ `;+ const options: ts.CompilerOptions = {+ esModuleInterop: true,+ module: ts.ModuleKind.ESNext,+ moduleResolution: ts.ModuleResolutionKind.Bundler,+ noEmit: true,+ skipLibCheck: true,+ strict: true,+ target: ts.ScriptTarget.ES2022,+ types: [],+ };+ const host = ts.createCompilerHost(options);+ const originalGetSourceFile = host.getSourceFile.bind(host);+ host.getSourceFile = (file, languageVersion, onError, shouldCreateNewSourceFile) =>+ file === filename+ ? ts.createSourceFile(file, source, languageVersion, true)+ : originalGetSourceFile(file, languageVersion, onError, shouldCreateNewSourceFile);+ const program = ts.createProgram({ host, options, rootNames: [filename] });+ const diagnostics = ts.getPreEmitDiagnostics(program).map((diagnostic) => ({+ code: diagnostic.code,+ message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),+ }));+ expect(diagnostics).toEqual([]);+});diff --git a/scripts/stylexMigration/verification/analysis/compositionObserver.test.ts b/scripts/stylexMigration/verification/analysis/compositionObserver.test.tsnew file mode 100644index 00000000000..2286449f199--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/compositionObserver.test.ts@@ -0,0 +1,91 @@+// @vitest-environment node+import vm from 'node:vm';++import { describe, expect, it } from 'vitest';++import { planCompositionObserver } from './compositionObserver';++const instrument = (code: string) => {+ const plan = planCompositionObserver(code, 'Component.tsx');+ let output = code;+ for (const edit of [...plan.edits].sort((a, b) => b.start - a.start))+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);+ // The controlled test's import is replaced by its injected implementation.+ output = output.replace(/import[^;]+;/, '').replace('export const ', 'const ');+ return { output, plan };+};+describe('composition observer behavior', () => {+ it('preserves return identity, argument evaluation order, exceptions and top-level calls', () => {+ const { output, plan } = instrument(+ '"use client";import {cx} from "@lobehub/ui"; const value = cx(next(), cx("b"));',+ );+ expect(output.startsWith('"use client";')).toBe(true);+ expect(plan.calls).toHaveLength(2);+ const events: unknown[] = [];+ const context = {+ cx: (...args: unknown[]) => {+ events.push(args);+ return args.join(' ');+ },+ next: () => {+ events.push('next');+ return 'a';+ },+ };+ const result = vm.runInNewContext(+ `${output}\n({value, trace:__styleVerificationCompositions})`,+ context,+ );+ expect(events).toEqual(['next', ['b'], ['a', 'b']]);+ expect(result.value).toBe('a b');+ expect(result.trace.records).toHaveLength(2);+ const error = new Error('original');+ expect(() =>+ vm.runInNewContext(output, {+ ...context,+ cx: () => {+ throw error;+ },+ }),+ ).toThrow(error);+ });+ it('resolves aliases and does not instrument shadowed parameters or local functions', () => {+ const { plan } = instrument(+ 'import {cx as merge} from "@lobehub/ui"; const value=merge("a"); function f(merge){return merge("b")}',+ );+ expect(plan.calls).toHaveLength(1);+ expect(plan.calls[0].symbol).toBe('merge');+ });+ it('never inspects non-string arguments or changes an unsupported return object', () => {+ const { output } = instrument('import {cx} from "@lobehub/ui";const value=cx(argument);');+ const argument = new Proxy(+ {},+ {+ get: () => {+ throw new Error('argument read');+ },+ },+ );+ const returned = {};+ const result = vm.runInNewContext(+ `${output}\n({value,trace:__styleVerificationCompositions})`,+ { cx: () => returned, argument },+ );+ expect(result.value).toBe(returned);+ expect(result.trace.records).toHaveLength(0);+ expect(result.trace.gaps).toEqual(['COMPOSITION_ARGUMENT_UNSUPPORTED']);+ });+ it('records unobserved aliases, unsupported syntax and budget exhaustion as gaps', () => {+ const { plan } = instrument('import {cx} from "@lobehub/ui";const alias=cx;cx?.("a");');+ expect(plan.gaps).toContain('COMPOSITION_FUNCTION_REFERENCE_UNOBSERVED');+ expect(plan.gaps).toContain('COMPOSITION_CALL_SYNTAX_UNSUPPORTED');+ const { output } = instrument(+ 'import {cx} from "@lobehub/ui";for(let i=0;i<514;i++)cx(String(i));',+ );+ const trace = vm.runInNewContext(`${output}\n__styleVerificationCompositions`, {+ cx: (s: string) => s,+ });+ expect(trace.records).toHaveLength(512);+ expect(trace.gaps).toContain('COMPOSITION_TRACE_BUDGET_EXCEEDED');+ });+});diff --git a/scripts/stylexMigration/verification/analysis/compositionObserver.ts b/scripts/stylexMigration/verification/analysis/compositionObserver.tsnew file mode 100644index 00000000000..cf0fd3edd30--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/compositionObserver.ts@@ -0,0 +1,112 @@+import ts from 'typescript';++export interface CompositionTrace {+ calls: Array<{ end: number; start: number; symbol: string }>;+ edits: Array<{ end: number; start: number; text: string }>;+ gaps: string[];+}++/** Resolve the imported symbol, not identifiers with the same spelling in inner scopes. */+export const planCompositionObserver = (code: string, file: string): CompositionTrace => {+ if (code.includes('__styleVerification'))+ throw new Error('STYLE_BINDING_OBSERVER_NAME_COLLISION');+ const ast = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const program = ts.createProgram(+ [file],+ { noLib: true, noResolve: true },+ {+ fileExists: (name) => name === file,+ getCanonicalFileName: (name) => name,+ getCurrentDirectory: () => '',+ getDefaultLibFileName: () => '',+ getNewLine: () => '\n',+ getSourceFile: (name) => (name === file ? ast : undefined),+ readFile: () => undefined,+ useCaseSensitiveFileNames: () => true,+ writeFile: () => {+ throw new Error('COMPOSITION_OBSERVER_IS_READ_ONLY');+ },+ },+ );+ const checker = program.getTypeChecker();+ const imports = new Set<ts.Symbol>();+ for (const statement of ast.statements) {+ if (+ !ts.isImportDeclaration(statement) ||+ !ts.isStringLiteral(statement.moduleSpecifier) ||+ !['@lobehub/ui', 'antd-style'].includes(statement.moduleSpecifier.text) ||+ statement.importClause?.isTypeOnly+ )+ continue;+ const named = statement.importClause?.namedBindings;+ if (!named || !ts.isNamedImports(named)) continue;+ for (const element of named.elements) {+ if (element.isTypeOnly || (element.propertyName?.text ?? element.name.text) !== 'cx')+ continue;+ const symbol = checker.getSymbolAtLocation(element.name);+ if (symbol) imports.add(symbol);+ }+ }+ const calls: CompositionTrace['calls'] = [];+ const edits: CompositionTrace['edits'] = [];+ const gaps: string[] = [];+ const visit = (node: ts.Node) => {+ if (ts.isIdentifier(node) && imports.has(checker.getSymbolAtLocation(node)!)) {+ const parent = node.parent;+ if (ts.isCallExpression(parent) && parent.expression === node) {+ if (parent.questionDotToken || parent.typeArguments?.length) {+ gaps.push('COMPOSITION_CALL_SYNTAX_UNSUPPORTED');+ } else {+ const open = parent+ .getChildren(ast)+ .find((child) => child.kind === ts.SyntaxKind.OpenParenToken);+ if (!open) throw new Error('COMPOSITION_CALL_PAREN_MISSING');+ const start = parent.getStart(ast);+ calls.push({ end: parent.end, start, symbol: node.text });+ edits.push({+ start: node.getStart(ast),+ end: node.end,+ text: '__styleVerificationCompose',+ });+ edits.push({ start: open.end, end: open.end, text: `${start},${node.text},` });+ }+ } else if (!ts.isImportSpecifier(parent))+ gaps.push('COMPOSITION_FUNCTION_REFERENCE_UNOBSERVED');+ }+ ts.forEachChild(node, visit);+ };+ visit(ast);+ // Preserve directives (including "use client"); module imports are still hoisted.+ let insertion = 0;+ for (const statement of ast.statements) {+ if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) break;+ insertion = statement.end;+ }+ edits.push({ start: insertion, end: insertion, text: `\n${compositionRuntime}\n` });+ return { calls, edits, gaps: [...new Set(gaps)] };+};++// Only primitive class strings enter telemetry. Objects/arrays are never inspected,+// serialized or passed to cx twice. The original return value/exception is preserved.+const compositionRuntime = `+export const __styleVerificationCompositions = {records: [], gaps: []};+function __styleVerificationCompose(callId, original, ...args) {+ const output = original(...args);+ const trace = __styleVerificationCompositions;+ const gap = (reason) => { if (!trace.gaps.includes(reason)) trace.gaps.push(reason); };+ if (args.length > 256 || (typeof output === 'string' && output.length > 16384) || args.some(value => typeof value === 'string' && value.length > 16384)) {+ gap('COMPOSITION_DATA_BUDGET_EXCEEDED'); return output;+ }+ if (args.some(value => typeof value !== 'string' && value !== false && value !== null && value !== undefined && value !== 0)) {+ gap('COMPOSITION_ARGUMENT_UNSUPPORTED'); return output;+ }+ if (typeof output !== 'string') { gap('COMPOSITION_RESULT_UNSUPPORTED'); return output; }+ const record = {callId, inputs: args.filter(value => typeof value === 'string'), output};+ const key = JSON.stringify(record);+ if (!trace.records.some(value => JSON.stringify(value) === key)) {+ if (trace.records.length >= 512) gap('COMPOSITION_TRACE_BUDGET_EXCEEDED');+ else trace.records.push(record);+ }+ return output;+}+`;diff --git a/scripts/stylexMigration/verification/analysis/conditionCoverage.test.ts b/scripts/stylexMigration/verification/analysis/conditionCoverage.test.tsnew file mode 100644index 00000000000..738a6455f6b--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/conditionCoverage.test.ts@@ -0,0 +1,160 @@+import { describe, expect, it } from 'vitest';++import { summarizeConditionCoverage } from './conditionCoverage';+import type { ConditionProbePlan, ConditionRequirement } from './conditionProbePlanner';+import type { RuleProbeEvidence } from './ruleCoverage';++const required: ConditionRequirement = {+ conditions: [true],+ containerKey: 'root.0',+ containerQueries: [{ key: 'root.0', name: 'card' }],+ direction: 'ltr',+ expectedActive: true,+ id: 'key',+ partition: { host: '[600]', viewport: 'independent' },+ probeId: 'probe',+ ruleId: 'rule',+ side: 'base',+ sourceUnitIds: ['unit'],+ targetKey: 'root.0.1',+ viewportWidth: 1200,+ width: 600,+};+const plan: ConditionProbePlan = {+ blocked: [],+ gateEligible: false,+ gaps: [],+ mode: 'same-target-condition-partitions',+ scheduling: 'round-robin-trigger-state-direction',+ overflow: [],+ requirements: [required],+ reused: 1,+ scheduled: [],+ variant: 'normal',+ limitations: ['CONDITION_INFLUENCE_CLOSURE_UNPROVEN'],+};+const sample: RuleProbeEvidence = {+ evidenceRefs: ['snapshot'],+ probeId: 'probe',+ side: 'base',+ variant: 'normal',+ observation: {+ registeredProperties: [],+ viewportWidth: 1200,+ direction: 'ltr',+ observations: [+ {+ id: 'rule',+ targets: [+ {+ key: 'root.0.1',+ active: true,+ conditionStates: [true],+ containers: [{ key: 'root.0', name: 'card', type: 'inline-size', width: 600 }],+ content: undefined,+ display: undefined,+ triggers: [],+ },+ ],+ },+ ],+ },+};++describe('condition keys use measured per-node evidence', () => {+ it('accepts only the actual matching stable probe and leaves another partition missing', () => {+ const result = summarizeConditionCoverage(+ [+ {+ ...plan,+ requirements: [+ required,+ {+ ...required,+ id: 'other',+ probeId: 'missing',+ partition: { ...required.partition, host: '(600,920)' },+ },+ ],+ },+ ],+ [sample],+ ['probe'],+ );+ expect(result.keys.map((key) => key.status)).toEqual(['OBSERVED', 'MISSING_PROBE']);+ expect(result.summary.missing).toBe(1);+ expect(result.gateEligible).toBe(false);+ });+ it('does not use an unstable A/A capture or an evidence-free record', () => {+ expect(summarizeConditionCoverage([plan], [sample], []).keys[0].status).toBe('PROBE_UNSTABLE');+ expect(+ summarizeConditionCoverage([plan], [{ ...sample, evidenceRefs: [] }], ['probe']).keys[0]+ .status,+ ).toBe('MISSING_PROBE');+ });+ it('checks the real query content width, viewport and predicate rather than the requested width', () => {+ const changed = structuredClone(sample);+ changed.observation.observations[0].targets[0].containers[0].width = 599.999;+ expect(summarizeConditionCoverage([plan], [changed], ['probe']).keys[0].status).toBe(+ 'ENVIRONMENT_MISMATCH',+ );+ changed.observation.observations[0].targets[0].containers[0].width = 600;+ changed.observation.viewportWidth = 1201;+ expect(summarizeConditionCoverage([plan], [changed], ['probe']).keys[0].status).toBe(+ 'ENVIRONMENT_MISMATCH',+ );+ changed.observation.viewportWidth = 1200;+ changed.observation.observations[0].targets[0].conditionStates = [false];+ expect(summarizeConditionCoverage([plan], [changed], ['probe']).keys[0].status).toBe(+ 'CONDITION_TRUTH_MISMATCH',+ );+ });+ it('does not silently treat browser-quantized decimal boundaries as exact samples', () => {+ const changed = structuredClone(sample);+ changed.observation.observations[0].targets[0].containers[0].width = 599.296875;+ const fractional = {+ ...required,+ width: 599.3,+ partition: { ...required.partition, host: '[599.3]' },+ };+ expect(+ summarizeConditionCoverage([{ ...plan, requirements: [fractional] }], [changed], ['probe'])+ .keys[0].status,+ ).toBe('ENVIRONMENT_MISMATCH');+ });+ it('retains activation failures and missing targets', () => {+ const changed = structuredClone(sample);+ changed.observation.observations[0].targets[0].active = false;+ expect(summarizeConditionCoverage([plan], [changed], ['probe']).keys[0].status).toBe(+ 'ACTIVATION_MISMATCH',+ );+ changed.observation.observations[0].targets = [];+ expect(summarizeConditionCoverage([plan], [changed], ['probe']).keys[0].status).toBe(+ 'TARGET_UNMOUNTED',+ );+ });+ it('checks the actual direction and nearest named query container, not just the presence of an outer host', () => {+ const changed = structuredClone(sample);+ changed.observation.direction = 'rtl';+ expect(summarizeConditionCoverage([plan], [changed], ['probe']).keys[0].status).toBe(+ 'ENVIRONMENT_MISMATCH',+ );+ changed.observation.direction = 'ltr';+ changed.observation.observations[0].targets[0].containers.unshift({+ key: 'root.0.1.inner',+ name: 'card',+ type: 'inline-size',+ width: 600,+ });+ expect(summarizeConditionCoverage([plan], [changed], ['probe']).keys[0].status).toBe(+ 'ENVIRONMENT_MISMATCH',+ );+ });+ it('does not certify content width when query-container scrollbar metrics are unproven', () => {+ const changed = structuredClone(sample);+ changed.observation.observations[0].targets[0].containers[0].metricsTrusted = false;+ expect(summarizeConditionCoverage([plan], [changed], ['probe']).keys[0].status).toBe(+ 'ENVIRONMENT_MISMATCH',+ );+ });+});diff --git a/scripts/stylexMigration/verification/analysis/conditionCoverage.ts b/scripts/stylexMigration/verification/analysis/conditionCoverage.tsnew file mode 100644index 00000000000..0167e71d668--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/conditionCoverage.ts@@ -0,0 +1,95 @@+import type { ConditionProbePlan } from './conditionProbePlanner';+import type { RuleProbeEvidence } from './ruleCoverage';++const matchesCell = (id: string, width: number, planned: number) => {+ if (!Number.isFinite(width)) return false;+ if (id === 'independent') return Math.abs(width - planned) < 1e-7;+ if (id.startsWith('[')) return Math.abs(width - Number(id.slice(1, -1))) < 1e-7;+ const [lower, upper] = id.slice(1, -1).split(',').map(Number);+ return width > lower && width < upper;+};++/** Per side/rule/node/partition/direction/operation records, still not certified+ * gate witnesses. In particular a rule hit in one cell cannot close another. */+export const summarizeConditionCoverage = (+ plans: ConditionProbePlan[],+ evidence: RuleProbeEvidence[],+ stableProbeIds: string[],+) => {+ const stable = new Set(stableProbeIds);+ const keys = plans.flatMap((plan) =>+ plan.requirements.map((required) => {+ const sample = evidence.find(+ (entry) =>+ entry.probeId === required.probeId &&+ entry.side === required.side &&+ entry.variant === plan.variant,+ );+ const target = sample?.observation.observations+ .find((entry) => entry.id === required.ruleId)+ ?.targets.find((entry) => entry.key === required.targetKey);+ const container = target?.containers.find((entry) => entry.key === required.containerKey);+ const status =+ !sample || !sample.evidenceRefs.length+ ? 'MISSING_PROBE'+ : !stable.has(required.probeId)+ ? 'PROBE_UNSTABLE'+ : !target+ ? 'TARGET_UNMOUNTED'+ : sample.observation.direction !== required.direction ||+ required.containerQueries.some(+ (query) =>+ target.containers.find(+ (entry) => !query.name || entry.name.split(/\s+/).includes(query.name),+ )?.key !== query.key ||+ target.containers.find(+ (entry) => !query.name || entry.name.split(/\s+/).includes(query.name),+ )?.metricsTrusted === false,+ ) ||+ !matchesCell(+ required.partition.viewport,+ sample.observation.viewportWidth,+ required.viewportWidth,+ ) ||+ (required.containerKey &&+ (!container ||+ container.metricsTrusted === false ||+ !matchesCell(required.partition.host, container.width, required.width)))+ ? 'ENVIRONMENT_MISMATCH'+ : JSON.stringify(target.conditionStates) !== JSON.stringify(required.conditions)+ ? 'CONDITION_TRUTH_MISMATCH'+ : target.active !== required.expectedActive+ ? 'ACTIVATION_MISMATCH'+ : 'OBSERVED';+ return {+ ...required,+ status,+ variant: plan.variant,+ evidenceRefs: sample?.evidenceRefs ?? [],+ actual: target+ ? {+ active: target.active,+ conditions: target.conditionStates,+ containerWidth: container?.width,+ viewportWidth: sample?.observation.viewportWidth,+ direction: sample?.observation.direction,+ }+ : undefined,+ };+ }),+ );+ return {+ gateEligible: false as const,+ keys,+ limitations: [...new Set(plans.flatMap((plan) => plan.limitations))],+ summary: {+ required: keys.length,+ observed: keys.filter((entry) => entry.status === 'OBSERVED').length,+ missing: keys.filter((entry) => entry.status !== 'OBSERVED').length,+ blockedBindings: plans.reduce((sum, plan) => sum + plan.blocked.length, 0),+ scheduledProbes: plans.reduce((sum, plan) => sum + plan.scheduled.length, 0),+ overflowProbes: plans.reduce((sum, plan) => sum + plan.overflow.length, 0),+ reusedRequirements: plans.reduce((sum, plan) => sum + plan.reused, 0),+ },+ };+};diff --git a/scripts/stylexMigration/verification/analysis/conditionPartitions.test.ts b/scripts/stylexMigration/verification/analysis/conditionPartitions.test.tsnew file mode 100644index 00000000000..e52864af93f--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/conditionPartitions.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';++import { matchesWidth, parseWidthCondition, partitionWidths } from './conditionPartitions';++describe('tokenized width conditions', () => {+ it.each([+ ['(max-width: 600px)', 600, true],+ ['(width < 600px)', 600, false],+ ['(600px <= width)', 600, true],+ ['(599.2px < width <= 599.4px)', 599.3, true],+ ['card (width > 500px) and (width < 700px)', 600, true],+ ] as const)('evaluates %s at %s', (text, width, expected) => {+ expect(matchesWidth(parseWidthCondition(text)!, width)).toBe(expected);+ });+ it.each([+ 'not (width > 600px)',+ '(width > 600px) or (width < 300px)',+ '(width > 30em)',+ 'style(--x: red)',+ '(height: 600px)',+ '(width: 2px) and',+ '(width: 2px',+ '(color)',+ 'screen and (width > 600px)',+ ])('retains unsupported syntax as a gap: %s', (query) => {+ expect(parseWidthCondition(query)).toBeUndefined();+ });+ it('partitions close decimal boundaries with an interior instead of ±1 guesses', () => {+ const conditions = [+ parseWidthCondition('(width < 599.2px)')!,+ parseWidthCondition('(width > 599.4px)')!,+ ];+ const widths = partitionWidths(conditions, 320, 920);+ expect(widths).toContain(599.3);+ expect(widths).toContain(599.2);+ expect(widths).toContain(599.4);+ expect(() => partitionWidths(conditions, 920, 320)).toThrow('INVALID_WIDTH_DOMAIN');+ });+});diff --git a/scripts/stylexMigration/verification/analysis/conditionPartitions.ts b/scripts/stylexMigration/verification/analysis/conditionPartitions.tsnew file mode 100644index 00000000000..9203f6e62f4--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/conditionPartitions.ts@@ -0,0 +1,131 @@+import valueParser from 'postcss-value-parser';++export interface WidthCondition {+ bounds: Array<{ operator: '<' | '<=' | '=' | '>' | '>='; value: number }>;+ name?: string;+}++/** Conservative token AST grammar. Unsupported logic is not approximated. */+export const parseWidthCondition = (text: string): WidthCondition | undefined => {+ const nodes = valueParser(text).nodes.filter((node) => !['space', 'comment'].includes(node.type));+ let name: string | undefined;+ if (+ nodes[0]?.type === 'word' &&+ /^[a-z_][\w-]*$/i.test(nodes[0].value) &&+ !['not', 'only', 'all', 'screen', 'print'].includes(nodes[0].value)+ )+ name = nodes.shift()!.value;+ const bounds: WidthCondition['bounds'] = [];+ const number = (value: string) => {+ const match = value.match(/^(\d+(?:\.\d+)?|\.\d+)px$/i);+ return match && Number.isFinite(Number(match[1])) ? Number(match[1]) : undefined;+ };+ const inverse = { '<': '>', '<=': '>=', '>': '<', '>=': '<=', '=': '=' } as const;+ for (let index = 0; index < nodes.length; index++) {+ const node = nodes[index];+ if (index % 2) {+ if (node.type !== 'word' || node.value !== 'and') return;+ continue;+ }+ if (node.type !== 'function' || node.value || node.unclosed) return;+ const parts = node.nodes+ .filter((part) => !['space', 'comment'].includes(part.type))+ .map((part) => (part.type === 'word' || part.type === 'div' ? part.value : '?'));+ if (+ parts.length === 3 &&+ parts[1] === ':' &&+ ['min-width', 'max-width', 'width'].includes(parts[0])+ ) {+ const value = number(parts[2]);+ if (value === undefined) return;+ bounds.push({+ operator: parts[0] === 'min-width' ? '>=' : parts[0] === 'max-width' ? '<=' : '=',+ value,+ });+ } else if ([3, 5].includes(parts.length)) {+ for (let cursor = 0; cursor < parts.length - 2; cursor += 2) {+ const [left, operator, right] = parts.slice(cursor, cursor + 3);+ if (!Object.hasOwn(inverse, operator)) return;+ const typed = operator as keyof typeof inverse;+ const value = number(left === 'width' ? right : left);+ if (value === undefined || (left !== 'width' && right !== 'width')) return;+ bounds.push({ operator: left === 'width' ? typed : inverse[typed], value });+ }+ } else return;+ }+ return bounds.length && nodes.length % 2 ? { bounds, name } : undefined;+};++export const matchesWidth = (condition: WidthCondition, width: number) =>+ condition.bounds.every(({ operator, value }) => {+ switch (operator) {+ case '<': {+ return width < value;+ }+ case '<=': {+ return width <= value;+ }+ case '>': {+ return width > value;+ }+ case '>=': {+ return width >= value;+ }+ case '=': {+ return width === value;+ }+ }+ });++/** Explicit finite host contract; interiors never jump across close boundaries. */+export const partitionWidths = (conditions: WidthCondition[], minimum: number, maximum: number) => {+ if (!Number.isFinite(minimum) || !Number.isFinite(maximum) || minimum < 0 || minimum >= maximum)+ throw new Error('INVALID_WIDTH_DOMAIN');+ const boundaries = [+ ...new Set([+ minimum,+ maximum,+ ...conditions+ .flatMap((condition) => condition.bounds.map((bound) => bound.value))+ .filter((value) => value > minimum && value < maximum),+ ]),+ ].sort((a, b) => a - b);+ const widths = [...boundaries];+ for (let index = 1; index < boundaries.length; index++)+ widths.push((boundaries[index - 1] + boundaries[index]) / 2);+ return widths.sort((a, b) => a - b);+};++/** Keep every boundary and open interval. Existing probes may represent an+ * interval, but are never treated as proof of fluid-layout equivalence. */+export const partitionWidthCells = (+ conditions: WidthCondition[],+ minimum: number,+ maximum: number,+ preferred: number[] = [],+) => {+ partitionWidths(conditions, minimum, maximum); // validates the declared domain+ const boundaries = [+ ...new Set([+ minimum,+ maximum,+ ...conditions.flatMap((condition) =>+ condition.bounds+ .map((bound) => bound.value)+ .filter((value) => value > minimum && value < maximum),+ ),+ ]),+ ].sort((a, b) => a - b);+ return boundaries.flatMap((width, index) => {+ const result = [{ id: `[${width}]`, width }];+ const next = boundaries[index + 1];+ if (next !== undefined) {+ const midpoint = (width + next) / 2;+ const available = preferred+ .filter((value) => value > width && value < next)+ .sort((a, b) => Math.abs(a - midpoint) - Math.abs(b - midpoint) || a - b);+ result.push({ id: `(${width},${next})`, width: available[0] ?? midpoint });+ }+ return result;+ });+};diff --git a/scripts/stylexMigration/verification/analysis/conditionProbePlanner.test.ts b/scripts/stylexMigration/verification/analysis/conditionProbePlanner.test.tsnew file mode 100644index 00000000000..edca0a4c77c--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/conditionProbePlanner.test.ts@@ -0,0 +1,208 @@+import { describe, expect, it } from 'vitest';++import type { FixtureProbe } from '../pipeline/probePlanner';+import type { ConditionSeed } from './conditionProbePlanner';+import { planConditionProbes } from './conditionProbePlanner';+import { planRuleWitnesses } from './ruleWitnesses';++const makeSeed = (+ options: {+ conditions?: Array<{ kind: string; text: string }>;+ key?: string;+ selector?: string;+ side?: 'base' | 'candidate';+ } = {},+): ConditionSeed => {+ const plan = planRuleWitnesses(+ {+ gaps: [],+ rules: [+ {+ path: '0.0',+ kind: 'CSSStyleRule',+ selector: options.selector ?? '.row:hover',+ conditions: options.conditions ?? [],+ selectorAncestors: [],+ text: '',+ },+ ],+ },+ {+ bindings: [+ {+ kind: 'css-module',+ symbol: 'styles',+ slots: [{ name: 'row', start: 0, end: 1, unitId: 'unit' }],+ },+ ],+ gaps: [],+ source: 'file',+ sourceHash: 'hash',+ stylesheets: [],+ },+ { styles: { row: 'row' } },+ );+ const key = options.key ?? 'root.0.0';+ return {+ hostKey: 'root.0',+ legacyTriggerKey: key,+ side: options.side ?? 'base',+ plan,+ observation: {+ registeredProperties: [],+ viewportWidth: 1200,+ direction: 'ltr',+ observations: [+ {+ id: plan.rules[0].id,+ targets: [+ {+ key,+ active: false,+ conditionStates: plan.rules[0].conditions.map(() => true),+ containers: [{ key: 'root.0', name: 'card', type: 'inline-size', width: 320 }],+ content: undefined,+ display: undefined,+ triggers: [{ key, state: 'hover', tag: 'TR' }],+ },+ ],+ },+ ],+ },+ };+};+const probe: FixtureProbe = {+ direction: 'ltr',+ id: 'original',+ pseudo: 'default',+ variant: 'normal',+ width: 599,+};+const options = {+ hostDomain: [320, 920] as [number, number],+ viewportDomain: [320, 1200] as [number, number],+ probes: [probe],+ remaining: 256,+ variant: 'normal',+};++describe('source-bound condition partition planning', () => {+ it('unions B/M boundaries on the same target, reuses existing environments and preserves the declared matrix', () => {+ const probes = [probe, { ...probe, id: 'legacy-hover', pseudo: 'hover' as const }];+ const before = JSON.stringify(probes);+ const plan = planConditionProbes({+ ...options,+ probes,+ seeds: [+ makeSeed({ conditions: [{ kind: 'CSSContainerRule', text: '(max-width:600px)' }] }),+ makeSeed({+ side: 'candidate',+ conditions: [{ kind: 'CSSContainerRule', text: 'card (max-width:800px)' }],+ }),+ ],+ });+ expect(JSON.stringify(probes)).toBe(before);+ expect(plan.requirements.some((key) => key.width === 600)).toBe(true);+ expect(plan.requirements.some((key) => key.width === 800)).toBe(true);+ expect(+ plan.requirements.some(+ (key) => key.partition.host === '(320,600)' && key.probeId === 'legacy-hover',+ ),+ ).toBe(true);+ expect(plan.reused).toBeGreaterThan(0);+ expect(new Set(plan.requirements.map((key) => key.id)).size).toBe(plan.requirements.length);+ expect(plan.gateEligible).toBe(false);+ });+ it('does not cross unrelated media/container paths, but keeps their intersection on a shared target', () => {+ const media = makeSeed({ conditions: [{ kind: 'CSSMediaRule', text: '(max-width:700px)' }] });+ const container = makeSeed({+ key: 'root.0.1',+ conditions: [{ kind: 'CSSContainerRule', text: '(max-width:600px)' }],+ });+ const separate = planConditionProbes({ ...options, seeds: [media, container] });+ expect(+ separate.scheduled.some((probe) => probe.width !== 320 && probe.viewportWidth !== 1200),+ ).toBe(false);+ const together = planConditionProbes({+ ...options,+ seeds: [+ media,+ makeSeed({+ side: 'candidate',+ conditions: [{ kind: 'CSSContainerRule', text: '(max-width:600px)' }],+ }),+ ],+ });+ expect(+ together.scheduled.some((probe) => probe.width === 600 && probe.viewportWidth === 700),+ ).toBe(true);+ });+ it('never merges two DOM triggers just because they share a class', () => {+ const plan = planConditionProbes({+ ...options,+ seeds: [makeSeed(), makeSeed({ key: 'root.0.1' })],+ });+ expect(+ new Set(plan.scheduled.flatMap((probe) => (probe.interaction ? [probe.interaction.key] : [])))+ .size,+ ).toBe(2);+ });+ it('retains all required keys and overflow when the remaining probe budget is zero', () => {+ const plan = planConditionProbes({ ...options, seeds: [makeSeed()], remaining: 0 });+ expect(plan.scheduled).toHaveLength(0);+ expect(plan.overflow.length).toBeGreaterThan(0);+ expect(plan.requirements).toHaveLength(2);+ expect(plan.gaps).toContain('CONDITION_PROBE_BUDGET_EXCEEDED');+ });+ it('refuses unowned named containers and retains unsupported/unmounted branches', () => {+ const seed = makeSeed({+ conditions: [{ kind: 'CSSContainerRule', text: 'other (max-width:600px)' }],+ });+ expect(planConditionProbes({ ...options, seeds: [seed] }).gaps).toContain(+ 'QUERY_CONTAINER_NOT_CONTROLLABLE',+ );+ const unmounted = { ...seed, observation: { ...seed.observation, observations: [] } };+ expect(planConditionProbes({ ...options, seeds: [unmounted] }).gaps).toContain(+ 'CONDITION_TARGET_UNMOUNTED',+ );+ const unsupported = makeSeed({ selector: '.row:has(.child:hover)' });+ expect(planConditionProbes({ ...options, seeds: [unsupported] }).gaps).toContain(+ 'CONDITION_RULE_OR_TRIGGER_UNSUPPORTED',+ );+ });+ it('retains unrepresentable fractional viewport boundaries instead of rounding them into coverage', () => {+ const plan = planConditionProbes({+ ...options,+ seeds: [makeSeed({ conditions: [{ kind: 'CSSMediaRule', text: '(width < 599.3px)' }] })],+ });+ expect(plan.gaps).toContain('VIEWPORT_PARTITION_UNREPRESENTABLE');+ expect(plan.scheduled.every((probe) => Number.isInteger(probe.viewportWidth))).toBe(true);+ });+ it('gives later rows and both directions a sample before expanding the first row across every width', () => {+ const plan = planConditionProbes({+ ...options,+ remaining: 10,+ seeds: Array.from({ length: 4 }, (_, index) =>+ makeSeed({+ key: `root.0.${index}`,+ conditions: [{ kind: 'CSSContainerRule', text: '(max-width:600px)' }],+ }),+ ),+ });+ const scheduled = plan.scheduled.filter((probe) => probe.interaction);+ expect(+ new Set(scheduled.map((probe) => `${probe.interaction!.key}:${probe.direction}`)).size,+ ).toBe(8);+ expect(plan.overflow.length).toBeGreaterThan(0);+ expect(new Set([...plan.scheduled, ...plan.overflow].map((probe) => probe.id)).size).toBe(+ plan.scheduled.length + plan.overflow.length,+ );+ expect(+ plan.requirements.every(+ (key) =>+ options.probes.some((probe) => probe.id === key.probeId) ||+ [...plan.scheduled, ...plan.overflow].some((probe) => probe.id === key.probeId),+ ),+ ).toBe(true);+ });+});diff --git a/scripts/stylexMigration/verification/analysis/conditionProbePlanner.ts b/scripts/stylexMigration/verification/analysis/conditionProbePlanner.tsnew file mode 100644index 00000000000..97a6f4926c8--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/conditionProbePlanner.ts@@ -0,0 +1,290 @@+import type { FixtureProbe } from '../pipeline/probePlanner';+import type { WidthCondition } from './conditionPartitions';+import { matchesWidth, partitionWidthCells } from './conditionPartitions';+import type { RuleObservation, RuleWitnessPlan } from './ruleWitnesses';++export interface ConditionSeed {+ hostKey: string;+ hostWritingMode?: string;+ legacyTriggerKey?: string;+ legacyTriggerKeys?: Record<string, string | undefined>;+ observation: RuleObservation;+ plan: RuleWitnessPlan;+ side: 'base' | 'candidate';+}+export interface ConditionRequirement {+ conditions: boolean[];+ containerKey?: string;+ containerQueries: Array<{ key: string; name?: string }>;+ direction: FixtureProbe['direction'];+ expectedActive: boolean;+ id: string;+ partition: { host: string; viewport: string };+ probeId: string;+ ruleId: string;+ side: 'base' | 'candidate';+ sourceUnitIds: string[];+ targetKey: string;+ viewportWidth: number;+ width: number;+}++/** Read only the controlled host and legacy trigger; no marker/DOM mutation. */+export const readConditionHostInPage = (selectors: {+ 'hover'?: string;+ 'focus-visible'?: string;+}) => {+ const root = document.querySelector('[data-case-root]');+ if (!root) throw new Error('CONDITION_ROOT_MISSING');+ const keys = new Map<Element, string>();+ const walk = (element: Element, key: string) => {+ keys.set(element, key);+ [...element.children]+ .filter((child) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(child.tagName))+ .forEach((child, index) => walk(child, `${key}.${index}`));+ };+ walk(root, 'root');+ const host = document.querySelector('[data-component-mount]')?.firstElementChild;+ if (!host || !keys.has(host)) throw new Error('CONTROLLED_CONTAINER_MISSING');+ return {+ hostKey: keys.get(host)!,+ hostWritingMode: getComputedStyle(host).writingMode,+ legacyTriggerKeys: Object.fromEntries(+ Object.entries(selectors).map(([state, selector]) => [+ state,+ selector ? keys.get(document.querySelector(selector)!) : undefined,+ ]),+ ),+ };+};++/** Required keys are diagnostic, not certified source coverage. Preserve the+ * entire declared host matrix. Only identical environment + operation is reused. */+export const planConditionProbes = (options: {+ hostDomain: [number, number];+ probes: FixtureProbe[];+ remaining: number;+ seeds: ConditionSeed[];+ variant: string;+ viewportDomain: [number, number];+}) => {+ const entries = options.seeds.flatMap((seed) =>+ seed.plan.rules.flatMap((rule) => {+ const targets =+ seed.observation.observations.find((entry) => entry.id === rule.id)?.targets ?? [];+ return targets.map((target) => ({ seed, rule, target }));+ }),+ );+ const requirements: ConditionRequirement[] = [];+ const blocked: Array<{ reason: string; ruleId: string; side: string; targetKey?: string }> = [];+ const generated: FixtureProbe[] = [];+ const existing = options.probes.filter((probe) => probe.variant === options.variant);+ const candidates = [...existing];+ let reused = 0;+ for (const { seed, rule, target } of entries) {+ if (+ rule.gaps.length ||+ rule.states.length > 1 ||+ (rule.states.length === 1 && target.triggers.length !== 1)+ ) {+ blocked.push({+ reason: 'CONDITION_RULE_OR_TRIGGER_UNSUPPORTED',+ ruleId: rule.id,+ side: seed.side,+ targetKey: target.key,+ });+ continue;+ }+ // B/M rules affecting this same DOM binding contribute their conditions.+ // Ancestor/sibling/layout influence closure is still explicitly unproven.+ const related = entries.filter((entry) => entry.target.key === target.key);+ const hostConditions: WidthCondition[] = [];+ const viewportConditions: WidthCondition[] = [];+ let reason: string | undefined;+ for (const entry of related)+ for (const condition of entry.rule.conditionModels) {+ if (condition.kind === 'CSSSupportsRule') continue;+ if (!condition.width) {+ reason = 'CONDITION_WIDTH_GRAMMAR_UNSUPPORTED';+ continue;+ }+ if (condition.kind === 'CSSMediaRule') {+ if (condition.width.name) reason = 'MEDIA_TYPE_UNSUPPORTED';+ else viewportConditions.push(condition.width);+ } else if (condition.kind === 'CSSContainerRule') {+ if (entry.seed.hostWritingMode && entry.seed.hostWritingMode !== 'horizontal-tb')+ reason = 'QUERY_WRITING_MODE_UNSUPPORTED';+ const container = entry.target.containers.find(+ (candidate) =>+ !condition.width!.name ||+ candidate.name.split(/\s+/).includes(condition.width!.name!),+ );+ if (container?.key !== entry.seed.hostKey) reason = 'QUERY_CONTAINER_NOT_CONTROLLABLE';+ else if (container.metricsTrusted === false) reason = 'QUERY_CONTENT_METRICS_UNSUPPORTED';+ else hostConditions.push(condition.width);+ } else reason = 'CONDITION_KIND_UNSUPPORTED';+ }+ if (reason) {+ blocked.push({ reason, ruleId: rule.id, side: seed.side, targetKey: target.key });+ continue;+ }+ const hostCells = hostConditions.length+ ? partitionWidthCells(+ hostConditions,+ ...options.hostDomain,+ existing.map((probe) => probe.width),+ )+ : [{ id: 'independent', width: options.hostDomain[0] }];+ const viewportCells = viewportConditions.length+ ? partitionWidthCells(+ viewportConditions,+ ...options.viewportDomain,+ existing.map((probe) => probe.viewportWidth ?? 1200),+ )+ : [{ id: 'independent', width: 1200 }];+ if (requirements.length + hostCells.length * viewportCells.length * 2 > 12000) {+ blocked.push({+ reason: 'CONDITION_KEY_BUDGET_EXCEEDED',+ ruleId: rule.id,+ side: seed.side,+ targetKey: target.key,+ });+ continue;+ }+ for (const direction of ['ltr', 'rtl'] as const)+ for (const host of hostCells)+ for (const viewport of viewportCells) {+ if (!Number.isInteger(viewport.width)) {+ blocked.push({+ reason: 'VIEWPORT_PARTITION_UNREPRESENTABLE',+ ruleId: rule.id,+ side: seed.side,+ targetKey: target.key,+ });+ continue;+ }+ const conditions = rule.conditionModels.map((condition, index) =>+ condition.kind === 'CSSSupportsRule'+ ? target.conditionStates[index]+ : matchesWidth(+ condition.width!,+ condition.kind === 'CSSMediaRule' ? viewport.width : host.width,+ ),+ );+ if (conditions.some((state) => state === null || state === undefined)) {+ blocked.push({+ reason: 'CONDITION_TRUTH_UNRESOLVED',+ ruleId: rule.id,+ side: seed.side,+ targetKey: target.key,+ });+ continue;+ }+ const expectedActive = conditions.every(Boolean);+ const interaction = expectedActive && rule.states.length ? target.triggers[0] : undefined;+ const match = candidates.find(+ (probe) =>+ probe.direction === direction &&+ probe.width === host.width &&+ (probe.viewportWidth ?? 1200) === viewport.width &&+ (interaction+ ? (probe.interaction?.key === interaction.key &&+ probe.interaction.state === interaction.state) ||+ (!probe.interaction &&+ probe.pseudo === interaction.state &&+ (seed.legacyTriggerKeys?.[interaction.state] ?? seed.legacyTriggerKey) ===+ interaction.key)+ : !probe.interaction && probe.pseudo === 'default'),+ );+ let probe = match;+ if (probe) reused++;+ else {+ probe = {+ direction,+ id: `condition:${options.variant}:${direction}:${host.width}:${viewport.width}:${interaction?.key ?? 'default'}:${interaction?.state ?? 'default'}`,+ interaction,+ pseudo: 'default',+ variant: options.variant,+ viewportWidth: viewport.width,+ width: host.width,+ };+ generated.push(probe);+ candidates.push(probe);+ }+ requirements.push({+ conditions: conditions as boolean[],+ containerKey: hostConditions.length ? seed.hostKey : undefined,+ containerQueries: rule.conditionModels+ .filter((condition) => condition.kind === 'CSSContainerRule')+ .map((condition) => ({ key: seed.hostKey, name: condition.width?.name })),+ direction,+ expectedActive,+ id: JSON.stringify([+ seed.side,+ options.variant,+ rule.id,+ target.key,+ direction,+ host.id,+ viewport.id,+ interaction?.state ?? 'default',+ ]),+ partition: { host: host.id, viewport: viewport.id },+ probeId: probe.id,+ ruleId: rule.id,+ side: seed.side,+ sourceUnitIds: rule.sourceUnitIds,+ targetKey: target.key,+ viewportWidth: viewport.width,+ width: host.width,+ });+ }+ }+ for (const seed of options.seeds)+ for (const rule of seed.plan.rules)+ if (!entries.some((entry) => entry.seed === seed && entry.rule === rule))+ blocked.push({+ reason: rule.gaps.length+ ? 'CONDITION_RULE_OR_TRIGGER_UNSUPPORTED'+ : 'CONDITION_TARGET_UNMOUNTED',+ ruleId: rule.id,+ side: seed.side,+ });+ // Do not spend the remaining budget on every width of the first row while+ // later rows get no state sample at all. This only orders work; every unmet+ // key and every overflow probe remains in the report.+ const groups = new Map<string, FixtureProbe[]>();+ for (const probe of generated) {+ const key = JSON.stringify([probe.interaction?.key, probe.interaction?.state, probe.direction]);+ const group = groups.get(key) ?? [];+ group.push(probe);+ groups.set(key, group);+ }+ const ordered: FixtureProbe[] = [];+ for (let index = 0; ordered.length < generated.length; index++)+ for (const group of groups.values()) if (group[index]) ordered.push(group[index]);+ const scheduled = ordered.slice(0, Math.max(0, options.remaining));+ return {+ blocked,+ gateEligible: false as const,+ gaps: [+ ...new Set([+ ...blocked.map((entry) => entry.reason),+ ...(generated.length > scheduled.length ? ['CONDITION_PROBE_BUDGET_EXCEEDED'] : []),+ ]),+ ],+ mode: 'same-target-condition-partitions' as const,+ overflow: ordered.slice(scheduled.length),+ scheduling: 'round-robin-trigger-state-direction' as const,+ requirements,+ reused,+ scheduled,+ variant: options.variant,+ limitations: [+ 'CONDITION_INFLUENCE_CLOSURE_UNPROVEN',+ 'FLUID_LAYOUT_EQUIVALENCE_UNPROVEN',+ 'SOURCE_RULE_MAPPING_NOT_CERTIFIED',+ ],+ };+};+export type ConditionProbePlan = ReturnType<typeof planConditionProbes>;diff --git a/scripts/stylexMigration/verification/analysis/ruleCoverage.test.ts b/scripts/stylexMigration/verification/analysis/ruleCoverage.test.tsnew file mode 100644index 00000000000..f06c1f65012--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/ruleCoverage.test.ts@@ -0,0 +1,185 @@+import { expect, it } from 'vitest';++import { summarizeRuleCoverage } from './ruleCoverage';+import { planRuleWitnesses } from './ruleWitnesses';++it('reports an untouched second interaction target instead of closing the rule after one hit', () => {+ const plan = planRuleWitnesses(+ {+ gaps: [],+ rules: [+ {+ kind: 'CSSStyleRule',+ path: '0.0',+ selector: '.row:hover',+ selectorAncestors: [],+ conditions: [],+ text: '',+ },+ ],+ },+ {+ bindings: [+ {+ symbol: 'styles',+ kind: 'static-factory',+ slots: [{ name: 'row', unitId: 'unit', start: 0, end: 1 }],+ },+ ],+ gaps: [],+ source: 'file',+ sourceHash: 'hash',+ stylesheets: [],+ },+ { styles: { row: 'row' } },+ );+ const result = summarizeRuleCoverage(+ [{ plan, side: 'base', variant: 'normal' }],+ [+ {+ evidenceRefs: ['snapshot.json.gz'],+ probeId: 'hover-first',+ side: 'base',+ variant: 'normal',+ observation: {+ registeredProperties: [],+ viewportWidth: 1200,+ direction: 'ltr',+ observations: [+ {+ id: '0.0:0',+ targets: [+ {+ active: true,+ conditionStates: [],+ triggers: [],+ containers: [],+ key: 'root.0',+ content: undefined,+ display: undefined,+ },+ {+ active: false,+ conditionStates: [],+ triggers: [],+ containers: [],+ key: 'root.1',+ content: undefined,+ display: undefined,+ },+ ],+ },+ ],+ },+ },+ ],+ );+ expect(result.rules[0].status).toBe('PARTIAL_ACTIVATION');+ expect(result.rules[0].missingActivationKeys).toEqual(['root.1']);+ expect(result.gateEligible).toBe(false);+});++it('keeps unmounted source branches in the denominator', () => {+ const plan = planRuleWitnesses(+ {+ gaps: [],+ rules: [+ {+ kind: 'CSSStyleRule',+ path: '0.0',+ selector: '.unused',+ selectorAncestors: [],+ conditions: [],+ text: '',+ },+ ],+ },+ {+ bindings: [+ {+ symbol: 'styles',+ kind: 'static-factory',+ slots: [{ name: 'unused', unitId: 'unit', start: 0, end: 1 }],+ },+ ],+ gaps: [],+ source: 'file',+ sourceHash: 'hash',+ stylesheets: [],+ },+ { styles: { unused: 'unused' } },+ );+ expect(+ summarizeRuleCoverage([{ plan, side: 'candidate', variant: 'normal' }], []).summary.unmounted,+ ).toBe(1);+});++it('does not treat an intentional empty variant as globally missing when another variant mounts the rule', () => {+ const plan = planRuleWitnesses(+ {+ gaps: [],+ rules: [+ {+ kind: 'CSSStyleRule',+ path: '0.0',+ selector: '.row',+ selectorAncestors: [],+ conditions: [],+ text: '',+ },+ ],+ },+ {+ bindings: [+ {+ symbol: 'styles',+ kind: 'static-factory',+ slots: [{ name: 'row', unitId: 'unit', start: 0, end: 1 }],+ },+ ],+ gaps: [],+ source: 'file',+ sourceHash: 'hash',+ stylesheets: [],+ },+ { styles: { row: 'row' } },+ );+ const result = summarizeRuleCoverage(+ [+ { plan, side: 'base', variant: 'normal' },+ { plan, side: 'base', variant: 'empty' },+ ],+ [+ {+ evidenceRefs: ['snapshot.json.gz'],+ probeId: 'default',+ side: 'base',+ variant: 'normal',+ observation: {+ registeredProperties: [],+ viewportWidth: 1200,+ direction: 'ltr',+ observations: [+ {+ id: '0.0:0',+ targets: [+ {+ active: true,+ conditionStates: [],+ triggers: [],+ containers: [],+ key: 'root.0',+ content: undefined,+ display: undefined,+ },+ ],+ },+ ],+ },+ },+ ],+ );+ expect(result.summary.unmounted).toBe(1);+ expect(result.summary.globallyUnmounted).toBe(0);+ expect(result.summary.uniqueActivationBranches).toBe(1);+});diff --git a/scripts/stylexMigration/verification/analysis/ruleCoverage.ts b/scripts/stylexMigration/verification/analysis/ruleCoverage.tsnew file mode 100644index 00000000000..b9fecfbbd73--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/ruleCoverage.ts@@ -0,0 +1,121 @@+import type { RuleObservation, RuleWitnessPlan } from './ruleWitnesses';++export interface RuleProbeEvidence {+ evidenceRefs: string[];+ observation: RuleObservation;+ probeId: string;+ side: 'base' | 'candidate';+ variant: string;+}++/** Diagnostic activation coverage, never a substitute for all required gate keys. */+export const summarizeRuleCoverage = (+ plans: Array<{ plan: RuleWitnessPlan; side: 'base' | 'candidate'; variant: string }>,+ evidence: RuleProbeEvidence[],+) => {+ const rules = plans.flatMap(({ plan, side, variant }) =>+ plan.rules.map((rule) => {+ const samples = evidence+ .filter((item) => item.side === side && item.variant === variant)+ .flatMap((item) => {+ const observation = item.observation.observations.find((entry) => entry.id === rule.id);+ return (+ observation?.targets.map((target) => ({+ ...target,+ evidenceRefs: item.evidenceRefs,+ probeId: item.probeId,+ })) ?? []+ );+ });+ const targetKeys = [...new Set(samples.map((sample) => sample.key))].sort();+ const activeKeys = [+ ...new Set(samples.filter((sample) => sample.active).map((sample) => sample.key)),+ ].sort();+ const requiredActivationKeys = [+ ...new Set(+ samples+ .filter((sample) => sample.conditionStates.every((condition) => condition === true))+ .map((sample) => sample.key),+ ),+ ].sort();+ const missingActivationKeys = requiredActivationKeys.filter(+ (key) => !activeKeys.includes(key),+ );+ const inactiveKeys = [+ ...new Set(samples.filter((sample) => !sample.active).map((sample) => sample.key)),+ ].sort();+ const status = rule.gaps.length+ ? 'UNSUPPORTED'+ : !targetKeys.length+ ? 'UNMOUNTED'+ : missingActivationKeys.length+ ? 'PARTIAL_ACTIVATION'+ : !activeKeys.length+ ? 'INACTIVE_ONLY'+ : 'OBSERVED';+ return {+ ...rule,+ activeKeys,+ inactiveKeys,+ missingActivationKeys,+ sampleCount: samples.length,+ side,+ status,+ targetKeys,+ variant,+ // Bounded references are enough to locate full per-probe records.+ positiveEvidence: samples+ .filter((sample) => sample.active)+ .slice(0, 3)+ .map(({ key, probeId, evidenceRefs }) => ({ key, probeId, evidenceRefs })),+ };+ }),+ );+ const gaps = [...new Set(plans.flatMap(({ plan }) => plan.gaps))];+ const groups = new Map<string, typeof rules>();+ for (const rule of rules) {+ // Activation identity across style variants, not declaration equivalence.+ const key = JSON.stringify([rule.side, rule.selector, rule.conditions, rule.sourceSlots]);+ const group = groups.get(key) ?? [];+ group.push(rule);+ groups.set(key, group);+ }+ const globallyUnmounted = [...groups.values()]+ .filter((group) =>+ group.every((rule) => rule.status !== 'UNSUPPORTED' && !rule.targetKeys.length),+ )+ .map((group) => ({+ side: group[0].side,+ selector: group[0].selector,+ conditions: group[0].conditions,+ sourceSlots: group[0].sourceSlots,+ variants: group.map((rule) => rule.variant),+ }));+ return {+ gateEligible: false as const,+ gaps,+ mode: 'diagnostic-source-slot-cssom-activation' as const,+ rules,+ globallyUnmounted,+ schemaVersion: 1,+ summary: {+ compiledBranches: rules.length,+ uniqueActivationBranches: groups.size,+ globallyUnmounted: globallyUnmounted.length,+ inactiveOnly: rules.filter((rule) => rule.status === 'INACTIVE_ONLY').length,+ missingActivationTargets: rules.reduce(+ (sum, rule) => sum + rule.missingActivationKeys.length,+ 0,+ ),+ observed: rules.filter((rule) => rule.status === 'OBSERVED').length,+ partialActivation: rules.filter((rule) => rule.status === 'PARTIAL_ACTIVATION').length,+ unmounted: rules.filter((rule) => rule.status === 'UNMOUNTED').length,+ unsupported: rules.filter((rule) => rule.status === 'UNSUPPORTED').length,+ },+ limitations: [+ 'SOURCE_RULE_MAPPING_NOT_CERTIFIED',+ 'FULL_CONDITION_PARTITION_KEYS_UNPROVEN',+ 'COMPOSITION_TRACE_SCOPE_LIMITED',+ ],+ };+};diff --git a/scripts/stylexMigration/verification/analysis/ruleWitnesses.test.ts b/scripts/stylexMigration/verification/analysis/ruleWitnesses.test.tsnew file mode 100644index 00000000000..13c81e70e0b--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/ruleWitnesses.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from 'vitest';++import { planRuleWitnesses } from './ruleWitnesses';+import type { StyleBindingPlan } from './styleBindings';++const plan: StyleBindingPlan = {+ bindings: [+ {+ kind: 'static-factory',+ symbol: 'styles',+ slots: [{ name: 'root', unitId: 'Component:style-slot:0', start: 0, end: 10 }],+ },+ ],+ gaps: [],+ source: 'Component.tsx',+ sourceHash: 'hash',+ stylesheets: [],+};+describe('compiled rule / source slot joins', () => {+ const rule = {+ conditions: [],+ selectorAncestors: [],+ kind: 'CSSStyleRule',+ path: '0.0',+ selector: '.compiled:hover',+ text: '.compiled:hover{color:red}',+ };+ it('retains rules even if no target was mounted and does not remove inactive conditions', () => {+ const result = planRuleWitnesses(+ {+ gaps: [],+ rules: [{ ...rule, conditions: [{ kind: 'CSSContainerRule', text: '(max-width:600px)' }] }],+ },+ plan,+ { styles: { root: 'compiled' } },+ );+ expect(result.rules[0]).toMatchObject({+ sourceSlots: ['styles.root'],+ sourceUnitIds: ['Component:style-slot:0'],+ conditions: [{ kind: 'CSSContainerRule', text: '(max-width:600px)' }],+ });+ expect(result.rules[0].targetSelector).toBe('.compiled');+ });+ it('does not attribute unrelated UI library classes to this component', () => {+ expect(+ planRuleWitnesses({ gaps: [], rules: [{ ...rule, selector: '.ui-library' }] }, plan, {+ styles: { root: 'compiled' },+ }).rules,+ ).toHaveLength(0);+ });+ it('traces replaced Emotion classes through nested compositions without claiming declaration ownership', () => {+ const result = planRuleWitnesses(+ { gaps: [], rules: [{ ...rule, selector: '.combined:hover' }] },+ plan,+ { styles: { root: 'original' } },+ {+ gaps: [],+ records: [+ { callId: 2, inputs: ['intermediate'], output: 'combined' },+ { callId: 1, inputs: ['original'], output: 'intermediate' },+ ],+ },+ );+ expect(result.rules[0].sourceSlots).toEqual(['styles.root']);+ expect(result.compositions.map((entry) => entry.className)).toContain('combined');+ expect(result.gaps).toContain('COMPOSITION_DECLARATION_OWNERSHIP_UNPROVEN');+ });+ it('does not assign all contributing slots to unchanged output tokens and retains unknown inputs', () => {+ const result = planRuleWitnesses(+ { gaps: [], rules: [{ ...rule, selector: '.external' }] },+ plan,+ { styles: { root: 'original' } },+ {+ gaps: [],+ records: [{ callId: 1, inputs: ['original', 'external'], output: 'original external' }],+ },+ );+ expect(result.rules).toHaveLength(0);+ expect(result.gaps).toContain('COMPOSITION_INPUT_SOURCE_UNPROVEN');+ });+ it('keeps missing exports, unsupported selectors and query syntax as explicit gaps', () => {+ expect(planRuleWitnesses({ gaps: [], rules: [rule] }, plan, {}).gaps).toContain(+ 'SOURCE_SLOT_NOT_EXPORTED:styles.root',+ );+ const result = planRuleWitnesses(+ {+ gaps: [],+ rules: [+ {+ ...rule,+ selector: '.compiled:has(.child:hover)',+ conditions: [{ kind: 'CSSContainerRule', text: 'style(--x: red)' }],+ },+ ],+ },+ plan,+ { styles: { root: 'compiled' } },+ );+ expect(result.rules[0].gaps).toContain('NESTED_STATE_SELECTOR_UNSUPPORTED');+ expect(result.rules[0].gaps).toContain('WIDTH_CONDITION_UNSUPPORTED:style(--x: red)');+ });+});diff --git a/scripts/stylexMigration/verification/analysis/ruleWitnesses.ts b/scripts/stylexMigration/verification/analysis/ruleWitnesses.tsnew file mode 100644index 00000000000..1c5a84e117f--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/ruleWitnesses.ts@@ -0,0 +1,309 @@+import type { Page } from '@playwright/test';+import { z } from 'zod';++import type { collectRulesInPage } from '../browser/ruleInventory';+import type { RuntimeCompositions } from '../browser/runtimeCompositions';+import { parseWidthCondition } from './conditionPartitions';+import { analyzeSelector } from './selectorAnalysis';+import type { StyleBindingPlan } from './styleBindings';++const runtimeBindingsSchema = z.record(z.string(), z.record(z.string(), z.string()));+export type RuntimeBindings = z.infer<typeof runtimeBindingsSchema>;+type Inventory = ReturnType<typeof collectRulesInPage>;++export const readRuntimeBindings = async (page: Page) =>+ runtimeBindingsSchema.parse(+ await page.evaluate(() => {+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, '__styleVerificationBindings');+ if (!descriptor || !('value' in descriptor))+ throw new Error('STYLE_BINDING_OBSERVER_MISSING');+ return Object.fromEntries(+ Object.entries(Object.getOwnPropertyDescriptors(descriptor.value)).map(+ ([symbol, binding]) => {+ if (!('value' in binding)) throw new Error('STYLE_BINDING_ACCESSOR_UNSUPPORTED');+ return [+ symbol,+ Object.fromEntries(+ Object.entries(Object.getOwnPropertyDescriptors(binding.value)).map(+ ([name, slot]) => {+ if (!('value' in slot)) throw new Error('STYLE_BINDING_ACCESSOR_UNSUPPORTED');+ return [name, slot.value];+ },+ ),+ ),+ ];+ },+ ),+ );+ }),+ );++export const planRuleWitnesses = (+ inventory: Inventory,+ plan: StyleBindingPlan,+ bindings: RuntimeBindings,+ compositions: RuntimeCompositions = { records: [], gaps: [] },+) => {+ const classes = new Map<string, Array<{ slot: string; unitId: string }>>();+ const gaps = [...plan.gaps, ...compositions.gaps];+ for (const binding of plan.bindings)+ for (const slot of binding.slots) {+ const value = bindings[binding.symbol]?.[slot.name];+ if (!value) {+ gaps.push(`SOURCE_SLOT_NOT_EXPORTED:${binding.symbol}.${slot.name}`);+ continue;+ }+ for (const name of value.split(/\s+/).filter(Boolean)) {+ const current = classes.get(name) ?? [];+ current.push({ slot: `${binding.symbol}.${slot.name}`, unitId: slot.unitId });+ classes.set(name, current);+ }+ }+ // cx may replace several registered classes with one new class. Retain the+ // union of originating slots; this is NOT per-declaration ownership proof.+ const composedClasses = new Set<string>();+ for (let pass = 0; pass <= compositions.records.length; pass++) {+ let changed = false;+ for (const record of compositions.records) {+ const inputs = record.inputs.flatMap((value) => value.split(/\s+/).filter(Boolean));+ const origins = inputs.flatMap((name) => classes.get(name) ?? []);+ for (const name of record.output.split(/\s+/).filter(Boolean)) {+ if (inputs.includes(name)) continue;+ const current = classes.get(name) ?? [];+ const merged = [+ ...new Map([...current, ...origins].map((slot) => [slot.slot, slot])).values(),+ ];+ if (merged.length !== current.length) {+ classes.set(name, merged);+ composedClasses.add(name);+ changed = true;+ }+ }+ }+ if (!changed) break;+ }+ for (const record of compositions.records) {+ if (+ record.inputs+ .flatMap((value) => value.split(/\s+/).filter(Boolean))+ .some((name) => !classes.has(name))+ )+ gaps.push('COMPOSITION_INPUT_SOURCE_UNPROVEN');+ if (plan.composition && !plan.composition.calls.some((call) => call.start === record.callId))+ gaps.push('COMPOSITION_CALL_SITE_UNBOUND');+ }+ if (composedClasses.size) gaps.push('COMPOSITION_DECLARATION_OWNERSHIP_UNPROVEN');+ const rules = [];+ for (const rule of inventory.rules) {+ const selectorText =+ rule.selector ??+ (rule.kind === 'CSSNestedDeclarations' ? rule.selectorAncestors.at(-1) : undefined);+ if (!selectorText) continue;+ let branches;+ try {+ branches = analyzeSelector(selectorText);+ } catch (error) {+ console.error('COMPILED_SELECTOR_PARSE_ERROR', error);+ gaps.push(`COMPILED_SELECTOR_PARSE_ERROR:${rule.path}`);+ continue;+ }+ for (const [index, branch] of branches.entries()) {+ const ancestorClasses = rule.selectorAncestors.flatMap((selector) =>+ analyzeSelector(selector).flatMap((branch) => branch.classes),+ );+ const slots = [...branch.classes, ...ancestorClasses].flatMap(+ (name) => classes.get(name) ?? [],+ );+ if (!slots.length) continue;+ const limitations = [...branch.gaps];+ if (rule.selectorAncestors.length) limitations.push('NATIVE_NESTING_BINDING_UNSUPPORTED');+ for (const condition of rule.conditions)+ if (!['CSSContainerRule', 'CSSMediaRule', 'CSSSupportsRule'].includes(condition.kind))+ limitations.push(`CONDITION_KIND_UNSUPPORTED:${condition.kind}`);+ else if (condition.kind !== 'CSSSupportsRule' && !parseWidthCondition(condition.text))+ limitations.push(`WIDTH_CONDITION_UNSUPPORTED:${condition.text}`);+ rules.push({+ conditionModels: rule.conditions.map((condition) => ({+ ...condition,+ width:+ condition.kind === 'CSSSupportsRule' ? undefined : parseWidthCondition(condition.text),+ })),+ ...branch,+ conditions: rule.conditions,+ cssomPath: rule.path,+ gaps: [...new Set(limitations)],+ id: `${rule.path}:${index}`,+ sourceSlots: [...new Set(slots.map((slot) => slot.slot))],+ sourceUnitIds: [...new Set(slots.map((slot) => slot.unitId))],+ });+ }+ }+ return {+ compositions: [...composedClasses].map((name) => ({+ className: name,+ sourceSlots: classes.get(name)!.map((slot) => slot.slot),+ })),+ gaps: [...new Set(gaps)],+ rules,+ };+};+export type RuleWitnessPlan = ReturnType<typeof planRuleWitnesses>;++/** Run ONLY after product snapshots. Private non-inheriting markers, then cleanup. */+export const collectRuleWitnessesInPage = (input: {+ nonce: string;+ rules: RuleWitnessPlan['rules'];+}) => {+ if (!/^[a-f\d]{16}$/.test(input.nonce)) throw new Error('INVALID_WITNESS_NAMESPACE');+ if (input.rules.length > 1000) throw new Error('RULE_WITNESS_BUDGET_EXCEEDED');+ const root = document.querySelector('[data-case-root]');+ if (!root) throw new Error('RULE_WITNESS_ROOT_MISSING');+ const keys = new Map<Element, string>();+ const walk = (element: Element, key: string) => {+ keys.set(element, key);+ [...element.children]+ .filter((child) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(child.tagName))+ .forEach((child, index) => walk(child, `${key}.${index}`));+ };+ walk(root, 'root');+ const absoluteSelector = (element: Element) => {+ const segments: string[] = [];+ for (+ let current: Element | null = element;+ current?.parentElement;+ current = current.parentElement+ )+ segments.unshift(`:nth-child(${[...current.parentElement.children].indexOf(current) + 1})`);+ return [':root', ...segments].join(' > ');+ };+ const styles = new CSSStyleSheet();+ // The browser returns a live ObservableArray. Preserve its contents, not the+ // live object that assignment itself mutates, or cleanup retains the marker.+ const originalSheets = [...document.adoptedStyleSheets];+ const supported = input.rules.filter((rule) => !rule.gaps.length);+ const entries = supported.map((rule, index) => ({+ rule,+ property: `--style-verifier-${input.nonce}-${index}`,+ }));+ const text = entries+ .map(({ rule, property }) => {+ CSS.registerProperty({+ name: property,+ syntax: '<integer>',+ inherits: false,+ initialValue: '0',+ });+ let text = `${rule.selector}{${property}:1 !important;}`;+ for (const condition of [...rule.conditions].reverse()) {+ const kind =+ condition.kind === 'CSSContainerRule'+ ? 'container'+ : condition.kind === 'CSSMediaRule'+ ? 'media'+ : 'supports';+ text = `@${kind} ${condition.text}{${text}}`;+ }+ return text;+ })+ .join('\n');+ styles.replaceSync(text);+ const observations = [];+ try {+ document.adoptedStyleSheets = [...originalSheets, styles];+ for (const { rule, property } of entries) {+ const triggers =+ rule.states.length === 1+ ? [...document.querySelectorAll(rule.states[0].selector)].filter((element) =>+ root.contains(element),+ )+ : [];+ if (triggers.length > 512) throw new Error('RULE_TRIGGER_BUDGET_EXCEEDED');+ const targets = [...document.querySelectorAll(rule.targetSelector)]+ .filter((element) => root.contains(element))+ .map((element) => {+ const computed = getComputedStyle(element, rule.pseudo);+ const containers: Array<{+ key: string;+ name: string;+ type: string;+ width: number;+ metricsTrusted?: boolean;+ }> = [];+ for (let parent = element.parentElement; parent; parent = parent.parentElement) {+ const style = getComputedStyle(parent);+ if (!['size', 'inline-size'].includes(style.containerType)) continue;+ const width = Number.parseFloat(style.width);+ const padding =+ Number.parseFloat(style.paddingLeft) + Number.parseFloat(style.paddingRight);+ const border =+ Number.parseFloat(style.borderLeftWidth) + Number.parseFloat(style.borderRightWidth);+ containers.push({+ key: keys.get(parent) ?? 'outside-surface',+ name: style.containerName,+ type: style.containerType,+ width: style.boxSizing === 'border-box' ? width - padding - border : width,+ metricsTrusted:+ style.writingMode === 'horizontal-tb' &&+ !['auto', 'scroll'].includes(style.overflowX) &&+ !['auto', 'scroll'].includes(style.overflowY) &&+ style.scrollbarGutter === 'auto',+ });+ }+ const conditionStates = rule.conditionModels.map((condition) => {+ if (condition.kind === 'CSSMediaRule') return matchMedia(condition.text).matches;+ if (condition.kind === 'CSSSupportsRule') return CSS.supports(condition.text);+ const model = condition.width;+ if (!model) return null;+ const container = containers.find(+ (candidate) => !model.name || candidate.name.split(/\s+/).includes(model.name),+ );+ if (!container || !Number.isFinite(container.width)) return false;+ if (container.metricsTrusted === false) return null;+ return model.bounds.every(({ operator, value }) =>+ operator === '<'+ ? container.width < value+ : operator === '<='+ ? container.width <= value+ : operator === '>'+ ? container.width > value+ : operator === '>='+ ? container.width >= value+ : container.width === value,+ );+ });+ return {+ conditionStates,+ active: computed.getPropertyValue(property).trim() === '1',+ content: rule.pseudo ? computed.content : undefined,+ display: rule.pseudo ? computed.display : undefined,+ key: keys.get(element)!,+ triggers: triggers+ .filter((trigger) =>+ element.matches(+ rule.bindingSelector.replaceAll(+ ':--style-verifier-trigger',+ `:is(${absoluteSelector(trigger)})`,+ ),+ ),+ )+ .map((trigger) => ({+ key: keys.get(trigger)!,+ state: rule.states[0].state,+ tag: trigger.tagName,+ })),+ containers,+ };+ });+ observations.push({ id: rule.id, targets });+ }+ return {+ observations,+ registeredProperties: entries.map((entry) => entry.property),+ viewportWidth: innerWidth,+ direction: getComputedStyle(document.documentElement).direction,+ };+ } finally {+ document.adoptedStyleSheets = originalSheets;+ }+};+export type RuleObservation = ReturnType<typeof collectRuleWitnessesInPage>;diff --git a/scripts/stylexMigration/verification/analysis/scopeInventory.test.ts b/scripts/stylexMigration/verification/analysis/scopeInventory.test.tsnew file mode 100644index 00000000000..2abd6210ca9--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/scopeInventory.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest';++import { findCssModuleResidue, inventorySource } from './scopeInventory';++const slots = (source: string) =>+ inventorySource(source, 'component.tsx', 'base', 'blob').filter(+ (unit) => unit.kind === 'style-slot',+ );++describe('source style inventory', () => {+ it('uses import and syntax nodes, not commented source or CSS-shaped strings', () => {+ expect(slots('// createStyles({ hidden: {} })\nconst text = "stylex.create({})";')).toEqual([]);+ expect(inventorySource('export const x = 1', 'helper.ts', 'candidate', 'blob')[0].kind).toBe(+ 'source',+ );+ });++ it('retains unmounted slots and aliased StyleX imports', () => {+ const units = slots(+ 'import * as sx from "@stylexjs/stylex"; const s = sx.create({ root: {color:"red"}, neverMounted: {color:"blue"} });',+ );+ expect(units.map((unit) => unit.label)).toEqual(['sx.create', 'root', 'neverMounted']);+ });++ it('finds legacy callback styles with a renamed import', () => {+ expect(+ slots(+ 'import { createStaticStyles as make } from "@lobehub/ui"; const s = make(({css}) => ({root: css`color:red;`, hidden: css`&:hover {color:blue;}`}));',+ ).map((unit) => unit.label),+ ).toEqual(['make', 'root', 'hidden']);+ });++ it('retains dynamic spreads and unknown source as unresolved units', () => {+ expect(+ slots('import sx from "@stylexjs/stylex"; sx.create({...extra});').map((unit) => unit.label),+ ).toContain('dynamic-slot');+ expect(inventorySource('opaque', 'asset.svg', 'base', 'blob')[0].kind).toBe('opaque');+ });++ it('keeps the two source sides distinguishable even when paths match', () => {+ const source = 'import {create} from "@stylexjs/stylex"; create({a:{color:"red"}});';+ expect(inventorySource(source, 'x.ts', 'base', 'blob')[0].id).not.toBe(+ inventorySource(source, 'x.ts', 'candidate', 'blob')[0].id,+ );+ });++ it('identifies CSS Modules as migration residue without matching comments or prose', () => {+ expect(+ slots(`+ import styles from './styles.module.css';+ import './legacy.module.scss?inline';+ // import ignored from './ignored.module.css';+ const prose = "import ignored from './prose.module.css'";+ `).map((unit) => unit.label),+ ).toEqual(['css-module:./styles.module.css', 'css-module:./legacy.module.scss?inline']);+ });++ it('reports candidate imports and stylesheets, not a deleted base stylesheet', () => {+ const base = inventorySource('.root {}', 'old.module.css', 'base', 'before');+ const candidate = inventorySource('.root {}', 'new.module.scss', 'candidate', 'after');+ const imports = inventorySource(+ "import s from './nested.module.css'; export type { S } from './type.module.css';",+ 'component.tsx',+ 'candidate',+ 'source',+ );+ expect(findCssModuleResidue([...base, ...candidate, ...imports])).toEqual([+ { file: 'new.module.scss', label: 'new.module.scss', start: 0 },+ { file: 'component.tsx', label: 'css-module:./nested.module.css', start: 0 },+ ]);+ });+});diff --git a/scripts/stylexMigration/verification/analysis/scopeInventory.ts b/scripts/stylexMigration/verification/analysis/scopeInventory.tsnew file mode 100644index 00000000000..7aea1a23025--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/scopeInventory.ts@@ -0,0 +1,209 @@+import { createHash } from 'node:crypto';+import path from 'node:path';++import ts from 'typescript';++import { listSourceEntries, readBlobs } from '../source/buildSnapshots';+import { git } from '../source/git';+import type { RevisionSession, ScopeInventory, ScopeUnit } from '../types';++const styleFactories = new Set([+ 'createStyles',+ 'createStaticStyles',+ 'create',+ 'keyframes',+ 'defineVars',+ 'createTheme',+]);+const stylePackages = new Set([+ '@lobehub/ui',+ '@stylexjs/stylex',+ 'antd-style',+ '@emotion/react',+ '@emotion/css',+]);++const cssModulePath = /\.module\.(?:css|less|sass|scss|styl)(?:[?#].*)?$/i;++/** Changed files only; absence here is not proof of a complete migration. */+export const findCssModuleResidue = (units: ScopeUnit[]) =>+ units+ .filter(+ (unit) =>+ unit.side === 'candidate' &&+ (unit.kind === 'source' || unit.kind === 'stylesheet' || unit.kind === 'opaque'+ ? cssModulePath.test(unit.file)+ : unit.label.startsWith('css-module:')),+ )+ .map(({ file, label, start }) => ({ file, label, start }));++/** An inventory, not an equivalence proof: source/binding units stay unresolved. */+export const inventorySource = (+ source: string,+ file: string,+ side: ScopeUnit['side'],+ blobSha: string,+): ScopeUnit[] => {+ const units: ScopeUnit[] = [];+ const extension = path.extname(file);+ const unit = (kind: ScopeUnit['kind'], label: string, start: number, end: number) => {+ units.push({+ blobSha,+ end,+ file,+ id: `${side}:${file}:${kind}:${start}`,+ kind,+ label,+ side,+ start,+ });+ };+ unit(+ extension === '.css' ? 'stylesheet' : /\.[cm]?[jt]sx?$/.test(file) ? 'source' : 'opaque',+ file,+ 0,+ source.length,+ );+ if (!/\.[cm]?[jt]sx?$/.test(file)) return units;+ const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);+ const importedFunctions = new Set<string>();+ const namespaces = new Set<string>();+ for (const statement of ast.statements) {+ if (+ (ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) &&+ statement.moduleSpecifier &&+ ts.isStringLiteral(statement.moduleSpecifier) &&+ cssModulePath.test(statement.moduleSpecifier.text) &&+ !(ts.isImportDeclaration(statement) && statement.importClause?.isTypeOnly) &&+ !(ts.isExportDeclaration(statement) && statement.isTypeOnly)+ )+ unit(+ 'style-slot',+ `css-module:${statement.moduleSpecifier.text}`,+ statement.getStart(ast),+ statement.end,+ );+ if (+ !ts.isImportDeclaration(statement) ||+ !ts.isStringLiteral(statement.moduleSpecifier) ||+ !stylePackages.has(statement.moduleSpecifier.text)+ )+ continue;+ const clause = statement.importClause;+ if (clause?.isTypeOnly) continue;+ if (clause?.name && statement.moduleSpecifier.text === '@stylexjs/stylex')+ namespaces.add(clause.name.text);+ const bindings = clause?.namedBindings;+ if (bindings && ts.isNamespaceImport(bindings)) namespaces.add(bindings.name.text);+ if (bindings && ts.isNamedImports(bindings))+ for (const element of bindings.elements)+ if (+ !element.isTypeOnly &&+ styleFactories.has(element.propertyName?.text ?? element.name.text)+ )+ importedFunctions.add(element.name.text);+ }+ const visit = (node: ts.Node) => {+ if (ts.isCallExpression(node)) {+ const callee = node.expression;+ const isFactory = ts.isIdentifier(callee)+ ? importedFunctions.has(callee.text)+ : ts.isPropertyAccessExpression(callee) &&+ ts.isIdentifier(callee.expression) &&+ namespaces.has(callee.expression.text) &&+ styleFactories.has(callee.name.text);+ if (isFactory) {+ unit('style-slot', callee.getText(ast), node.getStart(ast), node.end);+ const visitSlots = (child: ts.Node) => {+ if (ts.isObjectLiteralExpression(child)) {+ for (const property of child.properties) {+ if (ts.isPropertyAssignment(property))+ unit(+ 'style-slot',+ property.name.getText(ast),+ property.getStart(ast),+ property.end,+ );+ else unit('style-slot', 'dynamic-slot', property.getStart(ast), property.end);+ }+ } else ts.forEachChild(child, visitSlots);+ };+ node.arguments.forEach(visitSlots);+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(ast);+ return units;+};++export const inventoryScope = async (session: RevisionSession): Promise<ScopeInventory> => {+ // Disable rename similarity heuristics: deletion/addition cannot disappear from scope.+ const tokens = (+ await git(session.directory, [+ 'diff',+ '--name-status',+ '--no-renames',+ '-z',+ session.identity.baseSha,+ session.identity.candidateTreeSha,+ ])+ )+ .toString()+ .split('\0')+ .filter(Boolean);+ const changedFiles: ScopeInventory['changedFiles'] = [];+ for (let index = 0; index < tokens.length; index += 2) {+ const status = tokens[index];+ const file = tokens[index + 1];+ if (!file || !['A', 'D', 'M', 'T'].includes(status))+ throw new Error('UNSUPPORTED_GIT_DIFF_STATUS');+ changedFiles.push({+ after: status === 'D' ? undefined : file,+ before: status === 'A' ? undefined : file,+ status,+ });+ }+ const units: ScopeUnit[] = [];+ for (const side of ['base', 'candidate'] as const) {+ const files = new Set(+ changedFiles.map((entry) => (side === 'base' ? entry.before : entry.after)).filter(Boolean),+ );+ const entries = (+ await listSourceEntries(+ session.directory,+ side === 'base' ? session.identity.baseSha : session.identity.candidateTreeSha,+ )+ ).filter((entry) => files.has(entry.path));+ for (const entry of entries) {+ if (entry.bytes > 4 * 1024 ** 2 || entry.type !== 'blob') {+ units.push({+ blobSha: entry.oid,+ end: entry.bytes,+ file: entry.path,+ id: `${side}:${entry.path}:opaque:0`,+ kind: 'opaque',+ label: entry.path,+ side,+ start: 0,+ });+ } else {+ const [blob] = await readBlobs(session.directory, [entry]);+ units.push(...inventorySource(blob.toString(), entry.path, side, entry.oid));+ }+ }+ }+ const limitations = changedFiles.length+ ? [+ 'TRANSITIVE_IMPACT_UNPROVEN',+ 'SOURCE_BINDING_UNPROVEN',+ 'CONDITION_PARTITIONS_UNPLANNED',+ 'PURE_STYLE_MIGRATION_UNPROVEN',+ ]+ : [];+ if (findCssModuleResidue(units).length) limitations.push('CSS_MODULE_MIGRATION_REMAINS');+ const hash = createHash('sha256')+ .update(JSON.stringify({ changedFiles, limitations, units }))+ .digest('hex');+ return { changedFiles, hash, limitations, units };+};diff --git a/scripts/stylexMigration/verification/analysis/selectorAnalysis.test.ts b/scripts/stylexMigration/verification/analysis/selectorAnalysis.test.tsnew file mode 100644index 00000000000..7589267d33c--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/selectorAnalysis.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';++import { analyzeSelector } from './selectorAnalysis';++describe('selector AST targeting', () => {+ it('keeps trigger and style target distinct for sibling/ancestor selectors', () => {+ const [plan] = analyzeSelector('.trigger:hover + .target::before');+ expect(plan).toMatchObject({+ gaps: [],+ pseudo: '::before',+ states: [{ selector: '.trigger', state: 'hover' }],+ targetSelector: '.trigger+.target',+ });+ expect(analyzeSelector('.parent:hover .child')[0].states[0].selector).toBe('.parent');+ });+ it('includes classes after the state in the trigger compound and preserves structural constraints', () => {+ const [plan] = analyzeSelector(+ '.row:hover.enabled:not([disabled]) > td[data-name="a,b"]::before',+ );+ expect(plan.gaps).toEqual([]);+ expect(plan.states[0].selector).toBe('.row.enabled:not([disabled])');+ expect(plan.targetSelector).toContain('[data-name="a,b"]');+ });+ it('retains multiple operation owners and individual selector-list branches', () => {+ const plans = analyzeSelector('.parent:hover .child:focus-visible, .other:active');+ expect(plans).toHaveLength(2);+ expect(plans[0].states.map((state) => state.selector)).toEqual(['.parent', '.parent .child']);+ });+ it.each([+ '.parent:has(.child:hover)',+ '.x:not(:hover)',+ '.x:is(.a:hover,.b)',+ '.x::selection',+ '&:hover',+ ])('does not silently simplify unsupported syntax: %s', (selector) => {+ expect(analyzeSelector(selector)[0].gaps.length).toBeGreaterThan(0);+ });+});diff --git a/scripts/stylexMigration/verification/analysis/selectorAnalysis.ts b/scripts/stylexMigration/verification/analysis/selectorAnalysis.tsnew file mode 100644index 00000000000..6535bcc50c4--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/selectorAnalysis.ts@@ -0,0 +1,87 @@+import selectorParser from 'postcss-selector-parser';++const dynamic = new Set([':hover', ':active', ':focus', ':focus-visible', ':focus-within']);+const structural = new Set([+ ':first-child',+ ':last-child',+ ':only-child',+ ':empty',+ ':root',+ ':first-of-type',+ ':last-of-type',+ ':only-of-type',+ ':nth-child',+ ':nth-last-child',+ ':nth-of-type',+ ':nth-last-of-type',+ ':not',+]);+const pseudos = new Set(['::before', '::after', '::marker', '::placeholder']);++/** One list branch per binding; never erase complex relations to claim support. */+export const analyzeSelector = (text: string) => {+ const root = selectorParser().astSync(text, { lossless: false });+ return root.nodes.map((original) => {+ const selector = original.clone();+ const binding = original.clone();+ const gaps = new Set<string>();+ if (text.includes(':--style-verifier-trigger')) gaps.add('TRIGGER_PLACEHOLDER_COLLISION');+ const classes = new Set<string>();+ const states: Array<{ selector: string; state: string }> = [];+ let pseudo: string | undefined;+ original.walkClasses((node) => {+ classes.add(node.value);+ });+ original.walkPseudos((node) => {+ if (pseudos.has(node.value)) {+ if (node.parent !== original || node !== original.last || pseudo)+ gaps.add('PSEUDO_TARGET_UNSUPPORTED');+ pseudo = node.value;+ } else if (dynamic.has(node.value)) {+ if (node.parent !== original) gaps.add('NESTED_STATE_SELECTOR_UNSUPPORTED');+ else {+ const prefix = original.clone();+ const position = original.nodes.indexOf(node);+ // Include the whole trigger compound, not only the part before :hover.+ const end = original.nodes.findIndex(+ (entry, index) => index > position && entry.type === 'combinator',+ );+ prefix.nodes+ .slice(end < 0 ? original.nodes.length : end)+ .forEach((entry) => entry.remove());+ prefix.walkPseudos((entry) => {+ if (dynamic.has(entry.value) || pseudos.has(entry.value)) entry.remove();+ });+ if (!prefix.nodes.length || prefix.last?.type === 'combinator')+ gaps.add('EMPTY_STATE_TRIGGER');+ states.push({ selector: prefix.toString(), state: node.value.slice(1) });+ }+ } else if (!structural.has(node.value)) gaps.add(`SELECTOR_PSEUDO_UNSUPPORTED:${node.value}`);+ if (node.value === ':not')+ node.walkPseudos((nested) => {+ if (nested !== node && dynamic.has(nested.value)) gaps.add('NEGATED_STATE_UNSUPPORTED');+ });+ });+ selector.walkPseudos((node) => {+ if (dynamic.has(node.value) || pseudos.has(node.value)) node.remove();+ });+ binding.walkPseudos((node) => {+ if (pseudos.has(node.value)) node.remove();+ else if (dynamic.has(node.value)) node.value = ':--style-verifier-trigger';+ });+ selector.walkNesting(() => {+ gaps.add('NATIVE_NESTING_BINDING_UNSUPPORTED');+ });+ if (!selector.nodes.length || selector.last?.type === 'combinator')+ gaps.add('EMPTY_STYLE_TARGET');+ return {+ classes: [...classes],+ bindingSelector: binding.toString(),+ gaps: [...gaps],+ pseudo,+ selector: original.toString(),+ states,+ targetSelector: selector.toString(),+ };+ });+};diff --git a/scripts/stylexMigration/verification/analysis/styleBindings.test.ts b/scripts/stylexMigration/verification/analysis/styleBindings.test.tsnew file mode 100644index 00000000000..1e3363d153e--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/styleBindings.test.ts@@ -0,0 +1,70 @@+// @vitest-environment node+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { analyzeStyleBindings, bindingObserverExport, prepareStyleBindings } from './styleBindings';++const owned: string[] = [];+afterEach(async () => {+ for (const root of owned.splice(0)) await rm(root, { force: true, recursive: true });+});++describe('source binding observer', () => {+ it('resolves imported factory aliases and preserves slot source ranges, including unmounted slots', () => {+ const code =+ 'import {createStaticStyles as make} from "@lobehub/ui"; const styles=make(({css})=>{return {root:css`color:red`, unused:css`display:none`}});';+ const result = analyzeStyleBindings(code, 'Component.tsx');+ expect(result.bindings[0].slots.map((slot) => slot.name)).toEqual(['root', 'unused']);+ expect(code.slice(result.bindings[0].slots[1].start, result.bindings[0].slots[1].end)).toBe(+ 'unused:css`display:none`',+ );+ expect(result.gaps).toContain('LEGACY_TEMPLATE_RULE_SOURCE_UNPROVEN');+ expect(analyzeStyleBindings('const styles=make({root:1})', 'Other.tsx').bindings).toHaveLength(+ 0,+ );+ });+ it('retains dynamic slots and unsupported factory returns as gaps', () => {+ expect(+ analyzeStyleBindings(+ 'import {createStaticStyles as make} from "@lobehub/ui"; const styles=make(()=>({[dynamic]:1,...more}));',+ 'Dynamic.tsx',+ ).gaps.length,+ ).toBeGreaterThan(0);+ });+ it('supports parenthesized object returns but refuses conditional return inference', () => {+ const simple = analyzeStyleBindings(+ 'import {createStaticStyles as make} from "@lobehub/ui"; const styles=make(({css})=>({root:css`color:red`}));',+ 'Simple.tsx',+ );+ expect(simple.bindings[0].slots[0].name).toBe('root');+ const conditional = analyzeStyleBindings(+ 'import {createStaticStyles as make} from "@lobehub/ui"; const styles=make(({css})=>{if(flag)return {hidden:css`color:red`};return {root:css`color:blue`};});',+ 'Conditional.tsx',+ );+ expect(conditional.gaps).toContain('STATIC_FACTORY_CONTROL_FLOW_UNSUPPORTED');+ expect(conditional.bindings).toHaveLength(0);+ });++ it('inventories inactive CSS module rules without executing or changing the source component', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-bindings-test-'));+ owned.push(root);+ await mkdir(path.join(root, 'src'));+ const code = 'import styles from "./Table.module.css"; export const Component=()=>styles.root;';+ await writeFile(path.join(root, 'src/Component.tsx'), code);+ await writeFile(+ path.join(root, 'src/Table.module.css'),+ '.root {color:red} @container (max-width:600px){.root:hover td::before {content:"x"}} .unused{display:none}',+ );+ const plan = await prepareStyleBindings(root, 'src/Component.tsx');+ expect(plan.bindings[0].slots.map((slot) => slot.name)).toEqual(['root', 'unused']);+ expect(plan.stylesheets[0].rules[1].conditions).toEqual([+ { kind: 'container', text: '(max-width:600px)' },+ ]);+ expect(plan.stylesheets[0].rules).toHaveLength(3);+ expect(bindingObserverExport(plan)).toContain('"styles":styles');+ expect(await readFile(path.join(root, 'src/Component.tsx'), 'utf8')).toBe(code);+ });+});diff --git a/scripts/stylexMigration/verification/analysis/styleBindings.ts b/scripts/stylexMigration/verification/analysis/styleBindings.tsnew file mode 100644index 00000000000..82147fd0e4f--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/styleBindings.ts@@ -0,0 +1,201 @@+import { readFile, realpath } from 'node:fs/promises';+import path from 'node:path';++import postcss from 'postcss';+import ts from 'typescript';++import { sha256 } from '../reporting/report';+import type { CompositionTrace } from './compositionObserver';+import { planCompositionObserver } from './compositionObserver';+import { analyzeSelector } from './selectorAnalysis';++export interface StyleBindingPlan {+ bindings: Array<{+ kind: 'css-module' | 'static-factory';+ symbol: string;+ slots: Array<{ end: number; name: string; start: number; unitId: string }>;+ }>;+ composition?: CompositionTrace;+ gaps: string[];+ source: string;+ sourceHash: string;+ stylesheets: Array<{+ file: string;+ hash: string;+ rules: Array<{+ conditions: Array<{ kind: string; text: string }>;+ end: number;+ selector: string;+ start: number;+ }>;+ }>;+}++/** Observes existing module bindings; never assigns classes to product nodes. */+export const analyzeStyleBindings = (code: string, file: string) => {+ const ast = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true);+ const factories = new Set<string>();+ const imports: Array<{ source: string; symbol: string }> = [];+ const bindings: StyleBindingPlan['bindings'] = [];+ const gaps: string[] = [];+ for (const statement of ast.statements) {+ if (+ !ts.isImportDeclaration(statement) ||+ !ts.isStringLiteral(statement.moduleSpecifier) ||+ statement.importClause?.isTypeOnly+ )+ continue;+ const clause = statement.importClause;+ if (clause?.name && statement.moduleSpecifier.text.endsWith('.module.css'))+ imports.push({ source: statement.moduleSpecifier.text, symbol: clause.name.text });+ if (+ ['@lobehub/ui', 'antd-style'].includes(statement.moduleSpecifier.text) &&+ clause?.namedBindings &&+ ts.isNamedImports(clause.namedBindings)+ )+ for (const element of clause.namedBindings.elements)+ if (+ !element.isTypeOnly &&+ (element.propertyName?.text ?? element.name.text) === 'createStaticStyles'+ )+ factories.add(element.name.text);+ }+ for (const statement of ast.statements) {+ if (!ts.isVariableStatement(statement)) continue;+ for (const declaration of statement.declarationList.declarations) {+ const call = declaration.initializer;+ if (+ !ts.isIdentifier(declaration.name) ||+ !call ||+ !ts.isCallExpression(call) ||+ !ts.isIdentifier(call.expression) ||+ !factories.has(call.expression.text)+ )+ continue;+ const callback = call.arguments[0];+ const body =+ callback && (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback))+ ? callback.body+ : undefined;+ if (+ body &&+ ts.isBlock(body) &&+ body.statements.some(+ (statement) => !ts.isVariableStatement(statement) && !ts.isReturnStatement(statement),+ )+ ) {+ gaps.push('STATIC_FACTORY_CONTROL_FLOW_UNSUPPORTED');+ continue;+ }+ let returned =+ body && ts.isBlock(body) ? body.statements.find(ts.isReturnStatement)?.expression : body;+ while (+ returned &&+ (ts.isParenthesizedExpression(returned) ||+ ts.isAsExpression(returned) ||+ ts.isSatisfiesExpression(returned) ||+ ts.isTypeAssertionExpression(returned))+ )+ returned = returned.expression;+ if (!returned || !ts.isObjectLiteralExpression(returned)) {+ gaps.push('STATIC_FACTORY_RETURN_UNSUPPORTED');+ continue;+ }+ const slots: StyleBindingPlan['bindings'][number]['slots'] = [];+ for (const property of returned.properties) {+ if (+ !ts.isPropertyAssignment(property) ||+ (!ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name))+ ) {+ gaps.push('DYNAMIC_STYLE_SLOT_UNSUPPORTED');+ continue;+ }+ slots.push({+ end: property.end,+ name: property.name.text,+ start: property.getStart(ast),+ unitId: `${file}:style-slot:${property.getStart(ast)}`,+ });+ }+ bindings.push({ kind: 'static-factory', slots, symbol: declaration.name.text });+ // The observer proves slot identity, not that template compilation was complete.+ gaps.push('LEGACY_TEMPLATE_RULE_SOURCE_UNPROVEN');+ }+ }+ if (!bindings.length && !imports.length) gaps.push('STYLE_BINDING_ADAPTER_UNAVAILABLE');+ return { bindings, gaps, imports };+};++export const prepareStyleBindings = async (+ directory: string,+ source: string,+): Promise<StyleBindingPlan> => {+ const root = await realpath(directory);+ const file = await realpath(path.resolve(root, source));+ if (!file.startsWith(root + path.sep)) throw new Error('STYLE_BINDING_SOURCE_ESCAPE');+ const code = await readFile(file, 'utf8');+ const analysis = analyzeStyleBindings(code, source);+ const composition = planCompositionObserver(code, source);+ const stylesheets: StyleBindingPlan['stylesheets'] = [];+ if (analysis.imports.length > 20 || code.length > 4 * 1024 ** 2)+ throw new Error('STYLE_BINDING_SOURCE_BUDGET_EXCEEDED');+ for (const imported of analysis.imports) {+ if (!imported.source.startsWith('.')) {+ analysis.gaps.push('CSS_MODULE_SOURCE_ALIAS_UNSUPPORTED');+ continue;+ }+ const cssFile = await realpath(path.resolve(path.dirname(file), imported.source));+ if (!cssFile.startsWith(root + path.sep)) throw new Error('STYLE_BINDING_SOURCE_ESCAPE');+ const css = await readFile(cssFile, 'utf8');+ if (css.length > 4 * 1024 ** 2) throw new Error('STYLE_BINDING_SOURCE_BUDGET_EXCEEDED');+ const cssPath = path.relative(root, cssFile);+ const rules: StyleBindingPlan['stylesheets'][number]['rules'] = [];+ const classes = new Set<string>();+ const parsed = postcss.parse(css, { from: cssPath });+ parsed.walkRules((rule) => {+ const conditions: Array<{ kind: string; text: string }> = [];+ for (let parent = rule.parent; parent && parent.type !== 'root'; parent = parent.parent) {+ if (parent.type === 'atrule')+ conditions.unshift({ kind: parent.name, text: parent.params });+ else if (parent.type === 'rule') analysis.gaps.push('SOURCE_NATIVE_NESTING_UNBOUND');+ }+ try {+ analyzeSelector(rule.selector).forEach((selector) => {+ selector.classes.forEach((name) => classes.add(name));+ analysis.gaps.push(...selector.gaps);+ });+ } catch (error) {+ console.error('SOURCE_SELECTOR_PARSE_ERROR', error);+ analysis.gaps.push('SOURCE_SELECTOR_PARSE_ERROR');+ }+ rules.push({+ conditions,+ end: rule.source?.end?.offset ?? css.length,+ selector: rule.selector,+ start: rule.source?.start?.offset ?? 0,+ });+ });+ analysis.bindings.push({+ kind: 'css-module',+ symbol: imported.symbol,+ slots: [...classes]+ .sort()+ .map((name) => ({ name, start: 0, end: css.length, unitId: `${cssPath}:stylesheet:0` })),+ });+ stylesheets.push({ file: cssPath, hash: sha256(css), rules });+ }+ return {+ bindings: analysis.bindings,+ composition,+ gaps: [...new Set([...analysis.gaps, ...composition.gaps])],+ source,+ sourceHash: sha256(code),+ stylesheets,+ };+};++export const bindingObserverExport = (plan: StyleBindingPlan) => {+ for (const binding of plan.bindings)+ if (!/^[$A-Z_][$\w]*$/i.test(binding.symbol)) throw new Error('INVALID_STYLE_BINDING_SYMBOL');+ return `\nexport const __styleVerificationBindings = {${plan.bindings.map(({ symbol }) => `${JSON.stringify(symbol)}:${symbol}`).join(',')}};\n`;+};diff --git a/scripts/stylexMigration/verification/analysis/supplementalProbes.test.ts b/scripts/stylexMigration/verification/analysis/supplementalProbes.test.tsnew file mode 100644index 00000000000..e4264258fc1--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/supplementalProbes.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from 'vitest';++import type { FixtureProbe } from '../pipeline/probePlanner';+import type { RuleProbeEvidence } from './ruleCoverage';+import { planRuleWitnesses } from './ruleWitnesses';+import { planSupplementalProbes } from './supplementalProbes';++const plan = planRuleWitnesses(+ {+ gaps: [],+ rules: [+ {+ kind: 'CSSStyleRule',+ path: '0.0',+ selector: '.row:hover',+ selectorAncestors: [],+ conditions: [],+ text: '',+ },+ ],+ },+ {+ bindings: [+ {+ kind: 'css-module',+ symbol: 'styles',+ slots: [{ name: 'row', start: 0, end: 1, unitId: 'row' }],+ },+ ],+ gaps: [],+ source: 'file',+ sourceHash: 'hash',+ stylesheets: [],+ },+ { styles: { row: 'row' } },+);+const probe: FixtureProbe = {+ id: 'initial',+ variant: 'normal',+ pseudo: 'default',+ direction: 'ltr',+ width: 320,+};+const target = (key: string, active: boolean) => ({+ key,+ active,+ conditionStates: [],+ containers: [],+ content: undefined,+ display: undefined,+ triggers: [{ key, state: 'hover', tag: 'TR' }],+});+const evidence: RuleProbeEvidence = {+ probeId: probe.id,+ side: 'base',+ variant: 'normal',+ evidenceRefs: ['capture'],+ observation: {+ registeredProperties: [],+ viewportWidth: 1200,+ direction: 'ltr',+ observations: [{ id: '0.0:0', targets: [target('root.0', true), target('root.1', false)] }],+ },+};+const input = {+ plans: [{ plan, side: 'base' as const, variant: 'normal' }],+ evidence: [evidence],+ probes: [probe],+ remaining: 80,+};++describe('bounded activation-gap supplementation', () => {+ it('targets the untouched row instead of forcing every matching row together', () => {+ const result = planSupplementalProbes(input);+ expect(result.scheduled).toHaveLength(1);+ expect(result.scheduled[0].interaction).toEqual({ key: 'root.1', state: 'hover', tag: 'TR' });+ expect(result.requirements[0].key).toBe('root.1');+ expect(result.gateEligible).toBe(false);+ });+ it('deduplicates a paired B/M gap but never drops overflow requirements', () => {+ const result = planSupplementalProbes({+ ...input,+ plans: [...input.plans, { plan, side: 'candidate', variant: 'normal' }],+ evidence: [evidence, { ...evidence, side: 'candidate' }],+ remaining: 0,+ });+ expect(result.blocked).toHaveLength(1);+ expect(result.requirements).toHaveLength(2);+ expect(result.scheduled).toHaveLength(0);+ expect(result.gaps).toContain('SUPPLEMENTAL_PROBE_BUDGET_EXCEEDED');+ });+ it('does not invent operations for ambiguous or missing trigger bindings', () => {+ const result = planSupplementalProbes({+ ...input,+ evidence: [+ {+ ...evidence,+ observation: {+ registeredProperties: [],+ viewportWidth: 1200,+ direction: 'ltr',+ observations: [+ { id: '0.0:0', targets: [{ ...target('root.1', false), triggers: [] }] },+ ],+ },+ },+ ],+ });+ expect(result.scheduled).toHaveLength(0);+ expect(result.gaps).toContain('TRIGGER_BINDING_AMBIGUOUS_OR_MISSING');+ expect(result.requirements).toHaveLength(1);+ });+ it('does not schedule states where no observation has satisfied the condition', () => {+ const result = planSupplementalProbes({+ ...input,+ evidence: [+ {+ ...evidence,+ observation: {+ registeredProperties: [],+ viewportWidth: 1200,+ direction: 'ltr',+ observations: [+ { id: '0.0:0', targets: [{ ...target('root.1', false), conditionStates: [false] }] },+ ],+ },+ },+ ],+ });+ expect(result.scheduled).toHaveLength(0);+ });+});diff --git a/scripts/stylexMigration/verification/analysis/supplementalProbes.ts b/scripts/stylexMigration/verification/analysis/supplementalProbes.tsnew file mode 100644index 00000000000..b5adf95146e--- /dev/null+++ b/scripts/stylexMigration/verification/analysis/supplementalProbes.ts@@ -0,0 +1,79 @@+import type { FixtureProbe } from '../pipeline/probePlanner';+import type { RuleProbeEvidence } from './ruleCoverage';+import { summarizeRuleCoverage } from './ruleCoverage';+import type { RuleWitnessPlan } from './ruleWitnesses';++/** Minimum activation-gap probes, NOT full condition/state partition coverage. */+export const planSupplementalProbes = (options: {+ evidence: RuleProbeEvidence[];+ plans: Array<{ plan: RuleWitnessPlan; side: 'base' | 'candidate'; variant: string }>;+ probes: FixtureProbe[];+ remaining: number;+}) => {+ const coverage = summarizeRuleCoverage(options.plans, options.evidence);+ const probes = new Map<string, FixtureProbe>();+ const requirements: Array<{+ key: string;+ evidenceRefs?: string[];+ probeId?: string;+ sourceProbeId?: string;+ reason?: string;+ ruleId: string;+ side: string;+ variant: string;+ }> = [];+ for (const rule of coverage.rules) {+ if (rule.gaps.length) continue;+ for (const key of rule.missingActivationKeys) {+ const requirement = { key, ruleId: rule.id, side: rule.side, variant: rule.variant };+ if (rule.states.length !== 1) {+ requirements.push({+ ...requirement,+ reason: 'MULTI_STATE_OR_NON_INTERACTION_GAP_UNPLANNED',+ });+ continue;+ }+ const sample = options.evidence+ .filter((entry) => entry.side === rule.side && entry.variant === rule.variant)+ .flatMap((entry) =>+ (entry.observation.observations.find((item) => item.id === rule.id)?.targets ?? [])+ .filter(+ (target) =>+ target.key === key && target.conditionStates.every((state) => state === true),+ )+ .map((target) => ({ entry, target })),+ )+ .find(({ target }) => target.triggers?.length === 1);+ const contract = options.probes.find((probe) => probe.id === sample?.entry.probeId);+ if (!sample || !contract) {+ requirements.push({ ...requirement, reason: 'TRIGGER_BINDING_AMBIGUOUS_OR_MISSING' });+ continue;+ }+ const interaction = sample.target.triggers![0];+ const id = `supplement:${contract.variant}:${contract.direction}:${contract.width}:${interaction.key}:${interaction.state}`;+ probes.set(id, { ...contract, id, interaction, pseudo: 'default' });+ requirements.push({+ ...requirement,+ probeId: id,+ sourceProbeId: sample.entry.probeId,+ evidenceRefs: sample.entry.evidenceRefs,+ });+ }+ }+ const planned = [...probes.values()];+ const scheduled = planned.slice(0, Math.max(0, options.remaining));+ return {+ coverageBefore: coverage.summary,+ gaps: [+ ...new Set([+ ...requirements.flatMap((entry) => (entry.reason ? [entry.reason] : [])),+ ...(planned.length > scheduled.length ? ['SUPPLEMENTAL_PROBE_BUDGET_EXCEEDED'] : []),+ ]),+ ],+ mode: 'minimum-target-activation-gap' as const,+ requirements,+ scheduled,+ blocked: planned.slice(scheduled.length),+ gateEligible: false as const,+ };+};diff --git a/scripts/stylexMigration/verification/browser/capture.ts b/scripts/stylexMigration/verification/browser/capture.tsnew file mode 100644index 00000000000..6fc3dc6c176--- /dev/null+++ b/scripts/stylexMigration/verification/browser/capture.ts@@ -0,0 +1,59 @@+import type { CDPSession, Page } from '@playwright/test';++import { createFastCapture } from './fastCapture';+import type { StyleSnapshot } from './snapshot';+import { captureInPage } from './snapshot';++export interface ComponentSnapshot {+ attributes: Array<{ attributes: Array<[string, string]>; key: string; text: string }>;+ backend: 'hybrid' | 'strict';+ tree: StyleSnapshot;+}++export interface CaptureTiming {+ custom?: number;+ fast?: Record<string, number>;+ merge?: number;+ metadata?: number;+ standard?: number;+ total?: number;+}++export const captureComponent = async (+ page: Page,+ cdp: CDPSession,+ timing?: CaptureTiming,+): Promise<ComponentSnapshot> => {+ const started = performance.now();+ let phaseStarted = started;+ const { captureMetadata: metadata, ...prepared } = await page.evaluate(captureInPage, {+ animationTime: 0,+ collectMetadata: true,+ });+ if (!metadata) throw new Error('CAPTURE_PREPARATION_MISSING');+ if (timing) timing.metadata = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ if (metadata.standard.join('\0') !== metadata.rootProperties.toSorted().join('\0')) {+ const tree = await page.evaluate(captureInPage, {});+ if (timing) {+ timing.standard = performance.now() - phaseStarted;+ timing.total = performance.now() - started;+ }+ return {+ attributes: metadata.attributes,+ backend: 'strict',+ tree,+ };+ }+ const capture = await createFastCapture(page, cdp, {+ properties: metadata.rootProperties,+ prepared,+ nodeStyles: metadata.custom.length > 0,+ });+ const tree = await capture(0, timing ? (timing.fast = {}) : undefined);+ if (timing) timing.standard = performance.now() - phaseStarted;+ // Keep the existing node-local schema for custom values. The decoder avoids+ // interning full 1k-property styles only to immediately expand them again.+ if (timing) timing.total = performance.now() - started;+ return { attributes: metadata.attributes, backend: 'hybrid', tree };+};diff --git a/scripts/stylexMigration/verification/browser/compareSnapshots.test.ts b/scripts/stylexMigration/verification/browser/compareSnapshots.test.tsnew file mode 100644index 00000000000..7b53df33c99--- /dev/null+++ b/scripts/stylexMigration/verification/browser/compareSnapshots.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from 'vitest';++import type { ComponentSnapshot } from './capture';+import { compareComponents } from './compareSnapshots';++const snapshot = (style: Record<string, string> = {}): ComponentSnapshot => ({+ attributes: [{ attributes: [['role', 'status']], key: 'root.0', text: ' Text ' }],+ backend: 'hybrid',+ tree: {+ animations: [],+ durationMs: 0,+ nodes: [+ {+ box: [0, 0, 10, 10],+ key: 'root.0',+ scroll: [10, 10, 10, 10],+ style: 0,+ tag: 'SPAN',+ text: 'Text',+ },+ ],+ propertyReads: Object.keys(style).length,+ styles: [style],+ },+});++describe('extended component tree comparison', () => {+ it('detects SVG/render attributes even when computed styles are equal', () => {+ const before = snapshot();+ const after = snapshot();+ before.attributes[0].attributes = [['d', 'M0 0L10 10']];+ after.attributes[0].attributes = [['d', 'M0 0L20 20']];+ expect(compareComponents(before, after).differences).toContainEqual(+ expect.objectContaining({ key: 'root.0', property: 'DOM_ATTRIBUTES_OR_TEXT_CHANGED' }),+ );+ });+ it('does not trim away rendering-relevant whitespace', () => {+ const after = snapshot();+ after.attributes[0].text = 'Text';+ expect(compareComponents(snapshot(), after).differences).toHaveLength(1);+ });+ it('never blanket-ignores unknown custom properties', () => {+ const result = compareComponents(+ snapshot({ '--unknown': 'red' }),+ snapshot({ '--unknown': 'blue' }),+ );+ expect(result.raw).toHaveLength(1);+ expect(result.review).toHaveLength(1);+ expect(result.diagnostics).toHaveLength(0);+ });+ it('retains a custom property and its resolved consumer change separately', () => {+ const result = compareComponents(+ snapshot({ '--x': 'red', 'color': 'red' }),+ snapshot({ '--x': 'blue', 'color': 'blue' }),+ );+ expect(result.review).toHaveLength(1);+ expect(result.differences).toContainEqual(expect.objectContaining({ property: 'color' }));+ });+ it('explains only contextually nonpainting border differences', () => {+ const style = {+ 'border-top-color': 'red',+ 'border-top-style': 'none',+ 'border-top-width': '0px',+ };+ expect(+ compareComponents(snapshot(style), snapshot({ ...style, 'border-top-color': 'blue' }))+ .diagnostics,+ ).toHaveLength(1);+ expect(+ compareComponents(+ snapshot({ ...style, 'border-top-style': 'solid', 'border-top-width': '1px' }),+ snapshot({+ ...style,+ 'border-top-color': 'blue',+ 'border-top-style': 'solid',+ 'border-top-width': '1px',+ }),+ ).differences,+ ).toHaveLength(1);+ });+});diff --git a/scripts/stylexMigration/verification/browser/compareSnapshots.ts b/scripts/stylexMigration/verification/browser/compareSnapshots.tsnew file mode 100644index 00000000000..302d4b566a4--- /dev/null+++ b/scripts/stylexMigration/verification/browser/compareSnapshots.ts@@ -0,0 +1,27 @@+import type { ComponentSnapshot } from './capture';+import { compareSnapshots } from './snapshot';++export const compareComponents = (before: ComponentSnapshot, after: ComponentSnapshot) => {+ const raw = compareSnapshots(before.tree, after.tree);+ const beforeAttributes = new Map(before.attributes.map((entry) => [entry.key, entry]));+ const afterAttributes = new Map(after.attributes.map((entry) => [entry.key, entry]));+ for (const key of new Set([...beforeAttributes.keys(), ...afterAttributes.keys()])) {+ const previous = beforeAttributes.get(key);+ const current = afterAttributes.get(key);+ if (JSON.stringify(previous) !== JSON.stringify(current))+ raw.push({+ after: JSON.stringify(current),+ before: JSON.stringify(previous),+ key,+ property: 'DOM_ATTRIBUTES_OR_TEXT_CHANGED',+ });+ }+ return {+ diagnostics: raw.filter(+ (difference) => difference.diagnosticReason && !difference.property.startsWith('--'),+ ),+ differences: raw.filter((difference) => !difference.diagnosticReason),+ raw,+ review: raw.filter((difference) => difference.property.startsWith('--')),+ };+};diff --git a/scripts/stylexMigration/verification/browser/fastCapture.ts b/scripts/stylexMigration/verification/browser/fastCapture.tsnew file mode 100644index 00000000000..dce32d0e7fb--- /dev/null+++ b/scripts/stylexMigration/verification/browser/fastCapture.ts@@ -0,0 +1,136 @@+import type { CDPSession, Page } from '@playwright/test';++import type { StyleSnapshot } from './snapshot';+import { captureInPage } from './snapshot';++/** Blink batches standard computed properties and interns their values in DOMSnapshot.+ * Custom properties are not accepted by this CDP method. Resolved consumers still are.+ * No-layout nodes and pseudos missing from the protocol use the JS collector as fallback.+ */+export const createFastCapture = async (+ page: Page,+ cdp: CDPSession,+ options?: { properties: string[]; prepared: StyleSnapshot; nodeStyles?: boolean },+) => {+ const properties =+ options?.properties ??+ (await page.evaluate(() =>+ [...getComputedStyle(document.querySelector('[data-case-root]')!)].filter(+ (property) => !property.startsWith('--'),+ ),+ ));+ let preparedUsed = false;+ return async (+ animationTime?: number,+ timing?: Record<string, number>,+ ): Promise<StyleSnapshot> => {+ if (options?.prepared) {+ // A prepared frame is immediate, time-zero and one-shot. Never reuse its+ // names, geometry or custom values after a state/document change.+ if (animationTime !== undefined && animationTime !== 0)+ throw new Error('PREPARED_CAPTURE_REQUIRES_TIME_ZERO');+ if (preparedUsed) throw new Error('PREPARED_CAPTURE_ALREADY_USED');+ preparedUsed = true;+ }+ const started = performance.now();+ let phaseStarted = started;+ const metadata =+ options?.prepared ??+ (await page.evaluate(captureInPage, {+ animationTime,+ properties: ['animation-name'],+ }));+ if (timing) timing.metadata = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ const snapshot = await cdp.send('DOMSnapshot.captureSnapshot', { computedStyles: properties });+ if (timing) timing.protocol = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ const styleValues = new Map<string, Record<string, string>>();+ const normalKeys = metadata.nodes+ .filter((node) => !node.key.includes('::'))+ .map((node) => node.key);+ for (const document of snapshot.documents) {+ const nodes = document.nodes;+ const nodeCount = nodes.nodeName?.length ?? 0;+ const keys = new Map<number, string>();+ for (let index = 0; index < nodeCount; index++) {+ const attributes = nodes.attributes?.[index] ?? [];+ for (let item = 0; item < attributes.length; item += 2) {+ if (snapshot.strings[attributes[item]] !== 'data-experiment-node') continue;+ const key = normalKeys[Number(snapshot.strings[attributes[item + 1]])];+ if (key) keys.set(index, key);+ }+ }+ for (let item = 0; item < (nodes.pseudoType?.index.length ?? 0); item++) {+ const index = nodes.pseudoType!.index[item];+ const parent = keys.get(nodes.parentIndex?.[index] ?? -1);+ if (parent)+ keys.set(index, `${parent}::${snapshot.strings[nodes.pseudoType!.value[item]]}`);+ }+ document.layout.nodeIndex.forEach((index, layoutIndex) => {+ const key = keys.get(index);+ const values = document.layout.styles[layoutIndex];+ if (!key || !values?.length) return;+ styleValues.set(+ key,+ Object.fromEntries(+ properties.map((property, propertyIndex) => [+ property,+ snapshot.strings[values[propertyIndex]] ?? '',+ ]),+ ),+ );+ });+ }+ const missing = metadata.nodes+ .filter((node) => !styleValues.has(node.key))+ .map((node) => node.key);+ if (timing) timing.decode = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ let fallbackReads = 0;+ if (missing.length) {+ const fallback = await page.evaluate(captureInPage, {+ animationTime,+ properties,+ styleKeys: missing,+ });+ fallbackReads = fallback.propertyReads;+ for (const node of fallback.nodes)+ if (missing.includes(node.key)) styleValues.set(node.key, fallback.styles[node.style]);+ }+ if (timing) timing.fallback = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ const styles: StyleSnapshot['styles'] = [];+ const interned = new Map<string, number>();+ const resultNodes = metadata.nodes.map((node) => {+ const values = {+ ...styleValues.get(node.key),+ ...metadata.styles[node.style],+ };+ if (options?.nodeStyles) {+ const style = styles.length;+ styles.push(values);+ return { ...node, style };+ }+ const signature = JSON.stringify(values);+ let style = interned.get(signature);+ if (style === undefined) {+ style = styles.length;+ styles.push(values);+ interned.set(signature, style);+ }+ return { ...node, style };+ });+ if (timing) timing.intern = performance.now() - phaseStarted;+ return {+ ...metadata,+ durationMs: performance.now() - started,+ nodes: resultNodes,+ propertyReads:+ metadata.propertyReads ++ properties.length * (metadata.nodes.length - missing.length) ++ fallbackReads,+ styles,+ };+ };+};diff --git a/scripts/stylexMigration/verification/browser/probes.ts b/scripts/stylexMigration/verification/browser/probes.tsnew file mode 100644index 00000000000..9c7d42728b7--- /dev/null+++ b/scripts/stylexMigration/verification/browser/probes.ts@@ -0,0 +1,405 @@+import type { Page } from '@playwright/test';++import { createFastCapture } from './fastCapture';+import type { RuleInventory, StyleDifference, StyleSnapshot } from './snapshot';+import { captureInPage, compareSnapshots, inventoryInPage } from './snapshot';+import { createWitness } from './witness';++export interface Probe {+ animationTime?: number;+ containers?: Array<{ index: number; width: number }>;+ direction?: 'ltr' | 'rtl';+ forced?: { index: number; states: string[] };+ id: string;+ reducedMotion?: 'reduce' | 'no-preference';+ styleContainer?: { index: number; property: string; value: string };+ theme?: 'dark' | 'light';+ viewportWidth?: number;+}++export interface ProbePlan {+ inventories: RuleInventory[];+ probes: Probe[];+ unsupported: string[];+}++const forceable = ['hover', 'active', 'focus-visible', 'focus-within', 'focus'];+const numericWidths = (condition: string) =>+ [+ ...condition.matchAll(+ /(?:min-|max-)?(?:width|inline-size)\s*(?::|[<>=]{1,2})\s*(\d+(?:\.\d+)?)px/g,+ ),+ ...condition.matchAll(/(\d+(?:\.\d+)?)px\s*[<>=]{1,2}\s*(?:width|inline-size)/g),+ ].map((match) => Number(match[1]));++export const discoverProbes = async (+ pages: Page[],+ options: { extraEnvironments?: boolean; maxProbes?: number } = {},+): Promise<ProbePlan> => {+ const inventories = await Promise.all(+ pages.map((page) => page.evaluate(inventoryInPage, '[data-case-root]')),+ );+ const unsupported = new Set(inventories.flatMap((inventory) => inventory.unsupported));+ const probes: Probe[] = [{ id: 'default' }];+ const seen = new Set<string>();+ const add = (probe: Probe) => {+ const signature = JSON.stringify({ ...probe, id: undefined });+ if (!seen.has(signature)) {+ seen.add(signature);+ probes.push(probe);+ }+ };+ if (options.extraEnvironments !== false) {+ add({ id: 'dark', theme: 'dark' });+ add({ direction: 'rtl', id: 'rtl' });+ }+ const mediaWidths = new Set<number>();+ const containerWidths = new Map<string, { condition: string; widths: number[] }>();+ const allConditions = new Map(+ inventories+ .flatMap((inventory) => inventory.conditions)+ .map((entry) => [`${entry.kind}:${entry.condition}`, entry]),+ );+ for (const entry of allConditions.values()) {+ if (entry.kind === 'CSSMediaRule') {+ numericWidths(entry.condition).forEach((width) => mediaWidths.add(width));+ if (entry.condition.includes('prefers-reduced-motion'))+ add({ id: 'reduced-motion', reducedMotion: 'reduce' });+ if (entry.condition.includes('prefers-color-scheme'))+ add({ id: 'dark-media', theme: 'dark' });+ if (+ !numericWidths(entry.condition).length &&+ !/prefers-reduced-motion|prefers-color-scheme|\(hover: hover\)/.test(entry.condition)+ )+ unsupported.add(`media:${entry.condition}`);+ } else if (entry.kind === 'CSSContainerRule') {+ const widths = numericWidths(entry.condition);+ if (widths.length)+ containerWidths.set(entry.condition, { condition: entry.condition, widths });+ else {+ const literalStyle = entry.condition.match(+ /^(?:([\w-]+)\s+)?style\(\s*(--[\w-]+)\s*:\s*([\w.-]+)\s*\)$/,+ );+ if (!literalStyle) {+ unsupported.add(`container:${entry.condition}`);+ continue;+ }+ let found = false;+ for (let side = 0; side < pages.length; side++) {+ const targets = inventories[side].selectors+ .filter((selector) =>+ selector.conditions.some(+ (condition) =>+ condition.kind === entry.kind && condition.condition === entry.condition,+ ),+ )+ .flatMap((selector) => selector.targets);+ const indices = await pages[side].evaluate(+ ({ name, targets }) => {+ const result = new Set<number>();+ for (const target of targets) {+ let parent = document.querySelector(+ `[data-experiment-node="${target}"]`,+ )?.parentElement;+ while (parent?.hasAttribute('data-experiment-node')) {+ if (!name || getComputedStyle(parent).containerName.split(' ').includes(name)) {+ result.add(Number(parent.getAttribute('data-experiment-node')));+ break;+ }+ parent = parent.parentElement;+ }+ }+ return [...result];+ },+ { name: literalStyle[1], targets },+ );+ for (const index of indices) {+ found = true;+ add({+ id: `style-container-${index}-${literalStyle[2]}-${literalStyle[3]}`,+ styleContainer: { index, property: literalStyle[2], value: literalStyle[3] },+ });+ }+ }+ if (!found) unsupported.add(`style-container-not-found:${entry.condition}`);+ }+ } else if (entry.kind === 'CSSSupportsRule') {+ if (!(await pages[0].evaluate((condition) => CSS.supports(condition), entry.condition)))+ unsupported.add(`inactive-supports:${entry.condition}`);+ } else unsupported.add(`condition:${entry.kind}:${entry.condition}`);+ }+ for (const width of mediaWidths)+ for (const delta of [-1, 0, 1])+ add({ id: `viewport-${width + delta}`, viewportWidth: Math.max(1, width + delta) });+ for (const { condition, widths } of containerWidths.values()) {+ const name = condition.match(/^([\w-]+)\s+\(/)?.[1];+ const indices = new Set<number>();+ for (let side = 0; side < pages.length; side++) {+ const inventory = inventories[side];+ const selectors =+ inventory.conditions.find(+ (entry) => entry.kind === 'CSSContainerRule' && entry.condition === condition,+ )?.selectors ?? [];+ const targets = inventory.selectors+ .filter((entry) => selectors.includes(entry.selector))+ .flatMap((entry) => entry.targets);+ const containers = await pages[side].evaluate(+ ({ name, targets }) => {+ const result = new Set<number>();+ for (const index of targets) {+ let element = document.querySelector(+ `[data-experiment-node="${index}"]`,+ )?.parentElement;+ while (element) {+ const style = getComputedStyle(element);+ if (+ ['inline-size', 'size'].includes(style.containerType) &&+ (!name || style.containerName.split(' ').includes(name))+ ) {+ const containerIndex = element.getAttribute('data-experiment-node');+ if (containerIndex !== null) result.add(Number(containerIndex));+ break;+ }+ element = element.parentElement;+ }+ }+ return [...result];+ },+ { name, targets },+ );+ containers.forEach((index) => indices.add(index));+ }+ if (indices.size === 0) unsupported.add(`container-not-found:${condition}`);+ for (const index of indices)+ for (const width of widths)+ for (const delta of [-1, 0, 1])+ add({+ containers: [{ index, width: Math.max(1, width + delta) }],+ id: `container-${index}-${width + delta}`,+ });+ }+ // A bounded cross-product covers the common nested media + container case.+ const viewportProbes = probes.filter((probe) => probe.viewportWidth !== undefined);+ const containerProbes = probes.filter((probe) => probe.containers?.length);+ if (viewportProbes.length * containerProbes.length <= 24)+ for (const viewport of viewportProbes)+ for (const container of containerProbes)+ add({+ containers: container.containers,+ id: `${viewport.id}+${container.id}`,+ viewportWidth: viewport.viewportWidth,+ });+ else if (viewportProbes.length && containerProbes.length)+ unsupported.add('condition-product-budget');+ const states = new Set<string>();+ const targetSet = new Set<number>();+ for (let side = 0; side < pages.length; side++) {+ const inventory = inventories[side];+ for (const entry of inventory.selectors) {+ const matches = [+ ...entry.selector.matchAll(/:(hover|active|focus-visible|focus-within|focus)(?![\w-])/g),+ ].map((match) => match[1]);+ matches.forEach((state) => states.add(state));+ if (matches.length) {+ const ancestors = await pages[side].evaluate(+ ({ exhaustive, targets }) => {+ if (exhaustive)+ return [...document.querySelectorAll('[data-experiment-node]')].map((element) =>+ Number(element.getAttribute('data-experiment-node')),+ );+ const result = new Set<number>();+ for (const index of targets) {+ let element = document.querySelector(`[data-experiment-node="${index}"]`);+ while (element?.hasAttribute('data-experiment-node')) {+ result.add(Number(element.getAttribute('data-experiment-node')));+ element = element.parentElement;+ }+ }+ return [...result];+ },+ { exhaustive: /[+~]|:has\(/.test(entry.selector), targets: entry.targets },+ );+ ancestors.forEach((index) => targetSet.add(index));+ }+ if (matches.length > 1) {+ for (const index of entry.targets)+ add({+ forced: { index, states: [...new Set(matches)] },+ id: `combined-${matches.join('-')}-${index}`,+ });+ }+ }+ }+ for (const state of forceable.filter((state) => states.has(state)))+ for (const index of targetSet)+ add({ forced: { index, states: [state] }, id: `${state}-${index}` });+ // Conditional interactions must run inside the condition, not just at desktop width.+ const conditionedInteraction = inventories.some((inventory) =>+ inventory.selectors.some(+ (entry) =>+ entry.conditions.length &&+ /:(?:hover|active|focus-visible|focus-within|focus)\b/.test(entry.selector),+ ),+ );+ if (conditionedInteraction) {+ const environments = probes.filter(+ (probe) =>+ probe.viewportWidth !== undefined || probe.containers || probe.reducedMotion || probe.theme,+ );+ const interactions = probes.filter((probe) => probe.forced);+ for (const environment of environments)+ for (const interaction of interactions)+ add({ ...environment, ...interaction, id: `${environment.id}+${interaction.id}` });+ }+ const hasAnimations = await pages[0].evaluate(() =>+ document.getAnimations().some((animation) => animation instanceof CSSAnimation),+ );+ if (hasAnimations)+ for (const animationTime of [450, 900])+ add({ animationTime, id: `animation-${animationTime}ms` });+ const maxProbes = options.maxProbes ?? 160;+ if (probes.length > maxProbes) {+ unsupported.add(`probe-budget:${probes.length}>${maxProbes}`);+ probes.length = maxProbes;+ }+ return { inventories, probes, unsupported: [...unsupported] };+};++export const createProbeDriver = async (page: Page, selector = '[data-case-root]') => {+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('DOM.enable');+ await cdp.send('CSS.enable');+ const { root } = await cdp.send('DOM.getDocument');+ const nodeIds = new Map<number, number>();+ let forcedNode: number | undefined;+ await page.evaluate((selector) => {+ const root = document.querySelector(selector)!;+ const entries = [root, ...root.querySelectorAll('*')].map(+ (element) => [element, element.getAttribute('style')] as const,+ );+ Object.assign(window, {+ __restoreExperimentStyles: () => {+ for (const [element, value] of entries)+ value === null ? element.removeAttribute('style') : element.setAttribute('style', value);+ },+ });+ }, selector);+ const readNode = async (index: number) => {+ const known = nodeIds.get(index);+ if (known) return known;+ const { nodeId } = await cdp.send('DOM.querySelector', {+ nodeId: root.nodeId,+ selector: `[data-experiment-node="${index}"]`,+ });+ if (!nodeId) throw new Error(`Missing probe target ${index}`);+ nodeIds.set(index, nodeId);+ return nodeId;+ };+ return {+ cdp,+ async apply(probe: Probe) {+ if (forcedNode)+ await cdp.send('CSS.forcePseudoState', { forcedPseudoClasses: [], nodeId: forcedNode });+ forcedNode = undefined;+ await page.setViewportSize({ height: 900, width: probe.viewportWidth ?? 1200 });+ await cdp.send('Emulation.setEmulatedMedia', {+ features: [+ { name: 'prefers-reduced-motion', value: probe.reducedMotion ?? 'no-preference' },+ { name: 'prefers-color-scheme', value: probe.theme ?? 'light' },+ ],+ });+ await page.evaluate((probe) => {+ (+ window as unknown as { __restoreExperimentStyles: () => void }+ ).__restoreExperimentStyles();+ document.documentElement.dataset.theme = probe.theme ?? 'light';+ document.documentElement.dir = probe.direction ?? 'ltr';+ for (const container of probe.containers ?? []) {+ const element = document.querySelector<HTMLElement>(+ `[data-experiment-node="${container.index}"]`,+ );+ if (!element) throw new Error(`Missing container ${container.index}`);+ element.style.width = `${container.width}px`;+ }+ if (probe.styleContainer) {+ const container = probe.styleContainer;+ document+ .querySelector<HTMLElement>(`[data-experiment-node="${container.index}"]`)!+ .style.setProperty(container.property, container.value);+ }+ }, probe);+ if (probe.forced) {+ forcedNode = await readNode(probe.forced.index);+ await cdp.send('CSS.forcePseudoState', {+ forcedPseudoClasses: probe.forced.states,+ nodeId: forcedNode,+ });+ }+ // Computed style forces style/layout synchronously; rAF can stall in background headless-shell tabs.+ await page.evaluate(() => document.documentElement.getBoundingClientRect().width);+ },+ async dispose() {+ if (forcedNode)+ await cdp.send('CSS.forcePseudoState', { forcedPseudoClasses: [], nodeId: forcedNode });+ await page.evaluate(() =>+ (+ window as unknown as { __restoreExperimentStyles: () => void }+ ).__restoreExperimentStyles(),+ );+ await cdp.detach();+ },+ };+};++export interface ProbeResult {+ differenceCount: number;+ differences: StyleDifference[];+ durationMs: number;+ id: string;+ propertyReads: number;+}++export const compareWithProbes = async (+ pages: Page[],+ plan: ProbePlan,+ backend: 'strict' | 'fast' = 'strict',+) => {+ const drivers = await Promise.all(pages.map((page) => createProbeDriver(page)));+ const witnesses = await Promise.all(+ pages.map((page, index) => createWitness(page, plan.inventories[index])),+ );+ const fastCollectors =+ backend === 'fast'+ ? await Promise.all(pages.map((page, index) => createFastCapture(page, drivers[index].cdp)))+ : undefined;+ const results: ProbeResult[] = [];+ let baseline: StyleSnapshot[] = [];+ try {+ for (const probe of plan.probes) {+ const started = performance.now();+ await Promise.all(drivers.map((driver) => driver.apply(probe)));+ const snapshots = await Promise.all(+ pages.map((page, index) =>+ fastCollectors+ ? fastCollectors[index](probe.animationTime)+ : page.evaluate(captureInPage, { animationTime: probe.animationTime }),+ ),+ );+ if (probe.id === 'default') baseline = snapshots;+ const differences = compareSnapshots(snapshots[0], snapshots[1]);+ await Promise.all(witnesses.map((witness) => witness.collect()));+ results.push({+ differenceCount: differences.length,+ differences,+ durationMs: performance.now() - started,+ id: probe.id,+ propertyReads: snapshots.reduce((sum, snapshot) => sum + snapshot.propertyReads, 0),+ });+ }+ } finally {+ await Promise.all(drivers.map((driver) => driver.dispose()));+ await Promise.all(witnesses.map((witness) => witness.dispose()));+ }+ const coverage = witnesses.map((witness) => witness.report());+ return { baseline, coverage, results };+};diff --git a/scripts/stylexMigration/verification/browser/ruleInventory.ts b/scripts/stylexMigration/verification/browser/ruleInventory.tsnew file mode 100644index 00000000000..2340983a658--- /dev/null+++ b/scripts/stylexMigration/verification/browser/ruleInventory.ts@@ -0,0 +1,73 @@+/** CSSOM inventory retains inactive rules, layers and native nested declarations. */+export const collectRulesInPage = () => {+ const rules: Array<{+ conditions: Array<{ kind: string; text: string }>;+ condition?: string;+ declarations?: Array<{ important: boolean; property: string; value: string }>;+ kind: string;+ name?: string;+ path: string;+ selector?: string;+ selectorAncestors: string[];+ text: string;+ }> = [];+ const gaps: string[] = [];+ const visit = (+ list: CSSRuleList,+ prefix: string,+ conditions: Array<{ kind: string; text: string }> = [],+ selectors: string[] = [],+ ) => {+ [...list].forEach((rule, index) => {+ const key = `${prefix}.${index}`;+ const grouping = rule as CSSGroupingRule;+ const style = rule as CSSStyleRule;+ const kind = rule.constructor.name;+ const condition = (rule as CSSConditionRule).conditionText;+ rules.push({+ conditions,+ condition,+ declarations: style.style+ ? [...style.style].map((property) => ({+ property,+ value: style.style.getPropertyValue(property),+ important: style.style.getPropertyPriority(property) === 'important',+ }))+ : undefined,+ kind,+ name: (rule as CSSRule & { name?: string }).name,+ path: key,+ selector: style.selectorText,+ selectorAncestors: selectors,+ text: grouping.cssRules?.length ? (style.style?.cssText ?? '') : rule.cssText,+ });+ if (kind === 'CSSImportRule') gaps.push(`IMPORTED_STYLESHEET_ADAPTER_UNAVAILABLE:${key}`);+ if (grouping.cssRules)+ visit(+ grouping.cssRules,+ key,+ condition+ ? [...conditions, { kind, text: condition }]+ : ['CSSScopeRule', 'CSSStartingStyleRule'].includes(kind)+ ? [...conditions, { kind, text: rule.cssText }]+ : conditions,+ style.selectorText ? [...selectors, style.selectorText] : selectors,+ );+ });+ };+ for (const [index, sheet] of [...document.styleSheets].entries()) {+ try {+ visit(sheet.cssRules, String(index));+ } catch (error) {+ console.error('STYLESHEET_UNREADABLE', error);+ gaps.push(`STYLESHEET_UNREADABLE:${index}`);+ }+ }+ if (+ document.adoptedStyleSheets.length ||+ document.querySelector('iframe') ||+ [...document.querySelectorAll('*')].some((element) => element.shadowRoot)+ )+ gaps.push('SURFACE_ADAPTER_UNAVAILABLE');+ return { gaps, rules };+};diff --git a/scripts/stylexMigration/verification/browser/runtimeCompositions.ts b/scripts/stylexMigration/verification/browser/runtimeCompositions.tsnew file mode 100644index 00000000000..77e410adc06--- /dev/null+++ b/scripts/stylexMigration/verification/browser/runtimeCompositions.ts@@ -0,0 +1,44 @@+import type { Page } from '@playwright/test';+import { z } from 'zod';++const schema = z.object({+ gaps: z.array(z.string()).max(20),+ records: z+ .array(+ z.object({+ callId: z.number().int().nonnegative(),+ inputs: z.array(z.string().max(16384)).max(256),+ output: z.string().max(16384),+ }),+ )+ .max(512),+});+export type RuntimeCompositions = z.infer<typeof schema>;++export const readRuntimeCompositions = async (page: Page) =>+ schema.parse(+ await page.evaluate(() => {+ const field = (value: unknown, key: string) => {+ const descriptor = Object.getOwnPropertyDescriptor(value, key);+ if (!descriptor || !('value' in descriptor))+ throw new Error('COMPOSITION_DATA_DESCRIPTOR_REQUIRED');+ return descriptor.value;+ };+ const array = (value: unknown) => {+ if (!Array.isArray(value)) throw new Error('COMPOSITION_ARRAY_REQUIRED');+ const length = field(value, 'length');+ if (!Number.isSafeInteger(length) || length < 0 || length > 512)+ throw new Error('COMPOSITION_READ_BUDGET_EXCEEDED');+ return Array.from({ length }, (_, index) => field(value, String(index)));+ };+ const trace = field(globalThis, '__styleVerificationCompositions');+ return {+ gaps: array(field(trace, 'gaps')),+ records: array(field(trace, 'records')).map((record) => ({+ callId: field(record, 'callId'),+ inputs: array(field(record, 'inputs')),+ output: field(record, 'output'),+ })),+ };+ }),+ );diff --git a/scripts/stylexMigration/verification/browser/snapshot.test.ts b/scripts/stylexMigration/verification/browser/snapshot.test.tsnew file mode 100644index 00000000000..2d0038f84c9--- /dev/null+++ b/scripts/stylexMigration/verification/browser/snapshot.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from 'vitest';++import type { StyleSnapshot } from './snapshot';+import { compareSnapshots } from './snapshot';++const snapshot = (style: Record<string, string> = {}, box = [0, 0, 100, 40]): StyleSnapshot => ({+ animations: [],+ durationMs: 0,+ nodes: [{ box, key: 'root.0', scroll: [100, 40, 100, 40], style: 0, tag: 'DIV', text: 'Text' }],+ propertyReads: Object.keys(style).length,+ styles: [style],+});++describe('component style snapshot comparison', () => {+ it('compares properties independently of declaration order', () => {+ expect(+ compareSnapshots(+ snapshot({ color: 'red', opacity: '1' }),+ snapshot({ opacity: '1', color: 'red' }),+ ),+ ).toEqual([]);+ });+ it('detects removed properties and generated pseudo-elements', () => {+ const before = snapshot({ color: 'red' });+ before.nodes.push({ ...before.nodes[0], key: 'root.0::before' });+ expect(compareSnapshots(before, snapshot())).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ property: 'color' }),+ expect.objectContaining({ key: 'root.0::before', property: 'node' }),+ ]),+ );+ });+ it('allows only bounded subpixel geometry noise', () => {+ expect(compareSnapshots(snapshot(), snapshot({}, [0, 0, 100.04, 40]))).toEqual([]);+ expect(compareSnapshots(snapshot(), snapshot({}, [0, 0, 100.1, 40]))).toEqual([+ expect.objectContaining({ property: 'box' }),+ ]);+ });+ it('retains but annotates inactive legacy flex differences', () => {+ const differences = compareSnapshots(+ snapshot({ '-webkit-box-align': 'center', 'display': 'flex' }),+ snapshot({ '-webkit-box-align': 'stretch', 'display': 'flex' }),+ );+ expect(differences).toHaveLength(1);+ expect(differences[0].diagnosticReason).toContain('inactive');+ });+ it('does not suppress legacy flex differences when either side uses that layout', () => {+ expect(+ compareSnapshots(+ snapshot({ '-webkit-box-align': 'center', 'display': '-webkit-box' }),+ snapshot({ '-webkit-box-align': 'stretch', 'display': '-webkit-box' }),+ )[0].diagnosticReason,+ ).toBeUndefined();+ });+ it('annotates only nonpainting border colors', () => {+ const border = {+ 'border-top-color': 'red',+ 'border-top-style': 'none',+ 'border-top-width': '0px',+ };+ expect(+ compareSnapshots(snapshot(border), snapshot({ ...border, 'border-top-color': 'blue' }))[0]+ .diagnosticReason,+ ).toContain('nonpainting');+ expect(+ compareSnapshots(+ snapshot({ ...border, 'border-top-style': 'solid', 'border-top-width': '2px' }),+ snapshot({+ ...border,+ 'border-top-color': 'blue',+ 'border-top-style': 'solid',+ 'border-top-width': '2px',+ }),+ )[0].diagnosticReason,+ ).toBeUndefined();+ });+ it('keeps custom-property diagnostics and their resolved rendering changes', () => {+ const differences = compareSnapshots(+ snapshot({ '--color': 'red', 'color': 'red' }),+ snapshot({ '--color': 'blue', 'color': 'blue' }),+ );+ expect(+ differences.find((difference) => difference.property === '--color')?.diagnosticReason,+ ).toContain('resolved');+ expect(+ differences.find((difference) => difference.property === 'color')?.diagnosticReason,+ ).toBeUndefined();+ });+ it('compares animation timing even at an identical first frame', () => {+ const before = snapshot();+ const after = snapshot();+ before.animations = [+ { key: 'root.0', keyframes: [{ opacity: 1 }], timing: { duration: 1000 } },+ ];+ after.animations = [{ key: 'root.0', keyframes: [{ opacity: 1 }], timing: { duration: 2000 } }];+ expect(compareSnapshots(before, after)).toEqual([+ expect.objectContaining({ property: 'animation-effects' }),+ ]);+ });+});diff --git a/scripts/stylexMigration/verification/browser/snapshot.ts b/scripts/stylexMigration/verification/browser/snapshot.tsnew file mode 100644index 00000000000..79a5c053aee--- /dev/null+++ b/scripts/stylexMigration/verification/browser/snapshot.ts@@ -0,0 +1,419 @@+export interface SnapshotNode {+ box: number[];+ key: string;+ scroll: number[];+ style: number;+ tag: string;+ text: string;+}++export interface StyleSnapshot {+ animations: Array<{ key: string; keyframes: unknown; timing: unknown }>;+ captureMetadata?: {+ attributes: Array<{ attributes: Array<[string, string]>; key: string; text: string }>;+ custom: string[];+ rootProperties: string[];+ standard: string[];+ };+ durationMs: number;+ nodes: SnapshotNode[];+ propertyReads: number;+ styles: Array<Record<string, string>>;+}++/** Self-contained: Playwright serializes this function into the test document. */+export const captureInPage = (+ options: {+ animationTime?: number;+ collectMetadata?: boolean;+ geometry?: boolean;+ properties?: string[];+ selector?: string;+ styleKeys?: string[];+ } = {},+): StyleSnapshot => {+ const started = performance.now();+ const root = document.querySelector(options.selector ?? '[data-case-root]');+ if (!root) throw new Error('The component root is missing');+ const elements = [root, ...root.querySelectorAll('*')].filter(+ (element) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(element.tagName),+ );+ if (elements.length < 2) throw new Error('The component has not mounted');+ const keys = new Map<Element, string>();+ const walk = (element: Element, key: string) => {+ keys.set(element, key);+ [...element.children]+ .filter((child) => elements.includes(child))+ .forEach((child, index) => walk(child, `${key}.${index}`));+ };+ walk(root, 'root');+ if (options.collectMetadata)+ elements.forEach((element, index) =>+ element.setAttribute('data-experiment-node', String(index)),+ );+ root.getBoundingClientRect();+ const canonical = (value: Record<string, unknown>) =>+ Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));+ const animationNames = new Map<string, string>();+ const animations: StyleSnapshot['animations'] = [];+ for (const animation of document.getAnimations()) {+ const effect = animation.effect;+ if (+ !(effect instanceof KeyframeEffect) ||+ !(effect.target instanceof Element) ||+ !root.contains(effect.target)+ )+ continue;+ if (animation instanceof CSSTransition) {+ animation.finish();+ continue;+ }+ animation.pause();+ animation.currentTime = options.animationTime ?? 0;+ const key = `${keys.get(effect.target)}${effect.pseudoElement ?? ''}`;+ const keyframes = effect+ .getKeyframes()+ .map((frame) => canonical(frame as unknown as Record<string, unknown>));+ const timing = canonical(effect.getTiming() as unknown as Record<string, unknown>);+ animations.push({ key, keyframes, timing });+ if (animation instanceof CSSAnimation)+ animationNames.set(animation.animationName, JSON.stringify({ keyframes, timing }));+ }+ animations.sort((a, b) => a.key.localeCompare(b.key));+ const declarations = new Map<Element, Map<string | undefined, CSSStyleDeclaration>>();+ const custom = new Set<string>();+ const standard = new Set<string>();+ const rootProperties: string[] = [];+ if (options.collectMetadata) {+ // Keep ALL five declaration inventories, including currently ungenerated+ // pseudos. Do not cache names across documents, widths or states.+ for (const element of elements) {+ const byPseudo = new Map<string | undefined, CSSStyleDeclaration>();+ declarations.set(element, byPseudo);+ for (const pseudo of [undefined, '::before', '::after', '::marker', '::placeholder']) {+ const computed = getComputedStyle(element, pseudo);+ byPseudo.set(pseudo, computed);+ const length = computed.length;+ for (let index = 0; index < length; index++) {+ const property = computed.item(index);+ (property.startsWith('--') ? custom : standard).add(property);+ if (element === root && !pseudo && !property.startsWith('--'))+ rootProperties.push(property);+ }+ }+ }+ }+ const origin = root.getBoundingClientRect();+ const rounded = (value: number) => Math.round(value * 1000) / 1000;+ const styles: StyleSnapshot['styles'] = [];+ const interned = new Map<string, number>();+ const nodes: SnapshotNode[] = [];+ let propertyReads = 0;+ const customProperties = [...custom].sort();+ const read = (element: Element, pseudo?: string) => {+ const computed = declarations.get(element)?.get(pseudo) ?? getComputedStyle(element, pseudo);+ const values: Record<string, string> = {};+ const key = `${keys.get(element)}${pseudo ?? ''}`;+ for (const property of options.styleKeys && !options.styleKeys.includes(key)+ ? []+ : options.collectMetadata+ ? ['animation-name', ...customProperties]+ : (options.properties ?? [...computed].sort())) {+ if (property.startsWith('--_stylex_experiment_witness_')) continue;+ let value = computed.getPropertyValue(property);+ if (property === 'animation-name' && value !== 'none')+ value = value+ .split(',')+ .map((name) => animationNames.get(name.trim()) ?? `unresolved:${name.trim()}`)+ .join(',');+ values[property] = value;+ propertyReads++;+ }+ const signature = JSON.stringify(values);+ let style = interned.get(signature);+ if (style === undefined) {+ style = styles.length;+ interned.set(signature, style);+ styles.push(values);+ }+ const box = element.getBoundingClientRect();+ nodes.push({+ box:+ options.geometry === false || pseudo+ ? []+ : [box.x - origin.x, box.y - origin.y, box.width, box.height].map(rounded),+ key: `${keys.get(element)}${pseudo ?? ''}`,+ scroll:+ options.geometry === false || pseudo+ ? []+ : [element.clientWidth, element.clientHeight, element.scrollWidth, element.scrollHeight],+ style,+ tag: element.tagName,+ text: pseudo+ ? computed.content+ : [...element.childNodes]+ .filter((node) => node.nodeType === Node.TEXT_NODE)+ .map((node) => node.textContent)+ .join('')+ .trim(),+ });+ };+ for (const element of elements) {+ read(element);+ for (const pseudo of ['::before', '::after']) {+ const content = getComputedStyle(element, pseudo).content;+ if (content && !['none', 'normal'].includes(content)) read(element, pseudo);+ }+ if (getComputedStyle(element).display === 'list-item') read(element, '::marker');+ if (element.matches('input[placeholder], textarea[placeholder]'))+ read(element, '::placeholder');+ }+ return {+ animations,+ durationMs: performance.now() - started,+ nodes,+ propertyReads,+ styles,+ ...(options.collectMetadata+ ? {+ captureMetadata: {+ attributes: elements.map((element) => ({+ attributes: [...element.attributes]+ .filter(+ (attribute) =>+ !['class', 'style', 'data-experiment-node'].includes(attribute.name),+ )+ .map((attribute): [string, string] => [attribute.name, attribute.value])+ .sort(([a], [b]) => (a < b ? -1 : 1)),+ key: keys.get(element)!,+ text: [...element.childNodes]+ .filter((node) => node.nodeType === Node.TEXT_NODE)+ .map((node) => node.textContent)+ .join(''),+ })),+ custom: customProperties,+ rootProperties,+ standard: [...standard].sort(),+ },+ }+ : {}),+ };+};++export interface RuleInventory {+ conditions: Array<{ condition: string; kind: string; selectors: string[] }>;+ cssText: string;+ nodeCount: number;+ pseudoElements: string[];+ relevantRules: number;+ selectors: Array<{+ conditions: Array<{ condition: string; kind: string }>;+ selector: string;+ targets: number[];+ }>;+ unsupported: string[];+}++/** Discovery retains inactive rules; matched styles alone do not do that. */+export const inventoryInPage = (selector = '[data-case-root]'): RuleInventory => {+ const root = document.querySelector(selector);+ if (!root) throw new Error('The component root is missing');+ const elements = [root, ...root.querySelectorAll('*')].filter(+ (element) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(element.tagName),+ );+ elements.forEach((element, index) => element.setAttribute('data-experiment-node', String(index)));+ const conditions = new Map<string, { condition: string; kind: string; selectors: string[] }>();+ const selectors: RuleInventory['selectors'] = [];+ const unsupported = new Set<string>();+ if (root.shadowRoot || [...root.querySelectorAll('*')].some((element) => element.shadowRoot))+ unsupported.add('shadow-dom');+ if (document.adoptedStyleSheets.length) unsupported.add('adopted-stylesheets');+ const pseudoElements = new Set<string>();+ const texts: string[] = [];+ let relevantRules = 0;+ const visit = (+ rules: CSSRuleList,+ parents: Array<{ condition: string; kind: string }>,+ parentSelector?: string,+ ) => {+ for (const rule of rules) {+ const kind = rule.constructor.name;+ const grouping = rule as CSSGroupingRule;+ const styleRule = rule as CSSStyleRule;+ const condition =+ (rule as CSSConditionRule).conditionText ??+ (['CSSScopeRule', 'CSSStartingStyleRule', 'CSSPositionTryRule'].includes(kind)+ ? rule.cssText.split('{')[0].trim()+ : undefined);+ if (kind === 'CSSLayerBlockRule' && (rule as CSSLayerBlockRule).name.startsWith('lobe-'))+ continue;+ const path = condition ? [...parents, { condition, kind }] : parents;+ const ownSelector = styleRule.selectorText;+ const currentSelector = ownSelector+ ? parentSelector+ ? ownSelector.includes('&')+ ? ownSelector.replaceAll('&', `:is(${parentSelector})`)+ : `:is(${parentSelector}) ${ownSelector}`+ : ownSelector+ : parentSelector;+ if (currentSelector && styleRule.style?.length) {+ const pseudos = [...currentSelector.matchAll(/::([\w-]+)(?:\([^)]*\))?/g)].map(+ (match) => match[1],+ );+ const targetSelector = currentSelector+ .replaceAll(/::[\w-]+(?:\([^)]*\))?/g, '')+ .replaceAll(/:dir\([^)]*\)|\[(?:data-theme|dir)\s*=[^\]]*\]/g, ':is(*)')+ .replaceAll(/:not\(\s*:(?:hover|active|focus-visible|focus-within|focus)\s*\)/g, ':is(*)')+ .replaceAll(+ /:(?:hover|active|focus-visible|focus-within|focus|checked|disabled|enabled|indeterminate|valid|invalid|user-valid|user-invalid|placeholder-shown|autofill|target|target-within|visited|open|popover-open|fullscreen|modal|picture-in-picture)(?![\w-])/g,+ ':is(*)',+ );+ const targets: number[] = [];+ try {+ elements.forEach((element, index) => {+ if (element.matches(targetSelector)) targets.push(index);+ });+ } catch {+ unsupported.add(`selector:${currentSelector}`);+ }+ if (targets.length > 0) {+ relevantRules++;+ selectors.push({ conditions: path, selector: currentSelector, targets });+ pseudos.forEach((pseudo) => pseudoElements.add(pseudo));+ for (const pseudo of pseudos)+ if (!['before', 'after', 'marker', 'placeholder'].includes(pseudo))+ unsupported.add(`pseudo-element:${pseudo}`);+ if (currentSelector.includes(':visited')) unsupported.add('pseudo-class:visited');+ if (+ /:(?:checked|disabled|enabled|indeterminate|valid|invalid|user-valid|user-invalid|placeholder-shown|autofill|target|target-within|open|popover-open|fullscreen|modal|picture-in-picture)\b/.test(+ currentSelector,+ )+ )+ unsupported.add(`state-needs-fixture:${currentSelector}`);+ for (const entry of path) {+ const key = `${entry.kind}:${entry.condition}`;+ const item = conditions.get(key) ?? { ...entry, selectors: [] };+ item.selectors.push(currentSelector);+ conditions.set(key, item);+ }+ }+ }+ if (grouping.cssRules) visit(grouping.cssRules, path, currentSelector);+ }+ };+ for (const sheet of document.styleSheets) {+ try {+ texts.push([...sheet.cssRules].map((rule) => rule.cssText).join('\n'));+ visit(sheet.cssRules, []);+ } catch (error) {+ unsupported.add(`stylesheet:${String(error)}`);+ }+ }+ return {+ conditions: [...conditions.values()],+ cssText: texts.join('\n'),+ nodeCount: elements.length,+ pseudoElements: [...pseudoElements],+ relevantRules,+ selectors,+ unsupported: [...unsupported],+ };+};++export interface StyleDifference {+ after?: string;+ before?: string;+ diagnosticReason?: string;+ key: string;+ property: string;+}++export const compareSnapshots = (+ before: StyleSnapshot,+ after: StyleSnapshot,+): StyleDifference[] => {+ const differences: StyleDifference[] = [];+ const beforeNodes = new Map(before.nodes.map((node) => [node.key, node]));+ const afterNodes = new Map(after.nodes.map((node) => [node.key, node]));+ for (const key of new Set([...beforeNodes.keys(), ...afterNodes.keys()])) {+ const oldNode = beforeNodes.get(key);+ const newNode = afterNodes.get(key);+ if (!oldNode || !newNode) {+ differences.push({ after: newNode?.tag, before: oldNode?.tag, key, property: 'node' });+ continue;+ }+ for (const property of ['tag', 'text'] as const)+ if (oldNode[property] !== newNode[property])+ differences.push({ after: newNode[property], before: oldNode[property], key, property });+ for (const property of ['box', 'scroll'] as const) {+ if (+ oldNode[property].some(+ (value, index) => Math.abs(value - (newNode[property][index] ?? Infinity)) > 0.05,+ ) ||+ oldNode[property].length !== newNode[property].length+ )+ differences.push({+ after: JSON.stringify(newNode[property]),+ before: JSON.stringify(oldNode[property]),+ key,+ property,+ });+ }+ const oldStyle = before.styles[oldNode.style];+ const newStyle = after.styles[newNode.style];+ for (const property of new Set([...Object.keys(oldStyle), ...Object.keys(newStyle)])) {+ if (oldStyle[property] !== newStyle[property])+ differences.push({ after: newStyle[property], before: oldStyle[property], key, property });+ }+ }+ if (JSON.stringify(before.animations) !== JSON.stringify(after.animations))+ differences.push({+ after: JSON.stringify(after.animations),+ before: JSON.stringify(before.animations),+ key: 'root',+ property: 'animation-effects',+ });+ return differences.map((difference) => {+ const oldNode = beforeNodes.get(difference.key);+ const newNode = afterNodes.get(difference.key);+ const oldStyle = oldNode ? before.styles[oldNode.style] : undefined;+ const newStyle = newNode ? after.styles[newNode.style] : undefined;+ if (difference.property.startsWith('--'))+ return {+ ...difference,+ diagnosticReason: 'custom-property: compare resolved consumers separately',+ };+ if (+ difference.property.startsWith('-webkit-box-') &&+ oldStyle &&+ newStyle &&+ ![oldStyle.display, newStyle.display].some((display) =>+ ['-webkit-box', '-webkit-inline-box'].includes(display),+ )+ )+ return {+ ...difference,+ diagnosticReason: 'inactive legacy flex property in this display context',+ };+ if (+ /^border-(?:block-(?:start|end)|inline-(?:start|end)|top|right|bottom|left)-color$/.test(+ difference.property,+ ) &&+ oldStyle &&+ newStyle+ ) {+ const width = difference.property.replace(/color$/, 'width');+ const style = difference.property.replace(/color$/, 'style');+ if (+ [oldStyle, newStyle].every(+ (values) => values[width] === '0px' && ['none', 'hidden'].includes(values[style]),+ )+ )+ return {+ ...difference,+ diagnosticReason: 'nonpainting border color at zero width and none/hidden style',+ };+ }+ return difference;+ });+};diff --git a/scripts/stylexMigration/verification/browser/witness.ts b/scripts/stylexMigration/verification/browser/witness.tsnew file mode 100644index 00000000000..c8c8637a0f6--- /dev/null+++ b/scripts/stylexMigration/verification/browser/witness.ts@@ -0,0 +1,60 @@+import type { Page } from '@playwright/test';++import type { RuleInventory } from './snapshot';++/** Independent marker rules prove that a discovered branch was actually activated.+ * These internal-only custom properties are excluded from the product snapshot.+ * This witnesses activation, not exhaustive truth-table coverage of all conditions.+ */+export const createWitness = async (page: Page, inventory: RuleInventory) => {+ const branches = inventory.selectors.filter(+ (entry) =>+ entry.conditions.length ||+ /:(?:hover|active|focus-visible|focus-within|focus)\b/.test(entry.selector),+ );+ const selectors = branches.map((entry, index) => {+ const selector = entry.selector.replaceAll(/::[\w-]+(?:\([^)]*\))?/g, '');+ let css = `${selector}{--_stylex_experiment_witness_${index}:active!important}`;+ for (const condition of [...entry.conditions].reverse()) {+ const keyword = {+ CSSContainerRule: 'container',+ CSSMediaRule: 'media',+ CSSSupportsRule: 'supports',+ }[condition.kind];+ if (keyword) css = `@${keyword} ${condition.condition}{${css}}`;+ }+ return css;+ });+ await page.evaluate((css) => {+ const style = document.createElement('style');+ style.id = 'stylex-experiment-witness';+ style.textContent = css;+ document.head.append(style);+ }, selectors.join('\n'));+ const witnessed = new Set<number>();+ return {+ async collect() {+ const indices = await page.evaluate((branches) => {+ const elements = [...document.querySelectorAll('[data-experiment-node]')];+ const computed = elements.map((element) => getComputedStyle(element));+ return branches.flatMap((entry, index) =>+ computed.some(+ (style) =>+ style.getPropertyValue(`--_stylex_experiment_witness_${index}`).trim() === 'active',+ )+ ? [index]+ : [],+ );+ }, branches);+ indices.forEach((index) => witnessed.add(index));+ },+ async dispose() {+ await page.evaluate(() => document.getElementById('stylex-experiment-witness')?.remove());+ },+ report: () => ({+ branches: branches.length,+ unwitnessed: branches.filter((_, index) => !witnessed.has(index)),+ witnessed: witnessed.size,+ }),+ };+};diff --git a/scripts/stylexMigration/verification/build/buildFixtures.ts b/scripts/stylexMigration/verification/build/buildFixtures.tsnew file mode 100644index 00000000000..130ede53311--- /dev/null+++ b/scripts/stylexMigration/verification/build/buildFixtures.ts@@ -0,0 +1,65 @@+import { readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';++import { compileFixtureTools } from './compileFixtureTools';+import { prepareFixtureHost } from '../fixtures/host';+import type { StyleFixture } from '../fixtures/fixtureRegistry';+import { runIsolatedProcess } from './isolatedProcess';+import { writeJson } from '../reporting/report';+import { bindingObserverExport, prepareStyleBindings } from '../analysis/styleBindings';++export const buildComponentFixture = async (+ root: string,+ sourceDirectory: string,+ fixture: StyleFixture,+ side: 'base' | 'candidate',+) => {+ const started = performance.now();+ const { componentSource, fixtureHashes, relativeTools, tools } = await prepareFixtureHost(+ root,+ sourceDirectory,+ fixture,+ side,+ );+ const bindingPlan = await prepareStyleBindings(root, componentSource);+ await writeJson(tools, 'style-bindings.json', {+ ...bindingPlan,+ observerExport: bindingObserverExport(bindingPlan),+ });+ await writeFile(+ path.join(tools, 'fixtureBuildWorker.ts'),+ await readFile(path.join(sourceDirectory, 'build/fixtureBuildWorker.ts')),+ { flag: 'wx' },+ );+ const compiler = await compileFixtureTools(+ root,+ [+ { source: 'plugins/vite/stylex.ts', output: 'stylex.mjs' },+ { source: 'plugins/vite/lobeUiImports.ts', output: 'lobeUiImports.mjs' },+ { source: `${relativeTools}/fixtureBuildWorker.ts`, output: 'fixtureBuildWorker.mjs' },+ ],+ `${relativeTools}/compiler`,+ );+ await writeJson(tools, 'compiler.json', compiler);+ const built = await runIsolatedProcess(+ root,+ process.execPath,+ [path.join(tools, 'compiler/fixtureBuildWorker.mjs'), componentSource, relativeTools],+ [process.execPath],+ tools,+ );+ await writeFile(path.join(tools, 'build.log'), built.stdout + built.stderr, { flag: 'wx' });+ const result = {+ componentSource,+ bindingPlan,+ durationMs: performance.now() - started,+ fixtureHashes,+ fixtureId: fixture.id,+ modules: JSON.parse(await readFile(path.join(tools, 'build-modules.json'), 'utf8')) as string[],+ sandbox: 'macos-sandbox-exec',+ toolchain: { node: process.version, compiler },+ output: path.join(tools, 'dist'),+ };+ await writeJson(tools, 'fixture-build.json', result);+ return result;+};diff --git a/scripts/stylexMigration/verification/build/compileFixtureTools.test.ts b/scripts/stylexMigration/verification/build/compileFixtureTools.test.tsnew file mode 100644index 00000000000..cb3852cd8a5--- /dev/null+++ b/scripts/stylexMigration/verification/build/compileFixtureTools.test.ts@@ -0,0 +1,67 @@+// @vitest-environment node+import { execFile } from 'node:child_process';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';++import { afterEach, expect, it } from 'vitest';++import { compileFixtureTools } from './compileFixtureTools';++const owned: string[] = [];+afterEach(async () => {+ for (const root of owned.splice(0)) await rm(root, { recursive: true, force: true });+});+const fixture = async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-tool-compile-test-'));+ owned.push(root);+ await mkdir(path.join(root, 'plugins'));+ return root;+};++it('erases types, follows only local runtime imports and preserves executable plugin behavior', async () => {+ const root = await fixture();+ await writeFile(+ path.join(root, 'plugins/entry.ts'),+ 'import {value} from "./local"; import type {Unused} from "./not-present"; console.log(value);',+ );+ await writeFile(path.join(root, 'plugins/local.ts'), 'export const value: number = 42;');+ const result = await compileFixtureTools(root, [+ { source: 'plugins/entry.ts', output: 'entry.mjs' },+ ]);+ expect(result.modules).toHaveLength(2);+ const { stdout } = await promisify(execFile)(process.execPath, [+ path.join(root, '.stylex-tools/compiler/entry.mjs'),+ ]);+ expect(stdout.trim()).toBe('42');+ expect(await readFile(path.join(root, '.stylex-tools/compiler/entry.mjs'), 'utf8')).toContain(+ './local.mjs',+ );+});++it('rejects escaping source/output paths and unsupported dynamic local imports', async () => {+ const root = await fixture();+ await writeFile(path.join(root, 'plugins/entry.ts'), 'export const value = 42;');+ await expect(+ compileFixtureTools(root, [{ source: 'plugins/entry.ts', output: '../escape.mjs' }]),+ ).rejects.toThrow('PATH_ESCAPE');+ await writeFile(path.join(root, 'plugins/entry.ts'), 'export const value = import("./dynamic");');+ await expect(+ compileFixtureTools(root, [{ source: 'plugins/entry.ts', output: 'entry.mjs' }]),+ ).rejects.toThrow('DYNAMIC_LOCAL_IMPORT');+});++it('isolates compiled tools for two fixtures and rejects output namespaces outside tools', async () => {+ const root = await fixture();+ await writeFile(path.join(root, 'plugins/entry.ts'), 'export const value: number = 42;');+ for (const id of ['One', 'Two']) {+ const result = await compileFixtureTools(+ root,+ [{ source: 'plugins/entry.ts', output: 'entry.mjs' }],+ `.stylex-tools/fixtures/${id}/compiler`,+ );+ expect(result.modules[0].output).toBe(`.stylex-tools/fixtures/${id}/compiler/entry.mjs`);+ }+ await expect(compileFixtureTools(root, [], '../outside')).rejects.toThrow('PATH_ESCAPE');+});diff --git a/scripts/stylexMigration/verification/build/compileFixtureTools.ts b/scripts/stylexMigration/verification/build/compileFixtureTools.tsnew file mode 100644index 00000000000..c3ffc2e1b83--- /dev/null+++ b/scripts/stylexMigration/verification/build/compileFixtureTools.ts@@ -0,0 +1,129 @@+import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises';+import path from 'node:path';++import ts from 'typescript';++import { sha256 } from '../reporting/report';++/** Type erasure only: never evaluates source plugins in the controller. */+export const compileFixtureTools = async (+ directory: string,+ entries: Array<{ output: string; source: string }>,+ outputDirectory = '.stylex-tools/compiler',+) => {+ const root = await realpath(directory);+ const outputRoot = path.resolve(root, outputDirectory);+ if (!outputRoot.startsWith(path.join(root, '.stylex-tools') + path.sep))+ throw new Error('FIXTURE_COMPILER_PATH_ESCAPE');+ const compiled = new Map<string, { source: string; sourceHash: string; outputHash: string }>();+ let bytes = 0;+ const compile = async (source: string, output: string): Promise<void> => {+ const file = await realpath(path.resolve(root, source));+ const target = path.resolve(outputRoot, output);+ if (!file.startsWith(root + path.sep) || !target.startsWith(outputRoot + path.sep))+ throw new Error('FIXTURE_COMPILER_PATH_ESCAPE');+ const existing = compiled.get(target);+ if (existing) {+ if (existing.source !== file) throw new Error('FIXTURE_COMPILER_OUTPUT_COLLISION');+ return;+ }+ const code = await readFile(file, 'utf8');+ bytes += Buffer.byteLength(code);+ if (compiled.size >= 100 || bytes > 5 * 1024 ** 2)+ throw new Error('FIXTURE_COMPILER_BUDGET_EXCEEDED');+ const transpiled = ts.transpileModule(code, {+ compilerOptions: {+ jsx: ts.JsxEmit.ReactJSX,+ module: ts.ModuleKind.ESNext,+ target: ts.ScriptTarget.ES2023,+ },+ fileName: file,+ reportDiagnostics: true,+ });+ if (+ transpiled.diagnostics?.some(+ (diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error,+ )+ )+ throw new Error(`FIXTURE_COMPILER_SYNTAX_ERROR:${source}`);+ const parsed = ts.createSourceFile(+ file + '.js',+ transpiled.outputText,+ ts.ScriptTarget.ES2023,+ true,+ ts.ScriptKind.JS,+ );+ const imports = new Set<string>();+ const visit = (node: ts.Node) => {+ if (+ (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&+ node.moduleSpecifier &&+ ts.isStringLiteral(node.moduleSpecifier) &&+ node.moduleSpecifier.text.startsWith('.')+ )+ imports.add(node.moduleSpecifier.text);+ if (+ ts.isCallExpression(node) &&+ node.expression.kind === ts.SyntaxKind.ImportKeyword &&+ node.arguments[0] &&+ ts.isStringLiteral(node.arguments[0]) &&+ node.arguments[0].text.startsWith('.')+ )+ throw new Error('FIXTURE_COMPILER_DYNAMIC_LOCAL_IMPORT_UNSUPPORTED');+ ts.forEachChild(node, visit);+ };+ visit(parsed);+ const replacements = new Map<string, string>();+ const pending: Array<{ output: string; source: string }> = [];+ for (const specifier of imports) {+ const stem = path.resolve(path.dirname(file), specifier);+ let resolved: string | undefined;+ for (const candidate of [stem, stem + '.ts', stem + '.js', path.join(stem, 'index.ts')]) {+ try {+ resolved = await realpath(candidate);+ break;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ }+ if (!resolved || !/\.[cm]?[jt]s$/.test(resolved))+ throw new Error(`FIXTURE_COMPILER_LOCAL_IMPORT_UNRESOLVED:${specifier}`);+ const rewritten = specifier.replace(/\.[cm]?[jt]s$/, '') + '.mjs';+ replacements.set(specifier, rewritten);+ pending.push({+ output: path.join(path.dirname(output), rewritten),+ source: path.relative(root, resolved),+ });+ }+ const transformed = ts.transform(parsed, [+ (context) => {+ const rewrite: ts.Visitor = (node) => {+ if (+ ts.isStringLiteral(node) &&+ (ts.isImportDeclaration(node.parent) || ts.isExportDeclaration(node.parent))+ ) {+ const replacement = replacements.get(node.text);+ if (replacement) return context.factory.createStringLiteral(replacement);+ }+ return ts.visitEachChild(node, rewrite, context);+ };+ return (sourceFile) => ts.visitNode(sourceFile, rewrite) as ts.SourceFile;+ },+ ]);+ const emitted = ts.createPrinter().printFile(transformed.transformed[0]);+ transformed.dispose();+ compiled.set(target, { outputHash: sha256(emitted), source: file, sourceHash: sha256(code) });+ await mkdir(path.dirname(target), { recursive: true });+ await writeFile(target, emitted, { flag: 'wx' });+ for (const entry of pending) await compile(entry.source, entry.output);+ };+ for (const entry of entries) await compile(entry.source, entry.output);+ return {+ compiler: `typescript@${ts.version}`,+ modules: [...compiled.entries()].map(([output, evidence]) => ({+ ...evidence,+ output: path.relative(root, output),+ source: path.relative(root, evidence.source),+ })),+ };+};diff --git a/scripts/stylexMigration/verification/build/fixtureBuildWorker.ts b/scripts/stylexMigration/verification/build/fixtureBuildWorker.tsnew file mode 100644index 00000000000..44abd1e939e--- /dev/null+++ b/scripts/stylexMigration/verification/build/fixtureBuildWorker.ts@@ -0,0 +1,128 @@+import { createHash } from 'node:crypto';+import { readFile, realpath, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { pathToFileURL } from 'node:url';++import react from '@vitejs/plugin-react';+import type { Plugin } from 'vite';+import { build } from 'vite';++/** Bundled into the source snapshot, then executed as a separate Node process. */+const main = async () => {+ const root = await realpath(process.cwd());+ const source = process.argv[2];+ const relativeTools = process.argv[3];+ if (!source || path.isAbsolute(source) || source.split('/').includes('..'))+ throw new Error('INVALID_COMPONENT_SOURCE');+ const component = await realpath(path.join(root, source));+ if (!component.startsWith(root + path.sep)) throw new Error('COMPONENT_SOURCE_ESCAPE');+ if (!relativeTools || path.isAbsolute(relativeTools) || relativeTools.split('/').includes('..'))+ throw new Error('INVALID_FIXTURE_TOOLS');+ const tools = await realpath(path.join(root, relativeTools));+ if (!tools.startsWith(path.join(root, '.stylex-tools') + path.sep))+ throw new Error('FIXTURE_TOOLS_ESCAPE');+ // These are the version's actual compiler/import plugins, not checkout plugins.+ const { stylexPlugin } = await import(+ pathToFileURL(path.join(tools, 'compiler/stylex.mjs')).href+ );+ const { lobeUiImports } = await import(+ pathToFileURL(path.join(tools, 'compiler/lobeUiImports.mjs')).href+ );+ const modules = new Set<string>();+ const observer = JSON.parse(await readFile(path.join(tools, 'style-bindings.json'), 'utf8')) as {+ composition: { edits: Array<{ start: number; end: number; text: string }> };+ observerExport: string;+ sourceHash: string;+ };+ const bindingObserver: Plugin = {+ name: 'verification-readonly-binding-observer',+ enforce: 'pre',+ transform(code, id) {+ if (id.split('?')[0] !== component) return;+ if (code.includes('__styleVerificationBindings'))+ throw new Error('STYLE_BINDING_OBSERVER_NAME_COLLISION');+ if (createHash('sha256').update(code).digest('hex') !== observer.sourceHash)+ throw new Error('STYLE_BINDING_OBSERVER_SOURCE_DRIFT');+ let rightBoundary = code.length;+ for (const edit of [...observer.composition.edits].sort((a, b) => b.start - a.start)) {+ if (+ !Number.isSafeInteger(edit.start) ||+ !Number.isSafeInteger(edit.end) ||+ edit.start < 0 ||+ edit.end < edit.start ||+ edit.end > rightBoundary+ )+ throw new Error('STYLE_BINDING_OBSERVER_EDIT_RANGE_INVALID');+ code = code.slice(0, edit.start) + edit.text + code.slice(edit.end);+ rightBoundary = edit.start;+ }+ return { code: code + observer.observerExport, map: null };+ },+ };+ const audit: Plugin = {+ name: 'verification-module-provenance',+ async load(id) {+ if (id.startsWith('\0') || id.startsWith('virtual:')) return;+ const file = id.split('?')[0];+ if (!path.isAbsolute(file)) return;+ const resolved = await realpath(file);+ if (!resolved.startsWith(root + path.sep)) throw new Error(`BUILD_MODULE_ESCAPE:${resolved}`);+ modules.add(path.relative(root, resolved));+ },+ };+ await build({+ base: './',+ build: {+ cssMinify: false,+ minify: false,+ outDir: path.join(tools, 'dist'),+ reportCompressedSize: false,+ chunkSizeWarningLimit: 10_000,+ },+ configFile: false,+ define: {+ '__CI__': 'false',+ '__DEV__': 'false',+ '__ELECTRON__': 'false',+ '__MOBILE__': 'false',+ '__REACT_SCAN__': 'false',+ '__TEST__': 'false',+ 'process.env': '{}',+ },+ logLevel: 'error',+ plugins: [+ audit,+ bindingObserver,+ stylexPlugin({ overlaySrcDirs: [path.join(root, 'src')] }),+ react(),+ ...lobeUiImports(),+ ],+ publicDir: false,+ resolve: {+ alias: [+ { find: 'verification:component', replacement: path.join(tools, 'host/component.ts') },+ {+ find: 'verification:locale/chat',+ replacement: path.join(root, 'packages/locales/src/default/chat.ts'),+ },+ {+ find: 'verification:locale/components',+ replacement: path.join(root, 'packages/locales/src/default/components.ts'),+ },+ { find: /^@\/const\//, replacement: path.join(root, 'packages/const/src/') },+ { find: '@', replacement: path.join(root, 'src') },+ ],+ dedupe: ['react', 'react-dom', '@emotion/react', '@emotion/css', '@stylexjs/stylex'],+ },+ root: path.join(tools, 'host'),+ });+ if (!modules.has(source)) throw new Error('COMPONENT_NOT_IN_BUILD_GRAPH');+ await writeFile(path.join(tools, 'build-modules.json'), JSON.stringify([...modules].sort()), {+ flag: 'wx',+ });+};++main().catch((error) => {+ console.error(error);+ process.exitCode = 3;+});diff --git a/scripts/stylexMigration/verification/build/isolatedProcess.test.ts b/scripts/stylexMigration/verification/build/isolatedProcess.test.tsnew file mode 100644index 00000000000..11cd47b43ba--- /dev/null+++ b/scripts/stylexMigration/verification/build/isolatedProcess.test.ts@@ -0,0 +1,108 @@+// @vitest-environment node+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { compileFixtureTools } from './compileFixtureTools';+import { runIsolatedProcess, sandboxProfile } from './isolatedProcess';++const owned: string[] = [];+afterEach(async () => {+ for (const root of owned.splice(0)) await rm(root, { force: true, recursive: true });+});++describe('build process boundary', () => {+ it('does not allow network or writes to source and dependency files', () => {+ const profile = sandboxProfile('/task', ['/bin/node']);+ expect(profile).toContain('(deny default)');+ expect(profile).not.toContain('allow network');+ expect(profile).toContain('(allow file-write* (subpath "/task/.stylex-tools")');+ });++ it('rejects writable paths outside the tool namespace', () => {+ expect(() => sandboxProfile('/task', ['/bin/node'], '/task/source')).toThrow(+ 'BUILD_WRITE_SCOPE_ESCAPE',+ );+ });++ it.skipIf(process.platform !== 'darwin')(+ 'cannot overwrite another component build namespace',+ async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-build-namespace-test-'));+ owned.push(root);+ const first = path.join(root, '.stylex-tools/fixtures/One');+ const second = path.join(root, '.stylex-tools/fixtures/Two');+ await mkdir(first, { recursive: true });+ await mkdir(second, { recursive: true });+ const other = path.join(second, 'output.txt');+ await writeFile(other, 'preserve');+ const code = `const fs=require('node:fs');fs.writeFileSync(${JSON.stringify(path.join(first, 'output.txt'))},'own');try{fs.writeFileSync(${JSON.stringify(other)},'changed');console.log('WRITE')}catch{console.log('other-denied')}`;+ const result = await runIsolatedProcess(+ root,+ process.execPath,+ ['-e', code],+ [process.execPath],+ first,+ );+ expect(result.stdout.trim()).toBe('other-denied');+ expect(await readFile(other, 'utf8')).toBe('preserve');+ expect(await readFile(path.join(first, 'output.txt'), 'utf8')).toBe('own');+ },+ );++ it.skipIf(process.platform !== 'darwin')(+ 'executes transpiled local plugins without consulting ancestor configuration',+ async () => {+ const parent = await mkdtemp(path.join(tmpdir(), 'stylex-sandbox-tool-test-'));+ owned.push(parent);+ const root = path.join(parent, 'nested/snapshot');+ await mkdir(path.join(root, '.stylex-tools/tmp'), { recursive: true });+ await writeFile(path.join(root, 'package.json'), '{"type":"module"}');+ await writeFile(path.join(parent, 'tsconfig.json'), 'must not load ancestor configuration');+ await writeFile(path.join(root, 'tsconfig.json'), '{}');+ await writeFile(+ path.join(root, 'entry.ts'),+ 'import {value} from "./value"; console.log(value);',+ );+ await writeFile(path.join(root, 'value.ts'), 'export const value: number = 42;');+ await compileFixtureTools(root, [{ source: 'entry.ts', output: 'entry.mjs' }]);+ const result = await runIsolatedProcess(+ root,+ process.execPath,+ [path.join(root, '.stylex-tools/compiler/entry.mjs')],+ [process.execPath],+ );+ expect(result.stdout.trim()).toBe('42');+ },+ );++ it.skipIf(process.platform !== 'darwin')(+ 'permits tool output but denies source writes, outside reads and outbound network',+ async () => {+ const parent = await mkdtemp(path.join(tmpdir(), 'stylex-sandbox-test-'));+ owned.push(parent);+ const root = path.join(parent, 'snapshot');+ await mkdir(path.join(root, '.stylex-tools/tmp'), { recursive: true });+ const outside = path.join(parent, 'outside.txt');+ await writeFile(outside, 'must not read');+ const source = path.join(root, 'source.txt');+ await writeFile(source, 'preserve');+ const code = `const fs=require('node:fs');const net=require('node:net');const results=[];try{fs.readFileSync(${JSON.stringify(outside)});results.push('LEAK')}catch{results.push('outside-denied')}try{fs.writeFileSync(${JSON.stringify(source)},'changed');results.push('WRITE')}catch{results.push('source-denied')}fs.writeFileSync('.stylex-tools/output.txt','safe');const socket=net.connect({host:'127.0.0.1',port:9});socket.on('error',()=>{results.push('network-denied');console.log(JSON.stringify(results));});setTimeout(()=>process.exit(3),2000).unref();`;+ const result = await runIsolatedProcess(+ root,+ process.execPath,+ ['-e', code],+ [process.execPath],+ );+ expect(JSON.parse(result.stdout)).toEqual([+ 'outside-denied',+ 'source-denied',+ 'network-denied',+ ]);+ expect(await readFile(source, 'utf8')).toBe('preserve');+ expect(await readFile(path.join(root, '.stylex-tools/output.txt'), 'utf8')).toBe('safe');+ },+ );+});diff --git a/scripts/stylexMigration/verification/build/isolatedProcess.ts b/scripts/stylexMigration/verification/build/isolatedProcess.tsnew file mode 100644index 00000000000..f808ecc906f--- /dev/null+++ b/scripts/stylexMigration/verification/build/isolatedProcess.ts@@ -0,0 +1,82 @@+import { execFile } from 'node:child_process';+import { realpath } from 'node:fs/promises';+import path from 'node:path';+import { promisify } from 'node:util';++import { childEnvironment } from '../dependencies/dependencySnapshot';++const execute = promisify(execFile);+const quote = (value: string) => JSON.stringify(value);++export const sandboxProfile = (+ root: string,+ executables: string[],+ writableDirectory = path.join(root, '.stylex-tools'),+) => {+ const toolRoot = path.resolve(root, '.stylex-tools');+ const writable = path.resolve(writableDirectory);+ if (writable !== toolRoot && !writable.startsWith(toolRoot + path.sep))+ throw new Error('BUILD_WRITE_SCOPE_ESCAPE');+ const readable = [+ '/System',+ '/usr',+ '/Library',+ '/private/etc',+ '/private/var/db',+ '/dev',+ '/bin',+ '/sbin',+ root,+ ];+ return `(version 1)+(deny default)+(import "dyld-support.sb")+(allow process*)+(allow sysctl-read)+(allow mach-lookup)+(allow file-read-metadata)+(allow file-read* file-map-executable ${readable.map((file) => `(subpath ${quote(file)})`).join(' ')} ${executables.map((file) => `(literal ${quote(file)})`).join(' ')})+(allow file-write* (subpath ${quote(writable)}) (literal "/dev/null"))+`;+};++/** Local macOS adapter only. No silent unsandboxed build fallback. */+export const runIsolatedProcess = async (+ root: string,+ executable: string,+ args: string[],+ executablePaths: string[],+ writableDirectory = path.join(root, '.stylex-tools'),+) => {+ if (process.platform !== 'darwin') throw new Error('BUILD_SANDBOX_ADAPTER_UNAVAILABLE');+ const canonicalRoot = await realpath(root);+ const executables = await Promise.all(executablePaths.map((file) => realpath(file)));+ const writable = await realpath(writableDirectory);+ return execute(+ '/usr/bin/sandbox-exec',+ ['-p', sandboxProfile(canonicalRoot, executables, writable), executable, ...args],+ {+ cwd: canonicalRoot,+ env: {+ ...childEnvironment(canonicalRoot),+ BROWSERSLIST_ROOT_PATH: canonicalRoot,+ PATH: [+ ...new Set(executables.map((file) => path.dirname(file))),+ '/usr/bin',+ '/bin',+ '/usr/sbin',+ '/sbin',+ ].join(path.delimiter),+ },+ maxBuffer: 8 * 1024 ** 2,+ timeout: 60_000,+ },+ ).catch((error: Error & { code?: number | string; signal?: string; stderr?: string }) => {+ console.error('ISOLATED_PROCESS_FAILED', {+ code: error.code,+ signal: error.signal,+ stderr: error.stderr,+ });+ throw error;+ });+};diff --git a/scripts/stylexMigration/verification/cli.ts b/scripts/stylexMigration/verification/cli.tsnew file mode 100644index 00000000000..9d4ce02b5da--- /dev/null+++ b/scripts/stylexMigration/verification/cli.ts@@ -0,0 +1,202 @@+import { mkdir, mkdtemp } from 'node:fs/promises';+import path from 'node:path';+import { parseArgs } from 'node:util';++import { fixtureIds, getStyleFixture } from './fixtures/fixtureRegistry';+import { exitCode } from './gate/gate';+import { runPreflight } from './pipeline/preflight';+import { fingerprintSources, writeJson } from './reporting/report';+import { resolvePullRequest } from './source/pullRequest';++const help = `StyleX migration verification — local M1 foundation (advisory only)++ bun run stylex:verify --base <ref> --head <ref> [--plan-only]+ bun run stylex:verify --pr <number> [--repo owner/name] [--plan-only]+ bun run stylex:verify --base <ref> --head <ref> --restore-dependencies [--dependency-store <path>]+ bun run stylex:verify --base <ref> --head <ref> --restore-dependencies --fixture LiteTable+ bun run stylex:verify --base <ref> --head <ref> --restore-dependencies --fixture LiteTable --fixture-dependencies+ bun run stylex:verify --base <ref> --head <ref> --restore-dependencies --fixtures DotsLoading,UnreadDot --fixture-dependencies+ bun run stylex:verify self-test [--browser <executable>]++Options: --output <parent-directory>, --repository <local-path>, --help+Available fixtures: ${fixtureIds.join(', ')}+Revision objects must exist locally. No Git fetch, GitHub writes or PR merges.+Dependency restore is opt-in, offline by default; --dependency-network explicitly enables public npm preparation.+Dependency scripts/hooks and credentials are disabled; component builds run in an offline macOS sandbox.+Default: export both complete source trees and report remaining verification gaps.+No PR receives PASS until isolated dependencies and certified fixture binding exist.+Exit: PASS 0 (self-test only), FAIL 1, NEEDS_REVIEW 2, ERROR 3, no change 4.+`;++const main = async () => {+ const { positionals, values } = parseArgs({+ allowPositionals: true,+ options: {+ 'base': { type: 'string' },+ 'browser': { type: 'string' },+ 'dependency-network': { type: 'boolean' },+ 'dependency-store': { type: 'string' },+ 'head': { type: 'string' },+ 'fixture': { type: 'string' },+ 'fixtures': { type: 'string' },+ 'fixture-dependencies': { type: 'boolean' },+ 'help': { short: 'h', type: 'boolean' },+ 'output': { type: 'string' },+ 'plan-only': { type: 'boolean' },+ 'pr': { type: 'string' },+ 'pnpm': { type: 'string' },+ 'restore-dependencies': { type: 'boolean' },+ 'repo': { type: 'string' },+ 'repository': { type: 'string' },+ },+ strict: true,+ });+ if (values.help) {+ console.log(help);+ return;+ }+ if (positionals.length > 1 || (positionals.length && positionals[0] !== 'self-test'))+ throw new Error('UNSUPPORTED_COMMAND');+ const selfTest = positionals[0] === 'self-test';+ if (+ (values['dependency-network'] || values['dependency-store'] || values.pnpm) &&+ !values['restore-dependencies']+ )+ throw new Error('DEPENDENCY_OPTIONS_REQUIRE_RESTORE');+ if (values['restore-dependencies'] && (selfTest || values['plan-only']))+ throw new Error('DEPENDENCY_RESTORE_REQUIRES_FULL_SOURCE');+ if (values.fixture && values.fixtures) throw new Error('CONFLICTING_FIXTURE_OPTIONS');+ const selectedFixtures = values.fixtures?.split(',').map((id) => id.trim());+ if (+ selectedFixtures &&+ (!selectedFixtures.length ||+ selectedFixtures.length > 32 ||+ new Set(selectedFixtures).size !== selectedFixtures.length ||+ selectedFixtures.some((id) => !id))+ )+ throw new Error('INVALID_FIXTURE_SELECTION');+ if (+ (values.fixture || values.fixtures) &&+ (!values['restore-dependencies'] || selfTest || values['plan-only'])+ )+ throw new Error('FIXTURE_REQUIRES_ISOLATED_DEPENDENCIES');+ if (values.fixture) getStyleFixture(values.fixture);+ selectedFixtures?.forEach(getStyleFixture);+ if (values['fixture-dependencies'] && !values.fixture && !values.fixtures)+ throw new Error('FIXTURE_DEPENDENCIES_REQUIRE_FIXTURE');+ if (selfTest && (values.pr || values.base || values.head || values['plan-only']))+ throw new Error('INVALID_SELF_TEST_OPTIONS');+ if (+ !selfTest &&+ ((!values.pr && (!values.base || !values.head)) || (values.pr && (values.base || values.head)))+ )+ throw new Error('Specify --pr OR both --base and --head');+ if (!selfTest && values.browser && !values.fixture && !values.fixtures)+ throw new Error('--browser requires self-test or --fixture');+ const repository = path.resolve(+ values.repository ?? process.env.STYLEX_VERIFIER_REPOSITORY ?? process.cwd(),+ );+ const sourceDirectory = process.env.STYLEX_VERIFIER_SOURCE_DIRECTORY;+ if (!sourceDirectory)+ throw new Error('Run through bun run stylex:verify to bind verifier sources');+ const verifierHash = await fingerprintSources([sourceDirectory]);+ if (verifierHash !== process.env.STYLEX_VERIFIER_SOURCE_HASH)+ throw new Error('VERIFIER_SOURCE_HASH_MISMATCH');+ const parent = path.resolve(+ values.output ?? path.join(repository, '.records/stylex-verification'),+ );+ await mkdir(parent, { recursive: true });+ const output = await mkdtemp(path.join(parent, `${selfTest ? 'self-test' : 'run'}-`));+ console.log(`Evidence: ${output}`);+ // Bounded process watchdog also covers page.evaluate calls without protocol timeouts.+ const watchdog = setTimeout(+ () => {+ console.error('ERROR: VERIFICATION_TIME_BUDGET_EXCEEDED');+ process.exit(3);+ },+ values['restore-dependencies'] ? 900_000 : 120_000,+ );+ watchdog.unref();+ try {+ if (selfTest) {+ const { runSelfTest } = await import('./selfTest');+ const result = await runSelfTest(output, verifierHash, values.browser);+ console.log(JSON.stringify(result));+ process.exitCode = exitCode(result.status);+ return;+ }+ let base = values.base;+ let head = values.head;+ let pullRequest: Awaited<ReturnType<typeof resolvePullRequest>> | undefined;+ if (values.pr) {+ if (!/^[1-9]\d*$/.test(values.pr) || !Number.isSafeInteger(Number(values.pr)))+ throw new Error('INVALID_PR_NUMBER');+ const pr = await resolvePullRequest(repository, Number(values.pr), values.repo);+ pullRequest = pr;+ await writeJson(output, 'pull-request.json', pr);+ base = pr.base;+ head = pr.head;+ }+ if (!base || !head) throw new Error('MISSING_REVISIONS');+ const result = await runPreflight({+ base,+ dependencyOptions: values['restore-dependencies']+ ? {+ allowNetwork: values['dependency-network'] ?? false,+ pnpm: values.pnpm ?? 'pnpm',+ store: path.resolve(+ values['dependency-store'] ?? path.join(output, 'dependency-store'),+ ),+ }+ : undefined,+ fixture: values.fixture+ ? {+ browser: values.browser,+ id: values.fixture,+ sourceDirectory,+ }+ : undefined,+ fixtureDependencies: values['fixture-dependencies'] ?? false,+ fixtureBatch: selectedFixtures+ ? { browser: values.browser, ids: selectedFixtures, sourceDirectory }+ : undefined,+ head,+ output,+ planOnly: values['plan-only'] ?? false,+ pullRequest,+ repository,+ verifierHash,+ });+ console.log(+ JSON.stringify({+ changedFiles: result.fixtures.unmappedFiles.length + result.fixtures.candidates.length,+ component: result.componentSummary,+ componentBatch: result.componentBatchSummary,+ gateEligible: result.gateEligible,+ reasonCodes: result.reasonCodes,+ report: path.join(output, 'report.html'),+ status: result.status,+ units: result.unresolvedUnitIds.length,+ }),+ );+ process.exitCode = exitCode(result.status);+ } catch (error) {+ console.error(error);+ await writeJson(output, 'error.json', {+ gateEligible: false,+ message: error instanceof Error ? error.message : String(error),+ mode: selfTest ? 'self-test' : 'preflight',+ schemaVersion: 1,+ status: 'ERROR',+ verifierHash,+ });+ process.exitCode = 3;+ } finally {+ clearTimeout(watchdog);+ }+};++main().catch((error) => {+ console.error(error);+ process.exitCode = 3;+});diff --git a/scripts/stylexMigration/verification/dependencies/dependencySnapshot.test.ts b/scripts/stylexMigration/verification/dependencies/dependencySnapshot.test.tsnew file mode 100644index 00000000000..540d6e88bbc--- /dev/null+++ b/scripts/stylexMigration/verification/dependencies/dependencySnapshot.test.ts@@ -0,0 +1,193 @@+// @vitest-environment node+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import {+ childEnvironment,+ fingerprintInstalledDependencies,+ restoreDependencies,+ validateDependencyLock,+} from './dependencySnapshot';++const owned: string[] = [];+const directory = async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-dependency-test-'));+ owned.push(root);+ return root;+};+afterEach(async () => {+ for (const root of owned.splice(0)) await rm(root, { force: true, recursive: true });+});++describe('immutable dependency evidence', () => {+ it('requires a complete graph and registry integrity rather than accepting module metadata alone', () => {+ expect(() => validateDependencyLock('nodeLinker: isolated')).toThrow(+ 'DEPENDENCY_LOCK_GRAPH_MISSING',+ );+ expect(() =>+ validateDependencyLock(+ 'lockfileVersion: "9.0"\nimporters: {.: {}}\npackages: {[email protected]: {resolution: {}}}',+ ),+ ).toThrow('DEPENDENCY_INTEGRITY_MISSING');+ const sri = 'sha512-' + Buffer.alloc(64).toString('base64');+ expect(+ validateDependencyLock(+ `lockfileVersion: "9.0"\nimporters: {.: {}}\npackages: {[email protected]: {resolution: {integrity: "${sri}"}}}`,+ ),+ ).toMatchObject({ importers: ['.'], packageCount: 1 });+ });++ it('does not inherit authentication, Node hooks, home or npm configuration', () => {+ const env = childEnvironment('/task');+ expect(env).not.toHaveProperty('HOME');+ expect(env).not.toHaveProperty('GH_TOKEN');+ expect(env).not.toHaveProperty('NODE_OPTIONS');+ expect(env).not.toHaveProperty('npm_config_userconfig');+ expect(env.XDG_CONFIG_HOME).toBe('/task/.stylex-tools/config');+ });++ it('hashes actual installed bytes and rejects links outside the snapshot', async () => {+ const root = await directory();+ const modules = path.join(root, 'node_modules/package');+ await mkdir(modules, { recursive: true });+ await writeFile(path.join(modules, 'index.js'), 'export const x=1');+ const first = await fingerprintInstalledDependencies(root);+ await writeFile(path.join(modules, 'index.js'), 'export const x=2');+ expect((await fingerprintInstalledDependencies(root)).sha256).not.toBe(first.sha256);+ await symlink(tmpdir(), path.join(root, 'node_modules/escape'));+ await expect(fingerprintInstalledDependencies(root)).rejects.toThrow('DEPENDENCY_LINK_ESCAPE');+ });+});++describe('real offline pnpm restore', () => {+ const fixture = async () => {+ const root = await directory();+ await mkdir(path.join(root, 'packages/local'), { recursive: true });+ await writeFile(+ path.join(root, 'package.json'),+ JSON.stringify({+ dependencies: { 'stylex-local-fixture': 'workspace:*' },+ name: 'verification-root',+ packageManager: '[email protected]',+ private: true,+ scripts: { postinstall: 'touch MUST_NOT_RUN' },+ }),+ );+ await writeFile(+ path.join(root, 'pnpm-workspace.yaml'),+ 'packages:\n - packages/*\nlockfile: false\n',+ );+ await writeFile(+ path.join(root, 'packages/local/package.json'),+ JSON.stringify({+ bin: { 'stylex-local-cli': 'cli.js' },+ main: 'index.js',+ name: 'stylex-local-fixture',+ version: '1.0.0',+ }),+ );+ await writeFile(path.join(root, 'packages/local/index.js'), 'module.exports=42');+ await writeFile(+ path.join(root, 'packages/local/cli.js'),+ '#!/usr/bin/env node\nconsole.log(42);',+ );+ return root;+ };+ const inputs = ['package.json', 'pnpm-workspace.yaml', 'packages/local/package.json'];++ it('generates a temporary lock then restores both sides frozen without running lifecycle scripts', async () => {+ const base = await fixture();+ const candidate = await fixture();+ const store = await directory();+ const options = { allowNetwork: false, pnpm: 'pnpm', store };+ const first = await restoreDependencies(base, inputs, options);+ const second = await restoreDependencies(candidate, inputs, options, first.lock);+ expect(second.snapshot.lockHash).toBe(first.snapshot.lockHash);+ expect(second.snapshot.content.sha256).toBe(first.snapshot.content.sha256);+ expect(second.snapshot.content.rawSha256).not.toBe(first.snapshot.content.rawSha256);+ expect(+ second.snapshot.content.normalizations.some(+ (entry) => entry.kind === 'pnpm-generated-launcher-location',+ ),+ ).toBe(true);+ expect(second.snapshot.snapshotHash).toBe(first.snapshot.snapshotHash);+ await expect(readFile(path.join(base, 'MUST_NOT_RUN'))).rejects.toThrow();+ expect(+ await readFile(path.join(candidate, 'node_modules/stylex-local-fixture/index.js'), 'utf8'),+ ).toContain('42');+ }, 30_000);++ it('refuses mismatched package-manager versions and executable config dependencies', async () => {+ const root = await fixture();+ await writeFile(+ path.join(root, 'pnpm-workspace.yaml'),+ 'configDependencies: {"malicious": "1.0.0"}\n',+ );+ await expect(+ restoreDependencies(root, inputs, { allowNetwork: false, pnpm: 'pnpm', store: root }),+ ).rejects.toThrow('DEPENDENCY_CONFIG_UNSUPPORTED');+ });++ it('does not turn a pre-existing node_modules into trusted dependency evidence', async () => {+ const root = await fixture();+ await mkdir(path.join(root, 'node_modules'));+ await expect(+ restoreDependencies(root, inputs, { allowNetwork: false, pnpm: 'pnpm', store: root }),+ ).rejects.toThrow('DEPENDENCY_TARGET_NOT_CLEAN');+ });++ it('rejects non-registry specifiers even in overrides before invoking pnpm', async () => {+ const root = await fixture();+ await writeFile(+ path.join(root, 'pnpm-workspace.yaml'),+ 'overrides:\n x: github:someone/private\n',+ );+ await expect(+ restoreDependencies(root, inputs, { allowNetwork: false, pnpm: 'pnpm', store: root }),+ ).rejects.toThrow('DEPENDENCY_PROTOCOL_UNSUPPORTED');+ });++ it('keeps offline cache misses as errors and saves the failed resolution log', async () => {+ const root = await fixture();+ const manifest = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));+ manifest.dependencies = { 'stylex-verifier-offline-cache-miss-fixture': '0.0.0' };+ await writeFile(path.join(root, 'package.json'), JSON.stringify(manifest));+ await expect(+ restoreDependencies(root, inputs, {+ allowNetwork: false,+ pnpm: 'pnpm',+ store: await directory(),+ }),+ ).rejects.toThrow('DEPENDENCY_RESOLVE_FAILED');+ expect(await readFile(path.join(root, '.stylex-tools/resolve.log'), 'utf8')).toContain(+ 'stylex-verifier-offline-cache-miss-fixture',+ );+ });++ it('validates root manifest overrides before allowing registry resolution', async () => {+ const root = await fixture();+ const manifest = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));+ manifest.overrides = { x: 'https://example.invalid/package.tgz' };+ await writeFile(path.join(root, 'package.json'), JSON.stringify(manifest));+ await expect(+ restoreDependencies(root, inputs, {+ allowNetwork: false,+ pnpm: 'pnpm',+ store: root,+ }),+ ).rejects.toThrow('DEPENDENCY_PROTOCOL_UNSUPPORTED');+ });++ it('does not let a snapshot select a different package-manager executable version', async () => {+ const root = await fixture();+ const manifest = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));+ manifest.packageManager = '[email protected]';+ await writeFile(path.join(root, 'package.json'), JSON.stringify(manifest));+ await expect(+ restoreDependencies(root, inputs, { allowNetwork: false, pnpm: 'pnpm', store: root }),+ ).rejects.toThrow('PNPM_ADAPTER_VERSION_UNSUPPORTED');+ });+});diff --git a/scripts/stylexMigration/verification/dependencies/dependencySnapshot.ts b/scripts/stylexMigration/verification/dependencies/dependencySnapshot.tsnew file mode 100644index 00000000000..5cdfc972a21--- /dev/null+++ b/scripts/stylexMigration/verification/dependencies/dependencySnapshot.ts@@ -0,0 +1,371 @@+import { execFile } from 'node:child_process';+import { createHash } from 'node:crypto';+import { createReadStream } from 'node:fs';+import { lstat, mkdir, readdir, readFile, readlink, realpath, writeFile } from 'node:fs/promises';+import { homedir } from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';++import { validRange } from 'semver';+import { parse, parseAllDocuments } from 'yaml';+import { z } from 'zod';++import { sha256, writeJson } from '../reporting/report';++const execute = promisify(execFile);+const record = z.record(z.string(), z.unknown());+const manifestSchema = z.object({ packageManager: z.string().optional() });+const supportedPnpmVersion = '12.4.1';++export interface DependencyOptions {+ allowNetwork: boolean;+ pnpm: string;+ store: string;+}++/** No inherited tokens, .env, Node loaders, npm config, SSH agent or Git overrides. */+export const childEnvironment = (directory: string): NodeJS.ProcessEnv => ({+ CI: 'true',+ COREPACK_ENABLE_NETWORK: '0',+ COREPACK_HOME:+ process.env.COREPACK_HOME ??+ path.join(process.env.XDG_CACHE_HOME ?? path.join(homedir(), '.cache'), 'node/corepack'),+ LANG: 'en_US.UTF-8',+ NODE_ENV: 'production',+ PATH: process.env.PATH,+ PNPM_HOME: path.join(directory, '.stylex-tools/pnpm'),+ TMPDIR: path.join(directory, '.stylex-tools/tmp'),+ XDG_CACHE_HOME: path.join(directory, '.stylex-tools/cache'),+ XDG_CONFIG_HOME: path.join(directory, '.stylex-tools/config'),+ XDG_DATA_HOME: path.join(directory, '.stylex-tools/data'),+ XDG_STATE_HOME: path.join(directory, '.stylex-tools/state'),+});++export const digestFile = async (file: string) => {+ const hash = createHash('sha256');+ for await (const chunk of createReadStream(file)) hash.update(chunk);+ return hash.digest('hex');+};++/** Canonical content/links/modes, not mtimes or package-manager bookkeeping. */+export const fingerprintInstalledDependencies = async (directory: string) => {+ const root = await realpath(directory);+ const hash = createHash('sha256');+ const rawHash = createHash('sha256');+ const normalizations: Array<{ kind: string; path: string; sha256: string }> = [];+ let bytes = 0;+ let files = 0;+ const visit = async (current: string) => {+ const entries = (await readdir(current, { withFileTypes: true })).sort((a, b) =>+ a.name < b.name ? -1 : 1,+ );+ for (const entry of entries) {+ const file = path.join(current, entry.name);+ const relative = path.relative(root, file).split(path.sep).join('/');+ if (entry.isDirectory()) await visit(file);+ else if (entry.isSymbolicLink()) {+ const target = await realpath(file);+ if (!target.startsWith(root + path.sep))+ throw new Error(`DEPENDENCY_LINK_ESCAPE:${relative}`);+ const evidence = JSON.stringify([relative, 'link', await readlink(file)]);+ hash.update(evidence);+ rawHash.update(evidence);+ files++;+ } else if (entry.isFile()) {+ const stat = await lstat(file);+ bytes += stat.size;+ files++;+ if (files > 1_000_000 || bytes > 16 * 1024 ** 3)+ throw new Error('DEPENDENCY_CONTENT_BUDGET_EXCEEDED');+ const digest = await digestFile(file);+ rawHash.update(JSON.stringify([relative, stat.mode & 0o111, stat.size, digest]));+ if (+ current === path.join(root, 'node_modules') &&+ ['.modules.yaml', '.pnpm-workspace-state-v1.json'].includes(entry.name)+ ) {+ normalizations.push({+ kind: 'pnpm-install-location-metadata',+ path: relative,+ sha256: digest,+ });+ continue;+ }+ let portableDigest = digest;+ let portableSize = stat.size;+ if (relative.includes('node_modules/.bin/') && stat.size < 1024 ** 2) {+ const launcher = await readFile(file, 'utf8');+ const target = launcher.match(/\n# cmd-shim-target=(.+)\n*$/)?.[1];+ if (launcher.startsWith('#!/bin/sh\n# Resolve $0 through symlinks') && target) {+ const resolvedTarget = await realpath(target);+ if (!resolvedTarget.startsWith(root + path.sep))+ throw new Error('DEPENDENCY_LAUNCHER_ESCAPE');+ let portable = launcher;+ for (const prefix of new Set([root, directory]))+ portable = portable.replaceAll(prefix + path.sep, '<snapshot>/');+ portableDigest = sha256(portable);+ portableSize = Buffer.byteLength(portable);+ normalizations.push({+ kind: 'pnpm-generated-launcher-location',+ path: relative,+ sha256: digest,+ });+ }+ }+ hash.update(JSON.stringify([relative, stat.mode & 0o111, portableSize, portableDigest]));+ } else throw new Error('DEPENDENCY_FILE_MODE_UNSUPPORTED');+ }+ };+ await visit(path.join(root, 'node_modules'));+ return {+ bytes,+ files,+ normalizations,+ rawSha256: rawHash.digest('hex'),+ sha256: hash.digest('hex'),+ };+};++export const validateDependencyLock = (text: string) => {+ const documents = parseAllDocuments(text);+ if (!documents.length || documents.some((document) => document.errors.length))+ throw new Error('INVALID_DEPENDENCY_LOCK');+ const values = documents.map((document) => record.parse(document.toJS()));+ const graph = values.find((value) => value.importers !== undefined);+ if (!graph || !graph.lockfileVersion) throw new Error('DEPENDENCY_LOCK_GRAPH_MISSING');+ const importers = record.parse(graph.importers);+ if (!Object.keys(importers).length || !importers['.'])+ throw new Error('DEPENDENCY_IMPORTERS_MISSING');+ const packages = record.parse(graph.packages ?? {});+ for (const [name, value] of Object.entries(packages)) {+ const resolution = z.object({ resolution: record }).parse(value).resolution;+ if (+ typeof resolution.integrity !== 'string' ||+ !/^sha512-[A-Za-z0-9+/]{86}==$/.test(resolution.integrity)+ )+ throw new Error(`DEPENDENCY_INTEGRITY_MISSING:${name}`);+ if (+ resolution.tarball !== undefined &&+ (typeof resolution.tarball !== 'string' ||+ !resolution.tarball.startsWith('https://registry.npmjs.org/'))+ )+ throw new Error(`DEPENDENCY_REGISTRY_UNSUPPORTED:${name}`);+ }+ return {+ importers: Object.keys(importers).sort(),+ packageCount: Object.keys(packages).length,+ sha256: sha256(text),+ };+};++const validateSpecifier = (value: string, context: string) => {+ const range = value.startsWith('workspace:')+ ? value.slice('workspace:'.length)+ : value.startsWith('npm:')+ ? value.match(/^npm:(?:@[^/]+\/[^@]+|[^@]+)@(.+)$/)?.[1]+ : value;+ if (+ !range ||+ (!validRange(range) && !(value.startsWith('workspace:') && ['^', '~'].includes(range)))+ )+ throw new Error(`DEPENDENCY_PROTOCOL_UNSUPPORTED:${context}`);+};++const checkInstallConfiguration = async (directory: string, inputs: string[]) => {+ for (const file of inputs) {+ if (path.basename(file) === 'package.json') {+ const manifest = record.parse(JSON.parse(await readFile(path.join(directory, file), 'utf8')));+ if (manifest.pnpm !== undefined)+ throw new Error('DEPENDENCY_ROOT_PNPM_CONFIG_REQUIRES_REVIEW');+ for (const [name, value] of Object.entries(+ z.record(z.string(), z.string()).parse(manifest.overrides ?? {}),+ ))+ validateSpecifier(value, `${file}:overrides:${name}`);+ for (const field of [+ 'dependencies',+ 'devDependencies',+ 'optionalDependencies',+ 'peerDependencies',+ ]) {+ if (manifest[field] === undefined) continue;+ for (const [name, value] of Object.entries(+ z.record(z.string(), z.string()).parse(manifest[field]),+ )) {+ validateSpecifier(value, `${file}:${name}`);+ }+ }+ }+ if (path.basename(file) === '.npmrc') {+ const text = await readFile(path.join(directory, file), 'utf8');+ if (text.split('\n').some((line) => line.trim() && !/^[#;]/.test(line.trim())))+ throw new Error('DEPENDENCY_NPMRC_REQUIRES_REVIEW');+ }+ }+ const config = record.parse(+ parse(await readFile(path.join(directory, 'pnpm-workspace.yaml'), 'utf8')),+ );+ for (const key of [+ 'configDependencies',+ 'hooks',+ 'globalPnpmfile',+ 'pnpmfile',+ 'registries',+ 'pnpr',+ 'catalogs',+ ])+ if (config[key] !== undefined) throw new Error(`DEPENDENCY_CONFIG_UNSUPPORTED:${key}`);+ for (const [name, value] of Object.entries(+ z.record(z.string(), z.string()).parse(config.overrides ?? {}),+ ))+ validateSpecifier(value, `overrides:${name}`);+ if (config.packageExtensions !== undefined)+ throw new Error('DEPENDENCY_CONFIG_UNSUPPORTED:packageExtensions');+ for (const value of Object.values(+ z.record(z.string(), z.string()).parse(config.patchedDependencies ?? {}),+ )) {+ if (+ path.isAbsolute(value) ||+ value.includes('\\') ||+ value.split('/').includes('..') ||+ !(await realpath(path.join(directory, value))).startsWith(+ (await realpath(directory)) + path.sep,+ )+ )+ throw new Error('DEPENDENCY_PATCH_ESCAPE');+ }+};++export const dependencyInputFingerprint = async (directory: string, inputs: string[]) => {+ const hash = createHash('sha256');+ for (const file of [...inputs].sort())+ hash+ .update(file)+ .update('\0')+ .update(await readFile(path.join(directory, file)))+ .update('\0');+ return hash.digest('hex');+};++/** Only invoked in an owned exported tree; never in the user's checkout. */+export const restoreDependencies = async (+ directory: string,+ inputs: string[],+ options: DependencyOptions,+ frozenLock?: string,+) => {+ const started = performance.now();+ if ((await readdir(directory)).includes('node_modules'))+ throw new Error('DEPENDENCY_TARGET_NOT_CLEAN');+ await checkInstallConfiguration(directory, inputs);+ const inputHash = await dependencyInputFingerprint(directory, inputs);+ const manifest = manifestSchema.parse(+ JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8')),+ );+ const declaredVersion = manifest.packageManager?.match(+ /^pnpm@(\d+\.\d+\.\d+)(?:\+sha512\.[\da-f]+)?$/,+ )?.[1];+ if (!declaredVersion) throw new Error('EXACT_PNPM_VERSION_REQUIRED');+ if (declaredVersion !== supportedPnpmVersion) throw new Error('PNPM_ADAPTER_VERSION_UNSUPPORTED');+ const env: NodeJS.ProcessEnv = { ...childEnvironment(directory), NODE_ENV: 'development' };+ await mkdir(path.join(directory, '.stylex-tools'));+ await mkdir(env.TMPDIR!, { recursive: true });+ const { stdout } = await execute(options.pnpm, ['--version'], {+ cwd: directory,+ env,+ timeout: 15_000,+ });+ if (stdout.trim() !== declaredVersion) throw new Error('PNPM_VERSION_MISMATCH');+ const common = [+ '--config.pm-on-fail=ignore',+ '--ignore-scripts',+ '--ignore-pnpmfile',+ '--no-runtime',+ '--node-linker=isolated',+ '--config.enable-global-virtual-store=false',+ '--config.virtual-store-dir=node_modules/.pnpm',+ '--config.modules-dir=node_modules',+ '--config.lockfile-dir=' + directory,+ '--config.package-import-method=copy',+ '--config.verify-store-integrity=true',+ '--config.side-effects-cache=false',+ '--config.enable-pre-post-scripts=false',+ '--config.cache-dir=' + path.join(directory, '.stylex-tools/cache'),+ '--userconfig=/dev/null',+ '--registry=https://registry.npmjs.org',+ '--store-dir=' + options.store,+ '--lockfile=true',+ '--reporter=append-only',+ ];+ const invoke = async (stage: string, args: string[]) => {+ const result = await new Promise<{ code: number; stderr: string; stdout: string }>(+ (resolve, reject) => {+ execFile(+ options.pnpm,+ ['install', ...common, ...args],+ { cwd: directory, env, maxBuffer: 8 * 1024 ** 2, timeout: 300_000 },+ (error, stdout, stderr) => {+ if (!error) resolve({ code: 0, stderr, stdout });+ else if (typeof error.code === 'number') resolve({ code: error.code, stderr, stdout });+ else reject(error);+ },+ );+ },+ );+ await writeFile(+ path.join(directory, `.stylex-tools/${stage}.log`),+ result.stdout + result.stderr,+ { flag: 'wx' },+ );+ if (result.code)+ throw new Error(+ `DEPENDENCY_${stage.toUpperCase()}_FAILED: exit ${result.code}; see .stylex-tools/${stage}.log`,+ );+ };+ if (frozenLock !== undefined) {+ if (inputs.includes('pnpm-lock.yaml')) {+ if ((await readFile(path.join(directory, 'pnpm-lock.yaml'), 'utf8')) !== frozenLock)+ throw new Error('DEPENDENCY_LOCK_CONFLICT');+ } else await writeFile(path.join(directory, 'pnpm-lock.yaml'), frozenLock, { flag: 'wx' });+ } else+ await invoke('resolve', [+ '--lockfile-only',+ '--no-frozen-lockfile',+ ...(options.allowNetwork ? [] : ['--offline']),+ ]);+ const lock = await readFile(path.join(directory, 'pnpm-lock.yaml'), 'utf8');+ const graph = validateDependencyLock(lock);+ // Resolution can use the public registry only in the explicit fetch phase.+ if (options.allowNetwork) await invoke('fetch', ['--frozen-lockfile']);+ await invoke('restore', ['--offline', '--frozen-lockfile', '--frozen-store']);+ if (+ (await dependencyInputFingerprint(directory, inputs)) !== inputHash ||+ sha256(await readFile(path.join(directory, 'pnpm-lock.yaml'))) !== graph.sha256+ )+ throw new Error('DEPENDENCY_INPUT_DRIFT');+ const content = await fingerprintInstalledDependencies(directory);+ const result = {+ content,+ durationMs: performance.now() - started,+ graph,+ instanceHash: sha256(+ JSON.stringify({ content: content.rawSha256, inputHash, lock: graph.sha256 }),+ ),+ inputHash,+ lockHash: graph.sha256,+ node: process.version,+ pnpmVersion: declaredVersion,+ runtimePolicy: 'fixed-controller-node-no-provisioning',+ schemaVersion: 1 as const,+ snapshotHash: sha256(+ JSON.stringify({+ content: content.sha256,+ inputHash,+ lock: graph.sha256,+ node: process.version,+ pnpm: declaredVersion,+ }),+ ),+ status: 'RESTORED' as const,+ };+ await writeJson(directory, '.stylex-tools/dependency-snapshot.json', result);+ return { lock, snapshot: result };+};diff --git a/scripts/stylexMigration/verification/dependencies/fixtureDependencies.test.ts b/scripts/stylexMigration/verification/dependencies/fixtureDependencies.test.tsnew file mode 100644index 00000000000..ee37762fba9--- /dev/null+++ b/scripts/stylexMigration/verification/dependencies/fixtureDependencies.test.ts@@ -0,0 +1,128 @@+// @vitest-environment node+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, expect, it } from 'vitest';+import { parse } from 'yaml';++import { prepareFixtureDependencies } from './fixtureDependencies';++const owned: string[] = [];+afterEach(async () => {+ for (const root of owned.splice(0)) await rm(root, { force: true, recursive: true });+});++const fixture = async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-capsule-test-'));+ owned.push(root);+ const dependencies = Object.fromEntries(+ [+ '@lobehub/ui',+ '@rolldown/plugin-transform-imports',+ '@stylexjs/stylex',+ '@stylexjs/unplugin',+ '@vitejs/plugin-react',+ 'motion',+ 'i18next',+ 'react',+ 'react-dom',+ 'react-i18next',+ 'vite',+ ].map((name) => [name, '1.0.0']),+ );+ await writeFile(+ path.join(root, 'package.json'),+ JSON.stringify({+ dependencies,+ packageManager: '[email protected]',+ }),+ );+ await writeFile(+ path.join(root, 'pnpm-workspace.yaml'),+ 'packages: [packages/*]\noverrides: {react: 1.0.0}\npatchedDependencies: {react: patches/react.patch}\n',+ );+ await mkdir(path.join(root, 'patches'));+ await writeFile(path.join(root, 'patches/react.patch'), 'reviewed patch');+ await mkdir(path.join(root, 'packages/unrelated'), { recursive: true });+ await writeFile(+ path.join(root, 'packages/unrelated/package.json'),+ JSON.stringify({ dependencies: { xlsx: 'https://example.invalid/unrelated.tgz' } }),+ );+ return root;+};+const inputs = [+ 'package.json',+ 'pnpm-workspace.yaml',+ 'patches/react.patch',+ 'packages/unrelated/package.json',+];++it('preserves source inputs and resolution policy, excludes unrelated importers and records the peer-context gap', async () => {+ const root = await fixture();+ const original = await readFile(path.join(root, 'package.json'), 'utf8');+ const result = await prepareFixtureDependencies(root, inputs, 'LiteTable');+ const config = parse(await readFile(path.join(result.directory, 'pnpm-workspace.yaml'), 'utf8'));+ expect(config).toMatchObject({ overrides: { react: '1.0.0' }, packages: ['.'] });+ expect(await readFile(path.join(result.directory, 'patches/react.patch'), 'utf8')).toBe(+ 'reviewed patch',+ );+ expect(result.evidence.reasonCodes).toContain('FIXTURE_CAPSULE_WORKSPACE_PEER_CONTEXT_UNPROVEN');+ expect(result.evidence.gateEligible).toBe(false);+ expect(await readFile(path.join(root, 'package.json'), 'utf8')).toBe(original);+ const second = await fixture();+ expect((await prepareFixtureDependencies(second, inputs, 'LiteTable')).hash).toBe(result.hash);+});++it('does not silently discard root package-manager config', async () => {+ const root = await fixture();+ const manifest = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));+ manifest.pnpm = { hooks: {} };+ await writeFile(path.join(root, 'package.json'), JSON.stringify(manifest));+ await expect(prepareFixtureDependencies(root, inputs, 'LiteTable')).rejects.toThrow(+ 'ROOT_PNPM_CONFIG',+ );+});++it('unions only selected fixture roots and preserves source versions deterministically', async () => {+ const single = await fixture();+ const singleResult = await prepareFixtureDependencies(single, inputs, 'LiteTable');+ expect(Object.keys(singleResult.evidence.roots)).toHaveLength(9);+ const first = await fixture();+ const result = await prepareFixtureDependencies(first, inputs, ['StatusBar', 'DotsLoading']);+ expect(result.evidence.fixtureIds).toEqual(['DotsLoading', 'StatusBar']);+ expect(result.evidence.roots.i18next).toBe('1.0.0');+ expect(result.evidence.roots['react-i18next']).toBe('1.0.0');+ expect(Object.keys(result.evidence.roots)).toHaveLength(11);+ const second = await fixture();+ expect(+ (await prepareFixtureDependencies(second, inputs, ['DotsLoading', 'StatusBar'])).hash,+ ).toBe(result.hash);+});++it('rejects empty, duplicate or undeclared dependency selections', async () => {+ const root = await fixture();+ await expect(prepareFixtureDependencies(root, inputs, [])).rejects.toThrow(+ 'INVALID_FIXTURE_SELECTION',+ );+ await expect(+ prepareFixtureDependencies(root, inputs, ['LiteTable', 'LiteTable']),+ ).rejects.toThrow('INVALID_FIXTURE_SELECTION');+ await expect(+ prepareFixtureDependencies(root, inputs, ['DotsLoading', 'OptionCard']),+ ).rejects.toThrow('FIXTURE_DEPENDENCY_DECLARATION_MISSING:lucide-react');+});++it('rejects unknown adapters and patches escaping the exported tree', async () => {+ const root = await fixture();+ await expect(prepareFixtureDependencies(root, inputs, 'Other')).rejects.toThrow(+ 'ADAPTER_UNAVAILABLE',+ );+ await writeFile(+ path.join(root, 'pnpm-workspace.yaml'),+ 'patchedDependencies: {react: ../outside.patch}\n',+ );+ await expect(prepareFixtureDependencies(root, inputs, 'LiteTable')).rejects.toThrow(+ 'PATCH_ESCAPE',+ );+});diff --git a/scripts/stylexMigration/verification/dependencies/fixtureDependencies.ts b/scripts/stylexMigration/verification/dependencies/fixtureDependencies.tsnew file mode 100644index 00000000000..b019064e36b--- /dev/null+++ b/scripts/stylexMigration/verification/dependencies/fixtureDependencies.ts@@ -0,0 +1,129 @@+import { mkdir, readFile, realpath, symlink, writeFile } from 'node:fs/promises';+import path from 'node:path';++import { parse, stringify } from 'yaml';+import { z } from 'zod';++import { getStyleFixture } from '../fixtures/fixtureRegistry';+import { sha256, writeJson } from '../reporting/report';+import { dependencyInputFingerprint } from './dependencySnapshot';++// Reviewed direct imports of the shared host and its compiler closure. This+// is an advisory capsule, NOT a proof of the production workspace peer graph.+const hostRoots = [+ '@lobehub/ui',+ '@rolldown/plugin-transform-imports',+ '@stylexjs/stylex',+ '@stylexjs/unplugin',+ '@vitejs/plugin-react',+ 'motion',+ 'react',+ 'react-dom',+ 'vite',+] as const;++const manifestSchema = z.object({+ dependencies: z.record(z.string(), z.string()).default({}),+ devDependencies: z.record(z.string(), z.string()).default({}),+ overrides: z.record(z.string(), z.string()).optional(),+ packageManager: z.string(),+ pnpm: z.unknown().optional(),+});++/** Never edits source manifests; installation lives inside the owned export. */+export const prepareFixtureDependencies = async (+ directory: string,+ inputs: string[],+ fixtureId: string | string[],+) => {+ const fixtureIds = (typeof fixtureId === 'string' ? [fixtureId] : [...fixtureId]).sort();+ if (!fixtureIds.length || new Set(fixtureIds).size !== fixtureIds.length)+ throw new Error('INVALID_FIXTURE_SELECTION');+ const fixtures = fixtureIds.map(getStyleFixture);+ const root = await realpath(directory);+ const manifest = manifestSchema.parse(+ JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')),+ );+ // Do not silently drop executable package-manager configuration.+ if (manifest.pnpm !== undefined) throw new Error('FIXTURE_ROOT_PNPM_CONFIG_REQUIRES_REVIEW');+ const available = { ...manifest.devDependencies, ...manifest.dependencies };+ const dependencies: Record<string, string> = {};+ const roots = [+ ...new Set([...hostRoots, ...fixtures.flatMap((fixture) => fixture.dependencyRoots)]),+ ].sort();+ for (const name of roots) {+ const specifier = available[name];+ if (!specifier || specifier.startsWith('workspace:'))+ throw new Error(`FIXTURE_DEPENDENCY_DECLARATION_MISSING:${name}`);+ dependencies[name] = specifier;+ }+ const workspace = z+ .record(z.string(), z.unknown())+ .parse(parse(await readFile(path.join(root, 'pnpm-workspace.yaml'), 'utf8')));+ const capsule = path.join(root, '.stylex-dependencies');+ await mkdir(capsule);+ const capsuleInputs = ['package.json', 'pnpm-workspace.yaml'];+ await writeFile(+ path.join(capsule, 'package.json'),+ JSON.stringify({+ dependencies,+ name: 'stylex-fixture-dependency-capsule',+ overrides: manifest.overrides,+ packageManager: manifest.packageManager,+ private: true,+ }),+ { flag: 'wx' },+ );+ await writeFile(+ path.join(capsule, 'pnpm-workspace.yaml'),+ stringify({+ ...workspace,+ // Preserve dependency resolution/overrides/patch semantics, but not the+ // unrelated workspace importers. Missing workspace imports fail closed.+ allowUnusedPatches: true,+ packages: ['.'],+ }),+ { flag: 'wx' },+ );+ for (const input of inputs.filter((file) => path.basename(file) === '.npmrc')) {+ const config = await readFile(path.join(root, input), 'utf8');+ if (config.split('\n').some((line) => line.trim() && !/^[#;]/.test(line.trim())))+ throw new Error('DEPENDENCY_NPMRC_REQUIRES_REVIEW');+ }+ const patches = z.record(z.string(), z.string()).parse(workspace.patchedDependencies ?? {});+ for (const patch of new Set(Object.values(patches))) {+ if (path.isAbsolute(patch) || patch.includes('\\') || patch.split('/').includes('..'))+ throw new Error('DEPENDENCY_PATCH_ESCAPE');+ const source = await realpath(path.join(root, patch));+ if (!source.startsWith(root + path.sep)) throw new Error('DEPENDENCY_PATCH_ESCAPE');+ const target = path.join(capsule, patch);+ await mkdir(path.dirname(target), { recursive: true });+ await writeFile(target, await readFile(source), { flag: 'wx' });+ capsuleInputs.push(patch);+ }+ const evidence = {+ fixtureId: fixtureIds.length === 1 ? fixtureIds[0] : undefined,+ fixtureIds,+ gateEligible: false,+ policy: 'reviewed-fixture-roots-v2',+ reasonCodes: ['FIXTURE_CAPSULE_WORKSPACE_PEER_CONTEXT_UNPROVEN'],+ roots: dependencies,+ sourceDependencyInputHash: await dependencyInputFingerprint(root, inputs),+ schemaVersion: 1,+ };+ await writeJson(capsule, 'capsule.json', evidence);+ return {+ directory: capsule,+ evidence,+ hash: sha256(JSON.stringify(evidence)),+ inputs: [...capsuleInputs, 'capsule.json'],+ };+};++export const mountFixtureDependencies = async (directory: string) => {+ const root = await realpath(directory);+ const modules = await realpath(path.join(root, '.stylex-dependencies/node_modules'));+ if (!modules.startsWith(root + path.sep)) throw new Error('FIXTURE_DEPENDENCY_MOUNT_ESCAPE');+ await symlink('.stylex-dependencies/node_modules', path.join(root, 'node_modules'));+ await mkdir(path.join(root, '.stylex-tools'));+};diff --git a/scripts/stylexMigration/verification/fixtures/CollapsibleContentFixture.tsx b/scripts/stylexMigration/verification/fixtures/CollapsibleContentFixture.tsxnew file mode 100644index 00000000000..57382e2b46b--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/CollapsibleContentFixture.tsx@@ -0,0 +1,20 @@+import { CollapsibleContent } from 'verification:component';++import { FixtureI18n } from './FixtureI18n';++const lines = Array.from(+ { length: 20 },+ (_, index) => `Line ${index + 1}: deterministic component content.`,+);++export const Fixture = ({ variant }: { variant: string }) => (+ <FixtureI18n>+ <CollapsibleContent+ collapsed={variant !== 'expanded'}+ maxHeight={100}+ onCollapsedChange={() => {}}+ >+ {variant === 'short' ? <p>Short content</p> : lines.map((line) => <p key={line}>{line}</p>)}+ </CollapsibleContent>+ </FixtureI18n>+);diff --git a/scripts/stylexMigration/verification/fixtures/CommandLineFixture.tsx b/scripts/stylexMigration/verification/fixtures/CommandLineFixture.tsxnew file mode 100644index 00000000000..3f03d518f68--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/CommandLineFixture.tsx@@ -0,0 +1,11 @@+import { CommandLine } from 'verification:component';++export const Fixture = ({ variant }: { variant: string }) => (+ <CommandLine+ command={+ variant === 'long'+ ? 'node ./scripts/a-long-deterministic-command-name/verify-component-styles --all-components --offline --compare-computed-properties'+ : 'node verify-styles.mjs'+ }+ />+);diff --git a/scripts/stylexMigration/verification/fixtures/DotsLoadingFixture.tsx b/scripts/stylexMigration/verification/fixtures/DotsLoadingFixture.tsxnew file mode 100644index 00000000000..20468854a0d--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/DotsLoadingFixture.tsx@@ -0,0 +1,4 @@+import { DotsLoading } from 'verification:component';++export const Fixture = ({ variant }: { variant: string }) =>+ variant === 'custom' ? <DotsLoading color="#345678" gap={6} size={8} /> : <DotsLoading />;diff --git a/scripts/stylexMigration/verification/fixtures/FilePathDisplayFixture.tsx b/scripts/stylexMigration/verification/fixtures/FilePathDisplayFixture.tsxnew file mode 100644index 00000000000..4420a96b077--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/FilePathDisplayFixture.tsx@@ -0,0 +1,16 @@+import { FilePathDisplay } from 'verification:component';++export const Fixture = ({ variant }: { variant: string }) => (+ <div style={{ alignItems: 'center', display: 'flex' }}>+ <FilePathDisplay+ isDirectory={variant === 'directory'}+ filePath={+ variant === 'image'+ ? '/project/images/example.png'+ : variant === 'directory'+ ? '/project/components'+ : '/project/src/example.tsx'+ }+ />+ </div>+);diff --git a/scripts/stylexMigration/verification/fixtures/FixtureHost.tsx b/scripts/stylexMigration/verification/fixtures/FixtureHost.tsxnew file mode 100644index 00000000000..680820e8579--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/FixtureHost.tsx@@ -0,0 +1,46 @@+import '@lobehub/ui/theme.css';+import '@lobehub/ui/global.css';+import '@lobehub/ui/style.css';+import '@/styles/stylex.css';++import { ConfigProvider } from '@lobehub/ui';+import * as motion from 'motion/react-m';+import { type ComponentType, useLayoutEffect } from 'react';+import { createRoot } from 'react-dom/client';++const Ready = () => {+ useLayoutEffect(() => {+ document.getElementById('app')?.setAttribute('data-verification-ready', 'true');+ }, []);+ return null;+};++/** This identical module is copied and built independently inside B and M. */+export const startFixture = (+ Fixture: ComponentType<{ variant: string }>,+ variants: string[],+ containerMode: 'component-root' | 'fixture-wrapper',+) => {+ const root = document.getElementById('app');+ if (!root) throw new Error('FIXTURE_ROOT_MISSING');+ const variant = new URL(location.href).searchParams.get('variant') ?? variants[0];+ if (!variants.includes(variant)) throw new Error('UNKNOWN_STYLE_VARIANT');+ document.body.style.margin = '0';+ document.body.style.fontFamily = 'Arial, sans-serif';+ createRoot(root).render(+ <ConfigProvider enableCustomFonts={false} motion={motion}>+ <main data-case-root data-verification-host style={{ padding: 16, width: 920 }}>+ <div data-component-mount>+ {containerMode === 'component-root' ? (+ <Fixture variant={variant} />+ ) : (+ <div>+ <Fixture variant={variant} />+ </div>+ )}+ </div>+ </main>+ <Ready />+ </ConfigProvider>,+ );+};diff --git a/scripts/stylexMigration/verification/fixtures/FixtureI18n.tsx b/scripts/stylexMigration/verification/fixtures/FixtureI18n.tsxnew file mode 100644index 00000000000..0034e4512ed--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/FixtureI18n.tsx@@ -0,0 +1,26 @@+import { createInstance } from 'i18next';+import type { ReactNode } from 'react';+import { I18nextProvider } from 'react-i18next';+import chat from 'verification:locale/chat';+import components from 'verification:locale/components';++const instance = createInstance();+void instance+ .init({+ fallbackLng: 'en-US',+ initImmediate: false,+ interpolation: { escapeValue: false },+ keySeparator: false,+ lng: 'en-US',+ react: { useSuspense: false },+ resources: { 'en-US': { chat, components } },+ })+ .catch((error) => {+ console.error(error);+ throw error;+ });++/** Actual locale modules from each source snapshot; no mocked translation hook. */+export const FixtureI18n = ({ children }: { children: ReactNode }) => (+ <I18nextProvider i18n={instance}>{children}</I18nextProvider>+);diff --git a/scripts/stylexMigration/verification/fixtures/GalleyGridFixture.tsx b/scripts/stylexMigration/verification/fixtures/GalleyGridFixture.tsxnew file mode 100644index 00000000000..0392a5b5a64--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/GalleyGridFixture.tsx@@ -0,0 +1,17 @@+import { GalleyGrid } from 'verification:component';++const items = ['one', 'two', 'three', 'four', 'five', 'six'];++export const Fixture = ({ variant }: { variant: string }) => (+ <GalleyGrid+ col={variant === 'single' ? 1 : variant === 'compact' ? 2 : 3}+ gap={variant === 'compact' ? 2 : 6}+ max={420}+ >+ {items.map((item) => (+ <div key={item} style={{ background: '#8cb4ff', height: 80 }}>+ {item}+ </div>+ ))}+ </GalleyGrid>+);diff --git a/scripts/stylexMigration/verification/fixtures/GeneratingBorderFixture.tsx b/scripts/stylexMigration/verification/fixtures/GeneratingBorderFixture.tsxnew file mode 100644index 00000000000..2dd1c327751--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/GeneratingBorderFixture.tsx@@ -0,0 +1,7 @@+import { GeneratingBorder } from 'verification:component';++export const Fixture = ({ variant }: { variant: string }) => (+ <GeneratingBorder generating={variant === 'generating'}>+ <div style={{ height: 80, padding: 12 }}>Writing deterministic content</div>+ </GeneratingBorder>+);diff --git a/scripts/stylexMigration/verification/fixtures/InlineTableFixture.tsx b/scripts/stylexMigration/verification/fixtures/InlineTableFixture.tsxnew file mode 100644index 00000000000..125d130c770--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/InlineTableFixture.tsx@@ -0,0 +1,19 @@+import { InlineTable } from 'verification:component';++const rows = [+ { id: 'one', name: 'First row', status: 'Ready' },+ { id: 'two', name: 'Second row', status: 'Pending' },+];+const columns = [+ { dataIndex: 'name', key: 'name', title: 'Name' },+ { dataIndex: 'status', key: 'status', title: 'Status' },+];++export const Fixture = ({ variant }: { variant: string }) => (+ <InlineTable+ columns={columns}+ dataSource={variant === 'empty' ? [] : rows}+ hoverToActive={variant === 'hoverable'}+ rowKey="id"+ />+);diff --git a/scripts/stylexMigration/verification/fixtures/LiteTableFixture.tsx b/scripts/stylexMigration/verification/fixtures/LiteTableFixture.tsxnew file mode 100644index 00000000000..061f3f1c462--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/LiteTableFixture.tsx@@ -0,0 +1,33 @@+import { LiteTable } from 'verification:component';++const rows = [+ { id: 'one', name: 'A deterministic first row', status: 'Ready' },+ { id: 'two', name: 'A second row with a longer title', status: 'Pending' },+];++export const Fixture = ({ variant }: { variant: string }) => (+ <LiteTable+ dataSource={variant === 'empty' || variant === 'loading' ? [] : rows}+ emptyText={<span>No rows</span>}+ listBreakpoint={variant === 'wide' ? 800 : 600}+ loading={variant === 'loading'}+ rowKey={(row: (typeof rows)[number]) => row.id}+ tableLayout={variant === 'fixed' ? 'fixed' : 'auto'}+ columns={[+ {+ key: 'name',+ listSlot: 'title',+ render: (row: (typeof rows)[number]) => row.name,+ title: 'Name',+ },+ { key: 'status', render: (row: (typeof rows)[number]) => row.status, title: 'Status' },+ {+ key: 'actions',+ listSlot: 'actions',+ render: () => <button type="button">Open</button>,+ title: 'Actions',+ },+ ]}+ onRowClick={() => {}}+ />+);diff --git a/scripts/stylexMigration/verification/fixtures/MenuFixture.tsx b/scripts/stylexMigration/verification/fixtures/MenuFixture.tsxnew file mode 100644index 00000000000..be8e4cc3f20--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/MenuFixture.tsx@@ -0,0 +1,20 @@+import { Menu } from 'verification:component';++const items = [+ { key: 'first', label: 'First item' },+ { key: 'divider', type: 'divider' as const },+ { disabled: true, key: 'disabled', label: 'Disabled item' },+ { key: 'last', label: 'A longer menu label with trailing content', extra: 'Extra' },+];++export const Fixture = ({ variant }: { variant: string }) => (+ <Menu+ activeKey={variant === 'selectable' ? 'first' : undefined}+ compact={variant === 'compact'}+ items={items}+ selectable={variant === 'selectable'}+ styles={+ variant === 'custom' ? { item: { marginInline: 12, color: 'rgb(80, 90, 100)' } } : undefined+ }+ />+);diff --git a/scripts/stylexMigration/verification/fixtures/OptionCardFixture.tsx b/scripts/stylexMigration/verification/fixtures/OptionCardFixture.tsxnew file mode 100644index 00000000000..ce4f6c98e81--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/OptionCardFixture.tsx@@ -0,0 +1,14 @@+import { OptionCard } from 'verification:component';++export const Fixture = ({ variant }: { variant: string }) => (+ <OptionCard+ description="Deterministic description"+ disabled={variant === 'disabled'}+ highlighted={variant === 'highlighted'}+ index={1}+ label="Choice"+ recommendedText="Suggested"+ selected={variant === 'selected'}+ onToggle={() => {}}+ />+);diff --git a/scripts/stylexMigration/verification/fixtures/OptionRowFixture.tsx b/scripts/stylexMigration/verification/fixtures/OptionRowFixture.tsxnew file mode 100644index 00000000000..97d007dc95e--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/OptionRowFixture.tsx@@ -0,0 +1,14 @@+import { OptionRow } from 'verification:component';++export const Fixture = ({ variant }: { variant: string }) => (+ <OptionRow+ active={variant === 'active'}+ desc="Deterministic description"+ disabled={variant === 'disabled'}+ extra={<button type="button">Details</button>}+ icon={<span aria-hidden>◎</span>}+ label="Option"+ tag="Local"+ onClick={() => {}}+ />+);diff --git a/scripts/stylexMigration/verification/fixtures/SpendTypeFixture.tsx b/scripts/stylexMigration/verification/fixtures/SpendTypeFixture.tsxnew file mode 100644index 00000000000..9a82182867e--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/SpendTypeFixture.tsx@@ -0,0 +1,14 @@+import { SpendType } from 'verification:component';++const types = [+ 'chat',+ 'embedding',+ 'imageGeneration',+ 'speechRecognition',+ 'textToSpeech',+ 'videoGeneration',+] as const;++export const Fixture = ({ variant }: { variant: string }) => (+ <SpendType type={types.find((type) => type === variant) ?? 'chat'}>Usage type</SpendType>+);diff --git a/scripts/stylexMigration/verification/fixtures/StatusBarFixture.tsx b/scripts/stylexMigration/verification/fixtures/StatusBarFixture.tsxnew file mode 100644index 00000000000..d6defccedf8--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/StatusBarFixture.tsx@@ -0,0 +1,16 @@+import { StatusBar } from 'verification:component';++import { FixtureI18n } from './FixtureI18n';++export const Fixture = ({ variant }: { variant: string }) => (+ <FixtureI18n>+ <StatusBar+ cursor={{ column: 4, line: 12, selectionLength: 8 }}+ indent={{ size: variant === 'tabs' ? 4 : 2, useTabs: variant === 'tabs' }}+ languageLabel="TypeScript"+ lineWrapping={variant === 'wrap'}+ readOnly={variant === 'readonly'}+ onLineWrappingChange={() => {}}+ />+ </FixtureI18n>+);diff --git a/scripts/stylexMigration/verification/fixtures/TailMarqueeFixture.tsx b/scripts/stylexMigration/verification/fixtures/TailMarqueeFixture.tsxnew file mode 100644index 00000000000..be6ee69d8e5--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/TailMarqueeFixture.tsx@@ -0,0 +1,11 @@+import { TailMarquee } from 'verification:component';++export const Fixture = ({ variant }: { variant: string }) => (+ <button style={{ display: 'flex', width: '100%' }} type="button">+ <TailMarquee>+ {variant === 'short'+ ? 'file.tsx'+ : '/project/a-long-deterministic-directory/components/another-long-directory/path-to-a-component/another-long-directory/path-to-a-component/ExampleComponent.tsx'}+ </TailMarquee>+ </button>+);diff --git a/scripts/stylexMigration/verification/fixtures/UnreadDotFixture.tsx b/scripts/stylexMigration/verification/fixtures/UnreadDotFixture.tsxnew file mode 100644index 00000000000..aa3297a820f--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/UnreadDotFixture.tsx@@ -0,0 +1,3 @@+import { UnreadDot } from 'verification:component';++export const Fixture = () => <UnreadDot label="Unread" />;diff --git a/scripts/stylexMigration/verification/fixtures/VersionTagFixture.tsx b/scripts/stylexMigration/verification/fixtures/VersionTagFixture.tsxnew file mode 100644index 00000000000..9939762888e--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/VersionTagFixture.tsx@@ -0,0 +1,3 @@+import { VersionTag } from 'verification:component';++export const Fixture = () => <VersionTag range={['2.0.0', '2.5.1']} />;diff --git a/scripts/stylexMigration/verification/fixtures/fixtureRegistry.test.ts b/scripts/stylexMigration/verification/fixtures/fixtureRegistry.test.tsnew file mode 100644index 00000000000..1d43833266e--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/fixtureRegistry.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest';++import { planFixtureProbes } from '../pipeline/probePlanner';+import { fixtureIds, getStyleFixture, styleFixtureSchema } from './fixtureRegistry';++describe('explicit fixture contract', () => {+ it('declares real versioned entries and does not claim source-unit coverage', () => {+ const fixture = getStyleFixture('LiteTable');+ expect(fixture.component.base.source).toBe('src/components/LiteTable/index.tsx');+ expect(fixture.styleVariants).toHaveLength(5);+ expect(fixture.fontContract.productionFontsVerified).toBe(false);+ expect(fixture.styleVariants.every((variant) => variant.expectedUnits.length === 0)).toBe(true);+ });+ it('rejects arbitrary render paths and unsupported component adapters', () => {+ expect(() =>+ styleFixtureSchema.parse({ ...getStyleFixture('LiteTable'), render: '../escape.tsx' }),+ ).toThrow();+ expect(() => getStyleFixture('Unknown')).toThrow('FIXTURE_ADAPTER_UNAVAILABLE');+ });+ it('plans explicit breakpoint boundaries, RTL, states and all variants within budget', () => {+ const probes = planFixtureProbes(getStyleFixture('LiteTable'));+ expect(probes).toHaveLength(176);+ expect(new Set(probes.map((probe) => probe.id)).size).toBe(176);+ expect(probes).toContainEqual(+ expect.objectContaining({ direction: 'rtl', pseudo: 'hover', variant: 'wide', width: 799 }),+ );+ expect(+ probes.some(+ (probe) => ['loading', 'empty'].includes(probe.variant) && probe.pseudo !== 'default',+ ),+ ).toBe(false);+ });++ it('connects all sixteen entries with explicit mounting and probe contracts', () => {+ expect(fixtureIds).toHaveLength(16);+ for (const id of fixtureIds) {+ const fixture = getStyleFixture(id);+ expect(fixture.component.id).toBe(id);+ expect(fixture.render).toBe(`fixtures/${id}Fixture.tsx`);+ expect(fixture.probeWidths.length).toBeGreaterThan(0);+ const probes = planFixtureProbes(fixture);+ expect(probes.length).toBeGreaterThan(0);+ expect(new Set(probes.map((probe) => probe.id)).size).toBe(probes.length);+ if (!fixture.defaultInteractionSelector)+ expect(probes.every((probe) => probe.pseudo === 'default')).toBe(true);+ for (const variant of fixture.styleVariants)+ expect(probes.some((probe) => probe.variant === variant.id)).toBe(true);+ }+ expect(getStyleFixture('FilePathDisplay').component.base.exportName).toBe('FilePathDisplay');+ expect(getStyleFixture('DotsLoading').containerMode).toBe('fixture-wrapper');+ expect(getStyleFixture('TailMarquee').settleFrames).toBe(2);+ });++ it('does not assign LiteTable states or selectors to other components', () => {+ expect(planFixtureProbes(getStyleFixture('DotsLoading'))).toHaveLength(12);+ expect(getStyleFixture('StatusBar').defaultInteractionSelector).toContain('button');+ expect(getStyleFixture('GeneratingBorder').styleVariants.map((entry) => entry.id)).toEqual([+ 'resting',+ 'generating',+ ]);+ });++ it('rejects ambiguous variants, invalid exports and widths outside the host contract', () => {+ const fixture = getStyleFixture('DotsLoading');+ expect(() =>+ styleFixtureSchema.parse({+ ...fixture,+ styleVariants: [fixture.styleVariants[0], fixture.styleVariants[0]],+ }),+ ).toThrow();+ expect(() =>+ styleFixtureSchema.parse({+ ...fixture,+ component: {+ ...fixture.component,+ base: { ...fixture.component.base, exportName: 'default;invalid()' },+ },+ }),+ ).toThrow();+ expect(() => styleFixtureSchema.parse({ ...fixture, probeWidths: [1] })).toThrow();+ expect(() =>+ styleFixtureSchema.parse({+ ...fixture,+ styleVariants: [{ id: 'normal', expectedUnits: [], states: ['default', 'default'] }],+ }),+ ).toThrow('DUPLICATE_FIXTURE_STATE');+ });+});diff --git a/scripts/stylexMigration/verification/fixtures/fixtureRegistry.ts b/scripts/stylexMigration/verification/fixtures/fixtureRegistry.tsnew file mode 100644index 00000000000..be8ff1d512b--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/fixtureRegistry.ts@@ -0,0 +1,275 @@+import { z } from 'zod';++import type { ScopeInventory } from '../types';++const relativePath = z+ .string()+ .min(1)+ .refine(+ (value) =>+ !value.startsWith('/') &&+ !value.includes('\\') &&+ !value.split('/').some((part) => ['..', '.', ''].includes(part)),+ );+const identifier = z.string().regex(/^[$A-Z_][\w$]*$/i);+const pseudo = z.enum(['default', 'hover', 'focus-visible']);+export const styleFixtureSchema = z+ .strictObject({+ assets: z.array(relativePath),+ component: z.strictObject({+ base: z.strictObject({ exportName: identifier, source: relativePath }),+ candidate: z.strictObject({ exportName: identifier, source: relativePath }),+ id: identifier,+ }),+ containerMode: z.enum(['component-root', 'fixture-wrapper']).default('fixture-wrapper'),+ defaultInteractionSelector: z.string().min(1).optional(),+ dependencyRoots: z.array(z.string().min(1)).default([]),+ host: relativePath,+ fontContract: z.strictObject({+ family: z.literal('Arial, sans-serif'),+ mode: z.literal('system-font-diagnostic'),+ productionFontsVerified: z.literal(false),+ }),+ id: identifier,+ interactionSelectors: z+ .strictObject({+ 'hover': z.string().min(1).optional(),+ 'focus-visible': z.string().min(1).optional(),+ })+ .default({}),+ probeWidths: z.array(z.number().finite().positive()).min(1).max(32).default([320, 600, 920]),+ render: relativePath,+ settleFrames: z.union([z.literal(0), z.literal(2)]).default(0),+ sizeContract: z+ .strictObject({+ host: z.tuple([z.number().finite().nonnegative(), z.number().finite().positive()]),+ viewport: z.tuple([z.number().int().positive(), z.number().int().positive()]),+ })+ .refine(({ host, viewport }) => host[0] < host[1] && viewport[0] < viewport[1])+ .optional(),+ styleVariants: z+ .array(+ z.strictObject({+ expectedUnits: z.array(z.string().min(1)),+ id: z.string().min(1),+ states: z.array(pseudo).min(1).optional(),+ }),+ )+ .min(1),+ surfaces: z+ .array(+ z.strictObject({+ id: z.string().min(1),+ kind: z.enum(['component', 'host', 'portal']),+ selector: z.string().min(1),+ }),+ )+ .min(1),+ })+ .superRefine((fixture, context) => {+ if (+ new Set(fixture.styleVariants.map((variant) => variant.id)).size !==+ fixture.styleVariants.length+ )+ context.addIssue({ code: 'custom', message: 'DUPLICATE_FIXTURE_VARIANT' });+ if (new Set(fixture.probeWidths).size !== fixture.probeWidths.length)+ context.addIssue({ code: 'custom', message: 'DUPLICATE_PROBE_WIDTH' });+ if (+ fixture.sizeContract &&+ fixture.probeWidths.some(+ (width) => width < fixture.sizeContract!.host[0] || width > fixture.sizeContract!.host[1],+ )+ )+ context.addIssue({ code: 'custom', message: 'PROBE_OUTSIDE_HOST_CONTRACT' });+ for (const variant of fixture.styleVariants) {+ if (variant.states && new Set(variant.states).size !== variant.states.length)+ context.addIssue({ code: 'custom', message: 'DUPLICATE_FIXTURE_STATE' });+ for (const state of variant.states ?? ['default'])+ if (+ state !== 'default' &&+ !fixture.defaultInteractionSelector &&+ !fixture.interactionSelectors[state]+ )+ context.addIssue({ code: 'custom', message: 'FIXTURE_INTERACTION_TARGET_REQUIRED' });+ }+ });+export type StyleFixture = z.infer<typeof styleFixtureSchema>;++/** Discovery hints only. An experimental render is not a certified source binding. */+export const experimentalFixtures = [+ ['CollapsibleContent', 'src/components/CollapsibleContent/index.tsx'],+ ['CommandLine', 'src/components/CommandLine/index.tsx'],+ ['DotsLoading', 'src/components/DotsLoading/index.tsx'],+ ['FilePathDisplay', 'packages/shared-tool-ui/src/components/FilePathDisplay.tsx'],+ ['GalleyGrid', 'src/components/GalleyGrid/Grid.tsx'],+ ['GeneratingBorder', 'src/components/GeneratingBorder/index.tsx'],+ ['InlineTable', 'src/components/InlineTable/index.tsx'],+ ['LiteTable', 'src/components/LiteTable/index.tsx'],+ ['Menu', 'src/components/Menu/index.tsx'],+ ['OptionCard', 'packages/shared-tool-ui/src/components/OptionCard.tsx'],+ ['OptionRow', 'src/features/ChatInput/ControlBar/OptionRow.tsx'],+ ['SpendType', 'src/components/SpendType/index.tsx'],+ ['StatusBar', 'src/components/CodeEditorPane/StatusBar.tsx'],+ ['TailMarquee', 'src/components/TailMarquee/index.tsx'],+ ['UnreadDot', 'src/components/UnreadDot/index.tsx'],+ ['VersionTag', 'src/components/ChangelogModal/VersionTag.tsx'],+] as const;++export const fixtureIds = experimentalFixtures.map(([id]) => id);+const interactive = ['default', 'hover', 'focus-visible'] as const;+const profiles: Record<+ string,+ {+ dependencies?: string[];+ i18n?: boolean;+ selector?: string;+ selectors?: { 'hover'?: string; 'focus-visible'?: string };+ settleFrames?: 2;+ variants: Array<{ id: string; states?: readonly (typeof interactive)[number][] }>;+ }+> = {+ CollapsibleContent: {+ dependencies: ['lucide-react', 'i18next', 'react-i18next'],+ i18n: true,+ selector: '[data-component-mount] button',+ settleFrames: 2,+ variants: [+ { id: 'collapsed', states: interactive },+ { id: 'expanded', states: interactive },+ { id: 'short' },+ ],+ },+ CommandLine: { variants: [{ id: 'normal' }, { id: 'long' }] },+ DotsLoading: { variants: [{ id: 'normal' }, { id: 'custom' }] },+ FilePathDisplay: {+ dependencies: ['lucide-react', 'path-browserify-esm'],+ variants: [{ id: 'image' }, { id: 'file' }, { id: 'directory' }],+ },+ GalleyGrid: { variants: [{ id: 'normal' }, { id: 'single' }, { id: 'compact' }] },+ GeneratingBorder: { variants: [{ id: 'resting' }, { id: 'generating' }] },+ InlineTable: {+ selector: '[data-component-mount] tbody tr',+ settleFrames: 2,+ variants: [+ { id: 'normal', states: interactive },+ { id: 'hoverable', states: interactive },+ { id: 'empty' },+ ],+ },+ LiteTable: {+ selector: '[data-component-mount] tbody tr[tabindex]',+ variants: ['normal', 'wide', 'fixed', 'loading', 'empty'].map((id) => ({+ id,+ states: id === 'loading' || id === 'empty' ? ['default'] : interactive,+ })),+ },+ Menu: {+ selector: '[data-component-mount] li:not([role="separator"])',+ variants: ['normal', 'compact', 'selectable', 'custom'].map((id) => ({+ id,+ states: interactive,+ })),+ },+ OptionCard: {+ dependencies: ['lucide-react'],+ selector: '[data-component-mount] [role="option"]',+ variants: [+ { id: 'normal', states: interactive },+ { id: 'selected', states: interactive },+ { id: 'highlighted', states: interactive },+ { id: 'disabled', states: interactive },+ ],+ },+ OptionRow: {+ dependencies: ['lucide-react'],+ selector: '[data-component-mount] > div > div',+ variants: [+ { id: 'normal', states: interactive },+ { id: 'active', states: interactive },+ { id: 'disabled', states: interactive },+ ],+ },+ SpendType: {+ dependencies: ['lucide-react'],+ variants: [+ 'chat',+ 'embedding',+ 'imageGeneration',+ 'speechRecognition',+ 'textToSpeech',+ 'videoGeneration',+ ].map((id) => ({ id })),+ },+ StatusBar: {+ dependencies: ['i18next', 'react-i18next'],+ i18n: true,+ selector: '[data-component-mount] button',+ variants: [+ { id: 'normal', states: interactive },+ { id: 'readonly', states: interactive },+ { id: 'tabs', states: interactive },+ { id: 'wrap', states: interactive },+ ],+ },+ TailMarquee: {+ selector: '[data-component-mount] button',+ selectors: {+ 'hover': '[data-component-mount] button > div',+ 'focus-visible': '[data-component-mount] button',+ },+ settleFrames: 2,+ variants: [+ { id: 'overflow', states: interactive },+ { id: 'short', states: interactive },+ ],+ },+ UnreadDot: { variants: [{ id: 'normal' }] },+ VersionTag: { variants: [{ id: 'normal' }] },+};++export const getStyleFixture = (id: string): StyleFixture => {+ const entry = experimentalFixtures.find(([name]) => name === id);+ const profile = profiles[id];+ if (!entry || !profile) throw new Error(`FIXTURE_ADAPTER_UNAVAILABLE:${id}`);+ const component = { exportName: id === 'FilePathDisplay' ? id : 'default', source: entry[1] };+ return styleFixtureSchema.parse({+ assets: profile.i18n ? ['fixtures/FixtureI18n.tsx'] : [],+ component: { base: component, candidate: component, id },+ containerMode: id === 'LiteTable' ? 'component-root' : 'fixture-wrapper',+ defaultInteractionSelector: profile.selector,+ dependencyRoots: profile.dependencies ?? [],+ fontContract: {+ family: 'Arial, sans-serif',+ mode: 'system-font-diagnostic',+ productionFontsVerified: false,+ },+ host: 'fixtures/FixtureHost.tsx',+ id,+ interactionSelectors: profile.selectors,+ probeWidths: id === 'LiteTable' ? [320, 599, 600, 601, 799, 800, 801, 920] : [320, 600, 920],+ render: `fixtures/${id}Fixture.tsx`,+ settleFrames: profile.settleFrames ?? 0,+ sizeContract: { host: [320, 920], viewport: [320, 1200] },+ styleVariants: profile.variants.map((variant) => ({ ...variant, expectedUnits: [] })),+ surfaces: [+ { id: 'host', kind: 'host', selector: '[data-verification-host]' },+ { id: 'component', kind: 'component', selector: '[data-component-mount] > *' },+ ],+ });+};++export const discoverFixtureCandidates = (scope: ScopeInventory) => {+ const changed = new Set(scope.units.map((unit) => unit.file));+ return {+ candidates: experimentalFixtures+ .filter(([, file]) => changed.has(file))+ .map(([componentId, source]) => ({+ componentId,+ reasonCode: 'FIXTURE_BINDING_NOT_CERTIFIED',+ source,+ })),+ unmappedFiles: [...changed]+ .filter((file) => !experimentalFixtures.some(([, source]) => source === file))+ .sort(),+ };+};diff --git a/scripts/stylexMigration/verification/fixtures/fixtureServer.test.ts b/scripts/stylexMigration/verification/fixtures/fixtureServer.test.tsnew file mode 100644index 00000000000..58e54b97bb7--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/fixtureServer.test.ts@@ -0,0 +1,36 @@+// @vitest-environment node+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import { serveFixtures } from './fixtureServer';++describe('fixture asset boundary', () => {+ it('serves only explicit build roots and refuses symlink escapes', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-server-test-'));+ const base = path.join(root, 'base');+ const candidate = path.join(root, 'candidate');+ await mkdir(base);+ await mkdir(candidate);+ await writeFile(path.join(root, 'outside.txt'), 'must not expose');+ await writeFile(path.join(base, 'index.html'), '<main>base</main>');+ await writeFile(path.join(candidate, 'index.html'), '<main>candidate</main>');+ await symlink(path.join(root, 'outside.txt'), path.join(base, 'escape.txt'));+ const server = await serveFixtures({ base, candidate });+ try {+ expect(await (await fetch(server.origin + '/base/')).text()).toBe('<main>base</main>');+ expect(await (await fetch(server.origin + '/candidate/')).text()).toBe(+ '<main>candidate</main>',+ );+ expect((await fetch(server.origin + '/base/escape.txt')).status).toBe(403);+ expect((await fetch(server.origin + '/base/%2e%2e%2foutside.txt')).status).not.toBe(200);+ expect((await fetch(server.origin + '/unrelated/')).status).toBe(404);+ expect((await fetch(server.origin + '/base/', { method: 'POST' })).status).toBe(404);+ } finally {+ await server.close();+ await rm(root, { force: true, recursive: true });+ }+ });+});diff --git a/scripts/stylexMigration/verification/fixtures/fixtureServer.ts b/scripts/stylexMigration/verification/fixtures/fixtureServer.tsnew file mode 100644index 00000000000..9a5f1f94da3--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/fixtureServer.ts@@ -0,0 +1,56 @@+import { readFile, realpath } from 'node:fs/promises';+import { createServer } from 'node:http';+import path from 'node:path';++const types: Record<string, string> = {+ '.css': 'text/css',+ '.html': 'text/html',+ '.js': 'text/javascript',+ '.svg': 'image/svg+xml',+ '.woff2': 'font/woff2',+};++/** Serves only the two explicit build roots, including realpath checks on assets. */+export const serveFixtures = async (builds: { base: string; candidate: string }) => {+ const roots = { base: await realpath(builds.base), candidate: await realpath(builds.candidate) };+ const server = createServer(async (request, response) => {+ try {+ const url = new URL(request.url ?? '/', 'http://localhost');+ const match = /^\/(base|candidate)\/(.*)$/.exec(url.pathname);+ if (!match || !['GET', 'HEAD'].includes(request.method ?? '')) {+ response.writeHead(404).end();+ return;+ }+ const root = roots[match[1] as keyof typeof roots];+ const file = await realpath(path.resolve(root, decodeURIComponent(match[2] || 'index.html')));+ if (!file.startsWith(root + path.sep)) {+ response.writeHead(403).end();+ return;+ }+ const data = await readFile(file);+ response.writeHead(200, {+ 'Cache-Control': 'no-store',+ 'Content-Type': types[path.extname(file)] ?? 'application/octet-stream',+ 'X-Content-Type-Options': 'nosniff',+ });+ response.end(request.method === 'HEAD' ? undefined : data);+ } catch (error) {+ // Request failures are expected (missing asset, malformed URL, traversal).+ response.writeHead(404).end();+ if (!(error instanceof Error)) console.error(error);+ }+ });+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', resolve);+ });+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('FIXTURE_PORT_UNAVAILABLE');+ return {+ close: () =>+ new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ ),+ origin: `http://127.0.0.1:${address.port}`,+ };+};diff --git a/scripts/stylexMigration/verification/fixtures/host.test.ts b/scripts/stylexMigration/verification/fixtures/host.test.tsnew file mode 100644index 00000000000..04ab8b6df4c--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/host.test.ts@@ -0,0 +1,74 @@+// @vitest-environment node+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterEach, expect, it } from 'vitest';++import { fixtureIds, getStyleFixture } from './fixtureRegistry';+import { prepareFixtureHost } from './host';++const owned: string[] = [];+afterEach(async () => {+ for (const root of owned.splice(0)) await rm(root, { force: true, recursive: true });+});+const setup = async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'stylex-host-test-'));+ owned.push(root);+ await mkdir(path.join(root, '.stylex-tools'));+ return root;+};+const sourceDirectory = fileURLToPath(new URL('../', import.meta.url));++it('prepares all registered hosts independently and hashes actual verifier inputs', async () => {+ const root = await setup();+ for (const id of fixtureIds) {+ const fixture = getStyleFixture(id);+ const result = await prepareFixtureHost(root, sourceDirectory, fixture, 'base');+ expect(result.relativeTools).toBe(`.stylex-tools/fixtures/${id}`);+ expect(result.fixtureHashes[fixture.host]).toMatch(/^[a-f0-9]{64}$/);+ expect(result.fixtureHashes[fixture.render]).toMatch(/^[a-f0-9]{64}$/);+ const proxy = await readFile(path.join(result.host, 'component.ts'), 'utf8');+ expect(proxy).toContain(`${fixture.component.base.exportName} as ${id}`);+ expect(proxy).toContain(fixture.component.base.source);+ const entry = await readFile(path.join(result.host, 'entry.tsx'), 'utf8');+ expect(entry).toContain(`./${fixture.render}`);+ expect(entry).toContain(JSON.stringify(fixture.containerMode));+ if (id !== 'LiteTable') expect(entry).not.toContain('LiteTable');+ }+});++it('selects the candidate export and source without changing the base', async () => {+ const root = await setup();+ const fixture = getStyleFixture('DotsLoading');+ fixture.component.candidate = { exportName: 'ChangedDots', source: 'src/changed.tsx' };+ const result = await prepareFixtureHost(root, sourceDirectory, fixture, 'candidate');+ expect(await readFile(path.join(result.host, 'component.ts'), 'utf8')).toContain(+ 'ChangedDots as DotsLoading',+ );+ expect(result.componentSource).toBe('src/changed.tsx');+});++it('fails closed for injected identifiers, escaping paths and repeated namespaces', async () => {+ const root = await setup();+ const fixture = getStyleFixture('DotsLoading');+ await expect(+ prepareFixtureHost(root, sourceDirectory, { ...fixture, id: '../escape' }, 'base'),+ ).rejects.toThrow();+ await expect(+ prepareFixtureHost(root, sourceDirectory, { ...fixture, assets: ['../escape'] }, 'base'),+ ).rejects.toThrow();+ await prepareFixtureHost(root, sourceDirectory, fixture, 'base');+ await expect(prepareFixtureHost(root, sourceDirectory, fixture, 'base')).rejects.toThrow();+});++it('does not borrow missing fixture modules from the checkout or another host', async () => {+ const root = await setup();+ const source = path.join(root, 'source');+ await mkdir(source);+ await writeFile(path.join(source, 'FixtureHost.tsx'), 'export const startFixture = () => {};');+ await expect(+ prepareFixtureHost(root, source, getStyleFixture('DotsLoading'), 'base'),+ ).rejects.toThrow();+});diff --git a/scripts/stylexMigration/verification/fixtures/host.ts b/scripts/stylexMigration/verification/fixtures/host.tsnew file mode 100644index 00000000000..f5cbc09fe1a--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/host.ts@@ -0,0 +1,51 @@+import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises';+import path from 'node:path';++import { sha256 } from '../reporting/report';+import type { StyleFixture } from './fixtureRegistry';+import { styleFixtureSchema } from './fixtureRegistry';++/** Only copies declared trusted fixture files; never borrows product modules. */+export const prepareFixtureHost = async (+ root: string,+ sourceDirectory: string,+ definition: StyleFixture,+ side: 'base' | 'candidate',+) => {+ const fixture = styleFixtureSchema.parse(definition);+ const sourceRoot = await realpath(sourceDirectory);+ const relativeTools = `.stylex-tools/fixtures/${fixture.id}`;+ const tools = path.join(root, relativeTools);+ await mkdir(path.dirname(tools), { recursive: true });+ await mkdir(tools);+ const host = path.join(tools, 'host');+ await mkdir(host);+ const fixtureHashes: Record<string, string> = {};+ for (const file of new Set([fixture.host, fixture.render, ...fixture.assets])) {+ const source = await realpath(path.join(sourceRoot, file));+ if (!source.startsWith(sourceRoot + path.sep)) throw new Error('FIXTURE_SOURCE_ESCAPE');+ const content = await readFile(source);+ const target = path.resolve(host, file);+ if (!target.startsWith(host + path.sep)) throw new Error('FIXTURE_OUTPUT_ESCAPE');+ await mkdir(path.dirname(target), { recursive: true });+ await writeFile(target, content, { flag: 'wx' });+ fixtureHashes[file] = sha256(content);+ }+ const component = fixture.component[side];+ await writeFile(+ path.join(host, 'component.ts'),+ `export {${component.exportName} as ${fixture.component.id}, __styleVerificationBindings, __styleVerificationCompositions} from ${JSON.stringify(path.join(root, component.source))};\n`,+ { flag: 'wx' },+ );+ await writeFile(+ path.join(host, 'index.html'),+ '<!doctype html><html><head><meta charset="utf-8"></head><body><div id="app"></div><script type="module" src="./entry.tsx"></script></body></html>',+ { flag: 'wx' },+ );+ await writeFile(+ path.join(host, 'entry.tsx'),+ `import {startFixture} from ${JSON.stringify('./' + fixture.host)}; import {Fixture} from ${JSON.stringify('./' + fixture.render)}; import {__styleVerificationBindings,__styleVerificationCompositions} from "verification:component"; Object.defineProperty(globalThis,"__styleVerificationBindings",{value:__styleVerificationBindings}); Object.defineProperty(globalThis,"__styleVerificationCompositions",{value:__styleVerificationCompositions}); startFixture(Fixture,${JSON.stringify(fixture.styleVariants.map((variant) => variant.id))},${JSON.stringify(fixture.containerMode)});\n`,+ { flag: 'wx' },+ );+ return { componentSource: component.source, fixtureHashes, host, relativeTools, tools };+};diff --git a/scripts/stylexMigration/verification/fixtures/modules.d.ts b/scripts/stylexMigration/verification/fixtures/modules.d.tsnew file mode 100644index 00000000000..9e2bf47c76f--- /dev/null+++ b/scripts/stylexMigration/verification/fixtures/modules.d.ts@@ -0,0 +1,100 @@+declare module 'verification:component' {+ import type { ListProps } from '@lobehub/ui';+ import type { ComponentType, CSSProperties, ReactNode } from 'react';++ interface Row {+ id: string;+ name: string;+ status: string;+ }+ interface Props {+ columns: Array<{+ key: string;+ listSlot?: 'title' | 'actions';+ render: (row: Row) => ReactNode;+ title: string;+ }>;+ dataSource: Row[];+ emptyText: ReactNode;+ listBreakpoint: 600 | 800;+ loading: boolean;+ onRowClick: () => void;+ rowKey: (row: Row) => string;+ tableLayout: 'auto' | 'fixed';+ }+ export const LiteTable: ComponentType<Props>;+ export const Menu: ComponentType<ListProps>;+ export const SpendType: ComponentType<{+ children: ReactNode;+ type:+ | 'chat'+ | 'embedding'+ | 'imageGeneration'+ | 'speechRecognition'+ | 'textToSpeech'+ | 'videoGeneration';+ }>;+ export const CommandLine: ComponentType<{ command: string }>;+ export const DotsLoading: ComponentType<{ color?: string; gap?: number; size?: number }>;+ export const UnreadDot: ComponentType<{ label?: string }>;+ export const VersionTag: ComponentType<{ range: string[] }>;+ export const GeneratingBorder: ComponentType<{ children: ReactNode; generating: boolean }>;+ export const GalleyGrid: ComponentType<{+ children: ReactNode;+ col: number;+ gap: number;+ max: number;+ }>;+ export const TailMarquee: ComponentType<{ children: ReactNode; style?: CSSProperties }>;+ export const CollapsibleContent: ComponentType<{+ children: ReactNode;+ collapsed: boolean;+ maxHeight: number;+ onCollapsedChange: () => void;+ }>;+ export const InlineTable: ComponentType<{+ columns: Array<{ dataIndex: string; key: string; title: string }>;+ dataSource: Row[];+ hoverToActive: boolean;+ rowKey: string;+ }>;+ export const StatusBar: ComponentType<{+ cursor: { column: number; line: number; selectionLength: number };+ indent: { size: number; useTabs: boolean };+ languageLabel: string;+ lineWrapping: boolean;+ readOnly: boolean;+ onLineWrappingChange: () => void;+ }>;+ export const FilePathDisplay: ComponentType<{ filePath: string; isDirectory: boolean }>;+ export const OptionCard: ComponentType<{+ description: string;+ disabled: boolean;+ highlighted: boolean;+ index: number;+ label: string;+ recommendedText: string;+ selected: boolean;+ onToggle: () => void;+ }>;+ export const OptionRow: ComponentType<{+ active: boolean;+ desc: string;+ disabled: boolean;+ extra: ReactNode;+ icon: ReactNode;+ label: string;+ tag: string;+ onClick: () => void;+ }>;+}++declare module 'verification:locale/chat' {+ const value: Record<string, string>;+ export default value;+}+declare module 'verification:locale/components' {+ const value: Record<string, string>;+ export default value;+}+declare module '*.css';diff --git a/scripts/stylexMigration/verification/gate/coverage.ts b/scripts/stylexMigration/verification/gate/coverage.tsnew file mode 100644index 00000000000..6face619598--- /dev/null+++ b/scripts/stylexMigration/verification/gate/coverage.ts@@ -0,0 +1,36 @@+import type { CoverageSummary, GateInput } from '../types';++/** Keys are namespaced by unit: two distinct slots can never close one another. */+export const calculateCoverage = (input: GateInput): CoverageSummary => {+ const fixtures = new Set(input.fixtures.map((fixture) => fixture.id));+ const missingKeys: string[] = [];+ const unresolvedUnitIds: string[] = [];+ let requiredKeys = 0;+ for (const unit of input.units) {+ const witnessed = new Set(+ input.witnesses+ .filter(+ (witness) =>+ witness.unitId === unit.id &&+ unit.fixtureIds.includes(witness.fixtureId) &&+ fixtures.has(witness.fixtureId) &&+ witness.evidenceRefs.length > 0,+ )+ .map((witness) => witness.key),+ );+ const missing = unit.requiredKeys.filter((key) => !witnessed.has(key));+ requiredKeys += unit.requiredKeys.length;+ missingKeys.push(...missing);+ if (!unit.fixtureIds.length || !unit.requiredKeys.length || missing.length)+ unresolvedUnitIds.push(unit.id);+ }+ return {+ machineResolvedUnits: input.units.length - unresolvedUnitIds.length,+ missingKeys,+ requiredKeys,+ reviewResolvedUnits: 0,+ totalUnits: input.units.length,+ unresolvedUnitIds,+ witnessedKeys: requiredKeys - missingKeys.length,+ };+};diff --git a/scripts/stylexMigration/verification/gate/gate.test.ts b/scripts/stylexMigration/verification/gate/gate.test.tsnew file mode 100644index 00000000000..c626556bfea--- /dev/null+++ b/scripts/stylexMigration/verification/gate/gate.test.ts@@ -0,0 +1,170 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import type { GateInput } from '../types';+import { evaluateGate, exitCode } from './gate';++const input = (): GateInput => ({+ errors: [],+ fixtures: [{ aaStable: true, comparisons: 1, id: 'button', nodeCount: 2, propertyReads: 12 }],+ findings: [],+ fullScope: true,+ identityVerified: true,+ pureStyleMigration: true,+ units: [+ { componentId: 'button', fixtureIds: ['button'], id: 'root', requiredKeys: ['root:default'] },+ ],+ witnesses: [+ {+ evidenceRefs: ['snapshot.json'],+ fixtureId: 'button',+ key: 'root:default',+ probeId: 'default',+ unitId: 'root',+ },+ ],+});++describe('style migration gate', () => {+ it('passes only complete, stable, identity-verified comparisons', () => {+ const result = evaluateGate(input());+ expect(result).toMatchObject({ gateEligible: true, status: 'PASS' });+ expect(exitCode(result.status)).toBe(0);+ });++ it('keeps an unmounted style unit in the coverage denominator', () => {+ const value = input();+ value.units.push({+ componentId: 'button',+ fixtureIds: [],+ id: 'hidden',+ requiredKeys: ['hidden:hover'],+ });+ const result = evaluateGate(value);+ expect(result.status).toBe('NEEDS_REVIEW');+ expect(result.coverage).toMatchObject({+ totalUnits: 2,+ machineResolvedUnits: 1,+ missingKeys: ['hidden:hover'],+ unresolvedUnitIds: ['hidden'],+ });+ expect(exitCode(result.status)).toBe(2);+ });++ it.each(['fixtures', 'units', 'witnesses'] as const)(+ 'never passes an empty %s collection',+ (key) => {+ const value = input();+ value[key] = [];+ expect(evaluateGate(value).status).not.toBe('PASS');+ },+ );++ it.each(['nodeCount', 'comparisons', 'propertyReads'] as const)(+ 'rejects empty %s measurements',+ (key) => {+ const value = input();+ value.fixtures[0][key] = 0;+ expect(evaluateGate(value).status).toBe('ERROR');+ },+ );++ it('does not accept a witness from the wrong fixture or without evidence', () => {+ for (const witness of [+ { ...input().witnesses[0], fixtureId: 'unrelated' },+ { ...input().witnesses[0], evidenceRefs: [] },+ { ...input().witnesses[0], unitId: 'unrelated' },+ ]) {+ expect(evaluateGate({ ...input(), witnesses: [witness] }).status).not.toBe('PASS');+ }+ });++ it('requires every conditional key, not merely one hit per rule', () => {+ const value = input();+ value.units[0].requiredKeys.push('root:hover:media-small');+ expect(evaluateGate(value).coverage.missingKeys).toEqual(['root:hover:media-small']);+ });++ it('fails confirmed differences even when coverage is incomplete', () => {+ const value = input();+ value.witnesses = [];+ value.findings.push({+ confirmed: true,+ id: 'padding',+ reasonCode: 'STYLE_CHANGED',+ severity: 'difference',+ });+ expect(evaluateGate(value).status).toBe('FAIL');+ expect(exitCode(evaluateGate(value).status)).toBe(1);+ });++ it('does not call an unconfirmed difference stable', () => {+ const value = input();+ value.findings.push({+ confirmed: false,+ id: 'padding',+ reasonCode: 'UNSTABLE_DIFFERENCE',+ severity: 'difference',+ });+ expect(evaluateGate(value).status).toBe('NEEDS_REVIEW');+ });++ it('retains failures and missing coverage when an execution error wins', () => {+ const value = input();+ value.errors.push('BROWSER_DISCONNECTED');+ value.witnesses = [];+ value.findings.push({+ confirmed: true,+ id: 'padding',+ reasonCode: 'STYLE_CHANGED',+ severity: 'difference',+ });+ const result = evaluateGate(value);+ expect(result.status).toBe('ERROR');+ expect(result.findings).toHaveLength(1);+ expect(result.coverage.missingKeys).toHaveLength(1);+ expect(exitCode(result.status)).toBe(3);+ });++ it.each(['fullScope', 'identityVerified', 'pureStyleMigration'] as const)(+ 'does not issue a gate PASS without %s',+ (key) => {+ expect(evaluateGate({ ...input(), [key]: false })).toMatchObject({+ gateEligible: false,+ status: 'NEEDS_REVIEW',+ });+ },+ );++ it('rejects unstable A/A and missing A/A controls', () => {+ const value = input();+ value.fixtures[0].aaStable = false;+ expect(evaluateGate(value).status).toBe('NEEDS_REVIEW');+ });++ it('does not turn unsupported conditions or empty key sets green', () => {+ const value = input();+ value.units[0].requiredKeys = [];+ expect(evaluateGate(value).status).toBe('NEEDS_REVIEW');+ expect(+ evaluateGate({+ ...input(),+ findings: [+ {+ confirmed: false,+ id: 'highlight',+ reasonCode: 'UNSUPPORTED_HIGHLIGHT',+ severity: 'review',+ },+ ],+ }).status,+ ).toBe('NEEDS_REVIEW');+ });++ it('rejects duplicate IDs and unknown schema fields', () => {+ const value = input();+ value.units.push(value.units[0]);+ expect(() => evaluateGate(value)).toThrow();+ expect(() => evaluateGate({ ...input(), approvedBy: 'author' })).toThrow();+ });+});diff --git a/scripts/stylexMigration/verification/gate/gate.ts b/scripts/stylexMigration/verification/gate/gate.tsnew file mode 100644index 00000000000..2f80e46d96d--- /dev/null+++ b/scripts/stylexMigration/verification/gate/gate.ts@@ -0,0 +1,55 @@+import type { GateDecision, MachineStatus } from '../types';+import { gateInputSchema } from '../types';+import { calculateCoverage } from './coverage';++export const exitCode = (status: MachineStatus | 'NOT_APPLICABLE') =>+ ({+ ERROR: 3,+ FAIL: 1,+ NEEDS_REVIEW: 2,+ NOT_APPLICABLE: 4,+ PASS: 0,+ })[status];++/** All collection adapters must pass through this reducer. It never approves evidence. */+export const evaluateGate = (value: unknown): GateDecision => {+ const input = gateInputSchema.parse(value);+ const coverage = calculateCoverage(input);+ const errors = [...input.errors];+ const reasons = new Set<string>();+ if (!input.identityVerified) reasons.add('IDENTITY_UNVERIFIED');+ if (!input.fullScope) reasons.add('PARTIAL_SCOPE');+ if (!input.pureStyleMigration) reasons.add('PURE_STYLE_MIGRATION_UNPROVEN');+ if (!input.units.length) reasons.add('EMPTY_SCOPE');+ if (!input.fixtures.length) reasons.add('MISSING_FIXTURE');+ if (coverage.unresolvedUnitIds.length || !coverage.requiredKeys)+ reasons.add('INCOMPLETE_COVERAGE');+ for (const fixture of input.fixtures) {+ if (!fixture.nodeCount || !fixture.comparisons || !fixture.propertyReads)+ errors.push(`EMPTY_CAPTURE:${fixture.id}`);+ if (!fixture.aaStable) reasons.add(`UNSTABLE_FIXTURE:${fixture.id}`);+ }+ for (const unit of input.units) {+ if (unit.fixtureIds.some((id) => !input.fixtures.some((fixture) => fixture.id === id)))+ reasons.add('MISSING_FIXTURE');+ }+ const difference = input.findings.some(+ (finding) => finding.severity === 'difference' && finding.confirmed,+ );+ input.findings.forEach((finding) => reasons.add(finding.reasonCode));+ const status: MachineStatus = errors.length+ ? 'ERROR'+ : difference+ ? 'FAIL'+ : reasons.size+ ? 'NEEDS_REVIEW'+ : 'PASS';+ return {+ coverage,+ errors,+ findings: input.findings,+ gateEligible: status === 'PASS',+ reasonCodes: [...reasons].sort(),+ status,+ };+};diff --git a/scripts/stylexMigration/verification/pipeline/componentRunner.ts b/scripts/stylexMigration/verification/pipeline/componentRunner.tsnew file mode 100644index 00000000000..f379cba6ccd--- /dev/null+++ b/scripts/stylexMigration/verification/pipeline/componentRunner.ts@@ -0,0 +1,694 @@+import { randomBytes } from 'node:crypto';+import { writeFile } from 'node:fs/promises';+import path from 'node:path';+import { promisify } from 'node:util';+import { gzip } from 'node:zlib';++import type { Browser, CDPSession, Page } from '@playwright/test';+import { chromium } from '@playwright/test';++import { summarizeConditionCoverage } from '../analysis/conditionCoverage';+import type { ConditionProbePlan } from '../analysis/conditionProbePlanner';+import { planConditionProbes, readConditionHostInPage } from '../analysis/conditionProbePlanner';+import type { RuleProbeEvidence } from '../analysis/ruleCoverage';+import { summarizeRuleCoverage } from '../analysis/ruleCoverage';+import type { RuleWitnessPlan } from '../analysis/ruleWitnesses';+import {+ collectRuleWitnessesInPage,+ planRuleWitnesses,+ readRuntimeBindings,+} from '../analysis/ruleWitnesses';+import type { StyleBindingPlan } from '../analysis/styleBindings';+import { planSupplementalProbes } from '../analysis/supplementalProbes';+import type { CaptureTiming } from '../browser/capture';+import { captureComponent } from '../browser/capture';+import { compareComponents } from '../browser/compareSnapshots';+import { collectRulesInPage } from '../browser/ruleInventory';+import { readRuntimeCompositions } from '../browser/runtimeCompositions';+import { buildComponentFixture } from '../build/buildFixtures';+import { digestFile } from '../dependencies/dependencySnapshot';+import type { StyleFixture } from '../fixtures/fixtureRegistry';+import { serveFixtures } from '../fixtures/fixtureServer';+import { sha256, writeJson } from '../reporting/report';+import type { GateInput } from '../types';+import type { FixtureProbe } from './probePlanner';+import { planFixtureProbes } from './probePlanner';+import type { ProbeShardBudget } from './probeShards';+import { createProbeShardController } from './probeShards';++const compress = promisify(gzip);++interface ProbeResult {+ aaDifferences: ReturnType<typeof compareComponents>['raw'];+ aaStable: boolean;+ captureTiming: CaptureTiming[];+ comparison: ReturnType<typeof compareComponents>;+ confirmation?: ReturnType<typeof compareComponents>;+ confirmationCaptureTiming?: CaptureTiming;+ confirmed: boolean;+ evidenceRefs: string[];+ measured: number[];+ probe: FixtureProbe;+ shardId: string;+ timing: Record<+ | 'setup'+ | 'inventory'+ | 'capture'+ | 'comparison'+ | 'persist'+ | 'confirmation'+ | 'witness'+ | 'planning',+ number+ >;+}++const openPage = async (browser: Browser, origin: string, failures: Set<string>) => {+ const context = await browser.newContext({+ colorScheme: 'light',+ deviceScaleFactor: 1,+ locale: 'en-US',+ reducedMotion: 'no-preference',+ serviceWorkers: 'block',+ timezoneId: 'UTC',+ viewport: { height: 900, width: 1200 },+ });+ await context.route('**/*', async (route) => {+ if (new URL(route.request().url()).origin === origin) await route.continue();+ else {+ failures.add(`EXTERNAL_REQUEST_BLOCKED:${route.request().resourceType()}`);+ await route.abort();+ }+ });+ const page = await context.newPage();+ await page.routeWebSocket('**/*', (socket) => socket.close());+ page.setDefaultTimeout(10_000);+ page.on('pageerror', (error) => failures.add(`PAGE_ERROR:${error.message}`));+ page.on('response', (response) => {+ if (response.status() >= 400) failures.add(`ASSET_HTTP_ERROR:${response.status()}`);+ });+ const cdp = await context.newCDPSession(page);+ await cdp.send('DOM.enable');+ await cdp.send('CSS.enable');+ return { cdp, context, page };+};++const applyProbe = async (+ page: Page,+ cdp: CDPSession,+ origin: string,+ side: string,+ probe: FixtureProbe,+ fixture: StyleFixture,+) => {+ const viewportWidth = probe.viewportWidth ?? 1200;+ if (page.viewportSize()?.width !== viewportWidth)+ await page.setViewportSize({ width: viewportWidth, height: 900 });+ // A navigation resets prior forced nodes, inline overrides, focus and animation.+ await page.goto(`${origin}/${side}/?variant=${encodeURIComponent(probe.variant)}`, {+ waitUntil: 'domcontentloaded',+ });+ await page.waitForSelector('[data-verification-ready]', { state: 'attached' });+ const measured = await page.evaluate(+ async ({ direction, width, settleFrames }) => {+ document.documentElement.dir = direction;+ const host = document.querySelector<HTMLElement>('[data-component-mount]');+ if (!host) throw new Error('FIXTURE_HOST_MISSING');+ host.style.width = `${width}px`;+ await document.fonts.ready;+ await Promise.all([...document.images].map((image) => image.decode()));+ for (let frame = 0; frame < settleFrames; frame++)+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ const container = host.firstElementChild;+ if (!(container instanceof HTMLElement)) throw new Error('COMPONENT_NOT_MOUNTED');+ const computed = getComputedStyle(container);+ const measured =+ Number.parseFloat(computed.width) -+ (computed.boxSizing === 'border-box'+ ? Number.parseFloat(computed.paddingLeft) ++ Number.parseFloat(computed.paddingRight) ++ Number.parseFloat(computed.borderLeftWidth) ++ Number.parseFloat(computed.borderRightWidth)+ : 0);+ if (!Number.isFinite(measured)) throw new Error('CONTROLLED_CONTENT_WIDTH_UNRESOLVED');+ return measured;+ },+ { ...probe, settleFrames: fixture.settleFrames },+ );+ if (probe.interaction || probe.pseudo !== 'default') {+ const selector = probe.interaction+ ? await page.evaluate(({ key, tag }) => {+ if (!/^root(?:\.\d+)*$/.test(key)) throw new Error('INVALID_TRIGGER_KEY');+ let element = document.querySelector('[data-case-root]');+ for (const index of key.split('.').slice(1).map(Number))+ element = element+ ? [...element.children].filter(+ (child) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(child.tagName),+ )[index]+ : null;+ if (!element || element.tagName !== tag)+ throw new Error('PAIRED_TRIGGER_STRUCTURE_MISMATCH');+ const segments: string[] = [];+ for (+ let current: Element | null = element;+ current?.parentElement;+ current = current.parentElement+ )+ segments.unshift(+ `:nth-child(${[...current.parentElement.children].indexOf(current) + 1})`,+ );+ return [':root', ...segments].join(' > ');+ }, probe.interaction)+ : (fixture.interactionSelectors[probe.pseudo as 'hover' | 'focus-visible'] ??+ fixture.defaultInteractionSelector);+ if (!selector) throw new Error('PSEUDO_TRIGGER_CONTRACT_MISSING');+ const documentNode = await cdp.send('DOM.getDocument');+ const target = await cdp.send('DOM.querySelector', {+ nodeId: documentNode.root.nodeId,+ selector,+ });+ if (!target.nodeId) throw new Error('PSEUDO_TRIGGER_NOT_MOUNTED');+ await cdp.send('CSS.forcePseudoState', {+ forcedPseudoClasses: [probe.interaction?.state ?? probe.pseudo],+ nodeId: target.nodeId,+ });+ }+ return measured;+};++export const runComponentFixture = async (options: {+ baseRoot: string;+ browser?: string;+ candidateRoot: string;+ fixture: StyleFixture;+ output: string;+ sourceDirectory: string;+}) => {+ const { fixture, output } = options;+ const builds = {+ base: await buildComponentFixture(options.baseRoot, options.sourceDirectory, fixture, 'base'),+ candidate: await buildComponentFixture(+ options.candidateRoot,+ options.sourceDirectory,+ fixture,+ 'candidate',+ ),+ };+ await writeJson(output, 'fixture-builds.json', builds);+ const result = await runFixtureComparison({+ browser: options.browser,+ builds,+ bindingPlans: { base: builds.base.bindingPlan, candidate: builds.candidate.bindingPlan },+ fixture,+ output,+ provenance: 'component-build',+ });+ return { ...result, artifactFiles: ['fixture-builds.json', ...result.artifactFiles] };+};++/** Lower-level browser integration; callers cannot turn this into a gate approval. */+export const runFixtureComparison = async (options: {+ browser?: string;+ bindingPlans?: { base: StyleBindingPlan; candidate: StyleBindingPlan };+ builds: { base: { output: string }; candidate: { output: string } };+ fixture: StyleFixture;+ output: string;+ probes?: FixtureProbe[];+ probeBudget?: Partial<ProbeShardBudget>;+ planConditions?: boolean;+ provenance: 'component-build' | 'infrastructure-corpus';+}) => {+ const { builds, fixture, output } = options;+ const started = performance.now();+ if (options.probeBudget && options.provenance !== 'infrastructure-corpus')+ throw new Error('UNTRUSTED_PROBE_BUDGET_OVERRIDE');+ const shardController = createProbeShardController({ budget: options.probeBudget });+ const probes = [...(options.probes ?? planFixtureProbes(fixture))];+ const planConditions = options.planConditions ?? (!!fixture.sizeContract && !options.probes);+ if (planConditions && !fixture.sizeContract) throw new Error('CONDITION_SIZE_CONTRACT_REQUIRED');+ await writeJson(output, 'probe-plan.json', {+ coverageMode: 'declared-discrete-host-contract',+ gaps: ['CONDITION_IR_UNPLANNED', 'SOURCE_UNIT_BINDING_UNPROVEN'],+ probes,+ });+ const server = await serveFixtures({+ base: builds.base.output,+ candidate: builds.candidate.output,+ });+ let browser: Browser | undefined;+ const failures = new Set<string>();+ const findings: GateInput['findings'] = [+ {+ confirmed: false,+ id: 'font-contract',+ reasonCode: 'PRODUCTION_FONT_METRICS_UNVERIFIED',+ severity: 'review',+ },+ ];+ const fixtureResults: GateInput['fixtures'] = [];+ const artifactFiles = ['probe-plan.json'];+ const results: ProbeResult[] = [];+ const rulePlans: Array<{ plan: RuleWitnessPlan; side: 'base' | 'candidate'; variant: string }> =+ [];+ const ruleEvidence: RuleProbeEvidence[] = [];+ const supplementalPlans: Array<ReturnType<typeof planSupplementalProbes> & { variant: string }> =+ [];+ const conditionPlans: ConditionProbePlan[] = [];+ try {+ browser = await chromium.launch({+ args: ['--enable-automation'],+ env: { LANG: 'en_US.UTF-8', PATH: process.env.PATH, TZ: 'UTC' },+ executablePath: options.browser,+ headless: true,+ timeout: 15_000,+ });+ const session = await browser.newBrowserCDPSession();+ const command = await session.send('Browser.getBrowserCommandLine');+ const binary = command.arguments[0];+ if (!binary || !path.isAbsolute(binary)) throw new Error('BROWSER_BINARY_IDENTITY_UNRESOLVED');+ const browserIdentity = { binaryHash: await digestFile(binary), version: browser.version() };+ await session.detach();+ let pages: Array<Awaited<ReturnType<typeof openPage>>> = [];+ const savedSnapshots = new Set<string>();+ const saveSnapshot = async (snapshot: Awaited<ReturnType<typeof captureComponent>>) => {+ const data = JSON.stringify({ ...snapshot, tree: { ...snapshot.tree, durationMs: 0 } });+ const file = `snapshot-${sha256(data)}.json.gz`;+ if (!savedSnapshots.has(file)) {+ savedSnapshots.add(file);+ await writeFile(path.join(output, file), await compress(data), { flag: 'wx' });+ artifactFiles.push(file);+ }+ return file;+ };+ for (const variant of fixture.styleVariants) {+ const variantStarted = performance.now();+ let stable = true;+ let count = 0;+ let nodes = Infinity;+ let reads = 0;+ const variantProbes = probes.filter((entry) => entry.variant === variant.id);+ const initialCount = variantProbes.length;+ for (let probeIndex = 0; probeIndex < variantProbes.length; probeIndex++) {+ const probe = variantProbes[probeIndex];+ const timing: ProbeResult['timing'] = {+ setup: 0,+ inventory: 0,+ capture: 0,+ comparison: 0,+ persist: 0,+ confirmation: 0,+ witness: 0,+ planning: 0,+ };+ const assignment = shardController.beginProbe(probe.id, variant.id);+ if (!assignment) break;+ let phaseStarted = performance.now();+ if (assignment.newShard) {+ await shardController.runOperation(() =>+ Promise.all(pages.map((entry) => entry.context.close())),+ );+ pages = await shardController.runOperation(() =>+ Promise.all(+ Array.from({ length: 4 }, () => openPage(browser!, server.origin, failures)),+ ),+ );+ }+ const measured = await shardController.runOperation(() =>+ Promise.all(+ pages+ .slice(0, 3)+ .map((entry, index) =>+ applyProbe(+ entry.page,+ entry.cdp,+ server.origin,+ index === 2 ? 'candidate' : 'base',+ probe,+ fixture,+ ),+ ),+ ),+ );+ timing.setup = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ if (measured.some((width) => Math.abs(width - probe.width) > 0.05))+ findings.push({+ confirmed: false,+ id: `${probe.id}:content-size`,+ reasonCode: 'CONTAINER_CONTENT_SIZE_MISMATCH',+ severity: 'review',+ });+ if (count === 0) {+ for (const index of [0, 2]) {+ const file = `rules-${variant.id}-${index === 0 ? 'base' : 'candidate'}.json`;+ const inventory = await shardController.runOperation(() =>+ pages[index].page.evaluate(collectRulesInPage),+ );+ await writeJson(output, file, inventory);+ artifactFiles.push(file);+ if (options.bindingPlans) {+ const side = index === 0 ? ('base' as const) : ('candidate' as const);+ const bindings = await shardController.runOperation(() =>+ readRuntimeBindings(pages[index].page),+ );+ const compositions = await shardController.runOperation(() =>+ readRuntimeCompositions(pages[index].page),+ );+ const plan = planRuleWitnesses(+ inventory,+ options.bindingPlans[side],+ bindings,+ compositions,+ );+ const planFile = `rule-plan-${variant.id}-${side}.json`;+ await writeJson(output, planFile, { bindings, compositions, plan });+ artifactFiles.push(planFile);+ rulePlans.push({ plan, side, variant: variant.id });+ }+ inventory.gaps.forEach((gap, gapIndex) =>+ findings.push({+ confirmed: false,+ id: `${variant.id}:${index}:rule-gap:${gapIndex}`,+ reasonCode: gap,+ severity: 'review',+ }),+ );+ }+ }+ timing.inventory = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ const captureTiming: CaptureTiming[] = [{}, {}, {}];+ const [base, aa, candidate] = await shardController.runOperation(() =>+ Promise.all(+ pages+ .slice(0, 3)+ .map((entry, index) => captureComponent(entry.page, entry.cdp, captureTiming[index])),+ ),+ );+ timing.capture = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ const control = compareComponents(base, aa);+ const comparison = compareComponents(base, candidate);+ timing.comparison = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ const evidenceRefs = await Promise.all([base, aa, candidate].map(saveSnapshot));+ timing.persist = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ const aaStable = control.raw.length === 0;+ stable &&= aaStable;+ let confirmed = false;+ let confirmation;+ let confirmationCaptureTiming: CaptureTiming | undefined;+ if (comparison.differences.length && aaStable) {+ await shardController.runOperation(() =>+ applyProbe(pages[3].page, pages[3].cdp, server.origin, 'candidate', probe, fixture),+ );+ const repeated = await shardController.runOperation(() =>+ captureComponent(pages[3].page, pages[3].cdp, (confirmationCaptureTiming = {})),+ );+ confirmation = compareComponents(aa, repeated);+ evidenceRefs.push(await saveSnapshot(repeated));+ confirmed =+ JSON.stringify(comparison.differences) === JSON.stringify(confirmation.differences);+ }+ timing.confirmation = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ if (comparison.differences.length)+ findings.push({+ confirmed,+ id: `${probe.id}:difference`,+ reasonCode: confirmed ? 'COMPONENT_STYLE_DIFFERENCE' : 'UNSTABLE_DIFFERENCE',+ severity: 'difference',+ });+ if (comparison.review.length)+ findings.push({+ confirmed: false,+ id: `${probe.id}:custom-properties`,+ reasonCode: 'CUSTOM_PROPERTY_CONSUMERS_UNPROVEN',+ severity: 'review',+ });+ if (options.bindingPlans) {+ for (const index of [0, 2]) {+ const side = index === 0 ? ('base' as const) : ('candidate' as const);+ const plan = rulePlans.find(+ (entry) => entry.side === side && entry.variant === variant.id,+ )?.plan;+ if (!plan) throw new Error('RULE_WITNESS_PLAN_MISSING');+ const observation = await shardController.runOperation(() =>+ pages[index].page.evaluate(collectRuleWitnessesInPage, {+ nonce: randomBytes(8).toString('hex'),+ rules: plan.rules,+ }),+ );+ ruleEvidence.push({+ evidenceRefs,+ observation,+ probeId: probe.id,+ side,+ variant: variant.id,+ });+ }+ }+ timing.witness = performance.now() - phaseStarted;+ phaseStarted = performance.now();+ results.push({+ aaDifferences: control.raw,+ aaStable,+ comparison,+ confirmation,+ confirmed,+ evidenceRefs,+ measured,+ probe,+ shardId: assignment.shardId,+ captureTiming,+ confirmationCaptureTiming,+ timing,+ });+ count++;+ nodes = Math.min(nodes, base.tree.nodes.length, candidate.tree.nodes.length);+ reads += base.tree.propertyReads + aa.tree.propertyReads + candidate.tree.propertyReads;+ if (options.bindingPlans && planConditions && count === 1 && fixture.sizeContract) {+ const seeds = await Promise.all(+ [0, 2].map(async (index) => {+ const side = index === 0 ? ('base' as const) : ('candidate' as const);+ const plan = rulePlans.find(+ (entry) => entry.side === side && entry.variant === variant.id,+ )!.plan;+ const observation = ruleEvidence.find(+ (entry) => entry.side === side && entry.probeId === probe.id,+ )!.observation;+ return {+ ...(await pages[index].page.evaluate(readConditionHostInPage, {+ 'hover': fixture.interactionSelectors.hover ?? fixture.defaultInteractionSelector,+ 'focus-visible':+ fixture.interactionSelectors['focus-visible'] ??+ fixture.defaultInteractionSelector,+ })),+ observation,+ plan,+ side,+ };+ }),+ );+ const plan = planConditionProbes({+ hostDomain: fixture.sizeContract.host,+ viewportDomain: fixture.sizeContract.viewport,+ probes,+ remaining: shardController.capacity - probes.length,+ seeds,+ variant: variant.id,+ });+ conditionPlans.push(plan);+ variantProbes.push(...plan.scheduled);+ probes.push(...plan.scheduled);+ for (const [index, reasonCode] of plan.gaps.entries())+ findings.push({+ confirmed: false,+ id: `conditions:${variant.id}:${index}`,+ reasonCode,+ severity: 'review',+ });+ }+ if (options.bindingPlans && !planConditions && probeIndex === initialCount - 1) {+ const supplement = planSupplementalProbes({+ plans: rulePlans.filter((entry) => entry.variant === variant.id),+ evidence: ruleEvidence.filter((entry) => entry.variant === variant.id),+ probes,+ remaining: shardController.capacity - probes.length,+ });+ supplementalPlans.push({ ...supplement, variant: variant.id });+ variantProbes.push(...supplement.scheduled);+ probes.push(...supplement.scheduled);+ for (const [index, reasonCode] of supplement.gaps.entries())+ findings.push({+ confirmed: false,+ id: `supplement:${variant.id}:${index}`,+ reasonCode,+ severity: 'review',+ });+ }+ timing.planning = performance.now() - phaseStarted;+ shardController.completeProbe(probe.id);+ }+ shardController.closeShard();+ fixtureResults.push({+ aaStable: stable,+ comparisons: count,+ id: `${fixture.id}:${variant.id}`,+ nodeCount: Number.isFinite(nodes) ? nodes : 0,+ propertyReads: reads,+ });+ console.log(+ JSON.stringify({+ fixture: fixture.id,+ variant: variant.id,+ probes: count,+ durationMs: performance.now() - variantStarted,+ }),+ );+ }+ const probeShards = shardController.report(probes.map((probe) => probe.id));+ await writeJson(output, 'probe-shards.json', probeShards);+ artifactFiles.push('probe-shards.json');+ for (const [index, reasonCode] of probeShards.gaps.entries())+ findings.push({+ confirmed: false,+ id: `probe-shards:${index}`,+ reasonCode,+ severity: 'review',+ });+ const ruleCoverage = options.bindingPlans+ ? summarizeRuleCoverage(rulePlans, ruleEvidence)+ : undefined;+ const conditionCoverage = conditionPlans.length+ ? summarizeConditionCoverage(+ conditionPlans,+ ruleEvidence,+ results.filter((entry) => entry.aaStable).map((entry) => entry.probe.id),+ )+ : undefined;+ if (conditionCoverage) {+ await writeJson(output, 'condition-plan.json', conditionPlans);+ await writeJson(output, 'condition-coverage.json', conditionCoverage);+ artifactFiles.push('condition-plan.json', 'condition-coverage.json');+ for (const [index, reasonCode] of [+ ...conditionCoverage.limitations,+ ...(conditionCoverage.summary.missing ? ['CONDITION_PARTITION_KEYS_MISSING'] : []),+ ].entries())+ findings.push({+ confirmed: false,+ id: `condition-coverage:${index}`,+ reasonCode,+ severity: 'review',+ });+ }+ if (ruleCoverage) {+ await writeJson(output, 'supplemental-plan.json', supplementalPlans);+ await writeJson(output, 'rule-observations.json', ruleEvidence);+ await writeJson(output, 'rule-coverage.json', ruleCoverage);+ artifactFiles.push('rule-observations.json', 'rule-coverage.json', 'supplemental-plan.json');+ const reasons = [+ ...ruleCoverage.gaps,+ ...ruleCoverage.limitations,+ ...(ruleCoverage.summary.globallyUnmounted ? ['RULE_TARGET_UNMOUNTED'] : []),+ ...(ruleCoverage.summary.partialActivation ? ['RULE_TARGET_ACTIVATION_INCOMPLETE'] : []),+ ...(ruleCoverage.summary.unsupported ? ['RULE_SELECTOR_OR_CONDITION_UNSUPPORTED'] : []),+ ...(ruleCoverage.summary.inactiveOnly ? ['RULE_ACTIVATION_UNPROVEN'] : []),+ ];+ for (const [index, reasonCode] of [...new Set(reasons)].entries())+ findings.push({+ confirmed: false,+ id: `rule-coverage:${index}`,+ reasonCode,+ severity: 'review',+ });+ }+ const durationMs = performance.now() - started;+ if (probes.length > 256)+ findings.push({+ confirmed: false,+ id: 'fixture-total-probe-budget',+ reasonCode: 'FIXTURE_TOTAL_PROBE_BUDGET_EXCEEDED',+ severity: 'review',+ });+ if (durationMs > 30_000)+ findings.push({+ confirmed: false,+ id: 'fixture-total-budget',+ reasonCode: 'FIXTURE_TOTAL_BUDGET_EXCEEDED',+ severity: 'review',+ });+ const result = {+ conditionCoverage: conditionCoverage?.summary,+ conditionCoverageRef: conditionCoverage ? 'condition-coverage.json' : undefined,+ timing: results.reduce(+ (totals, entry) => {+ for (const [key, value] of Object.entries(entry.timing))+ totals[key] = (totals[key] ?? 0) + value;+ return totals;+ },+ {} as Record<string, number>,+ ),+ ruleCoverage: ruleCoverage?.summary,+ supplemental: {+ scheduled: supplementalPlans.reduce((sum, entry) => sum + entry.scheduled.length, 0),+ blocked: supplementalPlans.reduce((sum, entry) => sum + entry.blocked.length, 0),+ unresolved: supplementalPlans.reduce(+ (sum, entry) => sum + entry.requirements.filter((item) => item.reason).length,+ 0,+ ),+ },+ browser: browserIdentity,+ probeShards: probeShards.summary,+ probeShardsRef: 'probe-shards.json',+ durationMs,+ errors: [...failures].filter((failure) => failure.startsWith('PAGE_ERROR')),+ findings: [+ ...findings,+ ...[...failures]+ .filter((failure) => !failure.startsWith('PAGE_ERROR'))+ .map((reasonCode, index) => ({+ confirmed: false,+ id: `resource:${index}`,+ reasonCode,+ severity: 'review' as const,+ })),+ ],+ fixture,+ fixtureResults,+ gateEligible: false,+ results,+ ruleCoverageRef: ruleCoverage ? 'rule-coverage.json' : undefined,+ schemaVersion: 1,+ provenance: options.provenance,+ unexecutedProbeIds: probeShards.unexecutedProbeIds,+ };+ await writeJson(output, 'component-run.json', result);+ artifactFiles.push('component-run.json');+ return { artifactFiles, result };+ } catch (error) {+ console.error(error);+ await writeJson(output, 'component-error.json', {+ ruleEvidence,+ probeShards: shardController.report(probes.map((probe) => probe.id)),+ conditionPlans,+ supplementalPlans,+ rulePlans,+ artifactFiles,+ failures: [...failures],+ findings,+ fixtureResults,+ message: error instanceof Error ? error.message : String(error),+ results,+ status: 'ERROR',+ unexecutedProbeIds: probes+ .filter((probe) => !results.some((result) => result.probe.id === probe.id))+ .map((probe) => probe.id),+ });+ throw error;+ } finally {+ await browser?.close();+ await server.close();+ }+};diff --git a/scripts/stylexMigration/verification/pipeline/fixtureBatch.ts b/scripts/stylexMigration/verification/pipeline/fixtureBatch.tsnew file mode 100644index 00000000000..ba6ecdcddd6--- /dev/null+++ b/scripts/stylexMigration/verification/pipeline/fixtureBatch.ts@@ -0,0 +1,146 @@+import { mkdir, readdir } from 'node:fs/promises';+import path from 'node:path';++import { type StyleFixture, styleFixtureSchema } from '../fixtures/fixtureRegistry';+import { summarizeComponentRun } from '../reporting/componentSummary';+import { writeArtifactManifest, writeHtmlReport, writeJson } from '../reporting/report';+import type { GateInput } from '../types';+import { runComponentFixture } from './componentRunner';++/** One frozen B/M pair and dependency capsule; isolated build namespace per+ * component. A failed component cannot skip the remaining planned components. */+export const runFixtureBatch = async (options: {+ baseRoot: string;+ browser?: string;+ candidateRoot: string;+ fixtures: StyleFixture[];+ output: string;+ sourceDirectory: string;+}) => {+ const started = performance.now();+ const errors: string[] = [];+ const findings: GateInput['findings'] = [];+ const fixtureResults: GateInput['fixtures'] = [];+ const artifactFiles: string[] = [];+ const entries: Array<{+ fixtureId: string;+ outcome: 'COMPLETED' | 'ERROR' | 'NOT_RUN';+ reason?: string;+ reportRef: string;+ summary?: ReturnType<typeof summarizeComponentRun>;+ }> = [];+ const fixtures = options.fixtures.map((fixture) => styleFixtureSchema.parse(fixture));+ const ids = fixtures.map((fixture) => fixture.id);+ if (!ids.length || ids.length > 32 || new Set(ids).size !== ids.length)+ throw new Error('INVALID_FIXTURE_BATCH');+ for (const fixture of fixtures) {+ const directory = path.join(options.output, 'components', fixture.id);+ await mkdir(directory, { recursive: true });+ await writeJson(directory, 'fixture-contract.json', fixture);+ try {+ // Reserve the two 60s sandbox build deadlines before starting new work.+ if (performance.now() - started >= 13 * 60_000) {+ const reason = 'FIXTURE_BATCH_TIME_BUDGET_EXCEEDED';+ findings.push({+ confirmed: false,+ id: `${fixture.id}:batch-budget`,+ reasonCode: reason,+ severity: 'review',+ });+ entries.push({+ fixtureId: fixture.id,+ outcome: 'NOT_RUN',+ reason,+ reportRef: `components/${fixture.id}/report.html`,+ });+ await writeJson(directory, 'not-run.json', {+ fixtureId: fixture.id,+ gateEligible: false,+ reason,+ });+ await writeHtmlReport(directory, { fixtureId: fixture.id, gateEligible: false, reason });+ } else {+ console.log(JSON.stringify({ phase: 'component-start', fixture: fixture.id }));+ const run = await runComponentFixture({ ...options, fixture, output: directory });+ const summary = summarizeComponentRun(run.result);+ errors.push(...run.result.errors.map((error) => `${fixture.id}:${error}`));+ findings.push(+ ...run.result.findings.map((finding) => ({+ ...finding,+ id: `${fixture.id}:${finding.id}`,+ })),+ );+ fixtureResults.push(...run.result.fixtureResults);+ entries.push({+ fixtureId: fixture.id,+ outcome: 'COMPLETED',+ reportRef: `components/${fixture.id}/report.html`,+ summary,+ });+ await writeJson(directory, 'component-summary.json', {+ ...summary,+ fixtureId: fixture.id,+ gateEligible: false,+ });+ await writeHtmlReport(directory, {+ ...summary,+ fixtureId: fixture.id,+ gateEligible: false,+ componentRunRef: 'component-run.json',+ });+ console.log(+ JSON.stringify({ phase: 'component-completed', fixture: fixture.id, ...summary }),+ );+ }+ } catch (error) {+ console.error(error);+ const reason = error instanceof Error ? error.message : String(error);+ errors.push(`${fixture.id}:${reason}`);+ entries.push({+ fixtureId: fixture.id,+ outcome: 'ERROR',+ reason,+ reportRef: `components/${fixture.id}/report.html`,+ });+ await writeJson(directory, 'fixture-error.json', {+ fixtureId: fixture.id,+ gateEligible: false,+ reason,+ });+ await writeHtmlReport(directory, { fixtureId: fixture.id, gateEligible: false, reason });+ }+ const files = await readdir(directory, { withFileTypes: true });+ if (files.some((file) => !file.isFile())) throw new Error('UNEXPECTED_FIXTURE_REPORT_ENTRY');+ await writeArtifactManifest(+ directory,+ files.map((file) => file.name),+ );+ artifactFiles.push(`components/${fixture.id}/artifacts.json`);+ }+ const summary = {+ completed: entries.filter((entry) => entry.outcome === 'COMPLETED').length,+ different: entries.filter((entry) => entry.summary?.sampledStyleStatus === 'DIFFERENT').length,+ equalInSamples: entries.filter(+ (entry) => entry.summary?.sampledStyleStatus === 'EQUAL_IN_SAMPLES',+ ).length,+ errors: entries.filter(+ (entry) => entry.outcome === 'ERROR' || entry.summary?.sampledStyleStatus === 'ERROR',+ ).length,+ notRun: entries.filter((entry) => entry.outcome === 'NOT_RUN').length,+ planned: ids.length,+ review: entries.filter(+ (entry) =>+ entry.summary &&+ !['DIFFERENT', 'EQUAL_IN_SAMPLES', 'ERROR'].includes(entry.summary.sampledStyleStatus),+ ).length,+ };+ await writeJson(options.output, 'fixture-batch.json', {+ durationMs: performance.now() - started,+ entries,+ gateEligible: false,+ plannedFixtureIds: ids,+ summary,+ });+ artifactFiles.push('fixture-batch.json');+ return { artifactFiles, errors, findings, fixtureResults, summary };+};diff --git a/scripts/stylexMigration/verification/pipeline/preflight.ts b/scripts/stylexMigration/verification/pipeline/preflight.tsnew file mode 100644index 00000000000..fd260b7b647--- /dev/null+++ b/scripts/stylexMigration/verification/pipeline/preflight.ts@@ -0,0 +1,208 @@+import { performance } from 'node:perf_hooks';++import { findCssModuleResidue, inventoryScope } from '../analysis/scopeInventory';+import type { DependencyOptions } from '../dependencies/dependencySnapshot';+import { restoreDependencies } from '../dependencies/dependencySnapshot';+import {+ mountFixtureDependencies,+ prepareFixtureDependencies,+} from '../dependencies/fixtureDependencies';+import { discoverFixtureCandidates, getStyleFixture } from '../fixtures/fixtureRegistry';+import { evaluateGate } from '../gate/gate';+import { summarizeComponentRun } from '../reporting/componentSummary';+import { writeArtifactManifest, writeHtmlReport, writeJson } from '../reporting/report';+import { prepareSourceSnapshots } from '../source/buildSnapshots';+import { closeRevisionSession, createRevisionSession } from '../source/revisionResolver';+import type { runComponentFixture } from './componentRunner';+import { runFixtureBatch } from './fixtureBatch';++export interface PreflightOptions {+ base: string;+ dependencyOptions?: DependencyOptions;+ fixture?: { browser?: string; id: string; sourceDirectory: string };+ fixtureBatch?: { browser?: string; ids: string[]; sourceDirectory: string };+ fixtureDependencies?: boolean;+ head: string;+ output: string;+ planOnly: boolean;+ pullRequest?: { baseRef: string; headRepository: string; number: number; repository: string };+ repository: string;+ verifierHash: string;+}++/** Preparation evidence has its own schema: do not fabricate a browser RunResult. */+export const runPreflight = async (options: PreflightOptions) => {+ const started = performance.now();+ if (options.fixture && options.fixtureBatch) throw new Error('CONFLICTING_FIXTURE_OPTIONS');+ const selected = options.fixtureBatch?.ids ?? (options.fixture ? [options.fixture.id] : []);+ const session = await createRevisionSession(options.repository, options.base, options.head);+ try {+ const scope = await inventoryScope(session);+ const migrationResidue = findCssModuleResidue(scope.units);+ const fixtures = discoverFixtureCandidates(scope);+ await writeJson(options.output, 'identity.json', session.identity);+ await writeJson(options.output, 'scope.json', scope);+ await writeJson(options.output, 'migration-residue.json', {+ cssModules: migrationResidue,+ scope: 'changed-files-only',+ completeMigrationProven: false,+ });+ await writeJson(options.output, 'fixtures.json', fixtures);+ const routing = !options.planOnly && scope.changedFiles.length === 0;+ const gateInput = {+ errors: [],+ findings: [],+ fixtures: [],+ fullScope: false,+ identityVerified: false,+ pureStyleMigration: false,+ units: scope.units.map((unit) => ({+ componentId: unit.file,+ fixtureIds: [],+ id: unit.id,+ requiredKeys: [],+ })),+ witnesses: [],+ };+ const snapshots =+ !routing && !options.planOnly+ ? await prepareSourceSnapshots(session, options.output)+ : undefined;+ let dependencies:+ | {+ base: Awaited<ReturnType<typeof restoreDependencies>>['snapshot'];+ candidate: Awaited<ReturnType<typeof restoreDependencies>>['snapshot'];+ }+ | undefined;+ if (snapshots && options.dependencyOptions) {+ const baseInputs = snapshots.base.dependencyInputs.map((input) => input.path);+ const candidateInputs = snapshots.candidate.dependencyInputs.map((input) => input.path);+ const capsules =+ options.fixtureDependencies && selected.length+ ? {+ base: await prepareFixtureDependencies(+ snapshots.base.directory,+ baseInputs,+ selected,+ ),+ candidate: await prepareFixtureDependencies(+ snapshots.candidate.directory,+ candidateInputs,+ selected,+ ),+ }+ : undefined;+ if (capsules) await writeJson(options.output, 'dependency-capsules.json', capsules);+ console.log('Restoring isolated dependencies: base');+ const base = await restoreDependencies(+ capsules?.base.directory ?? snapshots.base.directory,+ capsules?.base.inputs ?? baseInputs,+ options.dependencyOptions,+ );+ console.log('Restoring isolated dependencies: candidate');+ const sameInputs = capsules+ ? capsules.base.hash === capsules.candidate.hash+ : snapshots.base.dependencyInputHash === snapshots.candidate.dependencyInputHash;+ const candidate = await restoreDependencies(+ capsules?.candidate.directory ?? snapshots.candidate.directory,+ capsules?.candidate.inputs ?? candidateInputs,+ options.dependencyOptions,+ sameInputs ? base.lock : undefined,+ );+ if (sameInputs && candidate.snapshot.snapshotHash !== base.snapshot.snapshotHash)+ throw new Error('DEPENDENCY_RESTORE_DRIFT');+ dependencies = { base: base.snapshot, candidate: candidate.snapshot };+ await writeJson(options.output, 'dependencies.json', dependencies);+ if (capsules) {+ await mountFixtureDependencies(snapshots.base.directory);+ await mountFixtureDependencies(snapshots.candidate.directory);+ }+ }+ let component: Awaited<ReturnType<typeof runComponentFixture>> | undefined;+ let batch: Awaited<ReturnType<typeof runFixtureBatch>> | undefined;+ if (options.fixture && snapshots) {+ if (!dependencies) throw new Error('ISOLATED_DEPENDENCIES_REQUIRED');+ const { runComponentFixture } = await import('./componentRunner');+ component = await runComponentFixture({+ baseRoot: snapshots.base.directory,+ candidateRoot: snapshots.candidate.directory,+ browser: options.fixture.browser,+ fixture: getStyleFixture(options.fixture.id),+ output: options.output,+ sourceDirectory: options.fixture.sourceDirectory,+ });+ }+ if (options.fixtureBatch && snapshots) {+ if (!dependencies) throw new Error('ISOLATED_DEPENDENCIES_REQUIRED');+ batch = await runFixtureBatch({+ baseRoot: snapshots.base.directory,+ candidateRoot: snapshots.candidate.directory,+ browser: options.fixtureBatch.browser,+ fixtures: options.fixtureBatch.ids.map(getStyleFixture),+ output: options.output,+ sourceDirectory: options.fixtureBatch.sourceDirectory,+ });+ }+ const gate = evaluateGate({+ ...gateInput,+ errors: component?.result.errors ?? batch?.errors ?? [],+ findings: component?.result.findings ?? batch?.findings ?? [],+ fixtures: component?.result.fixtureResults ?? batch?.fixtureResults ?? [],+ });+ await writeJson(options.output, 'coverage.json', gate.coverage);+ const reasonCodes = routing+ ? ['NO_STYLE_IMPACT']+ : [+ ...(options.planOnly ? ['PLAN_ONLY'] : []),+ ...(!dependencies ? ['DEPENDENCY_SNAPSHOT_NOT_RESTORED'] : []),+ ...(options.fixtureDependencies+ ? ['FIXTURE_CAPSULE_WORKSPACE_PEER_CONTEXT_UNPROVEN']+ : []),+ 'SOURCE_UNIT_BINDING_UNPROVEN',+ ...(!component && !batch ? ['BROWSER_VERIFICATION_NOT_RUN'] : []),+ ...gate.reasonCodes,+ ...scope.limitations,+ ];+ const result = {+ classificationEvidenceRefs: routing ? ['scope.json', 'identity.json'] : [],+ durationMs: performance.now() - started,+ dependencies,+ componentSummary: component ? summarizeComponentRun(component.result) : undefined,+ componentBatchSummary: batch?.summary,+ componentBatchRef: batch ? 'fixture-batch.json' : undefined,+ componentRunRef: component ? 'component-run.json' : undefined,+ fixtures,+ gateEligible: false as const,+ identity: session.identity,+ mode: 'preflight' as const,+ migrationResidueRef: 'migration-residue.json',+ pullRequest: options.pullRequest,+ reasonCodes,+ schemaVersion: 1 as const,+ scopeHash: scope.hash,+ snapshots,+ status: routing ? ('NOT_APPLICABLE' as const) : gate.status,+ unresolvedUnitIds: scope.units.map((unit) => unit.id),+ verifierHash: options.verifierHash,+ };+ await writeJson(options.output, 'preflight.json', result);+ await writeHtmlReport(options.output, result);+ await writeArtifactManifest(options.output, [+ 'identity.json',+ 'scope.json',+ 'migration-residue.json',+ 'fixtures.json',+ 'coverage.json',+ 'preflight.json',+ 'report.html',+ ...(options.pullRequest ? ['pull-request.json'] : []),+ ...(dependencies ? ['dependencies.json'] : []),+ ...(options.fixtureDependencies && dependencies ? ['dependency-capsules.json'] : []),+ ...(component?.artifactFiles ?? []),+ ...(batch?.artifactFiles ?? []),+ ]);+ return result;+ } finally {+ await closeRevisionSession(session);+ }+};diff --git a/scripts/stylexMigration/verification/pipeline/probePlanner.ts b/scripts/stylexMigration/verification/pipeline/probePlanner.tsnew file mode 100644index 00000000000..79f30dd43a4--- /dev/null+++ b/scripts/stylexMigration/verification/pipeline/probePlanner.ts@@ -0,0 +1,31 @@+import type { StyleFixture } from '../fixtures/fixtureRegistry';++export interface FixtureProbe {+ direction: 'ltr' | 'rtl';+ id: string;+ interaction?: { key: string; state: string; tag: string };+ pseudo: 'default' | 'hover' | 'focus-visible';+ variant: string;+ viewportWidth?: number;+ width: number;+}++/** A finite declared host contract, NOT automatic CSS condition coverage. */+export const planFixtureProbes = (fixture: StyleFixture): FixtureProbe[] => {+ const probes: FixtureProbe[] = [];+ for (const variant of fixture.styleVariants) {+ const states = variant.states ?? ['default' as const];+ for (const direction of ['ltr', 'rtl'] as const)+ for (const width of fixture.probeWidths)+ for (const pseudo of states)+ probes.push({+ direction,+ id: `${variant.id}:${direction}:${width}:${pseudo}`,+ pseudo,+ variant: variant.id,+ width,+ });+ }+ if (probes.length > 256) throw new Error('PROBE_BUDGET_EXCEEDED');+ return probes;+};diff --git a/scripts/stylexMigration/verification/pipeline/probeShards.test.ts b/scripts/stylexMigration/verification/pipeline/probeShards.test.tsnew file mode 100644index 00000000000..ecc003c9689--- /dev/null+++ b/scripts/stylexMigration/verification/pipeline/probeShards.test.ts@@ -0,0 +1,204 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createProbeShardController } from './probeShards';++describe('bounded probe shards', () => {+ afterEach(() => vi.useRealTimers());++ it('splits work without discarding or duplicating planned probes', () => {+ const controller = createProbeShardController({ budget: { maxProbesPerShard: 2 } });+ const assignments = ['a', 'b', 'c'].map((id) => {+ const assignment = controller.beginProbe(id, 'normal');+ controller.completeProbe(id);+ return assignment;+ });+ const report = controller.report(['a', 'b', 'c']);+ expect(assignments.map((entry) => entry?.newShard)).toEqual([true, false, true]);+ expect(report.shards.map((shard) => shard.completedProbeIds)).toEqual([['a', 'b'], ['c']]);+ expect(report.unexecutedProbeIds).toEqual([]);+ expect(report.gaps).toEqual([]);+ expect(report.gateEligible).toBe(false);+ });++ it('starts a fresh shard at a variant boundary', () => {+ const controller = createProbeShardController();+ const first = controller.beginProbe('a', 'normal');+ controller.completeProbe('a');+ const second = controller.beginProbe('b', 'loading');+ controller.completeProbe('b');+ expect(second?.newShard).toBe(true);+ expect(second?.shardId).not.toBe(first?.shardId);+ expect(controller.report(['a', 'b']).shards.map((entry) => entry.variant)).toEqual([+ 'normal',+ 'loading',+ ]);+ });++ it('rolls over before the time reserve is consumed', () => {+ let now = 0;+ const controller = createProbeShardController({ clock: () => now });+ controller.beginProbe('a', 'normal');+ now = 28_000;+ controller.completeProbe('a');+ expect(controller.beginProbe('b', 'normal')?.newShard).toBe(true);+ controller.completeProbe('b');+ expect(controller.report(['a', 'b']).gaps).toEqual([]);+ });++ it('retains unfinished work when the shard count is exhausted', () => {+ const controller = createProbeShardController({+ budget: { maxProbesPerShard: 1, maxShards: 1 },+ });+ controller.beginProbe('a', 'normal');+ controller.completeProbe('a');+ expect(controller.beginProbe('b', 'normal')).toBeUndefined();+ const report = controller.report(['a', 'b', 'c']);+ expect(report.unexecutedProbeIds).toEqual(['b', 'c']);+ expect(report.gaps).toContain('PROBE_SHARD_COUNT_BUDGET_EXCEEDED');+ });++ it('bounds the whole execution, not just each shard', () => {+ let now = 0;+ const controller = createProbeShardController({+ budget: { maxRunDurationMs: 4000, probeReserveMs: 100 },+ clock: () => now,+ });+ controller.beginProbe('a', 'normal');+ controller.completeProbe('a');+ now = 3900;+ expect(controller.beginProbe('b', 'loading')).toBeUndefined();+ expect(controller.report(['a', 'b']).gaps).toContain('PROBE_RUN_TIME_BUDGET_EXCEEDED');+ });++ it('never hides an over-budget completed shard', () => {+ let now = 0;+ const controller = createProbeShardController({ clock: () => now });+ controller.beginProbe('a', 'normal');+ now = 30_001;+ controller.completeProbe('a');+ const report = controller.report(['a']);+ expect(report.shards[0].status).toBe('BUDGET_EXCEEDED');+ expect(report.gaps).toContain('PROBE_SHARD_TIME_BUDGET_EXCEEDED');+ });++ it('retains a whole-run overrun even when the final probe completed', () => {+ let now = 0;+ const controller = createProbeShardController({+ budget: { maxRunDurationMs: 4000, probeReserveMs: 100 },+ clock: () => now,+ });+ controller.beginProbe('a', 'normal');+ now = 4001;+ controller.completeProbe('a');+ expect(controller.report(['a']).gaps).toContain('PROBE_RUN_TIME_BUDGET_EXCEEDED');+ });++ it('records an interrupted probe as incomplete and does not retry it', () => {+ const controller = createProbeShardController();+ controller.beginProbe('a', 'normal');+ const report = controller.report(['a', 'b']);+ expect(report.shards[0].status).toBe('ERROR');+ expect(report.unexecutedProbeIds).toEqual(['a', 'b']);+ expect(report.gaps).toContain('PROBE_SHARD_INCOMPLETE');+ expect(() => controller.beginProbe('a', 'normal')).toThrow('DUPLICATE_PROBE_EXECUTION');+ });++ it('bounds each browser operation by the current shard deadline', () => {+ let now = 0;+ const controller = createProbeShardController({ clock: () => now });+ controller.beginProbe('a', 'normal');+ now = 2000;+ expect(controller.remaining()).toBe(28_000);+ now = 30_000;+ expect(() => controller.remaining()).toThrow('PROBE_SHARD_TIME_BUDGET_EXCEEDED');+ });++ it('also bounds each browser operation by the whole-run deadline', () => {+ let now = 0;+ const controller = createProbeShardController({+ budget: { maxRunDurationMs: 4000, probeReserveMs: 100 },+ clock: () => now,+ });+ controller.beginProbe('a', 'normal');+ now = 1000;+ expect(controller.remaining()).toBe(3000);+ });++ it('does not start a browser operation after its deadline', async () => {+ let now = 0;+ const controller = createProbeShardController({ clock: () => now });+ controller.beginProbe('a', 'normal');+ now = 30_000;+ const operation = vi.fn(async () => 42);+ await expect(controller.runOperation(operation)).rejects.toThrow(+ 'PROBE_SHARD_TIME_BUDGET_EXCEEDED',+ );+ expect(operation).not.toHaveBeenCalled();+ });++ it('fails a hung operation and keeps the unfinished probe', async () => {+ vi.useFakeTimers();+ const controller = createProbeShardController({+ budget: { maxShardDurationMs: 1000, probeReserveMs: 0 },+ clock: () => 0,+ });+ controller.beginProbe('a', 'normal');+ const failure = expect(+ controller.runOperation(() => new Promise<never>(() => {})),+ ).rejects.toThrow('BROWSER_OPERATION_TIMEOUT');+ await vi.advanceTimersByTimeAsync(1000);+ await failure;+ const report = controller.report(['a']);+ expect(report.shards[0].status).toBe('ERROR');+ expect(report.unexecutedProbeIds).toEqual(['a']);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('cleans operation timers on success and on synchronous failure', async () => {+ vi.useFakeTimers();+ const controller = createProbeShardController({ clock: () => 0 });+ controller.beginProbe('a', 'normal');+ await expect(controller.runOperation(async () => 42)).resolves.toBe(42);+ await expect(+ controller.runOperation(() => {+ throw new Error('BROKEN_OPERATION');+ }),+ ).rejects.toThrow('BROKEN_OPERATION');+ expect(vi.getTimerCount()).toBe(0);+ });++ it('keeps a completed difference independent of missing later probes', () => {+ const controller = createProbeShardController({+ budget: { maxProbesPerShard: 1, maxShards: 1 },+ });+ controller.beginProbe('difference', 'normal');+ controller.completeProbe('difference');+ controller.beginProbe('not-run', 'normal');+ const report = controller.report(['difference', 'not-run']);+ expect(report.shards[0].completedProbeIds).toEqual(['difference']);+ expect(report.unexecutedProbeIds).toEqual(['not-run']);+ });++ it('rejects mismatched completion, overlapping work and duplicate planned IDs', () => {+ const controller = createProbeShardController();+ controller.beginProbe('a', 'normal');+ expect(() => controller.completeProbe('b')).toThrow('PROBE_COMPLETION_MISMATCH');+ expect(() => controller.beginProbe('b', 'normal')).toThrow('PROBE_ALREADY_RUNNING');+ controller.completeProbe('a');+ expect(() => controller.report(['a', 'a'])).toThrow('DUPLICATE_PLANNED_PROBE');+ expect(() => controller.report(['b'])).toThrow('EXECUTED_PROBE_NOT_PLANNED');+ });++ it.each([+ { maxProbesPerShard: 65 },+ { maxShards: 17 },+ { maxShardDurationMs: 30_001 },+ { maxRunDurationMs: 900_001 },+ { maxProbesPerShard: 0 },+ { maxShards: 1.5 },+ { maxShardDurationMs: 1000 },+ { maxShards: Number.NaN },+ ])('rejects invalid or expanded diagnostic budgets: %j', (budget) => {+ expect(() => createProbeShardController({ budget })).toThrow('INVALID_PROBE_SHARD_BUDGET');+ });+});diff --git a/scripts/stylexMigration/verification/pipeline/probeShards.ts b/scripts/stylexMigration/verification/pipeline/probeShards.tsnew file mode 100644index 00000000000..96fcfb6e7e5--- /dev/null+++ b/scripts/stylexMigration/verification/pipeline/probeShards.ts@@ -0,0 +1,164 @@+export interface ProbeShardBudget {+ maxProbesPerShard: number;+ maxRunDurationMs: number;+ maxShardDurationMs: number;+ maxShards: number;+ probeReserveMs: number;+}++const diagnosticBudget: Readonly<ProbeShardBudget> = Object.freeze({+ maxProbesPerShard: 64,+ maxRunDurationMs: 15 * 60_000,+ maxShardDurationMs: 30_000,+ maxShards: 16,+ probeReserveMs: 3000,+});++interface ProbeShard {+ completedProbeIds: string[];+ durationMs: number;+ id: string;+ probeIds: string[];+ status: 'RUNNING' | 'COMPLETED' | 'BUDGET_EXCEEDED' | 'ERROR';+ variant: string;+}++/** In-process execution only: not an ingestion/approval API for remote shards.+ * Tests may tighten budgets, never expand the trusted diagnostic bounds. */+export const createProbeShardController = (+ options: { budget?: Partial<ProbeShardBudget>; clock?: () => number } = {},+) => {+ const budget = Object.freeze({ ...diagnosticBudget, ...options.budget });+ if (+ Object.entries(budget).some(+ ([key, value]) =>+ !Number.isSafeInteger(value) ||+ value < (key === 'probeReserveMs' ? 0 : 1) ||+ value > diagnosticBudget[key as keyof ProbeShardBudget],+ ) ||+ budget.probeReserveMs >= Math.min(budget.maxShardDurationMs, budget.maxRunDurationMs)+ )+ throw new Error('INVALID_PROBE_SHARD_BUDGET');+ const clock = options.clock ?? (() => performance.now());+ const started = clock();+ const shards: ProbeShard[] = [];+ const gaps = new Set<string>();+ const attempted = new Set<string>();+ const completed = new Set<string>();+ let active: { pending?: string; shard: ProbeShard; started: number } | undefined;++ const closeShard = () => {+ if (!active) return;+ active.shard.durationMs = clock() - active.started;+ if (active.pending) {+ active.shard.status = 'ERROR';+ gaps.add('PROBE_SHARD_INCOMPLETE');+ } else if (active.shard.durationMs > budget.maxShardDurationMs) {+ active.shard.status = 'BUDGET_EXCEEDED';+ gaps.add('PROBE_SHARD_TIME_BUDGET_EXCEEDED');+ } else active.shard.status = 'COMPLETED';+ active = undefined;+ };+ const remaining = () => {+ if (!active?.pending) throw new Error('PROBE_NOT_RUNNING');+ const now = clock();+ if (now >= started + budget.maxRunDurationMs) throw new Error('PROBE_RUN_TIME_BUDGET_EXCEEDED');+ const milliseconds =+ Math.min(started + budget.maxRunDurationMs, active.started + budget.maxShardDurationMs) - now;+ if (milliseconds <= 0) throw new Error('PROBE_SHARD_TIME_BUDGET_EXCEEDED');+ return milliseconds;+ };++ return {+ budget,+ capacity: budget.maxProbesPerShard * budget.maxShards,+ beginProbe: (id: string, variant: string) => {+ if (attempted.has(id)) throw new Error('DUPLICATE_PROBE_EXECUTION');+ if (active?.pending) throw new Error('PROBE_ALREADY_RUNNING');+ const now = clock();+ if (now - started >= budget.maxRunDurationMs - budget.probeReserveMs) {+ closeShard();+ gaps.add('PROBE_RUN_TIME_BUDGET_EXCEEDED');+ return undefined;+ }+ if (+ active &&+ (active.shard.variant !== variant ||+ active.shard.probeIds.length >= budget.maxProbesPerShard ||+ now - active.started >= budget.maxShardDurationMs - budget.probeReserveMs)+ )+ closeShard();+ const newShard = !active;+ if (!active) {+ if (shards.length >= budget.maxShards) {+ gaps.add('PROBE_SHARD_COUNT_BUDGET_EXCEEDED');+ return undefined;+ }+ const shard: ProbeShard = {+ completedProbeIds: [],+ durationMs: 0,+ id: `shard-${shards.length + 1}`,+ probeIds: [],+ status: 'RUNNING',+ variant,+ };+ active = { shard, started: now };+ shards.push(shard);+ }+ attempted.add(id);+ active.pending = id;+ active.shard.probeIds.push(id);+ return { newShard, shardId: active.shard.id };+ },+ remaining,+ runOperation: async <T>(operation: () => Promise<T>): Promise<T> => {+ // Check before invoking the operation: an already-created Promise would+ // start browser work even if reading the remaining budget then throws.+ const milliseconds = remaining();+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('BROWSER_OPERATION_TIMEOUT')), milliseconds);+ });+ return await Promise.race([operation(), timeout]);+ } finally {+ clearTimeout(timer);+ }+ },+ completeProbe: (id: string) => {+ if (active?.pending !== id) throw new Error('PROBE_COMPLETION_MISMATCH');+ active.pending = undefined;+ active.shard.completedProbeIds.push(id);+ completed.add(id);+ },+ closeShard,+ report: (plannedProbeIds: string[]) => {+ const planned = new Set(plannedProbeIds);+ if (planned.size !== plannedProbeIds.length) throw new Error('DUPLICATE_PLANNED_PROBE');+ if ([...attempted].some((id) => !planned.has(id)))+ throw new Error('EXECUTED_PROBE_NOT_PLANNED');+ closeShard();+ if (clock() - started > budget.maxRunDurationMs) gaps.add('PROBE_RUN_TIME_BUDGET_EXCEEDED');+ const unexecutedProbeIds = plannedProbeIds.filter((id) => !completed.has(id));+ if (unexecutedProbeIds.length) gaps.add('PROBE_EXECUTION_INCOMPLETE');+ return {+ budget,+ durationMs: clock() - started,+ gaps: [...gaps],+ gateEligible: false as const,+ mode: 'bounded-in-process-shards' as const,+ plannedProbeIds,+ shards,+ summary: {+ completedProbes: completed.size,+ completedShards: shards.filter((shard) => shard.status === 'COMPLETED').length,+ failedShards: shards.filter((shard) => shard.status !== 'COMPLETED').length,+ plannedProbes: plannedProbeIds.length,+ shards: shards.length,+ unexecutedProbes: unexecutedProbeIds.length,+ },+ unexecutedProbeIds,+ };+ },+ };+};diff --git a/scripts/stylexMigration/verification/reporting/componentSummary.test.ts b/scripts/stylexMigration/verification/reporting/componentSummary.test.tsnew file mode 100644index 00000000000..c86f6092b04--- /dev/null+++ b/scripts/stylexMigration/verification/reporting/componentSummary.test.ts@@ -0,0 +1,36 @@+import { expect, it } from 'vitest';++import { sampledStyleStatus } from './componentSummary';++const equal = { aaStable: true, comparison: { differences: [], review: [] }, confirmed: false };+it('qualifies equality and never treats zero execution as equal', () => {+ expect(sampledStyleStatus([equal], [], false)).toBe('EQUAL_IN_SAMPLES');+ expect(sampledStyleStatus([], [], false)).toBe('NOT_RUN');+ expect(sampledStyleStatus([equal], [], true)).toBe('INCOMPLETE');+});+it('retains a confirmed difference when later samples are missing', () => {+ const different = {+ ...equal,+ comparison: { differences: ['color'], review: [] },+ confirmed: true,+ };+ expect(sampledStyleStatus([different], [], true)).toBe('DIFFERENT');+ expect(sampledStyleStatus([different], ['PAGE_ERROR'], false)).toBe('ERROR');+});+it('does not promote unstable, unconfirmed or custom-property-only results', () => {+ expect(sampledStyleStatus([{ ...equal, aaStable: false }], [], false)).toBe('UNSTABLE');+ expect(+ sampledStyleStatus(+ [{ ...equal, comparison: { differences: ['color'], review: [] } }],+ [],+ false,+ ),+ ).toBe('NEEDS_REVIEW');+ expect(+ sampledStyleStatus(+ [{ ...equal, comparison: { differences: [], review: ['--unknown'] } }],+ [],+ false,+ ),+ ).toBe('NEEDS_REVIEW');+});diff --git a/scripts/stylexMigration/verification/reporting/componentSummary.ts b/scripts/stylexMigration/verification/reporting/componentSummary.tsnew file mode 100644index 00000000000..7b53cb7a69d--- /dev/null+++ b/scripts/stylexMigration/verification/reporting/componentSummary.ts@@ -0,0 +1,44 @@+import type { runFixtureComparison } from '../pipeline/componentRunner';++/** Equality is explicitly limited to executed samples, never a gate PASS. */+export const sampledStyleStatus = (+ probes: Array<{+ aaStable: boolean;+ comparison: { differences: readonly unknown[]; review: readonly unknown[] };+ confirmed: boolean;+ }>,+ errors: readonly string[],+ incomplete: boolean,+) => {+ if (errors.length) return 'ERROR';+ if (probes.some((probe) => probe.confirmed && probe.comparison.differences.length))+ return 'DIFFERENT';+ if (!probes.length) return 'NOT_RUN';+ if (probes.some((probe) => !probe.aaStable)) return 'UNSTABLE';+ if (incomplete) return 'INCOMPLETE';+ if (probes.some((probe) => probe.comparison.differences.length || probe.comparison.review.length))+ return 'NEEDS_REVIEW';+ return 'EQUAL_IN_SAMPLES';+};++export const summarizeComponentRun = (+ run: Awaited<ReturnType<typeof runFixtureComparison>>['result'],+) => ({+ aaUnstableProbes: run.results.filter((probe) => !probe.aaStable).length,+ confirmedDifferenceProbes: run.results.filter((probe) => probe.confirmed).length,+ durationMs: run.durationMs,+ timing: run.timing,+ conditionCoverage: run.conditionCoverage,+ conditionCoverageRef: run.conditionCoverageRef,+ executedProbes: run.results.length,+ probeShards: run.probeShards,+ probeShardsRef: run.probeShardsRef,+ ruleCoverage: run.ruleCoverage,+ ruleCoverageRef: run.ruleCoverageRef,+ sampledStyleStatus: sampledStyleStatus(+ run.results,+ run.errors,+ !!run.unexecutedProbeIds.length || !!run.conditionCoverage?.missing,+ ),+ unexecutedProbes: run.unexecutedProbeIds.length,+});diff --git a/scripts/stylexMigration/verification/reporting/report.test.ts b/scripts/stylexMigration/verification/reporting/report.test.tsnew file mode 100644index 00000000000..97d533696df--- /dev/null+++ b/scripts/stylexMigration/verification/reporting/report.test.ts@@ -0,0 +1,41 @@+// @vitest-environment node+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { sha256, writeArtifactManifest, writeHtmlReport, writeJson } from './report';++const owned: string[] = [];+const output = async () => {+ const directory = await mkdtemp(path.join(tmpdir(), 'stylex-report-test-'));+ owned.push(directory);+ return directory;+};+afterEach(async () => {+ for (const directory of owned.splice(0)) await rm(directory, { force: true, recursive: true });+});++describe('local evidence reports', () => {+ it('treats component text as data, not executable HTML', async () => {+ const directory = await output();+ await writeHtmlReport(directory, { text: '</pre><script>alert(1)</script>' });+ const html = await readFile(path.join(directory, 'report.html'), 'utf8');+ expect(html).not.toContain('<script>');+ expect(html).toContain('<script>');+ expect(html).toContain("default-src 'none'");+ });+ it('refuses traversal and overwrites, and hashes the exact evidence bytes', async () => {+ const directory = await output();+ await expect(writeJson(directory, '../escape.json', {})).rejects.toThrow(+ 'UNSAFE_ARTIFACT_PATH',+ );+ await writeJson(directory, 'scope.json', { units: 2 });+ await expect(writeJson(directory, 'scope.json', {})).rejects.toThrow();+ const bytes = await readFile(path.join(directory, 'scope.json'));+ expect(await writeArtifactManifest(directory, ['scope.json'])).toEqual([+ { bytes: bytes.length, path: 'scope.json', sha256: sha256(bytes) },+ ]);+ });+});diff --git a/scripts/stylexMigration/verification/reporting/report.ts b/scripts/stylexMigration/verification/reporting/report.tsnew file mode 100644index 00000000000..ff9cbb0136b--- /dev/null+++ b/scripts/stylexMigration/verification/reporting/report.ts@@ -0,0 +1,63 @@+import { createHash } from 'node:crypto';+import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';++export const sha256 = (data: string | Buffer) => createHash('sha256').update(data).digest('hex');++export const writeJson = async (directory: string, file: string, value: unknown) => {+ const target = path.resolve(directory, file);+ if (!target.startsWith(directory + path.sep)) throw new Error('UNSAFE_ARTIFACT_PATH');+ await mkdir(path.dirname(target), { recursive: true });+ await writeFile(target, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });+};++const escapeHtml = (value: string) =>+ value+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"')+ .replaceAll("'", ''');++export const writeHtmlReport = async (directory: string, value: unknown) => {+ await writeFile(+ path.join(directory, 'report.html'),+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><title>Style migration verification</title><style>body{font:14px system-ui;max-width:1100px;margin:32px auto;padding:16px}pre{white-space:pre-wrap;overflow-wrap:anywhere}</style></head><body><h1>Style migration verification</h1><p>Local evidence only. A preflight or self-test is not a PR gate approval.</p><pre>${escapeHtml(JSON.stringify(value, null, 2))}</pre></body></html>`,+ { flag: 'wx' },+ );+};++export const fingerprintSources = async (directories: string[]) => {+ const hash = createHash('sha256');+ const visit = async (directory: string, prefix: string) => {+ for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) =>+ a.name.localeCompare(b.name),+ )) {+ const name = `${prefix}/${entry.name}`;+ const file = path.join(directory, entry.name);+ if (entry.isDirectory()) await visit(file, name);+ else if (entry.isFile())+ hash+ .update(name)+ .update('\0')+ .update(sha256(await readFile(file)))+ .update('\0');+ else throw new Error('VERIFIER_SOURCE_SYMLINK_UNSUPPORTED');+ }+ };+ for (const [index, directory] of directories.entries()) await visit(directory, String(index));+ return hash.digest('hex');+};++export const writeArtifactManifest = async (directory: string, files: string[]) => {+ const manifest = await Promise.all(+ files.map(async (file) => {+ const target = path.resolve(directory, file);+ if (!target.startsWith(directory + path.sep)) throw new Error('UNSAFE_ARTIFACT_PATH');+ const data = await readFile(target);+ return { bytes: data.length, path: file, sha256: sha256(data) };+ }),+ );+ await writeJson(directory, 'artifacts.json', manifest);+ return manifest;+};diff --git a/scripts/stylexMigration/verification/run.ts b/scripts/stylexMigration/verification/run.tsnew file mode 100644index 00000000000..cd251125465--- /dev/null+++ b/scripts/stylexMigration/verification/run.ts@@ -0,0 +1,60 @@+import { execFile, spawn } from 'node:child_process';+import { mkdir, mkdtemp } from 'node:fs/promises';+import path from 'node:path';+import { promisify } from 'node:util';++import { fingerprintSources } from './reporting/report';++/** Bun compiles; Node owns Playwright. Avoid tsx's function-serialization helpers. */+const main = async () => {+ const sourceDirectory = import.meta.dirname;+ const repository = path.resolve(sourceDirectory, '../../..');+ const sourceDirectories = [sourceDirectory];+ const verifierHash = await fingerprintSources(sourceDirectories);+ const parent = path.join(repository, '.records/stylex-verification/runners');+ await mkdir(parent, { recursive: true });+ const output = await mkdtemp(path.join(parent, 'node-'));+ await promisify(execFile)(+ process.execPath,+ [+ 'build',+ '--target=node',+ '--packages=external',+ '--entry-naming=[name].mjs',+ '--outdir',+ output,+ path.join(sourceDirectory, 'cli.ts'),+ ],+ { maxBuffer: 8 * 1024 ** 2, timeout: 30_000 },+ );+ if ((await fingerprintSources(sourceDirectories)) !== verifierHash)+ throw new Error('VERIFIER_CHANGED_DURING_BUILD');+ const child = spawn('node', [path.join(output, 'cli.mjs'), ...process.argv.slice(2)], {+ env: {+ ...process.env,+ STYLEX_VERIFIER_REPOSITORY: repository,+ STYLEX_VERIFIER_SOURCE_DIRECTORY: sourceDirectory,+ STYLEX_VERIFIER_SOURCE_HASH: verifierHash,+ },+ stdio: 'inherit',+ });+ const forward = (signal: NodeJS.Signals) => child.kill(signal);+ const interrupt = () => forward('SIGINT');+ const terminate = () => forward('SIGTERM');+ process.on('SIGINT', interrupt);+ process.on('SIGTERM', terminate);+ try {+ process.exitCode = await new Promise<number>((resolve, reject) => {+ child.on('error', reject);+ child.on('exit', (code) => resolve(code ?? 3));+ });+ } finally {+ process.off('SIGINT', interrupt);+ process.off('SIGTERM', terminate);+ }+};++main().catch((error) => {+ console.error(error);+ process.exitCode = 3;+});diff --git a/scripts/stylexMigration/verification/selfTest/boundaries.ts b/scripts/stylexMigration/verification/selfTest/boundaries.tsnew file mode 100644index 00000000000..ce446d343ea--- /dev/null+++ b/scripts/stylexMigration/verification/selfTest/boundaries.ts@@ -0,0 +1,277 @@+export interface BoundaryCase {+ after: string;+ afterMarkup?: string;+ before: string;+ expected: 'changed' | 'equivalent';+ feature: string;+ id: string;+ markup?: string;+ setup?: string;+}++const item = '<div class="item">Deterministic text</div>';+const wrap = (css: string, markup = item) =>+ `<!doctype html><html><head><style>body{margin:0;font:14px Arial} [data-case-root]{width:920px} ${css}</style></head><body><main data-case-root>${markup}</main></body></html>`;++export const boundaryHtml = (entry: BoundaryCase, side: 'before' | 'after') =>+ wrap(entry[side], side === 'after' ? (entry.afterMarkup ?? entry.markup) : entry.markup);++export const boundaries: BoundaryCase[] = [+ {+ after: '.item{color:blue}',+ before: '.item{color:red}',+ expected: 'changed',+ feature: '普通颜色',+ id: 'color',+ },+ {+ after: '.item{background-image:linear-gradient(red,blue)}.item{background-color:red}',+ before: '.item{background-image:linear-gradient(red,blue)}.item{background:red}',+ expected: 'changed',+ feature: 'shorthand 隐含 reset',+ id: 'background-reset',+ },+ {+ after: '.item{border:0 solid red}',+ before: '.item{border:2px solid red}',+ expected: 'changed',+ feature: '边框',+ id: 'border',+ },+ {+ after: '.item{color:blue}',+ before: '.item{color:blue!important}',+ expected: 'changed',+ feature: '!important 与 inline',+ id: 'important',+ markup: '<div class="item" style="color:red">Text</div>',+ },+ {+ after: '@layer b,a;@layer a{.item{color:red}}@layer b{.item{color:blue}}',+ before: '@layer a,b;@layer a{.item{color:red}}@layer b{.item{color:blue}}',+ expected: 'changed',+ feature: 'cascade layer 顺序',+ id: 'layer-order',+ },+ {+ after: '.item{color:var(--missing,blue)}',+ before: '.item{color:var(--missing,red)}',+ expected: 'changed',+ feature: '变量 fallback',+ id: 'variable-fallback',+ },+ {+ after: '.item::before{content:"label";color:blue}',+ before: '.item::before{content:"label";color:red}',+ expected: 'changed',+ feature: '::before',+ id: 'before',+ },+ {+ after: '.item::after{color:red}',+ before: '.item::after{content:"label";color:red}',+ expected: 'changed',+ feature: '伪元素消失',+ id: 'after-content',+ },+ {+ after: 'input::placeholder{color:blue}',+ before: 'input::placeholder{color:red}',+ expected: 'changed',+ feature: '::placeholder',+ id: 'placeholder',+ markup: '<input placeholder="Placeholder">',+ },+ {+ after: 'li::marker{color:blue}',+ before: 'li::marker{color:red}',+ expected: 'changed',+ feature: '::marker',+ id: 'marker',+ markup: '<ul><li>List item</li></ul>',+ },+ {+ after: '.item{color:black}',+ before: '.item{color:black}.item:hover{color:red}',+ expected: 'changed',+ feature: ':hover',+ id: 'hover',+ },+ {+ after: '.item{outline:none}',+ before: '.item{outline:none}.item:focus-visible{outline:2px solid red}',+ expected: 'changed',+ feature: ':focus-visible',+ id: 'focus-visible',+ markup: '<button class="item">Button</button>',+ },+ {+ after: '.target{opacity:0}',+ before: '.target{opacity:0}.parent:hover .target{opacity:1}',+ expected: 'changed',+ feature: '祖先 hover',+ id: 'ancestor-hover',+ markup: '<div class="parent"><span class="target">Action</span></div>',+ },+ {+ after: '.target{color:black}',+ before: '.target{color:black}.trigger:hover + .target{color:red}',+ expected: 'changed',+ feature: '兄弟 hover',+ id: 'sibling-hover',+ markup: '<button class="trigger">Trigger</button><span class="target">Target</span>',+ },+ {+ after: '.target{color:black}',+ before: '.target{color:black}.parent:has(.trigger:hover) .target{color:red}',+ expected: 'changed',+ feature: ':has + hover',+ id: 'has-hover',+ markup:+ '<div class="parent"><button class="trigger">Trigger</button><span class="target">Target</span></div>',+ },+ {+ after: '.item{color:black}',+ before: '.item{color:black;@media(width<600px){color:red}}',+ expected: 'changed',+ feature: '原生嵌套 media',+ id: 'nested-media',+ },+ {+ after: '.item{color:black}',+ before: '.item{color:black}@media(600px<=width<800px){.item{color:red}}',+ expected: 'changed',+ feature: '范围 media',+ id: 'range-media',+ },+ {+ after: '.host{container-type:inline-size;width:400px}.item{color:black}',+ before:+ '.host{container-type:inline-size;width:400px}.item{color:black}@container(width<300px){.item{color:red}}',+ expected: 'changed',+ feature: '尺寸 container',+ id: 'container',+ markup: '<div class="host"><div class="item">Text</div></div>',+ },+ {+ after: '.host{container:panel/inline-size;width:400px}.item{color:black}',+ before:+ '.host{container:panel/inline-size;width:400px}.item{color:black}@container panel (width<300px){.item{color:red}}',+ expected: 'changed',+ feature: '命名 container',+ id: 'named-container',+ markup: '<div class="host"><div class="item">Text</div></div>',+ },+ {+ after: '.host{container-type:inline-size;width:400px}.item{color:black}',+ before:+ '.host{container-type:inline-size;width:400px}.item{color:black;@media(width<600px){@container(width<300px){color:red}}}',+ expected: 'changed',+ feature: 'media 与 container 交集',+ id: 'media-container',+ markup: '<div class="host"><div class="item">Text</div></div>',+ },+ {+ after: '.item{color:black}',+ before: '.item{color:black}@media(width<600px){.item:hover{color:red}}',+ expected: 'changed',+ feature: 'media 与 hover 交集',+ id: 'media-hover',+ },+ {+ after: '.row~.row{border-top:1px solid red}',+ before: '.row+.row{border-top:1px solid red}',+ expected: 'changed',+ feature: '相邻兄弟与一般兄弟',+ id: 'adjacent-sibling',+ markup: '<div class="row">First</div><div>Separator</div><div class="row">Last</div>',+ },+ {+ after: '.item{padding-left:8px}',+ before: '.item{padding-inline-start:8px}',+ expected: 'changed',+ feature: 'RTL 逻辑属性',+ id: 'rtl',+ },+ {+ after: '.item{color:black}',+ before: '.item{color:black}.item:hover:focus-visible{color:red}',+ expected: 'changed',+ feature: '伪类组合',+ id: 'combined-pseudos',+ markup: '<button class="item">Button</button>',+ },+ {+ after: '.item{animation:fade 2s linear infinite}@keyframes fade{to{opacity:0}}',+ before: '.item{animation:fade 1s linear infinite}@keyframes fade{to{opacity:0}}',+ expected: 'changed',+ feature: '动画 timing',+ id: 'animation-timing',+ },+ {+ after: '.item{animation:fade 1s linear infinite}@keyframes fade{from{opacity:1}to{opacity:0}}',+ before:+ '.item{animation:fade 1s linear infinite}@keyframes fade{from{opacity:1}to{opacity:0}}@media(prefers-reduced-motion:reduce){.item{animation:none}}',+ expected: 'changed',+ feature: 'reduced-motion',+ id: 'reduced-motion',+ },+ {+ after: '.item{transition:color .4s}',+ before: '.item{transition:color .2s}',+ expected: 'changed',+ feature: 'transition 参数',+ id: 'transition',+ },+ {+ after:+ '.item{color:blue;--density:normal}@container style(--density:compact){.item{color:red}}',+ before:+ '.item{color:blue;--density:normal}@container style(--density:compact){.item{color:green}}',+ expected: 'changed',+ feature: '字面量 style container 查询',+ id: 'style-container',+ markup: '<div style="--density:normal"><div class="item">Text</div></div>',+ },+ {+ after: '.item::highlight(experiment){background:blue}',+ before: '.item::highlight(experiment){background:red}',+ expected: 'changed',+ feature: 'CSS Highlight,需反馈',+ id: 'highlight',+ setup:+ 'const range=new Range();range.selectNodeContents(document.querySelector(".item"));CSS.highlights.set("experiment",new Highlight(range));',+ },+ {+ after: '.item{color:blue}',+ before: '.item{color:blue}',+ expected: 'equivalent',+ feature: '完全相同正对照',+ id: 'identity',+ },+ {+ after: '.renamed{color:blue;padding:8px}',+ afterMarkup: '<div class="renamed">Deterministic text</div>',+ before: '.item{color:blue;padding:8px}',+ expected: 'equivalent',+ feature: '类名变化正对照',+ id: 'class-rename',+ },+ {+ after: '.color{color:blue}.padding{padding:8px}',+ afterMarkup: '<div class="color padding">Deterministic text</div>',+ before: '.item{color:blue;padding:8px}',+ expected: 'equivalent',+ feature: '原子类拆分正对照',+ id: 'atomic-split',+ },+ {+ after:+ '.item{animation:hash123 1s linear infinite}@keyframes hash123{from{opacity:1}to{opacity:0}}',+ before:+ '.item{animation:original 1s linear infinite}@keyframes original{from{opacity:1}to{opacity:0}}',+ expected: 'equivalent',+ feature: '动画名变化正对照',+ id: 'keyframe-rename',+ },+];diff --git a/scripts/stylexMigration/verification/selfTest/browserPipelineSelfTest.ts b/scripts/stylexMigration/verification/selfTest/browserPipelineSelfTest.tsnew file mode 100644index 00000000000..747d2047cc5--- /dev/null+++ b/scripts/stylexMigration/verification/selfTest/browserPipelineSelfTest.ts@@ -0,0 +1,194 @@+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { promisify } from 'node:util';+import { gunzip } from 'node:zlib';++import type { StyleBindingPlan } from '../analysis/styleBindings';+import type { ComponentSnapshot } from '../browser/capture';+import { getStyleFixture } from '../fixtures/fixtureRegistry';+import { evaluateGate, exitCode } from '../gate/gate';+import { runFixtureComparison } from '../pipeline/componentRunner';+import { writeArtifactManifest } from '../reporting/report';++const decompress = promisify(gunzip);++/** Controlled HTML tests the infrastructure only; it is not a component adapter. */+export const runBrowserPipelineSelfTest = async (output: string, browser?: string) => {+ const results = [];+ for (const mode of [+ 'equal',+ 'difference',+ 'supplemental',+ 'condition-intersection',+ 'condition-fraction',+ 'shards-complete',+ 'shards-truncated',+ 'shards-difference-truncated',+ ]) {+ const changed = mode === 'difference' || mode === 'shards-difference-truncated';+ const supplemental = mode === 'supplemental';+ const conditional = mode.startsWith('condition-');+ const sharded = mode.startsWith('shards-');+ const truncated = mode.endsWith('-truncated');+ const directory = path.join(output, `pipeline-${mode}`);+ const base = path.join(directory, 'base');+ const candidate = path.join(directory, 'candidate');+ await mkdir(base, { recursive: true });+ await mkdir(candidate);+ const html = (color: string, candidate = false) => {+ const conditionalCss =+ mode === 'condition-intersection'+ ? `@media (max-width:650px){@container card (max-width:550px){.row:hover>td{color:${candidate ? 'blue' : 'red'}}}}`+ : mode === 'condition-fraction'+ ? `@container card (599.2px < width < 599.4px){.row td{color:${candidate ? 'blue' : 'red'}}}`+ : '';+ const contextCheck = sharded+ ? `addEventListener('DOMContentLoaded',()=>{const count=Number(localStorage.getItem('visits')||0)+1;localStorage.setItem('visits',String(count));document.querySelector('[data-case-root]').setAttribute('data-context-visits',String(count));});`+ : '';+ return `<!doctype html><html><head><style>body{margin:0;font:14px Arial}td{color:${color}}tr:hover{background:yellow}${supplemental ? `.row:hover>td{background:red}${candidate ? '.row:nth-child(2):hover>td{background:blue}' : ''}` : ''}${conditionalCss}</style><script>Object.defineProperty(globalThis,'__styleVerificationBindings',{value:{styles:{row:'row'}}});Object.defineProperty(globalThis,'__styleVerificationCompositions',{value:{records:[],gaps:[]}});${contextCheck}</script></head><body><div id="app" data-verification-ready><main data-case-root data-verification-host><div data-component-mount><div style="container:card / inline-size"><table><tbody><tr class="row" tabindex="0"><td>Controlled infrastructure corpus</td></tr>${supplemental ? '<tr class="row" tabindex="0"><td>Second target</td></tr>' : ''}</tbody></table></div></div></main></div></body></html>`;+ };+ await writeFile(path.join(base, 'index.html'), html('red'), { flag: 'wx' });+ await writeFile(path.join(candidate, 'index.html'), html(changed ? 'blue' : 'red', true), {+ flag: 'wx',+ });+ const fixture = {+ ...getStyleFixture('LiteTable'),+ component: {+ id: 'infrastructure-corpus-no-react',+ base: { exportName: 'none', source: 'base/index.html' },+ candidate: { exportName: 'none', source: 'candidate/index.html' },+ },+ host: 'base/index.html',+ id: 'infrastructure-corpus',+ render: 'base/index.html',+ styleVariants: [{ expectedUnits: [], id: 'normal' }],+ };+ const comparison = await runFixtureComparison({+ bindingPlans:+ supplemental || conditional+ ? { base: controlledBindingPlan, candidate: controlledBindingPlan }+ : undefined,+ browser,+ builds: { base: { output: base }, candidate: { output: candidate } },+ fixture,+ output: directory,+ provenance: 'infrastructure-corpus',+ probeBudget: sharded ? { maxProbesPerShard: 1, maxShards: truncated ? 1 : 2 } : undefined,+ planConditions: conditional,+ probes: [+ {+ direction: 'ltr',+ id: 'normal:default',+ pseudo: 'default',+ variant: 'normal',+ width: 320,+ },+ { direction: 'rtl', id: 'normal:hover', pseudo: 'hover', variant: 'normal', width: 600 },+ ],+ });+ const gate = evaluateGate({+ errors: comparison.result.errors,+ findings: comparison.result.findings,+ fixtures: comparison.result.fixtureResults,+ fullScope: false,+ identityVerified: false,+ pureStyleMigration: false,+ units: [+ {+ componentId: 'infrastructure-corpus',+ fixtureIds: [],+ id: 'unresolved-source',+ requiredKeys: [],+ },+ ],+ witnesses: [],+ });+ await writeArtifactManifest(directory, [+ ...comparison.artifactFiles,+ 'base/index.html',+ 'candidate/index.html',+ ]);+ const expected = changed || supplemental || conditional ? 'FAIL' : 'NEEDS_REVIEW';+ const supplementPassed =+ !supplemental ||+ (comparison.result.supplemental.scheduled === 1 &&+ comparison.result.ruleCoverage?.missingActivationTargets === 0 &&+ comparison.result.results+ .slice(0, 2)+ .every((entry) => !entry.comparison.differences.length) &&+ comparison.result.results[2]?.confirmed === true);+ const conditionPassed =+ !conditional ||+ (comparison.result.results+ .slice(0, 2)+ .every((entry) => entry.comparison.differences.length === 0) &&+ comparison.result.results.slice(2).some((entry) => entry.confirmed) &&+ (mode === 'condition-fraction'+ ? comparison.result.conditionCoverage!.missing > 0+ : comparison.result.conditionCoverage!.missing === 0));+ let freshContexts = true;+ if (sharded)+ for (const file of comparison.result.results.flatMap((entry) => entry.evidenceRefs)) {+ const snapshot: ComponentSnapshot = JSON.parse(+ (await decompress(await readFile(path.join(directory, file)))).toString(),+ );+ freshContexts &&=+ snapshot.attributes+ .find((entry) => entry.key === 'root')+ ?.attributes.find(([name]) => name === 'data-context-visits')?.[1] === '1';+ }+ const shardsPassed =+ !sharded ||+ (freshContexts &&+ comparison.result.probeShards.shards === (truncated ? 1 : 2) &&+ comparison.result.probeShards.completedShards === (truncated ? 1 : 2) &&+ comparison.result.probeShards.failedShards === 0 &&+ comparison.result.unexecutedProbeIds.length === (truncated ? 1 : 0) &&+ comparison.result.findings.some(+ (entry) => entry.reasonCode === 'PROBE_SHARD_COUNT_BUDGET_EXCEEDED',+ ) === truncated);+ results.push({+ actual: gate.status,+ aaStable: comparison.result.fixtureResults.every((entry) => entry.aaStable),+ browserIdentity: comparison.result.browser,+ confirmed: comparison.result.results.filter((entry) => entry.confirmed).length,+ exitCode: exitCode(gate.status),+ expected,+ gateEligible: gate.gateEligible,+ supplemental: comparison.result.supplemental,+ conditionCoverage: comparison.result.conditionCoverage,+ probeShards: comparison.result.probeShards,+ freshContexts,+ passed:+ gate.status === expected &&+ !gate.gateEligible &&+ (conditional ||+ comparison.result.results.length === (supplemental ? 3 : truncated ? 1 : 2)) &&+ comparison.result.fixtureResults.every((entry) => entry.aaStable) &&+ !comparison.result.errors.length &&+ (truncated || !comparison.result.unexecutedProbeIds.length) &&+ supplementPassed &&+ conditionPassed &&+ shardsPassed,+ report: path.relative(output, path.join(directory, 'component-run.json')),+ });+ }+ return {+ results,+ summary: { cases: results.length, failed: results.filter((result) => !result.passed).length },+ };+};++const controlledBindingPlan: StyleBindingPlan = {+ bindings: [+ {+ kind: 'css-module',+ symbol: 'styles',+ slots: [{ name: 'row', start: 0, end: 1, unitId: 'controlled-row' }],+ },+ ],+ gaps: [],+ source: 'controlled.html',+ sourceHash: 'controlled',+ stylesheets: [],+};diff --git a/scripts/stylexMigration/verification/selfTest/capturePreparationSelfTest.ts b/scripts/stylexMigration/verification/selfTest/capturePreparationSelfTest.tsnew file mode 100644index 00000000000..470c2e50fc3--- /dev/null+++ b/scripts/stylexMigration/verification/selfTest/capturePreparationSelfTest.ts@@ -0,0 +1,230 @@+import type { Browser } from '@playwright/test';++import { captureComponent } from '../browser/capture';+import { createFastCapture } from '../browser/fastCapture';+import { captureInPage, compareSnapshots } from '../browser/snapshot';++/** Independent legacy enumeration. Never share the optimized name list with the+ * reference collector: doing so could hide an omitted property in both trees. */+const referenceNamesInPage = () => {+ const root = document.querySelector('[data-case-root]')!;+ const names = new Set<string>();+ let rootProperties: string[] = [];+ for (const element of [root, ...root.querySelectorAll('*')].filter(+ (element) => !['LINK', 'META', 'SCRIPT', 'STYLE'].includes(element.tagName),+ ))+ for (const pseudo of [undefined, '::before', '::after', '::marker', '::placeholder']) {+ const current = [...getComputedStyle(element, pseudo)];+ current.forEach((name) => names.add(name));+ if (element === root && !pseudo)+ rootProperties = current.filter((name) => !name.startsWith('--'));+ }+ return {+ custom: [...names].filter((name) => name.startsWith('--')).sort(),+ properties: [...names].sort(),+ rootProperties,+ standard: [...names].filter((name) => !name.startsWith('--')).sort(),+ };+};++interface Case {+ css?: string;+ html: string;+ id: string;+ setup?: () => void;+ strict?: boolean;+ update?: () => void;+}+const cases: Case[] = [+ { id: 'raw-attributes-and-whitespace', html: '<div data-label="A" role="status"> Text </div>' },+ {+ id: 'node-local-custom-values',+ html: '<div style="--local:red">One</div><div style="--local:blue">Two</div>',+ },+ {+ id: 'inactive-pseudo-inventory',+ css: '.x::before{content:none;--inactive:retained}',+ html: '<div class="x">Text</div>',+ },+ {+ id: 'generated-pseudo',+ css: '.x::before{content:attr(data-label);--pseudo:red;color:var(--pseudo)}',+ html: '<div class="x" data-label="Label">Text</div>',+ },+ {+ id: 'list-marker',+ css: '.x::marker{content:"* ";--marker:red;color:var(--marker)}',+ html: '<ul><li class="x">Text</li></ul>',+ },+ {+ id: 'placeholder',+ css: '.x::placeholder{--placeholder:blue;color:var(--placeholder)}',+ html: '<input class="x" placeholder="Placeholder"/>',+ },+ { id: 'no-layout-node', html: '<div hidden style="--hidden:red">Hidden</div><div>Visible</div>' },+ {+ id: 'display-contents',+ html: '<div style="display:contents;--contents:red"><span>Text</span></div>',+ },+ {+ id: 'svg',+ html: '<svg viewBox="0 0 100 100"><path d="M0 0L20 20" style="--stroke:red;stroke:var(--stroke)"/></svg>',+ },+ {+ id: 'frozen-animation',+ css: '@keyframes fade{from{opacity:.2}to{opacity:.8}} .x{animation:fade 3s linear infinite}',+ html: '<div class="x">Text</div>',+ },+ {+ id: 'registered-non-inheriting-custom',+ css: '@property --registered{syntax:"<color>";inherits:false;initial-value:red} .x{--registered:blue}',+ html: '<div class="x"><span>Child</span></div>',+ },+ {+ id: 'new-document-and-width-freshness',+ css: '.box{container-type:inline-size;width:320px}@container(width<600px){.x{--narrow:red}}@container(width>=600px){.x{--wide:blue}}',+ html: '<div class="box"><div class="x">Text</div></div>',+ update: () => {+ (document.querySelector('.box') as HTMLElement).style.width = '800px';+ },+ },+ {+ id: 'generated-pseudo-state-freshness',+ css: '.box{container-type:inline-size;width:320px}.x::after{content:none;--after:red}@container(width>=600px){.x::after{content:"After";--after:blue}}',+ html: '<div class="box"><div class="x">Text</div></div>',+ update: () => {+ (document.querySelector('.box') as HTMLElement).style.width = '800px';+ },+ },+ {+ id: 'standard-property-union-fallback',+ html: '<span>Text</span>',+ strict: true,+ setup: () => {+ const original = getComputedStyle;+ Object.defineProperty(globalThis, 'getComputedStyle', {+ value: (element: Element, pseudo?: string) => {+ const computed = original(element, pseudo);+ if (element.tagName !== 'SPAN') return computed;+ return new Proxy(computed, {+ get(target, property) {+ if (property === 'length') return target.length + 1;+ if (property === 'item')+ return (index: number) =>+ index === target.length ? 'verification-only-property' : target.item(index);+ if (property === 'getPropertyValue')+ return (name: string) =>+ name === 'verification-only-property'+ ? 'retained'+ : target.getPropertyValue(name);+ if (property === Symbol.iterator)+ return function* () {+ yield* target;+ yield 'verification-only-property';+ };+ const value = Reflect.get(target, property, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ },+ });+ },+ },+];++/** Real browser parity with a strict, independently enumerated collector. */+export const runCapturePreparationSelfTest = async (browser: Browser) => {+ const page = await browser.newPage();+ await page.route('**/*', (route) => route.abort());+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('DOM.enable');+ await cdp.send('CSS.enable');+ const results = [];+ try {+ for (const entry of cases) {+ await page.goto('about:blank');+ await page.setContent(+ `<!doctype html><html><head><style>body{margin:0;font:14px Arial}${entry.css ?? ''}</style></head><body><main data-case-root>${entry.html}</main></body></html>`,+ );+ if (entry.setup) await page.evaluate(entry.setup);+ for (const phase of entry.update ? ['initial', 'updated'] : ['initial']) {+ if (phase === 'updated') await page.evaluate(entry.update!);+ const component = await captureComponent(page, cdp);+ const names = await page.evaluate(referenceNamesInPage);+ const reference = await page.evaluate(captureInPage, {+ animationTime: 0,+ ...(entry.strict ? {} : { properties: names.properties }),+ });+ const prepared = await page.evaluate(captureInPage, {+ animationTime: 0,+ collectMetadata: true,+ });+ const metadata = prepared.captureMetadata;+ const differences = compareSnapshots(reference, component.tree);+ const namesMatch =+ !!metadata &&+ JSON.stringify(metadata.custom) === JSON.stringify(names.custom) &&+ JSON.stringify(metadata.standard) === JSON.stringify(names.standard) &&+ JSON.stringify(metadata.rootProperties) === JSON.stringify(names.rootProperties);+ const inactiveRetained =+ entry.id !== 'inactive-pseudo-inventory' || metadata!.custom.includes('--inactive');+ const backendMatches = component.backend === (entry.strict ? 'strict' : 'hybrid');+ results.push({+ id: `${entry.id}:${phase}`,+ backend: component.backend,+ nodes: component.tree.nodes.length,+ differences,+ namesMatch,+ inactiveRetained,+ passed:+ !differences.length &&+ namesMatch &&+ inactiveRetained &&+ backendMatches &&+ component.tree.nodes.length > 1 &&+ !component.tree.captureMetadata,+ });+ }+ }+ await page.goto('about:blank');+ await page.setContent('<main data-case-root><div>One-shot</div></main>');+ const { captureMetadata, ...prepared } = await page.evaluate(captureInPage, {+ collectMetadata: true,+ animationTime: 0,+ });+ const once = await createFastCapture(page, cdp, {+ prepared,+ properties: captureMetadata!.rootProperties,+ });+ let wrongTimeRejected = false;+ let reuseRejected = false;+ try {+ await once(1);+ } catch (error) {+ if (!String(error).includes('PREPARED_CAPTURE_REQUIRES_TIME_ZERO')) throw error;+ wrongTimeRejected = true;+ }+ const first = await once(0);+ try {+ await once(0);+ } catch (error) {+ if (!String(error).includes('PREPARED_CAPTURE_ALREADY_USED')) throw error;+ reuseRejected = true;+ }+ results.push({+ id: 'prepared-frame-is-time-zero-and-single-use',+ backend: 'hybrid',+ nodes: first.nodes.length,+ differences: [],+ namesMatch: true,+ inactiveRetained: true,+ passed: wrongTimeRejected && reuseRejected && first.nodes.length > 1,+ });+ return {+ results,+ summary: { cases: results.length, failed: results.filter((entry) => !entry.passed).length },+ };+ } finally {+ await page.close();+ }+};diff --git a/scripts/stylexMigration/verification/selfTest/collectorSelfTest.ts b/scripts/stylexMigration/verification/selfTest/collectorSelfTest.tsnew file mode 100644index 00000000000..767562d9a6e--- /dev/null+++ b/scripts/stylexMigration/verification/selfTest/collectorSelfTest.ts@@ -0,0 +1,141 @@+import type { Browser } from '@playwright/test';++import { captureComponent } from '../browser/capture';+import { compareComponents } from '../browser/compareSnapshots';+import { collectRulesInPage } from '../browser/ruleInventory';++interface Case {+ after: string;+ before: string;+ expected: 'difference' | 'equal' | 'review';+ id: string;+}++/** Infrastructure corpus, not substitutes for actual React component fixtures. */+const cases: Case[] = [+ {+ after: '<div style="color:blue">Text</div>',+ before: '<div style="color:red">Text</div>',+ expected: 'difference',+ id: 'resolved-color',+ },+ {+ after: '<div hidden style="color:blue">Text</div>',+ before: '<div hidden style="color:red">Text</div>',+ expected: 'difference',+ id: 'no-layout-hidden',+ },+ {+ after: '<div style="display:contents;color:blue">Text</div>',+ before: '<div style="display:contents;color:red">Text</div>',+ expected: 'difference',+ id: 'display-contents',+ },+ {+ after: '<svg><path d="M0 0L20 20" /></svg>',+ before: '<svg><path d="M0 0L10 10" /></svg>',+ expected: 'difference',+ id: 'svg-path-attributes',+ },+ {+ after: '<div style="white-space:pre">Text</div>',+ before: '<div style="white-space:pre"> Text </div>',+ expected: 'difference',+ id: 'raw-text-whitespace',+ },+ {+ after: '<div style="--unknown:blue">Text</div>',+ before: '<div style="--unknown:red">Text</div>',+ expected: 'review',+ id: 'unproven-custom-property',+ },+ {+ after: '<div style="--x:blue;color:var(--x)">Text</div>',+ before: '<div style="--x:red;color:var(--x)">Text</div>',+ expected: 'difference',+ id: 'custom-consumer',+ },+ {+ after: '<style>.x::before{content:"x";--pseudo:blue}</style><div class="x">Text</div>',+ before: '<style>.x::before{content:"x";--pseudo:red}</style><div class="x">Text</div>',+ expected: 'review',+ id: 'pseudo-only-custom-property',+ },+ {+ after: '<div class="new" style="color:blue">Text</div>',+ before: '<div class="old" style="color:blue">Text</div>',+ expected: 'equal',+ id: 'generated-class-rename',+ },+ {+ after: '<div style="border:0 none blue">Text</div>',+ before: '<div style="border:0 none red">Text</div>',+ expected: 'equal',+ id: 'nonpainting-border',+ },+ {+ after: '<style>.unused{color:blue}</style><div>Text</div>',+ before: '<style>.unused{color:red}</style><div>Text</div>',+ expected: 'equal',+ id: 'unmatched-rule-inventory-only',+ },+];++export const runCollectorSelfTest = async (browser: Browser) => {+ const pages = await Promise.all([browser.newPage(), browser.newPage(), browser.newPage()]);+ const sessions = await Promise.all(+ pages.map(async (page) => {+ await page.route('**/*', (route) => route.abort());+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('DOM.enable');+ await cdp.send('CSS.enable');+ return cdp;+ }),+ );+ const results = [];+ try {+ for (const entry of cases) {+ await Promise.all(+ pages.map((page, index) =>+ page.setContent(+ `<!doctype html><html><head><style>body{margin:0;font:14px Arial}</style></head><body><main data-case-root>${index === 2 ? entry.after : entry.before}</main></body></html>`,+ ),+ ),+ );+ const [before, aa, after] = await Promise.all(+ pages.map((page, index) => captureComponent(page, sessions[index])),+ );+ const control = compareComponents(before, aa);+ const comparison = compareComponents(before, after);+ const inventory = await pages[0].evaluate(collectRulesInPage);+ const actual = comparison.differences.length+ ? 'difference'+ : comparison.review.length+ ? 'review'+ : 'equal';+ const retainedUnmatchedRule =+ entry.id !== 'unmatched-rule-inventory-only' ||+ inventory.rules.some((rule) => rule.selector === '.unused');+ results.push({+ actual,+ aaDifferences: control.raw.length,+ backend: before.backend,+ comparison,+ expected: entry.expected,+ id: entry.id,+ nodes: before.tree.nodes.length,+ passed: actual === entry.expected && !control.raw.length && retainedUnmatchedRule,+ });+ }+ return {+ results,+ summary: {+ cases: results.length,+ failed: results.filter((entry) => !entry.passed).length,+ independentControls: results.length,+ },+ };+ } finally {+ await Promise.all(pages.map((page) => page.close()));+ }+};diff --git a/scripts/stylexMigration/verification/selfTest/index.ts b/scripts/stylexMigration/verification/selfTest/index.tsnew file mode 100644index 00000000000..50bec34c088--- /dev/null+++ b/scripts/stylexMigration/verification/selfTest/index.ts@@ -0,0 +1,151 @@+import path from 'node:path';++import { chromium } from '@playwright/test';++import { createFastCapture } from '../browser/fastCapture';+import { createProbeDriver } from '../browser/probes';+import { captureInPage, compareSnapshots } from '../browser/snapshot';+import { writeArtifactManifest, writeHtmlReport, writeJson } from '../reporting/report';+import { boundaries, boundaryHtml } from './boundaries';+import { runBrowserPipelineSelfTest } from './browserPipelineSelfTest';+import { runCapturePreparationSelfTest } from './capturePreparationSelfTest';+import { runCollectorSelfTest } from './collectorSelfTest';+import { runBoundaryMatrix } from './matrix';+import { runRuleWitnessSelfTest } from './ruleWitnessSelfTest';++/** The prototype corpus remains regression evidence, never a whole-PR PASS. */+export const runSelfTest = async (+ output: string,+ verifierHash: string,+ executablePath?: string,+) => {+ const browser = await chromium.launch({+ env: { LANG: 'en_US.UTF-8', PATH: process.env.PATH, TZ: 'UTC' },+ executablePath,+ headless: true,+ timeout: 15_000,+ });+ try {+ const started = performance.now();+ const strict = await runBoundaryMatrix(browser, undefined, 'strict');+ const fast = await runBoundaryMatrix(browser, undefined, 'fast');+ const regressions: string[] = [];+ for (const backend of [strict, fast]) {+ if (+ backend.results.length !== boundaries.length ||+ new Set(backend.results.map((entry) => entry.id)).size !== boundaries.length+ )+ regressions.push('CORPUS_INCOMPLETE');+ for (const entry of backend.results) {+ const expected =+ entry.id === 'highlight'+ ? 'feedback'+ : entry.expected === 'equivalent'+ ? 'equal'+ : 'different';+ if (entry.decision !== expected)+ regressions.push(`${entry.id}:${entry.decision}:expected-${expected}`);+ }+ }+ for (const entry of fast.results)+ if (entry.decision !== strict.results.find((value) => value.id === entry.id)?.decision)+ regressions.push(`BACKEND_DECISION_MISMATCH:${entry.id}`);+ const collector = await runCollectorSelfTest(browser);+ for (const entry of collector.results)+ if (!entry.passed) regressions.push(`COLLECTOR_REGRESSION:${entry.id}`);+ const capturePreparation = await runCapturePreparationSelfTest(browser);+ if (capturePreparation.summary.failed) regressions.push('CAPTURE_PREPARATION_REGRESSION');+ const pipeline = await runBrowserPipelineSelfTest(output, executablePath);+ if (pipeline.summary.failed) regressions.push('BROWSER_PIPELINE_REGRESSION');+ const ruleWitness = await runRuleWitnessSelfTest(browser);+ if (ruleWitness.summary.failed) regressions.push('RULE_WITNESS_REGRESSION');++ const parity: Array<{ caseId: string; differences: number; nodes: number; side: string }> = [];+ const page = await browser.newPage();+ try {+ await page.route('**/*', (route) => route.abort());+ for (const entry of boundaries) {+ for (const side of ['before', 'after'] as const) {+ await page.setContent(boundaryHtml(entry, side));+ if (entry.setup) await page.evaluate(entry.setup);+ const driver = await createProbeDriver(page);+ try {+ const capture = await createFastCapture(page, driver.cdp);+ const properties = await page.evaluate(() =>+ [...getComputedStyle(document.querySelector('[data-case-root]')!)].filter(+ (property) => !property.startsWith('--'),+ ),+ );+ const js = await page.evaluate(captureInPage, { properties });+ const hybrid = await capture();+ const differences = compareSnapshots(js, hybrid);+ parity.push({+ caseId: entry.id,+ differences: differences.length,+ nodes: js.nodes.length,+ side,+ });+ if (differences.length || !js.nodes.length)+ regressions.push(`BACKEND_TREE_MISMATCH:${entry.id}:${side}`);+ } finally {+ await driver.dispose();+ }+ }+ }+ } finally {+ await page.close();+ }+ const result = {+ browserVersion: browser.version(),+ corpus: { fast: fast.summary, strict: strict.summary },+ collector: collector.summary,+ capturePreparation: capturePreparation.summary,+ ruleWitness: ruleWitness.summary,+ pipeline: pipeline.summary,+ durationMs: performance.now() - started,+ gateEligible: false,+ mode: 'self-test',+ parity: {+ comparisons: parity.length,+ mismatching: parity.filter((entry) => entry.differences > 0).length,+ },+ regressions,+ runtime: process.version,+ schemaVersion: 1,+ status: regressions.length ? ('FAIL' as const) : ('PASS' as const),+ verifierHash,+ };+ await writeJson(output, 'strict.json', strict);+ await writeJson(output, 'fast.json', fast);+ await writeJson(output, 'parity.json', parity);+ await writeJson(output, 'collector.json', collector);+ await writeJson(output, 'capture-preparation.json', capturePreparation);+ await writeJson(output, 'pipeline.json', pipeline);+ await writeJson(output, 'rule-witness.json', ruleWitness);+ await writeJson(output, 'self-test.json', result);+ await writeHtmlReport(output, result);+ await writeArtifactManifest(output, [+ 'strict.json',+ 'fast.json',+ 'parity.json',+ 'collector.json',+ 'capture-preparation.json',+ 'pipeline.json',+ 'rule-witness.json',+ 'pipeline-equal/artifacts.json',+ 'pipeline-difference/artifacts.json',+ 'pipeline-supplemental/artifacts.json',+ 'pipeline-condition-intersection/artifacts.json',+ 'pipeline-condition-fraction/artifacts.json',+ 'pipeline-shards-complete/artifacts.json',+ 'pipeline-shards-truncated/artifacts.json',+ 'pipeline-shards-difference-truncated/artifacts.json',+ 'self-test.json',+ 'report.html',+ ]);+ console.log(`Self-test report: ${path.join(output, 'report.html')}`);+ return result;+ } finally {+ await browser.close();+ }+};diff --git a/scripts/stylexMigration/verification/selfTest/matrix.ts b/scripts/stylexMigration/verification/selfTest/matrix.tsnew file mode 100644index 00000000000..e08be8633cb--- /dev/null+++ b/scripts/stylexMigration/verification/selfTest/matrix.ts@@ -0,0 +1,81 @@+import type { Browser } from '@playwright/test';++import { compareWithProbes, discoverProbes } from '../browser/probes';+import { captureInPage, compareSnapshots } from '../browser/snapshot';+import { boundaries, boundaryHtml } from './boundaries';++export const runBoundaryMatrix = async (+ browser: Browser,+ only?: string,+ backend: 'strict' | 'fast' = 'strict',+) => {+ const started = performance.now();+ const pages = await Promise.all([browser.newPage(), browser.newPage()]);+ const results = [];+ try {+ for (const entry of boundaries.filter((entry) => !only || entry.id === only)) {+ const caseStarted = performance.now();+ await Promise.all(+ pages.map(async (page, index) => {+ await page.setViewportSize({ height: 900, width: 1200 });+ await page.emulateMedia({ colorScheme: 'light', reducedMotion: 'no-preference' });+ await page.setContent(boundaryHtml(entry, index ? 'after' : 'before'));+ if (entry.setup) await page.evaluate(entry.setup);+ }),+ );+ const defaultSnapshots = await Promise.all(+ pages.map((page) => page.evaluate(captureInPage, {})),+ );+ const defaultDifferences = compareSnapshots(defaultSnapshots[0], defaultSnapshots[1]);+ const plan = await discoverProbes(pages);+ const comparison = await compareWithProbes(pages, plan, backend);+ const detectingProbes = comparison.results.filter((probe) => probe.differenceCount > 0);+ const uncovered = comparison.coverage.flatMap((coverage) => coverage.unwitnessed);+ const decision = detectingProbes.length+ ? 'different'+ : plan.unsupported.length || uncovered.length+ ? 'feedback'+ : 'equal';+ results.push({+ coverage: comparison.coverage,+ decision,+ defaultDifferenceCount: defaultDifferences.length,+ detectingProbes,+ durationMs: performance.now() - caseStarted,+ expected: entry.expected,+ feature: entry.feature,+ id: entry.id,+ probeCount: plan.probes.length,+ propertyReads: comparison.results.reduce((sum, result) => sum + result.propertyReads, 0),+ unsupported: plan.unsupported,+ });+ console.log(+ JSON.stringify({+ matrix: entry.id,+ decision,+ defaultDifferences: defaultDifferences.length,+ probes: plan.probes.length,+ }),+ );+ }+ } finally {+ await Promise.all(pages.map((page) => page.close()));+ }+ const changed = results.filter((result) => result.expected === 'changed');+ const controls = results.filter((result) => result.expected === 'equivalent');+ return {+ durationMs: performance.now() - started,+ results,+ summary: {+ changed: changed.length,+ controls: controls.length,+ defaultDetected: changed.filter((result) => result.defaultDifferenceCount > 0).length,+ detected: changed.filter((result) => result.decision === 'different').length,+ feedback: changed.filter((result) => result.decision === 'feedback').length,+ falseEqual: changed.filter((result) => result.decision === 'equal').length,+ falsePositive: controls.filter((result) => result.decision === 'different').length,+ controlsEqual: controls.filter((result) => result.decision === 'equal').length,+ properties: results.reduce((sum, result) => sum + result.propertyReads, 0),+ },+ };+};diff --git a/scripts/stylexMigration/verification/selfTest/ruleWitnessSelfTest.ts b/scripts/stylexMigration/verification/selfTest/ruleWitnessSelfTest.tsnew file mode 100644index 00000000000..5603d7104dd--- /dev/null+++ b/scripts/stylexMigration/verification/selfTest/ruleWitnessSelfTest.ts@@ -0,0 +1,274 @@+import type { Browser } from '@playwright/test';++import {+ collectRuleWitnessesInPage,+ planRuleWitnesses,+ readRuntimeBindings,+} from '../analysis/ruleWitnesses';+import type { StyleBindingPlan } from '../analysis/styleBindings';+import { collectRulesInPage } from '../browser/ruleInventory';+import { captureInPage, compareSnapshots } from '../browser/snapshot';+import { sha256 } from '../reporting/report';++/** Real browser tests of marker isolation and branch activation, not React substitutes. */+export const runRuleWitnessSelfTest = async (browser: Browser) => {+ const page = await browser.newPage();+ await page.route('**/*', (route) => route.abort());+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('DOM.enable');+ await cdp.send('CSS.enable');+ const results: Array<{ id: string; passed: boolean; detail: unknown }> = [];+ let sequence = 0;+ const mount = async (css: string, html: string) => {+ await page.goto('about:blank');+ await page.setContent(+ `<!doctype html><html><head><style>${css}</style></head><body><main data-case-root>${html}</main></body></html>`,+ );+ };+ const observe = async () => {+ const inventory = await page.evaluate(collectRulesInPage);+ const source: StyleBindingPlan = {+ bindings: [+ {+ kind: 'css-module',+ symbol: 'styles',+ slots: ['x', 'container'].map((name) => ({+ name,+ unitId: `source:${name}`,+ start: 0,+ end: 1,+ })),+ },+ ],+ gaps: [],+ source: 'corpus.css',+ sourceHash: 'controlled',+ stylesheets: [],+ };+ const plan = planRuleWitnesses(inventory, source, {+ styles: { x: 'x', container: 'container' },+ });+ const properties = await page.evaluate(() =>+ [...getComputedStyle(document.querySelector('[data-case-root]')!)].filter(+ (property) => !property.startsWith('--'),+ ),+ );+ const sheetCount = await page.evaluate(() => document.adoptedStyleSheets.length);+ const before = await page.evaluate(captureInPage, { properties });+ const observation = await page.evaluate(collectRuleWitnessesInPage, {+ nonce: sha256(String(sequence++)).slice(0, 16),+ rules: plan.rules,+ });+ const after = await page.evaluate(captureInPage, { properties });+ const clean = (await page.evaluate(() => document.adoptedStyleSheets.length)) === sheetCount;+ return {+ inventory,+ observation,+ plan,+ pure: clean && compareSnapshots(before, after).length === 0,+ };+ };+ try {+ await mount(+ '.x:focus-visible{color:red}',+ '<div class="x" tabindex="0"><span class="x" tabindex="0">Child</span></div>',+ );+ const document = await cdp.send('DOM.getDocument');+ const target = await cdp.send('DOM.querySelector', {+ nodeId: document.root.nodeId,+ selector: 'div.x',+ });+ await cdp.send('CSS.forcePseudoState', {+ nodeId: target.nodeId,+ forcedPseudoClasses: ['focus-visible'],+ });+ const inheritance = await observe();+ const activation = inheritance.observation.observations[0].targets.map(+ (target) => target.active,+ );+ results.push({+ id: 'non-inheriting-marker-and-second-target',+ passed: inheritance.pure && JSON.stringify(activation) === '[true,false]',+ detail: activation,+ });++ await mount(+ '.container{container:card / inline-size;box-sizing:border-box;width:640px;padding:18px;border:2px solid} @container card (max-width:600px){.x{color:red}}',+ '<div class="container"><div class="x">Target</div></div>',+ );+ const narrow = await observe();+ await page.locator('.container').evaluate((element) => {+ (element as HTMLElement).style.width = '641px';+ });+ const wide = await observe();+ const narrowTarget = narrow.observation.observations.find(+ (entry) => narrow.plan.rules.find((rule) => rule.id === entry.id)?.conditions.length,+ )?.targets[0];+ const wideTarget = wide.observation.observations.find(+ (entry) => wide.plan.rules.find((rule) => rule.id === entry.id)?.conditions.length,+ )?.targets[0];+ results.push({+ id: 'named-container-content-box',+ passed:+ narrow.pure &&+ wide.pure &&+ narrowTarget?.active === true &&+ wideTarget?.active === false &&+ narrowTarget.containers[0].width === 600 &&+ wideTarget.containers[0].width === 601,+ detail: { narrowTarget, wideTarget },+ });+ await mount(+ '.container{container:card / inline-size;width:300px;height:20px;overflow-y:scroll} @container card (max-width:400px){.x{color:red}}',+ '<div class="container"><div class="x" style="height:100px">Target</div></div>',+ );+ const scroll = await observe();+ const scrollTarget = scroll.observation.observations.find(+ (entry) => scroll.plan.rules.find((rule) => rule.id === entry.id)?.conditions.length,+ )?.targets[0];+ results.push({+ id: 'scrollbar-content-metrics-retained-as-gap',+ passed:+ scroll.pure &&+ scrollTarget?.containers[0].metricsTrusted === false &&+ scrollTarget.conditionStates[0] === null,+ detail: scrollTarget,+ });++ await mount(+ '.container{container-type:inline-size;width:300px} @container (width < 400px){.x::before{content:attr(data-label)}}',+ '<div class="container"><div class="x" data-label="Label">Target</div></div>',+ );+ const pseudo = await observe();+ const pseudoTarget = pseudo.observation.observations.find(+ (entry) => pseudo.plan.rules.find((rule) => rule.id === entry.id)?.pseudo === '::before',+ )?.targets[0];+ results.push({+ id: 'pseudo-element-conditional-marker',+ passed: pseudo.pure && pseudoTarget?.active === true && pseudoTarget.content === '"Label"',+ detail: pseudoTarget,+ });++ await page.setViewportSize({ width: 900, height: 800 });+ await mount(+ '.container{container-type:inline-size;width:300px} @media (width < 700px){@container (width < 400px){.x{color:red}}}',+ '<div class="container"><div class="x">Target</div></div>',+ );+ const mediaOff = await observe();+ await page.setViewportSize({ width: 600, height: 800 });+ const mediaOn = await observe();+ const conditional = (result: typeof mediaOff) =>+ result.observation.observations.find(+ (entry) => result.plan.rules.find((rule) => rule.id === entry.id)?.conditions.length,+ )?.targets[0];+ results.push({+ id: 'media-container-intersection',+ passed:+ mediaOff.pure &&+ mediaOn.pure &&+ conditional(mediaOff)?.active === false &&+ conditional(mediaOn)?.active === true,+ detail: { off: conditional(mediaOff), on: conditional(mediaOn) },+ });++ await mount('.x{color:red; &:hover{color:blue}}', '<div class="x">Target</div>');+ const nested = await observe();+ results.push({+ id: 'native-nesting-retained-as-gap',+ passed:+ nested.pure &&+ nested.plan.rules.some(+ (rule) =>+ rule.selector === '&:hover' && rule.gaps.includes('NATIVE_NESTING_BINDING_UNSUPPORTED'),+ ),+ detail: nested.plan,+ });++ await mount(+ '.x:has(.child:hover){color:red}',+ '<div class="x"><span class="child">Target</span></div>',+ );+ const complex = await observe();+ results.push({+ id: 'unsupported-selector-not-fabricated',+ passed:+ complex.pure &&+ complex.plan.rules.length === 1 &&+ complex.plan.rules[0].gaps.length > 0 &&+ complex.observation.observations.length === 0,+ detail: complex.plan,+ });+ await mount(+ '.container{container-type:inline-size;width:600px} html:has(head > style:nth-of-type(2)) .container{width:100px} @container (width < 500px){.x{color:red}}',+ '<div class="container"><div class="x">Target</div></div>',+ );+ const domIsolation = await observe();+ const isolated = domIsolation.observation.observations.find(+ (entry) => domIsolation.plan.rules.find((rule) => rule.id === entry.id)?.conditions.length,+ )?.targets[0];+ results.push({+ id: 'marker-does-not-insert-dom-nodes',+ passed:+ domIsolation.pure && isolated?.active === false && isolated.containers[0].width === 600,+ detail: isolated,+ });+ for (const relation of ['>', '+']) {+ await mount(+ `.x:hover ${relation} .label{color:red}`,+ relation === '>'+ ? '<div class="x"><span class="label">One</span></div><div class="x"><span class="label">Two</span></div>'+ : '<div class="x">One</div><span class="label">Target one</span><div class="x">Two</div><span class="label">Target two</span>',+ );+ const relationResult = await observe();+ const targets = relationResult.observation.observations[0].targets;+ results.push({+ id:+ relation === '>'+ ? 'ancestor-trigger-bound-to-each-target'+ : 'sibling-trigger-bound-to-each-target',+ passed:+ relationResult.pure &&+ targets.length === 2 &&+ targets.every((target) => target.triggers.length === 1) &&+ targets[0].triggers[0].key !== targets[1].triggers[0].key,+ detail: targets,+ });+ }+ await page.goto('about:blank');+ await page.evaluate(() => {+ const styles = {};+ Reflect.set(globalThis, '__getterReads', 0);+ Object.defineProperty(styles, 'root', {+ enumerable: true,+ get() {+ Reflect.set(+ globalThis,+ '__getterReads',+ Number(Reflect.get(globalThis, '__getterReads')) + 1,+ );+ return 'must-not-read';+ },+ });+ Object.defineProperty(globalThis, '__styleVerificationBindings', { value: { styles } });+ });+ let accessorRejected = false;+ try {+ await readRuntimeBindings(page);+ } catch (error) {+ if (!String(error).includes('STYLE_BINDING_ACCESSOR_UNSUPPORTED')) throw error;+ accessorRejected = true;+ }+ const reads = await page.evaluate(() => Reflect.get(globalThis, '__getterReads'));+ results.push({+ id: 'binding-observer-does-not-invoke-getters',+ passed: accessorRejected && reads === 0,+ detail: { accessorRejected, reads },+ });+ return {+ results,+ summary: { cases: results.length, failed: results.filter((result) => !result.passed).length },+ };+ } finally {+ await page.close();+ }+};diff --git a/scripts/stylexMigration/verification/source/buildSnapshots.ts b/scripts/stylexMigration/verification/source/buildSnapshots.tsnew file mode 100644index 00000000000..95649821d78--- /dev/null+++ b/scripts/stylexMigration/verification/source/buildSnapshots.ts@@ -0,0 +1,160 @@+import { createHash } from 'node:crypto';+import { mkdir, symlink, writeFile } from 'node:fs/promises';+import path from 'node:path';++import type { RevisionSession, SourceEntry } from '../types';+import { git } from './git';++const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex');++export const listSourceEntries = async (+ repository: string,+ tree: string,+): Promise<SourceEntry[]> => {+ const output = (await git(repository, ['ls-tree', '-r', '-l', '-z', tree])).toString();+ return output+ .split('\0')+ .filter(Boolean)+ .map((line) => {+ const tab = line.indexOf('\t');+ const [mode, type, oid, size] = line.slice(0, tab).trim().split(/\s+/);+ const file = line.slice(tab + 1);+ if (+ tab < 0 ||+ !file ||+ path.isAbsolute(file) ||+ file.split('/').some((part) => ['..', '.', '.git', ''].includes(part)) ||+ file.includes('\\')+ )+ throw new Error('UNSAFE_SOURCE_PATH');+ return { bytes: size === '-' ? 0 : Number(size), mode, oid, path: file, type };+ });+};++/** Read blobs by object ID, never by interpolating a revision:path expression. */+export const readBlobs = async (repository: string, entries: SourceEntry[]) => {+ const output = await git(+ repository,+ ['cat-file', '--batch'],+ entries.map((entry) => entry.oid).join('\n') + '\n',+ );+ let cursor = 0;+ return entries.map((entry) => {+ const end = output.indexOf(10, cursor);+ const [oid, type, size] = output.subarray(cursor, end).toString().split(' ');+ if (end < 0 || oid !== entry.oid || type !== 'blob' || Number(size) !== entry.bytes)+ throw new Error('INVALID_GIT_BLOB_STREAM');+ cursor = end + 1;+ const value = output.subarray(cursor, cursor + entry.bytes);+ cursor += entry.bytes + 1;+ if (value.length !== entry.bytes || output[cursor - 1] !== 10)+ throw new Error('TRUNCATED_GIT_BLOB');+ return value;+ });+};++export const exportSourceTree = async (repository: string, tree: string, destination: string) => {+ const sourceTreeSha = (await git(repository, ['rev-parse', '--verify', `${tree}^{tree}`]))+ .toString()+ .trim();+ const entries = await listSourceEntries(repository, sourceTreeSha);+ if (+ entries.length > 150_000 ||+ entries.reduce((sum, entry) => sum + entry.bytes, 0) > 2 * 1024 ** 3+ )+ throw new Error('SOURCE_BUDGET_EXCEEDED');+ if (+ entries.some(+ (entry) => entry.type !== 'blob' || !['100644', '100755', '120000'].includes(entry.mode),+ )+ )+ throw new Error('SUBMODULE_OR_SOURCE_MODE_UNSUPPORTED');+ if (entries.some((entry) => entry.bytes > 32 * 1024 ** 2))+ throw new Error('SOURCE_BLOB_BUDGET_EXCEEDED');+ // Destination must be new: never overwrite user files or follow existing links.+ await mkdir(destination);+ const links: Array<{ file: string; target: string }> = [];+ for (let offset = 0; offset < entries.length;) {+ const batch: SourceEntry[] = [];+ let bytes = 0;+ do {+ const entry = entries[offset++];+ batch.push(entry);+ bytes += entry.bytes;+ } while (+ offset < entries.length &&+ bytes + entries[offset].bytes < 8 * 1024 ** 2 &&+ batch.length < 256+ );+ const blobs = await readBlobs(repository, batch);+ await Promise.all(+ batch.map(async (entry, index) => {+ const file = path.join(destination, entry.path);+ await mkdir(path.dirname(file), { recursive: true });+ if (entry.mode === '120000') {+ const target = blobs[index].toString();+ const resolved = path.resolve(path.dirname(file), target);+ if (+ path.isAbsolute(target) ||+ !resolved.startsWith(destination + path.sep) ||+ target.includes('\0')+ )+ throw new Error(`EXTERNAL_SOURCE_SYMLINK:${entry.path}`);+ links.push({ file, target });+ } else+ await writeFile(file, blobs[index], {+ flag: 'wx',+ mode: entry.mode === '100755' ? 0o755 : 0o644,+ });+ }),+ );+ }+ // Reject chains: lexical containment alone is insufficient when a target+ // traverses another link before '..' is resolved by the operating system.+ const linkPaths = links.map((link) => link.file);+ for (const link of links) {+ const target = path.resolve(path.dirname(link.file), link.target);+ if (+ link.target.includes('\\') ||+ linkPaths.some((file) => target === file || target.startsWith(file + path.sep))+ )+ throw new Error('SOURCE_SYMLINK_CHAIN_UNSUPPORTED');+ }+ // Links are created last. No file write can traverse an untrusted link.+ for (const link of links) await symlink(link.target, link.file);+ const dependencyInputs = entries.filter(+ (entry) =>+ path.basename(entry.path) === 'package.json' ||+ [+ 'pnpm-workspace.yaml',+ 'pnpm-lock.yaml',+ 'package-lock.json',+ 'bun.lock',+ '.npmrc',+ '.pnpmfile.cjs',+ ].includes(entry.path) ||+ entry.path.startsWith('patches/'),+ );+ return {+ dependencyInputHash: hash(JSON.stringify(dependencyInputs)),+ dependencyInputs,+ dependencyRestore: 'NOT_RESTORED' as const,+ directory: destination,+ fileCount: entries.length,+ sourceTreeSha,+ };+};++/** Full trees, including workspace sources: no alias fallback into the checkout. */+export const prepareSourceSnapshots = async (session: RevisionSession, runDirectory: string) => ({+ base: await exportSourceTree(+ session.directory,+ session.identity.baseSha,+ path.join(runDirectory, 'base-source'),+ ),+ candidate: await exportSourceTree(+ session.directory,+ session.identity.candidateTreeSha,+ path.join(runDirectory, 'candidate-source'),+ ),+});diff --git a/scripts/stylexMigration/verification/source/git.ts b/scripts/stylexMigration/verification/source/git.tsnew file mode 100644index 00000000000..398ef610d05--- /dev/null+++ b/scripts/stylexMigration/verification/source/git.ts@@ -0,0 +1,27 @@+import { execFile } from 'node:child_process';++/** No shell interpolation; ignore ambient Git overrides that can change the repository. */+export const gitEnvironment = () => ({+ ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_'))),+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_TERMINAL_PROMPT: '0',+});++export const git = (directory: string, args: string[], input?: string) =>+ new Promise<Buffer>((resolve, reject) => {+ const child = execFile(+ 'git',+ ['--no-replace-objects', '-c', 'core.hooksPath=/dev/null', ...args],+ {+ cwd: directory,+ encoding: 'buffer',+ env: gitEnvironment(),+ maxBuffer: 64 * 1024 * 1024,+ timeout: 30_000,+ },+ (error, stdout) => (error ? reject(error) : resolve(stdout)),+ );+ child.stdin?.on('error', reject);+ child.stdin?.end(input);+ });diff --git a/scripts/stylexMigration/verification/source/pullRequest.test.ts b/scripts/stylexMigration/verification/source/pullRequest.test.tsnew file mode 100644index 00000000000..05af43eaffd--- /dev/null+++ b/scripts/stylexMigration/verification/source/pullRequest.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';++import { validatePullRequest } from './pullRequest';++const response = () => ({+ base: { ref: 'canary', repo: { full_name: 'lobehub/lobehub' }, sha: 'a'.repeat(40) },+ head: { repo: { full_name: 'contributor/lobehub' }, sha: 'b'.repeat(40) },+ number: 21447,+});++describe('PR revision identity', () => {+ it('keeps a fork head separate from the target repository', () => {+ expect(validatePullRequest(response(), 'lobehub/lobehub', 21447)).toMatchObject({+ baseRef: 'canary',+ headRepository: 'contributor/lobehub',+ });+ });+ it('rejects an identically numbered PR from a different target repository', () => {+ expect(() => validatePullRequest(response(), 'other/lobehub', 21447)).toThrow(+ 'PR_REPOSITORY_IDENTITY_MISMATCH',+ );+ expect(() => validatePullRequest(response(), 'lobehub/lobehub', 1)).toThrow(+ 'PR_REPOSITORY_IDENTITY_MISMATCH',+ );+ });+ it('rejects missing forks and malformed SHAs', () => {+ expect(() =>+ validatePullRequest(+ { ...response(), head: { repo: null, sha: 'b'.repeat(40) } },+ 'lobehub/lobehub',+ 21447,+ ),+ ).toThrow('PR_HEAD_REPOSITORY_UNAVAILABLE');+ expect(() =>+ validatePullRequest(+ { ...response(), base: { ...response().base, sha: '--help' } },+ 'lobehub/lobehub',+ 21447,+ ),+ ).toThrow();+ });+});diff --git a/scripts/stylexMigration/verification/source/pullRequest.ts b/scripts/stylexMigration/verification/source/pullRequest.tsnew file mode 100644index 00000000000..3cd8ec618d4--- /dev/null+++ b/scripts/stylexMigration/verification/source/pullRequest.ts@@ -0,0 +1,59 @@+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';++import { z } from 'zod';++import { git } from './git';++const execute = promisify(execFile);+const repositoryName = z.string().regex(/^[\w.-]+\/[\w.-]+$/);+const sha = z.string().regex(/^[\da-f]{40}$/);+const prSchema = z.object({+ base: z.object({ ref: z.string().min(1), repo: z.object({ full_name: repositoryName }), sha }),+ head: z.object({ repo: z.object({ full_name: repositoryName }).nullable(), sha }),+ number: z.number().int().positive(),+});++export const resolveRepositoryName = async (directory: string, explicit?: string) => {+ if (explicit) return repositoryName.parse(explicit);+ const url = (await git(directory, ['remote', 'get-url', 'origin'])).toString().trim();+ const match = url.match(+ /^(?:git@github\.com:|https:\/\/github\.com\/)([\w.-]+\/[\w.-]+?)(?:\.git)?$/,+ );+ if (!match) throw new Error('GITHUB_REPOSITORY_REQUIRED: pass --repo owner/name');+ return repositoryName.parse(match[1]);+};++export const validatePullRequest = (value: unknown, repository: string, number: number) => {+ const pr = prSchema.parse(value);+ if (pr.number !== number || pr.base.repo.full_name.toLowerCase() !== repository.toLowerCase())+ throw new Error('PR_REPOSITORY_IDENTITY_MISMATCH');+ if (!pr.head.repo) throw new Error('PR_HEAD_REPOSITORY_UNAVAILABLE');+ return {+ base: pr.base.sha,+ baseRef: pr.base.ref,+ head: pr.head.sha,+ headRepository: pr.head.repo.full_name,+ number,+ repository,+ };+};++/** Read-only API. Objects must exist locally; never fetch into the user's Git database. */+export const resolvePullRequest = async (+ directory: string,+ number: number,+ explicitRepository?: string,+) => {+ const repository = await resolveRepositoryName(directory, explicitRepository);+ const { stdout } = await execute(+ 'gh',+ ['api', '--hostname', 'github.com', `repos/${repository}/pulls/${number}`],+ {+ cwd: directory,+ maxBuffer: 8 * 1024 * 1024,+ timeout: 30_000,+ },+ );+ return validatePullRequest(JSON.parse(stdout), repository, number);+};diff --git a/scripts/stylexMigration/verification/source/revisionResolver.ts b/scripts/stylexMigration/verification/source/revisionResolver.tsnew file mode 100644index 00000000000..24191e69abb--- /dev/null+++ b/scripts/stylexMigration/verification/source/revisionResolver.ts@@ -0,0 +1,98 @@+import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import type { RevisionSession } from '../types';+import { git } from './git';++export const resolveCommit = async (repository: string, ref: string) => {+ if (!ref || ref.startsWith('-') || /[\s\0]/.test(ref)) throw new Error('INVALID_REVISION');+ const sha = (+ await git(repository, ['rev-parse', '--verify', '--end-of-options', `${ref}^{commit}`])+ )+ .toString()+ .trim();+ if (!/^(?:[\da-f]{40}|[\da-f]{64})$/.test(sha)) throw new Error('INVALID_COMMIT_ID');+ return sha;+};++/** B is the target tip, not the merge-base. M includes concurrent changes from B. */+export const createRevisionSession = async (+ repository: string,+ base: string,+ head: string,+): Promise<RevisionSession> => {+ const sourceRepository = await realpath(repository);+ const [baseSha, headSha, format, commonDirectory] = await Promise.all([+ resolveCommit(sourceRepository, base),+ resolveCommit(sourceRepository, head),+ git(sourceRepository, ['rev-parse', '--show-object-format']),+ git(sourceRepository, ['rev-parse', '--path-format=absolute', '--git-common-dir']),+ ]);+ let shallow: string | undefined;+ if (+ (await git(sourceRepository, ['rev-parse', '--is-shallow-repository'])).toString().trim() ===+ 'true'+ ) {+ // A shallow checkout is safe only when no cut edge occurs between B/H and+ // their common ancestor. Copy those boundaries into the owned object DB.+ const shallowPath = (+ await git(sourceRepository, ['rev-parse', '--path-format=absolute', '--git-path', 'shallow'])+ )+ .toString()+ .trim();+ shallow = await readFile(shallowPath, 'utf8');+ const bases = (await git(sourceRepository, ['merge-base', '--all', baseSha, headSha]))+ .toString()+ .trim()+ .split('\n');+ if (bases.length !== 1 || !bases[0]) throw new Error('SHALLOW_MERGE_BASE_UNPROVEN');+ const region = new Set(+ (await git(sourceRepository, ['rev-list', baseSha, headSha, '--not', ...bases]))+ .toString()+ .trim()+ .split('\n'),+ );+ if (+ shallow+ .trim()+ .split('\n')+ .some((sha) => region.has(sha))+ )+ throw new Error('SHALLOW_RELEVANT_HISTORY_INCOMPLETE');+ }+ const directory = await mkdtemp(path.join(tmpdir(), 'stylex-verification-git-'));+ try {+ await git(directory, ['init', '--bare', `--object-format=${format.toString().trim()}`, '.']);+ const objects = path.join(commonDirectory.toString().trim(), 'objects');+ if (/[\r\n]/.test(objects)) throw new Error('INVALID_OBJECT_DIRECTORY');+ await writeFile(path.join(directory, 'objects/info/alternates'), `${objects}\n`);+ if (shallow) await writeFile(path.join(directory, 'shallow'), shallow);+ const merged = (+ await git(directory, ['merge-tree', '--write-tree', baseSha, headSha])+ ).toString();+ const candidateTreeSha = merged.split('\n')[0];+ if (!/^(?:[\da-f]{40}|[\da-f]{64})$/.test(candidateTreeSha))+ throw new Error('INVALID_CANDIDATE_TREE');+ return {+ directory,+ identity: { baseSha, candidateTreeSha, headSha, repository: sourceRepository },+ sourceRepository,+ };+ } catch (error) {+ await rm(directory, { force: true, recursive: true });+ throw error;+ }+};++/** Only callers holding the session returned above can clean this owned scratch repo. */+export const closeRevisionSession = async (session: RevisionSession) => {+ if (+ path.dirname(session.directory) !== (await realpath(tmpdir())) &&+ path.dirname(session.directory) !== tmpdir()+ )+ throw new Error('REFUSE_UNOWNED_CLEANUP');+ if (!path.basename(session.directory).startsWith('stylex-verification-git-'))+ throw new Error('REFUSE_UNOWNED_CLEANUP');+ await rm(session.directory, { force: true, recursive: true });+};diff --git a/scripts/stylexMigration/verification/types.ts b/scripts/stylexMigration/verification/types.tsnew file mode 100644index 00000000000..6ff12898e66--- /dev/null+++ b/scripts/stylexMigration/verification/types.ts@@ -0,0 +1,115 @@+import { z } from 'zod';++const nonempty = z.string().min(1).max(8192);+const unique = <T>(values: T[]) => new Set(values).size === values.length;++export const machineStatusSchema = z.enum(['PASS', 'FAIL', 'NEEDS_REVIEW', 'ERROR']);+export type MachineStatus = z.infer<typeof machineStatusSchema>;++export const coverageUnitSchema = z.strictObject({+ componentId: nonempty,+ fixtureIds: z.array(nonempty).refine(unique, 'Duplicate fixture ID'),+ id: nonempty,+ requiredKeys: z.array(nonempty).refine(unique, 'Duplicate coverage key'),+});++export const witnessSchema = z.strictObject({+ evidenceRefs: z.array(nonempty),+ fixtureId: nonempty,+ key: nonempty,+ probeId: nonempty,+ unitId: nonempty,+});++export const gateInputSchema = z.strictObject({+ errors: z.array(nonempty),+ findings: z+ .array(+ z.strictObject({+ confirmed: z.boolean(),+ id: nonempty,+ reasonCode: nonempty,+ severity: z.enum(['difference', 'review']),+ }),+ )+ .refine((values) => unique(values.map((value) => value.id)), 'Duplicate finding ID'),+ fixtures: z+ .array(+ z.strictObject({+ aaStable: z.boolean(),+ comparisons: z.number().int().nonnegative(),+ id: nonempty,+ nodeCount: z.number().int().nonnegative(),+ propertyReads: z.number().int().nonnegative(),+ }),+ )+ .refine((values) => unique(values.map((value) => value.id)), 'Duplicate fixture ID'),+ fullScope: z.boolean(),+ identityVerified: z.boolean(),+ pureStyleMigration: z.boolean(),+ units: z+ .array(coverageUnitSchema)+ .refine((values) => unique(values.map((value) => value.id)), 'Duplicate unit ID'),+ witnesses: z.array(witnessSchema),+});++export type GateInput = z.infer<typeof gateInputSchema>;+export type CoverageUnit = z.infer<typeof coverageUnitSchema>;++export interface CoverageSummary {+ machineResolvedUnits: number;+ missingKeys: string[];+ requiredKeys: number;+ reviewResolvedUnits: number;+ totalUnits: number;+ unresolvedUnitIds: string[];+ witnessedKeys: number;+}++export interface GateDecision {+ coverage: CoverageSummary;+ errors: string[];+ findings: GateInput['findings'];+ gateEligible: boolean;+ reasonCodes: string[];+ status: MachineStatus;+}++export interface RevisionIdentity {+ baseSha: string;+ candidateTreeSha: string;+ headSha: string;+ repository: string;+}++export interface SourceEntry {+ bytes: number;+ mode: string;+ oid: string;+ path: string;+ type: string;+}++export interface RevisionSession {+ directory: string;+ identity: RevisionIdentity;+ sourceRepository: string;+}++export interface ScopeUnit {+ blobSha: string;+ end: number;+ file: string;+ id: string;+ kind: 'source' | 'style-slot' | 'stylesheet' | 'opaque';+ label: string;+ side: 'base' | 'candidate';+ start: number;+}++export interface ScopeInventory {+ changedFiles: Array<{ after?: string; before?: string; status: string }>;+ hash: string;+ limitations: string[];+ units: ScopeUnit[];+}diff --git a/scripts/stylexMigration/verification/vitest.config.test.ts b/scripts/stylexMigration/verification/vitest.config.test.tsnew file mode 100644index 00000000000..3ea57e748f4--- /dev/null+++ b/scripts/stylexMigration/verification/vitest.config.test.ts@@ -0,0 +1,80 @@+import { execFile } from 'node:child_process';+import { readdir } from 'node:fs/promises';+import { createRequire } from 'node:module';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++import { describe, expect, it } from 'vitest';++const execute = promisify(execFile);+const root = fileURLToPath(new URL('../../../', import.meta.url));+const require = createRequire(import.meta.url);+const vitest = path.join(path.dirname(require.resolve('vitest/package.json')), 'vitest.mjs');+const localConfig = 'scripts/stylexMigration/verification/vitest.config.ts';+const localTest = (file: string) => file.startsWith('scripts/stylexMigration/verification/');++const listTests = async (config: string, project?: string) => {+ const { stdout } = await execute(+ process.execPath,+ [+ vitest,+ 'list',+ '--config',+ config,+ '--filesOnly',+ ...(project ? ['--project', project] : []),+ 'scripts/stylexMigration',+ 'src/styles/sx.test.ts',+ '--json',+ ],+ {+ cwd: root,+ env: { ...process.env, CI: 'true', FORCE_COLOR: '0', NO_COLOR: '1' },+ maxBuffer: 4 * 1024 ** 2,+ timeout: 30_000,+ },+ );+ const files: { file: string }[] = JSON.parse(stdout);+ return files.map(({ file }) => path.relative(root, file).split(path.sep).join('/'));+};++describe('local StyleX verification test discovery', () => {+ it('has unambiguous module names on case-insensitive filesystems', async () => {+ const files = await readdir(fileURLToPath(new URL('./', import.meta.url)), {+ recursive: true,+ });+ const modules = files+ .filter((file) => /\.[cm]?[jt]sx?$/.test(file))+ .map((file) => file.replace(/\.[cm]?[jt]sx?$/, '').toLowerCase());+ expect(new Set(modules).size).toBe(modules.length);+ });++ it('keeps verification out of app CI without hiding existing migration or sx tests', async () => {+ const files = await listTests('vitest.config.mts', 'app');+ expect(files.filter(localTest)).toEqual([]);+ expect(files).toContain('scripts/stylexMigration/baseline.test.ts');+ expect(files).toContain('src/styles/sx.test.ts');+ });++ it('does not collect local tooling in server CI', async () => {+ expect(await listTests('vitest.config.mts', 'server')).toEqual([]);+ });++ it('keeps the CLI, local helpers and type contract available through the opt-in config', async () => {+ const files = await listTests(localConfig);+ expect(files.length).toBeGreaterThan(0);+ expect(files.every(localTest)).toBe(true);+ expect(files).toEqual(+ expect.arrayContaining([+ 'scripts/stylexMigration/verification/__tests__/cliIntegration.test.ts',+ 'scripts/stylexMigration/verification/gate/gate.test.ts',+ 'scripts/stylexMigration/verification/vitest.config.test.ts',+ 'scripts/stylexMigration/verification/browser/snapshot.test.ts',+ 'scripts/stylexMigration/verification/__tests__/sxArguments.test.ts',+ ]),+ );+ expect(files).not.toContain('scripts/stylexMigration/baseline.test.ts');+ expect(files).not.toContain('src/styles/sx.test.ts');+ });+});diff --git a/scripts/stylexMigration/verification/vitest.config.ts b/scripts/stylexMigration/verification/vitest.config.tsnew file mode 100644index 00000000000..4eb2fe9c5b0--- /dev/null+++ b/scripts/stylexMigration/verification/vitest.config.ts@@ -0,0 +1,17 @@+import { fileURLToPath } from 'node:url';++import { defineConfig } from 'vitest/config';++// Opt-in local tooling tests, separate from the app/server CI projects.+export default defineConfig({+ root: fileURLToPath(new URL('../../../', import.meta.url)),+ test: {+ environment: 'node',+ hookTimeout: 30_000,+ include: ['scripts/stylexMigration/verification/**/*.test.ts'],+ maxWorkers: 2,+ name: 'stylex-local',+ // CLI contract cases start several bounded subprocesses sequentially.+ testTimeout: 60_000,+ },+});diff --git a/src/components/AsyncError/index.tsx b/src/components/AsyncError/index.tsxindex bb989050d75..7241c3dbe27 100644--- a/src/components/AsyncError/index.tsx+++ b/src/components/AsyncError/index.tsx@@ -1,6 +1,8 @@'use client';-import { Button, Center, createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';+import { Button, Center, Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { RotateCwIcon, TriangleAlertIcon } from 'lucide-react';import { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -42,32 +44,23 @@ export interface AsyncErrorProps {variant?: AsyncErrorVariant;}-const styles = createStaticStyles(({ css }) => ({- block: css`- width: 100%;- min-height: 180px;- padding: 32px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorBgContainer};- `,- icon: css`- color: ${cssVar.colorTextTertiary};- `,- inline: css`- padding-block: 8px;- `,- metric: css`- color: ${cssVar.colorTextQuaternary};- `,- page: css`- flex: 1;- width: 100%;- min-height: 320px;- padding: 48px;- `,-}));+const styles = stylex.create({+ block: {+ width: '100%',+ minHeight: '180px',+ padding: '32px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ icon: { color: cssVar.colorTextTertiary },+ inline: { paddingBlock: '8px' },+ metric: { color: cssVar.colorTextQuaternary },+ page: { flex: '1', width: '100%', minHeight: '320px', padding: '48px' },+});const AsyncError = memo<AsyncErrorProps>(({ variant = 'block', error, onRetry, retrying = false, title, description, action }) => {@@ -84,7 +77,12 @@ const AsyncError = memo<AsyncErrorProps>(// ─── metric: a failed marker where a number would render (never a fake $0) ───if (variant === 'metric') {return (- <Flexbox horizontal align={'center'} className={styles.metric} gap={6}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.metric).className}+ gap={6}+ ><Icon icon={TriangleAlertIcon} size={14} /><Text color={cssVar.colorTextQuaternary} fontSize={13}>{t('asyncState.metricLabel')}@@ -107,8 +105,18 @@ const AsyncError = memo<AsyncErrorProps>(// ─── inline: single-line row failure with a retry link ───if (variant === 'inline') {return (- <Flexbox horizontal align={'center'} className={styles.inline} gap={8} justify={'center'}>- <Icon className={styles.icon} icon={TriangleAlertIcon} size={14} />+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.inline).className}+ gap={8}+ justify={'center'}+ >+ <Icon+ className={stylex.props(styles.icon).className}+ icon={TriangleAlertIcon}+ size={14}+ /><Text color={cssVar.colorTextSecondary} fontSize={13}>{heading}</Text>@@ -129,9 +137,12 @@ const AsyncError = memo<AsyncErrorProps>(// ─── page / block: centered hero, sized by variant ───return (- <Center className={variant === 'page' ? styles.page : styles.block} gap={12}>+ <Center+ className={stylex.props(variant === 'page' ? styles.page : styles.block).className}+ gap={12}+ ><Icon- className={styles.icon}+ className={stylex.props(styles.icon).className}icon={TriangleAlertIcon}size={variant === 'page' ? 32 : 24}/>diff --git a/src/components/AvatarUpload/index.tsx b/src/components/AvatarUpload/index.tsxindex d636f81b476..1bc9b6c9536 100644--- a/src/components/AvatarUpload/index.tsx+++ b/src/components/AvatarUpload/index.tsx@@ -1,6 +1,8 @@'use client';-import { Avatar, createStaticStyles, cssVar, Icon, Spin, Upload } from '@lobehub/ui';+import { Avatar, Icon, Spin, Upload } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { PencilIcon, X } from 'lucide-react';import { memo, type ReactNode, useMemo } from 'react';@@ -25,61 +27,49 @@ interface AvatarUploadProps {value?: string;}-const styles = createStaticStyles(({ css }) => ({- delete: css`- cursor: pointer;-- position: absolute;- z-index: 2;- inset-block-start: 2px;- inset-inline-end: 2px;-- display: flex;- align-items: center;- justify-content: center;-- width: 20px;- height: 20px;- border: 2px solid ${cssVar.colorBgContainer};- border-radius: 50%;-- color: ${cssVar.colorTextLightSolid};-- opacity: 0;- background: ${cssVar.colorError};-- transition: opacity ${cssVar.motionDurationMid} ease;- `,- overlay: css`- cursor: pointer;-- position: absolute;- z-index: 1;- inset: 0;-- display: flex;- align-items: center;- justify-content: center;-- border-radius: 8px;-- opacity: 0;- background: ${cssVar.colorBgMask};-- transition: opacity ${cssVar.motionDurationMid} ease;- `,- wrapper: css`- cursor: pointer;- position: relative;- flex: none;- border-radius: 8px;-- &:hover .avatar-edit-overlay,- &:hover .avatar-delete-badge {- opacity: 1;- }- `,-}));+const styles = stylex.create({+ delete: {+ cursor: 'pointer',+ position: 'absolute',+ zIndex: 2,+ insetBlockStart: '2px',+ insetInlineEnd: '2px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '20px',+ borderWidth: '2px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBgContainer,+ borderRadius: '50%',+ color: cssVar.colorTextLightSolid,+ opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 },+ backgroundColor: cssVar.colorError,+ backgroundImage: 'none',+ transition: `opacity ${cssVar.motionDurationMid} ease`,+ },+ overlay: {+ cursor: 'pointer',+ position: 'absolute',+ zIndex: 1,+ inset: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ borderRadius: '8px',+ opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 },+ backgroundColor: cssVar.colorBgMask,+ backgroundImage: 'none',+ transition: `opacity ${cssVar.motionDurationMid} ease`,+ },+ wrapper: {+ cursor: 'pointer',+ position: 'relative',+ flex: 'none',+ borderRadius: '8px',+ },+});const AvatarUpload = memo<AvatarUploadProps>(({@@ -113,9 +103,9 @@ const AvatarUpload = memo<AvatarUploadProps>(return (<Upload maxCount={1} onFiles={([file]) => handleUpload(file)}><Spin size="small" spinning={!!loading}>- <div className={styles.wrapper}>+ <div {...stylex.props(styles.wrapper, stylex.defaultMarker())}><Avatar avatar={value || placeholder} shape={shape} size={size} title={title} />- <div className={`${styles.overlay} avatar-edit-overlay`}>+ <div {...stylex.props(styles.overlay)}><Iconcolor={cssVar.colorTextLightSolid}icon={PencilIcon}@@ -124,7 +114,7 @@ const AvatarUpload = memo<AvatarUploadProps>(</div>{allowDelete && (<div- className={`${styles.delete} avatar-delete-badge`}+ {...stylex.props(styles.delete)}onClick={(event) => {event.stopPropagation();onDelete?.();diff --git a/src/components/BrandWatermark/index.tsx b/src/components/BrandWatermark/index.tsxindex 46a28f82220..9ce5018eac1 100644--- a/src/components/BrandWatermark/index.tsx+++ b/src/components/BrandWatermark/index.tsx@@ -2,23 +2,18 @@import { ORG_NAME, UTM_SOURCE } from '@lobechat/business-const';import { type FlexboxProps } from '@lobehub/ui';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { LobeHub } from '@lobehub/ui/brand';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { OFFICIAL_SITE } from '@/const/url';import { isCustomORG } from '@/const/version';-const styles = createStaticStyles(({ css, cssVar }) => ({- logoLink: css`- line-height: 1;- color: inherit;-- &:hover {- color: ${cssVar.colorLink};- }- `,-}));+const styles = stylex.create({+ logoLink: { lineHeight: 1, color: { 'default': 'inherit', ':hover': cssVar.colorLink } },+});const BrandWatermark = memo<Omit<FlexboxProps, 'children'>>(({ style, ...rest }) => {return (@@ -36,7 +31,7 @@ const BrandWatermark = memo<Omit<FlexboxProps, 'children'>>(({ style, ...rest })<span>{ORG_NAME}</span>) : (<a- className={styles.logoLink}+ {...stylex.props(styles.logoLink)}href={`${OFFICIAL_SITE}?utm_source=${UTM_SOURCE}&utm_content=brand_watermark`}rel="noreferrer"target="_blank"diff --git a/src/components/Branding/ProductLogo/Custom.tsx b/src/components/Branding/ProductLogo/Custom.tsxindex 8b8d9f6eaa4..d4217ad526f 100644--- a/src/components/Branding/ProductLogo/Custom.tsx+++ b/src/components/Branding/ProductLogo/Custom.tsx@@ -1,22 +1,17 @@import { BRANDING_LOGO_URL, BRANDING_NAME } from '@lobechat/business-const';import { type IconType } from '@lobehub/icons';import { type FlexboxProps } from '@lobehub/ui';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { type LobeChatProps } from '@lobehub/ui/brand';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { type ReactNode } from 'react';import { memo } from 'react';import { type ImageProps } from '@/libs/next/Image';import Image from '@/libs/next/Image';-const styles = createStaticStyles(({ css }) => {- return {- extraTitle: css`- font-weight: 300;- white-space: nowrap;- `,- };-});+const styles = stylex.create({ extraTitle: { fontWeight: 300, whiteSpace: 'nowrap' } });const CustomTextLogo = memo<FlexboxProps & { size: number }>(({ size, style, ...rest }) => {return (@@ -118,7 +113,7 @@ const CustomLogo = memo<LobeChatProps>(({ extra, size = 32, className, style, ty<Flexbox horizontal align={'center'} className={className} flex={'none'} {...rest}>{logoComponent}<Divider size={extraSize} style={{ color: cssVar.colorFill }} />- <div className={styles.extraTitle} style={{ fontSize: extraSize }}>+ <div className={stylex.props(styles.extraTitle).className} style={{ fontSize: extraSize }}>{extra}</div></Flexbox>diff --git a/src/components/Cell/Divider.tsx b/src/components/Cell/Divider.tsxindex 1f5f3e9cdc0..13f5f1c6ba9 100644--- a/src/components/Cell/Divider.tsx+++ b/src/components/Cell/Divider.tsx@@ -1,29 +1,32 @@'use client';-import { createStaticStyles } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useIsDark } from '@/hooks/useIsDark';-const styles = createStaticStyles(({ css, cssVar }) => ({- dividerDark: css`- flex: none;- width: 100%;- height: 6px;- background: color-mix(in srgb, ${cssVar.colorFillTertiary} 4%, transparent);- `,- dividerLight: css`- flex: none;- width: 100%;- height: 6px;- background: ${cssVar.colorFillTertiary};- `,-}));+const styles = stylex.create({+ dividerDark: {+ flex: 'none',+ width: '100%',+ height: '6px',+ backgroundColor: `color-mix(in srgb, ${cssVar.colorFillTertiary} 4%, transparent)`,+ backgroundImage: 'none',+ },+ dividerLight: {+ flex: 'none',+ width: '100%',+ height: '6px',+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+});const Divider = memo(() => {const isDarkMode = useIsDark();- return <div className={isDarkMode ? styles.dividerDark : styles.dividerLight} />;+ return <div {...stylex.props(isDarkMode ? styles.dividerDark : styles.dividerLight)} />;});export default Divider;diff --git a/src/components/Cell/index.tsx b/src/components/Cell/index.tsxindex 7cda9845195..963bcf46a45 100644--- a/src/components/Cell/index.tsx+++ b/src/components/Cell/index.tsx@@ -1,22 +1,22 @@import { type IconProps } from '@lobehub/ui';-import { createStaticStyles, cssVar, cx, Flexbox, Icon } from '@lobehub/ui';+import { Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronRight } from 'lucide-react';import { type ReactNode } from 'react';import { memo } from 'react';import Divider from './Divider';-const styles = createStaticStyles(({ css }) => ({- container: css`- position: relative;- border-radius: 0;- font-size: 15px;-- &:active {- background: ${cssVar.colorFillTertiary};- }- `,-}));+const styles = stylex.create({+ container: {+ position: 'relative',+ borderRadius: '0',+ fontSize: '15px',+ backgroundColor: { 'default': null, ':active': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':active': 'none' },+ },+});export interface CellProps {icon?: IconProps['icon'];@@ -33,7 +33,7 @@ const Cell = memo<CellProps>(({ label, icon, onClick, type }) => {<Flexboxhorizontalalign={'center'}- className={cx(styles.container)}+ className={stylex.props(styles.container).className}gap={12}justify={'space-between'}padding={16}diff --git a/src/components/ChangelogModal/VersionTag.tsx b/src/components/ChangelogModal/VersionTag.tsxindex c759d8d6a23..c0d1a3b09e4 100644--- a/src/components/ChangelogModal/VersionTag.tsx+++ b/src/components/ChangelogModal/VersionTag.tsx@@ -1,23 +1,26 @@'use client';-import { createStaticStyles, Tag } from '@lobehub/ui';+import { Tag } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- tag: css`- margin: 0;- padding-block: 4px;- padding-inline: 12px;- border-radius: 16px;-- color: ${cssVar.colorTextSecondary};- `,- };+const styles = stylex.create({+ tag: {+ margin: '0',+ paddingBlock: '4px',+ paddingInline: '12px',+ borderRadius: '16px',+ color: cssVar.colorTextSecondary,+ },});const VersionTag = memo<{ range: string[] }>(({ range }) => {- return <Tag className={styles.tag}>{range.map((v) => 'v' + v).join(' ~ ')}</Tag>;+ return (+ <Tag className={stylex.props(styles.tag).className}>+ {range.map((v) => 'v' + v).join(' ~ ')}+ </Tag>+ );});export default VersionTag;diff --git a/src/components/ChatGroupWizard/ChatGroupWizard.tsx b/src/components/ChatGroupWizard/ChatGroupWizard.tsxindex da400b1bb90..ade26d33706 100644--- a/src/components/ChatGroupWizard/ChatGroupWizard.tsx+++ b/src/components/ChatGroupWizard/ChatGroupWizard.tsx@@ -4,9 +4,6 @@ import {Accordion,Button,Checkbox,- createStaticStyles,- cssVar,- cx,Empty,Flexbox,List,@@ -17,6 +14,8 @@ import {Text,Tooltip,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { omit } from 'es-toolkit/compat';import { Users } from 'lucide-react';import { type ChangeEvent } from 'react';@@ -30,23 +29,89 @@ import GroupAvatar from '@/features/GroupAvatar';import ModelSelect from '@/features/ModelSelect';import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';import { useSessionStore } from '@/store/session';+import { sx } from '@/styles/sx';import { type LobeAgentSession } from '@/types/session';import { LobeSessionType } from '@/types/session';import { type GroupTemplate } from './templates';import { useGroupTemplates } from './templates';+const styles = stylex.create({+ container: {+ display: 'flex',+ flexDirection: 'row',+ height: '500px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ },+ description: {+ fontSize: '12px',+ lineHeight: 1.2,+ color: cssVar.colorTextSecondary,+ },+ hostCard: {+ marginBlockStart: cssVar.paddingSM,+ marginInline: cssVar.paddingSM,+ padding: cssVar.padding,+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ leftColumn: {+ userSelect: 'none',+ overflowY: 'auto',+ flex: '1',+ padding: '0',+ borderInlineEndWidth: '1px',+ borderInlineEndStyle: 'solid',+ borderInlineEndColor: cssVar.colorBorderSecondary,+ },+ listItem: {+ cursor: 'pointer',+ position: 'relative',+ marginBlock: '2px',+ padding: cssVar.paddingSM,+ borderRadius: cssVar.borderRadius,+ transition: 'all 0.2s ease',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ memberDescription: {+ display: 'block',+ paddingInlineEnd: '48px',+ },+ modelSelectDisabled: {+ pointerEvents: 'none',+ },+ rightColumn: {+ overflowY: 'auto',+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ padding: '0',+ },+ title: {+ fontSize: '14px',+ fontWeight: 500,+ },+});++const memberDescriptionClass = stylex.props(styles.description, styles.memberDescription).className;+const TemplateItem = memo<{- cx: (..._args: any[]) => string;isSelected: boolean;onToggle: (_templateId: string) => void;- styles: Record<string, string>;template: GroupTemplate;-}>(({ template, isSelected, onToggle, styles, cx }) => {+}>(({ template, isSelected, onToggle }) => {const { t } = useTranslation('chat');return (- <div className={cx(styles.listItem)} onClick={() => onToggle(template.id)}>+ <div {...stylex.props(styles.listItem)} onClick={() => onToggle(template.id)}><Flexbox horizontal align="center" gap={12} width="100%"><Checkboxchecked={isSelected}@@ -63,8 +128,8 @@ const TemplateItem = memo<{}))}/><Flexbox flex={1} gap={2}>- <Text className={styles.title}>{template.title}</Text>- <Text ellipsis className={styles.description}>+ <Text className={stylex.props(styles.title).className}>{template.title}</Text>+ <Text ellipsis className={stylex.props(styles.description).className}>{template.description}</Text><Flexbox horizontal align="center" gap={4}>@@ -84,11 +149,9 @@ const TemplateItem = memo<{const ExistingMemberItem = memo<{agent: LobeAgentSession;- cx: (..._args: any[]) => string;isSelected: boolean;onToggle: (_agentId: string) => void;- styles: Record<string, string>;-}>(({ agent, isSelected, onToggle, styles, cx }) => {+}>(({ agent, isSelected, onToggle }) => {const { t } = useTranslation(['chat', 'common']);const agentId = agent.config?.id;const title = agent.meta?.title || t('defaultSession', { ns: 'common' });@@ -99,7 +162,7 @@ const ExistingMemberItem = memo<{if (!agentId) return null;return (- <div className={cx(styles.listItem)} onClick={() => onToggle(agentId)}>+ <div {...stylex.props(styles.listItem)} onClick={() => onToggle(agentId)}><Flexbox horizontal align="center" gap={12} width="100%"><Checkboxchecked={isSelected}@@ -115,9 +178,9 @@ const ExistingMemberItem = memo<{size={40}/><Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>- <Text className={styles.title}>{title}</Text>+ <Text className={stylex.props(styles.title).className}>{title}</Text>{description && (- <Text ellipsis className={styles.description}>+ <Text ellipsis className={stylex.props(styles.description).className}>{description}</Text>)}@@ -127,78 +190,6 @@ const ExistingMemberItem = memo<{);});-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- display: flex;- flex-direction: row;-- height: 500px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadius};- `,- description: css`- font-size: 12px;- line-height: 1.2;- color: ${cssVar.colorTextSecondary};- `,- hostCard: css`- margin-block-start: ${cssVar.paddingSM};- margin-inline: ${cssVar.paddingSM};- padding: ${cssVar.padding};- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorFillTertiary};- `,- leftColumn: css`- user-select: none;-- overflow-y: auto;- flex: 1;-- padding: 0;- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};- `,- listHeader: css`- padding: 0;- color: ${cssVar.colorTextDescription};- `,- listItem: css`- cursor: pointer;-- position: relative;-- margin-block: 2px;- padding: ${cssVar.paddingSM} !important;- border-radius: ${cssVar.borderRadius};-- transition: all 0.2s ease;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- memberDescription: css`- display: block;- padding-inline-end: 48px;- `,- modelSelectDisabled: css`- pointer-events: none;- `,- rightColumn: css`- overflow-y: auto;- display: flex;- flex: 1;- flex-direction: column;-- padding: 0;- `,- title: css`- font-size: 14px;- font-weight: 500;- `,-}));-export interface ChatGroupWizardProps {/*** External loading state for template creation (controlled by parent)@@ -233,8 +224,6 @@ const ChatGroupWizard = memo<ChatGroupWizardProps>([agentSessions],);- const memberDescriptionClass = cx(styles.description, styles.memberDescription);-const defaultModel = useMemo(() => {if (enabledModels.length > 0 && enabledModels[0].children.length > 0) {const firstProvider = enabledModels[0];@@ -491,7 +480,7 @@ const ChatGroupWizard = memo<ChatGroupWizardProps>(}).filter((item): item is NonNullable<typeof item> => Boolean(item));- }, [selectedAgents, agentSessions, t, handleRemoveAgent, memberDescriptionClass]);+ }, [selectedAgents, agentSessions, t, handleRemoveAgent]);const normalizedHostModelConfig = useMemo(() => {const model = hostModelConfig.model ?? defaultModel.model;@@ -575,8 +564,8 @@ const ChatGroupWizard = memo<ChatGroupWizardProps>(}onCancel={handleCancel}>- <Flexbox horizontal className={styles.container}>- <Flexbox className={styles.leftColumn} flex={1} gap={12}>+ <Flexbox horizontal className={stylex.props(styles.container).className}>+ <Flexbox className={stylex.props(styles.leftColumn).className} flex={1} gap={12}><SearchBarallowClearplaceholder={t('memberSelection.searchAgents')}@@ -610,10 +599,8 @@ const ChatGroupWizard = memo<ChatGroupWizardProps>(<Flexbox gap={4}>{filteredTemplates.map((template) => (<TemplateItem- cx={cx}isSelected={selectedTemplate === template.id}key={template.id}- styles={styles}template={template}onToggle={handleTemplateToggle}/>@@ -641,10 +628,8 @@ const ChatGroupWizard = memo<ChatGroupWizardProps>({filteredAgents.map((agent) => (<ExistingMemberItemagent={agent}- cx={cx}isSelected={selectedAgents.includes(agent.config?.id || '')}key={agent.id}- styles={styles}onToggle={handleAgentToggle}/>))}@@ -662,9 +647,14 @@ const ChatGroupWizard = memo<ChatGroupWizardProps>(</Flexbox></Flexbox>- <Flexbox className={styles.rightColumn} flex={1}>+ <Flexbox className={stylex.props(styles.rightColumn).className} flex={1}><Flexbox flex={1} gap={16} style={{ overflowY: 'auto' }}>- <Flexbox horizontal align="center" className={styles.hostCard} gap={12}>+ <Flexbox+ horizontal+ align="center"+ className={stylex.props(styles.hostCard).className}+ gap={12}+ ><Flexbox flex={1} gap={2}><Textstyle={{ fontSize: 14, fontWeight: 500 }}@@ -681,8 +671,9 @@ const ChatGroupWizard = memo<ChatGroupWizardProps>(</Flexbox><Flexbox horizontal align="center" gap={12}><div- className={cx(isHostRemoved && styles.modelSelectDisabled)}- style={{ opacity: isHostRemoved ? 0.6 : 1 }}+ {...sx([isHostRemoved && styles.modelSelectDisabled], undefined, {+ opacity: isHostRemoved ? 0.6 : 1,+ })}><ModelSelectrequiredAbilities={['functionCall']}diff --git a/src/components/CodeEditorPane/StatusBar.tsx b/src/components/CodeEditorPane/StatusBar.tsxindex 8a87aa7a229..e8349aac766 100644--- a/src/components/CodeEditorPane/StatusBar.tsx+++ b/src/components/CodeEditorPane/StatusBar.tsx@@ -1,55 +1,48 @@'use client';-import { createStaticStyles, cssVar, Flexbox, Tooltip } from '@lobehub/ui';+import { Flexbox, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { useTranslation } from 'react-i18next';import type { IndentStyle } from './indent';-const styles = createStaticStyles(({ css }) => ({- bar: css`- flex-shrink: 0;-- height: 24px;- padding-inline: 10px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};-- font-size: 11px;- line-height: 1;- color: ${cssVar.colorTextTertiary};-- background: ${cssVar.colorBgContainer};- `,- button: css`- cursor: pointer;-- height: 18px;- padding-inline: 6px;- border: none;- border-radius: ${cssVar.borderRadiusSM};-- font-size: 11px;- line-height: 1;- color: inherit;- white-space: nowrap;-- background: none;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,- item: css`- padding-inline: 6px;- white-space: nowrap;- `,- readOnly: css`- padding-inline: 6px;- border-radius: ${cssVar.borderRadiusSM};- color: ${cssVar.colorTextSecondary};- background: ${cssVar.colorFillTertiary};- `,-}));+const styles = stylex.create({+ bar: {+ flexShrink: 0,+ height: '24px',+ paddingInline: '10px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ fontSize: '11px',+ lineHeight: 1,+ color: cssVar.colorTextTertiary,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ button: {+ cursor: 'pointer',+ height: '18px',+ paddingInline: '6px',+ borderStyle: 'none',+ borderRadius: cssVar.borderRadiusSM,+ fontSize: '11px',+ lineHeight: 1,+ color: { 'default': 'inherit', ':hover': cssVar.colorText },+ whiteSpace: 'nowrap',+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': 'none', ':hover': 'none' },+ },+ item: { paddingInline: '6px', whiteSpace: 'nowrap' },+ readOnly: {+ paddingInline: '6px',+ borderRadius: cssVar.borderRadiusSM,+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+});export interface CursorPosition {column: number;@@ -78,19 +71,24 @@ const StatusBar = ({const { t } = useTranslation('components');return (- <Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.bar).className}+ justify={'space-between'}+ ><Flexbox horizontal align={'center'}>- {readOnly && <span className={styles.readOnly}>{t('CodeEditorPane.readOnly')}</span>}+ {readOnly && <span {...stylex.props(styles.readOnly)}>{t('CodeEditorPane.readOnly')}</span>}</Flexbox><Flexbox horizontal align={'center'}>{cursor && (- <span className={styles.item}>+ <span {...stylex.props(styles.item)}>{t('CodeEditorPane.cursor', { column: cursor.column, line: cursor.line })}{cursor.selectionLength > 0 &&` ${t('CodeEditorPane.selected', { length: cursor.selectionLength })}`}</span>)}- <span className={styles.item}>+ <span {...stylex.props(styles.item)}>{t(indent.useTabs ? 'CodeEditorPane.tabSize' : 'CodeEditorPane.spaces', {size: indent.size,})}@@ -98,14 +96,14 @@ const StatusBar = ({<Tooltip title={t('CodeEditorPane.toggleWordWrap')}><buttonaria-pressed={lineWrapping}- className={styles.button}+ {...stylex.props(styles.button)}type={'button'}onClick={() => onLineWrappingChange(!lineWrapping)}>{t(lineWrapping ? 'CodeEditorPane.wrapOn' : 'CodeEditorPane.wrapOff')}</button></Tooltip>- <span className={styles.item}>{languageLabel}</span>+ <span {...stylex.props(styles.item)}>{languageLabel}</span></Flexbox></Flexbox>);diff --git a/src/components/CodeEditorPane/index.tsx b/src/components/CodeEditorPane/index.tsxindex fac25353f03..cb6dae4a426 100644--- a/src/components/CodeEditorPane/index.tsx+++ b/src/components/CodeEditorPane/index.tsx@@ -13,7 +13,7 @@ import { useIsDark } from '@/hooks/useIsDark';import { detectIndentStyle } from './indent';import { getEditorLanguage } from './language';import StatusBar, { type CursorPosition } from './StatusBar';-import { styles } from './style';+import styles from './style.module.css';/*** The parts of the underlying CodeMirror 6 view that the compat wrapper doesdiff --git a/src/components/CodeEditorPane/style.module.css b/src/components/CodeEditorPane/style.module.cssnew file mode 100644index 00000000000..bf4360ff24f--- /dev/null+++ b/src/components/CodeEditorPane/style.module.css@@ -0,0 +1,173 @@+/*+ * The editor chrome. Selectors are one level deeper than the CodeMirror theme+ * emits (`.cm-editor.cm-editor`) so these rules win regardless of which style+ * sheet the browser inserted last.+ */+.container {+ overflow: hidden;+ display: flex;+ flex-direction: column;++ width: 100%;+ height: 100%;++ background: var(--lobe-color-bg-container);+}++.container :global(.cm-textarea) {+ height: 0;+ opacity: 0;+}++.editorArea {+ overflow: hidden;+ flex: 1;+ min-height: 0;+}++.editorArea :global(.cm-editor) {+ height: 100%;+ padding-block: 0;+}++/* Own the vertical scroll here rather than in an outer wrapper, so the+ gutter and the fold markers stay pinned while the text scrolls. */+.editorArea :global(.cm-scroller) {+ overflow: auto;+ font-variant-ligatures: none;+ line-height: 20px;+}++.editorArea :global(.cm-editor.cm-editor) span,+.editorArea :global(.cm-editor.cm-editor) :global(.cm-line) {+ font-family: var(--lobe-font-family-code);+ font-size: 12px;+ line-height: 20px;+}++/* Clicking below the last line should still land in the document, the way+ every desktop editor behaves. */+.editorArea :global(.cm-content) {+ min-height: 100%;+ padding-block: 8px;+}++.editorArea :global(.cm-gutters) {+ user-select: none;+ border-inline-end: 1px solid var(--lobe-color-border-secondary);+ background: var(--lobe-color-bg-container);+}++/* The bundled theme pads every line by 12px, which lands on top of the+ gutter's own trailing space and pushes the code away from its number. */+.editorArea :global(.cm-editor.cm-editor) :global(.cm-line) {+ padding-inline: 6px 12px;+}++/* The number sits closer to the code than to the pane edge: it labels the+ line, so the eye should travel from it rightwards, not across a gap. */+.editorArea :global(.cm-lineNumbers) :global(.cm-gutterElement) {+ min-width: 22px;+ padding-inline: 16px 2px;++ font-family: var(--lobe-font-family-code);+ font-size: 11px;+ font-variant-numeric: tabular-nums;+ line-height: 20px;+ color: var(--lobe-color-text-quaternary);+}++/* The bundle carries a base style that paints the caret's line and gutter a+ hard-coded near-white, in dark mode too, and qualifies both of them with+ the editor class. Naming that class twice is what outranks it: otherwise+ the focused line reads as a white band with its punctuation washed out. */+.editorArea :global(.cm-editor.cm-editor) :global(.cm-activeLineGutter) {+ color: var(--lobe-color-text) !important;+ background: transparent;+}++.editorArea :global(.cm-editor.cm-editor) :global(.cm-activeLine) {+ background: var(--lobe-color-fill-quaternary);+}++/* A focused editor gets the stronger cue; an unfocused one keeps a faint+ marker so the caret position is still findable after a click elsewhere. */+.editorArea :global(.cm-editor.cm-editor:not(.cm-focused)) :global(.cm-activeLine) {+ background: transparent;+}++.editorArea :global(.cm-matchingBracket),+.editorArea :global(.cm-editor.cm-focused) :global(.cm-matchingBracket) {+ border-radius: 2px;+ background: var(--lobe-color-fill-secondary);+ outline: 1px solid var(--lobe-color-border);+}++.editorArea :global(.cm-nonmatchingBracket) {+ border-radius: 2px;+ background: var(--lobe-color-error-bg);+}++/* Fold markers render as empty divs; the chevron is entirely ours. */+.editorArea :global(.gutter-fold-open),+.editorArea :global(.gutter-fold-close) {+ cursor: pointer;++ display: flex;+ align-items: center;+ justify-content: center;++ width: 13px;+ height: 20px;++ color: var(--lobe-color-text-tertiary);++ transition: opacity 0.15s;+}++.editorArea :global(.gutter-fold-open)::before,+.editorArea :global(.gutter-fold-close)::before {+ content: '';++ width: 5px;+ height: 5px;+ border-block-end: 1.4px solid currentcolor;+ border-inline-end: 1.4px solid currentcolor;+}++/* Pointing down: this range is expanded. Only offered on gutter hover, so+ the gutter is not a column of permanent arrows. */+.editorArea :global(.gutter-fold-open) {+ opacity: 0;+}++.editorArea :global(.gutter-fold-open)::before {+ transform: translateY(-1px) rotate(45deg);+}++/* Pointing right: content is hidden here, so this one always shows. */+.editorArea :global(.gutter-fold-close)::before {+ transform: translateX(-2px) rotate(-45deg);+}++.editorArea :global(.gutter-fold-open):hover,+.editorArea :global(.gutter-fold-close):hover {+ color: var(--lobe-color-text);+}++.editorArea :global(.cm-gutters):hover :global(.gutter-fold-open) {+ opacity: 1;+}++.editorArea :global(.cm-editor.cm-editor) :global(.cm-foldPlaceholder) {+ width: auto;+ height: auto;+ padding-inline: 6px;+ border: 1px solid var(--lobe-color-border-secondary);+ border-radius: 4px;++ font-size: 11px;+ color: var(--lobe-color-text-tertiary);++ background: var(--lobe-color-fill-tertiary);+}diff --git a/src/components/CodeEditorPane/style.ts b/src/components/CodeEditorPane/style.tsdeleted file mode 100644index e0a4b585a0c..00000000000--- a/src/components/CodeEditorPane/style.ts+++ /dev/null@@ -1,176 +0,0 @@-import { createStaticStyles, cssVar } from '@lobehub/ui';--/**- * The editor chrome. Selectors are one level deeper than the CodeMirror theme- * emits (`.cm-editor.cm-editor`) so these rules win regardless of which style- * sheet the browser inserted last.- */-export const styles = createStaticStyles(({ css }) => ({- container: css`- overflow: hidden;- display: flex;- flex-direction: column;-- width: 100%;- height: 100%;-- background: ${cssVar.colorBgContainer};-- .cm-textarea {- height: 0;- opacity: 0;- }- `,-- editorArea: css`- overflow: hidden;- flex: 1;- min-height: 0;-- .cm-editor {- height: 100%;- padding-block: 0;- }-- /* Own the vertical scroll here rather than in an outer wrapper, so the- gutter and the fold markers stay pinned while the text scrolls. */- .cm-scroller {- overflow: auto;- font-variant-ligatures: none;- line-height: 20px;- }-- .cm-editor.cm-editor span,- .cm-editor.cm-editor .cm-line {- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- line-height: 20px;- }-- /* Clicking below the last line should still land in the document, the way- every desktop editor behaves. */- .cm-content {- min-height: 100%;- padding-block: 8px;- }-- .cm-gutters {- user-select: none;- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};- background: ${cssVar.colorBgContainer};- }-- /* The bundled theme pads every line by 12px, which lands on top of the- gutter's own trailing space and pushes the code away from its number. */- .cm-editor.cm-editor .cm-line {- padding-inline: 6px 12px;- }-- /* The number sits closer to the code than to the pane edge: it labels the- line, so the eye should travel from it rightwards, not across a gap. */- .cm-lineNumbers .cm-gutterElement {- min-width: 22px;- padding-inline: 16px 2px;-- font-family: ${cssVar.fontFamilyCode};- font-size: 11px;- font-variant-numeric: tabular-nums;- line-height: 20px;- color: ${cssVar.colorTextQuaternary};- }-- /* The bundle carries a base style that paints the caret's line and gutter a- hard-coded near-white, in dark mode too, and qualifies both of them with- the editor class. Naming that class twice is what outranks it: otherwise- the focused line reads as a white band with its punctuation washed out. */- .cm-editor.cm-editor .cm-activeLineGutter {- color: ${cssVar.colorText} !important;- background: transparent;- }-- .cm-editor.cm-editor .cm-activeLine {- background: ${cssVar.colorFillQuaternary};- }-- /* A focused editor gets the stronger cue; an unfocused one keeps a faint- marker so the caret position is still findable after a click elsewhere. */- .cm-editor.cm-editor:not(.cm-focused) .cm-activeLine {- background: transparent;- }-- .cm-matchingBracket,- .cm-editor.cm-focused .cm-matchingBracket {- border-radius: 2px;- background: ${cssVar.colorFillSecondary};- outline: 1px solid ${cssVar.colorBorder};- }-- .cm-nonmatchingBracket {- border-radius: 2px;- background: ${cssVar.colorErrorBg};- }-- /* Fold markers render as empty divs; the chevron is entirely ours. */- .gutter-fold-open,- .gutter-fold-close {- cursor: pointer;-- display: flex;- align-items: center;- justify-content: center;-- width: 13px;- height: 20px;-- color: ${cssVar.colorTextTertiary};-- transition: opacity 0.15s;-- &::before {- content: '';-- width: 5px;- height: 5px;- border-block-end: 1.4px solid currentcolor;- border-inline-end: 1.4px solid currentcolor;- }- }-- /* Pointing down: this range is expanded. Only offered on gutter hover, so- the gutter is not a column of permanent arrows. */- .gutter-fold-open {- opacity: 0;-- &::before {- transform: translateY(-1px) rotate(45deg);- }- }-- /* Pointing right: content is hidden here, so this one always shows. */- .gutter-fold-close::before {- transform: translateX(-2px) rotate(-45deg);- }-- .gutter-fold-open:hover,- .gutter-fold-close:hover {- color: ${cssVar.colorText};- }-- .cm-gutters:hover .gutter-fold-open {- opacity: 1;- }-- .cm-editor.cm-editor .cm-foldPlaceholder {- width: auto;- height: auto;- padding-inline: 6px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 4px;-- font-size: 11px;- color: ${cssVar.colorTextTertiary};-- background: ${cssVar.colorFillTertiary};- }- `,-}));diff --git a/src/components/CollapsibleContent/index.tsx b/src/components/CollapsibleContent/index.tsxindex 168e1724c35..d9274e0b2a4 100644--- a/src/components/CollapsibleContent/index.tsx+++ b/src/components/CollapsibleContent/index.tsx@@ -1,6 +1,7 @@'use client';-import { createStaticStyles } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronDownIcon, ChevronUpIcon } from 'lucide-react';import type { CSSProperties, ReactNode } from 'react';import { memo, useRef } from 'react';@@ -17,53 +18,31 @@ const FADE_RATIO = 0.2;// handful of extra pixels.const OVERFLOW_THRESHOLD = 32;-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- position: relative;- width: 100%;- `,- contentCollapsed: css`- overflow: hidden;-- /* Fade height scales with the clamp — a fixed 48px would swallow most of a- three-line preview and leave the last line unreadable. */- mask-image: linear-gradient(to bottom, #000 calc(100% - var(--collapse-fade)), transparent);- `,- contentExpanded: css`- overflow: visible;- `,- toggleButton: css`- cursor: pointer;-- display: inline-flex;- gap: 4px;- align-items: center;-- block-size: 24px;- padding-inline: 10px;- border: none;- border-radius: 12px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillQuaternary};-- transition:- color 150ms ${cssVar.motionEaseOut},- background 150ms ${cssVar.motionEaseOut};-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,- toggleWrapper: css`- display: flex;- justify-content: center;- margin-block-start: 6px;- `,-}));+const styles = stylex.create({+ container: { position: 'relative', width: '100%' },+ contentCollapsed: {+ overflow: 'hidden',+ maskImage: 'linear-gradient(to bottom, #000 calc(100% - var(--collapse-fade)), transparent)',+ },+ contentExpanded: { overflow: 'visible' },+ toggleButton: {+ cursor: 'pointer',+ display: 'inline-flex',+ gap: '4px',+ alignItems: 'center',+ blockSize: '24px',+ paddingInline: '10px',+ borderStyle: 'none',+ borderRadius: '12px',+ fontSize: '12px',+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ backgroundColor: { 'default': cssVar.colorFillQuaternary, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': 'none', ':hover': 'none' },+ transition: `color 150ms ${cssVar.motionEaseOut},+ background 150ms ${cssVar.motionEaseOut}`,+ },+ toggleWrapper: { display: 'flex', justifyContent: 'center', marginBlockStart: '6px' },+});interface CollapsibleContentProps {children: ReactNode;@@ -121,10 +100,12 @@ const CollapsibleContent = memo<CollapsibleContentProps>(});return (- <div className={styles.container}>+ <div {...stylex.props(styles.container)}><div- className={isCollapsed ? styles.contentCollapsed : styles.contentExpanded}ref={contentRef}+ className={+ stylex.props(isCollapsed ? styles.contentCollapsed : styles.contentExpanded).className+ }style={isCollapsed? ({@@ -137,10 +118,10 @@ const CollapsibleContent = memo<CollapsibleContentProps>({children}</div>{shouldCollapse && (- <div className={styles.toggleWrapper}>+ <div {...stylex.props(styles.toggleWrapper)}><buttonaria-expanded={!collapsed}- className={styles.toggleButton}+ {...stylex.props(styles.toggleButton)}type="button"onClick={toggle}>diff --git a/src/components/CommandLine/index.tsx b/src/components/CommandLine/index.tsxindex 30b0a5213ed..5179671ee8b 100644--- a/src/components/CommandLine/index.tsx+++ b/src/components/CommandLine/index.tsx@@ -1,44 +1,45 @@'use client';-import { CopyButton, createStaticStyles, cssVar } from '@lobehub/ui';+import { CopyButton } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';-const styles = createStaticStyles(({ css }) => ({- codeBlock: css`- display: flex;- flex: none;- gap: 12px;- align-items: center;-- min-width: 0;- padding-block: 12px;- padding-inline: 16px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadius};-- background: ${cssVar.colorFillQuaternary};- `,- command: css`- overflow: hidden;- flex: 1;-- min-width: 0;-- font-family: ${cssVar.fontFamilyCode};- font-size: ${cssVar.fontSizeSM};- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;- `,-}));+const styles = stylex.create({+ codeBlock: {+ display: 'flex',+ flex: 'none',+ gap: '12px',+ alignItems: 'center',+ minWidth: '0',+ paddingBlock: '12px',+ paddingInline: '16px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ command: {+ overflow: 'hidden',+ flex: '1',+ minWidth: '0',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: cssVar.fontSizeSM,+ color: cssVar.colorText,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+});interface CommandLineProps {command: string;}const CommandLine = memo<CommandLineProps>(({ command }) => (- <div className={styles.codeBlock}>- <code className={styles.command}>{command}</code>+ <div {...stylex.props(styles.codeBlock)}>+ <code {...stylex.props(styles.command)}>{command}</code><CopyButton content={command} size={'small'} /></div>));diff --git a/src/components/CommentList/CommentItem.module.css b/src/components/CommentList/CommentItem.module.cssnew file mode 100644index 00000000000..a4a9ec18005--- /dev/null+++ b/src/components/CommentList/CommentItem.module.css@@ -0,0 +1,28 @@+.content {+ font-size: 16px;+ line-height: 1.56;+ color: var(--lobe-color-text-secondary);+}++.content p {+ margin-block: 0;+}++.content p + p {+ margin-block-start: 0.72em;+}++.content a {+ color: var(--lobe-color-link);+}++.content strong {+ font-weight: 600;+ color: var(--lobe-color-text);+}++@media (max-width: 575.98px) {+ .content {+ font-size: 15px;+ }+}diff --git a/src/components/CommentList/CommentItem.tsx b/src/components/CommentList/CommentItem.tsxindex f817c079cf9..83535fdcf84 100644--- a/src/components/CommentList/CommentItem.tsx+++ b/src/components/CommentList/CommentItem.tsx@@ -1,82 +1,52 @@'use client';import { AgentIcon } from '@lobehub/icons';-import { Avatar, createStaticStyles, Flexbox, Markdown, responsive, Text } from '@lobehub/ui';+import { Avatar, Flexbox, Markdown, 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 { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import Rate from '@/components/RatingOverview/Rate';import { type SkillCommentItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => ({- author: css`- font-size: 16px;- font-weight: 700;- line-height: 1.2;- color: ${cssVar.colorText};- word-break: break-word;-- ${responsive.sm} {- font-size: 15px;- }- `,- avatar: css`- flex: none;- line-height: 0;- `,- card: css`- padding-block: 22px;- padding-inline: 24px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 22px;-- background: ${cssVar.colorBgContainer};-- ${responsive.sm} {- padding-block: 18px;- padding-inline: 16px;- border-radius: 18px;- }- `,- content: css`- font-size: 16px;- line-height: 1.56;- color: ${cssVar.colorTextSecondary};-- p {- margin-block: 0;- }-- p + p {- margin-block-start: 0.72em;- }-- a {- color: ${cssVar.colorLink};- }-- strong {- font-weight: 600;- color: ${cssVar.colorText};- }-- ${responsive.sm} {- font-size: 15px;- }- `,- date: css`- flex: none;-- font-size: 13px;- font-weight: 500;- line-height: 1.3;- color: ${cssVar.colorTextDescription};- white-space: nowrap;- `,- rate: css`- line-height: 1;- `,-}));+import moduleStyles from './CommentItem.module.css';++const styles = stylex.create({+ author: {+ fontSize: { default: '16px', [media.sm]: '15px' },+ fontWeight: 700,+ lineHeight: 1.2,+ color: cssVar.colorText,+ wordBreak: 'break-word',+ },+ avatar: {+ flex: 'none',+ lineHeight: 0,+ },+ card: {+ paddingBlock: { default: '22px', [media.sm]: '18px' },+ paddingInline: { default: '24px', [media.sm]: '16px' },+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: { default: '22px', [media.sm]: '18px' },+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ date: {+ flex: 'none',+ fontSize: '13px',+ fontWeight: 500,+ lineHeight: 1.3,+ color: cssVar.colorTextDescription,+ whiteSpace: 'nowrap',+ },+ rate: {+ lineHeight: 1,+ },+});const CommentItem = memo<{ item: SkillCommentItem }>(({ item }) => {const { i18n, t } = useTranslation('discover');@@ -117,20 +87,25 @@ const CommentItem = memo<{ item: SkillCommentItem }>(({ item }) => {}, [author?.avatar, author?.sourceType, author?.type, authorName]);return (- <Flexbox className={styles.card} gap={14}>+ <Flexbox className={stylex.props(styles.card).className} gap={14}><Flexbox horizontal align={'center'} gap={12} justify={'space-between'} wrap={'wrap'}><Flexbox horizontal align={'center'} gap={12}>- <div className={styles.avatar}>{avatar}</div>+ <div {...stylex.props(styles.avatar)}>{avatar}</div><Flexbox gap={6}>- <Text className={styles.author}>{authorName}</Text>+ <Text className={stylex.props(styles.author).className}>{authorName}</Text>{typeof item.rating === 'number' && (- <Rate className={styles.rate} gap={3} size={16} value={item.rating} />+ <Rate+ className={stylex.props(styles.rate).className}+ gap={3}+ size={16}+ value={item.rating}+ />)}</Flexbox></Flexbox>- <Text className={styles.date}>{createdAt}</Text>+ <Text className={stylex.props(styles.date).className}>{createdAt}</Text></Flexbox>- <Markdown className={styles.content} variant={'chat'}>+ <Markdown className={moduleStyles.content} variant={'chat'}>{item.content}</Markdown></Flexbox>diff --git a/src/components/DataStyleModal/index.tsx b/src/components/DataStyleModal/index.tsxindex 2c30c66913a..2e9f0414ea1 100644--- a/src/components/DataStyleModal/index.tsx+++ b/src/components/DataStyleModal/index.tsx@@ -1,47 +1,9 @@-import { createStaticStyles, Flexbox, Icon } from '@lobehub/ui';+import { Flexbox, Icon } from '@lobehub/ui';import { type LucideIcon } from 'lucide-react';import { type ReactNode } from 'react';import { memo } from 'react';import ImperativeModal from '@/components/ImperativeModal';-import { useIsDark } from '@/hooks/useIsDark';--const prefixCls = 'ant';--const styles = createStaticStyles(({ css, cssVar }) => ({- modalTitleDark: css`- &.${prefixCls}-modal-header {- height: 80px;- background:- linear-gradient(- 180deg,- color-mix(in srgb, ${cssVar.colorBgElevated} 0%, transparent),- ${cssVar.colorBgContainer} 80px- ),- fixed 0 0 /10px 10px radial-gradient(${cssVar.colorFill} 1px, transparent 0);- }-- & .${prefixCls}-modal-title {- font-size: 24px;- }- `,- modalTitleLight: css`- &.${prefixCls}-modal-header {- height: 80px;- background:- linear-gradient(- 180deg,- color-mix(in srgb, ${cssVar.colorBgElevated} 0%, transparent),- ${cssVar.colorBgContainer} 140px- ),- fixed 0 0 /10px 10px radial-gradient(${cssVar.colorFill} 1px, transparent 0);- }-- & .${prefixCls}-modal-title {- font-size: 24px;- }- `,-}));interface DataStyleModalProps {children: ReactNode;@@ -55,8 +17,6 @@ interface DataStyleModalProps {const DataStyleModal = memo<DataStyleModalProps>(({ icon, onOpenChange, title, open, children, width = 550, height }) => {- const isDarkMode = useIsDark();-return (<ImperativeModalcentered@@ -66,9 +26,6 @@ const DataStyleModal = memo<DataStyleModalProps>(height={height}open={open}width={width}- classNames={{- header: isDarkMode ? styles.modalTitleDark : styles.modalTitleLight,- }}title={<Flexbox horizontal gap={8}><Icon icon={icon} />diff --git a/src/components/Descriptions/index.tsx b/src/components/Descriptions/index.tsxindex 60b508e229f..513a79af561 100644--- a/src/components/Descriptions/index.tsx+++ b/src/components/Descriptions/index.tsx@@ -1,30 +1,37 @@import { type GridProps, type IconProps } from '@lobehub/ui';-import { createStaticStyles, cssVar, cx, Flexbox, Grid, Icon, responsive, Text } from '@lobehub/ui';+import { cx, Flexbox, Grid, Icon, 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';+import { sx } from '@/styles/sx';+import CopyableLabel from '../CopyableLabel';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- bordered: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- ${responsive.sm} {- background: ${cssVar.colorBgContainer};- }- `,- cell: css`- overflow: hidden;- box-shadow: 0 0 0 0.5px ${cssVar.colorBorderSecondary};- `,- label: css`- overflow: hidden;- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};- background: ${cssVar.colorFillQuaternary};- `,- };+const styles = stylex.create({+ bordered: {+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: { default: null, [media.sm]: cssVar.colorBgContainer },+ backgroundImage: { default: null, [media.sm]: 'none' },+ },+ cell: {+ overflow: 'hidden',+ boxShadow: `0 0 0 0.5px ${cssVar.colorBorderSecondary}`,+ },+ label: {+ overflow: 'hidden',+ borderInlineEndWidth: '1px',+ borderInlineEndStyle: 'solid',+ borderInlineEndColor: cssVar.colorBorderSecondary,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },});export interface DescriptionItem {@@ -78,18 +85,18 @@ const Descriptions = memo<DescriptionsProps>(<>{title && <h3 style={{ marginTop: 12 }}>{title}</h3>}<Grid- className={cx(bordered && styles.bordered, className)}gap={0}maxItemWidth={450}+ {...sx([bordered && styles.bordered], className)}{...rest}>{items.map((item) => (<Flexboxhorizontalalign={wrap ? 'flex-start' : 'center'}- className={cx(bordered && styles.cell, item.className, classNames?.item)}flex={1}key={item.key}+ {...sx([bordered && styles.cell], cx(item.className, classNames?.item))}style={{overflow: wrap ? undefined : 'hidden',position: 'relative',@@ -100,9 +107,9 @@ const Descriptions = memo<DescriptionsProps>(<Flexboxhorizontalalign={'center'}- className={cx(bordered && styles.label)}flex={'none'}gap={6}+ {...sx([bordered && styles.label])}paddingBlock={bordered ? 12 : 4}paddingInline={bordered ? 16 : 0}style={{ height: '100%', position: 'relative' }}diff --git a/src/components/DiscreteSlider/index.tsx b/src/components/DiscreteSlider/index.tsxindex 45f4941c870..3b492c9a839 100644--- a/src/components/DiscreteSlider/index.tsx+++ b/src/components/DiscreteSlider/index.tsx@@ -1,58 +1,45 @@-import { createStaticStyles, cx, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { Slider, type SliderProps, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import type { CSSProperties, ReactNode } from 'react';import { memo, useMemo } from 'react';-import { findClosestOptionIndex } from './utils';--const styles = createStaticStyles(({ css, cssVar }) => ({- label: css`- cursor: pointer;-- padding: 0;- border: none;-- font: inherit;- font-size: 12px;- line-height: 16px;- color: ${cssVar.colorTextTertiary};- text-align: center;- overflow-wrap: anywhere;-- background: transparent;+import { sx } from '@/styles/sx';- transition: color 0.2s ease;-- &:hover {- color: ${cssVar.colorTextSecondary};- }-- &:focus-visible {- border-radius: 6px;- outline: 1px solid ${cssVar.colorBorder};- outline-offset: 2px;- }+import { findClosestOptionIndex } from './utils';- &:disabled {- cursor: not-allowed;- }- `,- labels: css`- display: grid;- gap: 8px;- width: 100%;- `,- root: css`- width: 100%;- `,- selectedLabel: css`- color: ${cssVar.colorText};- `,- slider: css`- width: 100%;- padding-inline: 6px;- `,-}));+const styles = stylex.create({+ label: {+ cursor: { 'default': 'pointer', ':disabled': 'not-allowed' },+ padding: '0',+ borderStyle: 'none',+ fontFamily: 'inherit',+ fontStyle: 'inherit',+ fontWeight: 'inherit',+ fontSize: '12px',+ lineHeight: '16px',+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorTextSecondary },+ textAlign: 'center',+ overflowWrap: 'anywhere',+ backgroundColor: 'transparent',+ backgroundImage: 'none',+ transition: 'color 0.2s ease',+ borderRadius: { 'default': null, ':focus-visible': '6px' },+ outlineWidth: { 'default': null, ':focus-visible': '1px' },+ outlineStyle: { 'default': null, ':focus-visible': 'solid' },+ outlineColor: { 'default': null, ':focus-visible': cssVar.colorBorder },+ outlineOffset: { 'default': null, ':focus-visible': '2px' },+ },+ labels: { display: 'grid', gap: '8px', width: '100%' },+ root: { width: '100%' },+ // `.label:hover` outranked `.selectedLabel` in the emotion cascade, so a selected label+ // still dims to the secondary colour on hover.+ selectedLabel: {+ color: { 'default': cssVar.colorText, ':hover': cssVar.colorTextSecondary },+ },+ slider: { width: '100%', paddingInline: '6px' },+});export interface DiscreteSliderOption {ariaLabel?: string;@@ -96,7 +83,7 @@ const DiscreteSlider = memo<DiscreteSliderProps>(: 'minmax(0, 1fr)';const slider = (- <div className={styles.slider}>+ <div {...stylex.props(styles.slider)}><Slider{...rest}disabled={disabled || options.length === 0}@@ -117,13 +104,13 @@ const DiscreteSlider = memo<DiscreteSliderProps>();return (- <Flexbox className={cx(styles.root, className)} gap={6} style={style}>+ <Flexbox gap={6} {...sx([styles.root], className, style)}>{formatTooltip && currentOption ? (<Tooltip title={formatTooltip(currentOption.value)}>{slider}</Tooltip>) : (slider)}- <div className={styles.labels} style={{ gridTemplateColumns }}>+ <div {...sx([styles.labels], undefined, { gridTemplateColumns })}>{options.map((option, index) => {const isFirst = index === 0;const isLast = index === options.length - 1;@@ -133,10 +120,12 @@ const DiscreteSlider = memo<DiscreteSliderProps>(<buttonaria-current={index === currentIndex ? 'true' : undefined}aria-label={option.ariaLabel}- className={cx(styles.label, index === currentIndex && styles.selectedLabel)}disabled={disabled}key={option.value}- style={{ textAlign, ...option.style }}+ {...sx([styles.label, index === currentIndex && styles.selectedLabel], undefined, {+ textAlign,+ ...option.style,+ })}type={'button'}onClick={() => onChange?.(option.value)}>diff --git a/src/components/DotsLoading/index.tsx b/src/components/DotsLoading/index.tsxindex f6bf1ca2db3..8f5db7d10a6 100644--- a/src/components/DotsLoading/index.tsx+++ b/src/components/DotsLoading/index.tsx@@ -1,34 +1,32 @@-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { type CSSProperties, memo } from 'react';-const styles = createStaticStyles(({ css }) => ({- container: css`- display: inline-flex;- flex-direction: row;- gap: var(--dots-loading-gap);- align-items: center;- `,- dot: css`- width: var(--dots-loading-size);- height: var(--dots-loading-size);- border-radius: 50%;-- background-color: var(--dots-loading-color);-- animation: dots-loading-fade 1.2s ease-in-out infinite;-- @keyframes dots-loading-fade {- 0%,- 100% {- opacity: 0.3;- }-- 50% {- opacity: 1;- }- }- `,-}));+import { sx } from '@/styles/sx';++const fade = stylex.keyframes({+ '0%, 100%': { opacity: 0.3 },+ '50%': { opacity: 1 },+});++const styles = stylex.create({+ container: {+ display: 'inline-flex',+ flexDirection: 'row',+ gap: 'var(--dots-loading-gap)',+ alignItems: 'center',+ },+ dot: {+ width: 'var(--dots-loading-size)',+ height: 'var(--dots-loading-size)',+ borderRadius: '50%',+ backgroundColor: 'var(--dots-loading-color)',+ animationName: fade,+ animationDuration: '1.2s',+ animationTimingFunction: 'ease-in-out',+ animationIterationCount: 'infinite',+ },+});interface StyleArgs {color?: string;@@ -49,10 +47,10 @@ const DotsLoading = memo<DotsLoadingProps>(({ size = 4, gap = 3, color, classNam} as CSSProperties;return (- <div className={cx(styles.container, className)} style={{ ...cssVars, ...style }}>- <div className={styles.dot} style={{ animationDelay: '0s' }} />- <div className={styles.dot} style={{ animationDelay: '0.15s' }} />- <div className={styles.dot} style={{ animationDelay: '0.3s' }} />+ <div {...sx([styles.container], className, { ...cssVars, ...style })}>+ <div {...sx([styles.dot], undefined, { animationDelay: '0s' })} />+ <div {...sx([styles.dot], undefined, { animationDelay: '0.15s' })} />+ <div {...sx([styles.dot], undefined, { animationDelay: '0.3s' })} /></div>);});diff --git a/src/components/DragUploadZone/index.tsx b/src/components/DragUploadZone/index.tsxindex 8c757185c75..2530c84877f 100644--- a/src/components/DragUploadZone/index.tsx+++ b/src/components/DragUploadZone/index.tsx@@ -1,11 +1,15 @@'use client';-import { Center, createStaticStyles, cssVar, cx, Flexbox, Icon } from '@lobehub/ui';+import { Center, Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { FileImage, FileText, FileUpIcon, FolderIcon } from 'lucide-react';import { type CSSProperties, type ReactNode } from 'react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { sx } from '@/styles/sx';+import { useDragUploadContext } from './DragUploadProvider';import { type DroppedLocalPath, useLocalDragUpload } from './useLocalDragUpload';@@ -26,78 +30,59 @@ const LOCAL_PATH_TONE = {iconSoftBg: `color-mix(in srgb, ${cssVar.purple} 64%, white)`,};-const styles = createStaticStyles(({ css }) => ({- container: css`- position: relative;- `,- content: css`- position: relative;- z-index: 1;-- box-sizing: border-box;- width: 100%;- height: 100%;- padding-block: 24px;- padding-inline: 28px;- `,- desc: css`- font-size: 12px;- line-height: 18px;- color: #fff;- `,- icon: css`- border-radius: ${cssVar.borderRadiusSM};- `,- iconGroup: css`- margin-block-start: 0;- `,- overlay: css`- pointer-events: none;-- position: absolute;- z-index: 100;- inset: 0;-- display: flex;- align-items: center;- justify-content: center;-- background: ${cssVar.colorBgMask};-- transition: all 0.2s ease-in-out;- `,- overlayContent: css`- position: relative;-- box-sizing: border-box;- width: min(460px, 72vw);- padding: ${OVERLAY_INSET}px;- border-radius: 16px;-- background: ${cssVar.geekblue};- box-shadow: 0 16px 48px color-mix(in srgb, ${cssVar.geekblue} 32%, transparent);-- &::before {- pointer-events: none;- content: '';-- position: absolute;- inset: ${OVERLAY_BORDER_INSET}px;-- border: 1.5px dashed #fff;- border-radius: ${cssVar.borderRadiusLG};- }- `,- overlayContentLocalPath: css`- background: color-mix(in srgb, ${cssVar.purple} 82%, ${cssVar.geekblue});- box-shadow: 0 16px 48px color-mix(in srgb, ${cssVar.purple} 32%, transparent);- `,- title: css`- font-size: 16px;- font-weight: bold;- color: #fff;- `,-}));+const styles = stylex.create({+ container: { position: 'relative' },+ content: {+ position: 'relative',+ zIndex: 1,+ boxSizing: 'border-box',+ width: '100%',+ height: '100%',+ paddingBlock: '24px',+ paddingInline: '28px',+ },+ desc: { fontSize: '12px', lineHeight: '18px', color: '#fff' },+ icon: { borderRadius: cssVar.borderRadiusSM },+ iconGroup: { marginBlockStart: '0' },+ overlay: {+ pointerEvents: 'none',+ position: 'absolute',+ zIndex: 100,+ inset: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: cssVar.colorBgMask,+ backgroundImage: 'none',+ transition: 'all 0.2s ease-in-out',+ },+ overlayContent: {+ 'position': 'relative',+ 'boxSizing': 'border-box',+ 'width': 'min(460px, 72vw)',+ 'padding': `${OVERLAY_INSET}px`,+ 'borderRadius': '16px',+ 'backgroundColor': cssVar.geekblue,+ 'backgroundImage': 'none',+ 'boxShadow': `0 16px 48px color-mix(in srgb, ${cssVar.geekblue} 32%, transparent)`,+ '::before': {+ pointerEvents: 'none',+ content: '""',+ position: 'absolute',+ inset: `${OVERLAY_BORDER_INSET}px`,+ borderWidth: '1.5px',+ borderStyle: 'dashed',+ borderColor: '#fff',+ borderRadius: cssVar.borderRadiusLG,+ },+ },+ overlayContentLocalPath: {+ backgroundColor: `color-mix(in srgb, ${cssVar.purple} 82%, ${cssVar.geekblue})`,+ backgroundImage: 'none',+ boxShadow: `0 16px 48px color-mix(in srgb, ${cssVar.purple} 32%, transparent)`,+ },+ title: { fontSize: '16px', fontWeight: 'bold', color: '#fff' },+});export interface DragUploadZoneProps {/**@@ -212,21 +197,24 @@ const DragUploadZone = memo<DragUploadZoneProps>(const tone = isLocalPathReferenceOverlay ? LOCAL_PATH_TONE : DEFAULT_TONE;return (- <div className={cx(styles.container, className)} style={style} {...getContainerProps()}>+ <div {...sx([styles.container], className, style)} {...getContainerProps()}>{children}{showOverlay && (- <div className={styles.overlay}>+ <div {...stylex.props(styles.overlay)}><div- style={{ minHeight: overlayMinHeight }}- className={cx(- styles.overlayContent,- isLocalPathReferenceOverlay && styles.overlayContentLocalPath,+ {...sx(+ [+ styles.overlayContent,+ isLocalPathReferenceOverlay && styles.overlayContentLocalPath,+ ],+ undefined,+ { minHeight: overlayMinHeight },)}>- <Center className={styles.content} gap={8}>- <Flexbox horizontal className={styles.iconGroup}>+ <Center className={stylex.props(styles.content).className} gap={8}>+ <Flexbox horizontal className={stylex.props(styles.iconGroup).className}><Center- className={styles.icon}+ className={stylex.props(styles.icon).className}height={BLOCK_SIZE * 1.2}width={BLOCK_SIZE}style={{@@ -238,7 +226,7 @@ const DragUploadZone = memo<DragUploadZoneProps>(<Icon icon={overlayIcons[0]} size={ICON_SIZE} /></Center><Center- className={styles.icon}+ className={stylex.props(styles.icon).className}height={BLOCK_SIZE * 1.2}width={BLOCK_SIZE}style={{@@ -251,7 +239,7 @@ const DragUploadZone = memo<DragUploadZoneProps>(<Icon icon={overlayIcons[1]} size={ICON_SIZE} /></Center><Center- className={styles.icon}+ className={stylex.props(styles.icon).className}height={BLOCK_SIZE * 1.2}width={BLOCK_SIZE}style={{@@ -264,8 +252,12 @@ const DragUploadZone = memo<DragUploadZoneProps>(</Center></Flexbox><Flexbox align={'center'} gap={4} style={{ textAlign: 'center' }}>- <Flexbox className={styles.title}>{overlayCopy.title}</Flexbox>- <Flexbox className={styles.desc}>{overlayCopy.desc}</Flexbox>+ <Flexbox className={stylex.props(styles.title).className}>+ {overlayCopy.title}+ </Flexbox>+ <Flexbox className={stylex.props(styles.desc).className}>+ {overlayCopy.desc}+ </Flexbox></Flexbox></Center></div>diff --git a/src/components/FileParsingStatus/EmbeddingStatus.tsx b/src/components/FileParsingStatus/EmbeddingStatus.tsxindex 6c74fc95194..422374db71e 100644--- a/src/components/FileParsingStatus/EmbeddingStatus.tsx+++ b/src/components/FileParsingStatus/EmbeddingStatus.tsx@@ -1,4 +1,6 @@-import { createStaticStyles, cx, Flexbox, Icon, Tag, Tooltip } from '@lobehub/ui';+import { cx, Flexbox, Icon, Tag, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BoltIcon, RotateCwIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -6,17 +8,16 @@ import { useTranslation } from 'react-i18next';import { type FileParsingTask } from '@/types/asyncTask';import { AsyncTaskStatus } from '@/types/asyncTask';-const styles = createStaticStyles(({ css, cssVar }) => ({- errorReason: css`- padding: 4px;- border-radius: 4px;-- font-family: monospace;- font-size: 12px;-- background: ${cssVar.colorFillTertiary};- `,-}));+const styles = stylex.create({+ errorReason: {+ padding: '4px',+ borderRadius: '4px',+ fontFamily: 'monospace',+ fontSize: '12px',+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+});interface EmbeddingStatusProps extends FileParsingTask {className?: string;@@ -62,7 +63,7 @@ const EmbeddingStatus = memo<EmbeddingStatusProps>(<Flexbox gap={4}>{t('FileParsingStatus.chunks.embeddingStatus.errorResult')}{embeddingError && (- <Flexbox className={styles.errorReason}>+ <Flexbox className={stylex.props(styles.errorReason).className}>[{embeddingError.name}]:{' '}{embeddingError.body && typeof embeddingError.body !== 'string'? embeddingError.body.detaildiff --git a/src/components/FileParsingStatus/index.tsx b/src/components/FileParsingStatus/index.tsxindex 8da16ede061..0b6bf98ab83 100644--- a/src/components/FileParsingStatus/index.tsx+++ b/src/components/FileParsingStatus/index.tsx@@ -1,15 +1,6 @@-import {- Badge,- Button,- createStaticStyles,- cssVar,- cx,- Flexbox,- Icon,- Spin,- Tag,- Tooltip,-} from '@lobehub/ui';+import { Badge, Button, cx, Flexbox, Icon, Spin, Tag, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BoltIcon, RotateCwIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -19,17 +10,16 @@ import { AsyncTaskStatus } from '@/types/asyncTask';import EmbeddingStatus from './EmbeddingStatus';-const styles = createStaticStyles(({ css }) => ({- errorReason: css`- padding: 4px;- border-radius: 4px;-- font-family: monospace;- font-size: 12px;-- background: ${cssVar.colorFillTertiary};- `,-}));+const styles = stylex.create({+ errorReason: {+ padding: '4px',+ borderRadius: '4px',+ fontFamily: 'monospace',+ fontSize: '12px',+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+});interface FileParsingStatusProps extends FileParsingTask {className?: string;@@ -79,7 +69,7 @@ const FileParsingStatus = memo<FileParsingStatusProps>(<Flexbox gap={4}>{t('FileParsingStatus.chunks.status.errorResult')}{chunkingError && (- <Flexbox className={styles.errorReason}>+ <Flexbox className={stylex.props(styles.errorReason).className}>[{chunkingError.name}]:{' '}{chunkingError.body && typeof chunkingError.body !== 'string'? chunkingError.body.detaildiff --git a/src/components/FormAction/index.tsx b/src/components/FormAction/index.tsxindex fafb9fa7dcb..5f82b26d839 100644--- a/src/components/FormAction/index.tsx+++ b/src/components/FormAction/index.tsx@@ -1,24 +1,22 @@import { type CenterProps } from '@lobehub/ui';-import { Avatar, Center, createStaticStyles, cssVar, cx, Flexbox } from '@lobehub/ui';+import { Avatar, Center, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { type ReactNode } from 'react';import { memo } from 'react';-export const styles = createStaticStyles(({ css }) => ({- container: css`- border: 1px solid ${cssVar.colorSplit};- border-radius: 8px;- color: ${cssVar.colorText};- background: ${cssVar.colorBgContainer};- `,- desc: css`- color: ${cssVar.colorTextTertiary};- text-align: center;- `,- form: css`- width: 100%;- max-width: 300px;- `,-}));+import { sx } from '@/styles/sx';++const styles = stylex.create({+ desc: {+ color: cssVar.colorTextTertiary,+ textAlign: 'center',+ },+ form: {+ width: '100%',+ maxWidth: '300px',+ },+});const FormAction = memo<{@@ -41,7 +39,7 @@ const FormAction = memo<...rest}) => {return (- <Center className={cx(styles.form, className)} gap={gap} {...rest}>+ <Center gap={gap} {...sx([styles.form], className)} {...rest}><Avataranimation={animation}avatar={avatar}@@ -52,7 +50,7 @@ const FormAction = memo<<Flexbox style={{ fontSize: 18, fontWeight: 'bold', textAlign: 'center' }}>{title}</Flexbox>- <Flexbox className={styles.desc}>{description}</Flexbox>+ <Flexbox className={stylex.props(styles.desc).className}>{description}</Flexbox></Flexbox>{children}</Center>diff --git a/src/components/GalleyGrid/Grid.tsx b/src/components/GalleyGrid/Grid.tsxindex 6fe13550efc..ebab441ed6a 100644--- a/src/components/GalleyGrid/Grid.tsx+++ b/src/components/GalleyGrid/Grid.tsx@@ -2,7 +2,8 @@ import { cx, Flexbox } from '@lobehub/ui';import { type CSSProperties, type ReactNode } from 'react';import { memo, useMemo } from 'react';-import { MAX_SIZE_DESKTOP, MIN_IMAGE_SIZE, styles } from './style';+import { MAX_SIZE_DESKTOP, MIN_IMAGE_SIZE } from './style';+import styles from './style.module.css';interface GridProps {children: ReactNode;diff --git a/src/components/GalleyGrid/style.module.css b/src/components/GalleyGrid/style.module.cssnew file mode 100644index 00000000000..01824cd9313--- /dev/null+++ b/src/components/GalleyGrid/style.module.css@@ -0,0 +1,21 @@+.container {+ display: grid;+ grid-gap: var(--galley-grid-gap, 6px);+ grid-template-columns: repeat(var(--galley-grid-col, 3), 1fr);++ width: 100%;+ max-width: var(--galley-grid-max, 200px);+}++.container > div {+ width: 100%;+ min-width: var(--galley-grid-min, 64px);+ min-height: var(--galley-grid-min, 64px);+ max-height: calc(+ (+ var(--galley-grid-max, 200px) - var(--galley-grid-gap, 6px) *+ (var(--galley-grid-col, 3) - 1)+ ) /+ var(--galley-grid-col, 3)+ );+}diff --git a/src/components/GalleyGrid/style.ts b/src/components/GalleyGrid/style.tsindex d442e13551f..5efa8fe27a8 100644--- a/src/components/GalleyGrid/style.ts+++ b/src/components/GalleyGrid/style.ts@@ -1,29 +1,3 @@-import { createStaticStyles } from '@lobehub/ui';-export const MIN_IMAGE_SIZE = 64;export const MAX_SIZE_DESKTOP = 200;export const MAX_SIZE_MOBILE = 90;--export const styles = createStaticStyles(({ css }) => ({- container: css`- display: grid;- grid-gap: var(--galley-grid-gap, 6px);- grid-template-columns: repeat(var(--galley-grid-col, 3), 1fr);-- width: 100%;- max-width: var(--galley-grid-max, 200px);-- & > div {- width: 100%;- min-width: var(--galley-grid-min, 64px);- min-height: var(--galley-grid-min, 64px);- max-height: calc(- (- var(--galley-grid-max, 200px) - var(--galley-grid-gap, 6px) *- (var(--galley-grid-col, 3) - 1)- ) /- var(--galley-grid-col, 3)- );- }- `,-}));diff --git a/src/components/GeneratingBorder/index.tsx b/src/components/GeneratingBorder/index.tsxindex 6a233f183a7..eb963a8b31f 100644--- a/src/components/GeneratingBorder/index.tsx+++ b/src/components/GeneratingBorder/index.tsx@@ -1,43 +1,50 @@'use client';-import { createGlobalStyle, createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';-import { memo, type ReactNode } from 'react';--/**- * `@property` is what makes the angle animatable — a plain custom property is- * an unregistered token and jumps from 0deg to 360deg instead of sweeping.- * Declared once here rather than per call site.- */-const BorderAngleProperty = createGlobalStyle`- @property --lobe-generating-border-angle {- inherits: false;- initial-value: 0deg;- syntax: '<angle>';- }-`;+import './property.css';-const styles = createStaticStyles(({ css }) => ({- shell: css`- position: relative;- border-radius: 8px;- `,- // `overflow: hidden` belongs to the generating state only: on the resting- // shell it clips the wrapped input's own focus glow while the user types.- shellGenerating: css`- overflow: hidden;+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo, type ReactNode } from 'react';- &::after {- pointer-events: none;- content: '';+import { sx } from '@/styles/sx';- position: absolute;- z-index: 1;- inset: 0;+// The compiler supports registered custom-property keyframes; its public+// CSSProperties type does not yet include them. Keep that extension local.+type SweepFrame = stylex.CSSProperties & {+ '--lobe-generating-border-angle': `${number}deg`;+};- padding: 2px;- border-radius: inherit;+const sweep = stylex.keyframes({+ from: { '--lobe-generating-border-angle': '0deg' } as SweepFrame,+ to: { '--lobe-generating-border-angle': '360deg' } as SweepFrame,+});- background: conic-gradient(+const styles = stylex.create({+ shell: { position: 'relative', borderRadius: '8px' },+ // `overflow: hidden` belongs to the generating state only: on the resting+ // shell it clips the wrapped input's own focus glow while the user types.+ shellGenerating: {+ 'overflow': 'hidden',+ '::after': {+ animationName: { 'default': sweep, '@media (prefers-reduced-motion: reduce)': 'none' },+ animationDuration: { 'default': '1.8s', '@media (prefers-reduced-motion: reduce)': '0s' },+ animationTimingFunction: {+ 'default': 'linear',+ '@media (prefers-reduced-motion: reduce)': 'ease',+ },+ animationIterationCount: {+ 'default': 'infinite',+ '@media (prefers-reduced-motion: reduce)': 1,+ },+ pointerEvents: 'none',+ content: '""',+ position: 'absolute',+ zIndex: 1,+ inset: 0,+ padding: '2px',+ borderRadius: 'inherit',+ backgroundImage: `conic-gradient(from var(--lobe-generating-border-angle),${cssVar.colorBorderSecondary} 0deg 210deg,#ff3d8d 238deg,@@ -47,35 +54,13 @@ const styles = createStaticStyles(({ css }) => ({#ffd43b 318deg,#ff6b35 338deg,${cssVar.colorBorderSecondary} 360deg- );-- /* Masks the gradient down to the 2px padding ring, so only the edge lights up. */- mask:- linear-gradient(#fff 0 0) content-box,- linear-gradient(#fff 0 0);-- animation: lobe-generating-border-flow 1.8s linear infinite;-- mask-composite: exclude;- }-- @keyframes lobe-generating-border-flow {- from {- --lobe-generating-border-angle: 0deg;- }-- to {- --lobe-generating-border-angle: 360deg;- }- }-- @media (prefers-reduced-motion: reduce) {- &::after {- animation: none;- }- }- `,-}));+ )`,+ // Masks the gradient down to the 2px padding ring, so only the edge lights up.+ mask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',+ maskComposite: 'exclude',+ },+ },+});export interface GeneratingBorderProps {children?: ReactNode;@@ -96,17 +81,9 @@ export interface GeneratingBorderProps {*/const GeneratingBorder = memo<GeneratingBorderProps>(({ children, className, generating, style }) => (- <>- <BorderAngleProperty />- <Flexbox- style={style}- className={[styles.shell, generating && styles.shellGenerating, className]- .filter(Boolean)- .join(' ')}- >- {children}- </Flexbox>- </>+ <Flexbox {...sx([styles.shell, generating && styles.shellGenerating], className, style)}>+ {children}+ </Flexbox>),);diff --git a/src/components/GeneratingBorder/property.css b/src/components/GeneratingBorder/property.cssnew file mode 100644index 00000000000..43ac8ad4737--- /dev/null+++ b/src/components/GeneratingBorder/property.css@@ -0,0 +1,10 @@+/*+ * `@property` is what makes the angle animatable — a plain custom property is+ * an unregistered token and jumps from 0deg to 360deg instead of sweeping.+ * Declared once here rather than per call site.+ */+@property --lobe-generating-border-angle {+ inherits: false;+ initial-value: 0deg;+ syntax: '<angle>';+}diff --git a/src/components/GuideModal/GuideModal.module.css b/src/components/GuideModal/GuideModal.module.cssnew file mode 100644index 00000000000..4ccf180758a--- /dev/null+++ b/src/components/GuideModal/GuideModal.module.css@@ -0,0 +1,8 @@+.body h3 {+ margin: 0;+ font-weight: bold;+}++.body p {+ margin: 0;+}diff --git a/src/components/GuideModal/index.tsx b/src/components/GuideModal/index.tsxindex 5cca130707e..04491edcca6 100644--- a/src/components/GuideModal/index.tsx+++ b/src/components/GuideModal/index.tsx@@ -1,22 +1,11 @@'use client';-import { createStaticStyles, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui';import { type ReactNode } from 'react';import { memo } from 'react';-const styles = createStaticStyles(({ css }) => ({- body: css`- h3 {- margin: 0;- font-weight: bold;- }-- p {- margin: 0;- }- `,-}));+import styles from './GuideModal.module.css';interface GuideModalContentProps {cancelText?: ReactNode;diff --git a/src/components/HtmlPreview/HtmlDocumentFrame.tsx b/src/components/HtmlPreview/HtmlDocumentFrame.tsxindex 7aae636b912..2c3c275976f 100644--- a/src/components/HtmlPreview/HtmlDocumentFrame.tsx+++ b/src/components/HtmlPreview/HtmlDocumentFrame.tsx@@ -1,18 +1,13 @@-import { createStaticStyles, HtmlPreviewIframe } from '@lobehub/ui';+import { HtmlPreviewIframe } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { useEffect, useRef, useState } from 'react';import { nextWidenBaseline } from './widenRemount';-const styles = createStaticStyles(({ css }) => ({- container: css`- width: 100%;- `,- frame: css`- display: block;- width: 100%;- border: 0;- `,-}));+const styles = stylex.create({+ container: { width: '100%' },+ frame: { display: 'block', width: '100%', borderStyle: 'none' },+});interface HtmlDocumentFrameProps {content: string;@@ -53,9 +48,9 @@ const HtmlDocumentFrame = ({ content, title }: HtmlDocumentFrameProps) => {}, []);return (- <div className={styles.container} ref={containerRef}>+ <div {...stylex.props(styles.container)} ref={containerRef}><HtmlPreviewIframe- className={styles.frame}+ className={stylex.props(styles.frame).className}content={content}defaultHeight={480}key={frameKey}diff --git a/src/components/HtmlPreview/PreviewDrawer.tsx b/src/components/HtmlPreview/PreviewDrawer.tsxindex c4966b2a33c..8fddadff9cd 100644--- a/src/components/HtmlPreview/PreviewDrawer.tsx+++ b/src/components/HtmlPreview/PreviewDrawer.tsx@@ -1,27 +1,15 @@import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';import { extractHtmlTitle } from '@lobechat/html-artifact';import { exportFile } from '@lobechat/utils/client';-import {- Block,- Button,- createStaticStyles,- Drawer,- Flexbox,- Highlighter,- HtmlPreview,- Tabs,-} from '@lobehub/ui';+import { Block, Button, Drawer, Flexbox, Highlighter, HtmlPreview, Tabs } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { Code2, Download, Eye } from 'lucide-react';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import { isDesktop } from '@/const/version';-const styles = createStaticStyles(({ css }) => ({- container: css`- height: 100%;- `,-}));+const styles = stylex.create({ container: { height: '100%' } });const hideHtmlPreviewActions = () => null;@@ -96,7 +84,7 @@ const HtmlPreviewDrawer = memo<HtmlPreviewDrawerProps>(({ content, open, onCloseonClose={onClose}>{mode === 'preview' ? (- <Block className={styles.container}>+ <Block className={stylex.props(styles.container).className}><HtmlPreviewactionsRender={hideHtmlPreviewActions}copyable={false}@@ -110,7 +98,7 @@ const HtmlPreviewDrawer = memo<HtmlPreviewDrawerProps>(({ content, open, onClose</HtmlPreview></Block>) : (- <Block className={styles.container}>+ <Block className={stylex.props(styles.container).className}><Highlighterlanguage={'html'}showLanguage={false}diff --git a/src/components/ImageItem/index.tsx b/src/components/ImageItem/index.tsxindex 409cfa453c4..e08c6957b70 100644--- a/src/components/ImageItem/index.tsx+++ b/src/components/ImageItem/index.tsx@@ -1,30 +1,29 @@import { type ImageProps } from '@lobehub/ui';-import { ActionIcon, createStaticStyles, cssVar, cx, Image } from '@lobehub/ui';+import { ActionIcon, Image } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { Trash } from 'lucide-react';import { type CSSProperties } from 'react';import { memo } from 'react';import { usePlatform } from '@/hooks/usePlatform';+import { sx } from '@/styles/sx';import { MIN_IMAGE_SIZE } from './style';-const styles = createStaticStyles(({ css }) => ({- deleteButton: css`- color: #fff;- background: ${cssVar.colorBgMask};-- &:hover {- background: ${cssVar.colorError};- }- `,- editableImage: css`- background: ${cssVar.colorBgContainer};- box-shadow: 0 0 0 1px ${cssVar.colorFill} inset;- `,- image: css`- margin-block: 0 !important;- `,-}));+const styles = stylex.create({+ deleteButton: {+ color: '#fff',+ backgroundColor: { 'default': cssVar.colorBgMask, ':hover': cssVar.colorError },+ backgroundImage: { 'default': 'none', ':hover': 'none' },+ },+ editableImage: {+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ boxShadow: `0 0 0 1px ${cssVar.colorFill} inset`,+ },+ image: { marginBlock: '0' },+});interface ImageItemProps {alt?: string;@@ -70,7 +69,6 @@ const ImageItem = memo<ImageItemProps>(<Imagealt={alt || ''}alwaysShowActions={alwaysShowClose}- classNames={{ wrapper: cx(styles.image, editable && styles.editableImage, className) }}height={isSafari ? 'auto' : '100%'}isLoading={loading}preview={preview}@@ -80,7 +78,7 @@ const ImageItem = memo<ImageItemProps>(editable && (<ActionIconglass- className={styles.deleteButton}+ className={stylex.props(styles.deleteButton).className}icon={Trash}size={'small'}onClick={(e) => {@@ -90,6 +88,9 @@ const ImageItem = memo<ImageItemProps>(/>)}+ classNames={{+ wrapper: sx([styles.image, editable && styles.editableImage], className).className,+ }}style={{aspectRatio,height: aspectRatio || isSafari ? 'auto' : '100%',diff --git a/src/components/InlineTable/InlineTable.module.css b/src/components/InlineTable/InlineTable.module.cssnew file mode 100644index 00000000000..876ffdff1f7--- /dev/null+++ b/src/components/InlineTable/InlineTable.module.css@@ -0,0 +1,27 @@+.table table {+ font-size: 13px;+}++.table th {+ background: transparent;+ box-shadow: inset 0 999px 0 var(--lobe-color-fill-quaternary);+}++.table td {+ border: none;+ background: transparent;+}++.table tr:hover > td {+ background: var(--lobe-color-fill-quaternary);+}++.table tr td:first-child,+.table tr th:first-child {+ padding-inline-start: 24px;+}++.table tr td:last-child,+.table tr th:last-child {+ padding-inline-end: 24px;+}diff --git a/src/components/InlineTable/index.tsx b/src/components/InlineTable/index.tsxindex 590900a75a7..bb2e15b0bff 100644--- a/src/components/InlineTable/index.tsx+++ b/src/components/InlineTable/index.tsx@@ -1,46 +1,16 @@import { Table, type TableProps } from '@lobehub/ui';-import { createStaticStyles, cx } from '@lobehub/ui';+import { cx } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-const styles = createStaticStyles(({ css, cssVar }) => ({- hoverToActive: css`- opacity: 0.6;+import { sx } from '@/styles/sx';- &:hover {- opacity: 1;- }- `,- table: css`- table {- font-size: 13px;- }-- th {- background: transparent;- box-shadow: inset 0 999px 0 ${cssVar.colorFillQuaternary};- }+import styles from './InlineTable.module.css';- td {- border: none;- background: transparent;- }-- tr:hover > td {- background: ${cssVar.colorFillQuaternary};- }-- tr {- td:first-child,- th:first-child {- padding-inline-start: 24px;- }-- td:last-child,- th:last-child {- padding-inline-end: 24px;- }- }- `,-}));+const hoverStyles = stylex.create({+ hoverToActive: {+ opacity: { 'default': 0.6, ':hover': 1 },+ },+});export type InlineTableProps<T> = TableProps<T> & { hoverToActive?: boolean };@@ -50,9 +20,11 @@ const InlineTable = <T extends object>({...rest}: InlineTableProps<T>) => (<Table<T>- className={cx(styles.table, hoverToActive && styles.hoverToActive, className)}pagination={false}size={'small'}+ className={+ sx([hoverToActive && hoverStyles.hoverToActive], cx(styles.table, className)).className+ }{...rest}/>);diff --git a/src/components/KeyValueEditor/index.tsx b/src/components/KeyValueEditor/index.tsxindex 64b4559f811..3362721d4e6 100644--- a/src/components/KeyValueEditor/index.tsx+++ b/src/components/KeyValueEditor/index.tsx@@ -1,4 +1,6 @@-import { ActionIcon, Button, createStaticStyles, Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, Button, Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import fastDeepEqual from 'fast-deep-equal';import { LucidePlus, LucideTrash } from 'lucide-react';import { type CSSProperties } from 'react';@@ -11,31 +13,20 @@ import { FormInput } from '@/components/FormInput';import { type KeyValueItem } from './utils';import { localListToRecord, recordToLocalList } from './utils';-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- position: relative;-- width: 100%;- padding: 12px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- `,- input: css`- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- `,- row: css`- margin-block-end: 8px;-- &:last-child {- margin-block-end: 0;- }- `,- title: css`- margin-block-end: 8px;- color: ${cssVar.colorTextTertiary};- `,-}));+const styles = stylex.create({+ container: {+ position: 'relative',+ width: '100%',+ padding: '12px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ },+ input: { fontFamily: cssVar.fontFamilyCode, fontSize: '12px' },+ row: { marginBlockEnd: { 'default': '8px', ':last-child': '0' } },+ title: { marginBlockEnd: '8px', color: cssVar.colorTextTertiary },+});export interface KeyValueEditorProps {addButtonText?: string;@@ -137,8 +128,8 @@ const KeyValueEditor = memo<KeyValueEditorProps>(const duplicateKeys = getDuplicateKeys(items);return (- <div className={styles.container} style={style}>- <Flexbox horizontal className={styles.title} gap={8}>+ <div className={stylex.props(styles.container).className} style={style}>+ <Flexbox horizontal className={stylex.props(styles.title).className} gap={8}><Flexbox flex={1}>{keyPlaceholder || t('KeyValueEditor.keyPlaceholder')}</Flexbox><Flexbox flex={2}>{valuePlaceholder || t('KeyValueEditor.valuePlaceholder')}</Flexbox><Flexbox style={{ width: 30 }} />@@ -150,7 +141,7 @@ const KeyValueEditor = memo<KeyValueEditorProps>(<Flexboxhorizontalalign="flex-start"- className={styles.row}+ className={stylex.props(styles.row).className}gap={8}key={item.id}width={'100%'}@@ -158,7 +149,7 @@ const KeyValueEditor = memo<KeyValueEditorProps>(<Flexbox flex={1} style={{ position: 'relative' }}><FormInputaria-invalid={isDuplicate || undefined}- className={styles.input}+ className={stylex.props(styles.input).className}data-invalid={isDuplicate || undefined}disabled={disabled}placeholder={keyPlaceholder || t('KeyValueEditor.keyPlaceholder')}@@ -181,7 +172,7 @@ const KeyValueEditor = memo<KeyValueEditorProps>(</Flexbox><Flexbox flex={2}><FormInput- className={styles.input}+ className={stylex.props(styles.input).className}disabled={disabled}placeholder={valuePlaceholder || t('KeyValueEditor.valuePlaceholder')}value={item.value}diff --git a/src/components/LibIcon/Locked.tsx b/src/components/LibIcon/Locked.tsxindex a416bee8db1..a812b5de3d4 100644--- a/src/components/LibIcon/Locked.tsx+++ b/src/components/LibIcon/Locked.tsx@@ -1,34 +1,29 @@'use client';-import { createStaticStyles, cssVar, Icon } from '@lobehub/ui';+import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { LockIcon } from 'lucide-react';import { memo } from 'react';import LibIcon from './index';-const styles = createStaticStyles(({ css }) => ({- // The plate under the lock keeps it legible over the folder strokes.- badge: css`- position: absolute;- inset-block-end: -3px;- inset-inline-end: -4px;-- display: flex;- align-items: center;- justify-content: center;-- padding: 1px;- border-radius: 50%;-- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorBgLayout};- `,- root: css`- position: relative;- display: flex;- `,-}));+const styles = stylex.create({+ badge: {+ position: 'absolute',+ insetBlockEnd: '-3px',+ insetInlineEnd: '-4px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '1px',+ borderRadius: '50%',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorBgLayout,+ backgroundImage: 'none',+ },+ root: { position: 'relative', display: 'flex' },+});interface LockedLibIconProps {size?: number;@@ -41,9 +36,9 @@ interface LockedLibIconProps {* so the state reads the same across sidebar, cards, and pickers.*/const LockedLibIcon = memo<LockedLibIconProps>(({ size = 20 }) => (- <span className={styles.root}>+ <span {...stylex.props(styles.root)}><LibIcon size={size} />- <span className={styles.badge}>+ <span {...stylex.props(styles.badge)}><Icon icon={LockIcon} size={Math.min(12, Math.round(size / 2))} /></span></span>diff --git a/src/components/LiteTable/index.tsx b/src/components/LiteTable/index.tsxindex 688758c06dd..f44445040b3 100644--- a/src/components/LiteTable/index.tsx+++ b/src/components/LiteTable/index.tsx@@ -1,158 +1,351 @@-import { createStaticStyles, cx, Skeleton } from '@lobehub/ui';+import { Skeleton } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { type ReactNode } from 'react';import { memo } from 'react';-const LIST_BREAKPOINT = 600;+import { sx } from '@/styles/sx';++const styles = stylex.create({+ body: { overflowX: 'auto' },+ clickableRow: {+ cursor: 'pointer',+ outlineWidth: { 'default': null, ':focus-visible': '2px' },+ outlineStyle: { 'default': null, ':focus-visible': 'solid' },+ outlineColor: { 'default': null, ':focus-visible': cssVar.colorPrimary },+ outlineOffset: { 'default': null, ':focus-visible': '-2px' },+ },+ container: { containerType: 'inline-size' },+ table: {+ borderCollapse: 'collapse',+ width: '100%',+ minWidth: { 'default': 'max-content', '@container (max-width: 600px)': '0' },+ fontSize: '13px',+ display: { 'default': null, '@container (max-width: 600px)': 'block' },+ },+ cell: {+ 'paddingBlockStart': {+ 'default': '8px',+ '@container (max-width: 600px)': {+ 'default': '6px',+ ":is([data-list-slot='title'])": '8px',+ ":is([data-list-slot='extra'])": '8px',+ },+ },+ 'paddingBlockEnd': {+ 'default': '8px',+ '@container (max-width: 600px)': {+ 'default': '6px',+ ":is([data-list-slot='title'])": '8px',+ ":is([data-list-slot='extra'])": '8px',+ },+ },+ 'paddingInlineStart': {+ 'default': '8px',+ ':first-child': '24px',+ '@container (max-width: 600px)': '0',+ },+ 'paddingInlineEnd': {+ 'default': '8px',+ ':last-child': '24px',+ '@container (max-width: 600px)': '0',+ },+ 'textAlign': 'start',+ 'verticalAlign': 'middle',+ 'display': { 'default': null, '@container (max-width: 600px)': 'flex' },+ 'gridColumn': {+ 'default': null,+ '@container (max-width: 600px)': {+ 'default': '1 / -1',+ ":is([data-list-slot='title'])": '1',+ ":is([data-list-slot='extra'])": '2',+ },+ },+ 'gap': { 'default': null, '@container (max-width: 600px)': '16px' },+ 'alignItems': { 'default': null, '@container (max-width: 600px)': 'center' },+ 'justifyContent': {+ 'default': null,+ '@container (max-width: 600px)': {+ 'default': 'space-between',+ ':not([data-label], [data-list-slot])': 'flex-end',+ ":is([data-list-slot='title'])": 'flex-start',+ ":is([data-list-slot='extra'])": 'flex-end',+ ":is([data-list-slot='actions'])": 'flex-end',+ },+ },+ 'gridRow': {+ 'default': null,+ '@container (max-width: 600px)': {+ 'default': null,+ ":is([data-list-slot='title'])": '1',+ ":is([data-list-slot='extra'])": '1',+ },+ },+ 'borderBlockEndWidth': {+ 'default': null,+ '@container (max-width: 600px)': {+ 'default': null,+ ":is([data-list-slot='title'])": '1px',+ ":is([data-list-slot='extra'])": '1px',+ },+ },+ 'borderBlockEndStyle': {+ 'default': null,+ '@container (max-width: 600px)': {+ 'default': null,+ ":is([data-list-slot='title'])": 'solid',+ ":is([data-list-slot='extra'])": 'solid',+ },+ },+ 'borderBlockEndColor': {+ 'default': null,+ '@container (max-width: 600px)': {+ 'default': null,+ ":is([data-list-slot='title'])": cssVar.colorBorderSecondary,+ ":is([data-list-slot='extra'])": cssVar.colorBorderSecondary,+ },+ },+ 'fontSize': {+ 'default': null,+ '@container (max-width: 600px)': { 'default': null, ":is([data-list-slot='title'])": '14px' },+ },+ 'fontWeight': {+ 'default': null,+ '@container (max-width: 600px)': { 'default': null, ":is([data-list-slot='title'])": 600 },+ },+ '::before': {+ content: {+ 'default': null,+ '@container (max-width: 600px)': {+ 'default': null,+ ':is([data-label])': 'attr(data-label)',+ },+ },+ flexShrink: {+ 'default': null,+ '@container (max-width: 600px)': { 'default': null, ':is([data-label])': 0 },+ },+ color: {+ 'default': null,+ '@container (max-width: 600px)': {+ 'default': null,+ ':is([data-label])': cssVar.colorTextSecondary,+ },+ },+ },+ },+ heading: {+ paddingBlockStart: '8px',+ paddingBlockEnd: '8px',+ paddingInlineStart: { 'default': '8px', ':first-child': '24px' },+ paddingInlineEnd: { 'default': '8px', ':last-child': '24px' },+ textAlign: 'start',+ verticalAlign: 'middle',+ fontWeight: 500,+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ row: {+ backgroundColor: {+ 'default': null,+ ':hover': cssVar.colorFillQuaternary,+ '@container (max-width: 600px)': { 'default': null, ':hover': 'transparent' },+ },+ backgroundImage: {+ 'default': null,+ ':hover': 'none',+ '@container (max-width: 600px)': { 'default': null, ':hover': 'none' },+ },+ display: { 'default': null, '@container (max-width: 600px)': 'grid' },+ gridTemplateColumns: { 'default': null, '@container (max-width: 600px)': '1fr auto' },+ alignItems: { 'default': null, '@container (max-width: 600px)': 'center' },+ paddingBlockStart: { 'default': null, '@container (max-width: 600px)': '4px' },+ paddingBlockEnd: { 'default': null, '@container (max-width: 600px)': '8px' },+ paddingInlineStart: { 'default': null, '@container (max-width: 600px)': '16px' },+ paddingInlineEnd: { 'default': null, '@container (max-width: 600px)': '16px' },+ borderWidth: { 'default': null, '@container (max-width: 600px)': '1px' },+ borderStyle: { 'default': null, '@container (max-width: 600px)': 'solid' },+ borderColor: { 'default': null, '@container (max-width: 600px)': cssVar.colorBorderSecondary },+ borderRadius: { 'default': null, '@container (max-width: 600px)': cssVar.borderRadiusLG },+ },+ wideTable: {+ borderCollapse: 'collapse',+ width: '100%',+ minWidth: { 'default': 'max-content', '@container (max-width: 800px)': '0' },+ fontSize: '13px',+ display: { 'default': null, '@container (max-width: 800px)': 'block' },+ },+ wideCell: {+ 'paddingBlockStart': {+ 'default': '8px',+ '@container (max-width: 800px)': {+ 'default': '6px',+ ":is([data-list-slot='title'])": '8px',+ ":is([data-list-slot='extra'])": '8px',+ },+ },+ 'paddingBlockEnd': {+ 'default': '8px',+ '@container (max-width: 800px)': {+ 'default': '6px',+ ":is([data-list-slot='title'])": '8px',+ ":is([data-list-slot='extra'])": '8px',+ },+ },+ 'paddingInlineStart': {+ 'default': '8px',+ ':first-child': '24px',+ '@container (max-width: 800px)': '0',+ },+ 'paddingInlineEnd': {+ 'default': '8px',+ ':last-child': '24px',+ '@container (max-width: 800px)': '0',+ },+ 'textAlign': 'start',+ 'verticalAlign': 'middle',+ 'display': { 'default': null, '@container (max-width: 800px)': 'flex' },+ 'gridColumn': {+ 'default': null,+ '@container (max-width: 800px)': {+ 'default': '1 / -1',+ ":is([data-list-slot='title'])": '1',+ ":is([data-list-slot='extra'])": '2',+ },+ },+ 'gap': { 'default': null, '@container (max-width: 800px)': '16px' },+ 'alignItems': { 'default': null, '@container (max-width: 800px)': 'center' },+ 'justifyContent': {+ 'default': null,+ '@container (max-width: 800px)': {+ 'default': 'space-between',+ ':not([data-label], [data-list-slot])': 'flex-end',+ ":is([data-list-slot='title'])": 'flex-start',+ ":is([data-list-slot='extra'])": 'flex-end',+ ":is([data-list-slot='actions'])": 'flex-end',+ },+ },+ 'gridRow': {+ 'default': null,+ '@container (max-width: 800px)': {+ 'default': null,+ ":is([data-list-slot='title'])": '1',+ ":is([data-list-slot='extra'])": '1',+ },+ },+ 'borderBlockEndWidth': {+ 'default': null,+ '@container (max-width: 800px)': {+ 'default': null,+ ":is([data-list-slot='title'])": '1px',+ ":is([data-list-slot='extra'])": '1px',+ },+ },+ 'borderBlockEndStyle': {+ 'default': null,+ '@container (max-width: 800px)': {+ 'default': null,+ ":is([data-list-slot='title'])": 'solid',+ ":is([data-list-slot='extra'])": 'solid',+ },+ },+ 'borderBlockEndColor': {+ 'default': null,+ '@container (max-width: 800px)': {+ 'default': null,+ ":is([data-list-slot='title'])": cssVar.colorBorderSecondary,+ ":is([data-list-slot='extra'])": cssVar.colorBorderSecondary,+ },+ },+ 'fontSize': {+ 'default': null,+ '@container (max-width: 800px)': { 'default': null, ":is([data-list-slot='title'])": '14px' },+ },+ 'fontWeight': {+ 'default': null,+ '@container (max-width: 800px)': { 'default': null, ":is([data-list-slot='title'])": 600 },+ },+ '::before': {+ content: {+ 'default': null,+ '@container (max-width: 800px)': {+ 'default': null,+ ':is([data-label])': 'attr(data-label)',+ },+ },+ flexShrink: {+ 'default': null,+ '@container (max-width: 800px)': { 'default': null, ':is([data-label])': 0 },+ },+ color: {+ 'default': null,+ '@container (max-width: 800px)': {+ 'default': null,+ ':is([data-label])': cssVar.colorTextSecondary,+ },+ },+ },+ },+ wideHeading: {+ paddingBlockStart: '8px',+ paddingBlockEnd: '8px',+ paddingInlineStart: { 'default': '8px', ':first-child': '24px' },+ paddingInlineEnd: { 'default': '8px', ':last-child': '24px' },+ textAlign: 'start',+ verticalAlign: 'middle',+ fontWeight: 500,+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ wideRow: {+ backgroundColor: {+ 'default': null,+ ':hover': cssVar.colorFillQuaternary,+ '@container (max-width: 800px)': { 'default': null, ':hover': 'transparent' },+ },+ backgroundImage: {+ 'default': null,+ ':hover': 'none',+ '@container (max-width: 800px)': { 'default': null, ':hover': 'none' },+ },+ display: { 'default': null, '@container (max-width: 800px)': 'grid' },+ gridTemplateColumns: { 'default': null, '@container (max-width: 800px)': '1fr auto' },+ alignItems: { 'default': null, '@container (max-width: 800px)': 'center' },+ paddingBlockStart: { 'default': null, '@container (max-width: 800px)': '4px' },+ paddingBlockEnd: { 'default': null, '@container (max-width: 800px)': '8px' },+ paddingInlineStart: { 'default': null, '@container (max-width: 800px)': '16px' },+ paddingInlineEnd: { 'default': null, '@container (max-width: 800px)': '16px' },+ borderWidth: { 'default': null, '@container (max-width: 800px)': '1px' },+ borderStyle: { 'default': null, '@container (max-width: 800px)': 'solid' },+ borderColor: { 'default': null, '@container (max-width: 800px)': cssVar.colorBorderSecondary },+ borderRadius: { 'default': null, '@container (max-width: 800px)': cssVar.borderRadiusLG },+ },+ head: { display: { 'default': null, '@container (max-width: 600px)': 'none' } },+ wideHead: { display: { 'default': null, '@container (max-width: 800px)': 'none' } },+ bodyRows: {+ display: { 'default': null, '@container (max-width: 600px)': 'flex' },+ flexDirection: { 'default': null, '@container (max-width: 600px)': 'column' },+ gap: { 'default': null, '@container (max-width: 600px)': '12px' },+ paddingInlineStart: { 'default': null, '@container (max-width: 600px)': '16px' },+ paddingInlineEnd: { 'default': null, '@container (max-width: 600px)': '16px' },+ },+ wideBodyRows: {+ display: { 'default': null, '@container (max-width: 800px)': 'flex' },+ flexDirection: { 'default': null, '@container (max-width: 800px)': 'column' },+ gap: { 'default': null, '@container (max-width: 800px)': '12px' },+ paddingInlineStart: { 'default': null, '@container (max-width: 800px)': '16px' },+ paddingInlineEnd: { 'default': null, '@container (max-width: 800px)': '16px' },+ },+ fixedTable: { tableLayout: 'fixed', minWidth: '0' },+});/** Placeholder rows shown before the first load settles. */const SKELETON_ROWS = 4;-const styles = createStaticStyles(({ css, cssVar }) => {- const listLayout = `- display: block;- min-width: 0;-- thead {- display: none;- }-- tbody {- display: flex;- flex-direction: column;- gap: 12px;- padding-inline: 16px;- }-- tbody tr {- display: grid;- grid-template-columns: 1fr auto;- align-items: center;-- padding-block: 4px 8px;- padding-inline: 16px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- &:hover {- background: transparent;- }- }-- td {- display: flex;- grid-column: 1 / -1;- gap: 16px;- align-items: center;- justify-content: space-between;-- padding-block: 6px;- padding-inline: 0 !important;- }-- td[data-label]::before {- content: attr(data-label);- flex-shrink: 0;- color: ${cssVar.colorTextSecondary};- }-- td:not([data-label], [data-list-slot]) {- justify-content: flex-end;- }-- td[data-list-slot='title'] {- grid-column: 1;- grid-row: 1;- justify-content: flex-start;-- padding-block: 8px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};-- font-size: 14px;- font-weight: 600;- }-- td[data-list-slot='extra'] {- grid-column: 2;- grid-row: 1;- justify-content: flex-end;-- padding-block: 8px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- }-- td[data-list-slot='actions'] {- justify-content: flex-end;- }- `;-- return {- body: css`- overflow-x: auto;- `,- clickableRow: css`- cursor: pointer;-- &:focus-visible {- outline: 2px solid ${cssVar.colorPrimary};- outline-offset: -2px;- }- `,- container: css`- container-type: inline-size;- `,- fixedTable: css`- table-layout: fixed;- min-width: 0;- `,- wideList: css`- @container (max-width: 800px) {- ${listLayout}- }- `,- table: css`- border-collapse: collapse;- width: 100%;- min-width: max-content;- font-size: 13px;-- th,- td {- padding-block: 8px;- padding-inline: 8px;- text-align: start;- vertical-align: middle;- }-- thead th {- font-weight: 500;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;- background: ${cssVar.colorFillQuaternary};- }-- tr {- th:first-child,- td:first-child {- padding-inline-start: 24px;- }-- th:last-child,- td:last-child {- padding-inline-end: 24px;- }- }-- tbody tr:hover {- background: ${cssVar.colorFillQuaternary};- }-- @container (max-width: ${LIST_BREAKPOINT}px) {- ${listLayout}- }- `,- };-});-export interface LiteTableColumn<RecordType> {key: string;listLabel?: string | false;@@ -193,6 +386,7 @@ const LiteTableInner = <RecordType,>({}: LiteTableProps<RecordType>) => {const items = dataSource ?? [];const initialLoading = !!loading && items.length === 0;+ const wide = listBreakpoint === 800;const listLabelOf = (column: LiteTableColumn<RecordType>) =>column.listSlot || column.listLabel === false@@ -200,35 +394,40 @@ const LiteTableInner = <RecordType,>({: (column.listLabel ?? (typeof column.title === 'string' ? column.title : undefined));return (- <div aria-busy={initialLoading} className={cx(styles.container, className)}>+ <div aria-busy={initialLoading} {...sx(styles.container, className)}>{!initialLoading && items.length === 0 ? (emptyText) : (// The loading state keeps the table chrome and skeletonises only the// cells, so settling is a content swap rather than a relayout (ux §4.1).- <div className={styles.body}>+ <div {...stylex.props(styles.body)}><table- className={cx(- styles.table,+ {...stylex.props(+ wide ? styles.wideTable : styles.table,tableLayout === 'fixed' && styles.fixedTable,- listBreakpoint === 800 && styles.wideList,)}>- <thead>+ <thead {...stylex.props(wide ? styles.wideHead : styles.head)}><tr>{columns.map((column) => (- <th key={column.key} style={{ width: column.width }}>+ <th+ {...sx(wide ? styles.wideHeading : styles.heading, undefined, {+ width: column.width,+ })}+ key={column.key}+ >{column.title}</th>))}</tr></thead>- <tbody>+ <tbody {...stylex.props(wide ? styles.wideBodyRows : styles.bodyRows)}>{initialLoading? Array.from({ length: SKELETON_ROWS }, (_, index) => (- <tr key={index}>+ <tr key={index} {...stylex.props(wide ? styles.wideRow : styles.row)}>{columns.map((column) => (<td+ {...stylex.props(wide ? styles.wideCell : styles.cell)}data-label={listLabelOf(column)}data-list-slot={column.listSlot}key={column.key}@@ -240,7 +439,10 @@ const LiteTableInner = <RecordType,>({)): items.map((record, index) => (<tr- className={onRowClick ? styles.clickableRow : undefined}+ {...stylex.props(+ wide ? styles.wideRow : styles.row,+ onRowClick && styles.clickableRow,+ )}key={rowKey(record)}tabIndex={onRowClick ? 0 : undefined}onClick={onRowClick ? () => onRowClick(record) : undefined}@@ -259,6 +461,7 @@ const LiteTableInner = <RecordType,>({>{columns.map((column) => (<td+ {...stylex.props(wide ? styles.wideCell : styles.cell)}data-label={listLabelOf(column)}data-list-slot={column.listSlot}key={column.key}diff --git a/src/components/Loading/ContentLoading/index.tsx b/src/components/Loading/ContentLoading/index.tsxindex a1e95757a50..5a773b9a433 100644--- a/src/components/Loading/ContentLoading/index.tsx+++ b/src/components/Loading/ContentLoading/index.tsx@@ -1,31 +1,33 @@-import { createStaticStyles, cssVar } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';-const styles = createStaticStyles(({ css }) => ({- container: css`- display: flex;- align-items: center;- justify-content: center;+const spin = stylex.keyframes({+ to: { transform: 'rotate(360deg)' },+});- width: 100%;- height: 100%;- min-height: 96px;- `,- spinner: css`- width: 28px;- height: 28px;- border: 2px solid ${cssVar.colorFillSecondary};- border-block-start-color: ${cssVar.colorTextSecondary};- border-radius: 50%;-- animation: content-loading-spin 0.8s linear infinite;-- @keyframes content-loading-spin {- to {- transform: rotate(360deg);- }- }- `,-}));+const styles = stylex.create({+ container: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '100%',+ height: '100%',+ minHeight: '96px',+ },+ spinner: {+ width: '28px',+ height: '28px',+ borderWidth: '2px',+ borderStyle: 'solid',+ borderColor: cssVar.colorFillSecondary,+ borderBlockStartColor: cssVar.colorTextSecondary,+ borderRadius: '50%',+ animationName: spin,+ animationDuration: '0.8s',+ animationTimingFunction: 'linear',+ animationIterationCount: 'infinite',+ },+});/*** Loading state for a content region whose chrome is already on screen.@@ -37,8 +39,8 @@ const styles = createStaticStyles(({ css }) => ({* conversation. `BrandTextLoading` stays for full-page boundaries.*/const ContentLoading = () => (- <div className={styles.container}>- <span aria-label={'Loading'} className={styles.spinner} role={'status'} />+ <div {...stylex.props(styles.container)}>+ <span aria-label={'Loading'} role={'status'} {...stylex.props(styles.spinner)} /></div>);diff --git a/src/components/Loading/SkeletonLoading/index.tsx b/src/components/Loading/SkeletonLoading/index.tsxindex a3635707f64..c827ed7085e 100644--- a/src/components/Loading/SkeletonLoading/index.tsx+++ b/src/components/Loading/SkeletonLoading/index.tsx@@ -1,20 +1,18 @@'use client';-import { createStaticStyles, cx, responsive } from '@lobehub/ui';+import { media } from '@lobehub/ui/stylex/media.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { ArticleSkeleton } from '@/components/Skeleton';+import { sx } from '@/styles/sx';-const styles = createStaticStyles(- ({ css }) => css`- ${responsive.sm} {- padding: 16px;- }- `,-);+const styles = stylex.create({+ root: { padding: { default: null, [media.sm]: '16px' } },+});const SkeletonLoading = memo<{ className?: string }>(({ className }) => (- <ArticleSkeleton className={cx(styles, className)} rows={8} />+ <ArticleSkeleton className={sx([styles.root], className).className} rows={8} />));export default SkeletonLoading;diff --git a/src/components/MemberSelectionModal/MemberSelectionModal.tsx b/src/components/MemberSelectionModal/MemberSelectionModal.tsxindex 085d596013a..8e1a9f58a8e 100644--- a/src/components/MemberSelectionModal/MemberSelectionModal.tsx+++ b/src/components/MemberSelectionModal/MemberSelectionModal.tsx@@ -5,9 +5,6 @@ import {ActionIcon,Button,Checkbox,- createStaticStyles,- cssVar,- cx,Flexbox,List,ModalFooter,@@ -16,6 +13,9 @@ import {Text,Tooltip,} 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 { useHover } from 'ahooks';import { X } from 'lucide-react';import { type ChangeEvent } from 'react';@@ -31,15 +31,14 @@ import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/selectors';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';+import { sx } from '@/styles/sx';const AvailableAgentItem = memo<{agent: SidebarAgentItem;- cx: any;isSelected: boolean;onToggle: (_agentId: string) => void;- styles: any;t: any;-}>(({ agent, isSelected, onToggle, styles, cx, t }) => {+}>(({ agent, isSelected, onToggle, t }) => {const ref = useRef<HTMLDivElement>(null);const isHovering = useHover(ref);@@ -52,7 +51,7 @@ const AvailableAgentItem = memo<{if (!_agentId) return null;return (- <div className={cx(styles.listItem)} ref={ref} onClick={() => onToggle(_agentId)}>+ <div {...stylex.props(styles.listItem)} ref={ref} onClick={() => onToggle(_agentId)}><Flexbox horizontal align="center" gap={12} width="100%"><Checkboxchecked={isSelected}@@ -75,11 +74,9 @@ const AvailableAgentItem = memo<{/></Flexbox><Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>- <Text className={styles.title} weight={500}>- {title}- </Text>+ <Text weight={500}>{title}</Text>{description && (- <Text ellipsis className={styles.description}>+ <Text ellipsis className={stylex.props(styles.description).className}>{description}</Text>)}@@ -89,92 +86,70 @@ const AvailableAgentItem = memo<{);});-const styles = createStaticStyles(({ css, cssVar, responsive }) => ({- container: css`- display: flex;- flex-direction: row;-- height: 500px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadius};-- ${responsive.sm} {- flex-direction: column;- height: min(500px, calc(100dvh - 160px));- }- `,- description: css`- font-size: 11px;- line-height: 1.2;- color: ${cssVar.colorTextSecondary};- `,- hostCard: css`- margin-block-end: ${cssVar.paddingSM};- padding: ${cssVar.padding};- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorFillTertiary};-- ${responsive.sm} {- flex-direction: column;- align-items: stretch;- }- `,- hostModelSelect: css`- ${responsive.sm} {- flex: 1;- min-width: 0;- }- `,- leftColumn: css`- user-select: none;-- overflow-y: auto;- flex: 1;-- padding-block: ${cssVar.paddingSM} 0;- padding-inline: ${cssVar.paddingSM};- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};-- ${responsive.sm} {- min-height: 0;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- border-inline-end: 0;- }- `,- listItem: css`- cursor: pointer;-- position: relative;-- margin-block: 2px;- padding: ${cssVar.paddingSM} !important;- border-radius: ${cssVar.borderRadius};-- transition: all 0.2s ease;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- modelSelectDisabled: css`- pointer-events: none;- `,- rightColumn: css`- overflow-y: auto;- flex: 1;- padding: ${cssVar.paddingSM};-- ${responsive.sm} {- min-height: 0;- }- `,- selectedItem: css`- opacity: 0.6;- background: ${cssVar.colorFillQuaternary};- `,-}));+const styles = stylex.create({+ container: {+ display: 'flex',+ flexDirection: { default: 'row', [media.sm]: 'column' },+ height: { default: '500px', [media.sm]: 'min(500px, calc(100dvh - 160px))' },+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ },+ description: {+ fontSize: '11px',+ lineHeight: 1.2,+ color: cssVar.colorTextSecondary,+ },+ hostCard: {+ marginBlockEnd: cssVar.paddingSM,+ padding: cssVar.padding,+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ flexDirection: { default: null, [media.sm]: 'column' },+ alignItems: { default: null, [media.sm]: 'stretch' },+ },+ hostModelSelect: {+ flex: { default: null, [media.sm]: '1' },+ minWidth: { default: null, [media.sm]: 0 },+ },+ leftColumn: {+ userSelect: 'none',+ overflowY: 'auto',+ flex: '1',+ paddingBlockStart: cssVar.paddingSM,+ paddingBlockEnd: 0,+ paddingInline: cssVar.paddingSM,+ minHeight: { default: null, [media.sm]: 0 },+ borderBlockEndWidth: { default: null, [media.sm]: '1px' },+ borderBlockEndStyle: { default: null, [media.sm]: 'solid' },+ borderBlockEndColor: { default: null, [media.sm]: cssVar.colorBorderSecondary },+ borderInlineEndWidth: { default: '1px', [media.sm]: 0 },+ borderInlineEndStyle: 'solid',+ borderInlineEndColor: cssVar.colorBorderSecondary,+ },+ listItem: {+ cursor: 'pointer',+ position: 'relative',+ marginBlock: '2px',+ padding: cssVar.paddingSM,+ borderRadius: cssVar.borderRadius,+ transition: 'all 0.2s ease',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ modelSelectDisabled: { pointerEvents: 'none' },+ rightColumn: {+ overflowY: 'auto',+ flex: '1',+ padding: cssVar.paddingSM,+ minHeight: { default: null, [media.sm]: 0 },+ },+});export type MemberSelectionMode = 'create' | 'add';@@ -425,9 +400,9 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(}onCancel={handleCancel}>- <Flexbox horizontal className={styles.container}>+ <Flexbox horizontal className={stylex.props(styles.container).className}>{/* Left Column - Available Agents */}- <Flexbox className={styles.leftColumn} flex={1} gap={12}>+ <Flexbox className={stylex.props(styles.leftColumn).className} flex={1} gap={12}><SearchBarallowClearplaceholder={t('memberSelection.searchAgents')}@@ -450,10 +425,8 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(return (<AvailableAgentItemagent={agent}- cx={cx}isSelected={selectedAgents.includes(agentId)}key={agentId}- styles={styles}t={t}onToggle={handleAgentToggle}/>@@ -464,11 +437,16 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(</Flexbox>{/* Right Column - Host and Selected Agents */}- <Flexbox className={styles.rightColumn} flex={1}>+ <Flexbox className={stylex.props(styles.rightColumn).className} flex={1}><Flexbox gap={16}>{/* Host Card - Only show in create mode or when host is disabled in add mode */}{!isHostCurrentlyEnabled && (- <Flexbox horizontal align="center" className={styles.hostCard} gap={12}>+ <Flexbox+ horizontal+ align="center"+ className={stylex.props(styles.hostCard).className}+ gap={12}+ ><Flexbox flex={1} gap={2}><Textstyle={{ fontSize: 14, fontWeight: 500 }}@@ -485,10 +463,10 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(</Flexbox><Flexbox horizontal align="center" gap={12}><div- style={{ opacity: isHostRemoved ? 0.6 : 1 }}- className={cx(- styles.hostModelSelect,- isHostRemoved && styles.modelSelectDisabled,+ {...sx(+ [styles.hostModelSelect, isHostRemoved && styles.modelSelectDisabled],+ undefined,+ { opacity: isHostRemoved ? 0.6 : 1 },)}><ModelSelectdiff --git a/src/components/Menu/Menu.module.css b/src/components/Menu/Menu.module.cssnew file mode 100644index 00000000000..f83d1f32004--- /dev/null+++ b/src/components/Menu/Menu.module.css@@ -0,0 +1,3 @@+.inset > li:not([role='separator']) {+ margin-inline: 4px;+}diff --git a/src/components/Menu/index.tsx b/src/components/Menu/index.tsxindex ac8a866976d..26323b4979c 100644--- a/src/components/Menu/index.tsx+++ b/src/components/Menu/index.tsx@@ -1,16 +1,11 @@import { List, type ListProps } from '@lobehub/ui';-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';+import { cx } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import { memo } from 'react';-export type MenuProps = ListProps;+import styles from './Menu.module.css';-const styles = createStaticStyles(({ css }) => ({- inset: css`- & > li:not([role='separator']) {- margin-inline: 4px;- }- `,-}));+export type MenuProps = ListProps;const Menu = memo<MenuProps>(({ className, compact, selectable = false, styles: customStyles, ...rest }) => (diff --git a/src/components/ModelSelect/index.tsx b/src/components/ModelSelect/index.tsxindex 31e1769d478..adf367a6f9e 100644--- a/src/components/ModelSelect/index.tsx+++ b/src/components/ModelSelect/index.tsx@@ -3,16 +3,9 @@ import { type ChatModelCard } from '@lobechat/types';import { type IconAvatarProps } from '@lobehub/icons';import { LobeHub } from '@lobehub/icons';import { type FlexboxProps } from '@lobehub/ui';-import {- Avatar,- createStaticStyles,- Flexbox,- Icon,- Tag,- Text,- Tooltip,- useResponsive,-} from '@lobehub/ui';+import { Avatar, Flexbox, Icon, Tag, Text, Tooltip, useResponsive } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {AudioLines,Infinity as InfinityIcon,@@ -39,32 +32,27 @@ import RoutingBadge from './RoutingBadge';export const TAG_CLASSNAME = 'lobe-model-info-tags';-const styles = createStaticStyles(({ css, cssVar }) => ({- tag: css`- cursor: default;-- display: flex;- align-items: center;- justify-content: center;-- width: 20px !important;- height: 20px;- border-radius: 4px;- `,- token: css`- width: 36px !important;- height: 20px;- border-radius: 4px;-- font-family: ${cssVar.fontFamilyCode};- font-size: 11px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};- `,-}));--type TooltipStyles = typeof styles;+const styles = stylex.create({+ tag: {+ cursor: 'default',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '20px',+ borderRadius: '4px',+ },+ token: {+ width: '36px',+ height: '20px',+ borderRadius: '4px',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: '11px',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+});interface ModelInfoTagsProps extends ModelAbilities {contextWindowTokens?: number | null;@@ -194,18 +182,16 @@ const Context = memo(contextWindowTokens,disableTooltip,placement,- styles,}: {contextWindowTokens: number;disableTooltip?: boolean;placement: 'top' | 'right';- styles: TooltipStyles;}) => {const { t } = useTranslation('components');const tokensText = contextWindowTokens === 0 ? '∞' : formatTokenNumber(contextWindowTokens);const tag = (- <Tag className={styles.token} size={'small'}>+ <Tag className={stylex.props(styles.token).className} size={'small'}>{contextWindowTokens === 0 ? <InfinityIcon size={17} strokeWidth={1.6} /> : tokensText}</Tag>);@@ -242,7 +228,7 @@ export const ModelInfoTags = memo<ModelInfoTagsProps>(functionCall={model.functionCall}imageOutput={model.imageOutput}placement={placement}- tagClassName={styles.tag}+ tagClassName={stylex.props(styles.tag).className ?? ''}video={model.video}vision={model.vision}/>@@ -251,7 +237,6 @@ export const ModelInfoTags = memo<ModelInfoTagsProps>(contextWindowTokens={model.contextWindowTokens}disableTooltip={disableTooltip}placement={placement}- styles={styles}/>)}</Flexbox>diff --git a/src/components/Notification/index.tsx b/src/components/Notification/index.tsxindex ad6c93fd7fb..4883929cec8 100644--- a/src/components/Notification/index.tsx+++ b/src/components/Notification/index.tsx@@ -1,53 +1,51 @@'use client';import { type FlexboxProps } from '@lobehub/ui';-import { ActionIcon, createStaticStyles, cssVar, cx, Flexbox } from '@lobehub/ui';+import { ActionIcon, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { XIcon } from 'lucide-react';import { memo } from 'react';import { useIsDark } from '@/hooks/useIsDark';+import { sx } from '@/styles/sx';-const styles = createStaticStyles(({ css }) => ({- cancelIcon: css`- position: absolute;- z-index: 100;- inset-block-start: 8px;- inset-inline-end: 8px;- `,- container: css`- position: absolute;- z-index: 1100;- inset-block-end: 16px;- inset-inline-end: 20px;-- overflow: hidden;-- border: 1px solid ${cssVar.colorSplit};- border-radius: 8px;-- background: ${cssVar.colorBgContainer};- box-shadow: ${cssVar.boxShadowSecondary};- `,- mobileContainer: css`- inset-block-end: 8px;- inset-inline-start: 8px;- `,- wrapper: css`- background:- linear-gradient(+const styles = stylex.create({+ cancelIcon: {+ position: 'absolute',+ zIndex: 100,+ insetBlockStart: '8px',+ insetInlineEnd: '8px',+ },+ container: {+ position: 'absolute',+ zIndex: 1100,+ insetBlockEnd: '16px',+ insetInlineEnd: '20px',+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorSplit,+ borderRadius: '8px',+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ boxShadow: cssVar.boxShadowSecondary,+ },+ mobileContainer: {+ insetBlockEnd: '8px',+ insetInlineStart: '8px',+ },+ wrapper: {+ backgroundImage: `linear-gradient(180deg,color-mix(in srgb, ${cssVar.colorBgContainer} 0%, transparent),${cssVar.colorBgContainer} var(--gradient-stop, 140px)),- url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24'%3E%3Cg fill='${cssVar.colorFillTertiary}' %3E %3Cpolygon fill-rule='evenodd' points='8 4 12 6 8 8 6 12 4 8 0 6 4 4 6 0 8 4'/%3E%3C/g%3E%3C/svg%3E");- `,- wrapperDark: css`- --gradient-stop: 80px;- `,- wrapperLight: css`- --gradient-stop: 140px;- `,-}));+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24'%3E%3Cg fill='${cssVar.colorFillTertiary}' %3E %3Cpolygon fill-rule='evenodd' points='8 4 12 6 8 8 6 12 4 8 0 6 4 4 6 0 8 4'/%3E%3C/g%3E%3C/svg%3E")`,+ },+ wrapperDark: { '--gradient-stop': '80px' },+ wrapperLight: { '--gradient-stop': '140px' },+});interface NotificationProps extends FlexboxProps {height?: number | string;@@ -77,21 +75,24 @@ const Notification = memo<NotificationProps>(return (show && (<Flexbox- className={cx(styles.container, mobile && styles.mobileContainer, className)}height={height}width={mobile ? 'calc(100% - 16px)' : width}+ {...sx([styles.container, mobile && styles.mobileContainer], className)}{...rest}>{showCloseIcon && (- <ActionIcon className={styles.cancelIcon} icon={XIcon} onClick={() => onCancel?.()} />+ <ActionIcon+ className={stylex.props(styles.cancelIcon).className}+ icon={XIcon}+ onClick={() => onCancel?.()}+ />)}<Flexboxhorizontalgap={16}padding={'20px 20px 16px'}- className={cx(- styles.wrapper,- isDarkMode ? styles.wrapperDark : styles.wrapperLight,+ {...sx(+ [styles.wrapper, isDarkMode ? styles.wrapperDark : styles.wrapperLight],wrapperClassName,)}{...restWrapper}diff --git a/src/components/PublishedTime.tsx b/src/components/PublishedTime.tsxindex 25373d8dbe1..07bdc667715 100644--- a/src/components/PublishedTime.tsx+++ b/src/components/PublishedTime.tsx@@ -1,10 +1,13 @@'use client';-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import dayjs from 'dayjs';import { type CSSProperties, type FC } from 'react';import { useTranslation } from 'react-i18next';+import { sx } from '@/styles/sx';+const LAST_MODIFIED = new Date().toISOString();const formatTime = (time?: string) => {@@ -27,14 +30,12 @@ const formatDate = (date: string, t: (key: string) => string, template?: string)return d.format(t('time.formatOtherYear'));};-const styles = createStaticStyles(({ css }) => {- return {- time: css`- font-size: 12px;- color: ${cssVar.colorTextSecondary};- letter-spacing: 0.02em;- `,- };+const styles = stylex.create({+ time: {+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ letterSpacing: '0.02em',+ },});interface PublishedTimeProps {@@ -50,9 +51,8 @@ const PublishedTime: FC<PublishedTimeProps> = ({ date, style, className, templatreturn (<timearia-label={'published-date'}- className={cx(styles.time, className)}dateTime={formatTime(date)}- style={style}+ {...sx([styles.time], className, style)}>{time}</time>diff --git a/src/components/RatingOverview/Rate.tsx b/src/components/RatingOverview/Rate.tsxindex dd632fbcc5e..d32d8b32499 100644--- a/src/components/RatingOverview/Rate.tsx+++ b/src/components/RatingOverview/Rate.tsx@@ -1,15 +1,15 @@import { Rate as BaseRate, type RateProps } from '@lobehub/ui';-import { createStaticStyles, cx } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';-const styles = createStaticStyles(({ css }) => ({- rate: css`- display: flex;- `,-}));+import { sx } from '@/styles/sx';++const styles = stylex.create({+ rate: { display: 'flex' },+});const Rate = memo<RateProps>(({ className, size = 16, ...props }) => (- <BaseRate allowHalf readOnly className={cx(styles.rate, className)} size={size} {...props} />+ <BaseRate allowHalf readOnly size={size} {...sx([styles.rate], className)} {...props} />));export default Rate;diff --git a/src/components/Skeleton/AgentChannel.tsx b/src/components/Skeleton/AgentChannel.tsxindex 2f735033cab..6520eb8f9b0 100644--- a/src/components/Skeleton/AgentChannel.tsx+++ b/src/components/Skeleton/AgentChannel.tsx@@ -1,6 +1,9 @@'use client';-import { Block, createStaticStyles, cssVar, Flexbox, responsive } from '@lobehub/ui';+import { Block, Flexbox } 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 { RouteSkeletonProps } from '@/spa/router/routeMeta';@@ -10,53 +13,44 @@ import SkeletonBar from './Bar';/** Platform cards drawn by the list skeleton — the built-in catalog fills three rows. */const PLATFORM_CARD_COUNT = 9;-const styles = createStaticStyles(({ css }) => ({+const styles = stylex.create({// `content-box` so the 1px divider sits outside the measured row height,// matching `Form.Field divider` / `Form.Group` (64px rows, 45px group header).- advanced: css`- box-sizing: content-box;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- `,- card: css`- min-height: 104px;- `,- field: css`- box-sizing: content-box;- min-height: 64px;-- & + & {- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- }- `,- grid: css`- display: grid;- grid-template-columns: repeat(3, minmax(0, 1fr));- gap: 12px;- width: 100%;-- ${responsive.md} {- grid-template-columns: repeat(2, minmax(0, 1fr));- }-- ${responsive.sm} {- grid-template-columns: minmax(0, 1fr);- }- `,- root: css`- overflow: hidden;- display: flex;- flex: 1;- flex-direction: column;- align-items: center;-- width: 100%;- min-height: 0;- `,- title: css`- height: 34px;- margin-block-end: 20px;- `,-}));+ advanced: {+ boxSizing: 'content-box',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+ card: { minHeight: '104px' },+ field: { boxSizing: 'content-box', minHeight: '64px' },+ // `& + &`: every field after the first draws a divider above it.+ fieldDivider: {+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+ grid: {+ display: 'grid',+ gridTemplateColumns: {+ default: 'repeat(3, minmax(0, 1fr))',+ [media.md]: 'repeat(2, minmax(0, 1fr))',+ [media.sm]: 'minmax(0, 1fr)',+ },+ gap: '12px',+ width: '100%',+ },+ root: {+ overflow: 'hidden',+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ alignItems: 'center',+ width: '100%',+ minHeight: 0,+ },+ title: { height: '34px', marginBlockEnd: '20px' },+});/*** Body of the agent channel list (`features/AgentChannel/PlatformGrid.tsx`):@@ -66,17 +60,28 @@ const styles = createStaticStyles(({ css }) => ({* data-loading state, so route load and platform fetch share one shape.*/export const AgentChannelListBodySkeleton = () => (- <div aria-busy className={styles.root}>+ <div aria-busy {...stylex.props(styles.root)}><Flexbox padding={24} width={'100%'}><Flexbox style={{ alignSelf: 'center', maxWidth: 1024, width: '100%' }}>- <Flexbox horizontal align={'center'} className={styles.title} gap={8}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.title).className}+ gap={8}+ ><SkeletonBar height={24} width={220} /><SkeletonBar height={28} width={28} /><SkeletonBar height={24} width={96} /></Flexbox>- <div className={styles.grid}>+ <div {...stylex.props(styles.grid)}>{Array.from({ length: PLATFORM_CARD_COUNT }).map((_, index) => (- <Block className={styles.card} gap={8} key={index} padding={12} variant={'outlined'}>+ <Block+ className={stylex.props(styles.card).className}+ gap={8}+ key={index}+ padding={12}+ variant={'outlined'}+ ><Flexbox horizontal align={'center'} gap={8} height={24}><SkeletonBar height={24} width={24} /><SkeletonBar height={14} width={56 + (index % 3) * 12} />@@ -100,7 +105,7 @@ export const AgentChannelListBodySkeleton = () => (* group — followed by the right-aligned save button of the footer.*/export const AgentChannelDetailBodySkeleton = () => (- <div aria-busy className={styles.root}>+ <div aria-busy {...stylex.props(styles.root)}><Flexboxalign={'center'}paddingInline={24}@@ -113,7 +118,7 @@ export const AgentChannelDetailBodySkeleton = () => (<Flexboxhorizontalalign={'center'}- className={styles.field}+ className={stylex.props(styles.field, index > 0 && styles.fieldDivider).className}gap={16}justify={'space-between'}key={index}@@ -126,7 +131,7 @@ export const AgentChannelDetailBodySkeleton = () => (</Flexbox>))}{/* Collapsed `Form.Group` header: a 28px title button at the top of a 45px row. */}- <Flexbox className={styles.advanced} height={45}>+ <Flexbox className={stylex.props(styles.advanced).className} height={45}><Flexbox justify={'center'} style={{ height: 28 }}><SkeletonBar height={13} width={52} /></Flexbox>diff --git a/src/components/Skeleton/AgentShare.tsx b/src/components/Skeleton/AgentShare.tsxindex 1d92a31ee47..b30a9d74713 100644--- a/src/components/Skeleton/AgentShare.tsx+++ b/src/components/Skeleton/AgentShare.tsx@@ -1,6 +1,8 @@'use client';-import { Block, createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Block, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import type { ReactNode } from 'react';import WideScreenContainer from '@/features/WideScreenContainer';@@ -9,16 +11,21 @@ import type { RouteSkeletonProps } from '@/spa/router/routeMeta';import AgentProfileNavSkeleton from './AgentProfileNav';import SkeletonBar from './Bar';-const styles = createStaticStyles(({ css }) => ({- notice: css`- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorFillQuaternary};- `,- tabs: css`- border-block-end: 1px solid ${cssVar.colorBorder};- `,-}));+const styles = stylex.create({+ notice: {+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ tabs: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorder,+ },+});const SettingRowSkeleton = ({ control, index }: { control: 'switch' | 'input'; index: number }) => (<Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>@@ -65,7 +72,7 @@ export const AgentShareSettingsBodySkeleton = () => (<Flexboxhorizontalalign={'flex-start'}- className={styles.notice}+ className={stylex.props(styles.notice).className}gap={12}padding={'12px 16px'}>@@ -80,7 +87,7 @@ export const AgentShareSettingsBodySkeleton = () => (<SkeletonBar height={36} width={'100%'} /></SectionSkeleton>{/* Mirrors `ShareTabs`: two underline tabs on a hairline. */}- <Flexbox horizontal className={styles.tabs} gap={24} paddingBlock={10}>+ <Flexbox horizontal className={stylex.props(styles.tabs).className} gap={24} paddingBlock={10}><SkeletonBar height={14} width={64} /><SkeletonBar height={14} width={64} /></Flexbox>diff --git a/src/components/Skeleton/AgentStatistics.tsx b/src/components/Skeleton/AgentStatistics.tsxindex 012d04fdadc..937d07048bc 100644--- a/src/components/Skeleton/AgentStatistics.tsx+++ b/src/components/Skeleton/AgentStatistics.tsx@@ -1,6 +1,8 @@'use client';-import { Block, createStaticStyles, cssVar, Flexbox, Grid, Skeleton } from '@lobehub/ui';+import { Block, Flexbox, Grid, Skeleton } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import WideScreenContainer from '@/features/WideScreenContainer';import type { RouteSkeletonProps } from '@/spa/router/routeMeta';@@ -8,15 +10,21 @@ import type { RouteSkeletonProps } from '@/spa/router/routeMeta';import AgentProfileNavSkeleton from './AgentProfileNav';import SkeletonBar from './Bar';-const styles = createStaticStyles(({ css }) => ({- tableHead: css`- border-radius: ${cssVar.borderRadius} ${cssVar.borderRadius} 0 0;- background: ${cssVar.colorFillQuaternary};- `,- tableRow: css`- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ tableHead: {+ borderTopLeftRadius: cssVar.borderRadius,+ borderTopRightRadius: cssVar.borderRadius,+ borderBottomRightRadius: '0',+ borderBottomLeftRadius: '0',+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ tableRow: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ },+});/** Label + small Segmented pair of the controls row (`维度 [按天|按周]`). */const LabelledSegmentedSkeleton = ({@@ -70,7 +78,7 @@ const ModelBreakdownRowsSkeleton = () => (<Flexboxhorizontalalign={'center'}- className={styles.tableRow}+ className={stylex.props(styles.tableRow).className}gap={16}key={index}paddingBlock={12}@@ -103,7 +111,7 @@ export const AgentModelBreakdownTableSkeleton = () => (<Flexboxhorizontalalign={'center'}- className={styles.tableHead}+ className={stylex.props(styles.tableHead).className}gap={16}height={44}paddingInline={16}diff --git a/src/components/Skeleton/AgentViewAll.tsx b/src/components/Skeleton/AgentViewAll.tsxindex d49d6c7f560..6d12c0bd9c0 100644--- a/src/components/Skeleton/AgentViewAll.tsx+++ b/src/components/Skeleton/AgentViewAll.tsx@@ -1,6 +1,8 @@'use client';-import { Block, Center, createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Block, Center, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import WideScreenContainer from '@/features/WideScreenContainer';import type { RouteSkeletonProps } from '@/spa/router/routeMeta';@@ -14,25 +16,20 @@ const ACTION_COL_WIDTH = 64;const NAME_COL_WIDTH = 240;const ROLE_COL_WIDTH = 200;-const styles = createStaticStyles(({ css }) => ({- sidebarCard: css`- min-height: 72px;- padding-block: 10px;- padding-inline: 12px;- `,- sidebarGrid: css`- display: grid;-- /* Full-width page: as many 280px+ columns as fit, one column on narrow screens. */- grid-template-columns: repeat(auto-fill, minmax(min(280px, 100%), 1fr));- gap: 12px;- `,- sidebarSection: css`- padding: 12px;- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorFillQuaternary};- `,-}));+const styles = stylex.create({+ sidebarCard: { minHeight: '72px', paddingBlock: '10px', paddingInline: '12px' },+ sidebarGrid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(min(280px, 100%), 1fr))',+ gap: '12px',+ },+ sidebarSection: {+ padding: '12px',+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+});/*** The "In sidebar" block (`features/AgentViewAll/SidebarAgentsSection.tsx`)@@ -47,7 +44,7 @@ export const AgentViewAllSidebarSectionSkeleton = () => {return (<Flexbox- className={styles.sidebarSection}+ className={stylex.props(styles.sidebarSection).className}data-testid={'agent-view-all-sidebar-skeleton'}gap={12}>@@ -56,10 +53,10 @@ export const AgentViewAllSidebarSectionSkeleton = () => {<SkeletonBar height={12} width={40} /></Flexbox>{!collapsed && (- <div className={styles.sidebarGrid}>+ <div {...stylex.props(styles.sidebarGrid)}>{[0, 1, 2].map((key) => (<Block- className={styles.sidebarCard}+ className={stylex.props(styles.sidebarCard).className}data-testid={'agent-view-all-sidebar-card-skeleton'}key={key}variant={'outlined'}diff --git a/src/components/Skeleton/CommunityList.tsx b/src/components/Skeleton/CommunityList.tsxindex 4ec1eff15f6..53f7746e61b 100644--- a/src/components/Skeleton/CommunityList.tsx+++ b/src/components/Skeleton/CommunityList.tsx@@ -1,6 +1,8 @@'use client';-import { Block, createStaticStyles, Flexbox, Grid, Skeleton } from '@lobehub/ui';+import { Block, Flexbox, Grid, Skeleton } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo, type ReactNode } from 'react';import WideScreenContainer from '@/features/WideScreenContainer';@@ -8,15 +10,20 @@ import type { RouteSkeletonChrome, RouteSkeletonProps } from '@/spa/router/routeconst COMMUNITY_MAX_WIDTH = 1440;-const styles = createStaticStyles(({ css, cssVar }) => ({- footer: css`- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- toolbar: css`- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ footer: {+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ toolbar: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ },+});// Mirrors the community list layout (search header + centered wide-screen// container) for the fallback that paints before that layout has mounted.@@ -34,7 +41,7 @@ export const CommunityPageChrome = ({<Flexboxhorizontalalign={'center'}- className={styles.toolbar}+ className={stylex.props(styles.toolbar).className}flex={'none'}gap={12}height={56}@@ -87,7 +94,7 @@ const CommunityListSkeleton = memo<CommunityListSkeletonProps>(<Skeleton height={20} width={50} /></Flexbox><Flexbox- className={styles.footer}+ className={stylex.props(styles.footer).className}gap={4}padding={8}style={{ marginBottom: -16, marginInline: -16 }}diff --git a/src/components/Skeleton/Conversation/AgentLayout.tsx b/src/components/Skeleton/Conversation/AgentLayout.tsxindex 66342f0339b..08081e66514 100644--- a/src/components/Skeleton/Conversation/AgentLayout.tsx+++ b/src/components/Skeleton/Conversation/AgentLayout.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {OVERVIEW_PANEL_WIDTH,@@ -12,17 +14,22 @@ import { systemStatusSelectors } from '@/store/global/selectors';import SkeletonBar from '../Bar';import ConversationLayoutSkeleton from './Layout';-const styles = createStaticStyles(({ css }) => ({- overviewCard: css`- margin: 16px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 16px;- background: ${cssVar.colorBgContainer};- `,- rightPanel: css`- border-inline-start: 1px solid ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ overviewCard: {+ margin: '16px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: '16px',+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ rightPanel: {+ borderInlineStartWidth: '1px',+ borderInlineStartStyle: 'solid',+ borderInlineStartColor: cssVar.colorBorderSecondary,+ },+});const PanelRows = ({ rows }: { rows: number }) => (<Flexbox gap={12} padding={16}>@@ -51,7 +58,7 @@ const AgentConversationLayoutSkeleton = () => {aside={overview && (<Flexbox flex={'none'} width={OVERVIEW_PANEL_WIDTH + 32}>- <Flexbox className={styles.overviewCard}>+ <Flexbox className={stylex.props(styles.overviewCard).className}><PanelRows rows={5} /></Flexbox></Flexbox>@@ -59,7 +66,11 @@ const AgentConversationLayoutSkeleton = () => {}/>{rightPanelWidth && (- <Flexbox className={styles.rightPanel} flex={'none'} width={rightPanelWidth}>+ <Flexbox+ className={stylex.props(styles.rightPanel).className}+ flex={'none'}+ width={rightPanelWidth}+ ><PanelRows rows={8} /></Flexbox>)}diff --git a/src/components/Skeleton/Conversation/Container.tsx b/src/components/Skeleton/Conversation/Container.tsxindex c14f5db3cb3..e4b22bc25a4 100644--- a/src/components/Skeleton/Conversation/Container.tsx+++ b/src/components/Skeleton/Conversation/Container.tsx@@ -1,18 +1,17 @@'use client';import { type FlexboxProps } from '@lobehub/ui';-import { createStaticStyles, cx, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { CONVERSATION_MIN_WIDTH } from '@/const/layoutTokens';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';+import { sx } from '@/styles/sx';-const styles = createStaticStyles(({ css }) => ({- container: css`- flex-grow: 1;- align-self: center;- `,-}));+const styles = stylex.create({+ container: { flexGrow: 1, alignSelf: 'center' },+});const ConversationSkeletonContainer = ({children,@@ -26,7 +25,7 @@ const ConversationSkeletonContainer = ({return (<Flexbox aria-busy flex={flex} height={height} style={{ minHeight: 0 }} width={'100%'}><Flexbox- className={cx(styles.container, className)}+ {...sx([styles.container], className)}flex={flex}height={height}paddingInline={16}diff --git a/src/components/Skeleton/Conversation/Segment.tsx b/src/components/Skeleton/Conversation/Segment.tsxindex cb643224690..6507658bd3c 100644--- a/src/components/Skeleton/Conversation/Segment.tsx+++ b/src/components/Skeleton/Conversation/Segment.tsx@@ -1,27 +1,33 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import SkeletonBar from '../Bar';import ConversationSkeletonContainer from './Container';import ConversationListSkeleton from './List';-const styles = createStaticStyles(({ css }) => ({- composer: css`- overflow: hidden;-- height: 106px;- border: 1px solid ${cssVar.colorFill};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorBgElevated};- box-shadow: 0 4px 4px color-mix(in srgb, #000 4%, transparent);- `,-}));+const styles = stylex.create({+ composer: {+ overflow: 'hidden',+ height: '106px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorFill,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ boxShadow: '0 4px 4px color-mix(in srgb, #000 4%, transparent)',+ },+});const ComposerSkeleton = () => (<ConversationSkeletonContainer flex={'none'} paddingBlock={'0 8px'}>- <Flexbox className={styles.composer} data-testid={'conversation-composer-skeleton'}>+ <Flexbox+ className={stylex.props(styles.composer).className}+ data-testid={'conversation-composer-skeleton'}+ ><Flexbox flex={1} paddingBlock={'12px 8px'} paddingInline={12}><SkeletonBar height={14} width={'38%'} /></Flexbox>diff --git a/src/components/Skeleton/Goal.tsx b/src/components/Skeleton/Goal.tsxindex 736dff3b559..fa9cbe61fbf 100644--- a/src/components/Skeleton/Goal.tsx+++ b/src/components/Skeleton/Goal.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import NavHeader from '@/features/NavHeader';import WideScreenContainer from '@/features/WideScreenContainer';@@ -8,13 +10,15 @@ import type { RouteSkeletonProps } from '@/spa/router/routeMeta';import SkeletonBar from './Bar';-const styles = createStaticStyles(({ css }) => ({- listRows: css`- display: flex;- flex-direction: column;- border-block: 1px solid ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ listRows: {+ display: 'flex',+ flexDirection: 'column',+ borderBlockWidth: '1px',+ borderBlockStyle: 'solid',+ borderBlockColor: cssVar.colorBorderSecondary,+ },+});/*** The three row shapes a goal list settles into. Exported so a list that is@@ -22,7 +26,7 @@ const styles = createStaticStyles(({ css }) => ({* blank while the server answers.*/export const GoalListRowsSkeleton = () => (- <Flexbox aria-busy className={styles.listRows}>+ <Flexbox aria-busy className={stylex.props(styles.listRows).className}>{Array.from({ length: 3 }).map((_, index) => (<Flexbox horizontal align={'center'} gap={12} key={index} paddingBlock={14}><SkeletonBar height={20} radius={'50%'} width={20} />diff --git a/src/components/Skeleton/Profile.tsx b/src/components/Skeleton/Profile.tsxindex e48c58132ce..10efc1337fb 100644--- a/src/components/Skeleton/Profile.tsx+++ b/src/components/Skeleton/Profile.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import WideScreenContainer from '@/features/WideScreenContainer';import type { RouteSkeletonProps } from '@/spa/router/routeMeta';@@ -13,36 +15,43 @@ interface ProfileSkeletonProps extends RouteSkeletonProps {variant?: ProfileSkeletonVariant;}-const styles = createStaticStyles(({ css }) => ({- configPanel: css`- padding: 24px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorFillQuaternary};- `,- cover: css`- width: calc(100% + 32px);- height: 80px;- margin-inline: -16px;- background: ${cssVar.colorFillQuaternary};- `,- divider: css`- width: 100%;- height: 1px;- background: ${cssVar.colorBorderSecondary};- `,- editor: css`- padding-block: 24px 96px;- `,- header: css`- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ configPanel: {+ padding: '24px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ cover: {+ width: 'calc(100% + 32px)',+ height: '80px',+ marginInline: '-16px',+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ divider: {+ width: '100%',+ height: '1px',+ backgroundColor: cssVar.colorBorderSecondary,+ backgroundImage: 'none',+ },+ editor: { paddingBlockStart: '24px', paddingBlockEnd: '96px' },+ header: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ },+});-const NavigationSkeleton = () => <Flexbox className={styles.header} flex={'none'} height={44} />;+const NavigationSkeleton = () => (+ <Flexbox className={stylex.props(styles.header).className} flex={'none'} height={44} />+);const EditorPlaceholder = () => (- <Flexbox className={styles.editor} gap={14}>+ <Flexbox className={stylex.props(styles.editor).className} gap={14}><SkeletonBar height={18} width={120} /><SkeletonBar height={14} width={'92%'} /><SkeletonBar height={14} width={'84%'} />@@ -54,7 +63,7 @@ const AgentProfileSkeleton = () => (<WideScreenContainer><Flexbox style={{ marginBottom: 28 }}><Flexbox paddingBlock={'0 16px'} style={{ marginInline: -16 }}>- <div className={styles.cover} />+ <div {...stylex.props(styles.cover)} /><Flexboxhorizontalalign={'flex-end'}@@ -69,7 +78,7 @@ const AgentProfileSkeleton = () => (</Flexbox></Flexbox></Flexbox>- <Flexbox className={styles.configPanel} gap={14}>+ <Flexbox className={stylex.props(styles.configPanel).className} gap={14}><Flexbox horizontal align={'center'} justify={'space-between'}><SkeletonBar height={12} width={96} /><SkeletonBar height={12} width={72} />@@ -97,7 +106,7 @@ const GroupProfileSkeleton = () => (<SkeletonBar height={32} width={132} /><SkeletonBar height={32} width={96} /></Flexbox>- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /><EditorPlaceholder /></WideScreenContainer>);diff --git a/src/components/Skeleton/ResourceHome.tsx b/src/components/Skeleton/ResourceHome.tsxindex 315fa797a8d..61031277e98 100644--- a/src/components/Skeleton/ResourceHome.tsx+++ b/src/components/Skeleton/ResourceHome.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { cssVar as cssVarValue, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import SkeletonBar from './Bar';@@ -32,27 +34,27 @@ export const ResourceSectionSkeleton = ({}}>{Array.from({ length: count }).map((_, index) => (- <SkeletonBar height={itemHeight} key={index} radius={cssVar.borderRadiusLG} />+ <SkeletonBar height={itemHeight} key={index} radius={cssVarValue.borderRadiusLG} />))}</div>);-const styles = createStaticStyles(({ css }) => ({- content: css`- width: 100%;- max-width: 1200px;- margin-inline: auto;- padding-block: 24px 64px;- padding-inline: 32px;- `,- header: css`- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,- scroll: css`- overflow: hidden;- flex: 1;- `,-}));+const styles = stylex.create({+ content: {+ width: '100%',+ maxWidth: '1200px',+ marginInline: 'auto',+ paddingBlockStart: '24px',+ paddingBlockEnd: '64px',+ paddingInline: '32px',+ },+ header: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ },+ scroll: { overflow: 'hidden', flex: '1' },+});/** Mirrors the Docs home: quick actions, then the tabbed list. */const ListSkeleton = () => (@@ -75,7 +77,7 @@ const ResourceHomeSkeleton = () => (<Flexboxhorizontalalign={'center'}- className={styles.header}+ className={stylex.props(styles.header).className}flex={'none'}height={44}justify={'space-between'}@@ -84,8 +86,8 @@ const ResourceHomeSkeleton = () => (<SkeletonBar height={20} width={96} /><SkeletonBar height={28} width={88} /></Flexbox>- <div className={styles.scroll}>- <Flexbox className={styles.content} gap={28}>+ <div className={stylex.props(styles.scroll).className}>+ <Flexbox className={stylex.props(styles.content).className} gap={28}><ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.quickActions} /><ListSkeleton /></Flexbox>diff --git a/src/components/Skeleton/Settings/MessengerDetail.tsx b/src/components/Skeleton/Settings/MessengerDetail.tsxindex b658f689f8f..c14cb229456 100644--- a/src/components/Skeleton/Settings/MessengerDetail.tsx+++ b/src/components/Skeleton/Settings/MessengerDetail.tsx@@ -1,21 +1,25 @@'use client';-import { Block, createStaticStyles, Flexbox, Skeleton } from '@lobehub/ui';+import { Block, Flexbox, Skeleton } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => ({- card: css`- padding: 16px;- border: 1px solid ${cssVar.colorBorder};- border-radius: ${cssVar.borderRadius};- `,-}));+const styles = stylex.create({+ card: {+ padding: '16px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorder,+ borderRadius: cssVar.borderRadius,+ },+});const ConnectionsSkeleton = memo<{ withNestedContent?: boolean }>(({ withNestedContent = false }) => (<Flexbox gap={12}>{Array.from({ length: 2 }).map((_, index) => (- <Block className={styles.card} key={index}>+ <Block className={stylex.props(styles.card).className} key={index}><Flexbox gap={12}><Flexbox horizontal align="center" gap={12}><Skeleton.Avatar shape={'square'} size={36} />@@ -48,7 +52,7 @@ export const IntegrationDetailSkeleton = memo<{ withNestedContent?: boolean }>(<Skeleton height={28} width={96} /></Flexbox>- <Block className={styles.card}>+ <Block className={stylex.props(styles.card).className}><Flexbox horizontal align="center" gap={16}><Skeleton.Avatar shape={'square'} size={48} /><Flexbox flex={1} gap={6}>diff --git a/src/components/Skeleton/Settings/Profile.tsx b/src/components/Skeleton/Settings/Profile.tsxindex acf7ff3a806..ec16b835b71 100644--- a/src/components/Skeleton/Settings/Profile.tsx+++ b/src/components/Skeleton/Settings/Profile.tsx@@ -1,7 +1,10 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { Form } from '@lobehub/ui/form';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { media } from '@lobehub/ui/stylex/media.stylex';+import * as stylex from '@stylexjs/stylex';import { type ReactNode } from 'react';import { useUserStore } from '@/store/user';@@ -9,47 +12,36 @@ import { authSelectors, userProfileSelectors } from '@/store/user/selectors';import SkeletonBar from '../Bar';-const styles = createStaticStyles(({ css, responsive }) => ({- action: css`- flex-shrink: 0;- margin-inline-start: auto;- `,- body: css`- display: flex;- flex: 1;- gap: 12px;- align-items: center;- justify-content: space-between;-- min-width: 0;- `,- divider: css`- width: 100%;- height: 1px;- background: ${cssVar.colorBorderSecondary};- `,- label: css`- flex: 0 0 160px;-- ${responsive.md} {- flex: 0 0 auto;- }- `,- row: css`- display: flex;- gap: 24px;- align-items: center;-- min-height: 48px;- padding-block: 16px;-- ${responsive.md} {- flex-direction: column;- gap: 12px;- align-items: stretch;- }- `,-}));+const styles = stylex.create({+ action: { flexShrink: 0, marginInlineStart: 'auto' },+ body: {+ display: 'flex',+ flex: '1',+ gap: '12px',+ alignItems: 'center',+ justifyContent: 'space-between',+ minWidth: '0',+ },+ divider: {+ width: '100%',+ height: '1px',+ backgroundColor: cssVar.colorBorderSecondary,+ backgroundImage: 'none',+ },+ label: {+ flexGrow: { default: 0, [media.md]: 0 },+ flexShrink: { default: 0, [media.md]: 0 },+ flexBasis: { default: '160px', [media.md]: 'auto' },+ },+ row: {+ display: 'flex',+ gap: { default: '24px', [media.md]: '12px' },+ alignItems: { default: 'center', [media.md]: 'stretch' },+ minHeight: '48px',+ paddingBlock: '16px',+ flexDirection: { default: null, [media.md]: 'column' },+ },+});interface SettingsProfileRowSkeletonProps {action?: boolean;@@ -68,14 +60,19 @@ export const SettingsProfileRowSkeleton = ({height,labelWidth = 80,}: SettingsProfileRowSkeletonProps) => (- <div className={styles.row} style={height ? { minHeight: height } : undefined}>- <div className={styles.label}>+ <div+ className={stylex.props(styles.row).className}+ style={height ? { minHeight: height } : undefined}+ >+ <div {...stylex.props(styles.label)}><SkeletonBar height={22} width={labelWidth} /></div>- <div className={styles.body}>+ <div {...stylex.props(styles.body)}>{body === undefined ? <SkeletonBar height={22} width={bodyWidth} /> : body}{action && (- <div className={styles.action}>{actionNode ?? <SkeletonBar height={22} width={80} />}</div>+ <div {...stylex.props(styles.action)}>+ {actionNode ?? <SkeletonBar height={22} width={80} />}+ </div>)}</div></div>@@ -111,11 +108,11 @@ const SettingsProfileSkeleton = () => {body={null}height={78}/>- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /><SettingsProfileRowSkeleton action={false} bodyWidth={194} height={68} labelWidth={72} />- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /><SettingsProfileRowSkeleton action={false} bodyWidth={194} height={68} labelWidth={88} />- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /><SettingsProfileRowSkeletonaction={false}body={<InterestsSkeleton />}@@ -124,7 +121,7 @@ const SettingsProfileSkeleton = () => {/>{isLogin && email && (<>- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /><SettingsProfileRowSkeleton bodyWidth={184} height={54} labelWidth={96} /></>)}diff --git a/src/components/Skeleton/Settings/Section.module.css b/src/components/Skeleton/Settings/Section.module.cssnew file mode 100644index 00000000000..1f3402aaf03--- /dev/null+++ b/src/components/Skeleton/Settings/Section.module.css@@ -0,0 +1,5 @@+/* A loaded settings form renders its fields flush in the group body (each field+ pads itself), while a bare `Form.Group` pads the body by 16px on both ends. */+.group > :last-child {+ padding-block: 0;+}diff --git a/src/components/Skeleton/Settings/Section.tsx b/src/components/Skeleton/Settings/Section.tsxindex e4974ef171e..6698a4aead6 100644--- a/src/components/Skeleton/Settings/Section.tsx+++ b/src/components/Skeleton/Settings/Section.tsx@@ -1,33 +1,29 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { Form } from '@lobehub/ui/form';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import SkeletonBar from '../Bar';+import moduleStyles from './Section.module.css';-const styles = createStaticStyles(({ css }) => ({- divider: css`- width: 100%;- height: 1px;- background: ${cssVar.colorBorderSecondary};- `,- // A loaded settings form renders its fields flush in the group body (each field- // pads itself), while a bare `Form.Group` pads the body by 16px on both ends.- group: css`- & > :last-child {- padding-block: 0;- }- `,- row: css`- display: flex;- gap: 24px;- align-items: center;- justify-content: space-between;-- min-height: 64px;- padding-block: 16px;- `,-}));+const styles = stylex.create({+ divider: {+ width: '100%',+ height: '1px',+ backgroundColor: cssVar.colorBorderSecondary,+ backgroundImage: 'none',+ },+ row: {+ display: 'flex',+ gap: '24px',+ alignItems: 'center',+ justifyContent: 'space-between',+ minHeight: '64px',+ paddingBlock: '16px',+ },+});export interface SettingsSectionSkeletonControl {height: number;@@ -43,7 +39,7 @@ const Row = ({index: number;withDesc: boolean;}) => (- <div className={styles.row}>+ <div {...stylex.props(styles.row)}>{/* Line boxes match the loaded label (14px / 22px) and description (12px / 13px) stack. */}<Flexbox gap={4}><Flexbox height={22} justify={'center'}>@@ -92,7 +88,7 @@ const Group = ({withDesc = true,}: SettingsSectionSkeletonGroup) => (<Form.Group- className={styles.group}+ className={moduleStyles.group}collapsible={false}variant={'filled'}title={@@ -105,7 +101,7 @@ const Group = ({<Flexbox>{Array.from({ length: rows }).map((_, index) => (<Flexbox key={index}>- {index > 0 && <div className={styles.divider} />}+ {index > 0 && <div {...stylex.props(styles.divider)} />}<Row control={controls?.[index] ?? control} index={index} withDesc={withDesc} /></Flexbox>))}diff --git a/src/components/Skeleton/Settings/Sections.module.css b/src/components/Skeleton/Settings/Sections.module.cssnew file mode 100644index 00000000000..a708d7d7cd6--- /dev/null+++ b/src/components/Skeleton/Settings/Sections.module.css@@ -0,0 +1,7 @@+.flush {+ overflow: hidden;+}++.flush [data-form-group-body] {+ padding: 0;+}diff --git a/src/components/Skeleton/Settings/Sections.tsx b/src/components/Skeleton/Settings/Sections.tsxindex 4ec474b95b5..38f0ac4997d 100644--- a/src/components/Skeleton/Settings/Sections.tsx+++ b/src/components/Skeleton/Settings/Sections.tsx@@ -1,14 +1,18 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { Form } from '@lobehub/ui/form';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import type { ComponentType, ReactNode } from 'react';import NavHeader from '@/features/NavHeader';import SettingContainer from '@/features/Setting/SettingContainer';import type { RouteSkeletonProps } from '@/spa/router/routeMeta';+import { sx } from '@/styles/sx';import SkeletonBar from '../Bar';+import moduleStyles from './Sections.module.css';/** Shared head options of every section rendered as a filled `Form.Group`. */interface GroupHeadOptions {@@ -100,36 +104,36 @@ export interface SettingsSectionsShape {*/export type SettingsSectionsFrame = 'container' | 'header' | 'none';-const styles = createStaticStyles(({ css }) => ({- banner: css`- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- `,- card: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- `,- divider: css`- width: 100%;- height: 1px;- background: ${cssVar.colorBorderSecondary};- `,- flush: css`- overflow: hidden;-- [data-form-group-body] {- padding: 0;- }- `,- grid: css`- display: grid;- `,- tile: css`- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ banner: {+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ },+ card: {+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ },+ divider: {+ width: '100%',+ height: '1px',+ backgroundColor: cssVar.colorBorderSecondary,+ backgroundImage: 'none',+ },+ grid: { display: 'grid' },+ tile: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderInlineEndWidth: '1px',+ borderInlineEndStyle: 'solid',+ borderInlineEndColor: cssVar.colorBorderSecondary,+ },+});const widthAt = (index: number, widths: number[]) => widths[index % widths.length];@@ -155,7 +159,7 @@ const Group = ({titleWidth,}: GroupHeadOptions & { children: ReactNode; flush?: boolean }) => (<Form.Group- className={flush ? styles.flush : undefined}+ className={flush ? moduleStyles.flush : undefined}collapsible={false}desc={desc ? <GroupDesc /> : undefined}extra={extra ? <SkeletonBar height={32} width={120} /> : undefined}@@ -170,7 +174,7 @@ const FormRows = ({ rows }: { rows: number }) => (<Flexbox>{Array.from({ length: rows }).map((_, index) => (<Flexbox key={index}>- {index > 0 && <div className={styles.divider} />}+ {index > 0 && <div {...stylex.props(styles.divider)} />}<Flexboxhorizontalalign={'center'}@@ -231,7 +235,7 @@ const TableBody = ({</Flexbox>{Array.from({ length: rows }).map((_, row) => (<Flexbox key={row}>- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /><Flexbox horizontal align={'center'} gap={24} height={52} paddingInline={16}>{TABLE_COLUMNS.map((flex, index) => (<Flexbox flex={flex} key={index}>@@ -263,14 +267,13 @@ const Tiles = ({tiles: number;}) => (<div- className={styles.grid}- style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}+ {...sx([styles.grid], undefined, { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` })}>{Array.from({ length: tiles }).map((_, index) => (<Flexboxhorizontalalign={'center'}- className={styles.tile}+ className={stylex.props(styles.tile).className}gap={12}height={tileHeight}justify={'space-between'}@@ -300,7 +303,7 @@ const Summary = ({<SkeletonBar height={28} width={48} /><SkeletonBar height={16} width={72} /><SkeletonBar height={20} width={'56%'} />- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /><SkeletonBar height={20} width={200} /></Flexbox>) : (@@ -340,14 +343,14 @@ const Detail = ({ lines }: { lines: number }) => (<SkeletonBar height={12} width={200} /></Flexbox></Flexbox>- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /><Checklist lines={lines} /></Flexbox>);const Card = ({ size }: { size: 'large' | 'small' }) =>size === 'large' ? (- <Flexbox className={styles.card} gap={16} height={720} padding={16}>+ <Flexbox className={stylex.props(styles.card).className} gap={16} height={720} padding={16}><SkeletonBar height={36} radius={cssVar.borderRadiusLG} width={36} /><Flexbox gap={10}><SkeletonBar height={18} width={72} />@@ -361,7 +364,13 @@ const Card = ({ size }: { size: 'large' | 'small' }) =><Checklist lines={12} /></Flexbox>) : (- <Flexbox className={styles.card} gap={8} height={65} justify={'center'} paddingInline={12}>+ <Flexbox+ className={stylex.props(styles.card).className}+ gap={8}+ height={65}+ justify={'center'}+ paddingInline={12}+ ><SkeletonBar height={18} width={48} /><SkeletonBar height={12} width={64} /></Flexbox>@@ -378,7 +387,7 @@ const CardsFooter = () => ())}</Flexbox><SkeletonBar height={56} radius={cssVar.borderRadiusLG} />- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /><Flexbox horizontal align={'center'} justify={'space-between'}><SkeletonBar height={28} width={120} /><SkeletonBar height={38} width={128} />@@ -398,8 +407,10 @@ const CardGrid = ({size: 'large' | 'small';}) => (<div- className={styles.grid}- style={{ gap, gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}+ {...sx([styles.grid], undefined, {+ gap,+ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,+ })}>{Array.from({ length: cards }).map((_, index) => (<Card key={index} size={size} />@@ -411,7 +422,13 @@ const Section = ({ section }: { section: SettingsSectionSkeleton }) => {switch (section.variant) {case 'banner': {return (- <Flexbox horizontal align={'center'} className={styles.banner} gap={16} padding={18}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.banner).className}+ gap={16}+ padding={18}+ ><SkeletonBar height={48} radius={'50%'} width={48} /><Flexbox gap={10}><SkeletonBar height={18} width={240} />@@ -503,7 +520,7 @@ const PageTitle = () => (<Flexbox height={38} justify={'center'}><SkeletonBar height={28} width={96} /></Flexbox>- <div className={styles.divider} />+ <div {...stylex.props(styles.divider)} /></Flexbox>);diff --git a/src/components/Skeleton/SkeletonSwitch.tsx b/src/components/Skeleton/SkeletonSwitch.tsxindex af6f0d01282..5ccc35af6d2 100644--- a/src/components/Skeleton/SkeletonSwitch.tsx+++ b/src/components/Skeleton/SkeletonSwitch.tsx@@ -1,12 +1,6 @@-import { css, cx, Skeleton } from '@lobehub/ui';--const switchLoading = cx(css`- width: 44px !important;- min-width: 44px !important;- height: 22px !important;- border-radius: 12px !important;-`);+import { Skeleton } from '@lobehub/ui';+// Inline size: Skeleton sets its own height/width inline, which only an inline value can override.export const SkeletonSwitch = () => {- return <Skeleton className={switchLoading} height={36} />;+ return <Skeleton height={22} radius={12} style={{ minWidth: 44 }} width={44} />;};diff --git a/src/components/Skeleton/Surface.tsx b/src/components/Skeleton/Surface.tsxindex 2a5e0ca98aa..2658f435d8b 100644--- a/src/components/Skeleton/Surface.tsx+++ b/src/components/Skeleton/Surface.tsx@@ -1,7 +1,9 @@'use client';-import { createStaticStyles, cssVar, Flexbox, Grid } from '@lobehub/ui';+import { Flexbox, Grid } from '@lobehub/ui';import { Form } from '@lobehub/ui/form';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import type { ComponentType } from 'react';import type { RouteSkeletonProps } from '@/spa/router/routeMeta';@@ -15,26 +17,28 @@ interface SurfaceSkeletonProps {variant?: SurfaceSkeletonVariant;}-const styles = createStaticStyles(({ css }) => ({- card: css`- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorFillQuaternary};- `,- divider: css`- width: 100%;- height: 1px;- background: ${cssVar.colorBorderSecondary};- `,- editor: css`- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorBgContainer};- `,- row: css`- min-height: 64px;- padding-block: 16px;- `,-}));+const styles = stylex.create({+ card: {+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ divider: {+ width: '100%',+ height: '1px',+ backgroundColor: cssVar.colorBorderSecondary,+ backgroundImage: 'none',+ },+ editor: {+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ row: { minHeight: '64px', paddingBlock: '16px' },+});const HeaderSkeleton = () => (<Flexbox@@ -53,7 +57,7 @@ const HeaderSkeleton = () => (const ListSkeleton = () => (<Flexbox gap={12} padding={16}>{Array.from({ length: 5 }).map((_, index) => (- <Flexbox className={styles.card} gap={10} key={index} padding={16}>+ <Flexbox className={stylex.props(styles.card).className} gap={10} key={index} padding={16}><Flexbox horizontal align={'center'} gap={8}><SkeletonBar height={24} radius={'50%'} width={24} /><SkeletonBar height={14} width={96 + (index % 3) * 24} />@@ -76,11 +80,11 @@ const FormSkeleton = () => (<Flexbox>{Array.from({ length: 3 }).map((_, index) => (<Flexbox key={index}>- {index > 0 && <div className={styles.divider} />}+ {index > 0 && <div {...stylex.props(styles.divider)} />}<Flexboxhorizontalalign={'center'}- className={styles.row}+ className={stylex.props(styles.row).className}gap={24}justify={'space-between'}>@@ -138,7 +142,7 @@ const DetailSkeleton = () => (const EditorSkeleton = () => (<Flexbox align={'center'} flex={1} padding={'32px 24px'}><Flexbox- className={styles.editor}+ className={stylex.props(styles.editor).className}gap={20}padding={'32px 40px 96px'}width={'min(760px, 100%)'}diff --git a/src/components/Skeleton/Topics.tsx b/src/components/Skeleton/Topics.tsxindex 8a0d0707c36..2ddead40d8d 100644--- a/src/components/Skeleton/Topics.tsx+++ b/src/components/Skeleton/Topics.tsx@@ -1,47 +1,51 @@'use client';-import { createStaticStyles, cssVar, Flexbox, responsive } from '@lobehub/ui';+import { Flexbox } 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 NavHeader from '@/features/NavHeader';import type { RouteSkeletonProps } from '@/spa/router/routeMeta';import SkeletonBar from './Bar';-const styles = createStaticStyles(({ css }) => ({- card: css`- min-height: 140px;- padding: 14px;- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorFillQuaternary};- `,- footer: css`- margin-block-start: auto;- padding-block-start: 10px;- border-block-start: 1px solid ${cssVar.colorSplit};- `,- grid: css`- display: grid;- grid-template-columns: repeat(auto-fill, minmax(min(280px, 100%), 1fr));- gap: 12px;-- width: 100%;- min-width: 0;-- ${responsive.md} {- grid-template-columns: repeat(auto-fill, minmax(min(240px, 100%), 1fr));- }- `,-}));+const styles = stylex.create({+ card: {+ minHeight: '140px',+ padding: '14px',+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ footer: {+ marginBlockStart: 'auto',+ paddingBlockStart: '10px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorSplit,+ },+ grid: {+ display: 'grid',+ gridTemplateColumns: {+ default: 'repeat(auto-fill, minmax(min(280px, 100%), 1fr))',+ [media.md]: 'repeat(auto-fill, minmax(min(240px, 100%), 1fr))',+ },+ gap: '12px',+ width: '100%',+ minWidth: '0',+ },+});const TopicCardSkeleton = ({ index }: { index: number }) => (- <Flexbox className={styles.card} gap={10}>+ <Flexbox className={stylex.props(styles.card).className} gap={10}><Flexbox horizontal align={'center'} gap={8}><SkeletonBar height={8} radius={'50%'} width={8} /><SkeletonBar height={16} width={`${46 + (index % 3) * 10}%`} /></Flexbox><SkeletonBar height={12} width={`${72 + (index % 2) * 8}%`} /><SkeletonBar height={12} width={`${48 + (index % 3) * 6}%`} />- <Flexbox horizontal align={'center'} className={styles.footer} gap={12}>+ <Flexbox horizontal align={'center'} className={stylex.props(styles.footer).className} gap={12}><SkeletonBar height={12} width={48} /><SkeletonBar height={12} width={36} /><SkeletonBar height={12} width={56} />@@ -50,7 +54,7 @@ const TopicCardSkeleton = ({ index }: { index: number }) => ();const TopicGridSkeleton = () => (- <div aria-busy className={styles.grid}>+ <div aria-busy {...stylex.props(styles.grid)}>{Array.from({ length: 6 }).map((_, index) => (<TopicCardSkeleton index={index} key={index} />))}diff --git a/src/components/SpendType/index.tsx b/src/components/SpendType/index.tsxindex f2a9eec0bcb..f87a003394a 100644--- a/src/components/SpendType/index.tsx+++ b/src/components/SpendType/index.tsx@@ -1,4 +1,6 @@-import { createStaticStyles, Icon, Tooltip } from '@lobehub/ui';+import { Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {AudioLines,CircleDotDashed,@@ -10,26 +12,14 @@ import {} from 'lucide-react';import { memo, type ReactNode } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => ({- chat: css`- color: ${cssVar.colorInfo};- `,- embedding: css`- color: ${cssVar.purple};- `,- imageGeneration: css`- color: ${cssVar.colorSuccess};- `,- speechRecognition: css`- color: ${cssVar.colorInfo};- `,- textToSpeech: css`- color: ${cssVar.cyan};- `,- videoGeneration: css`- color: ${cssVar.colorWarning};- `,-}));+const styles = stylex.create({+ chat: { color: cssVar.colorInfo },+ embedding: { color: cssVar.purple },+ imageGeneration: { color: cssVar.colorSuccess },+ speechRecognition: { color: cssVar.colorInfo },+ textToSpeech: { color: cssVar.cyan },+ videoGeneration: { color: cssVar.colorWarning },+});export type SpendTypeValue =| 'chat'@@ -73,7 +63,7 @@ const getIcon = (type: string) => {const SpendType = memo<SpendTypeProps>(({ type, children }) => (<Tooltip title={children}>- <Icon className={styles[type]} icon={getIcon(type)} size={16} />+ <Icon className={stylex.props(styles[type]).className} icon={getIcon(type)} size={16} /></Tooltip>));diff --git a/src/components/StreamingMarkdown/index.tsx b/src/components/StreamingMarkdown/index.tsxindex 25bd71c380e..1091a0838cf 100644--- a/src/components/StreamingMarkdown/index.tsx+++ b/src/components/StreamingMarkdown/index.tsx@@ -1,23 +1,16 @@'use client';-import { createStaticStyles, Markdown, ScrollArea } from '@lobehub/ui';+import { Markdown, ScrollArea } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import type { RefObject } from 'react';import { memo, useEffect } from 'react';import { useAutoScroll } from '@/hooks/useAutoScroll';-const styles = createStaticStyles(({ css }) => ({- container: css`- padding-block: 12px;- padding-inline: 16px;- border-radius: 8px;- font-size: 14px;- `,- scrollRoot: css`- border-radius: 0;- background: transparent;- `,-}));+const styles = stylex.create({+ container: { paddingBlock: '12px', paddingInline: '16px', borderRadius: '8px', fontSize: '14px' },+ scrollRoot: { borderRadius: '0', backgroundColor: 'transparent', backgroundImage: 'none' },+});interface StreamingMarkdownProps {children?: string;@@ -42,9 +35,9 @@ const StreamingMarkdown = memo<StreamingMarkdownProps>(({ children, maxHeight =<ScrollAreadisableContentFitscrollFade- className={styles.scrollRoot}+ className={stylex.props(styles.scrollRoot).className}viewportProps={{- className: styles.container,+ className: stylex.props(styles.container).className,ref: ref as RefObject<HTMLDivElement>,style: { maxHeight },onScroll: handleScroll,diff --git a/src/components/TablePagination/index.tsx b/src/components/TablePagination/index.tsxindex 81d45c44c2b..1632e700211 100644--- a/src/components/TablePagination/index.tsx+++ b/src/components/TablePagination/index.tsx@@ -1,10 +1,13 @@'use client';-import { Button, createStaticStyles, cx, Flexbox } from '@lobehub/ui';+import { Button, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronLeft, ChevronRight } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { sx } from '@/styles/sx';import { formatIntergerNumber } from '@/utils/format';import PageSizeSelect from './PageSizeSelect';@@ -13,23 +16,25 @@ const DEFAULT_PAGE_SIZE_OPTIONS = [10, 20, 50, 100];/** Pages either side of the current one that stay visible before an ellipsis. */const SIBLINGS = 1;-const styles = createStaticStyles(({ css, cssVar }) => ({- ellipsis: css`- min-width: 24px;- color: ${cssVar.colorTextQuaternary};- text-align: center;- `,- root: css`- padding-block: 10px;- padding-inline: 12px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- `,- total: css`- font-size: 13px;- font-variant-numeric: tabular-nums;- color: ${cssVar.colorTextSecondary};- `,-}));+const styles = stylex.create({+ ellipsis: {+ minWidth: '24px',+ color: cssVar.colorTextQuaternary,+ textAlign: 'center',+ },+ root: {+ paddingBlock: '10px',+ paddingInline: '12px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+ total: {+ fontSize: '13px',+ fontVariantNumeric: 'tabular-nums',+ color: cssVar.colorTextSecondary,+ },+});type PageItem = number | 'ellipsis-end' | 'ellipsis-start';@@ -94,11 +99,11 @@ const TablePagination = memo<TablePaginationProps>(<Flexboxhorizontalalign={'center'}- className={cx(styles.root, className)}gap={12}justify={'space-between'}+ {...sx([styles.root], className)}>- <span className={styles.total}>+ <span {...stylex.props(styles.total)}>{t('table.pagination.range', {from: formatIntergerNumber(from),to: formatIntergerNumber(to),@@ -138,7 +143,7 @@ const TablePagination = memo<TablePaginationProps>({item}</Button>) : (- <span className={styles.ellipsis} key={item}>+ <span {...stylex.props(styles.ellipsis)} key={item}>…</span>),diff --git a/src/components/TailMarquee/index.tsx b/src/components/TailMarquee/index.tsxindex 968292e2628..b505cbdb06c 100644--- a/src/components/TailMarquee/index.tsx+++ b/src/components/TailMarquee/index.tsx@@ -1,4 +1,4 @@-import { createStaticStyles, cx, keyframes } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import {type CSSProperties,type PointerEvent,@@ -8,84 +8,128 @@ import {useState,} from 'react';-import { getMarqueeDuration, HOLD_RATIO, shouldRevealOnPointerDown } from './utils';--const HOLD = HOLD_RATIO * 100;--// Hold at the tail, scroll to the head, hold, scroll back.-const scrollToHead = keyframes`- 0%,- ${HOLD}% {- transform: translateX(0);- }-- ${50 - HOLD / 2}%,- ${50 + HOLD / 2}% {- transform: translateX(var(--tail-marquee-offset));- }-- ${100 - HOLD}%,- 100% {- transform: translateX(0);- }-`;--const styles = createStaticStyles(({ css }) => ({- container: css`- /* Paths read left to right in every locale; the alignment, fade and- translate below all assume LTR, so pin it even inside an RTL page. */- direction: ltr;- unicode-bidi: isolate;- overflow: hidden;- display: flex;- flex: 1;- justify-content: flex-end;-- min-width: 0;- `,- overflowing: css`- mask-image: linear-gradient(to right, transparent, #000 16px);-- /* Keyboard focus on the enclosing control (e.g. an accordion trigger)- loops; a tap on a touch screen plays one loop. */- *:focus-visible > &,- *:focus-visible > * > &,- &[data-revealing] {- mask-image: none;- }-- *:focus-visible > & > span,- *:focus-visible > * > & > span {- animation: ${scrollToHead} var(--tail-marquee-duration) ease-in-out infinite;- }-- &[data-revealing] > span {- animation: ${scrollToHead} var(--tail-marquee-duration) ease-in-out 1;- }-- /* Only real hover loops: touch browsers keep a sticky :hover after a tap,- which would otherwise turn the one-loop tap reveal into an endless one. */- @media (hover: hover) {- &:hover {- mask-image: none;- }-- &:hover > span {- animation: ${scrollToHead} var(--tail-marquee-duration) ease-in-out infinite;- }- }-- @media (prefers-reduced-motion: reduce) {- & > span {- animation: none !important;- }- }- `,- content: css`- flex: none;- white-space: nowrap;- `,-}));+import { sx } from '@/styles/sx';++import { getMarqueeDuration, shouldRevealOnPointerDown } from './utils';++const scrollToHead = stylex.keyframes({+ '0%, 20%': { transform: 'translateX(0)' },+ '40%, 60%': { transform: 'translateX(var(--tail-marquee-offset))' },+ '80%, 100%': { transform: 'translateX(0)' },+});++const styles = stylex.create({+ container: {+ // Paths read left to right in every locale; the alignment, fade and+ // translate below all assume LTR, so pin it even inside an RTL page.+ direction: 'ltr',+ unicodeBidi: 'isolate',+ overflow: 'hidden',+ display: 'flex',+ flex: '1',+ justifyContent: 'flex-end',+ minWidth: 0,+ },+ content: {+ flex: 'none',+ whiteSpace: 'nowrap',+ },+ overflowing: {+ maskImage: {+ 'default': 'linear-gradient(to right, transparent, #000 16px)',+ ':is(:focus-visible > *, :focus-visible > * > *)': 'none',+ ':is([data-revealing])': 'none',+ '@media (hover: hover)': { 'default': null, ':hover': 'none' },+ },+ },+ animated: {+ animationName: {+ 'default': null,+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': scrollToHead,+ ':is([data-revealing] > span)': scrollToHead,+ '@media (hover: hover)': {+ 'default': null,+ ':is(:hover > span)': scrollToHead,+ '@media (prefers-reduced-motion: reduce)': {+ 'default': 'none',+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': 'none',+ ':is([data-revealing] > span)': 'none',+ ':is(:hover > span)': 'none',+ },+ },+ '@media (prefers-reduced-motion: reduce)': {+ 'default': 'none',+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': 'none',+ ':is([data-revealing] > span)': 'none',+ ':is(:hover > span)': 'none',+ },+ },+ animationDuration: {+ 'default': null,+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)':+ 'var(--tail-marquee-duration)',+ ':is([data-revealing] > span)': 'var(--tail-marquee-duration)',+ '@media (hover: hover)': {+ 'default': null,+ ':is(:hover > span)': 'var(--tail-marquee-duration)',+ '@media (prefers-reduced-motion: reduce)': {+ 'default': '0s',+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': '0s',+ ':is([data-revealing] > span)': '0s',+ ':is(:hover > span)': '0s',+ },+ },+ '@media (prefers-reduced-motion: reduce)': {+ 'default': '0s',+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': '0s',+ ':is([data-revealing] > span)': '0s',+ ':is(:hover > span)': '0s',+ },+ },+ animationTimingFunction: {+ 'default': null,+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': 'ease-in-out',+ ':is([data-revealing] > span)': 'ease-in-out',+ '@media (hover: hover)': {+ 'default': null,+ ':is(:hover > span)': 'ease-in-out',+ '@media (prefers-reduced-motion: reduce)': {+ 'default': 'ease',+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': 'ease',+ ':is([data-revealing] > span)': 'ease',+ ':is(:hover > span)': 'ease',+ },+ },+ '@media (prefers-reduced-motion: reduce)': {+ 'default': 'ease',+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': 'ease',+ ':is([data-revealing] > span)': 'ease',+ ':is(:hover > span)': 'ease',+ },+ },+ animationIterationCount: {+ 'default': null,+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': 'infinite',+ ':is([data-revealing] > span)': 1,+ '@media (hover: hover)': {+ 'default': null,+ ':is(:hover > span)': 'infinite',+ '@media (prefers-reduced-motion: reduce)': {+ 'default': 1,+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': 1,+ ':is([data-revealing] > span)': 1,+ ':is(:hover > span)': 1,+ },+ },+ '@media (prefers-reduced-motion: reduce)': {+ 'default': 1,+ ':is(:focus-visible > * > span, :focus-visible > * > * > span)': 1,+ ':is([data-revealing] > span)': 1,+ ':is(:hover > span)': 1,+ },+ },+ },+});interface TailMarqueeProps {children: ReactNode;@@ -133,21 +177,18 @@ const TailMarquee = ({ children, className, style }: TailMarqueeProps) => {return (<div- className={cx(styles.container, overflow > 0 && styles.overflowing, className)}data-revealing={revealing || undefined}ref={containerRef}title={overflow > 0 ? fullText : undefined}- style={- {- ...style,- '--tail-marquee-duration': `${duration}s`,- '--tail-marquee-offset': `${overflow}px`,- } as CSSProperties- }+ {...sx([styles.container, overflow > 0 && styles.overflowing], className, {+ ...style,+ '--tail-marquee-duration': `${duration}s`,+ '--tail-marquee-offset': `${overflow}px`,+ } as CSSProperties)}onAnimationEnd={() => setRevealing(false)}onPointerDown={handlePointerDown}>- <span className={styles.content} ref={contentRef}>+ <span ref={contentRef} {...stylex.props(styles.content, overflow > 0 && styles.animated)}>{children}</span></div>diff --git a/src/components/TipGuide/index.tsx b/src/components/TipGuide/index.tsxindex 0a06e4483a2..84f1874cb65 100644--- a/src/components/TipGuide/index.tsx+++ b/src/components/TipGuide/index.tsx@@ -1,27 +1,12 @@-import { createStaticStyles, Flexbox, Popover } from '@lobehub/ui';+import { Flexbox, Popover } from '@lobehub/ui';import { ActionIcon, type PopoverPlacement } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { XIcon } from 'lucide-react';import { type CSSProperties, type FC, type ReactNode } from 'react';-const styles = createStaticStyles(({ css }) => {- return {- close: css`- color: white;- `,- container: css`- position: relative;- `,- footer: css`- display: flex;- justify-content: end;- width: 100%;- `,- tip: css`- position: absolute;- inset-inline-start: 50%;- transform: translate(-50%);- `,- };+const styles = stylex.create({+ close: { color: 'white' },+ container: { position: 'relative' },});export interface TipGuideProps {@@ -86,7 +71,7 @@ const TipGuide: FC<TipGuideProps> = ({if (!open) return children;return (- <div className={styles.container}>+ <div {...stylex.props(styles.container)}><divstyle={{marginTop: offsetY,@@ -102,7 +87,7 @@ const TipGuide: FC<TipGuideProps> = ({<Flexbox horizontal gap={24} style={{ userSelect: 'none' }}><div>{title}</div><ActionIcon- className={styles.close}+ className={stylex.props(styles.close).className}icon={XIcon}size={'small'}onClick={() => {diff --git a/src/components/UnreadDot/index.tsx b/src/components/UnreadDot/index.tsxindex 4406e94f95a..ff74db9199f 100644--- a/src/components/UnreadDot/index.tsx+++ b/src/components/UnreadDot/index.tsx@@ -1,54 +1,49 @@-import { createStaticStyles, keyframes } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';-const rippleAnim = keyframes`- 0% {- transform: scale(1);- opacity: 0.7;- }- 100% {- transform: scale(3);- opacity: 0;- }-`;+const rippleAnim = stylex.keyframes({+ '0%': { opacity: 0.7, transform: 'scale(1)' },+ '100%': { opacity: 0, transform: 'scale(3)' },+});-const styles = createStaticStyles(({ css, cssVar }) => ({- dot: css`- position: relative;- z-index: 1;-- width: 6px;- height: 6px;- border-radius: 50%;-- background: ${cssVar.colorInfo};- `,- ripple: css`- position: absolute;- inset: 0;-- width: 6px;- height: 6px;- margin: auto;- border: 1px solid ${cssVar.colorInfo};- border-radius: 50%;-- background: transparent;-- animation: ${rippleAnim} 1.8s ease-out infinite;- `,- wrapper: css`- position: relative;-- display: flex;- flex: none;- align-items: center;- justify-content: center;-- width: 14px;- height: 14px;- `,-}));+const styles = stylex.create({+ dot: {+ position: 'relative',+ zIndex: 1,+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: cssVar.colorInfo,+ backgroundImage: 'none',+ },+ ripple: {+ position: 'absolute',+ inset: 0,+ width: '6px',+ height: '6px',+ margin: 'auto',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorInfo,+ borderRadius: '50%',+ backgroundColor: 'transparent',+ backgroundImage: 'none',+ animationName: rippleAnim,+ animationDuration: '1.8s',+ animationTimingFunction: 'ease-out',+ animationIterationCount: 'infinite',+ },+ wrapper: {+ position: 'relative',+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ width: '14px',+ height: '14px',+ },+});interface UnreadDotProps {/** Announces the mark to screen readers — pass it wherever the dot is the only carrier of "unread". */@@ -64,12 +59,12 @@ interface UnreadDotProps {const UnreadDot = memo<UnreadDotProps>(({ label }) => (<spanaria-label={label}- className={styles.wrapper}data-testid="topic-unread-dot"role={label ? 'status' : undefined}+ {...stylex.props(styles.wrapper)}>- <span className={styles.ripple} />- <span className={styles.dot} />+ <span {...stylex.props(styles.ripple)} />+ <span {...stylex.props(styles.dot)} /></span>));diff --git a/src/components/mdx/CollapsibleSection.tsx b/src/components/mdx/CollapsibleSection.tsxindex b93b23ca2e2..bacdc7632c5 100644--- a/src/components/mdx/CollapsibleSection.tsx+++ b/src/components/mdx/CollapsibleSection.tsx@@ -1,20 +1,15 @@'use client';-import { Accordion, createStaticStyles } from '@lobehub/ui';+import { Accordion } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { kebabCase } from 'es-toolkit';import { type FC, type ReactNode } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => ({- collapse: css`- margin-block: 1em;- `,- label: css`- font-size: 1.25em;- font-weight: 600;- line-height: 1.4;- color: ${cssVar.colorText};- `,-}));+const styles = stylex.create({+ collapse: { marginBlock: '1em' },+ label: { fontSize: '1.25em', fontWeight: 600, lineHeight: 1.4, color: cssVar.colorText },+});interface CollapsibleSectionProps {children?: ReactNode;@@ -31,7 +26,7 @@ const CollapsibleSection: FC<CollapsibleSectionProps> = ({ children, title = ''return (<Accordion- className={styles.collapse}+ className={stylex.props(styles.collapse).className}defaultValue={[]}gap={8}indicatorPlacement={'end'}@@ -41,7 +36,7 @@ const CollapsibleSection: FC<CollapsibleSectionProps> = ({ children, title = ''{children,key: id || 'section',- title: <span className={styles.label}>{title}</span>,+ title: <span {...stylex.props(styles.label)}>{title}</span>,},]}/>diff --git a/src/components/server/MobileNavLayout.tsx b/src/components/server/MobileNavLayout.tsxindex bab44d3cb9a..0e2546acdc2 100644--- a/src/components/server/MobileNavLayout.tsx+++ b/src/components/server/MobileNavLayout.tsx@@ -1,7 +1,21 @@import { type FlexboxProps } from '@lobehub/ui';import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { type ReactNode } from 'react';+import { sx } from '@/styles/sx';++const DEFAULT_SCROLL_ID = 'lobe-mobile-scroll-container';++const styles = stylex.create({+ // Full-height mobile pages scroll their content pane without a visible bar.+ // This used to be AppTheme's descendant `#lobe-mobile-scroll-container` rule.+ hiddenScrollbar: {+ '::-webkit-scrollbar': { height: 0, width: 0 },+ 'scrollbarWidth': 'none',+ },+});+interface MobileContentLayoutProps extends FlexboxProps {header?: ReactNode;withNav?: boolean;@@ -12,11 +26,15 @@ const MobileContentLayout = ({withNav,style,header,- id = 'lobe-mobile-scroll-container',+ className,+ id = DEFAULT_SCROLL_ID,...rest}: MobileContentLayoutProps) => {const content = (+ // Only the shared scroll container hides its bar; a caller that renames the+ // element opts out, exactly as the id-scoped CSS rule did.<Flexbox+ className={sx(id === DEFAULT_SCROLL_ID && styles.hiddenScrollbar, className).className}height="100%"id={id}width="100%"@@ -40,8 +58,9 @@ const MobileContentLayout = ({<Flexbox height={'100%'} style={{ overflow: 'hidden', position: 'relative' }} width={'100%'}>{header}<Flexbox+ className={sx(styles.hiddenScrollbar, className).className}height="100%"- id={'lobe-mobile-scroll-container'}+ id={DEFAULT_SCROLL_ID}width="100%"style={{overflowX: 'hidden',diff --git a/src/features/ChatInput/ControlBar/ApprovalMode.tsx b/src/features/ChatInput/ControlBar/ApprovalMode.tsxindex 94372cc8d47..a95fe4dedcf 100644--- a/src/features/ChatInput/ControlBar/ApprovalMode.tsx+++ b/src/features/ChatInput/ControlBar/ApprovalMode.tsx@@ -1,13 +1,7 @@import { type DropdownItem } from '@lobehub/ui';-import {- Button,- Center,- createStaticStyles,- DropdownMenu,- Flexbox,- Icon,- Tooltip,-} from '@lobehub/ui';+import { Button, Center, DropdownMenu, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { Check, ChevronDown, Hand, ListChecks, Zap } from 'lucide-react';import { type LucideIcon } from 'lucide-react';import { memo, useCallback, useMemo, useState } from 'react';@@ -19,46 +13,31 @@ import { useUserStore } from '@/store/user';import { toolInterventionSelectors } from '@/store/user/selectors';import { type ApprovalMode } from '@/store/user/slices/settings/selectors';-const styles = createStaticStyles(({ css, cssVar }) => ({- desc: css`- font-size: 12px;- line-height: 1.4;- color: ${cssVar.colorTextDescription};- `,- icon: css`- border: 1px solid ${cssVar.colorFillTertiary};- border-radius: ${cssVar.borderRadius};- background: ${cssVar.colorBgElevated};- `,- modeButton: css`- font-size: ${cssVar.fontSizeSM};- color: ${cssVar.colorTextSecondary};- `,- modeButtonDisabled: css`- cursor: not-allowed;- opacity: 0.5;- `,- title: css`- font-size: 14px;- font-weight: 500;- line-height: 1.4;- color: ${cssVar.colorText};- `,- trigger: css`- overflow: hidden;- border-radius: ${cssVar.borderRadius};- `,-}));+const styles = stylex.create({+ desc: { fontSize: '12px', lineHeight: 1.4, color: cssVar.colorTextDescription },+ icon: {+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorFillTertiary,+ borderRadius: cssVar.borderRadius,+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+ modeButton: { fontSize: cssVar.fontSizeSM, color: cssVar.colorTextSecondary },+ modeButtonDisabled: { cursor: 'not-allowed', opacity: 0.5 },+ title: { fontSize: '14px', fontWeight: 500, lineHeight: 1.4, color: cssVar.colorText },+ trigger: { overflow: 'hidden', borderRadius: cssVar.borderRadius },+});const ModeItemLabel = memo<{ desc: string; icon: LucideIcon; title: string }>(({ desc, icon, title }) => (<Flexbox horizontal align={'flex-start'} gap={12}>- <Center className={styles.icon} flex={'none'} height={32} width={32}>+ <Center className={stylex.props(styles.icon).className} flex={'none'} height={32} width={32}><Icon icon={icon} /></Center><Flexbox flex={1} style={{ minWidth: 120 }}>- <div className={styles.title}>{title}</div>- <div className={styles.desc}>{desc}</div>+ <div {...stylex.props(styles.title)}>{title}</div>+ <div {...stylex.props(styles.desc)}>{desc}</div></Flexbox></Flexbox>),@@ -146,7 +125,7 @@ const ModeSelector = memo(() => {const button = (<Button- className={styles.modeButton}+ className={stylex.props(styles.modeButton).className}disabled={disabled}icon={ChevronDown}iconPosition="end"@@ -166,7 +145,7 @@ const ModeSelector = memo(() => {: t(isGroupContext ? 'input.viewOnlyGroup' : 'input.viewOnlyAgent')}>- <div className={styles.modeButtonDisabled}>{button}</div>+ <div {...stylex.props(styles.modeButtonDisabled)}>{button}</div></Tooltip>);@@ -177,7 +156,7 @@ const ModeSelector = memo(() => {placement="bottomRight"onOpenChange={handleOpenChange}>- <div className={styles.trigger}>+ <div {...stylex.props(styles.trigger)}>{dropdownOpen ? (button) : (diff --git a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx b/src/features/ChatInput/ControlBar/BranchSwitcher.tsxindex c129f4c33d2..bf27db1521d 100644--- a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx@@ -2,9 +2,6 @@ import type { DeviceGitWorktreeListItem } from '@lobechat/types';import {confirmModal,copyToClipboard,- createStaticStyles,- cssVar,- cx,DropdownMenuFooter,DropdownMenuHeader,DropdownMenuItem,@@ -19,6 +16,8 @@ import {toast,Tooltip,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {CheckIcon,CopyIcon,@@ -47,176 +46,128 @@ import { gitService } from '@/services/git';import { useFetchGitWorkingTreeStatus } from '@/store/device';import { openCreateBranchModal } from './CreateBranchModal';-import { gitMenuTriggerStyles } from './gitMenuTriggerStyles';+import gitMenuTriggerStyles from './gitMenuTrigger.module.css';import { openRenameBranchModal } from './RenameBranchModal';import { useBranchList } from './useBranchList';import { useSwitchWorktree } from './useSwitchWorktree';import { findWorktreeForBranch, getPathName } from './worktreeHelpers';-const styles = createStaticStyles(({ css }) => ({- branchLabel: css`- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- `,- footer: css`- border-block-start: 1px solid ${cssVar.colorSplit};- `,- header: css`- padding: 0;- `,+const spin = stylex.keyframes({ to: { transform: 'rotate(360deg)' } });++const styles = stylex.create({+ branchLabel: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },// Fill the list slot like `list` does, so the footer stays pinned to the// bottom of the fixed-height popup while loading / empty.- emptyState: css`- display: flex;- flex: 1;- align-items: center;- justify-content: center;-- min-height: 0;- padding-block: 12px;-- font-size: 12px;- color: ${cssVar.colorTextTertiary};- text-align: center;- `,- item: css`- display: flex;- gap: 8px;- align-items: center;-- height: auto;- min-height: 32px;- padding-block: 4px;- padding-inline: 8px;- border-radius: 4px;-- font-size: 14px;- line-height: 20px;- color: ${cssVar.colorText};-- /* Swap the checkmark for the row actions while hovering the row. */- &:hover .branch-row-actions {- display: flex;- }-- &:hover .branch-row-check {- display: none;- }- `,- itemCheck: css`- flex: none;- color: ${cssVar.colorPrimary};- `,- rowAction: css`- cursor: pointer;-- display: flex;- align-items: center;- justify-content: center;-- width: 20px;- height: 20px;- border-radius: 4px;-- color: ${cssVar.colorTextTertiary};-- transition: all 0.2s;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillSecondary};- }- `,- rowActionDanger: css`- &:hover {- color: ${cssVar.colorError};- background: ${cssVar.colorErrorBg};- }- `,- rowActions: css`- display: none;- flex: none;- gap: 2px;- align-items: center;- `,- itemIcon: css`- flex: none;- color: ${cssVar.colorTextSecondary};- `,- itemMain: css`- overflow: hidden;- flex: 1;- min-width: 0;- `,- itemMeta: css`- font-size: 12px;- line-height: 16px;- color: ${cssVar.colorTextTertiary};- `,- list: css`- flex: 1;- min-height: 0;- `,+ emptyState: {+ display: 'flex',+ flex: '1',+ alignItems: 'center',+ justifyContent: 'center',+ minHeight: '0',+ paddingBlock: '12px',+ fontSize: '12px',+ color: cssVar.colorTextTertiary,+ textAlign: 'center',+ },+ footer: {+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorSplit,+ },+ header: { padding: '0' },+ item: {+ display: 'flex',+ gap: '8px',+ alignItems: 'center',+ height: 'auto',+ minHeight: '32px',+ paddingBlock: '4px',+ paddingInline: '8px',+ borderRadius: '4px',+ fontSize: '14px',+ lineHeight: '20px',+ color: cssVar.colorText,+ },+ // Swap the checkmark for the row actions while hovering the row (the+ // `defaultMarker` on `item`).+ itemCheck: {+ display: { default: null, [stylex.when.ancestor(':hover')]: 'none' },+ flex: 'none',+ color: cssVar.colorPrimary,+ },+ itemIcon: { flex: 'none', color: cssVar.colorTextSecondary },+ itemMain: { overflow: 'hidden', flex: '1', minWidth: '0' },+ itemMeta: { fontSize: '12px', lineHeight: '16px', color: cssVar.colorTextTertiary },+ list: { flex: '1', minHeight: '0' },// The base popup only becomes a flex column once the virtual list mounts;// force it so the loading / empty placeholder can fill the list slot too.- popup: css`- overflow: hidden;- display: flex;- flex-direction: column;-- width: 300px;- height: 360px;- `,- searchBar: css`- padding-block: 4px;- padding-inline: 12px;- border-block-end: 1px solid ${cssVar.colorSplit};- `,- refreshButton: css`- cursor: pointer;-- display: flex;- align-items: center;- justify-content: center;-- width: 20px;- height: 20px;- border-radius: 4px;-- color: ${cssVar.colorTextTertiary};-- transition: all 0.2s;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,- section: css`- flex: 1;- font-size: 11px;- font-weight: 500;- color: ${cssVar.colorTextTertiary};- `,- sectionRow: css`- display: flex;- gap: 4px;- align-items: center;-- padding-block: 4px 2px;- padding-inline: 8px;- `,- spinning: css`- animation: branch-switcher-spin 0.8s linear infinite;-- @keyframes branch-switcher-spin {- to {- transform: rotate(360deg);- }- }- `,-}));+ popup: {+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column',+ width: '300px',+ height: '360px',+ },+ refreshButton: {+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '20px',+ borderRadius: '4px',+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },+ transition: 'all 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ rowAction: {+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '20px',+ borderRadius: '4px',+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },+ transition: 'all 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillSecondary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ rowActionDanger: {+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorError },+ backgroundColor: { 'default': null, ':hover': cssVar.colorErrorBg },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ rowActions: {+ display: { default: 'none', [stylex.when.ancestor(':hover')]: 'flex' },+ flex: 'none',+ gap: '2px',+ alignItems: 'center',+ },+ searchBar: {+ paddingBlock: '4px',+ paddingInline: '12px',+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorSplit,+ },+ section: { flex: '1', fontSize: '11px', fontWeight: 500, color: cssVar.colorTextTertiary },+ sectionRow: {+ display: 'flex',+ gap: '4px',+ alignItems: 'center',+ paddingBlockStart: '4px',+ paddingBlockEnd: '2px',+ paddingInline: '8px',+ },+ spinning: {+ animationName: spin,+ animationDuration: '0.8s',+ animationTimingFunction: 'linear',+ animationIterationCount: 'infinite',+ },+});interface BranchSwitcherProps {agentId: string;@@ -489,9 +440,9 @@ const BranchSwitcher = memo<BranchSwitcherProps>(</DropdownMenuTrigger><DropdownMenuPortal><DropdownMenuPositioner placement={placement} sideOffset={8}>- <DropdownMenuPopup className={styles.popup}>- <DropdownMenuHeader className={styles.header}>- <div className={styles.searchBar}>+ <DropdownMenuPopup className={stylex.props(styles.popup).className}>+ <DropdownMenuHeader className={stylex.props(styles.header).className}>+ <div {...stylex.props(styles.searchBar)}><InputautoFocusplaceholder={t('workingDirectory.branchSearchPlaceholder')}@@ -504,11 +455,17 @@ const BranchSwitcher = memo<BranchSwitcherProps>(onKeyDown={(e) => e.stopPropagation()}/></div>- <div className={styles.sectionRow}>- <div className={styles.section}>{t('workingDirectory.branchesHeading')}</div>- <div className={styles.refreshButton} role="button" onClick={handleRefresh}>+ <div {...stylex.props(styles.sectionRow)}>+ <div {...stylex.props(styles.section)}>+ {t('workingDirectory.branchesHeading')}+ </div>+ <div+ {...stylex.props(styles.refreshButton)}+ role="button"+ onClick={handleRefresh}+ ><Icon- className={cx(isRefreshing && styles.spinning)}+ className={isRefreshing ? stylex.props(styles.spinning).className : undefined}icon={RefreshCwIcon}size={12}/>@@ -517,12 +474,16 @@ const BranchSwitcher = memo<BranchSwitcherProps>(</DropdownMenuHeader>{isLoading && branches.length === 0 ? (- <div className={styles.emptyState}>{t('workingDirectory.branchesLoading')}</div>+ <div {...stylex.props(styles.emptyState)}>+ {t('workingDirectory.branchesLoading')}+ </div>) : loadFailed ? (// A failed refresh keeps the list it already has on screen.- <div className={styles.emptyState}>{t('workingDirectory.branchesLoadFailed')}</div>+ <div {...stylex.props(styles.emptyState)}>+ {t('workingDirectory.branchesLoadFailed')}+ </div>) : filtered.length === 0 ? (- <div className={styles.emptyState}>+ <div {...stylex.props(styles.emptyState)}>{search.trim()? t('workingDirectory.branchesNoMatch'): t('workingDirectory.branchesEmpty')}@@ -530,7 +491,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>() : (<DropdownMenuScrollViewportvirtual- className={styles.list}+ className={stylex.props(styles.list).className}getItemLabel={(_, index) => filtered[index]?.name}// The virtual viewport sizes itself on mount: a background// refresh that adds branches while the dropdown is open@@ -547,28 +508,30 @@ const BranchSwitcher = memo<BranchSwitcherProps>(const owner = findWorktreeForBranch(worktrees, branch.name);return (<DropdownMenuItem- className={styles.item}+ className={stylex.props(stylex.defaultMarker(), styles.item).className}closeOnClick={false}key={branch.name}ref={isCurrent ? currentRowRef : undefined}onClick={() => handleCheckout(branch.name)}><Icon- className={cx(styles.itemIcon, isBusy && styles.spinning)}icon={isBusy ? LoaderIcon : owner ? GitForkIcon : GitBranchIcon}size={14}+ className={+ stylex.props(styles.itemIcon, isBusy && styles.spinning).className+ }/>- <div className={styles.itemMain}>- <div className={styles.branchLabel}>{branch.name}</div>+ <div {...stylex.props(styles.itemMain)}>+ <div {...stylex.props(styles.branchLabel)}>{branch.name}</div>{isCurrent && workingStatus && !workingStatus.clean && (- <div className={styles.itemMeta}>+ <div {...stylex.props(styles.itemMeta)}>{t('workingDirectory.uncommittedChanges', {count: workingStatus.total,})}</div>)}{owner && (- <div className={styles.itemMeta}>+ <div {...stylex.props(styles.itemMeta)}>{t('workingDirectory.branchInWorktree', {name: getPathName(owner.path),})}@@ -577,16 +540,16 @@ const BranchSwitcher = memo<BranchSwitcherProps>(</div>{isCurrent && (<Icon- className={cx('branch-row-check', styles.itemCheck)}+ className={stylex.props(styles.itemCheck).className}icon={CheckIcon}size={14}/>)}- <div className={cx('branch-row-actions', styles.rowActions)}>+ <div {...stylex.props(styles.rowActions)}><Tooltip title={tCommon('copy')}><divaria-label={tCommon('copy')}- className={styles.rowAction}+ {...stylex.props(styles.rowAction)}role="button"onClick={(e) => void handleCopy(e, branch.name)}>@@ -595,7 +558,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(</Tooltip><Tooltip title={t('workingDirectory.renameBranchAction')}><div- className={styles.rowAction}+ {...stylex.props(styles.rowAction)}role="button"onClick={(e) => handleRename(e, branch.name)}>@@ -605,7 +568,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>({!isCurrent && !owner && (<Tooltip title={t('workingDirectory.deleteBranchAction')}><div- className={cx(styles.rowAction, styles.rowActionDanger)}+ {...stylex.props(styles.rowAction, styles.rowActionDanger)}role="button"onClick={(e) => handleDelete(e, branch.name)}>@@ -620,10 +583,19 @@ const BranchSwitcher = memo<BranchSwitcherProps>(</DropdownMenuScrollViewport>)}- <DropdownMenuFooter className={styles.footer}>- <DropdownMenuItem className={styles.item} onClick={openCreateBranch}>- <Icon className={styles.itemIcon} icon={GitBranchPlusIcon} size={14} />- <div className={styles.itemMain}>{t('workingDirectory.createBranchAction')}</div>+ <DropdownMenuFooter className={stylex.props(styles.footer).className}>+ <DropdownMenuItem+ className={stylex.props(styles.item).className}+ onClick={openCreateBranch}+ >+ <Icon+ className={stylex.props(styles.itemIcon).className}+ icon={GitBranchPlusIcon}+ size={14}+ />+ <div {...stylex.props(styles.itemMain)}>+ {t('workingDirectory.createBranchAction')}+ </div></DropdownMenuItem></DropdownMenuFooter></DropdownMenuPopup>diff --git a/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx b/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsxindex e7e6a77bd0c..9d7cad69b37 100644--- a/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx@@ -1,7 +1,9 @@'use client';import { Github } from '@lobehub/icons';-import { createStaticStyles, cssVar, cx, Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { CheckIcon, ChevronDownIcon, SquircleDashed } from 'lucide-react';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -12,90 +14,72 @@ import { agentByIdSelectors } from '@/store/agent/selectors';import { useTopicRepoSelection } from './useTopicRepoSelection';-const styles = createStaticStyles(({ css }) => ({- button: css`- cursor: pointer;-- display: flex;- gap: 6px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};-- transition: background 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- buttonDisabled: css`- cursor: not-allowed;- opacity: 0.5;-- &:hover {- background: transparent;- }- `,- checkIndicator: css`- display: flex;- flex: none;- align-items: center;- justify-content: center;-- width: 20px;- height: 20px;- border: 1.5px solid ${cssVar.colorBorder};- border-radius: 4px;- `,- checkIndicatorChecked: css`- border-color: ${cssVar.colorPrimary};- color: #fff;- background: ${cssVar.colorPrimary};- `,- repoItem: css`- cursor: pointer;-- padding-block: 6px;- padding-inline: 8px;- border-radius: ${cssVar.borderRadius};-- transition: background-color 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- repoName: css`- font-size: 13px;- font-weight: 500;- color: ${cssVar.colorText};- `,- repoUrl: css`- overflow: hidden;-- font-size: 11px;- color: ${cssVar.colorTextDescription};- text-overflow: ellipsis;- white-space: nowrap;- `,- scrollContainer: css`- overflow-y: auto;- max-height: 360px;- `,- sectionTitle: css`- padding-block: 6px 2px;- padding-inline: 8px;-- font-size: 11px;- font-weight: 500;- color: ${cssVar.colorTextQuaternary};- `,-}));+const styles = stylex.create({+ button: {+ cursor: 'pointer',+ display: 'flex',+ gap: '6px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ transition: 'background 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ buttonDisabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ backgroundColor: { 'default': null, ':hover': 'transparent' },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ checkIndicator: {+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '20px',+ borderWidth: '1.5px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorder,+ borderRadius: '4px',+ },+ checkIndicatorChecked: {+ borderColor: cssVar.colorPrimary,+ color: '#fff',+ backgroundColor: cssVar.colorPrimary,+ backgroundImage: 'none',+ },+ repoItem: {+ cursor: 'pointer',+ paddingBlock: '6px',+ paddingInline: '8px',+ borderRadius: cssVar.borderRadius,+ transition: 'background-color 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ repoName: { fontSize: '13px', fontWeight: 500, color: cssVar.colorText },+ repoUrl: {+ overflow: 'hidden',+ fontSize: '11px',+ color: cssVar.colorTextDescription,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ scrollContainer: { overflowY: 'auto', maxHeight: '360px' },+ sectionTitle: {+ paddingBlockStart: '6px',+ paddingBlockEnd: '2px',+ paddingInline: '8px',+ fontSize: '11px',+ fontWeight: 500,+ color: cssVar.colorTextQuaternary,+ },+});const getRepoName = (repo: string) => repo.split('/').findLast(Boolean) || repo;@@ -141,28 +125,28 @@ const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {const content = (<Flexbox gap={4} style={{ minWidth: 280 }}>- <div className={styles.sectionTitle}>{t('heteroAgent.cloudRepo.sectionTitle')}</div>- <div className={styles.scrollContainer}>+ <div {...stylex.props(styles.sectionTitle)}>{t('heteroAgent.cloudRepo.sectionTitle')}</div>+ <div {...stylex.props(styles.scrollContainer)}>{availableRepos.map((repo) => {const isChecked = displayRepos.includes(repo);return (<Flexboxhorizontalalign="center"- className={styles.repoItem}+ className={stylex.props(styles.repoItem).className}gap={8}key={repo}onClick={() => toggleRepo(repo)}><div- className={`${styles.checkIndicator} ${isChecked ? styles.checkIndicatorChecked : ''}`}+ {...stylex.props(styles.checkIndicator, isChecked && styles.checkIndicatorChecked)}>{isChecked && <Icon icon={CheckIcon} size={12} />}</div><Github size={16} style={{ color: cssVar.colorTextTertiary, flex: 'none' }} /><Flexbox flex={1} style={{ minWidth: 0 }}>- <div className={styles.repoName}>{getRepoName(repo)}</div>- <div className={styles.repoUrl}>{repo}</div>+ <div {...stylex.props(styles.repoName)}>{getRepoName(repo)}</div>+ <div {...stylex.props(styles.repoUrl)}>{repo}</div></Flexbox></Flexbox>);@@ -172,7 +156,7 @@ const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {);const button = (- <div className={cx(styles.button, !canCreateContent && styles.buttonDisabled)}>+ <div {...stylex.props(styles.button, !canCreateContent && styles.buttonDisabled)}>{displayRepos.length > 0 ? <Github size={14} /> : <Icon icon={SquircleDashed} size={14} />}<span>{buttonLabel}</span><Icon icon={ChevronDownIcon} size={12} />diff --git a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsxindex d24435072b0..2fbc1f8942e 100644--- a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx+++ b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx@@ -1,7 +1,8 @@'use client';import type { DeviceListItem } from '@lobechat/types';-import { Button, createStaticStyles, Icon } from '@lobehub/ui';+import { Button, Icon } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { RefreshCwIcon } from 'lucide-react';import type { ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -13,14 +14,9 @@ import DeviceDetailPopover from './DeviceDetailPopover';import { handleDeviceRowKeyDown } from './deviceRowKeyDown';import OptionRow from './OptionRow';-const styles = createStaticStyles(({ css }) => ({- reconnectButton: css`- min-height: 18px;- padding-block: 0;- padding-inline: 2px;- font-size: 11px;- `,-}));+const styles = stylex.create({+ reconnectButton: { minHeight: '18px', paddingBlock: '0', paddingInline: '2px', fontSize: '11px' },+});interface DeviceOptionRowProps {active: boolean;@@ -79,7 +75,7 @@ const DeviceOptionRow = ({)}{device.online || presenceUnknown ? null : (<Button- className={styles.reconnectButton}+ className={stylex.props(styles.reconnectButton).className}icon={<Icon icon={RefreshCwIcon} size={10} />}loading={reconnecting}size={'small'}diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsxindex c2f8999c1e7..c244e6de33e 100644--- a/src/features/ChatInput/ControlBar/GitStatus.tsx+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx@@ -1,5 +1,7 @@import type { WorkingDirGitState } from '@lobechat/types';-import { createStaticStyles, cssVar, Icon, toast, Tooltip } from '@lobehub/ui';+import { Icon, toast, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ArrowDownIcon, ArrowUpIcon, GitPullRequest } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -25,84 +27,56 @@ import { gitChipStyles } from './gitChipStyles';import StaleGitSnapshot from './StaleGitSnapshot';import WorktreeSwitcher from './WorktreeSwitcher';-const styles = createStaticStyles(({ css }) => {- return {- aheadBehindStat: css`- display: inline-flex;- gap: 0;- align-items: center;-- margin-inline-start: -2px;-- font-variant-numeric: tabular-nums;- line-height: 1;- `,- aheadStat: css`- color: ${cssVar.colorInfo};- `,- behindStat: css`- color: ${cssVar.colorError};- `,- branchGroup: css`- display: flex;- flex: none;- gap: 2px;- align-items: center;- `,- branchLabel: css`- overflow: hidden;- max-width: 160px;- text-overflow: ellipsis;- white-space: nowrap;- `,- diffStat: css`- display: inline-flex;- flex-shrink: 0;- gap: 4px;- align-items: center;-- font-variant-numeric: tabular-nums;- `,- diffStatAdded: css`- color: ${cssVar.colorSuccess};- `,- diffStatDeleted: css`- color: ${cssVar.colorError};- `,- diffStatModified: css`- color: ${cssVar.colorWarning};- `,- syncTrigger: css`- cursor: pointer;-- display: inline-flex;- flex: none;- gap: 2px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- font-variant-numeric: tabular-nums;- line-height: 1;-- transition: background 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- syncTriggerDisabled: css`- cursor: progress;- opacity: 0.6;-- &:hover {- background: transparent;- }- `,- };+const styles = stylex.create({+ aheadBehindStat: {+ display: 'inline-flex',+ gap: '0',+ alignItems: 'center',+ marginInlineStart: '-2px',+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 1,+ },+ aheadStat: { color: cssVar.colorInfo },+ behindStat: { color: cssVar.colorError },+ branchGroup: { display: 'flex', flex: 'none', gap: '2px', alignItems: 'center' },+ branchLabel: {+ overflow: 'hidden',+ maxWidth: '160px',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ diffStat: {+ display: 'inline-flex',+ flexShrink: 0,+ gap: '4px',+ alignItems: 'center',+ fontVariantNumeric: 'tabular-nums',+ },+ diffStatAdded: { color: cssVar.colorSuccess },+ diffStatDeleted: { color: cssVar.colorError },+ diffStatModified: { color: cssVar.colorWarning },+ syncTrigger: {+ cursor: 'pointer',+ display: 'inline-flex',+ flex: 'none',+ gap: '2px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 1,+ transition: 'background 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ syncTriggerDisabled: {+ cursor: 'progress',+ opacity: 0.6,+ backgroundColor: { 'default': null, ':hover': 'transparent' },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },});interface GitStatusProps {@@ -373,17 +347,21 @@ const GitStatus = memo<GitStatusProps>(if (!probeSettled && fallbackGit?.branch) {return (<>- <div className={gitChipStyles.separator} />- <div aria-busy className={styles.branchGroup}>- <div className={gitChipStyles.trigger}>- <span className={styles.branchLabel}>{fallbackGit.branch}</span>+ <div {...stylex.props(gitChipStyles.separator)} />+ <div aria-busy {...stylex.props(styles.branchGroup)}>+ <div {...stylex.props(gitChipStyles.trigger)}>+ <span {...stylex.props(styles.branchLabel)}>{fallbackGit.branch}</span></div></div>{pullRequest && (<>- <div className={gitChipStyles.separator} />+ <div {...stylex.props(gitChipStyles.separator)} /><Tooltip title={pullRequest.title}>- <div className={gitChipStyles.prTrigger} role="button" onClick={handleOpenPr}>+ <div+ {...stylex.props(gitChipStyles.prTrigger)}+ role="button"+ onClick={handleOpenPr}+ ><Icon icon={GitPullRequest} size={12} /><span>#{pullRequest.number}</span></div>@@ -424,8 +402,8 @@ const GitStatus = memo<GitStatusProps>(const pushTargetExists = !!aheadBehind?.pushTargetExists;const branchTrigger = (- <div className={gitChipStyles.trigger}>- <span className={styles.branchLabel}>{branch}</span>+ <div {...stylex.props(gitChipStyles.trigger)}>+ <span {...stylex.props(styles.branchLabel)}>{branch}</span></div>);@@ -501,11 +479,15 @@ const GitStatus = memo<GitStatusProps>(<divaria-busy={pulling}aria-disabled={actionsBlocked}- className={`${styles.syncTrigger} ${styles.behindStat} ${actionsBlocked ? styles.syncTriggerDisabled : ''}`}+ {...stylex.props(+ styles.syncTrigger,+ styles.behindStat,+ actionsBlocked && styles.syncTriggerDisabled,+ )}role="button"onClick={actionsBlocked ? undefined : handlePull}>- <span className={styles.aheadBehindStat}>+ <span {...stylex.props(styles.aheadBehindStat)}>{pulling ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowDownIcon} size={10} />}{aheadBehind!.behind}</span>@@ -518,11 +500,15 @@ const GitStatus = memo<GitStatusProps>(<divaria-busy={pushing}aria-disabled={actionsBlocked}- className={`${styles.syncTrigger} ${styles.aheadStat} ${actionsBlocked ? styles.syncTriggerDisabled : ''}`}+ {...stylex.props(+ styles.syncTrigger,+ styles.aheadStat,+ actionsBlocked && styles.syncTriggerDisabled,+ )}role="button"onClick={actionsBlocked ? undefined : handlePush}>- <span className={styles.aheadBehindStat}>+ <span {...stylex.props(styles.aheadBehindStat)}>{pushing ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowUpIcon} size={10} />}{aheadBehind!.ahead}</span>@@ -533,16 +519,16 @@ const GitStatus = memo<GitStatusProps>(const diffNode = (() => {if (!hasChanges) return null;const diffButton = (- <div className={gitChipStyles.trigger} role="button" onClick={handleToggleReview}>- <span className={styles.diffStat}>+ <div {...stylex.props(gitChipStyles.trigger)} role="button" onClick={handleToggleReview}>+ <span {...stylex.props(styles.diffStat)}>{diffStats.additions > 0 && (- <span className={styles.diffStatAdded}>+{diffStats.additions}</span>+ <span {...stylex.props(styles.diffStatAdded)}>+{diffStats.additions}</span>)}{diffStats.deletions > 0 && (- <span className={styles.diffStatDeleted}>-{diffStats.deletions}</span>+ <span {...stylex.props(styles.diffStatDeleted)}>-{diffStats.deletions}</span>)}{diffStats.additions === 0 && diffStats.deletions === 0 && diffStats.files > 0 && (- <span className={styles.diffStatModified}>±{diffStats.files}</span>+ <span {...stylex.props(styles.diffStatModified)}>±{diffStats.files}</span>)}</span></div>@@ -552,10 +538,10 @@ const GitStatus = memo<GitStatusProps>(return (<>- <div className={gitChipStyles.separator} />+ <div {...stylex.props(gitChipStyles.separator)} />{/* The worktree icon and the branch name name one thing — which checkout* you're on — so they sit closer to each other than to their neighbours. */}- <div className={styles.branchGroup}>+ <div {...stylex.props(styles.branchGroup)}>{worktreeNode}{branchNode}</div>@@ -564,9 +550,9 @@ const GitStatus = memo<GitStatusProps>({diffNode}{pullRequest && (<>- <div className={gitChipStyles.separator} />+ <div {...stylex.props(gitChipStyles.separator)} /><Tooltip title={prTooltip}>- <div className={gitChipStyles.prTrigger} role="button" onClick={handleOpenPr}>+ <div {...stylex.props(gitChipStyles.prTrigger)} role="button" onClick={handleOpenPr}><Icon icon={GitPullRequest} size={12} /><span>#{pullRequest.number}</span></div>diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsxindex f0e095f9998..4251193a333 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx@@ -6,17 +6,9 @@ import type {CodexRateLimitResetCredit,} from '@lobechat/electron-client-ipc';import { uuid } from '@lobechat/utils';-import {- Accordion,- Button,- confirmModal,- createStaticStyles,- cssVar,- Flexbox,- Icon,- Text,- toast,-} from '@lobehub/ui';+import { Accordion, Button, confirmModal, Flexbox, Icon, Text, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { RotateCcwIcon } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -39,71 +31,72 @@ const isConnectionError = (quota: CodexQuotaSnapshot) =>quota.error ?? '',);-const styles = createStaticStyles(({ css }) => ({- credit: css`- min-width: 0;- padding-block: 8px;- padding-inline: 10px;-- &:not(:last-child) {- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- }- `,- creditCollapse: css`- width: 100%;- `,- creditExpiry: css`- flex: none;- text-align: end;- white-space: nowrap;- `,- creditIndex: css`- flex: 0 0 20px;- font-variant-numeric: tabular-nums;- color: ${cssVar.colorTextTertiary};- text-align: center;- `,- creditList: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadius};- background: ${cssVar.colorFillQuaternary};- `,- creditTitle: css`- overflow: hidden;- flex: 1;-- min-width: 0;-- text-overflow: ellipsis;- white-space: nowrap;- `,- feedback: css`- padding: 8px;- border: 1px solid ${cssVar.colorInfoBorder};- border-radius: ${cssVar.borderRadius};-- color: ${cssVar.colorInfoText};-- background: ${cssVar.colorInfoBg};-- &[data-kind='error'] {- border-color: ${cssVar.colorErrorBorder};- color: ${cssVar.colorErrorText};- background: ${cssVar.colorErrorBg};- }-- &[data-kind='success'] {- border-color: ${cssVar.colorSuccessBorder};- color: ${cssVar.colorSuccessText};- background: ${cssVar.colorSuccessBg};- }- `,- resetCredits: css`- padding-block-start: 8px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ credit: {+ minWidth: '0',+ paddingBlock: '8px',+ paddingInline: '10px',+ borderBlockEndWidth: { 'default': '1px', ':last-child': '0' },+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ },+ creditCollapse: { width: '100%' },+ creditExpiry: { flex: 'none', textAlign: 'end', whiteSpace: 'nowrap' },+ creditIndex: {+ flexGrow: '0',+ flexShrink: '0',+ flexBasis: '20px',+ fontVariantNumeric: 'tabular-nums',+ color: cssVar.colorTextTertiary,+ textAlign: 'center',+ },+ creditList: {+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ creditTitle: {+ overflow: 'hidden',+ flex: '1',+ minWidth: '0',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ feedback: {+ padding: '8px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorInfoBorder,+ borderRadius: cssVar.borderRadius,+ color: cssVar.colorInfoText,+ backgroundColor: cssVar.colorInfoBg,+ backgroundImage: 'none',+ },+ // [data-kind='error']+ feedbackError: {+ borderColor: cssVar.colorErrorBorder,+ color: cssVar.colorErrorText,+ backgroundColor: cssVar.colorErrorBg,+ backgroundImage: 'none',+ },+ // [data-kind='success']+ feedbackSuccess: {+ borderColor: cssVar.colorSuccessBorder,+ color: cssVar.colorSuccessText,+ backgroundColor: cssVar.colorSuccessBg,+ backgroundImage: 'none',+ },+ resetCredits: {+ paddingBlockStart: '8px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+});const createErrorSnapshot = (error: unknown): CodexQuotaSnapshot => ({error: error instanceof Error ? error.message : String(error),@@ -329,7 +322,7 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>if (!resetCredits) {return (- <Flexbox className={styles.resetCredits} gap={4}>+ <Flexbox className={stylex.props(styles.resetCredits).className} gap={4}><Flexbox horizontal align={'center'} gap={4}><Icon icon={RotateCcwIcon} size={14} /><Text style={{ fontSize: 12 }} type="secondary">@@ -352,9 +345,9 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>}));return (- <Flexbox className={styles.resetCredits}>+ <Flexbox className={stylex.props(styles.resetCredits).className}><Accordion- className={styles.creditCollapse}+ className={stylex.props(styles.creditCollapse).className}defaultValue={[]}indicatorPlacement={'end'}variant={'borderless'}@@ -363,7 +356,7 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>children: (<Flexbox gap={8}>{resetCreditItems.length > 0 && (- <Flexbox className={styles.creditList}>+ <Flexbox className={stylex.props(styles.creditList).className}>{resetCreditItems.map(({ credit, index }) => {const fallbackExpiry =index === 1 ? resetCredits.nextExpiresAt : undefined;@@ -374,18 +367,25 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =><Flexboxhorizontalalign={'center'}- className={styles.credit}+ className={stylex.props(styles.credit).className}gap={8}key={credit?.id ?? `reset-credit-${index}`}>- <Text className={styles.creditIndex} style={{ fontSize: 12 }}>+ <Text+ className={stylex.props(styles.creditIndex).className}+ style={{ fontSize: 12 }}+ >{`#${index}`}</Text>- <Text strong className={styles.creditTitle} style={{ fontSize: 12 }}>+ <Text+ strong+ className={stylex.props(styles.creditTitle).className}+ style={{ fontSize: 12 }}+ >{credit?.title || t('heteroAgent.codexQuota.resetCreditTitle')}</Text><Text- className={styles.creditExpiry}+ className={stylex.props(styles.creditExpiry).className}style={{ fontSize: 12 }}type="secondary">@@ -408,9 +408,13 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>{resetFeedback && (<divaria-live="polite"- className={styles.feedback}data-kind={resetFeedback.kind}role={resetFeedback.kind === 'error' ? 'alert' : 'status'}+ {...stylex.props(+ styles.feedback,+ resetFeedback.kind === 'error' && styles.feedbackError,+ resetFeedback.kind === 'success' && styles.feedbackSuccess,+ )}>{resetFeedback.text}</div>diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsxindex 5d2bc828149..0fe0eeba9c2 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx@@ -1,7 +1,9 @@'use client';import type { KimiCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';-import { createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { WalletIcon } from 'lucide-react';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -13,12 +15,14 @@ import QuotaAccountSwitcher from './QuotaAccountSwitcher';import type { QuotaWindowItem } from './QuotaMenu';import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';-const styles = createStaticStyles(({ css }) => ({- extraUsage: css`- padding-block-start: 8px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ extraUsage: {+ paddingBlockStart: '8px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+});const createErrorSnapshot = (error: unknown): KimiCodeQuotaSnapshot => ({error: error instanceof Error ? error.message : String(error),@@ -108,7 +112,7 @@ const KimiCodeQuotaMenu = memo<KimiCodeQuotaMenuProps>(({ deviceId, env }) => {if (!extraUsage) return null;return (- <Flexbox className={styles.extraUsage} gap={4}>+ <Flexbox className={stylex.props(styles.extraUsage).className} gap={4}><Flexbox horizontal align={'center'} justify={'space-between'}><Flexbox horizontal align={'center'} gap={4}><Icon icon={WalletIcon} size={14} />diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.module.css b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.module.cssnew file mode 100644index 00000000000..a5e5d9a6de4--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.module.css@@ -0,0 +1,13 @@+.radioGroup {+ width: 100%;+}++/* Targets the RadioGroup's own label / text DOM, which has no className hook. */+.radioGroup > label {+ width: 100%;+}++.radioGroup > label > span:last-child {+ flex: 1;+ min-width: 0;+}diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsxindex 1cb412c6e97..92f487f1775 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx@@ -2,7 +2,7 @@import { isDesktop } from '@lobechat/const';import { currentUtilization, isWeeklyAllLimit } from '@lobechat/heterogeneous-agents/quota';-import { createStaticStyles, cssVar, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';+import { DropdownMenu, Flexbox, Icon } from '@lobehub/ui';import {ActionIcon,Button,@@ -14,6 +14,8 @@ import {Text,toast,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { t as i18nT } from 'i18next';import {CheckIcon,@@ -38,55 +40,37 @@ import {import { useElectronStore } from '@/store/electron';import { electronGatewaySelectors } from '@/store/electron/selectors';-const styles = createStaticStyles(({ css }) => ({- footer: css`- margin-block-start: 4px;- padding-block-start: 10px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- `,- hint: css`- font-size: 12px;- color: ${cssVar.colorTextTertiary};- `,- interactive: css`- display: contents;- `,- radioGroup: css`- width: 100%;-- > label {- width: 100%;- }-- > label > span:last-child {- flex: 1;- min-width: 0;- }- `,- routing: css`- padding-block: 6px;- padding-inline: 10px;- border-radius: ${cssVar.borderRadius};-- font-size: 12px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillQuaternary};- `,- row: css`- padding-block: 6px;- padding-inline: 4px;- border-radius: ${cssVar.borderRadius};-- &:hover {- background: ${cssVar.colorFillQuaternary};- }-- &[data-off='true'] {- opacity: 0.5;- }- `,-}));+import radioGroupStyles from './QuotaAccountManagerModal.module.css';++const styles = stylex.create({+ footer: {+ marginBlockStart: '4px',+ paddingBlockStart: '10px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+ hint: { fontSize: '12px', color: cssVar.colorTextTertiary },+ interactive: { display: 'contents' },+ routing: {+ paddingBlock: '6px',+ paddingInline: '10px',+ borderRadius: cssVar.borderRadius,+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ row: {+ paddingBlock: '6px',+ paddingInline: '4px',+ borderRadius: cssVar.borderRadius,+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ // [data-off='true']+ rowOff: { opacity: 0.5 },+});type Account = QuotaAccount;type Binding = QuotaBinding;@@ -427,7 +411,7 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId<AccountReadingsSync accountId={a.id} key={a.id} />))}<RadioGroup- className={styles.radioGroup}+ className={radioGroupStyles.radioGroup}gap={2}horizontal={false}// Which mode is active is unknown until the bindings are on screen. The@@ -439,10 +423,15 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId{disabled: busy || !canEditBindings,label: (- <Flexbox className={styles.row} gap={4}>+ <Flexbox className={stylex.props(styles.row).className} gap={4}><Text style={{ fontSize: 13 }}>{t('heteroAgent.claudeQuota.manage.modeAuto')}</Text>{bindingsLoaded && selected === AUTO && (- <Flexbox horizontal align={'center'} className={styles.routing} gap={6}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.routing).className}+ gap={6}+ ><Icon icon={ZapIcon} size={14} />{routeAccount? t('heteroAgent.claudeQuota.manage.autoRoutingTo', {@@ -484,7 +473,7 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId<Flexboxhorizontalalign={'center'}- className={styles.row}+ className={stylex.props(styles.row, !rotate && styles.rowOff).className}data-off={!rotate}gap={8}>@@ -540,7 +529,7 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId)}</Flexbox>{!runnable && (- <span className={styles.interactive} onClick={preventRadioSelection}>+ <span {...stylex.props(styles.interactive)} onClick={preventRadioSelection}><Buttondisabled={loginPending}size={'small'}@@ -551,7 +540,7 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId</Button></span>)}- <span className={styles.interactive} onClick={preventRadioSelection}>+ <span {...stylex.props(styles.interactive)} onClick={preventRadioSelection}><Switchchecked={rotate}disabled={busy || !canEditBindings}@@ -559,7 +548,7 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceIdonChange={(v) => void setRotation(a.id, v)}/></span>- <span className={styles.interactive} onClick={preventRadioSelection}>+ <span {...stylex.props(styles.interactive)} onClick={preventRadioSelection}><DropdownMenu items={menuItems} placement={'bottomRight'}><ActionIconicon={MoreHorizontalIcon}@@ -580,11 +569,18 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId/>{accounts.length === 0 && (accountsConfirmed || !!accountsError) && (- <Text className={styles.hint}>{t('heteroAgent.claudeQuota.manage.empty')}</Text>+ <Text className={stylex.props(styles.hint).className}>+ {t('heteroAgent.claudeQuota.manage.empty')}+ </Text>)}{dirty ? (- <Flexbox horizontal className={styles.footer} gap={8} justify={'flex-end'}>+ <Flexbox+ horizontal+ className={stylex.props(styles.footer).className}+ gap={8}+ justify={'flex-end'}+ ><Button disabled={busy} onClick={() => setPending(null)}>{i18nT('cancel', { ns: 'common' })}</Button>@@ -596,11 +592,11 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}gap={8}justify={'space-between'}>- <Text className={styles.hint}>+ <Text className={stylex.props(styles.hint).className}>{loginPending? t('heteroAgent.claudeQuota.manage.loginWaiting'): t('heteroAgent.claudeQuota.manage.addHintDesktop')}@@ -621,7 +617,7 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId)}</Flexbox>) : (- <Text className={styles.hint} style={{ marginBlockStart: 4 }}>+ <Text className={stylex.props(styles.hint).className} style={{ marginBlockStart: 4 }}>{t('heteroAgent.claudeQuota.manage.addHint')}</Text>)}diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsxindex 56bedfc0cfe..6207d669170 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx@@ -1,15 +1,9 @@'use client';import type { QuotaAccountIdentity } from '@lobechat/heterogeneous-agents/quota';-import {- ActionIcon,- Button,- createStaticStyles,- cssVar,- Flexbox,- Text,- usePopoverContext,-} from '@lobehub/ui';+import { ActionIcon, Button, Flexbox, Text, usePopoverContext } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { CalendarDaysIcon } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -19,17 +13,20 @@ import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { openQuotaAccountManagerModal } from './QuotaAccountManagerModal';-const styles = createStaticStyles(({ css }) => ({- // Divider faces the quota windows: below when on top, above when it trails.- bottom: css`- padding-block-start: 8px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- `,- top: css`- padding-block-end: 8px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ bottom: {+ paddingBlockStart: '8px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+ top: {+ paddingBlockEnd: '8px',+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ },+});/*** Compact account line in the quota panel: shows the account this quota belongs@@ -62,7 +59,7 @@ const QuotaAccountSwitcher = memo<{<Flexboxhorizontalalign={'center'}- className={placement === 'top' ? styles.top : styles.bottom}+ className={stylex.props(placement === 'top' ? styles.top : styles.bottom).className}gap={8}justify={'space-between'}>diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsxindex 2437c3aa1a5..38d5764b40c 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx@@ -1,19 +1,9 @@'use client';import type { HeteroQuotaWindow } from '@lobechat/electron-client-ipc';-import {- ActionIcon,- Alert,- createStaticStyles,- cssVar,- cx,- Flexbox,- Icon,- Popover,- Skeleton,- Text,- Tooltip,-} from '@lobehub/ui';+import { ActionIcon, Alert, Flexbox, Icon, Popover, Skeleton, Text, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronDownIcon, GaugeIcon, RefreshCwIcon } from 'lucide-react';import type { ReactNode } from 'react';import { useCallback, useEffect, useRef, useState } from 'react';@@ -28,127 +18,83 @@ import {const QUOTA_STALE_MS = 60_000;const QUOTA_RETRY_COOLDOWN_MS = 60_000;-const styles = createStaticStyles(({ css }) => ({- compactItem: css`- color: inherit;-- &[data-quota-level='low'] {- color: ${cssVar.colorWarningText};- }- `,- compactItems: css`- display: inline-flex;- gap: 4px;- align-items: center;- `,- compactSeparator: css`- color: ${cssVar.colorTextQuaternary};- `,- emptyState: css`- padding-block: 10px;- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- error: css`- padding: 8px;- border: 1px solid ${cssVar.colorErrorBorder};- border-radius: ${cssVar.borderRadius};-- font-size: 12px;- color: ${cssVar.colorError};-- background: ${cssVar.colorErrorBg};- `,- header: css`- padding-block-end: 6px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,- popover: css`- width: 292px;- `,- progressFill: css`- height: 100%;- border-radius: inherit;- background: ${cssVar.colorSuccess};- `,- progressFillWarning: css`- background: ${cssVar.colorWarning};- `,- progressTrack: css`- overflow: hidden;- flex: 1;-- min-width: 24px;- height: 6px;- border-radius: 999px;-- background: ${cssVar.colorFillQuaternary};- `,- resetShort: css`- flex: none;- white-space: nowrap;- `,- trigger: css`- cursor: pointer;-- display: flex;- flex: none;- gap: 6px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border: 0;- border-radius: 4px;-- font: inherit;- font-size: 12px;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;-- appearance: none;- background: transparent;-- transition: all 0.2s;-- &:hover {- color: ${cssVar.colorTextSecondary};- background: ${cssVar.colorFillTertiary};- }-- &[data-quota-level='low'] {- color: ${cssVar.colorWarningText};-- &:hover {- color: ${cssVar.colorWarningText};- }- }- `,- triggerOpen: css`- color: ${cssVar.colorTextSecondary};- background: ${cssVar.colorFillSecondary};- `,- value: css`- flex: none;- font-variant-numeric: tabular-nums;- color: ${cssVar.colorText};- `,- valueWarning: css`- color: ${cssVar.colorWarningText};- `,- window: css`- min-width: 0;- `,- windowExhausted: css`- /* nothing to act on until reset → grey the whole row out */- opacity: 0.45;- `,- windowLabel: css`- flex: none;- width: 84px;- color: ${cssVar.colorTextSecondary};- `,-}));+const styles = stylex.create({+ compactItem: { color: 'inherit' },+ // [data-quota-level='low']+ compactItemLow: { color: cssVar.colorWarningText },+ compactItems: { display: 'inline-flex', gap: '4px', alignItems: 'center' },+ compactSeparator: { color: cssVar.colorTextQuaternary },+ emptyState: { paddingBlock: '10px', fontSize: '12px', color: cssVar.colorTextDescription },+ error: {+ padding: '8px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorErrorBorder,+ borderRadius: cssVar.borderRadius,+ fontSize: '12px',+ color: cssVar.colorError,+ backgroundColor: cssVar.colorErrorBg,+ backgroundImage: 'none',+ },+ header: {+ paddingBlockEnd: '6px',+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ },+ popover: { width: '292px' },+ progressTrack: {+ overflow: 'hidden',+ flex: '1',+ minWidth: '24px',+ height: '6px',+ borderRadius: '999px',+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ resetShort: { flex: 'none', whiteSpace: 'nowrap' },+ trigger: {+ cursor: 'pointer',+ display: 'flex',+ flex: 'none',+ gap: '6px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderWidth: '0',+ borderRadius: '4px',+ fontFamily: 'inherit',+ fontStyle: 'inherit',+ fontWeight: 'inherit',+ lineHeight: 'inherit',+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ appearance: 'none',+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },+ backgroundImage: 'none',+ transition: 'all 0.2s',+ },+ // [data-quota-level='low'] — after triggerOpen, as the attribute rule outranked it.+ triggerLow: {+ color: { 'default': cssVar.colorWarningText, ':hover': cssVar.colorWarningText },+ },+ triggerOpen: {+ color: cssVar.colorTextSecondary,+ backgroundColor: { 'default': cssVar.colorFillSecondary, ':hover': cssVar.colorFillTertiary },+ backgroundImage: 'none',+ },+ value: {+ flex: 'none',+ fontVariantNumeric: 'tabular-nums',+ color: cssVar.colorText,+ },+ valueWarning: { color: cssVar.colorWarningText },+ window: { minWidth: '0' },+ // nothing to act on until reset → grey the whole row out+ windowExhausted: { opacity: 0.45 },+ windowLabel: { flex: 'none', width: '84px', color: cssVar.colorTextSecondary },+});const clampPercent = (value: number) => Math.min(100, Math.max(0, Math.round(value)));const LOW_QUOTA_THRESHOLD = 15;@@ -614,28 +560,35 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({<Flexboxhorizontalalign={'center'}- className={cx(styles.window, exhausted && styles.windowExhausted)}+ className={stylex.props(styles.window, exhausted && styles.windowExhausted).className}gap={8}key={key}>- <Text ellipsis className={styles.windowLabel} style={{ fontSize: 12 }}>+ <Text+ ellipsis+ className={stylex.props(styles.windowLabel).className}+ style={{ fontSize: 12 }}+ >{label}</Text>- <div className={styles.progressTrack}>+ <div {...stylex.props(styles.progressTrack)}><div- className={cx(styles.progressFill, lowQuota && styles.progressFillWarning)}data-quota-level={lowQuota ? 'low' : 'normal'}style={{ width: `${leftPercent}%` }}/></div><Text- className={cx(styles.value, lowQuota && styles.valueWarning)}+ className={stylex.props(styles.value, lowQuota && styles.valueWarning).className}style={{ fontSize: 12 }}>{exhausted ? t('heteroAgent.quota.exhausted') : `${leftPercent}%`}</Text>{resetShort && (- <Text className={styles.resetShort} style={{ fontSize: 12 }} type="secondary">+ <Text+ className={stylex.props(styles.resetShort).className}+ style={{ fontSize: 12 }}+ type="secondary"+ >{resetShort}</Text>)}@@ -644,11 +597,15 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({};const content = (- <Flexbox className={styles.popover} gap={10} style={{ width: contentWidth }}>+ <Flexbox+ className={stylex.props(styles.popover).className}+ gap={10}+ style={{ width: contentWidth }}+ ><Flexboxhorizontalalign={'center'}- className={styles.header}+ className={stylex.props(styles.header).className}gap={8}justify={'space-between'}>@@ -682,14 +639,14 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({) : quota?.status === 'unavailable' ? (<>{alwaysRenderHeader && renderHeader?.(quota, { applyQuota, formatDuration, now })}- <div className={styles.emptyState}>+ <div {...stylex.props(styles.emptyState)}>{getUnavailableText?.(quota) || quota.error || t('heteroAgent.quota.unavailable')}</div></>) : quota?.status === 'error' && !hasQuotaData ? (<>{alwaysRenderHeader && renderHeader?.(quota, { applyQuota, formatDuration, now })}- <div className={styles.error}>+ <div {...stylex.props(styles.error)}>{getErrorText?.(quota) || quota.error || t('heteroAgent.quota.unavailable')}</div></>@@ -714,54 +671,64 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({{alwaysRenderHeader &"a &&renderHeader?.(quota, { applyQuota, formatDuration, now })}- <div className={styles.emptyState}>{t('heteroAgent.quota.noData')}</div>+ <div {...stylex.props(styles.emptyState)}>{t('heteroAgent.quota.noData')}</div></>)}</Flexbox>);+ const triggerQuotaLevel =+ compactItems.length === 1+ ? isLowQuota(compactItems[0].leftPercent)+ ? 'low'+ : 'normal'+ : undefined;+const trigger = (<buttonaria-expanded={open}aria-haspopup="dialog"aria-label={tooltip}- className={cx(styles.trigger, open && styles.triggerOpen)}+ data-quota-level={triggerQuotaLevel}type="button"- data-quota-level={- compactItems.length === 1- ? isLowQuota(compactItems[0].leftPercent)- ? 'low'- : 'normal'- : undefined- }+ {...stylex.props(+ styles.trigger,+ open && styles.triggerOpen,+ triggerQuotaLevel === 'low' && styles.triggerLow,+ )}><Icon icon={GaugeIcon} size={14} />{compactItems.length > 0 && (- <span className={styles.compactItems}>- {compactItems.map((item, index) => (- <span key={item.key}>- {index > 0 && (- <span aria-hidden className={styles.compactSeparator}>- {' · '}+ <span {...stylex.props(styles.compactItems)}>+ {compactItems.map((item, index) => {+ const itemQuotaLevel =+ compactItems.length > 1+ ? isLowQuota(item.leftPercent)+ ? 'low'+ : 'normal'+ : undefined;+ return (+ <span key={item.key}>+ {index > 0 && (+ <span aria-hidden {...stylex.props(styles.compactSeparator)}>+ {' · '}+ </span>+ )}+ <span+ data-quota-level={itemQuotaLevel}+ {...stylex.props(+ styles.compactItem,+ itemQuotaLevel === 'low' && styles.compactItemLow,+ )}+ >+ {item.label && `${item.label} `}+ {item.leftPercent === 0 && !item.label+ ? t('heteroAgent.quota.exhausted')+ : t('heteroAgent.quota.compactLeft', { percent: item.leftPercent })}</span>- )}- <span- className={styles.compactItem}- data-quota-level={- compactItems.length > 1- ? isLowQuota(item.leftPercent)- ? 'low'- : 'normal'- : undefined- }- >- {item.label && `${item.label} `}- {item.leftPercent === 0 && !item.label- ? t('heteroAgent.quota.exhausted')- : t('heteroAgent.quota.compactLeft', { percent: item.leftPercent })}</span>- </span>- ))}+ );+ })}</span>)}<Icon icon={ChevronDownIcon} size={12} />diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsxindex ca6e6129da6..a5ab62046b0 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx@@ -6,7 +6,9 @@ import {type HeterogeneousAgentRuntimeStatus,useWatchBroadcast,} from '@lobechat/electron-client-ipc';-import { createStaticStyles, cssVar, cx, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ActivityIcon, CircleAlertIcon, RadioTowerIcon, TimerResetIcon } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -25,97 +27,93 @@ import { agentByIdSelectors } from '@/store/agent/selectors';import { ClaudeCodeQuotaMenu, CodexQuotaMenu, KimiCodeQuotaMenu } from './QuotaMenu';-const styles = createStaticStyles(({ css }) => ({+const styles = stylex.create({// Pinned to the same 28px row as the plain ControlBar so the composer footer// keeps its rhythm regardless of which chips render. `flex: none` matters:// the bar sits in a column flex parent and would otherwise shrink to the// (compact) chips' min-content height.- bar: css`- container: runtimebar / inline-size;- flex: none;-- height: 28px;- padding-block: 0;- padding-inline: 4px;- `,- fullAccess: css`- cursor: default;-- display: flex;- flex: none;- gap: 6px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;- `,+ bar: {+ containerName: 'runtimebar',+ containerType: 'inline-size',+ flex: 'none',+ height: '28px',+ paddingBlock: '0',+ paddingInline: '4px',+ },+ fullAccess: {+ cursor: 'default',+ display: 'flex',+ flex: 'none',+ gap: '6px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ },// On a narrow bar the "full access" badge collapses to just its icon — the// hover tooltip still spells it out. Saves a chunk of horizontal space that// the truncating workspace cluster can use instead.- fullAccessLabel: css`- @container runtimebar (width < 600px) {- display: none;- }- `,- sdkRuntime: css`- cursor: default;-- display: flex;- flex: none;- gap: 6px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorInfo};- white-space: nowrap;-- background: color-mix(in srgb, ${cssVar.colorInfoBg} 55%, transparent);- `,- sdkRuntimeClosing: css`- color: ${cssVar.colorTextDescription};- background: ${cssVar.colorFillQuaternary};- `,- sdkRuntimeError: css`- color: ${cssVar.colorError};- background: color-mix(in srgb, ${cssVar.colorErrorBg} 55%, transparent);- `,- sdkRuntimeIdle: css`- color: ${cssVar.colorTextSecondary};- background: ${cssVar.colorFillQuaternary};- `,- sdkRuntimeMonitoring: css`- color: ${cssVar.colorWarning};- background: color-mix(in srgb, ${cssVar.colorWarningBg} 55%, transparent);- `,- sdkRuntimeStale: css`- color: ${cssVar.colorWarning};- background: color-mix(in srgb, ${cssVar.colorWarningBg} 55%, transparent);- `,+ fullAccessLabel: {+ display: {+ 'default': null,+ '@container runtimebar (width < 600px)': 'none',+ },+ },// Mirror RuntimeConfig: the workspace cluster shrinks then scrolls horizontally// (hidden scrollbar) instead of wrapping each chip's text on narrow screens.- leftGroup: css`- scrollbar-width: none;- overflow: auto hidden;- flex: 1;- min-width: 0;-- &::-webkit-scrollbar {- display: none;- }- `,- rightGroup: css`- flex: none;- `,-}));+ leftGroup: {+ 'scrollbarWidth': 'none',+ 'overflowX': 'auto',+ 'overflowY': 'hidden',+ 'flex': '1',+ 'minWidth': '0',+ '::-webkit-scrollbar': { display: 'none' },+ },+ rightGroup: { flex: 'none' },+ sdkRuntime: {+ cursor: 'default',+ display: 'flex',+ flex: 'none',+ gap: '6px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ color: cssVar.colorInfo,+ whiteSpace: 'nowrap',+ backgroundColor: `color-mix(in srgb, ${cssVar.colorInfoBg} 55%, transparent)`,+ backgroundImage: 'none',+ },+ sdkRuntimeClosing: {+ color: cssVar.colorTextDescription,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ sdkRuntimeError: {+ color: cssVar.colorError,+ backgroundColor: `color-mix(in srgb, ${cssVar.colorErrorBg} 55%, transparent)`,+ backgroundImage: 'none',+ },+ sdkRuntimeIdle: {+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ sdkRuntimeMonitoring: {+ color: cssVar.colorWarning,+ backgroundColor: `color-mix(in srgb, ${cssVar.colorWarningBg} 55%, transparent)`,+ backgroundImage: 'none',+ },+ sdkRuntimeStale: {+ color: cssVar.colorWarning,+ backgroundColor: `color-mix(in srgb, ${cssVar.colorWarningBg} 55%, transparent)`,+ backgroundImage: 'none',+ },+});const visibleSdkRuntimeStates = new Set<HeterogeneousAgentRuntimeState>(['starting',@@ -137,7 +135,7 @@ const HeteroControlBarSkeleton = ({ showRight }: { showRight?: boolean }) => (aria-busyhorizontalalign={'center'}- className={styles.bar}+ className={stylex.props(styles.bar).className}data-testid={'hetero-control-bar-skeleton'}gap={4}justify={'space-between'}@@ -204,7 +202,12 @@ const HeteroControlBar = memo(() => {if (!canConfigureResource) {if (!agentId || isLoading) return <HeteroControlBarSkeleton />;return (- <Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.bar).className}+ justify={'space-between'}+ ><DeviceSwitcher agentId={agentId} />{shouldShowApiCredits && <ChatInputCredits />}</Flexbox>@@ -219,15 +222,30 @@ const HeteroControlBar = memo(() => {if (!isDesktop) {if (!agentId) return null;return (- <Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>- <Flexbox horizontal align={'center'} className={styles.leftGroup} gap={4}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.bar).className}+ justify={'space-between'}+ >+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.leftGroup).className}+ gap={4}+ ><WorkspaceControls alwaysShowWorkspace agentId={agentId} /></Flexbox>{(shouldShowApiCredits ||(shouldShowClaudeQuota && quotaDeviceId) ||(shouldShowCodexQuota && quotaDeviceId) ||(shouldShowKimiCodeQuota && quotaDeviceId)) && (- <Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.rightGroup).className}+ gap={4}+ >{shouldShowApiCredits && <ChatInputCredits />}{shouldShowClaudeQuota && quotaDeviceId && (<ClaudeCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />@@ -251,9 +269,9 @@ const HeteroControlBar = memo(() => {if (!agentId || isLoading) return <HeteroControlBarSkeleton showRight />;const fullAccessBadge = (- <div className={styles.fullAccess}>+ <div {...stylex.props(styles.fullAccess)}><Icon icon={CircleAlertIcon} size={14} />- <span className={styles.fullAccessLabel}>{tChat('heteroAgent.fullAccess.label')}</span>+ <span {...stylex.props(styles.fullAccessLabel)}>{tChat('heteroAgent.fullAccess.label')}</span></div>);const shouldShowSdkRuntime =@@ -286,9 +304,9 @@ const HeteroControlBar = memo(() => {state: tChat(`heteroAgent.claudeSdkRuntime.state.${runtimeStatus.state}`),})}>- <div className={cx(styles.sdkRuntime, sdkRuntimeClassName)}>+ <div {...stylex.props(styles.sdkRuntime, sdkRuntimeClassName)}><Icon icon={sdkRuntimeIcon} size={14} />- <span className={styles.fullAccessLabel}>+ <span {...stylex.props(styles.fullAccessLabel)}>{tChat(`heteroAgent.claudeSdkRuntime.state.${runtimeStatus.state}`)}</span></div>@@ -296,11 +314,26 @@ const HeteroControlBar = memo(() => {) : null;return (- <Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>- <Flexbox horizontal align={'center'} className={styles.leftGroup} gap={4}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.bar).className}+ justify={'space-between'}+ >+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.leftGroup).className}+ gap={4}+ ><WorkspaceControls alwaysShowWorkspace agentId={agentId} /></Flexbox>- <Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.rightGroup).className}+ gap={4}+ >{shouldShowApiCredits && <ChatInputCredits />}{shouldShowCodexQuota && (<CodexQuotaMenudiff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex 5504bfdf064..f9e9b07c8bb 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -3,17 +3,9 @@import { isDesktop } from '@lobechat/const';import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';import type { DeviceExecutionTarget } from '@lobechat/types';-import {- Button,- createStaticStyles,- cssVar,- cx,- Flexbox,- Icon,- Popover,- toast,- Tooltip,-} from '@lobehub/ui';+import { Button, Flexbox, Icon, Popover, toast, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {ChevronDownIcon,ExternalLinkIcon,@@ -57,204 +49,143 @@ import OptionRow from './OptionRow';import { useSandboxNetworkToggle } from './useSandboxNetworkToggle';import { useTopicAwareTargetSelect } from './useTopicAwareTargetSelect';-const styles = createStaticStyles(({ css }) => ({- button: css`- cursor: pointer;-- display: flex;- flex: none;- gap: 6px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;-- transition: all 0.2s;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,- buttonLabel: css`- overflow: hidden;- max-width: 120px;- text-overflow: ellipsis;- white-space: nowrap;- `,- buttonReadonly: css`- cursor: default;-- &:hover {- color: ${cssVar.colorTextSecondary};- background: transparent;- }- `,- desc: css`- display: flex;- gap: 6px;- align-items: center;-- font-size: 11px;- color: ${cssVar.colorTextDescription};- `,- extraInfo: css`- cursor: help;-- display: flex;- align-items: center;-- color: ${cssVar.colorTextQuaternary};-- transition: color 0.2s;-- &:hover {- color: ${cssVar.colorTextSecondary};- }- `,- deviceList: css`- overflow-y: auto;- max-height: 240px;-- /* Room for the scrollbar so rows don't sit flush against it. */- margin-inline-end: -4px;- padding-inline-end: 4px;- `,- empty: css`- padding-block: 8px;- padding-inline: 8px;- font-size: 12px;- color: ${cssVar.colorTextQuaternary};- `,- downloadCard: css`- cursor: pointer;-- display: flex;- gap: 10px;- align-items: center;-- padding-block: 8px;- padding-inline: 8px;- border-radius: ${cssVar.borderRadius};-- text-decoration: none;-- transition: background-color 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- downloadCardArrow: css`- flex: none;- margin-inline-start: auto;- color: ${cssVar.colorTextQuaternary};- `,- optionIcon: css`- display: flex;- flex: none;- align-items: center;- justify-content: center;-- width: 28px;- height: 28px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadius};-- color: ${cssVar.colorText};-- background: ${cssVar.colorBgElevated};- `,- optionMeta: css`- display: flex;- flex: 1;- flex-direction: column;- gap: 1px;-- min-width: 0;- `,- optionTitle: css`- overflow: hidden;-- font-size: 13px;- font-weight: 500;- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;- `,- header: css`- display: flex;- gap: 6px;- align-items: center;- justify-content: space-between;-- padding-block: 4px;- padding-inline: 8px;- `,- headerInfo: css`- cursor: help;- color: ${cssVar.colorTextQuaternary};- transition: color 0.2s;-- &:hover {- color: ${cssVar.colorTextSecondary};- }- `,- headerLink: css`- display: flex;- gap: 3px;- align-items: center;-- font-size: 11px;- color: ${cssVar.colorTextQuaternary};- text-decoration: none;-- transition: color 0.2s;-- &:hover {- color: ${cssVar.colorPrimary};- }- `,- headerTitle: css`- font-size: 12px;- font-weight: 500;- color: ${cssVar.colorTextTertiary};- `,- manageButton: css`- cursor: pointer;-- display: flex;- gap: 3px;- align-items: center;-- padding: 0;- border: none;-- font-size: 11px;- color: ${cssVar.colorTextQuaternary};-- background: none;-- transition: color 0.2s;-- &:hover {- color: ${cssVar.colorPrimary};- }- `,- groupLabel: css`- padding-block: 4px;- padding-inline: 8px;-- font-size: 11px;- font-weight: 500;- color: ${cssVar.colorTextQuaternary};- `,-}));+const styles = stylex.create({+ button: {+ cursor: 'pointer',+ display: 'flex',+ flex: 'none',+ gap: '6px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ whiteSpace: 'nowrap',+ transition: 'all 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ buttonLabel: {+ overflow: 'hidden',+ maxWidth: '120px',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ buttonReadonly: {+ cursor: 'default',+ color: { 'default': null, ':hover': cssVar.colorTextSecondary },+ backgroundColor: { 'default': null, ':hover': 'transparent' },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ desc: {+ display: 'flex',+ gap: '6px',+ alignItems: 'center',+ fontSize: '11px',+ color: cssVar.colorTextDescription,+ },+ extraInfo: {+ cursor: 'help',+ display: 'flex',+ alignItems: 'center',+ color: { 'default': cssVar.colorTextQuaternary, ':hover': cssVar.colorTextSecondary },+ transition: 'color 0.2s',+ },+ deviceList: {+ overflowY: 'auto',+ maxHeight: '240px',+ marginInlineEnd: '-4px',+ paddingInlineEnd: '4px',+ },+ empty: {+ paddingBlock: '8px',+ paddingInline: '8px',+ fontSize: '12px',+ color: cssVar.colorTextQuaternary,+ },+ downloadCard: {+ cursor: 'pointer',+ display: 'flex',+ gap: '10px',+ alignItems: 'center',+ paddingBlock: '8px',+ paddingInline: '8px',+ borderRadius: cssVar.borderRadius,+ textDecoration: 'none',+ transition: 'background-color 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ downloadCardArrow: { flex: 'none', marginInlineStart: 'auto', color: cssVar.colorTextQuaternary },+ optionIcon: {+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ width: '28px',+ height: '28px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ color: cssVar.colorText,+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+ optionMeta: { display: 'flex', flex: '1', flexDirection: 'column', gap: '1px', minWidth: '0' },+ optionTitle: {+ overflow: 'hidden',+ fontSize: '13px',+ fontWeight: 500,+ color: cssVar.colorText,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ header: {+ display: 'flex',+ gap: '6px',+ alignItems: 'center',+ justifyContent: 'space-between',+ paddingBlock: '4px',+ paddingInline: '8px',+ },+ headerInfo: {+ cursor: 'help',+ color: { 'default': cssVar.colorTextQuaternary, ':hover': cssVar.colorTextSecondary },+ transition: 'color 0.2s',+ },+ headerLink: {+ display: 'flex',+ gap: '3px',+ alignItems: 'center',+ fontSize: '11px',+ color: { 'default': cssVar.colorTextQuaternary, ':hover': cssVar.colorPrimary },+ textDecoration: 'none',+ transition: 'color 0.2s',+ },+ headerTitle: { fontSize: '12px', fontWeight: 500, color: cssVar.colorTextTertiary },+ manageButton: {+ cursor: 'pointer',+ display: 'flex',+ gap: '3px',+ alignItems: 'center',+ padding: '0',+ borderStyle: 'none',+ fontSize: '11px',+ color: { 'default': cssVar.colorTextQuaternary, ':hover': cssVar.colorPrimary },+ backgroundColor: 'transparent',+ backgroundImage: 'none',+ transition: 'color 0.2s',+ },+ groupLabel: {+ paddingBlock: '4px',+ paddingInline: '8px',+ fontSize: '11px',+ fontWeight: 500,+ color: cssVar.colorTextQuaternary,+ },+});interface HeteroDeviceSwitcherProps {agentId: string;@@ -610,18 +541,20 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {const content = (<Flexbox style={{ maxWidth: 320, minWidth: 280 }}>- <div className={styles.header}>+ <div {...stylex.props(styles.header)}><Flexbox horizontal align={'center'} gap={4}>- <span className={styles.headerTitle}>{t('heteroAgent.executionTarget.title')}</span>+ <span {...stylex.props(styles.headerTitle)}>+ {t('heteroAgent.executionTarget.title')}+ </span><Tooltip title={t('heteroAgent.executionTarget.infoTooltip')}>- <span className={styles.headerInfo}>+ <span {...stylex.props(styles.headerInfo)}><Icon icon={InfoIcon} size={12} /></span></Tooltip></Flexbox>{isDesktop || showWebDownloadCard ? (<button- className={styles.manageButton}+ {...stylex.props(styles.manageButton)}type="button"onClick={() => {setOpen(false);@@ -633,7 +566,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {</button>) : (<a- className={styles.headerLink}+ {...stylex.props(styles.headerLink)}href={DOWNLOAD_URL.default}rel="noreferrer"target="_blank"@@ -713,7 +646,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {onChange={handleToggleSandboxNetwork}/><Tooltip title={t('heteroAgent.executionTarget.localSandboxNetworkTip')}>- <span className={styles.extraInfo}>+ <span {...stylex.props(styles.extraInfo)}><Icon icon={InfoIcon} size={12} /></span></Tooltip>@@ -747,36 +680,36 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {<>{privateDevices.length > 0 ? (<>- <div className={styles.groupLabel}>+ <div {...stylex.props(styles.groupLabel)}>{t('heteroAgent.executionTarget.personalGroup')}</div>- <div className={styles.deviceList}>+ <div {...stylex.props(styles.deviceList)}>{privateDevices.map((d) => renderDeviceRow(d))}</div></>) : null}{workspaceDevices.length > 0 ? (<>- <div className={styles.groupLabel}>+ <div {...stylex.props(styles.groupLabel)}>{t('heteroAgent.executionTarget.workspaceGroup')}</div>- <div className={styles.deviceList}>+ <div {...stylex.props(styles.deviceList)}>{workspaceDevices.map((d) => renderDeviceRow(d))}</div></>) : null}</>) : (- <div className={styles.deviceList}>+ <div {...stylex.props(styles.deviceList)}>{personalOnlyDevices.map((d) => renderDeviceRow(d))}</div>)) : null}{poolStatus === 'loading' ? (- <div className={styles.empty}>{t('heteroAgent.executionTarget.loading')}</div>+ <div {...stylex.props(styles.empty)}>{t('heteroAgent.executionTarget.loading')}</div>) : null}{poolStatus === 'error' ? (- <div className={styles.empty}>+ <div {...stylex.props(styles.empty)}>{t('heteroAgent.executionTarget.loadFailed')}{' '}<arole="button"@@ -792,7 +725,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {suppressed above, so guide the user to enroll one into the sharedpool instead of showing a bare menu. */}{showWorkspaceEnrollHint ? (- <div className={styles.empty}>+ <div {...stylex.props(styles.empty)}>{t('heteroAgent.executionTarget.noWorkspaceDevices', {cmd: `lh connect --workspace ${agentWorkspaceId}`,})}@@ -802,35 +735,39 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {unlocks local execution + `lh connect`) rather than a muted dead-end. */}{showWebDownloadCard ? (<a- className={styles.downloadCard}+ {...stylex.props(styles.downloadCard)}href={DOWNLOAD_URL.default}rel="noreferrer"target="_blank">- <div className={styles.optionIcon}>+ <div {...stylex.props(styles.optionIcon)}><Icon icon={MonitorDownIcon} size={14} /></div>- <div className={styles.optionMeta}>- <div className={styles.optionTitle}>+ <div {...stylex.props(styles.optionMeta)}>+ <div {...stylex.props(styles.optionTitle)}>{t('heteroAgent.executionTarget.downloadDesktopTitle')}</div>- <div className={styles.desc}>+ <div {...stylex.props(styles.desc)}>{t('heteroAgent.executionTarget.downloadDesktopDesc')}</div></div>- <Icon className={styles.downloadCardArrow} icon={ExternalLinkIcon} size={13} />+ <Icon+ className={stylex.props(styles.downloadCardArrow).className}+ icon={ExternalLinkIcon}+ size={13}+ /></a>) : null}{isPoolEmpty && isDesktop && !isWorkspaceAgent ? (- <div className={styles.empty}>{t('heteroAgent.executionTarget.noDevices')}</div>+ <div {...stylex.props(styles.empty)}>{t('heteroAgent.executionTarget.noDevices')}</div>) : null}</Flexbox>);const chip = (- <div className={cx(styles.button, !canShowExecutionTargetSelector && styles.buttonReadonly)}>+ <div {...stylex.props(styles.button, !canShowExecutionTargetSelector && styles.buttonReadonly)}>{chipIcon}- <span className={styles.buttonLabel}>{chipLabel}</span>+ <span {...stylex.props(styles.buttonLabel)}>{chipLabel}</span>{load && <DeviceLoadMeter load={load} />}{canShowExecutionTargetSelector ? <Icon icon={ChevronDownIcon} size={12} /> : null}</div>diff --git a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsxindex 0fa19c3712f..4b5de7c8b07 100644--- a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx+++ b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx@@ -6,9 +6,6 @@ import { HETEROGENEOUS_AGENT_DEFAULT_SELECTION } from '@lobechat/types';import {ActionIcon,Button,- createStaticStyles,- cssVar,- cx,DropdownMenuGroup,DropdownMenuGroupLabel,DropdownMenuHeader,@@ -31,6 +28,8 @@ import {Input,Tooltip,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {CheckIcon,ChevronDownIcon,@@ -57,89 +56,58 @@ import { useMenuContentLifecycle } from '../useMenuContentLifecycle';import { useModelCatalog } from './useModelCatalog';import { useModelCatalogView } from './useModelCatalogView';-const styles = createStaticStyles(({ css }) => ({- check: css`- flex: none;- color: ${cssVar.colorPrimary};- `,- empty: css`- padding-block: 24px;- padding-inline: 16px;+const spin = stylex.keyframes({ to: { transform: 'rotate(360deg)' } });- font-size: 12px;- color: ${cssVar.colorTextTertiary};- text-align: center;- `,- groupLabel: css`- text-transform: none;- letter-spacing: normal;- `,- item: css`- min-height: 42px;- `,- popup: css`- overflow: hidden;- display: flex;- flex-direction: column;-- width: 340px;- max-height: 430px;- `,- search: css`- display: flex;- gap: 8px;- align-items: center;- padding-block: 10px;- `,- spinning: css`- animation: heterogeneous-agent-model-spin 0.8s linear infinite;-- @keyframes heterogeneous-agent-model-spin {- to {- transform: rotate(360deg);- }- }- `,- stale: css`- color: ${cssVar.colorWarning};- `,- submenuMeta: css`- overflow: hidden;-- max-width: 150px;-- font-family: inherit;- text-overflow: ellipsis;- white-space: nowrap;- `,- trigger: css`- cursor: pointer;-- display: flex;- flex: none;- gap: 6px;- align-items: center;-- height: 28px;- padding-inline: 8px;- border-radius: 6px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillSecondary};- }- `,- triggerDisabled: css`- cursor: not-allowed;- opacity: 0.5;- `,- triggerLabel: css`- white-space: nowrap;- `,-}));+const styles = stylex.create({+ check: { flex: 'none', color: cssVar.colorPrimary },+ empty: {+ paddingBlock: '24px',+ paddingInline: '16px',+ fontSize: '12px',+ color: cssVar.colorTextTertiary,+ textAlign: 'center',+ },+ groupLabel: { textTransform: 'none', letterSpacing: 'normal' },+ item: { minHeight: '42px' },+ popup: {+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column',+ width: '340px',+ maxHeight: '430px',+ },+ search: { display: 'flex', gap: '8px', alignItems: 'center', paddingBlock: '10px' },+ spinning: {+ animationName: spin,+ animationDuration: '0.8s',+ animationTimingFunction: 'linear',+ animationIterationCount: 'infinite',+ },+ stale: { color: cssVar.colorWarning },+ submenuMeta: {+ overflow: 'hidden',+ maxWidth: '150px',+ fontFamily: 'inherit',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ trigger: {+ cursor: 'pointer',+ display: 'flex',+ flex: 'none',+ gap: '6px',+ alignItems: 'center',+ height: '28px',+ paddingInline: '8px',+ borderRadius: '6px',+ fontSize: '12px',+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillSecondary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ triggerDisabled: { cursor: 'not-allowed', opacity: 0.5 },+ triggerLabel: { whiteSpace: 'nowrap' },+});const getCatalogErrorKey = (name: string) => {switch (name) {@@ -252,7 +220,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(const trigger = (<div- className={cx(styles.trigger, disabled && styles.triggerDisabled)}+ {...stylex.props(styles.trigger, disabled && styles.triggerDisabled)}aria-label={t('heteroAgent.cliModel.ariaLabel', {name: agentName,model:@@ -261,7 +229,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(: currentModel,})}>- <span className={styles.triggerLabel}>+ <span {...stylex.props(styles.triggerLabel)}>{currentModel === HETEROGENEOUS_AGENT_DEFAULT_SELECTION? t('heteroAgent.modelSelector.default'): currentModel}@@ -282,7 +250,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(const closeOnSelect = variant !== 'submenu';const menu = (<>- <DropdownMenuHeader className={styles.search}>+ <DropdownMenuHeader className={stylex.props(styles.search).className}><InputautoFocusplaceholder={t('heteroAgent.cliModel.search')}@@ -295,7 +263,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(/><ActionIconaria-label={t('heteroAgent.cliModel.reload')}- className={cx(isValidating && styles.spinning)}+ className={isValidating ? stylex.props(styles.spinning).className : undefined}disabled={!targetReady || isValidating}icon={isValidating ? LoaderCircleIcon : RefreshCwIcon}size="small"@@ -305,7 +273,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(</DropdownMenuHeader><DropdownMenuScrollViewport><DropdownMenuItem- className={styles.item}+ className={stylex.props(styles.item).className}closeOnClick={closeOnSelect}onClick={() => handleModelSelect(HETEROGENEOUS_AGENT_DEFAULT_SELECTION)}>@@ -319,7 +287,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(</DropdownMenuItemDesc></DropdownMenuItemLabelGroup>{currentModel === HETEROGENEOUS_AGENT_DEFAULT_SELECTION && (- <DropdownMenuItemExtra className={styles.check}>+ <DropdownMenuItemExtra className={stylex.props(styles.check).className}><Icon icon={CheckIcon} size={14} /></DropdownMenuItemExtra>)}@@ -327,15 +295,15 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(</DropdownMenuItem>{isLoading && !data && (- <div className={styles.empty}>+ <div {...stylex.props(styles.empty)}>{t('heteroAgent.cliModel.loading', { name: agentName })}</div>)}{!targetReady && (- <div className={styles.empty}>{t('heteroAgent.cliModel.targetUnavailable')}</div>+ <div {...stylex.props(styles.empty)}>{t('heteroAgent.cliModel.targetUnavailable')}</div>)}{error && (- <div className={styles.empty}>+ <div {...stylex.props(styles.empty)}>{t(getCatalogErrorKey(error.name))}<br /><Button size="small" type="text" onClick={() => void mutate()}>@@ -344,7 +312,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(</div>)}{data && !error && rows.length === 0 && (- <div className={styles.empty}>+ <div {...stylex.props(styles.empty)}>{search.trim()? t('heteroAgent.cliModel.noMatch'): t('heteroAgent.cliModel.empty', { name: agentName })}@@ -352,7 +320,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>()}{Object.entries(groups).map(([providerId, models]) => (<DropdownMenuGroup key={providerId}>- <DropdownMenuGroupLabel className={styles.groupLabel}>+ <DropdownMenuGroupLabel className={stylex.props(styles.groupLabel).className}>{getHeterogeneousTypeLabel(providerId) ?? providerId}</DropdownMenuGroupLabel>{models.map((item) => {@@ -360,7 +328,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(return (<DropdownMenuItem- className={styles.item}+ className={stylex.props(styles.item).className}closeOnClick={closeOnSelect}key={item.id}onClick={() => handleModelSelect(item.id)}@@ -368,13 +336,15 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(<DropdownMenuItemContent><DropdownMenuItemLabelGroup><DropdownMenuItemLabel>{item.label ?? item.modelId}</DropdownMenuItemLabel>- <DropdownMenuItemDesc className={cx(isStale && styles.stale)}>+ <DropdownMenuItemDesc+ className={isStale ? stylex.props(styles.stale).className : undefined}+ >{item.id}{isStale ? ` · ${t('heteroAgent.cliModel.stale')}` : ''}</DropdownMenuItemDesc></DropdownMenuItemLabelGroup>{item.id === currentModel && (- <DropdownMenuItemExtra className={styles.check}>+ <DropdownMenuItemExtra className={stylex.props(styles.check).className}><Icon icon={CheckIcon} size={14} /></DropdownMenuItemExtra>)}@@ -412,7 +382,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>({t('heteroAgent.modelSelector.model')}</DropdownMenuItemLabel>)}- <DropdownMenuItemExtra className={styles.submenuMeta}>+ <DropdownMenuItemExtra className={stylex.props(styles.submenuMeta).className}>{currentModel === HETEROGENEOUS_AGENT_DEFAULT_SELECTION? t('heteroAgent.modelSelector.default'): currentModel}@@ -424,7 +394,10 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(</DropdownMenuSubmenuTrigger><DropdownMenuPortal><DropdownMenuPositioner alignOffset={-4} anchor={null} placement="right" sideOffset={8}>- <DropdownMenuPopup className={styles.popup} data-has-header="">+ <DropdownMenuPopup+ className={stylex.props(styles.popup).className}+ data-has-header=""+ >{menu}</DropdownMenuPopup></DropdownMenuPositioner>@@ -442,7 +415,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(<DropdownMenuTrigger nativeButton={false}>{trigger}</DropdownMenuTrigger><DropdownMenuPortal><DropdownMenuPositioner placement="topLeft" sideOffset={8}>- <DropdownMenuPopup className={styles.popup} data-has-header="">+ <DropdownMenuPopup className={stylex.props(styles.popup).className} data-has-header="">{menu}</DropdownMenuPopup></DropdownMenuPositioner>diff --git a/src/features/ChatInput/ControlBar/ModeSelector.tsx b/src/features/ChatInput/ControlBar/ModeSelector.tsxindex a20e27f8b63..d7b179b4713 100644--- a/src/features/ChatInput/ControlBar/ModeSelector.tsx+++ b/src/features/ChatInput/ControlBar/ModeSelector.tsx@@ -1,4 +1,6 @@-import { createStaticStyles, cssVar, cx, Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {ChevronDownIcon,FolderIcon,@@ -19,111 +21,84 @@ import { useEffectiveAgentMode } from '@/features/ChatInput/hooks/useEffectiveAgimport { useToggleAgentMode } from '@/features/ChatInput/hooks/useToggleAgentMode';import { usePermission } from '@/hooks/usePermission';-const styles = createStaticStyles(({ css }) => ({- activeOption: css`- background: ${cssVar.colorFillSecondary};- `,- agentTooltip: css`- display: flex;- flex-direction: column;- gap: 4px;- min-width: 160px;- `,- agentTooltipCap: css`- display: flex;- gap: 6px;- align-items: center;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};- `,- agentTooltipTitle: css`- margin-block-end: 2px;- font-size: 12px;- font-weight: 600;- color: ${cssVar.colorText};- `,- button: css`- cursor: pointer;-- display: flex;- flex: none;- gap: 6px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;-- transition: all 0.2s;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,- buttonDisabled: css`- cursor: not-allowed;- opacity: 0.5;-- &:hover {- color: ${cssVar.colorTextSecondary};- background: transparent;- }- `,- option: css`- cursor: pointer;-- width: 100%;- padding-block: 10px;- padding-inline: 8px;- border-radius: ${cssVar.borderRadius};-- transition: background-color 0.2s;-- &:hover {- background: ${cssVar.colorFillSecondary};- }- `,- optionDisabled: css`- cursor: not-allowed;- opacity: 0.55;-- &:hover {- background: transparent;- }- `,- optionDesc: css`- font-size: 12px;- line-height: 1.4;- color: ${cssVar.colorTextDescription};- `,- optionIcon: css`- flex-shrink: 0;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadius};- background: ${cssVar.colorBgElevated};- `,- optionTitle: css`- font-size: 14px;- font-weight: 500;- line-height: 1.4;- color: ${cssVar.colorText};- `,- popoverPopup: css`- /* The popup pads its option rows by 4px, so its corner must be one step larger- than the rows' radius (borderRadius 8 → borderRadiusLG 12 = 8 + 4) to wrap them- concentrically instead of looking tighter than them. &&& outranks the base- popup style's border-radius. */- &&& {- border-radius: ${cssVar.borderRadiusLG};- }- `,-}));+const styles = stylex.create({+ activeOption: {+ backgroundColor: { 'default': cssVar.colorFillSecondary, ':hover': cssVar.colorFillSecondary },+ backgroundImage: 'none',+ },+ agentTooltip: { display: 'flex', flexDirection: 'column', gap: '4px', minWidth: '160px' },+ agentTooltipCap: {+ display: 'flex',+ gap: '6px',+ alignItems: 'center',+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ },+ agentTooltipTitle: {+ marginBlockEnd: '2px',+ fontSize: '12px',+ fontWeight: 600,+ color: cssVar.colorText,+ },+ button: {+ cursor: 'pointer',+ display: 'flex',+ flex: 'none',+ gap: '6px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ whiteSpace: 'nowrap',+ transition: 'all 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ buttonDisabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorTextSecondary },+ backgroundColor: { 'default': null, ':hover': 'transparent' },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ option: {+ cursor: 'pointer',+ width: '100%',+ paddingBlock: '10px',+ paddingInline: '8px',+ borderRadius: cssVar.borderRadius,+ transition: 'background-color 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillSecondary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ optionDesc: { fontSize: '12px', lineHeight: 1.4, color: cssVar.colorTextDescription },+ optionDisabled: {+ cursor: 'not-allowed',+ opacity: 0.55,+ backgroundColor: { 'default': null, ':hover': 'transparent' },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ optionDisabledActive: {+ backgroundColor: { 'default': cssVar.colorFillSecondary, ':hover': 'transparent' },+ backgroundImage: 'none',+ },+ optionIcon: {+ flexShrink: 0,+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+ optionTitle: { fontSize: '14px', fontWeight: 500, lineHeight: 1.4, color: cssVar.colorText },+ // The popup pads its option rows by 4px, so its corner must be one step larger+ // than the rows' radius (borderRadius 8 → borderRadiusLG 12 = 8 + 4) to wrap them+ // concentrically instead of looking tighter than them.+ popoverPopup: { borderRadius: cssVar.borderRadiusLG },+});const AGENT_CAPS = [{ icon: WrenchIcon, key: 'tools' },@@ -172,10 +147,10 @@ const ModeSelector = memo(() => {);const agentTooltip = (- <div className={styles.agentTooltip}>- <div className={styles.agentTooltipTitle}>{t('chatMode.agent')}</div>+ <div {...stylex.props(styles.agentTooltip)}>+ <div {...stylex.props(styles.agentTooltipTitle)}>{t('chatMode.agent')}</div>{AGENT_CAPS.map(({ key, icon }) => (- <div className={styles.agentTooltipCap} key={key}>+ <div {...stylex.props(styles.agentTooltipCap)} key={key}><Icon icon={icon} size={12} />{t(`chatMode.agentCap.${key}`)}</div>@@ -197,16 +172,19 @@ const ModeSelector = memo(() => {horizontalalign="center"gap={12}- className={cx(- styles.option,- currentMode === 'agent' && styles.activeOption,- !canSelectAgentMode && styles.optionDisabled,- )}+ className={+ stylex.props(+ styles.option,+ currentMode === 'agent' && styles.activeOption,+ !canSelectAgentMode && styles.optionDisabled,+ currentMode === 'agent' && !canSelectAgentMode && styles.optionDisabledActive,+ ).className+ }onClick={() => handleSelect('agent')}><Flexboxalign="center"- className={styles.optionIcon}+ className={stylex.props(styles.optionIcon).className}height={32}justify="center"width={32}@@ -214,21 +192,23 @@ const ModeSelector = memo(() => {<Icon icon={InfinityIcon} size={16} /></Flexbox><Flexbox flex={1}>- <div className={styles.optionTitle}>{t('chatMode.agent')}</div>- <div className={styles.optionDesc}>{agentDesc}</div>+ <div {...stylex.props(styles.optionTitle)}>{t('chatMode.agent')}</div>+ <div {...stylex.props(styles.optionDesc)}>{agentDesc}</div></Flexbox></Flexbox><Flexboxhorizontalalign="center"- className={cx(styles.option, currentMode === 'chat' && styles.activeOption)}gap={12}+ className={+ stylex.props(styles.option, currentMode === 'chat' && styles.activeOption).className+ }onClick={() => handleSelect('chat')}><Flexboxalign="center"- className={styles.optionIcon}+ className={stylex.props(styles.optionIcon).className}height={32}justify="center"width={32}@@ -236,15 +216,15 @@ const ModeSelector = memo(() => {<Icon icon={MessageCircleIcon} size={16} /></Flexbox><Flexbox flex={1}>- <div className={styles.optionTitle}>{t('chatMode.chat')}</div>- <div className={styles.optionDesc}>{t('chatMode.chatDesc')}</div>+ <div {...stylex.props(styles.optionTitle)}>{t('chatMode.chat')}</div>+ <div {...stylex.props(styles.optionDesc)}>{t('chatMode.chatDesc')}</div></Flexbox></Flexbox></Flexbox>);const button = (- <div className={cx(styles.button, disabled && styles.buttonDisabled)}>+ <div {...stylex.props(styles.button, disabled && styles.buttonDisabled)}><Icon icon={CurrentIcon} size={14} /><span>{t(`chatMode.${currentMode}`)}</span><Icon icon={ChevronDownIcon} size={12} />@@ -263,7 +243,7 @@ const ModeSelector = memo(() => {return (<Popover- className={styles.popoverPopup}+ className={stylex.props(styles.popoverPopup).className}content={popoverContent}open={!disabled && open}placement="topLeft"diff --git a/src/features/ChatInput/ControlBar/OptionRow.tsx b/src/features/ChatInput/ControlBar/OptionRow.tsxindex b453747ecdc..d5b7c56c07d 100644--- a/src/features/ChatInput/ControlBar/OptionRow.tsx+++ b/src/features/ChatInput/ControlBar/OptionRow.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, cx, Flexbox, Icon } from '@lobehub/ui';+import { Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { CheckIcon } from 'lucide-react';import { memo, type ReactNode } from 'react';@@ -12,113 +14,97 @@ import { memo, type ReactNode } from 'react';* same bar and are read as one control surface — a second copy of the styles* would drift into looking like a different kind of thing.*/-const styles = createStaticStyles(({ css }) => ({- check: css`- flex: none;- margin-inline-start: auto;- color: ${cssVar.colorPrimary};- `,- desc: css`- display: flex;- gap: 6px;- align-items: center;-- font-size: 11px;- color: ${cssVar.colorTextDescription};- `,- extra: css`- display: flex;- flex: none;- gap: 4px;- align-items: center;-- margin-inline-start: auto;- `,- option: css`- cursor: pointer;-- display: flex;- gap: 10px;- align-items: center;-- padding-block: 8px;- padding-inline: 8px;- border-radius: ${cssVar.borderRadius};-- transition: background-color 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- optionActive: css`- background: ${cssVar.colorFillSecondary};- `,+const styles = stylex.create({+ check: { flex: 'none', marginInlineStart: 'auto', color: cssVar.colorPrimary },+ desc: {+ display: 'flex',+ gap: '6px',+ alignItems: 'center',+ fontSize: '11px',+ color: cssVar.colorTextDescription,+ },+ extra: {+ display: 'flex',+ flex: 'none',+ gap: '4px',+ alignItems: 'center',+ marginInlineStart: 'auto',+ },+ option: {+ cursor: 'pointer',+ display: 'flex',+ gap: '10px',+ alignItems: 'center',+ paddingBlock: '8px',+ paddingInline: '8px',+ borderRadius: cssVar.borderRadius,+ transition: 'background-color 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ optionActive: {+ backgroundColor: { 'default': cssVar.colorFillSecondary, ':hover': cssVar.colorFillTertiary },+ backgroundImage: 'none',+ },+ optionActiveDisabled: {+ backgroundColor: { 'default': cssVar.colorFillSecondary, ':hover': 'transparent' },+ backgroundImage: 'none',+ },+ optionDisabled: {+ cursor: 'not-allowed',+ backgroundColor: { 'default': null, ':hover': 'transparent' },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },/* Dims the row's own content rather than the row. Its trailing action is theway OUT of that state — dimming it would read as "also unavailable" — andopacity on the row cannot be undone by a child, so the action is left out- of the selector instead. */- optionDisabled: css`- cursor: not-allowed;-- & > :not([data-option-extra]) {- opacity: 0.55;- }-- &:hover {- background: transparent;- }- `,- optionIcon: css`- display: flex;- flex: none;- align-items: center;- justify-content: center;-- width: 28px;- height: 28px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadius};-- color: ${cssVar.colorText};-- background: ${cssVar.colorBgElevated};- `,- optionMeta: css`- display: flex;- flex: 1;- flex-direction: column;- gap: 1px;-- min-width: 0;- `,- optionTitle: css`- overflow: hidden;-- font-size: 13px;- font-weight: 500;- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;- `,- tag: css`- flex: none;-- padding-block: 0;- padding-inline: 5px;- border-radius: 4px;-- font-size: 10px;- line-height: 16px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillSecondary};- `,-}));+ of the dimmed elements instead. */+ dimmed: { opacity: 0.55 },+ optionIcon: {+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ width: '28px',+ height: '28px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ color: cssVar.colorText,+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+ optionMeta: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ gap: '1px',+ minWidth: '0',+ },+ optionTitle: {+ overflow: 'hidden',+ fontSize: '13px',+ fontWeight: 500,+ color: cssVar.colorText,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ tag: {+ flex: 'none',+ paddingBlock: '0',+ paddingInline: '5px',+ borderRadius: '4px',+ fontSize: '10px',+ lineHeight: '16px',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillSecondary,+ backgroundImage: 'none',+ },+});export interface OptionRowProps {active?: boolean;- className?: string;desc?: ReactNode;disabled?: boolean;/** Trailing action, kept live while the row itself is disabled. */@@ -130,38 +116,41 @@ export interface OptionRowProps {tag?: ReactNode;/** Several tags, each in its own pill rather than one pill holding them all. */tags?: ReactNode[];+ /** Restyles the row; applied last so it wins over the defaults. */+ xstyle?: stylex.StyleXStyles;}const OptionRow = memo<OptionRowProps>(- ({ active, className, desc, disabled, extra, icon, label, onClick, tag, tags }) => (+ ({ active, desc, disabled, extra, icon, label, onClick, tag, tags, xstyle }) => (<div- className={cx(+ onClick={() => {+ if (!disabled) onClick();+ }}+ {...stylex.props(styles.option,active && styles.optionActive,disabled && styles.optionDisabled,- className,+ active && disabled && styles.optionActiveDisabled,+ xstyle,)}- onClick={() => {- if (!disabled) onClick();- }}>- <div className={styles.optionIcon}>{icon}</div>- <div className={styles.optionMeta}>+ <div {...stylex.props(styles.optionIcon, disabled && styles.dimmed)}>{icon}</div>+ <div {...stylex.props(styles.optionMeta, disabled && styles.dimmed)}><Flexbox horizontal align={'center'} gap={6}>- <span className={styles.optionTitle}>{label}</span>- {tag ? <span className={styles.tag}>{tag}</span> : null}+ <span {...stylex.props(styles.optionTitle)}>{label}</span>+ {tag ? <span {...stylex.props(styles.tag)}>{tag}</span> : null}{tags?.map((item, index) => (- <span className={styles.tag} key={index}>+ <span key={index} {...stylex.props(styles.tag)}>{item}</span>))}</Flexbox>- {desc ? <div className={styles.desc}>{desc}</div> : null}+ {desc ? <div {...stylex.props(styles.desc)}>{desc}</div> : null}</div>{extra ? (<divdata-option-extra- className={styles.extra}+ {...stylex.props(styles.extra)}onClick={(event) => {event.stopPropagation();}}@@ -169,7 +158,13 @@ const OptionRow = memo<OptionRowProps>({extra}</div>) : null}- {active ? <Icon className={styles.check} icon={CheckIcon} size={14} /> : null}+ {active ? (+ <Icon+ className={stylex.props(styles.check, disabled && styles.dimmed).className}+ icon={CheckIcon}+ size={14}+ />+ ) : null}</div>),);diff --git a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsxindex 552b628595a..087398bfb52 100644--- a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronDownIcon } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';@@ -22,32 +24,25 @@ import {} from './projectDeviceTargets';import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';-const styles = createStaticStyles(({ css }) => ({+const styles = stylex.create({// Picking a device here really picks an environment, and the path is what// tells them apart, so it wraps in full instead of truncating.- desc: css`- min-width: 0;- overflow-wrap: anywhere;- `,- hint: css`- padding-block: 6px;- padding-inline: 8px;- font-size: 11px;- color: ${cssVar.colorTextDescription};- `,- status: css`- flex: none;- white-space: nowrap;- `,- title: css`- padding-block: 4px;- padding-inline: 8px;-- font-size: 12px;- font-weight: 500;- color: ${cssVar.colorTextTertiary};- `,-}));+ desc: { minWidth: '0', overflowWrap: 'anywhere' },+ hint: {+ paddingBlock: '6px',+ paddingInline: '8px',+ fontSize: '11px',+ color: cssVar.colorTextDescription,+ },+ status: { flex: 'none', whiteSpace: 'nowrap' },+ title: {+ paddingBlock: '4px',+ paddingInline: '8px',+ fontSize: '12px',+ fontWeight: 500,+ color: cssVar.colorTextTertiary,+ },+});interface ProjectDeviceSwitcherProps {/** Tag on the current directory's row, naming what runs there. */@@ -101,7 +96,7 @@ const ProjectDeviceSwitcher = ({const content = (<Flexbox style={{ maxWidth: 400, minWidth: 280 }}>- <div className={styles.title}>{t('heteroAgent.executionTarget.title')}</div>+ <div {...stylex.props(styles.title)}>{t('heteroAgent.executionTarget.title')}</div>{targets.map((target) => {const selectable = target.online && target.allowed;const row = (@@ -114,8 +109,8 @@ const ProjectDeviceSwitcher = ({desc={target.allowed ? (<>- <span className={styles.desc}>{target.directory.path}</span>- <span className={styles.status}>+ <span {...stylex.props(styles.desc)}>{target.directory.path}</span>+ <span {...stylex.props(styles.status)}><ExecutionTargetDeviceStatusofflineLabel={t('heteroAgent.executionTarget.offline')}online={target.online}@@ -126,7 +121,9 @@ const ProjectDeviceSwitcher = ({</span></>) : (- <span className={styles.desc}>{t('heteroAgent.executionTarget.fixedTip')}</span>+ <span {...stylex.props(styles.desc)}>+ {t('heteroAgent.executionTarget.fixedTip')}+ </span>)}icon={@@ -145,14 +142,16 @@ const ProjectDeviceSwitcher = ({row);})}- <div className={styles.hint}>{t('heteroAgent.executionTarget.projectDevicesHint')}</div>+ <div {...stylex.props(styles.hint)}>+ {t('heteroAgent.executionTarget.projectDevicesHint')}+ </div></Flexbox>);const trigger = (- <div className={workingDirectoryChipStyles.chip}>+ <div {...stylex.props(workingDirectoryChipStyles.chip)}><ExecutionTargetIcon devicePlatform={directory?.platform} target={'device'} />- <span className={workingDirectoryChipStyles.label}>+ <span {...stylex.props(workingDirectoryChipStyles.label)}>{directory? projectDirectoryDeviceName(directory, devices): t('heteroAgent.executionTarget.unknownDevice')}diff --git a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsxindex 7d34130d2f6..05a529db4a8 100644--- a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx+++ b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx@@ -1,6 +1,6 @@'use client';-import { cx, Flexbox, Icon, Popover, Skeleton, Text, toast, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Popover, Skeleton, Text, toast, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import {@@ -53,7 +53,7 @@ const styles = stylex.create({paddingBlock: 8,paddingInline: 8,},- // StyleX longhands outrank the row's own emotion padding.+ // Applied after the row's defaults through xstyle.option: {paddingInline: 0,},@@ -62,8 +62,6 @@ const styles = stylex.create({},});-const optionClassName = stylex.props(styles.option).className;-interface SandboxDrivePickerProps {/** Whether this plan includes a drive. Without one the menu offers the way to a plan. */entitled: boolean;@@ -211,19 +209,19 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(<OptionRowactive={!persistent}- className={optionClassName}desc={t('sandboxStorage.ephemeralDesc')}icon={<Icon icon={TimerIcon} size={16} />}label={t('sandboxStorage.ephemeral')}+ xstyle={styles.option}onClick={() => void select({})}/>{entitled && persistent && currentLabel && (<OptionRowactive- className={optionClassName}icon={<Icon icon={currentIcon} size={16} />}label={currentLabel}+ xstyle={styles.option}desc={value.instanceId? t('sandboxDrive.environmentDesc')@@ -242,10 +240,10 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>({entitled && (<OptionRow- className={optionClassName}desc={t('sandboxDrive.browseDesc')}icon={<Icon icon={persistent ? FolderOpenIcon : HardDriveIcon} size={16} />}label={t(persistent ? 'sandboxDrive.browseOther' : 'sandboxDrive.browse')}+ xstyle={styles.option}onClick={openBrowser}/>)}@@ -255,11 +253,11 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(// same list, in the same shape, so the row reads as one more place// files could go — and the tag says why it is not simply selectable.<OptionRow- className={optionClassName}desc={t('sandboxStorage.persistentUpsellDesc')}icon={<Icon icon={FolderClockIcon} size={16} />}label={t('sandboxDrive.upsell')}tag={t('pro', { ns: 'common' })}+ xstyle={styles.option}onClick={() => {setOpen(false);openSandboxStorageUpsell();@@ -286,16 +284,13 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(<Tooltip title={fallbackMessage}><divdata-testid={'sandbox-drive-chip'}- className={cx(- workingDirectoryChipStyles.chip,- fallback && stylex.props(styles.warning).className,- )}+ {...stylex.props(workingDirectoryChipStyles.chip, fallback && styles.warning)}>{chipIcon}{resolving ? (<Skeleton.Text rows={1} style={{ height: 12, width: 56 }} />) : (- <span className={workingDirectoryChipStyles.label}>{chipLabel}</span>+ <span {...stylex.props(workingDirectoryChipStyles.label)}>{chipLabel}</span>)}<Icon icon={ChevronDownIcon} size={12} /></div>diff --git a/src/features/ChatInput/ControlBar/SandboxEnvironmentPicker.tsx b/src/features/ChatInput/ControlBar/SandboxEnvironmentPicker.tsxindex d427c3009b1..6510fd8123b 100644--- a/src/features/ChatInput/ControlBar/SandboxEnvironmentPicker.tsx+++ b/src/features/ChatInput/ControlBar/SandboxEnvironmentPicker.tsx@@ -53,14 +53,12 @@ const styles = stylex.create({padding: 0,transition: 'color 0.2s',},- // StyleX longhands outrank the row's own emotion padding.+ // Applied after the row's defaults through xstyle.option: {paddingInline: 0,},});-const optionClassName = stylex.props(styles.option).className;-interface SandboxEnvironmentPickerProps {onChange: (selection: SandboxSelection) => Promise<void>;/** Where this conversation works today, and what it is initialized from. */@@ -131,21 +129,21 @@ const SandboxEnvironmentPicker = memo<SandboxEnvironmentPickerProps>(({ onChange<OptionRowactive={!value.environmentId}- className={optionClassName}desc={t('sandboxEnvironment.noneDesc')}icon={<Icon icon={CircleSlashIcon} size={16} />}label={t('sandboxEnvironment.none')}+ xstyle={styles.option}onClick={() => void select(undefined)}/><div {...stylex.props(styles.list)}>{environments.map((environment) => (<OptionRowactive={environment.id === value.environmentId}- className={optionClassName}desc={environment.description || undefined}icon={<Icon icon={PackageIcon} size={16} />}key={environment.id}label={environment.name}+ xstyle={styles.option}onClick={() => void select(environment.id)}/>))}@@ -187,9 +185,12 @@ const SandboxEnvironmentPicker = memo<SandboxEnvironmentPickerProps>(({ onChangeonOpenChange={setOpen}><div>- <div className={workingDirectoryChipStyles.chip} data-testid={'sandbox-environment-chip'}>+ <div+ {...stylex.props(workingDirectoryChipStyles.chip)}+ data-testid={'sandbox-environment-chip'}+ ><Icon icon={value.environmentId ? PackageIcon : CircleSlashIcon} size={14} />- <span className={workingDirectoryChipStyles.label}>{label}</span>+ <span {...stylex.props(workingDirectoryChipStyles.label)}>{label}</span><Icon icon={ChevronDownIcon} size={12} /></div></div>diff --git a/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsxindex 16ccb8881e2..7a5d19376d9 100644--- a/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx+++ b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx@@ -1,7 +1,5 @@import type { WorkingDirGitState } from '@lobechat/types';import {- createStaticStyles,- cssVar,DropdownMenuItem,DropdownMenuPopup,DropdownMenuPortal,@@ -10,6 +8,8 @@ import {DropdownMenuTrigger,Icon,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { GitBranchIcon, GitForkIcon, GitPullRequest, RotateCcwIcon } from 'lucide-react';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -20,39 +20,27 @@ import { gitChipStyles } from './gitChipStyles';import { resolveStaleSnapshot } from './staleSnapshot';import { useSwitchWorktree } from './useSwitchWorktree';-const styles = createStaticStyles(({ css }) => ({- action: css`- display: flex;- gap: 8px;- align-items: center;- `,- explanation: css`- max-width: 320px;- padding-block: 6px 8px;- padding-inline: 10px;-- font-size: 12px;- line-height: 1.5;- color: ${cssVar.colorTextSecondary};- `,- path: css`- display: block;-- margin-block-start: 2px;-- font-family: ${cssVar.fontFamilyCode};- color: ${cssVar.colorTextTertiary};- word-break: break-all;- `,- popup: css`- padding: 0;- `,- triggerLabel: css`- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- `,-}));+const styles = stylex.create({+ action: { display: 'flex', gap: '8px', alignItems: 'center' },+ explanation: {+ maxWidth: '320px',+ paddingBlockStart: '6px',+ paddingBlockEnd: '8px',+ paddingInline: '10px',+ fontSize: '12px',+ lineHeight: 1.5,+ color: cssVar.colorTextSecondary,+ },+ path: {+ display: 'block',+ marginBlockStart: '2px',+ fontFamily: cssVar.fontFamilyCode,+ color: cssVar.colorTextTertiary,+ wordBreak: 'break-all',+ },+ popup: { padding: '0' },+ triggerLabel: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },+});interface StaleGitSnapshotProps {agentId: string;@@ -114,25 +102,25 @@ const StaleGitSnapshot = memo<StaleGitSnapshotProps>(}, [resetting, resetTarget, switchWorktree]);const trigger = (- <div className={gitChipStyles.staleTrigger}>+ <div {...stylex.props(gitChipStyles.staleTrigger)}><Icon icon={isWorktree ? GitForkIcon : GitBranchIcon} size={12} />- <span className={styles.triggerLabel}>{label}</span>+ <span {...stylex.props(styles.triggerLabel)}>{label}</span></div>);return (<>- <div className={gitChipStyles.separator} />+ <div {...stylex.props(gitChipStyles.separator)} /><DropdownMenuRoot open={open} onOpenChange={setOpen}><DropdownMenuTrigger><div>{trigger}</div></DropdownMenuTrigger><DropdownMenuPortal><DropdownMenuPositioner placement="topLeft" sideOffset={8}>- <DropdownMenuPopup className={styles.popup}>- <div className={styles.explanation}>+ <DropdownMenuPopup className={stylex.props(styles.popup).className}>+ <div {...stylex.props(styles.explanation)}>{t(explanation.key, explanation.values)}- <span className={styles.path}>{worktreePath}</span>+ <span {...stylex.props(styles.path)}>{worktreePath}</span></div>{reset && (<DropdownMenuItem@@ -140,7 +128,7 @@ const StaleGitSnapshot = memo<StaleGitSnapshotProps>(closeOnClick={false}onClick={handleReset}>- <div className={styles.action}>+ <div {...stylex.props(styles.action)}><Icon icon={RotateCcwIcon} size={14} /><span>{t('workingDirectory.staleResetToSource', { name: reset.name })}</span></div>@@ -152,8 +140,8 @@ const StaleGitSnapshot = memo<StaleGitSnapshotProps>(</DropdownMenuRoot>{pullRequest && (<>- <div className={gitChipStyles.separator} />- <div className={gitChipStyles.prTrigger} role="button" onClick={handleOpenPr}>+ <div {...stylex.props(gitChipStyles.separator)} />+ <div {...stylex.props(gitChipStyles.prTrigger)} role="button" onClick={handleOpenPr}><Icon icon={GitPullRequest} size={12} /><span>#{pullRequest.number}</span></div>diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsxindex 7ec8c0029d0..3088672431a 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx@@ -3,18 +3,9 @@import { isDesktop } from '@lobechat/const';import type { WorkingDirEntry } from '@lobechat/types';import { getWorkingDirSourcePath } from '@lobechat/types';-import {- ActionIcon,- createStaticStyles,- cssVar,- cx,- Flexbox,- Icon,- Input,- Popover,- toast,- Tooltip,-} from '@lobehub/ui';+import { ActionIcon, Flexbox, Icon, Input, Popover, toast, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {CheckIcon,ChevronDownIcon,@@ -57,114 +48,88 @@ import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';// gets tedious — a short list doesn't need the extra chrome.const SEARCH_THRESHOLD = 8;-const styles = createStaticStyles(({ css }) => ({- badge: css`- flex: none;-- padding-inline: 5px;- border-radius: 999px;-- font-size: 10px;- line-height: 15px;- color: ${cssVar.colorTextTertiary};-- background: ${cssVar.colorFillSecondary};- `,- chooseFolderItem: css`- cursor: pointer;-- padding-block: 8px;- padding-inline: 8px;- border-radius: ${cssVar.borderRadius};-- font-size: 13px;- color: ${cssVar.colorTextSecondary};-- transition: background-color 0.2s;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,- clearText: css`- cursor: pointer;-- padding-block: 6px 2px;- padding-inline: 8px;-- font-size: 11px;- font-weight: 500;- color: ${cssVar.colorTextTertiary};-- transition: color 0.2s;-- &:hover {- color: ${cssVar.colorText};- }- `,- dirItem: css`- cursor: pointer;-- padding-block: 6px;- padding-inline: 8px;- border-radius: ${cssVar.borderRadius};-- transition: background-color 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }-- /* Reveal the row actions (set-default / remove) only on hover. */- &:hover .wd-row-actions {- display: flex;- }- `,- dirItemActive: css`- background: ${cssVar.colorFillTertiary};- `,- dirName: css`- overflow: hidden;-- font-size: 13px;- font-weight: 500;- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;- `,- dirPath: css`- overflow: hidden;-- font-size: 11px;- color: ${cssVar.colorTextDescription};- text-overflow: ellipsis;- white-space: nowrap;- `,- rowActions: css`- display: none;- flex: none;- gap: 2px;- align-items: center;- `,- scrollContainer: css`- overflow-y: auto;- max-height: 320px;- `,- searchBar: css`- padding-block: 2px;- padding-inline: 8px;- border-block-end: 1px solid ${cssVar.colorSplit};- `,- sectionTitle: css`- padding-block: 6px 2px;- padding-inline: 8px;-- font-size: 11px;- font-weight: 500;- color: ${cssVar.colorTextQuaternary};- `,-}));+const styles = stylex.create({+ badge: {+ flex: 'none',+ paddingInline: '5px',+ borderRadius: '999px',+ fontSize: '10px',+ lineHeight: '15px',+ color: cssVar.colorTextTertiary,+ backgroundColor: cssVar.colorFillSecondary,+ backgroundImage: 'none',+ },+ chooseFolderItem: {+ cursor: 'pointer',+ paddingBlock: '8px',+ paddingInline: '8px',+ borderRadius: cssVar.borderRadius,+ fontSize: '13px',+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ transition: 'background-color 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ clearText: {+ cursor: 'pointer',+ paddingBlockStart: '6px',+ paddingBlockEnd: '2px',+ paddingInline: '8px',+ fontSize: '11px',+ fontWeight: 500,+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },+ transition: 'color 0.2s',+ },+ dirItem: {+ cursor: 'pointer',+ paddingBlock: '6px',+ paddingInline: '8px',+ borderRadius: cssVar.borderRadius,+ transition: 'background-color 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ dirItemActive: { backgroundColor: cssVar.colorFillTertiary, backgroundImage: 'none' },+ dirName: {+ overflow: 'hidden',+ fontSize: '13px',+ fontWeight: 500,+ color: cssVar.colorText,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ dirPath: {+ overflow: 'hidden',+ fontSize: '11px',+ color: cssVar.colorTextDescription,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ // Reveal the row actions (set-default / remove) only on hover of the row+ // (the `defaultMarker` on `dirItem`).+ rowActions: {+ display: { default: 'none', [stylex.when.ancestor(':hover')]: 'flex' },+ flex: 'none',+ gap: '2px',+ alignItems: 'center',+ },+ scrollContainer: { overflowY: 'auto', maxHeight: '320px' },+ searchBar: {+ paddingBlock: '2px',+ paddingInline: '8px',+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorSplit,+ },+ sectionTitle: {+ paddingBlockStart: '6px',+ paddingBlockEnd: '2px',+ paddingInline: '8px',+ fontSize: '11px',+ fontWeight: 500,+ color: cssVar.colorTextQuaternary,+ },+});const isValidWorkingDirEntry = (entry: WorkingDirEntry): boolean =>!!getWorkingDirectoryPathString(entry.path);@@ -186,7 +151,7 @@ const ChooseLocalFolderRow = memo<{ defaultPath?: string; onPick: (entry: Folder<Flexboxhorizontalalign={'center'}- className={styles.chooseFolderItem}+ className={stylex.props(styles.chooseFolderItem).className}gap={8}onClick={handleClick}>@@ -222,7 +187,7 @@ const AddRemoteFolderRow = memo<{<Flexboxhorizontalalign={'center'}- className={styles.chooseFolderItem}+ className={stylex.props(styles.chooseFolderItem).className}gap={8}onClick={handleClick}>@@ -405,29 +370,32 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =<Flexboxhorizontalalign={'center'}- className={cx(styles.dirItem, isActive && styles.dirItemActive)}gap={8}key={entry.path}ref={isActive ? activeRowRef : undefined}+ className={+ stylex.props(stylex.defaultMarker(), styles.dirItem, isActive && styles.dirItemActive)+ .className+ }onClick={() => void pick(entry)}><DirIcon repoType={entry.repoType} /><Flexbox flex={1} style={{ minWidth: 0 }}><Flexbox horizontal align={'center'} gap={6}>- <div className={styles.dirName}>+ <div {...stylex.props(styles.dirName)}>{getWorkingDirectoryName(entry.path) ?? entry.path}</div>{isDefault && (- <span className={styles.badge}>{t('workingDirectory.defaultBadge')}</span>+ <span {...stylex.props(styles.badge)}>{t('workingDirectory.defaultBadge')}</span>)}</Flexbox>- <div className={styles.dirPath}>{entry.path}</div>+ <div {...stylex.props(styles.dirPath)}>{entry.path}</div></Flexbox><Flexbox horizontal align={'center'} gap={2} style={{ flex: 'none' }}>{/* The same Star toggles the device default in both directions. Remove(X) is hidden on the active row: you can't remove the selection outfrom under yourself. */}- <div className={cx('wd-row-actions', styles.rowActions)}>+ <div {...stylex.props(styles.rowActions)}><ActionIconactive={isDefault}aria-label={defaultActionLabel}@@ -458,7 +426,7 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =const content = (<Flexbox gap={4} style={{ maxWidth: 'calc(100vw - 48px)', width: 320 }}>{showSearch && (- <div className={styles.searchBar}>+ <div {...stylex.props(styles.searchBar)}><InputautoFocusplaceholder={t('workingDirectory.searchPlaceholder')}@@ -472,14 +440,17 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =</div>)}<Flexbox horizontal align={'center'} distribution={'space-between'}>- <div className={styles.sectionTitle}>{t('workingDirectory.recent')}</div>+ <div {...stylex.props(styles.sectionTitle)}>{t('workingDirectory.recent')}</div>{hasClearableSelection && (- <div className={styles.clearText} onClick={() => void clear().then(() => setOpen(false))}>+ <div+ {...stylex.props(styles.clearText)}+ onClick={() => void clear().then(() => setOpen(false))}+ >{t('workingDirectory.clear')}</div>)}</Flexbox>- <div className={styles.scrollContainer}>+ <div {...stylex.props(styles.scrollContainer)}>{filtered.length === 0 ? (<Flexboxalign={'center'}@@ -513,13 +484,13 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =: t('workingDirectory.unselected');const trigger = (- <div className={workingDirectoryChipStyles.chip}>+ <div {...stylex.props(workingDirectoryChipStyles.chip)}>{selectedDir ? (<DirIcon repoType={recents.find((r) => r.path === selectedDir)?.repoType} />) : (<DashedFolderIcon size={14} />)}- <span className={workingDirectoryChipStyles.label}>{displayName}</span>+ <span {...stylex.props(workingDirectoryChipStyles.label)}>{displayName}</span><Icon icon={ChevronDownIcon} size={12} /></div>);diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsxindex 54ffda741f7..e9c0206b590 100644--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx@@ -1,9 +1,6 @@import { deriveWorktreePath, type DeviceGitWorktreeListItem } from '@lobechat/types';import {confirmModal,- createStaticStyles,- cssVar,- cx,DropdownMenuItem,DropdownMenuPopup,DropdownMenuPortal,@@ -16,6 +13,8 @@ import {toast,Tooltip,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {CheckIcon,FolderPlusIcon,@@ -40,290 +39,224 @@ import { useTranslation } from 'react-i18next';import { gitService } from '@/services/git';import { openCreateWorktreeModal } from './CreateWorktreeModal';-import { gitMenuTriggerStyles } from './gitMenuTriggerStyles';+import gitMenuTriggerStyles from './gitMenuTrigger.module.css';import { useSwitchWorktree } from './useSwitchWorktree';import { getPathName, isDisabled, normalizeDisplayPath } from './worktreeHelpers';-const styles = createStaticStyles(({ css }) => ({- badge: css`- flex: none;-- padding-block: 1px;- padding-inline: 5px;- border-radius: 999px;-- font-size: 11px;- line-height: 15px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillSecondary};- `,- branch: css`- overflow: hidden;- flex: 0 1 auto;-- min-width: 40px;- max-width: 300px;-- font-size: 13px;- line-height: 18px;- color: ${cssVar.colorTextSecondary};- text-overflow: ellipsis;- white-space: nowrap;- `,- check: css`- display: flex;- flex: none;- align-items: center;- justify-content: center;-- width: 18px;-- color: ${cssVar.colorPrimary};- `,- actionCell: css`- display: flex;- flex: none;- align-items: center;- justify-content: center;-- width: 20px;- `,- container: css`- display: flex;- flex-direction: column;-- width: 460px;- max-width: calc(100vw - 48px);- height: 380px;-- /* Cancel DropdownMenuPopup's default 4px padding so our sections align edge-to-edge */- margin: -4px;- `,- diffStat: css`- display: inline-flex;- flex: none;- gap: 3px;- justify-content: flex-end;-- font-variant-numeric: tabular-nums;- line-height: 1;- `,- diffStatAdded: css`- color: ${cssVar.colorSuccess};- `,- diffStatDeleted: css`- color: ${cssVar.colorError};- `,- diffStatModified: css`- color: ${cssVar.colorWarning};- `,- emptyState: css`- padding-block: 16px;- font-size: 12px;- color: ${cssVar.colorTextTertiary};- text-align: center;- `,- searchBar: css`- padding-block: 4px;- padding-inline: 12px;- border-block-end: 1px solid ${cssVar.colorSplit};- `,- section: css`- flex: 1;- font-size: 11px;- font-weight: 500;- color: ${cssVar.colorTextTertiary};- `,- sectionRow: css`- display: flex;- gap: 4px;- align-items: center;-- padding-block: 4px 2px;- padding-inline: 8px;- `,- refreshButton: css`- cursor: pointer;-- display: flex;- align-items: center;- justify-content: center;-- width: 20px;- height: 20px;- border-radius: 4px;-- color: ${cssVar.colorTextTertiary};-- transition: all 0.2s;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,- spinning: css`- animation: worktree-switcher-spin 0.8s linear infinite;-- @keyframes worktree-switcher-spin {- to {- transform: rotate(360deg);- }- }- `,- item: css`- cursor: pointer;-- display: grid;- grid-template-columns: minmax(0, 1fr) minmax(44px, auto) 20px;- gap: 10px;- align-items: center;-- min-height: 48px;- padding-block: 6px;- padding-inline: 8px;- border-radius: 8px;-- font-size: 13px;- color: ${cssVar.colorText};-- &:hover {- background: ${cssVar.colorFillTertiary};- }-- &:hover .worktree-row-action {- display: flex;- }-- &[data-current='true'] {- background: ${cssVar.colorFillSecondary};- }-- &[aria-disabled='true'] {- cursor: not-allowed;- opacity: 0.55;- }- `,- itemMain: css`- overflow: hidden;- min-width: 0;- `,- dirtyCell: css`- display: flex;- flex: none;- align-items: center;- justify-content: flex-end;-- min-width: 44px;- `,- list: css`- overflow-y: auto;- flex: 1;- padding: 6px;- `,- createItemWrapper: css`- padding: 6px;- border-block-start: 1px solid ${cssVar.colorSplit};- `,- createItem: css`- cursor: pointer;-- display: flex;- gap: 8px;- align-items: center;-- padding-block: 6px;- padding-inline: 8px;- border-radius: 8px;-- font-size: 13px;- color: ${cssVar.colorText};-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- createItemIcon: css`- flex: none;- color: ${cssVar.colorTextSecondary};- `,- name: css`- overflow: hidden;- flex: 0 1 auto;-- max-width: 240px;-- font-size: 13px;- font-weight: 400;- line-height: 18px;- text-overflow: ellipsis;- white-space: nowrap;- `,- path: css`- overflow: hidden;-- margin-block-start: 1px;-- font-size: 11px;- line-height: 16px;- color: ${cssVar.colorTextTertiary};- text-overflow: ellipsis;- white-space: nowrap;- `,- rowTitle: css`- overflow: hidden;- display: flex;- gap: 6px;- align-items: center;-- min-width: 0;-- white-space: nowrap;- `,- rowAction: css`- cursor: pointer;-- display: none;- align-items: center;- justify-content: center;-- width: 20px;- height: 20px;- border-radius: 4px;-- color: ${cssVar.colorTextTertiary};-- transition: all 0.2s;-- &:hover {- color: ${cssVar.colorError};- background: ${cssVar.colorErrorBg};- }- `,- trigger: css`- cursor: pointer;-- display: inline-flex;- flex: none;- align-items: center;- justify-content: center;-- width: 20px;- height: 22px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;-- transition: background 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,-}));+const spin = stylex.keyframes({ to: { transform: 'rotate(360deg)' } });++const styles = stylex.create({+ actionCell: {+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ },+ badge: {+ flex: 'none',+ paddingBlock: '1px',+ paddingInline: '5px',+ borderRadius: '999px',+ fontSize: '11px',+ lineHeight: '15px',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillSecondary,+ backgroundImage: 'none',+ },+ branch: {+ overflow: 'hidden',+ flexGrow: '0',+ flexShrink: '1',+ flexBasis: 'auto',+ minWidth: '40px',+ maxWidth: '300px',+ fontSize: '13px',+ lineHeight: '18px',+ color: cssVar.colorTextSecondary,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ check: {+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ width: '18px',+ color: cssVar.colorPrimary,+ },+ container: {+ display: 'flex',+ flexDirection: 'column',+ width: '460px',+ maxWidth: 'calc(100vw - 48px)',+ height: '380px',+ // Cancel DropdownMenuPopup's default 4px padding so our sections align edge-to-edge+ margin: '-4px',+ },+ createItem: {+ cursor: 'pointer',+ display: 'flex',+ gap: '8px',+ alignItems: 'center',+ paddingBlock: '6px',+ paddingInline: '8px',+ borderRadius: '8px',+ fontSize: '13px',+ color: cssVar.colorText,+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ createItemIcon: { flex: 'none', color: cssVar.colorTextSecondary },+ createItemWrapper: {+ padding: '6px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorSplit,+ },+ diffStat: {+ display: 'inline-flex',+ flex: 'none',+ gap: '3px',+ justifyContent: 'flex-end',+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 1,+ },+ diffStatAdded: { color: cssVar.colorSuccess },+ diffStatDeleted: { color: cssVar.colorError },+ diffStatModified: { color: cssVar.colorWarning },+ dirtyCell: {+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'flex-end',+ minWidth: '44px',+ },+ emptyState: {+ paddingBlock: '16px',+ fontSize: '12px',+ color: cssVar.colorTextTertiary,+ textAlign: 'center',+ },+ item: {+ cursor: 'pointer',+ display: 'grid',+ gridTemplateColumns: 'minmax(0, 1fr) minmax(44px, auto) 20px',+ gap: '10px',+ alignItems: 'center',+ minHeight: '48px',+ paddingBlock: '6px',+ paddingInline: '8px',+ borderRadius: '8px',+ fontSize: '13px',+ color: cssVar.colorText,+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ // [data-current='true'] — declared after the hover rule, so it wins on hover too.+ itemCurrent: { backgroundColor: cssVar.colorFillSecondary, backgroundImage: 'none' },+ // [aria-disabled='true']+ itemDisabled: { cursor: 'not-allowed', opacity: 0.55 },+ itemMain: { overflow: 'hidden', minWidth: '0' },+ list: { overflowY: 'auto', flex: '1', padding: '6px' },+ name: {+ overflow: 'hidden',+ flexGrow: '0',+ flexShrink: '1',+ flexBasis: 'auto',+ maxWidth: '240px',+ fontSize: '13px',+ fontWeight: 400,+ lineHeight: '18px',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ path: {+ overflow: 'hidden',+ marginBlockStart: '1px',+ fontSize: '11px',+ lineHeight: '16px',+ color: cssVar.colorTextTertiary,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ refreshButton: {+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '20px',+ borderRadius: '4px',+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },+ transition: 'all 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ // Revealed while the row (the `defaultMarker` on `item`) is hovered.+ rowAction: {+ cursor: 'pointer',+ display: {+ default: 'none',+ [stylex.when.ancestor(':hover')]: 'flex',+ },+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '20px',+ borderRadius: '4px',+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorError },+ transition: 'all 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorErrorBg },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ rowTitle: {+ overflow: 'hidden',+ display: 'flex',+ gap: '6px',+ alignItems: 'center',+ minWidth: '0',+ whiteSpace: 'nowrap',+ },+ searchBar: {+ paddingBlock: '4px',+ paddingInline: '12px',+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorSplit,+ },+ section: { flex: '1', fontSize: '11px', fontWeight: 500, color: cssVar.colorTextTertiary },+ sectionRow: {+ display: 'flex',+ gap: '4px',+ alignItems: 'center',+ paddingBlockStart: '4px',+ paddingBlockEnd: '2px',+ paddingInline: '8px',+ },+ spinning: {+ animationName: spin,+ animationDuration: '0.8s',+ animationTimingFunction: 'linear',+ animationIterationCount: 'infinite',+ },+ trigger: {+ cursor: 'pointer',+ display: 'inline-flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '22px',+ borderRadius: '4px',+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ transition: 'background 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+});const TEMP_PATH_PREFIXES = ['/tmp', '/var/tmp', '/private/tmp'];@@ -401,10 +334,14 @@ const DirtyStat = memo<DirtyStatProps>(({ status }) => {if (!status || status.clean) return null;return (- <span className={styles.diffStat}>- {status.added > 0 && <span className={styles.diffStatAdded}>+{status.added}</span>}- {status.modified > 0 && <span className={styles.diffStatModified}>±{status.modified}</span>}- {status.deleted > 0 && <span className={styles.diffStatDeleted}>-{status.deleted}</span>}+ <span {...stylex.props(styles.diffStat)}>+ {status.added > 0 && <span {...stylex.props(styles.diffStatAdded)}>+{status.added}</span>}+ {status.modified > 0 && (+ <span {...stylex.props(styles.diffStatModified)}>±{status.modified}</span>+ )}+ {status.deleted > 0 && (+ <span {...stylex.props(styles.diffStatDeleted)}>-{status.deleted}</span>+ )}</span>);});@@ -633,7 +570,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(const trigger = children ?? (<divaria-label={t('workingDirectory.worktreesHeading')}- className={styles.trigger}+ {...stylex.props(styles.trigger)}role="button"><Icon icon={triggerIcon} size={13} />@@ -659,8 +596,8 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(<DropdownMenuPortal><DropdownMenuPositioner placement={placement} sideOffset={8}><DropdownMenuPopup>- <div className={styles.container}>- <div className={styles.searchBar}>+ <div {...stylex.props(styles.container)}>+ <div {...stylex.props(styles.searchBar)}><InputautoFocusplaceholder={t('workingDirectory.worktreeSearchPlaceholder')}@@ -674,20 +611,28 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(/></div>- <div className={styles.list}>- <div className={styles.sectionRow}>- <div className={styles.section}>{t('workingDirectory.worktreesHeading')}</div>- <div className={styles.refreshButton} role="button" onClick={handleRefresh}>+ <div {...stylex.props(styles.list)}>+ <div {...stylex.props(styles.sectionRow)}>+ <div {...stylex.props(styles.section)}>+ {t('workingDirectory.worktreesHeading')}+ </div>+ <div+ {...stylex.props(styles.refreshButton)}+ role="button"+ onClick={handleRefresh}+ ><Icon- className={cx(isRefreshing && styles.spinning)}icon={RefreshCwIcon}size={12}+ className={+ isRefreshing ? stylex.props(styles.spinning).className : undefined+ }/></div></div>{filtered.length === 0 ? (- <div className={styles.emptyState}>+ <div {...stylex.props(styles.emptyState)}>{search.trim()? t('workingDirectory.worktreesNoMatch'): t('workingDirectory.worktreesEmpty')}@@ -706,61 +651,74 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(return (<DropdownMenuItemaria-disabled={disabled}- className={styles.item}closeOnClick={false}data-current={worktree.current}key={worktree.path}ref={worktree.path === currentPath ? currentRowRef : undefined}+ className={+ stylex.props(+ stylex.defaultMarker(),+ styles.item,+ worktree.current && styles.itemCurrent,+ disabled && styles.itemDisabled,+ ).className+ }onClick={() => void commitWorktree(worktree)}>- <div className={styles.itemMain}>- <div className={styles.rowTitle}>- <span className={styles.name}>{getPathName(worktree.path)}</span>- <span className={styles.branch}>{branch}</span>+ <div {...stylex.props(styles.itemMain)}>+ <div {...stylex.props(styles.rowTitle)}>+ <span {...stylex.props(styles.name)}>+ {getPathName(worktree.path)}+ </span>+ <span {...stylex.props(styles.branch)}>{branch}</span>{worktree.current && (- <span className={styles.badge}>+ <span {...stylex.props(styles.badge)}>{t('workingDirectory.currentWorktree')}</span>)}{worktree.detached && (- <span className={styles.badge}>+ <span {...stylex.props(styles.badge)}>{t('workingDirectory.detachedWorktree')}</span>)}{worktree.locked && (- <span className={styles.badge}>+ <span {...stylex.props(styles.badge)}>{t('workingDirectory.lockedWorktree')}</span>)}{worktree.prunable && (- <span className={styles.badge}>+ <span {...stylex.props(styles.badge)}>{t('workingDirectory.prunableWorktree')}</span>)}{worktree.bare && (- <span className={styles.badge}>+ <span {...stylex.props(styles.badge)}>{t('workingDirectory.bareWorktree')}</span>)}</div>- <div className={styles.path} title={worktree.path}>+ <div {...stylex.props(styles.path)} title={worktree.path}>{displayPath}</div></div>- <div className={styles.dirtyCell}>+ <div {...stylex.props(styles.dirtyCell)}><DirtyStat status={worktree.status} /></div>- <div className={styles.actionCell}>+ <div {...stylex.props(styles.actionCell)}>{removing ? (<Spin size={13} />) : worktree.current ? (- <Icon className={styles.check} icon={CheckIcon} size={14} />+ <Icon+ className={stylex.props(styles.check).className}+ icon={CheckIcon}+ size={14}+ />) : (removable && (<Tooltip title={t('workingDirectory.removeWorktreeAction')}><divaria-label={t('workingDirectory.removeWorktreeAction')}- className={`${styles.rowAction} worktree-row-action`}+ {...stylex.props(styles.rowAction)}role="button"onClick={(event) => handleRemoveWorktree(event, worktree)}>@@ -776,13 +734,17 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>()}</div>- <div className={styles.createItemWrapper}>+ <div {...stylex.props(styles.createItemWrapper)}><DropdownMenuItem- className={styles.createItem}+ className={stylex.props(styles.createItem).className}closeOnClick={false}onClick={openCreateWorktree}>- <Icon className={styles.createItemIcon} icon={FolderPlusIcon} size={14} />+ <Icon+ className={stylex.props(styles.createItemIcon).className}+ icon={FolderPlusIcon}+ size={14}+ /><div>{t('workingDirectory.createWorktreeAction')}</div></DropdownMenuItem></div>diff --git a/src/features/ChatInput/ControlBar/gitChipStyles.ts b/src/features/ChatInput/ControlBar/gitChipStyles.tsindex 2a62bde30a1..c3ff81ee374 100644--- a/src/features/ChatInput/ControlBar/gitChipStyles.ts+++ b/src/features/ChatInput/ControlBar/gitChipStyles.ts@@ -1,4 +1,5 @@-import { createStaticStyles, cssVar } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';/*** Chips shared by the live git status and by the snapshot that stands in for it@@ -7,81 +8,63 @@ import { createStaticStyles, cssVar } from '@lobehub/ui';* the deliberately muted variant of `trigger`, lives next to the live one so the* two can't drift apart.*/-export const gitChipStyles = createStaticStyles(({ css }) => ({- prTrigger: css`- cursor: pointer;-- display: flex;- flex: none;- gap: 4px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;-- transition: background 0.2s;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,- separator: css`- flex: none;- width: 1px;- height: 10px;- background: ${cssVar.colorSplit};- `,+export const gitChipStyles = stylex.create({+ prTrigger: {+ cursor: 'pointer',+ display: 'flex',+ flex: 'none',+ gap: '4px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ whiteSpace: 'nowrap',+ transition: 'background 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ separator: {+ flex: 'none',+ width: '1px',+ height: '10px',+ backgroundColor: cssVar.colorSplit,+ backgroundImage: 'none',+ },// Muted so the snapshot never reads as live state, but still a control: the// recovery action is the only thing this cluster can still do.- staleTrigger: css`- cursor: pointer;-- display: flex;- flex: none;- gap: 4px;- align-items: center;-- max-width: 200px;- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextQuaternary};- white-space: nowrap;-- transition: background 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- trigger: css`- cursor: pointer;-- display: flex;- flex: none;- gap: 4px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;-- transition: background 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,-}));+ staleTrigger: {+ cursor: 'pointer',+ display: 'flex',+ flex: 'none',+ gap: '4px',+ alignItems: 'center',+ maxWidth: '200px',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ color: cssVar.colorTextQuaternary,+ whiteSpace: 'nowrap',+ transition: 'background 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ trigger: {+ cursor: 'pointer',+ display: 'flex',+ flex: 'none',+ gap: '4px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ transition: 'background 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+});diff --git a/src/features/ChatInput/ControlBar/gitMenuTrigger.module.css b/src/features/ChatInput/ControlBar/gitMenuTrigger.module.cssnew file mode 100644index 00000000000..254a75539b6--- /dev/null+++ b/src/features/ChatInput/ControlBar/gitMenuTrigger.module.css@@ -0,0 +1,32 @@+.trigger {+ display: inline-flex;+ flex: none;+ min-width: 0;+}++/* The stable menu anchor must not paint behind the child's rounded chip or+ overview row. Keep hover and popup-open feedback on that same surface. */+.trigger.trigger.trigger[data-popup-open] {+ background: transparent;+}++/* Child rules use !important: the chips inside are StyleX-styled, and StyleX+ longhands (raised specificity) would otherwise beat these selectors. */++/* A column host stretches the anchor for overview rows; compact composer+ chips use their intrinsic width instead of 100% of the whole git group. */+.trigger.trigger > * {+ flex: 1 !important;+ min-width: 0 !important;+}++.trigger[data-popup-open] > * {+ background: var(--lobe-color-fill-tertiary) !important;+}++/* Stale-first: the trigger stays in place (no layout jump) but cannot+ checkout until the current probe confirms the branch. */+.trigger[aria-disabled='true'] > * {+ cursor: not-allowed !important;+ opacity: 0.6 !important;+}diff --git a/src/features/ChatInput/ControlBar/gitMenuTriggerStyles.ts b/src/features/ChatInput/ControlBar/gitMenuTriggerStyles.tsdeleted file mode 100644index ec1897dc49e..00000000000--- a/src/features/ChatInput/ControlBar/gitMenuTriggerStyles.ts+++ /dev/null@@ -1,33 +0,0 @@-import { createStaticStyles, cssVar } from '@lobehub/ui';--export const gitMenuTriggerStyles = createStaticStyles(({ css }) => ({- trigger: css`- display: inline-flex;- flex: none;- min-width: 0;-- /* The stable menu anchor must not paint behind the child's rounded chip or- overview row. Keep hover and popup-open feedback on that same surface. */- &&&[data-popup-open] {- background: transparent;- }-- /* A column host stretches the anchor for overview rows; compact composer- chips use their intrinsic width instead of 100% of the whole git group. */- && > * {- flex: 1;- min-width: 0;- }-- &[data-popup-open] > * {- background: ${cssVar.colorFillTertiary};- }-- /* Stale-first: the trigger stays in place (no layout jump) but cannot- checkout until the current probe confirms the branch. */- &[aria-disabled='true'] > * {- cursor: not-allowed;- opacity: 0.6;- }- `,-}));diff --git a/src/features/ChatInput/ControlBar/index.tsx b/src/features/ChatInput/ControlBar/index.tsxindex ea38c9cc35f..002283ac97f 100644--- a/src/features/ChatInput/ControlBar/index.tsx+++ b/src/features/ChatInput/ControlBar/index.tsx@@ -1,4 +1,5 @@-import { createStaticStyles, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import ChatInputCredits from '@/business/client/features/ChatInputCredits';@@ -16,34 +17,25 @@ import ModeSelector from './ModeSelector';import { resolveControlBarView } from './resolveControlBarView';import WorkspaceControls from './WorkspaceControls';-const styles = createStaticStyles(({ css }) => ({+const styles = stylex.create({// `flex: none` keeps the row at 28px inside the column-flex composer; without// it the bar shrinks to the compact chips' min-content height.- bar: css`- flex: none;- height: 28px;- padding-block: 0;- padding-inline: 4px;- `,+ bar: { flex: 'none', height: '28px', paddingBlock: '0', paddingInline: '4px' },// Left cluster (mode + device + working directory + git) is the variable-width// part. It shrinks first and, once its long labels have truncated as far as// they can, scrolls horizontally instead of wrapping each chip's text. The// scrollbar is hidden — trackpad / wheel still works.- leftGroup: css`- scrollbar-width: none;- overflow: auto hidden;- flex: 1;- min-width: 0;-- &::-webkit-scrollbar {- display: none;- }- `,+ leftGroup: {+ 'scrollbarWidth': 'none',+ 'overflowX': 'auto',+ 'overflowY': 'hidden',+ 'flex': '1',+ 'minWidth': '0',+ '::-webkit-scrollbar': { display: 'none' },+ },// Right cluster (approval mode + context window) stays pinned and intact.- rightGroup: css`- flex: none;- `,-}));+ rightGroup: { flex: 'none' },+});interface ControlBarSkeletonProps {/** Mirror the right-pinned context-window pill only when the loaded bar renders it. */@@ -57,7 +49,13 @@ interface ControlBarSkeletonProps {* does not move when the real controls replace it.*/export const ControlBarSkeleton = ({ showContextWindow }: ControlBarSkeletonProps) => (- <Flexbox aria-busy horizontal align={'center'} className={styles.bar} justify={'space-between'}>+ <Flexbox+ aria-busy+ horizontal+ align={'center'}+ className={stylex.props(styles.bar).className}+ justify={'space-between'}+ ><SkeletonBar height={22} radius={4} width={68} />{showContextWindow && <SkeletonBar height={22} radius={4} width={88} />}</Flexbox>@@ -85,14 +83,29 @@ const ControlBar = memo(() => {if (view === 'skeleton') return <ControlBarSkeleton showContextWindow={showContextWindow} />;return (- <Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.bar).className}+ justify={'space-between'}+ >{/* Left: chat-mode switcher + (agent-only) execution device + working directory */}- <Flexbox horizontal align={'center'} className={styles.leftGroup} gap={4}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.leftGroup).className}+ gap={4}+ ><ModeSelector />{isAgentRuntimeMode && <WorkspaceControls agentId={agentId} />}</Flexbox>- <Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.rightGroup).className}+ gap={4}+ ><ChatInputCredits />{isAgentRuntimeMode && <ApprovalMode />}{showContextWindow && <ContextWindow />}diff --git a/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts b/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.tsindex 7f505fee0b0..87b1fa61a61 100644--- a/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts+++ b/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts@@ -1,4 +1,5 @@-import { createStaticStyles, cssVar } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';/*** The composer's working-directory chip — for a run on a machine and for one in@@ -6,41 +7,33 @@ import { createStaticStyles, cssVar } from '@lobehub/ui';* and are read as one control: a second copy drifts (a darker hover here, a* wider gap there) into looking like a different kind of thing.*/-export const workingDirectoryChipStyles = createStaticStyles(({ css }) => ({- chip: css`- cursor: pointer;-- display: flex;- flex: none;- gap: 6px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;-- transition: background 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,+export const workingDirectoryChipStyles = stylex.create({+ chip: {+ cursor: 'pointer',+ display: 'flex',+ flex: 'none',+ gap: '6px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '4px',+ borderRadius: '4px',+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ transition: 'background 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ label: {+ overflow: 'hidden',+ maxWidth: '140px',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },/** Shown, not picked — e.g. a directory owned by the conversation's project. */- readonly: css`- cursor: default;-- &:hover {- background: transparent;- }- `,- label: css`- overflow: hidden;- max-width: 140px;- text-overflow: ellipsis;- white-space: nowrap;- `,-}));+ readonly: {+ cursor: 'default',+ backgroundColor: { 'default': null, ':hover': 'transparent' },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+});diff --git a/src/features/CommunitySkillDetail/Details/Info/index.tsx b/src/features/CommunitySkillDetail/Details/Info/index.tsxindex 2c8df44af21..3e9fccb15ea 100644--- a/src/features/CommunitySkillDetail/Details/Info/index.tsx+++ b/src/features/CommunitySkillDetail/Details/Info/index.tsx@@ -1,6 +1,9 @@'use client';-import { Block, createStaticStyles, responsive } from '@lobehub/ui';+import { Block } 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 { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -13,78 +16,54 @@ import { isGitHubUrl } from './isGitHubUrl';const EMPTY_VALUE = '--';-const styles = createStaticStyles(({ css, cssVar }) => ({- card: css`- overflow: hidden;- border-color: ${cssVar.colorBorderSecondary} !important;- border-radius: 16px !important;- background: ${cssVar.colorBgContainer} !important;- `,- label: css`- font-size: 14px;- font-weight: 500;- line-height: 1.35;- color: ${cssVar.colorTextDescription};-- ${responsive.sm} {- font-size: 13px;- }- `,- row: css`- display: grid;- grid-template-columns: minmax(120px, 1fr) minmax(0, 2fr);- align-items: center;-- min-height: 58px;- padding-block: 0;- padding-inline: 24px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};-- &:last-child {- border-block-end: 0;- }-- ${responsive.sm} {- grid-template-columns: 1fr;- gap: 6px;- align-items: flex-start;-- min-height: 56px;- padding-block: 14px;- padding-inline: 18px;- }- `,- sourceLink: css`- display: inline-flex;- gap: 4px;- align-items: center;- justify-content: flex-end;-- color: ${cssVar.colorLink};-- &:hover {- color: ${cssVar.colorLinkHover};- }- `,- value: css`- min-width: 0;-- font-size: 14px;- font-weight: 600;- font-variant-numeric: tabular-nums;- line-height: 1.35;- color: ${cssVar.colorText};- text-align: end;- word-break: break-word;-- ${responsive.sm} {- text-align: start;- }- `,- valueMuted: css`- color: ${cssVar.colorTextDescription};- `,-}));+const styles = stylex.create({+ card: {+ overflow: 'hidden',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: '16px',+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ label: {+ fontSize: { default: '14px', [media.sm]: '13px' },+ fontWeight: 500,+ lineHeight: 1.35,+ color: cssVar.colorTextDescription,+ },+ row: {+ display: 'grid',+ gridTemplateColumns: {+ default: 'minmax(120px, 1fr) minmax(0, 2fr)',+ [media.sm]: '1fr',+ },+ gap: { default: null, [media.sm]: '6px' },+ alignItems: { default: 'center', [media.sm]: 'flex-start' },+ minHeight: { default: '58px', [media.sm]: '56px' },+ paddingBlock: { default: '0', [media.sm]: '14px' },+ paddingInline: { default: '24px', [media.sm]: '18px' },+ borderBlockEndWidth: { 'default': '1px', ':last-child': '0' },+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ },+ sourceLink: {+ display: 'inline-flex',+ gap: '4px',+ alignItems: 'center',+ justifyContent: 'flex-end',+ color: { 'default': cssVar.colorLink, ':hover': cssVar.colorLinkHover },+ },+ value: {+ minWidth: 0,+ fontSize: '14px',+ fontWeight: 600,+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 1.35,+ color: cssVar.colorText,+ textAlign: { default: 'end', [media.sm]: 'start' },+ wordBreak: 'break-word',+ },+ valueMuted: { color: cssVar.colorTextDescription },+});const isEmptyValue = (value: ReactNode) => value === undefined || value === null || value === '';@@ -92,9 +71,9 @@ const InfoRow = memo<{ label: ReactNode; value: ReactNode }>(({ label, value })const empty = isEmptyValue(value);return (- <div className={styles.row}>- <span className={styles.label}>{label}</span>- <div className={[styles.value, empty ? styles.valueMuted : ''].filter(Boolean).join(' ')}>+ <div {...stylex.props(styles.row)}>+ <span {...stylex.props(styles.label)}>{label}</span>+ <div {...stylex.props(styles.value, empty && styles.valueMuted)}>{empty ? EMPTY_VALUE : value}</div></div>@@ -129,7 +108,12 @@ const Info = memo(() => {const updatedDate = selectedVersion?.createdAt || updatedAt || createdAt;const sourceValue = sourceUrl ? (- <a className={styles.sourceLink} href={sourceUrl} rel={'noopener noreferrer'} target={'_blank'}>+ <a+ {...stylex.props(styles.sourceLink)}+ href={sourceUrl}+ rel={'noopener noreferrer'}+ target={'_blank'}+ >{isGitHubSource ? t('skills.details.info.viewOnGithub') : t('skills.details.info.viewSource')}{' '}↗</a>@@ -198,7 +182,12 @@ const Info = memo(() => {];return (- <Block className={styles.card} paddingBlock={0} paddingInline={0} variant={'outlined'}>+ <Block+ className={stylex.props(styles.card).className}+ paddingBlock={0}+ paddingInline={0}+ variant={'outlined'}+ >{rows.map((row) => (<InfoRow key={row.key} label={row.label} value={row.value} />))}diff --git a/src/features/CommunitySkillDetail/Details/Install/Platform.module.css b/src/features/CommunitySkillDetail/Details/Install/Platform.module.cssnew file mode 100644index 00000000000..1b9659a4aba--- /dev/null+++ b/src/features/CommunitySkillDetail/Details/Install/Platform.module.css@@ -0,0 +1,3 @@+.lite pre {+ padding: 12px !important;+}diff --git a/src/features/CommunitySkillDetail/Details/Install/Platform.tsx b/src/features/CommunitySkillDetail/Details/Install/Platform.tsxindex 5a87bc2a5d6..b8bb107aacc 100644--- a/src/features/CommunitySkillDetail/Details/Install/Platform.tsx+++ b/src/features/CommunitySkillDetail/Details/Install/Platform.tsx@@ -6,8 +6,6 @@ import {Avatar,Block,Button,- createStaticStyles,- cx,Divider,Flexbox,Highlighter,@@ -28,6 +26,7 @@ import { useChatStore } from '@/store/chat';import { useDetailActionContext } from '../../DetailProvider';import { getSkillInstructionsUrl } from './getSkillInstructionsUrl';+import styles from './Platform.module.css';import VsCodeIcon from './VsCodeIcon';const Title = ({ children }: { children?: React.ReactNode }) => (@@ -47,14 +46,6 @@ enum PlatformType {VsCode = 'vscode',}-export const styles = createStaticStyles(({ css }) => ({- lite: css`- pre {- padding: 12px !important;- }- `,-}));-interface PlatformProps {downloadUrl?: string;expandCodeByDefault?: boolean;@@ -255,7 +246,7 @@ const Platform = memo<PlatformProps>(<HighlighterfullFeaturedwrap- className={cx(lite && styles.lite)}+ className={lite ? styles.lite : undefined}defaultExpand={expandCodeByDefault ?? false}fileName={'Agent prompt'}language={'bash'}@@ -314,7 +305,7 @@ const Platform = memo<PlatformProps>({lite && <Divider dashed />}<HighlighterfullFeatured- className={cx(lite && styles.lite)}+ className={lite ? styles.lite : undefined}defaultExpand={expandCodeByDefault ?? false}fileName={t('skills.details.sidebar.installCommand')}language={'bash'}@@ -326,7 +317,7 @@ const Platform = memo<PlatformProps>({lite && <Divider dashed />}<HighlighterfullFeatured- className={cx(lite && styles.lite)}+ className={lite ? styles.lite : undefined}defaultExpand={false}fileName={t('skills.details.sidebar.directoryLayout')}language={'text'}diff --git a/src/features/CommunitySkillDetail/Details/Install/index.tsx b/src/features/CommunitySkillDetail/Details/Install/index.tsxindex 757c09f7b86..38f33dceb99 100644--- a/src/features/CommunitySkillDetail/Details/Install/index.tsx+++ b/src/features/CommunitySkillDetail/Details/Install/index.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, Flexbox, MaterialFileTypeIcon, Text } from '@lobehub/ui';+import { Flexbox, MaterialFileTypeIcon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -9,22 +11,24 @@ import { formatSize } from '@/utils/format';import { useDetailContext } from '../../DetailProvider';import Platform from './Platform';-const styles = createStaticStyles(({ css, cssVar }) => ({- filesCard: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 16px;- background: ${cssVar.colorBgContainer};- `,- sectionLabel: css`- margin: 0;-- font-size: 20px;- font-weight: 700;- line-height: 1.25;- color: ${cssVar.colorText};- `,-}));+const styles = stylex.create({+ filesCard: {+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: '16px',+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ sectionLabel: {+ margin: '0',+ fontSize: '20px',+ fontWeight: 700,+ lineHeight: 1.25,+ color: cssVar.colorText,+ },+});const Install = memo<{ mobile?: boolean }>(({ mobile }) => {const { identifier, downloadUrl, resources, content } = useDetailContext();@@ -47,10 +51,10 @@ const Install = memo<{ mobile?: boolean }>(({ mobile }) => {/>{entries.length > 0 && (<Flexbox gap={12}>- <Text as={'h2'} className={styles.sectionLabel}>+ <Text as={'h2'} className={stylex.props(styles.sectionLabel).className}>{t('skills.details.installation.filesIncluded')}</Text>- <div className={styles.filesCard}>+ <div {...stylex.props(styles.filesCard)}>{entries.map(([name, meta], index) => (<Flexboxhorizontaldiff --git a/src/features/CommunitySkillDetail/Details/Nav.tsx b/src/features/CommunitySkillDetail/Details/Nav.tsxindex 9a605473c46..5c67fe5baca 100644--- a/src/features/CommunitySkillDetail/Details/Nav.tsx+++ b/src/features/CommunitySkillDetail/Details/Nav.tsx@@ -1,90 +1,73 @@'use client';-import { createStaticStyles } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { SkillNavKey } from '../types';-const styles = createStaticStyles(({ css, cssVar }) => ({- item: css`- cursor: pointer;-- position: relative;-- height: 42px;- padding-block: 0;- padding-inline: 12px;- border: 0;- border-radius: 8px;-- font: inherit;- font-size: 15px;- font-weight: 500;- color: ${cssVar.colorTextSecondary};-- background: transparent;-- transition:- background 0.2s ease,- color 0.2s ease;-- &::after {- content: '';-- position: absolute;- z-index: 1;- inset-block-end: 0;- inset-inline: 12px;- transform: scaleX(0.4);-- height: 2px;- border-radius: 999px;-- opacity: 0;- background: ${cssVar.colorPrimary};-- transition:- opacity 0.2s ease,- transform 0.2s ease;- }-- &:hover {- color: ${cssVar.colorText};- background: color-mix(in srgb, ${cssVar.colorFillQuaternary} 70%, transparent);- }-- &:focus-visible {- outline: 2px solid ${cssVar.colorInfo};- outline-offset: 2px;- }- `,- itemActive: css`- font-weight: 700;- color: ${cssVar.colorText};- background: color-mix(in srgb, ${cssVar.colorFillQuaternary} 76%, transparent);-- &::after {- transform: scaleX(1);- opacity: 1;- }- `,- nav: css`- scrollbar-width: none;-- overflow-x: auto;- display: flex;- gap: 8px;-- width: 100%;- padding-block-end: 8px;- border-block-end: 1px solid color-mix(in srgb, ${cssVar.colorBorderSecondary} 88%, transparent);-- &::-webkit-scrollbar {- display: none;- }- `,-}));+const styles = stylex.create({+ item: {+ 'cursor': 'pointer',+ 'position': 'relative',+ 'height': '42px',+ 'paddingBlock': '0',+ 'paddingInline': '12px',+ 'borderStyle': 'none',+ 'borderRadius': '8px',+ 'font': 'inherit',+ 'fontSize': '15px',+ 'fontWeight': 500,+ 'color': { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ 'backgroundColor': {+ 'default': 'transparent',+ ':hover': `color-mix(in srgb, ${cssVar.colorFillQuaternary} 70%, transparent)`,+ },+ 'backgroundImage': { 'default': 'none', ':hover': 'none' },+ 'transition': 'background 0.2s ease, color 0.2s ease',+ 'outlineWidth': { 'default': null, ':focus-visible': '2px' },+ 'outlineStyle': { 'default': null, ':focus-visible': 'solid' },+ 'outlineColor': { 'default': null, ':focus-visible': cssVar.colorInfo },+ 'outlineOffset': { 'default': null, ':focus-visible': '2px' },+ '::after': {+ content: "''",+ position: 'absolute',+ zIndex: 1,+ insetBlockEnd: '0',+ insetInline: '12px',+ transform: 'scaleX(0.4)',+ height: '2px',+ borderRadius: '999px',+ opacity: 0,+ backgroundColor: cssVar.colorPrimary,+ backgroundImage: 'none',+ transition: 'opacity 0.2s ease, transform 0.2s ease',+ },+ },+ itemActive: {+ 'fontWeight': 700,+ 'color': cssVar.colorText,+ 'backgroundColor': {+ 'default': `color-mix(in srgb, ${cssVar.colorFillQuaternary} 76%, transparent)`,+ ':hover': `color-mix(in srgb, ${cssVar.colorFillQuaternary} 70%, transparent)`,+ },+ 'backgroundImage': 'none',+ '::after': { transform: 'scaleX(1)', opacity: 1 },+ },+ nav: {+ 'scrollbarWidth': 'none',+ 'overflowX': 'auto',+ 'display': 'flex',+ 'gap': '8px',+ 'width': '100%',+ 'paddingBlockEnd': '8px',+ 'borderBlockEndWidth': '1px',+ 'borderBlockEndStyle': 'solid',+ 'borderBlockEndColor': `color-mix(in srgb, ${cssVar.colorBorderSecondary} 88%, transparent)`,+ '::-webkit-scrollbar': { display: 'none' },+ },+});const Nav = memo<{activeTab?: SkillNavKey;@@ -100,14 +83,12 @@ const Nav = memo<{];return (- <div className={styles.nav}>+ <div {...stylex.props(styles.nav)}>{items.map((item) => (<buttonkey={item.key}type={'button'}- className={[styles.item, activeTab === item.key ? styles.itemActive : '']- .filter(Boolean)- .join(' ')}+ {...stylex.props(styles.item, activeTab === item.key && styles.itemActive)}onClick={() => setActiveTab?.(item.key)}>{item.label}diff --git a/src/features/CommunitySkillDetail/Details/Overview/Overview.module.css b/src/features/CommunitySkillDetail/Details/Overview/Overview.module.cssnew file mode 100644index 00000000000..9edbb735b76--- /dev/null+++ b/src/features/CommunitySkillDetail/Details/Overview/Overview.module.css@@ -0,0 +1,3 @@+.summary p {+ margin-block: 0 0.8em;+}diff --git a/src/features/CommunitySkillDetail/Details/Overview/RelatedSkillCard.tsx b/src/features/CommunitySkillDetail/Details/Overview/RelatedSkillCard.tsxindex 00ec5c4e80c..718e17ff243 100644--- a/src/features/CommunitySkillDetail/Details/Overview/RelatedSkillCard.tsx+++ b/src/features/CommunitySkillDetail/Details/Overview/RelatedSkillCard.tsx@@ -1,6 +1,8 @@'use client';-import { Avatar, Block, createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo, useCallback } from 'react';import urlJoin from 'url-join';@@ -10,55 +12,38 @@ import { type DiscoverSkillItem } from '@/types/discover';import { useDetailActionContext } from '../../DetailProvider';-const styles = createStaticStyles(({ css, cssVar }) => ({- card: css`- border-color: ${cssVar.colorBorderSecondary} !important;- border-radius: 16px !important;- background: ${cssVar.colorBgContainer} !important;- transition:- transform 0.2s ease,- border-color 0.2s ease,- box-shadow 0.2s ease;-- &:hover {- transform: translateY(-1px);- border-color: ${cssVar.colorBorder} !important;- box-shadow: 0 10px 28px color-mix(in srgb, ${cssVar.colorText} 8%, transparent);- }-- &:active {- transform: translateY(0);- }- `,- meta: css`- overflow: hidden;-- min-width: 0;-- font-size: 13px;- color: ${cssVar.colorTextDescription};- white-space: nowrap;- `,- metaAuthor: css`- overflow: hidden;- flex: 1 1 auto;-- min-width: 0;-- text-overflow: ellipsis;- white-space: nowrap;- `,- metaRating: css`- flex: none;- font-variant-numeric: tabular-nums;- white-space: nowrap;- `,- name: css`- font-size: 14px;- font-weight: 600;- line-height: 1.3;- `,-}));+const styles = stylex.create({+ card: {+ borderColor: { 'default': cssVar.colorBorderSecondary, ':hover': cssVar.colorBorder },+ borderRadius: '16px',+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ transform: { 'default': null, ':hover': 'translateY(-1px)', ':active': 'translateY(0)' },+ boxShadow: {+ 'default': null,+ ':hover': `0 10px 28px color-mix(in srgb, ${cssVar.colorText} 8%, transparent)`,+ },+ transition: 'transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease',+ },+ meta: {+ overflow: 'hidden',+ minWidth: 0,+ fontSize: '13px',+ color: cssVar.colorTextDescription,+ whiteSpace: 'nowrap',+ },+ metaAuthor: {+ overflow: 'hidden',+ flexGrow: '1',+ flexShrink: '1',+ flexBasis: 'auto',+ minWidth: 0,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ metaRating: { flex: 'none', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },+ name: { fontSize: '14px', fontWeight: 600, lineHeight: 1.3 },+});const RelatedSkillCard = memo<DiscoverSkillItem>(({ name, identifier, author, icon, ratingAvg }) => {@@ -79,7 +64,7 @@ const RelatedSkillCard = memo<DiscoverSkillItem>(return (<Blockclickable- className={styles.card}+ className={stylex.props(styles.card).className}paddingBlock={12}paddingInline={14}variant={'outlined'}@@ -88,13 +73,23 @@ const RelatedSkillCard = memo<DiscoverSkillItem>(<Flexbox horizontal align={'center'} gap={12}><Avatar avatar={icon || name || identifier} size={40} style={{ flex: 'none' }} /><Flexbox flex={1} gap={2} style={{ minWidth: 0, overflow: 'hidden' }}>- <Text ellipsis className={styles.name}>+ <Text ellipsis className={stylex.props(styles.name).className}>{name || identifier}</Text>- <Flexbox horizontal align={'center'} className={styles.meta} gap={4}>- {author && <span className={styles.metaAuthor}>{author}</span>}+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.meta).className}+ gap={4}+ >+ {author && <span {...stylex.props(styles.metaAuthor)}>{author}</span>}{displayRating && (- <Flexbox horizontal align={'center'} className={styles.metaRating} gap={3}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.metaRating).className}+ gap={3}+ >{author && <span>·</span>}<Rate gap={1} size={10} value={displayRating} /><span>{displayRating.toFixed(1)}</span>diff --git a/src/features/CommunitySkillDetail/Details/Overview/index.tsx b/src/features/CommunitySkillDetail/Details/Overview/index.tsxindex 2d533b70a9e..39acf7bf4ad 100644--- a/src/features/CommunitySkillDetail/Details/Overview/index.tsx+++ b/src/features/CommunitySkillDetail/Details/Overview/index.tsx@@ -4,16 +4,16 @@ import {Accordion,Block,Button,- createStaticStyles,- cssVar,Flexbox,Icon,Markdown,- responsive,ScrollShadow,Tag,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 { ChevronRight } from 'lucide-react';import qs from 'query-string';import { memo, useCallback } from 'react';@@ -23,58 +23,39 @@ import PublishedTime from '@/components/PublishedTime';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useDiscoverStore } from '@/store/discover';import { skillSelectors } from '@/store/discover/selectors';+import { sx } from '@/styles/sx';import { useDetailActionContext, useDetailContext } from '../../DetailProvider';+import moduleStyles from './Overview.module.css';import RelatedSkillCard from './RelatedSkillCard';-const styles = createStaticStyles(({ css, cssVar }) => ({- relatedGrid: css`- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: 12px;-- ${responsive.sm} {- grid-template-columns: 1fr;- }- `,- sectionLabel: css`- margin: 0;-- font-size: 20px;- font-weight: 700;- line-height: 1.25;- color: ${cssVar.colorText};-- ${responsive.sm} {- font-size: 18px;- }- `,- more: css`- display: flex;- align-items: center;- color: ${cssVar.colorTextSecondary};- `,- summary: css`- font-size: 15px;- line-height: 1.7;- color: ${cssVar.colorTextSecondary};-- p {- margin-block: 0 0.8em;- }- `,- tag: css`- border-color: color-mix(in srgb, ${cssVar.colorBorderSecondary} 84%, transparent) !important;- border-radius: 8px !important;- `,- versionCard: css`- border-color: color-mix(in srgb, ${cssVar.colorBorderSecondary} 88%, transparent) !important;- border-radius: 8px !important;- `,-}));+const styles = stylex.create({+ relatedGrid: {+ display: 'grid',+ gridTemplateColumns: { default: 'repeat(2, minmax(0, 1fr))', [media.sm]: '1fr' },+ gap: '12px',+ },+ sectionLabel: {+ margin: '0',+ fontSize: { default: '20px', [media.sm]: '18px' },+ fontWeight: 700,+ lineHeight: 1.25,+ color: cssVar.colorText,+ },+ more: { display: 'flex', alignItems: 'center', color: cssVar.colorTextSecondary },+ summary: { fontSize: '15px', lineHeight: 1.7, color: cssVar.colorTextSecondary },+ tag: {+ borderColor: `color-mix(in srgb, ${cssVar.colorBorderSecondary} 84%, transparent)`,+ borderRadius: '8px',+ },+ versionCard: {+ borderColor: `color-mix(in srgb, ${cssVar.colorBorderSecondary} 88%, transparent)`,+ borderRadius: '8px',+ },+});const SectionLabel = memo<{ children: string }>(({ children }) => (- <Text as={'h2'} className={styles.sectionLabel}>+ <Text as={'h2'} className={stylex.props(styles.sectionLabel).className}>{children}</Text>));@@ -114,7 +95,7 @@ const Overview = memo(() => {{/* ABOUT */}<Flexbox gap={12}><SectionLabel>{t('skills.details.overview.about')}</SectionLabel>- <div className={styles.summary}>+ <div {...sx(styles.summary, moduleStyles.summary)}><Markdown variant={'chat'}>{overview?.summary || description || ''}</Markdown></div></Flexbox>@@ -145,7 +126,7 @@ const Overview = memo(() => {<SectionLabel>{t('skills.details.overview.features')}</SectionLabel><Flexbox horizontal gap={8} wrap={'wrap'}>{tags.map((tag) => (- <Tag className={styles.tag} key={tag}>+ <Tag className={stylex.props(styles.tag).className} key={tag}>{tag}</Tag>))}@@ -158,7 +139,7 @@ const Overview = memo(() => {<Flexbox gap={12}><SectionLabel>{t('skills.details.overview.whatsNew')}</SectionLabel><Block- className={styles.versionCard}+ className={stylex.props(styles.versionCard).className}gap={12}paddingBlock={16}paddingInline={16}@@ -185,7 +166,7 @@ const Overview = memo(() => {<Flexbox horizontal align={'center'} justify={'space-between'}><SectionLabel>{t('skills.details.related.listTitle')}</SectionLabel><Button- className={styles.more}+ className={stylex.props(styles.more).className}style={{ paddingInline: 6 }}type={'text'}onClick={handleMoreRelated}@@ -194,7 +175,7 @@ const Overview = memo(() => {<Icon icon={ChevronRight} /></Button></Flexbox>- <div className={styles.relatedGrid}>+ <div {...stylex.props(styles.relatedGrid)}>{related.map((item) => (<RelatedSkillCard key={item.identifier} {...item} />))}diff --git a/src/features/CommunitySkillDetail/Header.tsx b/src/features/CommunitySkillDetail/Header.tsxindex 6cb3c3a0d4e..3984e935b51 100644--- a/src/features/CommunitySkillDetail/Header.tsx+++ b/src/features/CommunitySkillDetail/Header.tsx@@ -4,16 +4,16 @@ import {Avatar,Button,confirmModal,- createStaticStyles,- cssVar,DropdownMenu,Flexbox,Icon,- responsive,Text,toast,useResponsive,} 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 { CheckCircle2, CheckIcon, ChevronDown, Trash2 } from 'lucide-react';import { memo, type ReactNode, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -32,85 +32,69 @@ import { formatShortenNumber } from '@/utils/format';import { FIRST_COMMENTS_PAGE_QUERY } from './const';import { useDetailContext } from './DetailProvider';-const styles = createStaticStyles(({ css, cssVar }) => ({- author: css`- font-weight: 500;- color: ${cssVar.colorInfo};- `,- metaDivider: css`- flex: none;-- width: 1px;- height: 12px;- margin-inline: 3px;-- background: ${cssVar.colorBorderSecondary};- `,- ratingCount: css`- font-size: 11px;- font-weight: 600;- line-height: 1.1;- color: ${cssVar.colorTextDescription};- `,- ratingValue: css`- font-size: 26px;- font-weight: 700;- font-variant-numeric: tabular-nums;- line-height: 1;- color: ${cssVar.colorText};- `,- statBlock: css`- transition: background 0.2s ease;-- &:hover {- background: color-mix(in srgb, ${cssVar.colorFillQuaternary} 74%, transparent);- }- `,- statCaption: css`- display: flex;- align-items: center;- justify-content: center;-- min-height: 14px;-- font-size: 11px;- font-weight: 500;- line-height: 1.1;- color: ${cssVar.colorTextDescription};- `,- statLabel: css`- font-size: 11px;- font-weight: 600;- color: ${cssVar.colorTextDescription};- `,- statValue: css`- font-size: 24px;- font-weight: 700;- font-variant-numeric: tabular-nums;- line-height: 1;- color: ${cssVar.colorText};- `,- statsBar: css`- overflow: hidden;- border: 1px solid color-mix(in srgb, ${cssVar.colorBorderSecondary} 88%, transparent);- border-radius: 16px;- background: ${cssVar.colorBgContainer};- `,- statsGrid: css`- display: grid;- grid-template-columns: repeat(3, minmax(0, 1fr));-- ${responsive.sm} {- grid-template-columns: repeat(2, minmax(0, 1fr));- }- `,- time: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,-}));+const styles = stylex.create({+ author: { fontWeight: 500, color: cssVar.colorInfo },+ metaDivider: {+ flex: 'none',+ width: '1px',+ height: '12px',+ marginInline: '3px',+ backgroundColor: cssVar.colorBorderSecondary,+ backgroundImage: 'none',+ },+ ratingValue: {+ fontSize: '26px',+ fontWeight: 700,+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 1,+ color: cssVar.colorText,+ },+ statBlock: {+ transition: 'background 0.2s ease',+ backgroundColor: {+ 'default': null,+ ':hover': `color-mix(in srgb, ${cssVar.colorFillQuaternary} 74%, transparent)`,+ },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ statCaption: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ minHeight: '14px',+ fontSize: '11px',+ fontWeight: 500,+ lineHeight: 1.1,+ color: cssVar.colorTextDescription,+ },+ statLabel: { fontSize: '11px', fontWeight: 600, color: cssVar.colorTextDescription },+ statValue: {+ fontSize: '24px',+ fontWeight: 700,+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 1,+ color: cssVar.colorText,+ },+ statsBar: {+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: `color-mix(in srgb, ${cssVar.colorBorderSecondary} 88%, transparent)`,+ borderRadius: '16px',+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ statsGrid: {+ display: 'grid',+ gridTemplateColumns: {+ default: 'repeat(3, minmax(0, 1fr))',+ [media.sm]: 'repeat(2, minmax(0, 1fr))',+ },+ },+ time: { fontSize: '12px', color: cssVar.colorTextDescription },+});-const MetaDivider = () => <span aria-hidden className={styles.metaDivider} />;+const MetaDivider = () => <span aria-hidden {...stylex.props(styles.metaDivider)} />;const StatBlock = memo<{bordered?: boolean;@@ -121,7 +105,7 @@ const StatBlock = memo<{return (<Flexboxalign={'center'}- className={styles.statBlock}+ className={stylex.props(styles.statBlock).className}flex={1}gap={5}justify={'center'}@@ -132,9 +116,9 @@ const StatBlock = memo<{textAlign: 'center',}}>- <div className={styles.statLabel}>{label}</div>- <div className={styles.statValue}>{value}</div>- <div aria-hidden={!caption} className={styles.statCaption}>+ <div {...stylex.props(styles.statLabel)}>{label}</div>+ <div {...stylex.props(styles.statValue)}>{value}</div>+ <div aria-hidden={!caption} {...stylex.props(styles.statCaption)}>{caption}</div></Flexbox>@@ -269,7 +253,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {}): t('skills.details.header.stats.rating'),statKey: 'rating',- value: <div className={styles.ratingValue}>{displayRatingAverage.toFixed(1)}</div>,+ value: <div {...stylex.props(styles.ratingValue)}>{displayRatingAverage.toFixed(1)}</div>,}: undefined,github?.stars@@ -344,7 +328,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {>{author?.url ? (<a- className={styles.author}+ {...stylex.props(styles.author)}href={author.url}rel={'noopener noreferrer'}target={'_blank'}@@ -352,7 +336,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {{author.name}</a>) : (- <span className={styles.author}>{author?.name}</span>+ <span {...stylex.props(styles.author)}>{author?.name}</span>)}{isValidated && (<Icon@@ -374,7 +358,7 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {<><MetaDivider /><PublishedTime- className={styles.time}+ className={stylex.props(styles.time).className}date={(updatedAt || createdAt) as string}template={'MMM DD, YYYY'}/>@@ -385,9 +369,9 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {<InstallButton identifier={identifier} name={name} /></Flexbox>{stats.length > 0 && (- <div className={styles.statsBar} style={{ width: '100%' }}>+ <div className={stylex.props(styles.statsBar).className} style={{ width: '100%' }}><div- className={styles.statsGrid}+ className={stylex.props(styles.statsGrid).className}style={{gridTemplateColumns: mobile ? undefined : `repeat(${stats.length}, minmax(0, 1fr))`,}}diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsxindex dff4d063a77..c342714f46b 100644--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx@@ -1,8 +1,9 @@'use client';import { LayersEnum } from '@lobechat/types';-import { createStaticStyles, Icon, toast } from '@lobehub/ui';+import { Icon, toast } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';+import * as stylex from '@stylexjs/stylex';import type { LucideIcon } from 'lucide-react';import { Brain, ClipboardCheck } from 'lucide-react';import { memo, useCallback, useRef, useState } from 'react';@@ -21,16 +22,15 @@ import { useChatStore } from '@/store/chat';import type { AgentSignalReceiptView } from '../hooks/useAgentSignalReceipts';-const styles = createStaticStyles(({ css }) => ({- list: css`- display: flex;- flex-direction: column;- gap: 8px;-- width: 100%;- margin-block-start: 8px;- `,-}));+const styles = stylex.create({+ list: {+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ width: '100%',+ marginBlockStart: '8px',+ },+});const RECEIPT_LUCIDE_ICON_BY_KIND = {memory: Brain,@@ -316,7 +316,7 @@ const AgentSignalReceiptList = memo<AgentSignalReceiptListProps>(({ receipts })// TODO: Migrate this temporary receipt UI into the final Agent Signal feedback surface.return (- <div className={styles.list}>+ <div {...stylex.props(styles.list)}>{receipts.map((receipt) => (<AgentSignalReceiptItemkey={receipt.id}diff --git a/src/features/Conversation/ChatList/components/BackBottom/index.tsx b/src/features/Conversation/ChatList/components/BackBottom/index.tsxindex 5f118768886..d7d90fd0f7f 100644--- a/src/features/Conversation/ChatList/components/BackBottom/index.tsx+++ b/src/features/Conversation/ChatList/components/BackBottom/index.tsx@@ -1,4 +1,5 @@-import { ActionIcon, cx } from '@lobehub/ui';+import { ActionIcon } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { ArrowDownIcon } from 'lucide-react';import { lazy, memo, Suspense } from 'react';import { useTranslation } from 'react-i18next';@@ -39,7 +40,7 @@ const BackBottom = memo<BackBottomProps>(<ActionIconglass- className={cx(styles.container, visible && styles.visible)}+ className={stylex.props(styles.container, visible && styles.visible).className}icon={ArrowDownIcon}style={bottomOffset ? { insetBlockEnd: 16 + bottomOffset } : undefined}title={t('backToBottom')}diff --git a/src/features/Conversation/ChatList/components/BackBottom/style.ts b/src/features/Conversation/ChatList/components/BackBottom/style.tsindex 0cd68868e0f..6e84c9effa5 100644--- a/src/features/Conversation/ChatList/components/BackBottom/style.ts+++ b/src/features/Conversation/ChatList/components/BackBottom/style.ts@@ -1,24 +1,22 @@-import { createStaticStyles, cx, lobeStaticStylish } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css, cssVar }) => ({- container: cx(- lobeStaticStylish.blur,- css`- pointer-events: none;-- position: absolute;- z-index: 50;- inset-block-end: 16px;- inset-inline-end: 16px;- transform: translateY(16px);-- opacity: 0;- background: color-mix(in srgb, ${cssVar.colorBgElevated} 50%, transparent) !important;- `,- ),- visible: css`- pointer-events: all;- transform: translateY(0);- opacity: 1;- `,-}));+export const styles = stylex.create({+ container: {+ pointerEvents: 'none',+ position: 'absolute',+ zIndex: 50,+ insetBlockEnd: '16px',+ insetInlineEnd: '16px',+ transform: 'translateY(16px)',+ opacity: 0,+ backdropFilter: 'saturate(150%) blur(10px)',+ backgroundColor: `color-mix(in srgb, ${cssVar.colorBgElevated} 50%, transparent)`,+ backgroundImage: 'none',+ },+ visible: {+ pointerEvents: 'all',+ transform: 'translateY(0)',+ opacity: 1,+ },+});diff --git a/src/features/Conversation/ChatList/components/RefreshError.tsx b/src/features/Conversation/ChatList/components/RefreshError.tsxindex a459b1e00c5..7fc66bef361 100644--- a/src/features/Conversation/ChatList/components/RefreshError.tsx+++ b/src/features/Conversation/ChatList/components/RefreshError.tsx@@ -1,24 +1,28 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';-const styles = createStaticStyles(({ css }) => ({- row: css`- flex: none;-- width: 100%;- min-height: 40px;- padding-block: 2px 4px;- padding-inline: 12px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};-- background: ${cssVar.colorBgContainer};- `,-}));+const styles = stylex.create({+ row: {+ flex: 'none',+ width: '100%',+ minHeight: '40px',+ paddingBlockStart: '2px',+ paddingBlockEnd: '4px',+ paddingInline: '12px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+});interface RefreshErrorProps {error: unknown;@@ -34,7 +38,7 @@ export const RefreshError = memo<RefreshErrorProps>(({ error, onRetry, retryinghorizontalalign={'center'}aria-live={'polite'}- className={styles.row}+ className={stylex.props(styles.row).className}justify={'center'}role={'status'}>diff --git a/src/features/Conversation/Messages/AgentCouncil/components/ScrollShadowWithButton.tsx b/src/features/Conversation/Messages/AgentCouncil/components/ScrollShadowWithButton.tsxindex ff1d3fefbf2..bdd44a285a5 100644--- a/src/features/Conversation/Messages/AgentCouncil/components/ScrollShadowWithButton.tsx+++ b/src/features/Conversation/Messages/AgentCouncil/components/ScrollShadowWithButton.tsx@@ -1,40 +1,32 @@import { type FlexboxProps } from '@lobehub/ui';-import { Button, createStaticStyles, cx, Flexbox, ScrollShadow } from '@lobehub/ui';+import { Button, Flexbox, ScrollShadow } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronLeft, ChevronRight } from 'lucide-react';import { memo, useCallback, useEffect, useRef, useState } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => ({- button: css`- position: absolute;- z-index: 10;- inset-block-start: 50%;- transform: translateY(-50%);-- color: ${cssVar.colorTextSecondary};-- opacity: 0;-- transition: opacity ${cssVar.motionDurationMid} ${cssVar.motionEaseInOut};-- &:hover {- border-color: ${cssVar.colorBorder} !important;- box-shadow: ${cssVar.boxShadowTertiary} !important;- }- `,- container: css`- position: relative;-- &:hover .scroll-button {- opacity: 1;- }- `,- leftButton: css`- inset-inline-start: 16px;- `,- rightButton: css`- inset-inline-end: 16px;- `,-}));+const styles = stylex.create({+ button: {+ position: 'absolute',+ zIndex: 10,+ insetBlockStart: '50%',+ transform: 'translateY(-50%)',+ color: cssVar.colorTextSecondary,+ opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 },+ transition: `opacity ${cssVar.motionDurationMid} ${cssVar.motionEaseInOut}`,+ borderColor: { 'default': null, ':hover': cssVar.colorBorder },+ boxShadow: { 'default': null, ':hover': cssVar.boxShadowTertiary },+ },+ container: {+ position: 'relative',+ },+ leftButton: {+ insetInlineStart: '16px',+ },+ rightButton: {+ insetInlineEnd: '16px',+ },+});const ScrollShadowWithButton = memo<FlexboxProps>(({ children, ...rest }) => {const scrollRef = useRef<HTMLDivElement>(null);@@ -76,10 +68,15 @@ const ScrollShadowWithButton = memo<FlexboxProps>(({ children, ...rest }) => {}, []);return (- <Flexbox horizontal className={styles.container} width={'100%'} {...rest}>+ <Flexbox+ horizontal+ className={stylex.props(styles.container, stylex.defaultMarker()).className}+ width={'100%'}+ {...rest}+ >{canScrollLeft && (<Button- className={cx(styles.button, styles.leftButton, 'scroll-button')}+ className={stylex.props(styles.button, styles.leftButton).className}icon={ChevronLeft}shape={'circle'}type={'default'}@@ -99,7 +96,7 @@ const ScrollShadowWithButton = memo<FlexboxProps>(({ children, ...rest }) => {</ScrollShadow>{canScrollRight && (<Button- className={cx(styles.button, styles.rightButton, 'scroll-button')}+ className={stylex.props(styles.button, styles.rightButton).className}icon={ChevronRight}shape={'circle'}type={'default'}diff --git a/src/features/Conversation/Messages/Assistant/components/InterruptedHint.tsx b/src/features/Conversation/Messages/Assistant/components/InterruptedHint.tsxindex 0c8a93efdca..84ee4386f0c 100644--- a/src/features/Conversation/Messages/Assistant/components/InterruptedHint.tsx+++ b/src/features/Conversation/Messages/Assistant/components/InterruptedHint.tsx@@ -1,4 +1,5 @@-import { createStaticStyles } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -7,13 +8,9 @@ import { operationSelectors } from '@/store/chat/selectors';import { contextSelectors, useConversationStore } from '../../../store';-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- padding-block: 4px;- font-size: 12px;- color: ${cssVar.colorTextTertiary};- `,-}));+const styles = stylex.create({+ container: { paddingBlock: '4px', fontSize: '12px', color: cssVar.colorTextTertiary },+});const InterruptedHint = memo(() => {const { t } = useTranslation('chat');@@ -23,7 +20,7 @@ const InterruptedHint = memo(() => {if (handingOff) return null;return (- <div className={styles.container}>+ <div {...stylex.props(styles.container)}>{t('messageAction.interrupted')} · {t('messageAction.interruptedHint')}</div>);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsxindex cdea5f24307..132bd2da406 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx@@ -1,7 +1,9 @@import { registerPendingHotkeyCard } from '@lobechat/shared-tool-ui/pending-hotkeys';import type { BuiltinRememberApproval, DynamicInterventionResolver } from '@lobechat/types';import { safeParseJSON } from '@lobechat/utils';-import { Button, createStaticStyles, cx, Flexbox } from '@lobehub/ui';+import { Button, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { CircleStop, CornerDownLeft } from 'lucide-react';import type { KeyboardEvent as ReactKeyboardEvent } from 'react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';@@ -60,105 +62,79 @@ interface ApprovalActionsProps {type Choice = ApprovalChoice;-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- width: 100%;- `,- footer: css`- display: flex;- gap: 8px;- align-items: center;- justify-content: flex-end;-- margin-block-start: 8px;- `,- number: css`- flex-shrink: 0;- width: 18px;- font-variant-numeric: tabular-nums;- color: ${cssVar.colorTextTertiary};- `,- option: css`- cursor: pointer;-- display: flex;- gap: 8px;- align-items: center;-- min-height: 40px;- padding-block: 7px;- padding-inline: 16px;- border-radius: calc(${cssVar.borderRadiusLG} - 2px);-- color: ${cssVar.colorTextSecondary};-- transition:- background 120ms,- color 120ms;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,- optionLabel: css`- flex: 1;- line-height: 1.4;- `,- optionList: css`- display: flex;- flex-direction: column;- gap: 2px;- `,- optionSelected: css`- color: ${cssVar.colorText};- background: ${cssVar.colorFillSecondary};-- &:hover {- background: ${cssVar.colorFillSecondary};- }- `,- rejectInput: css`- flex: 1;-- width: 100%;- padding: 0;- border: none;- border-radius: 0;-- font-family: inherit;- font-size: 14px;- line-height: 1.4;- color: ${cssVar.colorText};-- background: transparent;-- &::placeholder {- color: ${cssVar.colorTextSecondary};- }-- &:focus,- &:focus-visible {- outline: none;- }-- &:disabled {- cursor: pointer;- color: ${cssVar.colorTextSecondary};- }- `,- shortcutHint: css`- display: inline-flex;- align-items: center;- margin-inline-start: 6px;- color: ${cssVar.colorTextTertiary};- `,- submitButton: css`- min-width: 88px;- height: 36px;- border-radius: calc(${cssVar.borderRadiusLG} - 2px);- `,-}));+const styles = stylex.create({+ container: {+ width: '100%',+ },+ footer: {+ display: 'flex',+ gap: '8px',+ alignItems: 'center',+ justifyContent: 'flex-end',+ marginBlockStart: '8px',+ },+ number: {+ flexShrink: 0,+ width: '18px',+ fontVariantNumeric: 'tabular-nums',+ color: cssVar.colorTextTertiary,+ },+ option: {+ cursor: 'pointer',+ display: 'flex',+ gap: '8px',+ alignItems: 'center',+ minHeight: '40px',+ paddingBlock: '7px',+ paddingInline: '16px',+ borderRadius: `calc(${cssVar.borderRadiusLG} - 2px)`,+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ transition: 'background 120ms, color 120ms',+ },+ optionLabel: {+ flex: '1',+ lineHeight: 1.4,+ },+ optionList: {+ display: 'flex',+ flexDirection: 'column',+ gap: '2px',+ },+ optionSelected: {+ color: cssVar.colorText,+ backgroundColor: cssVar.colorFillSecondary,+ backgroundImage: 'none',+ },+ rejectInput: {+ 'flex': '1',+ 'width': '100%',+ 'padding': '0',+ 'borderStyle': 'none',+ 'borderRadius': '0',+ 'fontFamily': 'inherit',+ 'fontSize': '14px',+ 'lineHeight': 1.4,+ 'color': { 'default': cssVar.colorText, ':disabled': cssVar.colorTextSecondary },+ 'backgroundColor': 'transparent',+ 'backgroundImage': 'none',+ 'outlineStyle': 'none',+ 'cursor': { 'default': null, ':disabled': 'pointer' },+ '::placeholder': { color: cssVar.colorTextSecondary },+ },+ shortcutHint: {+ display: 'inline-flex',+ alignItems: 'center',+ marginInlineStart: '6px',+ color: cssVar.colorTextTertiary,+ },+ submitButton: {+ minWidth: '88px',+ height: '36px',+ borderRadius: `calc(${cssVar.borderRadiusLG} - 2px)`,+ },+});const ApprovalActions = memo<ApprovalActionsProps>(({@@ -405,14 +381,14 @@ const ApprovalActions = memo<ApprovalActionsProps>(if (!canUseResource) return null;return (- <Flexbox className={styles.container} ref={containerRef}>- <div className={styles.optionList} role="radiogroup">+ <Flexbox className={stylex.props(styles.container).className} ref={containerRef}>+ <div {...stylex.props(styles.optionList)} role="radiogroup">{choices.map((c, index) => {if (c === 'reject') {return (<divaria-checked={choice === 'reject'}- className={cx(styles.option, choice === 'reject' && styles.optionSelected)}+ {...stylex.props(styles.option, choice === 'reject' && styles.optionSelected)}key={c}role="radio"onClick={() => {@@ -420,10 +396,10 @@ const ApprovalActions = memo<ApprovalActionsProps>(rejectInputRef.current?.focus();}}>- <span className={styles.number}>{rejectNumber}.</span>+ <span {...stylex.props(styles.number)}>{rejectNumber}.</span><inputaria-label={t('tool.intervention.rejectReasonPlaceholder')}- className={styles.rejectInput}+ {...stylex.props(styles.rejectInput)}disabled={loading || isMessageCreating}placeholder={t('tool.intervention.rejectReasonPlaceholder')}ref={rejectInputRef}@@ -442,19 +418,21 @@ const ApprovalActions = memo<ApprovalActionsProps>(<divaria-checked={effectiveChoice === c}aria-disabled={approveDisabled || undefined}- className={cx(styles.option, effectiveChoice === c && styles.optionSelected)}+ {...stylex.props(styles.option, effectiveChoice === c && styles.optionSelected)}key={c}role="radio"onClick={() => setChoice(c)}>- <span className={styles.number}>{index + 1}.</span>- <span className={styles.optionLabel}>{approveLabelFor(c)}</span>+ <span className={stylex.props(styles.number).className}>{index + 1}.</span>+ <span className={stylex.props(styles.optionLabel).className}>+ {approveLabelFor(c)}+ </span></div>);})}</div>- <div className={styles.footer}>+ <div {...stylex.props(styles.footer)}><Buttondisabled={loading || isMessageCreating}icon={CircleStop}@@ -466,7 +444,7 @@ const ApprovalActions = memo<ApprovalActionsProps>({t('tool.intervention.stop')}</Button><Button- className={styles.submitButton}+ className={stylex.props(styles.submitButton).className}disabled={isMessageCreating || submitBlocked}loading={loading}size={'middle'}@@ -474,7 +452,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(onClick={handleSubmit}>{t('tool.intervention.submit')}- <span className={styles.shortcutHint}>+ <span {...stylex.props(styles.shortcutHint)}><CornerDownLeft size={12} /></span></Button>diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsxindex 7e849c1019b..fd8b9454f13 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx@@ -5,7 +5,9 @@ import {} from '@lobechat/builtin-tool-activator';import { builtinToolIdentifiers } from '@lobechat/builtin-tools/identifiers';import { safeParseJSON } from '@lobechat/utils';-import { ActionIcon, Avatar, createStaticStyles, Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, Avatar, Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import { ChevronDown, ChevronRight, Edit3Icon } from 'lucide-react';import { memo, Suspense, useCallback, useMemo, useRef, useState } from 'react';@@ -22,39 +24,31 @@ import Arguments from '../Arguments';import ApprovalActions from './ApprovalActions';import KeyValueEditor from './KeyValueEditor';-const styles = createStaticStyles(({ css, cssVar }) => ({- collapseHeader: css`- cursor: pointer;- user-select: none;-- padding-block: 6px;- padding-inline: 10px;-- font-size: 12px;- color: ${cssVar.colorTextTertiary};-- &:hover {- color: ${cssVar.colorTextSecondary};- }- `,- description: css`- padding-block: 8px;- padding-inline: 16px;-- font-size: ${cssVar.fontSize};- font-weight: 600;- color: ${cssVar.colorText};- `,- reason: css`- margin-block-start: -4px;- padding-block-end: 8px;- padding-inline: 16px;-- font-size: ${cssVar.fontSizeSM};- line-height: 1.45;- color: ${cssVar.colorTextSecondary};- `,-}));+const styles = stylex.create({+ collapseHeader: {+ cursor: 'pointer',+ userSelect: 'none',+ paddingBlock: '6px',+ paddingInline: '10px',+ fontSize: '12px',+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorTextSecondary },+ },+ description: {+ paddingBlock: '8px',+ paddingInline: '16px',+ fontSize: cssVar.fontSize,+ fontWeight: 600,+ color: cssVar.colorText,+ },+ reason: {+ marginBlockStart: '-4px',+ paddingBlockEnd: '8px',+ paddingInline: '16px',+ fontSize: cssVar.fontSizeSM,+ lineHeight: 1.45,+ color: cssVar.colorTextSecondary,+ },+});interface FallbackInterventionProps {actionsPortalTarget?: HTMLDivElement | null;@@ -188,7 +182,12 @@ const FallbackIntervention = memo<FallbackInterventionProps>(return (<Flexbox gap={4}>- <Flexbox horizontal align="center" className={styles.description} gap={6}>+ <Flexbox+ horizontal+ align="center"+ className={stylex.props(styles.description).className}+ gap={6}+ >{pluginMeta?.avatar && (<Avataravatar={pluginMeta.avatar}@@ -204,14 +203,14 @@ const FallbackIntervention = memo<FallbackInterventionProps>(</span></Flexbox>- {activationReason && <div className={styles.reason}>{activationReason}</div>}+ {activationReason && <div {...stylex.props(styles.reason)}>{activationReason}</div>}{argCount > 0 && (<><Flexboxhorizontalalign="center"- className={styles.collapseHeader}+ className={stylex.props(styles.collapseHeader).className}gap={4}onClick={() => setShowArgs(!showArgs)}>diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/KeyValueEditor.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/KeyValueEditor.tsxindex 6c5a2d6c4cc..5f8c8f66ac1 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/KeyValueEditor.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/KeyValueEditor.tsx@@ -1,37 +1,25 @@-import { ActionIcon, Button, createStaticStyles, Flexbox, Icon, Input, toast } from '@lobehub/ui';+import { ActionIcon, Button, Flexbox, Icon, Input, toast } from '@lobehub/ui';import { Form, useForm } from '@lobehub/ui/form';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { LucidePlus, LucideTrash } from 'lucide-react';import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-const styles = createStaticStyles(({ css, cssVar }) => ({- form: css`- position: relative;-- width: 100%;- min-width: 600px;- padding: 8px;- border-radius: ${cssVar.borderRadiusLG};- `,- error: css`- font-size: 12px;- color: ${cssVar.colorError};- `,- formItem: css`- margin-block-end: 4px;- `,- input: css`- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- `,- row: css`- position: relative;- `,- title: css`- margin-block-end: 4px;- color: ${cssVar.colorTextTertiary};- `,-}));+const styles = stylex.create({+ form: {+ position: 'relative',+ width: '100%',+ minWidth: '600px',+ padding: '8px',+ borderRadius: cssVar.borderRadiusLG,+ },+ error: { fontSize: '12px', color: cssVar.colorError },+ formItem: { marginBlockEnd: '4px' },+ input: { fontFamily: cssVar.fontFamilyCode, fontSize: '12px' },+ row: { position: 'relative' },+ title: { marginBlockEnd: '4px', color: cssVar.colorTextTertiary },+});interface KeyValueItem {id: string;@@ -105,8 +93,8 @@ const KeyValueEditor = memo<KeyValueEditorProps>(({ initialValue = {}, onFinish,};return (- <Form autoComplete="off" className={styles.form} form={form} gap={0}>- <Flexbox horizontal className={styles.title} gap={8}>+ <Form autoComplete="off" className={stylex.props(styles.form).className} form={form} gap={0}>+ <Flexbox horizontal className={stylex.props(styles.title).className} gap={8}><Flexbox flex={1}>key</Flexbox><Flexbox flex={4}>value</Flexbox></Flexbox>@@ -117,7 +105,7 @@ const KeyValueEditor = memo<KeyValueEditorProps>(({ initialValue = {}, onFinish,<Flexboxhorizontalalign="center"- className={styles.row}+ className={stylex.props(styles.row).className}gap={8}key={key}width={'100%'}@@ -129,26 +117,26 @@ const KeyValueEditor = memo<KeyValueEditorProps>(({ initialValue = {}, onFinish,validate={validateKey}validateOn={'change'}render={({ error, onBlur, onChange, value }) => (- <Flexbox className={styles.formItem} flex={1}>+ <Flexbox className={stylex.props(styles.formItem).className} flex={1}><InputallowCleararia-invalid={error ? true : undefined}- className={styles.input}+ className={stylex.props(styles.input).className}placeholder={t('updateArgs.form.key')}value={value}variant={'filled'}onBlur={onBlur}onChange={(e) => onChange(e.target.value)}/>- {error && <div className={styles.error}>{error}</div>}+ {error && <div {...stylex.props(styles.error)}>{error}</div>}</Flexbox>)}/>- <Flexbox className={styles.formItem} flex={4}>+ <Flexbox className={stylex.props(styles.formItem).className} flex={4}><Form.Field bare name={`${name}.value`}><InputallowClear- className={styles.input}+ className={stylex.props(styles.input).className}placeholder={t('updateArgs.form.value')}variant={'filled'}/>diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/RejectedResponse.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/RejectedResponse.tsxindex 8d2f5bf406c..10a5ab82ba4 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/RejectedResponse.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/RejectedResponse.tsx@@ -1,24 +1,16 @@-import { createStaticStyles, cssVar, Flexbox, Icon } from '@lobehub/ui';+import { Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { AlertTriangle, CornerUpRight } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { resolveRejectedCopyKey } from './resolveRejectedCopyKey';-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- padding-block: 8px;- padding-inline: 6px;- `,- reason: css`- font-size: 12px;- color: ${cssVar.colorTextTertiary};- `,- title: css`- font-size: 14px;- color: ${cssVar.colorTextSecondary};- `,-}));+const styles = stylex.create({+ container: { paddingBlock: '8px', paddingInline: '6px' },+ title: { fontSize: '14px', color: cssVar.colorTextSecondary },+});interface RejectedResponseProps {/** Distinguishes question skips from other skipped interactions in the copy. */@@ -42,14 +34,14 @@ const RejectedResponse = memo<RejectedResponseProps>(({ apiName, reason, skippedconst copyKey = resolveRejectedCopyKey({ apiName, reason, skipped, timedOut });return (- <Flexbox className={styles.container} gap={8}>+ <Flexbox className={stylex.props(styles.container).className} gap={8}><Flexbox horizontal align={'center'} gap={8}>{skipped || timedOut ? (<Icon color={cssVar.colorTextTertiary} icon={CornerUpRight} size={16} />) : (<Icon color={cssVar.colorWarning} icon={AlertTriangle} size={16} />)}- <div className={styles.title}>{t(copyKey, { reason })}</div>+ <div {...stylex.props(styles.title)}>{t(copyKey, { reason })}</div></Flexbox></Flexbox>);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsxindex d5dbcd0a930..52ecd55688d 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx@@ -1,5 +1,7 @@import { getGoalCommand, isGoalCommandFailed } from '@lobechat/shared-tool-ui/goal-command';-import { createStaticStyles, cx, Icon } from '@lobehub/ui';+import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import { ChevronRight } from 'lucide-react';import { memo, useMemo } from 'react';@@ -8,47 +10,44 @@ import { useTranslation } from 'react-i18next';import { pluginHelpers, useToolStore } from '@/store/tool';import { toolSelectors } from '@/store/tool/selectors';import { shinyTextStyles } from '@/styles';+import { sx } from '@/styles/sx';import { getToolDisplayName } from '../../toolDisplayNames';import { extractToolKeyword } from './extractToolKeyword';-export const styles = createStaticStyles(({ css, cssVar }) => ({- aborted: css`- color: ${cssVar.colorTextQuaternary};- `,- keyword: css`- overflow: hidden;- flex: 0 1 auto;-- min-width: 0;-- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- color: ${cssVar.colorTextTertiary};- text-overflow: ellipsis;- `,- root: css`- overflow: hidden;- display: flex;- gap: 6px;- align-items: center;-- min-width: 0;- padding-block: 1px;-- color: ${cssVar.colorTextDescription};- white-space: nowrap;- `,- label: css`- flex: none;- `,- standalone: css`- overflow: hidden;- flex: 0 1 auto;- min-width: 0;- text-overflow: ellipsis;- `,-}));+export const styles = stylex.create({+ aborted: { color: cssVar.colorTextQuaternary },+ keyword: {+ overflow: 'hidden',+ flexGrow: 0,+ flexShrink: 1,+ flexBasis: 'auto',+ minWidth: '0',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: '12px',+ color: cssVar.colorTextTertiary,+ textOverflow: 'ellipsis',+ },+ root: {+ overflow: 'hidden',+ display: 'flex',+ gap: '6px',+ alignItems: 'center',+ minWidth: '0',+ paddingBlock: '1px',+ color: cssVar.colorTextDescription,+ whiteSpace: 'nowrap',+ },+ label: { flex: 'none' },+ standalone: {+ overflow: 'hidden',+ flexGrow: 0,+ flexShrink: 1,+ flexBasis: 'auto',+ minWidth: '0',+ textOverflow: 'ellipsis',+ },+});interface ToolTitleProps {apiName: string;@@ -114,24 +113,24 @@ const ToolTitle = memo<ToolTitleProps>(const failed = !isLoading && isGoalCommandFailed(result);const status = isLoading ? 'loading' : failed ? 'failed' : 'completed';return (- <div className={cx(styles.root, isAborted && styles.aborted)}>- <span className={cx(styles.label, isLoading && shinyTextStyles.shinyText)}>+ <div {...stylex.props(styles.root, isAborted && styles.aborted)}>+ <span {...sx([styles.label], isLoading ? shinyTextStyles.shinyText : undefined)}>{t(`builtins.goalCommand.${goalCommand.kind}.${status}`)}</span>- {goalTitle && <span className={styles.standalone}>{goalTitle}</span>}+ {goalTitle && <span {...stylex.props(styles.standalone)}>{goalTitle}</span>}</div>);}return (- <div className={cx(styles.root, isAborted && styles.aborted)}>+ <div {...stylex.props(styles.root, isAborted && styles.aborted)}>{isStandaloneDescription ? (- <span className={cx(styles.standalone, isLoading && shinyTextStyles.shinyText)}>+ <span {...sx([styles.standalone], isLoading ? shinyTextStyles.shinyText : undefined)}>{keyword}</span>) : (<>- <span className={cx(styles.label, isLoading && shinyTextStyles.shinyText)}>+ <span {...sx([styles.label], isLoading ? shinyTextStyles.shinyText : undefined)}>{actionLabel || (<>{pluginTitle && (@@ -144,7 +143,7 @@ const ToolTitle = memo<ToolTitleProps>(</>)}</span>- {keyword && <span className={styles.keyword}>{keyword}</span>}+ {keyword && <span {...stylex.props(styles.keyword)}>{keyword}</span>}</>)}</div>diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsxindex b2f727a85e5..99d72d75116 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx@@ -1,7 +1,8 @@'use client';import type { UIChatMessage } from '@lobechat/types';-import { createStaticStyles, Flexbox, ScrollArea } from '@lobehub/ui';+import { Flexbox, ScrollArea } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import type { RefObject } from 'react';import { memo, useMemo } from 'react';@@ -9,18 +10,19 @@ import { resolveAssistantGroupFromMessages } from '../utils/resolveAssistantGrouimport ContentBlock from './ContentBlock';import type { RenderableAssistantContentBlock } from './types';-const styles = createStaticStyles(({ css }) => ({- scrollRoot: css`- border-radius: 0;- background: transparent;- `,- scrollTask: css`- max-height: min(50vh, 300px);- `,- scrollWorkflow: css`- max-height: min(40vh, 320px);- `,-}));+const styles = stylex.create({+ scrollRoot: {+ borderRadius: '0',+ backgroundColor: 'transparent',+ backgroundImage: 'none',+ },+ scrollTask: {+ maxHeight: 'min(50vh, 300px)',+ },+ scrollWorkflow: {+ maxHeight: 'min(40vh, 320px)',+ },+});interface ContentBlocksScrollBaseProps {disableEditing?: boolean;@@ -84,13 +86,15 @@ const ContentBlocksScroll = memo<ContentBlocksScrollProps>((props) => {return body;}- const scrollClass = variant === 'task' ? styles.scrollTask : styles.scrollWorkflow;+ const scrollClass = stylex.props(+ variant === 'task' ? styles.scrollTask : styles.scrollWorkflow,+ ).className;return (<ScrollAreadisableContentFitscrollFade- className={styles.scrollRoot}+ className={stylex.props(styles.scrollRoot).className}contentProps={{ style: { paddingInlineEnd: 12 } }}scrollbarProps={{style: {diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsxindex 94fabe8aaba..89cb36d802f 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx@@ -1,5 +1,6 @@import { splitAssistantGroupFinalAnswer } from '@lobechat/conversation-flow';-import { createStaticStyles, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import { Fragment, memo, useMemo } from 'react';@@ -22,14 +23,8 @@ import { countAssistantLlmCalls, hasRenderableFinalAnswer, shouldFoldProcess } fimport SteerMessage from './SteerMessage';import type { WorkflowExpandLevelDefault } from './WorkflowCollapse';-const styles = createStaticStyles(({ css }) => {- return {- container: css`- &:has(.tool-blocks) {- width: 100%;- }- `,- };+const styles = stylex.create({+ container: { width: { 'default': null, ':has(.tool-blocks)': '100%' } },});const ACTIVE_OPERATION_STATUSES = new Set<OperationStatus>(['pending', 'paused', 'running']);@@ -217,7 +212,7 @@ const Group = memo<GroupChildrenProps>(};return (- <Flexbox className={styles.container} gap={4}>+ <Flexbox className={stylex.props(styles.container).className} gap={4}>{views.map((view, index) => (<Fragment key={view.id}>{view.steerUserId && <SteerMessage id={view.steerUserId} />}diff --git a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsxindex 8291214380f..4b7d770e618 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx@@ -1,5 +1,6 @@import { deserializeParts } from '@lobechat/utils';-import { createStaticStyles, cx } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { LOADING_FLAT } from '@/const/message';@@ -15,13 +16,7 @@ import { dataSelectors, messageStateSelectors, useConversationStore } from '../.import { normalizeThinkTags, processWithArtifact } from '../../../utils/markdown';import { useMarkdown } from '../useMarkdown';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- pWithTool: css`- color: ${cssVar.colorTextTertiary};- `,- };-});+const styles = stylex.create({ pWithTool: { color: cssVar.colorTextTertiary } });interface MessageContentProps {contentOverride?: string;disableStreaming?: boolean;@@ -93,7 +88,10 @@ const MessageContent = memo<MessageContentProps>(content && (<>{drawer}- <MarkdownMessage {...markdownProps} className={cx(isToolSingleLine && styles.pWithTool)}>+ <MarkdownMessage+ {...markdownProps}+ className={stylex.props(isToolSingleLine && styles.pWithTool).className}+ >{message}</MarkdownMessage></>diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ProcessFold.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ProcessFold.tsxindex dc3de366787..c6b8824da32 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ProcessFold.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ProcessFold.tsx@@ -1,22 +1,20 @@-import { Accordion, createStaticStyles, Divider, Flexbox, Icon, Text } from '@lobehub/ui';+import { Accordion, Divider, Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronRight } from 'lucide-react';import { memo, type ReactNode, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';const PROCESS_KEY = 'process';-const styles = createStaticStyles(({ css, cssVar }) => ({- title: css`- min-width: 0;- color: ${cssVar.colorTextTertiary};- white-space: nowrap;- transition: color 150ms ${cssVar.motionEaseOut};-- &:hover {- color: ${cssVar.colorText};- }- `,-}));+const styles = stylex.create({+ title: {+ minWidth: '0',+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },+ whiteSpace: 'nowrap',+ transition: `color 150ms ${cssVar.motionEaseOut}`,+ },+});/*** The Accordion's borderless header paints a hover fill that bleeds outward@@ -58,7 +56,7 @@ const ProcessFold = memo<ProcessFoldProps>(const value = useMemo(() => (expanded ? [PROCESS_KEY] : []), [expanded]);const title = (- <Flexbox horizontal align={'center'} className={styles.title} gap={6}>+ <Flexbox horizontal align={'center'} className={stylex.props(styles.title).className} gap={6}><Text style={{ color: 'inherit', minWidth: 0 }}>{durationText? t('turnProcess.ranFor', { count: stepCount, duration: durationText })diff --git a/src/features/Conversation/Messages/CompressedGroup/index.tsx b/src/features/Conversation/Messages/CompressedGroup/index.tsxindex d45e03435b7..90af3520020 100644--- a/src/features/Conversation/Messages/CompressedGroup/index.tsx+++ b/src/features/Conversation/Messages/CompressedGroup/index.tsx@@ -1,8 +1,10 @@'use client';import type { CompressionGroupMetadata, UIChatMessage } from '@lobechat/types';-import { createStaticStyles, cx, Divider, Flexbox, Icon, Markdown } from '@lobehub/ui';+import { cx, Divider, Flexbox, Icon, Markdown } from '@lobehub/ui';import { ActionIcon, confirmModal, Tabs, type TabsItem } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import { ChevronDown, ChevronUp, History, Sparkles, Undo2 } from 'lucide-react';import { memo, useCallback, useMemo } from 'react';@@ -22,40 +24,26 @@ import {} from './logic';import { useGroupPreferences } from './useGroupPreferences';-const styles = createStaticStyles(({ css, cssVar }) => ({- collapsedButton: css`- cursor: pointer;-- display: inline-flex;- gap: 6px;- align-items: center;-- padding-block: 2px;- padding-inline: 8px;- border: none;- border-radius: 6px;-- font-size: 12px;- color: ${cssVar.colorTextDescription};-- background: none;-- transition: color 0.2s ease;-- &:hover {- color: ${cssVar.colorText};- }- `,- container: css`- margin-block-end: 8px;- `,- divider: css`- margin: 0;- `,- messagesContainer: css`- padding-block: 8px;- `,-}));+const styles = stylex.create({+ collapsedButton: {+ cursor: 'pointer',+ display: 'inline-flex',+ gap: '6px',+ alignItems: 'center',+ paddingBlock: '2px',+ paddingInline: '8px',+ borderStyle: 'none',+ borderRadius: '6px',+ fontSize: '12px',+ color: { 'default': cssVar.colorTextDescription, ':hover': cssVar.colorText },+ backgroundColor: 'transparent',+ backgroundImage: 'none',+ transition: 'color 0.2s ease',+ },+ container: { marginBlockEnd: '8px' },+ divider: { margin: '0' },+ messagesContainer: { paddingBlock: '8px' },+});export interface CompressedGroupMessageProps {id: string;@@ -135,7 +123,7 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {if (isGeneratingSummary) {return (- <Flexbox className={styles.container} gap={8}>+ <Flexbox className={stylex.props(styles.container).className} gap={8}><Flexbox horizontal><span className={cx(shinyTextStyles.shinyText)}>{t('compressedHistory')}</span></Flexbox>@@ -145,7 +133,7 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {}return (- <Flexbox className={styles.container} gap={8}>+ <Flexbox className={stylex.props(styles.container).className} gap={8}>{expanded ? (<><Flexbox horizontal align={'center'} distribution={'space-between'} width={'100%'}>@@ -168,7 +156,7 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {{!showPanelContent ? null : activeTab === 'summary' ? (<Markdown variant={'chat'}>{content}</Markdown>) : (- <Flexbox className={styles.messagesContainer} gap={4}>+ <Flexbox className={stylex.props(styles.messagesContainer).className} gap={4}>{compressedMessages?.map((msg) => (<CompressedMessageItem key={msg.id} message={msg} />))}@@ -176,8 +164,12 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {)}</>) : (- <Divider className={styles.divider}>- <button className={styles.collapsedButton} type={'button'} onClick={toggleExpanded}>+ <Divider className={stylex.props(styles.divider).className}>+ <button+ {...stylex.props(styles.collapsedButton)}+ type={'button'}+ onClick={toggleExpanded}+ ><Icon icon={History} size={14} /><span>{compressedTurnCount > 0diff --git a/src/features/Conversation/Messages/EditedFilesCard/index.tsx b/src/features/Conversation/Messages/EditedFilesCard/index.tsxindex 4ceb8965bd0..e7da53661b0 100644--- a/src/features/Conversation/Messages/EditedFilesCard/index.tsx+++ b/src/features/Conversation/Messages/EditedFilesCard/index.tsx@@ -10,7 +10,9 @@ import {KindDot,LineStats,} from '@lobechat/shared-tool-ui/components';-import { Button, Center, createStaticStyles, cx, Flexbox, PatchDiff, Text } from '@lobehub/ui';+import { Button, Center, Flexbox, PatchDiff, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {ArrowUpRightIcon,ChevronDownIcon,@@ -40,160 +42,145 @@ const toggleOnKey = (toggle: () => void) => (event: KeyboardEvent<HTMLDivElement}};-const styles = createStaticStyles(({ css, cssVar }) => ({- card: css`- overflow: hidden;-- width: 100%;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorBgElevated};- `,- header: css`- padding-block: 8px;- padding-inline: 12px;- `,- headerIcon: css`- flex-shrink: 0;-- width: ${AGGREGATE_EDITED_FILE_ICON_SIZE}px;- height: ${AGGREGATE_EDITED_FILE_ICON_SIZE}px;- border-radius: 8px;-- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};- `,- singleHeader: css`- position: relative;- padding-block: 8px;- padding-inline: 12px;-- &:hover [data-view-changes],- &:focus-within [data-view-changes] {- pointer-events: auto;- transform: translateX(0);- opacity: 1;- }- `,- singleHeaderClickable: css`- cursor: pointer;-- &:hover {- background: ${cssVar.colorFillQuaternary};- }- `,- singleTitle: css`- min-width: 0;- font-size: 14px;- font-weight: 500;- `,+const styles = stylex.create({+ card: {+ overflow: 'hidden',+ width: '100%',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+ header: {+ paddingBlock: '8px',+ paddingInline: '12px',+ },+ headerIcon: {+ flexShrink: 0,+ width: `${AGGREGATE_EDITED_FILE_ICON_SIZE}px`,+ height: `${AGGREGATE_EDITED_FILE_ICON_SIZE}px`,+ borderRadius: '8px',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ singleHeader: {+ position: 'relative',+ paddingBlock: '8px',+ paddingInline: '12px',+ },+ singleHeaderClickable: {+ cursor: 'pointer',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ singleTitle: {+ minWidth: '0',+ fontSize: '14px',+ fontWeight: 500,+ },/*** The action slides *over* the line stats instead of displacing them, so the* `+N -M` column stays put on hover. The two stacked gradients composite to* exactly the hovered row colour (fill over elevated), which is why the* opaque end shows no seam against the row behind it.*/- viewChanges: css`- pointer-events: none;-- position: absolute;- inset-block: 0;- inset-inline-end: 0;-- display: flex;- align-items: center;- justify-content: flex-end;-- padding-inline: 56px 12px;-- opacity: 0;- background:- linear-gradient(to left, ${cssVar.colorFillQuaternary} 62%, transparent),- linear-gradient(to left, ${cssVar.colorBgElevated} 62%, transparent);-- transition: opacity 160ms ${cssVar.motionEaseOut};-- @media (hover: none) {- pointer-events: auto;- opacity: 1;- }- `,- viewChangesButton: css`- height: 22px;- padding: 0;- color: ${cssVar.colorTextSecondary};- `,- viewChangesVisible: css`- pointer-events: auto;- opacity: 1;- `,- chevron: css`- flex-shrink: 0;- color: ${cssVar.colorTextTertiary};- `,- title: css`- min-width: 0;- font-size: 14px;- font-weight: 500;- `,- stats: css`- font-weight: 500;- `,- list: css`- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- `,- showMore: css`- cursor: pointer;-- padding-block: 7px;- padding-inline: 12px;-- font-size: 13px;- color: ${cssVar.colorTextSecondary};-- &:hover {- background: ${cssVar.colorFillQuaternary};- }- `,- row: css`- position: relative;- padding-block: 6px;- padding-inline: 12px;-- &:hover [data-view-changes],- &:focus-within [data-view-changes] {- pointer-events: auto;- transform: translateX(0);- opacity: 1;- }- `,- rowMain: css`- min-height: 24px;- `,- rowClickable: css`- cursor: pointer;- border-radius: 6px;-- &:hover {- background: ${cssVar.colorFillQuaternary};- }- `,- path: css`- overflow: hidden;- display: flex;- flex: 1;- align-items: center;+ viewChanges: {+ position: 'absolute',+ insetBlockStart: 0,+ insetBlockEnd: 0,+ insetInlineEnd: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'flex-end',+ paddingInlineStart: '56px',+ paddingInlineEnd: '12px',+ pointerEvents: {+ 'default': 'none',+ [stylex.when.ancestor(':hover')]: 'auto',+ [stylex.when.ancestor(':focus-within')]: 'auto',+ '@media (hover: none)': 'auto',+ },+ transform: {+ default: null,+ [stylex.when.ancestor(':hover')]: 'translateX(0)',+ [stylex.when.ancestor(':focus-within')]: 'translateX(0)',+ },+ opacity: {+ 'default': 0,+ [stylex.when.ancestor(':hover')]: 1,+ [stylex.when.ancestor(':focus-within')]: 1,+ '@media (hover: none)': 1,+ },+ backgroundImage: `linear-gradient(to left, ${cssVar.colorFillQuaternary} 62%, transparent), linear-gradient(to left, ${cssVar.colorBgElevated} 62%, transparent)`,+ transition: `opacity 160ms ${cssVar.motionEaseOut}`,+ },+ viewChangesButton: {+ height: '22px',+ padding: '0',+ color: cssVar.colorTextSecondary,+ },+ viewChangesVisible: {+ pointerEvents: 'auto',+ opacity: 1,+ },+ chevron: {+ flexShrink: 0,+ color: cssVar.colorTextTertiary,+ },+ title: {+ minWidth: '0',+ fontSize: '14px',+ fontWeight: 500,+ },+ stats: {+ fontWeight: 500,+ },+ list: {+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+ showMore: {+ cursor: 'pointer',+ paddingBlock: '7px',+ paddingInline: '12px',+ fontSize: '13px',+ color: cssVar.colorTextSecondary,+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ row: {+ position: 'relative',+ paddingBlock: '6px',+ paddingInline: '12px',+ },+ rowMain: {+ minHeight: '24px',+ },+ rowClickable: {+ cursor: 'pointer',+ borderRadius: '6px',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ path: {+ overflow: 'hidden',+ display: 'flex',+ flex: '1',+ alignItems: 'center',+ minWidth: '0',+ },+ patch: {+ overflow: 'hidden',+ marginBlockStart: '6px',+ paddingInlineStart: '18px',+ },+});- min-width: 0;- `,- patch: css`- overflow: hidden;- margin-block-start: 6px;- padding-inline-start: 18px;- `,-}));+const marker = stylex.defaultMarker();const EditedFileRow = memo<{ entry: EditedFileEntry; onOpen?: () => void }>(({ entry, onOpen }) => {const { t } = useTranslation('chat');@@ -208,12 +195,14 @@ const EditedFileRow = memo<{ entry: EditedFileEntry; onOpen?: () => void }>(({ econst clickable = !!handleRowClick;return (- <Flexbox className={cx(styles.row, clickable && styles.rowClickable)}>+ <Flexbox+ className={stylex.props(styles.row, clickable && styles.rowClickable, marker).className}+ ><Flexboxhorizontalalign={'center'}aria-expanded={onOpen ? undefined : hasDiff ? expanded : undefined}- className={styles.rowMain}+ className={stylex.props(styles.rowMain).className}gap={10}role={clickable ? 'button' : undefined}tabIndex={clickable ? 0 : undefined}@@ -221,23 +210,23 @@ const EditedFileRow = memo<{ entry: EditedFileEntry; onOpen?: () => void }>(({ eonKeyDown={handleRowClick ? toggleOnKey(handleRowClick) : undefined}><KindDot kind={entry.kind} />- <div className={styles.path}>+ <div {...stylex.props(styles.path)}><FilePathDisplay filePath={entry.path} /></div><LineStatshideZeroDeltas- className={styles.stats}+ className={stylex.props(styles.stats).className}linesAdded={entry.linesAdded}linesDeleted={entry.linesDeleted}/>{onOpen && hasDiff && (<divdata-view-changes- className={cx(styles.viewChanges, expanded && styles.viewChangesVisible)}+ {...stylex.props(styles.viewChanges, expanded && styles.viewChangesVisible)}><Buttonaria-expanded={expanded}- className={styles.viewChangesButton}+ className={stylex.props(styles.viewChangesButton).className}size={'small'}type={'text'}// Enter/Space on the button must not bubble into the row's own@@ -255,13 +244,13 @@ const EditedFileRow = memo<{ entry: EditedFileEntry; onOpen?: () => void }>(({ e{!onOpen &&hasDiff &&(expanded ? (- <ChevronDownIcon className={styles.chevron} size={14} />+ <ChevronDownIcon className={stylex.props(styles.chevron).className} size={14} />) : (- <ChevronRightIcon className={styles.chevron} size={14} />+ <ChevronRightIcon className={stylex.props(styles.chevron).className} size={14} />))}</Flexbox>{hasDiff && expanded && (- <div className={styles.patch}>+ <div {...stylex.props(styles.patch)}>{entry.diffTexts.map((patch, index) => (<PatchDifffileName={fileName}@@ -306,15 +295,18 @@ const SingleEditedFileCard = memo<{ entry: EditedFileEntry; onOpen?: () => voidconst handleClick = onOpen ?? (hasDiff ? () => setShowDiff((prev) => !prev) : undefined);return (- <Flexbox className={styles.card}>+ <Flexbox className={stylex.props(styles.card).className}><Flexboxhorizontalalign={'center'}aria-expanded={onOpen ? undefined : hasDiff ? showDiff : undefined}- className={cx(styles.singleHeader, handleClick && styles.singleHeaderClickable)}gap={10}role={handleClick ? 'button' : undefined}tabIndex={handleClick ? 0 : undefined}+ className={+ stylex.props(styles.singleHeader, handleClick && styles.singleHeaderClickable, marker)+ .className+ }onClick={handleClick}onKeyDown={handleClick ? toggleOnKey(handleClick) : undefined}>@@ -323,12 +315,12 @@ const SingleEditedFileCard = memo<{ entry: EditedFileEntry; onOpen?: () => voidsize={SINGLE_EDITED_FILE_ICON_SIZE}/><Flexbox flex={1} gap={2}>- <Text ellipsis className={styles.singleTitle}>+ <Text ellipsis className={stylex.props(styles.singleTitle).className}>{t('editedFiles.singleTitle', { path: displayPath })}</Text><LineStatshideZeroDeltas- className={styles.stats}+ className={stylex.props(styles.stats).className}linesAdded={entry.linesAdded}linesDeleted={entry.linesDeleted}/>@@ -341,11 +333,11 @@ const SingleEditedFileCard = memo<{ entry: EditedFileEntry; onOpen?: () => void{hasDiff && (<divdata-view-changes- className={cx(styles.viewChanges, showDiff && styles.viewChangesVisible)}+ {...stylex.props(styles.viewChanges, showDiff && styles.viewChangesVisible)}><Buttonaria-expanded={showDiff}- className={styles.viewChangesButton}+ className={stylex.props(styles.viewChangesButton).className}icon={<ArrowUpRightIcon size={14} />}iconPosition={'end'}size={'small'}@@ -364,7 +356,7 @@ const SingleEditedFileCard = memo<{ entry: EditedFileEntry; onOpen?: () => void)}</Flexbox>{hasDiff && showDiff && (- <div className={styles.patch}>+ <div {...stylex.props(styles.patch)}>{entry.diffTexts.map((patch, index) => (<PatchDifffileName={fileName}@@ -407,24 +399,29 @@ const EditedFilesCard = memo<EditedFilesCardProps>(({ entries }) => {const toggleShowAll = () => setShowAll((prev) => !prev);return (- <Flexbox className={styles.card}>- <Flexbox horizontal align={'center'} className={styles.header} gap={10}>- <Center className={styles.headerIcon}>+ <Flexbox className={stylex.props(styles.card).className}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.header).className}+ gap={10}+ >+ <Center className={stylex.props(styles.headerIcon).className}><FilePenLineIcon size={20} /></Center><Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>- <Text ellipsis className={styles.title}>+ <Text ellipsis className={stylex.props(styles.title).className}>{t('editedFiles.title', { count: entries.length })}</Text><LineStatshideZeroDeltas- className={styles.stats}+ className={stylex.props(styles.stats).className}linesAdded={totals.linesAdded}linesDeleted={totals.linesDeleted}/></Flexbox></Flexbox>- <Flexbox className={styles.list}>+ <Flexbox className={stylex.props(styles.list).className}>{visible.map((entry) => (<EditedFileRow entry={entry} key={entry.path} onOpen={getOpenAction(entry)} />))}@@ -433,7 +430,7 @@ const EditedFilesCard = memo<EditedFilesCardProps>(({ entries }) => {horizontalalign={'center'}aria-expanded={showAll}- className={styles.showMore}+ className={stylex.props(styles.showMore).className}gap={6}role={'button'}tabIndex={0}@@ -444,9 +441,9 @@ const EditedFilesCard = memo<EditedFilesCardProps>(({ entries }) => {? t('editedFiles.showLess'): t('editedFiles.showMore', { count: hiddenCount })}{showAll ? (- <ChevronUpIcon className={styles.chevron} size={14} />+ <ChevronUpIcon className={stylex.props(styles.chevron).className} size={14} />) : (- <ChevronDownIcon className={styles.chevron} size={14} />+ <ChevronDownIcon className={stylex.props(styles.chevron).className} size={14} />)}</Flexbox>)}diff --git a/src/features/Conversation/Messages/GoalTaskCard/PlanChain.tsx b/src/features/Conversation/Messages/GoalTaskCard/PlanChain.tsxindex 31fd49c904b..8fee6af5880 100644--- a/src/features/Conversation/Messages/GoalTaskCard/PlanChain.tsx+++ b/src/features/Conversation/Messages/GoalTaskCard/PlanChain.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, cx, Flexbox, Icon, Text } from '@lobehub/ui';+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ArrowRight, type LucideIcon, ShieldCheck } from 'lucide-react';import { Fragment, memo } from 'react';import { useTranslation } from 'react-i18next';@@ -71,51 +73,48 @@ const STEP_VISUAL: Record<},};-const styles = createStaticStyles(({ css }) => ({- arrow: css`- flex: none;- color: ${cssVar.colorTextQuaternary};- `,- more: css`- flex: none;-- padding-block: 3px;- padding-inline: 8px;- border-radius: 6px;-- font-size: 12px;- font-variant-numeric: tabular-nums;- color: ${cssVar.colorTextTertiary};-- background: ${cssVar.colorFillQuaternary};- `,- placeholder: css`- padding-block: 4px;- padding-inline: 10px;- border: 1px dashed ${cssVar.colorBorder};- border-radius: 6px;- `,- step: css`- overflow: hidden;-- /* Equal share of the row, so a long first title cannot squeeze the rest to a few characters. */- flex: 1 1 0;-- min-width: 0;- max-width: 240px;- padding-block: 4px;- padding-inline: 8px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 6px;- `,- stepOpen: css`- border-color: ${cssVar.colorBorder};- background: ${cssVar.colorFillTertiary};- `,- stepQueued: css`- border-style: dashed;- `,-}));+const styles = stylex.create({+ arrow: { flex: 'none', color: cssVar.colorTextQuaternary },+ more: {+ flex: 'none',+ paddingBlock: '3px',+ paddingInline: '8px',+ borderRadius: '6px',+ fontSize: '12px',+ fontVariantNumeric: 'tabular-nums',+ color: cssVar.colorTextTertiary,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ placeholder: {+ paddingBlock: '4px',+ paddingInline: '10px',+ borderWidth: '1px',+ borderStyle: 'dashed',+ borderColor: cssVar.colorBorder,+ borderRadius: '6px',+ },+ step: {+ overflow: 'hidden',+ flexGrow: 1,+ flexShrink: 1,+ flexBasis: '0',+ minWidth: '0',+ maxWidth: '240px',+ paddingBlock: '4px',+ paddingInline: '8px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: '6px',+ },+ stepOpen: {+ borderColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ stepQueued: { borderStyle: 'dashed' },+});const Step = memo<{ step: PlanStep }>(({ step }) => {const { t } = useTranslation('chat');@@ -128,11 +127,13 @@ const Step = memo<{ step: PlanStep }>(({ step }) => {align={'center'}gap={6}title={`${t(visual.labelKey as any)} · ${title}`}- className={cx(- styles.step,- visual.open && styles.stepOpen,- step.state === 'queued' && styles.stepQueued,- )}+ className={+ stylex.props(+ styles.step,+ visual.open && styles.stepOpen,+ step.state === 'queued' && styles.stepQueued,+ ).className+ }>{visual.icon ? (<Icon color={visual.color} icon={visual.icon} size={13} style={{ flex: 'none' }} />@@ -165,7 +166,11 @@ const PlanChain = memo<{if (steps.length === 0) {if (stage !== 'planning') return null;return (- <Flexbox horizontal className={styles.placeholder} style={{ alignSelf: 'flex-start' }}>+ <Flexbox+ horizontal+ className={stylex.props(styles.placeholder).className}+ style={{ alignSelf: 'flex-start' }}+ ><Text className={shinyTextStyles.shinyText} fontSize={12}>{t('goalTask.plan.drafting')}</Text>@@ -177,20 +182,22 @@ const PlanChain = memo<{<Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>{hiddenBefore > 0 && (<>- <span className={styles.more}>+{hiddenBefore}</span>- <Icon className={styles.arrow} icon={ArrowRight} size={12} />+ <span {...stylex.props(styles.more)}>+{hiddenBefore}</span>+ <Icon className={stylex.props(styles.arrow).className} icon={ArrowRight} size={12} /></>)}{steps.map((step, index) => (<Fragment key={step.id}>- {index > 0 && <Icon className={styles.arrow} icon={ArrowRight} size={12} />}+ {index > 0 && (+ <Icon className={stylex.props(styles.arrow).className} icon={ArrowRight} size={12} />+ )}<Step step={step} /></Fragment>))}{hiddenAfter > 0 && (<>- <Icon className={styles.arrow} icon={ArrowRight} size={12} />- <span className={styles.more}>+{hiddenAfter}</span>+ <Icon className={stylex.props(styles.arrow).className} icon={ArrowRight} size={12} />+ <span {...stylex.props(styles.more)}>+{hiddenAfter}</span></>)}</Flexbox>diff --git a/src/features/Conversation/Messages/GoalTaskCard/StageTrack.tsx b/src/features/Conversation/Messages/GoalTaskCard/StageTrack.tsxindex 0c650382cee..ed5e8d15219 100644--- a/src/features/Conversation/Messages/GoalTaskCard/StageTrack.tsx+++ b/src/features/Conversation/Messages/GoalTaskCard/StageTrack.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, cx, Flexbox, Text } from '@lobehub/ui';+import { Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { Fragment, memo } from 'react';import { useTranslation } from 'react-i18next';@@ -14,36 +16,38 @@ const TONE_COLOR: Record<GoalCardTone, string> = {waiting: cssVar.colorWarning,};-const styles = createStaticStyles(({ css }) => ({- connector: css`- flex: 1;- min-width: 12px;- height: 1px;- background: ${cssVar.colorBorder};- `,- connectorDone: css`- background: ${cssVar.colorSuccessBorder};- `,- dot: css`- flex: none;-- box-sizing: border-box;- width: 8px;- height: 8px;- border: 1px solid ${cssVar.colorTextQuaternary};- border-radius: 50%;- `,- dotCurrent: css`- width: 10px;- height: 10px;- border-width: 2px;- background: ${cssVar.colorBgElevated};- `,- dotDone: css`- border-color: ${cssVar.colorSuccess};- background: ${cssVar.colorSuccess};- `,-}));+const styles = stylex.create({+ connector: {+ flex: '1',+ minWidth: '12px',+ height: '1px',+ backgroundColor: cssVar.colorBorder,+ backgroundImage: 'none',+ },+ connectorDone: { backgroundColor: cssVar.colorSuccessBorder, backgroundImage: 'none' },+ dot: {+ flex: 'none',+ boxSizing: 'border-box',+ width: '8px',+ height: '8px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorTextQuaternary,+ borderRadius: '50%',+ },+ dotCurrent: {+ width: '10px',+ height: '10px',+ borderWidth: '2px',+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+ dotDone: {+ borderColor: cssVar.colorSuccess,+ backgroundColor: cssVar.colorSuccess,+ backgroundImage: 'none',+ },+});/*** The goal's big stages as one left-to-right track — where it stands in the@@ -63,12 +67,15 @@ const StageTrack = memo<{ stage: GoalCardStage; tone: GoalCardTone }>(({ stage,return (<Fragment key={key}>{index > 0 && (- <div className={cx(styles.connector, index <= current && styles.connectorDone)} />+ <div {...stylex.props(styles.connector, index <= current && styles.connectorDone)} />)}<Flexbox horizontal align={'center'} gap={6} style={{ flex: 'none' }}><span- className={cx(styles.dot, done && styles.dotDone, isCurrent && styles.dotCurrent)}style={isCurrent ? { borderColor: TONE_COLOR[tone] } : undefined}+ className={+ stylex.props(styles.dot, done && styles.dotDone, isCurrent && styles.dotCurrent)+ .className+ }/><TextfontSize={12}diff --git a/src/features/Conversation/Messages/GoalTaskCard/index.tsx b/src/features/Conversation/Messages/GoalTaskCard/index.tsxindex cf5bdc6599d..73becb5c9d6 100644--- a/src/features/Conversation/Messages/GoalTaskCard/index.tsx+++ b/src/features/Conversation/Messages/GoalTaskCard/index.tsx@@ -1,7 +1,9 @@'use client';import type { OperationGoal } from '@lobechat/builtin-tools/operationArtifacts';-import { createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';+import { Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronRightIcon } from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -20,38 +22,28 @@ import { useGoalTaskStatus } from './useGoalTaskStatus';const ACTIVE_PHASES = new Set<GoalTaskPhase>(['planning', 'repairing', 'running', 'verifying']);-const styles = createStaticStyles(({ css }) => ({- card: css`- cursor: pointer;-- width: 100%;- padding-block: 12px;- padding-inline: 14px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 10px;-- background: ${cssVar.colorBgElevated};-- &:hover {- border-color: ${cssVar.colorBorder};- }- `,- chevron: css`- flex-shrink: 0;- color: ${cssVar.colorTextTertiary};- `,- meta: css`- font-size: 12px;- font-variant-numeric: tabular-nums;- color: ${cssVar.colorTextTertiary};- white-space: nowrap;- `,- title: css`- min-width: 0;- font-size: 14px;- font-weight: 500;- `,-}));+const styles = stylex.create({+ card: {+ cursor: 'pointer',+ width: '100%',+ paddingBlock: '12px',+ paddingInline: '14px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: { 'default': cssVar.colorBorderSecondary, ':hover': cssVar.colorBorder },+ borderRadius: '10px',+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+ chevron: { flexShrink: 0, color: cssVar.colorTextTertiary },+ meta: {+ fontSize: '12px',+ fontVariantNumeric: 'tabular-nums',+ color: cssVar.colorTextTertiary,+ whiteSpace: 'nowrap',+ },+ title: { minWidth: '0', fontSize: '14px', fontWeight: 500 },+});const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {const { t } = useTranslation('chat');@@ -68,7 +60,7 @@ const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {return (<Flexbox- className={styles.card}+ className={stylex.props(styles.card).className}gap={12}role={'button'}tabIndex={0}@@ -86,14 +78,17 @@ const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {) : (<GoalStatusGlyph size={14} status={snapshot.goal.status} />)}- <Text ellipsis className={styles.title} style={{ flex: 1 }}>+ <Text ellipsis className={stylex.props(styles.title).className} style={{ flex: 1 }}>{title ?? goal.name}</Text>- <Text className={styles.meta} style={{ color: cssVar.colorTextSecondary }}>+ <Text+ className={stylex.props(styles.meta).className}+ style={{ color: cssVar.colorTextSecondary }}+ >{t(`goalTask.status.${progress.phase}`)}</Text>{isActive && <GoalElapsedTime startedAt={startedAt} />}- <ChevronRightIcon className={styles.chevron} size={16} />+ <ChevronRightIcon className={stylex.props(styles.chevron).className} size={16} /></Flexbox>{requirement && requirement !== (title ?? goal.name) && (<Text ellipsis fontSize={12} style={{ paddingInlineStart: 22 }} type={'secondary'}>@@ -108,22 +103,25 @@ const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {{(model.taskTotal > 0 || model.needsYou > 0 || model.totalCost > 0) && (<Flexbox horizontal align={'center'} gap={12}>{model.needsYou > 0 && (- <span className={styles.meta} style={{ color: cssVar.colorWarning }}>+ <span+ className={stylex.props(styles.meta).className}+ style={{ color: cssVar.colorWarning }}+ >{t('goalList.needsYou', { count: model.needsYou })}</span>)}{model.taskTotal > 0 && (- <span className={styles.meta}>+ <span {...stylex.props(styles.meta)}>{t('goalList.taskProgress', { done: model.taskDone, total: model.taskTotal })}</span>)}{model.findingCount > 0 && (- <span className={styles.meta}>+ <span {...stylex.props(styles.meta)}>{t('goalList.findings', { count: model.findingCount })}</span>)}{model.totalCost > 0 && (- <span className={styles.meta}>{formatGoalCost(model.totalCost)}</span>+ <span {...stylex.props(styles.meta)}>{formatGoalCost(model.totalCost)}</span>)}</Flexbox>)}diff --git a/src/features/Conversation/Messages/MessageWorks/index.tsx b/src/features/Conversation/Messages/MessageWorks/index.tsxindex dca308ba8b2..ece22c90d12 100644--- a/src/features/Conversation/Messages/MessageWorks/index.tsx+++ b/src/features/Conversation/Messages/MessageWorks/index.tsx@@ -1,7 +1,8 @@'use client';import type { WorkSummaryItem } from '@lobechat/types';-import { createStaticStyles, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import type { ComponentProps } from 'react';import { memo } from 'react';@@ -11,11 +12,7 @@ import WorkSummaryCard from '@/features/Work/WorkSummaryCard';import { dataSelectors, useConversationStore } from '../../store';import { useVisitorWorkOpen } from './useVisitorWorkOpen';-const styles = createStaticStyles(({ css }) => ({- container: css`- width: 100%;- `,-}));+const styles = stylex.create({ container: { width: '100%' } });interface MessageWorkListProps {items: WorkSummaryItem[];@@ -26,7 +23,7 @@ export const MessageWorkList = memo<MessageWorkListProps>(({ items, onOpen }) =>if (items.length === 0) return null;return (- <Flexbox className={styles.container} gap={8}>+ <Flexbox className={stylex.props(styles.container).className} gap={8}>{items.map((item) => (<WorkSummaryCard item={item} key={item.id} onOpen={onOpen} />))}diff --git a/src/features/Conversation/Messages/SignalCallbacks/index.tsx b/src/features/Conversation/Messages/SignalCallbacks/index.tsxindex 9e7a05526d5..5d6a49f9790 100644--- a/src/features/Conversation/Messages/SignalCallbacks/index.tsx+++ b/src/features/Conversation/Messages/SignalCallbacks/index.tsx@@ -1,42 +1,29 @@'use client';import { type UISignalCallbacksBlock } from '@lobechat/types';-import {- Accordion,- Block,- createStaticStyles,- cssVar,- Flexbox,- Icon,- Markdown,- Text,-} from '@lobehub/ui';+import { Accordion, Block, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { Radio } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-const styles = createStaticStyles(({ css }) => ({- callbackBody: css`- overflow: auto;- max-height: 360px;- `,- callbackItem: css`- padding-block: 4px;-- &:not(:last-child) {- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- }- `,- sequence: css`- flex: none;-- min-width: 20px;-- font-size: 11px;- font-feature-settings: 'tnum';- color: ${cssVar.colorTextTertiary};- `,-}));+const styles = stylex.create({+ callbackBody: { overflow: 'auto', maxHeight: '360px' },+ callbackItem: {+ paddingBlock: '4px',+ borderBlockEndWidth: { 'default': null, ':not(:last-child)': '1px' },+ borderBlockEndStyle: { 'default': null, ':not(:last-child)': 'solid' },+ borderBlockEndColor: { 'default': null, ':not(:last-child)': cssVar.colorBorderSecondary },+ },+ sequence: {+ flex: 'none',+ minWidth: '20px',+ fontSize: '11px',+ fontFeatureSettings: "'tnum'",+ color: cssVar.colorTextTertiary,+ },+});const SignalCallbacks = memo<{ block: UISignalCallbacksBlock }>(({ block }) => {const { t } = useTranslation('chat');@@ -52,7 +39,7 @@ const SignalCallbacks = memo<{ block: UISignalCallbacksBlock }>(({ block }) => {{children: (<Block- className={styles.callbackBody}+ className={stylex.props(styles.callbackBody).className}padding={12}style={{ marginBlock: 8 }}variant={'outlined'}@@ -65,12 +52,12 @@ const SignalCallbacks = memo<{ block: UISignalCallbacksBlock }>(({ block }) => {<Flexboxhorizontalalign="flex-start"- className={styles.callbackItem}+ className={stylex.props(styles.callbackItem).className}gap={8}key={cb.id}>{typeof cb.sequence === 'number' && (- <span className={styles.sequence}>#{cb.sequence}</span>+ <span {...stylex.props(styles.sequence)}>#{cb.sequence}</span>)}<Flexbox flex={1}><Markdown variant="chat">{cb.content}</Markdown>diff --git a/src/features/Conversation/Messages/Task/ClientTaskDetail/InitializingState.tsx b/src/features/Conversation/Messages/Task/ClientTaskDetail/InitializingState.tsxindex 0e4d5cd4138..0a4d8f2f330 100644--- a/src/features/Conversation/Messages/Task/ClientTaskDetail/InitializingState.tsx+++ b/src/features/Conversation/Messages/Task/ClientTaskDetail/InitializingState.tsx@@ -1,58 +1,19 @@'use client';-import { createStaticStyles, Flexbox, keyframes, Spin, Text } from '@lobehub/ui';+import { Flexbox, Spin, Text } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { shinyTextStyles } from '@/styles';-const shimmer = keyframes`- 0% {- transform: translateX(-100%);- }-- 100% {- transform: translateX(100%);- }-`;--const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- padding-block: 12px;- `,- progress: css`- position: relative;-- overflow: hidden;-- height: 3px;- border-radius: 2px;-- background: ${cssVar.colorFillSecondary};- `,- progressShimmer: css`- position: absolute;- inset-block-start: 0;- inset-inline-start: 0;-- width: 100%;- height: 100%;-- background: linear-gradient(90deg, transparent, ${cssVar.colorPrimaryBgHover}, transparent);-- animation: ${shimmer} 2s infinite;-- @media (prefers-reduced-motion: reduce) {- display: none;- }- `,-}));+const styles = stylex.create({ container: { paddingBlock: '12px' } });const InitializingState = memo(() => {const { t } = useTranslation('chat');return (- <Flexbox className={styles.container} gap={12}>+ <Flexbox className={stylex.props(styles.container).className} gap={12}><Flexbox horizontal align="center" gap={8}><Spin size="small" variant="network" /><Text className={shinyTextStyles.shinyText} weight={500}>diff --git a/src/features/Conversation/Messages/TaskCallback/index.tsx b/src/features/Conversation/Messages/TaskCallback/index.tsxindex 94718cc44d3..3616a3710a5 100644--- a/src/features/Conversation/Messages/TaskCallback/index.tsx+++ b/src/features/Conversation/Messages/TaskCallback/index.tsx@@ -1,6 +1,8 @@'use client';-import { Button, createStaticStyles, cssVar, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';+import { Button, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import { CircleAlert, CircleCheck, CircleSlash, SquareArrowOutUpRight } from 'lucide-react';import { memo } from 'react';@@ -10,22 +12,20 @@ import { useChatStore } from '@/store/chat';import { dataSelectors, useConversationStore } from '../../store';-const styles = createStaticStyles(({ css, cssVar }) => ({- card: css`- overflow: hidden;-- padding-block: 12px;- padding-inline: 16px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 16px;-- background: ${cssVar.colorBgElevated};- `,- identifier: css`- font-family: ${cssVar.fontFamilyCode};- color: ${cssVar.colorTextSecondary};- `,-}));+const styles = stylex.create({+ card: {+ overflow: 'hidden',+ paddingBlock: '12px',+ paddingInline: '16px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: '16px',+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+ identifier: { fontFamily: cssVar.fontFamilyCode, color: cssVar.colorTextSecondary },+});interface TaskCallbackMessageProps {id: string;@@ -77,12 +77,12 @@ const TaskCallbackMessage = memo<TaskCallbackMessageProps>(({ id }) => {return (<Flexbox paddingBlock={8}>- <Flexbox className={styles.card} gap={8}>+ <Flexbox className={stylex.props(styles.card).className} gap={8}><Flexbox horizontal align={'center'} gap={8} justify={'space-between'}><Flexbox horizontal align={'center'} gap={8}><Icon color={cssVar[color]} icon={icon} size={18} /><Text strong>{t(i18nKey)}</Text>- <span className={styles.identifier}>{callback.identifier}</span>+ <span {...stylex.props(styles.identifier)}>{callback.identifier}</span></Flexbox>{viewTaskButton}</Flexbox>diff --git a/src/features/Conversation/Messages/Tasks/shared/CompletedState.tsx b/src/features/Conversation/Messages/Tasks/shared/CompletedState.tsxindex df651050926..6eab8fc4fad 100644--- a/src/features/Conversation/Messages/Tasks/shared/CompletedState.tsx+++ b/src/features/Conversation/Messages/Tasks/shared/CompletedState.tsx@@ -2,7 +2,9 @@import { type TaskDetail } from '@lobechat/types';import { type IconProps } from '@lobehub/ui';-import { createStaticStyles, cssVar, Flexbox, Icon, Tag } from '@lobehub/ui';+import { Flexbox, Icon, Tag } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BrainCircuit, Timer, Wrench } from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -10,20 +12,16 @@ import { useTranslation } from 'react-i18next';import Markdown from '../../../Markdown';import { formatCost, formatDuration } from './utils';-const styles = createStaticStyles(({ css, cssVar }) => ({- collapseContent: css`- padding-block: 8px;- padding-inline: 0;- font-size: 13px;- line-height: 1.6;- `,- separator: css`- width: 3px;- height: 3px;- border-radius: 50%;- background: ${cssVar.colorTextQuaternary};- `,-}));+const styles = stylex.create({+ collapseContent: { paddingBlock: '8px', paddingInline: '0', fontSize: '13px', lineHeight: 1.6 },+ separator: {+ width: '3px',+ height: '3px',+ borderRadius: '50%',+ backgroundColor: cssVar.colorTextQuaternary,+ backgroundImage: 'none',+ },+});export type CompletedStateVariant = 'detail' | 'compact';@@ -126,7 +124,7 @@ const MetricsRow = memo<MetricsRowProps>(<Flexbox horizontal align="center" gap={12}>{metrics.map((metric, index) => (<Flexbox horizontal align="center" gap={12} key={index}>- {index > 0 && <div className={styles.separator} />}+ {index > 0 && <div {...stylex.props(styles.separator)} />}<MetricItem icon={metric.icon} label={metric.label} value={metric.value} /></Flexbox>))}@@ -175,7 +173,7 @@ const CompletedState = memo<CompletedStateProps>(return (<>{hasContent && expanded && (- <div className={styles.collapseContent}>+ <div {...stylex.props(styles.collapseContent)}><Markdown>{content}</Markdown></div>)}diff --git a/src/features/Conversation/Messages/Tasks/shared/ErrorState.tsx b/src/features/Conversation/Messages/Tasks/shared/ErrorState.tsxindex 3ea7fe0d348..5a7c007c855 100644--- a/src/features/Conversation/Messages/Tasks/shared/ErrorState.tsx+++ b/src/features/Conversation/Messages/Tasks/shared/ErrorState.tsx@@ -1,6 +1,8 @@'use client';-import { Alert, createStaticStyles, Flexbox, Highlighter } from '@lobehub/ui';+import { Alert, Flexbox, Highlighter } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { MessageSquare, Timer, Wrench } from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -11,28 +13,15 @@ import { ThreadStatus } from '@/types/index';import { MetricItem } from './CompletedState';import { formatCost, formatDuration } from './utils';-const styles = createStaticStyles(({ css, cssVar }) => ({- separator: css`- width: 3px;- height: 3px;- border-radius: 50%;- background: ${cssVar.colorTextQuaternary};- `,- statusIcon: css`- display: flex;- flex-shrink: 0;- align-items: center;- justify-content: center;-- width: 16px;- height: 16px;- border-radius: 50%;-- color: ${cssVar.colorErrorText};-- background: ${cssVar.colorErrorBg};- `,-}));+const styles = stylex.create({+ separator: {+ width: '3px',+ height: '3px',+ borderRadius: '50%',+ backgroundColor: cssVar.colorTextQuaternary,+ backgroundImage: 'none',+ },+});interface ErrorStateProps {taskDetail: TaskDetail;@@ -121,7 +110,7 @@ const ErrorState = memo<ErrorStateProps>(({ taskDetail }) => {{/* Tool Calls */}{totalToolCalls !== undefined && totalToolCalls > 0 && (<>- <div className={styles.separator} />+ <div {...stylex.props(styles.separator)} /><MetricItemicon={Wrench}label={t('task.metrics.toolCallsShort', { defaultValue: 'tools' })}@@ -133,7 +122,7 @@ const ErrorState = memo<ErrorStateProps>(({ taskDetail }) => {{/* Messages */}{totalMessages !== undefined && totalMessages > 0 && (<>- <div className={styles.separator} />+ <div {...stylex.props(styles.separator)} /><MetricItemicon={MessageSquare}label={t('task.metrics.messagesShort', { defaultValue: 'messages' })}@@ -145,7 +134,7 @@ const ErrorState = memo<ErrorStateProps>(({ taskDetail }) => {{/* Cost */}{formattedCost && (<>- <div className={styles.separator} />+ <div {...stylex.props(styles.separator)} /><MetricItem value={formattedCost} /></>)}diff --git a/src/features/Conversation/Messages/Tasks/shared/InitializingState.tsx b/src/features/Conversation/Messages/Tasks/shared/InitializingState.tsxindex 3f8f577cf30..950801df068 100644--- a/src/features/Conversation/Messages/Tasks/shared/InitializingState.tsx+++ b/src/features/Conversation/Messages/Tasks/shared/InitializingState.tsx@@ -1,6 +1,7 @@'use client';-import { createStaticStyles, Flexbox, keyframes, Spin, Text } from '@lobehub/ui';+import { Flexbox, Spin, Text } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -8,47 +9,7 @@ import { shinyTextStyles } from '@/styles';import { formatElapsedTime } from './utils';-const shimmer = keyframes`- 0% {- transform: translateX(-100%);- }-- 100% {- transform: translateX(100%);- }-`;--const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- padding-block: 12px;- `,- progress: css`- position: relative;-- overflow: hidden;-- height: 3px;- border-radius: 2px;-- background: ${cssVar.colorFillSecondary};- `,- progressShimmer: css`- position: absolute;- inset-block-start: 0;- inset-inline-start: 0;-- width: 100%;- height: 100%;-- background: linear-gradient(90deg, transparent, ${cssVar.colorPrimaryBgHover}, transparent);-- animation: ${shimmer} 2s infinite;-- @media (prefers-reduced-motion: reduce) {- display: none;- }- `,-}));+const styles = stylex.create({ container: { paddingBlock: '12px' } });const InitializingState = memo(() => {const { t } = useTranslation('chat');@@ -66,7 +27,7 @@ const InitializingState = memo(() => {}, []);return (- <Flexbox className={styles.container} gap={12}>+ <Flexbox className={stylex.props(styles.container).className} gap={12}><Flexbox horizontal align="center" gap={8}><Spin size="small" variant="network" /><Text className={shinyTextStyles.shinyText} weight={500}>diff --git a/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx b/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsxindex 1f7f2587313..a7647e149c2 100644--- a/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx+++ b/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx@@ -1,94 +1,84 @@'use client';import { type TaskDetail } from '@lobechat/types';-import { createStaticStyles, Flexbox, keyframes, Spin, Text } from '@lobehub/ui';+import { Flexbox, Spin, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BrainCircuit, Timer, Wrench } from 'lucide-react';import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { useChatStore } from '@/store/chat';+import { sx } from '@/styles/sx';import { MAX_PROGRESS, PROGRESS_INCREMENT, PROGRESS_INTERVAL } from './constants';import { formatElapsedTime, formatToolName } from './utils';-const shimmer = keyframes`- 0% {- transform: translateX(-100%);- }-- 100% {- transform: translateX(100%);- }-`;--const styles = createStaticStyles(({ css, cssVar }) => ({- activityRow: css`- display: flex;- gap: 8px;- align-items: center;- padding-block: 8px;- `,- footer: css`- padding-block-start: 8px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- `,- progress: css`- position: relative;-- overflow: hidden;-- height: 3px;- margin-block: 12px;- margin-inline: 8px;- border-radius: 2px;-- background: ${cssVar.colorFillSecondary};- `,- progressBar: css`- position: absolute;- inset-block-start: 0;- inset-inline-start: 0;-- height: 100%;- border-radius: 2px;-- background: linear-gradient(90deg, ${cssVar.colorPrimary}, ${cssVar.colorPrimaryHover});-- transition: width 0.5s ease-out;- `,- progressCompact: css`- position: relative;-- overflow: hidden;-- height: 3px;- border-radius: 2px;-- background: ${cssVar.colorFillSecondary};- `,- progressShimmer: css`- position: absolute;- inset-block-start: 0;- inset-inline-start: 0;-- width: 100%;- height: 100%;-- background: linear-gradient(90deg, transparent, ${cssVar.colorPrimaryBgHover}, transparent);-- animation: ${shimmer} 2s infinite;-- @media (prefers-reduced-motion: reduce) {- display: none;- }- `,- separator: css`- width: 3px;- height: 3px;- border-radius: 50%;- background: ${cssVar.colorTextQuaternary};- `,-}));+const shimmer = stylex.keyframes({+ '0%': { transform: 'translateX(-100%)' },+ '100%': { transform: 'translateX(100%)' },+});++const styles = stylex.create({+ activityRow: {+ display: 'flex',+ gap: '8px',+ alignItems: 'center',+ paddingBlock: '8px',+ },+ footer: {+ paddingBlockStart: '8px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ },+ progress: {+ position: 'relative',+ overflow: 'hidden',+ height: '3px',+ marginBlock: '12px',+ marginInline: '8px',+ borderRadius: '2px',+ backgroundColor: cssVar.colorFillSecondary,+ backgroundImage: 'none',+ },+ progressBar: {+ position: 'absolute',+ insetBlockStart: 0,+ insetInlineStart: 0,+ height: '100%',+ borderRadius: '2px',+ backgroundImage: `linear-gradient(90deg, ${cssVar.colorPrimary}, ${cssVar.colorPrimaryHover})`,+ transition: 'width 0.5s ease-out',+ },+ progressCompact: {+ position: 'relative',+ overflow: 'hidden',+ height: '3px',+ borderRadius: '2px',+ backgroundColor: cssVar.colorFillSecondary,+ backgroundImage: 'none',+ },+ progressShimmer: {+ position: 'absolute',+ insetBlockStart: 0,+ insetInlineStart: 0,+ display: { 'default': null, '@media (prefers-reduced-motion: reduce)': 'none' },+ width: '100%',+ height: '100%',+ backgroundImage: `linear-gradient(90deg, transparent, ${cssVar.colorPrimaryBgHover}, transparent)`,+ animationName: shimmer,+ animationDuration: '2s',+ animationIterationCount: 'infinite',+ },+ separator: {+ width: '3px',+ height: '3px',+ borderRadius: '50%',+ backgroundColor: cssVar.colorTextQuaternary,+ backgroundImage: 'none',+ },+});export type ProcessingStateVariant = 'detail' | 'compact';@@ -202,7 +192,7 @@ const ProcessingState = memo<ProcessingStateProps>(<Flexbox>{/* Current Activity */}{currentActivity && (- <div className={styles.activityRow}>+ <div {...stylex.props(styles.activityRow)}><Flexbox horizontal align={'center'} gap={4}><Spin size="small" variant="network" /><Text as={'span'} fontSize={12} type={'secondary'}>@@ -224,16 +214,16 @@ const ProcessingState = memo<ProcessingStateProps>()}{/* Progress Bar */}- <div className={styles.progress}>- <div className={styles.progressBar} style={{ width: `${progress}%` }} />- <div className={styles.progressShimmer} />+ <div {...stylex.props(styles.progress)}>+ <div {...sx([styles.progressBar], undefined, { width: `${progress}%` })} />+ <div {...stylex.props(styles.progressShimmer)} /></div>{/* Footer with metrics */}<Flexboxhorizontalalign="center"- className={styles.footer}+ className={stylex.props(styles.footer).className}gap={12}justify={'space-between'}wrap="wrap"@@ -264,7 +254,7 @@ const ProcessingState = memo<ProcessingStateProps>({totalToolCalls !== undefined && totalToolCalls > 0 && (<>{hasMetrics && totalSteps !== undefined && totalSteps > 0 && (- <div className={styles.separator} />+ <div {...stylex.props(styles.separator)} />)}<Text as={'span'} fontSize={12} type={'secondary'}><Wrench size={12} />@@ -301,9 +291,9 @@ const ProcessingState = memo<ProcessingStateProps>()}{/* Progress Bar */}- <div className={styles.progressCompact}>- <div className={styles.progressBar} style={{ width: `${progress}%` }} />- <div className={styles.progressShimmer} />+ <div {...stylex.props(styles.progressCompact)}>+ <div {...sx([styles.progressBar], undefined, { width: `${progress}%` })} />+ <div {...stylex.props(styles.progressShimmer)} /></div>{/* Footer with metrics */}@@ -311,7 +301,7 @@ const ProcessingState = memo<ProcessingStateProps>(<Flexboxhorizontalalign="center"- className={styles.footer}+ className={stylex.props(styles.footer).className}gap={12}justify="space-between"wrap="wrap"@@ -342,7 +332,7 @@ const ProcessingState = memo<ProcessingStateProps>({totalToolCalls !== undefined && totalToolCalls > 0 && (<>{totalSteps !== undefined && totalSteps > 0 && (- <div className={styles.separator} />+ <div {...stylex.props(styles.separator)} />)}<Text as={'span'} fontSize={12} type={'secondary'}><Wrench size={12} />diff --git a/src/features/Conversation/Messages/Tasks/shared/TaskMessages.tsx b/src/features/Conversation/Messages/Tasks/shared/TaskMessages.tsxindex 62d9e794975..8bae5f3d097 100644--- a/src/features/Conversation/Messages/Tasks/shared/TaskMessages.tsx+++ b/src/features/Conversation/Messages/Tasks/shared/TaskMessages.tsx@@ -1,17 +1,9 @@'use client';import { type AssistantContentBlock, type UIChatMessage } from '@lobechat/types';-import {- Accordion,- Block,- createStaticStyles,- cssVar,- Flexbox,- Icon,- Markdown,- Spin,- Text,-} from '@lobehub/ui';+import { Accordion, Block, Flexbox, Icon, Markdown, Spin, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ScrollText, Workflow } from 'lucide-react';import { memo, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -27,12 +19,7 @@ import Usage from '../../components/Extras/Usage';import AnimatedNumber from '../../components/Extras/Usage/UsageDetail/AnimatedNumber';import { accumulateUsage, formatDuration, formatElapsedTime } from './utils';-const styles = createStaticStyles(({ css }) => ({- instructionContent: css`- overflow: auto;- max-height: 300px;- `,-}));+const styles = stylex.create({ instructionContent: { overflow: 'auto', maxHeight: '300px' } });/*** InstructionAccordion - Shows the task instruction in a collapsible accordion@@ -60,7 +47,7 @@ const InstructionAccordion = memo<{ childrenCount: number; instruction: string }{children: (<Block- className={styles.instructionContent}+ className={stylex.props(styles.instructionContent).className}padding={12}style={{ marginBlock: 8 }}variant={'outlined'}diff --git a/src/features/Conversation/Messages/User/components/AgentSenderSourceLink.tsx b/src/features/Conversation/Messages/User/components/AgentSenderSourceLink.tsxindex 8a5b6bd2715..3e70c4ce160 100644--- a/src/features/Conversation/Messages/User/components/AgentSenderSourceLink.tsx+++ b/src/features/Conversation/Messages/User/components/AgentSenderSourceLink.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, Icon, Tooltip } from '@lobehub/ui';+import { Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { Link2 } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -8,35 +10,21 @@ import { useTranslation } from 'react-i18next';import { buildOperationSourcePath } from '@/features/Portal/Thread/sharePath';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';-const styles = createStaticStyles(({ css, cssVar }) => ({- link: css`- display: inline-flex;-- /* Shrinkable, not fixed: the header is a non-wrapping flex row, so on a- phone-width viewport the cap below plus the author name and avatar would- overflow the row — the inner ellipsis can only truncate a link that is- allowed to shrink past its content. */- flex: 0 1 auto;- gap: 3px;- align-items: center;-- min-inline-size: 0;- max-inline-size: 320px;-- font-size: 12px;- color: ${cssVar.colorTextTertiary};-- &:hover {- color: ${cssVar.colorTextSecondary};- }- `,- label: css`- overflow: hidden;- min-inline-size: 0;- text-overflow: ellipsis;- white-space: nowrap;- `,-}));+const styles = stylex.create({+ link: {+ display: 'inline-flex',+ flexGrow: 0,+ flexShrink: 1,+ flexBasis: 'auto',+ gap: '3px',+ alignItems: 'center',+ minInlineSize: '0',+ maxInlineSize: '320px',+ fontSize: '12px',+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorTextSecondary },+ },+ label: { overflow: 'hidden', minInlineSize: '0', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },+});interface AgentSenderSourceLinkProps {/**@@ -96,9 +84,9 @@ const AgentSenderSourceLink = memo<AgentSenderSourceLinkProps>({/* `WorkspaceLink`, not the bare router `Link`: these routes are mirroredunder `/:workspaceSlug`, so an unprefixed href would drop a workspacereader into their personal route and the source would not load. */}- <WorkspaceLink className={styles.link} to={href}>+ <WorkspaceLink className={stylex.props(styles.link).className} to={href}><Icon icon={Link2} size={12} />- <span className={styles.label}>{name || caption}</span>+ <span {...stylex.props(styles.label)}>{name || caption}</span></WorkspaceLink></Tooltip>);diff --git a/src/features/Conversation/Messages/User/components/PageSelections.tsx b/src/features/Conversation/Messages/User/components/PageSelections.tsxindex ecad4395440..9b992d66df3 100644--- a/src/features/Conversation/Messages/User/components/PageSelections.tsx+++ b/src/features/Conversation/Messages/User/components/PageSelections.tsx@@ -1,4 +1,6 @@-import { createStaticStyles, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { Code2Icon, SquareDashedMousePointer } from 'lucide-react';import { memo } from 'react';@@ -6,113 +8,99 @@ import type { ContextSelection, ElementContextSelection, PageSelection } from '@type UserContextSelection = ContextSelection | PageSelection;-const styles = createStaticStyles(({ css, cssVar }) => ({- codeContainer: css`- cursor: pointer;-- overflow: hidden;-- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 8px;-- background: ${cssVar.colorFillQuaternary};-- :hover {- border-color: ${cssVar.colorBorder};- background: ${cssVar.colorFillTertiary};- }- `,- codeContent: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 4;-- margin: 0;- padding-block: 8px;- padding-inline: 10px;-- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- line-height: 1.55;- color: ${cssVar.colorTextSecondary};- white-space: pre;- `,- codeHeader: css`- overflow: hidden;- align-items: center;-- padding-block: 6px;- padding-inline: 10px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};-- color: ${cssVar.colorTextTertiary};- `,- codeMeta: css`- overflow: hidden;-- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- text-overflow: ellipsis;- white-space: nowrap;- `,- container: css`- cursor: pointer;- position: relative;- border-radius: 8px;-- :hover {- background: ${cssVar.colorFillQuaternary};- }- `,- content: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 3;-- font-size: 12px;- line-height: 1.5;- color: ${cssVar.colorTextSecondary};- white-space: pre-wrap;- `,- elementText: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 3;-- padding-block: 8px;- padding-inline: 10px;-- font-size: 12px;- line-height: 1.5;- color: ${cssVar.colorTextSecondary};- `,- elementThumbnail: css`- display: block;-- max-width: 100%;- max-height: 200px;- margin-block: 8px;- margin-inline: 10px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 6px;-- object-fit: contain;- background: ${cssVar.colorBgContainer};- `,- quote: css`- inset-block-start: 2px;- inset-inline-start: 0;-- font-family: Georgia, serif;- font-size: 28px;- line-height: 1;- color: ${cssVar.colorTextQuaternary};- `,- wrapper: css``,-}));+const styles = stylex.create({+ codeContainer: {+ cursor: 'pointer',+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: { 'default': cssVar.colorBorderSecondary, ':hover': cssVar.colorBorder },+ borderRadius: '8px',+ backgroundColor: { 'default': cssVar.colorFillQuaternary, ':hover': cssVar.colorFillTertiary },+ backgroundImage: 'none',+ },+ codeContent: {+ overflow: 'hidden',+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: '4',+ margin: '0',+ paddingBlock: '8px',+ paddingInline: '10px',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: '12px',+ lineHeight: 1.55,+ color: cssVar.colorTextSecondary,+ whiteSpace: 'pre',+ },+ codeHeader: {+ overflow: 'hidden',+ alignItems: 'center',+ paddingBlock: '6px',+ paddingInline: '10px',+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ color: cssVar.colorTextTertiary,+ },+ codeMeta: {+ overflow: 'hidden',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: '12px',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ container: {+ cursor: 'pointer',+ position: 'relative',+ borderRadius: '8px',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ content: {+ overflow: 'hidden',+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: '3',+ fontSize: '12px',+ lineHeight: 1.5,+ color: cssVar.colorTextSecondary,+ whiteSpace: 'pre-wrap',+ },+ elementText: {+ overflow: 'hidden',+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: '3',+ paddingBlock: '8px',+ paddingInline: '10px',+ fontSize: '12px',+ lineHeight: 1.5,+ color: cssVar.colorTextSecondary,+ },+ elementThumbnail: {+ display: 'block',+ maxWidth: '100%',+ maxHeight: '200px',+ marginBlock: '8px',+ marginInline: '10px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: '6px',+ objectFit: 'contain',+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ quote: {+ insetBlockStart: '2px',+ insetInlineStart: 0,+ fontFamily: 'Georgia, serif',+ fontSize: '28px',+ lineHeight: 1,+ color: cssVar.colorTextQuaternary,+ },+});interface PageSelectionsProps {selections: UserContextSelection[];@@ -140,12 +128,12 @@ const getCodeSelectionMeta = (selection: ContextSelection): string => {};const CodeSelection = memo<{ selection: ContextSelection }>(({ selection }) => (- <Flexbox className={styles.codeContainer}>- <Flexbox horizontal className={styles.codeHeader} gap={6}>+ <Flexbox className={stylex.props(styles.codeContainer).className}>+ <Flexbox horizontal className={stylex.props(styles.codeHeader).className} gap={6}><Code2Icon size={14} />- <div className={styles.codeMeta}>{getCodeSelectionMeta(selection)}</div>+ <div {...stylex.props(styles.codeMeta)}>{getCodeSelectionMeta(selection)}</div></Flexbox>- <pre className={styles.codeContent}>{selection.content}</pre>+ <pre {...stylex.props(styles.codeContent)}>{selection.content}</pre></Flexbox>));@@ -153,21 +141,21 @@ CodeSelection.displayName = 'UserMessageCodeSelection';/** A picked DOM element renders as what it is — its crop and locator, not a quote. */const ElementSelection = memo<{ selection: ElementContextSelection }>(({ selection }) => (- <Flexbox className={styles.codeContainer}>- <Flexbox horizontal className={styles.codeHeader} gap={6}>+ <Flexbox className={stylex.props(styles.codeContainer).className}>+ <Flexbox horizontal className={stylex.props(styles.codeHeader).className} gap={6}><SquareDashedMousePointer size={14} />- <div className={styles.codeMeta}>+ <div {...stylex.props(styles.codeMeta)}>{selection.element.selector || `<${selection.element.tag}>`}</div></Flexbox>{selection.element.thumbnailUrl ? (<imgalt={selection.element.selector || selection.element.tag}- className={styles.elementThumbnail}+ {...stylex.props(styles.elementThumbnail)}src={selection.element.thumbnailUrl}/>) : (- <div className={styles.elementText}>{selection.preview || selection.content}</div>+ <div {...stylex.props(styles.elementText)}>{selection.preview || selection.content}</div>)}</Flexbox>));@@ -175,10 +163,10 @@ const ElementSelection = memo<{ selection: ElementContextSelection }>(({ selectiElementSelection.displayName = 'UserMessageElementSelection';const QuoteSelection = memo<{ selection: UserContextSelection }>(({ selection }) => (- <Flexbox className={styles.container}>- <Flexbox horizontal className={styles.wrapper} gap={4} padding={4}>- <span className={styles.quote}>"</span>- <div className={styles.content}>{selection.content}</div>+ <Flexbox className={stylex.props(styles.container).className}>+ <Flexbox horizontal gap={4} padding={4}>+ <span {...stylex.props(styles.quote)}>"</span>+ <div {...stylex.props(styles.content)}>{selection.content}</div></Flexbox></Flexbox>));diff --git a/src/features/Conversation/Messages/User/components/ReferencedMessage.tsx b/src/features/Conversation/Messages/User/components/ReferencedMessage.tsxindex d4427219e71..d483d0b00bb 100644--- a/src/features/Conversation/Messages/User/components/ReferencedMessage.tsx+++ b/src/features/Conversation/Messages/User/components/ReferencedMessage.tsx@@ -1,57 +1,56 @@-import { createStaticStyles, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { Reply } from 'lucide-react';import { memo } from 'react';import type { ReferencedMessage as ReferencedMessageData } from '@/store/chat/utils/parseReferencedMessage';-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- overflow: hidden;-- padding-block: 6px;- padding-inline: 10px;- border-inline-start: 3px solid ${cssVar.colorBorder};- border-radius: 6px;-- font-size: 12px;- line-height: 1.5;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillQuaternary};- `,- header: css`- align-items: center;- font-weight: 500;- color: ${cssVar.colorTextTertiary};- `,- quote: css`- font-style: italic;- overflow-wrap: anywhere;- white-space: pre-wrap;- `,- text: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 4;-- overflow-wrap: anywhere;- white-space: pre-wrap;- `,-}));+const styles = stylex.create({+ container: {+ overflow: 'hidden',+ paddingBlock: '6px',+ paddingInline: '10px',+ borderInlineStartWidth: '3px',+ borderInlineStartStyle: 'solid',+ borderInlineStartColor: cssVar.colorBorder,+ borderRadius: '6px',+ fontSize: '12px',+ lineHeight: 1.5,+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ header: { alignItems: 'center', fontWeight: 500, color: cssVar.colorTextTertiary },+ quote: { fontStyle: 'italic', overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' },+ text: {+ overflow: 'hidden',+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: '4',+ overflowWrap: 'anywhere',+ whiteSpace: 'pre-wrap',+ },+});/*** The message a bot-channel user replied to, rendered as a quote above their* text instead of the raw `<referenced_message>` prompt markup.*/const ReferencedMessage = memo<{ reference: ReferencedMessageData }>(({ reference }) => (- <Flexbox className={styles.container} data-testid="referenced-message" gap={2}>- <Flexbox horizontal className={styles.header} gap={4}>+ <Flexbox+ className={stylex.props(styles.container).className}+ data-testid="referenced-message"+ gap={2}+ >+ <Flexbox horizontal className={stylex.props(styles.header).className} gap={4}><Reply size={12} /><span>{reference.sender}</span></Flexbox>- {reference.text && <div className={styles.text}>{reference.text}</div>}- {reference.selectedQuote && <div className={styles.quote}>“{reference.selectedQuote}”</div>}+ {reference.text && <div {...stylex.props(styles.text)}>{reference.text}</div>}+ {reference.selectedQuote && (+ <div {...stylex.props(styles.quote)}>“{reference.selectedQuote}”</div>+ )}</Flexbox>));diff --git a/src/features/Conversation/Messages/User/components/ScmEventSender.tsx b/src/features/Conversation/Messages/User/components/ScmEventSender.tsxindex b91f2838e88..11c06702f71 100644--- a/src/features/Conversation/Messages/User/components/ScmEventSender.tsx+++ b/src/features/Conversation/Messages/User/components/ScmEventSender.tsx@@ -1,5 +1,7 @@import { Github } from '@lobehub/icons';-import { createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import {@@ -8,40 +10,31 @@ import {scmEventTitle,} from '@/features/Conversation/Markdown/plugins/ScmEvent/parseScmEvent';-const styles = createStaticStyles(({ css, cssVar }) => ({- link: css`- display: inline-flex;- gap: 4px;- align-items: center;- color: inherit;-- &:hover {- color: ${cssVar.colorTextSecondary};- }- `,- mark: css`- display: flex;- flex: none;- align-items: center;- justify-content: center;-- inline-size: 36px;- block-size: 36px;- border-radius: 8px;-- color: ${cssVar.colorText};-- background: ${cssVar.colorFillTertiary};- `,- mono: css`- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- `,-}));+const styles = stylex.create({+ link: {+ display: 'inline-flex',+ gap: '4px',+ alignItems: 'center',+ color: { 'default': 'inherit', ':hover': cssVar.colorTextSecondary },+ },+ mark: {+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ inlineSize: '36px',+ blockSize: '36px',+ borderRadius: '8px',+ color: cssVar.colorText,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ mono: { fontFamily: cssVar.fontFamilyCode, fontSize: '12px' },+});/** GitHub mark standing in for the avatar of a wake-up message. */export const ScmEventAvatar = memo(() => (- <span className={styles.mark}>+ <span {...stylex.props(styles.mark)}><Github size={20} /></span>));@@ -63,7 +56,7 @@ export const ScmEventSenderTitle = memo<{ source: ScmEventAttributes }>(({ sourc<Flexbox align={'flex-end'} gap={2} style={{ minWidth: 0 }}><Text style={{ whiteSpace: 'nowrap' }} weight={500}>{url ? (- <a className={styles.link} href={url} rel="noreferrer" target="_blank">+ <a {...stylex.props(styles.link)} href={url} rel="noreferrer" target="_blank">{title}</a>) : (@@ -71,7 +64,7 @@ export const ScmEventSenderTitle = memo<{ source: ScmEventAttributes }>(({ sourc)}</Text>{subtitle ? (- <Text ellipsis className={styles.mono} type={'secondary'}>+ <Text ellipsis className={stylex.props(styles.mono).className} type={'secondary'}>{subtitle}</Text>) : null}diff --git a/src/features/Conversation/Messages/User/components/richTextImageRenderers.tsx b/src/features/Conversation/Messages/User/components/richTextImageRenderers.tsxindex f68f27acd8b..ba1532de94d 100644--- a/src/features/Conversation/Messages/User/components/richTextImageRenderers.tsx+++ b/src/features/Conversation/Messages/User/components/richTextImageRenderers.tsx@@ -1,18 +1,12 @@import type { NodeRenderer } from '@lobehub/editor/renderer';-import { createStaticStyles, Image } from '@lobehub/ui';+import { Image } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import type { CSSProperties } from 'react';-const styles = createStaticStyles(({ css }) => ({- blockImage: css`- position: relative;- display: block;- text-align: center;- `,- image: css`- position: relative;- display: inline-block;- `,-}));+const styles = stylex.create({+ blockImage: { position: 'relative', display: 'block', textAlign: 'center' },+ image: { position: 'relative', display: 'inline-block' },+});/*** The stored size the author picked with the resize handles. Mirrors the@@ -48,7 +42,7 @@ const renderPreviewableImage = (node: Record<string, any>,key: string,Wrapper: 'figure' | 'span',- className: string,+ className?: string,) => (<Wrapper className={className} key={key}><Image@@ -68,6 +62,8 @@ const renderPreviewableImage = (* in a `PreviewGroup` so several images in one message become a gallery.*/export const richTextImageRenderers: Record<string, NodeRenderer> = {- 'block-image': (node, key) => renderPreviewableImage(node, key, 'figure', styles.blockImage),- 'image': (node, key) => renderPreviewableImage(node, key, 'span', styles.image),+ 'block-image': (node, key) =>+ renderPreviewableImage(node, key, 'figure', stylex.props(styles.blockImage).className),+ 'image': (node, key) =>+ renderPreviewableImage(node, key, 'span', stylex.props(styles.image).className),};diff --git a/src/features/Conversation/Messages/Verify/index.tsx b/src/features/Conversation/Messages/Verify/index.tsxindex 68068ec7b92..e81a492e13f 100644--- a/src/features/Conversation/Messages/Verify/index.tsx+++ b/src/features/Conversation/Messages/Verify/index.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import { memo } from 'react';@@ -10,14 +12,17 @@ import { phaseCardBackground, phaseFromStatus } from '@/features/Acceptance/utilimport { contextSelectors, dataSelectors, useConversationStore } from '../../store';-const styles = createStaticStyles(({ css, cssVar }) => ({- card: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 16px;- background: ${cssVar.colorBgElevated};- `,-}));+const styles = stylex.create({+ card: {+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: '16px',+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+});interface VerifyMessageProps {id: string;@@ -48,7 +53,10 @@ const VerifyMessage = memo<VerifyMessageProps>(({ id }) => {return (<Flexbox paddingBlock={8}>- <div className={styles.card} style={{ background: phaseCardBackground(phase, cssVar) }}>+ <div+ className={stylex.props(styles.card).className}+ style={{ background: phaseCardBackground(phase, cssVar) }}+ ><RunResult embedded operationId={operationId} round={ordinal} /><CheckerDock embedded operationId={operationId} /></div>diff --git a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/ModelCard.tsx b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/ModelCard.tsxindex edba57f0645..b9ef7048025 100644--- a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/ModelCard.tsx+++ b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/ModelCard.tsx@@ -1,5 +1,7 @@import { getCachedTextInputUnitRate, getWriteCacheInputUnitRate } from '@lobechat/utils';-import { createStaticStyles, Flexbox, Icon, Tabs, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Tabs, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ArrowDownToDot, ArrowUpFromDot, BookUp2Icon, CircleFadingArrowUp } from 'lucide-react';import { type LobeDefaultAiModelListItem } from 'model-bank';import { memo } from 'react';@@ -11,20 +13,10 @@ import { systemStatusSelectors } from '@/store/global/selectors';import { getPrice } from './pricing';-export const styles = createStaticStyles(({ css, cssVar }) => {- return {- container: css`- font-size: 12px;- `,- desc: css`- line-height: 12px;- color: ${cssVar.colorTextDescription};- `,- pricing: css`- font-size: 12px;- color: ${cssVar.colorTextSecondary};- `,- };+export const styles = stylex.create({+ container: { fontSize: '12px' },+ desc: { lineHeight: '12px', color: cssVar.colorTextDescription },+ pricing: { fontSize: '12px', color: cssVar.colorTextSecondary },});interface ModelCardProps extends LobeDefaultAiModelListItem {@@ -44,7 +36,7 @@ const ModelCard = memo<ModelCardProps>(({ pricing, id, provider, displayName })<Flexboxhorizontalalign={'center'}- className={styles.container}+ className={stylex.props(styles.container).className}flex={1}gap={40}justify={'space-between'}@@ -55,7 +47,7 @@ const ModelCard = memo<ModelCardProps>(({ pricing, id, provider, displayName })<Flexbox horizontal align={'center'} gap={8} style={{ lineHeight: '12px' }}>{displayName || id}</Flexbox>- <span className={styles.desc}>{provider}</span>+ <span {...stylex.props(styles.desc)}>{provider}</span></Flexbox></Flexbox>{!!pricing && (@@ -84,7 +76,12 @@ const ModelCard = memo<ModelCardProps>(({ pricing, id, provider, displayName }){isShowCredit ? (<Flexbox horizontal justify={'space-between'}><div />- <Flexbox horizontal align={'center'} className={styles.pricing} gap={8}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.pricing).className}+ gap={8}+ >{t('messages.modelCard.creditPricing')}:{getCachedTextInputUnitRate(pricing) && (<Tooltipdiff --git a/src/features/Conversation/Messages/components/Extras/Usage/index.tsx b/src/features/Conversation/Messages/components/Extras/Usage/index.tsxindex 45741be299c..60e56ad2777 100644--- a/src/features/Conversation/Messages/components/Extras/Usage/index.tsx+++ b/src/features/Conversation/Messages/components/Extras/Usage/index.tsx@@ -4,7 +4,9 @@ import {} from '@lobechat/heterogeneous-agents';import type { ModelPerformance, ModelUsage } from '@lobechat/types';import { unwrapServerDefaultHeterogeneousModel } from '@lobechat/types';-import { Center, createStaticStyles, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { Center, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import { CircleDollarSignIcon, CoinsIcon } from 'lucide-react';import { memo } from 'react';@@ -22,13 +24,9 @@ import { formatNumber } from '@/utils/format';import { contextSelectors, useConversationStore } from '../../../../store';import TokenDetail from './UsageDetail';-export const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- font-size: 12px;- color: ${cssVar.colorTextQuaternary};- white-space: nowrap;- `,-}));+export const styles = stylex.create({+ container: { fontSize: '12px', color: cssVar.colorTextQuaternary, whiteSpace: 'nowrap' },+});// Cheap messages don't need a cost callout — only surface it once it's// expensive enough to matter.@@ -87,7 +85,7 @@ const Usage = memo<UsageProps>(({ model, usage, performance, provider }) => {<Flexboxhorizontalalign={'center'}- className={styles.container}+ className={stylex.props(styles.container).className}gap={12}justify={'space-between'}>diff --git a/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsx b/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsxindex 022ea1b80fe..7813dbe25a9 100644--- a/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsx+++ b/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsx@@ -1,5 +1,6 @@import { type ChatFileChunk } from '@lobechat/types';-import { Center, cx, Flexbox, Text, Tooltip } from '@lobehub/ui';+import { Center, Flexbox, Text, Tooltip } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import FileIcon from '@/components/FileIcon';@@ -21,9 +22,12 @@ const ChunkItem = memo<ChunkItemProps>(({ id, fileId, similarity, text, filename<Flexboxhorizontalalign={'center'}- className={cx(styles.container, isDarkMode ? styles.containerDark : styles.containerLight)}gap={4}key={id}+ className={+ stylex.props(styles.container, isDarkMode ? styles.containerDark : styles.containerLight)+ .className+ }onClick={(e) => {e.stopPropagation();openFilePreview({ chunkId: id, chunkText: text, fileId });@@ -34,7 +38,9 @@ const ChunkItem = memo<ChunkItemProps>(({ id, fileId, similarity, text, filename<Text ellipsis>{filename}</Text>{similarity && (<Tooltip title={similarity}>- <Center className={styles.badge}>{similarity.toFixed(1)}</Center>+ <Center className={stylex.props(styles.badge).className}>+ {similarity.toFixed(1)}+ </Center></Tooltip>)}</Flexbox>diff --git a/src/features/Conversation/Messages/components/FileChunks/index.tsx b/src/features/Conversation/Messages/components/FileChunks/index.tsxindex 54ddb95581f..1792491ecff 100644--- a/src/features/Conversation/Messages/components/FileChunks/index.tsx+++ b/src/features/Conversation/Messages/components/FileChunks/index.tsx@@ -1,5 +1,7 @@import { type ChatFileChunk } from '@lobechat/types';-import { createStaticStyles, cssVar, cx, Flexbox, Icon } from '@lobehub/ui';+import { Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BookOpenTextIcon, ChevronDown, ChevronRight } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -8,39 +10,23 @@ import { useIsDark } from '@/hooks/useIsDark';import ChunkItem from './ChunkItem';-const styles = createStaticStyles(({ css }) => ({- container: css`- cursor: pointer;-- padding-block: 8px;- padding-inline: 12px;- padding-inline-end: 12px;- border-radius: 8px;-- color: ${cssVar.colorText};-- background: ${cssVar.colorFillTertiary};- `,- containerDark: css`- &:hover {- background: '';- }- `,- containerLight: css`- &:hover {- background: ${cssVar.colorFillSecondary};- }- `,- title: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 1;-- font-size: 12px;- text-overflow: ellipsis;- `,-}));+const styles = stylex.create({+ container: {+ cursor: 'pointer',+ paddingBlock: '8px',+ paddingInline: '12px',+ borderRadius: '8px',+ color: cssVar.colorText,+ },+ containerDark: {+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ containerLight: {+ backgroundColor: { 'default': cssVar.colorFillTertiary, ':hover': cssVar.colorFillSecondary },+ backgroundImage: 'none',+ },+});interface FileChunksProps {data: ChatFileChunk[];@@ -54,9 +40,12 @@ const FileChunks = memo<FileChunksProps>(({ data }) => {return (<Flexbox- className={cx(styles.container, isDarkMode ? styles.containerDark : styles.containerLight)}gap={16}width={'100%'}+ className={+ stylex.props(styles.container, isDarkMode ? styles.containerDark : styles.containerLight)+ .className+ }onClick={() => {setShowDetail(!showDetail);}}diff --git a/src/features/Conversation/Messages/components/FileChunks/style.ts b/src/features/Conversation/Messages/components/FileChunks/style.tsindex bc3e7b62938..01e30223e1a 100644--- a/src/features/Conversation/Messages/components/FileChunks/style.ts+++ b/src/features/Conversation/Messages/components/FileChunks/style.ts@@ -1,59 +1,38 @@-import { createStaticStyles } from '@lobehub/ui';--export const styles = createStaticStyles(({ css, cssVar }) => ({- badge: css`- padding-block: 4px;- padding-inline: 6px;- border-radius: 2222px;-- font-size: 12px;- line-height: 12px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillSecondary};- `,-- container: css`- cursor: pointer;-- width: fit-content;- padding-block: 6px;- padding-inline: 8px;- padding-inline-end: 12px;- border-radius: 8px;-- color: ${cssVar.colorText};-- background: color-mix(in srgb, ${cssVar.colorBgElevated} 90%, white);- box-shadow: ${cssVar.boxShadowTertiary};-- transition: all 0.2s;-- &:hover {- box-shadow: ${cssVar.boxShadowSecondary};- }- `,- containerDark: css`- &:hover {- background: color-mix(in srgb, ${cssVar.colorBgElevated} 85%, white);- }- `,- containerLight: css`- &:hover {- background: '';- }- `,- filename: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 1;-- font-size: 12px;- text-overflow: ellipsis;- `,-- mobile: css`- width: 100%;- `,-}));+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++export const styles = stylex.create({+ badge: {+ paddingBlock: '4px',+ paddingInline: '6px',+ borderRadius: '2222px',+ fontSize: '12px',+ lineHeight: '12px',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillSecondary,+ backgroundImage: 'none',+ },+ container: {+ cursor: 'pointer',+ width: 'fit-content',+ paddingBlock: '6px',+ paddingInlineStart: '8px',+ paddingInlineEnd: '12px',+ borderRadius: '8px',+ color: cssVar.colorText,+ backgroundImage: 'none',+ boxShadow: { 'default': cssVar.boxShadowTertiary, ':hover': cssVar.boxShadowSecondary },+ transition: 'all 0.2s',+ },+ containerDark: {+ backgroundColor: {+ 'default': `color-mix(in srgb, ${cssVar.colorBgElevated} 90%, white)`,+ ':hover': `color-mix(in srgb, ${cssVar.colorBgElevated} 85%, white)`,+ },+ backgroundImage: 'none',+ },+ containerLight: {+ backgroundColor: `color-mix(in srgb, ${cssVar.colorBgElevated} 90%, white)`,+ backgroundImage: 'none',+ },+});diff --git a/src/features/Conversation/Messages/components/MessageBranch.tsx b/src/features/Conversation/Messages/components/MessageBranch.tsxindex e8222769ae5..c764c623e3b 100644--- a/src/features/Conversation/Messages/components/MessageBranch.tsx+++ b/src/features/Conversation/Messages/components/MessageBranch.tsx@@ -1,58 +1,50 @@-import { Center, createStaticStyles, cssVar, cx, Flexbox, Icon } from '@lobehub/ui';+import { Center, Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronLeft, ChevronRight } from 'lucide-react';import { memo } from 'react';import { useConversationStore } from '../../store';-const prefixCls = 'ant';--const styles = createStaticStyles(({ css }) => ({- button: css`- cursor: pointer;-- display: flex;- align-items: center;- justify-content: center;-- width: 20px;- height: 20px;- border-radius: 4px;-- color: ${cssVar.colorTextSecondary};-- transition: all 0.2s ease;-- &:hover:not(.${prefixCls}-disabled) {- color: ${cssVar.colorText};- background: ${cssVar.colorFillSecondary};- }-- &.${prefixCls}-disabled {- cursor: not-allowed;- opacity: 0.4;- }- `,- container: css`- user-select: none;-- display: inline-flex;- gap: 4px;- align-items: center;-- height: 20px;- padding-inline: 4px;- border-radius: ${cssVar.borderRadiusSM};- `,- text: css`- min-width: 24px;- height: 20px;-- font-size: 12px;- font-variant-numeric: tabular-nums;- color: ${cssVar.colorTextSecondary};- text-align: center;- `,-}));+const styles = stylex.create({+ button: {+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '20px',+ borderRadius: '4px',+ color: cssVar.colorTextSecondary,+ transition: 'all 0.2s ease',+ },+ buttonDisabled: {+ cursor: 'not-allowed',+ opacity: 0.4,+ },+ buttonEnabled: {+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillSecondary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ container: {+ userSelect: 'none',+ display: 'inline-flex',+ gap: '4px',+ alignItems: 'center',+ height: '20px',+ paddingInline: '4px',+ borderRadius: cssVar.borderRadiusSM,+ },+ text: {+ minWidth: '24px',+ height: '20px',+ fontSize: '12px',+ fontVariantNumeric: 'tabular-nums',+ color: cssVar.colorTextSecondary,+ textAlign: 'center',+ },+});interface MessageBranchProps {activeBranchIndex: number;@@ -79,20 +71,23 @@ const MessageBranch = memo<MessageBranchProps>(({ activeBranchIndex, count, messconst canGoNext = activeBranchIndex < count - 1;return (- <Flexbox horizontal className={styles.container}>+ <Flexbox horizontal className={stylex.props(styles.container).className}><div- className={cx(styles.button, !canGoPrevious && `${prefixCls}-disabled`)}+ {...stylex.props(+ styles.button,+ canGoPrevious ? styles.buttonEnabled : styles.buttonDisabled,+ )}role="button"tabIndex={canGoPrevious ? 0 : -1}onClick={handlePrevious}><Icon icon={ChevronLeft} size={16} /></div>- <Center className={styles.text}>+ <Center className={stylex.props(styles.text).className}>{activeBranchIndex + 1}/{count}</Center><div- className={cx(styles.button, !canGoNext && `${prefixCls}-disabled`)}+ {...stylex.props(styles.button, canGoNext ? styles.buttonEnabled : styles.buttonDisabled)}role="button"tabIndex={canGoNext ? 0 : -1}onClick={handleNext}diff --git a/src/features/Conversation/Messages/components/SearchGrounding.tsx b/src/features/Conversation/Messages/components/SearchGrounding.tsxindex 99f1a98f5a3..68259c496af 100644--- a/src/features/Conversation/Messages/components/SearchGrounding.tsx+++ b/src/features/Conversation/Messages/components/SearchGrounding.tsx@@ -1,4 +1,6 @@-import { createStaticStyles, cssVar, cx, Flexbox, Icon, SearchResultCards, Tag } from '@lobehub/ui';+import { Flexbox, Icon, SearchResultCards, Tag } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronDown, ChevronRight, Globe, Images } from 'lucide-react';import { AnimatePresence } from 'motion/react';import * as m from 'motion/react-m';@@ -33,93 +35,77 @@ const stripHtml = (html: string) =>.replaceAll(''', "'").replaceAll(' ', ' ');-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- width: fit-content;- padding-block: 4px;- padding-inline: 8px;- border-radius: 6px;-- color: ${cssVar.colorTextTertiary};- `,- containerDark: css`- &:hover {- background: ${cssVar.colorFillQuaternary};- }- `,- containerLight: css`- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- expandDark: css`- background: ${cssVar.colorFillQuaternary} !important;- `,- expandLight: css`- background: ${cssVar.colorFillTertiary} !important;- `,- imageCard: css`- overflow: hidden;- border-radius: 8px;- `,- imageCardLink: css`- color: inherit;- text-decoration: none;- transition: opacity 0.2s;-- &:hover {- opacity: 0.75;- }- `,- imageDomain: css`- overflow: hidden;-- font-size: 11px;- line-height: 1;- color: ${cssVar.colorTextQuaternary};- text-overflow: ellipsis;- white-space: nowrap;- `,- imageGrid: css`- display: grid;- grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));- gap: 8px;- `,- imageThumb: css`- display: block;- width: 100%;- height: 80px;- object-fit: cover;- `,- imageThumbWrap: css`- overflow: hidden;- display: block;- flex-shrink: 0;-- height: 80px;- border-radius: 6px;- `,- imageTitle: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 2;-- font-size: 11px;- line-height: 1.4;- color: ${cssVar.colorTextSecondary};- text-overflow: ellipsis;- `,- title: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 1;-- font-size: 12px;- text-overflow: ellipsis;- `,-}));+const styles = stylex.create({+ container: {+ width: 'fit-content',+ paddingBlock: '4px',+ paddingInline: '8px',+ borderRadius: '6px',+ color: cssVar.colorTextTertiary,+ },+ containerDark: {+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ containerLight: {+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ expandDark: {+ backgroundColor: cssVar.colorFillQuaternary,+ backgroundImage: 'none',+ },+ expandLight: {+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ imageCard: {+ overflow: 'hidden',+ borderRadius: '8px',+ },+ imageCardLink: {+ color: 'inherit',+ textDecoration: 'none',+ opacity: { 'default': null, ':hover': 0.75 },+ transition: 'opacity 0.2s',+ },+ imageDomain: {+ overflow: 'hidden',+ fontSize: '11px',+ lineHeight: 1,+ color: cssVar.colorTextQuaternary,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ imageGrid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(120px, 1fr))',+ gap: '8px',+ },+ imageThumb: {+ display: 'block',+ width: '100%',+ height: '80px',+ objectFit: 'cover',+ },+ imageThumbWrap: {+ overflow: 'hidden',+ display: 'block',+ flexShrink: 0,+ height: '80px',+ borderRadius: '6px',+ },+ imageTitle: {+ overflow: 'hidden',+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: '2',+ fontSize: '11px',+ lineHeight: 1.4,+ color: cssVar.colorTextSecondary,+ textOverflow: 'ellipsis',+ },+});const SearchGrounding = memo<GroundingSearch>(({ searchQueries, citations, imageResults, imageSearchQueries }) => {@@ -142,11 +128,13 @@ const SearchGrounding = memo<GroundingSearch>(<Flexboxgap={16}style={{ width: showDetail ? '100%' : undefined }}- className={cx(- styles.container,- isDarkMode ? styles.containerDark : styles.containerLight,- showDetail && (isDarkMode ? styles.expandDark : styles.expandLight),- )}+ className={+ stylex.props(+ styles.container,+ isDarkMode ? styles.containerDark : styles.containerLight,+ showDetail && (isDarkMode ? styles.expandDark : styles.expandLight),+ ).className+ }><Flexboxhorizontal@@ -259,26 +247,26 @@ const SearchGrounding = memo<GroundingSearch>(</Flexbox>)}{imageResults && imageResults.length > 0 && (- <div className={styles.imageGrid}>+ <div {...stylex.props(styles.imageGrid)}>{imageResults.map((item, index) => (- <div className={styles.imageCard} key={`${item.imageUri}-${index}`}>+ <div {...stylex.props(styles.imageCard)} key={`${item.imageUri}-${index}`}><Flexbox gap={4}><a- className={styles.imageCardLink}+ {...stylex.props(styles.imageCardLink)}href={item.imageUri}rel="noopener noreferrer"target="_blank">- <div className={styles.imageThumbWrap}>+ <div {...stylex.props(styles.imageThumbWrap)}><imgalt={item.title ? stripHtml(item.title) : ''}- className={styles.imageThumb}+ {...stylex.props(styles.imageThumb)}src={item.imageUri || ''}/></div></a><a- className={styles.imageCardLink}+ {...stylex.props(styles.imageCardLink)}href={item.sourceUri}rel="noopener noreferrer"target="_blank"@@ -286,7 +274,9 @@ const SearchGrounding = memo<GroundingSearch>(><Flexbox gap={2}>{item.title && (- <div className={styles.imageTitle}>{stripHtml(item.title)}</div>+ <div {...stylex.props(styles.imageTitle)}>+ {stripHtml(item.title)}+ </div>)}{item.domain && (<Flexbox horizontal align="center" gap={4}>@@ -298,7 +288,7 @@ const SearchGrounding = memo<GroundingSearch>(style={{ borderRadius: 2, flexShrink: 0 }}width={12}/>- <div className={styles.imageDomain}>{item.domain}</div>+ <div {...stylex.props(styles.imageDomain)}>{item.domain}</div></Flexbox>)}</Flexbox>diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx b/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsxindex 451c084e357..be2bee68093 100644--- a/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx@@ -1,7 +1,8 @@'use client';import { nanoid } from '@lobechat/utils';-import { Button, createStaticStyles, Flexbox, toast } from '@lobehub/ui';+import { Button, Flexbox, toast } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { MessageCirclePlusIcon } from 'lucide-react';import type { CSSProperties, PointerEvent, ReactNode } from 'react';import { memo, useCallback, useEffect, useRef, useState } from 'react';@@ -32,25 +33,22 @@ interface TextSelectionActionLayerProps {disabled?: boolean;}-const styles = createStaticStyles(({ css }) => ({- root: css`- display: contents;- `,- toolbar: css`- position: fixed;- z-index: 10000;- transform: translate(-50%, -100%);-- padding: 4px;- border: 1px solid light-dark(rgb(229 231 235), rgb(64 64 64));- border-radius: 999px;-- background: light-dark(#fff, #1f1f1f);- box-shadow:- 0 8px 24px rgb(0 0 0 / 12%),- 0 2px 8px rgb(0 0 0 / 8%);- `,-}));+const styles = stylex.create({+ root: { display: 'contents' },+ toolbar: {+ position: 'fixed',+ zIndex: 10000,+ transform: 'translate(-50%, -100%)',+ padding: '4px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: 'light-dark(rgb(229 231 235), rgb(64 64 64))',+ borderRadius: '999px',+ backgroundColor: 'light-dark(#fff, #1f1f1f)',+ backgroundImage: 'none',+ boxShadow: '0 8px 24px rgb(0 0 0 / 12%), 0 2px 8px rgb(0 0 0 / 8%)',+ },+});const focusChatInputSoon = () => {window.setTimeout(() => {@@ -182,7 +180,7 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ childrenreturn (<div- className={styles.root}+ {...stylex.props(styles.root)}ref={rootRef}onKeyUp={scheduleSelectionUpdate}onPointerUp={scheduleSelectionUpdate}@@ -193,7 +191,7 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ children<Flexboxhorizontalalign={'center'}- className={styles.toolbar}+ className={stylex.props(styles.toolbar).className}gap={2}ref={toolbarRef}style={toolbarStyle}diff --git a/src/features/Conversation/Messages/index.module.css b/src/features/Conversation/Messages/index.module.cssnew file mode 100644index 00000000000..ee9ce539fd0--- /dev/null+++ b/src/features/Conversation/Messages/index.module.css@@ -0,0 +1,4 @@+/* Prevent the antd textarea from growing too long. */+.message :global(.ant-input) {+ max-height: 900px;+}diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsxindex 6a31e28b732..546dd8c9dfc 100644--- a/src/features/Conversation/Messages/index.tsx+++ b/src/features/Conversation/Messages/index.tsx@@ -1,7 +1,8 @@'use client';import { isDesktop } from '@lobechat/const';-import { createStaticStyles, cx, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import { type MouseEvent, type ReactNode } from 'react';import { memo, Suspense, useCallback } from 'react';@@ -10,6 +11,7 @@ import BubblesLoading from '@/components/BubblesLoading';import SafeBoundary from '@/components/ErrorBoundary';import { useUserStore } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';+import { sx } from '@/styles/sx';import History from '../components/History';import { useChatItemContextMenu } from '../hooks/useChatItemContextMenu';@@ -24,6 +26,7 @@ import PendingRetryTurn from './components/PendingRetryTurn';import TextSelectionActionLayer from './components/TextSelectionActionLayer';import CompressedGroupMessage from './CompressedGroup';import GroupTasksMessage from './GroupTasks';+import cssModule from './index.module.css';import { getMessageInteractionState } from './messageInteraction';import TaskMessage from './Task';import TaskCallbackMessage from './TaskCallback';@@ -32,20 +35,10 @@ import ToolMessage from './Tool';import UserMessage from './User';import VerifyMessage from './Verify';-const prefixCls = 'ant';--const styles = createStaticStyles(({ css }) => ({- loading: css`- opacity: 0.6;- `,- message: css`- position: relative;- // prevent the textarea too long- .${prefixCls}-input {- max-height: 900px;- }- `,-}));+const styles = stylex.create({+ loading: { opacity: 0.6 },+ message: { position: 'relative' },+});export interface MessageItemProps {className?: string;@@ -284,7 +277,10 @@ const MessageItem = memo<MessageItemProps>(<>{enableHistoryDivider && <History />}<Flexbox- className={cx(styles.message, className, shouldDimCreatingMessage && styles.loading)}+ {...sx(+ [styles.message, shouldDimCreatingMessage && styles.loading],+ [cssModule.message, className].filter(Boolean).join(' '),+ )}data-index={index}onContextMenu={onContextMenu}>diff --git a/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx b/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsxindex 119a88145c1..3a648e439ea 100644--- a/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx+++ b/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx@@ -1,33 +1,16 @@'use client';import { BRANDING_NAME } from '@lobechat/business-const';-import { Block, createStaticStyles, cx, Text } from '@lobehub/ui';+import { Block, Text } from '@lobehub/ui';import { memo } from 'react';import { Trans, useTranslation } from 'react-i18next';import ImperativeModal from '@/components/ImperativeModal';-import { imageUrl, PRIVACY_URL, TERMS_URL } from '@/const/url';+import { PRIVACY_URL, TERMS_URL } from '@/const/url';import AuthCard from '@/features/AuthCard';-import { useIsDark } from '@/hooks/useIsDark';import type { MarketAuthScene } from './scenes';-const styles = createStaticStyles(({ css }) => ({- container: css`- padding-block-start: 32px;-- background-image: url(${imageUrl('community_header_light.webp')});- background-repeat: no-repeat;- background-position: 400% 0;- background-size: 400px auto;- background-blend-mode: multiply;- `,- container_dark: css`- background-image: url(${imageUrl('community_header_dark.webp')});- background-blend-mode: screen;- `,-}));-interface MarketAuthConfirmModalProps {onCancel: () => void;onConfirm: () => void;@@ -38,7 +21,6 @@ interface MarketAuthConfirmModalProps {const MarketAuthConfirmModal = memo<MarketAuthConfirmModalProps>(({ open, onConfirm, onCancel, scene = 'default' }) => {const { t } = useTranslation('marketAuth');- const isDarkMode = useIsDark();// Resolve scene-specific copy, falling back to the generic community-profile// wording when a scene has no dedicated key.@@ -88,9 +70,6 @@ const MarketAuthConfirmModal = memo<MarketAuthConfirmModalProps>(open={open}title={null}width={440}- classNames={{- container: cx(styles.container, isDarkMode && styles.container_dark),- }}paddings={{desktop: 24,}}diff --git a/src/layout/GlobalProvider/AppTheme.tsx b/src/layout/GlobalProvider/AppTheme.tsxindex b928ba7dd50..540b9de3ae1 100644--- a/src/layout/GlobalProvider/AppTheme.tsx+++ b/src/layout/GlobalProvider/AppTheme.tsx@@ -3,9 +3,11 @@import '@lobehub/ui/theme.css';import '@lobehub/ui/global.css';import '@lobehub/ui/style.css';+import '@/styles/global.css';import { type NeutralColors, type PrimaryColors } from '@lobehub/ui';-import { ConfigProvider, createStaticStyles, cx, FontLoader, setLobeTheme } from '@lobehub/ui';+import { ConfigProvider, FontLoader, setLobeTheme } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import * as m from 'motion/react-m';import { type ReactNode } from 'react';import { memo, useEffect, useMemo, useState } from 'react';@@ -20,66 +22,24 @@ import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useUserStore } from '@/store/user';import { preferenceSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';-import { GlobalStyle } from '@/styles';+import { sx } from '@/styles/sx';import { setCookie } from '@/utils/client/cookie';import { resolveLang } from '@/utils/client/switchLang';import { resolveFontFamilyOverride } from './fontFamilyOverride';-const styles = createStaticStyles(({ css, cssVar }) => ({- app: css`- position: relative;-- display: flex;- flex-direction: column;- align-items: center;-- height: 100%;- min-height: 100dvh;- max-height: 100dvh;-- @media (device-width >= 576px) {- overflow: hidden;- }- `,- // scrollbar-width and scrollbar-color are supported from Chrome 121- // https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-color- scrollbar: css`- scrollbar-color: ${cssVar.colorFill} transparent;- scrollbar-width: thin;-- #lobe-mobile-scroll-container {- scrollbar-width: none;-- ::-webkit-scrollbar {- width: 0;- height: 0;- }- }- `,-- // so this is a polyfill for older browsers- scrollbarPolyfill: css`- ::-webkit-scrollbar {- width: 0.75em;- height: 0.75em;- }-- ::-webkit-scrollbar-thumb {- border-radius: 10px;- }-- :hover::-webkit-scrollbar-thumb {- border: 3px solid transparent;- background-color: ${cssVar.colorText};- background-clip: content-box;- }-- ::-webkit-scrollbar-track {- background-color: transparent;- }- `,-}));+const styles = stylex.create({+ app: {+ position: 'relative',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ height: '100%',+ minHeight: '100dvh',+ maxHeight: '100dvh',+ overflow: { 'default': null, '@media (min-device-width: 576px)': 'hidden' },+ },+});export interface AppThemeProps {children?: ReactNode;@@ -180,9 +140,8 @@ const AppTheme = memo<AppThemeProps>(proxy: globalCDN ? 'unpkg' : undefined,}}>- <div className={cx(styles.app, styles.scrollbar, styles.scrollbarPolyfill)}>+ <div {...sx(styles.app)}>{!!customFontURL && <FontLoader url={customFontURL} />}- <GlobalStyle />{children}</div></ConfigProvider>diff --git a/src/layout/GlobalProvider/ServerVersionOutdatedAlert.tsx b/src/layout/GlobalProvider/ServerVersionOutdatedAlert.tsxindex 5bfeac0e32d..dfc99d00550 100644--- a/src/layout/GlobalProvider/ServerVersionOutdatedAlert.tsx+++ b/src/layout/GlobalProvider/ServerVersionOutdatedAlert.tsx@@ -1,6 +1,8 @@'use client';-import { Button, createStaticStyles, Flexbox, Icon, useTheme } from '@lobehub/ui';+import { Button, Flexbox, Icon, useTheme } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { TriangleAlert, X } from 'lucide-react';import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -11,75 +13,57 @@ import { useElectronStore } from '@/store/electron';import { electronSyncSelectors } from '@/store/electron/selectors';import { useGlobalStore } from '@/store/global';-const styles = createStaticStyles(({ css, cssVar }) => ({- closeButton: css`- cursor: pointer;-- position: absolute;- inset-block-start: 20px;- inset-inline-end: 20px;-- display: flex;- align-items: center;- justify-content: center;-- width: 28px;- height: 28px;- border-radius: ${cssVar.borderRadius};-- color: ${cssVar.colorTextSecondary};-- transition: all 0.2s;-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillSecondary};- }- `,- container: css`- position: fixed;- z-index: 9999;- inset: 0;-- display: flex;- align-items: center;- justify-content: center;-- background: ${cssVar.colorBgMask};- `,- content: css`- position: relative;-- overflow: hidden;-- max-width: 480px;- padding: 24px;- border: 1px solid ${cssVar.colorFillQuaternary};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorBgContainer};- box-shadow: ${cssVar.boxShadowSecondary};- `,- desc: css`- line-height: 1.6;- color: ${cssVar.colorTextSecondary};- `,- title: css`- font-size: 16px;- font-weight: bold;- color: ${cssVar.colorWarningText};- `,- titleIcon: css`- flex-shrink: 0;- color: ${cssVar.colorWarning};- `,- warning: css`- padding: 12px;- border-radius: ${cssVar.borderRadius};- color: ${cssVar.colorWarningText};- background: var(--warning-yellow-bg, ${cssVar.colorWarningBg});- `,-}));+const styles = stylex.create({+ closeButton: {+ cursor: 'pointer',+ position: 'absolute',+ insetBlockStart: '20px',+ insetInlineEnd: '20px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '28px',+ height: '28px',+ borderRadius: cssVar.borderRadius,+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ transition: 'all 0.2s',+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillSecondary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ container: {+ position: 'fixed',+ zIndex: 9999,+ inset: '0',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: cssVar.colorBgMask,+ backgroundImage: 'none',+ },+ content: {+ position: 'relative',+ overflow: 'hidden',+ maxWidth: '480px',+ padding: '24px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorFillQuaternary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ boxShadow: cssVar.boxShadowSecondary,+ },+ desc: { lineHeight: 1.6, color: cssVar.colorTextSecondary },+ title: { fontSize: '16px', fontWeight: 'bold', color: cssVar.colorWarningText },+ titleIcon: { flexShrink: 0, color: cssVar.colorWarning },+ warning: {+ padding: '12px',+ borderRadius: cssVar.borderRadius,+ color: cssVar.colorWarningText,+ backgroundColor: `var(--warning-yellow-bg, ${cssVar.colorWarningBg})`,+ backgroundImage: 'none',+ },+});const ServerVersionOutdatedAlert = () => {const theme = useTheme();@@ -99,23 +83,23 @@ const ServerVersionOutdatedAlert = () => {if (isOfficialServer || !isServerVersionOutdated || dismissed) return null;return (- <div className={styles.container}>- <div className={styles.content} style={cssVariables}>- <div className={styles.closeButton} onClick={() => setDismissed(true)}>+ <div {...stylex.props(styles.container)}>+ <div className={stylex.props(styles.content).className} style={cssVariables}>+ <div {...stylex.props(styles.closeButton)} onClick={() => setDismissed(true)}><Icon icon={X} /></div><Flexbox gap={16}><Flexbox horizontal align="center" gap={8}>- <Icon className={styles.titleIcon} icon={TriangleAlert} />- <div className={styles.title}>{t('serverVersionOutdated.title')}</div>+ <Icon className={stylex.props(styles.titleIcon).className} icon={TriangleAlert} />+ <div {...stylex.props(styles.title)}>{t('serverVersionOutdated.title')}</div></Flexbox>- <div className={styles.desc}>+ <div {...stylex.props(styles.desc)}>{t('serverVersionOutdated.desc', { version: CURRENT_VERSION })}</div>- <div className={styles.warning}>{t('serverVersionOutdated.warning')}</div>+ <div {...stylex.props(styles.warning)}>{t('serverVersionOutdated.warning')}</div><Flexbox horizontal gap={8} justify="flex-end" style={{ marginTop: 8 }}><a href={MANUAL_UPGRADE_URL} rel="noreferrer" target="_blank">diff --git a/src/routes/(main)/[workspaceSlug]/settings/credential/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/credential/index.tsxindex 0ca1262b101..d60c5438bd4 100644--- a/src/routes/(main)/[workspaceSlug]/settings/credential/index.tsx+++ b/src/routes/(main)/[workspaceSlug]/settings/credential/index.tsx@@ -1,16 +1,8 @@'use client';-import {- Block,- Button,- createStaticStyles,- Empty,- Flexbox,- Icon,- Tabs,- Text,- Tooltip,-} from '@lobehub/ui';+import { Block, Button, Empty, Flexbox, Icon, Tabs, Text, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { Lock, Plus, UsersIcon } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';@@ -24,18 +16,10 @@ import { usePermission } from '@/hooks/usePermission';import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- overflow: hidden;- width: 100%;- padding-block: 4px;- padding-inline: 16px;- `,- desc: css`- font-size: 13px;- color: ${cssVar.colorTextSecondary};- `,-}));+const styles = stylex.create({+ container: { overflow: 'hidden', width: '100%', paddingBlock: '4px', paddingInline: '16px' },+ desc: { fontSize: '13px', color: cssVar.colorTextSecondary },+});type Visibility = 'private' | 'public';@@ -150,10 +134,10 @@ const WorkspaceCredsSetting = () => {))}</Flexbox><Flexbox gap={12}>- <Text className={styles.desc}>+ <Text className={stylex.props(styles.desc).className}>{t(tab === 'public' ? 'creds.workspaceSection.desc' : 'creds.privateSection.desc')}</Text>- <Block className={styles.container} variant={'outlined'}>+ <Block className={stylex.props(styles.container).className} variant={'outlined'}><MarketSignInGate>{orgMissing ? (<Flexbox align={'center'} justify={'center'} style={{ padding: 48 }}>diff --git a/src/routes/(main)/_layout/index.desktop.tsx b/src/routes/(main)/_layout/index.desktop.tsxindex c61bd11f6f5..dcb9e89eeb0 100644--- a/src/routes/(main)/_layout/index.desktop.tsx+++ b/src/routes/(main)/_layout/index.desktop.tsx@@ -2,7 +2,8 @@import { HotkeyScopeEnum } from '@lobechat/const/hotkeys';import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';-import { cx, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { type CSSProperties, type FC } from 'react';import { Suspense } from 'react';import { HotkeysProvider } from 'react-hotkeys-hook';@@ -82,9 +83,11 @@ const Layout: FC = () => {<DndContextWrapper><Flexboxhorizontal- className={cx(isPWA ? styles.mainContainerPWA : styles.mainContainer)}height={`calc(100% - ${TITLE_BAR_HEIGHT}px)`}width={'100%'}+ className={+ stylex.props(isPWA ? styles.mainContainerPWA : styles.mainContainer).className+ }><NavPanelShell /><DesktopLayoutContainer>diff --git a/src/routes/(main)/_layout/index.tsx b/src/routes/(main)/_layout/index.tsxindex 2a672023179..9be706e4572 100644--- a/src/routes/(main)/_layout/index.tsx+++ b/src/routes/(main)/_layout/index.tsx@@ -1,7 +1,8 @@'use client';import { HotkeyScopeEnum } from '@lobechat/const/hotkeys';-import { cx, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { type FC } from 'react';import { Suspense } from 'react';import { HotkeysProvider } from 'react-hotkeys-hook';@@ -50,9 +51,11 @@ const Layout: FC = () => {<DndContextWrapper><Flexboxhorizontal- className={cx(isPWA ? styles.mainContainerPWA : styles.mainContainer)}height={showCloudPromotion ? `calc(100% - ${BANNER_HEIGHT}px)` : '100%'}width={'100%'}+ className={+ stylex.props(isPWA ? styles.mainContainerPWA : styles.mainContainer).className+ }><NavPanelShell /><DesktopLayoutContainer>diff --git a/src/routes/(main)/_layout/style.ts b/src/routes/(main)/_layout/style.tsindex 4ec1d629d24..58848eb651d 100644--- a/src/routes/(main)/_layout/style.ts+++ b/src/routes/(main)/_layout/style.ts@@ -1,14 +1,17 @@-import { createStaticStyles } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css, cssVar }) => ({+export const styles = stylex.create({// Main container - non-PWA mode (no top border)- mainContainer: css`- position: relative;- `,+ mainContainer: {+ position: 'relative',+ },// Main container - PWA mode (with top border)- mainContainerPWA: css`- position: relative;- border-block-start: 1px solid ${cssVar.colorBorder};- `,-}));+ mainContainerPWA: {+ position: 'relative',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'solid',+ borderBlockStartColor: cssVar.colorBorder,+ },+});diff --git a/src/routes/(main)/community/(detail)/_layout/Header.tsx b/src/routes/(main)/community/(detail)/_layout/Header.tsxindex 83631bd823b..5f232c9c366 100644--- a/src/routes/(main)/community/(detail)/_layout/Header.tsx+++ b/src/routes/(main)/community/(detail)/_layout/Header.tsx@@ -1,6 +1,7 @@'use client';import { ActionIcon, cssVar, Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { ArrowLeft } from 'lucide-react';import { memo } from 'react';import { useLocation } from 'react-router';@@ -58,7 +59,7 @@ const Header = memo(() => {return (<NavHeader- className={styles.headerContainer}+ className={stylex.props(styles.headerContainer).className}right={<UserAvatar avatarOverride={detailAvatar} />}style={cssVariables}left={diff --git a/src/routes/(main)/community/(detail)/_layout/Header/style.ts b/src/routes/(main)/community/(detail)/_layout/Header/style.tsindex 49c10d5bf3a..0fb96075091 100644--- a/src/routes/(main)/community/(detail)/_layout/Header/style.ts+++ b/src/routes/(main)/community/(detail)/_layout/Header/style.ts@@ -1,8 +1,11 @@-import { createStaticStyles } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css, cssVar }) => ({+export const styles = stylex.create({// Header container- headerContainer: css`- border-block-end: 1px solid var(--header-border-color, ${cssVar.colorBorderSecondary});- `,-}));+ headerContainer: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: `var(--header-border-color, ${cssVar.colorBorderSecondary})`,+ },+});diff --git a/src/routes/(main)/community/(detail)/_layout/index.tsx b/src/routes/(main)/community/(detail)/_layout/index.tsxindex 5818525d83d..c06d48a458a 100644--- a/src/routes/(main)/community/(detail)/_layout/index.tsx+++ b/src/routes/(main)/community/(detail)/_layout/index.tsx@@ -1,6 +1,7 @@'use client';import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { Outlet } from 'react-router';@@ -21,13 +22,13 @@ const DesktopDiscoverDetailLayout = memo(() => {<><Header /><Flexbox- className={styles.mainContainer}+ className={stylex.props(styles.mainContainer).className}height={'100%'}id={SCROLL_PARENT_ID}width={'100%'}><WideScreenContainer- className={styles.contentContainer}+ className={stylex.props(styles.contentContainer).className}gap={32}minWidth={MAX_WIDTH}paddingBlock={16}@@ -39,7 +40,7 @@ const DesktopDiscoverDetailLayout = memo(() => {<RouteSkeletonChromeProvider><Outlet /></RouteSkeletonChromeProvider>- <div className={styles.spacer} />+ <div {...stylex.props(styles.spacer)} /><Footer /></WideScreenContainer></Flexbox>diff --git a/src/routes/(main)/community/(detail)/_layout/style.ts b/src/routes/(main)/community/(detail)/_layout/style.tsindex d639a0b0e3d..4eac7deb270 100644--- a/src/routes/(main)/community/(detail)/_layout/style.ts+++ b/src/routes/(main)/community/(detail)/_layout/style.ts@@ -1,18 +1,12 @@-import { createStaticStyles } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css }) => ({+export const styles = stylex.create({// Content container- contentContainer: css`- min-height: 100%;- `,+ contentContainer: { minHeight: '100%' },// Main container- mainContainer: css`- overflow-y: auto;- `,+ mainContainer: { overflowY: 'auto' },// Placeholder- spacer: css`- flex: 1;- `,-}));+ spacer: { flex: '1' },+});diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/KnowledgeItem.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/KnowledgeItem.tsxindex 74eb0e75560..c554ff0f9b8 100644--- a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/KnowledgeItem.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/KnowledgeItem.tsx@@ -1,24 +1,16 @@-import { Avatar, Block, createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- flex: 1;- margin: 0 !important;- font-size: 14px !important;- color: ${cssVar.colorTextSecondary};- `,- title: css`- margin: 0 !important;- font-size: 14px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', fontSize: '14px', color: cssVar.colorTextSecondary },+ title: {+ margin: '0',+ fontSize: '14px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const KnowledgeItem = memo<{ avatar?: string; description?: string; title: string }>(@@ -33,12 +25,12 @@ const KnowledgeItem = memo<{ avatar?: string; description?: string; title: strinoverflow: 'hidden',}}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{title}</Text><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 2,}}diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.test.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.test.tsxindex 1408bbd8e2f..20b4466056f 100644--- a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.test.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.test.tsx@@ -32,9 +32,6 @@ vi.mock('@lobechat/builtin-tools', () => ({ builtinTools: [] }));vi.mock('@lobehub/ui', () => ({Avatar: () => null,Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,- createStaticStyles: () => ({}),- cssVar: new Proxy({}, { get: () => 'var(--x)' }),- cx: (...args: unknown[]) => args.filter(Boolean).join(' '),Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,Icon: () => null,Image: () => null,diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsxindex a2c2635d42d..0565a5583a6 100644--- a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx@@ -7,19 +7,9 @@ import {OFFICIAL_SITE,} from '@lobechat/const';import { type DiscoverPluginDetail, type PluginSource } from '@lobechat/types';-import {- Avatar,- Block,- createStaticStyles,- cssVar,- cx,- Flexbox,- Icon,- Image,- Skeleton,- Tag,- Text,-} from '@lobehub/ui';+import { Avatar, Block, Flexbox, Icon, Image, Skeleton, Tag, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import urlJoin from 'url-join';@@ -46,40 +36,18 @@ const BuiltinToolIcon = memo<Pick<ComposioAppType | LobehubSkillProviderType, 'iBuiltinToolIcon.displayName = 'BuiltinToolIcon';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- clickable: css`- cursor: pointer;-- &:hover {- .plugin-title {- color: ${cssVar.colorLink};- }- }- `,- desc: css`- flex: 1;- margin: 0 !important;- font-size: 14px !important;- color: ${cssVar.colorTextSecondary};- `,- noLink: css`- cursor: default;- `,- tag: css`- flex-shrink: 0;- `,- title: css`- margin: 0 !important;- font-size: 14px !important;- font-weight: 500 !important;- `,- titleRow: css`- display: flex;- gap: 8px;- align-items: center;- `,- };+const styles = stylex.create({+ clickable: { cursor: 'pointer' },+ desc: { flex: '1', margin: '0', fontSize: '14px', color: cssVar.colorTextSecondary },+ noLink: { cursor: 'default' },+ tag: { flexShrink: 0 },+ title: {+ margin: '0',+ fontSize: '14px',+ fontWeight: 500,+ color: { default: null, [stylex.when.ancestor(':hover')]: cssVar.colorLink },+ },+ titleRow: { display: 'flex', gap: '8px', alignItems: 'center' },});interface PluginItemProps {@@ -232,11 +200,15 @@ const PluginItem = memo<PluginItemProps>(({ identifier }) => {const content = (<Blockhorizontal- className={cx(sourceConfig.clickable ? styles.clickable : styles.noLink)}gap={12}key={identifier}padding={12}variant={'outlined'}+ className={+ stylex.props(+ sourceConfig.clickable ? [styles.clickable, stylex.defaultMarker()] : styles.noLink,+ ).className+ }>{renderAvatar()}<Flexbox@@ -246,19 +218,23 @@ const PluginItem = memo<PluginItemProps>(({ identifier }) => {overflow: 'hidden',}}>- <div className={styles.titleRow}>- <Text ellipsis as={'h2'} className={cx(styles.title, 'plugin-title')}>+ <div {...stylex.props(styles.titleRow)}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{data.title}</Text>{sourceConfig.tagText && (- <Tag className={styles.tag} color={sourceConfig.tagColor} size={'small'}>+ <Tag+ className={stylex.props(styles.tag).className}+ color={sourceConfig.tagColor}+ size={'small'}+ >{sourceConfig.tagText}</Tag>)}</div><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 2,}}diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/Nav.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/Nav.tsxindex c1fec66c73b..304c962a591 100644--- a/src/routes/(main)/community/(detail)/agent/features/Details/Nav.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Details/Nav.tsx@@ -1,7 +1,9 @@'use client';import { SOCIAL_URL } from '@lobechat/business-const';-import { createStaticStyles, Flexbox, Icon, Tabs, Tag } from '@lobehub/ui';+import { Flexbox, Icon, Tabs, Tag } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {BookOpenIcon,HistoryIcon,@@ -17,37 +19,26 @@ import { AssistantNavKey } from '@/types/discover';import { useDetailContext } from '../DetailProvider';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- link: css`- display: inline-flex;- gap: 4px;- align-items: center;- color: ${cssVar.colorTextDescription};-- &:hover {- color: ${cssVar.colorInfo};- }- `,- nav: css`- border-block-end: 1px solid ${cssVar.colorBorder};- `,- tabsWrapper: css`- scrollbar-width: none;-- overflow-x: auto;-- /* A swipe past the tabs' edge must not fire the browser back gesture. */- overscroll-behavior-x: none;- flex: 1;-- min-width: 0;-- &::-webkit-scrollbar {- display: none;- }- `,- };+const styles = stylex.create({+ link: {+ display: 'inline-flex',+ gap: '4px',+ alignItems: 'center',+ color: { 'default': cssVar.colorTextDescription, ':hover': cssVar.colorInfo },+ },+ nav: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorder,+ },+ tabsWrapper: {+ 'scrollbarWidth': 'none',+ 'overflowX': 'auto',+ 'overscrollBehaviorX': 'none',+ 'flex': '1',+ 'minWidth': '0',+ '::-webkit-scrollbar': { display: 'none' },+ },});interface NavProps {activeTab?: AssistantNavKey;@@ -114,10 +105,20 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = AssistantNavKey.return mobile ? (nav) : (- <Flexbox horizontal align={'center'} className={styles.nav} justify={'space-between'}>- <div className={styles.tabsWrapper}>{nav}</div>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.nav).className}+ justify={'space-between'}+ >+ <div {...stylex.props(styles.tabsWrapper)}>{nav}</div><Flexbox horizontal flex="none" gap={12} style={{ marginInlineStart: 12 }}>- <a className={styles.link} href={SOCIAL_URL.discord} rel="noreferrer" target="_blank">+ <a+ {...stylex.props(styles.link)}+ href={SOCIAL_URL.discord}+ rel="noreferrer"+ target="_blank"+ >{t('mcp.details.nav.needHelp')}<Icon icon={SquareArrowOutUpRight} size={12} /></a>diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/SystemRole/TagList.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/SystemRole/TagList.tsxindex a4311ec8696..917d95ec126 100644--- a/src/routes/(main)/community/(detail)/agent/features/Details/SystemRole/TagList.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Details/SystemRole/TagList.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, Flexbox, Tag } from '@lobehub/ui';+import { Flexbox, Tag } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import qs from 'query-string';import { memo } from 'react';@@ -8,17 +10,14 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { useQuery } from '@/hooks/useQuery';import { type AssistantMarketSource } from '@/types/discover';-const styles = createStaticStyles(({ cssVar, css }) => {- return {- tag: css`- margin: 0;- padding-block: 4px;- padding-inline: 12px;- border-radius: 16px;-- color: ${cssVar.colorTextSecondary};- `,- };+const styles = stylex.create({+ tag: {+ margin: '0',+ paddingBlock: '4px',+ paddingInline: '12px',+ borderRadius: '16px',+ color: cssVar.colorTextSecondary,+ },});const TagList = memo<{ tags: string[] }>(({ tags }) => {@@ -42,7 +41,7 @@ const TagList = memo<{ tags: string[] }>(({ tags }) => {{ skipNull: true },)}>- <Tag className={styles.tag}>{tag}</Tag>+ <Tag className={stylex.props(styles.tag).className}>{tag}</Tag></WorkspaceLink>))}</Flexbox>diff --git a/src/routes/(main)/community/(detail)/agent/features/Header.tsx b/src/routes/(main)/community/(detail)/agent/features/Header.tsxindex c17717e1547..84d781b3e6a 100644--- a/src/routes/(main)/community/(detail)/agent/features/Header.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Header.tsx@@ -5,8 +5,6 @@ import {ActionIcon,Avatar,Button,- createStaticStyles,- cssVar,Flexbox,Icon,Tag,@@ -16,6 +14,8 @@ import {TooltipGroup,useResponsive,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {BookmarkCheckIcon,BookmarkIcon,@@ -41,12 +41,7 @@ import { resolveCommunityProfileLink } from '../../utils/profileLink';import AgentForkTag from './AgentForkTag';import { useDetailContext } from './DetailProvider';-const styles = createStaticStyles(({ css, cssVar }) => ({- time: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,-}));+const styles = stylex.create({ time: { fontSize: '12px', color: cssVar.colorTextDescription } });const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {const { t } = useTranslation('discover');@@ -186,7 +181,10 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {author)}<Icon icon={DotIcon} />- <PublishedTime className={styles.time} date={createdAt as string} />+ <PublishedTime+ className={stylex.props(styles.time).className}+ date={createdAt as string}+ /><AgentForkTag />{!!forkCount && forkCount > 0 && (<Tag color="default" icon={<Icon icon={GitBranchIcon} />}>diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.test.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.test.tsxindex 842d8f42e32..9ee32ce94d3 100644--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.test.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.test.tsx@@ -30,7 +30,6 @@ vi.mock('@lobehub/ui', async (importOriginal) => ({Button: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (<button onClick={onClick}>{children}</button>),- createStaticStyles: () => ({}),Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,Select: () => null,toast: mocks.toast,diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsxindex 416d5319aa7..c6cb553462a 100644--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx@@ -1,7 +1,9 @@'use client';import { AGENT_CHAT_URL } from '@lobechat/const';-import { Button, createStaticStyles, Flexbox, Select, toast } from '@lobehub/ui';+import { Button, Flexbox, Select, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { customAlphabet } from 'nanoid/non-secure';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -20,48 +22,44 @@ import { useHomeStore } from '@/store/home';import { useDetailContext } from '../../DetailProvider';-const styles = createStaticStyles(({ css, cssVar }) => ({- buttonGroup: css`- width: 100%;- `,- forkButton: css`- flex: 1;- width: unset;- border-start-start-radius: 0 !important;- border-end-start-radius: 0 !important;- `,+const styles = stylex.create({+ buttonGroup: { width: '100%' },+ forkButton: {+ flex: '1',+ width: 'unset',+ borderStartStartRadius: '0',+ borderEndStartRadius: '0',+ },// Match Button type="primary" on the right so the two halves read as one// pill. (colorPrimary bg + colorBgLayout text) auto-flips with the theme:// dark bg + near-white text in light theme, white bg + near-black text// in dark theme. We use colorBgLayout directly instead of the// semantically-named colorTextLightSolid because the cssVar proxy doesn't// pick up LobeHub's JS-level override of that token.- visibilitySelect: css`- width: 130px;- border-color: ${cssVar.colorPrimary} !important;- border-inline-end-width: 0 !important;- border-start-end-radius: 0 !important;- border-end-end-radius: 0 !important;-- color: ${cssVar.colorBgLayout} !important;-- background: ${cssVar.colorPrimary} !important;-- & svg {- color: ${cssVar.colorBgLayout};- }-- &:hover:not([data-disabled]) {- border-color: ${cssVar.colorPrimaryHover} !important;- background: ${cssVar.colorPrimaryHover} !important;- }-- &:active:not([data-disabled]) {- border-color: ${cssVar.colorPrimaryActive} !important;- background: ${cssVar.colorPrimaryActive} !important;- }- `,-}));+ visibilitySelect: {+ width: '130px',+ borderColor: cssVar.colorPrimary,+ borderInlineEndWidth: '0',+ borderStartEndRadius: '0',+ borderEndEndRadius: '0',+ color: cssVar.colorBgLayout,+ backgroundColor: cssVar.colorPrimary,+ backgroundImage: 'none',+ },+ // Hover / active feedback; skipped while the select is disabled.+ visibilitySelectInteractive: {+ borderColor: {+ 'default': cssVar.colorPrimary,+ ':hover': cssVar.colorPrimaryHover,+ ':active': cssVar.colorPrimaryActive,+ },+ backgroundColor: {+ 'default': cssVar.colorPrimary,+ ':hover': cssVar.colorPrimaryHover,+ ':active': cssVar.colorPrimaryActive,+ },+ },+});/*** Generate a market identifier (8-character lowercase alphanumeric string)@@ -221,7 +219,7 @@ const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {return (<Buttonblock- className={styles.buttonGroup}+ className={stylex.props(styles.buttonGroup).className}disabled={!canCreate}loading={isLoading}size={'large'}@@ -241,19 +239,27 @@ const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {{ label: t('fork.visibilityPublic'), value: 'public' },];+ const isVisibilityDisabled = !canCreate || isLoading;+return (- <Flexbox horizontal className={styles.buttonGroup} gap={0}>+ <Flexbox horizontal className={stylex.props(styles.buttonGroup).className} gap={0}><Select- className={styles.visibilitySelect}- disabled={!canCreate || isLoading}+ disabled={isVisibilityDisabled}options={visibilityOptions}size={'large'}+ suffixIconProps={{ color: cssVar.colorBgLayout }}value={visibility}+ className={+ stylex.props(+ styles.visibilitySelect,+ !isVisibilityDisabled && styles.visibilitySelectInteractive,+ ).className+ }onChange={(v) => setVisibility(v as ForkTarget)}/><Buttonblock- className={styles.forkButton}+ className={stylex.props(styles.forkButton).className}disabled={!canCreate}loading={isLoading}size={'large'}diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/Related/Item.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/Related/Item.tsxindex f01cfe17ab8..843058fb352 100644--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/Related/Item.tsx+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/Related/Item.tsx@@ -1,26 +1,18 @@-import { Avatar, Block, createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { type DiscoverAssistantItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- flex: 1;- margin: 0 !important;- font-size: 14px !important;- color: ${cssVar.colorTextSecondary};- `,- title: css`- margin: 0 !important;- font-size: 14px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', fontSize: '14px', color: cssVar.colorTextSecondary },+ title: {+ margin: '0',+ fontSize: '14px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const RelatedItem = memo<DiscoverAssistantItem>(({ avatar, title, description, identifier }) => {@@ -34,12 +26,12 @@ const RelatedItem = memo<DiscoverAssistantItem>(({ avatar, title, description, ioverflow: 'hidden',}}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{title}</Text><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 2,}}diff --git a/src/routes/(main)/community/(detail)/features/ShareButton.module.css b/src/routes/(main)/community/(detail)/features/ShareButton.module.cssnew file mode 100644index 00000000000..0b22ea8e5bb--- /dev/null+++ b/src/routes/(main)/community/(detail)/features/ShareButton.module.css@@ -0,0 +1,15 @@+.icon {+ border: 1px solid var(--lobe-color-fill-secondary);+}++.icon svg {+ fill: var(--lobe-color-text-secondary);+}++.icon:hover {+ border: 1px solid var(--lobe-color-border-secondary);+}++.icon:hover svg {+ fill: var(--lobe-color-text);+}diff --git a/src/routes/(main)/community/(detail)/features/ShareButton.tsx b/src/routes/(main)/community/(detail)/features/ShareButton.tsxindex 2c2ba560cf8..3e94fa660ff 100644--- a/src/routes/(main)/community/(detail)/features/ShareButton.tsx+++ b/src/routes/(main)/community/(detail)/features/ShareButton.tsx@@ -4,8 +4,6 @@ import {Button,Center,CopyButton,- createStaticStyles,- cssVar,Flexbox,Icon,Input,@@ -13,6 +11,8 @@ import {Tag,Text,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { startCase } from 'es-toolkit/compat';import { LinkIcon, Share2Icon } from 'lucide-react';import { type ComponentProps, type ReactNode } from 'react';@@ -23,41 +23,23 @@ import ImperativeModal from '@/components/ImperativeModal';import { useShare } from '@/hooks/useShare';import CardBanner from '../../components/CardBanner';+import iconStyles from './ShareButton.module.css';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- banner: css`- overflow: hidden;-- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorBgContainer};- box-shadow: ${cssVar.boxShadowTertiary};- `,- copy: css`- background: ${cssVar.colorPrimary};-- &:hover {- background: ${cssVar.colorPrimaryHover};- }- `,- icon: css`- border: 1px solid ${cssVar.colorFillSecondary};-- svg {- fill: ${cssVar.colorTextSecondary};- }-- &:hover {- border: 1px solid ${cssVar.colorBorderSecondary};-- svg {- fill: ${cssVar.colorText};- }- }- `,- };+const styles = stylex.create({+ banner: {+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ boxShadow: cssVar.boxShadowTertiary,+ },+ copy: {+ backgroundColor: { 'default': cssVar.colorPrimary, ':hover': cssVar.colorPrimaryHover },+ backgroundImage: 'none',+ },});interface ShareButtonProps extends ComponentProps<typeof Button> {@@ -88,7 +70,7 @@ const ShareButton = memo<ShareButtonProps>(({ meta, ...rest }) => {if (meta) {content = (<Center gap={16} style={{ position: 'relative' }} width={'100%'}>- <Flexbox align={'center'} className={styles.banner} width={'100%'}>+ <Flexbox align={'center'} className={stylex.props(styles.banner).className} width={'100%'}><CardBanner avatar={meta.avatar} size={640} style={{ height: 72, marginBottom: -36 }} /><Centerflex={'none'}@@ -124,7 +106,7 @@ const ShareButton = memo<ShareButtonProps>(({ meta, ...rest }) => {item.icon && (<a href={item.link} key={item.title} rel="noreferrer" target="_blank"><ActionIcon- className={styles.icon}+ className={iconStyles.icon}icon={item.icon}size={{ blockSize: 36, borderRadius: 18, size: 16 }}title={item.title}@@ -136,7 +118,7 @@ const ShareButton = memo<ShareButtonProps>(({ meta, ...rest }) => {<Flexbox horizontal align={'center'} gap={8} width={'100%'}><Input value={meta.url} variant={'filled'} /><CopyButton- className={styles.copy}+ className={stylex.props(styles.copy).className}color={cssVar.colorBgLayout}content={meta.url}icon={LinkIcon}diff --git a/src/routes/(main)/community/(detail)/features/Toc/Heading.tsx b/src/routes/(main)/community/(detail)/features/Toc/Heading.tsxindex c2c91142b63..a1e66774a7a 100644--- a/src/routes/(main)/community/(detail)/features/Toc/Heading.tsx+++ b/src/routes/(main)/community/(detail)/features/Toc/Heading.tsx@@ -1,12 +1,16 @@'use client';-import { createStaticStyles, cssVar, cx, Icon } from '@lobehub/ui';+import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { kebabCase } from 'es-toolkit/compat';import { Heading2, Heading3, Heading4, Heading5 } from 'lucide-react';import { type ComponentProps, type FC, type ReactNode } from 'react';import { Children, isValidElement, useEffect, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { sx } from '@/styles/sx';+import { useToc } from './useToc';const extractTextChildren = (children: ReactNode) => {@@ -30,23 +34,13 @@ const HeadingIcon: any = {h5: Heading5,};-const styles = createStaticStyles(({ cx, css, cssVar }) => ({- anchor: cx(- 'toc-anchor',- css`- display: none;- margin-inline-start: 0.5rem;- color: ${cssVar.colorTextDescription} !important;- `,- ),- container: css`- &:hover {- .toc-anchor {- display: inline;- }- }- `,-}));+const styles = stylex.create({+ anchor: {+ display: { default: 'none', [stylex.when.ancestor(':hover')]: 'inline' },+ marginInlineStart: '0.5rem',+ color: cssVar.colorTextDescription,+ },+});const createHeading = (Tag: `h${1 | 2 | 3 | 4 | 5 | 6}`) => {const Heading: FC<ComponentProps<'h2'>> = ({ children, className, style, ...props }) => {@@ -79,15 +73,14 @@ const createHeading = (Tag: `h${1 | 2 | 3 | 4 | 5 | 6}`) => {return (<Tag- className={cx(styles.container, className)}- style={{ color: cssVar.colorText, ...style }}+ {...sx(stylex.defaultMarker(), className, { color: cssVar.colorText, ...style })}{...props}id={id}>{children}<aaria-label={t('toc.permalink')}- className={styles.anchor}+ className={stylex.props(styles.anchor).className}href={`#${id}`}style={{ scrollMarginTop: 96 }}>diff --git a/src/routes/(main)/community/(detail)/features/Toc/index.tsx b/src/routes/(main)/community/(detail)/features/Toc/index.tsxindex 34ee0e0fbc2..b11fa362772 100644--- a/src/routes/(main)/community/(detail)/features/Toc/index.tsx+++ b/src/routes/(main)/community/(detail)/features/Toc/index.tsx@@ -1,27 +1,23 @@'use client';import { Anchor, type AnchorProps } from '@lobehub/ui';-import { createStaticStyles, cx, responsive } from '@lobehub/ui';+import { media } from '@lobehub/ui/stylex/media.stylex';+import * as stylex from '@stylexjs/stylex';import { memo, useMemo } from 'react';import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';+import { sx } from '@/styles/sx';import { createTOCTree } from './useToc';-const styles = createStaticStyles(({ css }) => ({- toc: css`- ${responsive.lg} {- display: none;- }- `,-}));+const styles = stylex.create({ toc: { display: { default: null, [media.lg]: 'none' } } });const Toc = memo<AnchorProps>(({ items, className, ...rest }) => {const toc = useMemo(() => createTOCTree(items as any), [items]);return (<Anchor- className={cx(className, styles.toc)}+ {...sx(styles.toc, className)}getContainer={() => document.querySelector<HTMLElement>(`#${SCROLL_PARENT_ID}`)}items={toc}{...rest}diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Details/Nav.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Details/Nav.tsxindex 5421c15b030..451d875ff8d 100644--- a/src/routes/(main)/community/(detail)/group_agent/features/Details/Nav.tsx+++ b/src/routes/(main)/community/(detail)/group_agent/features/Details/Nav.tsx@@ -1,24 +1,20 @@'use client';import { SOCIAL_URL } from '@lobechat/business-const';-import { createStaticStyles, Flexbox, Icon, Tabs } from '@lobehub/ui';+import { Flexbox, Icon, Tabs } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BookOpenIcon, HistoryIcon, SquareUserIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- link: css`- color: ${cssVar.colorTextDescription};-- &:hover {- color: ${cssVar.colorInfo};- }- `,- nav: css`- border-block-end: 1px solid ${cssVar.colorBorder};- `,- };+const styles = stylex.create({+ link: { color: { 'default': cssVar.colorTextDescription, ':hover': cssVar.colorInfo } },+ nav: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorder,+ },});export enum GroupAgentNavKey {@@ -64,7 +60,12 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = GroupAgentNavKeyreturn mobile ? (nav) : (- <Flexbox horizontal align={'center'} className={styles.nav} justify={'space-between'}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.nav).className}+ justify={'space-between'}+ >{nav}<Flexboxhorizontal@@ -72,7 +73,12 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = GroupAgentNavKeygap={12}style={{ marginInlineStart: 12, whiteSpace: 'nowrap' }}>- <a className={styles.link} href={SOCIAL_URL.discord} rel="noreferrer" target="_blank">+ <a+ {...stylex.props(styles.link)}+ href={SOCIAL_URL.discord}+ rel="noreferrer"+ target="_blank"+ >{t('groupAgents.details.nav.needHelp', { defaultValue: 'Need help?' })}</a></Flexbox>diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Details/Overview/index.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Details/Overview/index.tsxindex 11a1bfd2458..173a1e05cd1 100644--- a/src/routes/(main)/community/(detail)/group_agent/features/Details/Overview/index.tsx+++ b/src/routes/(main)/community/(detail)/group_agent/features/Details/Overview/index.tsx@@ -1,15 +1,8 @@import { BRANDING_NAME } from '@lobechat/business-const';-import {- Accordion,- Avatar,- Block,- createStaticStyles,- Flexbox,- Grid,- Text,- useTheme,-} from '@lobehub/ui';+import { Accordion, Avatar, Block, Flexbox, Grid, Text, useTheme } from '@lobehub/ui';import { ChatList } from '@lobehub/ui/chat';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -20,19 +13,9 @@ import { authSelectors, userProfileSelectors } from '@/store/user/selectors';import Title from '../../../../../features/Title';import { useDetailContext } from '../../DetailProvider';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- flex: 1;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- title: css`- margin: 0 !important;- font-size: 14px !important;- font-weight: 500 !important;- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', color: cssVar.colorTextSecondary },+ title: { margin: '0', fontSize: '14px', fontWeight: 500 },});const MemberCard = memo(({ agent, currentVersion }: { agent: any; currentVersion: any }) => {@@ -62,7 +45,7 @@ const MemberCard = memo(({ agent, currentVersion }: { agent: any; currentVersionoverflow: 'hidden',}}>- <Text ellipsis as={'h3'} className={styles.title}>+ <Text ellipsis as={'h3'} className={stylex.props(styles.title).className}>{currentVersion.name || agent.name}</Text></Flexbox>@@ -72,7 +55,7 @@ const MemberCard = memo(({ agent, currentVersion }: { agent: any; currentVersion{currentVersion.description && currentVersion.description !== 'No description provided' && (<Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 2,}}diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Header.tsxindex e68309b8c46..64b182d60fc 100644--- a/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx+++ b/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx@@ -4,8 +4,6 @@ import {ActionIcon,Avatar,Button,- createStaticStyles,- cssVar,Flexbox,Icon,Tag,@@ -15,6 +13,8 @@ import {TooltipGroup,useResponsive,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BookmarkCheckIcon, BookmarkIcon, DotIcon, GitBranchIcon, UsersIcon } from 'lucide-react';import qs from 'query-string';import { memo, useState } from 'react';@@ -31,12 +31,7 @@ import { resolveCommunityProfileLink } from '../../utils/profileLink';import { useDetailContext } from './DetailProvider';import GroupAgentForkTag from './GroupAgentForkTag';-const styles = createStaticStyles(({ css, cssVar }) => ({- time: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,-}));+const styles = stylex.create({ time: { fontSize: '12px', color: cssVar.colorTextDescription } });const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {const { t } = useTranslation('discover');@@ -181,7 +176,10 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {);})()}<Icon icon={DotIcon} />- <PublishedTime className={styles.time} date={createdAt as string} />+ <PublishedTime+ className={stylex.props(styles.time).className}+ date={createdAt as string}+ /><GroupAgentForkTag />{!!forkCount && forkCount > 0 && (<Tag color="default" icon={<Icon icon={GitBranchIcon} />}>diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsxindex 29109da347b..2e71170cc22 100644--- a/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx+++ b/src/routes/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx@@ -1,6 +1,8 @@'use client';-import { Button, createStaticStyles, Flexbox, Select, toast } from '@lobehub/ui';+import { Button, Flexbox, Select, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { customAlphabet } from 'nanoid/non-secure';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -18,48 +20,44 @@ import { useAgentGroupStore } from '@/store/agentGroup';import { useDetailContext } from '../../DetailProvider';-const styles = createStaticStyles(({ css, cssVar }) => ({- buttonGroup: css`- width: 100%;- `,- forkButton: css`- flex: 1;- width: unset;- border-start-start-radius: 0 !important;- border-end-start-radius: 0 !important;- `,+const styles = stylex.create({+ buttonGroup: { width: '100%' },+ forkButton: {+ flex: '1',+ width: 'unset',+ borderStartStartRadius: '0',+ borderEndStartRadius: '0',+ },// Match Button type="primary" on the right so the two halves read as one// pill. (colorPrimary bg + colorBgLayout text) auto-flips with the theme:// dark bg + near-white text in light theme, white bg + near-black text// in dark theme. We use colorBgLayout directly instead of the// semantically-named colorTextLightSolid because the cssVar proxy doesn't// pick up LobeHub's JS-level override of that token.- visibilitySelect: css`- width: 130px;- border-color: ${cssVar.colorPrimary} !important;- border-inline-end-width: 0 !important;- border-start-end-radius: 0 !important;- border-end-end-radius: 0 !important;-- color: ${cssVar.colorBgLayout} !important;-- background: ${cssVar.colorPrimary} !important;-- & svg {- color: ${cssVar.colorBgLayout};- }-- &:hover:not([data-disabled]) {- border-color: ${cssVar.colorPrimaryHover} !important;- background: ${cssVar.colorPrimaryHover} !important;- }-- &:active:not([data-disabled]) {- border-color: ${cssVar.colorPrimaryActive} !important;- background: ${cssVar.colorPrimaryActive} !important;- }- `,-}));+ visibilitySelect: {+ width: '130px',+ borderColor: cssVar.colorPrimary,+ borderInlineEndWidth: '0',+ borderStartEndRadius: '0',+ borderEndEndRadius: '0',+ color: cssVar.colorBgLayout,+ backgroundColor: cssVar.colorPrimary,+ backgroundImage: 'none',+ },+ // Hover / active feedback; skipped while the select is disabled.+ visibilitySelectInteractive: {+ borderColor: {+ 'default': cssVar.colorPrimary,+ ':hover': cssVar.colorPrimaryHover,+ ':active': cssVar.colorPrimaryActive,+ },+ backgroundColor: {+ 'default': cssVar.colorPrimary,+ ':hover': cssVar.colorPrimaryHover,+ ':active': cssVar.colorPrimaryActive,+ },+ },+});/*** Generate a market identifier (8-character lowercase alphanumeric string)@@ -275,7 +273,7 @@ const ForkGroupAndChat = memo<{ mobile?: boolean }>(() => {return (<Buttonblock- className={styles.buttonGroup}+ className={stylex.props(styles.buttonGroup).className}disabled={!canCreate}loading={isLoading}size={'large'}@@ -295,19 +293,27 @@ const ForkGroupAndChat = memo<{ mobile?: boolean }>(() => {{ label: t('fork.visibilityPublic'), value: 'public' },];+ const isVisibilityDisabled = !canCreate || isLoading;+return (- <Flexbox horizontal className={styles.buttonGroup} gap={0}>+ <Flexbox horizontal className={stylex.props(styles.buttonGroup).className} gap={0}><Select- className={styles.visibilitySelect}- disabled={!canCreate || isLoading}+ disabled={isVisibilityDisabled}options={visibilityOptions}size={'large'}+ suffixIconProps={{ color: cssVar.colorBgLayout }}value={visibility}+ className={+ stylex.props(+ styles.visibilitySelect,+ !isVisibilityDisabled && styles.visibilitySelectInteractive,+ ).className+ }onChange={(v) => setVisibility(v as ForkTarget)}/><Buttonblock- className={styles.forkButton}+ className={stylex.props(styles.forkButton).className}disabled={!canCreate}loading={isLoading}size={'large'}diff --git a/src/routes/(main)/community/(detail)/mcp/features/Sidebar/ActionButton/index.tsx b/src/routes/(main)/community/(detail)/mcp/features/Sidebar/ActionButton/index.tsxindex 78925e32418..10ae96f2a5c 100644--- a/src/routes/(main)/community/(detail)/mcp/features/Sidebar/ActionButton/index.tsx+++ b/src/routes/(main)/community/(detail)/mcp/features/Sidebar/ActionButton/index.tsx@@ -1,6 +1,6 @@'use client';-import { Button, createStaticStyles, Flexbox, Icon } from '@lobehub/ui';+import { Button, Flexbox, Icon } from '@lobehub/ui';import { Trash2Icon } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -12,14 +12,6 @@ import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';import { useToolStore } from '@/store/tool';import { pluginSelectors } from '@/store/tool/slices/plugin/selectors';-const styles = createStaticStyles(({ css }) => ({- button: css`- button {- width: 100%;- }- `,-}));-const ActionButton = memo(() => {const { t } = useTranslation(['discover', 'plugin']);const detailContext = useDetailContext();@@ -64,13 +56,7 @@ const ActionButton = memo(() => {return installed ? (<Flexbox horizontal gap={8}>- <Button- block- className={styles.button}- disabled={buttonLoading}- size={'large'}- type={'default'}- >+ <Button block disabled={buttonLoading} size={'large'} type={'default'}>{t('plugins.installed')}</Button>@@ -95,7 +81,6 @@ const ActionButton = memo(() => {<><Buttonblock- className={styles.button}disabled={!canCreate || !canEdit}loading={buttonLoading}size={'large'}diff --git a/src/routes/(main)/community/(detail)/mcp/features/Sidebar/Related/Item.tsx b/src/routes/(main)/community/(detail)/mcp/features/Sidebar/Related/Item.tsxindex 8be4196221f..f801afbee05 100644--- a/src/routes/(main)/community/(detail)/mcp/features/Sidebar/Related/Item.tsx+++ b/src/routes/(main)/community/(detail)/mcp/features/Sidebar/Related/Item.tsx@@ -1,26 +1,18 @@-import { Avatar, Block, createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { type DiscoverMcpItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- flex: 1;- margin: 0 !important;- font-size: 14px !important;- color: ${cssVar.colorTextSecondary};- `,- title: css`- margin: 0 !important;- font-size: 14px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', fontSize: '14px', color: cssVar.colorTextSecondary },+ title: {+ margin: '0',+ fontSize: '14px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const RelatedItem = memo<DiscoverMcpItem>(({ name, icon, description, identifier }) => {@@ -34,12 +26,12 @@ const RelatedItem = memo<DiscoverMcpItem>(({ name, icon, description, identifieroverflow: 'hidden',}}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{name}</Text><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 2,}}diff --git a/src/routes/(main)/community/(detail)/model/features/Details/Nav.tsx b/src/routes/(main)/community/(detail)/model/features/Details/Nav.tsxindex 47596ca56ae..80134615483 100644--- a/src/routes/(main)/community/(detail)/model/features/Details/Nav.tsx+++ b/src/routes/(main)/community/(detail)/model/features/Details/Nav.tsx@@ -1,7 +1,9 @@'use client';import { SOCIAL_URL } from '@lobechat/business-const';-import { createStaticStyles, Flexbox, Icon, Tabs } from '@lobehub/ui';+import { Flexbox, Icon, Tabs } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BookOpenIcon, ListIcon, Settings2Icon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -10,19 +12,13 @@ import urlJoin from 'url-join';import { GITHUB, GITHUB_ISSUES } from '@/const/url';import { ModelNavKey } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- link: css`- color: ${cssVar.colorTextDescription};-- &:hover {- color: ${cssVar.colorInfo};- }- `,- nav: css`- border-block-end: 1px solid ${cssVar.colorBorder};- `,- };+const styles = stylex.create({+ link: { color: { 'default': cssVar.colorTextDescription, ':hover': cssVar.colorInfo } },+ nav: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorder,+ },});interface NavProps {@@ -62,7 +58,12 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = ModelNavKey.Overreturn mobile ? (nav) : (- <Flexbox horizontal align={'center'} className={styles.nav} justify={'space-between'}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.nav).className}+ justify={'space-between'}+ >{nav}<Flexboxhorizontal@@ -70,18 +71,23 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = ModelNavKey.Overgap={12}style={{ marginInlineStart: 12, whiteSpace: 'nowrap' }}>- <a className={styles.link} href={SOCIAL_URL.discord} rel="noreferrer" target="_blank">+ <a+ {...stylex.props(styles.link)}+ href={SOCIAL_URL.discord}+ rel="noreferrer"+ target="_blank"+ >{t('mcp.details.nav.needHelp')}</a><a- className={styles.link}+ {...stylex.props(styles.link)}href={urlJoin(GITHUB, 'tree/main/src/config/aiModels')}rel="noreferrer"target="_blank">{t('mcp.details.nav.viewSourceCode')}</a>- <a className={styles.link} href={GITHUB_ISSUES} rel="noreferrer" target="_blank">+ <a {...stylex.props(styles.link)} href={GITHUB_ISSUES} rel="noreferrer" target="_blank">{t('mcp.details.nav.reportIssue')}</a></Flexbox>diff --git a/src/routes/(main)/community/(detail)/model/features/Header.tsx b/src/routes/(main)/community/(detail)/model/features/Header.tsxindex 860a95c2168..672309bf77a 100644--- a/src/routes/(main)/community/(detail)/model/features/Header.tsx+++ b/src/routes/(main)/community/(detail)/model/features/Header.tsx@@ -1,6 +1,8 @@'use client';-import { createStaticStyles, cssVar, Flexbox, Icon, Text, useResponsive } from '@lobehub/ui';+import { Flexbox, Icon, Text, useResponsive } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { DotIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -12,20 +14,8 @@ import ModelTypeIcon from '@/routes/(main)/community/(list)/model/features/List/import { useDetailContext } from './DetailProvider';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- color: ${cssVar.colorTextSecondary};- `,- time: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- version: css`- font-family: ${cssVar.fontFamilyCode};- font-size: 13px;- `,- };+const styles = stylex.create({+ time: { fontSize: '12px', color: cssVar.colorTextDescription },});const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {@@ -87,7 +77,10 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {{...abilities}/><Icon icon={DotIcon} />- <PublishedTime className={styles.time} date={releasedAt as string} />+ <PublishedTime+ className={stylex.props(styles.time).className}+ date={releasedAt as string}+ /></Flexbox></Flexbox></Flexbox>diff --git a/src/routes/(main)/community/(detail)/model/features/Sidebar/ActionButton/ChatWithModel.tsx b/src/routes/(main)/community/(detail)/model/features/Sidebar/ActionButton/ChatWithModel.tsxindex 7ab21f6da1a..a0b0d6fef57 100644--- a/src/routes/(main)/community/(detail)/model/features/Sidebar/ActionButton/ChatWithModel.tsx+++ b/src/routes/(main)/community/(detail)/model/features/Sidebar/ActionButton/ChatWithModel.tsx@@ -1,6 +1,6 @@'use client';-import { Button, createStaticStyles, DropdownMenu, SplitButton } from '@lobehub/ui';+import { Button, DropdownMenu, SplitButton } from '@lobehub/ui';import { memo } from 'react';import { useTranslation } from 'react-i18next';import urlJoin from 'url-join';@@ -11,14 +11,6 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { useDetailContext } from '../../DetailProvider';-const styles = createStaticStyles(({ css }) => ({- button: css`- button {- width: 100%;- }- `,-}));-const ChatWithModel = memo(() => {const { t } = useTranslation('discover');const { providers = [] } = useDetailContext();@@ -53,7 +45,7 @@ const ChatWithModel = memo(() => {if (items.length === 1)return (<WorkspaceLink style={{ flex: 1 }} to={urlJoin('/community/provider', items[0].key)}>- <Button block className={styles.button} size={'large'} type={'primary'}>+ <Button block size={'large'} type={'primary'}>{t('models.guide')}</Button></WorkspaceLink>@@ -61,12 +53,7 @@ const ChatWithModel = memo(() => {return (<DropdownMenu data-no-highlight items={items}>- <Button- className={styles.button}- size={'large'}- style={{ flex: 1, width: 'unset' }}- type={'primary'}- >+ <Button size={'large'} style={{ flex: 1, width: 'unset' }} type={'primary'}>{t('models.guide')}</Button></DropdownMenu>diff --git a/src/routes/(main)/community/(detail)/model/features/Sidebar/Related/Item.tsx b/src/routes/(main)/community/(detail)/model/features/Sidebar/Related/Item.tsxindex 3f6b79b8b1e..994509e7777 100644--- a/src/routes/(main)/community/(detail)/model/features/Sidebar/Related/Item.tsx+++ b/src/routes/(main)/community/(detail)/model/features/Sidebar/Related/Item.tsx@@ -1,28 +1,20 @@-import { Block, createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { ModelIcon } from '@/components/LobeIcons';import { type DiscoverModelItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- flex: 1;- margin: 0 !important;- font-size: 14px !important;- color: ${cssVar.colorTextSecondary};- `,- title: css`- margin: 0 !important;- font-size: 14px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', fontSize: '14px', color: cssVar.colorTextSecondary },+ title: {+ margin: '0',+ fontSize: '14px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const RelatedItem = memo<DiscoverModelItem>(({ description, identifier, displayName }) => {@@ -37,12 +29,12 @@ const RelatedItem = memo<DiscoverModelItem>(({ description, identifier, displayNoverflow: 'hidden',}}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{displayName || identifier}</Text><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 2,}}diff --git a/src/routes/(main)/community/(detail)/model/features/Sidebar/RelatedProviders/Item.tsx b/src/routes/(main)/community/(detail)/model/features/Sidebar/RelatedProviders/Item.tsxindex bc5df504521..ecf89592fc6 100644--- a/src/routes/(main)/community/(detail)/model/features/Sidebar/RelatedProviders/Item.tsx+++ b/src/routes/(main)/community/(detail)/model/features/Sidebar/RelatedProviders/Item.tsx@@ -1,28 +1,20 @@-import { Block, createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { ProviderIcon } from '@/components/LobeIcons';import { type DiscoverModelDetailProviderItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- flex: 1;- margin: 0 !important;- font-size: 14px !important;- color: ${cssVar.colorTextSecondary};- `,- title: css`- margin: 0 !important;- font-size: 14px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', fontSize: '14px', color: cssVar.colorTextSecondary },+ title: {+ margin: '0',+ fontSize: '14px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const RelatedItem = memo<DiscoverModelDetailProviderItem>(({ description, id, name }) => {@@ -37,12 +29,12 @@ const RelatedItem = memo<DiscoverModelDetailProviderItem>(({ description, id, naoverflow: 'hidden',}}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{name}</Text><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 2,}}diff --git a/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx b/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsxindex b2ce527211c..4a220027abf 100644--- a/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx+++ b/src/routes/(main)/community/(detail)/organization/features/Header/Banner.tsx@@ -1,61 +1,47 @@'use client';-import { Center, createStaticStyles, responsive } from '@lobehub/ui';+import { Center } 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 { memo } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => ({- banner: css`- position: absolute;- inset-block-start: 0;- inset-inline-start: 0;+import { sx } from '@/styles/sx';- width: 100%;- height: 160px;- padding: 16px;+const WIDE = '@media (width <= 1720px)';- ${responsive.sm} {- position: relative;-- width: calc(100% + 32px);- height: 120px;- margin-block: -16px 0;- margin-inline: -16px;- }-- @media (width <= 1720px) {- height: 144px;- padding: 0;- }- `,- bannerAvatar: css`- filter: blur(100px);- `,- bannerInner: css`- position: relative;-- overflow: hidden;-- width: 100%;- height: 100%;- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorFillTertiary};-- @media (width <= 1720px) {- border-radius: 0;- }- `,- placeholder: css`- position: relative;- width: 100%;- height: 64px;- min-height: 64px;-- ${responsive.sm} {- display: none;- }- `,-}));+// Note: at the `sm` breakpoint the wide-screen rules also match, and they used to win+// for height / padding / border-radius, so only the effective values are kept.+const styles = stylex.create({+ banner: {+ position: { default: 'absolute', [media.sm]: 'relative' },+ insetBlockStart: '0',+ insetInlineStart: '0',+ width: { default: '100%', [media.sm]: 'calc(100% + 32px)' },+ height: { default: '160px', [WIDE]: '144px' },+ padding: { default: '16px', [WIDE]: '0' },+ marginBlockStart: { default: null, [media.sm]: '-16px' },+ marginBlockEnd: { default: null, [media.sm]: '0' },+ marginInline: { default: null, [media.sm]: '-16px' },+ },+ bannerAvatar: { filter: 'blur(100px)' },+ bannerInner: {+ position: 'relative',+ overflow: 'hidden',+ width: '100%',+ height: '100%',+ borderRadius: { default: cssVar.borderRadiusLG, [WIDE]: '0' },+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ placeholder: {+ position: 'relative',+ width: '100%',+ height: '64px',+ minHeight: '64px',+ display: { default: null, [media.sm]: 'none' },+ },+});interface BannerProps {avatar?: string | null;@@ -68,23 +54,22 @@ const Banner = memo<BannerProps>(({ avatar, bannerUrl }) => {return (<>- <div className={styles.banner}>- <Center className={styles.bannerInner}>+ <div {...stylex.props(styles.banner)}>+ <Center className={stylex.props(styles.bannerInner).className}>{backgroundImage && (<div- className={shouldBlur ? styles.bannerAvatar : undefined}- style={{+ {...sx(shouldBlur && styles.bannerAvatar, undefined, {backgroundImage: `url(${backgroundImage})`,backgroundPosition: 'center',backgroundSize: 'cover',height: '100%',width: '100%',- }}+ })}/>)}</Center></div>- <div className={styles.placeholder} />+ <div {...stylex.props(styles.placeholder)} /></>);});diff --git a/src/routes/(main)/community/(detail)/provider/features/Details/Nav.tsx b/src/routes/(main)/community/(detail)/provider/features/Details/Nav.tsxindex 5fd47cb9a53..c97b2061acd 100644--- a/src/routes/(main)/community/(detail)/provider/features/Details/Nav.tsx+++ b/src/routes/(main)/community/(detail)/provider/features/Details/Nav.tsx@@ -1,7 +1,9 @@'use client';import { BRANDING_PROVIDER, SOCIAL_URL } from '@lobechat/business-const';-import { createStaticStyles, Flexbox, Icon, Tabs } from '@lobehub/ui';+import { Flexbox, Icon, Tabs } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BookOpenIcon, BrainCircuitIcon, ListIcon, SquareArrowOutUpRight } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -12,22 +14,18 @@ import { ProviderNavKey } from '@/types/discover';import { useDetailContext } from '../DetailProvider';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- link: css`- display: inline-flex;- gap: 4px;- align-items: center;- color: ${cssVar.colorTextDescription};-- &:hover {- color: ${cssVar.colorInfo};- }- `,- nav: css`- border-block-end: 1px solid ${cssVar.colorBorder};- `,- };+const styles = stylex.create({+ link: {+ display: 'inline-flex',+ gap: '4px',+ alignItems: 'center',+ color: { 'default': cssVar.colorTextDescription, ':hover': cssVar.colorInfo },+ },+ nav: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorder,+ },});interface NavProps {@@ -77,7 +75,12 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = ProviderNavKey.Oreturn mobile ? (nav) : (- <Flexbox horizontal align={'center'} className={styles.nav} justify={'space-between'}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.nav).className}+ justify={'space-between'}+ >{nav}<Flexboxhorizontal@@ -85,13 +88,18 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = ProviderNavKey.Ogap={12}style={{ marginInlineStart: 12, whiteSpace: 'nowrap' }}>- <a className={styles.link} href={SOCIAL_URL.discord} rel="noreferrer" target="_blank">+ <a+ {...stylex.props(styles.link)}+ href={SOCIAL_URL.discord}+ rel="noreferrer"+ target="_blank"+ >{t('mcp.details.nav.needHelp')}<Icon icon={SquareArrowOutUpRight} size={12} /></a>{identifier && (<a- className={styles.link}+ {...stylex.props(styles.link)}href={urlJoin(GITHUB, 'tree/main/src/config/modelProviders', `${identifier}.ts`)}rel="noreferrer"target="_blank"@@ -100,7 +108,7 @@ const Nav = memo<NavProps>(({ mobile, setActiveTab, activeTab = ProviderNavKey.O<Icon icon={SquareArrowOutUpRight} size={12} /></a>)}- <a className={styles.link} href={GITHUB_ISSUES} rel="noreferrer" target="_blank">+ <a {...stylex.props(styles.link)} href={GITHUB_ISSUES} rel="noreferrer" target="_blank">{t('mcp.details.nav.reportIssue')}<Icon icon={SquareArrowOutUpRight} size={12} /></a>diff --git a/src/routes/(main)/community/(detail)/provider/features/Sidebar/Related/Item.tsx b/src/routes/(main)/community/(detail)/provider/features/Sidebar/Related/Item.tsxindex f435b41f9b8..19fb465d8e5 100644--- a/src/routes/(main)/community/(detail)/provider/features/Sidebar/Related/Item.tsx+++ b/src/routes/(main)/community/(detail)/provider/features/Sidebar/Related/Item.tsx@@ -1,28 +1,20 @@-import { Block, createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { ProviderIcon } from '@/components/LobeIcons';import { type DiscoverProviderItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- flex: 1;- margin: 0 !important;- font-size: 14px !important;- color: ${cssVar.colorTextSecondary};- `,- title: css`- margin: 0 !important;- font-size: 14px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', fontSize: '14px', color: cssVar.colorTextSecondary },+ title: {+ margin: '0',+ fontSize: '14px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const RelatedItem = memo<DiscoverProviderItem>(({ description, identifier, name }) => {@@ -37,12 +29,12 @@ const RelatedItem = memo<DiscoverProviderItem>(({ description, identifier, nameoverflow: 'hidden',}}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{name}</Text><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 2,}}diff --git a/src/routes/(main)/community/(detail)/provider/features/Sidebar/RelatedModels/Item.tsx b/src/routes/(main)/community/(detail)/provider/features/Sidebar/RelatedModels/Item.tsxindex 517358e1bbe..e78dd7e4d5a 100644--- a/src/routes/(main)/community/(detail)/provider/features/Sidebar/RelatedModels/Item.tsx+++ b/src/routes/(main)/community/(detail)/provider/features/Sidebar/RelatedModels/Item.tsx@@ -1,28 +1,20 @@-import { Block, createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { ModelIcon } from '@/components/LobeIcons';import { type DiscoverProviderDetailModelItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- flex: 1;- margin: 0 !important;- font-size: 14px !important;- color: ${cssVar.colorTextSecondary};- `,- title: css`- margin: 0 !important;- font-size: 14px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', fontSize: '14px', color: cssVar.colorTextSecondary },+ title: {+ margin: '0',+ fontSize: '14px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const RelatedItem = memo<DiscoverProviderDetailModelItem>(({ description, id, displayName }) => {@@ -37,12 +29,12 @@ const RelatedItem = memo<DiscoverProviderDetailModelItem>(({ description, id, dioverflow: 'hidden',}}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{displayName || id}</Text><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 2,}}diff --git a/src/routes/(main)/community/(detail)/user/features/Header/Banner.tsx b/src/routes/(main)/community/(detail)/user/features/Header/Banner.tsxindex 66fbf62ac9e..aa4b814efde 100644--- a/src/routes/(main)/community/(detail)/user/features/Header/Banner.tsx+++ b/src/routes/(main)/community/(detail)/user/features/Header/Banner.tsx@@ -1,66 +1,47 @@'use client';-import { Center, createStaticStyles, responsive } from '@lobehub/ui';+import { Center } 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 { memo } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => ({- banner: css`- position: absolute;- inset-block-start: 0;- inset-inline-start: 0;+import { sx } from '@/styles/sx';- width: 100%;- height: 160px;- padding: 16px;+const WIDE = '@media (width <= 1720px)';- ${responsive.sm} {- position: relative;-- width: calc(100% + 32px);- height: 120px;- margin-block: -16px 0;- margin-inline: -16px;- }-- @media (width <= 1720px) {- height: 144px;- padding: 0;- }- `,- bannerAvatar: css`- filter: blur(100px);- `,- bannerInner: css`- position: relative;-- overflow: hidden;-- width: 100%;- height: 100%;- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorFillTertiary};-- @media (width <= 1720px) {- border-radius: 0;- }- `,- button: css`- position: absolute;- inset-block-end: -16px;- inset-inline-end: 16px;- `,- placeholder: css`- position: relative;- width: 100%;- height: 64px;- min-height: 64px;-- ${responsive.sm} {- display: none;- }- `,-}));+// Note: at the `sm` breakpoint the wide-screen rules also match, and they used to win+// for height / padding / border-radius, so only the effective values are kept.+const styles = stylex.create({+ banner: {+ position: { default: 'absolute', [media.sm]: 'relative' },+ insetBlockStart: '0',+ insetInlineStart: '0',+ width: { default: '100%', [media.sm]: 'calc(100% + 32px)' },+ height: { default: '160px', [WIDE]: '144px' },+ padding: { default: '16px', [WIDE]: '0' },+ marginBlockStart: { default: null, [media.sm]: '-16px' },+ marginBlockEnd: { default: null, [media.sm]: '0' },+ marginInline: { default: null, [media.sm]: '-16px' },+ },+ bannerAvatar: { filter: 'blur(100px)' },+ bannerInner: {+ position: 'relative',+ overflow: 'hidden',+ width: '100%',+ height: '100%',+ borderRadius: { default: cssVar.borderRadiusLG, [WIDE]: '0' },+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ placeholder: {+ position: 'relative',+ width: '100%',+ height: '64px',+ minHeight: '64px',+ display: { default: null, [media.sm]: 'none' },+ },+});interface BannerProps {avatar?: string | null;@@ -74,23 +55,22 @@ const Banner = memo<BannerProps>(({ avatar, bannerUrl }) => {return (<>- <div className={styles.banner}>- <Center className={styles.bannerInner}>+ <div {...stylex.props(styles.banner)}>+ <Center className={stylex.props(styles.bannerInner).className}>{backgroundImage && (<div- className={shouldBlur ? styles.bannerAvatar : undefined}- style={{+ {...sx(shouldBlur && styles.bannerAvatar, undefined, {backgroundImage: `url(${backgroundImage})`,backgroundPosition: 'center',backgroundSize: 'cover',height: '100%',width: '100%',- }}+ })}/>)}</Center></div>- <div className={styles.placeholder} />+ <div {...stylex.props(styles.placeholder)} /></>);});diff --git a/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsxindex 5ed7d13a430..077e844e37e 100644--- a/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx+++ b/src/routes/(main)/community/(detail)/user/features/UserAgentCard.tsx@@ -3,8 +3,6 @@import {Avatar,Block,- createStaticStyles,- cx,DropdownMenu,Flexbox,Icon,@@ -16,6 +14,8 @@ import {Tooltip,TooltipGroup,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {AlertTriangle,ClockIcon,@@ -64,59 +64,39 @@ const getStatusTagColor = (status?: AgentStatus) => {}};-const styles = createStaticStyles(({ css, cssVar }) => {- return {- author: css`- color: ${cssVar.colorTextDescription};- `,- desc: css`- flex: 1;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- footer: css`- margin-block-start: 16px;- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- moreButton: css`- position: absolute;- z-index: 10;- inset-block-start: 12px;- inset-inline-end: 12px;-- opacity: 0;-- transition: opacity 0.2s;- `,- secondaryDesc: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- statTag: css`- border-radius: 4px;-- font-family: ${cssVar.fontFamilyCode};- font-size: 11px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};- `,- title: css`- margin: 0 !important;- font-size: 16px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- wrapper: css`- &:hover .more-button {- opacity: 1;- }- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', color: cssVar.colorTextSecondary },+ footer: {+ marginBlockStart: '16px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ moreButton: {+ position: 'absolute',+ zIndex: 10,+ insetBlockStart: '12px',+ insetInlineEnd: '12px',+ opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 },+ transition: 'opacity 0.2s',+ },+ secondaryDesc: { fontSize: '12px', color: cssVar.colorTextDescription },+ statTag: {+ borderRadius: '4px',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: '11px',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ title: {+ margin: '0',+ fontSize: '16px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});type UserAgentCardProps = DiscoverAssistantItem;@@ -255,7 +235,7 @@ const UserAgentCard = memo<UserAgentCardProps>(return (<Blockclickable- className={styles.wrapper}+ className={stylex.props(stylex.defaultMarker()).className}height={'100%'}variant={'outlined'}width={'100%'}@@ -269,7 +249,7 @@ const UserAgentCard = memo<UserAgentCardProps>({isOwner && !isUnderReview && (<div onClick={stopPropagation}><DropdownMenu items={menuItems as any}>- <div className={cx('more-button', styles.moreButton)}>+ <div {...stylex.props(styles.moreButton)}><Icon icon={MoreVerticalIcon} size={16} style={{ cursor: 'pointer' }} /></div></DropdownMenu>@@ -310,7 +290,12 @@ const UserAgentCard = memo<UserAgentCardProps>(to={link}onClick={(e) => e.stopPropagation()}>- <Text ellipsis as={'h3'} className={styles.title} style={{ flex: 1 }}>+ <Text+ ellipsis+ as={'h3'}+ className={stylex.props(styles.title).className}+ style={{ flex: 1 }}+ >{title}</Text></WorkspaceLink>@@ -333,7 +318,7 @@ const UserAgentCard = memo<UserAgentCardProps>(<Flexbox flex={1} gap={12} paddingInline={16}><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 3,}}@@ -347,7 +332,10 @@ const UserAgentCard = memo<UserAgentCardProps>(styles={{ root: { pointerEvents: 'none' } }}title={t('assistants.tokenUsage')}>- <Tag className={styles.statTag} icon={<Icon icon={CoinsIcon} />}>+ <Tag+ className={stylex.props(styles.statTag).className}+ icon={<Icon icon={CoinsIcon} />}+ >{formatIntergerNumber(tokenUsage)}</Tag></Tooltip>@@ -357,7 +345,10 @@ const UserAgentCard = memo<UserAgentCardProps>(styles={{ root: { pointerEvents: 'none' } }}title={t('fork.forksCount', { count: forkCount })}>- <Tag className={styles.statTag} icon={<Icon icon={GitForkIcon} />}>+ <Tag+ className={stylex.props(styles.statTag).className}+ icon={<Icon icon={GitForkIcon} />}+ >{formatIntergerNumber(forkCount)}</Tag></Tooltip>@@ -368,19 +359,22 @@ const UserAgentCard = memo<UserAgentCardProps>(<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}justify={'space-between'}padding={16}><Flexboxhorizontalalign={'center'}- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}justify={'space-between'}><Flexbox horizontal align={'center'} gap={4}><Icon icon={ClockIcon} size={14} />- <PublishedTime className={styles.secondaryDesc} date={createdAt} />+ <PublishedTime+ className={stylex.props(styles.secondaryDesc).className}+ date={createdAt}+ /></Flexbox>{category && t(`category.assistant.${category}` as any)}</Flexbox>diff --git a/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsxindex f85463dfaaa..f730042aa1f 100644--- a/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx+++ b/src/routes/(main)/community/(detail)/user/features/UserGroupCard.tsx@@ -3,8 +3,6 @@import {Avatar,Block,- createStaticStyles,- cx,DropdownMenu,Flexbox,Icon,@@ -15,6 +13,8 @@ import {Tooltip,TooltipGroup,} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import {AlertTriangle,ClockIcon,@@ -57,56 +57,39 @@ const getStatusTagColor = (status?: GroupAgentStatus) => {}};-const styles = createStaticStyles(({ css, cssVar }) => {- return {- desc: css`- flex: 1;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- footer: css`- margin-block-start: 16px;- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- moreButton: css`- position: absolute;- z-index: 10;- inset-block-start: 12px;- inset-inline-end: 12px;-- opacity: 0;-- transition: opacity 0.2s;- `,- secondaryDesc: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- statTag: css`- border-radius: 4px;-- font-family: ${cssVar.fontFamilyCode};- font-size: 11px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};- `,- title: css`- margin: 0 !important;- font-size: 16px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- wrapper: css`- &:hover .more-button {- opacity: 1;- }- `,- };+const styles = stylex.create({+ desc: { flex: '1', margin: '0', color: cssVar.colorTextSecondary },+ footer: {+ marginBlockStart: '16px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ moreButton: {+ position: 'absolute',+ zIndex: 10,+ insetBlockStart: '12px',+ insetInlineEnd: '12px',+ opacity: { default: 0, [stylex.when.ancestor(':hover')]: 1 },+ transition: 'opacity 0.2s',+ },+ secondaryDesc: { fontSize: '12px', color: cssVar.colorTextDescription },+ statTag: {+ borderRadius: '4px',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: '11px',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ title: {+ margin: '0',+ fontSize: '16px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});type UserGroupCardProps = DiscoverGroupAgentItem;@@ -179,7 +162,7 @@ const UserGroupCard = memo<UserGroupCardProps>(return (<Blockclickable- className={styles.wrapper}+ className={stylex.props(stylex.defaultMarker()).className}height={'100%'}variant={'outlined'}width={'100%'}@@ -193,7 +176,7 @@ const UserGroupCard = memo<UserGroupCardProps>({isOwner && !isUnderReview && (<div onClick={stopPropagation}><DropdownMenu items={menuItems as any}>- <div className={cx('more-button', styles.moreButton)}>+ <div {...stylex.props(styles.moreButton)}><Icon icon={MoreVerticalIcon} size={16} style={{ cursor: 'pointer' }} /></div></DropdownMenu>@@ -228,7 +211,12 @@ const UserGroupCard = memo<UserGroupCardProps>(to={link}onClick={stopPropagation}>- <Text ellipsis as={'h3'} className={styles.title} style={{ flex: 1 }}>+ <Text+ ellipsis+ as={'h3'}+ className={stylex.props(styles.title).className}+ style={{ flex: 1 }}+ >{title}</Text></WorkspaceLink>@@ -251,7 +239,7 @@ const UserGroupCard = memo<UserGroupCardProps>(<Flexbox flex={1} gap={12} paddingInline={16}><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 3,}}@@ -266,7 +254,10 @@ const UserGroupCard = memo<UserGroupCardProps>(styles={{ root: { pointerEvents: 'none' } }}title={t('groupAgents.memberCount', { defaultValue: 'Members' })}>- <Tag className={styles.statTag} icon={<Icon icon={UsersIcon} />}>+ <Tag+ className={stylex.props(styles.statTag).className}+ icon={<Icon icon={UsersIcon} />}+ >{formatIntergerNumber(memberCount)}</Tag></Tooltip>@@ -277,7 +268,10 @@ const UserGroupCard = memo<UserGroupCardProps>(styles={{ root: { pointerEvents: 'none' } }}title={t('fork.forksCount', { count: forkCount })}>- <Tag className={styles.statTag} icon={<Icon icon={GitForkIcon} />}>+ <Tag+ className={stylex.props(styles.statTag).className}+ icon={<Icon icon={GitForkIcon} />}+ >{formatIntergerNumber(forkCount)}</Tag></Tooltip>@@ -288,7 +282,10 @@ const UserGroupCard = memo<UserGroupCardProps>(styles={{ root: { pointerEvents: 'none' } }}title={t('groupAgents.downloads', { defaultValue: 'Downloads' })}>- <Tag className={styles.statTag} icon={<Icon icon={DownloadIcon} />}>+ <Tag+ className={stylex.props(styles.statTag).className}+ icon={<Icon icon={DownloadIcon} />}+ >{formatIntergerNumber(installCount)}</Tag></Tooltip>@@ -299,19 +296,22 @@ const UserGroupCard = memo<UserGroupCardProps>(<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}justify={'space-between'}padding={16}><Flexboxhorizontalalign={'center'}- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}justify={'space-between'}><Flexbox horizontal align={'center'} gap={4}><Icon icon={ClockIcon} size={14} />- <PublishedTime className={styles.secondaryDesc} date={createdAt} />+ <PublishedTime+ className={stylex.props(styles.secondaryDesc).className}+ date={createdAt}+ /></Flexbox>{category && t(`category.groupAgent.${category}` as any, { defaultValue: category })}</Flexbox>diff --git a/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsxindex aeca5c0c7eb..6fccf6ceab2 100644--- a/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx+++ b/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx@@ -1,6 +1,8 @@'use client';-import { Avatar, Block, createStaticStyles, Flexbox, Text } from '@lobehub/ui';+import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';import urlJoin from 'url-join';@@ -9,35 +11,24 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { type DiscoverPluginItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- author: css`- color: ${cssVar.colorTextDescription};- `,- desc: css`- flex: 1;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- footer: css`- margin-block-start: 16px;- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- secondaryDesc: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- title: css`- margin: 0 !important;- font-size: 16px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ author: { color: cssVar.colorTextDescription },+ desc: { flex: '1', margin: '0', color: cssVar.colorTextSecondary },+ footer: {+ marginBlockStart: '16px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ secondaryDesc: { fontSize: '12px', color: cssVar.colorTextDescription },+ title: {+ margin: '0',+ fontSize: '16px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});type UserPluginCardProps = DiscoverPluginItem;@@ -99,12 +90,17 @@ const UserPluginCard = memo<UserPluginCardProps>(}}><WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{title}</Text></WorkspaceLink></Flexbox>- <Flexbox horizontal align={'center'} className={styles.author} gap={8}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.author).className}+ gap={8}+ >{author && <div>{author}</div>}</Flexbox></Flexbox>@@ -113,7 +109,7 @@ const UserPluginCard = memo<UserPluginCardProps>(<Flexbox flex={1} gap={12} paddingInline={16}><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 3,}}@@ -124,11 +120,16 @@ const UserPluginCard = memo<UserPluginCardProps>(<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}justify={'space-between'}padding={16}>- <Flexbox horizontal align={'center'} className={styles.secondaryDesc} gap={8}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.secondaryDesc).className}+ gap={8}+ >{category && t(`plugins.categories.${category}.name` as any)}</Flexbox></Flexbox>diff --git a/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsxindex 4bf0d011ee1..7a1d8fd57f5 100644--- a/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx+++ b/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx@@ -1,18 +1,9 @@'use client';import { Github } from '@lobehub/icons';-import {- ActionIcon,- Avatar,- Block,- createStaticStyles,- cssVar,- Flexbox,- Icon,- stopPropagation,- Tag,- Text,-} from '@lobehub/ui';+import { ActionIcon, Avatar, Block, Flexbox, Icon, stopPropagation, Tag, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ClockIcon, FileTextIcon, StarIcon } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -24,35 +15,24 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { discoverService } from '@/services/discover';import { type DiscoverSkillItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- author: css`- color: ${cssVar.colorTextDescription};- `,- desc: css`- flex: 1;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- footer: css`- margin-block-start: 16px;- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- secondaryDesc: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- title: css`- margin: 0 !important;- font-size: 16px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ author: { color: cssVar.colorTextDescription },+ desc: { flex: '1', margin: '0', color: cssVar.colorTextSecondary },+ footer: {+ marginBlockStart: '16px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ secondaryDesc: { fontSize: '12px', color: cssVar.colorTextDescription },+ title: {+ margin: '0',+ fontSize: '16px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});type UserSkillCardProps = DiscoverSkillItem;@@ -135,12 +115,17 @@ const UserSkillCard = memo<UserSkillCardProps>(}}><WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{name}</Text></WorkspaceLink></Flexbox>- <Flexbox horizontal align={'center'} className={styles.author} gap={8}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.author).className}+ gap={8}+ >{Boolean(ratingAvg) && (<Flexbox horizontal align={'center'} gap={4} style={{ fontSize: 13 }}><Icon fill={cssVar.colorTextDescription} icon={StarIcon} size={12} />@@ -167,7 +152,7 @@ const UserSkillCard = memo<UserSkillCardProps>(<Flexbox flex={1} gap={12} paddingInline={16}><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 3,}}@@ -177,7 +162,7 @@ const UserSkillCard = memo<UserSkillCardProps>(<Flexboxhorizontalalign={'center'}- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}justify={'space-between'}><Tag@@ -191,7 +176,12 @@ const UserSkillCard = memo<UserSkillCardProps>(>{(resourcesCount || 0) + 1}</Tag>- <Flexbox horizontal align={'center'} className={styles.secondaryDesc} gap={8}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.secondaryDesc).className}+ gap={8}+ >{category && t(`skills.categories.${category}.name` as any)}</Flexbox></Flexbox>@@ -199,13 +189,20 @@ const UserSkillCard = memo<UserSkillCardProps>(<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}justify={'space-between'}padding={16}><Flexbox horizontal align={'center'} gap={4}>- <Icon className={styles.secondaryDesc} icon={ClockIcon} size={14} />- <PublishedTime className={styles.secondaryDesc} date={updatedAt} />+ <Icon+ className={stylex.props(styles.secondaryDesc).className}+ icon={ClockIcon}+ size={14}+ />+ <PublishedTime+ className={stylex.props(styles.secondaryDesc).className}+ date={updatedAt}+ /></Flexbox></Flexbox></Block>diff --git a/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx b/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsxindex b2ce527211c..4a220027abf 100644--- a/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx+++ b/src/routes/(main)/community/(detail)/workspace/features/Header/Banner.tsx@@ -1,61 +1,47 @@'use client';-import { Center, createStaticStyles, responsive } from '@lobehub/ui';+import { Center } 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 { memo } from 'react';-const styles = createStaticStyles(({ css, cssVar }) => ({- banner: css`- position: absolute;- inset-block-start: 0;- inset-inline-start: 0;+import { sx } from '@/styles/sx';- width: 100%;- height: 160px;- padding: 16px;+const WIDE = '@media (width <= 1720px)';- ${responsive.sm} {- position: relative;-- width: calc(100% + 32px);- height: 120px;- margin-block: -16px 0;- margin-inline: -16px;- }-- @media (width <= 1720px) {- height: 144px;- padding: 0;- }- `,- bannerAvatar: css`- filter: blur(100px);- `,- bannerInner: css`- position: relative;-- overflow: hidden;-- width: 100%;- height: 100%;- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorFillTertiary};-- @media (width <= 1720px) {- border-radius: 0;- }- `,- placeholder: css`- position: relative;- width: 100%;- height: 64px;- min-height: 64px;-- ${responsive.sm} {- display: none;- }- `,-}));+// Note: at the `sm` breakpoint the wide-screen rules also match, and they used to win+// for height / padding / border-radius, so only the effective values are kept.+const styles = stylex.create({+ banner: {+ position: { default: 'absolute', [media.sm]: 'relative' },+ insetBlockStart: '0',+ insetInlineStart: '0',+ width: { default: '100%', [media.sm]: 'calc(100% + 32px)' },+ height: { default: '160px', [WIDE]: '144px' },+ padding: { default: '16px', [WIDE]: '0' },+ marginBlockStart: { default: null, [media.sm]: '-16px' },+ marginBlockEnd: { default: null, [media.sm]: '0' },+ marginInline: { default: null, [media.sm]: '-16px' },+ },+ bannerAvatar: { filter: 'blur(100px)' },+ bannerInner: {+ position: 'relative',+ overflow: 'hidden',+ width: '100%',+ height: '100%',+ borderRadius: { default: cssVar.borderRadiusLG, [WIDE]: '0' },+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },+ placeholder: {+ position: 'relative',+ width: '100%',+ height: '64px',+ minHeight: '64px',+ display: { default: null, [media.sm]: 'none' },+ },+});interface BannerProps {avatar?: string | null;@@ -68,23 +54,22 @@ const Banner = memo<BannerProps>(({ avatar, bannerUrl }) => {return (<>- <div className={styles.banner}>- <Center className={styles.bannerInner}>+ <div {...stylex.props(styles.banner)}>+ <Center className={stylex.props(styles.bannerInner).className}>{backgroundImage && (<div- className={shouldBlur ? styles.bannerAvatar : undefined}- style={{+ {...sx(shouldBlur && styles.bannerAvatar, undefined, {backgroundImage: `url(${backgroundImage})`,backgroundPosition: 'center',backgroundSize: 'cover',height: '100%',width: '100%',- }}+ })}/>)}</Center></div>- <div className={styles.placeholder} />+ <div {...stylex.props(styles.placeholder)} /></>);});diff --git a/src/routes/(main)/community/(list)/(home)/features/CreatorRewardBanner.tsx b/src/routes/(main)/community/(list)/(home)/features/CreatorRewardBanner.tsxindex f9660c85d6c..8dbb394beb6 100644--- a/src/routes/(main)/community/(list)/(home)/features/CreatorRewardBanner.tsx+++ b/src/routes/(main)/community/(list)/(home)/features/CreatorRewardBanner.tsx@@ -1,83 +1,62 @@'use client';-import { Button, createStaticStyles, cx, Flexbox, responsive } from '@lobehub/ui';+import { Button, Flexbox } from '@lobehub/ui';+import { media } from '@lobehub/ui/stylex/media.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { imageUrl, OFFICIAL_SITE } from '@/const/url';import { useIsDark } from '@/hooks/useIsDark';+import { sx } from '@/styles/sx';-const styles = createStaticStyles(({ css }) => ({- banner: css`- position: relative;-- width: 100%;- padding-block: 24px;- padding-inline: 32px;- border-radius: 12px;-- ${responsive.sm} {- padding-block: 16px;- padding-inline: 20px;- }- `,- banner_dark: css`- background: linear-gradient(135deg, #5c3d0e 0%, #7a4f10 50%, #6b3a08 100%);- `,- banner_light: css`- background: linear-gradient(135deg, #fceabb 0%, #f8b500 50%, #e88a20 100%);- `,- subtitle: css`- margin: 0;- font-size: 14px;- font-weight: 400;- line-height: 1.5;-- ${responsive.sm} {- font-size: 12px;- }- `,- subtitle_dark: css`- color: rgb(255 255 255 / 65%);- `,- subtitle_light: css`- color: rgb(0 0 0 / 65%);- `,- symbols: css`- pointer-events: none;-- position: absolute;- inset-block: 0;- inset-inline-end: 0;-- overflow: hidden;-- width: 50%;- border-radius: 0 12px 12px 0;-- background: url(${imageUrl('banner_creator.png')}) right center / auto 100% no-repeat;-- ${responsive.sm} {- display: none;- }- `,- title: css`- margin: 0;- font-size: 22px;- font-weight: 700;- line-height: 1.3;-- ${responsive.sm} {- font-size: 18px;- }- `,- title_dark: css`- color: rgb(255 255 255 / 88%);- `,- title_light: css`- color: rgb(0 0 0 / 88%);- `,-}));+const styles = stylex.create({+ banner: {+ position: 'relative',+ width: '100%',+ paddingBlock: { default: '24px', [media.sm]: '16px' },+ paddingInline: { default: '32px', [media.sm]: '20px' },+ borderRadius: '12px',+ },+ bannerDark: {+ backgroundImage: 'linear-gradient(135deg, #5c3d0e 0%, #7a4f10 50%, #6b3a08 100%)',+ },+ bannerLight: {+ backgroundImage: 'linear-gradient(135deg, #fceabb 0%, #f8b500 50%, #e88a20 100%)',+ },+ subtitle: {+ margin: '0',+ fontSize: { default: '14px', [media.sm]: '12px' },+ fontWeight: 400,+ lineHeight: 1.5,+ },+ subtitleDark: { color: 'rgb(255 255 255 / 65%)' },+ subtitleLight: { color: 'rgb(0 0 0 / 65%)' },+ symbols: {+ pointerEvents: 'none',+ position: 'absolute',+ insetBlock: '0',+ insetInlineEnd: '0',+ overflow: 'hidden',+ width: '50%',+ borderTopLeftRadius: '0',+ borderTopRightRadius: '12px',+ borderBottomRightRadius: '12px',+ borderBottomLeftRadius: '0',+ backgroundPosition: 'right center',+ backgroundSize: 'auto 100%',+ backgroundRepeat: 'no-repeat',+ display: { default: null, [media.sm]: 'none' },+ },+ title: {+ margin: '0',+ fontSize: { default: '22px', [media.sm]: '18px' },+ fontWeight: 700,+ lineHeight: 1.3,+ },+ titleDark: { color: 'rgb(255 255 255 / 88%)' },+ titleLight: { color: 'rgb(0 0 0 / 88%)' },+});const CreatorRewardBanner = memo(() => {const { t } = useTranslation('discover');@@ -85,14 +64,16 @@ const CreatorRewardBanner = memo(() => {return (<Flexbox- className={cx(styles.banner, isDark ? styles.banner_dark : styles.banner_light)}width={'100%'}+ className={+ stylex.props(styles.banner, isDark ? styles.bannerDark : styles.bannerLight).className+ }><Flexbox gap={8} style={{ position: 'relative', zIndex: 1 }}>- <h2 className={cx(styles.title, isDark ? styles.title_dark : styles.title_light)}>+ <h2 {...stylex.props(styles.title, isDark ? styles.titleDark : styles.titleLight)}>{t('home.creatorReward.title')}</h2>- <p className={cx(styles.subtitle, isDark ? styles.subtitle_dark : styles.subtitle_light)}>+ <p {...stylex.props(styles.subtitle, isDark ? styles.subtitleDark : styles.subtitleLight)}>{t('home.creatorReward.subtitle')}</p><div style={{ marginBlockStart: 4 }}>@@ -105,7 +86,12 @@ const CreatorRewardBanner = memo(() => {</a></div></Flexbox>- <div className={styles.symbols} />+ <div+ {...sx(styles.symbols, undefined, {+ // Runtime CDN URL, so it cannot live in stylex.create.+ backgroundImage: `url(${imageUrl('banner_creator.png')})`,+ })}+ /></Flexbox>);});diff --git a/src/routes/(main)/community/(list)/_layout/Footer.tsx b/src/routes/(main)/community/(list)/_layout/Footer.tsxindex 6e17110001a..1c7445d3082 100644--- a/src/routes/(main)/community/(list)/_layout/Footer.tsx+++ b/src/routes/(main)/community/(list)/_layout/Footer.tsx@@ -1,4 +1,5 @@-import { Button, createStaticStyles, cx, Flexbox, Text } from '@lobehub/ui';+import { Button, Flexbox, Text } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -6,25 +7,17 @@ import { imageUrl } from '@/const/url';import DefaultFooter from '@/features/Setting/Footer';import { useIsDark } from '@/hooks/useIsDark';import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';+import { sx } from '@/styles/sx';-const styles = createStaticStyles(({ css }) => ({- footer: css`- min-height: 320px;- padding-block-start: 32px;-- background-repeat: no-repeat;- background-position: center bottom;- background-size: 512px auto;- `,- footer_dark: css`- background-image: url(${imageUrl('community_footer_dark.webp')});- background-blend-mode: screen;- `,- footer_light: css`- background-image: url(${imageUrl('community_footer_light.webp')});- background-blend-mode: multiply;- `,-}));+const styles = stylex.create({+ footer: {+ minHeight: '320px',+ paddingBlockStart: '32px',+ backgroundRepeat: 'no-repeat',+ backgroundPosition: 'center bottom',+ backgroundSize: '512px auto',+ },+});const Footer = memo(() => {const { t } = useTranslation('discover');@@ -46,9 +39,13 @@ const Footer = memo(() => {return (<Flexboxalign={'center'}- className={cx(styles.footer, isDarkMode ? styles.footer_dark : styles.footer_light)}flex={'none'}gap={4}+ {...sx(styles.footer, undefined, {+ // The image URL is resolved at runtime (CDN base), so it cannot live in stylex.create.+ backgroundBlendMode: isDarkMode ? 'screen' : 'multiply',+ backgroundImage: `url(${imageUrl(isDarkMode ? 'community_footer_dark.webp' : 'community_footer_light.webp')})`,+ })}><Text strong align={'center'} as={'h2'} fontSize={22}>{t('footer.title')}diff --git a/src/routes/(main)/community/(list)/_layout/Header.tsx b/src/routes/(main)/community/(list)/_layout/Header.tsxindex 22ef5138b5b..561d3b81625 100644--- a/src/routes/(main)/community/(list)/_layout/Header.tsx+++ b/src/routes/(main)/community/(list)/_layout/Header.tsx@@ -1,6 +1,7 @@'use client';import { cssVar } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useLocation } from 'react-router';@@ -21,7 +22,7 @@ const Header = memo(() => {return (<NavHeader- className={styles.headerContainer}+ className={stylex.props(styles.headerContainer).className}left={<StoreSearchBar />}style={cssVariables}right={diff --git a/src/routes/(main)/community/(list)/_layout/Header/style.ts b/src/routes/(main)/community/(list)/_layout/Header/style.tsindex 49c10d5bf3a..0fb96075091 100644--- a/src/routes/(main)/community/(list)/_layout/Header/style.ts+++ b/src/routes/(main)/community/(list)/_layout/Header/style.ts@@ -1,8 +1,11 @@-import { createStaticStyles } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css, cssVar }) => ({+export const styles = stylex.create({// Header container- headerContainer: css`- border-block-end: 1px solid var(--header-border-color, ${cssVar.colorBorderSecondary});- `,-}));+ headerContainer: {+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: `var(--header-border-color, ${cssVar.colorBorderSecondary})`,+ },+});diff --git a/src/routes/(main)/community/(list)/_layout/index.tsx b/src/routes/(main)/community/(list)/_layout/index.tsxindex cf00505710e..3aaeb4b2c2b 100644--- a/src/routes/(main)/community/(list)/_layout/index.tsx+++ b/src/routes/(main)/community/(list)/_layout/index.tsx@@ -1,4 +1,5 @@import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { Outlet } from 'react-router';import WideScreenContainer from '@/features/WideScreenContainer';@@ -13,9 +14,13 @@ const Layout = () => {return (<><Header />- <Flexbox className={styles.mainContainer} height={'100%'} width={'100%'}>+ <Flexbox+ className={stylex.props(styles.mainContainer).className}+ height={'100%'}+ width={'100%'}+ ><WideScreenContainer- className={styles.contentContainer}+ className={stylex.props(styles.contentContainer).className}gap={16}minWidth={MAX_WIDTH}style={{ paddingBottom: 56, paddingTop: 16 }}@@ -29,7 +34,7 @@ const Layout = () => {<Outlet /></RouteSkeletonChromeProvider></Flexbox>- <div className={styles.spacer} />+ <div {...stylex.props(styles.spacer)} /><Footer /></WideScreenContainer></Flexbox>diff --git a/src/routes/(main)/community/(list)/_layout/style.ts b/src/routes/(main)/community/(list)/_layout/style.tsindex 0e52f08d58d..4eac7deb270 100644--- a/src/routes/(main)/community/(list)/_layout/style.ts+++ b/src/routes/(main)/community/(list)/_layout/style.ts@@ -1,20 +1,12 @@-import { createStaticStyles } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css }) => ({-+export const styles = stylex.create({// Content container-contentContainer: css`- min-height: 100%;- `,+ contentContainer: { minHeight: '100%' },-// Main container-mainContainer: css`- overflow-y: auto;- `,+ mainContainer: { overflowY: 'auto' },// Placeholder- spacer: css`- flex: 1;- `,-}));+ spacer: { flex: '1' },+});diff --git a/src/routes/(main)/community/(list)/agent/_layout/index.tsx b/src/routes/(main)/community/(list)/agent/_layout/index.tsxindex 0c4f2f41ece..ef40d5c69a5 100644--- a/src/routes/(main)/community/(list)/agent/_layout/index.tsx+++ b/src/routes/(main)/community/(list)/agent/_layout/index.tsx@@ -1,4 +1,5 @@import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { Outlet } from 'react-router';import CategoryContainer from '../../../components/CategoryContainer';@@ -7,7 +8,12 @@ import { styles } from './style';const Layout = () => {return (- <Flexbox horizontal className={styles.mainContainer} gap={24} width={'100%'}>+ <Flexbox+ horizontal+ className={stylex.props(styles.mainContainer).className}+ gap={24}+ width={'100%'}+ ><CategoryContainer><Category /></CategoryContainer>diff --git a/src/routes/(main)/community/(list)/agent/_layout/style.ts b/src/routes/(main)/community/(list)/agent/_layout/style.tsindex dd210644e40..733bb4280ea 100644--- a/src/routes/(main)/community/(list)/agent/_layout/style.ts+++ b/src/routes/(main)/community/(list)/agent/_layout/style.ts@@ -1,8 +1,6 @@-import { createStaticStyles } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css }) => ({+export const styles = stylex.create({// Main container- mainContainer: css`- position: relative;- `,-}));+ mainContainer: { position: 'relative' },+});diff --git a/src/routes/(main)/community/(list)/agent/features/List/Item.tsx b/src/routes/(main)/community/(list)/agent/features/List/Item.tsxindex daf38d94189..f56ada426a7 100644--- a/src/routes/(main)/community/(list)/agent/features/List/Item.tsx+++ b/src/routes/(main)/community/(list)/agent/features/List/Item.tsx@@ -1,4 +1,6 @@-import { Avatar, Block, createStaticStyles, Flexbox, Icon, Tag, Text } from '@lobehub/ui';+import { Avatar, Block, Flexbox, Icon, Tag, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ClockIcon } from 'lucide-react';import qs from 'query-string';import React, { memo, useCallback } from 'react';@@ -11,47 +13,32 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { useQuery } from '@/hooks/useQuery';import { resolveCommunityProfileLink } from '@/routes/(main)/community/(detail)/utils/profileLink';import { discoverService } from '@/services/discover';+import { sx } from '@/styles/sx';import { type AssistantMarketSource, type DiscoverAssistantItem } from '@/types/discover';import TokenTag from './TokenTag';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- author: css`- cursor: pointer;- color: ${cssVar.colorTextDescription};-- &:hover {- color: ${cssVar.colorPrimary};- }- `,- code: css`- font-family: ${cssVar.fontFamilyCode};- `,- desc: css`- flex: 1;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- footer: css`- margin-block-start: 16px;- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- secondaryDesc: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- title: css`- margin: 0 !important;- font-size: 16px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ author: {+ cursor: 'pointer',+ color: { 'default': cssVar.colorTextDescription, ':hover': cssVar.colorPrimary },+ },+ desc: { flex: '1', margin: '0', color: cssVar.colorTextSecondary },+ footer: {+ marginBlockStart: '16px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ secondaryDesc: { fontSize: '12px', color: cssVar.colorTextDescription },+ title: {+ margin: '0',+ fontSize: '16px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const AssistantItem = memo<DiscoverAssistantItem>(@@ -182,15 +169,18 @@ const AssistantItem = memo<DiscoverAssistantItem>(}}><WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{title}</Text></WorkspaceLink></Flexbox>{author && (<div- className={userName ? styles.author : undefined}- style={userName ? undefined : { color: 'inherit' }}+ {...sx(+ !!userName && styles.author,+ undefined,+ userName ? undefined : { color: 'inherit' },+ )}onClick={userName ? handleAuthorClick : undefined}>{author}@@ -202,7 +192,7 @@ const AssistantItem = memo<DiscoverAssistantItem>(<Flexbox flex={1} gap={12} paddingInline={16}><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 3,}}@@ -219,20 +209,20 @@ const AssistantItem = memo<DiscoverAssistantItem>(<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}justify={'space-between'}padding={16}><Flexboxhorizontalalign={'center'}- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}justify={'space-between'}><Flexbox horizontal align={'center'} gap={4}><Icon icon={ClockIcon} size={14} /><PublishedTime- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}date={updatedAt || createdAt}template={'MMM DD, YYYY'}/>diff --git a/src/routes/(main)/community/(list)/agent/features/List/TokenTag.tsx b/src/routes/(main)/community/(list)/agent/features/List/TokenTag.tsxindex 0683c6e28f4..b545742660f 100644--- a/src/routes/(main)/community/(list)/agent/features/List/TokenTag.tsx+++ b/src/routes/(main)/community/(list)/agent/features/List/TokenTag.tsx@@ -1,23 +1,22 @@import { MCP } from '@lobehub/icons';-import { createStaticStyles, cssVar, Flexbox, Icon, Tag, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Tag, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { BookTextIcon, CoinsIcon, GitForkIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { formatIntergerNumber } from '@/utils/format';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- token: css`- border-radius: 4px;-- font-family: ${cssVar.fontFamilyCode};- font-size: 11px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};- `,- };+const styles = stylex.create({+ token: {+ borderRadius: '4px',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: '11px',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillTertiary,+ backgroundImage: 'none',+ },});interface TokenTagProps {@@ -38,7 +37,7 @@ const TokenTag = memo<TokenTagProps>(styles={{ root: { pointerEvents: 'none' } }}title={t('assistants.tokenUsage')}>- <Tag className={styles.token} icon={<Icon icon={CoinsIcon} />}>+ <Tag className={stylex.props(styles.token).className} icon={<Icon icon={CoinsIcon} />}>{formatIntergerNumber(tokenUsage)}</Tag></Tooltip>@@ -48,7 +47,10 @@ const TokenTag = memo<TokenTagProps>(styles={{ root: { pointerEvents: 'none' } }}title={t('fork.forksCount', { count: forkCount })}>- <Tag className={styles.token} icon={<Icon icon={GitForkIcon} />}>+ <Tag+ className={stylex.props(styles.token).className}+ icon={<Icon icon={GitForkIcon} />}+ >{formatIntergerNumber(forkCount)}</Tag></Tooltip>diff --git a/src/routes/(main)/community/(list)/mcp/_layout/index.tsx b/src/routes/(main)/community/(list)/mcp/_layout/index.tsxindex 0c4f2f41ece..ef40d5c69a5 100644--- a/src/routes/(main)/community/(list)/mcp/_layout/index.tsx+++ b/src/routes/(main)/community/(list)/mcp/_layout/index.tsx@@ -1,4 +1,5 @@import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { Outlet } from 'react-router';import CategoryContainer from '../../../components/CategoryContainer';@@ -7,7 +8,12 @@ import { styles } from './style';const Layout = () => {return (- <Flexbox horizontal className={styles.mainContainer} gap={24} width={'100%'}>+ <Flexbox+ horizontal+ className={stylex.props(styles.mainContainer).className}+ gap={24}+ width={'100%'}+ ><CategoryContainer><Category /></CategoryContainer>diff --git a/src/routes/(main)/community/(list)/mcp/_layout/style.ts b/src/routes/(main)/community/(list)/mcp/_layout/style.tsindex dd210644e40..733bb4280ea 100644--- a/src/routes/(main)/community/(list)/mcp/_layout/style.ts+++ b/src/routes/(main)/community/(list)/mcp/_layout/style.ts@@ -1,8 +1,6 @@-import { createStaticStyles } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css }) => ({+export const styles = stylex.create({// Main container- mainContainer: css`- position: relative;- `,-}));+ mainContainer: { position: 'relative' },+});diff --git a/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx b/src/routes/(main)/community/(list)/mcp/features/List/Item.tsxindex e336f686044..dc88121cb4a 100644--- a/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx+++ b/src/routes/(main)/community/(list)/mcp/features/List/Item.tsx@@ -5,8 +5,6 @@ import {ActionIcon,Avatar,Block,- createStaticStyles,- cssVar,Flexbox,Icon,stopPropagation,@@ -15,6 +13,8 @@ import {Tooltip,} from '@lobehub/ui';import { Spotlight } from '@lobehub/ui/awesome';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ClockIcon } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -32,38 +32,24 @@ import { type DiscoverMcpItem } from '@/types/discover';import ConnectionTypeTag from './ConnectionTypeTag';import MetaInfo from './MetaInfo';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- author: css`- color: ${cssVar.colorTextDescription};- `,- code: css`- font-family: ${cssVar.fontFamilyCode};- `,- desc: css`- flex: 1;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- footer: css`- margin-block-start: 16px;- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- secondaryDesc: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- title: css`- margin: 0 !important;- font-size: 16px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ author: { color: cssVar.colorTextDescription },+ desc: { flex: '1', margin: '0', color: cssVar.colorTextSecondary },+ footer: {+ marginBlockStart: '16px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ secondaryDesc: { fontSize: '12px', color: cssVar.colorTextDescription },+ title: {+ margin: '0',+ fontSize: '16px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const McpItem = memo<DiscoverMcpItem>(@@ -151,7 +137,7 @@ const McpItem = memo<DiscoverMcpItem>(}}><WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{name}</Text></WorkspaceLink>@@ -161,7 +147,7 @@ const McpItem = memo<DiscoverMcpItem>(</Tooltip>)}</Flexbox>- {author && <div className={styles.author}>{author}</div>}+ {author && <div className={stylex.props(styles.author).className}>{author}</div>}</Flexbox></Flexbox><Flexbox horizontal align={'center'} gap={4}>@@ -192,7 +178,7 @@ const McpItem = memo<DiscoverMcpItem>(/><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 3,}}@@ -202,12 +188,15 @@ const McpItem = memo<DiscoverMcpItem>(<Flexboxhorizontalalign={'center'}- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}justify={'space-between'}><Flexbox horizontal align={'center'} gap={4}><Icon icon={ClockIcon} size={14} />- <PublishedTime className={styles.secondaryDesc} date={updatedAt} />+ <PublishedTime+ className={stylex.props(styles.secondaryDesc).className}+ date={updatedAt}+ /></Flexbox><Flexbox horizontal align={'center'} gap={8}>{t(`mcp.categories.${category}.name` as any)}@@ -229,13 +218,13 @@ const McpItem = memo<DiscoverMcpItem>(<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}justify={'space-between'}padding={16}><ConnectionTypeTag type={connectionType} /><MetaInfo- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}installCount={installCount}stars={github?.stars}/>diff --git a/src/routes/(main)/community/(list)/model/_layout/index.tsx b/src/routes/(main)/community/(list)/model/_layout/index.tsxindex 0c4f2f41ece..ef40d5c69a5 100644--- a/src/routes/(main)/community/(list)/model/_layout/index.tsx+++ b/src/routes/(main)/community/(list)/model/_layout/index.tsx@@ -1,4 +1,5 @@import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { Outlet } from 'react-router';import CategoryContainer from '../../../components/CategoryContainer';@@ -7,7 +8,12 @@ import { styles } from './style';const Layout = () => {return (- <Flexbox horizontal className={styles.mainContainer} gap={24} width={'100%'}>+ <Flexbox+ horizontal+ className={stylex.props(styles.mainContainer).className}+ gap={24}+ width={'100%'}+ ><CategoryContainer><Category /></CategoryContainer>diff --git a/src/routes/(main)/community/(list)/model/_layout/style.ts b/src/routes/(main)/community/(list)/model/_layout/style.tsindex dd210644e40..733bb4280ea 100644--- a/src/routes/(main)/community/(list)/model/_layout/style.ts+++ b/src/routes/(main)/community/(list)/model/_layout/style.ts@@ -1,8 +1,6 @@-import { createStaticStyles } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css }) => ({+export const styles = stylex.create({// Main container- mainContainer: css`- position: relative;- `,-}));+ mainContainer: { position: 'relative' },+});diff --git a/src/routes/(main)/community/(list)/model/features/List/Item.tsx b/src/routes/(main)/community/(list)/model/features/List/Item.tsxindex 6cc9ddd669e..74dfc9c9d32 100644--- a/src/routes/(main)/community/(list)/model/features/List/Item.tsx+++ b/src/routes/(main)/community/(list)/model/features/List/Item.tsx@@ -1,6 +1,8 @@'use client';-import { Block, createStaticStyles, Flexbox, Icon, Popover, Tag, Text } from '@lobehub/ui';+import { Block, Flexbox, Icon, Popover, Tag, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import dayjs from 'dayjs';import { ClockIcon } from 'lucide-react';import { memo } from 'react';@@ -16,38 +18,24 @@ import { type DiscoverModelItem } from '@/types/discover';import ModelTypeIcon from './ModelTypeIcon';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- author: css`- color: ${cssVar.colorTextDescription};- `,- code: css`- font-family: ${cssVar.fontFamilyCode};- `,- desc: css`- flex: 1;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- footer: css`- margin-block-start: 16px;- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- secondaryDesc: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- title: css`- margin: 0 !important;- font-size: 16px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ author: { color: cssVar.colorTextDescription },+ desc: { flex: '1', margin: '0', color: cssVar.colorTextSecondary },+ footer: {+ marginBlockStart: '16px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ secondaryDesc: { fontSize: '12px', color: cssVar.colorTextDescription },+ title: {+ margin: '0',+ fontSize: '16px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const ModelItem = memo<DiscoverModelItem>(@@ -113,12 +101,12 @@ const ModelItem = memo<DiscoverModelItem>(}}><WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{displayName}</Text></WorkspaceLink></Flexbox>- <div className={styles.author}>{identifier}</div>+ <div className={stylex.props(styles.author).className}>{identifier}</div></Flexbox></Flexbox><Flexbox horizontal align={'center'} gap={4}>@@ -133,7 +121,7 @@ const ModelItem = memo<DiscoverModelItem>(/><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 3,}}@@ -144,20 +132,20 @@ const ModelItem = memo<DiscoverModelItem>(<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}justify={'space-between'}padding={16}><Flexboxhorizontalalign={'center'}- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}justify={'space-between'}><Flexbox horizontal align={'center'} gap={4}><Icon icon={ClockIcon} size={14} /><PublishedTime- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}date={releasedAt || dayjs().toISOString()}/></Flexbox>diff --git a/src/routes/(main)/community/(list)/provider/features/List/Item.tsx b/src/routes/(main)/community/(list)/provider/features/List/Item.tsxindex d5f82ff58e1..ed4497d3565 100644--- a/src/routes/(main)/community/(list)/provider/features/List/Item.tsx+++ b/src/routes/(main)/community/(list)/provider/features/List/Item.tsx@@ -1,14 +1,7 @@import { Github } from '@lobehub/icons';-import {- ActionIcon,- Block,- createStaticStyles,- cssVar,- Flexbox,- MaskShadow,- stopPropagation,- Text,-} from '@lobehub/ui';+import { ActionIcon, Block, Flexbox, MaskShadow, stopPropagation, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { GlobeIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -20,38 +13,17 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { type DiscoverProviderItem } from '@/types/discover';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- author: css`- color: ${cssVar.colorTextDescription};- `,- code: css`- font-family: ${cssVar.fontFamilyCode};- `,- desc: css`- flex: none;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- footer: css`- margin-block-start: 16px;- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- secondaryDesc: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- title: css`- margin: 0 !important;- font-size: 16px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ author: { color: cssVar.colorTextDescription },+ desc: { flex: 'none', margin: '0', color: cssVar.colorTextSecondary },+ footer: {+ marginBlockStart: '16px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },});const ProviderItem = memo<DiscoverProviderItem>(@@ -92,7 +64,7 @@ const ProviderItem = memo<DiscoverProviderItem>(<WorkspaceLink style={{ color: 'inherit', overflow: 'hidden' }} to={link}><ProviderCombine provider={identifier} size={28} style={{ flex: 'none' }} /></WorkspaceLink>- <div className={styles.author}>@{name}</div>+ <div className={stylex.props(styles.author).className}>@{name}</div></Flexbox><Flexbox horizontal align={'center'}><a href={url} rel="noopener noreferrer" target={'_blank'} onClick={stopPropagation}>@@ -111,7 +83,7 @@ const ProviderItem = memo<DiscoverProviderItem>(<Flexbox flex={1} gap={12} paddingInline={16}>{description && (<Text- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 3,}}@@ -123,7 +95,7 @@ const ProviderItem = memo<DiscoverProviderItem>(<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}justify={'space-between'}padding={16}>diff --git a/src/routes/(main)/community/(list)/skill/_layout/index.tsx b/src/routes/(main)/community/(list)/skill/_layout/index.tsxindex 0c4f2f41ece..ef40d5c69a5 100644--- a/src/routes/(main)/community/(list)/skill/_layout/index.tsx+++ b/src/routes/(main)/community/(list)/skill/_layout/index.tsx@@ -1,4 +1,5 @@import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { Outlet } from 'react-router';import CategoryContainer from '../../../components/CategoryContainer';@@ -7,7 +8,12 @@ import { styles } from './style';const Layout = () => {return (- <Flexbox horizontal className={styles.mainContainer} gap={24} width={'100%'}>+ <Flexbox+ horizontal+ className={stylex.props(styles.mainContainer).className}+ gap={24}+ width={'100%'}+ ><CategoryContainer><Category /></CategoryContainer>diff --git a/src/routes/(main)/community/(list)/skill/_layout/style.ts b/src/routes/(main)/community/(list)/skill/_layout/style.tsindex 7f150ec3518..733bb4280ea 100644--- a/src/routes/(main)/community/(list)/skill/_layout/style.ts+++ b/src/routes/(main)/community/(list)/skill/_layout/style.ts@@ -1,7 +1,6 @@-import { createStaticStyles } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css }) => ({- mainContainer: css`- position: relative;- `,-}));+export const styles = stylex.create({+ // Main container+ mainContainer: { position: 'relative' },+});diff --git a/src/routes/(main)/community/(list)/skill/features/List/Item.tsx b/src/routes/(main)/community/(list)/skill/features/List/Item.tsxindex da11c9718d0..790b20bdd66 100644--- a/src/routes/(main)/community/(list)/skill/features/List/Item.tsx+++ b/src/routes/(main)/community/(list)/skill/features/List/Item.tsx@@ -1,19 +1,10 @@'use client';import { Github } from '@lobehub/icons';-import {- ActionIcon,- Avatar,- Block,- createStaticStyles,- cssVar,- Flexbox,- Icon,- stopPropagation,- Tag,- Text,-} from '@lobehub/ui';+import { ActionIcon, Avatar, Block, Flexbox, Icon, stopPropagation, Tag, Text } from '@lobehub/ui';import { Spotlight } from '@lobehub/ui/awesome';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ClockIcon, FileTextIcon, StarIcon } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -27,35 +18,24 @@ import { type DiscoverSkillItem } from '@/types/discover';import MetaInfo from './MetaInfo';-const styles = createStaticStyles(({ css, cssVar }) => {- return {- author: css`- color: ${cssVar.colorTextDescription};- `,- desc: css`- flex: 1;- margin: 0 !important;- color: ${cssVar.colorTextSecondary};- `,- footer: css`- margin-block-start: 16px;- border-block-start: 1px dashed ${cssVar.colorBorder};- background: ${cssVar.colorBgContainer};- `,- secondaryDesc: css`- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- title: css`- margin: 0 !important;- font-size: 16px !important;- font-weight: 500 !important;-- &:hover {- color: ${cssVar.colorLink};- }- `,- };+const styles = stylex.create({+ author: { color: cssVar.colorTextDescription },+ desc: { flex: '1', margin: '0', color: cssVar.colorTextSecondary },+ footer: {+ marginBlockStart: '16px',+ borderBlockStartWidth: '1px',+ borderBlockStartStyle: 'dashed',+ borderBlockStartColor: cssVar.colorBorder,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ secondaryDesc: { fontSize: '12px', color: cssVar.colorTextDescription },+ title: {+ margin: '0',+ fontSize: '16px',+ fontWeight: 500,+ color: { 'default': null, ':hover': cssVar.colorLink },+ },});const SkillItem = memo<DiscoverSkillItem>(@@ -149,12 +129,17 @@ const SkillItem = memo<DiscoverSkillItem>(handleClick();}}>- <Text ellipsis as={'h2'} className={styles.title}>+ <Text ellipsis as={'h2'} className={stylex.props(styles.title).className}>{name}</Text></WorkspaceLink></Flexbox>- <Flexbox horizontal align={'center'} className={styles.author} gap={8}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.author).className}+ gap={8}+ >{Boolean(ratingAvg) && (<Flexbox horizontal align={'center'} gap={4} style={{ fontSize: 13 }}><Icon fill={cssVar.colorTextDescription} icon={StarIcon} size={12} />@@ -181,7 +166,7 @@ const SkillItem = memo<DiscoverSkillItem>(<Flexbox flex={1} gap={12} paddingInline={16}><Textas={'p'}- className={styles.desc}+ className={stylex.props(styles.desc).className}ellipsis={{rows: 3,}}@@ -191,7 +176,7 @@ const SkillItem = memo<DiscoverSkillItem>(<Flexboxhorizontalalign={'center'}- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}justify={'space-between'}><Tag@@ -205,7 +190,12 @@ const SkillItem = memo<DiscoverSkillItem>(>{(resourcesCount || 0) + 1}</Tag>- <Flexbox horizontal align={'center'} className={styles.secondaryDesc} gap={8}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.secondaryDesc).className}+ gap={8}+ >{category && t(`skills.categories.${category}.name` as any)}{isFeatured && (<Tag@@ -225,16 +215,23 @@ const SkillItem = memo<DiscoverSkillItem>(<Flexboxhorizontalalign={'center'}- className={styles.footer}+ className={stylex.props(styles.footer).className}justify={'space-between'}padding={16}><Flexbox horizontal align={'center'} gap={4}>- <Icon className={styles.secondaryDesc} icon={ClockIcon} size={14} />- <PublishedTime className={styles.secondaryDesc} date={updatedAt} />+ <Icon+ className={stylex.props(styles.secondaryDesc).className}+ icon={ClockIcon}+ size={14}+ />+ <PublishedTime+ className={stylex.props(styles.secondaryDesc).className}+ date={updatedAt}+ /></Flexbox><MetaInfo- className={styles.secondaryDesc}+ className={stylex.props(styles.secondaryDesc).className}commentCount={commentCount}installCount={installCount}stars={github?.stars}diff --git a/src/routes/(main)/community/_layout/index.tsx b/src/routes/(main)/community/_layout/index.tsxindex c8e90025481..dfe44f83370 100644--- a/src/routes/(main)/community/_layout/index.tsx+++ b/src/routes/(main)/community/_layout/index.tsx@@ -1,4 +1,5 @@import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { type FC } from 'react';import { Outlet } from 'react-router';@@ -9,7 +10,7 @@ const Layout: FC = () => {return (<><Sidebar />- <Flexbox className={styles.mainContainer} flex={1} height={'100%'}>+ <Flexbox className={stylex.props(styles.mainContainer).className} flex={1} height={'100%'}><Outlet /></Flexbox></>diff --git a/src/routes/(main)/community/_layout/style.ts b/src/routes/(main)/community/_layout/style.tsindex ea3f8047a08..50069b46b0d 100644--- a/src/routes/(main)/community/_layout/style.ts+++ b/src/routes/(main)/community/_layout/style.ts@@ -1,10 +1,12 @@-import { createStaticStyles } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css, cssVar }) => ({+export const styles = stylex.create({// Main container- mainContainer: css`- position: relative;- overflow: hidden;- background: ${cssVar.colorBgContainer};- `,-}));+ mainContainer: {+ position: 'relative',+ overflow: 'hidden',+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+});diff --git a/src/routes/(main)/community/components/CardBanner.tsx b/src/routes/(main)/community/components/CardBanner.tsxindex 73e07fedd05..05a41e23e4b 100644--- a/src/routes/(main)/community/components/CardBanner.tsx+++ b/src/routes/(main)/community/components/CardBanner.tsx@@ -1,24 +1,24 @@import { type DivProps } from '@lobehub/ui';-import { Avatar, createStaticStyles, cssVar, cx, Flexbox } from '@lobehub/ui';+import { Avatar, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { type ReactNode } from 'react';import { memo } from 'react';-export const styles = createStaticStyles(({ css, cssVar }) => ({- banner: css`- position: relative;+import { sx } from '@/styles/sx';- overflow: hidden;-- height: 64px;- margin-block-end: -56px;-- background: ${cssVar.colorFillSecondary};- `,- bannerImg: css`- position: absolute;- filter: blur(40px) saturate(1.5);- `,-}));+const styles = stylex.create({+ banner: {+ position: 'relative',+ overflow: 'hidden',+ height: '64px',+ marginBlockEnd: '-56px',+ backgroundColor: cssVar.colorFillSecondary,+ backgroundImage: 'none',+ },+ bannerEmpty: { backgroundColor: cssVar.colorFillTertiary },+ bannerImg: { position: 'absolute', filter: 'blur(40px) saturate(1.5)' },+});interface CardBannerProps extends DivProps {avatar?: string | ReactNode;@@ -33,17 +33,16 @@ const CardBanner = memo<CardBannerProps>(return (<Flexboxalign={'center'}- className={cx(styles.banner, className)}justify={'center'}- style={avatar ? {} : { backgroundColor: cssVar.colorFillTertiary }}width={'100%'}+ {...sx([styles.banner, !avatar && styles.bannerEmpty], className)}{...props}>{avatar && (<Avataralt={'banner'}avatar={avatar}- className={styles.bannerImg}+ className={stylex.props(styles.bannerImg).className}shape={'square'}size={size}/>diff --git a/src/routes/(main)/community/components/CategoryMenu.tsx b/src/routes/(main)/community/components/CategoryMenu.tsxindex 4ff383e3927..75018465db7 100644--- a/src/routes/(main)/community/components/CategoryMenu.tsx+++ b/src/routes/(main)/community/components/CategoryMenu.tsx@@ -1,14 +1,10 @@'use client';import { List, type ListClickInfo, type ListItemType } from '@lobehub/ui';-import { createStaticStyles } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';import { type CSSProperties, memo } from 'react';-const styles = createStaticStyles(({ css }) => ({- item: css`- min-height: 36px;- `,-}));+const styles = stylex.create({ item: { minHeight: '36px' } });export interface CategoryMenuProps {className?: string;@@ -25,7 +21,7 @@ const CategoryMenu = memo<CategoryMenuProps>(<ListactiveKey={selectedKeys?.[0]}className={className}- classNames={{ item: styles.item }}+ classNames={{ item: stylex.props(styles.item).className }}data-testid="category-menu"items={items}style={style}diff --git a/src/routes/(main)/community/components/Statistic.tsx b/src/routes/(main)/community/components/Statistic.tsxindex 767710a2a69..542bf81ebe3 100644--- a/src/routes/(main)/community/components/Statistic.tsx+++ b/src/routes/(main)/community/components/Statistic.tsx@@ -1,31 +1,30 @@import { type FlexboxProps } from '@lobehub/ui';-import { createStaticStyles, cx, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { HelpCircleIcon } from 'lucide-react';import { type CSSProperties, type ReactNode } from 'react';import { memo } from 'react';-export const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- overflow: hidden;- min-width: 64px;- `,- number: css`- margin: 0 !important;+import { sx } from '@/styles/sx';- font-size: 16px;- font-weight: 500;- line-height: 1.4;- text-align: center;- `,- title: css`- margin: 0 !important;-- font-size: 12px;- line-height: 1.2;- color: ${cssVar.colorTextSecondary};- text-align: center;- `,-}));+const styles = stylex.create({+ container: { overflow: 'hidden', minWidth: '64px' },+ number: {+ margin: '0',+ fontSize: '16px',+ fontWeight: 500,+ lineHeight: 1.4,+ textAlign: 'center',+ },+ title: {+ margin: '0',+ fontSize: '12px',+ lineHeight: 1.2,+ color: cssVar.colorTextSecondary,+ textAlign: 'center',+ },+});export interface StatisticProps extends Omit<FlexboxProps, 'children' | 'title'> {title: ReactNode;@@ -49,12 +48,20 @@ const Statistic = memo<StatisticProps>(}) => {const isTop = valuePlacement === 'top';const valueContent = (- <Text className={styles.number} ellipsis={{ rows: 1 }} style={valueStyle}>+ <Text+ className={stylex.props(styles.number).className}+ ellipsis={{ rows: 1 }}+ style={valueStyle}+ >{value}</Text>);const titleContent = (- <Text className={styles.title} ellipsis={{ rows: 1 }} style={titleStyle}>+ <Text+ className={stylex.props(styles.title).className}+ ellipsis={{ rows: 1 }}+ style={titleStyle}+ >{title}{tooltip && <Icon icon={HelpCircleIcon} style={{ marginLeft: '0.4em' }} />}</Text>@@ -62,9 +69,9 @@ const Statistic = memo<StatisticProps>(const content = (<Flexboxalign={'center'}- className={cx(styles.container, className)}flex={1}justify={'center'}+ {...sx(styles.container, className)}{...rest}>{isTop ? (diff --git a/src/routes/(main)/community/components/Title.tsx b/src/routes/(main)/community/components/Title.tsxindex a4ef7f2ff84..2a12696df6b 100644--- a/src/routes/(main)/community/components/Title.tsx+++ b/src/routes/(main)/community/components/Title.tsx@@ -1,15 +1,10 @@'use client';import { type FlexboxProps } from '@lobehub/ui';-import {- Button,- createStaticStyles,- Flexbox,- Icon,- responsive,- Tag,- useResponsive,-} from '@lobehub/ui';+import { Button, Flexbox, Icon, Tag, useResponsive } 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 { ChevronRight } from 'lucide-react';import { type ReactNode } from 'react';import { memo } from 'react';@@ -20,37 +15,25 @@ import { SCROLL_PARENT_ID } from '../features/const';const SCROLL_CONTAINER_ID = 'lobe-mobile-scroll-container';-const styles = createStaticStyles(({ css, cssVar }) => ({- more: css`- display: flex;- align-items: center;- color: ${cssVar.colorTextSecondary};- `,- tag: css`- flex: none;-- padding-block: 0.1em;- padding-inline: 0.3em;- border-radius: ${cssVar.borderRadius};-- font-size: 18px;- font-weight: 500;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillSecondary};- ${responsive.sm} {- font-size: 14px;- }- `,- title: css`- margin-block-start: 0.5em;- font-size: 20px;- font-weight: 600;- ${responsive.sm} {- font-size: 18px;- }- `,-}));+const styles = stylex.create({+ more: { display: 'flex', alignItems: 'center', color: cssVar.colorTextSecondary },+ tag: {+ flex: 'none',+ paddingBlock: '0.1em',+ paddingInline: '0.3em',+ borderRadius: cssVar.borderRadius,+ fontSize: { default: '18px', [media.sm]: '14px' },+ fontWeight: 500,+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillSecondary,+ backgroundImage: 'none',+ },+ title: {+ marginBlockStart: '0.5em',+ fontSize: { default: '20px', [media.sm]: '18px' },+ fontWeight: 600,+ },+});interface TitleProps extends FlexboxProps {more?: ReactNode;@@ -60,7 +43,7 @@ interface TitleProps extends FlexboxProps {const Title = memo<TitleProps>(({ tag, children, moreLink, more }) => {const { mobile } = useResponsive();- const title = <h2 className={styles.title}>{children}</h2>;+ const title = <h2 {...stylex.props(styles.title)}>{children}</h2>;const handleMoreClick = () => {if (!moreLink) return;@@ -77,7 +60,7 @@ const Title = memo<TitleProps>(({ tag, children, moreLink, more }) => {{tag ? (<Flexbox horizontal align={'center'} gap={8}>{title}- <Tag className={styles.tag}>{tag}</Tag>+ <Tag className={stylex.props(styles.tag).className}>{tag}</Tag></Flexbox>) : (title@@ -88,7 +71,11 @@ const Title = memo<TitleProps>(({ tag, children, moreLink, more }) => {to={moreLink}onClick={handleMoreClick}>- <Button className={styles.more} style={{ paddingInline: 6 }} type={'text'}>+ <Button+ className={stylex.props(styles.more).className}+ style={{ paddingInline: 6 }}+ type={'text'}+ ><span>{more}</span><Icon icon={ChevronRight} /></Button>diff --git a/src/routes/(main)/community/features/Search.tsx b/src/routes/(main)/community/features/Search.tsxindex ef3994a1e8c..38f0fc76b1f 100644--- a/src/routes/(main)/community/features/Search.tsx+++ b/src/routes/(main)/community/features/Search.tsx@@ -1,7 +1,7 @@'use client';import { type SearchBarProps } from '@lobehub/ui';-import { createStaticStyles, SearchBar } from '@lobehub/ui';+import { SearchBar } from '@lobehub/ui';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';import urlJoin from 'url-join';@@ -10,19 +10,6 @@ import { withSuspense } from '@/components/withSuspense';import { useQueryRoute } from '@/hooks/useQueryRoute';import { usePathname, useQuery } from '@/libs/router/navigation';-const prefixCls = 'ant';--export const styles = createStaticStyles(({ css, cssVar }) => ({- active: css`- box-shadow: ${cssVar.boxShadow};- `,- bar: css`- .${prefixCls}-input-group-wrapper {- padding: 0;- }- `,-}));-interface StoreSearchBarProps extends SearchBarProps {mobile?: boolean;}diff --git a/src/routes/(main)/community/features/Title.tsx b/src/routes/(main)/community/features/Title.tsxindex f667584a8ec..91ea9e3218d 100644--- a/src/routes/(main)/community/features/Title.tsx+++ b/src/routes/(main)/community/features/Title.tsx@@ -1,31 +1,21 @@'use client';import { type FlexboxProps } from '@lobehub/ui';-import { createStaticStyles, cx, Flexbox, Icon } from '@lobehub/ui';+import { Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { ChevronRight } from 'lucide-react';import { type ReactNode } from 'react';import { memo } from 'react';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';-const styles = createStaticStyles(({ css, cssVar }) => ({- more: css`- display: flex;- align-items: center;- color: ${cssVar.colorTextSecondary};- `,- title: css`- margin-block: 0.2em;- font-weight: bold;- line-height: 1.5;- `,- title2: css`- font-size: 18px;- `,- title3: css`- font-size: 16px;- `,-}));+const styles = stylex.create({+ more: { display: 'flex', alignItems: 'center', color: cssVar.colorTextSecondary },+ title: { marginBlock: '0.2em', fontWeight: 'bold', lineHeight: 1.5 },+ title2: { fontSize: '18px' },+ title3: { fontSize: '16px' },+});export interface TitleProps extends FlexboxProps {icon?: ReactNode;@@ -39,7 +29,7 @@ export interface TitleProps extends FlexboxProps {const Title = memo<TitleProps>(({ id, tag, children, moreLink, more, level = 2, icon, ...rest }) => {const title = (- <h2 className={cx(styles.title, styles[`title${level}` as 'title2' | 'title3'])} id={id}>+ <h2 {...stylex.props(styles.title, level === 3 ? styles.title3 : styles.title2)} id={id}>{children}</h2>);@@ -52,21 +42,21 @@ const Title = memo<TitleProps>(if (moreLink) {if (isExternalLink) {moreLinkElement = (- <a className={styles.more} href={moreLink} rel="noreferrer" target="_blank">+ <a {...stylex.props(styles.more)} href={moreLink} rel="noreferrer" target="_blank"><span style={{ marginRight: 4 }}>{more}</span><Icon icon={ChevronRight} /></a>);} else if (isCommunityRoute) {moreLinkElement = (- <WorkspaceLink className={styles.more} to={moreLink}>+ <WorkspaceLink className={stylex.props(styles.more).className} to={moreLink}><span style={{ marginRight: 4 }}>{more}</span><Icon icon={ChevronRight} /></WorkspaceLink>);} else {moreLinkElement = (- <WorkspaceLink className={styles.more} to={moreLink}>+ <WorkspaceLink className={stylex.props(styles.more).className} to={moreLink}><span style={{ marginRight: 4 }}>{more}</span><Icon icon={ChevronRight} /></WorkspaceLink>diff --git a/src/routes/(mobile)/_layout/NavBar.module.css b/src/routes/(mobile)/_layout/NavBar.module.cssnew file mode 100644index 00000000000..db3b7058736--- /dev/null+++ b/src/routes/(mobile)/_layout/NavBar.module.css@@ -0,0 +1,3 @@+.active svg {+ fill: color-mix(in srgb, var(--lobe-color-primary) 33%, transparent);+}diff --git a/src/routes/(mobile)/_layout/NavBar.tsx b/src/routes/(mobile)/_layout/NavBar.tsxindex f777affa927..c1bdead4198 100644--- a/src/routes/(mobile)/_layout/NavBar.tsx+++ b/src/routes/(mobile)/_layout/NavBar.tsx@@ -1,8 +1,9 @@'use client';-import { createStaticStyles, Icon } from '@lobehub/ui';+import { Icon } from '@lobehub/ui';import { type TabBarProps } from '@lobehub/ui/mobile';import { TabBar } from '@lobehub/ui/mobile';+import * as stylex from '@stylexjs/stylex';import { Compass, MessageSquare, User } from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -13,19 +14,16 @@ import { useMobileNavigation } from '@/hooks/useMobileNavigation';import { SidebarTabKey } from '@/store/global/initialState';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';-const styles = createStaticStyles(({ css, cssVar }) => ({- active: css`- svg {- fill: color-mix(in srgb, ${cssVar.colorPrimary} 33%, transparent);- }- `,- container: css`- position: fixed;- z-index: 100;- inset-block-end: 0;- inset-inline: 0;- `,-}));+import moduleStyles from './NavBar.module.css';++const styles = stylex.create({+ container: {+ position: 'fixed',+ zIndex: 100,+ insetBlockEnd: 0,+ insetInline: 0,+ },+});const NavBar = memo(() => {const { t } = useTranslation('common');@@ -39,7 +37,7 @@ const NavBar = memo(() => {[{icon: (active: boolean) => (- <Icon className={active ? styles.active : undefined} icon={MessageSquare} />+ <Icon className={active ? moduleStyles.active : undefined} icon={MessageSquare} />),key: SidebarTabKey.Chat,onClick: () => {@@ -49,7 +47,7 @@ const NavBar = memo(() => {},showMarket && {icon: (active: boolean) => (- <Icon className={active ? styles.active : undefined} icon={Compass} />+ <Icon className={active ? moduleStyles.active : undefined} icon={Compass} />),key: SidebarTabKey.Community,onClick: () => {@@ -59,7 +57,7 @@ const NavBar = memo(() => {},{icon: (active: boolean) => (- <Icon className={active ? styles.active : undefined} icon={User} />+ <Icon className={active ? moduleStyles.active : undefined} icon={User} />),key: SidebarTabKey.Me,onClick: () => {@@ -74,7 +72,7 @@ const NavBar = memo(() => {return (<TabBaractiveKey={activeKey}- className={styles.container}+ className={stylex.props(styles.container).className}height={MOBILE_TABBAR_HEIGHT}items={items}/>diff --git a/src/routes/(mobile)/chat/_layout/index.tsx b/src/routes/(mobile)/chat/_layout/index.tsxindex e5b82f83f72..4d47f1d8267 100644--- a/src/routes/(mobile)/chat/_layout/index.tsx+++ b/src/routes/(mobile)/chat/_layout/index.tsx@@ -1,5 +1,6 @@'use client';+import * as stylex from '@stylexjs/stylex';import { type FC } from 'react';import { Outlet } from 'react-router';@@ -12,7 +13,10 @@ import { styles } from './style';// Agent init and id sync live one level up in the agent scope layout// (`(mobile)/agent/_layout`), which the chat shares with the sub-pages.const Layout: FC = () => (- <MobileContentLayout className={styles.mainContainer} header={<ChatHeader />}>+ <MobileContentLayout+ className={stylex.props(styles.mainContainer).className}+ header={<ChatHeader />}+ >{/* Same 404 fallback as the desktop agent layout: only the content areacollapses when the routed agent is gone or turned private. */}<AgentNotFoundGuard>diff --git a/src/routes/(mobile)/chat/_layout/style.ts b/src/routes/(mobile)/chat/_layout/style.tsindex c05a133036e..6fa384af492 100644--- a/src/routes/(mobile)/chat/_layout/style.ts+++ b/src/routes/(mobile)/chat/_layout/style.ts@@ -1,8 +1,8 @@-import { createStaticStyles } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css }) => ({+export const styles = stylex.create({// Main container- mainContainer: css`- overflow-y: hidden;- `,-}));+ mainContainer: {+ overflowY: 'hidden',+ },+});diff --git a/src/routes/(mobile)/community/(list)/_layout/Header.tsx b/src/routes/(mobile)/community/(list)/_layout/Header.tsxindex 6b34d6cad6c..5004334f75a 100644--- a/src/routes/(mobile)/community/(list)/_layout/Header.tsx+++ b/src/routes/(mobile)/community/(list)/_layout/Header.tsx@@ -1,7 +1,9 @@'use client';-import { ActionIcon, createStaticStyles, Flexbox } from '@lobehub/ui';+import { ActionIcon, Flexbox } from '@lobehub/ui';import { ChatHeader } from '@lobehub/ui/mobile';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { SearchIcon } from 'lucide-react';import { memo, useState } from 'react';@@ -11,16 +13,16 @@ import { mobileHeaderSticky } from '@/styles/mobileHeader';import StoreSearchBar from '../../../../(main)/community/features/Search';import Nav from './Nav';-const styles = createStaticStyles(({ css, cssVar }) => ({- search: css`- position: absolute;- z-index: 10;- inset-block-start: 0;- inset-inline: 0;-- background: ${cssVar.colorBgLayout};- `,-}));+const styles = stylex.create({+ search: {+ position: 'absolute',+ zIndex: 10,+ insetBlockStart: '0',+ insetInline: '0',+ backgroundColor: cssVar.colorBgLayout,+ backgroundImage: 'none',+ },+});const Header = memo(() => {const [showSearch, setShowSearch] = useState(false);@@ -31,14 +33,24 @@ const Header = memo(() => {styles={{ center: { display: 'none' } }}center={showSearch && (- <Flexbox align={'center'} className={styles.search} paddingBlock={8} paddingInline={16}>+ <Flexbox+ align={'center'}+ className={stylex.props(styles.search).className}+ paddingBlock={8}+ paddingInline={16}+ ><StoreSearchBar mobile onBlur={() => setShowSearch(false)} /></Flexbox>)}right={showSearch ? (- <Flexbox align={'center'} className={styles.search} paddingBlock={8} paddingInline={16}>+ <Flexbox+ align={'center'}+ className={stylex.props(styles.search).className}+ paddingBlock={8}+ paddingInline={16}+ ><StoreSearchBar mobile onBlur={() => setShowSearch(false)} /></Flexbox>) : (diff --git a/src/routes/(mobile)/community/(list)/_layout/Nav.tsx b/src/routes/(mobile)/community/(list)/_layout/Nav.tsxindex 82ec45dc402..cfda1b64814 100644--- a/src/routes/(mobile)/community/(list)/_layout/Nav.tsx+++ b/src/routes/(mobile)/community/(list)/_layout/Nav.tsx@@ -1,6 +1,8 @@'use client';-import { ActionIcon, createStaticStyles, cssVar, Drawer, Flexbox } from '@lobehub/ui';+import { ActionIcon, Drawer, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { MenuIcon } from 'lucide-react';import { memo, useState } from 'react';@@ -19,24 +21,13 @@ const scrollToTop = () => {scrollableElement.scrollTo({ behavior: 'smooth', top: 0 });};-export const styles = createStaticStyles(({ css, cssVar }) => ({- activeNavItem: css`- background: ${cssVar.colorFillTertiary};- `,- container: css`- height: auto;- padding-block: 4px;- background: ${cssVar.colorBgLayout};- `,- navItem: css`- font-weight: 500;- `,- title: css`- font-size: 18px;- font-weight: 700;- line-height: 1.2;- `,-}));+const styles = stylex.create({+ title: {+ fontSize: '18px',+ fontWeight: 700,+ lineHeight: 1.2,+ },+});const Nav = memo(() => {const [open, setOpen] = useState(false);@@ -45,7 +36,7 @@ const Nav = memo(() => {return (<>- <Flexbox horizontal align={'center'} className={styles.title} gap={4}>+ <Flexbox horizontal align={'center'} className={stylex.props(styles.title).className} gap={4}><ActionIconcolor={cssVar.colorText}icon={MenuIcon}diff --git a/src/routes/(mobile)/community/(list)/_layout/index.tsx b/src/routes/(mobile)/community/(list)/_layout/index.tsxindex 3880f646bfb..49122ef4375 100644--- a/src/routes/(mobile)/community/(list)/_layout/index.tsx+++ b/src/routes/(mobile)/community/(list)/_layout/index.tsx@@ -1,3 +1,4 @@+import * as stylex from '@stylexjs/stylex';import { Outlet } from 'react-router';import MobileContentLayout from '@/components/server/MobileNavLayout';@@ -12,7 +13,7 @@ const Layout = () => {return (<MobileContentLayoutwithNav- className={styles.mainContainer}+ className={stylex.props(styles.mainContainer).className}gap={16}header={<Header />}id={SCROLL_PARENT_ID}diff --git a/src/routes/(mobile)/community/(list)/_layout/style.ts b/src/routes/(mobile)/community/(list)/_layout/style.tsindex 88ae94c30d3..ca657537639 100644--- a/src/routes/(mobile)/community/(list)/_layout/style.ts+++ b/src/routes/(mobile)/community/(list)/_layout/style.ts@@ -1,9 +1,10 @@-import { createStaticStyles } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-export const styles = createStaticStyles(({ css }) => ({+export const styles = stylex.create({// Main container- mainContainer: css`- padding-block: 8px 48px;- padding-inline: 16px;- `,-}));+ mainContainer: {+ paddingBlockStart: '8px',+ paddingBlockEnd: '48px',+ paddingInline: '16px',+ },+});diff --git a/src/routes/(mobile)/me/settings/features/Category.tsx b/src/routes/(mobile)/me/settings/features/Category.tsxindex bb9ee86c630..6542798629b 100644--- a/src/routes/(mobile)/me/settings/features/Category.tsx+++ b/src/routes/(mobile)/me/settings/features/Category.tsx@@ -1,6 +1,7 @@'use client';-import { createStaticStyles, cssVar } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { Fragment, memo } from 'react';import Cell from '@/components/Cell';@@ -8,16 +9,16 @@ import Divider from '@/components/Cell/Divider';import { useCategory } from './useCategory';-const styles = createStaticStyles(({ css }) => ({- groupTitle: css`- padding-block: 16px 4px;- padding-inline: 16px;-- font-size: 12px;- font-weight: 500;- color: ${cssVar.colorTextSecondary};- `,-}));+const styles = stylex.create({+ groupTitle: {+ paddingBlockStart: '16px',+ paddingBlockEnd: '4px',+ paddingInline: '16px',+ fontSize: '12px',+ fontWeight: 500,+ color: cssVar.colorTextSecondary,+ },+});const Category = memo(() => {const groups = useCategory();@@ -27,7 +28,7 @@ const Category = memo(() => {{groups.map((group, groupIndex) => (<Fragment key={group.key}>{groupIndex > 0 && <Divider />}- <div className={styles.groupTitle}>{group.title}</div>+ <div {...stylex.props(styles.groupTitle)}>{group.title}</div>{group.items.map(({ key, ...item }) => (<Cell key={key} {...item} />))}diff --git a/src/routes/(popup)/_layout/TitleBar.tsx b/src/routes/(popup)/_layout/TitleBar.tsxindex 6c17a6b47d3..173628d7168 100644--- a/src/routes/(popup)/_layout/TitleBar.tsx+++ b/src/routes/(popup)/_layout/TitleBar.tsx@@ -1,13 +1,16 @@'use client';import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';-import { createStaticStyles, cx, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo } from 'react';import { useWatchThemeUpdate } from '@/features/Electron/system/useWatchThemeUpdate';import { WINDOWS_NATIVE_CONTROL_WIDTH } from '@/features/Electron/titlebar/layout';import WinControl from '@/features/Electron/titlebar/WinControl';import { electronStylish } from '@/styles/electron';+import { sx } from '@/styles/sx';import { getPlatform, isMacOS } from '@/utils/platform';import PinOnTopButton from './PinOnTopButton';@@ -15,22 +18,24 @@ import PinOnTopButton from './PinOnTopButton';// Reserve space for macOS traffic lights when titleBarStyle is hidden.const MAC_TRAFFIC_LIGHT_WIDTH = 80;-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- user-select: none;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- background: ${cssVar.colorBgLayout};- `,- title: css`- overflow: hidden;-- font-size: 13px;- color: ${cssVar.colorTextSecondary};- text-align: center;- text-overflow: ellipsis;- white-space: nowrap;- `,-}));+const styles = stylex.create({+ container: {+ userSelect: 'none',+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ backgroundColor: cssVar.colorBgLayout,+ backgroundImage: 'none',+ },+ title: {+ overflow: 'hidden',+ fontSize: '13px',+ color: cssVar.colorTextSecondary,+ textAlign: 'center',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+});interface PopupTitleBarProps {title?: string;@@ -51,7 +56,7 @@ const PopupTitleBar = memo<PopupTitleBarProps>(({ title }) => {<Flexboxhorizontalalign={'center'}- className={cx(styles.container, electronStylish.draggable)}+ className={sx([styles.container], electronStylish.draggable).className}flex={'none'}gap={4}height={TITLE_BAR_HEIGHT}@@ -60,7 +65,7 @@ const PopupTitleBar = memo<PopupTitleBarProps>(({ title }) => {><div style={{ flex: `0 0 ${leftSpacer}px` }} /><Flexbox flex={1} style={{ minWidth: 0 }}>- {title && <div className={styles.title}>{title}</div>}+ {title && <div {...stylex.props(styles.title)}>{title}</div>}</Flexbox><PinOnTopButton />{showWinControl ? <WinControl /> : <div style={{ flex: `0 0 ${rightSpacer}px` }} />}diff --git a/src/routes/(popup)/_layout/index.tsx b/src/routes/(popup)/_layout/index.tsxindex c2f695648ed..9cea8e77e0d 100644--- a/src/routes/(popup)/_layout/index.tsx+++ b/src/routes/(popup)/_layout/index.tsx@@ -1,7 +1,9 @@'use client';import { HotkeyScopeEnum } from '@lobechat/const/hotkeys';-import { createStaticStyles, Flexbox } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { type FC } from 'react';import { HotkeysProvider } from 'react-hotkeys-hook';import { Outlet } from 'react-router';@@ -13,11 +15,9 @@ import { topicSelectors } from '@/store/chat/selectors';import PopupTitleBar from './TitleBar';-const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- background: ${cssVar.colorBgContainer};- `,-}));+const styles = stylex.create({+ container: { backgroundColor: cssVar.colorBgContainer, backgroundImage: 'none' },+});const PopupLayout: FC = () => {const topicTitle = useChatStore((s) => topicSelectors.currentActiveTopic(s)?.title);@@ -29,7 +29,7 @@ const PopupLayout: FC = () => {return (<HotkeysProvider initiallyActiveScopes={[HotkeyScopeEnum.Global]}><Flexbox- className={styles.container}+ className={stylex.props(styles.container).className}height={'100%'}style={{ overflow: 'hidden' }}width={'100%'}diff --git a/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx b/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsxindex d16494b46b7..e4869bd3d63 100644--- a/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx+++ b/src/routes/(popup)/agent/[aid]/QuickChatAgentSwitcher.tsx@@ -2,7 +2,9 @@import { INBOX_SESSION_ID } from '@lobechat/const';import { agentDisplayName } from '@lobechat/types';-import { createStaticStyles, cx, Flexbox, Icon, Input, Popover, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Input, Popover, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';import { MoreHorizontalIcon } from 'lucide-react';import { memo, useMemo, useState } from 'react';@@ -31,85 +33,60 @@ interface SwitchItem {title: string;}-const styles = createStaticStyles(({ css, cssVar }) => ({- active: css`- border-color: ${cssVar.colorPrimary};- box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBgHover};- `,- itemBtn: css`- cursor: pointer;-- box-sizing: content-box;- padding: 0;- border: 1.5px solid transparent;- border-radius: 8px;-- opacity: 0.65;- background: transparent;-- transition:- opacity 0.15s,- border-color 0.15s,- box-shadow 0.15s;-- &:hover {- opacity: 1;- }- `,- more: css`- display: flex;- align-items: center;- justify-content: center;-- width: ${AVATAR_SIZE}px;- height: ${AVATAR_SIZE}px;- border: 1.5px solid transparent;- border-radius: 8px;-- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};-- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillSecondary};- }- `,- popover: css`- padding: 0;- `,- popoverContent: css`- width: 240px;- padding: 8px;- `,- popoverEmpty: css`- padding-block: 16px;- padding-inline: 8px;- color: ${cssVar.colorTextTertiary};- text-align: center;- `,- popoverList: css`- overflow: auto;- max-height: 240px;- `,- popoverRow: css`- cursor: pointer;-- display: flex;- gap: 8px;- align-items: center;-- padding-block: 6px;- padding-inline: 8px;- border-radius: 6px;-- color: ${cssVar.colorText};-- &:hover {- background: ${cssVar.colorFillSecondary};- }- `,-}));+const styles = stylex.create({+ active: {+ borderColor: cssVar.colorPrimary,+ boxShadow: `0 0 0 2px ${cssVar.colorPrimaryBgHover}`,+ },+ itemBtn: {+ cursor: 'pointer',+ boxSizing: 'content-box',+ padding: '0',+ borderWidth: '1.5px',+ borderStyle: 'solid',+ borderColor: 'transparent',+ borderRadius: '8px',+ opacity: { 'default': 0.65, ':hover': 1 },+ backgroundColor: 'transparent',+ backgroundImage: 'none',+ transition: 'opacity 0.15s,\n border-color 0.15s,\n box-shadow 0.15s',+ },+ more: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: `${AVATAR_SIZE}px`,+ height: `${AVATAR_SIZE}px`,+ borderWidth: '1.5px',+ borderStyle: 'solid',+ borderColor: 'transparent',+ borderRadius: '8px',+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ backgroundColor: { 'default': cssVar.colorFillTertiary, ':hover': cssVar.colorFillSecondary },+ backgroundImage: { 'default': 'none', ':hover': 'none' },+ },+ popover: { padding: '0' },+ popoverContent: { width: '240px', padding: '8px' },+ popoverEmpty: {+ paddingBlock: '16px',+ paddingInline: '8px',+ color: cssVar.colorTextTertiary,+ textAlign: 'center',+ },+ popoverList: { overflow: 'auto', maxHeight: '240px' },+ popoverRow: {+ cursor: 'pointer',+ display: 'flex',+ gap: '8px',+ alignItems: 'center',+ paddingBlock: '6px',+ paddingInline: '8px',+ borderRadius: '6px',+ color: cssVar.colorText,+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillSecondary },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+});const useSwitchItems = (): SwitchItem[] => {const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);@@ -198,7 +175,7 @@ const QuickChatAgentSwitcher = memo(() => {<Tooltip key={item.id} title={item.title}><buttonaria-label={item.title}- className={cx(styles.itemBtn, isActive(item) && styles.active)}+ {...stylex.props(styles.itemBtn, isActive(item) && styles.active)}type={'button'}onClick={() => handleSelect(item)}>@@ -215,12 +192,12 @@ const QuickChatAgentSwitcher = memo(() => {{remaining.length > 0 && (<Popoverarrow={false}- classNames={{ content: styles.popover }}+ classNames={{ content: stylex.props(styles.popover).className }}open={popoverOpen}placement={'bottom'}trigger={'click'}content={- <div className={styles.popoverContent}>+ <div {...stylex.props(styles.popoverContent)}><InputallowClearplaceholder={t('quickChatSwitcher.searchPlaceholder')}@@ -228,13 +205,13 @@ const QuickChatAgentSwitcher = memo(() => {value={search}onChange={(e) => setSearch(e.target.value)}/>- <div className={styles.popoverList} style={{ marginTop: 8 }}>+ <div className={stylex.props(styles.popoverList).className} style={{ marginTop: 8 }}>{filteredRemaining.length === 0 ? (- <div className={styles.popoverEmpty}>{t('quickChatSwitcher.empty')}</div>+ <div {...stylex.props(styles.popoverEmpty)}>{t('quickChatSwitcher.empty')}</div>) : (filteredRemaining.map((item) => (<div- className={styles.popoverRow}+ {...stylex.props(styles.popoverRow)}key={item.id}onClick={() => handleSelect(item)}>@@ -262,7 +239,11 @@ const QuickChatAgentSwitcher = memo(() => {}onOpenChange={setPopoverOpen}>- <button aria-label={t('quickChatSwitcher.more')} className={styles.more} type={'button'}>+ <button+ aria-label={t('quickChatSwitcher.more')}+ {...stylex.props(styles.more)}+ type={'button'}+ ><Icon icon={MoreHorizontalIcon} size={16} /></button></Popover>diff --git a/src/spa/BootShell/AppShellSkeleton.tsx b/src/spa/BootShell/AppShellSkeleton.tsxindex 712de40cae0..59059c694f7 100644--- a/src/spa/BootShell/AppShellSkeleton.tsx+++ b/src/spa/BootShell/AppShellSkeleton.tsx@@ -1,8 +1,10 @@'use client';import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';-import { createStaticStyles, Flexbox, keyframes } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { LobeHub } from '@lobehub/ui/brand';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo, useLayoutEffect } from 'react';import { useTranslation } from 'react-i18next';@@ -14,6 +16,7 @@ import {} from '@/features/DesktopLayoutContainer/cssVariables';import { styles as containerStyles } from '@/features/DesktopLayoutContainer/style';import { electronStylish } from '@/styles/electron';+import { sx } from '@/styles/sx';import { readBootShellGeometry } from './geometry';import { useLoadingHint } from './useLoadingHint';@@ -26,80 +29,64 @@ const CSS_VAR_CLASS = 'lobe-vars';export const APP_SHELL_FALLBACK_ID = 'app-shell-fallback';-// Opacity only: on an otherwise still boot screen a rising caption reads as-// the layout jumping, and leaving `transform` alone keeps the centering in one-// place.-const fadeIn = keyframes`- from {- opacity: 0;- }-- to {- opacity: 1;- }-`;--const styles = createStaticStyles(({ css, cssVar }) => ({- contentBrand: css`- pointer-events: none;-- position: absolute;- inset: 0;-- display: flex;- align-items: center;- justify-content: center;+const fadeIn = stylex.keyframes({+ from: { opacity: 0 },+ to: { opacity: 1 },+});- color: ${cssVar.colorTextQuaternary};- `,+const styles = stylex.create({+ contentBrand: {+ pointerEvents: 'none',+ position: 'absolute',+ inset: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: cssVar.colorTextQuaternary,+ },// Floated rather than stacked in flow: a caption that joins the column would// push the brand mark off the center it shares with the app that replaces it.- hint: css`- position: absolute;- inset-block-start: calc(100% + 8px);- inset-inline-start: 50%;- transform: translateX(-50%);-- font-size: 13px;- white-space: nowrap;-- &[data-enter] {- animation: ${fadeIn} 0.3s ${cssVar.motionEaseOut} both;-- @media (prefers-reduced-motion: reduce) {- animation: none;- }- }- `,- brand: css`- position: relative;- display: flex;- align-items: center;- justify-content: center;- `,- dragRegion: css`- pointer-events: auto;- flex-shrink: 0;- width: 100%;- height: ${TITLE_BAR_HEIGHT}px;- `,- root: css`- pointer-events: none;-- position: fixed;- z-index: 99999;- inset: 0;-- display: flex;- flex-direction: column;-- /* Dialogs live inside the theme's isolated stacking context, so lowering- this z-index alone cannot reveal them. Yield without releasing the boot gate. */- body:has([role='dialog'][data-open]) & {- visibility: hidden;- }- `,-}));+ hint: {+ position: 'absolute',+ insetBlockStart: 'calc(100% + 8px)',+ insetInlineStart: '50%',+ transform: 'translateX(-50%)',+ fontSize: '13px',+ whiteSpace: 'nowrap',+ },+ hintEnter: {+ animationName: { 'default': fadeIn, '@media (prefers-reduced-motion: reduce)': 'none' },+ animationDuration: { 'default': '0.3s', '@media (prefers-reduced-motion: reduce)': '0s' },+ animationTimingFunction: {+ 'default': cssVar.motionEaseOut,+ '@media (prefers-reduced-motion: reduce)': 'ease',+ },+ animationFillMode: { 'default': 'both', '@media (prefers-reduced-motion: reduce)': 'none' },+ },+ brand: {+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ },+ dragRegion: {+ pointerEvents: 'auto',+ flexShrink: 0,+ width: '100%',+ },+ root: {+ // The dialog and boot shell are siblings, not a marker/descendant pair.+ // A self condition preserves the existing body :has() rule without moving+ // the shell or introducing a component-scoped stylesheet.+ visibility: { 'default': null, ':is(body:has([role="dialog"][data-open]) *)': 'hidden' },+ pointerEvents: 'none',+ position: 'fixed',+ zIndex: 99_999,+ inset: 0,+ display: 'flex',+ flexDirection: 'column',+ },+});/*** Split out so `useTranslation` runs only once the hint is due. The boot shell@@ -111,7 +98,7 @@ const LoadingHint = memo<{ enter: boolean }>(({ enter }) => {const { t } = useTranslation('common');return (- <div className={styles.hint} data-enter={enter || undefined}>+ <div {...stylex.props(styles.hint, enter && styles.hintEnter)} data-enter={enter || undefined}>{t('bootLoadingHint')}</div>);@@ -130,8 +117,12 @@ const AppShellSkeleton = memo<AppShellSkeletonProps>(({ id }) => {useLayoutEffect(retainSkeleton, []);return (- <div aria-hidden className={`${CSS_VAR_CLASS} ${styles.root}`} id={id}>- {isDesktop && <div className={`${styles.dragRegion} ${electronStylish.draggable}`} />}+ <div aria-hidden id={id} {...sx(styles.root, CSS_VAR_CLASS)}>+ {isDesktop && (+ <div+ {...sx([styles.dragRegion], electronStylish.draggable, { height: TITLE_BAR_HEIGHT })}+ />+ )}<Flexboxhorizontalheight={isDesktop ? `calc(100% - ${TITLE_BAR_HEIGHT}px)` : '100%'}@@ -160,8 +151,8 @@ const AppShellSkeleton = memo<AppShellSkeletonProps>(({ id }) => {style={getInnerCssVariables({ isDark })}width={'100%'}>- <div className={styles.contentBrand}>- <div className={styles.brand}>+ <div {...stylex.props(styles.contentBrand)}>+ <div {...stylex.props(styles.brand)}><LobeHub size={40} type={'text'} />{hint && <LoadingHint enter={hint === 'enter'} />}</div>diff --git a/src/styles/electron.ts b/src/styles/electron.tsindex 9d8a9c917a9..c626f0b230a 100644--- a/src/styles/electron.ts+++ b/src/styles/electron.ts@@ -1,12 +1,13 @@-import { css, cx } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';-export const draggable = cx(css`- -webkit-app-region: drag;-`);+const styles = stylex.create({+ draggable: { WebkitAppRegion: 'drag' },+ nodrag: { WebkitAppRegion: 'no-drag' },+});-export const nodrag = cx(css`- -webkit-app-region: no-drag;-`);+export const draggable = stylex.props(styles.draggable).className ?? '';++export const nodrag = stylex.props(styles.nodrag).className ?? '';export const electronStylish = {draggable,diff --git a/src/styles/global.css b/src/styles/global.cssnew file mode 100644index 00000000000..0717d3694ee--- /dev/null+++ b/src/styles/global.css@@ -0,0 +1,126 @@+/*+ * App-wide base rules, injected once by the SPA's AppTheme. Colours come from the+ * `--lobe-*` theme variables, which carry the same values `useTheme()` returned+ * when this was a runtime `createGlobalStyle`.+ */++/* fix ios input keyboard+ overflow: hidden;+ ref: https://zhuanlan.zhihu.com/p/113855026 */+html,+body,+#__next {+ position: relative;++ overscroll-behavior: none;++ height: 100%;+ min-height: 100dvh;+ max-height: 100dvh;+}++@media (device-width >= 576px) {+ html,+ body,+ #__next {+ overflow: hidden;++ /* The root cannot scroll here, and a root 'none' also suppresses the+ elastic overscroll of inner scrollers in Chromium on macOS. */+ overscroll-behavior: auto;+ }+}++body {+ /* Own stacking context, otherwise render black edges will appear. Must NOT+ be a transform-based hack: a transform on body rebases every position:+ fixed descendant onto body, and a drawer panel mid slide-in then overflows+ body horizontally — focusing it scrolls the whole page sideways. */+ will-change: opacity;+ isolation: isolate;+}++* {+ scrollbar-color: var(--lobe-color-fill) transparent;+ scrollbar-width: thin;+}++* ::-webkit-scrollbar {+ width: 0.75em;+ height: 0.75em;+}++* ::-webkit-scrollbar-thumb {+ border-radius: 10px;+}++* :hover::-webkit-scrollbar-thumb {+ border: 3px solid transparent;+ background-color: var(--lobe-color-text);+ background-clip: content-box;+}++* ::-webkit-scrollbar-track {+ background-color: transparent;+}++/* antd resets re-apply antialiased on each component root, so body alone is not enough */+html[data-font-antialiasing='off'] * {+ -webkit-font-smoothing: auto;+ -moz-osx-font-smoothing: auto;+}++html.desktop[data-theme='dark'] body {+ background-color: color-mix(in srgb, var(--lobe-color-bg-layout) 50%, transparent);+}++html.desktop[data-theme='light'] body {+ background-color: color-mix(in srgb, var(--lobe-color-bg-layout) 70%, transparent);+}++/* MAC_WINDOW_FULLSCREEN_SELECTOR / MAC_PANEL_BG_VAR from+ @/features/Electron/system/macWindowFullscreen */+html.desktop[data-window-fullscreen] {+ --mac-panel-bg: var(--lobe-color-bg-layout);+}++html.desktop[data-window-fullscreen] body {+ background-color: var(--lobe-color-bg-layout);+}++button {+ -webkit-app-region: no-drag;+}++/* CLASSNAMES.ContextTrigger / CLASSNAMES.DropdownMenuTrigger from @lobehub/ui */+.lobe-context-trigger[data-popup-open]:not([data-no-highlight]),+.lobe-dropdown-menu-trigger[data-popup-open]:not([data-no-highlight]) {+ background: var(--lobe-color-fill-tertiary);+}++.accordion-action:has(.lobe-dropdown-menu-trigger[data-popup-open]:not([data-no-highlight])) {+ opacity: 1;+}++/* CONVERSATION_PRINT_ROOT_CLASS from @/features/Conversation/ChatList/constants */+@media screen {+ .conversation-print-root {+ display: none;+ }+}++@media print {+ html:has(> body > .conversation-print-root),+ body:has(> .conversation-print-root) {+ overflow: visible;+ height: auto;+ min-height: 0;+ max-height: none;+ color-scheme: light !important;+ background: none !important;+ }++ body:has(> .conversation-print-root) > :not(.conversation-print-root) {+ display: none !important;+ }+}diff --git a/src/styles/global.ts b/src/styles/global.tsdeleted file mode 100644index 88b9ba8706f..00000000000--- a/src/styles/global.ts+++ /dev/null@@ -1,131 +0,0 @@-import { CLASSNAMES, css, cssVar } from '@lobehub/ui';--import { CONVERSATION_PRINT_ROOT_CLASS } from '@/features/Conversation/ChatList/constants';-import {- MAC_PANEL_BG_VAR,- MAC_WINDOW_FULLSCREEN_SELECTOR,-} from '@/features/Electron/system/macWindowFullscreen';--// fix ios input keyboard-// overflow: hidden;-// ref: https://zhuanlan.zhihu.com/p/113855026-const genGlobalStyle = () => css`- html,- body,- #__next {- position: relative;-- overscroll-behavior: none;-- height: 100%;- min-height: 100dvh;- max-height: 100dvh;-- @media (device-width >= 576px) {- overflow: hidden;-- /* The root cannot scroll here, and a root 'none' also suppresses the- elastic overscroll of inner scrollers in Chromium on macOS. */- overscroll-behavior: auto;- }- }-- body {- /* Own stacking context, otherwise render black edges will appear. Must NOT- be a transform-based hack: a transform on body rebases every position:- fixed descendant onto body, and a drawer panel mid slide-in then overflows- body horizontally — focusing it scrolls the whole page sideways. */- will-change: opacity;- isolation: isolate;- }-- * {- scrollbar-color: ${cssVar.colorFill} transparent;- scrollbar-width: thin;-- ::-webkit-scrollbar {- width: 0.75em;- height: 0.75em;- }-- ::-webkit-scrollbar-thumb {- border-radius: 10px;- }-- :hover::-webkit-scrollbar-thumb {- border: 3px solid transparent;- background-color: ${cssVar.colorText};- background-clip: content-box;- }-- ::-webkit-scrollbar-track {- background-color: transparent;- }- }-- /* antd resets re-apply antialiased on each component root, so body alone is not enough */- html[data-font-antialiasing='off'] * {- -webkit-font-smoothing: auto;- -moz-osx-font-smoothing: auto;- }-- html.desktop[data-theme='dark'] body {- background-color: color-mix(in srgb, ${cssVar.colorBgLayout} 50%, transparent);- }-- html.desktop[data-theme='light'] body {- background-color: color-mix(in srgb, ${cssVar.colorBgLayout} 70%, transparent);- }-- ${MAC_WINDOW_FULLSCREEN_SELECTOR} {- ${MAC_PANEL_BG_VAR}: ${cssVar.colorBgLayout};- }-- ${MAC_WINDOW_FULLSCREEN_SELECTOR} body {- background-color: ${cssVar.colorBgLayout};- }-- button {- -webkit-app-region: no-drag;- }-- .${CLASSNAMES.ContextTrigger}[data-popup-open]:not([data-no-highlight]),- .${CLASSNAMES.DropdownMenuTrigger}[data-popup-open]:not([data-no-highlight]) {- background: ${cssVar.colorFillTertiary};- }- .accordion-action:has(- .${CLASSNAMES.DropdownMenuTrigger}[data-popup-open]:not([data-no-highlight])- ) {- opacity: 1;- }-- /* Printing a conversation: keep only its transcript, no sidebars, headers,- composer or docks, and let the document grow past one viewport. */- @media screen {- .${CONVERSATION_PRINT_ROOT_CLASS} {- display: none;- }- }-- @media print {- html:has(> body > .${CONVERSATION_PRINT_ROOT_CLASS}),- body:has(> .${CONVERSATION_PRINT_ROOT_CLASS}) {- overflow: visible;-- height: auto;- min-height: 0;- max-height: none;-- /* Paper is white. next-themes writes a dark color-scheme inline on html,- which paints the page canvas dark, and the dark theme paints body. */- color-scheme: light !important;- background: none !important;- }-- body:has(> .${CONVERSATION_PRINT_ROOT_CLASS}) > :not(.${CONVERSATION_PRINT_ROOT_CLASS}) {- display: none !important;- }- }-`;--export default genGlobalStyle;diff --git a/src/styles/index.ts b/src/styles/index.tsindex 6832e0a695e..dd1f8139d43 100644--- a/src/styles/index.ts+++ b/src/styles/index.ts@@ -1,8 +1,2 @@-import { createGlobalStyle } from '@lobehub/ui';--import global from './global';--export const GlobalStyle = createGlobalStyle(() => [global()]);-export { shinyTextStyles } from './loading';export * from './text';diff --git a/src/styles/sx.ts b/src/styles/sx.tsindex b29aeb558f7..7d2ca3fb1be 100644--- a/src/styles/sx.ts+++ b/src/styles/sx.ts@@ -1,5 +1,5 @@import * as stylex from '@stylexjs/stylex';-import { type StyleXStyles } from '@stylexjs/stylex';+import { type CompiledStyles, type InlineStyles, type StyleXArray } from '@stylexjs/stylex';import { type CSSProperties } from 'react';/**@@ -12,11 +12,15 @@ import { type CSSProperties } from 'react';* specificity, so a plain class cannot override them. Components that let callers* restyle them take an `xstyle?: StyleXStyles` prop and pass it in `styles`.*- * `styles` is typed as `StyleXStyles`, not `Parameters<typeof stylex.props>`:- * `props` declares a `this` parameter, and the type-check resolves that derived- * type to `never`, rejecting every call.+ * Mirror props' exported argument types explicitly: StyleXStyles restricts CSS+ * properties and rejects compiled custom properties and marker symbols. Deriving+ * Parameters<typeof stylex.props> also resolves to never in Bun's checker.*/-export const sx = (styles: StyleXStyles, className?: string, style?: CSSProperties) => {+type SxArgument = StyleXArray<+ CompiledStyles | boolean | null | undefined | Readonly<[CompiledStyles, InlineStyles]>+>;++export const sx = (styles: SxArgument, className?: string, style?: CSSProperties) => {const props = stylex.props(styles);const mergedClassName = [props.className, className].filter(Boolean).join(' ');return {diff --git a/vitest.config.mts b/vitest.config.mtsindex 6a1f0901612..b1daea550a1 100644--- a/vitest.config.mts+++ b/vitest.config.mts@@ -66,6 +66,9 @@ const exclude = ['**/apps/cli/**','**/packages/**','**/e2e/**',+ // Opt-in local verification tooling, not app/server CI unit tests.+ // Run with `bun run stylex:verify:test` instead.+ '**/scripts/stylexMigration/verification/**',];export default defineConfig({