Self-hosted AI workspace.
Python
Merge origin/dev into main
pewdiepie-archdaemon324b1d9eaf7b
diff --cc docker/entrypoint.shindex 7d796d9ff,8a3ab4bb6..fc0e87a08--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@@ -24,51 -26,57 +26,78 @@@ if ! getent passwd "$PUID" >/dev/null 2useradd -u "$PUID" -g "$PGID" -M -s /bin/sh -d /app odysseusfi- # Docker-socket group plumbing. When /var/run/docker.sock is bind-- # mounted (cookbook uses `docker exec` to reach sibling containers- # like ollama-rocm), the socket is owned by root:docker on the host.- # We need the in-container odysseus user to be in the matching group- # so `gosu PUID:PGID` doesn't strip it. compose's `group_add` only- # applies to the initial root process — gosu drop resets supplementary- # groups — so detect the socket's GID here and add the user via the- # username form `gosu odysseus` below.++ODY_USER="$(getent passwd "$PUID" | cut -d: -f1)"++[ -z "$ODY_USER" ] && ODY_USER=odysseus++++# Docker-socket group plumbing. When /var/run/docker.sock is bind-mounted++# (Cookbook uses docker exec to reach sibling containers), the socket is++# owned by root:<host docker gid>. Add the app user to that group and later++# call gosu by username so supplementary groups are retained.+DOCKER_SOCK="${DOCKER_SOCK:-/var/run/docker.sock}"+if [ -S "$DOCKER_SOCK" ]; then+ SOCK_GID="$(stat -c '%g' "$DOCKER_SOCK" 2>/dev/null || echo '')"+ if [ -n "$SOCK_GID" ] && [ "$SOCK_GID" != "0" ]; then- # Create the group locally if missing, then add odysseus to it.+ if ! getent group "$SOCK_GID" >/dev/null 2>&1; then+ groupadd -g "$SOCK_GID" docker_host || true+ fi+ SOCK_GROUP="$(getent group "$SOCK_GID" | cut -d: -f1)"+ if [ -n "$SOCK_GROUP" ]; then- ODY_USER="$(getent passwd "$PUID" | cut -d: -f1)"- [ -z "$ODY_USER" ] && ODY_USER=odysseus+ usermod -aG "$SOCK_GROUP" "$ODY_USER" 2>/dev/null || true+ fi+ fi+fi+- # Repair ownership on every writable path the app touches at runtime.- #- # Bind-mounted dirs (/app/data, /app/logs) are the obvious ones, but- # the app ALSO writes inside the image's own source tree at runtime:- # - services/cache/{search,content}/* (search cache LRU)- # - services/search_analytics.json- # - services/search_engine_error.log- # - services/tts cache, etc.- # These dirs were created as root during `docker build`, so dropping- # to PUID:PGID would otherwise crash on the first import that tries- # to mkdir them. Chown the whole /app tree — fast (<1s on this size)- # and idempotent via the `-not -uid` filter so we only touch files- # that need fixing.- for dir in /app /app/data /app/logs; do+ mount_root_for() {+ awk -v target="$1" '$5 == target { print $4; exit }' /proc/self/mountinfo 2>/dev/null || true+ }++ is_broad_mount_root() {+ case "$1" in+ /|/home|/srv|/var|/usr|/opt|/tmp|/mnt|/media)+ return 0+ ;;+ esac+ return 1+ }++ repair_tree_ownership() {+ dir="$1"if [ -d "$dir" ]; then- # `find ... -not -uid` keeps this O(touched-files), not- # O(everything), so terabyte-sized maildirs don't slow startup.- find "$dir" -not -uid "$PUID" -print0 2>/dev/null \+ find "$dir" -xdev -not -uid "$PUID" -print0 2>/dev/null \+ | xargs -0 -r chown "$PUID:$PGID" 2>/dev/null || true+ fi+ }++ repair_app_tree_ownership() {+ if [ -d /app ]; then+ find /app -xdev \+ \( -path /app/data -o -path /app/logs -o -path /app/.ssh -o -path /app/.cache -o -path /app/.local \) -prune \+ -o -not -uid "$PUID" -print0 2>/dev/null \| xargs -0 -r chown "$PUID:$PGID" 2>/dev/null || truefi+ }++ repair_bind_mount_ownership() {+ dir="$1"+ if [ ! -d "$dir" ]; then+ return+ fi++ mount_root="$(mount_root_for "$dir")"+ if is_broad_mount_root "$mount_root"; then+ echo "Skipping recursive ownership repair for $dir because it maps to broad host path $mount_root" >&2+ chown "$PUID:$PGID" "$dir" 2>/dev/null || true+ return+ fi++ repair_tree_ownership "$dir"+ }++ # Repair image-owned writable paths without walking into bind-mounted host+ # trees, then repair the app-owned mount roots separately.+ repair_app_tree_ownership+ for dir in /app/data /app/logs /app/.ssh /app/.cache/huggingface /app/.local; do+ repair_bind_mount_ownership "$dir"done# Cookbook installs vllm/etc. via `pip install --user`, which pulls@@@ -95,6 -103,6 +124,7 @@@ for cu inbreakfidone++# Disable the FlashInfer JIT sampler unconditionally — it is sampler-only# and has no impact on the attention path, but requires nvcc + matching# CUDA headers at startup. Without this, vLLM crashes with "Could not find@@@ -108,13 -116,9 +138,9 @@@ export PATH="/app/.local/bin:$PATH# Run first-time setup as the app user so data/ files get the right ownership.# setup.py is idempotent — skips auth.json / .env if they already exist.# || true so a setup failure never prevents the container from starting.- # Use the username form (no :GID) so supplementary groups from /etc/group- # (including the docker-socket group set above) flow through to the child.- ODY_USER="$(getent passwd "$PUID" | cut -d: -f1)"- [ -z "$ODY_USER" ] && ODY_USER="$PUID:$PGID"- gosu "$ODY_USER" python /app/setup.py || true-"$GOSU_BIN" "$PUID:$PGID" "$PYTHON_BIN" /app/setup.py || true++"$GOSU_BIN" "$ODY_USER" "$PYTHON_BIN" /app/setup.py || true# Drop root and run the actual app. `gosu` is preferred over `su` /# `sudo` because it cleans up the process tree (no extra shell layer)# so signals (SIGTERM from `docker stop`) reach uvicorn directly.- exec gosu "$ODY_USER" "$@"-exec "$GOSU_BIN" "$PUID:$PGID" "$@"++exec "$GOSU_BIN" "$ODY_USER" "$@"diff --cc routes/chat_helpers.pyindex f030d6c91,880b4a5eb..06c92ac6b--- a/routes/chat_helpers.py+++ b/routes/chat_helpers.py@@@ -22,32 -22,23 +22,48 @@@ from fastapi import HTTPExceptiologger = logging.getLogger(__name__)+_CASUAL_OPENING_RE = re.compile(+ r"^\s*(?:h+i+|hey+|hello+|yo+|sup+|what'?s up|wass?up|hiya|howdy|"+ r"lol|lmao|haha+|hehe+|thanks?|thank you|ty|idk|dunno|meh|bruh|bro)\b(?P<tail>.*)$",+ re.IGNORECASE,+)+_CASUAL_BLOCKLIST_RE = re.compile(+ r"\b(?:cookbook|serve|serving|launch|start|vllm|sglang|llama\.?cpp|ollama|"+ r"download|model|email|document|doc|note|calendar|task|search|web|research|"+ r"file|folder|repo|git|settings?|endpoint|api|token|mcp)\b",+ re.IGNORECASE,+)+++def _is_casual_low_signal(text: str) -> bool:+ """Short greetings/slang should not pull memory, skills, RAG, or docs."""+ s = str(text or "").strip()+ m = _CASUAL_OPENING_RE.match(s)+ if not m:+ return False+ tail = m.group("tail") or ""+ if _CASUAL_BLOCKLIST_RE.search(tail):+ return False+ tail_words = re.findall(r"[A-Za-z0-9_'-]+", tail)+ return len(tail_words) <= 2++ # Strong references to in-flight fire-and-forget tasks scheduled from this+ # module. asyncio only keeps weak references to tasks created via+ # create_task, so without this the GC can collect a task mid-execution and+ # the background work (extraction, auto-naming) silently never runs.+ # Mirrors WebhookManager._spawn_tracked from src/webhook_manager.py.+ _BG_TASKS: set[asyncio.Task] = set()+++ def _spawn_bg(coro) -> asyncio.Task:+ """Schedule a background task and hold a strong reference until it finishes."""+ task = asyncio.create_task(coro)+ _BG_TASKS.add(task)+ task.add_done_callback(_BG_TASKS.discard)+ return task++# ── Data containers ────────────────────────────────────────────────────── #@dataclass@@@ -601,10 -584,10 +609,11 @@@ async def build_chat_contextif not incognito:fire_message_event(request, webhook_manager, session_id, sess, message, compare_mode)- # Resolve user prefs- user = get_current_user(request)+ # Resolve owner-scoped prefs/context. Browser requests keep the cookie user;+ # bearer-token chat requests use the token owner instead of the "api" sentinel.+ user = effective_user(request)uprefs = load_prefs_for_user(user)+ casual_low_signal = _is_casual_low_signal(message)# Memory enabled?mem_enabled = not incognito and not no_memory and uprefs.get("memory_enabled", True)diff --cc routes/email_routes.pyindex 779669198,b9da5a82e..79ddbb632--- a/routes/email_routes.py+++ b/routes/email_routes.py@@@ -43,8 -45,9 +45,9 @@@ from routes.email_helpers import_load_settings, _save_settings, _get_email_config,_send_smtp_message, _smtp_security_mode,_IMAP_TIMEOUT_SECONDS, _open_imap_connection,+ make_oauth_state, verify_oauth_state,_imap_connect, _imap, _decode_header, _detect_sent_folder, _detect_drafts_folder,- _extract_attachment_text, _list_attachments_from_msg,+ _extract_attachment_text, _list_attachments_from_msg, _has_visible_attachments, _is_likely_signature_image_attachment,_extract_attachment_to_disk, _extract_html, _extract_text,_fetch_sender_thread_context, _pre_retrieve_context,_EMAIL_REPLY_SYS_PROMPT_BASE, _POOL_HOOKS,@@@ -2162,10 -2027,7 +2168,10 @@@ def setup_email_routes()outer = MIMEMultipart("alternative")body_container = outer+ to = _normalize_addr_field(to or "")+ cc = _normalize_addr_field(cc or "")+ bcc = _normalize_addr_field(bcc or "")- outer["From"] = cfg["from_address"]+ outer["From"] = email.utils.formataddr((cfg.get("display_name") or "", cfg["from_address"]))outer["To"] = toif cc:outer["Cc"] = cc@@@ -2441,10 -2302,7 +2446,10 @@@outer = MIMEMultipart("alternative")body_container = outer+ req.to = _normalize_addr_field(req.to or "")+ req.cc = _normalize_addr_field(req.cc or "")+ req.bcc = _normalize_addr_field(req.bcc or "")- outer["From"] = cfg["from_address"]+ outer["From"] = email.utils.formataddr((cfg.get("display_name") or "", cfg["from_address"]))outer["To"] = req.toif req.cc:outer["Cc"] = req.ccdiff --cc src/constants.pyindex 16aecf19a,b76f5d97b..eceeb6eb0--- a/src/constants.py+++ b/src/constants.py@@@ -2,12 -2,14 +2,14 @@@"""Application-wide constants and configuration values."""import os+ from src.runtime_paths import get_app_root, get_default_data_dir+-APP_VERSION = "1.0.0"+APP_VERSION = "1.0.1"# Base paths- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"+ BASE_DIR = os.path.join(get_app_root(), "")STATIC_DIR = os.path.join(BASE_DIR, "static")- DATA_DIR = os.getenv("ODYSSEUS_DATA_DIR", os.path.join(BASE_DIR, "data"))+ DATA_DIR = os.getenv("ODYSSEUS_DATA_DIR", get_default_data_dir())# Data file paths# Single source of truth: every persisted file/dir lives under DATA_DIR, whichdiff --cc static/js/cookbookServe.jsindex da48507f7,33d56ef3c..a22c73af3--- a/static/js/cookbookServe.js+++ b/static/js/cookbookServe.js@@@ -497,9 -116,8 +497,10 @@@ function _selectedServeTarget(panel): (server?.name || 'local server');return {host,- port: host ? (server?.port || _getPort(host) || '') : '',+ serverKey: server ? (_serverKey?.(server) || '') : (select?.value || ''),+ serverName: server?.name || '',- port: host ? (_getPort(host) || server?.port || '') : '',+ env: server?.env || '',++ port: host ? (server?.port || _getPort(host) || '') : '',venv,platform: server?.platform || _envState.platform || '',label,@@@ -942,22 -544,17 +957,23 @@@ function _rerenderCachedModels()const ss = (_byRepo[repo] && typeof _byRepo[repo] === 'object')? _byRepo[repo]: (_lastUsed || (_isLegacyFlat ? _allSs : {}));+ const _modelSs = (_byRepo[repo] && typeof _byRepo[repo] === 'object') ? _byRepo[repo] : null;+ const _repoForcedBackend = !!(_modelSs && _modelSs._forceBackend);+ const _isMiniMaxM3 = _isMiniMaxM3Model({ ...m, repo_id: repo });+ const _isMiniMaxM2 = _isMiniMaxM2Model({ ...m, repo_id: repo });+ const _isMiniMaxMSeries = _isMiniMaxM3 || _isMiniMaxM2;+ const svm = (k, def) => (_modelSs && _hasOwn(_modelSs, k)) ? _modelSs[k] : def;+ const _serveTarget = _selectedServeTarget();+ const _backendChoices = _backendChoicesForTarget(_serveTarget);+ const _allowedBackends = new Set(_backendChoices.map(([v]) => v));const detectedBackend = _detectBackend(m).backend;- const _allowedBackends = new Set(_isWindows()- ? ['llamacpp', 'diffusers']- : (_isMetal() ? ['llamacpp', 'ollama'] : ['vllm', 'sglang', 'llamacpp', 'ollama', 'diffusers']));- const defaultBackend = (_repoForcedBackend && ss.backend && _allowedBackends.has(ss.backend))- let defaultBackend = (ss._forceBackend && ss.backend && _allowedBackends.has(ss.backend))++ let defaultBackend = (_repoForcedBackend && ss.backend && _allowedBackends.has(ss.backend))? ss.backend: detectedBackend;+ if (!_allowedBackends.has(defaultBackend)) defaultBackend = _backendChoices[0]?.[0] || detectedBackend;- const savedMatchesBackend = !!ss._forceBackend || (ss.backend || 'vllm') === detectedBackend;+ const savedMatchesBackend = _repoForcedBackend || (ss.backend || 'vllm') === detectedBackend;const sv = (k, def) => (ss[k] !== undefined && savedMatchesBackend) ? ss[k] : def;- const defaultTp = defaultBackend === 'llamacpp' ? '1' : sv('tp', '1');+ const defaultTp = defaultBackend === 'llamacpp' ? '1' : sv('tp', _isMiniMaxMSeries ? '8' : '1');const detectedGpuIds = _allGpuIds(_getGpuToggleTotal?.());const defaultGpus = defaultBackend === 'llamacpp'? '0'@@@ -1024,15 -621,8 +1040,9 @@@: `This model's download isn't complete yet (${esc(m.size || 'partial')}). The serve will start but is likely to crash on a missing shard. Wait for the download to finish, or relaunch after it's done.`;panelHtml += `<div class="hwfit-serve-warn" style="margin:0 0 8px;padding:6px 10px;border-radius:5px;font-size:11px;background:color-mix(in srgb, var(--color-warning, #f0ad4e) 14%, transparent);border:1px solid color-mix(in srgb, var(--color-warning, #f0ad4e) 40%, transparent);color:var(--color-warning, #f0ad4e);display:flex;gap:6px;align-items:flex-start;line-height:1.4;"><span aria-hidden="true">⚠</span><span>${_warnText}</span></div>`;}- // Row 1: Backend + Server + Env+ panelHtml += `<div class="hwfit-serve-preset-row">${_slotsHtml}</div>`;+ // Row 1: Engine + Server + EnvpanelHtml += `<div class="hwfit-serve-row">`;- const _backendChoices = _isWindows()- ? [['llamacpp','llama.cpp'],['diffusers','Diffusers']]- : _isMetal()- // Diffusers (diffusion_server.py) is CUDA-only — omit it on Metal.- ? [['llamacpp','llama.cpp'],['ollama','Ollama']]- : [['vllm','vLLM'],['sglang','SGLang'],['llamacpp','llama.cpp'],['ollama','Ollama'],['diffusers','Diffusers']];const backendOpts = _backendChoices.map(([v,l]) => `<option value="${v}"${defaultBackend===v?' selected':''}>${l}</option>`).join('');// Custom Backend picker — native <select> can't host SVG inside// options, so we render a button + menu that show the backend logo@@@ -2802,11 -1995,10 +2794,11 @@@// common case instantly without waiting for a network round-trip.try {const _runningMod = await import('./cookbookRunning.js');- const _hostStr = _selectedServeTarget.host || '';- const _serverKeyStr = _selectedServeTarget.serverKey || (_hostStr || 'local');+ const _hostStr = launchTarget.host || '';++ const _serverKeyStr = launchTarget.serverKey || (_hostStr || 'local');const _active = (_runningMod._loadTasks ? _runningMod._loadTasks() : []).filter(t =>t && t.type === 'serve'- && (t.remoteHost || '') === _hostStr+ && ((t.remoteHost || '') === _hostStr || (t.remoteServerKey || '') === _serverKeyStr)&& (t.status === 'running' || t.status === 'ready' || t._serveReady));if (_active.length) {@@@ -3086,11 -2143,11 +3077,14 @@@const venvVal = panel.querySelector('[data-field="venv"]')?.value?.trim();const gpusVal = panel.querySelector('[data-field="gpus"]')?.value?.trim();const origGpus = _envState.gpus;- const serveHost = _selectedServeTarget.host || '';- const serveServerKey = _selectedServeTarget.serverKey || '';- const serveServerName = _selectedServeTarget.serverName || '';- const _srvEnv = _selectedServeTarget.env || '';- const _srvEnvPath = _selectedServeTarget.envPath || '';+ // Resolve the target host from the visible Server dropdown — the reliable+ // source. Relying on _envState.remoteHost silently sent serves to Local+ // when that value was stale/empty. Pass it explicitly to the launcher.- let serveHost = launchTarget.host || '';- let _srvEnv = launchTarget.env || '', _srvEnvPath = launchTarget.venv || '';++ const serveHost = launchTarget.host || '';++ const serveServerKey = launchTarget.serverKey || '';++ const serveServerName = launchTarget.serverName || '';++ const _srvEnv = launchTarget.env || '';++ const _srvEnvPath = launchTarget.venv || '';// The venv field wins; otherwise fall back to the env configured for the// selected server in Settings, so the activation isn't silently dropped// when the field is left blank (the per-server venv wasn't being applied).diff --cc static/js/notes.jsindex 8c6f1a832,2aad036fc..fa754b771--- a/static/js/notes.js+++ b/static/js/notes.js@@@ -1096,9 -1114,15 +1114,12 @@@ export async function refreshDueBadge(o// ---- Panel ----export function openPanel() {- if (_open) return;+ if (_open) {+ _bringNotesToFront();+ return;+ }_open = true;_editingId = null;- // Reset the search filter — the rebuilt pane's search input renders empty, so a- // stale _searchQuery would silently hide non-matching notes after a reopen.- _searchQuery = '';_clearViewedReminderGlows();_firedDotDismissedAt = Date.now();try { localStorage.setItem(REMINDER_DISMISSED_AT_KEY, String(_firedDotDismissedAt)); } catch {}