From 28a4580c85d4e7d5e3ba70063266f0fd568222c3 Mon Sep 17 00:00:00 2001 From: "CodingClearLove@gmail.com" Date: Wed, 11 Nov 2026 10:34:30 +0800 Subject: [PATCH 1/2] feat: persist console settings across daemon restarts The admin console had no place to remember a preference: the screen-off-during-run switch and similar UI state reset on every daemon restart. Add a small key/value settings store on the Artemis SQLite database so a setting survives a restart and is readable from the task worker subprocess, which consumes it. - app_settings table via CREATE TABLE IF NOT EXISTS so existing databases pick it up on the next open - SettingsService returns built-in defaults overlaid with persisted JSON-encoded values; unknown keys round-trip untouched - GET/PUT /api/system/settings expose the merged snapshot - the worker inherits ARTEMIS_SCREEN_OFF from the screen_off setting and build_scrcpy_record_command honours it with scrcpy --turn-screen-off screen_off defaults to off, and so does the ARTEMIS_SCREEN_OFF fallback, so recording behaves exactly as it does today unless an operator explicitly opts in; no existing setup changes what it records. --- apps/admin_console/routers/system.py | 26 +++++ .../services/settings_service.py | 94 +++++++++++++++++++ .../services/task_queue_service.py | 9 ++ artemis/data_engine/storage.py | 7 ++ artemis/utils/video.py | 22 +++++ .../admin_console/test_console_settings.py | 70 ++++++++++++++ 6 files changed, 228 insertions(+) create mode 100644 apps/admin_console/services/settings_service.py create mode 100644 tests/unit/admin_console/test_console_settings.py diff --git a/apps/admin_console/routers/system.py b/apps/admin_console/routers/system.py index c8ce18343..deb3ae038 100644 --- a/apps/admin_console/routers/system.py +++ b/apps/admin_console/routers/system.py @@ -493,6 +493,32 @@ def mask_key(k: str | None) -> str | None: } +@router.get("/settings") +async def get_settings(): + """Return persisted console settings merged over their defaults.""" + try: + from apps.admin_console.services.settings_service import settings_service + except ImportError: + from admin_console.services.settings_service import settings_service + return {"settings": settings_service.get_all()} + + +@router.put("/settings") +async def update_settings(payload: dict): + """Persist the provided settings keys and return the merged snapshot.""" + try: + from apps.admin_console.services.settings_service import settings_service + except ImportError: + from admin_console.services.settings_service import settings_service + if not isinstance(payload, dict): + raise HTTPException(status_code=400, detail="Settings payload must be a JSON object.") + try: + merged = settings_service.update(payload) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return {"settings": merged} + + @router.get("/server-status") async def get_server_runtime_status(): """Retrieve runtime status, PID, port, and uptime of the Artemis server. diff --git a/apps/admin_console/services/settings_service.py b/apps/admin_console/services/settings_service.py new file mode 100644 index 000000000..d10b0e5e6 --- /dev/null +++ b/apps/admin_console/services/settings_service.py @@ -0,0 +1,94 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Small persisted key/value settings store for the Artemis console. + +Values are JSON-encoded in the ``app_settings`` table so a setting survives +daemon restarts and is readable from any process that shares the Artemis +database (notably the task worker subprocess, which consumes `screen_off`). +""" + +from __future__ import annotations + +import json +import time +from typing import Any + +try: + from admin_console.database.connection import db_session +except ImportError: # pragma: no cover - import path differs when run as a package + from apps.admin_console.database.connection import db_session + + +class SettingsService: + """Reads and writes console settings, falling back to built-in defaults.""" + + # `screen_off` powers the physical display off while a task runs (scrcpy + # `--turn-screen-off`); the device stays awake and input/screencap keep working. + # Off by default so opting in never changes the behaviour of an existing setup. + DEFAULTS: dict[str, Any] = { + "screen_off": False, + } + + def get_all(self) -> dict[str, Any]: + """Return defaults overlaid with every persisted override.""" + values = dict(self.DEFAULTS) + with db_session() as conn: + for row in conn.execute("SELECT key, value FROM app_settings").fetchall(): + key = row["key"] + if key not in self.DEFAULTS: + # Unknown keys are still surfaced so an older/newer frontend + # can round-trip settings it knows about. + pass + try: + values[key] = json.loads(row["value"]) if row["value"] is not None else None + except (ValueError, TypeError): + values[key] = row["value"] + return values + + def get(self, key: str, default: Any = None) -> Any: + """Return one setting value, or ``default`` when it was never set.""" + fallback = self.DEFAULTS.get(key, default) + with db_session() as conn: + row = conn.execute("SELECT value FROM app_settings WHERE key = ?", (key,)).fetchone() + if row is None: + return fallback + try: + return json.loads(row["value"]) if row["value"] is not None else None + except (ValueError, TypeError): + return row["value"] + + def update(self, values: dict[str, Any]) -> dict[str, Any]: + """Persist the provided keys and return the merged settings snapshot.""" + if not isinstance(values, dict): + raise ValueError("Settings payload must be a JSON object.") + now = time.time() + with db_session() as conn: + for key, value in values.items(): + if not isinstance(key, str) or not key.strip(): + continue + conn.execute( + """ + INSERT INTO app_settings (key, value, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value, + updated_at = excluded.updated_at + """, + (key, json.dumps(value), now), + ) + conn.commit() + return self.get_all() + + +settings_service = SettingsService() diff --git a/apps/admin_console/services/task_queue_service.py b/apps/admin_console/services/task_queue_service.py index b99b4c919..697784842 100644 --- a/apps/admin_console/services/task_queue_service.py +++ b/apps/admin_console/services/task_queue_service.py @@ -29,11 +29,13 @@ from admin_console.database.repositories.session_repository import session_repo from admin_console.services import worker_process_io from admin_console.services.media_service import media_service + from admin_console.services.settings_service import settings_service except ImportError: from apps.admin_console.core.state import state from apps.admin_console.database.repositories.session_repository import session_repo from apps.admin_console.services import worker_process_io from apps.admin_console.services.media_service import media_service + from apps.admin_console.services.settings_service import settings_service from artemis.config import ( PAUSE_FILE, @@ -525,6 +527,13 @@ def _build_worker_invocation( env["ARTEMIS_SESSION_ID"] = str(sess_id) env["ARTEMIS_TASK_INGRESS"] = str(task_item.get("ingress", "frontend")) env["ARTEMIS_TASK_WORKER"] = "1" + # Forward the console's power-off-during-run preference so every + # recording segment built by the worker honours it. + try: + screen_off = bool(settings_service.get("screen_off", True)) + except Exception: + screen_off = True + env["ARTEMIS_SCREEN_OFF"] = "1" if screen_off else "0" target.endpoint.apply_to_environment(env) env[DeviceExecutionLock.LOCK_SCOPE_ENV] = target.lock_scope queue_ticket = task_item.get("queue_ticket") diff --git a/artemis/data_engine/storage.py b/artemis/data_engine/storage.py index 581737c5f..1d6b3f21a 100644 --- a/artemis/data_engine/storage.py +++ b/artemis/data_engine/storage.py @@ -239,6 +239,13 @@ def _init_db(self): FOREIGN KEY(session_id) REFERENCES sessions(session_id) ) """) + conn.execute(""" + CREATE TABLE IF NOT EXISTS app_settings ( + key TEXT PRIMARY KEY, + value TEXT, + updated_at REAL + ) + """) conn.execute(""" CREATE TABLE IF NOT EXISTS video_recordings ( video_id TEXT PRIMARY KEY, diff --git a/artemis/utils/video.py b/artemis/utils/video.py index 76afb5df0..31aad6571 100644 --- a/artemis/utils/video.py +++ b/artemis/utils/video.py @@ -21,6 +21,7 @@ import asyncio import importlib.util import json +import os from pathlib import Path import re import shutil @@ -51,6 +52,7 @@ def build_scrcpy_record_command( output_path: Path, video_bit_rate: str = "2M", lock_capture_orientation: bool = True, + turn_screen_off: bool | None = None, ) -> list[str]: """Build the shared scrcpy command used by all recording paths. @@ -58,12 +60,32 @@ def build_scrcpy_record_command( The recording supervisor starts a new segment when Android rotates, so a segment never contains multiple coded sizes while still displaying the app in its natural orientation. + + ``--turn-screen-off`` powers the physical display off while scrcpy runs + (the device stays awake), so tasks run with a dark screen; SurfaceFlinger + keeps composing, so mirroring, screencap and input injection are unaffected + and the recorded track still carries the real frame content. When + ``turn_screen_off`` is ``None`` the value is read from the + ``ARTEMIS_SCREEN_OFF`` environment variable (set by the console settings), + which defaults to off so an existing setup records exactly as before unless + the operator opts in. """ + if turn_screen_off is None: + turn_screen_off = os.getenv("ARTEMIS_SCREEN_OFF", "0").strip().lower() not in { + "0", + "false", + "no", + "off", + } command = [ scrcpy_executable, "--serial", device_id, "--no-window", + ] + if turn_screen_off: + command.append("--turn-screen-off") + command += [ "--record", str(output_path), "--record-format", diff --git a/tests/unit/admin_console/test_console_settings.py b/tests/unit/admin_console/test_console_settings.py new file mode 100644 index 000000000..bc7c9e4e2 --- /dev/null +++ b/tests/unit/admin_console/test_console_settings.py @@ -0,0 +1,70 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Console settings persistence. + +``SettingsService`` backs ``GET/PUT /api/system/settings``: each key is stored +JSON-encoded in the ``app_settings`` table so a console preference survives a +daemon restart. These tests bind the service to a throwaway database. +""" + +import importlib + +import pytest + +connection = importlib.import_module("apps.admin_console.database.connection") +settings_module = importlib.import_module("apps.admin_console.services.settings_service") + + +@pytest.fixture +def service(tmp_path, monkeypatch): + """A SettingsService writing to an isolated database.""" + monkeypatch.setattr(connection, "DB_PATH", tmp_path / "settings.db") + return settings_module.SettingsService() + + +def test_defaults_are_returned_before_any_write(service): + assert service.get_all() == {"screen_off": False} + assert service.get("screen_off") is False + + +def test_update_persists_across_instances(service): + service.update({"screen_off": True}) + + assert service.get("screen_off") is True + # A second instance stands in for a restarted process reading the same row. + assert settings_module.SettingsService().get_all()["screen_off"] is True + + +def test_unknown_keys_round_trip(service): + service.update({"ui.wifi_host": "10.0.0.5", "nested": {"a": 1}}) + + assert service.get("ui.wifi_host") == "10.0.0.5" + assert service.get("nested") == {"a": 1} + assert service.get_all()["ui.wifi_host"] == "10.0.0.5" + + +def test_get_falls_back_for_unset_key(service): + assert service.get("never_set", "fallback") == "fallback" + + +def test_update_returns_the_merged_snapshot(service): + merged = service.update({"screen_off": True}) + + assert merged == {"screen_off": True} + + +def test_update_rejects_a_non_object_payload(service): + with pytest.raises(ValueError): + service.update(["not", "a", "mapping"]) From ea0cd9674f5cebc446bdb90645cf173f3ef13e16 Mon Sep 17 00:00:00 2001 From: "CodingClearLove@gmail.com" Date: Tue, 24 Nov 2026 09:18:47 +0800 Subject: [PATCH 2/2] feat: console automations, notification watcher and device runtime helpers Admin console - add automation scheduler with daily/interval/watch triggers; dispatch yields to the device lease so scheduled runs never fight a user task - add notification watcher that polls `dumpsys notification` (zero LLM cost) and turns new notifications into a durable event stream - add installed-app inventory API with persisted user labels for the picker - extend settings, task queue and system routers to support the above Showcase UI - add full zh/en i18n layer and locale files - add automations and notifications pages, settings service and confirm dialog - wire routes, nav switcher, chat/stream and home/workspace components to i18n Runtime / drivers - add device_unlock (keyguard inspection + PIN unlock) and app_launcher helpers - adb driver: prefer ADBKeyboard IME as tier 0 for UTF-8 text input and verify the result via uiautomator dump before reporting success Misc - fix llm service, video utils, memory chunking and data engine storage edge cases - add docs/PROJECT_MAP.md --- apps/admin_console/core/state.py | 1 + apps/admin_console/routers/apps.py | 149 ++++ apps/admin_console/routers/automations.py | 234 +++++++ apps/admin_console/routers/notifications.py | 141 ++++ apps/admin_console/routers/system.py | 31 + apps/admin_console/server.py | 45 +- .../services/automation_scheduler.py | 492 ++++++++++++++ .../services/automation_store.py | 198 ++++++ .../services/notification_watcher.py | 507 ++++++++++++++ .../services/settings_service.py | 11 +- .../services/task_queue_service.py | 8 + apps/showcase_ui/src/app/app.routes.ts | 4 + .../agent-stream/agent-stream.component.html | 264 +++---- .../agent-stream/agent-stream.component.ts | 191 +++--- .../chat-interface.component.html | 62 +- .../chat-interface.component.ts | 53 +- .../confirm-dialog.component.ts | 116 ++++ .../floating-video-player.component.html | 92 +-- .../floating-video-player.component.ts | 2 + .../legacy-agent-stream.component.html | 28 +- .../legacy-agent-stream.component.ts | 2 + .../nav-switcher/nav-switcher.component.scss | 1 + .../nav-switcher/nav-switcher.component.ts | 48 +- .../src/app/core/i18n/i18n.service.ts | 87 +++ .../src/app/core/i18n/i18n.types.ts | 21 + .../app/core/i18n/locales/en/automations.ts | 161 +++++ .../src/app/core/i18n/locales/en/chat.ts | 46 ++ .../src/app/core/i18n/locales/en/common.ts | 39 ++ .../src/app/core/i18n/locales/en/home.ts | 443 ++++++++++++ .../src/app/core/i18n/locales/en/index.ts | 49 ++ .../src/app/core/i18n/locales/en/nav.ts | 33 + .../app/core/i18n/locales/en/notifications.ts | 51 ++ .../src/app/core/i18n/locales/en/settings.ts | 38 ++ .../src/app/core/i18n/locales/en/stream.ts | 252 +++++++ .../src/app/core/i18n/locales/en/tasks.ts | 187 +++++ .../src/app/core/i18n/locales/en/video.ts | 75 ++ .../src/app/core/i18n/locales/en/workspace.ts | 36 + .../app/core/i18n/locales/zh/automations.ts | 161 +++++ .../src/app/core/i18n/locales/zh/chat.ts | 46 ++ .../src/app/core/i18n/locales/zh/common.ts | 39 ++ .../src/app/core/i18n/locales/zh/home.ts | 405 +++++++++++ .../src/app/core/i18n/locales/zh/index.ts | 49 ++ .../src/app/core/i18n/locales/zh/nav.ts | 33 + .../app/core/i18n/locales/zh/notifications.ts | 51 ++ .../src/app/core/i18n/locales/zh/settings.ts | 38 ++ .../src/app/core/i18n/locales/zh/stream.ts | 252 +++++++ .../src/app/core/i18n/locales/zh/tasks.ts | 177 +++++ .../src/app/core/i18n/locales/zh/video.ts | 75 ++ .../src/app/core/i18n/locales/zh/workspace.ts | 36 + .../automations/automations.component.html | 361 ++++++++++ .../automations/automations.component.scss | 632 +++++++++++++++++ .../automations/automations.component.ts | 636 +++++++++++++++++ .../src/app/pages/home/home.component.html | 525 ++++++++------ .../src/app/pages/home/home.component.scss | 175 +++++ .../src/app/pages/home/home.component.ts | 266 ++++++-- .../notifications.component.html | 121 ++++ .../notifications.component.scss | 306 +++++++++ .../notifications/notifications.component.ts | 287 ++++++++ .../pages/workspace/workspace.component.html | 20 +- .../pages/workspace/workspace.component.ts | 10 +- .../src/app/services/agent.service.ts | 18 +- .../src/app/services/settings.service.ts | 107 +++ .../src/app/services/system.service.ts | 10 +- .../src/app/utils/action-formatter.util.ts | 17 +- .../src/app/utils/run-info.util.ts | 7 + .../src/app/utils/tool-formatter.util.ts | 16 +- artemis/agents/flash/summarizer.py | 10 +- artemis/config/llm.py | 20 + artemis/data_engine/storage.py | 53 ++ artemis/drivers/android/adb_driver.py | 44 +- artemis/memory/chunking.py | 10 +- artemis/runtime/app_launcher.py | 63 ++ artemis/runtime/device_unlock.py | 100 +++ artemis/sdk/agent.py | 33 +- artemis/services/llm.py | 23 +- artemis/utils/video.py | 12 +- docs/PROJECT_MAP.md | 643 ++++++++++++++++++ 77 files changed, 9402 insertions(+), 683 deletions(-) create mode 100644 apps/admin_console/routers/apps.py create mode 100644 apps/admin_console/routers/automations.py create mode 100644 apps/admin_console/routers/notifications.py create mode 100644 apps/admin_console/services/automation_scheduler.py create mode 100644 apps/admin_console/services/automation_store.py create mode 100644 apps/admin_console/services/notification_watcher.py create mode 100644 apps/showcase_ui/src/app/components/confirm-dialog/confirm-dialog.component.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/i18n.service.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/i18n.types.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/automations.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/chat.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/common.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/home.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/index.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/nav.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/notifications.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/settings.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/stream.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/tasks.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/video.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/en/workspace.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/automations.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/chat.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/common.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/home.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/index.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/nav.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/notifications.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/settings.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/stream.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/tasks.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/video.ts create mode 100644 apps/showcase_ui/src/app/core/i18n/locales/zh/workspace.ts create mode 100644 apps/showcase_ui/src/app/pages/automations/automations.component.html create mode 100644 apps/showcase_ui/src/app/pages/automations/automations.component.scss create mode 100644 apps/showcase_ui/src/app/pages/automations/automations.component.ts create mode 100644 apps/showcase_ui/src/app/pages/notifications/notifications.component.html create mode 100644 apps/showcase_ui/src/app/pages/notifications/notifications.component.scss create mode 100644 apps/showcase_ui/src/app/pages/notifications/notifications.component.ts create mode 100644 apps/showcase_ui/src/app/services/settings.service.ts create mode 100644 artemis/runtime/app_launcher.py create mode 100644 artemis/runtime/device_unlock.py create mode 100644 docs/PROJECT_MAP.md diff --git a/apps/admin_console/core/state.py b/apps/admin_console/core/state.py index cc2c4a33c..fb02a2fd0 100644 --- a/apps/admin_console/core/state.py +++ b/apps/admin_console/core/state.py @@ -57,6 +57,7 @@ def __init__(self): self._wake_event: asyncio.Event | None = None self._shutdown_event: asyncio.Event | None = None self.worker_task: asyncio.Task | None = None + self.automation_scheduler_task: asyncio.Task | None = None @property def wake_event(self) -> asyncio.Event: diff --git a/apps/admin_console/routers/apps.py b/apps/admin_console/routers/apps.py new file mode 100644 index 000000000..9872b8bbf --- /dev/null +++ b/apps/admin_console/routers/apps.py @@ -0,0 +1,149 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Installed-app inventory for the automation app picker. + +Android does not expose an app's display name over adb: ``dumpsys package`` and +``pm dump`` only return a ``labelRes`` resource id (and MIUI strips even that). +So the picker gets the third-party package list from the device and resolves +display names from two sources instead: + +- built-in dictionaries in the frontend (i18n / APP_REGISTRY), and +- user-supplied labels persisted here under ``app_label.``. +""" + +from __future__ import annotations + +import asyncio +import subprocess +import time +from typing import Any + +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel + +from artemis.runtime.adb_endpoint import adb_command +from artemis.runtime.app_launcher import launch_package +from artemis.runtime.device_pool import device_pool + +try: + from admin_console.services.settings_service import settings_service +except ImportError: # pragma: no cover - import path differs when run as a package + from apps.admin_console.services.settings_service import settings_service + + +router = APIRouter(prefix="/api/apps", tags=["apps"]) + +_LABEL_PREFIX = "app_label." +_CACHE_TTL_SECONDS = 300.0 +_ADB_TIMEOUT_SECONDS = 20.0 +# System packages that still show up under "third-party" on some ROMs. +_SYSTEM_PREFIXES = ( + "com.miui.", + "com.mediatek.", + "com.android.internal.", + "com.android.cts.", + "com.google.android.syncadapters.", +) +_package_cache: dict[str, tuple[float, list[str]]] = {} + + +class AppLabelPayload(BaseModel): + label: str = "" + + +def _pick_serial() -> str | None: + try: + devices = device_pool.get_ready_devices() + except Exception: + return None + return devices[0].serial if devices else None + + +def _run_pm_list(serial: str, *extra: str) -> list[str]: + try: + completed = subprocess.run( + adb_command(["-s", serial, "shell", "pm", "list", "packages", *extra]), + capture_output=True, + text=True, + timeout=_ADB_TIMEOUT_SECONDS, + ) + except Exception: + return [] + return [ + line.split("package:", 1)[1].strip() + for line in (completed.stdout or "").splitlines() + if line.startswith("package:") and line.split("package:", 1)[1].strip() + ] + + +def _packages(serial: str | None, refresh: bool = False) -> dict[str, list[str]]: + """Every installed package plus the third-party subset. + + The picker needs the full list: some ROMs ship the messaging apps the user + cares about as system packages, so restricting to ``-3`` hides them. + """ + empty = {"apps": [], "third_party": []} + if not serial: + return empty + cached = _package_cache.get(serial) + if cached and not refresh and time.time() - cached[0] < _CACHE_TTL_SECONDS: + return cached[1] + apps = _run_pm_list(serial) + third = _run_pm_list(serial, "-3") + # Some ROMs report system components under "-3"; drop them from the + # "third-party" hint but keep them in the full list. + third = [p for p in third if not p.startswith(_SYSTEM_PREFIXES)] + payload = {"apps": apps, "third_party": third} + _package_cache[serial] = (time.time(), payload) + return payload + + +@router.get("") +async def list_apps(refresh: bool = False): + """Every installed package, the third-party subset, and user labels.""" + serial = await asyncio.to_thread(_pick_serial) + packages = await asyncio.to_thread(_packages, serial, refresh) + settings: dict[str, Any] = await asyncio.to_thread(settings_service.get_all) + labels = { + key[len(_LABEL_PREFIX) :]: value + for key, value in settings.items() + if key.startswith(_LABEL_PREFIX) and isinstance(value, str) and value.strip() + } + return { + "device_serial": serial, + "apps": packages["apps"], + "third_party": packages["third_party"], + "labels": labels, + } + + +@router.put("/labels/{package}") +async def set_app_label(package: str, payload: AppLabelPayload): + """Save a display name for a package; an empty label clears the override.""" + label = payload.label.strip() + await asyncio.to_thread(settings_service.update, {f"{_LABEL_PREFIX}{package}": label}) + return {"package": package, "label": label} + + +@router.post("/{package}/launch") +async def launch_app(package: str): + """Open an installed app on the phone so the user can confirm what it is.""" + serial = await asyncio.to_thread(_pick_serial) + if not serial: + raise HTTPException(status_code=400, detail="No device is connected.") + launched = await asyncio.to_thread(launch_package, serial, package) + if not launched: + raise HTTPException(status_code=400, detail=f"Could not launch {package}.") + return {"package": package, "launched": True} diff --git a/apps/admin_console/routers/automations.py b/apps/admin_console/routers/automations.py new file mode 100644 index 000000000..5383d7feb --- /dev/null +++ b/apps/admin_console/routers/automations.py @@ -0,0 +1,234 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Automation (scheduled / device-watch) management API.""" + +from __future__ import annotations + +from datetime import datetime +import re +from typing import Any + +from fastapi import APIRouter, HTTPException + +try: + from admin_console.services.automation_scheduler import ( + build_probe_argv, + compute_next_run, + ) + from admin_console.services.automation_store import TRIGGER_TYPES, automation_store + from admin_console.services.task_queue_service import task_queue_service +except ImportError: # pragma: no cover + from apps.admin_console.services.automation_scheduler import ( + build_probe_argv, + compute_next_run, + ) + from apps.admin_console.services.automation_store import TRIGGER_TYPES, automation_store + from apps.admin_console.services.task_queue_service import task_queue_service + + +router = APIRouter(prefix="/api/automations", tags=["automations"]) + +_TIME_RE = re.compile(r"^(\d{1,2}):(\d{2})$") +_PACKAGE_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$") + + +def _is_valid_time(value: Any) -> bool: + """True for a 'HH:MM' clock time within 00:00-23:59.""" + match = _TIME_RE.match(str(value).strip()) + if not match: + return False + hour, minute = int(match.group(1)), int(match.group(2)) + return 0 <= hour <= 23 and 0 <= minute <= 59 + + +def _validate_payload(payload: dict[str, Any], *, partial: dict[str, Any] | None = None) -> None: + """Validate a create/update payload, merging over an existing record for updates.""" + merged = {**(partial or {}), **payload} + trigger_type = merged.get("trigger_type") + if trigger_type not in TRIGGER_TYPES: + raise HTTPException( + status_code=400, + detail=f"trigger_type must be one of {', '.join(TRIGGER_TYPES)}.", + ) + goal = (merged.get("goal") or "").strip() + if not goal: + raise HTTPException(status_code=400, detail="goal must not be empty.") + if merged.get("profile") not in (None, "flash", "pro"): + raise HTTPException(status_code=400, detail="profile must be 'flash' or 'pro'.") + + config = merged.get("trigger_config") or {} + if trigger_type == "daily": + raw_times = config.get("times") or [] + invalid = [t for t in raw_times if not _is_valid_time(t)] + if invalid: + raise HTTPException( + status_code=400, + detail=f"Invalid time(s) {invalid!r}: expected 'HH:MM' between 00:00 and 23:59.", + ) + if not raw_times: + raise HTTPException( + status_code=400, detail="daily trigger needs at least one 'HH:MM' time." + ) + elif trigger_type == "interval": + try: + if int(config.get("minutes", 0)) < 1: + raise ValueError + except (TypeError, ValueError): + raise HTTPException( + status_code=400, detail="interval trigger needs 'minutes' >= 1." + ) from None + elif trigger_type == "watch": + try: + build_probe_argv(str(config.get("probe") or ""), config.get("params") or {}) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + pattern = config.get("pattern") + if not pattern: + raise HTTPException(status_code=400, detail="watch trigger needs a 'pattern' regex.") + try: + re.compile(str(pattern)) + except re.error as exc: + raise HTTPException(status_code=400, detail=f"Invalid pattern regex: {exc}") from exc + elif trigger_type == "notification": + packages = config.get("packages") or [] + if not isinstance(packages, list): + raise HTTPException( + status_code=400, detail="notification trigger 'packages' must be a list." + ) + invalid = [p for p in packages if not _PACKAGE_RE.match(str(p))] + if invalid: + raise HTTPException( + status_code=400, + detail=f"Invalid package name(s) {invalid!r}: expected e.g. 'com.tencent.mm'.", + ) + pattern = config.get("pattern") + if pattern: + try: + re.compile(str(pattern)) + except re.error as exc: + raise HTTPException( + status_code=400, detail=f"Invalid pattern regex: {exc}" + ) from exc + try: + if float(config.get("cooldown_seconds", 60)) < 0: + raise ValueError + except (TypeError, ValueError): + raise HTTPException( + status_code=400, detail="notification trigger 'cooldown_seconds' must be >= 0." + ) from None + if config.get("keep_alive"): + try: + if int(config.get("keep_alive_interval_seconds", 60)) < 30: + raise ValueError + except (TypeError, ValueError): + raise HTTPException( + status_code=400, + detail="notification trigger 'keep_alive_interval_seconds' must be >= 30.", + ) from None + elif trigger_type == "app_alive": + packages = config.get("packages") or [] + if not isinstance(packages, list) or not packages: + raise HTTPException( + status_code=400, + detail="app_alive trigger needs a non-empty 'packages' list.", + ) + invalid = [p for p in packages if not _PACKAGE_RE.match(str(p))] + if invalid: + raise HTTPException( + status_code=400, + detail=f"Invalid package name(s) {invalid!r}: expected e.g. 'com.tencent.mm'.", + ) + try: + if int(config.get("interval_seconds", 60)) < 30: + raise ValueError + except (TypeError, ValueError): + raise HTTPException( + status_code=400, + detail="app_alive trigger 'interval_seconds' must be >= 30.", + ) from None + if str(config.get("on_dead") or "restart") not in ("restart", "alert"): + raise HTTPException( + status_code=400, detail="app_alive trigger 'on_dead' must be 'restart' or 'alert'." + ) + + +def _prepare(payload: dict[str, Any], *, is_new: bool) -> dict[str, Any]: + cleaned = { + "name": (payload.get("name") or "").strip(), + "enabled": bool(payload.get("enabled", True)), + "trigger_type": payload["trigger_type"], + "trigger_config": payload.get("trigger_config") or {}, + "goal": payload["goal"].strip(), + "profile": payload.get("profile") or "flash", + "device_serial": payload.get("device_serial") or None, + } + if is_new or "trigger_type" in payload or "trigger_config" in payload: + cleaned["next_run_at"] = compute_next_run( + cleaned["trigger_type"], cleaned["trigger_config"], datetime.now() + ) + return cleaned + + +@router.get("") +async def list_automations(): + return {"automations": automation_store.list()} + + +@router.post("") +async def create_automation(payload: dict): + _validate_payload(payload) + return automation_store.create(_prepare(payload, is_new=True)) + + +@router.get("/{automation_id}") +async def get_automation(automation_id: str): + automation = automation_store.get(automation_id) + if automation is None: + raise HTTPException(status_code=404, detail="Automation not found.") + return automation + + +@router.put("/{automation_id}") +async def update_automation(automation_id: str, payload: dict): + current = automation_store.get(automation_id) + if current is None: + raise HTTPException(status_code=404, detail="Automation not found.") + _validate_payload(payload, partial=current) + updated = automation_store.update(automation_id, _prepare({**current, **payload}, is_new=False)) + return updated + + +@router.delete("/{automation_id}") +async def delete_automation(automation_id: str): + if not automation_store.delete(automation_id): + raise HTTPException(status_code=404, detail="Automation not found.") + return {"status": "deleted", "automation_id": automation_id} + + +@router.post("/{automation_id}/run-now") +async def run_automation_now(automation_id: str): + """Submit the automation's goal immediately, bypassing its schedule.""" + automation = automation_store.get(automation_id) + if automation is None: + raise HTTPException(status_code=404, detail="Automation not found.") + result = await task_queue_service.enqueue_tasks( + [automation["goal"]], + profile=automation.get("profile") or "flash", + device_serial=automation.get("device_serial"), + ingress="automation", + ) + tasks = result.get("tasks") or [] + session_id = str(tasks[0].get("session_id") or "") if tasks else "" + return {"status": "queued", "session_id": session_id, "automation_id": automation_id} diff --git a/apps/admin_console/routers/notifications.py b/apps/admin_console/routers/notifications.py new file mode 100644 index 000000000..68d7c9992 --- /dev/null +++ b/apps/admin_console/routers/notifications.py @@ -0,0 +1,141 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Read-only view over the captured device notification stream.""" + +from __future__ import annotations + +import sqlite3 +from typing import Any + +from fastapi import APIRouter, Query + +try: + from admin_console.database.connection import db_session + from admin_console.services.notification_watcher import notification_watcher +except ImportError: # pragma: no cover - import path differs when run as a package + from apps.admin_console.database.connection import db_session + from apps.admin_console.services.notification_watcher import notification_watcher + + +router = APIRouter(prefix="/api/notifications", tags=["notifications"]) + +_BASELINE_MARKER = "__baseline__" +_EXPIRED_MARKER = "__expired__" + + +def _row_to_dict(row: Any) -> dict[str, Any]: + session_id = row["dispatched_session_id"] + if session_id == _BASELINE_MARKER: + state = "baseline" + elif session_id == _EXPIRED_MARKER: + state = "expired" + elif session_id: + state = "dispatched" + else: + state = "pending" + return { + "fingerprint": row["fingerprint"], + "device_serial": row["device_serial"], + "package": row["package"], + "session_key": row["session_key"], + "title": row["title"] or "", + "text": row["text"] or "", + "captured_at": row["captured_at"], + "is_group_summary": bool(row["is_group_summary"]), + "state": state, + "session_id": None if state in ("baseline", "expired", "pending") else session_id, + "automation_id": row["automation_id"], + "automation_name": row["automation_name"] or "", + } + + +@router.get("") +async def list_notifications( + limit: int = Query(200, ge=1, le=1000), + package: str | None = Query(None), + state: str | None = Query(None), + automation_id: str | None = Query(None), +): + """Newest captured notifications, optionally filtered by app, state or rule.""" + clauses: list[str] = [] + params: list[Any] = [] + if package: + clauses.append("n.package = ?") + params.append(package) + if automation_id: + clauses.append("n.automation_id = ?") + params.append(automation_id) + if state == "pending": + clauses.append("n.dispatched_session_id IS NULL") + elif state == "dispatched": + clauses.append( + "n.dispatched_session_id IS NOT NULL " + "AND n.dispatched_session_id NOT IN (?, ?)" + ) + params.extend([_BASELINE_MARKER, _EXPIRED_MARKER]) + elif state == "baseline": + clauses.append("n.dispatched_session_id = ?") + params.append(_BASELINE_MARKER) + elif state == "expired": + clauses.append("n.dispatched_session_id = ?") + params.append(_EXPIRED_MARKER) + + where = f"WHERE {' AND '.join(clauses)}" if clauses else "" + query = ( + "SELECT n.fingerprint, n.device_serial, n.package, n.session_key, n.title, " + "n.text, n.captured_at, n.is_group_summary, n.dispatched_session_id, " + "n.automation_id, a.name AS automation_name " + "FROM device_notifications n " + "LEFT JOIN automations a ON a.automation_id = n.automation_id " + f"{where} ORDER BY n.captured_at DESC LIMIT ?" + ) + with db_session() as conn: + conn.row_factory = sqlite3.Row + rows = conn.execute(query, (*params, limit)).fetchall() + return {"notifications": [_row_to_dict(row) for row in rows]} + + +@router.get("/packages") +async def list_notification_packages(limit: int = Query(100, ge=1, le=500)): + """Packages seen in the stream, most recent first, with their counts.""" + query = ( + "SELECT package, COUNT(*) AS total, MAX(captured_at) AS last_at " + "FROM device_notifications WHERE package IS NOT NULL AND package != '' " + "GROUP BY package ORDER BY last_at DESC LIMIT ?" + ) + with db_session() as conn: + conn.row_factory = sqlite3.Row + rows = conn.execute(query, (limit,)).fetchall() + return { + "packages": [ + {"package": row["package"], "total": row["total"], "last_at": row["last_at"]} + for row in rows + ] + } + + +@router.delete("") +async def clear_notifications(): + """Drop the whole captured stream. + + The watcher's baseline is reset too, so whatever is still sitting in the + shade is re-recorded as history on the next poll rather than firing the + automations again. + """ + with db_session() as conn: + cursor = conn.execute("DELETE FROM device_notifications") + conn.commit() + notification_watcher.reset_baseline() + return {"status": "cleared", "deleted": cursor.rowcount} diff --git a/apps/admin_console/routers/system.py b/apps/admin_console/routers/system.py index deb3ae038..ead91818d 100644 --- a/apps/admin_console/routers/system.py +++ b/apps/admin_console/routers/system.py @@ -14,6 +14,7 @@ """System Readiness & Diagnostics Router for Artemis Admin Console.""" +import asyncio import ipaddress import os import secrets @@ -519,6 +520,36 @@ async def update_settings(payload: dict): return {"settings": merged} +@router.post("/device/unlock") +async def test_device_unlock(): + """Try the stored PIN against the current device so the operator can verify it.""" + try: + from apps.admin_console.services.settings_service import settings_service + except ImportError: + from admin_console.services.settings_service import settings_service + from artemis.runtime.device_pool import device_pool + from artemis.runtime.device_unlock import is_device_locked, unlock_with_pin + + try: + devices = device_pool.get_ready_devices() + except Exception: + devices = [] + serial = devices[0].serial if devices else None + if not serial: + raise HTTPException(status_code=400, detail="No device is connected.") + + locked_before = await asyncio.to_thread(is_device_locked, serial) + if not locked_before: + return {"ok": True, "alreadyUnlocked": True, "locked": False} + + pin = str(settings_service.get("device_unlock_pin", "") or "").strip() + if not pin: + raise HTTPException(status_code=400, detail="No lock-screen PIN is configured.") + + ok = await asyncio.to_thread(unlock_with_pin, serial, pin) + return {"ok": ok, "alreadyUnlocked": False, "locked": await asyncio.to_thread(is_device_locked, serial)} + + @router.get("/server-status") async def get_server_runtime_status(): """Retrieve runtime status, PID, port, and uptime of the Artemis server. diff --git a/apps/admin_console/server.py b/apps/admin_console/server.py index 151bb827b..0f9252a18 100644 --- a/apps/admin_console/server.py +++ b/apps/admin_console/server.py @@ -77,20 +77,46 @@ from admin_console.database.repositories.session_repository import session_repo from admin_console.database.repositories.step_repository import step_repo from admin_console.database.repositories.trace_repository import trace_repo - from admin_console.routers import media, replay, sessions, steps, stream, system, tasks + from admin_console.routers import ( + apps, + automations, + media, + notifications, + replay, + sessions, + steps, + stream, + system, + tasks, + ) from admin_console.routers.replay import replay_manager + from admin_console.services.automation_scheduler import automation_scheduler from admin_console.services.ipc_service import ipc_service from admin_console.services.media_service import media_service from admin_console.services.model_service import model_service + from admin_console.services.notification_watcher import notification_watcher from admin_console.services.task_queue_service import task_queue_service except ImportError: from apps.admin_console.core.security import SameOriginBoundaryMiddleware from apps.admin_console.core.state import state from apps.admin_console.database.repositories.session_repository import session_repo - from apps.admin_console.routers import media, replay, sessions, steps, stream, system, tasks + from apps.admin_console.routers import ( + apps, + automations, + media, + notifications, + replay, + sessions, + steps, + stream, + system, + tasks, + ) from apps.admin_console.routers.replay import replay_manager + from apps.admin_console.services.automation_scheduler import automation_scheduler from apps.admin_console.services.ipc_service import ipc_service from apps.admin_console.services.model_service import model_service + from apps.admin_console.services.notification_watcher import notification_watcher from apps.admin_console.services.task_queue_service import task_queue_service # Initialize language server synchronization address @@ -159,6 +185,12 @@ async def on_startup(): await ipc_service.start_server() state.worker_task = asyncio.create_task(task_queue_service.queue_worker()) + # Scheduler for persisted automations (daily / interval / watch triggers). + # Runs beside the queue worker and only enqueues goals when devices are free. + state.automation_scheduler_task = asyncio.create_task(automation_scheduler.start()) + # Event source for `notification` triggers: polls the shade over adb and + # dispatches matching automations itself. + state.notification_watcher_task = asyncio.create_task(notification_watcher.start()) async def on_shutdown(): @@ -181,6 +213,12 @@ async def on_shutdown(): pass state.worker_task = None + # Stop the automation scheduler loop before tearing down the queue. + await automation_scheduler.stop() + state.automation_scheduler_task = None + await notification_watcher.stop() + state.notification_watcher_task = None + # Cancel in-flight run coroutines and wait for their finalizers (DB status, # session_ended broadcast, trace sync, recording recovery) to run. run_tasks = [t for t in list(task_queue_service._run_tasks) if not t.done()] @@ -224,6 +262,9 @@ async def on_shutdown(): app.include_router(tasks.router) app.include_router(replay.router) app.include_router(system.router) +app.include_router(automations.router) +app.include_router(notifications.router) +app.include_router(apps.router) # Mount cloud gateway router for Frappe / Cloud integration if present try: diff --git a/apps/admin_console/services/automation_scheduler.py b/apps/admin_console/services/automation_scheduler.py new file mode 100644 index 000000000..66e838d2e --- /dev/null +++ b/apps/admin_console/services/automation_scheduler.py @@ -0,0 +1,492 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Background scheduler that turns durable automation definitions into tasks. + +Three structured trigger shapes are supported: + +- ``daily`` — fire at one or more wall-clock times (``HH:MM``), optionally on + selected weekdays. ``{"times": ["03:00", "05:00"], "weekdays": [1, 2, 3]}``. +- ``interval`` — fire every N minutes. ``{"minutes": 30}``. +- ``watch`` — poll a read-only ADB probe and fire when its output matches a + regex (zero LLM cost). ``{"probe": "notifications", "params": {...}, + "pattern": "...", "poll_seconds": 60}``. + +Scheduling never competes with a running user task: every dispatch first checks +the device lease and yields ("自动化让路") until the phone is free. +""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, timedelta +import re +import subprocess +from typing import Any + +from artemis.runtime import DeviceExecutionLock +from artemis.runtime.adb_endpoint import adb_command +from artemis.runtime.app_launcher import launch_package + +try: + from admin_console.services.automation_store import automation_store + from admin_console.services.task_queue_service import task_queue_service +except ImportError: # pragma: no cover - import path differs when run as a package + from apps.admin_console.services.automation_store import automation_store + from apps.admin_console.services.task_queue_service import task_queue_service + + +# Read-only probe templates mirrored from the Checker's enumerated probe table. +_PROBE_ARGS: dict[str, tuple[str, ...]] = { + "alarms": ("dumpsys", "alarm"), + "battery": ("dumpsys", "battery"), + "foreground": ("dumpsys", "activity", "activities"), + "notifications": ("dumpsys", "notification"), + "packages": ("pm", "list", "packages"), +} +_KEY_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,128}$") +_URI_RE = re.compile(r"^content://[A-Za-z0-9./_-]+$") +_SETTING_NAMESPACES = frozenset({"system", "secure", "global"}) + +TICK_SECONDS = 15.0 +_PROBE_TIMEOUT_SECONDS = 20.0 +_DEFAULT_POLL_SECONDS = 60 +_DEFAULT_COOLDOWN_SECONDS = 60 + + +def _now() -> datetime: + return datetime.now() + + +def build_probe_argv(probe: str, params: dict[str, Any] | None = None) -> list[str]: + """Build the argv for a watch probe, rejecting anything not enumerated.""" + params = dict(params or {}) + if probe in _PROBE_ARGS: + if params: + raise ValueError(f"Probe '{probe}' accepts no parameters.") + return list(_PROBE_ARGS[probe]) + if probe == "setting": + namespace, key = params.get("namespace"), params.get("key") + if namespace not in _SETTING_NAMESPACES or not isinstance(key, str) or not _KEY_RE.match(key): + raise ValueError("Probe 'setting' needs namespace in system|secure|global and a valid key.") + return ["settings", "get", namespace, key] + if probe == "content": + uri = params.get("uri") + if not isinstance(uri, str) or not _URI_RE.match(uri): + raise ValueError("Probe 'content' needs a valid content:// uri.") + return ["content", "query", "--uri", uri] + if probe == "prop": + key = params.get("key") + if not isinstance(key, str) or not _KEY_RE.match(key): + raise ValueError("Probe 'prop' needs a valid key.") + return ["getprop", key] + raise ValueError(f"Unknown probe '{probe}'.") + + +def compute_next_run( + trigger_type: str, + trigger_config: dict[str, Any], + after: datetime | None = None, +) -> float | None: + """Return the next fire time (epoch seconds) strictly after ``after``.""" + after = after or _now() + if trigger_type == "interval": + try: + minutes = max(1, int(trigger_config.get("minutes", 30))) + except (TypeError, ValueError): + minutes = 30 + return (after + timedelta(minutes=minutes)).timestamp() + + if trigger_type == "daily": + times = _normalized_times(trigger_config) + if not times: + return None + weekdays = _normalized_weekdays(trigger_config) + for day_offset in range(0, 8): + day = (after + timedelta(days=day_offset)).date() + if weekdays and day.isoweekday() not in weekdays: + continue + for clock in times: + candidate = datetime.combine(day, clock) + if candidate > after: + return candidate.timestamp() + return None + + if trigger_type == "watch": + poll = _int_setting(trigger_config, "poll_seconds", _DEFAULT_POLL_SECONDS, minimum=5) + return (after + timedelta(seconds=poll)).timestamp() + + if trigger_type == "app_alive": + interval = _int_setting(trigger_config, "interval_seconds", 60, minimum=30) + return (after + timedelta(seconds=interval)).timestamp() + + if trigger_type == "notification" and trigger_config.get("keep_alive"): + interval = _int_setting( + trigger_config, "keep_alive_interval_seconds", 60, minimum=30 + ) + return (after + timedelta(seconds=interval)).timestamp() + + return None + + +def _normalized_times(trigger_config: dict[str, Any]) -> list[Any]: + from datetime import time as _time + + times: list[Any] = [] + for raw in trigger_config.get("times", []) or []: + match = re.match(r"^(\d{1,2}):(\d{2})$", str(raw).strip()) + if not match: + continue + hour, minute = int(match.group(1)), int(match.group(2)) + if 0 <= hour <= 23 and 0 <= minute <= 59: + times.append(_time(hour=hour, minute=minute)) + return sorted(set(times)) + + +def _normalized_weekdays(trigger_config: dict[str, Any]) -> set[int]: + weekdays = set() + for raw in trigger_config.get("weekdays", []) or []: + try: + value = int(raw) + except (TypeError, ValueError): + continue + if 1 <= value <= 7: + weekdays.add(value) + return weekdays + + +def _int_setting(config: dict[str, Any], key: str, default: int, *, minimum: int = 0) -> int: + try: + return max(minimum, int(config.get(key, default))) + except (TypeError, ValueError): + return default + + +class AutomationScheduler: + """Persistent asyncio loop that fires due automations.""" + + def __init__(self) -> None: + self._task: asyncio.Task | None = None + self._in_flight: set[str] = set() + self._last_fire_at: dict[str, float] = {} + self._restart_history: dict[str, list[float]] = {} + + async def start(self) -> asyncio.Task: + if self._task is None or self._task.done(): + self._task = asyncio.create_task(self._run_forever()) + return self._task + + async def stop(self) -> None: + task = self._task + self._task = None + if task is not None and not task.done(): + task.cancel() + try: + await task + except (asyncio.CancelledError, Exception): + pass + + async def _run_forever(self) -> None: + print("[Automation] Scheduler started.") + try: + while True: + try: + await self._tick() + except Exception as exc: # keep the loop alive on any single failure + print(f"[Automation] Tick error: {exc}") + await asyncio.sleep(TICK_SECONDS) + except asyncio.CancelledError: + print("[Automation] Scheduler stopped.") + raise + + async def _tick(self) -> None: + automations = await asyncio.to_thread(automation_store.list, True) + now = _now() + now_ts = now.timestamp() + for automation in automations: + automation_id = automation["automation_id"] + if automation_id in self._in_flight: + continue + # Event-driven automations are fired by their own event source + # (see notification_watcher); this loop only handles their optional + # keep-alive side job. + if automation["trigger_type"] == "notification": + config = automation.get("trigger_config") or {} + if config.get("keep_alive"): + next_run_at = automation.get("next_run_at") + if next_run_at is None: + await asyncio.to_thread( + automation_store.set_next_run, + automation_id, + compute_next_run("notification", config, now), + ) + continue + if next_run_at > now_ts: + continue + await self._handle_app_alive(automation, now, keep_alive=True) + continue + next_run_at = automation.get("next_run_at") + if next_run_at is None: + # First sighting (e.g. created before the scheduler existed): + # establish a baseline instead of firing immediately. + next_at = compute_next_run( + automation["trigger_type"], automation.get("trigger_config") or {}, now + ) + await asyncio.to_thread(automation_store.set_next_run, automation_id, next_at) + continue + if next_run_at > now_ts: + continue + + if automation["trigger_type"] == "watch": + await self._handle_watch(automation, now) + elif automation["trigger_type"] == "app_alive": + await self._handle_app_alive(automation, now) + else: + await self._handle_schedule(automation, now) + + async def _handle_schedule(self, automation: dict[str, Any], now: datetime) -> None: + trigger_type = automation["trigger_type"] + config = automation.get("trigger_config") or {} + next_at = compute_next_run(trigger_type, config, now) + fired = await self._dispatch(automation) + if fired: + await asyncio.to_thread( + automation_store.record_run, + automation["automation_id"], + status="dispatched", + session_id=fired, + next_run_at=next_at, + ) + else: + # Device busy: keep the definition due and retry on the next tick. + pass + + async def _handle_watch(self, automation: dict[str, Any], now: datetime) -> None: + automation_id = automation["automation_id"] + config = automation.get("trigger_config") or {} + poll = _int_setting(config, "poll_seconds", _DEFAULT_POLL_SECONDS, minimum=5) + cooldown = _int_setting(config, "cooldown_seconds", _DEFAULT_COOLDOWN_SECONDS, minimum=0) + next_at = (now + timedelta(seconds=poll)).timestamp() + + matched = False + try: + output = await self._run_probe(config, automation.get("device_serial")) + pattern = config.get("pattern") or "" + matched = bool(pattern) and re.search(pattern, output, re.MULTILINE) is not None + except Exception as exc: + await asyncio.to_thread( + automation_store.record_run, + automation_id, + status="probe_error", + error=str(exc), + next_run_at=next_at, + ) + return + + if not matched: + await asyncio.to_thread(automation_store.set_next_run, automation_id, next_at) + return + + last_fire = self._last_fire_at.get(automation_id, 0.0) + if now.timestamp() - last_fire < cooldown: + await asyncio.to_thread(automation_store.set_next_run, automation_id, next_at) + return + + session_id = await self._dispatch(automation) + if session_id: + self._last_fire_at[automation_id] = now.timestamp() + await asyncio.to_thread( + automation_store.record_run, + automation_id, + status="triggered", + session_id=session_id, + next_run_at=next_at, + ) + else: + # Matched but the device is busy; retry shortly. + await asyncio.to_thread(automation_store.set_next_run, automation_id, next_at) + + async def _handle_app_alive( + self, automation: dict[str, Any], now: datetime, *, keep_alive: bool = False + ) -> None: + """Probe watched packages with ``pidof`` and revive them when asked. + + Pure adb, no LLM. Restarts are rate limited per automation so a package + that crashes on launch cannot turn into a launch loop, and they are + skipped entirely while a human task holds the device. + + ``keep_alive`` runs the same probe as a side job of a notification + automation; a healthy result stays silent so it does not overwrite the + notification rule's own last status. + """ + automation_id = automation["automation_id"] + config = automation.get("trigger_config") or {} + interval_key = "keep_alive_interval_seconds" if keep_alive else "interval_seconds" + interval = _int_setting(config, interval_key, 60, minimum=30) + next_at = (now + timedelta(seconds=interval)).timestamp() + packages = [str(p).strip() for p in (config.get("packages") or []) if str(p).strip()] + if not packages: + if keep_alive: + # Watching every app is the normal notification mode; there is + # nothing concrete to keep alive. + await asyncio.to_thread(automation_store.set_next_run, automation_id, next_at) + return + await asyncio.to_thread( + automation_store.record_run, + automation_id, + status="config_error", + error="no packages configured", + next_run_at=next_at, + ) + return + + serial = automation.get("device_serial") + dead = [ + package + for package in packages + if not await asyncio.to_thread(self._is_package_alive, serial, package) + ] + if not dead: + if keep_alive: + await asyncio.to_thread(automation_store.set_next_run, automation_id, next_at) + return + await asyncio.to_thread( + automation_store.record_run, + automation_id, + status="alive", + next_run_at=next_at, + ) + return + + if self._device_busy(serial): + await asyncio.to_thread( + automation_store.record_run, + automation_id, + status="deferred_busy", + error=", ".join(f"{p}:dead" for p in dead), + next_run_at=next_at, + ) + return + + on_dead = str(config.get("on_dead") or "restart") + outcomes: list[str] = [] + for package in dead: + if on_dead != "restart": + outcomes.append(f"{package}:dead") + continue + if not self._allow_restart(automation_id, config, now.timestamp()): + outcomes.append(f"{package}:throttled") + continue + launched = await asyncio.to_thread(self._launch_package, serial, package) + outcomes.append(f"{package}:{'restarted' if launched else 'restart_failed'}") + + await asyncio.to_thread( + automation_store.record_run, + automation_id, + status="restarted" if all(o.endswith(":restarted") for o in outcomes) else "app_dead", + error=", ".join(outcomes), + next_run_at=next_at, + ) + + def _allow_restart( + self, automation_id: str, config: dict[str, Any], now_ts: float + ) -> bool: + limit = _int_setting(config, "max_restarts_per_hour", 3, minimum=1) + history = [t for t in self._restart_history.get(automation_id, []) if now_ts - t < 3600] + if len(history) >= limit: + self._restart_history[automation_id] = history + return False + history.append(now_ts) + self._restart_history[automation_id] = history + return True + + @staticmethod + def _is_package_alive(serial: str | None, package: str) -> bool: + base = ["-s", serial] if serial else [] + try: + completed = subprocess.run( + adb_command([*base, "shell", "pidof", package]), + capture_output=True, + text=True, + timeout=_PROBE_TIMEOUT_SECONDS, + ) + except Exception: + # Unknown state must never trigger a restart on its own. + return True + return bool((completed.stdout or "").strip()) + + @staticmethod + def _launch_package(serial: str | None, package: str) -> bool: + """Resolve the launcher activity and start it; True when adb accepted.""" + return launch_package(serial, package) + + async def _run_probe(self, config: dict[str, Any], device_serial: str | None) -> str: + argv = build_probe_argv(str(config.get("probe") or ""), config.get("params") or {}) + base = ["-s", device_serial] if device_serial else [] + command = adb_command([*base, "shell", *argv]) + completed = await asyncio.to_thread( + subprocess.run, + command, + capture_output=True, + text=True, + timeout=_PROBE_TIMEOUT_SECONDS, + ) + return completed.stdout or "" + + async def _dispatch(self, automation: dict[str, Any], goal: str | None = None) -> str | None: + """Submit the automation's goal, yielding while the device is busy.""" + automation_id = automation["automation_id"] + device_serial = automation.get("device_serial") + if self._device_busy(device_serial): + return None + + self._in_flight.add(automation_id) + try: + result = await task_queue_service.enqueue_tasks( + [goal or automation["goal"]], + profile=automation.get("profile") or "flash", + device_serial=device_serial, + ingress="automation", + ) + except Exception as exc: + print(f"[Automation] Dispatch failed for {automation_id}: {exc}") + return None + finally: + self._in_flight.discard(automation_id) + + tasks = result.get("tasks") or [] + if tasks: + return str(tasks[0].get("session_id") or "") + return "" + + async def dispatch_goal(self, automation: dict[str, Any], goal: str) -> str | None: + """Dispatch an already-rendered goal (used by event-driven triggers).""" + if automation["automation_id"] in self._in_flight: + return None + return await self._dispatch(automation, goal) + + @staticmethod + def _device_busy(device_serial: str | None) -> bool: + try: + owners = DeviceExecutionLock.get_active_owners() + except Exception: + return False + if not owners: + return False + if device_serial: + return device_serial in owners + return True + + +automation_scheduler = AutomationScheduler() diff --git a/apps/admin_console/services/automation_store.py b/apps/admin_console/services/automation_store.py new file mode 100644 index 000000000..fb0cff035 --- /dev/null +++ b/apps/admin_console/services/automation_store.py @@ -0,0 +1,198 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Persistence for automations (scheduled / event-triggered agent tasks). + +Unlike the in-memory task queue, automation *definitions* survive a daemon +restart so a daily job or a device watcher keeps firing after a reboot. +""" + +from __future__ import annotations + +import json +import time +from typing import Any +import uuid + +try: + from admin_console.database.connection import db_session +except ImportError: # pragma: no cover - import path differs when run as a package + from apps.admin_console.database.connection import db_session + + +TRIGGER_TYPES = ("daily", "interval", "watch", "notification", "app_alive") + + +def _row_to_dict(row: Any) -> dict[str, Any]: + config: Any = {} + raw_config = row["trigger_config"] + if raw_config: + try: + config = json.loads(raw_config) + except (ValueError, TypeError): + config = {} + return { + "automation_id": row["automation_id"], + "name": row["name"] or "", + "enabled": bool(row["enabled"]), + "trigger_type": row["trigger_type"], + "trigger_config": config, + "goal": row["goal"] or "", + "profile": row["profile"] or "flash", + "device_serial": row["device_serial"], + "last_run_at": row["last_run_at"], + "last_run_session_id": row["last_run_session_id"], + "last_status": row["last_status"], + "last_error": row["last_error"], + "next_run_at": row["next_run_at"], + "created_at": row["created_at"], + "updated_at": row["updated_at"], + } + + +class AutomationStore: + """CRUD over the ``automations`` table.""" + + def list(self, enabled_only: bool = False) -> list[dict[str, Any]]: + query = "SELECT * FROM automations" + if enabled_only: + query += " WHERE enabled = 1" + query += " ORDER BY created_at ASC" + with db_session() as conn: + rows = conn.execute(query).fetchall() + return [_row_to_dict(row) for row in rows] + + def get(self, automation_id: str) -> dict[str, Any] | None: + with db_session() as conn: + row = conn.execute( + "SELECT * FROM automations WHERE automation_id = ?", (automation_id,) + ).fetchone() + return _row_to_dict(row) if row is not None else None + + def create(self, payload: dict[str, Any]) -> dict[str, Any]: + now = time.time() + automation_id = str(payload.get("automation_id") or f"auto_{uuid.uuid4().hex[:12]}") + with db_session() as conn: + conn.execute( + """ + INSERT INTO automations ( + automation_id, name, enabled, trigger_type, trigger_config, + goal, profile, device_serial, next_run_at, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + automation_id, + payload.get("name") or "", + 1 if payload.get("enabled", True) else 0, + payload["trigger_type"], + json.dumps(payload.get("trigger_config") or {}), + payload.get("goal") or "", + payload.get("profile") or "flash", + payload.get("device_serial"), + payload.get("next_run_at"), + now, + now, + ), + ) + conn.commit() + return self.get(automation_id) # type: ignore[return-value] + + def update(self, automation_id: str, payload: dict[str, Any]) -> dict[str, Any] | None: + current = self.get(automation_id) + if current is None: + return None + fields: dict[str, Any] = { + "name": payload.get("name", current["name"]), + "enabled": 1 if payload.get("enabled", current["enabled"]) else 0, + "trigger_type": payload.get("trigger_type", current["trigger_type"]), + "trigger_config": json.dumps( + payload.get("trigger_config", current["trigger_config"]) or {} + ), + "goal": payload.get("goal", current["goal"]), + "profile": payload.get("profile", current["profile"]), + "device_serial": payload.get("device_serial", current["device_serial"]), + "next_run_at": payload.get("next_run_at", current["next_run_at"]), + "updated_at": time.time(), + } + with db_session() as conn: + conn.execute( + """ + UPDATE automations SET + name = :name, + enabled = :enabled, + trigger_type = :trigger_type, + trigger_config = :trigger_config, + goal = :goal, + profile = :profile, + device_serial = :device_serial, + next_run_at = :next_run_at, + updated_at = :updated_at + WHERE automation_id = :automation_id + """, + {**fields, "automation_id": automation_id}, + ) + conn.commit() + return self.get(automation_id) + + def delete(self, automation_id: str) -> bool: + with db_session() as conn: + cursor = conn.execute( + "DELETE FROM automations WHERE automation_id = ?", (automation_id,) + ) + conn.commit() + return cursor.rowcount > 0 + + def set_next_run(self, automation_id: str, next_run_at: float | None) -> None: + with db_session() as conn: + conn.execute( + "UPDATE automations SET next_run_at = ?, updated_at = ? WHERE automation_id = ?", + (next_run_at, time.time(), automation_id), + ) + conn.commit() + + def record_run( + self, + automation_id: str, + *, + status: str, + session_id: str | None = None, + error: str | None = None, + next_run_at: float | None = None, + ) -> None: + with db_session() as conn: + conn.execute( + """ + UPDATE automations SET + last_run_at = ?, + last_run_session_id = ?, + last_status = ?, + last_error = ?, + next_run_at = ?, + updated_at = ? + WHERE automation_id = ? + """, + ( + time.time(), + session_id, + status, + error, + next_run_at, + time.time(), + automation_id, + ), + ) + conn.commit() + + +automation_store = AutomationStore() diff --git a/apps/admin_console/services/notification_watcher.py b/apps/admin_console/services/notification_watcher.py new file mode 100644 index 000000000..89ca457a8 --- /dev/null +++ b/apps/admin_console/services/notification_watcher.py @@ -0,0 +1,507 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Device notification event source. + +Polls ``dumpsys notification --noredact`` (read-only, zero LLM cost) and turns +newly observed notifications into a durable event stream plus automation +triggers. Notification text is readable without root on this device class. + +Limitations of the dumpsys transport, by design of the first iteration: + +- It reflects the *current* notification shade, so a notification that is + posted and dismissed between two polls is missed. The helper-based + accessibility event stream (a later protocol version) closes that gap. +- Group summaries ("you have 3 new messages") are recorded but never trigger, + because they carry no per-conversation text. + +Everything is keyed by a content fingerprint, so a notification that survives +many polls only fires once, and a same-slot notification whose text changed +counts as a new event. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import re +import sqlite3 +import subprocess +import time +import traceback +from typing import Any + +from artemis.runtime.adb_endpoint import adb_command +from artemis.runtime.device_pool import device_pool + +try: + from admin_console.database.connection import db_session + from admin_console.services import automation_store as _automation_store_module +except ImportError: # pragma: no cover - import path differs when run as a package + from apps.admin_console.database.connection import db_session + from apps.admin_console.services import automation_store as _automation_store_module + +_DUMP_TIMEOUT_SECONDS = 20.0 +_DEFAULT_POLL_SECONDS = 5.0 +_MAX_CAPTURED_TEXT = 4000 +# Messages older than this are no longer worth answering: the daemon was down, +# the device was offline, or the sender moved on long ago. +_PENDING_TTL_SECONDS = 600.0 +# How far back pending rows are re-examined at all. +_FETCH_WINDOW_SECONDS = 86400.0 +BASELINE_MARKER = "__baseline__" +EXPIRED_MARKER = "__expired__" + +_RECORD_START_RE = re.compile(r"^\s*NotificationRecord\(") +_PKG_RE = re.compile(r"\bpkg=(\S+)") +_ID_RE = re.compile(r"\bid=(-?\d+)\b") +_TAG_RE = re.compile(r"\btag=(\S+)") +_KEY_RE = re.compile(r"\bkey=(\S+?):\s+Notification\(") +_FIELD_RE = re.compile(r"^\s*android\.(title|text|bigText)=(.+?)\s*$") +_STRING_VALUE_RE = re.compile(r"^(?:String|SpannableString|CharSequence)\s*\((.*)\)$", re.S) +_GROUP_SUMMARY_RE = re.compile(r"ranker_group") + + +def _clean_value(raw: str) -> str | None: + """Unwrap ``String (foo)`` / ``SpannableString (foo)`` dump values.""" + raw = raw.strip() + if not raw or raw == "null": + return None + match = _STRING_VALUE_RE.match(raw) + value = match.group(1) if match else raw + value = value.strip() + return value or None + + +def parse_dumpsys_notifications(output: str) -> list[dict[str, Any]]: + """Split ``dumpsys notification --noredact`` output into notification dicts. + + Only fields that are stable across Android versions are extracted: package, + notification id/tag/key, title, text and bigText. Anything else is noise for + our purposes. + """ + notifications: list[dict[str, Any]] = [] + current: dict[str, Any] | None = None + + def flush() -> None: + if current is None: + return + pkg = current.get("package") + if not pkg: + return + title = current.get("title") or "" + text = current.get("text") or current.get("bigText") or "" + key = current.get("note_key") or "" + summary = bool( + _GROUP_SUMMARY_RE.search(key) + or _GROUP_SUMMARY_RE.search(str(current.get("tag") or "")) + or "GroupSummary" in title + ) + fingerprint_source = "|".join( + [ + pkg, + str(current.get("note_id") or ""), + str(current.get("tag") or ""), + title, + text, + ] + ) + fingerprint = hashlib.sha256(fingerprint_source.encode("utf-8")).hexdigest()[:32] + # A conversation is the package plus its title (sender nickname for + # direct chats, group name for groups). Notifications without a title + # fall back to their own key so unrelated system posts never merge. + session_source = f"{pkg}|{title}" if title else f"{pkg}|{key}" + session_key = hashlib.sha256(session_source.encode("utf-8")).hexdigest()[:16] + notifications.append( + { + "fingerprint": fingerprint, + "package": pkg, + "session_key": session_key, + "note_id": current.get("note_id"), + "tag": current.get("tag"), + "note_key": key, + "title": title[:_MAX_CAPTURED_TEXT], + "text": text[:_MAX_CAPTURED_TEXT], + "is_group_summary": 1 if summary else 0, + } + ) + + for line in output.splitlines(): + if _RECORD_START_RE.match(line): + flush() + current = { + "package": (_PKG_RE.search(line) or [None, None])[1], + "note_id": (_ID_RE.search(line) or [None, None])[1], + "tag": (_TAG_RE.search(line) or [None, None])[1], + "note_key": (_KEY_RE.search(line) or [None, None])[1], + "title": None, + "text": None, + "bigText": None, + } + if current["tag"] == "null": + current["tag"] = None + continue + if current is None: + continue + field = _FIELD_RE.match(line) + if field: + name = "bigText" if field.group(1) == "bigText" else field.group(1) + current[name] = _clean_value(field.group(2)) + + flush() + return notifications + + +DRAFT_INSTRUCTION = ( + "\n\n约束:只把回复内容填入输入框,不要点击发送按钮;" + "完成后停留在该会话界面,由用户自行确认后发送。" +) + + +class NotificationWatcher: + """Polls the notification shade and dispatches matching automations.""" + + def __init__(self, poll_seconds: float = _DEFAULT_POLL_SECONDS) -> None: + self._poll_seconds = poll_seconds + self._task: asyncio.Task | None = None + self._primed: set[str] = set() + self._in_flight: set[str] = set() + self._no_device_warned = False + + def reset_baseline(self) -> None: + """Forget the primed state so the next poll records the current shade + as history instead of treating it as brand-new messages.""" + self._primed.clear() + + async def start(self) -> asyncio.Task: + if self._task is None or self._task.done(): + self._task = asyncio.create_task(self._run_forever()) + return self._task + + async def stop(self) -> None: + task = self._task + self._task = None + if task is not None and not task.done(): + task.cancel() + try: + await task + except (asyncio.CancelledError, Exception): + pass + + async def _run_forever(self) -> None: + print("[Notifications] Watcher started.", flush=True) + while True: + try: + await self._tick() + except asyncio.CancelledError: + print("[Notifications] Watcher stopped.", flush=True) + raise + except BaseException as exc: # never let one bad poll kill the loop + print( + f"[Notifications] Tick error: {exc!r}\n{traceback.format_exc()}", + flush=True, + ) + await asyncio.sleep(self._poll_seconds) + + async def _tick(self) -> None: + serials = await asyncio.to_thread(self._ready_serials) + if not serials: + if not self._no_device_warned: + print("[Notifications] No ready device; skipping poll.", flush=True) + self._no_device_warned = True + return + self._no_device_warned = False + for serial in serials: + try: + await self._poll_device(serial) + except asyncio.CancelledError: + raise + except BaseException as exc: + print( + f"[Notifications] Poll failed for {serial}: {exc!r}\n" + f"{traceback.format_exc()}", + flush=True, + ) + + @staticmethod + def _ready_serials() -> list[str]: + try: + devices = device_pool.get_ready_devices() + except Exception: + return [] + return [device.serial for device in devices if device.serial] + + async def _poll_device(self, serial: str) -> None: + output = await asyncio.to_thread(self._dump_notifications, serial) + notifications = parse_dumpsys_notifications(output) + allowed = await asyncio.to_thread(self._allowed_packages) + primed = serial in self._primed + for notification in notifications: + # Only the apps the operator actually monitors are recorded; the + # rest of the shade never enters the event stream at all. + if allowed is not None and notification["package"] not in allowed: + continue + await asyncio.to_thread( + self._record, + serial, + notification, + None if primed else BASELINE_MARKER, + ) + self._primed.add(serial) + await self._flush_ready_groups(serial) + + @staticmethod + def _allowed_packages() -> set[str] | None: + """Packages watched by an enabled notification rule. + + ``None`` means "every app": at least one rule left its app list empty, + which the UI documents as monitoring the whole phone. + """ + store = _automation_store_module.automation_store + allowed: set[str] = set() + for automation in store.list(True): + if automation.get("trigger_type") != "notification": + continue + packages = (automation.get("trigger_config") or {}).get("packages") or [] + if not packages: + return None + allowed.update(str(p) for p in packages) + return allowed + + @staticmethod + def _dump_notifications(serial: str) -> str: + command = adb_command(["-s", serial, "shell", "dumpsys", "notification", "--noredact"]) + completed = subprocess.run( + command, + capture_output=True, + text=True, + timeout=_DUMP_TIMEOUT_SECONDS, + ) + return completed.stdout or "" + + @staticmethod + def _record(serial: str, notification: dict[str, Any], marker: str | None) -> bool: + """Insert the notification; True when it had not been seen before. + + ``marker`` pre-marks the row as already handled (the first poll after + boot batches the existing shade as history). + """ + now = time.time() + with db_session() as conn: + cursor = conn.execute( + """ + INSERT OR IGNORE INTO device_notifications ( + fingerprint, device_serial, package, session_key, title, text, + note_key, posted_at, captured_at, is_group_summary, + dispatched_session_id + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + notification["fingerprint"], + serial, + notification["package"], + notification["session_key"], + notification["title"], + notification["text"], + notification["note_key"], + now, + now, + notification["is_group_summary"], + marker, + ), + ) + conn.commit() + return cursor.rowcount > 0 + + @staticmethod + def _fetch_pending(serial: str) -> list[dict[str, Any]]: + # Deliberately wider than the pending TTL: rows past their TTL must + # still be returned once so they can be marked expired instead of + # sitting in "pending" forever. + cutoff = time.time() - _FETCH_WINDOW_SECONDS + with db_session() as conn: + conn.row_factory = sqlite3.Row + rows = conn.execute( + """ + SELECT fingerprint, device_serial, package, session_key, title, text, + captured_at + FROM device_notifications + WHERE device_serial = ? + AND dispatched_session_id IS NULL + AND is_group_summary = 0 + AND session_key IS NOT NULL + AND captured_at > ? + ORDER BY captured_at ASC + LIMIT 500 + """, + (serial, cutoff), + ).fetchall() + return [dict(row) for row in rows] + + async def _flush_ready_groups(self, serial: str) -> None: + """Fire one task per conversation once it has been quiet long enough. + + A conversation is a ``(package, title)`` pair. Messages that arrive + while the previous ones are still being answered accumulate into the + same group, and the group only fires after ``cooldown_seconds`` of + silence -- so a burst is answered once, like a person would. + """ + rows = await asyncio.to_thread(self._fetch_pending, serial) + if not rows: + return + + grouped: dict[str, list[dict[str, Any]]] = {} + for row in rows: + grouped.setdefault(str(row["session_key"]), []).append(row) + + store = _automation_store_module.automation_store + automations = await asyncio.to_thread(store.list, True) + candidates = [a for a in automations if a.get("trigger_type") == "notification"] + if not candidates: + return + + now = time.time() + for items in grouped.values(): + items.sort(key=lambda r: float(r["captured_at"])) + first, last = items[0], items[-1] + fingerprints = [str(i["fingerprint"]) for i in items] + + # Too old to be worth answering (daemon was down, device offline). + if now - float(first["captured_at"]) > _PENDING_TTL_SECONDS: + await asyncio.to_thread(self._mark_group, fingerprints, EXPIRED_MARKER) + continue + + automation = self._match_automation(candidates, serial, items, now) + if automation is None: + continue + + goal = render_group_goal(automation["goal"], items) + if (automation.get("trigger_config") or {}).get("draft_only", True): + goal += DRAFT_INSTRUCTION + + session_id = await self._dispatch(automation, goal) + if not session_id: + # Device busy: keep the group pending and retry next poll. + continue + + await asyncio.to_thread( + self._mark_group, + fingerprints, + session_id, + automation["automation_id"], + ) + await asyncio.to_thread( + store.record_run, + automation["automation_id"], + status="triggered", + session_id=session_id or None, + next_run_at=None, + ) + + def _match_automation( + self, + candidates: list[dict[str, Any]], + serial: str, + items: list[dict[str, Any]], + now: float, + ) -> dict[str, Any] | None: + first, last = items[0], items[-1] + haystack = "\n".join(f"{i['title']}\n{i['text']}" for i in items) + for automation in candidates: + if automation.get("device_serial") and automation["device_serial"] != serial: + continue + config = automation.get("trigger_config") or {} + + packages = config.get("packages") or [] + if packages and first["package"] not in packages: + continue + + pattern = config.get("pattern") + if pattern and re.search(str(pattern), haystack, re.MULTILINE) is None: + continue + + cooldown = _cooldown_seconds(config) + # "Reply like a person": wait for silence measured from the newest + # message, not from the oldest one. A chatty sender keeps pushing + # the window out until they stop. + if now - float(last["captured_at"]) < cooldown: + continue + if automation["automation_id"] in self._in_flight: + continue + last_run = automation.get("last_run_at") or 0.0 + if now - float(last_run) < cooldown: + continue + return automation + return None + + async def _dispatch(self, automation: dict[str, Any], goal: str) -> str | None: + try: + from admin_console.services.automation_scheduler import automation_scheduler + except ImportError: # pragma: no cover - package-mode import path + from apps.admin_console.services.automation_scheduler import automation_scheduler + + return await automation_scheduler.dispatch_goal(automation, goal) + + @staticmethod + def _mark_group( + fingerprints: list[str], session_id: str, automation_id: str | None = None + ) -> None: + if not fingerprints: + return + placeholders = ",".join("?" for _ in fingerprints) + with db_session() as conn: + conn.execute( + f"UPDATE device_notifications SET dispatched_session_id = ?, automation_id = ? " + f"WHERE fingerprint IN ({placeholders})", + (session_id, automation_id, *fingerprints), + ) + conn.commit() + + +def render_group_goal(template: str, items: list[dict[str, Any]]) -> str: + """Render the goal template against a whole conversation burst. + + ``{text}`` is the newest message; ``{messages}`` is the full list. When the + template has no ``{messages}`` slot but several messages were batched, the + list is appended so nothing is silently dropped. + """ + if not items: + return str(template) + title = str(items[0].get("title") or "") + package = str(items[0].get("package") or "") + newest = str(items[-1].get("text") or "") + messages = "\n".join(f"- {i['text']}" for i in items if i.get("text")) + + rendered = ( + str(template) + .replace("{package}", package) + .replace("{title}", title) + .replace("{text}", newest) + .replace("{count}", str(len(items))) + ) + if "{messages}" in template: + rendered = rendered.replace("{messages}", messages) + elif len(items) > 1 and messages: + rendered += f"\n\n对方连续发来 {len(items)} 条消息:\n{messages}" + return rendered + + +def _cooldown_seconds(config: dict[str, Any]) -> float: + try: + return max(0.0, float(config.get("cooldown_seconds", 60))) + except (TypeError, ValueError): + return 60.0 + + +notification_watcher = NotificationWatcher() diff --git a/apps/admin_console/services/settings_service.py b/apps/admin_console/services/settings_service.py index d10b0e5e6..145f5f02c 100644 --- a/apps/admin_console/services/settings_service.py +++ b/apps/admin_console/services/settings_service.py @@ -36,9 +36,12 @@ class SettingsService: # `screen_off` powers the physical display off while a task runs (scrcpy # `--turn-screen-off`); the device stays awake and input/screencap keep working. - # Off by default so opting in never changes the behaviour of an existing setup. DEFAULTS: dict[str, Any] = { - "screen_off": False, + "screen_off": True, + # Optional lock-screen PIN. When set, a task that starts while the + # device is locked wakes the screen and types this PIN instead of + # aborting. Empty means "never guess" (the upstream behaviour). + "device_unlock_pin": "", } def get_all(self) -> dict[str, Any]: @@ -61,7 +64,9 @@ def get(self, key: str, default: Any = None) -> Any: """Return one setting value, or ``default`` when it was never set.""" fallback = self.DEFAULTS.get(key, default) with db_session() as conn: - row = conn.execute("SELECT value FROM app_settings WHERE key = ?", (key,)).fetchone() + row = conn.execute( + "SELECT value FROM app_settings WHERE key = ?", (key,) + ).fetchone() if row is None: return fallback try: diff --git a/apps/admin_console/services/task_queue_service.py b/apps/admin_console/services/task_queue_service.py index 697784842..1413c5617 100644 --- a/apps/admin_console/services/task_queue_service.py +++ b/apps/admin_console/services/task_queue_service.py @@ -534,6 +534,14 @@ def _build_worker_invocation( except Exception: screen_off = True env["ARTEMIS_SCREEN_OFF"] = "1" if screen_off else "0" + # Forward the optional lock-screen PIN so unattended (notification + # driven) runs can unlock the device instead of aborting. + try: + unlock_pin = str(settings_service.get("device_unlock_pin", "") or "").strip() + except Exception: + unlock_pin = "" + if unlock_pin: + env["ARTEMIS_UNLOCK_PIN"] = unlock_pin target.endpoint.apply_to_environment(env) env[DeviceExecutionLock.LOCK_SCOPE_ENV] = target.lock_scope queue_ticket = task_item.get("queue_ticket") diff --git a/apps/showcase_ui/src/app/app.routes.ts b/apps/showcase_ui/src/app/app.routes.ts index 3c163ece9..69e5ce2e6 100644 --- a/apps/showcase_ui/src/app/app.routes.ts +++ b/apps/showcase_ui/src/app/app.routes.ts @@ -18,10 +18,14 @@ import { Routes } from '@angular/router'; import { HomeComponent } from './pages/home/home.component'; import { WorkspaceComponent } from './pages/workspace/workspace.component'; import { LegacyWorkspaceComponent } from './pages/legacy-workspace/legacy-workspace.component'; +import { AutomationsComponent } from './pages/automations/automations.component'; +import { NotificationsComponent } from './pages/notifications/notifications.component'; export const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'workspace', component: WorkspaceComponent }, + { path: 'automations', component: AutomationsComponent }, + { path: 'notifications', component: NotificationsComponent }, { path: 'check', component: LegacyWorkspaceComponent }, { path: '**', redirectTo: '' } ]; diff --git a/apps/showcase_ui/src/app/components/agent-stream/agent-stream.component.html b/apps/showcase_ui/src/app/components/agent-stream/agent-stream.component.html index 93172d380..f90fc62d7 100644 --- a/apps/showcase_ui/src/app/components/agent-stream/agent-stream.component.html +++ b/apps/showcase_ui/src/app/components/agent-stream/agent-stream.component.html @@ -24,11 +24,11 @@ class="vscode-tab-btn" [class.active]="isTaskDropdownOpen()" (click)="toggleTaskDropdown($event)" - title="Task Queue" - aria-label="Task Queue" + [title]="i18n.t('stream.queue.title')" + [attr.aria-label]="i18n.t('stream.queue.title')" > list_alt - Task Queue + {{ i18n.t('stream.queue.title') }} @@ -57,15 +57,15 @@
list_alt - Task Queue + {{ i18n.t('stream.queue.title') }}
@if (activeQueue().length === 0) { } @for (session of activeQueue(); track trackSession($index, session)) { @@ -80,11 +80,11 @@ @if (getTaskStatus(session) === 'running') { } - {{ getTaskStatus(session) | uppercase }} + {{ i18n.t('stream.status.' + getTaskStatus(session)) }}
@if (getDeviceSerial(session)) { - + phone_android {{ getDeviceSerial(session) }} @@ -98,8 +98,8 @@ type="button" class="btn-stop-card" (click)="stopTask(session.session_id, $event)" - title="Stop this task" - aria-label="Stop this task" + [title]="i18n.t('stream.task.stop')" + [attr.aria-label]="i18n.t('stream.task.stop')" > stop_circle @@ -109,8 +109,8 @@ type="button" class="btn-delete-card" (click)="deleteTask(session.session_id, $event)" - title="Delete this task" - aria-label="Delete this task" + [title]="i18n.t('stream.task.delete')" + [attr.aria-label]="i18n.t('stream.task.delete')" > delete @@ -118,21 +118,21 @@
- {{ session.initial_goal || 'Unnamed Task' }} + {{ session.initial_goal || i18n.t('stream.task.untitled') }}
} @if (historyTasks().length === 0) { }
- {{ session.initial_goal || 'Unnamed Task' }} + {{ session.initial_goal || i18n.t('stream.task.untitled') }}
@@ -200,7 +200,7 @@
description - Notes & Plans + {{ i18n.t('stream.notes.title') }}
@if (noteKeys().length > 1) { @@ -222,7 +222,7 @@ @if (noteKeys().length === 0) { } @@ -307,7 +307,7 @@

{{ parsedNote().title }}

[style.margin-left.px]="(check.indent > 2 ? (check.indent - 2) * 12 : 0)" >
- {{ check.checkKind || 'verify' }}{{ check.atEnd ? ' @end' : '' }} + {{ check.checkKind || i18n.t('stream.check.tag.verify') }}{{ check.atEnd ? ' ' + i18n.t('stream.check.atEnd') : '' }}
@for (seg of check.segments; track seg) { @@ -332,7 +332,7 @@

{{ parsedNote().title }}

@if (line.type === 'verify' || line.type === 'finding') {
- {{ line.checkKind || 'verify' }}{{ line.atEnd ? ' @end' : '' }} + {{ line.checkKind || i18n.t('stream.check.tag.verify') }}{{ line.atEnd ? ' ' + i18n.t('stream.check.atEnd') : '' }}
@for (seg of line.segments; track seg) { @@ -402,7 +402,7 @@

{{ parsedNote().title }}

(click)="toggleRunInfo($event)" > {{ getModelIcon(model.name) }} - Architecture: + {{ i18n.t('stream.model.architecture') }} {{ getModelDisplayName(model.name) }} @@ -415,7 +415,7 @@

{{ parsedNote().title }}

(backdropClick)="isRunInfoOpen.set(false)" [cdkConnectedOverlayPositions]="dropdownPositions" > - @@ -296,9 +296,9 @@

System & Environment

-

AI Model Setup

+

{{ i18n.t('home.model.title') }}

-

Google Gemini or custom LLM providers (OpenAI, Claude, Ollama)

+

{{ i18n.t('home.model.desc') }}

@@ -328,9 +328,9 @@

AI Model Setup

Google Gemini - Recommended + {{ i18n.t('home.model.recommended') }}
-

Fast multimodal reasoning with free API key from Google AI Studio.

+

{{ i18n.t('home.model.geminiDesc') }}

@@ -346,10 +346,9 @@

AI Model Setup

- Custom Configuration + {{ i18n.t('home.model.customTitle') }}
-

Define models in config/artemis.jsonc & keys in .env - (OpenAI, Claude, Ollama).

+

{{ i18n.t('home.model.customDescPre') }} config/artemis.jsonc {{ i18n.t('home.model.customDescMid') }} .env {{ i18n.t('home.model.customDescPost') }}

@@ -362,12 +361,12 @@

AI Model Setup

vpn_key - Enter Gemini API Key: + {{ i18n.t('home.model.geminiKeyLabel') }}
open_in_new - Get Free API Key (Google AI Studio) + {{ i18n.t('home.model.getFreeKey') }}
@@ -376,11 +375,11 @@

AI Model Setup

key - - @@ -443,13 +442,13 @@

AI Model Setup

document_scanner
- Optional: Google Cloud Vision OCR + {{ i18n.t('home.ocr.optionalTitle') }}
@if (isOcrConfigured()) { - + } {{ showOcrConfig() ? 'expand_less' : 'expand_more' }} @@ -460,7 +459,7 @@

AI Model Setup

@if (showOcrConfig()) {

- Provides screen text coordinate grounding to improve element detection and interaction accuracy on text-heavy apps. + {{ i18n.t('home.ocr.helpDesc') }}

@@ -468,7 +467,7 @@

AI Model Setup

key - Cloud Vision API Key: + {{ i18n.t('home.ocr.keyLabel') }}
@@ -477,10 +476,10 @@

AI Model Setup

key + [placeholder]="i18n.t('home.model.ocrKeyPlaceholder')" spellcheck="false" autocomplete="off" /> - -
@@ -549,25 +548,25 @@

AI Model Setup

tune
- Active Model Configuration - Defined in + {{ i18n.t('home.config.activeTitle') }} + {{ i18n.t('home.config.definedIn') }} {{ modelConfigEnv()?.config_path || 'config/artemis.jsonc' }}
-
@@ -575,7 +574,7 @@

AI Model Setup

- Default Model + {{ i18n.t('home.config.defaultModel') }}
{{ modelConfigEnv()?.default_model?.provider || 'google' }} @@ -586,7 +585,7 @@

AI Model Setup

@if (modelConfigEnv()?.default_model?.fallback) {
- Fallback Model + {{ i18n.t('home.config.fallbackModel') }}
{{ modelConfigEnv()?.default_model?.fallback?.provider }}/{{ modelConfigEnv()?.default_model?.fallback?.model }} @@ -610,17 +609,17 @@

AI Model Setup

vpn_key
- Environment Variables & API Keys - Loaded from {{ modelConfigEnv()?.env_path || '.env' }} + {{ i18n.t('home.config.envTitle') }} + {{ i18n.t('home.config.loadedFrom') }} {{ modelConfigEnv()?.env_path || '.env' }}
-
@@ -635,7 +634,7 @@

AI Model Setup

@if (envItem.is_set) { check_circle - Configured + {{ i18n.t('home.config.configured') }} @if (envItem.preview) { ({{ envItem.preview }}) } @@ -643,7 +642,7 @@

AI Model Setup

} @else { radio_button_unchecked - Not Set + {{ i18n.t('home.config.notSet') }} }
@@ -672,9 +671,9 @@

AI Model Setup

-

Android Device & Emulator Connection

+

{{ i18n.t('home.device.title') }}

-

Local emulator, attached phone, wireless device, or another ADB server

+

{{ i18n.t('home.device.desc') }}

@@ -723,7 +722,7 @@

Android Device & Emulator Connection

@if (activeDevice()?.is_emulator) { - Virtual Device + {{ i18n.t('home.device.virtualDevice') }} · } {{ activeDevice()?.serial }} @@ -738,21 +737,21 @@

Android Device & Emulator Connection

@if (isRemoteAdbServer()) { · - Remote via {{ adbServerStatus()?.endpoint?.host }}:{{ adbServerStatus()?.endpoint?.port }} + {{ i18n.t('home.device.remoteVia') }} {{ adbServerStatus()?.endpoint?.host }}:{{ adbServerStatus()?.endpoint?.port }} }
- Connected + {{ i18n.t('home.device.connected') }}
@if (connectedDevices().length > 1) {
- Select Active Device: + {{ i18n.t('home.device.selectActive') }}
@for (dev of connectedDevices(); track dev.serial) { } @@ -788,21 +787,21 @@

Android Device & Emulator Connection

- Launching Android Emulator: {{ emulatorLaunchState()?.avd_name || activeDevice()?.serial || 'Virtual Device' }} + {{ i18n.t('home.emulator.launching') }} {{ emulatorLaunchState()?.avd_name || activeDevice()?.serial || i18n.t('home.device.virtualDevice') }}

- {{ emulatorLaunchState()?.status === 'booting' ? 'OS Booting' : 'Starting' }} + {{ emulatorLaunchState()?.status === 'booting' ? i18n.t('home.emulator.osBooting') : i18n.t('home.emulator.starting') }}
-

{{ emulatorLaunchState()?.stage_message || 'Initializing Android Virtual Device...' }}

+

{{ emulatorStageText() }}

-
@@ -817,7 +816,7 @@

} - 1. Process Start + {{ i18n.t('home.emulator.step1') }}
@@ -832,7 +831,7 @@

2 } - 2. ADB Handshake + {{ i18n.t('home.emulator.step2') }}
@@ -847,7 +846,7 @@

3 } - 3. Android OS Boot + {{ i18n.t('home.emulator.step3') }}
@@ -856,7 +855,7 @@

check_circle
- 4. Ready + {{ i18n.t('home.emulator.step4') }} @@ -866,10 +865,10 @@

- {{ emulatorLaunchState()?.progress_percent || 25 }}% Complete + {{ i18n.t('home.emulator.percentComplete', {percent: emulatorLaunchState()?.progress_percent || 25}) }} timer - Elapsed: {{ emulatorLaunchState()?.elapsed_seconds || 0 }}s + {{ i18n.t('home.emulator.elapsed', {seconds: emulatorLaunchState()?.elapsed_seconds || 0}) }}
@@ -877,7 +876,7 @@

info - Android virtualization cold boot usually takes 20-45 seconds. Live progress is actively tracked above—please do not click launch repeatedly. + {{ i18n.t('home.emulator.bootTip') }}
@@ -886,14 +885,14 @@

terminal - Emulator Console Stream (stdout / stderr) + {{ i18n.t('home.emulator.consoleStream') }}
-
@if (emulatorLaunchState()?.logs?.length) {@for (log of emulatorLaunchState()?.logs; track log) {
{{ log }}
}} @else {
Waiting for process output...
}
+
@if (emulatorLaunchState()?.logs?.length) {@for (log of emulatorLaunchState()?.logs; track log) {
{{ log }}
}} @else {
{{ i18n.t('home.emulator.waitingOutput') }}
}
} @@ -910,11 +909,11 @@

error
-

Emulator Launch Failed

-

{{ emulatorLaunchState()?.error || 'The Android emulator process failed to start or crashed during initialization.' }}

+

{{ i18n.t('home.emulator.failedTitle') }}

+

{{ emulatorLaunchState()?.error || i18n.t('home.emulator.failedDesc') }}

- @@ -922,10 +921,10 @@

Emulator Launch Failed

@if (emulatorLaunchState()?.logs?.length) {
- Process Output / Failure Logs: + {{ i18n.t('home.emulator.failureLogs') }}
@for (log of emulatorLaunchState()?.logs; track log) {
{{ log }}
}
@@ -936,15 +935,15 @@

Emulator Launch Failed

@if (emulatorLaunchState()?.avd_name) { }
@@ -968,13 +967,13 @@

Emulator Launch Failed

- Android Emulator + {{ i18n.t('home.conn.emulator') }}
@if (installedAvds().length > 0) { - {{ installedAvds().length }} local virtual device{{ installedAvds().length > 1 ? 's' : '' }} available + {{ i18n.t('home.conn.avdAvailable', {count: installedAvds().length}) }} } @else { - Launch a local Android Virtual Device + {{ i18n.t('home.conn.launchLocal') }} }
@@ -996,9 +995,9 @@

Emulator Launch Failed

- USB Cable + {{ i18n.t('home.conn.usb') }}
- Connect physical phone via USB + {{ i18n.t('home.conn.usbDesc') }}
@@ -1018,9 +1017,9 @@

Emulator Launch Failed

- Wireless ADB + {{ i18n.t('home.conn.wifi') }}
- Connect over local Wi-Fi + {{ i18n.t('home.conn.wifiDesc') }}
@@ -1040,9 +1039,9 @@

Emulator Launch Failed

- Remote Computer + {{ i18n.t('home.conn.remote') }}
- Phone connected to another computer + {{ i18n.t('home.conn.remoteDesc') }}
@@ -1056,9 +1055,8 @@

Emulator Launch Failed

hub - Artemis is currently using - {{ adbServerStatus()?.endpoint?.host }}:{{ adbServerStatus()?.endpoint?.port }}. - Switch to local ADB before using a local emulator, USB cable, or Wireless ADB. + {{ i18n.t('home.conn.remoteActivePre') }} + {{ adbServerStatus()?.endpoint?.host }}:{{ adbServerStatus()?.endpoint?.port }}{{ i18n.t('home.conn.remoteActivePost') }}
} @@ -1082,8 +1080,8 @@

Emulator Launch Failed

devices - Installed Virtual Devices (AVD) - {{ installedAvds().length }} Available + {{ i18n.t('home.avd.installedTitle') }} + {{ i18n.t('home.avd.available', {count: installedAvds().length}) }}
@@ -1097,7 +1095,7 @@

Emulator Launch Failed

{{ avd }} - Virtual Device + {{ i18n.t('home.device.virtualDevice') }}
@@ -1109,14 +1107,14 @@

Emulator Launch Failed

[class.launching]="launchingAvd() === avd || (isEmulatorLaunching() && emulatorLaunchState()?.avd_name === avd)" [disabled]="isEmulatorLaunching() || isRemoteAdbServer()" (click)="launchAvdEmulator(avd)" - [title]="isEmulatorLaunching() ? 'An emulator is currently launching...' : 'Launch ' + avd" + [title]="isEmulatorLaunching() ? i18n.t('home.avd.launchingTip') : i18n.t('home.avd.launchTip', {name: avd})" > @if (launchingAvd() === avd || (isEmulatorLaunching() && emulatorLaunchState()?.avd_name === avd)) { - {{ emulatorLaunchState()?.status === 'booting' ? 'Booting OS' : 'Starting' }} ({{ emulatorLaunchState()?.elapsed_seconds || 0 }}s) + {{ emulatorLaunchState()?.status === 'booting' ? i18n.t('home.emulator.osBooting') : i18n.t('home.emulator.starting') }} ({{ emulatorLaunchState()?.elapsed_seconds || 0 }}s) } @else { play_arrow - Launch + {{ i18n.t('home.avd.launch') }} } @@ -1133,7 +1131,7 @@

Emulator Launch Failed

@@ -1155,7 +1153,7 @@

No Android Virtual Devices (AVD) Detected

(click)="setEmulatorSetupMode('studio')" > desktop_windows - Android Studio (GUI) + {{ i18n.t('home.avd.studioGui') }} @@ -1177,9 +1175,9 @@

No Android Virtual Devices (AVD) Detected

1 download -
Install Android Studio
+
{{ i18n.t('home.avd.s1Title') }}
- Download for {{ effectiveOs() === 'darwin' ? 'macOS' : (effectiveOs() === 'windows' ? 'Windows' : 'Linux') }} from developer.android.com/studio and install. + {{ i18n.t('home.avd.s1DescPre') }} developer.android.com/studio {{ i18n.t('home.avd.s1DescMid') }} {{ effectiveOs() === 'darwin' ? 'macOS' : (effectiveOs() === 'windows' ? 'Windows' : 'Linux') }} {{ i18n.t('home.avd.s1DescPost') }}
@@ -1188,9 +1186,9 @@

No Android Virtual Devices (AVD) Detected

2 developer_mode -
Open Device Manager
+
{{ i18n.t('home.avd.s2Title') }}
- On Studio welcome screen, open More Actions > Virtual Device Manager (or Tools > Device Manager). + {{ i18n.t('home.avd.s2DescPre') }} More Actions > Virtual Device Manager {{ i18n.t('home.avd.s2DescMid') }} Tools > Device Manager{{ i18n.t('home.avd.s2DescPost') }}
@@ -1199,9 +1197,9 @@

No Android Virtual Devices (AVD) Detected

3 add_circle -
Create Virtual Device
+
{{ i18n.t('home.avd.s3Title') }}
- Click Create Device, choose Pixel 8, select Android 14 (API 34), and click Finish. + {{ i18n.t('home.avd.s3DescPre') }} Create Device{{ i18n.t('home.avd.s3DescMid1') }} Pixel 8{{ i18n.t('home.avd.s3DescMid2') }} Android 14 (API 34){{ i18n.t('home.avd.s3DescMid3') }} Finish{{ i18n.t('home.avd.s3DescPost') }}
@@ -1210,9 +1208,9 @@

No Android Virtual Devices (AVD) Detected

4 play_arrow -
Launch Emulator
+
{{ i18n.t('home.avd.s4Title') }}
- Click ▶ Play in Device Manager. Artemis will detect and connect to it automatically! + {{ i18n.t('home.avd.s4DescPre') }} Play {{ i18n.t('home.avd.s4DescPost') }}
@@ -1232,7 +1230,7 @@

No Android Virtual Devices (AVD) Detected

@@ -1241,15 +1239,15 @@

No Android Virtual Devices (AVD) Detected

2
-
Download Emulator & System Image (API 34)
-

Install Android 14 Google APIs system image using SDK Manager:

+
{{ i18n.t('home.avd.cli2Title') }}
+

{{ i18n.t('home.avd.cli2Desc') }}

{{ effectiveOs() === 'windows' ? 'PS>' : '$' }} {{ emuSdkInstallCmd() }}
@@ -1258,15 +1256,15 @@

No Android Virtual Devices (AVD) Detected

3
-
Create Virtual Device (Pixel 8 AVD)
-

Initialize a new Android Virtual Device named Pixel_8_API_34:

+
{{ i18n.t('home.avd.cli3Title') }}
+

{{ i18n.t('home.avd.cli3DescPre') }} Pixel_8_API_34{{ i18n.t('home.avd.cli3DescPost') }}

{{ effectiveOs() === 'windows' ? 'PS>' : '$' }} {{ emuCreateAvdCmd() }}
@@ -1275,15 +1273,15 @@

No Android Virtual Devices (AVD) Detected

4
-
Start the Emulator
-

Launch the virtual device (or add -no-window for headless execution):

+
{{ i18n.t('home.avd.cli4Title') }}
+

{{ i18n.t('home.avd.cli4DescPre') }} -no-window {{ i18n.t('home.avd.cli4DescPost') }}

{{ effectiveOs() === 'windows' ? 'PS>' : '$' }} emulator -avd Pixel_8_API_34 -no-boot-anim
@@ -1301,7 +1299,7 @@

No Android Virtual Devices (AVD) Detected

cable - Connect your Android phone via USB cable and enable USB Debugging: + {{ i18n.t('home.usb.intro') }}
@@ -1310,8 +1308,8 @@

No Android Virtual Devices (AVD) Detected

1 usb
-
Connect USB Cable
-
Plug your Android phone into this computer with a data cable.
+
{{ i18n.t('home.usb.s1Title') }}
+
{{ i18n.t('home.usb.s1Desc') }}
@@ -1319,9 +1317,8 @@

No Android Virtual Devices (AVD) Detected

2 touch_app
-
Enable Developer Options
-
In phone Settings > About Phone, tap Build Number 7 - times.
+
{{ i18n.t('home.usb.s2Title') }}
+
{{ i18n.t('home.usb.s2DescPre') }} Settings > About Phone{{ i18n.t('home.usb.s2DescMid') }} Build Number {{ i18n.t('home.usb.s2DescPost') }}
@@ -1329,8 +1326,8 @@

No Android Virtual Devices (AVD) Detected

3 toggle_on
-
Enable USB Debugging
-
In Settings > Developer Options, turn USB Debugging ON. +
{{ i18n.t('home.usb.s3Title') }}
+
{{ i18n.t('home.usb.s3DescPre') }} Settings > Developer Options{{ i18n.t('home.usb.s3DescMid') }} USB Debugging {{ i18n.t('home.usb.s3DescPost') }}
@@ -1339,8 +1336,8 @@

No Android Virtual Devices (AVD) Detected

4 verified_user
-
Authorize Computer
-
Check "Always allow" and tap Allow on the phone prompt. +
{{ i18n.t('home.usb.s4Title') }}
+
{{ i18n.t('home.usb.s4DescPre') }} "Always allow"{{ i18n.t('home.usb.s4DescMid') }} Allow {{ i18n.t('home.usb.s4DescPost') }}
@@ -1352,23 +1349,23 @@

No Android Virtual Devices (AVD) Detected

wifi - Connect your phone and computer on the same Wi-Fi network: + {{ i18n.t('home.wifi.intro') }}
- +
router + [placeholder]="i18n.t('home.wifi.ipPlaceholder')" spellcheck="false" />
- +
tag No Android Virtual Devices (AVD) Detected (click)="connectWifiDevice()"> @if (isConnectingWifi()) { sync - Connecting... + {{ i18n.t('home.wifi.connecting') }} } @else { bolt - Connect + {{ i18n.t('home.wifi.connect') }} }
@@ -1406,7 +1403,7 @@

No Android Virtual Devices (AVD) Detected

help_outline
- Find IP & port in phone Settings > Developer Options > Wireless Debugging. + {{ i18n.t('home.wifi.findIpPre') }} Settings > Developer Options > Wireless Debugging {{ i18n.t('home.wifi.findIpPost') }}
@@ -1417,13 +1414,13 @@

No Android Virtual Devices (AVD) Detected

hub - Enter the host and port of an ADB server endpoint that this computer can access, so Artemis can discover and control a phone physically connected to another computer. + {{ i18n.t('home.remote.intro') }}
- +
dns No Android Virtual Devices (AVD) Detected
- +
tag No Android Virtual Devices (AVD) Detected > @if (isConnectingRemoteAdb()) { sync - Checking... + {{ i18n.t('home.remote.checking') }} } @else { bolt - Test Connection + {{ i18n.t('home.remote.testConnection') }} }
@@ -1481,7 +1478,7 @@

No Android Virtual Devices (AVD) Detected

[ngModel]="rememberRemoteAdb()" (ngModelChange)="rememberRemoteAdb.set($event)" /> - Remember this endpoint for future Artemis launches + {{ i18n.t('home.remote.remember') }} @if (remoteAdbMessage()) { @@ -1507,7 +1504,7 @@

No Android Virtual Devices (AVD) Detected

{{ device.serial }}
- {{ device.state === 'device' ? 'Ready' : device.state }} + {{ device.state === 'device' ? i18n.t('home.remote.ready') : device.state }}
} @@ -1523,17 +1520,17 @@

No Android Virtual Devices (AVD) Detected

> @if (isActivatingRemoteAdb()) { sync - Connecting... + {{ i18n.t('home.remote.connecting') }} } @else { check - {{ remoteAdbHasReadyDevice() ? 'Use Connection' : 'Use Anyway' }} + {{ remoteAdbHasReadyDevice() ? i18n.t('home.remote.useConnection') : i18n.t('home.remote.useAnyway') }} } }

- Artemis sends all ADB commands to this server instead of the default local server. Any phone visible to that server becomes available to Artemis. + {{ i18n.t('home.remote.explanation') }}

} @@ -1548,7 +1545,7 @@

No Android Virtual Devices (AVD) Detected

lock
- {{ adbProbe()?.summary === 'Device Locked' ? 'Device Is Locked' : 'Unable to Verify Lock State' }} + {{ adbProbe()?.summary === 'Device Locked' ? i18n.t('home.locked.title') : i18n.t('home.locked.unknownTitle') }}
{{ adbProbe()?.description }} @@ -1556,14 +1553,14 @@

No Android Virtual Devices (AVD) Detected

@if (connectedDevices().length > 1) {
- Select Active Device: + {{ i18n.t('home.device.selectActive') }}
@for (dev of connectedDevices(); track dev.serial) { } @@ -1593,14 +1590,14 @@

No Android Virtual Devices (AVD) Detected

screen_lock_portrait
-
USB Debugging Authorization Pending
+
{{ i18n.t('home.unauth.title') }}
- Your Android device was detected, but it requires authorization. Please unlock your phone screen and tap "Allow USB Debugging". + {{ i18n.t('home.unauth.descPre') }} "Allow USB Debugging"{{ i18n.t('home.unauth.descPost') }}
@@ -1612,7 +1609,7 @@

No Android Virtual Devices (AVD) Detected

error
- Android Platform Tools (adb) not found. Please install ADB on your operating system: + {{ i18n.t('home.adb.notFound') }} {{ i18n.t('home.adb.notFoundHint') }}
@@ -1621,7 +1618,7 @@

No Android Virtual Devices (AVD) Detected

Linux (Ubuntu / Debian) @if (effectiveOs() === 'linux') { - Detected + {{ i18n.t('home.adb.detected') }} }
@@ -1630,7 +1627,7 @@

No Android Virtual Devices (AVD) Detected

@@ -1639,7 +1636,7 @@

No Android Virtual Devices (AVD) Detected

macOS (Homebrew) @if (effectiveOs() === 'darwin') { - Detected + {{ i18n.t('home.adb.detected') }} }
@@ -1648,7 +1645,7 @@

No Android Virtual Devices (AVD) Detected

@@ -1657,7 +1654,7 @@

No Android Virtual Devices (AVD) Detected

Windows (WinGet) @if (effectiveOs() === 'windows') { - Detected + {{ i18n.t('home.adb.detected') }} }
@@ -1666,7 +1663,7 @@

No Android Virtual Devices (AVD) Detected

@@ -1685,17 +1682,107 @@

No Android Virtual Devices (AVD) Detected

check
-

System Ready for Autonomous Tasks

-

All dependencies, AI model credentials, and Android device are verified and ready to run.

+

{{ i18n.t('home.ready.title') }}

+

{{ i18n.t('home.ready.desc') }}

} + +
+
+
+ settings +
+
+
+

{{ i18n.t('settings.prefs.title') }}

+ @if (settingsService.saveState() === 'saving') { + {{ i18n.t('settings.prefs.saving') }} + } @else if (settingsService.saveState() === 'saved') { + {{ i18n.t('settings.prefs.saved') }} + } @else if (settingsService.saveState() === 'error') { + {{ i18n.t('settings.prefs.saveError') }} + } +
+

{{ i18n.t('settings.prefs.desc') }}

+
+
+ +
+
+
+ {{ i18n.t('settings.prefs.language') }} + {{ i18n.t('settings.prefs.languageHint') }} +
+
+ + +
+
+ +
+
+ {{ i18n.t('settings.prefs.screenOff') }} + {{ i18n.t('settings.prefs.screenOffHint') }} +
+
+ +
+
+ +
+
+ {{ i18n.t('settings.prefs.unlockPin') }} + {{ i18n.t('settings.prefs.unlockPinHint') }} +
+
+ + + @if (unlockTestMessage()) { + {{ unlockTestMessage() }} + } +
+
+
+
+ } @@ -1711,8 +1798,8 @@

System Ready for Autonomous Tasks

{{ adbProbe()?.summary === 'Device Locked' ? 'lock' : 'warning' }} {{ adbProbe()?.summary === 'Device Locked' - ? 'Android device is locked. Unlock it and enter the home screen before running a task.' - : 'Prerequisites incomplete: runtime, credentials, or Android device is not ready. Click here to open Setup Guide.' }} + ? i18n.t('home.launcher.lockedWarning') + : i18n.t('home.launcher.prereqWarning') }} arrow_forward @@ -1727,11 +1814,11 @@

