From 6df60c0bbd3862b5a7af7a94be2d7a9c3c7290fb Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Fri, 6 Nov 2026 22:35:19 +0000 Subject: [PATCH 1/8] fix(backend): report LLM configuration errors instead of failing silently A hosted model with an empty API key now raises MissingModelCredentialsError (503) naming the model and operation. Settings writes raise ConfigSaveError with the reason, including a read-only ConfigMap hint. A config.yml without a models key no longer makes /api/admin/models return 500. Co-Authored-By: Claude Opus 5.5 --- backend/src/backend/config_loader.py | 39 +++++++-- .../src/backend/middleware/app_middleware.py | 28 +++++++ backend/src/backend/model_registry.py | 41 +++++++++- .../backend/services/memory/agent/pi_agent.py | 12 ++- backend/tests/test_llm_config_errors.py | 79 +++++++++++++++++++ 5 files changed, 190 insertions(+), 9 deletions(-) create mode 100644 backend/tests/test_llm_config_errors.py diff --git a/backend/src/backend/config_loader.py b/backend/src/backend/config_loader.py index 50bf3a38..33b78fc4 100644 --- a/backend/src/backend/config_loader.py +++ b/backend/src/backend/config_loader.py @@ -11,10 +11,27 @@ from pathlib import Path from typing import Optional -from omegaconf import DictConfig, OmegaConf +from omegaconf import DictConfig, ListConfig, OmegaConf logger = logging.getLogger(__name__) + +class ConfigSaveError(RuntimeError): + """A runtime settings change could not be written to config.yml.""" + + +def _save_failure(what: str, config_path: Path, error: Exception) -> ConfigSaveError: + if isinstance(error, OSError) and error.errno == 30: # EROFS + reason = ( + f"{config_path} is read-only. In Kubernetes it is usually mounted from a " + "ConfigMap; edit that ConfigMap (or give the config directory writable " + "storage) instead of using the Settings page." + ) + else: + reason = f"{type(error).__name__}: {error}" + return ConfigSaveError(f"Could not save {what}: {reason}") + + # Global config cache _config_cache: Optional[DictConfig] = None _config_warnings: tuple[str, ...] = () @@ -250,8 +267,9 @@ def save_config_section(section_path: str, values: dict) -> bool: return True except Exception as e: - logger.error(f"Error saving config section '{section_path}': {e}") - return False + error = _save_failure(f"config section '{section_path}'", config_path, e) + logger.error(str(error)) + raise error from e def _load_raw_config() -> DictConfig: @@ -277,7 +295,15 @@ def get_raw_models() -> list: note it excludes default-only models that live solely in defaults.yml. """ raw = _load_raw_config() - models = raw.get("models", []) or [] + models = raw.get("models") + # A config.yml without a ``models`` key yields None, not a ListConfig, and + # OmegaConf.to_container() rejects plain Python values. + if models is None: + return [] + if not isinstance(models, ListConfig): + raise ValueError( + f"config.yml 'models' must be a list, got {type(models).__name__}" + ) return OmegaConf.to_container(models, resolve=False) @@ -306,5 +332,6 @@ def save_models_list(models: list) -> bool: return True except Exception as e: - logger.error(f"Error saving models list: {e}") - return False + error = _save_failure("the models list", config_path, e) + logger.error(str(error)) + raise error from e diff --git a/backend/src/backend/middleware/app_middleware.py b/backend/src/backend/middleware/app_middleware.py index 58a4382c..f063c96c 100644 --- a/backend/src/backend/middleware/app_middleware.py +++ b/backend/src/backend/middleware/app_middleware.py @@ -17,6 +17,8 @@ from starlette.responses import Response from backend.app_config import get_app_config +from backend.config_loader import ConfigSaveError +from backend.model_registry import MissingModelCredentialsError logger = logging.getLogger(__name__) request_logger = logging.getLogger("api.requests") @@ -225,6 +227,32 @@ async def connection_exception_handler(request: Request, exc: ConnectionError): }, ) + @app.exception_handler(ConfigSaveError) + async def config_save_exception_handler(request: Request, exc: ConfigSaveError): + """A settings write failed; tell the caller why instead of a bare 500.""" + return JSONResponse( + status_code=500, + content={ + "detail": str(exc), + "error_type": "config_save_failure", + "error_category": "configuration", + }, + ) + + @app.exception_handler(MissingModelCredentialsError) + async def missing_credentials_exception_handler( + request: Request, exc: MissingModelCredentialsError + ): + """An LLM call was attempted against a hosted model with no API key.""" + return JSONResponse( + status_code=503, + content={ + "detail": str(exc), + "error_type": "missing_model_credentials", + "error_category": "configuration", + }, + ) + @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): """Handle HTTP exceptions with structured error response.""" diff --git a/backend/src/backend/model_registry.py b/backend/src/backend/model_registry.py index 9b8ff584..29e2b651 100644 --- a/backend/src/backend/model_registry.py +++ b/backend/src/backend/model_registry.py @@ -34,6 +34,37 @@ logger = logging.getLogger(__name__) + +class MissingModelCredentialsError(RuntimeError): + """A hosted model was selected but its API key is not configured.""" + + +def require_api_key( + api_key: Optional[str], + url: str, + model_name: str, + *, + operation: Optional[str] = None, +) -> str: + """Return ``api_key``, or raise when a hosted HTTPS endpoint has none. + + Local servers (llama.cpp, Ollama, Tailnet ASR) declare a placeholder such as + ``no-key``. A key that resolved to empty for an HTTPS URL means a hosted + provider whose environment variable is unset; calling it would only fail + later as an opaque 401 inside a background job. + """ + if api_key: + return api_key + if url.startswith("https://"): + used_by = f" (used by LLM operation '{operation}')" if operation else "" + raise MissingModelCredentialsError( + f"Model '{model_name}'{used_by} calls {url} but its api_key is empty. " + "Set the environment variable its api_key references in config, " + "or select a different model in Settings > AI Model Settings." + ) + return "" + + # Operations whose normal routing role is not the primary LLM. Keeping this policy # beside the resolver makes the effective route inspectable without teaching every # caller or diagnostic which default it should use. @@ -254,6 +285,12 @@ def resolved_url(self) -> str: return _with_scheme(discovered) return _with_scheme(self.discovery_default or "") + def require_api_key(self, operation: Optional[str] = None) -> str: + """Return the API key, or raise when a hosted endpoint has none.""" + return require_api_key( + self.api_key, self.resolved_url(), self.name, operation=operation + ) + @model_validator(mode="after") def validate_model(self) -> ModelDef: """Cross-field validation.""" @@ -319,6 +356,7 @@ class ResolvedLLMOperation(BaseModel): max_tokens: Optional[int] = None response_format: Optional[Dict[str, Any]] = None # {"type": "json_object"} or None reasoning_effort: Optional[str] = None # OpenAI reasoning models OR thinking models + operation: Optional[str] = None # llm_operations name, for actionable errors @property def reasoning_allowed(self) -> bool: @@ -433,7 +471,7 @@ def get_client(self, is_async: bool = False): Uses create_openai_client which handles Langfuse tracing. """ return create_openai_client( - api_key=self.model_def.api_key or "", + api_key=self.model_def.require_api_key(self.operation), base_url=self.model_def.resolved_url(), is_async=is_async, ) @@ -609,6 +647,7 @@ def get_llm_operation( max_tokens=int(max_tokens) if max_tokens is not None else None, response_format=response_format, reasoning_effort=reasoning_effort, + operation=name, ) def explain_llm_operation(self, name: str) -> Dict[str, Optional[str]]: diff --git a/backend/src/backend/services/memory/agent/pi_agent.py b/backend/src/backend/services/memory/agent/pi_agent.py index dc7f82a0..ba219d5a 100644 --- a/backend/src/backend/services/memory/agent/pi_agent.py +++ b/backend/src/backend/services/memory/agent/pi_agent.py @@ -26,7 +26,12 @@ from urllib.parse import unquote, urlsplit import backend.services.privacy as privacy -from backend.model_registry import AppModels, ResolvedLLMOperation, get_models_registry +from backend.model_registry import ( + AppModels, + ResolvedLLMOperation, + get_models_registry, + require_api_key, +) from backend.services.inference_artifacts import canonical_hash, persist_inference_run from ..session_write import WriteSourcePermissions @@ -452,7 +457,10 @@ def _resolve_pi_config( provider=_provider_slug(str(model_def.model_provider)), model=resolved.model_name, base_url=base_url, - api_key=resolved.api_key or "no-key", + api_key=require_api_key( + resolved.api_key, base_url, model_def.name, operation=operation + ) + or "no-key", thinking=_thinking_level(settings.get("thinking"), resolved), max_tokens=max_tokens, context_window=context_window, diff --git a/backend/tests/test_llm_config_errors.py b/backend/tests/test_llm_config_errors.py new file mode 100644 index 00000000..2ac8507e --- /dev/null +++ b/backend/tests/test_llm_config_errors.py @@ -0,0 +1,79 @@ +"""Misconfigured LLMs and unwritable settings must fail loudly, not silently.""" + +import os +from pathlib import Path + +import pytest + +from backend import config_loader +from backend.config_loader import ConfigSaveError, get_raw_models, save_config_section +from backend.model_registry import ( + AppModels, + LLMOperationConfig, + MissingModelCredentialsError, + ModelDef, +) + + +def _model(name: str, url: str, api_key) -> ModelDef: + return ModelDef( + name=name, + model_type="llm", + model_provider="openrouter", + api_family="openai", + model_name=name, + model_url=url, + api_key=api_key, + ) + + +def test_hosted_model_without_key_raises_when_client_is_built(): + hosted = _model("openrouter-qwen", "https://openrouter.ai/api/v1", "") + registry = AppModels( + defaults={"llm": hosted.name}, + models={hosted.name: hosted}, + llm_operations={"memory_write": LLMOperationConfig(model=hosted.name)}, + ) + + op = registry.get_llm_operation("memory_write") + + with pytest.raises(MissingModelCredentialsError) as error: + op.get_client(is_async=True) + assert "openrouter-qwen" in str(error.value) + assert "memory_write" in str(error.value) + + +def test_local_model_without_key_is_allowed(): + local = _model("local-llm", "http://llama-cpp-llm:8080/v1", "") + assert local.require_api_key() == "" + + +def test_hosted_model_with_key_returns_key(): + hosted = _model("openai", "https://api.openai.com/v1", "sk-test") + assert hosted.require_api_key() == "sk-test" + + +@pytest.fixture +def config_dir(tmp_path: Path, monkeypatch): + monkeypatch.setenv("CONFIG_DIR", str(tmp_path)) + yield tmp_path + config_loader._runtime_overrides.clear() + + +def test_raw_models_is_empty_when_config_has_no_models_key(config_dir: Path): + (config_dir / "config.yml").write_text("llm_operations: {}\n") + assert get_raw_models() == [] + + +def test_save_to_read_only_config_raises_actionable_error(config_dir: Path): + config_file = config_dir / "config.yml" + config_file.write_text("llm_operations: {}\n") + os.chmod(config_dir, 0o500) + os.chmod(config_file, 0o400) + try: + with pytest.raises(ConfigSaveError) as error: + save_config_section("llm_operations", {"memory_write": {"model": "x"}}) + finally: + os.chmod(config_dir, 0o700) + os.chmod(config_file, 0o600) + assert "llm_operations" in str(error.value) From 3c59e0bdabb055b613df3d52295eb648eb132c2e Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Fri, 6 Nov 2026 22:35:22 +0000 Subject: [PATCH 2/8] feat(timeline): make Immich optional and let a reconciliation be cancelled A deployment without Immich no longer waits for a photo backup before day reconciliation. A running or queued reconciliation can be cancelled from the Timeline page; the job is stopped, its dirty range is dismissed, and a new request can start. Co-Authored-By: Claude Opus 5.5 --- .../backend/controllers/queue_controller.py | 22 +++ backend/src/backend/models/timeline.py | 15 +- .../routers/modules/timeline_routes.py | 17 +++ .../src/backend/services/immich_discovery.py | 7 +- .../backend/services/timeline/dirty_ranges.py | 59 ++++++++ .../timeline/explicit_reconciliation.py | 64 ++++++++- backend/src/backend/workers/timeline_jobs.py | 2 +- backend/tests/test_explicit_reconciliation.py | 134 +++++++++++++++++- backend/tests/test_immich_discovery.py | 5 +- backend/webui/src/pages/Timeline.tsx | 19 ++- backend/webui/src/services/api.ts | 4 +- 11 files changed, 331 insertions(+), 17 deletions(-) diff --git a/backend/src/backend/controllers/queue_controller.py b/backend/src/backend/controllers/queue_controller.py index 9707b2fe..f0000521 100644 --- a/backend/src/backend/controllers/queue_controller.py +++ b/backend/src/backend/controllers/queue_controller.py @@ -18,6 +18,7 @@ from fastapi.responses import JSONResponse from rq import Queue, Retry, Worker +from rq.command import send_stop_job_command from rq.exceptions import NoSuchJobError from rq.job import Dependency, Job, JobStatus from rq.registry import DeferredJobRegistry, ScheduledJobRegistry @@ -927,6 +928,27 @@ def enqueue_explicit_timeline_reconciliation(request_id: str) -> Optional[str]: return job.id +def stop_explicit_timeline_reconciliation(job_id: str) -> str: + """Stop one explicit reconciliation job wherever it is in its lifecycle. + + A running job's work-horse is killed; a queued, scheduled, or retry-deferred job + is cancelled so RQ never starts it. Returns what was done, for the caller's log. + """ + + try: + job = Job.fetch(job_id, connection=redis_conn) + except NoSuchJobError: + return "missing" + status = get_job_status_from_rq(job) + if status == "started": + send_stop_job_command(redis_conn, job_id) + return "stopped" + if status in {"queued", "deferred", "scheduled"}: + job.cancel() + return "cancelled" + return status + + def start_streaming_jobs( session_id: str, user_id: str, diff --git a/backend/src/backend/models/timeline.py b/backend/src/backend/models/timeline.py index f94b6a12..37b86bfd 100644 --- a/backend/src/backend/models/timeline.py +++ b/backend/src/backend/models/timeline.py @@ -534,10 +534,19 @@ class DirtyEvidenceRangeResolution(BaseModel): """Append-only human resolution of one terminal reconciliation range.""" resolution_id: str = Field(default_factory=lambda: str(uuid.uuid4())) - action: Literal["dismissed"] = "dismissed" + action: Literal["dismissed", "cancelled"] = "dismissed" actor_user_id: str = Field(min_length=1) reason: str = Field(min_length=1, max_length=500) - prior_state: Literal["failed"] = "failed" + # A cancel can stop a range at any non-terminal stage, not only after failure. + prior_state: Literal[ + "failed", + "pending", + "authorized_pending", + "leased", + "waiting", + "awaiting_context", + "context_pending", + ] = "failed" created_at: datetime = Field(default_factory=utcnow) @@ -768,7 +777,7 @@ class TimelineReconciliationRequest(Document): user_id: str local_date: date timezone: str - state: Literal["blocked", "queued", "running", "completed", "failed"] + state: Literal["blocked", "queued", "running", "completed", "failed", "cancelled"] reason: Literal[ "assets_on_day", "later_asset_watermark", diff --git a/backend/src/backend/routers/modules/timeline_routes.py b/backend/src/backend/routers/modules/timeline_routes.py index 6f8dcf16..f0490df5 100644 --- a/backend/src/backend/routers/modules/timeline_routes.py +++ b/backend/src/backend/routers/modules/timeline_routes.py @@ -61,6 +61,7 @@ ) from backend.services.timeline.dirty_ranges import ( DirtyRangeDismissalError, + DirtyRangeLeaseLost, dismiss_failed_range, ) from backend.services.timeline.dispatch import enqueue_episode_detailed_summary @@ -74,6 +75,8 @@ infer_evidence_relations, ) from backend.services.timeline.explicit_reconciliation import ( + ReconciliationNotCancellable, + cancel_explicit_reconciliation, reconciliation_request_payload, request_explicit_reconciliation, ) @@ -563,6 +566,20 @@ async def reconcile_timeline_day( return {**reconciliation_request_payload(request), "created": created} +@router.post("/reconciliation/{request_id}/cancel") +async def cancel_reconciliation_request( + request_id: str, + user: User = Depends(current_active_user), +): + try: + request = await cancel_explicit_reconciliation(user=user, request_id=request_id) + except LookupError as error: + raise HTTPException(status_code=404, detail=str(error)) from error + except (ReconciliationNotCancellable, DirtyRangeLeaseLost) as error: + raise HTTPException(status_code=409, detail=str(error)) from error + return reconciliation_request_payload(request) + + @router.get("/reconciliation/{request_id}") async def get_reconciliation_request( request_id: str, diff --git a/backend/src/backend/services/immich_discovery.py b/backend/src/backend/services/immich_discovery.py index 2003a934..95cbcf5e 100644 --- a/backend/src/backend/services/immich_discovery.py +++ b/backend/src/backend/services/immich_discovery.py @@ -49,6 +49,10 @@ def _settings() -> tuple[str, str] | None: return (url, key) if url and key else None +def immich_configured() -> bool: + return _settings() is not None + + async def resolve_immich_user_id() -> str | None: """Chronicle user that owns imported Immich references. @@ -146,7 +150,8 @@ async def check_immich_day_readiness( checked_at = utcnow() settings = _settings() if settings is None: - return ImmichDayReadiness(False, "immich_unconfigured", 0, None, checked_at, []) + # Immich is optional. A deployment without it has no backup to wait for. + return ImmichDayReadiness(True, "immich_unconfigured", 0, None, checked_at, []) try: zone = ZoneInfo(timezone_name) except Exception as error: diff --git a/backend/src/backend/services/timeline/dirty_ranges.py b/backend/src/backend/services/timeline/dirty_ranges.py index f03eedfb..e7def028 100644 --- a/backend/src/backend/services/timeline/dirty_ranges.py +++ b/backend/src/backend/services/timeline/dirty_ranges.py @@ -1253,6 +1253,65 @@ async def dismiss_failed_range( ) +CANCELLABLE_RANGE_STATES = ( + "pending", + "authorized_pending", + "leased", + "waiting", + "awaiting_context", + "context_pending", +) + + +async def cancel_range( + dirty_range_id: str, *, user_id: str, reason: str +) -> Optional[DirtyEvidenceRange]: + """Take one owner-scoped, unfinished range out of scheduling. + + Clearing the lease fences a still-running attempt: its next lease-checked write + raises ``DirtyRangeLeaseLost`` instead of publishing. ``dismissed`` keeps the + recovery cron from re-dispatching it. Returns None when the range had already + reached a terminal state, so there was nothing to cancel. + """ + + existing = await DirtyEvidenceRange.find_one( + DirtyEvidenceRange.dirty_range_id == dirty_range_id, + DirtyEvidenceRange.user_id == user_id, + ) + if existing is None: + raise LookupError("reconciliation range not found") + if existing.state not in CANCELLABLE_RANGE_STATES: + return None + resolution = DirtyEvidenceRangeResolution( + action="cancelled", + actor_user_id=user_id, + reason=reason, + prior_state=existing.state, + ) + document = await DirtyEvidenceRange.get_pymongo_collection().find_one_and_update( + { + "dirty_range_id": dirty_range_id, + "user_id": user_id, + "state": existing.state, + }, + { + "$set": { + "state": "dismissed", + "lease_owner": None, + "lease_expires_at": None, + "updated_at": resolution.created_at, + }, + "$push": {"resolution_history": resolution.model_dump(mode="python")}, + }, + return_document=ReturnDocument.AFTER, + ) + if document is None: + raise DirtyRangeLeaseLost( + f"dirty range {dirty_range_id} changed state while being cancelled; retry" + ) + return DirtyEvidenceRange.model_validate(document) + + async def release_range_for_retry( dirty_range: DirtyEvidenceRange, error: str ) -> DirtyEvidenceRange: diff --git a/backend/src/backend/services/timeline/explicit_reconciliation.py b/backend/src/backend/services/timeline/explicit_reconciliation.py index 099f5880..1f44c1b8 100644 --- a/backend/src/backend/services/timeline/explicit_reconciliation.py +++ b/backend/src/backend/services/timeline/explicit_reconciliation.py @@ -14,12 +14,16 @@ ) from backend.services.immich_discovery import ( check_immich_day_readiness, + immich_configured, import_immich_day_candidates, resolve_immich_user_id, ) from backend.services.notifications import NotificationCommand, enqueue_notification from backend.services.redis_lock import distributed_lock -from backend.services.timeline.dirty_ranges import authorize_explicit_range +from backend.services.timeline.dirty_ranges import ( + authorize_explicit_range, + cancel_range, +) from backend.users import User # The readiness check can page through several Immich search windows before importing @@ -61,7 +65,7 @@ async def request_explicit_reconciliation( start, _ = day_bounds(local_date, timezone_name) if start >= utcnow(): raise ValueError("Cannot reconcile a future evidence interval") - if not skip_immich: + if not skip_immich and immich_configured(): immich_owner_id = await resolve_immich_user_id() if immich_owner_id != user_id: raise PermissionError( @@ -178,7 +182,8 @@ async def _request_explicit_reconciliation_locked( await request.save() return request, True - if not skip_immich: + # Importing also registers an Immich capture source, so skip it without Immich. + if not skip_immich and readiness.reason != "immich_unconfigured": await import_immich_day_candidates(user_id, readiness.target_assets) started_at, _ = day_bounds(local_date, timezone_name) ended_at = evidence_cutoff(request) @@ -205,6 +210,59 @@ async def _request_explicit_reconciliation_locked( return request, True +class ReconciliationNotCancellable(ValueError): + """The request already finished, so there is nothing to stop.""" + + +CANCELLABLE_REQUEST_STATES = ("queued", "running") + + +async def cancel_explicit_reconciliation( + *, user: User, request_id: str +) -> TimelineReconciliationRequest: + """Stop one queued or running day request so the day can be requested again. + + Order matters: the range is fenced first, so a worker that outlives the stop + command loses its lease rather than publishing; then the RQ job is stopped; the + request is marked last, because a still-active request is what blocks a retry. + """ + + user_id = str(user.id) + request = await TimelineReconciliationRequest.find_one( + TimelineReconciliationRequest.request_id == request_id, + TimelineReconciliationRequest.user_id == user_id, + ) + if request is None: + raise LookupError("Reconciliation request not found") + if request.state not in CANCELLABLE_REQUEST_STATES: + raise ReconciliationNotCancellable( + f"Only a queued or running reconciliation can be cancelled " + f"(state={request.state})" + ) + if request.dirty_range_id: + await cancel_range( + request.dirty_range_id, + user_id=user_id, + reason=f"Cancelled by user (request {request_id})", + ) + if request.job_id: + await asyncio.to_thread(_stop_job, request.job_id) + request.state = "cancelled" + request.last_error = "Cancelled by user" + request.updated_at = utcnow() + await request.save() + return request + + +def _stop_job(job_id: str) -> str: + # Lazy for the same worker-bootstrap reason as _queue_request. + from backend.controllers.queue_controller import ( + stop_explicit_timeline_reconciliation, + ) + + return stop_explicit_timeline_reconciliation(job_id) + + def _queue_request(request_id: str) -> str | None: # Lazy to avoid coupling the Timeline service import graph to worker bootstrap. from backend.controllers.queue_controller import ( diff --git a/backend/src/backend/workers/timeline_jobs.py b/backend/src/backend/workers/timeline_jobs.py index b343ae8e..f23d8243 100644 --- a/backend/src/backend/workers/timeline_jobs.py +++ b/backend/src/backend/workers/timeline_jobs.py @@ -87,7 +87,7 @@ async def explicit_reconciliation_job(request_id: str, *, redis_client=None) -> request = await TimelineReconciliationRequest.find_one({"request_id": request_id}) if request is None: return {"request_id": request_id, "state": "missing"} - if request.state in {"completed", "failed", "blocked"}: + if request.state in {"completed", "failed", "blocked", "cancelled"}: return {"request_id": request_id, "state": request.state} return await _run_explicit_reconciliation(request) diff --git a/backend/tests/test_explicit_reconciliation.py b/backend/tests/test_explicit_reconciliation.py index eadd14d6..41bf672a 100644 --- a/backend/tests/test_explicit_reconciliation.py +++ b/backend/tests/test_explicit_reconciliation.py @@ -93,7 +93,7 @@ async def test_blocked_request_never_imports_or_queues_work(requests_db, monkeyp explicit_reconciliation, "check_immich_day_readiness", lambda *_args: _async_value( - readiness(ready=False, reason="immich_unconfigured") + readiness(ready=False, reason="immich_unreachable") ), ) imported = queued = 0 @@ -119,11 +119,55 @@ def queue_request(*_args): assert created is True assert request.state == "blocked" - assert request.reason == "immich_unconfigured" + assert request.reason == "immich_unreachable" assert imported == 0 assert queued == 0 +@pytest.mark.asyncio +async def test_unconfigured_immich_queues_any_user_without_import( + requests_db, monkeypatch +): + monkeypatch.setattr(explicit_reconciliation, "immich_configured", lambda: False) + monkeypatch.setattr( + explicit_reconciliation, + "check_immich_day_readiness", + lambda *_args: _async_value( + readiness(ready=True, reason="immich_unconfigured") + ), + ) + imported = 0 + + async def import_candidates(*_args): + nonlocal imported + imported += 1 + + async def not_called(): + raise AssertionError("Immich ownership does not apply without Immich") + + async def authorize(**_kwargs): + return SimpleNamespace(dirty_range_id="range-one") + + monkeypatch.setattr( + explicit_reconciliation, "import_immich_day_candidates", import_candidates + ) + monkeypatch.setattr(explicit_reconciliation, "resolve_immich_user_id", not_called) + monkeypatch.setattr(explicit_reconciliation, "authorize_explicit_range", authorize) + monkeypatch.setattr(explicit_reconciliation, "_queue_request", lambda *_args: "job") + + request, created = await explicit_reconciliation.request_explicit_reconciliation( + user=SimpleNamespace(id="not-the-admin"), + local_date=date(2026, 8, 15), + timezone_name="Asia/Kolkata", + ) + + assert created is True + assert request.state == "queued" + assert request.reason == "immich_unconfigured" + assert request.job_id == "job" + assert imported == 0 + + @pytest.mark.asyncio async def test_user_can_explicitly_reconcile_without_immich(requests_db, monkeypatch): checked = imported = 0 @@ -312,7 +356,7 @@ async def local_lock(*_args, **_kwargs): async def check(*_args): nonlocal checks checks += 1 - return readiness(ready=False, reason="immich_unconfigured") + return readiness(ready=False, reason="immich_unreachable") monkeypatch.setattr(explicit_reconciliation, "distributed_lock", local_lock) monkeypatch.setattr(explicit_reconciliation, "check_immich_day_readiness", check) @@ -335,6 +379,7 @@ async def check(*_args): @pytest.mark.asyncio async def test_non_owner_cannot_query_or_import_immich(requests_db, monkeypatch): + monkeypatch.setattr(explicit_reconciliation, "immich_configured", lambda: True) monkeypatch.setattr( explicit_reconciliation, "resolve_immich_user_id", @@ -696,3 +741,86 @@ def test_enqueue_keeps_running_retry_with_previous_ended_at(monkeypatch, status) queue_controller.enqueue_explicit_timeline_reconciliation("request") == "live-retry" ) + + +@pytest.mark.asyncio +async def test_cancel_stops_job_dismisses_range_and_allows_a_new_request( + requests_db, monkeypatch +): + stopped = [] + monkeypatch.setattr(explicit_reconciliation, "_queue_request", lambda _id: "job") + monkeypatch.setattr(explicit_reconciliation, "_stop_job", stopped.append) + user = SimpleNamespace(id="user") + day = date(2026, 8, 15) + + first, _ = await explicit_reconciliation.request_explicit_reconciliation( + user=user, local_date=day, timezone_name="Asia/Kolkata", skip_immich=True + ) + cancelled = await explicit_reconciliation.cancel_explicit_reconciliation( + user=user, request_id=first.request_id + ) + + assert cancelled.state == "cancelled" + assert stopped == ["job"] + dirty_range = await DirtyEvidenceRange.find_one( + DirtyEvidenceRange.dirty_range_id == first.dirty_range_id + ) + assert dirty_range.state == "dismissed" + assert dirty_range.lease_owner is None + assert dirty_range.resolution_history[-1].action == "cancelled" + assert dirty_range.resolution_history[-1].prior_state == "authorized_pending" + + # The cancelled request no longer pins the day: asking again starts fresh. + second, created = await explicit_reconciliation.request_explicit_reconciliation( + user=user, local_date=day, timezone_name="Asia/Kolkata", skip_immich=True + ) + assert created is True + assert second.request_id != first.request_id + + # The worker entrypoint refuses to run a cancelled request. + result = await timeline_jobs.explicit_reconciliation_job.__wrapped__( + first.request_id + ) + assert result == {"request_id": first.request_id, "state": "cancelled"} + + +@pytest.mark.asyncio +async def test_finished_request_cannot_be_cancelled(requests_db): + request = TimelineReconciliationRequest( + user_id="user", + local_date=date(2026, 8, 15), + timezone="Asia/Kolkata", + state="completed", + reason="user_bypassed_immich", + ) + await request.insert() + + with pytest.raises(explicit_reconciliation.ReconciliationNotCancellable): + await explicit_reconciliation.cancel_explicit_reconciliation( + user=SimpleNamespace(id="user"), request_id=request.request_id + ) + with pytest.raises(LookupError): + await explicit_reconciliation.cancel_explicit_reconciliation( + user=SimpleNamespace(id="someone-else"), request_id=request.request_id + ) + + +@pytest.mark.parametrize( + ("status", "expected"), + [("started", "stopped"), ("queued", "cancelled"), ("scheduled", "cancelled")], +) +def test_stop_job_kills_running_and_cancels_pending(monkeypatch, status, expected): + calls = [] + job = SimpleNamespace( + id="timeline-explicit_x", cancel=lambda: calls.append("cancel") + ) + monkeypatch.setattr(queue_controller.Job, "fetch", lambda *_a, **_k: job) + monkeypatch.setattr(queue_controller, "get_job_status_from_rq", lambda _j: status) + monkeypatch.setattr( + queue_controller, + "send_stop_job_command", + lambda _conn, job_id: calls.append(("stop", job_id)), + ) + + assert queue_controller.stop_explicit_timeline_reconciliation(job.id) == expected + assert calls == ([("stop", job.id)] if status == "started" else ["cancel"]) diff --git a/backend/tests/test_immich_discovery.py b/backend/tests/test_immich_discovery.py index 11f440b8..c2940a34 100644 --- a/backend/tests/test_immich_discovery.py +++ b/backend/tests/test_immich_discovery.py @@ -241,15 +241,16 @@ async def test_external_library_assets_do_not_satisfy_gate(monkeypatch): @pytest.mark.asyncio -async def test_unconfigured_immich_blocks_without_network(monkeypatch): +async def test_unconfigured_immich_is_ready_without_network(monkeypatch): monkeypatch.setattr(immich_discovery, "_settings", lambda: None) result = await immich_discovery.check_immich_day_readiness( date(2026, 8, 15), "Asia/Kolkata" ) - assert result.ready is False + assert result.ready is True assert result.reason == "immich_unconfigured" + assert result.target_assets == [] @pytest.mark.asyncio diff --git a/backend/webui/src/pages/Timeline.tsx b/backend/webui/src/pages/Timeline.tsx index 2de34764..b02f8c51 100644 --- a/backend/webui/src/pages/Timeline.tsx +++ b/backend/webui/src/pages/Timeline.tsx @@ -42,7 +42,7 @@ function readinessMessage(request?: TimelineReconciliationRequest) { if (reason === 'later_asset_watermark') return `Immich contains an eligible asset captured on ${watermark}, after this day.` if (reason === 'no_immich_evidence') return 'No eligible Immich evidence is available for this interval yet. Open Immich, back up photos up to the cutoff below, then check again.' if (reason === 'user_bypassed_immich') return 'Continuing without Immich evidence at your request.' - if (reason === 'immich_unconfigured') return 'Immich is not configured for Chronicle, so reconciliation cannot start.' + if (reason === 'immich_unconfigured') return 'Immich is not configured, so this analysis uses your other evidence.' return 'Chronicle could not reach Immich. Reconciliation did not start.' } @@ -208,6 +208,13 @@ export default function Timeline() { setReconciliationRequestId(request.request_id) }, }) + const cancelReconciliation = useMutation({ + mutationFn: async (requestId: string) => (await timelineApi.cancelReconciliation(requestId)).data, + onSuccess: request => { + queryClient.setQueryData(['timeline-reconciliation', request.request_id], request) + void queryClient.invalidateQueries({ queryKey: ['semantic-timeline', day, timezone] }) + }, + }) const reconciliation = useQuery({ queryKey: ['timeline-reconciliation', reconciliationRequestId], queryFn: async () => (await timelineApi.getReconciliation(reconciliationRequestId!)).data, @@ -353,7 +360,7 @@ export default function Timeline() { {(reconciliationStatus.state === 'blocked' || reconciliationStatus.state === 'failed') && } Reconciliation {reconciliationStatus.state}{reconciliationStatus.state === 'completed' && ` through ${new Date(reconciliationStatus.evidence_cutoff).toLocaleString('en-IN', { timeZone: timezone })} (${timezone})`} - {reconciliationStatus.state !== 'completed' &&

