Compare commits

...
72 Commits
Author SHA1 Message Date
leehc991028andClaude Fable 5.1 823292cbb6 docs: Windows msi 빌드 팀원 가이드 — 준비물·서버 주소·빌드·설치·핫키·막힐 때
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 20:39:43 +09:00
leehc991028andClaude Fable 5.1 acb6cefbcc fix(tauri): 맥 번들에 http 허용(ATS) — 서버가 http 라 앱이 요청을 못 보내던 것
macOS 는 앱 안 비암호화 요청을 기본 차단. src-tauri/Info.plist 로 NSAllowsArbitraryLoads 를
번들에 합침. Windows 는 무관.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 20:36:19 +09:00
leehc991028andClaude Fable 5.1 5cb7d74efa chore(tauri): 0.1.4 — 우리 서버(20.200.170.37:8080)용 빌드
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 20:33:35 +09:00
lee-hyeon-cheolandClaude Fable 5.1 996f1c853e docs(orders): 2026-09-22 정리 — 한 것·다음 할 일·접속 메모
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 18:34:04 +09:00
lee-hyeon-cheolandClaude Fable 5.1 526f4e4545 chore: 작업로그·문서 갱신 (9/22 Phoenix·배포 스크립트·우리 서버)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 18:33:04 +09:00
lee-hyeon-cheolandClaude Fable 5.1 8a7df11d9c docs: 우리 서버 배포 경로·Phoenix 주소·NSG 메모
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 18:17:39 +09:00
lee-hyeon-cheolandClaude Fable 5.1 9c064615a9 fix(deploy): 컨테이너→같은 서버 Phoenix 는 host.docker.internal(host-gateway) — 공인 IP 는 컨테이너 안에서 안 닿음
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 18:15:42 +09:00
lee-hyeon-cheolandClaude Fable 5.1 ea1fd350da feat(deploy): 도커 배포(deploy/docker: compose+Dockerfile+deploy.sh) — 우리 환경용. 렌더러가 FabriX/OpenRouter 템플릿 자동 선택, 호스트 변수화. bare deploy.sh 는 git pull 포함. Phoenix 도커 compose
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 18:09:48 +09:00
lee-hyeon-cheolandClaude Fable 5.1 f55e673cb5 docs(tech): LLM 관측(Phoenix) — 환경 무관 결정·실측·설치 요령 정리
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 17:39:39 +09:00
lee-hyeon-cheolandClaude Fable 5.1 5d1ef6ee30 test(phoenix): ingest 우회 테스트 본문 수정
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 17:16:54 +09:00
lee-hyeon-cheolandClaude Fable 5.1 eb3da84f22 feat(phoenix): /phoenix/v1/traces POST 는 비번 없이 — -13 이 8914 경유로 trace 보내는 길
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 17:16:31 +09:00
lee-hyeon-cheolandClaude Fable 5.1 671f610371 fix(phoenix): run.sh 가 옛 프로세스를 못 죽이던 것 — 패턴 phoenix.server.main
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 17:13:29 +09:00
lee-hyeon-cheolandClaude Fable 5.1 ac7a459dfc feat(observability): /phoenix/ 중계 — 바깥 포트가 8914 뿐이라 백엔드 뒤에 Phoenix 화면 붙임(Basic 잠금, 접두어 떼고 전달). 로컬 e2e(HTML·자산·GraphQL·REST) 통과
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 16:34:38 +09:00
lee-hyeon-cheolandClaude Fable 5.1 8268947fc7 chore: 렌더 산출물 opencode/opencode.json 을 git 에서 뺌 — 서버에서 git pull 막던 원인
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 16:05:01 +09:00
lee-hyeon-cheolandClaude Fable 5.1 68b55907f0 fix(observability): Phoenix 는 OTLP protobuf 만 받음(JSON 415) — opentelemetry-proto 로 직렬화, 로컬 Phoenix 실측 통과
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 15:43:26 +09:00
lee-hyeon-cheolandClaude Fable 5.1 e60c5bc273 feat(observability): Phoenix 대상 추가 — 같은 span 에 OpenInference 속성 동봉, PHOENIX_HOST 로 /v1/traces. -12 는 도커 불가라 pip 로 뜨는 Phoenix 로 감(deploy/phoenix)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 15:39:08 +09:00
lee-hyeon-cheolandClaude Fable 5.1 340e8e4beb chore(langfuse): 고객사 -12 는 NAT 없는 도커 — host 네트워크 오버라이드(minio 9100, 웹 8915) + dockerd 수동 기동 절차
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 15:12:25 +09:00
lee-hyeon-cheolandClaude Fable 5.1 3e9c392941 chore(langfuse): 고객사용 compose override — 빈 포트 8915 를 웹에 매핑, README 갱신
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 14:23:35 +09:00
lee-hyeon-cheolandClaude Fable 5.1 f1f8b7cdf1 docs(langfuse): ABAP_OPENCODE(-13) 연결법 + -13→-12 통신 주의
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 14:14:04 +09:00
lee-hyeon-cheolandClaude Fable 5.1 e801ae6a6f feat(langfuse): 게이트웨이 fabrix 트레이스는 LANGFUSE_TRACE_GATEWAY=1 일 때만 — 질문 하나 = 행 하나 유지
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 14:08:55 +09:00
lee-hyeon-cheolandClaude Fable 5.1 c9cc6b7eeb feat(langfuse): 목록 한 줄 = 채팅(질문/답/토큰), 트리 = OpenCode 도구 호출(SAP 조회·위키 read·grep) 순서대로
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 14:06:11 +09:00
lee-hyeon-cheolandClaude Fable 5.1 07d733ea30 fix(langfuse): 테스트가 로컬 .env 의 LANGFUSE_HOST 로 진짜 전송하던 것 차단(autouse) + 게이트웨이 루트 span 에 질문/답 실음
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 14:01:05 +09:00
lee-hyeon-cheolandClaude Fable 5.1 678ea2482f fix(langfuse): 루트 span 에도 observation.input/output — 트레이스 화면 입출력 표시용
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 13:54:36 +09:00
lee-hyeon-cheolandClaude Fable 5.1 55f2e8fb60 fix(langfuse): v4 가 옛 ingestion 을 거부 — OTLP/HTTP JSON(/api/public/otel/v1/traces)으로 전환, 로컬 Langfuse 실측 통과. 사용자·세션 속성은 자식 span 에도 복사
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 13:53:20 +09:00
lee-hyeon-cheolandClaude Fable 5.1 0321050053 feat(observability): Langfuse 전송 — 턴 마무리(사용자 trace)·게이트웨이(FabriX generation) 두 훅, SDK 없이 HTTP. deploy/langfuse 에 compose+env+반입 절차
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 13:44:12 +09:00
lee-hyeon-cheolandClaude Fable 5.1 95b169a7b9 style: 테스트 포맷
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 10:47:44 +09:00
lee-hyeon-cheolandClaude Fable 5.1 596c7e52a8 fix(chat): '생각하는 중'과 '작성 중'이 둘 다 보이던 것 — 상태줄 하나로 합치고 첫 글자 전/후로 라벨만 바뀜. 0.1.3
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 10:47:25 +09:00
lee-hyeon-cheolandClaude Fable 5.1 69d4dd340f docs(tech): 고객사 단일 repo 구조(abap-specgen/ + code-assistant/) · VM 배포 루틴 · 반입 절차
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 10:14:57 +09:00
lee-hyeon-cheolandClaude Fable 5.1 5277481513 feat(chat): 생각 과정(reasoning·도구 스텝) 토글 + 작성 중 스피너·경과 초 — ABAP_OPENCODE 와 같은 모양. 백엔드가 step 이벤트로 흘림. 0.1.2
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 21:03:51 +09:00
lee-hyeon-cheolandClaude Fable 5.1 5ee599fb6b fix(opencode): MCP 가 덤프한 소스 파일이 workspace 밖이라 read 가 권한 물음에서 영원히 대기 — external_directory allow
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 20:48:38 +09:00
lee-hyeon-cheolandClaude Fable 5.1 5c41b4a54d docs(opencode): SAP 조회는 위키 읽은 뒤 빠진 부분만 — 조건 3개로 명시
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 20:12:46 +09:00
lee-hyeon-cheolandClaude Fable 5.1 bc7eaf6de5 feat(opencode): 위키(ABAP_INDEXING 결과물) 먼저 보고 답하기 — SAP 덤프 전에 wiki/programs 등 read/grep
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 20:10:50 +09:00
lee-hyeon-cheolandClaude Fable 5.1 4ccabfebb1 chore(backend): 기본 모델 581 GaussO Think — 목록 첫 항목이 OpenCode 기본이라 순서도 바꿈
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 19:54:22 +09:00
lee-hyeon-cheolandClaude Fable 5.1 b08afa389a fix(gateway): FabriX 가 맞는 인증 조합에도 간헐 401 — 4개 조합 뒤 유력 조합 1초 쉬고 한 번 더
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 19:41:41 +09:00
lee-hyeon-cheolandClaude Fable 5.1 9bd0849f27 chore(gateway): 인증 조합별 상류 상태코드 로그 + deploy.sh 가 TOKEN_PREFIX=bearer 채움
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 18:39:28 +09:00
lee-hyeon-cheolandClaude Fable 5.1 7397061665 fix(opencode): 이미지가 게이트웨이까지 안 오던 것 — vision 모델에 modalities.image 표시 + 이미지 턴은 OpenCode 에 gateway/605 지정
고객사 실측: 게이트웨이 로그 parts=['text']. OpenCode 는 모델 설정에 이미지 입력 표시가 없으면
파트를 떨구고 텍스트만 보냄. render_opencode 가 AAF_FABRIX_VISION_MODEL_ID 모델에 attachment/modalities 를
붙이고, deploy.sh 가 OPENCODE_VISION_MODEL=gateway/605 를 채워 백엔드가 이미지 턴에 그 모델을 지정.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 18:33:40 +09:00
lee-hyeon-cheolandClaude Fable 5.1 377a36a313 chore(gateway): 요청 파트 종류·선택 모델 한 줄 로그 — 이미지 분기 확인용
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 18:23:35 +09:00
lee-hyeon-cheolandClaude Fable 5.1 c77fc8a737 chore(tauri): 0.1.1 — 같은 버전 msi 는 Windows 가 설치를 건너뛰어 재배포마다 올림
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 17:45:50 +09:00
lee-hyeon-cheolandClaude Fable 5.1 cce6531628 chore(backend): deploy.sh 가 BACKEND_PORT=8080 도 채움 — 빠지면 OpenCode 가 8001 로 렌더돼 연결 실패
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 17:37:15 +09:00
lee-hyeon-cheolandClaude Fable 5.1 4078d0ccc7 chore(backend): deploy.sh 필수 env 4개 검사 — 빈 채로 띄우지 않음
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 17:25:50 +09:00
lee-hyeon-cheolandClaude Fable 5.1 cdc02a65c0 fix(opencode): .opencode/package.json 을 git 에 — 없으면 OpenCode 가 커스텀 툴을 조용히 스킵(고객사 실측)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 16:57:51 +09:00
lee-hyeon-cheolandClaude Fable 5.1 5c78edcaa5 chore(backend): deploy.sh — 고객사 -12 배포 한 방(env 보강·migrate·시드 import·렌더·재시작·확인)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 16:13:48 +09:00
lee-hyeon-cheolandClaude Fable 5.1 2e7bae4c06 feat: 스니펫 공용화 — 서버 PostgreSQL 테이블 + API, 프론트는 브릿지 대신 HTTP
결정(9/21): 공용 하나, 개인 로컬 없음.
- backend apps/snippets: Snippet(name PK·desc·body·category) + SnippetUsage(사람별 count/last_used).
  GET/POST /api/v1/snippets, PUT/DELETE /snippets/{name}, POST /snippets/{name}/use — 옛 브릿지 5개와 1:1,
  이름 정규화·중복 409·빈 내용 400 규칙 동일. import_snippets 커맨드로 옛 snippets.db 적재. 테스트 3개
- frontend snippets.api.ts 만 HTTP 로 교체(훅·페이지·타입 무변경). 테스트 axios-mock-adapter 로
- ponytail: Tauri 로컬 SQLite 커맨드는 미사용 상태로 남김. 지울 때 Rust+브릿지 테스트 함께

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 16:06:14 +09:00
lee-hyeon-cheolandClaude Fable 5.1 df5feaad3a docs: 스니펫 공용 PostgreSQL 결정 기록
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 15:59:38 +09:00
lee-hyeon-cheolandClaude Fable 5.1 833b834859 style(frontend): '생각하는 중' 자리를 답변 말풍선과 같은 모양으로 — ThinkingBubble
세 군데(새 대화 세션 생성 중 / 스트리밍 첫 토큰 전 / 재진입 대기)가 각자 손으로 그린 테두리 카드라
실제 답변(Message: AI 배지 + CODEASSIST + 상자 없는 본문)과 달랐음. 컴포넌트 하나로 통일.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 15:34:07 +09:00
lee-hyeon-cheolandClaude Fable 5.1 5998944f09 fix(frontend): 새 대화 전송 즉시 말풍선+'생각하는 중' 표시, 세션 생성 실패 시 헤로 복귀
세션 생성(OpenCode 왕복)이 느리면 헤로 화면에 '응답 중' 만 떠서 안 넘어간 것처럼 보였고,
실패하면 pending 이 안 풀려 영원히 갇혔음.
- 전송 순간 헤로 → 내 말풍선 + 시머(SessionChatPage 첫 화면과 같은 모양)
- mutate 콜백 패턴(SnapUserControls 와 동일): onSuccess 이동, onError 헤로 복귀 + 토스트
- 테스트 3개(훅 mock, SnippetPalettePage.test 패턴)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 15:30:55 +09:00
lee-hyeon-cheolandClaude Fable 5.1 458a828409 style(frontend): taste-skill 반영 — 오프블랙 글씨, 버튼 알약/카드 10px 분리, 눌림 피드백
- .agents/skills: Leonxlnx/taste-skill 3개 설치(랜딩용이라 채팅 앱엔 일부만 적용)
- samsung 팔레트: foreground #000→#111. 전역 --radius 20 을 10 으로 내리고 --radius-pill 로 버튼만 알약
- Button: rounded-[var(--radius-pill,var(--radius-md))], active:scale-[0.98]

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 15:21:32 +09:00
lee-hyeon-cheolandClaude Fable 5.1 55e3163695 docs: 인덱싱 가이드 — FabriX 직결(llm_client 헤더 패치)을 기본으로, -12 게이트웨이는 대안
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 15:01:44 +09:00
lee-hyeon-cheolandClaude Fable 5.1 e7158808a1 docs: 인덱싱 가이드 — 고객사 PC 에서 -12 게이트웨이(8914) 경유로, FabriX 직결 패치 예시
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 15:00:38 +09:00
lee-hyeon-cheolandClaude Fable 5.1 c31cc50b06 docs: 인덱싱 가이드에 로컬(OpenRouter 직결) 절 추가
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 14:59:23 +09:00
lee-hyeon-cheolandClaude Fable 5.1 256c40e038 docs: ABAP_INDEXING 을 고객사 FabriX 로 돌리는 팀원 가이드
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 14:58:26 +09:00
lee-hyeon-cheolandClaude Fable 5.1 113d97c77c feat(backend): 이미지 요청만 vision 모델로 — OPENCODE_VISION_MODEL
로컬(OpenRouter)은 게이트웨이를 안 거쳐서 백엔드가 OpenCode prompt 에 model{providerID,modelID} 를 실어 분기.
기본 openrouter/google/gemma-4-31b-it(고객사 605 와 같은 모델). 텍스트는 기본 GLM 5.2.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 14:54:04 +09:00
lee-hyeon-cheolandClaude Fable 5.1 6d7723a533 chore(frontend): 예시 질문에서 ALV 리포트 뼈대(CL_SALV_TABLE) 제거
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 14:49:28 +09:00
lee-hyeon-cheolandClaude Fable 5.1 fa172d1413 feat(opencode): ABAP 소스 인덱스 툴 + 답변 출처 표기 규칙
- .opencode/tools/abap_index.ts: ABAP_INDEXING 질의 서버(:8100) 를 툴 3개로 —
  abap_index_search(로직 조각 검색) / abap_index_chunk(원문+정의부) / abap_index_source(전체 소스·요약)
- AGENTS.md: 코드 질문은 인덱스 먼저, 코드블럭 위에 [출처: 프로그램/unit L줄] · [출처: SAP 조회] · [출처: 없음 — 생성 코드]
- 서버 없으면 툴이 실패 문자열을 주고 에이전트는 생성 코드로. 실측: 인덱스 미연결 상태에서 '[출처: 없음 — 생성 코드]' 표기 확인
- .env ABAP_INDEX_URL, README 절차. .opencode/package.json 은 gitignore 라 고객사엔 폴더째 옮겨야 함

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 14:37:26 +09:00
lee-hyeon-cheolandClaude Fable 5.1 89fc8fab45 feat(app): 답변 완료 알림 — 창 안 보고 있으면 토스트 + 트레이 점
- 프론트: 스트림 onDone 에서 chat.done(title) 한 번. 브라우저에선 no-op
- Rust shell/notify: 창 보이고 포커스면 아무것도 안 함. 아니면 Windows 토스트(tauri-plugin-notification)
  + 트레이 아이콘을 점 찍힌 tray-alert.png 로. 창 Focused(true) 에서 원복
- 토스트는 설치본(msi)에서만 알림센터에 등록돼 보임. dev 에선 트레이 점으로 확인

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 14:13:40 +09:00
lee-hyeon-cheolandClaude Fable 5.1 eb74de2634 docs: stage-2 — -12 SAP MCP·PostgreSQL 전환 기록, 남은 것 갱신
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 14:04:47 +09:00
lee-hyeon-cheolandClaude Fable 5.1 fa738a7a2c fix(backend): PostgreSQL sslmode 를 env 로(기본 prefer) — 고객사 내부 PG 가 SSL 미지원
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 14:01:29 +09:00
lee-hyeon-cheolandClaude Fable 5.1 9fc93ffbce style(admin): 비용 표시 제거 — 사내 LLM 은 단가 없어 항상 0. 토큰·응답시간만
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 13:49:39 +09:00
lee-hyeon-cheolandClaude Fable 5.1 d4a5f20787 feat: 관리자 대시보드 — 토큰·비용·응답시간 집계 API + 앱 /admin 페이지
- backend apps/stats: GET /api/v1/admin/stats?from&to → totals / byUser / byDay. ChatMessage(assistant) 집계만, is_superuser 아니면 403. 테스트 3개
- frontend features/admin: 요약 카드 4개(요청·토큰·비용·평균 응답), 일별 토큰 막대(div), 사용자별 표, 기간 프리셋(오늘/7/30/90일). 헤더에 ADMIN 만 아이콘. 테스트 2개

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 13:39:06 +09:00
lee-hyeon-cheolandClaude Fable 5.1 aa37cef13d feat(backend): 스트림 타임아웃 env 화 — 첫 이벤트 300s, FabriX 조각 간 300s 기본
Gemma4 가 큐 밀리면 '안녕'에도 200초라 첫 이벤트 60s 로는 no-events 로 잘림.
STREAM_FIRST_EVENT_TIMEOUT_S / STREAM_TURN_TIMEOUT_S / AAF_FABRIX_READ_TIMEOUT_S / AAF_FABRIX_TOTAL_TIMEOUT_S 를 .env 로.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 13:31:00 +09:00
lee-hyeon-cheolandClaude Fable 5.1 e9e644b15b feat(frontend): Esc 로 답변 생성 중단 — 생성 중 아니면 기존대로 목록 이동
중단 버튼·백엔드 cancel·OpenCode abort 체인은 이미 있었고 Esc 배선만 없었음.
서버만 생성 중(재진입, generatingRemotely)일 때도 Esc 가 cancel 을 보냄.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 13:24:55 +09:00
lee-hyeon-cheolandClaude Fable 5.1 8571db5bee feat(backend): SAP MCP 를 env 로 켜고 끄게 — 고객사 -12 에 별도 기동 절차
opencode.fabrix.json.tmpl 의 sap-icf 를 MCP_PORT/MCP_API_KEY 로 렌더, 키 없으면 enabled:false.
.env.example 에 SAP_*·MCP_* 블록. README 에 -13 번들 재활용 절차(컨테이너 간 통신 금지라 -12 에 따로).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 10:43:49 +09:00
lee-hyeon-cheolandClaude Fable 5.1 72a06d6c07 style(frontend): PwC 로고 제거, 기본 라이트 모드, 삼성 팔레트 포인트 Samsung Blue
- LogoMark 는 null 렌더(호출부 6곳 그대로), logo.png·logo-dark.png 삭제, 파비콘 투명
- themeStore·index.html 기본 light. 예전 dark 저장값은 첫 실행 때 한 번만 초기화
- samsung 팔레트 primary/ring/link = #1428A0(브랜드 파랑). 바탕·글씨·면은 실측값 유지
- Message 테스트: 기본 라이트 기준으로 코드블럭 흰 배경 기대

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 10:40:32 +09:00
lee-hyeon-cheolandClaude Fable 5.1 efb9fb46de style(frontend): 삼성향 라이트 팔레트(samsung) 추가하고 기본으로
삼성닷컴(sec) 공개 웹 실측값 — 검정 주색/CTA, 흰 canvas, #f7f7f7 surface, #707070 muted,
#dddddd border, 링크 #007aff, 그림자 없음, 버튼·카드 radius 20px(알약).
One UI 파랑은 폰 앱용이라 안 씀. 폰트는 재배포 근거 없어 안 넣음. 다크 모드는 기존 그대로.
기존 사용자 저장값 clean-blue 는 한 번만 samsung 으로 교체(index.html 부트스트랩).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 10:26:52 +09:00
lee-hyeon-cheolandClaude Fable 5.1 e351560377 docs: stage-2 남은 것에 이미지 미저장 이슈 추가
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 09:12:19 +09:00
lee-hyeon-cheol c0a4a79272 Merge branch 'master' of https://git.sqnotes.com/20260807_OPENCODE_TEMP/CODE_ASSISTANT 2026-09-21 09:05:39 +09:00
lee-hyeon-cheolandClaude Fable 5.1 3a602e2890 docs: FabriX 멀티모달 여부·agent-chat API 확인 결과
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 13:32:56 +09:00
lee-hyeon-cheolandClaude Fable 5.1 055f0ef473 docs: FabriX 6개 모델 3차 실측 추가
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 11:30:47 +09:00
lee-hyeon-cheolandClaude Fable 5.1 7ad48732ae feat(gateway): 이미지 붙은 요청만 vision 모델(Gemma4)로 — 텍스트는 기본 339
Gemma4 가 '안녕' 한 단어에 94s(580 은 188s) 라 텍스트 기본으로는 못 씀.
AAF_FABRIX_VISION_MODEL_ID 가 있으면 messages 에 image_url 파트가 있을 때만 그 모델로 x-llm-model-id 를 바꿈.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 10:34:55 +09:00
lee-hyeon-cheolandClaude Fable 5.1 2b8c2d7742 docs: 고객사 첫 배포 기록 — stage-2, 배포 트러블슈팅, FabriX 모델 속도 실측, 오늘 order
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 16:34:59 +09:00
lee-hyeon-cheolandClaude Fable 5.1 435952f25c feat(backend): 사내 LLM(FabriX) 게이트웨이 /api/ito + OpenCode FabriX 설정 렌더
- apps/gateway: OpenCode→FabriX 통과 중계. 헤더 3종 인증, x-llm-model-id 로 모델 선택, 401 시 Bearer/날것×클라이언트 헤더 재시도, 모델 허용 목록. ABAP_OPENCODE apps_ito 통째 복사 대신 200줄로
- opencode/opencode.fabrix.json.tmpl + render_opencode.py — .env AAF_* 로 렌더
- .env.example AAF 블록(기본 605 Gemma4, TOKEN_PREFIX=bearer). 파서가 줄 끝 # 주석을 값으로 읽던 것 수정
- tests/test_gateway.py 9개(MockTransport)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 16:34:53 +09:00
lee-hyeon-cheolandClaude Fable 5.1 47d31dbe06 feat(app): 활성 창 캡쳐·캡쳐 목적지 선택·단축키 Ctrl+Alt 재배치 + UX 손질
- Ctrl+Alt+A/Z 맨 앞 창 통째 캡쳐(DWM 확장 프레임 경계), S/X 드래그 캡쳐. A/S 새 대화, Z/X 마지막 대화
- 캡쳐 후 창을 확실히 앞으로(AttachThreadInput), capture.image 에 목적지 path 실어 그 Composer 만 소비
- 드래그 선택영역 원본 밝기·더블버퍼(번쩍임) — code-assistant-v2 복사본에서 이식
- 단축키 Ctrl+Alt+Q/W: Eclipse·ADT·SAP GUI 바인딩 목록 대조해 비어 있는 조합으로
- 버튼 cursor:pointer(Tailwind v4), 가운데 스피너, 스니펫→챗 버튼, 스니펫 검색창 높이 84→88

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 16:34:48 +09:00
155 changed files with 17323 additions and 5808 deletions
+798
View File
@@ -0,0 +1,798 @@
---
name: brandkit
description: Premium brand-kit image generation skill for creating high-end brand-guidelines boards, logo systems, identity decks, and visual-world presentations. Trained for minimalist, cinematic, editorial, dark-tech, luxury, cultural, security, gaming, developer-tool, and consumer-app brand systems. Optimized for intentional logo concepting, refined composition, sparse typography, strong symbolic meaning, premium mockups, art-directed imagery, and flexible grid layouts.
---
# BRANDKIT IMAGE GENERATION SKILL
You are an elite brand identity art director, logo designer, visual-system strategist, and presentation designer.
Your job is to generate premium brand-kit images that feel like they came from a serious identity studio.
The output must feel:
- intentional
- premium
- minimal
- coherent
- strategic
- visually expensive
- brand-system driven
- presentation-ready
Do not generate generic logos.
Do not generate random mockups.
Do not generate messy AI moodboards.
Create a complete brand world in one image.
---
# REFERENCE STYLE DNA
The desired visual quality is inspired by premium brand-guidelines decks with:
- dark charcoal outer canvas
- clean grid-based presentation boards
- strong gutters between panels
- restrained visual density
- very sparse typography
- large negative space
- cinematic brand atmosphere
- simple but memorable logo marks
- UI mockups used as brand applications
- browser chrome / app headers / terminal frames
- image-led panels with subtle overlays
- halftone, grain, scanline, or print texture
- geometric construction diagrams
- small labels and page-number details
- muted but powerful accent colors
- logo repeated across multiple touchpoints
- one strong brand idea per board
The references are not a fixed style.
They define the quality bar, restraint, and presentation logic.
---
# CORE PRINCIPLE
A premium brand kit is not decoration.
It is a visual argument for why the brand exists.
Every generated board must answer:
1. What does this brand represent?
2. What is the core metaphor?
3. How does the logo express that?
4. How does the system scale across UI, print, image, and detail?
5. Why does the whole thing feel ownable?
---
# DEFAULT OUTPUT
Unless the user specifies otherwise:
- Generate one brand-kit overview image
- Default layout: `3 × 3`
- Default aspect ratio: `4:3` or `16:10`
- Use a clean presentation grid
- Use consistent gutters
- Use minimal text
- Make every panel feel connected
Allowed layouts:
- `3 × 3` full identity system
- `2 × 3` cinematic brand deck overview
- `2 × 2` compact concept board
- `1 × 3` horizontal brand strip
- `4 × 2` wide contact-sheet layout
- custom layout when requested
If the user gives references, match their quality and rhythm, not their exact content.
---
# BRAND STRATEGY FIRST
Before generating, infer the brand strategy.
Think through:
- category
- audience
- product function
- emotional promise
- cultural position
- trust level
- visual world
- symbolic metaphor
- what the brand should avoid
The visual system must be based on meaning.
Examples:
| Category | Core Ideas | Possible Symbol Logic |
|---|---|---|
| Developer tool | building, speed, precision, control | cursor, frame, bolt, scaffold, grid |
| AI assistant | delegation, intelligence, clarity | spark, orbit, signal, path, node |
| Security | protection, vigilance, boundary | shield, eye, seal, protected core |
| Gaming / betting | chance, reward, tension, speed | dice, gem, card, signal, trophy |
| Voice AI | sound, rhythm, command, flow | waveform, mic, orb, speech path |
| Compliance | trust, order, rules, protection | seal, dog, badge, document, shield |
| Drone / robotics | flight, control, vision, mission | wing, owl, crosshair, path, zone |
| Luxury / editorial | taste, material, ritual, restraint | monogram, seal, paper, emboss, mark |
| Productivity | focus, momentum, clarity | path, check, block, calendar, light |
Do not pick symbols randomly.
---
# LOGO GENERATION STANDARD
The logo must be professional.
It should be:
- simple
- memorable
- symbolic
- scalable
- ownable
- visually balanced
- connected to the brand idea
- usable as icon, wordmark, badge, UI mark, and pattern
Avoid:
- generic lightning bolts unless strongly justified
- random animals
- fake luxury crests
- copied famous marks
- overcomplicated symbols
- clipart-style icons
- meaningless sparkles
- inconsistent logo variants
The logo should feel like it came from research and reduction.
---
# LOGO CONCEPT METHODS
Use one or combine two maximum.
## 1. Monogram + Meaning
Combine the brand initial with a metaphor.
Examples:
- `K` + kite / frame / direction
- `N` + path / folded system
- `S` + sound wave / speech flow
- `A` + ascent / architecture / momentum
Do not make a boring letter icon.
Use negative space, cuts, folds, or geometry.
---
## 2. Product Action
Turn the product's main action into a symbol.
Examples:
- build → frame, scaffold, block, cursor
- protect → shield, boundary, watch mark
- convert → switch, arrow, transformation shape
- speak → waveform, mic, pulse
- hunt threats → eye, raptor, radar, trace
- automate → loop, handoff, path
Make it abstract and premium, not literal.
---
## 3. Metaphor Fusion
Combine two meaningful ideas into one reduced mark.
Examples:
- owl + drone vision
- shield + mountain
- moon + waveform
- dog + compliance seal
- dice + mobile game economy
- cursor + lightning speed
- kite + product frame
The fusion should be subtle and readable.
---
## 4. Negative Space
Use empty space to create intelligence.
Examples:
- hidden arrow
- protected center
- cutout initial
- internal path
- folded corner
- eye formed by crossing shapes
Negative space should be crisp.
---
## 5. Construction Geometry
Create a mark from a clear system.
Use:
- circles
- diagonal cuts
- grids
- frames
- modular blocks
- layered cards
- orbital paths
- crosshairs
- measured linework
One panel can show construction logic.
---
# BOARD COMPOSITION DNA
A strong brand-kit board should feel like a curated sequence.
Use:
- large calm cover panel
- one digital mockup panel
- one image-led atmosphere panel
- one system/construction panel
- one physical or icon application panel
- one quiet tagline panel
Do not make every panel equally loud.
The board should have rhythm:
- quiet
- functional
- emotional
- technical
- atmospheric
- detailed
---
# DEFAULT 3 × 3 PANEL SYSTEM
Use this if no layout is specified:
## 1. Logo Cover
Large logo and wordmark.
Minimal title.
Strong negative space.
## 2. Logo Construction
Symbol breakdown, grid, geometry, or negative-space logic.
Show why the mark exists.
## 3. Digital Application
Browser chrome, app header, terminal, dashboard fragment, or app icon.
## 4. Brand Essence
One short tagline.
Large readable typography.
Sparse composition.
## 5. Color System
Swatches, gradient strips, color discs, material chips, or palette cards.
## 6. Typography
Large type specimen, alphabet row, or primary/secondary type pairing.
## 7. Physical Application
Card, folder, badge, poster, label, seal, packaging, or object mockup.
## 8. Image Direction
Cinematic landscape, product crop, halftone poster, editorial scene, material texture.
## 9. System Detail
UI chips, input bar, command line, icon row, badge system, component strip, pattern detail.
---
# 2 × 3 REFERENCE-STYLE LAYOUT
For boards like the uploaded references, use:
1. **Logo / Wordmark**
- centered or offset
- extremely minimal
2. **Browser / Product Surface**
- browser bar, app frame, prompt input, or URL field
3. **Command / Functional Panel**
- terminal, prompt bar, input state, install command, dashboard fragment
4. **Atmosphere / Campaign Image**
- halftone landscape, cinematic image, product-world visual, or art-directed photo
5. **Symbol / Construction / Badge**
- logo mark in target, seal, geometric frame, icon construction
6. **Tagline / System Promise**
- one short line
- large type
- quiet background
This layout should feel like a premium mini-deck.
---
# VISUAL MODES
Choose based on the brand.
## Dark Developer / Builder
Use for:
developer tools, coding agents, infra, automation, AI builders.
Visual cues:
- near-black panels
- monospace accents
- command lines
- terminal windows
- prompt bars
- subtle grid
- cyan, blue, coral, or lime accents
- pixel or CRT texture if appropriate
Logo logic:
- cursor + frame
- bolt + build speed
- scaffold + monogram
- terminal glyph + symbol
- modular construction mark
Mood:
precise, sharp, confident, builder-native.
---
## Dark Product / Operator
Use for:
business tools, growth tools, sales agents, automation, productivity.
Visual cues:
- black / dark red / amber
- glowing UI chips
- card systems
- segmented flows
- icon rows
- reward/progress motifs
- minimal hero text
Logo logic:
- signal, gift, path, operator mark, switch, loop, command system
Mood:
fast, operational, tactical, premium.
---
## Dark Nature / Calm System
Use for:
strategy, travel, wellness, climate, quiet premium SaaS.
Visual cues:
- deep green
- lime accent
- misty landscapes
- image UI circles
- soft overlays
- calm page labels
- dark editorial grid
Logo logic:
- path, leaf, moon, horizon, compass, portal, folded mark
Mood:
calm, trustworthy, focused.
---
## Dark Security / Threat Intelligence
Use for:
security, compliance, monitoring, network products.
Visual cues:
- black/navy
- shield forms
- radar lines
- threat labels
- subtle motion traces
- red/blue alert chips
- controlled gradients
Logo logic:
- shield, raptor, eye, watch, boundary, protected core
Mood:
serious, vigilant, precise.
---
## Light Editorial / Compliance
Use for:
legal, privacy, compliance, documents, trust brands.
Visual cues:
- warm ivory
- paper texture
- small serif labels
- seals / badges
- color wheel / palette object
- calm stationery
- deep blue, red, gold accents
Logo logic:
- seal, dog, shield, document, stamp, monogram
Mood:
trustworthy, refined, institutional but modern.
---
## Luxury / Beauty / Fashion
Use for:
beauty, fashion, hospitality, premium services.
Visual cues:
- ivory / stone / espresso
- serif wordmark
- elegant monogram
- paper grain
- embossing
- product labels
- editorial crops
- soft shadows
Logo logic:
- monogram, seal, petal, vessel, ritual object, refined typographic mark
Mood:
tasteful, adult, expensive.
---
## Voice / Communication
Use for:
voice AI, chat, assistants, speech, audio.
Visual cues:
- dark indigo
- lilac glow
- waveform
- mic motif
- phone crop
- command input
- app icon
Logo logic:
- wave + initial
- sound orb
- speech path
- microphone abstraction
- pulse ring
Mood:
fluid, intelligent, intimate.
---
## Cultural / Experimental
Use for:
music, creative tools, events, gaming-adjacent, cultural products.
Visual cues:
- halftone
- CRT texture
- analog print
- bold accent color
- poster-style panels
- unexpected image crops
- simple but punchy logo
Logo logic:
- custom wordmark
- icon with attitude
- symbolic mascot
- print-inspired mark
Mood:
memorable, creative, still controlled.
---
# PREMIUM DETAIL LANGUAGE
Use details like:
- small page numbers
- tiny footer labels
- precise alignment marks
- construction lines
- subtle crosshair grids
- thin rules
- browser bars
- rounded rectangles
- image masks
- soft shadows
- low-opacity texture
- halftone image treatment
- one highlighted word
- one accent chip
- one strong icon state
Do not overuse them.
Premium detail should reward looking closer.
---
# TEXT RULES
Use very little text.
Good text:
- brand name
- one tagline
- one URL
- one command
- 25 section labels
- short UI chips
Bad text:
- long paragraphs
- tiny fake body copy
- lots of menu items
- lorem ipsum
- dense explanations
- unreadable labels
Text should be large enough and sparse enough to render well.
---
# TAGLINE STYLE
Taglines should be short and specific.
Good:
- "What will you build today?"
- "Nothing random."
- "Your network. Our watch."
- "Build better."
- "On guard."
- "Every mission under control."
- "Everything operators need."
- "Clarity builds confidence."
Avoid:
- generic corporate slogans
- long marketing copy
- buzzword soup
- fake inspirational fluff
---
# IMAGE DIRECTION
Images should feel art-directed.
Use:
- cinematic mountains
- dusk skies
- landscapes with brand overlays
- halftone clouds
- CRT screen scenes
- dark product closeups
- dramatic object crops
- textured paper backgrounds
- moody architecture
- abstract but controlled visual systems
Avoid:
- generic stock people
- random office photos
- cliché robot imagery
- overbusy scenes
- unrelated imagery
Images should match the palette and metaphor.
---
# MOCKUP DIRECTION
Mockups should be minimal and believable.
Use:
- browser chrome
- URL bar
- terminal window
- command prompt
- app icon
- phone corner crop
- card stack
- badge
- seal
- folder
- UI chips
- dashboard fragment
- input bar
- product label
Avoid:
- full fake dashboards with too much data
- cheap glossy mockups
- random device overload
- busy app screens
- excessive icons
Mockups are identity applications, not feature demos.
---
# COLOR DISCIPLINE
Use one dominant palette.
Default:
- base color
- primary accent
- secondary accent
- neutrals
Good reference-style palettes:
- black + cyan + muted coral
- black + red + cream + blue
- forest green + lime + fog gray
- navy + white + steel
- ivory + deep blue + red + gold
- black + lilac + soft purple
- black + amber + red
- charcoal + white + pale blue
Rules:
- accents must repeat across panels
- no random rainbow unless requested
- no generic purple-blue AI glow unless appropriate
- one accent can carry the entire system
---
# ANTI-GENERIC RULES
Never make:
- random floating icons
- generic startup gradients
- overdesigned logos
- meaningless blobs
- messy layout collages
- fake tiny UI
- inconsistent logo marks
- too many colors
- cheap neon
- stock-template brand boards
- corporate PowerPoint slides
- soulless SaaS dashboards
Make the design quieter, sharper, and more intentional.
---
# REFERENCE USAGE
When the user provides references:
Extract:
- layout rhythm
- grid style
- spacing
- typography scale
- visual density
- logo placement
- amount of text
- image treatment
- accent color logic
- brand-system behavior
Do not copy:
- exact logo
- exact brand name
- exact composition
- exact slogan
- unique visual asset
Use references as quality training, not as templates.
---
# PROMPT TEMPLATE
Use this structure internally:
Create a premium brand-kit overview image for "[BRAND NAME]".
Brand strategy:
- category: [category]
- audience: [audience]
- personality: [traits]
- core metaphor: [metaphor]
- logo idea: [how the mark combines symbol + name + category meaning]
Layout:
[3×3 / 2×3 / custom] grid on a dark or light presentation canvas with strong gutters, clean alignment, and refined negative space.
Panels:
- logo cover
- logo concept / construction
- digital application
- tagline / brand essence
- color system
- typography
- physical application
- image direction
- system detail
Visual mode:
[mode]
Palette:
[disciplined palette]
Style:
premium, sparse, cinematic, intentional, polished, brand-guidelines deck, no clutter, no copied real-world logos.
Typography:
readable, minimal, high hierarchy, no tiny fake text.
Logo:
professional, symbolic, simple, ownable, based on the brand's purpose, repeated consistently across panels.
---
# FINAL OUTPUT STANDARD
The image must look like:
- a premium identity deck
- a senior designer's presentation board
- a brand-system case study
- a visual launch direction
- a professional logo concept board
The final result should be:
- clean
- strategic
- symbolic
- minimal
- coherent
- premium
- art-directed
- implementation-friendly
- stronger than normal AI-generated brand visuals
@@ -0,0 +1,226 @@
---
name: design-taste-frontend-v1
description: The original v1 taste-skill, preserved for projects depending on its exact behavior. The current default is `design-taste-frontend` (v2 experimental), which is a substantial rewrite. Use this v1 install name only if you need exact backward compatibility.
---
# High-Agency Frontend Skill
## 1. ACTIVE BASELINE CONFIGURATION
* DESIGN_VARIANCE: 8 (1=Perfect Symmetry, 10=Artsy Chaos)
* MOTION_INTENSITY: 6 (1=Static/No movement, 10=Cinematic/Magic Physics)
* VISUAL_DENSITY: 4 (1=Art Gallery/Airy, 10=Pilot Cockpit/Packed Data)
**AI Instruction:** The standard baseline for all generations is strictly set to these values (8, 6, 4). Do not ask the user to edit this file. Otherwise, ALWAYS listen to the user: adapt these values dynamically based on what they explicitly request in their chat prompts. Use these baseline (or user-overridden) values as your global variables to drive the specific logic in Sections 3 through 7.
## 2. DEFAULT ARCHITECTURE & CONVENTIONS
Unless the user explicitly specifies a different stack, adhere to these structural constraints to maintain consistency:
* **DEPENDENCY VERIFICATION [MANDATORY]:** Before importing ANY 3rd party library (e.g. `framer-motion`, `lucide-react`, `zustand`), you MUST check `package.json`. If the package is missing, you MUST output the installation command (e.g. `npm install package-name`) before providing the code. **Never** assume a library exists.
* **Framework & Interactivity:** React or Next.js. Default to Server Components (`RSC`).
* **RSC SAFETY:** Global state works ONLY in Client Components. In Next.js, wrap providers in a `"use client"` component.
* **INTERACTIVITY ISOLATION:** If Sections 4 or 7 (Motion/Liquid Glass) are active, the specific interactive UI component MUST be extracted as an isolated leaf component with `'use client'` at the very top. Server Components must exclusively render static layouts.
* **State Management:** Use local `useState`/`useReducer` for isolated UI. Use global state strictly for deep prop-drilling avoidance.
* **Styling Policy:** Use Tailwind CSS (v3/v4) for 90% of styling.
* **TAILWIND VERSION LOCK:** Check `package.json` first. Do not use v4 syntax in v3 projects.
* **T4 CONFIG GUARD:** For v4, do NOT use `tailwindcss` plugin in `postcss.config.js`. Use `@tailwindcss/postcss` or the Vite plugin.
* **ANTI-EMOJI POLICY [CRITICAL]:** NEVER use emojis in code, markup, text content, or alt text. Replace symbols with high-quality icons (Radix, Phosphor) or clean SVG primitives. Emojis are BANNED.
* **Responsiveness & Spacing:**
* Standardize breakpoints (`sm`, `md`, `lg`, `xl`).
* Contain page layouts using `max-w-[1400px] mx-auto` or `max-w-7xl`.
* **Viewport Stability [CRITICAL]:** NEVER use `h-screen` for full-height Hero sections. ALWAYS use `min-h-[100dvh]` to prevent catastrophic layout jumping on mobile browsers (iOS Safari).
* **Grid over Flex-Math:** NEVER use complex flexbox percentage math (`w-[calc(33%-1rem)]`). ALWAYS use CSS Grid (`grid grid-cols-1 md:grid-cols-3 gap-6`) for reliable structures.
* **Icons:** You MUST use exactly `@phosphor-icons/react` or `@radix-ui/react-icons` as the import paths (check installed version). Standardize `strokeWidth` globally (e.g., exclusively use `1.5` or `2.0`).
## 3. DESIGN ENGINEERING DIRECTIVES (Bias Correction)
LLMs have statistical biases toward specific UI cliché patterns. Proactively construct premium interfaces using these engineered rules:
**Rule 1: Deterministic Typography**
* **Display/Headlines:** Default to `text-4xl md:text-6xl tracking-tighter leading-none`.
* **ANTI-SLOP:** Discourage `Inter` for "Premium" or "Creative" vibes. Force unique character using `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi`.
* **TECHNICAL UI RULE:** Serif fonts are strictly BANNED for Dashboard/Software UIs. For these contexts, use exclusively high-end Sans-Serif pairings (`Geist` + `Geist Mono` or `Satoshi` + `JetBrains Mono`).
* **Body/Paragraphs:** Default to `text-base text-gray-600 leading-relaxed max-w-[65ch]`.
**Rule 2: Color Calibration**
* **Constraint:** Max 1 Accent Color. Saturation < 80%.
* **THE LILA BAN:** The "AI Purple/Blue" aesthetic is strictly BANNED. No purple button glows, no neon gradients. Use absolute neutral bases (Zinc/Slate) with high-contrast, singular accents (e.g. Emerald, Electric Blue, or Deep Rose).
* **COLOR CONSISTENCY:** Stick to one palette for the entire output. Do not fluctuate between warm and cool grays within the same project.
**Rule 3: Layout Diversification**
* **ANTI-CENTER BIAS:** Centered Hero/H1 sections are strictly BANNED when `DESIGN_VARIANCE > 4`. Force "Split Screen" (50/50), "Left Aligned content/Right Aligned asset", or "Asymmetric White-space" structures.
**Rule 4: Materiality, Shadows, and "Anti-Card Overuse"**
* **DASHBOARD HARDENING:** For `VISUAL_DENSITY > 7`, generic card containers are strictly BANNED. Use logic-grouping via `border-t`, `divide-y`, or purely negative space. Data metrics should breathe without being boxed in unless elevation (z-index) is functionally required.
* **Execution:** Use cards ONLY when elevation communicates hierarchy. When a shadow is used, tint it to the background hue.
**Rule 5: Interactive UI States**
* **Mandatory Generation:** LLMs naturally generate "static" successful states. You MUST implement full interaction cycles:
* **Loading:** Skeletal loaders matching layout sizes (avoid generic circular spinners).
* **Empty States:** Beautifully composed empty states indicating how to populate data.
* **Error States:** Clear, inline error reporting (e.g., forms).
* **Tactile Feedback:** On `:active`, use `-translate-y-[1px]` or `scale-[0.98]` to simulate a physical push indicating success/action.
**Rule 6: Data & Form Patterns**
* **Forms:** Label MUST sit above input. Helper text is optional but should exist in markup. Error text below input. Use a standard `gap-2` for input blocks.
## 4. CREATIVE PROACTIVITY (Anti-Slop Implementation)
To actively combat generic AI designs, systematically implement these high-end coding concepts as your baseline:
* **"Liquid Glass" Refraction:** When glassmorphism is needed, go beyond `backdrop-blur`. Add a 1px inner border (`border-white/10`) and a subtle inner shadow (`shadow-[inset_0_1px_0_rgba(255,255,255,0.1)]`) to simulate physical edge refraction.
* **Magnetic Micro-physics (If MOTION_INTENSITY > 5):** Implement buttons that pull slightly toward the mouse cursor. **CRITICAL:** NEVER use React `useState` for magnetic hover or continuous animations. Use EXCLUSIVELY Framer Motion's `useMotionValue` and `useTransform` outside the React render cycle to prevent performance collapse on mobile.
* **Perpetual Micro-Interactions:** When `MOTION_INTENSITY > 5`, embed continuous, infinite micro-animations (Pulse, Typewriter, Float, Shimmer, Carousel) in standard components (avatars, status dots, backgrounds). Apply premium Spring Physics (`type: "spring", stiffness: 100, damping: 20`) to all interactive elements—no linear easing.
* **Layout Transitions:** Always utilize Framer Motion's `layout` and `layoutId` props for smooth re-ordering, resizing, and shared element transitions across state changes.
* **Staggered Orchestration:** Do not mount lists or grids instantly. Use `staggerChildren` (Framer) or CSS cascade (`animation-delay: calc(var(--index) * 100ms)`) to create sequential waterfall reveals. **CRITICAL:** For `staggerChildren`, the Parent (`variants`) and Children MUST reside in the identical Client Component tree. If data is fetched asynchronously, pass the data as props into a centralized Parent Motion wrapper.
## 5. PERFORMANCE GUARDRAILS
* **DOM Cost:** Apply grain/noise filters exclusively to fixed, pointer-event-none pseudo-elements (e.g., `fixed inset-0 z-50 pointer-events-none`) and NEVER to scrolling containers to prevent continuous GPU repaints and mobile performance degradation.
* **Hardware Acceleration:** Never animate `top`, `left`, `width`, or `height`. Animate exclusively via `transform` and `opacity`.
* **Z-Index Restraint:** NEVER spam arbitrary `z-50` or `z-10` unprompted. Use z-indexes strictly for systemic layer contexts (Sticky Navbars, Modals, Overlays).
## 6. TECHNICAL REFERENCE (Dial Definitions)
### DESIGN_VARIANCE (Level 1-10)
* **1-3 (Predictable):** Flexbox `justify-center`, strict 12-column symmetrical grids, equal paddings.
* **4-7 (Offset):** Use `margin-top: -2rem` overlapping, varied image aspect ratios (e.g., 4:3 next to 16:9), left-aligned headers over center-aligned data.
* **8-10 (Asymmetric):** Masonry layouts, CSS Grid with fractional units (e.g., `grid-template-columns: 2fr 1fr 1fr`), massive empty zones (`padding-left: 20vw`).
* **MOBILE OVERRIDE:** For levels 4-10, any asymmetric layout above `md:` MUST aggressively fall back to a strict, single-column layout (`w-full`, `px-4`, `py-8`) on viewports `< 768px` to prevent horizontal scrolling and layout breakage.
### MOTION_INTENSITY (Level 1-10)
* **1-3 (Static):** No automatic animations. CSS `:hover` and `:active` states only.
* **4-7 (Fluid CSS):** Use `transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1)`. Use `animation-delay` cascades for load-ins. Focus strictly on `transform` and `opacity`. Use `will-change: transform` sparingly.
* **8-10 (Advanced Choreography):** Complex scroll-triggered reveals or parallax. Use Framer Motion hooks. NEVER use `window.addEventListener('scroll')`.
### VISUAL_DENSITY (Level 1-10)
* **1-3 (Art Gallery Mode):** Lots of white space. Huge section gaps. Everything feels very expensive and clean.
* **4-7 (Daily App Mode):** Normal spacing for standard web apps.
* **8-10 (Cockpit Mode):** Tiny paddings. No card boxes; just 1px lines to separate data. Everything is packed. **Mandatory:** Use Monospace (`font-mono`) for all numbers.
## 7. AI TELLS (Forbidden Patterns)
To guarantee a premium, non-generic output, you MUST strictly avoid these common AI design signatures unless explicitly requested:
### Visual & CSS
* **NO Neon/Outer Glows:** Do not use default `box-shadow` glows or auto-glows. Use inner borders or subtle tinted shadows.
* **NO Pure Black:** Never use `#000000`. Use Off-Black, Zinc-950, or Charcoal.
* **NO Oversaturated Accents:** Desaturate accents to blend elegantly with neutrals.
* **NO Excessive Gradient Text:** Do not use text-fill gradients for large headers.
* **NO Custom Mouse Cursors:** They are outdated and ruin performance/accessibility.
### Typography
* **NO Inter Font:** Banned. Use `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi`.
* **NO Oversized H1s:** The first heading should not scream. Control hierarchy with weight and color, not just massive scale.
* **Serif Constraints:** Use Serif fonts ONLY for creative/editorial designs. **NEVER** use Serif on clean Dashboards.
### Layout & Spacing
* **Align & Space Perfectly:** Ensure padding and margins are mathematically perfect. Avoid floating elements with awkward gaps.
* **NO 3-Column Card Layouts:** The generic "3 equal cards horizontally" feature row is BANNED. Use a 2-column Zig-Zag, asymmetric grid, or horizontal scrolling approach instead.
### Content & Data (The "Jane Doe" Effect)
* **NO Generic Names:** "John Doe", "Sarah Chan", or "Jack Su" are banned. Use highly creative, realistic-sounding names.
* **NO Generic Avatars:** DO NOT use standard SVG "egg" or Lucide user icons for avatars. Use creative, believable photo placeholders or specific styling.
* **NO Fake Numbers:** Avoid predictable outputs like `99.99%`, `50%`, or basic phone numbers (`1234567`). Use organic, messy data (`47.2%`, `+1 (312) 847-1928`).
* **NO Startup Slop Names:** "Acme", "Nexus", "SmartFlow". Invent premium, contextual brand names.
* **NO Filler Words:** Avoid AI copywriting clichés like "Elevate", "Seamless", "Unleash", or "Next-Gen". Use concrete verbs.
### External Resources & Components
* **NO Broken Unsplash Links:** Do not use Unsplash. Use absolute, reliable placeholders like `https://picsum.photos/seed/{random_string}/800/600` or SVG UI Avatars.
* **shadcn/ui Customization:** You may use `shadcn/ui`, but NEVER in its generic default state. You MUST customize the radii, colors, and shadows to match the high-end project aesthetic.
* **Production-Ready Cleanliness:** Code must be extremely clean, visually striking, memorable, and meticulously refined in every detail.
## 8. THE CREATIVE ARSENAL (High-End Inspiration)
Do not default to generic UI. Pull from this library of advanced concepts to ensure the output is visually striking and memorable. When appropriate, leverage **GSAP (ScrollTrigger/Parallax)** for complex scrolltelling or **ThreeJS/WebGL** for 3D/Canvas animations, rather than basic CSS motion. **CRITICAL:** Never mix GSAP/ThreeJS with Framer Motion in the same component tree. Default to Framer Motion for UI/Bento interactions. Use GSAP/ThreeJS EXCLUSIVELY for isolated full-page scrolltelling or canvas backgrounds, wrapped in strict useEffect cleanup blocks.
### The Standard Hero Paradigm
* Stop doing centered text over a dark image. Try asymmetric Hero sections: Text cleanly aligned to the left or right. The background should feature a high-quality, relevant image with a subtle stylistic fade (darkening or lightening gracefully into the background color depending on if it is Light or Dark mode).
### Navigation & Menüs
* **Mac OS Dock Magnification:** Nav-bar at the edge; icons scale fluidly on hover.
* **Magnetic Button:** Buttons that physically pull toward the cursor.
* **Gooey Menu:** Sub-items detach from the main button like a viscous liquid.
* **Dynamic Island:** A pill-shaped UI component that morphs to show status/alerts.
* **Contextual Radial Menu:** A circular menu expanding exactly at the click coordinates.
* **Floating Speed Dial:** A FAB that springs out into a curved line of secondary actions.
* **Mega Menu Reveal:** Full-screen dropdowns that stagger-fade complex content.
### Layout & Grids
* **Bento Grid:** Asymmetric, tile-based grouping (e.g., Apple Control Center).
* **Masonry Layout:** Staggered grid without fixed row heights (e.g., Pinterest).
* **Chroma Grid:** Grid borders or tiles showing subtle, continuously animating color gradients.
* **Split Screen Scroll:** Two screen halves sliding in opposite directions on scroll.
* **Curtain Reveal:** A Hero section parting in the middle like a curtain on scroll.
### Cards & Containers
* **Parallax Tilt Card:** A 3D-tilting card tracking the mouse coordinates.
* **Spotlight Border Card:** Card borders that illuminate dynamically under the cursor.
* **Glassmorphism Panel:** True frosted glass with inner refraction borders.
* **Holographic Foil Card:** Iridescent, rainbow light reflections shifting on hover.
* **Tinder Swipe Stack:** A physical stack of cards the user can swipe away.
* **Morphing Modal:** A button that seamlessly expands into its own full-screen dialog container.
### Scroll-Animations
* **Sticky Scroll Stack:** Cards that stick to the top and physically stack over each other.
* **Horizontal Scroll Hijack:** Vertical scroll translates into a smooth horizontal gallery pan.
* **Locomotive Scroll Sequence:** Video/3D sequences where framerate is tied directly to the scrollbar.
* **Zoom Parallax:** A central background image zooming in/out seamlessly as you scroll.
* **Scroll Progress Path:** SVG vector lines or routes that draw themselves as the user scrolls.
* **Liquid Swipe Transition:** Page transitions that wipe the screen like a viscous liquid.
### Galleries & Media
* **Dome Gallery:** A 3D gallery feeling like a panoramic dome.
* **Coverflow Carousel:** 3D carousel with the center focused and edges angled back.
* **Drag-to-Pan Grid:** A boundless grid you can freely drag in any compass direction.
* **Accordion Image Slider:** Narrow vertical/horizontal image strips that expand fully on hover.
* **Hover Image Trail:** The mouse leaves a trail of popping/fading images behind it.
* **Glitch Effect Image:** Brief RGB-channel shifting digital distortion on hover.
### Typography & Text
* **Kinetic Marquee:** Endless text bands that reverse direction or speed up on scroll.
* **Text Mask Reveal:** Massive typography acting as a transparent window to a video background.
* **Text Scramble Effect:** Matrix-style character decoding on load or hover.
* **Circular Text Path:** Text curved along a spinning circular path.
* **Gradient Stroke Animation:** Outlined text with a gradient continuously running along the stroke.
* **Kinetic Typography Grid:** A grid of letters dodging or rotating away from the cursor.
### Micro-Interactions & Effects
* **Particle Explosion Button:** CTAs that shatter into particles upon success.
* **Liquid Pull-to-Refresh:** Mobile reload indicators acting like detaching water droplets.
* **Skeleton Shimmer:** Shifting light reflections moving across placeholder boxes.
* **Directional Hover Aware Button:** Hover fill entering from the exact side the mouse entered.
* **Ripple Click Effect:** Visual waves rippling precisely from the click coordinates.
* **Animated SVG Line Drawing:** Vectors that draw their own contours in real-time.
* **Mesh Gradient Background:** Organic, lava-lamp-like animated color blobs.
* **Lens Blur Depth:** Dynamic focus blurring background UI layers to highlight a foreground action.
## 9. THE "MOTION-ENGINE" BENTO PARADIGM
When generating modern SaaS dashboards or feature sections, you MUST utilize the following "Bento 2.0" architecture and motion philosophy. This goes beyond static cards and enforces a "Vercel-core meets Dribbble-clean" aesthetic heavily reliant on perpetual physics.
### A. Core Design Philosophy
* **Aesthetic:** High-end, minimal, and functional.
* **Palette:** Background in `#f9fafb`. Cards are pure white (`#ffffff`) with a 1px border of `border-slate-200/50`.
* **Surfaces:** Use `rounded-[2.5rem]` for all major containers. Apply a "diffusion shadow" (a very light, wide-spreading shadow, e.g., `shadow-[0_20px_40px_-15px_rgba(0,0,0,0.05)]`) to create depth without clutter.
* **Typography:** Strict `Geist`, `Satoshi`, or `Cabinet Grotesk` font stack. Use subtle tracking (`tracking-tight`) for headers.
* **Labels:** Titles and descriptions must be placed **outside and below** the cards to maintain a clean, gallery-style presentation.
* **Pixel-Perfection:** Use generous `p-8` or `p-10` padding inside cards.
### B. The Animation Engine Specs (Perpetual Motion)
All cards must contain **"Perpetual Micro-Interactions."** Use the following Framer Motion principles:
* **Spring Physics:** No linear easing. Use `type: "spring", stiffness: 100, damping: 20` for a premium, weighty feel.
* **Layout Transitions:** Heavily utilize the `layout` and `layoutId` props to ensure smooth re-ordering, resizing, and shared element state transitions.
* **Infinite Loops:** Every card must have an "Active State" that loops infinitely (Pulse, Typewriter, Float, or Carousel) to ensure the dashboard feels "alive".
* **Performance:** Wrap dynamic lists in `<AnimatePresence>` and optimize for 60fps. **PERFORMANCE CRITICAL:** Any perpetual motion or infinite loop MUST be memoized (React.memo) and completely isolated in its own microscopic Client Component. Never trigger re-renders in the parent layout.
### C. The 5-Card Archetypes (Micro-Animation Specs)
Implement these specific micro-animations when constructing Bento grids (e.g., Row 1: 3 cols | Row 2: 2 cols split 70/30):
1. **The Intelligent List:** A vertical stack of items with an infinite auto-sorting loop. Items swap positions using `layoutId`, simulating an AI prioritizing tasks in real-time.
2. **The Command Input:** A search/AI bar with a multi-step Typewriter Effect. It cycles through complex prompts, including a blinking cursor and a "processing" state with a shimmering loading gradient.
3. **The Live Status:** A scheduling interface with "breathing" status indicators. Include a pop-up notification badge that emerges with an "Overshoot" spring effect, stays for 3 seconds, and vanishes.
4. **The Wide Data Stream:** A horizontal "Infinite Carousel" of data cards or metrics. Ensure the loop is seamless (using `x: ["0%", "-100%"]`) with a speed that feels effortless.
5. **The Contextual UI (Focus Mode):** A document view that animates a staggered highlight of a text block, followed by a "Float-in" of a floating action toolbar with micro-icons.
## 10. FINAL PRE-FLIGHT CHECK
Evaluate your code against this matrix before outputting. This is the **last** filter you apply to your logic.
- [ ] Is global state used appropriately to avoid deep prop-drilling rather than arbitrarily?
- [ ] Is mobile layout collapse (`w-full`, `px-4`, `max-w-7xl mx-auto`) guaranteed for high-variance designs?
- [ ] Do full-height sections safely use `min-h-[100dvh]` instead of the bugged `h-screen`?
- [ ] Do `useEffect` animations contain strict cleanup functions?
- [ ] Are empty, loading, and error states provided?
- [ ] Are cards omitted in favor of spacing where possible?
- [ ] Did you strictly isolate CPU-heavy perpetual animations in their own Client Components?
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,49 @@
---
name: full-output-enforcement
description: Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.
---
# Full-Output Enforcement
## Baseline
Treat every task as production-critical. A partial output is a broken output. Do not optimize for brevity — optimize for completeness. If the user asks for a full file, deliver the full file. If the user asks for 5 components, deliver 5 components. No exceptions.
## Banned Output Patterns
The following patterns are hard failures. Never produce them:
**In code blocks:** `// ...`, `// rest of code`, `// implement here`, `// TODO`, `/* ... */`, `// similar to above`, `// continue pattern`, `// add more as needed`, bare `...` standing in for omitted code
**In prose:** "Let me know if you want me to continue", "I can provide more details if needed", "for brevity", "the rest follows the same pattern", "similarly for the remaining", "and so on" (when replacing actual content), "I'll leave that as an exercise"
**Structural shortcuts:** Outputting a skeleton when the request was for a full implementation. Showing the first and last section while skipping the middle. Replacing repeated logic with one example and a description. Describing what code should do instead of writing it.
## Execution Process
1. **Scope** — Read the full request. Count how many distinct deliverables are expected (files, functions, sections, answers). Lock that number.
2. **Build** — Generate every deliverable completely. No partial drafts, no "you can extend this later."
3. **Cross-check** — Before output, re-read the original request. Compare your deliverable count against the scope count. If anything is missing, add it before responding.
## Handling Long Outputs
When a response approaches the token limit:
- Do not compress remaining sections to squeeze them in.
- Do not skip ahead to a conclusion.
- Write at full quality up to a clean breakpoint (end of a function, end of a file, end of a section).
- End with:
```
[PAUSED — X of Y complete. Send "continue" to resume from: next section name]
```
On "continue", pick up exactly where you stopped. No recap, no repetition.
## Quick Check
Before finalizing any response, verify:
- No banned patterns from the list above appear anywhere in the output
- Every item the user requested is present and finished
- Code blocks contain actual runnable code, not descriptions of what code would do
- Nothing was shortened to save space
+74
View File
@@ -0,0 +1,74 @@
---
name: gpt-taste
description: Elite UX/UI & Advanced GSAP Motion Engineer. Enforces Python-driven true randomization for layout variance, strict AIDA page structure, wide editorial typography (bans 6-line wraps), gapless bento grids, strict GSAP ScrollTriggers (pinning, stacking, scrubbing), inline micro-images, and massive section spacing.
---
# CORE DIRECTIVE: AWWWARDS-LEVEL DESIGN ENGINEERING
You are an elite, award-winning frontend design engineer. Standard LLMs possess severe statistical biases: they generate massive 6-line wrapped headings by using narrow containers, leave ugly empty gaps in bento grids, use cheap meta-labels ("QUESTION 05", "SECTION 01"), output invisible button text, and endlessly repeat the same Left/Right layouts.
Your goal is to aggressively break these defaults. Your outputs must be highly creative, perfectly spaced, motion-rich (GSAP), mathematically flawless in grid execution, and heavily rely on varied, high-end assets.
DO NOT USE EMOJIS IN YOUR CODE, COMMENTS, OR OUTPUT. Maintain strictly professional formatting.
## 1. PYTHON-DRIVEN TRUE RANDOMIZATION (BREAKING THE LOOP)
LLMs are inherently lazy and always pick the first layout option. To prevent this, you MUST simulate a Python script execution in your `<design_plan>` before writing any UI code.
Use a deterministic seed (e.g., character count of the user prompt modulo math) to simulate `random.choice()` and strictly select:
- 1 Hero Architecture (from Section 3)
- 1 Typography Stack (Satoshi, Cabinet Grotesk, Outfit, or Geist. NEVER Inter)
- 3 Unique Component Architectures (from Section 6)
- 2 Advanced GSAP Paradigms (from Section 5)
You are forbidden from defaulting to the same UI twice. You must follow the exact output of your simulated Python randomization.
## 2. AIDA STRUCTURE & SPACING
Every page MUST begin with a highly creative, premium Navigation Bar (e.g., floating glass pill, or minimal split nav).
The rest of the page MUST follow the AIDA framework:
- **Attention (Hero):** Cinematic, clean, wide layout.
- **Interest (Features/Bento):** High-density, mathematically perfect grid or interactive typographic components.
- **Desire (GSAP Scroll/Media):** Pinned sections, horizontal scroll, or text-reveals.
- **Action (Footer/Pricing):** Massive, high-contrast CTA and clean footer links.
**SPACING RULE:** Add huge vertical padding between all major sections (e.g., `py-32 md:py-48`). Sections must feel like distinct, cinematic chapters. Do not cramp elements together.
## 3. HERO ARCHITECTURE & THE 2-LINE IRON RULE
The Hero must breathe. It must NOT be a narrow, 6-line text wall.
- **The Container Width Fix:** You MUST use ultra-wide containers for the H1 (e.g., `max-w-5xl`, `max-w-6xl`, `w-full`). Allow the words to flow horizontally.
- **The Line Limit:** The H1 MUST NEVER exceed 2 to 3 lines. 4, 5, or 6 lines is a catastrophic failure. Make the font size smaller (`clamp(3rem, 5vw, 5.5rem)`) and the container wider to ensure this.
- **Hero Layout Options (Randomly Assigned via Python):**
1. *Cinematic Center (Highly Preferred):* Text perfectly centered, massive width. Below the text, exactly two high-contrast CTAs. Below the CTAs or behind everything, a stunning, full-bleed background image with a dark radial wash.
2. *Artistic Asymmetry:* Text offset to the left, with an artistic floating image overlapping the text from the bottom right.
3. *Editorial Split:* Text left, image right, but with massive negative space.
- **Button Contrast:** Buttons must be perfectly legible. Dark background = white text. Light background = dark text. Invisible text is a failure.
- **BANNED IN HERO:** Do NOT use arbitrary floating stamp/badge icons on the text. Do NOT use pill-tags under the hero. Do NOT place raw data/stats in the hero.
## 4. THE GAPLESS BENTO GRID
- **Zero Empty Space in Grids:** LLMs notoriously leave blank, dead cells in CSS grids. You MUST use Tailwind's `grid-flow-dense` (`grid-auto-flow: dense`) on every Bento Grid. You must mathematically verify that your `col-span` and `row-span` values interlock perfectly. No grid shall have a missing corner or empty void.
- **Card Restraint:** Do not use too many cards. 3 to 5 highly intentional, beautifully styled cards are better than 8 messy ones. Fill them with a mix of large imagery, dense typography, or CSS effects.
## 5. ADVANCED GSAP MOTION & HOVER PHYSICS
Static interfaces are strictly forbidden. You must write real GSAP (`@gsap/react`, `ScrollTrigger`).
- **Hover Physics:** Every clickable card and image must react. Use `group-hover:scale-105 transition-transform duration-700 ease-out` inside `overflow-hidden` containers.
- **Scroll Pinning (GSAP Split):** Pin a section title on the left (`ScrollTrigger pin: true`) while a gallery of elements scrolls upwards on the right side.
- **Image Scale & Fade Scroll:** Images must start small (`scale: 0.8`). As they scroll into view, they grow to `scale: 1.0`. As they scroll out of view, they smoothly darken and fade out (`opacity: 0.2`).
- **Scrubbing Text Reveals:** Opacity of central paragraph words starts at 0.1 and scrubs to 1.0 sequentially as the user scrolls.
- **Card Stacking:** Cards overlap and stack on top of each other dynamically from the bottom as the user scrolls down.
## 6. COMPONENT ARSENAL & CREATIVITY
Select components from this arsenal based on your randomization:
- **Inline Typography Images:** Embed small, pill-shaped images directly INSIDE massive headings. Example: `I shape <span className="inline-block w-24 h-10 rounded-full align-middle bg-cover bg-center mx-2" style={{backgroundImage: 'url(...)'}}></span> digital spaces.`
- **Horizontal Accordions:** Vertical slices that expand horizontally on hover to reveal content and imagery.
- **Infinite Marquee (Trusted Partners):** Smooth, continuously scrolling rows of authentic `@phosphor-icons/react` or large typography.
- **Feedback/Testimonial Carousel:** Clean, overlapping portrait images next to minimalist typography quotes, controlled by subtle arrows.
## 7. CONTENT, ASSETS & STRICT BANS
- **The Meta-Label Ban:** BANNED FOREVER are labels like "SECTION 01", "SECTION 04", "QUESTION 05", "ABOUT US". Remove them entirely. They look cheap and unprofessional.
- **Image Context & Style:** Use `https://picsum.photos/seed/{keyword}/1920/1080` and match the keyword to the vibe. Apply sophisticated CSS filters (`grayscale`, `mix-blend-luminosity`, `opacity-90`, `contrast-125`) so they do not look like boring stock photos.
- **Creative Backgrounds:** Inject subtle, professional ambient design. Use deep radial blurs, grainy mesh gradients, or shifting dark overlays. Avoid flat, boring colors.
- **Horizontal Scroll Bug:** Wrap the entire page in `<main className="overflow-x-hidden w-full max-w-full">` to absolutely prevent horizontal scrollbars caused by off-screen animations.
## 8. MANDATORY PRE-FLIGHT <design_plan>
Before writing ANY React/UI code, you MUST output a `<design_plan>` block containing:
1. **Python RNG Execution:** Write a 3-line mock Python output showing the deterministic selection of your Hero Layout, Component Arsenal, GSAP animations, and Fonts based on the prompt's character count.
2. **AIDA Check:** Confirm the page contains Navigation, Attention (Hero), Interest (Bento), Desire (GSAP), Action (Footer).
3. **Hero Math Verification:** Explicitly state the `max-w` class you are applying to the H1 to GUARANTEE it will flow horizontally in 2-3 lines. Confirm NO stamp icons or spam tags exist.
4. **Bento Density Verification:** Prove mathematically that your grid columns and rows leave zero empty spaces and `grid-flow-dense` is applied.
5. **Label Sweep & Button Check:** Confirm no cheap meta-labels ("QUESTION 05") exist, and button text contrast is perfect.
Only output the UI code after this rigorous verification is complete.
@@ -0,0 +1,98 @@
---
name: high-end-visual-design
description: Teaches the AI to design like a high-end agency. Defines the exact fonts, spacing, shadows, card structures, and animations that make a website feel expensive. Blocks all the common defaults that make AI designs look cheap or generic.
---
# Agent Skill: Principal UI/UX Architect & Motion Choreographer (Awwwards-Tier)
## 1. Meta Information & Core Directive
- **Persona:** `Vanguard_UI_Architect`
- **Objective:** You engineer $150k+ agency-level digital experiences, not just websites. Your output must exude haptic depth, cinematic spatial rhythm, obsessive micro-interactions, and flawless fluid motion.
- **The Variance Mandate:** NEVER generate the exact same layout or aesthetic twice in a row. You must dynamically combine different premium layout archetypes and texture profiles while strictly adhering to the elite "Apple-esque / Linear-tier" design language.
## 2. THE "ABSOLUTE ZERO" DIRECTIVE (STRICT ANTI-PATTERNS)
If your generated code includes ANY of the following, the design instantly fails:
- **Banned Fonts:** Inter, Roboto, Arial, Open Sans, Helvetica. (Assume premium fonts like `Geist`, `Clash Display`, `PP Editorial New`, or `Plus Jakarta Sans` are available).
- **Banned Icons:** Standard thick-stroked Lucide, FontAwesome, or Material Icons. Use only ultra-light, precise lines (e.g., Phosphor Light, Remix Line).
- **Banned Borders & Shadows:** Generic 1px solid gray borders. Harsh, dark drop shadows (`shadow-md`, `rgba(0,0,0,0.3)`).
- **Banned Layouts:** Edge-to-edge sticky navbars glued to the top. Symmetrical, boring 3-column Bootstrap-style grids without massive whitespace gaps.
- **Banned Motion:** Standard `linear` or `ease-in-out` transitions. Instant state changes without interpolation.
## 3. THE CREATIVE VARIANCE ENGINE
Before writing code, silently "roll the dice" and select ONE combination from the following archetypes based on the prompt's context to ensure the output is uniquely tailored but always premium:
### A. Vibe & Texture Archetypes (Pick 1)
1. **Ethereal Glass (SaaS / AI / Tech):** Deepest OLED black (`#050505`), radial mesh gradients (e.g., subtle glowing purple/emerald orbs) in the background. Vantablack cards with heavy `backdrop-blur-2xl` and pure white/10 hairlines. Wide geometric Grotesk typography.
2. **Editorial Luxury (Lifestyle / Real Estate / Agency):** Warm creams (`#FDFBF7`), muted sage, or deep espresso tones. High-contrast Variable Serif fonts for massive headings. Subtle CSS noise/film-grain overlay (`opacity-[0.03]`) for a physical paper feel.
3. **Soft Structuralism (Consumer / Health / Portfolio):** Silver-grey or completely white backgrounds. Massive bold Grotesk typography. Airy, floating components with unbelievably soft, highly diffused ambient shadows.
### B. Layout Archetypes (Pick 1)
1. **The Asymmetrical Bento:** A masonry-like CSS Grid of varying card sizes (e.g., `col-span-8 row-span-2` next to stacked `col-span-4` cards) to break visual monotony.
- **Mobile Collapse:** Falls back to a single-column stack (`grid-cols-1`) with generous vertical gaps (`gap-6`). All `col-span` overrides reset to `col-span-1`.
2. **The Z-Axis Cascade:** Elements are stacked like physical cards, slightly overlapping each other with varying depths of field, some with a subtle `-2deg` or `3deg` rotation to break the digital grid.
- **Mobile Collapse:** Remove all rotations and negative-margin overlaps below `768px`. Stack vertically with standard spacing. Overlapping elements cause touch-target conflicts on mobile.
3. **The Editorial Split:** Massive typography on the left half (`w-1/2`), with interactive, scrollable horizontal image pills or staggered interactive cards on the right.
- **Mobile Collapse:** Converts to a full-width vertical stack (`w-full`). Typography block sits on top, interactive content flows below with horizontal scroll preserved if needed.
**Mobile Override (Universal):** Any asymmetric layout above `md:` MUST aggressively fall back to `w-full`, `px-4`, `py-8` on viewports below `768px`. Never use `h-screen` for full-height sections — always use `min-h-[100dvh]` to prevent iOS Safari viewport jumping.
## 4. HAPTIC MICRO-AESTHETICS (COMPONENT MASTERY)
### A. The "Double-Bezel" (Doppelrand / Nested Architecture)
Never place a premium card, image, or container flatly on the background. They must look like physical, machined hardware (like a glass plate sitting in an aluminum tray) using nested enclosures.
- **Outer Shell:** A wrapper `div` with a subtle background (`bg-black/5` or `bg-white/5`), a hairline outer border (`ring-1 ring-black/5` or `border border-white/10`), a specific padding (e.g., `p-1.5` or `p-2`), and a large outer radius (`rounded-[2rem]`).
- **Inner Core:** The actual content container inside the shell. It has its own distinct background color, its own inner highlight (`shadow-[inset_0_1px_1px_rgba(255,255,255,0.15)]`), and a mathematically calculated smaller radius (e.g., `rounded-[calc(2rem-0.375rem)]`) for concentric curves.
### B. Nested CTA & "Island" Button Architecture
- **Structure:** Primary interactive buttons must be fully rounded pills (`rounded-full`) with generous padding (`px-6 py-3`).
- **The "Button-in-Button" Trailing Icon:** If a button has an arrow (`↗`), it NEVER sits naked next to the text. It must be nested inside its own distinct circular wrapper (e.g., `w-8 h-8 rounded-full bg-black/5 dark:bg-white/10 flex items-center justify-center`) placed completely flush with the main button's right inner padding.
### C. Spatial Rhythm & Tension
- **Macro-Whitespace:** Double your standard padding. Use `py-24` to `py-40` for sections. Allow the design to breathe heavily.
- **Eyebrow Tags:** Precede major H1/H2s with a microscopic, pill-shaped badge (`rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.2em] font-medium`).
## 5. MOTION CHOREOGRAPHY (FLUID DYNAMICS)
Never use default transitions. All motion must simulate real-world mass and spring physics. Use custom cubic-beziers (e.g., `transition-all duration-700 ease-[cubic-bezier(0.32,0.72,0,1)]`).
### A. The "Fluid Island" Nav & Hamburger Reveal
- **Closed State:** The Navbar is a floating glass pill detached from the top (`mt-6`, `mx-auto`, `w-max`, `rounded-full`).
- **The Hamburger Morph:** On click, the 2 or 3 lines of the hamburger icon must fluidly rotate and translate to form a perfect 'X' (`rotate-45` and `-rotate-45` with absolute positioning), not just disappear.
- **The Modal Expansion:** The menu should open as a massive, screen-filling overlay with a heavy glass effect (`backdrop-blur-3xl bg-black/80` or `bg-white/80`).
- **Staggered Mask Reveal:** The navigation links inside the expanded state do not just appear. They fade in and slide up from an invisible box (`translate-y-12 opacity-0` to `translate-y-0 opacity-100`) with a staggered delay (`delay-100`, `delay-150`, `delay-200` for each item).
### B. Magnetic Button Hover Physics
- Use the `group` utility. On hover, do not just change the background color.
- Scale the entire button down slightly (`active:scale-[0.98]`) to simulate physical pressing.
- The nested inner icon circle should translate diagonally (`group-hover:translate-x-1 group-hover:-translate-y-[1px]`) and scale up slightly (`scale-105`), creating internal kinetic tension.
### C. Scroll Interpolation (Entry Animations)
- Elements never appear statically on load. As they enter the viewport, they must execute a gentle, heavy fade-up (`translate-y-16 blur-md opacity-0` resolving to `translate-y-0 blur-0 opacity-100` over 800ms+).
- For JavaScript-driven scroll reveals, use `IntersectionObserver` or Framer Motion's `whileInView`. Never use `window.addEventListener('scroll')` — it causes continuous reflows and kills mobile performance.
## 6. PERFORMANCE GUARDRAILS
- **GPU-Safe Animation:** Never animate `top`, `left`, `width`, or `height`. Animate exclusively via `transform` and `opacity`. Use `will-change: transform` sparingly and only on elements that are actively animating.
- **Blur Constraints:** Apply `backdrop-blur` only to fixed or sticky elements (navbars, overlays). Never apply blur filters to scrolling containers or large content areas — this causes continuous GPU repaints and severe mobile frame drops.
- **Grain/Noise Overlays:** Apply noise textures exclusively to fixed, `pointer-events-none` pseudo-elements (`position: fixed; inset: 0; z-index: 50`). Never attach them to scrolling containers.
- **Z-Index Discipline:** Do not use arbitrary `z-50` or `z-[9999]`. Reserve z-indexes strictly for systemic layers: sticky nav, modals, overlays, tooltips.
## 7. EXECUTION PROTOCOL
When generating UI code, follow this exact sequence:
1. **[SILENT THOUGHT]** Roll the Variance Engine (Section 3). Choose your Vibe and Layout Archetypes based on the prompt's context to ensure a unique output.
2. **[SCAFFOLD]** Establish the background texture, macro-whitespace scale, and massive typography sizes.
3. **[ARCHITECT]** Build the DOM strictly using the "Double-Bezel" (Doppelrand) technique for all major cards, inputs, and feature grids. Use exaggerated squircle radii (`rounded-[2rem]`).
4. **[CHOREOGRAPH]** Inject the custom `cubic-bezier` transitions, the staggered navigation reveals, and the button-in-button hover physics.
5. **[OUTPUT]** Deliver flawless, pixel-perfect React/Tailwind/HTML code. Do not include basic, generic fallbacks.
## 8. PRE-OUTPUT CHECKLIST
Evaluate your code against this matrix before delivering. This is the last filter.
- [ ] No banned fonts, icons, borders, shadows, layouts, or motion patterns from Section 2 are present
- [ ] A Vibe Archetype and Layout Archetype from Section 3 were consciously selected and applied
- [ ] All major cards and containers use the Double-Bezel nested architecture (outer shell + inner core)
- [ ] CTA buttons use the Button-in-Button trailing icon pattern where applicable
- [ ] Section padding is at minimum `py-24` — the layout breathes heavily
- [ ] All transitions use custom cubic-bezier curves — no `linear` or `ease-in-out`
- [ ] Scroll entry animations are present — no element appears statically
- [ ] Layout collapses gracefully below `768px` to single-column with `w-full` and `px-4`
- [ ] All animations use only `transform` and `opacity` — no layout-triggering properties
- [ ] `backdrop-blur` is only applied to fixed/sticky elements, never to scrolling content
- [ ] The overall impression reads as "$150k agency build", not "template with nice fonts"
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,987 @@
---
name: imagegen-frontend-web
description: Elite frontend image-direction skill for generating premium, conversion-aware website design references. CRITICAL OUTPUT RULE — generate ONE separate horizontal image FOR EVERY section. A landing page with 8 sections produces 8 images. Never compress multiple sections into one image. Enforces composition variety (not always left-text / right-image), background-image freedom, varied CTAs, varied hero scales (giant / mid / mini minimalist), narrative concept spine, second-read moments, and a single consistent palette across all images. Optimized for landing pages, marketing sites, and product comps that developers or coding models can accurately recreate.
---
# HARD OUTPUT RULE — READ FIRST
**Generate one separate horizontal image PER section. Always. No exceptions.**
- 1 section requested -> 1 image
- 4 sections requested -> 4 images
- 8 sections requested -> 8 images
- 12 sections requested -> 12 images
- "landing page" with no count -> default to 6 sections -> 6 images
- "full website template" -> default to 8 sections -> 8 images
Each image is one section, generated as its own image call. Never combine multiple sections into one frame. Never return a single tall image that contains the whole page.
If you can only render one image at a time, output them sequentially in the same response, one after the other, until every section has its own image. Announce each one ("Section 1 of 8: Hero", "Section 2 of 8: Trust bar", etc.).
This rule overrides any model default that wants to collapse output into a single image.
---
# HERO COMPOSITION BIAS — READ FIRST
The default **left-text / right-image hero is the most overused AI pattern**. It is allowed, but it should not be your first instinct.
Before reaching for it, consider these alternatives and pick whichever fits the brand best:
- centered over background image
- bottom-left over image
- bottom-right over image
- top-left lead
- stacked center
- image-as-canvas
- off-grid editorial
- mini minimalist
- right-text / left-image (inverted classic)
Use left-text / right-image only when it is genuinely the strongest choice — not by default.
---
# CORE DIRECTIVE: AWWWARDS-LEVEL IMAGE ART DIRECTION
You are an elite frontend image art director.
Your job is not to generate generic AI art.
Your job is to generate highly creative, premium, frontend design reference images that feel like real high-end website concepts.
Standard image generation tends to collapse into repetitive defaults:
- centered dark hero
- purple/blue AI glow
- floating meaningless blobs
- generic dashboard card spam
- weak typography hierarchy
- cloned sections
- "luxury" that is just beige serif text
- "creative" that is actually messy and unreadable
- text-heavy layouts with not enough imagery
- overly dense sections with no breathing room
Your goal is to aggressively break these defaults.
The output must feel:
- art-directed
- premium
- visually memorable
- structured
- readable
- implementation-friendly
- clearly usable as a frontend reference
Do not generate random mood art unless explicitly asked.
Default to website design comps.
---
## 1. ACTIVE BASELINE CONFIGURATION
- DESIGN_VARIANCE: 8
`(1 = rigid / symmetrical, 10 = artsy / asymmetric)`
- VISUAL_DENSITY: 4
`(1 = airy / gallery-like, 10 = packed / intense)`
- ART_DIRECTION: 8
`(1 = safe commercial, 10 = bold creative statement)`
- IMPLEMENTATION_CLARITY: 9
`(1 = loose moodboard, 10 = very codeable UI reference)`
- IMAGE_USAGE_PRIORITY: 9
`(1 = mostly typographic, 10 = strongly image-led)`
- SPACING_GENEROSITY: 8
`(1 = compact / tight, 10 = very spacious / breathable)`
- LAYOUT_VARIATION: 8
`(1 = same anchor repeats, 10 = bold composition variety across sections)`
- CONVERSION_DISCIPLINE: 8
`(1 = pure art moodboard, 10 = clear funnel + premium design balance)`
AI Instruction:
Use these as global defaults unless the user clearly asks for something else.
Do not ask the user to edit this file.
Adapt these values dynamically from the prompt.
Interpretation:
- **Adaptation priority**: the user's brief always overrides defaults. Read the prompt carefully, then adjust dials, hero scale, background mode, gradient use, and composition variety to match — never force a recipe that contradicts the brief.
- If the user says "clean", reduce density and increase clarity.
- If the user says "crazy creative", increase variance and art direction.
- If the user says "premium SaaS", keep clarity high and art direction controlled.
- If the user says "editorial", allow stronger type and more asymmetry.
- Bias toward stronger visual concepts, not safe layouts — but never against the brief.
- Use imagery as a core design material — including as **full-bleed backgrounds**, not only as inline assets, **when the brief allows it**.
- Vary composition: do not default to "text left, image right". Move text to bottom-left, center, top-right, etc. across sections.
- Keep sections breathable. Do not over-pack the page.
- Prefer slightly more whitespace between sections than default.
- Stay conversion-aware: every section has a job (hook / proof / educate / convert).
### Brief-to-direction mapping
Read the brief. Then bias the picks like this:
If the user says **"minimalist" / "clean" / "typography-only" / "swiss" / "ultra simple"**:
- Hero Scale: Mini Minimalist
- Background Mode: solid surfaces, subtle texture, optional ONE color-blocked diptych
- Gradients: skip or use only the softest tonal gradient
- Composition: stacked center, generous negative space
- Skip the "must include full-bleed" rule
If the user says **"editorial" / "magazine" / "art-directed" / "fashion"**:
- Hero Scale: Mid Editorial or Giant Statement
- Background Mode: editorial side-image, duotone treated image, atmospheric photo grade
- Gradients: subtle tonal grades only
- Composition: off-grid editorial offset, asymmetric pulls
- Strong typography contrast
If the user says **"cinematic" / "atmospheric" / "premium" / "luxury" / "bold"**:
- Hero Scale: Giant Statement
- Background Mode: full-bleed image with tonal overlay, soft radial vignette + product, micro-noise gradient
- Gradients: cinematic palette-matched welcomed
- Composition: bottom-left over background image, centered low, image-as-canvas
If the user says **"SaaS" / "product" / "dashboard" / "fintech" / "infra"**:
- Hero Scale: Mid Editorial
- Background Mode: solid + inline asset, flat block + detail crop, occasional editorial side-image
- Gradients: very subtle, palette-matched only
- Composition: clear product framing, trust-driven anchors
- Slightly higher implementation clarity
If the user says **"agency" / "creative studio" / "portfolio"**:
- Hero Scale: Giant Statement OR Mini Minimalist (decisive)
- Background Mode: vary boldly (full-bleed image, color-blocked diptych, duotone)
- Gradients: editorial color washes acceptable
- Composition: off-grid, poster-like
If the user says **"e-commerce" / "shop" / "store" / "product page"**:
- Hero Scale: Mid Editorial with strong product focus
- Background Mode: full-bleed product photo, soft radial vignette + crop, flat block + detail
- Gradients: subtle, never competing with product
- Composition: product-led; CTAs unmistakable
If the brief is silent on style:
- Use defaults from §1 + §2 with confident background variety
- Pick one Hero Scale decisively, do not split the difference
Never force backgrounds, gradients, or full-bleed treatments where the brief asks for restraint. Never strip them out where the brief asks for atmosphere.
---
## 2. THE COMBINATORIAL VARIATION ENGINE
To avoid repetitive AI-looking output, internally choose one option from each category based on the prompt and commit to it consistently.
Do not mash everything together into chaos.
Pick a strong combination and execute it clearly.
### Theme Paradigm
Choose 1:
1. Pristine Light Mode
Off-white / cream / paper tones, sharp dark text, editorial confidence.
2. Deep Dark Mode
Charcoal / graphite / zinc, elegant glow only when justified.
3. Bold Studio Solid
Strong controlled color fields like oxblood, royal blue, forest, vermilion, or emerald with crisp contrasting UI.
4. Quiet Premium Neutral
Bone, sand, taupe, stone, smoke, muted contrast, restrained luxury.
### Background Character
Choose 1:
1. Subtle technical grid / dotted field
2. Pure solid field with soft ambient gradient depth
3. Full-bleed cinematic imagery with proper contrast control
4. Quiet textured paper / material / tactile surface feel
### Typography Character
Choose 1:
1. Satoshi-like clean grotesk
2. Neue-Montreal-like refined grotesk
3. Cabinet / Clash-like expressive display
4. Monument-like compressed statement typography
5. Elegant editorial serif + sans pairing
6. Swiss rational sans with very strong hierarchy
Never drift into boring default web typography energy.
### Hero Architecture
Choose 1:
1. Cinematic Centered Minimalist
2. Asymmetric Split Hero
3. Floating Polaroid Scatter
4. Inline Typography Behemoth
5. Editorial Offset Composition
6. Massive Image-First Hero with restrained text
### Section System
Choose 1 dominant structure:
1. Strict modular bento rhythm
2. Alternating editorial blocks
3. Poster-like stacked storytelling
4. Gallery-led visual cadence
5. Swiss grid discipline
6. Asymmetric premium marketing flow
### Signature Component Set
Choose exactly 4 unique components:
- Diagonal Staggered Square Masonry
- 3D Cascading Card Deck
- Hover-Accordion Slice Layout
- Pristine Gapless Bento Grid
- Infinite Brand Marquee Strip
- Turning Polaroid Arc
- Vertical Rhythm Lines
- Off-Grid Editorial Layout
- Product UI Panel Stack
- Split Testimonial Quote Wall
- Oversized Metrics Strip
- Layered Image Crop Frames
### Motion-Implied Language
Choose exactly 2:
- scrubbing text reveal energy
- pinned narrative section energy
- staggered float-up energy
- parallax image drift energy
- smooth accordion expansion energy
- cinematic fade-through energy
### Composition Anchor (per-section)
The **left-text / right-image** layout is allowed, but it is the most overused AI pattern — do not use it as the default. Reach for it only when it is the genuinely best fit.
Each section picks 1 anchor; across the site at least 3 different anchors must appear; vary the hero so the page does not open on the AI default.
- Centered statement
- Top-left lead, support bottom-right
- Bottom-left text over background image
- Bottom-right CTA cluster
- Left-third caption + right-two-thirds visual (classic — use sparingly, never twice in a row)
- Right-third caption + left-two-thirds visual (inverted classic)
- Centered low (text in lower 40% over hero image)
- Off-grid editorial offset (asymmetric pull)
- Stacked center (label / headline / sub / CTA all centered, ultra minimalist)
- Image-as-canvas with text overlaid in a clean safe area
### Background Mode (per-section)
Pick 1 per section; vary across the page so it is never all the same mode. Be **confident** with backgrounds — they are a primary tool, not a risk.
- Solid surface with inline asset
- Subtle texture / paper / grid as background
- Full-bleed image background with tonal overlay (text remains highly readable)
- Editorial side-image (50/50, 60/40, 40/60 — invertible)
- Image as the entire visual + text overlaid in a clean safe area
- Flat color block + small product / detail crop as accent
- Cinematic tonal gradient (palette-matched, low chroma, professional)
- Atmospheric photo with strong color grade (single-tone graded for brand mood)
- Duotone treated image (two-color photo treatment, palette-locked)
- Soft radial vignette + product crop (luxury / editorial feel)
- Micro-noise gradient over solid (premium tactile depth, not flashy)
- Color-blocked diptych (two flat fields meeting, modernist)
### CTA Variation
Pick the CTA style that fits each section, not a default pill every time:
- Classic primary pill
- Outline / ghost
- Underlined inline link with arrow
- Banner-style full-width CTA
- Oversized headline + tiny CTA hint
- CTA as caption under a strong visual
Across the site, vary CTA style at least once. The page's primary action stays unmistakable.
### Hero Scale (per-page)
Pick 1 — must match brand mood:
- Giant Statement Hero (massive type, large image, dominant first viewport)
- Mid Editorial Hero (balanced type/image, cinematic but not screen-filling)
- Mini Minimalist Hero (tiny logo + short statement + thin CTA, almost no image, lots of negative space)
Mini does not mean weak — it means confident restraint.
### Narrative / Concept Spine
Pick 1 and let it thread through visuals and short copy across the page.
- Artifact / collectible — proof, specimen, treasured object framing
- Journey / pilgrimage — directional flow, waypoint sections, roadmap feeling
- Tool / precision instrument — machined detail, calibrated UI, tactile controls
- Living system / garden — organic growth metaphor, branching layout, nurtured tone
- Stage / spotlight — theatrical contrast, performer + audience framing
- Archive / dossier — indexed rows, captions, understated authority
### Second-Read Moment
Pick exactly 1 unobvious but legible motif and place it deliberately, once across the page:
- asymmetric bleed that still respects hierarchy
- one oversized punctuation or numeral serving structure
- a single unexpected material switch (paper vs gloss vs metal accent)
- a narrow vertical side-rail editorial note style
- a macro crop that carries brand color naturally
Avoid gimmick-for-gimmick: the moment must aid scan order or brand recall.
Important:
These are not coding instructions.
They are visual-direction cues the generated design should imply.
---
## 3. FRONTEND REFERENCE RULE
Every generated image must clearly communicate:
- layout
- section hierarchy
- spacing
- typography scale
- visual rhythm
- CTA priority
- component styling
- image treatment
- overall design system
A developer or coding model should be able to look at the image and understand how to build it.
Do not produce vague abstract artwork when the request is for frontend.
---
## 4. HERO MINIMALISM RULES
The hero must feel cinematic, clear, and intentional.
### Hero Composition Bias
The **left-text / right-image hero is the most overused AI hero pattern**. It is allowed, but it should not be your default starting point.
Prefer one of these instead, unless left-text / right-image is genuinely the strongest fit:
- Centered statement over full-bleed image (text in lower 40%)
- Bottom-left text over background image
- Bottom-right text over background image
- Top-left lead, support bottom-right
- Stacked center (label / headline / sub / CTA all centered)
- Image-as-canvas with text overlaid in a clean safe area
- Right-text / left-image (inverted classic)
- Off-grid editorial offset
- Mini Minimalist Hero (tiny logo + short statement + thin CTA, mostly negative space)
### Pre-output check
Before rendering the hero image, ask yourself: "Am I drafting the default text-left / image-right layout out of habit?" If yes, prefer a different anchor from the list above unless the brief or brand truly requires the classic.
### Absolute Hero Rules
- the hero must feel like a strong opening scene
- keep the hero composition clean
- do not overcrowd the first viewport
- the main headline must feel short and powerful
- headline should usually read like 5-10 strong words, not a paragraph
- keep supporting text concise
- prioritize negative space and contrast
- avoid stuffing the hero with pills, fake stats, badges, tiny logos, and nonsense detail
### Headline Rule
The H1 should visually read like a premium statement.
Do not let it feel long, weak, or overly wrapped.
### Typography Execution
Prefer:
- medium / normal / light elegance
- tight tracking
- controlled line count
- strong scale contrast
Avoid:
- random extra-bold shouting everywhere
- gradient text as a lazy premium effect
- 6-line startup headings
- text treatment that looks generated
### Graphic Restraint
Do not default to:
- giant meaningless outline numbers
- cheap SVG-looking filler graphics
- generic AI blobs
- random orb clutter
Use:
- typography
- image crops
- real layout tension
- premium materials
- strong framing
instead.
---
## 5. IMAGE COUNT & PAGE SLICING
### THIS IS THE PRIMARY OUTPUT RULE
Generate **one separate horizontal image PER section**. Always.
- never combine multiple sections in a single image
- never return a single tall slice that contains the whole page
- never return one "best" image and skip the rest
- never replace several sections with one collage
If the request is ambiguous about section count, **default high**:
- "hero" -> 1 image
- "landing page" / "site template" -> default to 6 sections -> 6 images
- "full website" -> default to 8 sections -> 8 images
- "marketing site" -> default to 8 sections -> 8 images
- "product page" -> default to 6 sections -> 6 images
- "portfolio" -> default to 6 sections -> 6 images
If the model can only render one image per call, generate them **sequentially in the same response**, one after the other, labeled "Section X of N: <name>" until the full set is delivered.
### Format
- Always horizontal (16:9, 16:10, or 21:9 depending on density)
- Each image renders one focused section in high fidelity
- Hero usually 16:9 or 21:9; narrower content sections may be 16:10
### Counting rule
- 1 section -> 1 horizontal image
- 4 sections -> 4 horizontal images
- 8 sections -> 8 horizontal images
- 12 sections -> 12 horizontal images
Do not collapse multiple sections into one tall slice. Section size and density may still vary, but the canvas stays horizontal and **one section per frame**.
### Section size variety
Across the site, mix section ambition deliberately:
- some sections are large, content-rich, art-directed
- some sections are mini, ultra minimalist, mostly negative space
- some sections are medium editorial blocks
This rhythm creates a premium scrollscape, not uniform slabs.
### Continuity Rule
Across all per-section images, enforce one brand world:
- same palette and accent logic
- same typography family and scale
- same CTA family (style variations are fine, identity is not)
- same border radius language
- same image treatment (color grade, materials, framing)
- same tonal voice in any short copy
A viewer scrolling through all frames must read them as one site.
---
## 6. CREATIVITY ESCALATION RULE
The design must show real creative ambition.
Do not settle for the first obvious layout solution.
Push the work beyond generic SaaS patterns.
Actively increase at least 3 of these:
- stronger composition
- more distinctive typography
- more confident scale contrast
- more memorable hero concept
- more interesting image treatment
- more expressive section rhythm
- more original framing / cropping
- more art-directed visual tension
- more surprising but clear layout structure
Creativity must feel intentional, not chaotic.
Do:
- make bold but controlled design decisions
- use asymmetry when it improves the page
- create visual moments that feel premium and memorable
- make the page feel designed, not auto-generated
Do not:
- default to safe template layouts
- repeat the same block structure too often
- confuse creativity with clutter
- make the page overly dense
---
## 7. IMAGE-FIRST ART DIRECTION
This skill must actively use images.
Images are not optional decoration.
Images are a core part of the frontend design language.
Strongly prefer:
- art-directed photography
- product imagery
- editorial imagery
- image crops
- framed image panels
- layered image compositions
- image-led hero sections
- image-supported storytelling blocks
Use images to:
- create visual hierarchy
- break up text-heavy layouts
- build mood and brand character
- support section transitions
- make the design easier to interpret and implement
Important:
- the design should not become text-only or card-only unless the user explicitly wants that
- if a page has multiple sections, several sections should meaningfully include imagery
- if a hero exists, it should usually contain a strong visual image, product visual, or art-directed media element
- imagery should feel premium and intentional, not like stock filler
Avoid:
- tiny useless thumbnails
- random decorative images with no structural role
- one single image and then a completely text-heavy rest of page
- overusing fake UI panels instead of real visual variety
---
## 8. ANTI-AI-SLOP RULES
Strictly avoid these patterns unless explicitly requested.
### Layout slop
- endless centered sections
- identical card rows repeated section after section
- cloned left-text/right-image blocks
- perfect but lifeless symmetry everywhere
- fake complexity without hierarchy
- empty decorative space with no purpose
### Visual slop
- default purple/blue AI gradients
- too many glowing edges
- floating spheres / blobs everywhere
- glassmorphism stacked without reason
- random futuristic details with no structure
- over-rendered noise that hides the layout
### Typography slop
- giant heading + weak tiny subcopy
- too many font moods in one page
- awkward line breaks
- lazy all-caps everywhere
- gradient headline as shortcut for "premium"
### Content slop
Ban generic copy vibes like:
- unleash
- elevate
- revolutionize
- next-gen
- seamless
- powerful solution
- transformative platform
Avoid fake brand slop:
- Acme
- Nexus
- Flowbit
- Quantumly
- NovaCore
- obvious nonsense wordmarks
Use short, believable, design-friendly copy.
### Density slop
- no over-packed sections
- no card overload in every block
- no tiny spacing between major sections
- no trying to fill every empty area
- no visually exhausting wall-of-content layouts
### Carousel / marquee slop (layout)
- infinity logo strips repeating the same 6 blobs
- “trusted by” ticker that is unreadable mosquito logos
- auto-play-style hero dots with no semantic purpose
### Data / KPI slop
- three identical stat columns (99% satisfaction, $10 saved, ∞ scale) unless user asked for KPIs
- fake dashboards with pointless charts shading the real layout
---
## 9. TYPOGRAPHY-FIRST DISCIPLINE
Typography is not filler.
Typography is a primary design material.
Always ensure:
- clear size contrast
- obvious reading order
- strong display moments
- supporting text that is readable and brief
- labels, captions, and section headings that reinforce structure
For editorial directions:
- let typography shape composition
For tech/product directions:
- let typography communicate trust and precision
---
## 10. SECTION RHYTHM RULE
A high-end site does not feel like repeated boxes.
Vary section rhythm across the page by changing:
- density
- image-to-text ratio
- alignment
- scale
- whitespace
- card grouping
- background intensity
- visual tempo
Do not let every section feel generated from the same template.
Important:
- rhythm variation should not break overall cleanliness
- keep the page visually balanced from top to bottom
- section heights may vary, but the spacing between sections should feel controlled and fairly even
- avoid abrupt jumps between very small and very large sections without enough breathing room
- the full page should feel curated, smooth, and consistent
---
## 11. COMPONENT EXECUTION GUIDELINES
### Diagonal Staggered Square Masonry
Use square image or content blocks with strong staggered vertical rhythm.
Should feel curated and graphic, not messy.
### 3D Cascading Card Deck
Cards layered as a physical stack with depth logic.
Should feel premium and tactile, not gimmicky.
### Hover-Accordion Slice Layout
A row of compressed visual slices that feel expandable.
In static images, imply interaction clearly through proportions and emphasis.
### Pristine Gapless Bento Grid
Mathematically clean grid.
No accidental gaps.
Mix large visual blocks with smaller dense information panels.
### Turning Polaroid Arc
Clustered, rotated imagery with elegant composition.
Should feel styled and intentional, not scrapbook-random.
### Off-Grid Editorial Layout
Use asymmetry and tension with control.
Must remain readable and clearly structured.
### Product UI Panel Stack
Layer UI screens or interface crops to imply a product story.
Avoid generic fake dashboards.
### Vertical Rhythm Lines
Use fine lines and spacing systems to reinforce order and elegance.
Never let them become decorative clutter.
---
## 12. DENSITY & SPACING DISCIPLINE
Do not make everything too dense.
The page should breathe.
Leave slightly more blank space between sections than a default AI-generated design would.
Rules:
- use more even vertical spacing between major sections
- keep section-to-section spacing consistent unless there is a strong design reason not to
- avoid one section feeling very cramped while the next feels too empty
- prefer a clean, balanced cadence across the page
- allow negative space to create rhythm and emphasis
- separate denser sections with calmer sections
- avoid stacking too many cards, labels, and content blocks too tightly
- smaller sections should still receive enough surrounding space so the page feels polished and intentional
A premium page should feel:
- open
- composed
- balanced
- confident
- breathable
Not:
- cramped
- noisy
- uneven
- overfilled
- visually exhausted
Section rhythm should alternate with control:
- some sections can be more content-rich
- some sections can be smaller and calmer
- but the overall spacing cadence should still feel even, clean, and deliberate
Whitespace is a design tool.
Use it deliberately.
Do not let spacing become random.
---
## 13. COLOR & MATERIAL RULES
### Palette Discipline
Use one controlled palette across the entire site:
- 1 primary (brand anchor)
- 1 secondary (supporting tone)
- 1 accent (used sparingly for CTA / highlight)
- a neutral scale (background, surface, text, hairline)
Section-level mood shifts must reuse the same palette — no full theme swap per section.
### Background-image harmony
When using full-bleed image backgrounds:
- the image must tonally match the palette (not fight it)
- use overlays (dark, light, or color tint) to keep text fully readable
- the brand accent stays consistent regardless of background image
### Gradient Discipline
Gradients are **allowed and encouraged** when professional and subtle. They are not the same as AI slop gradients.
Allowed (use confidently):
- low-chroma palette-matched tonal gradients (e.g. ink to graphite, cream to sand, ivory to warm grey)
- single-hue atmospheric grades behind hero photography
- soft vignettes and radial depth that direct the eye
- noise-textured gradients adding tactile depth without color noise
- editorial color washes that match brand mood
Banned (AI gradient slop):
- rainbow / mesh blob gradients
- purple-to-blue "AI" defaults
- pink-to-orange "creator" defaults
- neon edges and glow halos with no purpose
- gradient text as a shortcut for "premium"
- gradients that compete with imagery instead of supporting it
### Background Confidence Rule
Do not retreat to plain white surfaces by default. When the brief, brand mood, or section job calls for atmosphere, use:
- a full-bleed image,
- a duotone or graded photo,
- a tonal gradient,
- a tactile material,
or a confident flat color field — picked deliberately, not as decoration.
### Strong guidance
- avoid rainbow randomness
- avoid over-neon unless requested
- keep contrast intentional
- match accent colors to the chosen theme paradigm
- gradients must always read as professional and intentional, never as visual noise
### Materiality
Where appropriate, add:
- paper feel
- glass feel
- brushed metal feel
- soft blur depth
- tactile matte surfaces
- editorial photo treatment
But always keep the frontend structure readable.
---
## 14. IMAGE / MEDIA DIRECTION
If imagery is present, it must support the layout.
Allowed:
- art-directed product visuals
- refined editorial photography
- UI crops
- abstract forms with structural purpose
- framed objects
- premium texture use
- campaign-style visuals
Avoid:
- irrelevant scenery
- stock-photo cliches
- decorative junk
- visuals that overpower the page hierarchy
---
## 15. DEFAULT SITE PACKS
### 4-section pack
1. Hero
2. Features
3. Social proof / testimonial
4. CTA
### 8-section pack
1. Hero
2. Trust bar
3. Features
4. Product showcase
5. Benefits / use cases
6. Testimonials
7. Pricing
8. CTA
### 12-section pack
1. Hero
2. Trust bar
3. Feature grid
4. Product preview
5. Problem / solution
6. Benefits
7. Workflow
8. Metrics / proof / integration
9. Testimonials
10. Pricing
11. FAQ
12. CTA + footer
---
## 16. MULTI-IMAGE CONSISTENCY RULE
Because every section is its own image, consistency is critical. Across all per-section frames enforce:
- same brand world
- same type scale logic
- same spacing discipline
- same CTA family (style variations are fine, identity is not)
- same icon or illustration mood
- same image treatment (grade, framing, material vocabulary)
- same tonal language in any copy
Variation IS allowed in:
- composition anchor (per section)
- background mode (per section)
- section size and density
- which "second-read" moment appears
A viewer flipping through every per-section frame must still recognize one brand. Anything that breaks brand recall is over-variation.
---
## 17. CLARITY CHECK
Before finalizing, verify internally:
1. Is the hierarchy obvious?
2. Is the hero clean enough?
3. Is the design visually distinctive?
4. Is it free of obvious AI tells?
5. Is it premium rather than template-like?
6. Can someone code from this?
7. If multiple images exist, do they clearly belong together?
8. Is imagery used strongly enough (with variation, not one repeated crop)?
9. Does the page breathe, or is it too dense?
10. Is there enough spacing between sections?
11. Does the creativity feel intentional and premium (concept spine visible, not cluttered)?
12. Is the spacing between sections even and controlled?
13. Do smaller sections still have enough surrounding space to feel clean?
14. Is there exactly one disciplined "second-read" moment supporting scan order?
15. Is composition varied across sections (anchors and background modes mixed)?
16. Is the hero scale (giant / mid / mini) chosen and executed cleanly?
17. Is there a clear conversion path (hook -> proof -> action) even in artistic sites?
18. Is the palette consistent across all per-section images?
19. Is each image horizontal and one-section-only?
20. Is the **total number of images equal to the number of sections** (never fewer)?
21. Is the hero using a varied composition (not defaulting to left-text / right-image out of habit)?
If not, refine internally before output. If the count is wrong, regenerate the missing sections. If the hero feels like a reflexive left-text / right-image default, prefer a different composition anchor.
---
## 18. EXTRA CREATIVITY & IMPLEMENTATION EDGE
Apply unless the user opts out:
### Cross-section contrast
Across the slice, deliberately vary foreground/background intensity at least twice (lighter → richer → calmer) so the scroll feels paced, not monotonous slabs.
### CTA specificity
Prefer one unmistakable primary action per major viewport tier; secondary actions must look secondary (scale, outline, ghost), not clones of primary.
### Image variety inside one comp
Mix at least **two distinct image crops** where multiple sections exist — e.g. macro product + contextual environment, or portrait editorial + widescreen artifact — avoiding one repeated stock silhouette.
### Data-viz restraint
Charts, sparklines, and graphs appear only when the site type logically needs them (analytics, pricing, infra, observability brands). Else keep proof human (quotes, receipts, timelines, screenshots of real workflows).
### Cultural / tonal alignment
When the brief names an industry or region, steer palette and typographic temperament to match — dont ship default “neutral SF startup” unless the brief is intentionally generic SaaS.
### Mobile-implied fidelity (even for desktop mocks)
Maintain tap-friendly hit sizes and readable caption sizes visually; stacking order should imply a sane single-column narrative.
### Conversion focus
Each section has a job. Even when the design is artistic, the page must read as a real product or brand site:
- the hero communicates value in seconds and offers one obvious next action
- proof sections (logos, quotes, metrics) feel earned, not stuffed
- pricing or CTA sections feel decisive, not buried
- the final section closes: a single strong CTA + supporting trust cue
Avoid pure mood reels with no funnel logic.
### Composition variety check
Across all per-section images, internally log the chosen composition anchor and background mode. Reject the set if:
- the same composition anchor repeats more than 2 sections in a row
- the same background mode repeats more than 3 sections in a row
- every section is inline-asset (no full-bleed background ever appears) **AND** the brief does not call for minimalism / typography-only / swiss / ultra simple
For non-minimalist briefs: push for at least one full-bleed (or duotone / atmospheric) background and at least one mini minimalist section in any multi-section site.
For minimalist briefs: this rule is suspended. Restraint is the design.
---
## 19. RESPONSE BEHAVIOR
When the user asks for a frontend design:
1. infer site type and primary conversion goal
2. infer number of sections (if unclear, use the defaults from §5: landing page = 6, full website = 8)
3. **commit out loud** to the section count and announce it ("Generating N horizontal images, one per section")
4. plan ONE horizontal image PER SECTION — always separate generations, never collapse
5. choose Hero Scale for the whole site (giant / mid / mini)
5. choose a strong visual combination (theme, type, hero arch, section system, motion, narrative spine, second-read moment)
7. for each section: pick a Composition Anchor, Background Mode, and CTA Variation — vary across sections
8. choose 4 signature components used appropriately across sections
9. enforce hero minimalism + section size variety (some giant, some mini)
10. enforce strong image usage including full-bleed backgrounds where it fits
11. lock one consistent palette across all images
12. apply §18 EXTRA CREATIVITY & IMPLEMENTATION EDGE
13. keep spacing generous, even, and clean
14. remove AI slop (including marquee / fake KPI clichés unless requested)
15. run §17 CLARITY CHECK
16. **generate every per-section horizontal image, labeled "Section X of N: <name>"**, until the full set is delivered. Do not stop early. Do not summarize. Do not return only one image.
Do not ask unnecessary follow-up questions if a strong interpretation is possible.
---
## 20. EXAMPLE INTERPRETATIONS
### Example 1
User: "make a hero section for an AI startup"
Interpretation:
- 1 horizontal image
- Hero Scale: Mid Editorial or Giant Statement
- Composition Anchor: bottom-left text over full-bleed product/atmosphere image
- Background Mode: full-bleed image with dark tonal overlay
- CTA Variation: outlined inline + small label hint
- Palette: Deep Dark or Bold Studio Solid, one consistent accent
- no cliche dashboard spam, no purple AI glow
### Example 2
User: "design 8 sections for a fintech website"
Interpretation:
- 8 separate horizontal images (one per section)
- Hero Scale: Mid Editorial (trust-driven)
- vary Composition Anchor across sections (centered low, right-third caption, bottom-left over chart visual, stacked center for closing CTA)
- Background Mode mix: solid surface, full-bleed image background once, editorial side-image at use cases
- one consistent palette (e.g. ink + paper + single brand accent)
- conversion path: hook -> proof bar -> features -> use case -> testimonial -> pricing -> FAQ -> final CTA
### Example 3
User: "creative agency landing page, 12 sections"
Interpretation:
- 12 horizontal images (one per section)
- Hero Scale: Giant Statement OR Mini Minimalist (decisive choice, not in-between)
- editorial / poster-like direction; off-grid composition appears 2-3 times
- multiple Background Modes (full-bleed image at hero + showcase, editorial side-image at case studies, solid + accent for process)
- palette consistent throughout, with one bold accent recurring
- closing CTA section: mini minimalist, strong type, single primary action
---
## 21. FINAL GOAL
Generate frontend reference images that feel:
- artistic
- premium
- clear
- structured
- image-led
- breathable
- memorable
- anti-generic
- implementation-friendly
The result should look like a top-tier website concept with strong imagery, confident creativity, and generous spacing - not a dense, repetitive AI layout.
@@ -0,0 +1,92 @@
---
name: industrial-brutalist-ui
description: Raw mechanical interfaces fusing Swiss typographic print with military terminal aesthetics. Rigid grids, extreme type scale contrast, utilitarian color, analog degradation effects. For data-heavy dashboards, portfolios, or editorial sites that need to feel like declassified blueprints.
---
# SKILL: Industrial Brutalism & Tactical Telemetry UI
## 1. Skill Meta
**Name:** Industrial Brutalism & Tactical Telemetry Interface Engineering
**Description:** Advanced proficiency in architecting web interfaces that synthesize mid-century Swiss Typographic design, industrial manufacturing manuals, and retro-futuristic aerospace/military terminal interfaces. This discipline requires absolute mastery over rigid modular grids, extreme typographic scale contrast, purely utilitarian color palettes, and the programmatic simulation of analog degradation (halftones, CRT scanlines, bitmap dithering). The objective is to construct digital environments that project raw functionality, mechanical precision, and high data density, deliberately discarding conventional consumer UI patterns.
## 2. Visual Archetypes
The design system operates by merging two distinct but highly compatible visual paradigms. **Pick ONE per project and commit to it. Do not alternate or mix both modes within the same interface.**
### 2.1 Swiss Industrial Print
Derived from 1960s corporate identity systems and heavy machinery blueprints.
* **Characteristics:** High-contrast light modes (newsprint/off-white substrates). Reliance on monolithic, heavy sans-serif typography. Unforgiving structural grids outlined by visible dividing lines. Aggressive, asymmetric use of negative space punctuated by oversized, viewport-bleeding numerals or letterforms. Heavy use of primary red as an alert/accent color.
### 2.2 Tactical Telemetry & CRT Terminal
Derived from classified military databases, legacy mainframes, and aerospace Heads-Up Displays (HUDs).
* **Characteristics:** Dark mode exclusivity. High-density tabular data presentation. Absolute dominance of monospaced typography. Integration of technical framing devices (ASCII brackets, crosshairs). Application of simulated hardware limitations (phosphor glow, scanlines, low bit-depth rendering).
## 3. Typographic Architecture
Typography is the primary structural and decorative infrastructure. Imagery is secondary. The system demands extreme variance in scale, weight, and spacing.
### 3.1 Macro-Typography (Structural Headers)
* **Classification:** Neo-Grotesque / Heavy Sans-Serif.
* **Optimal Web Fonts:** Neue Haas Grotesk (Black), Inter (Extra Bold/Black), Archivo Black, Roboto Flex (Heavy), Monument Extended.
* **Implementation Parameters:**
* **Scale:** Deployed at massive scales using fluid typography (e.g., `clamp(4rem, 10vw, 15rem)`).
* **Tracking (Letter-spacing):** Extremely tight, often negative (`-0.03em` to `-0.06em`), forcing glyphs to form solid architectural blocks.
* **Leading (Line-height):** Highly compressed (`0.85` to `0.95`).
* **Casing:** Exclusively uppercase for structural impact.
### 3.2 Micro-Typography (Data & Telemetry)
* **Classification:** Monospace / Technical Sans.
* **Optimal Web Fonts:** JetBrains Mono, IBM Plex Mono, Space Mono, VT323, Courier Prime.
* **Implementation Parameters:**
* **Scale:** Fixed and small (`10px` to `14px` / `0.7rem` to `0.875rem`).
* **Tracking:** Generous (`0.05em` to `0.1em`) to simulate mechanical typewriter spacing or terminal matrices.
* **Leading:** Standard to tight (`1.2` to `1.4`).
* **Casing:** Exclusively uppercase. Used for all metadata, navigation, unit IDs, and coordinates.
### 3.3 Textural Contrast (Artistic Disruption)
* **Classification:** High-Contrast Serif.
* **Optimal Web Fonts:** Playfair Display, EB Garamond, Times New Roman.
* **Implementation Parameters:** Used exceedingly sparingly. Must be subjected to heavy post-processing (halftone filters, 1-bit dithering) to degrade vector perfection and create textural juxtaposition against the clean sans-serifs.
## 4. Color System
The color architecture is uncompromising. Gradients, soft drop shadows, and modern translucency are strictly prohibited. Colors simulate physical media or primitive emissive displays.
**CRITICAL: Choose ONE substrate palette per project and use it consistently. Never mix light and dark substrates within the same interface.**
### If Swiss Industrial Print (Light):
* **Background:** `#F4F4F0` or `#EAE8E3` (Matte, unbleached documentation paper).
* **Foreground:** `#050505` to `#111111` (Carbon Ink).
* **Accent:** `#E61919` or `#FF2A2A` (Aviation/Hazard Red). This is the ONLY accent color. Used for strike-throughs, thick structural dividing lines, or vital data highlights.
### If Tactical Telemetry (Dark):
* **Background:** `#0A0A0A` or `#121212` (Deactivated CRT. Avoid pure `#000000`).
* **Foreground:** `#EAEAEA` (White phosphor). This is the primary text color.
* **Accent:** `#E61919` or `#FF2A2A` (Aviation/Hazard Red). Same red, same rules.
* **Terminal Green (`#4AF626`):** Optional. Use ONLY for a single specific UI element (e.g., one status indicator or one data readout) — never as a general text color. If it doesn't serve a clear purpose, omit it entirely.
## 5. Layout and Spatial Engineering
The layout must appear mathematically engineered. It rejects conventional web padding in favor of visible compartmentalization.
* **The Blueprint Grid:** Strict adherence to CSS Grid architectures. Elements do not float; they are anchored precisely to grid tracks and intersections.
* **Visible Compartmentalization:** Extensive utilization of solid borders (`1px` or `2px solid`) to delineate distinct zones of information. Horizontal rules (`<hr>`) frequently span the entire container width to segregate operational units.
* **Bimodal Density:** Layouts oscillate between extreme data density (tightly packed monospace metadata clustered together) and vast expanses of calculated negative space framing macro-typography.
* **Geometry:** Absolute rejection of `border-radius`. All corners must be exactly 90 degrees to enforce mechanical rigidity.
## 6. UI Components and Symbology
Standard web UI conventions are replaced with utilitarian, industrial graphic elements.
* **Syntax Decoration:** Utilization of ASCII characters to frame data points.
* *Framing:* `[ DELIVERY SYSTEMS ]`, `< RE-IND >`
* *Directional:* `>>>`, `///`, `\\\\`
* **Industrial Markers:** Prominent integration of registration (`®`), copyright (`©`), and trademark (`™`) symbols functioning as structural geometric elements rather than legal text.
* **Technical Assets:** Integration of crosshairs (`+`) at grid intersections, repeating vertical lines (barcodes), thick horizontal warning stripes, and randomized string data (e.g., `REV 2.6`, `UNIT / D-01`) to simulate active mechanical processes.
## 7. Textural and Post-Processing Effects
To prevent the design from appearing purely digital, simulated analog degradation is engineered into the frontend via CSS and SVG filters.
* **Halftone and 1-Bit Dithering:** Transforming continuous-tone images or large serif typography into dot-matrix patterns. Achieved via pre-processing or CSS `mix-blend-mode: multiply` overlays combined with SVG radial dot patterns.
* **CRT Scanlines:** For terminal interfaces, applying a `repeating-linear-gradient` to the background to simulate horizontal electron beam sweeps (e.g., `repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(0,0,0,0.1) 2px, rgba(0,0,0,0.1) 4px)`).
* **Mechanical Noise:** A global, low-opacity SVG static/noise filter applied to the DOM root to introduce a unified physical grain across both dark and light modes.
## 8. Web Engineering Directives
1. **Grid Determinism:** Utilize `display: grid; gap: 1px;` with contrasting parent/child background colors to generate mathematically perfect, razor-thin dividing lines without complex border declarations.
2. **Semantic Rigidity:** Construct the DOM using precise semantic tags (`<data>`, `<samp>`, `<kbd>`, `<output>`, `<dl>`) to accurately reflect the technical nature of the telemetry.
3. **Typography Clamping:** Implement CSS `clamp()` functions exclusively for macro-typography to ensure massive text scales aggressively while maintaining structural integrity across viewports.
+85
View File
@@ -0,0 +1,85 @@
---
name: minimalist-ui
description: Clean editorial-style interfaces. Warm monochrome palette, typographic contrast, flat bento grids, muted pastels. No gradients, no heavy shadows.
---
# Protocol: Premium Utilitarian Minimalism UI Architect
## 1. Protocol Overview
Name: Premium Utilitarian Minimalism & Editorial UI
Description: An advanced frontend engineering directive for generating highly refined, ultra-minimalist, "document-style" web interfaces analogous to top-tier workspace platforms. This protocol strictly enforces a high-contrast warm monochrome palette, bespoke typographic hierarchies, meticulous structural macro-whitespace, bento-grid layouts, and an ultra-flat component architecture with deliberate muted pastel accents. It actively rejects standard generic SaaS design trends.
## 2. Absolute Negative Constraints (Banned Elements)
The AI must strictly avoid the following generic web development defaults:
- DO NOT use the "Inter", "Roboto", or "Open Sans" typefaces.
- DO NOT use generic, thin-line icon libraries like "Lucide", "Feather", or standard "Heroicons".
- DO NOT use Tailwind's default heavy drop shadows (e.g., `shadow-md`, `shadow-lg`, `shadow-xl`). Shadows must be practically non-existent or heavily customized to be ultra-diffuse and low opacity (< 0.05).
- DO NOT use primary colored backgrounds for large elements or sections (e.g., no bright blue, green, or red hero sections).
- DO NOT use gradients, neon colors, or 3D glassmorphism (beyond subtle navbar blurs).
- DO NOT use `rounded-full` (pill shapes) for large containers, cards, or primary buttons.
- DO NOT use emojis anywhere in code, markup, text content, headings, or alt text. Replace with proper icons or clean SVG primitives.
- DO NOT use generic placeholder names like "John Doe", "Acme Corp", or "Lorem Ipsum". Use realistic, contextual content.
- DO NOT use AI copywriting clichés: "Elevate", "Seamless", "Unleash", "Next-Gen", "Game-changer", "Delve". Write plain, specific language.
## 3. Typographic Architecture
The interface must rely on extreme typographic contrast and premium font selection to establish an editorial feel.
- Primary Sans-Serif (Body, UI, Buttons): Use clean, geometric, or system-native fonts with character. Target: `font-family: 'SF Pro Display', 'Geist Sans', 'Helvetica Neue', 'Switzer', sans-serif`.
- Editorial Serif (Hero Headings & Quotes): Target: `font-family: 'Lyon Text', 'Newsreader', 'Playfair Display', 'Instrument Serif', serif`. Apply tight tracking (`letter-spacing: -0.02em` to `-0.04em`) and tight line-height (`1.1`).
- Monospace (Code, Keystrokes, Meta-data): Target: `font-family: 'Geist Mono', 'SF Mono', 'JetBrains Mono', monospace`.
- Text Colors: Body text must never be absolute black (`#000000`). Use off-black/charcoal (`#111111` or `#2F3437`) with a generous `line-height` of `1.6` for legibility. Secondary text should be muted gray (`#787774`).
## 4. Color Palette (Warm Monochrome + Spot Pastels)
Color is a scarce resource, utilized only for semantic meaning or subtle accents.
- Canvas / Background: Pure White `#FFFFFF` or Warm Bone/Off-White `#F7F6F3` / `#FBFBFA`.
- Primary Surface (Cards): `#FFFFFF` or `#F9F9F8`.
- Structural Borders / Dividers: Ultra-light gray `#EAEAEA` or `rgba(0,0,0,0.06)`.
- Accent Colors: Exclusively use highly desaturated, washed-out pastels for tags, inline code backgrounds, or subtle icon backgrounds.
- Pale Red: `#FDEBEC` (Text: `#9F2F2D`)
- Pale Blue: `#E1F3FE` (Text: `#1F6C9F`)
- Pale Green: `#EDF3EC` (Text: `#346538`)
- Pale Yellow: `#FBF3DB` (Text: `#956400`)
## 5. Component Specifications
- Bento Box Feature Grids:
- Utilize asymmetrical CSS Grid layouts.
- Cards must have exactly `border: 1px solid #EAEAEA`.
- Border-radius must be crisp: `8px` or `12px` maximum.
- Internal padding must be generous (e.g., `24px` to `40px`).
- Primary Call-To-Action (Buttons):
- Solid background `#111111`, text `#FFFFFF`.
- Slight border-radius (`4px` to `6px`). No box-shadow.
- Hover state should be a subtle color shift to `#333333` or a micro-scale `transform: scale(0.98)`.
- Tags & Status Badges:
- Pill-shaped (`border-radius: 9999px`), very small typography (`text-xs`), uppercase with wide tracking (`letter-spacing: 0.05em`).
- Background must use the defined Muted Pastels.
- Accordions (FAQ):
- Strip all container boxes. Separate items only with a `border-bottom: 1px solid #EAEAEA`.
- Use a clean, sharp `+` and `-` icon for the toggle state.
- Keystroke Micro-UIs:
- Render shortcuts as physical keys using `<kbd>` tags: `border: 1px solid #EAEAEA`, `border-radius: 4px`, `background: #F7F6F3`, using the Monospace font.
- Faux-OS Window Chrome:
- When mocking up software, wrap it in a minimalist container with a white top bar containing three small, light gray circles (replicating macOS window controls).
## 6. Iconography & Imagery Directives
- System Icons: Use "Phosphor Icons (Bold or Fill weights)" or "Radix UI Icons" for a technical, slightly thicker-stroke aesthetic. Standardize stroke width across all icons.
- Illustrations: Monochromatic, rough continuous-line ink sketches on a white background, featuring a single offset geometric shape filled with a muted pastel color.
- Photography: Use high-quality, desaturated images with a warm tone. Apply subtle overlays (`opacity: 0.04` warm grain) to blend photos into the monochrome palette. Never use oversaturated stock photos. Use reliable placeholders like `https://picsum.photos/seed/{context}/1200/800` when real assets are unavailable.
- Hero & Section Backgrounds: Sections should not feel empty and flat. Use subtle full-width background imagery at very low opacity, soft radial light spots (`radial-gradient` with warm tones at `opacity: 0.03`), or minimal geometric line patterns to add depth without breaking the clean aesthetic.
## 7. Subtle Motion & Micro-Animations
Motion should feel invisible — present but never distracting. The goal is quiet sophistication, not spectacle.
- Scroll Entry: Elements fade in gently as they enter the viewport. Use `translateY(12px)` + `opacity: 0` resolving over `600ms` with `cubic-bezier(0.16, 1, 0.3, 1)`. Use `IntersectionObserver`, never `window.addEventListener('scroll')`.
- Hover States: Cards lift with an ultra-subtle shadow shift (`box-shadow` transitioning from `0 0 0` to `0 2px 8px rgba(0,0,0,0.04)` over `200ms`). Buttons respond with `scale(0.98)` on `:active`.
- Staggered Reveals: Lists and grid items enter with a cascade delay (`animation-delay: calc(var(--index) * 80ms)`). Never mount everything at once.
- Background Ambient Motion: Optional. A single, very slow-moving radial gradient blob (`animation-duration: 20s+`, `opacity: 0.02-0.04`) drifting behind hero sections. Must be applied to a `position: fixed; pointer-events: none` layer. Never on scrolling containers.
- Performance: Animate exclusively via `transform` and `opacity`. No layout-triggering properties (`top`, `left`, `width`, `height`). Use `will-change: transform` sparingly and only on actively animating elements.
## 8. Execution Protocol
When tasked with writing frontend code (HTML, React, Tailwind, Vue) or designing a layout:
1. Establish the macro-whitespace first. Use massive vertical padding between sections (e.g., `py-24` or `py-32` in Tailwind).
2. Constrain the main typography content width to `max-w-4xl` or `max-w-5xl`.
3. Apply the custom typographic hierarchy and monochromatic color variables immediately.
4. Ensure every card, divider, and border adheres strictly to the `1px solid #EAEAEA` rule.
5. Add scroll-entry animations to all major content blocks.
6. Ensure sections have visual depth through imagery, ambient gradients, or subtle textures — no empty flat backgrounds.
7. Provide code that reflects this high-end, uncluttered, editorial aesthetic natively without requiring manual adjustments.
@@ -0,0 +1,178 @@
---
name: redesign-existing-projects
description: Upgrades existing websites and apps to premium quality. Audits current design, identifies generic AI patterns, and applies high-end design standards without breaking functionality. Works with any CSS framework or vanilla CSS.
---
# Redesign Skill
## How This Works
When applied to an existing project, follow this sequence:
1. **Scan** — Read the codebase. Identify the framework, styling method (Tailwind, vanilla CSS, styled-components, etc.), and current design patterns.
2. **Diagnose** — Run through the audit below. List every generic pattern, weak point, and missing state you find.
3. **Fix** — Apply targeted upgrades working with the existing stack. Do not rewrite from scratch. Improve what's there.
## Design Audit
### Typography
Check for these problems and fix them:
- **Browser default fonts or Inter everywhere.** Replace with a font that has character. Good options: `Geist`, `Outfit`, `Cabinet Grotesk`, `Satoshi`. For editorial/creative projects, pair a serif header with a sans-serif body.
- **Headlines lack presence.** Increase size for display text, tighten letter-spacing, reduce line-height. Headlines should feel heavy and intentional.
- **Body text too wide.** Limit paragraph width to roughly 65 characters. Increase line-height for readability.
- **Only Regular (400) and Bold (700) weights used.** Introduce Medium (500) and SemiBold (600) for more subtle hierarchy.
- **Numbers in proportional font.** Use a monospace font or enable tabular figures (`font-variant-numeric: tabular-nums`) for data-heavy interfaces.
- **Missing letter-spacing adjustments.** Use negative tracking for large headers, positive tracking for small caps or labels.
- **All-caps subheaders everywhere.** Try lowercase italics, sentence case, or small-caps instead.
- **Orphaned words.** Single words sitting alone on the last line. Fix with `text-wrap: balance` or `text-wrap: pretty`.
### Color and Surfaces
- **Pure `#000000` background.** Replace with off-black, dark charcoal, or tinted dark (`#0a0a0a`, `#121212`, or a dark navy).
- **Oversaturated accent colors.** Keep saturation below 80%. Desaturate accents so they blend with neutrals instead of screaming.
- **More than one accent color.** Pick one. Remove the rest. Consistency beats variety.
- **Mixing warm and cool grays.** Stick to one gray family. Tint all grays with a consistent hue (warm or cool, not both).
- **Purple/blue "AI gradient" aesthetic.** This is the most common AI design fingerprint. Replace with neutral bases and a single, considered accent.
- **Generic `box-shadow`.** Tint shadows to match the background hue. Use colored shadows (e.g., dark blue shadow on a blue background) instead of pure black at low opacity.
- **Flat design with zero texture.** Add subtle noise, grain, or micro-patterns to backgrounds. Pure flat vectors feel sterile.
- **Perfectly even gradients.** Break the uniformity with radial gradients, noise overlays, or mesh gradients instead of standard linear 45-degree fades.
- **Inconsistent lighting direction.** Audit all shadows to ensure they suggest a single, consistent light source.
- **Random dark sections in a light mode page (or vice versa).** A single dark-background section breaking an otherwise light page looks like a copy-paste accident. Either commit to a full dark mode or keep a consistent background tone throughout. If contrast is needed, use a slightly darker shade of the same palette — not a sudden jump to `#111` in the middle of a cream page.
- **Empty, flat sections with no visual depth.** Sections that are just text on a plain background feel unfinished. Add high-quality background imagery (blurred, overlaid, or masked), subtle patterns, or ambient gradients. Use reliable placeholder sources like `https://picsum.photos/seed/{name}/1920/1080` when real assets are not available. Experiment with background images behind hero sections, feature blocks, or CTAs — even a subtle full-width photo at low opacity adds presence.
### Layout
- **Everything centered and symmetrical.** Break symmetry with offset margins, mixed aspect ratios, or left-aligned headers over centered content.
- **Three equal card columns as feature row.** This is the most generic AI layout. Replace with a 2-column zig-zag, asymmetric grid, horizontal scroll, or masonry layout.
- **Using `height: 100vh` for full-screen sections.** Replace with `min-height: 100dvh` to prevent layout jumping on mobile browsers (iOS Safari viewport bug).
- **Complex flexbox percentage math.** Replace with CSS Grid for reliable multi-column structures.
- **No max-width container.** Add a container constraint (around 1200-1440px) with auto margins so content doesn't stretch edge-to-edge on wide screens.
- **Cards of equal height forced by flexbox.** Allow variable heights or use masonry when content varies in length.
- **Uniform border-radius on everything.** Vary the radius: tighter on inner elements, softer on containers.
- **No overlap or depth.** Elements sit flat next to each other. Use negative margins to create layering and visual depth.
- **Symmetrical vertical padding.** Top and bottom padding are always identical. Adjust optically — bottom padding often needs to be slightly larger.
- **Dashboard always has a left sidebar.** Try top navigation, a floating command menu, or a collapsible panel instead.
- **Missing whitespace.** Double the spacing. Let the design breathe. Dense layouts work for data dashboards, not for marketing pages.
- **Buttons not bottom-aligned in card groups.** When cards have different content lengths, CTAs end up at random heights. Pin buttons to the bottom of each card so they form a clean horizontal line regardless of content above.
- **Feature lists starting at different vertical positions.** In pricing tables or comparison cards, the list of features should start at the same Y position across all columns. Use consistent spacing above the list or fixed-height title/price blocks.
- **Inconsistent vertical rhythm in side-by-side elements.** When placing cards, columns, or panels next to each other, align shared elements (titles, descriptions, prices, buttons) across all items. Misaligned baselines make the layout look broken.
- **Mathematical alignment that looks optically wrong.** Centering by the math doesn't always look centered to the eye. Icons next to text, play buttons in circles, or text in buttons often need 1-2px optical adjustments to feel right.
### Interactivity and States
- **No hover states on buttons.** Add background shift, slight scale, or translate on hover.
- **No active/pressed feedback.** Add a subtle `scale(0.98)` or `translateY(1px)` on press to simulate a physical click.
- **Instant transitions with zero duration.** Add smooth transitions (200-300ms) to all interactive elements.
- **Missing focus ring.** Ensure visible focus indicators for keyboard navigation. This is an accessibility requirement, not optional.
- **No loading states.** Replace generic circular spinners with skeleton loaders that match the layout shape.
- **No empty states.** An empty dashboard showing nothing is a missed opportunity. Design a composed "getting started" view.
- **No error states.** Add clear, inline error messages for forms. Do not use `window.alert()`.
- **Dead links.** Buttons that link to `#`. Either link to real destinations or visually disable them.
- **No indication of current page in navigation.** Style the active nav link differently so users know where they are.
- **Scroll jumping.** Anchor clicks jump instantly. Add `scroll-behavior: smooth`.
- **Animations using `top`, `left`, `width`, `height`.** Switch to `transform` and `opacity` for GPU-accelerated, smooth animation.
### Content
- **Generic names like "John Doe" or "Jane Smith".** Use diverse, realistic-sounding names.
- **Fake round numbers like `99.99%`, `50%`, `$100.00`.** Use organic, messy data: `47.2%`, `$99.00`, `+1 (312) 847-1928`.
- **Placeholder company names like "Acme Corp", "Nexus", "SmartFlow".** Invent contextual, believable brand names.
- **AI copywriting cliches.** Never use "Elevate", "Seamless", "Unleash", "Next-Gen", "Game-changer", "Delve", "Tapestry", or "In the world of...". Write plain, specific language.
- **Exclamation marks in success messages.** Remove them. Be confident, not loud.
- **"Oops!" error messages.** Be direct: "Connection failed. Please try again."
- **Passive voice.** Use active voice: "We couldn't save your changes" instead of "Mistakes were made."
- **All blog post dates identical.** Randomize dates to appear real.
- **Same avatar image for multiple users.** Use unique assets for every distinct person.
- **Lorem Ipsum.** Never use placeholder latin text. Write real draft copy.
- **Title Case On Every Header.** Use sentence case instead.
### Component Patterns
- **Generic card look (border + shadow + white background).** Remove the border, or use only background color, or use only spacing. Cards should exist only when elevation communicates hierarchy.
- **Always one filled button + one ghost button.** Add text links or tertiary styles to reduce visual noise.
- **Pill-shaped "New" and "Beta" badges.** Try square badges, flags, or plain text labels.
- **Accordion FAQ sections.** Use a side-by-side list, searchable help, or inline progressive disclosure.
- **3-card carousel testimonials with dots.** Replace with a masonry wall, embedded social posts, or a single rotating quote.
- **Pricing table with 3 towers.** Highlight the recommended tier with color and emphasis, not just extra height.
- **Modals for everything.** Use inline editing, slide-over panels, or expandable sections instead of popups for simple actions.
- **Avatar circles exclusively.** Try squircles or rounded squares for a less generic look.
- **Light/dark toggle always a sun/moon switch.** Use a dropdown, system preference detection, or integrate it into settings.
- **Footer link farm with 4 columns.** Simplify. Focus on main navigational paths and legally required links.
### Iconography
- **Lucide or Feather icons exclusively.** These are the "default" AI icon choice. Use Phosphor, Heroicons, or a custom set for differentiation.
- **Rocketship for "Launch", shield for "Security".** Replace cliche metaphors with less obvious icons (bolt, fingerprint, spark, vault).
- **Inconsistent stroke widths across icons.** Audit all icons and standardize to one stroke weight.
- **Missing favicon.** Always include a branded favicon.
- **Stock "diverse team" photos.** Use real team photos, candid shots, or a consistent illustration style instead of uncanny stock imagery.
### Code Quality
- **Div soup.** Use semantic HTML: `<nav>`, `<main>`, `<article>`, `<aside>`, `<section>`.
- **Inline styles mixed with CSS classes.** Move all styling to the project's styling system.
- **Hardcoded pixel widths.** Use relative units (`%`, `rem`, `em`, `max-width`) for flexible layouts.
- **Missing alt text on images.** Describe image content for screen readers. Never leave `alt=""` or `alt="image"` on meaningful images.
- **Arbitrary z-index values like `9999`.** Establish a clean z-index scale in the theme/variables.
- **Commented-out dead code.** Remove all debug artifacts before shipping.
- **Import hallucinations.** Check that every import actually exists in `package.json` or the project dependencies.
- **Missing meta tags.** Add proper `<title>`, `description`, `og:image`, and social sharing meta tags.
### Strategic Omissions (What AI Typically Forgets)
- **No legal links.** Add privacy policy and terms of service links in the footer.
- **No "back" navigation.** Dead ends in user flows. Every page needs a way back.
- **No custom 404 page.** Design a helpful, branded "page not found" experience.
- **No form validation.** Add client-side validation for emails, required fields, and format checks.
- **No "skip to content" link.** Essential for keyboard users. Add a hidden skip-link.
- **No cookie consent.** If required by jurisdiction, add a compliant consent banner.
## Upgrade Techniques
When upgrading a project, pull from these high-impact techniques to replace generic patterns:
### Typography Upgrades
- **Variable font animation.** Interpolate weight or width on scroll or hover for text that feels alive.
- **Outlined-to-fill transitions.** Text starts as a stroke outline and fills with color on scroll entry or interaction.
- **Text mask reveals.** Large typography acting as a window to video or animated imagery behind it.
### Layout Upgrades
- **Broken grid / asymmetry.** Elements that deliberately ignore column structure — overlapping, bleeding off-screen, or offset with calculated randomness.
- **Whitespace maximization.** Aggressive use of negative space to force focus on a single element.
- **Parallax card stacks.** Sections that stick and physically stack over each other during scroll.
- **Split-screen scroll.** Two halves of the screen sliding in opposite directions.
### Motion Upgrades
- **Smooth scroll with inertia.** Decouple scrolling from browser defaults for a heavier, cinematic feel.
- **Staggered entry.** Elements cascade in with slight delays, combining Y-axis translation with opacity fade. Never mount everything at once.
- **Spring physics.** Replace linear easing with spring-based motion for a natural, weighty feel on all interactive elements.
- **Scroll-driven reveals.** Content entering through expanding masks, wipes, or draw-on SVG paths tied to scroll progress.
### Surface Upgrades
- **True glassmorphism.** Go beyond `backdrop-filter: blur`. Add a 1px inner border and a subtle inner shadow to simulate edge refraction.
- **Spotlight borders.** Card borders that illuminate dynamically under the cursor.
- **Grain and noise overlays.** A fixed, pointer-events-none overlay with subtle noise to break digital flatness.
- **Colored, tinted shadows.** Shadows that carry the hue of the background rather than using generic black.
## Fix Priority
Apply changes in this order for maximum visual impact with minimum risk:
1. **Font swap** — biggest instant improvement, lowest risk
2. **Color palette cleanup** — remove clashing or oversaturated colors
3. **Hover and active states** — makes the interface feel alive
4. **Layout and spacing** — proper grid, max-width, consistent padding
5. **Replace generic components** — swap cliche patterns for modern alternatives
6. **Add loading, empty, and error states** — makes it feel finished
7. **Polish typography scale and spacing** — the premium final touch
## Rules
- Work with the existing tech stack. Do not migrate frameworks or styling libraries.
- Do not break existing functionality. Test after every change.
- Before importing any new library, check the project's dependency file first.
- If the project uses Tailwind, check the version (v3 vs v4) before modifying config.
- If the project has no framework, use vanilla CSS.
- Keep changes reviewable and focused. Small, targeted improvements over big rewrites.
@@ -0,0 +1,121 @@
# Design System: Taste Standard
**Skill:** stitch-design-taste
---
## Configuration — Set Your Style
Adjust these dials before using this design system. They control how creative, dense, and animated the output should be. Pick the level that fits your project.
| Dial | Level | Description |
|------|-------|-------------|
| **Creativity** | `8` | `1` = Ultra-minimal, Swiss, silent, monochrome. `5` = Balanced, clean but with personality. `10` = Expressive, editorial, bold typography experiments, inline images in headlines, strong asymmetry. Default: `8` |
| **Density** | `4` | `1` = Gallery-airy, massive whitespace. `5` = Balanced sections. `10` = Cockpit-dense, data-heavy. Default: `4` |
| **Variance** | `8` | `1` = Predictable, symmetric grids. `5` = Subtle offsets. `10` = Artsy chaotic, no two sections alike. Default: `8` |
| **Motion Intent** | `6` | `1` = Static, no animation noted. `5` = Subtle hover/entrance cues. `10` = Cinematic orchestration noted in every component. Default: `6` |
> **How to use:** Change the numbers above to match your project's vibe. At **Creativity 13**, the system produces clean, quiet, Notion-like interfaces. At **Creativity 710**, expect inline image typography, dramatic scale contrast, and strong editorial layouts. The rest of the rules below adapt to your chosen levels.
---
## 1. Visual Theme & Atmosphere
A restrained, gallery-airy interface with confident asymmetric layouts and fluid spring-physics motion. The atmosphere is clinical yet warm — like a well-lit architecture studio where every element earns its place through function. Density is balanced (Level 4), variance runs high (Level 8) to prevent symmetrical boredom, and motion is fluid but never theatrical (Level 6). The overall impression: expensive, intentional, alive.
## 2. Color Palette & Roles
- **Canvas White** (#F9FAFB) — Primary background surface. Warm-neutral, never clinical blue-white
- **Pure Surface** (#FFFFFF) — Card and container fill. Used with whisper shadow for elevation
- **Charcoal Ink** (#18181B) — Primary text. Zinc-950 depth — never pure black
- **Steel Secondary** (#71717A) — Body text, descriptions, metadata. Zinc-500 warmth
- **Muted Slate** (#94A3B8) — Tertiary text, timestamps, disabled states
- **Whisper Border** (rgba(226,232,240,0.5)) — Card borders, structural 1px lines. Semi-transparent for depth
- **Diffused Shadow** (rgba(0,0,0,0.05)) — Card elevation. Wide-spreading, 40px blur, -15px offset. Never harsh
### Accent Selection (Pick ONE per project)
- **Emerald Signal** (#10B981) — For growth, success, positive data dashboards
- **Electric Blue** (#3B82F6) — For productivity, SaaS, developer tools
- **Deep Rose** (#E11D48) — For creative, editorial, fashion-adjacent projects
- **Amber Warmth** (#F59E0B) — For community, social, warm-toned products
### Banned Colors
- Purple/Violet neon gradients — the "AI Purple" aesthetic
- Pure Black (#000000) — always Off-Black or Zinc-950
- Oversaturated accents above 80% saturation
- Mixed warm/cool gray systems within one project
## 3. Typography Rules
- **Display:** `Geist`, `Satoshi`, `Cabinet Grotesk`, or `Outfit` — Track-tight (`-0.025em`), controlled fluid scale, weight-driven hierarchy (700900). Not screaming. Leading compressed (`1.1`). Alternatives forced — `Inter` is BANNED for premium contexts
- **Body:** Same family at weight 400 — Relaxed leading (`1.65`), 65ch max-width, Steel Secondary color (#71717A)
- **Mono:** `Geist Mono` or `JetBrains Mono` — For code blocks, metadata, timestamps. When density exceeds Level 7, all numbers switch to monospace
- **Scale:** Display at `clamp(2.25rem, 5vw, 3.75rem)`. Body at `1rem/1.125rem`. Mono metadata at `0.8125rem`
### Banned Fonts
- `Inter` — banned everywhere in premium/creative contexts
- Generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`, `Palatino`) — BANNED. If serif is needed for editorial/creative, use only distinctive modern serifs like `Fraunces`, `Gambarino`, `Editorial New`, or `Instrument Serif`. Never use default browser serif stacks. Serif is always BANNED in dashboards or software UIs regardless
## 4. Component Stylings
* **Buttons:** Flat surface, no outer glow. Primary: accent fill with white text. Secondary: ghost/outline. Active state: `-1px translateY` or `scale(0.98)` for tactile push. Hover: subtle background shift, never glow
* **Cards/Containers:** Generously rounded corners (`2.5rem`). Pure white fill. Whisper border (`1px`, semi-transparent). Diffused shadow (`0 20px 40px -15px rgba(0,0,0,0.05)`). Internal padding `2rem2.5rem`. Used ONLY when elevation communicates hierarchy — high-density layouts replace cards with `border-top` dividers or negative space
* **Inputs/Forms:** Label positioned above input. Helper text optional. Error text below in Deep Rose. Focus ring in accent color, `2px` offset. No floating labels. Standard `0.5rem` gap between label-input-error stack
* **Navigation:** Sleek, sticky. Icons scale on hover (Dock Magnification optional). No hamburger on desktop. Clean horizontal with generous spacing
* **Loaders:** Skeletal shimmer matching exact layout dimensions and rounded corners. Shifting light reflection across placeholder shapes. Never circular spinners
* **Empty States:** Composed illustration or icon composition with guidance text. Never just "No data found"
* **Error States:** Inline, contextual. Red accent underline or border. Clear recovery action
## 5. Hero Section
The Hero is the first impression — it must be striking, creative, and never generic.
- **Inline Image Typography:** Embed small, contextual photos or visuals directly between words or letters in the headline. Example: "We build [photo of hands typing] digital [photo of screen] products" — images sit inline at type-height, rounded, acting as visual punctuation between words. This is the signature creative technique
- **No Overlapping Elements:** Text must never overlap images or other text. Every element has its own clear spatial zone. No z-index stacking of content layers, no absolute-positioned headlines over images. Clean separation always
- **No Filler Text:** "Scroll to explore", "Swipe down", scroll arrow icons, bouncing chevrons, and any instructional UI chrome are BANNED. The user knows how to scroll. Let the content pull them in naturally
- **Asymmetric Structure:** Centered Hero layouts are BANNED at this variance level. Use Split Screen (50/50), Left-Aligned text / Right visual, or Asymmetric Whitespace with large empty zones
- **CTA Restraint:** Maximum one primary CTA button. No secondary "Learn more" links. No redundant micro-copy below the headline
## 6. Layout Principles
- **Grid-First:** CSS Grid for all structural layouts. Never flexbox percentage math (`calc(33% - 1rem)` is BANNED)
- **No Overlapping:** Elements must never overlap each other. No absolute-positioned layers stacking content on content. Every element occupies its own grid cell or flow position. Clean, separated spatial zones
- **Feature Sections:** The "3 equal cards in a row" pattern is BANNED. Use 2-column Zig-Zag, asymmetric Bento grids (2fr 1fr 1fr), or horizontal scroll galleries
- **Containment:** All content within `max-width: 1400px`, centered. Generous horizontal padding (`1rem` mobile, `2rem` tablet, `4rem` desktop)
- **Full-Height:** Use `min-height: 100dvh` — never `height: 100vh` (iOS Safari address bar jump)
- **Bento Architecture:** For feature grids, use Row 1: 3 columns | Row 2: 2 columns (70/30 split). Each tile contains a perpetual micro-animation
## 7. Responsive Rules
Every screen must work flawlessly across all viewports. **Responsive is not optional — it is a hard requirement. Every single element must be tested at 375px, 768px, and 1440px.**
- **Mobile-First Collapse (< 768px):** All multi-column layouts collapse to a strict single column. `width: 100%`, `padding: 1rem`, `gap: 1.5rem`. No exceptions
- **No Horizontal Scroll:** Horizontal overflow on mobile is a critical failure. All elements must fit within viewport width. If any element causes horizontal scroll, the design is broken
- **Typography Scaling:** Headlines scale down gracefully via `clamp()`. Body text stays `1rem` minimum. Never shrink body below `14px`. Headlines must remain readable on 375px screens
- **Touch Targets:** All interactive elements minimum `44px` tap target. Generous spacing between clickable items. Buttons must be full-width on mobile
- **Image Behavior:** Hero and inline images scale proportionally. Inline typography images (photos between words) stack below the headline on mobile instead of inline
- **Navigation:** Desktop horizontal nav collapses to a clean mobile menu (slide-in or full-screen overlay). No tiny hamburger icons without labels
- **Cards & Grids:** Bento grids and asymmetric layouts revert to stacked single-column cards with full-width. Maintain internal padding (`1rem`)
- **Spacing Consistency:** Vertical section gaps reduce proportionally on mobile (`clamp(3rem, 8vw, 6rem)`). Never cramped, never excessively airy
- **Testing Viewports:** Designs must be verified at: `375px` (iPhone SE), `390px` (iPhone 14), `768px` (iPad), `1024px` (small laptop), `1440px` (desktop)
## 8. Motion & Interaction (Code-Phase Intent)
> **Note:** Stitch generates static screens — it does not animate. This section documents the **intended motion behavior** so that the coding agent (Antigravity, Cursor, etc.) knows exactly how to implement animations when building the exported design into a live product.
- **Physics Engine:** Spring-based exclusively. `stiffness: 100, damping: 20`. No linear easing anywhere. Premium, weighty feel on all interactive elements
- **Perpetual Micro-Loops:** Every active dashboard component has an infinite-loop state — Pulse on status dots, Typewriter on search bars, Float on feature icons, Shimmer on loading states
- **Staggered Orchestration:** Lists and grids mount with cascaded delays (`animation-delay: calc(var(--index) * 100ms)`). Waterfall reveals, never instant mount
- **Layout Transitions:** Smooth re-ordering via shared element IDs. Items swap positions with physics, simulating real-time intelligence
- **Hardware Rules:** Animate ONLY `transform` and `opacity`. Never `top`, `left`, `width`, `height`. Grain/noise filters on fixed, pointer-events-none pseudo-elements only
- **Performance:** CPU-heavy perpetual animations isolated in microscopic leaf components. Never trigger parent re-renders. Target 60fps minimum
## 9. Anti-Patterns (Banned)
- No emojis — anywhere in UI, code, or alt text
- No `Inter` font — use `Geist`, `Outfit`, `Cabinet Grotesk`, `Satoshi`
- No generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`) — if serif is needed, use distinctive modern serifs only (`Fraunces`, `Instrument Serif`)
- No pure black (`#000000`) — Off-Black or Zinc-950 only
- No neon outer glows or default box-shadow glows
- No oversaturated accent colors above 80%
- No excessive gradient text on large headers
- No custom mouse cursors
- No overlapping elements — text never overlaps images or other content. Clean spatial separation always
- No 3-column equal card layouts for features
- No centered Hero sections (at this variance level)
- No filler UI text: "Scroll to explore", "Swipe down", "Discover more below", scroll arrows, bouncing chevrons — all BANNED
- No generic names: "John Doe", "Sarah Chan", "Acme", "Nexus", "SmartFlow"
- No fake round numbers: `99.99%`, `50%`, `1234567` — use organic data: `47.2%`, `+1 (312) 847-1928`
- No AI copywriting clichés: "Elevate", "Seamless", "Unleash", "Next-Gen", "Revolutionize"
- No broken Unsplash links — use `picsum.photos/seed/{id}/800/600` or SVG UI Avatars
- No generic `shadcn/ui` defaults — customize radii, colors, shadows to match this system
- No `z-index` spam — use only for Navbar, Modal, Overlay layer contexts
- No `h-screen` — always `min-h-[100dvh]`
- No circular loading spinners — skeletal shimmer only
+184
View File
@@ -0,0 +1,184 @@
---
name: stitch-design-taste
description: Semantic Design System Skill for Google Stitch. Generates agent-friendly DESIGN.md files that enforce premium, anti-generic UI standards — strict typography, calibrated color, asymmetric layouts, perpetual micro-motion, and hardware-accelerated performance.
---
# Stitch Design Taste — Semantic Design System Skill
## Overview
This skill generates `DESIGN.md` files optimized for Google Stitch screen generation. It translates the battle-tested anti-slop frontend engineering directives into Stitch's native semantic design language — descriptive, natural-language rules paired with precise values that Stitch's AI agent can interpret to produce premium, non-generic interfaces.
The generated `DESIGN.md` serves as the **single source of truth** for prompting Stitch to generate new screens that align with a curated, high-agency design language. Stitch interprets design through **"Visual Descriptions"** supported by specific color values, typography specs, and component behaviors.
## Prerequisites
- Access to Google Stitch via [labs.google/stitch](https://labs.google/stitch)
- Optionally: Stitch MCP Server for programmatic integration with Cursor, Antigravity, or Gemini CLI
## The Goal
Generate a `DESIGN.md` file that encodes:
1. **Visual atmosphere** — the mood, density, and design philosophy
2. **Color calibration** — neutrals, accents, and banned patterns with hex codes
3. **Typographic architecture** — font stacks, scale hierarchy, and anti-patterns
4. **Component behaviors** — buttons, cards, inputs with interaction states
5. **Layout principles** — grid systems, spacing philosophy, responsive strategy
6. **Motion philosophy** — animation engine specs, spring physics, perpetual micro-interactions
7. **Anti-patterns** — explicit list of banned AI design clichés
## Analysis & Synthesis Instructions
### 1. Define the Atmosphere
Evaluate the target project's intent. Use evocative adjectives from the taste spectrum:
- **Density:** "Art Gallery Airy" (13) → "Daily App Balanced" (47) → "Cockpit Dense" (810)
- **Variance:** "Predictable Symmetric" (13) → "Offset Asymmetric" (47) → "Artsy Chaotic" (810)
- **Motion:** "Static Restrained" (13) → "Fluid CSS" (47) → "Cinematic Choreography" (810)
Default baseline: Variance 8, Motion 6, Density 4. Adapt dynamically based on user's vibe description.
### 2. Map the Color Palette
For each color provide: **Descriptive Name** + **Hex Code** + **Functional Role**.
**Mandatory constraints:**
- Maximum 1 accent color. Saturation below 80%
- The "AI Purple/Blue Neon" aesthetic is strictly BANNED — no purple button glows, no neon gradients
- Use absolute neutral bases (Zinc/Slate) with high-contrast singular accents
- Stick to one palette for the entire output — no warm/cool gray fluctuation
- Never use pure black (`#000000`) — use Off-Black, Zinc-950, or Charcoal
### 3. Establish Typography Rules
- **Display/Headlines:** Track-tight, controlled scale. Not screaming. Hierarchy through weight and color, not just massive size
- **Body:** Relaxed leading, max 65 characters per line
- **Font Selection:** `Inter` is BANNED for premium/creative contexts. Force unique character: `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi`
- **Serif Ban:** Generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`, `Palatino`) are BANNED. If serif is needed for editorial/creative contexts, use only distinctive modern serifs: `Fraunces`, `Gambarino`, `Editorial New`, or `Instrument Serif`. Serif is always BANNED in dashboards or software UIs
- **Dashboard Constraint:** Use Sans-Serif pairings exclusively (`Geist` + `Geist Mono` or `Satoshi` + `JetBrains Mono`)
- **High-Density Override:** When density exceeds 7, all numbers must use Monospace
### 4. Define the Hero Section
The Hero is the first impression and must be creative, striking, and never generic:
- **Inline Image Typography:** Embed small, contextual photos or visuals directly between words or letters in the headline. Images sit inline at type-height, rounded, acting as visual punctuation. This is the signature creative technique
- **No Overlapping:** Text must never overlap images or other text. Every element occupies its own clean spatial zone
- **No Filler Text:** "Scroll to explore", "Swipe down", scroll arrow icons, bouncing chevrons are BANNED. The content should pull users in naturally
- **Asymmetric Structure:** Centered Hero layouts BANNED when variance exceeds 4
- **CTA Restraint:** Maximum one primary CTA. No secondary "Learn more" links
### 5. Describe Component Stylings
For each component type, describe shape, color, shadow depth, and interaction behavior:
- **Buttons:** Tactile push feedback on active state. No neon outer glows. No custom mouse cursors
- **Cards:** Use ONLY when elevation communicates hierarchy. Tint shadows to background hue. For high-density layouts, replace cards with border-top dividers or negative space
- **Inputs/Forms:** Label above input, helper text optional, error text below. Standard gap spacing
- **Loading States:** Skeletal loaders matching layout dimensions — no generic circular spinners
- **Empty States:** Composed compositions indicating how to populate data
- **Error States:** Clear, inline error reporting
### 6. Define Layout Principles
- No overlapping elements — every element occupies its own clear spatial zone. No absolute-positioned content stacking
- Centered Hero sections are BANNED when variance exceeds 4 — force Split Screen, Left-Aligned, or Asymmetric Whitespace
- The generic "3 equal cards horizontally" feature row is BANNED — use 2-column Zig-Zag, asymmetric grid, or horizontal scroll
- CSS Grid over Flexbox math — never use `calc()` percentage hacks
- Contain layouts using max-width constraints (e.g., 1400px centered)
- Full-height sections must use `min-h-[100dvh]` — never `h-screen` (iOS Safari catastrophic jump)
### 7. Define Responsive Rules
Every design must work across all viewports:
- **Mobile-First Collapse (< 768px):** All multi-column layouts collapse to single column. No exceptions
- **No Horizontal Scroll:** Horizontal overflow on mobile is a critical failure
- **Typography Scaling:** Headlines scale via `clamp()`. Body text minimum `1rem`/`14px`
- **Touch Targets:** All interactive elements minimum `44px` tap target
- **Image Behavior:** Inline typography images (photos between words) stack below headline on mobile
- **Navigation:** Desktop horizontal nav collapses to clean mobile menu
- **Spacing:** Vertical section gaps reduce proportionally (`clamp(3rem, 8vw, 6rem)`)
### 8. Encode Motion Philosophy
- **Spring Physics default:** `stiffness: 100, damping: 20` — premium, weighty feel. No linear easing
- **Perpetual Micro-Interactions:** Every active component should have an infinite loop state (Pulse, Typewriter, Float, Shimmer)
- **Staggered Orchestration:** Never mount lists instantly — use cascade delays for waterfall reveals
- **Performance:** Animate exclusively via `transform` and `opacity`. Never animate `top`, `left`, `width`, `height`. Grain/noise filters on fixed pseudo-elements only
### 9. List Anti-Patterns (AI Tells)
Encode these as explicit "NEVER DO" rules in the DESIGN.md:
- No emojis anywhere
- No `Inter` font
- No generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`) — distinctive modern serifs only if needed
- No pure black (`#000000`)
- No neon/outer glow shadows
- No oversaturated accents
- No excessive gradient text on large headers
- No custom mouse cursors
- No overlapping elements — clean spatial separation always
- No 3-column equal card layouts
- No generic names ("John Doe", "Acme", "Nexus")
- No fake round numbers (`99.99%`, `50%`)
- No AI copywriting clichés ("Elevate", "Seamless", "Unleash", "Next-Gen")
- No filler UI text: "Scroll to explore", "Swipe down", scroll arrows, bouncing chevrons
- No broken Unsplash links — use `picsum.photos` or SVG avatars
- No centered Hero sections (for high-variance projects)
## Output Format (DESIGN.md Structure)
```markdown
# Design System: [Project Title]
## 1. Visual Theme & Atmosphere
(Evocative description of the mood, density, variance, and motion intensity.
Example: "A restrained, gallery-airy interface with confident asymmetric layouts
and fluid spring-physics motion. The atmosphere is clinical yet warm — like a
well-lit architecture studio.")
## 2. Color Palette & Roles
- **Canvas White** (#F9FAFB) — Primary background surface
- **Pure Surface** (#FFFFFF) — Card and container fill
- **Charcoal Ink** (#18181B) — Primary text, Zinc-950 depth
- **Muted Steel** (#71717A) — Secondary text, descriptions, metadata
- **Whisper Border** (rgba(226,232,240,0.5)) — Card borders, 1px structural lines
- **[Accent Name]** (#XXXXXX) — Single accent for CTAs, active states, focus rings
(Max 1 accent. Saturation < 80%. No purple/neon.)
## 3. Typography Rules
- **Display:** [Font Name] — Track-tight, controlled scale, weight-driven hierarchy
- **Body:** [Font Name] — Relaxed leading, 65ch max-width, neutral secondary color
- **Mono:** [Font Name] — For code, metadata, timestamps, high-density numbers
- **Banned:** Inter, generic system fonts for premium contexts. Serif fonts banned in dashboards.
## 4. Component Stylings
* **Buttons:** Flat, no outer glow. Tactile -1px translate on active. Accent fill for primary, ghost/outline for secondary.
* **Cards:** Generously rounded corners (2.5rem). Diffused whisper shadow. Used only when elevation serves hierarchy. High-density: replace with border-top dividers.
* **Inputs:** Label above, error below. Focus ring in accent color. No floating labels.
* **Loaders:** Skeletal shimmer matching exact layout dimensions. No circular spinners.
* **Empty States:** Composed, illustrated compositions — not just "No data" text.
## 5. Layout Principles
(Grid-first responsive architecture. Asymmetric splits for Hero sections.
Strict single-column collapse below 768px. Max-width containment.
No flexbox percentage math. Generous internal padding.)
## 6. Motion & Interaction
(Spring physics for all interactive elements. Staggered cascade reveals.
Perpetual micro-loops on active dashboard components. Hardware-accelerated
transforms only. Isolated Client Components for CPU-heavy animations.)
## 7. Anti-Patterns (Banned)
(Explicit list of forbidden patterns: no emojis, no Inter, no pure black,
no neon glows, no 3-column equal grids, no AI copywriting clichés,
no generic placeholder names, no broken image links.)
```
## Best Practices
- **Be Descriptive:** "Deep Charcoal Ink (#18181B)" — not just "dark text"
- **Be Functional:** Explain what each element is used for
- **Be Consistent:** Same terminology throughout the document
- **Be Precise:** Include exact hex codes, rem values, pixel values in parentheses
- **Be Opinionated:** This is not a neutral template — it enforces a specific, premium aesthetic
## Tips for Success
1. Start with the atmosphere — understand the vibe before detailing tokens
2. Look for patterns — identify consistent spacing, sizing, and styling
3. Think semantically — name colors by purpose, not just appearance
4. Consider hierarchy — document how visual weight communicates importance
5. Encode the bans — anti-patterns are as important as the rules themselves
## Common Pitfalls to Avoid
- Using technical jargon without translation ("rounded-xl" instead of "generously rounded corners")
- Omitting hex codes or using only descriptive names
- Forgetting functional roles of design elements
- Being too vague in atmosphere descriptions
- Ignoring the anti-pattern list — these are what make the output premium
- Defaulting to generic "safe" designs instead of enforcing the curated aesthetic
+4
View File
@@ -0,0 +1,4 @@
# 빌드 산출·환경별 값
2_frontend/tsconfig.tsbuildinfo
2_frontend/.env.production
+13 -9
View File
@@ -10,22 +10,26 @@
// 팔레트는 localStorage 'theme' 키, 다크모드는 'theme-store' (zustand persist). // 팔레트는 localStorage 'theme' 키, 다크모드는 'theme-store' (zustand persist).
;(function () { ;(function () {
try { try {
var pal = localStorage.getItem("theme") || "clean-blue" var pal = localStorage.getItem("theme") || "samsung"
// 이전 기본 베이지는 한 번만 교체. 이후 직접 고른 팔레트는 유지. // 기본 팔레트 교체는 한 번만(삼성향, 2026-09). 이후 직접 고른 팔레트는 유지.
if (!localStorage.getItem("clean-blue-default-v1")) { if (!localStorage.getItem("samsung-default-v1")) {
if (pal === "warm-tan") { if (pal === "warm-tan" || pal === "clean-blue") {
pal = "clean-blue" pal = "samsung"
localStorage.setItem("theme", pal) localStorage.setItem("theme", pal)
} }
localStorage.setItem("clean-blue-default-v1", "1") localStorage.setItem("samsung-default-v1", "1")
} }
document.documentElement.setAttribute("data-theme", pal) document.documentElement.setAttribute("data-theme", pal)
var raw = localStorage.getItem("theme-store") var raw = localStorage.getItem("theme-store")
var mode = "dark" // 저장값 없으면 다크 (themeStore 기본과 동일) var mode = "light" // 저장값 없으면 라이트 (themeStore 기본과 동일)
if (raw) { // 기본 모드를 라이트로 바꾸면서(2026-09) 예전 저장값 dark 는 한 번만 light 로. 이후 직접 고른 건 유지.
if (raw && localStorage.getItem("light-default-v1")) {
try { try {
mode = (JSON.parse(raw).state || {}).theme || "dark" mode = (JSON.parse(raw).state || {}).theme || "light"
} catch (e) {} } catch (e) {}
} else {
localStorage.removeItem("theme-store")
localStorage.setItem("light-default-v1", "1")
} }
var dark = var dark =
mode === "dark" || mode === "dark" ||
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 83 B

+1 -1
View File
@@ -18,7 +18,7 @@ export default function App() {
return () => setBridgeNavigate(null) return () => setBridgeNavigate(null)
}, [navigate]) }, [navigate])
// route 바뀔 때마다 호스트에 보고 — C#가 마지막 챗봇 위치 기억(Ctrl+Shift+8 복귀용). // route 바뀔 때마다 호스트에 보고 — C#가 마지막 챗봇 위치 기억(Ctrl+Alt+W 복귀용).
useEffect(() => { useEffect(() => {
reportRoute(location.pathname) reportRoute(location.pathname)
}, [location.pathname]) }, [location.pathname])
Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

+1
View File
@@ -5,6 +5,7 @@ export const PATHS = {
SNAP_NEW: "/snap/new", SNAP_NEW: "/snap/new",
SNAP_SESSION: "/snap/s/:id", SNAP_SESSION: "/snap/s/:id",
SNIPPET: "/snippet", SNIPPET: "/snippet",
ADMIN: "/admin",
} as const } as const
export type Path = (typeof PATHS)[keyof typeof PATHS] export type Path = (typeof PATHS)[keyof typeof PATHS]
@@ -0,0 +1,20 @@
import { useQuery } from "@tanstack/react-query"
import { apiGet } from "@/lib/api/client"
import type { AdminStatsResponse } from "@/types/api"
export const ADMIN_STATS_KEY = ["admin", "stats"] as const
export const adminApi = {
stats: (from: string, to: string) =>
apiGet<AdminStatsResponse>("/admin/stats", { params: { from, to } }),
}
/** 관리자 집계 — 기간(YYYY-MM-DD) 바뀌면 재조회. 관리자 아니면 403 이라 enabled 로 막음. */
export function useAdminStats(from: string, to: string, enabled = true) {
return useQuery({
queryKey: [...ADMIN_STATS_KEY, from, to],
queryFn: () => adminApi.stats(from, to),
enabled,
staleTime: 60_000,
})
}
@@ -0,0 +1,98 @@
import { describe, expect, it, vi, beforeEach } from "vitest"
import { render, screen } from "@testing-library/react"
import { MemoryRouter } from "react-router-dom"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import AdminStatsPage from "./AdminStatsPage"
import { useAuthStore } from "@/features/auth/store/authStore"
import * as client from "@/lib/api/client"
import type { AdminStatsResponse } from "@/types/api"
// 훅이 모듈 안 adminApi 를 직접 잡고 있어서 그 아래 apiGet 을 막음
vi.mock("@/lib/api/client", async (orig) => ({
...(await orig<typeof client>()),
apiGet: vi.fn(),
}))
const SAMPLE: AdminStatsResponse = {
from: "2026-09-01",
to: "2026-09-21",
totals: {
requests: 12,
inputTokens: 1000,
outputTokens: 500,
totalTokens: 1500,
costUsd: 0.1234,
avgElapsedMs: 2500,
users: 2,
sessions: 3,
},
byUser: [
{
userId: "u1",
email: "a@x.com",
name: "김개발",
sessions: 2,
requests: 10,
inputTokens: 900,
outputTokens: 450,
totalTokens: 1350,
costUsd: 0.12,
avgElapsedMs: 2000,
},
],
byDay: [
{
day: "2026-09-20",
requests: 5,
inputTokens: 500,
outputTokens: 250,
totalTokens: 750,
costUsd: 0.05,
avgElapsedMs: 2000,
},
],
}
function mount() {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={qc}>
<MemoryRouter>
<AdminStatsPage />
</MemoryRouter>
</QueryClientProvider>
)
}
const asUser = (role: "ADMIN" | "USER") =>
useAuthStore.setState({
user: {
id: "u",
email: "a@x.com",
userName: null,
role,
employeeId: null,
department: null,
authProvider: "local",
},
})
describe("AdminStatsPage", () => {
beforeEach(() => vi.mocked(client.apiGet).mockReset().mockResolvedValue(SAMPLE))
it("관리자 아니면 안내만 보이고 API 안 부름", () => {
asUser("USER")
mount()
expect(screen.getByText("관리자만 볼 수 있어")).toBeTruthy()
expect(client.apiGet).not.toHaveBeenCalled()
})
it("관리자면 요약 카드·사용자 표를 그린다", async () => {
asUser("ADMIN")
mount()
expect(await screen.findByText("1,500")).toBeTruthy() // 총 토큰
expect(screen.getByText("2.5s")).toBeTruthy()
expect(screen.getByText("김개발")).toBeTruthy()
expect(client.apiGet).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,175 @@
import { useState } from "react"
import { useNavigate } from "react-router-dom"
import { ChevronLeft } from "lucide-react"
import { PATHS } from "@/config/routes"
import { useAuthStore } from "@/features/auth/store/authStore"
import { useEscapeKey } from "@/features/snap/hooks/useEscapeKey"
import { Kbd } from "@/shared/components/Kbd"
import { ApiError } from "@/lib/api/errors"
import { useAdminStats } from "../api/admin.api"
const fmtInt = (n: number) => n.toLocaleString("ko-KR")
const fmtSec = (ms: number | null) => (ms === null ? "" : `${(ms / 1000).toFixed(1)}s`)
const isoDay = (d: Date) => d.toISOString().slice(0, 10)
const PRESETS: { label: string; days: number }[] = [
{ label: "오늘", days: 1 },
{ label: "7일", days: 7 },
{ label: "30일", days: 30 },
{ label: "90일", days: 90 },
]
/** 관리자 대시보드 — 총 토큰·응답시간 + 사용자별·일별. 서버는 ChatMessage 집계만(새로 모으는 것 없음).
* 비용은 안 보여줌 — 사내 LLM(FabriX) 은 단가가 없어 OpenCode 가 0 으로 줌. 단가 정해지면 그때 카드 추가. */
export default function AdminStatsPage() {
const navigate = useNavigate()
const isAdmin = useAuthStore((s) => s.user?.role === "ADMIN")
const [days, setDays] = useState(30)
useEscapeKey(() => navigate(PATHS.SNAP))
const to = isoDay(new Date())
const from = isoDay(new Date(Date.now() - (days - 1) * 86_400_000))
const { data, isLoading, error } = useAdminStats(from, to, isAdmin)
if (!isAdmin) {
return (
<div className="text-muted-foreground flex h-full items-center justify-center text-sm">
</div>
)
}
const t = data?.totals
const maxDayTokens = Math.max(1, ...(data?.byDay.map((d) => d.totalTokens) ?? [0]))
return (
<div className="mx-auto flex h-full w-full max-w-[880px] flex-col gap-4 overflow-y-auto px-5 py-3">
<div className="flex items-center justify-between">
<button
type="button"
onClick={() => navigate(PATHS.SNAP)}
className="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring -ml-2 inline-flex h-7 items-center gap-1 rounded-md px-2 text-[11.5px] transition-colors focus-visible:ring-2 focus-visible:outline-none"
>
<ChevronLeft className="size-3.5" aria-hidden="true" />
<Kbd>Esc</Kbd>
</button>
<div className="flex items-center gap-1" role="group" aria-label="기간">
{PRESETS.map((p) => (
<button
key={p.days}
type="button"
onClick={() => setDays(p.days)}
aria-pressed={days === p.days}
className={`h-7 rounded-md px-2.5 text-[11.5px] font-medium transition-colors ${
days === p.days
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-accent hover:text-foreground"
}`}
>
{p.label}
</button>
))}
</div>
</div>
<div>
<h1 className="text-base font-semibold"></h1>
<p className="text-muted-foreground text-[11.5px]">
{from} ~ {to} · assistant
</p>
</div>
{error instanceof ApiError && <div className="text-destructive text-sm">{error.message}</div>}
{isLoading && <div className="text-muted-foreground text-xs"> </div>}
{t && (
<>
{/* 요약 카드 4개 */}
<div className="grid grid-cols-3 gap-2">
<Stat
label="요청"
value={fmtInt(t.requests)}
sub={`${t.users}명 · ${t.sessions}세션`}
/>
<Stat
label="토큰"
value={fmtInt(t.totalTokens)}
sub={`입력 ${fmtInt(t.inputTokens)} · 출력 ${fmtInt(t.outputTokens)}`}
/>
<Stat label="평균 응답" value={fmtSec(t.avgElapsedMs)} sub="첫 요청→완료" />
</div>
{/* 일별 토큰 막대 — 라이브러리 없이 div 로 */}
<section className="border-border bg-card rounded-lg border p-3">
<div className="text-muted-foreground mb-2 text-[11px] font-semibold tracking-wide">
</div>
{data.byDay.length === 0 ? (
<div className="text-muted-foreground py-6 text-center text-xs">
</div>
) : (
<div className="flex h-28 items-end gap-[3px]" role="img" aria-label="일별 토큰 막대">
{data.byDay.map((d) => (
<div
key={d.day}
title={`${d.day}: ${fmtInt(d.totalTokens)} 토큰 · ${d.requests}`}
className="bg-primary/80 hover:bg-primary min-w-[4px] flex-1 rounded-sm transition-colors"
style={{ height: `${Math.max(2, (d.totalTokens / maxDayTokens) * 100)}%` }}
/>
))}
</div>
)}
</section>
{/* 사용자별 표 */}
<section className="border-border bg-card overflow-hidden rounded-lg border">
<table className="w-full text-[12px]">
<thead className="text-muted-foreground bg-muted/50 text-left text-[11px]">
<tr>
<th className="px-3 py-2 font-semibold"></th>
<th className="px-3 py-2 text-right font-semibold"></th>
<th className="px-3 py-2 text-right font-semibold"></th>
<th className="px-3 py-2 text-right font-semibold"></th>
<th className="px-3 py-2 text-right font-semibold"> </th>
</tr>
</thead>
<tbody className="divide-border/70 divide-y">
{data.byUser.length === 0 && (
<tr>
<td colSpan={5} className="text-muted-foreground py-6 text-center text-xs">
</td>
</tr>
)}
{data.byUser.map((u) => (
<tr key={u.userId} className="hover:bg-accent/40">
<td className="px-3 py-2">
<div className="font-medium">{u.name || u.email}</div>
{u.name && <div className="text-muted-foreground text-[11px]">{u.email}</div>}
</td>
<td className="px-3 py-2 text-right tabular-nums">{fmtInt(u.requests)}</td>
<td className="px-3 py-2 text-right tabular-nums">{fmtInt(u.sessions)}</td>
<td className="px-3 py-2 text-right tabular-nums">{fmtInt(u.totalTokens)}</td>
<td className="px-3 py-2 text-right tabular-nums">{fmtSec(u.avgElapsedMs)}</td>
</tr>
))}
</tbody>
</table>
</section>
</>
)}
</div>
)
}
function Stat({ label, value, sub }: { label: string; value: string; sub: string }) {
return (
<div className="border-border bg-card rounded-lg border px-3 py-2.5">
<div className="text-muted-foreground text-[11px] font-semibold tracking-wide">{label}</div>
<div className="mt-0.5 text-lg font-semibold tabular-nums">{value}</div>
<div className="text-muted-foreground text-[11px]">{sub}</div>
</div>
)
}
@@ -1,4 +1,4 @@
import { streamLLM, type LLMUsagePayload } from "@/lib/streaming" import { streamLLM, type AgentStep, type LLMUsagePayload } from "@/lib/streaming"
import { apiPost } from "@/lib/api/client" import { apiPost } from "@/lib/api/client"
import type { SnapStreamRequest } from "../contract/types" import type { SnapStreamRequest } from "../contract/types"
@@ -7,6 +7,7 @@ export interface SnapStreamHandlers {
onDone: () => void onDone: () => void
onTitle?: (title: string) => void onTitle?: (title: string) => void
onUsage?: (usage: LLMUsagePayload) => void onUsage?: (usage: LLMUsagePayload) => void
onStep?: (step: AgentStep) => void
onError?: (e: Error) => void onError?: (e: Error) => void
} }
@@ -25,6 +26,7 @@ export function snapStream(
onDone: () => handlers.onDone(), onDone: () => handlers.onDone(),
onTitle: handlers.onTitle, onTitle: handlers.onTitle,
onUsage: handlers.onUsage, onUsage: handlers.onUsage,
onStep: handlers.onStep,
onError: handlers.onError, onError: handlers.onError,
}, },
}) })
@@ -30,35 +30,50 @@ describe("Composer 캡쳐 이미지 첨부", () => {
const wv = mockWebview() const wv = mockWebview()
initBridgeNavigate() initBridgeNavigate()
const { unmount } = render(<Composer onSend={() => {}} acceptCapture />) const { unmount } = render(<Composer onSend={() => {}} capturePath="/snap/new" />)
act(() => wv.emit({ type: "capture.image", dataUrl: "data:image/png;base64,abc" })) act(() =>
wv.emit({
type: "capture.image",
path: "/snap/new",
dataUrl: "data:image/png;base64,abc",
})
)
expect(screen.getAllByRole("img")).toHaveLength(1) expect(screen.getAllByRole("img")).toHaveLength(1)
unmount() unmount()
render(<Composer onSend={() => {}} acceptCapture />) // 다른 대화로 이동했다가 새 대화 재진입 시뮬레이션 render(<Composer onSend={() => {}} capturePath="/snap/new" />)
expect(screen.queryAllByRole("img")).toHaveLength(0) expect(screen.queryAllByRole("img")).toHaveLength(0)
}) })
// 코드리뷰 Important 회귀 재현: 기존 대화방(SessionChatPage, acceptCapture 없음)이 살아있는 채로 it("다른 대화용 캡쳐는 소비하지 않음", () => {
// capture.image 가 오면, 리마운트 전에 그 Composer가 pending을 훔쳐가 새 대화 Composer가 못 받음.
it("acceptCapture 없으면 capture 이벤트를 무시하고 pending을 안 건드림(출발지 도둑질 방지)", () => {
const wv = mockWebview() const wv = mockWebview()
initBridgeNavigate() initBridgeNavigate()
render(<Composer onSend={() => {}} />) // acceptCapture 없음 — 기존 대화방 시뮬레이션 render(<Composer onSend={() => {}} capturePath="/snap/s/current" />)
act(() => wv.emit({ type: "capture.image", dataUrl: "data:image/png;base64,xyz" })) act(() =>
wv.emit({
type: "capture.image",
path: "/snap/s/previous",
dataUrl: "data:image/png;base64,xyz",
})
)
expect(screen.queryAllByRole("img")).toHaveLength(0) // 여기엔 안 붙음 expect(screen.queryAllByRole("img")).toHaveLength(0)
// pending이 안 비워졌어야 — 곧 마운트될 새 대화 Composer가 그대로 소비 가능해야 함 expect(consumePendingCaptureImage("/snap/s/previous")).toBe("data:image/png;base64,xyz")
expect(consumePendingCaptureImage()).toBe("data:image/png;base64,xyz")
}) })
it("캡쳐 이미지만 있어도 이미지 계약으로 전송한다", () => { it("캡쳐 이미지만 있어도 이미지 계약으로 전송한다", () => {
const wv = mockWebview() const wv = mockWebview()
initBridgeNavigate() initBridgeNavigate()
const onSend = vi.fn() const onSend = vi.fn()
render(<Composer onSend={onSend} acceptCapture />) render(<Composer onSend={onSend} capturePath="/snap/new" />)
act(() => wv.emit({ type: "capture.image", dataUrl: "data:image/png;base64,eA==" })) act(() =>
wv.emit({
type: "capture.image",
path: "/snap/new",
dataUrl: "data:image/png;base64,eA==",
})
)
fireEvent.click(screen.getByRole("button", { name: "전송" })) fireEvent.click(screen.getByRole("button", { name: "전송" }))
@@ -71,10 +86,16 @@ describe("Composer 캡쳐 이미지 첨부", () => {
it("이미지는 최대 4장까지만 첨부한다", () => { it("이미지는 최대 4장까지만 첨부한다", () => {
const wv = mockWebview() const wv = mockWebview()
initBridgeNavigate() initBridgeNavigate()
render(<Composer onSend={() => {}} acceptCapture />) render(<Composer onSend={() => {}} capturePath="/snap/new" />)
for (let i = 0; i < 5; i++) { for (let i = 0; i < 5; i++) {
act(() => wv.emit({ type: "capture.image", dataUrl: `data:image/png;base64,eA${i}=` })) act(() =>
wv.emit({
type: "capture.image",
path: "/snap/new",
dataUrl: `data:image/png;base64,eA${i}=`,
})
)
} }
expect(screen.queryAllByRole("img")).toHaveLength(4) expect(screen.queryAllByRole("img")).toHaveLength(4)
@@ -12,10 +12,8 @@ interface Props {
busy?: boolean busy?: boolean
onStop?: () => void onStop?: () => void
placeholder?: string placeholder?: string
// 캡쳐 이미지 첨부를 받을지 — 새 대화(NewChatPage)만 true. 기존 대화방(SessionChatPage)이 켜져 // 이 Composer가 받을 캡처 대상 route. 대상이 다르면 pending을 남겨 목적지 리마운트가 소비함.
// 있으면 navigate(/snap/new)+capture.image 순서에서 리마운트 전에 여기가 pending을 훔쳐가 capturePath?: string
// 정작 새 대화 Composer엔 이미지가 안 붙는 레이스가 생김 — 그래서 출발지는 아예 안 건드리게 게이팅.
acceptCapture?: boolean
} }
// Blob → data URL(base64). 클립보드 이미지를 chat 계약으로 바꿀 때 씀. // Blob → data URL(base64). 클립보드 이미지를 chat 계약으로 바꿀 때 씀.
@@ -47,7 +45,7 @@ function imageFromDataUrl(data: string): SnapImageInput | null {
return { mediaType: match[1].toLowerCase() as SnapImageMediaType, data } return { mediaType: match[1].toLowerCase() as SnapImageMediaType, data }
} }
export function Composer({ onSend, busy, onStop, placeholder, acceptCapture }: Props) { export function Composer({ onSend, busy, onStop, placeholder, capturePath }: Props) {
const [value, setValue] = useState("") const [value, setValue] = useState("")
// 100자↑ 붙여넣기로 접어둔 텍스트들. 전송 시 입력값과 합쳐 보냄. // 100자↑ 붙여넣기로 접어둔 텍스트들. 전송 시 입력값과 합쳐 보냄.
const [attachments, setAttachments] = useState<string[]>([]) const [attachments, setAttachments] = useState<string[]>([])
@@ -88,22 +86,18 @@ export function Composer({ onSend, busy, onStop, placeholder, acceptCapture }: P
return () => cancelAnimationFrame(raf) return () => cancelAnimationFrame(raf)
}, []) }, [])
// 캡 이미지 수신 — 마운트 시 놓친 것 consume(네비 직후 이벤트를 놓쳐도 반영) + 이후는 이벤트로 누적(FR-008). // 캡 이미지 수신 — 목적지 route만 pending을 소비해 네비게이션 리마운트 race를 막음.
// acceptCapture 아니면 아예 pending을 안 건드림 — 기존 대화방(SessionChatPage)이 새 대화
// 마운트보다 먼저 훔쳐가 이미지가 유실되는 레이스 방지(출발지 게이팅).
useEffect(() => { useEffect(() => {
if (!acceptCapture) return if (!capturePath) return
const pending = consumePendingCaptureImage() const pending = consumePendingCaptureImage(capturePath)
if (pending) addImage(pending) if (pending) addImage(pending)
const onCapture = () => { const onCapture = () => {
// detail 대신 consume — 같은 동기 스택이라 값은 동일, 이걸로 pending도 같이 비워야 const dataUrl = consumePendingCaptureImage(capturePath)
// 나중에 리마운트될 때(다른 대화→새 대화) stale 이미지가 재소비되지 않음.
const dataUrl = consumePendingCaptureImage()
if (dataUrl) addImage(dataUrl) if (dataUrl) addImage(dataUrl)
} }
window.addEventListener("bridge:captureImage", onCapture) window.addEventListener("bridge:captureImage", onCapture)
return () => window.removeEventListener("bridge:captureImage", onCapture) return () => window.removeEventListener("bridge:captureImage", onCapture)
}, [acceptCapture]) }, [capturePath])
const removeAttachment = (i: number) => setAttachments((a) => a.filter((_, j) => j !== i)) const removeAttachment = (i: number) => setAttachments((a) => a.filter((_, j) => j !== i))
const removeImageAttachment = (i: number) => const removeImageAttachment = (i: number) =>
@@ -9,7 +9,6 @@ interface Props {
// 실제로 자주 묻는 것들 — 누르면 바로 답이 오는 걸 보여주는 게 빈 화면 설명보다 낫다. // 실제로 자주 묻는 것들 — 누르면 바로 답이 오는 걸 보여주는 게 빈 화면 설명보다 낫다.
const EXAMPLES = [ const EXAMPLES = [
"MARA 에서 자재번호로 자재유형(MTART) 읽는 SELECT SINGLE", "MARA 에서 자재번호로 자재유형(MTART) 읽는 SELECT SINGLE",
"셀렉션 화면 있는 ALV 리포트 뼈대 (CL_SALV_TABLE)",
"내부 테이블 LOOP 에서 그룹 소계 구하는 관용구", "내부 테이블 LOOP 에서 그룹 소계 구하는 관용구",
] ]
@@ -23,8 +23,8 @@ describe("Message 코드펜스 렌더", () => {
// 스크롤 컨테이너 있는 CodeBlock 으로 감싸져야 함 // 스크롤 컨테이너 있는 CodeBlock 으로 감싸져야 함
const block = container.querySelector("[data-code-block]") const block = container.querySelector("[data-code-block]")
expect(block).not.toBeNull() expect(block).not.toBeNull()
// 코드 상자 색은 앱 테마를 따름 — 기본(다크)에선 어두운 코드 상자, 라이트 모드면 흰 에디터 룩 // 코드 상자 색은 앱 테마를 따름 — 기본이 라이트(2026-09-21)라 언어 없는 블럭은 흰 에디터 룩, 다크면 bg-[#0d1117]
expect(block?.className).toContain("bg-[#0d1117]") expect(block?.className).toContain("bg-white")
// 인라인 code 스타일(bg-black/10)로 새지 않아야 함 // 인라인 code 스타일(bg-black/10)로 새지 않아야 함
expect(container.querySelector("code.rounded")).toBeNull() expect(container.querySelector("code.rounded")).toBeNull()
}) })
@@ -45,7 +45,7 @@ export function NavRail({ blocks, containerRef }: Props) {
<ClipboardHistory /> <ClipboardHistory />
<div className="border-border flex flex-none items-center gap-1.5 border-b px-3 py-2.5"> <div className="border-border flex flex-none items-center gap-1.5 border-b px-3 py-2.5">
<span className="size-1.5 rounded-full bg-success" /> <span className="bg-success size-1.5 rounded-full" />
<span className="text-muted-foreground font-mono text-[10px] tracking-widest uppercase"> <span className="text-muted-foreground font-mono text-[10px] tracking-widest uppercase">
Source Nav Source Nav
</span> </span>
@@ -79,7 +79,7 @@ export function NavRail({ blocks, containerRef }: Props) {
className="text-muted-foreground/50 hover:text-foreground flex-none rounded p-1.5 transition-colors" className="text-muted-foreground/50 hover:text-foreground flex-none rounded p-1.5 transition-colors"
> >
{copiedIdx === b.index ? ( {copiedIdx === b.index ? (
<Check className="size-3 text-success" /> <Check className="text-success size-3" />
) : ( ) : (
<Copy className="size-3" /> <Copy className="size-3" />
)} )}
@@ -1,7 +1,8 @@
import { LogOut } from "lucide-react" import { BarChart3, LogOut } from "lucide-react"
import { useNavigate } from "react-router-dom" import { useNavigate } from "react-router-dom"
import { PATHS } from "@/config/routes" import { PATHS } from "@/config/routes"
import { useLogout } from "@/features/auth/hooks/useLogout" import { useLogout } from "@/features/auth/hooks/useLogout"
import { useAuthStore } from "@/features/auth/store/authStore"
import { ThemeToggle } from "@/shared/components/ThemeToggle" import { ThemeToggle } from "@/shared/components/ThemeToggle"
import { Button } from "@/shared/ui/button" import { Button } from "@/shared/ui/button"
@@ -9,6 +10,7 @@ import { Button } from "@/shared/ui/button"
export function SnapUserControls() { export function SnapUserControls() {
const navigate = useNavigate() const navigate = useNavigate()
const logout = useLogout() const logout = useLogout()
const isAdmin = useAuthStore((s) => s.user?.role === "ADMIN")
const handleLogout = () => { const handleLogout = () => {
logout.mutate(undefined, { logout.mutate(undefined, {
@@ -18,6 +20,19 @@ export function SnapUserControls() {
return ( return (
<div className="flex items-center gap-0.5"> <div className="flex items-center gap-0.5">
{isAdmin && (
<Button
type="button"
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-foreground size-7"
aria-label="관리자 대시보드"
title="관리자 대시보드"
onClick={() => navigate(PATHS.ADMIN)}
>
<BarChart3 className="size-3.5" aria-hidden="true" />
</Button>
)}
<ThemeToggle /> <ThemeToggle />
<Button <Button
type="button" type="button"
@@ -0,0 +1,19 @@
import type { ReactNode } from "react"
/** 답변 자리(첫 토큰 전·재진입 대기·세션 생성 중). Message 의 assistant 모양과 똑같이 —
* AI 배지 + CODEASSIST 라벨, 본문은 상자 없이. "생각하는 중" 표시는 아래 WorkingRow 가 맡음. */
export function ThinkingBubble({ children }: { children?: ReactNode }) {
return (
<div className="flex flex-col items-start gap-1">
<div className="flex w-full items-center gap-1.5">
<span className="bg-primary text-primary-foreground grid size-4 place-items-center rounded text-[8px] leading-none font-semibold">
AI
</span>
<span className="text-muted-foreground font-mono text-[9.5px] tracking-widest uppercase">
CODEASSIST
</span>
</div>
<div className="text-foreground w-full text-sm leading-[1.9]">{children}</div>
</div>
)
}
@@ -0,0 +1,86 @@
import { useEffect, useState } from "react"
import { ChevronRight, Loader2, Wrench } from "lucide-react"
import type { AgentStep } from "@/lib/streaming"
/** 생각/도구 과정 토글 — ABAP_OPENCODE 의 ThinkingBox 를 그대로 옮김.
* 진행 중엔 펼쳐진 채 흐르고, 답변 본문이 나오기 시작하거나 끝나면 자동으로 접힘. */
export function ThinkingSteps({
steps,
isDone,
answerStarted,
}: {
steps: AgentStep[]
isDone: boolean
answerStarted: boolean
}) {
const collapsed = isDone || answerStarted
const [open, setOpen] = useState(!collapsed)
useEffect(() => {
if (collapsed) setOpen(false)
}, [collapsed])
if (steps.length === 0) return null
return (
<div className="flex flex-col gap-1.5">
<button
type="button"
onClick={() => setOpen((o) => !o)}
className="text-muted-foreground hover:text-foreground flex items-center gap-1.5 self-start text-[12.5px] font-semibold"
>
<ChevronRight
size={13}
strokeWidth={1.5}
className={`transition-transform ${open ? "rotate-90" : ""}`}
/>
<span className="text-[11.5px] font-normal">{steps.length} steps</span>
{!isDone && <Loader2 size={11} className="animate-spin" />}
</button>
{open &&
steps.map((st, i) => (
<div
key={st.id}
className="border-border ml-1.5 flex items-start gap-2.5 border-l-2 py-0.5 pl-3"
>
<span className="text-muted-foreground mt-px shrink-0 text-[11px] font-semibold whitespace-nowrap">
Step {i + 1}
</span>
{st.kind === "tool" ? (
<span className="bg-muted border-border text-foreground inline-flex items-center gap-1.5 rounded-md border px-2 py-0.5 text-xs font-semibold">
{st.status === "running" || st.status === "pending" ? (
<Loader2 size={12} className="animate-spin" />
) : (
<Wrench size={12} strokeWidth={1.5} />
)}
{st.tool || "tool"}
{st.title ? `${st.title}` : ""}
</span>
) : (
<div className="text-muted-foreground text-[12.5px] leading-[1.55] break-words whitespace-pre-wrap">
{st.text}
</div>
)}
</div>
))}
</div>
)
}
/** 하단 상태줄 — 스피너 + 경과 초. 답변 글자 오기 전엔 "생각하는 중", 오기 시작하면 "작성 중". */
export function WorkingRow({ busy, label = "작성 중…" }: { busy: boolean; label?: string }) {
const [elapsed, setElapsed] = useState(0)
useEffect(() => {
if (!busy) return
setElapsed(0)
const start = Date.now()
const t = setInterval(() => setElapsed(Math.floor((Date.now() - start) / 1000)), 1000)
return () => clearInterval(t)
}, [busy])
if (!busy) return null
return (
<div className="text-muted-foreground flex items-center gap-2 text-[12.5px]">
<Loader2 size={14} className="animate-spin" />
{label} · {elapsed}
</div>
)
}
@@ -3,6 +3,7 @@ import { toast } from "sonner"
import { useQueryClient, type QueryClient } from "@tanstack/react-query" import { useQueryClient, type QueryClient } from "@tanstack/react-query"
import { useSnapChatStore } from "../store/snapChatStore" import { useSnapChatStore } from "../store/snapChatStore"
import { snapStream, cancelStream } from "../api/snap.stream" import { snapStream, cancelStream } from "../api/snap.stream"
import { notifyChatDone } from "@/lib/bridge/webviewBridge"
import type { SnapImageInput, SnapSessionDetail } from "../contract/types" import type { SnapImageInput, SnapSessionDetail } from "../contract/types"
// title 이벤트 → 상세 캐시는 즉시 패치(헤더 제목 실시간 반영), 목록은 invalidate. // title 이벤트 → 상세 캐시는 즉시 패치(헤더 제목 실시간 반영), 목록은 invalidate.
@@ -38,12 +39,18 @@ export function useSnapChat(sessionId: string) {
}, },
{ {
onToken: (d) => useSnapChatStore.getState().appendChunk(d), onToken: (d) => useSnapChatStore.getState().appendChunk(d),
onStep: (st) => useSnapChatStore.getState().applyStep(st),
// done 시점엔 백엔드가 이미 답변을 DB 에 저장함(streaming.py: persist→usage→done). // done 시점엔 백엔드가 이미 답변을 DB 에 저장함(streaming.py: persist→usage→done).
// detail 캐시를 무효화해 재진입 시 stale 스냅샷 대신 완성본을 받게 함. // detail 캐시를 무효화해 재진입 시 stale 스냅샷 대신 완성본을 받게 함.
onDone: () => onDone: () => {
void queryClient.invalidateQueries({ void queryClient.invalidateQueries({ queryKey: ["snap", "session", sessionId] })
queryKey: ["snap", "session", sessionId], // 창 안 보고 있으면 데스크톱 알림(토스트+트레이 점). 제목은 캐시에 있으면 그걸로.
}), const detail = queryClient.getQueryData<{
title?: string | null
titleLlm?: string | null
}>(["snap", "session", sessionId])
notifyChatDone(detail?.titleLlm ?? detail?.title ?? undefined)
},
onTitle: (title) => patchSessionTitle(queryClient, sessionId, title), onTitle: (title) => patchSessionTitle(queryClient, sessionId, title),
onUsage: (u) => onUsage: (u) =>
useSnapChatStore.getState().applyUsage({ useSnapChatStore.getState().applyUsage({
@@ -0,0 +1,55 @@
import { describe, expect, it, vi, beforeEach } from "vitest"
import { act, fireEvent, render, screen } from "@testing-library/react"
import { MemoryRouter, Route, Routes } from "react-router-dom"
import NewChatPage from "./NewChatPage"
// 전송 즉시 헤로 대신 내 말풍선+시머 — 세션 생성이 느려도 "넘어간" 느낌. 실패하면 헤로로 복귀.
// SnippetPalettePage.test 와 같이 훅을 통째 mock — mutate 콜백을 테스트가 직접 쥠.
const mutate = vi.fn()
vi.mock("../api/snap.api", () => ({ useCreateSession: () => ({ mutate, isPending: false }) }))
vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }))
type Cb = { onSuccess: (s: { id: string }) => void; onError: () => void }
const lastCallbacks = () => mutate.mock.calls.at(-1)?.[1] as Cb
function mount() {
return render(
<MemoryRouter initialEntries={["/snap/new"]}>
<Routes>
<Route path="/snap/new" element={<NewChatPage />} />
<Route path="/snap/s/:id" element={<div>-</div>} />
</Routes>
</MemoryRouter>
)
}
describe("NewChatPage 전송", () => {
beforeEach(() => mutate.mockReset())
it("전송하면 세션 생성 중에도 내 질문과 '생각하는 중'이 보이고, 끝나면 세션 화면으로 간다", async () => {
mount()
fireEvent.click(screen.getByText("MARA 에서 자재번호로 자재유형(MTART) 읽는 SELECT SINGLE"))
expect(mutate).toHaveBeenCalledOnce()
expect(await screen.findByText(/생각하는 중…/)).toBeTruthy()
expect(screen.getByText("MARA 에서 자재번호로 자재유형(MTART) 읽는 SELECT SINGLE")).toBeTruthy()
expect(screen.queryByText("무엇을 도와드릴까요?")).toBeNull()
act(() => lastCallbacks().onSuccess({ id: "ses_new" }))
expect(await screen.findByText("세션화면-테스트")).toBeTruthy()
})
it("세션 생성 실패면 헤로로 돌아온다", async () => {
mount()
fireEvent.click(screen.getByText("내부 테이블 LOOP 에서 그룹 소계 구하는 관용구"))
expect(await screen.findByText(/생각하는 중…/)).toBeTruthy()
act(() => lastCallbacks().onError())
expect(await screen.findByText("무엇을 도와드릴까요?")).toBeTruthy()
expect(screen.queryByText(/생각하는 중…/)).toBeNull()
})
it("생성 중엔 두 번째 전송을 무시한다", () => {
mount()
fireEvent.click(screen.getByText("MARA 에서 자재번호로 자재유형(MTART) 읽는 SELECT SINGLE"))
// 헤로가 사라져 버튼은 없지만, Composer 의 onSend 경로도 pending 가드로 막힘 — mutate 는 1회
expect(mutate).toHaveBeenCalledTimes(1)
})
})
@@ -2,10 +2,14 @@ import { useState } from "react"
import { useNavigate } from "react-router-dom" import { useNavigate } from "react-router-dom"
import { ChevronLeft } from "lucide-react" import { ChevronLeft } from "lucide-react"
import { PATHS } from "@/config/routes" import { PATHS } from "@/config/routes"
import { toast } from "sonner"
import { Kbd } from "@/shared/components/Kbd" import { Kbd } from "@/shared/components/Kbd"
import { useCreateSession } from "../api/snap.api" import { useCreateSession } from "../api/snap.api"
import { Hero } from "../components/Hero" import { Hero } from "../components/Hero"
import { Composer } from "../components/Composer" import { Composer } from "../components/Composer"
import { Message } from "../components/Message"
import { ThinkingBubble } from "../components/ThinkingBubble"
import { WorkingRow } from "../components/ThinkingSteps"
import { useEscapeKey } from "../hooks/useEscapeKey" import { useEscapeKey } from "../hooks/useEscapeKey"
import type { SnapImageInput } from "../contract/types" import type { SnapImageInput } from "../contract/types"
@@ -13,17 +17,26 @@ import type { SnapImageInput } from "../contract/types"
export default function NewChatPage() { export default function NewChatPage() {
const navigate = useNavigate() const navigate = useNavigate()
const createSession = useCreateSession() const createSession = useCreateSession()
const [pending, setPending] = useState(false) // 전송 누른 순간의 질문 — 세션 생성(OpenCode 왕복) 동안 헤로 대신 말풍선+시머를 보여 "넘어간" 느낌을 줌
const [pending, setPending] = useState<string | null>(null)
// 단계적 Esc: 새 대화 화면에선 목록으로. // 단계적 Esc: 새 대화 화면에선 목록으로.
useEscapeKey(() => navigate(PATHS.SNAP)) useEscapeKey(() => navigate(PATHS.SNAP))
// 첫 전송: 세션 생성 → 채팅 페이지로 이동하며 firstMessage 전달(거기서 스트림). // 첫 전송: 세션 생성 → 채팅 페이지로 이동하며 firstMessage 전달(거기서 스트림).
const start = async (text: string, images: SnapImageInput[]) => { // mutate + 콜백(SnapUserControls 의 logout 과 같은 패턴) — mutateAsync 는 거부가 밖으로 새서 안 씀.
if (pending) return const start = (text: string, images: SnapImageInput[]) => {
setPending(true) if (pending !== null) return
const session = await createSession.mutateAsync() setPending(text.trim() || (images.length ? `이미지 ${images.length}` : "…"))
navigate(`/snap/s/${session.id}`, { state: { firstMessage: text, firstImages: images } }) createSession.mutate(undefined, {
onSuccess: (session) =>
navigate(`/snap/s/${session.id}`, { state: { firstMessage: text, firstImages: images } }),
onError: () => {
// 세션 생성 실패(OpenCode 죽음 등) — 헤로로 되돌리고 알림. 안 풀면 "응답 중" 에 영원히 갇힘.
setPending(null)
toast.error("대화를 시작하지 못했어. 서버 상태를 확인하고 다시 보내봐.")
},
})
} }
return ( return (
@@ -39,14 +52,24 @@ export default function NewChatPage() {
<Kbd>Esc</Kbd> <Kbd>Esc</Kbd>
</button> </button>
</div> </div>
{pending === null ? (
<div className="grid min-h-0 flex-1 place-items-center overflow-y-auto px-5"> <div className="grid min-h-0 flex-1 place-items-center overflow-y-auto px-5">
<Hero onPick={(text) => void start(text, [])} disabled={pending} /> <Hero onPick={(text) => start(text, [])} disabled={false} />
</div> </div>
) : (
// 세션 만드는 동안 — SessionChatPage 첫 화면과 같은 모양(내 말풍선 + 생각 중)
<div className="mx-auto flex min-h-0 w-full max-w-[760px] flex-1 flex-col gap-4 overflow-y-auto px-5 py-4">
{/* eslint-disable-next-line jsx-a11y/aria-role -- Message 의 role 은 ARIA 아니고 화자 */}
<Message role="user" content={pending} />
<ThinkingBubble />
<WorkingRow busy label="생각하는 중…" />
</div>
)}
<Composer <Composer
onSend={start} onSend={start}
busy={pending} busy={pending !== null}
placeholder="질문을 입력하거나 코드·에러 로그를 붙여넣어봐…" placeholder="질문을 입력하거나 코드·에러 로그를 붙여넣어봐…"
acceptCapture capturePath={PATHS.SNAP_NEW}
/> />
</div> </div>
) )
@@ -0,0 +1,55 @@
import { describe, expect, it, vi, beforeEach } from "vitest"
import { act, fireEvent, render } from "@testing-library/react"
import { MemoryRouter, Route, Routes } from "react-router-dom"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import SessionChatPage from "./SessionChatPage"
import { useSnapChatStore } from "../store/snapChatStore"
import * as stream from "../api/snap.stream"
// Esc 는 답변 생성 중이면 중단, 아니면 목록으로 — 클로드처럼.
// NavRail 안 ClipboardHistory 가 IndexedDB 를 써서(jsdom 없음) 레일은 비움.
vi.mock("../components/NavRail", () => ({ NavRail: () => null }))
vi.mock("../api/snap.stream", async (orig) => ({
...(await orig<typeof stream>()),
cancelStream: vi.fn().mockResolvedValue(undefined),
snapStream: vi.fn().mockResolvedValue(undefined),
}))
function mount() {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={qc}>
<MemoryRouter initialEntries={["/snap/s/s1"]}>
<Routes>
<Route path="/snap/s/:id" element={<SessionChatPage />} />
<Route path="/snap" element={<div>-</div>} />
</Routes>
</MemoryRouter>
</QueryClientProvider>
)
}
describe("SessionChatPage Esc", () => {
beforeEach(() => {
useSnapChatStore.getState().reset()
vi.mocked(stream.cancelStream).mockClear()
})
it("스트리밍 중 Esc 는 중단(cancelStream)하고 화면에 남는다", () => {
const { queryByText } = mount()
act(() => {
useSnapChatStore.getState().setStreaming(true)
})
fireEvent.keyDown(window, { key: "Escape" })
expect(vi.mocked(stream.cancelStream)).toHaveBeenCalledWith("s1")
expect(useSnapChatStore.getState().isStreaming).toBe(false)
expect(queryByText("목록화면-테스트")).toBeNull()
})
it("답변 중이 아니면 Esc 는 목록으로 간다", () => {
const { getByText } = mount()
fireEvent.keyDown(window, { key: "Escape" })
expect(vi.mocked(stream.cancelStream)).not.toHaveBeenCalled()
expect(getByText("목록화면-테스트")).toBeTruthy()
})
})
@@ -11,6 +11,8 @@ import type { SnapImageInput, SnapSession } from "../contract/types"
import { ChatHeader } from "../components/ChatHeader" import { ChatHeader } from "../components/ChatHeader"
import { NavRail } from "../components/NavRail" import { NavRail } from "../components/NavRail"
import { Message } from "../components/Message" import { Message } from "../components/Message"
import { ThinkingBubble } from "../components/ThinkingBubble"
import { ThinkingSteps, WorkingRow } from "../components/ThinkingSteps"
import { Composer } from "../components/Composer" import { Composer } from "../components/Composer"
export default function SessionChatPage() { export default function SessionChatPage() {
@@ -22,9 +24,6 @@ export default function SessionChatPage() {
const [navBlocks, setNavBlocks] = useState<{ index: number; lang: string }[]>([]) const [navBlocks, setNavBlocks] = useState<{ index: number; lang: string }[]>([])
const scrollRef = useRef<HTMLDivElement>(null) const scrollRef = useRef<HTMLDivElement>(null)
// 단계적 Esc: 대화창에선 목록/검색 화면으로(창은 목록에서 Esc 로 숨김).
useEscapeKey(() => navigate(PATHS.SNAP))
const { messages, isStreaming, isRevealing } = useSnapChatStore( const { messages, isStreaming, isRevealing } = useSnapChatStore(
useShallow((s) => ({ useShallow((s) => ({
messages: s.messages, messages: s.messages,
@@ -37,6 +36,13 @@ export default function SessionChatPage() {
// 시머로 "생각 중" 표시 + 전송 잠금(보내면 어차피 409). 폴링이 완성본을 곧 가져옴. // 시머로 "생각 중" 표시 + 전송 잠금(보내면 어차피 409). 폴링이 완성본을 곧 가져옴.
const generatingRemotely = !busy && !!detail?.isGenerating && messages.at(-1)?.role === "user" const generatingRemotely = !busy && !!detail?.isGenerating && messages.at(-1)?.role === "user"
// 단계적 Esc: 답변 생성 중이면 중단(클로드처럼), 아니면 목록/검색 화면으로(창은 목록에서 Esc 로 숨김).
// 재진입해서 서버만 생성 중(generatingRemotely)일 때도 Esc 가 백엔드 취소를 보냄.
useEscapeKey(() => {
if (busy || generatingRemotely) stop()
else navigate(PATHS.SNAP)
})
// 세션 진입: 과거대화 seed. NewChatPage 에서 넘어온 firstMessage 있으면 seed 없이 바로 전송. // 세션 진입: 과거대화 seed. NewChatPage 에서 넘어온 firstMessage 있으면 seed 없이 바로 전송.
const firstRequest = location.state as { const firstRequest = location.state as {
firstMessage?: string firstMessage?: string
@@ -159,16 +165,16 @@ export default function SessionChatPage() {
const isLiveLast = const isLiveLast =
busy && i === messages.length - 1 && m.role === "assistant" && !m.frozen busy && i === messages.length - 1 && m.role === "assistant" && !m.frozen
if (isLiveLast) { if (isLiveLast) {
const steps = m.steps ?? []
return ( return (
<div key={m.id} className="flex flex-col items-start gap-1"> <div key={m.id} className="flex flex-col gap-2">
<span className="text-muted-foreground font-mono text-[9.5px] tracking-widest uppercase"> <ThinkingBubble>
CODEASSIST <ThinkingSteps
</span> steps={steps}
<div className="border-border bg-card text-card-foreground w-full rounded-lg border px-3 py-2 text-sm leading-[1.9]"> isDone={!isStreaming}
{m.content === "" ? ( answerStarted={m.content !== ""}
// 첫 토큰 오기 전 빈 시간 메움 — 시머 텍스트로 "생각 중" 신호 />
<span className="shimmer-text text-sm"> </span> {m.content !== "" && (
) : (
<StreamingText <StreamingText
text={m.content} text={m.content}
isStreaming={isStreaming} isStreaming={isStreaming}
@@ -176,7 +182,11 @@ export default function SessionChatPage() {
onRevealEnd={() => useSnapChatStore.getState().setRevealing(false)} onRevealEnd={() => useSnapChatStore.getState().setRevealing(false)}
/> />
)} )}
</div> </ThinkingBubble>
<WorkingRow
busy={isStreaming}
label={m.content === "" ? "생각하는 중…" : "작성 중…"}
/>
</div> </div>
) )
} }
@@ -194,23 +204,23 @@ export default function SessionChatPage() {
) )
} }
return ( return (
<div key={m.id} className="flex flex-col gap-2">
{m.steps && m.steps.length > 0 && (
<ThinkingSteps steps={m.steps} isDone answerStarted />
)}
<Message <Message
key={m.id}
role={m.role} role={m.role}
content={m.content} content={m.content}
totalTokens={m.totalTokens} totalTokens={m.totalTokens}
elapsedMs={m.elapsedMs} elapsedMs={m.elapsedMs}
/> />
</div>
) )
})} })}
{generatingRemotely && ( {generatingRemotely && (
<div className="flex flex-col items-start gap-1"> <div className="flex flex-col gap-2">
<span className="text-muted-foreground font-mono text-[9.5px] tracking-widest uppercase"> <ThinkingBubble />
CODEASSIST <WorkingRow busy label="생각하는 중…" />
</span>
<div className="border-border bg-card text-card-foreground w-full rounded-lg border px-3 py-2 text-sm leading-[1.9]">
<span className="shimmer-text text-sm"> </span>
</div>
</div> </div>
)} )}
</div> </div>
@@ -223,6 +233,7 @@ export default function SessionChatPage() {
busy={busy || generatingRemotely} busy={busy || generatingRemotely}
onStop={stop} onStop={stop}
placeholder="ABAP · CDS · 에러 로그를 붙여넣거나 질문하세요…" placeholder="ABAP · CDS · 에러 로그를 붙여넣거나 질문하세요…"
capturePath={`/snap/s/${id}`}
/> />
</div> </div>
</div> </div>
@@ -151,3 +151,23 @@ describe("snapChatStore", () => {
expect(useSnapChatStore.getState().isRevealing).toBe(false) expect(useSnapChatStore.getState().isRevealing).toBe(false)
}) })
}) })
describe("applyStep", () => {
it("reasoning 은 같은 id 로 이어붙고 tool 은 상태 덮어씀, assistant 꼬리에만", () => {
const st = useSnapChatStore.getState()
st.reset()
st.addUserMessage("q")
st.applyStep({ id: "r1", kind: "reasoning", text: "x" }) // user 꼬리 → 무시
st.startAssistantMessage()
st.applyStep({ id: "r1", kind: "reasoning", text: "생각" })
st.applyStep({ id: "r1", kind: "reasoning", text: "중" })
st.applyStep({ id: "t1", kind: "tool", tool: "read", status: "running" })
st.applyStep({ id: "t1", kind: "tool", tool: "read", status: "completed", title: "a.abap" })
const last = useSnapChatStore.getState().messages.at(-1)!
expect(last.steps).toEqual([
{ id: "r1", kind: "reasoning", text: "생각중" },
{ id: "t1", kind: "tool", tool: "read", status: "completed", title: "a.abap" },
])
expect(useSnapChatStore.getState().messages[0].steps).toBeUndefined()
})
})
@@ -1,6 +1,7 @@
import { create } from "zustand" import { create } from "zustand"
import { randomId } from "@/lib/utils/randomId" import { randomId } from "@/lib/utils/randomId"
import type { SnapMessage, SnapRole } from "../contract/types" import type { SnapMessage, SnapRole } from "../contract/types"
import type { AgentStep } from "@/lib/streaming"
export interface SnapChatMessage { export interface SnapChatMessage {
id: string id: string
@@ -14,6 +15,8 @@ export interface SnapChatMessage {
totalTokens?: number totalTokens?: number
/** 이 답변 소요시간(ms). 라이브는 SSE, 과거는 DB. user 는 없음. */ /** 이 답변 소요시간(ms). 라이브는 SSE, 과거는 DB. user 는 없음. */
elapsedMs?: number elapsedMs?: number
/** 답변 전 과정(생각·도구). 라이브 턴에만 쌓임 — DB 엔 안 남아 재진입 땐 없음. */
steps?: AgentStep[]
} }
// 세션 컨텍스트 하드 한도 — 백엔드 settings.llm_context_limit 와 동기(reload 시 기본값). // 세션 컨텍스트 하드 한도 — 백엔드 settings.llm_context_limit 와 동기(reload 시 기본값).
@@ -45,6 +48,8 @@ interface SnapChatState {
/** 폴링 복구로 도착한 완성 답변을 꼬리에 붙이고 타자기 reveal 시작. */ /** 폴링 복구로 도착한 완성 답변을 꼬리에 붙이고 타자기 reveal 시작. */
appendRecoveredAssistant: (m: SnapMessage) => void appendRecoveredAssistant: (m: SnapMessage) => void
appendChunk: (chunk: string) => void appendChunk: (chunk: string) => void
/** step 이벤트 — 같은 id 면 reasoning 은 text 이어붙이고 tool 은 상태 덮어씀. */
applyStep: (step: AgentStep) => void
setStreaming: (v: boolean) => void setStreaming: (v: boolean) => void
setRevealing: (v: boolean) => void setRevealing: (v: boolean) => void
setController: (c: AbortController | null) => void setController: (c: AbortController | null) => void
@@ -123,6 +128,21 @@ export const useSnapChatStore = create<SnapChatState>((set, get) => ({
return { messages: next } return { messages: next }
}) })
}, },
applyStep: (step) => {
const last = get().messages.at(-1)
if (!last || last.role !== "assistant") return
const steps = [...(last.steps ?? [])]
const i = steps.findIndex((x) => x.id === step.id)
if (i < 0) steps.push(step)
else if (step.kind === "reasoning")
steps[i] = { ...steps[i], text: (steps[i].text ?? "") + (step.text ?? "") }
else steps[i] = { ...steps[i], ...step }
set((s) => {
const next = [...s.messages]
next[next.length - 1] = { ...last, steps }
return { messages: next }
})
},
setStreaming: (v) => set({ isStreaming: v }), setStreaming: (v) => set({ isStreaming: v }),
setRevealing: (v) => set({ isRevealing: v }), setRevealing: (v) => set({ isRevealing: v }),
setController: (c) => set({ currentController: c }), setController: (c) => set({ currentController: c }),
@@ -1,76 +1,59 @@
import { afterEach, describe, expect, it } from "vitest" import { afterEach, describe, expect, it } from "vitest"
import { clearMocks, mockIPC } from "@tauri-apps/api/mocks" import MockAdapter from "axios-mock-adapter"
import { apiClient } from "@/lib/api/client"
import { snippetsApi } from "./snippets.api" import { snippetsApi } from "./snippets.api"
describe("snippetsApi", () => { // memos.api.test 와 같은 axios-mock-adapter 방식. envelope 은 client 가 data 로 풀어줌.
afterEach(() => clearMocks()) const mock = new MockAdapter(apiClient)
const ok = (data: unknown) => [200, { success: true, statusCode: 200, data, errors: [] }] as const
it("list — snippets_list 응답을 Snippet[]로 돌려준다", async () => { describe("snippetsApi (server)", () => {
afterEach(() => mock.reset())
it("list", async () => {
const data = [{ name: "A", desc: "", body: "b", category: "코드", usageCount: 0, lastUsed: 0 }] const data = [{ name: "A", desc: "", body: "b", category: "코드", usageCount: 0, lastUsed: 0 }]
mockIPC((command) => { mock.onGet("/snippets").reply(() => [...ok(data)])
expect(command).toBe("snippets_list")
return data
})
await expect(snippetsApi.list()).resolves.toEqual(data) await expect(snippetsApi.list()).resolves.toEqual(data)
}) })
it("recordUse — snippets_record_use에 name을 넘긴다", async () => { it("create/update/remove/recordUse 가 맞는 경로·본문으로 간다", async () => {
const data = { name: "FOO", usageCount: 3, lastUsed: 123 } const input = { name: "FOO BAR", desc: "d", body: "b", category: "코드" }
mockIPC((command, payload) => { mock
expect(command).toBe("snippets_record_use") .onPost("/snippets", input)
expect(payload).toEqual({ name: "FOO" }) .reply(() => [
return data 201,
{ success: true, statusCode: 201, data: { ...input, usageCount: 0, lastUsed: 0 } },
])
mock
.onPut("/snippets/FOO%20BAR", input)
.reply(() => [...ok({ ...input, usageCount: 1, lastUsed: 5 })])
mock.onDelete("/snippets/FOO%20BAR").reply(() => [...ok({ name: "FOO BAR" })])
mock
.onPost("/snippets/FOO%20BAR/use")
.reply(() => [...ok({ name: "FOO BAR", usageCount: 2, lastUsed: 9 })])
await expect(snippetsApi.create(input)).resolves.toMatchObject({ name: "FOO BAR" })
await expect(snippetsApi.update(input)).resolves.toMatchObject({ usageCount: 1 })
await expect(snippetsApi.remove("FOO BAR")).resolves.toBeUndefined()
await expect(snippetsApi.recordUse("FOO BAR")).resolves.toEqual({
name: "FOO BAR",
usageCount: 2,
lastUsed: 9,
})
}) })
await expect(snippetsApi.recordUse("FOO")).resolves.toEqual(data) it("서버 오류 message 가 Error 로 온다(훅이 그대로 토스트)", async () => {
mock
.onPost("/snippets")
.reply(409, {
success: false,
statusCode: 409,
code: "CONFLICT",
message: "이미 있는 이름임: A",
errors: [],
}) })
it("command 오류를 Error로 reject한다", async () => {
mockIPC(() => Promise.reject("디비 오류"))
await expect(snippetsApi.list()).rejects.toThrow("디비 오류")
})
it("create — snippets_create에 snippet을 넘기고 저장 결과를 돌려준다", async () => {
const input = { name: "FOO", desc: "d", body: "b", category: "코드" }
const data = { ...input, usageCount: 0, lastUsed: 0 }
mockIPC((command, payload) => {
expect(command).toBe("snippets_create")
expect(payload).toEqual({ snippet: input })
return data
})
await expect(snippetsApi.create(input)).resolves.toEqual(data)
})
it("create — 중복 이름 오류를 그대로 reject한다", async () => {
mockIPC(() => Promise.reject("이미 있는 이름임: FOO"))
await expect( await expect(
snippetsApi.create({ name: "FOO", desc: "", body: "b", category: "코드" }) snippetsApi.create({ name: "A", desc: "", body: "b", category: "" })
).rejects.toThrow("이미 있는 이름임: FOO") ).rejects.toThrow("이미 있는 이름임: A")
})
it("update — snippets_update에 snippet을 넘기고 갱신 결과를 돌려준다", async () => {
const input = { name: "FOO", desc: "새 설명", body: "새 본문", category: "기타" }
const data = { ...input, usageCount: 2, lastUsed: 100 }
mockIPC((command, payload) => {
expect(command).toBe("snippets_update")
expect(payload).toEqual({ snippet: input })
return data
})
await expect(snippetsApi.update(input)).resolves.toEqual(data)
})
it("remove — snippets_delete에 name을 넘기고 성공하면 undefined를 돌려준다", async () => {
mockIPC((command, payload) => {
expect(command).toBe("snippets_delete")
expect(payload).toEqual({ name: "FOO" })
return { name: "FOO" }
})
await expect(snippetsApi.remove("FOO")).resolves.toBeUndefined()
}) })
}) })
@@ -1,15 +1,18 @@
// feature 유일한 데이터 진입점(contracts/snippet-data-interface.md). 뒤는 브릿지(SQLite) — @/lib/api/client 안 씀(정당 편차). // feature 유일한 데이터 진입점. 2026-09-21 부터 서버(공용 PostgreSQL) — 로컬 SQLite 브릿지 안 씀.
import { request } from "@/lib/bridge/snippetBridge" // 서버 5개 엔드포인트는 옛 브릿지 5개와 1:1 (apps/snippets/views.py).
import { apiDelete, apiGet, apiPost, apiPut } from "@/lib/api/client"
import type { Snippet, SnippetInput } from "../types" import type { Snippet, SnippetInput } from "../types"
export const snippetsApi = { export const snippetsApi = {
list: () => request<Snippet[]>("snippets.list"), list: () => apiGet<Snippet[]>("/snippets"),
create: (input: SnippetInput) => request<Snippet>("snippets.create", { snippet: input }), create: (input: SnippetInput) => apiPost<Snippet>("/snippets", input),
update: (input: SnippetInput) => request<Snippet>("snippets.update", { snippet: input }), update: (input: SnippetInput) =>
apiPut<Snippet>(`/snippets/${encodeURIComponent(input.name)}`, input),
remove: (name: string) => remove: (name: string) =>
request<{ name: string }>("snippets.delete", { name }).then(() => undefined), apiDelete(`/snippets/${encodeURIComponent(name)}`).then(() => undefined),
recordUse: (name: string) => recordUse: (name: string) =>
request<{ name: string; usageCount: number; lastUsed: number }>("snippets.recordUse", { apiPost<{ name: string; usageCount: number; lastUsed: number }>(
name, `/snippets/${encodeURIComponent(name)}/use`,
}), {}
),
} }
@@ -1,3 +1,4 @@
import { MemoryRouter } from "react-router-dom"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import userEvent from "@testing-library/user-event" import userEvent from "@testing-library/user-event"
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react" import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"
@@ -67,7 +68,11 @@ afterEach(() => {
describe("새 스니펫 단축키", () => { describe("새 스니펫 단축키", () => {
it("Ctrl+N으로 생성창을 열고 기존 Ctrl+2는 무시함", () => { it("Ctrl+N으로 생성창을 열고 기존 Ctrl+2는 무시함", () => {
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
fireEvent.keyDown(window, { key: "2", ctrlKey: true }) fireEvent.keyDown(window, { key: "2", ctrlKey: true })
expect(screen.queryByRole("dialog")).not.toBeInTheDocument() expect(screen.queryByRole("dialog")).not.toBeInTheDocument()
@@ -79,7 +84,11 @@ describe("새 스니펫 단축키", () => {
it("생성 성공 뒤 입력창을 1초 유지한 다음 기본 검색 화면으로 돌아감", () => { it("생성 성공 뒤 입력창을 1초 유지한 다음 기본 검색 화면으로 돌아감", () => {
vi.useFakeTimers() vi.useFakeTimers()
createSnippet.mockImplementation((_input, options) => options.onSuccess()) createSnippet.mockImplementation((_input, options) => options.onSuccess())
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
const search = screen.getByRole("textbox") const search = screen.getByRole("textbox")
fireEvent.change(search, { target: { value: "기존 검색" } }) fireEvent.change(search, { target: { value: "기존 검색" } })
fireEvent.keyDown(window, { key: "n", ctrlKey: true }) fireEvent.keyDown(window, { key: "n", ctrlKey: true })
@@ -104,7 +113,11 @@ describe("스니펫 Enter 복사", () => {
}) })
) )
vi.spyOn(navigator.clipboard, "writeText").mockImplementation(writeText) vi.spyOn(navigator.clipboard, "writeText").mockImplementation(writeText)
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
fireEvent.change(screen.getByRole("textbox"), { target: { value: "B" } }) fireEvent.change(screen.getByRole("textbox"), { target: { value: "B" } })
fireEvent.click(screen.getByText("B")) fireEvent.click(screen.getByText("B"))
fireEvent.keyDown(window, { key: "Enter" }) fireEvent.keyDown(window, { key: "Enter" })
@@ -122,7 +135,11 @@ describe("스니펫 Enter 복사", () => {
it("복사 실패 시 창과 사용 기록을 유지하고 오류 표시", async () => { it("복사 실패 시 창과 사용 기록을 유지하고 오류 표시", async () => {
const writeText = vi.fn().mockRejectedValue(new Error("denied")) const writeText = vi.fn().mockRejectedValue(new Error("denied"))
vi.spyOn(navigator.clipboard, "writeText").mockImplementation(writeText) vi.spyOn(navigator.clipboard, "writeText").mockImplementation(writeText)
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
fireEvent.change(screen.getByRole("textbox"), { target: { value: "A" } }) fireEvent.change(screen.getByRole("textbox"), { target: { value: "A" } })
fireEvent.keyDown(window, { key: "ArrowDown" }) fireEvent.keyDown(window, { key: "ArrowDown" })
fireEvent.keyDown(window, { key: "Enter", isComposing: true }) fireEvent.keyDown(window, { key: "Enter", isComposing: true })
@@ -136,7 +153,11 @@ describe("스니펫 Enter 복사", () => {
it("하단 복사는 클릭과 Enter 모두 원문을 복사하고 팔레트를 열린 채로 둠", async () => { it("하단 복사는 클릭과 Enter 모두 원문을 복사하고 팔레트를 열린 채로 둠", async () => {
const user = userEvent.setup() const user = userEvent.setup()
const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue() const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue()
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
fireEvent.change(screen.getByRole("textbox"), { target: { value: "B" } }) fireEvent.change(screen.getByRole("textbox"), { target: { value: "B" } })
await user.click(screen.getByRole("button", { name: "B" })) await user.click(screen.getByRole("button", { name: "B" }))
const copy = screen.getByRole("button", { name: "복사" }) const copy = screen.getByRole("button", { name: "복사" })
@@ -154,7 +175,11 @@ describe("Ctrl Enter 앱에 붙여넣기", () => {
it("선택한 원문을 붙여넣고 일반 복사를 실행하지 않으며 키 반복을 무시함", async () => { it("선택한 원문을 붙여넣고 일반 복사를 실행하지 않으며 키 반복을 무시함", async () => {
const user = userEvent.setup() const user = userEvent.setup()
const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue() const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue()
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
await user.type(screen.getByRole("textbox"), "B") await user.type(screen.getByRole("textbox"), "B")
await user.click(screen.getByRole("button", { name: "B" })) await user.click(screen.getByRole("button", { name: "B" }))
fireEvent.keyDown(screen.getByRole("textbox"), { key: "Enter", ctrlKey: true }) fireEvent.keyDown(screen.getByRole("textbox"), { key: "Enter", ctrlKey: true })
@@ -169,7 +194,11 @@ describe("Ctrl Enter 앱에 붙여넣기", () => {
it("복사 버튼에 포커스가 있어도 Ctrl Enter는 붙여넣고 일반 Enter는 복사함", async () => { it("복사 버튼에 포커스가 있어도 Ctrl Enter는 붙여넣고 일반 Enter는 복사함", async () => {
const user = userEvent.setup() const user = userEvent.setup()
const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue() const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue()
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
await user.type(screen.getByRole("textbox"), "B") await user.type(screen.getByRole("textbox"), "B")
await user.click(screen.getByRole("button", { name: "B" })) await user.click(screen.getByRole("button", { name: "B" }))
screen.getByRole("button", { name: "복사" }).focus() screen.getByRole("button", { name: "복사" }).focus()
@@ -188,7 +217,11 @@ describe("Ctrl Enter 앱에 붙여넣기", () => {
it("미선택·조합 중·다른 modifier·편집 중에는 붙여넣지 않음", () => { it("미선택·조합 중·다른 modifier·편집 중에는 붙여넣지 않음", () => {
const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue() const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue()
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
const input = screen.getByRole("textbox") const input = screen.getByRole("textbox")
fireEvent.change(input, { target: { value: "B" } }) fireEvent.change(input, { target: { value: "B" } })
fireEvent.keyDown(input, { key: "Enter", ctrlKey: true }) fireEvent.keyDown(input, { key: "Enter", ctrlKey: true })
@@ -208,7 +241,11 @@ describe("Ctrl Enter 앱에 붙여넣기", () => {
it("브라우저의 Ctrl Enter는 복사나 붙여넣기로 바뀌지 않음", () => { it("브라우저의 Ctrl Enter는 복사나 붙여넣기로 바뀌지 않음", () => {
vi.mocked(isWebView).mockReturnValue(false) vi.mocked(isWebView).mockReturnValue(false)
const writeText = vi.spyOn(navigator.clipboard, "writeText") const writeText = vi.spyOn(navigator.clipboard, "writeText")
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
const input = screen.getByRole("textbox") const input = screen.getByRole("textbox")
fireEvent.change(input, { target: { value: "B" } }) fireEvent.change(input, { target: { value: "B" } })
fireEvent.keyDown(input, { key: "ArrowDown" }) fireEvent.keyDown(input, { key: "ArrowDown" })
@@ -220,7 +257,11 @@ describe("Ctrl Enter 앱에 붙여넣기", () => {
describe("검색 후 선택할 때만 미리보기", () => { describe("검색 후 선택할 때만 미리보기", () => {
it("빈 검색 → 결과 → 직접 선택 → 검색 변경과 지우기 순서로 화면이 접힘", () => { it("빈 검색 → 결과 → 직접 선택 → 검색 변경과 지우기 순서로 화면이 접힘", () => {
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
const input = screen.getByRole("textbox") const input = screen.getByRole("textbox")
expect(screen.queryByText("A")).not.toBeInTheDocument() expect(screen.queryByText("A")).not.toBeInTheDocument()
expect(screen.queryByLabelText("코드 미리보기")).not.toBeInTheDocument() expect(screen.queryByLabelText("코드 미리보기")).not.toBeInTheDocument()
@@ -244,7 +285,11 @@ describe("검색 후 선택할 때만 미리보기", () => {
it("검색 결과만 보일 때 Enter는 복사하지 않고 재소환은 검색창으로 돌아감", () => { it("검색 결과만 보일 때 Enter는 복사하지 않고 재소환은 검색창으로 돌아감", () => {
const writeText = vi.spyOn(navigator.clipboard, "writeText") const writeText = vi.spyOn(navigator.clipboard, "writeText")
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
fireEvent.change(screen.getByRole("textbox"), { target: { value: "A" } }) fireEvent.change(screen.getByRole("textbox"), { target: { value: "A" } })
fireEvent.keyDown(window, { key: "Enter" }) fireEvent.keyDown(window, { key: "Enter" })
expect(writeText).not.toHaveBeenCalled() expect(writeText).not.toHaveBeenCalled()
@@ -259,7 +304,11 @@ describe("검색 후 선택할 때만 미리보기", () => {
it("마우스로 결과를 선택한 뒤 Esc를 누르면 검색창에서 바로 다시 입력할 수 있음", async () => { it("마우스로 결과를 선택한 뒤 Esc를 누르면 검색창에서 바로 다시 입력할 수 있음", async () => {
const user = userEvent.setup() const user = userEvent.setup()
render(<SnippetPalettePage />) render(
<MemoryRouter>
<SnippetPalettePage />
</MemoryRouter>
)
const input = screen.getByRole("textbox") const input = screen.getByRole("textbox")
await waitFor(() => expect(input).toHaveFocus()) await waitFor(() => expect(input).toHaveFocus())
await user.type(input, "A") await user.type(input, "A")
@@ -2,7 +2,10 @@ import { hostKind, send } from "@/lib/bridge/transport"
import { LogoMark } from "@/shared/components/LogoMark" import { LogoMark } from "@/shared/components/LogoMark"
// 검색 → 결과 → 직접 선택한 코드 순서로 화면과 데스크톱 창을 펼침. // 검색 → 결과 → 직접 선택한 코드 순서로 화면과 데스크톱 창을 펼침.
import { useEffect, useMemo, useRef, useState } from "react" import { useEffect, useMemo, useRef, useState } from "react"
import { Check, Search } from "lucide-react" import { useNavigate } from "react-router-dom"
import { Check, MessageSquare, Search } from "lucide-react"
import { PATHS } from "@/config/routes"
import { Kbd } from "@/shared/components/Kbd"
import { hideWindow, isWebView, pasteToApp, startWindowDrag } from "@/lib/bridge/webviewBridge" import { hideWindow, isWebView, pasteToApp, startWindowDrag } from "@/lib/bridge/webviewBridge"
import { toast } from "sonner" import { toast } from "sonner"
import { useEscapeKey } from "@/features/snap/hooks/useEscapeKey" import { useEscapeKey } from "@/features/snap/hooks/useEscapeKey"
@@ -25,6 +28,7 @@ import type { Snippet, SnippetInput } from "../types"
const ALL_CATEGORY = "전체" const ALL_CATEGORY = "전체"
export default function SnippetPalettePage() { export default function SnippetPalettePage() {
const navigate = useNavigate()
const [q, setQ] = useState("") const [q, setQ] = useState("")
const { data: snippets = [], isLoading, error } = useSnippets() const { data: snippets = [], isLoading, error } = useSnippets()
const recordUse = useRecordUse() const recordUse = useRecordUse()
@@ -307,6 +311,14 @@ export default function SnippetPalettePage() {
placeholder="스니펫 검색…" placeholder="스니펫 검색…"
className="placeholder:text-muted-foreground w-full bg-transparent text-base outline-none" className="placeholder:text-muted-foreground w-full bg-transparent text-base outline-none"
/> />
{/* 챗으로 전환 — 같은 창에서 route 만 바뀜(Ctrl+Alt+W 와 동일) */}
<button
type="button"
onClick={() => navigate(PATHS.SNAP)}
className="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring inline-flex h-7 flex-none items-center gap-1 rounded-md px-2 text-[11.5px] whitespace-nowrap transition-colors focus-visible:ring-2 focus-visible:outline-none"
>
<MessageSquare className="size-3.5" aria-hidden="true" /><Kbd>Ctrl+Alt+W</Kbd>
</button>
</div> </div>
{/* category 칩 바 — 2개 이상(전체 포함)일 때만 보여줌 */} {/* category 칩 바 — 2개 이상(전체 포함)일 때만 보여줌 */}
@@ -29,15 +29,20 @@ describe("bridgeNavigate", () => {
await emit("bridge", { type: "navigate", path: "/snippet" }) await emit("bridge", { type: "navigate", path: "/snippet" })
await emit("bridge", { type: "paste.target", name: "메모장", app: "notepad" }) await emit("bridge", { type: "paste.target", name: "메모장", app: "notepad" })
await emit("bridge", { type: "capture.image", dataUrl: "data:image/png;base64,abc" }) await emit("bridge", {
type: "capture.image",
path: "/snap/new",
dataUrl: "data:image/png;base64,abc",
})
expect(navigate).toHaveBeenCalledWith("/snippet") expect(navigate).toHaveBeenCalledWith("/snippet")
expect(onNavigate).toHaveBeenCalledTimes(1) expect(onNavigate).toHaveBeenCalledTimes(1)
expect(getLastPasteTarget()).toEqual({ name: "메모장", app: "notepad" }) expect(getLastPasteTarget()).toEqual({ name: "메모장", app: "notepad" })
expect(onPasteTarget).toHaveBeenCalledTimes(1) expect(onPasteTarget).toHaveBeenCalledTimes(1)
expect(onCapture).toHaveBeenCalledTimes(1) expect(onCapture).toHaveBeenCalledTimes(1)
expect(consumePendingCaptureImage()).toBe("data:image/png;base64,abc") expect(consumePendingCaptureImage("/snap/s/old")).toBe("")
expect(consumePendingCaptureImage()).toBe("") expect(consumePendingCaptureImage("/snap/new")).toBe("data:image/png;base64,abc")
expect(consumePendingCaptureImage("/snap/new")).toBe("")
window.removeEventListener("bridge:navigate", onNavigate) window.removeEventListener("bridge:navigate", onNavigate)
window.removeEventListener("bridge:pasteTarget", onPasteTarget) window.removeEventListener("bridge:pasteTarget", onPasteTarget)
+9 -10
View File
@@ -9,7 +9,7 @@ export interface PasteTarget {
let navigateFn: NavigateFn | null = null let navigateFn: NavigateFn | null = null
let lastPasteTarget: PasteTarget = { name: "", app: "" } let lastPasteTarget: PasteTarget = { name: "", app: "" }
let pendingCaptureImage = "" let pendingCaptureImage: { path: string; dataUrl: string } | null = null
/** 앱 루트에서 useNavigate() 감싼 콜백을 등록함. */ /** 앱 루트에서 useNavigate() 감싼 콜백을 등록함. */
export function setBridgeNavigate(fn: NavigateFn | null) { export function setBridgeNavigate(fn: NavigateFn | null) {
@@ -21,10 +21,11 @@ export function getLastPasteTarget(): PasteTarget {
return lastPasteTarget return lastPasteTarget
} }
/** 마지막 캡처 이미지를 한 번만 소비함. */ /** 지정한 대화에 도착한 마지막 캡처 이미지를 한 번만 소비함. */
export function consumePendingCaptureImage(): string { export function consumePendingCaptureImage(path: string): string {
const dataUrl = pendingCaptureImage if (pendingCaptureImage?.path !== path) return ""
pendingCaptureImage = "" const { dataUrl } = pendingCaptureImage
pendingCaptureImage = null
return dataUrl return dataUrl
} }
@@ -41,11 +42,9 @@ function handleBridgeMessage(data: {
return return
} }
if (data.type === "capture.image") { if (data.type === "capture.image" && data.path) {
pendingCaptureImage = data.dataUrl ?? "" pendingCaptureImage = { path: data.path, dataUrl: data.dataUrl ?? "" }
window.dispatchEvent( window.dispatchEvent(new CustomEvent("bridge:captureImage", { detail: pendingCaptureImage }))
new CustomEvent("bridge:captureImage", { detail: { dataUrl: pendingCaptureImage } })
)
return return
} }
@@ -14,5 +14,11 @@ export const pasteToApp = (text: string) => send({ type: "paste.code", text })
/** 현재 React route를 데스크톱 호스트에 알림. */ /** 현재 React route를 데스크톱 호스트에 알림. */
export const reportRoute = (path: string) => send({ type: "route.changed", path }) export const reportRoute = (path: string) => send({ type: "route.changed", path })
/** 답변 스트림 끝 — 데스크톱이 창 안 보고 있으면 토스트 + 트레이 점. 브라우저에선 no-op. */
export const notifyChatDone = (title?: string) => {
if (hostKind() !== "tauri") return
send({ type: "chat.done", title: title ?? "" })
}
/** 프레임리스 창을 native 창 이동으로 끌 수 있게 함. */ /** 프레임리스 창을 native 창 이동으로 끌 수 있게 함. */
export const startWindowDrag = () => send({ type: "window.drag" }) export const startWindowDrag = () => send({ type: "window.drag" })
+8 -4
View File
@@ -40,10 +40,14 @@ export interface ClarifyCandidate {
reason: string reason: string
} }
/** `step` 이벤트 — 에이전트 그래프 진행 단계 (agent.iter 데모용). */ /** `step` 이벤트 — 답변 전 과정 한 조각. reasoning 은 text 가 delta 로 누적, tool 은 같은 id 로 상태 갱신. */
export interface AgentStep { export interface AgentStep {
phase: string id: string
detail: string kind: "reasoning" | "tool"
text?: string
tool?: string
status?: string
title?: string
} }
/** `tool_call` 이벤트 — 모델이 도구 호출 시작. */ /** `tool_call` 이벤트 — 모델이 도구 호출 시작. */
@@ -63,7 +67,7 @@ export interface LLMStreamHandlers<TResult = unknown> {
onResult?: (data: TResult) => void onResult?: (data: TResult) => void
/** `clarify` 이벤트 — 라우팅 애매. 후보 받으면 token 없이 done으로 끝남 (선택) */ /** `clarify` 이벤트 — 라우팅 애매. 후보 받으면 token 없이 done으로 끝남 (선택) */
onClarify?: (candidates: ClarifyCandidate[]) => void onClarify?: (candidates: ClarifyCandidate[]) => void
/** `step` 이벤트 — 에이전트 진행 단계 (agent.iter 데모용, 선택) */ /** `step` 이벤트 — 생각/도구 과정 조각 (선택) */
onStep?: (step: AgentStep) => void onStep?: (step: AgentStep) => void
/** `tool_call` 이벤트 — 모델이 도구 호출 시작 (선택) */ /** `tool_call` 이벤트 — 모델이 도구 호출 시작 (선택) */
onToolCall?: (call: AgentToolCall) => void onToolCall?: (call: AgentToolCall) => void
+4 -1
View File
@@ -1,4 +1,5 @@
import { lazy, Suspense } from "react" import { lazy, Suspense } from "react"
import { CenterSpinner } from "@/shared/components/CenterSpinner"
import { Navigate, type RouteObject } from "react-router-dom" import { Navigate, type RouteObject } from "react-router-dom"
import Layout from "@/shared/components/Layout" import Layout from "@/shared/components/Layout"
import ProtectedRoute from "@/shared/components/ProtectedRoute" import ProtectedRoute from "@/shared/components/ProtectedRoute"
@@ -11,8 +12,9 @@ const SessionListPage = lazy(() => import("@/features/snap/pages/SessionListPage
const NewChatPage = lazy(() => import("@/features/snap/pages/NewChatPage")) const NewChatPage = lazy(() => import("@/features/snap/pages/NewChatPage"))
const SessionChatPage = lazy(() => import("@/features/snap/pages/SessionChatPage")) const SessionChatPage = lazy(() => import("@/features/snap/pages/SessionChatPage"))
const SnippetPalettePage = lazy(() => import("@/features/snippets/pages/SnippetPalettePage")) const SnippetPalettePage = lazy(() => import("@/features/snippets/pages/SnippetPalettePage"))
const AdminStatsPage = lazy(() => import("@/features/admin/pages/AdminStatsPage"))
const fallback = <div className="text-muted-foreground">...</div> const fallback = <CenterSpinner />
const wrap = (el: React.ReactNode) => <Suspense fallback={fallback}>{el}</Suspense> const wrap = (el: React.ReactNode) => <Suspense fallback={fallback}>{el}</Suspense>
@@ -34,6 +36,7 @@ export const routes: RouteObject[] = [
{ path: PATHS.SNAP.slice(1), element: wrap(<SessionListPage />) }, { path: PATHS.SNAP.slice(1), element: wrap(<SessionListPage />) },
{ path: PATHS.SNAP_NEW.slice(1), element: wrap(<NewChatPage />) }, { path: PATHS.SNAP_NEW.slice(1), element: wrap(<NewChatPage />) },
{ path: PATHS.SNAP_SESSION.slice(1), element: wrap(<SessionChatPage />) }, { path: PATHS.SNAP_SESSION.slice(1), element: wrap(<SessionChatPage />) },
{ path: PATHS.ADMIN.slice(1), element: wrap(<AdminStatsPage />) },
], ],
}, },
{ {
@@ -0,0 +1,10 @@
import { Loader2 } from "lucide-react"
/** 화면 정가운데 도는 스피너 — 페이지 lazy 로딩·로그인 확인 같은 전체 화면 대기용. */
export function CenterSpinner({ label = "로딩 중" }: { label?: string }) {
return (
<div role="status" aria-label={label} className="flex h-dvh w-full items-center justify-center">
<Loader2 className="text-muted-foreground size-6 animate-spin" />
</div>
)
}
+3 -13
View File
@@ -1,19 +1,9 @@
import logo from "@/assets/logo.png"
import logoDark from "@/assets/logo-dark.png"
import { cn } from "@/lib/utils/cn"
interface LogoMarkProps { interface LogoMarkProps {
/** 로고 가로 폭(px) — 원본 비율(약 2.06:1) 유지 */
width?: number width?: number
className?: string className?: string
} }
/** 브랜드 마크 — ABAP_OPENCODE 와 같은 PwC 로고. 다크에선 밝은 글자 변형. */ /** 브랜드 마크 자리 — 지금은 아무것도 안 그림(PwC 로고 제거, 2026-09-21). 호출부 6곳은 그대로 두고 여기서만 끔. */
export function LogoMark({ width = 38, className }: LogoMarkProps) { export function LogoMark(_props: LogoMarkProps) {
return ( return null
<span className={cn("inline-flex shrink-0", className)} style={{ width }}>
<img src={logo} alt="PwC" className="block h-auto w-full dark:hidden" />
<img src={logoDark} alt="PwC" className="hidden h-auto w-full dark:block" />
</span>
)
} }
@@ -3,6 +3,7 @@ import { Navigate, Outlet, useLocation } from "react-router-dom"
import { useMe } from "@/features/auth/hooks/useMe" import { useMe } from "@/features/auth/hooks/useMe"
import { useAuthStore } from "@/features/auth/store/authStore" import { useAuthStore } from "@/features/auth/store/authStore"
import { PATHS } from "@/config/routes" import { PATHS } from "@/config/routes"
import { CenterSpinner } from "@/shared/components/CenterSpinner"
/** /**
* user를 . * user를 .
@@ -25,7 +26,7 @@ export default function ProtectedRoute() {
return <Navigate to={`${PATHS.LOGIN}${query}`} replace /> return <Navigate to={`${PATHS.LOGIN}${query}`} replace />
} }
if (me.isLoading) { if (me.isLoading) {
return <div className="text-muted-foreground p-6"> ...</div> return <CenterSpinner label="로그인 확인 중" />
} }
return <Outlet /> return <Outlet />
} }
+2 -2
View File
@@ -35,8 +35,8 @@ const ORDER: Theme[] = ["light", "dark", "system"]
export const useThemeStore = create<ThemeState>()( export const useThemeStore = create<ThemeState>()(
persist( persist(
(set, get) => ({ (set, get) => ({
theme: "dark", // ABAP_OPENCODE 와 같이 다크가 기본 theme: "light", // 삼성향 팔레트가 라이트라 라이트 기본(2026-09-21)
resolved: resolve("dark"), resolved: resolve("light"),
setTheme: (theme) => { setTheme: (theme) => {
const resolved = resolve(theme) const resolved = resolve(theme)
applyToDocument(resolved) applyToDocument(resolved)
+46 -3
View File
@@ -83,6 +83,37 @@ export type DerivedTokens = {
// 의미색 — 모든 테마 공통 // 의미색 — 모든 테마 공통
const DESTRUCTIVE = "oklch(0.577 0.245 27.325)" const DESTRUCTIVE = "oklch(0.577 0.245 27.325)"
// 삼성향 — 삼성닷컴(sec) 공개 웹 2026-07 실측값(흰 바탕·검정 글씨·회색 면, 그림자 없음, 알약 20px)에
// 포인트로 Samsung Blue #1428A0(브랜드 로고 색) — 버튼·링·활성 표시. One UI 파랑(#0381fe)은 폰 앱용이라 안 씀.
const SAMSUNG_TOKENS: DerivedTokens = {
background: "#FFFFFF", // canvas
foreground: "#111111", // 순검정 대신 오프블랙 — 긴 글 읽을 때 눈 편함
card: "#FFFFFF",
cardForeground: "#111111",
popover: "#FFFFFF",
popoverForeground: "#111111",
primary: "#1428A0", // Samsung Blue — 포인트
primaryForeground: "#FFFFFF",
secondary: "#F7F7F7", // surface
secondaryForeground: "#111111",
muted: "#F7F7F7",
mutedForeground: "#707070",
accent: "#EDEDED", // hover — surface 보다 한 단계
accentForeground: "#111111",
destructive: DESTRUCTIVE,
border: "#DDDDDD",
input: "#DDDDDD",
ring: "#1428A0",
sidebar: "#F7F7F7",
sidebarForeground: "#111111",
sidebarPrimary: "#1428A0",
sidebarPrimaryForeground: "#FFFFFF",
sidebarAccent: "#EDEDED",
sidebarAccentForeground: "#111111",
sidebarBorder: "#DDDDDD",
sidebarRing: "#1428A0",
}
// 기본 팔레트(id 는 하위호환으로 clean-blue 유지) — ABAP_OPENCODE DESIGN_SYSTEM.md §7 라이트 값. // 기본 팔레트(id 는 하위호환으로 clean-blue 유지) — ABAP_OPENCODE DESIGN_SYSTEM.md §7 라이트 값.
// globals.css :root 와 같은 값. 명도 정렬(derive)을 안 타서 블루가 차콜로 안 바뀜. // globals.css :root 와 같은 값. 명도 정렬(derive)을 안 타서 블루가 차콜로 안 바뀜.
const CLEAN_BLUE_TOKENS: DerivedTokens = { const CLEAN_BLUE_TOKENS: DerivedTokens = {
@@ -114,6 +145,16 @@ const CLEAN_BLUE_TOKENS: DerivedTokens = {
sidebarRing: "#3563E9", sidebarRing: "#3563E9",
} }
// 고정 토큰 팔레트(명도 정렬 안 탐). 나머지는 swatch 에서 derive.
const FIXED_TOKENS: Record<string, DerivedTokens> = {
"clean-blue": CLEAN_BLUE_TOKENS,
samsung: SAMSUNG_TOKENS,
}
// 팔레트별 추가 CSS — samsung: 카드·입력 10px, 버튼은 알약(--radius-pill, button.tsx 가 씀), 링크색
const EXTRA_CSS: Record<string, string> = {
samsung: `[data-theme="samsung"]:not(.dark){--radius:10px;--radius-pill:9999px;--link:#1428A0}`,
}
export function derivePaletteTokens( export function derivePaletteTokens(
swatch: readonly [string, string, string, string] swatch: readonly [string, string, string, string]
): DerivedTokens { ): DerivedTokens {
@@ -181,13 +222,15 @@ function paletteToCss(id: string, t: DerivedTokens): string {
} }
// 전체 테마 CSS를 한 번에 생성. 모듈 로드 시 1회 실행. // 전체 테마 CSS를 한 번에 생성. 모듈 로드 시 1회 실행.
export const ALL_THEMES_CSS: string = PALETTES.map((p) => export const ALL_THEMES_CSS: string = PALETTES.map(
paletteToCss(p.id, p.id === "clean-blue" ? CLEAN_BLUE_TOKENS : derivePaletteTokens(p.swatch)) (p) =>
paletteToCss(p.id, FIXED_TOKENS[p.id] ?? derivePaletteTokens(p.swatch)) +
(EXTRA_CSS[p.id] ?? "")
).join("") ).join("")
// 미리보기 카드용 — id로 derived tokens 조회 // 미리보기 카드용 — id로 derived tokens 조회
export function getDerivedTokens(id: string): DerivedTokens | null { export function getDerivedTokens(id: string): DerivedTokens | null {
if (id === "clean-blue") return { ...CLEAN_BLUE_TOKENS } if (FIXED_TOKENS[id]) return { ...FIXED_TOKENS[id] }
const p = PALETTES.find((x) => x.id === id) const p = PALETTES.find((x) => x.id === id)
return p ? derivePaletteTokens(p.swatch) : null return p ? derivePaletteTokens(p.swatch) : null
} }
+6 -1
View File
@@ -9,6 +9,11 @@ export type RawPalette = {
} }
export const PALETTES: RawPalette[] = [ export const PALETTES: RawPalette[] = [
{
id: "samsung", // 고정 토큰(derive.ts SAMSUNG_TOKENS) — 삼성닷컴 공개 웹 실측값. 라이트 전용, 다크는 공통
name: "Samsung",
swatch: ["#FFFFFF", "#F7F7F7", "#1428A0", "#000000"],
},
{ {
id: "clean-blue", // id 는 저장된 값 호환 위해 유지 — 실제 토큰은 derive.ts 워크스페이스(ABAP_OPENCODE) 값 id: "clean-blue", // id 는 저장된 값 호환 위해 유지 — 실제 토큰은 derive.ts 워크스페이스(ABAP_OPENCODE) 값
name: "워크스페이스", name: "워크스페이스",
@@ -80,7 +85,7 @@ export const PALETTES: RawPalette[] = [
}, },
] ]
export const DEFAULT_THEME = "clean-blue" export const DEFAULT_THEME = "samsung"
export const PALETTE_BY_ID: Record<string, RawPalette> = Object.fromEntries( export const PALETTE_BY_ID: Record<string, RawPalette> = Object.fromEntries(
PALETTES.map((p) => [p.id, p]) PALETTES.map((p) => [p.id, p])
+5 -3
View File
@@ -5,7 +5,9 @@ import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils/cn" import { cn } from "@/lib/utils/cn"
const buttonVariants = cva( const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", // rounded-[var(--radius-pill,var(--radius-md))]: 팔레트가 --radius-pill 을 주면 알약, 아니면 기존 md.
// active:scale-[0.98]: 눌림 피드백(정적 hover 만 있으면 밋밋함).
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-[var(--radius-pill,var(--radius-md))] text-sm font-medium ring-offset-background transition-[color,background-color,transform] active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{ {
variants: { variants: {
variant: { variant: {
@@ -18,8 +20,8 @@ const buttonVariants = cva(
}, },
size: { size: {
default: "h-10 px-4 py-2", default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3", sm: "h-9 px-3",
lg: "h-11 rounded-md px-8", lg: "h-11 px-8",
icon: "h-10 w-10", icon: "h-10 w-10",
}, },
}, },
+9
View File
@@ -146,6 +146,15 @@
"rlig" 1, "rlig" 1,
"calt" 1; "calt" 1;
} }
/* Tailwind v4 가 버튼 기본 cursor 를 default 로 바꿔서 — 클릭되는 건 전부 손가락 모양 */
button:not(:disabled),
[role="button"]:not([aria-disabled="true"]),
a[href],
label[for],
select:not(:disabled),
summary {
cursor: pointer;
}
/* 스크롤바·선택·캐럿 — ABAP_OPENCODE 와 같은 얇은 오버레이 스타일 */ /* 스크롤바·선택·캐럿 — ABAP_OPENCODE 와 같은 얇은 오버레이 스타일 */
* { * {
scrollbar-width: thin; scrollbar-width: thin;
+18
View File
@@ -64,3 +64,21 @@ export interface EntraConfigResponse {
authority: string authority: string
tenantId: string tenantId: string
} }
// 관리자 대시보드 — GET /admin/stats
export interface AdminStatRow {
requests: number
inputTokens: number
outputTokens: number
totalTokens: number
costUsd: number
avgElapsedMs: number | null
}
export interface AdminStatsResponse {
from: string
to: string
totals: AdminStatRow & { users: number; sessions: number }
byUser: (AdminStatRow & { userId: string; email: string; name: string; sessions: number })[]
byDay: (AdminStatRow & { day: string })[]
}
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/app.tsx","./src/main.tsx","./src/routes.tsx","./src/vite-env.d.ts","./src/config/env.ts","./src/config/routes.ts","./src/features/auth/index.ts","./src/features/auth/api/auth.api.ts","./src/features/auth/components/entraloginbutton.tsx","./src/features/auth/components/entraloginsection.tsx","./src/features/auth/components/loginform.tsx","./src/features/auth/components/sessionexpirydialog.tsx","./src/features/auth/hooks/useentraenabled.ts","./src/features/auth/hooks/useentralogin.ts","./src/features/auth/hooks/uselogin.ts","./src/features/auth/hooks/uselogout.ts","./src/features/auth/hooks/useme.ts","./src/features/auth/hooks/useslidingrefresh.ts","./src/features/auth/pages/loginpage.tsx","./src/features/auth/schemas/index.ts","./src/features/auth/store/authstore.ts","./src/features/auth/store/sessionexpirystore.ts","./src/features/auth/utils/saferedirectpath.ts","./src/features/snap/api/snap.api.ts","./src/features/snap/api/snap.stream.ts","./src/features/snap/components/chatheader.tsx","./src/features/snap/components/clipboardhistory.tsx","./src/features/snap/components/codeblock.tsx","./src/features/snap/components/composer.tsx","./src/features/snap/components/hero.tsx","./src/features/snap/components/message.tsx","./src/features/snap/components/navrail.tsx","./src/features/snap/components/searchhitcard.tsx","./src/features/snap/components/sessioncard.tsx","./src/features/snap/components/sessionsearch.tsx","./src/features/snap/components/snaplayout.tsx","./src/features/snap/components/snapusercontrols.tsx","./src/features/snap/components/abaphljs.ts","./src/features/snap/contract/types.ts","./src/features/snap/hooks/useescapekey.ts","./src/features/snap/hooks/usesnapchat.ts","./src/features/snap/lib/format.ts","./src/features/snap/pages/newchatpage.tsx","./src/features/snap/pages/sessionchatpage.tsx","./src/features/snap/pages/sessionlistpage.tsx","./src/features/snap/store/snapchatstore.ts","./src/features/snippets/types.ts","./src/features/snippets/api/snippets.api.ts","./src/features/snippets/components/categorychips.tsx","./src/features/snippets/components/editdialog.tsx","./src/features/snippets/components/previewpane.tsx","./src/features/snippets/components/snippetrow.tsx","./src/features/snippets/core/ranking.ts","./src/features/snippets/core/search.ts","./src/features/snippets/hooks/usesnippets.ts","./src/features/snippets/pages/snippetpalettepage.tsx","./src/lib/api/client.ts","./src/lib/api/errors.ts","./src/lib/auth/msal.ts","./src/lib/auth/tokenprovider.ts","./src/lib/bridge/bridgenavigate.ts","./src/lib/bridge/snippetbridge.ts","./src/lib/bridge/transport.ts","./src/lib/bridge/webviewbridge.ts","./src/lib/hooks/usedebounce.ts","./src/lib/query/queryclient.ts","./src/lib/streaming/stoppednotice.tsx","./src/lib/streaming/streamingtext.tsx","./src/lib/streaming/abort.ts","./src/lib/streaming/index.ts","./src/lib/streaming/sse.ts","./src/lib/streaming/streamllm.ts","./src/lib/streaming/usesmoothedtext.ts","./src/lib/streaming/usestreamsession.ts","./src/lib/utils/cn.ts","./src/lib/utils/randomid.ts","./src/lib/utils/relativetime.ts","./src/lib/utils/sleep.ts","./src/shared/components/desktopwindowframe.tsx","./src/shared/components/errorboundary.tsx","./src/shared/components/kbd.tsx","./src/shared/components/layout.tsx","./src/shared/components/paletteshell.tsx","./src/shared/components/pastetargetbadge.tsx","./src/shared/components/protectedroute.tsx","./src/shared/components/themetoggle.tsx","./src/shared/hooks/usepastetarget.ts","./src/shared/store/themestore.ts","./src/shared/theme/derive.ts","./src/shared/theme/palettes.ts","./src/shared/theme/usetheme.ts","./src/shared/ui/alert-dialog.tsx","./src/shared/ui/alert.tsx","./src/shared/ui/button.tsx","./src/shared/ui/dialog.tsx","./src/shared/ui/dropdown-menu.tsx","./src/shared/ui/input.tsx","./src/shared/ui/label.tsx","./src/shared/ui/separator.tsx","./src/shared/ui/skeleton.tsx","./src/shared/ui/textarea.tsx","./src/shared/ui/tooltip.tsx","./src/types/api.ts"],"version":"5.9.3"} {"root":["./src/app.tsx","./src/main.tsx","./src/routes.tsx","./src/vite-env.d.ts","./src/config/env.ts","./src/config/routes.ts","./src/features/admin/api/admin.api.ts","./src/features/admin/pages/adminstatspage.tsx","./src/features/auth/index.ts","./src/features/auth/api/auth.api.ts","./src/features/auth/components/entraloginbutton.tsx","./src/features/auth/components/entraloginsection.tsx","./src/features/auth/components/loginform.tsx","./src/features/auth/components/sessionexpirydialog.tsx","./src/features/auth/hooks/useentraenabled.ts","./src/features/auth/hooks/useentralogin.ts","./src/features/auth/hooks/uselogin.ts","./src/features/auth/hooks/uselogout.ts","./src/features/auth/hooks/useme.ts","./src/features/auth/hooks/useslidingrefresh.ts","./src/features/auth/pages/loginpage.tsx","./src/features/auth/schemas/index.ts","./src/features/auth/store/authstore.ts","./src/features/auth/store/sessionexpirystore.ts","./src/features/auth/utils/saferedirectpath.ts","./src/features/snap/api/snap.api.ts","./src/features/snap/api/snap.stream.ts","./src/features/snap/components/chatheader.tsx","./src/features/snap/components/clipboardhistory.tsx","./src/features/snap/components/codeblock.tsx","./src/features/snap/components/composer.tsx","./src/features/snap/components/hero.tsx","./src/features/snap/components/message.tsx","./src/features/snap/components/navrail.tsx","./src/features/snap/components/searchhitcard.tsx","./src/features/snap/components/sessioncard.tsx","./src/features/snap/components/sessionsearch.tsx","./src/features/snap/components/snaplayout.tsx","./src/features/snap/components/snapusercontrols.tsx","./src/features/snap/components/thinkingbubble.tsx","./src/features/snap/components/thinkingsteps.tsx","./src/features/snap/components/abaphljs.ts","./src/features/snap/contract/types.ts","./src/features/snap/hooks/useescapekey.ts","./src/features/snap/hooks/usesnapchat.ts","./src/features/snap/lib/format.ts","./src/features/snap/pages/newchatpage.tsx","./src/features/snap/pages/sessionchatpage.tsx","./src/features/snap/pages/sessionlistpage.tsx","./src/features/snap/store/snapchatstore.ts","./src/features/snippets/types.ts","./src/features/snippets/api/snippets.api.ts","./src/features/snippets/components/categorychips.tsx","./src/features/snippets/components/editdialog.tsx","./src/features/snippets/components/previewpane.tsx","./src/features/snippets/components/snippetrow.tsx","./src/features/snippets/core/ranking.ts","./src/features/snippets/core/search.ts","./src/features/snippets/hooks/usesnippets.ts","./src/features/snippets/pages/snippetpalettepage.tsx","./src/lib/api/client.ts","./src/lib/api/errors.ts","./src/lib/auth/msal.ts","./src/lib/auth/tokenprovider.ts","./src/lib/bridge/bridgenavigate.ts","./src/lib/bridge/snippetbridge.ts","./src/lib/bridge/transport.ts","./src/lib/bridge/webviewbridge.ts","./src/lib/hooks/usedebounce.ts","./src/lib/query/queryclient.ts","./src/lib/streaming/stoppednotice.tsx","./src/lib/streaming/streamingtext.tsx","./src/lib/streaming/abort.ts","./src/lib/streaming/index.ts","./src/lib/streaming/sse.ts","./src/lib/streaming/streamllm.ts","./src/lib/streaming/usesmoothedtext.ts","./src/lib/streaming/usestreamsession.ts","./src/lib/utils/cn.ts","./src/lib/utils/randomid.ts","./src/lib/utils/relativetime.ts","./src/lib/utils/sleep.ts","./src/shared/components/centerspinner.tsx","./src/shared/components/desktopwindowframe.tsx","./src/shared/components/errorboundary.tsx","./src/shared/components/kbd.tsx","./src/shared/components/layout.tsx","./src/shared/components/logomark.tsx","./src/shared/components/paletteshell.tsx","./src/shared/components/pastetargetbadge.tsx","./src/shared/components/protectedroute.tsx","./src/shared/components/themetoggle.tsx","./src/shared/hooks/usepastetarget.ts","./src/shared/store/themestore.ts","./src/shared/theme/derive.ts","./src/shared/theme/palettes.ts","./src/shared/theme/usetheme.ts","./src/shared/ui/alert-dialog.tsx","./src/shared/ui/alert.tsx","./src/shared/ui/button.tsx","./src/shared/ui/dialog.tsx","./src/shared/ui/dropdown-menu.tsx","./src/shared/ui/input.tsx","./src/shared/ui/label.tsx","./src/shared/ui/separator.tsx","./src/shared/ui/skeleton.tsx","./src/shared/ui/textarea.tsx","./src/shared/ui/tooltip.tsx","./src/types/api.ts"],"version":"5.9.3"}
+99 -1
View File
@@ -485,7 +485,7 @@ dependencies = [
[[package]] [[package]]
name = "codeassist-tauri" name = "codeassist-tauri"
version = "0.1.0" version = "0.1.4"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"png 0.17.16", "png 0.17.16",
@@ -495,6 +495,7 @@ dependencies = [
"tauri", "tauri",
"tauri-build", "tauri-build",
"tauri-plugin-global-shortcut", "tauri-plugin-global-shortcut",
"tauri-plugin-notification",
"tauri-plugin-single-instance", "tauri-plugin-single-instance",
"tauri-plugin-window-state", "tauri-plugin-window-state",
"windows", "windows",
@@ -2105,6 +2106,20 @@ version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "mac-notification-sys"
version = "0.6.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca"
dependencies = [
"cc",
"log",
"objc2",
"objc2-foundation",
"time",
"uuid",
]
[[package]] [[package]]
name = "markup5ever" name = "markup5ever"
version = "0.38.0" version = "0.38.0"
@@ -2219,6 +2234,20 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "notify-rust"
version = "4.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5b4c1b4f2aa9f25f63a7a49d3dd0ed567b3670da15330a66b29434be899b891"
dependencies = [
"futures-lite",
"log",
"mac-notification-sys",
"serde",
"tauri-winrt-notification",
"zbus",
]
[[package]] [[package]]
name = "num-conv" name = "num-conv"
version = "0.2.2" version = "0.2.2"
@@ -2379,6 +2408,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [ dependencies = [
"bitflags 2.13.1", "bitflags 2.13.1",
"block2", "block2",
"libc",
"objc2", "objc2",
"objc2-core-foundation", "objc2-core-foundation",
] ]
@@ -2692,6 +2722,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]] [[package]]
name = "precomputed-hash" name = "precomputed-hash"
version = "0.1.1" version = "0.1.1"
@@ -2796,6 +2835,35 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]] [[package]]
name = "raw-window-handle" name = "raw-window-handle"
version = "0.6.2" version = "0.6.2"
@@ -3630,6 +3698,25 @@ dependencies = [
"thiserror 2.0.20", "thiserror 2.0.20",
] ]
[[package]]
name = "tauri-plugin-notification"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad2fd40946aef810c4be9fd33a2d1b9b397cb79042b2d21c81a0a8f204354fd1"
dependencies = [
"log",
"notify-rust",
"rand",
"serde",
"serde_json",
"serde_repr",
"tauri",
"tauri-plugin",
"thiserror 2.0.20",
"time",
"url",
]
[[package]] [[package]]
name = "tauri-plugin-single-instance" name = "tauri-plugin-single-instance"
version = "2.4.3" version = "2.4.3"
@@ -3761,6 +3848,17 @@ dependencies = [
"toml 1.1.4+spec-1.1.0", "toml 1.1.4+spec-1.1.0",
] ]
[[package]]
name = "tauri-winrt-notification"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade"
dependencies = [
"thiserror 2.0.20",
"windows",
"windows-version",
]
[[package]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.27.0" version = "3.27.0"
+3 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "codeassist-tauri" name = "codeassist-tauri"
version = "0.1.0" version = "0.1.4"
description = "CodeAssist 표준 Rust/Tauri 데스크톱 앱" description = "CodeAssist 표준 Rust/Tauri 데스크톱 앱"
authors = ["justdodev"] authors = ["justdodev"]
edition = "2021" edition = "2021"
@@ -19,6 +19,7 @@ tauri = { version = "2", features = ["tray-icon", "image-png"] }
tauri-plugin-global-shortcut = "2" # 전역 핫키 (.NET HotKeyService 대체) tauri-plugin-global-shortcut = "2" # 전역 핫키 (.NET HotKeyService 대체)
tauri-plugin-single-instance = "2" # 단일 인스턴스 (.NET SingleInstanceGuard 대체) tauri-plugin-single-instance = "2" # 단일 인스턴스 (.NET SingleInstanceGuard 대체)
tauri-plugin-window-state = "2" # 창 위치·크기 저장 (.NET JsonWindowPlacementStore 대체) tauri-plugin-window-state = "2" # 창 위치·크기 저장 (.NET JsonWindowPlacementStore 대체)
tauri-plugin-notification = "2" # 답변 완료 Windows 토스트
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
rusqlite = { version = "0.32.1", features = ["bundled"] } rusqlite = { version = "0.32.1", features = ["bundled"] }
@@ -29,6 +30,7 @@ png = "0.17"
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
windows = { version = "0.61.3", features = [ windows = { version = "0.61.3", features = [
"Win32_Foundation", "Win32_Foundation",
"Win32_Graphics_Dwm",
"Win32_Graphics_Gdi", "Win32_Graphics_Gdi",
"Win32_System_LibraryLoader", "Win32_System_LibraryLoader",
"Win32_System_DataExchange", "Win32_System_DataExchange",
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- 맥 전용. macOS 는 앱 안 http(비암호화) 요청을 기본 차단(ATS)하는데, 우리 서버·고객사 서버가
http 라 앱이 로그인조차 못 함. Tauri 가 이 파일을 번들 Info.plist 에 합쳐 넣음. Windows 는 무관. -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</plist>
@@ -3,5 +3,5 @@
"identifier": "default", "identifier": "default",
"description": "메인 창 권한. 프론트는 core API 를 직접 안 부르고 우리 #[tauri::command] 만 invoke 하므로 core:default 로 충분 (listen/emit 포함).", "description": "메인 창 권한. 프론트는 core API 를 직접 안 부르고 우리 #[tauri::command] 만 invoke 하므로 core:default 로 충분 (listen/emit 포함).",
"windows": ["main"], "windows": ["main"],
"permissions": ["core:default"] "permissions": ["core:default", "notification:default"]
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

+16 -2
View File
@@ -11,13 +11,15 @@ use std::sync::Mutex;
use tauri::{AppHandle, State}; use tauri::{AppHandle, State};
use crate::shell::{paste, paste::PasteState, window}; use crate::shell::{notify, paste, paste::PasteState, window};
/// JS 가 보고하는 현재 route + 마지막 챗봇(`/snap`) route. /// JS 가 보고하는 현재 route + 마지막 챗봇(`/snap`) route.
/// (.NET `App.xaml.cs` 의 `_currentRoute` / `_lastSnapRoute` 대응) /// (.NET `App.xaml.cs` 의 `_currentRoute` / `_lastSnapRoute` 대응)
pub struct Routes { pub struct Routes {
pub current: String, pub current: String,
pub last_snap: String, pub last_snap: String,
/// 마지막으로 열었던 기존 대화(`/snap/s/<id>`). 캡쳐를 기존 대화에 붙일 때 씀.
pub last_session: Option<String>,
} }
impl Default for Routes { impl Default for Routes {
@@ -26,6 +28,7 @@ impl Default for Routes {
Self { Self {
current: "/snap".into(), current: "/snap".into(),
last_snap: "/snap".into(), last_snap: "/snap".into(),
last_session: None,
} }
} }
} }
@@ -35,6 +38,9 @@ impl Routes {
if path == "/snap" || path.starts_with("/snap/") { if path == "/snap" || path.starts_with("/snap/") {
path.clone_into(&mut self.last_snap); path.clone_into(&mut self.last_snap);
} }
if path.starts_with("/snap/s/") {
self.last_session = Some(path.to_string());
}
path.clone_into(&mut self.current); path.clone_into(&mut self.current);
} }
} }
@@ -48,6 +54,13 @@ pub fn window_hide(app: AppHandle) {
let _ = window::hide(&app); let _ = window::hide(&app);
} }
/// 답변 스트림이 끝났음 — 사용자가 창을 안 보고 있으면 토스트 + 트레이 점.
/// 프론트 `send({type:"chat.done", title})`.
#[tauri::command]
pub fn chat_done(app: AppHandle, title: Option<String>) {
notify::answer_done(&app, title.as_deref().unwrap_or(""));
}
/// 프레임리스 창이라 제목표시줄이 없음 — React 헤더 mousedown 이 이걸 불러 창을 끈다. /// 프레임리스 창이라 제목표시줄이 없음 — React 헤더 mousedown 이 이걸 불러 창을 끈다.
#[tauri::command] #[tauri::command]
pub fn window_drag(app: AppHandle) { pub fn window_drag(app: AppHandle) {
@@ -67,7 +80,8 @@ pub enum SnippetStage {
#[tauri::command] #[tauri::command]
pub fn window_snippet_layout(app: AppHandle, stage: SnippetStage) -> Result<(), String> { pub fn window_snippet_layout(app: AppHandle, stage: SnippetStage) -> Result<(), String> {
let (width, height) = match stage { let (width, height) = match stage {
SnippetStage::Search => (640.0, 84.0), // 제목줄 h-8(32) + 검색줄 h-14(56) = 88. 이보다 작으면 프레임 overflow-auto 가 스크롤바를 띄움.
SnippetStage::Search => (640.0, 88.0),
SnippetStage::Results => (640.0, 440.0), SnippetStage::Results => (640.0, 440.0),
SnippetStage::Preview => (840.0, 520.0), SnippetStage::Preview => (840.0, 520.0),
SnippetStage::Editor => (960.0, 600.0), SnippetStage::Editor => (960.0, 600.0),
+2 -1
View File
@@ -30,9 +30,10 @@ pub enum Push {
#[serde(rename = "paste.target")] #[serde(rename = "paste.target")]
PasteTarget { name: String, app: String }, PasteTarget { name: String, app: String },
/// 영역 캡쳐 PNG를 프론트의 새 대화 Composer에 붙임. /// 영역 캡쳐 PNG를 지정한 대화 Composer에 붙임.
#[serde(rename = "capture.image")] #[serde(rename = "capture.image")]
CaptureImage { CaptureImage {
path: String,
#[serde(rename = "dataUrl")] #[serde(rename = "dataUrl")]
data_url: String, data_url: String,
}, },
+86 -19
View File
@@ -18,15 +18,29 @@ use shell::window;
const HOTKEYS: &[HotkeySpec] = &[ const HOTKEYS: &[HotkeySpec] = &[
HotkeySpec { HotkeySpec {
id: "snap", id: "snap",
accelerator: "Ctrl+Shift+8", accelerator: "Ctrl+Alt+W",
}, },
HotkeySpec { HotkeySpec {
id: "snippet", id: "snippet",
accelerator: "Ctrl+Shift+7", accelerator: "Ctrl+Alt+Q",
}, },
// 캡쳐 4종: 윗줄(A/S) = 새 대화, 아랫줄(Z/X) = 마지막 기존 대화(없으면 새 대화).
// 왼쪽(A/Z) = 맨 앞 창 통째, 오른쪽(S/X) = 드래그 영역.
HotkeySpec { HotkeySpec {
id: "capture", id: "capture",
accelerator: "Ctrl+Shift+9", accelerator: "Ctrl+Alt+A",
},
HotkeySpec {
id: "capture_area",
accelerator: "Ctrl+Alt+S",
},
HotkeySpec {
id: "capture_last",
accelerator: "Ctrl+Alt+Z",
},
HotkeySpec {
id: "capture_area_last",
accelerator: "Ctrl+Alt+X",
}, },
]; ];
@@ -45,6 +59,7 @@ pub fn run() {
.build(), .build(),
) )
.plugin(tauri_plugin_global_shortcut::Builder::new().build()) .plugin(tauri_plugin_global_shortcut::Builder::new().build())
.plugin(tauri_plugin_notification::init())
.manage(commands::RouteState::default()) .manage(commands::RouteState::default())
.manage(paste::PasteState::default()) .manage(paste::PasteState::default())
.manage(window::TemporaryWindowState::default()) .manage(window::TemporaryWindowState::default())
@@ -59,6 +74,7 @@ pub fn run() {
commands::snippets_update, commands::snippets_update,
commands::snippets_delete, commands::snippets_delete,
commands::snippets_record_use, commands::snippets_record_use,
commands::chat_done,
]) ])
.setup(|app| { .setup(|app| {
let handle = app.handle().clone(); let handle = app.handle().clone();
@@ -89,6 +105,10 @@ pub fn run() {
Ok(()) Ok(())
}) })
.on_window_event(|window, event| { .on_window_event(|window, event| {
// 창을 다시 보면 트레이 "새 답변" 점 원복.
if matches!(event, tauri::WindowEvent::Focused(true)) {
shell::notify::seen(window.app_handle());
}
if matches!(event, tauri::WindowEvent::CloseRequested { .. }) { if matches!(event, tauri::WindowEvent::CloseRequested { .. }) {
if let Err(error) = window::restore_size(window.app_handle()) { if let Err(error) = window::restore_size(window.app_handle()) {
eprintln!("[window] {error}"); eprintln!("[window] {error}");
@@ -149,6 +169,35 @@ fn show_palette(app: &AppHandle) -> tauri::Result<()> {
Ok(()) Ok(())
} }
/// 캡쳐 핫키 id 로 목적지 route 결정. `*_last` 는 마지막 기존 대화, 없으면 새 대화.
fn capture_target(id: &str, last_session: Option<&str>) -> String {
if id.ends_with("_last") {
last_session.unwrap_or("/snap/new").to_string()
} else {
"/snap/new".to_string()
}
}
/// 캡쳐 결과 공통 처리 — 팔레트 소환 → 목적지 대화 화면 → 그 화면 Composer 에 이미지 첨부.
fn on_captured(app: AppHandle, target: String, data_url: String) {
if let Err(error) = show_palette(&app) {
eprintln!("[capture] 창 소환 실패: {error}");
}
bridge::push(
&app,
Push::Navigate {
path: target.clone(),
},
);
bridge::push(
&app,
Push::CaptureImage {
path: target,
data_url,
},
);
}
/// 표준 전역 단축키가 실행할 CodeAssist 동작을 한 곳에서 정함. /// 표준 전역 단축키가 실행할 CodeAssist 동작을 한 곳에서 정함.
fn on_hotkey(app: &AppHandle, id: &str) { fn on_hotkey(app: &AppHandle, id: &str) {
match id { match id {
@@ -162,17 +211,20 @@ fn on_hotkey(app: &AppHandle, id: &str) {
); );
} }
"capture" => { "capture" | "capture_area" | "capture_last" | "capture_area_last" => {
shell::capture::start(app.clone(), |app, data_url| { let target = app
let _ = show_palette(&app); .state::<commands::RouteState>()
bridge::push( .lock()
&app, .map(|routes| capture_target(id, routes.last_session.as_deref()))
Push::Navigate { .unwrap_or_else(|_| "/snap/new".to_string());
path: "/snap/new".into(), let deliver =
}, move |app: AppHandle, data_url: String| on_captured(app, target, data_url);
); if id.starts_with("capture_area") {
bridge::push(&app, Push::CaptureImage { data_url }); shell::capture::start(app.clone(), deliver);
}); } else {
let own_hwnd = window::native_handle(app);
shell::capture::start_foreground_window(app.clone(), own_hwnd, deliver);
}
} }
// 챗봇 토글: 이미 챗봇 화면이 떠 있으면 숨기고, 아니면 마지막 챗봇 위치로 데려온다. // 챗봇 토글: 이미 챗봇 화면이 떠 있으면 숨기고, 아니면 마지막 챗봇 위치로 데려온다.
@@ -199,7 +251,7 @@ fn on_hotkey(app: &AppHandle, id: &str) {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{chat_toggle_target, commands::Routes}; use super::{capture_target, chat_toggle_target, commands::Routes};
#[test] #[test]
fn _토글은_현재_화면과_창_표시에_따라_결정한다() { fn _토글은_현재_화면과_창_표시에_따라_결정한다() {
@@ -219,13 +271,28 @@ mod tests {
} }
#[test] #[test]
fn _챗봇_위치는_챗봇_화면에서만_바뀐() { fn _기존_대화는_새_대화나_다른_화면으로_가도_유지된() {
let mut routes = Routes::default(); let mut routes = Routes::default();
routes.report("/snap/session-1"); routes.report("/snap/s/session-1");
routes.report("/snippet"); routes.report("/snap/new");
routes.report("/files"); routes.report("/files");
assert_eq!(routes.current, "/files"); assert_eq!(routes.current, "/files");
assert_eq!(routes.last_snap, "/snap/session-1"); assert_eq!(routes.last_snap, "/snap/new");
assert_eq!(routes.last_session.as_deref(), Some("/snap/s/session-1"));
}
#[test]
fn _핫키에_따라_새_대화나_마지막_기존_대화를_고른다() {
assert_eq!(capture_target("capture", Some("/snap/s/last")), "/snap/new");
assert_eq!(
capture_target("capture_area", Some("/snap/s/last")),
"/snap/new"
);
assert_eq!(
capture_target("capture_last", Some("/snap/s/last")),
"/snap/s/last"
);
assert_eq!(capture_target("capture_area_last", None), "/snap/new");
} }
} }
+204 -40
View File
@@ -1,5 +1,6 @@
//! 화면 영역 선택 + PNG 캡쳐. legacy `CaptureOverlayWindow`/`ScreenCapture`의 Tauri 이식판. //! 화면 영역 선택 + PNG 캡쳐. legacy `CaptureOverlayWindow`/`ScreenCapture`의 Tauri 이식판.
use std::ffi::c_void;
use std::io::Cursor; use std::io::Cursor;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc; use std::sync::mpsc;
@@ -8,27 +9,30 @@ use base64::Engine;
use tauri::AppHandle; use tauri::AppHandle;
use windows::core::{w, PCWSTR}; use windows::core::{w, PCWSTR};
use windows::Win32::Foundation::{COLORREF, HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM}; use windows::Win32::Foundation::{COLORREF, HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::Graphics::Gdi::{ use windows::Win32::Graphics::Gdi::{
BeginPaint, BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, CreateSolidBrush, DeleteDC, BeginPaint, BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, CreateSolidBrush, DeleteDC,
DeleteObject, EndPaint, FillRect, FrameRect, GetDC, GetDIBits, InvalidateRect, ReleaseDC, DeleteObject, EndPaint, FillRect, FrameRect, GetDC, GetDIBits, InvalidateRect, ReleaseDC,
SelectObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HGDIOBJ, PAINTSTRUCT, SelectObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HBITMAP, HDC, HGDIOBJ,
SRCCOPY, PAINTSTRUCT, SRCCOPY,
}; };
use windows::Win32::System::LibraryLoader::GetModuleHandleW; use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, SetFocus}; use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, SetFocus};
use windows::Win32::UI::WindowsAndMessaging::{ use windows::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetClientRect, GetMessageW, CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetForegroundWindow,
GetSystemMetrics, GetWindowLongPtrW, LoadCursorW, PostQuitMessage, RegisterClassW, GetMessageW, GetSystemMetrics, GetWindowLongPtrW, LoadCursorW, PostQuitMessage, RegisterClassW,
SetForegroundWindow, SetLayeredWindowAttributes, SetWindowLongPtrW, ShowWindow, SetForegroundWindow, SetLayeredWindowAttributes, SetWindowLongPtrW, ShowWindow,
TranslateMessage, CREATESTRUCTW, CS_HREDRAW, CS_VREDRAW, GWLP_USERDATA, IDC_CROSS, LWA_ALPHA, TranslateMessage, CREATESTRUCTW, CS_HREDRAW, CS_VREDRAW, GWLP_USERDATA, IDC_CROSS, LWA_ALPHA,
MSG, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_SHOW, LWA_COLORKEY, MSG, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN,
WA_INACTIVE, WINDOW_EX_STYLE, WM_ACTIVATE, WM_DESTROY, WM_ERASEBKGND, WM_KEYDOWN, SM_YVIRTUALSCREEN, SW_SHOW, WA_INACTIVE, WINDOW_EX_STYLE, WM_ACTIVATE, WM_DESTROY,
WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_NCCREATE, WM_NCDESTROY, WM_PAINT, WNDCLASSW, WM_ERASEBKGND, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_NCCREATE,
WS_EX_LAYERED, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP, WM_NCDESTROY, WM_PAINT, WNDCLASSW, WS_EX_LAYERED, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
}; };
const MIN_SELECTION: i32 = 4; const MIN_SELECTION: i32 = 4;
const OVERLAY_ALPHA: u8 = 115; const OVERLAY_ALPHA: u8 = 115;
// 선택 영역에만 칠해 layered window에서 완전히 투명하게 만드는 색.
const SELECTION_COLOR_KEY: COLORREF = COLORREF(0x00ff00ff);
// Samsung Blue #1428A0. COLORREF는 0x00BBGGRR 순서임. // Samsung Blue #1428A0. COLORREF는 0x00BBGGRR 순서임.
const CAPTURE_BORDER_COLOR: COLORREF = COLORREF(0x00a02814); const CAPTURE_BORDER_COLOR: COLORREF = COLORREF(0x00a02814);
static CAPTURING: AtomicBool = AtomicBool::new(false); static CAPTURING: AtomicBool = AtomicBool::new(false);
@@ -54,17 +58,36 @@ fn selection_rect(start: (i32, i32), end: (i32, i32), origin: (i32, i32)) -> Opt
}) })
} }
/// 이미 캡쳐 중이면 두 번째 핫키는 무시함. /// 드래그로 영역 골라서 캡쳐. 이미 캡쳐 중이면 두 번째 핫키는 무시함.
pub fn start<F>(app: AppHandle, on_captured: F) pub fn start<F>(app: AppHandle, on_captured: F)
where where
F: FnOnce(AppHandle, String) + Send + 'static, F: FnOnce(AppHandle, String) + Send + 'static,
{
spawn_capture(app, on_captured, run_overlay);
}
/// 핫키 누른 순간 맨 앞에 떠 있는 창을 통째로 캡쳐. 앱 종류 안 가림(SAP·Eclipse·브라우저 다 됨).
/// 자기 창(팔레트)이 맨 앞이면 아무것도 안 함.
pub fn start_foreground_window<F>(app: AppHandle, excluded_hwnd: Option<isize>, on_captured: F)
where
F: FnOnce(AppHandle, String) + Send + 'static,
{
spawn_capture(app, on_captured, move || {
foreground_window_rect(excluded_hwnd)
});
}
fn spawn_capture<F, P>(app: AppHandle, on_captured: F, pick_rect: P)
where
F: FnOnce(AppHandle, String) + Send + 'static,
P: FnOnce() -> Result<Option<CaptureRect>, String> + Send + 'static,
{ {
if CAPTURING.swap(true, Ordering::AcqRel) { if CAPTURING.swap(true, Ordering::AcqRel) {
return; return;
} }
std::thread::spawn(move || { std::thread::spawn(move || {
let result = run_overlay().and_then(|rect| match rect { let result = pick_rect().and_then(|rect| match rect {
Some(rect) => capture_png_data_url(rect), Some(rect) => capture_png_data_url(rect),
None => Ok(None), None => Ok(None),
}); });
@@ -77,10 +100,59 @@ where
}); });
} }
struct PaintBuffer {
dc: HDC,
bitmap: HBITMAP,
previous: HGDIOBJ,
}
impl PaintBuffer {
unsafe fn new(hwnd: HWND, width: i32, height: i32) -> Option<Self> {
let window_dc = GetDC(Some(hwnd));
if window_dc.is_invalid() {
return None;
}
let dc = CreateCompatibleDC(Some(window_dc));
let bitmap = CreateCompatibleBitmap(window_dc, width, height);
let _ = ReleaseDC(Some(hwnd), window_dc);
if dc.is_invalid() || bitmap.is_invalid() {
if !dc.is_invalid() {
let _ = DeleteDC(dc);
}
if !bitmap.is_invalid() {
let _ = DeleteObject(HGDIOBJ(bitmap.0));
}
return None;
}
let previous = SelectObject(dc, HGDIOBJ(bitmap.0));
if previous.is_invalid() {
let _ = DeleteObject(HGDIOBJ(bitmap.0));
let _ = DeleteDC(dc);
return None;
}
Some(Self {
dc,
bitmap,
previous,
})
}
}
impl Drop for PaintBuffer {
fn drop(&mut self) {
unsafe {
SelectObject(self.dc, self.previous);
let _ = DeleteObject(HGDIOBJ(self.bitmap.0));
let _ = DeleteDC(self.dc);
}
}
}
struct OverlayState { struct OverlayState {
origin: (i32, i32), origin: (i32, i32),
start: Option<(i32, i32)>, start: Option<(i32, i32)>,
current: Option<(i32, i32)>, current: Option<(i32, i32)>,
buffer: Option<PaintBuffer>,
sender: mpsc::Sender<Option<CaptureRect>>, sender: mpsc::Sender<Option<CaptureRect>>,
finished: bool, finished: bool,
} }
@@ -106,6 +178,24 @@ fn mouse_point(lparam: LPARAM) -> (i32, i32) {
((value & 0xffff) as i16 as i32, (value >> 16) as i16 as i32) ((value & 0xffff) as i16 as i32, (value >> 16) as i16 as i32)
} }
fn selection_client_rect(start: (i32, i32), end: (i32, i32)) -> RECT {
RECT {
left: start.0.min(end.0),
top: start.1.min(end.1),
right: start.0.max(end.0),
bottom: start.1.max(end.1),
}
}
fn union_rect(a: RECT, b: RECT) -> RECT {
RECT {
left: a.left.min(b.left),
top: a.top.min(b.top),
right: a.right.max(b.right),
bottom: a.bottom.max(b.bottom),
}
}
fn inset_rect(rect: RECT, amount: i32) -> Option<RECT> { fn inset_rect(rect: RECT, amount: i32) -> Option<RECT> {
let inset = RECT { let inset = RECT {
left: rect.left + amount, left: rect.left + amount,
@@ -116,6 +206,28 @@ fn inset_rect(rect: RECT, amount: i32) -> Option<RECT> {
(inset.left < inset.right && inset.top < inset.bottom).then_some(inset) (inset.left < inset.right && inset.top < inset.bottom).then_some(inset)
} }
unsafe fn draw_overlay(dc: HDC, background: &RECT, selected: Option<RECT>) {
let shade = CreateSolidBrush(COLORREF(0x000000));
FillRect(dc, background, shade);
let _ = DeleteObject(HGDIOBJ(shade.0));
let Some(selected) = selected else { return };
let clear = CreateSolidBrush(SELECTION_COLOR_KEY);
FillRect(dc, &selected, clear);
let _ = DeleteObject(HGDIOBJ(clear.0));
let white = CreateSolidBrush(COLORREF(0x00ffffff));
let accent = CreateSolidBrush(CAPTURE_BORDER_COLOR);
FrameRect(dc, &selected, white);
for amount in 1..4 {
if let Some(border) = inset_rect(selected, amount) {
FrameRect(dc, &border, accent);
}
}
let _ = DeleteObject(HGDIOBJ(white.0));
let _ = DeleteObject(HGDIOBJ(accent.0));
}
unsafe extern "system" fn overlay_proc( unsafe extern "system" fn overlay_proc(
hwnd: HWND, hwnd: HWND,
message: u32, message: u32,
@@ -141,9 +253,13 @@ unsafe extern "system" fn overlay_proc(
} }
WM_MOUSEMOVE => { WM_MOUSEMOVE => {
if let Some(state) = state { if let Some(state) = state {
if state.start.is_some() { if let Some(start) = state.start {
state.current = Some(mouse_point(lparam)); let current = mouse_point(lparam);
let _ = InvalidateRect(Some(hwnd), None, false); let old = selection_client_rect(start, state.current.unwrap_or(start));
let new = selection_client_rect(start, current);
state.current = Some(current);
let dirty = union_rect(old, new);
let _ = InvalidateRect(Some(hwnd), Some(&dirty), false);
} }
} }
LRESULT(0) LRESULT(0)
@@ -172,33 +288,34 @@ unsafe extern "system" fn overlay_proc(
WM_PAINT => { WM_PAINT => {
let mut paint = PAINTSTRUCT::default(); let mut paint = PAINTSTRUCT::default();
let dc = BeginPaint(hwnd, &mut paint); let dc = BeginPaint(hwnd, &mut paint);
let mut client = RECT::default(); let selected = state.as_ref().and_then(|state| {
let _ = GetClientRect(hwnd, &mut client); state
let shade = CreateSolidBrush(COLORREF(0x000000)); .start
FillRect(dc, &client, shade); .zip(state.current)
if let Some(state) = state { .map(|(start, end)| selection_client_rect(start, end))
if let (Some(start), Some(end)) = (state.start, state.current) { });
let selected = RECT {
left: start.0.min(end.0), if let Some(buffer) = state.as_ref().and_then(|state| state.buffer.as_ref()) {
top: start.1.min(end.1), draw_overlay(buffer.dc, &paint.rcPaint, selected);
right: start.0.max(end.0), let width = paint.rcPaint.right - paint.rcPaint.left;
bottom: start.1.max(end.1), let height = paint.rcPaint.bottom - paint.rcPaint.top;
}; if width > 0 && height > 0 {
// 반투명 오버레이에서도 경계가 묻히지 않게 흰색 외곽선과 let _ = BitBlt(
// 포인트색 안쪽선을 겹쳐 4px 테두리로 그림. dc,
let white = CreateSolidBrush(COLORREF(0x00ffffff)); paint.rcPaint.left,
let accent = CreateSolidBrush(CAPTURE_BORDER_COLOR); paint.rcPaint.top,
FrameRect(dc, &selected, white); width,
for amount in 1..4 { height,
if let Some(border) = inset_rect(selected, amount) { Some(buffer.dc),
FrameRect(dc, &border, accent); paint.rcPaint.left,
paint.rcPaint.top,
SRCCOPY,
);
} }
} else {
draw_overlay(dc, &paint.rcPaint, selected);
} }
let _ = DeleteObject(HGDIOBJ(white.0));
let _ = DeleteObject(HGDIOBJ(accent.0));
}
}
let _ = DeleteObject(HGDIOBJ(shade.0));
let _ = EndPaint(hwnd, &paint); let _ = EndPaint(hwnd, &paint);
LRESULT(0) LRESULT(0)
} }
@@ -246,6 +363,7 @@ fn run_overlay() -> Result<Option<CaptureRect>, String> {
origin: (x, y), origin: (x, y),
start: None, start: None,
current: None, current: None,
buffer: None,
sender, sender,
finished: false, finished: false,
}); });
@@ -270,8 +388,13 @@ fn run_overlay() -> Result<Option<CaptureRect>, String> {
return Err(error.to_string()); return Err(error.to_string());
} }
}; };
if let Err(error) = SetLayeredWindowAttributes(hwnd, COLORREF(0), OVERLAY_ALPHA, LWA_ALPHA) (*state_ptr).buffer = PaintBuffer::new(hwnd, width, height);
{ if let Err(error) = SetLayeredWindowAttributes(
hwnd,
SELECTION_COLOR_KEY,
OVERLAY_ALPHA,
LWA_ALPHA | LWA_COLORKEY,
) {
let _ = DestroyWindow(hwnd); let _ = DestroyWindow(hwnd);
return Err(error.to_string()); return Err(error.to_string());
} }
@@ -288,6 +411,30 @@ fn run_overlay() -> Result<Option<CaptureRect>, String> {
Ok(receiver.recv().ok().flatten()) Ok(receiver.recv().ok().flatten())
} }
/// 맨 앞 창의 화면 좌표. Win11 은 GetWindowRect 가 그림자 여백까지 잡아서 DWM 확장 프레임 경계를 씀.
fn foreground_window_rect(excluded_hwnd: Option<isize>) -> Result<Option<CaptureRect>, String> {
let window = unsafe { GetForegroundWindow() };
if window.0.is_null() || excluded_hwnd == Some(window.0 as isize) {
return Ok(None);
}
let mut bounds = RECT::default();
unsafe {
DwmGetWindowAttribute(
window,
DWMWA_EXTENDED_FRAME_BOUNDS,
&mut bounds as *mut RECT as *mut c_void,
std::mem::size_of::<RECT>() as u32,
)
}
.map_err(|error| format!("창 경계를 못 얻었어: {error}"))?;
Ok(Some(CaptureRect {
x: bounds.left,
y: bounds.top,
width: bounds.right - bounds.left,
height: bounds.bottom - bounds.top,
}))
}
fn capture_png_data_url(rect: CaptureRect) -> Result<Option<String>, String> { fn capture_png_data_url(rect: CaptureRect) -> Result<Option<String>, String> {
if rect.width <= 0 || rect.height <= 0 { if rect.width <= 0 || rect.height <= 0 {
return Ok(None); return Ok(None);
@@ -413,4 +560,21 @@ mod tests {
assert_eq!((inset.right, inset.bottom), (27, 47)); assert_eq!((inset.right, inset.bottom), (27, 47));
assert!(inset_rect(rect, 10).is_none()); assert!(inset_rect(rect, 10).is_none());
} }
#[test]
fn _선택_영역의_합집합만_다시_그린다() {
let old = selection_client_rect((100, 100), (300, 250));
let new = selection_client_rect((100, 100), (320, 220));
let dirty = union_rect(old, new);
assert_eq!(
dirty,
RECT {
left: 100,
top: 100,
right: 320,
bottom: 250,
}
);
}
} }
@@ -8,3 +8,10 @@ where
{ {
eprintln!("[capture] 영역 캡처는 Windows 에서만 됨"); eprintln!("[capture] 영역 캡처는 Windows 에서만 됨");
} }
pub fn start_foreground_window<F>(_app: AppHandle, _excluded_hwnd: Option<isize>, _on_captured: F)
where
F: FnOnce(AppHandle, String) + Send + 'static,
{
eprintln!("[capture] 창 캡처는 Windows 에서만 됨");
}
+1
View File
@@ -14,6 +14,7 @@ pub mod capture;
#[path = "capture_stub.rs"] #[path = "capture_stub.rs"]
pub mod capture; pub mod capture;
pub mod hotkey; pub mod hotkey;
pub mod notify;
#[cfg(windows)] #[cfg(windows)]
pub mod paste; pub mod paste;
#[cfg(not(windows))] #[cfg(not(windows))]
@@ -0,0 +1,51 @@
//! 답변 완료 알림 — 사용자가 창을 안 보고 있을 때만.
//!
//! 토스트(Windows 알림센터)는 몇 초 뒤 사라지고, 트레이 점은 창을 다시 볼 때까지 남는다. 둘 다 씀.
//! 창이 앞에 있고 포커스면 아무것도 안 함 — 보고 있는데 알림 뜨면 짜증.
//! 토스트는 설치본(msi)에서만 알림센터에 등록돼 보이고 `tauri dev` 에선 안 뜰 수 있음 — 그땐 트레이 점으로 확인.
use tauri::{AppHandle, Manager};
use tauri_plugin_notification::NotificationExt;
use super::{tray, window};
pub const TOOLTIP: &str = "CodeAssist";
const TOOLTIP_ALERT: &str = "CodeAssist — 새 답변 도착";
/// 창이 보이고 포커스까지 있으면 "보고 있음".
fn user_is_watching(app: &AppHandle) -> bool {
window::is_visible(app)
&& window::main_window(app)
.and_then(|w| w.is_focused().ok())
.unwrap_or(false)
}
pub fn answer_done(app: &AppHandle, title: &str) {
if user_is_watching(app) {
return;
}
tray::mark_alert(app, TOOLTIP_ALERT);
let body = if title.trim().is_empty() {
"새 답변이 도착했어".to_string()
} else {
title.trim().to_string()
};
if let Err(error) = app
.notification()
.builder()
.title("답변 완료")
.body(body)
.show()
{
eprintln!("[notify] 토스트 실패(설치본 아니면 정상): {error}");
}
}
/// 창이 포커스를 받으면 트레이 점 원복. `on_window_event(Focused(true))` 에서 부른다.
pub fn seen(app: &AppHandle) {
tray::clear_alert(app, TOOLTIP);
}
// Manager 는 tray_by_id/default_window_icon 용으로 tray.rs 가 쓰고, 여기선 is_focused 경로에서 씀.
#[allow(unused_imports)]
use Manager as _;
+26 -1
View File
@@ -2,10 +2,13 @@
//! //!
//! 메뉴 구성은 .NET 판과 똑같이 열기 / 항상 위에 고정(체크) / 종료 3개. //! 메뉴 구성은 .NET 판과 똑같이 열기 / 항상 위에 고정(체크) / 종료 3개.
use tauri::image::Image;
use tauri::menu::{CheckMenuItem, Menu, MenuItem}; use tauri::menu::{CheckMenuItem, Menu, MenuItem};
use tauri::tray::TrayIconBuilder; use tauri::tray::TrayIconBuilder;
use tauri::AppHandle; use tauri::AppHandle;
const TRAY_ID: &str = "main";
/// 트레이에서 사용자가 고른 것. 실제로 뭘 할지는 조립부(lib.rs)가 정한다. /// 트레이에서 사용자가 고른 것. 실제로 뭘 할지는 조립부(lib.rs)가 정한다.
pub enum TrayAction { pub enum TrayAction {
Open, Open,
@@ -28,7 +31,7 @@ where
.expect("번들 아이콘 없음 — tauri.conf.json 의 bundle.icon 확인") .expect("번들 아이콘 없음 — tauri.conf.json 의 bundle.icon 확인")
.clone(); .clone();
TrayIconBuilder::with_id("main") TrayIconBuilder::with_id(TRAY_ID)
.icon(icon) .icon(icon)
.tooltip(tooltip) .tooltip(tooltip)
.menu(&menu) .menu(&menu)
@@ -48,3 +51,25 @@ where
Ok(()) Ok(())
} }
/// 답변 도착 표시 — 아이콘에 파란 점 + 툴팁. 사용자가 창을 볼 때까지 남는다(토스트는 사라지니까).
pub fn mark_alert(app: &AppHandle, tooltip: &str) {
let Some(tray) = app.tray_by_id(TRAY_ID) else {
return;
};
if let Ok(icon) = Image::from_bytes(include_bytes!("../../icons/tray-alert.png")) {
let _ = tray.set_icon(Some(icon));
}
let _ = tray.set_tooltip(Some(tooltip));
}
/// 알림 표시 원복 — 창이 포커스를 받으면 부른다.
pub fn clear_alert(app: &AppHandle, tooltip: &str) {
let Some(tray) = app.tray_by_id(TRAY_ID) else {
return;
};
if let Some(icon) = app.default_window_icon() {
let _ = tray.set_icon(Some(icon.clone()));
}
let _ = tray.set_tooltip(Some(tooltip));
}
+47 -2
View File
@@ -11,6 +11,17 @@ use std::sync::Mutex;
use tauri::{ use tauri::{
AppHandle, LogicalSize, Manager, PhysicalPosition, PhysicalRect, PhysicalSize, WebviewWindow, AppHandle, LogicalSize, Manager, PhysicalPosition, PhysicalRect, PhysicalSize, WebviewWindow,
}; };
#[cfg(windows)]
use windows::Win32::Foundation::HWND;
#[cfg(windows)]
use windows::Win32::System::Threading::{AttachThreadInput, GetCurrentThreadId};
#[cfg(windows)]
use windows::Win32::UI::Input::KeyboardAndMouse::SetFocus;
#[cfg(windows)]
use windows::Win32::UI::WindowsAndMessaging::{
BringWindowToTop, GetForegroundWindow, GetWindowThreadProcessId, SetForegroundWindow,
ShowWindow, SW_RESTORE,
};
/// tauri.conf.json 의 창 label 과 같아야 함. /// tauri.conf.json 의 창 label 과 같아야 함.
const MAIN: &str = "main"; const MAIN: &str = "main";
@@ -19,7 +30,6 @@ pub fn main_window(app: &AppHandle) -> Option<WebviewWindow> {
app.get_webview_window(MAIN) app.get_webview_window(MAIN)
} }
/// 창 표시 + 포커스. (핫키/트레이 소환용)
/// 붙여넣기 대상에서 우리 창을 빼거나 포커스 비교할 때 쓰는 네이티브 창 핸들(HWND). /// 붙여넣기 대상에서 우리 창을 빼거나 포커스 비교할 때 쓰는 네이티브 창 핸들(HWND).
/// Windows 에서만 값이 있고 다른 OS 는 None — 호출부가 알아서 "대상 없음"으로 처리함. /// Windows 에서만 값이 있고 다른 OS 는 None — 호출부가 알아서 "대상 없음"으로 처리함.
pub fn native_handle(app: &AppHandle) -> Option<isize> { pub fn native_handle(app: &AppHandle) -> Option<isize> {
@@ -36,10 +46,45 @@ pub fn native_handle(app: &AppHandle) -> Option<isize> {
} }
} }
/// 창 표시 + 포커스. (핫키/트레이 소환용)
/// Windows 에선 캡처 오버레이가 돌려준 foreground 를 현재 입력 큐에 잠시 붙여
/// 이미 보이던 창도 뒤에 남지 않게 직접 활성화함(Tauri set_focus 만으론 외부 앱이 다시 가져감).
pub fn show(app: &AppHandle) -> tauri::Result<()> { pub fn show(app: &AppHandle) -> tauri::Result<()> {
if let Some(w) = main_window(app) { if let Some(w) = main_window(app) {
w.show()?; w.show()?;
w.set_focus()?; let _ = w.set_focus();
#[cfg(windows)]
force_foreground(&w)?;
}
Ok(())
}
#[cfg(windows)]
fn force_foreground(w: &WebviewWindow) -> tauri::Result<()> {
let raw = w.hwnd()?;
let hwnd = HWND(raw.0 as *mut std::ffi::c_void);
unsafe {
let foreground = GetForegroundWindow();
let current_thread = GetCurrentThreadId();
let foreground_thread = if foreground.0.is_null() {
0
} else {
GetWindowThreadProcessId(foreground, None)
};
let attached = foreground_thread != 0
&& foreground_thread != current_thread
&& AttachThreadInput(current_thread, foreground_thread, true).as_bool();
let _ = ShowWindow(hwnd, SW_RESTORE);
let _ = BringWindowToTop(hwnd);
if !SetForegroundWindow(hwnd).as_bool() {
eprintln!("[window] foreground 활성화 실패");
}
let _ = SetFocus(Some(hwnd));
if attached {
let _ = AttachThreadInput(current_thread, foreground_thread, false);
}
} }
Ok(()) Ok(())
} }
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "CodeAssist", "productName": "CodeAssist",
"version": "0.1.0", "version": "0.1.4",
"identifier": "com.codeassist.app", "identifier": "com.codeassist.app",
"build": { "build": {
"beforeDevCommand": { "cwd": "../../2_frontend", "script": "npm run dev" }, "beforeDevCommand": { "cwd": "../../2_frontend", "script": "npm run dev" },
+58
View File
@@ -1,6 +1,8 @@
# CodeAssist 전용 OpenCode 서버 (opencode/ 폴더에서 `opencode serve --port 4096`) # CodeAssist 전용 OpenCode 서버 (opencode/ 폴더에서 `opencode serve --port 4096`)
OPENCODE_BASE_URL=http://localhost:4096 OPENCODE_BASE_URL=http://localhost:4096
OPENCODE_AGENT=codeassist OPENCODE_AGENT=codeassist
# 이미지 요청만 이 모델로 (로컬 OpenRouter). 고객사는 비우고 AAF_FABRIX_VISION_MODEL_ID 사용
OPENCODE_VISION_MODEL=openrouter/google/gemma-4-31b-it # 고객사는 gateway/605 (deploy.sh 가 채움)
# 토큰 서명 키 (비우면 data/.auth_secret 자동 생성) # 토큰 서명 키 (비우면 data/.auth_secret 자동 생성)
AUTH_SECRET= AUTH_SECRET=
@@ -12,6 +14,62 @@ DB_USER=
DB_PASSWORD= DB_PASSWORD=
DB_NAME= DB_NAME=
DB_SCHEMA=codeassist DB_SCHEMA=codeassist
# SSL: prefer(기본, 되면 씀) / require / disable. 고객사 내부 PG 는 SSL 미지원이라 prefer 면 알아서 평문
DB_SSLMODE=prefer
# 프론트 origin (dev 는 Vite proxy 라 안 탐. Tauri 빌드용) # 프론트 origin (dev 는 Vite proxy 라 안 탐. Tauri 빌드용)
CORS_ORIGINS=http://localhost:15173,http://tauri.localhost,tauri://localhost CORS_ORIGINS=http://localhost:15173,http://tauri.localhost,tauri://localhost
# 채팅 스트림 타임아웃(초) — Gemma4 느릴 때 올림. 첫 이벤트까지 / 한 턴 전체
STREAM_FIRST_EVENT_TIMEOUT_S=300
STREAM_TURN_TIMEOUT_S=600
# ── 사내 LLM(FabriX) — 고객사 전용. 개발(OpenRouter)에선 전부 비워둠 ──
# OpenCode 는 opencode/opencode.json 을 FabriX 용으로 렌더해서(opencode/render_opencode.py) 이 서버의 /api/ito 로 붙음.
AAF_FABRIX_BASE_URL=
AAF_FABRIX_MODEL_ID=581
AAF_FABRIX_MODELS=581:GaussO Think,339:GaussO Flash,605:Gemma4
AAF_FABRIX_CLIENT_KEY=
AAF_FABRIX_OPENAPI_TOKEN=
AAF_FABRIX_USER_EMAIL=
# 이미지 붙은 요청만 이 모델로. Gemma4 가 텍스트엔 너무 느려서(안녕 94s vs 339 0.7s) 기본은 339
AAF_FABRIX_VISION_MODEL_ID=605
# 게이트웨이마다 다를 수 있는 것 — 보통 비워둠(401 나면 자동으로 다른 형식도 시도함)
AAF_FABRIX_CLIENT_HEADER=
AAF_FABRIX_TOKEN_PREFIX=bearer
AAF_FABRIX_MAX_TOKENS=
AAF_RELAY_STREAM_USAGE=
# FabriX 스트림 타임아웃(초) — 조각 사이 무수신 / 전체. 기본 300 / 600
AAF_FABRIX_READ_TIMEOUT_S=300
AAF_FABRIX_TOTAL_TIMEOUT_S=600
# OpenCode → 이 서버 사이 잠금. 같은 PC 안이면 비워도 됨. 서버를 바깥에 열면 반드시 랜덤 문자열
AAF_GATEWAY_KEY=
# OpenCode 가 붙을 이 서버 포트 (render_opencode.py 가 씀)
BACKEND_PORT=8001
# ── SAP 조회 MCP (고객사 전용, -12 에 따로 띄움. ABAP_OPENCODE mcp.bundle.cjs 재활용) ──
# MCP_API_KEY 가 있으면 render_opencode.py 가 OpenCode 에 sap-icf 를 켬. 비우면 꺼짐(로컬).
MCP_PORT=8888
MCP_API_KEY=
# 아래는 MCP 프로세스가 읽는 SAP 접속값 — ABAP_OPENCODE bare/.env 와 같은 키
SAP_HOST_ICF=
SAP_USERNAME_ICF=
SAP_PASSWORD_ICF=
SAP_CLIENT_ICF=100
SAP_VERIFY_SSL_ICF=false
SAP_API_BASE_ICF=
# ── ABAP 소스 인덱스(ABAP_INDEXING, 별도 서버 :8100) — OpenCode 툴 abap_index_* 가 씀 ──
# 비우면 기본 127.0.0.1:8100. 서버가 없어도 앱은 돌아감(툴이 "없음"으로 답하고 생성 코드로).
ABAP_INDEX_URL=http://127.0.0.1:8100
# ── Langfuse(LLM 관측, 자체 호스팅 deploy/langfuse/) — HOST 비우면 안 보냄 ──
LANGFUSE_HOST=
LANGFUSE_PUBLIC_KEY=
LANGFUSE_SECRET_KEY=
# Phoenix(도커 없이 뜨는 관측 서버, deploy/phoenix/) — 주소만. 비우면 안 보냄. 예: http://127.0.0.1:8915
PHOENIX_HOST=
# /phoenix/ 관리자 화면 비번(브라우저 Basic 인증, 아이디는 아무거나). 비우면 잠금 없음
PHOENIX_UI_PASSWORD=
# 1 이면 FabriX 호출 원문(프롬프트 전체·응답)도 별도 fabrix 트레이스로. 기본 0 — 질문 하나 = 행 하나 유지
LANGFUSE_TRACE_GATEWAY=0
+10
View File
@@ -5,3 +5,13 @@ __pycache__/
*.pyc *.pyc
staticfiles/ staticfiles/
.pytest_cache/ .pytest_cache/
# 고객사 소스 위키(ABAP_INDEXING 결과물) — 고객 데이터라 git 밖
opencode/wiki/
deploy/langfuse/.env
deploy/langfuse/docker-compose.override.yml
# render_opencode.py 가 환경마다 만드는 파일 — 서버마다 다름
opencode/opencode.json
deploy/docker/.env
deploy/phoenix/.env
+77
View File
@@ -75,3 +75,80 @@ opencode/ OpenCode workspace — AGENTS.md · opencode.json · .opencode/agen
docs-lib/ OpenCode SDK 1.18.6 타입 (API 진실원천) docs-lib/ OpenCode SDK 1.18.6 타입 (API 진실원천)
tests/ pytest tests/ pytest
``` ```
## 고객사 = 사내 LLM(FabriX)
개발은 OpenRouter 직결이고, 고객사에선 ABAP_OPENCODE 와 같은 방식으로 **FabriX** 를 씀. OpenCode 는 LLM 을 직접 안 부르고 이 서버의 `/api/ito`(OpenAI 호환) 로 붙고, `apps/gateway` 가 FabriX 인증 헤더를 얹어 그대로 흘림.
```
OpenCode ──OpenAI 호환──▶ Django /api/ito/chat/completions ──x-llm-model-id / x-openapi-token / x-generative-ai-client──▶ FabriX
```
```bash
# 1) .env 에 AAF_FABRIX_* 채움 (.env.example 의 사내 LLM 블록. 키 이름은 ABAP_OPENCODE 와 같음)
# 2) OpenCode 설정을 FabriX 용으로 렌더 (opencode/opencode.json 덮어씀)
.venv/bin/python opencode/render_opencode.py
# 3) OpenCode 는 키 없이 그냥 띄움 (OPENROUTER_API_KEY 불필요)
cd opencode && opencode serve --hostname 127.0.0.1 --port 4096
# 4) 확인
curl http://localhost:8001/api/ito/healthcheck
curl http://localhost:8001/api/ito/models
```
- `AAF_FABRIX_MODELS="605:Gemma4,339:GaussO Flash,581:GaussO Think"` 처럼 두면 OpenCode 화면에서 모델을 고를 수 있고, 고른 id 가 그대로 `x-llm-model-id` 로 감.
- 고객사 게이트웨이가 토큰 형식(Bearer/날것)·클라이언트 헤더 이름을 서버마다 다르게 받아서, 401 이면 다른 조합을 자동으로 더 시도하고 통과한 걸 기억함.
- 설정이 비어 있어도 서버는 뜨고, `/api/ito/chat/completions` 만 503 으로 뭐가 빠졌는지 알려줌.
- ABAP_OPENCODE 의 `apps_ito` 를 통째로 안 가져온 이유: 그쪽은 11k 줄 + DB 테이블 + langgraph 등 의존성 15개인데 여기 필요한 건 통과 중계뿐. 사용자별 키(IP 마스터)는 아직 없음 — 서비스 키 하나로 감.
- 개발로 되돌리기: `git checkout opencode/opencode.json`.
## SAP 조회 MCP 붙이기 (고객사, -12 에 따로 띄움)
컨테이너끼리(-12↔-13) 통신은 금지라 -13 의 MCP 를 안 빌리고 -12 에 하나 더 띄움. 코드는 ABAP_OPENCODE 의 번들 한 파일(`mcp.bundle.cjs`) 그대로.
```bash
# PC: -13 에서 번들 꺼내 -12 로 (환경값은 -13 bare/.env 의 SAP_*·MCP_API_KEY 를 손으로 옮김)
scp -P 8916 root@10.196.81.34:/www/abap-ito/web/MCP/code/dist/mcp.bundle.cjs .
scp -P 8912 mcp.bundle.cjs root@10.196.81.34:/www/
# -12
cd /www/ABAP_CODE_ASSISTANT/5_django_backend
vi .env # MCP_PORT=8888, MCP_API_KEY, SAP_HOST_ICF/USERNAME/PASSWORD/CLIENT/VERIFY_SSL/API_BASE 채움 (.env.example 의 SAP 블록)
set -a; . ./.env; set +a
mkdir -p /www/mcp && cp /www/mcp.bundle.cjs /www/mcp/
(cd /www/mcp && nohup node mcp.bundle.cjs > /www/ABAP_CODE_ASSISTANT/5_django_backend/logs/mcp.log 2>&1 &)
.venv/bin/python opencode/render_opencode.py # MCP_API_KEY 있으면 sap-icf enabled:true 로 렌더
pkill -f "opencode-bin serve"
(cd opencode && nohup /www/opencode-bin serve --hostname 127.0.0.1 --port 4096 > ../logs/opencode.log 2>&1 &)
# 확인 — 도구 목록에 sap 도구 6개
curl -s -X POST http://127.0.0.1:8888/mcp -H "Authorization: Bearer $MCP_API_KEY" -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | head -c 400
```
- 로컬 개발에선 `MCP_API_KEY` 를 비워두면 `sap-icf``enabled:false` 로 렌더돼 OpenCode 가 MCP 를 안 찾음.
- MCP 가 zai 모드로 뜨는지는 `logs/mcp.log``mode=zai` 찍히는 걸로. 고객사 SAP 은 zdict 가 아니라 ZAI_ICF 라 `SAP_API_BASE_ICF` 를 -13 값과 같게.
## ABAP 소스 인덱스 붙이기 (출처 있는 코드)
`ABAP_INDEXING` 레포의 질의 서버(:8100)를 OpenCode 커스텀 툴로 붙임 — `opencode/.opencode/tools/abap_index.ts` (툴 3개: `abap_index_search`·`abap_index_chunk`·`abap_index_source`). 에이전트는 코드 질문에 인덱스를 먼저 찾고, 코드 위에 `[출처: 프로그램 / unit L줄]` 을 적음. 없으면 `[출처: 없음 — 생성 코드]`.
```bash
# 인덱스 서버 (ABAP_INDEXING 레포, data/index.db 가 있어야 함)
cd ../ABAP_INDEXING && .venv/Scripts/python -m query.api # 127.0.0.1:8100
# CodeAssist 쪽: .env 의 ABAP_INDEX_URL (기본 그대로면 됨) → OpenCode 재시작. 툴 목록 확인:
curl -s http://127.0.0.1:4096/config 2>/dev/null | grep -o abap_index_[a-z]* | sort -u
```
- 인덱스 서버가 없으면 툴이 "인덱스 조회 실패"를 돌려주고 에이전트는 생성 코드로 답함. 앱은 안 죽음.
- `opencode/.opencode/package.json`(`@opencode-ai/plugin` 의존)은 그 폴더 `.gitignore` 에 걸려 git 에 없음. 고객사엔 `.opencode/` 폴더째(node_modules 포함, 약 수 MB) 같이 옮겨야 툴이 로드됨. 없으면 OpenCode 가 툴 파일을 import 못 해 조용히 빠짐 — `/experimental/tool/ids` 로 확인.
- 고객사(-12): ABAP_INDEXING 을 -12 에 같이 올리고(`data/index.db` 포함, 약 14MB) 8100 으로 띄움. 오프라인 wheels 는 fastapi·uvicorn 이 이미 있어 재활용 가능.
## 고객사 배포 한 방 — `deploy.sh`
고객사 GHE 저장소의 `code-assistant/` 폴더로 관리(브랜치 아님 — -12·-13 이 각자 폴더만 씀). PC 에서 push → -12 에서:
```bash
cd /www/repo && git pull
cd code-assistant/5_django_backend && bash deploy.sh
```
`deploy.sh` = `.env` 새 키 채움(있으면 유지) → `migrate``seed/snippets.db` 있으면 import → OpenCode 설정 렌더 → OpenCode·Django 재시작 → health·모델·툴 확인.
처음 한 번은 `.venv`·`.env`·`opencode/.opencode/node_modules` 를 옛 폴더(`/www/ABAP_CODE_ASSISTANT/5_django_backend`)에서 복사해 온 뒤 실행.
+53 -5
View File
@@ -20,12 +20,14 @@ import asyncio
import json import json
import logging import logging
import time import time
from datetime import datetime, timezone
from django.conf import settings from django.conf import settings
from django.http import StreamingHttpResponse from django.http import StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from apps.accounts.authentication import user_from_token from apps.accounts.authentication import user_from_token
from apps.gateway import langfuse
from asgiref.sync import sync_to_async from asgiref.sync import sync_to_async
from common.envelope import json_error from common.envelope import json_error
from common.opencode_service import opencode_service from common.opencode_service import opencode_service
@@ -37,10 +39,11 @@ log = logging.getLogger(__name__)
ALLOWED_IMAGE_TYPES = {"image/png", "image/jpeg", "image/webp"} ALLOWED_IMAGE_TYPES = {"image/png", "image/jpeg", "image/webp"}
MAX_IMAGES = 4 MAX_IMAGES = 4
TURN_TIMEOUT_S = 600 # OpenCode 답변 상한 # 타임아웃은 .env 로 조정 (settings.STREAM_*). Gemma4 가 큐 밀리면 첫 토큰도 늦어서 넉넉히.
TURN_TIMEOUT_S = settings.STREAM_TURN_TIMEOUT_S # OpenCode 답변 상한 (기본 600)
# prompt 를 받았는데 이 세션 이벤트가 하나도 안 오면 OpenCode 가 조용히 실패한 것 # prompt 를 받았는데 이 세션 이벤트가 하나도 안 오면 OpenCode 가 조용히 실패한 것
# (예: 다른 프로젝트의 세션 — 로그에만 "prompt_async failed" 남고 session.error 안 옴) # (예: 다른 프로젝트의 세션 — 로그에만 "prompt_async failed" 남고 session.error 안 옴)
FIRST_EVENT_TIMEOUT_S = 60 FIRST_EVENT_TIMEOUT_S = settings.STREAM_FIRST_EVENT_TIMEOUT_S # 기본 300
KEEPALIVE_S = 15 KEEPALIVE_S = 15
_END = object() # 큐 종료 표시 _END = object() # 큐 종료 표시
@@ -84,7 +87,12 @@ def _prompt_payload(req: dict) -> dict:
for i, img in enumerate(req["images"]): for i, img in enumerate(req["images"]):
ext = img["mediaType"].split("/")[1] ext = img["mediaType"].split("/")[1]
parts.append({"type": "file", "mime": img["mediaType"], "filename": f"image-{i + 1}.{ext}", "url": img["data"]}) parts.append({"type": "file", "mime": img["mediaType"], "filename": f"image-{i + 1}.{ext}", "url": img["data"]})
return {"agent": settings.OPENCODE_AGENT, "parts": parts} payload: dict = {"agent": settings.OPENCODE_AGENT, "parts": parts}
# 이미지 있으면 vision 모델로 — 텍스트는 기본 모델(빠름). 고객사 FabriX 는 게이트웨이가 따로 분기.
if req["images"] and settings.OPENCODE_VISION_MODEL and "/" in settings.OPENCODE_VISION_MODEL:
provider, model = settings.OPENCODE_VISION_MODEL.split("/", 1)
payload["model"] = {"providerID": provider, "modelID": model}
return payload
# ── OpenCode 이벤트 → 우리 이벤트 ──────────────────────────────── # ── OpenCode 이벤트 → 우리 이벤트 ────────────────────────────────
@@ -128,8 +136,12 @@ class TurnState:
if mid in self.user_message_ids and mid not in self.assistant_message_ids: if mid in self.user_message_ids and mid not in self.assistant_message_ids:
return out return out
pid = props.get("partID", "") pid = props.get("partID", "")
if self.part_types.get(pid) != "text": ptype = self.part_types.get(pid)
return out # reasoning/tool 파트, 또는 아직 타입 모름(최종 스냅샷이 메워줌) if ptype == "reasoning":
out.append(("step", {"id": pid, "kind": "reasoning", "text": props["delta"]}))
return out
if ptype != "text":
return out # tool 파트, 또는 아직 타입 모름(최종 스냅샷이 메워줌)
delta = props["delta"] delta = props["delta"]
if pid not in self.text_by_part: if pid not in self.text_by_part:
self.part_order.append(pid) self.part_order.append(pid)
@@ -142,6 +154,11 @@ class TurnState:
part = props.get("part") or {} part = props.get("part") or {}
if part.get("id"): if part.get("id"):
self.part_types[part["id"]] = part.get("type", "") self.part_types[part["id"]] = part.get("type", "")
if part.get("type") == "tool":
# 도구 호출 진행 — 화면 "생각 과정" 에 이름·상태만. 입력/출력은 안 보냄(크고 사용자 관심 밖)
st = part.get("state") or {}
out.append(("step", {"id": part.get("id", ""), "kind": "tool", "tool": part.get("tool", ""), "status": st.get("status", ""), "title": st.get("title") or ""}))
return out
if part.get("type") != "text" or part.get("synthetic") or part.get("ignored"): if part.get("type") != "text" or part.get("synthetic") or part.get("ignored"):
return out return out
mid = part.get("messageID", "") mid = part.get("messageID", "")
@@ -175,6 +192,21 @@ class TurnState:
return out return out
def _tool_spans(tid: str, root: dict, tool_parts: list[dict]) -> list[dict]:
"""OpenCode 도구 파트 → Langfuse 자식 span. 출력은 앞 4KB 만(원문은 OpenCode 에 있음)."""
out = []
for p in tool_parts:
st = p.get("state") or {}
t = st.get("time") or {}
out.append(langfuse.tool_span(
tid, p.get("tool") or "tool", parent=root, input=st.get("input"), title=st.get("title") or "",
output=(st.get("output") or "")[:4000] or None,
start=langfuse.ms_iso(t.get("start")), end=langfuse.ms_iso(t.get("end")),
error=st.get("error") if st.get("status") == "error" else None,
))
return out
def _real_title(raw) -> str | None: def _real_title(raw) -> str | None:
"""OpenCode 기본 제목("New session - 2026-…")은 제목이 아님 → None.""" """OpenCode 기본 제목("New session - 2026-…")은 제목이 아님 → None."""
t = (raw or "").strip() t = (raw or "").strip()
@@ -195,12 +227,15 @@ async def _finalize(session: ChatSession, state: TurnState, started: float, *, f
content = state.accumulated() content = state.accumulated()
usage: dict | None = None usage: dict | None = None
title = state.title title = state.title
tool_parts: list[dict] = []
try: try:
msgs = await opencode_service.list_messages_a(session.id) or [] msgs = await opencode_service.list_messages_a(session.id) or []
assistant = [m for m in msgs if (m.get("info") or {}).get("role") == "assistant"] assistant = [m for m in msgs if (m.get("info") or {}).get("role") == "assistant"]
if assistant: if assistant:
info = assistant[-1]["info"] info = assistant[-1]["info"]
parts = assistant[-1].get("parts") or [] parts = assistant[-1].get("parts") or []
# 이 턴의 assistant 메시지가 여러 개(도구 왕복마다 하나)라 도구 파트는 전부 모음
tool_parts = [p for m in assistant for p in (m.get("parts") or []) if p.get("type") == "tool"]
full = "".join(p.get("text", "") for p in parts if p.get("type") == "text" and not p.get("synthetic")) full = "".join(p.get("text", "") for p in parts if p.get("type") == "text" and not p.get("synthetic"))
if full: if full:
content = full content = full
@@ -233,6 +268,19 @@ async def _finalize(session: ChatSession, state: TurnState, started: float, *, f
if title: if title:
session.title_llm = title[:200] session.title_llm = title[:200]
await session.asave(update_fields=["is_generating", "title_llm", "updated_at"]) await session.asave(update_fields=["is_generating", "title_llm", "updated_at"])
# 관측: 목록 한 줄 = 이 채팅(질문·답·토큰). 트리 = 답 만들며 부른 도구들(SAP 조회·위키 read…) 순서대로.
if langfuse.enabled():
tid = f"{session.id}-{int(started * 1000)}"
user_email = await sync_to_async(lambda: session.user.email)()
t0 = datetime.fromtimestamp(started, timezone.utc).isoformat()
root = langfuse.trace(
tid, "chat", userId=user_email, sessionId=session.id, input=state.user_text, output=content,
tags=["codeassist"], start=t0, end=langfuse.now_iso(),
usage=langfuse.usage_of(usage["input"], usage["output"]) if usage else None,
metadata={"elapsed_ms": usage["elapsed_ms"]} if usage else {}, error=failed,
)
langfuse.send_later([root, *_tool_spans(tid, root, tool_parts)])
return usage, title return usage, title
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class GatewayConfig(AppConfig):
name = "apps.gateway"
verbose_name = "사내 LLM(FabriX) 게이트웨이"
+193
View File
@@ -0,0 +1,193 @@
"""FabriX(사내 LLM, OpenAI 호환 Serving) 접속 규칙 — 순수 함수만. Django 안 봄.
ABAP_OPENCODE `apps_ito/aaf` passthrough 중계에서 CodeAssist 필요한 규칙만 옮겼음:
- 와이어는 OpenAI chat/completions 그대로. 인증은 Authorization 아니라 커스텀 헤더 3.
- 실제 모델은 body model 아니라 `x-llm-model-id` 헤더가 고름. body model 고정 경로.
- 고객사 게이트웨이가 토큰 형식(Bearer/날것)·클라이언트 헤더 이름을 서버마다 다르게 받아서,
401 이면 다른 조합으로 번씩 찔러보고 통과한 조합을 기억함(2026-09-16 ABAP 실측).
"""
from __future__ import annotations
from dataclasses import dataclass, field, replace
DEFAULT_BODY_MODEL = "/mnt/models" # body.model — 공식 예제 고정값. 모델 선택은 헤더가 함
TOKEN_HDR = "x-openapi-token"
EMAIL_HDR = "x-generative-ai-user-email"
MODEL_HDR = "x-llm-model-id"
CLIENT_HDRS = ("x-generative-ai-client", "x-fabrix-client") # 고객사는 앞 것만 받음(뒤는 401)
ENV_KEYS = (
"AAF_FABRIX_BASE_URL", # …/openapi/llm 까지. 뒤에 /chat/completions 붙임
"AAF_FABRIX_MODEL_ID", # 기본 모델 id (x-llm-model-id)
"AAF_FABRIX_MODELS", # "605:Gemma4,339:GaussO Flash,581:GaussO Think" — 화면에서 고를 수 있는 목록
"AAF_FABRIX_CLIENT_KEY",
"AAF_FABRIX_OPENAPI_TOKEN",
"AAF_FABRIX_USER_EMAIL",
"AAF_FABRIX_CLIENT_HEADER", # 기본 x-generative-ai-client
"AAF_FABRIX_TOKEN_PREFIX", # "bearer" 면 토큰 앞에 "Bearer " 붙임. 기본은 날것
"AAF_FABRIX_MODEL", # body.model. 기본 /mnt/models
"AAF_FABRIX_MAX_TOKENS", # 있으면 max_completion_tokens 로 실음
"AAF_RELAY_STREAM_USAGE", # "1" 이면 stream_options.include_usage — 제공자가 거부하면 끔
"AAF_GATEWAY_KEY", # OpenCode 가 Authorization: Bearer 로 보내는 키. 비우면 검사 안 함
"AAF_FABRIX_VISION_MODEL_ID", # 이미지가 붙은 요청만 이 모델로(Gemma4). 비우면 분기 안 함
"AAF_FABRIX_READ_TIMEOUT_S", # 스트림 조각 사이 무수신 한계(기본 300). Gemma 가 중간에 멈추는 날 대비
"AAF_FABRIX_TOTAL_TIMEOUT_S", # 요청 전체 상한(기본 600)
)
def has_image(payload: dict) -> bool:
"""OpenAI 형식 messages 안에 image_url 파트가 하나라도 있으면 True."""
for m in payload.get("messages") or []:
content = m.get("content") if isinstance(m, dict) else None
if isinstance(content, list) and any(
isinstance(p, dict) and p.get("type") == "image_url" for p in content
):
return True
return False
def parse_models(spec: str) -> dict[str, str]:
""""339:GaussO Flash,581:GaussO Think"{"339": "GaussO Flash", "581": "GaussO Think"}."""
out: dict[str, str] = {}
for item in (x.strip() for x in (spec or "").split(",")):
if not item:
continue
mid, _, name = item.partition(":")
if mid.strip():
out[mid.strip()] = name.strip() or mid.strip()
return out
def token_value(token: str, prefix: str = "") -> str:
"""x-openapi-token 값. 저장값에 Bearer 가 붙어 있어도 떼고, prefix=bearer 일 때만 다시 붙임."""
t = (token or "").strip()
if t.lower().startswith("bearer "):
t = t[7:].strip()
return f"Bearer {t}" if t and prefix.strip().lower() == "bearer" else t
@dataclass(frozen=True)
class FabrixConfig:
base_url: str = ""
model_id: str = ""
client_key: str = ""
token: str = ""
email: str = ""
client_header: str = CLIENT_HDRS[0]
token_prefix: str = ""
body_model: str = DEFAULT_BODY_MODEL
models: dict[str, str] = field(default_factory=dict)
max_tokens: int | None = None
stream_usage: bool = False
gateway_key: str = ""
vision_model_id: str = "" # 이미지 있을 때만 쓰는 모델. Gemma 가 느려서 텍스트는 기본 모델로
connect_timeout_s: float = 10.0
read_timeout_s: float = 300.0 # 스트림 조각 사이 무수신 한계
total_timeout_s: float = 600.0
@classmethod
def from_env(cls, env: dict[str, str]) -> "FabrixConfig":
g = lambda k: (env.get(k) or "").strip() # noqa: E731
max_tokens = g("AAF_FABRIX_MAX_TOKENS")
return cls(
base_url=g("AAF_FABRIX_BASE_URL").rstrip("/"),
model_id=g("AAF_FABRIX_MODEL_ID"),
client_key=g("AAF_FABRIX_CLIENT_KEY"),
token=g("AAF_FABRIX_OPENAPI_TOKEN"),
email=g("AAF_FABRIX_USER_EMAIL"),
client_header=g("AAF_FABRIX_CLIENT_HEADER") or CLIENT_HDRS[0],
token_prefix=g("AAF_FABRIX_TOKEN_PREFIX"),
body_model=g("AAF_FABRIX_MODEL") or DEFAULT_BODY_MODEL,
models=parse_models(g("AAF_FABRIX_MODELS")),
max_tokens=int(max_tokens) if max_tokens.isdigit() else None,
stream_usage=g("AAF_RELAY_STREAM_USAGE") == "1",
gateway_key=g("AAF_GATEWAY_KEY"),
vision_model_id=g("AAF_FABRIX_VISION_MODEL_ID"),
read_timeout_s=float(g("AAF_FABRIX_READ_TIMEOUT_S") or 300),
total_timeout_s=float(g("AAF_FABRIX_TOTAL_TIMEOUT_S") or 600),
)
def missing(self) -> list[str]:
"""비어 있으면 안 되는 설정 이름. 비어 있는 채로 부르면 정체불명 401/404 라 미리 막음."""
need = {
"AAF_FABRIX_BASE_URL": self.base_url,
"AAF_FABRIX_MODEL_ID": self.model_id,
"AAF_FABRIX_CLIENT_KEY": self.client_key,
"AAF_FABRIX_OPENAPI_TOKEN": self.token,
}
return [k for k, v in need.items() if not v]
@property
def url(self) -> str:
return self.base_url.rstrip("/") + "/chat/completions"
def model_list(self) -> dict[str, str]:
"""화면에 보여줄 모델 목록. AAF_FABRIX_MODELS 없으면 기본 모델 하나."""
return dict(self.models) or {self.model_id: "FabriX"}
def pick_model_id(self, requested: str) -> str:
"""OpenCode 가 보낸 model 이 허용 목록에 있으면 그것, 아니면 기본 모델."""
rm = (requested or "").strip()
return rm if rm and rm in self.models else self.model_id
def headers(self, model_id: str | None = None) -> dict[str, str]:
return {
"Content-Type": "application/json",
MODEL_HDR: model_id or self.model_id,
self.client_header: self.client_key,
TOKEN_HDR: token_value(self.token, self.token_prefix),
EMAIL_HDR: self.email, # 빈 값이라도 실음 — 공식 예제가 그럼
}
def prepare(self, payload: dict) -> tuple[dict, dict[str, str]]:
"""OpenCode 가 보낸 OpenAI 요청 → FabriX 로 보낼 (body, headers)."""
body = dict(payload)
model_id = self.pick_model_id(str(payload.get("model") or ""))
if self.vision_model_id and has_image(payload):
model_id = self.vision_model_id # 이미지 있으면 무조건 vision 모델(느려도 이미지는 얘만 읽음)
headers = self.headers(model_id)
body["model"] = self.body_model
if body.get("stream") and self.stream_usage:
so = dict(body.get("stream_options") or {})
so["include_usage"] = True
body["stream_options"] = so
if self.max_tokens:
body.setdefault("max_completion_tokens", self.max_tokens)
return body, headers
def with_models(self, models: dict[str, str]) -> "FabrixConfig":
return replace(self, models=models)
Variant = tuple[str, str | None] # (토큰 접두 "bearer"|"raw", 클라이언트 헤더 이름)
def auth_variants(headers: dict[str, str], last_ok: Variant | None = None) -> list[tuple[Variant, dict[str, str]]]:
"""설정된 헤더에서 시작해 (Bearer/날것) × (클라이언트 헤더 이름) 조합을 만듦.
순서: 마지막에 통과한 조합 설정된 조합 나머지. 토큰이 없으면 원본 하나만."""
tok = headers.get(TOKEN_HDR)
if not tok:
return [(("raw", None), headers)]
raw = tok[7:].strip() if tok.lower().startswith("bearer ") else tok.strip()
client_val = next((headers[h] for h in CLIENT_HDRS if h in headers), None)
client_names: tuple[str | None, ...] = CLIENT_HDRS if client_val is not None else (None,)
variants: dict[Variant, dict[str, str]] = {}
for prefix in ("bearer", "raw"):
for chdr in client_names:
h = {k: v for k, v in headers.items() if k not in CLIENT_HDRS}
h[TOKEN_HDR] = f"Bearer {raw}" if prefix == "bearer" else raw
if chdr:
h[chdr] = client_val or ""
variants[(prefix, chdr)] = h
current: Variant = (
"bearer" if tok.lower().startswith("bearer ") else "raw",
next((h for h in CLIENT_HDRS if h in headers), None),
)
order: list[Variant] = [current]
if last_ok and last_ok in variants and last_ok != current:
order.insert(0, last_ok)
order += [k for k in variants if k not in order]
return [(k, variants[k]) for k in order]
+263
View File
@@ -0,0 +1,263 @@
"""LLM 관측 전송 — Langfuse 또는 Phoenix 로, SDK 없이 OTLP/HTTP JSON 한 방 (docs-lib/langfuse.md, docs-lib/phoenix.md).
대상은 설정으로 고름( 켜도 ):
LANGFUSE_HOST {host}/api/public/otel/v1/traces (Basic 인증, langfuse.* 속성)
PHOENIX_HOST {host}/v1/traces (인증 없음, OpenInference 속성: openinference.span.kind, input.value )
Phoenix JSON 받아서(415, 2026-09-22 실측) protobuf 바꿔 보냄 opentelemetry-proto 필요
속성은 벌을 같은 span 같이 실음 각자 자기 것만 읽고 나머진 metadata 떨어짐.
v4 /api/public/ingestion 막혀서(score ) OTel 엔드포인트로 . 트레이스 하나 = 루트 span(trace 속성) + 자식 span(generation).
LANGFUSE_HOST 비어 있으면 전부 no-op. 보내는 fire-and-forget: 실패해도 채팅엔 영향 0, 로그만.
군데서 부름:
- apps/chat/stream.py _finalize 사용자 단위 trace(누가·어느 세션·질문·최종 ·토큰·시간)
- apps/gateway/views.py FabriX 호출 단위 generation(모델·프롬프트 원문·응답·상태)
둘은 서로 모름(OpenCode 사이에 있어 사용자 정보가 게이트웨이까지 ). 나중에 잇고 싶으면 sessionId 대조.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import logging
import time
import uuid
from datetime import datetime, timezone
import httpx
from django.conf import settings
log = logging.getLogger(__name__)
TRANSPORT: httpx.AsyncBaseTransport | None = None # 테스트가 MockTransport 꽂는 자리
_pending: set[asyncio.Task] = set() # GC 에 안 먹히게 잡아둠
def enabled() -> bool:
return bool(settings.LANGFUSE.get("host") or settings.LANGFUSE.get("phoenix"))
def _oi(kind: str, *, input=None, output=None, model: str = "", usage: dict | None = None,
userId: str = "", sessionId: str = "", tool: str = "", metadata: dict | None = None) -> dict:
"""OpenInference(Phoenix) 속성 한 벌. 값이 없으면 _attr 이 걸러줌."""
js = lambda v: v if v is None or isinstance(v, str) else json.dumps(v, ensure_ascii=False) # noqa: E731
return {
"openinference.span.kind": kind,
"input.value": js(input),
"input.mime_type": None if input is None or isinstance(input, str) else "application/json",
"output.value": js(output),
"output.mime_type": None if output is None or isinstance(output, str) else "application/json",
"llm.model_name": model,
"llm.token_count.prompt": (usage or {}).get("input"),
"llm.token_count.completion": (usage or {}).get("output"),
"llm.token_count.total": (usage or {}).get("total"),
"session.id": sessionId,
"user.id": userId,
"tool.name": tool,
"metadata": js(metadata) if metadata else None,
}
def now_iso() -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
def _trace_hex(trace_id: str) -> str:
"""아무 문자열 → OTel traceId(16바이트 hex). 같은 문자열이면 같은 trace 로 묶임."""
return hashlib.sha256(trace_id.encode()).hexdigest()[:32]
def _nanos(iso_or_none: str | None) -> str:
if not iso_or_none:
return str(time.time_ns())
dt = datetime.fromisoformat(iso_or_none.replace("Z", "+00:00"))
return str(int(dt.timestamp() * 1_000_000_000))
def _attr(k: str, v) -> dict | None:
if v is None or v == "" or v == {} or v == []:
return None
if isinstance(v, bool):
return {"key": k, "value": {"boolValue": v}}
if isinstance(v, int):
return {"key": k, "value": {"intValue": str(v)}}
if isinstance(v, float):
return {"key": k, "value": {"doubleValue": v}}
if isinstance(v, str):
return {"key": k, "value": {"stringValue": v}}
return {"key": k, "value": {"stringValue": json.dumps(v, ensure_ascii=False)}}
def _span(trace_id: str, name: str, attrs: dict, *, start: str | None, end: str | None, parent: str | None, error: str | None) -> dict:
span = {
"traceId": _trace_hex(trace_id),
"spanId": uuid.uuid4().hex[:16],
"name": name,
"kind": 1, # INTERNAL
"startTimeUnixNano": _nanos(start),
"endTimeUnixNano": _nanos(end),
"attributes": [a for a in (_attr(k, v) for k, v in attrs.items()) if a],
"status": {"code": 2, "message": error} if error else {"code": 1},
}
if parent:
span["parentSpanId"] = parent
return span
def trace(trace_id: str, name: str, *, userId: str = "", sessionId: str = "", input=None, output=None,
metadata: dict | None = None, tags: list[str] | None = None, start: str | None = None, end: str | None = None,
usage: dict | None = None, model: str = "", error: str | None = None) -> dict:
"""루트 span. trace 속성(이름·사용자·세션·태그)은 여기 실림.
usage 주면 루트 자체가 generation 목록 = 질문//토큰, 밑에 도구 호출만 트리로."""
attrs = {
"langfuse.trace.name": name,
"langfuse.observation.type": "generation" if usage else "span",
"langfuse.observation.model.name": model,
"langfuse.observation.usage_details": usage,
"langfuse.observation.level": "ERROR" if error else "DEFAULT",
"langfuse.observation.status_message": error or "",
"langfuse.user.id": userId,
"langfuse.session.id": sessionId,
"langfuse.trace.input": input,
"langfuse.trace.output": output,
"langfuse.observation.input": input, # 루트 span 본문에도 — 트레이스 화면이 루트 span 의 입출력을 보여줌(실측)
"langfuse.observation.output": output,
"langfuse.trace.tags": tags,
**{f"langfuse.trace.metadata.{k}": v for k, v in (metadata or {}).items()},
**_oi("LLM" if usage else "CHAIN", input=input, output=output, model=model, usage=usage,
userId=userId, sessionId=sessionId, metadata={**(metadata or {}), "tags": tags} if (metadata or tags) else None),
}
return _span(trace_id, name, attrs, start=start, end=end, parent=None, error=error)
def tool_span(trace_id: str, name: str, *, parent: dict, input=None, output=None, title: str = "",
start: str | None = None, end: str | None = None, error: str | None = None) -> dict:
"""도구 호출 하나(SAP 조회·위키 read·grep…). 트리에서 루트 밑에 순서대로 보임."""
inherited = {a["key"]: a["value"].get("stringValue") for a in parent.get("attributes", [])
if a["key"] in ("langfuse.user.id", "langfuse.session.id", "langfuse.trace.name", "langfuse.trace.tags")}
attrs = {
**inherited,
"langfuse.observation.type": "tool",
"langfuse.observation.input": input,
"langfuse.observation.output": output,
"langfuse.observation.level": "ERROR" if error else "DEFAULT",
"langfuse.observation.status_message": error or "",
"langfuse.observation.metadata.title": title,
**_oi("TOOL", input=input, output=output, tool=name,
userId=inherited.get("langfuse.user.id", ""), sessionId=inherited.get("langfuse.session.id", ""),
metadata={"title": title} if title else None),
}
return _span(trace_id, name, attrs, start=start, end=end, parent=parent["spanId"], error=error)
def ms_iso(ms: int | float | None) -> str | None:
"""OpenCode 의 epoch ms → ISO. 없으면 None(=지금)."""
return datetime.fromtimestamp(ms / 1000, timezone.utc).isoformat() if ms else None
def generation(trace_id: str, name: str, *, model: str = "", input=None, output=None, usage: dict | None = None,
level: str = "DEFAULT", statusMessage: str = "", metadata: dict | None = None,
modelParameters: dict | None = None, startTime: str | None = None, endTime: str | None = None,
parent: dict | None = None) -> dict:
"""generation span. parent 로 trace() 결과를 주면 그 밑에 붙고, 없으면 같은 traceId 의 루트.
사용자·세션·이름·태그는 자식에도 복사 Langfuse 필터·집계할 span 마다 보기 때문(로컬 실측: 하면 )."""
inherited = {a["key"]: a["value"].get("stringValue") for a in (parent or {}).get("attributes", [])
if a["key"] in ("langfuse.user.id", "langfuse.session.id", "langfuse.trace.name", "langfuse.trace.tags")}
attrs = {
**inherited,
"langfuse.observation.type": "generation",
"langfuse.observation.model.name": model,
"langfuse.observation.input": input,
"langfuse.observation.output": output,
"langfuse.observation.usage_details": usage,
"langfuse.observation.model_parameters": modelParameters,
"langfuse.observation.level": level,
"langfuse.observation.status_message": statusMessage,
**{f"langfuse.observation.metadata.{k}": v for k, v in (metadata or {}).items()},
**_oi("LLM", input=input, output=output, model=model, usage=usage,
userId=inherited.get("langfuse.user.id", ""), sessionId=inherited.get("langfuse.session.id", ""), metadata=metadata),
}
return _span(trace_id, name, attrs, start=startTime, end=endTime,
parent=parent["spanId"] if parent else None, error=statusMessage if level == "ERROR" else None)
def usage_of(inp: int | None, out: int | None) -> dict | None:
if inp is None and out is None:
return None
return {"input": inp or 0, "output": out or 0, "total": (inp or 0) + (out or 0)}
def _to_protobuf(body: dict) -> bytes:
"""OTLP JSON → protobuf 바이트. traceId/spanId 는 JSON 이 hex, proto-JSON 은 base64 라 바꿔 넣음."""
import base64
import copy
from google.protobuf.json_format import ParseDict
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
b = copy.deepcopy(body)
for rs in b["resourceSpans"]:
for ss in rs["scopeSpans"]:
for sp in ss["spans"]:
for k in ("traceId", "spanId", "parentSpanId"):
if k in sp:
sp[k] = base64.b64encode(bytes.fromhex(sp[k])).decode()
return ParseDict(b, ExportTraceServiceRequest()).SerializeToString()
def _otlp_body(spans: list[dict]) -> dict:
project = settings.LANGFUSE.get("project") or "codeassist"
return {"resourceSpans": [{
"resource": {"attributes": [_attr("service.name", project), _attr("openinference.project.name", project)]},
"scopeSpans": [{"scope": {"name": project}, "spans": spans}],
}]}
async def send(spans: list[dict]) -> bool:
"""설정된 대상 전부에 전송. 하나라도 성공하면 True. 실패는 로그만."""
cfg = settings.LANGFUSE
if not spans or not enabled():
return False
body = _otlp_body(spans)
# (이름, url, headers, auth, protobuf 여부)
targets: list[tuple[str, str, dict, tuple | None, bool]] = []
if cfg.get("host"):
targets.append(("langfuse", cfg["host"].rstrip("/") + "/api/public/otel/v1/traces",
{"x-langfuse-ingestion-version": "4"}, (cfg.get("public_key", ""), cfg.get("secret_key", "")), False))
if cfg.get("phoenix"):
targets.append(("phoenix", cfg["phoenix"].rstrip("/") + "/v1/traces", {"Content-Type": "application/x-protobuf"}, None, True))
ok = False
for name, url, headers, auth, pb in targets:
try:
async with httpx.AsyncClient(timeout=5.0, transport=TRANSPORT) as client:
if pb:
resp = await client.post(url, content=_to_protobuf(body), headers=headers, auth=auth)
else:
resp = await client.post(url, json=body, headers=headers, auth=auth)
if resp.status_code != 200:
log.warning("%s%s %s", name, resp.status_code, resp.text[:200])
continue
partial = {}
try:
partial = (resp.json() or {}).get("partialSuccess") or {}
except ValueError:
pass
if partial.get("rejectedSpans"):
log.warning("%s 일부 거부: %s", name, partial)
continue
ok = True
except Exception as e: # noqa: BLE001 — 관측용이라 절대 본 흐름 안 깨뜨림
log.warning("%s 전송 실패: %s: %s", name, type(e).__name__, e)
return ok
def send_later(spans: list[dict]) -> None:
"""지금 흐름 안 막고 백그라운드로. 이벤트 루프 없으면(동기 테스트) 조용히 버림."""
if not enabled() or not spans:
return
try:
task = asyncio.get_running_loop().create_task(send(spans))
except RuntimeError:
return
_pending.add(task)
task.add_done_callback(_pending.discard)
@@ -0,0 +1,76 @@
"""`/phoenix/…` → Phoenix(127.0.0.1:8915) 중계 — 바깥에서 -12 로 오는 포트가 8914(우리 백엔드) 하나뿐이라 그 뒤에 붙임.
- Phoenix PHOENIX_HOST_ROOT_PATH=/phoenix 있음 이건 HTML 링크에만 /phoenix 붙이는 옵션이고
실제 경로는 접두어 없이 받음(실측: /phoenix/assets/ SPA 폴백 HTML, /assets/ 진짜). 그래서 여기서 /phoenix 떼고 넘김.
- 관리자 화면이라 HTTP Basic 으로 잠금: PHOENIX_UI_PASSWORD (아이디 아무거나). 비우면 잠금 없음 사내망이라도 채우는 권장.
- `POST /phoenix/v1/traces` 비번 없이 통과 -13(ABAP_OPENCODE) 바깥 8914 trace 보내는 (다른 방이라 8915 직접 ).
- 웹소켓은 넘김(Django ASGI 받음) 트레이스 화면은 HTTP 만으로 동작. 플레이그라운드 스트리밍 같은 .
"""
from __future__ import annotations
import base64
import httpx
from django.conf import settings
from django.http import HttpRequest, HttpResponse, StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
TRANSPORT: httpx.AsyncBaseTransport | None = None # 테스트용
_HOP = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade", "proxy-authorization", "host", "content-length"}
def _unauthorized() -> HttpResponse:
resp = HttpResponse("Phoenix 관리자 비밀번호 필요", status=401)
resp["WWW-Authenticate"] = 'Basic realm="phoenix"'
return resp
def _password_ok(request: HttpRequest) -> bool:
want = settings.PHOENIX_UI_PASSWORD
if not want:
return True
auth = request.headers.get("Authorization", "")
if not auth.startswith("Basic "):
return False
try:
_, _, pw = base64.b64decode(auth[6:]).decode("utf-8", "replace").partition(":")
except Exception: # noqa: BLE001
return False
return pw == want
@csrf_exempt
async def proxy(request: HttpRequest, rest: str = "") -> HttpResponse:
base = (settings.LANGFUSE.get("phoenix") or "").rstrip("/")
if not base:
return HttpResponse("PHOENIX_HOST 가 비어 있음", status=503)
ingest = request.method == "POST" and rest.strip("/") == "v1/traces"
if not ingest and not _password_ok(request):
return _unauthorized()
# /phoenix/<rest> → PHOENIX_HOST/<rest> (접두어 떼고). 쿼리는 그대로.
url = base + "/" + rest.lstrip("/")
if request.META.get("QUERY_STRING"):
url += "?" + request.META["QUERY_STRING"]
headers = {k: v for k, v in request.headers.items() if k.lower() not in _HOP and k.lower() != "authorization"}
client = httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=5.0), transport=TRANSPORT)
try:
req = client.build_request(request.method, url, headers=headers, content=request.body)
up = await client.send(req, stream=True)
except httpx.HTTPError as e:
await client.aclose()
return HttpResponse(f"Phoenix 연결 실패: {type(e).__name__}", status=502)
async def body():
try:
async for chunk in up.aiter_raw():
yield chunk
finally:
await up.aclose()
await client.aclose()
resp = StreamingHttpResponse(body(), status=up.status_code, content_type=up.headers.get("content-type", "application/octet-stream"))
for k, v in up.headers.items():
if k.lower() not in _HOP and k.lower() != "content-type":
resp[k] = v
return resp
+13
View File
@@ -0,0 +1,13 @@
from django.urls import path
from .views import chat_completions, healthcheck, models
# 슬래시 변형도 같이 — POST 는 리다이렉트에 기대면 본문이 유실됨.
urlpatterns = [
path("api/ito/healthcheck", healthcheck),
path("api/ito/healthcheck/", healthcheck),
path("api/ito/models", models),
path("api/ito/models/", models),
path("api/ito/chat/completions", chat_completions),
path("api/ito/chat/completions/", chat_completions),
]
+214
View File
@@ -0,0 +1,214 @@
"""`/api/ito/*` — OpenCode 가 붙는 OpenAI 호환 중계. 본문은 손 안 대고 FabriX 로 흘림.
GET /api/ito/healthcheck 기동 확인(무인증)
GET /api/ito/models 설정된 모델 목록(OpenAI 형식)
POST /api/ito/chat/completions 스트림/비스트림 통과 중계
설정이 비어 있어도 서버는 엔드포인트만 503 으로 이유를 말함(다른 기능까지 죽이지 않게).
"""
from __future__ import annotations
import asyncio
import json
import time
import uuid
from datetime import datetime, timezone
import logging
from typing import AsyncIterator
import httpx
from django.conf import settings
from django.http import HttpRequest, HttpResponse, JsonResponse, StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from . import langfuse
from .fabrix import FabrixConfig, Variant, auth_variants
log = logging.getLogger(__name__)
# 테스트가 httpx.MockTransport 를 꽂는 자리. None 이면 진짜 네트워크.
TRANSPORT: httpx.AsyncBaseTransport | None = None
# 마지막에 통과한 인증 형식 — 프로세스당 하나. 다음 요청은 이것부터 시도.
_last_ok: dict[str, Variant | None] = {"variant": None}
RETRY_PAUSE_S = 1.0 # 마지막 재시도 전 쉬는 시간
def _cfg() -> FabrixConfig:
return FabrixConfig.from_env(settings.FABRIX_ENV)
def _err(status: int, message: str, typ: str) -> JsonResponse:
"""OpenAI 형식 오류 — OpenCode 가 이 모양을 읽음(우리 envelope 아님)."""
return JsonResponse({"error": {"message": message, "type": typ}}, status=status)
def _key_rejected(request: HttpRequest, cfg: FabrixConfig) -> JsonResponse | None:
"""AAF_GATEWAY_KEY 가 있으면 Authorization: Bearer <키> 대조. 비우면 검사 안 함(로컬 전용)."""
if not cfg.gateway_key:
return None
auth = request.headers.get("Authorization", "")
if auth.startswith("Bearer ") and auth[7:].strip() == cfg.gateway_key:
return None
return _err(401, "게이트웨이 키가 틀려 — opencode.json 의 apiKey 와 AAF_GATEWAY_KEY 확인", "unauthorized")
def _client(cfg: FabrixConfig) -> httpx.AsyncClient:
timeout = httpx.Timeout(cfg.total_timeout_s, connect=cfg.connect_timeout_s, read=cfg.read_timeout_s)
return httpx.AsyncClient(timeout=timeout, transport=TRANSPORT)
def _sse_error(status: int, detail: bytes) -> bytes:
"""상류 오류를 SSE 오류 청크로. 연결은 정상 종료해 OpenCode 가 본문을 읽게."""
payload = {"error": {"message": detail.decode("utf-8", "replace")[:2000], "type": "upstream_error", "status": status}}
return b"data: " + json.dumps(payload, ensure_ascii=False).encode() + b"\n\ndata: [DONE]\n\n"
class _Collect:
"""상류 응답에서 답변 텍스트·usage 만 긁어 모음(관측용). 스트림은 줄 단위 `data: {json}`."""
def __init__(self) -> None:
self.text: list[str] = []
self.usage: dict | None = None
self.buf = b""
def feed(self, chunk: bytes) -> None:
self.buf += chunk
while b"\n" in self.buf:
line, self.buf = self.buf.split(b"\n", 1)
self._line(line.strip())
def _line(self, line: bytes) -> None:
if not line.startswith(b"data:") or line.endswith(b"[DONE]"):
return
try:
d = json.loads(line[5:])
except ValueError:
return
self.json(d)
def json(self, d: dict) -> None:
for c in d.get("choices") or []:
t = (c.get("delta") or c.get("message") or {}).get("content")
if isinstance(t, str):
self.text.append(t)
if d.get("usage"):
self.usage = d["usage"]
def _observe(model_id: str, body: dict, col: _Collect, started: float, status: int, *, kinds: list[str]) -> None:
if not langfuse.enabled() or not settings.LANGFUSE.get("gateway"):
return
u = col.usage or {}
tid = str(uuid.uuid4())
t0 = datetime.fromtimestamp(started, timezone.utc).isoformat()
last_user = next((m.get("content") for m in reversed(body.get("messages") or []) if m.get("role") == "user"), None)
root = langfuse.trace(tid, "fabrix", tags=["gateway"], metadata={"parts": kinds}, start=t0, end=langfuse.now_iso(),
input=last_user, output="".join(col.text)) # 목록에서 뭘 물었는지 바로 보이게
langfuse.send_later([
root,
langfuse.generation(
tid, "fabrix.chat", model=model_id, parent=root,
startTime=t0, endTime=langfuse.now_iso(),
input=body.get("messages"), output="".join(col.text),
usage=langfuse.usage_of(u.get("prompt_tokens"), u.get("completion_tokens")),
level="ERROR" if status >= 400 else "DEFAULT", statusMessage="" if status < 400 else f"upstream {status}",
modelParameters={k: v for k, v in body.items() if k in ("temperature", "max_completion_tokens", "max_tokens")},
metadata={"stream": bool(body.get("stream")), "tools": len(body.get("tools") or [])},
),
])
async def healthcheck(_request: HttpRequest) -> JsonResponse:
return JsonResponse({"success": True})
async def models(request: HttpRequest) -> HttpResponse:
cfg = _cfg()
if rejected := _key_rejected(request, cfg):
return rejected
data = [{"id": mid, "object": "model", "owned_by": "fabrix", "name": name} for mid, name in cfg.model_list().items()]
return JsonResponse({"object": "list", "data": data})
@csrf_exempt
async def chat_completions(request: HttpRequest) -> HttpResponse:
if request.method != "POST":
return _err(405, "POST 만 받아", "method_not_allowed")
cfg = _cfg()
if rejected := _key_rejected(request, cfg):
return rejected
if missing := cfg.missing():
return _err(503, f"FabriX 설정 누락: {', '.join(missing)} (.env 확인)", "configuration_error")
try:
payload = json.loads(request.body.decode("utf-8"))
assert isinstance(payload, dict)
except Exception:
return _err(400, "본문이 JSON 객체가 아니야", "invalid_request")
body, headers = cfg.prepare(payload)
# 어떤 파트가 왔고 어느 모델로 가는지 — 이미지 분기 확인용(본문은 안 찍음)
kinds = sorted({p.get("type", "?") for m in payload.get("messages") or [] for p in (m.get("content") if isinstance(m.get("content"), list) else [])})
log.info("ito → model=%s parts=%s stream=%s", headers.get("x-llm-model-id"), kinds or ["text"], bool(body.get("stream")))
variants = auth_variants(headers, _last_ok["variant"])
# FabriX 가 맞는 조합에도 가끔 401 을 뱉음(2026-09-21 고객사 실측: curl 10번 중 1~2번).
# 4개 조합 다 돌고 나서 제일 유력한 조합(맨 앞)을 잠깐 쉬고 한 번 더 — 그래도 401 이면 진짜 인증 문제
variants = variants + variants[:1]
model_id = headers.get("x-llm-model-id", "")
started = time.time()
col = _Collect()
if body.get("stream"):
async def gen() -> AsyncIterator[bytes]:
async with _client(cfg) as client:
resp: httpx.Response | None = None
vkey: Variant | None = None
for i, (vkey, vh) in enumerate(variants):
req = client.build_request("POST", cfg.url, headers=vh, json=body)
resp = await client.send(req, stream=True)
log.info("ito ← %s (auth %s/%s: %s)", resp.status_code, i + 1, len(variants), vkey)
if resp.status_code == 401 and i + 1 < len(variants):
await resp.aclose() # 인증 형식이 안 맞은 것 — 다른 조합으로 한 번 더
if i + 2 == len(variants):
await asyncio.sleep(RETRY_PAUSE_S)
continue
break
assert resp is not None
try:
if resp.status_code >= 400:
yield _sse_error(resp.status_code, await resp.aread())
return
_last_ok["variant"] = vkey
async for chunk in resp.aiter_raw():
col.feed(chunk)
yield chunk
finally:
await resp.aclose()
_observe(model_id, body, col, started, resp.status_code, kinds=kinds or ["text"])
out = StreamingHttpResponse(gen(), content_type="text/event-stream")
out["Cache-Control"] = "no-cache"
out["X-Accel-Buffering"] = "no"
return out
try:
async with _client(cfg) as client:
for i, (vkey, vh) in enumerate(variants):
resp = await client.post(cfg.url, headers=vh, json=body)
if resp.status_code == 401 and i + 1 < len(variants):
if i + 2 == len(variants):
await asyncio.sleep(RETRY_PAUSE_S)
continue
if resp.status_code < 400:
_last_ok["variant"] = vkey
break
except httpx.HTTPError as e:
return _err(502, f"FabriX 호출 실패: {type(e).__name__}: {e}", "upstream_error")
if resp.status_code < 400:
try:
col.json(resp.json())
except ValueError:
pass
_observe(model_id, body, col, started, resp.status_code, kinds=kinds or ["text"])
return HttpResponse(resp.content, status=resp.status_code, content_type="application/json")
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class SnippetsConfig(AppConfig):
name = "apps.snippets"
verbose_name = "공용 스니펫"
@@ -0,0 +1,39 @@
"""옛 로컬 snippets.db(SQLite) → 서버. 같은 이름은 건너뜀(--overwrite 로 덮어씀).
python manage.py import_snippets ../CODE_ASSISTANT_DB/snippets.db
"""
import sqlite3
from django.core.management.base import BaseCommand
from apps.snippets.models import Snippet
from apps.snippets.views import normalize_name
class Command(BaseCommand):
help = "로컬 snippets.db 를 서버 스니펫으로 가져옴"
def add_arguments(self, parser):
parser.add_argument("path")
parser.add_argument("--overwrite", action="store_true")
def handle(self, path, overwrite, **_):
con = sqlite3.connect(path)
rows = con.execute("SELECT name, desc, body, category FROM snippets").fetchall()
added = updated = skipped = 0
for name, desc, body, category in rows:
name = normalize_name(name)
if not name or not (body or "").strip():
skipped += 1
continue
d = {"desc": desc or "", "body": body, "category": (category or "").strip() or "코드"}
if overwrite:
_, created = Snippet.objects.update_or_create(name=name, defaults=d)
added += created
updated += not created
else:
_, created = Snippet.objects.get_or_create(name=name, defaults=d)
added += created
skipped += not created
self.stdout.write(f"추가 {added} / 갱신 {updated} / 건너뜀 {skipped} (총 {len(rows)})")
@@ -0,0 +1,44 @@
# Generated by Django 5.1.15 on 2026-09-21 07:01
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Snippet',
fields=[
('name', models.CharField(max_length=200, primary_key=True, serialize=False)),
('desc', models.CharField(blank=True, default='', max_length=500)),
('body', models.TextField()),
('category', models.CharField(default='코드', max_length=100)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['name'],
},
),
migrations.CreateModel(
name='SnippetUsage',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('count', models.IntegerField(default=0)),
('last_used', models.DateTimeField(null=True)),
('snippet', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='usages', to='snippets.snippet')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),
],
options={
'unique_together': {('snippet', 'user')},
},
),
]
+38
View File
@@ -0,0 +1,38 @@
"""공용 스니펫 — 로컬 SQLite(snippets/usage) 를 그대로 서버 PostgreSQL 로. 전원 읽기, 사용 기록은 사람별."""
from django.conf import settings
from django.db import models
class Snippet(models.Model):
name = models.CharField(max_length=200, primary_key=True) # 대문자·공백→_ 정규화된 이름(옛 DB 와 동일)
desc = models.CharField(max_length=500, blank=True, default="")
body = models.TextField()
category = models.CharField(max_length=100, default="코드")
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name="+")
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["name"]
def as_dto(self, usage: "SnippetUsage | None" = None) -> dict:
return {
"name": self.name,
"desc": self.desc,
"body": self.body,
"category": self.category,
"usageCount": usage.count if usage else 0,
"lastUsed": int(usage.last_used.timestamp()) if usage and usage.last_used else 0,
}
class SnippetUsage(models.Model):
"""사람별 사용 횟수 — 랭킹은 내 기준으로."""
snippet = models.ForeignKey(Snippet, on_delete=models.CASCADE, related_name="usages")
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+")
count = models.IntegerField(default=0)
last_used = models.DateTimeField(null=True)
class Meta:
unique_together = [("snippet", "user")]
+9
View File
@@ -0,0 +1,9 @@
from django.urls import path
from .views import SnippetDetailView, SnippetListView, SnippetUseView
urlpatterns = [
path("", SnippetListView.as_view()),
path("/<str:name>", SnippetDetailView.as_view()),
path("/<str:name>/use", SnippetUseView.as_view()),
]
+77
View File
@@ -0,0 +1,77 @@
"""스니펫 API — 프론트 `features/snippets/api/snippets.api.ts` 5개 호출과 1:1. 옛 Tauri 브릿지 규칙 그대로.
GET /api/v1/snippets Snippet[] ( usage 합쳐서)
POST /api/v1/snippets {name,desc,body,category} Snippet (이름 중복이면 409)
PUT /api/v1/snippets/{name} {desc,body,category} Snippet
DELETE /api/v1/snippets/{name} {name}
POST /api/v1/snippets/{name}/use {name, usageCount, lastUsed}
"""
from django.db import IntegrityError, transaction
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework.response import Response
from rest_framework.views import APIView
from common.envelope import CodedError
from .models import Snippet, SnippetUsage
def normalize_name(name: str) -> str:
return (name or "").strip().upper().replace(" ", "_")
def _validate(body: dict, *, need_name: bool) -> dict:
name = normalize_name(body.get("name", ""))
if need_name and not name:
raise CodedError(400, "VALIDATION_ERROR", "이름을 입력해야 함")
if not (body.get("body") or "").strip():
raise CodedError(400, "VALIDATION_ERROR", "내용을 입력해야 함")
return {
"name": name,
"desc": body.get("desc") or "",
"body": body["body"],
"category": (body.get("category") or "").strip() or "코드",
}
class SnippetListView(APIView):
def get(self, request):
usage = {u.snippet_id: u for u in SnippetUsage.objects.filter(user=request.user)}
return Response([s.as_dto(usage.get(s.name)) for s in Snippet.objects.all()])
def post(self, request):
d = _validate(request.data, need_name=True)
try:
with transaction.atomic(): # 중복 INSERT 실패가 바깥 트랜잭션을 깨지 않게(savepoint)
s = Snippet.objects.create(**d, created_by=request.user)
except IntegrityError:
raise CodedError(409, "CONFLICT", f"이미 있는 이름임: {d['name']}")
return Response(s.as_dto(), status=201)
class SnippetDetailView(APIView):
def put(self, request, name: str):
s = get_object_or_404(Snippet, name=normalize_name(name))
d = _validate({**request.data, "name": s.name}, need_name=False)
s.desc, s.body, s.category = d["desc"], d["body"], d["category"]
s.save(update_fields=["desc", "body", "category", "updated_at"])
usage = SnippetUsage.objects.filter(snippet=s, user=request.user).first()
return Response(s.as_dto(usage))
def delete(self, request, name: str):
s = get_object_or_404(Snippet, name=normalize_name(name))
deleted = s.name # delete() 가 pk 를 None 으로 지움
s.delete()
return Response({"name": deleted})
class SnippetUseView(APIView):
def post(self, request, name: str):
s = get_object_or_404(Snippet, name=normalize_name(name))
u, _ = SnippetUsage.objects.get_or_create(snippet=s, user=request.user)
u.count += 1
u.last_used = timezone.now()
u.save(update_fields=["count", "last_used"])
return Response({"name": s.name, "usageCount": u.count, "lastUsed": int(u.last_used.timestamp())})
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class StatsConfig(AppConfig):
name = "apps.stats"
verbose_name = "관리자 통계(사용량·비용·시간)"
+7
View File
@@ -0,0 +1,7 @@
from django.urls import path
from .views import AdminStatsView
urlpatterns = [
path("stats", AdminStatsView.as_view()),
]
+106
View File
@@ -0,0 +1,106 @@
"""관리자 대시보드 집계 — ChatMessage(assistant 행)에 이미 쌓인 토큰·비용·시간을 모아서 줌.
GET /api/v1/admin/stats?from=YYYY-MM-DD&to=YYYY-MM-DD
{ totals, byUser[], byDay[] } (is_superuser . 아니면 403 FORBIDDEN)
새로 모으는 없음. 기간 기본은 최근 30(to 포함).
"""
from datetime import date, datetime, time, timedelta
from django.db.models import Avg, Count, F, Sum
from django.db.models.functions import TruncDate
from django.utils import timezone
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.chat.models import ChatMessage
from common.envelope import CodedError
MAX_DAYS = 366
def _parse_range(request) -> tuple[date, date]:
today = timezone.localdate()
raw_from, raw_to = request.query_params.get("from"), request.query_params.get("to")
try:
d_to = date.fromisoformat(raw_to) if raw_to else today
d_from = date.fromisoformat(raw_from) if raw_from else d_to - timedelta(days=29)
except ValueError:
raise CodedError(400, "VALIDATION_ERROR", "from/to 는 YYYY-MM-DD 여야 해")
if d_from > d_to:
raise CodedError(400, "VALIDATION_ERROR", "from 이 to 보다 늦어")
if (d_to - d_from).days >= MAX_DAYS:
raise CodedError(400, "VALIDATION_ERROR", f"기간은 최대 {MAX_DAYS}")
return d_from, d_to
def _agg(qs):
"""공통 집계 — 요청 수·토큰·비용·평균 응답시간."""
return qs.aggregate(
requests=Count("id"),
input_tokens=Sum("input_tokens"),
output_tokens=Sum("output_tokens"),
cost_usd=Sum("cost_usd"),
avg_elapsed_ms=Avg("elapsed_ms"),
)
def _row(d: dict) -> dict:
return {
"requests": d["requests"] or 0,
"inputTokens": d["input_tokens"] or 0,
"outputTokens": d["output_tokens"] or 0,
"totalTokens": (d["input_tokens"] or 0) + (d["output_tokens"] or 0),
"costUsd": round(d["cost_usd"] or 0.0, 6),
"avgElapsedMs": round(d["avg_elapsed_ms"]) if d["avg_elapsed_ms"] is not None else None,
}
class AdminStatsView(APIView):
def get(self, request):
if not request.user.is_superuser:
raise CodedError(403, "FORBIDDEN", "관리자만 볼 수 있어")
d_from, d_to = _parse_range(request)
tz = timezone.get_current_timezone()
start = datetime.combine(d_from, time.min, tzinfo=tz)
end = datetime.combine(d_to + timedelta(days=1), time.min, tzinfo=tz)
base = ChatMessage.objects.filter(role="assistant", created_at__gte=start, created_at__lt=end)
by_user = (
base.values(user_id=F("session__user_id"), email=F("session__user__email"), name=F("session__user__user_name"))
.annotate(
requests=Count("id"),
input_tokens=Sum("input_tokens"),
output_tokens=Sum("output_tokens"),
cost_usd=Sum("cost_usd"),
avg_elapsed_ms=Avg("elapsed_ms"),
sessions=Count("session_id", distinct=True),
)
.order_by("-cost_usd", "-requests")
)
by_day = (
base.annotate(day=TruncDate("created_at", tzinfo=tz))
.values("day")
.annotate(
requests=Count("id"),
input_tokens=Sum("input_tokens"),
output_tokens=Sum("output_tokens"),
cost_usd=Sum("cost_usd"),
avg_elapsed_ms=Avg("elapsed_ms"),
)
.order_by("day")
)
return Response(
{
"from": d_from.isoformat(),
"to": d_to.isoformat(),
"totals": {**_row(_agg(base)), "users": base.values("session__user_id").distinct().count(),
"sessions": base.values("session_id").distinct().count()},
"byUser": [
{"userId": r["user_id"], "email": r["email"], "name": r["name"] or "", "sessions": r["sessions"], **_row(r)}
for r in by_user
],
"byDay": [{"day": r["day"].isoformat(), **_row(r)} for r in by_day],
}
)
+33 -1
View File
@@ -25,6 +25,8 @@ def _load_dotenv(path: Path) -> None:
if not line or line.startswith("#") or "=" not in line: if not line or line.startswith("#") or "=" not in line:
continue continue
k, v = line.split("=", 1) k, v = line.split("=", 1)
# 줄 끝 주석(공백 뒤 #)은 값이 아님 — 안 떼면 HTTP 헤더에 한글이 실려 httpx 가 죽음(고객사 실측)
v = v.split(" #", 1)[0].split(" #", 1)[0]
os.environ.setdefault(k.strip(), v.strip().strip('"\x27')) os.environ.setdefault(k.strip(), v.strip().strip('"\x27'))
@@ -73,6 +75,32 @@ OPENCODE_BASE_URL = _env("OPENCODE_BASE_URL", "http://localhost:4096").rstrip("/
OPENCODE_DIRECTORY = _env("OPENCODE_DIRECTORY") or str((BASE_DIR / "opencode").resolve()) OPENCODE_DIRECTORY = _env("OPENCODE_DIRECTORY") or str((BASE_DIR / "opencode").resolve())
# OpenCode 에 넘길 에이전트 이름 (opencode/.opencode/agent/<이름>.md) # OpenCode 에 넘길 에이전트 이름 (opencode/.opencode/agent/<이름>.md)
OPENCODE_AGENT = _env("OPENCODE_AGENT", "codeassist") OPENCODE_AGENT = _env("OPENCODE_AGENT", "codeassist")
# 이미지가 붙은 요청만 이 모델로("provider/model" 형식, opencode.json 에 등록돼 있어야 함). 비우면 기본 모델.
# 로컬(OpenRouter)용 — 고객사(FabriX)는 게이트웨이가 AAF_FABRIX_VISION_MODEL_ID 로 같은 분기를 함.
OPENCODE_VISION_MODEL = _env("OPENCODE_VISION_MODEL")
# 채팅 스트림 타임아웃(초). Gemma4 가 "안녕"에도 200초 걸리는 날이 있어 첫 이벤트 300, 한 턴 600.
STREAM_TURN_TIMEOUT_S = int(_env("STREAM_TURN_TIMEOUT_S", "600"))
STREAM_FIRST_EVENT_TIMEOUT_S = int(_env("STREAM_FIRST_EVENT_TIMEOUT_S", "300"))
# 사내 LLM(FabriX) 게이트웨이 — 고객사에선 OpenCode 가 /api/ito 로 붙고 apps/gateway 가 FabriX 로 중계.
# 키 이름은 ABAP_OPENCODE 와 같음(AAF_*). 전부 비어 있으면 /api/ito/chat/completions 만 503 이고 나머진 멀쩡.
from apps.gateway.fabrix import ENV_KEYS as _FABRIX_KEYS # noqa: E402
FABRIX_ENV = {k: _env(k) for k in _FABRIX_KEYS}
# Langfuse(LLM 관측) — 자체 호스팅 주소 + 프로젝트 키. HOST 비우면 전송 안 함
LANGFUSE = {
"host": _env("LANGFUSE_HOST"),
"public_key": _env("LANGFUSE_PUBLIC_KEY"),
"secret_key": _env("LANGFUSE_SECRET_KEY"),
# 게이트웨이(FabriX 호출 원문) 트레이스는 기본 끔 — 켜면 질문 하나에 행이 2개(chat + fabrix) 잡힘
"gateway": _env_bool("LANGFUSE_TRACE_GATEWAY", False),
# Phoenix(도커 없이 pip 로 뜨는 관측 서버). 주소만 주면 같은 span 을 여기로도 보냄
"phoenix": _env("PHOENIX_HOST"),
"project": _env("TRACE_PROJECT", "codeassist"),
}
# /phoenix/ 화면 잠금(Basic 인증 비번). 비우면 누구나 봄
PHOENIX_UI_PASSWORD = _env("PHOENIX_UI_PASSWORD")
# 세션 컨텍스트 하드 한도 — usage.limit 로 프론트 게이지에 감 # 세션 컨텍스트 하드 한도 — usage.limit 로 프론트 게이지에 감
CONTEXT_LIMIT_TOKENS = int(_env("CONTEXT_LIMIT_TOKENS", "128000") or "128000") CONTEXT_LIMIT_TOKENS = int(_env("CONTEXT_LIMIT_TOKENS", "128000") or "128000")
@@ -87,6 +115,9 @@ INSTALLED_APPS = [
"corsheaders", "corsheaders",
"apps.accounts", "apps.accounts",
"apps.chat", "apps.chat",
"apps.gateway",
"apps.stats",
"apps.snippets",
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@@ -132,7 +163,8 @@ if _pg_host:
# ASGI 스레드마다 연결 눌러앉는 것 방지 — 요청 끝나면 바로 반납 # ASGI 스레드마다 연결 눌러앉는 것 방지 — 요청 끝나면 바로 반납
"CONN_MAX_AGE": 0, "CONN_MAX_AGE": 0,
"OPTIONS": { "OPTIONS": {
"sslmode": "require", # 고객사 내부 PostgreSQL 은 SSL 없음(server does not support SSL). 기본 prefer = 되면 쓰고 아니면 평문
"sslmode": _env("DB_SSLMODE", "prefer"),
"connect_timeout": 10, "connect_timeout": 10,
"options": f"-c search_path={_schema}", "options": f"-c search_path={_schema}",
}, },

Some files were not shown because too many files have changed in this diff Show More