refactor(web/default): adopt drill-in sidebar pattern for System Settings

Replace the ad-hoc "workspace" abstraction with a focused, URL-driven
"sidebar view" registry that implements the modern Vercel / Cloudflare
drill-in pattern: clicking a top-level entry (e.g. System Settings)
swaps the sidebar to a contextual workspace, with a `← Back to
Dashboard` affordance, instead of stacking sub-navigation in the root.

Architecture
------------
- types.ts
    + SidebarView           — declarative nested view config
                              (id, pathPattern, parent, getNavGroups)
    + SidebarViewParent     — back-navigation descriptor
    + ResolvedSidebarView   — { key, view, navGroups } returned by hook
    + SidebarData           — slimmed to { navGroups } only
    - Workspace             — removed (logo/plan never rendered)

- lib/sidebar-view-registry.ts (new, replaces workspace-registry.ts)
    + SIDEBAR_VIEWS array — single source of truth for nested views
    + resolveSidebarView(pathname)
    + getNavGroupsForPath(pathname, t) — back-compat helper for the
      command palette

- config/system-settings.config.ts
    Refactored to export a single SYSTEM_SETTINGS_VIEW (SidebarView)
    with parent `/dashboard/overview` + label `Back to Dashboard`.

- components/sidebar-view-header.tsx (new)
    Renders only the back affordance (chevron + label). Uses the
    default SidebarMenuButton size so its typography matches the
    nav items below; collapses gracefully into icon mode via the
    existing tooltip behavior. The redundant "title + icon" row was
    removed — workspace context is already carried by the nav groups.

- hooks/use-sidebar-view.ts (new)
    Encapsulates view resolution and root-nav filtering:
      · matched view  → returns its nav groups verbatim (route-level
                        beforeLoad guards already enforce access);
      · no match      → returns root nav groups, narrowed by user
                        role (admin gate) and useSidebarConfig
                        (admin × user sidebar_modules overlay).

- components/app-sidebar.tsx
    Now a thin presentation layer: reads { key, view, navGroups }
    from useSidebarView() and orchestrates the view transition via
    AnimatePresence + MOTION_VARIANTS.sidebarSlide (respects
    prefers-reduced-motion). No logic, no role checks, no path
    matching — those live in the hook.

- components/command-menu.tsx
    Switched to the new getNavGroupsForPath() API; behavior preserved.

Cleanup
-------
- Deleted layout/context/workspace-context.tsx (zero consumers).
- Deleted layout/lib/workspace-registry.ts and its
  workspace-registry.example.ts companion (over-abstracted: name/id
  metadata, isInWorkspace / getAllWorkspaces / WORKSPACE_IDS were
  registered but never read).
- Removed `workspaces` field from useSidebarData (never consumed
  after the top-switcher was dropped).
- Dropped WorkspaceProvider from authenticated-layout.tsx.
- Trimmed dead `Manage and configure` translation key from all six
  locale files and from static-keys.ts.

i18n
----
Added the `Back to Dashboard` key to en, zh, fr, ja, ru, vi, and
registered it in static-keys.ts under "Sidebar views".

Verification
------------
- bun run typecheck: passes
- Lint: no new warnings/errors on the touched files
- Adding a new drill-in workspace now only requires registering a
  SidebarView in SIDEBAR_VIEWS — no changes to AppSidebar required.
