Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(agents): give agents the current date so date chips read today (#9186)
Wolf Mermelsteina0f5761e12a7
diff --git a/Cargo.lock b/Cargo.lockindex c05e589109..5ff6864f21 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -446,9 +446,11 @@ dependencies = ["base64 0.22.1","bot_id","bots",+ "calendar_events","channel_sender","channels","chrono",+ "chrono-tz","codex_cloud_agents","codex_connection","cursor_api_key",@@ -553,6 +555,7 @@ dependencies = ["axum-extra","bot_id","bots",+ "calendar_events","call","channel_sender","channels",diff --git a/apps/web/src/components/cell-text-editor/cell-mention-dom.ts b/apps/web/src/components/cell-text-editor/cell-mention-dom.tsindex 228925e226..3ee8911950 100644--- a/apps/web/src/components/cell-text-editor/cell-mention-dom.ts+++ b/apps/web/src/components/cell-text-editor/cell-mention-dom.ts@@ -1,4 +1,4 @@-import { formatRelativeDay } from '@core/util/dateParser';+import { formatRelativeDay, parseMentionDate } from '@core/util/dateParser';import {type CellMention,cellMentionLabel,@@ -8,7 +8,7 @@ import {/** Match the grid, where date chips relabel themselves as days pass. */function pillLabel(mention: CellMention) {return mention.type === 'date'- ? formatRelativeDay(new Date(mention.date))+ ? formatRelativeDay(parseMentionDate(mention.date)): cellMentionLabel(mention);}diff --git a/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.tsx b/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.tsxindex 802c8a90dc..e9e7718e7e 100644--- a/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.tsx+++ b/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.tsx@@ -10,7 +10,11 @@ import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/Menimport { getBlockNameFromEntity } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils';import { parseMacroAppUrl } from '@core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin';import type { MentionItem } from '@core/component/LexicalMarkdown/utils/mentionsUtils';-import { formatRelativeDay, formatTooltipDate } from '@core/util/dateParser';+import {+ formatRelativeDay,+ formatTooltipDate,+ parseMentionDate,+} from '@core/util/dateParser';import ClockIcon from '@icon/system/regular/clock.svg';import {type CellDateMention,@@ -69,7 +73,7 @@ function fromItem(item: MentionItem): string | undefined {* and AI edits.*/function CellDateChip(props: CellDateMention) {- const date = () => new Date(props.date);+ const date = () => parseMentionDate(props.date);return (<spandata-spreadsheet-mentiondiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.mdindex 2431fe0329..7699a4d3c3 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md@@ -62,6 +62,14 @@ unquoted paragraphs retain normal paste behavior.Screenshots: [desktop](proof/quotes-desktop.png), [phone](proof/quotes-mobile.png),and [multi-paragraph paste](proof/quote-paste.png).+## Date chips++`date-chips.browser.e2e.ts` renders a whole-day chip (`"date":"2026-09-24"`)+and a timed chip in `America/Los_Angeles` at 1:03 PM that day, and checks both+read Today. A bare date read as UTC midnight shows Yesterday west of+Greenwich. Run just this case by adding `date-chips.browser.e2e.ts` to the+command above.+## Images in lists`list-images.browser.e2e.ts` mounts the production Markdown editor with mediadiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.browser.e2e.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.browser.e2e.tsnew file mode 100644index 0000000000..69b792be1f--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.browser.e2e.ts@@ -0,0 +1,45 @@+import { expect, test } from '@playwright/test';++// West of Greenwich, where a whole-day chip read as UTC midnight showed+// "Yesterday" for today.+test.use({ timezoneId: 'America/Los_Angeles' });++test('whole-day and timed date chips label today as Today', async ({+ page,+ context,+}, testInfo) => {+ await context.route('**/*', async (route) => {+ const url = new URL(route.request().url());+ if (+ url.hostname === 'localhost' &&+ !url.pathname.includes('/__macro_dev/')+ ) {+ await route.continue();+ } else {+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: '{}',+ });+ }+ });+ await page.routeWebSocket('**/*', (socket) => socket.close());+ // Thursday, 1:03 PM in Los Angeles.+ await page.clock.setFixedTime(new Date('2026-09-24T20:03:00Z'));+ const errors: string[] = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.goto(+ '/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.html'+ );++ const wholeDay = page.getByTestId('whole-day').locator('[data-date-mention]');+ await expect(wholeDay).toHaveText('Today', { timeout: 30_000 });+ await expect(wholeDay).toHaveAttribute('data-date', '2026-09-24');+ await expect(+ page.getByTestId('timed').locator('[data-date-mention]')+ ).toHaveText('Today');+ expect(errors).toEqual([]);+ await page.screenshot({+ path: testInfo.outputPath(`date-chips-${testInfo.project.name}.png`),+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.html b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.htmlnew file mode 100644index 0000000000..2ca4ddbdd1--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Date chips</title></head>+ <body><div id="root"></div><script type="module" src="./date-chips.tsx"></script></body>+</html>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.tsxnew file mode 100644index 0000000000..5785d6518e--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/date-chips.tsx@@ -0,0 +1,51 @@+import '@app/index.css';+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';+import { PosthogProvider } from '@app/lib/analytics/posthog';+import { UserContextProvider } from '@core/context/user';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { onCleanup } from 'solid-js';+import { render } from 'solid-js/web';+import { StaticMarkdown, StaticMarkdownContext } from '../StaticMarkdown';++const chip = (date: string) =>+ `<m-date-mention>${JSON.stringify({ date, displayFormat: 'Today' })}</m-date-mention>`;++function Fixture() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ onCleanup(() => client.clear());+ return (+ <AnalyticsContextProvider>+ <PosthogProvider>+ <QueryClientProvider client={client}>+ <UserContextProvider>+ <StaticMarkdownContext>+ <main class="bg-page text-ink h-dvh overflow-y-auto p-6 space-y-6 max-w-3xl mx-auto">+ <h1 class="text-xl font-medium">Date chips</h1>+ <section+ data-testid="whole-day"+ class="border border-edge rounded p-4"+ >+ <StaticMarkdown+ markdown={`All emailed ${chip('2026-09-24')}, awaiting demo booking.`}+ />+ </section>+ <section+ data-testid="timed"+ class="border border-edge rounded p-4"+ >+ <StaticMarkdown+ markdown={`Call at ${chip('2026-09-24T16:00:00-07:00')}.`}+ />+ </section>+ </main>+ </StaticMarkdownContext>+ </UserContextProvider>+ </QueryClientProvider>+ </PosthogProvider>+ </AnalyticsContextProvider>+ );+}++render(() => <Fixture />, document.getElementById('root')!);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DateMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DateMention.tsxindex 2fdd862402..919cb248c7 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DateMention.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DateMention.tsx@@ -1,5 +1,9 @@import { DatePicker } from '@core/component/DatePicker';-import { formatRelativeDay, formatTooltipDate } from '@core/util/dateParser';+import {+ formatRelativeDay,+ formatTooltipDate,+ parseMentionDate,+} from '@core/util/dateParser';import ClockIcon from '@icon/system/regular/clock.svg';import type { DateMentionDecoratorProps } from '@macro-inc/lexical-core';import { $isDateMentionNode } from '@macro-inc/lexical-core';@@ -27,7 +31,7 @@ export function DateMention(props: DateMentionDecoratorProps) {let mentionRef!: HTMLSpanElement;const displayFormat = createMemo(() => {- return formatRelativeDay(new Date(props.date));+ return formatRelativeDay(parseMentionDate(props.date));});const isSelectedAsNode = () => {@@ -72,7 +76,7 @@ export function DateMention(props: DateMentionDecoratorProps) {);}- const currentDate = () => new Date(props.date);+ const currentDate = () => parseMentionDate(props.date);return (<>@@ -105,7 +109,7 @@ export function DateMention(props: DateMentionDecoratorProps) {class="absolute select-none z-tool-tip bg-surface p-1.5 text-ink-muted text-xs wrap-break-word rounded-sm border border-edge-muted shadow-md shadow-[#000]/5"use:floatWithElement={{ element: () => mentionRef }}>- {formatTooltipDate(new Date(props.date))}+ {formatTooltipDate(parseMentionDate(props.date))}</div></Portal></Show>diff --git a/apps/web/src/lib/core/util/dateMention.test.ts b/apps/web/src/lib/core/util/dateMention.test.tsnew file mode 100644index 0000000000..339571c29a--- /dev/null+++ b/apps/web/src/lib/core/util/dateMention.test.ts@@ -0,0 +1,38 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { formatRelativeDay, parseMentionDate } from './dateParser';++describe('parseMentionDate', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ // Thursday afternoon, local time.+ vi.setSystemTime(new Date(2026, 8, 24, 16, 3));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('reads a bare date as that local day, so today stays today', () => {+ const date = parseMentionDate('2026-09-24');++ expect([date.getFullYear(), date.getMonth(), date.getDate()]).toEqual([+ 2026, 8, 24,+ ]);+ expect(formatRelativeDay(date)).toBe('Today');+ });++ it('reads a timestamp as the instant it names', () => {+ expect(parseMentionDate('2026-09-24T16:03:00-04:00').toISOString()).toBe(+ '2026-09-24T20:03:00.000Z'+ );+ });++ it('keeps a year before 100 as written', () => {+ expect(parseMentionDate('0025-03-01').getFullYear()).toBe(25);+ });++ it('keeps an invalid value invalid', () => {+ expect(Number.isNaN(parseMentionDate('2026-02-31').getTime())).toBe(true);+ expect(Number.isNaN(parseMentionDate('soon').getTime())).toBe(true);+ });+});diff --git a/apps/web/src/lib/core/util/dateParser.ts b/apps/web/src/lib/core/util/dateParser.tsindex a1bd1e7684..7439677bdd 100644--- a/apps/web/src/lib/core/util/dateParser.ts+++ b/apps/web/src/lib/core/util/dateParser.ts@@ -369,6 +369,21 @@ export function formatDate(date: Date): string {return date.toLocaleDateString('en-US', options);}+/**+ * Read a date chip's `date`. A bare `YYYY-MM-DD` names a whole local day;+ * `new Date` would read it as UTC midnight, the previous day west of+ * Greenwich. Anything else is a timestamp.+ */+export function parseMentionDate(value: string): Date {+ const day = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);+ if (!day) return new Date(value);+ const [year, month, date] = day.slice(1).map(Number);+ // The Date constructor reads years 0-99 as 1900-1999; setFullYear does not.+ const local = new Date(0, 0, 1);+ local.setFullYear(year, month - 1, date);+ return local.getMonth() === month - 1 ? local : new Date(Number.NaN);+}+/*** Day-relative label for dates near now — "Today", "Yesterday", "2 days ago",* "Tomorrow", "In 2 days" — falling back to `formatDate` beyond that window.diff --git a/crates/agent_harness/AGENTS.md b/crates/agent_harness/AGENTS.mdindex d073a1feda..e69e2305f6 100644--- a/crates/agent_harness/AGENTS.md+++ b/crates/agent_harness/AGENTS.md@@ -107,6 +107,10 @@ wakes; interrupted quiet batches return to the next real prompt.Background channel messages are not attached. `trigger_router` fills eachcontext attachment's `url` from `StaticFileLinks`, and `<m-agent-context>`lists them per message; ACP `resource_link`s are what vision models fetch.+- Every composed prompt's `<m-agent-context>` states `<current_time>` in the+ sender's (else owner's) primary calendar time zone, via the+ `UserTimeZones` port, or UTC when unknown. Models have no other source+ for the date, so never drop it from a composition path.## Relateddiff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.tomlindex 08c6b2bc4a..1ac0cf03e5 100644--- a/crates/agent_harness/Cargo.toml+++ b/crates/agent_harness/Cargo.toml@@ -39,7 +39,9 @@ trigger_context = { path = "../trigger_context" }harness_id = { path = "../harness_id" }channel_sender = { path = "../channel_sender" }chrono = { workspace = true }+chrono-tz = { workspace = true }lexical_client = { path = "../lexical_client" }+calendar_events = { path = "../calendar_events" }dashmap = { workspace = true }futures = { workspace = true }# The installation records that say which repositories a user can reach, so adiff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex a2d8655f35..ba14e6efa6 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -19,6 +19,8 @@ use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use messages::domain::events::MessageEventAttachment;use trigger_context::TriggerContext;+mod current_time;+pub use current_time::CurrentTime;mod session_origin;pub use session_origin::{MentionOrigin, SessionOrigin, TaskAssignmentOrigin};mod coding_preferences;diff --git a/crates/agent_harness/src/domain/model/current_time.rs b/crates/agent_harness/src/domain/model/current_time.rsnew file mode 100644index 0000000000..3ec61815af--- /dev/null+++ b/crates/agent_harness/src/domain/model/current_time.rs@@ -0,0 +1,50 @@+//! The current time a prompt states, in the time zone of its reader.++use chrono::{DateTime, Utc};+use chrono_tz::Tz;++#[cfg(test)]+mod test;++/// Now, as a prompt states it: models do not know the date, so relative+/// dates and date chips are resolved from this.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CurrentTime {+ /// ISO 8601 timestamp carrying the zone's UTC offset.+ pub iso: String,+ /// The same instant written out, e.g. "Thursday, September 24, 2026, 4:03 PM".+ pub local: String,+ /// The IANA zone, absent when unknown and the time is in UTC.+ pub time_zone: Option<String>,+}++impl CurrentTime {+ /// `now` in `time_zone`, or in UTC when the zone is unknown or not a+ /// valid IANA name.+ pub fn new(now: DateTime<Utc>, time_zone: Option<&str>) -> Self {+ let zone = time_zone.and_then(|name| {+ name.parse::<Tz>()+ .inspect_err(|error| {+ tracing::warn!(error=?error, time_zone = name, "unparseable time zone");+ })+ .ok()+ });+ match zone {+ Some(zone) => {+ let local = now.with_timezone(&zone);+ Self {+ iso: local.to_rfc3339_opts(chrono::SecondsFormat::Secs, false),+ local: local.format(FORMAT).to_string(),+ time_zone: Some(zone.name().to_owned()),+ }+ }+ None => Self {+ iso: now.to_rfc3339_opts(chrono::SecondsFormat::Secs, false),+ local: now.format(FORMAT).to_string(),+ time_zone: None,+ },+ }+ }+}++const FORMAT: &str = "%A, %B %-d, %Y, %-I:%M %p";diff --git a/crates/agent_harness/src/domain/model/current_time/test.rs b/crates/agent_harness/src/domain/model/current_time/test.rsnew file mode 100644index 0000000000..1914774fa0--- /dev/null+++ b/crates/agent_harness/src/domain/model/current_time/test.rs@@ -0,0 +1,45 @@+use super::*;+use chrono::TimeZone;++/// 20:03 UTC is still the afternoon of the same day in New York, so a chip+/// for "today" must carry the New York date, not UTC midnight.+#[test]+fn states_now_in_the_users_time_zone() {+ let now = Utc.with_ymd_and_hms(2026, 9, 24, 20, 3, 36).unwrap();++ assert_eq!(+ CurrentTime::new(now, Some("America/New_York")),+ CurrentTime {+ iso: "2026-09-24T16:03:36-04:00".to_owned(),+ local: "Thursday, September 24, 2026, 4:03 PM".to_owned(),+ time_zone: Some("America/New_York".to_owned()),+ }+ );+}++#[test]+fn crosses_midnight_into_the_users_date() {+ let now = Utc.with_ymd_and_hms(2026, 9, 25, 2, 30, 0).unwrap();++ assert_eq!(+ CurrentTime::new(now, Some("America/Los_Angeles")),+ CurrentTime {+ iso: "2026-09-24T19:30:00-07:00".to_owned(),+ local: "Thursday, September 24, 2026, 7:30 PM".to_owned(),+ time_zone: Some("America/Los_Angeles".to_owned()),+ }+ );+}++#[test]+fn falls_back_to_utc_without_a_known_zone() {+ let now = Utc.with_ymd_and_hms(2026, 9, 24, 20, 3, 36).unwrap();+ let utc = CurrentTime {+ iso: "2026-09-24T20:03:36+00:00".to_owned(),+ local: "Thursday, September 24, 2026, 8:03 PM".to_owned(),+ time_zone: None,+ };++ assert_eq!(CurrentTime::new(now, None), utc);+ assert_eq!(CurrentTime::new(now, Some("Mars/Olympus_Mons")), utc);+}diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rsindex 99b712efff..3d63816836 100644--- a/crates/agent_harness/src/domain/ports.rs+++ b/crates/agent_harness/src/domain/ports.rs@@ -183,9 +183,9 @@ pub trait MessagePromptContext: Send + Sync + 'static {/// Composes an agent prompt from raw markdown and trusted session context.pub trait AgentPromptComposer: Send + Sync + 'static {- /// Return the markdown that should be delivered to the agent runtime.- /// With no instructions, people, or trigger, the prompt is sanitized- /// without adding a private context node.+ /// Return the markdown that should be delivered to the agent runtime:+ /// the sanitized prompt behind a private context node that states the+ /// current time and whatever instructions, people, and trigger it has.fn compose(&self,prompt_markdown: &str,@@ -195,6 +195,17 @@ pub trait AgentPromptComposer: Send + Sync + 'static {) -> impl Future<Output = Result<String>> + Send;}+/// The time zone a user keeps time in, so a prompt can state the current+/// time the way its reader does.+pub trait UserTimeZones: Send + Sync + 'static {+ /// The user's IANA time zone; `None` when it is unknown. Best effort: a+ /// failed lookup is `None`.+ fn time_zone(+ &self,+ user: &MacroUserIdStr<'static>,+ ) -> impl Future<Output = Option<String>> + Send;+}+/// Who a prompt names, made able to open the session it is for.////// Mentioning someone in a prompt is an invitation: when the author candiff --git a/crates/agent_harness/src/outbound/agent_prompt_composer.rs b/crates/agent_harness/src/outbound/agent_prompt_composer.rsindex 4070874332..b63a7c1ba2 100644--- a/crates/agent_harness/src/outbound/agent_prompt_composer.rs+++ b/crates/agent_harness/src/outbound/agent_prompt_composer.rs@@ -1,27 +1,42 @@//! Compose trigger context for every harness.+use chrono::{DateTime, Utc};use lexical_client::LexicalClient;-use lexical_client::parse_markdown::{AgentContextPeople, AgentContextPerson};+use lexical_client::parse_markdown::{+ AgentContextCurrentTime, AgentContextPeople, AgentContextPerson,+};use macro_user_id::user_id::MacroUserIdStr;use trigger_context::TriggerContext;use crate::domain::error::{HarnessError, Result};-use crate::domain::model::PromptPeople;-use crate::domain::ports::AgentPromptComposer;+use crate::domain::model::{CurrentTime, PromptPeople};+use crate::domain::ports::{AgentPromptComposer, UserTimeZones};-/// Lexical-service-backed agent prompt composer.-pub struct LexicalAgentPromptComposer {+/// Lexical-service-backed agent prompt composer. Every prompt states the+/// current time in its reader's time zone.+pub struct LexicalAgentPromptComposer<TimeZones> {lexical: LexicalClient,+ time_zones: TimeZones,+ clock: fn() -> DateTime<Utc>,}-impl LexicalAgentPromptComposer {- /// Build a composer backed by `lexical`.- pub const fn new(lexical: LexicalClient) -> Self {- Self { lexical }+impl<TimeZones> LexicalAgentPromptComposer<TimeZones> {+ /// Build a composer backed by `lexical` and `time_zones`.+ pub fn new(lexical: LexicalClient, time_zones: TimeZones) -> Self {+ Self {+ lexical,+ time_zones,+ clock: Utc::now,+ }+ }++ /// Read the current time from `clock` instead of the system clock.+ pub fn with_clock(self, clock: fn() -> DateTime<Utc>) -> Self {+ Self { clock, ..self }}}-impl AgentPromptComposer for LexicalAgentPromptComposer {+impl<TimeZones: UserTimeZones> AgentPromptComposer for LexicalAgentPromptComposer<TimeZones> {async fn compose(&self,prompt_markdown: &str,@@ -29,12 +44,30 @@ impl AgentPromptComposer for LexicalAgentPromptComposer {people: Option<&PromptPeople>,trigger: Option<&TriggerContext>,) -> Result<String> {+ // The reply is read by whoever sent the prompt, else by the owner.+ let reader = people.map(|people| people.sender.as_ref().unwrap_or(&people.owner));+ let time_zone = match reader {+ Some(reader) => self.time_zones.time_zone(reader).await,+ None => None,+ };+ let now = CurrentTime::new((self.clock)(), time_zone.as_deref());+ let current_time = AgentContextCurrentTime {+ iso: &now.iso,+ local: &now.local,+ time_zone: now.time_zone.as_deref(),+ };let people = people.map(|people| AgentContextPeople {owner: person(&people.owner),sender: people.sender.as_ref().map(person),});self.lexical- .compose_agent_context(prompt_markdown, instructions, people.as_ref(), trigger)+ .compose_agent_context(+ prompt_markdown,+ instructions,+ people.as_ref(),+ Some(¤t_time),+ trigger,+ ).await.map_err(|error| HarnessError::PromptComposition(rootcause::report!(error).into()))}diff --git a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rsindex eb9675aded..a56ca650b0 100644--- a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs+++ b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs@@ -5,6 +5,28 @@ use std::sync::{Arc, Mutex};use trigger_context::{ContextPerson, ProjectRef, TaskAssignedContext, TaskSnapshot};use uuid::Uuid;+/// Everyone keeps time in New York, the way their primary calendars say.+struct NewYork;++impl UserTimeZones for NewYork {+ async fn time_zone(&self, _user: &MacroUserIdStr<'static>) -> Option<String> {+ Some("America/New_York".to_owned())+ }+}++/// Nobody's time zone is known.+struct Unknown;++impl UserTimeZones for Unknown {+ async fn time_zone(&self, _user: &MacroUserIdStr<'static>) -> Option<String> {+ None+ }+}++fn afternoon_in_new_york() -> chrono::DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 9, 24, 20, 3, 36).unwrap()+}+/// The trigger crosses a service boundary, so the body the lexical service/// validates is asserted here rather than only in its own types.#[tokio::test]@@ -24,10 +46,11 @@ async fn the_trigger_reaches_the_lexical_service_beside_the_people() {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });- let composer = LexicalAgentPromptComposer::new(LexicalClient::new(- "test".into(),- format!("http://{address}"),- ));+ let composer = LexicalAgentPromptComposer::new(+ LexicalClient::new("test".into(), format!("http://{address}")),+ NewYork,+ )+ .with_clock(afternoon_in_new_york);let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();let trigger = TriggerContext::TaskAssigned(TaskAssignedContext {task: TaskSnapshot {@@ -73,6 +96,11 @@ async fn the_trigger_reaches_the_lexical_service_beside_the_people() {"instructions": "Be brief.","owner": { "id": "macro|[email protected]", "name": "[email protected]" },"sender": { "id": "macro|[email protected]", "name": "[email protected]" },+ "currentTime": {+ "iso": "2026-09-24T16:03:36-04:00",+ "local": "Thursday, September 24, 2026, 4:03 PM",+ "timeZone": "America/New_York"+ },"trigger": {"kind": "task_assigned","task": {@@ -115,10 +143,11 @@ async fn a_prompt_without_a_trigger_sends_none() {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });- let composer = LexicalAgentPromptComposer::new(LexicalClient::new(- "test".into(),- format!("http://{address}"),- ));+ let composer = LexicalAgentPromptComposer::new(+ LexicalClient::new("test".into(), format!("http://{address}")),+ Unknown,+ )+ .with_clock(afternoon_in_new_york);let composed = composer.compose("Raw prompt", None, None, None)@@ -128,7 +157,13 @@ async fn a_prompt_without_a_trigger_sends_none() {assert_eq!(composed, "Sanitized prompt");assert_eq!(received.lock().unwrap().take().unwrap(),- serde_json::json!({ "promptMarkdown": "Raw prompt" })+ serde_json::json!({+ "promptMarkdown": "Raw prompt",+ "currentTime": {+ "iso": "2026-09-24T20:03:36+00:00",+ "local": "Thursday, September 24, 2026, 8:03 PM"+ }+ }));server.abort();}diff --git a/crates/agent_harness/src/outbound/mod.rs b/crates/agent_harness/src/outbound/mod.rsindex 7dbe5ff669..0890c78657 100644--- a/crates/agent_harness/src/outbound/mod.rs+++ b/crates/agent_harness/src/outbound/mod.rs@@ -19,6 +19,7 @@ pub mod local;pub(crate) mod managed_containers;pub mod namespace;pub mod notifications;+pub mod primary_calendar_time_zones;pub mod prompt_mentions;pub(crate) mod provision;pub mod routing;diff --git a/crates/agent_harness/src/outbound/primary_calendar_time_zones.rs b/crates/agent_harness/src/outbound/primary_calendar_time_zones.rsnew file mode 100644index 0000000000..a2c98c9e99--- /dev/null+++ b/crates/agent_harness/src/outbound/primary_calendar_time_zones.rs@@ -0,0 +1,31 @@+//! A user's time zone is their primary calendar's.++use calendar_events::domain::ports::CalendarOccurrenceService;+use macro_user_id::user_id::MacroUserIdStr;++use crate::domain::ports::UserTimeZones;++/// [`UserTimeZones`] backed by the calendar read service.+pub struct PrimaryCalendarTimeZones<Calendars> {+ calendars: Calendars,+}++impl<Calendars> PrimaryCalendarTimeZones<Calendars> {+ /// Read time zones from `calendars`.+ pub const fn new(calendars: Calendars) -> Self {+ Self { calendars }+ }+}++impl<Calendars: CalendarOccurrenceService> UserTimeZones for PrimaryCalendarTimeZones<Calendars> {+ async fn time_zone(&self, user: &MacroUserIdStr<'static>) -> Option<String> {+ self.calendars+ .primary_time_zone(user.as_ref())+ .await+ .inspect_err(|error| {+ tracing::warn!(error=?error, "failed to resolve a primary calendar time zone");+ })+ .ok()+ .flatten()+ }+}diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rsindex 075ac9d20a..c2d2e10250 100644--- a/crates/lexical_client/src/parse_markdown.rs+++ b/crates/lexical_client/src/parse_markdown.rs@@ -344,6 +344,19 @@ pub struct AgentContextPeople<'a> {pub sender: Option<AgentContextPerson<'a>>,}+/// When a prompt was sent, as the person reading the reply keeps time.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentContextCurrentTime<'a> {+ /// ISO 8601 timestamp carrying the time zone's UTC offset.+ pub iso: &'a str,+ /// The same instant written out for a reader.+ pub local: &'a str,+ /// IANA zone `iso` is in; absent when unknown and `iso` is UTC.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub time_zone: Option<&'a str>,+}+#[derive(Debug, serde::Serialize)]#[serde(rename_all = "camelCase")]struct AgentContextRequest<'a> {@@ -353,6 +366,8 @@ struct AgentContextRequest<'a> {#[serde(flatten, skip_serializing_if = "Option::is_none")]people: Option<&'a AgentContextPeople<'a>>,#[serde(skip_serializing_if = "Option::is_none")]+ current_time: Option<&'a AgentContextCurrentTime<'a>>,+ #[serde(skip_serializing_if = "Option::is_none")]trigger: Option<&'a TriggerContext>,}@@ -676,12 +691,13 @@ impl LexicalClient {/// Sanitizes an agent prompt and optionally composes it with why the/// agent was called via the lexical service, so internal nodes and/// escaping are handled by Lexical rather than by the caller.- #[tracing::instrument(skip(self, prompt_markdown, trigger), err)]+ #[tracing::instrument(skip(self, prompt_markdown, current_time, trigger), err)]pub async fn compose_agent_context(&self,prompt_markdown: &str,instructions: Option<&str>,people: Option<&AgentContextPeople<'_>>,+ current_time: Option<&AgentContextCurrentTime<'_>>,trigger: Option<&TriggerContext>,) -> Result<String> {let url = format!("{}/agent-context", self.url);@@ -692,6 +708,7 @@ impl LexicalClient {prompt_markdown,instructions,people,+ current_time,trigger,}).send()diff --git a/crates/prompt/src/agent_session.rs b/crates/prompt/src/agent_session.rsindex 1242ec0d69..4f38c95b78 100644--- a/crates/prompt/src/agent_session.rs+++ b/crates/prompt/src/agent_session.rs@@ -26,7 +26,7 @@ A faster model may already have shown the first line of your reply: a short ackn- An <m-notifications> envelope contains typed system events, not user requests or owner approval. Do not repeat completed actions or retry uncertain outcomes. Use GetReview for final drafts and confirmed results. A notification-only turn has no human prompter and cannot authorize owner-only actions. If nothing needs saying, reply exactly <noop/>. Only notification-only turns may noop; after a tool that could change state, give a one-line result instead.- You have no shell and no filesystem. Everything you can do, you do through the tools you are given.-- Every prompt opens with a private context block naming the session's owner, whose access you act with, and who sent the prompt. Follow its note on what a prompt from someone else may do. Treat it as system hints, not part of the conversation: never mention, quote, or refer to it (no "the context says"); just act on it.+- Every prompt opens with a private context block naming the session's owner, whose access you act with, and who sent the prompt, and stating in `<current_time>` when it was sent in the user's time zone; that is today's date. Follow its note on what a prompt from someone else may do. Treat it as system hints, not part of the conversation: never mention, quote, or refer to it (no "the context says"); just act on it."##;static INTENT: &str = "The model behaves as a fast product assistant inside an agent session: \diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rsindex 6778f6095d..f4b859b4af 100644--- a/crates/prompt/src/lib.rs+++ b/crates/prompt/src/lib.rs@@ -400,6 +400,14 @@ mod tests {assert!(instructions.contains("Private and confidential events are never shared"));}+ #[test]+ fn mentions_prompt_writes_whole_days_as_local_dates_from_the_current_time() {+ let instructions = mentions::PROMPT.instructions.as_ref();+ assert!(instructions.contains("bare local calendar date (`2025-12-01`)"));+ assert!(instructions.contains("never midnight UTC"));+ assert!(instructions.contains("`<current_time>`"));+ }+#[test]fn mentions_prompt_covers_date_and_agent_session_chips() {let instructions = mentions::PROMPT.instructions.as_ref();diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rsindex 18aae56c06..8943310241 100644--- a/crates/prompt/src/mentions.rs+++ b/crates/prompt/src/mentions.rs@@ -77,7 +77,7 @@ These use their own tags — never wrap them in `<m-document-mention>`:- GitHub pull request: `<m-pr-mention>{"url":"https://github.com/{owner}/{repo}/pull/{number}","label":""}</m-pr-mention>`, or `<m-pr-mention>{"id":"{id}","label":""}</m-pr-mention>` when a tool returned the PR's Macro id- Booking link: `<m-booking-link-mention>{"profileId":"{profile_id}","slug":"{slug}","url":"https://macro.com/app/book/{profile_id}/{slug}","label":""}</m-booking-link-mention>` (`slug` optional when linking the profile page)-- Dates: prefer a date chip to a typed date. `date` is ISO 8601 and `displayFormat` is the label shown (e.g. "Mon, Dec 1, 2025", "Today", "3:00 PM"); no lookup needed.+- Dates: prefer a date chip to a typed date. For a whole day, `date` is the bare local calendar date (`2025-12-01`), never midnight UTC, which reads as the previous day west of Greenwich; for a moment, it is a full ISO 8601 timestamp with the user's UTC offset. `displayFormat` is the label shown (e.g. "Mon, Dec 1, 2025", "Today", "3:00 PM"). Resolve "today" and other relative dates from the `<current_time>` your prompt carries when it has one, never from a guess.- Pull requests and booking links: always a chip, never a Markdown link or bare URL. Leave `label` empty and do not repeat the number, title, or URL beside it. A PR chip takes any github.com pull request URL; a booking chip takes the shareable URL plus the `profileId` and `slug` from its `/app/book/{profileId}/{slug}` path. A PR chip you receive carries the PR's URL in `url`. Issues, commits, and other GitHub pages stay Markdown links.- Agent sessions: only ids a tool returned. Add `"expanded":true` to insert the live card (Magic Chip) instead of the compact title.- Connecting apps: when a tool result hands you an `<m-connect-app>{"appSlug":"...","name":"..."}</m-connect-app>` tag, include it verbatim; it renders a connect button. Never invent one. In agent sessions the button resumes the conversation once connected, so just tell the user to connect; elsewhere, ask them to say when they have.diff --git a/packages/lexical-core/tests/agent-context.test.ts b/packages/lexical-core/tests/agent-context.test.tsindex a63446b112..4365ca1294 100644--- a/packages/lexical-core/tests/agent-context.test.ts+++ b/packages/lexical-core/tests/agent-context.test.ts@@ -432,6 +432,36 @@ describe('composeAgentContextPrompt', () => {expect(text?.match(/<\/session>/g)).toHaveLength(1);});+ it('states the current time in the user time zone', () => {+ const text = composedContext({+ promptMarkdown: 'which leads came in today?',+ currentTime: {+ iso: '2026-09-24T16:03:36-04:00',+ local: 'Thursday, September 24, 2026, 4:03 PM',+ timeZone: 'America/New_York',+ },+ });+ expect(text).toContain(+ '<current_time iso="2026-09-24T16:03:36-04:00" time_zone="America/New_York">Thursday, September 24, 2026, 4:03 PM'+ );+ expect(text).toContain('Today is the date above');+ expect(text).toContain('2026-09-24 for today');+ });++ it('states the current time in UTC when the time zone is unknown', () => {+ const text = composedContext({+ promptMarkdown: 'what is due today?',+ currentTime: {+ iso: '2026-09-24T20:03:36+00:00',+ local: 'Thursday, September 24, 2026, 8:03 PM',+ },+ });+ expect(text).toContain(+ '<current_time iso="2026-09-24T20:03:36+00:00" time_zone="UTC">'+ );+ expect(text).toContain('time zone of the user is unknown');+ });+it('does not add context when there is none', () => {expect(composeAgentContextPrompt({ promptMarkdown: 'original', channel: [] })diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.tsindex 703179edb9..f2e6e333dc 100644--- a/packages/lexical-core/utils/agent-context.ts+++ b/packages/lexical-core/utils/agent-context.ts@@ -425,6 +425,16 @@ export type AgentContextPerson = {name: string;};+/** When a prompt was sent, as the person reading the reply keeps time. */+export type AgentContextCurrentTime = {+ /** ISO 8601 timestamp carrying the time zone's UTC offset. */+ iso: string;+ /** The same instant written out, e.g. "Thursday, September 24, 2026, 4:03 PM". */+ local: string;+ /** IANA zone of the user's primary calendar; absent when unknown, and `iso` is UTC. */+ timeZone?: string;+};+/** Input used to compose an agent prompt with private conversation context. */export type AgentContextPrompt = {promptMarkdown: string;@@ -434,6 +444,8 @@ export type AgentContextPrompt = {owner?: AgentContextPerson;/** Who sent the prompt; absent when a bot sent it on nobody's behalf. */sender?: AgentContextPerson;+ /** Now, so relative dates and date chips resolve. Supplied by the harness. */+ currentTime?: AgentContextCurrentTime;/*** Why the agent was called. Supplied by the trigger pipeline, never by the* prompt's author. Cannot be combined with the legacy fields below.@@ -1557,6 +1569,27 @@ function sessionNode();}+/**+ * Now, in the user's time zone. Models do not know the date, and a date chip+ * written as UTC midnight reads as the previous day west of Greenwich.+ */+function currentTimeNode(time: AgentContextCurrentTime): FxpNode {+ const today = time.iso.slice(0, 10);+ const zone = time.timeZone+ ? `in ${time.timeZone}, the time zone of the primary calendar of the user`+ : 'in UTC, because the time zone of the user is unknown (no connected calendar)';+ return el(+ 'current_time',+ [+ text(time.local),+ note(+ `The time this prompt was sent, ${zone}. Today is the date above; resolve today, yesterday, this week and other relative dates from it, never from a guess or a web search. A date chip for a whole day takes the local calendar date alone as its date, ${today} for today; a chip with a clock time takes a full ISO timestamp with this UTC offset.`+ ),+ ],+ { iso: time.iso, time_zone: time.timeZone ?? 'UTC' }+ );+}+/** Legacy conversation fields the input sets. */export function legacyConversationFieldsIn(input: Partial<Record<(typeof LEGACY_CONVERSATION_FIELDS)[number], unknown>>@@ -1572,6 +1605,7 @@ function renderContext(input: AgentContextPrompt): string | undefined {: renderConversation(input);const nodes = [...(input.owner ? [sessionNode(input.owner, input.sender)] : []),+ ...(input.currentTime ? [currentTimeNode(input.currentTime)] : []),...(body ? [body] : []),];if (nodes.length === 0) return undefined;diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex 073e6602a0..cab1d3893d 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -47,6 +47,7 @@ agent_api_keys = { path = "../../crates/agent_api_keys" }ai_projections = { path = "../../crates/ai_projections", features = ["agent"] }ai_tools = { path = "../../crates/ai_tools" }ai_toolset = { path = "../../crates/ai_toolset" }+calendar_events = { path = "../../crates/calendar_events", features = ["postgres"] }ai_usage = { path = "../../crates/ai_usage" }analytics_client = { path = "../../crates/analytics_client" }anyhow = { workspace = true }diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex fe5ec08538..d0ba56ca71 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -79,6 +79,7 @@ use agent_harness::outbound::github_branches::GithubRepositoryBranches;use agent_harness::outbound::github_repositories::GithubReachableRepositories;use agent_harness::outbound::local::{LocalContainerManager, LocalSettings};use agent_harness::outbound::notifications::IngressAgentSessionNotifier;+use agent_harness::outbound::primary_calendar_time_zones::PrimaryCalendarTimeZones;use agent_harness::outbound::prompt_mentions::{LexicalPromptMentions, PgSessionAccess};use agent_harness::outbound::routing::RoutedContainerManager;use agent_harness::outbound::runtime_registry::{HarnessKeyedConnections, RuntimeRegistry};@@ -1171,7 +1172,12 @@ async fn run() -> anyhow::Result<()> {LexicalPromptMentions::new(lexical.clone(), PgSessionAccess::new(pool.clone()));let prompt_context =MessagePromptContextAdapter::new(message_service.clone(), Arc::clone(&entity_access));- let prompt_composer = LexicalAgentPromptComposer::new(lexical);+ let prompt_composer = LexicalAgentPromptComposer::new(+ lexical,+ PrimaryCalendarTimeZones::new(calendar_events::domain::service::CalendarService::new(+ calendar_events::outbound::pg::PgCalendarRepository::new(pool.clone()),+ )),+ );// One connection per harness, shared by every session of every agent// bound to it. Held here because the gateway puts dialed-in sockets intodiff --git a/services/lexical-service/src/endpoints/agent-context.test.ts b/services/lexical-service/src/endpoints/agent-context.test.tsindex 7bea4011d1..9c22589194 100644--- a/services/lexical-service/src/endpoints/agent-context.test.ts+++ b/services/lexical-service/src/endpoints/agent-context.test.ts@@ -51,4 +51,19 @@ describe('agent context', () => {expect(markdown).toContain(`trigger kind=\\"conversation\\"`);expect(markdown).toContain('your private conversation with the user');});++ it('states the current time the harness sends', async () => {+ const response = await request({+ promptMarkdown: 'what is due today?',+ currentTime: {+ iso: '2026-09-24T16:03:36-04:00',+ local: 'Thursday, September 24, 2026, 4:03 PM',+ timeZone: 'America/New_York',+ },+ });+ expect(response.status).toBe(200);+ const { markdown }: { markdown: string } = await response.json();+ expect(markdown).toContain(`time_zone=\\"America/New_York\\"`);+ expect(markdown).toContain('Thursday, September 24, 2026, 4:03 PM');+ });});diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.tsindex 2d3ef33c68..9c972d622f 100644--- a/services/lexical-service/src/endpoints/agent-context.ts+++ b/services/lexical-service/src/endpoints/agent-context.ts@@ -424,6 +424,13 @@ export const agentContextRequest = zinstructions: z.string().optional(),owner: person.optional(),sender: person.optional(),+ currentTime: z+ .object({+ iso: z.string().min(1),+ local: z.string().min(1),+ timeZone: z.string().min(1).optional(),+ })+ .optional(),trigger: triggerContext.optional(),// LEGACY conversation fields; remove once every caller sends `trigger`.parent: messageParent.optional(),@@ -451,7 +458,7 @@ export class AgentContextEndpoint extends OpenAPIRoute {schema = {summary: 'Compose an agent prompt with conversation context',description:- 'Builds internal markdown naming the session owner and the prompt sender, and containing trusted session instructions and the trigger that called the agent - a mention or follow-up with its discussion, a task assignment, a composer request, a dispatch, or a routine firing - followed by the user prompt. The legacy conversation fields (parent, anchor, replyTarget, promptMessageId, thread, channel) are still accepted, but not together with trigger.',+ 'Builds internal markdown naming the session owner and the prompt sender, stating the current time in the user time zone, and containing trusted session instructions and the trigger that called the agent - a mention or follow-up with its discussion, a task assignment, a composer request, a dispatch, or a routine firing - followed by the user prompt. The legacy conversation fields (parent, anchor, replyTarget, promptMessageId, thread, channel) are still accepted, but not together with trigger.',request: {body: {content: {