The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(assistant): let an admin switch the model of a shared ChatGPT plan
Mauriced911122a375f
diff --git a/client/src/api/assistant.ts b/client/src/api/assistant.tsindex 30ddf4459..82badd697 100644--- a/client/src/api/assistant.ts+++ b/client/src/api/assistant.ts@@ -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),};diff --git a/client/src/components/Admin/addons/useAiAdminConfig.test.ts b/client/src/components/Admin/addons/useAiAdminConfig.test.tsindex c8cc70393..81ce21f6e 100644--- a/client/src/components/Admin/addons/useAiAdminConfig.test.ts+++ b/client/src/components/Admin/addons/useAiAdminConfig.test.ts@@ -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();diff --git a/client/src/components/Admin/addons/useAiAdminConfig.ts b/client/src/components/Admin/addons/useAiAdminConfig.tsindex 90ac6eaf8..5c58b695f 100644--- a/client/src/components/Admin/addons/useAiAdminConfig.ts+++ b/client/src/components/Admin/addons/useAiAdminConfig.ts@@ -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 } : {}) }diff --git a/client/src/repo/aiConnectionsRepo.ts b/client/src/repo/aiConnectionsRepo.tsindex bfbd97ac4..9be470a02 100644--- a/client/src/repo/aiConnectionsRepo.ts+++ b/client/src/repo/aiConnectionsRepo.ts@@ -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();diff --git a/server/src/nest/ai-connections/ai-admin.controller.ts b/server/src/nest/ai-connections/ai-admin.controller.tsindex 83433af16..f4fd9eb72 100644--- a/server/src/nest/ai-connections/ai-admin.controller.ts+++ b/server/src/nest/ai-connections/ai-admin.controller.ts@@ -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)diff --git a/server/src/nest/ai-connections/ai-connections.service.ts b/server/src/nest/ai-connections/ai-connections.service.tsindex 5f030a3cd..0209e4ca4 100644--- a/server/src/nest/ai-connections/ai-connections.service.ts+++ b/server/src/nest/ai-connections/ai-connections.service.ts@@ -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');diff --git a/server/tests/e2e/ai-connections.e2e.test.ts b/server/tests/e2e/ai-connections.e2e.test.tsindex ebfe55e23..f4b25e5f8 100644--- a/server/tests/e2e/ai-connections.e2e.test.ts+++ b/server/tests/e2e/ai-connections.e2e.test.ts@@ -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({diff --git a/server/tests/unit/nest/ai-connections/ai-connections.controller.test.ts b/server/tests/unit/nest/ai-connections/ai-connections.controller.test.tsindex ae588595d..c69279c47 100644--- a/server/tests/unit/nest/ai-connections/ai-connections.controller.test.ts+++ b/server/tests/unit/nest/ai-connections/ai-connections.controller.test.ts@@ -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);diff --git a/server/tests/unit/nest/ai-connections/ai-connections.service.test.ts b/server/tests/unit/nest/ai-connections/ai-connections.service.test.tsindex 36b0b3f6b..6be56b8f6 100644--- a/server/tests/unit/nest/ai-connections/ai-connections.service.test.ts+++ b/server/tests/unit/nest/ai-connections/ai-connections.service.test.ts@@ -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({