Spaces:
Running
Running
File size: 17,594 Bytes
3eae4cc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | import { useState, useRef, useCallback, useEffect } from "react";
import { api } from "../api/client";
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Narrative translator: maps raw action β human-readable causeβeffect story
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function mapActionToStory(actionType, payload, reward, backlogDelta, slaDelta, fairnessDelta) {
let title = "Standard Processing Cycle";
let desc = "The system advanced one cycle and continued normal queue processing.";
let reason = "No override was required, so routine processing continued.";
let icon = "schedule";
let type = reward > 0 ? "success" : "info";
const changes = [];
if (backlogDelta < 0) changes.push(`backlog improved by ${Math.abs(backlogDelta)} case(s)`);
else if (backlogDelta > 0) changes.push(`backlog increased by ${backlogDelta} case(s)`);
else changes.push("backlog stayed stable");
if (slaDelta > 0) changes.push(`${slaDelta} new SLA breach(es) occurred`);
else if (slaDelta < 0) changes.push(`${Math.abs(slaDelta)} SLA breach(es) recovered`);
if (Number.isFinite(Number(fairnessDelta)) && Number(fairnessDelta) !== 0) {
const v = Number(fairnessDelta);
changes.push(`fairness gap ${v > 0 ? "worsened" : "improved"} by ${Math.abs(v).toFixed(3)}`);
}
const effectClause = `${changes.join(", ")}.`;
if (slaDelta > 0) type = "error";
switch (actionType) {
case "assign_capacity":
title = "Capacity Assigned";
desc = `Officers were assigned to '${payload.service_target ?? payload.service ?? "target queue"}'; ${effectClause}`;
reason = "The agent detected staffing pressure and increased capacity where it could reduce delay.";
icon = "group_add";
break;
case "reallocate_officers":
title = "Staff Reallocated";
desc = `Officers were reallocated toward higher-pressure services; ${effectClause}`;
reason = `The agent shifted staffing to reduce bottlenecks in '${payload.service_target ?? "priority"}' services.`;
icon = "compare_arrows";
break;
case "request_missing_documents":
title = "Documents Requested";
desc = `Missing documents were requested to unblock pending files; ${effectClause}`;
reason = "The agent prioritized document blockers to avoid queue stagnation.";
icon = "rule_folder";
type = type !== "error" ? "success" : type;
break;
case "escalate_service":
title = "Service Escalated";
desc = `At-risk services were escalated for faster handling; ${effectClause}`;
reason = "Escalation was used to protect SLA-critical cases.";
icon = "warning";
type = "warning";
break;
case "set_priority_mode":
title = "Priority Mode Updated";
desc = `Priority mode switched to '${payload.priority_mode ?? "balanced"}'; ${effectClause}`;
reason = "The agent changed queue strategy to better match current workload pressure.";
icon = "model_training";
break;
default:
desc = `Routine processing executed; ${effectClause}`;
break;
}
if (reward < 0 && type === "info") type = "warning";
const isHighReward = reward >= 1.0;
const isHugeImpact = backlogDelta <= -5;
return { title, desc, reason, icon, type, isHighReward, isHugeImpact };
}
// Determines the simulation phase label from step index and total
function getPhase(step, maxSteps) {
const pct = step / Math.max(maxSteps, 1);
if (pct < 0.33) return "early";
if (pct < 0.67) return "middle";
return "late";
}
// Detect if a step is a "key decision" turning point
function isKeyDecision(s, backlogDelta) {
return (
Math.abs(Number(s.reward)) >= 1.0 || // high reward magnitude
(backlogDelta !== 0 && Math.abs(backlogDelta) >= 5) || // large backlog swing
Boolean(s.invalid_action) // failed action = notable event
);
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Hook
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export function useStorySimulation({ defaultTask }) {
const [taskId, setTaskId] = useState(defaultTask || "district_backlog_easy");
const [maxSteps, setMaxSteps] = useState(40);
const [agentMode, setAgentMode] = useState("trained_rl");
const [policyName, setPolicyName] = useState("backlog_clearance");
const [modelPath, setModelPath] = useState("");
const [modelType, setModelType] = useState("maskable");
const [availablePolicies, setAvailablePolicies] = useState([]);
const [availableModels, setAvailableModels] = useState([]);
const [configError, setConfigError] = useState("");
const [running, setRunning] = useState(false);
const [starting, setStarting] = useState(false);
const [runId, setRunId] = useState("");
const [kpis, setKpis] = useState({
backlog: 0, backlogDelta: 0,
slaBreaches: 0, slaDelta: 0,
fairness: 0, fairnessDelta: 0,
});
const [timeline, setTimeline] = useState([]);
const [resources, setResources] = useState([]);
// Progress tracking
const [currentStep, setCurrentStep] = useState(0);
// Before vs after journey stats
const [journeyStats, setJourneyStats] = useState(null); // null = not yet done
// Internal refs
const lastState = useRef({ backlog: 0, sla: 0, fairness: 0 });
const initialSnapshot = useRef(null); // captured on first real step
const stepCount = useRef(0);
const maxStepsRef = useRef(40);
useEffect(() => {
let mounted = true;
(async () => {
try {
const [policiesRes, modelsV1Res, modelsV2Res] = await Promise.allSettled([
api("/agents"),
api("/rl_models"),
api("/rl/models"),
]);
if (!mounted) return;
const policyRows = policiesRes.status === "fulfilled" && Array.isArray(policiesRes.value) ? policiesRes.value : [];
setAvailablePolicies(policyRows);
if (policyRows.length > 0 && !policyRows.includes(policyName)) {
setPolicyName(policyRows[0]);
}
const modelRowsV1 = modelsV1Res.status === "fulfilled" && Array.isArray(modelsV1Res.value?.models)
? modelsV1Res.value.models
: [];
const modelRowsV2 = modelsV2Res.status === "fulfilled" && Array.isArray(modelsV2Res.value)
? modelsV2Res.value.map((row) => ({
label: row?.model_path ? String(row.model_path).split(/[\\/]/).pop() : "model",
path: row?.model_path ? (String(row.model_path).toLowerCase().endsWith(".zip") ? row.model_path : `${row.model_path}.zip`) : "",
exists: Boolean(row?.exists),
model_type: "maskable",
}))
: [];
const dedupe = new Map();
for (const m of [...modelRowsV1, ...modelRowsV2]) {
const key = String(m?.path || "").replace(/\\/g, "/").toLowerCase();
if (!key || dedupe.has(key)) continue;
dedupe.set(key, m);
}
const existingModels = Array.from(dedupe.values()).filter((m) => Boolean(m?.exists));
setAvailableModels(existingModels);
const preferred =
existingModels.find((m) => String(m.path || "").toLowerCase().includes("phase2_final")) ||
existingModels[0];
if (preferred?.path) {
setModelPath(preferred.path);
setModelType(preferred.model_type || "maskable");
setAgentMode((prev) => (prev === "baseline_policy" ? "trained_rl" : prev));
}
} catch (err) {
if (!mounted) return;
setConfigError(err?.message || "Failed to load simulation options.");
}
})();
return () => {
mounted = false;
};
}, []);
const startSimulation = async () => {
setStarting(true);
setConfigError("");
setJourneyStats(null);
setCurrentStep(0);
initialSnapshot.current = null;
stepCount.current = 0;
maxStepsRef.current = maxSteps;
try {
const payload = {
task_id: taskId,
agent_mode: agentMode,
max_steps: maxSteps,
policy_name: policyName,
model_path: modelPath || null,
model_type: modelType,
};
const started = await api("/simulation/live/start", {
method: "POST",
body: JSON.stringify(payload),
});
setRunId(started.run_id);
setTimeline([{
id: "start",
time: "Step 0",
title: "Simulation Initialized",
desc: `Scenario locked: ${taskId.replace(/_/g, " ")}. Agent mode '${agentMode}' engaged β agent begins resolving backlog.`,
impact: 0,
type: "info",
icon: "rocket_launch",
phase: "early",
key: false,
}]);
setResources([]);
lastState.current = { backlog: 0, sla: 0, fairness: 0 };
setRunning(true);
} catch (err) {
console.error("Start failed:", err);
setTimeline([{
id: "error",
time: "β",
title: "Initialization Failed",
desc: `Backend error: ${err.message || "Cannot start simulation."}`,
impact: 0,
type: "error",
icon: "error",
phase: "early",
key: false,
}]);
setConfigError(err?.message || "Cannot start simulation.");
} finally {
setStarting(false);
}
};
const stopSimulation = async () => {
if (!runId) return;
try {
await api(`/simulation/live/${runId}/stop`, { method: "POST" });
} catch (err) {
console.error(err);
} finally {
setRunning(false);
}
};
// Polling loop β runs while running=true
const runLoop = useCallback(async (rid, cancelled) => {
if (cancelled.v) return;
try {
const res = await api("/simulation/live/step", {
method: "POST",
body: JSON.stringify({ run_id: rid }),
});
if (cancelled.v) return;
if (res.step) {
const s = res.step;
stepCount.current += 1;
const stepNum = Number(s.step ?? stepCount.current);
setCurrentStep(stepNum);
const currentBacklog = Number(s.backlog ?? 0);
const currentSla = Number(s.sla_breaches ?? 0);
const currentFairness = Number(s.fairness_gap ?? 0);
// Capture initial snapshot from step 1
if (initialSnapshot.current === null) {
initialSnapshot.current = {
backlog: currentBacklog,
sla: currentSla,
fairness: currentFairness,
};
}
const backlogDelta = currentBacklog - lastState.current.backlog;
const slaDelta = currentSla - lastState.current.sla;
const fairnessDelta = currentFairness - lastState.current.fairness;
setKpis({
backlog: currentBacklog,
backlogDelta,
slaBreaches: currentSla,
slaDelta,
fairness: currentFairness,
fairnessDelta,
});
lastState.current = { backlog: currentBacklog, sla: currentSla, fairness: currentFairness };
const payload = typeof s.action_payload === "string"
? (() => { try { return JSON.parse(s.action_payload); } catch { return {}; } })()
: (s.action_payload || {});
const story = mapActionToStory(
s.action_type || "advance_time",
payload,
Number(s.reward),
backlogDelta,
slaDelta,
fairnessDelta
);
const phase = getPhase(stepNum, maxStepsRef.current);
const key = isKeyDecision(s, backlogDelta);
const improvesBacklog = backlogDelta < 0;
const worsensBacklog = backlogDelta > 0;
const worsensSla = slaDelta > 0;
const improvesSla = slaDelta < 0;
const outcomeLabel = improvesBacklog || improvesSla
? "Improvement"
: worsensBacklog || worsensSla
? "Degradation"
: "Stable";
const outcomeType = outcomeLabel === "Improvement" ? "success" : outcomeLabel === "Degradation" ? "warning" : "info";
const newEvent = {
id: `step-${stepNum}`,
time: `Step ${stepNum}`,
title: s.invalid_action ? "Action Blocked" : story.title,
desc: s.invalid_action
? "This action was blocked by environment constraints; the agent adapts on the next step."
: story.desc,
reason: s.invalid_action ? "The attempted operation violated environment constraints (e.g. over-assignment)." : story.reason,
impact: Number(s.reward),
type: s.invalid_action ? "error" : story.type,
icon: s.invalid_action ? "block" : story.icon,
isHighReward: story.isHighReward && !s.invalid_action,
isHugeImpact: story.isHugeImpact && !s.invalid_action,
phase,
key,
outcomeLabel,
outcomeType,
backlogDelta, // Used for phase summary
};
// Collapse consecutive identical titles (deduplication for repeated events)
setTimeline((prev) => {
const [top, ...rest] = prev;
if (
top &&
top.title === newEvent.title &&
top.phase === newEvent.phase &&
!top.key &&
!newEvent.key
) {
// Merge: bump count, accumulate reward and backlog diff
const merged = {
...top,
id: newEvent.id,
time: `${top.time?.split("β")[0]?.trim()}β${newEvent.time}`,
desc: top.desc,
impact: Number(top.impact) + Number(newEvent.impact),
backlogDelta: (top.backlogDelta || 0) + backlogDelta,
_count: (top._count || 1) + 1,
};
return [merged, ...rest].slice(0, 30);
}
return [newEvent, ...prev].slice(0, 30);
});
// Update queue monitors
if (Array.isArray(s.queue_rows) && s.queue_rows.length > 0) {
const maxCases = Math.max(...s.queue_rows.map((q) => q.active_cases ?? 0), 1);
setResources(s.queue_rows.map((q) => ({
name: (q.service ?? q.service_type ?? "unknown").replace(/_/g, " ").toUpperCase(),
activeCases: q.active_cases ?? 0,
percentage: Math.min(100, Math.floor(((q.active_cases ?? 0) / maxCases) * 100)),
})));
}
}
// Episode done
if (res.done || res.step?.done) {
const finalBacklog = lastState.current.backlog;
const initSnap = initialSnapshot.current ?? { backlog: finalBacklog, sla: 0, fairness: 0 };
const backlogImprovement = initSnap.backlog > 0
? Math.round(((initSnap.backlog - finalBacklog) / initSnap.backlog) * 100)
: 0;
setJourneyStats({
initialBacklog: initSnap.backlog,
finalBacklog,
backlogImprovement,
initialSla: initSnap.sla,
finalSla: lastState.current.sla,
totalSteps: stepCount.current,
finalScore: res.score ?? null,
totalReward: res.total_reward ?? null,
});
setTimeline((prev) => [{
id: "end",
time: "Final",
title: "Episode Complete",
desc: `Resolution finished in ${stepCount.current} steps. Final score: ${res.score != null ? (res.score * 100).toFixed(1) + "%" : "N/A"}. Backlog ${finalBacklog < initSnap.backlog ? "reduced" : "unchanged"} β SLAs verified.`,
impact: res.total_reward ?? 0,
type: "success",
icon: "verified",
phase: "late",
key: true,
}, ...prev]);
setRunning(false);
return;
}
setTimeout(() => runLoop(rid, cancelled), 1000);
} catch (err) {
if (!cancelled.v) {
setRunning(false);
setTimeline((prev) => [{
id: `error-${Date.now()}`,
time: "Halted",
title: "System Error Detected",
desc: `Backend synchronization failed: ${err.message}`,
impact: 0,
type: "error",
icon: "warning",
phase: "late",
key: false,
}, ...prev]);
}
}
}, []);
// Start/stop the polling loop reactively
const cancelRef = useRef({ v: false });
useEffect(() => {
if (!running || !runId) {
cancelRef.current.v = true;
return undefined;
}
cancelRef.current = { v: false };
const boot = setTimeout(() => {
if (!cancelRef.current.v) {
runLoop(runId, cancelRef.current);
}
}, 100);
return () => {
clearTimeout(boot);
cancelRef.current.v = true;
};
}, [running, runId, runLoop]);
return {
taskId, setTaskId,
maxSteps, setMaxSteps,
agentMode, setAgentMode,
policyName, setPolicyName,
modelPath, setModelPath,
modelType, setModelType,
availablePolicies,
availableModels,
configError,
running, starting,
currentStep,
kpis, timeline, resources,
journeyStats,
startSimulation, stopSimulation,
};
}
|