Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat: /whisper dual-seat page and capability-complete forwarding (#921)

alanguan73e82cdc564185
diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.py
index 710fe5c30..cdcd9a571 100644
--- a/deeptutor/runtime/orchestrator.py
+++ b/deeptutor/runtime/orchestrator.py
@@ -23,6 +23,34 @@ from deeptutor.runtime.registry.tool_registry import get_tool_registry
logger = logging.getLogger(__name__)
+def completion_event_fields(context: UnifiedContext, cap_name: str) -> tuple[str, dict[str, Any]]:
+ """Build CAPABILITY_COMPLETE ``agent_output`` + metadata.
+
+ Capabilities may stash a body on ``context.metadata["agent_output"]`` and
+ publishable extras under ``context.metadata["event_metadata"]``.
+ ``capability``, ``session_id`` and ``turn_id`` always win so consumers can
+ rely on those keys.
+
+ Only that explicit sub-dict is forwarded, never ``context.metadata`` whole.
+ Turn metadata is a scratchpad, not a wire format: it holds live callables
+ (``wait_for_user_reply``), the user's ask_user answers, and whatever else a
+ capability parked there mid-turn. Publishing it to the global EventBus —
+ whose subscribers include the Partner channels — would leak turn internals
+ to every listener and hand JSON-serialising consumers objects they cannot
+ encode. A capability that wants a value on the bus says so.
+ """
+ meta = context.metadata or {}
+ agent_output = str(meta.get("agent_output") or "")
+ published = meta.get("event_metadata")
+ extras = dict(published) if isinstance(published, dict) else {}
+ return agent_output, {
+ **extras,
+ "capability": cap_name,
+ "session_id": context.session_id,
+ "turn_id": str(meta.get("turn_id") or ""),
+ }
+
+
class ChatOrchestrator:
"""
Routes a ``UnifiedContext`` to the correct capability, manages
@@ -130,17 +158,14 @@ class ChatOrchestrator:
"""Publish CAPABILITY_COMPLETE to the global EventBus."""
try:
bus = get_event_bus()
+ agent_output, metadata = completion_event_fields(context, cap_name)
await bus.publish(
Event(
type=EventType.CAPABILITY_COMPLETE,
task_id=str(context.metadata.get("turn_id") or context.session_id),
user_input=context.user_message,
- agent_output="",
- metadata={
- "capability": cap_name,
- "session_id": context.session_id,
- "turn_id": str(context.metadata.get("turn_id", "")),
- },
+ agent_output=agent_output,
+ metadata=metadata,
)
)
except Exception:
diff --git a/tests/runtime/test_orchestrator.py b/tests/runtime/test_orchestrator.py
index 687820241..3f3de6537 100644
--- a/tests/runtime/test_orchestrator.py
+++ b/tests/runtime/test_orchestrator.py
@@ -254,3 +254,86 @@ class TestOrchestratorHelpers:
orch = _make_orchestrator()
schemas = orch.get_tool_schemas()
assert isinstance(schemas, list)
+
+
+class TestCompletionEventFields:
+ def test_reads_agent_output_and_declared_event_metadata(self) -> None:
+ from deeptutor.runtime.orchestrator import completion_event_fields
+
+ ctx = UnifiedContext(
+ user_message="hi",
+ session_id="sess-1",
+ metadata={
+ "agent_output": "## Debrief\nNice work.",
+ "turn_id": "turn-9",
+ "event_metadata": {"practice_trace": "keep-me"},
+ },
+ )
+ output, meta = completion_event_fields(ctx, "echo")
+ assert output == "## Debrief\nNice work."
+ assert meta["capability"] == "echo"
+ assert meta["session_id"] == "sess-1"
+ assert meta["turn_id"] == "turn-9"
+ assert meta["practice_trace"] == "keep-me"
+
+ def test_turn_scratchpad_is_not_published(self) -> None:
+ """Only the declared sub-dict reaches the bus.
+
+ Turn metadata holds live callables and the user's own answers; the
+ EventBus fans out to the Partner channels, and a JSON-serialising
+ subscriber cannot encode a function anyway.
+ """
+ from deeptutor.runtime.orchestrator import completion_event_fields
+
+ ctx = UnifiedContext(
+ user_message="hi",
+ session_id="sess-1",
+ metadata={
+ "wait_for_user_reply": lambda: None,
+ "ask_user_answers": [{"questionId": "q1", "text": "private"}],
+ "event_metadata": {"room_id": "room-7"},
+ },
+ )
+ _, meta = completion_event_fields(ctx, "whisper")
+ assert meta["room_id"] == "room-7"
+ assert "wait_for_user_reply" not in meta
+ assert "ask_user_answers" not in meta
+
+ def test_capability_and_ids_cannot_be_spoofed(self) -> None:
+ from deeptutor.runtime.orchestrator import completion_event_fields
+
+ ctx = UnifiedContext(
+ user_message="hi",
+ session_id="real-session",
+ metadata={
+ "turn_id": "t1",
+ "event_metadata": {
+ "capability": "spoofed",
+ "session_id": "spoofed-session",
+ "turn_id": "spoofed-turn",
+ },
+ },
+ )
+ _, meta = completion_event_fields(ctx, "echo")
+ assert meta["capability"] == "echo"
+ assert meta["session_id"] == "real-session"
+ assert meta["turn_id"] == "t1"
+
+ def test_non_dict_event_metadata_is_ignored(self) -> None:
+ from deeptutor.runtime.orchestrator import completion_event_fields
+
+ ctx = UnifiedContext(
+ user_message="hi",
+ session_id="s",
+ metadata={"event_metadata": "not-a-dict"},
+ )
+ _, meta = completion_event_fields(ctx, "chat")
+ assert meta == {"capability": "chat", "session_id": "s", "turn_id": ""}
+
+ def test_empty_agent_output_when_unset(self) -> None:
+ from deeptutor.runtime.orchestrator import completion_event_fields
+
+ ctx = UnifiedContext(user_message="hi", session_id="s", metadata={})
+ output, meta = completion_event_fields(ctx, "chat")
+ assert output == ""
+ assert "agent_output" not in meta
diff --git a/web/app/(workspace)/whisper/page.tsx b/web/app/(workspace)/whisper/page.tsx
new file mode 100644
index 000000000..a59a73e59
--- /dev/null
+++ b/web/app/(workspace)/whisper/page.tsx
@@ -0,0 +1,383 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Ear, Loader2 } from "lucide-react";
+import WhisperComposer from "@/components/whisper/WhisperComposer";
+import WhisperMessageList from "@/components/whisper/WhisperMessageList";
+import WhisperRoomChip from "@/components/whisper/WhisperRoomChip";
+import {
+ UnifiedWSClient,
+ type StartTurnMessage,
+ type StreamEvent,
+} from "@/lib/unified-ws";
+import {
+ filterMessagesForSeat,
+ looksLikeCrisisRedirect,
+ looksLikeTraineeCrisisSummary,
+ parseRoomIdFromContent,
+ type WhisperMessage,
+ type WhisperSeat,
+} from "@/lib/whisper-transcript";
+
+function newMessageId(): string {
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
+ return crypto.randomUUID();
+ }
+ return `msg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+}
+
+function looksLikeRoomEnded(text: string): boolean {
+ const t = (text || "").toLowerCase();
+ return (
+ t.includes("whisper room has ended") ||
+ t.includes("房间已结束") ||
+ t.includes("room has ended")
+ );
+}
+
+export default function WhisperPage() {
+ const [seat, setSeat] = useState<WhisperSeat>("visitor");
+ const [roomId, setRoomId] = useState<string | null>(null);
+ const [messages, setMessages] = useState<WhisperMessage[]>([]);
+ const [busy, setBusy] = useState(false);
+ const [crisisHit, setCrisisHit] = useState(false);
+ const [roomClosed, setRoomClosed] = useState(false);
+ const [draft, setDraft] = useState("");
+ const [dtSessionId, setDtSessionId] = useState<string | null>(null);
+ const [connected, setConnected] = useState(false);
+ const [everConnected, setEverConnected] = useState(false);
+
+ const clientRef = useRef<UnifiedWSClient | null>(null);
+ const seatRef = useRef<WhisperSeat>(seat);
+ const roomIdRef = useRef<string | null>(roomId);
+ const sessionBySeatRef = useRef<Record<WhisperSeat, string | null>>({
+ visitor: null,
+ trainee: null,
+ });
+ const retryTimersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());
+ const scrollerRef = useRef<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ seatRef.current = seat;
+ }, [seat]);
+
+ useEffect(() => {
+ roomIdRef.current = roomId;
+ }, [roomId]);
+
+ const handleEvent = useCallback((event: StreamEvent) => {
+ if (event.type === "session" || event.type === "session_meta") {
+ const metadata = (event.metadata || {}) as Record<string, unknown>;
+ const sessionId =
+ typeof metadata.session_id === "string"
+ ? metadata.session_id
+ : typeof event.session_id === "string"
+ ? event.session_id
+ : "";
+ if (sessionId) {
+ sessionBySeatRef.current[seatRef.current] = sessionId;
+ setDtSessionId(sessionId);
+ }
+ return;
+ }
+
+ if (event.type === "done") {
+ setBusy(false);
+ setConnected(true);
+ return;
+ }
+
+ if (event.type === "error") {
+ const text = event.content || "Something went wrong.";
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: newMessageId(),
+ role: "system",
+ text,
+ stage: event.stage,
+ source: event.source,
+ },
+ ]);
+ setBusy(false);
+ return;
+ }
+
+ if (event.type !== "content" || !event.content) return;
+
+ const text = event.content;
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: newMessageId(),
+ role: "assistant",
+ text,
+ stage: event.stage || undefined,
+ source: event.source || undefined,
+ },
+ ]);
+
+ // Visitor first-turn ack streams room_id=…; parse whenever unset so a
+ // mid-flight seat switch still auto-attaches the trainee seat.
+ if (!roomIdRef.current) {
+ const parsed = parseRoomIdFromContent(text);
+ if (parsed) setRoomId(parsed);
+ }
+
+ if (looksLikeCrisisRedirect(text) || looksLikeTraineeCrisisSummary(text)) {
+ setCrisisHit(true);
+ setRoomClosed(true);
+ }
+ if (looksLikeRoomEnded(text)) {
+ setRoomClosed(true);
+ }
+ }, []);
+
+ useEffect(() => {
+ const client = new UnifiedWSClient(handleEvent, () => {
+ setBusy(false);
+ setConnected(false);
+ });
+ clientRef.current = client;
+ setConnected(false);
+ client.connect();
+
+ // Poll readyState until open (UnifiedWSClient has no onOpen hook).
+ const poll = window.setInterval(() => {
+ if (client.connected) {
+ setConnected(true);
+ setEverConnected(true);
+ window.clearInterval(poll);
+ }
+ }, 100);
+ const giveUp = window.setTimeout(() => window.clearInterval(poll), 15_000);
+
+ const retryTimers = retryTimersRef.current;
+ return () => {
+ window.clearInterval(poll);
+ window.clearTimeout(giveUp);
+ retryTimers.forEach((timer) => clearTimeout(timer));
+ retryTimers.clear();
+ client.disconnect();
+ clientRef.current = null;
+ };
+ }, [handleEvent]);
+
+ useEffect(() => {
+ if (scrollerRef.current) {
+ scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;
+ }
+ }, [messages, seat]);
+
+ const visibleMessages = useMemo(
+ () => filterMessagesForSeat(messages, seat),
+ [messages, seat],
+ );
+
+ const traineeNeedsRoom = seat === "trainee" && !roomId;
+ const roomLocked = crisisHit || roomClosed;
+ // Typing stays available during busy / trainee-without-room; only Send locks.
+ const inputDisabled = roomLocked;
+ const sendBlocked = busy || roomLocked || traineeNeedsRoom;
+
+ function sendWithRetry(payload: StartTurnMessage, attempt = 0) {
+ const client = clientRef.current;
+ if (!client) return;
+ if (client.connected) {
+ client.send(payload);
+ setConnected(true);
+ setEverConnected(true);
+ return;
+ }
+ if (attempt >= 10) {
+ setBusy(false);
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: newMessageId(),
+ role: "system",
+ text: "Connection failed. Please try again.",
+ },
+ ]);
+ return;
+ }
+ const timer = setTimeout(() => {
+ retryTimersRef.current.delete(timer);
+ sendWithRetry(payload, attempt + 1);
+ }, 200);
+ retryTimersRef.current.add(timer);
+ }
+
+ function startTurn(content: string, options?: { hideOptimistic?: boolean }) {
+ const text = content.trim();
+ if (!text || sendBlocked) return;
+
+ if (!options?.hideOptimistic) {
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: newMessageId(),
+ role: "user",
+ text,
+ localSeat: seat,
+ },
+ ]);
+ }
+
+ setDraft("");
+ setBusy(true);
+
+ // If the turn never emits done/error (WS drop mid-flight), unlock Send.
+ const busyWatchdog = setTimeout(() => {
+ retryTimersRef.current.delete(busyWatchdog);
+ setBusy(false);
+ }, 120_000);
+ retryTimersRef.current.add(busyWatchdog);
+
+ const capability =
+ seat === "visitor" ? "whisper_visitor" : "whisper_trainee";
+ const payload: StartTurnMessage = {
+ type: "start_turn",
+ content: text,
+ capability,
+ session_id: sessionBySeatRef.current[seat] ?? undefined,
+ config: roomId ? { room_id: roomId } : {},
+ };
+ sendWithRetry(payload);
+ }
+
+ function handleSend() {
+ startTurn(draft);
+ }
+
+ function handleEnd() {
+ if (seat !== "trainee" || !roomId || sendBlocked) return;
+ // psych-academy is_end_command: 结束 | 复盘 | stop | debrief
+ startTurn("结束");
+ }
+
+ function switchSeat(next: WhisperSeat) {
+ setSeat(next);
+ setDtSessionId(sessionBySeatRef.current[next]);
+ }
+
+ function handleNewRoom() {
+ retryTimersRef.current.forEach((timer) => clearTimeout(timer));
+ retryTimersRef.current.clear();
+ sessionBySeatRef.current = { visitor: null, trainee: null };
+ setMessages([]);
+ setDraft("");
+ setBusy(false);
+ setCrisisHit(false);
+ setRoomClosed(false);
+ setRoomId(null);
+ setDtSessionId(null);
+ setSeat("visitor");
+ }
+
+ const canNewRoom = Boolean(roomId || roomClosed || crisisHit);
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <header className="flex flex-wrap items-center justify-between gap-3 border-b border-[var(--border)] px-4 py-3">
+ <div className="min-w-0">
+ <div className="flex items-center gap-2 text-sm font-medium text-[var(--foreground)]">
+ <Ear className="h-4 w-4 text-[var(--primary)]" aria-hidden />
+ Whisper
+ </div>
+ <p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">
+ Dual-seat supervision · seat switch (not split-screen)
+ {dtSessionId ? (
+ <span className="ml-2 font-mono opacity-70">
+ session {dtSessionId.slice(0, 8)}…
+ </span>
+ ) : null}
+ </p>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ {roomId ? <WhisperRoomChip roomId={roomId} /> : null}
+ <button
+ type="button"
+ onClick={handleNewRoom}
+ disabled={!canNewRoom}
+ className="rounded-lg border border-[var(--border)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--ring)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ New room
+ </button>
+ <div
+ role="tablist"
+ aria-label="Seat"
+ className="inline-flex rounded-xl border border-[var(--border)] bg-[var(--background)] p-0.5"
+ >
+ {(["visitor", "trainee"] as const).map((value) => {
+ const active = seat === value;
+ return (
+ <button
+ key={value}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ onClick={() => switchSeat(value)}
+ className={`rounded-[10px] px-3 py-1.5 text-xs font-medium capitalize transition-colors ${
+ active
+ ? "bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {value}
+ </button>
+ );
+ })}
+ </div>
+ {!connected && (
+ <span className="inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ {everConnected ? "Reconnecting…" : "Connecting…"}
+ </span>
+ )}
+ </div>
+ </header>
+
+ {(crisisHit || roomClosed) && (
+ <div
+ role="status"
+ className="border-b border-amber-500/30 bg-amber-500/10 px-4 py-2 text-xs text-amber-800 dark:text-amber-200"
+ >
+ {crisisHit
+ ? "Crisis redirect detected. Sending is disabled for this room."
+ : "This whisper room has ended. Sending is disabled."}{" "}
+ You can still copy the room id.
+ </div>
+ )}
+
+ {seat === "trainee" && !roomId && (
+ <div
+ role="status"
+ className="border-b border-[var(--border)] bg-[var(--background)] px-4 py-2 text-xs text-[var(--muted-foreground)]"
+ >
+ Open the room as Visitor first.
+ </div>
+ )}
+
+ <div ref={scrollerRef} className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
+ <div className="mx-auto w-full max-w-3xl">
+ <WhisperMessageList messages={visibleMessages} seat={seat} />
+ </div>
+ </div>
+
+ <WhisperComposer
+ seat={seat}
+ draft={draft}
+ busy={busy}
+ sendDisabled={sendBlocked}
+ inputDisabled={inputDisabled}
+ showEndButton={seat === "trainee"}
+ endDisabled={sendBlocked || !roomId}
+ onDraftChange={setDraft}
+ onSend={handleSend}
+ onEnd={handleEnd}
+ />
+ </div>
+ );
+}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index 5ef3c627d..294a77a1c 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -11,6 +11,7 @@ import {
Bot,
Brain,
ChevronDown,
+ Ear,
Github,
HeartHandshake,
House,
@@ -74,6 +75,13 @@ const PRIMARY_NAV: NavEntry[] = [
tooltipKey: "Co-Writer tooltip",
requires: "llm",
},
+ {
+ href: "/whisper",
+ label: "Whisper",
+ icon: Ear,
+ tooltipKey: "Whisper tooltip",
+ requires: "llm",
+ },
{
href: "/book",
label: "Book",
diff --git a/web/components/whisper/WhisperComposer.tsx b/web/components/whisper/WhisperComposer.tsx
new file mode 100644
index 000000000..999efd5a2
--- /dev/null
+++ b/web/components/whisper/WhisperComposer.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import type { KeyboardEvent } from "react";
+import { Loader2, Send } from "lucide-react";
+import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";
+import { useImeComposing } from "@/lib/use-ime-composing";
+import type { WhisperSeat } from "@/lib/whisper-transcript";
+
+type WhisperComposerProps = {
+ seat: WhisperSeat;
+ draft: string;
+ busy: boolean;
+ /** Blocks Send / Enter submit (busy, crisis, closed, trainee without room). */
+ sendDisabled: boolean;
+ /** Only lock the textarea for terminal room states — never for busy. */
+ inputDisabled: boolean;
+ showEndButton: boolean;
+ endDisabled: boolean;
+ onDraftChange: (value: string) => void;
+ onSend: () => void;
+ onEnd: () => void;
+};
+
+export default function WhisperComposer({
+ seat,
+ draft,
+ busy,
+ sendDisabled,
+ inputDisabled,
+ showEndButton,
+ endDisabled,
+ onDraftChange,
+ onSend,
+ onEnd,
+}: WhisperComposerProps) {
+ const { isComposingRef, onCompositionStart, onCompositionEnd } =
+ useImeComposing();
+
+ function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
+ if (!shouldSubmitOnEnter(event, isComposingRef.current)) return;
+ event.preventDefault();
+ if (!sendDisabled) onSend();
+ }
+
+ return (
+ <div className="border-t border-[var(--border)] bg-[var(--card)]/40 px-4 py-3 backdrop-blur">
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-2">
+ <div className="flex items-end gap-2">
+ <textarea
+ value={draft}
+ onChange={(e) => onDraftChange(e.target.value)}
+ onKeyDown={handleKeyDown}
+ onCompositionStart={onCompositionStart}
+ onCompositionEnd={onCompositionEnd}
+ disabled={inputDisabled}
+ rows={2}
+ placeholder={
+ seat === "visitor"
+ ? "Message as visitor…"
+ : "Counselor line as trainee…"
+ }
+ className="min-h-[2.75rem] flex-1 resize-none rounded-xl border border-[var(--border)] bg-[var(--background)] px-3.5 py-2.5 text-sm outline-none transition-colors focus:border-[var(--ring)] disabled:cursor-not-allowed disabled:opacity-60"
+ aria-label={seat === "visitor" ? "Visitor message" : "Trainee message"}
+ />
+ <button
+ type="button"
+ onClick={onSend}
+ disabled={sendDisabled || !draft.trim()}
+ className="inline-flex h-10 items-center gap-1.5 rounded-xl bg-[var(--primary)] px-3.5 text-sm font-medium text-[var(--primary-foreground)] transition-opacity disabled:cursor-not-allowed disabled:opacity-50"
+ aria-label="Send"
+ >
+ {busy ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Send className="h-4 w-4" />
+ )}
+ Send
+ </button>
+ </div>
+ {busy && (
+ <p className="text-[11px] text-[var(--muted-foreground)]">Waiting…</p>
+ )}
+ {showEndButton && (
+ <div className="flex justify-end">
+ <button
+ type="button"
+ onClick={onEnd}
+ disabled={endDisabled}
+ className="rounded-lg border border-[var(--border)] px-3 py-1.5 text-xs font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--ring)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ 结束
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/whisper/WhisperMessageList.tsx b/web/components/whisper/WhisperMessageList.tsx
new file mode 100644
index 000000000..f670576fc
--- /dev/null
+++ b/web/components/whisper/WhisperMessageList.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { Lock } from "lucide-react";
+import MarkdownRenderer from "@/components/common/MarkdownRenderer";
+import type { WhisperMessage, WhisperSeat } from "@/lib/whisper-transcript";
+
+type WhisperMessageListProps = {
+ messages: WhisperMessage[];
+ seat: WhisperSeat;
+};
+
+function bubbleClass(msg: WhisperMessage): string {
+ if (msg.role === "user") {
+ return "ml-auto bg-[var(--primary)] text-[var(--primary-foreground)]";
+ }
+ if (msg.stage === "whisper") {
+ return "mr-auto border border-amber-500/40 bg-amber-500/10 text-[var(--foreground)]";
+ }
+ if (msg.stage === "debrief") {
+ return "mr-auto border border-violet-500/40 bg-violet-500/10 text-[var(--foreground)]";
+ }
+ if (msg.role === "system") {
+ return "mx-auto border border-dashed border-[var(--border)] bg-[var(--background)]/60 text-[var(--muted-foreground)]";
+ }
+ return "mr-auto border border-[var(--border)] bg-[var(--card)] text-[var(--foreground)]";
+}
+
+function showSource(source?: string): boolean {
+ if (!source) return false;
+ return source !== "whisper_visitor" && source !== "whisper_trainee";
+}
+
+function useMarkdown(msg: WhisperMessage): boolean {
+ return msg.role !== "user" && msg.role !== "system";
+}
+
+export default function WhisperMessageList({
+ messages,
+ seat,
+}: WhisperMessageListProps) {
+ if (messages.length === 0) {
+ return (
+ <div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--background)]/50 p-4 text-xs leading-6 text-[var(--muted-foreground)]">
+ <p className="mb-2 font-medium text-[var(--foreground)]">
+ Dual-seat whisper — 3 steps
+ </p>
+ <ol className="list-decimal space-y-1.5 pl-4">
+ <li>
+ <span className="font-medium text-[var(--foreground)]">Visitor:</span>{" "}
+ send the first message → you get a{" "}
+ <code className="rounded bg-[var(--muted)] px-1">room_id</code>.
+ </li>
+ <li>
+ <span className="font-medium text-[var(--foreground)]">Trainee:</span>{" "}
+ switch seats and send counselor lines. Private notes show with a lock.
+ </li>
+ <li>
+ <span className="font-medium text-[var(--foreground)]">结束:</span>{" "}
+ on Trainee, end the room for a debrief.
+ </li>
+ </ol>
+ <p className="mt-3 opacity-80">
+ {seat === "visitor"
+ ? "You are on Visitor — start with step 1."
+ : "You are on Trainee — complete step 1 as Visitor first if there is no room yet."}
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-3">
+ {messages.map((msg) => {
+ const isWhisper = msg.stage === "whisper";
+ const metaStage =
+ msg.stage && msg.stage !== "whisper" ? msg.stage : null;
+ const metaSource = showSource(msg.source) ? msg.source : null;
+ const showMeta =
+ isWhisper || metaStage || metaSource || Boolean(msg.localSeat);
+
+ return (
+ <div
+ key={msg.id}
+ className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}
+ >
+ <div
+ className={`max-w-[85%] rounded-2xl px-3.5 py-2.5 text-sm leading-6 ${bubbleClass(msg)} ${
+ useMarkdown(msg) ? "" : "whitespace-pre-wrap"
+ }`}
+ >
+ {showMeta && (
+ <div className="mb-1.5 flex flex-wrap items-center gap-1.5 text-[10px] uppercase tracking-wide opacity-70">
+ {isWhisper && (
+ <span className="inline-flex items-center gap-1 font-semibold text-amber-600 dark:text-amber-400">
+ <Lock className="h-3 w-3" aria-hidden />
+ whisper
+ </span>
+ )}
+ {metaStage && <span>{metaStage}</span>}
+ {metaSource && <span>· {metaSource}</span>}
+ {msg.localSeat && <span>· you ({msg.localSeat})</span>}
+ </div>
+ )}
+ {useMarkdown(msg) ? (
+ <MarkdownRenderer
+ content={msg.text}
+ variant="compact"
+ className="text-sm leading-6"
+ />
+ ) : (
+ msg.text
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/web/components/whisper/WhisperRoomChip.tsx b/web/components/whisper/WhisperRoomChip.tsx
new file mode 100644
index 000000000..681803e50
--- /dev/null
+++ b/web/components/whisper/WhisperRoomChip.tsx
@@ -0,0 +1,44 @@
+"use client";
+
+import { useState } from "react";
+import { Check, Copy } from "lucide-react";
+
+type WhisperRoomChipProps = {
+ roomId: string;
+};
+
+export default function WhisperRoomChip({ roomId }: WhisperRoomChipProps) {
+ const [copied, setCopied] = useState(false);
+
+ async function copyRoomId() {
+ try {
+ await navigator.clipboard.writeText(roomId);
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1500);
+ } catch {
+ // Clipboard may be denied; leave chip usable without toast noise.
+ }
+ }
+
+ return (
+ <div className="flex items-center gap-2 rounded-full border border-[var(--border)] bg-[var(--background)] px-3 py-1 text-xs text-[var(--muted-foreground)]">
+ <span className="font-medium text-[var(--foreground)]">room</span>
+ <code className="max-w-[12rem] truncate font-mono text-[11px] text-[var(--foreground)]">
+ {roomId}
+ </code>
+ <button
+ type="button"
+ onClick={() => void copyRoomId()}
+ className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--card)] hover:text-[var(--foreground)]"
+ aria-label="Copy room id"
+ >
+ {copied ? (
+ <Check className="h-3.5 w-3.5 text-emerald-500" />
+ ) : (
+ <Copy className="h-3.5 w-3.5" />
+ )}
+ <span>{copied ? "Copied" : "Copy"}</span>
+ </button>
+ </div>
+ );
+}
diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.ts
index 6ac9b230e..87b0e309f 100644
--- a/web/lib/unified-ws.ts
+++ b/web/lib/unified-ws.ts
@@ -239,8 +239,14 @@ export class UnifiedWSClient {
}
};
- this.ws.onerror = (err) => {
- console.error("WS error:", err);
+ this.ws.onerror = () => {
+ // Browser Event objects serialize as `{}` and Next.js turns
+ // ``console.error`` into a blocking dev overlay, so this must not be an
+ // error-level log. ``onclose`` carries the actionable signal (reconnect
+ // vs. intentional disconnect); keep a debug breadcrumb so a socket that
+ // fails without ever closing is still visible.
+ if (this.intentionalClose) return;
+ console.debug("[unified-ws] socket error; awaiting close for the reason");
};
}
diff --git a/web/lib/whisper-transcript.ts b/web/lib/whisper-transcript.ts
new file mode 100644
index 000000000..683c0621c
--- /dev/null
+++ b/web/lib/whisper-transcript.ts
@@ -0,0 +1,55 @@
+export type WhisperSeat = "visitor" | "trainee";
+
+export type WhisperMessage = {
+ id: string;
+ role: "user" | "assistant" | "system";
+ text: string;
+ stage?: string;
+ source?: string;
+ localSeat?: WhisperSeat; // optimistic user bubble
+};
+
+export function parseRoomIdFromContent(text: string): string | null {
+ const m = /room_id=([A-Za-z0-9_-]+)/.exec(text || "");
+ return m ? m[1] : null;
+}
+
+export function filterMessagesForSeat(
+ messages: WhisperMessage[],
+ seat: WhisperSeat,
+): WhisperMessage[] {
+ if (seat === "trainee") return messages;
+ return messages.filter((msg) => {
+ if (msg.stage === "whisper") return false;
+ if (msg.source === "whisper_trainee" && msg.stage === "debrief") return false;
+ return true;
+ });
+}
+
+/**
+ * Detect visitor-facing crisis redirect copy from psych_academy/safety/redirect.py
+ * (_EN / _ZH). Match distinctive substrings from the real templates.
+ */
+export function looksLikeCrisisRedirect(text: string): boolean {
+ const t = (text || "").toLowerCase();
+ return (
+ t.includes("cannot provide crisis intervention") ||
+ t.includes("i am concerned you may be in danger") ||
+ t.includes("不能做危机干预") ||
+ t.includes("可能处于危险中") ||
+ // optional helpline_text appended by render_redirect
+ t.includes("转介") ||
+ t.includes("热线")
+ );
+}
+
+/**
+ * Detect trainee-facing crisis summary from whisper_trainee._CRISIS_SUMMARY.
+ */
+export function looksLikeTraineeCrisisSummary(text: string): boolean {
+ const t = (text || "").toLowerCase();
+ return (
+ t.includes("closed for crisis referral") ||
+ t.includes("no further counseling or whispers")
+ );
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 9df882e82..07b6e7b1b 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -1733,6 +1733,8 @@
"Ask about this page...": "Ask about this page...",
"Home tooltip": "Multi-tool AI chat and search.",
"Co-Writer tooltip": "AI-powered document editor.",
+ "Whisper": "Whisper",
+ "Whisper tooltip": "Dual-seat whisper room for visitor and trainee.",
"Book tooltip": "Create AI-powered books.",
"Knowledge tooltip": "Manage learning personas.",
"Space tooltip": "Your personal learning library.",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index dacfdf257..ae6fe7f00 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -1852,6 +1852,8 @@
"Ask about this page...": "询问本页内容…",
"Home tooltip": "多工具 AI 对话与搜索。",
"Co-Writer tooltip": "AI 驱动的协作文档编辑器。",
+ "Whisper": "密语",
+ "Whisper tooltip": "访客与学员双席位密语房间。",
"Book tooltip": "生成交互式 AI 书籍。",
"Knowledge tooltip": "管理文档与教学人设。",
"Space tooltip": "你的个人学习空间。",
diff --git a/web/tests/whisper-transcript.test.ts b/web/tests/whisper-transcript.test.ts
new file mode 100644
index 000000000..571c4e910
--- /dev/null
+++ b/web/tests/whisper-transcript.test.ts
@@ -0,0 +1,64 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ filterMessagesForSeat,
+ looksLikeCrisisRedirect,
+ looksLikeTraineeCrisisSummary,
+ parseRoomIdFromContent,
+ type WhisperMessage,
+} from "../lib/whisper-transcript";
+
+test("parseRoomIdFromContent extracts id from room_id=abc-123", () => {
+ assert.equal(parseRoomIdFromContent("join room_id=abc-123 please"), "abc-123");
+ assert.equal(parseRoomIdFromContent("no room here"), null);
+});
+
+test("visitor seat drops stage=whisper", () => {
+ const messages: WhisperMessage[] = [
+ { id: "1", role: "assistant", text: "hello", stage: "responding" },
+ { id: "2", role: "assistant", text: "secret", stage: "whisper" },
+ ];
+ const filtered = filterMessagesForSeat(messages, "visitor");
+ assert.equal(filtered.length, 1);
+ assert.equal(filtered[0].id, "1");
+});
+
+test("trainee seat keeps whisper", () => {
+ const messages: WhisperMessage[] = [
+ { id: "1", role: "assistant", text: "hello", stage: "responding" },
+ { id: "2", role: "assistant", text: "secret", stage: "whisper" },
+ ];
+ const filtered = filterMessagesForSeat(messages, "trainee");
+ assert.equal(filtered.length, 2);
+});
+
+test("visitor drops source=whisper_trainee + stage=debrief", () => {
+ const messages: WhisperMessage[] = [
+ { id: "1", role: "assistant", text: "ok", stage: "responding" },
+ {
+ id: "2",
+ role: "assistant",
+ text: "debrief notes",
+ source: "whisper_trainee",
+ stage: "debrief",
+ },
+ ];
+ const filtered = filterMessagesForSeat(messages, "visitor");
+ assert.equal(filtered.length, 1);
+ assert.equal(filtered[0].id, "1");
+});
+
+test("looksLikeCrisisRedirect true on real EN redirect snippet", () => {
+ const en =
+ "I am concerned you may be in danger. This system cannot provide crisis intervention. ";
+ assert.equal(looksLikeCrisisRedirect(en), true);
+ assert.equal(looksLikeCrisisRedirect("ordinary counseling reply"), false);
+});
+
+test("looksLikeTraineeCrisisSummary true on real _CRISIS_SUMMARY snippet", () => {
+ const summary =
+ "This room was closed for crisis referral. No further counseling or whispers.";
+ assert.equal(looksLikeTraineeCrisisSummary(summary), true);
+ assert.equal(looksLikeTraineeCrisisSummary("ordinary debrief"), false);
+});