feat(space): 종료 결과 모달과 current session thought 복원 추가

This commit is contained in:
2026-03-16 20:08:50 +09:00
parent 6194c19f3b
commit 1d2ce85cfd
10 changed files with 401 additions and 79 deletions

View File

@@ -77,6 +77,15 @@ Last Updated: 2026-03-16
- timer가 `00:00`에 도달하면 same-session modal이 자동으로 열리고, `완료하고 종료하기 / 10분 더` 두 경로만 제안한다 - timer가 `00:00`에 도달하면 same-session modal이 자동으로 열리고, `완료하고 종료하기 / 10분 더` 두 경로만 제안한다
- `10분 더`를 누르면 현재 focus phase에 10분이 추가되어 바로 running으로 돌아가고, 다시 시간이 끝나면 같은 modal이 다시 열린다 - `10분 더`를 누르면 현재 focus phase에 10분이 추가되어 바로 running으로 돌아가고, 다시 시간이 끝나면 같은 modal이 다시 열린다
- server와 web 모두 `extend-phase` 계약 기준으로 동작한다 - server와 web 모두 `extend-phase` 계약 기준으로 동작한다
- `10분 더`는 남은 시간만이 아니라 `focusDurationSeconds`도 함께 늘려 이후 결과 모달과 review의 집중 시간이 맞도록 정리됐다
- `/space` completion result modal 추가:
- `timer-complete -> 완료하고 종료하기``End Session -> 여기서 마무리하기`는 즉시 `/app`으로 가지 않고 중앙 결과 모달을 먼저 연다
- 결과 모달에는 `집중한 시간`, `완료한 목표`, `이번 세션 thought capsule`이 표시된다
- 결과 모달이 떠 있는 동안 `/space` 자동 `/app` redirect는 막히고, `확인하고 돌아가기`에서만 `/app`으로 이동한다
- current-session thought capsule 서버 복원:
- `/space` thought는 public `focusSessionId` 없이 auth 기반으로 현재 세션에 서버가 내부 연결한다
- `/space` 진입 시 `GET /api/v1/focus-sessions/current/thoughts`로 현재 세션 thought 목록을 복원한다
- 브라우저를 껐다 켜도 current session이 살아 있으면 같은 thought 목록을 다시 읽을 수 있다
- `/space` intent HUD collapsed / expanded 재설계: - `/space` intent HUD collapsed / expanded 재설계:
- 상시 큰 goal 카드 대신 idle에서는 goal 1줄만 남는 collapsed glass rail 구조로 변경 - 상시 큰 goal 카드 대신 idle에서는 goal 1줄만 남는 collapsed glass rail 구조로 변경
- hover / focus / rail tap에서만 expanded card로 열리며, 이때만 microStep과 `이번 목표 완료` 액션이 노출됨 - hover / focus / rail tap에서만 expanded card로 열리며, 이때만 microStep과 `이번 목표 완료` 액션이 노출됨

View File

@@ -14,10 +14,10 @@ Last Updated: 2026-03-16
## 현재 우선순위 ## 현재 우선순위
1. `/space` current-session-only cleanup 1. `/space` completion result modal browser QA
2. `Core Loop Alignment` browser audit 2. `/space` current-session-only cleanup
3. `Weekly Review` carry-forward 고도화 3. `Core Loop Alignment` browser audit
4. `Premium Ambience` polish 4. `Weekly Review` carry-forward 고도화
## 최근 세션 상태 ## 최근 세션 상태
@@ -87,6 +87,14 @@ Last Updated: 2026-03-16
- `00:00`이 되면 `완료하고 종료하기 / 10분 더` 모달이 자동으로 열린다. - `00:00`이 되면 `완료하고 종료하기 / 10분 더` 모달이 자동으로 열린다.
- `10분 더`는 server `extend-phase` 계약을 타고 현재 focus phase를 10분 연장한 뒤 다시 running으로 이어진다. - `10분 더`는 server `extend-phase` 계약을 타고 현재 focus phase를 10분 연장한 뒤 다시 running으로 이어진다.
- 그래서 사용자는 recovery 상태에서도 `계속 / 다시 잡기 / 마무리` 중 하나를 바로 고를 수 있다. - 그래서 사용자는 recovery 상태에서도 `계속 / 다시 잡기 / 마무리` 중 하나를 바로 고를 수 있다.
- `/space` 종료 결과 모달이 추가됐다.
- `완료하고 종료하기``여기서 마무리하기`는 바로 `/app`으로 가지 않고 중앙 결과 모달을 먼저 띄운다.
- 결과 모달에는 `집중한 시간`, `완료한 목표`, `이번 세션 thought capsule`이 들어간다.
- 닫기 전까지 `/space`는 결과 모달 상태로 유지되고, `확인하고 돌아가기`에서만 `/app`으로 이동한다.
- thought capsule은 서버가 현재 세션에 내부 귀속한다.
- 클라이언트는 `focusSessionId`를 보내지 않는다.
- `/space`는 current session이 살아 있으면 server `current thoughts` API로 same-session thought 목록을 복원한다.
- 그래서 브라우저 재시작 후에도 같은 세션이라면 결과 모달에 같은 thought들이 포함된다.
- `/space` 목표 카드를 collapsed / expanded 구조로 재설계했다. - `/space` 목표 카드를 collapsed / expanded 구조로 재설계했다.
- idle에서는 goal 1줄만 남는 얇은 glass rail로 줄였다. - idle에서는 goal 1줄만 남는 얇은 glass rail로 줄였다.
- microStep과 `이번 목표 완료`는 expanded 상태에서만 드러난다. - microStep과 `이번 목표 완료`는 expanded 상태에서만 드러난다.