This commit is contained in:
t0ng7u
2026-05-24 22:09:05 +08:00
parent 49bc3a1175
commit 92a0959448
46 changed files with 515 additions and 591 deletions
+13 -12
View File
@@ -35,18 +35,19 @@ export function SignIn() {
<h2 className='text-center text-2xl font-semibold tracking-tight sm:text-left'>
{t('Sign in')}
</h2>
{!status?.self_use_mode_enabled && status?.register_enabled !== false && (
<p className='text-muted-foreground text-left text-sm sm:text-base'>
{t("Don't have an account?")}{' '}
<Link
to='/sign-up'
className='hover:text-primary font-medium underline underline-offset-4'
>
{t('Sign up')}
</Link>
.
</p>
)}
{!status?.self_use_mode_enabled &&
status?.register_enabled !== false && (
<p className='text-muted-foreground text-left text-sm sm:text-base'>
{t("Don't have an account?")}{' '}
<Link
to='/sign-up'
className='hover:text-primary font-medium underline underline-offset-4'
>
{t('Sign up')}
</Link>
.
</p>
)}
</div>
<UserAuthForm redirectTo={redirect} />
@@ -319,7 +319,6 @@ export function SignUpForm({
)}
</Button>
</div>
</>
)}
@@ -36,7 +36,6 @@ import {
} from '@/lib/format'
import { getLobeIcon } from '@/lib/lobe-icon'
import { cn, truncateText } from '@/lib/utils'
import { TruncatedText } from '@/components/truncated-text'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
@@ -53,6 +52,7 @@ import {
dotColorMap,
textColorMap,
} from '@/components/status-badge'
import { TruncatedText } from '@/components/truncated-text'
import { getCodexUsage } from '../api'
import { CHANNEL_STATUS_CONFIG, MODEL_FETCHABLE_TYPES } from '../constants'
import {
@@ -89,9 +89,7 @@ export function FetchModelsDialog({
// Parse existing models
const existingModels = useMemo(
() =>
existingModelsOverride ??
parseModelsString(currentRow?.models || ''),
() => existingModelsOverride ?? parseModelsString(currentRow?.models || ''),
[existingModelsOverride, currentRow?.models]
)
@@ -369,12 +367,14 @@ export function FetchModelsDialog({
<DialogHeader>
<DialogTitle>{t('Fetch Models')}</DialogTitle>
<DialogDescription>
{currentRow
? <>
{t('Fetch available models for:')}{' '}
<strong>{currentRow.name}</strong>
</>
: t('Fetch available models from upstream')}
{currentRow ? (
<>
{t('Fetch available models for:')}{' '}
<strong>{currentRow.name}</strong>
</>
) : (
t('Fetch available models from upstream')
)}
</DialogDescription>
</DialogHeader>
@@ -3381,7 +3381,9 @@ export function ChannelMutateDrawer({
redirectSourceModels={redirectModelKeyList}
customFetcher={!isEditing ? createModeFetcher : undefined}
existingModelsOverride={
!isEditing ? parseModelsString(form.getValues('models') || '') : undefined
!isEditing
? parseModelsString(form.getValues('models') || '')
: undefined
}
/>
@@ -82,9 +82,17 @@ export function PerformanceHealthPanel() {
const summary = useMemo(() => {
return {
avgLatencyMs: Math.round(
simpleAverage(models, 'avg_latency_ms', (v) => Number.isFinite(v) && v > 0)
simpleAverage(
models,
'avg_latency_ms',
(v) => Number.isFinite(v) && v > 0
)
),
avgTps: simpleAverage(
models,
'avg_tps',
(v) => Number.isFinite(v) && v > 0
),
avgTps: simpleAverage(models, 'avg_tps', (v) => Number.isFinite(v) && v > 0),
successRate: simpleAverage(models, 'success_rate', Number.isFinite),
}
}, [models])
@@ -96,7 +104,10 @@ export function PerformanceHealthPanel() {
return (
<section className='bg-card h-full overflow-hidden rounded-2xl border shadow-xs'>
<div className='flex items-center gap-2 border-b px-4 py-3 sm:px-5'>
<HeartPulse className='text-muted-foreground/60 size-4 shrink-0' aria-hidden='true' />
<HeartPulse
className='text-muted-foreground/60 size-4 shrink-0'
aria-hidden='true'
/>
<h3 className='text-sm font-semibold'>{t('Performance health')}</h3>
<span className='text-muted-foreground ml-auto text-xs'>
{t('Performance metrics for the last 24 hours')}
@@ -132,38 +143,43 @@ export function PerformanceHealthPanel() {
<Skeleton key={i} className='h-5 w-full rounded' />
))}
</div>
) : hasData && (
<div>
<span className='text-muted-foreground mb-1 block text-[11px] font-medium'>
{t('Top models by traffic')}
</span>
<div className='grid grid-cols-1 gap-x-4 sm:grid-cols-2'>
{topModels.map((model) => (
<div
key={model.model_name}
className='flex items-center justify-between gap-2 rounded px-1.5 py-1'
>
<span className='min-w-0 flex-1 truncate font-mono text-[11px]'>
{model.model_name}
</span>
<span className='inline-flex shrink-0 items-center gap-1'>
<span
className={cn('size-1.5 rounded-full', rateDotClass(model.success_rate))}
aria-hidden='true'
/>
<span
className={cn(
'font-mono text-[11px] font-semibold tabular-nums',
rateTextClass(model.success_rate)
)}
>
{formatUptimePct(model.success_rate)}
) : (
hasData && (
<div>
<span className='text-muted-foreground mb-1 block text-[11px] font-medium'>
{t('Top models by traffic')}
</span>
<div className='grid grid-cols-1 gap-x-4 sm:grid-cols-2'>
{topModels.map((model) => (
<div
key={model.model_name}
className='flex items-center justify-between gap-2 rounded px-1.5 py-1'
>
<span className='min-w-0 flex-1 truncate font-mono text-[11px]'>
{model.model_name}
</span>
</span>
</div>
))}
<span className='inline-flex shrink-0 items-center gap-1'>
<span
className={cn(
'size-1.5 rounded-full',
rateDotClass(model.success_rate)
)}
aria-hidden='true'
/>
<span
className={cn(
'font-mono text-[11px] font-semibold tabular-nums',
rateTextClass(model.success_rate)
)}
>
{formatUptimePct(model.success_rate)}
</span>
</span>
</div>
))}
</div>
</div>
</div>
)
)}
</div>
</section>
@@ -19,12 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import { useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import {
ArrowRight,
Flame,
ShieldCheck,
TrendingDown,
} from 'lucide-react'
import { ArrowRight, Flame, ShieldCheck, TrendingDown } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { useAuthStore } from '@/stores/auth-store'
import { getCurrencyLabel, isCurrencyDisplayEnabled } from '@/lib/currency'
@@ -102,7 +97,10 @@ function getSummarySparkline(
return undefined
}
function getRunwayDays(remainQuota: number, recentUsage: number): number | null {
function getRunwayDays(
remainQuota: number,
recentUsage: number
): number | null {
if (remainQuota <= 0 || recentUsage <= 0) return null
const days = remainQuota / recentUsage
if (!Number.isFinite(days)) return null
@@ -111,10 +109,7 @@ function getRunwayDays(remainQuota: number, recentUsage: number): number | null
type HealthLevel = 'healthy' | 'caution' | 'critical'
function getHealthLevel(
remainQuota: number,
recentUsage: number
): HealthLevel {
function getHealthLevel(remainQuota: number, recentUsage: number): HealthLevel {
if (remainQuota <= 0) return 'critical'
const days = getRunwayDays(remainQuota, recentUsage)
if (days !== null && days < 3) return 'caution'
@@ -139,7 +134,6 @@ const HEALTH_CONFIG: Record<
},
}
export function SummaryCards() {
const { t } = useTranslation()
const user = useAuthStore((state) => state.auth.user)
@@ -341,10 +335,7 @@ export function SummaryCards() {
</div>
</div>
<Button
className='justify-between'
render={<Link to='/wallet' />}
>
<Button className='justify-between' render={<Link to='/wallet' />}>
<span>{t('Wallet')}</span>
<ArrowRight data-icon='inline-end' />
</Button>
@@ -96,8 +96,7 @@ function buildLineSparkline(values?: number[]) {
sanitized.length === 1
? width / 2
: (index / (sanitized.length - 1)) * width
const normalized =
range > 0 ? (value - min) / range : max > 0 ? 0.5 : 0
const normalized = range > 0 ? (value - min) / range : max > 0 ? 0.5 : 0
const y = height - padding - normalized * (height - padding * 2)
return { x, y }
+1 -1
View File
@@ -236,7 +236,7 @@ export function Dashboard() {
<div className='flex flex-wrap items-center justify-between gap-1.5 sm:gap-2'>
{showSectionTabs ? (
<Tabs value={activeSection} onValueChange={handleSectionChange}>
<TabsList className='group-data-horizontal/tabs:h-auto max-w-full flex-wrap justify-start'>
<TabsList className='max-w-full flex-wrap justify-start group-data-horizontal/tabs:h-auto'>
{visibleSections.map((section) => (
<TabsTrigger key={section} value={section}>
{t(SECTION_META[section].titleKey)}
+3 -1
View File
@@ -65,7 +65,9 @@ export function Hero(props: HeroProps) {
className='landing-animate-fade-up text-muted-foreground/80 mt-5 max-w-lg text-base leading-relaxed opacity-0 md:text-lg'
style={{ animationDelay: '80ms' }}
>
{t('Power AI applications, manage digital assets, connect the Future')}
{t(
'Power AI applications, manage digital assets, connect the Future'
)}
</p>
<div
className='landing-animate-fade-up mt-8 flex items-center gap-3 opacity-0'
@@ -168,7 +168,9 @@ export function ApiKeysMutateDrawer({
}
})
} else if (open && !isUpdate) {
form.reset(getApiKeyFormDefaultValues(defaultUseAutoGroup && backendHasAuto))
form.reset(
getApiKeyFormDefaultValues(defaultUseAutoGroup && backendHasAuto)
)
}
}, [open, isUpdate, currentRow, form, defaultUseAutoGroup, backendHasAuto])
@@ -177,7 +179,10 @@ export function ApiKeysMutateDrawer({
if (groups.length === 0) return
const currentGroup = form.getValues('group')
if (currentGroup && !groups.some((g) => g.value === currentGroup)) {
const fallback = groups.find((g) => g.value === 'default')?.value ?? groups[0]?.value ?? ''
const fallback =
groups.find((g) => g.value === 'default')?.value ??
groups[0]?.value ??
''
form.setValue('group', fallback)
if (currentGroup === 'auto') {
form.setValue('cross_group_retry', false)
+1 -3
View File
@@ -57,9 +57,7 @@ export function getApiKeyFormSchema(t: TFunction) {
})
}
export type ApiKeyFormValues = z.infer<
ReturnType<typeof getApiKeyFormSchema>
>
export type ApiKeyFormValues = z.infer<ReturnType<typeof getApiKeyFormSchema>>
// ============================================================================
// Form Defaults
+1 -1
View File
@@ -142,7 +142,7 @@ function ModelsContent() {
<SectionPageLayout.Content>
<div className='space-y-4'>
<Tabs value={activeSection} onValueChange={handleSectionChange}>
<TabsList className='group-data-horizontal/tabs:h-auto max-w-full flex-wrap justify-start'>
<TabsList className='max-w-full flex-wrap justify-start group-data-horizontal/tabs:h-auto'>
{MODELS_SECTION_IDS.map((section) => (
<TabsTrigger key={section} value={section}>
{t(SECTION_META[section].titleKey)}
@@ -69,7 +69,7 @@ export function ProfileSettingsCard({
icon={<Settings className='h-4 w-4' />}
>
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className='grid group-data-horizontal/tabs:h-10 w-full grid-cols-2 items-stretch gap-1 rounded-xl p-1'>
<TabsList className='grid w-full grid-cols-2 items-stretch gap-1 rounded-xl p-1 group-data-horizontal/tabs:h-10'>
<TabsTrigger
value='bindings'
className='h-full gap-2 rounded-lg px-3 py-0 leading-none'
@@ -673,9 +673,7 @@ export function SubscriptionsMutateDrawer({
disabled={items.length === 0}
>
<SelectTrigger className='w-full flex-1'>
<SelectValue
placeholder={t('Select a product')}
/>
<SelectValue placeholder={t('Select a product')} />
</SelectTrigger>
<SelectContent>
{items.map((item) => (
@@ -689,7 +687,9 @@ export function SubscriptionsMutateDrawer({
type='button'
variant='outline'
onClick={handleCreatePancakeProduct}
disabled={creatingPancakeProduct || !pancakeCreateReady}
disabled={
creatingPancakeProduct || !pancakeCreateReady
}
className='shrink-0'
>
{creatingPancakeProduct
@@ -75,9 +75,7 @@ const DEFAULT_NEW_PAIR_NAME = `${DEFAULT_NEW_STORE_NAME} + ${DEFAULT_NEW_PRODUCT
export function WaffoPancakeSettingsSection(props: Props) {
const { t } = useTranslation()
const [storeID, setStoreID] = React.useState(
props.provisionedStoreID ?? ''
)
const [storeID, setStoreID] = React.useState(props.provisionedStoreID ?? '')
const [productID, setProductID] = React.useState(
props.provisionedProductID ?? ''
)
@@ -283,9 +281,7 @@ export function WaffoPancakeSettingsSection(props: Props) {
// returning admins (saved merchant ID but empty key field) would send
// a mixed-state body that the backend rejects.
const readCreds = () => {
const formMerchant = (
form.getValues('WaffoPancakeMerchantID') || ''
).trim()
const formMerchant = (form.getValues('WaffoPancakeMerchantID') || '').trim()
const formKey = (form.getValues('WaffoPancakePrivateKey') || '').trim()
const saved = (props.defaultValues.WaffoPancakeMerchantID || '').trim()
const edited = formMerchant !== saved || formKey.length > 0
@@ -370,12 +366,8 @@ export function WaffoPancakeSettingsSection(props: Props) {
// Sends raw form values (not readCreds): SaveWaffoPancakeConfig already
// treats a blank PrivateKey as "keep existing", and MerchantID stays
// populated from props for returning admins.
const merchantID = (
form.getValues('WaffoPancakeMerchantID') || ''
).trim()
const privateKey = (
form.getValues('WaffoPancakePrivateKey') || ''
).trim()
const merchantID = (form.getValues('WaffoPancakeMerchantID') || '').trim()
const privateKey = (form.getValues('WaffoPancakePrivateKey') || '').trim()
if (!merchantID) {
toast.error(t('Merchant ID is required'))
return
@@ -441,9 +441,7 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
{sensitiveVisible ? log.username : '••••'}
</TooltipTrigger>
{sensitiveVisible && log.username.length > 12 && (
<TooltipContent side='top'>
{log.username}
</TooltipContent>
<TooltipContent side='top'>{log.username}</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
@@ -484,11 +482,7 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
<div className='flex max-w-[200px] flex-col gap-0.5'>
<TooltipProvider delay={300}>
<Tooltip>
<TooltipTrigger
render={
<div className='max-w-full' />
}
>
<TooltipTrigger render={<div className='max-w-full' />}>
<StatusBadge
label={displayName}
icon={KeyRound}
@@ -297,9 +297,7 @@ export function CommonLogsFilterBar<TData>(
<Input
placeholder={t('Upstream Request ID')}
value={filters.upstreamRequestId || ''}
onChange={(e) =>
handleChange('upstreamRequestId', e.target.value)
}
onChange={(e) => handleChange('upstreamRequestId', e.target.value)}
onKeyDown={handleKeyDown}
className={inputClass}
/>
@@ -986,35 +986,33 @@ export function DetailsDialog(props: DetailsDialogProps) {
)}
{/* Param override */}
{other?.po &&
Array.isArray(other.po) &&
other.po.length > 0 && (
<DetailSection
icon={<Settings2 className='size-3.5' aria-hidden='true' />}
label={`${t('Param Override')} (${other.po.length})`}
>
{other.po.filter(Boolean).map((line, idx) => {
const parsed = parseAuditLine(line)
if (!parsed) return null
return (
<div
key={idx}
className='bg-background/60 flex min-w-0 flex-col gap-1.5 rounded border p-2 sm:flex-row sm:items-start sm:gap-2'
>
<StatusBadge
variant='neutral'
label={getParamOverrideActionLabel(parsed.action, t)}
className='shrink-0 font-medium'
copyable={false}
/>
<span className='min-w-0 font-mono text-[11px] leading-relaxed break-all sm:break-words'>
{parsed.content}
</span>
</div>
)
})}
</DetailSection>
)}
{other?.po && Array.isArray(other.po) && other.po.length > 0 && (
<DetailSection
icon={<Settings2 className='size-3.5' aria-hidden='true' />}
label={`${t('Param Override')} (${other.po.length})`}
>
{other.po.filter(Boolean).map((line, idx) => {
const parsed = parseAuditLine(line)
if (!parsed) return null
return (
<div
key={idx}
className='bg-background/60 flex min-w-0 flex-col gap-1.5 rounded border p-2 sm:flex-row sm:items-start sm:gap-2'
>
<StatusBadge
variant='neutral'
label={getParamOverrideActionLabel(parsed.action, t)}
className='shrink-0 font-medium'
copyable={false}
/>
<span className='min-w-0 font-mono text-[11px] leading-relaxed break-all sm:break-words'>
{parsed.content}
</span>
</div>
)
})}
</DetailSection>
)}
{/* Content */}
{details && (
+1 -1
View File
@@ -127,7 +127,7 @@ function UsageLogsContent() {
<div className='space-y-4'>
{showTaskSwitcher && (
<Tabs value={activeCategory} onValueChange={handleSectionChange}>
<TabsList className='group-data-horizontal/tabs:h-auto max-w-full flex-wrap justify-start'>
<TabsList className='max-w-full flex-wrap justify-start group-data-horizontal/tabs:h-auto'>
{visibleSections.map((section) => (
<TabsTrigger key={section} value={section}>
{t(SECTION_META[section].titleKey)}
+1 -1
View File
@@ -17,9 +17,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type ReactNode } from 'react'
import i18next from 'i18next'
import { CreditCard, Landmark } from 'lucide-react'
import { SiAlipay, SiWechat, SiStripe } from 'react-icons/si'
import i18next from 'i18next'
import { PAYMENT_TYPES, PAYMENT_ICON_COLORS } from '../constants'
// ============================================================================