diff --git a/changelog.md b/changelog.md index 0b1d6657..ac38d496 100644 --- a/changelog.md +++ b/changelog.md @@ -4,6 +4,18 @@ Lightweight human-readable summary of meaningful repository changes. This does n ## [Unreleased] +## [v0.1.25] - 2026-11-15 + +- AI 여정 요청 시 Idempotency-Key UUID v4 규격 적용: + - 여정 생성 요청(`POST /api/v1/explorations`), 턴 추가(`POST /api/v1/explorations/{id}/turns`), 관리자 API 등에서 전송하는 `Idempotency-Key` 헤더를 RFC 4122 v4 UUID(8-4-4-4-12) 형식으로 표준화. + - 백엔드 `400 VALIDATION_ERROR` ('Idempotency-Key must be a UUID') 오류로 인해 여정 AI 생성이 중단되던 문제 해결. + - `clientTurnId` 역시 UUID 형식으로 일원화. +- Added Korean living-culture paths from the Hanok map home into stay, food, hands-on experience, and traditional-market exploration. +- Limited the Hanok Culture Walk panel to places identified as Hanok and removed duplicate English copy from the panel. +- Refined the map cultural-discovery panel into a compact editorial section with vertically ordered places and accessible interaction states. +- 지도마루 정보 모드의 전국 한옥 홈에 문화 발견 패널을 추가했다. 지역과 한옥 생활문화를 소개한 뒤 실제 장소 선택으로 이어지고, 한옥마루의 심화 콘텐츠로 이동할 수 있다. +- 한국어 문화 맥락과 영어 보조 해설을 함께 제공해 해외 방문자도 장소를 문화적 맥락에서 탐색할 수 있게 했다. + ## [v0.1.24] - 2026-11-09 - 모바일 좌우 여백을 16px로 통일: diff --git a/package.json b/package.json index 5f90fdcb..a06a91e9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "onmaru-frontend", - "version": "0.1.24", + "version": "0.1.25", "private": true, "scripts": { "dev": "next dev", diff --git a/src/features/admin/api/adminApi.ts b/src/features/admin/api/adminApi.ts index 6526d71e..2994df59 100644 --- a/src/features/admin/api/adminApi.ts +++ b/src/features/admin/api/adminApi.ts @@ -4,11 +4,9 @@ */ import { apiRequest, USE_MOCK } from '@/lib/api/client'; +import { generateUUID } from '@/lib/uuid'; -function newIdempotencyKey(): string { - if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID(); - return `${Date.now()}-${Math.random().toString(36).slice(2)}`; -} +const newIdempotencyKey = generateUUID; import { mockDashboardStats, mockRecentReviews, diff --git a/src/features/journey-curator/api/journeyApi.test.ts b/src/features/journey-curator/api/journeyApi.test.ts index 97925db4..cbf7be3a 100644 --- a/src/features/journey-curator/api/journeyApi.test.ts +++ b/src/features/journey-curator/api/journeyApi.test.ts @@ -1,7 +1,47 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { createJourneyRepository } from './journeyApi'; describe('journey repository', () => { + it('uses the RunAccepted snapshot URLs without rebuilding their paths', async () => { + const calls: Array<{ path: string; options: unknown }> = []; + const repository = createJourneyRepository((async (path: string, options: unknown) => { + calls.push({ path, options }); + return { schemaVersion: '1.3' }; + }) as never); + + await repository.getAcceptedSnapshots({ + schemaVersion: '1.3', + explorationId: 'exp-1', + runId: 'run-1', + stateVersion: 0, + runUrl: '/api/v1/explorations/exp-1/runs/run-1', + eventsUrl: '/api/v1/explorations/exp-1/runs/run-1/events', + snapshotUrl: '/api/v1/explorations/exp-1', + }); + + expect(calls).toEqual([ + { path: '/api/v1/explorations/exp-1/runs/run-1', options: { method: 'GET', cache: 'no-store', rootPath: true } }, + { path: '/api/v1/explorations/exp-1', options: { method: 'GET', cache: 'no-store', rootPath: true } }, + ]); + }); + + it('subscribes to the EventSource URL returned by RunAccepted without rebuilding it', () => { + const createEventSource = vi.fn(() => ({ + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + close: vi.fn(), + })) as unknown as import('./journeyApi').JourneyEventSourceFactory; + const repository = createJourneyRepository(); + + repository.subscribeToRunEvents( + 'https://journey.example.test/signed-events?run=accepted', + vi.fn(), + { createEventSource }, + ); + + expect(createEventSource).toHaveBeenCalledWith('https://journey.example.test/signed-events?run=accepted'); + }); + it('starts and recovers journey runs through the backend contract paths', async () => { const calls: Array<{ path: string; options: unknown }> = []; const repository = createJourneyRepository((async (path: string, options: unknown) => { diff --git a/src/features/journey-curator/api/journeyApi.ts b/src/features/journey-curator/api/journeyApi.ts index a029ed3b..01f6fe5b 100644 --- a/src/features/journey-curator/api/journeyApi.ts +++ b/src/features/journey-curator/api/journeyApi.ts @@ -1,13 +1,13 @@ -import { apiRequest, getApiV1BaseUrl, type ApiRequestOptions, USE_MOCK } from '@/lib/api/client'; +import { apiRequest, type ApiRequestOptions, USE_MOCK } from '@/lib/api/client'; import type { BentoJourneyPlan } from '../types/journey.types'; import { JOURNEY_PLANS } from '../data/curatedJourneys'; -import type { JourneyRunSnapshot, JourneySseFrame } from './journeyContract'; +import type { JourneyRunSnapshot, JourneySchemaVersion, JourneySseFrame } from './journeyContract'; import { parseJourneySseFrame } from '../reducers/journeySseParser'; type RequestFn = (path: string, options?: ApiRequestOptions) => Promise; export type RunAccepted = { - schemaVersion: '1.2'; + schemaVersion: JourneySchemaVersion; explorationId: string; runId: string; stateVersion: number; @@ -70,6 +70,7 @@ export type JourneyRepository = { }): Promise; getExploration(explorationId: string): Promise; getRun(explorationId: string, runId: string): Promise; + getAcceptedSnapshots(accepted: RunAccepted): Promise<{ run: JourneyRunSnapshot; snapshot: ExplorationSnapshot }>; cancelRun(explorationId: string, runId: string): Promise; applyAction(input: ApplyActionInput): Promise; @@ -78,8 +79,7 @@ export type JourneyRepository = { subscribeToRunEvents( - explorationId: string, - runId: string, + eventsUrl: string, onEvent: (frame: JourneySseFrame) => void, options?: { onError?: (error: unknown) => void; createEventSource?: JourneyEventSourceFactory }, ): () => void; @@ -124,6 +124,13 @@ export function createJourneyRepository(request: RequestFn = apiRequest): Journe cache: 'no-store', }); }, + async getAcceptedSnapshots(accepted) { + const [run, snapshot] = await Promise.all([ + request(accepted.runUrl, { method: 'GET', cache: 'no-store', rootPath: true }), + request(accepted.snapshotUrl, { method: 'GET', cache: 'no-store', rootPath: true }), + ]); + return { run, snapshot }; + }, cancelRun(explorationId, runId) { return request(`/explorations/${explorationId}/runs/${runId}/cancel`, { method: 'POST', @@ -143,17 +150,17 @@ export function createJourneyRepository(request: RequestFn = apiRequest): Journe idempotencyKey: input.idempotencyKey, }); }, - subscribeToRunEvents(explorationId, runId, onEvent, options) { - const url = `${getApiV1BaseUrl()}/explorations/${explorationId}/runs/${runId}/events`; + subscribeToRunEvents(eventsUrl, onEvent, options) { const createEventSource = options?.createEventSource ?? ((u) => new EventSource(u, { withCredentials: true })); - const source = createEventSource(url); + const source = createEventSource(eventsUrl); const eventNames = ['run.stage', 'run.terminal', 'heartbeat', 'reset', 'auth_closed'] as const; const listeners = eventNames.map((eventName) => { const listener = (event: Event) => { const messageEvent = event as MessageEvent; try { - onEvent(parseJourneySseFrame({ id: messageEvent.lastEventId, event: eventName, data: messageEvent.data })); + const frame = parseJourneySseFrame({ id: messageEvent.lastEventId, event: eventName, data: messageEvent.data }); + if (frame) onEvent(frame); } catch (err) { options?.onError?.(err); } @@ -181,6 +188,7 @@ const fixtureRun: JourneyRunSnapshot = { engine: 'BASELINE', degradedReason: 'AI_SERVICE_UNAVAILABLE', stage: null, + sequence: 1, outcome: 'INITIAL_BOARD', clarification: null, retryAfterMs: 0, @@ -224,13 +232,16 @@ export const fixtureJourneyRepository: JourneyRepository = { async getRun() { return fixtureRun; }, + async getAcceptedSnapshots() { + return { run: fixtureRun, snapshot: await this.getExploration('fixture-exploration') }; + }, async cancelRun() { return { ...fixtureRun, status: 'CANCELLED', outcome: null }; }, async applyAction() { return this.getExploration('fixture-exploration'); }, - subscribeToRunEvents(_expId, _runId, onEvent) { + subscribeToRunEvents(_eventsUrl, onEvent) { const timer = setTimeout(() => { onEvent({ id: '1', diff --git a/src/features/journey-curator/api/journeyContract.ts b/src/features/journey-curator/api/journeyContract.ts index 26553ed4..8d2ed81f 100644 --- a/src/features/journey-curator/api/journeyContract.ts +++ b/src/features/journey-curator/api/journeyContract.ts @@ -1,7 +1,13 @@ -export type JourneySchemaVersion = '1.2'; +export type JourneySchemaVersion = '1.2' | '1.3'; export type JourneyRunStatus = 'QUEUED' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELLED'; -export type JourneyRunStage = 'INTERPRETING' | 'RETRIEVING' | 'VALIDATING' | 'PERSISTING'; +export type JourneyRunStage = + | 'INTERPRETING' + | 'RETRIEVING' + | 'SELECTING_EVIDENCE' + | 'GENERATING' + | 'VALIDATING' + | 'PERSISTING'; export type JourneyRunEngine = 'LLM' | 'BASELINE'; export type JourneyDegradedReason = | 'AI_QUOTA_EXCEEDED' @@ -25,6 +31,7 @@ export type JourneyRunSnapshot = { engine: JourneyRunEngine; degradedReason: JourneyDegradedReason | null; stage: JourneyRunStage | null; + sequence: number; outcome: JourneyRunOutcome | null; clarification: JourneyClarification | null; retryAfterMs: number; diff --git a/src/features/journey-curator/api/journeyCuratorApi.ts b/src/features/journey-curator/api/journeyCuratorApi.ts index 8a0eb744..c65bb575 100644 --- a/src/features/journey-curator/api/journeyCuratorApi.ts +++ b/src/features/journey-curator/api/journeyCuratorApi.ts @@ -1,6 +1,7 @@ import type { BentoJourneyPlan, MoodId } from '../types/journey.types'; import { matchJourneyPlan } from '../data/curatedJourneys'; import { defaultJourneyRepository, type JourneyRepository, type RunAccepted } from './journeyApi'; +import { generateUUID } from '@/lib/uuid'; export interface CurateJourneyParams { query: string; @@ -21,8 +22,7 @@ type RunJourneyOptions = { }; function createIdempotencyKey(): string { - if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID(); - return `journey-${Date.now()}-${Math.random().toString(16).slice(2)}`; + return generateUUID(); } async function readAcceptedSnapshot( diff --git a/src/features/journey-curator/api/journeyCuratorServerRun.test.ts b/src/features/journey-curator/api/journeyCuratorServerRun.test.ts index 12e80dd1..39c72ca7 100644 --- a/src/features/journey-curator/api/journeyCuratorServerRun.test.ts +++ b/src/features/journey-curator/api/journeyCuratorServerRun.test.ts @@ -23,6 +23,7 @@ describe('runJourneyCurator', () => { engine: 'BASELINE', degradedReason: null, stage: null, + sequence: 1, outcome: 'INITIAL_BOARD', clarification: null, retryAfterMs: 0, @@ -41,6 +42,7 @@ describe('runJourneyCurator', () => { execution: null, }), cancelRun: vi.fn(), + getAcceptedSnapshots: vi.fn(), applyAction: vi.fn(), subscribeToRunEvents: vi.fn(), }; diff --git a/src/features/journey-curator/api/journeySse.test.ts b/src/features/journey-curator/api/journeySse.test.ts index 7fd5fc30..c66dcc7b 100644 --- a/src/features/journey-curator/api/journeySse.test.ts +++ b/src/features/journey-curator/api/journeySse.test.ts @@ -65,7 +65,7 @@ describe('journey repository actions/SSE (FE #93)', () => { const createEventSource: JourneyEventSourceFactory = () => fake as unknown as EventSource; const received: JourneySseFrame[] = []; - const unsubscribe = repository.subscribeToRunEvents('exp-1', 'run-1', (frame) => received.push(frame), { + const unsubscribe = repository.subscribeToRunEvents('https://journey.example.test/events/run-1', (frame) => received.push(frame), { createEventSource, }); @@ -86,7 +86,7 @@ describe('journey repository actions/SSE (FE #93)', () => { const createEventSource: JourneyEventSourceFactory = () => fake as unknown as EventSource; const onError = vi.fn(); - repository.subscribeToRunEvents('exp-1', 'run-1', () => {}, { createEventSource, onError }); + repository.subscribeToRunEvents('https://journey.example.test/events/run-1', () => {}, { createEventSource, onError }); fake.emit('run.stage', { lastEventId: '1', data: 'not json' }); diff --git a/src/features/journey-curator/application/conversationRepository.ts b/src/features/journey-curator/application/conversationRepository.ts new file mode 100644 index 00000000..57dcdf32 --- /dev/null +++ b/src/features/journey-curator/application/conversationRepository.ts @@ -0,0 +1,30 @@ +import type { RunAccepted } from '../api/journeyApi'; +import type { JourneyRunSnapshot, JourneySseFrame } from '../api/journeyContract'; +import type { + ConversationSnapshot, + ExplorationPage, + ExplorationTurnPage, +} from '../domain/conversation'; + +export interface ConversationRepository { + listExplorations(input?: { limit?: number; cursor?: string }): Promise; + getExploration(explorationId: string): Promise; + listTurns(input: { explorationId: string; limit?: number; cursor?: string }): Promise; + createExploration(input: { query: string; regionCode?: string | null; idempotencyKey: string }): Promise; + createTurn(input: { + explorationId: string; + query: string; + baseVersion: number; + clientTurnId: string; + clarificationAnswer?: { clarificationId: string; choiceId: string | null; text: string | null } | null; + idempotencyKey: string; + }): Promise; + getAcceptedSnapshots(accepted: RunAccepted): Promise<{ run: JourneyRunSnapshot; snapshot: ConversationSnapshot }>; + subscribeToRunEvents( + eventsUrl: string, + onEvent: (frame: JourneySseFrame) => void, + onError: (error: unknown) => void, + ): () => void; + cancelRun(input: { explorationId: string; runId: string; idempotencyKey: string }): Promise; + deleteExploration(input: { explorationId: string; idempotencyKey: string }): Promise; +} diff --git a/src/features/journey-curator/components/JourneyHome.tsx b/src/features/journey-curator/components/JourneyHome.tsx index 98bbef10..68749b2a 100644 --- a/src/features/journey-curator/components/JourneyHome.tsx +++ b/src/features/journey-curator/components/JourneyHome.tsx @@ -1,87 +1,59 @@ 'use client'; -import React, { useRef } from 'react'; -import styled from '@emotion/styled'; -import { surface } from '@/design-system/tokens'; +import { useCallback, useEffect, useState } from 'react'; +import JourneyChatInterface from '../presentation/JourneyChatInterface'; +import { useJourneyConversation } from '../presentation/hooks/useJourneyConversation'; -import { useJourneyStore } from '../store/useJourneyStore'; -import JourneyHeroSearch from './JourneyHeroSearch'; -import JourneyDiscoveryFeed from './JourneyDiscoveryFeed'; -import JourneyFlowRailSection from './JourneyFlowRailSection'; -import JourneyEnrichmentSections from './JourneyEnrichmentSections'; -import JourneyAssemblyLoader from './JourneyAssemblyLoader'; -import HomeBrandAurora from './HomeBrandAurora'; - -const MainWrapper = styled.main` - position: relative; - min-height: 100dvh; - overflow: hidden; - background-color: ${surface.light.card}; - transition: background-color 0.3s ease; - - [data-theme='dark'] & { - background-color: ${surface.dark.app}; - } -`; - -const Landing = styled.div<{ $centered: boolean }>` - position: relative; - z-index: 1; - display: flex; - flex-direction: column; - ${({ $centered }) => - $centered - ? ` - min-height: 74vh; - justify-content: center; - padding-top: 40px; - padding-bottom: 24px; - ` - : ` - padding-top: 80px; - padding-bottom: 12px; - `} - - @media (max-width: 767px) { - min-height: 0; - justify-content: flex-start; - padding-top: ${({ $centered }) => ($centered ? '32px' : '72px')}; - padding-bottom: 0; - } -`; - -const ContentLayer = styled.div` - position: relative; - z-index: 1; -`; +function readExplorationId(): string | null { + if (typeof window === 'undefined') return null; + return new URLSearchParams(window.location.search).get('exploration'); +} export default function JourneyHome() { - const hasSearched = useJourneyStore((s) => s.hasSearched); - const mainRef = useRef(null); - const searchFormRef = useRef(null); - const moodChipsRef = useRef(null); + const [selectedExplorationId, setSelectedExplorationId] = useState(null); + const conversation = useJourneyConversation(selectedExplorationId); + + useEffect(() => { + const syncFromUrl = () => setSelectedExplorationId(readExplorationId()); + syncFromUrl(); + window.addEventListener('popstate', syncFromUrl); + return () => window.removeEventListener('popstate', syncFromUrl); + }, []); + + const selectConversation = useCallback((explorationId: string | null) => { + const url = new URL(window.location.href); + if (explorationId) url.searchParams.set('exploration', explorationId); + else url.searchParams.delete('exploration'); + window.history.pushState({}, '', `${url.pathname}${url.search}`); + setSelectedExplorationId(explorationId); + }, []); + + useEffect(() => { + if (!conversation.activeExplorationId || conversation.activeExplorationId === selectedExplorationId) return; + const url = new URL(window.location.href); + url.searchParams.set('exploration', conversation.activeExplorationId); + window.history.replaceState({}, '', `${url.pathname}${url.search}`); + setSelectedExplorationId(conversation.activeExplorationId); + }, [conversation.activeExplorationId, selectedExplorationId]); return ( - - - - - - - - - {!hasSearched && ( - - - - )} - - {hasSearched && ( - - - - - )} - + void conversation.loadOlderTurns()} + onSend={async (query) => { + if (conversation.activeExplorationId) await conversation.sendTurn(query); + else await conversation.startConversation(query); + }} + onCancel={() => conversation.cancelRun()} + /> ); } diff --git a/src/features/journey-curator/domain/conversation.ts b/src/features/journey-curator/domain/conversation.ts new file mode 100644 index 00000000..412e44f0 --- /dev/null +++ b/src/features/journey-curator/domain/conversation.ts @@ -0,0 +1,58 @@ +import type { JourneyBoard, JourneyProposal, ResourceRef } from '../types/exploration.types'; +import type { JourneyRunSnapshot } from '../api/journeyContract'; + +export type ExplorationSummary = { + explorationId: string; + title: string; + lastUserQueryPreview: string | null; + latestRunStatus: JourneyRunSnapshot['status'] | null; + candidateCount: number; + pinnedCount: number; + updatedAt: string; +}; + +export type ExplorationPage = { + schemaVersion: '1.3'; + items: ExplorationSummary[]; + totalCount: number; + nextCursor: string | null; + hasMore: boolean; +}; + +export type TurnResponse = { + status: 'PENDING' | 'COMPLETED' | 'FAILED' | 'CANCELLED'; + outcome: JourneyRunSnapshot['outcome'] | null; + summary: string | null; + board: JourneyBoard | null; + proposal: JourneyProposal | null; + clarification: JourneyRunSnapshot['clarification']; + error: JourneyRunSnapshot['error']; +}; + +export type ExplorationTurn = { + turnId: string; + query: string; + createdAt: string; + runId: string | null; + response: TurnResponse; +}; + +export type ExplorationTurnPage = { + schemaVersion: '1.3'; + items: ExplorationTurn[]; + nextCursor: string | null; + hasMore: boolean; +}; + +export type ConversationSnapshot = { + schemaVersion: '1.3'; + explorationId: string; + stateVersion: number; + board: JourneyBoard | null; + pinnedRefs: ResourceRef[]; + excludedRefs: ResourceRef[]; + unavailableRefs: ResourceRef[]; + latestRun: JourneyRunSnapshot | null; + pendingProposal: JourneyProposal | null; + updatedAt: string; +}; diff --git a/src/features/journey-curator/domain/journeyConversation.test.ts b/src/features/journey-curator/domain/journeyConversation.test.ts new file mode 100644 index 00000000..43af2e8d --- /dev/null +++ b/src/features/journey-curator/domain/journeyConversation.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest'; +import { getJourneyStageMessage } from './journeyConversation'; + +describe('getJourneyStageMessage', () => { + it('uses the public v1.3 copy for evidence selection and generation', () => { + expect(getJourneyStageMessage('SELECTING_EVIDENCE')).toBe('관련 정보를 다루는 영역을 선택하고 있어요.'); + expect(getJourneyStageMessage('GENERATING')).toBe('찾은 정보를 바탕으로 여행을 정리하고 있어요.'); + }); + + it('keeps an unsupported stage in a safe generic progress state', () => { + expect(getJourneyStageMessage('FUTURE_STAGE')).toBe('여행을 준비하고 있어요.'); + }); +}); diff --git a/src/features/journey-curator/domain/journeyConversation.ts b/src/features/journey-curator/domain/journeyConversation.ts new file mode 100644 index 00000000..f996d81a --- /dev/null +++ b/src/features/journey-curator/domain/journeyConversation.ts @@ -0,0 +1,12 @@ +const STAGE_MESSAGES: Record = { + INTERPRETING: '질문에서 여행 조건을 정리하고 있어요.', + RETRIEVING: '조건에 맞는 장소와 정보를 찾고 있어요.', + SELECTING_EVIDENCE: '관련 정보를 다루는 영역을 선택하고 있어요.', + GENERATING: '찾은 정보를 바탕으로 여행을 정리하고 있어요.', + VALIDATING: '장소 정보와 권장 사항을 확인하고 있어요.', + PERSISTING: '여행 결과를 준비하고 있어요.', +}; + +export function getJourneyStageMessage(stage: string | null | undefined): string { + return (stage && STAGE_MESSAGES[stage]) || '여행을 준비하고 있어요.'; +} diff --git a/src/features/journey-curator/infrastructure/conversationHttpRepository.test.ts b/src/features/journey-curator/infrastructure/conversationHttpRepository.test.ts new file mode 100644 index 00000000..fe1cd597 --- /dev/null +++ b/src/features/journey-curator/infrastructure/conversationHttpRepository.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; +import { createConversationHttpRepository } from './conversationHttpRepository'; + +describe('conversation HTTP repository', () => { + it('reads conversation lists and transcript pages from the public exploration resources', async () => { + const calls: Array<{ path: string; options: unknown }> = []; + const repository = createConversationHttpRepository((async (path: string, options: unknown) => { + calls.push({ path, options }); + return { schemaVersion: '1.3', items: [], totalCount: 0, nextCursor: null, hasMore: false }; + }) as never); + + await repository.listExplorations({ limit: 20, cursor: 'next' }); + await repository.listTurns({ explorationId: 'exploration-1', limit: 10, cursor: 'older' }); + + expect(calls).toEqual([ + { path: '/explorations', options: { method: 'GET', cache: 'no-store', params: { limit: 20, cursor: 'next' } } }, + { + path: '/explorations/exploration-1/turns', + options: { method: 'GET', cache: 'no-store', params: { limit: 10, cursor: 'older' } }, + }, + ]); + }); +}); diff --git a/src/features/journey-curator/infrastructure/conversationHttpRepository.ts b/src/features/journey-curator/infrastructure/conversationHttpRepository.ts new file mode 100644 index 00000000..7dc17379 --- /dev/null +++ b/src/features/journey-curator/infrastructure/conversationHttpRepository.ts @@ -0,0 +1,109 @@ +import { apiRequest, type ApiRequestOptions } from '@/lib/api/client'; +import type { ConversationRepository } from '../application/conversationRepository'; +import type { + ConversationSnapshot, + ExplorationPage, + ExplorationTurnPage, +} from '../domain/conversation'; +import type { RunAccepted } from '../api/journeyApi'; +import type { JourneyRunSnapshot, JourneySseFrame } from '../api/journeyContract'; +import { parseJourneySseFrame } from '../reducers/journeySseParser'; + +type RequestFn = (path: string, options?: ApiRequestOptions) => Promise; + +export function createConversationHttpRepository(request: RequestFn = apiRequest): ConversationRepository { + return { + listExplorations(input) { + return request('/explorations', { + method: 'GET', + cache: 'no-store', + params: { limit: input?.limit ?? 20, cursor: input?.cursor }, + }); + }, + getExploration(explorationId) { + return request(`/explorations/${encodeURIComponent(explorationId)}`, { + method: 'GET', + cache: 'no-store', + }); + }, + listTurns(input) { + return request(`/explorations/${encodeURIComponent(input.explorationId)}/turns`, { + method: 'GET', + cache: 'no-store', + params: { limit: input.limit ?? 20, cursor: input.cursor }, + }); + }, + createExploration(input) { + return request('/explorations', { + method: 'POST', + body: { + query: input.query, + locale: 'ko-KR', + regionCode: input.regionCode ?? null, + }, + csrf: true, + idempotencyKey: input.idempotencyKey, + }); + }, + createTurn(input) { + return request(`/explorations/${encodeURIComponent(input.explorationId)}/turns`, { + method: 'POST', + body: { + clientTurnId: input.clientTurnId, + baseVersion: input.baseVersion, + query: input.query, + clarificationAnswer: input.clarificationAnswer ?? null, + }, + csrf: true, + idempotencyKey: input.idempotencyKey, + }); + }, + async getAcceptedSnapshots(accepted) { + const [run, snapshot] = await Promise.all([ + request(accepted.runUrl, { method: 'GET', cache: 'no-store', rootPath: true }), + request(accepted.snapshotUrl, { method: 'GET', cache: 'no-store', rootPath: true }), + ]); + return { run, snapshot }; + }, + subscribeToRunEvents(eventsUrl, onEvent, onError) { + const source = new EventSource(eventsUrl, { withCredentials: true }); + const eventNames = ['run.stage', 'run.terminal', 'heartbeat', 'reset', 'auth_closed'] as const; + const listeners = eventNames.map((eventName) => { + const listener = (event: Event) => { + const messageEvent = event as MessageEvent; + try { + const frame = parseJourneySseFrame({ id: messageEvent.lastEventId, event: eventName, data: messageEvent.data }); + if (frame) onEvent(frame); + } catch (error) { + onError(error); + } + }; + source.addEventListener(eventName, listener); + return { eventName, listener }; + }); + source.addEventListener('error', onError); + return () => { + listeners.forEach(({ eventName, listener }) => source.removeEventListener(eventName, listener)); + source.removeEventListener('error', onError); + source.close(); + }; + }, + cancelRun(input) { + return request(`/explorations/${encodeURIComponent(input.explorationId)}/runs/${encodeURIComponent(input.runId)}/cancel`, { + method: 'POST', + body: {}, + csrf: true, + idempotencyKey: input.idempotencyKey, + }); + }, + deleteExploration(input) { + return request(`/explorations/${encodeURIComponent(input.explorationId)}`, { + method: 'DELETE', + csrf: true, + idempotencyKey: input.idempotencyKey, + }); + }, + }; +} + +export const conversationHttpRepository = createConversationHttpRepository(); diff --git a/src/features/journey-curator/presentation/JourneyChatInterface.tsx b/src/features/journey-curator/presentation/JourneyChatInterface.tsx new file mode 100644 index 00000000..318b450a --- /dev/null +++ b/src/features/journey-curator/presentation/JourneyChatInterface.tsx @@ -0,0 +1,523 @@ +'use client'; + +import { FormEvent, useState } from 'react'; +import styled from '@emotion/styled'; +import type { ExplorationSummary, ExplorationTurn } from '../domain/conversation'; +import type { JourneyBoard, PlaceResource } from '../types/exploration.types'; + +type Props = { + explorations: ExplorationSummary[]; + activeExplorationId: string | null; + turns: ExplorationTurn[]; + pendingQuery: string | null; + progressMessage: string | null; + loading: boolean; + loadingOlder: boolean; + hasOlderTurns: boolean; + error: string | null; + onSelectConversation: (explorationId: string | null) => void; + onLoadOlder: () => void; + onSend: (query: string) => Promise; + onCancel: () => Promise; +}; + +const Page = styled.main` + min-height: 100dvh; + padding: 84px 20px 24px; + background: #f8f8f7; + color: #202124; + + [data-theme='dark'] & { + background: #171717; + color: #f5f5f5; + } + + @media (max-width: 720px) { + padding: 68px 0 0; + } +`; + +const Layout = styled.div` + width: min(1240px, 100%); + min-height: calc(100dvh - 108px); + margin: 0 auto; + display: grid; + grid-template-columns: 260px minmax(0, 1fr); + overflow: hidden; + border: 1px solid #e5e5e3; + border-radius: 24px; + background: #fff; + box-shadow: 0 18px 56px rgba(25, 25, 25, 0.08); + + [data-theme='dark'] & { + background: #202020; + border-color: #373737; + } + + @media (max-width: 720px) { + grid-template-columns: 1fr; + min-height: calc(100dvh - 68px); + border-radius: 0; + border-inline: 0; + } +`; + +const Sidebar = styled.aside` + display: flex; + flex-direction: column; + min-width: 0; + border-right: 1px solid #e5e5e3; + background: #f5f5f4; + + [data-theme='dark'] & { + background: #1c1c1c; + border-color: #373737; + } + + @media (max-width: 720px) { + flex-direction: row; + overflow-x: auto; + border-right: 0; + border-bottom: 1px solid #e5e5e3; + padding: 10px 12px; + gap: 8px; + scrollbar-width: none; + } +`; + +const NewChatButton = styled.button` + margin: 16px; + padding: 11px 14px; + border: 0; + border-radius: 12px; + background: #202124; + color: #fff; + font: inherit; + font-weight: 700; + cursor: pointer; + + &:hover { background: #383838; } + + @media (max-width: 720px) { + margin: 0; + white-space: nowrap; + } +`; + +const ConversationList = styled.div` + display: flex; + flex: 1; + flex-direction: column; + gap: 4px; + padding: 0 10px 14px; + overflow-y: auto; + + @media (max-width: 720px) { + flex-direction: row; + overflow: visible; + padding: 0; + } +`; + +const ConversationButton = styled.button<{ $active: boolean }>` + width: 100%; + padding: 11px 12px; + border: 0; + border-radius: 12px; + background: ${({ $active }) => ($active ? '#e5e5e3' : 'transparent')}; + color: inherit; + text-align: left; + cursor: pointer; + + &:hover { background: #e5e5e3; } + + [data-theme='dark'] & { + background: ${({ $active }) => ($active ? '#393939' : 'transparent')}; + &:hover { background: #393939; } + } + + @media (max-width: 720px) { + width: 190px; + flex: 0 0 190px; + } +`; + +const ConversationTitle = styled.span` + display: block; + overflow: hidden; + font-size: 13px; + font-weight: 700; + text-overflow: ellipsis; + white-space: nowrap; +`; + +const ConversationMeta = styled.span` + display: block; + margin-top: 4px; + overflow: hidden; + color: #777; + font-size: 12px; + text-overflow: ellipsis; + white-space: nowrap; +`; + +const Chat = styled.section` + display: grid; + grid-template-rows: auto minmax(0, 1fr) auto; + min-width: 0; + min-height: 0; +`; + +const ChatHeader = styled.header` + padding: 20px 24px 16px; + border-bottom: 1px solid #ededeb; + + [data-theme='dark'] & { border-color: #373737; } +`; + +const Title = styled.h1` + margin: 0; + font-size: clamp(20px, 2.6vw, 28px); + letter-spacing: -0.035em; +`; + +const Subtitle = styled.p` + margin: 5px 0 0; + color: #737373; + font-size: 13px; + line-height: 1.5; +`; + +const Transcript = styled.div` + min-height: 0; + overflow-y: auto; + padding: 28px clamp(16px, 4vw, 56px); +`; + +const LoadOlderButton = styled.button` + display: block; + margin: 0 auto 22px; + padding: 8px 12px; + border: 1px solid #dededc; + border-radius: 999px; + background: #fff; + color: #4a4a4a; + font: inherit; + font-size: 13px; + cursor: pointer; +`; + +const MessageGroup = styled.article<{ $user?: boolean }>` + display: flex; + flex-direction: column; + align-items: ${({ $user }) => ($user ? 'flex-end' : 'flex-start')}; + gap: 8px; + margin: 0 0 24px; +`; + +const Bubble = styled.div<{ $user?: boolean }>` + max-width: min(700px, 88%); + padding: 13px 16px; + border-radius: ${({ $user }) => ($user ? '18px 18px 4px 18px' : '18px 18px 18px 4px')}; + background: ${({ $user }) => ($user ? '#242424' : '#f1f1ef')}; + color: ${({ $user }) => ($user ? '#fff' : '#242424')}; + font-size: 15px; + line-height: 1.65; + white-space: pre-wrap; + + [data-theme='dark'] & { + background: ${({ $user }) => ($user ? '#f5f5f5' : '#303030')}; + color: ${({ $user }) => ($user ? '#202124' : '#f5f5f5')}; + } +`; + +const AssistantCard = styled.div` + width: min(760px, 100%); + overflow: hidden; + border: 1px solid #e5e5e3; + border-radius: 18px; + background: #fff; + + [data-theme='dark'] & { + border-color: #414141; + background: #242424; + } +`; + +const AssistantCopy = styled.p` + margin: 0; + padding: 15px 16px 8px; + font-size: 14px; + line-height: 1.65; +`; + +const Places = styled.div` + display: flex; + gap: 12px; + overflow-x: auto; + padding: 8px 16px 16px; + scroll-snap-type: x mandatory; + scrollbar-width: thin; +`; + +const PlaceCard = styled.article` + flex: 0 0 min(220px, 68vw); + overflow: hidden; + border: 1px solid #e5e5e3; + border-radius: 14px; + background: #fff; + scroll-snap-align: start; + transition: transform 180ms ease, box-shadow 180ms ease; + + &:hover { transform: translateY(-3px); box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1); } + + [data-theme='dark'] & { background: #2a2a2a; border-color: #444; } + + @media (prefers-reduced-motion: reduce) { + transition: none; + &:hover { transform: none; } + } +`; + +const PlaceImage = styled.div` + aspect-ratio: 4 / 3; + overflow: hidden; + background: #dededc; + + img { + width: 100%; + height: 100%; + object-fit: cover; + } +`; + +const PlaceContent = styled.div` + padding: 11px 12px 12px; +`; + +const PlaceTitle = styled.h3` + margin: 0; + font-size: 14px; +`; + +const PlaceMeta = styled.p` + margin: 4px 0 0; + color: #777; + font-size: 12px; +`; + +const Source = styled.p` + margin: 0; + padding: 0 16px 14px; + color: #777; + font-size: 11px; +`; + +const Progress = styled.div` + display: inline-flex; + align-items: center; + gap: 9px; + padding: 12px 14px; + border-radius: 16px 16px 16px 4px; + background: #f1f1ef; + color: #4a4a4a; + font-size: 14px; + + &::before { + width: 8px; + height: 8px; + border-radius: 50%; + background: #555; + content: ''; + animation: pulse 1.1s ease-in-out infinite; + } + + @keyframes pulse { 50% { opacity: 0.35; transform: scale(0.72); } } + @media (prefers-reduced-motion: reduce) { &::before { animation: none; } } +`; + +const Empty = styled.div` + max-width: 620px; + margin: 48px auto; + color: #5f5f5f; + text-align: center; +`; + +const SuggestionRow = styled.div` + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 8px; + margin-top: 20px; +`; + +const Suggestion = styled.button` + padding: 9px 12px; + border: 1px solid #dededc; + border-radius: 999px; + background: #fff; + color: #333; + font: inherit; + font-size: 13px; + cursor: pointer; +`; + +const Composer = styled.form` + display: flex; + gap: 10px; + padding: 15px clamp(16px, 4vw, 56px) 20px; + border-top: 1px solid #ededeb; + + [data-theme='dark'] & { border-color: #373737; } +`; + +const Input = styled.input` + min-width: 0; + flex: 1; + padding: 13px 14px; + border: 1px solid #d5d5d2; + border-radius: 14px; + background: #fff; + color: inherit; + font: inherit; + + [data-theme='dark'] & { background: #292929; border-color: #464646; } +`; + +const SendButton = styled.button` + padding: 0 16px; + border: 0; + border-radius: 14px; + background: #242424; + color: #fff; + font: inherit; + font-weight: 700; + cursor: pointer; + + &:disabled { cursor: not-allowed; opacity: 0.55; } +`; + +function findPlaces(board: JourneyBoard | null): PlaceResource[] { + return board?.resources.filter((resource): resource is PlaceResource => resource.ref.type === 'PLACE') ?? []; +} + +function AssistantResponse({ turn }: { turn: ExplorationTurn }) { + const { response } = turn; + if (response.status === 'PENDING') return null; + if (response.status === 'CANCELLED') return 요청이 취소되었어요.; + if (response.status === 'FAILED') return 요청을 완료하지 못했어요. {response.error?.requestId ? `요청 번호: ${response.error.requestId}` : ''}; + if (response.outcome === 'NO_RESULTS') return {response.summary ?? '조건에 맞는 여행 결과를 찾지 못했어요.'}; + + const places = findPlaces(response.board); + return ( + + {response.summary ?? (response.board ? response.board.querySummary : '여행 결과를 준비했어요.')} + {places.length > 0 && ( + + {places.map((place) => ( + + + {place.image && {place.image.alt}} + + + {place.title} + {place.category} · {place.regionRef.id} + {place.summary && {place.summary}} + + + ))} + + )} + {places.some((place) => place.image?.sourceName) && ( + 사진 출처: {places.map((place) => place.image?.sourceName).filter(Boolean).join(', ')} + )} + + ); +} + +export default function JourneyChatInterface({ + explorations, + activeExplorationId, + turns, + pendingQuery, + progressMessage, + loading, + loadingOlder, + hasOlderTurns, + error, + onSelectConversation, + onLoadOlder, + onSend, + onCancel, +}: Props) { + const [draft, setDraft] = useState(''); + const isRunning = Boolean(progressMessage); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + const query = draft.trim(); + if (!query || isRunning) return; + setDraft(''); + await onSend(query); + }; + + return ( + + + + onSelectConversation(null)}>새 대화 + + {explorations.map((conversation) => ( + onSelectConversation(conversation.explorationId)} + > + {conversation.title} + {conversation.lastUserQueryPreview ?? '여정 대화'} + + ))} + + + + + + AI 여정 대화 + 조건을 말해 주시면, 사진과 장소를 보며 함께 여행을 만들어 가요. + + + + {hasOlderTurns && {loadingOlder ? '불러오는 중…' : '이전 대화 더 보기'}} + {!activeExplorationId && !pendingQuery && ( + +

