Merge pull request #1117 from kaitranntt/kai/feat/1115-session-affinity

feat: add local CLIProxy session affinity controls
This commit is contained in:
Kai (Tam Nhu) Tran authored and GitHub committed 2026-04-28 13:37:37 -04:00
commit a8e0d95bc8
21 files changed
+1231 -63

No files matched your search

@@ -1,8 +1,12 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { ArrowRightLeft, ChevronDown, ChevronUp, RefreshCw } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import type { CliproxyRoutingState, RoutingStrategy } from '@/lib/api-client';
import type {
CliproxyRoutingState,
RoutingStrategy,
CliproxySessionAffinityState,
} from '@/lib/api-client';
import { cn } from '@/lib/utils';
import { useTranslation } from 'react-i18next';
@@ -10,10 +14,12 @@ interface RoutingGuidanceCardProps {
className?: string;
compact?: boolean;
state?: CliproxyRoutingState;
sessionAffinityState?: CliproxySessionAffinityState;
isLoading: boolean;
isSaving: boolean;
error?: Error | null;
onApply: (strategy: RoutingStrategy) => void;
onApplyAffinity: (data: { enabled: boolean; ttl?: string }) => void;
}
const STRATEGY_COPY: Record<RoutingStrategy, { title: string; description: string }> = {
@@ -31,18 +37,82 @@ export function RoutingGuidanceCard({
className,
compact = false,
state,
sessionAffinityState,
isLoading,
isSaving,
error,
onApply,
onApplyAffinity,
}: RoutingGuidanceCardProps) {
const { t } = useTranslation();
const currentStrategy = state?.strategy ?? 'round-robin';
const currentAffinityEnabled = sessionAffinityState?.enabled ?? false;
const currentAffinityTtl = sessionAffinityState?.ttl ?? '1h';
const sessionAffinityManageable = sessionAffinityState?.manageable ?? true;
const [selected, setSelected] = useState<RoutingStrategy>(currentStrategy);
const [selectedAffinityEnabled, setSelectedAffinityEnabled] = useState(currentAffinityEnabled);
const [selectedAffinityTtl, setSelectedAffinityTtl] = useState(currentAffinityTtl);
const [detailsOpen, setDetailsOpen] = useState(false);
const sourceLabel = state?.source === 'live' ? 'Live CLIProxy' : 'Saved startup default';
const saveDisabled = isLoading || isSaving || !state || selected === currentStrategy;
const detailToggleLabel = detailsOpen ? 'Hide details' : 'Show details';
const affinityControlDisabled = isLoading || isSaving || !!error || !sessionAffinityManageable;
const affinityActionLabel = sessionAffinityManageable
? selectedAffinityEnabled
? t('routingGuidance.disableSessionAffinity')
: t('routingGuidance.enableSessionAffinity')
: t('routingGuidance.sessionAffinityUnavailable');
const pendingAffinityRef = useRef<{ enabled: boolean; ttl: string } | null>(null);
const suppressNextAffinityBlurRef = useRef(false);
useEffect(() => {
setSelected(currentStrategy);
}, [currentStrategy]);
useEffect(() => {
setSelectedAffinityEnabled(currentAffinityEnabled);
setSelectedAffinityTtl(currentAffinityTtl);
}, [currentAffinityEnabled, currentAffinityTtl]);
useEffect(() => {
if (isSaving || !pendingAffinityRef.current) {
return;
}
const pending = pendingAffinityRef.current;
const succeeded =
pending.enabled === currentAffinityEnabled && pending.ttl === currentAffinityTtl;
if (!succeeded) {
setSelectedAffinityEnabled(currentAffinityEnabled);
setSelectedAffinityTtl(currentAffinityTtl);
}
pendingAffinityRef.current = null;
}, [isSaving, currentAffinityEnabled, currentAffinityTtl]);
const handleAffinityToggle = () => {
if (!sessionAffinityManageable) return;
const nextEnabled = !selectedAffinityEnabled;
const nextTtl = selectedAffinityTtl.trim() || '1h';
pendingAffinityRef.current = { enabled: nextEnabled, ttl: nextTtl };
setSelectedAffinityEnabled(nextEnabled);
onApplyAffinity({ enabled: nextEnabled, ttl: nextTtl });
};
const handleAffinityTtlBlur = () => {
if (!sessionAffinityManageable || !!error) return;
if (suppressNextAffinityBlurRef.current) {
suppressNextAffinityBlurRef.current = false;
return;
}
const nextTtl = selectedAffinityTtl.trim() || '1h';
if (nextTtl === currentAffinityTtl) {
return;
}
pendingAffinityRef.current = { enabled: selectedAffinityEnabled, ttl: nextTtl };
onApplyAffinity({ enabled: selectedAffinityEnabled, ttl: nextTtl });
};
if (compact) {
const handleApply = (s: RoutingStrategy) => {
@@ -53,57 +123,107 @@ export function RoutingGuidanceCard({
};
return (
<div
className={cn(
'group/routing flex items-center justify-between mt-1 p-1 -mx-1 rounded-lg transition-colors hover:bg-primary/5',
className
)}
>
<div className="flex items-center gap-2 text-xs font-medium text-foreground">
<div className="relative flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-background border border-border/60 text-muted-foreground shadow-sm overflow-hidden transition-all duration-300 group-hover/routing:border-primary/40 group-hover/routing:text-primary group-hover/routing:shadow-[0_0_12px_rgba(59,130,246,0.15)] dark:group-hover/routing:shadow-[0_0_12px_rgba(59,130,246,0.1)]">
<div className="absolute inset-0 bg-primary/10 translate-y-full group-hover/routing:translate-y-0 transition-transform duration-300 ease-out" />
<ArrowRightLeft className="relative z-10 h-3.5 w-3.5 transition-transform duration-300 group-hover/routing:scale-110" />
<div className={cn('group/routing mt-1 space-y-2 -mx-1 rounded-lg p-1', className)}>
<div className="flex items-center justify-between rounded-lg transition-colors hover:bg-primary/5">
<div className="flex items-center gap-2 px-1 text-xs font-medium text-foreground">
<div className="relative flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-background border border-border/60 text-muted-foreground shadow-sm overflow-hidden transition-all duration-300 group-hover/routing:border-primary/40 group-hover/routing:text-primary group-hover/routing:shadow-[0_0_12px_rgba(59,130,246,0.15)] dark:group-hover/routing:shadow-[0_0_12px_rgba(59,130,246,0.1)]">
<div className="absolute inset-0 bg-primary/10 translate-y-full group-hover/routing:translate-y-0 transition-transform duration-300 ease-out" />
<ArrowRightLeft className="relative z-10 h-3.5 w-3.5 transition-transform duration-300 group-hover/routing:scale-110" />
</div>
<span className="tracking-tight transition-colors duration-300 group-hover/routing:text-primary group-hover/routing:font-semibold">
Routing
</span>
{isSaving && <RefreshCw className="ml-1 h-3 w-3 shrink-0 animate-spin text-primary" />}
</div>
<div className="relative grid grid-cols-2 p-0.5 gap-0.5 rounded-lg border border-border/60 bg-muted/30 shadow-[inset_0_1px_2px_rgba(0,0,0,0.05)] dark:shadow-[inset_0_1px_3px_rgba(0,0,0,0.2)] transition-colors duration-300 group-hover/routing:border-primary/20 group-hover/routing:bg-primary/5">
<div
className={cn(
'absolute inset-y-0.5 left-0.5 w-[calc(50%-0.1875rem)] rounded bg-background shadow-[0_1px_3px_rgba(0,0,0,0.1),0_1px_2px_rgba(0,0,0,0.06)] ring-1 ring-black/5 dark:ring-white/10 transition-all duration-300',
selected === 'fill-first' ? 'translate-x-[calc(100%+0.125rem)]' : 'translate-x-0',
'group-hover/routing:shadow-[0_0_8px_rgba(59,130,246,0.15)] dark:group-hover/routing:shadow-[0_0_8px_rgba(59,130,246,0.1)] group-hover/routing:ring-primary/30'
)}
style={{ transitionTimingFunction: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)' }}
/>
{(
Object.entries(STRATEGY_COPY) as Array<
[RoutingStrategy, { title: string; description: string }]
>
).map(([strategy, copy]) => {
const active = selected === strategy;
return (
<button
key={strategy}
type="button"
className={cn(
'relative z-10 flex items-center justify-center rounded px-2.5 py-0.5 text-[10px] font-medium whitespace-nowrap transition-colors duration-200',
active
? 'text-foreground group-hover/routing:text-primary'
: 'text-muted-foreground/70 hover:text-foreground/90 group-hover/routing:text-muted-foreground/90'
)}
onClick={() => handleApply(strategy)}
disabled={isLoading || isSaving || !!error}
title={copy.description}
>
{copy.title}
</button>
);
})}
</div>
<span className="tracking-tight transition-colors duration-300 group-hover/routing:text-primary group-hover/routing:font-semibold">
Routing
</span>
{isSaving && <RefreshCw className="ml-1 h-3 w-3 shrink-0 animate-spin text-primary" />}
</div>
<div className="relative grid grid-cols-2 p-0.5 gap-0.5 rounded-lg border border-border/60 bg-muted/30 shadow-[inset_0_1px_2px_rgba(0,0,0,0.05)] dark:shadow-[inset_0_1px_3px_rgba(0,0,0,0.2)] transition-colors duration-300 group-hover/routing:border-primary/20 group-hover/routing:bg-primary/5">
<div
className={cn(
'absolute inset-y-0.5 left-0.5 w-[calc(50%-0.1875rem)] rounded bg-background shadow-[0_1px_3px_rgba(0,0,0,0.1),0_1px_2px_rgba(0,0,0,0.06)] ring-1 ring-black/5 dark:ring-white/10 transition-all duration-300',
selected === 'fill-first' ? 'translate-x-[calc(100%+0.125rem)]' : 'translate-x-0',
'group-hover/routing:shadow-[0_0_8px_rgba(59,130,246,0.15)] dark:group-hover/routing:shadow-[0_0_8px_rgba(59,130,246,0.1)] group-hover/routing:ring-primary/30'
)}
style={{ transitionTimingFunction: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)' }}
/>
{(
Object.entries(STRATEGY_COPY) as Array<
[RoutingStrategy, { title: string; description: string }]
<div className="flex items-center justify-between gap-2 rounded-lg border border-border/60 bg-muted/20 px-2 py-1.5">
<div className="min-w-0">
<div className="text-[10px] font-medium text-foreground">
{t('routingGuidance.sessionAffinity')}
</div>
<div className="text-[10px] text-muted-foreground">
{sessionAffinityManageable
? t('routingGuidance.ttlBadge', { ttl: currentAffinityTtl })
: t('routingGuidance.localOnlySetting')}
</div>
</div>
<div className="flex items-center gap-1">
{sessionAffinityManageable ? (
<input
aria-label="Session affinity TTL"
className="h-6 w-14 rounded border border-border/70 bg-background px-2 text-[10px] text-foreground"
value={selectedAffinityTtl}
onChange={(event) => setSelectedAffinityTtl(event.target.value)}
onBlur={handleAffinityTtlBlur}
disabled={affinityControlDisabled}
/>
) : null}
<button
type="button"
aria-label={affinityActionLabel}
className={cn(
'rounded border px-2 py-1 text-[10px] font-medium transition-colors',
sessionAffinityManageable
? 'border-border/70 bg-background text-foreground hover:border-primary/40 hover:text-primary'
: 'border-border/60 bg-muted/40 text-muted-foreground'
)}
onMouseDown={() => {
suppressNextAffinityBlurRef.current = true;
}}
onClick={handleAffinityToggle}
disabled={affinityControlDisabled}
title={sessionAffinityState?.message}
>
).map(([strategy, copy]) => {
const active = selected === strategy;
return (
<button
key={strategy}
type="button"
className={cn(
'relative z-10 flex items-center justify-center rounded px-2.5 py-0.5 text-[10px] font-medium whitespace-nowrap transition-colors duration-200',
active
? 'text-foreground group-hover/routing:text-primary'
: 'text-muted-foreground/70 hover:text-foreground/90 group-hover/routing:text-muted-foreground/90'
)}
onClick={() => handleApply(strategy)}
disabled={isLoading || isSaving || !!error}
title={copy.description}
>
{copy.title}
</button>
);
})}
{sessionAffinityManageable
? selectedAffinityEnabled
? t('routingGuidance.sessionAffinityOn')
: t('routingGuidance.sessionAffinityOff')
: t('routingGuidance.sessionAffinityUnavailable')}
</button>
</div>
</div>
{sessionAffinityState?.message ? (
<div className="rounded-lg border border-border/60 bg-muted/20 px-2 py-1.5 text-[10px] text-muted-foreground">
{sessionAffinityState.message}
</div>
) : null}
</div>
);
}
@@ -181,6 +301,55 @@ export function RoutingGuidanceCard({
<span>{t('routingGuidance.fillFirst')}</span>
</div>
<div className="grid gap-3 rounded-lg border border-border/70 bg-muted/20 px-3 py-3 xl:col-span-2">
<div className="flex flex-wrap items-center gap-2">
<div className="text-sm font-medium">{t('routingGuidance.sessionAffinity')}</div>
<Badge variant="secondary">
{selectedAffinityEnabled
? t('routingGuidance.sessionAffinityOn')
: t('routingGuidance.sessionAffinityOff')}
</Badge>
{sessionAffinityState?.ttl ? (
<Badge variant="outline">
{t('routingGuidance.ttlBadge', { ttl: currentAffinityTtl })}
</Badge>
) : null}
{!sessionAffinityManageable ? (
<Badge variant="outline">{t('routingGuidance.localOnly')}</Badge>
) : null}
</div>
<p className="text-xs leading-5 text-muted-foreground">
{t('routingGuidance.sessionAffinityDescription')}
</p>
<div className="flex flex-wrap items-center gap-2">
<input
aria-label="Session affinity TTL"
className="h-9 w-24 rounded-md border border-border/70 bg-background px-3 text-sm text-foreground"
value={selectedAffinityTtl}
onChange={(event) => setSelectedAffinityTtl(event.target.value)}
onBlur={handleAffinityTtlBlur}
disabled={affinityControlDisabled}
/>
<Button
type="button"
variant="outline"
onMouseDown={() => {
suppressNextAffinityBlurRef.current = true;
}}
onClick={handleAffinityToggle}
disabled={affinityControlDisabled}
aria-label={affinityActionLabel}
>
{affinityActionLabel}
</Button>
</div>
{sessionAffinityState?.message ? (
<div className="rounded-lg border border-border/70 bg-background/70 px-3 py-2 text-xs text-muted-foreground">
{sessionAffinityState.message}
</div>
) : null}
</div>
{error ? (
<div className="rounded-lg border border-destructive/25 bg-destructive/5 px-3 py-2 text-sm xl:col-span-2">
{error.message}
@@ -210,6 +379,14 @@ export function RoutingGuidanceCard({
</div>
);
})}
<div className="space-y-1 md:col-span-2">
<div className="text-sm font-medium">
{t('routingGuidance.sessionRecognitionTitle')}
</div>
<p className="text-xs leading-5 text-muted-foreground">
{t('routingGuidance.sessionRecognitionDescription')}
</p>
</div>
</div>
) : null}
</div>
@@ -61,7 +61,9 @@ import {
useInstallVersion,
useRestartProxy,
useCliproxyRoutingStrategy,
useCliproxySessionAffinity,
useUpdateCliproxyRoutingStrategy,
useUpdateCliproxySessionAffinity,
} from '@/hooks/use-cliproxy';
import { useSyncStatus, useExecuteSync } from '@/hooks/use-cliproxy-sync';
import { cn } from '@/lib/utils';
@@ -159,6 +161,14 @@ export function ProxyStatusWidget() {
error: routingError,
} = useCliproxyRoutingStrategy();
const updateRouting = useUpdateCliproxyRoutingStrategy();
const {
data: sessionAffinityState,
isLoading: sessionAffinityLoading,
error: sessionAffinityError,
} = useCliproxySessionAffinity();
const updateSessionAffinity = useUpdateCliproxySessionAffinity();
const isSavingRoutingConfig = updateRouting.isPending || updateSessionAffinity.isPending;
const routingConfigError = routingError instanceof Error ? routingError : null;
const startProxy = useStartProxy();
const stopProxy = useStopProxy();
const restartProxy = useRestartProxy();
@@ -190,6 +200,19 @@ export function ProxyStatusWidget() {
// Determine if remote mode is enabled
const remoteConfig = cliproxyConfig?.remote;
const isRemoteMode = remoteConfig?.enabled && remoteConfig?.host;
const effectiveSessionAffinityState =
sessionAffinityState ??
(sessionAffinityError instanceof Error
? {
source: 'unsupported' as const,
target: (routingState?.target ?? (isRemoteMode ? 'remote' : 'local')) as
| 'local'
| 'remote',
reachable: false,
manageable: false,
message: sessionAffinityError.message,
}
: undefined);
const isRunning = status?.running ?? false;
const isActioning =
@@ -315,14 +338,16 @@ export function ProxyStatusWidget() {
</div>
<RoutingGuidanceCard
key={`remote:${routingState?.strategy ?? 'round-robin'}`}
key={`remote:${routingState?.strategy ?? 'round-robin'}:${effectiveSessionAffinityState?.enabled ?? 'na'}:${effectiveSessionAffinityState?.ttl ?? 'na'}:${effectiveSessionAffinityState?.manageable ?? 'na'}`}
compact
className="mt-3"
state={routingState}
isLoading={routingLoading}
isSaving={updateRouting.isPending}
error={routingError instanceof Error ? routingError : null}
sessionAffinityState={effectiveSessionAffinityState}
isLoading={routingLoading || sessionAffinityLoading}
isSaving={isSavingRoutingConfig}
error={routingConfigError}
onApply={(strategy) => updateRouting.mutate(strategy)}
onApplyAffinity={(data) => updateSessionAffinity.mutate(data)}
/>
</div>
);
@@ -471,14 +496,16 @@ export function ProxyStatusWidget() {
</div>
<RoutingGuidanceCard
key={`local:${routingState?.strategy ?? 'round-robin'}`}
key={`local:${routingState?.strategy ?? 'round-robin'}:${effectiveSessionAffinityState?.enabled ?? 'na'}:${effectiveSessionAffinityState?.ttl ?? 'na'}:${effectiveSessionAffinityState?.manageable ?? 'na'}`}
compact
className="mt-3"
state={routingState}
isLoading={routingLoading}
isSaving={updateRouting.isPending}
error={routingError instanceof Error ? routingError : null}
sessionAffinityState={effectiveSessionAffinityState}
isLoading={routingLoading || sessionAffinityLoading}
isSaving={isSavingRoutingConfig}
error={routingConfigError}
onApply={(strategy) => updateRouting.mutate(strategy)}
onApplyAffinity={(data) => updateSessionAffinity.mutate(data)}
/>
{/* Expanded section: Version Management (available even when not running) */}
+32
View File
@@ -11,6 +11,7 @@ import {
type UpdateVariant,
type CreatePreset,
type RoutingStrategy,
type CliproxySessionAffinityApplyResult,
} from '@/lib/api-client';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
@@ -18,6 +19,7 @@ import { useTranslation } from 'react-i18next';
function invalidateCliproxyRoutingQueries(queryClient: ReturnType<typeof useQueryClient>): void {
queryClient.invalidateQueries({ queryKey: ['cliproxy-catalog'] });
queryClient.invalidateQueries({ queryKey: ['cliproxy-models'] });
queryClient.invalidateQueries({ queryKey: ['cliproxy-session-affinity'] });
}
function invalidateCliproxyAccountQueries(queryClient: ReturnType<typeof useQueryClient>): void {
@@ -74,6 +76,36 @@ export function useUpdateCliproxyRoutingStrategy() {
});
}
export function useCliproxySessionAffinity() {
return useQuery({
queryKey: ['cliproxy-session-affinity'],
queryFn: () => api.cliproxy.getSessionAffinity(),
});
}
export function useUpdateCliproxySessionAffinity() {
const queryClient = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: (data: { enabled: boolean; ttl?: string }) =>
api.cliproxy.updateSessionAffinity(data),
onSuccess: (result: CliproxySessionAffinityApplyResult) => {
queryClient.setQueryData(['cliproxy-session-affinity'], result);
queryClient.invalidateQueries({ queryKey: ['cliproxy-session-affinity'] });
const stateLabel = result.enabled
? t('routingGuidance.sessionAffinityEnabled')
: t('routingGuidance.sessionAffinityDisabled');
toast.success(
result.message || t('toasts.sessionAffinityUpdated', { state: stateLabel.toLowerCase() })
);
},
onError: (error: Error) => {
toast.error(error.message);
},
});
}
export function useCreateVariant() {
const queryClient = useQueryClient();
const { t } = useTranslation();
+21
View File
@@ -521,6 +521,20 @@ export interface CliproxyRoutingApplyResult extends CliproxyRoutingState {
applied: 'live' | 'live-and-config' | 'config-only';
}
export interface CliproxySessionAffinityState {
enabled?: boolean;
ttl?: string;
source: 'config' | 'unsupported';
target: 'local' | 'remote';
reachable: boolean;
manageable: boolean;
message?: string;
}
export interface CliproxySessionAffinityApplyResult extends CliproxySessionAffinityState {
applied: 'config-and-live' | 'config-only' | 'unsupported';
}
/** Auth file info for Config tab */
export interface AuthFile {
name: string;
@@ -1269,6 +1283,13 @@ export const api = {
method: 'PUT',
body: JSON.stringify({ value: strategy }),
}),
getSessionAffinity: () =>
request<CliproxySessionAffinityState>('/cliproxy/routing/session-affinity'),
updateSessionAffinity: (data: { enabled: boolean; ttl?: string }) =>
request<CliproxySessionAffinityApplyResult>('/cliproxy/routing/session-affinity', {
method: 'PUT',
body: JSON.stringify(data),
}),
aiProviders: {
list: () => request<ListAiProvidersResult>('/cliproxy/ai-providers'),
create: (family: AiProviderFamilyId, data: UpsertAiProviderEntryInput) =>
+68
View File
@@ -1823,6 +1823,22 @@ const resources = {
fillFirst: 'Fill first keeps backup accounts cold until they are needed.',
routingStrategy: 'Routing strategy',
optionalRouting: 'Optional routing',
sessionAffinity: 'Session affinity',
sessionAffinityOn: 'On',
sessionAffinityOff: 'Off',
sessionAffinityEnabled: 'Enabled',
sessionAffinityDisabled: 'Disabled',
enableSessionAffinity: 'Enable session affinity',
disableSessionAffinity: 'Disable session affinity',
sessionAffinityUnavailable: 'Session affinity unavailable',
localOnly: 'Local only',
localOnlySetting: 'Local-only setting',
ttlBadge: 'TTL {{ttl}}',
sessionAffinityDescription:
'Keep one conversation pinned to the same account when possible. CLIProxy prefers explicit session or thread identifiers when clients send them, then falls back to request metadata or the opening prompt history when it has to infer a stable key.',
sessionRecognitionTitle: 'Session recognition',
sessionRecognitionDescription:
'CCS does not promise one universal precedence order here. In practice, upstream backends prefer explicit session or thread IDs first, then fall back to metadata fields and finally a hash based on the opening prompt history.',
},
extendedContext: {
extendedContext: 'Extended Context',
@@ -2173,6 +2189,7 @@ const resources = {
accountsUpdated: 'Accounts updated',
noProfilesToSync: 'No profiles to sync',
syncFailed: 'Sync failed: {{error}}',
sessionAffinityUpdated: 'Session affinity {{state}}.',
providerAuthSuccess: '{{provider}} authentication successful',
providerDeviceCodeInCallback: 'Provider returned Device Code flow in callback mode',
providerAuthTimeout: 'Authentication timed out. Please try again.',
@@ -4289,6 +4306,22 @@ const resources = {
fillFirst: '优先填满模式让备用账号保持冷启动直到需要时。',
routingStrategy: '路由策略',
optionalRouting: '可选路由',
sessionAffinity: '会话粘性',
sessionAffinityOn: '开启',
sessionAffinityOff: '关闭',
sessionAffinityEnabled: '已启用',
sessionAffinityDisabled: '已禁用',
enableSessionAffinity: '启用会话粘性',
disableSessionAffinity: '禁用会话粘性',
sessionAffinityUnavailable: '会话粘性不可用',
localOnly: '仅本地',
localOnlySetting: '仅限本地设置',
ttlBadge: 'TTL {{ttl}}',
sessionAffinityDescription:
'尽量将同一对话固定到同一个账号。CLIProxy 会优先使用客户端显式提供的会话或线程标识;如果没有,再回退到请求元数据或开场提示历史来推断稳定键。',
sessionRecognitionTitle: '会话识别',
sessionRecognitionDescription:
'CCS 不承诺所有后端都使用同一优先级顺序。通常上游会优先使用显式会话或线程 ID,然后回退到元数据字段,最后再回退到基于开场提示历史的哈希。',
},
extendedContext: {
extendedContext: '扩展上下文',
@@ -4624,6 +4657,7 @@ const resources = {
accountsUpdated: '账号已更新',
noProfilesToSync: '没有可同步的配置',
syncFailed: '同步失败:{{error}}',
sessionAffinityUpdated: '会话粘性已{{state}}。',
providerAuthSuccess: '{{provider}} 认证成功',
providerDeviceCodeInCallback: '提供商在回调模式中返回了设备码流程',
providerAuthTimeout: '认证超时,请重试。',
@@ -6825,6 +6859,22 @@ const resources = {
fillFirst: 'Fill-first giữ tài khoản dự phòng cho đến khi cần thiết.',
routingStrategy: 'Chiến lược định tuyến',
optionalRouting: 'Định tuyến tùy chọn',
sessionAffinity: 'Ghim phiên',
sessionAffinityOn: 'Bật',
sessionAffinityOff: 'Tắt',
sessionAffinityEnabled: 'bật',
sessionAffinityDisabled: 'tắt',
enableSessionAffinity: 'Bật ghim phiên',
disableSessionAffinity: 'Tắt ghim phiên',
sessionAffinityUnavailable: 'Ghim phiên không khả dụng',
localOnly: 'Chỉ cục bộ',
localOnlySetting: 'Thiết lập chỉ cục bộ',
ttlBadge: 'TTL {{ttl}}',
sessionAffinityDescription:
'Giữ một cuộc hội thoại trên cùng một tài khoản khi có thể. CLIProxy ưu tiên mã phiên hoặc luồng mà client gửi rõ ràng; nếu không có, nó sẽ dùng metadata của request hoặc lịch sử prompt mở đầu để suy ra khóa ổn định.',
sessionRecognitionTitle: 'Nhận diện phiên',
sessionRecognitionDescription:
'CCS không cam kết một thứ tự ưu tiên chung cho mọi backend. Trên thực tế, backend upstream thường ưu tiên session hoặc thread id tường minh, rồi mới fallback sang metadata và cuối cùng là hàm băm của lịch sử prompt mở đầu.',
},
extendedContext: {
extendedContext: 'Ngữ cảnh mở rộng',
@@ -7163,6 +7213,7 @@ const resources = {
accountsUpdated: 'Tài khoản đã được cập nhật',
noProfilesToSync: 'Không có hồ sơ để đồng bộ',
syncFailed: 'Đồng bộ thất bại: {{error}}',
sessionAffinityUpdated: 'Ghim phiên đã {{state}}.',
providerAuthSuccess: 'Xác thực {{provider}} thành công',
providerDeviceCodeInCallback: 'Nhà cung cấp trả về Device Code flow trong chế độ callback',
providerAuthTimeout: 'Đã hết thời gian xác thực. Vui lòng thử lại.',
@@ -9790,6 +9841,22 @@ const resources = {
fillFirst: 'Fill first は、バックアップアカウントが必要になるまで待機させます。',
routingStrategy: 'ルーティング戦略',
optionalRouting: 'オプションのルーティング',
sessionAffinity: 'セッション固定',
sessionAffinityOn: 'オン',
sessionAffinityOff: 'オフ',
sessionAffinityEnabled: '有効',
sessionAffinityDisabled: '無効',
enableSessionAffinity: 'セッション固定を有効化',
disableSessionAffinity: 'セッション固定を無効化',
sessionAffinityUnavailable: 'セッション固定は利用できません',
localOnly: 'ローカルのみ',
localOnlySetting: 'ローカル専用設定',
ttlBadge: 'TTL {{ttl}}',
sessionAffinityDescription:
'可能な場合は 1 つの会話を同じアカウントに固定します。CLIProxy はクライアントが明示的に送るセッション ID やスレッド ID を優先し、それがない場合はリクエストのメタデータや冒頭プロンプト履歴から安定キーを推定します。',
sessionRecognitionTitle: 'セッション認識',
sessionRecognitionDescription:
'CCS はすべてのバックエンドで同一の優先順位を保証しません。一般に上流バックエンドは明示的なセッション / スレッド ID を優先し、その後にメタデータ、最後に冒頭プロンプト履歴のハッシュへフォールバックします。',
},
settingsDialog: {
editProfile: 'プロファイルを編集: {{name}}',
@@ -10015,6 +10082,7 @@ const resources = {
accountsUpdated: 'アカウントを更新しました',
noProfilesToSync: '同期するプロファイルがありません',
syncFailed: '同期に失敗しました: {{error}}',
sessionAffinityUpdated: 'セッション固定を{{state}}にしました。',
providerAuthSuccess: '{{provider}} の認証に成功しました',
providerDeviceCodeInCallback:
'コールバックモードでプロバイダーがデバイスコードフローを返しました',
@@ -5,6 +5,7 @@ import { RoutingGuidanceCard } from '@/components/cliproxy/routing-guidance-card
describe('RoutingGuidanceCard', () => {
it('shows the current strategy and applies an explicit change', async () => {
const onApply = vi.fn();
const onApplyAffinity = vi.fn();
render(
<RoutingGuidanceCard
@@ -14,19 +15,33 @@ describe('RoutingGuidanceCard', () => {
target: 'local',
reachable: true,
}}
sessionAffinityState={{
enabled: true,
ttl: '1h',
source: 'config',
target: 'local',
reachable: true,
manageable: true,
}}
isLoading={false}
isSaving={false}
onApply={onApply}
onApplyAffinity={onApplyAffinity}
/>
);
expect(screen.getByText('Routing strategy')).toBeInTheDocument();
expect(screen.getAllByText('round-robin').length).toBeGreaterThan(0);
expect(screen.getByText('Session affinity')).toBeInTheDocument();
expect(screen.getByDisplayValue('1h')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /fill first/i }));
fireEvent.click(screen.getByRole('button', { name: /use fill-first/i }));
expect(onApply).toHaveBeenCalledWith('fill-first');
fireEvent.click(screen.getByRole('button', { name: /disable session affinity/i }));
expect(onApplyAffinity).toHaveBeenCalledWith({ enabled: false, ttl: '1h' });
});
it('shows the error state and disables apply', () => {
@@ -36,10 +51,40 @@ describe('RoutingGuidanceCard', () => {
isSaving={false}
error={new Error('Remote CLIProxy is not reachable')}
onApply={() => undefined}
onApplyAffinity={() => undefined}
/>
);
expect(screen.getByText('Remote CLIProxy is not reachable')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /use round-robin/i })).toBeDisabled();
});
it('shows remote session-affinity guidance when the setting is not manageable', () => {
render(
<RoutingGuidanceCard
state={{
strategy: 'round-robin',
source: 'live',
target: 'remote',
reachable: true,
}}
sessionAffinityState={{
source: 'unsupported',
target: 'remote',
reachable: true,
manageable: false,
message: 'Remote session-affinity management is not supported from CCS yet.',
}}
isLoading={false}
isSaving={false}
onApply={() => undefined}
onApplyAffinity={() => undefined}
/>
);
expect(
screen.getByText('Remote session-affinity management is not supported from CCS yet.')
).toBeInTheDocument();
expect(screen.getByRole('button', { name: /session affinity unavailable/i })).toBeDisabled();
});
});