File size: 2,376 Bytes
537fc7e
 
b4980c3
 
537fc7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4980c3
114d838
 
 
 
 
 
537fc7e
 
 
b4980c3
537fc7e
 
114d838
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from typing import Any, List, Optional

from tools.text import normalize_message


class UIController:
    def __init__(
        self,
        logger: Any,
        chat_handler: Any,
        agent: Any = None,
        startup_error: Optional[str] = None,
    ):
        self.logger = logger
        self.chat_handler = chat_handler
        self.agent = agent
        self.startup_error = startup_error

    def status(self) -> str:
        if self.startup_error:
            return f"startup_error: {self.startup_error}"
        if self.agent is None:
            return "startup_error: agent unavailable"
        state = self.agent.status_snapshot()
        running = "running" if state["running"] else "stopped"
        return f"state={running} last_status={state['last_status']} dry_run={state['dry_run']}"

    def start(self) -> str:
        if self.startup_error:
            return f"startup_error: {self.startup_error}"
        if self.agent is None:
            return "startup_error: agent unavailable"
        result = self.agent.start()
        return f"agent {result}"

    def stop(self) -> str:
        if self.startup_error:
            return f"startup_error: {self.startup_error}"
        if self.agent is None:
            return "startup_error: agent unavailable"
        result = self.agent.stop()
        return f"agent {result}"

    def logs(self) -> str:
        return self.logger.snapshot()

    def chat_send(self, message: str, history: Optional[List[Any]]) -> tuple[str, List[Any]]:
        try:
            if self.chat_handler is None:
                clean = normalize_message(message)
                if not clean:
                    return "", history or []
                return "", (history or []) + [
                    {"role": "user", "content": clean},
                    {"role": "assistant", "content": "startup_error: chat unavailable"},
                ]
            return self.chat_handler.send(message, history)
        except Exception as exc:  # noqa: BLE001
            self.logger.error("Manual chat failed", {"error": str(exc)})
            clean = normalize_message(message)
            if not clean:
                return "", history or []
            return "", (history or []) + [
                {"role": "user", "content": clean},
                {"role": "assistant", "content": f"error: {exc}"},
            ]