Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1808ba1813 | |||
| 3cf5364955 | |||
| 6133eb6926 | |||
| e717de69ca | |||
| 05296b3166 |
@@ -11,8 +11,8 @@ RUN apt-get update && \
|
||||
ffmpeg && \
|
||||
apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt requirements.lock ./
|
||||
RUN pip install --no-cache-dir -r requirements.lock
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
"""study_concepts API — 이론공부 홈(오늘의 개념 · 진도 · 회독 SR). prefix = /api/study.
|
||||
|
||||
문제풀이 표면 무접촉. 개념문서(가스기사 태그) 읽기 집계 + 회독 SR write 만. 단일 토픽(가스기사=4).
|
||||
경로: GET /curriculum · GET /today-concepts · POST /concepts/{doc_id}/read.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from core.auth import get_current_user
|
||||
from core.database import get_session
|
||||
from models.user import User
|
||||
from services.study import concept_curriculum as cc
|
||||
from services.study import concept_links as cl
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# 가스기사 단일 토픽 운영(현행). 다토픽 확장 시 쿼리 파라미터로 승격.
|
||||
DEFAULT_TOPIC_ID = 4
|
||||
|
||||
|
||||
@router.get("/curriculum")
|
||||
async def get_curriculum(
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
session: Annotated[AsyncSession, Depends(get_session)],
|
||||
topic_id: int = DEFAULT_TOPIC_ID,
|
||||
):
|
||||
"""과목별 회독 진도 + 개념/문항 복습 due 요약."""
|
||||
return await cc.curriculum(session, user.id, topic_id)
|
||||
|
||||
|
||||
@router.get("/today-concepts")
|
||||
async def get_today_concepts(
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
session: Annotated[AsyncSession, Depends(get_session)],
|
||||
topic_id: int = DEFAULT_TOPIC_ID,
|
||||
limit: int = 6,
|
||||
):
|
||||
"""오늘 공부할 개념(재복습 → 미독 빈출순)."""
|
||||
return await cc.today_concepts(session, user.id, topic_id, limit)
|
||||
|
||||
|
||||
@router.get("/concepts/weakness-map")
|
||||
async def get_weakness_map(
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
session: Annotated[AsyncSession, Depends(get_session)],
|
||||
topic_id: int = DEFAULT_TOPIC_ID,
|
||||
limit: int = 12,
|
||||
):
|
||||
"""개념 약점 지도 — 링크된 기출 정답률로 약점 개념(정답률<60%) 우선(이론↔문제)."""
|
||||
name = await cc._topic_name(session, topic_id)
|
||||
if not name:
|
||||
return {"weak": [], "weak_total": 0, "evaluated_total": 0}
|
||||
return await cl.weakness_map(session, user.id, name, limit)
|
||||
|
||||
|
||||
@router.get("/concepts/{doc_id}")
|
||||
async def get_concept_detail(
|
||||
doc_id: int,
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
session: Annotated[AsyncSession, Depends(get_session)],
|
||||
topic_id: int = DEFAULT_TOPIC_ID,
|
||||
):
|
||||
"""개념 리더 재료 — 구조 파싱(요약/본문/빈출/관련) + 백링크 해소 + 회독/SR + 이전/다음."""
|
||||
detail = await cc.concept_detail(session, user.id, topic_id, doc_id)
|
||||
if detail is None:
|
||||
raise HTTPException(status_code=404, detail="concept not found")
|
||||
return detail
|
||||
|
||||
|
||||
@router.get("/concepts/{doc_id}/questions")
|
||||
async def get_concept_questions(
|
||||
doc_id: int,
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
session: Annotated[AsyncSession, Depends(get_session)],
|
||||
limit: int = 20,
|
||||
):
|
||||
"""개념 관련 기출 + 내 정답률 (이론↔문제 브리지)."""
|
||||
return await cl.related_questions(session, user.id, doc_id, limit)
|
||||
|
||||
|
||||
@router.post("/concepts/{doc_id}/read")
|
||||
async def post_concept_read(
|
||||
doc_id: int,
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
session: Annotated[AsyncSession, Depends(get_session)],
|
||||
topic_id: int = DEFAULT_TOPIC_ID,
|
||||
):
|
||||
"""개념 회독 처리 → 회독 플래그 + SR 입고/전진."""
|
||||
return await cc.mark_read(session, user.id, topic_id, doc_id)
|
||||
@@ -33,7 +33,6 @@ from api.study_sessions import router as study_sessions_router
|
||||
from api.study_topics import router as study_topics_router
|
||||
from api.study_reminders import router as study_reminders_router
|
||||
from api.study_cards import router as study_cards_router
|
||||
from api.study_concepts import router as study_concepts_router
|
||||
from api.video import router as video_router
|
||||
from core.config import settings
|
||||
from core.database import async_session, engine, init_db
|
||||
@@ -250,8 +249,6 @@ app.include_router(study_reminders_router, prefix="/api/study-reminders", tags=[
|
||||
app.include_router(study_cards_router, prefix="/api/study-cards", tags=["study-cards"])
|
||||
# Phase 1: 학습 진행 상태 (review-complete + review-queue). prefix=/api/study-topics 안에 정의됨.
|
||||
app.include_router(study_question_progress_router, prefix="/api", tags=["study-progress"])
|
||||
# 이론공부 홈: 오늘의 개념·진도·회독 SR (개념문서 소비 표면, 문제풀이 무접촉).
|
||||
app.include_router(study_concepts_router, prefix="/api/study", tags=["study-theory"])
|
||||
|
||||
# TODO: Phase 5에서 추가
|
||||
# app.include_router(tasks.router, prefix="/api/tasks", tags=["tasks"])
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
"""study_concept_progress — 사용자 × 개념문서 단위 간격반복(SR) 진행 (이론공부 홈).
|
||||
|
||||
문제 SR(study_question_progress)의 개념(이론)판. '개념문서' = documents 한 건(가스기사 태그).
|
||||
회독(첫 read) → 복습 큐 진입, 이후 회독마다 sr_schedule 산술(1·3·7·14·졸업) 공용 전진.
|
||||
concept_doc_id 는 documents.id 를 가리키나 FK 미설정 — hot 테이블(documents) 락 회피(clause_study 선례).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, ForeignKey, SmallInteger, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from core.database import Base
|
||||
|
||||
|
||||
class StudyConceptProgress(Base):
|
||||
__tablename__ = "study_concept_progress"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"user_id", "concept_doc_id", name="uq_concept_progress_user_doc"
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
BigInteger, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
study_topic_id: Mapped[int] = mapped_column(
|
||||
BigInteger, ForeignKey("study_topics.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
# documents.id 참조 — FK 없음(락 회피). 개념문서 삭제 시 고아 행은 read 집계에서 자연 제외.
|
||||
concept_doc_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
|
||||
# 복습 큐 (sr_schedule 공용): stage 0~3 = 1·3·7·14일, 4 = 졸업(due_at NULL)
|
||||
review_stage: Mapped[int | None] = mapped_column(SmallInteger)
|
||||
due_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
last_read_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=datetime.now, nullable=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=datetime.now, onupdate=datetime.now, nullable=False
|
||||
)
|
||||
@@ -36,8 +36,6 @@ KNOWN_4B_TASKS = {
|
||||
}
|
||||
KNOWN_26B_TASKS = {
|
||||
"p3c_deep_summary",
|
||||
# presegment PR2 — 거대문서 map-reduce 의 reduce 단계 (요약들의 요약)
|
||||
"p3c_deep_summary_reduce",
|
||||
"p4b_synthesis",
|
||||
}
|
||||
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
[System]
|
||||
너는 긴 문서·문서 묶음 분석가다. 이 문서는 한 번에 처리하기에 너무 커서, 원문을 순서대로 유닛으로 나눠 각 유닛을 먼저 요약했다(map 단계). 아래 "유닛 요약"들은 원문 순서 그대로이며 문서 전체를 빠짐없이 커버한다. 너는 이를 종합해 문서 전체의 최종 분석을 작성한다(reduce 단계).
|
||||
|
||||
subject_description: {subject_description}
|
||||
|
||||
{forbidden_block}
|
||||
|
||||
envelope 를 읽는 순서:
|
||||
1. risk_flags 를 먼저 본다. 어떤 위험 때문에 올라온 것인지 파악.
|
||||
2. synthesis_directives 를 system 지시로 간주하여 반드시 준수.
|
||||
3. distilled_context 는 "참고 요지"일 뿐, 근거는 유닛 요약에서 재확인.
|
||||
|
||||
작성 규칙:
|
||||
- TL;DR (1문장, 최대 60자)
|
||||
- 핵심 (bullets 5개, 각 30~80자)
|
||||
- 상세 (2~4 문단, 각 3~5문장) — 유닛(섹션) 순서의 논리 흐름을 보전하며 문서 전체를 관통하는 서술. 특정 유닛만 편식하지 말 것.
|
||||
- 유닛 요약에 없는 정보 금지 (hallucination 금지). 숫자·조문·인용은 유닛 요약에 있는 것만 사용.
|
||||
- 유닛 요약의 "불일치(...)" 줄들은 중복 제거해 inconsistencies 로 보전 — 임의로 버리지 않는다.
|
||||
- synthesis_directives 의 문구 규칙 ("원인은 ~" 금지 등) 반드시 준수.
|
||||
- multi_reference_synthesis flag 있으면 레퍼런스별 입장 분리 기술, 종합 권고 금지.
|
||||
|
||||
출력 (JSON only):
|
||||
{{
|
||||
"mode": "single|bundle",
|
||||
"tldr": "...",
|
||||
"bullets": ["..."],
|
||||
"detail": "...\\n\\n...",
|
||||
"bundle_flow": ["..."] | null,
|
||||
"inconsistencies": ["..."] | null,
|
||||
"entities_confirmed": {{
|
||||
"people": [{{"name": "...", "evidence": "..."}}],
|
||||
"orgs": [...],
|
||||
"projects": [...]
|
||||
}},
|
||||
"directives_applied": ["..."],
|
||||
"confidence": 0.0~1.0
|
||||
}}
|
||||
|
||||
[User]
|
||||
Envelope:
|
||||
{{escalation_envelope_json}}
|
||||
|
||||
유닛 요약 (총 {{unit_count}}개, 원문 순서 — 각 블록 = 원문 한 구간의 요약):
|
||||
{{unit_summaries}}
|
||||
@@ -1,104 +0,0 @@
|
||||
# requirements.lock — 라이브 fastapi 컨테이너 pip freeze 스냅샷 (2026-07-02, 101 pkgs, CVE-clear known-good)
|
||||
# 재생성: docker exec hyungi_document_server-fastapi-1 pip freeze > app/requirements.lock (헤더 재부착)
|
||||
# requirements.txt = 사람이 편집하는 floor 사양(>=) / 본 lock = Dockerfile 이 실제 설치하는 정본(==)
|
||||
annotated-doc==0.0.4
|
||||
annotated-types==0.7.0
|
||||
anthropic==0.109.1
|
||||
anyio==4.13.0
|
||||
APScheduler==3.11.2
|
||||
asyncpg==0.31.0
|
||||
babel==2.18.0
|
||||
bcrypt==5.0.0
|
||||
beautifulsoup4==4.15.0
|
||||
caldav==3.2.1
|
||||
certifi==2026.5.20
|
||||
cffi==2.0.0
|
||||
chardet==7.4.3
|
||||
charset-normalizer==3.4.7
|
||||
click==8.4.1
|
||||
cobble==0.1.4
|
||||
courlan==1.4.0
|
||||
cryptography==48.0.1
|
||||
cssselect==1.4.0
|
||||
dateparser==1.4.0
|
||||
defusedxml==0.7.1
|
||||
distro==1.9.0
|
||||
dnspython==2.8.0
|
||||
docstring_parser==0.18.0
|
||||
ecdsa==0.19.2
|
||||
et_xmlfile==2.0.0
|
||||
fastapi==0.136.3
|
||||
feedparser==6.0.12
|
||||
flatbuffers==25.12.19
|
||||
greenlet==3.5.1
|
||||
h11==0.16.0
|
||||
htmldate==1.10.0
|
||||
httpcore==1.0.9
|
||||
httptools==0.8.0
|
||||
httpx==0.28.1
|
||||
icalendar==7.1.2
|
||||
icalendar-searcher==1.0.6
|
||||
idna==3.18
|
||||
jh2==5.0.13
|
||||
Jinja2==3.1.6
|
||||
jiter==0.15.0
|
||||
jusText==3.0.2
|
||||
lxml==6.1.1
|
||||
lxml_html_clean==0.4.5
|
||||
magika==0.6.3
|
||||
mammoth==1.11.0
|
||||
Markdown==3.10.2
|
||||
markdownify==1.2.2
|
||||
markitdown==0.1.6
|
||||
MarkupSafe==3.0.3
|
||||
niquests==3.19.1
|
||||
numpy==2.4.6
|
||||
olefile==0.47
|
||||
onnxruntime==1.26.0
|
||||
openpyxl==3.1.5
|
||||
packaging==26.2
|
||||
pandas==3.0.3
|
||||
pgvector==0.4.2
|
||||
pillow==12.2.0
|
||||
protobuf==7.35.0
|
||||
pyasn1==0.6.3
|
||||
pycparser==3.0
|
||||
pydantic==2.13.4
|
||||
pydantic_core==2.46.4
|
||||
pyhwp==0.1b15
|
||||
PyMuPDF==1.27.2.3
|
||||
pyotp==2.9.0
|
||||
python-dateutil==2.9.0.post0
|
||||
python-dotenv==1.2.2
|
||||
python-jose==3.5.0
|
||||
python-multipart==0.0.32
|
||||
python-pptx==1.0.2
|
||||
pytz==2026.2
|
||||
PyYAML==6.0.3
|
||||
qh3==1.9.2
|
||||
readability-lxml==0.8.4.1
|
||||
recurring-ical-events==3.8.2
|
||||
regex==2026.5.9
|
||||
requests==2.34.2
|
||||
rsa==4.9.1
|
||||
sgmllib3k==1.0.0
|
||||
six==1.17.0
|
||||
sniffio==1.3.1
|
||||
soupsieve==2.8.4
|
||||
SQLAlchemy==2.0.50
|
||||
starlette==1.2.1
|
||||
tld==0.13.2
|
||||
trafilatura==2.1.0
|
||||
typing-inspection==0.4.2
|
||||
typing_extensions==4.15.0
|
||||
tzdata==2026.2
|
||||
tzlocal==5.3.1
|
||||
urllib3==2.7.0
|
||||
urllib3-future==2.21.902
|
||||
uvicorn==0.49.0
|
||||
uvloop==0.22.1
|
||||
wassima==2.1.1
|
||||
watchfiles==1.2.0
|
||||
websockets==16.0
|
||||
x-wr-timezone==2.0.1
|
||||
xlsxwriter==3.2.9
|
||||
@@ -1,284 +0,0 @@
|
||||
"""concept_curriculum — 이론공부 홈 재료 (오늘의 개념 · 진도 · 회독 SR).
|
||||
|
||||
개념문서 = documents (user_tags = @library/{topic}/{과목}/... , 가스기사). is_read = 회독,
|
||||
md_content 의 ★ 개수 = 빈출 tier(★★★=3 / ★★=2 / else 1). 회독 SR = study_concept_progress
|
||||
+ sr_schedule(문제 SR 공용 산술). 읽기 전용 집계 + mark_read(회독+SR 입고)만 write. LLM 0.
|
||||
|
||||
문제풀이 표면 무접촉 — 여기서 읽는 study_question_progress 는 '문항 due 카운트'만(홈 표시용).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import func, or_, select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from models.document_read import DocumentRead
|
||||
from models.study_concept_progress import StudyConceptProgress
|
||||
from models.study_question_progress import StudyQuestionProgress
|
||||
from models.study_topic import StudyTopic
|
||||
from services.study.concept_parser import parse_concept, resolve_related
|
||||
from services.study.sr_schedule import advance, first_due
|
||||
|
||||
# 개념 행 조회 — 태그로 개념문서 필터 + 회독 진행 LEFT JOIN. md_content 는 전송 안 하고
|
||||
# ★ 유무만 서버측 boolean 으로(홈이 자주 호출돼도 페이로드 최소).
|
||||
# is_read = document_reads(회독 정본, is_read 컬럼 아님) EXISTS. library unread 와 동일 기준.
|
||||
_CONCEPT_ROWS_SQL = text(
|
||||
"""
|
||||
SELECT d.id AS doc_id,
|
||||
d.title AS title,
|
||||
EXISTS (
|
||||
SELECT 1 FROM document_reads r
|
||||
WHERE r.document_id = d.id AND r.user_id = :uid
|
||||
) AS is_read,
|
||||
(d.md_content LIKE '%★★★%') AS f3,
|
||||
(d.md_content LIKE '%★★%') AS f2,
|
||||
split_part(replace(d.user_tags::text, '"', ''), '/', 3) AS subject,
|
||||
p.review_stage AS review_stage,
|
||||
p.due_at AS due_at,
|
||||
p.last_read_at AS last_read_at
|
||||
FROM documents d
|
||||
LEFT JOIN study_concept_progress p
|
||||
ON p.concept_doc_id = d.id AND p.user_id = :uid
|
||||
WHERE d.user_tags::text LIKE :like
|
||||
AND d.deleted_at IS NULL
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def _topic_name(session: AsyncSession, topic_id: int) -> str | None:
|
||||
return (
|
||||
await session.execute(select(StudyTopic.name).where(StudyTopic.id == topic_id))
|
||||
).scalar_one_or_none()
|
||||
|
||||
|
||||
async def _concept_rows(session: AsyncSession, user_id: int, topic_name: str):
|
||||
like = f"%@library/{topic_name}/%"
|
||||
return (
|
||||
await session.execute(_CONCEPT_ROWS_SQL, {"uid": user_id, "like": like})
|
||||
).mappings().all()
|
||||
|
||||
|
||||
def _freq(row) -> int:
|
||||
if row["f3"]:
|
||||
return 3
|
||||
if row["f2"]:
|
||||
return 2
|
||||
return 1
|
||||
|
||||
|
||||
def _is_due(row, now: datetime) -> bool:
|
||||
return (
|
||||
row["due_at"] is not None
|
||||
and row["due_at"] <= now
|
||||
and (row["review_stage"] or 0) < 4
|
||||
)
|
||||
|
||||
|
||||
def _item(row) -> dict:
|
||||
return {
|
||||
"doc_id": row["doc_id"],
|
||||
"title": row["title"],
|
||||
"subject": row["subject"],
|
||||
"freq": _freq(row),
|
||||
"review_stage": row["review_stage"],
|
||||
"due_at": row["due_at"],
|
||||
}
|
||||
|
||||
|
||||
async def _question_due_count(session: AsyncSession, user_id: int, topic_id: int, now: datetime) -> int:
|
||||
"""문항 복습 due (기존 study_question_progress 엔진 재사용, 홈 표시용)."""
|
||||
return (
|
||||
await session.execute(
|
||||
select(func.count())
|
||||
.select_from(StudyQuestionProgress)
|
||||
.where(
|
||||
StudyQuestionProgress.user_id == user_id,
|
||||
StudyQuestionProgress.study_topic_id == topic_id,
|
||||
StudyQuestionProgress.due_at.is_not(None),
|
||||
StudyQuestionProgress.due_at <= now,
|
||||
or_(
|
||||
StudyQuestionProgress.review_stage.is_(None),
|
||||
StudyQuestionProgress.review_stage < 4,
|
||||
),
|
||||
)
|
||||
)
|
||||
).scalar_one()
|
||||
|
||||
|
||||
async def curriculum(session: AsyncSession, user_id: int, topic_id: int) -> dict:
|
||||
"""과목별 회독 진도 + 개념/문항 복습 due 요약 (진도 대시보드)."""
|
||||
name = await _topic_name(session, topic_id)
|
||||
rows = await _concept_rows(session, user_id, name) if name else []
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
subj: dict[str, dict] = {}
|
||||
for r in rows:
|
||||
s = subj.setdefault(r["subject"], {"subject": r["subject"], "total": 0, "read": 0})
|
||||
s["total"] += 1
|
||||
if r["is_read"]:
|
||||
s["read"] += 1
|
||||
|
||||
total = len(rows)
|
||||
read = sum(1 for r in rows if r["is_read"])
|
||||
concept_due = sum(1 for r in rows if _is_due(r, now))
|
||||
question_due = await _question_due_count(session, user_id, topic_id, now)
|
||||
|
||||
return {
|
||||
"topic_id": topic_id,
|
||||
"topic_name": name,
|
||||
"subjects": sorted(subj.values(), key=lambda x: x["subject"]),
|
||||
"total": total,
|
||||
"read": read,
|
||||
"concept_due": concept_due,
|
||||
"question_due": question_due,
|
||||
}
|
||||
|
||||
|
||||
async def today_concepts(
|
||||
session: AsyncSession, user_id: int, topic_id: int, limit: int = 6
|
||||
) -> dict:
|
||||
"""오늘 공부할 개념 = 재복습(SR due) 먼저 → 미독(빈출 우선). 졸업/재복습대기 제외."""
|
||||
name = await _topic_name(session, topic_id)
|
||||
rows = await _concept_rows(session, user_id, name) if name else []
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
due = [r for r in rows if _is_due(r, now)]
|
||||
due.sort(key=lambda r: r["due_at"])
|
||||
|
||||
# 미독 & 아직 SR 큐 진입 전(due_at NULL) → 빈출 높은 순
|
||||
unread = [r for r in rows if not r["is_read"] and r["due_at"] is None]
|
||||
unread.sort(key=lambda r: (-_freq(r), r["subject"], r["title"]))
|
||||
|
||||
picked = [{**_item(r), "reason": "재복습"} for r in due]
|
||||
picked += [{**_item(r), "reason": "신규"} for r in unread]
|
||||
|
||||
return {
|
||||
"concepts": picked[:limit],
|
||||
"due_total": len(due),
|
||||
"unread_total": len(unread),
|
||||
}
|
||||
|
||||
|
||||
async def mark_read(
|
||||
session: AsyncSession, user_id: int, topic_id: int, doc_id: int, now: datetime | None = None
|
||||
) -> dict:
|
||||
"""개념 회독 처리 = document_reads(+1) + 회독 SR 입고/전진.
|
||||
|
||||
회독 정본 = document_reads(append-only), documents.is_read 컬럼 아님(library unread 와 정합).
|
||||
첫 회독 → first_due(stage 0, 내일). 이후 회독은 'due 도래(due_at<=now)' 때만 correct 로 전진
|
||||
(이른 재열람/다중클릭 과전진 방지). stage 4 졸업 후엔 due_at NULL 이라 전진 없음.
|
||||
"""
|
||||
now = now or datetime.now(timezone.utc)
|
||||
|
||||
# 회독 로그 append (+1) — 사용자 명시 회독. 자동 아님(엔드포인트 = 명시 POST).
|
||||
session.add(DocumentRead(user_id=user_id, document_id=doc_id, read_at=now))
|
||||
|
||||
prog = (
|
||||
await session.execute(
|
||||
select(StudyConceptProgress).where(
|
||||
StudyConceptProgress.user_id == user_id,
|
||||
StudyConceptProgress.concept_doc_id == doc_id,
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
|
||||
if prog is None:
|
||||
stage, due = first_due(now)
|
||||
prog = StudyConceptProgress(
|
||||
user_id=user_id,
|
||||
study_topic_id=topic_id,
|
||||
concept_doc_id=doc_id,
|
||||
review_stage=stage,
|
||||
due_at=due,
|
||||
last_read_at=now,
|
||||
)
|
||||
session.add(prog)
|
||||
else:
|
||||
# due 도래 시에만 전진 — 미래 due(재열람 이른 클릭)는 stage 불변, last_read_at 만 갱신.
|
||||
if prog.due_at is not None and prog.due_at <= now:
|
||||
res = advance(prog.review_stage, "correct", now)
|
||||
if res is not None:
|
||||
prog.review_stage, prog.due_at = res
|
||||
prog.last_read_at = now
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(prog)
|
||||
return {"ok": True, "review_stage": prog.review_stage, "due_at": prog.due_at}
|
||||
|
||||
|
||||
_CONCEPT_ONE_SQL = text(
|
||||
"""
|
||||
SELECT d.id AS doc_id, d.title AS title, d.md_content AS md_content,
|
||||
split_part(replace(d.user_tags::text, '"', ''), '/', 3) AS subject,
|
||||
(d.md_content LIKE '%★★★%') AS f3,
|
||||
(d.md_content LIKE '%★★%') AS f2,
|
||||
EXISTS (
|
||||
SELECT 1 FROM document_reads r
|
||||
WHERE r.document_id = d.id AND r.user_id = :uid
|
||||
) AS is_read,
|
||||
p.review_stage AS review_stage,
|
||||
p.due_at AS due_at
|
||||
FROM documents d
|
||||
LEFT JOIN study_concept_progress p ON p.concept_doc_id = d.id AND p.user_id = :uid
|
||||
WHERE d.id = :doc_id AND d.deleted_at IS NULL AND d.user_tags::text LIKE :like
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def concept_detail(
|
||||
session: AsyncSession, user_id: int, topic_id: int, doc_id: int
|
||||
) -> dict | None:
|
||||
"""개념 리더 재료 — md 구조 파싱 + 관련개념 백링크 해소 + 회독/SR 상태 + 같은 과목 이전/다음."""
|
||||
name = await _topic_name(session, topic_id)
|
||||
if not name:
|
||||
return None
|
||||
like = f"%@library/{name}/%"
|
||||
row = (
|
||||
await session.execute(
|
||||
_CONCEPT_ONE_SQL, {"uid": user_id, "doc_id": doc_id, "like": like}
|
||||
)
|
||||
).mappings().first()
|
||||
if row is None:
|
||||
return None
|
||||
|
||||
parsed = parse_concept(row["md_content"] or "")
|
||||
|
||||
# 백링크 해소 + 이전/다음 = 같은 토픽 개념 title 인덱스(회독 rows 재사용)
|
||||
idx = await _concept_rows(session, user_id, name)
|
||||
title_index = [(r["doc_id"], r["title"], r["subject"]) for r in idx]
|
||||
resolved = resolve_related(parsed["related"], title_index)
|
||||
|
||||
# 이전/다음 = 같은 과목, title 순
|
||||
same = sorted(
|
||||
[(r["doc_id"], r["title"]) for r in idx if r["subject"] == row["subject"]],
|
||||
key=lambda x: (x[1] or "", x[0]),
|
||||
)
|
||||
ids = [d for d, _ in same]
|
||||
prev_id = next_id = None
|
||||
if doc_id in ids:
|
||||
pos = ids.index(doc_id)
|
||||
if pos > 0:
|
||||
prev_id = ids[pos - 1]
|
||||
if pos < len(ids) - 1:
|
||||
next_id = ids[pos + 1]
|
||||
|
||||
freq = 3 if row["f3"] else (2 if row["f2"] else 1)
|
||||
|
||||
return {
|
||||
"doc_id": row["doc_id"],
|
||||
"db_title": row["title"],
|
||||
"title": parsed["title"] or row["title"],
|
||||
"subject": row["subject"],
|
||||
"freq": freq,
|
||||
"summary": parsed["summary"],
|
||||
"body": parsed["body"],
|
||||
"bincheol": parsed["bincheol"],
|
||||
"related": resolved,
|
||||
"is_read": row["is_read"],
|
||||
"review_stage": row["review_stage"],
|
||||
"due_at": row["due_at"],
|
||||
"prev_id": prev_id,
|
||||
"next_id": next_id,
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
"""concept_links — 이론↔문제 브리지 롤업 (Stage B).
|
||||
|
||||
study_concept_links(개념 doc ↔ 기출문항, 임베딩 코사인) + study_question_progress(내 풀이상태)를
|
||||
조인해 (a) 개념별 관련 기출 + 내 정답률(related_questions), (b) 개념 약점 지도(weakness_map) 산출.
|
||||
읽기 전용 집계 · LLM 0. 링크 적재는 scripts/concept_links_backfill.sql(임베딩) 배치.
|
||||
정답률 = 링크된 문항 중 progress.last_outcome 기준(attempted=풀이이력 보유, correct=최근정답).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
_ACCURACY_WEAK_PCT = 60 # 정답률 < 60% = 약점(attempted>0 일 때만)
|
||||
|
||||
_AGG_SQL = text(
|
||||
"""
|
||||
SELECT count(*) AS linked,
|
||||
count(pr.study_question_id) FILTER (WHERE pr.last_outcome IS NOT NULL) AS attempted,
|
||||
count(*) FILTER (WHERE pr.last_outcome = 'correct') AS correct
|
||||
FROM study_concept_links l
|
||||
LEFT JOIN study_question_progress pr
|
||||
ON pr.study_question_id = l.question_id AND pr.user_id = :uid
|
||||
WHERE l.concept_doc_id = :doc_id AND l.link_source = 'embedding'
|
||||
"""
|
||||
)
|
||||
|
||||
_QROWS_SQL = text(
|
||||
"""
|
||||
SELECT q.id AS id, q.subject AS subject, q.exam_round AS exam_round,
|
||||
q.exam_question_number AS qnum, l.score AS score,
|
||||
pr.last_outcome AS last_outcome, pr.review_stage AS review_stage
|
||||
FROM study_concept_links l
|
||||
JOIN study_questions q ON q.id = l.question_id AND q.deleted_at IS NULL AND q.is_active
|
||||
LEFT JOIN study_question_progress pr
|
||||
ON pr.study_question_id = q.id AND pr.user_id = :uid
|
||||
WHERE l.concept_doc_id = :doc_id AND l.link_source = 'embedding'
|
||||
ORDER BY l.score DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
)
|
||||
|
||||
_WEAKNESS_SQL = text(
|
||||
"""
|
||||
SELECT d.id AS doc_id, d.title AS title,
|
||||
split_part(replace(d.user_tags::text, '"', ''), '/', 3) AS subject,
|
||||
count(l.id) AS linked,
|
||||
count(pr.study_question_id) FILTER (WHERE pr.last_outcome IS NOT NULL) AS attempted,
|
||||
count(*) FILTER (WHERE pr.last_outcome = 'correct') AS correct
|
||||
FROM documents d
|
||||
JOIN study_concept_links l ON l.concept_doc_id = d.id AND l.link_source = 'embedding'
|
||||
LEFT JOIN study_question_progress pr
|
||||
ON pr.study_question_id = l.question_id AND pr.user_id = :uid
|
||||
WHERE d.user_tags::text LIKE :like AND d.deleted_at IS NULL
|
||||
GROUP BY d.id, d.title, subject
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def related_questions(
|
||||
session: AsyncSession, user_id: int, doc_id: int, limit: int = 20
|
||||
) -> dict:
|
||||
"""개념 doc 의 관련 기출 + 내 정답률(전체 링크 기준 집계 + 상위 N 표시용)."""
|
||||
agg = (
|
||||
await session.execute(_AGG_SQL, {"uid": user_id, "doc_id": doc_id})
|
||||
).mappings().first()
|
||||
rows = (
|
||||
await session.execute(
|
||||
_QROWS_SQL, {"uid": user_id, "doc_id": doc_id, "limit": limit}
|
||||
)
|
||||
).mappings().all()
|
||||
|
||||
linked = (agg["linked"] if agg else 0) or 0
|
||||
attempted = (agg["attempted"] if agg else 0) or 0
|
||||
correct = (agg["correct"] if agg else 0) or 0
|
||||
accuracy = round(100 * correct / attempted) if attempted else None
|
||||
|
||||
return {
|
||||
"linked": linked,
|
||||
"attempted": attempted,
|
||||
"correct": correct,
|
||||
"accuracy": accuracy,
|
||||
"questions": [
|
||||
{
|
||||
"id": r["id"],
|
||||
"subject": r["subject"],
|
||||
"exam_round": r["exam_round"],
|
||||
"qnum": r["qnum"],
|
||||
"score": round(r["score"], 3) if r["score"] is not None else None,
|
||||
"last_outcome": r["last_outcome"],
|
||||
"review_stage": r["review_stage"],
|
||||
}
|
||||
for r in rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
async def weakness_map(
|
||||
session: AsyncSession, user_id: int, topic_name: str, limit: int = 12
|
||||
) -> dict:
|
||||
"""개념 약점 지도 — 링크된 기출 정답률로 개념 채색. 약점(attempted>0·정답률<60%) 우선 정렬."""
|
||||
like = f"%@library/{topic_name}/%"
|
||||
rows = (
|
||||
await session.execute(_WEAKNESS_SQL, {"uid": user_id, "like": like})
|
||||
).mappings().all()
|
||||
|
||||
concepts = []
|
||||
for r in rows:
|
||||
attempted = r["attempted"] or 0
|
||||
correct = r["correct"] or 0
|
||||
accuracy = round(100 * correct / attempted) if attempted else None
|
||||
if accuracy is None:
|
||||
state = "unattempted"
|
||||
elif accuracy < _ACCURACY_WEAK_PCT:
|
||||
state = "weak"
|
||||
else:
|
||||
state = "ok"
|
||||
concepts.append(
|
||||
{
|
||||
"doc_id": r["doc_id"],
|
||||
"title": r["title"],
|
||||
"subject": r["subject"],
|
||||
"linked": r["linked"] or 0,
|
||||
"attempted": attempted,
|
||||
"accuracy": accuracy,
|
||||
"state": state,
|
||||
}
|
||||
)
|
||||
|
||||
# 약점 우선(정답률 오름차순) → 미평가는 뒤로. 홈 위젯용 상위 N.
|
||||
weak = sorted(
|
||||
[c for c in concepts if c["state"] == "weak"],
|
||||
key=lambda c: (c["accuracy"], -c["attempted"], c["doc_id"]),
|
||||
)
|
||||
return {
|
||||
"weak": weak[:limit],
|
||||
"weak_total": len(weak),
|
||||
"evaluated_total": sum(1 for c in concepts if c["state"] != "unattempted"),
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
"""concept_parser — 개념노트 markdown 구조 파서 + 관련개념 백링크 해소 (이론 리더용).
|
||||
|
||||
정찰 실측 불변식(273/273): 개념노트는 고정 골격을 100% 따름 —
|
||||
# {H1 제목} (첫 줄, DB title 과 다른 표시용 제목)
|
||||
> **한 줄 요약**: {요약} (blockquote, 라벨 고정)
|
||||
## {본문 라벨} ... (BODY, 자유 라벨 H2 0~N, 트레일 ★ 가능)
|
||||
## 빈출 포인트 (항상, 관련개념 직전)
|
||||
## 관련 개념 (항상, 문서 최종 섹션)
|
||||
|
||||
코드펜스(``` ASCII 도식) 내부의 ##/- 는 무시. 헤딩 트레일 ★ 는 스트립(라벨 정규화).
|
||||
'빈출 포인트'/'관련 개념' 앵커만 이름으로 잡고 나머지 BODY 는 순서·위치로 처리(라벨 화이트리스트 금지).
|
||||
순수 함수 · LLM 0.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
_FENCE = re.compile(r"^\s*```")
|
||||
_H1 = re.compile(r"^#\s+(.+?)\s*$")
|
||||
_H2 = re.compile(r"^##\s+(.+?)\s*$") # ### 는 매칭 안 됨(## 뒤 \s 요구)
|
||||
_SUMMARY = re.compile(r"^>\s*\*\*한 줄 요약\*\*:\s*(.+)$")
|
||||
_STAR_SUFFIX = re.compile(r"\s*★+\s*$")
|
||||
_TRAIL_STARS = re.compile(r"★+\s*$")
|
||||
_BINCHEOL_ITEM = re.compile(r"^\s*-\s+(★*)\s*(.+)$")
|
||||
_RELATED_ITEM = re.compile(r"^\s*-\s+(.+)$")
|
||||
_PAREN = re.compile(r"\s*\(.*$") # 괄호부터 끝(clarifier 힌트 절단)
|
||||
_NUM_PREFIX = re.compile(r"^\d+_")
|
||||
_STRIP_SYM = re.compile(r"[\s_·,./()\-]")
|
||||
|
||||
_ANCHOR_BINCHEOL = "빈출 포인트"
|
||||
_ANCHOR_RELATED = "관련 개념"
|
||||
|
||||
|
||||
def parse_concept(md: str) -> dict:
|
||||
"""개념노트 md → {title, summary, body[{label,stars,md}], bincheol[{tier,text}], related[{raw,phrase,hint}]}."""
|
||||
lines = (md or "").split("\n")
|
||||
title: str | None = None
|
||||
summary: str | None = None
|
||||
body: list[dict] = []
|
||||
bincheol_lines: list[str] = []
|
||||
related_lines: list[str] = []
|
||||
|
||||
in_fence = False
|
||||
zone = "pre" # pre | body | bincheol | related
|
||||
body_cur: dict | None = None
|
||||
|
||||
def emit(line: str) -> None:
|
||||
if body_cur is not None:
|
||||
body_cur["_lines"].append(line)
|
||||
elif zone == "bincheol":
|
||||
bincheol_lines.append(line)
|
||||
elif zone == "related":
|
||||
related_lines.append(line)
|
||||
# pre-zone 내용(요약 앞 잡음)은 버림
|
||||
|
||||
for ln in lines:
|
||||
if _FENCE.match(ln):
|
||||
in_fence = not in_fence
|
||||
emit(ln)
|
||||
continue
|
||||
if in_fence:
|
||||
emit(ln)
|
||||
continue
|
||||
|
||||
if title is None:
|
||||
m = _H1.match(ln)
|
||||
if m:
|
||||
title = m.group(1).strip()
|
||||
continue
|
||||
if summary is None:
|
||||
m = _SUMMARY.match(ln)
|
||||
if m:
|
||||
summary = m.group(1).strip()
|
||||
continue
|
||||
|
||||
m2 = _H2.match(ln)
|
||||
if m2:
|
||||
raw_label = m2.group(1).strip()
|
||||
star_m = _TRAIL_STARS.search(raw_label)
|
||||
stars = len(star_m.group(0).strip()) if star_m else 0
|
||||
label = _STAR_SUFFIX.sub("", raw_label).strip()
|
||||
if label == _ANCHOR_BINCHEOL:
|
||||
zone = "bincheol"
|
||||
body_cur = None
|
||||
continue
|
||||
if label == _ANCHOR_RELATED:
|
||||
zone = "related"
|
||||
body_cur = None
|
||||
continue
|
||||
body_cur = {"label": label, "stars": stars, "_lines": []}
|
||||
body.append(body_cur)
|
||||
zone = "body"
|
||||
continue
|
||||
|
||||
emit(ln)
|
||||
|
||||
body_out = []
|
||||
for s in body:
|
||||
text = "\n".join(s["_lines"]).strip()
|
||||
if text or s["label"]:
|
||||
body_out.append({"label": s["label"], "stars": s["stars"], "md": text})
|
||||
|
||||
bincheol = []
|
||||
for ln in bincheol_lines:
|
||||
m = _BINCHEOL_ITEM.match(ln)
|
||||
if m:
|
||||
bincheol.append({"tier": len(m.group(1)), "text": m.group(2).strip()})
|
||||
|
||||
related = []
|
||||
for ln in related_lines:
|
||||
m = _RELATED_ITEM.match(ln)
|
||||
if m:
|
||||
raw = m.group(1).strip()
|
||||
phrase = _PAREN.sub("", raw).strip()
|
||||
hint = raw[len(phrase):].strip() if len(raw) > len(phrase) else ""
|
||||
if phrase:
|
||||
related.append({"raw": raw, "phrase": phrase, "hint": hint})
|
||||
|
||||
return {
|
||||
"title": title,
|
||||
"summary": summary,
|
||||
"body": body_out,
|
||||
"bincheol": bincheol,
|
||||
"related": related,
|
||||
}
|
||||
|
||||
|
||||
def _normalize(s: str) -> str:
|
||||
"""해소용 정규화: NN_ 접두 제거 → 소문자 → 공백/기호 제거. 영문은 lowercase 유지."""
|
||||
s = _NUM_PREFIX.sub("", s or "")
|
||||
s = s.lower()
|
||||
s = _STRIP_SYM.sub("", s)
|
||||
return s
|
||||
|
||||
|
||||
def resolve_related(related: list[dict], title_index: list[tuple]) -> list[dict]:
|
||||
"""관련개념 구절 → 개념 doc 해소. title_index = [(doc_id, title, subject), ...].
|
||||
|
||||
다단 fallback(정찰 ~79%): 정규화 exact → 양방향 substring(≥2자 가드) → 미해소=dangling(doc_id None).
|
||||
"""
|
||||
norm_exact: dict[str, int] = {}
|
||||
norm_list: list[tuple[str, int, str]] = []
|
||||
for did, ttl, _subj in title_index:
|
||||
n = _normalize(ttl)
|
||||
if n:
|
||||
norm_exact.setdefault(n, did)
|
||||
norm_list.append((n, did, ttl))
|
||||
|
||||
out = []
|
||||
for it in related:
|
||||
pn = _normalize(it["phrase"])
|
||||
did: int | None = None
|
||||
rtitle: str | None = None
|
||||
if pn and len(pn) >= 2:
|
||||
if pn in norm_exact:
|
||||
did = norm_exact[pn]
|
||||
else:
|
||||
# substring 폴백: title-norm ⊆ phrase-norm 방향만(짧은 phrase 가 더 큰 title 을
|
||||
# 삼키는 오결선 방지, 예: '염산'→'염산나트륨' X) + 길이차 최소(가장 구체적) +
|
||||
# doc_id tiebreak(순서 무관 결정성). 후보 없으면 dangling(doc_id None).
|
||||
cands = [
|
||||
(abs(len(n) - len(pn)), cand, ttl)
|
||||
for n, cand, ttl in norm_list
|
||||
if len(n) >= 2 and n in pn
|
||||
]
|
||||
if cands:
|
||||
cands.sort(key=lambda c: (c[0], c[1]))
|
||||
_, did, rtitle = cands[0]
|
||||
if did is not None and rtitle is None:
|
||||
rtitle = next((t for d, t, _ in title_index if d == did), None)
|
||||
out.append(
|
||||
{"phrase": it["phrase"], "hint": it["hint"], "doc_id": did, "title": rtitle}
|
||||
)
|
||||
return out
|
||||
@@ -1,224 +0,0 @@
|
||||
"""summarize_units — 거대문서 요약 전용 분할(map-reduce 유닛) 순수함수 (presegment PR1).
|
||||
|
||||
plan ds-presegment-mapreduce-2 (2026-06-29 설계 합의 · PR0 실측 봉인):
|
||||
- CAP_TOKENS = 12,000 tok/unit — greedy-pack 상한 (PR0: giant 236건 실측 캘리브레이션)
|
||||
- TRIGGER_TOKENS = 25,000 tok — 이하는 단일콜 유지, 초과 시 map-reduce
|
||||
- 3-way over% 게이트 (단독 CAP 초과 섹션의 토큰 비중. 헤딩 개수는 무의미 — ASME 1,494개):
|
||||
over% == 0 → 'auto' (TIER1: 로컬 자동 분할, PR0 실측 78%)
|
||||
0 < over% <= 40 → 'hybrid' (패킹분 로컬 + 초과 섹션만 클로드, 8%)
|
||||
over% > 40 → 'whole' (TIER2: 클로드 전체 분할, 14%)
|
||||
- 토큰 추정 = PR0 실 Qwen 토크나이저 캘리브레이션: 한글 0.529 tok/char · 기타 0.217.
|
||||
구 휴리스틱(0.625/0.25)은 ~15% 과대라 폐기.
|
||||
|
||||
불변식:
|
||||
- 순수함수 — DB/네트워크/파일 접촉 0. 분할 = 요약 전용 아티팩트(문서 아님·검색/임베딩 미편입).
|
||||
- leaf 추출 = hier_decomp.builder 재사용, leaf_hard_max=∞ 로 window-split 억제
|
||||
(헤딩 leaf 만 — PR0 측정환경과 동일). 인접 섹션만 greedy-pack(순서 보존·중간 폐기 0
|
||||
— 구 deep_summary 의 head/mid/tail 가운데 폐기 버그를 커버리지로 대체).
|
||||
- 배선(deep_summary 분기·HOLD·클로드 알람)은 PR2/PR3 — 본 모듈은 계획만 산출.
|
||||
|
||||
호출: plan_summarize_units(md_text) -> UnitPlan
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
# 상대 import — 컨테이너(services.*)와 repo-root 테스트(app.services.*) 양쪽에서 동작.
|
||||
# (구 `from app.services...` 절대 import 는 컨테이너에 app 패키지가 없어 ModuleNotFoundError —
|
||||
# PR1 은 소비자 0 이라 잠복했던 버그, PR2 배선 시점에 수정.)
|
||||
from .hier_decomp.builder import HierNode, build_hier_tree
|
||||
|
||||
CAP_TOKENS = 12_000
|
||||
TRIGGER_TOKENS = 25_000
|
||||
HYBRID_MAX_OVER_PCT = 40.0
|
||||
|
||||
# PR0 실 Qwen tokenizer 캘리브레이션 (tok/char)
|
||||
KO_TOK_PER_CHAR = 0.529
|
||||
OTHER_TOK_PER_CHAR = 0.217
|
||||
|
||||
_HANGUL_RANGES = (
|
||||
(0xAC00, 0xD7A3), # 완성형 음절
|
||||
(0x1100, 0x11FF), # 자모
|
||||
(0x3130, 0x318F), # 호환 자모
|
||||
)
|
||||
|
||||
|
||||
def _is_hangul(ch: str) -> bool:
|
||||
cp = ord(ch)
|
||||
return any(lo <= cp <= hi for lo, hi in _HANGUL_RANGES)
|
||||
|
||||
|
||||
def estimate_tokens(text: str) -> int:
|
||||
"""PR0 캘리브레이션 기반 토큰 추정 (한글 0.529 · 기타 0.217 tok/char)."""
|
||||
if not text:
|
||||
return 0
|
||||
ko = sum(1 for ch in text if _is_hangul(ch))
|
||||
other = len(text) - ko
|
||||
return round(ko * KO_TOK_PER_CHAR + other * OTHER_TOK_PER_CHAR)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SummarizeUnit:
|
||||
"""map-reduce 1유닛 — 인접 leaf 섹션들의 greedy-pack (요약 전용, 문서 아님)."""
|
||||
index: int
|
||||
section_titles: list[str | None] = field(default_factory=list)
|
||||
text: str = ""
|
||||
est_tokens: int = 0
|
||||
over_cap: bool = False # 단독 섹션이 CAP 초과 (hybrid 시 클로드 대상)
|
||||
|
||||
|
||||
@dataclass
|
||||
class UnitPlan:
|
||||
mode: str # 'single' | 'map_reduce'
|
||||
tier: str | None # map_reduce 시 'auto' | 'hybrid' | 'whole'
|
||||
total_est_tokens: int = 0
|
||||
over_pct: float = 0.0
|
||||
units: list[SummarizeUnit] = field(default_factory=list)
|
||||
|
||||
|
||||
def extract_leaves(md_text: str) -> list[HierNode]:
|
||||
"""헤딩 leaf 만 추출 — leaf_hard_max=∞ 로 window-split 억제 (PR0 측정환경 동일)."""
|
||||
nodes = build_hier_tree(
|
||||
md_text,
|
||||
leaf_target_max=sys.maxsize,
|
||||
leaf_hard_max=sys.maxsize,
|
||||
)
|
||||
return [n for n in nodes if n.is_leaf]
|
||||
|
||||
|
||||
def greedy_pack(leaves: list[HierNode], cap: int = CAP_TOKENS) -> list[SummarizeUnit]:
|
||||
"""인접 leaf 를 순서 보존하며 est_tokens<=cap 으로 pack. 단독 초과 leaf = 전용 유닛(over_cap)."""
|
||||
units: list[SummarizeUnit] = []
|
||||
cur_titles: list[str | None] = []
|
||||
cur_texts: list[str] = []
|
||||
cur_tokens = 0
|
||||
|
||||
def _flush() -> None:
|
||||
nonlocal cur_titles, cur_texts, cur_tokens
|
||||
if cur_texts:
|
||||
units.append(SummarizeUnit(
|
||||
index=len(units),
|
||||
section_titles=cur_titles,
|
||||
text="\n\n".join(cur_texts),
|
||||
est_tokens=cur_tokens,
|
||||
))
|
||||
cur_titles, cur_texts, cur_tokens = [], [], 0
|
||||
|
||||
for leaf in leaves:
|
||||
t = estimate_tokens(leaf.text)
|
||||
if t > cap:
|
||||
_flush()
|
||||
units.append(SummarizeUnit(
|
||||
index=len(units),
|
||||
section_titles=[leaf.section_title],
|
||||
text=leaf.text,
|
||||
est_tokens=t,
|
||||
over_cap=True,
|
||||
))
|
||||
continue
|
||||
if cur_tokens + t > cap:
|
||||
_flush()
|
||||
cur_titles.append(leaf.section_title)
|
||||
cur_texts.append(leaf.text)
|
||||
cur_tokens += t
|
||||
_flush()
|
||||
return units
|
||||
|
||||
|
||||
def over_pct(leaves: list[HierNode], cap: int = CAP_TOKENS) -> float:
|
||||
"""단독 CAP 초과 섹션들의 토큰 비중(%) — 3-way 게이트 입력."""
|
||||
total = 0
|
||||
over = 0
|
||||
for leaf in leaves:
|
||||
t = estimate_tokens(leaf.text)
|
||||
total += t
|
||||
if t > cap:
|
||||
over += t
|
||||
if total == 0:
|
||||
return 0.0
|
||||
return over * 100.0 / total
|
||||
|
||||
|
||||
def gate(over: float) -> str:
|
||||
"""over% → tier. 0=auto / (0,40]=hybrid / >40=whole. 클로드 결과 재검증에도 재사용."""
|
||||
if over <= 0.0:
|
||||
return "auto"
|
||||
if over <= HYBRID_MAX_OVER_PCT:
|
||||
return "hybrid"
|
||||
return "whole"
|
||||
|
||||
|
||||
def plan_summarize_units(
|
||||
md_text: str, *,
|
||||
cap: int = CAP_TOKENS,
|
||||
trigger: int = TRIGGER_TOKENS,
|
||||
) -> UnitPlan:
|
||||
"""문서 → 요약 실행 계획. trigger 이하=single(현행 단일콜), 초과=map_reduce(tier+units)."""
|
||||
total = estimate_tokens(md_text)
|
||||
if total <= trigger:
|
||||
return UnitPlan(mode="single", tier=None, total_est_tokens=total)
|
||||
leaves = extract_leaves(md_text)
|
||||
pct = over_pct(leaves, cap)
|
||||
return UnitPlan(
|
||||
mode="map_reduce",
|
||||
tier=gate(pct),
|
||||
total_est_tokens=total,
|
||||
over_pct=round(pct, 2),
|
||||
units=greedy_pack(leaves, cap),
|
||||
)
|
||||
|
||||
|
||||
# ─── PR2 — map/reduce 프롬프트 조립 순수함수 (deep_summary_worker 가 소비) ───
|
||||
|
||||
def render_map_slice(unit: SummarizeUnit, total_units: int) -> str:
|
||||
"""map 콜의 {original_text_slices} 대체 — 유닛 위치·섹션 라벨 + 본문."""
|
||||
titles = " · ".join(t for t in unit.section_titles if t) or "(무제 구간)"
|
||||
return f"[유닛 {unit.index + 1}/{total_units} — 섹션: {titles}]\n{unit.text}"
|
||||
|
||||
|
||||
def _format_unit_summary(res: dict, total_units: int) -> str:
|
||||
"""map 결과 1건 → reduce 입력 블록. res 키 = index/titles/tldr/detail/inconsistencies."""
|
||||
titles = " · ".join(t for t in (res.get("titles") or []) if t) or "(무제 구간)"
|
||||
lines = [f"[유닛 {int(res.get('index', 0)) + 1}/{total_units} — 섹션: {titles}]"]
|
||||
if res.get("tldr"):
|
||||
lines.append(f"TLDR: {res['tldr']}")
|
||||
if res.get("detail"):
|
||||
lines.append(str(res["detail"]))
|
||||
for inc in res.get("inconsistencies") or []:
|
||||
if isinstance(inc, dict):
|
||||
lines.append(f"불일치({inc.get('kind', '')}): {inc.get('desc', '')}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_reduce_units_block(
|
||||
results: list[dict],
|
||||
budget_tokens: int,
|
||||
*,
|
||||
min_detail_chars: int = 200,
|
||||
) -> tuple[str, bool]:
|
||||
"""reduce 입력 블록 조립 — budget_tokens 이하 보장(캡 초과 0 검증 게이트의 reduce 측).
|
||||
|
||||
초과 시 detail 만 비례 절단(라벨·TLDR·불일치 보전, 원문 순서 유지). 반환 (block, truncated).
|
||||
"""
|
||||
total_units = len(results)
|
||||
work = [dict(r) for r in results]
|
||||
truncated = False
|
||||
for _ in range(4):
|
||||
block = "\n\n".join(_format_unit_summary(r, total_units) for r in work)
|
||||
est = estimate_tokens(block)
|
||||
if est <= budget_tokens:
|
||||
return block, truncated
|
||||
ratio = budget_tokens / est
|
||||
for r in work:
|
||||
detail = str(r.get("detail") or "")
|
||||
keep = max(min_detail_chars, int(len(detail) * ratio * 0.9))
|
||||
if len(detail) > keep:
|
||||
r["detail"] = detail[:keep] + "…(절단)"
|
||||
truncated = True
|
||||
# 최후 방어 — 비례 절단이 floor(min_detail_chars)에 막히면 문자 하드 컷(KO 최악 비율 가정)
|
||||
block = "\n\n".join(_format_unit_summary(r, total_units) for r in work)
|
||||
if estimate_tokens(block) > budget_tokens:
|
||||
block = block[: max(1, int(budget_tokens / KO_TOK_PER_CHAR))]
|
||||
truncated = True
|
||||
return block, truncated
|
||||
@@ -10,9 +10,7 @@ EscalationEnvelope + subject_domain 을 읽어, PR-A policy 템플릿 `p3c_deep_
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
@@ -31,25 +29,10 @@ from models.queue import ProcessingQueue, StageDeferred
|
||||
from policy.prompt_render import render_26b, policy_version as compute_policy_version
|
||||
from services.document_telemetry import record_analyze_event
|
||||
from services.search.llm_gate import Priority, acquire_mlx_gate
|
||||
from services.summarize_units import (
|
||||
CAP_TOKENS,
|
||||
UnitPlan,
|
||||
build_reduce_units_block,
|
||||
estimate_tokens,
|
||||
plan_summarize_units,
|
||||
render_map_slice,
|
||||
)
|
||||
|
||||
logger = setup_logger("deep_summary_worker")
|
||||
|
||||
DEEP_SUMMARY_TASK = "p3c_deep_summary"
|
||||
# presegment PR2 (plan ds-presegment-mapreduce-2) — 거대문서 map-reduce
|
||||
REDUCE_TASK = "p3c_deep_summary_reduce"
|
||||
# HYBRID/TIER2(클로드 유인 분할 필요) HOLD 재확인 간격. PR3(알람·경계 주입) 전까지는
|
||||
# 이 간격으로 재계획만 반복한다 — attempts 미소모(StageDeferred)라 영구 failed 없음.
|
||||
HOLD_RETRY_MINUTES = int(os.getenv("DEEP_SUMMARY_HOLD_RETRY_MINUTES", "1440"))
|
||||
# reduce 프롬프트 오버헤드가 비정상적으로 커도 유닛 블록 예산은 이 밑으로 안 내려감(방어).
|
||||
REDUCE_BUDGET_FLOOR_TOKENS = 1_000
|
||||
|
||||
# inconsistencies kind 허용 목록 (feedback_document_server_domain_scope.md — 구매/계약 제외)
|
||||
ALLOWED_INCONSISTENCY_KINDS = {
|
||||
@@ -111,25 +94,6 @@ async def process(
|
||||
|
||||
envelope = EscalationEnvelope.from_json(json.dumps(envelope_raw))
|
||||
|
||||
# ─── presegment PR2 게이트 (plan ds-presegment-mapreduce-2) ───
|
||||
# TRIGGER(25K tok) 이하 = 아래 기존 단일콜 경로 그대로(무회귀). 초과 시 3-way:
|
||||
# auto(over%==0) → 로컬 map-reduce (유닛별 26B → reduce)
|
||||
# hybrid/whole → HOLD(awaiting_split) — 맥미니 미전송, 클로드 유인 분할은 PR3
|
||||
# 게이트/유닛은 전체 extracted_text 기준 — 단일콜의 head/mid/tail "가운데 폐기"를
|
||||
# 전 유닛 커버리지로 대체한다. build_hier_tree 가 거대 md 에서 초 단위 CPU 라
|
||||
# 이벤트루프 점유 회피 위해 to_thread (presegment_worker._read_toc 와 동일 패턴).
|
||||
unit_plan = await asyncio.to_thread(plan_summarize_units, doc.extracted_text or "")
|
||||
if unit_plan.mode == "map_reduce":
|
||||
# units 빈 auto 는 이론상 불가(비어있지 않은 텍스트 = leaf >= 1)지만, 빈 reduce
|
||||
# 단일콜(환각 위험)로 흐르지 않게 방어적으로 HOLD 로 보낸다.
|
||||
if unit_plan.tier != "auto" or not unit_plan.units:
|
||||
await _hold_awaiting_split(session, queue_row, unit_plan, document_id)
|
||||
await _process_map_reduce(
|
||||
doc, queue_row, envelope, subject_domain, unit_plan, session,
|
||||
defer_on_deep_unavailable=defer_on_deep_unavailable,
|
||||
)
|
||||
return
|
||||
|
||||
# 원문 슬라이스 추출 (envelope.original_pointers.text_ranges 기반)
|
||||
slices = _build_text_slices(doc.extracted_text or "", envelope.original_pointers)
|
||||
|
||||
@@ -250,267 +214,6 @@ async def process(
|
||||
)
|
||||
|
||||
|
||||
async def _hold_awaiting_split(
|
||||
session: AsyncSession, queue_row: ProcessingQueue, plan: UnitPlan, document_id: int
|
||||
) -> None:
|
||||
"""HYBRID/TIER2 — 클로드 유인 분할 대기(HOLD). 맥미니 미전송, StageDeferred 보류.
|
||||
|
||||
payload.presegment.awaiting_split 마킹을 먼저 commit — StageDeferred 핸들러
|
||||
(queue_consumer)는 새 세션에서 행을 다시 읽어 deferred_until 만 병합하므로 유실 없음.
|
||||
알람(ntfy)·클로드 경계 주입은 PR3 — 그 전까지는 HOLD_RETRY_MINUTES 간격 재계획만 반복.
|
||||
무인 자동 cloud 호출 금지 룰 준수(클로드 경로는 항상 유인 게이트).
|
||||
"""
|
||||
payload = dict(queue_row.payload or {})
|
||||
preseg = dict(payload.get("presegment") or {})
|
||||
preseg.update({
|
||||
"awaiting_split": True,
|
||||
"tier": plan.tier,
|
||||
"over_pct": plan.over_pct,
|
||||
"total_est_tokens": plan.total_est_tokens,
|
||||
"units": len(plan.units),
|
||||
# 클로드가 분할해야 할 초과 섹션 표본 (PR3 알람 본문용)
|
||||
"oversized_sections": [
|
||||
(u.section_titles[0] if u.section_titles else None)
|
||||
for u in plan.units if u.over_cap
|
||||
][:20],
|
||||
})
|
||||
payload["presegment"] = preseg
|
||||
queue_row.payload = payload # 재할당 = JSONB 변경 감지
|
||||
await session.commit()
|
||||
logger.info(
|
||||
f"[deep] id={document_id} awaiting_split tier={plan.tier} over_pct={plan.over_pct} "
|
||||
f"total_est_tokens={plan.total_est_tokens} units={len(plan.units)} "
|
||||
f"→ HOLD ({HOLD_RETRY_MINUTES}분 후 재확인, 클로드 분할=PR3 유인)"
|
||||
)
|
||||
raise StageDeferred(
|
||||
f"awaiting_split:{plan.tier}", retry_after_minutes=HOLD_RETRY_MINUTES
|
||||
)
|
||||
|
||||
|
||||
async def _call_26b(
|
||||
client: AIClient, prompt: str, *, defer_on_deep_unavailable: bool, document_id: int
|
||||
):
|
||||
"""map/reduce 공용 26B 호출 — 단일콜 경로와 동일한 deep 슬롯 우선 + fair-share 폴백.
|
||||
|
||||
반환 (raw, used_cfg). 맥북(deep) 불가 시 consumer 경로는 맥미니 primary 로 즉시
|
||||
처리(동일 모델 — 강등 아님), drain 경로는 StageDeferred 전파(맥북 레버 시멘틱).
|
||||
"""
|
||||
deep_cfg = client.ai.deep
|
||||
if deep_cfg is not None:
|
||||
try:
|
||||
return await call_deep_or_defer(client, prompt), deep_cfg
|
||||
except StageDeferred:
|
||||
if defer_on_deep_unavailable:
|
||||
raise
|
||||
logger.info(f"[deep] id={document_id} 맥북 불가 → 맥미니 primary 처리 (fair-share)")
|
||||
async with acquire_mlx_gate(Priority.BACKGROUND):
|
||||
return await client.call_primary(prompt), settings.ai.primary
|
||||
|
||||
|
||||
def _parse_deep_output(raw: str) -> tuple[DeepSummaryOutput | None, str | None]:
|
||||
"""raw → DeepSummaryOutput. 단일콜 경로와 동일한 3단 파서. 실패 시 (None, parse_error)."""
|
||||
try:
|
||||
parsed = _parse_outermost_json(raw) or parse_json_response(raw)
|
||||
if not parsed:
|
||||
parsed = _regex_extract_fields(raw)
|
||||
return DeepSummaryOutput.model_validate(parsed or {}), None
|
||||
except (ValidationError, ValueError, TypeError) as exc:
|
||||
return None, f"parse:{type(exc).__name__}"
|
||||
|
||||
|
||||
async def _process_map_reduce(
|
||||
doc: Document,
|
||||
queue_row: ProcessingQueue,
|
||||
envelope: EscalationEnvelope,
|
||||
subject_domain: str,
|
||||
plan: UnitPlan,
|
||||
session: AsyncSession,
|
||||
*,
|
||||
defer_on_deep_unavailable: bool,
|
||||
) -> None:
|
||||
"""TIER1 자동 — 유닛별 map(26B) → reduce(26B) → 단일콜과 동일 필드 기록.
|
||||
|
||||
멱등 재개: 성공 유닛은 payload.presegment.map_results 에 즉시 commit —
|
||||
502/defer/재시작 후 재클레임 시 완료 유닛은 건너뛴다. 유닛 인덱스는
|
||||
plan_summarize_units 가 같은 extracted_text 에 결정적이라 attempt 간 안정.
|
||||
파싱 실패 유닛이 남으면 raise → queue_consumer 의 기존 attempts/백오프 재사용
|
||||
(실패 유닛만 재호출되므로 재시도 비용 = 잔여 유닛뿐).
|
||||
"""
|
||||
document_id = doc.id
|
||||
units = plan.units
|
||||
n = len(units)
|
||||
payload = dict(queue_row.payload or {})
|
||||
preseg = dict(payload.get("presegment") or {})
|
||||
preseg.pop("awaiting_split", None) # 재계획으로 auto 가 된 경우 HOLD 마킹 해제
|
||||
map_results: dict = dict(preseg.get("map_results") or {})
|
||||
|
||||
logger.info(
|
||||
f"[deep] id={document_id} map_reduce 시작 units={n} over_pct={plan.over_pct} "
|
||||
f"total_est_tokens={plan.total_est_tokens} resume={len(map_results)}/{n}"
|
||||
)
|
||||
|
||||
rendered = render_26b(DEEP_SUMMARY_TASK, subject_domain)
|
||||
envelope_injection = envelope.to_system_injection()
|
||||
|
||||
client = AIClient()
|
||||
start = time.perf_counter()
|
||||
used_cfg = client.ai.deep or settings.ai.primary
|
||||
failed_units: list[int] = []
|
||||
try:
|
||||
# ── map: 유닛별 26B (콜 사이마다 gate 를 놓아 짧은 인터랙티브 요청이 끼어든다) ──
|
||||
for unit in units:
|
||||
key = str(unit.index)
|
||||
if key in map_results:
|
||||
continue
|
||||
prompt = (
|
||||
rendered
|
||||
.replace("{escalation_envelope_json}", envelope_injection)
|
||||
.replace("{original_text_slices}", render_map_slice(unit, n))
|
||||
)
|
||||
# 검증 게이트 "모든 LLM 콜 캡 초과 0" 을 로그로 단정 가능하게 남긴다.
|
||||
logger.info(
|
||||
f"[deep] id={document_id} map {unit.index + 1}/{n} "
|
||||
f"unit_tokens={unit.est_tokens} prompt_est_tokens={estimate_tokens(prompt)} "
|
||||
f"cap={CAP_TOKENS}"
|
||||
)
|
||||
raw, used_cfg = await _call_26b(
|
||||
client, prompt,
|
||||
defer_on_deep_unavailable=defer_on_deep_unavailable,
|
||||
document_id=document_id,
|
||||
)
|
||||
out, perr = _parse_deep_output(raw)
|
||||
if out is None or not (out.detail or out.tldr):
|
||||
# 실패 유닛은 persist 하지 않음 — 재시도가 이 유닛만 다시 호출한다.
|
||||
failed_units.append(unit.index)
|
||||
logger.warning(
|
||||
f"[deep] id={document_id} map {unit.index + 1}/{n} 결과 비었음/파싱 실패"
|
||||
f"({perr}) — 유닛 재시도 대상"
|
||||
)
|
||||
continue
|
||||
# ★매 유닛 새 dict 로 재구성 (in-place 변경 금지) — 직전 commit 의 committed
|
||||
# 스냅샷이 같은 중첩 객체를 참조하면 old==new 로 보여 SQLAlchemy 가 UPDATE 를
|
||||
# 스킵한다(60254 라이브에서 unit 0 만 persist 된 aliasing 버그의 fix).
|
||||
map_results = {
|
||||
**map_results,
|
||||
key: {
|
||||
"index": unit.index,
|
||||
"titles": [t for t in unit.section_titles if t][:8],
|
||||
"tldr": out.tldr,
|
||||
"detail": out.detail,
|
||||
"inconsistencies": _filter_inconsistencies(out.inconsistencies or []),
|
||||
},
|
||||
}
|
||||
preseg = {
|
||||
**preseg,
|
||||
"tier": plan.tier,
|
||||
"over_pct": plan.over_pct,
|
||||
"total_est_tokens": plan.total_est_tokens,
|
||||
"units": n,
|
||||
"map_results": map_results,
|
||||
}
|
||||
payload = {**payload, "presegment": preseg}
|
||||
queue_row.payload = payload # 재할당 = JSONB 변경 감지
|
||||
await session.commit() # 유닛 단위 멱등 재개 지점
|
||||
|
||||
if failed_units:
|
||||
raise ValueError(
|
||||
f"map 유닛 {len(failed_units)}/{n}건 결과 없음 — 재시도 대상: {failed_units[:10]}"
|
||||
)
|
||||
|
||||
# ── reduce: 요약들의 요약 1콜 (유닛 블록도 캡 이하로 절단 보장) ──
|
||||
reduce_rendered = render_26b(REDUCE_TASK, subject_domain)
|
||||
base_prompt = (
|
||||
reduce_rendered
|
||||
.replace("{escalation_envelope_json}", envelope_injection)
|
||||
.replace("{unit_count}", str(n))
|
||||
)
|
||||
budget = max(
|
||||
REDUCE_BUDGET_FLOOR_TOKENS, CAP_TOKENS - estimate_tokens(base_prompt)
|
||||
)
|
||||
ordered = [map_results[str(u.index)] for u in units]
|
||||
block, reduce_truncated = build_reduce_units_block(ordered, budget)
|
||||
reduce_prompt = base_prompt.replace("{unit_summaries}", block)
|
||||
logger.info(
|
||||
f"[deep] id={document_id} reduce units={n} "
|
||||
f"prompt_est_tokens={estimate_tokens(reduce_prompt)} cap={CAP_TOKENS} "
|
||||
f"truncated={reduce_truncated}"
|
||||
)
|
||||
raw, used_cfg = await _call_26b(
|
||||
client, reduce_prompt,
|
||||
defer_on_deep_unavailable=defer_on_deep_unavailable,
|
||||
document_id=document_id,
|
||||
)
|
||||
except StageDeferred:
|
||||
logger.info(
|
||||
f"[deep] id={document_id} map_reduce 보류 — 완료 유닛 {len(map_results)}/{n} 보존"
|
||||
)
|
||||
raise
|
||||
except Exception as exc:
|
||||
# 단일콜 경로와 동일 — 호출 실패는 전파해 queue_consumer 가 재시도/dead-letter 처리.
|
||||
logger.warning(f"[deep] id={document_id} map_reduce 실패: {exc}")
|
||||
raise
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
latency_ms = int((time.perf_counter() - start) * 1000)
|
||||
deep_out, parse_error = _parse_deep_output(raw)
|
||||
if deep_out is None:
|
||||
# 단일콜 경로와 동일 시멘틱 — doc 미기록(legacy 결과 보존), 이벤트로 가시화.
|
||||
deep_out = DeepSummaryOutput()
|
||||
logger.warning(f"[deep] id={document_id} reduce 파싱 실패 ({parse_error}) — doc 미기록")
|
||||
|
||||
if not parse_error:
|
||||
doc.ai_detail_summary = (deep_out.detail or "").strip() or None
|
||||
# 불일치 = reduce 출력 + map 유닛 합본 dedup — reduce 가 떨궈도 유닛 발견분 보전.
|
||||
merged = _filter_inconsistencies(deep_out.inconsistencies or [])
|
||||
seen = {(i["kind"], i["desc"]) for i in merged}
|
||||
for res in ordered:
|
||||
for inc in res.get("inconsistencies") or []:
|
||||
k = (inc.get("kind"), inc.get("desc"))
|
||||
if k not in seen:
|
||||
seen.add(k)
|
||||
merged.append(inc)
|
||||
doc.ai_inconsistencies = merged
|
||||
doc.ai_analysis_tier = "deep"
|
||||
doc.ai_processed_at = datetime.now(timezone.utc)
|
||||
|
||||
try:
|
||||
pv = compute_policy_version(REDUCE_TASK)
|
||||
except Exception:
|
||||
pv = None
|
||||
|
||||
await record_analyze_event(
|
||||
doc_id=document_id,
|
||||
user_id=None,
|
||||
mode="summary_deep",
|
||||
text_limit=used_cfg.context_char_limit or 260000,
|
||||
truncated=reduce_truncated,
|
||||
layers_returned=["detail_summary", "inconsistencies"] if not parse_error else [],
|
||||
cached=False,
|
||||
latency_ms=latency_ms,
|
||||
model_name=used_cfg.model,
|
||||
prompt_version=(f"{REDUCE_TASK}@{pv}" if pv else REDUCE_TASK),
|
||||
error_code=parse_error,
|
||||
source="document_server",
|
||||
subject_domain=subject_domain,
|
||||
risk_flags=list(envelope.risk_flags),
|
||||
high_impact_task=None,
|
||||
escalation_reasons=list(envelope.escalation_reasons),
|
||||
confidence=deep_out.confidence,
|
||||
policy_version=pv,
|
||||
shadow_would_route_to="primary",
|
||||
tier="primary",
|
||||
escalated_to_26b=True,
|
||||
suppressed_reason=None,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"[deep] id={document_id} map_reduce 완료 units={n} "
|
||||
f"detail_len={len(doc.ai_detail_summary or '')} inc={len(doc.ai_inconsistencies or [])} "
|
||||
f"latency_ms={latency_ms} parse_error={parse_error}"
|
||||
)
|
||||
|
||||
|
||||
def _build_text_slices(text: str, pointers: dict) -> str:
|
||||
"""original_pointers.text_ranges 의 [{start, end}] 를 실제 본문 슬라이스로 합친다.
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
|
||||
/// macOS 파일 패널 + 네이티브 다운로드 헬퍼. AppKit(NSOpenPanel/NSSavePanel) 의존이라 AppFeature
|
||||
/// (맥OS UI 계층)에 둔다 — DSKit 은 크로스플랫폼 유지(향후 iOS/watchOS). 모두 @MainActor.
|
||||
@MainActor
|
||||
enum FilePanels {
|
||||
/// 업로드할 파일 1개 선택. 취소 시 nil.
|
||||
static func pickFileToUpload() -> URL? {
|
||||
let panel = NSOpenPanel()
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.canChooseDirectories = false
|
||||
panel.canChooseFiles = true
|
||||
panel.message = "업로드할 문서를 선택하세요"
|
||||
panel.prompt = "업로드"
|
||||
return panel.runModal() == .OK ? panel.url : nil
|
||||
}
|
||||
|
||||
/// 저장 위치 선택. 취소 시 nil. 사용자가 고른 위치 = 샌드박스 쓰기 권한 부여(files.user-selected).
|
||||
static func pickSaveDestination(suggestedName: String) -> URL? {
|
||||
let panel = NSSavePanel()
|
||||
panel.nameFieldStringValue = suggestedName
|
||||
panel.message = "원본 파일을 저장할 위치"
|
||||
panel.prompt = "저장"
|
||||
return panel.runModal() == .OK ? panel.url : nil
|
||||
}
|
||||
}
|
||||
|
||||
/// 원본 파일 네이티브 다운로드. 인증은 URL 쿼리의 ?token= 으로만 이뤄지므로(헤더 아님), 토큰이 든
|
||||
/// URL 은 절대 로깅/에러 메시지에 노출하지 않는다. 저장 위치는 사용자가 NSSavePanel 로 선택.
|
||||
@MainActor
|
||||
enum FileDownloader {
|
||||
enum Outcome: Equatable {
|
||||
case saved(URL)
|
||||
case cancelled
|
||||
case failed(String)
|
||||
}
|
||||
|
||||
/// `url` = DSDownload.fileURL 로 만든 ?token= 인증 URL. `suggestedName` = 원본 파일명.
|
||||
static func download(from url: URL, suggestedName: String) async -> Outcome {
|
||||
guard let dest = FilePanels.pickSaveDestination(suggestedName: suggestedName) else {
|
||||
return .cancelled
|
||||
}
|
||||
do {
|
||||
let (temp, response) = try await URLSession.shared.download(from: url)
|
||||
// 다운로드된 임시 파일은 호출자 책임(async download 변형은 자동삭제 안 함) — 모든 종료
|
||||
// 경로에서 정리. 성공 시 move 가 temp 를 옮긴 뒤라 removeItem 은 무해한 no-op.
|
||||
defer { try? FileManager.default.removeItem(at: temp) }
|
||||
if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
|
||||
// 상태 코드만 노출 — URL/토큰은 절대 포함하지 않는다.
|
||||
return .failed("다운로드 실패 (HTTP \(http.statusCode))")
|
||||
}
|
||||
if FileManager.default.fileExists(atPath: dest.path) {
|
||||
try FileManager.default.removeItem(at: dest)
|
||||
}
|
||||
try FileManager.default.moveItem(at: temp, to: dest)
|
||||
return .saved(dest)
|
||||
} catch {
|
||||
// URLError/파일 오류의 localizedDescription 엔 URL 이 포함되지 않는다.
|
||||
return .failed("저장 실패: \((error as NSError).localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
import SwiftUI
|
||||
import AIFabric
|
||||
|
||||
/// RAG proof page: routes corpusAsk through AIService (-> AIRouter -> MockAIProvider). Explicit backend
|
||||
/// pick sets explicitProvider; an explicit-unavailable result renders a visible, non-retrying error.
|
||||
struct AskView: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
@State private var backend: BackendChoice = .auto
|
||||
|
||||
var body: some View {
|
||||
@Bindable var model = model
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
Picker("백엔드", selection: $backend) {
|
||||
ForEach(BackendChoice.allCases) { Text($0.label).tag($0) }
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
|
||||
HStack(spacing: 8) {
|
||||
TextField("코퍼스 전체에 질문", text: $model.askQuery)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.onSubmit { Task { await model.runAsk(backend: backend.provider) } }
|
||||
Button("질문") { Task { await model.runAsk(backend: backend.provider) } }
|
||||
.buttonStyle(.borderedProminent)
|
||||
}
|
||||
|
||||
if let result = model.askResult {
|
||||
switch result {
|
||||
case .success(let response):
|
||||
AICompletionView(response: response) { docID in
|
||||
model.section = .documents
|
||||
Task { await model.openDocument(docID) }
|
||||
}
|
||||
if let meta = model.askMeta {
|
||||
HStack(spacing: 6) {
|
||||
Chip("완성도 \(meta.completeness)", Sage.muted)
|
||||
if let aspects = meta.coveredAspects {
|
||||
ForEach(aspects, id: \.self) { Chip($0, Sage.brand) }
|
||||
}
|
||||
}
|
||||
}
|
||||
case .failure(let err):
|
||||
ErrorBanner(text: message(for: err))
|
||||
}
|
||||
} else {
|
||||
EmptyState(text: "질문을 입력하세요").frame(minHeight: 160)
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
.background(Sage.surface)
|
||||
}
|
||||
|
||||
private func message(for error: AIServiceError) -> String {
|
||||
switch error {
|
||||
case .explicitUnavailable(let id):
|
||||
return "\(id.displayName) 백엔드를 쓸 수 없습니다 — 다른 백엔드로 자동 전환하지 않았습니다. 다른 백엔드를 고르세요."
|
||||
case .notConfigured(let id): return "\(id.displayName) 백엔드 미구성"
|
||||
case .noneAvailable: return "응답 가능한 백엔드가 없습니다."
|
||||
case .providerFailed(let s): return "응답 실패: \(s)"
|
||||
case .unknown(let s): return "오류: \(s)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum BackendChoice: String, CaseIterable, Identifiable {
|
||||
case auto, onDevice, localMLX, remoteDS
|
||||
var id: String { rawValue }
|
||||
var label: String {
|
||||
switch self {
|
||||
case .auto: return "자동"
|
||||
case .onDevice: return "온디바이스"
|
||||
case .localMLX: return "맥미니"
|
||||
case .remoteDS: return "원격 DS"
|
||||
}
|
||||
}
|
||||
var provider: AIProviderID? {
|
||||
switch self {
|
||||
case .auto: return nil
|
||||
case .onDevice: return .onDevice
|
||||
case .localMLX: return .localMLX
|
||||
case .remoteDS: return .remoteDS
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,51 +1,386 @@
|
||||
import SwiftUI
|
||||
import DSKit
|
||||
|
||||
/// Corpus-health overview (not a dumped table). Stat hero + domain distribution bars; tapping a
|
||||
/// domain jumps to Documents (cross-page nav proof).
|
||||
/// 홈 = 풀폭 데일리 코크핏 (시안 안1). detail 전폭을 받아 1000pt 캔버스로 좌측 정렬, 내부 2칼럼.
|
||||
/// 인사 → 오늘 스트립(검토 큐 + 속보 + 스탯) → 좌(빠른캡처·최근활동)/우(도메인분포·고정).
|
||||
struct DashboardView: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
ScrollView(.vertical) {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
if let s = model.stats {
|
||||
LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 12)], spacing: 12) {
|
||||
StatCard(title: "전체", value: s.total, color: Sage.brand)
|
||||
StatCard(title: "문서", value: s.counts["document"] ?? 0, color: Sage.brand)
|
||||
StatCard(title: "승인 대기", value: s.libraryPendingSuggestions, color: Sage.amber)
|
||||
}
|
||||
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Text("카테고리 분포").font(.headline).foregroundStyle(Sage.ink)
|
||||
ForEach(s.counts.sorted { $0.value > $1.value }, id: \.key) { key, value in
|
||||
DomainBar(name: Self.categoryLabel(key), count: value, max: s.counts.values.max() ?? 1)
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { model.section = .documents }
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.background(Sage.card, in: RoundedRectangle(cornerRadius: 14))
|
||||
.overlay(RoundedRectangle(cornerRadius: 14).stroke(Sage.line))
|
||||
} else {
|
||||
GreetingHeader()
|
||||
if model.stats == nil && model.tree.isEmpty {
|
||||
ProgressView().frame(maxWidth: .infinity, minHeight: 200)
|
||||
} else {
|
||||
TodayStrip()
|
||||
HStack(alignment: .top, spacing: 18) {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
CaptureCard()
|
||||
ActivityTimeline()
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
DomainDistribution()
|
||||
PinnedItems()
|
||||
}
|
||||
.frame(width: 312)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(maxWidth: 1000, alignment: .leading)
|
||||
.padding(.horizontal, 30)
|
||||
.padding(.vertical, 26)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .topLeading)
|
||||
.background(Sage.surface)
|
||||
}
|
||||
}
|
||||
|
||||
/// 서버 category enum → 표시명 (미등록 키는 raw 노출 — 신규 카테고리 추가에 안전).
|
||||
static func categoryLabel(_ key: String) -> String {
|
||||
switch key {
|
||||
case "document": return "문서"
|
||||
case "library": return "자료실"
|
||||
case "news": return "뉴스"
|
||||
case "law": return "법령"
|
||||
case "memo": return "메모"
|
||||
case "audio": return "오디오"
|
||||
case "video": return "비디오"
|
||||
default: return key
|
||||
// MARK: - Greeting
|
||||
|
||||
private struct GreetingHeader: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 10) {
|
||||
Text("안녕하세요, \(model.currentUser?.username ?? "사용자")")
|
||||
.font(.system(size: 22, weight: .bold)).kerning(-0.4).foregroundStyle(Sage.ink)
|
||||
Text("오늘도 지식 쌓는 날.").font(.callout).foregroundStyle(Sage.muted)
|
||||
}
|
||||
Text(Self.today).font(.caption).foregroundStyle(Sage.muted.opacity(0.8))
|
||||
}
|
||||
.padding(.bottom, 4)
|
||||
}
|
||||
|
||||
static var today: String {
|
||||
let f = DateFormatter()
|
||||
f.locale = Locale(identifier: "ko_KR")
|
||||
f.dateFormat = "y년 M월 d일 EEEE"
|
||||
return f.string(from: Date())
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Today strip (hero)
|
||||
|
||||
private struct TodayStrip: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 14) {
|
||||
HStack(alignment: .top, spacing: 0) {
|
||||
reviewQueue
|
||||
.frame(minWidth: 150, alignment: .leading)
|
||||
Rectangle().fill(Sage.line).frame(width: 1).padding(.horizontal, 22)
|
||||
digestTeaser
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
Divider().overlay(Sage.line)
|
||||
statRow
|
||||
}
|
||||
.dashCard(padding: 20)
|
||||
}
|
||||
|
||||
private var reviewQueue: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(model.reviewPendingCount.map(String.init) ?? "—")
|
||||
.font(.system(size: 38, weight: .bold)).kerning(-1.5).monospacedDigit()
|
||||
.foregroundStyle(Sage.amber)
|
||||
Text("검토 대기 문서").font(.caption).foregroundStyle(Sage.muted)
|
||||
Button { model.section = .documents } label: {
|
||||
Text("검토 시작 →").font(.caption.weight(.semibold)).foregroundStyle(Sage.brand)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder private var digestTeaser: some View {
|
||||
if let t = topTopic {
|
||||
Button { model.section = .digest } label: {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack(spacing: 8) {
|
||||
Chip("속보", Sage.danger)
|
||||
Text("\(model.digest?.digestDateDisplay ?? "") 브리핑")
|
||||
.font(.caption2).foregroundStyle(Sage.muted)
|
||||
}
|
||||
Text(t.label).font(.system(size: 15)).foregroundStyle(Sage.ink)
|
||||
.lineLimit(2).fixedSize(horizontal: false, vertical: true)
|
||||
.multilineTextAlignment(.leading)
|
||||
Text(t.meta).font(.caption2).foregroundStyle(Sage.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
} else {
|
||||
Text("오늘 브리핑이 아직 없습니다").font(.callout).foregroundStyle(Sage.muted)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private var statRow: some View {
|
||||
HStack(spacing: 0) {
|
||||
StatCell(value: model.stats?.total ?? 0, label: "전체", color: Sage.brand)
|
||||
StatCell(value: model.stats?.counts["document"] ?? 0, label: "문서")
|
||||
StatCell(value: domainCount("Industrial_Safety"), label: "산업안전",
|
||||
color: Sage.domainColor("Industrial_Safety"))
|
||||
StatCell(value: domainCount("Engineering"), label: "엔지니어링",
|
||||
color: Sage.domainColor("Engineering"))
|
||||
StatCell(value: domainCount("General"), label: "자료실", color: Sage.domainColor("General"))
|
||||
StatCell(value: model.stats?.counts["memo"] ?? model.memoList.count, label: "메모")
|
||||
}
|
||||
}
|
||||
|
||||
private func domainCount(_ name: String) -> Int {
|
||||
model.tree.first { $0.name == name }?.count ?? 0
|
||||
}
|
||||
|
||||
private var topTopic: (label: String, meta: String)? {
|
||||
guard let digest = model.digest else { return nil }
|
||||
var best: (TopicResponse, String)?
|
||||
for c in digest.countries {
|
||||
for t in c.topics where best == nil || (t.importanceScore ?? 0) > (best!.0.importanceScore ?? 0) {
|
||||
best = (t, c.country)
|
||||
}
|
||||
}
|
||||
guard let (t, country) = best else { return nil }
|
||||
let arts = t.articleCount ?? t.articles.count
|
||||
var meta = "관련 기사 \(arts)건"
|
||||
if let imp = t.importanceScore { meta += " · 중요도 \(String(format: "%.0f", imp))" }
|
||||
if !country.isEmpty { meta += " · \(country)" }
|
||||
return (t.topicLabel, meta)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Left column
|
||||
|
||||
private struct CaptureCard: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
@Bindable var m = model
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
SectionLabel("빠른 캡처")
|
||||
HStack(spacing: 8) {
|
||||
TextField("메모 한 줄 남기기…", text: $m.captureText)
|
||||
.textFieldStyle(.plain)
|
||||
.padding(.horizontal, 14).frame(height: 38)
|
||||
.background(Sage.surface, in: RoundedRectangle(cornerRadius: 8))
|
||||
.overlay(RoundedRectangle(cornerRadius: 8).stroke(Sage.line))
|
||||
.onSubmit { Task { await model.saveMemo() } }
|
||||
Button { Task { await model.saveMemo() } } label: {
|
||||
Text("저장").font(.callout.weight(.semibold)).foregroundStyle(.white)
|
||||
.padding(.horizontal, 18).frame(height: 38)
|
||||
.background(Sage.brand, in: RoundedRectangle(cornerRadius: 8))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.disabled(model.captureText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
Button {
|
||||
guard let url = FilePanels.pickFileToUpload() else { return }
|
||||
Task { await model.uploadPicked(url) }
|
||||
} label: {
|
||||
Text("+ 파일 업로드").font(.caption.weight(.semibold)).foregroundStyle(Sage.brand)
|
||||
.padding(.horizontal, 10).padding(.vertical, 5)
|
||||
.background(Sage.brand.opacity(0.12), in: Capsule())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.dashCard()
|
||||
}
|
||||
}
|
||||
|
||||
private struct ActivityTimeline: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
private var recent: [DocumentResponse] {
|
||||
model.documentList
|
||||
.sorted { ($0.updatedAt ?? .distantPast) > ($1.updatedAt ?? .distantPast) }
|
||||
.prefix(5).map { $0 }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack(alignment: .firstTextBaseline) {
|
||||
SectionLabel("최근 활동")
|
||||
Spacer()
|
||||
Button { model.section = .documents } label: {
|
||||
Text("전체 보기 →").font(.caption.weight(.semibold)).foregroundStyle(Sage.brand)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
if recent.isEmpty {
|
||||
Text("최근 활동이 없습니다").font(.caption).foregroundStyle(Sage.muted)
|
||||
} else {
|
||||
VStack(spacing: 0) {
|
||||
ForEach(Array(recent.enumerated()), id: \.element.id) { idx, doc in
|
||||
ActivityRow(doc: doc, isLast: idx == recent.count - 1)
|
||||
if idx != recent.count - 1 { Divider().overlay(Sage.line) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.dashCard()
|
||||
}
|
||||
}
|
||||
|
||||
private struct ActivityRow: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
let doc: DocumentResponse
|
||||
let isLast: Bool
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .top, spacing: 12) {
|
||||
Text(Self.relative(doc.updatedAt))
|
||||
.font(.caption2).foregroundStyle(Sage.muted)
|
||||
.frame(width: 54, alignment: .trailing)
|
||||
VStack(spacing: 0) {
|
||||
Circle().fill(Sage.domainColor(doc.aiDomain)).frame(width: 8, height: 8).padding(.top, 4)
|
||||
if !isLast { Rectangle().fill(Sage.line).frame(width: 1).frame(maxHeight: .infinity) }
|
||||
}
|
||||
.frame(width: 14)
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text("\(localizedDomain(doc.aiDomain)) · \(doc.displayFormat.uppercased())")
|
||||
.font(.caption2.weight(.bold)).foregroundStyle(Sage.domainColor(doc.aiDomain))
|
||||
Text(doc.title ?? doc.downloadLabel).font(.callout).foregroundStyle(Sage.ink).lineLimit(2)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.bottom, isLast ? 0 : 10)
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { model.section = .documents; Task { await model.openDocument(doc.id) } }
|
||||
}
|
||||
|
||||
static func relative(_ date: Date?) -> String {
|
||||
guard let date else { return "" }
|
||||
let f = RelativeDateTimeFormatter()
|
||||
f.locale = Locale(identifier: "ko_KR")
|
||||
f.unitsStyle = .short
|
||||
return f.localizedString(for: date, relativeTo: Date())
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Right column
|
||||
|
||||
private struct DomainDistribution: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
private var domains: [DomainTreeNode] { model.tree.sorted { $0.count > $1.count } }
|
||||
private var domainTotal: Int { domains.reduce(0) { $0 + $1.count } }
|
||||
private var sum: Int { max(1, domainTotal) } // 0-나눗셈 가드 (막대 폭 분모 전용)
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
SectionLabel("도메인 분포")
|
||||
// 헤드라인 합계 = 막대/범례와 동일 분모(도메인 트리 합) — 사용자가 범례를 더해 같은 값에 도달.
|
||||
HStack(alignment: .firstTextBaseline, spacing: 3) {
|
||||
Text("분류").font(.caption).foregroundStyle(Sage.muted)
|
||||
Text("\(domainTotal)").font(.system(size: 18, weight: .semibold))
|
||||
.monospacedDigit().foregroundStyle(Sage.ink)
|
||||
Text("건").font(.caption).foregroundStyle(Sage.muted)
|
||||
}
|
||||
GeometryReader { geo in
|
||||
HStack(spacing: 2) {
|
||||
ForEach(domains) { d in
|
||||
Rectangle().fill(Sage.domainColor(d.name))
|
||||
.frame(width: max(2, geo.size.width * CGFloat(d.count) / CGFloat(sum)))
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(height: 8)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 4))
|
||||
VStack(spacing: 7) {
|
||||
ForEach(domains) { d in
|
||||
Button {
|
||||
model.section = .documents
|
||||
Task { await model.loadDocuments(domain: d.path) }
|
||||
} label: {
|
||||
HStack(spacing: 8) {
|
||||
RoundedRectangle(cornerRadius: 2).fill(Sage.domainColor(d.name)).frame(width: 10, height: 10)
|
||||
Text(localizedDomain(d.name)).font(.caption).foregroundStyle(Sage.ink)
|
||||
.lineLimit(1).frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text("\(d.count)").font(.caption.monospacedDigit()).foregroundStyle(Sage.muted)
|
||||
}
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.dashCard()
|
||||
}
|
||||
}
|
||||
|
||||
private struct PinnedItems: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
private var docs: [DocumentResponse] { model.documentList.filter { $0.pinned == true } }
|
||||
private var memos: [MemoResponse] { model.memoList.filter { $0.isPinned } }
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
SectionLabel("고정 항목")
|
||||
Spacer()
|
||||
Button { model.section = .documents } label: {
|
||||
Text("관리 →").font(.caption.weight(.semibold)).foregroundStyle(Sage.brand)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
if docs.isEmpty && memos.isEmpty {
|
||||
Text("고정된 항목이 없습니다").font(.caption).foregroundStyle(Sage.muted)
|
||||
} else {
|
||||
VStack(spacing: 8) {
|
||||
ForEach(docs) { d in
|
||||
PinRow(kind: "문서", kindColor: Sage.domainColor("Engineering"),
|
||||
title: d.title ?? d.downloadLabel, date: d.updatedAtRaw) {
|
||||
model.section = .documents; Task { await model.openDocument(d.id) }
|
||||
}
|
||||
}
|
||||
ForEach(memos) { m in
|
||||
PinRow(kind: "메모", kindColor: Sage.brand,
|
||||
title: m.title ?? (m.content ?? "메모"), date: m.updatedAtRaw ?? "") {
|
||||
model.section = .memos; Task { await model.openMemo(m.id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.dashCard()
|
||||
}
|
||||
}
|
||||
|
||||
private struct PinRow: View {
|
||||
let kind: String
|
||||
let kindColor: Color
|
||||
let title: String
|
||||
let date: String
|
||||
let action: () -> Void
|
||||
|
||||
var body: some View {
|
||||
Button(action: action) {
|
||||
HStack(alignment: .top, spacing: 10) {
|
||||
Chip(kind, kindColor)
|
||||
Text(title).font(.caption).foregroundStyle(Sage.ink).lineLimit(2)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text(date.prefix(10)).font(.caption2.monospacedDigit()).foregroundStyle(Sage.muted)
|
||||
}
|
||||
.padding(10)
|
||||
.background(Sage.surface, in: RoundedRectangle(cornerRadius: 8))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
#Preview("Dashboard") {
|
||||
@Previewable @State var model = AppModel.preview
|
||||
DashboardView()
|
||||
.environment(model)
|
||||
.frame(width: 1100, height: 760)
|
||||
.task { await model.bootstrap() }
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1,91 +1,367 @@
|
||||
import SwiftUI
|
||||
import DSKit
|
||||
|
||||
struct DocumentListView: View {
|
||||
/// 문서 = DEVONthink식 컬럼 브라우저. 소스트리(분류)는 글로벌 사이드바에 있고, 이 페이지는 detail
|
||||
/// 전폭 안에서 내부 HSplitView 3-pane = 컬럼 리스트 | MD 리더 | 인스펙터(토글). 도메인 필터는
|
||||
/// 사이드바가 model.loadDocuments(domain:) 로 서버 재조회.
|
||||
struct DocumentsBrowser: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
@State private var showInspector = true
|
||||
@State private var sortOrder = [KeyPathComparator(\DocumentResponse.sortUpdated, order: .reverse)]
|
||||
|
||||
var body: some View {
|
||||
HSplitView {
|
||||
DocumentListTable(sortOrder: $sortOrder)
|
||||
.frame(minWidth: 300, idealWidth: 360, maxWidth: 460)
|
||||
DocumentReader(showInspector: $showInspector)
|
||||
.frame(minWidth: 420, maxWidth: .infinity)
|
||||
if showInspector, let d = model.documentDetail {
|
||||
DocumentInspector(detail: d)
|
||||
.frame(minWidth: 280, idealWidth: 320, maxWidth: 360)
|
||||
}
|
||||
}
|
||||
.task { await model.ensureDocumentsLoaded() } // 진입 시 현재 필터 전체 문서 load-all
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Column list (sortable Table)
|
||||
|
||||
private extension DocumentResponse {
|
||||
var sortTitle: String { title ?? downloadLabel }
|
||||
var sortFormat: String { (originalFormat ?? fileFormat ?? "").lowercased() }
|
||||
var sortUpdated: String { updatedAtRaw }
|
||||
/// "PDF→MD" / "MD" 식 종류 배지 라벨.
|
||||
var formatBadge: String {
|
||||
if let orig = originalFormat, orig.lowercased() != (fileFormat ?? "").lowercased() {
|
||||
return "\(orig.uppercased())→MD"
|
||||
}
|
||||
return displayFormat.uppercased()
|
||||
}
|
||||
}
|
||||
|
||||
struct DocumentListTable: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
@Binding var sortOrder: [KeyPathComparator<DocumentResponse>]
|
||||
|
||||
private var documents: [DocumentResponse] { model.documentList.sorted(using: sortOrder) }
|
||||
|
||||
var body: some View {
|
||||
let selection = Binding<Int?>(
|
||||
get: { model.selectedDocumentID },
|
||||
set: { if let id = $0 { Task { await model.openDocument(id) } } }
|
||||
)
|
||||
List(model.documentList, selection: selection) { doc in
|
||||
DocumentRow(doc: doc)
|
||||
}
|
||||
.listStyle(.inset)
|
||||
.background(Sage.surface)
|
||||
}
|
||||
}
|
||||
|
||||
struct DocumentRow: View {
|
||||
let doc: DocumentResponse
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack(spacing: 6) {
|
||||
Chip(doc.displayFormat.uppercased(), Sage.formatColor(doc.displayFormat))
|
||||
Text(doc.title ?? doc.downloadLabel)
|
||||
.font(.callout.weight(.medium)).foregroundStyle(Sage.ink).lineLimit(1)
|
||||
Spacer()
|
||||
if doc.pinned == true { Text("고정").font(.caption2).foregroundStyle(Sage.amber) }
|
||||
}
|
||||
HStack(spacing: 6) {
|
||||
if let d = doc.aiDomain { Chip(d, Sage.domainColor(d)) }
|
||||
if let r = doc.reviewStatus {
|
||||
Text(r).font(.caption2).foregroundStyle(Sage.reviewStatusColor(r))
|
||||
Group {
|
||||
if model.documentList.isEmpty {
|
||||
EmptyState(text: "문서가 없습니다")
|
||||
} else {
|
||||
Table(documents, selection: selection, sortOrder: $sortOrder) {
|
||||
TableColumn("제목", value: \.sortTitle) { doc in
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(doc.title ?? doc.downloadLabel)
|
||||
.font(.system(size: 12.5, weight: .semibold)).foregroundStyle(Sage.ink).lineLimit(1)
|
||||
Text(localizedDomain(doc.aiDomain))
|
||||
.font(.system(size: 11)).foregroundStyle(Sage.muted).lineLimit(1)
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
TableColumn("종류", value: \.sortFormat) { doc in
|
||||
Chip(doc.formatBadge, Sage.formatColor(doc.originalFormat ?? doc.displayFormat))
|
||||
}
|
||||
.width(min: 66, ideal: 74, max: 96)
|
||||
TableColumn("수정", value: \.sortUpdated) { doc in
|
||||
Text(doc.updatedAtRaw.prefix(10))
|
||||
.font(.caption2.monospacedDigit()).foregroundStyle(Sage.muted)
|
||||
}
|
||||
.width(min: 78, ideal: 86, max: 110)
|
||||
}
|
||||
Spacer()
|
||||
Text(doc.updatedAtRaw.prefix(10)).font(.caption2.monospacedDigit()).foregroundStyle(Sage.muted)
|
||||
.tint(Sage.brand)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
.background(Sage.card)
|
||||
}
|
||||
}
|
||||
|
||||
/// MD-first detail: render md_content when renderable, else extracted_text fallback + 'MD 변환 대기'
|
||||
/// badge + emphasized original-download button. (Download builds a real-shaped ?token= URL.)
|
||||
struct DocumentDetailView: View {
|
||||
// MARK: - Reader
|
||||
|
||||
struct DocumentReader: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
@Binding var showInspector: Bool
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if let detail = model.documentDetail {
|
||||
VStack(spacing: 0) {
|
||||
ReaderHeader(detail: detail, showInspector: $showInspector)
|
||||
ReaderBody(detail: detail)
|
||||
}
|
||||
} else {
|
||||
EmptyState(text: "문서를 선택하세요")
|
||||
}
|
||||
}
|
||||
.background(Sage.card)
|
||||
}
|
||||
}
|
||||
|
||||
private struct ReaderHeader: View {
|
||||
let detail: DocumentDetailResponse
|
||||
@Binding var showInspector: Bool
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(crumb).font(.system(size: 11)).foregroundStyle(Sage.muted).lineLimit(1)
|
||||
HStack(alignment: .firstTextBaseline, spacing: 10) {
|
||||
Text(detail.base.title ?? detail.base.downloadLabel)
|
||||
.font(.system(size: 18, weight: .heavy)).foregroundStyle(Sage.ink).lineLimit(2)
|
||||
Spacer()
|
||||
DownloadButton(doc: detail.base, compact: true)
|
||||
inspectorToggle
|
||||
}
|
||||
metaBadges
|
||||
tagRow
|
||||
}
|
||||
.padding(.horizontal, 26).padding(.vertical, 14)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(Sage.card)
|
||||
.overlay(alignment: .bottom) { Rectangle().fill(Sage.line).frame(height: 1) }
|
||||
}
|
||||
|
||||
private var crumb: String {
|
||||
let dom = localizedDomain(detail.base.aiDomain)
|
||||
if let sub = detail.base.aiSubGroup, !sub.isEmpty { return "\(dom) › \(sub)" }
|
||||
return dom
|
||||
}
|
||||
|
||||
/// 웹 상세 페이지 헤더 배지: 도메인 · 문서유형 · tier DEEP · 신뢰도 · PDF→MD success.
|
||||
@ViewBuilder private var metaBadges: some View {
|
||||
let b = detail.base
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
HStack(spacing: 6) {
|
||||
if let d = b.aiDomain { Chip(localizedDomain(d), Sage.domainColor(d)) }
|
||||
if let t = b.documentType, !t.isEmpty { Chip(t, Sage.muted) }
|
||||
if b.aiAnalysisTier == "deep" { Chip("tier DEEP", Sage.brand) }
|
||||
if let c = b.aiConfidence { Chip("신뢰도 \(String(format: "%.2f", c))", Sage.brandDark) }
|
||||
if detail.mdIsRenderable { Chip("PDF→MD success", Sage.mdStatusColor("completed")) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var inspectorToggle: some View {
|
||||
Button { withAnimation(.easeInOut(duration: 0.2)) { showInspector.toggle() } } label: {
|
||||
Image(systemName: "info.circle").font(.system(size: 15))
|
||||
.foregroundStyle(showInspector ? Sage.brandDark : Sage.muted)
|
||||
.frame(width: 30, height: 30)
|
||||
.background(showInspector ? Sage.brand.opacity(0.14) : Sage.card, in: RoundedRectangle(cornerRadius: 8))
|
||||
.overlay(RoundedRectangle(cornerRadius: 8).stroke(showInspector ? Sage.brand : Sage.line))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("인스펙터")
|
||||
}
|
||||
|
||||
@ViewBuilder private var tagRow: some View {
|
||||
let tags = detail.base.aiTags ?? []
|
||||
if detail.mdStatus != nil || !tags.isEmpty {
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
HStack(spacing: 6) {
|
||||
if let st = detail.mdStatus { Chip("MD \(st)", Sage.mdStatusColor(st)) }
|
||||
ForEach(tags, id: \.self) { Chip($0, Sage.brand) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ReaderBody: View {
|
||||
let detail: DocumentDetailResponse
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
Text(detail.base.title ?? detail.base.downloadLabel)
|
||||
.font(.title2.weight(.bold)).foregroundStyle(Sage.ink)
|
||||
|
||||
HStack(spacing: 8) {
|
||||
if let d = detail.base.aiDomain { Chip(d, Sage.domainColor(d)) }
|
||||
Chip(detail.base.displayFormat.uppercased(), Sage.formatColor(detail.base.displayFormat))
|
||||
if let conf = detail.base.aiConfidence {
|
||||
Chip("AI \(String(format: "%.0f%%", conf * 100))", Sage.muted)
|
||||
}
|
||||
Spacer()
|
||||
if let url = model.downloadURL(for: detail.base) {
|
||||
Link(detail.base.downloadLabel, destination: url).font(.callout.weight(.semibold))
|
||||
}
|
||||
}
|
||||
|
||||
if let tags = detail.base.aiTags, !tags.isEmpty {
|
||||
HStack(spacing: 6) { ForEach(tags, id: \.self) { Chip($0, Sage.brand) } }
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
if detail.mdIsRenderable, let md = detail.mdContent {
|
||||
MarkdownView(md)
|
||||
} else {
|
||||
HStack { Chip("MD 변환 대기", Sage.amber); Spacer() }
|
||||
Text(detail.extractedText ?? "본문 없음")
|
||||
.font(.body).foregroundStyle(Sage.muted)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
if let url = model.downloadURL(for: detail.base) {
|
||||
Link("원본 다운로드 — \(detail.base.downloadLabel)", destination: url)
|
||||
.font(.callout.weight(.semibold))
|
||||
HStack(spacing: 0) {
|
||||
Spacer(minLength: 0)
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
if detail.mdIsRenderable, let md = detail.mdContent {
|
||||
MarkdownView(md)
|
||||
} else {
|
||||
HStack { Chip("MD 변환 대기", Sage.amber); Spacer() }
|
||||
Text(detail.extractedText ?? "본문 없음")
|
||||
.font(.body).foregroundStyle(Sage.muted)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
DownloadButton(doc: detail.base, compact: false)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: 700, alignment: .leading)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.padding(.horizontal, 28).padding(.top, 22).padding(.bottom, 44)
|
||||
}
|
||||
.background(Sage.card)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Inspector
|
||||
|
||||
struct DocumentInspector: View {
|
||||
let detail: DocumentDetailResponse
|
||||
|
||||
private var base: DocumentResponse { detail.base }
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
// 인사이트 (웹 상세 페이지 양식: TL;DR · 핵심점 · 심층 · 불일치)
|
||||
if let tldr = (base.aiTldr ?? base.aiSummary), !tldr.isEmpty {
|
||||
InspectorSection("TL;DR") {
|
||||
Text(tldr).font(.system(size: 12)).foregroundStyle(Sage.ink).lineSpacing(2)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
if let bullets = base.aiBullets, !bullets.isEmpty {
|
||||
InspectorSection("핵심점") {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
ForEach(bullets, id: \.self) { b in
|
||||
HStack(alignment: .top, spacing: 6) {
|
||||
Text("·").font(.system(size: 12, weight: .bold)).foregroundStyle(Sage.amber)
|
||||
Text(b).font(.system(size: 12)).foregroundStyle(Sage.ink)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let deep = base.aiDetailSummary, !deep.isEmpty {
|
||||
InspectorSection("심층") {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
if base.aiAnalysisTier == "deep" { Chip("DEEP", Sage.brand) }
|
||||
Text(deep).font(.system(size: 11.5)).foregroundStyle(Sage.ink).lineSpacing(2)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
if let inc = base.aiInconsistencies, !inc.isEmpty {
|
||||
InspectorSection("불일치 \(inc.count)") {
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
ForEach(inc, id: \.self) { x in
|
||||
Text("· \(x)").font(.system(size: 11.5)).foregroundStyle(Sage.ink)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 정보
|
||||
InspectorSection("정보") {
|
||||
VStack(spacing: 0) {
|
||||
KV("종류", base.formatBadge)
|
||||
KV("도메인", localizedDomain(base.aiDomain))
|
||||
KV("하위", base.aiSubGroup ?? "—")
|
||||
KV("수정", String(base.updatedAtRaw.prefix(10)))
|
||||
if let size = base.fileSize {
|
||||
KV("원본", ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file))
|
||||
}
|
||||
if let st = detail.mdStatus { KV("md 상태", st, color: Sage.mdStatusColor(st)) }
|
||||
if let tier = base.aiAnalysisTier { KV("tier", tier, color: Sage.brandDark) }
|
||||
if let c = base.aiConfidence { KV("신뢰도", String(format: "%.2f", c), color: Sage.brand) }
|
||||
KV("읽음", "\(base.reads)회")
|
||||
}
|
||||
}
|
||||
if let tags = base.aiTags, !tags.isEmpty {
|
||||
InspectorSection("태그") { TagWrap(tags: tags) }
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 16).padding(.vertical, 18)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(Sage.sidebar)
|
||||
.overlay(alignment: .leading) { Rectangle().fill(Sage.line).frame(width: 1) }
|
||||
}
|
||||
}
|
||||
|
||||
private struct InspectorSection<Content: View>: View {
|
||||
let title: String
|
||||
@ViewBuilder let content: Content
|
||||
init(_ title: String, @ViewBuilder content: () -> Content) { self.title = title; self.content = content() }
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text(title).font(.system(size: 10, weight: .heavy)).tracking(0.8)
|
||||
.textCase(.uppercase).foregroundStyle(Sage.muted.opacity(0.8))
|
||||
content
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private struct KV: View {
|
||||
let k: String
|
||||
let v: String
|
||||
var color: Color = Sage.ink
|
||||
init(_ k: String, _ v: String, color: Color = Sage.ink) { self.k = k; self.v = v; self.color = color }
|
||||
var body: some View {
|
||||
HStack {
|
||||
Text(k).font(.system(size: 12)).foregroundStyle(Sage.muted)
|
||||
Spacer()
|
||||
Text(v).font(.system(size: 12, weight: .semibold)).foregroundStyle(color)
|
||||
.multilineTextAlignment(.trailing)
|
||||
}
|
||||
.padding(.vertical, 3)
|
||||
}
|
||||
}
|
||||
|
||||
/// 좁은 인스펙터용 태그 줄바꿈 (2개씩 한 줄 — 커스텀 Layout 없이 결정적).
|
||||
private struct TagWrap: View {
|
||||
let tags: [String]
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
ForEach(Array(stride(from: 0, to: tags.count, by: 2)), id: \.self) { i in
|
||||
HStack(spacing: 6) {
|
||||
Chip(tags[i], Sage.brand)
|
||||
if i + 1 < tags.count { Chip(tags[i + 1], Sage.brand) }
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Native download button (preserved)
|
||||
|
||||
/// 원본 파일 네이티브 다운로드 버튼. ?token= 인증 URL 을 NSSavePanel 로 고른 위치에 저장(브라우저
|
||||
/// 핸드오프 아님). 진행 스피너 + 저장 결과/오류를 인라인 표시. note 문서는 다운로드 대상 없음 → 숨김.
|
||||
struct DownloadButton: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
let doc: DocumentResponse
|
||||
/// compact = 헤더용 짧은 라벨(파일명만) / false = 본문 폴백용 긴 라벨.
|
||||
var compact: Bool
|
||||
|
||||
@State private var busy = false
|
||||
@State private var status: String?
|
||||
@State private var isError = false
|
||||
|
||||
var body: some View {
|
||||
if let url = model.downloadURL(for: doc) {
|
||||
HStack(spacing: 8) {
|
||||
Button {
|
||||
Task {
|
||||
busy = true; status = nil; isError = false
|
||||
let outcome = await FileDownloader.download(from: url, suggestedName: doc.downloadLabel)
|
||||
busy = false
|
||||
switch outcome {
|
||||
case .saved(let dest): status = "저장됨: \(dest.lastPathComponent)"; isError = false
|
||||
case .cancelled: status = nil
|
||||
case .failed(let msg): status = msg; isError = true
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
Label(compact ? doc.downloadLabel : "원본 다운로드 — \(doc.downloadLabel)",
|
||||
systemImage: "arrow.down.circle")
|
||||
.font(.callout.weight(.semibold))
|
||||
}
|
||||
.buttonStyle(.borderless)
|
||||
.disabled(busy)
|
||||
if busy { ProgressView().controlSize(.small) }
|
||||
if let s = status {
|
||||
Text(s).font(.caption)
|
||||
.foregroundStyle(isError ? Sage.danger : Sage.muted)
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
}
|
||||
.background(Sage.surface)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,11 +13,10 @@ struct MemoListView: View {
|
||||
.textFieldStyle(.roundedBorder)
|
||||
Button("저장") {
|
||||
let content = draft
|
||||
draft = ""
|
||||
Task { _ = try? await model.client.createMemo(MemoCreate(content: content)) }
|
||||
Task { if await model.saveMemo(content) { draft = "" } }
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.disabled(draft.isEmpty)
|
||||
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
.padding(12)
|
||||
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import SwiftUI
|
||||
import DSKit
|
||||
|
||||
/// Distinct from the Documents table: relevance-forward result cards (score bar + match_reason).
|
||||
struct SearchView: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
@Bindable var model = model
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack(spacing: 8) {
|
||||
TextField("검색어를 입력하세요", text: $model.searchQuery)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.onSubmit { Task { await model.runSearch() } }
|
||||
Button("검색") { Task { await model.runSearch() } }
|
||||
.buttonStyle(.borderedProminent)
|
||||
}
|
||||
.padding(12)
|
||||
|
||||
if let response = model.searchResponse {
|
||||
List(response.results) { result in
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
HStack(spacing: 6) {
|
||||
if let d = result.aiDomain { Chip(d, Sage.domainColor(d)) }
|
||||
Text(result.title ?? "문서 \(result.id)")
|
||||
.font(.callout.weight(.medium)).foregroundStyle(Sage.ink).lineLimit(1)
|
||||
Spacer()
|
||||
if let m = result.matchReason {
|
||||
Text(m).font(.caption2).foregroundStyle(Sage.muted)
|
||||
}
|
||||
}
|
||||
Text(result.snippet ?? result.aiSummary ?? "")
|
||||
.font(.caption).foregroundStyle(Sage.muted).lineLimit(2)
|
||||
if let score = result.score { ScoreBar(score: score) }
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture {
|
||||
model.section = .documents
|
||||
Task { await model.openDocument(result.id) }
|
||||
}
|
||||
}
|
||||
.listStyle(.inset)
|
||||
} else {
|
||||
EmptyState(text: "검색어를 입력하세요")
|
||||
}
|
||||
}
|
||||
.background(Sage.surface)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,58 @@
|
||||
import SwiftUI
|
||||
|
||||
/// 도메인 raw 값(영문/한자 enum 키) → 한글 표시 라벨. 색은 Sage.domainColor(raw) 가 raw 로 키잉하므로
|
||||
/// 색에는 raw, 표시에만 이 라벨을 쓴다. 미매핑은 원본 그대로.
|
||||
func localizedDomain(_ raw: String?) -> String {
|
||||
guard let raw, !raw.isEmpty else { return "미분류" }
|
||||
// 경로형(Philosophy/Aesthetics)이면 leaf 만 매핑 시도, 없으면 leaf 원본
|
||||
let leaf = raw.split(separator: "/").last.map(String.init) ?? raw
|
||||
let map: [String: String] = [
|
||||
"Engineering": "엔지니어링", "Industrial_Safety": "산업안전", "General": "자료실",
|
||||
"Programming": "프로그래밍", "법령": "법령", "Philosophy": "철학",
|
||||
]
|
||||
return map[raw] ?? map[leaf] ?? leaf
|
||||
}
|
||||
|
||||
/// 카드/섹션 머리말 라벨 (대문자·heavy·muted) — 대시보드/인스펙터 공용.
|
||||
struct SectionLabel: View {
|
||||
let text: String
|
||||
init(_ text: String) { self.text = text }
|
||||
var body: some View {
|
||||
Text(text)
|
||||
.font(.caption.weight(.heavy))
|
||||
.textCase(.uppercase)
|
||||
.kerning(0.7)
|
||||
.foregroundStyle(Sage.muted)
|
||||
}
|
||||
}
|
||||
|
||||
/// 공용 카드 크롬 (Sage.card + corner 12 + Sage.line stroke + 패딩).
|
||||
struct DashCard: ViewModifier {
|
||||
var padding: CGFloat = 18
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
.padding(padding)
|
||||
.background(Sage.card, in: RoundedRectangle(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(Sage.line))
|
||||
}
|
||||
}
|
||||
extension View { func dashCard(padding: CGFloat = 18) -> some View { modifier(DashCard(padding: padding)) } }
|
||||
|
||||
/// 보더리스 인라인 통계 셀 (대시보드 스탯 스트립). StatCard 와 달리 카드 테두리 없음.
|
||||
struct StatCell: View {
|
||||
let value: Int
|
||||
let label: String
|
||||
var color: Color = Sage.ink
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text("\(value)").font(.system(size: 20, weight: .semibold)).kerning(-0.6)
|
||||
.monospacedDigit().foregroundStyle(color)
|
||||
Text(label).font(.caption2).foregroundStyle(Sage.muted)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
struct StatCard: View {
|
||||
let title: String
|
||||
let value: Int
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import SwiftUI
|
||||
import DSKit
|
||||
|
||||
/// DEVONthink-style 3-column shell. RootView only ROUTES; each page owns its own interior treatment
|
||||
/// (no shell-level auto-inherit). macOS-only target.
|
||||
/// 인증 게이트: checking(부팅 시 refresh 쿠키 복귀 시도) → loggedOut(LoginView) → ready(3-pane 셸).
|
||||
/// 2-column 셸 (사이드바 + 단일 detail). 각 섹션이 detail 전폭을 받아 자기 내부 레이아웃을 소유한다
|
||||
/// (개요=풀폭 캔버스 / 문서=내부 HSplitView 3-pane / 메모=리스트+상세). 이전 3-column 이 대시보드를
|
||||
/// 좁은 가운데칸에 욱여넣어 깨지던 문제를 구조적으로 제거. macOS-only.
|
||||
/// 인증 게이트: checking(refresh 쿠키 복귀) → loggedOut(LoginView) → ready(셸).
|
||||
public struct RootView: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
@State private var columnVisibility: NavigationSplitViewVisibility = .all
|
||||
@@ -29,38 +30,45 @@ public struct RootView: View {
|
||||
private var shell: some View {
|
||||
NavigationSplitView(columnVisibility: $columnVisibility) {
|
||||
Sidebar()
|
||||
.navigationSplitViewColumnWidth(min: 220, ideal: 250)
|
||||
} content: {
|
||||
ContentColumn()
|
||||
.navigationSplitViewColumnWidth(min: 300, ideal: 380)
|
||||
.navigationSplitViewColumnWidth(min: 200, ideal: 215, max: 270)
|
||||
} detail: {
|
||||
DetailColumn()
|
||||
SectionDetail()
|
||||
}
|
||||
.navigationSplitViewStyle(.balanced)
|
||||
.tint(Sage.brand)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .primaryAction) { UploadToolbarButton() }
|
||||
ToolbarItem(placement: .primaryAction) { AccountMenu() }
|
||||
}
|
||||
.safeAreaInset(edge: .bottom) {
|
||||
// 라이브 데이터 호출 실패 가시화 (no-silent-fallback) — 닫기 전까지 유지.
|
||||
if let err = model.errorText {
|
||||
HStack(spacing: 10) {
|
||||
Text(err)
|
||||
.font(.callout)
|
||||
.foregroundStyle(.white)
|
||||
.lineLimit(2)
|
||||
Spacer()
|
||||
Button("닫기") { model.errorText = nil }
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(.white.opacity(0.85))
|
||||
VStack(spacing: 0) {
|
||||
UploadStatusBar()
|
||||
// 라이브 데이터 호출 실패 가시화 (no-silent-fallback) — 닫기 전까지 유지.
|
||||
if let err = model.errorText {
|
||||
HStack(spacing: 10) {
|
||||
Text(err)
|
||||
.font(.callout)
|
||||
.foregroundStyle(.white)
|
||||
.lineLimit(2)
|
||||
Spacer()
|
||||
Button("닫기") { model.errorText = nil }
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(.white.opacity(0.85))
|
||||
}
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.vertical, 8)
|
||||
.background(Sage.danger)
|
||||
}
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.vertical, 8)
|
||||
.background(Sage.danger)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sidebar
|
||||
|
||||
struct Sidebar: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
private let navSections: [AppModel.Section] = [.dashboard, .documents, .digest, .memos]
|
||||
|
||||
var body: some View {
|
||||
let selection = Binding<AppModel.Section?>(
|
||||
@@ -68,73 +76,132 @@ struct Sidebar: View {
|
||||
set: { if let v = $0 { model.section = v } }
|
||||
)
|
||||
List(selection: selection) {
|
||||
BrandRow().selectionDisabled()
|
||||
Section {
|
||||
ForEach(AppModel.Section.allCases) { s in
|
||||
Text(s.title).tag(s)
|
||||
ForEach(navSections) { s in
|
||||
Label(s.title, systemImage: Self.icon(s)).tag(s)
|
||||
}
|
||||
}
|
||||
if model.section == .documents, !model.tree.isEmpty {
|
||||
Section("도메인") {
|
||||
ForEach(model.tree) { node in
|
||||
DomainRow(node: node)
|
||||
}
|
||||
}
|
||||
// 문서 섹션일 때만 분류 소스트리 노출 (다른 섹션은 4-섹션만 보임).
|
||||
if model.section == .documents {
|
||||
DocumentsSourceSidebar()
|
||||
}
|
||||
}
|
||||
.listStyle(.sidebar)
|
||||
.background(Sage.sidebar)
|
||||
}
|
||||
}
|
||||
|
||||
struct DomainRow: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
let node: DomainTreeNode
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
Circle().fill(Sage.domainColor(node.name)).frame(width: 8, height: 8)
|
||||
Text(node.name).font(.callout).foregroundStyle(Sage.ink)
|
||||
Spacer()
|
||||
Text("\(node.count)").font(.caption).foregroundStyle(Sage.muted)
|
||||
static func icon(_ s: AppModel.Section) -> String {
|
||||
switch s {
|
||||
case .dashboard: return "house"
|
||||
case .documents: return "folder"
|
||||
case .digest: return "newspaper"
|
||||
case .memos: return "note.text"
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { model.section = .documents }
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentColumn: View {
|
||||
struct BrandRow: View {
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
RoundedRectangle(cornerRadius: 7).fill(Sage.brand).frame(width: 26, height: 26)
|
||||
.overlay(Text("DS").font(.system(size: 10, weight: .heavy)).foregroundStyle(.white))
|
||||
Text("Document Server").font(.system(size: 13.5, weight: .heavy)).foregroundStyle(Sage.ink)
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
}
|
||||
}
|
||||
|
||||
/// 문서 전용 소스트리: 분류(도메인 필터 = 실데이터) + 스마트그룹/태그(데이터 미연결 placeholder).
|
||||
struct DocumentsSourceSidebar: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
Section("분류") {
|
||||
SourceRow(label: "전체 문서", color: nil, count: model.stats?.total,
|
||||
selected: model.documentDomainFilter == nil) {
|
||||
Task { await model.loadDocuments(domain: nil) }
|
||||
}
|
||||
ForEach(model.tree) { node in
|
||||
SourceRow(label: localizedDomain(node.name), color: Sage.domainColor(node.name),
|
||||
count: node.count, selected: model.documentDomainFilter == node.path) {
|
||||
Task { await model.loadDocuments(domain: node.path) }
|
||||
}
|
||||
}
|
||||
}
|
||||
// 데이터 미연결 — IA 만 맞추고 비활성(가짜 카운트 금지).
|
||||
Section("스마트 그룹") {
|
||||
ForEach(["최근 7일", "검토 대기", "법령 알림"], id: \.self) { t in
|
||||
Text(t).font(.callout).foregroundStyle(Sage.muted).opacity(0.5)
|
||||
}
|
||||
}
|
||||
Section("태그") {
|
||||
ForEach(["압력용기", "ASME", "받은편지함"], id: \.self) { t in
|
||||
Text("#\(t)").font(.callout).foregroundStyle(Sage.muted).opacity(0.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 소스트리 행 (분류). 선택 시 brand-soft 배경 — List 시스템 선택과 분리(수동 하이라이트).
|
||||
struct SourceRow: View {
|
||||
let label: String
|
||||
let color: Color?
|
||||
let count: Int?
|
||||
let selected: Bool
|
||||
let action: () -> Void
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
if let color { RoundedRectangle(cornerRadius: 3).fill(color).frame(width: 8, height: 8) }
|
||||
Text(label).font(.callout)
|
||||
.foregroundStyle(selected ? Sage.brandDark : Sage.ink)
|
||||
.fontWeight(selected ? .bold : .regular)
|
||||
.lineLimit(1)
|
||||
Spacer()
|
||||
if let count { Text("\(count)").font(.caption.monospacedDigit()).foregroundStyle(Sage.muted) }
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture(perform: action)
|
||||
.listRowBackground(selected ? Sage.brand.opacity(0.14) : Color.clear)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Section router
|
||||
|
||||
/// 선택 섹션을 detail 전폭으로 라우팅. 셸 차원 inspector/list 칼럼 없음 — 각 페이지가 내부에서 소유.
|
||||
struct SectionDetail: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
switch model.section {
|
||||
case .dashboard: DashboardView()
|
||||
case .documents: DocumentListView()
|
||||
case .search: SearchView()
|
||||
case .ask: AskView()
|
||||
case .memos: MemoListView()
|
||||
case .digest: DigestView()
|
||||
case .dashboard: DashboardView() // 풀폭 캔버스
|
||||
case .documents: DocumentsBrowser() // 내부 HSplitView 3-pane
|
||||
case .digest: DigestView() // 풀폭 (뉴스 — 후속 모닝브리핑 재구성)
|
||||
case .memos: MemosBoard() // 리스트 + 상세 (후속 버킷 트리아지)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(Sage.surface)
|
||||
.navigationTitle(model.section.title)
|
||||
}
|
||||
}
|
||||
|
||||
struct DetailColumn: View {
|
||||
/// 메모 — v1 리스트+상세 split (확정 버킷 트리아지는 후속 트랙).
|
||||
struct MemosBoard: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
switch model.section {
|
||||
case .documents:
|
||||
if let d = model.documentDetail { DocumentDetailView(detail: d) }
|
||||
else { EmptyState(text: "문서를 선택하세요") }
|
||||
case .memos:
|
||||
HSplitView {
|
||||
MemoListView()
|
||||
.frame(minWidth: 300, idealWidth: 360, maxWidth: 460)
|
||||
Group {
|
||||
if let m = model.memoDetail { MemoDetailView(memo: m) }
|
||||
else { EmptyState(text: "메모를 선택하세요") }
|
||||
default:
|
||||
EmptyState(text: model.section.title)
|
||||
}
|
||||
.frame(minWidth: 360, maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,11 +216,96 @@ struct EmptyState: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Toolbar items
|
||||
|
||||
/// 툴바 업로드 버튼 — NSOpenPanel 로 파일 선택 → 멀티파트 업로드. 진행 중 비활성.
|
||||
struct UploadToolbarButton: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
Button {
|
||||
guard let fileURL = FilePanels.pickFileToUpload() else { return }
|
||||
Task { await model.uploadPicked(fileURL) }
|
||||
} label: {
|
||||
Label("업로드", systemImage: "square.and.arrow.up")
|
||||
}
|
||||
.help("문서 업로드")
|
||||
.disabled(isUploading)
|
||||
}
|
||||
|
||||
private var isUploading: Bool {
|
||||
if case .uploading = model.uploadState { return true }
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// 계정 메뉴 — 사용자명 표시 + 로그아웃(확인 대화상자).
|
||||
struct AccountMenu: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
@State private var confirmLogout = false
|
||||
|
||||
var body: some View {
|
||||
Menu {
|
||||
Button("로그아웃", role: .destructive) { confirmLogout = true }
|
||||
} label: {
|
||||
Label(model.currentUser?.username ?? "계정", systemImage: "person.crop.circle")
|
||||
}
|
||||
.help("계정")
|
||||
.confirmationDialog("로그아웃하시겠습니까?", isPresented: $confirmLogout, titleVisibility: .visible) {
|
||||
Button("로그아웃", role: .destructive) { Task { await model.logout() } }
|
||||
Button("취소", role: .cancel) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 업로드 진행/결과 상태바. uploading=스피너(닫기 없음) / done=성공(처리 대기 안내)+닫기 / failed=오류+닫기.
|
||||
struct UploadStatusBar: View {
|
||||
@Environment(AppModel.self) private var model
|
||||
|
||||
var body: some View {
|
||||
switch model.uploadState {
|
||||
case .idle:
|
||||
EmptyView()
|
||||
case .uploading(let name):
|
||||
row(bg: Sage.brand) {
|
||||
ProgressView().controlSize(.small).tint(.white)
|
||||
Text("업로드 중 — \(name)").font(.callout).foregroundStyle(.white).lineLimit(1)
|
||||
Spacer()
|
||||
}
|
||||
case .done(let title):
|
||||
row(bg: Sage.brand) {
|
||||
Text("업로드 완료 — \(title) (처리 대기 중)").font(.callout).foregroundStyle(.white).lineLimit(1)
|
||||
Spacer()
|
||||
closeButton
|
||||
}
|
||||
case .failed(let msg):
|
||||
row(bg: Sage.danger) {
|
||||
Text("업로드 실패 — \(msg)").font(.callout).foregroundStyle(.white).lineLimit(2)
|
||||
Spacer()
|
||||
closeButton
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var closeButton: some View {
|
||||
Button("닫기") { model.dismissUploadStatus() }
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(.white.opacity(0.85))
|
||||
}
|
||||
|
||||
private func row<Content: View>(bg: Color, @ViewBuilder _ content: () -> Content) -> some View {
|
||||
HStack(spacing: 10) { content() }
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.vertical, 8)
|
||||
.background(bg)
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
#Preview("DS App — full shell") {
|
||||
@Previewable @State var model = AppModel.preview
|
||||
RootView()
|
||||
.environment(model)
|
||||
.frame(minWidth: 1000, minHeight: 660)
|
||||
.frame(minWidth: 1100, minHeight: 700)
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -2,23 +2,24 @@ import SwiftUI
|
||||
import Observation
|
||||
import DSKit
|
||||
import AIFabric
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// The single app-state store driving the 3-pane shell. @MainActor @Observable: mutations are
|
||||
/// main-isolated; the DSClient returns Sendable models; AIService is an actor.
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class AppModel {
|
||||
/// 표시 순서 = 홈·문서·뉴스·메모. 질문(ask)·이드(AI chat)는 v1 macOS 표면에서 제거(2026-06-15) —
|
||||
/// AIFabric(S2) 코드는 향후 iPhone/Watch 이드용으로 보존, UI 섹션만 미노출.
|
||||
public enum Section: String, CaseIterable, Identifiable, Hashable {
|
||||
case dashboard, documents, search, ask, memos, digest
|
||||
case dashboard, documents, digest, memos
|
||||
public var id: String { rawValue }
|
||||
public var title: String {
|
||||
switch self {
|
||||
case .dashboard: return "대시보드"
|
||||
case .dashboard: return "홈"
|
||||
case .documents: return "문서"
|
||||
case .search: return "검색"
|
||||
case .ask: return "질문"
|
||||
case .memos: return "메모"
|
||||
case .digest: return "뉴스"
|
||||
case .memos: return "메모"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,19 +28,33 @@ public final class AppModel {
|
||||
/// → 성공 시 셸(ready). Fixture 클라이언트는 refresh 가 fixture 토큰을 돌려줘 곧장 ready.
|
||||
public enum AuthPhase: Equatable { case checking, loggedOut, ready }
|
||||
|
||||
/// 업로드 진행/결과 — 셸 하단 상태바 + 툴바 버튼 스피너용. done/failed 는 닫기 또는 다음 업로드로 소거.
|
||||
public enum UploadState: Equatable, Sendable {
|
||||
case idle
|
||||
case uploading(name: String)
|
||||
case done(title: String)
|
||||
case failed(String)
|
||||
}
|
||||
|
||||
public var section: Section = .dashboard
|
||||
public var selectedDocumentID: Int?
|
||||
public var selectedMemoID: Int?
|
||||
|
||||
public var tree: [DomainTreeNode] = []
|
||||
public var stats: CategoryCounts?
|
||||
/// 검토 대기 문서 총수 (홈 검토 큐 히어로). loadInitial 에서 count 쿼리로 채움. nil=미로드.
|
||||
public var reviewPendingCount: Int?
|
||||
/// 로그인 사용자 (계정 메뉴 표시용). loadInitial 에서 me() 로 채움.
|
||||
public var currentUser: UserResponse?
|
||||
public private(set) var uploadState: UploadState = .idle
|
||||
/// 홈 빠른 캡처 입력 (CaptureCard 바인딩, saveMemo 후 비움).
|
||||
public var captureText: String = ""
|
||||
public var documentList: [DocumentResponse] = []
|
||||
public var documentDetail: DocumentDetailResponse?
|
||||
public var searchQuery: String = ""
|
||||
public var searchResponse: SearchResponse?
|
||||
public var askQuery: String = ""
|
||||
public var askResult: AIResult?
|
||||
public var askMeta: DSKit.AskResponse? // qualified: AIFabric also defines an AskResponse
|
||||
/// 문서 사이드바 분류 필터 (선택된 도메인 path, nil = 전체 문서).
|
||||
public var documentDomainFilter: String?
|
||||
/// 현재 필터의 전체 문서를 다 불러왔는지 (페이지네이션 load-all 완료). 섹션 재진입 중복로드 방지.
|
||||
public private(set) var documentsFullyLoaded = false
|
||||
public var memoList: [MemoResponse] = []
|
||||
public var memoDetail: MemoResponse?
|
||||
public var digest: DigestResponse?
|
||||
@@ -129,11 +144,16 @@ public final class AppModel {
|
||||
}
|
||||
|
||||
public func loadInitial() async {
|
||||
await guarded { self.currentUser = try await self.client.me() }
|
||||
await guarded { self.tree = try await self.client.documentTree() }
|
||||
await guarded { self.stats = try await self.client.categoryCounts() }
|
||||
await guarded { self.documentList = try await self.client.documents(DocumentListQuery()).items }
|
||||
await guarded { self.memoList = try await self.client.memos(MemoListQuery()).items }
|
||||
await guarded { self.digest = try await self.client.digest(date: nil, country: nil) }
|
||||
await guarded {
|
||||
var q = DocumentListQuery(); q.reviewStatus = "pending"; q.pageSize = 1
|
||||
self.reviewPendingCount = try await self.client.documents(q).total
|
||||
}
|
||||
}
|
||||
|
||||
public func openDocument(_ id: Int) async {
|
||||
@@ -141,15 +161,60 @@ public final class AppModel {
|
||||
await guarded { self.documentDetail = try await self.client.document(id: id) }
|
||||
}
|
||||
|
||||
public func runSearch() async {
|
||||
guard !searchQuery.isEmpty else { return }
|
||||
await guarded { self.searchResponse = try await self.client.search(q: self.searchQuery, mode: .hybrid, page: 1, debug: false) }
|
||||
/// 문서 섹션 진입 시 현재 필터의 전체 문서 확보 (중복로드 방지). 미로드 상태일 때만 load-all.
|
||||
public func ensureDocumentsLoaded() async {
|
||||
if !documentsFullyLoaded { await loadDocuments(domain: documentDomainFilter) }
|
||||
}
|
||||
|
||||
public func runAsk(backend: AIProviderID?) async {
|
||||
guard !askQuery.isEmpty else { return }
|
||||
askResult = await ai.corpusAsk(question: askQuery, explicit: backend)
|
||||
await guarded { self.askMeta = try await self.client.ask(q: self.askQuery, limit: nil, backend: nil, debug: false) }
|
||||
/// 사이드바 분류 선택 → 도메인 필터로 **전체** 문서 load-all (서버 page_size 상한 100을 페이지네이션으로
|
||||
/// 모두 수집 — 1582건도 전부 노출). 페이지마다 append 라 목록이 점진적으로 채워진다. 재조회 후
|
||||
/// 선택 문서가 새 목록에 없으면 선택/상세를 비워 3-pane 정합 유지.
|
||||
public func loadDocuments(domain: String?) async {
|
||||
documentDomainFilter = domain
|
||||
documentsFullyLoaded = false
|
||||
documentList = []
|
||||
let pageSize = 100
|
||||
var page = 1
|
||||
do {
|
||||
while page <= 80 { // 안전 상한 ~8000건
|
||||
var q = DocumentListQuery(); q.domain = domain; q.page = page; q.pageSize = pageSize
|
||||
let resp = try await client.documents(q)
|
||||
documentList.append(contentsOf: resp.items)
|
||||
if resp.items.count < pageSize || documentList.count >= resp.total { break }
|
||||
page += 1
|
||||
}
|
||||
documentsFullyLoaded = true
|
||||
} catch let e as DSError where e.isAuthExpired {
|
||||
authPhase = .loggedOut
|
||||
loginError = "세션이 만료되었습니다. 다시 로그인하세요."
|
||||
} catch {
|
||||
errorText = (error as? LocalizedError)?.errorDescription ?? "\(error)"
|
||||
}
|
||||
await syncAccessToken()
|
||||
if let sel = selectedDocumentID, !documentList.contains(where: { $0.id == sel }) {
|
||||
selectedDocumentID = nil
|
||||
documentDetail = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// 텍스트로 메모 생성 후 목록 맨 앞 반영. 성공 시 true. 빈/공백 입력은 무시(false). 에러는
|
||||
/// guarded 깔때기로 errorText 노출(삼키지 않음).
|
||||
@discardableResult
|
||||
public func saveMemo(_ text: String) async -> Bool {
|
||||
let t = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !t.isEmpty else { return false }
|
||||
var ok = false
|
||||
await guarded {
|
||||
let memo = try await self.client.createMemo(MemoCreate(content: t))
|
||||
self.memoList.insert(memo, at: 0)
|
||||
ok = true
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
/// 홈 빠른 캡처 — captureText 사용, 성공 시 입력 비움.
|
||||
public func saveMemo() async {
|
||||
if await saveMemo(captureText) { captureText = "" }
|
||||
}
|
||||
|
||||
public func openMemo(_ id: Int) async {
|
||||
@@ -162,6 +227,67 @@ public final class AppModel {
|
||||
return DSDownload.fileURL(base: base, documentID: doc.id, accessToken: accessToken)
|
||||
}
|
||||
|
||||
/// 로그아웃: 서버 쿠키/토큰 폐기(best-effort) 후 세션 상태 전체 초기화 → loggedOut. 다음 로그인이
|
||||
/// stale 데이터 없이 깨끗하게 시작하도록 로드 상태를 비운다. 실패해도 로컬은 무조건 로그아웃 처리.
|
||||
public func logout() async {
|
||||
try? await client.logout()
|
||||
accessToken = ""
|
||||
currentUser = nil
|
||||
tree = []
|
||||
stats = nil
|
||||
reviewPendingCount = nil
|
||||
captureText = ""
|
||||
documentList = []
|
||||
documentDetail = nil
|
||||
documentDomainFilter = nil
|
||||
documentsFullyLoaded = false
|
||||
memoList = []
|
||||
memoDetail = nil
|
||||
digest = nil
|
||||
selectedDocumentID = nil
|
||||
selectedMemoID = nil
|
||||
section = .dashboard // 다음 로그인은 홈에서 시작 (리뷰 LOW: 이전 사용자 마지막 페이지 잔류 방지)
|
||||
errorText = nil
|
||||
uploadState = .idle
|
||||
authPhase = .loggedOut
|
||||
}
|
||||
|
||||
/// 사용자가 고른 파일(NSOpenPanel 보안 스코프 URL)을 읽어 업로드. 파일 IO 실패는 uploadState 로 노출.
|
||||
public func uploadPicked(_ fileURL: URL) async {
|
||||
let accessed = fileURL.startAccessingSecurityScopedResource()
|
||||
defer { if accessed { fileURL.stopAccessingSecurityScopedResource() } }
|
||||
let filename = fileURL.lastPathComponent
|
||||
let data: Data
|
||||
do {
|
||||
data = try Data(contentsOf: fileURL)
|
||||
} catch {
|
||||
uploadState = .failed("파일을 읽을 수 없습니다: \((error as NSError).localizedDescription)")
|
||||
return
|
||||
}
|
||||
let mime = UTType(filenameExtension: fileURL.pathExtension)?.preferredMIMEType
|
||||
await upload(DocumentUpload(filename: filename, data: data, mimeType: mime))
|
||||
}
|
||||
|
||||
/// 멀티파트 업로드 실행 + 결과 반영. 성공 시 목록 재로드(신규 문서 = 처리 대기 상태로 노출).
|
||||
public func upload(_ payload: DocumentUpload) async {
|
||||
uploadState = .uploading(name: payload.filename)
|
||||
do {
|
||||
let doc = try await client.uploadDocument(payload)
|
||||
uploadState = .done(title: doc.title ?? doc.downloadLabel)
|
||||
await guarded { self.documentList = try await self.client.documents(DocumentListQuery()).items }
|
||||
} catch let e as DSError where e.isAuthExpired {
|
||||
authPhase = .loggedOut
|
||||
loginError = "세션이 만료되었습니다. 다시 로그인하세요."
|
||||
uploadState = .failed("세션이 만료되었습니다.")
|
||||
} catch {
|
||||
uploadState = .failed((error as? LocalizedError)?.errorDescription ?? "\(error)")
|
||||
}
|
||||
await syncAccessToken()
|
||||
}
|
||||
|
||||
/// 업로드 상태바 닫기 (done/failed 소거).
|
||||
public func dismissUploadStatus() { uploadState = .idle }
|
||||
|
||||
private func guarded(_ work: () async throws -> Void) async {
|
||||
do {
|
||||
try await work()
|
||||
|
||||
@@ -23,6 +23,8 @@ public protocol DSClient: Sendable {
|
||||
func patchDocument(id: Int, _ update: DocumentUpdate) async throws -> DocumentResponse
|
||||
func putContent(id: Int, content: String) async throws
|
||||
func deleteDocument(id: Int) async throws
|
||||
/// 멀티파트 업로드 (POST /documents/) → Inbox 저장 + 처리 큐 등록. 201 DocumentResponse.
|
||||
func uploadDocument(_ upload: DocumentUpload) async throws -> DocumentResponse
|
||||
|
||||
// Search / Ask
|
||||
func search(q: String, mode: SearchMode?, page: Int?, debug: Bool?) async throws -> SearchResponse
|
||||
|
||||
@@ -53,6 +53,9 @@ public struct FixtureDSClient: DSClient {
|
||||
}
|
||||
public func putContent(id: Int, content: String) async throws {}
|
||||
public func deleteDocument(id: Int) async throws {}
|
||||
public func uploadDocument(_ upload: DocumentUpload) async throws -> DocumentResponse {
|
||||
try load("document_detail", as: DocumentDetailResponse.self).base
|
||||
}
|
||||
|
||||
// Search / Ask
|
||||
public func search(q: String, mode: SearchMode?, page: Int?, debug: Bool?) async throws -> SearchResponse {
|
||||
|
||||
@@ -64,15 +64,26 @@ public final class LiveDSClient: DSClient, @unchecked Sendable {
|
||||
}
|
||||
|
||||
private func perform(_ endpoint: DSEndpoint) async throws -> Data {
|
||||
let request = try makeRequest(endpoint, token: await tokens.current())
|
||||
try await performWithRetry(requiresBearer: endpoint.requiresBearer) { token in
|
||||
try self.makeRequest(endpoint, token: token)
|
||||
}
|
||||
}
|
||||
|
||||
/// 401 단일-비행 refresh + 1회 재시도의 공용 경로. `build` 가 (현 토큰)→URLRequest 를 만들고,
|
||||
/// 401 이면 새 토큰으로 한 번 더 빌드해 재전송한다. JSON 경로(perform)와 멀티파트 업로드가 공유.
|
||||
private func performWithRetry(
|
||||
requiresBearer: Bool,
|
||||
_ build: (_ token: String?) throws -> URLRequest
|
||||
) async throws -> Data {
|
||||
let request = try build(await tokens.current())
|
||||
let (data, response) = try await dataOrTransport(request)
|
||||
guard let http = response as? HTTPURLResponse else {
|
||||
throw DSError.transport(underlying: "no HTTP response")
|
||||
}
|
||||
if http.statusCode == 401, endpoint.requiresBearer {
|
||||
if http.statusCode == 401, requiresBearer {
|
||||
// Single-flight refresh + one retry.
|
||||
let newToken = try await tokens.refreshOnce()
|
||||
let retry = try makeRequest(endpoint, token: newToken)
|
||||
let retry = try build(newToken)
|
||||
let (data2, response2) = try await dataOrTransport(retry)
|
||||
guard let http2 = response2 as? HTTPURLResponse else {
|
||||
throw DSError.transport(underlying: "no HTTP response")
|
||||
@@ -122,6 +133,44 @@ public final class LiveDSClient: DSClient, @unchecked Sendable {
|
||||
public func putContent(id: Int, content: String) async throws { try await sendVoid(.putContent(id, content)) }
|
||||
public func deleteDocument(id: Int) async throws { try await sendVoid(.deleteDocument(id)) }
|
||||
|
||||
public func uploadDocument(_ upload: DocumentUpload) async throws -> DocumentResponse {
|
||||
let boundary = "DSBoundary-\(UUID().uuidString)"
|
||||
let body = LiveDSClient.multipartBody(for: upload, boundary: boundary)
|
||||
// 트레일링 슬래시 유지(POST /documents/) — base 문자열 결합 (appendingPathComponent 는 슬래시 strip).
|
||||
let raw = base.url.absoluteString + "/documents/"
|
||||
guard let url = URL(string: raw) else { throw DSError.transport(underlying: "bad URL \(raw)") }
|
||||
let data = try await performWithRetry(requiresBearer: true) { token in
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = "POST"
|
||||
if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
|
||||
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
|
||||
request.httpBody = body
|
||||
return request
|
||||
}
|
||||
do { return try decoder.decode(DocumentResponse.self, from: data) }
|
||||
catch { throw DSError.decoding("documents/ upload: \(error)") }
|
||||
}
|
||||
|
||||
/// multipart/form-data 본문 생성. file 파트 + 선택 form 필드(doc_purpose/library_path).
|
||||
/// internal(테스트 가시) — 한글 파일명은 UTF-8 바이트 그대로(Starlette 가 디코드).
|
||||
static func multipartBody(for upload: DocumentUpload, boundary: String) -> Data {
|
||||
var body = Data()
|
||||
func appendField(_ name: String, _ value: String) {
|
||||
body.append(Data("--\(boundary)\r\n".utf8))
|
||||
body.append(Data("Content-Disposition: form-data; name=\"\(name)\"\r\n\r\n".utf8))
|
||||
body.append(Data("\(value)\r\n".utf8))
|
||||
}
|
||||
if let p = upload.docPurpose { appendField("doc_purpose", p) }
|
||||
if let lp = upload.libraryPath { appendField("library_path", lp) }
|
||||
body.append(Data("--\(boundary)\r\n".utf8))
|
||||
body.append(Data("Content-Disposition: form-data; name=\"file\"; filename=\"\(upload.filename)\"\r\n".utf8))
|
||||
body.append(Data("Content-Type: \(upload.mimeType ?? "application/octet-stream")\r\n\r\n".utf8))
|
||||
body.append(upload.data)
|
||||
body.append(Data("\r\n".utf8))
|
||||
body.append(Data("--\(boundary)--\r\n".utf8))
|
||||
return body
|
||||
}
|
||||
|
||||
public func search(q: String, mode: SearchMode?, page: Int?, debug: Bool?) async throws -> SearchResponse { try await send(.search(q, mode, page, debug), as: SearchResponse.self) }
|
||||
public func ask(q: String, limit: Int?, backend: String?, debug: Bool?) async throws -> AskResponse { try await send(.ask(q, limit, backend, debug), as: AskResponse.self) }
|
||||
|
||||
|
||||
@@ -24,6 +24,25 @@ public struct MemoListQuery: Sendable {
|
||||
public init() {}
|
||||
}
|
||||
|
||||
/// 멀티파트 업로드 페이로드 (POST /documents/). `file` 파트 + 선택 form 필드.
|
||||
/// `data` 는 메모리 적재(개인 문서 규모 가정) — 대용량 디스크 스트리밍은 후속.
|
||||
public struct DocumentUpload: Sendable {
|
||||
public var filename: String
|
||||
public var data: Data
|
||||
public var mimeType: String?
|
||||
/// "business" | "knowledge" | nil. business 는 서버가 @library 로 자동 태깅.
|
||||
public var docPurpose: String?
|
||||
public var libraryPath: String?
|
||||
public init(filename: String, data: Data, mimeType: String? = nil,
|
||||
docPurpose: String? = nil, libraryPath: String? = nil) {
|
||||
self.filename = filename
|
||||
self.data = data
|
||||
self.mimeType = mimeType
|
||||
self.docPurpose = docPurpose
|
||||
self.libraryPath = libraryPath
|
||||
}
|
||||
}
|
||||
|
||||
public struct DocumentUpdate: Codable, Sendable {
|
||||
public var title: String?
|
||||
public var userNote: String?
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import XCTest
|
||||
@testable import AppFeature
|
||||
import DSKit
|
||||
|
||||
/// 로그아웃 상태 초기화 + 업로드 결과 반영 — 네트워크 0 (Fixture).
|
||||
final class AppModelActionsTests: XCTestCase {
|
||||
|
||||
// ready 세션에서 로그아웃 → loggedOut + 토큰/사용자/로드상태 전부 초기화
|
||||
@MainActor
|
||||
func testLogoutResetsStateAndLogsOut() async {
|
||||
let model = AppModel.preview
|
||||
await model.bootstrap()
|
||||
XCTAssertEqual(model.authPhase, .ready)
|
||||
XCTAssertFalse(model.documentList.isEmpty)
|
||||
XCTAssertNotNil(model.currentUser, "loadInitial 이 me() 로 사용자 채움")
|
||||
|
||||
await model.logout()
|
||||
|
||||
XCTAssertEqual(model.authPhase, .loggedOut)
|
||||
XCTAssertTrue(model.accessToken.isEmpty)
|
||||
XCTAssertNil(model.currentUser)
|
||||
XCTAssertTrue(model.documentList.isEmpty)
|
||||
XCTAssertNil(model.documentDetail)
|
||||
XCTAssertTrue(model.tree.isEmpty)
|
||||
XCTAssertEqual(model.uploadState, .idle)
|
||||
}
|
||||
|
||||
// 업로드 성공 → uploadState=.done + 목록 재로드
|
||||
@MainActor
|
||||
func testUploadSuccessSetsDoneAndReloads() async {
|
||||
let model = AppModel.preview
|
||||
await model.bootstrap()
|
||||
await model.upload(DocumentUpload(filename: "x.pdf", data: Data("x".utf8), mimeType: "application/pdf"))
|
||||
|
||||
if case .done = model.uploadState {} else {
|
||||
XCTFail("기대 .done, 실제 \(model.uploadState)")
|
||||
}
|
||||
XCTAssertFalse(model.documentList.isEmpty)
|
||||
}
|
||||
|
||||
// 업로드 진행 상태 전이 표현 (Equatable 동작 확인 — 상태바 분기 근거)
|
||||
@MainActor
|
||||
func testDismissUploadStatusReturnsToIdle() async {
|
||||
let model = AppModel.preview
|
||||
await model.bootstrap()
|
||||
await model.upload(DocumentUpload(filename: "x.pdf", data: Data("x".utf8)))
|
||||
model.dismissUploadStatus()
|
||||
XCTAssertEqual(model.uploadState, .idle)
|
||||
}
|
||||
}
|
||||
@@ -168,6 +168,7 @@ final class AuthStubClient: DSClient, @unchecked Sendable {
|
||||
func patchDocument(id: Int, _ update: DocumentUpdate) async throws -> DocumentResponse { try await inner.patchDocument(id: id, update) }
|
||||
func putContent(id: Int, content: String) async throws { try await inner.putContent(id: id, content: content) }
|
||||
func deleteDocument(id: Int) async throws { try await inner.deleteDocument(id: id) }
|
||||
func uploadDocument(_ upload: DocumentUpload) async throws -> DocumentResponse { try await inner.uploadDocument(upload) }
|
||||
func search(q: String, mode: SearchMode?, page: Int?, debug: Bool?) async throws -> SearchResponse { try await inner.search(q: q, mode: mode, page: page, debug: debug) }
|
||||
func ask(q: String, limit: Int?, backend: String?, debug: Bool?) async throws -> AskResponse { try await inner.ask(q: q, limit: limit, backend: backend, debug: debug) }
|
||||
func memos(_ query: MemoListQuery) async throws -> MemoListResponse { try await inner.memos(query) }
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import XCTest
|
||||
@testable import DSKit
|
||||
|
||||
/// 멀티파트 업로드 — Fixture 에코 + multipart 본문 형태(경계/디스포지션/한글 파일명/필드/파일 데이터).
|
||||
final class UploadTests: XCTestCase {
|
||||
|
||||
func testFixtureUploadReturnsDocument() async throws {
|
||||
let doc = try await FixtureDSClient().uploadDocument(
|
||||
DocumentUpload(filename: "a.pdf", data: Data("x".utf8), mimeType: "application/pdf"))
|
||||
XCTAssertGreaterThan(doc.id, 0)
|
||||
}
|
||||
|
||||
func testMultipartBodyShape() throws {
|
||||
let upload = DocumentUpload(
|
||||
filename: "보고서.pdf",
|
||||
data: Data("PDFDATA".utf8),
|
||||
mimeType: "application/pdf",
|
||||
docPurpose: "knowledge"
|
||||
)
|
||||
let boundary = "TESTBOUNDARY"
|
||||
let body = LiveDSClient.multipartBody(for: upload, boundary: boundary)
|
||||
let s = try XCTUnwrap(String(data: body, encoding: .utf8))
|
||||
|
||||
XCTAssertTrue(s.contains("--TESTBOUNDARY\r\n"), "경계 마커")
|
||||
XCTAssertTrue(s.contains(#"Content-Disposition: form-data; name="file"; filename="보고서.pdf""#),
|
||||
"file 파트 + 한글 파일명")
|
||||
XCTAssertTrue(s.contains("Content-Type: application/pdf"), "파일 mime")
|
||||
XCTAssertTrue(s.contains(#"Content-Disposition: form-data; name="doc_purpose""#), "선택 form 필드")
|
||||
XCTAssertTrue(s.contains("knowledge"))
|
||||
XCTAssertTrue(s.contains("PDFDATA"), "파일 데이터")
|
||||
XCTAssertTrue(s.hasSuffix("--TESTBOUNDARY--\r\n"), "종료 경계")
|
||||
}
|
||||
|
||||
func testMultipartOmitsAbsentOptionalFields() throws {
|
||||
let upload = DocumentUpload(filename: "x.txt", data: Data("a".utf8))
|
||||
let body = LiveDSClient.multipartBody(for: upload, boundary: "B")
|
||||
let s = try XCTUnwrap(String(data: body, encoding: .utf8))
|
||||
XCTAssertFalse(s.contains("doc_purpose"), "미지정 doc_purpose 는 본문에 없어야 함")
|
||||
XCTAssertFalse(s.contains("library_path"), "미지정 library_path 는 본문에 없어야 함")
|
||||
XCTAssertTrue(s.contains("Content-Type: application/octet-stream"), "mime 미지정 = octet-stream 폴백")
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ UserResponse { id: Int, username: String, is_active: Bool, totp_enabled: Bool, l
|
||||
| GET | `/documents/{id}/content` | — | 경량 텍스트(`content` 15k cap) | `document_content.json` |
|
||||
| GET | `/documents/tree` | — | 도메인 트리(사이드바) | `documents_tree.json` |
|
||||
| GET | `/documents/stats/category-counts` | — | `{counts: {category: n}, library_pending_suggestions}` — **raw dict 반환(Pydantic 모델 없음), 2026-06-07 라이브 재캡처로 정정**(초기 추출이 shape 합성 오류) | `documents_stats.json` |
|
||||
| POST | `/documents/` (multipart) | 파일 업로드 | `DocumentResponse` (201) | `document_detail.json` |
|
||||
| POST | `/documents/` (multipart/form-data) | `file`(필수) + `doc_purpose?`(business\|knowledge) `library_path?` `facet_*?` | `DocumentResponse` (201) | `document_detail.json` |
|
||||
| PATCH | `/documents/{id}` | `DocumentUpdate` | `DocumentResponse` | — |
|
||||
| PUT | `/documents/{id}/content` | `{content}` (md 편집 저장) | `{}` | — |
|
||||
| POST | `/documents/{id}/accept-suggestion` | `{expected_source_updated_at}` | `DocumentResponse` | — |
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
DSShell.xcodeproj/
|
||||
Support/
|
||||
.build/
|
||||
*.xcuserstate
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
},
|
||||
"images" : [
|
||||
{
|
||||
"scale" : "1x",
|
||||
"filename" : "mac_16.png",
|
||||
"idiom" : "mac",
|
||||
"size" : "16x16"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"size" : "16x16",
|
||||
"scale" : "2x",
|
||||
"filename" : "mac_32.png"
|
||||
},
|
||||
{
|
||||
"filename" : "mac_32.png",
|
||||
"size" : "32x32",
|
||||
"scale" : "1x",
|
||||
"idiom" : "mac"
|
||||
},
|
||||
{
|
||||
"scale" : "2x",
|
||||
"idiom" : "mac",
|
||||
"size" : "32x32",
|
||||
"filename" : "mac_64.png"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"size" : "128x128",
|
||||
"filename" : "mac_128.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"size" : "128x128",
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"filename" : "mac_256.png"
|
||||
},
|
||||
{
|
||||
"filename" : "mac_256.png",
|
||||
"scale" : "1x",
|
||||
"idiom" : "mac",
|
||||
"size" : "256x256"
|
||||
},
|
||||
{
|
||||
"filename" : "mac_512.png",
|
||||
"scale" : "2x",
|
||||
"size" : "256x256",
|
||||
"idiom" : "mac"
|
||||
},
|
||||
{
|
||||
"filename" : "mac_512.png",
|
||||
"size" : "512x512",
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"filename" : "mac_1024.png",
|
||||
"size" : "512x512",
|
||||
"scale" : "2x",
|
||||
"idiom" : "mac"
|
||||
},
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"filename" : "ios_1024.png",
|
||||
"size" : "1024x1024",
|
||||
"platform" : "ios"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 569 B |
|
After Width: | Height: | Size: 8.3 KiB |
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import SwiftUI
|
||||
|
||||
/// DS 웹 래퍼 — document.hyungi.net 을 네이티브 창에 로드. 로그인은 WKWebsiteDataStore.default()
|
||||
/// 영속 쿠키로 유지(브라우저처럼). 맥·iOS 공용 @main.
|
||||
@main
|
||||
struct DSShellApp: App {
|
||||
private let url = URL(string: "https://document.hyungi.net")!
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
RootWeb(url: url)
|
||||
}
|
||||
#if os(macOS)
|
||||
.windowStyle(.automatic)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
struct RootWeb: View {
|
||||
let url: URL
|
||||
var body: some View {
|
||||
WebView(url: url)
|
||||
.ignoresSafeArea()
|
||||
#if os(macOS)
|
||||
.frame(minWidth: 900, minHeight: 600)
|
||||
.background(WindowOnScreenGuard()) // 분리된 모니터 좌표 저장 시 화면 밖 방지
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import SwiftUI
|
||||
import WebKit
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
#else
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// document.hyungi.net 을 로드하는 WKWebView 래퍼 (맥=NSViewRepresentable / iOS=UIViewRepresentable).
|
||||
/// 영속 데이터스토어 = 로그인 쿠키 유지. 첨부(Content-Disposition: attachment) 응답은 다운로드 처리.
|
||||
/// 파일 업로드(file input)는 WKWebView 가 네이티브 피커로 자동 처리.
|
||||
struct WebView {
|
||||
let url: URL
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||
|
||||
@MainActor
|
||||
fileprivate func makeWebView(coordinator: Coordinator) -> WKWebView {
|
||||
let cfg = WKWebViewConfiguration()
|
||||
cfg.websiteDataStore = .default() // 영속 쿠키 → 로그인 유지(브라우저처럼)
|
||||
let wv = WKWebView(frame: .zero, configuration: cfg)
|
||||
wv.navigationDelegate = coordinator
|
||||
wv.allowsBackForwardNavigationGestures = true
|
||||
wv.load(URLRequest(url: url))
|
||||
return wv
|
||||
}
|
||||
|
||||
final class Coordinator: NSObject, WKNavigationDelegate, WKDownloadDelegate {
|
||||
// 첨부 응답이면 다운로드, 아니면 일반 표시(PDF 등 인라인).
|
||||
func webView(_ webView: WKWebView,
|
||||
decidePolicyFor navigationResponse: WKNavigationResponse,
|
||||
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
|
||||
if let http = navigationResponse.response as? HTTPURLResponse,
|
||||
let cd = http.value(forHTTPHeaderField: "Content-Disposition"),
|
||||
cd.lowercased().contains("attachment") {
|
||||
decisionHandler(.download)
|
||||
} else {
|
||||
decisionHandler(.allow)
|
||||
}
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {
|
||||
download.delegate = self
|
||||
}
|
||||
func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) {
|
||||
download.delegate = self
|
||||
}
|
||||
|
||||
func download(_ download: WKDownload,
|
||||
decideDestinationUsing response: URLResponse,
|
||||
suggestedFilename: String) async -> URL? {
|
||||
#if os(macOS)
|
||||
let folder = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first
|
||||
#else
|
||||
let folder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
|
||||
#endif
|
||||
let dir = folder ?? FileManager.default.temporaryDirectory
|
||||
var dest = dir.appendingPathComponent(suggestedFilename.isEmpty ? "download" : suggestedFilename)
|
||||
// 충돌 회피 (name_1.ext …)
|
||||
let base = dest.deletingPathExtension().lastPathComponent
|
||||
let ext = dest.pathExtension
|
||||
var n = 1
|
||||
while FileManager.default.fileExists(atPath: dest.path) {
|
||||
let name = ext.isEmpty ? "\(base)_\(n)" : "\(base)_\(n).\(ext)"
|
||||
dest = dir.appendingPathComponent(name); n += 1
|
||||
}
|
||||
return dest
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if os(macOS)
|
||||
extension WebView: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> WKWebView { makeWebView(coordinator: context.coordinator) }
|
||||
func updateNSView(_ nsView: WKWebView, context: Context) {}
|
||||
}
|
||||
|
||||
/// 창이 어느 화면과도 안 겹치면(분리된 외부모니터 좌표 저장 등) 메인 화면 중앙으로 복귀 — "창 안 뜸" 방지.
|
||||
struct WindowOnScreenGuard: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> NSView { OnScreenView() }
|
||||
func updateNSView(_ nsView: NSView, context: Context) {}
|
||||
final class OnScreenView: NSView {
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
guard let win = window else { return }
|
||||
if !NSScreen.screens.contains(where: { $0.visibleFrame.intersects(win.frame) }) { win.center() }
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
extension WebView: UIViewRepresentable {
|
||||
func makeUIView(context: Context) -> WKWebView { makeWebView(coordinator: context.coordinator) }
|
||||
func updateUIView(_ uiView: WKWebView, context: Context) {}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,87 @@
|
||||
# DS 웹 래퍼 — document.hyungi.net 을 WKWebView 로 감싼 네이티브 앱(맥 + iOS).
|
||||
# 웹 UI 100% 재사용·항상 최신·코드 1벌(2026-06-15 결정). 순수 네이티브는 워치(clients/ds-watch)만.
|
||||
# project.yml = source of truth, *.xcodeproj/Support = 생성물(gitignore).
|
||||
name: DSShell
|
||||
options:
|
||||
bundleIdPrefix: net.hyungi
|
||||
deploymentTarget:
|
||||
macOS: "14.0"
|
||||
iOS: "17.0"
|
||||
createIntermediateGroups: true
|
||||
minimumXcodeGenVersion: "2.40.0"
|
||||
|
||||
settings:
|
||||
base:
|
||||
SWIFT_VERSION: "6.0"
|
||||
CODE_SIGN_STYLE: Automatic
|
||||
# 실기기 설치(맥/아이폰)는 Xcode 자동서명(본인 Apple ID 팀). 헤드리스 빌드만 CLI 로 CODE_SIGNING_ALLOWED=NO 전달.
|
||||
GENERATE_INFOPLIST_FILE: "NO"
|
||||
|
||||
targets:
|
||||
DSShellMac:
|
||||
type: application
|
||||
platform: macOS
|
||||
deploymentTarget: "14.0"
|
||||
sources:
|
||||
- path: Sources
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_BUNDLE_IDENTIFIER: net.hyungi.dsshell
|
||||
PRODUCT_NAME: DS
|
||||
MARKETING_VERSION: "0.1"
|
||||
CURRENT_PROJECT_VERSION: "1"
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
|
||||
info:
|
||||
path: Support/Mac-Info.plist
|
||||
properties:
|
||||
CFBundleName: DS
|
||||
CFBundleDisplayName: DS
|
||||
CFBundleShortVersionString: "0.1"
|
||||
CFBundleVersion: "1"
|
||||
CFBundlePackageType: APPL
|
||||
LSMinimumSystemVersion: "14.0"
|
||||
LSApplicationCategoryType: public.app-category.productivity
|
||||
entitlements:
|
||||
path: Support/Mac.entitlements
|
||||
properties:
|
||||
com.apple.security.app-sandbox: true
|
||||
com.apple.security.network.client: true
|
||||
com.apple.security.files.downloads.read-write: true # 원본 다운로드 저장
|
||||
com.apple.security.files.user-selected.read-write: true # 업로드 파일 선택
|
||||
|
||||
DSShelliOS:
|
||||
type: application
|
||||
platform: iOS
|
||||
deploymentTarget: "17.0"
|
||||
sources:
|
||||
- path: Sources
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_BUNDLE_IDENTIFIER: net.hyungi.dsshell
|
||||
PRODUCT_NAME: DS
|
||||
MARKETING_VERSION: "0.1"
|
||||
CURRENT_PROJECT_VERSION: "1"
|
||||
TARGETED_DEVICE_FAMILY: "1,2"
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
|
||||
info:
|
||||
path: Support/iOS-Info.plist
|
||||
properties:
|
||||
CFBundleName: DS
|
||||
CFBundleDisplayName: DS
|
||||
CFBundleShortVersionString: "0.1"
|
||||
CFBundleVersion: "1"
|
||||
UILaunchScreen: {}
|
||||
UISupportedInterfaceOrientations:
|
||||
- UIInterfaceOrientationPortrait
|
||||
- UIInterfaceOrientationLandscapeLeft
|
||||
- UIInterfaceOrientationLandscapeRight
|
||||
|
||||
schemes:
|
||||
DSShellMac:
|
||||
build:
|
||||
targets: { DSShellMac: all }
|
||||
run: { config: Debug }
|
||||
DSShelliOS:
|
||||
build:
|
||||
targets: { DSShelliOS: all }
|
||||
run: { config: Debug }
|
||||
@@ -0,0 +1,5 @@
|
||||
# xcodegen 생성물 (project.yml 이 source of truth)
|
||||
DSWatch.xcodeproj/
|
||||
Support/
|
||||
.build/
|
||||
*.xcuserstate
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"images" : [
|
||||
{ "idiom" : "universal", "platform" : "watchos", "size" : "1024x1024", "filename" : "watch_1024.png" }
|
||||
],
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
|
After Width: | Height: | Size: 38 KiB |
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import SwiftUI
|
||||
|
||||
/// DS 애플워치 앱 (standalone). 4기능 = 이드(AI채팅)·공부(암기카드)·할 일·브리핑.
|
||||
/// 공부 = 라이브 결선(/study-cards/due·rate) / 나머지 = 스캐폴드. 다크 OLED.
|
||||
@main
|
||||
struct DSWatchApp: App {
|
||||
@State private var model = WatchModel()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
RootGate()
|
||||
.environment(model)
|
||||
.task { await model.bootstrap() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 인증 게이트: checking(쿠키 복귀) → loggedOut(로그인) → ready(메뉴).
|
||||
struct RootGate: View {
|
||||
@Environment(WatchModel.self) private var model
|
||||
var body: some View {
|
||||
switch model.phase {
|
||||
case .checking: ProgressView()
|
||||
case .loggedOut: LoginView()
|
||||
case .ready: RootMenu()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import WatchKit
|
||||
|
||||
/// 워치 햅틱 — 평정/완료의 손목 탭 피드백(워치 고유 감각).
|
||||
@MainActor
|
||||
enum Haptics {
|
||||
static func success() { WKInterfaceDevice.current().play(.success) }
|
||||
static func retry() { WKInterfaceDevice.current().play(.retry) }
|
||||
static func click() { WKInterfaceDevice.current().play(.click) }
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
import Foundation
|
||||
|
||||
/// 워치 전용 경량 API 클라이언트. DS 공개 TLS(document.hyungi.net) 직접 도달 — 워치는 Tailscale 불가.
|
||||
/// access 토큰=메모리 / refresh 쿠키=HTTPCookieStorage(7일 영속) 라 1회 로그인 후 자동 유지.
|
||||
/// 계약은 백엔드 Pydantic 모델에서 추출(study_cards.py CardItem/RateBody) — 지어내지 않음.
|
||||
enum WatchAPI {
|
||||
static let baseString = "https://document.hyungi.net/api"
|
||||
}
|
||||
|
||||
/// GET /study-cards/due 의 CardItem (워치가 쓰는 필드만).
|
||||
struct WCard: Decodable, Identifiable, Sendable {
|
||||
let id: Int
|
||||
let format: String
|
||||
let cue: String
|
||||
let fact: String
|
||||
let clozeText: String?
|
||||
let needsReview: Bool
|
||||
let reviewStage: Int?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, format, cue, fact
|
||||
case clozeText = "cloze_text"
|
||||
case needsReview = "needs_review"
|
||||
case reviewStage = "review_stage"
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /events/today 의 EventResponse (워치 할일이 쓰는 필드만).
|
||||
struct WEvent: Decodable, Identifiable, Sendable {
|
||||
let id: Int
|
||||
let title: String
|
||||
let status: String
|
||||
let dueAt: String?
|
||||
let completedAt: String?
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, title, status
|
||||
case dueAt = "due_at"
|
||||
case completedAt = "completed_at"
|
||||
}
|
||||
var isDone: Bool { status == "completed" || completedAt != nil }
|
||||
}
|
||||
private struct WEventList: Decodable { let items: [WEvent] }
|
||||
|
||||
/// GET /briefing/latest 의 토픽/국가관점 (워치 글랜스용 부분집합).
|
||||
struct WPerspective: Decodable, Identifiable, Sendable {
|
||||
let country: String
|
||||
let summary: String
|
||||
var id: String { country }
|
||||
}
|
||||
struct WTopic: Decodable, Identifiable, Sendable {
|
||||
let id: Int
|
||||
let topicLabel: String
|
||||
let headline: String
|
||||
let countryPerspectives: [WPerspective]
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, headline
|
||||
case topicLabel = "topic_label"
|
||||
case countryPerspectives = "country_perspectives"
|
||||
}
|
||||
}
|
||||
struct WBriefing: Decodable, Sendable {
|
||||
let status: String
|
||||
let headlineOneliner: String?
|
||||
let topics: [WTopic]
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case status, topics
|
||||
case headlineOneliner = "headline_oneliner"
|
||||
}
|
||||
}
|
||||
|
||||
/// 이드 채팅 결과 — SSE 누적 답변 또는 unavailable(맥미니 대기/고장).
|
||||
struct ChatResult: Sendable {
|
||||
let answer: String
|
||||
let unavailable: Bool
|
||||
let reason: String?
|
||||
}
|
||||
|
||||
private struct AccessTokenBody: Decodable { let accessToken: String
|
||||
enum CodingKeys: String, CodingKey { case accessToken = "access_token" } }
|
||||
|
||||
enum WCError: Error, LocalizedError {
|
||||
case transport(String)
|
||||
case http(Int, String?)
|
||||
case decoding(String)
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .transport(let m): return "네트워크 오류: \(m)"
|
||||
case .http(let s, let m): return m ?? "서버 오류 (\(s))"
|
||||
case .decoding(let m): return "응답 해석 실패: \(m)"
|
||||
}
|
||||
}
|
||||
var isUnauthorized: Bool { if case .http(401, _) = self { return true }; return false }
|
||||
}
|
||||
|
||||
actor WatchClient {
|
||||
private let session: URLSession
|
||||
private var accessToken: String?
|
||||
|
||||
init() {
|
||||
let cfg = URLSessionConfiguration.default
|
||||
cfg.httpCookieStorage = .shared
|
||||
cfg.httpShouldSetCookies = true
|
||||
cfg.waitsForConnectivity = true
|
||||
session = URLSession(configuration: cfg)
|
||||
}
|
||||
|
||||
private func url(_ path: String) -> URL { URL(string: WatchAPI.baseString + "/" + path)! }
|
||||
|
||||
private func send(_ req: URLRequest) async throws -> (Data, HTTPURLResponse) {
|
||||
do {
|
||||
let (d, r) = try await session.data(for: req)
|
||||
guard let h = r as? HTTPURLResponse else { throw WCError.transport("no HTTP response") }
|
||||
return (d, h)
|
||||
} catch let e as WCError { throw e }
|
||||
catch { throw WCError.transport("\(error.localizedDescription)") }
|
||||
}
|
||||
|
||||
private static func decodeMessage(_ data: Data) -> String? {
|
||||
guard let o = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
|
||||
if let s = o["detail"] as? String { return s }
|
||||
if let d = o["detail"] as? [String: Any] { return d["message"] as? String }
|
||||
return nil
|
||||
}
|
||||
|
||||
// MARK: auth
|
||||
|
||||
func login(username: String, password: String, totp: String?) async throws {
|
||||
var req = URLRequest(url: url("auth/login"))
|
||||
req.httpMethod = "POST"
|
||||
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
var body: [String: Any] = ["username": username, "password": password]
|
||||
if let totp, !totp.isEmpty { body["totp_code"] = totp }
|
||||
req.httpBody = try JSONSerialization.data(withJSONObject: body)
|
||||
let (data, http) = try await send(req)
|
||||
guard (200..<300).contains(http.statusCode) else { throw WCError.http(http.statusCode, Self.decodeMessage(data)) }
|
||||
accessToken = try decodeToken(data)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func refresh() async throws -> String {
|
||||
var req = URLRequest(url: url("auth/refresh"))
|
||||
req.httpMethod = "POST"
|
||||
let (data, http) = try await send(req)
|
||||
guard (200..<300).contains(http.statusCode) else { throw WCError.http(http.statusCode, Self.decodeMessage(data)) }
|
||||
let t = try decodeToken(data)
|
||||
accessToken = t
|
||||
return t
|
||||
}
|
||||
|
||||
func logout() async {
|
||||
accessToken = nil
|
||||
var req = URLRequest(url: url("auth/logout")); req.httpMethod = "POST"
|
||||
_ = try? await send(req)
|
||||
}
|
||||
|
||||
private func decodeToken(_ data: Data) throws -> String {
|
||||
do { return try JSONDecoder().decode(AccessTokenBody.self, from: data).accessToken }
|
||||
catch { throw WCError.decoding("token: \(error)") }
|
||||
}
|
||||
|
||||
// MARK: authed request (401 → single refresh + retry)
|
||||
|
||||
private func authed(_ path: String, method: String = "GET", json: [String: Any]? = nil) async throws -> Data {
|
||||
func make(_ token: String?) throws -> URLRequest {
|
||||
var r = URLRequest(url: url(path))
|
||||
r.httpMethod = method
|
||||
if let token { r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
|
||||
if let json { r.httpBody = try JSONSerialization.data(withJSONObject: json); r.setValue("application/json", forHTTPHeaderField: "Content-Type") }
|
||||
return r
|
||||
}
|
||||
let (data, http) = try await send(make(accessToken))
|
||||
if http.statusCode == 401 {
|
||||
let newToken = try await refresh()
|
||||
let (d2, h2) = try await send(make(newToken))
|
||||
guard (200..<300).contains(h2.statusCode) else { throw WCError.http(h2.statusCode, Self.decodeMessage(d2)) }
|
||||
return d2
|
||||
}
|
||||
guard (200..<300).contains(http.statusCode) else { throw WCError.http(http.statusCode, Self.decodeMessage(data)) }
|
||||
return data
|
||||
}
|
||||
|
||||
// MARK: study cards
|
||||
|
||||
func dueCards() async throws -> [WCard] {
|
||||
let data = try await authed("study-cards/due")
|
||||
do { return try JSONDecoder().decode([WCard].self, from: data) }
|
||||
catch { throw WCError.decoding("due: \(error)") }
|
||||
}
|
||||
|
||||
func rate(cardId: Int, outcome: String) async throws {
|
||||
_ = try await authed("study-cards/\(cardId)/rate", method: "POST", json: ["outcome": outcome])
|
||||
}
|
||||
|
||||
func flag(cardId: Int) async throws {
|
||||
_ = try await authed("study-cards/\(cardId)", method: "PATCH", json: ["needs_review": true])
|
||||
}
|
||||
|
||||
// MARK: events (할일)
|
||||
|
||||
func events() async throws -> [WEvent] {
|
||||
let data = try await authed("events/today")
|
||||
do { return try JSONDecoder().decode(WEventList.self, from: data).items }
|
||||
catch { throw WCError.decoding("events: \(error)") }
|
||||
}
|
||||
|
||||
func completeEvent(id: Int) async throws {
|
||||
_ = try await authed("events/\(id)/complete", method: "POST")
|
||||
}
|
||||
|
||||
// MARK: briefing (모닝 브리핑)
|
||||
|
||||
func briefing() async throws -> WBriefing {
|
||||
let data = try await authed("briefing/latest")
|
||||
do { return try JSONDecoder().decode(WBriefing.self, from: data) }
|
||||
catch { throw WCError.decoding("briefing: \(error)") }
|
||||
}
|
||||
|
||||
// MARK: eid chat (SSE 누적 — 맥미니 26B via DS 프록시)
|
||||
|
||||
func chat(_ text: String) async throws -> ChatResult {
|
||||
let payload: [String: Any] = ["mode": "daily", "messages": [["role": "user", "content": text]]]
|
||||
func make(_ token: String?) throws -> URLRequest {
|
||||
var r = URLRequest(url: url("eid/chat"))
|
||||
r.httpMethod = "POST"
|
||||
r.timeoutInterval = 120
|
||||
if let token { r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
|
||||
r.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
r.setValue("text/event-stream", forHTTPHeaderField: "Accept")
|
||||
r.httpBody = try JSONSerialization.data(withJSONObject: payload)
|
||||
return r
|
||||
}
|
||||
var (stream, resp) = try await session.bytes(for: make(accessToken))
|
||||
if (resp as? HTTPURLResponse)?.statusCode == 401 {
|
||||
let t = try await refresh()
|
||||
(stream, resp) = try await session.bytes(for: make(t))
|
||||
}
|
||||
guard let http = resp as? HTTPURLResponse else { throw WCError.transport("no HTTP response") }
|
||||
let ctype = http.value(forHTTPHeaderField: "Content-Type") ?? ""
|
||||
|
||||
if ctype.contains("text/event-stream") {
|
||||
var answer = ""
|
||||
for try await line in stream.lines {
|
||||
guard line.hasPrefix("data:") else { continue }
|
||||
let body = line.dropFirst(5).trimmingCharacters(in: .whitespaces)
|
||||
if body == "[DONE]" || body.isEmpty { continue }
|
||||
if let d = body.data(using: .utf8),
|
||||
let obj = try? JSONSerialization.jsonObject(with: d) as? [String: Any],
|
||||
let choices = obj["choices"] as? [[String: Any]],
|
||||
let delta = choices.first?["delta"] as? [String: Any],
|
||||
let content = delta["content"] as? String {
|
||||
answer += content
|
||||
}
|
||||
}
|
||||
return ChatResult(answer: answer, unavailable: answer.isEmpty,
|
||||
reason: answer.isEmpty ? "빈 응답" : nil)
|
||||
}
|
||||
// 비-스트림 = unavailable JSONResponse (맥미니 대기/고장) — 사유 추출.
|
||||
var raw = Data()
|
||||
for try await b in stream { raw.append(b) }
|
||||
return ChatResult(answer: "", unavailable: true, reason: Self.decodeMessage(raw) ?? "이드 연결 불가")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import SwiftUI
|
||||
|
||||
/// 워치 홈 = 4기능 메뉴. 작은 화면이라 큰 탭타깃 리스트.
|
||||
struct RootMenu: View {
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
List {
|
||||
NavigationLink { EidView() } label: {
|
||||
MenuRow(symbol: "bubble.left.and.bubble.right.fill", title: "이드", sub: "AI 채팅")
|
||||
}
|
||||
NavigationLink { StudyView() } label: {
|
||||
MenuRow(symbol: "rectangle.on.rectangle.angled.fill", title: "공부", sub: "암기 카드")
|
||||
}
|
||||
NavigationLink { TodoView() } label: {
|
||||
MenuRow(symbol: "checklist", title: "할 일", sub: "오늘")
|
||||
}
|
||||
NavigationLink { BriefingView() } label: {
|
||||
MenuRow(symbol: "newspaper.fill", title: "브리핑", sub: "모닝")
|
||||
}
|
||||
}
|
||||
.navigationTitle("DS")
|
||||
}
|
||||
.tint(WT.accent)
|
||||
}
|
||||
}
|
||||
|
||||
struct MenuRow: View {
|
||||
let symbol: String
|
||||
let title: String
|
||||
let sub: String
|
||||
var body: some View {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: symbol)
|
||||
.font(.system(size: 16))
|
||||
.foregroundStyle(WT.accent)
|
||||
.frame(width: 24)
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(title).font(.system(size: 16, weight: .semibold)).foregroundStyle(WT.ink)
|
||||
Text(sub).font(.system(size: 11)).foregroundStyle(WT.muted)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 3)
|
||||
}
|
||||
}
|
||||
|
||||
#Preview { RootMenu() }
|
||||
@@ -0,0 +1,160 @@
|
||||
import SwiftUI
|
||||
|
||||
// MARK: - 할 일 (Todo) — GET /events/today + 탭하면 POST /complete
|
||||
|
||||
struct TodoView: View {
|
||||
@Environment(WatchModel.self) private var model
|
||||
@State private var loaded = false
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if model.eventsLoading && model.events.isEmpty {
|
||||
ProgressView()
|
||||
} else if let e = model.eventsError, model.events.isEmpty {
|
||||
retry("불러오기 실패\n\(e)") { await model.loadEvents() }
|
||||
} else if model.events.isEmpty {
|
||||
retry("오늘 할 일이 없어요", color: WT.muted) { await model.loadEvents() }
|
||||
} else {
|
||||
List(model.events) { ev in
|
||||
Button {
|
||||
if !ev.isDone { Haptics.success() }
|
||||
Task { await model.completeEvent(ev.id) }
|
||||
} label: {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: ev.isDone ? "checkmark.circle.fill" : "circle")
|
||||
.font(.system(size: 17))
|
||||
.foregroundStyle(ev.isDone ? WT.accent : WT.muted)
|
||||
Text(ev.title)
|
||||
.font(.system(size: 14))
|
||||
.foregroundStyle(ev.isDone ? WT.muted : WT.ink)
|
||||
.strikethrough(ev.isDone, color: WT.muted)
|
||||
Spacer()
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
}
|
||||
.navigationTitle("할 일")
|
||||
.task { if !loaded { loaded = true; await model.loadEvents() } }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 브리핑 (모닝) — GET /briefing/latest, 글랜스→정독 스크롤
|
||||
|
||||
struct BriefingView: View {
|
||||
@Environment(WatchModel.self) private var model
|
||||
@State private var loaded = false
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
if model.briefingLoading && model.briefing == nil {
|
||||
ProgressView().padding(.top, 20)
|
||||
} else if let e = model.briefingError, model.briefing == nil {
|
||||
retry("불러오기 실패\n\(e)") { await model.loadBriefing() }
|
||||
} else if let b = model.briefing, !b.topics.isEmpty {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
if let one = b.headlineOneliner, !one.isEmpty {
|
||||
Text(one).font(.system(size: 15, weight: .semibold)).foregroundStyle(WT.ink)
|
||||
}
|
||||
ForEach(b.topics) { t in
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
Text(t.headline).font(.system(size: 13, weight: .semibold)).foregroundStyle(WT.ink)
|
||||
ForEach(t.countryPerspectives) { p in
|
||||
HStack(alignment: .top, spacing: 5) {
|
||||
Text(p.country.uppercased())
|
||||
.font(.system(size: 9, weight: .bold)).foregroundStyle(WT.accent)
|
||||
.frame(minWidth: 22, alignment: .leading)
|
||||
Text(p.summary).font(.system(size: 11)).foregroundStyle(WT.muted).lineLimit(4)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(8)
|
||||
.background(WT.card, in: RoundedRectangle(cornerRadius: 12))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
retry("오늘 브리핑이 아직 없어요", color: WT.muted) { await model.loadBriefing() }
|
||||
}
|
||||
}
|
||||
.navigationTitle("브리핑")
|
||||
.task { if !loaded { loaded = true; await model.loadBriefing() } }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 이드 (AI 채팅) — POST /eid/chat (맥미니 26B via DS 프록시)
|
||||
|
||||
struct EidView: View {
|
||||
@Environment(WatchModel.self) private var model
|
||||
@State private var draft = ""
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 8) {
|
||||
HStack(spacing: 6) {
|
||||
TextField("물어보기…", text: $draft)
|
||||
.textFieldStyle(.plain)
|
||||
.padding(8)
|
||||
.background(WT.card, in: RoundedRectangle(cornerRadius: 10))
|
||||
Button {
|
||||
let t = draft; draft = ""
|
||||
Task { await model.sendChat(t) }
|
||||
} label: {
|
||||
Image(systemName: "arrow.up.circle.fill").font(.system(size: 22))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(WT.accent)
|
||||
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.chatSending)
|
||||
}
|
||||
if model.chatSending {
|
||||
HStack(spacing: 6) {
|
||||
ProgressView().controlSize(.small)
|
||||
Text("이드 생각 중…").font(.system(size: 11)).foregroundStyle(WT.muted)
|
||||
}
|
||||
}
|
||||
ForEach(model.chatTurns.reversed()) { turn in
|
||||
ChatBubble(turn: turn)
|
||||
}
|
||||
if model.chatTurns.isEmpty && !model.chatSending {
|
||||
Text("음성·키보드로 묻고\n맥미니 26B 가 답합니다")
|
||||
.font(.system(size: 11)).foregroundStyle(WT.muted)
|
||||
.multilineTextAlignment(.center).padding(.top, 8)
|
||||
}
|
||||
}
|
||||
}
|
||||
.navigationTitle("이드")
|
||||
}
|
||||
}
|
||||
|
||||
private struct ChatBubble: View {
|
||||
let turn: WatchModel.ChatTurn
|
||||
var body: some View {
|
||||
let isUser = turn.role == "user"
|
||||
let isError = turn.role == "error"
|
||||
HStack {
|
||||
if isUser { Spacer(minLength: 24) }
|
||||
Text(turn.text)
|
||||
.font(.system(size: 12))
|
||||
.foregroundStyle(isUser ? .black : (isError ? WT.danger : WT.ink))
|
||||
.frame(maxWidth: .infinity, alignment: isUser ? .trailing : .leading)
|
||||
.padding(8)
|
||||
.background(isUser ? WT.accent : (isError ? WT.danger.opacity(0.15) : WT.card),
|
||||
in: RoundedRectangle(cornerRadius: 10))
|
||||
if !isUser { Spacer(minLength: 24) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 공용 상태/재시도
|
||||
|
||||
@MainActor
|
||||
private func retry(_ text: String, color: Color = WT.danger, _ action: @escaping () async -> Void) -> some View {
|
||||
VStack(spacing: 10) {
|
||||
Text(text).font(.system(size: 13)).foregroundStyle(color).multilineTextAlignment(.center)
|
||||
Button("다시 불러오기") { Task { await action() } }.tint(WT.accent)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.horizontal, 6).padding(.top, 16)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import SwiftUI
|
||||
|
||||
/// 암기 카드 학습 (라이브) — 능동 회상(앞면 cue → 답 보기 → 뒷면 fact) + 2단 평정(다시/알아요).
|
||||
/// 확정 워치 설계(B5): 2단 평정만(애매는 웹), '이 카드 이상해요' 플래그(교정은 웹/폰), 다크 OLED.
|
||||
/// 데이터 = GET /study-cards/due, 평정 = POST /{id}/rate (correct/wrong), 플래그 = PATCH needs_review.
|
||||
struct StudyView: View {
|
||||
@Environment(WatchModel.self) private var model
|
||||
@State private var index = 0
|
||||
@State private var revealed = false
|
||||
@State private var correctCount = 0
|
||||
@State private var flagged = false
|
||||
@State private var loaded = false
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if model.studyLoading && model.cards.isEmpty {
|
||||
ProgressView()
|
||||
} else if let err = model.studyError, model.cards.isEmpty {
|
||||
stateText("불러오기 실패\n\(err)", color: WT.danger, retry: true)
|
||||
} else if model.cards.isEmpty {
|
||||
stateText("복습할 카드가 없어요", color: WT.muted, retry: true)
|
||||
} else if index >= model.cards.count {
|
||||
ResultView(total: model.cards.count, correct: correctCount) { Task { await reload() } }
|
||||
} else {
|
||||
cardScreen(model.cards[index])
|
||||
}
|
||||
}
|
||||
.navigationTitle("공부")
|
||||
.task { if !loaded { loaded = true; await model.loadDue(); reset() } }
|
||||
}
|
||||
|
||||
private func cardScreen(_ c: WCard) -> some View {
|
||||
VStack(spacing: 8) {
|
||||
HStack {
|
||||
Text("\(index + 1) / \(model.cards.count)").font(.system(size: 11)).foregroundStyle(WT.muted)
|
||||
Spacer()
|
||||
Button {
|
||||
flagged = true
|
||||
Haptics.click()
|
||||
Task { await model.flag(cardId: c.id) }
|
||||
} label: {
|
||||
Image(systemName: flagged ? "flag.fill" : "flag")
|
||||
.font(.system(size: 11)).foregroundStyle(flagged ? WT.amber : WT.muted)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
|
||||
ScrollView {
|
||||
VStack(spacing: 10) {
|
||||
Text(c.cue)
|
||||
.font(.system(size: 17, weight: .semibold)).foregroundStyle(WT.ink)
|
||||
.multilineTextAlignment(.center)
|
||||
if revealed {
|
||||
Divider().overlay(WT.muted.opacity(0.4))
|
||||
Text(c.fact)
|
||||
.font(.system(size: 15)).foregroundStyle(WT.accent)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(12)
|
||||
.background(WT.card, in: RoundedRectangle(cornerRadius: 14))
|
||||
}
|
||||
|
||||
if revealed {
|
||||
HStack(spacing: 8) {
|
||||
rateButton("다시", sub: "내일", color: WT.danger) { advance(c, correct: false) }
|
||||
rateButton("알아요", sub: nil, color: WT.accent) { advance(c, correct: true) }
|
||||
}
|
||||
} else {
|
||||
Button { withAnimation(.easeOut(duration: 0.15)) { revealed = true } } label: {
|
||||
Text("답 보기").frame(maxWidth: .infinity)
|
||||
}
|
||||
.tint(WT.accent)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 4)
|
||||
}
|
||||
|
||||
private func rateButton(_ title: String, sub: String?, color: Color, _ action: @escaping () -> Void) -> some View {
|
||||
Button(action: action) {
|
||||
VStack(spacing: 1) {
|
||||
Text(title).font(.system(size: 14, weight: .semibold))
|
||||
if let sub { Text(sub).font(.system(size: 9)).opacity(0.8) }
|
||||
}
|
||||
.frame(maxWidth: .infinity).padding(.vertical, 2)
|
||||
}
|
||||
.tint(color)
|
||||
}
|
||||
|
||||
private func stateText(_ text: String, color: Color, retry: Bool) -> some View {
|
||||
VStack(spacing: 10) {
|
||||
Text(text).font(.system(size: 13)).foregroundStyle(color).multilineTextAlignment(.center)
|
||||
if retry { Button("다시 불러오기") { Task { await reload() } }.tint(WT.accent) }
|
||||
}
|
||||
.padding(.horizontal, 6)
|
||||
}
|
||||
|
||||
private func advance(_ c: WCard, correct: Bool) {
|
||||
if correct { correctCount += 1 }
|
||||
Haptics.success() // 평정 손목 탭 (다시/알아요 동일 확정 피드백)
|
||||
Task { await model.rate(cardId: c.id, outcome: correct ? "correct" : "wrong") }
|
||||
flagged = false
|
||||
revealed = false
|
||||
index += 1
|
||||
}
|
||||
|
||||
private func reload() async { await model.loadDue(); reset() }
|
||||
private func reset() { index = 0; revealed = false; correctCount = 0; flagged = false }
|
||||
}
|
||||
|
||||
/// 세션 결과 — 정직한 tally만(서버 미제공 streak 등 날조 X).
|
||||
struct ResultView: View {
|
||||
let total: Int
|
||||
let correct: Int
|
||||
let onRestart: () -> Void
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 10) {
|
||||
Image(systemName: "checkmark.seal.fill").font(.system(size: 30)).foregroundStyle(WT.accent)
|
||||
Text("오늘 복습 완료").font(.system(size: 16, weight: .semibold)).foregroundStyle(WT.ink)
|
||||
Text("\(correct) / \(total) 알아요").font(.system(size: 13)).foregroundStyle(WT.muted)
|
||||
Text("애매하거나 몰랐던 카드는 내일 다시 만나요")
|
||||
.font(.system(size: 11)).foregroundStyle(WT.muted).multilineTextAlignment(.center)
|
||||
Button("다시 불러오기", action: onRestart).tint(WT.accent).padding(.top, 4)
|
||||
}
|
||||
.frame(maxWidth: .infinity).padding(.vertical, 6)
|
||||
}
|
||||
.navigationTitle("결과")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import SwiftUI
|
||||
import Observation
|
||||
|
||||
/// 워치 앱 상태. 부팅 시 refresh 쿠키로 무로그인 복귀 시도 → 실패 시 로그인. 공부 카드 라이브 결선.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class WatchModel {
|
||||
enum Phase: Equatable { case checking, loggedOut, ready }
|
||||
|
||||
var phase: Phase = .checking
|
||||
var loginError: String?
|
||||
|
||||
// 공부(study)
|
||||
var cards: [WCard] = []
|
||||
var studyLoading = false
|
||||
var studyError: String?
|
||||
|
||||
// 할일(events)
|
||||
var events: [WEvent] = []
|
||||
var eventsLoading = false
|
||||
var eventsError: String?
|
||||
|
||||
// 브리핑
|
||||
var briefing: WBriefing?
|
||||
var briefingLoading = false
|
||||
var briefingError: String?
|
||||
|
||||
// 이드(chat)
|
||||
struct ChatTurn: Identifiable, Sendable { let id: Int; let role: String; let text: String }
|
||||
var chatTurns: [ChatTurn] = []
|
||||
var chatSending = false
|
||||
private var chatSeq = 0
|
||||
|
||||
private let client = WatchClient()
|
||||
|
||||
func bootstrap() async {
|
||||
do { _ = try await client.refresh(); phase = .ready }
|
||||
catch { phase = .loggedOut } // 쿠키 없음/만료 = 정상 로그인 흐름
|
||||
}
|
||||
|
||||
func login(username: String, password: String, totp: String?) async {
|
||||
loginError = nil
|
||||
let code = totp?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
do {
|
||||
try await client.login(username: username, password: password,
|
||||
totp: (code?.isEmpty ?? true) ? nil : code)
|
||||
phase = .ready
|
||||
} catch {
|
||||
loginError = (error as? LocalizedError)?.errorDescription ?? "\(error)"
|
||||
}
|
||||
}
|
||||
|
||||
func logout() async {
|
||||
await client.logout()
|
||||
cards = []; studyError = nil
|
||||
phase = .loggedOut
|
||||
}
|
||||
|
||||
func loadDue() async {
|
||||
studyLoading = true; studyError = nil
|
||||
do { cards = try await client.dueCards() }
|
||||
catch let e as WCError where e.isUnauthorized { phase = .loggedOut }
|
||||
catch { studyError = (error as? LocalizedError)?.errorDescription ?? "\(error)" }
|
||||
studyLoading = false
|
||||
}
|
||||
|
||||
/// 평정 전송 (correct/wrong). 실패해도 학습 흐름은 진행(다음 카드) — 오류만 표시.
|
||||
func rate(cardId: Int, outcome: String) async {
|
||||
do { try await client.rate(cardId: cardId, outcome: outcome) }
|
||||
catch let e as WCError where e.isUnauthorized { phase = .loggedOut }
|
||||
catch { studyError = (error as? LocalizedError)?.errorDescription ?? "\(error)" }
|
||||
}
|
||||
|
||||
func flag(cardId: Int) async {
|
||||
do { try await client.flag(cardId: cardId) }
|
||||
catch { studyError = (error as? LocalizedError)?.errorDescription ?? "\(error)" }
|
||||
}
|
||||
|
||||
// MARK: 할일(events)
|
||||
|
||||
func loadEvents() async {
|
||||
eventsLoading = true; eventsError = nil
|
||||
do { events = try await client.events() }
|
||||
catch let e as WCError where e.isUnauthorized { phase = .loggedOut }
|
||||
catch { eventsError = (error as? LocalizedError)?.errorDescription ?? "\(error)" }
|
||||
eventsLoading = false
|
||||
}
|
||||
|
||||
func completeEvent(_ id: Int) async {
|
||||
do { try await client.completeEvent(id: id); await loadEvents() }
|
||||
catch let e as WCError where e.isUnauthorized { phase = .loggedOut }
|
||||
catch { eventsError = (error as? LocalizedError)?.errorDescription ?? "\(error)" }
|
||||
}
|
||||
|
||||
// MARK: 브리핑
|
||||
|
||||
func loadBriefing() async {
|
||||
briefingLoading = true; briefingError = nil
|
||||
do { briefing = try await client.briefing() }
|
||||
catch let e as WCError where e.isUnauthorized { phase = .loggedOut }
|
||||
catch { briefingError = (error as? LocalizedError)?.errorDescription ?? "\(error)" }
|
||||
briefingLoading = false
|
||||
}
|
||||
|
||||
// MARK: 이드(chat)
|
||||
|
||||
func sendChat(_ text: String) async {
|
||||
let t = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !t.isEmpty, !chatSending else { return }
|
||||
chatSeq += 1; chatTurns.append(.init(id: chatSeq, role: "user", text: t))
|
||||
chatSending = true
|
||||
do {
|
||||
let result = try await client.chat(t)
|
||||
chatSeq += 1
|
||||
if result.unavailable {
|
||||
chatTurns.append(.init(id: chatSeq, role: "error", text: result.reason ?? "이드 연결 불가"))
|
||||
} else {
|
||||
chatTurns.append(.init(id: chatSeq, role: "assistant", text: result.answer))
|
||||
}
|
||||
} catch let e as WCError where e.isUnauthorized {
|
||||
phase = .loggedOut
|
||||
} catch {
|
||||
chatSeq += 1
|
||||
chatTurns.append(.init(id: chatSeq, role: "error",
|
||||
text: (error as? LocalizedError)?.errorDescription ?? "\(error)"))
|
||||
}
|
||||
chatSending = false
|
||||
}
|
||||
}
|
||||
|
||||
/// 워치 1회 로그인 (refresh 쿠키 7일 → 사실상 주1회). TOTP 사용 계정이라 6자리 코드 입력란 포함.
|
||||
struct LoginView: View {
|
||||
@Environment(WatchModel.self) private var model
|
||||
@State private var username = ""
|
||||
@State private var password = ""
|
||||
@State private var totp = ""
|
||||
@State private var busy = false
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 8) {
|
||||
Text("DS 로그인").font(.system(size: 16, weight: .semibold)).foregroundStyle(WT.ink)
|
||||
TextField("아이디", text: $username)
|
||||
.textContentType(.username)
|
||||
SecureField("비밀번호", text: $password)
|
||||
TextField("OTP 6자리", text: $totp)
|
||||
if let err = model.loginError {
|
||||
Text(err).font(.system(size: 11)).foregroundStyle(WT.danger).multilineTextAlignment(.center)
|
||||
}
|
||||
Button {
|
||||
busy = true
|
||||
Task { await model.login(username: username, password: password, totp: totp); busy = false }
|
||||
} label: {
|
||||
if busy { ProgressView() } else { Text("로그인").frame(maxWidth: .infinity) }
|
||||
}
|
||||
.tint(WT.accent)
|
||||
.disabled(busy || username.isEmpty || password.isEmpty)
|
||||
}
|
||||
.padding(.horizontal, 4)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import SwiftUI
|
||||
|
||||
/// 워치 다크 OLED 토큰 (시안 watch-app: --wgreen #37d67a). 검정 배경 = OLED 절전·대비.
|
||||
enum WT {
|
||||
static let bg = Color.black
|
||||
static let card = Color(white: 0.12)
|
||||
static let accent = Color(red: 0x37 / 255, green: 0xd6 / 255, blue: 0x7a / 255) // #37d67a
|
||||
static let ink = Color.white
|
||||
static let muted = Color(white: 0.62)
|
||||
static let amber = Color(red: 0xf2 / 255, green: 0xb6 / 255, blue: 0x3c / 255)
|
||||
static let danger = Color(red: 0xe5 / 255, green: 0x6a / 255, blue: 0x5a / 255)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
# DS Apple Watch 앱 (단일 타깃 standalone watchOS, WKApplication). 맥/아이폰은 웹 래퍼로 가고
|
||||
# 순수 네이티브는 워치 전용(2026-06-15 사용자 결정). 시뮬레이터 빌드·스크린샷으로 검증, 실기기
|
||||
# 설치는 사용자 Xcode 서명. project.yml = source of truth, *.xcodeproj/Support 는 생성물(gitignore).
|
||||
name: DSWatch
|
||||
options:
|
||||
bundleIdPrefix: net.hyungi
|
||||
deploymentTarget:
|
||||
watchOS: "11.0"
|
||||
createIntermediateGroups: true
|
||||
minimumXcodeGenVersion: "2.40.0"
|
||||
|
||||
settings:
|
||||
base:
|
||||
SWIFT_VERSION: "6.0"
|
||||
SWIFT_STRICT_CONCURRENCY: complete
|
||||
WATCHOS_DEPLOYMENT_TARGET: "11.0"
|
||||
CODE_SIGN_STYLE: Automatic
|
||||
# 실기기 설치 시 Xcode 에서 Signing → 본인 Apple ID 팀 선택하면 자동 서명.
|
||||
# (헤드리스 시뮬 빌드는 xcodebuild 에 CODE_SIGNING_ALLOWED=NO 를 CLI 로 전달)
|
||||
|
||||
targets:
|
||||
DSWatch:
|
||||
type: application
|
||||
platform: watchOS
|
||||
deploymentTarget: "11.0"
|
||||
sources:
|
||||
- path: Sources
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_BUNDLE_IDENTIFIER: net.hyungi.dswatch
|
||||
PRODUCT_NAME: DS
|
||||
GENERATE_INFOPLIST_FILE: "NO"
|
||||
MARKETING_VERSION: "0.1"
|
||||
CURRENT_PROJECT_VERSION: "1"
|
||||
TARGETED_DEVICE_FAMILY: "4" # Apple Watch
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
|
||||
info:
|
||||
path: Support/Info.plist
|
||||
properties:
|
||||
CFBundleDisplayName: DS
|
||||
CFBundleName: DS
|
||||
CFBundleVersion: "1"
|
||||
CFBundleShortVersionString: "0.1"
|
||||
WKApplication: true # 단일 타깃 standalone 워치 앱 (컴패니언 불요)
|
||||
WKWatchOnly: true # 컴패니언 iOS 앱 없는 watch-only (설치 필수 키)
|
||||
UISupportedInterfaceOrientations:
|
||||
- UIInterfaceOrientationPortrait
|
||||
|
||||
schemes:
|
||||
DSWatch:
|
||||
build:
|
||||
targets:
|
||||
DSWatch: all
|
||||
run:
|
||||
config: Debug
|
||||
@@ -2,7 +2,7 @@
|
||||
import { page } from '$app/stores';
|
||||
import { goto } from '$app/navigation';
|
||||
import { api } from '$lib/api';
|
||||
import { ChevronRight, ChevronDown, FolderOpen, FolderTree, Inbox, Clock, Mail, Scale, StickyNote, GraduationCap, CalendarCheck, MessageCircle, Hash, HardHat } from 'lucide-svelte';
|
||||
import { ChevronRight, ChevronDown, FolderOpen, FolderTree, Inbox, Clock, Mail, Scale, StickyNote, GraduationCap, CalendarCheck, MessageCircle, Hash } from 'lucide-svelte';
|
||||
|
||||
let tree = $state([]);
|
||||
let loading = $state(true);
|
||||
@@ -195,13 +195,6 @@
|
||||
>
|
||||
<FolderTree size={14} /> 자료실
|
||||
</a>
|
||||
<a
|
||||
href="/safety"
|
||||
class="w-full flex items-center gap-2 px-3 py-1.5 rounded-md text-sm transition-colors
|
||||
{$page.url.pathname.startsWith('/safety') ? 'bg-accent/15 text-accent' : 'text-dim hover:bg-surface hover:text-text'}"
|
||||
>
|
||||
<HardHat size={14} /> 안전 자료실
|
||||
</a>
|
||||
<a
|
||||
href="/clause"
|
||||
class="w-full flex items-center gap-2 px-3 py-1.5 rounded-md text-sm transition-colors
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
<script>
|
||||
// 안전 자료실 (safety-library-1 Phase 3) — 재해/법령·지침/서적·표준·매뉴얼 3탭.
|
||||
import { page } from '$app/stores';
|
||||
|
||||
const TABS = [
|
||||
{ href: '/safety/incidents', label: '재해사례' },
|
||||
{ href: '/safety/laws', label: '법령·지침' },
|
||||
{ href: '/safety/materials', label: '서적·표준·매뉴얼' },
|
||||
];
|
||||
</script>
|
||||
|
||||
<div class="max-w-5xl mx-auto px-4 py-5 flex flex-col gap-4">
|
||||
<header>
|
||||
<h1 class="text-lg font-bold text-text">안전 자료실</h1>
|
||||
<p class="text-xs text-dim mt-0.5">재해사례·법령·지침·표준 — 자료유형(material_type) 축 기반</p>
|
||||
</header>
|
||||
|
||||
<nav class="flex gap-1 border-b border-default" aria-label="안전 자료실 탭">
|
||||
{#each TABS as tab}
|
||||
<a
|
||||
href={tab.href}
|
||||
aria-current={$page.url.pathname === tab.href ? 'page' : undefined}
|
||||
class="px-3 py-2 text-sm font-medium border-b-2 -mb-px transition-colors
|
||||
{$page.url.pathname === tab.href
|
||||
? 'border-accent text-accent'
|
||||
: 'border-transparent text-dim hover:text-text'}"
|
||||
>
|
||||
{tab.label}
|
||||
</a>
|
||||
{/each}
|
||||
</nav>
|
||||
|
||||
<slot />
|
||||
</div>
|
||||
@@ -1,9 +0,0 @@
|
||||
<script>
|
||||
// /safety 진입 = 재해 탭 redirect (plan: +page=재해 탭 redirect)
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
|
||||
onMount(() => {
|
||||
goto('/safety/incidents', { replaceState: true });
|
||||
});
|
||||
</script>
|
||||
@@ -1,75 +0,0 @@
|
||||
<script>
|
||||
// 안전 자료실 공용 목록 — material_type + jurisdiction 필터로 GET /documents/ 조회.
|
||||
// C-1 계약: material_type 지정 = 기본 exclude(news·law_monitor·note) 해제 (documents.py list_documents).
|
||||
import { api } from '$lib/api';
|
||||
import { addToast } from '$lib/stores/toast';
|
||||
import DocumentCard from '$lib/components/DocumentCard.svelte';
|
||||
|
||||
let { materialType, jurisdiction = '' } = $props();
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
let docs = $state([]);
|
||||
let total = $state(0);
|
||||
let nextPage = $state(1);
|
||||
let loading = $state(false);
|
||||
|
||||
async function load(reset = false) {
|
||||
loading = true;
|
||||
const pageToLoad = reset ? 1 : nextPage;
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.set('material_type', materialType);
|
||||
if (jurisdiction) params.set('jurisdiction', jurisdiction);
|
||||
params.set('page', String(pageToLoad));
|
||||
params.set('page_size', String(PAGE_SIZE));
|
||||
const result = await api(`/documents/?${params}`);
|
||||
docs = reset ? result.items : [...docs, ...result.items];
|
||||
total = result.total;
|
||||
nextPage = pageToLoad + 1;
|
||||
} catch {
|
||||
addToast('error', '안전 자료 로딩 실패');
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
// 필터 변경 시 1페이지부터 재조회 (materialType/jurisdiction 읽기 = 반응 트리거)
|
||||
void materialType;
|
||||
void jurisdiction;
|
||||
docs = [];
|
||||
load(true);
|
||||
});
|
||||
|
||||
let hasMore = $derived(docs.length < total);
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
{#if !loading || docs.length > 0}
|
||||
<p class="text-xs text-dim tabular-nums">총 {total.toLocaleString()}건</p>
|
||||
{/if}
|
||||
|
||||
{#if docs.length > 0}
|
||||
<div class="flex flex-col gap-2">
|
||||
{#each docs as doc (doc.id)}
|
||||
<DocumentCard {doc} />
|
||||
{/each}
|
||||
</div>
|
||||
{:else if !loading}
|
||||
<div class="py-12 text-center text-sm text-dim">
|
||||
해당 조건의 자료가 없습니다.
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if loading}
|
||||
<div class="py-6 text-center text-sm text-dim">불러오는 중…</div>
|
||||
{:else if hasMore}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => load(false)}
|
||||
class="self-center px-4 py-1.5 rounded-md text-sm text-dim border border-default hover:bg-surface hover:text-text transition-colors"
|
||||
>
|
||||
더 보기 ({docs.length}/{total.toLocaleString()})
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,29 +0,0 @@
|
||||
<script>
|
||||
// 재해사례 탭 — material_type=incident (KOSHA 사고사망·재해사례·CSB 등).
|
||||
// 케이스 그룹핑(boardno 본문+첨부 1카드)은 API 확장 필요라 후속(DS freeze 하 백엔드 무변경).
|
||||
import SafetyDocList from '../SafetyDocList.svelte';
|
||||
|
||||
const JURISDICTIONS = [
|
||||
{ value: '', label: '전체' },
|
||||
{ value: 'KR', label: 'KR' },
|
||||
{ value: 'US', label: 'US' },
|
||||
];
|
||||
let jurisdiction = $state('');
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="flex items-center gap-1.5" role="group" aria-label="관할 필터">
|
||||
{#each JURISDICTIONS as j}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (jurisdiction = j.value)}
|
||||
class="px-2.5 py-1 rounded-full text-xs font-medium transition-colors
|
||||
{jurisdiction === j.value ? 'bg-accent/15 text-accent' : 'text-dim hover:bg-surface hover:text-text'}"
|
||||
>
|
||||
{j.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<SafetyDocList materialType="incident" {jurisdiction} />
|
||||
</div>
|
||||
@@ -1,48 +0,0 @@
|
||||
<script>
|
||||
// 법령·지침 탭 — 법령(law, 버전체인 current 만 코퍼스 노출) / 지침(guide, KOSHA GUIDE 등).
|
||||
// 법령 기본 관할 = KR (plan: country 누락 = KR 정규화). version_status 뱃지는 API 확장 후속.
|
||||
import SafetyDocList from '../SafetyDocList.svelte';
|
||||
|
||||
const KINDS = [
|
||||
{ value: 'law', label: '법령' },
|
||||
{ value: 'guide', label: '지침' },
|
||||
];
|
||||
const JURISDICTIONS = [
|
||||
{ value: 'KR', label: 'KR' },
|
||||
{ value: 'US', label: 'US' },
|
||||
{ value: '', label: '전체' },
|
||||
];
|
||||
let kind = $state('law');
|
||||
let jurisdiction = $state('KR');
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="flex items-center justify-between flex-wrap gap-2">
|
||||
<div class="flex items-center gap-1" role="group" aria-label="자료유형">
|
||||
{#each KINDS as k}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (kind = k.value)}
|
||||
class="px-3 py-1 rounded-md text-sm font-medium transition-colors
|
||||
{kind === k.value ? 'bg-accent/15 text-accent' : 'text-dim hover:bg-surface hover:text-text'}"
|
||||
>
|
||||
{k.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="flex items-center gap-1.5" role="group" aria-label="관할 필터">
|
||||
{#each JURISDICTIONS as j}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (jurisdiction = j.value)}
|
||||
class="px-2.5 py-1 rounded-full text-xs font-medium transition-colors
|
||||
{jurisdiction === j.value ? 'bg-accent/15 text-accent' : 'text-dim hover:bg-surface hover:text-text'}"
|
||||
>
|
||||
{j.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SafetyDocList materialType={kind} {jurisdiction} />
|
||||
</div>
|
||||
@@ -1,29 +0,0 @@
|
||||
<script>
|
||||
// 서적·표준·매뉴얼 탭 — 필터 프리셋(전용 뷰는 50건+ 게이트 뒤, plan Phase 3).
|
||||
import SafetyDocList from '../SafetyDocList.svelte';
|
||||
|
||||
const KINDS = [
|
||||
{ value: 'standard', label: '표준 (NB 등)' },
|
||||
{ value: 'book', label: '서적' },
|
||||
{ value: 'manual', label: '매뉴얼' },
|
||||
{ value: 'paper', label: '논문' },
|
||||
];
|
||||
let kind = $state('standard');
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="flex items-center gap-1" role="group" aria-label="자료유형">
|
||||
{#each KINDS as k}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (kind = k.value)}
|
||||
class="px-3 py-1 rounded-md text-sm font-medium transition-colors
|
||||
{kind === k.value ? 'bg-accent/15 text-accent' : 'text-dim hover:bg-surface hover:text-text'}"
|
||||
>
|
||||
{k.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<SafetyDocList materialType={kind} />
|
||||
</div>
|
||||
@@ -1,58 +1,13 @@
|
||||
<script>
|
||||
// /study — 학습 hub + 데일리 랜딩('오늘의 공부' 대시보드).
|
||||
// 상단 = 이론 홈(진도·오늘의 개념·복습 due, 재노출 트리거). 하단 = 기존 모드 진입.
|
||||
// /study — 학습 hub.
|
||||
// 주제로 보기(퀴즈·복습·통계) / 자료 학습 / 필사 세션 / 암기카드 검수.
|
||||
import { onMount } from 'svelte';
|
||||
import { api } from '$lib/api';
|
||||
import { addToast } from '$lib/stores/toast';
|
||||
import { BookOpen, PenLine, GraduationCap, FolderKanban, Layers, Repeat, Flag, Inbox, Activity, CalendarCheck, Target } from 'lucide-svelte';
|
||||
import { BookOpen, PenLine, GraduationCap, FolderKanban, Layers, Repeat, Flag, Inbox, Activity } from 'lucide-svelte';
|
||||
|
||||
let cardReviewCount = $state(0);
|
||||
let questionFlagCount = $state(0);
|
||||
|
||||
// 오늘의 공부 (이론 홈)
|
||||
let curriculum = $state(null);
|
||||
let todayConcepts = $state([]);
|
||||
let weakConcepts = $state([]); // 약점 개념(관련 기출 정답률 낮음)
|
||||
let dashLoading = $state(true);
|
||||
|
||||
let readPct = $derived(
|
||||
curriculum && curriculum.total ? Math.round((curriculum.read / curriculum.total) * 100) : 0
|
||||
);
|
||||
|
||||
async function loadDashboard() {
|
||||
dashLoading = true;
|
||||
try {
|
||||
const [cur, today] = await Promise.all([
|
||||
api('/study/curriculum'),
|
||||
api('/study/today-concepts?limit=6'),
|
||||
]);
|
||||
curriculum = cur;
|
||||
todayConcepts = today?.concepts ?? [];
|
||||
} catch {
|
||||
// 코어 대시보드 실패해도 허브 나머지는 동작 (조용히)
|
||||
} finally {
|
||||
dashLoading = false;
|
||||
}
|
||||
// 약점 개념 = 비차단(신규 엔드포인트 실패해도 코어 대시보드 블랙아웃 방지)
|
||||
try {
|
||||
const weak = await api('/study/concepts/weakness-map?limit=5');
|
||||
weakConcepts = weak?.weak ?? [];
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function markRead(doc) {
|
||||
try {
|
||||
await api(`/study/concepts/${doc.doc_id}/read`, { method: 'POST' });
|
||||
todayConcepts = todayConcepts.filter((c) => c.doc_id !== doc.doc_id);
|
||||
addToast('success', `회독: ${doc.title}`);
|
||||
loadDashboard(); // 진도 갱신
|
||||
} catch {
|
||||
addToast('error', '회독 처리 실패');
|
||||
}
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
loadDashboard();
|
||||
try {
|
||||
const r = await api('/study-cards/needs-review/count');
|
||||
cardReviewCount = r?.count ?? 0;
|
||||
@@ -72,80 +27,6 @@
|
||||
<p class="text-sm text-dim mt-1">주제별 퀴즈·복습(SRS)·통계 / 학습 자료 회독 / 손글씨 필사 세션.</p>
|
||||
</header>
|
||||
|
||||
<!-- 오늘의 공부 (이론 홈 대시보드 = 데일리 트리거) -->
|
||||
<section class="mb-5 rounded-lg border border-default bg-surface p-4 md:p-5">
|
||||
<div class="flex items-center gap-2 mb-3">
|
||||
<CalendarCheck size={18} class="text-accent" />
|
||||
<h2 class="text-base font-semibold text-text">오늘의 공부</h2>
|
||||
{#if curriculum}
|
||||
<span class="ml-auto text-xs text-dim">이론 회독 <span class="text-text font-medium">{curriculum.read}</span> / {curriculum.total} ({readPct}%)</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if dashLoading}
|
||||
<p class="text-xs text-dim">불러오는 중…</p>
|
||||
{:else}
|
||||
{#if curriculum}
|
||||
<div class="h-2 rounded-full bg-bg overflow-hidden mb-3">
|
||||
<div class="h-full bg-accent" style="width: {readPct}%"></div>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-x-4 gap-y-1 mb-4 text-xs text-dim">
|
||||
{#each curriculum.subjects as s}
|
||||
<span>{s.subject} <span class="text-text">{s.read}/{s.total}</span></span>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2 mb-4">
|
||||
<a
|
||||
href="/study/topics/{curriculum.topic_id}/review-queue"
|
||||
class="flex items-center gap-1.5 rounded border border-default px-3 py-1.5 text-xs text-dim hover:border-accent hover:text-text transition-colors"
|
||||
>
|
||||
<Repeat size={13} /> 문항 복습 <span class="font-semibold text-text">{curriculum.question_due}</span>
|
||||
</a>
|
||||
<span class="flex items-center gap-1.5 rounded border border-default px-3 py-1.5 text-xs text-dim">
|
||||
<BookOpen size={13} /> 개념 재복습 <span class="font-semibold text-text">{curriculum.concept_due}</span>
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="text-xs text-dim mb-2">오늘의 개념</div>
|
||||
{#if todayConcepts.length === 0}
|
||||
<p class="text-xs text-dim">오늘 볼 개념이 없습니다. 잘 하고 있어요.</p>
|
||||
{:else}
|
||||
<ul class="space-y-1.5">
|
||||
{#each todayConcepts as c (c.doc_id)}
|
||||
<li class="flex items-center gap-2 rounded border border-default px-3 py-2">
|
||||
<span class="text-accent shrink-0 text-xs" title="빈출">{#each Array(c.freq) as _}★{/each}</span>
|
||||
<a href="/study/read/{c.doc_id}" class="text-sm text-text hover:text-accent truncate flex-1">{c.title}</a>
|
||||
<span class="shrink-0 text-[10px] rounded-full px-2 py-0.5 {c.reason === '재복습' ? 'bg-accent/15 text-accent' : 'bg-surface border border-default text-dim'}">{c.reason}</span>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => markRead(c)}
|
||||
class="shrink-0 text-xs rounded border border-default px-2 py-1 text-dim hover:border-accent hover:text-accent transition-colors"
|
||||
>읽음</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
{#if weakConcepts.length > 0}
|
||||
<div class="mt-4 pt-3 border-t border-default">
|
||||
<div class="text-xs text-dim mb-2 flex items-center gap-1.5">
|
||||
<Target size={13} class="text-error" /> 약점 개념 <span class="text-faint">(관련 기출 정답률 낮음)</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each weakConcepts as w (w.doc_id)}
|
||||
<a href="/study/read/{w.doc_id}"
|
||||
class="text-xs rounded-full border border-error/40 bg-error/10 text-error px-3 py-1 hover:bg-error/20 transition-colors">
|
||||
{w.title.replace(/^\d+_/, '')} <span class="font-semibold">{w.accuracy}%</span>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<a
|
||||
href="/study/topics"
|
||||
class="block mb-3 p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
|
||||
@@ -245,8 +126,7 @@
|
||||
<div class="mt-6 p-4 rounded-lg border border-dashed border-default/60 text-xs text-dim">
|
||||
<div class="font-medium text-dim mb-1">예정</div>
|
||||
<ul class="list-disc list-inside space-y-0.5">
|
||||
<li>개념 학습 리더 (가리고 떠올리기 · 빈출★ · 관련개념 백링크)</li>
|
||||
<li>이론↔문제 연결 (개념별 정답률 · 약점 개념 지도)</li>
|
||||
<li>애플워치 빠른복습 + 공부 알람(push)</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
<script>
|
||||
/**
|
||||
* /study/read/[docId] — 개념 학습 리더.
|
||||
* 개념노트(가스기사 documents)를 구조(요약/본문/빈출★/관련개념)로 렌더 +
|
||||
* '떠올리기' 능동 회상 토글 + 회독 SR(POST read) + 관련개념 백링크 + 이전/다음.
|
||||
* 본문 렌더 = MarkdownDoc(KaTeX + docimg 내장). 서버 파싱 = /api/study/concepts/{id}.
|
||||
*/
|
||||
import { page } from '$app/stores';
|
||||
import { api } from '$lib/api';
|
||||
import { addToast } from '$lib/stores/toast';
|
||||
import { renderMathMarkdownInline } from '$lib/utils/mathMarkdown';
|
||||
import MarkdownDoc from '$lib/components/MarkdownDoc.svelte';
|
||||
import Button from '$lib/components/ui/Button.svelte';
|
||||
import EmptyState from '$lib/components/ui/EmptyState.svelte';
|
||||
import Skeleton from '$lib/components/ui/Skeleton.svelte';
|
||||
import { BookOpen, ArrowLeft, Eye, EyeOff, Check, ChevronLeft, ChevronRight, FileQuestion } from 'lucide-svelte';
|
||||
|
||||
let docId = $derived($page.params.docId);
|
||||
|
||||
let concept = $state(null);
|
||||
let relatedQ = $state(null); // 관련 기출(이론↔문제, 비차단)
|
||||
let loading = $state(true);
|
||||
let notFound = $state(false);
|
||||
let mode = $state('read'); // 'read' | 'recall'(떠올리기)
|
||||
let revealed = $state({}); // {sectionIndex: true}
|
||||
let marking = $state(false);
|
||||
|
||||
const STAGE_LABEL = { 0: '복습 시작', 1: '복습 1단계', 2: '복습 2단계', 3: '복습 3단계', 4: '학습 완료' };
|
||||
const OUTCOME_MARK = { correct: '○', wrong: '✕', unsure: '?' };
|
||||
const OUTCOME_CLASS = { correct: 'text-success', wrong: 'text-error', unsure: 'text-warning' };
|
||||
const outcomeMark = (o) => OUTCOME_MARK[o] ?? '–';
|
||||
const outcomeClass = (o) => OUTCOME_CLASS[o] ?? 'text-faint';
|
||||
|
||||
async function load() {
|
||||
const reqId = docId; // in-flight 가드: 백링크 연타 시 stale 응답 무시
|
||||
loading = true;
|
||||
notFound = false;
|
||||
concept = null;
|
||||
relatedQ = null;
|
||||
revealed = {};
|
||||
mode = 'read';
|
||||
try {
|
||||
const data = await api(`/study/concepts/${reqId}`);
|
||||
if (reqId !== docId) return; // 그새 다른 개념으로 이동 → 폐기
|
||||
concept = data;
|
||||
} catch (e) {
|
||||
if (reqId !== docId) return;
|
||||
if (e?.status === 404) notFound = true;
|
||||
else addToast('error', '개념을 불러오지 못했습니다');
|
||||
return; // 본문 실패 → 관련기출 스킵
|
||||
} finally {
|
||||
if (reqId === docId) loading = false;
|
||||
}
|
||||
// 관련 기출(비차단 — 실패해도 본문 표시엔 영향 없음)
|
||||
try {
|
||||
const rq = await api(`/study/concepts/${reqId}/questions?limit=6`);
|
||||
if (reqId === docId) relatedQ = rq;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// $effect 가 마운트 1회 + docId 변경(백링크/이전·다음) 재로드를 모두 커버 (onMount 불필요)
|
||||
$effect(() => {
|
||||
void docId;
|
||||
load();
|
||||
});
|
||||
|
||||
function toggleMode() {
|
||||
mode = mode === 'read' ? 'recall' : 'read';
|
||||
revealed = {};
|
||||
}
|
||||
function reveal(i) {
|
||||
revealed = { ...revealed, [i]: true };
|
||||
}
|
||||
function shown(i) {
|
||||
return mode === 'read' || revealed[i];
|
||||
}
|
||||
|
||||
async function markRead() {
|
||||
marking = true;
|
||||
try {
|
||||
const r = await api(`/study/concepts/${docId}/read`, { method: 'POST' });
|
||||
if (concept) {
|
||||
concept.is_read = true;
|
||||
concept.review_stage = r?.review_stage ?? concept.review_stage;
|
||||
concept.due_at = r?.due_at ?? concept.due_at;
|
||||
}
|
||||
addToast('success', '회독 완료 — 다음 복습에 다시 나옵니다');
|
||||
} catch {
|
||||
addToast('error', '회독 처리 실패');
|
||||
} finally {
|
||||
marking = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{concept?.title ?? '개념'} — 공부</title></svelte:head>
|
||||
|
||||
<div class="p-4 md:p-6 max-w-3xl mx-auto">
|
||||
<!-- 상단 네비 -->
|
||||
<div class="flex items-center gap-2 text-xs md:text-sm mb-4 min-w-0">
|
||||
<a href="/study" class="text-dim hover:text-text flex items-center gap-1 shrink-0">
|
||||
<ArrowLeft size={14} /> 공부
|
||||
</a>
|
||||
{#if concept?.subject}
|
||||
<span class="text-faint shrink-0">/</span>
|
||||
<span class="text-dim truncate">{concept.subject}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<Skeleton h="h-10" rounded="card" />
|
||||
<div class="mt-3 space-y-2">
|
||||
{#each Array(4) as _}<Skeleton h="h-24" rounded="card" />{/each}
|
||||
</div>
|
||||
{:else if notFound}
|
||||
<EmptyState icon={BookOpen} title="개념을 찾을 수 없습니다" description="삭제되었거나 잘못된 주소입니다." />
|
||||
{:else if concept}
|
||||
<!-- 제목 + 빈출 tier -->
|
||||
<header class="mb-3">
|
||||
<div class="flex items-start gap-2">
|
||||
<h1 class="text-xl md:text-2xl font-semibold text-text flex-1">{concept.title}</h1>
|
||||
<span class="text-accent text-sm shrink-0 mt-1" title="빈출도">
|
||||
{#each Array(concept.freq) as _}★{/each}
|
||||
</span>
|
||||
</div>
|
||||
{#if concept.is_read || (concept.review_stage !== null && concept.review_stage !== undefined)}
|
||||
<div class="mt-1 text-xs text-dim">
|
||||
{#if concept.review_stage !== null && concept.review_stage !== undefined}
|
||||
{STAGE_LABEL[concept.review_stage] ?? '복습 중'}
|
||||
{:else}회독함{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</header>
|
||||
|
||||
<!-- 한 줄 요약 (고정 표시) -->
|
||||
{#if concept.summary}
|
||||
<div class="mb-4 rounded-lg border-l-4 border-accent bg-accent/10 px-4 py-3 markdown-body text-sm text-text">
|
||||
{@html renderMathMarkdownInline(concept.summary)}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- 모드 토글 -->
|
||||
<div class="flex items-center gap-2 mb-4">
|
||||
<Button variant={mode === 'recall' ? 'primary' : 'secondary'} size="sm" icon={mode === 'recall' ? EyeOff : Eye} onclick={toggleMode}>
|
||||
{mode === 'recall' ? '떠올리기 모드' : '읽기 모드'}
|
||||
</Button>
|
||||
{#if mode === 'recall'}
|
||||
<span class="text-xs text-dim">각 섹션을 떠올린 뒤 확인하세요</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- 본문 섹션 -->
|
||||
{#if concept.body.length > 0}
|
||||
<div class="space-y-3 mb-5">
|
||||
{#each concept.body as sec, i (i)}
|
||||
<section class="rounded-lg border border-default bg-surface overflow-hidden">
|
||||
<div class="flex items-center gap-2 px-4 py-2.5 border-b border-default bg-surface-hover">
|
||||
<h2 class="text-sm font-semibold text-text flex-1">{sec.label}</h2>
|
||||
{#if sec.stars > 0}
|
||||
<span class="text-accent text-xs shrink-0">{#each Array(sec.stars) as _}★{/each}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if shown(i)}
|
||||
<div class="px-4 py-3">
|
||||
<MarkdownDoc documentId={concept.doc_id} mdContent={sec.md} mdStatus={null}
|
||||
class="markdown-body max-w-none text-text" />
|
||||
</div>
|
||||
{:else}
|
||||
<button type="button" onclick={() => reveal(i)}
|
||||
class="w-full px-4 py-6 text-center text-sm text-dim hover:text-accent hover:bg-accent/5 transition-colors">
|
||||
<Eye size={16} class="inline mr-1" /> 떠올린 뒤 확인
|
||||
</button>
|
||||
{/if}
|
||||
</section>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- 빈출 포인트 -->
|
||||
{#if concept.bincheol.length > 0}
|
||||
<section class="mb-5 rounded-lg border border-default bg-surface p-4">
|
||||
<h2 class="text-sm font-semibold text-text mb-2 flex items-center gap-1.5">
|
||||
<span class="text-accent">★</span> 빈출 포인트
|
||||
</h2>
|
||||
<ul class="space-y-1.5">
|
||||
{#each concept.bincheol as item}
|
||||
<li class="flex gap-2 text-sm text-text">
|
||||
<span class="text-accent shrink-0 text-xs mt-0.5">{#each Array(item.tier || 1) as _}★{/each}</span>
|
||||
<span class="markdown-body flex-1">{@html renderMathMarkdownInline(item.text)}</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<!-- 관련 개념 (백링크) -->
|
||||
{#if concept.related.length > 0}
|
||||
<section class="mb-5">
|
||||
<h2 class="text-xs text-dim mb-2">관련 개념</h2>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each concept.related as rel}
|
||||
{#if rel.doc_id}
|
||||
<a href="/study/read/{rel.doc_id}"
|
||||
class="text-xs rounded-full border border-accent/40 bg-accent/10 text-accent px-3 py-1 hover:bg-accent/20 transition-colors">
|
||||
{rel.phrase}
|
||||
</a>
|
||||
{:else}
|
||||
<span class="text-xs rounded-full border border-default bg-surface text-faint px-3 py-1" title="아직 없는 개념">
|
||||
{rel.phrase}
|
||||
</span>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<!-- 관련 기출 (이론↔문제 브리지) -->
|
||||
{#if relatedQ && relatedQ.linked > 0}
|
||||
<section class="mb-5 rounded-lg border border-default bg-surface p-4">
|
||||
<h2 class="text-sm font-semibold text-text mb-2 flex items-center gap-1.5">
|
||||
<FileQuestion size={15} class="text-accent" /> 관련 기출
|
||||
<span class="ml-1 text-xs font-normal text-dim">
|
||||
{relatedQ.linked}문항{#if relatedQ.accuracy !== null} · 정답률 <span class="{relatedQ.accuracy < 60 ? 'text-error' : 'text-text'} font-medium">{relatedQ.accuracy}%</span>{:else} · 아직 안 풂{/if}
|
||||
</span>
|
||||
</h2>
|
||||
<ul class="space-y-0.5">
|
||||
{#each relatedQ.questions as q (q.id)}
|
||||
<li>
|
||||
<a href="/study/topics/4/questions/{q.id}"
|
||||
class="flex items-center gap-2 text-xs py-1 text-dim hover:text-accent transition-colors">
|
||||
<span class="{outcomeClass(q.last_outcome)} shrink-0 w-4 text-center font-bold">{outcomeMark(q.last_outcome)}</span>
|
||||
<span class="truncate">{q.subject ?? '기출'}{#if q.exam_round} · {q.exam_round}{/if}</span>
|
||||
</a>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<!-- 액션바 -->
|
||||
<div class="flex items-center gap-2 border-t border-default pt-4 mt-2">
|
||||
{#if concept.prev_id}
|
||||
<Button variant="ghost" size="sm" icon={ChevronLeft} href="/study/read/{concept.prev_id}">이전</Button>
|
||||
{/if}
|
||||
<div class="flex-1"></div>
|
||||
<Button variant="primary" size="sm" icon={Check} onclick={markRead} loading={marking}>
|
||||
{concept.is_read ? '다시 회독' : '회독 완료'}
|
||||
</Button>
|
||||
{#if concept.next_id}
|
||||
<Button variant="secondary" size="sm" icon={ChevronRight} href="/study/read/{concept.next_id}">다음 개념</Button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,16 +0,0 @@
|
||||
-- 381_study_concept_progress.sql — 이론 개념(문서) 간격반복(SR) 진행. 이론공부 홈 트리거.
|
||||
-- concept_doc_id 는 documents.id 를 가리키나 FK 미설정(hot 테이블 락 회피, clause_study 380 선례).
|
||||
-- SR 산술은 study_question_progress 와 동일(sr_schedule 공용): stage 0→1→2→3(1·3·7·14일)→4 졸업.
|
||||
CREATE TABLE IF NOT EXISTS study_concept_progress (
|
||||
id bigserial PRIMARY KEY,
|
||||
user_id bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
study_topic_id bigint NOT NULL REFERENCES study_topics(id) ON DELETE CASCADE,
|
||||
concept_doc_id bigint NOT NULL,
|
||||
review_stage smallint,
|
||||
due_at timestamptz,
|
||||
last_read_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT uq_concept_progress_user_doc UNIQUE (user_id, concept_doc_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_concept_progress_due ON study_concept_progress(user_id, due_at) WHERE due_at IS NOT NULL;
|
||||
@@ -1,15 +0,0 @@
|
||||
-- 382_study_concept_links.sql — 개념문서 ↔ 기출문항 링크 (이론↔문제 브리지, Stage B).
|
||||
-- concept_doc_id=documents.id, question_id=study_questions.id — FK 없음(hot 테이블 락 회피, 선례).
|
||||
-- link_source: 'embedding'(bge-m3 코사인 top-k, 주력) | 'ref'(해설 .md 참조, 후속 enrichment).
|
||||
-- score=코사인 유사도(0~1). UNIQUE(doc,question,source) — source별 공존 허용(재튜닝=source 전삭제 후 재삽입).
|
||||
CREATE TABLE IF NOT EXISTS study_concept_links (
|
||||
id bigserial PRIMARY KEY,
|
||||
concept_doc_id bigint NOT NULL,
|
||||
question_id bigint NOT NULL,
|
||||
link_source text NOT NULL,
|
||||
score double precision,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT uq_concept_link UNIQUE (concept_doc_id, question_id, link_source)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_concept_links_doc ON study_concept_links(concept_doc_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_concept_links_q ON study_concept_links(question_id);
|
||||
@@ -1,23 +0,0 @@
|
||||
-- concept_links_backfill.sql — 개념↔문항 임베딩 링크 재생성 (Stage B, 멱등·재실행 안전).
|
||||
-- 정찰 확정: bge-m3 1024d 코사인, per-concept top-k=10, threshold 0.62 → ~2362링크·284/289개념·964문항.
|
||||
-- 재튜닝 시 DELETE(embedding 소스만) 후 재삽입 = ref 링크(후속) 불변. 개념 doc = 가스기사 태그.
|
||||
DELETE FROM study_concept_links WHERE link_source = 'embedding';
|
||||
INSERT INTO study_concept_links (concept_doc_id, question_id, link_source, score)
|
||||
WITH cd AS (
|
||||
SELECT id, embedding FROM documents
|
||||
WHERE user_tags::text LIKE '%@library/가스기사/%'
|
||||
AND deleted_at IS NULL AND embedding IS NOT NULL
|
||||
),
|
||||
ranked AS (
|
||||
SELECT cd.id AS concept_doc_id, q.id AS question_id,
|
||||
1 - (q.embedding <=> cd.embedding) AS score,
|
||||
row_number() OVER (PARTITION BY cd.id ORDER BY q.embedding <=> cd.embedding) AS rn
|
||||
FROM cd
|
||||
JOIN study_questions q
|
||||
ON q.study_topic_id = 4 AND q.embedding IS NOT NULL
|
||||
AND q.deleted_at IS NULL AND q.is_active
|
||||
)
|
||||
SELECT concept_doc_id, question_id, 'embedding', score
|
||||
FROM ranked
|
||||
WHERE rn <= 10 AND score >= 0.62
|
||||
ON CONFLICT (concept_doc_id, question_id, link_source) DO NOTHING;
|
||||
@@ -1,80 +0,0 @@
|
||||
"""summarize_units PR2 헬퍼 단위테스트 — map/reduce 프롬프트 조립 순수함수.
|
||||
|
||||
핵심 불변식:
|
||||
- render_map_slice: 유닛 위치(1-based)/섹션 라벨 + 본문 그대로 (손실 0).
|
||||
- build_reduce_units_block: 어떤 입력에도 반환 블록 est_tokens <= budget (캡 초과 0
|
||||
검증 게이트의 reduce 측). 절단은 detail 만 — 라벨/TLDR/불일치/순서 보존.
|
||||
|
||||
pytest + 단독 실행 양쪽 지원:
|
||||
PYTHONPATH=. pytest tests/summarize_units/ -q
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.summarize_units import (
|
||||
SummarizeUnit,
|
||||
build_reduce_units_block,
|
||||
estimate_tokens,
|
||||
render_map_slice,
|
||||
)
|
||||
|
||||
|
||||
def _result(idx: int, detail: str, *, tldr: str = "요약", inc: list | None = None) -> dict:
|
||||
return {
|
||||
"index": idx,
|
||||
"titles": [f"섹션{idx}"],
|
||||
"tldr": tldr,
|
||||
"detail": detail,
|
||||
"inconsistencies": inc or [],
|
||||
}
|
||||
|
||||
|
||||
# ---------- render_map_slice ----------
|
||||
|
||||
def test_render_map_slice_label_and_body():
|
||||
unit = SummarizeUnit(index=2, section_titles=["개요", None, "본론"], text="본문입니다")
|
||||
out = render_map_slice(unit, total_units=5)
|
||||
assert out.startswith("[유닛 3/5 — 섹션: 개요 · 본론]\n")
|
||||
assert out.endswith("본문입니다")
|
||||
|
||||
|
||||
def test_render_map_slice_untitled():
|
||||
unit = SummarizeUnit(index=0, section_titles=[None], text="x")
|
||||
assert "(무제 구간)" in render_map_slice(unit, total_units=1)
|
||||
|
||||
|
||||
# ---------- build_reduce_units_block ----------
|
||||
|
||||
def test_reduce_block_within_budget_untouched():
|
||||
results = [_result(i, "가" * 100) for i in range(3)]
|
||||
block, truncated = build_reduce_units_block(results, budget_tokens=11_000)
|
||||
assert not truncated
|
||||
# 순서/라벨/TLDR 보존
|
||||
assert block.index("[유닛 1/3") < block.index("[유닛 2/3") < block.index("[유닛 3/3")
|
||||
assert "TLDR: 요약" in block
|
||||
assert "가" * 100 in block
|
||||
|
||||
|
||||
def test_reduce_block_truncates_to_budget():
|
||||
# 유닛 8개 × 한글 detail 5,000자 ≈ 21K tok — budget 5,000 으로 절단 강제
|
||||
results = [_result(i, "가" * 5_000) for i in range(8)]
|
||||
block, truncated = build_reduce_units_block(results, budget_tokens=5_000)
|
||||
assert truncated
|
||||
assert estimate_tokens(block) <= 5_000
|
||||
# 라벨(유닛 순서)은 절단 후에도 보존
|
||||
assert "[유닛 1/8" in block
|
||||
|
||||
|
||||
def test_reduce_block_hard_cut_floor():
|
||||
# min_detail_chars floor 에 막혀 비례 절단으로 불충분한 극단 케이스 — 하드 컷 발동
|
||||
results = [_result(i, "가" * 300) for i in range(50)]
|
||||
block, truncated = build_reduce_units_block(results, budget_tokens=500)
|
||||
assert truncated
|
||||
assert estimate_tokens(block) <= 500
|
||||
|
||||
|
||||
def test_reduce_block_preserves_inconsistencies():
|
||||
results = [
|
||||
_result(0, "가" * 50, inc=[{"kind": "version_drift", "desc": "개정판 차이"}]),
|
||||
]
|
||||
block, _ = build_reduce_units_block(results, budget_tokens=10_000)
|
||||
assert "불일치(version_drift): 개정판 차이" in block
|
||||
@@ -1,180 +0,0 @@
|
||||
"""summarize_units 단위테스트 (presegment PR1 — 순수함수·fixture).
|
||||
|
||||
핵심 불변식:
|
||||
- estimate_tokens = PR0 캘리브레이션(한글 0.529 · 기타 0.217 tok/char) 정확 재현.
|
||||
- greedy_pack: 순서 보존·인접만·cap 준수·단독 초과 leaf=over_cap 전용 유닛·텍스트 손실 0
|
||||
(구 deep_summary head/mid/tail 가운데 폐기 버그의 반대 성질).
|
||||
- gate 3-way: 0=auto / (0,40]=hybrid / >40=whole (경계 포함).
|
||||
- plan_summarize_units: trigger 이하=single(현행 단일콜 유지=무회귀) / 초과=map_reduce.
|
||||
|
||||
pytest + 단독 실행 양쪽 지원:
|
||||
PYTHONPATH=. .venv/bin/pytest tests/summarize_units/ -q
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.hier_decomp.builder import HierNode
|
||||
from app.services.summarize_units import (
|
||||
CAP_TOKENS,
|
||||
TRIGGER_TOKENS,
|
||||
SummarizeUnit,
|
||||
estimate_tokens,
|
||||
extract_leaves,
|
||||
gate,
|
||||
greedy_pack,
|
||||
over_pct,
|
||||
plan_summarize_units,
|
||||
)
|
||||
|
||||
|
||||
def _leaf(idx: int, text: str, title: str | None = None) -> HierNode:
|
||||
return HierNode(idx=idx, parent_idx=None, level=1, node_type=None,
|
||||
section_title=title, heading_path=title, text=text)
|
||||
|
||||
|
||||
# ---------- estimate_tokens ----------
|
||||
|
||||
def test_estimate_tokens_korean_calibration():
|
||||
# 한글 1000자 → 529 tok (PR0: 0.529 tok/char)
|
||||
assert estimate_tokens("가" * 1000) == 529
|
||||
|
||||
|
||||
def test_estimate_tokens_english_calibration():
|
||||
# 비한글 1000자 → 217 tok (PR0: 0.217 tok/char)
|
||||
assert estimate_tokens("a" * 1000) == 217
|
||||
|
||||
|
||||
def test_estimate_tokens_mixed_and_empty():
|
||||
assert estimate_tokens("") == 0
|
||||
mixed = "가" * 100 + "a" * 100
|
||||
assert estimate_tokens(mixed) == round(100 * 0.529 + 100 * 0.217)
|
||||
|
||||
|
||||
# ---------- greedy_pack ----------
|
||||
|
||||
def test_greedy_pack_adjacency_and_cap():
|
||||
# 4000tok 짜리 한글 leaf 4개 (4000/0.529 ≈ 7562자) → cap 12000 이면 [3개, 1개]... 아니
|
||||
# 4000*3=12000 = cap 정확 경계(<=cap 허용) → [1,2,3] + [4]
|
||||
body = "가" * 7562 # ≈ 3999~4000 tok
|
||||
leaves = [_leaf(i, body, f"s{i}") for i in range(4)]
|
||||
units = greedy_pack(leaves, cap=12_000)
|
||||
assert len(units) == 2
|
||||
assert [len(u.section_titles) for u in units] == [3, 1]
|
||||
# 순서 보존
|
||||
assert units[0].section_titles == ["s0", "s1", "s2"]
|
||||
assert units[1].section_titles == ["s3"]
|
||||
# cap 준수
|
||||
assert all(u.est_tokens <= 12_000 for u in units)
|
||||
|
||||
|
||||
def test_greedy_pack_oversized_leaf_gets_own_unit():
|
||||
small = "가" * 1000 # ≈ 529 tok
|
||||
big = "가" * 30_000 # ≈ 15,870 tok > CAP
|
||||
leaves = [_leaf(0, small, "a"), _leaf(1, big, "mega"), _leaf(2, small, "b")]
|
||||
units = greedy_pack(leaves, cap=CAP_TOKENS)
|
||||
assert len(units) == 3
|
||||
assert units[1].over_cap and units[1].section_titles == ["mega"]
|
||||
assert not units[0].over_cap and not units[2].over_cap
|
||||
# 인접성: 초과 leaf 가 앞뒤 pack 을 넘나들며 합쳐지지 않음
|
||||
assert units[0].section_titles == ["a"] and units[2].section_titles == ["b"]
|
||||
|
||||
|
||||
def test_greedy_pack_no_text_loss():
|
||||
leaves = [_leaf(i, f"본문{i} " + "가" * 500, f"s{i}") for i in range(7)]
|
||||
units = greedy_pack(leaves, cap=1_000)
|
||||
joined = "\n\n".join(u.text for u in units)
|
||||
for leaf in leaves:
|
||||
assert leaf.text in joined # 커버리지 — 중간 폐기 0
|
||||
|
||||
|
||||
def test_greedy_pack_empty():
|
||||
assert greedy_pack([]) == []
|
||||
|
||||
|
||||
# ---------- over_pct + gate ----------
|
||||
|
||||
def test_over_pct_and_gate_boundaries():
|
||||
assert gate(0.0) == "auto"
|
||||
assert gate(0.01) == "hybrid"
|
||||
assert gate(40.0) == "hybrid"
|
||||
assert gate(40.01) == "whole"
|
||||
assert gate(100.0) == "whole"
|
||||
|
||||
|
||||
def test_over_pct_computation():
|
||||
# leaf: 6000tok + 18000tok(초과) → over% = 18000/24000 = 75%
|
||||
l_small = _leaf(0, "가" * round(6000 / 0.529), "a")
|
||||
l_big = _leaf(1, "가" * round(18000 / 0.529), "b")
|
||||
pct = over_pct([l_small, l_big], cap=CAP_TOKENS)
|
||||
assert 74.0 < pct < 76.0
|
||||
assert over_pct([], cap=CAP_TOKENS) == 0.0
|
||||
assert over_pct([l_small], cap=CAP_TOKENS) == 0.0
|
||||
|
||||
|
||||
# ---------- plan_summarize_units (fixture md) ----------
|
||||
|
||||
def _md_doc(sections: int, chars_per_section: int, ch: str = "가") -> str:
|
||||
parts = []
|
||||
for i in range(sections):
|
||||
parts.append(f"# 제{i+1}장 섹션{i}\n\n" + ch * chars_per_section)
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def test_plan_small_doc_stays_single():
|
||||
md = _md_doc(3, 1000) # ≈ 3×529 tok ≪ trigger
|
||||
plan = plan_summarize_units(md)
|
||||
assert plan.mode == "single" and plan.tier is None and plan.units == []
|
||||
assert plan.total_est_tokens <= TRIGGER_TOKENS
|
||||
|
||||
|
||||
def test_plan_large_doc_auto_tier():
|
||||
# 섹션 20개 × ≈4000tok = ≈80K tok > trigger, 전 섹션 < cap → auto
|
||||
md = _md_doc(20, 7562)
|
||||
plan = plan_summarize_units(md)
|
||||
assert plan.mode == "map_reduce"
|
||||
assert plan.tier == "auto" and plan.over_pct == 0.0
|
||||
assert len(plan.units) >= 2
|
||||
assert all(u.est_tokens <= CAP_TOKENS for u in plan.units)
|
||||
|
||||
|
||||
def test_plan_mega_section_whole_tier():
|
||||
# 작은 섹션 2 + 초대형 1(≈53K tok — 전체의 >40%) → whole
|
||||
md = (_md_doc(2, 7562)
|
||||
+ "\n\n# 메가섹션\n\n" + "가" * 100_000)
|
||||
plan = plan_summarize_units(md)
|
||||
assert plan.mode == "map_reduce"
|
||||
assert plan.tier == "whole" and plan.over_pct > 40.0
|
||||
assert any(u.over_cap for u in plan.units)
|
||||
|
||||
|
||||
def test_plan_hybrid_tier():
|
||||
# 정상 섹션 15개(≈60K tok) + 초과 섹션 1개(≈15.9K tok) → over% ≈ 21% → hybrid
|
||||
md = _md_doc(15, 7562) + "\n\n# 초과섹션\n\n" + "가" * 30_000
|
||||
plan = plan_summarize_units(md)
|
||||
assert plan.mode == "map_reduce"
|
||||
assert plan.tier == "hybrid"
|
||||
assert 0.0 < plan.over_pct <= 40.0
|
||||
over_units = [u for u in plan.units if u.over_cap]
|
||||
assert len(over_units) == 1 # hybrid 시 클로드 대상 = 이 유닛들만
|
||||
|
||||
|
||||
def test_plan_headingless_giant_is_whole():
|
||||
# 헤딩 없는 거대 EN 문서 — leaf 1개 전체 초과 → over% 100 → whole (PR0: EN 책 다수)
|
||||
md = "x" * 200_000 # ≈ 43K tok > trigger, 단일 leaf > cap
|
||||
plan = plan_summarize_units(md)
|
||||
assert plan.mode == "map_reduce" and plan.tier == "whole"
|
||||
|
||||
|
||||
def test_plan_deterministic():
|
||||
md = _md_doc(10, 7562)
|
||||
p1, p2 = plan_summarize_units(md), plan_summarize_units(md)
|
||||
assert p1 == p2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||
for fn in fns:
|
||||
fn()
|
||||
print(f"ok {fn.__name__}")
|
||||
print(f"{len(fns)} passed (standalone)")
|
||||
sys.exit(0)
|
||||
@@ -1,266 +0,0 @@
|
||||
"""presegment PR2 — deep_summary_worker map-reduce/HOLD 배선 단위테스트.
|
||||
|
||||
worker-process 레벨(DB 필요)의 큐 상태 전이는 라이브 E2E 로 검증하고, 여기서는
|
||||
새 메커니즘의 seam 을 단위 검증한다 (test_fair_share.py 선례):
|
||||
- _hold_awaiting_split: payload 마킹 commit 후 StageDeferred(HOLD_RETRY_MINUTES).
|
||||
- _process_map_reduce: 유닛별 map → reduce → doc 필드 기록 / 모든 콜 캡 준수 /
|
||||
payload.presegment.map_results 유닛 단위 persist(멱등 재개) / 실패 유닛 raise /
|
||||
drain 보류(StageDeferred) 시 완료 유닛 보존.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "app"))
|
||||
|
||||
from ai.envelope import EscalationEnvelope # noqa: E402
|
||||
from models.queue import StageDeferred # noqa: E402
|
||||
from services.summarize_units import ( # noqa: E402
|
||||
CAP_TOKENS,
|
||||
estimate_tokens,
|
||||
plan_summarize_units,
|
||||
)
|
||||
import workers.deep_summary_worker as dsw # noqa: E402
|
||||
|
||||
|
||||
# ─── fixtures ────────────────────────────────────────────────────────────────
|
||||
|
||||
# 30 절 × 한글 2,000자 ≈ 31.7K tok (> TRIGGER 25K) · 절당 ≈ 1,060 tok (< CAP) → auto
|
||||
GIANT_AUTO_MD = "\n".join(f"# 절 {i}\n" + ("가" * 2_000) for i in range(30))
|
||||
# 헤딩 1개 + 한글 60,000자 단일 섹션 ≈ 31.7K tok (> CAP) → over% 100 → whole
|
||||
GIANT_WHOLE_MD = "# 통짜\n" + ("가" * 60_000)
|
||||
|
||||
MAP_JSON = (
|
||||
'{"mode": "single", "tldr": "유닛 요약", "detail": "유닛 상세.",'
|
||||
' "inconsistencies": [{"kind": "version_drift", "desc": "개정판 차이"}],'
|
||||
' "confidence": 0.9}'
|
||||
)
|
||||
REDUCE_JSON = (
|
||||
'{"mode": "single", "tldr": "전체 요약", "detail": "최종 상세.",'
|
||||
' "inconsistencies": [], "confidence": 0.8}'
|
||||
)
|
||||
|
||||
|
||||
class FakeSession:
|
||||
"""commit 시점의 queue_row.payload 를 **객체 참조**로 박제 — SQLAlchemy 의 committed
|
||||
스냅샷과 동일하게, 이후 in-place 변경이 과거 커밋 객체에 소급 반영되는 aliasing
|
||||
(60254 라이브에서 unit 0 만 persist 된 버그)을 검증 시점 직렬화로 탐지한다."""
|
||||
|
||||
def __init__(self, row=None):
|
||||
self.commits = 0
|
||||
self._row = row
|
||||
self.snapshots: list = []
|
||||
|
||||
async def commit(self):
|
||||
self.commits += 1
|
||||
if self._row is not None:
|
||||
self.snapshots.append(self._row.payload) # 참조 박제 — 복사 금지(의도)
|
||||
|
||||
|
||||
class FakeClient:
|
||||
"""deep 슬롯 보유 클라이언트 — call_deep_or_defer 가 call_deep 을 타게 한다."""
|
||||
|
||||
def __init__(self, responses=None, fail_indexes=frozenset(), defer_from=None):
|
||||
self.ai = SimpleNamespace(
|
||||
deep=SimpleNamespace(model="qwen-macbook", context_char_limit=260_000)
|
||||
)
|
||||
self.prompts: list[str] = []
|
||||
self._fail_indexes = fail_indexes # 이 순번(0-based) 콜은 파싱 불가 응답
|
||||
self._defer_from = defer_from # 이 순번부터 연결 실패(StageDeferred 변환 대상)
|
||||
|
||||
async def call_deep(self, prompt: str, system=None) -> str:
|
||||
import httpx
|
||||
|
||||
idx = len(self.prompts)
|
||||
if self._defer_from is not None and idx >= self._defer_from:
|
||||
raise httpx.ConnectError("macbook down")
|
||||
self.prompts.append(prompt)
|
||||
if idx in self._fail_indexes:
|
||||
return "정상 JSON 아님"
|
||||
if "유닛 요약 (총" in prompt: # reduce 프롬프트 마커
|
||||
return REDUCE_JSON
|
||||
return MAP_JSON
|
||||
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def _doc():
|
||||
return SimpleNamespace(
|
||||
id=999,
|
||||
extracted_text=GIANT_AUTO_MD,
|
||||
ai_detail_summary=None,
|
||||
ai_inconsistencies=None,
|
||||
ai_analysis_tier="triage",
|
||||
ai_processed_at=None,
|
||||
)
|
||||
|
||||
|
||||
def _envelope():
|
||||
return EscalationEnvelope(
|
||||
from_stage="classify",
|
||||
escalation_reasons=("long_context",),
|
||||
risk_flags=(),
|
||||
distilled_context="4B 요지",
|
||||
original_pointers={"doc_ids": [999]},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _patch_telemetry(monkeypatch):
|
||||
events: list[dict] = []
|
||||
|
||||
async def fake_record(**kwargs):
|
||||
events.append(kwargs)
|
||||
|
||||
monkeypatch.setattr(dsw, "record_analyze_event", fake_record)
|
||||
return events
|
||||
|
||||
|
||||
# ─── _hold_awaiting_split ────────────────────────────────────────────────────
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hold_marks_payload_and_defers():
|
||||
plan = plan_summarize_units(GIANT_WHOLE_MD)
|
||||
assert plan.mode == "map_reduce" and plan.tier == "whole"
|
||||
|
||||
session, row = FakeSession(), SimpleNamespace(payload={"envelope": {"x": 1}})
|
||||
with pytest.raises(StageDeferred) as ei:
|
||||
await dsw._hold_awaiting_split(session, row, plan, document_id=999)
|
||||
|
||||
assert ei.value.retry_after_minutes == dsw.HOLD_RETRY_MINUTES
|
||||
assert session.commits == 1 # 마킹이 defer 전에 commit — consumer 재읽기에서 보존
|
||||
preseg = row.payload["presegment"]
|
||||
assert preseg["awaiting_split"] is True
|
||||
assert preseg["tier"] == "whole"
|
||||
assert preseg["units"] == len(plan.units)
|
||||
assert row.payload["envelope"] == {"x": 1} # 기존 payload 병합 보존
|
||||
|
||||
|
||||
# ─── _process_map_reduce — 정상 경로 ────────────────────────────────────────
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_map_reduce_end_to_end(monkeypatch, _patch_telemetry):
|
||||
plan = plan_summarize_units(GIANT_AUTO_MD)
|
||||
assert plan.mode == "map_reduce" and plan.tier == "auto"
|
||||
n = len(plan.units)
|
||||
assert n >= 2 # greedy-pack 이 실제로 유닛을 나눴는지
|
||||
|
||||
client = FakeClient()
|
||||
monkeypatch.setattr(dsw, "AIClient", lambda: client)
|
||||
doc = _doc()
|
||||
row = SimpleNamespace(payload={"envelope": {"x": 1}})
|
||||
session = FakeSession(row)
|
||||
|
||||
await dsw._process_map_reduce(
|
||||
doc, row, _envelope(), "generic", plan, session,
|
||||
defer_on_deep_unavailable=False,
|
||||
)
|
||||
|
||||
# 콜 수 = 유닛 map n + reduce 1
|
||||
assert len(client.prompts) == n + 1
|
||||
# 검증 게이트: 모든 콜 est_tokens <= CAP + 오버헤드(정책 템플릿+envelope ~3K)
|
||||
for p in client.prompts:
|
||||
assert estimate_tokens(p) <= CAP_TOKENS + 3_000
|
||||
# doc 기록 = reduce 출력, 불일치 = map 유닛 합본 dedup
|
||||
assert doc.ai_detail_summary == "최종 상세."
|
||||
assert doc.ai_analysis_tier == "deep"
|
||||
assert doc.ai_inconsistencies == [{"kind": "version_drift", "desc": "개정판 차이"}]
|
||||
# 유닛 단위 persist — 유닛마다 commit
|
||||
assert row.payload["presegment"]["units"] == n
|
||||
assert len(row.payload["presegment"]["map_results"]) == n
|
||||
assert session.commits == n
|
||||
# ★aliasing 회귀 방지: 각 commit 이 박제한 payload 객체를 사후에 봤을 때
|
||||
# map_results 가 1,2,...,n 로 단조 증가해야 한다. in-place 변경(구 버그)이면
|
||||
# 모든 스냅샷이 같은 dict 를 공유해 [n,n,...,n] 으로 보인다 = SQLAlchemy 가
|
||||
# committed 스냅샷과 new 가 같다고 판정해 UPDATE 를 스킵하는 것과 등가.
|
||||
per_commit_units = [
|
||||
len(s["presegment"]["map_results"]) for s in session.snapshots
|
||||
]
|
||||
assert per_commit_units == list(range(1, n + 1))
|
||||
# telemetry 1건 (reduce 기준)
|
||||
events = _patch_telemetry
|
||||
assert len(events) == 1 and events[0]["error_code"] is None
|
||||
|
||||
|
||||
# ─── 멱등 재개 ───────────────────────────────────────────────────────────────
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_map_reduce_resume_skips_done_units(monkeypatch, _patch_telemetry):
|
||||
plan = plan_summarize_units(GIANT_AUTO_MD)
|
||||
n = len(plan.units)
|
||||
|
||||
client = FakeClient()
|
||||
monkeypatch.setattr(dsw, "AIClient", lambda: client)
|
||||
done_unit = {
|
||||
"index": 0, "titles": ["절 0"], "tldr": "이전 요약", "detail": "이전 상세.",
|
||||
"inconsistencies": [],
|
||||
}
|
||||
row = SimpleNamespace(payload={
|
||||
"envelope": {"x": 1},
|
||||
"presegment": {"map_results": {"0": done_unit}},
|
||||
})
|
||||
doc, session = _doc(), FakeSession()
|
||||
|
||||
await dsw._process_map_reduce(
|
||||
doc, row, _envelope(), "generic", plan, session,
|
||||
defer_on_deep_unavailable=False,
|
||||
)
|
||||
|
||||
# 유닛 0 은 재호출 안 함 — map (n-1) + reduce 1
|
||||
assert len(client.prompts) == n
|
||||
assert row.payload["presegment"]["map_results"]["0"]["detail"] == "이전 상세."
|
||||
assert doc.ai_detail_summary == "최종 상세."
|
||||
|
||||
|
||||
# ─── map 유닛 실패 → raise (성공분 persist) ─────────────────────────────────
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_map_unit_parse_failure_raises_but_persists_good_units(
|
||||
monkeypatch, _patch_telemetry
|
||||
):
|
||||
plan = plan_summarize_units(GIANT_AUTO_MD)
|
||||
n = len(plan.units)
|
||||
|
||||
client = FakeClient(fail_indexes={1}) # 두 번째 map 콜만 파싱 불가
|
||||
monkeypatch.setattr(dsw, "AIClient", lambda: client)
|
||||
doc, session = _doc(), FakeSession()
|
||||
row = SimpleNamespace(payload={"envelope": {"x": 1}})
|
||||
|
||||
with pytest.raises(ValueError, match="map 유닛"):
|
||||
await dsw._process_map_reduce(
|
||||
doc, row, _envelope(), "generic", plan, session,
|
||||
defer_on_deep_unavailable=False,
|
||||
)
|
||||
|
||||
# 성공 유닛(n-1)은 persist — 재시도 시 실패 1건만 재호출
|
||||
assert len(row.payload["presegment"]["map_results"]) == n - 1
|
||||
assert "1" not in row.payload["presegment"]["map_results"]
|
||||
assert doc.ai_detail_summary is None # doc 은 미기록
|
||||
assert _patch_telemetry == [] # 가짜 완료 이벤트 없음
|
||||
|
||||
|
||||
# ─── drain 보류 — 완료 유닛 보존 + StageDeferred 전파 ───────────────────────
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_map_defer_propagates_and_keeps_progress(monkeypatch, _patch_telemetry):
|
||||
plan = plan_summarize_units(GIANT_AUTO_MD)
|
||||
|
||||
client = FakeClient(defer_from=1) # 첫 유닛 성공 후 맥북 절단
|
||||
monkeypatch.setattr(dsw, "AIClient", lambda: client)
|
||||
doc, session = _doc(), FakeSession()
|
||||
row = SimpleNamespace(payload={"envelope": {"x": 1}})
|
||||
|
||||
with pytest.raises(StageDeferred):
|
||||
await dsw._process_map_reduce(
|
||||
doc, row, _envelope(), "generic", plan, session,
|
||||
defer_on_deep_unavailable=True, # drain 시멘틱 — 보류 전파
|
||||
)
|
||||
|
||||
assert len(row.payload["presegment"]["map_results"]) == 1
|
||||
assert doc.ai_detail_summary is None
|
||||