Skip to content

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

Block 18: StreamBus wait_for_input bidirectional mechanism with bus registry

whf315b5d0da002
diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.py
index 97275df43..77fa3a91a 100644
--- a/deeptutor/api/routers/unified_ws.py
+++ b/deeptutor/api/routers/unified_ws.py
@@ -224,6 +224,20 @@ async def unified_websocket(ws: WebSocket) -> None:
await subscribe_turn(turn["id"], after_seq=0)
continue
+ if msg_type == "user_input":
+ turn_id = str(msg.get("turn_id") or "").strip()
+ if not turn_id:
+ await safe_send({"type": "error", "content": "Missing turn_id for user_input."})
+ continue
+ from deeptutor.core.stream_bus import get_bus
+
+ bus = get_bus(turn_id)
+ if bus is None:
+ await safe_send({"type": "error", "content": f"No active bus for turn: {turn_id}"})
+ continue
+ bus.submit_input(str(msg.get("content") or ""))
+ continue
+
await safe_send({"type": "error", "content": f"Unknown type: {msg_type}"})
except WebSocketDisconnect:
diff --git a/deeptutor/core/stream.py b/deeptutor/core/stream.py
index 6569b49a0..75117666f 100644
--- a/deeptutor/core/stream.py
+++ b/deeptutor/core/stream.py
@@ -30,6 +30,8 @@ class StreamEventType(str, Enum):
ERROR = "error"
SESSION = "session"
DONE = "done"
+ WAIT_FOR_INPUT = "wait_for_input"
+ USER_INPUT = "user_input"
@dataclass
diff --git a/deeptutor/core/stream_bus.py b/deeptutor/core/stream_bus.py
index c7e83974a..4ab32dcd8 100644
--- a/deeptutor/core/stream_bus.py
+++ b/deeptutor/core/stream_bus.py
@@ -35,6 +35,7 @@ class StreamBus:
self._subscribers: list[asyncio.Queue[StreamEvent | None]] = []
self._closed = False
self._history: list[StreamEvent] = []
+ self._input_listeners: list[asyncio.Queue[str]] = []
async def emit(self, event: StreamEvent) -> None:
"""Push *event* to every active subscriber."""
@@ -253,9 +254,58 @@ class StreamBus:
)
)
+ async def wait_for_input(
+ self,
+ prompt: str,
+ source: str = "",
+ stage: str = "",
+ ) -> str:
+ """Pause capability execution and wait for user input from the frontend."""
+ await self.emit(
+ StreamEvent(
+ type=StreamEventType.WAIT_FOR_INPUT,
+ source=source,
+ stage=stage,
+ content=prompt,
+ )
+ )
+ input_queue: asyncio.Queue[str] = asyncio.Queue()
+ self._input_listeners.append(input_queue)
+ try:
+ return await input_queue.get()
+ finally:
+ if input_queue in self._input_listeners:
+ self._input_listeners.remove(input_queue)
+
+ def submit_input(self, content: str) -> None:
+ """Receive user input from the frontend/WS and deliver to waiters."""
+ for q in self._input_listeners:
+ q.put_nowait(content)
+ self._input_listeners.clear()
+
# ---- consumer adapters ----
@staticmethod
def event_to_json(event: StreamEvent) -> str:
"""Serialize an event to a single-line JSON string (NDJSON)."""
return json.dumps(event.to_dict(), ensure_ascii=False)
+
+
+# ---- per-turn bus registry for user_input routing ----
+
+_bus_registry: dict[str, StreamBus] = {}
+
+
+def register_bus(turn_id: str, bus: StreamBus) -> None:
+ """Register a bus so ``user_input`` WS messages can find it."""
+ _bus_registry[turn_id] = bus
+
+
+def unregister_bus(turn_id: str) -> None:
+ """Remove a bus from the registry."""
+ _bus_registry.pop(turn_id, None)
+
+
+def get_bus(turn_id: str) -> StreamBus | None:
+ """Look up the active bus for *turn_id*."""
+ return _bus_registry.get(turn_id)
diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.py
index 7d877df59..35450f5b0 100644
--- a/deeptutor/runtime/orchestrator.py
+++ b/deeptutor/runtime/orchestrator.py
@@ -15,7 +15,7 @@ import uuid
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream import StreamEvent, StreamEventType
-from deeptutor.core.stream_bus import StreamBus
+from deeptutor.core.stream_bus import StreamBus, register_bus, unregister_bus
from deeptutor.events.event_bus import Event, EventType, get_event_bus
from deeptutor.runtime.registry.capability_registry import get_capability_registry
from deeptutor.runtime.registry.tool_registry import get_tool_registry
@@ -90,6 +90,9 @@ class ChatOrchestrator:
)
bus = StreamBus()
+ _turn_id = str(context.metadata.get("turn_id") or "")
+ if _turn_id:
+ register_bus(_turn_id, bus)
async def _run() -> None:
try:
@@ -100,6 +103,8 @@ class ChatOrchestrator:
finally:
await bus.emit(StreamEvent(type=StreamEventType.DONE, source=cap_name))
await bus.close()
+ if _turn_id:
+ unregister_bus(_turn_id)
stream = bus.subscribe()
task = asyncio.create_task(_run())
diff --git a/web/app/(workspace)/learning/[bookId]/page.tsx b/web/app/(workspace)/learning/[bookId]/page.tsx
index b241b23c8..5165ddb58 100644
--- a/web/app/(workspace)/learning/[bookId]/page.tsx
+++ b/web/app/(workspace)/learning/[bookId]/page.tsx
@@ -13,6 +13,7 @@ interface StreamEvent {
stage: string;
content: string;
metadata: Record<string, unknown>;
+ turn_id?: string;
}
interface StageProgress {
@@ -60,6 +61,10 @@ export default function LearningBookPage() {
const [modules, setModules] = useState<ModuleData[]>([]);
const [masteryLevels, setMasteryLevels] = useState<Record<string, number>>({});
const [currentModuleId, setCurrentModuleId] = useState<string>("");
+ const [waitingForInput, setWaitingForInput] = useState(false);
+ const [inputPrompt, setInputPrompt] = useState("");
+ const [userInput, setUserInput] = useState("");
+ const currentTurnRef = useRef<string>("");
const fetchProgress = useCallback(() => {
fetch(apiUrl(`/api/v1/learning/progress/${params.bookId}`), { credentials: "include" })
@@ -104,6 +109,16 @@ export default function LearningBookPage() {
}, [params.bookId]);
const handleStreamEvent = (evt: StreamEvent) => {
+ if (evt.type === "session") {
+ const tid = (evt.metadata?.turn_id as string) || evt.turn_id || "";
+ if (tid) currentTurnRef.current = tid;
+ return;
+ }
+ if (evt.type === "wait_for_input") {
+ setWaitingForInput(true);
+ setInputPrompt(evt.content || "Please enter your answer");
+ return;
+ }
if (evt.type === "stage_start") {
currentStageRef.current = evt.stage;
setCurrentStage(evt.stage);
@@ -252,8 +267,36 @@ export default function LearningBookPage() {
{(stages.find(s => s.status === "active") || stages.find(s => s.status === "completed" && s.content))?.content}
</div>
) : (
- <div className="flex items-center justify-center h-full text-[var(--muted-foreground)]">
- {connecting ? <Loader2 className="w-8 h-8 animate-spin" /> : t("guidedLearning.ready")}
+ !waitingForInput && (
+ <div className="flex items-center justify-center h-full text-[var(--muted-foreground)]">
+ {connecting ? <Loader2 className="w-8 h-8 animate-spin" /> : t("guidedLearning.ready")}
+ </div>
+ )
+ )}
+ {waitingForInput && (
+ <div className="mt-4 p-4 border border-[var(--border)] rounded-lg">
+ <p className="mb-2 text-sm text-[var(--foreground)]">{inputPrompt}</p>
+ <textarea
+ value={userInput}
+ onChange={(e) => setUserInput(e.target.value)}
+ className="w-full p-2 border border-[var(--border)] rounded bg-[var(--background)] text-[var(--foreground)] resize-y min-h-[80px]"
+ placeholder={t("guidedLearning.inputPlaceholder", "Type your answer...")}
+ />
+ <button
+ onClick={() => {
+ if (!currentTurnRef.current) return;
+ wsRef.current?.send(JSON.stringify({
+ type: "user_input",
+ turn_id: currentTurnRef.current,
+ content: userInput,
+ }));
+ setWaitingForInput(false);
+ setUserInput("");
+ }}
+ className="mt-2 px-4 py-2 rounded bg-[var(--primary)] text-[var(--primary-foreground)] text-sm hover:opacity-90"
+ >
+ {t("guidedLearning.submit", "Submit")}
+ </button>
</div>
)}
</div>