View File

@@ -18,6 +18,31 @@
## 작업 1 ## 작업 1
- 제목: `/space` completion result modal browser QA
- 목적:
- 세션 완전 종료 직후 결과 모달이 자연스럽게 뜨는지 확인한다.
- timer-complete, End Session finish, 10분 더 이후 재종료, thought 복원 흐름을 실제 브라우저에서 검증한다.
- 변경 범위:
- `/space` timer-complete finish
- `/space` End Session finish
- current-session thoughts restore
- 결과 모달 -> `/app`
- 제외 범위:
- 새로운 stats/weekly review 기능 추가 금지
- 완료 조건:
- 종료 직후 중앙 결과 모달이 보인다
- 결과 모달에 집중 시간/목표/thought가 맞게 보인다
- 결과 모달 확인 후에만 `/app`으로 이동한다
- 브라우저 재실행 뒤 current session이 살아 있으면 thought capture가 유지된다
- 진행 상태:
- 다음 작업
- 검증:
- manual browser QA
- 커밋 힌트:
- docs(qa): completion result modal browser audit 기록
## 작업 2
- 제목: `/app` Atmosphere Entry Shell - 제목: `/app` Atmosphere Entry Shell
- 목적: - 목적:
- `docs/screens/app/current/19_app_atmosphere_entry_spec.md` 기준으로 `/app` no-session 상태를 `goal + duration + atmosphere` 중심의 premium entry screen으로 재설계한다. - `docs/screens/app/current/19_app_atmosphere_entry_spec.md` 기준으로 `/app` no-session 상태를 `goal + duration + atmosphere` 중심의 premium entry screen으로 재설계한다.
@@ -44,7 +69,7 @@
- 커밋 힌트: - 커밋 힌트:
- feat(app): atmosphere entry shell 1차 구현 - feat(app): atmosphere entry shell 1차 구현
## 작업 2 ## 작업 3
- 제목: `Custom Duration Contract` - 제목: `Custom Duration Contract`
- 목적: - 목적:
@@ -61,13 +86,13 @@
- `70분` 같은 값이 실제 focus duration으로 반영된다 - `70분` 같은 값이 실제 focus duration으로 반영된다
- break duration이 정책 기준으로 계산된다 - break duration이 정책 기준으로 계산된다
- 진행 상태: - 진행 상태:
- 다음 작업 - 구현 완료
- 검증: - 검증:
- start -> `/space` -> timer duration 확인 - start -> `/space` -> timer duration 확인
- 커밋 힌트: - 커밋 힌트:
- feat(flow): custom duration contract 연결 - feat(flow): custom duration contract 연결
## 작업 3 ## 작업 4
- 제목: `Weekly Review Dock Reposition` - 제목: `Weekly Review Dock Reposition`
- 목적: - 목적:
@@ -89,7 +114,7 @@
- 커밋 힌트: - 커밋 힌트:
- fix(app): review dock 위치 재정렬 - fix(app): review dock 위치 재정렬
## 작업 4 ## 작업 5
- 제목: `Core Loop Alignment Audit` browser slice - 제목: `Core Loop Alignment Audit` browser slice
- 목적: - 목적:

View File

