Skip to content

Agent Zero AI framework

(WIP) feat: Task Scheduler Management UI/UX and tools - Part 3

Rafael Uzarowskieb275d9c9cd1
diff --git a/agent.py b/agent.py
index 3bfd885f8..4bad52ec2 100644
--- a/agent.py
+++ b/agent.py
@@ -27,6 +27,7 @@ from python.helpers.dirty_json import DirtyJson
from python.helpers.defer import DeferredTask
from typing import Callable
from python.helpers.history import OutputMessage
+from python.helpers.localization import Localization
class AgentContext:
@@ -80,6 +81,21 @@ class AgentContext:
context.task.kill()
return context
+ def serialize(self):
+ return {
+ "id": self.id,
+ "name": self.name,
+ "created_at": (
+ Localization.get().serialize_datetime(self.created_at)
+ if self.created_at else Localization.get().serialize_datetime(datetime.fromtimestamp(0))
+ ),
+ "no": self.no,
+ "log_guid": self.log.guid,
+ "log_version": len(self.log.updates),
+ "log_length": len(self.log.logs),
+ "paused": self.paused,
+ }
+
def get_created_at(self):
return self.created_at
@@ -654,8 +670,13 @@ class Agent:
if tool_request is not None:
tool_name = tool_request.get("tool_name", "")
+ tool_method = None
tool_args = tool_request.get("tool_args", {})
- tool = self.get_tool(tool_name, tool_args, msg)
+
+ if ":" in tool_name:
+ tool_name, tool_method = tool_name.split(":", 1)
+
+ tool = self.get_tool(name=tool_name, method=tool_method, args=tool_args, message=msg)
await self.handle_intervention() # wait if paused and handle intervention message if needed
await tool.before_execution(**tool_args)
@@ -685,7 +706,7 @@ class Agent:
except Exception as e:
pass
- def get_tool(self, name: str, args: dict, message: str, **kwargs):
+ def get_tool(self, name: str, method: str | None, args: dict, message: str, **kwargs):
from python.tools.unknown import Unknown
from python.helpers.tool import Tool
@@ -693,7 +714,7 @@ class Agent:
"python/tools", name + ".py", Tool
)
tool_class = classes[0] if classes else Unknown
- return tool_class(agent=self, name=name, args=args, message=message, **kwargs)
+ return tool_class(agent=self, name=name, method=method, args=args, message=message, **kwargs)
async def call_extensions(self, folder: str, **kwargs) -> Any:
from python.helpers.extension import Extension
diff --git a/docker/run/Dockerfile b/docker/run/Dockerfile
index 935d347b0..4502b077c 100644
--- a/docker/run/Dockerfile
+++ b/docker/run/Dockerfile
@@ -6,6 +6,19 @@ ARG BRANCH
RUN if [ -z "$BRANCH" ]; then echo "ERROR: BRANCH is not set!" >&2; exit 1; fi
ENV BRANCH=$BRANCH
+# Set locale to en_US.UTF-8 and timezone to UTC
+RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y locales tzdata
+RUN sed -i -e 's/# \(en_US\.UTF-8 .*\)/\1/' /etc/locale.gen && \
+ dpkg-reconfigure --frontend=noninteractive locales && \
+ update-locale LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_ALL=en_US.UTF-8
+RUN ln -sf /usr/share/zoneinfo/UTC /etc/localtime
+RUN echo "UTC" > /etc/timezone
+RUN dpkg-reconfigure -f noninteractive tzdata
+ENV LANG=en_US.UTF-8
+ENV LANGUAGE=en_US:en
+ENV LC_ALL=en_US.UTF-8
+ENV TZ=UTC
+
# Copy contents of the project to /a0
COPY ./fs/ /
diff --git a/docker/run/DockerfileKali b/docker/run/DockerfileKali
index 41cbeaa30..c456ae4e2 100644
--- a/docker/run/DockerfileKali
+++ b/docker/run/DockerfileKali
@@ -6,6 +6,19 @@ ARG BRANCH
RUN if [ -z "$BRANCH" ]; then echo "ERROR: BRANCH is not set!" >&2; exit 1; fi
ENV BRANCH=$BRANCH
+# Set locale to en_US.UTF-8 and timezone to UTC
+RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y locales tzdata
+RUN sed -i -e 's/# \(en_US\.UTF-8 .*\)/\1/' /etc/locale.gen && \
+ dpkg-reconfigure --frontend=noninteractive locales && \
+ update-locale LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_ALL=en_US.UTF-8
+RUN ln -sf /usr/share/zoneinfo/UTC /etc/localtime
+RUN echo "UTC" > /etc/timezone
+RUN dpkg-reconfigure -f noninteractive tzdata
+ENV LANG=en_US.UTF-8
+ENV LANGUAGE=en_US:en
+ENV LC_ALL=en_US.UTF-8
+ENV TZ=UTC
+
# Copy contents of the project to /a0
COPY ./fs/ /
diff --git a/prompts/default/agent.system.datetime.md b/prompts/default/agent.system.datetime.md
new file mode 100644
index 000000000..2dd47f898
--- /dev/null
+++ b/prompts/default/agent.system.datetime.md
@@ -0,0 +1,3 @@
+# Current system date and time of user
+- Current Date and Time is: {{date_time}}
+- !!! rely solely on this information for time-sensitive tasks as it is always up to date
diff --git a/prompts/default/agent.system.main.environment.md b/prompts/default/agent.system.main.environment.md
index a53608d39..6585e5ad1 100644
--- a/prompts/default/agent.system.main.environment.md
+++ b/prompts/default/agent.system.main.environment.md
@@ -1,4 +1,3 @@
## Environment
live in debian linux docker container
agent zero framework is python project in /a0 folder
-
diff --git a/prompts/default/agent.system.main.md b/prompts/default/agent.system.main.md
index 7fb284c7a..e18153064 100644
--- a/prompts/default/agent.system.main.md
+++ b/prompts/default/agent.system.main.md
@@ -8,4 +8,4 @@
{{ include "./agent.system.main.solving.md" }}
-{{ include "./agent.system.main.tips.md" }}
\ No newline at end of file
+{{ include "./agent.system.main.tips.md" }}
diff --git a/prompts/default/agent.system.tool.scheduler.md b/prompts/default/agent.system.tool.scheduler.md
new file mode 100644
index 000000000..fd281e58a
--- /dev/null
+++ b/prompts/default/agent.system.tool.scheduler.md
@@ -0,0 +1,215 @@
+## Task Scheduler Subsystem:
+The task scheduler is a part of agent-zero enabling the system to execute
+arbitrary tasks defined by a "system prompt" and "user prompt".
+
+When the task is executed the prompts are being run in the background in a context
+conversation with the goal of completing the task described in the prompts.
+
+Dedicated context means the task will run in it's own chat. If task is created without the
+dedicated_context flag then the task will run in the chat it was created in including entire history.
+
+There are manual and automatically executed tasks.
+Automatic execution happens by a schedule defined when creating the task.
+
+### Types of scheduler tasks
+There are 3 types of scheduler tasks:
+
+#### Scheduled - type="scheduled"
+This type of task is run by a recurring schedule defined in the crontab syntax with 5 fields (ex. */5 * * * * means every 5 minutes).
+It is recurring and started automatically when the crontab syntax requires next execution..
+
+#### Planned - type="planned"
+This type of task is run by a linear schedule defined as discrete datetimes of the upcoming executions.
+It is started automatically when a scheduled time elapses.
+
+#### AdHoc - type="adhoc"
+This type of task is run manually and does not follow any schedule. It can be run explicitly by "scheduler:run_task" agent tool or by the user in the UI.
+
+### Tools to manage the task scheduler system and it's tasks
+
+#### scheduler:list_tasks
+List all tasks present in the system with their 'uuid', 'name', 'type', 'state', 'schedule' and 'next_run'.
+All runnable tasks can be listed and filtered here. The arbuments a filter fields.
+
+##### Arguments:
+* state: list(str) (Optional) - The state filter, one of "idle", "running", "disabled", "error". To only show tasks in given state.
+* type: list(str) (Optional) - The task type filter, one of "adhoc", "planned", "scheduled"
+* next_run_within: int (Optional) - The next run of the task must be within this many minutes
+* next_run_after: int (Optional) - The next run of the task must be after not less than this many minutes
+
+##### Usage:
+~~~json
+{
+ "thoughts": [
+ "I must look for planned runnable tasks with name ... and state idle or error",
+ "The tasks should run within next 20 minutes"
+ ],
+ "tool_name": "scheduler:list_tasks",
+ "tool_args": {
+ "state": ["idle", "error"],
+ "type": ["planned"],
+ "next_run_within": 20
+ }
+}
+~~~
+
+
+#### scheduler:show_task
+Show task details for scheduler task with the given uuid.
+
+##### Arguments:
+* uuid: string - The uuid of the task to display
+
+##### Usage (execute task with uuid "xyz-123"):
+~~~json
+{
+ "thoughts": [
+ "I need details of task xxx-yyy-zzz",
+ ],
+ "tool_name": "scheduler:show_task",
+ "tool_args": {
+ "uuid": "xxx-yyy-zzz",
+ }
+}
+~~~
+
+
+#### scheduler:run_task
+Execute a task manually which is not in "running" state
+This can be used to trigger tasks manually.
+Normally you should only "run" tasks manually if they are in the "idle" state.
+It is also advised to only run "adhoc" tasks manually but every task type can be triggered by this tool.
+
+##### Arguments:
+* uuid: string - The uuid of the task to run. Can be retrieved for example from "scheduler:tasks_list"
+
+##### Usage (execute task with uuid "xyz-123"):
+~~~json
+{
+ "thoughts": [
+ "I must run task xyz-123",
+ ],
+ "tool_name": "scheduler:run_task",
+ "tool_args": {
+ "uuid": "xyz-123",
+ }
+}
+~~~
+
+
+#### scheduler:delete_task
+Delete the task defined by the given uuid from the system.
+
+##### Arguments:
+* uuid: string - The uuid of the task to run. Can be retrieved for example from "scheduler:tasks_list"
+
+##### Usage (execute task with uuid "xyz-123"):
+~~~json
+{
+ "thoughts": [
+ "I must delete task xyz-123",
+ ],
+ "tool_name": "scheduler:delete_task",
+ "tool_args": {
+ "uuid": "xyz-123",
+ }
+}
+~~~
+
+
+#### scheduler:create_scheduled_task
+Create a task within the scheduler system with the type "scheduled".
+The scheduled type of tasks is being run by a cron schedule that you must provide.
+
+##### Arguments:
+* name: str - The name of the task, will also be displayed when listing tasks
+* system_prompt: str - The system prompt to be used when executing the task
+* prompt: str - The actual prompt with the task definition
+* schedule: dict[str,str] - the dict of all cron schedule values. The keys are descriptive: minute, hour, day, month, weekday. The values are cron syntax fields named by the keys.
+* attachments: list[str] - Here you can add message attachments, valid are filesystem paths and internet urls
+* dedicated_context: bool - if false, then the task will run in the context it was created in. If true, the task will have it's own context. If unspecified then false is assumed. The tasks run in the context they were created in by default.
+
+##### Usage:
+~~~json
+{
+ "thoughts": [
+ "I must create new scheduled task with name XXX running every 20 minutes in a separate chat"
+ ],
+ "tool_name": "scheduler:create_scheduled_task",
+ "tool_args": {
+ "name": "XXX",
+ "system_prompt": "You are a software developer",
+ "prompt": "Send the user an email with a greeting using python and smtp. The user's address is: [email protected]",
+ "attachments": [],
+ "schedule": {
+ "minute": "*/20",
+ "hour": "*",
+ "day": "*",
+ "month": "*",
+ "weekday": "*",
+ },
+ "dedicated_context": true
+ }
+}
+~~~
+
+
+#### scheduler:create_adhoc_task
+Create a task within the scheduler system with the type "adhoc".
+The adhoc type of tasks is being run manually by "scheduler:run_task" tool or by the user via ui.
+
+##### Arguments:
+* name: str - The name of the task, will also be displayed when listing tasks
+* system_prompt: str - The system prompt to be used when executing the task
+* prompt: str - The actual prompt with the task definition
+* attachments: list[str] - Here you can add message attachments, valid are filesystem paths and internet urls
+* dedicated_context: bool - if false, then the task will run in the context it was created in. If true, the task will have it's own context. If unspecified then false is assumed. The tasks run in the context they were created in by default.
+
+##### Usage:
+~~~json
+{
+ "thoughts": [
+ "I must create new scheduled task with name XXX running every 20 minutes"
+ ],
+ "tool_name": "scheduler:create_adhoc_task",
+ "tool_args": {
+ "name": "XXX",
+ "system_prompt": "You are a software developer",
+ "prompt": "Send the user an email with a greeting using python and smtp. The user's address is: [email protected]",
+ "attachments": [],
+ "dedicated_context": false
+ }
+}
+~~~
+
+
+#### scheduler:create_planned_task
+Create a task within the scheduler system with the type "planned".
+The planned type of tasks is being run by a fixed plan, a list of datetimes that you must provide.
+
+##### Arguments:
+* name: str - The name of the task, will also be displayed when listing tasks
+* system_prompt: str - The system prompt to be used when executing the task
+* prompt: str - The actual prompt with the task definition
+* plan: list(iso datetime string) - the list of all execution timestamps. The dates should be in the 24 hour (!) strftime iso format: "%Y-%m-%dT%H:%M:%S"
+* attachments: list[str] - Here you can add message attachments, valid are filesystem paths and internet urls
+* dedicated_context: bool - if false, then the task will run in the context it was created in. If true, the task will have it's own context. If unspecified then false is assumed. The tasks run in the context they were created in by default.
+
+##### Usage:
+~~~json
+{
+ "thoughts": [
+ "I must create new planned task to run tomorow at 6:25 PM",
+ "Today is 2025-04-29 according to system prompt"
+ ],
+ "tool_name": "scheduler:create_planned_task",
+ "tool_args": {
+ "name": "XXX",
+ "system_prompt": "You are a software developer",
+ "prompt": "Send the user an email with a greeting using python and smtp. The user's address is: [email protected]",
+ "attachments": [],
+ "plan": ["2025-04-29T18:25:00"],
+ "dedicated_context": false
+ }
+}
+~~~
diff --git a/prompts/default/agent.system.tools.md b/prompts/default/agent.system.tools.md
index 43f35ea12..ce151c2b2 100644
--- a/prompts/default/agent.system.tools.md
+++ b/prompts/default/agent.system.tools.md
@@ -15,3 +15,5 @@
{{ include './agent.system.tool.input.md' }}
{{ include './agent.system.tool.browser.md' }}
+
+{{ include './agent.system.tool.scheduler.md' }}
diff --git a/prompts/default/fw.intervention.md b/prompts/default/fw.intervention.md
index 7f03e2521..793dbd3cc 100644
--- a/prompts/default/fw.intervention.md
+++ b/prompts/default/fw.intervention.md
@@ -1,7 +1,7 @@
```json
{
- "user_intervention": {{message}},
"system_message": {{system_message}},
+ "user_intervention": {{message}},
"attachments": {{attachments}}
}
```
diff --git a/prompts/default/fw.user_message.md b/prompts/default/fw.user_message.md
index bf73ed899..096f71a3f 100644
--- a/prompts/default/fw.user_message.md
+++ b/prompts/default/fw.user_message.md
@@ -1,7 +1,7 @@
```json
{
- "user_message": {{message}},
"system_message": {{system_message}},
+ "user_message": {{message}},
"attachments": {{attachments}}
}
```
diff --git a/python/api/chat_remove.py b/python/api/chat_remove.py
index e137d6c48..a0b186e14 100644
--- a/python/api/chat_remove.py
+++ b/python/api/chat_remove.py
@@ -1,16 +1,28 @@
from python.helpers.api import ApiHandler, Input, Output, Request, Response
from agent import AgentContext
from python.helpers import persist_chat
+from python.helpers.task_scheduler import TaskScheduler
class RemoveChat(ApiHandler):
async def process(self, input: Input, request: Request) -> Output:
ctxid = input.get("context", "")
- # context instance - get or create
+ context = AgentContext.get(ctxid)
+ if context:
+ # stop processing any tasks
+ context.reset()
+
AgentContext.remove(ctxid)
persist_chat.remove_chat(ctxid)
+ scheduler = TaskScheduler.get()
+ await scheduler.reload()
+
+ tasks = scheduler.get_tasks_by_context_id(ctxid)
+ for task in tasks:
+ await scheduler.remove_task_by_uuid(task.uuid)
+
return {
"message": "Context removed.",
}
diff --git a/python/api/poll.py b/python/api/poll.py
index 7aefa0f37..4e9c1c411 100644
--- a/python/api/poll.py
+++ b/python/api/poll.py
@@ -1,5 +1,5 @@
import time
-
+from datetime import datetime
from python.helpers.api import ApiHandler
from flask import Request, Response
@@ -7,6 +7,8 @@ from agent import AgentContext
from python.helpers import persist_chat
from python.helpers.task_scheduler import TaskScheduler
+from python.helpers.localization import Localization
+from python.helpers.dotenv import get_dotenv_value
class Poll(ApiHandler):
@@ -15,6 +17,10 @@ class Poll(ApiHandler):
ctxid = input.get("context", None)
from_no = input.get("log_from", 0)
+ # Get timezone from input (default to dotenv default or UTC if not provided)
+ timezone = input.get("timezone", get_dotenv_value("DEFAULT_USER_TIMEZONE", "UTC"))
+ Localization.get().set_timezone(timezone)
+
# context instance - get or create
context = self.get_context(ctxid)
@@ -28,7 +34,7 @@ class Poll(ApiHandler):
# Always reload the scheduler on each poll to ensure we have the latest task state
await scheduler.reload()
- # loop AgentContext._contexts and number unnamed chats
+ # loop AgentContext._contexts and divide into contexts and tasks
ctxs = []
tasks = []
@@ -42,21 +48,15 @@ class Poll(ApiHandler):
continue
# Create the base context data that will be returned
- context_data = {
- "id": ctx.id,
- "name": ctx.name,
- "created_at": ctx.created_at,
- "no": ctx.no,
- "log_guid": ctx.log.guid,
- "log_version": len(ctx.log.updates),
- "log_length": len(ctx.log.logs),
- "paused": ctx.paused,
- }
-
- # Determine if this is a task by checking if a task with this UUID exists
- is_task = scheduler.get_task_by_uuid(ctx.id) is not None
-
- if not is_task:
+ context_data = ctx.serialize()
+
+ context_task = scheduler.get_task_by_uuid(ctx.id)
+ # Determine if this is a task-dedicated context by checking if a task with this UUID exists
+ is_task_context = (
+ context_task is not None and context_task.context_id == ctx.id
+ )
+
+ if not is_task_context:
ctxs.append(context_data)
else:
# If this is a task, get task details from the scheduler
@@ -65,6 +65,7 @@ class Poll(ApiHandler):
# Add task details to context_data with the same field names
# as used in scheduler endpoints to maintain UI compatibility
context_data.update({
+ "task_name": task_details.get("name"), # name is for context, task_name for the task name
"uuid": task_details.get("uuid"),
"state": task_details.get("state"),
"type": task_details.get("type"),
@@ -72,12 +73,15 @@ class Poll(ApiHandler):
"prompt": task_details.get("prompt"),
"last_run": task_details.get("last_run"),
"last_result": task_details.get("last_result"),
- "attachments": task_details.get("attachments", [])
+ "attachments": task_details.get("attachments", []),
+ "context_id": task_details.get("context_id"),
})
# Add type-specific fields
if task_details.get("type") == "scheduled":
context_data["schedule"] = task_details.get("schedule")
+ elif task_details.get("type") == "planned":
+ context_data["plan"] = task_details.get("plan")
else:
context_data["token"] = task_details.get("token")
diff --git a/python/api/scheduler_adhoc.py_ b/python/api/scheduler_adhoc.py_
deleted file mode 100644
index 136af9a31..000000000
--- a/python/api/scheduler_adhoc.py_
+++ /dev/null
@@ -1,5 +0,0 @@
-## JSON Body
-# api_key
-# task_id
-# params
-# callback
diff --git a/python/api/scheduler_task_create.py b/python/api/scheduler_task_create.py
index 5f657989f..385f858e6 100644
--- a/python/api/scheduler_task_create.py
+++ b/python/api/scheduler_task_create.py
@@ -1,8 +1,11 @@
from python.helpers.api import ApiHandler, Input, Output, Request
from python.helpers.task_scheduler import (
- TaskScheduler, ScheduledTask, AdHocTask, TaskSchedule,
- serialize_task, parse_task_schedule
+ TaskScheduler, ScheduledTask, AdHocTask, PlannedTask, TaskSchedule,
+ serialize_task, parse_task_schedule, parse_task_plan, TaskType
)
+from python.helpers.localization import Localization
+from python.helpers.print_style import PrintStyle
+import random
class SchedulerTaskCreate(ApiHandler):
@@ -10,6 +13,12 @@ class SchedulerTaskCreate(ApiHandler):
"""
Create a new task in the scheduler
"""
+ printer = PrintStyle(italic=True, font_color="blue", padding=False)
+
+ # Get timezone from input (do not set if not provided, we then rely on poll() to set it)
+ if timezone := input.get("timezone", None):
+ Localization.get().set_timezone(timezone)
+
scheduler = TaskScheduler.get()
await scheduler.reload()
@@ -18,11 +27,22 @@ class SchedulerTaskCreate(ApiHandler):
system_prompt = input.get("system_prompt")
prompt = input.get("prompt")
attachments = input.get("attachments", [])
+ context_id = input.get("context_id", None)
# Check if schedule is provided (for ScheduledTask)
schedule = input.get("schedule", {})
token: str = input.get("token", "")
+ # Debug log the token value
+ printer.print(f"Token received from frontend: '{token}' (type: {type(token)}, length: {len(token) if token else 0})")
+
+ # Generate a random token if empty or not provided
+ if not token:
+ token = str(random.randint(1000000000000000000, 9999999999999999999))
+ printer.print(f"Generated new token: '{token}'")
+
+ plan = input.get("plan", {})
+
# Validate required fields
if not name or not system_prompt or not prompt:
return {"error": "Missing required fields: name, system_prompt, prompt"}
@@ -55,24 +75,61 @@ class SchedulerTaskCreate(ApiHandler):
system_prompt=system_prompt,
prompt=prompt,
schedule=task_schedule,
- attachments=attachments
+ attachments=attachments,
+ context_id=context_id,
+ timezone=timezone
+ )
+ elif plan:
+ # Create a planned task
+ try:
+ # Use our standardized parsing function
+ task_plan = parse_task_plan(plan)
+ except ValueError as e:
+ return {"error": str(e)}
+
+ task = PlannedTask.create(
+ name=name,
+ system_prompt=system_prompt,
+ prompt=prompt,
+ plan=task_plan,
+ attachments=attachments,
+ context_id=context_id
)
else:
# Create an ad-hoc task
+ printer.print(f"Creating AdHocTask with token: '{token}'")
task = AdHocTask.create(
name=name,
system_prompt=system_prompt,
prompt=prompt,
token=token,
- attachments=attachments
+ attachments=attachments,
+ context_id=context_id
)
+ # Verify token after creation
+ if isinstance(task, AdHocTask):
+ printer.print(f"AdHocTask created with token: '{task.token}'")
# Add the task to the scheduler
await scheduler.add_task(task)
+ # Verify the task was added correctly - retrieve by UUID to check persistence
+ saved_task = scheduler.get_task_by_uuid(task.uuid)
+ if saved_task:
+ if saved_task.type == TaskType.AD_HOC and isinstance(saved_task, AdHocTask):
+ printer.print(f"Task verified after save, token: '{saved_task.token}'")
+ else:
+ printer.print("Task verified after save, not an adhoc task")
+ else:
+ printer.print("WARNING: Task not found after save!")
+
# Return the created task using our standardized serialization function
task_dict = serialize_task(task)
+ # Debug log the serialized task
+ if task_dict and task_dict.get('type') == 'adhoc':
+ printer.print(f"Serialized adhoc task, token in response: '{task_dict.get('token')}'")
+
return {
"task": task_dict
}
diff --git a/python/api/scheduler_task_delete.py b/python/api/scheduler_task_delete.py
index e526285aa..59e718799 100644
--- a/python/api/scheduler_task_delete.py
+++ b/python/api/scheduler_task_delete.py
@@ -1,5 +1,8 @@
from python.helpers.api import ApiHandler, Input, Output, Request
-from python.helpers.task_scheduler import TaskScheduler
+from python.helpers.task_scheduler import TaskScheduler, TaskState
+from python.helpers.localization import Localization
+from agent import AgentContext
+from python.helpers import persist_chat
class SchedulerTaskDelete(ApiHandler):
@@ -7,6 +10,10 @@ class SchedulerTaskDelete(ApiHandler):
"""
Delete a task from the scheduler by ID
"""
+ # Get timezone from input (do not set if not provided, we then rely on poll() to set it)
+ if timezone := input.get("timezone", None):
+ Localization.get().set_timezone(timezone)
+
scheduler = TaskScheduler.get()
await scheduler.reload()
@@ -21,6 +28,24 @@ class SchedulerTaskDelete(ApiHandler):
if not task:
return {"error": f"Task with ID {task_id} not found"}
+ context = None
+ if task.context_id:
+ context = self.get_context(task.context_id)
+
+ # If the task is running, update its state to IDLE first
+ if task.state == TaskState.RUNNING:
+ if context:
+ context.reset()
+ # Update the state to IDLE so any ongoing processes know to terminate
+ await scheduler.update_task(task_id, state=TaskState.IDLE)
+ # Force a save to ensure the state change is persisted
+ await scheduler.save()
+
+ # This is a dedicated context for the task, so we remove it
+ if context and context.id == task.uuid:
+ AgentContext.remove(context.id)
+ persist_chat.remove_chat(context.id)
+
# Remove the task
await scheduler.remove_task_by_uuid(task_id)
diff --git a/python/api/scheduler_task_run.py b/python/api/scheduler_task_run.py
index afd8f2c53..00c3dd8b4 100644
--- a/python/api/scheduler_task_run.py
+++ b/python/api/scheduler_task_run.py
@@ -1,6 +1,7 @@
from python.helpers.api import ApiHandler, Input, Output, Request
from python.helpers.task_scheduler import TaskScheduler, TaskState
from python.helpers.print_style import PrintStyle
+from python.helpers.localization import Localization
class SchedulerTaskRun(ApiHandler):
@@ -11,6 +12,9 @@ class SchedulerTaskRun(ApiHandler):
"""
Manually run a task from the scheduler by ID
"""
+ # Get timezone from input (do not set if not provided, we then rely on poll() to set it)
+ if timezone := input.get("timezone", None):
+ Localization.get().set_timezone(timezone)
# Get task ID from input
task_id: str = input.get("task_id", "")
diff --git a/python/api/scheduler_task_update.py b/python/api/scheduler_task_update.py
index ca73bd39f..433738652 100644
--- a/python/api/scheduler_task_update.py
+++ b/python/api/scheduler_task_update.py
@@ -1,8 +1,9 @@
from python.helpers.api import ApiHandler, Input, Output, Request
from python.helpers.task_scheduler import (
- TaskScheduler, ScheduledTask, AdHocTask, TaskState,
- serialize_task, parse_task_schedule
+ TaskScheduler, ScheduledTask, AdHocTask, PlannedTask, TaskState,
+ serialize_task, parse_task_schedule, parse_task_plan
)
+from python.helpers.localization import Localization
class SchedulerTaskUpdate(ApiHandler):
@@ -10,6 +11,10 @@ class SchedulerTaskUpdate(ApiHandler):
"""
Update an existing task in the scheduler
"""
+ # Get timezone from input (do not set if not provided, we then rely on poll() to set it)
+ if timezone := input.get("timezone", None):
+ Localization.get().set_timezone(timezone)
+
scheduler = TaskScheduler.get()
await scheduler.reload()
@@ -47,11 +52,28 @@ class SchedulerTaskUpdate(ApiHandler):
if isinstance(task, ScheduledTask) and "schedule" in input:
schedule_data = input.get("schedule", {})
try:
- update_params["schedule"] = parse_task_schedule(schedule_data)
+ # Parse the schedule with timezone handling
+ task_schedule = parse_task_schedule(schedule_data)
+
+ # Set the timezone from the request if not already in schedule_data
+ if not schedule_data.get('timezone', None) and timezone:
+ task_schedule.timezone = timezone
+
+ update_params["schedule"] = task_schedule
except ValueError as e:
return {"error": f"Invalid schedule format: {str(e)}"}
elif isinstance(task, AdHocTask) and "token" in input:
- update_params["token"] = input.get("token", "")
+ token_value = input.get("token", "")
+ if token_value: # Only update if non-empty
+ update_params["token"] = token_value
+ elif isinstance(task, PlannedTask) and "plan" in input:
+ plan_data = input.get("plan", {})
+ try:
+ # Parse the plan data
+ task_plan = parse_task_plan(plan_data)
+ update_params["plan"] = task_plan
+ except ValueError as e:
+ return {"error": f"Invalid plan format: {str(e)}"}
# Use atomic update method to apply changes
updated_task = await scheduler.update_task(task_id, **update_params)
diff --git a/python/api/scheduler_tasks_list.py b/python/api/scheduler_tasks_list.py
index 29fc154b2..30a8c3f06 100644
--- a/python/api/scheduler_tasks_list.py
+++ b/python/api/scheduler_tasks_list.py
@@ -2,6 +2,7 @@ from python.helpers.api import ApiHandler, Input, Output, Request
from python.helpers.task_scheduler import TaskScheduler
import traceback
from python.helpers.print_style import PrintStyle
+from python.helpers.localization import Localization
class SchedulerTasksList(ApiHandler):
@@ -10,6 +11,10 @@ class SchedulerTasksList(ApiHandler):
List all tasks in the scheduler with their types
"""
try:
+ # Get timezone from input (do not set if not provided, we then rely on poll() to set it)
+ if timezone := input.get("timezone", None):
+ Localization.get().set_timezone(timezone)
+
# Get task scheduler
scheduler = TaskScheduler.get()
await scheduler.reload()
diff --git a/python/api/scheduler_tick.py b/python/api/scheduler_tick.py
index 87bd9c568..3d7935f22 100644
--- a/python/api/scheduler_tick.py
+++ b/python/api/scheduler_tick.py
@@ -3,14 +3,19 @@ from datetime import datetime
from python.helpers.api import ApiHandler, Input, Output, Request
from python.helpers.print_style import PrintStyle
from python.helpers.task_scheduler import TaskScheduler
+from python.helpers.localization import Localization
class SchedulerTick(ApiHandler):
@classmethod
- def requires_loopback(cls):
+ def requires_loopback(cls) -> bool:
return True
async def process(self, input: Input, request: Request) -> Output:
+ # Get timezone from input (do not set if not provided, we then rely on poll() to set it)
+ if timezone := input.get("timezone", None):
+ Localization.get().set_timezone(timezone)
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
printer = PrintStyle(font_color="green", padding=False)
printer.print(f"Scheduler tick - API: {timestamp}")
diff --git a/python/extensions/message_loop_prompts/_60_include_current_datetime.py b/python/extensions/message_loop_prompts/_60_include_current_datetime.py
new file mode 100644
index 000000000..53a47951e
--- /dev/null
+++ b/python/extensions/message_loop_prompts/_60_include_current_datetime.py
@@ -0,0 +1,22 @@
+from datetime import datetime, timezone
+from python.helpers.extension import Extension
+from agent import LoopData
+from python.helpers.localization import Localization
+
+
+class IncludeCurrentDatetime(Extension):
+ async def execute(self, loop_data: LoopData = LoopData(), **kwargs):
+ # get current datetime
+ current_datetime = Localization.get().utc_dt_to_localtime_str(datetime.now(timezone.utc), sep=" ", timespec="seconds")
+ # remove timezone offset
+ current_datetime = current_datetime.split("+")[0]
+
+ # remove old current datetime from loop data
+ if "current_datetime" in loop_data.extras_temporary:
+ del loop_data.extras_temporary["current_datetime"]
+
+ # read prompt
+ datetime_prompt = self.agent.read_prompt("agent.system.datetime.md", date_time=current_datetime)
+
+ # add current datetime to the loop data
+ loop_data.extras_temporary["current_datetime"] = datetime_prompt
diff --git a/python/extensions/system_prompt/_10_system_prompt.py b/python/extensions/system_prompt/_10_system_prompt.py
index 68f7d6dd8..3a8a1d949 100644
--- a/python/extensions/system_prompt/_10_system_prompt.py
+++ b/python/extensions/system_prompt/_10_system_prompt.py
@@ -1,6 +1,7 @@
-from datetime import datetime
+from datetime import datetime, timezone
from python.helpers.extension import Extension
from agent import Agent, LoopData
+from python.helpers.localization import Localization
class SystemPrompt(Extension):
@@ -28,8 +29,12 @@ def get_prompt(file: str, agent: Agent):
# variables for system prompts
# TODO: move variables to the end of chain
# variables in system prompt would break prompt caching, better to add them to the last message in conversation
+ # get current datetime
+ current_datetime = Localization.get().utc_dt_to_localtime_str(datetime.now(timezone.utc), sep=" ", timespec="seconds")
+ # remove timezone offset
+ current_datetime = current_datetime.split("+")[0]
vars = {
- "date_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
+ "date_time": current_datetime,
"agent_name": agent.agent_name,
}
return agent.read_prompt(file, **vars)
diff --git a/python/helpers/api.py b/python/helpers/api.py
index 2d1cbfaa5..aee332591 100644
--- a/python/helpers/api.py
+++ b/python/helpers/api.py
@@ -12,7 +12,7 @@ from werkzeug.serving import make_server
Input = dict
-Output = Union[Dict[str, Any], Response, TypedDict]
+Output = Union[Dict[str, Any], Response, TypedDict] # type: ignore
class ApiHandler:
@@ -21,15 +21,15 @@ class ApiHandler:
self.thread_lock = thread_lock
@classmethod
- def requires_loopback(cls):
+ def requires_loopback(cls) -> bool:
return False
@classmethod
- def requires_api_key(cls):
+ def requires_api_key(cls) -> bool:
return False
@classmethod
- def requires_auth(cls):
+ def requires_auth(cls) -> bool:
return True
@abstractmethod
diff --git a/python/helpers/chat_names.py b/python/helpers/chat_names.py
deleted file mode 100644
index ef414cabf..000000000
--- a/python/helpers/chat_names.py
+++ /dev/null
@@ -1,137 +0,0 @@
-import json
-import os
-import time
-from typing import Dict, Any
-
-from python.helpers import files
-
-
-class ChatNames:
- _instance = None
- _names_file = "chat_names.json"
- _metadata_file = "chat_metadata.json"
-
- @classmethod
- def get_instance(cls):
- if cls._instance is None:
- cls._instance = ChatNames()
- cls._instance._names_file = files.get_abs_path("tmp") + "/" + cls._names_file
- cls._instance._metadata_file = files.get_abs_path("tmp") + "/" + cls._metadata_file
- return cls._instance
-
- def _read_names(self) -> dict:
- """Read current names from file"""
- try:
- if os.path.exists(self._names_file):
- with open(self._names_file, 'r') as f:
- return json.load(f)
- except Exception as e:
- print(f"Error reading chat names: {e}")
- return {}
-
- def _save_names(self, names: dict):
- """Save names to file"""
- try:
- with open(self._names_file, 'w') as f:
- json.dump(names, f, indent=2)
- except Exception as e:
- print(f"Error saving chat names: {e}")
-
- def _read_metadata(self) -> dict:
- """Read context metadata from file"""
- try:
- if os.path.exists(self._metadata_file):
- with open(self._metadata_file, 'r') as f:
- return json.load(f)
- except Exception as e:
- print(f"Error reading context metadata: {e}")
- return {}
-
- def _save_metadata(self, metadata: dict):
- """Save metadata to file"""
- try:
- with open(self._metadata_file, 'w') as f:
- json.dump(metadata, f, indent=2)
- except Exception as e:
- print(f"Error saving context metadata: {e}")
-
- def set_name(self, chat_id: str, name: str):
- """Set name for a chat/task"""
- names = self._read_names()
- names[chat_id] = name
- self._save_names(names)
-
- # Also update the name in metadata if it exists
- self.update_metadata(chat_id, {"name": name})
-
- def get_name(self, chat_id: str) -> str:
- """Get name for a chat/task"""
- names = self._read_names()
- return names.get(chat_id, f"Chat #{chat_id[:8]}")
-
- def set_metadata(self, chat_id: str, metadata_dict: Dict[str, Any]):
- """Set complete metadata for a chat/task"""
- all_metadata = self._read_metadata()
-
- # Ensure we have created_at timestamp if not provided
- if "created_at" not in metadata_dict:
- metadata_dict["created_at"] = int(time.time())
-
- all_metadata[chat_id] = metadata_dict
- self._save_metadata(all_metadata)
-
- # Also update the name in the names file for backward compatibility
- if "name" in metadata_dict:
- self.set_name(chat_id, metadata_dict["name"])
-
- def update_metadata(self, chat_id: str, metadata_update: Dict[str, Any]):
- """Update specific metadata fields for a chat/task"""
- all_metadata = self._read_metadata()
-
- if chat_id in all_metadata:
- all_metadata[chat_id].update(metadata_update)
- else:
- # Initialize with current timestamp if creating new metadata
- metadata_update["created_at"] = metadata_update.get("created_at", int(time.time()))
- all_metadata[chat_id] = metadata_update
-
- self._save_metadata(all_metadata)
-
- def get_metadata(self, chat_id: str) -> Dict[str, Any]:
- """Get metadata for a chat/task"""
- all_metadata = self._read_metadata()
-
- # Return metadata if it exists
- if chat_id in all_metadata:
- return all_metadata[chat_id]
-
- # Otherwise create default metadata with just the name
- name = self.get_name(chat_id)
- default_metadata = {
- "name": name,
- "created_at": int(time.time()) # Current time as fallback
- }
- return default_metadata
-
- def get_created_at(self, chat_id: str) -> int:
- """Get creation timestamp for a chat/task"""
- metadata = self.get_metadata(chat_id)
- return metadata.get("created_at", 0)
-
- def remove_chat(self, chat_id: str):
- """Remove chat/task and its metadata"""
- print("Removing chat name and metadata: ", chat_id)
-
- # Remove from names file
- names = self._read_names()
- if chat_id in names:
- del names[chat_id]
- print("Chat name removed: ", chat_id)
- self._save_names(names)
-
- # Remove from metadata file
- metadata = self._read_metadata()
- if chat_id in metadata:
- del metadata[chat_id]
- print("Chat metadata removed: ", chat_id)
- self._save_metadata(metadata)
diff --git a/python/helpers/localization.py b/python/helpers/localization.py
new file mode 100644
index 000000000..3356150d0
--- /dev/null
+++ b/python/helpers/localization.py
@@ -0,0 +1,123 @@
+from datetime import datetime
+import pytz # type: ignore
+
+from python.helpers.print_style import PrintStyle
+from python.helpers.dotenv import get_dotenv_value, save_dotenv_value
+
+
+class Localization:
+ """
+ Localization class for handling timezone conversions between UTC and local time.
+ """
+
+ # singleton
+ _instance = None
+
+ @classmethod
+ def get(cls, *args, **kwargs):
+ if cls._instance is None:
+ cls._instance = cls(*args, **kwargs)
+ return cls._instance
+
+ def __init__(self, timezone: str | None = None):
+ if timezone is not None:
+ self.set_timezone(timezone) # Use the setter to validate
+ else:
+ timezone = str(get_dotenv_value("DEFAULT_USER_TIMEZONE", "UTC"))
+ self.set_timezone(timezone)
+
+ def get_timezone(self) -> str:
+ return self.timezone
+
+ def set_timezone(self, timezone: str) -> None:
+ """Set the timezone, with validation."""
+ # Validate timezone
+ try:
+ pytz.timezone(timezone)
+ if timezone != getattr(self, 'timezone', None):
+ PrintStyle.debug(f"Changing timezone from {getattr(self, 'timezone', 'None')} to {timezone}")
+ self.timezone = timezone
+ save_dotenv_value("DEFAULT_USER_TIMEZONE", timezone)
+ except pytz.exceptions.UnknownTimeZoneError:
+ PrintStyle.error(f"Unknown timezone: {timezone}, defaulting to UTC")
+ self.timezone = "UTC"
+ # save the default timezone to the environment variable to avoid future errors on startup
+ save_dotenv_value("DEFAULT_USER_TIMEZONE", "UTC")
+
+ 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.
+ """
+ if not localtime_str:
+ return None
+
+ try:
+ # Handle both with and without timezone info
+ try:
+ # Try parsing with timezone info first
+ local_datetime_obj = datetime.fromisoformat(localtime_str)
+ if local_datetime_obj.tzinfo is None:
+ # If no timezone info, assume it's in the configured timezone
+ local_datetime_obj = pytz.timezone(self.timezone).localize(local_datetime_obj)
+ except ValueError:
+ # If timezone parsing fails, try without timezone
+ local_datetime_obj = datetime.fromisoformat(localtime_str.split('Z')[0].split('+')[0])
+ local_datetime_obj = pytz.timezone(self.timezone).localize(local_datetime_obj)
+
+ # Convert to UTC
+ return local_datetime_obj.astimezone(pytz.utc)
+ except Exception as e:
+ PrintStyle.error(f"Error converting localtime string to UTC: {e}")
+ return None
+
+ 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.
+ Returns None if input is None.
+ """
+ if utc_dt is None:
+ return None
+
+ # At this point, utc_dt is definitely not None
+ assert utc_dt is not None
+
+ try:
+ # Ensure datetime is timezone aware
+ if utc_dt.tzinfo is None:
+ utc_dt = pytz.utc.localize(utc_dt)
+ elif utc_dt.tzinfo != pytz.utc:
+ utc_dt = utc_dt.astimezone(pytz.utc)
+
+ # Convert to local time
+ local_datetime_obj = utc_dt.astimezone(pytz.timezone(self.timezone))
+ # Return the local time string
+ return local_datetime_obj.isoformat(sep=sep, timespec=timespec)
+ except Exception as e:
+ PrintStyle.error(f"Error converting UTC datetime to localtime string: {e}")
+ return None
+
+ def serialize_datetime(self, dt: datetime | None) -> str | None:
+ """
+ Serialize a datetime object to ISO format string in the user's timezone.
+ This ensures the frontend receives dates in the correct timezone for display.
+ """
+ if dt is None:
+ return None
+
+ # At this point, dt is definitely not None
+ assert dt is not None
+
+ try:
+ # Ensure datetime is timezone aware (if not, assume UTC)
+ if dt.tzinfo is None:
+ dt = pytz.utc.localize(dt)
+
+ # Convert to the user's timezone
+ local_timezone = pytz.timezone(self.timezone)
+ local_dt = dt.astimezone(local_timezone)
+
+ return local_dt.isoformat()
+ except Exception as e:
+ PrintStyle.error(f"Error serializing datetime: {e}")
+ return None
diff --git a/python/helpers/persist_chat.py b/python/helpers/persist_chat.py
index 4a9eed093..3c3356a34 100644
--- a/python/helpers/persist_chat.py
+++ b/python/helpers/persist_chat.py
@@ -1,4 +1,5 @@
from collections import OrderedDict
+from datetime import datetime
from typing import Any
import uuid
from agent import Agent, AgentConfig, AgentContext
@@ -104,6 +105,10 @@ def _serialize_context(context: AgentContext):
return {
"id": context.id,
"name": context.name,
+ "created_at": (
+ context.created_at.isoformat() if context.created_at
+ else datetime.fromtimestamp(0).isoformat()
+ ),
"agents": agents,
"streaming_agent": (
context.streaming_agent.number if context.streaming_agent else 0
@@ -143,6 +148,12 @@ def _deserialize_context(data):
config=config,
id=data.get("id", None), # get new id
name=data.get("name", None),
+ created_at=(
+ datetime.fromisoformat(
+ # older chats may not have created_at - backcompat
+ data.get("created_at", datetime.fromtimestamp(0).isoformat())
+ )
+ ),
log=log,
paused=False,
# agent0=agent0,
diff --git a/python/helpers/task_scheduler.py b/python/helpers/task_scheduler.py
index 6cde068d6..2139cae1f 100644
--- a/python/helpers/task_scheduler.py
+++ b/python/helpers/task_scheduler.py
@@ -1,15 +1,13 @@
import asyncio
from datetime import datetime, timezone, timedelta
-import json
import os
import random
import threading
from urllib.parse import urlparse
import uuid
-from dataclasses import dataclass
from enum import Enum
from os.path import exists
-from typing import Any, Callable, Coroutine, Dict, Literal, Optional, Type, TypeVar, Union, cast, ClassVar
+from typing import Any, Callable, Dict, Literal, Optional, Type, TypeVar, Union, cast, ClassVar
import nest_asyncio
nest_asyncio.apply()
@@ -17,22 +15,23 @@ nest_asyncio.apply()
from crontab import CronTab
from pydantic import BaseModel, Field, PrivateAttr
-from agent import Agent, AgentConfig, AgentContext, UserMessage
+from agent import Agent, AgentContext, UserMessage
from initialize import initialize
-from python.helpers.persist_chat import load_tmp_chats, save_tmp_chat
+from python.helpers.persist_chat import save_tmp_chat
from python.helpers.print_style import PrintStyle
from python.helpers.defer import DeferredTask
-from python.helpers.files import get_abs_path, list_files, make_dirs, read_file, write_file
-from python.helpers.persist_chat import load_tmp_chats, save_tmp_chat
-from python.helpers.print_style import PrintStyle
-
-SCHEDULER_FOLDER = "memory/scheduler"
+from python.helpers.files import get_abs_path, make_dirs, read_file, write_file
+from python.helpers.localization import Localization
+import pytz
+from typing import Annotated
+SCHEDULER_FOLDER = "tmp/scheduler"
# ----------------------
# Task Models
# ----------------------
+
class TaskState(str, Enum):
IDLE = "idle"
RUNNING = "running"
@@ -40,49 +39,100 @@ class TaskState(str, Enum):
ERROR = "error"
+class TaskType(str, Enum):
+ AD_HOC = "adhoc"
+ SCHEDULED = "scheduled"
+ PLANNED = "planned"
+
+
class TaskSchedule(BaseModel):
minute: str
hour: str
day: str
month: str
weekday: str
+ timezone: str = Field(default_factory=lambda: Localization.get().get_timezone())
def to_crontab(self) -> str:
return f"{self.minute} {self.hour} {self.day} {self.month} {self.weekday}"
-class AdHocTask(BaseModel):
+class TaskPlan(BaseModel):
+ todo: list[datetime] = Field(default_factory=list)
+ in_progress: datetime | None = None
+ done: list[datetime] = Field(default_factory=list)
+
+ @classmethod
+ def create(cls, todo: list[datetime] = list(), in_progress: datetime | None = None, done: list[datetime] = list()):
+ if todo:
+ for idx, dt in enumerate(todo):
+ if dt.tzinfo is None:
+ todo[idx] = pytz.timezone("UTC").localize(dt)
+ if in_progress:
+ if in_progress.tzinfo is None:
+ in_progress = pytz.timezone("UTC").localize(in_progress)
+ if done:
+ for idx, dt in enumerate(done):
+ if dt.tzinfo is None:
+ done[idx] = pytz.timezone("UTC").localize(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)
+ 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)
+ if launch_time not in self.todo:
+ raise ValueError(f"Launch time {launch_time} not in todo list")
+ self.todo.remove(launch_time)
+ self.todo = sorted(self.todo)
+ self.in_progress = launch_time
+
+ def set_done(self, launch_time: datetime):
+ if launch_time.tzinfo is None:
+ launch_time = pytz.timezone("UTC").localize(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:
+ raise ValueError(f"Launch time {launch_time} already in done list")
+ self.in_progress = None
+ self.done.append(launch_time)
+ self.done = sorted(self.done)
+
+ def get_next_launch_time(self) -> datetime | None:
+ return self.todo[0] if self.todo else None
+
+ def should_launch(self) -> datetime | None:
+ 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:
+ return next_launch_time
+ return None
+
+
+class BaseTask(BaseModel):
uuid: str = Field(default_factory=lambda: str(uuid.uuid4()))
+ context_id: Optional[str] = Field(default=None)
state: TaskState = Field(default=TaskState.IDLE)
name: str = Field()
system_prompt: str
prompt: str
attachments: list[str] = Field(default_factory=list)
- token: str = Field(default_factory=lambda: str(random.randint(1000000000000000000, 9999999999999999999)))
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
last_run: datetime | None = None
last_result: str | None = None
- # lock: Optional[threading.Lock] = Field(exclude=True, default=threading.Lock())
-
- @classmethod
- def create(
- cls,
- name: str,
- system_prompt: str,
- prompt: str,
- token: str,
- attachments: list[str] = list()
- ):
- return cls(name=name,
- system_prompt=system_prompt,
- prompt=prompt,
- attachments=attachments,
- token=token)
-
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ if not self.context_id:
+ self.context_id = self.uuid
self._lock = threading.RLock()
def update(self,
@@ -93,7 +143,8 @@ class AdHocTask(BaseModel):
attachments: list[str] | None = None,
last_run: datetime | None = None,
last_result: str | None = None,
- token: str | None = None):
+ context_id: str | None = None,
+ **kwargs):
with self._lock:
if name is not None:
self.name = name
@@ -116,29 +167,73 @@ class AdHocTask(BaseModel):
if last_result is not None:
self.last_result = last_result
self.updated_at = datetime.now(timezone.utc)
- if token is not None:
- self.token = token
+ if context_id is not None:
+ self.context_id = context_id
self.updated_at = datetime.now(timezone.utc)
+ for key, value in kwargs.items():
+ if value is not None:
+ setattr(self, key, value)
+ self.updated_at = datetime.now(timezone.utc)
def check_schedule(self, frequency_seconds: float = 60.0) -> bool:
- with self._lock:
- return False
+ return False
+ def get_next_run(self) -> datetime | None:
+ return None
-class ScheduledTask(BaseModel):
- uuid: str = Field(default_factory=lambda: str(uuid.uuid4()))
- state: TaskState = Field(default=TaskState.IDLE)
- name: str
- schedule: TaskSchedule
- system_prompt: str
- prompt: str
- attachments: list[str] = Field(default_factory=list)
- created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
- updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
- last_run: datetime | None = None
- last_result: str | None = None
+ def get_next_run_minutes(self) -> int | None:
+ next_run = self.get_next_run()
+ if next_run is None:
+ return None
+ return int((next_run - datetime.now(timezone.utc)).total_seconds() / 60)
+
+ async def on_run(self):
+ pass
+
+ async def on_finish(self):
+ # Ensure that updated_at is refreshed to reflect completion time
+ # This helps track when the task actually finished, regardless of success/error
+ await TaskScheduler.get().update_task(
+ self.uuid,
+ updated_at=datetime.now(timezone.utc)
+ )
+
+ async def on_error(self, error: str):
+ # Update task state to ERROR and set last result
+ scheduler = TaskScheduler.get()
+ await scheduler.reload() # Ensure we have the latest state
+ updated_task = await scheduler.update_task(
+ self.uuid,
+ state=TaskState.ERROR,
+ last_run=datetime.now(timezone.utc),
+ last_result=f"ERROR: {error}"
+ )
+ if not updated_task:
+ PrintStyle(italic=True, font_color="red", padding=False).print(
+ f"Failed to update task {self.uuid} state to ERROR after error: {error}"
+ )
+ await scheduler.save() # Force save after update
+
+ async def on_success(self, result: str):
+ # Update task state to IDLE and set last result
+ scheduler = TaskScheduler.get()
+ await scheduler.reload() # Ensure we have the latest state
+ updated_task = await scheduler.update_task(
+ self.uuid,
+ state=TaskState.IDLE,
+ last_run=datetime.now(timezone.utc),
+ last_result=result
+ )
+ if not updated_task:
+ PrintStyle(italic=True, font_color="red", padding=False).print(
+ f"Failed to update task {self.uuid} state to IDLE after success"
+ )
+ await scheduler.save() # Force save after update
- # lock: Optional[threading.Lock] = Field(exclude=True, default=threading.Lock())
+
+class AdHocTask(BaseTask):
+ type: Literal[TaskType.AD_HOC] = TaskType.AD_HOC
+ token: str = Field(default_factory=lambda: str(random.randint(1000000000000000000, 9999999999999999999)))
@classmethod
def create(
@@ -146,18 +241,67 @@ class ScheduledTask(BaseModel):
name: str,
system_prompt: str,
prompt: str,
- schedule: TaskSchedule,
- attachments: list[str] = []
+ token: str,
+ attachments: list[str] = list(),
+ context_id: str | None = None
):
return cls(name=name,
system_prompt=system_prompt,
prompt=prompt,
attachments=attachments,
- schedule=schedule)
+ token=token,
+ context_id=context_id)
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self._lock = threading.RLock()
+ def update(self,
+ name: str | None = None,
+ state: TaskState | None = None,
+ system_prompt: str | None = None,
+ prompt: str | None = None,
+ attachments: list[str] | None = None,
+ last_run: datetime | None = None,
+ last_result: str | None = None,
+ context_id: str | None = None,
+ token: str | None = None,
+ **kwargs):
+ super().update(name=name,
+ state=state,
+ system_prompt=system_prompt,
+ prompt=prompt,
+ attachments=attachments,
+ last_run=last_run,
+ last_result=last_result,
+ context_id=context_id,
+ token=token,
+ **kwargs)
+
+
+class ScheduledTask(BaseTask):
+ type: Literal[TaskType.SCHEDULED] = TaskType.SCHEDULED
+ schedule: TaskSchedule
+
+ @classmethod
+ def create(
+ cls,
+ name: str,
+ system_prompt: str,
+ prompt: str,
+ schedule: TaskSchedule,
+ attachments: list[str] = list(),
+ context_id: str | None = None,
+ timezone: str | None = None
+ ):
+ # Set timezone in schedule if provided
+ if timezone is not None:
+ schedule.timezone = timezone
+ else:
+ schedule.timezone = Localization.get().get_timezone()
+
+ return cls(name=name,
+ system_prompt=system_prompt,
+ prompt=prompt,
+ attachments=attachments,
+ schedule=schedule,
+ context_id=context_id)
def update(self,
name: str | None = None,
@@ -165,55 +309,140 @@ class ScheduledTask(BaseModel):
system_prompt: str | None = None,
prompt: str | None = None,
attachments: list[str] | None = None,
- schedule: TaskSchedule | None = None,
last_run: datetime | None = None,
- last_result: str | None = None):
- with self._lock:
- if name is not None:
- self.name = name
- self.updated_at = datetime.now(timezone.utc)
- if state is not None:
- self.state = state
- self.updated_at = datetime.now(timezone.utc)
- if system_prompt is not None:
- self.system_prompt = system_prompt
- self.updated_at = datetime.now(timezone.utc)
- if prompt is not None:
- self.prompt = prompt
- self.updated_at = datetime.now(timezone.utc)
- if attachments is not None:
- self.attachments = attachments
- self.updated_at = datetime.now(timezone.utc)
- if schedule is not None:
- self.schedule = schedule
- self.updated_at = datetime.now(timezone.utc)
- if last_run is not None:
- self.last_run = last_run
- self.updated_at = datetime.now(timezone.utc)
- if last_result is not None:
- self.last_result = last_result
- self.updated_at = datetime.now(timezone.utc)
+ last_result: str | None = None,
+ context_id: str | None = None,
+ schedule: TaskSchedule | None = None,
+ **kwargs):
+ super().update(name=name,
+ state=state,
+ system_prompt=system_prompt,
+ prompt=prompt,
+ attachments=attachments,
+ last_run=last_run,
+ last_result=last_result,
+ context_id=context_id,
+ schedule=schedule,
+ **kwargs)
def check_schedule(self, frequency_seconds: float = 60.0) -> bool:
with self._lock:
- crontab = CronTab(crontab=self.schedule.to_crontab())
+ crontab = CronTab(crontab=self.schedule.to_crontab()) # type: ignore
+
+ # Get the timezone from the schedule or use UTC as fallback
+ task_timezone = pytz.timezone(self.schedule.timezone or Localization.get().get_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)
+
# Get next run time as seconds until next execution
- # Set reference time to now - 1 minute to avoid off-by-one
- next_run_seconds: Optional[float] = crontab.next(
- now=datetime.now(timezone.utc) - timedelta(seconds=frequency_seconds),
+ next_run_seconds: Optional[float] = crontab.next( # type: ignore
+ now=reference_time,
return_datetime=False
) # type: ignore
+
if next_run_seconds is None:
return False
+
return next_run_seconds < frequency_seconds
- def run(self):
- pass
+ def get_next_run(self) -> datetime | None:
+ with self._lock:
+ crontab = CronTab(crontab=self.schedule.to_crontab()) # type: ignore
+ return crontab.next(now=datetime.now(timezone.utc), return_datetime=True) # type: ignore
-class SchedulerTaskList(BaseModel):
- tasks: list[Union[ScheduledTask, AdHocTask]]
+class PlannedTask(BaseTask):
+ type: Literal[TaskType.PLANNED] = TaskType.PLANNED
+ plan: TaskPlan
+
+ @classmethod
+ def create(
+ cls,
+ name: str,
+ system_prompt: str,
+ prompt: str,
+ plan: TaskPlan,
+ attachments: list[str] = list(),
+ context_id: str | None = None
+ ):
+ return cls(name=name,
+ system_prompt=system_prompt,
+ prompt=prompt,
+ plan=plan,
+ attachments=attachments,
+ context_id=context_id)
+
+ def update(self,
+ name: str | None = None,
+ state: TaskState | None = None,
+ system_prompt: str | None = None,
+ prompt: str | None = None,
+ attachments: list[str] | None = None,
+ last_run: datetime | None = None,
+ last_result: str | None = None,
+ context_id: str | None = None,
+ plan: TaskPlan | None = None,
+ **kwargs):
+ super().update(name=name,
+ state=state,
+ system_prompt=system_prompt,
+ prompt=prompt,
+ attachments=attachments,
+ last_run=last_run,
+ last_result=last_result,
+ context_id=context_id,
+ plan=plan,
+ **kwargs)
+
+ def check_schedule(self, frequency_seconds: float = 60.0) -> bool:
+ with self._lock:
+ return self.plan.should_launch() is not None
+
+ def get_next_run(self) -> datetime | None:
+ with self._lock:
+ return self.plan.get_next_launch_time()
+
+ async def on_run(self):
+ with self._lock:
+ # Get the next launch time and set it as in_progress
+ next_launch_time = self.plan.should_launch()
+ if next_launch_time is not None:
+ self.plan.set_in_progress(next_launch_time)
+ await super().on_run()
+
+ async def on_finish(self):
+ # Handle plan item progression regardless of success or error
+ plan_updated = False
+
+ with self._lock:
+ # If there's an in_progress time, mark it as done
+ if self.plan.in_progress is not None:
+ self.plan.set_done(self.plan.in_progress)
+ plan_updated = True
+ # If we updated the plan, make sure to persist it
+ if plan_updated:
+ scheduler = TaskScheduler.get()
+ await scheduler.reload()
+ await scheduler.update_task(self.uuid, plan=self.plan)
+ await scheduler.save() # Force save
+
+ # Call the parent implementation for any additional cleanup
+ await super().on_finish()
+
+ async def on_success(self, result: str):
+ # Call parent implementation to update state, etc.
+ await super().on_success(result)
+
+ async def on_error(self, error: str):
+ # Call parent implementation to update state, etc.
+ await super().on_error(error)
+
+
+class SchedulerTaskList(BaseModel):
+ tasks: list[Annotated[Union[ScheduledTask, AdHocTask, PlannedTask], Field(discriminator="type")]] = Field(default_factory=list)
# Singleton instance
__instance: ClassVar[Optional["SchedulerTaskList"]] = PrivateAttr(default=None)
@@ -245,7 +474,7 @@ class SchedulerTaskList(BaseModel):
self.tasks.extend(data.tasks)
return self
- async def add_task(self, task: Union[ScheduledTask, AdHocTask]) -> "SchedulerTaskList":
+ async def add_task(self, task: Union[ScheduledTask, AdHocTask, PlannedTask]) -> "SchedulerTaskList":
with self._lock:
self.tasks.append(task)
await self.save()
@@ -253,13 +482,50 @@ class SchedulerTaskList(BaseModel):
async def save(self) -> "SchedulerTaskList":
with self._lock:
+ # Debug: check for AdHocTasks with null tokens before saving
+ for task in self.tasks:
+ if isinstance(task, AdHocTask):
+ if task.token is None or task.token == "":
+ PrintStyle(italic=True, font_color="red", padding=False).print(
+ f"WARNING: AdHocTask {task.name} ({task.uuid}) has a null or empty token before saving: '{task.token}'"
+ )
+ # Generate a new token to prevent errors
+ task.token = str(random.randint(1000000000000000000, 9999999999999999999))
+ PrintStyle(italic=True, font_color="red", padding=False).print(
+ f"Fixed: Generated new token '{task.token}' for task {task.name}"
+ )
+
path = get_abs_path(SCHEDULER_FOLDER, "tasks.json")
if not exists(path):
make_dirs(path)
- write_file(path, self.model_dump_json())
+
+ # Get the JSON string before writing
+ json_data = self.model_dump_json()
+
+ # Debug: check if 'null' appears as token value in JSON
+ if '"type": "adhoc"' in json_data and '"token": null' in json_data:
+ PrintStyle(italic=True, font_color="red", padding=False).print(
+ "ERROR: Found null token in JSON output for an adhoc task"
+ )
+
+ write_file(path, json_data)
+
+ # Debug: Verify after saving
+ if exists(path):
+ loaded_json = read_file(path)
+ if '"type": "adhoc"' in loaded_json and '"token": null' in loaded_json:
+ PrintStyle(italic=True, font_color="red", padding=False).print(
+ "ERROR: Null token persisted in JSON file for an adhoc task"
+ )
+
return self
- async def update_task_by_uuid(self, task_uuid: str, updater_func) -> Union[ScheduledTask, AdHocTask] | None:
+ async def update_task_by_uuid(
+ self,
+ task_uuid: str,
+ updater_func: Callable[[Union[ScheduledTask, AdHocTask, PlannedTask]], None],
+ verify_func: Callable[[Union[ScheduledTask, AdHocTask, PlannedTask]], bool] = lambda task: True
+ ) -> Union[ScheduledTask, AdHocTask, PlannedTask] | None:
"""
Atomically update a task by UUID using the provided updater function.
@@ -273,7 +539,7 @@ class SchedulerTaskList(BaseModel):
await self.reload()
# Find the task
- task = next((task for task in self.tasks if task.uuid == task_uuid), None)
+ task = next((task for task in self.tasks if task.uuid == task_uuid and verify_func(task)), None)
if task is None:
return None
@@ -281,27 +547,35 @@ class SchedulerTaskList(BaseModel):
updater_func(task)
# Save the changes
- path = get_abs_path(SCHEDULER_FOLDER, "tasks.json")
- if not exists(path):
- make_dirs(path)
- write_file(path, self.model_dump_json())
+ await self.save()
return task
- def get_tasks(self) -> list[Union[ScheduledTask, AdHocTask]]:
+ def get_tasks(self) -> list[Union[ScheduledTask, AdHocTask, PlannedTask]]:
with self._lock:
return self.tasks
- async def get_due_tasks(self) -> list[Union[ScheduledTask, AdHocTask]]:
+ def get_tasks_by_context_id(self, context_id: str, only_running: bool = False) -> list[Union[ScheduledTask, AdHocTask, PlannedTask]]:
+ with self._lock:
+ return [
+ task for task in self.tasks
+ if task.context_id == context_id
+ and (not only_running or task.state == TaskState.RUNNING)
+ ]
+
+ async def get_due_tasks(self) -> list[Union[ScheduledTask, AdHocTask, PlannedTask]]:
with self._lock:
await self.reload()
- return [task for task in self.tasks if task.check_schedule() and task.state == TaskState.IDLE]
+ return [
+ task for task in self.tasks
+ if task.check_schedule() and task.state == TaskState.IDLE
+ ]
- def get_task_by_uuid(self, task_uuid: str) -> Union[ScheduledTask, AdHocTask] | None:
+ def get_task_by_uuid(self, task_uuid: str) -> Union[ScheduledTask, AdHocTask, PlannedTask] | None:
with self._lock:
return next((task for task in self.tasks if task.uuid == task_uuid), None)
- def get_task_by_name(self, name: str) -> Union[ScheduledTask, AdHocTask] | None:
+ def get_task_by_name(self, name: str) -> Union[ScheduledTask, AdHocTask, PlannedTask] | None:
with self._lock:
return next((task for task in self.tasks if task.name == name), None)
@@ -340,10 +614,13 @@ class TaskScheduler:
async def reload(self):
await self._tasks.reload()
- def get_tasks(self) -> list[Union[ScheduledTask, AdHocTask]]:
+ def get_tasks(self) -> list[Union[ScheduledTask, AdHocTask, PlannedTask]]:
return self._tasks.get_tasks()
- async def add_task(self, task: Union[ScheduledTask, AdHocTask]) -> "TaskScheduler":
+ def get_tasks_by_context_id(self, context_id: str, only_running: bool = False) -> list[Union[ScheduledTask, AdHocTask, PlannedTask]]:
+ return self._tasks.get_tasks_by_context_id(context_id, only_running)
+
+ async def add_task(self, task: Union[ScheduledTask, AdHocTask, PlannedTask]) -> "TaskScheduler":
await self._tasks.add_task(task)
return self
@@ -355,10 +632,10 @@ class TaskScheduler:
await self._tasks.remove_task_by_name(name)
return self
- def get_task_by_uuid(self, task_uuid: str) -> Union[ScheduledTask, AdHocTask] | None:
+ def get_task_by_uuid(self, task_uuid: str) -> Union[ScheduledTask, AdHocTask, PlannedTask] | None:
return self._tasks.get_task_by_uuid(task_uuid)
- def get_task_by_name(self, name: str) -> Union[ScheduledTask, AdHocTask] | None:
+ def get_task_by_name(self, name: str) -> Union[ScheduledTask, AdHocTask, PlannedTask] | None:
return self._tasks.get_task_by_name(name)
async def tick(self):
@@ -366,11 +643,33 @@ class TaskScheduler:
await self._run_task(task)
async def run_task_by_uuid(self, task_uuid: str):
- task = self._tasks.get_task_by_uuid(task_uuid)
- if task is None:
- raise ValueError(f"Task with UUID {task_uuid} not found")
+ # First reload tasks to ensure we have the latest state
+ await self._tasks.reload()
- # The actual state check and running will be handled in the _run_task method
+ # Get the task to run
+ task = self.get_task_by_uuid(task_uuid)
+ if not task:
+ raise ValueError(f"Task with UUID '{task_uuid}' not found")
+
+ # If the task is already running, raise an error
+ if task.state == TaskState.RUNNING:
+ raise ValueError(f"Task '{task.name}' is already running")
+
+ # If the task is disabled, raise an error
+ if task.state == TaskState.DISABLED:
+ raise ValueError(f"Task '{task.name}' is disabled")
+
+ # If the task is in error state, reset it to IDLE first
+ if task.state == TaskState.ERROR:
+ self._printer.print(f"Resetting task '{task.name}' from ERROR to IDLE state before running")
+ await self.update_task(task_uuid, state=TaskState.IDLE)
+ # Force a reload to ensure we have the updated state
+ await self._tasks.reload()
+ task = self.get_task_by_uuid(task_uuid)
+ if not task:
+ raise ValueError(f"Task with UUID '{task_uuid}' not found after state reset")
+
+ # Run the task
await self._run_task(task)
async def run_task_by_name(self, name: str):
@@ -382,7 +681,12 @@ class TaskScheduler:
async def save(self):
await self._tasks.save()
- async def update_task(self, task_uuid: str, **update_params) -> Union[ScheduledTask, AdHocTask] | None:
+ async def update_task_checked(
+ self,
+ task_uuid: str,
+ verify_func: Callable[[Union[ScheduledTask, AdHocTask, PlannedTask]], bool] = lambda task: True,
+ **update_params
+ ) -> Union[ScheduledTask, AdHocTask, PlannedTask] | None:
"""
Atomically update a task by UUID with the provided parameters.
This prevents race conditions when multiple processes update tasks concurrently.
@@ -392,49 +696,52 @@ class TaskScheduler:
def _update_task(task):
task.update(**update_params)
- return await self._tasks.update_task_by_uuid(task_uuid, _update_task)
+ return await self._tasks.update_task_by_uuid(task_uuid, _update_task, verify_func)
+
+ async def update_task(self, task_uuid: str, **update_params) -> Union[ScheduledTask, AdHocTask, PlannedTask] | None:
+ return await self.update_task_checked(task_uuid, lambda task: True, **update_params)
+
+ async def __new_context(self, task: Union[ScheduledTask, AdHocTask, PlannedTask]) -> AgentContext:
+ if not task.context_id:
+ raise ValueError(f"Task {task.name} has no context ID")
- async def __new_context(self, task: Union[ScheduledTask, AdHocTask]) -> AgentContext:
config = initialize()
context: AgentContext = AgentContext(config)
- context.id = task.uuid
+ context.id = task.context_id
+ # initial name before renaming is same as task name
+ context.name = task.name
+
# Save the context
save_tmp_chat(context)
return context
- async def _get_chat_context(self, task: Union[ScheduledTask, AdHocTask]) -> AgentContext:
- ctxids = load_tmp_chats()
+ async def _get_chat_context(self, task: Union[ScheduledTask, AdHocTask, PlannedTask]) -> AgentContext:
+ context = AgentContext.get(task.context_id) if task.context_id else None
- if task.uuid in ctxids:
- context = AgentContext.get(task.uuid)
- if isinstance(context, AgentContext):
- self._printer.print(
- f"Scheduler Task {task.name} loaded from task {task.uuid}, context ok"
- )
- context.id = task.uuid
- save_tmp_chat(context)
- return context
- else:
- self._printer.print(
- f"Scheduler Task {task.name} loaded from task {task.uuid} but failed to load context"
- )
- return await self.__new_context(task)
+ if context:
+ assert isinstance(context, AgentContext)
+ self._printer.print(
+ f"Scheduler Task {task.name} loaded from task {task.uuid}, context ok"
+ )
+ save_tmp_chat(context)
+ return context
else:
self._printer.print(
f"Scheduler Task {task.name} loaded from task {task.uuid} but context not found"
)
return await self.__new_context(task)
- async def _persist_chat(self, task: Union[ScheduledTask, AdHocTask], context: AgentContext):
- context.id = task.uuid
+ async def _persist_chat(self, task: Union[ScheduledTask, AdHocTask, PlannedTask], context: AgentContext):
+ if context.id != task.context_id:
+ raise ValueError(f"Context ID mismatch for task {task.name}: context {context.id} != task {task.context_id}")
save_tmp_chat(context)
- async def _run_task(self, task: Union[ScheduledTask, AdHocTask]):
+ async def _run_task(self, task: Union[ScheduledTask, AdHocTask, PlannedTask]):
async def _run_task_wrapper(task_uuid: str):
# preflight checks with a snapshot of the task
- task_snapshot: Union[ScheduledTask, AdHocTask] | None = self.get_task_by_uuid(task_uuid)
+ task_snapshot: Union[ScheduledTask, AdHocTask, PlannedTask] | None = self.get_task_by_uuid(task_uuid)
if task_snapshot is None:
self._printer.print(f"Scheduler Task with UUID '{task_uuid}' not found")
return
@@ -443,15 +750,20 @@ class TaskScheduler:
return
# Atomically fetch and check the task's current state
- current_task = await self.update_task(task_uuid, state=TaskState.RUNNING)
+ current_task = await self.update_task_checked(task_uuid, lambda task: task.state != TaskState.RUNNING, state=TaskState.RUNNING)
if not current_task:
- self._printer.print(f"Scheduler Task with UUID '{task_uuid}' not found")
+ self._printer.print(f"Scheduler Task with UUID '{task_uuid}' not found or updated by another process")
return
if current_task.state != TaskState.RUNNING:
# This means the update failed due to state conflict
self._printer.print(f"Scheduler Task '{current_task.name}' state is '{current_task.state}', skipping")
return
+ await current_task.on_run()
+
+ # the agent instance - init in try block
+ agent = None
+
try:
self._printer.print(f"Scheduler Task '{current_task.name}' started")
@@ -459,9 +771,9 @@ class TaskScheduler:
# Ensure the context is properly registered in the AgentContext._contexts
# This is critical for the polling mechanism to find and stream logs
+ # Dict operations are atomic
AgentContext._contexts[context.id] = context
-
- agent = Agent(0, context.config, context)
+ agent = context.streaming_agent or context.agent0
# Prepare attachment filenames for logging
attachment_filenames = []
@@ -507,34 +819,46 @@ class TaskScheduler:
result = await agent.monologue()
- # Atomically update task state after completion
- await self.update_task(
- task_uuid,
- state=TaskState.IDLE,
- last_run=datetime.now(timezone.utc),
- last_result="SUCCESS: " + result
- )
-
+ # Success
self._printer.print(f"Scheduler Task '{current_task.name}' completed: {result}")
-
await self._persist_chat(current_task, context)
+ await current_task.on_success(result)
+
+ # Explicitly verify task was updated in storage after success
+ await self._tasks.reload()
+ updated_task = self.get_task_by_uuid(task_uuid)
+ if updated_task and updated_task.state != TaskState.IDLE:
+ self._printer.print(f"Fixing task state consistency: '{current_task.name}' state is not IDLE after success")
+ await self.update_task(task_uuid, state=TaskState.IDLE)
except Exception as e:
+ # Error
self._printer.print(f"Scheduler Task '{current_task.name}' failed: {e}")
+ await current_task.on_error(str(e))
- # Atomically update task state on error
- await self.update_task(
- task_uuid,
- state=TaskState.ERROR,
- last_result=f"ERROR: {str(e)}"
- )
+ # Explicitly verify task was updated in storage after error
+ await self._tasks.reload()
+ updated_task = self.get_task_by_uuid(task_uuid)
+ if updated_task and updated_task.state != TaskState.ERROR:
+ self._printer.print(f"Fixing task state consistency: '{current_task.name}' state is not ERROR after failure")
+ await self.update_task(task_uuid, state=TaskState.ERROR)
if agent:
agent.handle_critical_exception(e)
+ finally:
+ # Call on_finish for task-specific cleanup
+ await current_task.on_finish()
+
+ # Make one final save to ensure all states are persisted
+ await self._tasks.save()
deferred_task = DeferredTask(thread_name=self.__class__.__name__)
deferred_task.start_task(_run_task_wrapper, task.uuid)
+ # Ensure background execution doesn't exit immediately on async await, especially in script contexts
+ # This helps prevent premature exits when running from non-event-loop contexts
+ asyncio.create_task(asyncio.sleep(0.1))
+
def serialize_all_tasks(self) -> list[Dict[str, Any]]:
"""
Serialize all tasks in the scheduler to a list of dictionaries.
@@ -558,18 +882,35 @@ class TaskScheduler:
# ----------------------
def serialize_datetime(dt: Optional[datetime]) -> Optional[str]:
- """Convert datetime to ISO format string or None if dt is None."""
- return dt.isoformat() if dt is not None else None
+ """
+ Serialize a datetime object to ISO format string in the user's timezone.
+
+ This uses the Localization singleton to convert the datetime to the user's timezone
+ before serializing it to an ISO format string for frontend display.
+
+ Returns None if the input is None.
+ """
+ # Use the Localization singleton for timezone conversion and serialization
+ return Localization.get().serialize_datetime(dt)
def parse_datetime(dt_str: Optional[str]) -> Optional[datetime]:
- """Parse ISO format datetime string with validation or return None if dt_str is None."""
+ """
+ Parse ISO format datetime string with timezone awareness.
+
+ This converts from the localized ISO format returned by serialize_datetime
+ back to a datetime object with proper timezone handling.
+
+ Returns None if dt_str is None.
+ """
if not dt_str:
return None
+
try:
- return datetime.fromisoformat(dt_str)
- except ValueError:
- raise ValueError(f"Invalid datetime format: {dt_str}. Expected ISO format.")
+ # Use the Localization singleton for consistent timezone handling
+ return Localization.get().localtime_str_to_utc_dt(dt_str)
+ except ValueError as e:
+ raise ValueError(f"Invalid datetime format: {dt_str}. Expected ISO format. Error: {e}")
def serialize_task_schedule(schedule: TaskSchedule) -> Dict[str, str]:
@@ -579,7 +920,8 @@ def serialize_task_schedule(schedule: TaskSchedule) -> Dict[str, str]:
'hour': schedule.hour,
'day': schedule.day,
'month': schedule.month,
- 'weekday': schedule.weekday
+ 'weekday': schedule.weekday,
+ 'timezone': schedule.timezone
}
@@ -591,16 +933,84 @@ def parse_task_schedule(schedule_data: Dict[str, str]) -> TaskSchedule:
hour=schedule_data.get('hour', '*'),
day=schedule_data.get('day', '*'),
month=schedule_data.get('month', '*'),
- weekday=schedule_data.get('weekday', '*')
+ weekday=schedule_data.get('weekday', '*'),
+ timezone=schedule_data.get('timezone', Localization.get().get_timezone())
)
except Exception as e:
raise ValueError(f"Invalid schedule format: {e}") from e
-T = TypeVar('T', bound=Union[ScheduledTask, AdHocTask])
+def serialize_task_plan(plan: TaskPlan) -> Dict[str, Any]:
+ """Convert TaskPlan to a standardized dictionary format."""
+ return {
+ 'todo': [serialize_datetime(dt) for dt in plan.todo],
+ 'in_progress': serialize_datetime(plan.in_progress) if plan.in_progress else None,
+ 'done': [serialize_datetime(dt) for dt in plan.done]
+ }
-def serialize_task(task: Union[ScheduledTask, AdHocTask]) -> Dict[str, Any]:
+def parse_task_plan(plan_data: Dict[str, Any]) -> TaskPlan:
+ """Parse dictionary into TaskPlan with validation."""
+ try:
+ # Handle case where plan_data might be None or empty
+ if not plan_data:
+ return TaskPlan(todo=[], in_progress=None, done=[])
+
+ # Parse todo items with careful validation
+ todo_dates = []
+ for dt_str in plan_data.get('todo', []):
+ if dt_str:
+ parsed_dt = parse_datetime(dt_str)
+ if parsed_dt:
+ # Ensure datetime is timezone-aware (use UTC if not specified)
+ if parsed_dt.tzinfo is None:
+ parsed_dt = parsed_dt.replace(tzinfo=timezone.utc)
+ todo_dates.append(parsed_dt)
+
+ # Parse in_progress with validation
+ in_progress = None
+ if plan_data.get('in_progress'):
+ in_progress = parse_datetime(plan_data.get('in_progress'))
+ # Ensure datetime is timezone-aware
+ if in_progress and in_progress.tzinfo is None:
+ in_progress = in_progress.replace(tzinfo=timezone.utc)
+
+ # Parse done items with validation
+ done_dates = []
+ for dt_str in plan_data.get('done', []):
+ if dt_str:
+ parsed_dt = parse_datetime(dt_str)
+ if parsed_dt:
+ # Ensure datetime is timezone-aware
+ if parsed_dt.tzinfo is None:
+ parsed_dt = parsed_dt.replace(tzinfo=timezone.utc)
+ done_dates.append(parsed_dt)
+
+ # Sort dates for better usability
+ todo_dates.sort()
+ done_dates.sort(reverse=True) # Most recent first for done items
+
+ # Cast to ensure type safety
+ todo_dates_cast: list[datetime] = cast(list[datetime], todo_dates)
+ done_dates_cast: list[datetime] = cast(list[datetime], done_dates)
+
+ return TaskPlan.create(
+ todo=todo_dates_cast,
+ in_progress=in_progress,
+ done=done_dates_cast
+ )
+ except Exception as e:
+ PrintStyle(italic=True, font_color="red", padding=False).print(
+ f"Error parsing task plan: {e}"
+ )
+ # Return empty plan instead of failing
+ return TaskPlan(todo=[], in_progress=None, done=[])
+
+
+T = TypeVar('T', bound=Union[ScheduledTask, AdHocTask, PlannedTask])
+
+
+def serialize_task(task: Union[ScheduledTask, AdHocTask, PlannedTask]) -> Dict[str, Any]:
"""
Standardized serialization for task objects with proper handling of all complex types.
"""
@@ -615,22 +1025,28 @@ def serialize_task(task: Union[ScheduledTask, AdHocTask]) -> Dict[str, Any]:
"created_at": serialize_datetime(task.created_at),
"updated_at": serialize_datetime(task.updated_at),
"last_run": serialize_datetime(task.last_run),
- "last_result": task.last_result
+ "next_run": serialize_datetime(task.get_next_run()),
+ "last_result": task.last_result,
+ "context_id": task.context_id
}
# Add type-specific fields
if isinstance(task, ScheduledTask):
task_dict['type'] = 'scheduled'
- task_dict['schedule'] = serialize_task_schedule(task.schedule)
- else:
+ task_dict['schedule'] = serialize_task_schedule(task.schedule) # type: ignore
+ elif isinstance(task, AdHocTask):
task_dict['type'] = 'adhoc'
adhoc_task = cast(AdHocTask, task)
task_dict['token'] = adhoc_task.token
+ else:
+ task_dict['type'] = 'planned'
+ planned_task = cast(PlannedTask, task)
+ task_dict['plan'] = serialize_task_plan(planned_task.plan) # type: ignore
return task_dict
-def serialize_tasks(tasks: list[Union[ScheduledTask, AdHocTask]]) -> list[Dict[str, Any]]:
+def serialize_tasks(tasks: list[Union[ScheduledTask, AdHocTask, PlannedTask]]) -> list[Dict[str, Any]]:
"""
Serialize a list of tasks to a list of dictionaries.
"""
@@ -651,10 +1067,18 @@ def deserialize_task(task_data: Dict[str, Any], task_class: Optional[Type[T]] =
determined_class = cast(Type[T], ScheduledTask)
elif task_type_str == 'adhoc':
determined_class = cast(Type[T], AdHocTask)
+ # Ensure token is a valid non-empty string
+ if not task_data.get('token'):
+ task_data['token'] = str(random.randint(1000000000000000000, 9999999999999999999))
+ elif task_type_str == 'planned':
+ determined_class = cast(Type[T], PlannedTask)
else:
raise ValueError(f"Unknown task type: {task_type_str}")
else:
determined_class = task_class
+ # If this is an AdHocTask, ensure token is valid
+ if determined_class == AdHocTask and not task_data.get('token'): # type: ignore
+ task_data['token'] = str(random.randint(1000000000000000000, 9999999999999999999))
common_args = {
"uuid": task_data.get("uuid"),
@@ -666,14 +1090,19 @@ def deserialize_task(task_data: Dict[str, Any], task_class: Optional[Type[T]] =
"created_at": parse_datetime(task_data.get("created_at")),
"updated_at": parse_datetime(task_data.get("updated_at")),
"last_run": parse_datetime(task_data.get("last_run")),
- "last_result": task_data.get("last_result")
+ "last_result": task_data.get("last_result"),
+ "context_id": task_data.get("context_id")
}
# Add type-specific fields
- if determined_class == ScheduledTask:
+ if determined_class == ScheduledTask: # type: ignore
schedule_data = task_data.get("schedule", {})
common_args["schedule"] = parse_task_schedule(schedule_data)
return ScheduledTask(**common_args) # type: ignore
- else:
+ elif determined_class == AdHocTask: # type: ignore
common_args["token"] = task_data.get("token", "")
return AdHocTask(**common_args) # type: ignore
+ else:
+ plan_data = task_data.get("plan", {})
+ common_args["plan"] = parse_task_plan(plan_data)
+ return PlannedTask(**common_args) # type: ignore
diff --git a/python/helpers/tool.py b/python/helpers/tool.py
index fef3058ac..d3c3c8714 100644
--- a/python/helpers/tool.py
+++ b/python/helpers/tool.py
@@ -12,9 +12,10 @@ class Response:
class Tool:
- def __init__(self, agent: Agent, name: str, args: dict[str,str], message: str, **kwargs) -> None:
+ def __init__(self, agent: Agent, name: str, method: str | None, args: dict[str,str], message: str, **kwargs) -> None:
self.agent = agent
self.name = name
+ self.method = method
self.args = args
self.message = message
@@ -39,7 +40,11 @@ class Tool:
self.log.update(content=response.message)
def get_log_object(self):
- return self.agent.context.log.log(type="tool", heading=f"{self.agent.agent_name}: Using tool '{self.name}'", content="", kvps=self.args)
+ if self.method:
+ heading = f"{self.agent.agent_name}: Using tool '{self.name}:{self.method}'"
+ else:
+ heading = f"{self.agent.agent_name}: Using tool '{self.name}'"
+ return self.agent.context.log.log(type="tool", heading=heading, content="", kvps=self.args)
def nice_key(self, key:str):
words = key.split('_')
diff --git a/python/tools/scheduler.py b/python/tools/scheduler.py
new file mode 100644
index 000000000..978b6e0aa
--- /dev/null
+++ b/python/tools/scheduler.py
@@ -0,0 +1,197 @@
+from datetime import datetime
+import json
+import random
+import re
+from python.helpers.tool import Tool, Response
+from python.helpers.task_scheduler import (
+ TaskScheduler, ScheduledTask, AdHocTask, PlannedTask, serialize_task, TaskState, TaskSchedule, TaskPlan, parse_datetime
+)
+from agent import AgentContext
+from python.helpers import persist_chat
+
+
+class SchedulerTool(Tool):
+
+ async def execute(self, **kwargs):
+ if self.method == "list_tasks":
+ return await self.list_tasks(**kwargs)
+ elif self.method == "show_task":
+ return await self.show_task(**kwargs)
+ elif self.method == "run_task":
+ return await self.run_task(**kwargs)
+ elif self.method == "delete_task":
+ return await self.delete_task(**kwargs)
+ elif self.method == "create_scheduled_task":
+ return await self.create_scheduled_task(**kwargs)
+ elif self.method == "create_adhoc_task":
+ return await self.create_adhoc_task(**kwargs)
+ elif self.method == "create_planned_task":
+ return await self.create_planned_task(**kwargs)
+ else:
+ return Response(message=f"Unknown method '{self.name}:{self.method}'", break_loop=False)
+
+ async def list_tasks(self, **kwargs) -> Response:
+ state_filter: list[str] | None = kwargs.get("state", None)
+ type_filter: list[str] | None = kwargs.get("type", None)
+ next_run_within_filter: int | None = kwargs.get("next_run_within", None)
+ next_run_after_filter: int | None = kwargs.get("next_run_after", None)
+
+ tasks: list[ScheduledTask | AdHocTask | PlannedTask] = TaskScheduler.get().get_tasks()
+ filtered_tasks = []
+ for task in tasks:
+ if state_filter and task.state not in state_filter:
+ continue
+ if type_filter and task.type not in type_filter:
+ continue
+ if next_run_within_filter and task.get_next_run_minutes() is not None and task.get_next_run_minutes() > next_run_within_filter: # type: ignore
+ continue
+ if next_run_after_filter and task.get_next_run_minutes() is not None and task.get_next_run_minutes() < next_run_after_filter: # type: ignore
+ continue
+ filtered_tasks.append(serialize_task(task))
+
+ return Response(message=json.dumps(filtered_tasks, indent=4), break_loop=False)
+
+ async def show_task(self, **kwargs) -> Response:
+ task_uuid: str = kwargs.get("uuid", None)
+ if not task_uuid:
+ return Response(message="Task UUID is required", break_loop=False)
+ task: ScheduledTask | AdHocTask | PlannedTask | None = TaskScheduler.get().get_task_by_uuid(task_uuid)
+ if not task:
+ return Response(message=f"Task not found: {task_uuid}", break_loop=False)
+ return Response(message=json.dumps(serialize_task(task), indent=4), break_loop=False)
+
+ async def run_task(self, **kwargs) -> Response:
+ task_uuid: str = kwargs.get("uuid", None)
+ if not task_uuid:
+ return Response(message="Task UUID is required", break_loop=False)
+ task: ScheduledTask | AdHocTask | PlannedTask | None = TaskScheduler.get().get_task_by_uuid(task_uuid)
+ if not task:
+ return Response(message=f"Task not found: {task_uuid}", break_loop=False)
+ await TaskScheduler.get().run_task_by_uuid(task_uuid)
+ return Response(message=f"Task started: {task_uuid}", break_loop=False)
+
+ async def delete_task(self, **kwargs) -> Response:
+ task_uuid: str = kwargs.get("uuid", None)
+ if not task_uuid:
+ return Response(message="Task UUID is required", break_loop=False)
+
+ task: ScheduledTask | AdHocTask | PlannedTask | None = TaskScheduler.get().get_task_by_uuid(task_uuid)
+ if not task:
+ return Response(message=f"Task not found: {task_uuid}", break_loop=False)
+
+ context = None
+ if task.context_id:
+ context = AgentContext.get(task.context_id)
+
+ if task.state == TaskState.RUNNING:
+ if context:
+ context.reset()
+ await TaskScheduler.get().update_task(task_uuid, state=TaskState.IDLE)
+ await TaskScheduler.get().save()
+
+ if context and context.id == task.uuid:
+ AgentContext.remove(context.id)
+ persist_chat.remove_chat(context.id)
+
+ await TaskScheduler.get().remove_task_by_uuid(task_uuid)
+ if TaskScheduler.get().get_task_by_uuid(task_uuid) is None:
+ return Response(message=f"Task deleted: {task_uuid}", break_loop=False)
+ else:
+ return Response(message=f"Task failed to delete: {task_uuid}", break_loop=False)
+
+ async def create_scheduled_task(self, **kwargs) -> Response:
+ # "name": "XXX",
+ # "system_prompt": "You are a software developer",
+ # "prompt": "Send the user an email with a greeting using python and smtp. The user's address is: [email protected]",
+ # "attachments": [],
+ # "schedule": {
+ # "minute": "*/20",
+ # "hour": "*",
+ # "day": "*",
+ # "month": "*",
+ # "weekday": "*",
+ # }
+ name: str = kwargs.get("name", None)
+ system_prompt: str = kwargs.get("system_prompt", None)
+ prompt: str = kwargs.get("prompt", None)
+ attachments: list[str] = kwargs.get("attachments", [])
+ schedule: dict[str, str] = kwargs.get("schedule", {})
+ dedicated_context: bool = kwargs.get("dedicated_context", False)
+
+ task_schedule = TaskSchedule(
+ minute=schedule.get("minute", "*"),
+ hour=schedule.get("hour", "*"),
+ day=schedule.get("day", "*"),
+ month=schedule.get("month", "*"),
+ weekday=schedule.get("weekday", "*"),
+ )
+
+ # Validate cron expression, agent might hallucinate
+ cron_regex = "^((((\d+,)+\d+|(\d+(\/|-|#)\d+)|\d+L?|\*(\/\d+)?|L(-\d+)?|\?|[A-Z]{3}(-[A-Z]{3})?) ?){5,7})$"
+ if not re.match(cron_regex, task_schedule.to_crontab()):
+ return Response(message="Invalid cron expression: " + task_schedule.to_crontab(), break_loop=False)
+
+ task = ScheduledTask.create(
+ name=name,
+ system_prompt=system_prompt,
+ prompt=prompt,
+ attachments=attachments,
+ schedule=task_schedule,
+ context_id=None if dedicated_context else self.agent.context.id
+ )
+ await TaskScheduler.get().add_task(task)
+ return Response(message=f"Scheduled task '{name}' created: {task.uuid}", break_loop=False)
+
+ async def create_adhoc_task(self, **kwargs) -> Response:
+ name: str = kwargs.get("name", None)
+ system_prompt: str = kwargs.get("system_prompt", None)
+ prompt: str = kwargs.get("prompt", None)
+ attachments: list[str] = kwargs.get("attachments", [])
+ token: str = str(random.randint(1000000000000000000, 9999999999999999999))
+ dedicated_context: bool = kwargs.get("dedicated_context", False)
+
+ task = AdHocTask.create(
+ name=name,
+ system_prompt=system_prompt,
+ prompt=prompt,
+ attachments=attachments,
+ token=token,
+ context_id=None if dedicated_context else self.agent.context.id
+ )
+ await TaskScheduler.get().add_task(task)
+ return Response(message=f"Adhoc task '{name}' created: {task.uuid}", break_loop=False)
+
+ async def create_planned_task(self, **kwargs) -> Response: # TODO: Implement
+ name: str = kwargs.get("name", None)
+ system_prompt: str = kwargs.get("system_prompt", None)
+ prompt: str = kwargs.get("prompt", None)
+ attachments: list[str] = kwargs.get("attachments", [])
+ plan: list[str] = kwargs.get("plan", [])
+ dedicated_context: bool = kwargs.get("dedicated_context", False)
+
+ # Convert plan to list of datetimes in UTC
+ todo: list[datetime] = []
+ for item in plan:
+ dt = parse_datetime(item)
+ if dt is None:
+ return Response(message=f"Invalid datetime: {item}", break_loop=False)
+ todo.append(dt)
+
+ # Create task plan with todo list
+ task_plan = TaskPlan.create(
+ todo=todo,
+ in_progress=None,
+ done=[]
+ )
+
+ # Create planned task with task plan
+ task = PlannedTask.create(
+ name=name,
+ system_prompt=system_prompt,
+ prompt=prompt,
+ attachments=attachments,
+ plan=task_plan,
+ context_id=None if dedicated_context else self.agent.context.id
+ )
+ await TaskScheduler.get().add_task(task)
+ return Response(message=f"Planned task '{name}' created: {task.uuid}", break_loop=False)
diff --git a/run_ui.py b/run_ui.py
index 0aecbeec6..6e8427b1c 100644
--- a/run_ui.py
+++ b/run_ui.py
@@ -1,3 +1,9 @@
+import os
+import sys
+import time
+import socket
+import struct
+import asyncio
from functools import wraps
import threading
import signal
@@ -10,10 +16,12 @@ from python.helpers.cloudflare_tunnel import CloudflareTunnel
from python.helpers.extract_tools import load_classes_from_folder
from python.helpers.api import ApiHandler
from python.helpers.print_style import PrintStyle
-import sys
-import socket
-import struct
+from python.helpers.task_scheduler import TaskScheduler
+# Set the new timezone to 'UTC'
+os.environ['TZ'] = 'UTC'
+# Apply the timezone change
+time.tzset()
# initialize the internal Flask server
app = Flask("app", static_folder=get_abs_path("./webui"), static_url_path="/")
@@ -166,6 +174,9 @@ def run():
# initialize contexts from persisted chats
persist_chat.load_tmp_chats()
+ # reload scheduler
+ scheduler = TaskScheduler.get()
+ asyncio.run(scheduler.reload())
except Exception as e:
PrintStyle().error(errors.format_error(e))
diff --git a/webui/css/scheduler-datepicker.css b/webui/css/scheduler-datepicker.css
new file mode 100644
index 000000000..c0686f490
--- /dev/null
+++ b/webui/css/scheduler-datepicker.css
@@ -0,0 +1,127 @@
+/* Flatpickr Customization for Scheduler */
+
+/* Custom styling wrapper */
+.scheduler-flatpickr-wrapper {
+ position: relative;
+ width: 100%;
+ overflow: visible !important; /* Ensure dropdown can escape container */
+}
+
+/* Input styling */
+.scheduler-flatpickr-input {
+ width: 100%;
+ padding: 8px 12px;
+ border: 1px solid var(--color-border, #ccc);
+ border-radius: 4px;
+ background-color: var(--color-input, #fff);
+ color: var(--color-text, #333);
+ font-size: 14px;
+ cursor: pointer;
+}
+
+/* Calendar container customization */
+.flatpickr-calendar.scheduler-theme {
+ background: var(--color-panel, #fff);
+ border: 1px solid var(--color-border, #ccc);
+ border-radius: 4px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
+ color: var(--color-text, #333);
+ font-size: 14px;
+ max-width: 320px;
+ padding: 0;
+ z-index: 9999 !important; /* Ensure it's above other elements */
+ position: absolute !important;
+ visibility: visible !important;
+ opacity: 1 !important;
+}
+
+/* Month navigation */
+.flatpickr-calendar.scheduler-theme .flatpickr-months {
+ background-color: var(--color-primary, #4a90e2);
+ border-radius: 4px 4px 0 0;
+ color: var(--color-text, #333);
+ padding: 8px 0;
+}
+
+.flatpickr-calendar.scheduler-theme .flatpickr-prev-month,
+.flatpickr-calendar.scheduler-theme .flatpickr-next-month {
+ color: var(--color-text, #333);
+}
+
+.flatpickr-calendar.scheduler-theme .flatpickr-prev-month:hover,
+.flatpickr-calendar.scheduler-theme .flatpickr-next-month:hover {
+ color: var(--color-text, #333);
+}
+
+/* Days of week */
+.flatpickr-calendar.scheduler-theme .flatpickr-weekdays {
+ background-color: var(--color-panel, #fff);
+ border-bottom: 1px solid var(--color-border, #eee);
+}
+
+.flatpickr-calendar.scheduler-theme .flatpickr-weekday {
+ color: var(--color-text, #333);
+ font-weight: bold;
+}
+
+/* Day cells */
+.flatpickr-calendar.scheduler-theme .flatpickr-day {
+ border-radius: 4px;
+ color: var(--color-text, #333);
+ transition: background-color 0.2s, color 0.2s;
+}
+
+.flatpickr-calendar.scheduler-theme .flatpickr-day:hover {
+ background-color: var(--color-panel, #f0f0f0);
+}
+
+.flatpickr-calendar.scheduler-theme .flatpickr-day.selected {
+ background-color: var(--color-primary, #4a90e2);
+ border-color: var(--color-border, #ccc);
+ color: var(--color-text, #333);
+}
+
+.flatpickr-calendar.scheduler-theme .flatpickr-day.today {
+ border-color: var(--color-border, #ccc);
+ color: var(--color-text, #333);
+}
+
+/* Time picker */
+.flatpickr-calendar.scheduler-theme .flatpickr-time {
+ border-top: 1px solid var(--color-border, #eee);
+ background-color: var(--color-panel, #fff);
+}
+
+.flatpickr-calendar.scheduler-theme .numInputWrapper span {
+ border-color: var(--color-border, #eee);
+}
+
+.flatpickr-calendar.scheduler-theme .numInputWrapper span:hover {
+ background-color: var(--color-panel, #f0f0f0);
+}
+
+.flatpickr-calendar.scheduler-theme input.flatpickr-hour,
+.flatpickr-calendar.scheduler-theme input.flatpickr-minute,
+.flatpickr-calendar.scheduler-theme input.flatpickr-second {
+ color: var(--color-text, #333);
+ background-color: transparent;
+}
+
+/* Clear button in the input field */
+.scheduler-flatpickr-clear {
+ position: absolute;
+ right: 8px;
+ top: 50%;
+ transform: translateY(-50%);
+ cursor: pointer;
+ padding: 4px;
+ display: none;
+ color: var(--color-text-light, #999);
+ background: transparent;
+ border: none;
+ z-index: 1;
+}
+
+.scheduler-flatpickr-wrapper:hover .scheduler-flatpickr-clear {
+ display: block;
+}
diff --git a/webui/css/settings.css b/webui/css/settings.css
index f2aab3182..76f69b533 100644
--- a/webui/css/settings.css
+++ b/webui/css/settings.css
@@ -145,7 +145,7 @@ select {
}
select:disabled {
- background-color: #f5f5f5;
+ background-color: var(--color-background);
cursor: not-allowed;
}
@@ -324,16 +324,15 @@ nav ul li a img {
.settings-tab:not(.active) {
opacity: 0.8;
border-bottom: 3px solid var(--color-border);
- background-color: rgba(255, 255, 255, 0.03);
+ background-color: var(--color-background);
}
.settings-tab.active {
- color: var(--color-border);
border-color: var(--color-border);
box-shadow:
- 0 -4px 8px -2px var(--color-border) 0.5,
- 4px 0 8px -2px var(--color-border) 0.5,
- -4px 0 8px -2px var(--color-border) 0.5;
+ 0 -4px 8px -2px var(--color-border),
+ 4px 0 8px -2px var(--color-border),
+ -4px 0 8px -2px var(--color-border);
font-weight: bold;
background-color: var(--color-panel);
}
@@ -342,9 +341,9 @@ nav ul li a img {
.light-mode .settings-tab.active {
color: var(--color-border);
box-shadow:
- 0 -4px 8px -2px var(--color-border) 0.5,
- 4px 0 8px -2px var(--color-border) 0.5,
- -4px 0 8px -2px var(--color-border) 0.5;
+ 0 -4px 8px -2px var(--color-border),
+ 4px 0 8px -2px var(--color-border),
+ -4px 0 8px -2px var(--color-border);
}
.light-mode .settings-tab:not(.active) {
@@ -798,3 +797,155 @@ nav ul li a img {
.light-mode .scheduler-state-explanation span {
background-color: rgba(255, 255, 255, 0.3);
}
+
+/* Schedule Builder (for scheduled tasks) */
+.scheduler-schedule-builder {
+ display: grid;
+ grid-template-columns: repeat(5, 1fr);
+ gap: 10px;
+ width: 100%;
+ margin-bottom: 10px;
+}
+
+.scheduler-schedule-field {
+ display: flex;
+ flex-direction: column;
+}
+
+.scheduler-schedule-label {
+ font-size: 0.8rem;
+ margin-bottom: 5px;
+ color: var(--color-text);
+ opacity: 0.8;
+}
+
+/* Plan Builder (for planned tasks) */
+.scheduler-plan-builder {
+ width: 100%;
+ margin-bottom: 10px;
+ border: 1px solid var(--color-border);
+ border-radius: 8px;
+ padding: 10px;
+ background-color: rgba(0, 0, 0, 0.2);
+}
+
+.scheduler-plan-todo {
+ display: flex;
+ flex-direction: column;
+}
+
+.scheduler-plan-label {
+ font-size: 0.9rem;
+ margin-bottom: 10px;
+ color: var(--color-text);
+ font-weight: bold;
+}
+
+.scheduler-todo-list {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ margin-top: 8px;
+ max-height: 200px;
+ overflow-y: auto;
+}
+
+.scheduler-todo-item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ background-color: var(--color-background);
+ border-radius: 6px;
+ padding: 8px 12px;
+ border: 1px solid var(--color-border);
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
+}
+
+.scheduler-todo-item span {
+ flex: 1;
+ font-size: 14px;
+}
+
+.scheduler-add-todo {
+ margin-top: 12px;
+ display: flex;
+ gap: 8px;
+ align-items: center;
+}
+
+.scheduler-add-todo input[type="datetime-local"] {
+ flex: 1;
+ min-width: 0;
+ padding: 8px 12px;
+ border-radius: 6px;
+ border: 1px solid var(--color-border);
+ background-color: var(--color-background);
+ color: var(--color-text);
+}
+
+.scheduler-add-todo-button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background-color: var(--color-accent);
+ color: white;
+ border: none;
+ border-radius: 6px;
+ padding: 8px 12px;
+ cursor: pointer;
+ transition: background-color 0.2s ease;
+ font-weight: 500;
+}
+
+.scheduler-add-todo-button:hover {
+ background-color: var(--color-accent-dark);
+}
+
+.scheduler-todo-remove {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background-color: transparent;
+ color: var(--color-text);
+ border: none;
+ border-radius: 4px;
+ width: 24px;
+ height: 24px;
+ cursor: pointer;
+ transition: background-color 0.2s ease;
+ margin-left: 8px;
+}
+
+.scheduler-todo-remove:hover {
+ background-color: var(--color-accent-light);
+ color: var(--color-accent-dark);
+}
+
+.light-mode .scheduler-todo-item {
+ background-color: var(--color-background-light);
+ border-color: var(--color-border-light);
+}
+
+.light-mode .scheduler-todo-remove:hover {
+ background-color: #e0e0e0;
+ color: #d32f2f;
+}
+
+.scheduler-empty-plan {
+ padding: 12px;
+ color: var(--color-text-muted);
+ font-style: italic;
+ text-align: center;
+ border: 1px dashed var(--color-border);
+ border-radius: 6px;
+ margin-top: 8px;
+}
+
+/* Responsive design for plan builder */
+@media (max-width: 768px) {
+ .scheduler-add-todo {
+ flex-direction: column;
+ }
+}
+
+/* Token field (for ad-hoc tasks) */
diff --git a/webui/index.css b/webui/index.css
index 7719fc601..e812ec14f 100644
--- a/webui/index.css
+++ b/webui/index.css
@@ -2243,37 +2243,6 @@ a:active {
margin-left: 5px;
}
-.task-detail-button {
- background: transparent;
- border: 1px solid rgba(255, 255, 255, 0.2);
- color: #999;
- cursor: pointer;
- padding: 5px;
- margin-left: auto;
- border-radius: 4px;
- display: flex;
- align-items: center;
- justify-content: center;
- transition: all 0.2s ease;
-}
-
-.task-detail-button:hover {
- color: #fff;
- background-color: rgba(255, 255, 255, 0.15);
- border-color: rgba(255, 255, 255, 0.3);
-}
-
-.light-mode .task-detail-button {
- color: #666;
- border: 1px solid rgba(0, 0, 0, 0.1);
-}
-
-.light-mode .task-detail-button:hover {
- color: #222;
- background-color: rgba(0, 0, 0, 0.08);
- border-color: rgba(0, 0, 0, 0.2);
-}
-
.task-name:hover {
background-color: rgba(255, 255, 255, 0.1);
text-decoration: none;
@@ -2330,7 +2299,6 @@ a:active {
}
.tab.active {
- color: var(--color-primary);
border-color: var(--color-border);
box-shadow:
0 -4px 8px -2px var(--color-border),
@@ -2341,7 +2309,6 @@ a:active {
}
.light-mode .tab.active {
- color: var(--color-primary);
box-shadow:
0 -4px 8px -2px var(--color-border),
4px 0 8px -2px var(--color-border),
@@ -2509,40 +2476,6 @@ a:active {
overflow: auto;
}
-/* Settings Tabs */
-.settings-tabs {
- display: flex;
- border-bottom: 1px solid var(--color-border);
- margin-bottom: 24px;
- gap: 8px;
- overflow-x: auto;
- scrollbar-width: none;
- -ms-overflow-style: none;
-}
-
-.settings-tabs::-webkit-scrollbar {
- display: none;
-}
-
-.settings-tab {
- padding: 8px 16px;
- cursor: pointer;
- border-bottom: 3px solid transparent;
- color: var(--color-text-secondary);
- transition: all 0.2s ease;
- white-space: nowrap;
-}
-
-.settings-tab:hover {
- color: var(--color-text);
-}
-
-.settings-tab.active {
- border-bottom-color: var(--color-primary);
- color: var(--color-primary);
- font-weight: 500;
-}
-
/* Settings Sections */
nav ul {
display: grid;
diff --git a/webui/index.html b/webui/index.html
index 2a380c602..f166aabad 100644
--- a/webui/index.html
+++ b/webui/index.html
@@ -13,6 +13,11 @@
<link rel="stylesheet" href="css/modals.css">
<link rel="stylesheet" href="css/speech.css">
<link rel="stylesheet" href="css/history.css">
+ <link rel="stylesheet" href="css/scheduler-datepicker.css">
+
+ <!-- Flatpickr for datetime picker -->
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
+ <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
window.safeCall = function (name, ...args) {
@@ -20,6 +25,80 @@
}
</script>
+ <!-- Pre-initialize schedulerSettings to ensure Alpine doesn't miss it -->
+ <script>
+ // Pre-define schedulerSettings skeleton to ensure it's available to Alpine
+ window.schedulerSettings = function() {
+ return {
+ tasks: [],
+ isLoading: true,
+ selectedTask: null,
+ expandedTaskId: null,
+ sortField: 'name',
+ sortDirection: 'asc',
+ filterType: 'all',
+ filterState: 'all',
+ pollingInterval: null,
+ pollingActive: false,
+ editingTask: {
+ name: '',
+ type: 'scheduled',
+ state: 'idle',
+ schedule: {
+ minute: '*',
+ hour: '*',
+ day: '*',
+ month: '*',
+ weekday: '*',
+ timezone: ''
+ },
+ token: '',
+ plan: {
+ todo: [],
+ in_progress: null,
+ done: []
+ },
+ system_prompt: '',
+ prompt: '',
+ attachments: []
+ },
+ isCreating: false,
+ isEditing: false,
+ showLoadingState: false,
+ viewMode: 'list',
+ selectedTaskForDetail: null,
+ attachmentsText: '',
+ filteredTasks: [],
+ // Minimal init to avoid errors
+ init() {
+ console.log('Basic schedulerSettings initialized');
+ // Watch for task type changes
+ this.$watch('editingTask.type', (newType) => {
+ if (newType === 'planned') {
+ // When switching to planned task type, initialize the datetime picker
+ this.$nextTick(() => {
+ if (this.initFlatpickr) {
+ if (this.isCreating) {
+ this.initFlatpickr('create');
+ } else if (this.isEditing) {
+ this.initFlatpickr('edit');
+ }
+ }
+ });
+ }
+ });
+ }
+ };
+ };
+ </script>
+
+ <!-- Load module scripts first -->
+ <script type="module" src="js/scheduler.js"></script>
+ <script type="module" src="js/speech.js"></script>
+ <script type="module" src="js/history.js"></script>
+ <script type="module" src="index.js"></script>
+
+ <!-- Then load Alpine.js -->
<script defer src="https://cdn.jsdelivr.net/npm/@alpinejs/[email protected]/dist/cdn.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
@@ -33,15 +112,10 @@
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js"
crossorigin="anonymous"></script>
-
- <script type="module" src="index.js"></script>
+ <!-- Non-module scripts after Alpine.js -->
<script type="text/javascript" src="js/settings.js"></script>
<script type="text/javascript" src="js/file_browser.js"></script>
<script type="text/javascript" src="js/modal.js"></script>
- <script type="text/javascript" src="js/scheduler.js"></script>
- <script type="module" src="js/speech.js"></script>
- <script type="module" src="js/history.js"></script>
-
</head>
<body>
@@ -106,7 +180,8 @@
<li>
<div :class="{'chat-list-button': true, 'font-bold': context.id === selected}"
@click="selected = context.id; selectChat(context.id)">
- <span class="chat-name" x-text="context.name ? context.name : 'Chat #' + context.no"></span>
+ <span class="chat-name" :title="context.name ? context.name : 'Chat #' + context.no"
+ x-text="context.name ? context.name : 'Chat #' + context.no"></span>
</div>
<button class="edit-button" @click="killChat(context.id)">X</button>
</li>
@@ -136,8 +211,8 @@
<!-- Task container with a vertical layout -->
<div class="task-container task-container-vertical">
<!-- Task name on its own line with full width -->
- <span class="task-name"
- x-text="task.name || `Task #${task.id.substring(0,8)}`"
+ <span class="task-name" :title="(task.task_name || `Task #${task.no}`) + ' (' + (task.name || `Chat #${task.no}`) + ')'"
+ x-text="(task.task_name || `Task #${task.no}`) + ' (' + (task.name || `Chat #${task.no}`) + ')'"
:data-task-id="task.id"></span>
<!-- Second line with status badge and action button -->
<div class="task-info-line">
@@ -145,15 +220,22 @@
<span class="scheduler-status-badge scheduler-status-badge-small"
:class="task.state ? `scheduler-status-${task.state}` : 'scheduler-status-idle'"
x-text="task.state || 'idle'"></span>
- <!-- Action button -->
- <button class="task-detail-button"
+ <!-- Action buttons -->
+ <button class="edit-button"
@click.stop="openTaskDetail(task.id)"
- title="View task details">
- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path>
- <path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path>
+ title="View task details" style="margin-left: auto; margin-right: 5px;">
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 512 512" fill="var(--color-primary)" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M256 0c70.69 0 134.69 28.66 181.02 74.98C483.34 121.3 512 185.31 512 256c0 70.69-28.66 134.7-74.98 181.02C390.69 483.34 326.69 512 256 512c-70.69 0-134.69-28.66-181.02-74.98C28.66 390.69 0 326.69 0 256c0-70.69 28.66-134.69 74.98-181.02C121.31 28.66 185.31 0 256 0zm-9.96 161.03c0-4.28.76-8.26 2.27-11.91 1.5-3.63 3.77-6.94 6.79-9.91 3-2.95 6.29-5.2 9.84-6.7 3.57-1.5 7.41-2.28 11.52-2.28 4.12 0 7.96.78 11.49 2.27 3.54 1.51 6.78 3.76 9.75 6.73 2.95 2.97 5.16 6.26 6.64 9.91 1.49 3.63 2.22 7.61 2.22 11.89 0 4.17-.73 8.08-2.21 11.69-1.48 3.6-3.68 6.94-6.65 9.97-2.94 3.03-6.18 5.32-9.72 6.84-3.54 1.51-7.38 2.29-11.52 2.29-4.22 0-8.14-.76-11.75-2.26-3.58-1.51-6.86-3.79-9.83-6.79-2.94-3.02-5.16-6.34-6.63-9.97-1.48-3.62-2.21-7.54-2.21-11.77zm13.4 178.16c-1.11 3.97-3.35 11.76 3.3 11.76 1.44 0 3.27-.81 5.46-2.4 2.37-1.71 5.09-4.31 8.13-7.75 3.09-3.5 6.32-7.65 9.67-12.42 3.33-4.76 6.84-10.22 10.49-16.31.37-.65 1.23-.87 1.89-.48l12.36 9.18c.6.43.73 1.25.35 1.86-5.69 9.88-11.44 18.51-17.26 25.88-5.85 7.41-11.79 13.57-17.8 18.43l-.1.06c-6.02 4.88-12.19 8.55-18.51 11.01-17.58 6.81-45.36 5.7-53.32-14.83-5.02-12.96-.9-27.69 3.06-40.37l19.96-60.44c1.28-4.58 2.89-9.62 3.47-14.33.97-7.87-2.49-12.96-11.06-12.96h-17.45c-.76 0-1.38-.62-1.38-1.38l.08-.48 4.58-16.68c.16-.62.73-1.04 1.35-1.02l89.12-2.79c.76-.03 1.41.57 1.44 1.33l-.07.43-37.76 124.7zm158.3-244.93c-41.39-41.39-98.58-67-161.74-67-63.16 0-120.35 25.61-161.74 67-41.39 41.39-67 98.58-67 161.74 0 63.16 25.61 120.35 67 161.74 41.39 41.39 98.58 67 161.74 67 63.16 0 120.35-25.61 161.74-67 41.39-41.39 67-98.58 67-161.74 0-63.16-25.61-120.35-67-161.74z"/>
+ </svg>
+ </button>
+ <button class="edit-button"
+ @click.stop="resetChat(task.id)"
+ title="Reset chat">
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 122.88 121.1" fill="var(--color-primary)" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M62.89,56.03c1.11-0.35,2.34-0.25,3.72,0.37l10.4,7.87c2.26,1.71,4.24,3.78,2.73,6.9 c-0.51,1.06-1.4,2.1-2.38,3.49l-0.53,0.75c-1.97,2.8-2.61,2-5.71,1.83c0.56,13.37,1.75,27.82-2.64,40.88 c-0.87,2.7-3.32,3.44-6.95,2.71l-6.1-2.03c4.11-6.14,6.16-13.85,6.44-22.89c-3.46,8.58-6.8,16.96-10.68,20.86l-6.28-2.08 c0.61-3.05,1.05-5.43,0.35-6.9l-4.07,4.24l-9.33-5.77c6.36-3.36,11.62-7.87,15.6-13.73c-6.69,5.01-12.76,8.1-18.14,8.99 c-2.75,0.83-4.49,0.35-5.16-1.53c-0.48-1.34-0.05-1.77,0.81-2.86c1.11-1.41,2.61-2.67,4.35-3.79c-3.13,1.1-4.64,0.95-6.37,1.51 c-4.9,1.59-9.94-1.86-8.26-6.9c1.07-3.23,3.54-3.09,6.67-4.07l5.42-1.69c-5.19,0.28-10.32,0.45-15.02-0.25 c-5.4-0.8-5.31-0.99-8.24-5.38c-3.94-5.91-6.25-11.45,2.52-9.16c16.73,3.18,33.56,5.34,51.25-0.98c-0.76-1.32-0.9-2.57-0.5-3.73 C57.37,60.94,61.13,56.58,62.89,56.03L62.89,56.03z M113.8,2.42L74.45,51.53c-4.71,6.68,3.2,11.91,8.39,5.64l39.2-49.27 C125.12,1.86,119.13-3.16,113.8,2.42L113.8,2.42z"/>
</svg>
</button>
+
</div>
</div>
</div>
@@ -653,15 +735,16 @@
<input type="text" x-model="editingTask.name" placeholder="Enter task name">
</div>
- <!-- Task Type (only editable when creating) -->
+ <!-- Task Type Selection -->
<div class="scheduler-form-field">
<div class="label-help-wrapper">
- <label class="scheduler-form-label">Task Type</label>
- <div class="scheduler-form-help">Task type cannot be changed after creation</div>
+ <label class="scheduler-form-label">Type</label>
+ <div class="scheduler-form-help">Task execution method</div>
</div>
- <select x-model="editingTask.type" :disabled="!isCreating">
- <option value="scheduled">Scheduled Task</option>
- <option value="adhoc">Ad-hoc Task</option>
+ <select x-model="editingTask.type">
+ <option value="scheduled">Scheduled (Cron)</option>
+ <option value="adhoc">Ad-hoc (Manual)</option>
+ <option value="planned">Planned (Specific Times)</option>
</select>
</div>
@@ -695,11 +778,11 @@
</div>
</div>
- <!-- Schedule (for scheduled tasks) -->
- <div class="scheduler-form-field full-width" x-show="editingTask && editingTask.type === 'scheduled'">
+ <!-- Schedule (only for scheduled tasks) -->
+ <div class="scheduler-form-field full-width" x-show="editingTask.type === 'scheduled'">
<div class="label-help-wrapper">
- <label class="scheduler-form-label">Schedule (Cron Expression)</label>
- <div class="scheduler-form-help">Format: minute hour day month weekday (e.g., "* * * * *" for every minute)</div>
+ <label class="scheduler-form-label">Schedule</label>
+ <div class="scheduler-form-help">Cron schedule for automated execution (minute hour day month weekday)</div>
</div>
<div class="scheduler-schedule-builder">
<div class="scheduler-schedule-field">
@@ -725,6 +808,94 @@
</div>
</div>
+ <!-- Plan (for planned tasks) -->
+ <div class="scheduler-form-field full-width" x-show="editingTask.type === 'planned'">
+ <div class="label-help-wrapper">
+ <label class="scheduler-form-label">Plan</label>
+ <div class="scheduler-form-help">Specific execution times for this task</div>
+ </div>
+ <div class="scheduler-plan-builder">
+ <div class="scheduler-plan-todo">
+ <span class="scheduler-plan-label">Upcoming Executions</span>
+ <div class="scheduler-todo-list">
+ <template x-if="editingTask.plan && Array.isArray(editingTask.plan.todo) && editingTask.plan.todo.length > 0">
+ <template x-for="(time, index) in editingTask.plan.todo" :key="index">
+ <div class="scheduler-todo-item">
+ <span x-text="formatDate(time)"></span>
+ <button @click.prevent="editingTask.plan.todo.splice(index, 1)" class="scheduler-todo-remove">
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <line x1="18" y1="6" x2="6" y2="18"></line>
+ <line x1="6" y1="6" x2="18" y2="18"></line>
+ </svg>
+ </button>
+ </div>
+ </template>
+ </template>
+ <template x-if="!editingTask.plan || !Array.isArray(editingTask.plan.todo) || editingTask.plan.todo.length === 0">
+ <div class="scheduler-empty-plan">
+ No scheduled execution times yet. Add one below.
+ </div>
+ </template>
+ <div class="scheduler-add-todo">
+ <!-- Create form planned task input -->
+ <input type="text" id="newPlannedTime-create"
+ x-ref="plannedTimeCreate"
+ class="scheduler-flatpickr-input"
+ placeholder="Select date and time">
+ <!-- Create Task Form Add Time Button -->
+ <button @click.prevent="
+ const input = $refs.plannedTimeCreate;
+ if (!input) {
+ console.error('Input reference not found for plannedTimeCreate');
+ return;
+ }
+
+ // Ensure plan structure exists
+ if (!editingTask.plan) {
+ editingTask.plan = { todo: [], in_progress: null, done: [] };
+ }
+ if (!Array.isArray(editingTask.plan.todo)) {
+ editingTask.plan.todo = [];
+ }
+
+ // Get date from Flatpickr if available
+ let selectedDate;
+ if (input._flatpickr && input._flatpickr.selectedDates.length > 0) {
+ selectedDate = input._flatpickr.selectedDates[0];
+ } else if (input.value) {
+ selectedDate = new Date(input.value);
+ }
+
+ if (!selectedDate || isNaN(selectedDate.getTime())) {
+ alert('Please select a valid date and time');
+ return;
+ }
+
+ // Convert to ISO string and add to plan
+ editingTask.plan.todo.push(selectedDate.toISOString());
+
+ // Sort by date (earliest first)
+ editingTask.plan.todo.sort();
+
+ // Clear the input
+ if (input._flatpickr) {
+ input._flatpickr.clear();
+ } else {
+ input.value = '';
+ }
+ " class="scheduler-add-todo-button">
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 4px;">
+ <line x1="12" y1="5" x2="12" y2="19"></line>
+ <line x1="5" y1="12" x2="19" y2="12"></line>
+ </svg>
+ Add Time
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- Token (for ad-hoc tasks) -->
<div class="scheduler-form-field full-width" x-show="editingTask.type === 'adhoc'">
<div class="label-help-wrapper">
@@ -801,6 +972,7 @@
<select x-model="editingTask.type" disabled>
<option value="scheduled">Scheduled Task</option>
<option value="adhoc">Ad-hoc Task</option>
+ <option value="planned">Planned Task</option>
</select>
</div>
@@ -864,6 +1036,94 @@
</div>
</div>
+ <!-- Plan (for planned tasks) -->
+ <div class="scheduler-form-field full-width" x-show="editingTask.type === 'planned'">
+ <div class="label-help-wrapper">
+ <label class="scheduler-form-label">Plan</label>
+ <div class="scheduler-form-help">Specific execution times for this task</div>
+ </div>
+ <div class="scheduler-plan-builder">
+ <div class="scheduler-plan-todo">
+ <span class="scheduler-plan-label">Upcoming Executions</span>
+ <div class="scheduler-todo-list">
+ <template x-if="editingTask.plan && Array.isArray(editingTask.plan.todo) && editingTask.plan.todo.length > 0">
+ <template x-for="(time, index) in editingTask.plan.todo" :key="index">
+ <div class="scheduler-todo-item">
+ <span x-text="formatDate(time)"></span>
+ <button @click.prevent="editingTask.plan.todo.splice(index, 1)" class="scheduler-todo-remove">
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <line x1="18" y1="6" x2="6" y2="18"></line>
+ <line x1="6" y1="6" x2="18" y2="18"></line>
+ </svg>
+ </button>
+ </div>
+ </template>
+ </template>
+ <template x-if="!editingTask.plan || !Array.isArray(editingTask.plan.todo) || editingTask.plan.todo.length === 0">
+ <div class="scheduler-empty-plan">
+ No scheduled execution times yet. Add one below.
+ </div>
+ </template>
+ <div class="scheduler-add-todo">
+ <!-- Edit form planned task input -->
+ <input type="text" id="newPlannedTime-edit"
+ x-ref="plannedTimeEdit"
+ class="scheduler-flatpickr-input"
+ placeholder="Select date and time">
+ <!-- Edit Task Form Add Time Button -->
+ <button @click.prevent="
+ const input = $refs.plannedTimeEdit;
+ if (!input) {
+ console.error('Input reference not found for plannedTimeEdit');
+ return;
+ }
+
+ // Ensure plan structure exists
+ if (!editingTask.plan) {
+ editingTask.plan = { todo: [], in_progress: null, done: [] };
+ }
+ if (!Array.isArray(editingTask.plan.todo)) {
+ editingTask.plan.todo = [];
+ }
+
+ // Get date from Flatpickr if available
+ let selectedDate;
+ if (input._flatpickr && input._flatpickr.selectedDates.length > 0) {
+ selectedDate = input._flatpickr.selectedDates[0];
+ } else if (input.value) {
+ selectedDate = new Date(input.value);
+ }
+
+ if (!selectedDate || isNaN(selectedDate.getTime())) {
+ alert('Please select a valid date and time');
+ return;
+ }
+
+ // Convert to ISO string and add to plan
+ editingTask.plan.todo.push(selectedDate.toISOString());
+
+ // Sort by date (earliest first)
+ editingTask.plan.todo.sort();
+
+ // Clear the input
+ if (input._flatpickr) {
+ input._flatpickr.clear();
+ } else {
+ input.value = '';
+ }
+ " class="scheduler-add-todo-button">
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 4px;">
+ <line x1="12" y1="5" x2="12" y2="19"></line>
+ <line x1="5" y1="12" x2="19" y2="12"></line>
+ </svg>
+ Add Time
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- Token (for ad-hoc tasks) -->
<div class="scheduler-form-field full-width" x-show="editingTask.type === 'adhoc'">
<div class="label-help-wrapper">
@@ -927,6 +1187,7 @@
<option value="all">All Types</option>
<option value="scheduled">Scheduled</option>
<option value="adhoc">Ad-hoc</option>
+ <option value="planned">Planned</option>
</select>
</div>
@@ -943,19 +1204,23 @@
</div>
<!-- Loading State -->
- <div class="scheduler-loading" x-show="isLoading">
+ <!-- <div class="scheduler-loading" x-show="isLoading">
Loading tasks...
- </div>
+ </div> -->
<!-- Empty State -->
- <div class="scheduler-empty" x-show="!isLoading && filteredTasks.length === 0">
+ <div class="scheduler-empty"
+ x-show="!isLoading && filteredTasks.length === 0"
+ x-effect="$el.style.display = (!isLoading && filteredTasks.length === 0) ? '' : 'none'">
<div class="scheduler-empty-icon">📋</div>
<div class="scheduler-empty-text">No tasks found</div>
<button class="btn btn-ok" @click="startCreateTask()">Create your first task</button>
</div>
<!-- Task List Table -->
- <table class="scheduler-task-list" x-show="!isLoading && filteredTasks.length > 0">
+ <table class="scheduler-task-list"
+ x-show="!isLoading && filteredTasks.length > 0"
+ x-effect="$el.style.display = (!isLoading && filteredTasks.length > 0) ? '' : 'none'">
<thead>
<tr>
<th @click="changeSort('name')">
@@ -991,6 +1256,7 @@
<td>
<span x-show="task.type === 'scheduled'" x-text="formatSchedule(task)"></span>
<span x-show="task.type === 'adhoc'" class="scheduler-no-schedule">—</span>
+ <span x-show="task.type === 'planned'" x-html="formatPlan(task).replace(/\n/g, '<br>')"></span>
</td>
<td x-text="formatDate(task.last_run)"></td>
<td @click.stop>
@@ -1054,6 +1320,38 @@
<div class="scheduler-details-label" x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'adhoc'">Token:</div>
<div class="scheduler-details-value" x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'adhoc'" x-text="selectedTaskForDetail ? selectedTaskForDetail.token : ''"></div>
+ <div class="scheduler-details-label" x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'planned'">Plan:</div>
+ <div class="scheduler-details-value" x-show="selectedTaskForDetail && selectedTaskForDetail.type === 'planned'">
+ <div x-show="selectedTaskForDetail && selectedTaskForDetail.plan">
+ <div><strong>Upcoming:</strong></div>
+ <template x-if="selectedTaskForDetail && selectedTaskForDetail.plan && selectedTaskForDetail.plan.todo && selectedTaskForDetail.plan.todo.length > 0">
+ <div>
+ <template x-for="(time, index) in selectedTaskForDetail.plan.todo" :key="index">
+ <div x-text="formatDate(time)"></div>
+ </template>
+ </div>
+ </template>
+ <template x-if="!selectedTaskForDetail || !selectedTaskForDetail.plan || !selectedTaskForDetail.plan.todo || selectedTaskForDetail.plan.todo.length === 0">
+ <div>No upcoming executions</div>
+ </template>
+
+ <div><strong>In Progress:</strong></div>
+ <div x-text="selectedTaskForDetail && selectedTaskForDetail.plan && selectedTaskForDetail.plan.in_progress ? formatDate(selectedTaskForDetail.plan.in_progress) : 'None'"></div>
+
+ <div><strong>Completed:</strong></div>
+ <template x-if="selectedTaskForDetail && selectedTaskForDetail.plan && selectedTaskForDetail.plan.done && selectedTaskForDetail.plan.done.length > 0">
+ <div>
+ <template x-for="(time, index) in selectedTaskForDetail.plan.done" :key="index">
+ <div x-text="formatDate(time)"></div>
+ </template>
+ </div>
+ </template>
+ <template x-if="!selectedTaskForDetail || !selectedTaskForDetail.plan || !selectedTaskForDetail.plan.done || selectedTaskForDetail.plan.done.length === 0">
+ <div>No completed executions</div>
+ </template>
+ </div>
+ </div>
+
<div class="scheduler-details-label">Last Result:</div>
<div class="scheduler-details-value" x-text="selectedTaskForDetail && selectedTaskForDetail.last_result ? selectedTaskForDetail.last_result : 'No results yet'"></div>
diff --git a/webui/index.js b/webui/index.js
index e6452d981..9f2ddb6a6 100644
--- a/webui/index.js
+++ b/webui/index.js
@@ -342,7 +342,17 @@ let lastSpokenNo = 0
async function poll() {
let updated = false
try {
- const response = await sendJsonData("/poll", { log_from: lastLogVersion, context });
+ // Get timezone from navigator
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+
+ const response = await sendJsonData(
+ "/poll",
+ {
+ log_from: lastLogVersion,
+ context: context || null,
+ timezone: timezone
+ }
+ );
// Check if the response is valid
if (!response) {
@@ -421,7 +431,13 @@ async function poll() {
// If it doesn't exist in the chats list but we're in chats tab, try to select the first chat
if (!contextExists && contexts.length > 0) {
+ // Check if the current context is empty before creating a new one
+ // If there's already a current context and we're just updating UI, don't automatically
+ // create a new context by calling setContext
const firstChatId = contexts[0].id;
+
+ // Only create a new context if we're not currently in an existing context
+ // This helps prevent duplicate contexts when switching tabs
setContext(firstChatId);
chatsAD.selected = firstChatId;
localStorage.setItem('lastSelectedChat', firstChatId);
@@ -454,11 +470,18 @@ async function poll() {
} else if (contexts.length > 0 && localStorage.getItem('activeTab') === 'chats') {
// If we're in chats tab with no selection but have chats, select the first one
const firstChatId = contexts[0].id;
- setContext(firstChatId);
- chatsAD.selected = firstChatId;
- localStorage.setItem('lastSelectedChat', firstChatId);
+
+ // Only set context if we don't already have one to avoid duplicates
+ if (!context) {
+ setContext(firstChatId);
+ chatsAD.selected = firstChatId;
+ localStorage.setItem('lastSelectedChat', firstChatId);
+ }
}
+ lastLogVersion = response.log_version;
+ lastLogGuid = response.log_guid;
+
} catch (error) {
console.error('Error:', error);
setConnectionStatus(false)
@@ -509,12 +532,12 @@ window.pauseAgent = async function (paused) {
}
}
-window.resetChat = async function () {
+window.resetChat = async function (ctxid=null) {
try {
- const resp = await sendJsonData("/chat_reset", { context });
- updateAfterScroll()
+ const resp = await sendJsonData("/chat_reset", { "context": ctxid === null ? context : ctxid });
+ if (ctxid === null) updateAfterScroll();
} catch (e) {
- window.toastFetchError("Error resetting chat", e)
+ window.toastFetchError("Error resetting chat", e);
}
}
@@ -1193,10 +1216,20 @@ function activateTab(tabName) {
chatsTab.classList.add('active');
chatsSection.style.display = '';
+ // Get the available contexts from Alpine.js data
+ const chatsAD = Alpine.$data(chatsSection);
+ const availableContexts = chatsAD.contexts || [];
+
// Restore previous chat selection
const lastSelectedChat = localStorage.getItem('lastSelectedChat');
- if (lastSelectedChat && lastSelectedChat !== currentContext) {
- // Only switch if there's a stored selection and it's different from current
+
+ // Only switch if:
+ // 1. lastSelectedChat exists AND
+ // 2. It's different from current context AND
+ // 3. The context actually exists in our contexts list OR there are no contexts yet
+ if (lastSelectedChat &&
+ lastSelectedChat !== currentContext &&
+ (availableContexts.some(ctx => ctx.id === lastSelectedChat) || availableContexts.length === 0)) {
setContext(lastSelectedChat);
}
} else if (tabName === 'tasks') {
@@ -1204,10 +1237,20 @@ function activateTab(tabName) {
tasksSection.style.display = 'flex';
tasksSection.style.flexDirection = 'column';
+ // Get the available tasks from Alpine.js data
+ const tasksAD = Alpine.$data(tasksSection);
+ const availableTasks = tasksAD.tasks || [];
+
// Restore previous task selection
const lastSelectedTask = localStorage.getItem('lastSelectedTask');
- if (lastSelectedTask && lastSelectedTask !== currentContext) {
- // Only switch if there's a stored selection and it's different from current
+
+ // Only switch if:
+ // 1. lastSelectedTask exists AND
+ // 2. It's different from current context AND
+ // 3. The task actually exists in our tasks list
+ if (lastSelectedTask &&
+ lastSelectedTask !== currentContext &&
+ availableTasks.some(task => task.id === lastSelectedTask)) {
setContext(lastSelectedTask);
}
}
diff --git a/webui/js/scheduler.js b/webui/js/scheduler.js
index c22873512..765758f7d 100644
--- a/webui/js/scheduler.js
+++ b/webui/js/scheduler.js
@@ -3,141 +3,222 @@
* Manages scheduled and ad-hoc tasks through a dedicated settings tab
*/
-// Add a document ready event handler to ensure the scheduler tab can be clicked on first load
-document.addEventListener('DOMContentLoaded', function() {
- // Setup scheduler tab click handling
- const setupSchedulerTab = () => {
- const settingsModal = document.getElementById('settingsModal');
- if (!settingsModal) {
- setTimeout(setupSchedulerTab, 100);
- return;
- }
-
- // Create a global event listener for clicks on the scheduler tab
- document.addEventListener('click', function(e) {
- // Find if the click was on the scheduler tab or its children
- const schedulerTab = e.target.closest('.settings-tab[title="Task Scheduler"]');
- if (!schedulerTab) return;
-
- e.preventDefault();
- e.stopPropagation();
-
- // Get the settings modal data
- try {
- const modalData = Alpine.$data(settingsModal);
- if (modalData.activeTab !== 'scheduler') {
- // Directly call the modal's switchTab method
- modalData.switchTab('scheduler');
- }
- } catch (err) {
- console.error('Error handling scheduler tab click:', err);
- }
- }, true); // Use capture phase to intercept before Alpine.js handlers
- };
-
- // Initialize the tab handling
- setupSchedulerTab();
-});
-
-document.addEventListener('alpine:init', () => {
- // Register as an Alpine component
- Alpine.data('schedulerSettings', () => ({
+import { formatDateTime, getUserTimezone } from './time-utils.js';
+
+// Ensure the showToast function is available
+// if (typeof window.showToast !== 'function') {
+// window.showToast = function(message, type = 'info') {
+// console.log(`[Toast ${type}]: ${message}`);
+// // Create toast element if not already present
+// let toastContainer = document.getElementById('toast-container');
+// if (!toastContainer) {
+// toastContainer = document.createElement('div');
+// toastContainer.id = 'toast-container';
+// toastContainer.style.position = 'fixed';
+// toastContainer.style.bottom = '20px';
+// toastContainer.style.right = '20px';
+// toastContainer.style.zIndex = '9999';
+// document.body.appendChild(toastContainer);
+// }
+
+// // Create the toast
+// const toast = document.createElement('div');
+// toast.className = `toast toast-${type}`;
+// toast.style.padding = '10px 15px';
+// toast.style.margin = '5px 0';
+// toast.style.backgroundColor = type === 'error' ? '#f44336' :
+// type === 'success' ? '#4CAF50' :
+// type === 'warning' ? '#ff9800' : '#2196F3';
+// toast.style.color = 'white';
+// toast.style.borderRadius = '4px';
+// toast.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';
+// toast.style.width = 'auto';
+// toast.style.maxWidth = '300px';
+// toast.style.wordWrap = 'break-word';
+
+// toast.innerHTML = message;
+
+// // Add to container
+// toastContainer.appendChild(toast);
+
+// // Auto remove after 3 seconds
+// setTimeout(() => {
+// if (toast.parentNode) {
+// toast.style.opacity = '0';
+// toast.style.transition = 'opacity 0.5s ease';
+// setTimeout(() => {
+// if (toast.parentNode) {
+// toast.parentNode.removeChild(toast);
+// }
+// }, 500);
+// }
+// }, 3000);
+// };
+// }
+
+// Add this near the top of the scheduler.js file, outside of any function
+const showToast = function(message, type = 'info') {
+ // Use the global toast function if available, otherwise fallback to console
+ if (typeof window.toast === 'function') {
+ window.toast(message, type);
+ } else {
+ console.log(`Toast (${type}): ${message}`);
+ }
+};
+
+// Define the full component implementation
+const fullComponentImplementation = function() {
+ return {
tasks: [],
isLoading: true,
selectedTask: null,
expandedTaskId: null,
sortField: 'name',
sortDirection: 'asc',
- filterType: 'all', // all, scheduled, adhoc
+ filterType: 'all', // all, scheduled, adhoc, planned
filterState: 'all', // all, idle, running, disabled, error
pollingInterval: null,
pollingActive: false, // Track if polling is currently active
- editingTask: null,
+ editingTask: {
+ name: '',
+ type: 'scheduled',
+ state: 'idle',
+ schedule: {
+ minute: '*',
+ hour: '*',
+ day: '*',
+ month: '*',
+ weekday: '*',
+ timezone: getUserTimezone()
+ },
+ token: '',
+ plan: {
+ todo: [],
+ in_progress: null,
+ done: []
+ },
+ system_prompt: '',
+ prompt: '',
+ attachments: []
+ },
isCreating: false,
isEditing: false,
showLoadingState: false,
viewMode: 'list', // Controls whether to show list or detail view
selectedTaskForDetail: null, // Task object for detail view
+ attachmentsText: '',
+ filteredTasks: [],
+ hasNoTasks: true, // Add explicit reactive property
// Initialize the component
init() {
- // Initialize editingTask with default values but ensure we're not in editing mode
+ // Initialize component data
+ this.tasks = [];
+ this.isLoading = true;
+ this.hasNoTasks = true; // Add explicit reactive property
+ this.filterType = 'all';
+ this.filterState = 'all';
+ this.sortField = 'name';
+ this.sortDirection = 'asc';
+ this.pollingInterval = null;
+ this.pollingActive = false;
+
+ // Start polling for tasks
+ this.startPolling();
+
+ // Refresh initial data
+ this.fetchTasks();
+
+ // Set up event handler for tab selection to ensure view is refreshed when tab becomes visible
+ document.addEventListener('click', (event) => {
+ // Check if a tab was clicked
+ const clickedTab = event.target.closest('.settings-tab');
+ if (clickedTab && clickedTab.getAttribute('data-tab') === 'scheduler') {
+ setTimeout(() => {
+ this.fetchTasks();
+ }, 100);
+ }
+ });
+
+ // Watch for changes to the tasks array to update UI
+ this.$watch('tasks', (newTasks) => {
+ this.updateTasksUI();
+ });
+
+ this.$watch('filterType', () => {
+ this.updateTasksUI();
+ });
+
+ this.$watch('filterState', () => {
+ this.updateTasksUI();
+ });
+
+ // Set up default configuration
+ this.viewMode = localStorage.getItem('scheduler_view_mode') || 'list';
+ this.selectedTask = null;
+ this.expandedTaskId = null;
this.editingTask = {
name: '',
type: 'scheduled',
- state: 'idle', // Initialize with idle state
+ state: 'idle',
schedule: {
minute: '*',
hour: '*',
day: '*',
month: '*',
- weekday: '*'
+ weekday: '*',
+ timezone: getUserTimezone()
+ },
+ token: this.generateRandomToken ? this.generateRandomToken() : '',
+ plan: {
+ todo: [],
+ in_progress: null,
+ done: []
},
- token: '',
system_prompt: '',
prompt: '',
attachments: []
};
- // Make sure we're in "list view" mode by default
- this.isCreating = false;
- this.isEditing = false;
-
- // Add a watcher for task type changes to initialize the appropriate properties
- this.$watch('editingTask.type', (newType) => {
- if (newType === 'scheduled' && !this.editingTask.schedule) {
- // Initialize schedule if changing to scheduled type
- this.editingTask.schedule = {
- minute: '*',
- hour: '*',
- day: '*',
- month: '*',
- weekday: '*'
- };
- } else if (newType === 'adhoc' && !this.editingTask.token) {
- // Initialize token if changing to adhoc type
- this.editingTask.token = this.generateRandomToken();
- }
+ // Initialize Flatpickr for date/time pickers after Alpine is fully initialized
+ this.$nextTick(() => {
+ // Wait until DOM is updated
+ setTimeout(() => {
+ if (this.isCreating) {
+ this.initFlatpickr('create');
+ } else if (this.isEditing) {
+ this.initFlatpickr('edit');
+ }
+ }, 100);
});
- // Use a small delay to ensure Alpine.js has fully initialized
- // before fetching tasks, which helps prevent layout shift
- setTimeout(() => {
- // Initial fetch to populate the list
- this.fetchTasks();
+ // Cleanup on component destruction
+ this.$cleanup = () => {
+ console.log('Cleaning up schedulerSettings component');
+ this.stopPolling();
- // Only start polling if the modal is actually open
- const store = Alpine.store('root');
- if (store && store.isOpen === true) {
- this.startPolling();
+ // Clean up any Flatpickr instances
+ const createInput = document.getElementById('newPlannedTime-create');
+ if (createInput && createInput._flatpickr) {
+ createInput._flatpickr.destroy();
}
- }, 100);
- // Initialize safe watchers with defensive checks
- this.$nextTick(() => {
- // Watch the modal state from the root store
- this.$watch('$store.root.isOpen', (isOpen) => {
- // Only proceed if the value is not undefined
- if (typeof isOpen !== 'undefined') {
- if (isOpen === true) {
- // Modal just opened
- this.startPolling();
- } else if (isOpen === false) {
- // Modal closed, stop polling
- this.stopPolling();
- }
- }
- });
- });
+ const editInput = document.getElementById('newPlannedTime-edit');
+ if (editInput && editInput._flatpickr) {
+ editInput._flatpickr.destroy();
+ }
+ };
},
// Start polling for task updates
startPolling() {
// Don't start if already polling
if (this.pollingInterval) {
+ console.log('Polling already active, not starting again');
return;
}
+ console.log('Starting task polling');
this.pollingActive = true;
// Fetch immediately, then set up interval for every 2 seconds
@@ -151,6 +232,7 @@ document.addEventListener('alpine:init', () => {
// Stop polling when tab is inactive
stopPolling() {
+ console.log('Stopping task polling');
this.pollingActive = false;
if (this.pollingInterval) {
@@ -177,7 +259,10 @@ document.addEventListener('alpine:init', () => {
method: 'POST',
headers: {
'Content-Type': 'application/json'
- }
+ },
+ body: JSON.stringify({
+ timezone: getUserTimezone()
+ })
});
if (!response.ok) {
@@ -185,68 +270,58 @@ document.addEventListener('alpine:init', () => {
}
const data = await response.json();
- console.log('Tasks fetched from backend:', data.tasks);
- this.tasks = data.tasks || [];
+
+ // Check if data.tasks exists and is an array
+ if (!data || !data.tasks) {
+ console.error('Invalid response: data.tasks is missing', data);
+ this.tasks = [];
+ } else if (!Array.isArray(data.tasks)) {
+ console.error('Invalid response: data.tasks is not an array', data.tasks);
+ this.tasks = [];
+ } else {
+ // Verify each task has necessary properties
+ const validTasks = data.tasks.filter(task => {
+ if (!task || typeof task !== 'object') {
+ console.error('Invalid task (not an object):', task);
+ return false;
+ }
+ if (!task.uuid) {
+ console.error('Task missing uuid:', task);
+ return false;
+ }
+ if (!task.name) {
+ console.error('Task missing name:', task);
+ return false;
+ }
+ if (!task.type) {
+ console.error('Task missing type:', task);
+ return false;
+ }
+ return true;
+ });
+
+ if (validTasks.length !== data.tasks.length) {
+ console.warn(`Filtered out ${data.tasks.length - validTasks.length} invalid tasks`);
+ }
+
+ this.tasks = validTasks;
+
+ // Update UI using the shared function
+ this.updateTasksUI();
+ }
} catch (error) {
console.error('Error fetching tasks:', error);
// Only show toast for errors on manual refresh, not during polling
if (!this.pollingInterval) {
showToast('Failed to fetch tasks: ' + error.message, 'error');
}
+ // Reset tasks to empty array on error
+ this.tasks = [];
} finally {
this.isLoading = false;
}
},
- // Computed property for filtered tasks
- get filteredTasks() {
- return this.tasks
- .filter(task => {
- // Filter by type
- if (this.filterType !== 'all') {
- if (this.filterType === 'scheduled' && !task.schedule) return false;
- if (this.filterType === 'adhoc' && !task.token) return false;
- }
-
- // Filter by state
- if (this.filterState !== 'all' && task.state !== this.filterState) {
- return false;
- }
-
- return true;
- })
- .sort((a, b) => {
- // Handle sorting
- let valueA, valueB;
-
- switch (this.sortField) {
- case 'name':
- valueA = a.name.toLowerCase();
- valueB = b.name.toLowerCase();
- break;
- case 'state':
- valueA = a.state;
- valueB = b.state;
- break;
- case 'last_run':
- valueA = a.last_run ? new Date(a.last_run).getTime() : 0;
- valueB = b.last_run ? new Date(b.last_run).getTime() : 0;
- break;
- default:
- valueA = a.name.toLowerCase();
- valueB = b.name.toLowerCase();
- }
-
- // Determine sort direction
- const direction = this.sortDirection === 'asc' ? 1 : -1;
-
- // Compare values
- if (valueA < valueB) return -1 * direction;
- if (valueA > valueB) return 1 * direction;
- return 0;
- });
- },
-
// Change sort field/direction
changeSort(field) {
if (this.sortField === field) {
@@ -296,9 +371,38 @@ document.addEventListener('alpine:init', () => {
// Format date for display
formatDate(dateString) {
if (!dateString) return 'Never';
+ return formatDateTime(dateString, 'full');
+ },
+
+ // Format plan for display
+ formatPlan(task) {
+ if (!task || !task.plan) return 'No plan';
+
+ const todoCount = Array.isArray(task.plan.todo) ? task.plan.todo.length : 0;
+ const inProgress = task.plan.in_progress ? 'Yes' : 'No';
+ const doneCount = Array.isArray(task.plan.done) ? task.plan.done.length : 0;
+
+ let nextRun = '';
+ if (Array.isArray(task.plan.todo) && task.plan.todo.length > 0) {
+ try {
+ const nextTime = new Date(task.plan.todo[0]);
+
+ // Verify it's a valid date before formatting
+ if (!isNaN(nextTime.getTime())) {
+ nextRun = formatDateTime(nextTime, 'short');
+ } else {
+ nextRun = 'Invalid date';
+ console.warn(`Invalid date format in plan.todo[0]: ${task.plan.todo[0]}`);
+ }
+ } catch (error) {
+ console.error(`Error formatting next run time: ${error.message}`);
+ nextRun = 'Error';
+ }
+ } else {
+ nextRun = 'None';
+ }
- const date = new Date(dateString);
- return date.toLocaleString();
+ return `Next: ${nextRun}\nTodo: ${todoCount}\nIn Progress: ${inProgress}\nDone: ${doneCount}`;
},
// Format schedule for display
@@ -309,6 +413,7 @@ document.addEventListener('alpine:init', () => {
if (typeof task.schedule === 'string') {
schedule = task.schedule;
} else if (typeof task.schedule === 'object') {
+ // Display only the cron parts, not the timezone
schedule = `${task.schedule.minute || '*'} ${task.schedule.hour || '*'} ${task.schedule.day || '*'} ${task.schedule.month || '*'} ${task.schedule.weekday || '*'}`;
}
@@ -333,20 +438,31 @@ document.addEventListener('alpine:init', () => {
document.querySelector('[x-data="schedulerSettings"]')?.setAttribute('data-editing-state', 'creating');
this.editingTask = {
name: '',
- type: 'scheduled',
+ type: 'scheduled', // Default to scheduled
state: 'idle', // Initialize with idle state
schedule: {
minute: '*',
hour: '*',
day: '*',
month: '*',
- weekday: '*'
+ weekday: '*',
+ timezone: getUserTimezone()
},
token: this.generateRandomToken(), // Generate token even for scheduled tasks to prevent undefined errors
+ plan: { // Initialize plan for all task types to prevent undefined errors
+ todo: [],
+ in_progress: null,
+ done: []
+ },
system_prompt: '',
prompt: '',
attachments: [], // Always initialize as an empty array
};
+
+ // Set up Flatpickr after the component is visible
+ this.$nextTick(() => {
+ this.initFlatpickr('create');
+ });
},
// Edit an existing task
@@ -371,6 +487,38 @@ document.addEventListener('alpine:init', () => {
// Ensure state is set with a default if missing
if (!this.editingTask.state) this.editingTask.state = 'idle';
+ // Always initialize schedule to prevent UI errors
+ // All task types need this structure for the form to work properly
+ if (!this.editingTask.schedule || typeof this.editingTask.schedule === 'string') {
+ let scheduleObj = {
+ minute: '*',
+ hour: '*',
+ day: '*',
+ month: '*',
+ weekday: '*',
+ timezone: getUserTimezone()
+ };
+
+ // If it's a string, parse it
+ if (typeof this.editingTask.schedule === 'string') {
+ const parts = this.editingTask.schedule.split(' ');
+ if (parts.length >= 5) {
+ scheduleObj.minute = parts[0] || '*';
+ scheduleObj.hour = parts[1] || '*';
+ scheduleObj.day = parts[2] || '*';
+ scheduleObj.month = parts[3] || '*';
+ scheduleObj.weekday = parts[4] || '*';
+ }
+ }
+
+ this.editingTask.schedule = scheduleObj;
+ } else {
+ // Ensure timezone exists in the schedule
+ if (!this.editingTask.schedule.timezone) {
+ this.editingTask.schedule.timezone = getUserTimezone();
+ }
+ }
+
// Ensure attachments is always an array
if (!this.editingTask.attachments) {
this.editingTask.attachments = [];
@@ -387,50 +535,92 @@ document.addEventListener('alpine:init', () => {
// Ensure appropriate properties are initialized based on task type
if (this.editingTask.type === 'scheduled') {
- // Ensure proper structure for schedule
- if (typeof this.editingTask.schedule === 'string') {
- const parts = this.editingTask.schedule.split(' ');
- this.editingTask.schedule = {
- minute: parts[0] || '*',
- hour: parts[1] || '*',
- day: parts[2] || '*',
- month: parts[3] || '*',
- weekday: parts[4] || '*'
- };
- } else if (!this.editingTask.schedule) {
- // Initialize schedule if it doesn't exist
- this.editingTask.schedule = {
- minute: '*',
- hour: '*',
- day: '*',
- month: '*',
- weekday: '*'
- };
- }
// Initialize token for scheduled tasks to prevent undefined errors if UI accesses it
if (!this.editingTask.token) {
this.editingTask.token = '';
}
+
+ // Initialize plan stub for scheduled tasks to prevent undefined errors
+ if (!this.editingTask.plan) {
+ this.editingTask.plan = {
+ todo: [],
+ in_progress: null,
+ done: []
+ };
+ }
} else if (this.editingTask.type === 'adhoc') {
// Initialize token if it doesn't exist
if (!this.editingTask.token) {
this.editingTask.token = this.generateRandomToken();
+ console.log('Generated new token for adhoc task:', this.editingTask.token);
}
- // Initialize schedule for adhoc tasks to prevent undefined errors when UI accesses schedule properties
- if (!this.editingTask.schedule) {
- this.editingTask.schedule = {
- minute: '*',
- hour: '*',
- day: '*',
- month: '*',
- weekday: '*'
+
+ console.log('Setting token for adhoc task:', this.editingTask.token);
+
+ // Initialize plan stub for adhoc tasks to prevent undefined errors
+ if (!this.editingTask.plan) {
+ this.editingTask.plan = {
+ todo: [],
+ in_progress: null,
+ done: []
+ };
+ }
+ } else if (this.editingTask.type === 'planned') {
+ // Initialize plan if it doesn't exist
+ if (!this.editingTask.plan) {
+ this.editingTask.plan = {
+ todo: [],
+ in_progress: null,
+ done: []
};
}
+
+ // Ensure todo is an array
+ if (!Array.isArray(this.editingTask.plan.todo)) {
+ this.editingTask.plan.todo = [];
+ }
+
+ // Initialize token to prevent undefined errors
+ if (!this.editingTask.token) {
+ this.editingTask.token = '';
+ }
}
+
+ // Set up Flatpickr after the component is visible and task data is loaded
+ this.$nextTick(() => {
+ this.initFlatpickr('edit');
+ });
},
// Cancel editing
cancelEdit() {
+ // Clean up Flatpickr instances
+ const destroyFlatpickr = (inputId) => {
+ const input = document.getElementById(inputId);
+ if (input && input._flatpickr) {
+ console.log(`Destroying Flatpickr instance for ${inputId}`);
+ input._flatpickr.destroy();
+
+ // Also remove any wrapper elements that might have been created
+ const wrapper = input.closest('.scheduler-flatpickr-wrapper');
+ if (wrapper && wrapper.parentNode) {
+ // Move the input back to its original position
+ wrapper.parentNode.insertBefore(input, wrapper);
+ // Remove the wrapper
+ wrapper.parentNode.removeChild(wrapper);
+ }
+
+ // Remove any added classes
+ input.classList.remove('scheduler-flatpickr-input');
+ }
+ };
+
+ if (this.isCreating) {
+ destroyFlatpickr('newPlannedTime-create');
+ } else if (this.isEditing) {
+ destroyFlatpickr('newPlannedTime-edit');
+ }
+
// Reset to initial state but keep default values to prevent errors
this.editingTask = {
name: '',
@@ -441,9 +631,15 @@ document.addEventListener('alpine:init', () => {
hour: '*',
day: '*',
month: '*',
- weekday: '*'
+ weekday: '*',
+ timezone: getUserTimezone()
},
token: '',
+ plan: { // Initialize plan for planned tasks
+ todo: [],
+ in_progress: null,
+ done: []
+ },
system_prompt: '',
prompt: '',
attachments: [], // Always initialize as an empty array
@@ -469,7 +665,8 @@ document.addEventListener('alpine:init', () => {
name: this.editingTask.name,
system_prompt: this.editingTask.system_prompt || '',
prompt: this.editingTask.prompt || '',
- state: this.editingTask.state || 'idle' // Include state in task data
+ state: this.editingTask.state || 'idle', // Include state in task data
+ timezone: getUserTimezone()
};
// Process attachments - now always stored as array
@@ -479,7 +676,7 @@ document.addEventListener('alpine:init', () => {
.filter(line => line && line.trim().length > 0)
: [];
- // Handle schedule based on task type
+ // Handle task type specific data
if (this.editingTask.type === 'scheduled') {
// Ensure schedule is properly formatted as an object
if (typeof this.editingTask.schedule === 'string') {
@@ -490,19 +687,87 @@ document.addEventListener('alpine:init', () => {
hour: parts[1] || '*',
day: parts[2] || '*',
month: parts[3] || '*',
- weekday: parts[4] || '*'
+ weekday: parts[4] || '*',
+ timezone: getUserTimezone() // Add timezone to schedule object
};
} else {
- // Use object schedule directly
- taskData.schedule = this.editingTask.schedule;
+ // Use object schedule directly but ensure timezone is included
+ taskData.schedule = {
+ ...this.editingTask.schedule,
+ timezone: this.editingTask.schedule.timezone || getUserTimezone()
+ };
}
- // Don't send token for scheduled tasks
+ // Don't send token or plan for scheduled tasks
delete taskData.token;
- } else {
+ delete taskData.plan;
+ } else if (this.editingTask.type === 'adhoc') {
// Ad-hoc task with token
+ // Ensure token is a non-empty string, generate a new one if needed
+ if (!this.editingTask.token) {
+ this.editingTask.token = this.generateRandomToken();
+ console.log('Generated new token for adhoc task:', this.editingTask.token);
+ }
+
+ console.log('Setting token in taskData:', this.editingTask.token);
taskData.token = this.editingTask.token;
- // Don't send schedule for adhoc tasks
+
+ // Don't send schedule or plan for adhoc tasks
+ delete taskData.schedule;
+ delete taskData.plan;
+ } else if (this.editingTask.type === 'planned') {
+ // Planned task with plan
+ // Make sure plan exists and has required properties
+ if (!this.editingTask.plan) {
+ this.editingTask.plan = {
+ todo: [],
+ in_progress: null,
+ done: []
+ };
+ }
+
+ // Ensure todo and done are arrays
+ if (!Array.isArray(this.editingTask.plan.todo)) {
+ this.editingTask.plan.todo = [];
+ }
+
+ if (!Array.isArray(this.editingTask.plan.done)) {
+ this.editingTask.plan.done = [];
+ }
+
+ // Validate each date in the todo list to ensure it's a valid ISO string
+ const validatedTodo = [];
+ for (const dateStr of this.editingTask.plan.todo) {
+ try {
+ const date = new Date(dateStr);
+ if (!isNaN(date.getTime())) {
+ validatedTodo.push(date.toISOString());
+ } else {
+ console.warn(`Skipping invalid date in todo list: ${dateStr}`);
+ }
+ } catch (error) {
+ console.warn(`Error processing date: ${error.message}`);
+ }
+ }
+
+ // Replace with validated list
+ this.editingTask.plan.todo = validatedTodo;
+
+ // Sort the todo items by date (earliest first)
+ this.editingTask.plan.todo.sort();
+
+ // Set the plan in taskData
+ taskData.plan = {
+ todo: this.editingTask.plan.todo,
+ in_progress: this.editingTask.plan.in_progress,
+ done: this.editingTask.plan.done || []
+ };
+
+ // Log the plan data for debugging
+ console.log('Planned task plan data:', JSON.stringify(taskData.plan, null, 2));
+
+ // Don't send schedule or token for planned tasks
delete taskData.schedule;
+ delete taskData.token;
}
// Determine if creating or updating
@@ -513,6 +778,9 @@ document.addEventListener('alpine:init', () => {
taskData.task_id = this.editingTask.uuid;
}
+ // Debug: Log the final task data being sent
+ console.log('Final task data being sent to API:', JSON.stringify(taskData, null, 2));
+
// Make API request
const response = await fetch(apiEndpoint, {
method: 'POST',
@@ -527,14 +795,73 @@ document.addEventListener('alpine:init', () => {
throw new Error(errorData.error || 'Failed to save task');
}
+ // Parse response data to get the created/updated task
+ const responseData = await response.json();
+
// Show success message
showToast(this.isCreating ? 'Task created successfully' : 'Task updated successfully', 'success');
- // Refresh task list
- this.fetchTasks();
+ // Immediately update the UI if the response includes the task
+ if (responseData && responseData.task) {
+ console.log('Task received in response:', responseData.task);
+
+ // Update the tasks array
+ if (this.isCreating) {
+ // For new tasks, add to the array
+ this.tasks = [...this.tasks, responseData.task];
+ } else {
+ // For updated tasks, replace the existing one
+ this.tasks = this.tasks.map(t =>
+ t.uuid === responseData.task.uuid ? responseData.task : t
+ );
+ }
+
+ // Update UI using the shared function
+ this.updateTasksUI();
+ } else {
+ // Fallback to fetching tasks if no task in response
+ await this.fetchTasks();
+ }
- // Reset form to default state without setting to null
- this.cancelEdit();
+ // Clean up Flatpickr instances
+ const destroyFlatpickr = (inputId) => {
+ const input = document.getElementById(inputId);
+ if (input && input._flatpickr) {
+ input._flatpickr.destroy();
+ }
+ };
+
+ if (this.isCreating) {
+ destroyFlatpickr('newPlannedTime-create');
+ } else if (this.isEditing) {
+ destroyFlatpickr('newPlannedTime-edit');
+ }
+
+ // Reset task data and form state
+ this.editingTask = {
+ name: '',
+ type: 'scheduled',
+ state: 'idle',
+ schedule: {
+ minute: '*',
+ hour: '*',
+ day: '*',
+ month: '*',
+ weekday: '*',
+ timezone: getUserTimezone()
+ },
+ token: '',
+ plan: {
+ todo: [],
+ in_progress: null,
+ done: []
+ },
+ system_prompt: '',
+ prompt: '',
+ attachments: []
+ };
+ this.isCreating = false;
+ this.isEditing = false;
document.querySelector('[x-data="schedulerSettings"]')?.removeAttribute('data-editing-state');
} catch (error) {
console.error('Error saving task:', error);
@@ -550,7 +877,10 @@ document.addEventListener('alpine:init', () => {
headers: {
'Content-Type': 'application/json'
},
- body: JSON.stringify({ task_id: taskId })
+ body: JSON.stringify({
+ task_id: taskId,
+ timezone: getUserTimezone()
+ })
});
if (!response.ok) {
@@ -593,7 +923,8 @@ document.addEventListener('alpine:init', () => {
},
body: JSON.stringify({
task_id: taskId,
- state: 'idle' // Always reset to idle state
+ state: 'idle', // Always reset to idle state
+ timezone: getUserTimezone()
})
});
@@ -627,7 +958,10 @@ document.addEventListener('alpine:init', () => {
headers: {
'Content-Type': 'application/json'
},
- body: JSON.stringify({ task_id: taskId })
+ body: JSON.stringify({
+ task_id: taskId,
+ timezone: getUserTimezone()
+ })
});
if (!response.ok) {
@@ -637,19 +971,44 @@ document.addEventListener('alpine:init', () => {
showToast('Task deleted successfully', 'success');
- // Refresh task list
- this.fetchTasks();
-
- // Close expanded view if this task was expanded
- if (this.expandedTaskId === taskId) {
- this.expandedTaskId = null;
+ // If we were viewing the detail of the deleted task, close the detail view
+ if (this.selectedTaskForDetail && this.selectedTaskForDetail.uuid === taskId) {
+ this.closeTaskDetail();
}
+
+ // Immediately update UI without waiting for polling
+ this.tasks = this.tasks.filter(t => t.uuid !== taskId);
+
+ // Update UI using the shared function
+ this.updateTasksUI();
} catch (error) {
console.error('Error deleting task:', error);
showToast('Failed to delete task: ' + error.message, 'error');
}
},
+ // Initialize datetime input with default value (30 minutes from now)
+ initDateTimeInput(event) {
+ if (!event.target.value) {
+ const now = new Date();
+ now.setMinutes(now.getMinutes() + 30);
+
+ // Format as YYYY-MM-DDThh:mm
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ const day = String(now.getDate()).padStart(2, '0');
+ const hours = String(now.getHours()).padStart(2, '0');
+ const minutes = String(now.getMinutes()).padStart(2, '0');
+
+ event.target.value = `${year}-${month}-${day}T${hours}:${minutes}`;
+
+ // If using Flatpickr, update it as well
+ if (event.target._flatpickr) {
+ event.target._flatpickr.setDate(event.target.value);
+ }
+ }
+ },
+
// Generate a random token for ad-hoc tasks
generateRandomToken() {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
@@ -660,6 +1019,72 @@ document.addEventListener('alpine:init', () => {
return token;
},
+ // Getter for filtered tasks
+ get filteredTasks() {
+ // Make sure we have tasks to filter
+ if (!Array.isArray(this.tasks)) {
+ console.warn('Tasks is not an array:', this.tasks);
+ return [];
+ }
+
+ let filtered = [...this.tasks];
+
+ // Apply type filter with case-insensitive comparison
+ if (this.filterType && this.filterType !== 'all') {
+ filtered = filtered.filter(task => {
+ if (!task.type) return false;
+ return String(task.type).toLowerCase() === this.filterType.toLowerCase();
+ });
+ }
+
+ // Apply state filter with case-insensitive comparison
+ if (this.filterState && this.filterState !== 'all') {
+ filtered = filtered.filter(task => {
+ if (!task.state) return false;
+ return String(task.state).toLowerCase() === this.filterState.toLowerCase();
+ });
+ }
+
+ // Sort the filtered tasks
+ return this.sortTasks(filtered);
+ },
+
+ // Sort the tasks based on sort field and direction
+ sortTasks(tasks) {
+ if (!Array.isArray(tasks) || tasks.length === 0) {
+ return tasks;
+ }
+
+ return [...tasks].sort((a, b) => {
+ if (!this.sortField) return 0;
+
+ const fieldA = a[this.sortField];
+ const fieldB = b[this.sortField];
+
+ // Handle cases where fields might be undefined
+ if (fieldA === undefined && fieldB === undefined) return 0;
+ if (fieldA === undefined) return 1;
+ if (fieldB === undefined) return -1;
+
+ // For dates, convert to timestamps
+ if (this.sortField === 'createdAt' || this.sortField === 'updatedAt') {
+ const dateA = new Date(fieldA).getTime();
+ const dateB = new Date(fieldB).getTime();
+ return this.sortDirection === 'asc' ? dateA - dateB : dateB - dateA;
+ }
+
+ // For string comparisons
+ if (typeof fieldA === 'string' && typeof fieldB === 'string') {
+ return this.sortDirection === 'asc'
+ ? fieldA.localeCompare(fieldB)
+ : fieldB.localeCompare(fieldA);
+ }
+
+ // For numerical comparisons
+ return this.sortDirection === 'asc' ? fieldA - fieldB : fieldB - fieldA;
+ });
+ },
+
// Computed property for attachments text representation
get attachmentsText() {
// Ensure we always have an array to work with
@@ -667,16 +1092,12 @@ document.addEventListener('alpine:init', () => {
? this.editingTask.attachments
: [];
- console.log('attachmentsText getter called, source:', this.editingTask.attachments);
-
// Join array items with newlines
return attachments.join('\n');
},
// Setter for attachments text - preserves empty lines during editing
set attachmentsText(value) {
- console.log('attachmentsText setter called with:', value);
-
if (typeof value === 'string') {
// Just split by newlines without filtering to preserve editing experience
this.editingTask.attachments = value.split('\n');
@@ -684,8 +1105,572 @@ document.addEventListener('alpine:init', () => {
// Fallback to empty array if not a string
this.editingTask.attachments = [];
}
+ },
+
+ // Debug method to test filtering logic
+ testFiltering() {
+ console.group('SchedulerSettings Debug: Filter Test');
+ console.log('Current Filter Settings:');
+ console.log('- Filter Type:', this.filterType);
+ console.log('- Filter State:', this.filterState);
+ console.log('- Sort Field:', this.sortField);
+ console.log('- Sort Direction:', this.sortDirection);
+
+ // Check if tasks is an array
+ if (!Array.isArray(this.tasks)) {
+ console.error('ERROR: this.tasks is not an array!', this.tasks);
+ console.groupEnd();
+ return;
+ }
+
+ console.log(`Raw Tasks (${this.tasks.length}):`, this.tasks);
+
+ // Test filtering by type
+ console.group('Filter by Type Test');
+ ['all', 'adhoc', 'scheduled', 'recurring'].forEach(type => {
+ const filtered = this.tasks.filter(task =>
+ type === 'all' ||
+ (task.type && String(task.type).toLowerCase() === type)
+ );
+ console.log(`Type "${type}": ${filtered.length} tasks`, filtered);
+ });
+ console.groupEnd();
+
+ // Test filtering by state
+ console.group('Filter by State Test');
+ ['all', 'idle', 'running', 'completed', 'failed'].forEach(state => {
+ const filtered = this.tasks.filter(task =>
+ state === 'all' ||
+ (task.state && String(task.state).toLowerCase() === state)
+ );
+ console.log(`State "${state}": ${filtered.length} tasks`, filtered);
+ });
+ console.groupEnd();
+
+ // Show current filtered tasks
+ console.log('Current Filtered Tasks:', this.filteredTasks);
+
+ console.groupEnd();
+ },
+
+ // New comprehensive debug method
+ debugTasks() {
+ console.group('SchedulerSettings Comprehensive Debug');
+
+ // Component state
+ console.log('Component State:');
+ console.log({
+ filterType: this.filterType,
+ filterState: this.filterState,
+ sortField: this.sortField,
+ sortDirection: this.sortDirection,
+ isLoading: this.isLoading,
+ isEditing: this.isEditing,
+ isCreating: this.isCreating,
+ viewMode: this.viewMode
+ });
+
+ // Tasks validation
+ if (!this.tasks) {
+ console.error('ERROR: this.tasks is undefined or null!');
+ console.groupEnd();
+ return;
+ }
+
+ if (!Array.isArray(this.tasks)) {
+ console.error('ERROR: this.tasks is not an array!', typeof this.tasks, this.tasks);
+ console.groupEnd();
+ return;
+ }
+
+ // Raw tasks
+ console.group('Raw Tasks');
+ console.log(`Count: ${this.tasks.length}`);
+ if (this.tasks.length > 0) {
+ console.table(this.tasks.map(t => ({
+ uuid: t.uuid,
+ name: t.name,
+ type: t.type,
+ state: t.state
+ })));
+
+ // Inspect first task in detail
+ console.log('First Task Structure:', JSON.stringify(this.tasks[0], null, 2));
+ } else {
+ console.log('No tasks available');
+ }
+ console.groupEnd();
+
+ // Filtered tasks
+ console.group('Filtered Tasks');
+ const filteredTasks = this.filteredTasks;
+ console.log(`Count: ${filteredTasks.length}`);
+ if (filteredTasks.length > 0) {
+ console.table(filteredTasks.map(t => ({
+ uuid: t.uuid,
+ name: t.name,
+ type: t.type,
+ state: t.state
+ })));
+ } else {
+ console.log('No filtered tasks');
+ }
+ console.groupEnd();
+
+ // Check for potential issues
+ console.group('Potential Issues');
+
+ // Check for case mismatches
+ if (this.tasks.length > 0 && filteredTasks.length === 0) {
+ console.warn('Filter seems to exclude all tasks. Checking why:');
+
+ // Check type values
+ const uniqueTypes = [...new Set(this.tasks.map(t => t.type))];
+ console.log('Unique task types in data:', uniqueTypes);
+
+ // Check state values
+ const uniqueStates = [...new Set(this.tasks.map(t => t.state))];
+ console.log('Unique task states in data:', uniqueStates);
+
+ // Check for exact mismatches
+ if (this.filterType !== 'all') {
+ const typeMatch = this.tasks.some(t =>
+ t.type && String(t.type).toLowerCase() === this.filterType.toLowerCase()
+ );
+ console.log(`Type "${this.filterType}" matches found:`, typeMatch);
+ }
+
+ if (this.filterState !== 'all') {
+ const stateMatch = this.tasks.some(t =>
+ t.state && String(t.state).toLowerCase() === this.filterState.toLowerCase()
+ );
+ console.log(`State "${this.filterState}" matches found:`, stateMatch);
+ }
+ }
+
+ // Check for undefined or null values
+ const hasUndefinedType = this.tasks.some(t => t.type === undefined || t.type === null);
+ const hasUndefinedState = this.tasks.some(t => t.state === undefined || t.state === null);
+
+ if (hasUndefinedType) {
+ console.warn('Some tasks have undefined or null type values!');
+ }
+
+ if (hasUndefinedState) {
+ console.warn('Some tasks have undefined or null state values!');
+ }
+
+ console.groupEnd();
+
+ console.groupEnd();
+ },
+
+ // Initialize Flatpickr datetime pickers for both create and edit forms
+ /**
+ * Initialize Flatpickr date/time pickers for scheduler forms
+ *
+ * @param {string} mode - Which pickers to initialize: 'all', 'create', or 'edit'
+ * @returns {void}
+ */
+ initFlatpickr(mode = 'all') {
+ const initPicker = (inputId, refName, wrapperClass, options = {}) => {
+ // Try to get input using Alpine.js x-ref first (more reliable)
+ let input = this.$refs[refName];
+
+ // Fall back to getElementById if x-ref is not available
+ if (!input) {
+ input = document.getElementById(inputId);
+ console.log(`Using getElementById fallback for ${inputId}`);
+ }
+
+ if (!input) {
+ console.warn(`Input element ${inputId} not found by ID or ref`);
+ return null;
+ }
+
+ // Create a wrapper around the input
+ const wrapper = document.createElement('div');
+ wrapper.className = wrapperClass || 'scheduler-flatpickr-wrapper';
+ wrapper.style.overflow = 'visible'; // Ensure dropdown can escape container
+
+ // Replace the input with our wrapped version
+ input.parentNode.insertBefore(wrapper, input);
+ wrapper.appendChild(input);
+ input.classList.add('scheduler-flatpickr-input');
+
+ // Default options
+ const defaultOptions = {
+ dateFormat: "Y-m-d H:i",
+ enableTime: true,
+ time_24hr: true,
+ static: false, // Not static so it will float
+ appendTo: document.body, // Append to body to avoid overflow issues
+ theme: "scheduler-theme",
+ allowInput: true,
+ positionElement: wrapper, // Position relative to wrapper
+ onOpen: function(selectedDates, dateStr, instance) {
+ // Ensure calendar is properly positioned and visible
+ instance.calendarContainer.style.zIndex = '9999';
+ instance.calendarContainer.style.position = 'absolute';
+ instance.calendarContainer.style.visibility = 'visible';
+ instance.calendarContainer.style.opacity = '1';
+
+ // Add class to calendar container for our custom styling
+ instance.calendarContainer.classList.add('scheduler-theme');
+ },
+ // Set default date to 30 minutes from now if no date selected
+ onReady: function(selectedDates, dateStr, instance) {
+ if (!dateStr) {
+ const now = new Date();
+ now.setMinutes(now.getMinutes() + 30);
+ instance.setDate(now, true);
+ }
+ }
+ };
+
+ // Merge options
+ const mergedOptions = {...defaultOptions, ...options};
+
+ // Initialize flatpickr
+ const fp = flatpickr(input, mergedOptions);
+
+ // Add a clear button
+ const clearButton = document.createElement('button');
+ clearButton.className = 'scheduler-flatpickr-clear';
+ clearButton.innerHTML = '×';
+ clearButton.type = 'button';
+ clearButton.addEventListener('click', (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (fp) {
+ fp.clear();
+ }
+ });
+ wrapper.appendChild(clearButton);
+
+ return fp;
+ };
+
+ // Clear any existing Flatpickr instances to prevent duplication
+ if (mode === 'all' || mode === 'create') {
+ const createInput = document.getElementById('newPlannedTime-create');
+ if (createInput && createInput._flatpickr) {
+ createInput._flatpickr.destroy();
+ }
+ }
+
+ if (mode === 'all' || mode === 'edit') {
+ const editInput = document.getElementById('newPlannedTime-edit');
+ if (editInput && editInput._flatpickr) {
+ editInput._flatpickr.destroy();
+ }
+ }
+
+ // Initialize new instances
+ if (mode === 'all' || mode === 'create') {
+ initPicker('newPlannedTime-create', 'plannedTimeCreate', 'scheduler-flatpickr-wrapper', {
+ minuteIncrement: 5,
+ defaultHour: new Date().getHours(),
+ defaultMinute: Math.ceil(new Date().getMinutes() / 5) * 5
+ });
+ }
- console.log('editingTask.attachments is now:', this.editingTask.attachments);
+ if (mode === 'all' || mode === 'edit') {
+ initPicker('newPlannedTime-edit', 'plannedTimeEdit', 'scheduler-flatpickr-wrapper', {
+ minuteIncrement: 5,
+ defaultHour: new Date().getHours(),
+ defaultMinute: Math.ceil(new Date().getMinutes() / 5) * 5
+ });
+ }
+ },
+
+ // Update tasks UI
+ updateTasksUI() {
+ // First update filteredTasks if that method exists
+ if (typeof this.updateFilteredTasks === 'function') {
+ this.updateFilteredTasks();
+ }
+
+ // Wait for UI to update
+ this.$nextTick(() => {
+ // Get empty state and task list elements
+ const emptyElement = document.querySelector('.scheduler-empty');
+ const tableElement = document.querySelector('.scheduler-task-list');
+
+ // Calculate visibility state based on filtered tasks
+ const hasFilteredTasks = Array.isArray(this.filteredTasks) && this.filteredTasks.length > 0;
+
+ // Update visibility directly
+ if (emptyElement) {
+ emptyElement.style.display = !hasFilteredTasks ? '' : 'none';
+ }
+
+ if (tableElement) {
+ tableElement.style.display = hasFilteredTasks ? '' : 'none';
+ }
+ });
+ }
+ };
+};
+
+// Only define the component if it doesn't already exist or extend the existing one
+if (!window.schedulerSettings) {
+ console.log('Defining schedulerSettings component from scratch');
+ window.schedulerSettings = fullComponentImplementation;
+} else {
+ console.log('Extending existing schedulerSettings component');
+ // Store the original function
+ const originalSchedulerSettings = window.schedulerSettings;
+
+ // Replace with enhanced version that merges the pre-initialized stub with the full implementation
+ window.schedulerSettings = function() {
+ // Get the base pre-initialized component
+ const baseComponent = originalSchedulerSettings();
+
+ // Create a backup of the original init function
+ const originalInit = baseComponent.init || function() {};
+
+ // Create our enhanced init function that adds the missing functionality
+ baseComponent.init = function() {
+ // Call the original init if it exists
+ originalInit.call(this);
+
+ console.log('Enhanced init running: adding missing methods to component');
+
+ // Get the full implementation
+ const fullImpl = fullComponentImplementation();
+
+ // Add essential methods directly
+ const essentialMethods = [
+ 'fetchTasks', 'startPolling', 'stopPolling',
+ 'startCreateTask', 'startEditTask', 'cancelEdit',
+ 'saveTask', 'runTask', 'resetTaskState', 'deleteTask',
+ 'toggleTaskExpand', 'showTaskDetail', 'closeTaskDetail',
+ 'changeSort', 'formatDate', 'formatPlan', 'formatSchedule',
+ 'getStateBadgeClass', 'generateRandomToken', 'testFiltering',
+ 'debugTasks', 'sortTasks', 'initFlatpickr', 'initDateTimeInput',
+ 'updateTasksUI'
+ ];
+
+ essentialMethods.forEach(method => {
+ if (typeof this[method] !== 'function' && typeof fullImpl[method] === 'function') {
+ console.log(`Adding missing method: ${method}`);
+ this[method] = fullImpl[method];
+ }
+ });
+
+ // Make sure we have a filteredTasks array initialized
+ this.filteredTasks = [];
+
+ // Initialize essential properties if missing
+ if (!Array.isArray(this.tasks)) {
+ this.tasks = [];
+ }
+
+ // Make sure attachmentsText getter/setter are defined
+ if (!Object.getOwnPropertyDescriptor(this, 'attachmentsText')?.get) {
+ Object.defineProperty(this, 'attachmentsText', {
+ get: function() {
+ // Ensure we always have an array to work with
+ const attachments = Array.isArray(this.editingTask?.attachments)
+ ? this.editingTask.attachments
+ : [];
+
+ // Join array items with newlines
+ return attachments.join('\n');
+ },
+ set: function(value) {
+ if (!this.editingTask) {
+ this.editingTask = { attachments: [] };
+ }
+
+ if (typeof value === 'string') {
+ // Just split by newlines without filtering to preserve editing experience
+ this.editingTask.attachments = value.split('\n');
+ } else {
+ // Fallback to empty array if not a string
+ this.editingTask.attachments = [];
+ }
+ }
+ });
+ }
+
+ // Add methods for updating filteredTasks directly
+ if (typeof this.updateFilteredTasks !== 'function') {
+ this.updateFilteredTasks = function() {
+ // Make sure we have tasks to filter
+ if (!Array.isArray(this.tasks)) {
+ this.filteredTasks = [];
+ return;
+ }
+
+ let filtered = [...this.tasks];
+
+ // Apply type filter with case-insensitive comparison
+ if (this.filterType && this.filterType !== 'all') {
+ filtered = filtered.filter(task => {
+ if (!task.type) return false;
+ return String(task.type).toLowerCase() === this.filterType.toLowerCase();
+ });
+ }
+
+ // Apply state filter with case-insensitive comparison
+ if (this.filterState && this.filterState !== 'all') {
+ filtered = filtered.filter(task => {
+ if (!task.state) return false;
+ return String(task.state).toLowerCase() === this.filterState.toLowerCase();
+ });
+ }
+
+ // Sort the filtered tasks
+ if (typeof this.sortTasks === 'function') {
+ filtered = this.sortTasks(filtered);
+ }
+
+ // Directly update the filteredTasks property
+ this.filteredTasks = filtered;
+ };
+ }
+
+ // Set up watchers to update filtered tasks when dependencies change
+ this.$nextTick(() => {
+ // Update filtered tasks when raw tasks change
+ this.$watch('tasks', () => {
+ this.updateFilteredTasks();
+ });
+
+ // Update filtered tasks when filter type changes
+ this.$watch('filterType', () => {
+ this.updateFilteredTasks();
+ });
+
+ // Update filtered tasks when filter state changes
+ this.$watch('filterState', () => {
+ this.updateFilteredTasks();
+ });
+
+ // Update filtered tasks when sort field or direction changes
+ this.$watch('sortField', () => {
+ this.updateFilteredTasks();
+ });
+
+ this.$watch('sortDirection', () => {
+ this.updateFilteredTasks();
+ });
+
+ // Initial update
+ this.updateFilteredTasks();
+
+ // Set up watcher for task type changes to initialize Flatpickr for planned tasks
+ this.$watch('editingTask.type', (newType) => {
+ if (newType === 'planned') {
+ this.$nextTick(() => {
+ // Reinitialize Flatpickr when switching to planned task type
+ if (this.isCreating) {
+ this.initFlatpickr('create');
+ } else if (this.isEditing) {
+ this.initFlatpickr('edit');
+ }
+ });
+ }
+ });
+
+ // Initialize Flatpickr
+ this.$nextTick(() => {
+ if (typeof this.initFlatpickr === 'function') {
+ this.initFlatpickr();
+ } else {
+ console.error('initFlatpickr is not available');
+ }
+ });
+ });
+
+ // Try fetching tasks after a short delay
+ setTimeout(() => {
+ if (typeof this.fetchTasks === 'function') {
+ this.fetchTasks();
+ } else {
+ console.error('fetchTasks still not available after enhancement');
+ }
+ }, 100);
+
+ console.log('Enhanced init complete');
+ };
+
+ return baseComponent;
+ };
+}
+
+// Force Alpine.js to register the component immediately
+if (window.Alpine) {
+ // Alpine is already loaded, register now
+ console.log('Alpine already loaded, registering schedulerSettings component now');
+ window.Alpine.data('schedulerSettings', window.schedulerSettings);
+} else {
+ // Wait for Alpine to load
+ document.addEventListener('alpine:init', () => {
+ console.log('Alpine:init - immediately registering schedulerSettings component');
+ Alpine.data('schedulerSettings', window.schedulerSettings);
+ });
+}
+
+// Add a document ready event handler to ensure the scheduler tab can be clicked on first load
+document.addEventListener('DOMContentLoaded', function() {
+ console.log('DOMContentLoaded - setting up scheduler tab click handler');
+ // Setup scheduler tab click handling
+ const setupSchedulerTab = () => {
+ const settingsModal = document.getElementById('settingsModal');
+ if (!settingsModal) {
+ setTimeout(setupSchedulerTab, 100);
+ return;
}
- }));
+
+ // Create a global event listener for clicks on the scheduler tab
+ document.addEventListener('click', function(e) {
+ // Find if the click was on the scheduler tab or its children
+ const schedulerTab = e.target.closest('.settings-tab[title="Task Scheduler"]');
+ if (!schedulerTab) return;
+
+ e.preventDefault();
+ e.stopPropagation();
+
+ // Get the settings modal data
+ try {
+ const modalData = Alpine.$data(settingsModal);
+ if (modalData.activeTab !== 'scheduler') {
+ // Directly call the modal's switchTab method
+ modalData.switchTab('scheduler');
+ }
+
+ // Force start polling and fetch tasks immediately when tab is selected
+ setTimeout(() => {
+ // Get the scheduler component data
+ const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');
+ if (schedulerElement) {
+ const schedulerData = Alpine.$data(schedulerElement);
+
+ // Force fetch tasks and start polling
+ if (typeof schedulerData.fetchTasks === 'function') {
+ schedulerData.fetchTasks();
+ } else {
+ console.error('fetchTasks is not a function on scheduler component');
+ }
+
+ if (typeof schedulerData.startPolling === 'function') {
+ schedulerData.startPolling();
+ } else {
+ console.error('startPolling is not a function on scheduler component');
+ }
+ } else {
+ console.error('Could not find scheduler component element');
+ }
+ }, 100);
+ } catch (err) {
+ console.error('Error handling scheduler tab click:', err);
+ }
+ }, true); // Use capture phase to intercept before Alpine.js handlers
+ };
+
+ // Initialize the tab handling
+ setupSchedulerTab();
});
diff --git a/webui/js/settings.js b/webui/js/settings.js
index cb2b45f9b..6c01737d7 100644
--- a/webui/js/settings.js
+++ b/webui/js/settings.js
@@ -36,6 +36,36 @@ const settingsModalProxy = {
if (activeTab) {
activeTab.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
}
+
+ // When switching to the scheduler tab, initialize Flatpickr components
+ if (tabName === 'scheduler') {
+ console.log('Switching to scheduler tab, initializing Flatpickr');
+ const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');
+ if (schedulerElement) {
+ const schedulerData = Alpine.$data(schedulerElement);
+ if (schedulerData) {
+ // Start polling
+ if (typeof schedulerData.startPolling === 'function') {
+ schedulerData.startPolling();
+ }
+
+ // Initialize Flatpickr if editing or creating
+ if (typeof schedulerData.initFlatpickr === 'function') {
+ // Check if we're creating or editing and initialize accordingly
+ if (schedulerData.isCreating) {
+ schedulerData.initFlatpickr('create');
+ } else if (schedulerData.isEditing) {
+ schedulerData.initFlatpickr('edit');
+ }
+ }
+
+ // Force an immediate fetch
+ if (typeof schedulerData.fetchTasks === 'function') {
+ schedulerData.fetchTasks();
+ }
+ }
+ }
+ }
}, 10);
},
@@ -103,9 +133,25 @@ const settingsModalProxy = {
}
// Debug log
const schedulerTab = document.querySelector('.settings-tab[title="Task Scheduler"]');
- console.log(`Current active tab after direct set: ${modalAD.activeTab}`);
+ console.log(`Current active tab after direct set: ${modalAD.activeTab}`);
console.log('Scheduler tab active after direct initialization?',
schedulerTab && schedulerTab.classList.contains('active'));
+
+ // Explicitly start polling if we're on the scheduler tab
+ if (modalAD.activeTab === 'scheduler') {
+ console.log('Settings opened directly to scheduler tab, initializing polling');
+ const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');
+ if (schedulerElement) {
+ const schedulerData = Alpine.$data(schedulerElement);
+ if (schedulerData && typeof schedulerData.startPolling === 'function') {
+ schedulerData.startPolling();
+ // Also force an immediate fetch
+ if (typeof schedulerData.fetchTasks === 'function') {
+ schedulerData.fetchTasks();
+ }
+ }
+ }
+ }
}, 10); // Small delay just for scrolling
}, 5); // Keep a minimal delay for modal opening reactivity
@@ -170,6 +216,9 @@ const settingsModalProxy = {
this.handleCancel();
}
+ // Stop scheduler polling if it's running
+ this.stopSchedulerPolling();
+
// First update our component state
this.isOpen = false;
@@ -189,6 +238,9 @@ const settingsModalProxy = {
data: null
});
+ // Stop scheduler polling if it's running
+ this.stopSchedulerPolling();
+
// First update our component state
this.isOpen = false;
@@ -202,6 +254,19 @@ const settingsModalProxy = {
}
},
+ // Add a helper method to stop scheduler polling
+ stopSchedulerPolling() {
+ // Find the scheduler component and stop polling if it exists
+ const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');
+ if (schedulerElement) {
+ const schedulerData = Alpine.$data(schedulerElement);
+ if (schedulerData && typeof schedulerData.stopPolling === 'function') {
+ console.log('Stopping scheduler polling on modal close');
+ schedulerData.stopPolling();
+ }
+ }
+ },
+
handleFieldButton(field) {
console.log(`Button clicked: ${field.action}`);
}
@@ -463,6 +528,16 @@ document.addEventListener('alpine:init', function () {
},
closeModal() {
+ // Stop scheduler polling before closing the modal
+ const schedulerElement = document.querySelector('[x-data="schedulerSettings"]');
+ if (schedulerElement) {
+ const schedulerData = Alpine.$data(schedulerElement);
+ if (schedulerData && typeof schedulerData.stopPolling === 'function') {
+ console.log('Stopping scheduler polling on modal close');
+ schedulerData.stopPolling();
+ }
+ }
+
this.$store.root.isOpen = false;
}
};
diff --git a/webui/js/time-utils.js b/webui/js/time-utils.js
new file mode 100644
index 000000000..9baba7fa6
--- /dev/null
+++ b/webui/js/time-utils.js
@@ -0,0 +1,71 @@
+/**
+ * Time utilities for handling UTC to local time conversion
+ */
+
+/**
+ * Convert a UTC ISO string to a local time string
+ * @param {string} utcIsoString - UTC time in ISO format
+ * @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 defaultOptions = {
+ dateStyle: 'medium',
+ timeStyle: 'medium'
+ };
+
+ return new Intl.DateTimeFormat(
+ undefined, // Use browser's locale
+ { ...defaultOptions, ...options }
+ ).format(date);
+}
+
+/**
+ * Convert a local Date object to UTC ISO string
+ * @param {Date} date - Date object in local time
+ * @returns {string} UTC ISO string
+ */
+export function toUTCISOString(date) {
+ if (!date) return '';
+ return date.toISOString();
+}
+
+/**
+ * Get current time as UTC ISO string
+ * @returns {string} Current UTC time in ISO format
+ */
+export function getCurrentUTCISOString() {
+ return new Date().toISOString();
+}
+
+/**
+ * Format a UTC ISO string for display in local time with configurable format
+ * @param {string} utcIsoString - UTC time in ISO format
+ * @param {string} format - Format type ('full', 'date', 'time', 'short')
+ * @returns {string} Formatted local time string
+ */
+export function formatDateTime(utcIsoString, format = 'full') {
+ if (!utcIsoString) return '';
+
+ const date = new Date(utcIsoString);
+
+ const formatOptions = {
+ full: { dateStyle: 'medium', timeStyle: 'medium' },
+ date: { dateStyle: 'medium' },
+ time: { timeStyle: 'medium' },
+ short: { dateStyle: 'short', timeStyle: 'short' }
+ };
+
+ return toLocalTime(utcIsoString, formatOptions[format] || formatOptions.full);
+}
+
+/**
+ * Get the user's local timezone name
+ * @returns {string} Timezone name (e.g., 'America/New_York')
+ */
+export function getUserTimezone() {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
+}