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.

♻️ refactor(chat): render temporal placeholders through the shared core in the browser (#19538)

Arvin Xu96d550581c53
diff --git a/src/helpers/parserPlaceholder/index.ts b/src/helpers/parserPlaceholder/index.ts
index a899535f89e..06ebe0bfef4 100644
--- a/src/helpers/parserPlaceholder/index.ts
+++ b/src/helpers/parserPlaceholder/index.ts
@@ -34,7 +34,15 @@ const WORKING_DIRECTORY_UNSPECIFIED = '(not specified, use user Home directory a
export const getEffectiveWorkingDirectoryPath = (topicId?: string | null): string | undefined =>
resolveEffectiveWorkingDirectory(useChatStore.getState(), topicId);
-export const VARIABLE_GENERATORS = {
+/**
+ * Temporal placeholders rendered from the browser's own clock and locale.
+ *
+ * Only `parsePlaceholderVariables` (client-side text expansion) still uses
+ * these. Agent runs render their temporal placeholders through the shared
+ * context engineering core (`@lobechat/mecha`), localized to the user's
+ * timezone the same way on every host.
+ */
+export const TEMPORAL_VARIABLE_GENERATORS = {
/**
* Time-related template variables
*
@@ -61,7 +69,6 @@ export const VARIABLE_GENERATORS = {
day: () => new Date().getDate().toString().padStart(2, '0'),
hour: () => new Date().getHours().toString().padStart(2, '0'),
iso: () => new Date().toISOString(),
- locale: () => Intl.DateTimeFormat().resolvedOptions().locale,
minute: () => new Date().getMinutes().toString().padStart(2, '0'),
month: () => (new Date().getMonth() + 1).toString().padStart(2, '0'),
second: () => new Date().getSeconds().toString().padStart(2, '0'),
@@ -70,7 +77,16 @@ export const VARIABLE_GENERATORS = {
timezone: () => Intl.DateTimeFormat().resolvedOptions().timeZone,
weekday: () => new Date().toLocaleDateString('en-US', { weekday: 'long' }),
year: () => new Date().getFullYear().toString(),
+};
+/**
+ * Placeholders only this host can answer: the signed-in user, the desktop
+ * device paths, the active agent's model. Handed to the context engineering
+ * core as `variables`, where they override its defaults and leak guards.
+ */
+export const HOST_VARIABLE_GENERATORS = {
+ /** `{{locale}}` — the browser's locale, e.g. zh-CN. */
+ locale: () => Intl.DateTimeFormat().resolvedOptions().locale,
/**
* User information template variables
*
@@ -212,6 +228,11 @@ const extractPlaceholderVariables = (text: string): string[] => {
* @param depth - Recursion depth, default 1, set higher to support {{date}} within {{text}} etc.
* @returns Replaced text
*/
+export const VARIABLE_GENERATORS: Record<string, () => string> = {
+ ...TEMPORAL_VARIABLE_GENERATORS,
+ ...HOST_VARIABLE_GENERATORS,
+};
+
export const parsePlaceholderVariables = (text: string, depth = 2): string => {
let result = text;
diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.ts
index bd1868c92ad..6e9e6936eae 100644
--- a/src/services/chat/mecha/contextEngineering.test.ts
+++ b/src/services/chat/mecha/contextEngineering.test.ts
@@ -5,6 +5,7 @@ import * as isCanUseFCModule from '@/helpers/isCanUseFC';
import { agentService } from '@/services/agent';
import { agentDocumentService } from '@/services/agentDocument';
import { useAgentStore } from '@/store/agent';
+import { useUserStore } from '@/store/user';
import * as helpers from '../helper';
import { contextEngineering } from './contextEngineering';
@@ -34,9 +35,7 @@ vi.hoisted(() => {
// Mock VARIABLE_GENERATORS
vi.mock('@/helpers/parserPlaceholder', () => ({
- VARIABLE_GENERATORS: {
- date: () => '2023-12-25',
- time: () => '14:30:45',
+ HOST_VARIABLE_GENERATORS: {
username: () => 'TestUser',
random: () => '12345',
},
@@ -75,6 +74,9 @@ vi.mock('@lobechat/const', async (importOriginal) => {
beforeEach(() => {
vi.mocked(agentService.queryAgents).mockResolvedValue([]);
+ // Temporal placeholders render in the user's timezone; pin it so the
+ // expectations below do not depend on the machine running the suite.
+ useUserStore.setState({ settings: { general: { timezone: 'UTC' } } } as any);
useAgentStore.setState({
activeAgentId: undefined,
agentMap: {},
@@ -84,6 +86,7 @@ beforeEach(() => {
afterEach(() => {
runtimeFlags.isServerMode = false;
+ vi.useRealTimers();
vi.resetModules();
vi.clearAllMocks();
});
@@ -673,6 +676,8 @@ describe('contextEngineering', () => {
describe('Process placeholder variables', () => {
it('should process placeholder variables in string content', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2023-12-25T14:30:45Z'));
const messages: UIChatMessage[] = [
{
role: 'user',
@@ -700,13 +705,65 @@ describe('contextEngineering', () => {
content: expect.stringContaining(getCurrentDateContent()),
role: 'system',
});
+ // Temporal placeholders come from the shared core: the user's timezone,
+ // `en-US`, the same rendering a server-mode run produces.
expect(result[1].content).toBe(
- 'Hello TestUser, today is 2023-12-25 and the time is 14:30:45',
+ 'Hello TestUser, today is Monday, December 25, 2023 and the time is 2:30:45 PM',
);
expect(result[2].content).toBe('Hi there! Your random number is 12345');
});
+ it('renders temporal placeholders in the user timezone setting', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2023-12-25T23:30:00Z'));
+ useUserStore.setState({ settings: { general: { timezone: 'Asia/Tokyo' } } } as any);
+
+ const result = await contextEngineering({
+ messages: [
+ {
+ role: 'user',
+ content: '{{date}} / {{hour}} / {{timezone}}',
+ createdAt: Date.now(),
+ id: 'tz-1',
+ updatedAt: Date.now(),
+ },
+ ],
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(result.at(-1)?.content).toBe('Tuesday, December 26, 2023 / 08 / Asia/Tokyo');
+ });
+
+ it('renders session_date in the same timezone as the temporal placeholders', async () => {
+ // 23:30 UTC is already the next day in Tokyo; both dates must roll over
+ // together or the prompt would carry two different "today"s.
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2023-12-25T23:30:00Z'));
+ useUserStore.setState({ settings: { general: { timezone: 'Asia/Tokyo' } } } as any);
+
+ const result = await contextEngineering({
+ messages: [
+ {
+ role: 'user',
+ content: '{{session_date}} | {{date}}',
+ createdAt: Date.now(),
+ id: 'session-date-1',
+ updatedAt: Date.now(),
+ },
+ ],
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(result.at(-1)?.content).toBe(
+ 'Tuesday, December 26, 2023 | Tuesday, December 26, 2023',
+ );
+ });
+
it('should process placeholder variables in array content', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2023-12-25T14:30:45Z'));
const messages = [
{
role: 'user',
@@ -738,7 +795,7 @@ describe('contextEngineering', () => {
});
expect(Array.isArray(result[1].content)).toBe(true);
const content = result[1].content as any[];
- expect(content[0].text).toBe('Hello TestUser, today is 2023-12-25');
+ expect(content[0].text).toBe('Hello TestUser, today is Monday, December 25, 2023');
expect(content[1].image_url.url).toBe('data:image/png;base64,abc123');
});
@@ -863,6 +920,8 @@ describe('contextEngineering', () => {
});
it('should process placeholder variables combined with other processors', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2023-12-25T14:30:45Z'));
runtimeFlags.isServerMode = true;
vi.spyOn(helpers, 'isCanUseVision').mockReturnValue(true);
@@ -897,7 +956,9 @@ describe('contextEngineering', () => {
const content = result[1].content as any[];
// Should contain processed placeholder variables in the text content
- expect(content[0].text).toContain('Hello TestUser, check this image from 2023-12-25');
+ expect(content[0].text).toContain(
+ 'Hello TestUser, check this image from Monday, December 25, 2023',
+ );
// Should also contain file context from MessageContentProcessor
expect(content[0].text).toContain('SYSTEM CONTEXT');
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index d524dd8b984..6b8323a887a 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -51,7 +51,7 @@ import debug from 'debug';
import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { isCanUseFC } from '@/helpers/isCanUseFC';
-import { VARIABLE_GENERATORS } from '@/helpers/parserPlaceholder';
+import { HOST_VARIABLE_GENERATORS } from '@/helpers/parserPlaceholder';
import { lambdaClient } from '@/libs/trpc/client';
import {
agentService,
@@ -76,6 +76,8 @@ import {
toolSelectors,
} from '@/store/tool/selectors';
import { ComposioServerStatus } from '@/store/tool/slices/composioStore';
+import { useUserStore } from '@/store/user';
+import { userGeneralSettingsSelectors } from '@/store/user/selectors';
import {
getRuntimeModelDisplayName,
@@ -722,6 +724,11 @@ export const contextEngineering = async ({
const workspaceContext = resolveClientWorkspaceContext();
// Create MessagesEngine with injected dependencies
+ // One timezone for every date the prompt renders — the core's temporal
+ // placeholders, the system-date line and the host's own `session_date` —
+ // so a run near midnight cannot carry two different dates.
+ const userTimezone = userGeneralSettingsSelectors.currentTimezone(useUserStore.getState());
+
// Everything gathered above is host-specific; shaping it into engine
// parameters is shared with the server through `@lobechat/mecha`.
const snapshot: ContextSnapshot = {
@@ -774,9 +781,11 @@ export const contextEngineering = async ({
toolDiscoveryConfig,
},
// Browser-resolved placeholders. The store-backed generators stay lazy so a
- // placeholder that never renders costs nothing.
+ // placeholder that never renders costs nothing. Temporal placeholders are
+ // not among them: the core renders those in the user's timezone, the same
+ // way on every host.
variables: {
- ...VARIABLE_GENERATORS,
+ ...HOST_VARIABLE_GENERATORS,
// NOTICE: required by builtin-tool-creds/src/systemRole.ts
CREDS_LIST: () => (credsList ? generateCredsList(credsList) : ''),
// NOTICE: required by builtin-tool-creds/src/systemRole.ts (Composio integrations)
@@ -786,6 +795,7 @@ export const contextEngineering = async ({
new Intl.DateTimeFormat('en-US', {
day: 'numeric',
month: 'long',
+ timeZone: userTimezone,
weekday: 'long',
year: 'numeric',
}).format(new Date()),
@@ -818,7 +828,11 @@ export const contextEngineering = async ({
return topic?.title ?? '';
},
},
- world: { group: agentGroup, userMemory: userMemoryConfig },
+ world: {
+ group: agentGroup,
+ userMemory: userMemoryConfig,
+ userTimezone,
+ },
};
log('Input messages count: %d', messages.length);
diff --git a/src/store/user/slices/settings/selectors/general.ts b/src/store/user/slices/settings/selectors/general.ts
index ecea5d5c0cb..ba6f1c26a72 100644
--- a/src/store/user/slices/settings/selectors/general.ts
+++ b/src/store/user/slices/settings/selectors/general.ts
@@ -32,6 +32,11 @@ const currentResponseLanguage = (s: UserStore): Locales => {
return normalizeLocale(getSystemLanguage());
};
const telemetry = (s: UserStore) => generalConfig(s).telemetry;
+const timezone = (s: UserStore) => generalConfig(s).timezone;
+/** The user's timezone setting, falling back to the browser's. */
+const currentTimezone = (s: UserStore): string | undefined =>
+ timezone(s) ||
+ (typeof Intl === 'undefined' ? undefined : Intl.DateTimeFormat().resolvedOptions().timeZone);
const enableAutoScrollOnStreaming = (s: UserStore) =>
generalConfig(s).enableAutoScrollOnStreaming ?? true;
const enableMessageLinkIcon = (s: UserStore) => generalConfig(s).enableMessageLinkIcon ?? true;
@@ -50,8 +55,10 @@ export const userGeneralSettingsSelectors = {
neutralColor,
primaryColor,
currentResponseLanguage,
+ currentTimezone,
responseLanguage,
telemetry,
+ timezone,
transitionMode,
workflowStreamingExpandLevel,
};