Compare commits
11 Commits
docs/contr
...
feat/add-c
| Author | SHA1 | Date | |
|---|---|---|---|
| 537839ba1a | |||
| 6a29c5f3dd | |||
| 7d3540483b | |||
| fb7c25ec78 | |||
| b83929fac2 | |||
| e616bebdb9 | |||
| 8f8e63f56f | |||
| df377cf2df | |||
| 906022555a | |||
| ebe7902362 | |||
| 582c19bb50 |
10
.env.example
10
.env.example
@@ -6,10 +6,16 @@ SLACK_APP_TOKEN=xapp-your-app-token
|
||||
SLACK_ALLOWED_USER_ID=U0XXXXXXXXX
|
||||
SLACK_ALLOWED_CHANNEL_ID=C0XXXXXXXXX
|
||||
|
||||
# PTY 설정
|
||||
DEFAULT_SHELL=claude
|
||||
# PTY / tmux 연결 설정
|
||||
TMUX_SESSION_NAME=claude
|
||||
CODEX_TMUX_SESSION_NAME=codex
|
||||
PTY_READ_TIMEOUT=5
|
||||
|
||||
# 출력 버퍼 설정
|
||||
OUTPUT_BUFFER_INTERVAL=2.0
|
||||
MAX_MESSAGE_LENGTH=3000
|
||||
|
||||
# 상태 보고 / 재연결 설정
|
||||
RECONNECT_DELAY_SECONDS=5.0
|
||||
OUTPUT_IDLE_REPORT_SECONDS=120
|
||||
INPUT_IDLE_REPORT_SECONDS=300
|
||||
|
||||
32
AGENTS.md
32
AGENTS.md
@@ -42,3 +42,35 @@ Current git history is minimal (`Initial commit`), so enforce clear conventions
|
||||
## Security & Configuration Tips
|
||||
Do not commit secrets. Copy `.env.example` to `.env` locally.
|
||||
Restrict Slack access with `SLACK_ALLOWED_USER_ID` and `SLACK_ALLOWED_CHANNEL_ID` before running in shared workspaces.
|
||||
|
||||
## Git & Gitea Workflow Notes
|
||||
Use `tea` (Gitea CLI), not `gh`.
|
||||
|
||||
Hard rule:
|
||||
- Never implement changes, stage files, or commit on `main`.
|
||||
- Always create/use a feature branch first, and merge via PR.
|
||||
|
||||
- Check login:
|
||||
- `tea login ls`
|
||||
- `tea whoami`
|
||||
- Create/update feature branch:
|
||||
- `git checkout -b <branch>` (or `git checkout <branch>`)
|
||||
- `git add <files>`
|
||||
- `git commit -m "<message>"`
|
||||
- Push to Gitea:
|
||||
- Normal: `git push -u origin <branch>`
|
||||
- If HTTP username prompt fails in this environment, use the token from `~/.config/tea/config.yml`:
|
||||
- `TOKEN=$(sed -n 's/^[[:space:]]*token: //p' ~/.config/tea/config.yml | head -n1)`
|
||||
- `git push "http://agentson:${TOKEN}@localhost:3000/jihoson/LazyEnter.git" <branch>`
|
||||
- After token-based push, ensure tracking is on `origin/<branch>` (not token URL):
|
||||
- `git fetch origin <branch>:refs/remotes/origin/<branch>`
|
||||
- `git branch --set-upstream-to=origin/<branch> <branch>`
|
||||
- Create PR on Gitea:
|
||||
- `tea pr create --base main --head <branch> --title "<title>" --description "<body>"`
|
||||
- Sync local main:
|
||||
- `git checkout main`
|
||||
- `git pull --ff-only`
|
||||
|
||||
Safety:
|
||||
- Do not commit or print tokens in logs/docs.
|
||||
- Keep unrelated local files (for example `uv.lock`) out of PRs unless intentionally changed.
|
||||
|
||||
41
README.md
41
README.md
@@ -1,15 +1,18 @@
|
||||
# LazyEnter
|
||||
|
||||
소파에서 엔터나 치자.
|
||||
로컬 PC의 Claude Code CLI 세션을 Slack Socket Mode로 중계해 모바일에서도 원격으로 입력/승인을 처리하는 브릿지입니다.
|
||||
로컬 PC의 Claude/Codex CLI 세션을 Slack Socket Mode로 중계해 모바일에서도 원격으로 입력/승인을 처리하는 브릿지입니다.
|
||||
|
||||
## 동작 방식
|
||||
|
||||
1. Slack에서 `/start-claude` 실행
|
||||
2. 로컬에서 `claude` 프로세스(기본값)가 PTY로 시작됨
|
||||
3. Slack 채널 메시지가 CLI 입력으로 전달됨
|
||||
4. CLI 출력이 Slack으로 다시 전송됨
|
||||
5. `/stop-claude`로 세션 종료
|
||||
1. 로컬에서 Claude 또는 Codex를 tmux 세션으로 미리 실행
|
||||
- Claude: `tmux new -s claude claude`
|
||||
- Codex: `tmux new -s codex codex`
|
||||
2. Slack에서 `/start-claude` 또는 `/start-codex` 실행
|
||||
3. 브릿지가 기존 tmux 세션에 attach
|
||||
4. Slack 채널 메시지가 CLI 입력으로 전달됨
|
||||
5. CLI 출력이 Slack으로 다시 전송됨
|
||||
6. `/stop-claude`로 브릿지 연결 해제 (tmux 세션은 유지)
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
@@ -34,10 +37,16 @@ cp .env.example .env
|
||||
- `SLACK_ALLOWED_CHANNEL_ID`
|
||||
|
||||
선택 환경 변수:
|
||||
- `DEFAULT_SHELL` (기본: `claude`)
|
||||
- `TMUX_SESSION_NAME` (기본: `claude`, `/start-claude` 대상)
|
||||
- `CODEX_TMUX_SESSION_NAME` (기본: `codex`, `/start-codex` 대상)
|
||||
- `PTY_READ_TIMEOUT` (기본: `5`)
|
||||
- `OUTPUT_BUFFER_INTERVAL` (기본: `2.0`)
|
||||
- `MAX_MESSAGE_LENGTH` (기본: `3000`)
|
||||
- `RECONNECT_DELAY_SECONDS` (기본: `5.0`, Socket Mode 재연결 대기 시간)
|
||||
- `OUTPUT_IDLE_REPORT_SECONDS` (기본: `120`, 출력 정지 보고 임계값)
|
||||
- `INPUT_IDLE_REPORT_SECONDS` (기본: `300`, 입력 정지 보고 임계값)
|
||||
|
||||
`SLACK_ALLOWED_USER_ID`, `SLACK_ALLOWED_CHANNEL_ID`가 비어 있으면 실행이 중단됩니다.
|
||||
|
||||
## Slack 앱 설정
|
||||
|
||||
@@ -46,10 +55,22 @@ cp .env.example .env
|
||||
- Slash Commands 생성:
|
||||
- `/start-claude`
|
||||
- `/stop-claude`
|
||||
- `/start-codex`
|
||||
- `/stop-codex`
|
||||
- 앱을 워크스페이스에 설치 후 토큰을 `.env`에 반영
|
||||
|
||||
## 실행
|
||||
|
||||
먼저 로컬에서 원하는 tmux 세션을 실행:
|
||||
|
||||
```bash
|
||||
tmux new -s claude claude
|
||||
# 또는
|
||||
tmux new -s codex codex
|
||||
```
|
||||
|
||||
그 다음 브릿지 실행:
|
||||
|
||||
```bash
|
||||
lazy-enter
|
||||
# 또는
|
||||
@@ -57,9 +78,9 @@ python -m lazy_enter
|
||||
```
|
||||
|
||||
실행 후 Slack의 허용된 채널에서:
|
||||
- `/start-claude`: 세션 시작
|
||||
- 일반 메시지 전송: Claude CLI로 입력 전달
|
||||
- `/stop-claude`: 세션 종료
|
||||
- `/start-claude`, `/start-codex`: 기존 세션에 연결
|
||||
- 일반 메시지 전송: 현재 연결된 CLI(Claude/Codex)로 입력 전달
|
||||
- `/stop-claude`, `/stop-codex`: 브릿지 연결 해제 (세션 유지)
|
||||
|
||||
## 테스트 및 품질 점검
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""LazyEnter - Slack을 통한 Claude Code 원격 제어 브릿지."""
|
||||
"""LazyEnter - Slack을 통한 Claude/Codex 원격 제어 브릿지."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
"""CLI 엔트리포인트."""
|
||||
|
||||
import sys
|
||||
|
||||
from lazy_enter.bridge import Bridge
|
||||
from lazy_enter.config import Config
|
||||
|
||||
|
||||
def main() -> None:
|
||||
bridge = Bridge()
|
||||
config = Config()
|
||||
try:
|
||||
config.validate_required_settings()
|
||||
except ValueError as exc:
|
||||
print(f"[LazyEnter] 설정 오류: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1) from exc
|
||||
|
||||
bridge = Bridge(config)
|
||||
bridge.run()
|
||||
|
||||
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
|
||||
from lazy_enter.config import Config
|
||||
from lazy_enter.output_filter import clean_terminal_output
|
||||
from lazy_enter.pty_manager import PtyManager
|
||||
from lazy_enter.slack_handler import SlackHandler
|
||||
|
||||
@@ -23,73 +25,171 @@ class Bridge:
|
||||
self._output_thread: threading.Thread | None = None
|
||||
self._running = False
|
||||
self._channel: str = self.config.allowed_channel_id
|
||||
self._active_target: str | None = None
|
||||
self._last_sent_output: str = ""
|
||||
self._last_input_at = time.monotonic()
|
||||
self._last_output_at = time.monotonic()
|
||||
self._input_idle_reported = False
|
||||
self._output_idle_reported = False
|
||||
|
||||
self.slack.on_message(self._handle_message)
|
||||
self.slack.on_command(self._handle_command)
|
||||
|
||||
def _handle_message(self, text: str, channel: str) -> None:
|
||||
"""Slack 메시지를 PTY 프로세스로 전달한다."""
|
||||
if self._is_blocked_input(text):
|
||||
self.slack.send_message(
|
||||
channel, ":no_entry: 차단된 명령 패턴이 감지되었습니다."
|
||||
)
|
||||
return
|
||||
|
||||
if self.pty and self.pty.is_alive:
|
||||
self.pty.send(text)
|
||||
self._last_input_at = time.monotonic()
|
||||
self._input_idle_reported = False
|
||||
logger.info("입력 전달: %s", text)
|
||||
else:
|
||||
self.slack.send_message(channel, ":warning: 실행 중인 세션이 없습니다.")
|
||||
self.slack.send_message(channel, ":warning: 연결된 세션이 없습니다.")
|
||||
|
||||
def _handle_command(self, command: str, channel: str) -> None:
|
||||
@staticmethod
|
||||
def _is_blocked_input(text: str) -> bool:
|
||||
"""치명적 쉘 명령 패턴을 단순 차단한다."""
|
||||
normalized = re.sub(r"\s+", " ", text.lower()).strip()
|
||||
blocked_patterns = (
|
||||
"rm -rf /",
|
||||
"rm -rf /*",
|
||||
"mkfs",
|
||||
":(){:|:&};:",
|
||||
"shutdown -h",
|
||||
"reboot",
|
||||
"poweroff",
|
||||
)
|
||||
return any(pattern in normalized for pattern in blocked_patterns)
|
||||
|
||||
@staticmethod
|
||||
def _display_name(target: str) -> str:
|
||||
if target == "codex":
|
||||
return "Codex"
|
||||
return "Claude"
|
||||
|
||||
def _session_name_for_target(self, target: str) -> str:
|
||||
if target == "codex":
|
||||
return self.config.codex_tmux_session_name
|
||||
return self.config.tmux_session_name
|
||||
|
||||
def _handle_command(self, action: str, target: str, channel: str) -> None:
|
||||
"""슬래시 커맨드를 처리한다."""
|
||||
if command == "start":
|
||||
self._start_session(channel)
|
||||
elif command == "stop":
|
||||
if target not in {"claude", "codex"}:
|
||||
self.slack.send_message(channel, ":warning: 지원하지 않는 대상입니다.")
|
||||
return
|
||||
|
||||
if action == "start":
|
||||
self._start_session(channel, target)
|
||||
elif action == "stop":
|
||||
self._stop_session(channel)
|
||||
|
||||
def _start_session(self, channel: str) -> None:
|
||||
"""Claude Code 세션을 시작한다."""
|
||||
def _start_session(self, channel: str, target: str) -> None:
|
||||
"""지정한 대상의 tmux 세션에 연결한다."""
|
||||
if self.pty and self.pty.is_alive:
|
||||
self.slack.send_message(
|
||||
channel, ":information_source: 이미 세션이 실행 중입니다."
|
||||
channel, ":information_source: 이미 세션에 연결되어 있습니다."
|
||||
)
|
||||
return
|
||||
|
||||
self._channel = channel
|
||||
self.pty = PtyManager(self.config.default_shell)
|
||||
self.pty.start()
|
||||
self._active_target = target
|
||||
self._last_sent_output = ""
|
||||
self.pty = PtyManager(
|
||||
self._session_name_for_target(target),
|
||||
cli_name=target,
|
||||
)
|
||||
try:
|
||||
self.pty.start()
|
||||
except RuntimeError as exc:
|
||||
self.pty = None
|
||||
self.slack.send_message(channel, f":warning: {exc}")
|
||||
return
|
||||
|
||||
self._running = True
|
||||
self._last_input_at = time.monotonic()
|
||||
self._last_output_at = time.monotonic()
|
||||
self._input_idle_reported = False
|
||||
self._output_idle_reported = False
|
||||
self._output_thread = threading.Thread(target=self._poll_output, daemon=True)
|
||||
self._output_thread.start()
|
||||
|
||||
self.slack.send_message(channel, ":rocket: Claude Code 세션이 시작되었습니다.")
|
||||
display_name = self._display_name(target)
|
||||
self.slack.send_message(
|
||||
channel, f":link: {display_name} 세션에 연결되었습니다."
|
||||
)
|
||||
|
||||
def _stop_session(self, channel: str) -> None:
|
||||
"""Claude Code 세션을 종료한다."""
|
||||
"""브릿지 연결만 해제한다."""
|
||||
self._running = False
|
||||
if self.pty:
|
||||
self.pty.stop()
|
||||
self.pty = None
|
||||
self.slack.send_message(channel, ":stop_sign: 세션이 종료되었습니다.")
|
||||
self._active_target = None
|
||||
self._last_sent_output = ""
|
||||
self.slack.send_message(channel, ":electric_plug: 세션 연결이 해제되었습니다.")
|
||||
|
||||
def _poll_output(self) -> None:
|
||||
"""PTY 출력을 주기적으로 읽어 Slack으로 전송한다."""
|
||||
buffer = ""
|
||||
while self._running and self.pty and self.pty.is_alive:
|
||||
now = time.monotonic()
|
||||
output = self.pty.read_output(timeout=self.config.pty_read_timeout)
|
||||
if output:
|
||||
buffer += output
|
||||
cleaned = clean_terminal_output(output)
|
||||
if cleaned:
|
||||
buffer += f"{cleaned}\n"
|
||||
self._last_output_at = now
|
||||
self._output_idle_reported = False
|
||||
|
||||
if buffer:
|
||||
# 메시지 길이 제한 적용
|
||||
message = buffer[: self.config.max_message_length]
|
||||
message = buffer[: self.config.max_message_length].rstrip()
|
||||
if len(buffer) > self.config.max_message_length:
|
||||
message += "\n... (truncated)"
|
||||
self.slack.send_message(self._channel, f"```\n{message}\n```")
|
||||
if message and message != self._last_sent_output:
|
||||
self.slack.send_message(self._channel, f"```\n{message}\n```")
|
||||
self._last_sent_output = message
|
||||
buffer = ""
|
||||
|
||||
output_idle = now - self._last_output_at
|
||||
if (
|
||||
self.config.output_idle_report_seconds > 0
|
||||
and not self._output_idle_reported
|
||||
and output_idle >= self.config.output_idle_report_seconds
|
||||
):
|
||||
self.slack.send_message(
|
||||
self._channel,
|
||||
(
|
||||
f":hourglass_flowing_sand: 출력이 {int(output_idle)}초 동안 "
|
||||
"없습니다. 세션 상태를 확인해주세요."
|
||||
),
|
||||
)
|
||||
self._output_idle_reported = True
|
||||
|
||||
input_idle = now - self._last_input_at
|
||||
if (
|
||||
self.config.input_idle_report_seconds > 0
|
||||
and not self._input_idle_reported
|
||||
and input_idle >= self.config.input_idle_report_seconds
|
||||
):
|
||||
self.slack.send_message(
|
||||
self._channel,
|
||||
f":information_source: 입력이 {int(input_idle)}초 동안 없습니다.",
|
||||
)
|
||||
self._input_idle_reported = True
|
||||
|
||||
time.sleep(self.config.output_buffer_interval)
|
||||
|
||||
if not self._running:
|
||||
return
|
||||
|
||||
# 프로세스가 예기치 않게 종료된 경우
|
||||
self.slack.send_message(self._channel, ":warning: 프로세스가 종료되었습니다.")
|
||||
# attach 프로세스가 예기치 않게 종료된 경우
|
||||
self.slack.send_message(self._channel, ":warning: 세션 연결이 종료되었습니다.")
|
||||
|
||||
def run(self) -> None:
|
||||
"""브릿지를 시작한다."""
|
||||
|
||||
@@ -18,10 +18,34 @@ class Config:
|
||||
allowed_user_id: str = os.getenv("SLACK_ALLOWED_USER_ID", "")
|
||||
allowed_channel_id: str = os.getenv("SLACK_ALLOWED_CHANNEL_ID", "")
|
||||
|
||||
# PTY
|
||||
default_shell: str = os.getenv("DEFAULT_SHELL", "claude")
|
||||
# PTY / tmux attach
|
||||
tmux_session_name: str = os.getenv("TMUX_SESSION_NAME", "claude")
|
||||
codex_tmux_session_name: str = os.getenv("CODEX_TMUX_SESSION_NAME", "codex")
|
||||
pty_read_timeout: int = int(os.getenv("PTY_READ_TIMEOUT", "5"))
|
||||
|
||||
# Buffer
|
||||
output_buffer_interval: float = float(os.getenv("OUTPUT_BUFFER_INTERVAL", "2.0"))
|
||||
max_message_length: int = int(os.getenv("MAX_MESSAGE_LENGTH", "3000"))
|
||||
|
||||
# Status reporting / reconnect
|
||||
reconnect_delay_seconds: float = float(os.getenv("RECONNECT_DELAY_SECONDS", "5.0"))
|
||||
output_idle_report_seconds: int = int(
|
||||
os.getenv("OUTPUT_IDLE_REPORT_SECONDS", "120")
|
||||
)
|
||||
input_idle_report_seconds: int = int(os.getenv("INPUT_IDLE_REPORT_SECONDS", "300"))
|
||||
|
||||
def validate_required_settings(self) -> None:
|
||||
"""필수 설정값 누락 여부를 검증한다."""
|
||||
missing: list[str] = []
|
||||
if not self.slack_bot_token:
|
||||
missing.append("SLACK_BOT_TOKEN")
|
||||
if not self.slack_app_token:
|
||||
missing.append("SLACK_APP_TOKEN")
|
||||
if not self.allowed_user_id:
|
||||
missing.append("SLACK_ALLOWED_USER_ID")
|
||||
if not self.allowed_channel_id:
|
||||
missing.append("SLACK_ALLOWED_CHANNEL_ID")
|
||||
|
||||
if missing:
|
||||
joined = ", ".join(missing)
|
||||
raise ValueError(f"필수 환경 변수가 누락되었습니다: {joined}")
|
||||
|
||||
32
src/lazy_enter/output_filter.py
Normal file
32
src/lazy_enter/output_filter.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""PTY 출력에서 터미널 제어 시퀀스를 제거한다."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
# ANSI CSI / OSC / DCS / 단일 ESC 시퀀스를 폭넓게 제거한다.
|
||||
_ANSI_ESCAPE_RE = re.compile(
|
||||
r"(?:\x1B\[[0-?]*[ -/]*[@-~])"
|
||||
r"|(?:\x1B\][^\x1B\x07]*(?:\x07|\x1B\\))"
|
||||
r"|(?:\x1BP[^\x1B]*(?:\x1B\\))"
|
||||
r"|(?:\x1B[@-_])"
|
||||
)
|
||||
|
||||
# ESC 문자가 유실된 상태로 남는 CSI 토큰(예: [38;2;153;153;153m) 제거.
|
||||
_BROKEN_CSI_RE = re.compile(r"\[(?:[0-9;<=>?]|(?:\d+;))*\d*[A-Za-z]")
|
||||
|
||||
# C0 제어문자 중 개행/탭/캐리지리턴을 제외하고 제거.
|
||||
_CONTROL_RE = re.compile(r"[\x00-\x08\x0B-\x1F\x7F]")
|
||||
|
||||
|
||||
def clean_terminal_output(text: str) -> str:
|
||||
"""Slack 전송용 텍스트를 정리한다."""
|
||||
cleaned = _ANSI_ESCAPE_RE.sub("", text)
|
||||
cleaned = _BROKEN_CSI_RE.sub("", cleaned)
|
||||
cleaned = cleaned.replace("\r", "")
|
||||
cleaned = _CONTROL_RE.sub("", cleaned)
|
||||
|
||||
# 제어 코드 제거 후 남는 빈 줄을 축소한다.
|
||||
lines = [line.rstrip() for line in cleaned.splitlines()]
|
||||
compact = "\n".join(lines).strip()
|
||||
return compact
|
||||
@@ -1,8 +1,9 @@
|
||||
"""pexpect 기반 PTY 프로세스 관리."""
|
||||
"""기존 tmux 세션에 attach하여 CLI 입출력을 중계한다."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
|
||||
import pexpect
|
||||
|
||||
@@ -10,21 +11,38 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PtyManager:
|
||||
"""가상 터미널에서 CLI 프로세스를 생성하고 입출력을 제어한다."""
|
||||
"""기존 tmux 세션에 attach하고 입출력을 제어한다."""
|
||||
|
||||
def __init__(self, command: str = "claude") -> None:
|
||||
self.command = command
|
||||
def __init__(self, session_name: str = "claude", cli_name: str = "claude") -> None:
|
||||
self.session_name = session_name
|
||||
self.cli_name = cli_name
|
||||
self._process: pexpect.spawn | None = None
|
||||
|
||||
@property
|
||||
def is_alive(self) -> bool:
|
||||
return self._process is not None and self._process.isalive()
|
||||
|
||||
def _ensure_session_exists(self) -> None:
|
||||
"""attach 대상 tmux 세션 존재 여부를 검증한다."""
|
||||
result = subprocess.run(
|
||||
["tmux", "has-session", "-t", self.session_name],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(
|
||||
"tmux 세션이 없습니다. 먼저 실행하세요: "
|
||||
f"tmux new -s {self.session_name} {self.cli_name}"
|
||||
)
|
||||
|
||||
def start(self) -> None:
|
||||
"""프로세스를 시작한다."""
|
||||
logger.info("프로세스 시작: %s", self.command)
|
||||
"""기존 tmux 세션에 attach한다."""
|
||||
self._ensure_session_exists()
|
||||
logger.info("tmux 세션 attach: %s", self.session_name)
|
||||
self._process = pexpect.spawn(
|
||||
self.command,
|
||||
"tmux",
|
||||
["attach-session", "-t", self.session_name],
|
||||
encoding="utf-8",
|
||||
timeout=None,
|
||||
)
|
||||
@@ -49,8 +67,8 @@ class PtyManager:
|
||||
return self._process.before or ""
|
||||
|
||||
def stop(self) -> None:
|
||||
"""프로세스를 종료한다."""
|
||||
"""attach 연결만 종료한다(원격 세션은 유지)."""
|
||||
if self._process is not None:
|
||||
logger.info("프로세스 종료")
|
||||
logger.info("tmux attach 종료")
|
||||
self._process.close(force=True)
|
||||
self._process = None
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
from slack_bolt import App
|
||||
from slack_bolt.adapter.socket_mode import SocketModeHandler
|
||||
@@ -19,9 +21,10 @@ class SlackHandler:
|
||||
def __init__(self, config: Config) -> None:
|
||||
self.config = config
|
||||
self.app = App(token=config.slack_bot_token)
|
||||
self._handler = SocketModeHandler(self.app, config.slack_app_token)
|
||||
self._on_message_callback: callable | None = None
|
||||
self._on_command_callback: callable | None = None
|
||||
self._handler: SocketModeHandler | None = None
|
||||
self._stop_requested = False
|
||||
self._on_message_callback: Callable[[str, str], None] | None = None
|
||||
self._on_command_callback: Callable[[str, str, str], None] | None = None
|
||||
|
||||
self._register_listeners()
|
||||
|
||||
@@ -44,7 +47,7 @@ class SlackHandler:
|
||||
"""Slack 이벤트 리스너를 등록한다."""
|
||||
|
||||
@self.app.event("message")
|
||||
def handle_message(event: dict, say: callable) -> None:
|
||||
def handle_message(event: dict, say: Callable[..., None]) -> None:
|
||||
user_id = event.get("user", "")
|
||||
channel_id = event.get("channel", "")
|
||||
text = event.get("text", "")
|
||||
@@ -56,7 +59,7 @@ class SlackHandler:
|
||||
self._on_message_callback(text, channel_id)
|
||||
|
||||
@self.app.command("/start-claude")
|
||||
def handle_start(ack: callable, body: dict) -> None:
|
||||
def handle_start_claude(ack: Callable[..., None], body: dict) -> None:
|
||||
ack()
|
||||
user_id = body.get("user_id", "")
|
||||
channel_id = body.get("channel_id", "")
|
||||
@@ -65,10 +68,10 @@ class SlackHandler:
|
||||
return
|
||||
|
||||
if self._on_command_callback:
|
||||
self._on_command_callback("start", channel_id)
|
||||
self._on_command_callback("start", "claude", channel_id)
|
||||
|
||||
@self.app.command("/stop-claude")
|
||||
def handle_stop(ack: callable, body: dict) -> None:
|
||||
def handle_stop_claude(ack: Callable[..., None], body: dict) -> None:
|
||||
ack()
|
||||
user_id = body.get("user_id", "")
|
||||
channel_id = body.get("channel_id", "")
|
||||
@@ -77,13 +80,37 @@ class SlackHandler:
|
||||
return
|
||||
|
||||
if self._on_command_callback:
|
||||
self._on_command_callback("stop", channel_id)
|
||||
self._on_command_callback("stop", "claude", channel_id)
|
||||
|
||||
def on_message(self, callback: callable) -> None:
|
||||
@self.app.command("/start-codex")
|
||||
def handle_start_codex(ack: Callable[..., None], body: dict) -> None:
|
||||
ack()
|
||||
user_id = body.get("user_id", "")
|
||||
channel_id = body.get("channel_id", "")
|
||||
|
||||
if not self._is_authorized(user_id, channel_id):
|
||||
return
|
||||
|
||||
if self._on_command_callback:
|
||||
self._on_command_callback("start", "codex", channel_id)
|
||||
|
||||
@self.app.command("/stop-codex")
|
||||
def handle_stop_codex(ack: Callable[..., None], body: dict) -> None:
|
||||
ack()
|
||||
user_id = body.get("user_id", "")
|
||||
channel_id = body.get("channel_id", "")
|
||||
|
||||
if not self._is_authorized(user_id, channel_id):
|
||||
return
|
||||
|
||||
if self._on_command_callback:
|
||||
self._on_command_callback("stop", "codex", channel_id)
|
||||
|
||||
def on_message(self, callback: Callable[[str, str], None]) -> None:
|
||||
"""메시지 수신 콜백을 등록한다."""
|
||||
self._on_message_callback = callback
|
||||
|
||||
def on_command(self, callback: callable) -> None:
|
||||
def on_command(self, callback: Callable[[str, str, str], None]) -> None:
|
||||
"""슬래시 커맨드 콜백을 등록한다."""
|
||||
self._on_command_callback = callback
|
||||
|
||||
@@ -98,11 +125,31 @@ class SlackHandler:
|
||||
)
|
||||
|
||||
def start(self) -> None:
|
||||
"""Socket Mode 핸들러를 시작한다."""
|
||||
"""Socket Mode 핸들러를 시작한다. 연결이 끊기면 재연결한다."""
|
||||
self._stop_requested = False
|
||||
logger.info("Slack Socket Mode 시작")
|
||||
self._handler.start()
|
||||
|
||||
while not self._stop_requested:
|
||||
try:
|
||||
self._handler = SocketModeHandler(self.app, self.config.slack_app_token)
|
||||
self._handler.start()
|
||||
except Exception:
|
||||
if self._stop_requested:
|
||||
break
|
||||
logger.exception("Socket Mode 연결이 종료되었습니다.")
|
||||
|
||||
if self._stop_requested:
|
||||
break
|
||||
|
||||
logger.warning(
|
||||
"Socket Mode 재연결 시도 (%s초 후)",
|
||||
self.config.reconnect_delay_seconds,
|
||||
)
|
||||
time.sleep(self.config.reconnect_delay_seconds)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Socket Mode 핸들러를 종료한다."""
|
||||
logger.info("Slack Socket Mode 종료")
|
||||
self._handler.close()
|
||||
self._stop_requested = True
|
||||
if self._handler is not None:
|
||||
self._handler.close()
|
||||
|
||||
115
tests/test_bridge.py
Normal file
115
tests/test_bridge.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""Bridge 명령 라우팅 테스트."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import types
|
||||
|
||||
slack_bolt = types.ModuleType("slack_bolt")
|
||||
slack_bolt.App = object
|
||||
socket_mode = types.ModuleType("slack_bolt.adapter.socket_mode")
|
||||
socket_mode.SocketModeHandler = object
|
||||
slack_sdk = types.ModuleType("slack_sdk")
|
||||
slack_sdk.WebClient = object
|
||||
sys.modules.setdefault("slack_bolt", slack_bolt)
|
||||
sys.modules.setdefault("slack_bolt.adapter.socket_mode", socket_mode)
|
||||
sys.modules.setdefault("slack_sdk", slack_sdk)
|
||||
|
||||
|
||||
class FakeSlackHandler:
|
||||
def __init__(self, _config) -> None:
|
||||
self.message_callback = None
|
||||
self.command_callback = None
|
||||
self.sent_messages: list[tuple[str, str]] = []
|
||||
|
||||
def on_message(self, callback) -> None:
|
||||
self.message_callback = callback
|
||||
|
||||
def on_command(self, callback) -> None:
|
||||
self.command_callback = callback
|
||||
|
||||
def send_message(self, channel: str, text: str) -> None:
|
||||
self.sent_messages.append((channel, text))
|
||||
|
||||
def start(self) -> None:
|
||||
return None
|
||||
|
||||
def stop(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class FakePtyManager:
|
||||
instances: list[FakePtyManager] = []
|
||||
|
||||
def __init__(self, session_name: str, cli_name: str = "claude") -> None:
|
||||
self.session_name = session_name
|
||||
self.cli_name = cli_name
|
||||
self._alive = False
|
||||
FakePtyManager.instances.append(self)
|
||||
|
||||
@property
|
||||
def is_alive(self) -> bool:
|
||||
return self._alive
|
||||
|
||||
def start(self) -> None:
|
||||
self._alive = True
|
||||
|
||||
def stop(self) -> None:
|
||||
self._alive = False
|
||||
|
||||
def send(self, _text: str) -> None:
|
||||
return None
|
||||
|
||||
def read_output(self, timeout: int = 5) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _make_bridge(monkeypatch):
|
||||
from lazy_enter.bridge import Bridge
|
||||
from lazy_enter.config import Config
|
||||
|
||||
monkeypatch.setattr("lazy_enter.bridge.SlackHandler", FakeSlackHandler)
|
||||
monkeypatch.setattr("lazy_enter.bridge.PtyManager", FakePtyManager)
|
||||
config = Config()
|
||||
config.tmux_session_name = "claude-room"
|
||||
config.codex_tmux_session_name = "codex-room"
|
||||
return Bridge(config)
|
||||
|
||||
|
||||
def test_start_claude_routes_to_claude_session(monkeypatch) -> None:
|
||||
FakePtyManager.instances.clear()
|
||||
bridge = _make_bridge(monkeypatch)
|
||||
|
||||
bridge._handle_command("start", "claude", "C1")
|
||||
|
||||
assert FakePtyManager.instances[-1].session_name == "claude-room"
|
||||
assert FakePtyManager.instances[-1].cli_name == "claude"
|
||||
assert bridge.slack.sent_messages[-1] == (
|
||||
"C1",
|
||||
":link: Claude 세션에 연결되었습니다.",
|
||||
)
|
||||
|
||||
|
||||
def test_start_codex_routes_to_codex_session(monkeypatch) -> None:
|
||||
FakePtyManager.instances.clear()
|
||||
bridge = _make_bridge(monkeypatch)
|
||||
|
||||
bridge._handle_command("start", "codex", "C1")
|
||||
|
||||
assert FakePtyManager.instances[-1].session_name == "codex-room"
|
||||
assert FakePtyManager.instances[-1].cli_name == "codex"
|
||||
assert bridge.slack.sent_messages[-1] == (
|
||||
"C1",
|
||||
":link: Codex 세션에 연결되었습니다.",
|
||||
)
|
||||
|
||||
|
||||
def test_unknown_target_is_rejected(monkeypatch) -> None:
|
||||
bridge = _make_bridge(monkeypatch)
|
||||
|
||||
bridge._handle_command("start", "unknown", "C1")
|
||||
|
||||
assert bridge.slack.sent_messages[-1] == (
|
||||
"C1",
|
||||
":warning: 지원하지 않는 대상입니다.",
|
||||
)
|
||||
@@ -1,11 +1,38 @@
|
||||
"""Config 테스트."""
|
||||
|
||||
import pytest
|
||||
|
||||
from lazy_enter.config import Config
|
||||
|
||||
|
||||
def test_config_defaults():
|
||||
config = Config()
|
||||
assert config.default_shell == "claude"
|
||||
assert config.tmux_session_name == "claude"
|
||||
assert config.codex_tmux_session_name == "codex"
|
||||
assert config.pty_read_timeout == 5
|
||||
assert config.output_buffer_interval == 2.0
|
||||
assert config.max_message_length == 3000
|
||||
assert config.reconnect_delay_seconds == 5.0
|
||||
assert config.output_idle_report_seconds == 120
|
||||
assert config.input_idle_report_seconds == 300
|
||||
|
||||
|
||||
def test_validate_required_settings_missing() -> None:
|
||||
config = Config()
|
||||
config.slack_bot_token = ""
|
||||
config.slack_app_token = ""
|
||||
config.allowed_user_id = ""
|
||||
config.allowed_channel_id = ""
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
config.validate_required_settings()
|
||||
|
||||
|
||||
def test_validate_required_settings_ok() -> None:
|
||||
config = Config()
|
||||
config.slack_bot_token = "xoxb-test"
|
||||
config.slack_app_token = "xapp-test"
|
||||
config.allowed_user_id = "U000"
|
||||
config.allowed_channel_id = "C000"
|
||||
|
||||
config.validate_required_settings()
|
||||
|
||||
18
tests/test_output_filter.py
Normal file
18
tests/test_output_filter.py
Normal file
@@ -0,0 +1,18 @@
|
||||
"""output_filter 모듈 테스트."""
|
||||
|
||||
from lazy_enter.output_filter import clean_terminal_output
|
||||
|
||||
|
||||
def test_clean_terminal_output_removes_ansi_sequences():
|
||||
raw = "\x1b[?2004h\x1b[38;2;153;153;153mClaude Code\x1b[39m"
|
||||
assert clean_terminal_output(raw) == "Claude Code"
|
||||
|
||||
|
||||
def test_clean_terminal_output_removes_broken_csi_tokens():
|
||||
raw = "[?2004h[38;2;153;153;153mhello[39m"
|
||||
assert clean_terminal_output(raw) == "hello"
|
||||
|
||||
|
||||
def test_clean_terminal_output_preserves_plain_text():
|
||||
raw = "line1\nline2"
|
||||
assert clean_terminal_output(raw) == "line1\nline2"
|
||||
@@ -1,16 +1,84 @@
|
||||
"""PtyManager 테스트."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import pytest
|
||||
|
||||
from lazy_enter.pty_manager import PtyManager
|
||||
|
||||
|
||||
class FakeSpawn:
|
||||
def __init__(self, *_args: object, **_kwargs: object) -> None:
|
||||
self.before = ""
|
||||
self._alive = True
|
||||
|
||||
def isalive(self) -> bool:
|
||||
return self._alive
|
||||
|
||||
def sendline(self, _text: str) -> None:
|
||||
return None
|
||||
|
||||
def expect(self, *_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
def close(self, force: bool = False) -> None:
|
||||
assert force is True
|
||||
self._alive = False
|
||||
|
||||
|
||||
def test_initial_state():
|
||||
pty = PtyManager("echo hello")
|
||||
pty = PtyManager("claude")
|
||||
assert not pty.is_alive
|
||||
|
||||
|
||||
def test_start_and_stop():
|
||||
pty = PtyManager("cat")
|
||||
def test_start_raises_when_tmux_session_missing(monkeypatch: pytest.MonkeyPatch):
|
||||
def fake_run(
|
||||
cmd: Sequence[str],
|
||||
check: bool,
|
||||
capture_output: bool,
|
||||
text: bool,
|
||||
):
|
||||
assert list(cmd) == ["tmux", "has-session", "-t", "claude"]
|
||||
assert check is False
|
||||
assert capture_output is True
|
||||
assert text is True
|
||||
|
||||
class Result:
|
||||
returncode = 1
|
||||
|
||||
return Result()
|
||||
|
||||
monkeypatch.setattr("lazy_enter.pty_manager.subprocess.run", fake_run)
|
||||
|
||||
pty = PtyManager("claude")
|
||||
with pytest.raises(RuntimeError):
|
||||
pty.start()
|
||||
|
||||
|
||||
def test_start_and_stop_attach(monkeypatch: pytest.MonkeyPatch):
|
||||
def fake_run(
|
||||
_cmd: Sequence[str],
|
||||
check: bool,
|
||||
capture_output: bool,
|
||||
text: bool,
|
||||
):
|
||||
assert check is False
|
||||
assert capture_output is True
|
||||
assert text is True
|
||||
|
||||
class Result:
|
||||
returncode = 0
|
||||
|
||||
return Result()
|
||||
|
||||
monkeypatch.setattr("lazy_enter.pty_manager.subprocess.run", fake_run)
|
||||
monkeypatch.setattr("lazy_enter.pty_manager.pexpect.spawn", FakeSpawn)
|
||||
|
||||
pty = PtyManager("claude")
|
||||
pty.start()
|
||||
assert pty.is_alive
|
||||
|
||||
pty.stop()
|
||||
assert not pty.is_alive
|
||||
|
||||
Reference in New Issue
Block a user