어떤 여행을 함께 만들어 볼까요?

+

장소, 분위기, 이동 시간처럼 원하는 조건을 편하게 말해 주세요.

+ + {['비 오는 날 조용한 서울 산책', '아이와 함께 가기 좋은 한옥 여행', '전주에서 하루 동안 걷는 여행'].map((suggestion) => ( + void onSend(suggestion)}>{suggestion} + ))} + +
+ )} + {loading && activeExplorationId && 대화를 불러오는 중이에요.} + {turns.map((turn) => ( +
+ {turn.query} + +
+ ))} + {pendingQuery && {pendingQuery}} + {progressMessage && {progressMessage}} + {error && {error}} +
+ + + setDraft(event.target.value)} placeholder="여행 조건을 이어서 물어보세요" aria-label="여행 질문" disabled={isRunning} /> + {isRunning ? void onCancel()}>취소 : 보내기} + +
+
+
+ ); +} diff --git a/src/features/journey-curator/presentation/hooks/useJourneyConversation.ts b/src/features/journey-curator/presentation/hooks/useJourneyConversation.ts new file mode 100644 index 00000000..2215018c --- /dev/null +++ b/src/features/journey-curator/presentation/hooks/useJourneyConversation.ts @@ -0,0 +1,279 @@ +'use client'; + +import { useCallback, useEffect, useRef, useState } from 'react'; +import type { ConversationRepository } from '../../application/conversationRepository'; +import type { + ConversationSnapshot, + ExplorationSummary, + ExplorationTurn, +} from '../../domain/conversation'; +import { getJourneyStageMessage } from '../../domain/journeyConversation'; +import { conversationHttpRepository } from '../../infrastructure/conversationHttpRepository'; +import type { RunAccepted } from '../../api/journeyApi'; +import type { JourneyRunSnapshot, JourneySseFrame } from '../../api/journeyContract'; +import { generateUUID } from '@/lib/uuid'; + +type ConversationProgress = { + runId: string; + stage: string | null; + message: string; +} | null; + +const createUuid = generateUUID; + +function isActiveRun(run: JourneyRunSnapshot | null): boolean { + return run?.status === 'QUEUED' || run?.status === 'RUNNING'; +} + +export type JourneyConversationState = { + explorations: ExplorationSummary[]; + activeExplorationId: string | null; + snapshot: ConversationSnapshot | null; + turns: ExplorationTurn[]; + progress: ConversationProgress; + pendingQuery: string | null; + loading: boolean; + loadingOlder: boolean; + olderCursor: string | null; + hasOlderTurns: boolean; + error: string | null; +}; + +export function useJourneyConversation( + activeExplorationId: string | null, + repository: ConversationRepository = conversationHttpRepository, +) { + const [state, setState] = useState({ + explorations: [], + activeExplorationId, + snapshot: null, + turns: [], + progress: null, + pendingQuery: null, + loading: true, + loadingOlder: false, + olderCursor: null, + hasOlderTurns: false, + error: null, + }); + const unsubscribeRef = useRef<(() => void) | null>(null); + const loadVersionRef = useRef(0); + const activeIdRef = useRef(activeExplorationId); + const acceptedRef = useRef(null); + const latestSequenceRef = useRef(0); + const recoveringRef = useRef(false); + + const closeStream = useCallback(() => { + unsubscribeRef.current?.(); + unsubscribeRef.current = null; + }, []); + + const refreshSidebar = useCallback(async () => { + const page = await repository.listExplorations({ limit: 20 }); + setState((current) => ({ ...current, explorations: page.items })); + }, [repository]); + + const loadConversation = useCallback(async (explorationId: string, options?: { preserveTurns?: boolean }) => { + const version = ++loadVersionRef.current; + activeIdRef.current = explorationId; + setState((current) => ({ + ...current, + activeExplorationId: explorationId, + loading: !options?.preserveTurns, + error: null, + })); + + try { + const [snapshot, turnPage] = await Promise.all([ + repository.getExploration(explorationId), + repository.listTurns({ explorationId, limit: 20 }), + ]); + if (version !== loadVersionRef.current || activeIdRef.current !== explorationId) return; + + latestSequenceRef.current = snapshot.latestRun?.sequence ?? 0; + setState((current) => ({ + ...current, + activeExplorationId: explorationId, + snapshot, + turns: [...turnPage.items].reverse(), + progress: isActiveRun(snapshot.latestRun) + ? { + runId: snapshot.latestRun!.runId, + stage: snapshot.latestRun!.stage, + message: getJourneyStageMessage(snapshot.latestRun!.stage), + } + : null, + pendingQuery: null, + loading: false, + olderCursor: turnPage.nextCursor, + hasOlderTurns: turnPage.hasMore, + })); + } catch { + if (version !== loadVersionRef.current) return; + setState((current) => ({ ...current, loading: false, error: '대화를 불러오지 못했어요. 잠시 후 다시 시도해 주세요.' })); + } + }, [repository]); + + const recoverAcceptedRun = useCallback(async (accepted: RunAccepted) => { + if (recoveringRef.current) return; + recoveringRef.current = true; + closeStream(); + + try { + const { run, snapshot } = await repository.getAcceptedSnapshots(accepted); + if (activeIdRef.current !== accepted.explorationId) return; + + latestSequenceRef.current = run.sequence; + setState((current) => ({ + ...current, + snapshot, + progress: isActiveRun(run) + ? { runId: run.runId, stage: run.stage, message: getJourneyStageMessage(run.stage) } + : null, + })); + + if (!isActiveRun(run)) { + await loadConversation(accepted.explorationId, { preserveTurns: true }); + await refreshSidebar(); + return; + } + + unsubscribeRef.current = repository.subscribeToRunEvents( + accepted.eventsUrl, + (frame: JourneySseFrame) => { + if (activeIdRef.current !== accepted.explorationId) return; + if (frame.event === 'reset' || frame.event === 'run.terminal') { + void recoverAcceptedRun(accepted); + return; + } + if (frame.event === 'auth_closed') { + closeStream(); + setState((current) => ({ ...current, error: '로그인이 필요해요.' })); + return; + } + if (frame.data.sequence <= latestSequenceRef.current) return; + latestSequenceRef.current = frame.data.sequence; + if (frame.event === 'run.stage') { + setState((current) => ({ + ...current, + progress: { + runId: frame.data.runId, + stage: frame.data.stage, + message: getJourneyStageMessage(frame.data.stage), + }, + })); + } + }, + () => { + // EventSource retries itself. A server terminal/reset is handled by its explicit event. + }, + ); + } catch { + if (activeIdRef.current === accepted.explorationId) { + setState((current) => ({ ...current, error: '여정 상태를 복구하지 못했어요. 잠시 후 다시 시도해 주세요.' })); + } + } finally { + recoveringRef.current = false; + } + }, [closeStream, loadConversation, refreshSidebar, repository]); + + const beginRun = useCallback(async (accepted: RunAccepted) => { + acceptedRef.current = accepted; + activeIdRef.current = accepted.explorationId; + setState((current) => ({ ...current, activeExplorationId: accepted.explorationId })); + await recoverAcceptedRun(accepted); + }, [recoverAcceptedRun]); + + const startConversation = useCallback(async (query: string) => { + const trimmed = query.trim(); + if (!trimmed) return; + setState((current) => ({ ...current, pendingQuery: trimmed, error: null })); + try { + const accepted = await repository.createExploration({ query: trimmed, idempotencyKey: createUuid() }); + await beginRun(accepted); + } catch { + setState((current) => ({ ...current, pendingQuery: null, error: '여정을 시작하지 못했어요. 잠시 후 다시 시도해 주세요.' })); + } + }, [beginRun, repository]); + + const sendTurn = useCallback(async (query: string) => { + const trimmed = query.trim(); + const snapshot = state.snapshot; + if (!trimmed || !snapshot || isActiveRun(snapshot.latestRun)) return; + setState((current) => ({ ...current, pendingQuery: trimmed, error: null })); + try { + const accepted = await repository.createTurn({ + explorationId: snapshot.explorationId, + query: trimmed, + baseVersion: snapshot.stateVersion, + clientTurnId: createUuid(), + idempotencyKey: createUuid(), + }); + await beginRun(accepted); + } catch { + setState((current) => ({ ...current, pendingQuery: null, error: '질문을 보내지 못했어요. 잠시 후 다시 시도해 주세요.' })); + } + }, [beginRun, repository, state.snapshot]); + + const loadOlderTurns = useCallback(async () => { + const explorationId = state.activeExplorationId; + if (!explorationId || state.loadingOlder || !state.hasOlderTurns) return; + setState((current) => ({ ...current, loadingOlder: true })); + try { + const page = await repository.listTurns({ explorationId, limit: 20, cursor: state.olderCursor ?? undefined }); + setState((current) => ({ + ...current, + turns: [...page.items].reverse().concat(current.turns), + olderCursor: page.nextCursor, + hasOlderTurns: page.hasMore, + loadingOlder: false, + })); + } catch { + setState((current) => ({ ...current, loadingOlder: false, error: '이전 대화를 불러오지 못했어요.' })); + } + }, [repository, state.activeExplorationId, state.hasOlderTurns, state.loadingOlder]); + + const cancelRun = useCallback(async () => { + const snapshot = state.snapshot; + const runId = acceptedRef.current?.runId ?? snapshot?.latestRun?.runId; + if (!snapshot || !runId) return; + try { + await repository.cancelRun({ explorationId: snapshot.explorationId, runId, idempotencyKey: createUuid() }); + if (acceptedRef.current) await recoverAcceptedRun(acceptedRef.current); + else await loadConversation(snapshot.explorationId); + } catch { + setState((current) => ({ ...current, error: '실행을 취소하지 못했어요. 잠시 후 다시 시도해 주세요.' })); + } + }, [loadConversation, recoverAcceptedRun, repository, state.snapshot]); + + useEffect(() => { + void refreshSidebar().catch(() => { + setState((current) => ({ ...current, loading: false, error: '대화 목록을 불러오지 못했어요.' })); + }); + }, [refreshSidebar]); + + useEffect(() => { + if (activeExplorationId && activeExplorationId === activeIdRef.current) return; + closeStream(); + acceptedRef.current = null; + if (!activeExplorationId) { + activeIdRef.current = null; + setState((current) => ({ ...current, activeExplorationId: null, snapshot: null, turns: [], progress: null, pendingQuery: null, loading: false })); + return; + } + void loadConversation(activeExplorationId); + return closeStream; + }, [activeExplorationId, closeStream, loadConversation]); + + useEffect(() => () => closeStream(), [closeStream]); + + return { + ...state, + loadConversation, + startConversation, + sendTurn, + loadOlderTurns, + cancelRun, + refreshSidebar, + }; +} diff --git a/src/features/journey-curator/reducers/journeyRunReducer.test.ts b/src/features/journey-curator/reducers/journeyRunReducer.test.ts index 63a1a5c5..d583bf6e 100644 --- a/src/features/journey-curator/reducers/journeyRunReducer.test.ts +++ b/src/features/journey-curator/reducers/journeyRunReducer.test.ts @@ -7,6 +7,38 @@ import { } from './journeyRunReducer'; describe('journey run reducer', () => { + it('ignores duplicate and out-of-order replay events', () => { + const newer = parseJourneySseFrame({ + id: '2', + event: 'run.stage', + data: JSON.stringify({ schemaVersion: '1.3', runId: '00000000-0000-4000-8000-0000-000000000001', sequence: 2, status: 'RUNNING', stage: 'GENERATING' }), + }); + const older = parseJourneySseFrame({ + id: '1', + event: 'run.stage', + data: JSON.stringify({ schemaVersion: '1.3', runId: '00000000-0000-4000-8000-0000-000000000001', sequence: 1, status: 'RUNNING', stage: 'RETRIEVING' }), + }); + + expect(newer).not.toBeNull(); + expect(older).not.toBeNull(); + + const afterNewer = reduceJourneyRunState(createInitialJourneyRunState(), { type: 'sse-frame', frame: newer! }); + const afterOlder = reduceJourneyRunState(afterNewer, { type: 'sse-frame', frame: older! }); + + expect(afterOlder).toBe(afterNewer); + expect(afterOlder.latestSequence).toBe(2); + }); + + it('ignores an unsupported SSE event without interrupting the run', () => { + const frame = parseJourneySseFrame({ + id: '3', + event: 'run.future_event', + data: JSON.stringify({ schemaVersion: '1.3', runId: '00000000-0000-4000-8000-0000-000000000002' }), + }); + + expect(frame).toBeNull(); + }); + it('parses terminal frames without treating them as renderable board data', () => { const frame = parseJourneySseFrame({ id: '2', @@ -20,7 +52,7 @@ describe('journey run reducer', () => { }), }); - const state = reduceJourneyRunState(createInitialJourneyRunState(), { type: 'sse-frame', frame }); + const state = reduceJourneyRunState(createInitialJourneyRunState(), { type: 'sse-frame', frame: frame! }); expect(state.connection.status).toBe('terminal'); expect(state.renderSource).toBe('snapshot'); @@ -33,7 +65,7 @@ describe('journey run reducer', () => { data: JSON.stringify({ schemaVersion: '1.2', runId: '00000000-0000-4000-8000-000000000002' }), }); - const state = reduceJourneyRunState(createInitialJourneyRunState(), { type: 'sse-frame', frame }); + const state = reduceJourneyRunState(createInitialJourneyRunState(), { type: 'sse-frame', frame: frame! }); expect(state.connection.status).toBe('reset'); expect(shouldRecoverJourneySnapshot(state)).toBe(true); @@ -49,6 +81,7 @@ describe('journey run reducer', () => { engine: 'BASELINE', degradedReason: 'AI_TIMEOUT', stage: null, + sequence: 1, outcome: 'INITIAL_BOARD', clarification: null, retryAfterMs: 0, diff --git a/src/features/journey-curator/reducers/journeyRunReducer.ts b/src/features/journey-curator/reducers/journeyRunReducer.ts index bffb8997..7115e0b6 100644 --- a/src/features/journey-curator/reducers/journeyRunReducer.ts +++ b/src/features/journey-curator/reducers/journeyRunReducer.ts @@ -67,6 +67,7 @@ export function reduceJourneyRunState( badgeLabel: badgeFromSnapshot(event.run), renderSource: 'snapshot', run: event.run, + latestSequence: event.run.sequence, needsSnapshotRecovery: false, connection: { ...state.connection, @@ -76,6 +77,15 @@ export function reduceJourneyRunState( } const frame = event.frame; + if ( + frame.event !== 'reset' && + frame.event !== 'auth_closed' && + state.latestSequence !== null && + frame.data.sequence <= state.latestSequence + ) { + return state; + } + if (frame.event === 'run.stage') { return { ...state, diff --git a/src/features/journey-curator/reducers/journeySseParser.ts b/src/features/journey-curator/reducers/journeySseParser.ts index fa49c9f8..fd65ce6a 100644 --- a/src/features/journey-curator/reducers/journeySseParser.ts +++ b/src/features/journey-curator/reducers/journeySseParser.ts @@ -21,7 +21,7 @@ function requireReplayId(event: string, id?: string): string { return id; } -export function parseJourneySseFrame(input: RawFrame): JourneySseFrame { +export function parseJourneySseFrame(input: RawFrame): JourneySseFrame | null { const data = parseData(input.data); switch (input.event) { @@ -36,6 +36,6 @@ export function parseJourneySseFrame(input: RawFrame): JourneySseFrame { case 'auth_closed': return { event: 'auth_closed', data: 0 }; default: - throw new Error('Unsupported journey SSE event'); + return null; } } diff --git a/src/features/journey-curator/store/useJourneyStore.ts b/src/features/journey-curator/store/useJourneyStore.ts index c98b2d93..11e6e058 100644 --- a/src/features/journey-curator/store/useJourneyStore.ts +++ b/src/features/journey-curator/store/useJourneyStore.ts @@ -7,6 +7,7 @@ import { defaultJourneyRepository, type RunAccepted, type ExplorationSnapshot } import { fetchExplorationBoard } from '../api/explorationApi'; import { isOnmaruApiError } from '@/lib/api/errors'; import { USE_MOCK } from '@/lib/api/client'; +import { generateUUID } from '@/lib/uuid'; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); @@ -114,7 +115,7 @@ function runWithSse(accepted: RunAccepted, set: SetFn, gen: number, timeoutMs = const fetchAndResolve = async () => { cleanup(); try { - const snapshot = await defaultJourneyRepository.getExploration(accepted.explorationId); + const { snapshot } = await defaultJourneyRepository.getAcceptedSnapshots(accepted); if ( snapshot.latestRun?.runId === accepted.runId && snapshot.latestRun?.status === 'COMPLETED' && @@ -137,8 +138,7 @@ function runWithSse(accepted: RunAccepted, set: SetFn, gen: number, timeoutMs = const doSubscribe = () => { unsubscribe = defaultJourneyRepository.subscribeToRunEvents( - accepted.explorationId, - accepted.runId, + accepted.eventsUrl, (frame) => { if (gen !== currentGen) { cleanup(); return; } if (frame.event === 'run.terminal' || frame.event === 'reset') { @@ -178,7 +178,7 @@ async function runInitialExploration(query: string, set: SetFn, gen: number) { try { const accepted = await defaultJourneyRepository.start({ query, - idempotencyKey: `journey-${Date.now()}-${Math.random().toString(16).slice(2)}`, + idempotencyKey: generateUUID(), }); if (gen !== currentGen) return; set({ explorationId: accepted.explorationId, runId: accepted.runId }); @@ -318,8 +318,8 @@ export const useJourneyStore = create((set, get) => ({ explorationId, query: prompt, baseVersion: stateVersion, - clientTurnId: `turn-${Date.now()}`, - idempotencyKey: `turn-${Date.now()}-${Math.random().toString(16).slice(2)}`, + clientTurnId: generateUUID(), + idempotencyKey: generateUUID(), }); const snapshot = await runWithSse(accepted, set, currentGen); diff --git a/src/features/map/application/selectCulturalCollection.test.ts b/src/features/map/application/selectCulturalCollection.test.ts new file mode 100644 index 00000000..dd6925ff --- /dev/null +++ b/src/features/map/application/selectCulturalCollection.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest'; +import { selectCulturalCollection } from './selectCulturalCollection'; + +const collections = [{ + id: 'bukchon', + scope: 'hanok-home' as const, + title: { ko: '북촌' }, + subtitle: { ko: '한옥' }, + provenance: 'Editorial', + placeRefs: [], +}]; + +describe('selectCulturalCollection', () => { + it('returns the collection for an exact discovery scope', () => { + expect(selectCulturalCollection(collections, 'hanok-home')?.id).toBe('bukchon'); + }); + + it('returns null for utility or unmatched scopes', () => { + expect(selectCulturalCollection(collections, 'utility')).toBeNull(); + expect(selectCulturalCollection(collections, 'region-home')).toBeNull(); + }); +}); diff --git a/src/features/map/application/selectCulturalCollection.ts b/src/features/map/application/selectCulturalCollection.ts new file mode 100644 index 00000000..e5263f73 --- /dev/null +++ b/src/features/map/application/selectCulturalCollection.ts @@ -0,0 +1,12 @@ +import type { + CulturalCollection, + CulturalCollectionScope, +} from '@/features/map/domain/culturalCollection'; + +export function selectCulturalCollection( + collections: readonly CulturalCollection[], + scope: CulturalCollectionScope, +): CulturalCollection | null { + if (scope === 'utility') return null; + return collections.find((collection) => collection.scope === scope) ?? null; +} diff --git a/src/features/map/components/CulturalDiscoveryCollection.test.tsx b/src/features/map/components/CulturalDiscoveryCollection.test.tsx new file mode 100644 index 00000000..08bef81b --- /dev/null +++ b/src/features/map/components/CulturalDiscoveryCollection.test.tsx @@ -0,0 +1,44 @@ +// @vitest-environment jsdom + +import { render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import CulturalDiscoveryCollection from './CulturalDiscoveryCollection'; + +const collection = { + id: 'hanok-neighborhoods', + scope: 'hanok-home' as const, + title: { ko: '동네 이야기', en: 'Stories in the neighborhood' }, + subtitle: { ko: '동네의 이야기를 발견하세요.', en: 'Discover how Hanok culture connects this neighborhood.' }, + provenance: 'OnMaru editorial collection', + placeRefs: [{ placeId: 'p-1' }], + paths: [ + { id: 'stay', label: '한옥에 머물다', category: 'stay' as const, searchQuery: '한옥스테이' }, + { id: 'food', label: '지역을 맛보다', category: 'food' as const, searchQuery: '향토음식' }, + ], +}; +const place = { id: 'p-1', name: '북촌 한옥', category: 'spot' as const, lat: 37.58, lng: 126.98, addr: '서울', image: null, tel: null, dist: null, isTraditional: true }; +const unrelatedPlace = { id: 'p-2', name: '일반 카페', category: 'cafe' as const, lat: 37.58, lng: 126.98, addr: '서울', image: null, tel: null, dist: null, isTraditional: false }; + +describe('CulturalDiscoveryCollection', () => { + it('renders title before cultural context and uses supplied place selection', () => { + const onPlaceSelect = vi.fn(); + const onPathSelect = vi.fn(); + render( + , + ); + expect(screen.getByRole('heading', { name: collection.title.ko })).toBeTruthy(); + expect(screen.queryByText(collection.title.en!)).toBeNull(); + expect(screen.getByRole('link', { name: 'HANOK CULTURE WALK' }).getAttribute('href')).toBe('/hanok'); + screen.getByRole('button', { name: place.name }).click(); + expect(onPlaceSelect).toHaveBeenCalledWith(place); + expect(screen.queryByRole('button', { name: unrelatedPlace.name })).toBeNull(); + screen.getByRole('button', { name: '지역을 맛보다' }).click(); + expect(onPathSelect).toHaveBeenCalledWith(collection.paths[1]); + }); +}); diff --git a/src/features/map/components/CulturalDiscoveryCollection.tsx b/src/features/map/components/CulturalDiscoveryCollection.tsx new file mode 100644 index 00000000..4f916c56 --- /dev/null +++ b/src/features/map/components/CulturalDiscoveryCollection.tsx @@ -0,0 +1,180 @@ +'use client'; + +import styled from '@emotion/styled'; +import type { CulturalCollection, CulturalCollectionPath } from '@/features/map/domain/culturalCollection'; +import type { Item } from '@/features/map/types'; + +const Section = styled.section` + margin: 16px 14px 20px; + padding: 0 0 18px; + border-bottom: 1px solid #e5e5e3; +`; + +const Title = styled.h2` + margin: 0; + color: #1f2937; + font-size: 1.0625rem; + font-weight: 750; + letter-spacing: -0.025em; + line-height: 1.4; +`; + +const Subtitle = styled.p` + margin: 7px 0 14px; + color: #656565; + font-size: 0.875rem; + line-height: 1.55; +`; + +const Paths = styled.div` + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 6px; + margin-bottom: 14px; +`; + +const PathButton = styled.button` + min-height: 38px; + padding: 8px 10px; + border: 1px solid #e5e5e3; + border-radius: 9px; + background: #f8f8f7; + color: #475569; + font: inherit; + font-size: 0.75rem; + font-weight: 700; + letter-spacing: -0.015em; + text-align: left; + cursor: pointer; + + &:hover { + border-color: #b8b8b4; + background: #fff; + color: #1f2937; + } + + &:focus-visible { + outline: 2px solid #475569; + outline-offset: 2px; + } +`; + +const Places = styled.div` + display: grid; + gap: 6px; +`; + +const PlaceButton = styled.button` + display: flex; + align-items: center; + justify-content: space-between; + width: 100%; + min-height: 48px; + padding: 11px 12px 11px 14px; + border: 1px solid #e5e5e3; + border-radius: 12px; + background: #fff; + color: #303030; + font: inherit; + font-size: 0.875rem; + font-weight: 600; + letter-spacing: -0.015em; + text-align: left; + transition: border-color 150ms ease, background-color 150ms ease, transform 150ms ease; + cursor: pointer; + + &::after { + color: #8a8a88; + content: '↗'; + font-size: 1rem; + font-weight: 400; + } + + &:hover { + border-color: #b8b8b4; + background: #f8f8f7; + } + + &:focus-visible { + outline: 2px solid #475569; + outline-offset: 2px; + } + + &:active { + transform: translateY(1px); + } +`; + +const HanokLink = styled.a` + display: inline-flex; + align-items: center; + gap: 6px; + margin: 0 0 5px; + color: #64748b; + font-size: 0.6875rem; + font-weight: 800; + letter-spacing: 0.08em; + line-height: 1.4; + text-decoration: underline; + text-decoration-color: #94a3b8; + text-decoration-thickness: 1px; + text-underline-offset: 4px; + + &::after { + content: '\\2197'; + font-size: 0.95rem; + transition: transform 150ms ease; + } + + &:hover { + color: #1f2937; + text-decoration-color: currentColor; + } + + &:hover::after { + transform: translateX(2px); + } + + &:focus-visible { + outline: 2px solid #475569; + outline-offset: 3px; + } +`; + +interface Props { + collection: CulturalCollection; + places: Item[]; + loading: boolean; + onPlaceSelect: (place: Item) => void; + onPathSelect: (path: CulturalCollectionPath) => void; +} + +export default function CulturalDiscoveryCollection({ collection, places, loading, onPlaceSelect, onPathSelect }: Props) { + const referenced = collection.placeRefs.length === 0 + ? places.filter((place) => place.isTraditional) + : places.filter((place) => collection.placeRefs.some((ref) => ref.placeId === place.id)); + + return ( +
+ HANOK CULTURE WALK + {collection.title.ko} + {collection.subtitle.ko} + {collection.paths && collection.paths.length > 0 && ( + + {collection.paths.map((path) => ( + onPathSelect(path)}> + {path.label} + + ))} + + )} + + {referenced.map((place) => ( + onPlaceSelect(place)}> + {place.name} + + ))} + +
+ ); +} diff --git a/src/features/map/components/InfoMapEditorialFeed.tsx b/src/features/map/components/InfoMapEditorialFeed.tsx index d1ea5f12..a9be970b 100644 --- a/src/features/map/components/InfoMapEditorialFeed.tsx +++ b/src/features/map/components/InfoMapEditorialFeed.tsx @@ -1,41 +1,34 @@ 'use client'; +import { useCallback } from 'react'; +import type { Item } from '@/features/map/types'; +import type { CulturalCollectionPath } from '@/features/map/domain/culturalCollection'; +import { CULTURAL_COLLECTIONS } from '@/features/map/infrastructure/culturalCollections.fixture'; +import { selectCulturalCollection } from '@/features/map/application/selectCulturalCollection'; +import { useMapStore } from '@/features/map/hooks/useMapStore'; +import { useInfoMapPresentation } from '@/features/map/presentation/useInfoMapPresentation'; +import { useInfoMapHomeNavigation } from '@/features/map/presentation/useInfoMapHomeNavigation'; +import CulturalDiscoveryCollection from './CulturalDiscoveryCollection'; +interface Props { items: Item[]; loading?: boolean; onPlaceSelect: (place: Item) => void; } +export default function InfoMapEditorialFeed({ items, loading = false, onPlaceSelect }: Props) { + const { isDiscovery, collectionScope } = useInfoMapPresentation(); + const { captureBeforeNavigation } = useInfoMapHomeNavigation(); + const collection = selectCulturalCollection(CULTURAL_COLLECTIONS, collectionScope); + const handlePathSelect = useCallback((path: CulturalCollectionPath) => { + captureBeforeNavigation(); + const store = useMapStore.getState(); + store.setInfoCategory(path.category); + store.setSearchQuery(path.searchQuery); + store.setPanelOpen(true); + }, [captureBeforeNavigation]); -import styled from '@emotion/styled'; -import type { Item, MapInfoCategory } from '@/features/map/types'; -import LiveNoticeBanner from './feed/LiveNoticeBanner'; -import SorimaruSpotlightBanner from './feed/SorimaruSpotlightBanner'; -import SmartAroundFeed from './feed/SmartAroundFeed'; - -const EditorialSections = styled.div` - display: flex; - flex-direction: column; - gap: 32px; - margin-top: 12px; - margin-bottom: 20px; -`; - -interface InfoMapEditorialFeedProps { - category: MapInfoCategory; - regionCode: string | null; - items: Item[]; -} - -export default function InfoMapEditorialFeed({ - category, - regionCode, - items, -}: InfoMapEditorialFeedProps) { - const showDiscovery = category === 'hanok' && regionCode === null; - + if (!isDiscovery || !collection) return null; return ( - <> - - {showDiscovery && ( - - - - - )} - + ); } diff --git a/src/features/map/components/InfoPlaceList.test.tsx b/src/features/map/components/InfoPlaceList.test.tsx index eef2dde1..55dcba72 100644 --- a/src/features/map/components/InfoPlaceList.test.tsx +++ b/src/features/map/components/InfoPlaceList.test.tsx @@ -65,26 +65,27 @@ describe('InfoPlaceList', () => { render(); expect(screen.getByText('한옥 공간·체험 23,675곳')).toBeTruthy(); - expect(screen.getByText('유지되는 한옥')).toBeTruthy(); + expect(screen.getAllByText('유지되는 한옥')).toHaveLength(2); }); - it('shows the editorial discovery modules above the canonical HANOK list', () => { + it('shows the cultural discovery panel above the canonical HANOK list', () => { render(); - expect(screen.getByText('실시간 한옥 소식')).toBeTruthy(); - expect(screen.queryByText('축제·기획전')).toBeNull(); - expect(screen.getByText('이번 주 소리마루')).toBeTruthy(); - expect(screen.getByText('추천 한옥 명소')).toBeTruthy(); + expect(screen.getByRole('heading', { name: '한옥에서 시작하는 한국의 하루' })).toBeTruthy(); + expect(screen.getByText('한옥의 마당에서 시작해 지역의 맛과 손으로 만드는 경험까지 이어가 보세요.')).toBeTruthy(); + expect(screen.getByRole('link', { name: 'HANOK CULTURE WALK' }).getAttribute('href')).toBe('/hanok'); expect(screen.getByText('한옥 공간·체험 23,675곳')).toBeTruthy(); - expect(screen.getByText('유지되는 한옥')).toBeTruthy(); + expect(screen.getAllByText('유지되는 한옥')).toHaveLength(2); + fireEvent.click(screen.getByRole('button', { name: '지역을 맛보다' })); + expect(useMapStore.getState()).toMatchObject({ infoCategory: 'food', searchQuery: '향토음식' }); }); it('places the count heading immediately before the actual place list', () => { render(); - const editorial = screen.getByText('추천 한옥 명소'); + const editorial = screen.getByRole('heading', { name: '한옥에서 시작하는 한국의 하루' }); const countHeading = screen.getByText('한옥 공간·체험 23,675곳'); - const firstPlace = screen.getByText('유지되는 한옥'); + const firstPlace = screen.getAllByText('유지되는 한옥')[1]; expect(editorial.compareDocumentPosition(countHeading) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); expect(countHeading.compareDocumentPosition(firstPlace) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); @@ -126,7 +127,7 @@ describe('InfoPlaceList', () => { render(); - expect(screen.getByText('유지되는 한옥')).toBeTruthy(); + expect(screen.getAllByText('유지되는 한옥')).toHaveLength(2); expect(screen.getByRole('button', { name: '다시 시도' })).toBeTruthy(); }); diff --git a/src/features/map/components/InfoPlaceList.tsx b/src/features/map/components/InfoPlaceList.tsx index 3c84cf6b..71dc1dd1 100644 --- a/src/features/map/components/InfoPlaceList.tsx +++ b/src/features/map/components/InfoPlaceList.tsx @@ -323,9 +323,9 @@ export default function InfoPlaceList() { )} diff --git a/src/features/map/domain/culturalCollection.test.ts b/src/features/map/domain/culturalCollection.test.ts new file mode 100644 index 00000000..761c85fc --- /dev/null +++ b/src/features/map/domain/culturalCollection.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest'; +import { validateCulturalCollections } from './culturalCollection'; + +describe('validateCulturalCollections', () => { + it('rejects duplicate collection ids and missing provenance', () => { + expect(() => validateCulturalCollections([ + { id: 'bukchon', scope: 'hanok-home', title: { ko: '북촌' }, subtitle: { ko: '한옥' }, provenance: 'Editorial', placeRefs: [] }, + { id: 'bukchon', scope: 'hanok-home', title: { ko: '북촌' }, subtitle: { ko: '한옥' }, provenance: '', placeRefs: [] }, + ])).toThrow(); + }); +}); diff --git a/src/features/map/domain/culturalCollection.ts b/src/features/map/domain/culturalCollection.ts new file mode 100644 index 00000000..0c720632 --- /dev/null +++ b/src/features/map/domain/culturalCollection.ts @@ -0,0 +1,43 @@ +import type { MapInfoCategory } from '@/features/map/domain/infoCategory'; + +export type CulturalCollectionScope = 'hanok-home' | 'region-home' | 'utility'; + +export interface LocalizedText { + ko: string; + en?: string; +} + +export interface CulturalCollectionPlaceRef { + placeId: string; +} + +export interface CulturalCollectionPath { + id: string; + label: string; + category: MapInfoCategory; + searchQuery: string; +} + +export interface CulturalCollection { + id: string; + scope: CulturalCollectionScope; + title: LocalizedText; + subtitle: LocalizedText; + provenance: string; + placeRefs: CulturalCollectionPlaceRef[]; + paths?: CulturalCollectionPath[]; +} + +export function validateCulturalCollections(collections: readonly CulturalCollection[]): void { + const ids = new Set(); + + for (const collection of collections) { + if (!collection.id || ids.has(collection.id)) { + throw new Error('Cultural collection ids must be unique.'); + } + if (!collection.provenance.trim()) { + throw new Error('Cultural collections require provenance.'); + } + ids.add(collection.id); + } +} diff --git a/src/features/map/infrastructure/culturalCollections.fixture.ts b/src/features/map/infrastructure/culturalCollections.fixture.ts new file mode 100644 index 00000000..2d7b9cc9 --- /dev/null +++ b/src/features/map/infrastructure/culturalCollections.fixture.ts @@ -0,0 +1,26 @@ +import { + validateCulturalCollections, + type CulturalCollection, +} from '@/features/map/domain/culturalCollection'; + +export const CULTURAL_COLLECTIONS: readonly CulturalCollection[] = [ + { + id: 'hanok-neighborhoods', + scope: 'hanok-home', + title: { ko: '한옥에서 시작하는 한국의 하루', en: 'A day in Korea, beginning with Hanok' }, + subtitle: { + ko: '한옥의 마당에서 시작해 지역의 맛과 손으로 만드는 경험까지 이어가 보세요.', + en: 'Start in a Hanok courtyard, then continue into local food and hands-on traditions.', + }, + provenance: 'OnMaru editorial collection', + placeRefs: [], + paths: [ + { id: 'stay', label: '한옥에 머물다', category: 'stay', searchQuery: '한옥스테이' }, + { id: 'food', label: '지역을 맛보다', category: 'food', searchQuery: '향토음식' }, + { id: 'experience', label: '손으로 만들다', category: 'experience', searchQuery: '체험' }, + { id: 'market', label: '시장을 걷다', category: 'market', searchQuery: '전통시장' }, + ], + }, +]; + +validateCulturalCollections(CULTURAL_COLLECTIONS); diff --git a/src/features/map/presentation/useInfoMapPresentation.test.tsx b/src/features/map/presentation/useInfoMapPresentation.test.tsx new file mode 100644 index 00000000..ea949764 --- /dev/null +++ b/src/features/map/presentation/useInfoMapPresentation.test.tsx @@ -0,0 +1,26 @@ +// @vitest-environment jsdom + +import { renderHook } from '@testing-library/react'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { useMapStore } from '../hooks/useMapStore'; +import { useInfoMapPresentation } from './useInfoMapPresentation'; + +describe('useInfoMapPresentation', () => { + beforeEach(() => useMapStore.setState({ ...useMapStore.getInitialState(), mode: 'info' }, true)); + + it('uses discovery only for a root hanok view without a direct query', () => { + const { result } = renderHook(useInfoMapPresentation); + expect(result.current).toMatchObject({ isDiscovery: true, collectionScope: 'hanok-home' }); + }); + + it('uses utility presentation for text, category, region, and warmth intent', () => { + useMapStore.setState({ searchQuery: '북촌' }); + expect(renderHook(useInfoMapPresentation).result.current.isUtility).toBe(true); + useMapStore.setState({ searchQuery: '', infoCategory: 'cafe' }); + expect(renderHook(useInfoMapPresentation).result.current.isDiscovery).toBe(false); + useMapStore.setState({ infoCategory: 'hanok', infoRegionCode: '11' }); + expect(renderHook(useInfoMapPresentation).result.current.collectionScope).toBe('region-home'); + useMapStore.setState({ mode: 'warmth' }); + expect(renderHook(useInfoMapPresentation).result.current.isUtility).toBe(true); + }); +}); diff --git a/src/features/map/presentation/useInfoMapPresentation.ts b/src/features/map/presentation/useInfoMapPresentation.ts new file mode 100644 index 00000000..e0ad497b --- /dev/null +++ b/src/features/map/presentation/useInfoMapPresentation.ts @@ -0,0 +1,23 @@ +'use client'; + +import { useMapStore } from '@/features/map/hooks/useMapStore'; +import type { CulturalCollectionScope } from '@/features/map/domain/culturalCollection'; + +export function useInfoMapPresentation(): { + isDiscovery: boolean; + isUtility: boolean; + collectionScope: CulturalCollectionScope; +} { + const mode = useMapStore((state) => state.mode); + const category = useMapStore((state) => state.infoCategory); + const regionCode = useMapStore((state) => state.infoRegionCode); + const searchQuery = useMapStore((state) => state.searchQuery); + const hasDirectQuery = searchQuery.trim().length > 0; + const isDiscovery = mode === 'info' && category === 'hanok' && regionCode === null && !hasDirectQuery; + + return { + isDiscovery, + isUtility: !isDiscovery, + collectionScope: isDiscovery ? 'hanok-home' : regionCode ? 'region-home' : 'utility', + }; +} diff --git a/src/features/map/services/infoMarker.service.test.ts b/src/features/map/services/infoMarker.service.test.ts index 2475cfd7..35ea69fd 100644 --- a/src/features/map/services/infoMarker.service.test.ts +++ b/src/features/map/services/infoMarker.service.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { getInfoPlaceMarkerPresentation, selectInfoMarkerItems } from './infoMarker.service'; +import { getInfoPlaceMarkerPresentation, mapInfoPlaceToItem, selectInfoMarkerItems } from './infoMarker.service'; import type { ViewportItem } from '../types'; const placeItem: ViewportItem = { @@ -37,6 +37,22 @@ describe('selectInfoMarkerItems', () => { }); }); +describe('mapInfoPlaceToItem', () => { + it('preserves the Hanok category as the traditional-place signal', () => { + const place = { + placeId: 'hanok-1', + name: 'Hanok place', + category: 'HANOK', + coordinates: { lat: 37.5, lng: 127 }, + region: { regionCode: '11', name: 'Seoul' }, + thumbnailUrl: null, + summary: '', + }; + + expect(mapInfoPlaceToItem(place).isTraditional).toBe(true); + }); +}); + describe('getInfoPlaceMarkerPresentation', () => { it('keeps PLACE responses as complete markers without a compact icon-only state', () => { expect(getInfoPlaceMarkerPresentation('PLACE')).toBe('full'); diff --git a/src/features/map/services/infoMarker.service.ts b/src/features/map/services/infoMarker.service.ts index f8bcc005..44723bc5 100644 --- a/src/features/map/services/infoMarker.service.ts +++ b/src/features/map/services/infoMarker.service.ts @@ -18,6 +18,11 @@ export function mapInfoCategoryToPlaceCategory(category?: string): PlaceCategory return 'spot'; } +function isHanokInfoCategory(category?: string): boolean { + const normalized = category?.toUpperCase() ?? ''; + return normalized.includes('HANOK') || category?.includes('한옥') === true; +} + export function mapInfoPlaceToItem(place: InfoPlaceItem): Item { return { id: place.placeId, @@ -29,6 +34,7 @@ export function mapInfoPlaceToItem(place: InfoPlaceItem): Item { image: place.thumbnailUrl, tel: null, dist: null, + isTraditional: isHanokInfoCategory(place.category), savedByMe: place.savedByMe, }; } diff --git a/src/lib/uuid.test.ts b/src/lib/uuid.test.ts new file mode 100644 index 00000000..d96ebb5a --- /dev/null +++ b/src/lib/uuid.test.ts @@ -0,0 +1,18 @@ +import { describe, it, expect } from 'vitest'; +import { generateUUID } from './uuid'; + +describe('generateUUID', () => { + it('generates a valid RFC 4122 v4 UUID format (8-4-4-4-12)', () => { + const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + for (let i = 0; i < 20; i++) { + const id = generateUUID(); + expect(id).toMatch(uuidRegex); + } + }); + + it('generates distinct IDs on successive calls', () => { + const id1 = generateUUID(); + const id2 = generateUUID(); + expect(id1).not.toBe(id2); + }); +}); diff --git a/src/lib/uuid.ts b/src/lib/uuid.ts new file mode 100644 index 00000000..76e0175b --- /dev/null +++ b/src/lib/uuid.ts @@ -0,0 +1,16 @@ +/** + * RFC 4122 v4 UUID generator + * Standardizes UUID generation across browser and SSR/Node runtimes + * for API headers (e.g., Idempotency-Key) and client turn IDs. + */ +export function generateUUID(): string { + if (typeof globalThis !== 'undefined' && globalThis.crypto?.randomUUID) { + return globalThis.crypto.randomUUID(); + } + // Fallback RFC 4122 v4 UUID generator (8-4-4-4-12) + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +}