Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(session): allow the tunable session config to be changed after creation

Yudhi Armyndharisd06425cef9df
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index f697d53ed..3cf2c7fb4 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -367,6 +367,20 @@ clears it, and so does a gateway restart.
| `reconnectBaseDelay` | `5000` ms | Base delay of the reconnect backoff, clamped to 1000–300000 ms |
| `autoRejectCalls` | `false` | Auto-reject an incoming call as soon as it rings |
+Set them at creation with `POST /api/sessions`, or on an existing session with
+`PATCH /api/sessions/{id}/config` — no restart, and no re-scan of the QR. The patch merges, so a key
+it does not mention keeps its stored value, and an explicit `null` clears a key back to the default
+above (the only way back to unlimited reconnect attempts once a cap is set).
+
+When each takes effect differs, because each is read at a different moment: `autoRejectCalls` is
+re-read from this row on every incoming call, so a patch applies to the next call. The two reconnect
+keys are read once per `start()` into the in-memory reconnect state, so a patch applies on the next
+start and leaves a reconnect sequence already in flight alone.
+
+`GET /api/sessions/{id}/config` reports the effective values. It reports only these three keys and
+never the raw column — `config` is stripped from `SessionResponseDto` alongside the
+credential-bearing `proxyUrl`, and echoing an opaque blob back would defeat that.
+
> [!NOTE]
> Proxy settings are **not** read from `config` — they live in the dedicated `proxyUrl` / `proxyType` columns shown in the DDL above. Puppeteer options are global engine configuration from the environment (`engine.puppeteer.*`), not per-session. Anything else placed in `config` is stored but ignored.
diff --git a/openapi.json b/openapi.json
index f0a02a3ca..c6b5955f8 100644
--- a/openapi.json
+++ b/openapi.json
@@ -25,6 +25,7 @@
"session_force_killed",
"session_logged_out",
"session_deleted",
+ "session_config_updated",
"session_qr_generated",
"session_connected",
"session_disconnected",
@@ -472,6 +473,88 @@
]
}
},
+ "/api/sessions/{id}/config": {
+ "get": {
+ "operationId": "SessionController_getConfig",
+ "parameters": [
+ {
+ "name": "id",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Effective session configuration",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SessionConfigResponseDto"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Session not found"
+ }
+ },
+ "summary": "Get the tunable configuration for a session",
+ "tags": [
+ "sessions"
+ ]
+ },
+ "patch": {
+ "description": "Merges the supplied keys into the session config; omitted keys are left unchanged and an explicit null clears a key back to its default. No restart is required or performed. `autoRejectCalls` is re-read on every incoming call, so it applies immediately; the two reconnect settings are read once per start and therefore apply on the next start.",
+ "operationId": "SessionController_updateConfig",
+ "parameters": [
+ {
+ "name": "id",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateSessionConfigDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Updated session configuration",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SessionConfigResponseDto"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "A supplied value is outside its accepted range"
+ },
+ "404": {
+ "description": "Session not found"
+ }
+ },
+ "summary": "Update the tunable configuration for a session",
+ "tags": [
+ "sessions"
+ ]
+ }
+ },
"/api/sessions/{id}/start": {
"post": {
"operationId": "SessionController_start",
@@ -8329,9 +8412,11 @@
},
"config": {
"type": "object",
- "description": "Session configuration options. Set autoRejectCalls (boolean, default false) to automatically reject incoming calls — the call.received event is still emitted.",
+ "description": "Session configuration. Only three keys are read: autoRejectCalls (boolean, default false) rejects incoming calls as soon as they ring — the call.received event is still emitted first; maxReconnectAttempts (0-20, default unlimited) caps consecutive reconnects; and reconnectBaseDelay (1000-300000 ms, default 5000) sets the backoff base. Anything else is stored but ignored. All three can be changed later with PATCH /api/sessions/{id}/config, without restarting the session.",
"example": {
- "autoReconnect": true
+ "autoRejectCalls": false,
+ "maxReconnectAttempts": 5,
+ "reconnectBaseDelay": 5000
}
},
"proxyUrl": {
@@ -8473,6 +8558,59 @@
"engineLoaded"
]
},
+ "SessionConfigResponseDto": {
+ "type": "object",
+ "properties": {
+ "autoRejectCalls": {
+ "type": "boolean",
+ "description": "Whether incoming calls are auto-rejected",
+ "example": false
+ },
+ "maxReconnectAttempts": {
+ "type": "object",
+ "description": "Reconnect attempt cap; `null` means unlimited",
+ "example": 5,
+ "nullable": true
+ },
+ "reconnectBaseDelay": {
+ "type": "number",
+ "description": "Base reconnect backoff in milliseconds",
+ "example": 5000
+ }
+ },
+ "required": [
+ "autoRejectCalls",
+ "maxReconnectAttempts",
+ "reconnectBaseDelay"
+ ]
+ },
+ "UpdateSessionConfigDto": {
+ "type": "object",
+ "properties": {
+ "autoRejectCalls": {
+ "type": "object",
+ "description": "Auto-reject every incoming call as soon as it rings. The call.received event is still emitted first, so a webhook consumer sees the call regardless. Takes effect on the next incoming call — the session is not restarted.",
+ "example": true,
+ "nullable": true
+ },
+ "maxReconnectAttempts": {
+ "type": "object",
+ "description": "Cap on consecutive reconnect attempts (`0` disables reconnect entirely). Send `null` for unlimited, which is the default. Applies on the next session start, not to a reconnect sequence already in flight.",
+ "minimum": 0,
+ "maximum": 20,
+ "example": 5,
+ "nullable": true
+ },
+ "reconnectBaseDelay": {
+ "type": "object",
+ "description": "Base delay of the reconnect backoff in milliseconds. Applies on the next session start, not to a reconnect sequence already in flight.",
+ "minimum": 1000,
+ "maximum": 300000,
+ "example": 5000,
+ "nullable": true
+ }
+ }
+ },
"QRCodeResponseDto": {
"type": "object",
"properties": {
diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.ts
index c2efd8c98..25f9c2bfd 100644
--- a/src/modules/audit/entities/audit-log.entity.ts
+++ b/src/modules/audit/entities/audit-log.entity.ts
@@ -23,6 +23,7 @@ export enum AuditAction {
SESSION_FORCE_KILLED = 'session_force_killed',
SESSION_LOGGED_OUT = 'session_logged_out',
SESSION_DELETED = 'session_deleted',
+ SESSION_CONFIG_UPDATED = 'session_config_updated',
SESSION_QR_GENERATED = 'session_qr_generated',
SESSION_CONNECTED = 'session_connected',
SESSION_DISCONNECTED = 'session_disconnected',
diff --git a/src/modules/session/dto/create-session.dto.ts b/src/modules/session/dto/create-session.dto.ts
index fc49daa58..8f17b0135 100644
--- a/src/modules/session/dto/create-session.dto.ts
+++ b/src/modules/session/dto/create-session.dto.ts
@@ -18,9 +18,13 @@ export class CreateSessionDto {
@ApiPropertyOptional({
description:
- 'Session configuration options. Set autoRejectCalls (boolean, default false) to ' +
- 'automatically reject incoming calls — the call.received event is still emitted.',
- example: { autoReconnect: true },
+ 'Session configuration. Only three keys are read: autoRejectCalls (boolean, default false) ' +
+ 'rejects incoming calls as soon as they ring — the call.received event is still emitted ' +
+ 'first; maxReconnectAttempts (0-20, default unlimited) caps consecutive reconnects; and ' +
+ 'reconnectBaseDelay (1000-300000 ms, default 5000) sets the backoff base. Anything else is ' +
+ 'stored but ignored. All three can be changed later with PATCH /api/sessions/{id}/config, ' +
+ 'without restarting the session.',
+ example: { autoRejectCalls: false, maxReconnectAttempts: 5, reconnectBaseDelay: 5000 },
})
@IsOptional()
config?: Record<string, unknown>;
diff --git a/src/modules/session/dto/index.ts b/src/modules/session/dto/index.ts
index e2e090a6f..3521dc185 100644
--- a/src/modules/session/dto/index.ts
+++ b/src/modules/session/dto/index.ts
@@ -1,4 +1,5 @@
export * from './create-session.dto';
+export * from './session-config.dto';
export * from './session-response.dto';
export * from './mark-chat-read.dto';
export * from './archive-chat.dto';
diff --git a/src/modules/session/dto/session-config.dto.spec.ts b/src/modules/session/dto/session-config.dto.spec.ts
new file mode 100644
index 000000000..d2e5baa43
--- /dev/null
+++ b/src/modules/session/dto/session-config.dto.spec.ts
@@ -0,0 +1,84 @@
+import { validateSync } from 'class-validator';
+import { plainToInstance } from 'class-transformer';
+import { UpdateSessionConfigDto } from './session-config.dto';
+
+/**
+ * Instantiate the way the global pipe does (src/config/app-validation.ts), including
+ * `enableImplicitConversion`. Validating a hand-built instance instead would pass while the real
+ * request path fails: implicit conversion runs BEFORE the validators and is the whole hazard here.
+ */
+const parse = (body: Record<string, unknown>): UpdateSessionConfigDto =>
+ plainToInstance(UpdateSessionConfigDto, body, { enableImplicitConversion: true });
+
+const errorsFor = (body: Record<string, unknown>): ReturnType<typeof validateSync> => validateSync(parse(body));
+
+describe('UpdateSessionConfigDto', () => {
+ it('accepts an empty body — every key is optional', () => {
+ expect(errorsFor({})).toHaveLength(0);
+ });
+
+ describe('null clears a key', () => {
+ it.each(['autoRejectCalls', 'maxReconnectAttempts', 'reconnectBaseDelay'])(
+ 'accepts an explicit null for %s and preserves it as null',
+ key => {
+ expect(errorsFor({ [key]: null })).toHaveLength(0);
+ // The service distinguishes null (delete the key) from undefined (leave it alone), so the
+ // null must survive transformation as a real null rather than being coerced or dropped.
+ expect(parse({ [key]: null })[key as keyof UpdateSessionConfigDto]).toBeNull();
+ },
+ );
+ });
+
+ describe('autoRejectCalls', () => {
+ it.each([
+ [true, true],
+ [false, false],
+ ['true', true],
+ ['false', false],
+ ])('reads %p as %p', (input, expected) => {
+ expect(errorsFor({ autoRejectCalls: input })).toHaveLength(0);
+ expect(parse({ autoRejectCalls: input }).autoRejectCalls).toBe(expected);
+ });
+
+ it("does not turn the string 'false' into true", () => {
+ // The regression @ToStrictBoolean exists for: with enableImplicitConversion, class-transformer
+ // casts ANY non-empty string to true before @IsBoolean() can object. A form-encoded body
+ // delivers scalars as strings, so an operator turning the toggle OFF would turn it ON.
+ expect(parse({ autoRejectCalls: 'false' }).autoRejectCalls).toBe(false);
+ });
+
+ it.each(['yes', '1', 'off', ''])('rejects the ambiguous spelling %p rather than guessing', input => {
+ expect(errorsFor({ autoRejectCalls: input }).length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('bounds mirror resolveReconnectConfig', () => {
+ it.each([0, 1, 20])('accepts maxReconnectAttempts %i', v => {
+ expect(errorsFor({ maxReconnectAttempts: v })).toHaveLength(0);
+ });
+
+ it.each([-1, 21, 1.5])('rejects maxReconnectAttempts %p', v => {
+ expect(errorsFor({ maxReconnectAttempts: v }).length).toBeGreaterThan(0);
+ });
+
+ it.each([1000, 5000, 300000])('accepts reconnectBaseDelay %i', v => {
+ expect(errorsFor({ reconnectBaseDelay: v })).toHaveLength(0);
+ });
+
+ it.each([999, 300001, 2.5])('rejects reconnectBaseDelay %p', v => {
+ expect(errorsFor({ reconnectBaseDelay: v }).length).toBeGreaterThan(0);
+ });
+
+ it('rejects a non-numeric string instead of silently reading it as 0', () => {
+ // Number('') and Number(' ') are both 0, and 0 means "never reconnect" — a meaningful value.
+ // @ToStrictNumber leaves these unconverted so @IsInt() rejects them.
+ expect(errorsFor({ maxReconnectAttempts: '' }).length).toBeGreaterThan(0);
+ expect(errorsFor({ maxReconnectAttempts: 'lots' }).length).toBeGreaterThan(0);
+ });
+
+ it('accepts a numeric string, which is how a form-encoded body arrives', () => {
+ expect(errorsFor({ reconnectBaseDelay: '5000' })).toHaveLength(0);
+ expect(parse({ reconnectBaseDelay: '5000' }).reconnectBaseDelay).toBe(5000);
+ });
+ });
+});
diff --git a/src/modules/session/dto/session-config.dto.ts b/src/modules/session/dto/session-config.dto.ts
new file mode 100644
index 000000000..8237bc08a
--- /dev/null
+++ b/src/modules/session/dto/session-config.dto.ts
@@ -0,0 +1,88 @@
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
+import { IsBoolean, IsInt, IsOptional, Max, Min } from 'class-validator';
+import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';
+
+/**
+ * The three keys the session service actually reads out of the opaque `config` column. Anything
+ * else stored there is ignored (see docs/05-database-design.md), so this DTO is the whole tunable
+ * surface rather than a subset of it.
+ *
+ * Omitting a key leaves it unchanged; sending `null` clears it back to the default. The null case
+ * is not decoration: `maxReconnectAttempts` defaults to unlimited, which no in-range number can
+ * express, so without it a session could never be returned to unlimited retries once capped.
+ *
+ * The bounds mirror resolveReconnectConfig's clamps exactly. Duplicating them as validation turns a
+ * silent clamp into a 400 that names the real range — the clamp still runs at use time and remains
+ * the authority for rows written before this endpoint existed.
+ */
+export class UpdateSessionConfigDto {
+ @ApiPropertyOptional({
+ description:
+ 'Auto-reject every incoming call as soon as it rings. The call.received event is still ' +
+ 'emitted first, so a webhook consumer sees the call regardless. Takes effect on the next ' +
+ 'incoming call — the session is not restarted.',
+ example: true,
+ nullable: true,
+ })
+ @ToStrictBoolean()
+ @IsOptional()
+ @IsBoolean()
+ autoRejectCalls?: boolean | null;
+
+ @ApiPropertyOptional({
+ description:
+ 'Cap on consecutive reconnect attempts (`0` disables reconnect entirely). Send `null` for ' +
+ 'unlimited, which is the default. Applies on the next session start, not to a reconnect ' +
+ 'sequence already in flight.',
+ minimum: 0,
+ maximum: 20,
+ example: 5,
+ nullable: true,
+ })
+ @ToStrictNumber()
+ @IsOptional()
+ @IsInt()
+ @Min(0)
+ @Max(20)
+ maxReconnectAttempts?: number | null;
+
+ @ApiPropertyOptional({
+ description:
+ 'Base delay of the reconnect backoff in milliseconds. Applies on the next session start, ' +
+ 'not to a reconnect sequence already in flight.',
+ minimum: 1000,
+ maximum: 300000,
+ example: 5000,
+ nullable: true,
+ })
+ @ToStrictNumber()
+ @IsOptional()
+ @IsInt()
+ @Min(1000)
+ @Max(300000)
+ reconnectBaseDelay?: number | null;
+}
+
+/**
+ * The effective configuration, not the stored blob. `config` is deliberately stripped from
+ * SessionResponseDto because it is an opaque column an operator may have put anything into
+ * (alongside the credential-bearing proxyUrl) — echoing it back would leak that. Reporting only
+ * the three recognised keys keeps that guarantee while still letting a caller confirm what landed.
+ *
+ * Values are resolved through resolveReconnectConfig, so what is reported is what the engine will
+ * actually do, including for legacy rows whose stored values fall outside the accepted range.
+ */
+export class SessionConfigResponseDto {
+ @ApiProperty({ description: 'Whether incoming calls are auto-rejected', example: false })
+ autoRejectCalls!: boolean;
+
+ @ApiProperty({
+ description: 'Reconnect attempt cap; `null` means unlimited',
+ example: 5,
+ nullable: true,
+ })
+ maxReconnectAttempts!: number | null;
+
+ @ApiProperty({ description: 'Base reconnect backoff in milliseconds', example: 5000 })
+ reconnectBaseDelay!: number;
+}
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 2e08ef35f..1926a3f56 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -1,8 +1,22 @@
-import { Controller, Get, Post, Delete, Param, Query, Body, HttpCode, HttpStatus, ParseUUIDPipe } from '@nestjs/common';
+import {
+ Controller,
+ Get,
+ Post,
+ Patch,
+ Delete,
+ Param,
+ Query,
+ Body,
+ HttpCode,
+ HttpStatus,
+ ParseUUIDPipe,
+} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
import { SessionService } from './session.service';
import {
CreateSessionDto,
+ SessionConfigResponseDto,
+ UpdateSessionConfigDto,
SessionResponseDto,
QRCodeResponseDto,
MarkChatReadDto,
@@ -98,6 +112,51 @@ export class SessionController {
return this.transformSession(session);
}
+ @Get(':id/config')
+ @ApiOperation({ summary: 'Get the tunable configuration for a session' })
+ @ApiParam({ name: 'id', description: 'Session ID' })
+ @ApiResponse({
+ status: 200,
+ description: 'Effective session configuration',
+ type: SessionConfigResponseDto,
+ })
+ @ApiResponse({ status: 404, description: 'Session not found' })
+ async getConfig(@Param('id', ParseUUIDPipe) id: string): Promise<SessionConfigResponseDto> {
+ return this.sessionService.getConfig(id);
+ }
+
+ @Patch(':id/config')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @ApiOperation({
+ summary: 'Update the tunable configuration for a session',
+ description:
+ 'Merges the supplied keys into the session config; omitted keys are left unchanged and an ' +
+ 'explicit null clears a key back to its default. No restart is required or performed. ' +
+ '`autoRejectCalls` is re-read on every incoming call, so it applies immediately; the two ' +
+ 'reconnect settings are read once per start and therefore apply on the next start.',
+ })
+ @ApiParam({ name: 'id', description: 'Session ID' })
+ @ApiResponse({
+ status: 200,
+ description: 'Updated session configuration',
+ type: SessionConfigResponseDto,
+ })
+ @ApiResponse({ status: 400, description: 'A supplied value is outside its accepted range' })
+ @ApiResponse({ status: 404, description: 'Session not found' })
+ async updateConfig(
+ @Param('id', ParseUUIDPipe) id: string,
+ @Body() dto: UpdateSessionConfigDto,
+ ): Promise<SessionConfigResponseDto> {
+ const config = await this.sessionService.updateConfig(id, dto);
+ await this.auditService.logInfo(AuditAction.SESSION_CONFIG_UPDATED, {
+ sessionId: id,
+ // The resulting state, not the request: a merge patch is meaningless in an audit trail without
+ // knowing what it merged into. Only the three recognised keys, never the raw column.
+ metadata: { ...config },
+ });
+ return config;
+ }
+
@Delete(':id')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.NO_CONTENT)
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index e432fb403..17d2375df 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -5894,4 +5894,84 @@ describe('SessionService', () => {
expect(replacement.initialize).not.toHaveBeenCalled();
});
});
+
+ describe('session config', () => {
+ const writtenConfig = (): Record<string, unknown> => {
+ const calls = (repository.update as jest.Mock).mock.calls as unknown[][];
+ return (calls[0][1] as { config: Record<string, unknown> }).config;
+ };
+
+ beforeEach(() => {
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ });
+
+ it('reports the documented defaults for a session that has never been configured', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ config: {} }));
+
+ // maxReconnectAttempts is unlimited by default, which no in-range number can express — it has
+ // to serialise as null, not as the cap.
+ await expect(service.getConfig('sess-uuid-1')).resolves.toEqual({
+ autoRejectCalls: false,
+ maxReconnectAttempts: null,
+ reconnectBaseDelay: 5000,
+ });
+ });
+
+ it('merges into the opaque column, leaving keys it does not own untouched', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(
+ createMockSession({ config: { autoRejectCalls: false, somethingOperatorPutHere: 'keep me' } }),
+ );
+
+ await service.updateConfig('sess-uuid-1', { autoRejectCalls: true });
+
+ expect(writtenConfig()).toEqual({ autoRejectCalls: true, somethingOperatorPutHere: 'keep me' });
+ });
+
+ it('deletes a key on an explicit null, which is the only route back to unlimited reconnects', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(
+ createMockSession({ config: { maxReconnectAttempts: 5, autoRejectCalls: true } }),
+ );
+
+ const result = await service.updateConfig('sess-uuid-1', { maxReconnectAttempts: null });
+
+ // Deleted outright rather than written as null: resolveReconnectConfig reads Number(null) as 0,
+ // so a stored null would mean "never reconnect" — the exact opposite of the default it restores.
+ expect(writtenConfig()).not.toHaveProperty('maxReconnectAttempts');
+ expect(writtenConfig()).toEqual({ autoRejectCalls: true });
+ expect(result.maxReconnectAttempts).toBeNull();
+ });
+
+ it('leaves a key alone when the request simply omits it', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(
+ createMockSession({ config: { maxReconnectAttempts: 5, reconnectBaseDelay: 9000 } }),
+ );
+
+ await service.updateConfig('sess-uuid-1', { autoRejectCalls: true });
+
+ expect(writtenConfig()).toEqual({ maxReconnectAttempts: 5, reconnectBaseDelay: 9000, autoRejectCalls: true });
+ });
+
+ it('does not read a truthy non-boolean as opted in, matching maybeAutoRejectCall', async () => {
+ // The column is opaque, so a legacy row can hold anything. maybeAutoRejectCall gates on
+ // `=== true`; reporting 'yes' as enabled here would tell an operator calls are being rejected
+ // when the engine will never reject one.
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ config: { autoRejectCalls: 'yes' } }));
+
+ await expect(service.getConfig('sess-uuid-1')).resolves.toMatchObject({ autoRejectCalls: false });
+ });
+
+ it('reports an out-of-range legacy value as the engine will actually apply it', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(
+ createMockSession({ config: { maxReconnectAttempts: 999, reconnectBaseDelay: 1 } }),
+ );
+
+ // Written before this endpoint existed, so it never passed the DTO bounds. The clamp is still
+ // the authority at use time, and this must agree with it rather than echo the stored value.
+ await expect(service.getConfig('sess-uuid-1')).resolves.toEqual({
+ autoRejectCalls: false,
+ maxReconnectAttempts: 20,
+ reconnectBaseDelay: 1000,
+ });
+ });
+ });
});
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 41c96c5e5..3363474c2 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -11,16 +11,17 @@ import {
import { ConfigService } from '@nestjs/config';
import { InjectRepository, InjectDataSource } from '@nestjs/typeorm';
import { Repository, In, Not, IsNull, DataSource, FindManyOptions } from 'typeorm';
+import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { Session, SessionStatus } from './entities/session.entity';
import { Message } from '../message/entities/message.entity';
-import { CreateSessionDto } from './dto';
+import { CreateSessionDto, SessionConfigResponseDto, UpdateSessionConfigDto } from './dto';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { SessionLidResolver } from './session-lid-resolver.service';
import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
import { SessionErrorStore } from './session-error-store.service';
import { SessionRestrictionStore } from './session-restriction-store.service';
import { PresenceStore, type ChatPresence } from './presence-store.service';
-import { SessionEngineLifecycle } from './session-engine-lifecycle.service';
+import { SessionEngineLifecycle, resolveReconnectConfig } from './session-engine-lifecycle.service';
import { SessionOwnershipService } from './session-ownership.service';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
@@ -274,6 +275,62 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return session;
}
+ /**
+ * Project the opaque `config` column onto the three keys the engine actually reads, resolved
+ * through the same clamp the engine uses — so a legacy row holding an out-of-range value reports
+ * what will really happen rather than what someone once wrote.
+ */
+ private projectConfig(config: Record<string, unknown>): SessionConfigResponseDto {
+ const { maxAttempts, baseDelay } = resolveReconnectConfig(config);
+ return {
+ // Strict `=== true` mirrors maybeAutoRejectCall: a truthy string or 1 left in the opaque blob
+ // must not read as opted in here when it would not opt in there.
+ autoRejectCalls: config?.autoRejectCalls === true,
+ maxReconnectAttempts: Number.isFinite(maxAttempts) ? maxAttempts : null,
+ reconnectBaseDelay: baseDelay,
+ };
+ }
+
+ async getConfig(id: string): Promise<SessionConfigResponseDto> {
+ const session = await this.findOne(id);
+ return this.projectConfig(session.config ?? {});
+ }
+
+ /**
+ * Merge the supplied keys into `config` and persist. Merge rather than replace: the column is
+ * documented as an opaque blob, so a key this endpoint does not know about belongs to the
+ * operator and must survive a write that never mentioned it.
+ *
+ * An explicit `null` deletes the key, which is the only way back to a default that no in-range
+ * value can express (`maxReconnectAttempts` unlimited). `undefined` — the key simply absent from
+ * the request — leaves the stored value alone.
+ *
+ * No restart, and deliberately no engine call: `autoRejectCalls` is re-read from this row on
+ * every incoming call, so the write alone is what takes effect. The reconnect pair is read once
+ * per start() into reconnectStates, so it lands on the next start; that asymmetry is documented
+ * on the DTO rather than papered over by forcing a reconnect nobody asked for.
+ */
+ async updateConfig(id: string, dto: UpdateSessionConfigDto): Promise<SessionConfigResponseDto> {
+ const session = await this.findOne(id);
+ const config = { ...(session.config ?? {}) };
+
+ for (const key of ['autoRejectCalls', 'maxReconnectAttempts', 'reconnectBaseDelay'] as const) {
+ const value = dto[key];
+ if (value === undefined) continue;
+ if (value === null) {
+ delete config[key];
+ } else {
+ config[key] = value;
+ }
+ }
+
+ // update() with an explicit object rather than save() on the loaded entity: the entity carries
+ // runtime-attached fields (lastError, restriction) that no column backs, and save() would try to
+ // write the whole row back from a snapshot taken before this await.
+ await this.sessionRepository.update(id, { config: config as QueryDeepPartialEntity<Record<string, unknown>> });
+ return this.projectConfig(config);
+ }
+
/** Record removal + engine retirement + credential purge: owned by the lifecycle service. */
async delete(id: string): Promise<void> {
// Set the tearing-down mark SYNCHRONOUSLY, before the ownership fence's awaited query. The