Skip to content
Closed

Dev #361

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
6df60c0
fix(backend): report LLM configuration errors instead of failing sile…
thestumonkey Nov 6, 2026
3c59e0b
feat(timeline): make Immich optional and let a reconciliation be canc…
thestumonkey Nov 6, 2026
67acc0b
fix(transcription): end a stream cleanly when the provider already cl…
thestumonkey Nov 7, 2026
062e97c
feat(webui): show timestamps in the user's timezone instead of IST
thestumonkey Nov 7, 2026
7fbdf43
chore: ignore k8s-manifests/secrets.yaml
thestumonkey Nov 7, 2026
32b8752
ci: install pytest-asyncio for the chronicle-client tests
thestumonkey Nov 7, 2026
577269a
Merge pull request #33 from Ushadow-io/fix/ci-client-pytest-asyncio
thestumonkey Nov 7, 2026
54ee539
Merge branch 'dev' into feat/user-timezone-dates
thestumonkey Nov 7, 2026
17eef0a
test(asr): stub faster_whisper so the service tests run without CUDA …
thestumonkey Nov 7, 2026
97568d6
Merge pull request #34 from Ushadow-io/fix/ci-asr-faster-whisper-stub
thestumonkey Nov 7, 2026
992d473
Merge branch 'dev' into feat/user-timezone-dates
thestumonkey Nov 7, 2026
f099479
Merge pull request #28 from Ushadow-io/pr/timeline-cancel-reconciliation
thestumonkey Nov 9, 2026
6f6057c
Merge pull request #31 from Ushadow-io/feat/user-timezone-dates
thestumonkey Nov 9, 2026
5a2151b
Merge pull request #27 from Ushadow-io/pr/llm-config-errors
thestumonkey Nov 9, 2026
6cce121
Merge pull request #30 from Ushadow-io/pr/stt-closed-stream
thestumonkey Nov 9, 2026
44b4933
fix(models): refuse operations whose max_tokens the model cannot produce
thestumonkey Nov 14, 2026
1107cee
Merge pull request #39 from Ushadow-io/fix/model-output-limits-fork
thestumonkey Nov 14, 2026
358d263
Merge branch 'dev' into dev
thestumonkey Nov 14, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/python-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ jobs:
uv run --no-project
--with ./extras/chronicle-client
--with pytest
--with pytest-asyncio
pytest extras/chronicle-client/tests -q

backend-unit:
Expand Down
39 changes: 33 additions & 6 deletions backend/src/backend/config_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, ...] = ()
Expand Down Expand Up @@ -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:
Expand All @@ -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)


Expand Down Expand Up @@ -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
22 changes: 22 additions & 0 deletions backend/src/backend/controllers/queue_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
55 changes: 52 additions & 3 deletions backend/src/backend/controllers/system_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from datetime import UTC, datetime
from io import StringIO
from pathlib import Path
from typing import Optional
from typing import Any, Optional
from urllib.parse import urlparse

import httpx
Expand Down Expand Up @@ -48,6 +48,7 @@
_find_config_path,
get_models_registry,
load_models_config,
output_token_limit_findings,
)
from backend.model_routes import effective_model_routes, effective_operation_routes
from backend.models.user import User
Expand Down Expand Up @@ -176,6 +177,42 @@ def _is_self_hosted_model(model) -> bool:
return host.endswith(".ts.net") or "." not in host


def _output_limit_issues(registry: Any) -> list[dict[str, Any]]:
"""Report each max_tokens setting its model cannot honour.

These are errors: the operation refuses to run (see ``OutputLimitExceeded``)
until a larger-output model is chosen or the setting is lowered.
"""

timeline_pi = (load_config().get("timeline", {}) or {}).get("pi", {}) or {}
extra = [
(
"timeline.pi.max_tokens",
str(timeline_pi.get("operation") or "timeline_segmentation"),
timeline_pi.get("max_tokens"),
)
]
return [
{
"component": "Model Limits",
"severity": "error",
"message": (
f"'{finding['operation']}' needs a model with at least "
f"{finding['requested']} output tokens, but it uses "
f"{finding['model']} ({finding['model_name']}), which accepts at most "
f"{finding['limit']}. It will not run until this is fixed."
),
"resolution": (
f"Settings > AI Model Settings: route '{finding['operation']}' to a "
f"model that supports at least {finding['requested']} output "
f"tokens. Or lower {finding['setting']} to {finding['limit']} or "
f"less, if shorter results are acceptable."
),
}
for finding in output_token_limit_findings(registry, extra)
]


async def get_config_diagnostics():
"""
Get comprehensive configuration diagnostics.
Expand Down Expand Up @@ -360,6 +397,13 @@ async def get_config_diagnostics():
}
)

# Listed under issues so the health poller records a System Event.
limit_issues = _output_limit_issues(registry)
if limit_issues:
diagnostics["issues"].extend(limit_issues)
if diagnostics["overall_status"] == "healthy":
diagnostics["overall_status"] = "partial"

else:
diagnostics["overall_status"] = "unhealthy"
diagnostics["issues"].append(
Expand Down Expand Up @@ -2679,7 +2723,9 @@ async def create_plugin(
if events
else '"conversation.complete"'
)
boilerplate = inspect.cleandoc(f'''
boilerplate = (
inspect.cleandoc(
f'''
"""
{class_name} implementation.

Expand Down Expand Up @@ -2716,7 +2762,10 @@ async def cleanup(self):
async def on_conversation_complete(self, context: PluginContext) -> Optional[PluginResult]:
logger.info(f"Processing conversation for user: {{context.user_id}}")
return PluginResult(success=True, message="OK")
''') + "\n"
'''
)
+ "\n"
)
(plugin_dir / "plugin.py").write_text(boilerplate, encoding="utf-8")
created_files.append("plugin.py")

Expand Down
28 changes: 28 additions & 0 deletions backend/src/backend/middleware/app_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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."""
Expand Down
Loading
Loading