Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog/unreleased/account-proxy-override.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### English

- Each account can set its own outbound proxy again. Leave it blank to use that provider and region's proxy, then the global proxy. `direct` or `none` bypasses both.
- A proxy saved on an account before provider settings is used again when it differs from the current provider proxy. A saved value that matches the provider proxy is cleared, so later changes to the provider proxy still apply. Accounts added after provider settings, with no proxy of their own, keep inheriting.

### 中文

- 每个账号可以再次单独设置出站代理。留空则使用该供应商和区域的代理,再留空则使用全局代理。填写 `direct` 或 `none` 会同时绕过这两层。
- 供应商策略出现之前写在账号上的代理,如果和当前供应商代理不同,会重新生效。和供应商代理相同的旧值会被清掉,之后修改供应商代理仍然对这个账号生效。供应商策略上线后新增、且自己没有代理的账号,继续继承。
1 change: 1 addition & 0 deletions frontend/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ export type Overview = {
auto_checkin?: boolean
checkin_time?: string
proxy_url?: string
inherited_proxy_url?: string
status?: string
cooldown_until?: string | null
url?: string
Expand Down
14 changes: 14 additions & 0 deletions frontend/src/components/AddAccountModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ export function AddAccountModal({ isOpen, onClose, onAdded }: Props) {
const [name, setName] = useState('')
const [maxInFlight, setMaxInFlight] = useState(4)
const [priority, setPriority] = useState(50)
const [proxyUrl, setProxyUrl] = useState('')
const [pat, setPat] = useState('')
const [json, setJson] = useState('')
const [zhipuMode, setZhipuMode] = useState<'payg' | 'coding'>('payg')
Expand Down Expand Up @@ -249,6 +250,7 @@ export function AddAccountModal({ isOpen, onClose, onAdded }: Props) {
return {
max_inflight: parsedMaxInFlight(),
priority: parsedPriority(),
...(proxyUrl.trim() ? { proxy_url: proxyUrl.trim() } : {}),
}
}

Expand All @@ -262,6 +264,7 @@ export function AddAccountModal({ isOpen, onClose, onAdded }: Props) {
setName('')
setMaxInFlight(4)
setPriority(50)
setProxyUrl('')
setPat('')
setJson('')
setZhipuMode('payg')
Expand Down Expand Up @@ -734,6 +737,17 @@ export function AddAccountModal({ isOpen, onClose, onAdded }: Props) {
<Description className="text-caption leading-5 text-muted">{t('priorityHint')}</Description>
</div>
</div>
<div className="space-y-1.5">
<Label className="text-body font-medium text-muted">{t('proxyUrl')}</Label>
<Input
value={proxyUrl}
onChange={(event) => setProxyUrl(event.target.value)}
placeholder={t('proxyUrlPlaceholder')}
aria-label={t('proxyUrl')}
disabled={settingsLocked}
/>
<Description className="text-caption leading-5 text-muted">{t('accountProxyUrlHint')}</Description>
</div>
</div>
) : null}
</div>
Expand Down
5 changes: 5 additions & 0 deletions frontend/src/components/account/AccountCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,11 @@ export function AccountCard({
<Card.Description className="mono truncate text-caption leading-4 text-foreground/60" title={`${account.id}${account.remote_uid ? ` · UID ${account.remote_uid}` : ''}`}>
{shortIdentity}
</Card.Description>
{account.proxy_url ? (
<p className="mono truncate text-caption leading-4 text-muted" title={account.proxy_url}>
{t('accountProxyOverride', { proxy: account.proxy_url })}
</p>
) : null}
<Button
isIconOnly
size="sm"
Expand Down
14 changes: 12 additions & 2 deletions frontend/src/components/account/EditAccountModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ type Props = {
busy: boolean
t: Translate
onClose: () => void
onSave: (input: { name: string; max_inflight: number; priority: number }) => Promise<void>
onSave: (input: { name: string; max_inflight: number; priority: number; proxy_url: string }) => Promise<void>
}

export function EditAccountModal({ account, busy, t, onClose, onSave }: Props) {
const [name, setName] = useState(account?.name || '')
const [maxInFlight, setMaxInFlight] = useState<number>(account?.max_inflight ?? 4)
const [priority, setPriority] = useState<number>(account?.priority ?? 50)
const [proxyUrl, setProxyUrl] = useState(account?.proxy_url || '')
const [error, setError] = useState('')

const title = t('editAccountTitle', { name: account?.name || account?.id || '' })
Expand All @@ -42,7 +43,7 @@ export function EditAccountModal({ account, busy, t, onClose, onSave }: Props) {
}
setError('')
try {
await onSave({ name: trimmed, max_inflight: maxInFlight, priority })
await onSave({ name: trimmed, max_inflight: maxInFlight, priority, proxy_url: proxyUrl.trim() })
onClose()
} catch (err) {
setError(err instanceof Error ? err.message : String(err))
Expand Down Expand Up @@ -110,6 +111,15 @@ export function EditAccountModal({ account, busy, t, onClose, onSave }: Props) {
</NumberField.Group>
</NumberField>
</FormRow>
<FormRow label={t('proxyUrl')} hint={t('accountProxyUrlHint')}>
<Input
value={proxyUrl}
onChange={(event) => setProxyUrl(event.target.value)}
placeholder={account?.inherited_proxy_url || t('proxyUrlPlaceholder')}
aria-label={t('proxyUrl')}
disabled={busy}
/>
</FormRow>
<FormRow label={t('priority')} hint={t('priorityHint')}>
<NumberField
value={priority}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/provider/ProviderSettingsModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ export function ProviderSettingsModal({
)}
</div>
</FormRow>
<FormRow label={t('proxyUrl')} hint={t('proxyUrlHint')}>
<FormRow label={t('proxyUrl')} hint={t('providerProxyUrlHint')}>
<Input
value={proxyUrl}
onChange={(event) => setProxyUrl(event.target.value)}
Expand Down
14 changes: 10 additions & 4 deletions frontend/src/i18n/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ export const messages: Record<Lang, Dict> = {
providerSettingsOpen: 'Settings',
providerExpand: 'Expand provider',
providerCollapse: 'Collapse provider',
providerSettingsHint: 'Applies to every account of this provider and region. The provider policy is the single source of truth for floors, proxy, system-prompt handling, aliases, model restrictions, and check-in time; account names, concurrency, and priority stay account-local.',
providerSettingsHint: 'Applies to every account of this provider and region. An account can set its own proxy. Floors, system-prompt handling, aliases, model restrictions, and check-in time stay on this policy; account name, concurrency, and priority stay on the account.',
providerSettingsSaved: 'Provider settings saved. Matching accounts now read this policy directly; no account rows were rewritten.',
providerSettingsLoadFailed: 'Could not load provider settings. Refresh the page and try again.',
providerSettingsRegionMissing: 'This provider group has no region yet. Refresh the model catalog and try again.',
Expand Down Expand Up @@ -1101,7 +1101,7 @@ export const messages: Record<Lang, Dict> = {
wizardSettingsHint: 'Set these before login. You can still change them later from Edit on the account card.',
editAccount: 'Edit',
editAccountTitle: 'Edit {name}',
editAccountHint: 'Change the display name, concurrency, and routing priority. Provider-level settings on the Models page control proxy, aliases, model restrictions, floors, and check-in time.',
editAccountHint: 'Change the display name, concurrency, routing priority, and this account\'s proxy. Leave the proxy blank to inherit the provider proxy.',
accountModelAliases: 'Aliases',
accountModelAliasesHint: 'A name this provider answers as. The request is rewritten to an account\'s real model after an account is picked.',
accountModelAliasTargetPlaceholder: 'real model on this provider',
Expand Down Expand Up @@ -1139,6 +1139,9 @@ export const messages: Record<Lang, Dict> = {
proxyUrl: 'Proxy URL',
proxyUrlPlaceholder: 'http://127.0.0.1:7890, direct',
proxyUrlHint: 'Blank inherits the global proxy. Use direct or none to bypass proxies for this provider. Qoder supports HTTP(S) only; WorkBuddy/Trae also support SOCKS5.',
providerProxyUrlHint: 'Blank inherits the global proxy. Accounts that set their own proxy keep it. Use direct or none to bypass proxies for accounts that inherit this one. Qoder supports HTTP(S) only; WorkBuddy/Trae also support SOCKS5.',
accountProxyUrlHint: 'Blank uses this provider\'s proxy, then the global proxy. Use direct or none to bypass both. Qoder supports HTTP(S) only; WorkBuddy/Trae also support SOCKS5.',
accountProxyOverride: 'Proxy {proxy}',
proxySettingsTitle: 'Outbound proxy',
proxySettingsHint: 'Set the default proxy for upstream requests. Global proxies support HTTP(S) only. SOCKS5 is available for WorkBuddy/Trae provider-level proxies. Provider settings override it.',
dropSystemPromptCreateHint: 'WorkBuddy only. Strip caller system prompts, then send an empty leading system slot so Global still accepts the request.',
Expand Down Expand Up @@ -1999,7 +2002,7 @@ export const messages: Record<Lang, Dict> = {
providerSettingsOpen: '设置',
providerExpand: '展开供应商',
providerCollapse: '折叠供应商',
providerSettingsHint: '对该供应商和区域下的所有账号生效。积分/百分比保底、代理、系统提示词处理、别名、可用模型和签到时间统一由供应商策略管理;账号名、并发和优先级仍由账号自己管理。',
providerSettingsHint: '对该供应商和区域下的账号生效。账号单独填写的代理优先。积分/百分比保底、系统提示词处理、别名、可用模型和签到时间仍由这份策略管理;账号名、并发和优先级仍由账号自己管理。',
providerSettingsSaved: '供应商设置已保存。匹配账号直接读取该策略,不再改写账号数据。',
providerSettingsLoadFailed: '无法加载供应商设置,请刷新页面后重试。',
providerSettingsRegionMissing: '这个供应商分组还没有确定区域,请刷新模型目录后重试。',
Expand Down Expand Up @@ -2357,7 +2360,7 @@ export const messages: Record<Lang, Dict> = {
wizardSettingsHint: '登录前先设好这些选项,之后仍可在账号卡片上点编辑修改。',
editAccount: '编辑',
editAccountTitle: '编辑 {name}',
editAccountHint: '修改显示名称、并发和调度优先级。代理、别名、可用模型、保底和签到时间等供应商级设置已移到模型页的供应商分组。',
editAccountHint: '修改显示名称、并发、调度优先级和这个账号自己的代理。代理留空则继承供应商代理。',
accountModelAliases: '别名',
accountModelAliasesHint: '这个供应商对外应答的名字。选中账号后,请求会换成该账号自己的真实模型。',
accountModelAliasTargetPlaceholder: '这个供应商上的真实模型',
Expand Down Expand Up @@ -2395,6 +2398,9 @@ export const messages: Record<Lang, Dict> = {
proxyUrl: '代理地址',
proxyUrlPlaceholder: 'http://127.0.0.1:7890、direct',
proxyUrlHint: '留空继承全局代理;填写 direct 或 none 可让此供应商直连。Qoder 仅支持 HTTP(S),WorkBuddy/Trae 额外支持 SOCKS5。',
providerProxyUrlHint: '留空继承全局代理。单独设置过代理的账号保持自己的出口。填写 direct 或 none 会让继承这里的账号直连。Qoder 仅支持 HTTP(S),WorkBuddy/Trae 额外支持 SOCKS5。',
accountProxyUrlHint: '留空则使用该供应商的代理,供应商也留空时再用全局代理。填写 direct 或 none 会同时绕过这两层。Qoder 仅支持 HTTP(S),WorkBuddy/Trae 额外支持 SOCKS5。',
accountProxyOverride: '代理 {proxy}',
proxySettingsTitle: '统一代理出口',
proxySettingsHint: '设置所有上游请求的默认代理;全局代理支持 HTTP(S),SOCKS5 仅支持 WorkBuddy/Trae 的供应商级代理;供应商设置优先于全局代理。',
dropSystemPromptCreateHint: '仅 WorkBuddy。剥离调用方系统提示词后仍补一条空的 system,避免国际版拒绝请求。',
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/AccountsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -809,7 +809,7 @@ export function AccountsPage() {
})
}

async function onSaveSettings(id: string, input: { name: string; max_inflight: number; priority: number }) {
async function onSaveSettings(id: string, input: { name: string; max_inflight: number; priority: number; proxy_url: string }) {
if (!id) throw new Error(t('accountNameRequired'))
setNameById((current) => ({ ...current, [id]: input.name }))
setInflightById((current) => ({ ...current, [id]: input.max_inflight }))
Expand Down
16 changes: 10 additions & 6 deletions internal/accounts/provider_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,20 @@ func NormalizeProviderPolicy(policy ProviderPolicy) (ProviderPolicy, error) {

// ApplyProviderPolicy overlays an account with its provider-scoped settings in
// memory. The account keeps its own name, concurrency, priority, credential,
// and enabled state; only fields owned by the provider policy change. This is
// never written back to SQLite: the provider policy stays the source of truth.
// enabled state, and a non-empty proxy. An empty proxy inherits the provider
// proxy. Nothing here is written back to SQLite.
func ApplyProviderPolicy(account *Account, policy ProviderPolicy) {
if account == nil {
return
}
account.CreditFloor = cloneFloat(policy.CreditFloor)
account.PercentFloor = cloneFloat(policy.PercentFloor)
account.ProxyURL = strings.TrimSpace(policy.ProxyURL)
// A saved account proxy is an override. Blank inherits the provider proxy,
// and a blank provider proxy leaves the effective value empty so callers
// fall through to the global proxy.
if strings.TrimSpace(account.ProxyURL) == "" {
account.ProxyURL = strings.TrimSpace(policy.ProxyURL)
}
account.DropSystemPrompt = DefaultDropSystemPrompt(account.Provider, policy.DropSystemPrompt)
account.ModelAliases = cloneAliases(policy.ModelAliases)
account.EnabledModels = cloneStrings(policy.EnabledModels)
Expand All @@ -109,14 +114,13 @@ func ApplyProviderPolicy(account *Account, policy ProviderPolicy) {
}

// StripProviderOwnedSettings removes fields owned by a provider policy from an
// account PATCH. Identity, concurrency, priority, enabled state, and automatic
// check-in opt-in stay account-scoped.
// account PATCH. Identity, concurrency, priority, enabled state, the proxy
// override, and automatic check-in opt-in stay account-scoped.
func StripProviderOwnedSettings(input UpdateAccount) UpdateAccount {
input.CreditFloor = nil
input.SetCreditFloor = false
input.PercentFloor = nil
input.SetPercentFloor = false
input.ProxyURL = nil
input.DropSystemPrompt = nil
input.ModelAliases = nil
input.EnabledModels = nil
Expand Down
17 changes: 14 additions & 3 deletions internal/accounts/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,14 @@ type Account struct {
WorkBuddyCheckinTime string `json:"workbuddy_checkin_time"`
AutoCheckin bool `json:"auto_checkin"`
CheckinTime string `json:"checkin_time"`
ProxyURL string `json:"-"`
// ProxyURL is the effective egress after a provider policy overlay. An
// empty stored value inherits the provider proxy. Callers of Get and List
// see that effective value; it is not written back to the row.
ProxyURL string `json:"-"`
// StoredProxyURL is the account's own proxy column. Empty means inherit.
// ApplyProviderPolicy does not change it, so the console can edit the
// override without pinning the inherited provider proxy.
StoredProxyURL string `json:"-"`
// LastCheckin* are display-only WorkBuddy ops results.
LastCheckinAt string `json:"last_checkin_at,omitempty"`
LastCheckinMsg string `json:"last_checkin_msg,omitempty"`
Expand Down Expand Up @@ -184,8 +191,12 @@ type AccountView struct {
// OverageWritable is set for Kiro. False means this login cannot name a
// profile, so the console keeps the switch disabled. Nil means the
// provider has no overage switch.
OverageWritable *bool `json:"overage_writable,omitempty"`
ProxyURL string `json:"proxy_url,omitempty"`
OverageWritable *bool `json:"overage_writable,omitempty"`
// ProxyURL is this account's saved override, redacted. Empty inherits.
ProxyURL string `json:"proxy_url,omitempty"`
// InheritedProxyURL is the provider proxy used when ProxyURL is empty,
// redacted. Empty means the next fallback is the global proxy.
InheritedProxyURL string `json:"inherited_proxy_url,omitempty"`
}

type ProviderModelSetting struct {
Expand Down
6 changes: 5 additions & 1 deletion internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,13 @@ func New(cfg config.Config) *App {
}, store, nil)
// Existing provider-region groups migrate to provider policies before the
// runtime starts, so workers see the same unified values on first boot.
if err := appsvc.NewProviderSettings(manager).SeedMissing(context.Background()); err != nil {
providerSettings := appsvc.NewProviderSettings(manager)
if err := providerSettings.SeedMissing(context.Background()); err != nil {
log.Printf("[provider-settings] seed existing groups: %v", err)
}
if err := providerSettings.ReconcileAccountProxyOverrides(context.Background()); err != nil {
log.Printf("[provider-settings] reconcile account proxies: %v", err)
}
if err := manager.Start(context.Background()); err != nil {
panic(err)
}
Expand Down
34 changes: 31 additions & 3 deletions internal/app/provider_policy_seed_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
sqlstore "github.com/caigee-cmd/cli2api/internal/store"
)

func TestAppSeedsProviderPolicyForExistingAccountWithoutRewritingIt(t *testing.T) {
func TestAppStartupRestoresDistinctAccountProxies(t *testing.T) {
ctx := context.Background()
dataDir := t.TempDir()
store, err := sqlstore.OpenStore(filepath.Join(dataDir, "qoder.db"))
Expand All @@ -26,6 +26,14 @@ func TestAppSeedsProviderPolicyForExistingAccountWithoutRewritingIt(t *testing.T
_ = store.Close()
t.Fatal(err)
}
other, err := store.Create(ctx, accounts.CreateAccount{
Name: "other", Provider: "trae", Region: "cn", Enabled: false,
ProxyURL: "http://other.example:9090",
})
if err != nil {
_ = store.Close()
t.Fatal(err)
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
Expand All @@ -45,8 +53,21 @@ func TestAppSeedsProviderPolicyForExistingAccountWithoutRewritingIt(t *testing.T
if err != nil {
t.Fatal(err)
}
if len(raw) != 1 || raw[0].ID != account.ID || raw[0].ProxyURL != "http://user:secret@example.test:8080" {
t.Fatalf("startup seed rewrote account row: %#v", raw)
if len(raw) != 2 {
t.Fatalf("raw accounts = %d, want 2", len(raw))
}
rawByID := map[string]accounts.Account{}
for _, item := range raw {
rawByID[item.ID] = item
}
// The seeded policy copied this account's proxy, so startup clears the
// duplicate and the account inherits. The other account's proxy differed
// and stays as an override.
if rawByID[account.ID].ProxyURL != "" {
t.Fatalf("duplicate account proxy was kept: %#v", rawByID[account.ID])
}
if rawByID[other.ID].ProxyURL != "http://other.example:9090" {
t.Fatalf("distinct account proxy was cleared: %#v", rawByID[other.ID])
}

effective, err := a.Manager.Store().Get(ctx, account.ID)
Expand All @@ -56,4 +77,11 @@ func TestAppSeedsProviderPolicyForExistingAccountWithoutRewritingIt(t *testing.T
if effective.ProxyURL != "http://user:secret@example.test:8080" {
t.Fatalf("effective account proxy = %q", effective.ProxyURL)
}
otherEffective, err := a.Manager.Store().Get(ctx, other.ID)
if err != nil {
t.Fatal(err)
}
if otherEffective.ProxyURL != "http://other.example:9090" {
t.Fatalf("effective override proxy = %q", otherEffective.ProxyURL)
}
}
Loading
Loading