Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: scheduled tasks that run a prompt on a schedule and save each answer as a new chat (#13871)
alkinunba5c3b2d07c4
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.pyindex 4641d8bf3a2..b496342d245 100644--- a/studio/backend/core/inference/llama_keepwarm.py+++ b/studio/backend/core/inference/llama_keepwarm.py@@ -225,6 +225,11 @@ def _is_idle(ttl_seconds: float) -> bool:return _inflight == 0 and _pending == 0 and (time.monotonic() - _last_active) >= ttl_seconds+def inference_in_flight() -> bool:+ with _lock:+ return _inflight > 0 or _pending > 0++def _note_activity() -> None:"""Stamp activity, e.g. on a (re)load, so the model survives at least one TTL."""global _last_active@@ -472,6 +477,18 @@ def untrack_admitted_inference(scope) -> None:_note_admitted_end()+def end_in_process_request(scope, answered: bool) -> None:+ """LlamaKeepWarmMiddleware's end-of-request bookkeeping for an in-process request. Idempotent."""+ if (+ answered+ and isinstance(scope, dict)+ and scope.get(_ADMITTED_SCOPE_KEY)+ and not scope.get(_RESPONSE_FAILED_SCOPE_KEY)+ ):+ _claim_non_preview_slot()+ untrack_admitted_inference(scope)++def begin_preview_serializer_wait(scope) -> bool:"""Move a tracked preview from active to pending while it waits on the route lock."""global _inflight, _pending, _preview_inflight, _preview_pendingdiff --git a/studio/backend/core/scheduled_tasks/__init__.py b/studio/backend/core/scheduled_tasks/__init__.pynew file mode 100644index 00000000000..4e8479d722c--- /dev/null+++ b/studio/backend/core/scheduled_tasks/__init__.py@@ -0,0 +1,4 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Scheduled tasks: prompts that run on their own and post the answer to a new chat."""diff --git a/studio/backend/core/scheduled_tasks/schedule.py b/studio/backend/core/scheduled_tasks/schedule.pynew file mode 100644index 00000000000..dab2051deee--- /dev/null+++ b/studio/backend/core/scheduled_tasks/schedule.py@@ -0,0 +1,142 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""When a task runs next: wall clock in its IANA zone; a skipped time runs past the gap, a repeated one once."""++from __future__ import annotations++import calendar+import re+from datetime import date, datetime, time as wall_time, timedelta, timezone+from typing import Annotated, Any, Literal, Optional, Union+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++from pydantic import AfterValidator, BaseModel, ConfigDict, Field, TypeAdapter, field_validator++_CLOCK = re.compile(r"^([01][0-9]|2[0-3]):([0-5][0-9])$")+_LOCAL_MINUTE_FORMAT = "%Y-%m-%dT%H:%M"+_MAX_TIMEZONE_LENGTH = 64+++class InvalidSchedule(ValueError):+ """A schedule or time zone that cannot produce a run time."""+++def _check_clock(value: str) -> str:+ if not _CLOCK.match(value):+ raise ValueError("time must be HH:MM on a 24-hour clock")+ return value+++def _check_local_minute(value: str) -> str:+ try:+ datetime.strptime(value, _LOCAL_MINUTE_FORMAT)+ except ValueError:+ raise ValueError("at must be YYYY-MM-DDTHH:MM") from None+ return value+++Clock = Annotated[str, AfterValidator(_check_clock)]+LocalMinute = Annotated[str, AfterValidator(_check_local_minute)]+++class OnceSchedule(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ kind: Literal["once"]+ at: LocalMinute+++class DailySchedule(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ kind: Literal["daily"]+ time: Clock+++class WeeklySchedule(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ kind: Literal["weekly"]+ time: Clock+ # ISO weekdays: 1 is Monday, 7 is Sunday.+ days: list[int] = Field(min_length = 1, max_length = 7)++ @field_validator("days")+ @classmethod+ def _iso_weekdays(cls, value: list[int]) -> list[int]:+ if any(day < 1 or day > 7 for day in value):+ raise ValueError("days must be ISO weekdays, 1 (Monday) to 7 (Sunday)")+ return sorted(set(value))+++class MonthlySchedule(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ kind: Literal["monthly"]+ time: Clock+ # A month without this day runs on its last day.+ day: int = Field(ge = 1, le = 31)+++Schedule = Annotated[+ Union[OnceSchedule, DailySchedule, WeeklySchedule, MonthlySchedule],+ Field(discriminator = "kind"),+]+_SCHEDULE = TypeAdapter(Schedule)+++def parse_schedule(value: Any) -> Schedule:+ """A schedule from its JSON form; raises pydantic's ValidationError."""+ return _SCHEDULE.validate_python(value)+++def resolve_timezone(name: str) -> ZoneInfo:+ if not name or len(name) > _MAX_TIMEZONE_LENGTH:+ raise InvalidSchedule("Unknown time zone.")+ try:+ return ZoneInfo(name)+ except (ZoneInfoNotFoundError, ValueError, OSError):+ raise InvalidSchedule(f"Unknown time zone: {name}") from None+++def _utc(day: date, clock: wall_time, zone: ZoneInfo) -> datetime:+ # fold=0 (PEP 495) is what moves a skipped time past the gap and picks the first of a repeated one.+ return datetime.combine(day, clock, tzinfo = zone).astimezone(timezone.utc)+++def _next_after(schedule: Schedule, zone: ZoneInfo, after: datetime) -> Optional[datetime]:+ if isinstance(schedule, OnceSchedule):+ moment = datetime.strptime(schedule.at, _LOCAL_MINUTE_FORMAT)+ candidate = _utc(moment.date(), moment.time(), zone)+ return candidate if candidate > after else None+ hour, minute = (int(part) for part in schedule.time.split(":"))+ clock = wall_time(hour, minute)+ today = after.astimezone(zone).date()+ if isinstance(schedule, MonthlySchedule):+ year, month = today.year, today.month+ for _ in range(2):+ last_day = calendar.monthrange(year, month)[1]+ candidate = _utc(date(year, month, min(schedule.day, last_day)), clock, zone)+ if candidate > after:+ return candidate+ year, month = (year + 1, 1) if month == 12 else (year, month + 1)+ return None+ days = set(schedule.days) if isinstance(schedule, WeeklySchedule) else None+ # Eight days reach the same weekday a week on, whichever single day is set.+ for offset in range(8):+ day = today + timedelta(days = offset)+ if days is not None and day.isoweekday() not in days:+ continue+ candidate = _utc(day, clock, zone)+ if candidate > after:+ return candidate+ return None+++def next_run_after(schedule: Schedule, timezone_name: str, after_ms: int) -> Optional[int]:+ """The first run strictly after ``after_ms`` (epoch ms), or None once a schedule has none left."""+ zone = resolve_timezone(timezone_name)+ after = datetime.fromtimestamp(after_ms / 1000, tz = timezone.utc)+ candidate = _next_after(schedule, zone, after)+ return None if candidate is None else int(candidate.timestamp() * 1000)diff --git a/studio/backend/core/scheduled_tasks/scheduler.py b/studio/backend/core/scheduled_tasks/scheduler.pynew file mode 100644index 00000000000..1a67c26405e--- /dev/null+++ b/studio/backend/core/scheduled_tasks/scheduler.py@@ -0,0 +1,626 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Runs scheduled tasks while Studio is up: one loop, one run at a time, each saved as a chat."""++from __future__ import annotations++import asyncio+import contextlib+import json+import threading+import uuid+import weakref+from dataclasses import dataclass+from datetime import datetime, timezone+from typing import Any, Optional++from starlette.requests import Request++from core.scheduled_tasks.schedule import next_run_after, parse_schedule, resolve_timezone+from core.training.account_jobs import job_accounts+from loggers import get_logger+from storage import scheduled_tasks_db as db+from utils.account_context import AccountContext, arun_as, current_account_id, run_as++logger = get_logger(__name__)++# Longest sleep: asyncio's clock stops while a computer sleeps, so a run due meanwhile starts at most this late.+_POLL_SECONDS = 60.0+# Floor after a pass that claimed nothing, so an unclaimable due task cannot spin the loop.+_MIN_SLEEP_SECONDS = 1.0+_HEARTBEAT_SECONDS = 30.0+_STALE_RUN_MS = 2 * 60 * 1000+_RUN_TIMEOUT_SECONDS = 20 * 60+_CANCEL_GRACE_SECONDS = 10.0+_STOP_GRACE_SECONDS = 5.0+_SETTLE_ATTEMPTS = 3+_SETTLE_RETRY_SECONDS = 1.0+_ERROR_TEXT_LIMIT = 500+_YIELD_SECONDS = 5 * 60+_YIELD_POLL_SECONDS = 2.0++_schedulers: "weakref.WeakSet[ScheduledTaskScheduler]" = weakref.WeakSet()+++class RunFailed(Exception):+ """A run that ends without a chat. ``code`` is a reason the UI words itself."""++ def __init__(+ self,+ code: Optional[str] = None,+ message: Optional[str] = None,+ ):+ super().__init__(message or code or "failed")+ self.code = code+ self.message = message+++@dataclass+class Answer:+ content: str+ reasoning: str+ model: Optional[str]+ # What Chat selects to continue the conversation; `model` is the reply's display name.+ checkpoint: Optional[str] = None+ gguf_variant: Optional[str] = None+++@dataclass+class _ActiveRun:+ account_id: str+ task_id: str+ run_id: str+ cancel_event: threading.Event+++def cancel_account_runs(account_id: str) -> None:+ for scheduler in list(_schedulers):+ scheduler.cancel_account(account_id)+++def retire_account_scheduled_tasks(account: AccountContext) -> None:+ cancel_account_runs(account.account_id)+++def next_run_for(task: dict, after_ms: int) -> Optional[int]:+ return next_run_after(parse_schedule(task["schedule"]), task["timezone"], after_ms)+++def system_prompt(task: dict, now_ms: int) -> str:+ try:+ zone = resolve_timezone(task["timezone"])+ except ValueError:+ zone = timezone.utc+ local = datetime.fromtimestamp(now_ms / 1000, tz = zone)+ when = f"{local:%A}, {local:%B} {local.day}, {local.year} at {local:%H:%M}"+ return (+ f"This is a scheduled task the user set up in Unsloth Studio, running on {when} "+ f"({task['timezone']}). The user is not watching this chat and will read your reply "+ "later, so complete the task directly and do not ask follow-up questions."+ )+++def _loop_cancelled(current: Optional[asyncio.Task], stopping: bool) -> bool:+ """Whether the scheduler's own task is being cancelled. ``Task.cancelling()`` is 3.11+; before it only stop() does."""+ if current is None:+ return False+ cancelling = getattr(current, "cancelling", None)+ return bool(cancelling()) if cancelling is not None else stopping+++def _producer_request(app: Any, run_id: str, cancel_event: threading.Event, tz: str) -> Request:+ from utils.current_date_prompt_settings import CURRENT_DATE_TIMEZONE_HEADER+ from utils.keyless_api_access import KEYLESS_ADMISSION_STATE_KEY+ from routes.inference import LOADED_MODELS_ONLY_SCOPE_KEY, REQUIRE_TEXT_HEADER++ path = f"/api/scheduled-tasks/runs/{run_id}"+ scope = {+ "type": "http",+ "asgi": {"version": "3.0", "spec_version": "2.3"},+ "http_version": "1.1",+ "method": "POST",+ "scheme": "http",+ "path": path,+ "raw_path": path.encode("ascii", "ignore"),+ "query_string": b"",+ "headers": [+ (CURRENT_DATE_TIMEZONE_HEADER.encode("latin-1"), tz.encode("latin-1", "ignore")),+ (REQUIRE_TEXT_HEADER.lower().encode("latin-1"), b"1"),+ ],+ "client": ("127.0.0.1", 0),+ "server": ("127.0.0.1", 0),+ "app": app,+ # The kept model it names may be unloaded before routing: never load it back.+ LOADED_MODELS_ONLY_SCOPE_KEY: True,+ "state": {+ "generation_cancel_event": cancel_event,+ "api_monitor_via_api_key": False,+ # Created by a signed-in user, so never classified as keyless loopback traffic.+ KEYLESS_ADMISSION_STATE_KEY: False,+ },+ }++ async def receive():+ return {"type": "http.request", "body": b"", "more_body": False}++ return Request(scope, receive)+++def _error_text(detail: Any) -> str:+ if isinstance(detail, dict):+ nested = detail.get("error")+ if isinstance(nested, dict):+ detail = nested+ detail = detail.get("message") or detail.get("detail") or detail.get("error") or detail+ text = detail if isinstance(detail, str) else json.dumps(detail, default = str)+ return text.strip()[:_ERROR_TEXT_LIMIT] or "The model could not answer."+++def _chat_model_loaded() -> bool:+ from routes.inference import _loaded_slot_ident+ return _loaded_slot_ident() is not None+++def _speech_only(llama: Any, orchestrator: Any) -> bool:+ """A loaded audio model a text-only run cannot use: TTS answers with speech, Whisper refuses a request without audio."""+ if getattr(llama, "is_loaded", False):+ return bool(getattr(llama, "_is_audio", False))+ active = getattr(orchestrator, "active_model_name", None)+ info = (getattr(orchestrator, "models", None) or {}).get(active) or {}+ return bool(info.get("is_audio"))+++def _slot_model(slot: Any) -> Optional[str]:+ if _speech_only(slot.llama, slot.orchestrator):+ return None+ if getattr(slot.llama, "is_loaded", False) and getattr(slot.llama, "model_identifier", None):+ return str(slot.llama.model_identifier)+ name = getattr(slot.orchestrator, "active_model_name", None)+ return str(name) if name else None+++def _sole_kept_model() -> Optional[str]:+ """With no primary this account may use for text, its one model kept alongside: named, a run routes to it without a load."""+ from core.inference import model_slots+ from hub.services.models import account_access+ from routes.inference import _loaded_slot_ident, _peek_inference_backend, get_llama_cpp_backend++ primary = _loaded_slot_ident()+ if (+ primary is not None+ and not (+ account_access.managed_account() and account_access.resident_hidden("chat", primary)+ )+ and not _speech_only(get_llama_cpp_backend(), _peek_inference_backend())+ ):+ return None+ names = [name for name in map(_slot_model, model_slots.visible()) if name]+ return names[0] if len(names) == 1 else None+++async def generate_answer(app: Any, task: dict, run: dict, cancel_event: threading.Event) -> Answer:+ """Ask the loaded chat model to do the task. Text only: tools never run unattended."""+ from fastapi import HTTPException++ from core.inference.gpu_arbiter import GpuBusyForAnotherAccountError+ from core.inference.llama_keepwarm import InferenceActivityReservation, end_in_process_request+ from models.inference import ChatCompletionRequest+ from routes.inference import produce_openai_chat_completions++ loop = asyncio.get_running_loop()+ deadline = loop.time() + _RUN_TIMEOUT_SECONDS+ request = _producer_request(app, run["id"], cancel_event, task["timezone"])+ activity = InferenceActivityReservation()+ activity.reserve()+ producer: Optional[asyncio.Future] = None+ response = None+ try:+ # The deadline covers the wait for a model load or unload to let go too: one that never+ # does must not keep the scheduler from every other task.+ try:+ await asyncio.wait_for(activity.start(cancel_event), timeout = _RUN_TIMEOUT_SECONDS)+ except TimeoutError:+ raise RunFailed("timeout") from None+ if cancel_event.is_set():+ raise RunFailed("cancelled")+ # Built once admitted: a model kept alongside is chosen as it stands now, not before a load or unload.+ payload = ChatCompletionRequest.model_validate(+ {+ # No model: the loaded one answers, and an idle-unloaded one is brought back. Naming+ # one could switch models under the user.+ "messages": [+ {"role": "system", "content": system_prompt(task, db.now_ms())},+ {"role": "user", "content": task["prompt"]},+ ],+ "stream": False,+ "cancel_id": run["id"],+ # Both opt-outs: --enable-tools overrides enable_tools, and an omitted enabled_tools+ # means every built-in, python and terminal included.+ "tool_choice": "none",+ "enabled_tools": [],+ **({"model": kept} if (kept := _sole_kept_model()) else {}),+ }+ )++ serving: dict = {}++ async def produce() -> Any:+ # Settled in this task: slot routing lives in its context, which the caller never sees.+ reply = None+ try:+ reply = await produce_openai_chat_completions(+ payload,+ request,+ task["ownerSubject"],+ cancel_on_disconnect = False,+ )+ serving.update(_serving_checkpoint())+ return reply+ finally:+ end_in_process_request(+ request.scope,+ answered = reply is not None and int(getattr(reply, "status_code", 200)) < 400,+ )++ producer = asyncio.ensure_future(produce())+ done, _ = await asyncio.wait({producer}, timeout = max(0.0, deadline - loop.time()))+ if not done:+ raise RunFailed("timeout")+ try:+ response = producer.result()+ except HTTPException as exc:+ # A named kept model answered for itself, so its refusal is not "nothing loaded",+ # unless it was unloaded before the request reached it.+ named = "model" in payload.model_fields_set+ if (not named and not _chat_model_loaded()) or (named and _sole_kept_model() is None):+ raise RunFailed("no_model") from None+ raise RunFailed(None, _error_text(exc.detail)) from None+ except GpuBusyForAnotherAccountError as exc:+ raise RunFailed(None, _error_text(exc.as_http_exception().detail)) from None+ finally:+ if producer is not None and not producer.done():+ # A timeout or shutdown: stop the generation itself, not just this wait.+ cancel_event.set()+ producer.cancel()+ await asyncio.wait({producer}, timeout = _CANCEL_GRACE_SECONDS)++ def release(*_: Any) -> None:+ activity.finish()+ if producer is None:+ end_in_process_request(request.scope, answered = False)++ if producer is not None and not producer.done():+ # Its worker has not unwound yet: the model stays busy until it does.+ producer.add_done_callback(release)+ else:+ release()+ if cancel_event.is_set():+ raise RunFailed("cancelled")+ body = getattr(response, "body", None)+ if body is None:+ raise RunFailed(None, "The model did not return a reply.")+ data = json.loads(bytes(body))+ if int(getattr(response, "status_code", 200)) >= 400:+ raise RunFailed(None, _error_text(data))+ choices = data.get("choices") or [{}]+ message = choices[0].get("message") or {}+ content = message.get("content") or ""+ if not content.strip():+ raise RunFailed("empty")+ return Answer(+ content = content,+ reasoning = message.get("reasoning_content") or "",+ model = data.get("model") or None,+ checkpoint = serving.get("checkpoint"),+ gguf_variant = serving.get("gguf_variant"),+ )+++def _serving_checkpoint() -> dict:+ """The model that answered, as Chat names it: read in the producer's task, where its slot was routed."""+ from routes.inference import _loaded_slot_ident, get_llama_cpp_backend++ llama = get_llama_cpp_backend()+ variant = getattr(llama, "hf_variant", None) if getattr(llama, "is_loaded", False) else None+ return {"checkpoint": _loaded_slot_ident(), "gguf_variant": variant or None}+++def _project_or_none(project_id: Optional[str]) -> Optional[str]:+ from storage import studio_db+ return project_id if project_id and studio_db.get_chat_project(project_id) else None+++def save_chat(task: dict, run: dict, answer: Answer, started_at: int, finished_at: int) -> str:+ from storage import studio_db++ thread_id = db.chat_id_for_run(run["id"])+ user_message_id = str(uuid.uuid4())+ # After the prompt even within one millisecond, which the message order relies on.+ answered_at = max(finished_at, started_at + 1)+ model = answer.model or ""+ checkpoint = answer.checkpoint or model+ studio_db.upsert_chat_thread(+ {+ "id": thread_id,+ "title": task["title"],+ "modelType": "base",+ "modelId": checkpoint,+ "modelGgufVariant": answer.gguf_variant,+ "createdAt": started_at,+ "updatedAt": answered_at,+ "scheduledTaskId": task["id"],+ "projectId": _project_or_none(task.get("projectId")),+ "archived": bool(task.get("archiveSuccessful")),+ }+ )+ parts: list[dict] = []+ source = {"taskId": task["id"], "runId": run["id"]}+ metadata: dict = {+ "scheduledTask": source,+ "responseDetails": {+ "modelId": checkpoint,+ "modelLabel": model,+ "responseModelId": model,+ "providerName": "Local model",+ "providerType": "local",+ "startedAt": started_at,+ "finishedAt": answered_at,+ "durationMs": answered_at - started_at,+ "toolCalls": [],+ },+ }+ if answer.reasoning.strip():+ parts.append({"type": "reasoning", "text": answer.reasoning})+ seconds = max(0, round((answered_at - started_at) / 1000))+ metadata.update(reasoningDuration = seconds, reasoningDurations = [seconds])+ parts.append({"type": "text", "text": answer.content})+ try:+ studio_db.sync_chat_messages(+ thread_id,+ [+ {+ "id": user_message_id,+ "threadId": thread_id,+ "parentId": None,+ "role": "user",+ "content": [{"type": "text", "text": task["prompt"]}],+ "metadata": {"scheduledTask": source},+ "createdAt": started_at,+ },+ {+ "id": str(uuid.uuid4()),+ "threadId": thread_id,+ "parentId": user_message_id,+ "role": "assistant",+ "content": parts,+ "metadata": metadata,+ "createdAt": answered_at,+ },+ ],+ )+ except Exception:+ # Never leave an empty chat behind.+ _discard_chat(thread_id)+ raise+ return thread_id+++def _discard_chat(thread_id: str) -> None:+ from storage import studio_db+ try:+ studio_db.delete_chat_threads([thread_id])+ except Exception:+ logger.exception("scheduled_tasks.discard_chat_failed")+++class ScheduledTaskScheduler:+ def __init__(self, app: Any) -> None:+ _schedulers.add(self)+ self.app = app+ self.worker_id = uuid.uuid4().hex+ self._task: Optional[asyncio.Task] = None+ self._loop: Optional[asyncio.AbstractEventLoop] = None+ # Made in start(): an asyncio.Event is bound to its loop, and a second lifespan may run on another.+ self._wake: Optional[asyncio.Event] = None+ self._stopping = False+ self._active: Optional[_ActiveRun] = None+ self._last_account: Optional[str] = None+ self._due: Optional[int] = None++ def start(self) -> None:+ if self._task is not None:+ return+ self._stopping = False+ self._loop = asyncio.get_running_loop()+ self._wake = asyncio.Event()+ self._task = asyncio.create_task(self._run_loop(), name = "scheduled-task-scheduler")++ async def stop(self) -> None:+ self._stopping = True+ self.wake()+ active = self._active+ if active is not None:+ active.cancel_event.set()+ task, self._task = self._task, None+ if task is None:+ return+ done, _ = await asyncio.wait({task}, timeout = _STOP_GRACE_SECONDS)+ if not done:+ task.cancel()+ await asyncio.wait({task}, timeout = _STOP_GRACE_SECONDS)++ def wake(self) -> None:+ """Re-check what is due now. Safe from any thread: sync routes run in a pool."""+ loop, event = self._loop, self._wake+ if loop is None or event is None or loop.is_closed():+ return+ with contextlib.suppress(RuntimeError):+ loop.call_soon_threadsafe(event.set)++ def cancel_task_run(+ self,+ task_id: str,+ account_id: Optional[str] = None,+ ) -> None:+ active = self._active+ account_id = current_account_id() if account_id is None else account_id+ if active is not None and active.task_id == task_id and active.account_id == account_id:+ active.cancel_event.set()++ def cancel_account(self, account_id: str) -> None:+ active = self._active+ if active is not None and active.account_id == account_id:+ active.cancel_event.set()++ async def _run_loop(self) -> None:+ while not self._stopping:+ # Cleared before looking, so a wake that lands while this pass runs is not lost.+ self._wake.clear()+ try:+ claimed = await asyncio.to_thread(self._claim)+ if claimed is not None:+ account, task, run = claimed+ # Shutdown began after the claim: give it back. Past here nothing awaits before the run is active.+ if self._stopping:+ await asyncio.to_thread(self._release, account, task, run)+ return+ await arun_as(account, self._execute(account, task, run))+ continue+ # Sleep until the next run is due (APScheduler, Celery beat); wake() cuts it short on any change.+ delay = _POLL_SECONDS+ if self._due is not None:+ delay = min(delay, max(_MIN_SLEEP_SECONDS, (self._due - db.now_ms()) / 1000))+ except asyncio.CancelledError:+ raise+ except Exception:+ # Never escape the loop: that would stop every schedule for the life of the process.+ logger.exception("scheduled_tasks.loop_iteration_failed")+ delay = 5.0+ if self._stopping:+ return+ with contextlib.suppress(asyncio.TimeoutError):+ await asyncio.wait_for(self._wake.wait(), timeout = delay)++ async def _yield_to_inference(self, cancel_event: threading.Event) -> None:+ from core.inference.llama_keepwarm import inference_in_flight+ deadline = asyncio.get_running_loop().time() + _YIELD_SECONDS+ while (+ inference_in_flight()+ and not cancel_event.is_set()+ and not self._stopping+ and asyncio.get_running_loop().time() < deadline+ ):+ await asyncio.sleep(_YIELD_POLL_SECONDS)++ def _accounts(self) -> list[AccountContext]:+ accounts = job_accounts()+ for index, account in enumerate(accounts):+ if account.account_id == self._last_account:+ return accounts[index + 1 :] + accounts[: index + 1]+ return accounts++ def _claim(self) -> Optional[tuple[AccountContext, dict, dict]]:+ """One pass, one read per account: claim the next due run, else note in ``_due`` when one is."""+ now = db.now_ms()+ self._due = None+ for account in self._accounts():+ if self._stopping:+ return None+ try:+ claimed, due = run_as(+ account, db.poll, now, now - _STALE_RUN_MS, self.worker_id, next_run_for+ )+ except Exception:+ logger.exception("scheduled_tasks.claim_failed_for_account")+ continue+ if claimed is not None:+ # stop() cannot cancel this thread, so give the claim back here; its occurrence runs at next start.+ if self._stopping:+ self._release(account, *claimed)+ return None+ self._last_account = account.account_id+ return (account, *claimed)+ if due is not None and (self._due is None or due < self._due):+ self._due = due+ return None++ def _release(self, account: AccountContext, task: dict, run: dict) -> None:+ try:+ run_as(account, db.release_claim, run["id"], self.worker_id, task["nextRunAt"])+ except Exception:+ logger.exception("scheduled_tasks.release_failed")++ async def _heartbeat(self, run_id: str) -> None:+ while True:+ await asyncio.sleep(_HEARTBEAT_SECONDS)+ with contextlib.suppress(Exception):+ await asyncio.to_thread(db.heartbeat, run_id, self.worker_id)++ async def _execute(self, account: AccountContext, task: dict, run: dict) -> None:+ cancel_event = threading.Event()+ self._active = _ActiveRun(account.account_id, task["id"], run["id"], cancel_event)+ heartbeat = asyncio.create_task(self._heartbeat(run["id"]))+ started_at = run["startedAt"] or db.now_ms()+ outcome: dict[str, Any] = {"status": "failed"}+ saving = False+ try:+ if not await asyncio.to_thread(self._still_wanted, account, task["id"]):+ outcome = {"status": "failed", "error_code": "cancelled"}+ return+ if run.get("source") == "schedule":+ await self._yield_to_inference(cancel_event)+ if cancel_event.is_set():+ raise RunFailed("cancelled")+ answer = await generate_answer(self.app, task, run, cancel_event)+ if not await asyncio.to_thread(db.task_exists, task["id"]):+ return+ saving = True+ thread_id = await asyncio.to_thread(+ save_chat, task, run, answer, started_at, db.now_ms()+ )+ outcome = {"status": "succeeded", "thread_id": thread_id, "model": answer.model}+ except RunFailed as failure:+ if self._stopping and failure.code == "cancelled":+ failure = RunFailed("interrupted")+ outcome = {+ "status": "failed",+ "error_code": failure.code,+ "error": failure.message,+ }+ except asyncio.CancelledError:+ if _loop_cancelled(asyncio.current_task(), self._stopping):+ outcome = {"status": "failed", "error_code": "interrupted"}+ raise+ # This run's own cancel (the unload gate raises it while waiting): ends the run, not the loop.+ outcome = {+ "status": "failed",+ "error_code": "interrupted" if self._stopping else "cancelled",+ }+ except Exception as exc:+ logger.exception("scheduled_tasks.run_failed")+ outcome = {"status": "failed", "error": _error_text(str(exc))}+ finally:+ heartbeat.cancel()+ self._active = None+ # A chat stands only for a succeeded run; a failure removes it in the same transaction.+ discard = saving and outcome["status"] != "succeeded"+ settled = await self._settle(run["id"], {**outcome, "discard_chat": discard})+ if saving and settled is not True:+ await asyncio.to_thread(_discard_chat, db.chat_id_for_run(run["id"]))++ @staticmethod+ def _still_wanted(account: AccountContext, task_id: str) -> bool:+ return db.task_exists(task_id) and any(+ entry.account_id == account.account_id for entry in job_accounts()+ )++ async def _settle(self, run_id: str, outcome: dict[str, Any]) -> Optional[bool]:+ for attempt in range(_SETTLE_ATTEMPTS):+ try:+ return await asyncio.to_thread(db.finish_run, run_id, self.worker_id, **outcome)+ except Exception:+ logger.exception("scheduled_tasks.finish_failed")+ if attempt + 1 < _SETTLE_ATTEMPTS:+ await asyncio.sleep(_SETTLE_RETRY_SECONDS)+ return Nonediff --git a/studio/backend/core/training/account_jobs.py b/studio/backend/core/training/account_jobs.pyindex a20a8faecea..dbe71367a0c 100644--- a/studio/backend/core/training/account_jobs.py+++ b/studio/backend/core/training/account_jobs.py@@ -463,6 +463,7 @@ def retire_account_jobs(account: AccountContext) -> None:)from core.rag import folder_sync, ingestion, reembedfrom core.research_runs import retire_account_research+ from core.scheduled_tasks.scheduler import retire_account_scheduled_tasksfrom routes.inference import retire_stt_downloadsfor cancel in (@@ -473,6 +474,7 @@ def retire_account_jobs(account: AccountContext) -> None:reembed.retire_account_reembed,folder_sync.retire_account_sync,lambda: retire_account_research(account),+ lambda: retire_account_scheduled_tasks(account),):try:run_as(account, cancel)diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 28b56c265ae..738b22f970f 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -452,6 +452,7 @@ from routes.sandbox_capability import router as sandbox_capability_routerfrom routes.systemone import MCP_PATH as DECISIONS_MCP_PATH, RequireStudioAuth, decisions_mcpfrom routes.systemone import router as systemone_routerfrom routes.prompts import router as prompts_router+from routes.scheduled_tasks import router as scheduled_tasks_routerfrom routes.library import router as library_routerfrom routes.profile_stats import router as profile_stats_routerfrom auth import policy as auth_policy, storage@@ -1013,6 +1014,11 @@ async def lifespan(app: FastAPI):except Exception as exc:_lifespan_log.warning("re-arming unattended research runs failed: %s", exc)+ from core.scheduled_tasks.scheduler import ScheduledTaskScheduler++ app.state.scheduled_task_scheduler = ScheduledTaskScheduler(app)+ app.state.scheduled_task_scheduler.start()+from core.inference.chat_generation_runs import ChatGenerationSupervisorapp.state.chat_generation_supervisor = ChatGenerationSupervisor(app)@@ -1135,6 +1141,10 @@ async def lifespan(app: FastAPI):if _research_supervisor is not None:await _research_supervisor.stop()+ _scheduled_task_scheduler = getattr(app.state, "scheduled_task_scheduler", None)+ if _scheduled_task_scheduler is not None:+ await _scheduled_task_scheduler.stop()+_chat_generation_supervisor = getattr(app.state, "chat_generation_supervisor", None)if _chat_generation_supervisor is not None:await _chat_generation_supervisor.stop()@@ -1982,6 +1992,7 @@ app.include_router(sandbox_capability_router, prefix = "/api/sandbox", tags = ["app.include_router(mcp_servers_router, prefix = "/api/mcp/servers", tags = ["mcp"])app.include_router(skills_router, prefix = "/api/skills", tags = ["skills"])app.include_router(prompts_router, prefix = "/api/prompts", tags = ["prompts"])+app.include_router(scheduled_tasks_router, prefix = "/api/scheduled-tasks", tags = ["scheduled-tasks"])app.include_router(library_router, prefix = "/api/library", tags = ["library"])app.include_router(profile_stats_router, prefix = "/api/profile", tags = ["profile"])app.include_router(datasets_router, prefix = "/api/datasets", tags = ["datasets"])diff --git a/studio/backend/routes/accounts.py b/studio/backend/routes/accounts.pyindex ecf14966657..425503742ad 100644--- a/studio/backend/routes/accounts.py+++ b/studio/backend/routes/accounts.py@@ -169,11 +169,14 @@ def set_account_active(account_id: str, payload: AccountActiveRequest):restore_account_clients(account_id)active_generations.lift_fence(account_id)else:+ from core.scheduled_tasks.scheduler import cancel_account_runsfrom routes.inference import retire_account_loads# Fence first, so a request registering after the sweep is cancelled too.active_generations.fence(account_id)active_generations.cancel_all(account_id)+ # A scheduled run still waiting for the model gate has not registered yet.+ cancel_account_runs(account_id)retire_account_loads(account_id)account_access.retire_resident_shares(account_id)return resultdiff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 97a284b2f09..c61d801ce10 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -194,6 +194,8 @@ class ChatThread(BaseModel):forkedFromMessageId: Optional[str] = NoneforkBoundaryMessageId: Optional[str] = NoneforkTitleBase: Optional[str] = None+ # Server-set: the scheduled task whose run made this chat.+ scheduledTaskId: Optional[str] = None# Server-set on rename, move or (un)archive.modifiedAt: Optional[int] = Nonesettings: Optional[ChatThreadSettings] = None@@ -402,6 +404,7 @@ class ChatSidebarRow(BaseModel):modifiedAt: Optional[int] = NonemodelIds: Optional[list[str]] = NoneisFork: Optional[bool] = None+ isScheduled: Optional[bool] = NonethreadTitles: Optional[list[str]] = NoneprojectId: Optional[str] = Nonediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 013593afad3..7362a8247b7 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -9768,6 +9768,8 @@ def _llama_status_checkpoint_id(llama_backend) -> Optional[str]:_DISABLE_OPENAI_AUTO_SWITCH_SCOPE_KEY = "_unsloth_disable_openai_auto_switch"+# Routes a named model to the slot already serving it but never loads one (scheduled runs).+LOADED_MODELS_ONLY_SCOPE_KEY = "_unsloth_loaded_models_only"# Sentinel a raw-body endpoint passes when the request omits ``model``: it must# only restore an idle-freed model, never run the resolver (so a downloaded GGUF# literally named "default" can't be swapped to). The NUL keeps it off any index.@@ -11953,6 +11955,19 @@ async def _maybe_auto_switch_model(# pinned preview checkpoint it just loaded.if _auto_switch_opted_out(fastapi_request):return+ if (+ named_model+ and isinstance(_swap_scope, dict)+ and _swap_scope.get(LOADED_MODELS_ONLY_SCOPE_KEY)+ ):+ # A named model not routed to a kept slot: only the resident may answer, under the same+ # access check. An omitted one (the reload-only sentinel) keeps the path below.+ if not await asyncio.to_thread(_loaded_identity_satisfies, named_model):+ raise HTTPException(status_code = 404, detail = "Model not found")+ await _refuse_foreign_resident()+ if claim_resident:+ _claim_slot_for_non_preview(fastapi_request)+ returnauto_switch_on = get_openai_auto_switch_enabled()def _refuse_non_gguf_endpoint() -> None:diff --git a/studio/backend/routes/scheduled_tasks.py b/studio/backend/routes/scheduled_tasks.pynew file mode 100644index 00000000000..2b73002f1d1--- /dev/null+++ b/studio/backend/routes/scheduled_tasks.py@@ -0,0 +1,276 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Scheduled tasks: a prompt that runs on a schedule and posts the answer to a new chat."""++from __future__ import annotations++import uuid+from typing import Annotated, Literal, Optional++from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response+from pydantic import AfterValidator, BaseModel, ConfigDict, Field++from auth.authentication import authenticated_via_api_key, get_current_subject+from core.scheduled_tasks.schedule import InvalidSchedule, Schedule+from core.scheduled_tasks.scheduler import next_run_for+from storage import scheduled_tasks_db as db++router = APIRouter()++_NOT_FOUND = "Scheduled task not found"+++def _not_blank(value: str) -> str:+ value = value.strip()+ if not value:+ raise ValueError("must not be blank")+ return value+++Title = Annotated[str, Field(max_length = 120), AfterValidator(_not_blank)]+Prompt = Annotated[str, Field(max_length = 20_000), AfterValidator(_not_blank)]+TimeZoneName = Annotated[str, Field(max_length = 64)]+# Which finished runs get a toast and system notification; every run's chat still shows unread in Recents.+Notify = Literal["all", "failures", "none"]+ProjectId = Annotated[str, Field(max_length = 128), AfterValidator(_not_blank)]+# Fields an update may set back to null, unlike the rest, where null means unchanged.+_CLEARABLE = ("projectId",)+++class ScheduledTaskCreate(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ title: Title+ prompt: Prompt+ schedule: Schedule+ timezone: TimeZoneName+ enabled: bool = True+ notify: Notify = "all"+ named: bool = True+ archiveSuccessful: bool = False+ projectId: Optional[ProjectId] = None+++class ScheduledTaskUpdate(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ title: Optional[Title] = None+ prompt: Optional[Prompt] = None+ schedule: Optional[Schedule] = None+ timezone: Optional[TimeZoneName] = None+ enabled: Optional[bool] = None+ notify: Optional[Notify] = None+ named: Optional[bool] = None+ archiveSuccessful: Optional[bool] = None+ projectId: Optional[ProjectId] = None+++class ScheduledTaskRun(BaseModel):+ id: str+ taskId: str+ source: Literal["schedule", "manual"]+ status: Literal["queued", "running", "succeeded", "failed"]+ scheduledFor: Optional[int] = None+ createdAt: int+ startedAt: Optional[int] = None+ finishedAt: Optional[int] = None+ threadId: Optional[str] = None+ model: Optional[str] = None+ # no_model, timeout, cancelled, interrupted or empty.+ errorCode: Optional[str] = None+ error: Optional[str] = None+++class FinishedScheduledTaskRun(ScheduledTaskRun):+ taskTitle: str+ taskNotify: Notify+++class ScheduledTask(BaseModel):+ id: str+ title: str+ prompt: str+ schedule: Schedule+ timezone: str+ enabled: bool+ notify: Notify+ named: bool+ archiveSuccessful: bool = False+ projectId: Optional[str] = None+ status: Literal["active", "paused", "completed"]+ nextRunAt: Optional[int] = None+ createdAt: int+ updatedAt: int+ lastRun: Optional[ScheduledTaskRun] = None+++class ScheduledTaskList(BaseModel):+ tasks: list[ScheduledTask]+ # Server clock (nextRunAt and run times use it); clients time refreshes from it.+ now: int+++class ScheduledTaskActivity(BaseModel):+ now: int+ runs: list[FinishedScheduledTaskRun]+ more: bool = False+ activeRuns: int+ nextRunAt: Optional[int] = None+++def _response(task: dict) -> dict:+ status = (+ "paused" if not task["enabled"] else "completed" if task["nextRunAt"] is None else "active"+ )+ return {**task, "status": status}+++def _existing_project(project_id: Optional[str]) -> Optional[str]:+ from storage import studio_db+ if project_id is not None and studio_db.get_chat_project(project_id) is None:+ raise HTTPException(status_code = 400, detail = "Project not found")+ return project_id+++def _next_run(task: dict, now: int) -> Optional[int]:+ try:+ following = next_run_for(task, now)+ except InvalidSchedule as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None+ if following is None and task["enabled"]:+ raise HTTPException(status_code = 400, detail = "Pick a time in the future.")+ return following if task["enabled"] else None+++def _require_ui_session(via_api_key: bool) -> None:+ """Tasks run as the account: signed-in users only, never API keys."""+ if via_api_key:+ raise HTTPException(+ status_code = 403,+ detail = "Scheduled tasks can only be changed from the Unsloth app, not with an API key.",+ )+++def _wake_scheduler(request: Request) -> None:+ scheduler = getattr(request.app.state, "scheduled_task_scheduler", None)+ if scheduler is not None:+ scheduler.wake()++[email protected]("", response_model = ScheduledTaskList)+def list_scheduled_tasks(current_subject: str = Depends(get_current_subject)):+ return {"tasks": [_response(task) for task in db.list_tasks()], "now": db.now_ms()}++[email protected]("", status_code = 201, response_model = ScheduledTask)+def create_scheduled_task(+ payload: ScheduledTaskCreate,+ request: Request,+ current_subject: str = Depends(get_current_subject),+ via_api_key: bool = Depends(authenticated_via_api_key),+):+ _require_ui_session(via_api_key)+ now = db.now_ms()+ task = {+ "id": str(uuid.uuid4()),+ "ownerSubject": current_subject,+ "title": payload.title,+ "prompt": payload.prompt,+ "schedule": payload.schedule.model_dump(),+ "timezone": payload.timezone,+ "enabled": payload.enabled,+ "notify": payload.notify,+ "named": payload.named,+ "archiveSuccessful": payload.archiveSuccessful,+ "projectId": _existing_project(payload.projectId),+ "createdAt": now,+ "updatedAt": now,+ }+ task["nextRunAt"] = _next_run(task, now)+ try:+ created = db.create_task(task)+ except db.TaskLimitReached:+ raise HTTPException(+ status_code = 409,+ detail = f"You can have up to {db.MAX_TASKS} scheduled tasks. Delete one to add another.",+ ) from None+ _wake_scheduler(request)+ return _response(created)+++# Declared ahead of /{task_id} so "runs" is never read as a task id.[email protected]("/runs", response_model = ScheduledTaskActivity)+def scheduled_task_activity(+ since: Optional[int] = Query(default = None, ge = 0),+ current_subject: str = Depends(get_current_subject),+):+ """Runs finished since ``since`` (ms), for a client that notifies when results arrive."""+ return {"now": db.now_ms(), **db.activity(since)}++[email protected]("/{task_id}", response_model = ScheduledTask)+def get_scheduled_task(task_id: str, current_subject: str = Depends(get_current_subject)):+ task = db.get_task(task_id)+ if task is None:+ raise HTTPException(status_code = 404, detail = _NOT_FOUND)+ return _response(task)++[email protected]("/{task_id}", response_model = ScheduledTask)+def update_scheduled_task(+ task_id: str,+ payload: ScheduledTaskUpdate,+ request: Request,+ current_subject: str = Depends(get_current_subject),+ via_api_key: bool = Depends(authenticated_via_api_key),+):+ _require_ui_session(via_api_key)+ changes = payload.model_dump(exclude_unset = True, exclude_none = True)+ changes.update(+ {key: getattr(payload, key) for key in _CLEARABLE if key in payload.model_fields_set}+ )+ if changes.get("projectId") is not None:+ _existing_project(changes["projectId"])+ now = db.now_ms()+ # Only on schedule, time zone or enabled changes: a rename or resent value keeps an overdue run due.+ updated = db.update_task(task_id, changes, lambda task: _next_run(task, now))+ if updated is None:+ raise HTTPException(status_code = 404, detail = _NOT_FOUND)+ _wake_scheduler(request)+ return _response(updated)++[email protected]("/{task_id}", status_code = 204, response_class = Response)+def delete_scheduled_task(+ task_id: str,+ request: Request,+ current_subject: str = Depends(get_current_subject),+ via_api_key: bool = Depends(authenticated_via_api_key),+):+ _require_ui_session(via_api_key)+ if not db.delete_task(task_id):+ raise HTTPException(status_code = 404, detail = _NOT_FOUND)+ scheduler = getattr(request.app.state, "scheduled_task_scheduler", None)+ if scheduler is not None:+ scheduler.cancel_task_run(task_id)+ return Response(status_code = 204)++[email protected]("/{task_id}/run", status_code = 202, response_model = ScheduledTaskRun)+def run_scheduled_task_now(+ task_id: str,+ request: Request,+ current_subject: str = Depends(get_current_subject),+ via_api_key: bool = Depends(authenticated_via_api_key),+):+ """Queue a run outside the schedule; the next scheduled run is unaffected."""+ _require_ui_session(via_api_key)+ try:+ run = db.request_run(task_id)+ except db.TaskRunActive:+ raise HTTPException(status_code = 409, detail = "This task is already running.") from None+ if run is None:+ raise HTTPException(status_code = 404, detail = _NOT_FOUND)+ _wake_scheduler(request)+ return rundiff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex b5caa2be215..da3df81bcf4 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -4789,6 +4789,7 @@ SIDEBAR_NAV_ITEM_DEFAULTS = {"recipes": False,"export": False,"api": False,+ "tasks": False,}MAX_SIDEBAR_NAV_INPUT_ITEMS = 4 * len(SIDEBAR_NAV_ITEM_DEFAULTS)@@ -4831,6 +4832,7 @@ SidebarNavItemId = Literal["recipes","export","api",+ "tasks",]diff --git a/studio/backend/storage/scheduled_tasks_db.py b/studio/backend/storage/scheduled_tasks_db.pynew file mode 100644index 00000000000..844344d5d21--- /dev/null+++ b/studio/backend/storage/scheduled_tasks_db.py@@ -0,0 +1,523 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Scheduled tasks and their runs in the account's studio.db."""++from __future__ import annotations++import json+import sqlite3+import time+import uuid+from contextlib import contextmanager+from typing import Callable, Iterator, Optional++from storage.studio_db import delete_chat_threads_in, get_connection++# Per account. Every run opens a chat, so this also bounds how many chats schedules can make.+MAX_TASKS = 100+RUN_HISTORY_LIMIT = 20++_ACTIVE = "('queued', 'running')"+_NO_ACTIVE_RUN = (+ "NOT EXISTS (SELECT 1 FROM scheduled_task_runs r"+ f" WHERE r.task_id = t.id AND r.status IN {_ACTIVE})"+)+_DUE_TASK = (+ f"t.enabled = 1 AND t.next_run_at IS NOT NULL AND t.next_run_at <= ? AND {_NO_ACTIVE_RUN}"+)+++class TaskLimitReached(Exception):+ pass+++class TaskRunActive(Exception):+ """The task already has a run queued or in progress."""+++# Any fixed value: it only keeps run chat ids apart from every other uuid5.+_RUN_CHAT_NAMESPACE = uuid.UUID("5b0e7a1e-36a4-4a39-9c1f-2f6d3c8e9a41")+++@contextmanager+def _connect(begin: Optional[str] = None) -> Iterator[sqlite3.Connection]:+ """One connection: commits what the block wrote, rolls back on any exception."""+ conn = get_connection()+ try:+ if begin:+ conn.execute(begin)+ yield conn+ if conn.in_transaction:+ conn.commit()+ except BaseException:+ conn.rollback()+ raise+ finally:+ conn.close()+++def now_ms() -> int:+ return int(time.time() * 1000)+++def chat_id_for_run(run_id: str) -> str:+ """The run's chat id, derived from the run so an unsettled run's chat can still be found."""+ return str(uuid.uuid5(_RUN_CHAT_NAMESPACE, run_id))+++def _task_from_row(row: sqlite3.Row) -> dict:+ return {+ "id": row["id"],+ "ownerSubject": row["owner_subject"],+ "title": row["title"],+ "prompt": row["prompt"],+ "schedule": json.loads(row["schedule_json"]),+ "timezone": row["timezone"],+ "enabled": bool(row["enabled"]),+ "notify": row["notify"],+ "named": bool(row["named"]),+ "archiveSuccessful": bool(row["archive_successful"]),+ "projectId": row["project_id"],+ "nextRunAt": row["next_run_at"],+ "createdAt": row["created_at"],+ "updatedAt": row["updated_at"],+ }+++def _run_from_row(row: sqlite3.Row) -> dict:+ return {+ "id": row["id"],+ "taskId": row["task_id"],+ "source": row["source"],+ "status": row["status"],+ "scheduledFor": row["scheduled_for"],+ "createdAt": row["created_at"],+ "startedAt": row["started_at"],+ "finishedAt": row["finished_at"],+ "threadId": row["thread_id"],+ "model": row["model"],+ "errorCode": row["error_code"],+ "error": row["error"],+ }+++def _latest_runs(conn: sqlite3.Connection, task_ids: list[str]) -> dict[str, dict]:+ if not task_ids:+ return {}+ rows = conn.execute(+ f"""+ SELECT * FROM scheduled_task_runs WHERE rowid IN (+ SELECT (+ SELECT r.rowid FROM scheduled_task_runs r WHERE r.task_id = t.id+ ORDER BY r.created_at DESC, r.rowid DESC LIMIT 1+ )+ FROM scheduled_tasks t WHERE t.id IN ({", ".join("?" for _ in task_ids)})+ )+ """,+ task_ids,+ ).fetchall()+ return {row["task_id"]: _run_from_row(row) for row in rows}+++def _with_last_run(conn: sqlite3.Connection, tasks: list[dict]) -> list[dict]:+ latest = _latest_runs(conn, [task["id"] for task in tasks])+ for task in tasks:+ task["lastRun"] = latest.get(task["id"])+ return tasks+++def _get_task(conn: sqlite3.Connection, task_id: str) -> Optional[dict]:+ row = conn.execute("SELECT * FROM scheduled_tasks WHERE id = ?", (task_id,)).fetchone()+ return None if row is None else _with_last_run(conn, [_task_from_row(row)])[0]+++def list_tasks() -> list[dict]:+ with _connect("BEGIN") as conn:+ rows = conn.execute(+ "SELECT * FROM scheduled_tasks ORDER BY created_at DESC, rowid DESC"+ ).fetchall()+ return _with_last_run(conn, [_task_from_row(row) for row in rows])+++def get_task(task_id: str) -> Optional[dict]:+ with _connect("BEGIN") as conn:+ return _get_task(conn, task_id)+++# The columns create and update both write, in _task_values order.+_TASK_COLUMNS = (+ "title",+ "prompt",+ "schedule_json",+ "timezone",+ "enabled",+ "notify",+ "named",+ "archive_successful",+ "project_id",+ "next_run_at",+)+++def _task_values(task: dict) -> tuple:+ return (+ task["title"],+ task["prompt"],+ json.dumps(task["schedule"]),+ task["timezone"],+ 1 if task["enabled"] else 0,+ task["notify"],+ 1 if task["named"] else 0,+ 1 if task.get("archiveSuccessful") else 0,+ task.get("projectId"),+ task["nextRunAt"],+ )+++def create_task(task: dict) -> dict:+ with _connect("BEGIN IMMEDIATE") as conn:+ (count,) = conn.execute("SELECT COUNT(*) FROM scheduled_tasks").fetchone()+ if count >= MAX_TASKS:+ raise TaskLimitReached()+ conn.execute(+ f"INSERT INTO scheduled_tasks (id, owner_subject, created_at, {', '.join(_TASK_COLUMNS)},"+ f" updated_at) VALUES ({', '.join('?' * (len(_TASK_COLUMNS) + 4))})",+ (+ task["id"],+ task["ownerSubject"],+ task["createdAt"],+ *_task_values(task),+ task["updatedAt"],+ ),+ )+ return _get_task(conn, task["id"])+++# What decides when a task runs; any other change keeps its next run, an overdue one included.+_TIMING_FIELDS = ("schedule", "timezone", "enabled")+++def update_task(+ task_id: str,+ changes: dict,+ reschedule: Optional[Callable[[dict], Optional[int]]] = None,+) -> Optional[dict]:+ """Apply ``changes``; ``reschedule`` returns the next run time in the same transaction (raising rolls back)."""+ with _connect("BEGIN IMMEDIATE") as conn:+ row = conn.execute("SELECT * FROM scheduled_tasks WHERE id = ?", (task_id,)).fetchone()+ if row is None:+ return None+ stored = _task_from_row(row)+ task = {**stored, **changes}+ if reschedule is not None and any(task[key] != stored[key] for key in _TIMING_FIELDS):+ task["nextRunAt"] = reschedule(task)+ conn.execute(+ f"UPDATE scheduled_tasks SET {', '.join(f'{column} = ?' for column in _TASK_COLUMNS)},"+ " updated_at = ? WHERE id = ?",+ (*_task_values(task), now_ms(), task_id),+ )+ return _get_task(conn, task_id)+++def delete_task(task_id: str) -> bool:+ """Delete a task and its run history; finished runs' chats stay, an in-progress run's chat goes too."""+ with _connect("BEGIN IMMEDIATE") as conn:+ running = conn.execute(+ "SELECT id FROM scheduled_task_runs WHERE task_id = ? AND status = 'running'",+ (task_id,),+ ).fetchall()+ if running:+ delete_chat_threads_in(conn, [chat_id_for_run(row["id"]) for row in running])+ cursor = conn.execute("DELETE FROM scheduled_tasks WHERE id = ?", (task_id,))+ return cursor.rowcount > 0+++def request_run(task_id: str) -> Optional[dict]:+ """Queue a run now, outside the schedule. None when the task does not exist."""+ with _connect("BEGIN IMMEDIATE") as conn:+ if (+ conn.execute("SELECT 1 FROM scheduled_tasks WHERE id = ?", (task_id,)).fetchone()+ is None+ ):+ return None+ active = conn.execute(+ f"SELECT 1 FROM scheduled_task_runs WHERE task_id = ? AND status IN {_ACTIVE}",+ (task_id,),+ ).fetchone()+ if active is not None:+ raise TaskRunActive()+ run_id = str(uuid.uuid4())+ conn.execute(+ "INSERT INTO scheduled_task_runs"+ " (id, task_id, source, status, created_at)"+ " VALUES (?, ?, 'manual', 'queued', ?)",+ (run_id, task_id, now_ms()),+ )+ row = conn.execute("SELECT * FROM scheduled_task_runs WHERE id = ?", (run_id,)).fetchone()+ return _run_from_row(row)+++_STALE_RUN = "status = 'running' AND COALESCE(heartbeat_at, started_at, created_at) < ?"+++def _state(+ conn: sqlite3.Connection, now: int, stale_before: Optional[int]+) -> tuple[bool, Optional[int]]:+ """(stale runs to fail, when the next run is due: ``now`` for a queued one), in one read."""+ stale, queued, due = conn.execute(+ f"SELECT ? IS NOT NULL AND EXISTS (SELECT 1 FROM scheduled_task_runs WHERE {_STALE_RUN}),"+ " EXISTS (SELECT 1 FROM scheduled_task_runs WHERE status = 'queued'),"+ " (SELECT MIN(t.next_run_at) FROM scheduled_tasks t"+ f" WHERE t.enabled = 1 AND t.next_run_at IS NOT NULL AND {_NO_ACTIVE_RUN})",+ (stale_before, stale_before),+ ).fetchone()+ return bool(stale), now if queued else due+++def poll(+ now: int,+ stale_before: Optional[int],+ worker_id: str,+ next_run_after: Callable[[dict, int], Optional[int]],+) -> tuple[Optional[tuple[dict, dict]], Optional[int]]:+ """A scheduler pass on one connection: fail stale runs, claim what is due, and say when the next run is due.++ Reads first, so an idle pass never takes the writer lock."""+ with _connect() as conn:+ stale, due = _state(conn, now, stale_before)+ if stale:+ conn.execute("BEGIN IMMEDIATE")+ _fail_stale(conn, stale_before)+ conn.commit()+ _stale, due = _state(conn, now, None)+ if due is None or due > now:+ return None, due+ conn.execute("BEGIN IMMEDIATE")+ return _claim(conn, now, worker_id, next_run_after), due+++def claim_next(+ now: int, worker_id: str, next_run_after: Callable[[dict, int], Optional[int]]+) -> Optional[tuple[dict, dict]]:+ """Claim the next run (queued Run now first, then most overdue); missed occurrences collapse into one."""+ return poll(now, None, worker_id, next_run_after)[0]+++def _claim(+ conn: sqlite3.Connection,+ now: int,+ worker_id: str,+ next_run_after: Callable[[dict, int], Optional[int]],+) -> Optional[tuple[dict, dict]]:+ queued = conn.execute(+ "SELECT * FROM scheduled_task_runs WHERE status = 'queued'"+ " ORDER BY created_at, rowid LIMIT 1"+ ).fetchone()+ if queued is not None:+ conn.execute(+ "UPDATE scheduled_task_runs"+ " SET status = 'running', started_at = ?, heartbeat_at = ?, worker_id = ?"+ " WHERE id = ?",+ (now, now, worker_id, queued["id"]),+ )+ task_id, run_id = queued["task_id"], queued["id"]+ else:+ task_row = conn.execute(+ f"SELECT * FROM scheduled_tasks t WHERE {_DUE_TASK}"+ " ORDER BY t.next_run_at, t.created_at LIMIT 1",+ (now,),+ ).fetchone()+ if task_row is None:+ return None+ task = _task_from_row(task_row)+ try:+ following = next_run_after(task, max(now, task["nextRunAt"]))+ except Exception:+ # A schedule that no longer resolves runs once, then waits for an edit instead of firing every poll.+ following = None+ task_id, run_id = task["id"], str(uuid.uuid4())+ conn.execute(+ """+ INSERT INTO scheduled_task_runs+ (id, task_id, source, status, scheduled_for, created_at, started_at,+ heartbeat_at, worker_id)+ VALUES (?, ?, 'schedule', 'running', ?, ?, ?, ?, ?)+ """,+ (run_id, task_id, task["nextRunAt"], now, now, now, worker_id),+ )+ conn.execute(+ "UPDATE scheduled_tasks SET next_run_at = ? WHERE id = ?", (following, task_id)+ )+ task_row = conn.execute("SELECT * FROM scheduled_tasks WHERE id = ?", (task_id,)).fetchone()+ run_row = conn.execute("SELECT * FROM scheduled_task_runs WHERE id = ?", (run_id,)).fetchone()+ return _task_from_row(task_row), _run_from_row(run_row)+++def release_claim(run_id: str, worker_id: str, claimed_next_run_at: Optional[int]) -> bool:+ """Undo a claim that will not run; False when the run is no longer this worker's to give back."""+ with _connect("BEGIN IMMEDIATE") as conn:+ run = conn.execute(+ "SELECT * FROM scheduled_task_runs WHERE id = ? AND worker_id = ? AND status = 'running'",+ (run_id, worker_id),+ ).fetchone()+ if run is None:+ return False+ if run["source"] == "manual":+ conn.execute(+ "UPDATE scheduled_task_runs"+ " SET status = 'queued', started_at = NULL, heartbeat_at = NULL, worker_id = NULL"+ " WHERE id = ?",+ (run_id,),+ )+ else:+ conn.execute("DELETE FROM scheduled_task_runs WHERE id = ?", (run_id,))+ conn.execute(+ "UPDATE scheduled_tasks SET next_run_at = ?"+ " WHERE id = ? AND enabled = 1 AND next_run_at IS ?",+ (run["scheduled_for"], run["task_id"], claimed_next_run_at),+ )+ return True+++def heartbeat(run_id: str, worker_id: str) -> bool:+ with _connect() as conn:+ cursor = conn.execute(+ "UPDATE scheduled_task_runs SET heartbeat_at = ?"+ " WHERE id = ? AND worker_id = ? AND status = 'running'",+ (now_ms(), run_id, worker_id),+ )+ return cursor.rowcount > 0+++def task_exists(task_id: str) -> bool:+ with _connect() as conn:+ return (+ conn.execute("SELECT 1 FROM scheduled_tasks WHERE id = ?", (task_id,)).fetchone()+ is not None+ )+++def _trim_history(conn: sqlite3.Connection, task_id: str) -> None:+ """Drop the task's finished runs past the newest RUN_HISTORY_LIMIT."""+ conn.execute(+ f"""+ DELETE FROM scheduled_task_runs+ WHERE task_id = ? AND status NOT IN {_ACTIVE} AND rowid NOT IN (+ SELECT rowid FROM scheduled_task_runs+ WHERE task_id = ? AND status NOT IN {_ACTIVE}+ ORDER BY created_at DESC, rowid DESC LIMIT ?+ )+ """,+ (task_id, task_id, RUN_HISTORY_LIMIT),+ )+++def finish_run(+ run_id: str,+ worker_id: str,+ *,+ status: str,+ thread_id: Optional[str] = None,+ model: Optional[str] = None,+ error_code: Optional[str] = None,+ error: Optional[str] = None,+ discard_chat: bool = False,+) -> bool:+ """Settle a run this worker owns and trim history; ``discard_chat`` removes a failed run's chat atomically."""+ with _connect("BEGIN IMMEDIATE") as conn:+ row = conn.execute(+ "SELECT task_id FROM scheduled_task_runs"+ " WHERE id = ? AND worker_id = ? AND status = 'running'",+ (run_id, worker_id),+ ).fetchone()+ if row is None:+ return False+ if discard_chat:+ delete_chat_threads_in(conn, [chat_id_for_run(run_id)])+ # The chat can already be gone; the foreign key would refuse the whole update.+ if (+ thread_id is not None+ and conn.execute("SELECT 1 FROM chat_threads WHERE id = ?", (thread_id,)).fetchone()+ is None+ ):+ thread_id = None+ conn.execute(+ """+ UPDATE scheduled_task_runs+ SET status = ?, finished_at = ?, thread_id = ?, model = ?, error_code = ?, error = ?+ WHERE id = ?+ """,+ (status, now_ms(), thread_id, model, error_code, error, run_id),+ )+ _trim_history(conn, row["task_id"])+ return True+++def _fail_stale(conn: sqlite3.Connection, stale_before: int) -> None:+ """Fail runs whose heartbeat stopped before ``stale_before`` (Studio quit or crashed mid-run)."""+ rows = conn.execute(+ f"SELECT id, task_id FROM scheduled_task_runs WHERE {_STALE_RUN}", (stale_before,)+ ).fetchall()+ run_ids = [row["id"] for row in rows]+ conn.executemany(+ "UPDATE scheduled_task_runs"+ " SET status = 'failed', finished_at = ?, error_code = 'interrupted', error = NULL"+ " WHERE id = ?",+ [(now_ms(), run_id) for run_id in run_ids],+ )+ # Delete its chat in this transaction, so a failed run never keeps one and a late save cannot restore it.+ if run_ids:+ delete_chat_threads_in(conn, [chat_id_for_run(run_id) for run_id in run_ids])+ for task_id in {row["task_id"] for row in rows}:+ _trim_history(conn, task_id)+++def list_runs(task_id: str, limit: int = RUN_HISTORY_LIMIT) -> list[dict]:+ with _connect() as conn:+ rows = conn.execute(+ "SELECT * FROM scheduled_task_runs WHERE task_id = ?"+ " ORDER BY created_at DESC, rowid DESC LIMIT ?",+ (task_id, limit),+ ).fetchall()+ return [_run_from_row(row) for row in rows]+++# Finished runs per answer; Run now is unbounded, so clients page via ``more``.+ACTIVITY_LIMIT = 200+++def activity(since: Optional[int]) -> dict:+ """Runs finished since ``since`` (oldest first, at most ACTIVITY_LIMIT, ``more`` pages), active count, next run."""+ with _connect() as conn:+ # One snapshot, so a run settling between two reads is not missed by both.+ conn.execute("BEGIN")+ runs: list[dict] = []+ more = False+ if since is not None:+ rows = conn.execute(+ """+ SELECT r.*, t.title AS task_title, t.notify AS task_notify+ FROM scheduled_task_runs r+ JOIN scheduled_tasks t ON t.id = r.task_id+ WHERE r.finished_at IS NOT NULL AND r.finished_at >= ?+ ORDER BY r.finished_at, r.rowid LIMIT ?+ """,+ (since, ACTIVITY_LIMIT + 1),+ ).fetchall()+ more = len(rows) > ACTIVITY_LIMIT+ runs = [+ {+ **_run_from_row(row),+ "taskTitle": row["task_title"],+ "taskNotify": row["task_notify"],+ }+ for row in rows[:ACTIVITY_LIMIT]+ ]+ (active,) = conn.execute(+ f"SELECT COUNT(*) FROM scheduled_task_runs WHERE status IN {_ACTIVE}"+ ).fetchone()+ (next_run_at,) = conn.execute(+ "SELECT MIN(next_run_at) FROM scheduled_tasks WHERE enabled = 1"+ ).fetchone()+ return {"runs": runs, "more": more, "activeRuns": active, "nextRunAt": next_run_at}diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 4f6e8a1618c..cbb2aa2ffc9 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -483,6 +483,7 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:fork_title_base TEXT,settings_json TEXT,modified_at INTEGER,+ scheduled_task_id TEXT,FOREIGN KEY(project_id) REFERENCES chat_projects(id) ON DELETE CASCADE)"""@@ -519,6 +520,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:# Null on every earlier row, which then numbers from its whole title.if "fork_title_base" not in chat_thread_cols:conn.execute("ALTER TABLE chat_threads ADD COLUMN fork_title_base TEXT")+ # The task whose run made this chat; kept after the task is deleted.+ if "scheduled_task_id" not in chat_thread_cols:+ conn.execute("ALTER TABLE chat_threads ADD COLUMN scheduled_task_id TEXT")# Last rename, move or (un)archive. Null until then.if "modified_at" not in chat_thread_cols:conn.execute("ALTER TABLE chat_threads ADD COLUMN modified_at INTEGER")@@ -854,6 +858,71 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:"CREATE INDEX IF NOT EXISTS idx_data_recipe_executions_recipe"" ON data_recipe_executions(recipe_id, created_at)")+ # next_run_at NULL = nothing left to run; notify = all|failures|none; named=0 = title follows the instructions.+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS scheduled_tasks (+ id TEXT NOT NULL PRIMARY KEY,+ owner_subject TEXT NOT NULL,+ title TEXT NOT NULL,+ prompt TEXT NOT NULL,+ schedule_json TEXT NOT NULL,+ timezone TEXT NOT NULL,+ enabled INTEGER NOT NULL DEFAULT 1,+ next_run_at INTEGER,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ notify TEXT NOT NULL DEFAULT 'all',+ named INTEGER NOT NULL DEFAULT 1,+ archive_successful INTEGER NOT NULL DEFAULT 0,+ project_id TEXT+ )+ """+ )+ scheduled_task_cols = {+ row[1] for row in conn.execute("PRAGMA table_info(scheduled_tasks)").fetchall()+ }+ if "notify" not in scheduled_task_cols:+ conn.execute("ALTER TABLE scheduled_tasks ADD COLUMN notify TEXT NOT NULL DEFAULT 'all'")+ if "named" not in scheduled_task_cols:+ conn.execute("ALTER TABLE scheduled_tasks ADD COLUMN named INTEGER NOT NULL DEFAULT 1")+ if "archive_successful" not in scheduled_task_cols:+ conn.execute(+ "ALTER TABLE scheduled_tasks ADD COLUMN archive_successful INTEGER NOT NULL DEFAULT 0"+ )+ if "project_id" not in scheduled_task_cols:+ conn.execute("ALTER TABLE scheduled_tasks ADD COLUMN project_id TEXT")+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_next_run ON scheduled_tasks(next_run_at)"+ )+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS scheduled_task_runs (+ id TEXT NOT NULL PRIMARY KEY,+ task_id TEXT NOT NULL REFERENCES scheduled_tasks(id) ON DELETE CASCADE,+ source TEXT NOT NULL,+ status TEXT NOT NULL,+ scheduled_for INTEGER,+ created_at INTEGER NOT NULL,+ started_at INTEGER,+ finished_at INTEGER,+ heartbeat_at INTEGER,+ worker_id TEXT,+ thread_id TEXT REFERENCES chat_threads(id) ON DELETE SET NULL,+ model TEXT,+ error_code TEXT,+ error TEXT+ )+ """+ )+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_scheduled_task_runs_task"+ " ON scheduled_task_runs(task_id, created_at)"+ )+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_scheduled_task_runs_finished"+ " ON scheduled_task_runs(finished_at)"+ )conn.execute("""CREATE TABLE IF NOT EXISTS research_runs (@@ -2080,6 +2149,7 @@ def _chat_thread_from_row(row: sqlite3.Row, include_settings: bool = True) -> di"forkBoundaryMessageId": data.get("fork_boundary_message_id"),"forkTitleBase": data.get("fork_title_base"),"modifiedAt": data.get("modified_at"),+ "scheduledTaskId": data.get("scheduled_task_id") or None,}if include_settings:thread["settings"] = _json_loads(data.get("settings_json"), None)@@ -2143,8 +2213,8 @@ def upsert_chat_thread(thread: dict) -> dict:conn.execute("""INSERT INTO chat_threads- (id, title, model_type, model_id, model_gguf_variant, pair_id, project_id, archived, created_at, updated_at, openai_code_exec_container_id, anthropic_code_exec_container_id, forked_from_thread_id, forked_from_message_id, fork_boundary_message_id, fork_title_base, settings_json)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ (id, title, model_type, model_id, model_gguf_variant, pair_id, project_id, archived, created_at, updated_at, openai_code_exec_container_id, anthropic_code_exec_container_id, forked_from_thread_id, forked_from_message_id, fork_boundary_message_id, fork_title_base, settings_json, scheduled_task_id)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT(id) DO UPDATE SETtitle = excluded.title,model_type = excluded.model_type,@@ -2177,7 +2247,9 @@ def upsert_chat_thread(thread: dict) -> dict:ELSE NULLEND,-- an absent snapshot keeps the stored one: most writers rebuild the record without it.- settings_json = COALESCE(excluded.settings_json, chat_threads.settings_json)+ settings_json = COALESCE(excluded.settings_json, chat_threads.settings_json),+ -- Set by the scheduler when it makes the chat; no later writer changes it.+ scheduled_task_id = COALESCE(chat_threads.scheduled_task_id, excluded.scheduled_task_id)""",(thread["id"],@@ -2197,6 +2269,7 @@ def upsert_chat_thread(thread: dict) -> dict:thread.get("forkBoundaryMessageId"),thread.get("forkTitleBase"),json.dumps(thread["settings"]) if thread.get("settings") is not None else None,+ thread.get("scheduledTaskId"),),)conn.commit()@@ -2569,6 +2642,7 @@ def list_chat_sidebar_rows({_SIDEBAR_ACTIVITY_SQL} AS activity_at,NULLIF(modified_at, 0) AS modified_at,CASE WHEN COALESCE(forked_from_thread_id, '') <> '' THEN 1 ELSE 0 END AS is_fork,+ CASE WHEN COALESCE(scheduled_task_id, '') <> '' THEN 1 ELSE 0 END AS is_scheduled,rowid AS member_rowid,ROW_NUMBER() OVER (PARTITION BY {_SIDEBAR_ROW_ID_SQL}@@ -2586,6 +2660,7 @@ def list_chat_sidebar_rows(MAX(CASE WHEN member_rank = 1 THEN title END) AS title,MAX(CASE WHEN member_rank = 1 THEN project_id END) AS project_id,MAX(CASE WHEN member_rank = 1 THEN is_fork END) AS is_fork,+ MAX(CASE WHEN member_rank = 1 THEN is_scheduled END) AS is_scheduled,-- groupThreads sorts stably, so rows tied on updatedAt keep list order: their newest-- member's created_at DESC, then storage order.MAX(CASE WHEN member_rank = 1 THEN created_at END) AS lead_created_at,@@ -2679,6 +2754,8 @@ def list_chat_sidebar_rows(item["modelIds"] = model_idsif not row["is_pair"]:item["isFork"] = bool(row["is_fork"])+ if row["is_scheduled"]:+ item["isScheduled"] = Trueelse:item["threadTitles"] = [member["title"] or "" for member in members]rows.append(item)@@ -2861,28 +2938,34 @@ def _active_chat_generation_run_ids(return [row["id"] for row in sorted(rows, key = lambda row: (row["created_at"], row["id"]))]+def delete_chat_threads_in(conn: sqlite3.Connection, ids: list[str]) -> tuple[list[str], list[str]]:+ """Delete chats in the caller's write transaction; returns the still-active research and chat run ids."""+ _ensure_chat_attachment_inventory_current(conn)+ thread_ids = set(ids)+ active_research_run_ids = _active_research_run_ids(conn, thread_ids)+ active_chat_run_ids = _active_chat_generation_run_ids(conn, thread_ids)+ _reparent_surviving_forks(conn, thread_ids)+ # Record the delete even when no row exists yet. A late POST carrying the same unique id+ # must not recreate a thread after this request has confirmed deletion.+ _tombstone_chat_threads(conn, thread_ids)+ conn.executemany(+ "DELETE FROM chat_attachment_tombstones WHERE thread_id = ?",+ [(id,) for id in ids],+ )+ conn.executemany("DELETE FROM chat_threads WHERE id = ?", [(id,) for id in ids])+ _mark_chat_attachment_inventory_clean(conn)+ return active_research_run_ids, active_chat_run_ids++def delete_chat_threads_with_active_runs(ids: list[str]) -> tuple[list[str], list[str]]:if not ids:return [], []conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)try:conn.execute("BEGIN IMMEDIATE")- _ensure_chat_attachment_inventory_current(conn)- thread_ids = set(ids)- active_research_run_ids = _active_research_run_ids(conn, thread_ids)- active_chat_run_ids = _active_chat_generation_run_ids(conn, thread_ids)- _reparent_surviving_forks(conn, thread_ids)- # Record the delete even when no row exists yet. A late POST carrying the same unique id- # must not recreate a thread after this request has confirmed deletion.- _tombstone_chat_threads(conn, thread_ids)- conn.executemany(- "DELETE FROM chat_attachment_tombstones WHERE thread_id = ?",- [(id,) for id in ids],- )- conn.executemany("DELETE FROM chat_threads WHERE id = ?", [(id,) for id in ids])- _mark_chat_attachment_inventory_clean(conn)+ active = delete_chat_threads_in(conn, ids)conn.commit()- return active_research_run_ids, active_chat_run_ids+ return activeexcept Exception:conn.rollback()raisediff --git a/studio/backend/tests/multi_account/factories.py b/studio/backend/tests/multi_account/factories.pyindex d6321e1343b..45e58e3f73f 100644--- a/studio/backend/tests/multi_account/factories.py+++ b/studio/backend/tests/multi_account/factories.py@@ -194,6 +194,7 @@ from . import ( # noqa: E402 domain tables import Factory and register their sfactories_providers,factories_rag,factories_runs,+ factories_scheduled_tasks,factories_training,)@@ -204,6 +205,7 @@ DOMAINS = (factories_providers,factories_rag,factories_runs,+ factories_scheduled_tasks,factories_training,)diff --git a/studio/backend/tests/multi_account/factories_scheduled_tasks.py b/studio/backend/tests/multi_account/factories_scheduled_tasks.pynew file mode 100644index 00000000000..488a0683d8f--- /dev/null+++ b/studio/backend/tests/multi_account/factories_scheduled_tasks.py@@ -0,0 +1,52 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from .factory_base import Factory, seeder++TITLE = "scheduled-task-matrix-title"+EDITED = "scheduled-task-matrix-edited"+++@seeder("scheduled-task")+def seed_scheduled_task(account) -> dict[str, str]:+ from storage import scheduled_tasks_db+ from utils.account_context import run_as++ now = scheduled_tasks_db.now_ms()+ task = run_as(+ account,+ scheduled_tasks_db.create_task,+ {+ "id": "scheduled-task-matrix",+ "ownerSubject": account.username,+ "title": TITLE,+ "prompt": "scheduled task matrix prompt",+ "schedule": {"kind": "daily", "time": "09:00"},+ "timezone": "UTC",+ "enabled": False,+ "notify": "all",+ "named": True,+ "nextRunAt": None,+ "createdAt": now,+ "updatedAt": now,+ },+ )+ return {"task_id": task["id"]}+++FACTORIES = {+ "routes.scheduled_tasks:GET:/{task_id}": Factory(+ "scheduled-task", fragment = TITLE, absent = TITLE+ ),+ "routes.scheduled_tasks:PATCH:/{task_id}": Factory(+ "scheduled-task", {"title": EDITED}, fragment = EDITED, absent = TITLE+ ),+ "routes.scheduled_tasks:DELETE:/{task_id}": Factory(+ "scheduled-task", success = 204, absent = TITLE+ ),+ "routes.scheduled_tasks:POST:/{task_id}/run": Factory(+ "scheduled-task", success = 202, fragment = '"status":"queued"', absent = TITLE+ ),+}++SKIPPED: dict[str, str] = {}diff --git a/studio/backend/tests/test_account_deactivation_fence.py b/studio/backend/tests/test_account_deactivation_fence.pyindex 6ba342519fa..41cfd3d7955 100644--- a/studio/backend/tests/test_account_deactivation_fence.py+++ b/studio/backend/tests/test_account_deactivation_fence.py@@ -4,6 +4,7 @@"""Generations registered after deactivation start cancelled; reactivation lifts that fence."""import threading+from types import SimpleNamespacefrom auth import storagefrom state import active_generations@@ -36,3 +37,20 @@ def test_retirement_fences_late_registration(matrix):alice = storage.get_account("alice")assert client.delete(f"/api/accounts/{alice.account_id}", headers = headers()).status_code == 204assert _register(alice) is True+++def test_deactivation_cancels_a_scheduled_run_still_waiting_for_the_model(matrix):+ from core.scheduled_tasks.scheduler import ScheduledTaskScheduler, _ActiveRun++ client, _, _ = matrix+ alice, bob = storage.get_account("alice"), storage.get_account("bob")+ alices_scheduler = ScheduledTaskScheduler(SimpleNamespace(state = SimpleNamespace()))+ bobs_scheduler = ScheduledTaskScheduler(SimpleNamespace(state = SimpleNamespace()))+ alices_run, bobs_run = threading.Event(), threading.Event()+ alices_scheduler._active = _ActiveRun(alice.account_id, "task-1", "run-1", alices_run)+ bobs_scheduler._active = _ActiveRun(bob.account_id, "task-2", "run-2", bobs_run)++ url = f"/api/accounts/{alice.account_id}"+ assert client.patch(url, headers = headers(), json = {"is_active": False}).status_code == 200+ assert alices_run.is_set()+ assert not bobs_run.is_set()diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.pyindex f44b7c30d36..976a296e39a 100644--- a/studio/backend/tests/test_desktop_auth.py+++ b/studio/backend/tests/test_desktop_auth.py@@ -799,6 +799,8 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):llama_compat_module.is_engine_probe_path = lambda full_path: Falseprompts_module = ModuleType("routes.prompts")prompts_module.router = APIRouter()+ scheduled_tasks_module = ModuleType("routes.scheduled_tasks")+ scheduled_tasks_module.router = APIRouter()preview_module = ModuleType("routes.preview")preview_module.router = APIRouter()whisper_module = ModuleType("routes.whisper")@@ -820,6 +822,11 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):systemone_module.MCP_PATH = "/mcp/decisions"systemone_module.RequireStudioAuth = lambda app: appsystemone_module.decisions_mcp = FastMCP("Unsloth Decisions")+ browser_module = ModuleType("routes.browser")+ browser_module.router = APIRouter()+ browser_module.BROWSER_FRAME_PATH = "/api/browser/frame"+ browser_module.BROWSER_PRINT_PATH = "/api/browser/print"+ browser_module.EXPOSED_HEADERS = ()# Derived from main.py's import block: hand-listed stubs went stale and broke this file.for name in _routers_main_imports():@@ -837,6 +844,7 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):monkeypatch.setitem(sys.modules, "routes.engines", engines_module)monkeypatch.setitem(sys.modules, "routes.llama_compat", llama_compat_module)monkeypatch.setitem(sys.modules, "routes.prompts", prompts_module)+ monkeypatch.setitem(sys.modules, "routes.scheduled_tasks", scheduled_tasks_module)monkeypatch.setitem(sys.modules, "routes.preview", preview_module)monkeypatch.setitem(sys.modules, "routes.whisper", whisper_module)monkeypatch.setitem(sys.modules, "routes.npu", npu_module)@@ -845,6 +853,7 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):monkeypatch.setitem(sys.modules, "routes.library", library_module)monkeypatch.setitem(sys.modules, "routes.sandbox_capability", sandbox_capability_module)monkeypatch.setitem(sys.modules, "routes.systemone", systemone_module)+ monkeypatch.setitem(sys.modules, "routes.browser", browser_module)import studio.backend.main as backend_maindiff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 64df20eb13f..4aca9950c00 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -2788,6 +2788,9 @@ def test_inactive_hf_cache_entry_skips_newer_companion_only_snapshot(tmp_path):def test_hf_cache_entry_stays_within_the_scanned_case_variant(tmp_path):"""A cache row must load from its exact repo directory, not a case-folded peer."""+ (tmp_path / "Case").mkdir()+ if (tmp_path / "case").exists():+ pytest.skip("case-insensitive file system: the two repo directories are one")scanned_repo = tmp_path / "models--Org--Repo"scanned_snapshot = scanned_repo / "snapshots" / "scanned-revision"scanned_snapshot.mkdir(parents = True)@@ -3890,6 +3893,74 @@ def test_preview_scope_disables_auto_switch(monkeypatch):assert len(rec.calls) == 1+def test_loaded_models_only_scope_routes_but_never_loads(monkeypatch):+ # Scheduled runs name the model kept alongside; one unloaded before routing must not come back.+ backend, rec = _wired(monkeypatch, _FakeBackend(None), ("/p/B", "Q8_0", "org/B-GGUF"))+ routed = []++ async def route(requested):+ routed.append(requested)+ return None++ monkeypatch.setattr(inference_route, "_route_to_extra_slot", route)++ class _Req:+ def __init__(self, scope):+ self.scope = scope++ def only():+ return _Req({inference_route.LOADED_MODELS_ONLY_SCOPE_KEY: True})++ def switch(req):+ asyncio.run(inference_route._maybe_auto_switch_model("org/B-GGUF", req, "tester"))++ with pytest.raises(HTTPException) as gone:+ switch(only())+ assert gone.value.status_code == 404+ assert routed == ["org/B-GGUF"] and rec.calls == []++ # An omitted model (the reload-only sentinel) is not a name: the loaded one answers.+ asyncio.run(+ inference_route._maybe_auto_switch_model(+ inference_route._RELOAD_ONLY_MODEL, only(), "tester"+ )+ )+ assert rec.calls == []++ # A resident answering to the name serves it, but only under the resident access check:+ # an account's request never lands on another account's hidden primary.+ monkeypatch.setattr(inference_route, "_loaded_identity_satisfies", lambda name: True)+ switch(only())+ assert rec.calls == []++ async def allowed(*_):+ return None++ monkeypatch.setattr(inference_route, "_require_named_model_access", allowed)+ monkeypatch.setattr(inference_route.account_access, "managed_account", lambda: True)+ monkeypatch.setattr(inference_route.account_access, "resident_hidden", lambda *a: True)+ monkeypatch.setattr(+ inference_route.account_access,+ "require_model_access",+ lambda ref: (_ for _ in ()).throw(HTTPException(status_code = 404, detail = "Model not found")),+ )+ monkeypatch.setattr(inference_route.account_access, "cached_model_repo", lambda ref: None)++ async def no_token(*_):+ return False++ monkeypatch.setattr(inference_route, "_caller_token_authorizes_download", no_token)+ with pytest.raises(HTTPException) as hidden:+ switch(only())+ assert hidden.value.status_code == 404 and rec.calls == []+ monkeypatch.setattr(inference_route.account_access, "managed_account", lambda: False)++ # Control: without the flag the same request loads it.+ monkeypatch.setattr(inference_route, "_loaded_identity_satisfies", lambda name: False)+ asyncio.run(inference_route._maybe_auto_switch_model("org/B-GGUF", _Req({}), "tester"))+ assert len(rec.calls) == 1++def test_preview_chat_is_tracked_as_inference_path():# Keep-warm counts long preview streams so the idle loop cannot unload mid-response.@@ -11338,6 +11409,12 @@ def test_a_host_with_no_accelerator_serves_gguf_only(monkeypatch):monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU, raising = False)assert _REAL_HOST_HAS_NON_GGUF_BACKEND() is Falsemonkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CUDA, raising = False)+ # The check also asks for torch, which a runner without it would answer False.+ import importlib.util++ monkeypatch.setattr(+ importlib.util, "find_spec", lambda name, *a: object() if name == "torch" else None+ )assert _REAL_HOST_HAS_NON_GGUF_BACKEND() is Truediff --git a/studio/backend/tests/test_personalization_settings.py b/studio/backend/tests/test_personalization_settings.pyindex 23805639e17..cd923b51f8b 100644--- a/studio/backend/tests/test_personalization_settings.py+++ b/studio/backend/tests/test_personalization_settings.py@@ -193,6 +193,7 @@ FRONTEND_SHIPPED_SIDEBAR_NAV = [("recipes", False),("export", False),("api", False),+ ("tasks", False),]@@ -231,6 +232,7 @@ def test_customization_sidebar_nav_preserves_order_and_normalizes():("recipes", False),("export", False),("api", False),+ ("tasks", False),]@@ -514,6 +516,7 @@ def test_personalization_route_roundtrip_real_shape(monkeypatch):{"id": "recipes", "pinned": False},{"id": "export", "pinned": False},{"id": "api", "pinned": False},+ {"id": "tasks", "pinned": False},],"sidebarNavAuto": [],},diff --git a/studio/backend/tests/test_scheduled_tasks.py b/studio/backend/tests/test_scheduled_tasks.pynew file mode 100644index 00000000000..04fde9c8264--- /dev/null+++ b/studio/backend/tests/test_scheduled_tasks.py@@ -0,0 +1,1474 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Scheduled tasks: schedule math, storage, routes, and the runner that posts answers to chats."""++import asyncio+import sqlite3+import threading+from datetime import datetime+from types import SimpleNamespace++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.responses import JSONResponse+from fastapi.testclient import TestClient+from pydantic import ValidationError++from auth.authentication import authenticated_via_api_key, get_current_subject+from core.inference import llama_keepwarm+from core.scheduled_tasks import scheduler as scheduler_module+from core.scheduled_tasks.schedule import InvalidSchedule, next_run_after, parse_schedule+from core.scheduled_tasks.scheduler import (+ Answer,+ RunFailed,+ ScheduledTaskScheduler,+ generate_answer,+ next_run_for,+)+from routes import inference as inference_routes+from routes.scheduled_tasks import router+from storage import scheduled_tasks_db as db+from storage import studio_db+from utils.account_context import OWNER++DAY = 24 * 60 * 60 * 1000+++def ms(iso: str) -> int:+ return int(datetime.fromisoformat(iso).timestamp() * 1000)+++def make_task(**overrides) -> dict:+ task = {+ "id": "task-1",+ "ownerSubject": "unsloth",+ "title": "Morning brief",+ "prompt": "Write a haiku about mornings.",+ "schedule": {"kind": "daily", "time": "09:00"},+ "timezone": "UTC",+ "enabled": True,+ "notify": "all",+ "named": True,+ "nextRunAt": ms("2026-10-14T09:00:00+00:00"),+ "createdAt": 1,+ "updatedAt": 1,+ }+ task.update(overrides)+ return db.create_task(task)+++def client():+ app = FastAPI()+ app.include_router(router, prefix = "/api/scheduled-tasks")+ app.dependency_overrides[get_current_subject] = lambda: "unsloth"+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ with TestClient(app) as test_client:+ yield test_client+++ "schedule, zone, after, expected",+ [+ ({"kind": "daily", "time": "09:00"}, "UTC", "2026-10-14T08:59", "2026-10-14T09:00"),+ ({"kind": "daily", "time": "09:00"}, "UTC", "2026-10-14T09:00", "2026-10-15T09:00"),+ # Wall-clock time in the task's zone: 09:00 in Istanbul is 06:00 UTC.+ (+ {"kind": "daily", "time": "09:00"},+ "Europe/Istanbul",+ "2026-10-14T05:00",+ "2026-10-14T06:00",+ ),+ (+ {"kind": "weekly", "time": "09:00", "days": [1, 5]},+ "UTC",+ "2026-10-14T12:00",+ "2026-10-16T09:00",+ ),+ (+ {"kind": "weekly", "time": "09:00", "days": [3]},+ "UTC",+ "2026-10-14T12:00",+ "2026-10-21T09:00",+ ),+ (+ {"kind": "monthly", "time": "09:00", "day": 31},+ "UTC",+ "2026-02-01T00:00",+ "2026-02-28T09:00",+ ),+ (+ {"kind": "monthly", "time": "09:00", "day": 31},+ "UTC",+ "2028-02-01T00:00",+ "2028-02-29T09:00",+ ),+ (+ {"kind": "monthly", "time": "09:00", "day": 15},+ "UTC",+ "2026-12-20T00:00",+ "2027-01-15T09:00",+ ),+ (+ {"kind": "once", "at": "2026-10-15T09:00"},+ "America/New_York",+ "2026-10-14T00:00",+ "2026-10-15T13:00",+ ),+ ],+)+def test_next_run_after(schedule, zone, after, expected):+ following = next_run_after(parse_schedule(schedule), zone, ms(f"{after}:00+00:00"))+ assert following == ms(f"{expected}:00+00:00")+++def test_a_one_time_task_has_no_run_left_once_its_time_passes():+ schedule = parse_schedule({"kind": "once", "at": "2026-10-15T09:00"})+ assert next_run_after(schedule, "UTC", ms("2026-10-15T09:00:00+00:00")) is None+++def test_a_time_the_clocks_skip_runs_just_past_the_change():+ # New York skips 02:00-03:00 on 2026-03-08; 02:30 runs at 03:30 EDT, 07:30 UTC.+ schedule = parse_schedule({"kind": "daily", "time": "02:30"})+ following = next_run_after(schedule, "America/New_York", ms("2026-03-08T05:00:00+00:00"))+ assert following == ms("2026-03-08T07:30:00+00:00")+++def test_a_time_that_happens_twice_runs_once():+ # 01:30 happens twice in New York on 2026-11-01: the run takes the first and skips the second.+ schedule = parse_schedule({"kind": "daily", "time": "01:30"})+ first = next_run_after(schedule, "America/New_York", ms("2026-11-01T04:00:00+00:00"))+ assert first == ms("2026-11-01T05:30:00+00:00")+ assert next_run_after(schedule, "America/New_York", first) == ms("2026-11-02T06:30:00+00:00")+++ "schedule",+ [+ {"kind": "daily", "time": "24:00"},+ {"kind": "daily", "time": "9:00"},+ {"kind": "weekly", "time": "09:00", "days": []},+ {"kind": "weekly", "time": "09:00", "days": [0]},+ {"kind": "monthly", "time": "09:00", "day": 32},+ {"kind": "once", "at": "2026-02-30T09:00"},+ {"kind": "daily", "time": "09:00", "extra": True},+ {"kind": "hourly", "time": "09:00"},+ ],+)+def test_malformed_schedules_are_refused(schedule):+ with pytest.raises(ValidationError):+ parse_schedule(schedule)++[email protected]("zone", ["Mars/Olympus_Mons", "../../etc/passwd", "", "x" * 65])+def test_unknown_time_zones_are_refused(zone):+ with pytest.raises(InvalidSchedule):+ next_run_after(parse_schedule({"kind": "daily", "time": "09:00"}), zone, 0)+++def test_weekdays_are_deduplicated_and_sorted():+ assert parse_schedule({"kind": "weekly", "time": "09:00", "days": [5, 1, 5]}).days == [1, 5]+++def test_a_claim_runs_an_occurrence_once_and_skips_the_ones_studio_missed():+ due = ms("2026-10-11T09:00:00+00:00")+ make_task(nextRunAt = due)+ now = ms("2026-10-14T12:00:00+00:00")++ task, run = db.claim_next(now, "worker", next_run_for)++ assert run["status"] == "running" and run["source"] == "schedule"+ assert run["scheduledFor"] == due+ assert task["nextRunAt"] == ms("2026-10-15T09:00:00+00:00")+ assert db.claim_next(now, "worker", next_run_for) is None+++def next_due():+ """When the scheduler would next look, without claiming (a pass at the epoch finds nothing due)."""+ return db.poll(0, None, "worker", next_run_for)[1]+++def sweep(stale_before):+ db.poll(0, stale_before, "sweeper", next_run_for)+++def test_a_due_task_waits_while_it_already_has_a_run():+ make_task()+ db.request_run("task-1")+ now = ms("2026-10-14T12:00:00+00:00")+ _task, manual = db.claim_next(now, "worker", next_run_for)+ assert manual["source"] == "manual"+ assert db.claim_next(now, "worker", next_run_for) is None+ assert next_due() is None+ db.finish_run(manual["id"], "worker", status = "succeeded")+ _task, scheduled = db.claim_next(now, "worker", next_run_for)+ assert scheduled["source"] == "schedule"+++def test_a_one_time_task_is_completed_once_claimed(client):+ make_task(schedule = {"kind": "once", "at": "2026-10-14T09:00"})+ db.claim_next(ms("2026-10-14T09:00:00+00:00"), "worker", next_run_for)+ task = client.get("/api/scheduled-tasks/task-1").json()+ assert task["status"] == "completed"+ assert task["nextRunAt"] is None+ assert task["lastRun"]["status"] == "running"+++def test_paused_and_future_tasks_are_not_claimed():+ make_task(id = "paused", enabled = False, nextRunAt = None)+ make_task(id = "later", nextRunAt = ms("2026-10-14T18:00:00+00:00"))+ assert db.claim_next(ms("2026-10-14T12:00:00+00:00"), "worker", next_run_for) is None+ assert next_due() == ms("2026-10-14T18:00:00+00:00")+++def test_runs_whose_heartbeat_stopped_are_failed_and_live_ones_kept():+ make_task(id = "unsettled", nextRunAt = ms("2026-10-14T08:00:00+00:00"))+ make_task(id = "crashed", nextRunAt = ms("2026-10-14T08:30:00+00:00"))+ make_task(id = "fresh", nextRunAt = ms("2026-10-14T08:45:00+00:00"))+ claim_at = ms("2026-10-14T12:00:00+00:00")+ db.claim_next(claim_at, "me", next_run_for)+ db.claim_next(claim_at, "crashed", next_run_for)+ db.claim_next(claim_at + 60_000, "alive", next_run_for)++ sweep(claim_at + 1)++ runs = {task["id"]: task["lastRun"] for task in db.list_tasks()}+ for stopped in ("unsettled", "crashed"):+ assert runs[stopped]["status"] == "failed"+ assert runs[stopped]["errorCode"] == "interrupted"+ assert runs["fresh"]["status"] == "running"+++def test_a_run_the_scheduler_could_not_settle_does_not_hold_its_task(monkeypatch):+ monkeypatch.setattr(scheduler_module, "job_accounts", lambda: [OWNER])+ scheduler = new_scheduler()+ make_task(schedule = {"kind": "once", "at": "2026-10-14T09:00"}, nextRunAt = db.now_ms() - DAY)+ assert scheduler._claim() is not None+ later = db.now_ms() + scheduler_module._STALE_RUN_MS + 1+ monkeypatch.setattr(db, "now_ms", lambda: later)++ assert scheduler._claim() is None++ last_run = db.get_task("task-1")["lastRun"]+ assert (last_run["status"], last_run["errorCode"]) == ("failed", "interrupted")+ assert db.request_run("task-1")["status"] == "queued"+++def test_finishing_settles_only_the_owners_run_and_bounds_the_history(monkeypatch):+ monkeypatch.setattr(db, "RUN_HISTORY_LIMIT", 2)+ make_task()+ for _ in range(3):+ db.request_run("task-1")+ _task, run = db.claim_next(db.now_ms(), "worker", next_run_for)+ assert not db.finish_run(run["id"], "someone-else", status = "succeeded")+ assert db.finish_run(run["id"], "worker", status = "failed", error_code = "empty")+ assert [run["errorCode"] for run in db.list_runs("task-1")] == ["empty", "empty"]+++def test_the_sweep_keeps_a_task_s_history_bounded_too(monkeypatch):+ monkeypatch.setattr(db, "RUN_HISTORY_LIMIT", 2)+ make_task()+ for _ in range(3):+ db.request_run("task-1")+ db.claim_next(db.now_ms(), "crashed", next_run_for)+ sweep(db.now_ms() + scheduler_module._STALE_RUN_MS + 1)+ assert [run["errorCode"] for run in db.list_runs("task-1")] == ["interrupted", "interrupted"]+++def test_a_deleted_chat_unlinks_from_its_run():+ make_task()+ studio_db.upsert_chat_thread(+ {"id": "chat-1", "title": "Morning brief", "modelType": "base", "createdAt": 1}+ )+ db.request_run("task-1")+ _task, run = db.claim_next(db.now_ms(), "worker", next_run_for)+ db.finish_run(run["id"], "worker", status = "succeeded", thread_id = "chat-1")+ assert db.get_task("task-1")["lastRun"]["threadId"] == "chat-1"++ studio_db.delete_chat_threads(["chat-1"])++ assert db.get_task("task-1")["lastRun"]["threadId"] is None+++def test_a_run_whose_chat_is_already_gone_still_settles():+ make_task()+ db.request_run("task-1")+ _task, run = db.claim_next(db.now_ms(), "worker", next_run_for)+ assert db.finish_run(run["id"], "worker", status = "succeeded", thread_id = "missing")+ assert db.get_task("task-1")["lastRun"]["threadId"] is None+++def create(client, **overrides):+ body = {+ "title": "Morning brief",+ "prompt": "Write a haiku about mornings.",+ "schedule": {"kind": "daily", "time": "09:00"},+ "timezone": "UTC",+ }+ body.update(overrides)+ return client.post("/api/scheduled-tasks", json = body)+++def make_project(project_id = "proj-1"):+ return studio_db.upsert_chat_project(+ {"id": project_id, "name": "Reports", "instructions": "", "createdAt": 1, "updatedAt": 1}+ )+++def test_a_task_keeps_its_chat_options_and_refuses_a_missing_project(client):+ make_project()+ task = create(client, archiveSuccessful = True, projectId = "proj-1").json()+ assert (task["archiveSuccessful"], task["projectId"]) == (True, "proj-1")+ assert create(client, projectId = "nowhere").status_code == 400+ cleared = client.patch(f"/api/scheduled-tasks/{task['id']}", json = {"projectId": None}).json()+ assert cleared["projectId"] is None+ assert create(client).json()["archiveSuccessful"] is False+++def test_create_list_and_read(client, monkeypatch):+ monkeypatch.setattr(db, "now_ms", lambda: ms("2026-10-14T12:00:00+00:00"))+ response = create(client, title = " Morning brief ")+ assert response.status_code == 201+ task = response.json()+ assert task["title"] == "Morning brief"+ assert task["status"] == "active"+ assert task["notify"] == "all"+ assert task["named"] is True+ assert task["nextRunAt"] == ms("2026-10-15T09:00:00+00:00")+ assert task["lastRun"] is None+ assert "ownerSubject" not in task+ listed = client.get("/api/scheduled-tasks").json()+ assert listed["tasks"] == [task]+ assert listed["now"] == ms("2026-10-14T12:00:00+00:00")+ assert client.get(f"/api/scheduled-tasks/{task['id']}").json() == task+++ "overrides, status",+ [+ ({"title": " "}, 422),+ ({"prompt": ""}, 422),+ ({"title": "x" * 121}, 422),+ ({"schedule": {"kind": "daily", "time": "25:00"}}, 422),+ ({"timezone": "Nowhere/Special"}, 400),+ ({"schedule": {"kind": "once", "at": "2020-01-01T09:00"}}, 400),+ ({"model": " "}, 422),+ ({"notify": "sometimes"}, 422),+ ],+)+def test_invalid_tasks_are_refused(client, overrides, status):+ assert create(client, **overrides).status_code == status+ assert client.get("/api/scheduled-tasks").json()["tasks"] == []+++def test_the_task_limit(client, monkeypatch):+ monkeypatch.setattr(db, "MAX_TASKS", 1)+ assert create(client).status_code == 201+ response = create(client)+ assert response.status_code == 409+ assert "up to 1 scheduled tasks" in response.json()["detail"]+++def test_pause_clears_the_next_run_and_resume_schedules_from_now(client, monkeypatch):+ now = ms("2026-10-14T12:00:00+00:00")+ monkeypatch.setattr(db, "now_ms", lambda: now)+ task = create(client).json()++ paused = client.patch(f"/api/scheduled-tasks/{task['id']}", json = {"enabled": False}).json()+ assert paused["status"] == "paused"+ assert paused["nextRunAt"] is None++ now = ms("2026-10-20T12:00:00+00:00")+ resumed = client.patch(f"/api/scheduled-tasks/{task['id']}", json = {"enabled": True}).json()+ assert resumed["status"] == "active"+ assert resumed["nextRunAt"] == ms("2026-10-21T09:00:00+00:00")+++ "patch",+ [+ {"title": "Evening brief"},+ {"notify": "none"},+ {"named": False},+ {"enabled": True, "schedule": {"kind": "daily", "time": "09:00"}, "timezone": "UTC"},+ ],+)+def test_an_edit_that_keeps_the_timing_keeps_an_overdue_run_due(client, patch):+ make_task(nextRunAt = ms("2026-10-14T09:00:00+00:00"))+ edited = client.patch("/api/scheduled-tasks/task-1", json = patch).json()+ assert edited["nextRunAt"] == ms("2026-10-14T09:00:00+00:00")+ stored = client.get("/api/scheduled-tasks/task-1").json()+ assert all(stored[key] == value for key, value in patch.items())+++def test_whether_a_task_was_named_is_kept(client):+ unnamed = create(client, title = "Write a haiku about mornings.", named = False).json()+ assert unnamed["named"] is False+ named = client.patch(f"/api/scheduled-tasks/{unnamed['id']}", json = {"named": True}).json()+ assert named["named"] is True+ assert client.get(f"/api/scheduled-tasks/{unnamed['id']}").json()["named"] is True+++def test_a_database_from_before_notification_settings_gains_them():+ conn = sqlite3.connect(":memory:")+ try:+ conn.execute(+ """CREATE TABLE scheduled_tasks (+ id TEXT NOT NULL PRIMARY KEY, owner_subject TEXT NOT NULL, title TEXT NOT NULL,+ prompt TEXT NOT NULL, schedule_json TEXT NOT NULL, timezone TEXT NOT NULL,+ enabled INTEGER NOT NULL DEFAULT 1, next_run_at INTEGER,+ created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL+ )"""+ )+ conn.execute(+ "INSERT INTO scheduled_tasks VALUES ('t', 'u', 'T', 'P', '{}', 'UTC', 1, NULL, 1, 1)"+ )+ studio_db._ensure_schema(conn)+ studio_db._ensure_schema(conn)+ assert conn.execute("SELECT notify, named FROM scheduled_tasks").fetchall() == [("all", 1)]+ finally:+ conn.close()+++def test_a_new_schedule_moves_the_next_run(client, monkeypatch):+ monkeypatch.setattr(db, "now_ms", lambda: ms("2026-10-14T12:00:00+00:00"))+ make_task()+ updated = client.patch(+ "/api/scheduled-tasks/task-1",+ json = {"schedule": {"kind": "weekly", "time": "18:30", "days": [3]}},+ ).json()+ assert updated["schedule"] == {"kind": "weekly", "time": "18:30", "days": [3]}+ assert updated["nextRunAt"] == ms("2026-10-14T18:30:00+00:00")+++def test_a_refused_update_changes_nothing(client):+ make_task()+ before = client.get("/api/scheduled-tasks/task-1").json()+ response = client.patch(+ "/api/scheduled-tasks/task-1",+ json = {"title": "Changed", "schedule": {"kind": "once", "at": "2020-01-01T09:00"}},+ )+ assert response.status_code == 400+ assert client.get("/api/scheduled-tasks/task-1").json() == before+++def test_unknown_tasks_are_404(client):+ assert client.get("/api/scheduled-tasks/nope").status_code == 404+ assert client.patch("/api/scheduled-tasks/nope", json = {"title": "x"}).status_code == 404+ assert client.delete("/api/scheduled-tasks/nope").status_code == 404+ assert client.post("/api/scheduled-tasks/nope/run").status_code == 404+++def test_run_now_queues_one_run_at_a_time_and_delete_removes_it(client):+ task = create(client).json()+ response = client.post(f"/api/scheduled-tasks/{task['id']}/run")+ assert response.status_code == 202+ assert response.json()["status"] == "queued"+ assert response.json()["source"] == "manual"+ assert client.post(f"/api/scheduled-tasks/{task['id']}/run").status_code == 409+ assert client.get("/api/scheduled-tasks/runs").json()["activeRuns"] == 1++ assert client.delete(f"/api/scheduled-tasks/{task['id']}").status_code == 204+ assert client.get("/api/scheduled-tasks").json()["tasks"] == []+ assert client.get("/api/scheduled-tasks/runs").json()["activeRuns"] == 0+++def test_activity_lists_runs_finished_since_a_cursor(client):+ make_task(notify = "failures")+ db.request_run("task-1")+ _task, run = db.claim_next(db.now_ms(), "worker", next_run_for)+ first = client.get("/api/scheduled-tasks/runs").json()+ assert first["runs"] == [] and first["activeRuns"] == 1+ db.finish_run(run["id"], "worker", status = "failed", error_code = "no_model")++ later = client.get("/api/scheduled-tasks/runs", params = {"since": first["now"]}).json()+ assert [(r["taskTitle"], r["taskNotify"], r["errorCode"]) for r in later["runs"]] == [+ ("Morning brief", "failures", "no_model")+ ]+ assert later["activeRuns"] == 0+ assert later["nextRunAt"] == ms("2026-10-14T09:00:00+00:00")+ assert later["more"] is False+++def test_activity_pages_through_more_runs_than_one_answer_holds(client, monkeypatch):+ monkeypatch.setattr(db, "ACTIVITY_LIMIT", 2)+ clock = iter(range(1_000, 100_000, 1_000))+ monkeypatch.setattr(db, "now_ms", lambda: next(clock))+ make_task()+ finished = []+ for _ in range(3):+ db.request_run("task-1")+ _task, run = db.claim_next(db.now_ms(), "worker", next_run_for)+ db.finish_run(run["id"], "worker", status = "failed", error_code = "empty")+ finished.append(run["id"])++ first = client.get("/api/scheduled-tasks/runs", params = {"since": 0}).json()+ assert [run["id"] for run in first["runs"]] == finished[:2]+ assert first["more"] is True+ rest = client.get(+ "/api/scheduled-tasks/runs", params = {"since": first["runs"][-1]["finishedAt"]}+ ).json()+ assert [run["id"] for run in rest["runs"]] == finished[1:]+ assert rest["more"] is False+++def new_scheduler():+ return ScheduledTaskScheduler(SimpleNamespace(state = SimpleNamespace()))+++def execute(task, run):+ scheduler = new_scheduler()+ scheduler.worker_id = "worker-under-test"+ asyncio.run(scheduler._execute(OWNER, task, run))+++def claim():+ return db.claim_next(db.now_ms(), "worker-under-test", next_run_for)+++def claim_manual_run(**task_overrides):+ task = make_task(**task_overrides)+ db.request_run(task["id"])+ return claim()+++def run_scheduler(+ task,+ run,+ answer = None,+ failure = None,+ monkeypatch = None,+):+ async def fake_generate(app, task, run, *_):+ if failure is not None:+ raise failure+ return answer++ monkeypatch.setattr(scheduler_module, "generate_answer", fake_generate)+ execute(task, run)+++def test_a_run_saves_the_exchange_as_a_new_chat(monkeypatch):+ task, run = claim_manual_run()+ answer = Answer(content = "Dawn light on the sill.", reasoning = "A haiku.", model = "gemma-3")++ run_scheduler(task, run, answer = answer, monkeypatch = monkeypatch)++ last_run = db.get_task(task["id"])["lastRun"]+ assert last_run["status"] == "succeeded"+ assert last_run["model"] == "gemma-3"+ thread = studio_db.get_chat_thread(last_run["threadId"])+ assert thread["title"] == "Morning brief"+ assert thread["modelId"] == "gemma-3"+ user, assistant = studio_db.list_chat_messages(last_run["threadId"])+ assert user["role"] == "user" and user["parentId"] is None+ assert user["content"] == [{"type": "text", "text": "Write a haiku about mornings."}]+ assert assistant["parentId"] == user["id"]+ assert assistant["createdAt"] > user["createdAt"]+ assert assistant["content"] == [+ {"type": "reasoning", "text": "A haiku."},+ {"type": "text", "text": "Dawn light on the sill."},+ ]+ assert assistant["metadata"]["scheduledTask"] == {"taskId": task["id"], "runId": run["id"]}+ assert assistant["metadata"]["responseDetails"]["modelId"] == "gemma-3"+ duration = assistant["metadata"]["reasoningDuration"]+ assert isinstance(duration, int) and assistant["metadata"]["reasoningDurations"] == [duration]+++def test_a_run_chat_is_marked_as_the_tasks_and_keeps_the_mark(monkeypatch):+ task, run = claim_manual_run()+ run_scheduler(+ task, run, answer = Answer(content = "Hi.", reasoning = "", model = "m"), monkeypatch = monkeypatch+ )++ thread_id = db.get_task(task["id"])["lastRun"]["threadId"]+ thread = studio_db.get_chat_thread(thread_id)+ assert thread["scheduledTaskId"] == task["id"]+ user, _assistant = studio_db.list_chat_messages(thread_id)+ assert user["metadata"]["scheduledTask"] == {"taskId": task["id"], "runId": run["id"]}+ (row,) = [r for r in studio_db.list_chat_sidebar_rows()["rows"] if thread_id in r["threadIds"]]+ assert row["isScheduled"] is True++ studio_db.upsert_chat_thread({**thread, "title": "Renamed", "scheduledTaskId": None})+ assert studio_db.get_chat_thread(thread_id)["scheduledTaskId"] == task["id"]+++def test_a_saved_chat_names_the_checkpoint_chat_can_select(monkeypatch):+ task, run = claim_manual_run()+ answer = Answer(+ content = "Hi.",+ reasoning = "",+ model = "Qwen3-0.6B-Q4_K_M",+ checkpoint = "unsloth/Qwen3-0.6B-GGUF",+ gguf_variant = "Q4_K_M",+ )+ run_scheduler(task, run, answer = answer, monkeypatch = monkeypatch)+ thread_id = db.get_task(task["id"])["lastRun"]["threadId"]+ thread = studio_db.get_chat_thread(thread_id)+ assert (thread["modelId"], thread["modelGgufVariant"]) == ("unsloth/Qwen3-0.6B-GGUF", "Q4_K_M")+ details = studio_db.list_chat_messages(thread_id)[1]["metadata"]["responseDetails"]+ assert (details["modelId"], details["modelLabel"]) == (+ "unsloth/Qwen3-0.6B-GGUF",+ "Qwen3-0.6B-Q4_K_M",+ )+++def test_an_answer_without_reasoning_carries_no_reasoning_time(monkeypatch):+ task, run = claim_manual_run()+ answer = Answer(content = "Dawn light on the sill.", reasoning = "", model = "gemma-3")++ run_scheduler(task, run, answer = answer, monkeypatch = monkeypatch)++ thread_id = db.get_task(task["id"])["lastRun"]["threadId"]+ _user, assistant = studio_db.list_chat_messages(thread_id)+ assert assistant["content"] == [{"type": "text", "text": "Dawn light on the sill."}]+ assert "reasoningDuration" not in assistant["metadata"]+++ "failure, code, error",+ [+ (RunFailed("no_model"), "no_model", None),+ (RunFailed(None, "context window exceeded"), None, "context window exceeded"),+ (RuntimeError("llama-server exited"), None, "llama-server exited"),+ ],+)+def test_a_failed_run_records_why_and_writes_no_chat(monkeypatch, failure, code, error):+ task, run = claim_manual_run()++ run_scheduler(task, run, failure = failure, monkeypatch = monkeypatch)++ last_run = db.get_task(task["id"])["lastRun"]+ assert (last_run["status"], last_run["errorCode"], last_run["error"]) == (+ "failed",+ code,+ error,+ )+ assert studio_db.list_chat_threads() == []+++def test_a_task_deleted_mid_run_writes_no_chat(monkeypatch):+ task, run = claim_manual_run()++ async def delete_then_answer(app, task, run, *_):+ await asyncio.to_thread(db.delete_task, task["id"])+ return Answer(content = "Too late.", reasoning = "", model = "gemma-3")++ monkeypatch.setattr(scheduler_module, "generate_answer", delete_then_answer)+ execute(task, run)++ assert studio_db.list_chat_threads() == []+++def recording_generate(asked):+ async def generate(app, task, run, *_):+ asked.append(run["id"])+ return Answer(content = "Done.", reasoning = "", model = "gemma-3")++ return generate+++def test_a_task_deleted_before_its_claimed_run_starts_is_not_run(monkeypatch):+ task, run = claim_manual_run()+ asked = []+ monkeypatch.setattr(scheduler_module, "generate_answer", recording_generate(asked))+ db.delete_task(task["id"])+ execute(task, run)++ assert asked == []+ assert studio_db.list_chat_threads() == []+++def test_a_run_claimed_for_an_account_disabled_since_is_not_run(monkeypatch):+ task, run = claim_manual_run()+ asked = []+ monkeypatch.setattr(scheduler_module, "generate_answer", recording_generate(asked))+ monkeypatch.setattr(scheduler_module, "job_accounts", lambda: [])+ execute(task, run)++ assert asked == []+ last_run = db.get_task(task["id"])["lastRun"]+ assert (last_run["status"], last_run["errorCode"]) == ("failed", "cancelled")+++def test_the_sweep_removes_the_chat_of_a_run_that_stopped_before_settling():+ task, run = claim_manual_run()+ answer = Answer(content = "Written, never settled.", reasoning = "", model = "gemma-3")+ scheduler_module.save_chat(task, run, answer, 1_000, 2_000)+ assert len(studio_db.list_chat_threads()) == 1++ sweep(db.now_ms() + scheduler_module._STALE_RUN_MS + 1)++ assert studio_db.list_chat_threads() == []+ last_run = db.get_task(task["id"])["lastRun"]+ assert (last_run["status"], last_run["errorCode"]) == ("failed", "interrupted")+++def refuse_chat_deletion(conn, ids):+ raise sqlite3.OperationalError("disk I/O error")+++def test_a_sweep_that_cannot_remove_a_chat_records_nothing(monkeypatch):+ task, run = claim_manual_run()+ answer = Answer(content = "Written, never settled.", reasoning = "", model = "gemma-3")+ scheduler_module.save_chat(task, run, answer, 1_000, 2_000)+ monkeypatch.setattr(db, "delete_chat_threads_in", refuse_chat_deletion)++ with pytest.raises(sqlite3.OperationalError):+ sweep(db.now_ms() + scheduler_module._STALE_RUN_MS + 1)++ assert db.get_task(task["id"])["lastRun"]["status"] == "running"+ assert len(studio_db.list_chat_threads()) == 1+++def test_a_run_recorded_as_failed_takes_its_chat_in_the_same_transaction(monkeypatch):+ task, run = claim_manual_run()+ answer = Answer(content = "Written, then failed.", reasoning = "", model = "gemma-3")+ scheduler_module.save_chat(task, run, answer, 1_000, 2_000)+ delete_chat_threads_in = db.delete_chat_threads_in+ monkeypatch.setattr(db, "delete_chat_threads_in", refuse_chat_deletion)+ with pytest.raises(sqlite3.OperationalError):+ db.finish_run(run["id"], "worker-under-test", status = "failed", discard_chat = True)+ assert db.get_task(task["id"])["lastRun"]["status"] == "running"+ assert len(studio_db.list_chat_threads()) == 1++ monkeypatch.setattr(db, "delete_chat_threads_in", delete_chat_threads_in)+ assert db.finish_run(run["id"], "worker-under-test", status = "failed", discard_chat = True)+ assert db.get_task(task["id"])["lastRun"]["status"] == "failed"+ assert studio_db.list_chat_threads() == []+++def test_a_run_that_fails_after_writing_its_chat_leaves_none_however_soon_studio_stops(monkeypatch):+ task, run = claim_manual_run()+ save_chat = scheduler_module.save_chat++ def save_then_fail(*args):+ save_chat(*args)+ raise sqlite3.OperationalError("disk I/O error")++ monkeypatch.setattr(scheduler_module, "generate_answer", answer_with("Half saved."))+ monkeypatch.setattr(scheduler_module, "save_chat", save_then_fail)+ monkeypatch.setattr(scheduler_module, "_discard_chat", lambda thread_id: None)+ execute(task, run)++ assert db.get_task(task["id"])["lastRun"]["status"] == "failed"+ assert studio_db.list_chat_threads() == []+++def test_deleting_a_task_removes_only_the_chat_its_running_run_may_be_writing():+ task, run = claim_manual_run()+ kept = scheduler_module.save_chat(+ task, run, Answer(content = "Finished.", reasoning = "", model = "gemma-3"), 1_000, 2_000+ )+ assert db.finish_run(run["id"], "worker-under-test", status = "succeeded", thread_id = kept)+ db.request_run(task["id"])+ _task, running = claim()+ scheduler_module.save_chat(+ task, running, Answer(content = "Mid-run.", reasoning = "", model = "gemma-3"), 3_000, 4_000+ )+ assert len(studio_db.list_chat_threads()) == 2++ assert db.delete_task(task["id"])++ assert [thread["id"] for thread in studio_db.list_chat_threads()] == [kept]+++def test_a_task_deleted_while_its_chat_is_saved_keeps_no_chat(monkeypatch):+ task, run = claim_manual_run()++ answer = answer_with("Just in time?")+ save_chat = scheduler_module.save_chat++ def save_then_delete(*args):+ thread_id = save_chat(*args)+ db.delete_task(task["id"])+ return thread_id++ monkeypatch.setattr(scheduler_module, "generate_answer", answer)+ monkeypatch.setattr(scheduler_module, "save_chat", save_then_delete)+ execute(task, run)++ assert db.get_task(task["id"]) is None+ assert studio_db.list_chat_threads() == []+++def answer_with(content):+ async def generate(app, task, run, *_):+ return Answer(content = content, reasoning = "", model = "gemma-3")++ return generate+++def test_settling_a_run_is_tried_again_over_a_locked_database(monkeypatch):+ task, run = claim_manual_run()+ finish_run = db.finish_run+ attempts = []++ def locked_once(*args, **kwargs):+ attempts.append(args)+ if len(attempts) == 1:+ raise sqlite3.OperationalError("database is locked")+ return finish_run(*args, **kwargs)++ monkeypatch.setattr(scheduler_module, "generate_answer", answer_with("Done."))+ monkeypatch.setattr(scheduler_module, "_SETTLE_RETRY_SECONDS", 0)+ monkeypatch.setattr(db, "finish_run", locked_once)+ execute(task, run)++ assert len(attempts) == 2+ last_run = db.get_task(task["id"])["lastRun"]+ assert last_run["status"] == "succeeded"+ assert [thread["id"] for thread in studio_db.list_chat_threads()] == [last_run["threadId"]]+++def test_a_chat_whose_run_cannot_be_settled_is_removed(monkeypatch):+ task, run = claim_manual_run()++ def locked(*args, **kwargs):+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr(scheduler_module, "generate_answer", answer_with("Stranded."))+ monkeypatch.setattr(scheduler_module, "_SETTLE_RETRY_SECONDS", 0)+ monkeypatch.setattr(db, "finish_run", locked)+ execute(task, run)++ assert studio_db.list_chat_threads() == []+ assert db.get_task(task["id"])["lastRun"]["status"] == "running"+++class FakeProducer:+ def __init__(+ self,+ response = None,+ error = None,+ hang = False,+ ):+ self.response, self.error, self.hang = response, error, hang+ self.payload = self.request = None+ self.cancelled = False++ async def __call__(self, payload, request, current_subject, *, cancel_on_disconnect):+ self.payload, self.request = payload, request+ assert cancel_on_disconnect is False+ if self.hang:+ try:+ await asyncio.sleep(3600)+ except asyncio.CancelledError:+ self.cancelled = True+ raise+ if self.error is not None:+ raise self.error+ return self.response+++def completion(+ content,+ reasoning = None,+ model = "gemma-3",+):+ message = {"role": "assistant", "content": content}+ if reasoning is not None:+ message["reasoning_content"] = reasoning+ return JSONResponse(+ {"model": model, "choices": [{"index": 0, "message": message, "finish_reason": "stop"}]}+ )+++class LoadsItsModel(FakeProducer):+ """A producer whose request loads the model it names, as the backend's switch does."""++ def __init__(self, monkeypatch, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.monkeypatch = monkeypatch++ async def __call__(self, payload, request, current_subject, *, cancel_on_disconnect):+ self.monkeypatch.setattr(+ inference_routes, "_loaded_satisfies", lambda model: model == payload.model+ )+ return await super().__call__(+ payload, request, current_subject, cancel_on_disconnect = cancel_on_disconnect+ )+++def generate(+ monkeypatch,+ producer,+ task = None,+ cancel_event = None,+):+ monkeypatch.setattr(inference_routes, "produce_openai_chat_completions", producer)+ task = task or make_task(timezone = "Europe/Istanbul")+ run = {"id": "run-1"}+ app = SimpleNamespace(state = SimpleNamespace())+ return asyncio.run(generate_answer(app, task, run, cancel_event or threading.Event()))+++def test_a_run_asks_the_loaded_model_for_text_only(monkeypatch):+ producer = FakeProducer(completion("Dawn light.", reasoning = "Short."))+ monkeypatch.setattr(db, "now_ms", lambda: ms("2026-10-14T06:00:00+00:00"))++ answer = generate(monkeypatch, producer)++ assert answer == Answer(content = "Dawn light.", reasoning = "Short.", model = "gemma-3")+ payload = producer.payload+ assert "model" not in payload.model_fields_set+ assert payload.stream is False+ assert payload.tool_choice == "none" and payload.enabled_tools == []+ assert payload.cancel_id == "run-1"+ system, user = payload.messages+ assert system.role == "system"+ # The time in the task's own zone: 06:00 UTC is 09:00 in Istanbul.+ assert "Wednesday, October 14, 2026 at 09:00 (Europe/Istanbul)" in system.content+ assert user.role == "user" and user.content == "Write a haiku about mornings."+ request = producer.request+ assert request.headers["x-unsloth-timezone"] == "Europe/Istanbul"+ assert request.headers["x-unsloth-require-text"] == "1"+ assert request.state.api_monitor_via_api_key is False+ assert request.state.keyless_api_admitted is False++[email protected]("primary", [None, "gemma-3"])+def test_a_run_names_the_one_model_kept_alongside_only_when_the_primary_is_empty(+ monkeypatch, primary+):+ from core.inference import model_slots++ gguf = SimpleNamespace(+ llama = SimpleNamespace(is_loaded = True, model_identifier = "qwen-kept"),+ orchestrator = SimpleNamespace(active_model_name = None),+ )+ monkeypatch.setattr(model_slots, "visible", lambda: [gguf])+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: primary)+ producer = FakeProducer(completion("Dawn light."))++ generate(monkeypatch, producer)++ if primary is None:+ assert producer.payload.model == "qwen-kept"+ else:+ assert "model" not in producer.payload.model_fields_set+++def test_a_run_finds_a_kept_safetensors_model_and_skips_a_primary_hidden_from_its_account(+ monkeypatch,+):+ from core.inference import model_slots+ from hub.services.models import account_access++ mlx = SimpleNamespace(+ llama = SimpleNamespace(is_loaded = False, model_identifier = None),+ orchestrator = SimpleNamespace(active_model_name = "my/mlx-model"),+ )+ monkeypatch.setattr(model_slots, "visible", lambda: [mlx])+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: "their/model")+ monkeypatch.setattr(account_access, "managed_account", lambda: True)+ monkeypatch.setattr(account_access, "resident_hidden", lambda kind, ident: True)+ assert scheduler_module._sole_kept_model() == "my/mlx-model"++ monkeypatch.setattr(account_access, "resident_hidden", lambda kind, ident: False)+ assert scheduler_module._sole_kept_model() is None+++def test_a_run_settles_its_request_where_the_slot_was_routed(monkeypatch):+ from core.inference import model_slots++ seen = []+ monkeypatch.setattr(+ llama_keepwarm,+ "end_in_process_request",+ lambda scope, answered: seen.append((model_slots.routed_slot.get(), answered)),+ )++ slot = SimpleNamespace(+ llama = SimpleNamespace(is_loaded = True, model_identifier = "kept/model", hf_variant = "Q4_K_M"),+ orchestrator = SimpleNamespace(active_model_name = None),+ )++ class Routed(FakeProducer):+ async def __call__(self, *args, **kwargs):+ model_slots.routed_slot.set(slot)+ return await super().__call__(*args, **kwargs)++ answer = generate(monkeypatch, Routed(completion("Done.")))+ assert seen == [(slot, True)]+ assert (answer.checkpoint, answer.gguf_variant) == ("kept/model", "Q4_K_M")+++def test_a_named_kept_model_keeps_its_own_refusal(monkeypatch):+ monkeypatch.setattr(scheduler_module, "_sole_kept_model", lambda: "qwen-kept")+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: None)+ producer = FakeProducer(+ error = HTTPException(status_code = 400, detail = {"error": {"message": "Too long."}})+ )+ with pytest.raises(RunFailed) as failure:+ generate(monkeypatch, producer)+ assert (failure.value.code, failure.value.message) == (None, "Too long.")+++def test_a_run_picks_its_kept_model_after_the_model_gate_lets_it_in(monkeypatch):+ from core.inference import model_slots++ def kept(name):+ return SimpleNamespace(+ llama = SimpleNamespace(is_loaded = True, model_identifier = name),+ orchestrator = SimpleNamespace(active_model_name = None),+ )++ slots = [kept("before-the-wait")]+ monkeypatch.setattr(model_slots, "visible", lambda: slots)+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: None)+ real_start = llama_keepwarm.InferenceActivityReservation.start++ async def start(self, cancel_event = None):+ slots[:] = [kept("after-the-wait")]+ return await real_start(self, cancel_event)++ monkeypatch.setattr(llama_keepwarm.InferenceActivityReservation, "start", start)+ producer = FakeProducer(completion("Done."))+ generate(monkeypatch, producer)+ assert producer.payload.model == "after-the-wait"+++def test_a_reply_marked_failed_does_not_claim_the_model(monkeypatch):+ claims = []+ monkeypatch.setattr(llama_keepwarm, "_claim_non_preview_slot", lambda: claims.append(1))+ scope = {+ llama_keepwarm._ADMITTED_SCOPE_KEY: True,+ llama_keepwarm._RESPONSE_FAILED_SCOPE_KEY: True,+ }+ llama_keepwarm.end_in_process_request(scope, answered = True)+ llama_keepwarm.end_in_process_request({llama_keepwarm._ADMITTED_SCOPE_KEY: True}, answered = True)+ assert claims == [1]+++def test_a_run_skips_a_speech_primary_for_the_text_model_kept_alongside(monkeypatch):+ from core.inference import model_slots++ def slot(name, audio):+ return SimpleNamespace(+ llama = SimpleNamespace(is_loaded = True, model_identifier = name, _is_audio = audio),+ orchestrator = SimpleNamespace(active_model_name = None),+ )++ monkeypatch.setattr(+ model_slots, "visible", lambda: [slot("tts/voice", True), slot("text/model", False)]+ )+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: "speech/primary")+ speech = SimpleNamespace(is_loaded = True, _is_audio = True)+ monkeypatch.setattr(inference_routes, "get_llama_cpp_backend", lambda: speech)+ assert scheduler_module._sole_kept_model() == "text/model"++ speech._is_audio = False+ assert scheduler_module._sole_kept_model() is None+++def test_a_run_never_loads_a_model_and_a_vanished_kept_model_means_no_model(monkeypatch):+ request = scheduler_module._producer_request(None, "run-1", threading.Event(), "UTC")+ assert request.scope[inference_routes.LOADED_MODELS_ONLY_SCOPE_KEY] is True++ # Named the kept model, which was unloaded before the request reached it.+ names = iter(["kept/model", None])+ monkeypatch.setattr(scheduler_module, "_sole_kept_model", lambda: next(names))+ producer = FakeProducer(error = HTTPException(status_code = 400, detail = "No model loaded."))+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: None)+ with pytest.raises(RunFailed) as failure:+ generate(monkeypatch, producer)+ assert failure.value.code == "no_model"+++def test_a_run_skips_whisper_which_refuses_a_request_without_audio(monkeypatch):+ from core.inference import model_slots++ def orchestrator(name, info):+ return SimpleNamespace(active_model_name = name, models = {name: info})++ whisper = {"is_audio": True, "audio_type": "whisper"}+ text = SimpleNamespace(+ llama = SimpleNamespace(is_loaded = False), orchestrator = orchestrator("text/model", {})+ )+ kept_whisper = SimpleNamespace(+ llama = SimpleNamespace(is_loaded = False), orchestrator = orchestrator("asr/kept", whisper)+ )+ monkeypatch.setattr(model_slots, "visible", lambda: [text, kept_whisper])+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: "asr/primary")+ monkeypatch.setattr(+ inference_routes, "get_llama_cpp_backend", lambda: SimpleNamespace(is_loaded = False)+ )+ monkeypatch.setattr(+ inference_routes, "_peek_inference_backend", lambda: orchestrator("asr/primary", whisper)+ )+ assert scheduler_module._sole_kept_model() == "text/model"+++def test_a_run_with_no_model_loaded_says_so(monkeypatch):+ producer = FakeProducer(error = HTTPException(status_code = 400, detail = "No model loaded."))+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: None)+ with pytest.raises(RunFailed) as failure:+ generate(monkeypatch, producer)+ assert failure.value.code == "no_model"+++def test_a_refusal_from_a_loaded_model_keeps_its_reason(monkeypatch):+ producer = FakeProducer(+ error = HTTPException(status_code = 400, detail = {"error": {"message": "Too long."}})+ )+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: "gemma-3")+ with pytest.raises(RunFailed) as failure:+ generate(monkeypatch, producer)+ assert (failure.value.code, failure.value.message) == (None, "Too long.")+++def test_a_scheduled_run_waits_for_a_reply_being_generated(monkeypatch):+ keepwarm = llama_keepwarm+ busy = iter([True, True, False])+ monkeypatch.setattr(keepwarm, "inference_in_flight", lambda: next(busy))+ monkeypatch.setattr(scheduler_module, "_YIELD_POLL_SECONDS", 0.0)+ scheduler = new_scheduler()+ asyncio.run(scheduler._yield_to_inference(threading.Event()))+ assert next(busy, "done") == "done"+ monkeypatch.setattr(keepwarm, "inference_in_flight", lambda: True)+ monkeypatch.setattr(scheduler_module, "_YIELD_SECONDS", 0.0)+ asyncio.run(scheduler._yield_to_inference(threading.Event()))+++def test_only_a_signed_in_user_changes_tasks(client):+ task = create(client).json()+ client.app.dependency_overrides[authenticated_via_api_key] = lambda: True+ new_task = {+ "title": "x",+ "prompt": "y",+ "schedule": {"kind": "daily", "time": "09:00"},+ "timezone": "UTC",+ }+ for method, path, body in (+ ("post", "", new_task),+ ("patch", f"/{task['id']}", {"title": "Renamed"}),+ ("post", f"/{task['id']}/run", {}),+ ("delete", f"/{task['id']}", None),+ ):+ kwargs = {} if body is None else {"json": body}+ response = getattr(client, method)(f"/api/scheduled-tasks{path}", **kwargs)+ assert response.status_code == 403, (method, path)+ listed = client.get("/api/scheduled-tasks").json()["tasks"]+ assert [entry["title"] for entry in listed] == [task["title"]]+ assert client.get("/api/scheduled-tasks/runs?since=0").status_code == 200+++def test_a_new_chat_per_run_can_go_to_a_project_and_be_archived():+ make_project()+ task, run = claim_manual_run()+ db.update_task(task["id"], {"archiveSuccessful": True, "projectId": "proj-1"})+ task = db.get_task(task["id"])+ answer = Answer(content = "Done.", reasoning = "", model = "gemma-3")+ thread = studio_db.get_chat_thread(scheduler_module.save_chat(task, run, answer, 1_000, 2_000))+ assert (thread["projectId"], thread["archived"]) == ("proj-1", True)+++def test_a_project_deleted_since_the_task_was_saved_is_skipped():+ task, run = claim_manual_run()+ db.update_task(task["id"], {"projectId": "gone"})+ answer = Answer(content = "Done.", reasoning = "", model = "gemma-3")+ thread_id = scheduler_module.save_chat(db.get_task(task["id"]), run, answer, 1_000, 2_000)+ assert studio_db.get_chat_thread(thread_id)["projectId"] is None+++def test_an_empty_reply_is_a_failure(monkeypatch):+ with pytest.raises(RunFailed) as failure:+ generate(monkeypatch, FakeProducer(completion(" ", reasoning = "Thinking only.")))+ assert failure.value.code == "empty"+++def test_a_run_that_never_answers_is_stopped(monkeypatch):+ monkeypatch.setattr(scheduler_module, "_RUN_TIMEOUT_SECONDS", 0.05)+ producer = FakeProducer(hang = True)+ cancel_event = threading.Event()+ with pytest.raises(RunFailed) as failure:+ generate(monkeypatch, producer, cancel_event = cancel_event)+ assert failure.value.code == "timeout"+ assert cancel_event.is_set() and producer.cancelled+++def test_a_timed_out_run_counts_as_inference_until_its_worker_unwinds(monkeypatch):+ monkeypatch.setattr(scheduler_module, "_RUN_TIMEOUT_SECONDS", 0.05)+ monkeypatch.setattr(scheduler_module, "_CANCEL_GRACE_SECONDS", 0.01)+ unwound = asyncio.Event()++ async def slow_to_stop(*_, **__):+ try:+ await asyncio.sleep(3600)+ finally:+ await unwound.wait()++ monkeypatch.setattr(inference_routes, "produce_openai_chat_completions", slow_to_stop)+ app = SimpleNamespace(state = SimpleNamespace())++ async def scenario():+ with pytest.raises(RunFailed):+ await generate_answer(app, make_task(), {"id": "run-1"}, threading.Event())+ busy_while_unwinding = llama_keepwarm.inference_in_flight()+ unwound.set()+ for _ in range(20):+ await asyncio.sleep(0)+ return busy_while_unwinding, llama_keepwarm.inference_in_flight()++ assert asyncio.run(scenario()) == (True, False)+++class AdmittedProducer(FakeProducer):+ """Admits the request the way the auto-switch hook does for local chat."""++ async def __call__(self, payload, request, current_subject, *, cancel_on_disconnect):+ from core.inference import llama_keepwarm++ llama_keepwarm.note_admitted_inference(request.scope)+ self.admitted = llama_keepwarm.other_admitted_inference_count()+ return await super().__call__(+ payload, request, current_subject, cancel_on_disconnect = cancel_on_disconnect+ )++[email protected]("answers", [True, False])+def test_a_run_gives_back_its_admission_and_adopts_the_model_only_once_answered(+ monkeypatch, answers+):+ from core.inference import llama_keepwarm++ claims = []+ monkeypatch.setattr(inference_routes, "_set_preview_resident", claims.append)+ before = llama_keepwarm.other_admitted_inference_count()+ producer = (+ AdmittedProducer(completion("Done."))+ if answers+ else AdmittedProducer(error = HTTPException(status_code = 500, detail = "boom"))+ )+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: "gemma-3")+ try:+ generate(monkeypatch, producer)+ except RunFailed:+ assert not answers++ assert producer.admitted == before + 1+ assert llama_keepwarm.other_admitted_inference_count() == before+ assert claims == ([None] if answers else [])+++def test_a_run_whose_model_load_never_lets_go_times_out(monkeypatch):+ from core.inference import llama_keepwarm++ async def wedged(self, cancel_event = None):+ await asyncio.sleep(3600)++ monkeypatch.setattr(llama_keepwarm.InferenceActivityReservation, "start", wedged)+ monkeypatch.setattr(scheduler_module, "_RUN_TIMEOUT_SECONDS", 0.05)+ producer = FakeProducer(completion("Never asked."))+ with pytest.raises(RunFailed) as failure:+ generate(monkeypatch, producer)+ assert failure.value.code == "timeout"+ assert producer.payload is None+++def test_a_cancelled_run_discards_its_partial_answer(monkeypatch):+ cancel_event = threading.Event()++ class CancelledMidway(FakeProducer):+ async def __call__(self, *args, **kwargs):+ cancel_event.set()+ return completion("Half an ans")++ with pytest.raises(RunFailed) as failure:+ generate(monkeypatch, CancelledMidway(), cancel_event = cancel_event)+ assert failure.value.code == "cancelled"+++def test_the_scheduler_runs_a_due_task_and_wakes_for_run_now(monkeypatch):+ monkeypatch.setattr(scheduler_module, "job_accounts", lambda: [OWNER])+ answered = []++ async def fake_generate(app, task, run, *_):+ answered.append(run["source"])+ return Answer(content = "Done.", reasoning = "", model = "gemma-3")++ monkeypatch.setattr(scheduler_module, "generate_answer", fake_generate)+ make_task(nextRunAt = db.now_ms() - DAY)++ async def settled(count: int) -> None:+ for _ in range(500):+ last_run = db.get_task("task-1")["lastRun"]+ if len(answered) == count and last_run and last_run["status"] == "succeeded":+ return+ await asyncio.sleep(0.01)+ raise AssertionError(f"run {count} never settled")++ async def scenario():+ scheduler = new_scheduler()+ scheduler.start()+ try:+ await settled(1)+ db.request_run("task-1")+ scheduler.wake()+ await settled(2)+ finally:+ await scheduler.stop()++ asyncio.run(scenario())++ assert answered == ["schedule", "manual"]+ assert len(studio_db.list_chat_threads()) == 2+ assert db.get_task("task-1")["nextRunAt"] > db.now_ms()+++def test_a_claim_given_back_is_due_again_or_queued_again():+ due_at = ms("2026-10-14T09:00:00+00:00")+ now = ms("2026-10-14T09:00:05+00:00")+ make_task(nextRunAt = due_at)+ task, run = db.claim_next(now, "worker", next_run_for)+ assert task["nextRunAt"] == ms("2026-10-15T09:00:00+00:00")++ assert db.release_claim(run["id"], "worker", task["nextRunAt"])+ returned = db.get_task("task-1")+ assert (returned["nextRunAt"], returned["lastRun"]) == (due_at, None)+ assert not db.release_claim(run["id"], "worker", task["nextRunAt"])++ db.request_run("task-1")+ task, run = db.claim_next(now, "worker", next_run_for)+ assert run["source"] == "manual"+ assert db.release_claim(run["id"], "worker", task["nextRunAt"])+ assert db.get_task("task-1")["lastRun"]["status"] == "queued"+++ "change",+ [+ {"schedule": {"kind": "daily", "time": "18:00"}},+ {"enabled": False},+ ],+)+def test_a_claim_given_back_keeps_a_schedule_changed_since(change):+ make_task(nextRunAt = ms("2026-10-14T09:00:00+00:00"))+ task, run = db.claim_next(ms("2026-10-14T09:00:05+00:00"), "worker", next_run_for)+ changed = db.update_task(+ "task-1", change, lambda t: None if not t["enabled"] else ms("2026-10-14T18:00:00+00:00")+ )++ assert db.release_claim(run["id"], "worker", task["nextRunAt"])+ assert db.get_task("task-1")["nextRunAt"] == changed["nextRunAt"]+++def test_an_idle_pass_is_one_read_and_sleeps_until_the_next_due_run(monkeypatch):+ monkeypatch.setattr(scheduler_module, "job_accounts", lambda: [OWNER])+ due_at = db.now_ms() + 30_000+ make_task(nextRunAt = due_at)+ scheduler = new_scheduler()+ connect = db.get_connection+ opened = []++ def counted(*args, **kwargs):+ opened.append(1)+ return connect(*args, **kwargs)++ monkeypatch.setattr(db, "get_connection", counted)+ assert scheduler._claim() is None+ assert (len(opened), scheduler._due) == (1, due_at)+++def test_a_claim_made_as_shutdown_begins_is_given_back(monkeypatch):+ monkeypatch.setattr(scheduler_module, "job_accounts", lambda: [OWNER])+ due_at = db.now_ms() - DAY+ make_task(nextRunAt = due_at)+ scheduler = new_scheduler()+ poll = db.poll++ def claim_as_stop_begins(*args):+ answer = poll(*args)+ scheduler._stopping = True+ return answer++ monkeypatch.setattr(db, "poll", claim_as_stop_begins)++ assert scheduler._claim() is None+ task = db.get_task("task-1")+ assert (task["nextRunAt"], task["lastRun"]) == (due_at, None)+++def test_the_loop_gives_back_a_claim_that_returns_after_shutdown_began(monkeypatch):+ monkeypatch.setattr(scheduler_module, "job_accounts", lambda: [OWNER])+ due_at = db.now_ms() - DAY+ make_task(nextRunAt = due_at)+ scheduler = new_scheduler()+ claim = scheduler._claim+ started = []++ def claim_then_stop():+ claimed = claim()+ scheduler._stopping = True+ return claimed++ async def execute(*args):+ started.append(args)++ monkeypatch.setattr(scheduler, "_claim", claim_then_stop)+ monkeypatch.setattr(scheduler, "_execute", execute)++ async def scenario():+ scheduler.start()+ await asyncio.wait_for(scheduler._task, timeout = 10)++ asyncio.run(scenario())++ assert started == []+ task = db.get_task("task-1")+ assert (task["nextRunAt"], task["lastRun"]) == (due_at, None)+++def test_a_cancellation_raised_for_a_run_ends_the_run_not_the_scheduler(monkeypatch):+ monkeypatch.setattr(scheduler_module, "job_accounts", lambda: [OWNER])+ calls = []++ async def fake_generate(app, task, run, *_):+ calls.append(run["id"])+ if len(calls) == 1:+ raise asyncio.CancelledError()+ return Answer(content = "Done.", reasoning = "", model = "gemma-3")++ monkeypatch.setattr(scheduler_module, "generate_answer", fake_generate)+ make_task(nextRunAt = db.now_ms() + DAY)+ db.request_run("task-1")++ async def settled(count: int) -> dict:+ for _ in range(500):+ runs = db.list_runs("task-1")+ if len(calls) == count and runs and runs[0]["status"] in ("succeeded", "failed"):+ return runs[0]+ await asyncio.sleep(0.01)+ raise AssertionError(f"run {count} never settled")++ async def scenario():+ scheduler = new_scheduler()+ scheduler.start()+ try:+ first = await settled(1)+ assert (first["status"], first["errorCode"]) == ("failed", "cancelled")+ db.request_run("task-1")+ scheduler.wake()+ assert (await settled(2))["status"] == "succeeded"+ finally:+ await scheduler.stop()++ asyncio.run(scenario())+++def test_a_run_s_own_cancel_is_told_apart_without_task_cancelling():+ # Python 3.10 tasks have no cancelling(): only a stopping scheduler cancels its loop there.+ old_task = SimpleNamespace()+ assert scheduler_module._loop_cancelled(old_task, stopping = False) is False+ assert scheduler_module._loop_cancelled(old_task, stopping = True) is True+ assert scheduler_module._loop_cancelled(SimpleNamespace(cancelling = lambda: 1), False) is True+ assert scheduler_module._loop_cancelled(None, True) is False+++def test_the_system_prompt_falls_back_to_utc_for_an_unknown_zone():+ prompt = scheduler_module.system_prompt(+ {"timezone": "Gone/Zone"}, ms("2026-10-14T06:00:00+00:00")+ )+ assert "Wednesday, October 14, 2026 at 06:00 (Gone/Zone)" in promptdiff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex b05dcfa3bb0..1140acebca1 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -427,8 +427,11 @@ export const BUDGET = {// raw, 2,088,616 -> 2,088,672 B transfer against cfc593f0bd, Node 26, unchanged at 99 chunks). Raised by that.// Its "System and Engine" page title adds 11 B raw / 34 B transfer to the eager en locale (6,933,189 -> 6,933,200 B// raw, 2,088,699 -> 2,088,733 B transfer merged with f49cbdf535, Node 26, 99 chunks). Raised by that.- transferBytes: 2_091_207,- rawBytes: 6_942_431,+ // Scheduled tasks (#13871) add 15.9 KB raw / 5.0 KB transfer (results poll, unseen dots, strings; page and+ // dialog lazy): 6,766.5 -> 6,782.4 KB raw, 2,041.5 -> 2,046.5 KB transfer against main 90164297d, one machine+ // and build, Node 24, 105 chunks. Raised by that growth over main's budget.+ transferBytes: 2_096_327,+ rawBytes: 6_958_713,};// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering thediff --git a/studio/frontend/src/app/router.tsx b/studio/frontend/src/app/router.tsxindex 85ee5f04d74..f2ed533568d 100644--- a/studio/frontend/src/app/router.tsx+++ b/studio/frontend/src/app/router.tsx@@ -19,6 +19,7 @@ import { Route as loginRoute } from "./routes/login";import { Route as hubRoute } from "./routes/hub";import { Route as projectsRoute } from "./routes/projects";import { Route as libraryRoute } from "./routes/library";+import { Route as tasksRoute } from "./routes/tasks";import { Route as changePasswordRoute } from "./routes/change-password";import { Route as settingsRoute } from "./routes/settings";import { Route as studioRoute } from "./routes/studio";@@ -33,6 +34,7 @@ const routeTree = rootRoute.addChildren([chatRoute,projectsRoute,libraryRoute,+ tasksRoute,exportRoute,imagesRoute,videoRoute,diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 9a400df37f0..3cd5ae9dffb 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -41,6 +41,7 @@ import {import { backfillModelOverrides } from "@/features/model-picker/api/migrate-model-overrides";import { hydratePins } from "@/lib/pins-mirror";import { usePersonalizationSync } from "@/features/profile";+import { ScheduledTaskRunNotifier } from "@/features/scheduled-tasks/run-notifier";import { RemoteCodeConsentDialog } from "@/features/security";import {SETTINGS_TABS,@@ -277,6 +278,8 @@ const CHAT_ONLY_ALLOWED = new Set(["/chat","/projects","/library",+ // Tasks only need a chat model, which a chat-only host runs.+ "/tasks","/hub","/login","/signup",@@ -824,8 +827,9 @@ function RootLayout() {</SidebarInset></SidebarProvider>)}- {/* This side-effect-only mount stays last so it cannot shift existing React useId paths. */}+ {/* These side-effect-only mounts stay last so they cannot shift existing React useId paths. */}{!isAuthFlowRoute && <HubSourceNoticeMount />}+ {!isAuthFlowRoute && <ScheduledTaskRunNotifier />}</>);diff --git a/studio/frontend/src/app/routes/tasks.tsx b/studio/frontend/src/app/routes/tasks.tsxnew file mode 100644index 00000000000..bf5579e50a8--- /dev/null+++ b/studio/frontend/src/app/routes/tasks.tsx@@ -0,0 +1,24 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { createRoute, lazyRouteComponent } from "@tanstack/react-router";+import { requireAuth } from "../auth-guards";+import { Route as rootRoute } from "./__root";++const TasksPage = lazyRouteComponent(+ () => import("@/features/scheduled-tasks/tasks-page"),+ "TasksPage",+);++export const Route = createRoute({+ getParentRoute: () => rootRoute,+ path: "/tasks",+ staticData: { titleKey: "shell.navigation.tasks" },+ // ?edit=<task id> opens that task; ?create=true opens a new one.+ validateSearch: (search: Record<string, unknown>): { edit?: string; create?: boolean } => ({+ ...(typeof search.edit === "string" && search.edit !== "" ? { edit: search.edit } : {}),+ ...(search.create === true || search.create === "true" ? { create: true } : {}),+ }),+ beforeLoad: () => requireAuth(),+ component: TasksPage,+});diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 9950b644009..48e4282f4ea 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -148,8 +148,14 @@ import {ArrowUpDownIcon,LayerIcon,ApiIcon,+ Clock01Icon,} from "@hugeicons/core-free-icons";-import { AiSpeechIcon, MessageCircleIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";+import {+ AiSpeechIcon,+ MessageCircleIcon,+ TestTubeOutlineIcon,+ withNoticeDot,+} from "@/lib/hugeicons-derived";import {Tooltip,TooltipContent,@@ -315,6 +321,7 @@ import { ShutdownDialog } from "@/components/shutdown-dialog";import { buildChatItemMarkdown } from "@/features/chat/prompt-storage/prompt-storage-dialog";import { useActiveChatMenuStore } from "@/features/chat/stores/active-chat-menu-store";import { type PinnedPage, PinnedPageRow, usePinnedPages } from "@/features/browser";+import { useUnseenScheduledRuns } from "@/features/scheduled-tasks";import { translate, useT, type TranslationKey } from "@/i18n";const RECENT_SLOT_NUMBERS = [1, 2, 3, 4, 5, 6] as const;@@ -371,12 +378,18 @@ type NavRowDef = {dimmed?: boolean;tooltipAction?: { label: string; onClick: () => void };badge?: string;+ // Something new behind the row; its icon carries the dot, and More repeats it while unpinned.+ dot?: boolean;+ // A "+" that makes a new one of the row's things, offered in More when the row is unpinned.+ newAction?: { label: string; run: () => void };onClick: () => void;onIntent?: () => void;className?: string;children?: ReactNode;};+const CLOCK_NOTICE_ICON = withNoticeDot(Clock01Icon);+// row kebab with centred dots: Hugeicons draws them half a unit low.const MoreVerticalCenteredIcon = MoreVerticalIcon.map(([tag, attrs]) => [tag,@@ -1008,6 +1021,7 @@ const MORE_DOTS_ICON: IconSvgElement = [["circle", { cx: "12", cy: "12", r: "1", stroke: "currentColor", strokeWidth: "1.5", key: "1" }],["circle", { cx: "19.5", cy: "12", r: "1", stroke: "currentColor", strokeWidth: "1.5", key: "2" }],];+const MORE_DOTS_NOTICE_ICON = withNoticeDot(MORE_DOTS_ICON);// A NavItem's affordances in dropdown-item form, for the "More" flyout.function MoreMenuItem({@@ -1019,6 +1033,7 @@ function MoreMenuItem({tooltip,badge,spinner,+ newAction,onSelect,onIntent,}: {@@ -1030,6 +1045,7 @@ function MoreMenuItem({tooltip?: string;badge?: string;spinner?: boolean;+ newAction?: NavRowDef["newAction"];onSelect: () => void;onIntent?: () => void;}) {@@ -1041,12 +1057,30 @@ function MoreMenuItem({onSelect={onSelect}onPointerEnter={disabled ? undefined : onIntent}onFocus={disabled ? undefined : onIntent}- className={cn(active && "bg-accent/60", dimmed && "opacity-50")}+ className={cn("group/more-item", active && "bg-accent/60", dimmed && "opacity-50")}><HugeiconsIcon icon={icon} strokeWidth={1.75} /><span className="min-w-0 flex-1 truncate">{label}</span>{badge && <Badge variant="secondary">{badge}</Badge>}{spinner && <Spinner className="size-3.5 shrink-0 text-muted-foreground" />}+ {newAction && (+ <button+ type="button"+ aria-label={newAction.label}+ title={newAction.label}+ // The item selects on click and pointer-up; the plus is its own action, not the row's.+ onPointerDown={(event) => event.stopPropagation()}+ onPointerUp={(event) => event.stopPropagation()}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ newAction.run();+ }}+ className="-my-1 -mr-1 ml-auto flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground opacity-0 transition-opacity hover:bg-[rgb(0_0_0_/_calc(0.06*var(--contrast-wash-gain,1)))] hover:text-foreground group-hover/more-item:opacity-100 group-data-[highlighted]/more-item:opacity-100 focus-visible:opacity-100 dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] [@media(pointer:coarse)]:opacity-100"+ >+ <HugeiconsIcon icon={PlusSignIcon} strokeWidth={1.75} className="size-4" />+ </button>+ )}</DropdownMenuItem>);}@@ -1335,6 +1369,8 @@ export function AppSidebar() {// Route alone is not enough: a page can gate its tour behind a capability check, and an entry// that dispatches to nobody does nothing when clicked.const routeTourId = getTourId(pathname);+ const scheduledNotice =+ useUnseenScheduledRuns((state) => state.page) && pathname !== "/tasks";const tourAvailable = useTourAvailable(routeTourId);const {pinned,@@ -3425,6 +3461,14 @@ export function AppSidebar() {preloadSilently(router.preloadRoute({ to: "/projects" }));},className: "group/projects-item relative",+ newAction: {+ label: "New project",+ run: () => {+ setMoreOpen(false);+ setProjectCreateMoveTarget(null);+ setCreatingProject(true);+ },+ },// The inline "new project" affordance only fits a real row.children: (<button@@ -3594,6 +3638,45 @@ export function AppSidebar() {preloadSilently(router.preloadRoute({ to: "/api-monitor" }));},},+ tasks: {+ icon: scheduledNotice ? CLOCK_NOTICE_ICON : Clock01Icon,+ label: t("shell.navigation.tasks"),+ badge: t("shell.navigation.newBadge"),+ active: pathname === "/tasks",+ dot: scheduledNotice,+ onClick: () => {+ navigateFromRow({ to: "/tasks" });+ closeMobileIfOpen();+ },+ onIntent: () => {+ preloadSilently(router.preloadRoute({ to: "/tasks" }));+ },+ className: "group/tasks-item relative",+ newAction: {+ label: t("scheduledTasks.newTask"),+ run: () => {+ setMoreOpen(false);+ navigateFromRow({ to: "/tasks", search: { create: true } });+ closeMobileIfOpen();+ },+ },+ children: (+ <button+ type="button"+ aria-label={t("scheduledTasks.newTask")}+ onClick={(e) => {+ e.stopPropagation();+ navigateFromRow({ to: "/tasks", search: { create: true } });+ closeMobileIfOpen();+ }}+ className="sidebar-row-action group-hover/tasks-item:opacity-100 group-hover/tasks-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto group-data-[collapsible=icon]:hidden"+ >+ <span className="sidebar-row-action-glyph">+ <HugeiconsIcon icon={PlusSignIcon} strokeWidth={1.75} className="size-4" />+ </span>+ </button>+ ),+ },};// The Projects row repeats the section, so it only earns its place while the section is absent.const navRowPinned = (item: SidebarNavItemPref) =>@@ -5510,8 +5593,10 @@ export function AppSidebar() {);const hasUnreadActivity =!isGenerating && !hasQueuedActivity && alreadyUnread;- // The spinner and the unread dot say more, and share its spot.- const showForkMark = Boolean(item.isFork) && !showWorkSpinner && !hasUnreadActivity;+ // A scheduled task's chat carries a clock in the same slot, once there is no news to show.+ const showScheduledMark = Boolean(item.isScheduled) && !showWorkSpinner && !hasUnreadActivity;+ const showForkMark =+ Boolean(item.isFork) && !showWorkSpinner && !hasUnreadActivity && !showScheduledMark;const itemClass = cn(variant === "project"? "group/project-chat-item relative"@@ -5530,7 +5615,7 @@ export function AppSidebar() {isPinned && variant !== "project" && "gap-[calc(8.5px*var(--ui-space-scale,1))]",// A spinner glyph cannot truncate, and the pin and the kebab overlay that same edge, so a// working row holds their room open whether or not it is hovered.- showWorkSpinner ? "pr-16" : hasUnreadActivity || showForkMark ? "pr-9" : undefined,+ showWorkSpinner ? "pr-16" : hasUnreadActivity || showForkMark ? "pr-9" : showScheduledMark ? "pr-7" : undefined,// Coarse pointers reveal the actions permanently, so the spinner drops back beside// them (right-16, ending 78px in) and the title has to clear that, not just pr-16.showWorkSpinner && "[@media(pointer:coarse)]:pr-[calc(78px*var(--ui-space-scale,1))]",@@ -5664,6 +5749,20 @@ export function AppSidebar() {<span className="size-2 rounded-full bg-primary" /></span>) : null}+ {showScheduledMark ? (+ <span+ role="img"+ aria-label={translate("scheduledTasks.chatMark")}+ className={cn(+ "pointer-events-none absolute right-2 top-1/2 z-10 flex size-4 -translate-y-1/2 items-center justify-center text-muted-foreground transition-opacity",+ variant === "project"+ ? "group-hover/project-chat-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:opacity-0 group-has-[.sidebar-row-action:focus-visible]/project-chat-item:opacity-0"+ : "group-hover/recent-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/recent-item:opacity-0 group-has-[.sidebar-row-action:focus-visible]/recent-item:opacity-0",+ )}+ >+ <HugeiconsIcon icon={Clock01Icon} strokeWidth={1.75} className="size-3.5" />+ </span>+ ) : null}{showForkMark ? (// In the trailing column the spinner uses, and yields it to the pin and kebab like the unread dot.<span@@ -6395,7 +6494,11 @@ export function AppSidebar() {className="sidebar-nav-btn h-[calc(33px*var(--ui-space-scale,1))] rounded-full gap-[calc(8.5px*var(--ui-space-scale,1))] pl-3 pr-2.5 font-medium group-data-[collapsible=icon]:!p-0 group-data-[collapsible=icon]:!size-[calc(28px*var(--ui-space-scale,1))] group-data-[collapsible=icon]:my-[calc(2.5px*var(--ui-space-scale,1))] group-data-[collapsible=icon]:mx-auto"><HugeiconsIcon- icon={MORE_DOTS_ICON}+ icon={+ overflowNavIds.some((id) => navRows[id].dot)+ ? MORE_DOTS_NOTICE_ICON+ : MORE_DOTS_ICON+ }strokeWidth={1.75}className="size-icon! shrink-0 translate-x-0.5 group-data-[collapsible=icon]:translate-x-0 group-hover/menu-button:animate-icon-pop"/>@@ -6420,7 +6523,7 @@ export function AppSidebar() {side="right"align="start"sideOffset={6}- className="sidebar-more-menu w-48 p-1"+ className="sidebar-more-menu w-max min-w-48 max-w-72 p-1 [--icon-dot-ring:var(--popover)] dark:[--icon-dot-ring:var(--sidebar)]"{...moreHover.content}// The trigger handles its own presses.onPointerDownOutside={(event) => {@@ -6494,6 +6597,7 @@ export function AppSidebar() {: rowState.tooltip}spinner={rowState.spinner}+ newAction={row.newAction}onSelect={row.onClick}onIntent={row.onIntent}/>diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 166265d3048..6f598553e32 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -435,6 +435,7 @@ import {UndoIcon,VolumeMute02Icon,WorkflowCircle05Icon,+ Clock01Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { RefreshGlyph } from "@/lib/refresh-icon";@@ -9289,6 +9290,46 @@ const UserMessageAudio: FC = () => {);};+const SCHEDULED_REPLY_KEY = "scheduled-task-replies";++function scheduledTaskIdOf(custom: unknown): string | null {+ const source = (custom as { scheduledTask?: { taskId?: unknown } } | undefined)?.scheduledTask;+ return typeof source?.taskId === "string" ? source.taskId : null;+}++/** "Sent by scheduled task" over a task run's prompt; the reply carries the mark too, surviving rewrites. */+const ScheduledTaskSource: FC = () => {+ const t = useT();+ const navigate = useNavigate();+ const taskId = useAuiState(({ thread, message }) => {+ const own = scheduledTaskIdOf(message.metadata?.custom);+ if (own) return own;+ // One pass per messages snapshot, not a search per prompt per streamed token.+ const byPrompt = memoOnArrayByKey(thread.messages, SCHEDULED_REPLY_KEY, () => {+ const map = new Map<string, string>();+ thread.messages.forEach((entry, index) => {+ const reply = thread.messages[index + 1];+ const replyTask =+ reply?.role === "assistant" ? scheduledTaskIdOf(reply.metadata?.custom) : null;+ if (replyTask) map.set(entry.id, replyTask);+ });+ return map;+ });+ return byPrompt.get(message.id) ?? null;+ });+ if (!taskId) return null;+ return (+ <button+ type="button"+ onClick={() => void navigate({ to: "/tasks", search: { edit: taskId } })}+ className="inline-flex cursor-pointer items-center gap-1.5 rounded-md text-ui-13 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ <HugeiconsIcon icon={Clock01Icon} strokeWidth={1.75} className="size-3.5" />+ {t("scheduledTasks.sentBy")}+ </button>+ );+};+const UserMessage: FC = () => {const focusReveal = useActionBarFocusReveal();// Attachments alone (annotations, images) get no empty bubble under them.@@ -9302,6 +9343,7 @@ const UserMessage: FC = () => {tabIndex={0}{...focusReveal}>+ <ScheduledTaskSource /><UserMessageAttachments /><UserMessageAudio />diff --git a/studio/frontend/src/components/command-palette.tsx b/studio/frontend/src/components/command-palette.tsxindex 02814a55672..b5696734732 100644--- a/studio/frontend/src/components/command-palette.tsx+++ b/studio/frontend/src/components/command-palette.tsx@@ -45,6 +45,7 @@ import {Sun03Icon,TestTube01Icon,ApiIcon,+ Clock01Icon,} from "@hugeicons/core-free-icons";import { AiSpeechIcon } from "@/lib/hugeicons-derived";import { HugeiconsIcon } from "@hugeicons/react";@@ -302,6 +303,13 @@ function PaletteContent() {<HugeiconsIcon icon={LibrariesIcon} strokeWidth={1.75} /><span>{t("shell.navigation.library")}</span></PaletteItem>+ <PaletteItem+ onSelect={runAndClose(() => void navigate({ to: "/tasks" }))}+ keywords={["scheduled", "schedule", "tasks", "reminders"]}+ >+ <HugeiconsIcon icon={Clock01Icon} strokeWidth={1.75} />+ <span>{t("shell.navigation.tasks")}</span>+ </PaletteItem><PaletteItemonSelect={runAndClose(() => void navigate({ to: "/api-monitor" }))}keywords={["api", "monitor", "requests"]}diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex b1e9a5d47a5..3cca8f1187b 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -938,6 +938,7 @@ export interface SidebarRowRecord {modifiedAt?: number | null;modelIds?: string[] | null;isFork?: boolean | null;+ isScheduled?: boolean | null;/** Compare rows: each pane's own title, by `threadIds` position. */threadTitles?: string[] | null;projectId?: string | null;diff --git a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.tsindex e12fe69e580..fda05646fe8 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts@@ -39,6 +39,8 @@ export interface SidebarItem {modifiedAt?: number;modelIds?: string[];isFork?: boolean;+ /** Made by a scheduled task's run. */+ isScheduled?: boolean;projectId?: string | null;}@@ -96,6 +98,7 @@ export function groupThreads(...(t.modifiedAt ? { modifiedAt: t.modifiedAt } : {}),...(t.modelId ? { modelIds: [t.modelId] } : {}),isFork: Boolean(t.forkedFromThreadId),+ ...(t.scheduledTaskId ? { isScheduled: true } : {}),projectId: t.projectId ?? null,});}diff --git a/studio/frontend/src/features/chat/hooks/use-sidebar-row-pages.ts b/studio/frontend/src/features/chat/hooks/use-sidebar-row-pages.tsindex d8af5002ed9..e453f32fac6 100644--- a/studio/frontend/src/features/chat/hooks/use-sidebar-row-pages.ts+++ b/studio/frontend/src/features/chat/hooks/use-sidebar-row-pages.ts@@ -43,6 +43,7 @@ function toSidebarItem(row: SidebarRowRecord): SidebarItem | null {...(row.modifiedAt ? { modifiedAt: row.modifiedAt } : {}),...(row.modelIds?.length ? { modelIds: row.modelIds } : {}),...(row.type === "single" ? { isFork: Boolean(row.isFork) } : {}),+ ...(row.isScheduled ? { isScheduled: true } : {}),projectId: row.projectId ?? null,};}diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 81d4a0a6307..89e32784606 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -1421,6 +1421,7 @@ function toThreadMessage(m: MessageRecord): ThreadMessage {metadata: {custom: {...(m.metadata?.createdAtEstimated === true ? { createdAtEstimated: true } : {}),+ ...(m.metadata?.scheduledTask ? { scheduledTask: m.metadata.scheduledTask } : {}),...(typeof m.metadata?.revision === "number" ? { revision: m.metadata.revision } : {}),},},diff --git a/studio/frontend/src/features/chat/types.ts b/studio/frontend/src/features/chat/types.tsindex c33ad7d1b8c..aebc1517f98 100644--- a/studio/frontend/src/features/chat/types.ts+++ b/studio/frontend/src/features/chat/types.ts@@ -63,6 +63,8 @@ export interface ThreadRecord {forkTitleBase?: string | null;/** Last rename, move or (un)archive (server-set). */modifiedAt?: number | null;+ /** The scheduled task whose run made this chat (server-set). */+ scheduledTaskId?: string | null;/** this chat's own settings, applied when it is opened; absent means the global ones. */settings?:| import("./utils/thread-scoped-settings").ThreadScopedSettingsdiff --git a/studio/frontend/src/features/scheduled-tasks/api.ts b/studio/frontend/src/features/scheduled-tasks/api.tsnew file mode 100644index 00000000000..cd366668d6a--- /dev/null+++ b/studio/frontend/src/features/scheduled-tasks/api.ts@@ -0,0 +1,127 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch, getAuthSessionEpoch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";+import type { TaskSchedule } from "./schedule";++export const SCHEDULED_TASKS_API = "/api/scheduled-tasks";++export type TaskRunStatus = "queued" | "running" | "succeeded" | "failed";++export type TaskNotify = "all" | "failures" | "none";++export interface ScheduledTaskRun {+ id: string;+ taskId: string;+ source: "schedule" | "manual";+ status: TaskRunStatus;+ scheduledFor: number | null;+ createdAt: number;+ startedAt: number | null;+ finishedAt: number | null;+ threadId: string | null;+ model: string | null;+ errorCode: string | null;+ error: string | null;+}++export interface FinishedScheduledTaskRun extends ScheduledTaskRun {+ taskTitle: string;+ taskNotify: TaskNotify;+}++export interface ScheduledTask {+ id: string;+ title: string;+ prompt: string;+ schedule: TaskSchedule;+ timezone: string;+ enabled: boolean;+ notify: TaskNotify;+ named: boolean;+ archiveSuccessful: boolean;+ projectId: string | null;+ status: "active" | "paused" | "completed";+ nextRunAt: number | null;+ createdAt: number;+ updatedAt: number;+ lastRun: ScheduledTaskRun | null;+}++export interface ScheduledTaskInput {+ title: string;+ prompt: string;+ schedule: TaskSchedule;+ timezone: string;+ notify: TaskNotify;+ named: boolean;+ archiveSuccessful?: boolean;+ projectId?: string | null;+}++export type ScheduledTaskPatch = Partial<ScheduledTaskInput> & { enabled?: boolean };++export interface ScheduledTaskActivity {+ now: number;+ runs: FinishedScheduledTaskRun[];+ more: boolean;+ activeRuns: number;+ nextRunAt: number | null;+}++async function request<T>(path: string, init?: RequestInit): Promise<T> {+ const epoch = getAuthSessionEpoch();+ const res = await authFetch(+ `${SCHEDULED_TASKS_API}${path}`,+ {+ ...init,+ headers: init?.body ? { "Content-Type": "application/json" } : undefined,+ },+ {+ beforeRetry: () => {+ if (getAuthSessionEpoch() !== epoch) {+ throw new Error("Signed out before the scheduled task was saved.");+ }+ },+ },+ );+ if (!res.ok) throw new Error(await readFastApiError(res));+ return (res.status === 204 ? undefined : await res.json()) as T;+}++function taskPath(id: string, suffix = ""): string {+ return `/${encodeURIComponent(id)}${suffix}`;+}++export interface ScheduledTaskList {+ tasks: ScheduledTask[];+ now: number;+}++export function listScheduledTasks(): Promise<ScheduledTaskList> {+ return request("");+}++export function createScheduledTask(input: ScheduledTaskInput): Promise<ScheduledTask> {+ return request("", { method: "POST", body: JSON.stringify(input) });+}++export function updateScheduledTask(+ id: string,+ patch: ScheduledTaskPatch,+): Promise<ScheduledTask> {+ return request(taskPath(id), { method: "PATCH", body: JSON.stringify(patch) });+}++export function deleteScheduledTask(id: string): Promise<void> {+ return request(taskPath(id), { method: "DELETE" });+}++export function runScheduledTaskNow(id: string): Promise<ScheduledTaskRun> {+ return request(taskPath(id, "/run"), { method: "POST" });+}++export function getScheduledTaskActivity(since: number | null): Promise<ScheduledTaskActivity> {+ return request(since === null ? "/runs" : `/runs?since=${since}`);+}diff --git a/studio/frontend/src/features/scheduled-tasks/index.ts b/studio/frontend/src/features/scheduled-tasks/index.tsnew file mode 100644index 00000000000..53eede710dc--- /dev/null+++ b/studio/frontend/src/features/scheduled-tasks/index.ts@@ -0,0 +1,6 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Startup-safe exports only: the page and its dialog load with the /tasks route.+export { ScheduledTaskRunNotifier } from "./run-notifier";+export { useUnseenScheduledRuns } from "./unseen";diff --git a/studio/frontend/src/features/scheduled-tasks/results.ts b/studio/frontend/src/features/scheduled-tasks/results.tsnew file mode 100644index 00000000000..6ed68559c33--- /dev/null+++ b/studio/frontend/src/features/scheduled-tasks/results.ts@@ -0,0 +1,200 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++import type { InterpolationValues, TranslationKey } from "@/i18n";+import type { FinishedScheduledTaskRun, ScheduledTaskActivity } from "./api";++/** A task was added, rescheduled or started: the results poll looks again now. */+export const SCHEDULED_TASKS_CHANGED_EVENT = "unsloth-scheduled-tasks-changed";+/** Bumped on every task change so other tabs get a storage event. */+export const SCHEDULED_TASKS_WRITTEN_KEY = "unsloth_scheduled_tasks_written";+/** A run started or finished: a loaded Tasks page re-reads its list, so it needs no poll of its own. */+export const SCHEDULED_TASK_RUNS_FINISHED_EVENT = "unsloth-scheduled-task-runs-finished";++/** Per-account results-poll record key; in `ACCOUNT_KEYED_PREFIXES`, so it survives account switches. */+export const SEEN_KEY_PREFIX = "unsloth_scheduled_tasks_seen:";+export const UNSEEN_KEY_PREFIX = "unsloth_scheduled_tasks_unseen:";++export const ACTIVE_POLL_MS = 2_000;+// A run that keeps going is looked at less often: 2, 4, 8, then every 10 s.+export const ACTIVE_POLL_MAX_MS = 10_000;+export const IDLE_POLL_MS = 5 * 60_000;+// Every hidden tab polling every 2 s through a long CPU run adds up; their notifications can wait.+export const HIDDEN_POLL_MS = 30_000;+const SEEN_SAVE_STEP_MS = 60_000;+const DUE_SLACK_MS = 3_000;+/** Runs that finished further behind the server's present than this are not announced. */+export const CATCH_UP_MS = 24 * 60 * 60_000;+// A run committed just after the server read its clock predates that time: poll from a minute earlier, skip seen ids.+const CURSOR_SLACK_MS = 60_000;+// The server's page size, so every run the slack window or a page boundary returns stays listed.+const SEEN_IDS_LIMIT = 200;+const PAGES_PER_POLL = 10;++/** Delay before the next results poll: backing off while the same runs stay active, else just after the next due time. */+export function nextPollDelay(+ activity: { now: number; activeRuns: number; nextRunAt: number | null; more?: boolean },+ previous = 0,+): number {+ if (activity.more) return ACTIVE_POLL_MS;+ if (activity.activeRuns > 0) return Math.min(ACTIVE_POLL_MAX_MS, Math.max(ACTIVE_POLL_MS, previous * 2));+ if (activity.nextRunAt === null) return IDLE_POLL_MS;+ const untilDue = activity.nextRunAt - activity.now + DUE_SLACK_MS;+ return Math.min(IDLE_POLL_MS, Math.max(ACTIVE_POLL_MS, untilDue));+}++export function pollDelayFor(delay: number, hidden: boolean): number {+ return hidden ? Math.max(delay, HIDDEN_POLL_MS) : delay;+}++export function shouldSaveSeen(+ stored: SeenRuns | null,+ record: SeenRuns,+ claimed: number,+): boolean {+ return claimed > 0 || stored === null || record.since - stored.since >= SEEN_SAVE_STEP_MS;+}++/** What the results poll has announced, persisted so a reopened Studio reports runs finished while closed. */+export interface SeenRuns {+ /** Server time from which finished runs are still to be announced. */+ since: number;+ /** Runs already announced at or after `since`. */+ ids: string[];+}++/** The stored record to resume from; the server's first answer, not this clock, decides how far behind it is. */+export function readSeenRuns(stored: string | null): SeenRuns | null {+ let value: unknown;+ try {+ value = JSON.parse(stored ?? "null");+ } catch {+ return null;+ }+ const { since, ids } = (value ?? {}) as Partial<SeenRuns>;+ if (typeof since !== "number" || !Number.isFinite(since)) return null;+ return {+ since,+ ids: (Array.isArray(ids) ? ids : [])+ .filter((id): id is string => typeof id === "string")+ .slice(-SEEN_IDS_LIMIT),+ };+}++/** The record after one server answer: a full answer stops at its last run, else it moves to the server's present. */+export function advanceSeenRuns(+ seen: SeenRuns | null,+ answer: Pick<ScheduledTaskActivity, "now" | "runs" | "more">,+ announced: readonly string[],+): SeenRuns {+ const lastFinished = answer.runs.at(-1)?.finishedAt;+ const reached =+ answer.more && typeof lastFinished === "number"+ ? lastFinished+ : answer.now - CURSOR_SLACK_MS;+ return {+ since: Math.max(seen?.since ?? 0, reached),+ ids: [...(seen?.ids ?? []), ...announced].slice(-SEEN_IDS_LIMIT),+ };+}++/** Which of `fresh` this tab announces (skipping ones another tab claimed), and the shared record after. */+export function claimAnnouncements<T extends { id: string; finishedAt: number | null }>(+ shared: SeenRuns | null,+ cursor: SeenRuns,+ fresh: readonly T[],+): { mine: T[]; record: SeenRuns } {+ const announced = new Set(shared?.ids);+ const claimedBefore = shared?.since ?? Number.NEGATIVE_INFINITY;+ const mine = fresh.filter(+ (run) => !announced.has(run.id) && (run.finishedAt ?? Number.POSITIVE_INFINITY) >= claimedBefore,+ );+ return {+ mine,+ record: {+ since: Math.max(shared?.since ?? 0, cursor.since),+ ids: [...(shared?.ids ?? []), ...mine.map((run) => run.id)].slice(-SEEN_IDS_LIMIT),+ },+ };+}++/** Unannounced runs since `seen`, read page by page; a record older than the catch-up window resumes from it (server clock only). */+export async function collectFinishedRuns(+ seen: SeenRuns | null,+ fetchAnswer: (since: number | null) => Promise<ScheduledTaskActivity>,+): Promise<{ fresh: FinishedScheduledTaskRun[]; seen: SeenRuns; last: ScheduledTaskActivity }> {+ const fresh: FinishedScheduledTaskRun[] = [];+ let record = seen;+ for (let page = 1; ; page += 1) {+ let last = await fetchAnswer(record?.since ?? null);+ const oldest = last.now - CATCH_UP_MS;+ if (page === 1 && record !== null && record.since < oldest) {+ record = { since: oldest, ids: record.ids };+ last = await fetchAnswer(oldest);+ }+ const announced = new Set(record?.ids);+ const unseen = last.runs.filter((run) => !announced.has(run.id));+ fresh.push(...unseen);+ record = advanceSeenRuns(+ record,+ last,+ unseen.map((run) => run.id),+ );+ if (!last.more || page >= PAGES_PER_POLL) return { fresh, seen: record, last };+ }+}++/** Finished runs worth announcing: a succeeded run whose chat is already gone is skipped. */+export function runsToAnnounce<T extends { status: string; threadId: string | null }>(+ runs: readonly T[],+): T[] {+ return runs.filter((run) => run.status !== "succeeded" || run.threadId !== null);+}++export function runsToNotify<T extends { status: string; taskNotify: string }>(+ runs: readonly T[],+): T[] {+ return runs.filter(+ (run) => run.taskNotify === "all" || (run.taskNotify === "failures" && run.status === "failed"),+ );+}++/** Chats to mark unread and to clear between two copies of the stored unread result chats. */+export function unseenChatChanges(+ now: readonly string[],+ before: readonly string[],+): { added: string[]; opened: string[] } {+ return {+ added: now.filter((id) => !before.includes(id)),+ opened: before.filter((id) => !now.includes(id)),+ };+}++/** Stored unread result chats that Recents has just marked read. */+export function readInRecents(+ threads: readonly string[],+ before: ReadonlySet<string>,+ now: ReadonlySet<string>,+): string[] {+ return threads.filter((id) => before.has(id) && !now.has(id));+}++type Translate = (key: TranslationKey, values?: InterpolationValues) => string;++const ERROR_KEYS: Record<string, TranslationKey> = {+ no_model: "scheduledTasks.errors.noModel",+ timeout: "scheduledTasks.errors.timeout",+ cancelled: "scheduledTasks.errors.cancelled",+ interrupted: "scheduledTasks.errors.interrupted",+ empty: "scheduledTasks.errors.empty",+};++export function runErrorText(+ run: { errorCode: string | null; error: string | null },+ t: Translate,+): string {+ const key = run.errorCode ? ERROR_KEYS[run.errorCode] : undefined;+ if (key) return t(key);+ return run.error?.trim() || t("scheduledTasks.errors.unknown");+}diff --git a/studio/frontend/src/features/scheduled-tasks/run-notifier.tsx b/studio/frontend/src/features/scheduled-tasks/run-notifier.tsxnew file mode 100644index 00000000000..2afb401218d--- /dev/null+++ b/studio/frontend/src/features/scheduled-tasks/run-notifier.tsx@@ -0,0 +1,307 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useNavigate, useRouterState } from "@tanstack/react-router";+import { useEffect, useRef } from "react";+import { AUTH_SESSION_STORED_EVENT, getAuthSessionEpoch, hasSettledAuthSession } from "@/features/auth";+import { notifyChatHistoryUpdated, useChatNavigationStore } from "@/features/chat";+import { translate } from "@/i18n";+import { browserAccountKey } from "@/lib/account-transition";+import { isTauri } from "@/lib/api-base";+import { notifyNative } from "@/lib/native-notifications";+import { toast } from "@/lib/toast";+import { type FinishedScheduledTaskRun, getScheduledTaskActivity } from "./api";+import {+ IDLE_POLL_MS,+ SCHEDULED_TASKS_CHANGED_EVENT,+ SCHEDULED_TASKS_WRITTEN_KEY,+ SCHEDULED_TASK_RUNS_FINISHED_EVENT,+ SEEN_KEY_PREFIX,+ type SeenRuns,+ claimAnnouncements,+ collectFinishedRuns,+ nextPollDelay,+ pollDelayFor,+ readSeenRuns,+ runErrorText,+ runsToAnnounce,+ runsToNotify,+ readInRecents,+ unseenChatChanges,+ shouldSaveSeen,+} from "./results";+import { useUnseenScheduledRuns } from "./unseen";++// More than this at once, e.g. on reopening Studio, and one toast speaks for them all.+const INDIVIDUAL_TOASTS = 2;+const RECHECK_MS = 500;+// Lock one tab holds while claiming what to announce (account name appended).+const ANNOUNCE_LOCK_PREFIX = "unsloth-scheduled-task-results:";++/** The signed-in account the record belongs to, by id so a recreated name starts afresh. */+function currentAccount(): string {+ return browserAccountKey();+}++function loadSeen(account: string): SeenRuns | null {+ try {+ return readSeenRuns(localStorage.getItem(SEEN_KEY_PREFIX + account));+ } catch {+ return null;+ }+}++function saveSeen(account: string, seen: SeenRuns): void {+ try {+ localStorage.setItem(SEEN_KEY_PREFIX + account, JSON.stringify(seen));+ } catch {+ // Without storage the next launch only announces runs from then on.+ }+}++/** `claim` under a Web Lock where available (secure contexts); elsewhere two tabs may both announce. */+async function exclusively<T>(name: string, claim: () => T): Promise<T> {+ const locks = (navigator as Navigator & { locks?: LockManager }).locks;+ if (!locks) return claim();+ let claimed = false;+ try {+ return await locks.request(name, () => {+ claimed = true;+ return claim();+ });+ } catch (error) {+ if (claimed) throw error;+ return claim();+ }+}++function windowIsInBackground(): boolean {+ return (+ document.visibilityState !== "visible" ||+ (typeof document.hasFocus === "function" && !document.hasFocus())+ );+}++function notifySystem(runs: FinishedScheduledTaskRun[]): void {+ const [run] = runs;+ const single = runs.length === 1;+ const title = !single+ ? translate("scheduledTasks.toast.many", { count: runs.length })+ : run.status === "succeeded"+ ? translate("scheduledTasks.toast.finished", { title: run.taskTitle })+ : translate("scheduledTasks.toast.failed", { title: run.taskTitle });+ const body = !single+ ? runs.map((entry) => entry.taskTitle).join(", ")+ : run.status === "succeeded"+ ? translate("scheduledTasks.notificationBody")+ : runErrorText(run, translate);+ if (isTauri) {+ void notifyNative({+ key: `scheduled-task:${runs.map((entry) => entry.id).join(",")}`,+ title,+ body,+ requestPermission: false,+ });+ return;+ }+ if (!("Notification" in window) || Notification.permission !== "granted") return;+ try {+ const notification = new Notification(title, { body });+ notification.onclick = () => {+ window.focus();+ notification.close();+ };+ } catch {+ // Some browsers only allow notifications from a service worker.+ }+}++/** Watches for scheduled results: refreshes Recents, marks chats unread, toasts and notifies. Renders nothing. */+export function ScheduledTaskRunNotifier() {+ const navigate = useNavigate();+ const navigateRef = useRef(navigate);+ const pathname = useRouterState({ select: (state) => state.location.pathname });+ const pathnameRef = useRef(pathname);+ const openThread = useRouterState({+ select: (state) => (state.location.search as { thread?: unknown }).thread,+ });+ useEffect(() => {+ if (typeof openThread === "string") useUnseenScheduledRuns.getState().clearThread(openThread);+ }, [openThread]);+ // Recents' unread marks follow the account's stored unseen results, so every tab and a reload+ // show them, and opening one anywhere clears it everywhere.+ useEffect(() => {+ const sync = (now: readonly string[], before: readonly string[]) => {+ const chats = useChatNavigationStore.getState();+ const { added, opened } = unseenChatChanges(now, before);+ const fresh = added.filter((id) => !chats.unreadThreadIds.has(id));+ if (fresh.length > 0) chats.markThreadsUnread(fresh);+ if (opened.length > 0) chats.clearThreadsUnread(opened);+ };+ sync(useUnseenScheduledRuns.getState().threads, []);+ const offUnseen = useUnseenScheduledRuns.subscribe((state, previous) => {+ if (state.threads !== previous.threads) sync(state.threads, previous.threads);+ });+ // Read in Recents (opened, "Mark as read", all at once) is read for good. A sign-out's reset+ // comes after the token is gone, when the record is out of reach and stays as it was.+ const offChats = useChatNavigationStore.subscribe((state, previous) => {+ if (state.unreadThreadIds === previous.unreadThreadIds) return;+ const unseen = useUnseenScheduledRuns.getState();+ for (const id of readInRecents(unseen.threads, previous.unreadThreadIds, state.unreadThreadIds)) {+ unseen.clearThread(id);+ }+ });+ return () => {+ offUnseen();+ offChats();+ };+ }, []);+ useEffect(() => {+ navigateRef.current = navigate;+ pathnameRef.current = pathname;+ }, [navigate, pathname]);++ useEffect(() => {+ let disposed = false;+ let polling = false;+ let recheckAfterPoll = false;+ let timer: ReturnType<typeof setTimeout> | null = null;+ let account: string | null = null;+ let seen: SeenRuns | null = null;+ let lastState = "";+ let lastDelay = 0;++ const openChat = (threadId: string) =>+ void navigateRef.current({ to: "/chat", search: { thread: threadId } });+ const openTasks = () => void navigateRef.current({ to: "/tasks" });++ const refreshFor = (finished: FinishedScheduledTaskRun[]) => {+ if (finished.some((run) => run.status === "succeeded" && run.threadId)) {+ notifyChatHistoryUpdated();+ }+ window.dispatchEvent(new Event(SCHEDULED_TASK_RUNS_FINISHED_EVENT));+ };++ // Only the claiming tab records and notifies, so it cannot revive a dot cleared in a faster tab.+ const announce = (claimed: FinishedScheduledTaskRun[]) => {+ const runs = runsToAnnounce(claimed);+ if (runs.length === 0) return;+ useUnseenScheduledRuns.getState().markFinished(+ runs.map((run) => ({+ taskId: run.taskId,+ threadId: run.status === "succeeded" ? run.threadId : null,+ })),+ pathnameRef.current === "/tasks",+ );+ const notified = runsToNotify(runs);+ if (notified.length === 0) return;+ if (notified.length > INDIVIDUAL_TOASTS) {+ toast(translate("scheduledTasks.toast.many", { count: notified.length }), {+ action: { label: translate("scheduledTasks.toast.view"), onClick: openTasks },+ });+ } else {+ for (const run of notified) {+ const threadId = run.threadId;+ if (run.status === "succeeded" && threadId) {+ toast.success(translate("scheduledTasks.toast.finished", { title: run.taskTitle }), {+ action: {+ label: translate("scheduledTasks.toast.open"),+ onClick: () => openChat(threadId),+ },+ });+ } else {+ toast.error(translate("scheduledTasks.toast.failed", { title: run.taskTitle }), {+ description: runErrorText(run, translate),+ action: { label: translate("scheduledTasks.toast.view"), onClick: openTasks },+ });+ }+ }+ }+ if (windowIsInBackground()) notifySystem(notified);+ };++ const schedule = (delay: number) => {+ if (disposed) return;+ if (timer !== null) clearTimeout(timer);+ timer = setTimeout(() => void poll(), delay);+ };++ const poll = async () => {+ if (disposed || polling) return;+ if (!hasSettledAuthSession()) {+ schedule(IDLE_POLL_MS);+ return;+ }+ const owner = currentAccount();+ if (owner !== account) {+ account = owner;+ seen = loadSeen(owner);+ lastState = "";+ }+ const epoch = getAuthSessionEpoch();+ polling = true;+ try {+ const result = await collectFinishedRuns(seen, getScheduledTaskActivity);+ const mine = await exclusively(ANNOUNCE_LOCK_PREFIX + owner, () => {+ if (disposed || getAuthSessionEpoch() !== epoch || currentAccount() !== owner) return null;+ const stored = loadSeen(owner);+ const claim = claimAnnouncements(stored, result.seen, result.fresh);+ if (shouldSaveSeen(stored, claim.record, claim.mine.length)) saveSeen(owner, claim.record);+ return claim.mine;+ });+ if (disposed) return;+ if (mine === null) {+ recheckAfterPoll = true;+ return;+ }+ seen = result.seen;+ const state = `${result.last.activeRuns}:${result.last.nextRunAt}`;+ // The first answer only sets the baseline: a page that just mounted read its own list.+ const changed = result.fresh.length > 0 || (lastState !== "" && state !== lastState);+ lastState = state;+ if (changed) refreshFor(result.fresh);+ if (mine.length > 0) announce(mine);+ lastDelay = nextPollDelay(result.last, changed ? 0 : lastDelay);+ schedule(pollDelayFor(lastDelay, document.visibilityState === "hidden"));+ } catch {+ schedule(IDLE_POLL_MS);+ } finally {+ polling = false;+ if (recheckAfterPoll) {+ recheckAfterPoll = false;+ schedule(RECHECK_MS);+ }+ }+ };++ const recheck = () => {+ lastDelay = 0;+ if (polling) recheckAfterPoll = true;+ else schedule(RECHECK_MS);+ };+ const onVisible = () => {+ if (document.visibilityState === "visible") recheck();+ };+ // Another tab's change: it may have made a task due sooner than this tab's next look.+ const onStorage = (event: StorageEvent) => {+ if (event.key === SCHEDULED_TASKS_WRITTEN_KEY) recheck();+ };+ window.addEventListener(SCHEDULED_TASKS_CHANGED_EVENT, recheck);+ window.addEventListener("storage", onStorage);+ window.addEventListener(AUTH_SESSION_STORED_EVENT, recheck);+ window.addEventListener("focus", recheck);+ document.addEventListener("visibilitychange", onVisible);+ void poll();+ return () => {+ disposed = true;+ if (timer !== null) clearTimeout(timer);+ window.removeEventListener(SCHEDULED_TASKS_CHANGED_EVENT, recheck);+ window.removeEventListener("storage", onStorage);+ window.removeEventListener(AUTH_SESSION_STORED_EVENT, recheck);+ window.removeEventListener("focus", recheck);+ document.removeEventListener("visibilitychange", onVisible);+ };+ }, []);++ return null;+}diff --git a/studio/frontend/src/features/scheduled-tasks/schedule.ts b/studio/frontend/src/features/scheduled-tasks/schedule.tsnew file mode 100644index 00000000000..eb6f12a205c--- /dev/null+++ b/studio/frontend/src/features/scheduled-tasks/schedule.ts@@ -0,0 +1,327 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++/** Mirrors core/scheduled_tasks/schedule.py: wall clock in the task's zone, ISO weekdays, a missing monthly day runs on the last. */+export type TaskSchedule =+ | { kind: "once"; at: string }+ | { kind: "daily"; time: string }+ | { kind: "weekly"; time: string; days: number[] }+ | { kind: "monthly"; time: string; day: number };++export type RepeatKind = "once" | "daily" | "weekdays" | "weekly" | "monthly";++export const REPEAT_KINDS: readonly RepeatKind[] = [+ "once",+ "daily",+ "weekdays",+ "weekly",+ "monthly",+];++export const ISO_WEEKDAYS = [1, 2, 3, 4, 5, 6, 7] as const;+const WORKDAYS = [1, 2, 3, 4, 5];++export interface ScheduleForm {+ repeat: RepeatKind;+ time: string;+ date: string;+ days: number[];+ dayOfMonth: number;+}++const CLOCK = /^([01]\d|2[0-3]):[0-5]\d$/;+const DATE = /^\d{4}-\d{2}-\d{2}$/;++function pad(value: number): string {+ return String(value).padStart(2, "0");+}++export function localDateKey(date: Date): string {+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;+}++function isoWeekday(date: Date): number {+ return ((date.getDay() + 6) % 7) + 1;+}++function isWorkdays(days: readonly number[]): boolean {+ return days.length === WORKDAYS.length && WORKDAYS.every((day) => days.includes(day));+}++/** A new task: daily 09:00, other kinds pre-filled from today; a one-time task starts tomorrow. */+export function defaultScheduleForm(now: Date): ScheduleForm {+ const tomorrow = new Date(now);+ tomorrow.setDate(now.getDate() + 1);+ return {+ repeat: "daily",+ time: "09:00",+ date: localDateKey(tomorrow),+ days: [isoWeekday(now)],+ dayOfMonth: now.getDate(),+ };+}++export function formFromSchedule(schedule: TaskSchedule, now: Date): ScheduleForm {+ const form = defaultScheduleForm(now);+ switch (schedule.kind) {+ case "once": {+ const [date, time] = schedule.at.split("T");+ return { ...form, repeat: "once", date, time };+ }+ case "daily":+ return { ...form, repeat: "daily", time: schedule.time };+ case "weekly":+ return isWorkdays(schedule.days)+ ? { ...form, repeat: "weekdays", time: schedule.time }+ : { ...form, repeat: "weekly", time: schedule.time, days: [...schedule.days] };+ case "monthly":+ return { ...form, repeat: "monthly", time: schedule.time, dayOfMonth: schedule.day };+ }+}++export function scheduleFromForm(form: ScheduleForm): TaskSchedule {+ switch (form.repeat) {+ case "once":+ return { kind: "once", at: `${form.date}T${form.time}` };+ case "daily":+ return { kind: "daily", time: form.time };+ case "weekdays":+ return { kind: "weekly", time: form.time, days: [...WORKDAYS] };+ case "weekly":+ return {+ kind: "weekly",+ time: form.time,+ days: [...new Set(form.days)].sort((a, b) => a - b),+ };+ case "monthly":+ return { kind: "monthly", time: form.time, day: form.dayOfMonth };+ }+}++export function scheduleFormComplete(form: ScheduleForm): boolean {+ if (!CLOCK.test(form.time)) return false;+ switch (form.repeat) {+ case "once":+ return DATE.test(form.date);+ case "weekly":+ return form.days.length > 0;+ case "monthly":+ return Number.isInteger(form.dayOfMonth) && form.dayOfMonth >= 1 && form.dayOfMonth <= 31;+ default:+ return true;+ }+}++const formatters = new Map<string, Intl.DateTimeFormat | Intl.ListFormat | Intl.RelativeTimeFormat>();++function dateFormat(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {+ const key = `date|${locale}|${JSON.stringify(options)}`;+ let format = formatters.get(key) as Intl.DateTimeFormat | undefined;+ if (!format) {+ format = new Intl.DateTimeFormat(locale, options);+ formatters.set(key, format);+ }+ return format;+}++function listFormat(locale: string, options: Intl.ListFormatOptions): Intl.ListFormat {+ const key = `list|${locale}|${JSON.stringify(options)}`;+ let format = formatters.get(key) as Intl.ListFormat | undefined;+ if (!format) {+ format = new Intl.ListFormat(locale, options);+ formatters.set(key, format);+ }+ return format;+}++function relativeFormat(locale: string): Intl.RelativeTimeFormat {+ const key = `relative|${locale}`;+ let format = formatters.get(key) as Intl.RelativeTimeFormat | undefined;+ if (!format) {+ format = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });+ formatters.set(key, format);+ }+ return format;+}++export function formatClock(time: string, locale: string): string {+ const [hour, minute] = time.split(":").map(Number);+ return dateFormat(locale, { hour: "numeric", minute: "2-digit", timeZone: "UTC" }).format(+ Date.UTC(2000, 0, 1, hour, minute),+ );+}++/** Quarter-hour times plus `current` when it falls between them. */+export function timeChoices(current: string): string[] {+ const times = Array.from(+ { length: 96 },+ (_, index) => `${pad(Math.floor(index / 4))}:${pad((index % 4) * 15)}`,+ );+ return !CLOCK.test(current) || times.includes(current) ? times : [...times, current].sort();+}++/** A time zone as briefly as the locale names it ("PT", "MEZ"), else its offset at `at` ("GMT+3"). */+export function zoneLabel(timeZone: string, locale: string, at: number): string {+ const name = (style: "short" | "shortGeneric") => {+ try {+ return (+ dateFormat(locale, { timeZone, timeZoneName: style })+ .formatToParts(at)+ .find((part) => part.type === "timeZoneName")?.value ?? ""+ );+ } catch {+ return "";+ }+ };+ // The generic name holds across daylight saving, but past an abbreviation it is a phrase.+ const generic = name("shortGeneric");+ const specific = name("short");+ if (generic && !/\s/.test(generic) && (!specific || generic.length <= specific.length)) {+ return generic;+ }+ return specific || timeZone;+}++export function weekdayName(day: number, locale: string, width: "short" | "long"): string {+ // 2024-01-01 was a Monday, so day d of that week is ISO weekday d.+ return dateFormat(locale, { weekday: width, timeZone: "UTC" }).format(Date.UTC(2024, 0, day));+}++/** Short weekday names via the long list style (the short style writes English as "Mon, Wed, & Fri"). */+export function formatWeekdays(days: readonly number[], locale: string): string {+ return listFormat(locale, { style: "long", type: "conjunction" }).format(+ days.map((day) => weekdayName(day, locale, "short")),+ );+}++export function sameSchedule(a: TaskSchedule, b: TaskSchedule): boolean {+ switch (a.kind) {+ case "once":+ return b.kind === "once" && a.at === b.at;+ case "daily":+ return b.kind === "daily" && a.time === b.time;+ case "weekly":+ return (+ b.kind === "weekly" &&+ a.time === b.time &&+ a.days.length === b.days.length &&+ a.days.every((day) => b.days.includes(day))+ );+ case "monthly":+ return b.kind === "monthly" && a.time === b.time && a.day === b.day;+ }+}++export type ScheduleSummary =+ | { key: "once"; values: { date: string; time: string } }+ | { key: "daily" | "weekdays"; values: { time: string } }+ | { key: "weekly"; values: { days: string; time: string } }+ | { key: "monthly"; values: { day: number; time: string } };++export function summarizeSchedule(schedule: TaskSchedule, locale: string): ScheduleSummary {+ const clock = schedule.kind === "once" ? schedule.at.split("T")[1] : schedule.time;+ const time = formatClock(clock, locale);+ switch (schedule.kind) {+ case "once": {+ const [year, month, day] = schedule.at.split("T")[0].split("-").map(Number);+ const date = dateFormat(locale, { dateStyle: "medium", timeZone: "UTC" }).format(+ Date.UTC(year, month - 1, day),+ );+ return { key: "once", values: { date, time } };+ }+ case "daily":+ return { key: "daily", values: { time } };+ case "weekly":+ if (schedule.days.length === ISO_WEEKDAYS.length) return { key: "daily", values: { time } };+ if (isWorkdays(schedule.days)) return { key: "weekdays", values: { time } };+ return { key: "weekly", values: { days: formatWeekdays(schedule.days, locale), time } };+ case "monthly":+ return { key: "monthly", values: { day: schedule.day, time } };+ }+}++/** The Repeats column: the cadence alone; weekly is the days themselves. */+export type RepeatsSummary =+ | { key: "once" | "daily" | "weekdays" }+ | { key: "weekly"; days: string }+ | { key: "monthly"; day: number };++export function summarizeRepeats(schedule: TaskSchedule, locale: string): RepeatsSummary {+ switch (schedule.kind) {+ case "once":+ case "daily":+ return { key: schedule.kind };+ case "weekly":+ if (schedule.days.length === ISO_WEEKDAYS.length) return { key: "daily" };+ if (isWorkdays(schedule.days)) return { key: "weekdays" };+ return {+ key: "weekly",+ days: listFormat(locale, { style: "short", type: "unit" }).format(+ schedule.days.map((day) => weekdayName(day, locale, "short")),+ ),+ };+ case "monthly":+ return { key: "monthly", day: schedule.day };+ }+}++/** The day in `timeZone` (default: this browser's), so it agrees with a time shown in that zone. */+export function formatRunDay(+ epochMs: number,+ now: number,+ locale: string,+ timeZone?: string,+): string {+ const dayStart = (at: number) => {+ const parts = dateFormat("en-US", { timeZone, year: "numeric", month: "numeric", day: "numeric" })+ .formatToParts(at);+ const part = (type: string) => Number(parts.find((entry) => entry.type === type)?.value);+ return Date.UTC(part("year"), part("month") - 1, part("day"));+ };+ // Rounded: a DST change makes one day 23 or 25 hours long.+ const days = Math.round((dayStart(epochMs) - dayStart(now)) / 86_400_000);+ if (days === 0 || days === 1) {+ const word = relativeFormat(locale).format(days, "day");+ return word.charAt(0).toLocaleUpperCase(locale) + word.slice(1);+ }+ return dateFormat(locale, { weekday: "short", month: "short", day: "numeric", timeZone }).format(epochMs);+}++export function relativeTimeParts(+ target: number,+ now: number,+): [number, Intl.RelativeTimeFormatUnit] {+ const seconds = Math.round((target - now) / 1000);+ if (Math.abs(seconds) < 60) return [seconds, "second"];+ const minutes = Math.round(seconds / 60);+ if (Math.abs(minutes) < 60) return [minutes, "minute"];+ const hours = Math.round(minutes / 60);+ if (Math.abs(hours) < 24) return [hours, "hour"];+ const days = Math.round(hours / 24);+ if (Math.abs(days) < 30) return [days, "day"];+ const months = Math.round(days / 30);+ if (Math.abs(months) < 12) return [months, "month"];+ return [Math.round(days / 365), "year"];+}++export function browserTimeZone(): string {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";+ } catch {+ return "UTC";+ }+}++const AUTO_TITLE_LENGTH = 60;++/** A blank name falls back to the instructions' first line, cut at a word near 60 characters. */+export function titleFromPrompt(prompt: string): string {+ const line = prompt.trim().split("\n")[0]?.replace(/\s+/g, " ").trim() ?? "";+ // By code point: cutting by code unit can split an emoji into a lone surrogate, which the server refuses.+ const chars = Array.from(line);+ if (chars.length <= AUTO_TITLE_LENGTH) return line;+ const cut = chars.slice(0, AUTO_TITLE_LENGTH).join("");+ const space = cut.lastIndexOf(" ");+ return `${(space > AUTO_TITLE_LENGTH / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;+}diff --git a/studio/frontend/src/features/scheduled-tasks/store.ts b/studio/frontend/src/features/scheduled-tasks/store.tsnew file mode 100644index 00000000000..8062c8077d8--- /dev/null+++ b/studio/frontend/src/features/scheduled-tasks/store.ts@@ -0,0 +1,157 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { create } from "zustand";+import { AUTH_SESSION_CLEARED_EVENT, getAuthSessionEpoch } from "@/features/auth";+import { notifyChatHistoryUpdated } from "@/features/chat";+import {+ type ScheduledTask,+ type ScheduledTaskInput,+ type ScheduledTaskPatch,+ createScheduledTask,+ deleteScheduledTask,+ listScheduledTasks,+ runScheduledTaskNow,+ updateScheduledTask,+} from "./api";+import {+ SCHEDULED_TASKS_CHANGED_EVENT,+ SCHEDULED_TASKS_WRITTEN_KEY,+ SCHEDULED_TASK_RUNS_FINISHED_EVENT,+} from "./results";++export { SCHEDULED_TASKS_WRITTEN_KEY };++function announceChange(): void {+ if (typeof window === "undefined") return;+ window.dispatchEvent(new Event(SCHEDULED_TASKS_CHANGED_EVENT));+ try {+ localStorage.setItem(SCHEDULED_TASKS_WRITTEN_KEY, `${Date.now()}.${Math.random()}`);+ } catch {+ // Without storage, another tab shows the change when it next refreshes.+ }+}++interface ScheduledTasksState {+ tasks: ScheduledTask[];+ /** The server's clock less this browser's, as of the last refresh. */+ serverOffset: number;+ status: "idle" | "loading" | "ready" | "error";+ error: string | null;+ refresh: () => Promise<void>;+ create: (input: ScheduledTaskInput) => Promise<ScheduledTask>;+ update: (id: string, patch: ScheduledTaskPatch) => Promise<ScheduledTask>;+ remove: (id: string) => Promise<void>;+ runNow: (id: string) => Promise<void>;+}++let refreshGeneration = 0;+let refreshesInFlight = 0;+let refreshesDone = 0;++type LastRun = ScheduledTask["lastRun"];++/** The newer of two records of a task's last run: a write's answer can predate a refresh that saw it finish. */+function newerRun(held: LastRun, incoming: LastRun): LastRun {+ if (!held || !incoming) return incoming ?? held;+ if (held.id !== incoming.id) return incoming.createdAt >= held.createdAt ? incoming : held;+ return held.finishedAt !== null && incoming.finishedAt === null ? held : incoming;+}++function withTask(tasks: ScheduledTask[], task: ScheduledTask): ScheduledTask[] {+ return tasks.some((entry) => entry.id === task.id)+ ? tasks.map((entry) =>+ entry.id === task.id ? { ...task, lastRun: newerRun(entry.lastRun, task.lastRun) } : entry,+ )+ : [task, ...tasks];+}++export const useScheduledTasksStore = create<ScheduledTasksState>()((set, get) => {+ /** Applies a write's answer unless the account changed; drops a refresh that started before the write. */+ async function write<T>(request: () => Promise<T>, apply: (result: T) => void): Promise<T> {+ const epoch = getAuthSessionEpoch();+ const listedBefore = refreshesDone;+ const result = await request();+ if (getAuthSessionEpoch() === epoch) {+ // A refresh dropped now, or one that landed while the write was out, may be newer than its answer.+ const stale = refreshesInFlight > 0 || refreshesDone !== listedBefore;+ refreshGeneration += 1;+ apply(result);+ if (stale) void get().refresh();+ }+ announceChange();+ return result;+ }++ return {+ tasks: [],+ serverOffset: 0,+ status: "idle",+ error: null,+ refresh: async () => {+ const generation = ++refreshGeneration;+ if (get().status === "idle") set({ status: "loading" });+ refreshesInFlight += 1;+ try {+ const list = await listScheduledTasks();+ if (generation !== refreshGeneration) return;+ set({+ tasks: list.tasks,+ serverOffset: list.now - Date.now(),+ status: "ready",+ error: null,+ });+ refreshesDone += 1;+ } catch (error) {+ if (generation !== refreshGeneration) return;+ set({+ status: get().status === "ready" ? "ready" : "error",+ error: error instanceof Error ? error.message : String(error),+ });+ } finally {+ refreshesInFlight -= 1;+ }+ },+ create: (input) =>+ write(+ () => createScheduledTask(input),+ (task) => set((state) => ({ tasks: withTask(state.tasks, task) })),+ ),+ update: (id, patch) =>+ write(+ () => updateScheduledTask(id, patch),+ (task) => set((state) => ({ tasks: withTask(state.tasks, task) })),+ ),+ remove: async (id) => {+ await write(+ () => deleteScheduledTask(id),+ () => set((state) => ({ tasks: state.tasks.filter((task) => task.id !== id) })),+ );+ // Its chat survives but the run record went with the task, so the results poll never reports it.+ notifyChatHistoryUpdated();+ },+ runNow: async (id) => {+ await write(+ () => runScheduledTaskNow(id),+ (run) =>+ set((state) => ({+ tasks: state.tasks.map((task) =>+ task.id === id ? { ...task, lastRun: newerRun(task.lastRun, run) } : task,+ ),+ })),+ );+ },+ };+});++if (typeof window !== "undefined") {+ window.addEventListener(SCHEDULED_TASK_RUNS_FINISHED_EVENT, () => {+ const { status, refresh } = useScheduledTasksStore.getState();+ if (status !== "idle") void refresh();+ });+ // Module state: a sign-out must drop it or the next account sees these tasks.+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, () => {+ refreshGeneration += 1;+ useScheduledTasksStore.setState({ tasks: [], serverOffset: 0, status: "idle", error: null });+ });+}diff --git a/studio/frontend/src/features/scheduled-tasks/task-dialog.tsx b/studio/frontend/src/features/scheduled-tasks/task-dialog.tsxnew file mode 100644index 00000000000..1c2d02f2187--- /dev/null+++ b/studio/frontend/src/features/scheduled-tasks/task-dialog.tsx@@ -0,0 +1,455 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Folder01Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { type ReactNode, useId, useRef, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { useChatProjects } from "@/features/chat";+import { type TranslationKey, useLocale, useT } from "@/i18n";+import { isTauri } from "@/lib/api-base";+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";+import { primeNativeNotificationPermission } from "@/lib/native-notifications";+import { toast } from "@/lib/toast";+import { cn } from "@/lib/utils";+import type { ScheduledTask, ScheduledTaskPatch, TaskNotify } from "./api";+import {+ ISO_WEEKDAYS,+ REPEAT_KINDS,+ type RepeatKind,+ type ScheduleForm,+ browserTimeZone,+ defaultScheduleForm,+ formFromSchedule,+ formatClock,+ localDateKey,+ sameSchedule,+ scheduleFormComplete,+ scheduleFromForm,+ timeChoices,+ titleFromPrompt,+ weekdayName,+ zoneLabel,+} from "./schedule";+import { useScheduledTasksStore } from "./store";++const REPEAT_LABELS: Record<RepeatKind, TranslationKey> = {+ once: "scheduledTasks.form.once",+ daily: "scheduledTasks.form.daily",+ weekdays: "scheduledTasks.form.weekdays",+ weekly: "scheduledTasks.form.weekly",+ monthly: "scheduledTasks.form.monthly",+};+const NOTIFY_LABELS: Record<TaskNotify, TranslationKey> = {+ all: "scheduledTasks.form.notifyAll",+ failures: "scheduledTasks.form.notifyFailures",+ none: "scheduledTasks.form.notifyNone",+};+const NOTIFY_CHOICES: readonly TaskNotify[] = ["all", "failures", "none"];+const DAYS_OF_MONTH = Array.from({ length: 31 }, (_, index) => index + 1);++/** Ask for notification permission from the save click: browsers prompt only during a user gesture. */+function askToNotify(): void {+ if (isTauri) {+ void primeNativeNotificationPermission();+ return;+ }+ if ("Notification" in window && Notification.permission === "default") {+ void Notification.requestPermission().catch(() => undefined);+ }+}++function Row({ id, label, children }: { id?: string; label: string; children: ReactNode }) {+ return (+ <div className="flex min-h-14 flex-wrap items-center justify-between gap-x-4 gap-y-2 px-5 py-2">+ <label htmlFor={id} className="text-ui-15 text-foreground">+ {label}+ </label>+ {children}+ </div>+ );+}++// Dark mode separates by fill, not outline: a white wash on the card surface, no borders or dividers.+const CARD =+ "flex flex-col divide-y divide-border overflow-hidden rounded-[20px] border border-border dark:divide-y-0 dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.05*var(--contrast-wash-gain,1)))]";+const BARE_SELECT =+ "h-9 w-auto gap-1.5 border-none bg-transparent px-2 text-ui-15 text-muted-foreground shadow-none hover:text-foreground focus-visible:ring-1 dark:bg-transparent dark:hover:bg-transparent";+const BARE_INPUT =+ "h-9 w-auto border-none bg-transparent px-2 text-right text-ui-15 text-muted-foreground shadow-none focus-visible:ring-1 dark:bg-transparent";+// Its scroll buttons paint the base popover colour, which shows as bands on the lifted dark menu.+const LONG_LIST =+ "max-h-[min(--spacing(72),var(--radix-select-content-available-height))] [&_[data-slot^=select-scroll]]:bg-transparent";++// Select values cannot be empty, so null (no project) has a stand-in.+const NO_PROJECT = "__none__";++export function TaskDialog({+ task,+ onClose,+ onDelete,+}: {+ task: ScheduledTask | null;+ onClose: () => void;+ onDelete?: (task: ScheduledTask) => void;+}) {+ const t = useT();+ const locale = useLocale();+ const ids = useId();+ const promptRef = useRef<HTMLTextAreaElement>(null);+ const create = useScheduledTasksStore((state) => state.create);+ const update = useScheduledTasksStore((state) => state.update);+ const [now] = useState(() => new Date());+ // A task named after its instructions edits with an empty name, so the name keeps following them.+ const [title, setTitle] = useState(task?.named ? task.title : "");+ const [prompt, setPrompt] = useState(task?.prompt ?? "");+ const [form, setForm] = useState<ScheduleForm>(() =>+ task ? formFromSchedule(task.schedule, now) : defaultScheduleForm(now),+ );+ const [notify, setNotify] = useState<TaskNotify>(task?.notify ?? "all");+ const [archiveSuccessful, setArchiveSuccessful] = useState(task?.archiveSuccessful ?? false);+ const [projectId, setProjectId] = useState<string | null>(task?.projectId ?? null);+ const { projects } = useChatProjects();+ const openProjects = projects.filter((project) => !project.archived || project.id === projectId);+ const [advanced, setAdvanced] = useState(+ () =>+ task !== null &&+ (task.notify !== "all" || task.archiveSuccessful || task.projectId !== null),+ );+ const [busy, setBusy] = useState(false);+ const timezone = task?.timezone ?? browserTimeZone();+ const valid = prompt.trim() !== "" && scheduleFormComplete(form);+ const named = title.trim() !== "";+ const finalTitle = named ? title.trim() : titleFromPrompt(prompt);++ const patchForm = (patch: Partial<ScheduleForm>) => setForm((current) => ({ ...current, ...patch }));+ const toggleDay = (day: number) =>+ setForm((current) => ({+ ...current,+ days: current.days.includes(day)+ ? current.days.filter((entry) => entry !== day)+ : [...current.days, day],+ }));++ async function save() {+ if (!valid || busy) return;+ if (notify !== "none" && (!task || task.notify === "none")) askToNotify();+ setBusy(true);+ const schedule = scheduleFromForm(form);+ try {+ if (task) {+ // Only what changed: a rename must not move a run that is already due.+ const patch: ScheduledTaskPatch = {};+ if (finalTitle !== task.title) patch.title = finalTitle;+ if (prompt.trim() !== task.prompt) patch.prompt = prompt.trim();+ if (!sameSchedule(schedule, task.schedule)) patch.schedule = schedule;+ if (named !== task.named) patch.named = named;+ if (notify !== task.notify) patch.notify = notify;+ if (archiveSuccessful !== task.archiveSuccessful) patch.archiveSuccessful = archiveSuccessful;+ if (projectId !== task.projectId) patch.projectId = projectId;+ if (Object.keys(patch).length > 0) await update(task.id, patch);+ } else {+ await create({+ title: finalTitle,+ prompt: prompt.trim(),+ schedule,+ timezone,+ notify,+ named,+ archiveSuccessful,+ projectId,+ });+ }+ onClose();+ } catch (error) {+ toast.error(t("scheduledTasks.errors.saveFailed"), {+ description: error instanceof Error ? error.message : undefined,+ });+ } finally {+ setBusy(false);+ }+ }++ return (+ <Dialog+ open={true}+ onOpenChange={(open) => {+ if (!open && !busy) onClose();+ }}+ >+ <DialogContent+ className="corner-squircle dialog-soft-surface gap-4 sm:max-w-xl"+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ const field = promptRef.current;+ field?.focus();+ field?.setSelectionRange(field.value.length, field.value.length);+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ void save();+ }+ }}+ >+ <DialogHeader>+ <DialogTitle className="text-ui-21">+ {task ? t("scheduledTasks.form.editTitle") : t("scheduledTasks.form.createTitle")}+ </DialogTitle>+ <DialogDescription className="sr-only">{t("scheduledTasks.description")}</DialogDescription>+ </DialogHeader>+ <div className="flex flex-col gap-2">+ <div className={CARD}>+ <Input+ id={`${ids}-name`}+ aria-label={t("scheduledTasks.form.name")}+ value={title}+ onChange={(event) => setTitle(event.target.value)}+ maxLength={120}+ disabled={busy}+ placeholder={t("scheduledTasks.form.namePlaceholder")}+ className="h-12 rounded-none border-none bg-transparent px-5 text-ui-15 font-medium shadow-none focus-visible:ring-0 dark:bg-transparent dark:focus-visible:bg-transparent"+ />+ </div>+ <div className={CARD}>+ <Textarea+ ref={promptRef}+ id={`${ids}-prompt`}+ aria-label={t("scheduledTasks.form.instructions")}+ aria-describedby={`${ids}-prompt-hint`}+ value={prompt}+ onChange={(event) => setPrompt(event.target.value)}+ maxLength={20_000}+ rows={5}+ disabled={busy}+ placeholder={t("scheduledTasks.form.instructionsPlaceholder")}+ className="max-h-60 min-h-32 resize-none rounded-none border-none bg-transparent px-5 py-3.5 text-ui-15 shadow-none focus-visible:ring-0 dark:bg-transparent dark:focus-visible:bg-transparent"+ />+ </div>+ </div>+ <p id={`${ids}-prompt-hint`} className="sr-only">+ {t("scheduledTasks.form.instructionsHint")}+ </p>+ <div className={CARD}>+ <Row id={`${ids}-repeat`} label={t("scheduledTasks.form.repeat")}>+ <Select+ value={form.repeat}+ onValueChange={(value) => patchForm({ repeat: value as RepeatKind })}+ disabled={busy}+ >+ <SelectTrigger id={`${ids}-repeat`} className={BARE_SELECT}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end">+ {REPEAT_KINDS.map((kind) => (+ <SelectItem key={kind} value={kind}>+ {t(REPEAT_LABELS[kind])}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Row>+ {form.repeat === "once" && (+ <Row id={`${ids}-date`} label={t("scheduledTasks.form.date")}>+ <Input+ id={`${ids}-date`}+ type="date"+ value={form.date}+ min={localDateKey(now)}+ onChange={(event) => patchForm({ date: event.target.value })}+ disabled={busy}+ className={BARE_INPUT}+ />+ </Row>+ )}+ {form.repeat === "monthly" && (+ <Row id={`${ids}-day`} label={t("scheduledTasks.form.dayOfMonth")}>+ <Select+ value={String(form.dayOfMonth)}+ onValueChange={(value) => patchForm({ dayOfMonth: Number(value) })}+ disabled={busy}+ >+ <SelectTrigger id={`${ids}-day`} className={BARE_SELECT}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end" className={LONG_LIST}>+ {DAYS_OF_MONTH.map((day) => (+ <SelectItem key={day} value={String(day)}>+ {day}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Row>+ )}+ {form.repeat === "weekly" && (+ <Row label={t("scheduledTasks.form.days")}>+ <div role="group" aria-label={t("scheduledTasks.form.days")} className="flex flex-wrap justify-end gap-1">+ {ISO_WEEKDAYS.map((day) => {+ const selected = form.days.includes(day);+ return (+ <button+ key={day}+ type="button"+ aria-pressed={selected}+ title={weekdayName(day, locale, "long")}+ disabled={busy}+ onClick={() => toggleDay(day)}+ className={cn(+ "h-8 min-w-11 cursor-pointer rounded-full px-2.5 text-ui-13 font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",+ selected+ ? "bg-primary text-primary-foreground"+ : "bg-muted text-muted-foreground hover:text-foreground dark:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] dark:text-foreground/75",+ )}+ >+ {weekdayName(day, locale, "short")}+ </button>+ );+ })}+ </div>+ </Row>+ )}+ <Row id={`${ids}-time`} label={t("scheduledTasks.form.time")}>+ <Select+ value={form.time}+ onValueChange={(value) => patchForm({ time: value })}+ disabled={busy}+ >+ <SelectTrigger id={`${ids}-time`} title={timezone} className={BARE_SELECT}>+ <SelectValue>+ {`${formatClock(form.time, locale)} ${zoneLabel(timezone, locale, now.getTime())}`}+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="end" className={LONG_LIST}>+ {timeChoices(form.time).map((time) => (+ <SelectItem key={time} value={time}>+ {formatClock(time, locale)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Row>+ </div>+ {form.repeat === "monthly" && form.dayOfMonth > 28 && (+ <p className="-mt-2 px-1 text-ui-13 text-muted-foreground">+ {t("scheduledTasks.form.lastDayNote")}+ </p>+ )}+ <div className="pb-5">+ <button+ type="button"+ aria-expanded={advanced}+ aria-controls={advanced ? `${ids}-advanced` : undefined}+ onClick={() => setAdvanced((open) => !open)}+ className="flex cursor-pointer items-center gap-1 rounded-md px-1 text-ui-14 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("scheduledTasks.form.advanced")}+ <HugeiconsIcon+ icon={ChevronDownStandardIcon}+ strokeWidth={2}+ className={cn("size-4 transition-transform", advanced && "rotate-180")}+ />+ </button>+ {advanced && (+ <div id={`${ids}-advanced`} className={cn(CARD, "mt-3")}>+ <Row id={`${ids}-notify`} label={t("scheduledTasks.form.notifications")}>+ <Select+ value={notify}+ onValueChange={(value) => setNotify(value as TaskNotify)}+ disabled={busy}+ >+ <SelectTrigger id={`${ids}-notify`} className={BARE_SELECT}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end">+ {NOTIFY_CHOICES.map((choice) => (+ <SelectItem key={choice} value={choice}>+ {t(NOTIFY_LABELS[choice])}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Row>+ <Row id={`${ids}-archive`} label={t("scheduledTasks.form.archiveSuccessful")}>+ <Switch+ id={`${ids}-archive`}+ checked={archiveSuccessful}+ onCheckedChange={setArchiveSuccessful}+ disabled={busy}+ className="mr-2"+ />+ </Row>+ <Row id={`${ids}-project`} label={t("scheduledTasks.form.project")}>+ <Select+ value={projectId ?? NO_PROJECT}+ onValueChange={(value) => setProjectId(value === NO_PROJECT ? null : value)}+ disabled={busy}+ >+ <SelectTrigger id={`${ids}-project`} className={cn(BARE_SELECT, "max-w-[60%]")}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end" className={cn(LONG_LIST, "max-w-72")}>+ {openProjects.map((project) => (+ <SelectItem key={project.id} value={project.id}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ {project.name}+ </SelectItem>+ ))}+ <SelectItem value={NO_PROJECT}>{t("scheduledTasks.form.projectNone")}</SelectItem>+ </SelectContent>+ </Select>+ </Row>+ </div>+ )}+ </div>+ <DialogFooter className="flex-wrap gap-2 sm:justify-between">+ {task && onDelete ? (+ <Button+ type="button"+ variant="destructive"+ disabled={busy}+ onClick={() => {+ onClose();+ onDelete(task);+ }}+ >+ {t("common.delete")}+ </Button>+ ) : (+ <span />+ )}+ <span className="flex flex-wrap gap-2">+ <Button type="button" variant="muted" disabled={busy} onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button type="button" disabled={!valid || busy} onClick={() => void save()}>+ {busy+ ? t("common.saving")+ : task+ ? t("common.save")+ : t("scheduledTasks.form.create")}+ </Button>+ </span>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/studio/frontend/src/features/scheduled-tasks/tasks-page.tsx b/studio/frontend/src/features/scheduled-tasks/tasks-page.tsxnew file mode 100644index 00000000000..e3ab536049b--- /dev/null+++ b/studio/frontend/src/features/scheduled-tasks/tasks-page.tsx@@ -0,0 +1,570 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ Add01Icon,+ Delete02Icon,+ FilterMailIcon,+ MoreHorizontalIcon,+ PencilEdit02Icon,+ Search01Icon,+ Clock01Icon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { useNavigate, useSearch } from "@tanstack/react-router";+import { PauseIcon, PlayIcon } from "lucide-react";+import { useEffect, useMemo, useState } from "react";+import { useShallow } from "zustand/react/shallow";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import { Skeleton } from "@/components/ui/skeleton";+import { Spinner } from "@/components/ui/spinner";+import {+ type InterpolationValues,+ type TranslationKey,+ formatRelativeTime,+ useLocale,+ useT,+} from "@/i18n";+import { toast } from "@/lib/toast";+import { cn } from "@/lib/utils";+import type { ScheduledTask } from "./api";+import { runErrorText } from "./results";+import {+ type TaskSchedule,+ formatClock,+ formatRunDay,+ relativeTimeParts,+ summarizeRepeats,+ summarizeSchedule,+} from "./schedule";+import { SCHEDULED_TASKS_WRITTEN_KEY, useScheduledTasksStore } from "./store";+import { TaskDialog } from "./task-dialog";+import { useUnseenScheduledRuns } from "./unseen";++const REFOCUS_DEDUPE_MS = 1_000;++const ROW_BUTTON =+ "flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition hover:bg-[rgb(0_0_0_/_calc(0.05*var(--contrast-wash-gain,1)))] hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50 data-[state=open]:bg-[rgb(0_0_0_/_calc(0.05*var(--contrast-wash-gain,1)))] dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] dark:data-[state=open]:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))]";++type TaskStatus = ScheduledTask["status"];++const STATUSES: TaskStatus[] = ["active", "paused", "completed"];+const STATUS_LABEL = {+ active: "scheduledTasks.active",+ paused: "scheduledTasks.paused",+ completed: "scheduledTasks.completed",+} as const satisfies Record<TaskStatus, TranslationKey>;+const FILTER_KEY = "unsloth_scheduled_tasks_filter";++function loadFilter(): TaskStatus[] {+ try {+ const saved: unknown = JSON.parse(localStorage.getItem(FILTER_KEY) ?? "null");+ if (Array.isArray(saved)) return STATUSES.filter((status) => saved.includes(status));+ } catch {+ // Unreadable storage shows every task.+ }+ return STATUSES;+}++function saveFilter(shown: TaskStatus[]): void {+ try {+ localStorage.setItem(FILTER_KEY, JSON.stringify(shown));+ } catch {+ // Without storage the filter resets on the next visit.+ }+}++function compareTasks(a: ScheduledTask, b: ScheduledTask): number {+ const rank = STATUSES.indexOf(a.status) - STATUSES.indexOf(b.status);+ if (rank !== 0) return rank;+ if (a.nextRunAt !== null && b.nextRunAt !== null && a.nextRunAt !== b.nextRunAt) {+ return a.nextRunAt - b.nextRunAt;+ }+ return b.updatedAt - a.updatedAt;+}++function scheduleText(+ schedule: TaskSchedule,+ locale: string,+ t: (key: TranslationKey, values?: InterpolationValues) => string,+): string {+ const summary = summarizeSchedule(schedule, locale);+ return t(`scheduledTasks.schedule.${summary.key}`, summary.values);+}++function repeatsText(+ schedule: TaskSchedule,+ locale: string,+ t: (key: TranslationKey, values?: InterpolationValues) => string,+): string {+ const summary = summarizeRepeats(schedule, locale);+ if (summary.key === "weekly") return summary.days;+ if (summary.key === "monthly") return t("scheduledTasks.monthlyDay", { day: summary.day });+ return t(`scheduledTasks.form.${summary.key}`);+}++function clockText(schedule: TaskSchedule, locale: string): string {+ return formatClock(schedule.kind === "once" ? schedule.at.split("T")[1] : schedule.time, locale);+}++const REPEATS_COLUMN = "hidden w-36 shrink-0 truncate md:block";+const TIME_COLUMN = "hidden w-24 shrink-0 truncate md:block";+const NEXT_RUN_COLUMN = "hidden w-32 shrink-0 truncate md:block";++function errorText(error: unknown): string | undefined {+ return error instanceof Error ? error.message : undefined;+}++function useMinuteClock(): number {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const timer = window.setInterval(() => setNow(Date.now()), 30_000);+ return () => window.clearInterval(timer);+ }, []);+ return now;+}++function TaskRow({+ task,+ now,+ unseen,+ onEdit,+ onDelete,+}: {+ task: ScheduledTask;+ now: number;+ unseen: boolean;+ onEdit: () => void;+ onDelete: () => void;+}) {+ const t = useT();+ const locale = useLocale();+ const navigate = useNavigate();+ const update = useScheduledTasksStore((state) => state.update);+ const runNow = useScheduledTasksStore((state) => state.runNow);+ const clearUnseen = useUnseenScheduledRuns((state) => state.clearTask);+ const [busy, setBusy] = useState(false);+ const run = task.lastRun;+ const running = run?.status === "queued" || run?.status === "running";++ async function act(action: () => Promise<unknown>, failure: "runFailed" | "updateFailed") {+ setBusy(true);+ try {+ await action();+ } catch (error) {+ toast.error(t(`scheduledTasks.errors.${failure}`), { description: errorText(error) });+ } finally {+ setBusy(false);+ }+ }++ // Always past tense: a just-finished run (or a server clock slightly ahead) would read "in 0 sec.".+ const ago = (at: number) =>+ formatRelativeTime(locale, ...relativeTimeParts(Math.min(at, now - 1_000), now));+ const finishedAt = run?.finishedAt ?? null;+ const repeats = repeatsText(task.schedule, locale, t);+ const clock = clockText(task.schedule, locale);+ const nextDay = task.nextRunAt === null ? "—" : formatRunDay(task.nextRunAt, now, locale, task.timezone);++ return (+ <div className="group/task-row flex items-center gap-4 rounded-xl px-5 py-4 transition-colors duration-150 hover:bg-muted/70 dark:hover:bg-[rgb(255_255_255_/_calc(0.055*var(--contrast-wash-gain,1)))]">+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex min-w-0 items-center gap-2">+ <button+ type="button"+ onClick={() => {+ clearUnseen(task.id);+ onEdit();+ }}+ className="min-w-0 cursor-pointer truncate rounded-md text-left text-ui-15 font-semibold text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ {task.title}+ </button>+ {unseen && (+ <span+ role="img"+ aria-label={t("scheduledTasks.newResult")}+ className="size-2 shrink-0 rounded-full bg-primary"+ />+ )}+ {task.status !== "active" && (+ <span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-ui-11 font-medium text-muted-foreground">+ {task.status === "paused" ? t("scheduledTasks.paused") : t("scheduledTasks.completed")}+ </span>+ )}+ </div>+ <p className="truncate text-ui-13 text-muted-foreground md:hidden">+ {[repeats, clock, task.nextRunAt === null ? null : nextDay]+ .filter(Boolean)+ .join(" · ")}+ </p>+ {running ? (+ <p className="flex items-center gap-1.5 text-ui-13 text-foreground">+ <Spinner className="size-3.5" label={t("scheduledTasks.running")} />+ {t("scheduledTasks.running")}+ </p>+ ) : run?.status === "succeeded" && finishedAt !== null ? (+ <p className="text-ui-13 text-muted-foreground">+ {t("scheduledTasks.lastRun", { when: ago(finishedAt) })}+ {run.threadId && (+ <>+ {" · "}+ <button+ type="button"+ onClick={() => {+ clearUnseen(task.id);+ void navigate({ to: "/chat", search: { thread: run.threadId ?? undefined } });+ }}+ className="cursor-pointer font-medium text-foreground underline-offset-2 hover:underline"+ >+ {t("scheduledTasks.openChat")}+ </button>+ </>+ )}+ </p>+ ) : run?.status === "failed" && finishedAt !== null ? (+ <p title={runErrorText(run, t)} className="truncate text-ui-13 text-destructive">+ {t("scheduledTasks.lastRunFailed", {+ when: ago(finishedAt),+ reason: runErrorText(run, t),+ })}+ </p>+ ) : null}+ </div>+ <span title={scheduleText(task.schedule, locale, t)} className={cn(REPEATS_COLUMN, "text-ui-15 text-foreground/85")}>+ {repeats}+ </span>+ <span title={task.timezone} className={cn(TIME_COLUMN, "text-ui-15 text-foreground/85")}>+ {clock}+ </span>+ <span className={cn(NEXT_RUN_COLUMN, "text-ui-15 text-muted-foreground")}>{nextDay}</span>+ <div className="flex shrink-0 items-center gap-1">+ <button+ type="button"+ aria-label={t("scheduledTasks.runNow")}+ title={t("scheduledTasks.runNow")}+ disabled={busy || running}+ onClick={() => {+ clearUnseen(task.id);+ void act(() => runNow(task.id), "runFailed");+ }}+ className={cn(+ ROW_BUTTON,+ "opacity-0 group-hover/task-row:opacity-100 group-focus-within/task-row:opacity-100 [@media(pointer:coarse)]:opacity-100",+ )}+ >+ <PlayIcon strokeWidth={1.75} className="size-4.5" />+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" aria-label={t("scheduledTasks.options")} className={ROW_BUTTON}>+ <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="app-user-menu menu-soft-surface menu-flat-destructive ring-0 w-48 font-heading rounded-[14px] border-0"+ >+ <DropdownMenuItem onSelect={onEdit}>+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />+ {t("scheduledTasks.edit")}+ </DropdownMenuItem>+ {task.status !== "completed" && (+ <DropdownMenuItem+ disabled={busy}+ onSelect={() =>+ void act(() => update(task.id, { enabled: !task.enabled }), "updateFailed")+ }+ >+ {task.enabled ? (+ <PauseIcon strokeWidth={1.75} className="size-icon" />+ ) : (+ <PlayIcon strokeWidth={1.75} className="size-icon" />+ )}+ {task.enabled ? t("scheduledTasks.pause") : t("scheduledTasks.resume")}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem variant="destructive" onSelect={onDelete}>+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />+ {t("common.delete")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ );+}++export function TasksPage() {+ const t = useT();+ const { tasks, status, error, refresh, remove } = useScheduledTasksStore(+ useShallow((state) => ({+ tasks: state.tasks,+ status: state.status,+ error: state.error,+ refresh: state.refresh,+ remove: state.remove,+ })),+ );+ const serverOffset = useScheduledTasksStore((state) => state.serverOffset);+ const now = useMinuteClock() + serverOffset;+ const [editing, setEditing] = useState<ScheduledTask | null | undefined>(undefined);+ const [deleting, setDeleting] = useState<ScheduledTask | null>(null);+ const [shown, setShown] = useState<TaskStatus[]>(loadFilter);+ const [query, setQuery] = useState("");+ const [listed, setListed] = useState(false);+ const visibleTasks = useMemo(() => {+ const needle = query.trim().toLocaleLowerCase();+ return tasks+ .filter(+ (task) =>+ shown.includes(task.status) &&+ (needle === "" ||+ task.title.toLocaleLowerCase().includes(needle) ||+ task.prompt.toLocaleLowerCase().includes(needle)),+ )+ .sort(compareTasks);+ }, [tasks, shown, query]);+ const unseenTasks = useUnseenScheduledRuns((state) => state.tasks);+ const pageUnseen = useUnseenScheduledRuns((state) => state.page);+ const clearPageUnseen = useUnseenScheduledRuns((state) => state.clearPage);++ useEffect(() => {+ if (pageUnseen) clearPageUnseen();+ }, [pageUnseen, clearPageUnseen]);++ // ?edit=<id>: open that task once listed, then drop the param so close/reload does not reopen it.+ const navigate = useNavigate();+ const { edit: editId, create } = useSearch({ strict: false });+ useEffect(() => {+ if (!create) return;+ // eslint-disable-next-line react-hooks/set-state-in-effect -- the URL asks for the dialog once, then is cleared.+ setEditing(null);+ void navigate({ to: "/tasks", search: {}, replace: true });+ }, [create, navigate]);+ useEffect(() => {+ // Only this visit's list: one kept from an earlier visit can lack the task or hold old instructions.+ if (!editId || !listed || status !== "ready") return;+ const target = tasks.find((task) => task.id === editId);+ // eslint-disable-next-line react-hooks/set-state-in-effect -- as above, once the list has the task.+ if (target) setEditing(target);+ else toast.info(t("scheduledTasks.taskMissing"));+ void navigate({ to: "/tasks", search: {}, replace: true });+ }, [editId, listed, status, tasks, navigate, t]);++ function toggleStatus(status: TaskStatus, on: boolean) {+ const next = STATUSES.filter((candidate) => (candidate === status ? on : shown.includes(candidate)));+ setShown(next);+ saveFilter(next);+ }++ useEffect(() => {+ void refresh().finally(() => setListed(true));+ // Other tabs/devices send no event: re-read on storage marks, show and focus.+ const onStorage = (event: StorageEvent) => {+ if (event.key === SCHEDULED_TASKS_WRITTEN_KEY) void refresh();+ };+ let lookedAt = 0;+ const lookAgain = () => {+ const now = Date.now();+ if (now - lookedAt < REFOCUS_DEDUPE_MS) return;+ lookedAt = now;+ void refresh();+ };+ const onVisible = () => {+ if (document.visibilityState === "visible") lookAgain();+ };+ const onFocus = lookAgain;+ window.addEventListener("storage", onStorage);+ window.addEventListener("focus", onFocus);+ document.addEventListener("visibilitychange", onVisible);+ return () => {+ window.removeEventListener("storage", onStorage);+ window.removeEventListener("focus", onFocus);+ document.removeEventListener("visibilitychange", onVisible);+ };+ }, [refresh]);++ async function confirmDelete() {+ const target = deleting;+ if (!target) return;+ setDeleting(null);+ try {+ await remove(target.id);+ } catch (error) {+ toast.error(t("scheduledTasks.errors.deleteFailed"), { description: errorText(error) });+ }+ }++ const loading = status === "idle" || status === "loading";++ return (+ <main className="mx-auto w-full max-w-5xl 4xl:max-w-6xl px-6 pb-10 pt-8 max-sm:px-4 font-heading sm:px-10">+ <div className="flex flex-wrap items-center justify-between gap-4">+ <h1 className="text-ui-30 font-semibold leading-[1.04] tracking-[-0.028em] text-foreground sm:text-ui-34">+ {t("scheduledTasks.title")}+ </h1>+ <div className="flex w-full min-w-0 items-center justify-end gap-3 sm:w-auto sm:flex-1">+ <div className="relative min-w-0 flex-1 sm:max-w-sm">+ <span className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-muted-foreground">+ <HugeiconsIcon icon={Search01Icon} strokeWidth={1.75} className="size-4" />+ </span>+ <Input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t("scheduledTasks.search")}+ aria-label={t("scheduledTasks.search")}+ className="h-9 w-full rounded-full border-none bg-muted pl-10 pr-4 shadow-none dark:bg-card"+ />+ </div>+ <Button onClick={() => setEditing(null)}>+ <HugeiconsIcon icon={Add01Icon} strokeWidth={1.75} className="size-icon" />+ {t("scheduledTasks.newTask")}+ </Button>+ </div>+ </div>+ <p className="mt-4 text-ui-15 text-muted-foreground">{t("scheduledTasks.description")}</p>++ {loading && tasks.length === 0 ? (+ <div className="mt-12">+ {Array.from({ length: 3 }).map((_, index) => (+ <div key={index} className="flex items-start gap-4 rounded-xl px-5 py-4">+ <div className="flex flex-1 flex-col gap-2">+ <Skeleton className="h-4 w-48 rounded-[8px]" />+ <Skeleton className="h-3.5 w-72 rounded-[8px]" />+ </div>+ </div>+ ))}+ </div>+ ) : status === "error" && tasks.length === 0 ? (+ <div className="mt-16 flex flex-col items-center gap-3 text-center">+ <p className="text-sm text-muted-foreground">{t("scheduledTasks.loadFailed")}</p>+ {error && <p className="max-w-md text-ui-13 text-muted-foreground">{error}</p>}+ <Button variant="outline" onClick={() => void refresh()}>+ {t("scheduledTasks.retry")}+ </Button>+ </div>+ ) : tasks.length === 0 ? (+ <div className="mt-16 flex flex-col items-center gap-2 text-center">+ <span className="mb-2 flex size-12 items-center justify-center rounded-2xl bg-muted text-foreground/70">+ <HugeiconsIcon icon={Clock01Icon} strokeWidth={1.75} className="size-6" />+ </span>+ <p className="text-ui-15 font-semibold text-foreground">{t("scheduledTasks.emptyTitle")}</p>+ <p className="max-w-sm text-sm text-muted-foreground">+ {t("scheduledTasks.emptyDescription")}+ </p>+ <Button+ variant="outline"+ className="mt-3 border-none bg-background shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-card dark:shadow-none"+ onClick={() => setEditing(null)}+ >+ <HugeiconsIcon icon={Add01Icon} strokeWidth={1.75} className="size-icon" />+ {t("scheduledTasks.createFirst")}+ </Button>+ </div>+ ) : (+ <div className="mt-10 flex flex-col">+ <div className="flex items-center gap-4 px-5 pb-2 text-ui-14 font-medium text-muted-foreground">+ <h2 className="min-w-0 flex-1">{t("scheduledTasks.upcoming")}</h2>+ <span className={REPEATS_COLUMN}>{t("scheduledTasks.columns.repeats")}</span>+ <span className={TIME_COLUMN}>{t("scheduledTasks.columns.time")}</span>+ <span className={NEXT_RUN_COLUMN}>{t("scheduledTasks.columns.nextRun")}</span>+ <span className="flex shrink-0 items-center gap-1">+ <span className="size-9" />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t("scheduledTasks.filter")}+ title={t("scheduledTasks.filter")}+ className={cn(ROW_BUTTON, shown.length < STATUSES.length && "text-foreground")}+ >+ <HugeiconsIcon icon={FilterMailIcon} strokeWidth={1.75} className="size-5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="app-user-menu menu-soft-surface ring-0 w-52 font-heading rounded-[14px] border-0"+ >+ <DropdownMenuLabel className="text-muted-foreground">+ {t("scheduledTasks.filterBy")}+ </DropdownMenuLabel>+ {STATUSES.map((status) => (+ <DropdownMenuCheckboxItem+ key={status}+ checked={shown.includes(status)}+ onCheckedChange={(on) => toggleStatus(status, on)}+ onSelect={(event) => event.preventDefault()}+ >+ {t(STATUS_LABEL[status])}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </span>+ </div>+ {visibleTasks.length === 0 ? (+ <p className="px-5 py-4 text-ui-13 text-muted-foreground">+ {t("scheduledTasks.noMatches")}+ </p>+ ) : (+ visibleTasks.map((task) => (+ <TaskRow+ key={task.id}+ task={task}+ now={now}+ unseen={task.id in unseenTasks}+ onEdit={() => setEditing(task)}+ onDelete={() => setDeleting(task)}+ />+ ))+ )}+ </div>+ )}++ {editing !== undefined && (+ <TaskDialog+ key={editing?.id ?? "new"}+ task={editing}+ onClose={() => setEditing(undefined)}+ onDelete={(task) => setDeleting(task)}+ />+ )}+ <AlertDialog open={deleting !== null} onOpenChange={(open) => !open && setDeleting(null)}>+ <AlertDialogContent onOverlayClick={() => setDeleting(null)}>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("scheduledTasks.deleteDialog.title")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t("scheduledTasks.deleteDialog.description", { title: deleting?.title ?? "" })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>+ <AlertDialogAction variant="destructive" onClick={() => void confirmDelete()}>+ {t("common.delete")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </main>+ );+}diff --git a/studio/frontend/src/features/scheduled-tasks/unseen.ts b/studio/frontend/src/features/scheduled-tasks/unseen.tsnew file mode 100644index 00000000000..a143054a031--- /dev/null+++ b/studio/frontend/src/features/scheduled-tasks/unseen.ts@@ -0,0 +1,117 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Unseen finished runs: dots on the Scheduled sidebar row and on each task until opened. */++import { create } from "zustand";+import { AUTH_SESSION_CLEARED_EVENT, AUTH_SESSION_STORED_EVENT, getAuthToken } from "@/features/auth";+import { browserAccountKey } from "@/lib/account-transition";+import { UNSEEN_KEY_PREFIX } from "./results";++/** The signed-in account's record (by id), or none while signed out. */+function storageKey(): string | null {+ return getAuthToken() ? UNSEEN_KEY_PREFIX + browserAccountKey() : null;+}++interface Stored {+ tasks: Record<string, string | null>;+ page: boolean;+ /** Result chats not yet opened, apart from `tasks`, which keeps only each task's latest. */+ threads: string[];+}++interface UnseenState extends Stored {+ markFinished: (runs: { taskId: string; threadId: string | null }[], onPage: boolean) => void;+ clearTask: (taskId: string) => void;+ clearThread: (threadId: string) => void;+ clearPage: () => void;+}++const NOTHING_UNSEEN: Stored = { tasks: {}, page: false, threads: [] };++function stored(): Stored | null {+ const key = storageKey();+ if (key === null) return null;+ try {+ const value = JSON.parse(localStorage.getItem(key) ?? "null") as Partial<Stored> | null;+ if (value && typeof value.tasks === "object" && value.tasks !== null) {+ const threads = Array.isArray(value.threads)+ ? value.threads.filter((id): id is string => typeof id === "string")+ : [];+ return { tasks: value.tasks, page: value.page === true, threads };+ }+ return NOTHING_UNSEEN;+ } catch {+ return null;+ }+}++function load(): Stored {+ return stored() ?? NOTHING_UNSEEN;+}++function save({ tasks, page, threads }: Stored): void {+ const key = storageKey();+ if (key === null) return;+ try {+ localStorage.setItem(key, JSON.stringify({ tasks, page, threads }));+ } catch {+ // Without storage the dots last until the next launch.+ }+}++export const useUnseenScheduledRuns = create<UnseenState>()((set, get) => {+ // Start each change from the stored record: another tab may have changed it, and a stale copy would undo that.+ const change = (apply: (current: Stored) => Stored | null) => {+ const current = stored() ?? { tasks: get().tasks, page: get().page, threads: get().threads };+ const next = apply(current);+ if (next === null) return;+ set(next);+ save(next);+ };+ const withoutTask = (current: Stored, taskId: string | undefined): Stored | null => {+ if (taskId === undefined || !(taskId in current.tasks)) return null;+ const tasks = { ...current.tasks };+ delete tasks[taskId];+ return { ...current, tasks };+ };+ return {+ ...(typeof window === "undefined" ? NOTHING_UNSEEN : load()),+ markFinished: (runs, onPage) =>+ change((current) => {+ const tasks = { ...current.tasks };+ const threads = new Set(current.threads);+ for (const run of runs) {+ tasks[run.taskId] = run.threadId;+ if (run.threadId) threads.add(run.threadId);+ }+ // The newest only: a result never opened must not grow the record without end.+ return { tasks, page: current.page || !onPage, threads: [...threads].slice(-200) };+ }),+ clearTask: (taskId) => change((current) => withoutTask(current, taskId)),+ clearThread: (threadId) =>+ change((current) => {+ const read = current.threads.includes(threadId)+ ? { ...current, threads: current.threads.filter((id) => id !== threadId) }+ : current;+ const task = Object.keys(read.tasks).find((id) => read.tasks[id] === threadId);+ return withoutTask(read, task) ?? (read === current ? null : read);+ }),+ clearPage: () =>+ change((current) => (current.page ? { ...current, page: false } : null)),+ };+});++if (typeof window !== "undefined") {+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, () => {+ useUnseenScheduledRuns.setState(NOTHING_UNSEEN);+ });+ window.addEventListener(AUTH_SESSION_STORED_EVENT, () => {+ useUnseenScheduledRuns.setState(load());+ });+ window.addEventListener("storage", (event) => {+ if (event.key?.startsWith(UNSEEN_KEY_PREFIX) && event.key === storageKey()) {+ useUnseenScheduledRuns.setState(load());+ }+ });+}diff --git a/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx b/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsxindex c146b9abf1d..80d50ac6ce8 100644--- a/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx+++ b/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx@@ -13,6 +13,7 @@ import {MoreHorizontalIcon,PencilEdit02Icon,ApiIcon,+ Clock01Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { Reorder, useDragControls } from "motion/react";@@ -44,6 +45,7 @@ const ITEM_META: Record<recipes: { icon: ChefHatIcon, labelKey: "shell.navigation.recipes" },export: { icon: Download01Icon, labelKey: "shell.navigation.export" },api: { icon: ApiIcon, labelKey: "shell.navigation.api" },+ tasks: { icon: Clock01Icon, labelKey: "shell.navigation.tasks" },};function FixedRow({ icon, label }: { icon: IconSvgElement; label: string }) {diff --git a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts b/studio/frontend/src/features/settings/stores/appearance-custom-store.tsindex 7ac59b78d6f..5d7c27d8865 100644--- a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts+++ b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts@@ -104,6 +104,8 @@ export const SIDEBAR_NAV_ITEM_IDS = ["recipes","export","api",+ // Last and under "More", so it joins every saved layout without moving anything.+ "tasks",] as const;export type SidebarNavItemId = (typeof SIDEBAR_NAV_ITEM_IDS)[number];@@ -152,6 +154,7 @@ export const SIDEBAR_NAV_DEFAULT_PINNED: Record<SidebarNavItemId, boolean> = {recipes: false,export: false,api: false,+ tasks: false,};/** Every previously shipped layout, so a migration can tell an untouched install from one thediff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex f4b537de657..ed82abb6a57 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -764,6 +764,7 @@ export const ar = {images: "الصور",video: "الفيديو",audio: "الصوت",+ tasks: "المجدولة",trainChecking: "جارٍ التحقق من دعم هذا الجهاز للتدريب...",videoChecking: "جارٍ التحقق من دعم هذا الجهاز للفيديو...",more: "المزيد",@@ -4279,6 +4280,103 @@ export const ar = {resetDescription: "تعود كل مهارة إلى حالتها في التثبيت الجديد: مهاراتك ومهارات Claude مفعّلة، والمهارات المضمّنة معطّلة. ستُمسح اختياراتك للتفعيل والتعطيل.",reset: "إعادة التعيين",},+ scheduledTasks: {+ title: "المجدولة",+ description: "شغّل الموجّهات وفق جدول باستخدام النموذج المحمّل.",+ newTask: "مهمة جديدة",+ upcoming: "القادمة",+ columns: {+ repeats: "التكرار",+ time: "الوقت",+ nextRun: "التشغيل التالي",+ },+ monthlyDay: "شهريًا، اليوم {day}",+ filterBy: "تصفية حسب",+ filter: "تصفية المهام",+ active: "نشطة",+ noMatches: "لا توجد مهام مجدولة",+ search: "البحث في المهام المجدولة",+ newResult: "نتيجة جديدة",+ sentBy: "أُرسلت بواسطة مهمة مجدولة",+ chatMark: "محادثة من مهمة مجدولة",+ taskMissing: "لم تعد هذه المهمة موجودة.",+ emptyTitle: "لا توجد مهام مجدولة بعد",+ emptyDescription: "ملخص يومي، أو تذكير أسبوعي، أو أي شيء آخر تريد إنجازه وفق جدول.",+ createFirst: "إنشاء مهمة",+ loadFailed: "تعذّر تحميل المهام المجدولة.",+ retry: "إعادة المحاولة",+ paused: "متوقفة مؤقتًا",+ completed: "مكتملة",+ running: "قيد التشغيل",+ lastRun: "آخر تشغيل: {when}",+ lastRunFailed: "فشل آخر تشغيل ({when}): {reason}",+ openChat: "فتح المحادثة",+ runNow: "تشغيل الآن",+ pause: "إيقاف مؤقت",+ resume: "استئناف",+ edit: "تعديل",+ options: "خيارات المهمة",+ schedule: {+ once: "مرة واحدة، {date} في {time}",+ daily: "كل يوم في {time}",+ weekdays: "أيام العمل في {time}",+ weekly: "كل {days} في {time}",+ monthly: "كل شهر في اليوم {day} في {time}",+ },+ form: {+ createTitle: "جدولة مهمة",+ editTitle: "تعديل المهمة المجدولة",+ name: "الاسم",+ namePlaceholder: "الاسم (اختياري)",+ instructions: "التعليمات",+ instructionsHint: "تُرسل إلى النموذج في كل مرة تعمل فيها المهمة.",+ instructionsPlaceholder: "التعليمات…",+ repeat: "التكرار",+ once: "مرة واحدة",+ daily: "يوميًا",+ weekdays: "أيام العمل",+ weekly: "أسبوعيًا",+ monthly: "شهريًا",+ date: "التاريخ",+ time: "الوقت",+ days: "الأيام",+ dayOfMonth: "يوم الشهر",+ lastDayNote: "في الأشهر التي لا تحتوي على هذا اليوم، تعمل في آخر يوم.",+ advanced: "متقدم",+ notifications: "الإشعارات",+ notifyAll: "كل تشغيل",+ notifyFailures: "عند الفشل فقط",+ notifyNone: "إيقاف",+ archiveSuccessful: "أرشفة عمليات التشغيل الناجحة",+ project: "المشروع",+ projectNone: "بلا",+ create: "إنشاء",+ },+ deleteDialog: {+ title: "حذف المهمة المجدولة؟",+ description: "ستتوقف «{title}» عن العمل. ستبقى المحادثات التي أنشأتها.",+ },+ errors: {+ noModel: "لم يكن هناك نموذج مُحمَّل. حمّل نموذجًا في المحادثة، ثم شغّل المهمة مرة أخرى.",+ timeout: "استغرق النموذج وقتًا طويلًا جدًا للإجابة.",+ cancelled: "توقف التشغيل قبل اكتماله.",+ interrupted: "أُغلق Unsloth قبل اكتمال التشغيل.",+ empty: "أعاد النموذج إجابة فارغة.",+ unknown: "فشل التشغيل.",+ saveFailed: "تعذّر حفظ المهمة",+ updateFailed: "تعذّر تحديث المهمة",+ deleteFailed: "تعذّر حذف المهمة",+ runFailed: "تعذّر بدء المهمة",+ },+ toast: {+ finished: "«{title}» جاهزة",+ failed: "فشلت «{title}»",+ many: "اكتملت المهام المجدولة: {count}",+ open: "فتح",+ view: "عرض",+ },+ notificationBody: "اكتملت مهمتك المجدولة. افتح Unsloth لقراءة الإجابة.",+ },library: {tabs: {ariaLabel: "أقسام المكتبة",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex d007f691042..c639da92bac 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -768,6 +768,7 @@ export const de = {images: "Bilder",video: "Video",audio: "Audio",+ tasks: "Geplant",trainChecking: "Dieser Rechner wird auf Trainingsunterstützung geprüft...",videoChecking: "Dieser Rechner wird auf Video-Unterstützung geprüft...",more: "Mehr",@@ -4354,6 +4355,103 @@ export const de = {resetDescription: "Jede Fähigkeit kehrt zum Zustand einer Neuinstallation zurück: deine Fähigkeiten und Claude-Fähigkeiten an, mitgelieferte Fähigkeiten aus. Deine An/Aus-Auswahl wird gelöscht.",reset: "Zurücksetzen",},+ scheduledTasks: {+ title: "Geplant",+ description: "Prompts nach Zeitplan mit dem geladenen Modell ausführen.",+ newTask: "Neue Aufgabe",+ upcoming: "Anstehend",+ columns: {+ repeats: "Wiederholung",+ time: "Uhrzeit",+ nextRun: "Nächste Ausführung",+ },+ monthlyDay: "Monatlich, Tag {day}",+ filterBy: "Filtern nach",+ filter: "Aufgaben filtern",+ active: "Aktiv",+ noMatches: "Keine geplanten Aufgaben",+ search: "Geplante Aufgaben durchsuchen",+ newResult: "Neues Ergebnis",+ sentBy: "Von geplanter Aufgabe gesendet",+ chatMark: "Chat einer geplanten Aufgabe",+ taskMissing: "Diese Aufgabe gibt es nicht mehr.",+ emptyTitle: "Noch keine geplanten Aufgaben",+ emptyDescription: "Eine tägliche Zusammenfassung, eine wöchentliche Erinnerung oder alles andere, was nach Zeitplan erledigt werden soll.",+ createFirst: "Aufgabe erstellen",+ loadFailed: "Geplante Aufgaben konnten nicht geladen werden.",+ retry: "Erneut versuchen",+ paused: "Pausiert",+ completed: "Abgeschlossen",+ running: "Läuft",+ lastRun: "Letzte Ausführung {when}",+ lastRunFailed: "Letzte Ausführung {when} fehlgeschlagen: {reason}",+ openChat: "Chat öffnen",+ runNow: "Jetzt ausführen",+ pause: "Pausieren",+ resume: "Fortsetzen",+ edit: "Bearbeiten",+ options: "Aufgabenoptionen",+ schedule: {+ once: "Einmalig, {date} um {time}",+ daily: "Täglich um {time}",+ weekdays: "Werktags um {time}",+ weekly: "Jeden {days} um {time}",+ monthly: "Monatlich am {day}. um {time}",+ },+ form: {+ createTitle: "Aufgabe planen",+ editTitle: "Geplante Aufgabe bearbeiten",+ name: "Name",+ namePlaceholder: "Name (optional)",+ instructions: "Anweisungen",+ instructionsHint: "Wird bei jeder Ausführung an das Modell gesendet.",+ instructionsPlaceholder: "Anweisungen…",+ repeat: "Wiederholen",+ once: "Einmalig",+ daily: "Täglich",+ weekdays: "Werktags",+ weekly: "Wöchentlich",+ monthly: "Monatlich",+ date: "Datum",+ time: "Uhrzeit",+ days: "Tage",+ dayOfMonth: "Tag im Monat",+ lastDayNote: "In Monaten ohne diesen Tag läuft sie am letzten Tag.",+ advanced: "Erweitert",+ notifications: "Benachrichtigungen",+ notifyAll: "Jede Ausführung",+ notifyFailures: "Nur bei Fehlern",+ notifyNone: "Aus",+ archiveSuccessful: "Erfolgreiche Ausführungen archivieren",+ project: "Projekt",+ projectNone: "Keins",+ create: "Erstellen",+ },+ deleteDialog: {+ title: "Geplante Aufgabe löschen?",+ description: "„{title}“ wird nicht mehr ausgeführt. Bereits erstellte Chats bleiben erhalten.",+ },+ errors: {+ noModel: "Es war kein Modell geladen. Laden Sie im Chat ein Modell und führen Sie die Aufgabe erneut aus.",+ timeout: "Das Modell hat zu lange für die Antwort gebraucht.",+ cancelled: "Die Ausführung wurde vor dem Ende gestoppt.",+ interrupted: "Unsloth wurde geschlossen, bevor die Ausführung fertig war.",+ empty: "Das Modell hat eine leere Antwort geliefert.",+ unknown: "Die Ausführung ist fehlgeschlagen.",+ saveFailed: "Aufgabe konnte nicht gespeichert werden",+ updateFailed: "Aufgabe konnte nicht aktualisiert werden",+ deleteFailed: "Aufgabe konnte nicht gelöscht werden",+ runFailed: "Aufgabe konnte nicht gestartet werden",+ },+ toast: {+ finished: "„{title}“ ist fertig",+ failed: "„{title}“ ist fehlgeschlagen",+ many: "{count} geplante Aufgaben abgeschlossen",+ open: "Öffnen",+ view: "Anzeigen",+ },+ notificationBody: "Ihre geplante Aufgabe ist fertig. Öffnen Sie Unsloth, um die Antwort zu lesen.",+ },library: {tabs: {ariaLabel: "Bereiche der Bibliothek",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 08d9ba6bdda..d4d89a3ec9c 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -816,6 +816,7 @@ export const en = {images: "Images",video: "Video",audio: "Audio",+ tasks: "Scheduled",// Hover text while the row spins, before this machine's capability is measured.trainChecking: "Checking this machine for training support...",videoChecking: "Checking this machine for video support...",@@ -4329,6 +4330,115 @@ export const en = {resetDescription: "Every skill goes back to how a fresh install has it: your skills and Claude skills on, bundled skills off. Your on and off choices are cleared.",reset: "Reset",},+ // The Scheduled page: prompts that run on a schedule, each run answered in a new chat.+ scheduledTasks: {+ title: "Scheduled",+ description: "Run prompts on a schedule with your loaded model.",+ newTask: "New task",+ upcoming: "Upcoming",+ // Column headers over the list, and the Repeats value of a monthly task.+ columns: {+ repeats: "Repeats",+ time: "Time",+ nextRun: "Next run",+ },+ monthlyDay: "Monthly, day {day}",+ // The list's status filter: a menu of Active, Paused and Completed.+ filterBy: "Filter by",+ filter: "Filter tasks",+ active: "Active",+ noMatches: "No scheduled tasks",+ search: "Search scheduled tasks",+ // Read out for the dot on a task whose latest run the user has not opened yet.+ newResult: "New result",+ // Above a prompt a task sent; opens that task for editing.+ sentBy: "Sent by scheduled task",+ // Read out for the clock on a Recents row a task's run made.+ chatMark: "Chat from a scheduled task",+ taskMissing: "This task no longer exists.",+ emptyTitle: "No scheduled tasks yet",+ emptyDescription: "Get a daily summary, a weekly reminder, or anything else you want done on a schedule.",+ createFirst: "Create a task",+ loadFailed: "Could not load scheduled tasks.",+ retry: "Retry",+ // Pills beside a task's name.+ paused: "Paused",+ completed: "Completed",+ running: "Running",+ // {when} is relative, e.g. "2 hours ago".+ lastRun: "Last run {when}",+ // {reason} says why, e.g. "No model was loaded."+ lastRunFailed: "Last run failed {when}: {reason}",+ openChat: "Open chat",+ runNow: "Run now",+ pause: "Pause",+ resume: "Resume",+ edit: "Edit",+ options: "Task options",+ schedule: {+ once: "Once, {date} at {time}",+ daily: "Every day at {time}",+ weekdays: "Every weekday at {time}",+ // {days} is a list of short weekday names, e.g. "Mon, Wed, and Fri".+ weekly: "Every {days} at {time}",+ monthly: "Every month on day {day} at {time}",+ },+ form: {+ createTitle: "Schedule a task",+ editTitle: "Edit scheduled task",+ name: "Name",+ // Left blank, the name is taken from the first line of the instructions.+ namePlaceholder: "Name (optional)",+ instructions: "Instructions",+ instructionsHint: "Sent to the model each time the task runs.",+ instructionsPlaceholder: "Instructions…",+ repeat: "Repeat",+ once: "Once",+ daily: "Daily",+ weekdays: "Weekdays",+ weekly: "Weekly",+ monthly: "Monthly",+ date: "Date",+ time: "Time",+ days: "Days",+ dayOfMonth: "Day of the month",+ lastDayNote: "Months without this day run on their last day.",+ advanced: "Advanced",+ notifications: "Notifications",+ // Which of a task's finished runs get a toast and a system notification.+ notifyAll: "Every run",+ notifyFailures: "Only failures",+ notifyNone: "Off",+ archiveSuccessful: "Archive successful runs",+ project: "Project",+ projectNone: "None",+ create: "Create",+ },+ deleteDialog: {+ title: "Delete scheduled task?",+ description: "“{title}” will stop running. Chats it already made are kept.",+ },+ errors: {+ noModel: "No model was loaded. Load a model in Chat, then run the task again.",+ timeout: "The model took too long to answer.",+ cancelled: "The run was stopped before it finished.",+ interrupted: "Unsloth closed before the run finished.",+ empty: "The model returned an empty answer.",+ unknown: "The run failed.",+ saveFailed: "Could not save the task",+ updateFailed: "Could not update the task",+ deleteFailed: "Could not delete the task",+ runFailed: "Could not start the task",+ },+ toast: {+ finished: "“{title}” is ready",+ failed: "“{title}” failed",+ many: "{count} scheduled tasks finished",+ open: "Open",+ view: "View",+ },+ notificationBody: "Your scheduled task finished. Open Unsloth to read the answer.",+ },// The Library page, its file viewer, and the menus and toasts that act on its files.library: {tabs: {diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex c54ae92ab80..fccc5df76e4 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -767,6 +767,7 @@ export const es = {images: "Imágenes",video: "Vídeo",audio: "Audio",+ tasks: "Programadas",trainChecking: "Comprobando si este equipo admite entrenamiento...",videoChecking: "Comprobando si este equipo admite vídeo...",more: "Más",@@ -4353,6 +4354,103 @@ export const es = {resetDescription: "Cada habilidad vuelve a como está en una instalación nueva: tus habilidades y las de Claude activadas, las incluidas desactivadas. Se borran tus elecciones de activar y desactivar.",reset: "Restablecer",},+ scheduledTasks: {+ title: "Programadas",+ description: "Ejecuta prompts según una programación con tu modelo cargado.",+ newTask: "Nueva tarea",+ upcoming: "Próximas",+ columns: {+ repeats: "Repetición",+ time: "Hora",+ nextRun: "Próxima ejecución",+ },+ monthlyDay: "Mensual, día {day}",+ filterBy: "Filtrar por",+ filter: "Filtrar tareas",+ active: "Activas",+ noMatches: "No hay tareas programadas",+ search: "Buscar tareas programadas",+ newResult: "Nuevo resultado",+ sentBy: "Enviado por una tarea programada",+ chatMark: "Chat de una tarea programada",+ taskMissing: "Esta tarea ya no existe.",+ emptyTitle: "Aún no hay tareas programadas",+ emptyDescription: "Un resumen diario, un recordatorio semanal o cualquier otra cosa que quieras hacer de forma programada.",+ createFirst: "Crear una tarea",+ loadFailed: "No se pudieron cargar las tareas programadas.",+ retry: "Reintentar",+ paused: "En pausa",+ completed: "Completada",+ running: "En ejecución",+ lastRun: "Última ejecución {when}",+ lastRunFailed: "La última ejecución falló {when}: {reason}",+ openChat: "Abrir chat",+ runNow: "Ejecutar ahora",+ pause: "Pausar",+ resume: "Reanudar",+ edit: "Editar",+ options: "Opciones de la tarea",+ schedule: {+ once: "Una vez, el {date} a las {time}",+ daily: "Todos los días a las {time}",+ weekdays: "Entre semana a las {time}",+ weekly: "Cada {days} a las {time}",+ monthly: "Cada mes el día {day} a las {time}",+ },+ form: {+ createTitle: "Programar una tarea",+ editTitle: "Editar tarea programada",+ name: "Nombre",+ namePlaceholder: "Nombre (opcional)",+ instructions: "Instrucciones",+ instructionsHint: "Se envían al modelo cada vez que se ejecuta la tarea.",+ instructionsPlaceholder: "Instrucciones…",+ repeat: "Repetir",+ once: "Una vez",+ daily: "Diaria",+ weekdays: "Entre semana",+ weekly: "Semanal",+ monthly: "Mensual",+ date: "Fecha",+ time: "Hora",+ days: "Días",+ dayOfMonth: "Día del mes",+ lastDayNote: "En los meses sin este día, se ejecuta el último día.",+ advanced: "Avanzado",+ notifications: "Notificaciones",+ notifyAll: "Cada ejecución",+ notifyFailures: "Solo si falla",+ notifyNone: "Desactivadas",+ archiveSuccessful: "Archivar ejecuciones correctas",+ project: "Proyecto",+ projectNone: "Ninguno",+ create: "Crear",+ },+ deleteDialog: {+ title: "¿Eliminar la tarea programada?",+ description: "«{title}» dejará de ejecutarse. Los chats que ya creó se conservan.",+ },+ errors: {+ noModel: "No había ningún modelo cargado. Carga un modelo en el chat y vuelve a ejecutar la tarea.",+ timeout: "El modelo tardó demasiado en responder.",+ cancelled: "La ejecución se detuvo antes de terminar.",+ interrupted: "Unsloth se cerró antes de que terminara la ejecución.",+ empty: "El modelo devolvió una respuesta vacía.",+ unknown: "La ejecución falló.",+ saveFailed: "No se pudo guardar la tarea",+ updateFailed: "No se pudo actualizar la tarea",+ deleteFailed: "No se pudo eliminar la tarea",+ runFailed: "No se pudo iniciar la tarea",+ },+ toast: {+ finished: "«{title}» está lista",+ failed: "«{title}» falló",+ many: "{count} tareas programadas terminaron",+ open: "Abrir",+ view: "Ver",+ },+ notificationBody: "Tu tarea programada terminó. Abre Unsloth para leer la respuesta.",+ },library: {tabs: {ariaLabel: "Secciones de la Biblioteca",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 02d7c9087b0..7b6a2cc9887 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -768,6 +768,7 @@ export const fr = {images: "Images",video: "Vidéo",audio: "Audio",+ tasks: "Planifiées",trainChecking: "Vérification de la prise en charge de l'entraînement sur cette machine...",videoChecking: "Vérification de la prise en charge de la vidéo sur cette machine...",more: "Plus",@@ -4365,6 +4366,103 @@ export const fr = {resetDescription: "Chaque compétence revient à son état d’installation : vos compétences et celles de Claude activées, les compétences intégrées désactivées. Vos choix d’activation sont effacés.",reset: "Réinitialiser",},+ scheduledTasks: {+ title: "Planifiées",+ description: "Exécutez des prompts selon un planning avec le modèle chargé.",+ newTask: "Nouvelle tâche",+ upcoming: "À venir",+ columns: {+ repeats: "Répétition",+ time: "Heure",+ nextRun: "Prochaine exécution",+ },+ monthlyDay: "Mensuel, jour {day}",+ filterBy: "Filtrer par",+ filter: "Filtrer les tâches",+ active: "Actives",+ noMatches: "Aucune tâche planifiée",+ search: "Rechercher des tâches planifiées",+ newResult: "Nouveau résultat",+ sentBy: "Envoyé par une tâche planifiée",+ chatMark: "Discussion d’une tâche planifiée",+ taskMissing: "Cette tâche n’existe plus.",+ emptyTitle: "Aucune tâche planifiée",+ emptyDescription: "Un résumé quotidien, un rappel hebdomadaire ou tout ce que vous voulez faire selon un planning.",+ createFirst: "Créer une tâche",+ loadFailed: "Impossible de charger les tâches planifiées.",+ retry: "Réessayer",+ paused: "En pause",+ completed: "Terminée",+ running: "En cours",+ lastRun: "Dernière exécution {when}",+ lastRunFailed: "Échec de la dernière exécution {when} : {reason}",+ openChat: "Ouvrir le chat",+ runNow: "Exécuter maintenant",+ pause: "Mettre en pause",+ resume: "Reprendre",+ edit: "Modifier",+ options: "Options de la tâche",+ schedule: {+ once: "Une fois, le {date} à {time}",+ daily: "Tous les jours à {time}",+ weekdays: "En semaine à {time}",+ weekly: "Chaque {days} à {time}",+ monthly: "Tous les mois le {day} à {time}",+ },+ form: {+ createTitle: "Planifier une tâche",+ editTitle: "Modifier la tâche planifiée",+ name: "Nom",+ namePlaceholder: "Nom (facultatif)",+ instructions: "Instructions",+ instructionsHint: "Envoyées au modèle à chaque exécution de la tâche.",+ instructionsPlaceholder: "Instructions…",+ repeat: "Répétition",+ once: "Une fois",+ daily: "Tous les jours",+ weekdays: "En semaine",+ weekly: "Chaque semaine",+ monthly: "Chaque mois",+ date: "Date",+ time: "Heure",+ days: "Jours",+ dayOfMonth: "Jour du mois",+ lastDayNote: "Les mois sans ce jour, elle s’exécute le dernier jour.",+ advanced: "Avancé",+ notifications: "Notifications",+ notifyAll: "Chaque exécution",+ notifyFailures: "Seulement en cas d’échec",+ notifyNone: "Désactivées",+ archiveSuccessful: "Archiver les exécutions réussies",+ project: "Projet",+ projectNone: "Aucun",+ create: "Créer",+ },+ deleteDialog: {+ title: "Supprimer la tâche planifiée ?",+ description: "« {title} » ne s’exécutera plus. Les chats déjà créés sont conservés.",+ },+ errors: {+ noModel: "Aucun modèle n’était chargé. Chargez un modèle dans le chat, puis relancez la tâche.",+ timeout: "Le modèle a mis trop de temps à répondre.",+ cancelled: "L’exécution a été arrêtée avant la fin.",+ interrupted: "Unsloth a été fermé avant la fin de l’exécution.",+ empty: "Le modèle a renvoyé une réponse vide.",+ unknown: "L’exécution a échoué.",+ saveFailed: "Impossible d’enregistrer la tâche",+ updateFailed: "Impossible de mettre à jour la tâche",+ deleteFailed: "Impossible de supprimer la tâche",+ runFailed: "Impossible de lancer la tâche",+ },+ toast: {+ finished: "« {title} » est prête",+ failed: "« {title} » a échoué",+ many: "{count} tâches planifiées terminées",+ open: "Ouvrir",+ view: "Voir",+ },+ notificationBody: "Votre tâche planifiée est terminée. Ouvrez Unsloth pour lire la réponse.",+ },library: {tabs: {ariaLabel: "Sections de la Bibliothèque",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex da7ddf8d1da..562a05b1eb3 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -848,6 +848,7 @@ export const he = {images: "תמונות",video: "וידאו",audio: "אודיו",+ tasks: "מתוזמנות",trainChecking: "בודק תמיכה באימון במכשיר זה...",videoChecking: "בודק תמיכה בווידאו במכשיר זה...",more: "עוד",@@ -4397,6 +4398,103 @@ export const he = {resetDescription: "כל מיומנות חוזרת למצב של התקנה חדשה: המיומנויות שלך ומיומנויות Claude מופעלות, מיומנויות מובנות מושבתות. בחירות ההפעלה וההשבתה שלך יימחקו.",reset: "איפוס",},+ scheduledTasks: {+ title: "מתוזמנות",+ description: "הרצת הנחיות לפי לוח זמנים עם המודל הטעון.",+ newTask: "משימה חדשה",+ upcoming: "קרובות",+ columns: {+ repeats: "חזרה",+ time: "שעה",+ nextRun: "ההרצה הבאה",+ },+ monthlyDay: "חודשי, יום {day}",+ filterBy: "סינון לפי",+ filter: "סינון משימות",+ active: "פעילות",+ noMatches: "אין משימות מתוזמנות",+ search: "חיפוש משימות מתוזמנות",+ newResult: "תוצאה חדשה",+ sentBy: "נשלח על ידי משימה מתוזמנת",+ chatMark: "צ׳אט ממשימה מתוזמנת",+ taskMissing: "המשימה הזו כבר לא קיימת.",+ emptyTitle: "אין עדיין משימות מתוזמנות",+ emptyDescription: "סיכום יומי, תזכורת שבועית או כל דבר אחר שתרצה שיתבצע לפי לוח זמנים.",+ createFirst: "צור משימה",+ loadFailed: "לא ניתן לטעון את המשימות המתוזמנות.",+ retry: "נסה שוב",+ paused: "מושהית",+ completed: "הושלמה",+ running: "פועלת",+ lastRun: "ההרצה האחרונה: {when}",+ lastRunFailed: "ההרצה האחרונה נכשלה ({when}): {reason}",+ openChat: "פתח צ'אט",+ runNow: "הפעל עכשיו",+ pause: "השהה",+ resume: "המשך",+ edit: "עריכה",+ options: "אפשרויות משימה",+ schedule: {+ once: "פעם אחת, {date} ב-{time}",+ daily: "כל יום ב-{time}",+ weekdays: "בימי חול ב-{time}",+ weekly: "בכל {days} ב-{time}",+ monthly: "בכל חודש ביום {day} ב-{time}",+ },+ form: {+ createTitle: "תזמון משימה",+ editTitle: "עריכת משימה מתוזמנת",+ name: "שם",+ namePlaceholder: "שם (אופציונלי)",+ instructions: "הוראות",+ instructionsHint: "נשלחות למודל בכל פעם שהמשימה רצה.",+ instructionsPlaceholder: "הוראות…",+ repeat: "חזרה",+ once: "פעם אחת",+ daily: "יומי",+ weekdays: "ימי חול",+ weekly: "שבועי",+ monthly: "חודשי",+ date: "תאריך",+ time: "שעה",+ days: "ימים",+ dayOfMonth: "יום בחודש",+ lastDayNote: "בחודשים שאין בהם יום זה, המשימה רצה ביום האחרון.",+ advanced: "מתקדם",+ notifications: "התראות",+ notifyAll: "כל הרצה",+ notifyFailures: "רק בכישלון",+ notifyNone: "כבויות",+ archiveSuccessful: "להעביר לארכיון הרצות שהצליחו",+ project: "פרויקט",+ projectNone: "ללא",+ create: "יצירה",+ },+ deleteDialog: {+ title: "למחוק את המשימה המתוזמנת?",+ description: "\"{title}\" תפסיק לרוץ. צ'אטים שכבר נוצרו יישמרו.",+ },+ errors: {+ noModel: "לא היה מודל טעון. טען מודל בצ'אט ואז הפעל את המשימה שוב.",+ timeout: "למודל לקח יותר מדי זמן לענות.",+ cancelled: "ההרצה נעצרה לפני שהסתיימה.",+ interrupted: "Unsloth נסגר לפני שההרצה הסתיימה.",+ empty: "המודל החזיר תשובה ריקה.",+ unknown: "ההרצה נכשלה.",+ saveFailed: "לא ניתן לשמור את המשימה",+ updateFailed: "לא ניתן לעדכן את המשימה",+ deleteFailed: "לא ניתן למחוק את המשימה",+ runFailed: "לא ניתן להפעיל את המשימה",+ },+ toast: {+ finished: "\"{title}\" מוכנה",+ failed: "\"{title}\" נכשלה",+ many: "{count} משימות מתוזמנות הסתיימו",+ open: "פתח",+ view: "הצג",+ },+ notificationBody: "המשימה המתוזמנת שלך הסתיימה. פתח את Unsloth כדי לקרוא את התשובה.",+ },library: {tabs: {ariaLabel: "מדורי הספרייה",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 31879dc1b9f..7ebaf1c63d4 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -768,6 +768,7 @@ export const hi = {images: "इमेज",video: "वीडियो",audio: "ऑडियो",+ tasks: "शेड्यूल्ड",trainChecking: "इस मशीन पर ट्रेनिंग सपोर्ट की जाँच हो रही है...",videoChecking: "इस मशीन पर वीडियो सपोर्ट की जाँच हो रही है...",more: "अधिक",@@ -4290,6 +4291,103 @@ export const hi = {resetDescription: "हर कौशल नए इंस्टॉल वाली स्थिति में लौट आता है: आपके कौशल और Claude कौशल चालू, बंडल किए गए कौशल बंद। आपकी चालू/बंद पसंद हटा दी जाती है।",reset: "रीसेट करें",},+ scheduledTasks: {+ title: "शेड्यूल्ड",+ description: "लोड किए गए मॉडल के साथ शेड्यूल पर प्रॉम्प्ट चलाएँ।",+ newTask: "नया टास्क",+ upcoming: "आगामी",+ columns: {+ repeats: "दोहराव",+ time: "समय",+ nextRun: "अगला रन",+ },+ monthlyDay: "मासिक, दिन {day}",+ filterBy: "इसके अनुसार फ़िल्टर करें",+ filter: "टास्क फ़िल्टर करें",+ active: "सक्रिय",+ noMatches: "कोई शेड्यूल किया गया टास्क नहीं",+ search: "शेड्यूल किए गए टास्क खोजें",+ newResult: "नया नतीजा",+ sentBy: "शेड्यूल किए गए टास्क ने भेजा",+ chatMark: "शेड्यूल किए गए टास्क की चैट",+ taskMissing: "यह टास्क अब मौजूद नहीं है।",+ emptyTitle: "अभी कोई शेड्यूल किया गया टास्क नहीं है",+ emptyDescription: "रोज़ का सारांश, हर हफ़्ते का रिमाइंडर, या कुछ भी जो आप शेड्यूल पर करवाना चाहें।",+ createFirst: "टास्क बनाएँ",+ loadFailed: "शेड्यूल किए गए टास्क लोड नहीं हो सके।",+ retry: "फिर से कोशिश करें",+ paused: "रुका हुआ",+ completed: "पूर्ण",+ running: "चल रहा है",+ lastRun: "पिछला रन: {when}",+ lastRunFailed: "पिछला रन विफल रहा ({when}): {reason}",+ openChat: "चैट खोलें",+ runNow: "अभी चलाएँ",+ pause: "रोकें",+ resume: "फिर शुरू करें",+ edit: "संपादित करें",+ options: "टास्क विकल्प",+ schedule: {+ once: "एक बार, {date} को {time} बजे",+ daily: "हर दिन {time} बजे",+ weekdays: "हर कार्यदिवस {time} बजे",+ weekly: "हर {days} को {time} बजे",+ monthly: "हर महीने की {day} तारीख को {time} बजे",+ },+ form: {+ createTitle: "टास्क शेड्यूल करें",+ editTitle: "शेड्यूल किया गया टास्क संपादित करें",+ name: "नाम",+ namePlaceholder: "नाम (वैकल्पिक)",+ instructions: "निर्देश",+ instructionsHint: "टास्क चलने पर हर बार मॉडल को भेजे जाते हैं।",+ instructionsPlaceholder: "निर्देश…",+ repeat: "दोहराएँ",+ once: "एक बार",+ daily: "रोज़ाना",+ weekdays: "कार्यदिवस",+ weekly: "साप्ताहिक",+ monthly: "मासिक",+ date: "तारीख",+ time: "समय",+ days: "दिन",+ dayOfMonth: "महीने का दिन",+ lastDayNote: "जिन महीनों में यह दिन नहीं होता, उनमें यह आखिरी दिन चलता है।",+ advanced: "उन्नत",+ notifications: "सूचनाएँ",+ notifyAll: "हर रन",+ notifyFailures: "सिर्फ़ विफल होने पर",+ notifyNone: "बंद",+ archiveSuccessful: "सफल रन संग्रहित करें",+ project: "प्रोजेक्ट",+ projectNone: "कोई नहीं",+ create: "बनाएँ",+ },+ deleteDialog: {+ title: "शेड्यूल किया गया टास्क हटाएँ?",+ description: "“{title}” अब नहीं चलेगा। इसके द्वारा पहले बनाई गई चैट बनी रहेंगी।",+ },+ errors: {+ noModel: "कोई मॉडल लोड नहीं था। चैट में मॉडल लोड करें, फिर टास्क दोबारा चलाएँ।",+ timeout: "मॉडल ने जवाब देने में बहुत ज़्यादा समय लिया।",+ cancelled: "रन पूरा होने से पहले रोक दिया गया।",+ interrupted: "रन पूरा होने से पहले Unsloth बंद हो गया।",+ empty: "मॉडल ने खाली जवाब दिया।",+ unknown: "रन विफल रहा।",+ saveFailed: "टास्क सहेजा नहीं जा सका",+ updateFailed: "टास्क अपडेट नहीं हो सका",+ deleteFailed: "टास्क हटाया नहीं जा सका",+ runFailed: "टास्क शुरू नहीं हो सका",+ },+ toast: {+ finished: "“{title}” तैयार है",+ failed: "“{title}” विफल रहा",+ many: "{count} शेड्यूल किए गए टास्क पूरे हुए",+ open: "खोलें",+ view: "देखें",+ },+ notificationBody: "आपका शेड्यूल किया गया टास्क पूरा हो गया। जवाब पढ़ने के लिए Unsloth खोलें।",+ },library: {tabs: {ariaLabel: "लाइब्रेरी के सेक्शन",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 8192fee39ac..2912b37cd66 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -669,6 +669,7 @@ export const it = {images: "Immagini",video: "Video",audio: "Audio",+ tasks: "Pianificate",trainChecking: "Verifica del supporto all'addestramento su questa macchina...",videoChecking: "Verifica del supporto video su questa macchina...",more: "Altro",@@ -4355,6 +4356,103 @@ export const it = {resetDescription: "Ogni competenza torna come in una nuova installazione: le tue competenze e quelle di Claude attive, quelle incluse disattivate. Le tue scelte di attivazione vengono cancellate.",reset: "Ripristina",},+ scheduledTasks: {+ title: "Pianificate",+ description: "Esegui prompt secondo una pianificazione con il modello caricato.",+ newTask: "Nuova attività",+ upcoming: "In arrivo",+ columns: {+ repeats: "Ripetizione",+ time: "Ora",+ nextRun: "Prossima esecuzione",+ },+ monthlyDay: "Mensile, giorno {day}",+ filterBy: "Filtra per",+ filter: "Filtra attività",+ active: "Attive",+ noMatches: "Nessuna attività pianificata",+ search: "Cerca attività pianificate",+ newResult: "Nuovo risultato",+ sentBy: "Inviato da un’attività pianificata",+ chatMark: "Chat di un’attività pianificata",+ taskMissing: "Questa attività non esiste più.",+ emptyTitle: "Ancora nessuna attività pianificata",+ emptyDescription: "Un riepilogo giornaliero, un promemoria settimanale o qualsiasi altra cosa da fare a orari prestabiliti.",+ createFirst: "Crea un’attività",+ loadFailed: "Impossibile caricare le attività pianificate.",+ retry: "Riprova",+ paused: "In pausa",+ completed: "Completata",+ running: "In esecuzione",+ lastRun: "Ultima esecuzione {when}",+ lastRunFailed: "Ultima esecuzione non riuscita {when}: {reason}",+ openChat: "Apri chat",+ runNow: "Esegui ora",+ pause: "Metti in pausa",+ resume: "Riprendi",+ edit: "Modifica",+ options: "Opzioni attività",+ schedule: {+ once: "Una volta, il {date} alle {time}",+ daily: "Ogni giorno alle {time}",+ weekdays: "Nei giorni feriali alle {time}",+ weekly: "Ogni {days} alle {time}",+ monthly: "Ogni mese il giorno {day} alle {time}",+ },+ form: {+ createTitle: "Pianifica un’attività",+ editTitle: "Modifica attività pianificata",+ name: "Nome",+ namePlaceholder: "Nome (facoltativo)",+ instructions: "Istruzioni",+ instructionsHint: "Inviate al modello a ogni esecuzione dell’attività.",+ instructionsPlaceholder: "Istruzioni…",+ repeat: "Ripeti",+ once: "Una volta",+ daily: "Ogni giorno",+ weekdays: "Giorni feriali",+ weekly: "Ogni settimana",+ monthly: "Ogni mese",+ date: "Data",+ time: "Ora",+ days: "Giorni",+ dayOfMonth: "Giorno del mese",+ lastDayNote: "Nei mesi senza questo giorno viene eseguita l’ultimo giorno.",+ advanced: "Avanzate",+ notifications: "Notifiche",+ notifyAll: "Ogni esecuzione",+ notifyFailures: "Solo se non riesce",+ notifyNone: "Disattivate",+ archiveSuccessful: "Archivia le esecuzioni riuscite",+ project: "Progetto",+ projectNone: "Nessuno",+ create: "Crea",+ },+ deleteDialog: {+ title: "Eliminare l’attività pianificata?",+ description: "«{title}» non verrà più eseguita. Le chat già create vengono mantenute.",+ },+ errors: {+ noModel: "Nessun modello era caricato. Carica un modello nella chat, poi esegui di nuovo l’attività.",+ timeout: "Il modello ha impiegato troppo tempo a rispondere.",+ cancelled: "L’esecuzione è stata interrotta prima della fine.",+ interrupted: "Unsloth è stato chiuso prima della fine dell’esecuzione.",+ empty: "Il modello ha restituito una risposta vuota.",+ unknown: "Esecuzione non riuscita.",+ saveFailed: "Impossibile salvare l’attività",+ updateFailed: "Impossibile aggiornare l’attività",+ deleteFailed: "Impossibile eliminare l’attività",+ runFailed: "Impossibile avviare l’attività",+ },+ toast: {+ finished: "«{title}» è pronta",+ failed: "«{title}» non è riuscita",+ many: "{count} attività pianificate completate",+ open: "Apri",+ view: "Visualizza",+ },+ notificationBody: "La tua attività pianificata è terminata. Apri Unsloth per leggere la risposta.",+ },library: {tabs: {ariaLabel: "Sezioni della Libreria",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 6a80e6713a4..f73ee1a3202 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -766,6 +766,7 @@ export const ja = {images: "画像",video: "動画",audio: "音声",+ tasks: "スケジュール済み",trainChecking: "このマシンのトレーニング対応を確認しています...",videoChecking: "このマシンの動画生成対応を確認しています...",more: "その他",@@ -4229,6 +4230,103 @@ export const ja = {resetDescription: "すべてのスキルが新規インストール時の状態に戻ります。自分のスキルと Claude のスキルはオン、同梱スキルはオフになり、オン/オフの選択は消去されます。",reset: "リセット",},+ scheduledTasks: {+ title: "スケジュール済み",+ description: "読み込んだモデルでプロンプトをスケジュール実行します。",+ newTask: "新しいタスク",+ upcoming: "今後の予定",+ columns: {+ repeats: "繰り返し",+ time: "時刻",+ nextRun: "次回実行",+ },+ monthlyDay: "毎月{day}日",+ filterBy: "フィルター",+ filter: "タスクを絞り込む",+ active: "有効",+ noMatches: "スケジュール済みのタスクはありません",+ search: "スケジュール済みタスクを検索",+ newResult: "新しい結果",+ sentBy: "スケジュール済みタスクから送信",+ chatMark: "スケジュール済みタスクのチャット",+ taskMissing: "このタスクはもう存在しません。",+ emptyTitle: "スケジュール済みのタスクはまだありません",+ emptyDescription: "毎日の要約、毎週のリマインダーなど、決まった時間に行いたいことを設定できます。",+ createFirst: "タスクを作成",+ loadFailed: "スケジュール済みタスクを読み込めませんでした。",+ retry: "再試行",+ paused: "一時停止中",+ completed: "完了",+ running: "実行中",+ lastRun: "前回実行: {when}",+ lastRunFailed: "前回の実行は失敗しました({when}): {reason}",+ openChat: "チャットを開く",+ runNow: "今すぐ実行",+ pause: "一時停止",+ resume: "再開",+ edit: "編集",+ options: "タスクのオプション",+ schedule: {+ once: "1 回のみ、{date} {time}",+ daily: "毎日 {time}",+ weekdays: "平日 {time}",+ weekly: "毎週 {days} {time}",+ monthly: "毎月 {day} 日 {time}",+ },+ form: {+ createTitle: "タスクをスケジュール",+ editTitle: "スケジュール済みタスクを編集",+ name: "名前",+ namePlaceholder: "名前(任意)",+ instructions: "指示",+ instructionsHint: "タスクを実行するたびにモデルへ送信されます。",+ instructionsPlaceholder: "指示…",+ repeat: "繰り返し",+ once: "1 回のみ",+ daily: "毎日",+ weekdays: "平日",+ weekly: "毎週",+ monthly: "毎月",+ date: "日付",+ time: "時刻",+ days: "曜日",+ dayOfMonth: "日にち",+ lastDayNote: "その日がない月は、月末に実行されます。",+ advanced: "詳細設定",+ notifications: "通知",+ notifyAll: "毎回",+ notifyFailures: "失敗時のみ",+ notifyNone: "オフ",+ archiveSuccessful: "成功した実行をアーカイブ",+ project: "プロジェクト",+ projectNone: "なし",+ create: "作成",+ },+ deleteDialog: {+ title: "スケジュール済みタスクを削除しますか?",+ description: "「{title}」は実行されなくなります。作成済みのチャットは残ります。",+ },+ errors: {+ noModel: "モデルが読み込まれていませんでした。チャットでモデルを読み込んでから、もう一度タスクを実行してください。",+ timeout: "モデルの応答に時間がかかりすぎました。",+ cancelled: "実行は完了前に停止されました。",+ interrupted: "実行が完了する前に Unsloth が閉じられました。",+ empty: "モデルが空の回答を返しました。",+ unknown: "実行に失敗しました。",+ saveFailed: "タスクを保存できませんでした",+ updateFailed: "タスクを更新できませんでした",+ deleteFailed: "タスクを削除できませんでした",+ runFailed: "タスクを開始できませんでした",+ },+ toast: {+ finished: "「{title}」が完了しました",+ failed: "「{title}」が失敗しました",+ many: "{count} 件のスケジュール済みタスクが完了しました",+ open: "開く",+ view: "表示",+ },+ notificationBody: "スケジュール済みタスクが完了しました。Unsloth を開いて回答をご確認ください。",+ },library: {tabs: {ariaLabel: "ライブラリのセクション",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex cda60440a5e..9d2c8a5e9fa 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -764,6 +764,7 @@ export const ko = {images: "이미지",video: "동영상",audio: "오디오",+ tasks: "예약됨",trainChecking: "이 컴퓨터의 학습 지원 여부를 확인하는 중...",videoChecking: "이 컴퓨터의 비디오 지원 여부를 확인하는 중...",more: "더 보기",@@ -4268,6 +4269,103 @@ export const ko = {resetDescription: "모든 스킬이 새로 설치한 상태로 돌아갑니다. 내 스킬과 Claude 스킬은 켜지고 번들 스킬은 꺼지며, 켜기/끄기 선택은 지워집니다.",reset: "재설정",},+ scheduledTasks: {+ title: "예약됨",+ description: "불러온 모델로 프롬프트를 예약 실행합니다.",+ newTask: "새 작업",+ upcoming: "예정",+ columns: {+ repeats: "반복",+ time: "시간",+ nextRun: "다음 실행",+ },+ monthlyDay: "매월 {day}일",+ filterBy: "필터 기준",+ filter: "작업 필터",+ active: "활성",+ noMatches: "예약된 작업이 없습니다",+ search: "예약된 작업 검색",+ newResult: "새 결과",+ sentBy: "예약된 작업이 보냄",+ chatMark: "예약된 작업의 채팅",+ taskMissing: "이 작업은 더 이상 없습니다.",+ emptyTitle: "아직 예약된 작업이 없습니다",+ emptyDescription: "매일 요약, 매주 알림 등 정해진 일정에 하고 싶은 일을 설정하세요.",+ createFirst: "작업 만들기",+ loadFailed: "예약된 작업을 불러오지 못했습니다.",+ retry: "다시 시도",+ paused: "일시 중지됨",+ completed: "완료됨",+ running: "실행 중",+ lastRun: "마지막 실행: {when}",+ lastRunFailed: "마지막 실행 실패({when}): {reason}",+ openChat: "채팅 열기",+ runNow: "지금 실행",+ pause: "일시 중지",+ resume: "재개",+ edit: "편집",+ options: "작업 옵션",+ schedule: {+ once: "한 번, {date} {time}",+ daily: "매일 {time}",+ weekdays: "평일 {time}",+ weekly: "매주 {days} {time}",+ monthly: "매월 {day}일 {time}",+ },+ form: {+ createTitle: "작업 예약",+ editTitle: "예약 작업 편집",+ name: "이름",+ namePlaceholder: "이름 (선택 사항)",+ instructions: "지침",+ instructionsHint: "작업이 실행될 때마다 모델에 전송됩니다.",+ instructionsPlaceholder: "지침…",+ repeat: "반복",+ once: "한 번",+ daily: "매일",+ weekdays: "평일",+ weekly: "매주",+ monthly: "매월",+ date: "날짜",+ time: "시간",+ days: "요일",+ dayOfMonth: "날짜(일)",+ lastDayNote: "해당 날짜가 없는 달에는 마지막 날에 실행됩니다.",+ advanced: "고급",+ notifications: "알림",+ notifyAll: "모든 실행",+ notifyFailures: "실패 시에만",+ notifyNone: "끄기",+ archiveSuccessful: "성공한 실행 보관",+ project: "프로젝트",+ projectNone: "없음",+ create: "만들기",+ },+ deleteDialog: {+ title: "예약된 작업을 삭제할까요?",+ description: "\"{title}\" 작업이 더 이상 실행되지 않습니다. 이미 만든 채팅은 유지됩니다.",+ },+ errors: {+ noModel: "로드된 모델이 없었습니다. 채팅에서 모델을 로드한 다음 작업을 다시 실행하세요.",+ timeout: "모델이 응답하는 데 너무 오래 걸렸습니다.",+ cancelled: "실행이 완료되기 전에 중지되었습니다.",+ interrupted: "실행이 끝나기 전에 Unsloth가 닫혔습니다.",+ empty: "모델이 빈 답변을 반환했습니다.",+ unknown: "실행에 실패했습니다.",+ saveFailed: "작업을 저장하지 못했습니다",+ updateFailed: "작업을 업데이트하지 못했습니다",+ deleteFailed: "작업을 삭제하지 못했습니다",+ runFailed: "작업을 시작하지 못했습니다",+ },+ toast: {+ finished: "\"{title}\" 완료",+ failed: "\"{title}\" 실패",+ many: "예약된 작업 {count}개 완료",+ open: "열기",+ view: "보기",+ },+ notificationBody: "예약된 작업이 완료되었습니다. Unsloth를 열어 답변을 확인하세요.",+ },library: {tabs: {ariaLabel: "라이브러리 섹션",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex e6b0708eada..638cb60bb61 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -767,6 +767,7 @@ export const ptBR = {images: "Imagens",video: "Vídeo",audio: "Áudio",+ tasks: "Agendadas",trainChecking: "Verificando se esta máquina oferece suporte a treino...",videoChecking: "Verificando se esta máquina oferece suporte a vídeo...",more: "Mais",@@ -4313,6 +4314,103 @@ export const ptBR = {resetDescription: "Cada habilidade volta ao estado de uma instalação nova: suas habilidades e as do Claude ativadas, as incluídas desativadas. Suas escolhas de ativar e desativar são apagadas.",reset: "Redefinir",},+ scheduledTasks: {+ title: "Agendadas",+ description: "Execute prompts em uma programação com o modelo carregado.",+ newTask: "Nova tarefa",+ upcoming: "Próximas",+ columns: {+ repeats: "Repetição",+ time: "Horário",+ nextRun: "Próxima execução",+ },+ monthlyDay: "Mensal, dia {day}",+ filterBy: "Filtrar por",+ filter: "Filtrar tarefas",+ active: "Ativas",+ noMatches: "Nenhuma tarefa agendada",+ search: "Pesquisar tarefas agendadas",+ newResult: "Novo resultado",+ sentBy: "Enviado por tarefa agendada",+ chatMark: "Chat de uma tarefa agendada",+ taskMissing: "Esta tarefa não existe mais.",+ emptyTitle: "Nenhuma tarefa agendada ainda",+ emptyDescription: "Um resumo diário, um lembrete semanal ou qualquer outra coisa que você queira em horários programados.",+ createFirst: "Criar uma tarefa",+ loadFailed: "Não foi possível carregar as tarefas agendadas.",+ retry: "Tentar novamente",+ paused: "Pausada",+ completed: "Concluída",+ running: "Em execução",+ lastRun: "Última execução {when}",+ lastRunFailed: "A última execução falhou {when}: {reason}",+ openChat: "Abrir chat",+ runNow: "Executar agora",+ pause: "Pausar",+ resume: "Retomar",+ edit: "Editar",+ options: "Opções da tarefa",+ schedule: {+ once: "Uma vez, em {date} às {time}",+ daily: "Todos os dias às {time}",+ weekdays: "Em dias úteis às {time}",+ weekly: "Toda semana: {days}, às {time}",+ monthly: "Todo mês no dia {day} às {time}",+ },+ form: {+ createTitle: "Agendar uma tarefa",+ editTitle: "Editar tarefa agendada",+ name: "Nome",+ namePlaceholder: "Nome (opcional)",+ instructions: "Instruções",+ instructionsHint: "Enviadas ao modelo sempre que a tarefa for executada.",+ instructionsPlaceholder: "Instruções…",+ repeat: "Repetir",+ once: "Uma vez",+ daily: "Diariamente",+ weekdays: "Dias úteis",+ weekly: "Semanalmente",+ monthly: "Mensalmente",+ date: "Data",+ time: "Horário",+ days: "Dias",+ dayOfMonth: "Dia do mês",+ lastDayNote: "Nos meses sem esse dia, ela é executada no último dia.",+ advanced: "Avançado",+ notifications: "Notificações",+ notifyAll: "Cada execução",+ notifyFailures: "Só em caso de falha",+ notifyNone: "Desativadas",+ archiveSuccessful: "Arquivar execuções bem-sucedidas",+ project: "Projeto",+ projectNone: "Nenhum",+ create: "Criar",+ },+ deleteDialog: {+ title: "Excluir tarefa agendada?",+ description: "“{title}” deixará de ser executada. Os chats que ela já criou serão mantidos.",+ },+ errors: {+ noModel: "Nenhum modelo estava carregado. Carregue um modelo no chat e execute a tarefa de novo.",+ timeout: "O modelo demorou demais para responder.",+ cancelled: "A execução foi interrompida antes de terminar.",+ interrupted: "O Unsloth foi fechado antes de a execução terminar.",+ empty: "O modelo retornou uma resposta vazia.",+ unknown: "A execução falhou.",+ saveFailed: "Não foi possível salvar a tarefa",+ updateFailed: "Não foi possível atualizar a tarefa",+ deleteFailed: "Não foi possível excluir a tarefa",+ runFailed: "Não foi possível iniciar a tarefa",+ },+ toast: {+ finished: "“{title}” está pronta",+ failed: "“{title}” falhou",+ many: "{count} tarefas agendadas concluídas",+ open: "Abrir",+ view: "Ver",+ },+ notificationBody: "Sua tarefa agendada terminou. Abra o Unsloth para ler a resposta.",+ },library: {tabs: {ariaLabel: "Seções da Biblioteca",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex e65d4d15e02..ac2e3b0387a 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -767,6 +767,7 @@ export const ru = {images: "Изображения",video: "Видео",audio: "Аудио",+ tasks: "Запланированные",trainChecking: "Проверка поддержки обучения на этой машине...",videoChecking: "Проверка поддержки видео на этой машине...",more: "Ещё",@@ -4311,6 +4312,103 @@ export const ru = {resetDescription: "Каждый навык вернётся в состояние новой установки: ваши навыки и навыки Claude включены, встроенные отключены. Ваш выбор включения и отключения будет удалён.",reset: "Сбросить",},+ scheduledTasks: {+ title: "Запланированные",+ description: "Запускайте промпты по расписанию на загруженной модели.",+ newTask: "Новая задача",+ upcoming: "Предстоящие",+ columns: {+ repeats: "Повтор",+ time: "Время",+ nextRun: "Следующий запуск",+ },+ monthlyDay: "Ежемесячно, {day}-е число",+ filterBy: "Фильтр",+ filter: "Фильтровать задачи",+ active: "Активные",+ noMatches: "Нет запланированных задач",+ search: "Поиск запланированных задач",+ newResult: "Новый результат",+ sentBy: "Отправлено запланированной задачей",+ chatMark: "Чат запланированной задачи",+ taskMissing: "Этой задачи больше нет.",+ emptyTitle: "Запланированных задач пока нет",+ emptyDescription: "Ежедневная сводка, еженедельное напоминание или что угодно другое по расписанию.",+ createFirst: "Создать задачу",+ loadFailed: "Не удалось загрузить запланированные задачи.",+ retry: "Повторить",+ paused: "Приостановлена",+ completed: "Завершена",+ running: "Выполняется",+ lastRun: "Последний запуск {when}",+ lastRunFailed: "Последний запуск {when} не удался: {reason}",+ openChat: "Открыть чат",+ runNow: "Запустить сейчас",+ pause: "Приостановить",+ resume: "Возобновить",+ edit: "Изменить",+ options: "Параметры задачи",+ schedule: {+ once: "Однократно, {date} в {time}",+ daily: "Каждый день в {time}",+ weekdays: "По будням в {time}",+ weekly: "По дням: {days}, в {time}",+ monthly: "Каждый месяц, {day}-го числа, в {time}",+ },+ form: {+ createTitle: "Запланировать задачу",+ editTitle: "Изменить запланированную задачу",+ name: "Название",+ namePlaceholder: "Название (необязательно)",+ instructions: "Инструкции",+ instructionsHint: "Отправляются модели при каждом запуске задачи.",+ instructionsPlaceholder: "Инструкции…",+ repeat: "Повтор",+ once: "Однократно",+ daily: "Ежедневно",+ weekdays: "По будням",+ weekly: "Еженедельно",+ monthly: "Ежемесячно",+ date: "Дата",+ time: "Время",+ days: "Дни",+ dayOfMonth: "День месяца",+ lastDayNote: "В месяцы без этого дня задача выполняется в последний день.",+ advanced: "Дополнительно",+ notifications: "Уведомления",+ notifyAll: "Каждый запуск",+ notifyFailures: "Только ошибки",+ notifyNone: "Выключены",+ archiveSuccessful: "Архивировать успешные запуски",+ project: "Проект",+ projectNone: "Нет",+ create: "Создать",+ },+ deleteDialog: {+ title: "Удалить запланированную задачу?",+ description: "«{title}» больше не будет запускаться. Уже созданные ею чаты сохранятся.",+ },+ errors: {+ noModel: "Модель не была загружена. Загрузите модель в чате и запустите задачу снова.",+ timeout: "Модель отвечала слишком долго.",+ cancelled: "Запуск был остановлен до завершения.",+ interrupted: "Unsloth закрылся до завершения запуска.",+ empty: "Модель вернула пустой ответ.",+ unknown: "Запуск не удался.",+ saveFailed: "Не удалось сохранить задачу",+ updateFailed: "Не удалось обновить задачу",+ deleteFailed: "Не удалось удалить задачу",+ runFailed: "Не удалось запустить задачу",+ },+ toast: {+ finished: "«{title}»: готово",+ failed: "«{title}»: ошибка",+ many: "Завершено запланированных задач: {count}",+ open: "Открыть",+ view: "Показать",+ },+ notificationBody: "Запланированная задача выполнена. Откройте Unsloth, чтобы прочитать ответ.",+ },library: {tabs: {ariaLabel: "Разделы библиотеки",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 7cb0b9d1833..257f8380d02 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -866,6 +866,7 @@ export const sv = {images: "Bilder",video: "Video",audio: "Ljud",+ tasks: "Schemalagt",trainChecking: "Kontrollerar om denna dator stöder träning …",videoChecking: "Kontrollerar om denna dator stöder video …",more: "Mer",@@ -4532,6 +4533,103 @@ export const sv = {resetDescription: "Varje färdighet återgår till hur en ny installation har den: dina färdigheter och Claude-färdigheter på, medföljande färdigheter av. Dina val av på och av rensas.",reset: "Återställ",},+ scheduledTasks: {+ title: "Schemalagt",+ description: "Kör promptar enligt schema med den inlästa modellen.",+ newTask: "Ny uppgift",+ upcoming: "Kommande",+ columns: {+ repeats: "Upprepning",+ time: "Tid",+ nextRun: "Nästa körning",+ },+ monthlyDay: "Månadsvis, dag {day}",+ filterBy: "Filtrera efter",+ filter: "Filtrera uppgifter",+ active: "Aktiva",+ noMatches: "Inga schemalagda uppgifter",+ search: "Sök schemalagda uppgifter",+ newResult: "Nytt resultat",+ sentBy: "Skickat av schemalagd uppgift",+ chatMark: "Chatt från en schemalagd uppgift",+ taskMissing: "Den här uppgiften finns inte längre.",+ emptyTitle: "Inga schemalagda uppgifter än",+ emptyDescription: "En daglig sammanfattning, en påminnelse varje vecka eller något annat du vill få gjort enligt ett schema.",+ createFirst: "Skapa en uppgift",+ loadFailed: "Det gick inte att läsa in schemalagda uppgifter.",+ retry: "Försök igen",+ paused: "Pausad",+ completed: "Slutförd",+ running: "Körs",+ lastRun: "Senaste körning {when}",+ lastRunFailed: "Senaste körningen misslyckades {when}: {reason}",+ openChat: "Öppna chatt",+ runNow: "Kör nu",+ pause: "Pausa",+ resume: "Återuppta",+ edit: "Redigera",+ options: "Uppgiftsalternativ",+ schedule: {+ once: "En gång, {date} kl. {time}",+ daily: "Varje dag kl. {time}",+ weekdays: "Vardagar kl. {time}",+ weekly: "Varje {days} kl. {time}",+ monthly: "Dag {day} varje månad kl. {time}",+ },+ form: {+ createTitle: "Schemalägg en uppgift",+ editTitle: "Redigera schemalagd uppgift",+ name: "Namn",+ namePlaceholder: "Namn (valfritt)",+ instructions: "Instruktioner",+ instructionsHint: "Skickas till modellen varje gång uppgiften körs.",+ instructionsPlaceholder: "Instruktioner…",+ repeat: "Upprepa",+ once: "En gång",+ daily: "Dagligen",+ weekdays: "Vardagar",+ weekly: "Varje vecka",+ monthly: "Varje månad",+ date: "Datum",+ time: "Tid",+ days: "Dagar",+ dayOfMonth: "Dag i månaden",+ lastDayNote: "Månader utan den dagen körs den på sista dagen.",+ advanced: "Avancerat",+ notifications: "Aviseringar",+ notifyAll: "Varje körning",+ notifyFailures: "Bara vid fel",+ notifyNone: "Av",+ archiveSuccessful: "Arkivera lyckade körningar",+ project: "Projekt",+ projectNone: "Inget",+ create: "Skapa",+ },+ deleteDialog: {+ title: "Ta bort schemalagd uppgift?",+ description: "”{title}” slutar köras. Chattar som den redan har skapat behålls.",+ },+ errors: {+ noModel: "Ingen modell var inläst. Läs in en modell i chatten och kör sedan uppgiften igen.",+ timeout: "Modellen tog för lång tid på sig att svara.",+ cancelled: "Körningen stoppades innan den var klar.",+ interrupted: "Unsloth stängdes innan körningen var klar.",+ empty: "Modellen returnerade ett tomt svar.",+ unknown: "Körningen misslyckades.",+ saveFailed: "Det gick inte att spara uppgiften",+ updateFailed: "Det gick inte att uppdatera uppgiften",+ deleteFailed: "Det gick inte att ta bort uppgiften",+ runFailed: "Det gick inte att starta uppgiften",+ },+ toast: {+ finished: "”{title}” är klar",+ failed: "”{title}” misslyckades",+ many: "{count} schemalagda uppgifter är klara",+ open: "Öppna",+ view: "Visa",+ },+ notificationBody: "Din schemalagda uppgift är klar. Öppna Unsloth för att läsa svaret.",+ },library: {tabs: {ariaLabel: "Bibliotekssektioner",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 7620484183e..cc0e80ff8d0 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -762,6 +762,7 @@ export const zhCN = {images: "图像",video: "视频",audio: "音频",+ tasks: "定时任务",trainChecking: "正在检查此设备是否支持训练...",videoChecking: "正在检查此设备是否支持视频生成...",more: "更多",@@ -4181,6 +4182,103 @@ export const zhCN = {resetDescription: "每个技能都会恢复为全新安装时的状态:你的技能和 Claude 技能开启,内置技能关闭。你的开关选择将被清除。",reset: "重置",},+ scheduledTasks: {+ title: "定时任务",+ description: "使用已加载的模型按计划运行提示词。",+ newTask: "新建任务",+ upcoming: "即将运行",+ columns: {+ repeats: "重复",+ time: "时间",+ nextRun: "下次运行",+ },+ monthlyDay: "每月 {day} 日",+ filterBy: "筛选条件",+ filter: "筛选任务",+ active: "活跃",+ noMatches: "没有定时任务",+ search: "搜索定时任务",+ newResult: "新结果",+ sentBy: "由定时任务发送",+ chatMark: "来自定时任务的对话",+ taskMissing: "此任务已不存在。",+ emptyTitle: "还没有定时任务",+ emptyDescription: "每日摘要、每周提醒,或任何你想按计划完成的事情。",+ createFirst: "创建任务",+ loadFailed: "无法加载定时任务。",+ retry: "重试",+ paused: "已暂停",+ completed: "已完成",+ running: "运行中",+ lastRun: "上次运行:{when}",+ lastRunFailed: "上次运行失败({when}):{reason}",+ openChat: "打开聊天",+ runNow: "立即运行",+ pause: "暂停",+ resume: "恢复",+ edit: "编辑",+ options: "任务选项",+ schedule: {+ once: "仅一次,{date} {time}",+ daily: "每天 {time}",+ weekdays: "工作日 {time}",+ weekly: "每{days} {time}",+ monthly: "每月 {day} 日 {time}",+ },+ form: {+ createTitle: "安排任务",+ editTitle: "编辑定时任务",+ name: "名称",+ namePlaceholder: "名称(可选)",+ instructions: "指令",+ instructionsHint: "每次运行任务时都会发送给模型。",+ instructionsPlaceholder: "指令…",+ repeat: "重复",+ once: "仅一次",+ daily: "每天",+ weekdays: "工作日",+ weekly: "每周",+ monthly: "每月",+ date: "日期",+ time: "时间",+ days: "星期",+ dayOfMonth: "每月日期",+ lastDayNote: "没有这一天的月份会在最后一天运行。",+ advanced: "高级",+ notifications: "通知",+ notifyAll: "每次运行",+ notifyFailures: "仅失败时",+ notifyNone: "关闭",+ archiveSuccessful: "归档成功的运行",+ project: "项目",+ projectNone: "无",+ create: "创建",+ },+ deleteDialog: {+ title: "删除定时任务?",+ description: "“{title}”将不再运行。已创建的聊天会保留。",+ },+ errors: {+ noModel: "当时没有加载模型。请在聊天中加载模型,然后重新运行任务。",+ timeout: "模型回答用时过长。",+ cancelled: "运行在完成前被停止。",+ interrupted: "运行完成前 Unsloth 已关闭。",+ empty: "模型返回了空回答。",+ unknown: "运行失败。",+ saveFailed: "无法保存任务",+ updateFailed: "无法更新任务",+ deleteFailed: "无法删除任务",+ runFailed: "无法启动任务",+ },+ toast: {+ finished: "“{title}”已完成",+ failed: "“{title}”运行失败",+ many: "{count} 个定时任务已完成",+ open: "打开",+ view: "查看",+ },+ notificationBody: "你的定时任务已完成。打开 Unsloth 查看回答。",+ },library: {tabs: {ariaLabel: "资料库分区",diff --git a/studio/frontend/src/lib/account-transition.ts b/studio/frontend/src/lib/account-transition.tsindex c2026791195..ee0e533cfc3 100644--- a/studio/frontend/src/lib/account-transition.ts+++ b/studio/frontend/src/lib/account-transition.ts@@ -74,6 +74,11 @@ export const ACCOUNT_CHROME_KEYS = new Set([export const ACCOUNT_CHROME_PREFIXES = ["unsloth_web_update_dismissed:",] as const;+/** Per-account bookkeeping records kept across sign-ins; never content, credentials or cross-account data. */+export const ACCOUNT_KEYED_PREFIXES = [+ "unsloth_scheduled_tasks_seen:",+ "unsloth_scheduled_tasks_unseen:",+] as const;/** Per-tab flags about the browser session, not the account. Never add content. */export const ACCOUNT_SESSION_CHROME_KEYS = new Set([USER_STOPPED_KEY]);/** Purged on an account change. Durable stores are named per account (`accountDatabaseName`). */@@ -106,9 +111,8 @@ export function browserAccountMarker(account: BrowserAccount | string): string {: username;}-/** The owner keeps the historical name; a managed account gets its own store. */-export function accountDatabaseName(- name: string,+/** The account as `owner` or a managed account's id, never a reusable username alone where the id is known. */+export function browserAccountKey(storage: Pick<Storage, "getItem"> | null = typeof window === "undefined"? null: window.localStorage,@@ -116,9 +120,18 @@ export function accountDatabaseName(const account = parseAccountMarker(storage?.getItem(BROWSER_ACCOUNT_KEY) ?? OWNER_BROWSER_ACCOUNT,);- return isOwnerAccount(account)- ? name- : `${name}:${account.accountId ?? account.username}`;+ return isOwnerAccount(account) ? "owner" : (account.accountId ?? account.username);+}++/** The owner keeps the historical name; a managed account gets its own store. */+export function accountDatabaseName(+ name: string,+ storage: Pick<Storage, "getItem"> | null = typeof window === "undefined"+ ? null+ : window.localStorage,+): string {+ const account = browserAccountKey(storage);+ return account === "owner" ? name : `${name}:${account}`;}type MarkedAccount = { accountId: string | null; username: string };@@ -261,7 +274,8 @@ export async function transitionBrowserAccount(ACCOUNT_CHROME_KEYS.has(key) ||// About this machine's install, not the account signed in to it.key === RUNTIME_REPAIR_KEY ||- ACCOUNT_CHROME_PREFIXES.some((prefix) => key.startsWith(prefix))+ ACCOUNT_CHROME_PREFIXES.some((prefix) => key.startsWith(prefix)) ||+ ACCOUNT_KEYED_PREFIXES.some((prefix) => key.startsWith(prefix)))continue;if (key.startsWith("unsloth") || key.startsWith("chat-draft"))diff --git a/studio/frontend/src/lib/hugeicons-derived.ts b/studio/frontend/src/lib/hugeicons-derived.tsindex 1fa4e62db69..05655307da7 100644--- a/studio/frontend/src/lib/hugeicons-derived.ts+++ b/studio/frontend/src/lib/hugeicons-derived.ts@@ -109,3 +109,25 @@ export const TextToSpeechIcon: IconSvgElement = [},],];++/** `icon` with an accent dot; colours go in `style` because HugeiconsIcon overwrites child stroke attributes. */+export function withNoticeDot(icon: IconSvgElement): IconSvgElement {+ return [+ ...icon,+ [+ "circle",+ {+ cx: "19",+ cy: "5",+ r: "3.75",+ key: "notice-dot",+ style: {+ fill: "var(--primary)",+ stroke: "var(--icon-dot-ring, var(--sidebar))",+ strokeWidth: 2.5,+ paintOrder: "stroke",+ },+ },+ ],+ ] as unknown as IconSvgElement;+}diff --git a/studio/frontend/tests/account-transition.test.ts b/studio/frontend/tests/account-transition.test.tsindex cd180a5ee07..8c1000db41a 100644--- a/studio/frontend/tests/account-transition.test.ts+++ b/studio/frontend/tests/account-transition.test.ts@@ -6,9 +6,11 @@ import test from "node:test";import {ACCOUNT_CHROME_KEYS,ACCOUNT_DATABASES,+ ACCOUNT_KEYED_PREFIXES,BROWSER_ACCOUNT_FENCE_KEY,BROWSER_ACCOUNT_KEY,accountDatabaseName,+ browserAccountKey,accountTransitionPending,browserAccountMarker,installAccountTransitionListener,@@ -17,6 +19,7 @@ import {transitionBrowserAccount,} from "../src/lib/account-transition.ts";import { RUNTIME_REPAIR_KEY } from "../src/hooks/runtime-repair-history.ts";+import { SEEN_KEY_PREFIX, UNSEEN_KEY_PREFIX } from "../src/features/scheduled-tasks/results.ts";function browserWith(values: Record<string, string> = {},@@ -148,6 +151,8 @@ test("switch removes every content prefix and preserves only listed chrome and u...Object.fromEntries(content.map((key) => [key, "private"])),unrelated: "keep","unsloth_web_update_dismissed:pip:1": "keep",+ [`${SEEN_KEY_PREFIX}unsloth`]: "keep",+ [`${UNSEEN_KEY_PREFIX}unsloth`]: "keep",[BROWSER_ACCOUNT_KEY]: "unsloth",});const changed = await transitionBrowserAccount(@@ -166,6 +171,10 @@ test("switch removes every content prefix and preserves only listed chrome and uassert.equal(b.data.get(key), "chrome");assert.equal(b.data.get("unrelated"), "keep");assert.equal(b.data.get("unsloth_web_update_dismissed:pip:1"), "keep");+ for (const prefix of [SEEN_KEY_PREFIX, UNSEEN_KEY_PREFIX]) {+ assert.equal(b.data.get(`${prefix}unsloth`), "keep");+ assert.ok(ACCOUNT_KEYED_PREFIXES.some((kept) => prefix.startsWith(kept)));+ }assert.equal(b.data.get("unsloth_auth_token"), "alice-token");assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "alice");assert.deepEqual(b.replaced, ["/change-password"]);@@ -598,6 +607,16 @@ test("saved recipes live in a per-account store and are never purged", () => {);});+test("an account's key is its id where the marker has one, so a reused username starts afresh", () => {+ const stored = (marker: string | null) => ({ getItem: () => marker });+ assert.equal(browserAccountKey(stored(null)), "owner");+ assert.equal(browserAccountKey(stored("unsloth")), "owner");+ assert.equal(browserAccountKey(stored("account:owner:unsloth")), "owner");+ assert.equal(browserAccountKey(stored("account:a1:alice")), "a1");+ assert.equal(browserAccountKey(stored("account:a2:alice")), "a2");+ assert.equal(browserAccountKey(stored("alice")), "alice");+});+test("transcript recovery survives reauthentication but is cleared on account changes", async () => {const { readTranscriptDraft, transcriptDraftKey, writeTranscriptDraft } =await import("../src/features/audio/transcript-draft.ts");diff --git a/studio/frontend/tests/scheduled-tasks.test.ts b/studio/frontend/tests/scheduled-tasks.test.tsnew file mode 100644index 00000000000..f7d13382d48--- /dev/null+++ b/studio/frontend/tests/scheduled-tasks.test.ts@@ -0,0 +1,728 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import { loadWithStubs } from "./helpers/module-stubs.ts";+import * as formatFastApiError from "../src/lib/format-fastapi-error.ts";+import * as zustand from "zustand";+import type * as ScheduledTasksApi from "../src/features/scheduled-tasks/api.ts";+import type * as ScheduledTasksStore from "../src/features/scheduled-tasks/store.ts";+import type * as UnseenStore from "../src/features/scheduled-tasks/unseen.ts";+import {+ ACTIVE_POLL_MAX_MS,+ ACTIVE_POLL_MS,+ CATCH_UP_MS,+ HIDDEN_POLL_MS,+ IDLE_POLL_MS,+ advanceSeenRuns,+ claimAnnouncements,+ collectFinishedRuns,+ nextPollDelay,+ pollDelayFor,+ readSeenRuns,+ runErrorText,+ runsToAnnounce,+ runsToNotify,+ readInRecents,+ unseenChatChanges,+ shouldSaveSeen,+} from "../src/features/scheduled-tasks/results.ts";+import {+ type ScheduleSummary,+ type TaskSchedule,+ ISO_WEEKDAYS,+ defaultScheduleForm,+ formFromSchedule,+ formatRunDay,+ relativeTimeParts,+ sameSchedule,+ scheduleFormComplete,+ scheduleFromForm,+ summarizeRepeats,+ summarizeSchedule,+ timeChoices,+ titleFromPrompt,+ zoneLabel,+} from "../src/features/scheduled-tasks/schedule.ts";++const ISO_ALL = [...ISO_WEEKDAYS];++// ICU puts a narrow no-break space before AM/PM; compare the words, not the spacing.+function plain(summary: ScheduleSummary): ScheduleSummary {+ const values = Object.fromEntries(+ Object.entries(summary.values).map(([key, value]) => [+ key,+ typeof value === "string" ? value.replace(/\s/g, " ") : value,+ ]),+ );+ return { ...summary, values } as ScheduleSummary;+}++test("a new task runs every day at 09:00, and a one-time one starts tomorrow", () => {+ assert.deepEqual(defaultScheduleForm(new Date(2026, 9, 14, 16, 30)), {+ repeat: "daily",+ time: "09:00",+ date: "2026-10-15",+ days: [3],+ dayOfMonth: 14,+ });+ assert.equal(defaultScheduleForm(new Date(2026, 11, 31, 12)).date, "2027-01-01");+});++test("the form round-trips every kind of schedule", () => {+ const now = new Date(2026, 9, 14);+ const schedules: TaskSchedule[] = [+ { kind: "once", at: "2026-10-15T09:30" },+ { kind: "daily", time: "07:00" },+ { kind: "weekly", time: "18:00", days: [1, 2, 3, 4, 5] },+ { kind: "weekly", time: "18:00", days: [2, 6] },+ { kind: "monthly", time: "08:15", day: 31 },+ ];+ for (const schedule of schedules) {+ assert.deepEqual(scheduleFromForm(formFromSchedule(schedule, now)), schedule);+ }+});++test("Monday to Friday reads back as Weekdays, anything else as Weekly", () => {+ const now = new Date(2026, 9, 14);+ const weekdays = formFromSchedule({ kind: "weekly", time: "09:00", days: [1, 2, 3, 4, 5] }, now);+ const weekly = formFromSchedule({ kind: "weekly", time: "09:00", days: [1, 2, 3, 4] }, now);+ assert.equal(weekdays.repeat, "weekdays");+ assert.deepEqual([weekly.repeat, weekly.days], ["weekly", [1, 2, 3, 4]]);+});++test("weekly days are sent once each, in order", () => {+ const form = { ...defaultScheduleForm(new Date(2026, 9, 14)), repeat: "weekly" as const, days: [5, 1, 5] };+ assert.deepEqual(scheduleFromForm(form), { kind: "weekly", time: "09:00", days: [1, 5] });+});++test("an incomplete form cannot be saved", () => {+ const form = defaultScheduleForm(new Date(2026, 9, 14));+ assert.equal(scheduleFormComplete(form), true);+ assert.equal(scheduleFormComplete({ ...form, time: "" }), false);+ assert.equal(scheduleFormComplete({ ...form, time: "24:00" }), false);+ assert.equal(scheduleFormComplete({ ...form, repeat: "once", date: "" }), false);+ assert.equal(scheduleFormComplete({ ...form, repeat: "weekly", days: [] }), false);+ assert.equal(scheduleFormComplete({ ...form, repeat: "monthly", dayOfMonth: 32 }), false);+ assert.equal(scheduleFormComplete({ ...form, days: [], date: "" }), true);+});++test("schedules compare by what they mean", () => {+ assert.ok(+ sameSchedule(+ { kind: "weekly", time: "09:00", days: [1, 3] },+ { kind: "weekly", time: "09:00", days: [3, 1] },+ ),+ );+ assert.ok(!sameSchedule({ kind: "daily", time: "09:00" }, { kind: "daily", time: "09:01" }));+ assert.ok(+ !sameSchedule(+ { kind: "daily", time: "09:00" },+ { kind: "weekly", time: "09:00", days: [1, 2, 3, 4, 5, 6, 7] },+ ),+ );+ assert.ok(+ !sameSchedule(+ { kind: "monthly", time: "09:00", day: 1 },+ { kind: "monthly", time: "09:00", day: 2 },+ ),+ );+});++test("schedules are described in the user's locale", () => {+ assert.deepEqual(plain(summarizeSchedule({ kind: "daily", time: "21:05" }, "en-US")), {+ key: "daily",+ values: { time: "9:05 PM" },+ });+ assert.deepEqual(summarizeSchedule({ kind: "daily", time: "21:05" }, "de"), {+ key: "daily",+ values: { time: "21:05" },+ });+ assert.deepEqual(+ plain(summarizeSchedule({ kind: "weekly", time: "09:00", days: [1, 3, 5] }, "en-US")),+ { key: "weekly", values: { days: "Mon, Wed, and Fri", time: "9:00 AM" } },+ );+ assert.equal(+ summarizeSchedule({ kind: "weekly", time: "09:00", days: [1, 2, 3, 4, 5] }, "en-US").key,+ "weekdays",+ );+ assert.equal(+ summarizeSchedule({ kind: "weekly", time: "09:00", days: [1, 2, 3, 4, 5, 6, 7] }, "en-US").key,+ "daily",+ );+ assert.deepEqual(plain(summarizeSchedule({ kind: "once", at: "2026-10-15T09:00" }, "en-US")), {+ key: "once",+ values: { date: "Oct 15, 2026", time: "9:00 AM" },+ });+ assert.deepEqual(plain(summarizeSchedule({ kind: "monthly", time: "09:00", day: 31 }, "en-US")), {+ key: "monthly",+ values: { day: 31, time: "9:00 AM" },+ });+});++test("the Repeats column names the cadence without its time", () => {+ assert.deepEqual(summarizeRepeats({ kind: "daily", time: "09:00" }, "en-US"), { key: "daily" });+ assert.deepEqual(summarizeRepeats({ kind: "once", at: "2026-10-21T09:00" }, "en-US"), {+ key: "once",+ });+ assert.deepEqual(summarizeRepeats({ kind: "weekly", time: "09:00", days: ISO_ALL }, "en-US"), {+ key: "daily",+ });+ assert.deepEqual(+ summarizeRepeats({ kind: "weekly", time: "09:00", days: [1, 2, 3, 4, 5] }, "en-US"),+ { key: "weekdays" },+ );+ assert.deepEqual(summarizeRepeats({ kind: "weekly", time: "09:00", days: [1, 3, 5] }, "en-US"), {+ key: "weekly",+ days: "Mon, Wed, Fri",+ });+ assert.deepEqual(summarizeRepeats({ kind: "monthly", time: "09:00", day: 31 }, "en-US"), {+ key: "monthly",+ day: 31,+ });+});++test("a next run reads Today or Tomorrow, else its date", () => {+ const now = new Date(2026, 9, 20, 23, 30).getTime();+ assert.equal(formatRunDay(new Date(2026, 9, 20, 23, 45).getTime(), now, "en-US"), "Today");+ assert.equal(formatRunDay(new Date(2026, 9, 21, 0, 15).getTime(), now, "en-US"), "Tomorrow");+ assert.equal(formatRunDay(new Date(2026, 9, 21, 0, 15).getTime(), now, "de"), "Morgen");+ assert.equal(formatRunDay(new Date(2026, 9, 29, 9, 0).getTime(), now, "en-US"), "Thu, Oct 29");+});++test("the results poll looks quickly as a run starts, backs off while it goes on, and again just after one is due", () => {+ const going = { now: 0, activeRuns: 1, nextRunAt: null };+ assert.equal(nextPollDelay(going), ACTIVE_POLL_MS);+ assert.equal(nextPollDelay(going, ACTIVE_POLL_MS), 2 * ACTIVE_POLL_MS);+ assert.equal(nextPollDelay(going, ACTIVE_POLL_MAX_MS), ACTIVE_POLL_MAX_MS);+ assert.equal(nextPollDelay({ ...going, more: true }, ACTIVE_POLL_MAX_MS), ACTIVE_POLL_MS);+ assert.equal(nextPollDelay({ now: 0, activeRuns: 0, nextRunAt: null }), IDLE_POLL_MS);+ assert.equal(nextPollDelay({ now: 0, activeRuns: 0, nextRunAt: 60_000 }), 63_000);+ assert.equal(nextPollDelay({ now: 0, activeRuns: 0, nextRunAt: 1_000 }), 4_000);+ assert.equal(nextPollDelay({ now: 10_000, activeRuns: 0, nextRunAt: 0 }), ACTIVE_POLL_MS);+ assert.equal(nextPollDelay({ now: 0, activeRuns: 0, nextRunAt: 3_600_000 }), IDLE_POLL_MS);+ assert.equal(nextPollDelay({ now: 0, activeRuns: 0, nextRunAt: null, more: true }), ACTIVE_POLL_MS);+});++test("a hidden tab polls no faster than every 30 seconds, a shown one as paced", () => {+ assert.equal(pollDelayFor(ACTIVE_POLL_MS, true), HIDDEN_POLL_MS);+ assert.equal(pollDelayFor(ACTIVE_POLL_MS, false), ACTIVE_POLL_MS);+ assert.equal(pollDelayFor(IDLE_POLL_MS, true), IDLE_POLL_MS);+});++test("a poll that announced nothing writes the shared record only once its cursor moved a minute", () => {+ const stored = { since: 100_000, ids: ["a"] };+ assert.equal(shouldSaveSeen(stored, { since: 130_000, ids: ["a"] }, 0), false);+ assert.equal(shouldSaveSeen(stored, { since: 160_000, ids: ["a"] }, 0), true);+ assert.equal(shouldSaveSeen(stored, { since: 100_000, ids: ["a", "b"] }, 1), true);+ assert.equal(shouldSaveSeen(null, { since: 100_000, ids: [] }, 0), true);+});++test("a next run's day is counted in the task's zone, like its time", () => {+ // 00:15 on Oct 24 in New York is 21:15 on Oct 23 in Los Angeles.+ const at = Date.UTC(2026, 9, 24, 4, 15);+ const now = Date.UTC(2026, 9, 23, 20, 0);+ assert.equal(formatRunDay(at, now, "en-US", "America/New_York"), "Tomorrow");+ assert.equal(formatRunDay(at, now, "en-US", "America/Los_Angeles"), "Today");+});++test("formatters are kept per locale", () => {+ const at = new Date(2026, 9, 29, 9, 0).getTime();+ const now = new Date(2026, 9, 20, 9, 0).getTime();+ assert.equal(formatRunDay(at, now, "en-US"), "Thu, Oct 29");+ assert.notEqual(formatRunDay(at, now, "de-DE"), "Thu, Oct 29");+ assert.equal(formatRunDay(at, now, "en-US"), "Thu, Oct 29");+});++test("a saved record reads back as it was saved, with no clock of this browser's involved", () => {+ const stored = (since: unknown, ids: unknown = ["run-1"]) => JSON.stringify({ since, ids });+ assert.deepEqual(readSeenRuns(stored(5_000)), { since: 5_000, ids: ["run-1"] });+ assert.equal(readSeenRuns(null), null);+ assert.equal(readSeenRuns("not json"), null);+ assert.equal(readSeenRuns(JSON.stringify({ ids: [] })), null);+ assert.equal(readSeenRuns(stored("5000")), null);+ assert.deepEqual(readSeenRuns(stored(5_000, ["a", 7, null, "b"])), { since: 5_000, ids: ["a", "b"] });+ assert.deepEqual(readSeenRuns(JSON.stringify({ since: 5_000, ids: [], savedAt: 1 })), { since: 5_000, ids: [] });+ const seen = { since: 5_000, ids: ["a"] };+ assert.deepEqual(readSeenRuns(JSON.stringify(seen)), seen);+});++test("a record further behind the server than the catch-up window resumes from that window, by the server's clock", async () => {+ const now = 10 * CATCH_UP_MS;+ const oldest = now - CATCH_UP_MS;+ const runs = [finished("older", oldest - 60_000), finished("recent", oldest + 60_000)];+ const asked: (number | null)[] = [];+ const fetchAnswer = async (since: number | null) => {+ asked.push(since);+ const after = runs.filter((run) => since !== null && (run.finishedAt ?? 0) >= since);+ return { now, runs: after, more: false, activeRuns: 0, nextRunAt: null };+ };+ const resumed = await collectFinishedRuns({ since: now - 3 * CATCH_UP_MS, ids: [] }, fetchAnswer);+ assert.deepEqual(asked, [now - 3 * CATCH_UP_MS, oldest]);+ assert.deepEqual(resumed.fresh.map((run) => run.id), ["recent"]);+ assert.equal(resumed.seen.since, now - 60_000);+ asked.length = 0;+ const kept = await collectFinishedRuns({ since: oldest - 1 + 60_000, ids: [] }, fetchAnswer);+ assert.deepEqual(asked, [oldest - 1 + 60_000]);+ assert.deepEqual(kept.fresh.map((run) => run.id), ["recent"]);+});++test("the record moves on every poll, a minute behind the server, and remembers what it announced", () => {+ const answer = (now: number) => ({ now, runs: [], more: false });+ const first = advanceSeenRuns(null, answer(600_000), []);+ assert.deepEqual(first, { since: 540_000, ids: [] });+ const second = advanceSeenRuns(first, answer(900_000), ["run-1"]);+ assert.deepEqual(second, { since: 840_000, ids: ["run-1"] });+ assert.equal(advanceSeenRuns(second, answer(700_000), []).since, 840_000);+ const many = Array.from({ length: 260 }, (_, index) => `run-${index}`);+ const capped = advanceSeenRuns(second, answer(900_000), many).ids;+ assert.equal(capped.length, 200);+ assert.equal(capped.at(-1), "run-259");+});++function finished(id: string, finishedAt: number): ScheduledTasksApi.FinishedScheduledTaskRun {+ return {+ id,+ taskId: "task-1",+ source: "manual",+ status: "succeeded",+ scheduledFor: null,+ createdAt: finishedAt,+ startedAt: finishedAt,+ finishedAt,+ threadId: `chat-${id}`,+ model: null,+ errorCode: null,+ error: null,+ taskTitle: "Morning brief",+ taskNotify: "all",+ };+}++test("results past one answer are read a page at a time and announced once", async () => {+ const runs = [finished("a", 1_000), finished("b", 2_000), finished("c", 3_000)];+ const asked: (number | null)[] = [];+ const fetchAnswer = async (since: number | null) => {+ asked.push(since);+ const after = runs.filter((run) => since !== null && (run.finishedAt ?? 0) >= since);+ return { now: 100_000, runs: after.slice(0, 2), more: after.length > 2, activeRuns: 0, nextRunAt: null };+ };+ const { fresh, seen, last } = await collectFinishedRuns({ since: 0, ids: [] }, fetchAnswer);+ assert.deepEqual(asked, [0, 2_000]);+ assert.deepEqual(fresh.map((run) => run.id), ["a", "b", "c"]);+ assert.deepEqual(seen, { since: 40_000, ids: ["a", "b", "c"] });+ assert.equal(last.more, false);+});++test("a run that succeeded after its chat was deleted is not announced, least of all as failed", () => {+ const ready = finished("ready", 1_000);+ const gone = { ...finished("gone", 2_000), threadId: null };+ const failed = { ...finished("failed", 3_000), status: "failed" as const, threadId: null };+ assert.deepEqual(runsToAnnounce([ready, gone, failed]).map((run) => run.id), ["ready", "failed"]);+});++test("a task's toasts cover every run, only its failures, or none", () => {+ const ok = finished("ok", 1_000);+ const bad = { ...finished("bad", 2_000), status: "failed" as const, threadId: null };+ const notified = (taskNotify: ScheduledTasksApi.TaskNotify) =>+ runsToNotify([ok, bad].map((run) => ({ ...run, taskNotify }))).map((run) => run.id);+ assert.deepEqual(notified("all"), ["ok", "bad"]);+ assert.deepEqual(notified("failures"), ["bad"]);+ assert.deepEqual(notified("none"), []);+});++test("of an account's tabs, the first to claim a run announces it, and the record keeps the furthest cursor", () => {+ const fresh = [finished("a", 3_000), finished("b", 3_500)];+ const { mine, record } = claimAnnouncements({ since: 3_200, ids: ["a"] }, { since: 4_000, ids: ["a", "b"] }, fresh);+ assert.deepEqual(mine.map((run) => run.id), ["b"]);+ assert.deepEqual(record, { since: 4_000, ids: ["a", "b"] });+ const late = claimAnnouncements({ since: 3_200, ids: [] }, { since: 4_000, ids: [] }, fresh);+ assert.deepEqual(late.mine.map((run) => run.id), ["b"]);+ assert.equal(claimAnnouncements({ since: 5_000, ids: [] }, { since: 4_000, ids: [] }, fresh).record.since, 5_000);+ const first = claimAnnouncements(null, { since: 4_000, ids: [] }, fresh);+ assert.deepEqual(first.mine.map((run) => run.id), ["a", "b"]);+ assert.deepEqual(first.record, { since: 4_000, ids: ["a", "b"] });+});++test("a backlog longer than one poll reads is picked up again shortly", async () => {+ let pages = 0;+ const endless = async () => {+ pages += 1;+ return { now: 100_000, runs: [finished(`run-${pages}`, pages)], more: true, activeRuns: 0, nextRunAt: null };+ };+ const { fresh, seen, last } = await collectFinishedRuns(null, endless);+ assert.equal(pages, 10);+ assert.equal(fresh.length, 10);+ assert.equal(seen.since, 10);+ assert.equal(nextPollDelay(last), ACTIVE_POLL_MS);+});++test("unread chats follow the stored unread result chats", () => {+ assert.deepEqual(unseenChatChanges(["c1"], []), { added: ["c1"], opened: [] });+ assert.deepEqual(unseenChatChanges(["c1", "c2"], ["c1"]), { added: ["c2"], opened: [] });+ assert.deepEqual(unseenChatChanges(["c2"], ["c1", "c2"]), { added: [], opened: ["c1"] });+});++test("a result chat marked read in Recents is read for good, others untouched", () => {+ const before = new Set(["c1", "c2", "other"]);+ assert.deepEqual(readInRecents(["c1", "c2"], before, new Set(["c2", "other"])), ["c1"]);+ assert.deepEqual(readInRecents(["c1", "c2"], before, new Set()), ["c1", "c2"]);+ assert.deepEqual(readInRecents(["c3"], before, new Set()), []);+});++test("a failed run is worded from its error code, else from the server's text", () => {+ const t = (key: string) => `<${key}>`;+ assert.equal(+ runErrorText({ errorCode: "no_model", error: null }, t),+ "<scheduledTasks.errors.noModel>",+ );+ assert.equal(runErrorText({ errorCode: null, error: " Context full. " }, t), "Context full.");+ assert.equal(+ runErrorText({ errorCode: "something_new", error: null }, t),+ "<scheduledTasks.errors.unknown>",+ );+});++test("relative times use the largest whole unit", () => {+ assert.deepEqual(relativeTimeParts(0, 30_000), [-30, "second"]);+ assert.deepEqual(relativeTimeParts(0, 5 * 60_000), [-5, "minute"]);+ assert.deepEqual(relativeTimeParts(0, 2 * 3_600_000), [-2, "hour"]);+ assert.deepEqual(relativeTimeParts(3 * 86_400_000, 0), [3, "day"]);+});++function client(respond: (path: string, init?: RequestInit) => Response) {+ const requests: { method: string; path: string; body: unknown }[] = [];+ const api = loadWithStubs<typeof ScheduledTasksApi>(+ new URL("../src/features/scheduled-tasks/api.ts", import.meta.url),+ {+ "@/features/auth": {+ authFetch: async (path: string, init?: RequestInit) => {+ requests.push({+ method: init?.method ?? "GET",+ path,+ body: typeof init?.body === "string" ? JSON.parse(init.body) : undefined,+ });+ return respond(path, init);+ },+ getAuthSessionEpoch: () => 1,+ },+ "@/lib/format-fastapi-error": formatFastApiError,+ },+ );+ return { api, requests };+}++test("the client reaches every scheduled task route", async () => {+ const c = client((path, init) =>+ init?.method === "DELETE"+ ? new Response(null, { status: 204 })+ : Response.json(path === "/api/scheduled-tasks" && !init?.method ? { tasks: [], now: 7 } : {}),+ );+ const schedule: TaskSchedule = { kind: "daily", time: "09:00" };+ assert.deepEqual(await c.api.listScheduledTasks(), { tasks: [], now: 7 });+ await c.api.createScheduledTask({+ title: "Brief",+ prompt: "Hi",+ schedule,+ timezone: "UTC",+ notify: "failures",+ named: false,+ });+ await c.api.updateScheduledTask("a/b", { enabled: false });+ assert.equal(await c.api.deleteScheduledTask("t1"), undefined);+ await c.api.runScheduledTaskNow("t1");+ await c.api.getScheduledTaskActivity(null);+ await c.api.getScheduledTaskActivity(42);+ assert.deepEqual(+ c.requests.map(({ method, path }) => [method, path]),+ [+ ["GET", "/api/scheduled-tasks"],+ ["POST", "/api/scheduled-tasks"],+ ["PATCH", "/api/scheduled-tasks/a%2Fb"],+ ["DELETE", "/api/scheduled-tasks/t1"],+ ["POST", "/api/scheduled-tasks/t1/run"],+ ["GET", "/api/scheduled-tasks/runs"],+ ["GET", "/api/scheduled-tasks/runs?since=42"],+ ],+ );+ assert.deepEqual(c.requests[1].body, {+ title: "Brief",+ prompt: "Hi",+ schedule,+ timezone: "UTC",+ notify: "failures",+ named: false,+ });+ assert.deepEqual(c.requests[2].body, { enabled: false });+});++test("a task change reaches the account's other tabs, and a deletion has Recents look again", async () => {+ const globals = globalThis as Record<string, unknown>;+ const saved = { window: globals.window, localStorage: globals.localStorage };+ const stored = new Map<string, string>();+ globals.window = new EventTarget();+ globals.localStorage = { setItem: (key: string, value: string) => void stored.set(key, value) };+ let historyRefreshes = 0;+ try {+ const store = loadWithStubs<typeof ScheduledTasksStore>(+ new URL("../src/features/scheduled-tasks/store.ts", import.meta.url),+ {+ zustand,+ "@/features/auth": { AUTH_SESSION_CLEARED_EVENT: "signed-out", getAuthSessionEpoch: () => 1 },+ "@/features/chat": {+ notifyChatHistoryUpdated: () => {+ historyRefreshes += 1;+ },+ },+ "./api": { deleteScheduledTask: async () => undefined },+ "./results": {+ SCHEDULED_TASKS_CHANGED_EVENT: "changed",+ SCHEDULED_TASKS_WRITTEN_KEY: "written",+ SCHEDULED_TASK_RUNS_FINISHED_EVENT: "finished",+ },+ },+ );+ await store.useScheduledTasksStore.getState().remove("t1");+ const first = stored.get(store.SCHEDULED_TASKS_WRITTEN_KEY);+ assert.ok(first);+ assert.equal(historyRefreshes, 1);+ await store.useScheduledTasksStore.getState().remove("t2");+ assert.notEqual(stored.get(store.SCHEDULED_TASKS_WRITTEN_KEY), first);+ } finally {+ globals.window = saved.window;+ globals.localStorage = saved.localStorage;+ }+});++test("a Run now answer arriving after its run finished keeps the finished run", async () => {+ const globals = globalThis as Record<string, unknown>;+ const saved = { window: globals.window, localStorage: globals.localStorage };+ globals.window = new EventTarget();+ globals.localStorage = { setItem: () => undefined };+ try {+ let answer: (run: unknown) => void = () => undefined;+ const store = loadWithStubs<typeof ScheduledTasksStore>(+ new URL("../src/features/scheduled-tasks/store.ts", import.meta.url),+ {+ zustand,+ "@/features/auth": { AUTH_SESSION_CLEARED_EVENT: "signed-out", getAuthSessionEpoch: () => 1 },+ "@/features/chat": { notifyChatHistoryUpdated: () => undefined },+ "./api": { runScheduledTaskNow: () => new Promise((resolve) => (answer = resolve)) },+ "./results": {+ SCHEDULED_TASKS_CHANGED_EVENT: "changed",+ SCHEDULED_TASKS_WRITTEN_KEY: "written",+ SCHEDULED_TASK_RUNS_FINISHED_EVENT: "finished",+ },+ },+ );+ const tasks = store.useScheduledTasksStore;+ tasks.setState({ tasks: [{ id: "t1", lastRun: null } as never] });+ const pending = tasks.getState().runNow("t1");+ tasks.setState({+ tasks: [{ id: "t1", lastRun: { id: "r1", createdAt: 1, finishedAt: 2, status: "succeeded" } } as never],+ });+ answer({ id: "r1", createdAt: 1, finishedAt: null, status: "queued" });+ await pending;+ assert.equal(tasks.getState().tasks[0].lastRun?.status, "succeeded");+ } finally {+ globals.window = saved.window;+ globals.localStorage = saved.localStorage;+ }+});++test("an edit answer that predates its run's finish keeps the finished run", async () => {+ const globals = globalThis as Record<string, unknown>;+ const saved = { window: globals.window, localStorage: globals.localStorage };+ globals.window = new EventTarget();+ globals.localStorage = { setItem: () => undefined };+ try {+ let answer: (task: unknown) => void = () => undefined;+ const store = loadWithStubs<typeof ScheduledTasksStore>(+ new URL("../src/features/scheduled-tasks/store.ts", import.meta.url),+ {+ zustand,+ "@/features/auth": { AUTH_SESSION_CLEARED_EVENT: "signed-out", getAuthSessionEpoch: () => 1 },+ "@/features/chat": { notifyChatHistoryUpdated: () => undefined },+ "./api": { updateScheduledTask: () => new Promise((resolve) => (answer = resolve)) },+ "./results": {+ SCHEDULED_TASKS_CHANGED_EVENT: "changed",+ SCHEDULED_TASKS_WRITTEN_KEY: "written",+ SCHEDULED_TASK_RUNS_FINISHED_EVENT: "finished",+ },+ },+ );+ const tasks = store.useScheduledTasksStore;+ const run = { id: "r1", createdAt: 1, finishedAt: null, status: "running" };+ const pending = tasks.getState().update("t1", { title: "Renamed" });+ tasks.setState({+ tasks: [{ id: "t1", title: "Old", lastRun: { ...run, finishedAt: 2, status: "succeeded" } } as never],+ });+ answer({ id: "t1", title: "Renamed", lastRun: run });+ await pending;+ const [task] = tasks.getState().tasks;+ assert.equal(task.title, "Renamed");+ assert.equal(task.lastRun?.status, "succeeded");+ } finally {+ globals.window = saved.window;+ globals.localStorage = saved.localStorage;+ }+});++test("an edit answered after a refresh that landed meanwhile reads the list again", async () => {+ const globals = globalThis as Record<string, unknown>;+ const saved = { window: globals.window, localStorage: globals.localStorage };+ globals.window = new EventTarget();+ globals.localStorage = { setItem: () => undefined };+ try {+ let answer: (task: unknown) => void = () => undefined;+ let lists = 0;+ const completed = { id: "t1", title: "Old", status: "completed", nextRunAt: null, lastRun: null };+ const store = loadWithStubs<typeof ScheduledTasksStore>(+ new URL("../src/features/scheduled-tasks/store.ts", import.meta.url),+ {+ zustand,+ "@/features/auth": { AUTH_SESSION_CLEARED_EVENT: "signed-out", getAuthSessionEpoch: () => 1 },+ "@/features/chat": { notifyChatHistoryUpdated: () => undefined },+ "./api": {+ updateScheduledTask: () => new Promise((resolve) => (answer = resolve)),+ listScheduledTasks: async () => {+ lists += 1;+ return { tasks: [{ ...completed, title: lists > 1 ? "Renamed" : "Old" }], now: 0 };+ },+ },+ "./results": {+ SCHEDULED_TASKS_CHANGED_EVENT: "changed",+ SCHEDULED_TASKS_WRITTEN_KEY: "written",+ SCHEDULED_TASK_RUNS_FINISHED_EVENT: "finished",+ },+ },+ );+ const tasks = store.useScheduledTasksStore;+ const pending = tasks.getState().update("t1", { title: "Renamed" });+ // The once task is claimed and completes; a refresh sees it before the rename's answer arrives.+ await tasks.getState().refresh();+ answer({ ...completed, title: "Renamed", status: "active", nextRunAt: 5 });+ await pending;+ for (let i = 0; i < 5 && lists < 2; i += 1) await Promise.resolve();+ assert.equal(lists, 2);+ await new Promise((resolve) => setTimeout(resolve, 0));+ const [task] = tasks.getState().tasks;+ assert.equal(task.status, "completed");+ assert.equal(task.nextRunAt, null);+ } finally {+ globals.window = saved.window;+ globals.localStorage = saved.localStorage;+ }+});++test("every unopened result chat stays unread across reloads, and opening one clears only it", () => {+ const globals = globalThis as Record<string, unknown>;+ const saved = { window: globals.window, localStorage: globals.localStorage };+ const stored = new Map<string, string>();+ globals.window = new EventTarget();+ globals.localStorage = {+ getItem: (key: string) => stored.get(key) ?? null,+ setItem: (key: string, value: string) => void stored.set(key, value),+ };+ try {+ const load = () =>+ loadWithStubs<typeof UnseenStore>(new URL("../src/features/scheduled-tasks/unseen.ts", import.meta.url), {+ zustand,+ "@/features/auth": { AUTH_SESSION_CLEARED_EVENT: "out", AUTH_SESSION_STORED_EVENT: "in", getAuthToken: () => "t" },+ "@/lib/account-transition": { browserAccountKey: () => "owner" },+ "./results": { UNSEEN_KEY_PREFIX: "unseen:" },+ }).useUnseenScheduledRuns;+ const first = load();+ first.getState().markFinished([{ taskId: "t1", threadId: "c1" }], false);+ first.getState().markFinished([{ taskId: "t1", threadId: "c2" }], false);+ assert.deepEqual(load().getState().threads, ["c1", "c2"]);+ load().getState().clearThread("c1");+ assert.deepEqual(load().getState().threads, ["c2"]);+ } finally {+ globals.window = saved.window;+ globals.localStorage = saved.localStorage;+ }+});++test("a write that drops a list refresh in flight asks for the list again", async () => {+ const globals = globalThis as Record<string, unknown>;+ const saved = { window: globals.window, localStorage: globals.localStorage };+ globals.window = new EventTarget();+ globals.localStorage = { setItem: () => undefined };+ try {+ let lists = 0;+ let firstList: (list: unknown) => void = () => undefined;+ const store = loadWithStubs<typeof ScheduledTasksStore>(+ new URL("../src/features/scheduled-tasks/store.ts", import.meta.url),+ {+ zustand,+ "@/features/auth": { AUTH_SESSION_CLEARED_EVENT: "signed-out", getAuthSessionEpoch: () => 1 },+ "@/features/chat": { notifyChatHistoryUpdated: () => undefined },+ "./api": {+ listScheduledTasks: () => {+ lists += 1;+ if (lists === 1) return new Promise((resolve) => (firstList = resolve));+ return Promise.resolve({ tasks: [{ id: "t1", lastRun: { id: "r1", status: "succeeded" } }], now: 0 });+ },+ runScheduledTaskNow: async () => ({ id: "r1", createdAt: 1, finishedAt: null, status: "queued" }),+ },+ "./results": {+ SCHEDULED_TASKS_CHANGED_EVENT: "changed",+ SCHEDULED_TASKS_WRITTEN_KEY: "written",+ SCHEDULED_TASK_RUNS_FINISHED_EVENT: "finished",+ },+ },+ );+ const tasks = store.useScheduledTasksStore;+ const dropped = tasks.getState().refresh();+ await tasks.getState().runNow("t1");+ firstList({ tasks: [], now: 0 });+ await dropped;+ await new Promise((resolve) => setTimeout(resolve, 0));+ assert.equal(lists, 2);+ assert.equal(tasks.getState().tasks[0]?.lastRun?.status, "succeeded");+ } finally {+ globals.window = saved.window;+ globals.localStorage = saved.localStorage;+ }+});++test("a refused request carries the server's reason", async () => {+ const c = client(() => Response.json({ detail: "Pick a time in the future." }, { status: 400 }));+ await assert.rejects(c.api.updateScheduledTask("t1", { enabled: true }), {+ message: "Pick a time in the future.",+ });+});++test("times are offered every quarter hour, keeping a saved one that falls between", () => {+ const choices = timeChoices("09:00");+ assert.equal(choices.length, 96);+ assert.deepEqual(choices.slice(0, 3), ["00:00", "00:15", "00:30"]);+ assert.equal(choices.at(-1), "23:45");+ const kept = timeChoices("09:07");+ const nine = kept.indexOf("09:00");+ assert.deepEqual(kept.slice(nine, nine + 3), ["09:00", "09:07", "09:15"]);+ assert.equal(timeChoices("9am").length, 96);+});++test("a time's zone is named as briefly as the locale allows", () => {+ const at = Date.UTC(2026, 9, 17, 12);+ assert.equal(zoneLabel("America/Los_Angeles", "en-US", at), "PT");+ assert.equal(zoneLabel("Europe/Berlin", "de", at), "MEZ");+ assert.equal(zoneLabel("Europe/Istanbul", "en-US", at), "GMT+3");+ assert.equal(zoneLabel("UTC", "en-US", at), "UTC");+ assert.equal(zoneLabel("Nowhere/Special", "en-US", at), "Nowhere/Special");+});++test("a task left unnamed is named after its instructions' first line", () => {+ assert.equal(titleFromPrompt(" What's the weather today?\nIn Paris."), "What's the weather today?");+ assert.equal(titleFromPrompt("Summarize three\tpapers"), "Summarize three papers");+ const long = "Write a short upbeat note to start the day with three ideas for staying focused";+ const title = titleFromPrompt(long);+ assert.ok(title.endsWith("…") && title.length <= 61, title);+ assert.ok(long.startsWith(title.slice(0, -1)), "cut at a word, from the start");+ const emoji = titleFromPrompt(`Describe ${"\u{1F600}".repeat(70)}`);+ assert.ok(!/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(emoji), "no lone surrogate");+ assert.equal(Array.from(emoji).length, 61);+});diff --git a/studio/frontend/tests/sidebar-nav-migration.test.ts b/studio/frontend/tests/sidebar-nav-migration.test.tsindex 67f77195223..f6cb1291d17 100644--- a/studio/frontend/tests/sidebar-nav-migration.test.ts+++ b/studio/frontend/tests/sidebar-nav-migration.test.ts@@ -113,7 +113,7 @@ test("a customized version-5 sidebar keeps its order and only gains the rows add);assert.deepEqual(customization.sidebarNav.map((item) => item.id),- [...customizedV5.map((item) => item.id), "library", "audio"],+ [...customizedV5.map((item) => item.id), "library", "audio", "tasks"],);assert.equal(customization.sidebarNav.at(-1)?.pinned, false);});diff --git a/studio/frontend/tests/sidebar-row-actions.test.ts b/studio/frontend/tests/sidebar-row-actions.test.tsindex 0f84d02b1eb..83fdafdd2cf 100644--- a/studio/frontend/tests/sidebar-row-actions.test.ts+++ b/studio/frontend/tests/sidebar-row-actions.test.ts@@ -81,7 +81,7 @@ test("every chat row offers the pin without opening a menu", () => {test("a chat row reserves one gutter, whatever its state", () => {assert.match(APP_SIDEBAR,- /showWorkSpinner \? "pr-16" : hasUnreadActivity \|\| showForkMark \? "pr-9" : undefined,/,+ /showWorkSpinner \? "pr-16" : hasUnreadActivity \|\| showForkMark \? "pr-9" : showScheduledMark \? "pr-7" : undefined,/,);// The fork mark sits in the trailing column in grey, not inline after the title.assert.match(