JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix:解决randomUUID的兼容性问题;去掉会话运行中不允许切换code和work的限制;增加初次进入系统,渐进式引导配置模型
xiaoyao42564ed861a3bb
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 45f3957021..afcf64a3af 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -78,14 +78,26 @@ import {isDesktopSaveOk,} from './utils/desktopSave';import type { DesktopSaveApiResult } from './utils/desktopSave';+import { generateUuidV4 } from './utils/uuid';+import {+ ModelSetupGuide,+ type ModelSetupGuideStep,+} from './features/modelSetupGuide/ModelSetupGuide';+import { isSetupGuideEnabled } from './features/modelSetupGuide/modelSetupGuideState';import './App.css';const TEAM_SESSION_MODES = new Set(['team', 'team.plan', 'code.team']);+const PREVIEW_MODEL_SETUP_GUIDE = import.meta.env.DEV+ && new URLSearchParams(window.location.search).get('modelSetupGuide') === '1';function isTeamMode(mode: string): boolean {return TEAM_SESSION_MODES.has(mode);}+function shouldPreviewModelSetupGuide(): boolean {+ return PREVIEW_MODEL_SETUP_GUIDE;+}+type MainNavKey = 'chat' | 'skills' | 'agents' | 'teams' | 'sessions' | 'cron' | 'channels' | 'extensions' | 'configpanel' | 'browserpanel' | 'updatepanel';type LoadedHistoryPage = {@@ -222,7 +234,7 @@ function ErrorFallback({ error }: { error: Error | null }) {function generateSessionId(): string {const ts = Date.now().toString(16);- const rand = crypto.randomUUID().replaceAll('-', '').slice(0, 12);+ const rand = generateUuidV4().replaceAll('-', '').slice(0, 12);return `sess_${ts}_${rand}`;}@@ -281,12 +293,15 @@ function AppContent() {const [hasVisitedSkills, setHasVisitedSkills] = useState(false);const [hasVisitedChannels, setHasVisitedChannels] = useState(false);const [sidebarMorePanelOpen, setSidebarMorePanelOpen] = useState(false);+ const [modelSetupGuideStep, setModelSetupGuideStep] = useState<ModelSetupGuideStep | null>(null);+ const [modelSetupGuideManual, setModelSetupGuideManual] = useState(false);const [deleteTarget, setDeleteTarget] = useState<Session | null>(null);const [dialogBusy, setDialogBusy] = useState(false);const [dialogError, setDialogError] = useState<string | null>(null);const [composerFocusNonce, setComposerFocusNonce] = useState(0);const [missingSessionId, setMissingSessionId] = useState<string | null>(null);const startupUpdateCheckRef = useRef(false);+ const modelSetupGuideEvaluatedRef = useRef(false);/** 从 SkillNet 等入口跳转配置页时,首次展开对应配置分组(如第三方服务) */const [configInitialExpandGroup, setConfigInitialExpandGroup] = useState<string | null>(null);@@ -829,6 +844,14 @@ function AppContent() {setA2UIFeatureEnabled(normalizeA2UIEnabled(config.a2ui_enabled));setServerConfig(config);setConfigError(null);+ if (!modelSetupGuideEvaluatedRef.current) {+ modelSetupGuideEvaluatedRef.current = true;+ if (shouldPreviewModelSetupGuide() || isSetupGuideEnabled(config.setup_guide_enabled)) {+ setActiveNav('chat');+ setModelSetupGuideManual(false);+ setModelSetupGuideStep(1);+ }+ }} catch (error) {console.error('Failed to fetch config:', error);setServerConfig(null);@@ -1937,8 +1960,38 @@ function AppContent() {const handleNavigate = useCallback((nav: MainNavKey) => {setActiveNav(nav);+ if (modelSetupGuideStep === 1 && nav === 'configpanel') {+ setModelSetupGuideStep(2);+ }if (nav === 'skills') setHasVisitedSkills(true);if (nav === 'channels') setHasVisitedChannels(true);+ }, [modelSetupGuideStep]);++ const skipModelSetupGuide = useCallback(() => {+ setModelSetupGuideStep(null);+ setModelSetupGuideManual(false);+ }, []);++ const acknowledgeModelSetupGuide = useCallback(() => {+ setModelSetupGuideStep(null);+ setModelSetupGuideManual(false);++ void request('config.set', { setup_guide_enabled: 'false' })+ .then(() => {+ setServerConfig((current) => ({+ ...(current ?? {}),+ setup_guide_enabled: 'false',+ }));+ })+ .catch((error) => {+ console.error('Failed to disable setup guide:', error);+ });+ }, [request]);++ const openModelSetupGuide = useCallback(() => {+ setActiveNav('chat');+ setModelSetupGuideManual(true);+ setModelSetupGuideStep(1);}, []);const handleExportShare = useCallback(async () => {@@ -2044,8 +2097,18 @@ function AppContent() {showNewSession={false}hiddenNavItems={['sessions']}onMorePanelOpenChange={setSidebarMorePanelOpen}+ onSetupGuideRequest={openModelSetupGuide}/>+ {modelSetupGuideStep ? (+ <ModelSetupGuide+ step={modelSetupGuideStep}+ manual={modelSetupGuideManual}+ onAcknowledge={acknowledgeModelSetupGuide}+ onSkip={skipModelSetupGuide}+ />+ ) : null}+{/* Main Content */}<main className={`content ${activeNav === 'chat' ? 'content--chat' : ''} ${isTeamAreaExpanded ? 'content--team-expanded' : ''}`}>{configError && (diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsxindex 6a98ffdf47..85c3f78c0b 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx@@ -26,6 +26,7 @@ import sendIcon from '../../assets/send.svg';import sendActiveIcon from '../../assets/send_active.svg';import { TeamMemberAvatar } from '../TeamMemberAvatar';import { CodeBranchSelector } from '../../features/code-mode/CodeBranchSelector';+import { generateUuidV4 } from '../../utils/uuid';/** 输入栏下拉所需的最小技能数据结构(与 SkillPanel 中的 SkillItem 保持一致) */type InputAreaSkillItem = {@@ -157,10 +158,7 @@ function formatAttachmentSize(size: number): string {}function makeAttachmentId(file: File): string {- const random = typeof crypto !== 'undefined' && 'randomUUID' in crypto- ? crypto.randomUUID()- : `${Date.now()}-${Math.random().toString(36).slice(2)}`;- return `${file.name || 'image'}-${file.size}-${random}`;+ return `${file.name || 'image'}-${file.size}-${generateUuidV4()}`;}function attachmentToMediaItem(attachment: AttachmentDraft): MediaItem {diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.cssindex 7552c676af..3abf15fd30 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css@@ -311,7 +311,16 @@min-height: 8px;}-/* Last bottom item gets more spacing */-.icon-rail-spacer + .icon-rail-nav-item {+.icon-rail-help-button {+ min-height: 36px;+ margin-bottom: 2px;+ color: var(--color-text-secondary);+}++.icon-rail-help-button:hover {+ color: var(--color-text-primary);+}++.icon-rail-help-button + .icon-rail-nav-item {margin-bottom: 12px;}diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsxindex deac93f522..f3c89e5965 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx@@ -32,6 +32,7 @@ interface SessionSidebarProps {showNewSession?: boolean;hiddenNavItems?: MainNavKey[];onMorePanelOpenChange?: (open: boolean) => void;+ onSetupGuideRequest: () => void;}interface NavItem {@@ -55,9 +56,9 @@ const mainNavItems: NavItem[] = [];const moreNavItems: NavItem[] = [+ { key: 'configpanel', labelKey: 'nav.config', icon: <ConfigIcon aria-hidden /> },{ key: 'extensions', labelKey: 'nav.extensions', icon: <PluginIcon aria-hidden /> },{ key: 'browserpanel', labelKey: 'nav.browser', icon: <WebIcon aria-hidden /> },- { key: 'configpanel', labelKey: 'nav.config', icon: <ConfigIcon aria-hidden /> },{ key: 'updatepanel', labelKey: 'nav.update', icon: <UpdateIcon aria-hidden /> },];@@ -156,6 +157,7 @@ export function SessionSidebar({showNewSession = true,hiddenNavItems = [],onMorePanelOpenChange,+ onSetupGuideRequest,}: SessionSidebarProps) {const { t } = useTranslation();const [advancedConfigOpen, setAdvancedConfigOpen] = useState(false);@@ -238,6 +240,7 @@ export function SessionSidebar({className={`icon-rail-nav-item${isMoreActive ? ' icon-rail-nav-item--active' : ''}`}onClick={handleMoreClick}aria-expanded={isMoreActive}+ data-model-setup-guide-target="more"><span className="icon-rail-nav-item__icon"><MoreDesignIcon aria-hidden />@@ -266,6 +269,27 @@ export function SessionSidebar({<div className="icon-rail-spacer" />+ <button+ type="button"+ className="icon-rail-nav-item icon-rail-help-button"+ onClick={onSetupGuideRequest}+ aria-label={t('modelSetupGuide.open')}+ title={t('modelSetupGuide.open')}+ >+ <span className="icon-rail-nav-item__icon">+ <svg viewBox="0 0 24 24" fill="none" aria-hidden>+ <circle cx="12" cy="12" r="8.25" stroke="currentColor" strokeWidth="1.5" />+ <path+ d="M9.8 9.35a2.35 2.35 0 014.55.82c0 1.57-1.2 2.05-2.02 2.7-.48.38-.73.74-.73 1.38"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ />+ <circle cx="11.6" cy="17.15" r=".85" fill="currentColor" />+ </svg>+ </span>+ </button>+<buttonref={settingsRef}className="icon-rail-nav-item"diff --git a/jiuwenswarm/channels/web/frontend/src/features/modelSetupGuide/ModelSetupGuide.css b/jiuwenswarm/channels/web/frontend/src/features/modelSetupGuide/ModelSetupGuide.cssnew file mode 100644index 0000000000..82825a29b0--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/modelSetupGuide/ModelSetupGuide.css@@ -0,0 +1,197 @@+.model-setup-guide {+ position: fixed;+ z-index: 2000;+ inset: 0;+ pointer-events: none;+}++.model-setup-guide__mask {+ position: fixed;+ background: var(--color-backdrop-strong);+ pointer-events: auto;+}++.model-setup-guide__spotlight {+ position: fixed;+ border: 1px solid var(--color-action-primary);+ border-radius: 12px;+ box-shadow: var(--effect-shadow-lg);+ pointer-events: none;+}++[data-model-setup-guide-target='more'][aria-describedby^='model-setup-guide-description-'] {+ outline: none;+ box-shadow: none;+}++.model-setup-guide__callout {+ position: fixed;+ padding: 20px;+ border: 1px solid var(--color-border-default);+ border-radius: 16px;+ background: var(--color-surface-popover);+ box-shadow: var(--effect-shadow-lg);+ color: var(--color-text-primary);+ pointer-events: auto;+ animation: modelSetupGuideEnter 200ms cubic-bezier(0.16, 1, 0.3, 1);+}++.model-setup-guide__skip {+ appearance: none;+ position: absolute;+ top: 20px;+ right: 16px;+ min-width: 44px;+ height: 24px;+ padding: 0 10px;+ border: 0;+ border-radius: 999px;+ outline: none;+ background: var(--color-action-secondary);+ box-shadow: none;+ color: var(--color-text-secondary);+ font-size: 12px;+ font-weight: 500;+ line-height: 24px;+ text-align: center;+ cursor: pointer;+ transition:+ background-color 120ms ease,+ color 120ms ease,+ transform 120ms ease;+}++.model-setup-guide__skip:hover,+.model-setup-guide__skip:focus-visible {+ background: var(--color-sidebar-nav-hover);+ color: var(--color-text-primary);+}++.model-setup-guide__skip:active {+ transform: translateY(1px);+}++@keyframes modelSetupGuideEnter {+ from {+ opacity: 0;+ transform: translateY(6px) scale(0.985);+ }+ to {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+}++.model-setup-guide__content {+ display: flex;+ align-items: flex-start;+ gap: 14px;+}++.model-setup-guide__avatar {+ width: 52px;+ height: 52px;+ flex: 0 0 52px;+ overflow: hidden;+ border-radius: 14px;+}++.model-setup-guide__copy {+ min-width: 0;+ flex: 1;+}++.model-setup-guide__title {+ margin: 2px 0 0;+ color: var(--color-text-strong);+ font-size: 17px;+ font-weight: 650;+ line-height: 1.4;+}++.model-setup-guide__callout--manual .model-setup-guide__title {+ padding-right: 48px;+}++.model-setup-guide__description {+ max-width: 34ch;+ margin: 7px 0 0;+ color: var(--color-text-secondary);+ font-size: 13px;+ line-height: 1.6;+}++.model-setup-guide__footer {+ display: flex;+ min-height: 30px;+ align-items: flex-end;+ justify-content: space-between;+ gap: 16px;+ margin-top: 18px;+ padding-top: 14px;+ border-top: 1px solid var(--color-border-default);+}++.model-setup-guide__hint {+ margin: 0;+ color: var(--color-text-primary);+ font-size: 12px;+ font-weight: 500;+}++.model-setup-guide__progress {+ color: var(--color-text-secondary);+ font-size: 11px;+ font-weight: 500;+ white-space: nowrap;+}++.model-setup-guide__actions {+ display: flex;+ align-items: center;+ gap: 16px;+}++.model-setup-guide__text-button {+ appearance: none;+ padding: 2px 0;+ border: 0;+ outline: none;+ background: transparent;+ box-shadow: none;+ color: var(--color-text-secondary);+ font-size: 12px;+ font-weight: 500;+ line-height: 1.5;+ text-decoration: none;+ cursor: pointer;+}++.model-setup-guide__text-button:hover {+ color: var(--color-text-primary);+ text-decoration: none;+}++.model-setup-guide__text-button:focus-visible {+ outline: none;+ box-shadow: none;+ color: var(--color-text-primary);+ text-decoration: none;+}++.model-setup-guide__actions .model-setup-guide__text-button--primary,+.model-setup-guide__actions .model-setup-guide__text-button--primary:hover,+.model-setup-guide__actions .model-setup-guide__text-button--primary:focus,+.model-setup-guide__actions .model-setup-guide__text-button--primary:focus-visible,+.model-setup-guide__actions .model-setup-guide__text-button--primary:active {+ color: var(--color-action-primary);+ font-weight: 600;+}++@media (prefers-reduced-motion: reduce) {+ .model-setup-guide__spotlight,+ .model-setup-guide__callout {+ animation: none;+ transition: none;+ }+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/modelSetupGuide/ModelSetupGuide.tsx b/jiuwenswarm/channels/web/frontend/src/features/modelSetupGuide/ModelSetupGuide.tsxnew file mode 100644index 0000000000..ee8c0c931b--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/modelSetupGuide/ModelSetupGuide.tsx@@ -0,0 +1,277 @@+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { useTranslation } from 'react-i18next';+import { TeamMemberAvatar } from '../../components/TeamMemberAvatar';+import './ModelSetupGuide.css';++export type ModelSetupGuideStep = 1 | 2;++interface ModelSetupGuideProps {+ step: ModelSetupGuideStep;+ manual: boolean;+ onAcknowledge: () => void;+ onSkip: () => void;+}++interface SpotlightRect {+ top: number;+ right: number;+ bottom: number;+ left: number;+ width: number;+ height: number;+}++const TARGET_SELECTORS: Record<ModelSetupGuideStep, string> = {+ 1: '[data-model-setup-guide-target="more"]',+ 2: '#config-group-model_default',+};++function toSpotlightRect(target: Element): SpotlightRect {+ const rect = target.getBoundingClientRect();+ const padding = 6;+ const left = Math.min(window.innerWidth, Math.max(0, rect.left - padding));+ const top = Math.min(window.innerHeight, Math.max(0, rect.top - padding));+ const right = Math.max(left, Math.min(window.innerWidth, rect.right + padding));+ const bottom = Math.max(top, Math.min(window.innerHeight, rect.bottom + padding));+ return {+ top,+ right,+ bottom,+ left,+ width: right - left,+ height: bottom - top,+ };+}++function rectsEqual(left: SpotlightRect | null, right: SpotlightRect): boolean {+ return Boolean(left && left.top === right.top && left.right === right.right && left.bottom === right.bottom && left.left === right.left);+}++function findVerticalScrollContainer(target: Element): HTMLElement | null {+ let ancestor = target.parentElement;++ while (ancestor) {+ const overflowY = window.getComputedStyle(ancestor).overflowY;+ const isScrollable = (overflowY === 'auto' || overflowY === 'scroll')+ && ancestor.scrollHeight > ancestor.clientHeight;+ if (isScrollable) {+ return ancestor;+ }+ ancestor = ancestor.parentElement;+ }++ return null;+}++export function ModelSetupGuide({+ step,+ manual,+ onAcknowledge,+ onSkip,+}: ModelSetupGuideProps) {+ const { t } = useTranslation();+ const [spotlight, setSpotlight] = useState<SpotlightRect | null>(null);+ const acknowledgementRef = useRef<HTMLButtonElement>(null);+ const hasSpotlightTarget = spotlight !== null;++ useLayoutEffect(() => {+ const selector = TARGET_SELECTORS[step];+ let resizeObserver: ResizeObserver | null = null;+ let observedTarget: Element | null = null;++ const updateSpotlight = () => {+ const target = document.querySelector(selector);+ if (!target) {+ setSpotlight(null);+ return;+ }++ const nextRect = toSpotlightRect(target);+ setSpotlight(current => (rectsEqual(current, nextRect) ? current : nextRect));++ if (target !== observedTarget) {+ resizeObserver?.disconnect();+ observedTarget = target;+ resizeObserver = new ResizeObserver(updateSpotlight);+ resizeObserver.observe(target);+ }+ };++ const mutationObserver = new MutationObserver(updateSpotlight);+ mutationObserver.observe(document.body, { childList: true, subtree: true });+ window.addEventListener('resize', updateSpotlight);+ window.addEventListener('scroll', updateSpotlight, true);+ updateSpotlight();++ return () => {+ resizeObserver?.disconnect();+ mutationObserver.disconnect();+ window.removeEventListener('resize', updateSpotlight);+ window.removeEventListener('scroll', updateSpotlight, true);+ };+ }, [step]);++ useLayoutEffect(() => {+ if (step !== 2 || !hasSpotlightTarget) return;++ const target = document.querySelector(TARGET_SELECTORS[step]);+ if (!target) return;++ const scrollContainer = findVerticalScrollContainer(target);+ if (!scrollContainer) return;++ const previousOverflowY = scrollContainer.style.overflowY;+ scrollContainer.style.overflowY = 'hidden';++ return () => {+ scrollContainer.style.overflowY = previousOverflowY;+ };+ }, [hasSpotlightTarget, step]);++ useEffect(() => {+ const target = document.querySelector<HTMLElement>(TARGET_SELECTORS[step]);+ if (!target) return;++ const descriptionId = `model-setup-guide-description-${step}`;+ const previousDescription = target.getAttribute('aria-describedby');+ target.setAttribute('aria-describedby', descriptionId);++ if (step === 1) {+ target.focus();+ } else {+ acknowledgementRef.current?.focus();+ }++ return () => {+ if (previousDescription) {+ target.setAttribute('aria-describedby', previousDescription);+ } else {+ target.removeAttribute('aria-describedby');+ }+ };+ }, [hasSpotlightTarget, step]);++ const calloutStyle = useMemo(() => {+ if (!spotlight) return undefined;++ const gap = 16;+ const width = Math.min(344, window.innerWidth - 32);+ const estimatedHeight = step === 1 ? 164 : 174;+ const roomOnRight = window.innerWidth - spotlight.right;+ const roomBelow = window.innerHeight - spotlight.bottom;++ if (roomOnRight >= width + gap) {+ return {+ left: spotlight.right + gap,+ top: Math.min(Math.max(16, spotlight.top), window.innerHeight - estimatedHeight - 16),+ width,+ };+ }++ if (roomBelow >= estimatedHeight + gap) {+ return {+ left: Math.min(Math.max(16, spotlight.left), window.innerWidth - width - 16),+ top: spotlight.bottom + gap,+ width,+ };+ }++ return {+ left: Math.min(Math.max(16, spotlight.right - width), window.innerWidth - width - 16),+ top: Math.max(16, spotlight.top - estimatedHeight - gap),+ width,+ };+ }, [spotlight, step]);++ if (!spotlight || !calloutStyle) return null;++ return createPortal(+ <div className="model-setup-guide" aria-live="polite">+ <div+ className="model-setup-guide__mask"+ style={{ top: 0, right: 0, height: spotlight.top, left: 0 }}+ />+ <div+ className="model-setup-guide__mask"+ style={{+ top: spotlight.top,+ left: 0,+ width: spotlight.left,+ height: spotlight.height,+ }}+ />+ <div+ className="model-setup-guide__mask"+ style={{+ top: spotlight.top,+ right: 0,+ left: spotlight.right,+ height: spotlight.height,+ }}+ />+ <div+ className="model-setup-guide__mask"+ style={{ top: spotlight.bottom, right: 0, bottom: 0, left: 0 }}+ />+ <div+ className="model-setup-guide__spotlight"+ style={{+ top: spotlight.top,+ left: spotlight.left,+ width: spotlight.width,+ height: spotlight.height,+ }}+ aria-hidden+ />+ <section+ key={step}+ className={`model-setup-guide__callout${manual ? ' model-setup-guide__callout--manual' : ''}`}+ style={calloutStyle}+ aria-labelledby={`model-setup-guide-title-${step}`}+ aria-describedby={`model-setup-guide-description-${step}`}+ >+ {manual ? (+ <button+ type="button"+ className="model-setup-guide__skip"+ onClick={onSkip}+ aria-label={t('modelSetupGuide.skip')}+ title={t('modelSetupGuide.skip')}+ >+ {t('modelSetupGuide.skip')}+ </button>+ ) : null}+ <div className="model-setup-guide__content">+ <TeamMemberAvatar member="team_leader" className="model-setup-guide__avatar" alt="" />+ <div className="model-setup-guide__copy">+ <h2 id={`model-setup-guide-title-${step}`} className="model-setup-guide__title">+ {t(`modelSetupGuide.steps.${step}.title`)}+ </h2>+ <p id={`model-setup-guide-description-${step}`} className="model-setup-guide__description">+ {t(`modelSetupGuide.steps.${step}.description`)}+ </p>+ </div>+ </div>+ <footer className="model-setup-guide__footer">+ {step === 2 ? (+ <div className="model-setup-guide__actions">+ <button+ ref={acknowledgementRef}+ type="button"+ className="model-setup-guide__text-button model-setup-guide__text-button--primary"+ onClick={onAcknowledge}+ >+ {t('modelSetupGuide.acknowledge')}+ </button>+ </div>+ ) : (+ <p className="model-setup-guide__hint">{t('modelSetupGuide.clickMore')}</p>+ )}+ <span className="model-setup-guide__progress">{t('modelSetupGuide.progress', { current: step, total: 2 })}</span>+ </footer>+ </section>+ </div>,+ document.body+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/modelSetupGuide/modelSetupGuideState.ts b/jiuwenswarm/channels/web/frontend/src/features/modelSetupGuide/modelSetupGuideState.tsnew file mode 100644index 0000000000..07a1f7745f--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/modelSetupGuide/modelSetupGuideState.ts@@ -0,0 +1,17 @@+const ENABLED_VALUES = new Set(['true', '1', 'yes', 'on']);+const DISABLED_VALUES = new Set(['false', '0', 'no', 'off']);++/**+ * Missing configuration is enabled by default so existing installations receive+ * the setup guide once after upgrading.+ */+export function isSetupGuideEnabled(value: unknown): boolean {+ if (typeof value === 'boolean') return value;+ if (typeof value === 'number') return value !== 0;+ if (typeof value !== 'string') return true;++ const normalized = value.trim().toLowerCase();+ if (ENABLED_VALUES.has(normalized)) return true;+ if (DISABLED_VALUES.has(normalized)) return false;+ return true;+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsx b/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsxindex 4676289dc1..5e75db64fd 100644--- a/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsx@@ -15,6 +15,7 @@ import { parseHistoryJsonFileToPreviewMessages } from './historyRestore';import { parseTeamHistoryPanelRecords } from './teamHistoryPanelRestore';import { isA2UIClientEventContent } from './a2ui/a2uiContent';import { getSvgNaturalHeight, getSvgNaturalWidth } from '../utils/svgDimensions';+import { generateUuidV4 } from '../utils/uuid';import './shareImageExport.css';export interface ShareImageMetadata {@@ -481,25 +482,6 @@ function crc32(bytes: Uint8Array): number {return (crc ^ 0xffffffff) >>> 0;}-/** Generate a v4 UUID, falling back when crypto.randomUUID is unavailable. */-function generateUuid(): string {- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {- return crypto.randomUUID();- }- const random = (typeof crypto !== 'undefined' && crypto.getRandomValues)- ? (n: number) => crypto.getRandomValues(new Uint8Array(n))- : (n: number) => {- const out = new Uint8Array(n);- for (let i = 0; i < n; i++) out[i] = Math.floor(Math.random() * 256);- return out;- };- const b = random(16);- b[6] = (b[6] & 0x0f) | 0x40;- b[8] = (b[8] & 0x3f) | 0x80;- const hex = Array.from(b, (x) => x.toString(16).padStart(2, '0'));- return `${hex.slice(0, 4).join('')}-${hex.slice(4, 6).join('')}-${hex.slice(6, 8).join('')}-${hex.slice(8, 10).join('')}-${hex.slice(10, 16).join('')}`;-}-const EMPTY_MD5 = '';/**@@ -515,7 +497,7 @@ const EMPTY_MD5 = '';*/function buildAigcLabel(): { xmp: string } {const producer = 'JiuwenSwarm';- const produceId = generateUuid();+ const produceId = generateUuidV4();const payload = {Label: '1',ContentProducer: producer,diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex c512124024..c5e7bd9742 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -707,6 +707,23 @@"addApp": "Add app"}},+ "modelSetupGuide": {+ "progress": "Step {{current}} of {{total}}",+ "clickMore": "Select More to continue",+ "acknowledge": "Got it",+ "skip": "Skip",+ "open": "Setup guide",+ "steps": {+ "1": {+ "title": "Configure your first model",+ "description": "Model settings are under More, in Configuration."+ },+ "2": {+ "title": "Complete model configuration",+ "description": "Enter the model name, API URL, API key, and model provider in Default model, then select Save."+ }+ }+ },"config": {"title": "Configuration","subtitle": "Edit by category using the tabs above. The backend will restart after saving to load changes.",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex baabf23f13..205fac753c 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -707,6 +707,23 @@"addApp": "添加应用"}},+ "modelSetupGuide": {+ "progress": "第 {{current}} 步,共 {{total}} 步",+ "clickMore": "点击“更多”继续",+ "acknowledge": "我知道了",+ "skip": "跳过",+ "open": "配置指引",+ "steps": {+ "1": {+ "title": "配置你的首个模型",+ "description": "模型配置位于“更多”中的“配置信息”。"+ },+ "2": {+ "title": "完成模型配置",+ "description": "在默认模型区域填写模型名称、API 地址、API Key 和模型提供商,然后点击保存。"+ }+ }+ },"config": {"title": "配置信息","subtitle": "按顶部标签分类编辑;保存后后端将自动重启以加载最新配置。",diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx b/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsxindex e766a524ae..0388fa91e8 100644--- a/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx@@ -1088,7 +1088,6 @@ export function ConversationSidebar({onClick={() => setWorkModeMenuOpen((open) => !open)}aria-haspopup="menu"aria-expanded={workModeMenuOpen}- disabled={Boolean(activeSessionId && runtimes[activeSessionId]?.isProcessing)}><span>{workMode === 'code' ? t('codeMode.code') : t('codeMode.work')}</span><ChevronDown size={15} className={workModeMenuOpen ? 'is-open' : ''} />diff --git a/jiuwenswarm/channels/web/frontend/src/utils/uuid.ts b/jiuwenswarm/channels/web/frontend/src/utils/uuid.tsnew file mode 100644index 0000000000..6537e35a23--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/utils/uuid.ts@@ -0,0 +1,22 @@+/**+ * Generate an RFC 4122 version 4 UUID.+ *+ * `Crypto.randomUUID()` is restricted to secure contexts, while+ * `Crypto.getRandomValues()` remains available when the web UI is served from a+ * remote HTTP origin.+ */+export function generateUuidV4(cryptoApi: Crypto = globalThis.crypto): string {+ if (typeof cryptoApi?.randomUUID === 'function') {+ return cryptoApi.randomUUID();+ }+ if (typeof cryptoApi?.getRandomValues !== 'function') {+ throw new Error('Cryptographically secure random number generation is unavailable.');+ }++ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));+ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;++ const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));+ return `${hex.slice(0, 4).join('')}-${hex.slice(4, 6).join('')}-${hex.slice(6, 8).join('')}-${hex.slice(8, 10).join('')}-${hex.slice(10).join('')}`;+}diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex 1511cdb038..8253cddca1 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -659,6 +659,19 @@ def update_auto_recap_enabled_in_config(value: bool) -> None:dump_yaml_round_trip(CONFIG_YAML_PATH, data)+def update_setup_guide_enabled_in_config(value: bool) -> None:+ """原子更新 setup_guide.enabled(Web 首次配置引导开关)。"""+ def mutator(data: dict[str, Any]) -> dict[str, Any]:+ section = data.get("setup_guide")+ if not isinstance(section, dict):+ section = {}+ data["setup_guide"] = section+ section["enabled"] = value+ return data++ update_config(mutator)++def update_proactive_recommendation_in_config(updates: dict[str, Any]) -> None:"""更新 proactive_recommendation 配置段并写回。"""data = load_yaml_round_trip(CONFIG_YAML_PATH)diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 99876b6492..145b9b6be6 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -61,6 +61,7 @@ from jiuwenswarm.common.config import (update_skill_retrieval_in_config,update_symphony_in_config,update_permissions_enabled_in_config,+ update_setup_guide_enabled_in_config,update_memory_forbidden_enabled_in_config,update_memory_forbidden_description_in_config,update_swarmflow_enabled_in_config,@@ -169,7 +170,7 @@ class _ConfigChangeSet:scopes.add("proactive")elif key_text.startswith("symphony") or key_text.startswith("skill_retrieval"):scopes.add("agent_runtime")- elif key_text.startswith("a2ui_"):+ elif key_text.startswith("a2ui_") or key_text == "setup_guide_enabled":scopes.add("web_ui")else:scopes.add("agent_runtime")@@ -800,6 +801,7 @@ _CONFIG_YAML_KEYS = frozenset({"proactive_recommendation_max_recommend_per_day","proactive_recommendation_max_rounds_per_tick","swarmflow_enabled",+ "setup_guide_enabled",})# 微信通道数值参数的取值范围:(下限, 上限, 是否必须为整数)。均为秒,必须为有限正数。@@ -1585,6 +1587,10 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:# 合并 config.yaml 中的配置项try:raw = get_config_raw()+ setup_guide_cfg = raw.get("setup_guide") or {}+ payload["setup_guide_enabled"] = (+ "true" if setup_guide_cfg.get("enabled", True) else "false"+ )for key, val in payload.items():from jiuwenswarm.extensions.registry import ExtensionRegistryif (("api_key" in key.lower() or "token" in key.lower())@@ -1639,6 +1645,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:payload.setdefault("kv_cache_release_enabled", "false")payload.setdefault("kv_cache_affinity_enabled", "false")payload.setdefault("permissions_enabled", "false")+ payload.setdefault("setup_guide_enabled", "true")payload.setdefault("skill_create", "false")payload.setdefault("evolution_auto_scan", "false")payload.setdefault("memory_forbidden_enabled", "false")@@ -1788,6 +1795,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:update_kv_cache_affinity_enabled_in_config(parsed)elif param_key == "permissions_enabled":update_permissions_enabled_in_config(parsed)+ elif param_key == "setup_guide_enabled":+ update_setup_guide_enabled_in_config(parsed)elif param_key == "memory_forbidden_enabled":update_memory_forbidden_enabled_in_config(parsed)elif param_key == "memory_forbidden_description":diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 47d97f43c7..50e93a23a6 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -1,6 +1,10 @@# 前端显示语言:zh(中文)/ en(英文),与 Web 界面语言切换同步preferred_language: zh+# Web 首次模型配置引导;用户确认完成后会自动关闭,可通过侧栏问号再次打开+setup_guide:+ enabled: true+# auto-recap:用户空闲5分钟后自动生成会话摘要(TUI 端)auto_recap:enabled: truediff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.pyindex eed32ed1fe..48a5943a34 100644--- a/tests/unit_tests/test_app_web_handlers.py+++ b/tests/unit_tests/test_app_web_handlers.py@@ -464,6 +464,83 @@ async def test_config_set_reports_saved_when_hot_reload_callback_fails(monkeypat]+async def test_config_set_persists_setup_guide_without_runtime_reload(monkeypatch):+ channel = FakeWebChannel()+ persisted: list[bool] = []+ reload_options_seen: list[dict] = []++ monkeypatch.setattr(+ app_web_handlers,+ "get_config_raw",+ lambda: {"setup_guide": {"enabled": True}},+ )+ monkeypatch.setattr(+ app_web_handlers,+ "get_config",+ lambda: {"setup_guide": {"enabled": False}},+ )+ monkeypatch.setattr(+ app_web_handlers,+ "update_setup_guide_enabled_in_config",+ lambda enabled: persisted.append(enabled),+ )++ async def on_config_saved(updated_keys, *, env_updates, config_payload, reload_options):+ del updated_keys, env_updates, config_payload+ reload_options_seen.append(dict(reload_options))+ return True++ _register_web_handlers(+ WebHandlersBindParams(+ channel=channel,+ on_config_saved=on_config_saved,+ )+ )++ await channel.methods["config.set"](+ object(),+ "req-setup-guide",+ {"setup_guide_enabled": "false"},+ "sess-setup-guide",+ )++ assert persisted == [False]+ assert reload_options_seen == [{+ "target_channel_id": "web",+ "reload_scopes": ["web_ui"],+ }]+ assert channel.responses[-1]["payload"] == {+ "updated": ["setup_guide_enabled"],+ "applied_without_restart": True,+ }+++ ("raw_config", "expected"),+ [+ ({}, "true"),+ ({"setup_guide": {"enabled": False}}, "false"),+ ],+)+async def test_config_get_returns_setup_guide_switch(monkeypatch, raw_config, expected):+ channel = FakeWebChannel()+ monkeypatch.setattr(app_web_handlers, "get_config_raw", lambda: raw_config)+ monkeypatch.setattr(app_web_handlers, "get_config", lambda: raw_config)+ _register_web_handlers(WebHandlersBindParams(channel=channel))++ await channel.methods["config.get"](+ object(),+ "req-get-setup-guide",+ {},+ "sess-get-setup-guide",+ )++ assert channel.responses[-1]["ok"] is True+ assert channel.responses[-1]["payload"]["setup_guide_enabled"] == expected++@pytest.mark.asyncioasync def test_models_replace_all_applies_scoped_reload_before_responding(monkeypatch):channel = FakeWebChannel()diff --git a/tests/unit_tests/test_config.py b/tests/unit_tests/test_config.pyindex ae82d7cee3..e434275908 100644--- a/tests/unit_tests/test_config.py+++ b/tests/unit_tests/test_config.py@@ -19,6 +19,7 @@ from jiuwenswarm.common.config import (replace_teams_in_config,resolve_env_vars,update_skill_retrieval_in_config,+ update_setup_guide_enabled_in_config,update_xiaoyi_runtime_in_config,)@@ -118,6 +119,18 @@ class TestResolveEnvVars:class TestConfigFunctions:"""Test config module functions."""+ @staticmethod+ def test_update_setup_guide_enabled_in_config(+ monkeypatch: pytest.MonkeyPatch,+ temp_config_file: Path,+ ):+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)++ update_setup_guide_enabled_in_config(False)++ raw = yaml.safe_load(temp_config_file.read_text(encoding="utf-8"))+ assert raw["setup_guide"] == {"enabled": False}+@pytest.mark.parametrize(("config", "expected"),[