Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c718b5cbc5 | ||
|
|
b948b09ba1 | ||
|
|
9c107fa895 | ||
|
|
42803de966 | ||
|
|
2c230c8c7f |
No files matched your search
+12
-3
@@ -428,11 +428,20 @@ URL 만 알면 누구나 이 엔드포인트를 때릴 수 있고, `userRequest.
|
||||
|
||||
```
|
||||
카카오 → 우리 발화 + callbackUrl
|
||||
우리 → 카카오 {"version":"2.0","useCallback":true,"data":{"text":"확인하고 있어요…"}} (즉답)
|
||||
… 백그라운드에서 답을 만든다 (상한 45초)
|
||||
우리 → 카카오 POST callbackUrl {"version":"2.0","template":{…}} (완성분)
|
||||
… 답을 만들기 시작하고 FAST_REPLY_SEC(3.5초)까지 기다린다
|
||||
(빨리 끝남) 우리 → 카카오 {"version":"2.0","template":{…}} (바로 답, 콜백 안 씀)
|
||||
(늦어짐) 우리 → 카카오 {"version":"2.0","useCallback":true,"data":{"text":"확인하고 있어요…"}} (즉답)
|
||||
… 같은 작업을 끝까지 기다린다 (처음부터 상한 45초)
|
||||
우리 → 카카오 POST callbackUrl {"version":"2.0","template":{…}} (완성분)
|
||||
```
|
||||
|
||||
★ **대기 문구는 늦어질 때만 나간다**(2026-10-02). 예전엔 콜백이 켜져 있으면 무조건 대기 문구부터
|
||||
보내서, 1초면 끝나는 답에도 "확인하고 있어요" 가 먼저 붙었다 — 사장님에게는 두 번 말하는 봇이다.
|
||||
★ 3.5초를 넘겨도 작업을 **취소하지 않고**(`asyncio.shield`) 그 작업의 결과를 콜백으로 보낸다.
|
||||
취소하고 다시 돌리면 도구(값 바꾸기·발행 접수)가 두 번 실행될 수 있다.
|
||||
★ 콜백이 켜진 블록에서 `useCallback` 없이 일반 응답을 주는 것은 개발 채널에서 실제로 확인한 뒤
|
||||
운영에 올린다 — 카카오 문서상 허용이지만 이 레포에서 아직 실측하지 않았다.
|
||||
|
||||
★ 콜백 주소는 **1분 · 1회**만 유효하다. 전송에 실패해도 **재시도하지 않는다** — 두 번째 POST 는
|
||||
어차피 거절되고, 사장님에게는 이미 "확인하고 있어요" 가 가 있다.
|
||||
|
||||
|
||||
+5
-2
@@ -47,8 +47,11 @@
|
||||
|
||||
## 가게 정보 조회 · 수정
|
||||
|
||||
동작 : "지금 저장된 정보 보여줘", "주차 정보 뭐로 돼 있어?"
|
||||
행동 : 저장된 값을 최대 20개까지 보여 줌 (키워드를 말하면 그 항목만)
|
||||
동작 : "가게 정보 알려줘", "지금 저장된 정보 보여줘"
|
||||
행동 : 요약을 보여 줌 — 가게 이름·업종, 발행 여부·마지막 발행 시각·사이트 주소, 업종 핵심 항목(스키마 `critical`)만 한 줄씩(긴 값은 첫 줄 30자에서 자름), 나머지는 개수로만
|
||||
|
||||
동작 : "주차 정보 뭐로 돼 있어?", "취소 규정 보여줘"
|
||||
행동 : 그 항목만 자르지 않고 보여 줌 (최대 20개)
|
||||
|
||||
동작 : "체크인 오후 3시로 바꿔줘", "체크인 15시 30분", "체크인 3시 반"
|
||||
행동 : 시각으로 저장 (15:00 / 15:30). "3시"처럼 오전인지 오후인지 모르면 되물음
|
||||
|
||||
@@ -12,8 +12,10 @@
|
||||
★ 5초 벽: 오픈빌더의 스킬 타임아웃은 **5초**다. 넘기면 카카오가 끊어 사장님에게는
|
||||
**말없이 실패하는 봇**이 된다.
|
||||
→ 오픈빌더 스킬 설정에서 **콜백 사용**을 켜면 요청에 `userRequest.callbackUrl` 이 실려 온다.
|
||||
그때는 `{"useCallback": true}` 로 **즉답**하고, 답을 다 만든 뒤 그 주소로 따로 보낸다.
|
||||
콜백 주소는 **1분 · 1회**만 유효하다.
|
||||
그때도 `FAST_REPLY_SEC` 안에 끝나면 **답을 바로** 준다. 넘을 때만 `{"useCallback": true}` 로
|
||||
대기 문구를 즉답하고, 답을 다 만든 뒤 그 주소로 따로 보낸다. 콜백 주소는 **1분 · 1회**만 유효하다.
|
||||
예전엔 콜백이 켜져 있으면 무조건 대기 문구부터 나가서, 1초면 끝나는 답에도 "확인하고 있어요"
|
||||
가 먼저 붙었다(2026-10-02, 사장님 체감 지적).
|
||||
→ 콜백이 꺼져 있으면 예전처럼 동기로 답하되 `DEADLINE_SEC` 로 끊는다. 실측(2026-09-22):
|
||||
필드 43개 + fact 수십 개가 실린 실제 프롬프트는 4초를 넘겼다 — 개발 중 재본
|
||||
1.3~2.4초는 항목 두 개짜리 장난감 프롬프트였다.
|
||||
@@ -36,6 +38,8 @@ router = APIRouter(prefix="/v1/agent/kakao", tags=["Agent"])
|
||||
DEADLINE_SEC = 4.5
|
||||
# 콜백이 켜져 있을 때의 상한. 콜백 주소가 1분간 유효하므로 그 안에서 넉넉히 잡는다.
|
||||
CALLBACK_DEADLINE_SEC = 45.0
|
||||
# 콜백이 켜져 있어도 이 안에 끝나면 대기 문구 없이 바로 답한다. 5초 벽에서 왕복 몫을 남긴다.
|
||||
FAST_REPLY_SEC = 3.5
|
||||
|
||||
_TIMEOUT_TEXT = "확인하는 데 시간이 조금 걸리네요. 잠시 뒤 다시 말씀해 주세요."
|
||||
_ERROR_TEXT = "지금은 처리할 수 없어요. 잠시 뒤 다시 말씀해 주세요."
|
||||
@@ -102,10 +106,13 @@ def _authorize(secret_in_path: str | None, header_secret: str | None, body: dict
|
||||
|
||||
|
||||
async def _answer(utterance: str, speaker: str, deadline: float, app_user_id: str = '') -> dict:
|
||||
return await _settle(asyncio.ensure_future(channel.handle(utterance, speaker, app_user_id)), deadline)
|
||||
|
||||
|
||||
async def _settle(task: asyncio.Future, deadline: float) -> dict:
|
||||
"""대화 한 턴을 SkillResponse 로. 어떤 실패도 문구로 바꾼다."""
|
||||
try:
|
||||
answer = await asyncio.wait_for(
|
||||
channel.handle(utterance, speaker, app_user_id), timeout=deadline)
|
||||
answer = await asyncio.wait_for(task, timeout=deadline)
|
||||
except asyncio.TimeoutError:
|
||||
LOG.w("[agent/kakao] 응답 시간 초과 — 안내로 끊음")
|
||||
return _reply(_TIMEOUT_TEXT)
|
||||
@@ -159,12 +166,12 @@ async def _approve_click(extra: dict, speaker: str) -> dict:
|
||||
return _reply_from(answer)
|
||||
|
||||
|
||||
async def _push(callback_url: str, utterance: str, speaker: str, app_user_id: str = '') -> None:
|
||||
"""답을 다 만든 뒤 콜백 주소로 보낸다.
|
||||
async def _push(callback_url: str, task: asyncio.Future, deadline: float) -> None:
|
||||
"""이미 돌고 있는 대화 한 턴이 끝나기를 기다렸다가 콜백 주소로 보낸다.
|
||||
|
||||
★ 주소는 1분 · 1회만 유효하다. 실패해도 재시도하지 않는다 — 두 번째 POST 는 어차피
|
||||
거절되고, 사장님에게는 이미 "확인하고 있어요" 가 가 있다."""
|
||||
payload = await _answer(utterance, speaker, CALLBACK_DEADLINE_SEC, app_user_id)
|
||||
payload = await _settle(task, deadline)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
res = await client.post(callback_url, json=payload)
|
||||
@@ -212,8 +219,18 @@ async def _handle(body: dict, tasks: BackgroundTasks) -> dict:
|
||||
LOG.i(f"[agent/kakao] 요청 — callbackUrl={'있음' if callback_url else '없음'} "
|
||||
f"block={(request.get('block') or {}).get('name')!r}")
|
||||
if callback_url:
|
||||
tasks.add_task(_push, callback_url, utterance, speaker, app_user_id)
|
||||
return {"version": "2.0", "useCallback": True, "data": {"text": _WAIT_TEXT}}
|
||||
# ★ 기다리는 동안 작업을 취소하지 않는다(shield) — 늦어지면 같은 작업을 콜백으로 이어 보낸다.
|
||||
# 취소하고 다시 돌리면 도구가 두 번 실행될 수 있다.
|
||||
task = asyncio.ensure_future(channel.handle(utterance, speaker, app_user_id))
|
||||
try:
|
||||
answer = await asyncio.wait_for(asyncio.shield(task), timeout=FAST_REPLY_SEC)
|
||||
except asyncio.TimeoutError:
|
||||
tasks.add_task(_push, callback_url, task, CALLBACK_DEADLINE_SEC - FAST_REPLY_SEC)
|
||||
return {"version": "2.0", "useCallback": True, "data": {"text": _WAIT_TEXT}}
|
||||
except Exception as ex: # noqa: BLE001 — 메신저에서는 500 도 침묵으로 보인다
|
||||
LOG.w(f"[agent/kakao] 처리 실패: {type(ex).__name__}: {ex}")
|
||||
return _reply(_ERROR_TEXT)
|
||||
return _reply_from(answer)
|
||||
|
||||
return await _answer(utterance, speaker, DEADLINE_SEC, app_user_id)
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""목업(stay · stay2) index.html 의 미니블로그 글을 DB 최신으로 채운다. 목업을 덮어쓴 직후에 돌린다."""
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import places, sites
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from services import build_service, mockup_blog
|
||||
|
||||
|
||||
async def _load_place(slug: str):
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: DB_SESSION_MNG.execute(
|
||||
s,
|
||||
select(places)
|
||||
.join(sites, sites.place_id == places.place_id)
|
||||
.where(sites.domain == slug, places.deleted == False) # noqa: E712
|
||||
.limit(1),
|
||||
),
|
||||
)
|
||||
return (rows[0] if rows else None) if err == ErrorType.SUCCESS else None
|
||||
|
||||
|
||||
async def main(slug: str) -> None:
|
||||
if not mockup_blog.is_mockup(slug):
|
||||
raise SystemExit(f"목업이 아니다: {slug} (대상: {', '.join(sorted(mockup_blog.MOCKUP_SLUGS))})")
|
||||
try:
|
||||
place = await _load_place(slug)
|
||||
if place is None:
|
||||
raise SystemExit(f"domain={slug} 인 사이트의 사업장이 없다")
|
||||
result = await build_service._refresh_mockup_blog(place, str(place.place_id), slug)
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
finally:
|
||||
await DB_SESSION_MNG.dispose_all()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("slug", nargs="?", default="stay")
|
||||
asyncio.run(main(parser.parse_args().slug))
|
||||
@@ -208,35 +208,79 @@ def _display(spec, value: str) -> str:
|
||||
|
||||
# ── 읽기 ────────────────────────────────────────────────────────────────
|
||||
|
||||
async def _get_site_status(ctx: ToolContext, args: dict) -> str:
|
||||
async def _published(ctx: ToolContext) -> tuple[str, str] | None:
|
||||
"""(주소, 마지막 발행 시각). 발행 전이면 None."""
|
||||
_fact, site_service = _services()
|
||||
res = await site_service.get_site(ctx.user, ctx.place_id)
|
||||
site = res.site
|
||||
site = (await site_service.get_site(ctx.user, ctx.place_id)).site
|
||||
if site is None or site.published_at is None:
|
||||
return "아직 발행 전입니다. 준비가 되면 발행해 드릴게요."
|
||||
return None
|
||||
# ★ 주소는 site_payload 의 함수로 만든다. 문자열로 조립하면 canonical 과 갈린다
|
||||
# (CLAUDE.md '슬러그 규칙은 두 곳에 있고 같아야 한다').
|
||||
url = f"{site_payload.publish_origin()}/s/{site_payload.publish_slug(ctx.place, site)}"
|
||||
when = site.published_at.strftime("%Y-%m-%d %H:%M")
|
||||
return url, site.published_at.strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
|
||||
async def _get_site_status(ctx: ToolContext, args: dict) -> str:
|
||||
published = await _published(ctx)
|
||||
if published is None:
|
||||
return "아직 발행 전입니다. 준비가 되면 발행해 드릴게요."
|
||||
url, when = published
|
||||
return f"발행되어 있습니다.\n주소: {url}\n마지막 발행: {when}"
|
||||
|
||||
|
||||
# 요약 한 줄에 싣는 값의 길이. 카톡 말풍선에서 한 줄로 읽히는 정도다.
|
||||
SUMMARY_VALUE_MAX = 30
|
||||
|
||||
|
||||
def _short(value: str) -> str:
|
||||
"""첫 줄만, 길면 자른다 — 순환 문구처럼 수십 줄인 값이 요약을 통째로 덮었다(2026-10-21 캡처)."""
|
||||
lines = value.strip().splitlines()
|
||||
first = lines[0].strip() if lines else ""
|
||||
if len(first) > SUMMARY_VALUE_MAX:
|
||||
return first[:SUMMARY_VALUE_MAX].rstrip() + "…"
|
||||
return first + ("…" if len(lines) > 1 else "")
|
||||
|
||||
|
||||
async def _list_facts(ctx: ToolContext, args: dict) -> str:
|
||||
"""키워드가 없으면 요약(발행 주소 + 업종 핵심 항목), 있으면 그 항목을 자르지 않고.
|
||||
|
||||
★ 요약 항목은 업종 스키마의 `critical` 이다 — 틀리면 예약 클레임이 나는 값이라 사장님이
|
||||
제일 먼저 확인해야 하고, 목록을 여기 따로 두면 스키마와 갈린다."""
|
||||
fact_service, _site = _services()
|
||||
res = await fact_service.list_facts(ctx.user, ctx.place_id, publishable_only=True)
|
||||
rows = [f for f in (res.facts or []) if (f.value or "").strip()]
|
||||
schema = get_schema(PlaceCategory(ctx.place.category))
|
||||
|
||||
def label(f) -> str:
|
||||
spec = schema.get(f.key)
|
||||
return spec.label if spec else f.key
|
||||
|
||||
def shown(f) -> str:
|
||||
spec = schema.get(f.key)
|
||||
return _display(spec, f.value) if spec else f.value
|
||||
|
||||
keyword = _arg(args, "keyword")
|
||||
if keyword:
|
||||
rows = [f for f in rows if keyword in f.key or keyword in ((schema.get(f.key).label if schema.get(f.key) else ""))]
|
||||
if not rows:
|
||||
return "저장된 가게 정보가 아직 없습니다." if not keyword else f"'{keyword}' 로 찾은 정보가 없습니다."
|
||||
lines = []
|
||||
for f in rows[:20]:
|
||||
spec = schema.get(f.key)
|
||||
lines.append(f"· {spec.label if spec else f.key}: {f.value}")
|
||||
more = f"\n(그 밖에 {len(rows) - 20}개 더 있습니다)" if len(rows) > 20 else ""
|
||||
return "지금 저장된 정보입니다.\n" + "\n".join(lines) + more
|
||||
rows = [f for f in rows if keyword in f.key or keyword in label(f)]
|
||||
if not rows:
|
||||
return f"'{keyword}' 로 찾은 정보가 없습니다."
|
||||
lines = [f"· {label(f)}: {shown(f)}" for f in rows[:20]]
|
||||
more = f"\n(그 밖에 {len(rows) - 20}개 더 있습니다)" if len(rows) > 20 else ""
|
||||
return "\n".join(lines) + more
|
||||
|
||||
published = await _published(ctx)
|
||||
head = [f"{ctx.place.name} · {schema.label}"]
|
||||
head += [f"발행됨 · {published[1]}", published[0]] if published else ["아직 발행 전이에요."]
|
||||
|
||||
critical = set(schema.critical_keys())
|
||||
key_rows = [f for f in rows if f.key in critical]
|
||||
body = ["핵심 정보"] + [f"· {label(f)}: {_short(shown(f))}" for f in key_rows] if key_rows \
|
||||
else ["저장된 핵심 정보가 아직 없어요."]
|
||||
|
||||
rest = len(rows) - len(key_rows)
|
||||
tail = [f"그 밖에 {rest}개 항목이 저장돼 있어요."] if rest else []
|
||||
tail.append("\"주차 정보 보여줘\"처럼 물어보시면 자세히 알려 드려요.")
|
||||
return "\n\n".join(["\n".join(head), "\n".join(body), "\n".join(tail)])
|
||||
|
||||
|
||||
# ── 되돌릴 수 있는 쓰기 ──────────────────────────────────────────────────
|
||||
@@ -688,7 +732,7 @@ REGISTRY: dict[str, Tool] = {
|
||||
name="list_facts",
|
||||
grade=ToolGrade.READ,
|
||||
title="가게 정보 보기",
|
||||
summary="지금 저장된 가게 정보를 보여준다.",
|
||||
summary="가게 정보를 요약해 보여준다(발행 주소 포함). 특정 항목을 물으면 그 값을 자세히 보여준다.",
|
||||
args={"keyword": "찾고 싶은 항목이 있으면 그 말(선택)"},
|
||||
run=_list_facts,
|
||||
),
|
||||
|
||||
@@ -1116,3 +1116,54 @@ async def test_못_한_요청_이름의_줄바꿈은_한_칸으로_편다(client
|
||||
choose({"actions": [], "skipped": ["전화번호\n변경"], "message": ""})
|
||||
reply = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "전화번호"})).json()["reply"]
|
||||
assert "'전화번호 변경' 은(는)" in reply
|
||||
|
||||
|
||||
# ── 가게 정보 요약 (2026-10-23) ─────────────────────────────────────────
|
||||
|
||||
async def _say(client, h, pid, choose, actions, message="해줘"):
|
||||
choose({"actions": actions, "message": ""})
|
||||
return (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": message})).json()["reply"]
|
||||
|
||||
|
||||
async def _fill(client, h, pid, choose):
|
||||
await _say(client, h, pid, choose, [
|
||||
{"tool": "set_fact", "args": {"key": "check_in_time", "value": "15:00"}},
|
||||
{"tool": "set_fact", "args": {"key": "pet_allowed", "value": "가능"}},
|
||||
{"tool": "set_fact", "args": {"key": "cancel_policy", "value": "이용 7일 전까지 전액 환불, 3일 전까지 50% 환불, 이후 환불 불가\n당일 취소 불가"}},
|
||||
{"tool": "set_fact", "args": {"key": "wifi", "value": "가능"}},
|
||||
])
|
||||
|
||||
|
||||
async def test_가게_정보는_핵심_항목만_요약한다(client, auth_headers, choose, db_engine):
|
||||
"""캡처(2026-10-21): 순환 문구 한 항목이 20줄을 넘겨 요약을 덮었고, 바비큐가 'true' 로 나왔다."""
|
||||
h, pid = await seed(client, auth_headers, name="요약숙소")
|
||||
await _fill(client, h, pid, choose)
|
||||
|
||||
reply = await _say(client, h, pid, choose, [{"tool": "list_facts", "args": {}}], "가게 정보 알려줘")
|
||||
assert reply.startswith("요약숙소 · 숙박")
|
||||
assert "아직 발행 전이에요." in reply
|
||||
assert "· 체크인 시간: 15:00" in reply
|
||||
assert "· 반려동물 동반: 가능" in reply
|
||||
assert "true" not in reply
|
||||
assert "와이파이" not in reply # critical 아님 → 개수로만
|
||||
assert "그 밖에 1개 항목이 저장돼 있어요." in reply
|
||||
assert "당일 취소 불가" not in reply # 둘째 줄은 싣지 않는다
|
||||
line = next(x for x in reply.splitlines() if x.startswith("· 취소·환불 규정"))
|
||||
assert line.endswith("…") and len(line.split(": ", 1)[1]) <= tools.SUMMARY_VALUE_MAX + 1
|
||||
|
||||
|
||||
async def test_발행됐으면_요약에_주소가_붙는다(client, auth_headers, choose, db_engine, monkeypatch):
|
||||
h, pid = await seed(client, auth_headers)
|
||||
monkeypatch.setattr(tools, "_published", AsyncMock(return_value=("https://host/s/x", "2026-10-21 14:30")))
|
||||
reply = await _say(client, h, pid, choose, [{"tool": "list_facts", "args": {}}], "가게 정보 알려줘")
|
||||
assert "발행됨 · 2026-10-21 14:30\nhttps://host/s/x" in reply
|
||||
assert "저장된 핵심 정보가 아직 없어요." in reply
|
||||
|
||||
|
||||
async def test_항목을_물으면_자르지_않고_보여준다(client, auth_headers, choose, db_engine):
|
||||
h, pid = await seed(client, auth_headers)
|
||||
await _fill(client, h, pid, choose)
|
||||
reply = await _say(client, h, pid, choose, [{"tool": "list_facts", "args": {"keyword": "취소"}}], "취소 규정 보여줘")
|
||||
assert "당일 취소 불가" in reply
|
||||
reply = await _say(client, h, pid, choose, [{"tool": "list_facts", "args": {"keyword": "와이파이"}}], "와이파이 보여줘")
|
||||
assert "· 와이파이: 가능" in reply
|
||||
@@ -317,19 +317,55 @@ async def test_목록은_발행_여부를_같이_말한다(client, auth_headers,
|
||||
|
||||
# ── 콜백 (5초 벽 넘기) ───────────────────────────────────────────────────
|
||||
|
||||
async def test_콜백이_켜져_있으면_즉답하고_뒤에서_마저_만든다(client, auth_headers, db_engine, monkeypatch):
|
||||
"""오픈빌더 스킬 타임아웃은 5초다."""
|
||||
async def test_콜백이_켜져_있어도_빨리_끝나면_대기_문구_없이_바로_답한다(client, db_engine, monkeypatch):
|
||||
"""1초면 끝나는 답에 "확인하고 있어요" 가 먼저 붙으면 사장님에게는 두 번 말하는 봇이다."""
|
||||
import router.v1.agent.kakao_bot as bot
|
||||
|
||||
pushed = AsyncMock()
|
||||
monkeypatch.setattr(bot, "_push", pushed)
|
||||
|
||||
payload = body("안녕", "콜백-빠른-발화자")
|
||||
payload["userRequest"]["callbackUrl"] = "https://callback.example/one-shot"
|
||||
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=payload)
|
||||
|
||||
assert "useCallback" not in res.json()
|
||||
assert "연결" in said(res)
|
||||
pushed.assert_not_awaited() # 콜백 주소는 쓰지 않는다
|
||||
|
||||
|
||||
async def test_콜백이_켜져_있고_늦어지면_즉답하고_같은_작업을_콜백으로_보낸다(client, monkeypatch):
|
||||
"""오픈빌더 스킬 타임아웃은 5초다. 늦어진 작업은 취소하지 않고 끝난 결과를 콜백으로 보낸다."""
|
||||
import asyncio
|
||||
|
||||
import router.v1.agent.kakao_bot as bot
|
||||
|
||||
runs = []
|
||||
|
||||
async def slow_handle(utterance, speaker, app_user_id=""):
|
||||
runs.append(utterance)
|
||||
await asyncio.sleep(0.2)
|
||||
return channel._say("늦은 답")
|
||||
|
||||
monkeypatch.setattr(bot.channel, "handle", slow_handle)
|
||||
monkeypatch.setattr(bot, "FAST_REPLY_SEC", 0.05)
|
||||
|
||||
sent = {}
|
||||
|
||||
async def fake_push(callback_url, utterance, speaker, app_user_id=""):
|
||||
sent["url"] = callback_url
|
||||
sent["payload"] = await bot._answer(utterance, speaker, 5.0)
|
||||
class FakeClient:
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
monkeypatch.setattr(bot, "_push", fake_push)
|
||||
async def __aexit__(self, *_):
|
||||
return False
|
||||
|
||||
payload = body("안녕", "콜백-발화자")
|
||||
async def post(self, url, json):
|
||||
sent["url"], sent["payload"] = url, json
|
||||
return SimpleNamespace(status_code=200)
|
||||
|
||||
# 테스트 클라이언트도 httpx 라 모듈 전체가 아니라 bot 이 보는 이름만 바꾼다.
|
||||
monkeypatch.setattr(bot, "httpx", SimpleNamespace(AsyncClient=lambda **_kw: FakeClient()))
|
||||
|
||||
payload = body("휴무 바꿔줘", "콜백-느린-발화자")
|
||||
payload["userRequest"]["callbackUrl"] = "https://callback.example/one-shot"
|
||||
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=payload)
|
||||
|
||||
@@ -338,9 +374,10 @@ async def test_콜백이_켜져_있으면_즉답하고_뒤에서_마저_만든
|
||||
assert res.json()["data"]["text"]
|
||||
assert "template" not in res.json()
|
||||
|
||||
# 실제 답은 콜백으로 간다.
|
||||
# 실제 답은 콜백으로 가고, 작업은 한 번만 돌았다.
|
||||
assert sent["url"] == "https://callback.example/one-shot"
|
||||
assert "연결" in sent["payload"]["template"]["outputs"][0]["simpleText"]["text"]
|
||||
assert sent["payload"]["template"]["outputs"][0]["simpleText"]["text"] == "늦은 답"
|
||||
assert runs == ["휴무 바꿔줘"]
|
||||
|
||||
|
||||
async def test_콜백이_없으면_예전처럼_동기로_답한다(client, db_engine):
|
||||
@@ -353,7 +390,10 @@ async def test_콜백_전송이_실패해도_터지지_않는다(monkeypatch):
|
||||
"""주소는 1분 · 1회다."""
|
||||
import router.v1.agent.kakao_bot as bot
|
||||
|
||||
monkeypatch.setattr(bot, "_answer", AsyncMock(return_value=bot._reply("답")))
|
||||
import asyncio
|
||||
|
||||
done = asyncio.get_running_loop().create_future()
|
||||
done.set_result(channel._say("답"))
|
||||
|
||||
class Boom:
|
||||
async def __aenter__(self):
|
||||
@@ -363,7 +403,7 @@ async def test_콜백_전송이_실패해도_터지지_않는다(monkeypatch):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(bot.httpx, "AsyncClient", lambda **_kw: Boom())
|
||||
await bot._push("https://callback.example/x", "안녕", "누구") # 예외가 새 나오지 않는다
|
||||
await bot._push("https://callback.example/x", done, 1.0) # 예외가 새 나오지 않는다
|
||||
|
||||
|
||||
# ── 여러 가게 ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -783,18 +783,19 @@ docker exec \$C mkdir -p /app/solution/site/out/s/stay/img/people /app/solution/
|
||||
docker cp build/index.html \$C:/app/solution/site/out/s/stay/index.html
|
||||
docker cp img/. \$C:/app/solution/site/out/s/stay/img/
|
||||
docker cp audio/. \$C:/app/solution/site/out/s/stay/audio/
|
||||
docker cp vendor/. \$C:/app/solution/site/out/s/stay/vendor/"
|
||||
docker cp vendor/. \$C:/app/solution/site/out/s/stay/vendor/
|
||||
docker exec -w /app/solution/backend \$C python scripts/refresh_mockup_blog.py stay"
|
||||
```
|
||||
|
||||
★ **덮기 전에 운영본을 백업한다** — `docker exec $C cp …/s/stay/index.html …/s/stay/index.html.bak-<날짜>`.
|
||||
|
||||
### 미니블로그 글
|
||||
|
||||
`build/index.html` 의 `posts` 는 비어 있다. 덮은 직후 `/s/stay` 의 미니블로그가 비어 보이는 게 정상이다.
|
||||
글은 DB(`place_posts`)에서 다시 채운다 — 스테이,머뭄 계정으로 빌더에서 **발행**을 한 번 누른다.
|
||||
`stay` 는 목업이라 발행이 사이트를 굽지 않고 `index.html` 의 `posts` 만 갈아 끼운다
|
||||
(`solution/backend/services/mockup_blog.py` `refresh_posts`, `build_service._refresh_mockup_blog`).
|
||||
블로그 글이 승인·게재될 때도 같은 경로로 자동으로 채워진다. 갈아 끼우기 직전 파일은 `index.html.bak-blog` 로 남는다.
|
||||
`build/index.html` 의 `posts` 는 비어 있다 — 빌드는 DB 없이 어느 PC 에서나 돌게 해 두었다.
|
||||
그래서 덮어쓴 **바로 다음에** `scripts/refresh_mockup_blog.py stay` 를 worker 안에서 돌려 DB 최신 글을 채운다
|
||||
(위 킹서버 명령 마지막 줄). 글만 갈아 끼우고 나머지는 건드리지 않는다
|
||||
(`solution/backend/services/mockup_blog.py` `refresh_posts`). 직전 파일은 `index.html.bak-blog` 로 남는다.
|
||||
블로그 글이 승인·게재될 때도 같은 경로로 자동으로 채워진다.
|
||||
|
||||
확인: 글을 채운 뒤 `node audit-all.mjs https://web4ai.o2osolution.ai/s/stay`.
|
||||
`index.html` 은 글 때문에 `build/index.html` 과 md5 가 다르다 — 비교하려면 payload 의 `posts` 를 빼고 본다.
|
||||
|
||||
Reference in new issue
Block a user