fix(assistant): let an admin switch the model of a shared ChatGPT plan

The model picker in Admin > Addons did nothing for a ChatGPT connection: the
only way to change the instance's model was saving the connection again, which
needs an API key a plan does not have. A PATCH /api/admin/ai/connection/model
now switches it on its own, to a model the provider offers.

Closes #2783
This commit is contained in:
Maurice
2026-10-25 15:48:32 +01:00
parent a69eee191c
commit d911122a37
9 changed files with 107 additions and 5 deletions
+2
View File
@@ -229,6 +229,8 @@ export const aiAdminApi = {
connection: (): Promise<AiAdminConnectionResponse> => apiClient.get('/admin/ai/connection').then((r) => r.data),
saveConnection: (body: AiInstanceConnectionRequest): Promise<AiAdminConnectionResponse> =>
apiClient.put('/admin/ai/connection', body, viaProvider).then((r) => r.data),
setModel: (model: string): Promise<AiAdminConnectionResponse> =>
apiClient.patch('/admin/ai/connection/model', { model }).then((r) => r.data),
removeConnection: (): Promise<SuccessResponse> => apiClient.delete('/admin/ai/connection').then((r) => r.data),
models: (): Promise<AiModelListResponse> => apiClient.get('/admin/ai/models', viaProvider).then((r) => r.data),
};
@@ -1,4 +1,4 @@
// FE-HOOK-AI-ADMIN-001 to FE-HOOK-AI-ADMIN-007: the AI assistant's settings and connection for everyone.
// FE-HOOK-AI-ADMIN-001 to FE-HOOK-AI-ADMIN-008: the AI assistant's settings and connection for everyone.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { AiAdminConnectionResponse, AiAdminSettings } from '@trek/shared';
import { MASKED_SETTING_VALUE } from '@trek/shared';
@@ -16,6 +16,7 @@ const repo = vi.hoisted(() => ({
saveAdminSettings: vi.fn(),
adminConnection: vi.fn(),
saveAdminConnection: vi.fn(),
setAdminModel: vi.fn(),
removeAdminConnection: vi.fn(),
adminModels: vi.fn(),
}));
@@ -157,6 +158,29 @@ describe('useAiAdminConfig', () => {
});
});
it("FE-HOOK-AI-ADMIN-008: a shared ChatGPT plan's model is switched on its own, and the answer shows (#2783)", async () => {
const plan = (model: string): AiAdminConnectionResponse => ({
connection: {
scope: 'instance',
kind: 'chatgpt',
model,
hint: null,
status: 'ok',
host: 'api.openai.com',
baseUrl: null,
},
prefill: null,
});
repo.adminConnection.mockResolvedValue(plan('gpt-6.1-sol'));
repo.setAdminModel.mockResolvedValue(plan('gpt-6.1-sol-mini'));
const { result } = await renderLoaded();
await act(async () => result.current.instance.setModel('gpt-6.1-sol-mini'));
await waitFor(() => expect(repo.setAdminModel).toHaveBeenCalledWith('gpt-6.1-sol-mini'));
expect(repo.saveAdminConnection).not.toHaveBeenCalled();
await waitFor(() => expect(result.current.instance.live?.model).toBe('gpt-6.1-sol-mini'));
expect(toast.success).toHaveBeenCalled();
});
it('FE-HOOK-AI-ADMIN-007: removing asks first, then shows the setup again; replacing opens it beside the old one', async () => {
repo.adminConnection.mockResolvedValueOnce(LIVE).mockResolvedValue(NONE);
const { result } = await renderLoaded();
@@ -124,9 +124,16 @@ function useInstanceConnection(onChanged: () => void) {
}
};
/** Another model on the same connection: the stored key is kept by sending the mask in its place. */
/**
* Another model on the same connection: the stored key is kept by sending the mask in its place.
* A shared ChatGPT plan has a sign-in, not a key, so its model is switched on its own (#2783).
*/
const setModel = (model: string) => {
if (!live || live.kind === 'chatgpt') return;
if (!live) return;
if (live.kind === 'chatgpt') {
void act(() => aiConnectionsRepo.setAdminModel(model), 'common.saved');
return;
}
const request: AiInstanceConnectionRequest =
live.kind === 'custom'
? { kind: 'custom', baseUrl: live.baseUrl ?? '', model, ...(live.hint ? { apiKey: MASKED_SETTING_VALUE } : {}) }
+5
View File
@@ -104,6 +104,11 @@ export const aiConnectionsRepo = {
return aiAdminConnectionResponseSchema.parse(await aiAdminApi.saveConnection(body));
},
async setAdminModel(model: string) {
requireOnline();
return aiAdminConnectionResponseSchema.parse(await aiAdminApi.setModel(model));
},
async removeAdminConnection(): Promise<void> {
requireOnline();
await aiAdminApi.removeConnection();
@@ -7,11 +7,11 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { AiAdminSettingsDto, AiInstanceConnectionDto } from './ai-connections.dto';
import { AiAdminSettingsDto, AiInstanceConnectionDto, AiModelUpdateDto } from './ai-connections.dto';
import { AiConnectionsService } from './ai-connections.service';
import { ChatgptAuthService } from './chatgpt-auth.service';
import { OpenrouterAuthService } from './openrouter-auth.service';
import { Body, Controller, Delete, Get, HttpCode, Post, Put, UseGuards } from '@nestjs/common';
import { Body, Controller, Delete, Get, HttpCode, Patch, Post, Put, UseGuards } from '@nestjs/common';
import {
aiAdminConnectionResponseSchema,
aiAdminSettingsSchema,
@@ -63,6 +63,12 @@ export class AiAdminController {
return this.connections.saveInstance(user.id, body as AiInstanceConnectionRequest);
}
@Patch('connection/model')
@ResponseContract(aiAdminConnectionResponseSchema)
setModel(@CurrentUser() user: User, @Body() body: AiModelUpdateDto) {
return this.connections.setInstanceModel(user.id, body.model);
}
@Delete('connection')
@HttpCode(200)
@ResponseContract(successResponseSchema)
@@ -328,6 +328,26 @@ export class AiConnectionsService implements SharedAiConnectionPort {
return this.modelsOf(adminId, row);
}
/**
* Picks the model of the instance's connection, one the provider offers. The
* only way to do so for a shared ChatGPT plan: saving the connection again
* needs a key, and a plan has a sign-in instead.
* @txIndependent reading the credential may renew a ChatGPT sign-in first; that write stands on its own.
*/
async setInstanceModel(adminId: number, model: string): Promise<AiAdminConnectionResponse> {
const row = await this.connections.findInstance();
if (!row) throw aiRefusal('not_found', 'No connection is set up for everyone');
const models = await this.modelsOf(adminId, row);
if (!models.some((m) => m.id === model)) throw aiRefusal('unknown_model', 'This model is not offered here');
await this.connections.setModel(row.id, model);
await this.audit.writeAudit({
userId: adminId,
action: 'ai.connection.saved',
details: { scope: 'instance', kind: row.kind, model },
});
return this.instanceConnection();
}
async removeInstance(adminId: number): Promise<void> {
const row = await this.connections.findInstance();
if (!row) throw aiRefusal('not_found', 'No connection is set up for everyone');
@@ -204,6 +204,16 @@ describe('AI connections e2e', () => {
expect(saved.body.connection).toMatchObject({ scope: 'instance', kind: 'anthropic', hint: '…7777', baseUrl: null });
expect(saved.body.prefill).toBeNull();
// The model for everyone is switched on its own, by an admin only, to one the provider offers (#2783).
const model = (as_: number, body: object) =>
request(server).patch('/api/admin/ai/connection/model').set(as(as_)).send(body);
expect((await model(USER, { model: 'claude-haiku' })).status).toBe(403);
expect((await model(ADMIN, {})).status).toBe(400);
expect((await model(ADMIN, { model: 'nope' })).body).toMatchObject({ code: 'unknown_model' });
const switched = await model(ADMIN, { model: 'claude-haiku' });
expect(switched.status).toBe(200);
expect(switched.body.connection).toMatchObject({ kind: 'anthropic', model: 'claude-haiku', hint: '…7777' });
// A user now runs on the instance's connection, with the daily limit and a privacy notice to acknowledge.
const status = await request(server).get('/api/ai/status').set(as(USER));
expect(status.body).toMatchObject({
@@ -42,6 +42,7 @@ function services() {
writeSettings: vi.fn(async () => ({ policy: 'user' })),
instanceConnection: vi.fn(async () => ADMIN_CONNECTION),
saveInstance: vi.fn(async () => ({ connection: null, prefill: null })),
setInstanceModel: vi.fn(async () => ADMIN_CONNECTION),
removeInstance: vi.fn(async () => undefined),
listInstanceModels: vi.fn(async () => []),
},
@@ -187,6 +188,7 @@ describe('AiAdminController', () => {
'saveSettings',
'connection',
'saveConnection',
'setModel',
'removeConnection',
'models',
'startOpenrouter',
@@ -198,6 +200,7 @@ describe('AiAdminController', () => {
{ method: RequestMethod.PUT, path: 'settings', httpCode: undefined },
{ method: RequestMethod.GET, path: 'connection', httpCode: undefined },
{ method: RequestMethod.PUT, path: 'connection', httpCode: undefined },
{ method: RequestMethod.PATCH, path: 'connection/model', httpCode: undefined },
{ method: RequestMethod.DELETE, path: 'connection', httpCode: 200 },
{ method: RequestMethod.GET, path: 'models', httpCode: undefined },
{ method: RequestMethod.POST, path: 'connect/openrouter/start', httpCode: 200 },
@@ -225,6 +228,9 @@ describe('AiAdminController', () => {
baseUrl: 'http://ollama:11434/v1',
model: 'llama',
});
// A model picked for everyone, the only way to switch a shared ChatGPT plan's (#2783).
expect(await controller.setModel(admin, { model: 'gpt-6.1-sol-mini' })).toBe(ADMIN_CONNECTION);
expect(s.connections.setInstanceModel).toHaveBeenCalledWith(1, 'gpt-6.1-sol-mini');
expect(await controller.removeConnection(admin)).toEqual({ success: true });
expect(await controller.models(admin)).toEqual({ models: [] });
await controller.startOpenrouter(admin);
@@ -316,6 +316,28 @@ describe('the instance connection', () => {
expect(service().readsImages({ ...haiku, model: 'claude-sonnet' })).toBe(true);
});
it("AICS-019: a shared ChatGPT plan's model is switched on its own, to one the plan offers (#2783)", async () => {
const admin = await user();
expect((await refusal(service().setInstanceModel(admin, 'claude-haiku'))).status).toBe(404);
await orm().em.fork().insert(AiConnections, { scope: 'instance', kind: 'chatgpt', model: 'claude-sonnet' });
audit.writeAudit.mockClear();
const saved = await service().setInstanceModel(admin, 'claude-haiku');
expect(catalog.list).toHaveBeenLastCalledWith({ kind: 'chatgpt', baseUrl: null, secret: 'chatgpt-access' });
expect(saved.connection).toMatchObject({ kind: 'chatgpt', model: 'claude-haiku' });
expect(audit.writeAudit).toHaveBeenCalledWith({
userId: admin,
action: 'ai.connection.saved',
details: { scope: 'instance', kind: 'chatgpt', model: 'claude-haiku' },
});
expect(await refusal(service().setInstanceModel(admin, 'nope'))).toMatchObject({
status: 422,
body: { code: 'unknown_model' },
});
expect((await service().instanceConnection()).connection?.model).toBe('claude-haiku');
await service().removeInstance(admin);
});
it('AICS-014: settings are read with their defaults and written back', async () => {
const admin = await user();
expect(await service().readSettings()).toEqual({