Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style: get user timezone when open (#12567)

Arvin Xu16946a4d5b21
diff --git a/packages/types/src/user/settings/general.ts b/packages/types/src/user/settings/general.ts
index 8035d4b64bc..a18acbad330 100644
--- a/packages/types/src/user/settings/general.ts
+++ b/packages/types/src/user/settings/general.ts
@@ -23,5 +23,6 @@ export interface UserGeneralConfig {
primaryColor?: PrimaryColors;
responseLanguage?: string;
telemetry: boolean;
+ timezone?: string;
transitionMode?: ResponseAnimationStyle;
}
diff --git a/src/libs/next/proxy/define-config.ts b/src/libs/next/proxy/define-config.ts
index a717b824065..1d30af2e16f 100644
--- a/src/libs/next/proxy/define-config.ts
+++ b/src/libs/next/proxy/define-config.ts
@@ -241,11 +241,7 @@ export function defineConfig() {
return response;
};
- logDefault('Middleware configuration: %O', {
- enableOIDC: authEnv.ENABLE_OIDC,
- });
+ logDefault('Middleware configuration: %O', { enableOIDC: authEnv.ENABLE_OIDC });
- return {
- middleware: betterAuthMiddleware,
- };
+ return { middleware: betterAuthMiddleware };
}
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.ts
index df7e4524bd4..203d3b0bbe8 100644
--- a/src/server/services/bot/AgentBridgeService.ts
+++ b/src/server/services/bot/AgentBridgeService.ts
@@ -4,7 +4,8 @@ import { emoji } from 'chat';
import debug from 'debug';
import urlJoin from 'url-join';
-import { getServerDB } from '@/database/core/db-adaptor';
+import { UserModel } from '@/database/models/user';
+import type { LobeChatDatabase } from '@/database/type';
import { appEnv } from '@/envs/app';
import { AiAgentService } from '@/server/services/aiAgent';
import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
@@ -65,16 +66,28 @@ async function safeReaction(fn: () => Promise<void>, label: string): Promise<voi
interface BridgeHandlerOpts {
agentId: string;
botContext?: ChatTopicBotContext;
- userId: string;
}
/**
* Platform-agnostic bridge between Chat SDK events and Agent Runtime.
*
- * Uses in-process onComplete callback to get agent execution results.
+ * Each instance is bound to a specific (serverDB, userId) pair,
+ * following the same pattern as other server services (AiAgentService, UserModel, etc.).
+ *
* Provides real-time feedback via emoji reactions and editable progress messages.
*/
export class AgentBridgeService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+
+ private timezone: string | undefined;
+ private timezoneLoaded = false;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.db = db;
+ this.userId = userId;
+ }
+
/**
* Handle a new @mention — start a fresh conversation.
*/
@@ -83,9 +96,14 @@ export class AgentBridgeService {
message: Message,
opts: BridgeHandlerOpts,
): Promise<void> {
- const { agentId, botContext, userId } = opts;
+ const { agentId, botContext } = opts;
- log('handleMention: agentId=%s, user=%s, text=%s', agentId, userId, message.text.slice(0, 80));
+ log(
+ 'handleMention: agentId=%s, user=%s, text=%s',
+ agentId,
+ this.userId,
+ message.text.slice(0, 80),
+ );
// Immediate feedback: mark as received + show typing
await safeReaction(
@@ -102,7 +120,6 @@ export class AgentBridgeService {
agentId,
botContext,
trigger: 'bot',
- userId,
});
// Persist topic mapping in thread state for follow-up messages
@@ -128,7 +145,7 @@ export class AgentBridgeService {
message: Message,
opts: BridgeHandlerOpts,
): Promise<void> {
- const { agentId, botContext, userId } = opts;
+ const { agentId, botContext } = opts;
const threadState = await thread.state;
const topicId = threadState?.topicId;
@@ -136,7 +153,7 @@ export class AgentBridgeService {
if (!topicId) {
log('handleSubscribedMessage: no topicId in thread state, treating as new mention');
- return this.handleMention(thread, message, { agentId, botContext, userId });
+ return this.handleMention(thread, message, { agentId, botContext });
}
// Immediate feedback: mark as received + show typing
@@ -153,7 +170,6 @@ export class AgentBridgeService {
botContext,
topicId,
trigger: 'bot',
- userId,
});
} catch (error) {
log('handleSubscribedMessage error: %O', error);
@@ -175,7 +191,6 @@ export class AgentBridgeService {
botContext?: ChatTopicBotContext;
topicId?: string;
trigger?: string;
- userId: string;
},
): Promise<{ reply: string; topicId: string }> {
if (isQueueAgentRuntimeEnabled()) {
@@ -197,18 +212,17 @@ export class AgentBridgeService {
botContext?: ChatTopicBotContext;
topicId?: string;
trigger?: string;
- userId: string;
},
): Promise<{ reply: string; topicId: string }> {
- const { agentId, botContext, userId, topicId, trigger } = opts;
+ const { agentId, botContext, topicId, trigger } = opts;
- const serverDB = await getServerDB();
- const aiAgentService = new AiAgentService(serverDB, userId);
+ const aiAgentService = new AiAgentService(this.db, this.userId);
+ const timezone = await this.loadTimezone();
// Post initial progress message to get the message ID
let progressMessage: SentMessage | undefined;
try {
- progressMessage = await thread.post(renderStart(userMessage.text));
+ progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
} catch (error) {
log('executeWithWebhooks: failed to post progress message: %O', error);
}
@@ -274,18 +288,17 @@ export class AgentBridgeService {
botContext?: ChatTopicBotContext;
topicId?: string;
trigger?: string;
- userId: string;
},
): Promise<{ reply: string; topicId: string }> {
- const { agentId, botContext, userId, topicId, trigger } = opts;
+ const { agentId, botContext, topicId, trigger } = opts;
- const serverDB = await getServerDB();
- const aiAgentService = new AiAgentService(serverDB, userId);
+ const aiAgentService = new AiAgentService(this.db, this.userId);
+ const timezone = await this.loadTimezone();
// Post initial progress message
let progressMessage: SentMessage | undefined;
try {
- progressMessage = await thread.post(renderStart(userMessage.text));
+ progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
} catch (error) {
log('executeWithInMemoryCallbacks: failed to post progress message: %O', error);
}
@@ -430,6 +443,26 @@ export class AgentBridgeService {
});
}
+ /**
+ * Lazily load and cache user timezone from settings.
+ */
+ private async loadTimezone(): Promise<string | undefined> {
+ if (this.timezoneLoaded) return this.timezone;
+
+ try {
+ const userModel = new UserModel(this.db, this.userId);
+ const settings = await userModel.getUserSettings();
+ this.timezone = (settings?.general as Record<string, unknown>)?.timezone as
+ | string
+ | undefined;
+ } catch {
+ // Fall back to server time if settings can't be loaded
+ }
+
+ this.timezoneLoaded = true;
+ return this.timezone;
+ }
+
/**
* Remove the received reaction from a user message (fire-and-forget).
*/
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index ea6e9e96a15..05d0ff873af 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -5,6 +5,7 @@ import debug from 'debug';
import { getServerDB } from '@/database/core/db-adaptor';
import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
+import type { LobeChatDatabase } from '@/database/type';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
@@ -28,8 +29,6 @@ interface DiscordCredentials {
* and triggers message processing via AgentBridgeService.
*/
export class BotMessageRouter {
- private bridge = new AgentBridgeService();
-
/** botToken → Chat instance (for webhook routing via x-discord-gateway-token) */
private botInstancesByToken = new Map<string, Chat<any>>();
@@ -221,7 +220,12 @@ export class BotMessageRouter {
};
const bot = this.createBot(adapters, `agent-${agentId}`);
- this.registerHandlers(bot, { agentId, applicationId, platform: 'discord', userId });
+ this.registerHandlers(bot, serverDB, {
+ agentId,
+ applicationId,
+ platform: 'discord',
+ userId,
+ });
await bot.initialize();
this.botInstances.set(applicationId, bot);
@@ -256,16 +260,17 @@ export class BotMessageRouter {
private registerHandlers(
bot: Chat<any>,
+ serverDB: LobeChatDatabase,
info: ResolvedAgentInfo & { applicationId: string; platform: string },
): void {
const { agentId, applicationId, platform, userId } = info;
+ const bridge = new AgentBridgeService(serverDB, userId);
bot.onNewMention(async (thread, message) => {
log('onNewMention: agent=%s, author=%s', agentId, message.author.userName);
- await this.bridge.handleMention(thread, message, {
+ await bridge.handleMention(thread, message, {
agentId,
botContext: { applicationId, platform, platformThreadId: thread.id },
- userId,
});
});
@@ -274,10 +279,9 @@ export class BotMessageRouter {
log('onSubscribedMessage: agent=%s, author=%s', agentId, message.author.userName);
- await this.bridge.handleSubscribedMessage(thread, message, {
+ await bridge.handleSubscribedMessage(thread, message, {
agentId,
botContext: { applicationId, platform, platformThreadId: thread.id },
- userId,
});
});
}
diff --git a/src/server/services/bot/replyTemplate.ts b/src/server/services/bot/replyTemplate.ts
index 7933aad25d8..650de47f119 100644
--- a/src/server/services/bot/replyTemplate.ts
+++ b/src/server/services/bot/replyTemplate.ts
@@ -139,9 +139,7 @@ function renderInlineStats(params: {
// ==================== 1. Start ====================
-export function renderStart(content?: string): string {
- return getExtremeAck(content);
-}
+export const renderStart = getExtremeAck;
// ==================== 2. LLM Generating ====================
diff --git a/src/store/user/slices/common/action.test.ts b/src/store/user/slices/common/action.test.ts
index 2ed8dca7b47..e4bab197b1b 100644
--- a/src/store/user/slices/common/action.test.ts
+++ b/src/store/user/slices/common/action.test.ts
@@ -78,7 +78,7 @@ describe('createCommonSlice', () => {
telemetry: true,
},
settings: {
- general: { fontSize: 14 },
+ general: { fontSize: 14, timezone: 'America/New_York' },
},
};
@@ -194,7 +194,10 @@ describe('createCommonSlice', () => {
expect(result.current.isUserStateInit).toBeTruthy();
// 验证状态未被错误更新
expect(result.current.user?.avatar).toEqual('abc');
- expect(result.current.settings).toEqual({});
+ // When settings is null, auto-detect timezone will set it
+ expect(result.current.settings).toEqual({
+ general: { timezone: expect.any(String) },
+ });
});
});
diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.ts
index 9929eb13ba1..24498af69df 100644
--- a/src/store/user/slices/common/action.ts
+++ b/src/store/user/slices/common/action.ts
@@ -149,6 +149,18 @@ export class CommonActionImpl {
false,
n('initUserState'),
);
+
+ // Auto-detect and sync browser timezone on first load
+ const currentTimezone = data.settings?.general?.timezone;
+ if (!currentTimezone && typeof Intl !== 'undefined') {
+ const detectedTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ if (detectedTimezone) {
+ this.#get()
+ .updateGeneralConfig({ timezone: detectedTimezone })
+ .catch(() => {});
+ }
+ }
+
//analytics
const analytics = getSingletonAnalyticsOptional();
analytics?.identify(data.userId || '', {