feat(health): wire H5 health page, WeChat channel, and observation API.

Expose /health and /api/health/observations behind MEMIND_HEALTH_ENABLED, redirect ordinary chat health intents without persisting, and run a dedicated WeChat menu flow with confirm-before-write semantics.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
john
2026-09-02 10:05:56 +08:00
parent f96fdcb3b9
commit 7bf16500a1
22 changed files with 1132 additions and 10 deletions
+12
View File
@@ -10,6 +10,7 @@ import { ChatProvider } from './context/ChatProvider';
import { PREVIEW_USER } from './dev/mindspacePreviewData';
import { MindSpaceRoute } from './routes/MindSpaceRoute';
import { FeedbackRoutes } from './routes/FeedbackRoute';
import { HealthPage } from './pages/HealthPage';
import { useProductAnalytics } from './analytics/productAnalytics';
import type { CapabilityMap, PortalUser } from './types';
@@ -43,6 +44,7 @@ function AuthenticatedApp({
capabilities,
grantedSkills,
goalRunEnabled,
healthEnabled,
onUserUpdate,
onGrantedSkillsUpdate,
onLogout,
@@ -51,6 +53,7 @@ function AuthenticatedApp({
capabilities?: CapabilityMap;
grantedSkills?: string[];
goalRunEnabled?: boolean;
healthEnabled?: boolean;
onUserUpdate: (user: PortalUser) => void;
onGrantedSkillsUpdate: (skills: string[]) => void;
onLogout: () => void;
@@ -104,6 +107,7 @@ function AuthenticatedApp({
capabilities={capabilities}
grantedSkills={grantedSkills}
goalRunEnabled={goalRunEnabled}
healthEnabled={healthEnabled}
onUserUpdate={onUserUpdate}
>
<Routes>
@@ -115,6 +119,10 @@ function AuthenticatedApp({
path="/feedback/*"
element={<FeedbackRoutes user={user} onLogout={handleLogout} />}
/>
<Route
path="/health"
element={healthEnabled ? <HealthPage /> : <Navigate to="/" replace />}
/>
<Route path="/" element={chatElement} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
@@ -130,6 +138,7 @@ export function App() {
const [capabilities, setCapabilities] = useState<CapabilityMap | undefined>();
const [grantedSkills, setGrantedSkills] = useState<string[] | undefined>();
const [goalRunEnabled, setGoalRunEnabled] = useState<boolean | undefined>(undefined);
const [healthEnabled, setHealthEnabled] = useState<boolean | undefined>(undefined);
const [legacyMode, setLegacyMode] = useState(false);
const [authUnavailable, setAuthUnavailable] = useState<string | null>(null);
useProductAnalytics(user?.id);
@@ -156,6 +165,7 @@ export function App() {
setCapabilities(status.capabilities);
setGrantedSkills(status.grantedSkills);
setGoalRunEnabled(status.goalRun?.enabled);
setHealthEnabled(status.health?.enabled);
if (status.authenticated) void loadBlockedWords();
});
return () => setUnauthorizedHandler(null);
@@ -217,6 +227,7 @@ export function App() {
setGrantedSkills(nextSkills);
void checkAuth().then((status) => {
setGoalRunEnabled(status.goalRun?.enabled);
setHealthEnabled(status.health?.enabled);
});
}}
/>
@@ -229,6 +240,7 @@ export function App() {
capabilities={capabilities}
grantedSkills={grantedSkills}
goalRunEnabled={goalRunEnabled}
healthEnabled={healthEnabled}
onUserUpdate={setUser}
onGrantedSkillsUpdate={setGrantedSkills}
onLogout={() => {
+27
View File
@@ -0,0 +1,27 @@
import { apiFetch } from './core';
export async function listHealthObservations(limit = 50) {
const data = await apiFetch(`/health/observations?limit=${limit}`);
return Array.isArray(data?.observations) ? data.observations : [];
}
export async function saveConfirmedBloodPressure(input: {
systolic: number;
diastolic: number;
context: 'morning' | 'evening' | 'other';
observedAt?: number;
}) {
return apiFetch('/health/observations', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
confirmed: true,
metricSet: 'blood_pressure',
systolic: input.systolic,
diastolic: input.diastolic,
context: input.context,
observedAt: input.observedAt ?? Date.now(),
source: 'manual',
}),
});
}
+28 -3
View File
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useChat } from '../context/ChatProvider';
import { INSUFFICIENT_BALANCE_NOTICE } from '../hooks/useTKMindChat';
import { useGoalRunBanner } from '../hooks/useGoalRunBanner';
@@ -19,6 +20,10 @@ import { ChatHeaderMoreMenu } from './ChatHeaderMoreMenu';
import { NotificationCenter } from './NotificationCenter';
import { GoalRunAwaitingBanner } from './GoalRunAwaitingBanner';
import type { MindSpaceSaveCategory } from '../types';
import {
HEALTH_REDIRECT_COPY,
shouldRedirectOrdinaryChatToHealth,
} from '../../health-intent-rules.mjs';
function RecentSessionRail({
sessions,
@@ -222,7 +227,9 @@ export function ChatView({
uploadChatAttachment,
followAgentRun,
goalRunEnabled,
healthEnabled,
} = useChat();
const navigate = useNavigate();
const online = useNetworkStatus();
const goalRunBanner = useGoalRunBanner({
userId: user?.id,
@@ -312,6 +319,9 @@ export function ChatView({
...(onOpenAdmin
? [{ id: 'admin', label: '管理', onClick: () => onOpenAdmin() }]
: []),
...(healthEnabled
? [{ id: 'health', label: '健康', onClick: () => navigate('/health') }]
: []),
...(onLogout
? [{ id: 'logout', label: '登出', onClick: () => onLogout(), danger: true }]
: []),
@@ -409,6 +419,16 @@ export function ChatView({
管理
</button>
)}
{healthEnabled && (
<button
type="button"
className="ghost-btn"
data-analytics-action="open_health"
onClick={() => navigate('/health')}
>
健康
</button>
)}
{onOpenSpace && (
<button
ref={spaceButtonRef}
@@ -579,7 +599,12 @@ export function ChatView({
onGrantedSkillsUpdate={onGrantedSkillsUpdate}
onOpenRecharge={() => openRecharge(false)}
taskLoadingTip={taskLoadingTip}
onSubmit={(text, imageUrls, previewImageUrls, options) =>
onSubmit={(text, imageUrls, previewImageUrls, options) => {
if (healthEnabled && shouldRedirectOrdinaryChatToHealth(text) && !options?.selectedChatSkill) {
window.alert(HEALTH_REDIRECT_COPY);
navigate('/health');
return;
}
void submit(
text,
{
@@ -593,8 +618,8 @@ export function ChatView({
},
imageUrls,
previewImageUrls,
)
}
);
}}
onUploadImage={(file, onProgress, options) =>
uploadChatImage(file, onProgress, { messageId: options?.messageId })
}
+7 -2
View File
@@ -4,7 +4,10 @@ import { SubscribeModal } from '../components/SubscribeModal';
import { useTKMindChat } from '../hooks/useTKMindChat';
import type { CapabilityMap, PortalUser } from '../types';
type ChatContextValue = ReturnType<typeof useTKMindChat>;
type ChatContextValue = ReturnType<typeof useTKMindChat> & {
goalRunEnabled?: boolean;
healthEnabled?: boolean;
};
const ChatContext = createContext<ChatContextValue | null>(null);
@@ -13,6 +16,7 @@ export function ChatProvider({
capabilities,
grantedSkills,
goalRunEnabled,
healthEnabled,
onUserUpdate,
children,
}: {
@@ -20,13 +24,14 @@ export function ChatProvider({
capabilities?: CapabilityMap | null;
grantedSkills?: string[];
goalRunEnabled?: boolean;
healthEnabled?: boolean;
onUserUpdate?: (user: PortalUser) => void;
children: ReactNode;
}) {
const chat = useTKMindChat(user, onUserUpdate, capabilities, grantedSkills);
return (
<ChatContext.Provider value={{ ...chat, goalRunEnabled }}>
<ChatContext.Provider value={{ ...chat, goalRunEnabled, healthEnabled }}>
{children}
{typeof chat.balanceCents === 'number' && chat.rechargePrompt && (
<RechargeModal
+54
View File
@@ -1081,6 +1081,60 @@ body,
justify-content: flex-end;
}
.health-page {
max-width: 720px;
margin: 0 auto;
padding: 24px 16px 48px;
display: flex;
flex-direction: column;
gap: 16px;
}
.health-page-header h1 {
margin: 8px 0 4px;
font-size: 22px;
}
.health-page-header p,
.health-message,
.health-empty {
color: var(--color-text-secondary, #5b6472);
line-height: 1.5;
}
.health-actions,
.health-form {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.health-form {
flex-direction: column;
max-width: 360px;
}
.health-form label {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 14px;
}
.health-form input,
.health-form select {
min-height: 40px;
padding: 8px 10px;
}
.health-timeline {
display: flex;
flex-direction: column;
gap: 8px;
padding: 0;
list-style: none;
}
.text-error {
color: var(--color-text-error);
}
+180
View File
@@ -0,0 +1,180 @@
import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { listHealthObservations, saveConfirmedBloodPressure } from '../api/health';
import {
HEALTH_CHANNEL_STEPS,
HEALTH_ACTIONS,
createIdleHealthChannelState,
reduceHealthChannel,
} from '../../health-channel-state.mjs';
import { inferBloodPressureContext, validateBloodPressurePair } from '../../health-observation-validate.mjs';
export function HealthPage() {
const navigate = useNavigate();
const [state, setState] = useState(() => createIdleHealthChannelState({ channel: 'h5' }));
const [systolic, setSystolic] = useState('');
const [diastolic, setDiastolic] = useState('');
const [context, setContext] = useState<'morning' | 'evening' | 'other'>(
inferBloodPressureContext(Date.now()),
);
const [draft, setDraft] = useState<{ systolic: number; diastolic: number; context: 'morning' | 'evening' | 'other' } | null>(null);
const [rows, setRows] = useState<Array<{ id: number; metricType: string; valueNum: number | null; context?: string | null; createdAt: number }>>([]);
const [message, setMessage] = useState('');
const [saving, setSaving] = useState(false);
const refresh = async () => {
try {
setRows(await listHealthObservations(30));
} catch (error) {
setMessage(error instanceof Error ? error.message : '读取失败');
}
};
useEffect(() => {
void refresh();
}, []);
const startRecord = () => {
const next = reduceHealthChannel(state, { type: 'select_action', action: HEALTH_ACTIONS.RECORD });
const picked = reduceHealthChannel(next.state, { type: 'pick_metric', metricSet: 'blood_pressure' });
const ready = reduceHealthChannel(picked.state, { type: 'pick_context', context });
setState(ready.state);
setMessage('请填写血压并确认。数值不会在确认前保存。');
};
const goConfirm = () => {
const pair = validateBloodPressurePair(Number(systolic), Number(diastolic));
if (!pair.ok) {
setMessage('请输入有效血压,例如 128 / 76。收缩压必须大于舒张压。');
return;
}
const next = reduceHealthChannel(state, { type: 'submit_value', draftId: 'h5-bp' });
setState(next.state);
setDraft({ systolic: pair.systolic, diastolic: pair.diastolic, context });
setMessage(`确认保存:${pair.systolic}/${pair.diastolic}(${context === 'morning' ? '晨间' : context === 'evening' ? '晚间' : '其他'})`);
};
const commit = async () => {
if (!draft) return;
setSaving(true);
try {
await saveConfirmedBloodPressure(draft);
const next = reduceHealthChannel(state, { type: 'commit' });
const reset = reduceHealthChannel(next.state, { type: 'continue' });
setState(reset.state);
setDraft(null);
setSystolic('');
setDiastolic('');
setMessage('已写入你的健康档案。这不是医疗诊断。');
await refresh();
} catch (error) {
setMessage(error instanceof Error ? error.message : '保存失败');
} finally {
setSaving(false);
}
};
const grouped = useMemo(() => {
const byTime = new Map<string, { systolic?: number; diastolic?: number; context?: string | null }>();
for (const row of rows) {
const key = String(row.createdAt);
const current = byTime.get(key) ?? {};
if (row.metricType === 'bp_systolic') current.systolic = Number(row.valueNum);
if (row.metricType === 'bp_diastolic') current.diastolic = Number(row.valueNum);
current.context = row.context;
byTime.set(key, current);
}
return [...byTime.entries()].map(([createdAt, value]) => ({ createdAt: Number(createdAt), ...value }));
}, [rows]);
return (
<div className="health-page">
<header className="health-page-header">
<button type="button" className="ghost-btn" onClick={() => navigate('/')}>
返回聊天
</button>
<h1>健康助手</h1>
<p>只记录你本人的数据。确认前不会写入,也不会在普通聊天落库。</p>
</header>
{state.step === HEALTH_CHANNEL_STEPS.IDLE && (
<div className="health-actions">
<button type="button" className="primary-btn" onClick={startRecord}>
1 健康录入
</button>
<button type="button" className="ghost-btn" onClick={() => setMessage('评估将在基线成熟后开启。请先连续记录。')}>
2 健康评估
</button>
<button type="button" className="ghost-btn" onClick={() => navigate('/space?category=health')}>
4 健康档案区
</button>
</div>
)}
{state.step !== HEALTH_CHANNEL_STEPS.IDLE && (
<form
className="health-form"
onSubmit={(event) => {
event.preventDefault();
if (state.step === HEALTH_CHANNEL_STEPS.CONFIRM) void commit();
else goConfirm();
}}
>
<label>
情境
<select value={context} onChange={(event) => setContext(event.target.value as typeof context)}>
<option value="morning">晨间</option>
<option value="evening">晚间</option>
<option value="other">其他</option>
</select>
</label>
<label>
收缩压
<input inputMode="numeric" value={systolic} onChange={(event) => setSystolic(event.target.value)} />
</label>
<label>
舒张压
<input inputMode="numeric" value={diastolic} onChange={(event) => setDiastolic(event.target.value)} />
</label>
{state.step === HEALTH_CHANNEL_STEPS.CONFIRM ? (
<button type="submit" className="primary-btn" disabled={saving}>
确认保存
</button>
) : (
<button type="submit" className="primary-btn">
下一步确认
</button>
)}
<button
type="button"
className="ghost-btn"
onClick={() => {
setState(createIdleHealthChannelState({ channel: 'h5' }));
setDraft(null);
setMessage('已取消本次录入。');
}}
>
取消
</button>
</form>
)}
{message && <p className="health-message">{message}</p>}
<section>
<h2>最近记录</h2>
{grouped.length === 0 ? (
<p className="health-empty">还没有确认过的血压记录。</p>
) : (
<ul className="health-timeline">
{grouped.map((item) => (
<li key={item.createdAt}>
{new Date(item.createdAt).toLocaleString()} · {item.systolic}/{item.diastolic} · {item.context || 'other'}
</li>
))}
</ul>
)}
</section>
</div>
);
}
+1
View File
@@ -1016,6 +1016,7 @@ export type AuthStatus = {
unrestricted?: boolean;
agentCodeRun?: AgentCodeRunClientPolicy | null;
goalRun?: GoalRunClientPolicy | null;
health?: { enabled: boolean } | null;
};
export type PageTemplateCatalogItem = {