{readinessMessage(reconciliationStatus)}

} + {reconciliationStatus.state !== 'completed' && reconciliationStatus.state !== 'cancelled' &&

{readinessMessage(reconciliationStatus)}

}

{reconciliationStatus.state === 'completed' ? 'Later evidence is not included.' : `Evidence cutoff: ${new Date(reconciliationStatus.evidence_cutoff).toLocaleString('en-IN', { timeZone: timezone })} (${timezone}).`}

Evidence details @@ -377,7 +384,13 @@ export default function Timeline() {
{reconciliationStatus.state === 'blocked' && reconciliationStatus.notification_id &&

Backup reminder: {reconciliationStatus.notification_status || 'queued'}

} {reconciliationStatus.last_error &&

{reconciliationStatus.last_error}

} - {(reconciliationStatus.state === 'blocked' || reconciliationStatus.state === 'failed') && ( + {(reconciliationStatus.state === 'queued' || reconciliationStatus.state === 'running') && ( +
+ + {cancelReconciliation.isError && {(cancelReconciliation.error as { response?: { data?: { detail?: string } } })?.response?.data?.detail || 'Cancel failed'}} +
+ )} + {(reconciliationStatus.state === 'blocked' || reconciliationStatus.state === 'failed' || reconciliationStatus.state === 'cancelled') && (
{reconciliationStatus.state === 'blocked' && reconciliationStatus.reason === 'no_immich_evidence' && } diff --git a/backend/webui/src/services/api.ts b/backend/webui/src/services/api.ts index f6d91182..f2d8937d 100644 --- a/backend/webui/src/services/api.ts +++ b/backend/webui/src/services/api.ts @@ -775,7 +775,7 @@ export interface TimelineReconciliationRequest { request_id: string date: string timezone: string - state: 'blocked' | 'queued' | 'running' | 'completed' | 'failed' + state: 'blocked' | 'queued' | 'running' | 'completed' | 'failed' | 'cancelled' reason: 'assets_on_day' | 'later_asset_watermark' | 'no_immich_evidence' | 'immich_unconfigured' | 'immich_unreachable' | 'user_bypassed_immich' target_asset_count: number latest_eligible_asset_date: string | null @@ -852,6 +852,8 @@ export const timelineApi = { api.post(`/api/timeline/reconciliation/day/${date}`, { timezone, skip_immich: skipImmich }), getReconciliation: (requestId: string) => api.get(`/api/timeline/reconciliation/${requestId}`), + cancelReconciliation: (requestId: string) => + api.post(`/api/timeline/reconciliation/${requestId}/cancel`), dismissFailedRange: (dirtyRangeId: string, reason: string) => api.post(`/api/timeline/reconciliation/ranges/${encodeURIComponent(dirtyRangeId)}/dismiss`, { reason }), getAnalysis: (runId: string) => From 67acc0bd482f146c9f66b053244fa0e9de284b8f Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Sat, 7 Nov 2026 11:07:18 +0000 Subject: [PATCH 3/8] fix(transcription): end a stream cleanly when the provider already closed it Deepgram closes an idle stream (NET-0001) after ~10 s without audio. When the session then ended, end_stream sent CloseStream on the dead socket, raised ConnectionClosedError, and never removed the stream entry. It now unregisters the stream first and logs one warning for an already-closed socket instead of raising. Co-Authored-By: Claude Opus 5.5 --- .../services/transcription/__init__.py | 29 +++++++---- .../tests/test_streaming_end_stream_closed.py | 52 +++++++++++++++++++ 2 files changed, 72 insertions(+), 9 deletions(-) create mode 100644 backend/tests/test_streaming_end_stream_closed.py diff --git a/backend/src/backend/services/transcription/__init__.py b/backend/src/backend/services/transcription/__init__.py index cd9585df..3d4ddce5 100644 --- a/backend/src/backend/services/transcription/__init__.py +++ b/backend/src/backend/services/transcription/__init__.py @@ -944,16 +944,29 @@ async def process_audio_chunk( return None async def end_stream(self, stream_id: str) -> dict: - if stream_id not in self._streams: + # Unregister first so no exit path below can leak the stream entry. + stream = self._streams.pop(stream_id, None) + if stream is None: return {"text": "", "words": [], "segments": []} - ws = self._streams[stream_id]["ws"] + ws = stream["ws"] ops = self.model.operations or {} - pending = self._streams[stream_id].get("pending_audio") - if pending: - await ws.send(bytes(pending)) - pending.clear() + pending = stream.get("pending_audio") end_msg = (ops.get("end", {}) or {}).get("message", {"type": "stop"}) - await ws.send(json.dumps(end_msg)) + try: + if pending: + await ws.send(bytes(pending)) + pending.clear() + await ws.send(json.dumps(end_msg)) + except websockets.exceptions.ConnectionClosed as e: + # The provider already closed the socket, e.g. Deepgram's idle + # timeout (NET-0001) after ~10 s without audio. Finals that arrived + # before the close were already published; nothing is left to flush. + logger.warning( + f"Provider closed stream {stream_id} before it ended " + f"(code={e.rcvd.code if e.rcvd else None}, " + f"reason={e.rcvd.reason if e.rcvd else ''})" + ) + return {"text": "", "words": [], "segments": []} expect = ops.get("expect", {}) or {} final_type = expect.get("final_type") @@ -978,8 +991,6 @@ async def end_stream(self, stream_id: str) -> dict: except Exception: pass - self._streams.pop(stream_id, None) - if not isinstance(final, dict): return {"text": "", "words": [], "segments": []} segments = ( diff --git a/backend/tests/test_streaming_end_stream_closed.py b/backend/tests/test_streaming_end_stream_closed.py new file mode 100644 index 00000000..b8a57cb7 --- /dev/null +++ b/backend/tests/test_streaming_end_stream_closed.py @@ -0,0 +1,52 @@ +"""Ending a stream whose provider socket already closed. + +Deepgram closes an idle stream (NET-0001) after about 10 seconds without audio. +When the session then ends, the CloseStream send hits a dead socket. That must +end the stream cleanly, not raise and leave the stream registered. +""" + +import pytest +from websockets.exceptions import ConnectionClosedError +from websockets.frames import Close + +from backend.services.transcription import RegistryStreamingTranscriptionProvider + +IDLE_CLOSE = Close( + 1011, "Deepgram did not receive audio data within the timeout window." +) + + +class ClosedSocket: + def __init__(self): + self.closed_called = False + + async def send(self, _payload): + raise ConnectionClosedError(IDLE_CLOSE, IDLE_CLOSE, rcvd_then_sent=True) + + async def recv(self): + raise ConnectionClosedError(IDLE_CLOSE, IDLE_CLOSE, rcvd_then_sent=True) + + async def close(self): + self.closed_called = True + + +def _provider_with(ws, pending=b""): + provider = object.__new__(RegistryStreamingTranscriptionProvider) + provider.model = type( + "Model", (), {"operations": {"end": {"message": {"type": "CloseStream"}}}} + )() + provider._streams = {"s1": {"ws": ws, "pending_audio": bytearray(pending)}} + return provider + + +@pytest.mark.parametrize("pending", [b"", b"\x00" * 64]) +async def test_end_stream_on_provider_closed_socket_returns_empty_and_unregisters( + pending, +): + ws = ClosedSocket() + provider = _provider_with(ws, pending) + + result = await provider.end_stream("s1") + + assert result == {"text": "", "words": [], "segments": []} + assert "s1" not in provider._streams From 062e97c8405ba9931dba1c613646b1deb0ab3ed0 Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Sat, 7 Nov 2026 11:47:34 +0000 Subject: [PATCH 4/8] feat(webui): show timestamps in the user's timezone instead of IST Timestamps across the WebUI and the services CLI were hard-coded to Asia/Kolkata. Add one display-timezone authority (utils/datetime.ts) and a component. The zone follows the user's saved timezone, falling back to the browser's, and updates when the Timeline saves a new zone. - formatDateTime/formatTime/formatDate replace per-page toLocaleString calls; PRECISE_* presets keep seconds on queue, audit and log views - recording context and chat source refs send the display zone, not IST - CLI operation stamps use the host's local zone Co-Authored-By: Claude Opus 5.5 --- .../components/AutomationSettings.test.tsx | 10 ++- .../src/components/AutomationSettings.tsx | 6 +- .../webui/src/components/ChatRunViewer.tsx | 7 +- backend/webui/src/components/DateTime.tsx | 27 ++++++ .../src/components/RecordingMemoryContext.tsx | 30 +++---- .../webui/src/components/SourceResults.tsx | 15 +--- .../src/components/VoiceLatencyReport.tsx | 3 +- .../webui/src/components/dataAudit/format.ts | 3 +- .../timeline/SessionMemoryBoard.tsx | 5 +- backend/webui/src/contexts/AuthContext.tsx | 4 + .../webui/src/hooks/useTimelineTimezone.ts | 2 + backend/webui/src/pages/Chat.tsx | 11 +-- backend/webui/src/pages/Finetuning.tsx | 3 +- .../webui/src/pages/MemorySpaceWorkspace.tsx | 3 +- backend/webui/src/pages/Network.tsx | 5 +- .../src/pages/OperationalClarity.test.tsx | 8 +- backend/webui/src/pages/Queue.tsx | 29 +++--- backend/webui/src/pages/RecordingDetail.tsx | 5 +- backend/webui/src/pages/Recordings.tsx | 7 +- backend/webui/src/pages/System.tsx | 3 +- backend/webui/src/pages/SystemEvents.tsx | 24 ++--- backend/webui/src/pages/WakeWordLab.tsx | 3 +- backend/webui/src/utils/datetime.test.ts | 36 ++++++++ backend/webui/src/utils/datetime.ts | 88 +++++++++++++++++++ docs/init-system.md | 2 +- service_cli.py | 10 ++- 26 files changed, 247 insertions(+), 102 deletions(-) create mode 100644 backend/webui/src/components/DateTime.tsx create mode 100644 backend/webui/src/utils/datetime.test.ts create mode 100644 backend/webui/src/utils/datetime.ts diff --git a/backend/webui/src/components/AutomationSettings.test.tsx b/backend/webui/src/components/AutomationSettings.test.tsx index c2a14239..96887b40 100644 --- a/backend/webui/src/components/AutomationSettings.test.tsx +++ b/backend/webui/src/components/AutomationSettings.test.tsx @@ -3,17 +3,19 @@ import '@testing-library/jest-dom/vitest' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import AutomationSettings from './AutomationSettings' +import { formatDateTime, setDisplayTimezone } from '../utils/datetime' const state = vi.hoisted(() => ({ next: '2026-09-14T04:30:00+00:00' as string | null, update: vi.fn() })) vi.mock('../hooks/useFinetuning', () => ({ useCronJobs: () => ({ data: [{ job_id: 'daily', description: '', enabled: true, schedule: '30 4 * * *', last_run: null, next_run: state.next }], isLoading: false, refetch: vi.fn() }), useToggleCronJob: () => ({ mutateAsync: vi.fn() }), useRunCronJob: () => ({ mutateAsync: vi.fn() }), useUpdateCronSchedule: () => ({ mutateAsync: state.update }), })) -beforeEach(() => { state.next = '2026-09-14T04:30:00+00:00'; state.update.mockReset().mockResolvedValue({}) }) -afterEach(cleanup) -it('shows the UTC next-run instant in IST while preserving the UTC expression when edited', async () => { +beforeEach(() => { setDisplayTimezone('Asia/Kolkata'); state.next = '2026-09-14T04:30:00+00:00'; state.update.mockReset().mockResolvedValue({}) }) +afterEach(() => { cleanup(); setDisplayTimezone(null) }) +it('shows the UTC next-run instant in the display timezone while preserving the UTC expression when edited', async () => { render() - expect(screen.getByText(/Next:/)).toHaveTextContent(/10:00 am IST/i) + expect(screen.getByText(/Next:/)).toHaveTextContent(formatDateTime('2026-09-14T04:30:00Z')) + expect(screen.getByText(/Next:/)).toHaveTextContent(/10:00/) fireEvent.click(screen.getByText('Schedule and last run')) expect(screen.getByText(/At 04:30 AM/)).toHaveTextContent('(UTC)') fireEvent.click(screen.getByRole('button', { name: 'Edit schedule' })) diff --git a/backend/webui/src/components/AutomationSettings.tsx b/backend/webui/src/components/AutomationSettings.tsx index fbd39fb6..27479af8 100644 --- a/backend/webui/src/components/AutomationSettings.tsx +++ b/backend/webui/src/components/AutomationSettings.tsx @@ -3,6 +3,7 @@ import { Clock, ToggleLeft, ToggleRight, Edit3, Check, X, Play, RefreshCw, Eye } import cronstrue from 'cronstrue' import { useCronJobs, useToggleCronJob, useUpdateCronSchedule, useRunCronJob } from '../hooks/useFinetuning' import { Alert, Button, Card, IconButton, StateBadge, StateTone } from './ui' +import { formatDateTime, useDisplayTimezone } from '../utils/datetime' // Human-friendly names + what kind of automation each job is. Trigger-now lives // on the Training page; this card owns only "should it run / when". @@ -34,10 +35,11 @@ function humanCron(expr: string): string { function formatTs(iso: string | null): string { if (!iso) return 'Never' - return `${new Date(iso).toLocaleString('en-IN', { timeZone: 'Asia/Kolkata', dateStyle: 'medium', timeStyle: 'short' })} IST` + return formatDateTime(iso) } export default function AutomationSettings({ isAdmin }: { isAdmin: boolean }) { + const timezone = useDisplayTimezone() const { data: jobs = [], isLoading, refetch } = useCronJobs() const toggleJob = useToggleCronJob() const updateSchedule = useUpdateCronSchedule() @@ -96,7 +98,7 @@ export default function AutomationSettings({ isAdmin }: { isAdmin: boolean }) { Automation & Schedules

- Next runs are shown in IST. Enabling or disabling a job takes effect immediately. + Next runs are shown in {timezone}. Enabling or disabling a job takes effect immediately.

{error && ( diff --git a/backend/webui/src/components/ChatRunViewer.tsx b/backend/webui/src/components/ChatRunViewer.tsx index db7c2c19..994a6383 100644 --- a/backend/webui/src/components/ChatRunViewer.tsx +++ b/backend/webui/src/components/ChatRunViewer.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react' import { useQuery } from '@tanstack/react-query' import { X } from 'lucide-react' import { chatApi } from '../services/api' +import { formatDateTime } from '../utils/datetime' export interface ChatRun { run_id: string @@ -26,9 +27,9 @@ interface RunStep { response_unavailable?: boolean } -const stamp = (value: string) => new Date(value).toLocaleString('en-IN', { - timeZone: 'Asia/Kolkata', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', -}) + ' IST' +const stamp = (value: string) => formatDateTime(value, { + day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', timeZoneName: 'short', +}) function Payload({ label, value }: { label: string; value: unknown }) { if (value === undefined) return null diff --git a/backend/webui/src/components/DateTime.tsx b/backend/webui/src/components/DateTime.tsx new file mode 100644 index 00000000..d03554e4 --- /dev/null +++ b/backend/webui/src/components/DateTime.tsx @@ -0,0 +1,27 @@ +import { formatDate, formatDateTime, formatTime, toDate, useDisplayTimezone, type DateInput, type FormatOptions } from '../utils/datetime' + +const FORMATTERS = { datetime: formatDateTime, date: formatDate, time: formatTime } + +interface DateTimeProps { + value: DateInput + /** Defaults to "datetime". */ + format?: keyof typeof FORMATTERS + options?: FormatOptions + className?: string +} + +/** A timestamp shown in the user's display timezone; hover shows the full date and time. */ +export default function DateTime({ value, format = 'datetime', options, className }: DateTimeProps) { + useDisplayTimezone() + const date = toDate(value) + if (Number.isNaN(date.getTime())) return null + return ( + + ) +} diff --git a/backend/webui/src/components/RecordingMemoryContext.tsx b/backend/webui/src/components/RecordingMemoryContext.tsx index 7742a615..bba679a1 100644 --- a/backend/webui/src/components/RecordingMemoryContext.tsx +++ b/backend/webui/src/components/RecordingMemoryContext.tsx @@ -1,4 +1,3 @@ -import { sourceDate } from "../utils/sourceTime"; import { useState } from "react"; import { Link, useSearchParams } from "react-router-dom"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; @@ -13,6 +12,7 @@ import { Button } from "./ui"; import { CandidateChanges } from "./timeline/ReviewDesk"; import ContextRefreshes from "./ContextRefreshes"; import { sourceLabel } from "./timeline/SessionMemoryBoard"; +import { formatDateTime, formatTime, useDisplayTimezone } from '../utils/datetime' interface Context { organization_requests?: { request_id?: string }[]; @@ -54,15 +54,16 @@ export default function RecordingMemoryContext({ const client = useQueryClient(); const [params] = useSearchParams(); const space = params.get("memory_space_id") || undefined; + const timezone = useDisplayTimezone(); const [clarification, setClarification] = useState(""); const [requestId, setRequestId] = useState(); const [inspect, setInspect] = useState(false); const query = useQuery({ - queryKey: ["recording-context", recordingId, space], + queryKey: ["recording-context", recordingId, space, timezone], queryFn: async () => ( await api.get(`/api/recordings/${recordingId}/context`, { - params: { timezone: "Asia/Kolkata", memory_space_id: space }, + params: { timezone, memory_space_id: space }, }) ).data, refetchInterval: 5000, @@ -80,7 +81,7 @@ export default function RecordingMemoryContext({ mutationFn: (day: string) => api.post(`/api/recordings/${recordingId}/organize-day`, { local_date: day, - timezone: "Asia/Kolkata", + timezone, }), onSuccess: (response) => { setRequestId(response.data.request_id); @@ -170,10 +171,8 @@ export default function RecordingMemoryContext({ {!data.event_date_known && (

Recording date unknown. Uploaded{" "} - {sourceDate(data.uploaded_at).toLocaleString("en-IN", { - timeZone: "Asia/Kolkata", - })}{" "} - IST. This session stays undated. + {formatDateTime(data.uploaded_at)}. This session stays + undated.

)} {data.event_date_known && !data.sessions.length && ( @@ -220,18 +219,11 @@ export default function RecordingMemoryContext({

{s.title}

- {sourceDate(s.started_at).toLocaleTimeString("en-IN", { - timeZone: "Asia/Kolkata", - hour: "numeric", + {formatTime(s.started_at, { + hour: "2-digit", minute: "2-digit", })} - – - {sourceDate(s.ended_at).toLocaleTimeString("en-IN", { - timeZone: "Asia/Kolkata", - hour: "numeric", - minute: "2-digit", - })}{" "} - IST + –{formatTime(s.ended_at)}

{s.summary} @@ -423,7 +415,7 @@ export default function RecordingMemoryContext({

{session.total_sources > 0 && (busy || session.state === 'paused') &&

{session.completed_sources} of {session.total_sources} source groups complete · {({ account: 'Building the session account', combining: 'Combining source accounts', checking_claims: 'Independent account review', memory: 'Preparing note changes' } as Record)[session.stage || 'account']}

} - {busy && activityLabel(session) &&

{activityLabel(session)} · last activity {clock(session.investigation_activity!.updated_at, 'Asia/Kolkata')} IST

} + {busy && activityLabel(session) &&

{activityLabel(session)} · last activity {formatTime(session.investigation_activity!.updated_at)}

} {session.error && session.state !== 'generating' &&

{session.state === 'paused' ? (session.failure_kind === 'repeated_tool_call' ? 'Repeated identical tool calls stopped this investigation. Saved source reads and drafts remain inspectable. Restart begins a fresh attempt; no automatic retry is scheduled.' : 'The investigation reached its work limit. Restart to begin a new attempt with completed source groups retained; no automatic retry is scheduled. Earlier exchanges remain available below.') : session.state === 'failed' ? 'Preparation stopped before a reviewed draft was completed. Retry preparation, or inspect the details below.' : session.state === 'stale' ? 'This draft needs refreshing against the current sources before it can be approved.' : session.failure_kind === 'time_slice' ? 'Saved work will continue in the queue.' : session.error}

{session.state === 'failed' &&
Technical details
{session.error}
} @@ -152,7 +153,7 @@ function SessionRow({ session, day, timezone }: { session: MemorySession; day: s {(decide.error || generate.error || restart.error || correction.error) &&

{errorMessage(decide.error || generate.error || restart.error || correction.error)}

} {notice &&

{notice}

} {open &&
- {session.investigation_activity?.event &&
Investigation activity

{session.investigation_activity.tool_calls} tool calls · {session.investigation_activity.rounds} model rounds · Pi {session.investigation_activity.runtime_version}

{session.investigation_activity.checkpoint_saved ? 'Native session checkpoint saved' : 'Awaiting first complete checkpoint'}{session.investigation_activity.resumed ? ' · resumed saved work' : ''}

Last activity {clock(session.investigation_activity.updated_at, 'Asia/Kolkata')} IST

} + {session.investigation_activity?.event &&
Investigation activity

{session.investigation_activity.tool_calls} tool calls · {session.investigation_activity.rounds} model rounds · Pi {session.investigation_activity.runtime_version}

{session.investigation_activity.checkpoint_saved ? 'Native session checkpoint saved' : 'Awaiting first complete checkpoint'}{session.investigation_activity.resumed ? ' · resumed saved work' : ''}

Last activity {formatTime(session.investigation_activity.updated_at)}

} {proposal && reviewing && } {questions.map(question =>

{question}

)} {questions.length > 0 &&