Skip to content

웹소켓 url 수정 및 인증 기반 사용자 ID로 웹소켓 연결 구조 정리 - #21

Merged
minseokim0113 merged 2 commits into
devfrom
feat/ai-chat-ui
Apr 12, 2026
Merged

웹소켓 url 수정 및 인증 기반 사용자 ID로 웹소켓 연결 구조 정리#21
minseokim0113 merged 2 commits into
devfrom
feat/ai-chat-ui

Conversation

@minseokim0113

@minseokim0113 minseokim0113 commented Apr 11, 2026

Copy link
Copy Markdown
Contributor

📌 PR 설명

로그인 기능 적용 이후에도 남아 있던 데모용 사용자 ID 흐름을 제거하고, 인증 토큰 기반으로 웹소켓 연결이 동작하도록 구조를 정리했습니다.
전역 채팅 부트스트랩은 AppLayout에서 인증 사용자 ID를 기반으로 시작되도록 바꿨고, AI 채팅 위젯도 동일한 사용자 식별 방식을 사용하도록 맞췄습니다.
추가로 배포 환경에서 웹소켓 주소를 안정적으로 계산할 수 있도록 stomp-client 정리와 배포 env 설정도 함께 반영했습니다.


✅ 완료한 기능 명세

  • 데모용 사용자 ID 훅 의존 제거
  • 로그인 토큰 기반 사용자 ID 훅 추가
  • AppLayout에서 인증 사용자 기준으로 전역 채팅 부트스트랩 연결
  • AI 채팅 위젯의 사용자 식별 방식 통일
  • stomp-client의 불필요한 임시 사용자 ID 제거
  • 배포 환경에서 웹소켓 URL을 명시적으로 주입할 수 있도록 workflow 정리

💭 고민과 해결과정

기존에는 use-demo-user-id라는 이름의 훅이 실제로는 로그인 토큰에서 사용자 ID를 읽고 있었는데, 이름과 역할이 맞지 않아 흐름을 이해하기 어렵고 유지보수 시 혼동을 만들 수 있었습니다.
그래서 인증 사용자 ID를 읽는 책임을 별도 훅으로 분리하고, 전역 채팅 연결 시작 지점도 connectStomp() 직접 호출 방식이 아니라 useGlobalChatBoot(userId)를 통해 일관되게 관리하도록 정리했습니다.

또한 dev 환경에서 웹소켓이 프론트 도메인으로 잘못 붙는 문제가 있었기 때문에, VITE_API_BASE_URLVITE_WS_URL을 기준으로 웹소켓 주소를 계산하도록 구조를 맞췄습니다.
이 과정에서 stomp-client.ts에 남아 있던 충돌 흔적과 TEMP_USER_ID도 함께 제거해 인증 기반 연결 흐름으로 통일했습니다.

Summary by CodeRabbit

  • 새로운 기능

    • 채팅 페이지에 탭 네비게이션 추가 — 그룹 채팅/전체 채팅 전환 가능
    • 채팅 제목이 한국어로 변경 및 탭 UI에 활성 표시 추가
  • 개선 사항

    • 채팅 입력창에 지원 슬래시 명령어 안내 추가 (예: /slow, /rename)
    • WebSocket 및 API 환경 변수 설정 검증·정규화 및 관련 URL 구성 개선
    • 인증된 사용자 기반으로 채팅 연결 초기화 로직 개선

@minseokim0113 minseokim0113 added CHORE 설정, 빌드 등 기타 작업 FIX 버그 수정 REFACTOR 코드 개선 labels Apr 11, 2026
@coderabbitai

coderabbitai Bot commented Apr 11, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

배포 워크플로우의 API/WS 환경 변수 설정을 정규화하고, 인증 기반 사용자 ID 훅으로 전환한 뒤 채팅 페이지에 탭 UI를 추가하고 STOMP 연결을 인증 토큰으로 구성하도록 변경했습니다.

Changes

Cohort / File(s) Summary
CI / 배포 설정
.github/workflows/frontend-deploy.yml
API URL을 임시 변수로 선택·검증·후처리하고 .env.production을 한 번에 재작성하며 VITE_WS_URL을 추가함.
인증 훅 & AI 채팅 위젯
src/features/auth/model/use-auth-user-id.ts, src/features/ai-chat/ui/wefini-chat-widget.tsx
훅 명칭 useDemoUserIduseAuthUserId로 변경하고 AI 채팅 위젯이 인증 기반 훅을 사용하도록 임포트/호출을 교체함.
앱 레이아웃 & STOMP 부트스트랩
src/widgets/app-layout/ui/app-layout.tsx, src/shared/api/stomp-client.ts
앱 레이아웃에서 직접 connect/disconnect 사이드이펙트를 제거하고 useGlobalChatBoot(userId)로 위임. STOMP 클라이언트는 토큰이 있을 때 Authorization: Bearer <token>을 connect header로 설정하고 WS URL 해석 로직을 조정함.
채팅 UI 변경
src/pages/chat/ui/chat-page.tsx, src/features/chat/ui/group-chat-room.tsx, src/features/chat/ui/global-chat-room.tsx
채팅 페이지에 로컬 탭 상태(group/global)와 탭 기반 조건부 렌더링을 추가. 그룹 채팅 입력 플레이스홀더에 슬래시 명령어 안내를 확장하고 글로벌 채팅의 주석을 정리함.

Sequence Diagram(s)

