feat(server): converge legacy compatibility (#15426)

#### PR Dependency Tree


* **PR #15426** 👈

This tree was auto-generated by
[Charcoal](https://github.com/danerwilliams/charcoal)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added workspace BYOK profiles with provider/model catalogs, capability
validation, connection probing, credential rotation, reordering, and
secure local leases.
* Added Copilot route options, selectable targets, managed tiers,
explicit profile/model overrides, and improved streaming with tool
callbacks and abort support.
* Added Copilot availability controls to prevent access when the feature
is disabled.
* **Changes**
* Simplified Copilot configuration and removed legacy provider-specific
settings.
* Removed obsolete model, token-cost, transcript strategy, and provider
metadata fields from public responses.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
DarkSky
2026-08-05 00:40:13 +08:00
committed by GitHub
parent fdfb6df826
commit 965f4590ff
272 changed files with 12430 additions and 33824 deletions
@@ -14,20 +14,55 @@ export function disposeWorkspaceByokStorage() {
}
const allowedProviders = new Set(['openai', 'anthropic', 'gemini', 'fal']);
const allowedInputs = new Set(['text', 'image', 'audio', 'file']);
const allowedOutputs = new Set([
'text',
'object',
'structured',
'embedding',
'rerank',
'image',
]);
const allowedFeatures = new Set(['tool_calling', 'reasoning', 'web_search']);
const allowedAttachmentKinds = new Set(['image', 'audio', 'file']);
const allowedAttachmentSources = new Set([
'url',
'data',
'bytes',
'file_handle',
]);
type WorkspaceByokKey = {
id: string;
provider: 'openai' | 'anthropic' | 'gemini' | 'fal';
name: string;
description?: string | null;
apiKey: string;
endpoint?: string | null;
credential: string;
definition: {
version: number;
endpoint: { kind: string; url?: string | null };
models: Array<{
modelId: string;
enabled: boolean;
capabilities: Array<{
input: string[];
output: string[];
features: string[];
attachmentKinds: string[];
attachmentSources: string[];
}>;
}>;
};
sortOrder?: number | null;
enabled?: boolean | null;
};
type WorkspaceByokKeyInput = Omit<WorkspaceByokKey, 'apiKey'> & {
apiKey?: string | null;
type WorkspaceByokKeyInput = Omit<
WorkspaceByokKey,
'credential' | 'definition'
> & {
credential?: string | null;
definition?: WorkspaceByokKey['definition'];
};
function assertSupported() {
@@ -43,6 +78,73 @@ function hasOwnField(
return Object.prototype.hasOwnProperty.call(key, field);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isAllowedStringArray(
value: unknown,
allowed: Set<string>
): value is string[] {
return (
Array.isArray(value) &&
value.every(item => typeof item === 'string' && allowed.has(item))
);
}
function isValidEndpoint(value: unknown) {
if (!isRecord(value) || typeof value.kind !== 'string') return false;
if (value.kind === 'provider_default') return value.url == null;
if (value.kind !== 'custom' || typeof value.url !== 'string') return false;
try {
const endpoint = new URL(value.url);
return (
(endpoint.protocol === 'http:' || endpoint.protocol === 'https:') &&
!!endpoint.hostname &&
!endpoint.username &&
!endpoint.password
);
} catch {
return false;
}
}
function isValidCapability(value: unknown) {
return (
isRecord(value) &&
isAllowedStringArray(value.input, allowedInputs) &&
value.input.length > 0 &&
isAllowedStringArray(value.output, allowedOutputs) &&
value.output.length > 0 &&
isAllowedStringArray(value.features, allowedFeatures) &&
isAllowedStringArray(value.attachmentKinds, allowedAttachmentKinds) &&
isAllowedStringArray(value.attachmentSources, allowedAttachmentSources)
);
}
function isValidDefinition(
value: unknown
): value is WorkspaceByokKey['definition'] {
return (
isRecord(value) &&
value.version === 1 &&
isValidEndpoint(value.endpoint) &&
Array.isArray(value.models) &&
value.models.length > 0 &&
value.models.every(
model =>
isRecord(model) &&
typeof model.modelId === 'string' &&
model.modelId.trim().length > 0 &&
model.modelId.length <= 512 &&
typeof model.enabled === 'boolean' &&
Array.isArray(model.capabilities) &&
model.capabilities.length > 0 &&
model.capabilities.every(isValidCapability)
)
);
}
function normalizeKey(
key: WorkspaceByokKeyInput,
existing?: WorkspaceByokKey,
@@ -51,8 +153,9 @@ function normalizeKey(
if (!allowedProviders.has(key.provider)) {
throw new Error('Unsupported BYOK provider.');
}
const apiKey = key.apiKey ?? existing?.apiKey;
if (!key.id || !key.name || !apiKey) {
const credential = key.credential ?? existing?.credential;
const definition = key.definition ?? existing?.definition;
if (!key.id || !key.name || !credential || !isValidDefinition(definition)) {
throw new Error('Invalid BYOK key.');
}
return {
@@ -62,10 +165,8 @@ function normalizeKey(
description: hasOwnField(key, 'description')
? (key.description ?? null)
: (existing?.description ?? null),
apiKey,
endpoint: hasOwnField(key, 'endpoint')
? (key.endpoint ?? null)
: (existing?.endpoint ?? null),
credential,
definition,
sortOrder: hasOwnField(key, 'sortOrder')
? (key.sortOrder ?? defaultSortOrder)
: (existing?.sortOrder ?? defaultSortOrder),
@@ -111,13 +212,11 @@ function writeWorkspaceKeys(workspaceId: string, keys: WorkspaceByokKey[]) {
byokStorage.set(workspaceId, keys.map(encryptKey));
}
function toPublicKey({ apiKey: _, ...key }: WorkspaceByokKey) {
function toPublicKey({ credential: _, ...key }: WorkspaceByokKey) {
return {
...key,
storage: 'local',
configured: true,
endpointEditable: false,
testStatus: 'passed',
};
}
@@ -75,6 +75,25 @@ afterEach(async () => {
});
describe('byok storage handlers', () => {
const definition = {
version: 1,
endpoint: { kind: 'provider_default' },
models: [
{
modelId: 'model-1',
enabled: true,
capabilities: [
{
input: ['text'],
output: ['text'],
features: [],
attachmentKinds: [],
attachmentSources: [],
},
],
},
],
};
test('stores encrypted local keys and keeps lease providers sorted', async () => {
const { byokStorageHandlers, disposeWorkspaceByokStorage: dispose } =
await import('@affine/electron/main/byok-storage/handlers');
@@ -85,14 +104,16 @@ describe('byok storage handlers', () => {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI',
apiKey: 'sk-openai',
credential: 'sk-openai',
definition,
sortOrder: 1,
});
await byokStorageHandlers.upsertWorkspaceKey(ipcEvent, 'workspace-1', {
id: 'local-gemini',
provider: 'gemini',
name: 'Gemini',
apiKey: 'sk-gemini',
credential: 'sk-gemini',
definition,
sortOrder: 0,
});
@@ -117,7 +138,7 @@ describe('byok storage handlers', () => {
ipcEvent,
'workspace-1'
);
expect(leaseProviders.map(key => key.apiKey)).toEqual([
expect(leaseProviders.map(key => key.credential)).toEqual([
'sk-openai',
'sk-gemini',
]);
@@ -142,12 +163,60 @@ describe('byok storage handlers', () => {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI',
apiKey: 'sk-openai',
credential: 'sk-openai',
definition,
})
).rejects.toThrow('Secure BYOK key storage is not available.');
expect(electronMock.encryptString).not.toHaveBeenCalled();
});
test.each([
[
'custom endpoint without URL',
{ ...definition, endpoint: { kind: 'custom' } },
],
[
'unsupported endpoint protocol',
{ ...definition, endpoint: { kind: 'custom', url: 'file:///tmp/api' } },
],
[
'malformed capability object',
{
...definition,
models: [{ ...definition.models[0], capabilities: [{}] }],
},
],
[
'unknown capability value',
{
...definition,
models: [
{
...definition.models[0],
capabilities: [
{ ...definition.models[0].capabilities[0], input: ['video'] },
],
},
],
},
],
])('rejects %s from IPC input', async (_name, malformedDefinition) => {
const { byokStorageHandlers, disposeWorkspaceByokStorage: dispose } =
await import('@affine/electron/main/byok-storage/handlers');
disposeWorkspaceByokStorage = dispose;
await expect(
byokStorageHandlers.upsertWorkspaceKey(undefined, 'workspace-1', {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI',
credential: 'sk-openai',
definition: malformedDefinition as typeof definition,
})
).rejects.toThrow('Invalid BYOK key.');
expect(electronMock.encryptString).not.toHaveBeenCalled();
});
test('preserves existing local key fields during partial updates', async () => {
const { byokStorageHandlers, disposeWorkspaceByokStorage: dispose } =
await import('@affine/electron/main/byok-storage/handlers');
@@ -159,8 +228,11 @@ describe('byok storage handlers', () => {
provider: 'openai',
name: 'OpenAI',
description: 'Primary key',
apiKey: 'sk-openai',
endpoint: 'https://api.openai.example/v1',
credential: 'sk-openai',
definition: {
...definition,
endpoint: { kind: 'custom', url: 'https://api.openai.example/v1' },
},
sortOrder: 4,
enabled: false,
});
@@ -169,7 +241,7 @@ describe('byok storage handlers', () => {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI renamed',
apiKey: 'sk-openai-next',
credential: 'sk-openai-next',
});
const [publicKey] = await byokStorageHandlers.listWorkspaceKeys(
@@ -180,7 +252,10 @@ describe('byok storage handlers', () => {
id: 'local-openai',
name: 'OpenAI renamed',
description: 'Primary key',
endpoint: 'https://api.openai.example/v1',
definition: {
...definition,
endpoint: { kind: 'custom', url: 'https://api.openai.example/v1' },
},
sortOrder: 4,
enabled: false,
});
@@ -206,8 +281,11 @@ describe('byok storage handlers', () => {
);
expect(enabledLeaseProvider).toMatchObject({
name: 'OpenAI renamed again',
apiKey: 'sk-openai-next',
endpoint: 'https://api.openai.example/v1',
credential: 'sk-openai-next',
definition: {
...definition,
endpoint: { kind: 'custom', url: 'https://api.openai.example/v1' },
},
sortOrder: 4,
enabled: true,
});