Agent Zero AI framework
Refactor: use user locale for time displays
Alessandrod1827e6c6607
diff --git a/agent.py b/agent.pyindex 267a90807..7fc238ce6 100644--- a/agent.py+++ b/agent.py@@ -2,7 +2,7 @@ import asyncio, random, string, threadingfrom collections import OrderedDictfrom dataclasses import dataclass, field-from datetime import datetime, timezone+from datetime import datetimefrom typing import Any, Awaitable, Coroutine, Dict, Literalfrom enum import Enumimport models@@ -86,11 +86,11 @@ class AgentContext:self.paused = pausedself.streaming_agent = streaming_agentself.task: DeferredTask | None = None- self.created_at = created_at or datetime.now(timezone.utc)+ self.created_at = created_at or Localization.get().now()self.type = typeAgentContext._counter += 1self.no = AgentContext._counter- self.last_message = last_message or datetime.now(timezone.utc)+ self.last_message = last_message or Localization.get().now()# initialize agent at last (context is complete now)self.agent0 = agent0 or Agent(0, self.config, self)@@ -666,7 +666,7 @@ class Agent:def hist_add_message(self, ai: bool, content: history.MessageContent, tokens: int = 0, id: str = ""):- self.last_message = datetime.now(timezone.utc)+ self.last_message = Localization.get().now()# Allow extensions to process content before adding to historycontent_data = {"content": content}extension.call_extensions_sync(diff --git a/api/download_work_dir_files.py b/api/download_work_dir_files.pyindex a7a18d5de..74b668706 100644--- a/api/download_work_dir_files.py+++ b/api/download_work_dir_files.py@@ -1,5 +1,4 @@import base64-from datetime import datetimefrom io import BytesIOimport osfrom pathlib import Path@@ -10,6 +9,7 @@ from flask import Responsefrom helpers.api import ApiHandler, Input, Output, Requestfrom helpers import files, runtime+from helpers.localization import Localizationfrom api.download_work_dir_file import fetch_file, stream_file_download@@ -65,7 +65,7 @@ def normalize_paths(paths) -> list[str]:def selected_archive_name(count: int) -> str:- stamp = datetime.now().strftime("%Y%m%d-%H%M%S")+ stamp = Localization.get().now().strftime("%Y%m%d-%H%M%S")return f"agent-zero-selected-{count}-{stamp}.zip"diff --git a/api/notification_create.py b/api/notification_create.pyindex 11609a0db..73538922e 100644--- a/api/notification_create.py+++ b/api/notification_create.py@@ -57,6 +57,7 @@ class NotificationCreate(ApiHandler):return {"success": True,"notification_id": notification.id,+ "notification": notification.output(),"message": "Notification created successfully",}diff --git a/api/plugins.py b/api/plugins.pyindex 6e43dc34a..130ce7e8f 100644--- a/api/plugins.py+++ b/api/plugins.py@@ -2,10 +2,10 @@ import jsonimport osimport subprocessimport sys-from datetime import datetime, timezonefrom helpers.api import ApiHandler, Request, Responsefrom helpers import plugins, files, extension+from helpers.localization import Localizationclass Plugins(ApiHandler):@@ -287,7 +287,7 @@ class Plugins(ApiHandler):if not files.exists(execute_script):return Response(status=404, response="execute.py not found")- executed_at = datetime.now(timezone.utc).isoformat()+ executed_at = Localization.get().now_iso()try:result = subprocess.run([sys.executable, execute_script],diff --git a/api/settings_set.py b/api/settings_set.pyindex 21146605e..2118f2b60 100644--- a/api/settings_set.py+++ b/api/settings_set.py@@ -8,7 +8,11 @@ from typing import Anyclass SetSettings(ApiHandler):async def process(self, input: dict[Any, Any], request: Request) -> dict[Any, Any] | Response:frontend = input.get("settings", input)+ browser_timezone = input.get("browser_timezone")backend = settings.convert_in(settings.Settings(**frontend))- backend = settings.set_settings(backend)+ backend = settings.set_settings(+ backend,+ browser_timezone=browser_timezone if isinstance(browser_timezone, str) else None,+ )out = settings.convert_out(backend)return dict(out)diff --git a/extensions/python/message_loop_prompts_after/_60_include_current_datetime.py b/extensions/python/message_loop_prompts_after/_60_include_current_datetime.pyindex 7ab073c45..c57c52291 100644--- a/extensions/python/message_loop_prompts_after/_60_include_current_datetime.py+++ b/extensions/python/message_loop_prompts_after/_60_include_current_datetime.py@@ -1,4 +1,3 @@-from datetime import datetime, timezonefrom helpers.extension import Extensionfrom agent import LoopDatafrom helpers.localization import Localization@@ -9,13 +8,7 @@ class IncludeCurrentDatetime(Extension):if not self.agent:return- # get current datetime- current_datetime = Localization.get().utc_dt_to_localtime_str(- datetime.now(timezone.utc), sep=" ", timespec="seconds"- )- # remove timezone offset- if current_datetime and "+" in current_datetime:- current_datetime = current_datetime.split("+")[0]+ current_datetime = Localization.get().now().strftime("%Y-%m-%d %H:%M:%S %Z")# read promptdatetime_prompt = self.agent.read_prompt(diff --git a/extensions/python/user_message_ui/_10_update_check.py b/extensions/python/user_message_ui/_10_update_check.pyindex 5c4508712..ff1e5844e 100644--- a/extensions/python/user_message_ui/_10_update_check.py+++ b/extensions/python/user_message_ui/_10_update_check.py@@ -2,6 +2,7 @@ from helpers import notificationfrom helpers.extension import Extensionfrom agent import LoopDatafrom helpers import files, settings, update_check+from helpers.localization import Localizationimport datetimeimport json@@ -11,14 +12,18 @@ import json# do not check too often, use cooldown# do not notify too often-last_check = datetime.datetime.fromtimestamp(0)+last_check = datetime.datetime.fromtimestamp(0, tz=Localization.get().get_tzinfo())check_cooldown_seconds = 60last_notification_id = None-last_notification_time = datetime.datetime.fromtimestamp(0)+last_notification_time = datetime.datetime.fromtimestamp(0, tz=Localization.get().get_tzinfo())notification_cooldown_seconds = 60 * 60 * 24notification_state_file = "usr/update-check-state.json"+def _now() -> datetime.datetime:+ return Localization.get().now()++def _load_notification_state() -> dict:try:return json.loads(files.read_file(notification_state_file))@@ -34,13 +39,13 @@ def _parse_timestamp(value: str | None) -> datetime.datetime | None:except ValueError:return Noneif parsed.tzinfo:- return parsed.astimezone(datetime.timezone.utc).replace(tzinfo=None)- return parsed+ return parsed.astimezone(Localization.get().get_tzinfo())+ return Localization.get().localize_naive_datetime(parsed)def _remember_notification(notif: dict, now: datetime.datetime):state = {- "last_notification_at": now.replace(tzinfo=datetime.timezone.utc).isoformat(),+ "last_notification_at": now.isoformat(),"last_notification_id": notif.get("id") or "","last_notification_group": notif.get("group", "update_check"),}@@ -62,16 +67,17 @@ class UpdateCheck(Extension):return# check if cooldown has passed- if (datetime.datetime.now() - last_check).total_seconds() < check_cooldown_seconds:+ now = _now()+ if (now - last_check).total_seconds() < check_cooldown_seconds:return- last_check = datetime.datetime.now()+ last_check = now# check for updatesversion = await update_check.check_version()# if the user should update, send notificationif notif := version.get("notification"):- now = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)+ now = _now()stored_state = _load_notification_state()stored_notification_time = _parse_timestamp(stored_state.get("last_notification_at"))effective_notification_time = stored_notification_time or last_notification_timediff --git a/helpers/backup.py b/helpers/backup.pyindex 0100fdf77..1aa651893 100644--- a/helpers/backup.py+++ b/helpers/backup.py@@ -9,6 +9,7 @@ from typing import List, Dict, Any, Optionalfrom pathspec import PathSpecfrom helpers import files, runtime, git+from helpers.localization import Localizationfrom helpers.print_style import PrintStyle@@ -35,7 +36,7 @@ class BackupService:def get_default_backup_metadata(self) -> Dict[str, Any]:"""Get default backup patterns and metadata"""- timestamp = datetime.datetime.now().isoformat()+ timestamp = Localization.get().now_iso()default_patterns = self._get_default_patterns()include_patterns, exclude_patterns = self._parse_patterns(default_patterns)@@ -144,7 +145,7 @@ class BackupService:"home": os.environ.get("HOME", "unknown"),"shell": os.environ.get("SHELL", "unknown"),"path": os.environ.get("PATH", "")[:200] + "..." if len(os.environ.get("PATH", "")) > 200 else os.environ.get("PATH", ""),- "timezone": str(datetime.datetime.now().astimezone().tzinfo),+ "timezone": Localization.get().get_timezone(),"working_directory": os.getcwd(),"agent_zero_root": files.get_abs_path(""),"runtime_mode": "development" if runtime.is_development() else "production"@@ -305,7 +306,10 @@ class BackupService:"path": pattern_path,"real_path": file_path,"size": stat.st_size,- "modified": datetime.datetime.fromtimestamp(stat.st_mtime).isoformat(),+ "modified": datetime.datetime.fromtimestamp(+ stat.st_mtime,+ tz=Localization.get().get_tzinfo(),+ ).isoformat(),"type": "file"})processed_count += 1@@ -356,7 +360,7 @@ class BackupService:metadata = {# Basic backup information"agent_zero_version": self.agent_zero_version,- "timestamp": datetime.datetime.now().isoformat(),+ "timestamp": Localization.get().now_iso(),"backup_name": backup_name,"include_hidden": include_hidden,@@ -698,7 +702,7 @@ class BackupService:})continueelif overwrite_policy == "backup":- timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')+ timestamp = Localization.get().now().strftime('%Y%m%d_%H%M%S')backup_path = f"{target_path}.backup.{timestamp}"import shutilshutil.move(target_path, backup_path)diff --git a/helpers/document_query.py b/helpers/document_query.pyindex 4bc8052a6..31053721f 100644--- a/helpers/document_query.py+++ b/helpers/document_query.py@@ -10,7 +10,6 @@ from langchain_unstructured import UnstructuredLoader # noqa E402from urllib.parse import urlparsefrom typing import Callable, Sequence, List, Optional, Tuple-from datetime import datetimefrom langchain_community.document_loaders.pdf import PyMuPDFLoaderfrom langchain_community.document_transformers import MarkdownifyTransformer@@ -20,6 +19,7 @@ from langchain_core.documents import Documentfrom langchain.schema import SystemMessage, HumanMessagefrom helpers.print_style import PrintStyle+from helpers.localization import Localizationfrom helpers import files, errorsfrom helpers.network import HttpFetchResult, fetch_public_http_resourcefrom agent import Agent@@ -120,7 +120,7 @@ class DocumentQueryStore:# Initialize metadatadoc_metadata = metadata or {}doc_metadata["document_uri"] = document_uri- doc_metadata["timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")+ doc_metadata["timestamp"] = Localization.get().now_iso(timespec="seconds")# Split text into chunkstext_splitter = RecursiveCharacterTextSplitter(diff --git a/helpers/file_browser.py b/helpers/file_browser.pyindex 4f58d4c2e..4b3ac2746 100644--- a/helpers/file_browser.py+++ b/helpers/file_browser.py@@ -8,6 +8,7 @@ from helpers.security import safe_filenamefrom datetime import datetimefrom helpers import files+from helpers.localization import Localizationfrom helpers.print_style import PrintStyle@@ -260,7 +261,10 @@ class FileBrowser:entry_data: Dict[str, Any] = {"name": filename,"path": str(entry_path.relative_to(self.base_dir)),- "modified": datetime.fromtimestamp(stat_info.st_mtime).isoformat()+ "modified": datetime.fromtimestamp(+ stat_info.st_mtime,+ tz=Localization.get().get_tzinfo(),+ ).isoformat()}# Add symlink information if this is a symlinkdiff --git a/helpers/file_tree.py b/helpers/file_tree.pyindex b08361e60..abc0a982f 100644--- a/helpers/file_tree.py+++ b/helpers/file_tree.py@@ -2,13 +2,14 @@ from __future__ import annotationsfrom collections import dequefrom dataclasses import dataclass-from datetime import datetime, timezone+from datetime import datetimeimport osfrom typing import Any, Callable, Iterable, Literal, Optional, Sequencefrom pathspec import PathSpecfrom helpers import files as files_helper+from helpers.localization import LocalizationSORT_BY_NAME = "name"SORT_BY_CREATED = "created"@@ -22,6 +23,10 @@ OUTPUT_MODE_FLAT = "flat"OUTPUT_MODE_NESTED = "nested"+def _from_timestamp(timestamp: float) -> datetime:+ return datetime.fromtimestamp(timestamp, tz=Localization.get().get_tzinfo())++def file_tree(relative_path: str,*,@@ -75,7 +80,7 @@ def file_tree(while traversal and limit calculations remain breadth-first by depth. When ``max_lines`` is set, the numberof non-comment entries (excluding the root banner) never exceeds that limit; informational summary commentsare emitted in addition when necessary.- * ``created`` and ``modified`` values in structured outputs are timezone-aware UTC+ * ``created`` and ``modified`` values in structured outputs are timezone-aware user-local:class:`datetime.datetime` objects::item = flat_items[0]@@ -111,8 +116,8 @@ def file_tree(name=root_name,level=0,item_type="folder",- created=datetime.fromtimestamp(root_stat.st_ctime, tz=timezone.utc),- modified=datetime.fromtimestamp(root_stat.st_mtime, tz=timezone.utc),+ created=_from_timestamp(root_stat.st_ctime),+ modified=_from_timestamp(root_stat.st_mtime),parent=None,items=[],rel_path="",@@ -132,8 +137,8 @@ def file_tree(name=entry.name,level=level,item_type=item_type,- created=datetime.fromtimestamp(stat.st_ctime, tz=timezone.utc),- modified=datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc),+ created=_from_timestamp(stat.st_ctime),+ modified=_from_timestamp(stat.st_mtime),parent=parent,items=[] if item_type == "folder" else None,rel_path=rel_posix,@@ -413,8 +418,8 @@ def _create_folder_unprocessed_comment(name=entry.name,level=folder_node.level + 1,item_type="folder",- created=datetime.fromtimestamp(stat.st_ctime, tz=timezone.utc),- modified=datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc),+ created=_from_timestamp(stat.st_ctime),+ modified=_from_timestamp(stat.st_mtime),parent=folder_node,items=None,rel_path=os.path.join(folder_node.rel_path, entry.name),@@ -427,8 +432,8 @@ def _create_folder_unprocessed_comment(name=entry.name,level=folder_node.level + 1,item_type="file",- created=datetime.fromtimestamp(stat.st_ctime, tz=timezone.utc),- modified=datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc),+ created=_from_timestamp(stat.st_ctime),+ modified=_from_timestamp(stat.st_mtime),parent=folder_node,items=None,rel_path=os.path.join(folder_node.rel_path, entry.name),diff --git a/helpers/git.py b/helpers/git.pyindex f3aa9a303..609db2bbb 100644--- a/helpers/git.py+++ b/helpers/git.py@@ -8,6 +8,7 @@ import base64import refrom urllib.parse import urlparse, urlunparsefrom helpers import files+from helpers.localization import Localizationdef strip_auth_from_url(url: str) -> str:@@ -98,7 +99,10 @@ class GitRepoReleaseInfo:def _format_git_timestamp(timestamp: int) -> str:- return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')+ return datetime.fromtimestamp(+ timestamp,+ tz=Localization.get().get_tzinfo(),+ ).strftime('%Y-%m-%d %H:%M:%S %Z')def _split_describe_version(describe: str) -> tuple[str, int]:@@ -517,7 +521,10 @@ def get_repo_status(repo_path: str) -> dict:"hash": commit.hexsha[:7],"message": str(commit.message).split("\n")[0][:80],"author": str(commit.author),- "date": datetime.fromtimestamp(commit.committed_date).strftime('%Y-%m-%d %H:%M')+ "date": datetime.fromtimestamp(+ commit.committed_date,+ tz=Localization.get().get_tzinfo(),+ ).strftime('%Y-%m-%d %H:%M %Z')}except Exception:passdiff --git a/helpers/localization.py b/helpers/localization.pyindex e9076a55b..eaf8c749a 100644--- a/helpers/localization.py+++ b/helpers/localization.py@@ -1,4 +1,6 @@-from datetime import datetime, timezone as dt_timezone, timedelta+from datetime import datetime, timezone as dt_timezone+import os+import timeimport pytz # type: ignorefrom helpers.print_style import PrintStyle@@ -8,9 +10,9 @@ from helpers.dotenv import get_dotenv_value, save_dotenv_valueclass Localization:"""- Localization class for handling timezone conversions between UTC and local time.- Now stores a fixed UTC offset (in minutes) derived from the provided timezone name- to avoid noisy updates when equivalent timezones share the same offset.+ Localization class for handling timezone conversions around the user's IANA+ timezone. UTC is still used when an external protocol requires an absolute+ instant, but user-facing timestamps are formatted in the configured timezone."""# singleton@@ -26,29 +28,38 @@ class Localization:self.timezone: str = "UTC"self._offset_minutes: int = 0self._last_timezone_change: datetime | None = None- # Load persisted values if available- persisted_tz = str(get_dotenv_value("DEFAULT_USER_TIMEZONE", "UTC"))+ # Load persisted values if available.+ persisted_tz = str(get_dotenv_value("DEFAULT_USER_TIMEZONE", os.environ.get("TZ") or "UTC"))persisted_offset = get_dotenv_value("DEFAULT_USER_UTC_OFFSET_MINUTES", None)if timezone is not None:# Explicit overrideself.set_timezone(timezone)else:# Initialize from persisted values- self.timezone = persisted_tz- if persisted_offset is not None:- try:- self._offset_minutes = int(str(persisted_offset))- except Exception:- self._offset_minutes = self._compute_offset_minutes(self.timezone)- save_dotenv_value("DEFAULT_USER_UTC_OFFSET_MINUTES", str(self._offset_minutes))- else:- # Compute from timezone and persist- self._offset_minutes = self._compute_offset_minutes(self.timezone)+ try:+ pytz.timezone(persisted_tz)+ self.timezone = persisted_tz+ except pytz.exceptions.UnknownTimeZoneError:+ self.timezone = "UTC"+ current_offset = self._compute_offset_minutes(self.timezone)+ try:+ persisted_offset_minutes = int(str(persisted_offset)) if persisted_offset is not None else None+ except Exception:+ persisted_offset_minutes = None+ self._offset_minutes = current_offset+ if persisted_offset_minutes != current_offset:save_dotenv_value("DEFAULT_USER_UTC_OFFSET_MINUTES", str(self._offset_minutes))+ self.apply_process_timezone()def get_timezone(self) -> str:return self.timezone+ def get_tzinfo(self):+ try:+ return pytz.timezone(self.timezone)+ except pytz.exceptions.UnknownTimeZoneError:+ return pytz.timezone("UTC")+def _compute_offset_minutes(self, timezone_name: str) -> int:tzinfo = pytz.timezone(timezone_name)now_in_tz = datetime.now(tzinfo)@@ -58,76 +69,97 @@ class Localization:def get_offset_minutes(self) -> int:return self._offset_minutes- def _can_change_timezone(self) -> bool:- """Check if timezone can be changed (rate limited to once per hour)."""- if self._last_timezone_change is None:- return True-- time_diff = datetime.now() - self._last_timezone_change- return time_diff >= timedelta(hours=1)+ def apply_process_timezone(self) -> None:+ """Apply the configured timezone to this process and child processes."""+ os.environ["TZ"] = self.timezone+ if hasattr(time, "tzset"):+ try:+ time.tzset()+ except Exception as e:+ PrintStyle.error(f"Error applying timezone {self.timezone}: {e}")++ def now(self) -> datetime:+ """Return the current datetime in the user's configured timezone."""+ return datetime.now(self.get_tzinfo())++ def now_iso(self, sep: str = "T", timespec: str = "auto") -> str:+ return self.now().isoformat(sep=sep, timespec=timespec)++ def localize_naive_datetime(self, dt: datetime) -> datetime:+ """Treat a naive datetime as user-local and make it timezone-aware."""+ if dt.tzinfo is not None:+ return dt+ tzinfo = self.get_tzinfo()+ try:+ return tzinfo.localize(dt, is_dst=None)+ except pytz.exceptions.AmbiguousTimeError:+ return tzinfo.localize(dt, is_dst=False)+ except pytz.exceptions.NonExistentTimeError:+ return tzinfo.localize(dt, is_dst=True)def set_timezone(self, timezone: str) -> None:- """Set the timezone name, but internally store and compare by UTC offset minutes."""+ """Set the user's IANA timezone and propagate it to child processes."""try:# Validate timezone and compute its current offset_ = pytz.timezone(timezone)new_offset = self._compute_offset_minutes(timezone)-- # If offset changes, check rate limit and update- if new_offset != getattr(self, "_offset_minutes", None):- if not self._can_change_timezone():- return-- prev_tz = getattr(self, "timezone", "None")- prev_off = getattr(self, "_offset_minutes", None)- PrintStyle.debug(- f"Changing timezone from {prev_tz} (offset {prev_off}) to {timezone} (offset {new_offset})"- )- self._offset_minutes = new_offset- self.timezone = timezone- # Persist both the human-readable tz and the numeric offset- save_dotenv_value("DEFAULT_USER_TIMEZONE", timezone)- save_dotenv_value("DEFAULT_USER_UTC_OFFSET_MINUTES", str(self._offset_minutes))-- # Update rate limit timestamp only when actual change occurs- self._last_timezone_change = datetime.now()- else:- # Offset unchanged: update stored timezone without logging or persisting to avoid churn- self.timezone = timezone+ if timezone == self.timezone and new_offset == self._offset_minutes:+ self.apply_process_timezone()+ return++ prev_tz = getattr(self, "timezone", "None")+ prev_off = getattr(self, "_offset_minutes", None)+ PrintStyle.debug(+ f"Changing timezone from {prev_tz} (offset {prev_off}) to {timezone} (offset {new_offset})"+ )+ self._offset_minutes = new_offset+ self.timezone = timezone+ save_dotenv_value("DEFAULT_USER_TIMEZONE", timezone)+ save_dotenv_value("DEFAULT_USER_UTC_OFFSET_MINUTES", str(self._offset_minutes))+ self.apply_process_timezone()+ self._last_timezone_change = datetime.now()except pytz.exceptions.UnknownTimeZoneError:- PrintStyle.error(f"Unknown timezone: {timezone}, defaulting to UTC")- self.timezone = "UTC"- self._offset_minutes = 0- # save defaults to avoid future errors on startup- save_dotenv_value("DEFAULT_USER_TIMEZONE", "UTC")- save_dotenv_value("DEFAULT_USER_UTC_OFFSET_MINUTES", "0")+ fallback_timezone = self.timezone+ try:+ pytz.timezone(fallback_timezone)+ except pytz.exceptions.UnknownTimeZoneError:+ fallback_timezone = "UTC"++ PrintStyle.error(f"Unknown timezone: {timezone}, keeping {fallback_timezone}")+ self.timezone = fallback_timezone+ self._offset_minutes = self._compute_offset_minutes(fallback_timezone)+ self.apply_process_timezone()def localtime_str_to_utc_dt(self, localtime_str: str | None) -> datetime | None:"""Convert a local time ISO string to a UTC datetime object.Returns None if input is None or invalid.- When input lacks tzinfo, assume the configured fixed UTC offset.+ When input lacks tzinfo, assume the configured user timezone."""if not localtime_str:return Nonetry:+ localtime_str = localtime_str.strip().replace("Z", "+00:00")# Handle both with and without timezone infotry:# Try parsing with timezone info firstlocal_datetime_obj = datetime.fromisoformat(localtime_str)if local_datetime_obj.tzinfo is None:- # If no timezone info, assume fixed offset- local_datetime_obj = local_datetime_obj.replace(- tzinfo=dt_timezone(timedelta(minutes=self._offset_minutes))- )+ # If no timezone info, assume the configured user timezone.+ local_datetime_obj = self.localize_naive_datetime(local_datetime_obj)except ValueError:- # If timezone parsing fails, try without timezone- base = localtime_str.split('Z')[0].split('+')[0]- local_datetime_obj = datetime.fromisoformat(base)- local_datetime_obj = local_datetime_obj.replace(- tzinfo=dt_timezone(timedelta(minutes=self._offset_minutes))- )+ # If timezone parsing fails, try a few common local formats.+ cleaned = localtime_str.replace("T", " ")+ for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):+ try:+ local_datetime_obj = datetime.strptime(cleaned, fmt)+ local_datetime_obj = self.localize_naive_datetime(local_datetime_obj)+ break+ except ValueError:+ continue+ else:+ raise# Convert to UTCreturn local_datetime_obj.astimezone(dt_timezone.utc)@@ -137,7 +169,7 @@ class Localization:def utc_dt_to_localtime_str(self, utc_dt: datetime | None, sep: str = "T", timespec: str = "auto") -> str | None:"""- Convert a UTC datetime object to a local time ISO string using the fixed UTC offset.+ Convert a UTC datetime object to a local time ISO string using the user's timezone.Returns None if input is None."""if utc_dt is None:@@ -153,9 +185,8 @@ class Localization:else:utc_dt = utc_dt.astimezone(dt_timezone.utc)- # Convert to local time using fixed offset- local_tz = dt_timezone(timedelta(minutes=self._offset_minutes))- local_datetime_obj = utc_dt.astimezone(local_tz)+ # Convert to local time using the user's timezone.+ local_datetime_obj = utc_dt.astimezone(self.get_tzinfo())return local_datetime_obj.isoformat(sep=sep, timespec=timespec)except Exception as e:PrintStyle.error(f"Error converting UTC datetime to localtime string: {e}")@@ -163,8 +194,8 @@ class Localization:def serialize_datetime(self, dt: datetime | None) -> str | None:"""- Serialize a datetime object to ISO format string using the user's fixed UTC offset.- This ensures the frontend receives dates with the correct current offset for display.+ Serialize a datetime object to ISO format string using the user's timezone.+ This ensures the frontend receives dates with the correct offset for display."""if dt is None:return None@@ -173,12 +204,11 @@ class Localization:assert dt is not Nonetry:- # Ensure datetime is timezone aware (if not, assume UTC)+ # Ensure datetime is timezone aware (if not, assume the user's timezone)if dt.tzinfo is None:- dt = dt.replace(tzinfo=dt_timezone.utc)+ dt = self.localize_naive_datetime(dt)- local_tz = dt_timezone(timedelta(minutes=self._offset_minutes))- local_dt = dt.astimezone(local_tz)+ local_dt = dt.astimezone(self.get_tzinfo())return local_dt.isoformat()except Exception as e:PrintStyle.error(f"Error serializing datetime: {e}")diff --git a/helpers/notification.py b/helpers/notification.pyindex 908596b21..e76de42e5 100644--- a/helpers/notification.py+++ b/helpers/notification.py@@ -1,9 +1,11 @@from dataclasses import dataclassimport uuidimport threading-from datetime import datetime, timezone, timedelta+from datetime import datetime, timedeltafrom enum import Enum+from helpers.localization import Localization+class NotificationType(Enum):INFO = "info"@@ -53,7 +55,7 @@ class NotificationItem:"title": self.title,"message": self.message,"detail": self.detail,- "timestamp": self.timestamp.isoformat(),+ "timestamp": Localization.get().serialize_datetime(self.timestamp),"display_time": self.display_time,"read": self.read,"group": self.group,@@ -106,7 +108,7 @@ class NotificationManager:existing.title = titleexisting.message = messageexisting.detail = detail- existing.timestamp = datetime.now(timezone.utc)+ existing.timestamp = Localization.get().now()existing.display_time = display_timeexisting.group = groupexisting.read = False@@ -122,7 +124,7 @@ class NotificationManager:title=title,message=message,detail=detail,- timestamp=datetime.now(timezone.utc),+ timestamp=Localization.get().now(),display_time=display_time,id=id,group=group,@@ -149,7 +151,7 @@ class NotificationManager:self.updates = [no - to_remove for no in self.updates if no >= to_remove]def get_recent_notifications(self, seconds: int = 30) -> list[NotificationItem]:- cutoff = datetime.now(timezone.utc) - timedelta(seconds=seconds)+ cutoff = Localization.get().now() - timedelta(seconds=seconds)with self._lock:return [n for n in self.notifications if n.timestamp >= cutoff]diff --git a/helpers/persist_chat.py b/helpers/persist_chat.pyindex 3d0081ddd..086a68fa7 100644--- a/helpers/persist_chat.py+++ b/helpers/persist_chat.py@@ -4,6 +4,7 @@ from typing import Anyimport uuidfrom agent import Agent, AgentConfig, AgentContext, AgentContextTypefrom helpers import files, history+from helpers.localization import Localizationimport jsonfrom initialize import initialize_agent@@ -14,6 +15,18 @@ LOG_SIZE = 1000CHAT_FILE_NAME = "chat.json"+def _fallback_datetime_iso() -> str:+ return datetime.fromtimestamp(0, tz=Localization.get().get_tzinfo()).isoformat()+++def _parse_persisted_datetime(value: str | None) -> datetime:+ raw_value = value or _fallback_datetime_iso()+ dt = datetime.fromisoformat(raw_value)+ if dt.tzinfo is None:+ dt = Localization.get().localize_naive_datetime(dt)+ return dt++def get_chat_folder_path(ctxid: str):"""Get the folder path for any context (chat or task).@@ -137,15 +150,15 @@ def _serialize_context(context: AgentContext):"id": context.id,"name": context.name,"created_at": (- context.created_at.isoformat()+ Localization.get().serialize_datetime(context.created_at)if context.created_at- else datetime.fromtimestamp(0).isoformat()+ else _fallback_datetime_iso()),"type": context.type.value,"last_message": (- context.last_message.isoformat()+ Localization.get().serialize_datetime(context.last_message)if context.last_message- else datetime.fromtimestamp(0).isoformat()+ else _fallback_datetime_iso()),"agents": agents,"streaming_agent": (@@ -196,16 +209,11 @@ def _deserialize_context(data):id=data.get("id", None), # get new idname=data.get("name", None),created_at=(- datetime.fromisoformat(- # older chats may not have created_at - backcompat- data.get("created_at", datetime.fromtimestamp(0).isoformat())- )+ _parse_persisted_datetime(data.get("created_at"))),type=AgentContextType(data.get("type", AgentContextType.USER.value)),last_message=(- datetime.fromisoformat(- data.get("last_message", datetime.fromtimestamp(0).isoformat())- )+ _parse_persisted_datetime(data.get("last_message"))),log=log,paused=False,diff --git a/helpers/self_update.py b/helpers/self_update.pyindex 37f589464..cd718de8b 100644--- a/helpers/self_update.py+++ b/helpers/self_update.py@@ -5,11 +5,12 @@ import reimport subprocessimport tempfileimport time-from datetime import UTC, datetime+from datetime import datetimefrom pathlib import Pathfrom typing import Any, Literal, TypedDictfrom helpers import git, yaml+from helpers.localization import LocalizationOFFICIAL_REPO_AUTHOR = "agent0ai"@@ -73,7 +74,7 @@ class SelectorTagOption(TypedDict):def _now_iso() -> str:- return datetime.now(UTC).isoformat().replace("+00:00", "Z")+ return Localization.get().now_iso()def get_update_file_path() -> Path:@@ -197,7 +198,10 @@ def _get_tag_release_time_in_repo(timestamp = _run_git(repo_dir, "log", "-1", "--format=%ct", normalized_tag)if not timestamp:return ""- return datetime.fromtimestamp(int(timestamp)).strftime("%Y-%m-%d %H:%M:%S")+ return datetime.fromtimestamp(+ int(timestamp),+ tz=Localization.get().get_tzinfo(),+ ).strftime("%Y-%m-%d %H:%M:%S %Z")except Exception:return ""@@ -242,7 +246,7 @@ def build_default_backup_name(current_version: str,target_tag: str | None = None,) -> str:- timestamp = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")+ timestamp = Localization.get().now().strftime("%Y%m%d-%H%M%S")return f"usr-{timestamp}.zip"diff --git a/helpers/settings.py b/helpers/settings.pyindex f42a48b93..e9b707f5e 100644--- a/helpers/settings.py+++ b/helpers/settings.py@@ -7,6 +7,7 @@ import subprocessfrom typing import Any, Literal, TypedDict, cast, TypeVarimport models+import pytz # type: ignorefrom helpers import runtime, defer, git, subagentsfrom . import files, dotenvfrom helpers.print_style import PrintStyle@@ -55,6 +56,8 @@ class Settings(TypedDict):agent_profile: stragent_knowledge_subdir: str+ timezone: str+ time_format: strworkdir_path: strworkdir_show: bool@@ -143,6 +146,8 @@ class SettingsOutputAdditional(TypedDict):embedding_providers: list[ModelProvider]agent_subdirs: list[FieldOption]knowledge_subdirs: list[FieldOption]+ timezones: list[FieldOption]+ resolved_timezone: stris_dockerized: boolruntime_settings: dict[str, Any]@@ -154,6 +159,9 @@ class SettingsOutput(TypedDict):PASSWORD_PLACEHOLDER = "****PSWD****"API_KEY_PLACEHOLDER = "************"+TIMEZONE_AUTO = "auto"+TIME_FORMAT_12H = "12h"+TIME_FORMAT_24H = "24h"SETTINGS_FILE = files.get_abs_path("usr/settings.json")_settings: Settings | None = None@@ -175,6 +183,49 @@ def _ensure_option_present(options: list[OptionT] | None, current_value: str | Nopts.insert(0, cast(OptionT, {"value": current_value, "label": current_value}))return opts++def _is_valid_timezone(value: str) -> bool:+ try:+ pytz.timezone(value)+ return True+ except pytz.exceptions.UnknownTimeZoneError:+ return False+++def _normalize_timezone_setting(value: Any, default: str = TIMEZONE_AUTO) -> str:+ timezone = str(value or "").strip()+ if timezone.lower() == TIMEZONE_AUTO:+ return TIMEZONE_AUTO+ if _is_valid_timezone(timezone):+ return timezone+ return default if default == TIMEZONE_AUTO or _is_valid_timezone(default) else TIMEZONE_AUTO+++def _normalize_time_format(value: Any, default: str = TIME_FORMAT_12H) -> str:+ time_format = str(value or "").strip().lower()+ if time_format in {TIME_FORMAT_12H, TIME_FORMAT_24H}:+ return time_format+ return default if default in {TIME_FORMAT_12H, TIME_FORMAT_24H} else TIME_FORMAT_12H+++def _resolve_runtime_timezone(setting_value: str, browser_timezone: str | None = None) -> str:+ if setting_value == TIMEZONE_AUTO:+ candidate = str(browser_timezone or "").strip()+ if _is_valid_timezone(candidate):+ return candidate+ try:+ from helpers.localization import Localization++ return Localization.get().get_timezone()+ except Exception:+ return "UTC"+ return _normalize_timezone_setting(setting_value, default="UTC")+++def _timezone_options() -> list[FieldOption]:+ return [{"value": timezone, "label": timezone} for timezone in pytz.common_timezones]++def convert_out(settings: Settings) -> SettingsOutput:out = SettingsOutput(settings = settings.copy(),@@ -187,6 +238,8 @@ def convert_out(settings: Settings) -> SettingsOutput:if item["key"] != "_example"],knowledge_subdirs=[{"value": subdir, "label": subdir}for subdir in files.get_subdirectories("knowledge", exclude="default")],+ timezones=_timezone_options(),+ resolved_timezone="UTC",runtime_settings={},),)@@ -208,6 +261,9 @@ def convert_out(settings: Settings) -> SettingsOutput:additional["agent_subdirs"] = _ensure_option_present(additional.get("agent_subdirs"), current.get("agent_profile"))additional["knowledge_subdirs"] = _ensure_option_present(additional.get("knowledge_subdirs"), current.get("agent_knowledge_subdir"))+ if current.get("timezone") != TIMEZONE_AUTO:+ additional["timezones"] = _ensure_option_present(additional.get("timezones"), current.get("timezone"))+ additional["resolved_timezone"] = _resolve_runtime_timezone(current.get("timezone", TIMEZONE_AUTO))# masked api keysproviders = get_providers("chat") + get_providers("embedding")@@ -294,13 +350,13 @@ def set_runtime_settings_snapshot(settings: Settings) -> None:_runtime_settings_snapshot = settings.copy()-def set_settings(settings: Settings, apply: bool = True):+def set_settings(settings: Settings, apply: bool = True, browser_timezone: str | None = None):global _settingsprevious = _settings_settings = normalize_settings(settings)_write_settings_file(_settings)if apply:- _apply_settings(previous)+ _apply_settings(previous, browser_timezone)return reload_settings()@@ -344,6 +400,8 @@ def normalize_settings(settings: Settings) -> Settings:# mcp server token is set automaticallycopy["mcp_server_token"] = create_auth_token()+ copy["timezone"] = _normalize_timezone_setting(copy.get("timezone"), default["timezone"])+ copy["time_format"] = _normalize_time_format(copy.get("time_format"), default["time_format"])return copy@@ -439,6 +497,8 @@ def get_default_settings() -> Settings:root_password="",agent_profile=get_default_value("agent_profile", "agent0"),agent_knowledge_subdir=get_default_value("agent_knowledge_subdir", "custom"),+ timezone=_normalize_timezone_setting(get_default_value("timezone", TIMEZONE_AUTO)),+ time_format=_normalize_time_format(get_default_value("time_format", TIME_FORMAT_12H)),workdir_path=get_default_value("workdir_path", files.get_abs_path_dockerized("usr/workdir")),workdir_show=get_default_value("workdir_show", True),workdir_max_depth=get_default_value("workdir_max_depth", 5),@@ -466,9 +526,47 @@ def get_default_settings() -> Settings:)-def _apply_settings(previous: Settings | None):+def _apply_timezone_setting(previous: Settings | None, browser_timezone: str | None = None) -> None:+ if not _settings:+ return++ from helpers.localization import Localization++ localization = Localization.get()+ previous_timezone = localization.get_timezone()+ target_timezone = _resolve_runtime_timezone(_settings["timezone"], browser_timezone)+ if (+ previous+ and _settings["timezone"] == previous.get("timezone")+ and _settings["timezone"] != TIMEZONE_AUTO+ and previous_timezone == target_timezone+ ):+ return++ localization.set_timezone(target_timezone)+ current_timezone = localization.get_timezone()+ if current_timezone == previous_timezone:+ return++ try:+ from helpers import plugins++ plugins.call_plugin_hook(+ "_office",+ "timezone_changed",+ None,+ previous_timezone=previous_timezone,+ timezone=current_timezone,+ )+ except Exception:+ return+++def _apply_settings(previous: Settings | None, browser_timezone: str | None = None):global _settingsif _settings:+ _apply_timezone_setting(previous, browser_timezone)+from agent import AgentContextfrom initialize import initialize_agentdiff --git a/helpers/state_snapshot.py b/helpers/state_snapshot.pyindex 6c8753270..a51f6239e 100644--- a/helpers/state_snapshot.py+++ b/helpers/state_snapshot.py@@ -200,7 +200,7 @@ def _coerce_state_request_inputs(timezone: Any,) -> StateRequestV1:tz = timezone if isinstance(timezone, str) and timezone else None- tz = tz or get_dotenv_value("DEFAULT_USER_TIMEZONE", "UTC")+ tz = tz or get_dotenv_value("DEFAULT_USER_TIMEZONE", Localization.get().get_timezone())ctxid: str | None = context.strip() if isinstance(context, str) else Noneif ctxid == "":@@ -242,7 +242,12 @@ def advance_state_request_after_snapshot(async def build_snapshot_from_request(*, request: StateRequestV1) -> SnapshotV1:"""Build a poll-shaped snapshot for both /poll and state_push."""- Localization.get().set_timezone(request.timezone)+ localization = Localization.get()+ previous_timezone = localization.get_timezone()+ localization.set_timezone(request.timezone)+ current_timezone = localization.get_timezone()+ if current_timezone != previous_timezone:+ _notify_timezone_changed(previous_timezone, current_timezone)ctxid = request.context if isinstance(request.context, str) else ""ctxid = ctxid.strip()@@ -339,6 +344,21 @@ async def build_snapshot_from_request(*, request: StateRequestV1) -> SnapshotV1:return snapshot+def _notify_timezone_changed(previous_timezone: str, current_timezone: str) -> None:+ try:+ from helpers import plugins++ plugins.call_plugin_hook(+ "_office",+ "timezone_changed",+ None,+ previous_timezone=previous_timezone,+ timezone=current_timezone,+ )+ except Exception:+ return++async def build_snapshot(*,context: str | None,diff --git a/helpers/task_scheduler.py b/helpers/task_scheduler.pyindex 94a36f378..fada618e9 100644--- a/helpers/task_scheduler.py+++ b/helpers/task_scheduler.py@@ -41,6 +41,35 @@ def normalize_schedule_timezone(timezone_name: str | None) -> str:return Localization.get().get_timezone()return name++def _now() -> datetime:+ localization = Localization.get()+ now = getattr(localization, "now", None)+ if callable(now):+ return now()++ try:+ tzinfo = pytz.timezone(localization.get_timezone())+ except Exception:+ tzinfo = pytz.timezone("UTC")+ return datetime.now(tzinfo)+++def _localize_task_datetime(dt: datetime) -> datetime:+ if dt.tzinfo is not None:+ return dt++ localization = Localization.get()+ localize = getattr(localization, "localize_naive_datetime", None)+ if callable(localize):+ return localize(dt)++ try:+ tzinfo = pytz.timezone(localization.get_timezone())+ except Exception:+ tzinfo = pytz.timezone("UTC")+ return tzinfo.localize(dt)+# ----------------------# Task Models# ----------------------@@ -77,29 +106,31 @@ class TaskPlan(BaseModel):done: list[datetime] = Field(default_factory=list)@classmethod- def create(cls, todo: list[datetime] = list(), in_progress: datetime | None = None, done: list[datetime] = list()):+ def create(+ cls,+ todo: list[datetime] | None = None,+ in_progress: datetime | None = None,+ done: list[datetime] | None = None,+ ):+ todo = list(todo or [])+ done = list(done or [])if todo:for idx, dt in enumerate(todo):- if dt.tzinfo is None:- todo[idx] = pytz.timezone("UTC").localize(dt)+ todo[idx] = _localize_task_datetime(dt)if in_progress:- if in_progress.tzinfo is None:- in_progress = pytz.timezone("UTC").localize(in_progress)+ in_progress = _localize_task_datetime(in_progress)if done:for idx, dt in enumerate(done):- if dt.tzinfo is None:- done[idx] = pytz.timezone("UTC").localize(dt)+ done[idx] = _localize_task_datetime(dt)return cls(todo=todo, in_progress=in_progress, done=done)def add_todo(self, launch_time: datetime):- if launch_time.tzinfo is None:- launch_time = pytz.timezone("UTC").localize(launch_time)+ launch_time = _localize_task_datetime(launch_time)self.todo.append(launch_time)self.todo = sorted(self.todo)def set_in_progress(self, launch_time: datetime):- if launch_time.tzinfo is None:- launch_time = pytz.timezone("UTC").localize(launch_time)+ launch_time = _localize_task_datetime(launch_time)if launch_time not in self.todo:raise ValueError(f"Launch time {launch_time} not in todo list")self.todo.remove(launch_time)@@ -107,8 +138,7 @@ class TaskPlan(BaseModel):self.in_progress = launch_timedef set_done(self, launch_time: datetime):- if launch_time.tzinfo is None:- launch_time = pytz.timezone("UTC").localize(launch_time)+ launch_time = _localize_task_datetime(launch_time)if launch_time != self.in_progress:raise ValueError(f"Launch time {launch_time} is not the same as in progress time {self.in_progress}")if launch_time in self.done:@@ -124,8 +154,7 @@ class TaskPlan(BaseModel):next_launch_time = self.get_next_launch_time()if next_launch_time is None:return None- # return next launch time if current datetime utc is later than next launch time- if datetime.now(timezone.utc) > next_launch_time:+ if _now() > next_launch_time:return next_launch_timereturn None@@ -140,8 +169,8 @@ class BaseTask(BaseModel):attachments: list[str] = Field(default_factory=list)project_name: str | None = Field(default=None)project_color: str | None = Field(default=None)- created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))- updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))+ created_at: datetime = Field(default_factory=_now)+ updated_at: datetime = Field(default_factory=_now)last_run: datetime | None = Nonelast_result: str | None = None@@ -164,32 +193,32 @@ class BaseTask(BaseModel):with self._lock:if name is not None:self.name = name- self.updated_at = datetime.now(timezone.utc)+ self.updated_at = _now()if state is not None:self.state = state- self.updated_at = datetime.now(timezone.utc)+ self.updated_at = _now()if system_prompt is not None:self.system_prompt = system_prompt- self.updated_at = datetime.now(timezone.utc)+ self.updated_at = _now()if prompt is not None:self.prompt = prompt- self.updated_at = datetime.now(timezone.utc)+ self.updated_at = _now()if attachments is not None:self.attachments = attachments- self.updated_at = datetime.now(timezone.utc)+ self.updated_at = _now()if last_run is not None:self.last_run = last_run- self.updated_at = datetime.now(timezone.utc)+ self.updated_at = _now()if last_result is not None:self.last_result = last_result- self.updated_at = datetime.now(timezone.utc)+ self.updated_at = _now()if context_id is not None:self.context_id = context_id- self.updated_at = datetime.now(timezone.utc)+ self.updated_at = _now()for key, value in kwargs.items():if value is not None:setattr(self, key, value)- self.updated_at = datetime.now(timezone.utc)+ self.updated_at = _now()def check_schedule(self, frequency_seconds: float = 60.0) -> bool:return False@@ -204,7 +233,7 @@ class BaseTask(BaseModel):next_run = self.get_next_run()if next_run is None:return None- return int((next_run - datetime.now(timezone.utc)).total_seconds() / 60)+ return int((next_run - _now()).total_seconds() / 60)async def on_run(self):pass@@ -214,7 +243,7 @@ class BaseTask(BaseModel):# This helps track when the task actually finished, regardless of success/errorawait TaskScheduler.get().update_task(self.uuid,- updated_at=datetime.now(timezone.utc)+ updated_at=_now())async def on_error(self, error: str):@@ -224,7 +253,7 @@ class BaseTask(BaseModel):updated_task = await scheduler.update_task(self.uuid,state=TaskState.ERROR,- last_run=datetime.now(timezone.utc),+ last_run=_now(),last_result=f"ERROR: {error}")if not updated_task:@@ -240,7 +269,7 @@ class BaseTask(BaseModel):updated_task = await scheduler.update_task(self.uuid,state=TaskState.IDLE,- last_run=datetime.now(timezone.utc),+ last_run=_now(),last_result=result)if not updated_task:@@ -261,7 +290,7 @@ class AdHocTask(BaseTask):system_prompt: str,prompt: str,token: str,- attachments: list[str] = list(),+ attachments: list[str] | None = None,context_id: str | None = None,project_name: str | None = None,project_color: str | None = None@@ -269,7 +298,7 @@ class AdHocTask(BaseTask):return cls(name=name,system_prompt=system_prompt,prompt=prompt,- attachments=attachments,+ attachments=list(attachments or []),token=token,context_id=context_id,project_name=project_name,@@ -309,7 +338,7 @@ class ScheduledTask(BaseTask):system_prompt: str,prompt: str,schedule: TaskSchedule,- attachments: list[str] = list(),+ attachments: list[str] | None = None,context_id: str | None = None,timezone: str | None = None,project_name: str | None = None,@@ -324,7 +353,7 @@ class ScheduledTask(BaseTask):return cls(name=name,system_prompt=system_prompt,prompt=prompt,- attachments=attachments,+ attachments=list(attachments or []),schedule=schedule,context_id=context_id,project_name=project_name,@@ -361,8 +390,7 @@ class ScheduledTask(BaseTask):task_timezone = pytz.timezone(self.schedule.timezone)# Get reference time in task's timezone (by default now - frequency_seconds)- reference_time = datetime.now(timezone.utc) - timedelta(seconds=frequency_seconds)- reference_time = reference_time.astimezone(task_timezone)+ reference_time = (_now() - timedelta(seconds=frequency_seconds)).astimezone(task_timezone)# Get next run time as seconds until next executionnext_run_seconds: Optional[float] = crontab.next( # type: ignore@@ -400,7 +428,7 @@ class PlannedTask(BaseTask):system_prompt: str,prompt: str,plan: TaskPlan,- attachments: list[str] = list(),+ attachments: list[str] | None = None,context_id: str | None = None,project_name: str | None = None,project_color: str | None = None@@ -409,7 +437,7 @@ class PlannedTask(BaseTask):system_prompt=system_prompt,prompt=prompt,plan=plan,- attachments=attachments,+ attachments=list(attachments or []),context_id=context_id,project_name=project_name,project_color=project_color)@@ -1095,9 +1123,9 @@ def parse_task_plan(plan_data: Dict[str, Any]) -> TaskPlan:if dt_str:parsed_dt = parse_datetime(dt_str)if parsed_dt:- # Ensure datetime is timezone-aware (use UTC if not specified)+ # Ensure datetime is timezone-aware (use the user's timezone if not specified)if parsed_dt.tzinfo is None:- parsed_dt = parsed_dt.replace(tzinfo=timezone.utc)+ parsed_dt = _localize_task_datetime(parsed_dt)todo_dates.append(parsed_dt)# Parse in_progress with validation@@ -1106,7 +1134,7 @@ def parse_task_plan(plan_data: Dict[str, Any]) -> TaskPlan:in_progress = parse_datetime(plan_data.get('in_progress'))# Ensure datetime is timezone-awareif in_progress and in_progress.tzinfo is None:- in_progress = in_progress.replace(tzinfo=timezone.utc)+ in_progress = _localize_task_datetime(in_progress)# Parse done items with validationdone_dates = []@@ -1116,7 +1144,7 @@ def parse_task_plan(plan_data: Dict[str, Any]) -> TaskPlan:if parsed_dt:# Ensure datetime is timezone-awareif parsed_dt.tzinfo is None:- parsed_dt = parsed_dt.replace(tzinfo=timezone.utc)+ parsed_dt = _localize_task_datetime(parsed_dt)done_dates.append(parsed_dt)# Sort dates for better usabilitydiff --git a/helpers/ui_server.py b/helpers/ui_server.pyindex 57519660d..0756c6e0d 100644--- a/helpers/ui_server.py+++ b/helpers/ui_server.py@@ -41,10 +41,10 @@ UPLOAD_LIMIT_BYTES = 5 * 1024 * 1024 * 1024def configure_process_environment() -> None:logging.getLogger().setLevel(logging.WARNING)- os.environ["TZ"] = "UTC"os.environ["TOKENIZERS_PARALLELISM"] = "false"- if hasattr(time, "tzset"):- time.tzset()+ from helpers.localization import Localization++ Localization.get().apply_process_timezone()@dataclass@@ -229,6 +229,14 @@ class UiRouteHandlers:"version": "unknown","commit_time": "unknown",}+ try:+ user_timezone_setting = str(settings_helper.get_settings().get("timezone", "auto"))+ except Exception:+ user_timezone_setting = "auto"+ try:+ user_time_format_setting = str(settings_helper.get_settings().get("time_format", "12h"))+ except Exception:+ user_time_format_setting = "12h"index = files.read_file("webui/index.html")return files.replace_placeholders_text(@@ -238,6 +246,8 @@ class UiRouteHandlers:runtime_id=runtime.get_runtime_id(),runtime_is_development=("true" if runtime.is_development() else "false"),logged_in=("true" if login.get_credentials_hash() else "false"),+ user_timezone_setting=user_timezone_setting,+ user_time_format_setting=user_time_format_setting,)@requires_authdiff --git a/helpers/virtual_desktop.py b/helpers/virtual_desktop.pyindex 7e42e8546..cd1020492 100644--- a/helpers/virtual_desktop.py+++ b/helpers/virtual_desktop.py@@ -13,6 +13,7 @@ from typing import Any, Callablefrom urllib.parse import quote, urlencodefrom helpers import files+from helpers.localization import LocalizationSTATE_DIR = Path(files.get_abs_path("usr", "plugins", "_desktop", "virtual_desktop"))@@ -563,6 +564,7 @@ def _display_env(display: int, *, xauthority: str = "", home: str = "") -> dict[**os.environ,"DISPLAY": f":{display}","XDG_RUNTIME_DIR": str(runtime_dir),+ "TZ": Localization.get().get_timezone(),}if home:env["HOME"] = homediff --git a/helpers/wait.py b/helpers/wait.pyindex 050b08638..17e297260 100644--- a/helpers/wait.py+++ b/helpers/wait.py@@ -1,6 +1,6 @@import asyncio-from datetime import datetime, timezone+from helpers.localization import Localizationfrom helpers.print_style import PrintStyle@@ -41,20 +41,20 @@ def format_remaining_time(total_seconds: float) -> str:async def managed_wait(agent, target_time, is_duration_wait, log, get_heading_callback):- while datetime.now(timezone.utc) < target_time:- before_intervention = datetime.now(timezone.utc)+ while Localization.get().now() < target_time:+ before_intervention = Localization.get().now()await agent.handle_intervention()- after_intervention = datetime.now(timezone.utc)+ after_intervention = Localization.get().now()if is_duration_wait:pause_duration = after_intervention - before_interventionif pause_duration.total_seconds() > 1.5: # Adjust for pauses longer than the sleep cycletarget_time += pause_durationPrintStyle.info(- f"Wait extended by {pause_duration.total_seconds():.1f}s to {target_time.isoformat()}...",+ f"Wait extended by {pause_duration.total_seconds():.1f}s to {Localization.get().serialize_datetime(target_time)}...",)- current_time = datetime.now(timezone.utc)+ current_time = Localization.get().now()if current_time >= target_time:breakdiff --git a/lib/browser/extract_dom.js b/lib/browser/extract_dom.jsindex 0d47506a7..b1b1a0576 100644--- a/lib/browser/extract_dom.js+++ b/lib/browser/extract_dom.js@@ -4,7 +4,13 @@ function extractDOM([guidName = "data-a0gu1d",]) {let elementCounter = 0;- const time = new Date().toISOString().slice(11, -1).replace(/[:.]/g, "");+ const now = new Date();+ const time = [+ String(now.getHours()).padStart(2, "0"),+ String(now.getMinutes()).padStart(2, "0"),+ String(now.getSeconds()).padStart(2, "0"),+ String(now.getMilliseconds()).padStart(3, "0"),+ ].join("");const ignoredTags = ["style","script",diff --git a/plugins/_chat_branching/api/branch_chat.py b/plugins/_chat_branching/api/branch_chat.pyindex bdc33edda..56e418f78 100644--- a/plugins/_chat_branching/api/branch_chat.py+++ b/plugins/_chat_branching/api/branch_chat.py@@ -1,7 +1,7 @@import json-from datetime import datetimefrom helpers.api import ApiHandler, Input, Output, Request, Response+from helpers.localization import Localizationfrom helpers.persist_chat import (_serialize_context,_deserialize_context,@@ -128,7 +128,7 @@ class BranchChat(ApiHandler):# Give the branch a distinguishable namesrc_name = data.get("name") or "Chat"data["name"] = f"{src_name} (branch)"- data["created_at"] = datetime.now().isoformat()+ data["created_at"] = Localization.get().now_iso()# Deserialize into a brand-new context (new id, fresh agent config)new_context = _deserialize_context(data)@@ -144,4 +144,4 @@ class BranchChat(ApiHandler):"ok": True,"ctxid": new_context.id,"message": "Chat branched successfully.",- }\ No newline at end of file+ }diff --git a/plugins/_chat_compaction/helpers/compactor.py b/plugins/_chat_compaction/helpers/compactor.pyindex 19b2105c7..8561dc620 100644--- a/plugins/_chat_compaction/helpers/compactor.py+++ b/plugins/_chat_compaction/helpers/compactor.py@@ -1,7 +1,6 @@"""Core compaction logic for the compaction plugin."""import osfrom collections import deque-from datetime import datetimeimport models as models_modulefrom agent import Agent@@ -14,6 +13,7 @@ from helpers.persist_chat import (remove_msg_files,)from helpers.state_monitor_integration import mark_dirty_all+from helpers.localization import LocalizationMIN_COMPACTION_TOKENS = 1000COMPACTION_CHUNK_TARGET_RATIO = 0.9@@ -34,7 +34,7 @@ def _save_pre_compaction_backup(context, full_text: str) -> dict[str, str]:Returns dict with 'json' and 'txt' absolute file paths."""- timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")+ timestamp = Localization.get().now().strftime("%Y%m%d-%H%M%S")backup_dir = os.path.join(get_chat_folder_path(context.id), "backups")os.makedirs(backup_dir, exist_ok=True)diff --git a/plugins/_desktop/helpers/desktop_session.py b/plugins/_desktop/helpers/desktop_session.pyindex 16fc39c68..0b8960916 100644--- a/plugins/_desktop/helpers/desktop_session.py+++ b/plugins/_desktop/helpers/desktop_session.py@@ -18,6 +18,7 @@ from pathlib import Pathfrom typing import Anyfrom helpers import files, virtual_desktop+from helpers.localization import Localizationfrom plugins._desktop.helpers import desktop_statefrom plugins._office.helpers import document_store, libreoffice@@ -103,6 +104,7 @@ class DesktopSession:process_ids: dict[str, int] = field(default_factory=dict)owns_processes: bool = Truestarted_at: float = field(default_factory=time.time)+ timezone: str = field(default_factory=lambda: Localization.get().get_timezone())def alive(self) -> bool:return _running(self.processes.get("xpra")) or _pid_is_running(self.process_ids.get("xpra", 0))@@ -456,6 +458,27 @@ class DesktopSessionManager:self._terminate_session(session)self._remove_manifest(session.session_id)+ def sync_timezone(self, timezone: str | None = None) -> dict[str, Any]:+ target_timezone = str(timezone or Localization.get().get_timezone()).strip()+ if not target_timezone:+ target_timezone = Localization.get().get_timezone()++ with self._lock:+ self._reap_dead_locked()+ session = self._sessions.get(SYSTEM_SESSION_ID)+ if not session or not session.alive():+ return {"ok": True, "restarted": False, "reason": "no_active_desktop"}+ if session.timezone == target_timezone:+ return {"ok": True, "restarted": False, "timezone": target_timezone}++ replacement = self._restart_system_desktop_for_timezone_locked(session)+ return {+ "ok": True,+ "restarted": True,+ "session_id": replacement.session_id,+ "timezone": replacement.timezone,+ }+def _document_for_save(self, session: DesktopSession, file_id: str = "") -> dict[str, Any] | None:normalized = str(file_id or "").strip()if normalized == SYSTEM_FILE_ID:@@ -471,6 +494,32 @@ class DesktopSessionManager:return document_store.register_document(path)return None+ def _restart_system_desktop_for_timezone_locked(self, session: DesktopSession) -> DesktopSession:+ try:+ doc = self._document_for_save(session, session.file_id)+ except Exception:+ doc = None+ if doc:+ try:+ self.save(session.session_id, str(doc.get("file_id") or ""))+ except Exception:+ pass++ virtual_desktop.unregister_session(session.token)+ self._sessions.pop(session.session_id, None)+ self._terminate_session(session, include_rehydrated=True)+ self._remove_manifest(session.session_id)++ replacement = self._ensure_system_desktop_locked()+ if doc:+ self._open_document_locked(replacement, doc)+ replacement.file_id = str(doc["file_id"])+ replacement.extension = str(doc["extension"])+ replacement.path = str(doc["path"])+ replacement.title = str(doc["basename"])+ self._write_manifest(replacement)+ return replacement+def _register_virtual_desktop(self, session: DesktopSession) -> None:virtual_desktop.register_session(token=session.token,@@ -482,8 +531,11 @@ class DesktopSessionManager:)def _ensure_system_desktop_locked(self) -> DesktopSession:+ target_timezone = Localization.get().get_timezone()existing = self._sessions.get(SYSTEM_SESSION_ID)if existing and existing.alive():+ if existing.timezone != target_timezone:+ return self._restart_system_desktop_for_timezone_locked(existing)self._prepare_desktop_url_bridge(existing)self._refresh_xfce_desktop(existing)return existing@@ -492,6 +544,8 @@ class DesktopSessionManager:if existing:self._sessions[existing.session_id] = existingself._register_virtual_desktop(existing)+ if existing.timezone != target_timezone:+ return self._restart_system_desktop_for_timezone_locked(existing)self._prepare_desktop_url_bridge(existing)self._refresh_xfce_desktop(existing)return existing@@ -513,6 +567,7 @@ class DesktopSessionManager:token=SYSTEM_SESSION_ID,url=_xpra_url(SYSTEM_SESSION_ID),profile_dir=profile_dir,+ timezone=target_timezone,)try:self._prepare_profile(session)@@ -572,6 +627,7 @@ class DesktopSessionManager:process_ids=process_ids,owns_processes=False,started_at=float(payload.get("started_at") or time.time()),+ timezone=str(payload.get("timezone") or Localization.get().get_timezone()),)except Exception:return None@@ -1431,6 +1487,7 @@ fi**os.environ,"HOME": str(session.profile_dir),"LANG": os.environ.get("LANG") or "C.UTF-8",+ "TZ": session.timezone or Localization.get().get_timezone(),}browser_bridge = _url_bridge_script_path(session)if browser_bridge.exists():@@ -1532,6 +1589,7 @@ fi"width": session.width,"height": session.height,"started_at": session.started_at,+ "timezone": session.timezone,"owner_pid": os.getpid(),"pids": pids,}diff --git a/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py b/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.pyindex 2b24d8cd9..c1b2a0c4f 100644--- a/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py+++ b/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py@@ -1,12 +1,12 @@"""Per-handler email poll loop with configurable seconds/cron intervals."""import asyncio-from datetime import datetime, timezonefrom typing import Anyfrom crontab import CronTabfrom helpers.extension import Extension+from helpers.localization import Localizationfrom helpers.errors import format_errorfrom helpers.print_style import PrintStylefrom helpers import plugins@@ -96,7 +96,7 @@ def _get_sleep_seconds(handler_cfg: dict) -> float:expr = handler_cfg.get("poll_interval_cron", "*/2 * * * *")try:cron = CronTab(expr)- next_sec = cron.next(now=datetime.now(timezone.utc)) # type: ignore[union-attr]+ next_sec = cron.next(now=Localization.get().now()) # type: ignore[union-attr]return max(next_sec, MIN_INTERVAL)except Exception:return DEFAULT_INTERVALdiff --git a/plugins/_memory/api/memory_dashboard.py b/plugins/_memory/api/memory_dashboard.pyindex 8db2f70bf..f6d2c35b7 100644--- a/plugins/_memory/api/memory_dashboard.py+++ b/plugins/_memory/api/memory_dashboard.py@@ -1,5 +1,6 @@from helpers.api import ApiHandler, Request, Responsefrom helpers import files+from helpers.localization import Localizationfrom models import ModelConfig, ModelTypefrom langchain_core.documents import Documentfrom agent import AgentContext@@ -174,8 +175,10 @@ class MemoryDashboard(ApiHandler):# sort by timestampdef get_sort_key(m):- timestamp = m.metadata.get("timestamp", "0000-00-00 00:00:00")- return timestamp+ timestamp = self._serialize_memory_timestamp(+ m.metadata.get("timestamp", "0000-00-00 00:00:00")+ )+ return timestamp or "0000-00-00T00:00:00"memories.sort(key=get_sort_key, reverse=True)@@ -214,10 +217,11 @@ class MemoryDashboard(ApiHandler):def _format_memory_for_dashboard(self, m: Document) -> dict:"""Format a memory document for the dashboard."""metadata = m.metadata+ timestamp = self._serialize_memory_timestamp(metadata.get("timestamp", "unknown"))return {"id": metadata.get("id", "unknown"),"area": metadata.get("area", "unknown"),- "timestamp": metadata.get("timestamp", "unknown"),+ "timestamp": timestamp,# "content_preview": m.page_content[:200]# + ("..." if len(m.page_content) > 200 else ""),"content_full": m.page_content,@@ -229,6 +233,24 @@ class MemoryDashboard(ApiHandler):"metadata": metadata, # Include full metadata for advanced users}+ def _serialize_memory_timestamp(self, value) -> str:+ if not value or value == "unknown":+ return "unknown"++ if isinstance(value, str):+ value = value.strip()+ if not value or value == "unknown":+ return "unknown"++ localization = Localization.get()+ if isinstance(value, str):+ parsed = localization.localtime_str_to_utc_dt(value)+ if parsed is None:+ return value+ return localization.utc_dt_to_localtime_str(parsed, timespec="seconds") or value++ return localization.serialize_datetime(value) or str(value)+async def _update_memory(self, input: dict) -> dict:try:memory_subdir = input.get("memory_subdir")diff --git a/plugins/_memory/helpers/memory.py b/plugins/_memory/helpers/memory.pyindex 21e830c40..364bfe76c 100644--- a/plugins/_memory/helpers/memory.py+++ b/plugins/_memory/helpers/memory.py@@ -1,4 +1,3 @@-from datetime import datetimefrom typing import Any, List, Sequencefrom langchain.storage import InMemoryByteStore, LocalFileStorefrom langchain.embeddings import CacheBackedEmbeddings@@ -24,6 +23,7 @@ import numpy as npfrom helpers.print_style import PrintStylefrom helpers import files, plugins, projects+from helpers.localization import Localizationfrom langchain_core.documents import Documentfrom . import knowledge_importfrom helpers.log import Log, LogItem@@ -609,7 +609,7 @@ class Memory:@staticmethoddef get_timestamp():- return datetime.now().strftime("%Y-%m-%d %H:%M:%S")+ return Localization.get().now_iso(timespec="seconds")def get_custom_knowledge_subdir_abs(agent: Agent) -> str:diff --git a/plugins/_memory/helpers/memory_consolidation.py b/plugins/_memory/helpers/memory_consolidation.pyindex 817ff9427..227fb11e8 100644--- a/plugins/_memory/helpers/memory_consolidation.py+++ b/plugins/_memory/helpers/memory_consolidation.py@@ -1,7 +1,6 @@import asyncioimport jsonfrom dataclasses import dataclass, field-from datetime import datetime, timezonefrom typing import Any, Dict, List, Optionalfrom enum import Enum@@ -9,6 +8,7 @@ from langchain_core.documents import Documentfrom plugins._memory.helpers.memory import Memoryfrom helpers.dirty_json import DirtyJson+from helpers.localization import Localizationfrom helpers.log import LogItemfrom helpers.print_style import PrintStylefrom agent import Agent@@ -753,7 +753,7 @@ class MemoryConsolidator:def _get_timestamp(self) -> str:"""Get current timestamp in standard format."""- return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")+ return Localization.get().now_iso(timespec="seconds")# Factory function for easy instantiationdiff --git a/plugins/_memory/webui/memory-dashboard-store.js b/plugins/_memory/webui/memory-dashboard-store.jsindex 6cd2d271c..5de28fbc6 100644--- a/plugins/_memory/webui/memory-dashboard-store.js+++ b/plugins/_memory/webui/memory-dashboard-store.js@@ -3,6 +3,12 @@ import { getContext } from "/index.js";import * as API from "/js/api.js";import { openModal, closeModal } from "/js/modals.js";import { store as notificationStore } from "/components/notifications/notification-store.js";+import {+ getCurrentUserDateString,+ getCurrentUserISOString,+ getUserHour12,+ getUserTimezone,+} from "/js/time-utils.js";const MEMORY_DASHBOARD_API = "/plugins/_memory/memory_dashboard";// Helper function for toasts@@ -407,7 +413,7 @@ ${memory.content_full}if (selectedMemories.length === 0) return;const exportData = {- export_timestamp: new Date().toISOString(),+ export_timestamp: getCurrentUserISOString(),memory_subdir: this.selectedMemorySubdir,total_memories: selectedMemories.length,memories: selectedMemories.map((memory) => ({@@ -426,7 +432,7 @@ ${memory.content_full}const blob = new Blob([jsonString], { type: "application/json" });const url = URL.createObjectURL(blob);- const timestamp = new Date().toISOString().split("T")[0];+ const timestamp = getCurrentUserDateString();const filename = `memories_${this.selectedMemorySubdir}_selected_${selectedMemories.length}_${timestamp}.json`;const a = document.createElement("a");@@ -468,34 +474,28 @@ ${memory.content_full}}if (compact) {+ const hour12 = getUserHour12();// For table display: MM/DD HH:mm- return (- date.toLocaleDateString("en-US", {- month: "2-digit",- day: "2-digit",- }) +- " " +- date.toLocaleTimeString("en-US", {- hour12: false,- hour: "2-digit",- minute: "2-digit",- })- );+ return new Intl.DateTimeFormat("en-US", {+ month: "2-digit",+ day: "2-digit",+ hour12,+ hour: hour12 ? "numeric" : "2-digit",+ minute: "2-digit",+ timeZone: getUserTimezone(),+ }).format(date);} else {+ const hour12 = getUserHour12();// For details: Full format- return (- date.toLocaleDateString("en-US", {- year: "numeric",- month: "long",- day: "numeric",- }) +- " at " +- date.toLocaleTimeString("en-US", {- hour12: true,- hour: "numeric",- minute: "2-digit",- })- );+ return new Intl.DateTimeFormat("en-US", {+ year: "numeric",+ month: "long",+ day: "numeric",+ hour12,+ hour: hour12 ? "numeric" : "2-digit",+ minute: "2-digit",+ timeZone: getUserTimezone(),+ }).format(date);}},@@ -593,7 +593,7 @@ ${memory.content_full}try {const exportData = {memory_subdir: this.selectedMemorySubdir,- export_timestamp: new Date().toISOString(),+ export_timestamp: getCurrentUserISOString(),total_memories: this.memories.length,search_query: this.searchQuery,area_filter: this.areaFilter,@@ -613,7 +613,7 @@ ${memory.content_full}const a = document.createElement("a");a.href = url;a.download = `memory-export-${this.selectedMemorySubdir}-${- new Date().toISOString().split("T")[0]+ getCurrentUserDateString()}.json`;document.body.appendChild(a);a.click();diff --git a/plugins/_office/helpers/document_store.py b/plugins/_office/helpers/document_store.pyindex 485194e8e..1d6c472d0 100644--- a/plugins/_office/helpers/document_store.py+++ b/plugins/_office/helpers/document_store.py@@ -16,6 +16,7 @@ from typing import Anyfrom xml.sax.saxutils import escapefrom helpers import files+from helpers.localization import Localizationfrom plugins._office.helpers import pptx_writer@@ -52,7 +53,7 @@ def now() -> float:def now_iso() -> str:- return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+ return Localization.get().now_iso(timespec="seconds")def ensure_dirs() -> None:diff --git a/plugins/_office/helpers/libreoffice_desktop.py b/plugins/_office/helpers/libreoffice_desktop.pyindex 6e09385ed..0537ebabc 100644--- a/plugins/_office/helpers/libreoffice_desktop.py+++ b/plugins/_office/helpers/libreoffice_desktop.py@@ -3,3 +3,4 @@ from __future__ import annotations# Compatibility facade for pre-split callers. New Desktop runtime ownership# lives in plugins._desktop.helpers.desktop_session.from plugins._desktop.helpers.desktop_session import * # noqa: F401,F403+from plugins._desktop.helpers.desktop_session import DesktopSessionManager as LibreOfficeDesktopManagerdiff --git a/plugins/_office/hooks.py b/plugins/_office/hooks.pyindex 9a81b4c0c..0d094767d 100644--- a/plugins/_office/hooks.py+++ b/plugins/_office/hooks.py@@ -138,6 +138,20 @@ def cleanup_stale_runtime_state(force: bool = False) -> dict[str, Any]:}+def timezone_changed(timezone: str, previous_timezone: str | None = None) -> dict[str, Any]:+ try:+ from plugins._office.helpers import libreoffice_desktop++ return libreoffice_desktop.get_manager().sync_timezone(timezone)+ except Exception as exc:+ return {+ "ok": False,+ "error": str(exc),+ "timezone": timezone,+ "previous_timezone": previous_timezone,+ }++def retire_collabora_web_runtime(force: bool = False) -> dict[str, Any]:"""Retire the legacy Collabora web runtime without preparing LibreOffice.diff --git a/plugins/_office/webui/office-store.js b/plugins/_office/webui/office-store.jsindex 9eeae3bcf..34083179a 100644--- a/plugins/_office/webui/office-store.js+++ b/plugins/_office/webui/office-store.js@@ -2,6 +2,7 @@ import { createStore } from "/js/AlpineStore.js";import { callJsonApi } from "/js/api.js";import { store as fileBrowserStore } from "/components/modals/file-browser/file-browser-store.js";import { open as openSurface } from "/js/surfaces.js";+import { getCurrentUserDateString } from "/js/time-utils.js";const SAVE_MESSAGE_MS = 1800;const DESKTOP_DOCUMENT_EXTENSIONS = new Set(["odt", "ods", "odp", "docx", "xlsx", "pptx"]);@@ -185,7 +186,7 @@ const model = {},defaultTitle(kind, fmt) {- const date = new Date().toISOString().slice(0, 10);+ const date = getCurrentUserDateString();if (fmt === "md") return `Document ${date}`;if (fmt === "odt") return `Writer ${date}`;if (fmt === "docx") return `DOCX ${date}`;diff --git a/plugins/_plugin_installer/helpers/install.py b/plugins/_plugin_installer/helpers/install.pyindex 3722cba61..d5ac1cc1f 100644--- a/plugins/_plugin_installer/helpers/install.py+++ b/plugins/_plugin_installer/helpers/install.py@@ -1,10 +1,9 @@from __future__ import annotations-from datetime import datetime, timezone+from datetime import datetimeimport jsonimport osimport time-from turtle import stampimport urllib.requestimport uuidimport zipfile@@ -12,6 +11,7 @@ from pathlib import Pathfrom typing import Anyfrom helpers import files, print_style, plugins, git+from helpers.localization import Localizationfrom helpers import yaml as yaml_helperfrom helpers.plugins import (META_FILE_NAME,@@ -272,7 +272,10 @@ def update_from_git(plugin_name: str) -> dict:"title": meta.title if meta else plugin_name,"path": files.deabsolute_path(plugin_dir),"current_commit": head.hexsha,- "current_commit_timestamp": datetime.fromtimestamp(head.committed_date, timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),+ "current_commit_timestamp": datetime.fromtimestamp(+ head.committed_date,+ tz=Localization.get().get_tzinfo(),+ ).strftime("%Y-%m-%d %H:%M:%S %Z"),"version": getattr(meta, "version", "") or "","branch": repo.active_branch.name if not repo.head.is_detached else "","remote_url": git.strip_auth_from_url(repo.remotes.origin.url) if repo.remotes else "",diff --git a/plugins/_plugin_installer/webui/pluginInstallStore.js b/plugins/_plugin_installer/webui/pluginInstallStore.jsindex d49843193..7be752bde 100644--- a/plugins/_plugin_installer/webui/pluginInstallStore.js+++ b/plugins/_plugin_installer/webui/pluginInstallStore.js@@ -4,6 +4,7 @@ import { openModal } from "/js/modals.js";import { renderSafeMarkdown } from "/js/safe-markdown.js";import { toastFrontendSuccess, toastFrontendError } from "/components/notifications/notification-store.js";import { showConfirmDialog } from "/js/confirmDialog.js";+import { formatDateTime } from "/js/time-utils.js";import { store as imageViewerStore } from "/components/modals/image-viewer/image-viewer-store.js";import { store as pluginListStore } from "/components/plugins/list/pluginListStore.js";import { store as pluginExecuteStore } from "/components/plugins/list/plugin-execute-store.js";@@ -776,14 +777,7 @@ const model = {const date = new Date(normalizedValue);if (Number.isNaN(date.getTime())) return value;- return new Intl.DateTimeFormat(undefined, {- year: "numeric",- month: "2-digit",- day: "2-digit",- hour: "2-digit",- minute: "2-digit",- second: "2-digit",- }).format(date);+ return formatDateTime(normalizedValue, "full");},getRepoCommitUrl(plugin, commitHash) {diff --git a/plugins/_plugin_scan/webui/plugin-scan-store.js b/plugins/_plugin_scan/webui/plugin-scan-store.jsindex f5fc6c1e7..a16fbeefa 100644--- a/plugins/_plugin_scan/webui/plugin-scan-store.js+++ b/plugins/_plugin_scan/webui/plugin-scan-store.js@@ -2,6 +2,7 @@ import { marked } from "/vendor/marked/marked.esm.js";import { createStore } from "/js/AlpineStore.js";import * as api from "/js/api.js";import { openModal } from "/js/modals.js";+import { getUserTimezone } from "/js/time-utils.js";import { toastFrontendError } from "/components/notifications/notification-store.js";const BASE = "/plugins/_plugin_scan/webui";@@ -225,7 +226,7 @@ export const store = createStore("pluginScan", {try {const snap = await api.callJsonApi("/poll", {context: ctxId, log_from: 0, notifications_from: 0,- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ timezone: getUserTimezone(),});if (gen === _pollGen && snap.logs?.length) {diff --git a/plugins/_plugin_validator/webui/plugin-validator-store.js b/plugins/_plugin_validator/webui/plugin-validator-store.jsindex a8fd0c191..bdd0b8dc8 100644--- a/plugins/_plugin_validator/webui/plugin-validator-store.js+++ b/plugins/_plugin_validator/webui/plugin-validator-store.js@@ -2,6 +2,7 @@ import { marked } from "/vendor/marked/marked.esm.js";import { createStore } from "/js/AlpineStore.js";import * as api from "/js/api.js";import { openModal as openAppModal } from "/js/modals.js";+import { getUserTimezone } from "/js/time-utils.js";import { toastFrontendError } from "/components/notifications/notification-store.js";const BASE = "/plugins/_plugin_validator/webui";@@ -440,7 +441,7 @@ export const store = createStore("pluginValidator", {context: ctxId,log_from: 0,notifications_from: 0,- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ timezone: getUserTimezone(),});if (gen === _pollGen && snapshot.logs?.length) {diff --git a/plugins/_time_travel/helpers/time_travel.py b/plugins/_time_travel/helpers/time_travel.pyindex 3942f8317..e75c15f92 100644--- a/plugins/_time_travel/helpers/time_travel.py+++ b/plugins/_time_travel/helpers/time_travel.py@@ -11,11 +11,11 @@ import subprocessimport threadingimport timefrom dataclasses import dataclass-from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Iterablefrom helpers import files+from helpers.localization import Localizationfrom helpers.print_style import PrintStyle@@ -166,7 +166,7 @@ class SnapshotResult:def now_iso() -> str:- return datetime.now(timezone.utc).isoformat()+ return Localization.get().now_iso()def normalize_display_path(path: str) -> str:@@ -1026,7 +1026,7 @@ class TimeTravelService:return self._git("show", "-s", "--format=%T", commit_hash).stdout.strip()def _preserve_ref(self, commit_hash: str, *, reason: str) -> str:- stamp = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")+ stamp = Localization.get().now().strftime("%Y%m%d%H%M%S")base_ref = f"{PRESERVED_REF_PREFIX}/{stamp}-{reason}-{commit_hash[:12]}"ref = base_refcounter = 2@@ -1174,7 +1174,7 @@ class TimeTravelService:return "refs/heads/" + refs[0].relative_to(heads_dir).as_posix()def _next_invalid_repo_backup_path(self) -> Path:- stamp = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")+ stamp = Localization.get().now().strftime("%Y%m%d%H%M%S")base_path = self.workspace.shadow_path / f"{SHADOW_REPO_BACKUP_PREFIX}-{stamp}"backup_path = base_pathcounter = 2diff --git a/plugins/_time_travel/webui/time-travel-store.js b/plugins/_time_travel/webui/time-travel-store.jsindex 664ba463f..9e159fbc0 100644--- a/plugins/_time_travel/webui/time-travel-store.js+++ b/plugins/_time_travel/webui/time-travel-store.js@@ -2,6 +2,7 @@ import { createStore } from "/js/AlpineStore.js";import { callJsonApi } from "/js/api.js";import { getContext } from "/index.js";import { store as fileBrowserStore } from "/components/modals/file-browser/file-browser-store.js";+import { formatDateTime } from "/js/time-utils.js";const REFRESH_DEBOUNCE_MS = 180;@@ -392,12 +393,7 @@ const model = {if (!value) return "";const date = new Date(value);if (Number.isNaN(date.getTime())) return String(value);- return date.toLocaleString(undefined, {- month: "short",- day: "numeric",- hour: "2-digit",- minute: "2-digit",- });+ return formatDateTime(value, "short");},formatSigned(value, sign) {diff --git a/run_ui.py b/run_ui.pyindex a90e7a183..4edf94b8b 100644--- a/run_ui.py+++ b/run_ui.py@@ -5,10 +5,8 @@ from helpers.server_startup import run_uvicorn_with_retriesfrom helpers.ui_server import UiServerRuntime, configure_process_environment-configure_process_environment()--def run():+ configure_process_environment()PrintStyle().print("Initializing Python framework...")PrintStyle().print("Checking for data migration...")run_migration_checks()diff --git a/tests/test_settings_developer_sections.py b/tests/test_settings_developer_sections.pyindex ced73c8aa..05d8e726a 100644--- a/tests/test_settings_developer_sections.py+++ b/tests/test_settings_developer_sections.py@@ -28,3 +28,26 @@ def test_websocket_harness_template_is_gated_by_runtime():content = template_path.read_text(encoding="utf-8")assert "window.runtimeInfo?.isDevelopment" in contentassert "$store.root?.isDevelopment" not in content+++def test_timezone_settings_section_is_present():+ store_path = PROJECT_ROOT / "webui" / "components" / "settings" / "settings-store.js"+ agent_settings_path = PROJECT_ROOT / "webui" / "components" / "settings" / "agent" / "agent-settings.html"+ locale_path = PROJECT_ROOT / "webui" / "components" / "settings" / "agent" / "locale.html"++ store = store_path.read_text(encoding="utf-8")+ agent_settings = agent_settings_path.read_text(encoding="utf-8")+ assert "section-locale" in store+ assert "section-voice" in store+ assert "settings/agent/locale.html" in agent_settings+ assert store.index("section-models-summary") < store.index("section-locale")+ assert store.index("section-locale") < store.index("section-agent-plugins")+ assert agent_settings.index("section-models-summary") < agent_settings.index("section-locale")+ assert agent_settings.index("section-locale") < agent_settings.index("section-agent-plugins")+ assert agent_settings.rindex("section-locale") < agent_settings.rindex("section-agent-plugins")+ locale = locale_path.read_text(encoding="utf-8")+ assert "Automatic (browser)" in locale+ assert "$store.settings.settings.timezone" in locale+ assert "12-hour (AM/PM)" in locale+ assert "24-hour" in locale+ assert "$store.settings.settings.time_format" in localediff --git a/tests/test_timezone_regressions.py b/tests/test_timezone_regressions.pynew file mode 100644index 000000000..e47d2f500--- /dev/null+++ b/tests/test_timezone_regressions.py@@ -0,0 +1,348 @@+import os+import sys+import threading+from datetime import datetime+from pathlib import Path++import pytest+import pytz+from langchain_core.documents import Document++PROJECT_ROOT = Path(__file__).resolve().parents[1]+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))++import helpers.localization as localization_module+import helpers.plugins as plugins_module+import helpers.settings as settings_module+from helpers.localization import Localization+from helpers.task_scheduler import (+ TaskPlan,+ parse_task_plan,+ serialize_task_plan,+)+from plugins._memory.api.memory_dashboard import MemoryDashboard+from plugins._office.helpers import libreoffice_desktop+++def isolated_localization(monkeypatch):+ saved: list[tuple[str, str]] = []++ def fake_get_dotenv_value(key, default=None):+ if key == "DEFAULT_USER_TIMEZONE":+ return default or "UTC"+ if key == "DEFAULT_USER_UTC_OFFSET_MINUTES":+ return None+ return default++ monkeypatch.setattr(localization_module, "get_dotenv_value", fake_get_dotenv_value)+ monkeypatch.setattr(+ localization_module,+ "save_dotenv_value",+ lambda key, value: saved.append((key, str(value))),+ )+ monkeypatch.setattr(+ localization_module.PrintStyle,+ "error",+ staticmethod(lambda *args, **kwargs: None),+ )+ Localization._instance = None+ original_tz = os.environ.get("TZ")++ yield saved++ Localization._instance = None+ if original_tz is None:+ monkeypatch.delenv("TZ", raising=False)+ else:+ monkeypatch.setenv("TZ", original_tz)+++def set_test_timezone(timezone: str) -> Localization:+ Localization._instance = Localization(timezone)+ return Localization.get()+++def test_invalid_timezone_preserves_current_user_timezone(isolated_localization):+ saved = isolated_localization+ localization = set_test_timezone("Europe/Rome")+ saved.clear()++ localization.set_timezone("Mars/Olympus")++ assert localization.get_timezone() == "Europe/Rome"+ assert os.environ["TZ"] == "Europe/Rome"+ assert not any(item == ("DEFAULT_USER_TIMEZONE", "UTC") for item in saved)+ assert not any(item == ("DEFAULT_USER_TIMEZONE", "Mars/Olympus") for item in saved)+++def test_startup_refreshes_stale_persisted_offset(monkeypatch):+ saved: list[tuple[str, str]] = []++ def fake_get_dotenv_value(key, default=None):+ if key == "DEFAULT_USER_TIMEZONE":+ return "Europe/Rome"+ if key == "DEFAULT_USER_UTC_OFFSET_MINUTES":+ return "0"+ return default++ monkeypatch.setattr(localization_module, "get_dotenv_value", fake_get_dotenv_value)+ monkeypatch.setattr(+ localization_module,+ "save_dotenv_value",+ lambda key, value: saved.append((key, str(value))),+ )+ Localization._instance = None++ localization = Localization.get()+ expected_offset = int(+ datetime.now(pytz.timezone("Europe/Rome")).utcoffset().total_seconds() // 60+ )++ assert localization.get_timezone() == "Europe/Rome"+ assert localization.get_offset_minutes() == expected_offset+ assert ("DEFAULT_USER_UTC_OFFSET_MINUTES", str(expected_offset)) in saved+++def test_scheduler_naive_plan_times_round_trip_as_user_local(isolated_localization):+ set_test_timezone("Europe/Rome")++ plan = parse_task_plan({"todo": ["2026-05-03T09:30:00"], "in_progress": None, "done": []})+ serialized = serialize_task_plan(plan)++ assert serialized["todo"] == ["2026-05-03T09:30:00+02:00"]+++def test_settings_auto_timezone_resolves_to_browser_timezone(isolated_localization, monkeypatch):+ set_test_timezone("UTC")+ hooks: list[dict] = []+ base_settings = settings_module.get_default_settings()+ monkeypatch.setattr(+ settings_module,+ "_settings",+ {**base_settings, "timezone": settings_module.TIMEZONE_AUTO},+ )+ monkeypatch.setattr(+ plugins_module,+ "call_plugin_hook",+ lambda plugin_name, hook_name, *args, **kwargs: hooks.append(+ {+ "plugin_name": plugin_name,+ "hook_name": hook_name,+ "kwargs": kwargs,+ }+ ),+ )++ settings_module._apply_timezone_setting(+ {**base_settings, "timezone": settings_module.TIMEZONE_AUTO},+ browser_timezone="Europe/Rome",+ )++ assert Localization.get().get_timezone() == "Europe/Rome"+ assert hooks[0]["plugin_name"] == "_office"+ assert hooks[0]["hook_name"] == "timezone_changed"+ assert hooks[0]["kwargs"]["previous_timezone"] == "UTC"+ assert hooks[0]["kwargs"]["timezone"] == "Europe/Rome"+++def test_settings_fixed_timezone_ignores_browser_timezone(isolated_localization, monkeypatch):+ set_test_timezone("Europe/Rome")+ base_settings = settings_module.get_default_settings()+ monkeypatch.setattr(+ settings_module,+ "_settings",+ {**base_settings, "timezone": "America/New_York"},+ )+ monkeypatch.setattr(plugins_module, "call_plugin_hook", lambda *args, **kwargs: None)++ settings_module._apply_timezone_setting(+ {**base_settings, "timezone": settings_module.TIMEZONE_AUTO},+ browser_timezone="Europe/Rome",+ )++ assert Localization.get().get_timezone() == "America/New_York"+++def test_settings_fixed_timezone_reapplies_when_runtime_drifted(isolated_localization, monkeypatch):+ set_test_timezone("Europe/Rome")+ base_settings = settings_module.get_default_settings()+ fixed_settings = {**base_settings, "timezone": "America/New_York"}+ hooks: list[dict] = []+ monkeypatch.setattr(settings_module, "_settings", fixed_settings)+ monkeypatch.setattr(+ plugins_module,+ "call_plugin_hook",+ lambda plugin_name, hook_name, *args, **kwargs: hooks.append(+ {+ "plugin_name": plugin_name,+ "hook_name": hook_name,+ "kwargs": kwargs,+ }+ ),+ )++ settings_module._apply_timezone_setting(+ {**base_settings, "timezone": "America/New_York"},+ browser_timezone="Europe/Rome",+ )++ assert Localization.get().get_timezone() == "America/New_York"+ assert hooks[0]["plugin_name"] == "_office"+ assert hooks[0]["hook_name"] == "timezone_changed"+ assert hooks[0]["kwargs"]["previous_timezone"] == "Europe/Rome"+ assert hooks[0]["kwargs"]["timezone"] == "America/New_York"+++def test_settings_rejects_invalid_timezone_value():+ settings_data = settings_module.get_default_settings()+ normalized = settings_module.normalize_settings(+ {**settings_data, "timezone": "Mars/Olympus"}+ )++ assert normalized["timezone"] == settings_module.TIMEZONE_AUTO+++def test_settings_rejects_invalid_time_format_value():+ settings_data = settings_module.get_default_settings()++ invalid = settings_module.normalize_settings(+ {**settings_data, "time_format": "bananas"}+ )+ twenty_four = settings_module.normalize_settings(+ {**settings_data, "time_format": settings_module.TIME_FORMAT_24H}+ )++ assert invalid["time_format"] == settings_module.TIME_FORMAT_12H+ assert twenty_four["time_format"] == settings_module.TIME_FORMAT_24H+++def test_scheduler_naive_plan_times_follow_changed_user_timezone(isolated_localization):+ set_test_timezone("America/New_York")++ plan = parse_task_plan({"todo": ["2026-05-03T09:30:00"], "in_progress": None, "done": []})+ serialized = serialize_task_plan(plan)++ assert serialized["todo"] == ["2026-05-03T09:30:00-04:00"]+++def test_task_plan_create_localizes_naive_datetimes(isolated_localization):+ set_test_timezone("Europe/Rome")++ plan = TaskPlan.create(todo=[datetime(2026, 5, 3, 9, 30)])++ assert plan.todo[0].isoformat() == "2026-05-03T09:30:00+02:00"+++def test_memory_dashboard_normalizes_legacy_naive_timestamps(isolated_localization):+ set_test_timezone("Europe/Rome")+ dashboard = MemoryDashboard(app=None, thread_lock=threading.RLock())++ formatted = dashboard._format_memory_for_dashboard(+ Document(+ page_content="legacy memory",+ metadata={+ "id": "memory-1",+ "area": "main",+ "timestamp": "2026-05-02 18:27:51",+ },+ )+ )++ assert formatted["timestamp"] == "2026-05-02T18:27:51+02:00"+ assert formatted["metadata"]["timestamp"] == "2026-05-02 18:27:51"+++def test_memory_dashboard_converts_aware_timestamps_to_user_timezone(isolated_localization):+ set_test_timezone("Europe/Rome")+ dashboard = MemoryDashboard(app=None, thread_lock=threading.RLock())++ assert (+ dashboard._serialize_memory_timestamp("2026-05-02T16:27:51+00:00")+ == "2026-05-02T18:27:51+02:00"+ )+++class FakeProcess:+ pid = 4242++ def poll(self):+ return None+++def test_desktop_session_env_uses_session_timezone(isolated_localization, tmp_path):+ set_test_timezone("Europe/Rome")+ session = libreoffice_desktop.DesktopSession(+ session_id=libreoffice_desktop.SYSTEM_SESSION_ID,+ file_id=libreoffice_desktop.SYSTEM_FILE_ID,+ extension="desktop",+ path=str(tmp_path),+ title="Desktop",+ display=120,+ xpra_port=14500,+ token=libreoffice_desktop.SYSTEM_SESSION_ID,+ url="/desktop/session/agent-zero-desktop/index.html",+ profile_dir=tmp_path / "profile",+ timezone="America/New_York",+ )++ env = libreoffice_desktop.LibreOfficeDesktopManager()._session_env(session)++ assert env["TZ"] == "America/New_York"+++def test_desktop_timezone_sync_restarts_active_system_desktop(+ isolated_localization,+ monkeypatch,+ tmp_path,+):+ set_test_timezone("America/New_York")+ manager = libreoffice_desktop.LibreOfficeDesktopManager()+ old_session = libreoffice_desktop.DesktopSession(+ session_id=libreoffice_desktop.SYSTEM_SESSION_ID,+ file_id=libreoffice_desktop.SYSTEM_FILE_ID,+ extension="desktop",+ path=str(tmp_path),+ title="Desktop",+ display=120,+ xpra_port=14500,+ token=libreoffice_desktop.SYSTEM_SESSION_ID,+ url="/desktop/session/agent-zero-desktop/index.html",+ profile_dir=tmp_path / "profile-old",+ timezone="Europe/Rome",+ processes={"xpra": FakeProcess()},+ )+ replacement = libreoffice_desktop.DesktopSession(+ session_id=libreoffice_desktop.SYSTEM_SESSION_ID,+ file_id=libreoffice_desktop.SYSTEM_FILE_ID,+ extension="desktop",+ path=str(tmp_path),+ title="Desktop",+ display=120,+ xpra_port=14500,+ token=libreoffice_desktop.SYSTEM_SESSION_ID,+ url="/desktop/session/agent-zero-desktop/index.html",+ profile_dir=tmp_path / "profile-new",+ timezone="America/New_York",+ processes={"xpra": FakeProcess()},+ )+ manager._sessions[libreoffice_desktop.SYSTEM_SESSION_ID] = old_session+ restarted: list[libreoffice_desktop.DesktopSession] = []++ def fake_restart(session):+ restarted.append(session)+ manager._sessions[libreoffice_desktop.SYSTEM_SESSION_ID] = replacement+ return replacement++ monkeypatch.setattr(manager, "_restart_system_desktop_for_timezone_locked", fake_restart)++ result = manager.sync_timezone("America/New_York")++ assert result == {+ "ok": True,+ "restarted": True,+ "session_id": libreoffice_desktop.SYSTEM_SESSION_ID,+ "timezone": "America/New_York",+ }+ assert restarted == [old_session]diff --git a/tools/wait.py b/tools/wait.pyindex 660d4c127..9265ab635 100644--- a/tools/wait.py+++ b/tools/wait.py@@ -1,5 +1,5 @@import asyncio-from datetime import datetime, timedelta, timezone+from datetime import timedeltafrom helpers.tool import Tool, Responsefrom helpers.print_style import PrintStylefrom helpers.wait import managed_wait@@ -18,7 +18,7 @@ class WaitTool(Tool):is_duration_wait = not bool(until_timestamp_str)- now = datetime.now(timezone.utc)+ now = Localization.get().now()target_time = Noneif until_timestamp_str:@@ -47,11 +47,11 @@ class WaitTool(Tool):if target_time <= now:return Response(- message=f"Target time {target_time.isoformat()} is in the past.",+ message=f"Target time {Localization.get().serialize_datetime(target_time)} is in the past.",break_loop=False,)- PrintStyle.info(f"Waiting until {target_time.isoformat()}...")+ PrintStyle.info(f"Waiting until {Localization.get().serialize_datetime(target_time)}...")target_time = await managed_wait(agent=self.agent,@@ -66,7 +66,7 @@ class WaitTool(Tool):message = self.agent.read_prompt("fw.wait_complete.md",- target_time=target_time.isoformat()+ target_time=Localization.get().serialize_datetime(target_time))return Response(diff --git a/webui/components/chat/input/composer-banner-store.js b/webui/components/chat/input/composer-banner-store.jsindex dad0a93f5..e9923bc31 100644--- a/webui/components/chat/input/composer-banner-store.js+++ b/webui/components/chat/input/composer-banner-store.js@@ -1,5 +1,6 @@import { createStore } from "/js/AlpineStore.js";import { callJsonApi } from "/js/api.js";+import { getCurrentUserISOString } from "/js/time-utils.js";function buildBannersContext() {return {@@ -8,7 +9,7 @@ function buildBannersContext() {hostname: window.location.hostname,port: window.location.port,browser: navigator.userAgent,- timestamp: new Date().toISOString(),+ timestamp: getCurrentUserISOString(),};}diff --git a/webui/components/modals/file-browser/file-browser-store.js b/webui/components/modals/file-browser/file-browser-store.jsindex dd6fb0aca..7924fb1bd 100644--- a/webui/components/modals/file-browser/file-browser-store.js+++ b/webui/components/modals/file-browser/file-browser-store.js@@ -1,5 +1,6 @@import { createStore } from "/js/AlpineStore.js";import { fetchApi } from "/js/api.js";+import { formatDateTime } from "/js/time-utils.js";import { store as fileEditorStore } from "/components/modals/file-editor/file-editor-store.js";// Model migrated from legacy file_browser.js (lift-and-shift)@@ -134,14 +135,7 @@ const model = {},formatDate(dateString) {- const options = {- year: "numeric",- month: "short",- day: "numeric",- hour: "2-digit",- minute: "2-digit",- };- return new Date(dateString).toLocaleDateString(undefined, options);+ return formatDateTime(dateString, "short");},decorateEntries(entries = [], selectedPaths = new Set()) {diff --git a/webui/components/modals/process-step-detail/step-detail-store.js b/webui/components/modals/process-step-detail/step-detail-store.jsindex cc3618475..209c8a8de 100644--- a/webui/components/modals/process-step-detail/step-detail-store.js+++ b/webui/components/modals/process-step-detail/step-detail-store.js@@ -1,6 +1,7 @@import { createStore } from "/js/AlpineStore.js";import { createActionButton, copyToClipboard } from "/components/messages/action-buttons/simple-action-buttons.js";import { store as notificationStore } from "/components/notifications/notification-store.js";+import { formatDateTime } from "/js/time-utils.js";// Step Detail Store - manages the step detail modal@@ -62,7 +63,7 @@ const model = {if (heading) lines.push(`Heading: ${heading}`);if (step.timestamp) {const date = new Date(parseFloat(step.timestamp) * 1000);- lines.push(`Timestamp: ${date.toISOString()}`);+ lines.push(`Timestamp: ${formatDateTime(date.toISOString(), "full")}`);}if (step.durationMs) lines.push(`Duration: ${step.durationMs}ms`);if (step.kvps) {diff --git a/webui/components/modals/scheduler/scheduler-store.js b/webui/components/modals/scheduler/scheduler-store.jsindex 13b22a9e3..40721a1e4 100644--- a/webui/components/modals/scheduler/scheduler-store.js+++ b/webui/components/modals/scheduler/scheduler-store.js@@ -1,6 +1,12 @@import { createStore } from "/js/AlpineStore.js";import { fetchApi } from "/js/api.js";-import { formatDateTime, getUserTimezone } from "/js/time-utils.js";+import {+ formatDateTime,+ getUserDateTimeParts,+ getUserTimezone,+ toUserISOString,+ toUserWallClockISOString,+} from "/js/time-utils.js";import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";import { store as projectsStore } from "/components/projects/projects-store.js";import { store as notificationsStore } from "/components/notifications/notification-store.js";@@ -175,18 +181,18 @@ function normalizePlanStruct(plan) {const sanitized = clone.todo.map((value) => new Date(value)).filter((date) => !Number.isNaN(date.getTime()))- .map((date) => date.toISOString())+ .map((date) => toUserISOString(date)).sort();clone.todo = sanitized;clone.done = clone.done.map((value) => new Date(value)).filter((date) => !Number.isNaN(date.getTime()))- .map((date) => date.toISOString());+ .map((date) => toUserISOString(date));if (clone.in_progress) {const inProgress = new Date(clone.in_progress);clone.in_progress = Number.isNaN(inProgress.getTime())? null- : inProgress.toISOString();+ : toUserISOString(inProgress);}return clone;}@@ -382,6 +388,8 @@ function setupPlannerInput(inputId) {wrapper.appendChild(input);input.classList.add("scheduler-flatpickr-input");+ const nowParts = getUserDateTimeParts();+ const roundedMinute = Math.ceil(nowParts.minute / 5) * 5;const options = {dateFormat: "Y-m-d H:i",enableTime: true,@@ -392,8 +400,8 @@ function setupPlannerInput(inputId) {positionElement: wrapper,theme: "scheduler-theme",minuteIncrement: 5,- defaultHour: new Date().getHours(),- defaultMinute: Math.ceil(new Date().getMinutes() / 5) * 5,+ defaultHour: roundedMinute >= 60 ? (nowParts.hour + 1) % 24 : nowParts.hour,+ defaultMinute: roundedMinute % 60,onOpen(selectedDates, dateStr, instance) {instance.calendarContainer.style.zIndex = "9999";instance.calendarContainer.style.position = "absolute";@@ -1073,7 +1081,7 @@ const schedulerStoreModel = {return;}- this.editingTask.plan.todo.push(selectedDate.toISOString());+ this.editingTask.plan.todo.push(toUserWallClockISOString(selectedDate));this.editingTask.plan.todo.sort();if (input._flatpickr) {diff --git a/webui/components/notifications/notification-store.js b/webui/components/notifications/notification-store.jsindex f41981903..baa765aef 100644--- a/webui/components/notifications/notification-store.js+++ b/webui/components/notifications/notification-store.js@@ -1,6 +1,7 @@import { createStore } from "/js/AlpineStore.js";import * as API from "/js/api.js";import { openModal } from "/js/modals.js";+import { formatDateTime, getCurrentUserISOString } from "/js/time-utils.js";export const NotificationType = {INFO: "info",@@ -408,7 +409,7 @@ const model = {else if (diffHours < 24) return `${Math.round(diffHours)}h ago`;else if (diffDays < 7) return `${Math.round(diffDays)}d ago`;- return date.toLocaleDateString();+ return formatDateTime(timestamp, "date");},// Get CSS class for notification type@@ -615,7 +616,7 @@ const model = {group = "",priority = defaultPriority) {- const timestamp = new Date().toISOString();+ const timestamp = getCurrentUserISOString();const notification = {id: `frontend-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,type: type,diff --git a/webui/components/plugins/list/plugin-execute-modal.html b/webui/components/plugins/list/plugin-execute-modal.htmlindex 0833d3eb5..76e127af9 100644--- a/webui/components/plugins/list/plugin-execute-modal.html+++ b/webui/components/plugins/list/plugin-execute-modal.html@@ -21,7 +21,7 @@<template x-if="$store.pluginExecuteStore.lastExecution"><span class="last-exec-info">Last run:- <span x-text="new Date($store.pluginExecuteStore.lastExecution.executed_at).toLocaleString()"></span>+ <span x-text="$store.pluginExecuteStore.formatTimestamp($store.pluginExecuteStore.lastExecution.executed_at)"></span> — <span :class="$store.pluginExecuteStore.lastExecution.exit_code === 0 ? 'exit-ok' : 'exit-err'"x-text="$store.pluginExecuteStore.lastExecution.exit_code === 0 ? 'succeeded' : 'failed (exit ' + $store.pluginExecuteStore.lastExecution.exit_code + ')'">diff --git a/webui/components/plugins/list/plugin-execute-store.js b/webui/components/plugins/list/plugin-execute-store.jsindex 1c06d4bbb..7b8ee46ae 100644--- a/webui/components/plugins/list/plugin-execute-store.js+++ b/webui/components/plugins/list/plugin-execute-store.js@@ -4,6 +4,7 @@ import {store as notificationStore,defaultPriority,} from "/components/notifications/notification-store.js";+import { formatDateTime } from "/js/time-utils.js";const model = {pluginName: "",@@ -78,6 +79,11 @@ const model = {this.exitCode = null;this.lastExecution = null;},++ formatTimestamp(value) {+ if (!value) return "";+ return formatDateTime(value, "full");+ },};export const store = createStore("pluginExecuteStore", model);diff --git a/webui/components/settings/agent/agent-settings.html b/webui/components/settings/agent/agent-settings.htmlindex b4bdd33fa..6e0d27656 100644--- a/webui/components/settings/agent/agent-settings.html+++ b/webui/components/settings/agent/agent-settings.html@@ -33,6 +33,18 @@<span>Workdir</span></a></li>+ <li>+ <a href="#section-locale">+ <span class="material-symbols-outlined" aria-hidden="true">language</span>+ <span>Locale</span>+ </a>+ </li>+ <li>+ <a href="#section-agent-plugins">+ <span class="material-symbols-outlined" aria-hidden="true">extension</span>+ <span>Plugins</span>+ </a>+ </li></ul></nav>@@ -52,6 +64,10 @@<x-component path="settings/agent/workdir.html"></x-component></div>+ <div id="section-locale" class="section">+ <x-component path="settings/agent/locale.html"></x-component>+ </div>+<!-- Plugin settings subsection: shows plugins tagged with "agent" --><div id="section-agent-plugins" class="section"><x-component path="settings/plugins/plugins-subsection.html" data-tab="agent"></x-component>diff --git a/webui/components/settings/agent/locale.html b/webui/components/settings/agent/locale.htmlnew file mode 100644index 000000000..31667cddb--- /dev/null+++ b/webui/components/settings/agent/locale.html@@ -0,0 +1,58 @@+<html>+ <head>+ <title>Locale</title>+ </head>++ <body>+ <div x-data>+ <template x-if="$store.settings.settings">+ <div>+ <div class="section-title">Locale</div>+ <div class="section-description">+ Control how dates and times appear across Agent Zero.+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Timezone</div>+ <div class="field-description">+ Effective timezone: <span x-text="$store.settings.effectiveTimezone"></span>+ </div>+ </div>+ <div class="field-control">+ <select+ :value="$store.settings.settings.timezone || 'auto'"+ @change="$store.settings.settings.timezone = $event.target.value"+ x-effect="$nextTick(() => { $el.value = $store.settings.settings.timezone || 'auto'; })"+ >+ <option value="auto">Automatic (browser)</option>+ <template x-for="option in $store.settings.additional?.timezones || []" :key="option.value">+ <option :value="option.value" x-text="option.label"></option>+ </template>+ </select>+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Time format</div>+ <div class="field-description">+ Choose the clock style used for displayed times.+ </div>+ </div>+ <div class="field-control">+ <select+ :value="$store.settings.settings.time_format || '12h'"+ @change="$store.settings.settings.time_format = $event.target.value"+ x-effect="$nextTick(() => { $el.value = $store.settings.settings.time_format || '12h'; })"+ >+ <option value="12h">12-hour (AM/PM)</option>+ <option value="24h">24-hour</option>+ </select>+ </div>+ </div>+ </div>+ </template>+ </div>+ </body>+</html>diff --git a/webui/components/settings/backup/backup-store.js b/webui/components/settings/backup/backup-store.jsindex 760782529..870bb98f7 100644--- a/webui/components/settings/backup/backup-store.js+++ b/webui/components/settings/backup/backup-store.js@@ -1,4 +1,11 @@import { createStore } from "/js/AlpineStore.js";+import {+ formatDateTime,+ getCurrentUserDateString,+ getCurrentUserISOString,+ getUserHour12,+ getUserTimezone,+} from "/js/time-utils.js";// Global function referencesconst sendJsonData = globalThis.sendJsonData;@@ -70,7 +77,11 @@ const model = {// File operations loggingaddFileOperation(message) {- const timestamp = new Date().toLocaleTimeString();+ const timestamp = new Intl.DateTimeFormat(undefined, {+ timeStyle: "medium",+ hour12: getUserHour12(),+ timeZone: getUserTimezone(),+ }).format(new Date());this.fileOperationsLog += `[${timestamp}] ${message}\n`;// Auto-scroll to bottom - use setTimeout since $nextTick is not available in stores@@ -117,7 +128,7 @@ const model = {// Get default backup metadata with resolved patterns from backendasync getDefaultBackupMetadata() {- const timestamp = new Date().toISOString();+ const timestamp = getCurrentUserISOString();try {// Get resolved default patterns from backend@@ -129,7 +140,7 @@ const model = {const exclude_patterns = response.default_patterns.exclude_patterns;return {- backup_name: `agent-zero-backup-${timestamp.slice(0, 10)}`,+ backup_name: `agent-zero-backup-${getCurrentUserDateString()}`,include_hidden: true,include_patterns: include_patterns,exclude_patterns: exclude_patterns,@@ -841,7 +852,7 @@ const model = {// UtilityformatTimestamp(timestamp) {if (!timestamp) return 'Unknown';- return new Date(timestamp).toLocaleString();+ return formatDateTime(timestamp, "full");},formatFileSize(bytes) {@@ -853,7 +864,7 @@ const model = {formatDate(dateString) {if (!dateString) return 'Unknown';- return new Date(dateString).toLocaleDateString();+ return formatDateTime(dateString, "date");}};diff --git a/webui/components/settings/developer/websocket-event-console-store.js b/webui/components/settings/developer/websocket-event-console-store.jsindex 811842d5e..c3c19b6e0 100644--- a/webui/components/settings/developer/websocket-event-console-store.js+++ b/webui/components/settings/developer/websocket-event-console-store.js@@ -1,6 +1,7 @@import { createStore } from "/js/AlpineStore.js";import { getNamespacedClient } from "/js/websocket.js";import { store as notificationStore } from "/components/notifications/notification-store.js";+import { getCurrentUserISOString } from "/js/time-utils.js";const websocket = getNamespacedClient("/ws");websocket.addHandlers(["ws_dev_test"]);@@ -112,7 +113,7 @@ const model = {try {await websocket.request(SUBSCRIBE_EVENT, {- requestedAt: new Date().toISOString(),+ requestedAt: getCurrentUserISOString(),});this.subscriptionActive = true;this.lastError = null;@@ -205,7 +206,7 @@ const model = {eventId: envelope?.eventId || null,sid: payload.sid || null,correlationId: payload.correlationId || envelope?.correlationId || null,- timestamp: payload.timestamp || envelope?.ts || new Date().toISOString(),+ timestamp: payload.timestamp || envelope?.ts || getCurrentUserISOString(),handlerId: payload.handlerId || envelope?.handlerId || "WsManager",resultSummary: payload.resultSummary || {},payloadSummary: payload.payloadSummary || {},diff --git a/webui/components/settings/developer/websocket-test-store.js b/webui/components/settings/developer/websocket-test-store.jsindex fefcedec2..0d659a23f 100644--- a/webui/components/settings/developer/websocket-test-store.js+++ b/webui/components/settings/developer/websocket-test-store.js@@ -7,6 +7,7 @@ import {import { store as notificationStore } from "/components/notifications/notification-store.js";import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";import { store as syncStore } from "/components/sync/sync-store.js";+import { getCurrentUserISOString, getUserTimezone } from "/js/time-utils.js";const MAX_PAYLOAD_BYTES = 50 * 1024 * 1024;const TOAST_DURATION = 5;@@ -16,7 +17,7 @@ websocket.addHandlers(["ws_dev_test"]);const stateSocket = websocket; // same /ws namespace clientfunction now() {- return new Date().toISOString();+ return getCurrentUserISOString();}function payloadSize(value) {@@ -459,7 +460,7 @@ const model = {await this.ensureSubscribed("state_push", true);this.appendLog("Subscribed to state_push.");- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ const timezone = getUserTimezone();const response = await stateSocket.request("state_request",{diff --git a/webui/components/settings/external/self-update-store.js b/webui/components/settings/external/self-update-store.jsindex 242066064..36e58b1ba 100644--- a/webui/components/settings/external/self-update-store.js+++ b/webui/components/settings/external/self-update-store.js@@ -2,6 +2,7 @@ import { createStore } from "/js/AlpineStore.js";import * as API from "/js/api.js";import { store as notificationStore } from "/components/notifications/notification-store.js";import { openModal, closeModal } from "/js/modals.js";+import { formatDateTime } from "/js/time-utils.js";const HEALTH_POLL_INTERVAL_MS = 2000;const HEALTH_WAIT_BUFFER_MS = 30000;@@ -332,7 +333,7 @@ const model = {formatTimestamp(value) {if (!value) return "";try {- return new Date(value).toLocaleString();+ return formatDateTime(value, "full");} catch {return value;}diff --git a/webui/components/settings/settings-store.js b/webui/components/settings/settings-store.jsindex 2f1f28193..bd45b35c4 100644--- a/webui/components/settings/settings-store.js+++ b/webui/components/settings/settings-store.js@@ -1,6 +1,11 @@import { createStore } from "/js/AlpineStore.js";import * as API from "/js/api.js";import { store as notificationStore } from "/components/notifications/notification-store.js";+import {+ getBrowserTimezone,+ setConfiguredTimeFormat,+ setConfiguredTimezone,+} from "/js/time-utils.js";// Constantsconst VIEW_MODE_STORAGE_KEY = "settingsActiveTab";@@ -17,8 +22,9 @@ const TAB_ITEMS = Object.freeze([sections: [{ id: "section-agent-config", label: "Agent Config", icon: "settings" },{ id: "section-models-summary", label: "Models", icon: "forum" },- { id: "section-speech", label: "Speech", icon: "mic" },+ { id: "section-voice", label: "Voice", icon: "mic" },{ id: "section-workdir", label: "Workdir", icon: "folder" },+ { id: "section-locale", label: "Locale", icon: "language" },{ id: "section-agent-plugins", label: "Plugins", icon: "extension" },],},@@ -135,6 +141,7 @@ const model = {if (response && response.settings) {this.settings = response.settings;this.additional = response.additional || null;+ this.applyLocaleRuntime(this.settings);} else {throw new Error("Invalid settings response");}@@ -210,6 +217,30 @@ const model = {return tab?.sections?.[0]?.id || null;},+ get browserTimezone() {+ return getBrowserTimezone();+ },++ get effectiveTimezone() {+ if (!this.settings) return this.browserTimezone;+ return this.settings.timezone === "auto"+ ? this.browserTimezone+ : this.settings.timezone || this.browserTimezone;+ },++ applyTimezoneRuntime(timezone) {+ setConfiguredTimezone(timezone || "auto");+ },++ applyTimeFormatRuntime(timeFormat) {+ setConfiguredTimeFormat(timeFormat || "12h");+ },++ applyLocaleRuntime(settings) {+ this.applyTimezoneRuntime(settings?.timezone);+ this.applyTimeFormatRuntime(settings?.time_format);+ },+getTabIdForSection(sectionId) {if (!sectionId) return null;const tab = TAB_ITEMS.find((item) =>@@ -476,10 +507,14 @@ const model = {this.isLoading = true;try {- const response = await API.callJsonApi("settings_set", { settings: this.settings });+ const response = await API.callJsonApi("settings_set", {+ settings: this.settings,+ browser_timezone: this.browserTimezone,+ });if (response && response.settings) {this.settings = response.settings;this.additional = response.additional || this.additional;+ this.applyLocaleRuntime(this.settings);toast("Settings saved successfully", "success");document.dispatchEvent(new CustomEvent("settings-updated", { detail: response.settings })diff --git a/webui/components/welcome/welcome-store.js b/webui/components/welcome/welcome-store.jsindex 7d6d3bbe0..13fc5d730 100644--- a/webui/components/welcome/welcome-store.js+++ b/webui/components/welcome/welcome-store.js@@ -5,6 +5,7 @@ import { store as memoryStore } from "/plugins/_memory/webui/memory-dashboard-stimport { store as projectsStore } from "/components/projects/projects-store.js";import { store as chatInputStore } from "/components/chat/input/input-store.js";import * as API from "/js/api.js";+import { getCurrentUserISOString } from "/js/time-utils.js";const model = {// State@@ -44,7 +45,7 @@ const model = {hostname: window.location.hostname,port: window.location.port,browser: navigator.userAgent,- timestamp: new Date().toISOString(),+ timestamp: getCurrentUserISOString(),};},diff --git a/webui/index.html b/webui/index.htmlindex 97460bb84..5a7889211 100644--- a/webui/index.html+++ b/webui/index.html@@ -70,6 +70,8 @@id: "{{runtime_id}}",isDevelopment: "{{runtime_is_development}}" === "true",loggedIn: "{{logged_in}}" === "true",+ timezone: "{{user_timezone_setting}}",+ timeFormat: "{{user_time_format_setting}}",};</script><!-- Plugin head injections (scripts, stylesheets) -->diff --git a/webui/index.js b/webui/index.jsindex 97897fcbb..9320ad064 100644--- a/webui/index.js+++ b/webui/index.js@@ -14,6 +14,7 @@ import { store as chatTopStore } from "/components/chat/top-section/chat-top-stoimport { store as _tooltipsStore } from "/components/tooltips/tooltip-store.js";import { store as messageQueueStore } from "/components/chat/message-queue/message-queue-store.js";import { store as syncStore } from "/components/sync/sync-store.js"+import { getUserHour12, getUserTimezone } from "/js/time-utils.js";globalThis.fetchApi = api.fetchApi; // TODO - backward compatibility for non-modular scripts, remove once refactored to alpine@@ -198,20 +199,21 @@ async function updateUserTime() {}const now = new Date();- const hours = now.getHours();- const minutes = now.getMinutes();- const seconds = now.getSeconds();- const ampm = hours >= 12 ? "pm" : "am";- const formattedHours = hours % 12 || 12;-- // Format the time- const timeString = `${formattedHours}:${minutes- .toString()- .padStart(2, "0")}:${seconds.toString().padStart(2, "0")} ${ampm}`;-- // Format the date- const options = { year: "numeric", month: "short", day: "numeric" };- const dateString = now.toLocaleDateString(undefined, options);+ const timezone = getUserTimezone();+ const hour12 = getUserHour12();+ const timeString = new Intl.DateTimeFormat(undefined, {+ hour: "numeric",+ minute: "2-digit",+ second: "2-digit",+ hour12,+ timeZone: timezone,+ }).format(now).toLowerCase();+ const dateString = new Intl.DateTimeFormat(undefined, {+ year: "numeric",+ month: "short",+ day: "numeric",+ timeZone: timezone,+ }).format(now);// Update the HTMLuserTimeElement.innerHTML = `${timeString}<br><span id="user-date">${dateString}</span>`;@@ -288,7 +290,7 @@ let lastSpokenNo = 0;export function buildStateRequestPayload(options = {}) {const { forceFull = false } = options || {};- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ const timezone = getUserTimezone();return {context: context || null,log_from: forceFull ? 0 : lastLogVersion,@@ -415,8 +417,7 @@ export async function applySnapshot(snapshot, options = {}) {export async function poll() {try {- // Get timezone from navigator- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ const timezone = getUserTimezone();const log_from = lastLogVersion;const response = await sendJsonData("/poll", {diff --git a/webui/js/messages.js b/webui/js/messages.jsindex f45fb1ffa..6ed61338e 100644--- a/webui/js/messages.js+++ b/webui/js/messages.js@@ -10,7 +10,12 @@ import {} from "/components/messages/action-buttons/simple-action-buttons.js";import { store as stepDetailStore } from "/components/modals/process-step-detail/step-detail-store.js";import { store as preferencesStore } from "/components/sidebar/bottom/preferences/preferences-store.js";-import { formatDuration } from "./time-utils.js";+import {+ formatDateTime,+ formatDuration,+ getUserHour12,+ getUserTimezone,+} from "./time-utils.js";import { Scroller } from "./scroller.js";import { callJsExtensions } from "/js/extensions.js";import { addBlankTargetsToLinks } from "/js/html-links.js";@@ -2096,14 +2101,15 @@ function updateProcessGroupHeader(group) {const startTimestamp = group.getAttribute("data-start-timestamp");if (timeMetricEl && startTimestamp) {const date = new Date(parseFloat(startTimestamp) * 1000);- const hours = String(date.getHours()).padStart(2, "0");- const minutes = String(date.getMinutes()).padStart(2, "0");- timeMetricEl.textContent = `${hours}:${minutes}`;+ const hour12 = getUserHour12();+ timeMetricEl.textContent = new Intl.DateTimeFormat(undefined, {+ hour: hour12 ? "numeric" : "2-digit",+ minute: "2-digit",+ hour12,+ timeZone: getUserTimezone(),+ }).format(date);if (timeMetricContainerEl) {- const fullDateTime = date.toLocaleString(undefined, {- dateStyle: "medium",- timeStyle: "short",- });+ const fullDateTime = formatDateTime(date.toISOString(), "short");timeMetricContainerEl.title =timeMetricContainerEl.dataset.bsOriginalTitle = fullDateTime;}diff --git a/webui/js/time-utils.js b/webui/js/time-utils.jsindex 0850ff04f..a59dc7cfe 100644--- a/webui/js/time-utils.js+++ b/webui/js/time-utils.js@@ -1,30 +1,34 @@/**- * Time utilities for handling UTC to local time conversion+ * Time utilities for handling user-local time conversion.*/+const TIME_FORMAT_12H = "12h";+const TIME_FORMAT_24H = "24h";+/**- * Convert a UTC ISO string to a local time string- * @param {string} utcIsoString - UTC time in ISO format+ * Convert an ISO string to a local time string+ * @param {string} utcIsoString - ISO time string* @param {Object} options - Formatting options for Intl.DateTimeFormat* @returns {string} Formatted local time string*/export function toLocalTime(utcIsoString, options = {}) {if (!utcIsoString) return '';- const date = new Date(utcIsoString);+ const date = utcIsoString instanceof Date ? utcIsoString : new Date(utcIsoString);const defaultOptions = {dateStyle: 'medium',- timeStyle: 'medium'+ timeStyle: 'medium',+ timeZone: getUserTimezone(),};return new Intl.DateTimeFormat(undefined, // Use browser's locale- { ...defaultOptions, ...options }+ withUserTimeFormatOptions({ ...defaultOptions, ...options })).format(date);}/**- * Convert a local Date object to UTC ISO string+ * Convert a Date object to a UTC ISO string.* @param {Date} date - Date object in local time* @returns {string} UTC ISO string*/@@ -34,16 +38,171 @@ export function toUTCISOString(date) {}/**- * Get current time as UTC ISO string+ * Get current time as a UTC ISO string.* @returns {string} Current UTC time in ISO format*/export function getCurrentUTCISOString() {return new Date().toISOString();}+function padNumber(value, width = 2) {+ return String(value).padStart(width, "0");+}++function getTimeZoneParts(date, timeZone) {+ const formatter = new Intl.DateTimeFormat("en-US", {+ timeZone,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ hourCycle: "h23",+ });+ const parts = Object.fromEntries(+ formatter.formatToParts(date)+ .filter((part) => part.type !== "literal")+ .map((part) => [part.type, part.value])+ );+ return {+ year: Number(parts.year),+ month: Number(parts.month),+ day: Number(parts.day),+ hour: Number(parts.hour),+ minute: Number(parts.minute),+ second: Number(parts.second),+ millisecond: date.getMilliseconds(),+ };+}++export function getUserDateTimeParts(date = new Date()) {+ return getTimeZoneParts(date, getUserTimezone());+}++function getTimeZoneOffsetMinutes(date, timeZone, parts = getTimeZoneParts(date, timeZone)) {+ const asUtc = Date.UTC(+ parts.year,+ parts.month - 1,+ parts.day,+ parts.hour,+ parts.minute,+ parts.second,+ parts.millisecond,+ );+ return Math.round((asUtc - date.getTime()) / 60_000);+}++function formatOffset(offsetMinutes) {+ const sign = offsetMinutes >= 0 ? "+" : "-";+ const absOffset = Math.abs(offsetMinutes);+ return `${sign}${padNumber(Math.floor(absOffset / 60))}:${padNumber(absOffset % 60)}`;+}++function formatPartsAsIso(parts, offsetMinutes) {+ return [+ parts.year,+ "-",+ padNumber(parts.month),+ "-",+ padNumber(parts.day),+ "T",+ padNumber(parts.hour),+ ":",+ padNumber(parts.minute),+ ":",+ padNumber(parts.second),+ ".",+ padNumber(parts.millisecond, 3),+ formatOffset(offsetMinutes),+ ].join("");+}++function getLocalDateParts(date) {+ return {+ year: date.getFullYear(),+ month: date.getMonth() + 1,+ day: date.getDate(),+ hour: date.getHours(),+ minute: date.getMinutes(),+ second: date.getSeconds(),+ millisecond: date.getMilliseconds(),+ };+}++function getWallClockOffsetMinutes(parts, timeZone) {+ const wallClockUtc = Date.UTC(+ parts.year,+ parts.month - 1,+ parts.day,+ parts.hour,+ parts.minute,+ parts.second,+ parts.millisecond,+ );+ let offsetMinutes = getTimeZoneOffsetMinutes(new Date(wallClockUtc), timeZone);+ for (let attempt = 0; attempt < 3; attempt += 1) {+ const instant = new Date(wallClockUtc - offsetMinutes * 60_000);+ const nextOffset = getTimeZoneOffsetMinutes(instant, timeZone);+ if (nextOffset === offsetMinutes) return offsetMinutes;+ offsetMinutes = nextOffset;+ }+ return offsetMinutes;+}++/**+ * Convert a Date object to an ISO string with the user's local UTC offset.+ * @param {Date} date - Date object in local time+ * @returns {string} Local ISO string, e.g. 2026-05-03T10:15:30.000+02:00+ */+export function toUserISOString(date = new Date()) {+ if (!date) return "";+ const timeZone = getUserTimezone();+ const parts = getTimeZoneParts(date, timeZone);+ const offsetMinutes = getTimeZoneOffsetMinutes(date, timeZone, parts);+ return formatPartsAsIso(parts, offsetMinutes);+}++/**+ * Interpret a browser-local Date's visible wall-clock fields in the configured user timezone.+ * Use this for date/time picker values where the selected calendar fields matter more than+ * the browser's local instant.+ * @param {Date} date - Date object whose local fields came from user input+ * @returns {string} User-timezone ISO string preserving the selected wall-clock fields+ */+export function toUserWallClockISOString(date = new Date()) {+ if (!date) return "";+ const timeZone = getUserTimezone();+ const parts = getLocalDateParts(date);+ const offsetMinutes = getWallClockOffsetMinutes(parts, timeZone);+ return formatPartsAsIso(parts, offsetMinutes);+}+/**- * Format a UTC ISO string for display in local time with configurable format- * @param {string} utcIsoString - UTC time in ISO format+ * Get current time as an ISO string with the user's local UTC offset.+ * @returns {string}+ */+export function getCurrentUserISOString() {+ return toUserISOString(new Date());+}++/**+ * Get current user-local calendar date as YYYY-MM-DD.+ * @returns {string}+ */+export function getCurrentUserDateString() {+ const now = new Date();+ const parts = getTimeZoneParts(now, getUserTimezone());+ return [+ parts.year,+ padNumber(parts.month),+ padNumber(parts.day),+ ].join("-");+}++/**+ * Format an ISO string for display in local time with configurable format+ * @param {string} utcIsoString - ISO time string* @param {string} format - Format type ('full', 'date', 'time', 'short')* @returns {string} Formatted local time string*/@@ -51,6 +210,7 @@ export function formatDateTime(utcIsoString, format = 'full') {if (!utcIsoString) return '';const date = new Date(utcIsoString);+ if (Number.isNaN(date.getTime())) return String(utcIsoString);const formatOptions = {full: { dateStyle: 'medium', timeStyle: 'medium' },@@ -59,7 +219,7 @@ export function formatDateTime(utcIsoString, format = 'full') {short: { dateStyle: 'short', timeStyle: 'short' }};- return toLocalTime(utcIsoString, formatOptions[format] || formatOptions.full);+ return toLocalTime(date, formatOptions[format] || formatOptions.full);}/**@@ -67,7 +227,66 @@ export function formatDateTime(utcIsoString, format = 'full') {* @returns {string} Timezone name (e.g., 'America/New_York')*/export function getUserTimezone() {- return Intl.DateTimeFormat().resolvedOptions().timeZone;+ const configured = String(globalThis.runtimeInfo?.timezone || "").trim();+ if (configured && configured !== "auto") return configured;+ return getBrowserTimezone();+}++export function getBrowserTimezone() {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";+}++export function setConfiguredTimezone(timezone) {+ globalThis.runtimeInfo = {+ ...(globalThis.runtimeInfo || {}),+ timezone: String(timezone || "auto").trim() || "auto",+ };+}++function normalizeTimeFormat(timeFormat) {+ return String(timeFormat || "")+ .trim()+ .toLowerCase() === TIME_FORMAT_24H+ ? TIME_FORMAT_24H+ : TIME_FORMAT_12H;+}++/**+ * Get the preferred clock display format.+ * @returns {"12h" | "24h"}+ */+export function getUserTimeFormat() {+ return normalizeTimeFormat(+ globalThis.runtimeInfo?.timeFormat || globalThis.runtimeInfo?.time_format+ );+}++/**+ * Return whether user-facing times should use AM/PM.+ * @returns {boolean}+ */+export function getUserHour12() {+ return getUserTimeFormat() === TIME_FORMAT_12H;+}++export function setConfiguredTimeFormat(timeFormat) {+ globalThis.runtimeInfo = {+ ...(globalThis.runtimeInfo || {}),+ timeFormat: normalizeTimeFormat(timeFormat),+ };+}++export function withUserTimeFormatOptions(options = {}) {+ const formatted = { ...options };+ if (+ formatted.timeStyle ||+ formatted.hour ||+ formatted.minute ||+ formatted.second+ ) {+ formatted.hour12 = getUserHour12();+ }+ return formatted;}/**diff --git a/webui/js/websocket.js b/webui/js/websocket.jsindex 510c167f0..e7f655a29 100644--- a/webui/js/websocket.js+++ b/webui/js/websocket.js@@ -1,5 +1,6 @@import { io } from "/vendor/socket.io.esm.min.js";import { getCsrfToken, getRuntimeId, invalidateCsrfToken } from "/js/api.js";+import { getCurrentUserISOString } from "/js/time-utils.js";const MAX_PAYLOAD_BYTES = 50 * 1024 * 1024; // 50MB hard cap per contractconst DEFAULT_TIMEOUT_MS = 0;@@ -333,7 +334,7 @@ class WebSocketClient {}buildPayload(data) {- const ts = new Date().toISOString();+ const ts = getCurrentUserISOString();if (data == null) {return { ts, data: {} };}