System Ready for Autonomous Tasks

auto_awesome - Continuous monitoring or complex task detected. Recommended: Pro Mode + {{ i18n.t('home.launcher.intentPre') }} {{ i18n.t('home.launcher.intentProMode') }}
@@ -1745,7 +1832,7 @@

System Ready for Autonomous Tasks

rows="3" [(ngModel)]="taskGoal" [disabled]="isSubmitting()" - placeholder="Describe what you want to achieve on your phone (e.g. Open Gmail and search for latest emails)..." + [placeholder]="i18n.t('home.task.placeholder')" (keydown.control.enter)="runTask()" (keydown.meta.enter)="runTask()" > @@ -1761,14 +1848,14 @@

System Ready for Autonomous Tasks

Flash · - Token-efficient, rapid 3–5s/step decisions straight from the live screen. Best for everyday tasks with a clear path, however long they run. - (No plan, no result check, no ADB commands) + {{ i18n.t('home.launcher.flashDescPre') }} {{ i18n.t('home.launcher.flashDescSpeed') }} {{ i18n.t('home.launcher.flashDescPost') }} + {{ i18n.t('home.launcher.flashLimitation') }}

} @else {

Pro · - Plans first, checks its results and recovers when a tap is blocked. Handles 100+ step workflows and live phone monitoring (15–40s / step). + {{ i18n.t('home.launcher.proDescPre') }} {{ i18n.t('home.launcher.proDescSteps') }}{{ i18n.t('home.launcher.proDescMid') }}{{ i18n.t('home.launcher.proDescLatency') }}{{ i18n.t('home.launcher.proDescPost') }}

} @@ -1792,7 +1879,7 @@

