From ce021b50870b609863846ad32b89ede4b54df255 Mon Sep 17 00:00:00 2001
From: Danang Avan Maulana
Date: Fri, 30 Oct 2026 17:42:28 +0700
Subject: [PATCH] feat(triage): chat-channel messages, set authoring,
context-aware remediation
- POST /api/triage lets trainers add triage sets (validated: id pattern,
4-40 items, must mix pretexts and legitimate messages, every pretext
needs a principle and explanation); audited.
- Triage Inbox renders WhatsApp/SMS items as a phone chat and offers a
set picker when more than one set exists.
- Remediation assignments carry reason_key/reason_params so the reason is
translated in the UI instead of stored as English text.
- Remediation prefers content sharing context tags with the failed
exercise and never re-assigns the exercise that was just failed;
retests follow the same rule.
- Scenario debrief keeps line breaks; removed duplicate untranslated
"Try another scenario" button.
Co-Authored-By: Claude Opus 5.5
---
backend/models/schemas.py | 4 +
backend/routes/triage.py | 69 ++++++++++++++-
backend/services/demo.py | 4 +-
backend/services/remediation.py | 68 ++++++++++++---
backend/tests/test_remediation.py | 73 ++++++++++++++++
backend/tests/test_triage.py | 47 +++++++++++
docs/api.md | 15 ++++
frontend/src/i18n/locales/en.json | 17 +++-
frontend/src/i18n/locales/id.json | 17 +++-
frontend/src/pages/MyAssignmentsPage.js | 21 ++++-
frontend/src/pages/SimulationPlayerPage.js | 15 ++--
frontend/src/pages/TriageInboxPage.js | 97 ++++++++++++++++++----
12 files changed, 397 insertions(+), 50 deletions(-)
diff --git a/backend/models/schemas.py b/backend/models/schemas.py
index 2432430..875ea9e 100644
--- a/backend/models/schemas.py
+++ b/backend/models/schemas.py
@@ -353,6 +353,10 @@ class Assignment(BaseModel):
reason: str | None = None # human-readable explanation shown to the trainee
principle: str | None = None # the Cialdini principle being remediated
retest_of: str | None = None # the remediation assignment this re-tests
+ # Translatable form of `reason` for system assignments: the client renders
+ # remediation. with these params; `reason` stays as the fallback.
+ reason_key: str | None = None
+ reason_params: dict[str, Any] | None = None
created_at: str = Field(default_factory=lambda: datetime.now(UTC).isoformat())
diff --git a/backend/routes/triage.py b/backend/routes/triage.py
index d327363..1250e1b 100644
--- a/backend/routes/triage.py
+++ b/backend/routes/triage.py
@@ -5,12 +5,15 @@
the server grades, computing d' with a false-alarm penalty.
"""
-from fastapi import APIRouter, Depends
-from pydantic import BaseModel, Field
+import uuid
+from typing import Literal
+
+from fastapi import APIRouter, Depends, HTTPException
+from pydantic import BaseModel, Field, model_validator
from models.schemas import User
-from services import triage
-from services.auth import get_current_user
+from services import audit, triage
+from services.auth import get_current_user, require_trainer
from services.database import db
router = APIRouter(prefix="/triage", tags=["triage"])
@@ -43,3 +46,61 @@ async def submit(
set_id: str, data: TriageSubmission, current_user: User = Depends(get_current_user)
):
return await triage.grade(set_id, current_user.id, data.marks, data.duration_seconds)
+
+
+# ---- authoring: trainers add their own sets (e.g. a unit-specific content pack)
+
+
+class TriageItemIn(BaseModel):
+ model_config = {"extra": "forbid"}
+ channel: Literal["email_inbox", "whatsapp", "sms"] = "email_inbox"
+ # For chat channels `from` is the contact as shown in the chat header and
+ # `subject` is the one-line preview in the chat list.
+ from_: str = Field(alias="from", min_length=1, max_length=200)
+ subject: str = Field(min_length=1, max_length=200)
+ body: str = Field(min_length=1, max_length=5000)
+ is_pretext: bool
+ principle: str | None = Field(default=None, max_length=40)
+ explanation: str | None = Field(default=None, max_length=2000)
+
+ @model_validator(mode="after")
+ def _pretext_is_explained(self):
+ if self.is_pretext and not (self.principle and self.explanation):
+ raise ValueError("a pretext needs a principle and an explanation for the debrief")
+ return self
+
+
+class TriageSetIn(BaseModel):
+ model_config = {"extra": "forbid"}
+ id: str | None = Field(default=None, min_length=3, max_length=80, pattern=r"^[a-z0-9-]+$")
+ title: str = Field(min_length=1, max_length=120)
+ description: str = Field(default="", max_length=1000)
+ language: Literal["en", "id"] = "en"
+ difficulty: Literal["easy", "medium", "hard"] = "medium"
+ items: list[TriageItemIn] = Field(min_length=4, max_length=40)
+
+ @model_validator(mode="after")
+ def _has_both_kinds(self):
+ # d' needs at least one pretext and one legitimate message to be defined.
+ kinds = {i.is_pretext for i in self.items}
+ if kinds != {True, False}:
+ raise ValueError("a set needs both pretexts and legitimate messages")
+ return self
+
+
+@router.post("", status_code=201)
+async def create_set(data: TriageSetIn, current_user: User = Depends(require_trainer)):
+ set_id = data.id or f"triage-{uuid.uuid4().hex[:12]}"
+ if await db.triage_sets.find_one({"id": set_id}, {"_id": 1}):
+ raise HTTPException(status_code=409, detail="A triage set with this id already exists")
+ doc = {
+ **data.model_dump(exclude={"items", "id"}),
+ "id": set_id,
+ "created_by": current_user.id,
+ "items": [
+ {"id": str(uuid.uuid4()), **item.model_dump(by_alias=True)} for item in data.items
+ ],
+ }
+ await db.triage_sets.insert_one(doc)
+ await audit.record(current_user.id, "triage.set.create", set_id, {"items": len(data.items)})
+ return {"id": set_id, "items": len(data.items)}
diff --git a/backend/services/demo.py b/backend/services/demo.py
index 4e6ecd7..59bc793 100644
--- a/backend/services/demo.py
+++ b/backend/services/demo.py
@@ -303,9 +303,11 @@ def _assignment(
"trainee_id": trainee_id,
"content_type": content_type,
"content_id": content_id,
- "title": f"{'Retest' if source == 'retest' else 'Remediation'}: {title}",
+ "title": title,
"instructions": reason,
"reason": reason,
+ "reason_key": "retest" if source == "retest" else "live_clicked",
+ "reason_params": {"principle": principle},
"principle": principle,
"source": source,
"retest_of": retest_of,
diff --git a/backend/services/remediation.py b/backend/services/remediation.py
index 0cde246..20c06a5 100644
--- a/backend/services/remediation.py
+++ b/backend/services/remediation.py
@@ -33,24 +33,47 @@
}
-async def _pick_content(principle: str, exclude_ids: set[str]) -> dict | None:
+# Tags that describe who an exercise is written for (language, setting). A
+# remediation should feel like the exercise that was failed, so candidates that
+# share more of these tags are preferred.
+CONTEXT_TAGS = {"indonesia", "satuan", "military"}
+
+
+async def _pick_content(
+ principle: str, exclude_ids: set[str], prefer_tags: set[str] | None = None
+) -> dict | None:
"""Choose a lab exercise that trains `principle` and the trainee hasn't just done.
Prefers an interactive scenario; falls back to a quiz on the same principle.
+ Within a type, prefers content sharing the most `prefer_tags`.
"""
+ prefer_tags = prefer_tags or set()
for coll, content_type in (("challenges", "challenge"), ("quizzes", "quiz")):
- async for doc in db[coll].find(
- {"cialdini_categories": principle}, {"_id": 0, "id": 1, "title": 1}
- ):
- if doc["id"] not in exclude_ids:
- return {
- "content_type": content_type,
- "content_id": doc["id"],
- "title": doc["title"],
- }
+ candidates = [
+ doc
+ async for doc in db[coll].find(
+ {"cialdini_categories": principle},
+ {"_id": 0, "id": 1, "title": 1, "metadata.tags": 1},
+ )
+ if doc["id"] not in exclude_ids
+ ]
+ if candidates:
+ # max() keeps the first of equal scores, so the stored order breaks ties.
+ best = max(
+ candidates,
+ key=lambda d: len(prefer_tags & set((d.get("metadata") or {}).get("tags") or [])),
+ )
+ return {"content_type": content_type, "content_id": best["id"], "title": best["title"]}
return None
+async def _context_tags(challenge_id: str | None) -> set[str]:
+ if not challenge_id:
+ return set()
+ doc = await db.challenges.find_one({"id": challenge_id}, {"_id": 0, "metadata.tags": 1})
+ return CONTEXT_TAGS & set(((doc or {}).get("metadata") or {}).get("tags") or [])
+
+
async def _recent_content_ids(user_id: str) -> set[str]:
"""Content the user already has active, or passed recently — don't re-assign it."""
ids: set[str] = set()
@@ -69,6 +92,10 @@ async def assign_remediation(
source: str = "remediation",
retest_of: str | None = None,
due_days: int = REMEDIATION_DUE_DAYS,
+ reason_key: str | None = None,
+ reason_params: dict | None = None,
+ prefer_tags: set[str] | None = None,
+ exclude_content: str | None = None,
) -> str | None:
"""Create a remediation assignment for `principle`. Idempotent per principle:
skips if the user already has an active remediation for it."""
@@ -86,7 +113,10 @@ async def assign_remediation(
if existing:
return None
- content = await _pick_content(principle, await _recent_content_ids(user_id))
+ exclude = await _recent_content_ids(user_id)
+ if exclude_content:
+ exclude.add(exclude_content) # never "remediate" with the exercise just failed
+ content = await _pick_content(principle, exclude, prefer_tags)
if not content:
logger.info(f"No remediation content for principle '{principle}'")
return None
@@ -96,9 +126,12 @@ async def assign_remediation(
trainee_id=user_id,
content_type=content["content_type"],
content_id=content["content_id"],
- title=f"Remediation: {content['title']}",
+ # The UI badges the source (remediation / retest), so the title stays the exercise's own.
+ title=content["title"],
instructions=reason,
reason=reason,
+ reason_key=reason_key,
+ reason_params={"principle": principle, **(reason_params or {})},
principle=principle,
source=source,
retest_of=retest_of,
@@ -121,12 +154,17 @@ async def on_lab_result(sim: dict, user_id: str) -> None:
return
principles = (sim.get("challenge_data") or {}).get("cialdini_categories") or []
title = sim.get("title", "an exercise")
+ prefer = await _context_tags(sim.get("challenge_id"))
for principle in principles[:2]:
await assign_remediation(
user_id,
principle,
f"You scored {round(score)}% on '{title}', which tested {_label(principle)}. "
f"This exercise gives you focused practice.",
+ reason_key="lab_fail",
+ reason_params={"score": round(score), "title": title},
+ prefer_tags=prefer,
+ exclude_content=sim.get("challenge_id"),
)
@@ -150,6 +188,8 @@ async def on_live_fail(campaign: dict, email: str, outcome: str) -> None:
principle,
f"In a live phishing simulation you {verb} a message that used {_label(principle)}. "
f"This exercise helps you recognise it next time.",
+ reason_key=f"live_{outcome}",
+ prefer_tags={"indonesia"} if campaign.get("language") == "id" else set(),
)
@@ -165,4 +205,8 @@ async def on_assignment_passed(assignment: dict, user_id: str) -> None:
source="retest",
retest_of=assignment["id"],
due_days=RETEST_AFTER_DAYS,
+ reason_key="retest",
+ # A variant: same context as the practice, but not the same exercise.
+ prefer_tags=await _context_tags(assignment.get("content_id")),
+ exclude_content=assignment.get("content_id"),
)
diff --git a/backend/tests/test_remediation.py b/backend/tests/test_remediation.py
index ce1278d..7acbcab 100644
--- a/backend/tests/test_remediation.py
+++ b/backend/tests/test_remediation.py
@@ -129,3 +129,76 @@ async def test_retest_not_scheduled_for_manual_assignment(api):
{"id": "m1", "source": "manual", "principle": "authority"}, user.id
)
assert await db.assignments.count_documents({"source": "retest"}) == 0
+
+
+async def test_reason_is_translatable(api):
+ """System assignments carry a reason key + params so the UI can localise them."""
+ from services import remediation
+
+ user, _ = await make_user("user")
+ await db.challenges.insert_one(
+ {
+ "id": "c-auth",
+ "title": "Authority drill",
+ "cialdini_categories": ["authority"],
+ "nodes": [],
+ }
+ )
+ await remediation.on_lab_result(
+ {
+ "score": 40,
+ "title": "Boss on WhatsApp",
+ "challenge_data": {"cialdini_categories": ["authority"]},
+ },
+ user.id,
+ )
+ a = await db.assignments.find_one({"trainee_id": user.id})
+ assert a["reason_key"] == "lab_fail"
+ assert a["reason_params"] == {
+ "principle": "authority",
+ "score": 40,
+ "title": "Boss on WhatsApp",
+ }
+
+
+async def test_remediation_prefers_same_context_and_skips_the_failed_exercise(api):
+ from services import remediation
+
+ user, _ = await make_user("user")
+ await db.challenges.insert_many(
+ [
+ {
+ "id": "en-auth",
+ "title": "Generic CEO fraud",
+ "cialdini_categories": ["authority"],
+ "metadata": {"tags": ["bec"]},
+ "nodes": [],
+ },
+ {
+ "id": "unit-failed",
+ "title": "Boss on WhatsApp",
+ "cialdini_categories": ["authority"],
+ "metadata": {"tags": ["whatsapp", "satuan", "military", "indonesia"]},
+ "nodes": [],
+ },
+ {
+ "id": "unit-other",
+ "title": "Nota dinas APK",
+ "cialdini_categories": ["authority"],
+ "metadata": {"tags": ["email", "satuan", "military", "indonesia"]},
+ "nodes": [],
+ },
+ ]
+ )
+ await remediation.on_lab_result(
+ {
+ "score": 40,
+ "title": "Boss on WhatsApp",
+ "challenge_id": "unit-failed",
+ "challenge_data": {"cialdini_categories": ["authority"]},
+ },
+ user.id,
+ )
+ a = await db.assignments.find_one({"trainee_id": user.id})
+ assert a["content_id"] == "unit-other" # same unit context, not the one just failed
+ assert a["title"] == "Nota dinas APK" # no English "Remediation:" prefix
diff --git a/backend/tests/test_triage.py b/backend/tests/test_triage.py
index da8474f..8f43d25 100644
--- a/backend/tests/test_triage.py
+++ b/backend/tests/test_triage.py
@@ -149,3 +149,50 @@ async def test_seed_fills_missing_set_without_touching_edited_one(api):
await triage.seed_default_set()
assert (await db.triage_sets.find_one({"id": "triage-inbox-01"}))["title"] == "Edited"
assert await db.triage_sets.find_one({"id": "triage-inbox-01-id"})
+
+
+def _set_payload(**over):
+ items = [
+ {
+ "channel": "whatsapp",
+ "from": "Atasan (nomor baru)",
+ "subject": "Tolong transfer dulu",
+ "body": "..",
+ "is_pretext": True,
+ "principle": "authority",
+ "explanation": "nomor baru",
+ },
+ {"from": "hr@acme.com", "subject": "Timesheet", "body": "..", "is_pretext": False},
+ {"from": "cal@acme.com", "subject": "Invite", "body": "..", "is_pretext": False},
+ {
+ "channel": "whatsapp",
+ "from": "Grup Kantor",
+ "subject": "Rapat jam 9",
+ "body": "..",
+ "is_pretext": False,
+ },
+ ]
+ return {"id": "pack-1", "title": "Pack", "language": "id", "items": items, **over}
+
+
+async def test_trainer_can_add_a_set_with_chat_items(api):
+ _, h = await make_user("trainer")
+ r = await api.post("/api/triage", json=_set_payload(), headers=h)
+ assert r.status_code == 201, r.text
+ taker, th = await make_user("user")
+ got = (await api.get("/api/triage/pack-1", headers=th)).json()
+ assert got["items"][0]["channel"] == "whatsapp"
+ assert "is_pretext" not in got["items"][0] # labels stay on the server
+ assert (await api.post("/api/triage", json=_set_payload(), headers=h)).status_code == 409
+
+
+async def test_set_authoring_rules(api):
+ _, uh = await make_user("user")
+ assert (await api.post("/api/triage", json=_set_payload(), headers=uh)).status_code == 403
+ _, h = await make_user("trainer")
+ only_legit = _set_payload()
+ only_legit["items"] = [dict(i, is_pretext=False) for i in only_legit["items"]]
+ assert (await api.post("/api/triage", json=only_legit, headers=h)).status_code == 422
+ unexplained = _set_payload()
+ unexplained["items"][0].pop("explanation")
+ assert (await api.post("/api/triage", json=unexplained, headers=h)).status_code == 422
diff --git a/docs/api.md b/docs/api.md
index 31c8da6..34ea7cd 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -43,6 +43,14 @@ Scenarios — `/api/scenarios`:
| POST | `/resume` | U | Resume/begin a session by `simulation_id` |
| GET | `/session/{id}` | U | Current session state |
+Inbox Triage — `/api/triage`:
+
+| Method | Path | Role | Notes |
+|--------|------|------|-------|
+| GET | `` / `/{id}` | U | List sets; `/{id}` strips labels and explanations |
+| POST | `/{id}/submit` | U | Server grades with signal detection (d′) |
+| POST | `` | T | Add a set (e.g. a unit-specific content pack). Items may be `email_inbox`, `whatsapp` or `sms`; a set needs both pretexts and legitimate messages, and every pretext needs a principle + explanation |
+
Simulations, debrief, reports — `/api/simulations`, `/api/debrief`,
`/api/reports`: read your own
(staff may review trainees). Clients **cannot** create graded simulation types
@@ -109,6 +117,13 @@ Audit — `/api/audit` (admin): `GET /` (entries), `GET /verify` (chain integrit
- `GET /api/attack-surface/targets` — emailable people on the map, ranked
most-susceptible first, to seed a campaign aimed at the human weak points.
+- `GET /api/readiness` — staff home screen: readiness index (components and
+ weights exposed), report-rate trend, remediation-loop counts, principle
+ resistance, lab d′ and attack-surface posture. Cohort-level only (G13).
+- `/api/demo` (admin) — `GET` status, `POST` load the fictional demo
+ organization (`demo.test`), `DELETE` remove it; only records tagged as demo
+ are touched.
+
## Health
`GET /api/health` — liveness + DB connectivity (used by Docker healthchecks).
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 52a907e..4d0fb89 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -675,7 +675,12 @@
"legit": "Looks legit",
"select": "Select a message.",
"progress": "{{done}}/{{total}} reviewed — you can submit any time",
- "submit": "Submit triage"
+ "submit": "Submit triage",
+ "choose_set": "Choose an inbox",
+ "channel": {
+ "whatsapp": "WhatsApp message",
+ "sms": "SMS"
+ }
},
"readiness": {
"title": "Readiness",
@@ -736,5 +741,15 @@
},
"cohort_note": "Cohort of {{people}} trainees. Weights: report rate 40%, did not click 20%, principle resistance 20%, Inbox Triage 20%; missing parts are left out.",
"latest_campaign": "latest campaign"
+ },
+ "remediation": {
+ "why": "Why",
+ "instructor_note": "Instructor note",
+ "lab_fail": "You scored {{score}}% on '{{title}}', which tested {{principle}}. This exercise gives you focused practice.",
+ "live_clicked": "In a live phishing simulation you clicked the link in a message that used {{principle}}. This exercise helps you recognise it next time.",
+ "live_submitted": "In a live phishing simulation you submitted data to a page reached through a message that used {{principle}}. This exercise helps you recognise it next time.",
+ "live_complied": "In a live phishing simulation you agreed to a request that used {{principle}}. This exercise helps you recognise it next time.",
+ "live_disclosed": "In a live phishing simulation you shared a secret in reply to a message that used {{principle}}. This exercise helps you recognise it next time.",
+ "retest": "Scheduled retest for {{principle}} — a different exercise to confirm the lesson stuck."
}
}
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index 74019ee..2f43a51 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -675,7 +675,12 @@
"legit": "Tampak sah",
"select": "Pilih sebuah pesan.",
"progress": "{{done}}/{{total}} ditinjau — Anda bisa mengirim kapan saja",
- "submit": "Kirim hasil triase"
+ "submit": "Kirim hasil triase",
+ "choose_set": "Pilih inbox",
+ "channel": {
+ "whatsapp": "Pesan WhatsApp",
+ "sms": "SMS"
+ }
},
"readiness": {
"title": "Ketahanan",
@@ -736,5 +741,15 @@
},
"cohort_note": "Kohort {{people}} peserta. Bobot: report rate 40%, tidak mengklik 20%, resistansi prinsip 20%, Triase Inbox 20%; komponen tanpa data tidak dihitung.",
"latest_campaign": "kampanye terbaru"
+ },
+ "remediation": {
+ "why": "Alasan",
+ "instructor_note": "Catatan instruktur",
+ "lab_fail": "Skor Anda {{score}}% pada '{{title}}', yang menguji prinsip {{principle}}. Latihan ini memberi Anda latihan terarah.",
+ "live_clicked": "Dalam simulasi phishing, Anda mengklik tautan pada pesan yang memakai prinsip {{principle}}. Latihan ini membantu Anda mengenalinya lain kali.",
+ "live_submitted": "Dalam simulasi phishing, Anda mengirim data ke halaman dari pesan yang memakai prinsip {{principle}}. Latihan ini membantu Anda mengenalinya lain kali.",
+ "live_complied": "Dalam simulasi phishing, Anda menuruti permintaan yang memakai prinsip {{principle}}. Latihan ini membantu Anda mengenalinya lain kali.",
+ "live_disclosed": "Dalam simulasi phishing, Anda membagikan rahasia sebagai balasan pesan yang memakai prinsip {{principle}}. Latihan ini membantu Anda mengenalinya lain kali.",
+ "retest": "Tes ulang terjadwal untuk prinsip {{principle}} — latihan berbeda untuk memastikan pelajarannya melekat."
}
}
diff --git a/frontend/src/pages/MyAssignmentsPage.js b/frontend/src/pages/MyAssignmentsPage.js
index 3f50df1..4b5d6bf 100644
--- a/frontend/src/pages/MyAssignmentsPage.js
+++ b/frontend/src/pages/MyAssignmentsPage.js
@@ -28,6 +28,19 @@ const CONTENT_TYPE_LABELS = {
};
function AssignmentCard({ assignment }) {
+ const { t } = useTranslation();
+ // System (remediation/retest) reasons are rendered from a key so they follow
+ // the UI language; manual instructor notes are shown as written.
+ const note = assignment.reason_key
+ ? t(`remediation.${assignment.reason_key}`, {
+ ...assignment.reason_params,
+ principle: t(`principles.${assignment.reason_params?.principle}`, {
+ defaultValue: assignment.reason_params?.principle,
+ }),
+ defaultValue: assignment.instructions,
+ })
+ : assignment.instructions;
+ const isSystem = assignment.source === 'remediation' || assignment.source === 'retest';
const navigate = useNavigate();
const Icon = CONTENT_TYPE_ICONS[assignment.content_type] || Target;
const result = assignment.result;
@@ -119,11 +132,13 @@ function AssignmentCard({ assignment }) {
{result && ` · Percobaan ke-${result.attempts}`}
- {assignment.instructions && (
+ {note && (
- Catatan Instruktur:
- {assignment.instructions}
+
+ {isSystem ? t('remediation.why') : t('remediation.instructor_note')}:
+
+ {note}
)}
diff --git a/frontend/src/pages/SimulationPlayerPage.js b/frontend/src/pages/SimulationPlayerPage.js
index 405ef28..217764a 100644
--- a/frontend/src/pages/SimulationPlayerPage.js
+++ b/frontend/src/pages/SimulationPlayerPage.js
@@ -328,24 +328,19 @@ export default function SimulationPlayerPage() {
{getContent(currentNode, 'title')}
-
+ {/* Explanations are authored with line breaks and bullet lists. */}
+
{getContent(currentNode, 'explanation')}
navigate('/simulations')}>
- Lihat Semua Riwayat
+ {t('simulation.view_all_simulations')}
+ {/* A fresh attempt is a new scenario run, so scoring stays honest. */}
navigate('/scenarios')}>
- Coba Skenario Lain
+ {t('simulation.try_another')}
-
- {/* A fresh attempt is a new scenario run, so scoring stays honest. */}
- {outcome !== 'success' && (
- navigate('/scenarios')}>
- Try another scenario
-
- )}
)}
diff --git a/frontend/src/pages/TriageInboxPage.js b/frontend/src/pages/TriageInboxPage.js
index 7e812aa..9f5d105 100644
--- a/frontend/src/pages/TriageInboxPage.js
+++ b/frontend/src/pages/TriageInboxPage.js
@@ -1,5 +1,7 @@
import React, { useEffect, useState, useCallback, useRef } from 'react';
-import { Inbox, Flag, ShieldCheck, Mail, AlertTriangle, CheckCircle2, XCircle, Clock } from 'lucide-react';
+import {
+ Inbox, Flag, ShieldCheck, Mail, AlertTriangle, CheckCircle2, XCircle, Clock, MessageCircle, Smartphone,
+} from 'lucide-react';
import { Card } from '../components/ui/card';
import { Button } from '../components/ui/button';
import { Badge } from '../components/ui/badge';
@@ -18,8 +20,38 @@ function Metric({ label, value, hint }) {
);
}
+const CHAT_CHANNELS = ['whatsapp', 'sms'];
+const CHANNEL_ICON = { email_inbox: Mail, whatsapp: MessageCircle, sms: Smartphone };
+
+// A chat message rendered the way it arrives on a phone: contact header, one
+// incoming bubble. Same item, same grading — only the presentation differs.
+function ChatPane({ item, t }) {
+ const initial = (item.from || '?').trim().charAt(0).toUpperCase();
+ return (
+
+
+
{initial}
+
+
{item.from}
+
+ {item.channel === 'sms' ? t('triage.channel.sms') : t('triage.channel.whatsapp')}
+
+
+
+
+
+ );
+}
+
export default function TriageInboxPage() {
const { t, i18n } = useTranslation();
+ const [sets, setSets] = useState([]);
const [set, setSet] = useState(null);
const [marks, setMarks] = useState({});
const [selected, setSelected] = useState(null);
@@ -27,19 +59,29 @@ export default function TriageInboxPage() {
const [elapsed, setElapsed] = useState(0);
const startRef = useRef(Date.now());
+ const openSet = useCallback(async (id) => {
+ try {
+ const full = (await api.get(`/triage/${id}`)).data;
+ setSet(full);
+ setMarks({});
+ setResults(null);
+ setElapsed(0);
+ setSelected(full.items[0]?.id || null);
+ startRef.current = Date.now();
+ } catch { toast.error(t('triage.load_failed')); }
+ }, [t]);
+
const load = useCallback(async () => {
try {
const list = (await api.get('/triage')).data;
if (!list.length) return;
- // Prefer the set in the UI language; sets without a language are English.
+ setSets(list);
+ // Prefer a set in the UI language; sets without a language are English.
const lang = (i18n.language || 'en').slice(0, 2);
const pick = list.find((x) => (x.language || 'en') === lang) || list[0];
- const full = (await api.get(`/triage/${pick.id}`)).data;
- setSet(full);
- setSelected(full.items[0]?.id || null);
- startRef.current = Date.now();
+ await openSet(pick.id);
} catch { toast.error(t('triage.load_failed')); }
- }, [i18n.language, t]);
+ }, [i18n.language, t, openSet]);
useEffect(() => { load(); }, [load]);
useEffect(() => {
@@ -103,7 +145,7 @@ export default function TriageInboxPage() {
);
})}
- window.location.reload()}>{t('triage.run_again')}
+ openSet(set.id)}>{t('triage.run_again')}
);
}
@@ -115,34 +157,53 @@ export default function TriageInboxPage() {
- {elapsed}s
+
+ {sets.length > 1 && (
+ openSet(e.target.value)}
+ className="h-9 rounded-md border border-input bg-background px-2 text-xs font-mono">
+ {sets.map((x) => (
+ {x.title} · {x.item_count}
+ ))}
+
+ )}
+ {elapsed}s
+
{/* Inbox list */}
- {set.items.map((it) => (
+ {set.items.map((it) => {
+ const ChannelIcon = CHANNEL_ICON[it.channel] || Mail;
+ return (
setSelected(it.id)}
className={`w-full text-left p-3 rounded-md border-b border-border/50 hover:bg-muted/40 ${selected === it.id ? 'bg-muted/50' : ''}`}>
- {it.subject}
+
+ {it.subject}
{marks[it.id] === 'flag' && }
{marks[it.id] === 'leave' && }
- {it.from}
+ {it.from}
- ))}
+ );
+ })}
{/* Reading pane */}
{current ? (
<>
-
-
{current.from}
-
{current.subject}
-
- {current.body}
+ {CHAT_CHANNELS.includes(current.channel) ? : (
+ <>
+
+
{current.from}
+
{current.subject}
+
+ {current.body}
+ >
+ )}
mark(current.id, 'flag')}>
{t('triage.report')}