@@ -7,6 +7,20 @@ import type { RecentThought } from './types';
const MAX_THOUGHT_INBOX_ITEMS = 40; const MAX_THOUGHT_INBOX_ITEMS = 40;
const normalizeThought = (thought: {
id: string;
text: string;
sceneName: string;
isCompleted: boolean;
capturedAt: string;
}): RecentThought => ({
id: thought.id,
text: thought.text,
sceneName: thought.sceneName,
isCompleted: thought.isCompleted,
capturedAt: thought.capturedAt,
});
export const useThoughtInbox = () => { export const useThoughtInbox = () => {
const [thoughts, setThoughts] = useState<RecentThought[]>([]); const [thoughts, setThoughts] = useState<RecentThought[]>([]);
@@ -16,15 +30,7 @@ export const useThoughtInbox = () => {
inboxApi.getThoughts() inboxApi.getThoughts()
.then((data) => { .then((data) => {
if (!mounted) return; if (!mounted) return;
setThoughts( setThoughts(data.map(normalizeThought));
data.map((d) => ({
id: d.id,
text: d.text,
sceneName: d.sceneName,
isCompleted: d.isCompleted,
capturedAt: copy.session.justNow,
}))
);
}) })
.catch((err) => { .catch((err) => {
console.error('Failed to load inbox thoughts:', err); console.error('Failed to load inbox thoughts:', err);
@@ -35,7 +41,7 @@ export const useThoughtInbox = () => {
}; };
}, []); }, []);
const addThought = useCallback((text: string, sceneName: string) => { const addThought = useCallback(async (text: string, sceneName: string) => {
const trimmedText = text.trim(); const trimmedText = text.trim();
if (!trimmedText) { if (!trimmedText) {
@@ -57,18 +63,20 @@ export const useThoughtInbox = () => {
return next; return next;
}); });
inboxApi.addThought({ text: trimmedText, sceneName }) try {
.then((res) => { const response = await inboxApi.addThought({ text: trimmedText, sceneName });
setThoughts((current) => const normalized = normalizeThought(response);
current.map((t) => (t.id === tempId ? { ...t, id: res.id } : t))
);
})
.catch((err) => {
console.error('Failed to add thought:', err);
setThoughts((current) => current.filter((t) => t.id !== tempId));
});
return thought; setThoughts((current) =>
current.map((t) => (t.id === tempId ? normalized : t))
);
return normalized;
} catch (err) {
console.error('Failed to add thought:', err);
setThoughts((current) => current.filter((t) => t.id !== tempId));
return null;
}
}, []); }, []);
const removeThought = useCallback((thoughtId: string) => { const removeThought = useCallback((thoughtId: string) => {
@@ -140,15 +148,7 @@ export const useThoughtInbox = () => {
return inboxApi.getThoughts(); return inboxApi.getThoughts();
}) })
.then((data) => { .then((data) => {
setThoughts( setThoughts(data.map(normalizeThought));
data.map((d) => ({
id: d.id,
text: d.text,
sceneName: d.sceneName,
isCompleted: d.isCompleted,
capturedAt: copy.session.justNow,
}))
);
}) })
.catch((err) => { .catch((err) => {
console.error('Failed to restore thoughts:', err); console.error('Failed to restore thoughts:', err);

View File

@@ -31,6 +31,22 @@ interface RawAdvanceCurrentGoalResponse {
updatedPlanToday: Parameters<typeof normalizeFocusPlanToday>[0]; updatedPlanToday: Parameters<typeof normalizeFocusPlanToday>[0];
} }
interface RawCurrentSessionThought {
id: string;
text: string;
sceneName: string;
isCompleted: boolean;
capturedAt: string;
}
interface RawCompletionResult {
completedSessionId: string;
completionSource: 'timer-complete' | 'manual-end';
completedGoal: string;
focusedSeconds: number;
thoughts: RawCurrentSessionThought[];
}
export interface FocusSession { export interface FocusSession {
id: string; id: string;
sceneId: string; sceneId: string;
@@ -52,6 +68,22 @@ export interface FocusSession {
serverNow: string; serverNow: string;
} }
export interface CurrentSessionThought {
id: string;
text: string;
sceneName: string;
isCompleted: boolean;
capturedAt: string;
}
export interface CompletionResult {
completedSessionId: string;
completionSource: 'timer-complete' | 'manual-end';
completedGoal: string;
focusedSeconds: number;
thoughts: CurrentSessionThought[];
}
export interface StartFocusSessionRequest { export interface StartFocusSessionRequest {
sceneId: string; sceneId: string;
goal: string; goal: string;
@@ -126,6 +158,23 @@ const normalizeAdvanceGoalResponse = (
}; };
}; };
const normalizeCurrentSessionThought = (
thought: RawCurrentSessionThought,
): CurrentSessionThought => {
return {
...thought,
};
};
const normalizeCompletionResult = (
result: RawCompletionResult,
): CompletionResult => {
return {
...result,
thoughts: result.thoughts.map(normalizeCurrentSessionThought),
};
};
export const focusSessionApi = { export const focusSessionApi = {
getCurrentSession: async (): Promise<FocusSession | null> => { getCurrentSession: async (): Promise<FocusSession | null> => {
const response = await apiClient<RawFocusSession | null>('api/v1/focus-sessions/current', { const response = await apiClient<RawFocusSession | null>('api/v1/focus-sessions/current', {
@@ -135,6 +184,14 @@ export const focusSessionApi = {
return response ? normalizeFocusSession(response) : null; return response ? normalizeFocusSession(response) : null;
}, },
getCurrentSessionThoughts: async (): Promise<CurrentSessionThought[]> => {
const response = await apiClient<RawCurrentSessionThought[]>('api/v1/focus-sessions/current/thoughts', {
method: 'GET',
});
return response.map(normalizeCurrentSessionThought);
},
startSession: async (payload: StartFocusSessionRequest): Promise<FocusSession> => { startSession: async (payload: StartFocusSessionRequest): Promise<FocusSession> => {
const response = await apiClient<RawFocusSession>('api/v1/focus-sessions', { const response = await apiClient<RawFocusSession>('api/v1/focus-sessions', {
method: 'POST', method: 'POST',
@@ -202,13 +259,13 @@ export const focusSessionApi = {
return normalizeFocusSession(response); return normalizeFocusSession(response);
}, },
completeSession: async (payload: CompleteFocusSessionRequest): Promise<FocusSession> => { completeSession: async (payload: CompleteFocusSessionRequest): Promise<CompletionResult> => {
const response = await apiClient<RawFocusSession>('api/v1/focus-sessions/current/complete', { const response = await apiClient<RawCompletionResult>('api/v1/focus-sessions/current/complete', {
method: 'POST', method: 'POST',
body: JSON.stringify(payload), body: JSON.stringify(payload),
}); });
return normalizeFocusSession(response); return normalizeCompletionResult(response);
}, },
advanceGoal: async (payload: AdvanceCurrentGoalRequest): Promise<AdvanceCurrentGoalResponse> => { advanceGoal: async (payload: AdvanceCurrentGoalRequest): Promise<AdvanceCurrentGoalResponse> => {

View File

@@ -5,6 +5,7 @@ import { copy } from '@/shared/i18n';
import { import {
type AdvanceCurrentGoalRequest, type AdvanceCurrentGoalRequest,
type AdvanceCurrentGoalResponse, type AdvanceCurrentGoalResponse,
type CompletionResult,
focusSessionApi, focusSessionApi,
type CompleteFocusSessionRequest, type CompleteFocusSessionRequest,
type FocusSession, type FocusSession,
@@ -76,7 +77,7 @@ interface UseFocusSessionEngineResult {
extendCurrentPhase: (payload: { additionalMinutes: number }) => Promise<FocusSession | null>; extendCurrentPhase: (payload: { additionalMinutes: number }) => Promise<FocusSession | null>;
updateCurrentIntent: (payload: UpdateCurrentFocusSessionIntentRequest) => Promise<FocusSession | null>; updateCurrentIntent: (payload: UpdateCurrentFocusSessionIntentRequest) => Promise<FocusSession | null>;
updateCurrentSelection: (payload: UpdateCurrentFocusSessionSelectionRequest) => Promise<FocusSession | null>; updateCurrentSelection: (payload: UpdateCurrentFocusSessionSelectionRequest) => Promise<FocusSession | null>;
completeSession: (payload: CompleteFocusSessionRequest) => Promise<FocusSession | null>; completeSession: (payload: CompleteFocusSessionRequest) => Promise<CompletionResult | null>;
advanceGoal: (payload: AdvanceCurrentGoalRequest) => Promise<AdvanceCurrentGoalResponse | null>; advanceGoal: (payload: AdvanceCurrentGoalRequest) => Promise<AdvanceCurrentGoalResponse | null>;
abandonSession: () => Promise<boolean>; abandonSession: () => Promise<boolean>;
clearError: () => void; clearError: () => void;
@@ -279,16 +280,16 @@ export const useFocusSessionEngine = (): UseFocusSessionEngineResult => {
return null; return null;
} }
const session = await runMutation( const result = await runMutation(
() => focusSessionApi.completeSession(payload), () => focusSessionApi.completeSession(payload),
copy.focusSession.completeFailed, copy.focusSession.completeFailed,
); );
if (session) { if (result) {
applySession(null); applySession(null);
} }
return session; return result;
}, },
advanceGoal: async (payload) => { advanceGoal: async (payload) => {
if (!currentSession) { if (!currentSession) {

View File

@@ -122,6 +122,17 @@ export const space = {
confirmPending: '시작 중…', confirmPending: '시작 중…',
finishPending: '마무리 중…', finishPending: '마무리 중…',
}, },
completionResult: {
eyebrow: 'SESSION COMPLETE',
title: '이번 세션을 조용히 닫아둘게요.',
description: '얼마나 집중했는지, 무엇을 끝냈는지, 생각 캡슐에 남긴 것까지 한 번에 정리해둡니다.',
focusedLabel: '집중한 시간',
focusedValue: (minutes: number) => `${minutes}`,
goalLabel: '완료한 목표',
thoughtsLabel: '이번 세션 생각 캡슐',
thoughtCount: (count: number) => `${count}`,
confirmButton: '확인하고 돌아가기',
},
controlCenter: { controlCenter: {
sectionTitles: { sectionTitles: {
background: 'Background', background: 'Background',

View File

@@ -0,0 +1,138 @@
'use client';
import { copy } from '@/shared/i18n';
import { cn } from '@/shared/lib/cn';
import type { CompletionResult } from '@/features/focus-session';
interface CompletionResultModalProps {
open: boolean;
result: CompletionResult | null;
onClose: () => void;
}
const formatFocusedMinutes = (focusedSeconds: number) => {
const safeSeconds = Math.max(0, focusedSeconds);
return Math.round(safeSeconds / 60);
};
export const CompletionResultModal = ({
open,
result,
onClose,
}: CompletionResultModalProps) => {
if (!result) {
return null;
}
const focusedMinutes = formatFocusedMinutes(result.focusedSeconds);
const hasThoughts = result.thoughts.length > 0;
return (
<div
className={cn(
'pointer-events-none fixed inset-0 z-[70] flex items-center justify-center px-4 transition-all duration-300 ease-[cubic-bezier(0.16,1,0.3,1)]',
open ? 'opacity-100' : 'opacity-0',
)}
aria-hidden={!open}
>
<div
className={cn(
'absolute inset-0 bg-[radial-gradient(circle_at_center,rgba(5,7,11,0.22)_0%,rgba(2,6,23,0.68)_52%,rgba(2,6,23,0.84)_100%)] backdrop-blur-[14px] transition-opacity duration-300',
open ? 'opacity-100' : 'opacity-0',
)}
/>
<section
className={cn(
'relative w-full max-w-[38rem] overflow-hidden rounded-[32px] border border-white/12 bg-[linear-gradient(180deg,rgba(18,22,30,0.96)_0%,rgba(8,11,17,0.94)_100%)] text-white shadow-[0_30px_100px_rgba(2,6,23,0.5)] transition-all duration-300 ease-[cubic-bezier(0.16,1,0.3,1)]',
open ? 'pointer-events-auto translate-y-0 scale-100' : 'pointer-events-none translate-y-4 scale-[0.975]',
)}
role="dialog"
aria-modal="true"
aria-labelledby="completion-result-title"
>
<div
aria-hidden
className="pointer-events-none absolute inset-0 bg-[radial-gradient(100%_85%_at_50%_0%,rgba(255,255,255,0.12)_0%,rgba(255,255,255,0.02)_42%,rgba(255,255,255,0)_100%)]"
/>
<div className="relative px-7 py-7 md:px-9 md:py-8">
<header className="text-center">
<div className="mx-auto flex h-14 w-14 items-center justify-center rounded-[18px] border border-white/10 bg-white/[0.06] shadow-[inset_0_1px_0_rgba(255,255,255,0.08)]">
<span className="text-[20px] text-white/88"></span>
</div>
<p className="mt-5 text-[11px] font-medium tracking-[0.14em] text-white/34">
{copy.space.completionResult.eyebrow}
</p>
<h3
id="completion-result-title"
className="mx-auto mt-2 max-w-[24rem] text-[1.65rem] font-light leading-[1.16] tracking-[-0.03em] text-white/96 md:text-[1.9rem]"
>
{copy.space.completionResult.title}
</h3>
<p className="mx-auto mt-3 max-w-[28rem] text-[14px] leading-[1.7] text-white/56">
{copy.space.completionResult.description}
</p>
</header>
<div className="mt-7 grid gap-4">
<div className="rounded-[28px] border border-white/8 bg-black/16 px-5 py-5 text-center shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]">
<p className="text-[11px] font-medium uppercase tracking-[0.18em] text-white/34">
{copy.space.completionResult.focusedLabel}
</p>
<p className="mt-3 text-[2.6rem] font-light tracking-[-0.05em] text-white/96 md:text-[3.2rem]">
{copy.space.completionResult.focusedValue(focusedMinutes)}
</p>
</div>
<div className="rounded-[24px] border border-white/8 bg-black/14 px-5 py-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]">
<p className="text-[10px] font-medium uppercase tracking-[0.22em] text-white/34">
{copy.space.completionResult.goalLabel}
</p>
<p className="mt-2 text-[15px] font-medium leading-[1.45] tracking-[-0.01em] text-white/90">
{result.completedGoal}
</p>
</div>
{hasThoughts ? (
<div className="rounded-[24px] border border-white/8 bg-black/14 px-5 py-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]">
<div className="flex items-center justify-between gap-4">
<p className="text-[10px] font-medium uppercase tracking-[0.22em] text-white/34">
{copy.space.completionResult.thoughtsLabel}
</p>
<p className="text-[11px] text-white/38">
{copy.space.completionResult.thoughtCount(result.thoughts.length)}
</p>
</div>
<div className="mt-3 space-y-2.5">
{result.thoughts.map((thought) => (
<div
key={thought.id}
className="rounded-[18px] border border-white/7 bg-white/[0.04] px-4 py-3"
>
<p className="text-[13px] leading-[1.6] text-white/84">
{thought.text}
</p>
<p className="mt-2 text-[10px] uppercase tracking-[0.16em] text-white/32">
{thought.sceneName}
</p>
</div>
))}
</div>
</div>
) : null}
</div>
<footer className="mt-6 flex justify-center">
<button
type="button"
onClick={onClose}
className="inline-flex min-h-[3.5rem] min-w-[14rem] items-center justify-center rounded-[18px] border border-white/14 bg-white/[0.12] px-5 py-3 text-center text-[13px] font-medium tracking-[0.01em] text-white transition-all duration-200 hover:border-white/22 hover:bg-white/[0.17] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/12"
>
{copy.space.completionResult.confirmButton}
</button>
</footer>
</div>
</section>
</div>
);
};

View File

@@ -1,7 +1,7 @@
'use client'; 'use client';
import { useCallback, useEffect, useRef } from 'react'; import { useCallback, useEffect, useRef } from 'react';
import type { FocusSession } from '@/features/focus-session'; import type { CompletionResult, FocusSession } from '@/features/focus-session';
import { copy } from '@/shared/i18n'; import { copy } from '@/shared/i18n';
import type { HudStatusLinePayload } from '@/shared/lib/useHudStatusLine'; import type { HudStatusLinePayload } from '@/shared/lib/useHudStatusLine';
import { findAtmosphereOptionForSelection } from '@/widgets/focus-dashboard/model/atmosphereEntry'; import { findAtmosphereOptionForSelection } from '@/widgets/focus-dashboard/model/atmosphereEntry';
@@ -47,7 +47,7 @@ interface UseSpaceWorkspaceSessionControlsParams {
completedGoal?: string; completedGoal?: string;
focusScore?: number; focusScore?: number;
distractionCount?: number; distractionCount?: number;
}) => Promise<FocusSession | null>; }) => Promise<CompletionResult | null>;
advanceGoal: (input: { advanceGoal: (input: {
completedGoal: string; completedGoal: string;
nextGoal: string; nextGoal: string;
@@ -313,39 +313,33 @@ export const useSpaceWorkspaceSessionControls = ({
const trimmedCurrentGoal = goalInput.trim(); const trimmedCurrentGoal = goalInput.trim();
if (!currentSession) { if (!currentSession) {
return false; return null;
} }
const completedSession = await completeSession({ const completionResult = await completeSession({
completionType: 'goal-complete', completionType: 'goal-complete',
completedGoal: trimmedCurrentGoal || undefined, completedGoal: trimmedCurrentGoal || undefined,
}); });
if (!completedSession) { if (!completionResult) {
pushStatusLine({ pushStatusLine({
message: copy.space.workspace.goalCompleteSyncFailed, message: copy.space.workspace.goalCompleteSyncFailed,
}); });
return false; return null;
} }
setGoalInput('');
setLinkedFocusPlanItemId(null);
setSelectedGoalId(null);
setShowResumePrompt(false); setShowResumePrompt(false);
setPendingSessionEntryPoint('space-setup'); setPendingSessionEntryPoint('space-setup');
setPreviewPlaybackState('paused'); setPreviewPlaybackState('paused');
setWorkspaceMode('setup'); setWorkspaceMode('setup');
return true; return completionResult;
}, [ }, [
completeSession, completeSession,
currentSession, currentSession,
goalInput, goalInput,
pushStatusLine, pushStatusLine,
setGoalInput,
setLinkedFocusPlanItemId,
setPendingSessionEntryPoint, setPendingSessionEntryPoint,
setPreviewPlaybackState, setPreviewPlaybackState,
setSelectedGoalId,
setShowResumePrompt, setShowResumePrompt,
setWorkspaceMode, setWorkspaceMode,
]); ]);
@@ -354,39 +348,33 @@ export const useSpaceWorkspaceSessionControls = ({
const trimmedCurrentGoal = goalInput.trim(); const trimmedCurrentGoal = goalInput.trim();
if (!currentSession) { if (!currentSession) {
return false; return null;
} }
const completedSession = await completeSession({ const completionResult = await completeSession({
completionType: 'timer-complete', completionType: 'timer-complete',
completedGoal: trimmedCurrentGoal || undefined, completedGoal: trimmedCurrentGoal || undefined,
}); });
if (!completedSession) { if (!completionResult) {
pushStatusLine({ pushStatusLine({
message: copy.space.workspace.timerCompleteSyncFailed, message: copy.space.workspace.timerCompleteSyncFailed,
}); });
return false; return null;
} }
setGoalInput('');
setLinkedFocusPlanItemId(null);
setSelectedGoalId(null);
setShowResumePrompt(false); setShowResumePrompt(false);
setPendingSessionEntryPoint('space-setup'); setPendingSessionEntryPoint('space-setup');
setPreviewPlaybackState('paused'); setPreviewPlaybackState('paused');
setWorkspaceMode('setup'); setWorkspaceMode('setup');
return true; return completionResult;
}, [ }, [
completeSession, completeSession,
currentSession, currentSession,
goalInput, goalInput,
pushStatusLine, pushStatusLine,
setGoalInput,
setLinkedFocusPlanItemId,
setPendingSessionEntryPoint, setPendingSessionEntryPoint,
setPreviewPlaybackState, setPreviewPlaybackState,
setSelectedGoalId,
setShowResumePrompt, setShowResumePrompt,
setWorkspaceMode, setWorkspaceMode,
]); ]);

View File

@@ -9,7 +9,12 @@ import {
import { usePlanTier } from "@/entities/plan"; import { usePlanTier } from "@/entities/plan";
import { getSceneById, SCENE_THEMES } from "@/entities/scene"; import { getSceneById, SCENE_THEMES } from "@/entities/scene";
import { GOAL_CHIPS, SOUND_PRESETS, useThoughtInbox } from "@/entities/session"; import { GOAL_CHIPS, SOUND_PRESETS, useThoughtInbox } from "@/entities/session";
import { useFocusSessionEngine } from "@/features/focus-session"; import {
focusSessionApi,
type CompletionResult,
type CurrentSessionThought,
useFocusSessionEngine,
} from "@/features/focus-session";
import { useFocusStats } from "@/features/stats"; import { useFocusStats } from "@/features/stats";
import { import {
useSoundPlayback, useSoundPlayback,
@@ -19,6 +24,7 @@ import { useHudStatusLine } from "@/shared/lib/useHudStatusLine";
import { copy } from "@/shared/i18n"; import { copy } from "@/shared/i18n";
import { SpaceFocusHudWidget } from "@/widgets/space-focus-hud"; import { SpaceFocusHudWidget } from "@/widgets/space-focus-hud";
import { SpaceSetupDrawerWidget } from "@/widgets/space-setup-drawer"; import { SpaceSetupDrawerWidget } from "@/widgets/space-setup-drawer";
import { CompletionResultModal } from "@/widgets/space-focus-hud/ui/CompletionResultModal";
import { import {
findAtmosphereOptionForSelection, findAtmosphereOptionForSelection,
getRecommendedDurationMinutes, getRecommendedDurationMinutes,
@@ -83,6 +89,8 @@ export const SpaceWorkspaceWidget = () => {
const [pendingSessionEntryPoint, setPendingSessionEntryPoint] = const [pendingSessionEntryPoint, setPendingSessionEntryPoint] =
useState<SessionEntryPoint>("space-setup"); useState<SessionEntryPoint>("space-setup");
const [showReviewTeaserAfterComplete, setShowReviewTeaserAfterComplete] = useState(false); const [showReviewTeaserAfterComplete, setShowReviewTeaserAfterComplete] = useState(false);
const [, setCurrentSessionThoughts] = useState<CurrentSessionThought[]>([]);
const [pendingCompletionResult, setPendingCompletionResult] = useState<CompletionResult | null>(null);
const { const {
selectedPresetId, selectedPresetId,
@@ -107,10 +115,12 @@ export const SpaceWorkspaceWidget = () => {
advanceGoal, advanceGoal,
abandonSession, abandonSession,
} = useFocusSessionEngine(); } = useFocusSessionEngine();
const isCompletionResultOpen = pendingCompletionResult !== null;
const isFocusMode = workspaceMode === "focus"; const isFocusMode = workspaceMode === "focus";
const resolvedPlaybackState = currentSession?.state ?? previewPlaybackState; const resolvedPlaybackState = currentSession?.state ?? previewPlaybackState;
const shouldPlaySound = isFocusMode && resolvedPlaybackState === "running"; const shouldPlaySound = isFocusMode && resolvedPlaybackState === "running";
const currentSessionId = currentSession?.id ?? null;
const { activeStatus, pushStatusLine, runActiveAction } = const { activeStatus, pushStatusLine, runActiveAction } =
useHudStatusLine(isFocusMode); useHudStatusLine(isFocusMode);
@@ -207,10 +217,10 @@ export const SpaceWorkspaceWidget = () => {
: undefined; : undefined;
useEffect(() => { useEffect(() => {
if (!isBootstrapping && !currentSession) { if (!isBootstrapping && !currentSession && !pendingCompletionResult) {
router.replace("/app"); router.replace("/app");
} }
}, [isBootstrapping, currentSession, router]); }, [isBootstrapping, currentSession, pendingCompletionResult, router]);
useEffect(() => { useEffect(() => {
if (isBootstrapping || didResolveEntryRouteRef.current) { if (isBootstrapping || didResolveEntryRouteRef.current) {
@@ -224,6 +234,41 @@ export const SpaceWorkspaceWidget = () => {
} }
}, [currentSession, isBootstrapping]); }, [currentSession, isBootstrapping]);
useEffect(() => {
let mounted = true;
const syncCurrentSessionThoughts = async () => {
if (!currentSessionId) {
if (!pendingCompletionResult && mounted) {
setCurrentSessionThoughts([]);
}
return;
}
try {
const thoughts = await focusSessionApi.getCurrentSessionThoughts();
if (!mounted) {
return;
}
setCurrentSessionThoughts(thoughts);
} catch {
if (!mounted) {
return;
}
setCurrentSessionThoughts([]);
}
};
void syncCurrentSessionThoughts();
return () => {
mounted = false;
};
}, [currentSessionId, pendingCompletionResult]);
useEffect(() => { useEffect(() => {
const preferMobile = const preferMobile =
typeof window !== "undefined" typeof window !== "undefined"
@@ -258,7 +303,7 @@ export const SpaceWorkspaceWidget = () => {
</div> </div>
<SpaceSetupDrawerWidget <SpaceSetupDrawerWidget
open={!isFocusMode} open={!isFocusMode && !isCompletionResultOpen}
scenes={selection.setupScenes} scenes={selection.setupScenes}
sceneAssetMap={sceneAssetMap} sceneAssetMap={sceneAssetMap}
selectedSceneId={selection.selectedScene.id} selectedSceneId={selection.selectedScene.id}
@@ -322,23 +367,63 @@ export const SpaceWorkspaceWidget = () => {
sessionPhase={phase ?? 'focus'} sessionPhase={phase ?? 'focus'}
onIntentUpdate={controls.handleIntentUpdate} onIntentUpdate={controls.handleIntentUpdate}
onGoalFinish={async () => { onGoalFinish={async () => {
const didFinish = await controls.handleGoalComplete(); const completionResult = await controls.handleGoalComplete();
if (didFinish) { if (completionResult) {
setShowReviewTeaserAfterComplete(true); setPendingCompletionResult(completionResult);
setCurrentSessionThoughts([]);
} }
return didFinish; return Boolean(completionResult);
}}
onTimerFinish={async () => {
const completionResult = await controls.handleTimerComplete();
if (completionResult) {
setPendingCompletionResult(completionResult);
setCurrentSessionThoughts([]);
}
return Boolean(completionResult);
}} }}
onTimerFinish={controls.handleTimerComplete}
onAddTenMinutes={() => controls.handleExtendCurrentPhase(10)} onAddTenMinutes={() => controls.handleExtendCurrentPhase(10)}
onGoalUpdate={controls.handleGoalAdvance} onGoalUpdate={controls.handleGoalAdvance}
onStatusMessage={pushStatusLine} onStatusMessage={pushStatusLine}
onCaptureThought={(note) => addThought(note, selection.selectedScene.name)} onCaptureThought={(note) => {
void addThought(note, selection.selectedScene.name).then((savedThought) => {
if (!savedThought) {
return;
}
setCurrentSessionThoughts((current) => {
if (current.some((thought) => thought.id === savedThought.id)) {
return current;
}
return [...current, {
id: savedThought.id,
text: savedThought.text,
sceneName: savedThought.sceneName,
capturedAt: savedThought.capturedAt,
isCompleted: savedThought.isCompleted ?? false,
}];
});
});
}}
onExitRequested={() => void controls.handleExitRequested()} onExitRequested={() => void controls.handleExitRequested()}
/> />
) : null} ) : null}
<CompletionResultModal
open={isCompletionResultOpen}
result={pendingCompletionResult}
onClose={() => {
setPendingCompletionResult(null);
setCurrentSessionThoughts([]);
router.replace('/app');
}}
/>
<FocusTopToast <FocusTopToast
visible={isFocusMode && Boolean(activeStatus)} visible={isFocusMode && Boolean(activeStatus)}
message={activeStatus?.message ?? ""} message={activeStatus?.message ?? ""}