System Ready for Autonomous Tasks

class="model-toggle-btn btn-flash" [class.active]="selectedProfile() === 'flash'" (click)="setProfile('flash')" - title="Flash: fast single-look loop for everyday app tasks (3–5s/step)" + [title]="i18n.t('home.launcher.flashTitle')" > bolt Flash @@ -1802,7 +1889,7 @@

System Ready for Autonomous Tasks

class="model-toggle-btn btn-pro" [class.active]="selectedProfile() === 'pro'" (click)="setProfile('pro')" - title="Pro: plans first, checks results and recovers from blocked steps. For long or complex tasks (15–40s/step)" + [title]="i18n.t('home.launcher.proTitle')" > psychology Pro @@ -1812,7 +1899,7 @@

System Ready for Autonomous Tasks

@if (taskGoal().length > 0) { - {{ taskGoal().length }} chars + {{ i18n.t('home.launcher.charCount', { count: taskGoal().length }) }} } @@ -1821,13 +1908,13 @@

System Ready for Autonomous Tasks

class="btn-run-composer" [class.btn-run-pro]="selectedProfile() === 'pro'" [disabled]="!taskGoal().trim() || isSubmitting() || !isReady()" - [title]="!isReady() ? (adbProbe()?.summary === 'Device Locked' ? 'Unlock the Android device before running' : 'Complete System Setup before running') : 'Run task'" + [title]="!isReady() ? (adbProbe()?.summary === 'Device Locked' ? i18n.t('home.launcher.unlockTitle') : i18n.t('home.launcher.setupTitle')) : i18n.t('home.launcher.runTitle')" (click)="runTask()" > @if (isSubmitting()) { - Starting... + {{ i18n.t('home.launcher.starting') }} } @else { - play_arrowRun Task + play_arrow{{ i18n.t('home.launcher.runTask') }} }
@@ -1838,8 +1925,8 @@

