Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(provider-sharing): deduplicate model aliases without losing engine grants
zqchris81b32fd2d675
diff --git a/apps/desktop/scripts/fixtures/remote-model-access/remote-model-access-fixture.tsx b/apps/desktop/scripts/fixtures/remote-model-access/remote-model-access-fixture.tsxindex 80692e49bd..ab7a38783b 100644--- a/apps/desktop/scripts/fixtures/remote-model-access/remote-model-access-fixture.tsx+++ b/apps/desktop/scripts/fixtures/remote-model-access/remote-model-access-fixture.tsx@@ -4,6 +4,7 @@ import type { RemoteModelSelection } from '../../../src/shared/remoteModelAccessvoid mountPage({host: (ctx) => {+ const aliasCase = ctx.case.startsWith('alias-');const budgetCase = ctx.case.startsWith('budget');const claude = ctx.case === 'budget-claude';const recommended = claude ? 'claude-sonnet' : 'gpt-terra';@@ -15,23 +16,31 @@ void mountPage({...(ctx.case === 'budget-new-model' ? [{ id: 'catalog-new-model-42', name: 'New model 42' }] : []),];let budget = budgetCase ? { recommendedModel: recommended, rules: [{ id: 'premium', models: [limited], maxPercent: 30 }], basis: 'member-input-output-7d' as const, enabled: false } : null;- let models: RemoteModelSelection = ctx.case === 'member' ? ['small'] : null;+ let models: RemoteModelSelection = ctx.case === 'alias-partial' ? ['gpt-6.1-sol'] : ctx.case === 'member' ? ['small'] : null;return {providerShare: {onOwnedChanged: subscription('ownedShares'),command: async (cmd: { action: string; models?: RemoteModelSelection; memberBudget?: typeof budget }) => {if (cmd.action === 'set-model-access' && ctx.case === 'budget-save-failure') throw new Error('Fixture save failed');if (cmd.memberBudget !== undefined) budget = cmd.memberBudget;- if (cmd.action === 'set-model-access') models = cmd.models ?? null;+ if (cmd.action === 'set-model-access') {+ models = cmd.models ?? null;+ if (aliasCase) Object.assign(window, { modelAccessSaved: cmd });+ }return {- version: 1, providerName: claude ? 'Claude' : 'OpenAI', models, providerModels: ctx.case === 'member' ? ['small', 'medium'] : null,+ version: 1, providerName: claude ? 'Claude' : 'OpenAI', models, providerModels: ctx.case === 'alias-pi-ceiling' ? ['chatgpt/gpt-6.1-sol'] : ctx.case === 'member' ? ['small', 'medium'] : null,...(budgetCase ? {budgetSupported: true, budgetAvailable: ctx.case !== 'budget-unsupported', memberBudget: budget,budgetStatus: { state: ctx.case === 'budget-learning' ? 'empty' : 'recorded', enabled: false, windowStart: '2026-10-22', windowEnd: '2026-10-28', nextWindowAt: Date.parse('2026-10-29T00:00:00+08:00'), totalTokens: ctx.case === 'budget-learning' ? 0 : 100,recommendedModel: recommended,rules: [{ id: 'premium', models: [limited], tokens: ctx.case === 'budget-learning' ? 0 : 60, usedPercent: ctx.case === 'budget-learning' ? null : 60, limitPercent: 30, wouldBlock: ctx.case !== 'budget-learning', blocked: false }] },} : {}),- availableModels: budgetCase ? catalog : [+ availableModels: aliasCase ? [+ ...(ctx.case === 'alias-pi-only' ? [] : [{ id: 'gpt-6.1-sol', name: 'GPT-6.1-Sol' }]),+ { id: 'chatgpt/gpt-6.1-sol', name: 'GPT-6.1-Sol' },+ { id: 'gpt-6-astra', name: 'GPT-6-Astra' },+ { id: 'chatgpt/gpt-6-astra', name: 'GPT-6-Astra' },+ ] : budgetCase ? catalog : [{ id: 'small', name: 'Claude Haiku' },{ id: 'medium', name: 'Claude Sonnet' },{ id: 'large', name: 'Claude Opus' },@@ -45,6 +54,7 @@ void mountPage({<AppFrame header={false}><div className="p-6"><RemoteModelAccessSection providerId={ctx.case === 'budget-claude' ? 'anthropic' : 'openai'} />+ {ctx.case.startsWith('alias-') && <RemoteModelAccessDialog providerId="openai" memberId={ctx.case === 'alias-pi-ceiling' ? 'fixture-member' : undefined} onClose={() => {}} />}{(ctx.case === 'member' || ctx.case.startsWith('budget')) && <RemoteModelAccessDialog providerId={ctx.case === 'budget-claude' ? 'anthropic' : 'openai'} memberId="fixture-member" memberName="小林" onClose={() => {}} />}</div></AppFrame>diff --git a/apps/desktop/scripts/fixtures/remote-model-access/ui-page.mjs b/apps/desktop/scripts/fixtures/remote-model-access/ui-page.mjsindex 4f35c2dbf8..c62611f948 100644--- a/apps/desktop/scripts/fixtures/remote-model-access/ui-page.mjs+++ b/apps/desktop/scripts/fixtures/remote-model-access/ui-page.mjs@@ -7,6 +7,10 @@ export default {real: 'RemoteModelAccessSection, RemoteModelAccessDialog, product buttons, translations and themes',notCovered: 'Live IPC, persisted permissions and cross-device calls. Names and models are fixture data.',cases: {+ 'alias-all': { about: 'Codex and Pi/Claude aliases display once and are toggled together' },+ 'alias-partial': { about: 'Existing Codex-only permission remains mixed and unchanged on save' },+ 'alias-pi-ceiling': { about: 'Personal selection cannot exceed a Pi-only provider ceiling' },+ 'alias-pi-only': { about: 'Pi-only catalogs save the actual chatgpt/ ID without fabricating a Codex ID' },budget: { about: 'OpenAI single-model percentage limit' },'budget-claude': { about: 'Claude uses its own catalog and single-model percentage limit' },'budget-new-model': { about: 'A new catalog model can be selected without product code changes' },@@ -20,6 +24,31 @@ export default {await page.getByRole('button', { name: /.+/ }).first().waitFor();},async check(page, ui) {+ if (ui.case.startsWith('alias-')) {+ const sol = page.getByRole('checkbox', { name: 'GPT-6.1-Sol', exact: true });+ await sol.waitFor();+ assert.equal(await sol.count(), 1);+ assert.equal(await page.getByRole('checkbox', { name: 'GPT-6-Astra', exact: true }).count(), 1);+ const save = page.getByRole('button', { name: await ui.t('settings.providers.custom.save'), exact: true });+ if (ui.case === 'alias-partial') {+ assert.equal(await sol.evaluate(input => input.indeterminate), true);+ await save.click();+ assert.deepEqual(await page.evaluate(() => window.modelAccessSaved.models), ['gpt-6.1-sol']);+ return;+ }+ await sol.click();+ await save.click();+ const removed = await page.evaluate(() => window.modelAccessSaved.models);+ assert.ok(!removed.includes('gpt-6.1-sol') && !removed.includes('chatgpt/gpt-6.1-sol'));+ await sol.click();+ await save.click();+ const saved = await page.evaluate(() => window.modelAccessSaved.models);+ assert.ok(saved.includes('chatgpt/gpt-6.1-sol'));+ assert.equal(saved.includes('gpt-6.1-sol'), ui.case === 'alias-all');+ if (ui.case === 'alias-pi-ceiling') assert.deepEqual(saved, ['chatgpt/gpt-6.1-sol']);+ await ui.capture('selected');+ return;+ }if (ui.case.startsWith('budget')) {const percent = page.getByRole('spinbutton', { name: await ui.t('providerShare.memberBudget.maxPercent'), exact: true });await percent.waitFor();diff --git a/apps/desktop/src/main/remote-agent/__tests__/providerAccess.test.ts b/apps/desktop/src/main/remote-agent/__tests__/providerAccess.test.tsindex 6a5e9e9b4b..46a9c46b3e 100644--- a/apps/desktop/src/main/remote-agent/__tests__/providerAccess.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/providerAccess.test.ts@@ -93,6 +93,44 @@ afterEach(() => {// have no direct-share member. Minimum: an authorized same-account controller// binding a guest-isolated task. Verify the real proxy grant, including revocation.describe('guest proxy binding for direct shares and same-account group relays', () => {+ // Regression companion to RemoteModelAccessDialog: one visible GPT row grants+ // both exact IDs. Existing binder tests only covered Claude with unprefixed IDs.+ // Unit: switching to Pi must retain its bridge ID and still enforce revocation.+ it('keeps the exact GPT route for Codex, Pi and Claude Code after a grouped grant', async () => {+ const rootId = 'gpt-6.1-sol';+ const bridgeId = 'chatgpt/gpt-6.1-sol';+ const grants = new Set([rootId, bridgeId]);+ const provider: ProviderView = {+ ...view('openai', [bridgeId]),+ auth: { method: 'oauth' },+ agents: ['codex', 'pi', 'claude-code'],+ models: {+ codex: [{ id: rootId, name: 'GPT-6.1-Sol', contextWindow: 200_000, efforts: [], defaultEffort: null }],+ pi: [{ id: bridgeId, name: 'GPT-6.1-Sol', contextWindow: 200_000, efforts: [], defaultEffort: null }],+ 'claude-code': [{ id: bridgeId, name: 'GPT-6.1-Sol', contextWindow: 200_000, efforts: [], defaultEffort: null }],+ },+ };+ const binder = createGuestProviderRouteBinder({+ readProviders: async () => [provider],+ guestAccess: () => ({ providerId: 'openai', memberId: 'alice' }),+ ownerAllowed: () => true, providerAllowed: () => true,+ modelAccess: {+ allows: (_providerId, model) => grants.has(model),+ read: () => ({ models: [...grants], providerModels: [...grants] }),+ },+ });+ for (const kind of ['codex', 'pi', 'claude-code'] as const) {+ const id = kind === 'codex' ? rootId : bridgeId;+ const binding = await binder({ kind, hostSessionId: `gpt-${kind}`, providerId: 'openai',+ controller: providerShareGuestPeer('share', 'alice', 'phone'), isCurrent: () => true });+ expect(binding?.modelIds).toEqual([id]);+ expect(await binding?.allowsModel?.(id)).toBe(true);+ grants.delete(id);+ expect(await binding?.allowsModel?.(id)).toBe(false);+ grants.add(id);+ binding?.release();+ }+ });it('enforces a changed member budget on the next request and exempts same-account callers', async () => {let blocked = true;const checks: Array<string | undefined> = [];diff --git a/apps/desktop/src/renderer/features/provider-share/RemoteModelAccessSection.tsx b/apps/desktop/src/renderer/features/provider-share/RemoteModelAccessSection.tsxindex e0311ec8ed..d056d25640 100644--- a/apps/desktop/src/renderer/features/provider-share/RemoteModelAccessSection.tsx+++ b/apps/desktop/src/renderer/features/provider-share/RemoteModelAccessSection.tsx@@ -2,6 +2,7 @@ import { MemberBudgetEditor } from './MemberBudgetEditor';import { isProviderShareMemberBudget, type ProviderShareMemberBudget } from '../../../shared/providerShareBudget';import { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { unifiedModelKeyId } from '@cindy/model-providers';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { ErrorNotice } from '@/components/ui/error-notice';@@ -13,6 +14,20 @@ import { ProviderShareDialog, ProviderShareDialogFooter, ProviderShareDialogTitlconst key = 'providerShare.modelAccess.';+// Group display rows only. Permissions and runtime routing still use every exact+// catalog ID, including the chatgpt/ ID required by Pi and Claude Code.+function modelAccessRows(models: RemoteModelAccessView['availableModels']) {+ const rows = new Map<string, { id: string; name: string; ids: string[] }>();+ for (const model of models) {+ const id = unifiedModelKeyId(model.id);+ const row = rows.get(id);+ if (row) {+ if (!row.ids.includes(model.id)) row.ids.push(model.id);+ } else rows.set(id, { id, name: model.name, ids: [model.id] });+ }+ return [...rows.values()];+}+export function RemoteModelAccessSection({ providerId, deviceId }: { providerId: string; deviceId?: string }) {const { t } = useTranslation();useOptionalAuthUser();@@ -50,7 +65,7 @@ export function RemoteModelAccessSection({ providerId, deviceId }: { providerId:<p className="mt-1 text-12 leading-[1.5] text-[var(--text-secondary)]">{t(key + 'description')}</p><div className="mt-3 flex items-center justify-between gap-4 rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] px-4 py-3"><span className="text-13 leading-[1.5] text-[var(--text-primary)]">- {currentView ? t(key + (currentView.models === null ? 'all' : 'selected'), { count: currentView.models?.length ?? 0 }) : t(key + 'loading')}+ {currentView ? t(key + (currentView.models === null ? 'all' : 'selected'), { count: new Set(currentView.models?.map(unifiedModelKeyId)).size }) : t(key + 'loading')}</span><Button ref={trigger} variant="secondary" size="sm" disabled={!currentView || Boolean(error)} onClick={() => setOpen(true)}>{t(key + 'choose')}</Button></div>@@ -96,7 +111,8 @@ export function RemoteModelAccessDialog({ providerId, deviceId, memberId, memberconst available = view?.availableModels ?? [];// Preserve explicit selections for temporarily missing models; users can remove them without silently expanding a grant.const missing = (view ? models ?? [] : []).filter((id) => !available.some((model) => model.id === id)).map((id) => ({ id, name: id }));- const rows = [...available, ...missing].filter((model) => `${model.name} ${model.id}`.toLowerCase().includes(search.toLowerCase()));+ const availableIds = new Set(available.map(model => model.id));+ const rows = modelAccessRows([...available, ...missing]).filter((model) => `${model.name} ${model.ids.join(' ')}`.toLowerCase().includes(search.toLowerCase()));const save = async () => {if (inFlight.current || !view) return;if (memberBudget && !isProviderShareMemberBudget(memberBudget)) { setError('providerShare.memberBudget.invalid'); return; }@@ -124,12 +140,16 @@ export function RemoteModelAccessDialog({ providerId, deviceId, memberId, member<div className="mt-3"><Input inputRef={searchRef} value={search} onChange={setSearch} placeholder={t(key + 'search')} aria-label={t(key + 'search')} disabled={!view || saving} /></div><div className="mt-2 max-h-72 shrink-0 overflow-y-auto overscroll-contain rounded-lg border border-[var(--border-default)] p-2" aria-busy={!view}>{rows.map((model) => {- const allowed = providerAllows(model.id);- const checked = models === null ? allowed : models.includes(model.id);+ const allowedIds = model.ids.filter(id => availableIds.has(id) && providerAllows(id));+ const selectedIds = models === null ? allowedIds : model.ids.filter(id => models.includes(id));+ const allowed = allowedIds.length > 0;+ const checked = selectedIds.length > 0 && allowedIds.every(id => selectedIds.includes(id));+ const partial = selectedIds.length > 0 && !checked;return <label key={model.id} className="flex min-h-9 items-center gap-3 rounded-lg px-2 py-2 text-13 leading-[1.5] text-[var(--text-primary)] hover:bg-[var(--surface-hover)]">- <input type="checkbox" className="h-4 w-4 shrink-0 accent-[var(--text-primary)]" aria-label={model.name} checked={checked} disabled={!view || saving || (!allowed && !checked)} onChange={(event) => {+ <input type="checkbox" className="h-4 w-4 shrink-0 accent-[var(--text-primary)]" aria-label={model.name} aria-checked={partial ? 'mixed' : checked}+ ref={input => { if (input) input.indeterminate = partial; }} checked={checked} disabled={!view || saving || (!allowed && selectedIds.length === 0)} onChange={(event) => {const current = models ?? available.filter((entry) => providerAllows(entry.id)).map((entry) => entry.id);- setModels(event.target.checked ? [...new Set([...current, model.id])] : current.filter((id) => id !== model.id));+ setModels(event.target.checked ? [...new Set([...current, ...allowedIds])] : current.filter((id) => !model.ids.includes(id)));}} /><span className="min-w-0 flex-1 break-words">{model.name}{model.name !== model.id && <span className="block text-11 leading-[1.5] text-[var(--text-tertiary)]">{model.id}</span>}</span>{!allowed && <span className="text-11 leading-[1.5] text-[var(--text-secondary)]">{t(key + 'notOpen')}</span>}diff --git a/apps/desktop/src/renderer/features/provider-share/__tests__/RemoteModelAccessSection.test.tsx b/apps/desktop/src/renderer/features/provider-share/__tests__/RemoteModelAccessSection.test.tsxindex 7275b47c9f..8374008106 100644--- a/apps/desktop/src/renderer/features/provider-share/__tests__/RemoteModelAccessSection.test.tsx+++ b/apps/desktop/src/renderer/features/provider-share/__tests__/RemoteModelAccessSection.test.tsx@@ -22,6 +22,56 @@ beforeEach(() => {});afterEach(() => cleanup());describe('remote model settings', () => {+ // Regression: the real dialog listed Codex and Pi/Claude bridge IDs twice. Existing+ // fixtures had no aliases. Unit: two wire IDs must render once, but both must be+ // sent on an explicit grant/revoke; distinct context profiles stay independent.+ const gptModels = [+ { id: 'gpt-6.1-sol', name: 'GPT-6.1-Sol' },+ { id: 'chatgpt/gpt-6.1-sol', name: 'GPT-6.1-Sol' },+ { id: 'gpt-6.1-sol[1m]', name: 'GPT-6.1-Sol 1M' },+ ];+ it('groups engine aliases and saves both actual IDs so Pi remains available', async () => {+ local.mockResolvedValue({ ...value(), models: [], availableModels: gptModels });+ render(<RemoteModelAccessDialog providerId="openai" onClose={() => {}} />);+ await screen.findByRole('checkbox', { name: 'GPT-6.1-Sol 1M' });+ expect(screen.getAllByRole('checkbox', { name: 'GPT-6.1-Sol' })).toHaveLength(1);+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'chatgpt/' } });+ fireEvent.click(screen.getByRole('checkbox', { name: 'GPT-6.1-Sol' }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(local).toHaveBeenLastCalledWith(expect.objectContaining({+ action: 'set-model-access', models: ['gpt-6.1-sol', 'chatgpt/gpt-6.1-sol'],+ })));+ });+ it('removes every engine alias when excluding a model from an unrestricted grant', async () => {+ local.mockResolvedValue({ ...value(), availableModels: gptModels });+ render(<RemoteModelAccessDialog providerId="openai" onClose={() => {}} />);+ await screen.findByRole('checkbox', { name: 'GPT-6.1-Sol 1M' });+ fireEvent.click(screen.getByRole('checkbox', { name: 'GPT-6.1-Sol' }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(local).toHaveBeenLastCalledWith(expect.objectContaining({+ action: 'set-model-access', models: ['gpt-6.1-sol[1m]'],+ })));+ });+ it.each([false, true])('preserves an old partial grant without silently enabling Pi (missing alias: %s)', async missingAlias => {+ const selected = missingAlias ? 'chatgpt/gpt-6.1-sol' : 'gpt-6.1-sol';+ local.mockResolvedValue({ ...value(), models: [selected], availableModels: missingAlias ? [gptModels[0]] : gptModels });+ render(<RemoteModelAccessDialog providerId="openai" onClose={() => {}} />);+ const row = await screen.findByRole('checkbox', { name: 'GPT-6.1-Sol' });+ expect((row as HTMLInputElement).indeterminate).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(local).toHaveBeenLastCalledWith(expect.objectContaining({ action: 'set-model-access', models: [selected] })));+ });+ it.each([undefined, 'studio'])('respects a Pi-only provider ceiling when editing a member: %s', async deviceId => {+ local.mockResolvedValue({ ...value(), models: [], providerModels: ['chatgpt/gpt-6.1-sol'], availableModels: gptModels });+ render(<RemoteModelAccessDialog providerId="openai" deviceId={deviceId} memberId="alice" onClose={() => {}} />);+ await screen.findByRole('checkbox', { name: 'GPT-6.1-Sol 1M' });+ fireEvent.click(screen.getByRole('checkbox', { name: 'GPT-6.1-Sol' }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(local).toHaveBeenLastCalledWith(expect.objectContaining({+ action: 'set-model-access', memberId: 'alice', models: ['chatgpt/gpt-6.1-sol'],+ })));+ if (deviceId) expect(remote).toHaveBeenCalledWith(expect.objectContaining({ action: 'remote-manage', deviceId }));+ });// Unit: a member limit edit must preserve the existing model grant on save.it('saves member limits in the model access panel without broadening the model grant', async () => {local.mockResolvedValue({ ...value(), models: ['small'], budgetSupported: true, budgetAvailable: true });diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.mdindex cf91415e59..4a2a29fecc 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -619,6 +619,11 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):取消全部模型表示不开放任何模型,不能解释为恢复默认。个人转分享的调用继续受该个人范围约束。普通模型与 `[1m]` 作为独立目录条目存在时,授权分别按各自 ID 校验,不能通过后缀归一借用另一档的权限。+模型范围弹窗按统一选择器的逻辑模型标识合并引擎别名(如 `gpt-6.1-sol` 与+`chatgpt/gpt-6.1-sol`),一行的勾选同时保存当前目录中允许选择的全部实际 ID,取消则移除该行全部已选 ID。+运行时仍按精确 ID 校验,保留 Pi / Claude Code 的桥接路由;个人选择不超出供应商开放范围。+旧配置只选了部分引擎时显示部分勾选,打开或直接保存不补授权;暂时不在目录里的已选 ID 保留且可取消。+模型范围存于提供方电脑,按账号隔离。旧配置默认跟随全部模型;读取损坏配置时拒绝调用,不能恢复为全部开放。远程目录只提供可用模型;提供方还必须在创建、切换模型、发送下一轮消息及供应商组转发时校验权限,不能信任控制端传来的目录或模型 id。已开始的一轮不因修改勾选主动中断,下一轮或切换模型时按最新范围校验;同账号远程任务及受邀者经本机代理发出的后续模型请求(含子代理)也按实际供应商与模型复核最新范围。