fix(realtime): trip, member, chat, file, settings, tag and notification writes in parity

This commit is contained in:
Maurice
2026-10-22 12:14:27 +02:00
parent 94b8c3194c
commit ce7b5bf453
51 changed files with 2055 additions and 382 deletions
@@ -0,0 +1,41 @@
import { RealtimeService } from '../realtime/realtime.service';
import { SettingsService } from './settings.service';
import { Injectable } from '@nestjs/common';
import { MASKED_SETTING_VALUE } from '@trek/shared';
/**
* A user's own settings saved, for every surface, and their other tabs and
* devices told which keys changed so they read their settings again. The event
* names keys only, never a value: some keys hold secrets, and the receiving tab
* reads the values through its own session anyway.
*
* `socketId` is REST's requesting tab, which applied the change itself and is
* left out. MCP passes none, so the asking tab follows a change the assistant made.
*/
@Injectable()
export class SettingsWritesService {
constructor(
private readonly settings: SettingsService,
private readonly realtime: RealtimeService,
) {}
async saveOne(userId: number, key: string, value: unknown, socketId: string | undefined): Promise<void> {
await this.settings.upsertSetting(userId, key, value);
this.announce(userId, [key], socketId);
}
/** Answers how many rows were written. A masked secret echoed back is skipped, and named in no event. */
async saveMany(userId: number, values: Record<string, unknown>, socketId: string | undefined): Promise<number> {
const written = await this.settings.bulkUpsertSettings(userId, values);
this.announce(
userId,
Object.keys(values).filter((key) => values[key] !== MASKED_SETTING_VALUE),
socketId,
);
return written;
}
private announce(userId: number, keys: string[], socketId: string | undefined): void {
if (keys.length > 0) this.realtime.broadcastToUser(userId, { type: 'settings:updated', keys }, socketId);
}
}
@@ -7,9 +7,10 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { isManagedLockedKey, splitManagedKeys } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { SettingsWritesService } from './settings-writes.service';
import { AdminDefaultUserSettingsDto, SettingUpsertDto, SettingsBulkDto } from './settings.dto';
import { SettingsService, isAdminOnlyEndpointSetting } from './settings.service';
import { Body, Controller, Get, HttpCode, HttpException, Post, Put, Req, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, Headers, HttpCode, HttpException, Post, Put, Req, UseGuards } from '@nestjs/common';
import {
MASKED_SETTING_VALUE,
PLANNER_TRIP_VIEWS_KEY,
@@ -40,6 +41,8 @@ export class SettingsController {
constructor(
private readonly settings: SettingsService,
private readonly env: RuntimeEnvService,
// The writes, which tell the user's other tabs which keys changed.
private readonly writes: SettingsWritesService,
) {}
/**
@@ -87,7 +90,7 @@ export class SettingsController {
@Put()
@ResponseContract(settingUpsertResponseSchema)
async upsert(@CurrentUser() user: User, @Body() body: SettingUpsertDto) {
async upsert(@CurrentUser() user: User, @Body() body: SettingUpsertDto, @Headers('x-socket-id') socketId?: string) {
this.assertMayWriteInstanceEndpoint({ [body.key]: body.value });
this.assertValidValues({ [body.key]: body.value });
// assertMayWriteInstanceEndpoint only covers llm_base_url and provider 'local'.
@@ -100,19 +103,19 @@ export class SettingsController {
if (body.value === MASKED_SETTING_VALUE) {
return { success: true, key: body.key, unchanged: true };
}
await this.settings.upsertSetting(user.id, body.key, body.value);
await this.writes.saveOne(user.id, body.key, body.value, socketId);
return { success: true, key: body.key, value: body.value };
}
@Post('bulk')
@HttpCode(200) // Express answers bulk with res.json (200), not the POST-default 201.
@ResponseContract(settingsBulkResponseSchema)
async bulk(@CurrentUser() user: User, @Body() body: SettingsBulkDto) {
async bulk(@CurrentUser() user: User, @Body() body: SettingsBulkDto, @Headers('x-socket-id') socketId?: string) {
this.assertMayWriteInstanceEndpoint(body.settings);
this.assertValidValues(body.settings);
const { allowed, blocked } = splitManagedKeys(body.settings, this.env.isManaged());
try {
const updated = await this.settings.bulkUpsertSettings(user.id, allowed);
const updated = await this.writes.saveMany(user.id, allowed, socketId);
return { success: true, updated, ...(blocked.length ? { managed_keys: blocked } : {}) };
} catch (err) {
console.error('Error saving settings:', err);
+7 -2
View File
@@ -7,6 +7,7 @@ import {
errorResult,
ok,
} from '../../nest-mcp';
import { SettingsWritesService } from './settings-writes.service';
import { SettingsService } from './settings.service';
import {
MASKED_SETTING_VALUE,
@@ -110,7 +111,10 @@ const KEY_LIST = DISPLAY_PREFERENCE_KEYS.join(', ');
*/
@McpController()
export class SettingsMcp {
constructor(private readonly settings: SettingsService) {}
constructor(
private readonly settings: SettingsService,
private readonly writes: SettingsWritesService,
) {}
/**
* getUserSettings resolves admin defaults and the managed-install token
@@ -182,7 +186,8 @@ export class SettingsMcp {
validated[key] = parsed.data;
}
const updated = await this.settings.bulkUpsertSettings(ctx.userId, validated);
// Every tab of the user, the asking one included, reads its settings again.
const updated = await this.writes.saveMany(ctx.userId, validated, undefined);
// Read back rather than echoing the input: an admin default or the managed
// token injection can still shape what the user ends up seeing.
return ok({ success: true, updated, settings: await this.readDisplayPreferences(ctx.userId) });
+11 -2
View File
@@ -2,7 +2,9 @@ import { AppSettings } from '../../db/entities/AppSettings.entity';
import { Settings } from '../../db/entities/Settings.entity';
import { AppConfigModule } from '../app-config/app-config.module';
import { AuditModule } from '../audit/audit.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { SettingsWritesService } from './settings-writes.service';
import { AdminDefaultUserSettingsController, SettingsController } from './settings.controller';
import { SettingsMcp } from './settings.mcp';
import { SettingsService } from './settings.service';
@@ -26,9 +28,16 @@ import { Module } from '@nestjs/common';
// `@InjectRepository(Users)`. TripMembershipModule is here for the planner
// view row (#2639), which keeps only trips the user can still open: the
// trips table belongs to another domain, so the ids come from its service.
imports: [AppConfigModule, AuditModule, TripMembershipModule, MikroOrmModule.forFeature([AppSettings, Settings])],
// RealtimeModule for SettingsWritesService, which tells a user's other tabs which keys changed.
imports: [
AppConfigModule,
AuditModule,
TripMembershipModule,
RealtimeModule,
MikroOrmModule.forFeature([AppSettings, Settings]),
],
controllers: [SettingsController, AdminDefaultUserSettingsController],
providers: [SettingsService, SettingsMcp],
providers: [SettingsService, SettingsWritesService, SettingsMcp],
exports: [SettingsService],
})
export class SettingsModule {}