System Ready for Autonomous Tasks

@if (selectedProfile() === 'pro') {
- Expected Output - (Optional) + {{ i18n.t('home.outputter.title') }} + {{ i18n.t('home.outputter.optional') }}
@@ -1848,7 +1935,7 @@

System Ready for Autonomous Tasks

class="outputter-standalone-input" [ngModel]="expectedOutput()" (ngModelChange)="expectedOutput.set($event)" - placeholder="Specify expected output or schema (e.g. 'Extract SMS verification code as JSON' or 'Summary of discounts and total price')..." + [placeholder]="i18n.t('home.outputter.placeholder')" spellcheck="false" /> @if (expectedOutput().trim()) { @@ -1856,7 +1943,7 @@

System Ready for Autonomous Tasks

type="button" class="btn-clear-standalone" (click)="expectedOutput.set('')" - title="Clear expected output" + [title]="i18n.t('home.outputter.clearTitle')" > close @@ -1867,9 +1954,9 @@

System Ready for Autonomous Tasks

- Pro settings + {{ i18n.t('home.tuning.proSettings') }} @if (!isTuningDefault()) { - + }
@@ -1949,7 +2036,7 @@

System Ready for Autonomous Tasks

{{ slider.level.tagline }}

- What happens + {{ i18n.t('home.tuning.whatHappens') }}
    @for (line of slider.level.runs; track $index) {
  • {{ line }}
  • @@ -1958,7 +2045,7 @@

    System Ready for Autonomous Tasks

@if (slider.level.skips?.length) {
- Not included + {{ i18n.t('home.tuning.notIncluded') }}
    @for (line of slider.level.skips; track $index) {
  • {{ line }}
  • @@ -1967,7 +2054,7 @@

    System Ready for Autonomous Tasks

}
- Use it for + {{ i18n.t('home.tuning.useItFor') }} {{ slider.level.bestFor }}
@@ -1986,7 +2073,7 @@

System Ready for Autonomous Tasks

@@ -1997,7 +2084,7 @@

System Ready for Autonomous Tasks

[class.active]="selectedCategory() === 'all'" (click)="setCategory('all')" > - All + {{ i18n.t('home.recommended.all') }}
-
@@ -2063,7 +2150,7 @@

System Ready for Autonomous Tasks

@for (app of item.apps; track app.name) { -
+
{{ app.icon }}
} @@ -2071,22 +2158,22 @@

System Ready for Autonomous Tasks

+ [title]="item.profile === 'pro' ? i18n.t('home.recommended.usesPro') : i18n.t('home.recommended.usesFlash')"> {{ item.profile === 'pro' ? 'Pro' : 'Flash' }}
-

{{ item.title }}

-

{{ item.description }}

+

{{ taskText(item, 'title') }}

+

{{ taskText(item, 'description') }}

diff --git a/apps/showcase_ui/src/app/pages/home/home.component.scss b/apps/showcase_ui/src/app/pages/home/home.component.scss index c1a5e68d6..c850207b5 100644 --- a/apps/showcase_ui/src/app/pages/home/home.component.scss +++ b/apps/showcase_ui/src/app/pages/home/home.component.scss @@ -5166,3 +5166,178 @@ $text-light: #94a3b8; transform: translateY(0) scale(1); } } + +/* ========================================================================== */ +/* Console preferences card (language + screen-off), inside the setup guide */ +/* ========================================================================== */ +.setup-guide-view .prefs-card { + .prefs-save-state { + padding: 2px 9px; + border-radius: 999px; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.02em; + color: #64748b; + background: #f1f5f9; + + &.is-saved { + color: #0f9d58; + background: rgba(15, 157, 88, 0.1); + } + + &.is-error { + color: #d93025; + background: rgba(217, 48, 37, 0.1); + } + } + + .prefs-body { + display: flex; + flex-direction: column; + padding: 4px 20px 10px; + } + + .pref-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + padding: 14px 0; + border-bottom: 1px solid #f1f5f9; + + &:last-child { + border-bottom: none; + } + } + + .pref-label { + display: flex; + flex-direction: column; + gap: 3px; + min-width: 0; + + .pref-name { + font-size: 13.5px; + font-weight: 600; + color: #0f172a; + } + + .pref-hint { + font-size: 12px; + color: #64748b; + line-height: 1.45; + } + } + + .pref-control { + flex-shrink: 0; + display: inline-flex; + align-items: center; + } + + .pref-input { + width: 160px; + padding: 8px 12px; + border: 1px solid #cbd5e1; + border-radius: 10px; + background: #ffffff; + font-size: 14px; + letter-spacing: 2px; + color: #0f172a; + + &:focus { + outline: none; + border-color: #6366f1; + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15); + } + } + + .pref-inline-btn { + margin-left: 10px; + padding: 8px 14px; + border: 1px solid #cbd5e1; + border-radius: 10px; + background: #ffffff; + font-size: 13px; + color: #334155; + cursor: pointer; + + &:hover:not(:disabled) { + border-color: #6366f1; + color: #4f46e5; + } + + &:disabled { + opacity: 0.6; + cursor: default; + } + } + + .unlock-test-result { + margin-left: 10px; + font-size: 12px; + color: #475569; + } + + .lang-choice-group { + gap: 4px; + padding: 3px; + background: #f1f5f9; + border-radius: 10px; + + .lang-choice { + border: none; + background: transparent; + font-family: inherit; + font-size: 12.5px; + font-weight: 600; + color: #64748b; + padding: 6px 14px; + border-radius: 8px; + cursor: pointer; + transition: background 0.15s ease, color 0.15s ease, box-shadow 0.15s ease; + + &:hover:not(.active) { + color: #0f172a; + } + + &.active { + background: #ffffff; + color: #1a73e8; + box-shadow: 0 1px 3px rgba(15, 23, 42, 0.12); + } + } + } + + .switch { + position: relative; + width: 40px; + height: 22px; + padding: 0; + border: none; + border-radius: 11px; + background: #cbd5e1; + cursor: pointer; + transition: background 0.18s ease; + + .switch-thumb { + position: absolute; + top: 2px; + left: 2px; + width: 18px; + height: 18px; + border-radius: 50%; + background: #ffffff; + box-shadow: 0 1px 2px rgba(15, 23, 42, 0.25); + transition: transform 0.18s ease; + } + + &.on { + background: #1a73e8; + + .switch-thumb { + transform: translateX(18px); + } + } + } +} diff --git a/apps/showcase_ui/src/app/pages/home/home.component.ts b/apps/showcase_ui/src/app/pages/home/home.component.ts index e189b9ce5..2f7dbafa8 100644 --- a/apps/showcase_ui/src/app/pages/home/home.component.ts +++ b/apps/showcase_ui/src/app/pages/home/home.component.ts @@ -15,10 +15,15 @@ */ import { Component, signal, computed, effect, inject, OnInit, OnDestroy, ChangeDetectionStrategy } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { Router, RouterLink } from '@angular/router'; + +import { I18nService } from '../../core/i18n/i18n.service'; + import { AgentService } from '../../services/agent.service'; import { SystemService } from '../../services/system.service'; +import { SettingsService } from '../../services/settings.service'; import { AdbServerConnectionResult, AdbServerDevice, @@ -111,8 +116,11 @@ type AdbGuideTab = 'emulator' | 'usb' | 'wifi' | 'remote'; export class HomeComponent implements OnInit, OnDestroy { public agentService = inject(AgentService); public systemService = inject(SystemService); + public settingsService = inject(SettingsService); public taskRecService = inject(TaskRecommendationService); + private http = inject(HttpClient); private router = inject(Router); + protected readonly i18n = inject(I18nService); // High-level navigation mode: 'diagnostics' (System Setup Guide) vs 'launcher' (Task Execution) public activeTab = signal<'diagnostics' | 'launcher'>('launcher'); @@ -126,6 +134,14 @@ export class HomeComponent implements OnInit, OnDestroy { public showOcrConfig = signal(false); public showFullConfigFile = signal(false); + // Persisted console preference: power the physical screen off during runs. + public screenOff = signal(true); + // Persisted console preference: optional lock-screen PIN. When set, a task + // that starts while the phone is locked unlocks it instead of failing. + public unlockPin = signal(''); + public isTestingUnlock = signal(false); + public unlockTestMessage = signal(null); + // Model & Environment configuration from backend public modelConfigEnv = computed(() => this.systemService.modelConfigEnv()); @@ -222,6 +238,34 @@ export class HomeComponent implements OnInit, OnDestroy { /** Pixel cloud drawn over a rail once its slider reaches the last notch. */ public readonly ditherPixels: readonly DitherPixel[] = buildDitherPixels(); + // --- Persisted console preferences --------------------------------------- + // The setup guide used to reset on every reload because this state lived only + // in memory. It is now mirrored into the daemon's `app_settings` store. + private readonly settingsPatch = computed>(() => ({ + 'ui.active_tab': this.activeTab(), + 'ui.adb_guide_tab': this.activeAdbGuideTab(), + 'ui.emulator_setup_mode': this.emulatorSetupMode(), + 'ui.model_setup_mode': this.modelSetupMode(), + 'ui.wifi_host': this.wifiHost(), + 'ui.wifi_port': this.wifiPort(), + 'ui.remote_adb_host': this.remoteAdbHost(), + 'ui.remote_adb_port': this.remoteAdbPort(), + 'ui.remember_remote_adb': this.rememberRemoteAdb(), + 'screen_off': this.screenOff(), + 'device_unlock_pin': this.unlockPin() + })); + + /** Guards the persist effect until the stored settings have been applied. */ + private settingsHydrated = false; + + private readonly persistSettings = effect(() => { + const patch = this.settingsPatch(); + if (!this.settingsHydrated) { + return; + } + this.settingsService.setMany(patch); + }); + public verificationLevel = computed>( () => VERIFICATION_LEVELS[this.verificationIndex()] ); @@ -238,25 +282,44 @@ export class HomeComponent implements OnInit, OnDestroy { return [ { kind: 'verify', - name: 'Result check', - ends: ['Off', 'Strict'], + name: this.i18n.t('home.tuning.verifyName'), + ends: [this.i18n.t('home.tuning.verifyEndOff'), this.i18n.t('home.tuning.verifyEndStrict')], ladder: VERIFICATION_LEVELS, index: vi, - level: VERIFICATION_LEVELS[vi], + level: this.localizeTuningLevel(VERIFICATION_LEVELS[vi], 'verify'), fraction: notchPercent(vi, VERIFICATION_LEVELS.length) / 100 }, { kind: 'explore', - name: 'Screen reading', - ends: ['Faster', 'Sharper'], + name: this.i18n.t('home.tuning.exploreName'), + ends: [this.i18n.t('home.tuning.exploreEndFaster'), this.i18n.t('home.tuning.exploreEndSharper')], ladder: EXPLORER_MODES, index: ei, - level: EXPLORER_MODES[ei], + level: this.localizeTuningLevel(EXPLORER_MODES[ei], 'explore'), fraction: notchPercent(ei, EXPLORER_MODES.length) / 100 } ]; }); + /** Applies localized copy to a tuning level, falling back to the built-in wording. */ + private localizeTuningLevel( + level: TuningLevel, + kind: TuningKind + ): TuningLevel { + const key = (field: string) => `home.tuning.${kind}.${level.id}.${field}`; + const text = (field: string, fallback: string) => + this.i18n.has(key(field)) ? this.i18n.t(key(field)) : fallback; + return { + id: level.id, + label: text('label', level.label), + tagline: text('tagline', level.tagline), + latency: text('latency', level.latency), + runs: level.runs.map((line, i) => text(`runs.${i}`, line)), + skips: level.skips?.map((line, i) => text(`skips.${i}`, line)), + bestFor: text('bestFor', level.bestFor) + }; + } + public notchFraction(index: number, count: number): number { return notchPercent(index, count) / 100; } @@ -351,6 +414,22 @@ export class HomeComponent implements OnInit, OnDestroy { public launchingAvd = computed(() => this.systemService.launchingAvd()); public emulatorLaunchState = computed(() => this.systemService.emulatorLaunchState()); public isEmulatorLaunching = computed(() => this.systemService.isEmulatorLaunching()); + + /** Localized emulator progress text, keyed off the launch stage. */ + public emulatorStageText = computed(() => { + const stage = this.emulatorLaunchState()?.status; + const keys: Record = { + idle: 'home.emulator.stage.idle', + starting: 'home.emulator.stage.starting', + waiting_for_adb: 'home.emulator.stage.waitingAdb', + booting: 'home.emulator.stage.booting', + ready: 'home.emulator.stage.ready', + failed: 'home.emulator.stage.failed', + stopped: 'home.emulator.stage.stopped' + }; + const key = stage ? keys[stage] : undefined; + return key ? this.i18n.t(key) : this.i18n.t('home.emulator.initializing'); + }); public showLaunchLogs = signal(false); // Probes @@ -426,16 +505,16 @@ export class HomeComponent implements OnInit, OnDestroy { public emuHypervisorTitle = computed(() => { const os = this.effectiveOs(); - if (os === 'windows') return 'Enable Windows Hypervisor Platform (WHPX)'; - if (os === 'darwin') return 'Verify macOS Hypervisor / Install Tools'; - return 'Enable KVM Hardware Acceleration (Linux)'; + if (os === 'windows') return this.i18n.t('home.emu.winTitle'); + if (os === 'darwin') return this.i18n.t('home.emu.macTitle'); + return this.i18n.t('home.emu.linuxTitle'); }); public emuHypervisorDesc = computed(() => { const os = this.effectiveOs(); - if (os === 'windows') return 'Enable Windows Hypervisor Platform in PowerShell (Run as Administrator):'; - if (os === 'darwin') return 'macOS uses native Hypervisor.framework. Install SDK tools via Homebrew (or Studio):'; - return 'Ensure virtualization permissions are granted to your user account:'; + if (os === 'windows') return this.i18n.t('home.emu.winDesc'); + if (os === 'darwin') return this.i18n.t('home.emu.macDesc'); + return this.i18n.t('home.emu.linuxDesc'); }); public emuHypervisorCmd = computed(() => { @@ -538,6 +617,11 @@ export class HomeComponent implements OnInit, OnDestroy { ngOnInit(): void { this.loadProTuningDefaults(); + // Restore the last-used console state before wiring the persist effect. + this.settingsService.load().subscribe((settings) => { + this.applyPersistedSettings(settings); + this.settingsHydrated = true; + }); // Initial fetch of system readiness & model configuration this.systemService.fetchReadiness().subscribe(); this.systemService.fetchModelConfigEnv().subscribe(); @@ -555,10 +639,88 @@ export class HomeComponent implements OnInit, OnDestroy { window.addEventListener('focus', this.focusListener); } + /** Applies persisted settings to the guide's view state (no network side effects). */ + private applyPersistedSettings(settings: Record): void { + const str = (key: string): string | undefined => + typeof settings[key] === 'string' ? (settings[key] as string) : undefined; + + const tab = str('ui.active_tab'); + if (tab === 'launcher' || tab === 'diagnostics') { + this.activeTab.set(tab); + } + const adbTab = str('ui.adb_guide_tab'); + if (adbTab === 'emulator' || adbTab === 'usb' || adbTab === 'wifi' || adbTab === 'remote') { + this.activeAdbGuideTab.set(adbTab); + } + const emulatorMode = str('ui.emulator_setup_mode'); + if (emulatorMode === 'studio' || emulatorMode === 'cli') { + this.emulatorSetupMode.set(emulatorMode); + } + const modelMode = str('ui.model_setup_mode'); + if (modelMode === 'gemini' || modelMode === 'custom') { + this.modelSetupMode.set(modelMode); + this.systemService.setSkipCredentialsCheck(modelMode === 'custom'); + } + const wifiHost = str('ui.wifi_host'); + if (wifiHost !== undefined) { + this.wifiHost.set(wifiHost); + } + const wifiPort = str('ui.wifi_port'); + if (wifiPort !== undefined) { + this.wifiPort.set(wifiPort); + } + const remoteHost = str('ui.remote_adb_host'); + if (remoteHost !== undefined) { + this.remoteAdbHost.set(remoteHost); + } + const remotePort = str('ui.remote_adb_port'); + if (remotePort !== undefined) { + this.remoteAdbPort.set(remotePort); + } + if (typeof settings['ui.remember_remote_adb'] === 'boolean') { + this.rememberRemoteAdb.set(settings['ui.remember_remote_adb'] as boolean); + } + if (typeof settings['screen_off'] === 'boolean') { + this.screenOff.set(settings['screen_off'] as boolean); + } + if (typeof settings['device_unlock_pin'] === 'string') { + this.unlockPin.set(settings['device_unlock_pin'] as string); + } + } + ngOnDestroy(): void { window.removeEventListener('focus', this.focusListener); } + /** Try the stored PIN on the current device so the operator can verify it. */ + public testUnlock(): void { + if (this.isTestingUnlock()) { + return; + } + this.isTestingUnlock.set(true); + this.unlockTestMessage.set(null); + this.http + .post<{ ok: boolean; alreadyUnlocked: boolean }>('/api/system/device/unlock', {}) + .subscribe({ + next: (res) => { + this.isTestingUnlock.set(false); + this.unlockTestMessage.set( + this.i18n.t( + res.ok + ? res.alreadyUnlocked + ? 'settings.prefs.unlockAlreadyOpen' + : 'settings.prefs.unlockOk' + : 'settings.prefs.unlockFailed' + ) + ); + }, + error: () => { + this.isTestingUnlock.set(false); + this.unlockTestMessage.set(this.i18n.t('settings.prefs.unlockFailed')); + } + }); + } + public setTab(tab: 'diagnostics' | 'launcher'): void { this.activeTab.set(tab); if (tab === 'diagnostics') { @@ -632,12 +794,12 @@ export class HomeComponent implements OnInit, OnDestroy { next: (res) => { this.isSavingGeminiKey.set(false); this.isGeminiKeyEdited.set(false); - this.geminiSaveMessage.set(res?.message || '✓ Gemini API key verified & saved successfully.'); + this.geminiSaveMessage.set(res?.message || this.i18n.t('home.model.geminiSaved')); setTimeout(() => this.geminiSaveMessage.set(null), 5000); }, error: (err) => { this.isSavingGeminiKey.set(false); - this.geminiSaveError.set(err?.error?.detail || err?.message || 'Failed to update Gemini API key.'); + this.geminiSaveError.set(err?.error?.detail || err?.message || this.i18n.t('home.model.geminiSaveFailed')); } }); } @@ -653,16 +815,16 @@ export class HomeComponent implements OnInit, OnDestroy { this.systemService.updateApiKey('google', '', true).subscribe({ next: (res) => { this.isSavingGeminiKey.set(false); - this.geminiSaveMessage.set(res?.message || '✓ Gemini API key cleared.'); + this.geminiSaveMessage.set(res?.message || this.i18n.t('home.model.geminiCleared')); setTimeout(() => this.geminiSaveMessage.set(null), 5000); }, error: (err) => { this.isSavingGeminiKey.set(false); - this.geminiSaveError.set(err?.error?.detail || err?.message || 'Failed to clear Gemini API key.'); + this.geminiSaveError.set(err?.error?.detail || err?.message || this.i18n.t('home.model.geminiClearFailed')); } }); } else { - this.geminiSaveMessage.set('✓ Gemini API key cleared.'); + this.geminiSaveMessage.set(this.i18n.t('home.model.geminiCleared')); setTimeout(() => this.geminiSaveMessage.set(null), 3000); } } @@ -678,12 +840,12 @@ export class HomeComponent implements OnInit, OnDestroy { next: (res) => { this.isSavingOcrKey.set(false); this.isOcrKeyEdited.set(false); - this.ocrSaveMessage.set(res?.message || '✓ Vision OCR API key verified & saved.'); + this.ocrSaveMessage.set(res?.message || this.i18n.t('home.model.ocrSaved')); setTimeout(() => this.ocrSaveMessage.set(null), 5000); }, error: (err) => { this.isSavingOcrKey.set(false); - this.ocrSaveError.set(err?.error?.detail || err?.message || 'Failed to update Vision OCR key.'); + this.ocrSaveError.set(err?.error?.detail || err?.message || this.i18n.t('home.model.ocrSaveFailed')); } }); } @@ -699,16 +861,16 @@ export class HomeComponent implements OnInit, OnDestroy { this.systemService.updateApiKey('ocr', '', true).subscribe({ next: (res) => { this.isSavingOcrKey.set(false); - this.ocrSaveMessage.set(res?.message || '✓ Vision OCR API key cleared.'); + this.ocrSaveMessage.set(res?.message || this.i18n.t('home.model.ocrCleared')); setTimeout(() => this.ocrSaveMessage.set(null), 5000); }, error: (err) => { this.isSavingOcrKey.set(false); - this.ocrSaveError.set(err?.error?.detail || err?.message || 'Failed to clear Vision OCR key.'); + this.ocrSaveError.set(err?.error?.detail || err?.message || this.i18n.t('home.model.ocrClearFailed')); } }); } else { - this.ocrSaveMessage.set('✓ Vision OCR API key cleared.'); + this.ocrSaveMessage.set(this.i18n.t('home.model.ocrCleared')); setTimeout(() => this.ocrSaveMessage.set(null), 3000); } } @@ -724,15 +886,15 @@ export class HomeComponent implements OnInit, OnDestroy { next: (res) => { this.isTestingGeminiKey.set(false); if (res?.valid) { - this.geminiSaveMessage.set(res?.message || '✓ Gemini API key is valid!'); + this.geminiSaveMessage.set(res?.message || this.i18n.t('home.model.geminiValid')); } else { - this.geminiSaveError.set(res?.message || 'Gemini API key verification failed.'); + this.geminiSaveError.set(res?.message || this.i18n.t('home.model.geminiVerifyFailed')); } setTimeout(() => this.geminiSaveMessage.set(null), 5000); }, error: (err) => { this.isTestingGeminiKey.set(false); - this.geminiSaveError.set(err?.error?.detail || err?.message || 'Gemini API key test failed.'); + this.geminiSaveError.set(err?.error?.detail || err?.message || this.i18n.t('home.model.geminiTestFailed')); } }); } @@ -748,15 +910,15 @@ export class HomeComponent implements OnInit, OnDestroy { next: (res) => { this.isTestingOcrKey.set(false); if (res?.valid) { - this.ocrSaveMessage.set(res?.message || '✓ Vision OCR API key is valid!'); + this.ocrSaveMessage.set(res?.message || this.i18n.t('home.model.ocrValid')); } else { - this.ocrSaveError.set(res?.message || 'Vision OCR API key verification failed.'); + this.ocrSaveError.set(res?.message || this.i18n.t('home.model.ocrVerifyFailed')); } setTimeout(() => this.ocrSaveMessage.set(null), 5000); }, error: (err) => { this.isTestingOcrKey.set(false); - this.ocrSaveError.set(err?.error?.detail || err?.message || 'Vision OCR API key test failed.'); + this.ocrSaveError.set(err?.error?.detail || err?.message || this.i18n.t('home.model.ocrTestFailed')); } }); } @@ -829,12 +991,14 @@ export class HomeComponent implements OnInit, OnDestroy { this.systemService.restartAdb().subscribe({ next: (res) => { this.adbRestartFeedback.set( - res?.restart_result?.skipped ? 'Devices Refreshed ✓' : 'ADB Refreshed ✓' + res?.restart_result?.skipped + ? this.i18n.t('home.device.devicesRefreshed') + : this.i18n.t('home.device.adbRefreshed') ); setTimeout(() => this.adbRestartFeedback.set(null), 2500); }, error: () => { - this.adbRestartFeedback.set('Restart Failed'); + this.adbRestartFeedback.set(this.i18n.t('home.device.restartFailed')); setTimeout(() => this.adbRestartFeedback.set(null), 3000); } }); @@ -842,7 +1006,7 @@ export class HomeComponent implements OnInit, OnDestroy { public connectWifiDevice(): void { if (this.isRemoteAdbServer()) { - this.wifiConnectError.set('Switch to local ADB before connecting a Wireless ADB device.'); + this.wifiConnectError.set(this.i18n.t('home.wifi.errRemote')); return; } const host = this.wifiHost().trim(); @@ -850,7 +1014,7 @@ export class HomeComponent implements OnInit, OnDestroy { const port = parseInt(portStr, 10) || 5555; if (!host) { - this.wifiConnectError.set('Please enter a valid IP address.'); + this.wifiConnectError.set(this.i18n.t('home.wifi.errInvalidIp')); return; } @@ -863,15 +1027,15 @@ export class HomeComponent implements OnInit, OnDestroy { this.isConnectingWifi.set(false); const cr = res?.connect_result; if (cr?.success) { - this.wifiConnectMessage.set(`Connected to ${host}:${port}!`); + this.wifiConnectMessage.set(this.i18n.t('home.wifi.connectedTo', { host, port })); setTimeout(() => this.wifiConnectMessage.set(null), 4000); } else { - this.wifiConnectError.set(cr?.message || 'Connection failed. Please check phone IP & Wi-Fi.'); + this.wifiConnectError.set(cr?.message || this.i18n.t('home.wifi.errConnectFailed')); } }, error: (err) => { this.isConnectingWifi.set(false); - this.wifiConnectError.set(err?.error?.detail || 'Failed to connect. Please check adb connection.'); + this.wifiConnectError.set(err?.error?.detail || this.i18n.t('home.wifi.errConnectFailedShort')); } }); } @@ -881,11 +1045,11 @@ export class HomeComponent implements OnInit, OnDestroy { const port = Number(this.remoteAdbPort().trim()); if (!host) { - this.remoteAdbError.set('Enter the host name or IP address of the ADB server.'); + this.remoteAdbError.set(this.i18n.t('home.remote.errNoHost')); return; } if (!Number.isInteger(port) || port < 1 || port > 65535) { - this.remoteAdbError.set('Enter a port between 1 and 65535.'); + this.remoteAdbError.set(this.i18n.t('home.remote.errBadPort')); return; } @@ -910,7 +1074,7 @@ export class HomeComponent implements OnInit, OnDestroy { error: error => { this.isConnectingRemoteAdb.set(false); this.remoteAdbError.set( - error?.error?.detail || 'Unable to test the ADB server endpoint.' + error?.error?.detail || this.i18n.t('home.remote.errTestFailed') ); } }); @@ -919,7 +1083,7 @@ export class HomeComponent implements OnInit, OnDestroy { public activateRemoteAdbServer(): void { const tested = this.remoteAdbProbeResult(); if (!tested?.success) { - this.remoteAdbError.set('Test the endpoint before using it.'); + this.remoteAdbError.set(this.i18n.t('home.remote.errTestFirst')); return; } @@ -944,7 +1108,7 @@ export class HomeComponent implements OnInit, OnDestroy { error: error => { this.isActivatingRemoteAdb.set(false); this.remoteAdbError.set( - error?.error?.detail || 'Unable to use the ADB server endpoint.' + error?.error?.detail || this.i18n.t('home.remote.errUseFailed') ); } }); @@ -979,7 +1143,7 @@ export class HomeComponent implements OnInit, OnDestroy { error: error => { this.isSwitchingToLocalAdb.set(false); this.remoteAdbError.set( - error?.error?.detail || 'Unable to switch back to the local ADB server.' + error?.error?.detail || this.i18n.t('home.remote.errSwitchLocalFailed') ); } }); @@ -1043,8 +1207,20 @@ export class HomeComponent implements OnInit, OnDestroy { this.shuffleOffset.update(v => v + 3); } + /** Localized title/description/tag for a suggestion, falling back to the raw data. */ + protected taskText(item: SmartSuggestion, field: 'title' | 'description' | 'tag'): string { + const key = `tasks.${item.id}.${field}`; + return this.i18n.has(key) ? this.i18n.t(key) : item[field]; + } + + /** Localized app display name, falling back to the registry name. */ + protected appName(app: AppReference): string { + const key = `tasks.app.${app.pkg}`; + return this.i18n.has(key) ? this.i18n.t(key) : app.name; + } + public getAppNamesDisplay(apps: AppReference[]): string { - return apps.map(a => a.name).join(' + '); + return apps.map(a => this.appName(a)).join(' + '); } public applySuggestion(item: SmartSuggestion): void { @@ -1069,12 +1245,12 @@ export class HomeComponent implements OnInit, OnDestroy { public runTask(): void { const goal = this.taskGoal().trim(); if (!goal) { - this.errorMessage.set('Please enter a task goal before running.'); + this.errorMessage.set(this.i18n.t('home.launcher.errNoGoal')); return; } if (!this.isReady()) { - this.errorMessage.set('System prerequisites are not satisfied. Please review System Setup first.'); + this.errorMessage.set(this.i18n.t('home.launcher.errNotReady')); this.activeTab.set('diagnostics'); return; } @@ -1103,7 +1279,7 @@ export class HomeComponent implements OnInit, OnDestroy { console.error('Failed to submit task from home page:', err); this.isSubmitting.set(false); this.errorMessage.set( - err?.error?.detail || 'Failed to submit task. Please check server connection.' + err?.error?.detail || this.i18n.t('home.launcher.errSubmitFailed') ); } }); diff --git a/apps/showcase_ui/src/app/pages/notifications/notifications.component.html b/apps/showcase_ui/src/app/pages/notifications/notifications.component.html new file mode 100644 index 000000000..8fdebae62 --- /dev/null +++ b/apps/showcase_ui/src/app/pages/notifications/notifications.component.html @@ -0,0 +1,121 @@ +
+
+
+

{{ i18n.t('notifications.title') }}

+

{{ i18n.t('notifications.subtitle') }}

+
+
+ + +
+
+ + @if (actionMessage()) { + + } + +
+ + + + + + +
+ + + + +
+
+ + @if (loadError()) { + + } + + @if (isLoading()) { +

{{ i18n.t('notifications.loading') }}

+ } @else if (groups().length === 0) { +
+

{{ i18n.t('notifications.empty') }}

+

{{ i18n.t('notifications.emptyHint') }}

+
+ } @else { + @for (group of groups(); track group.key) { +
+
+ + expand_more + + {{ group.label }} + {{ group.sublabel }} + @if (group.pending > 0) { + {{ group.pending }} + } +
+ + @if (!isCollapsed(group.key)) { +
+ @for (item of group.items; track item.fingerprint) { +
+
+ {{ packageLabel(item.package) }} + {{ formatTime(item.captured_at) }} + {{ stateLabel(item.state) }} +
+
+ @if (item.title) { + {{ item.title }} + } + @if (item.is_group_summary) { + {{ i18n.t('notifications.groupSummary') }} + } @else { + {{ item.text }} + } +
+
+ } +
+ } +
+ } + } +
+ + diff --git a/apps/showcase_ui/src/app/pages/notifications/notifications.component.scss b/apps/showcase_ui/src/app/pages/notifications/notifications.component.scss new file mode 100644 index 000000000..46742f7fa --- /dev/null +++ b/apps/showcase_ui/src/app/pages/notifications/notifications.component.scss @@ -0,0 +1,306 @@ +.page { + padding: 24px; + max-width: 1080px; + margin: 0 auto; +} + +.page-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 18px; + + h2 { + margin: 0 0 4px; + font-size: 20px; + font-weight: 700; + color: #0f172a; + } + + .subtitle { + margin: 0; + font-size: 13px; + color: #64748b; + } +} + +.head-actions { + display: flex; + align-items: center; + gap: 8px; + + select { + padding: 7px 10px; + border: 1px solid #e2e8f0; + border-radius: 9px; + background: #ffffff; + font-family: inherit; + font-size: 13px; + color: #0f172a; + } +} + +.btn { + padding: 7px 14px; + border-radius: 9px; + border: 1px solid #e2e8f0; + background: #ffffff; + font-family: inherit; + font-size: 13px; + cursor: pointer; + + &:hover { + border-color: #1a73e8; + color: #1a73e8; + } +} + +.banner.error { + padding: 10px 12px; + border-radius: 9px; + background: #fef2f2; + color: #b91c1c; + font-size: 13px; + margin-bottom: 12px; +} + +.muted { + color: #94a3b8; + font-size: 13px; +} + +.empty { + padding: 40px 20px; + text-align: center; + border: 1px dashed #e2e8f0; + border-radius: 14px; + + .empty-title { + margin: 0 0 6px; + font-size: 14px; + color: #475569; + } + + .empty-hint { + margin: 0; + font-size: 12.5px; + color: #94a3b8; + line-height: 1.5; + } +} + +.list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.row { + padding: 10px 12px; + border: 1px solid #e2e8f0; + border-radius: 11px; + background: #ffffff; + + &.summary { + background: #f8fafc; + } +} + +.row-meta { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 5px; + font-size: 11.5px; + + .app { + font-weight: 600; + color: #334155; + } + + .time { + color: #94a3b8; + } + + .state { + margin-left: auto; + padding: 1px 7px; + border-radius: 999px; + background: #f1f5f9; + color: #475569; + } + + .state-pending { + background: #fef3c7; + color: #92400e; + } + + .state-dispatched { + background: #dcfce7; + color: #166534; + } + + .state-expired { + background: #f1f5f9; + color: #94a3b8; + } +} + +.row-body { + display: flex; + flex-direction: column; + gap: 3px; + + .title { + font-size: 13px; + font-weight: 600; + color: #0f172a; + } + + .text { + font-size: 13px; + color: #334155; + line-height: 1.45; + word-break: break-word; + } + + .muted-text { + color: #94a3b8; + font-style: italic; + } +} + +.toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-bottom: 14px; + + select { + max-width: 220px; + padding: 7px 10px; + border: 1px solid #e2e8f0; + border-radius: 9px; + background: #ffffff; + font-family: inherit; + font-size: 13px; + color: #0f172a; + } +} + +.view-switch { + display: inline-flex; + margin-left: auto; + border: 1px solid #e2e8f0; + border-radius: 9px; + overflow: hidden; + + button { + padding: 7px 12px; + border: none; + background: #ffffff; + font-family: inherit; + font-size: 12.5px; + color: #475569; + cursor: pointer; + + & + button { + border-left: 1px solid #e2e8f0; + } + + &.active { + background: #e8f0fe; + color: #1a73e8; + font-weight: 600; + } + } +} + +.group { + margin-bottom: 10px; + border: 1px solid #e2e8f0; + border-radius: 12px; + background: #ffffff; + overflow: hidden; +} + +.group-head { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 12px; + background: #f8fafc; + cursor: pointer; + user-select: none; + + &:hover { + background: #f1f5f9; + } +} + +.chevron { + display: inline-flex; + color: #94a3b8; + transition: transform 0.15s ease; + + &.collapsed { + transform: rotate(-90deg); + } + + .material-symbols-outlined { + font-size: 18px; + } +} + +.group-label { + font-size: 13.5px; + font-weight: 600; + color: #0f172a; +} + +.group-sub { + font-size: 12px; + color: #94a3b8; +} + +.badge { + min-width: 20px; + margin-left: auto; + padding: 1px 7px; + border-radius: 999px; + font-size: 11.5px; + text-align: center; + + &.pending { + background: #fef3c7; + color: #92400e; + } +} + +.group-body { + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px; +} + +.row { + border-radius: 9px; + border-color: #eef2f7; +} + +.btn.danger:hover { + border-color: #dc2626; + color: #dc2626; +} + +.banner.info { + margin-bottom: 12px; + padding: 10px 12px; + border-radius: 9px; + background: #ecfdf5; + color: #047857; + font-size: 13px; +} diff --git a/apps/showcase_ui/src/app/pages/notifications/notifications.component.ts b/apps/showcase_ui/src/app/pages/notifications/notifications.component.ts new file mode 100644 index 000000000..9fa9287b4 --- /dev/null +++ b/apps/showcase_ui/src/app/pages/notifications/notifications.component.ts @@ -0,0 +1,287 @@ +/** + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + ChangeDetectionStrategy, + Component, + OnDestroy, + OnInit, + computed, + inject, + signal +} from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { FormsModule } from '@angular/forms'; + +import { I18nService } from '../../core/i18n/i18n.service'; +import { APP_REGISTRY } from '../../core/data/smart-tasks.data'; +import { ConfirmDialogComponent } from '../../components/confirm-dialog/confirm-dialog.component'; + +type NotificationState = 'pending' | 'dispatched' | 'baseline' | 'expired'; +type ViewMode = 'session' | 'app' | 'rule' | 'time'; + +interface DeviceNotification { + fingerprint: string; + device_serial: string | null; + package: string; + title: string; + text: string; + captured_at: number; + is_group_summary: boolean; + state: NotificationState; + session_id: string | null; + automation_id: string | null; + automation_name: string; +} + +interface NotifGroup { + key: string; + label: string; + sublabel: string; + items: DeviceNotification[]; + latest: number; + pending: number; +} + +const REFRESH_MS = 10000; + +@Component({ + selector: 'app-notifications', + standalone: true, + imports: [FormsModule, ConfirmDialogComponent], + templateUrl: './notifications.component.html', + styleUrl: './notifications.component.scss', + changeDetection: ChangeDetectionStrategy.Eager +}) +export class NotificationsComponent implements OnInit, OnDestroy { + private readonly http = inject(HttpClient); + protected readonly i18n = inject(I18nService); + + public readonly items = signal([]); + public readonly isLoading = signal(true); + public readonly loadError = signal(false); + public readonly actionMessage = signal(null); + public readonly confirmClearOpen = signal(false); + + public readonly viewMode = signal('session'); + public readonly appFilter = signal(''); + public readonly ruleFilter = signal(''); + public readonly stateFilter = signal(''); + + public readonly packages = signal>([]); + public readonly rules = signal>([]); + + private readonly collapsed = signal>(new Set()); + private timer: ReturnType | null = null; + + /** Notifications grouped by conversation, app, rule or day. */ + public readonly groups = computed(() => { + const mode = this.viewMode(); + const map = new Map(); + for (const item of this.items()) { + const key = this.groupKey(item, mode); + let group = map.get(key); + if (!group) { + group = { key, label: '', sublabel: '', items: [], latest: 0, pending: 0 }; + map.set(key, group); + } + group.items.push(item); + group.latest = Math.max(group.latest, item.captured_at); + if (item.state === 'pending') { + group.pending += 1; + } + } + for (const group of map.values()) { + const labels = this.groupLabels(group, mode); + group.label = labels[0]; + group.sublabel = labels[1]; + } + return [...map.values()].sort((a, b) => b.latest - a.latest); + }); + + ngOnInit(): void { + this.loadFilters(); + this.load(); + this.timer = setInterval(() => this.load(true), REFRESH_MS); + } + + ngOnDestroy(): void { + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + } + + private loadFilters(): void { + this.http + .get<{ packages: Array<{ package: string; total: number }> }>( + '/api/notifications/packages?limit=200' + ) + .subscribe({ next: (res) => this.packages.set(res?.packages ?? []) }); + this.http + .get<{ automations: Array<{ automation_id: string; name: string }> }>('/api/automations') + .subscribe({ + next: (res) => + this.rules.set( + (res?.automations ?? []).map((a) => ({ + id: a.automation_id, + name: a.name || a.automation_id + })) + ) + }); + } + + public load(silent = false): void { + if (!silent) { + this.isLoading.set(true); + } + this.loadError.set(false); + let params = new HttpParams().set('limit', '300'); + if (this.appFilter()) { + params = params.set('package', this.appFilter()); + } + if (this.ruleFilter()) { + params = params.set('automation_id', this.ruleFilter()); + } + if (this.stateFilter()) { + params = params.set('state', this.stateFilter()); + } + this.http + .get<{ notifications: DeviceNotification[] }>('/api/notifications', { params }) + .subscribe({ + next: (res) => { + this.items.set(res?.notifications ?? []); + this.isLoading.set(false); + }, + error: (err) => { + console.error('Failed to load notifications:', err); + this.loadError.set(true); + this.isLoading.set(false); + } + }); + } + + public clearAll(): void { + this.confirmClearOpen.set(true); + } + + public performClear(): void { + this.confirmClearOpen.set(false); + this.http.delete<{ deleted: number }>('/api/notifications').subscribe({ + next: (res) => { + this.actionMessage.set( + this.i18n.t('notifications.cleared', { count: res?.deleted ?? 0 }) + ); + this.items.set([]); + this.loadFilters(); + }, + error: (err) => console.error('Failed to clear notifications:', err) + }); + } + + public setView(mode: ViewMode): void { + this.viewMode.set(mode); + } + + public setAppFilter(value: string): void { + this.appFilter.set(value); + this.load(); + } + + public setRuleFilter(value: string): void { + this.ruleFilter.set(value); + this.load(); + } + + public setStateFilter(value: string): void { + this.stateFilter.set(value); + this.load(); + } + + public isCollapsed(key: string): boolean { + return this.collapsed().has(key); + } + + public toggleGroup(key: string): void { + const next = new Set(this.collapsed()); + if (next.has(key)) { + next.delete(key); + } else { + next.add(key); + } + this.collapsed.set(next); + } + + private groupKey(item: DeviceNotification, mode: ViewMode): string { + if (mode === 'app') { + return `app:${item.package}`; + } + if (mode === 'rule') { + return `rule:${item.automation_id ?? 'none'}`; + } + if (mode === 'time') { + const d = new Date(item.captured_at * 1000); + return `day:${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`; + } + return `sess:${item.package}|${item.title}`; + } + + private groupLabels(group: NotifGroup, mode: ViewMode): [string, string] { + const first = group.items[0]; + const count = this.i18n.t('notifications.group.count', { count: group.items.length }); + if (mode === 'app') { + return [this.packageLabel(first.package), count]; + } + if (mode === 'rule') { + const name = first.automation_name || this.i18n.t('notifications.unmatchedRule'); + return [name, count]; + } + if (mode === 'time') { + const d = new Date(first.captured_at * 1000); + const locale = this.i18n.lang() === 'zh' ? 'zh-CN' : 'en-US'; + return [d.toLocaleDateString(locale), count]; + } + const conversation = first.title || this.i18n.t('notifications.noTitle'); + return [conversation, `${this.packageLabel(first.package)} · ${count}`]; + } + + public packageLabel(pkg: string): string { + if (!pkg) { + return this.i18n.t('notifications.packageUnknown'); + } + const key = `tasks.app.${pkg}`; + if (this.i18n.has(key)) { + return this.i18n.t(key); + } + return APP_REGISTRY[pkg]?.name ?? pkg; + } + + public stateLabel(state: NotificationState): string { + const key = `notifications.state.${state}`; + return this.i18n.has(key) ? this.i18n.t(key) : state; + } + + public formatTime(ts: number): string { + const locale = this.i18n.lang() === 'zh' ? 'zh-CN' : 'en-US'; + return new Date(ts * 1000).toLocaleString(locale, { + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit' + }); + } +} diff --git a/apps/showcase_ui/src/app/pages/workspace/workspace.component.html b/apps/showcase_ui/src/app/pages/workspace/workspace.component.html index a44cd84e3..0a8cfc946 100644 --- a/apps/showcase_ui/src/app/pages/workspace/workspace.component.html +++ b/apps/showcase_ui/src/app/pages/workspace/workspace.component.html @@ -27,7 +27,7 @@
error {{ errorMessage() }} -
@@ -89,7 +89,7 @@
- Start a new task... + {{ i18n.t('workspace.dock.placeholder.dormant') }}
@@ -105,8 +105,8 @@ rows="1" [disabled]="isSubmitting()" [placeholder]="selectedProfile() === 'pro' - ? 'Pro: plans first, checks results and recovers from blocked steps. For long or complex tasks' - : 'Flash: fast single-look loop for everyday app tasks'" + ? i18n.t('workspace.dock.placeholder.pro') + : i18n.t('workspace.dock.placeholder.flash')" class="dock-textarea" spellcheck="false" > @@ -115,7 +115,7 @@ @if (taskInput.trim() && !isSubmitting()) { } @@ -136,8 +136,8 @@ [class.has-content]="!!taskInput.trim()" [disabled]="!taskInput.trim() || isSubmitting()" (click)="submitTask()" - [title]="isSubmitting() ? 'Starting task...' : 'Start task (Enter)'" - aria-label="Start task" + [title]="isSubmitting() ? i18n.t('workspace.dock.start.busy') : i18n.t('workspace.dock.start.title')" + [attr.aria-label]="i18n.t('workspace.dock.start.aria')" > @if (isSubmitting()) { sync @@ -152,16 +152,16 @@