sequenceDiagram
    participant User as "사용자(UI)"
    participant ChatPage as "ChatPage (탭 선택)"
    participant BootHook as "useGlobalChatBoot(userId)"
    participant StompClient as "stomp-client"
    participant Server as "웹소켓 서버"

    User->>ChatPage: 채팅 페이지 진입 / user 인증 상태
    ChatPage->>BootHook: useGlobalChatBoot(userId) 호출
    BootHook->>StompClient: connect(accessToken?, wsUrl)
    alt accessToken 존재
        StompClient->>StompClient: set connectHeaders = Authorization: Bearer <token>
    else 토큰 없음
        StompClient->>StompClient: set connectHeaders = {}
    end
    StompClient->>Server: STOMP CONNECT (wsUrl, headers)
    Server-->>StompClient: CONNECTED
    StompClient-->>BootHook: 연결 성공
    BootHook-->>ChatPage: 상태(연결 됨)
    ChatPage-->>User: 채팅 활성화 UI
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

ready-for-review

Suggested reviewers

  • hjh79gw
  • kkhhmm3103

Poem

🐰✨ 토큰을 안고 점프했죠,
탭을 눌러 방을 바꾸고,
웹소켓은 깃털처럼 토큰을 실어,
배포는 단정히 정리되고,
귀여운 버그는 도망가라!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PR 제목은 주요 변경 사항(웹소켓 URL 수정 및 인증 기반 사용자 ID 적용)을 명확하고 간결하게 요약하고 있습니다.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/ai-chat-ui

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/shared/api/stomp-client.ts (1)

4-5: WS URL 조합 시 후행 슬래시 정규화를 추가하면 안전합니다.

VITE_API_BASE_URL 값이 /로 끝나면 //ws 형태가 될 수 있어, 초기화 시 정규화를 한 번 해두는 편이 좋습니다.

리팩터링 예시
-const API_BASE_URL = import.meta.env.VITE_API_BASE_URL
-const WS_URL = import.meta.env.VITE_WS_URL || (API_BASE_URL ? `${API_BASE_URL}/ws` : '/ws')
+const API_BASE_URL = import.meta.env.VITE_API_BASE_URL?.replace(/\/+$/, '')
+const EXPLICIT_WS_URL = import.meta.env.VITE_WS_URL?.replace(/\/+$/, '')
+const WS_URL = EXPLICIT_WS_URL || (API_BASE_URL ? `${API_BASE_URL}/ws` : '/ws')
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/shared/api/stomp-client.ts` around lines 4 - 5, The WS URL concatenation
can produce a double slash if VITE_API_BASE_URL ends with a slash; update the
initialization of WS_URL to normalize API_BASE_URL by trimming any trailing
slash before concatenation (i.e., ensure API_BASE_URL has no trailing "/" when
used to build `${API_BASE_URL}/ws`), and keep the fallback '/ws' behavior when
API_BASE_URL is falsy; adjust the logic referring to the API_BASE_URL and WS_URL
constants accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/frontend-deploy.yml:
- Around line 30-39: The workflow currently writes VITE_API_BASE_URL and
VITE_WS_URL even if the selected secret (secrets.PROD_API_URL or
secrets.DEV_API_URL) is empty, producing a bad .env.production; add a guard
after determining API_URL (the shell variable set based on GITHUB_REF_NAME) that
checks for emptiness (test API_URL, e.g., using -z) and fails the job
immediately with a clear error message to stderr and a non-zero exit (so the run
stops) before continuing to strip the trailing slash and echo to
.env.production; reference the variables GITHUB_REF_NAME, API_URL,
secrets.PROD_API_URL, secrets.DEV_API_URL, and the target file .env.production
when implementing the check.

---

Nitpick comments:
In `@src/shared/api/stomp-client.ts`:
- Around line 4-5: The WS URL concatenation can produce a double slash if
VITE_API_BASE_URL ends with a slash; update the initialization of WS_URL to
normalize API_BASE_URL by trimming any trailing slash before concatenation
(i.e., ensure API_BASE_URL has no trailing "/" when used to build
`${API_BASE_URL}/ws`), and keep the fallback '/ws' behavior when API_BASE_URL is
falsy; adjust the logic referring to the API_BASE_URL and WS_URL constants
accordingly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 41a612d5-d2a0-408f-8ae5-978416c3b6ca

📥 Commits

Reviewing files that changed from the base of the PR and between 70bf0b1 and ea7f9b2.

📒 Files selected for processing (9)
  • .github/workflows/frontend-deploy.yml
  • src/features/ai-chat/lib/wefini-chat-utils.ts
  • src/features/ai-chat/ui/wefini-chat-widget.tsx
  • src/features/auth/model/use-auth-user-id.ts
  • src/features/chat/ui/global-chat-room.tsx
  • src/features/chat/ui/group-chat-room.tsx
  • src/pages/chat/ui/chat-page.tsx
  • src/shared/api/stomp-client.ts
  • src/widgets/app-layout/ui/app-layout.tsx
💤 Files with no reviewable changes (1)
  • src/features/chat/ui/global-chat-room.tsx

Comment thread .github/workflows/frontend-deploy.yml Outdated
@minseokim0113 minseokim0113 changed the title 인증 기반 사용자 ID로 웹소켓 연결 구조 정리 웹소켓 url 수정 및 인증 기반 사용자 ID로 웹소켓 연결 구조 정리 Apr 11, 2026
@minseokim0113 minseokim0113 added the ready-for-review PR 리뷰 요청 label Apr 11, 2026

@hjh79gw hjh79gw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생하셨습니다

@minseokim0113
minseokim0113 merged commit 9007c18 into dev Apr 12, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CHORE 설정, 빌드 등 기타 작업 FIX 버그 수정 ready-for-review PR 리뷰 요청 REFACTOR 코드 개선

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants