merge: origin/main(에이전트 여러 동작 · 사진 도구 · 카톡 승인 알림) 을 feature/template-catalog 에 병합

충돌은 이 브랜치의 주석 정리 커밋(11d30bb)과 main 의 기능 변경이 겹친 백엔드 9개 파일 —
main 쪽을 그대로 썼다(기능이 main 에만 있다). AGENTS.md 는 양쪽 링크를 모두 두고,
DEVLOG 는 요약본 위에 main 의 09-28 에이전트 항목 셋을 붙였다.

site eslint 통과 · vitest 123 passed · frontend tsc·eslint 통과 · 백엔드 py_compile 통과
(백엔드 pytest 는 이 기계에 테스트 DB 계정이 없어 실행하지 못함)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 5.5 committed 2026-09-30 13:51:53 +09:00
commit 1dc4f5fbf5
33 files changed
+4208 -209

No files matched your search

+330 -1
View File
@@ -131,7 +131,8 @@ async def test_발행은_묻고_바로가기를_준다(client, auth_headers, db_
await link(db_engine, client, auth_headers, speaker)
# 테스트는 실제 모델을 부르지 않는다 — 런타임만 열고 선택 결과를 대신 준다.
monkeypatch.setattr(runtime, "is_configured", lambda: True)
monkeypatch.setattr(runtime, "_choose", AsyncMock(return_value={"tool": "publish", "args": {}, "message": ""}))
monkeypatch.setattr(runtime, "_choose",
AsyncMock(return_value={"actions": [{"tool": "publish", "args": {}}], "message": ""}))
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=body("발행해줘", speaker))
assert channel.CONFIRM_LABEL in quick(res)
@@ -363,3 +364,331 @@ async def test_콜백_전송이_실패해도_터지지_않는다(monkeypatch):
monkeypatch.setattr(bot.httpx, "AsyncClient", lambda **_kw: Boom())
await bot._push("https://callback.example/x", "안녕", "누구") # 예외가 새 나오지 않는다
# ── 여러 가게 ────────────────────────────────────────────────────────────
async def test_다른_가게_이름이_나오면_지금_가게를_고치지_않는다(client, auth_headers, db_engine, monkeypatch):
"""★ 프롬프트에는 지금 가게 하나만 실린다. "둘째가게 휴무 바꿔줘" 를 그대로 넘기면
첫째가게가 바뀌고, 사장님은 둘째가게가 바뀐 줄 안다."""
speaker = "다른가게-발화자"
h, _pid, _uid = await link(db_engine, client, auth_headers, speaker, "첫째가게")
await client.post("/v1/place", headers=h, json={"name": "둘째가게", "category": 1})
called = AsyncMock()
monkeypatch.setattr(runtime, "chat", called)
await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=body("첫째가게", speaker))
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=body("둘째가게 체크인 3시로 바꿔줘", speaker))
assert "지금은 '첫째가게'" in said(res)
assert "둘째가게" in quick(res)
called.assert_not_awaited()
async def test_고른_가게가_사라지면_목록으로_돌아간다(client, auth_headers, db_engine, monkeypatch):
"""★ 기억한 가게를 목록과 대조하지 않으면, 그 가게가 없어진 뒤로는 매번
"그 가게를 찾지 못했어요" 만 돌아온다 — 사장님은 '목록' 을 쳐야 풀린다는 걸 모른다."""
speaker = "사라진가게-발화자"
h, _pid, _uid = await link(db_engine, client, auth_headers, speaker, "첫째가게")
await client.post("/v1/place", headers=h, json={"name": "둘째가게", "category": 1})
async with db_engine.begin() as c:
await c.execute(
text("UPDATE owner_kakao_links SET current_place_id=:g WHERE channel_user_key=:k"),
{"g": uuid.uuid4(), "k": speaker},
)
called = AsyncMock()
monkeypatch.setattr(runtime, "chat", called)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=body("정보 보여줘", speaker))
assert "어느 가게" in said(res)
called.assert_not_awaited()
async def test_확인을_눌렀는데_가게가_없으면_그렇다고_말한다(client, auth_headers, db_engine, monkeypatch):
"""확인 경로도 런타임 오류를 사장님 말로 옮긴다 — "처리할 수 없어요" 로는 원인을 모른다."""
speaker = "확인-가게없음-키"
await link(db_engine, client, auth_headers, speaker)
async with db_engine.begin() as c:
await c.execute(
text("""UPDATE owner_kakao_links
SET pending_tool='publish', pending_args='{}'::jsonb,
pending_expires_at = now() + interval '1 minute', current_place_id=:g
WHERE channel_user_key=:k"""),
{"g": uuid.uuid4(), "k": speaker},
)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=body("네", speaker))
assert said(res) == channel._ERRORS["PLACE_NOT_FOUND"]
# ── 승인 알림(Event API 로 시작된 스킬 요청) ─────────────────────────────
# ★ 이 자리가 지키는 것: 글 본문은 **연결된 본인의 글일 때만** 나간다. 이벤트 요청의
# params 는 카카오가 채우지만, 발화자 키로 사장님을 찾고 그 글이 그 사장님 가게 것인지
# 서버가 다시 본다 — 글 ID 만 알면 남의 글이 보이는 구멍이 되면 안 된다.
POST_BODY = "비가 그친 뒤 마당 돌이 촉촉합니다. 대청마루에 앉아 빗소리를 들어 보세요."
def event_body(post_id, edit_token="EDITCODE1234", speaker="kakao-speaker-1"):
payload = body("", speaker)
payload["userRequest"]["params"] = {"post_id": str(post_id)}
if edit_token:
payload["userRequest"]["params"]["edit_token"] = edit_token
return payload
async def seed_post(db_engine, place_id, status=3, expires=None):
"""status 3 = SENT. expires 는 tz 를 단 UTC 로 넣는다(raw text() 로 timestamptz 를 바인딩할 때의 함정)."""
post_id = uuid.uuid4()
async with db_engine.begin() as c:
await c.execute(
text("INSERT INTO place_posts (post_id, place_id, body, topic_kind, topic_key, status, token_expires_at) "
"VALUES (:id, :pid, :body, 1, :key, :st, :exp)"),
{"id": post_id, "pid": uuid.UUID(str(place_id)), "body": POST_BODY,
"key": f"weather:{post_id.hex[:6]}", "st": status, "exp": expires},
)
return post_id
def outputs(res):
return res.json()["template"]["outputs"]
async def test_승인_알림은_본인_글이면_본문과_수정_링크를_그린다(client, auth_headers, db_engine):
h, pid, uid = await link(db_engine, client, auth_headers, "승인-발화자", "알림숙소")
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="승인-발화자"))
assert res.status_code == 200
first = outputs(res)[0]["simpleText"]["text"]
assert "알림숙소" in first and POST_BODY in first
button = outputs(res)[1]["textCard"]["buttons"][0]
assert button["label"] == "수정하기" and button["action"] == "webLink"
assert button["webLinkUrl"].endswith("/v1/site/post/edit?t=EDITCODE1234")
async def test_승인_알림은_수정_코드가_없으면_버튼_없이_본문만_준다(client, auth_headers, db_engine):
h, pid, uid = await link(db_engine, client, auth_headers, "코드없는-발화자")
post_id = await seed_post(db_engine, pid)
res = await client.post(
PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, edit_token=None, speaker="코드없는-발화자")
)
assert POST_BODY in outputs(res)[0]["simpleText"]["text"]
assert len(outputs(res)) == 1
async def test_남의_글은_본문을_주지_않는다(client, auth_headers, db_engine):
"""★ 글 ID 를 알아도 그 글의 주인에게 연결된 발화자가 아니면 아무것도 안 나온다."""
_h1, pid1, _uid1 = await link(db_engine, client, auth_headers, "주인-발화자", "주인숙소")
await link(db_engine, client, auth_headers, "남-발화자", "남의숙소")
post_id = await seed_post(db_engine, pid1)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="남-발화자"))
assert res.status_code == 200
assert POST_BODY not in res.text and "주인숙소" not in res.text
assert "EDITCODE1234" not in res.text
async def test_연결되지_않은_발화자에게는_본문을_주지_않는다(client, auth_headers, db_engine):
_h, pid, _uid = await link(db_engine, client, auth_headers, "연결된-발화자")
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="모르는-발화자"))
assert res.status_code == 200
assert POST_BODY not in res.text and "EDITCODE1234" not in res.text
async def test_이미_처리했거나_기한이_지난_글은_안내로_끝난다(client, auth_headers, db_engine):
from datetime import datetime, timedelta, timezone
h, pid, uid = await link(db_engine, client, auth_headers, "지난-발화자")
approved = await seed_post(db_engine, pid, status=4)
expired = await seed_post(db_engine, pid, expires=datetime.now(timezone.utc) - timedelta(hours=1))
for post_id in (approved, expired):
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="지난-발화자"))
assert res.status_code == 200
assert POST_BODY not in res.text
assert "기한" in said(res) or "처리" in said(res)
async def test_글_id_가_이상해도_터지지_않는다(client, auth_headers, db_engine):
await link(db_engine, client, auth_headers, "이상한-발화자")
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body("not-a-uuid", speaker="이상한-발화자"))
assert res.status_code == 200
assert said(res)
# ── [승인] 버튼 ──────────────────────────────────────────────────────────
# ★ 승인 권한은 링크가 아니라 **연결된 계정**이다. 버튼이 들고 오는 post_id 는 믿지 않고,
# 누른 발화자 → 사장님 → 그 글이 그 사장님 가게의 미처리·기한 전 글인지를 서버가 다시 본다.
# 틀리면 아무것도 승인되지 않고, 어느 쪽이 틀렸는지는 구분해 답하지 않는다.
APPROVE_BLOCK = "6abb6a319e1c4d176fa81ff4"
BUILD = 4 # JobType.BUILD
def click_body(post_id, speaker, kind="approve"):
"""[승인] 버튼(action: block)을 누르면 다음 스킬 요청의 action.clientExtra 로 extra 가 돌아온다."""
payload = body("승인", speaker)
payload["action"] = {"clientExtra": {"kind": kind, "post_id": str(post_id)}}
return payload
async def status_of(db_engine, post_id):
async with db_engine.begin() as c:
return (await c.execute(text("SELECT status FROM place_posts WHERE post_id=:p"), {"p": post_id})).scalar_one()
async def build_jobs(db_engine, place_id):
async with db_engine.begin() as c:
return (
await c.execute(
text("SELECT count(*) FROM jobs WHERE job_type=:t AND payload->>'place_id'=:p"),
{"t": BUILD, "p": str(place_id)},
)
).scalar_one()
async def publish_site(db_engine, place_id, domain="approve-click-test"):
async with db_engine.begin() as c:
await c.execute(
text("INSERT INTO sites (site_id, place_id, domain, status) VALUES (:sid, :pid, :dom, 3)"),
{"sid": uuid.uuid4(), "pid": uuid.UUID(str(place_id)), "dom": domain},
)
def card_buttons(res):
return outputs(res)[1]["textCard"]["buttons"]
async def test_승인_알림에_블록_id_가_있으면_승인_버튼을_그린다(client, auth_headers, db_engine, monkeypatch):
monkeypatch.setenv("KAKAO_APPROVE_BLOCK_ID", APPROVE_BLOCK)
h, pid, uid = await link(db_engine, client, auth_headers, "버튼-발화자", "버튼숙소")
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="버튼-발화자"))
buttons = card_buttons(res)
approve = next(b for b in buttons if b["label"] == "승인")
assert approve["action"] == "block" and approve["blockId"] == APPROVE_BLOCK
assert approve["extra"] == {"kind": "approve", "post_id": str(post_id)}
assert any(b["label"] == "수정하기" and b["action"] == "webLink" for b in buttons)
async def test_블록_id_가_없으면_죽은_승인_버튼을_그리지_않는다(client, auth_headers, db_engine, monkeypatch):
"""콘솔 준비 전에 켜도 눌러도 안 되는 버튼이 사장님 카톡에 나가지 않는다."""
monkeypatch.setenv("KAKAO_APPROVE_BLOCK_ID", "")
h, pid, uid = await link(db_engine, client, auth_headers, "버튼없는-발화자")
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="버튼없는-발화자"))
assert [b["label"] for b in card_buttons(res)] == ["수정하기"]
async def test_승인_버튼을_누르면_올라가고_사이트_보기를_준다(client, auth_headers, db_engine):
h, pid, uid = await link(db_engine, client, auth_headers, "승인-클릭자", "클릭숙소")
await publish_site(db_engine, pid)
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "승인-클릭자"))
assert res.status_code == 200
assert "올렸습니다" in said(res)
assert await status_of(db_engine, post_id) == 4 # APPROVED
assert await build_jobs(db_engine, pid) == 1
button = card_buttons(res)[0]
assert button["label"] == "사이트 보기" and button["action"] == "webLink"
assert button["webLinkUrl"].endswith("/s/approve-click-test#blog")
async def test_발행된_사이트가_없어도_승인은_되고_링크만_빠진다(client, auth_headers, db_engine):
h, pid, uid = await link(db_engine, client, auth_headers, "사이트없는-클릭자")
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "사이트없는-클릭자"))
assert "올렸습니다" in said(res)
assert await status_of(db_engine, post_id) == 4
assert len(outputs(res)) == 1
async def test_남의_글의_승인_버튼은_아무것도_승인하지_않는다(client, auth_headers, db_engine):
"""★ post_id 를 알아도 그 글 주인에게 연결된 발화자가 아니면 승인되지 않는다."""
_h1, pid1, _uid1 = await link(db_engine, client, auth_headers, "글주인-발화자", "글주인숙소")
await link(db_engine, client, auth_headers, "다른사람-발화자", "다른숙소")
post_id = await seed_post(db_engine, pid1)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "다른사람-발화자"))
assert res.status_code == 200
assert "올렸습니다" not in said(res)
assert await status_of(db_engine, post_id) == 3 # 그대로 SENT
assert await build_jobs(db_engine, pid1) == 0
async def test_연결되지_않은_발화자의_승인_버튼은_먹지_않는다(client, auth_headers, db_engine):
_h, pid, _uid = await link(db_engine, client, auth_headers, "연결된-사장님")
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "모르는-클릭자"))
assert "올렸습니다" not in said(res)
assert await status_of(db_engine, post_id) == 3
assert await build_jobs(db_engine, pid) == 0
async def test_이미_승인한_글을_또_눌러도_두_번_올라가지_않는다(client, auth_headers, db_engine):
h, pid, uid = await link(db_engine, client, auth_headers, "두번-클릭자")
post_id = await seed_post(db_engine, pid)
first = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "두번-클릭자"))
second = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "두번-클릭자"))
assert "올렸습니다" in said(first)
assert "올렸습니다" not in said(second)
assert await build_jobs(db_engine, pid) == 1
async def test_기한이_지난_글의_승인_버튼은_먹지_않는다(client, auth_headers, db_engine):
from datetime import datetime, timedelta, timezone
h, pid, uid = await link(db_engine, client, auth_headers, "만료-클릭자")
post_id = await seed_post(db_engine, pid, expires=datetime.now(timezone.utc) - timedelta(hours=1))
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "만료-클릭자"))
assert "올렸습니다" not in said(res)
assert await status_of(db_engine, post_id) == 3
async def test_승인_클릭은_모델을_부르지_않는다(client, auth_headers, db_engine, monkeypatch):
"""버튼 처리는 결정적이어야 한다 — 유료 호출도 없고, 모델이 다른 도구를 고를 여지도 없다."""
h, pid, uid = await link(db_engine, client, auth_headers, "모델없는-클릭자")
post_id = await seed_post(db_engine, pid)
called = AsyncMock()
monkeypatch.setattr(runtime, "chat", called)
await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "모델없는-클릭자"))
called.assert_not_awaited()
async def test_모르는_종류나_이상한_글_id_의_클릭은_터지지_않는다(client, auth_headers, db_engine):
await link(db_engine, client, auth_headers, "이상한-클릭자")
bad_id = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body("not-a-uuid", "이상한-클릭자"))
unknown = await client.post(
PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(uuid.uuid4(), "이상한-클릭자", kind="delete")
)
assert bad_id.status_code == 200 and said(bad_id)
assert "올렸습니다" not in said(bad_id)
assert unknown.status_code == 200