Merge branch 'feat/monitoringpage-pim' into feat/monitoringpage

This commit is contained in:
Pim Hutting
2026-01-12 13:04:15 +01:00
58 changed files with 4916 additions and 525 deletions

View File

@@ -3,7 +3,6 @@ import styles from './MonitoringPage.module.css';
/**
* HELPER: Unified sender function
* In a real app, you might move this to a /services or /hooks folder
*/
const sendUserInterrupt = async (type: string, context: string) => {
try {
@@ -115,42 +114,64 @@ interface StatusListProps {
title: string;
items: StatusItem[];
type: 'goal' | 'trigger' | 'norm'| 'cond_norm';
activeIds: Record<string, boolean>;
currentGoalIndex?: number;
}
// --- STATUS LIST COMPONENT ---
export const StatusList: React.FC<StatusListProps> = ({ title, items, type }) => {
export const StatusList: React.FC<StatusListProps> = ({
title,
items,
type,
activeIds,
currentGoalIndex // Destructure this prop
}) => {
return (
<section className={styles.phaseBox}>
<h3>{title}</h3>
<ul>
{items.length > 0 ? (
items.map((item, idx) => {
const isAchieved = item.achieved;
const showIndicator = type !== 'norm';
const canOverride = showIndicator && !isAchieved;
{items.map((item, idx) => {
const isActive = !!activeIds[item.id];
const showIndicator = type !== 'norm';
const canOverride = showIndicator && !isActive;
return (
<li key={item.id ?? idx} className={styles.statusItem}>
{showIndicator && (
<span
className={`${styles.statusIndicator} ${canOverride ? styles.clickable : ''}`}
onClick={() => canOverride && sendUserInterrupt("override", String(item.id))}
title={canOverride ? `Send override for ID: ${item.id}` : 'Achieved'}
style={{ cursor: canOverride ? 'pointer' : 'default' }}
>
{isAchieved ? "✔️" : "❌"}
</span>
)}
// HIGHLIGHT LOGIC:
// If this is the "Goals" list, check if the current index matches
const isCurrentGoal = type === 'goal' && idx === currentGoalIndex;
<span className={styles.itemDescription}>
{item.description || item.label || item.norm}
const handleOverrideClick = () => {
if (!canOverride) return;
sendUserInterrupt("override", String(item.id));
};
return (
<li key={item.id ?? idx} className={styles.statusItem}>
{showIndicator && (
<span
className={`${styles.statusIndicator} ${canOverride ? styles.clickable : ''}`}
onClick={handleOverrideClick}
>
{isActive ? "✔️" : "❌"}
</span>
</li>
);
})
) : (
<p className={styles.emptyText}>No {title.toLowerCase()} defined.</p>
)}
)}
<span
className={styles.itemDescription}
style={{
// Visual Feedback
textDecoration: isCurrentGoal ? 'underline' : 'none',
fontWeight: isCurrentGoal ? 'bold' : 'normal',
color: isCurrentGoal ? '#007bff' : 'inherit',
backgroundColor: isCurrentGoal ? '#e7f3ff' : 'transparent', // Added subtle highlight
padding: isCurrentGoal ? '2px 4px' : '0',
borderRadius: '4px'
}}
>
{item.description || item.label || item.norm}
{isCurrentGoal && " (Current)"}
</span>
</li>
);
})}
</ul>
</section>
);

View File

@@ -106,8 +106,31 @@
border: 1px solid var(--border-color);
box-shadow: var(--panel-shadow);
padding: 1rem;
display: flex;
display: flex;
flex-direction: column;
box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.05);
height: 250px;
}
.phaseBox ul {
list-style: none;
padding: 0;
margin: 0;
overflow-y: auto;
flex-grow: 1;
}
.phaseBox ul::-webkit-scrollbar {
width: 6px;
}
.phaseBox ul::-webkit-scrollbar-thumb {
background-color: #ccc;
border-radius: 10px;
}
.phaseOverviewText {

View File

@@ -1,13 +1,12 @@
import React from 'react';
import React, { use } from 'react';
import styles from './MonitoringPage.module.css';
import useProgramStore from "../../utils/programStore.ts";
import { GestureControls, SpeechPresets, DirectSpeechInput, StatusList, RobotConnected } from './Components';
import { nextPhase, pauseExperiment, playExperiment, resetExperiment, resetPhase } from ".//MonitoringPageAPI.ts"
type Goal = { id?: string | number; description?: string; achieved?: boolean };
type Trigger = { id?: string | number; label?: string ; achieved?: boolean };
type Norm = { id?: string | number; norm?: string };
import { nextPhase, useExperimentLogger, pauseExperiment, playExperiment, resetExperiment, resetPhase } from ".//MonitoringPageAPI.ts"
import type { GoalNodeData } from '../VisProgPage/visualProgrammingUI/nodes/GoalNode.tsx';
import type { TriggerNodeData } from '../VisProgPage/visualProgrammingUI/nodes/TriggerNode.tsx';
import type { NormNodeData } from '../VisProgPage/visualProgrammingUI/nodes/NormNode.tsx';
const MonitoringPage: React.FC = () => {
const getPhaseIds = useProgramStore((s) => s.getPhaseIds);
@@ -17,10 +16,72 @@ const MonitoringPage: React.FC = () => {
// Can be used to block actions until feedback from CB.
const [loading, setLoading] = React.useState(false);
const [activeIds, setActiveIds] = React.useState<Record<string, boolean>>({});
const [goalIndex, setGoalIndex] = React.useState(0);
const [isPlaying, setIsPlaying] = React.useState(false);
const phaseIds = getPhaseIds();
const [phaseIndex, _] = React.useState(0);
const [phaseIndex, setPhaseIndex] = React.useState(0);
const isFinished = phaseIndex >= phaseIds.length; //determines if experiment is over
const handleStreamUpdate = React.useCallback((data: any) => {
// Check for phase updates
if (data.type === 'phase_update' && data.phase_id) {
const allIds = getPhaseIds();
const newIndex = allIds.indexOf(data.phase_id);
if (newIndex !== -1) {
setPhaseIndex(newIndex);
setGoalIndex(0); //when phase change we reset the index
}
}
else if (data.type === 'goal_update') {
const currentPhaseGoals = getGoalsInPhase(phaseIds[phaseIndex]) as any[];
const gIndex = currentPhaseGoals.findIndex((g: any) => g.id === data.id);
if (gIndex !== -1) {
//set current goal to the goal that is just started
setGoalIndex(gIndex);
// All previous goals are set to "active" which means they are achieved
setActiveIds((prev) => {
const nextState = { ...prev };
// We loop until i is LESS than gIndex.
// This leaves currentPhaseGoals[gIndex] as isActive: false.
for (let i = 0; i < gIndex; i++) {
nextState[currentPhaseGoals[i].id ] = true;
}
return nextState;
});
console.log(`Now pursuing goal: ${data.id}. Previous goals marked achieved.`);
}
}
else if (data.type === 'trigger_update') {
setActiveIds((prev) => ({
...prev,
[data.id]: data.achieved // data.id is de key, achieved is true/false
}));
}
else if (data.type === 'cond_norms_state_update') {
setActiveIds((prev) => {
const nextState = { ...prev };
data.norms.forEach((normUpdate: { id: string; active: boolean }) => {
nextState[normUpdate.id] = normUpdate.active;
});
return nextState;
});
console.log("Updated conditional norms state:", data.norms);
}
}, [getPhaseIds]);
useExperimentLogger(handleStreamUpdate);
if (phaseIds.length === 0) {
return <p className={styles.empty}>No program loaded.</p>;
@@ -28,9 +89,72 @@ const MonitoringPage: React.FC = () => {
const phaseId = phaseIds[phaseIndex];
const goals = getGoalsInPhase(phaseId) as Goal[];
const triggers = getTriggersInPhase(phaseId) as Trigger[];
const norms = getNormsInPhase(phaseId) as Norm[];
const goals = (getGoalsInPhase(phaseId) as any[]).map(g => ({
...g,
label: g.name,
achieved: activeIds[g.id] ?? false
}));
const triggers = (getTriggersInPhase(phaseId) as any[]).map(t => ({
...t,
label: (() => {
let prefix = "";
if (t.condition?.keyword) {
prefix = `if keywords said: "${t.condition.keyword}"`;
} else if (t.condition?.name) {
prefix = `if LLM belief: ${t.condition.name}`;
} else { //fallback
prefix = t.label || "Trigger";
}
const stepLabels = t.plan?.steps?.map((step: any) => {
if (step.text) {
return `say: "${step.text}"`;
}
if (step.gesture) {
return `perform gesture: ${step.gesture.name || step.gesture.type}`;
}
if (step.goal) {
return `perform LLM: ${step.goal}`;
}
return "Action"; // Fallback
}) || [];
const planText = stepLabels.length > 0
? `➔ Do: ${stepLabels.join(", ")}`
: "➔ (No actions set)";
return `${prefix} ${planText}`;
})(),
isActive: activeIds[t.id] ?? false
}));
const norms = (getNormsInPhase(phaseId) as NormNodeData[])
.filter(n => !n.condition)
.map(n => ({
...n,
label: n.norm,
}));
const conditionalNorms = (getNormsInPhase(phaseId) as any[])
.filter(n => !!n.condition) // Only items with a condition
.map(n => ({
...n,
label: (() => {
let prefix = "";
if (n.condition?.keyword) {
prefix = `if keywords said: "${n.condition.keyword}"`;
} else if (n.condition?.name) {
prefix = `if LLM belief: ${n.condition.name}`;
}
return `${prefix} ➔ Norm: ${n.norm}`;
})(),
achieved: activeIds[n.id] ?? false
}));
// Handle logic of 'next' button.
@@ -67,13 +191,19 @@ const MonitoringPage: React.FC = () => {
<header className={styles.experimentOverview}>
<div className={styles.phaseName}>
<h2>Experiment Overview</h2>
<p><strong>Phase name:</strong> Rhyming fish</p>
<p><strong>Phase</strong> {` ${phaseIndex + 1}`} </p>
<div className={styles.phaseProgress}>
<span className={`${styles.phase} ${styles.completed}`}>1</span>
<span className={`${styles.phase} ${styles.completed}`}>2</span>
<span className={`${styles.phase} ${styles.current}`}>3</span>
<span className={styles.phase}>4</span>
<span className={styles.phase}>5</span>
{phaseIds.map((id, index) => (
<span
key={id}
className={`${styles.phase} ${
index < phaseIndex ? styles.completed :
index === phaseIndex ? styles.current : ""
}`}
>
{index + 1}
</span>
))}
</div>
</div>
@@ -140,15 +270,18 @@ const MonitoringPage: React.FC = () => {
<section className={styles.phaseOverviewText}>
<h3>Phase Overview</h3>
</section>
<StatusList title="Goals" items={goals} type="goal" />
<StatusList title="Triggers" items={triggers} type="trigger" />
<StatusList title="Norms" items={norms} type="norm" />
<StatusList
title="Conditional Norms"
items={[{ id: 'cn_1', norm: '“RP is sad” - Be nice', achieved: false }]}
type="cond_norm"
/>
{isFinished ? (
<div className={styles.finishedMessage}>
<p> All phases have been successfully completed.</p>
</div>
) : (
<>
<StatusList title="Goals" items={goals} type="goal" activeIds={activeIds} currentGoalIndex={goalIndex} />
<StatusList title="Triggers" items={triggers} type="trigger" activeIds={activeIds} />
<StatusList title="Norms" items={norms} type="norm" activeIds={activeIds} />
<StatusList title="Conditional Norms" items={conditionalNorms} type="cond_norm" activeIds={activeIds} />
</>
)}
</main>
{/* LOGS */}

View File

@@ -1,3 +1,4 @@
import { useEffect } from 'react';
const API_BASE = "http://localhost:8000/button_pressed"; // Change depending on Pims interup agent/ correct endpoint
@@ -62,3 +63,35 @@ export async function playExperiment(): Promise<void> {
const context = "false"
sendAPICall(type, context)
}
/**
* A hook that listens to the experiment stream and logs data to the console.
* It does not render anything.
*/
export function useExperimentLogger(onUpdate?: (data: any) => void) {
useEffect(() => {
const eventSource = new EventSource(`${API_BASE}`);
eventSource.onmessage = (event) => {
try {
const parsedData = JSON.parse(event.data);
if (onUpdate) {
console.log(event.data);
onUpdate(parsedData);
}
} catch (err) {
console.warn("Stream parse error:", err);
}
};
eventSource.onerror = (err) => {
console.error("SSE Connection Error:", err);
eventSource.close();
};
return () => {
eventSource.close();
};
}, [onUpdate]);
}