Skip to content

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

minor fixes

Bingxi Zhao (Frank)3b823ae5f7e0
diff --git a/artifacts/deeptutor-poster/deeptutor-technical-poster.html b/artifacts/deeptutor-poster/deeptutor-technical-poster.html
deleted file mode 100644
index 5034e0a12..000000000
--- a/artifacts/deeptutor-poster/deeptutor-technical-poster.html
+++ /dev/null
@@ -1,912 +0,0 @@
-<!doctype html>
-<html lang="zh-CN">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>DeepTutor Technical Poster</title>
- <style>
- :root {
- --ink: #25313b;
- --muted: #687782;
- --line: #dfe8e4;
- --paper: #f9fbf7;
- --panel: rgba(255, 255, 255, 0.78);
- --mint: #d9f0e7;
- --sage: #b7dccd;
- --sky: #d9ecfb;
- --blue: #9bc3e5;
- --rose: #f5ddd8;
- --peach: #f6e6c8;
- --lilac: #e7e1f5;
- --gold: #d5b86e;
- --shadow: 0 24px 70px rgba(59, 82, 92, 0.12);
- }
-
- * {
- box-sizing: border-box;
- }
-
- html,
- body {
- margin: 0;
- width: 1800px;
- min-height: 2600px;
- background: var(--paper);
- color: var(--ink);
- font-family: "Inter", "SF Pro Display", "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
- letter-spacing: 0;
- }
-
- body {
- overflow: hidden;
- }
-
- .poster {
- position: relative;
- width: 1800px;
- height: 2600px;
- padding: 96px 112px 78px;
- background:
- linear-gradient(90deg, rgba(129, 163, 155, 0.11) 1px, transparent 1px),
- linear-gradient(180deg, rgba(129, 163, 155, 0.10) 1px, transparent 1px),
- linear-gradient(155deg, rgba(217, 240, 231, 0.88), rgba(249, 251, 247, 0.96) 38%, rgba(246, 230, 200, 0.42) 70%, rgba(217, 236, 251, 0.58));
- background-size: 56px 56px, 56px 56px, 100% 100%;
- }
-
- .poster::before,
- .poster::after {
- content: "";
- position: absolute;
- left: 112px;
- right: 112px;
- height: 1px;
- background: linear-gradient(90deg, transparent, rgba(66, 88, 92, 0.18), transparent);
- }
-
- .poster::before {
- top: 78px;
- }
-
- .poster::after {
- bottom: 70px;
- }
-
- .hero {
- display: grid;
- grid-template-columns: 1fr 470px;
- gap: 72px;
- align-items: end;
- min-height: 320px;
- margin-bottom: 30px;
- }
-
- .kicker {
- display: inline-flex;
- width: fit-content;
- align-items: center;
- gap: 14px;
- padding: 10px 18px;
- border: 1px solid rgba(37, 49, 59, 0.16);
- border-radius: 999px;
- background: rgba(255, 255, 255, 0.52);
- color: #50646c;
- font-size: 22px;
- line-height: 1;
- font-weight: 650;
- text-transform: uppercase;
- }
-
- .kicker::before {
- content: "";
- width: 10px;
- height: 10px;
- border-radius: 50%;
- background: #6fa890;
- box-shadow: 20px 0 0 #a5c8e4, 40px 0 0 #e6b8af;
- margin-right: 40px;
- }
-
- h1 {
- margin: 34px 0 14px;
- font-size: 136px;
- line-height: 0.9;
- font-weight: 760;
- letter-spacing: 0;
- }
-
- .subtitle {
- margin: 0;
- max-width: 980px;
- color: #42545b;
- font-size: 44px;
- line-height: 1.16;
- font-weight: 520;
- }
-
- .hero-note {
- align-self: stretch;
- display: flex;
- flex-direction: column;
- justify-content: space-between;
- gap: 18px;
- padding: 28px;
- border: 1px solid rgba(37, 49, 59, 0.14);
- border-radius: 28px;
- background: rgba(255, 255, 255, 0.56);
- box-shadow: var(--shadow);
- }
-
- .hero-note .label {
- color: #6a7d83;
- font-size: 20px;
- font-weight: 720;
- text-transform: uppercase;
- }
-
- .hero-note .value {
- color: #26363d;
- font-size: 30px;
- line-height: 1.28;
- font-weight: 680;
- }
-
- .entry-grid {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 10px;
- }
-
- .entry-grid span {
- display: flex;
- align-items: center;
- justify-content: center;
- min-height: 54px;
- border-radius: 18px;
- background: rgba(217, 236, 251, 0.72);
- color: #315062;
- font-size: 22px;
- font-weight: 700;
- }
-
- .spine {
- position: relative;
- padding: 30px 34px 34px;
- margin-bottom: 30px;
- border: 1px solid rgba(37, 49, 59, 0.14);
- border-radius: 34px;
- background: rgba(255, 255, 255, 0.66);
- box-shadow: var(--shadow);
- }
-
- .section-title {
- margin: 0 0 22px;
- color: #2c3a40;
- font-size: 31px;
- line-height: 1.18;
- font-weight: 760;
- }
-
- .section-subtitle {
- margin: -12px 0 24px;
- color: var(--muted);
- font-size: 21px;
- line-height: 1.34;
- font-weight: 520;
- }
-
- .turn-flow {
- display: grid;
- grid-template-columns: 1fr 80px 1.1fr 80px 1fr 80px 1.1fr;
- align-items: stretch;
- gap: 0;
- }
-
- .flow-node {
- min-height: 116px;
- padding: 20px 22px 18px;
- border: 1px solid rgba(37, 49, 59, 0.12);
- border-radius: 26px;
- background: rgba(255, 255, 255, 0.74);
- }
-
- .flow-node strong {
- display: block;
- margin-bottom: 8px;
- color: #26363d;
- font-size: 25px;
- font-weight: 760;
- }
-
- .flow-node span {
- color: #61737a;
- font-size: 18px;
- line-height: 1.32;
- font-weight: 520;
- }
-
- .arrow {
- position: relative;
- min-height: 116px;
- }
-
- .arrow::before {
- content: "";
- position: absolute;
- top: 50%;
- left: 12px;
- right: 14px;
- height: 2px;
- background: rgba(58, 83, 88, 0.32);
- }
-
- .arrow::after {
- content: "";
- position: absolute;
- top: calc(50% - 8px);
- right: 10px;
- width: 16px;
- height: 16px;
- border-top: 2px solid rgba(58, 83, 88, 0.38);
- border-right: 2px solid rgba(58, 83, 88, 0.38);
- transform: rotate(45deg);
- }
-
- .main-grid {
- display: grid;
- grid-template-columns: 390px 1fr 390px;
- gap: 30px;
- align-items: stretch;
- margin-bottom: 28px;
- }
-
- .panel,
- .core-panel,
- .insight,
- .foundation-panel {
- border: 1px solid rgba(37, 49, 59, 0.13);
- background: var(--panel);
- box-shadow: var(--shadow);
- }
-
- .panel {
- min-height: 720px;
- padding: 26px;
- border-radius: 30px;
- }
-
- .eyebrow {
- display: block;
- margin-bottom: 16px;
- color: #70828a;
- font-size: 18px;
- font-weight: 760;
- text-transform: uppercase;
- }
-
- .panel h2,
- .core-panel h2,
- .foundation-panel h2 {
- margin: 0 0 18px;
- color: #26353b;
- font-size: 34px;
- line-height: 1.08;
- font-weight: 760;
- }
-
- .panel p,
- .foundation-panel p {
- margin: 0 0 16px;
- color: #5c7077;
- font-size: 19px;
- line-height: 1.30;
- }
-
- .mini-list {
- display: grid;
- gap: 8px;
- margin-top: 12px;
- }
-
- .mini-item {
- display: grid;
- grid-template-columns: 12px 1fr;
- gap: 14px;
- align-items: start;
- padding: 8px 0;
- border-top: 1px solid rgba(37, 49, 59, 0.09);
- color: #314349;
- font-size: 18px;
- line-height: 1.22;
- font-weight: 610;
- }
-
- .mini-item:first-child {
- border-top: 0;
- }
-
- .dot {
- width: 12px;
- height: 12px;
- margin-top: 6px;
- border-radius: 50%;
- background: #7db097;
- }
-
- .dot.blue {
- background: #84afd0;
- }
-
- .dot.rose {
- background: #ddb0a8;
- }
-
- .dot.gold {
- background: #d0b56e;
- }
-
- .chip-cloud {
- display: flex;
- flex-wrap: wrap;
- gap: 8px;
- margin-top: 12px;
- }
-
- .chip {
- display: inline-flex;
- align-items: center;
- min-height: 34px;
- padding: 7px 12px;
- border-radius: 999px;
- background: rgba(217, 240, 231, 0.74);
- color: #41575e;
- font-size: 16px;
- line-height: 1;
- font-weight: 690;
- }
-
- .chip.blue {
- background: rgba(217, 236, 251, 0.78);
- }
-
- .chip.rose {
- background: rgba(245, 221, 216, 0.82);
- }
-
- .chip.gold {
- background: rgba(246, 230, 200, 0.86);
- }
-
- .core-panel {
- min-height: 720px;
- padding: 28px 32px;
- border-radius: 36px;
- background:
- linear-gradient(180deg, rgba(255, 255, 255, 0.82), rgba(255, 255, 255, 0.62)),
- linear-gradient(135deg, rgba(217, 240, 231, 0.56), rgba(217, 236, 251, 0.48));
- }
-
- .core-caption {
- margin: -6px 0 18px;
- color: #61727a;
- font-size: 22px;
- line-height: 1.34;
- }
-
- .loop-stage {
- position: relative;
- height: 432px;
- margin-top: 16px;
- border-radius: 32px;
- border: 1px solid rgba(37, 49, 59, 0.10);
- background: rgba(249, 251, 247, 0.72);
- overflow: hidden;
- }
-
- .loop-stage svg {
- position: absolute;
- inset: 0;
- width: 100%;
- height: 100%;
- }
-
- .loop-center {
- position: absolute;
- left: 50%;
- top: 50%;
- width: 292px;
- min-height: 172px;
- transform: translate(-50%, -50%);
- display: flex;
- flex-direction: column;
- justify-content: center;
- align-items: center;
- padding: 26px;
- border-radius: 30px;
- background: #ffffff;
- border: 1px solid rgba(37, 49, 59, 0.14);
- box-shadow: 0 18px 40px rgba(55, 75, 82, 0.12);
- text-align: center;
- }
-
- .loop-center strong {
- color: #26353b;
- font-size: 30px;
- line-height: 1.1;
- font-weight: 790;
- }
-
- .loop-center span {
- margin-top: 10px;
- color: #62747c;
- font-size: 18px;
- line-height: 1.22;
- font-weight: 560;
- }
-
- .loop-node {
- position: absolute;
- width: 210px;
- min-height: 82px;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 15px 16px;
- border-radius: 22px;
- border: 1px solid rgba(37, 49, 59, 0.12);
- background: rgba(255, 255, 255, 0.88);
- color: #34494f;
- font-size: 20px;
- line-height: 1.16;
- font-weight: 760;
- text-align: center;
- }
-
- .loop-node.context {
- left: 60px;
- top: 62px;
- background: rgba(217, 240, 231, 0.88);
- }
-
- .loop-node.prompt {
- left: calc(50% - 105px);
- top: 26px;
- background: rgba(217, 236, 251, 0.88);
- }
-
- .loop-node.round {
- right: 60px;
- top: 62px;
- background: rgba(231, 225, 245, 0.88);
- }
-
- .loop-node.tools {
- right: 60px;
- bottom: 64px;
- background: rgba(246, 230, 200, 0.90);
- }
-
- .loop-node.evidence {
- left: calc(50% - 105px);
- bottom: 28px;
- background: rgba(245, 221, 216, 0.90);
- }
-
- .loop-node.finish {
- left: 60px;
- bottom: 64px;
- background: rgba(221, 237, 232, 0.92);
- }
-
- .gate-row {
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 12px;
- margin-top: 18px;
- }
-
- .gate {
- min-height: 82px;
- padding: 13px 12px;
- border-radius: 20px;
- background: rgba(255, 255, 255, 0.70);
- border: 1px solid rgba(37, 49, 59, 0.10);
- }
-
- .gate strong {
- display: block;
- margin-bottom: 6px;
- color: #314349;
- font-size: 17px;
- line-height: 1.1;
- font-weight: 780;
- }
-
- .gate span {
- color: #63767e;
- font-size: 14px;
- line-height: 1.22;
- font-weight: 540;
- }
-
- .insights {
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 18px;
- margin-bottom: 28px;
- }
-
- .insight {
- min-height: 230px;
- padding: 22px;
- border-radius: 28px;
- background: rgba(255, 255, 255, 0.72);
- }
-
- .insight .number {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 52px;
- height: 52px;
- margin-bottom: 14px;
- border-radius: 18px;
- background: rgba(121, 164, 146, 0.20);
- color: #4b7163;
- font-size: 23px;
- font-weight: 790;
- }
-
- .insight:nth-child(2) .number {
- background: rgba(132, 175, 208, 0.22);
- color: #3d6684;
- }
-
- .insight:nth-child(3) .number {
- background: rgba(221, 176, 168, 0.24);
- color: #8a5d57;
- }
-
- .insight:nth-child(4) .number {
- background: rgba(213, 184, 110, 0.22);
- color: #806a2f;
- }
-
- .insight h3 {
- margin: 0 0 12px;
- color: #26353b;
- font-size: 24px;
- line-height: 1.12;
- font-weight: 780;
- }
-
- .insight p {
- margin: 0;
- color: #5f7279;
- font-size: 18px;
- line-height: 1.28;
- font-weight: 520;
- }
-
- .foundation {
- display: grid;
- grid-template-columns: 1.08fr 1fr 1fr;
- gap: 22px;
- margin-bottom: 24px;
- }
-
- .foundation-panel {
- min-height: 300px;
- padding: 26px;
- border-radius: 30px;
- background: rgba(255, 255, 255, 0.70);
- }
-
- .metric-row {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: 12px;
- margin-top: 20px;
- }
-
- .metric {
- min-height: 104px;
- padding: 16px;
- border-radius: 22px;
- background: rgba(249, 251, 247, 0.74);
- border: 1px solid rgba(37, 49, 59, 0.10);
- }
-
- .metric strong {
- display: block;
- color: #26353b;
- font-size: 30px;
- line-height: 1;
- font-weight: 800;
- }
-
- .metric span {
- display: block;
- margin-top: 10px;
- color: #62747c;
- font-size: 15px;
- line-height: 1.24;
- font-weight: 560;
- }
-
- .timeline {
- display: grid;
- grid-template-columns: repeat(7, 1fr);
- gap: 8px;
- margin: 16px 0 12px;
- }
-
- .timeline span {
- display: flex;
- justify-content: center;
- align-items: center;
- min-height: 42px;
- border-radius: 16px;
- background: rgba(246, 230, 200, 0.86);
- color: #6b5b31;
- font-size: 16px;
- font-weight: 760;
- }
-
- .layer-stack {
- display: grid;
- gap: 10px;
- margin-top: 16px;
- }
-
- .layer {
- display: grid;
- grid-template-columns: 76px 1fr;
- gap: 14px;
- align-items: center;
- min-height: 62px;
- padding: 10px 14px;
- border-radius: 20px;
- background: rgba(249, 251, 247, 0.76);
- border: 1px solid rgba(37, 49, 59, 0.09);
- }
-
- .layer strong {
- color: #496960;
- font-size: 20px;
- font-weight: 800;
- }
-
- .layer span {
- color: #5e7077;
- font-size: 16px;
- line-height: 1.24;
- font-weight: 560;
- }
-
- .footer {
- display: flex;
- justify-content: space-between;
- align-items: center;
- color: #607178;
- font-size: 17px;
- font-weight: 600;
- }
-
- .footer strong {
- color: #34464d;
- font-weight: 790;
- }
-
- @page {
- size: 1800px 2600px;
- margin: 0;
- }
-
- @media print {
- html,
- body {
- width: 1800px;
- height: 2600px;
- }
-
- .poster {
- -webkit-print-color-adjust: exact;
- print-color-adjust: exact;
- }
- }
- </style>
-</head>
-<body>
- <main class="poster" aria-label="DeepTutor technical poster">
- <section class="hero">
- <div>
- <div class="kicker">Current codebase research · technical poster</div>
- <h1>DeepTutor</h1>
- <p class="subtitle">Agent-native personalized tutoring harness, where open-ended teaching is governed by deterministic learning engines.</p>
- </div>
- <aside class="hero-note">
- <div>
- <div class="label">Entry surfaces</div>
- <div class="value">CLI, WebSocket API, and Python SDK all converge on one turn contract.</div>
- </div>
- <div class="entry-grid">
- <span>CLI</span>
- <span>WebSocket</span>
- <span>SDK</span>
- </div>
- </aside>
- </section>
-
- <section class="spine">
- <h2 class="section-title">One learner turn becomes a governed agent loop</h2>
- <p class="section-subtitle">The surface changes; the runtime path stays stable: context assembly, capability routing, tool composition, streaming trace, final result envelope.</p>
- <div class="turn-flow">
- <div class="flow-node">
- <strong>Unified learner context</strong>
- <span>History, attachments, knowledge bases, persona, memory, skills, and request settings travel together.</span>
- </div>
- <div class="arrow"></div>
- <div class="flow-node">
- <strong>Orchestrator</strong>
- <span>Selects the active capability, defaults to chat, and opens the per-turn event bus.</span>
- </div>
- <div class="arrow"></div>
- <div class="flow-node">
- <strong>Capability owns intent</strong>
- <span>Chat, Solve, Question, Research, Visualize, Animator, and Mastery share the same result shape.</span>
- </div>
- <div class="arrow"></div>
- <div class="flow-node">
- <strong>Replayable stream</strong>
- <span>Stages, content, tool activity, sources, errors, and completion flow to every consumer.</span>
- </div>
- </div>
- </section>
-
- <section class="main-grid">
- <aside class="panel">
- <span class="eyebrow">Level 1 · adaptive tool surface</span>
- <h2>Tools are computed per turn</h2>
- <p>The model never receives a static toolbox. Each turn gets a computed surface assembled from choices, context, capability state, and grants.</p>
- <div class="mini-list">
- <div class="mini-item"><span class="dot"></span><span>User toggles expose brainstorming, web and paper search, and deep reasoning.</span></div>
- <div class="mini-item"><span class="dot blue"></span><span>Context gates mount retrieval, sources, memory, notebooks, skills, workspace actions, and Ask User.</span></div>
- <div class="mini-item"><span class="dot rose"></span><span>Active capabilities inject their own deterministic control tools.</span></div>
- <div class="mini-item"><span class="dot gold"></span><span>Partner and multi-user grants remove risky tools before prompting.</span></div>
- </div>
- <div class="chip-cloud">
- <span class="chip">toggleable</span>
- <span class="chip blue">context gated</span>
- <span class="chip rose">capability owned</span>
- <span class="chip gold">grant filtered</span>
- </div>
- </aside>
-
- <section class="core-panel">
- <span class="eyebrow">Core insight</span>
- <h2>Model agency inside deterministic gates</h2>
- <p class="core-caption">The model chooses how to teach, retrieve, reason, consult, and explain. The harness decides what is allowed, what must be recorded, and whether the learner may advance.</p>
- <div class="loop-stage">
- <svg viewBox="0 0 690 456" role="presentation" aria-hidden="true">
- <defs>
- <marker id="arrow" viewBox="0 0 10 10" refX="7.2" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
- <path d="M 0 0 L 10 5 L 0 10 z" fill="rgba(70, 91, 96, 0.46)"></path>
- </marker>
- </defs>
- <path d="M164,106 C226,38 462,38 526,106" fill="none" stroke="rgba(70,91,96,.25)" stroke-width="3" marker-end="url(#arrow)"></path>
- <path d="M590,160 C634,232 622,308 528,354" fill="none" stroke="rgba(70,91,96,.25)" stroke-width="3" marker-end="url(#arrow)"></path>
- <path d="M478,402 C400,436 276,432 214,394" fill="none" stroke="rgba(70,91,96,.25)" stroke-width="3" marker-end="url(#arrow)"></path>
- <path d="M102,328 C58,250 70,176 164,106" fill="none" stroke="rgba(70,91,96,.25)" stroke-width="3" marker-end="url(#arrow)"></path>
- <path d="M180,142 C244,188 244,270 180,316" fill="none" stroke="rgba(70,91,96,.18)" stroke-width="3"></path>
- <path d="M512,142 C448,188 448,270 512,316" fill="none" stroke="rgba(70,91,96,.18)" stroke-width="3"></path>
- </svg>
- <div class="loop-node context">Learner context</div>
- <div class="loop-node prompt">Prompt assembly</div>
- <div class="loop-node round">LLM round</div>
- <div class="loop-node tools">Tool dispatch</div>
- <div class="loop-node evidence">Evidence update</div>
- <div class="loop-node finish">Finish or ask</div>
- <div class="loop-center">
- <strong>Agentic Tutoring Harness</strong>
- <span>single growing conversation, tool observations folded back, final answer when no more tools are needed</span>
- </div>
- </div>
- <div class="gate-row">
- <div class="gate"><strong>Tool gate</strong><span>Only mounted tools are callable.</span></div>
- <div class="gate"><strong>Plan gate</strong><span>Solve steps must be committed and closed.</span></div>
- <div class="gate"><strong>Mastery gate</strong><span>Progress follows evidence, not a cursor.</span></div>
- <div class="gate"><strong>Consult gate</strong><span>Subagent help is budgeted and traced.</span></div>
- </div>
- </section>
-
- <aside class="panel">
- <span class="eyebrow">Level 2 · capability ownership</span>
- <h2>Capabilities take over the turn</h2>
- <p>A capability is a turn-owning tutoring objective. Most reuse the chat loop; specialist pipelines still emit the same event stream and result shape.</p>
- <div class="mini-list">
- <div class="mini-item"><span class="dot"></span><span>Chat and Solve run on the shared agent loop.</span></div>
- <div class="mini-item"><span class="dot blue"></span><span>Solve commits a plan, closes steps, and caps replans.</span></div>
- <div class="mini-item"><span class="dot rose"></span><span>Mastery locks advancement to evidence and review.</span></div>
- <div class="mini-item"><span class="dot gold"></span><span>Research, Question, Visualize, and Animator route staged production flows.</span></div>
- </div>
- <div class="chip-cloud">
- <span class="chip">chat</span>
- <span class="chip blue">solve</span>
- <span class="chip rose">mastery</span>
- <span class="chip gold">research</span>
- <span class="chip">question</span>
- <span class="chip blue">visualize</span>
- <span class="chip rose">animator</span>
- </div>
- </aside>
- </section>
-
- <section class="insights">
- <article class="insight">
- <span class="number">01</span>
- <h3>Tutoring is loop-native</h3>
- <p>A turn is a single growing conversation. Tool narration, observations, final answer, and learner clarification all stay inside the same loop.</p>
- </article>
- <article class="insight">
- <span class="number">02</span>
- <h3>Advancement is computed</h3>
- <p>Mastery Path asks the engine for the next objective. Pending answers, due reviews, and unmet gates outrank simple stage progression.</p>
- </article>
- <article class="insight">
- <span class="number">03</span>
- <h3>Retrieval is provider-bound</h3>
- <p>Each knowledge base keeps its retrieval engine. The service routes to local vector, page, graph, LightRAG, server, or pointer-backed sources.</p>
- </article>
- <article class="insight">
- <span class="number">04</span>
- <h3>Observability is first-class</h3>
- <p>The stream protocol records stages, tool calls, tool results, sources, costs, errors, and completion for live UI and replay.</p>
- </article>
- </section>
-
- <section class="foundation">
- <article class="foundation-panel">
- <span class="eyebrow">Learning algorithms</span>
- <h2>Hard mastery gate</h2>
- <p>Memory and procedure objectives require recency-weighted evidence to clear a 0.90 bar, with early-attempt confidence caps. Concept and design objectives use qualitative Feynman-style assessment.</p>
- <div class="timeline">
- <span>0</span>
- <span>1</span>
- <span>3</span>
- <span>7</span>
- <span>14</span>
- <span>30</span>
- <span>60</span>
- </div>
- <p>Type-specific review intervals turn mastery into scheduled reinforcement.</p>
- </article>
-
- <article class="foundation-panel">
- <span class="eyebrow">Knowledge fabric</span>
- <h2>Multiple retrieval kernels</h2>
- <p>The same tutoring loop can ground itself in indexed libraries, external graph retrieval, live Obsidian vaults, connected agents, or a LightRAG server.</p>
- <div class="metric-row">
- <div class="metric"><strong>5</strong><span>retrieval providers available through one service facade</span></div>
- <div class="metric"><strong>4</strong><span>connected knowledge-base pointer types skip re-indexing</span></div>
- </div>
- </article>
-
- <article class="foundation-panel">
- <span class="eyebrow">Memory fabric</span>
- <h2>Trace to learner model</h2>
- <p>Personalization is inspectable: raw events become surface summaries, then durable learner profiles and preferences.</p>
- <div class="layer-stack">
- <div class="layer"><strong>L1</strong><span>append-only interaction trace</span></div>
- <div class="layer"><strong>L2</strong><span>surface-level summaries</span></div>
- <div class="layer"><strong>L3</strong><span>editable learner model</span></div>
- </div>
- </article>
- </section>
-
- <footer class="footer">
- <span><strong>DeepTutor technical anatomy</strong> · agent-native tutoring, deterministic learning gates, pluggable knowledge, replayable streams</span>
- <span>HKUDS / DeepTutor · current repository snapshot</span>
- </footer>
- </main>
-</body>
-</html>
diff --git a/artifacts/deeptutor-poster/deeptutor-technical-poster.png b/artifacts/deeptutor-poster/deeptutor-technical-poster.png
deleted file mode 100644
index 18f35bfe3..000000000
Binary files a/artifacts/deeptutor-poster/deeptutor-technical-poster.png and /dev/null differ
diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.py
index 619245ca9..eba91a9f4 100644
--- a/deeptutor/agents/research/pipeline.py
+++ b/deeptutor/agents/research/pipeline.py
@@ -525,6 +525,36 @@ class ResearchPipeline:
client=client,
)
+ # A planned block that didn't reach COMPLETED (raised, or exhausted its
+ # iteration budget without a FINISH) is backfilled with empty knowledge
+ # so the surviving blocks can still produce a useful report. But the run
+ # must not then look like a clean success — surface the shortfall both
+ # visibly (a warning notice) and in the result envelope so callers can
+ # tell the report is partial (issue #595).
+ incomplete = [rb for rb in researched if rb.block.status != TopicStatus.COMPLETED]
+ failed_block_titles = [rb.block.sub_topic for rb in incomplete]
+ if incomplete:
+ logger.warning(
+ "Deep Research partial: %d/%d blocks did not complete: %s",
+ len(incomplete),
+ len(researched),
+ failed_block_titles,
+ )
+ await stream.progress(
+ self._t(
+ "notices.partial_results",
+ default=(
+ "{failed} of {total} research subtopics could not be completed; "
+ "the report is based on the remaining evidence."
+ ),
+ failed=len(incomplete),
+ total=len(researched),
+ ),
+ source=SOURCE,
+ stage="researching",
+ metadata={"trace_kind": "warning"},
+ )
+
# ----- Phase 4 (iterative reporting) -----
async with stream.stage(
"reporting",
@@ -550,6 +580,9 @@ class ResearchPipeline:
"topic": refined_topic,
"block_count": len(researched),
"citation_count": len(citations.get_all_citations()),
+ "partial": bool(incomplete),
+ "failed_block_count": len(incomplete),
+ "failed_block_titles": failed_block_titles,
},
}
await emit_capability_result(stream, result_payload, source=SOURCE, usage=self.usage)
diff --git a/deeptutor/agents/research/prompts/en/pipeline.yaml b/deeptutor/agents/research/prompts/en/pipeline.yaml
index 1550f46e7..0a4994a4a 100644
--- a/deeptutor/agents/research/prompts/en/pipeline.yaml
+++ b/deeptutor/agents/research/prompts/en/pipeline.yaml
@@ -45,6 +45,7 @@ notices:
tool_unknown_error: "Error executing {tool}."
too_many_tool_calls: "Requested {requested} tool calls; capped at {limit}."
max_iterations_reached: "Reached the iteration ceiling for this block; forcing FINISH."
+ partial_results: "{failed} of {total} research subtopics could not be completed; the report is based on the remaining evidence."
rephrase_cap_reached: "ask_user limit reached ({max_rounds} rounds). Emit FINISH now with the best refined topic you can produce from prior answers."
rephrase_only_ask_user: "Inside rephrase you may only call `ask_user`; `{tool}` is ignored."
append_rejected_empty: "APPEND rejected: provide a title on the first line after the label."
diff --git a/deeptutor/agents/research/prompts/zh/pipeline.yaml b/deeptutor/agents/research/prompts/zh/pipeline.yaml
index b05f58b86..1914b439f 100644
--- a/deeptutor/agents/research/prompts/zh/pipeline.yaml
+++ b/deeptutor/agents/research/prompts/zh/pipeline.yaml
@@ -37,6 +37,7 @@ notices:
tool_unknown_error: "执行 {tool} 时出错。"
too_many_tool_calls: "本轮请求 {requested} 次工具调用,已截断到上限 {limit}。"
max_iterations_reached: "当前研究块已达到迭代上限,强制 FINISH。"
+ partial_results: "{total} 个研究子主题中有 {failed} 个未能完成;报告基于其余已收集的证据生成。"
rephrase_cap_reached: "ask_user 已达上限({max_rounds} 轮)。请基于已有回答 FINISH 输出最优的精炼主题。"
rephrase_only_ask_user: "在 rephrase 阶段仅允许调用 `ask_user`;本次 `{tool}` 被忽略。"
append_rejected_empty: "APPEND 已拒绝:标签后第一行需提供新主题的标题。"
diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.py
index 81d40e0b5..f3b08d60d 100644
--- a/deeptutor/services/rag/pipelines/lightrag/engine.py
+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py
@@ -39,12 +39,23 @@ def build_rag(working_dir: Path) -> Any:
from raganything import RAGAnything, RAGAnythingConfig
config = RAGAnythingConfig(working_dir=str(working_dir))
- return RAGAnything(
+ rag = RAGAnything(
config=config,
llm_model_func=build_llm_model_func(),
vision_model_func=build_vision_model_func(),
embedding_func=build_embedding_func(),
)
+ # DeepTutor always feeds RAG-Anything a pre-parsed ``content_list`` (the
+ # parse layer runs upstream via DeepTutor's own ParseService), so
+ # RAG-Anything's bundled document parser is never invoked. Its LightRAG init
+ # nevertheless runs a one-time installation check on its *default* parser
+ # (``mineru``); when MinerU isn't installed that check hard-fails indexing
+ # with "Parser 'mineru' is not properly installed" — even though the user
+ # picked an entirely different parse engine (see issue #594). Marking the
+ # check as already satisfied skips that spurious gate for a parser we don't
+ # use, while leaving the real pre-parsed insert path untouched.
+ rag._parser_installation_checked = True
+ return rag
async def insert(rag: Any, content_list: list[dict], *, file_name: str, doc_id: str) -> None:
diff --git a/deeptutor/services/rag/pipelines/llamaindex/vector_store.py b/deeptutor/services/rag/pipelines/llamaindex/vector_store.py
index a8e9bcdab..00f2b1bcb 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/vector_store.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/vector_store.py
@@ -27,9 +27,11 @@ working (just without the speed-up).
from __future__ import annotations
import logging
+import os
from pathlib import Path
from typing import Any, Iterable, Optional
+from fsspec.implementations.local import LocalFileSystem
from llama_index.core import StorageContext, load_index_from_storage
from llama_index.core.vector_stores.simple import DEFAULT_VECTOR_STORE, NAMESPACE_SEP
import numpy as np
@@ -72,6 +74,40 @@ def _normalize(embedding: Any) -> list[float]:
return vector.tolist()
+def faiss_write_index(index: Any, persist_path: str) -> None:
+ """Persist a FAISS index through a Python byte stream (Unicode-path safe).
+
+ Stock ``faiss.write_index`` is a SWIG passthrough that hands the path
+ straight to C++ ``fopen``. On Windows that is the *narrow* ANSI API, while
+ SWIG encodes the Python string as UTF-8 — so any non-ASCII path (a Chinese
+ knowledge-base name, or a ``C:\\Users\\张三`` home directory) fails to open
+ and index rebuilds crash. Serializing to bytes in memory and letting Python
+ write the file sidesteps this: CPython opens files via the wide ``_wfopen``
+ API on Windows, so Unicode paths work. The byte payload is identical to
+ ``write_index`` output, so indexes stay cross-readable with stock FAISS.
+ """
+ import faiss
+
+ payload = faiss.serialize_index(index)
+ with open(persist_path, "wb") as handle:
+ handle.write(payload.tobytes())
+
+
+def faiss_read_index(persist_path: str) -> Any:
+ """Load a FAISS index written by :func:`faiss_write_index` (or stock FAISS).
+
+ The on-disk format is identical either way, so this also reads indexes
+ persisted by an older ``faiss.write_index`` call. Reading the bytes with
+ Python ``open`` keeps the load path Unicode-safe on Windows, mirroring
+ :func:`faiss_write_index`.
+ """
+ import faiss
+
+ with open(persist_path, "rb") as handle:
+ buffer = np.frombuffer(handle.read(), dtype="uint8")
+ return faiss.deserialize_index(buffer)
+
+
def _cosine_faiss_cls() -> Optional[type]:
"""Return a memoized FaissVectorStore subclass that ranks by cosine.
@@ -89,7 +125,14 @@ def _cosine_faiss_cls() -> Optional[type]:
return None
class _CosineFaissVectorStore(faiss_store_cls): # type: ignore[valid-type, misc]
- """FAISS store that L2-normalizes vectors for cosine ranking."""
+ """FAISS store that L2-normalizes vectors for cosine ranking.
+
+ It also overrides persistence to route through :func:`faiss_write_index`
+ / :func:`faiss_read_index` instead of the stock path-based
+ ``faiss.write_index`` / ``read_index``, which cannot handle non-ASCII
+ paths on Windows. The two concerns are independent: cosine ranking
+ shapes *what* is stored, the IO override shapes *how* it reaches disk.
+ """
def add(self, nodes: list[Any], **kwargs: Any) -> list[str]:
for node in nodes:
@@ -101,6 +144,22 @@ def _cosine_faiss_cls() -> Optional[type]:
query.query_embedding = _normalize(query.query_embedding)
return super().query(query, **kwargs)
+ def persist(self, persist_path: str, fs: Any = None) -> None:
+ if fs is not None and not isinstance(fs, LocalFileSystem):
+ raise NotImplementedError("FAISS only supports local storage for now.")
+ dirpath = os.path.dirname(persist_path)
+ if dirpath:
+ os.makedirs(dirpath, exist_ok=True)
+ faiss_write_index(self._faiss_index, persist_path)
+
+ @classmethod
+ def from_persist_path(cls, persist_path: str, fs: Any = None) -> Any:
+ if fs is not None and not isinstance(fs, LocalFileSystem):
+ raise NotImplementedError("FAISS only supports local storage for now.")
+ if not os.path.exists(persist_path):
+ raise ValueError(f"No existing FAISS index found at {persist_path}.")
+ return cls(faiss_index=faiss_read_index(persist_path))
+
_COSINE_FAISS_CLS = _CosineFaissVectorStore
return _COSINE_FAISS_CLS
@@ -197,6 +256,8 @@ __all__ = [
"DEFAULT_VECTOR_STORE_FILENAME",
"detect_backend",
"faiss_available",
+ "faiss_read_index",
+ "faiss_write_index",
"load_index",
"new_faiss_storage_context",
"storage_context_for_nodes",
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
index c75a9941d..ff02776d0 100644
--- a/deeptutor/services/session/pocketbase_store.py
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -65,6 +65,40 @@ def _to_float(value: Any, default: float = 0.0) -> float:
return default
+def _current_user_id() -> str:
+ """Id of the request-scoped current user, used to isolate session rows.
+
+ PocketBase is a single shared server queried by one process-wide
+ admin-authenticated client, so it has no filesystem-level isolation. Every
+ session row is therefore scoped by ``user_id`` (the SQLite backend isolates
+ via a per-user database file instead — see ``get_sqlite_session_store``).
+ This reads the same ``_current_user`` ContextVar that the SQLite path
+ service resolves against, so the two backends share one source of truth and
+ are equally reliable across HTTP, WebSocket, and turn-runtime threads. Falls
+ back to the local-admin id in single-user / no-auth mode.
+
+ The id is validated (it always matches ``_VALID_ID`` for real users — a
+ PocketBase record id, a ``u_<hex>`` id, or ``local-admin``) so it is safe to
+ interpolate into a PocketBase filter string.
+ """
+ from deeptutor.multi_user.context import get_current_user
+
+ return _validate_id(get_current_user().id, "user_id")
+
+
+def _find_session_record(pb: Any, session_id: str, user_id: str) -> Any | None:
+ """Return the ``sessions`` record for *session_id* owned by *user_id*.
+
+ Scoping every session lookup by ``user_id`` is the single point that keeps
+ one user from reading or mutating another's sessions on the shared
+ PocketBase backend. Returns ``None`` when no such row exists for this user.
+ """
+ records = pb.collection("sessions").get_full_list(
+ query_params={"filter": f'session_id="{session_id}" && user_id="{user_id}"'}
+ )
+ return records[0] if records else None
+
+
class PocketBaseSessionStore:
"""PocketBase-backed implementation of SessionStoreProtocol."""
@@ -80,6 +114,7 @@ class PocketBaseSessionStore:
now = time.time()
resolved_id = session_id or f"unified_{int(now * 1000)}_{uuid.uuid4().hex[:8]}"
resolved_title = (title or "New conversation").strip() or "New conversation"
+ owner_id = _current_user_id()
def _create():
return (
@@ -88,6 +123,7 @@ class PocketBaseSessionStore:
.create(
{
"session_id": resolved_id,
+ "user_id": owner_id,
"title": resolved_title[:100],
"compressed_summary": "",
"summary_up_to_msg_id": 0,
@@ -103,15 +139,11 @@ class PocketBaseSessionStore:
async def get_session(self, session_id: str) -> dict[str, Any] | None:
sid = _validate_id(session_id, "session_id")
+ uid = _current_user_id()
def _get():
try:
- records = (
- _pb()
- .collection("sessions")
- .get_full_list(query_params={"filter": f'session_id="{sid}"'})
- )
- return records[0] if records else None
+ return _find_session_record(_pb(), sid, uid)
except Exception:
return None
@@ -158,17 +190,14 @@ class PocketBaseSessionStore:
async def update_session_title(self, session_id: str, title: str) -> bool:
sid = _validate_id(session_id, "session_id")
+ uid = _current_user_id()
def _update():
- records = (
- _pb()
- .collection("sessions")
- .get_full_list(query_params={"filter": f'session_id="{sid}"'})
- )
- if not records:
+ record = _find_session_record(_pb(), sid, uid)
+ if record is None:
return False
_pb().collection("sessions").update(
- records[0].id, {"title": (title.strip() or "New conversation")[:100]}
+ record.id, {"title": (title.strip() or "New conversation")[:100]}
)
return True
@@ -180,16 +209,13 @@ class PocketBaseSessionStore:
async def delete_session(self, session_id: str) -> bool:
sid = _validate_id(session_id, "session_id")
+ uid = _current_user_id()
def _delete():
- records = (
- _pb()
- .collection("sessions")
- .get_full_list(query_params={"filter": f'session_id="{sid}"'})
- )
- if not records:
+ record = _find_session_record(_pb(), sid, uid)
+ if record is None:
return False
- _pb().collection("sessions").delete(records[0].id)
+ _pb().collection("sessions").delete(record.id)
return True
try:
@@ -204,9 +230,10 @@ class PocketBaseSessionStore:
offset: int = 0,
) -> list[dict[str, Any]]:
page = (offset // limit) + 1
+ uid = _current_user_id()
def _list():
- query_params: dict[str, Any] = {"sort": "-updated"}
+ query_params: dict[str, Any] = {"sort": "-updated", "filter": f'user_id="{uid}"'}
return _pb().collection("sessions").get_list(page, limit, query_params=query_params)
try:
@@ -218,17 +245,14 @@ class PocketBaseSessionStore:
async def update_summary(self, session_id: str, summary: str, up_to_msg_id: int) -> bool:
sid = _validate_id(session_id, "session_id")
+ uid = _current_user_id()
def _update():
- records = (
- _pb()
- .collection("sessions")
- .get_full_list(query_params={"filter": f'session_id="{sid}"'})
- )
- if not records:
+ record = _find_session_record(_pb(), sid, uid)
+ if record is None:
return False
_pb().collection("sessions").update(
- records[0].id,
+ record.id,
{
"compressed_summary": summary,
"summary_up_to_msg_id": max(0, int(up_to_msg_id)),
@@ -252,16 +276,13 @@ class PocketBaseSessionStore:
if session is None:
return False
merged = {**session.get("preferences", {}), **(preferences or {})}
+ uid = _current_user_id()
def _update():
- records = (
- _pb()
- .collection("sessions")
- .get_full_list(query_params={"filter": f'session_id="{sid}"'})
- )
- if not records:
+ record = _find_session_record(_pb(), sid, uid)
+ if record is None:
return False
- _pb().collection("sessions").update(records[0].id, {"preferences_json": merged})
+ _pb().collection("sessions").update(record.id, {"preferences_json": merged})
return True
return await asyncio.to_thread(_update)
@@ -283,6 +304,13 @@ class PocketBaseSessionStore:
# ------------------------------------------------------------------
# Messages
# ------------------------------------------------------------------
+ # Messages/turns/turn_events are keyed by ``session_id`` and are reached
+ # from the API only through a session lookup that is already user-scoped
+ # (``get_session_with_messages`` returns ``None`` for another user's
+ # session before any message is fetched, and ``create_turn`` rejects a
+ # session the caller doesn't own). Internal callers always operate on the
+ # current user's own session, so these rows don't carry a separate
+ # ``user_id`` filter — the session boundary above is the access gate.
async def add_message(
self,
@@ -421,17 +449,13 @@ class PocketBaseSessionStore:
async def create_turn(self, session_id: str, capability: str = "") -> dict[str, Any]:
sid = _validate_id(session_id, "session_id")
+ uid = _current_user_id()
now = time.time()
turn_id = f"turn_{int(now * 1000)}_{uuid.uuid4().hex[:10]}"
def _create():
- # Guard: ensure session exists
- sessions = (
- _pb()
- .collection("sessions")
- .get_full_list(query_params={"filter": f'session_id="{sid}"'})
- )
- if not sessions:
+ # Guard: ensure the session exists AND belongs to the current user.
+ if _find_session_record(_pb(), sid, uid) is None:
raise ValueError(f"Session not found: {sid}")
# Guard: no duplicate active turns
active = (
diff --git a/scripts/pb_setup.py b/scripts/pb_setup.py
index cf2ec7c15..48d1b9d64 100644
--- a/scripts/pb_setup.py
+++ b/scripts/pb_setup.py
@@ -83,9 +83,16 @@ def main():
existing = _existing_collections(pb)
print(f"Found {len(existing)} existing collection(s): {sorted(existing) or '(none)'}\n")
+ # Access control is enforced in the application layer, not by PocketBase
+ # collection rules: the backend connects with a single admin-authenticated
+ # client (see services/pocketbase_client.py), which bypasses collection
+ # RBAC entirely, so the rules below stay empty by design. Per-user session
+ # isolation is implemented in PocketBaseSessionStore by stamping every
+ # session row with ``user_id`` and filtering every query by the current
+ # user. Do NOT rely on these listRule/viewRule strings for isolation.
collections = [
# ----------------------------------------------------------------
- # sessions
+ # sessions (``user_id`` populated + filtered by PocketBaseSessionStore)
# ----------------------------------------------------------------
{
"name": "sessions",
diff --git a/tests/agents/research/test_pipeline_partial_failure.py b/tests/agents/research/test_pipeline_partial_failure.py
new file mode 100644
index 000000000..7b5a335eb
--- /dev/null
+++ b/tests/agents/research/test_pipeline_partial_failure.py
@@ -0,0 +1,116 @@
+"""Deep Research must not report success when a research block fails (issue #595).
+
+A subtopic that raises (or exhausts its iteration budget without finishing) is
+backfilled with empty knowledge so the surviving subtopics still yield a report.
+The fix keeps that resilience but makes the shortfall explicit in the result
+envelope (``metadata.partial`` / ``failed_block_count`` / ``failed_block_titles``)
+instead of returning a clean-success shape with missing evidence.
+"""
+
+from __future__ import annotations
+
+import types
+from unittest.mock import patch
+
+import pytest
+
+from deeptutor.agents.research.pipeline import ResearchedBlock, ResearchPipeline, SubTopicItem
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.stream_bus import StreamBus
+
+pytestmark = pytest.mark.asyncio
+
+
+class _FakeLLM:
+ binding = "openai"
+ model = "gpt-x"
+ api_key = "k"
+ base_url = "u"
+ api_version = None
+ extra_headers: dict = {}
+ reasoning_effort = None
+
+
+class _FakeRegistry:
+ def build_openai_schemas(self, _names):
+ return []
+
+ def build_prompt_text(self, _names, **_kwargs):
+ return "- none"
+
+ def get(self, _name):
+ return None
+
+ def get_enabled(self, _names):
+ return []
+
+
+def _make_pipeline() -> ResearchPipeline:
+ with (
+ patch("deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM()),
+ patch("deeptutor.agents.research.pipeline.get_tool_registry", lambda: _FakeRegistry()),
+ ):
+ return ResearchPipeline(language="en", runtime_config={"queue": {"max_length": 5}})
+
+
+async def _run(pipeline: ResearchPipeline) -> dict:
+ async def fake_emit(*_args, **_kwargs):
+ return None
+
+ with patch("deeptutor.agents.research.pipeline.emit_capability_result", fake_emit):
+ return await pipeline._run_inner(
+ context=UnifiedContext(session_id="s1", user_message="research this"),
+ topic="Research topic",
+ image_attachments=[],
+ confirmed_outline=[SubTopicItem(title="A"), SubTopicItem(title="B")],
+ stream=StreamBus(),
+ client=None,
+ )
+
+
+async def test_failed_block_marks_result_partial() -> None:
+ pipeline = _make_pipeline()
+
+ async def fake_research_block(self, *, block, queue, citations, topic, context, stream, client):
+ queue.mark_researching(block.block_id)
+ if block.block_id == "block_1":
+ raise RuntimeError("synthetic block failure")
+ queue.mark_completed(block.block_id)
+ return ResearchedBlock(block=block, knowledge=f"knowledge for {block.block_id}")
+
+ async def fake_write_report(self, *, topic, blocks, citations, stream, client):
+ return "REPORT_OK"
+
+ pipeline._research_block = types.MethodType(fake_research_block, pipeline)
+ pipeline._write_report = types.MethodType(fake_write_report, pipeline)
+
+ result = await _run(pipeline)
+ meta = result["metadata"]
+
+ assert result["response"] == "REPORT_OK" # surviving evidence still produces a report
+ assert meta["partial"] is True
+ assert meta["failed_block_count"] == 1
+ assert meta["failed_block_titles"] == ["A"]
+ assert meta["block_count"] == 2
+
+
+async def test_all_blocks_complete_is_not_partial() -> None:
+ pipeline = _make_pipeline()
+
+ async def fake_research_block(self, *, block, queue, citations, topic, context, stream, client):
+ queue.mark_researching(block.block_id)
+ queue.mark_completed(block.block_id)
+ return ResearchedBlock(block=block, knowledge=f"knowledge for {block.block_id}")
+
+ async def fake_write_report(self, *, topic, blocks, citations, stream, client):
+ return "REPORT_OK"
+
+ pipeline._research_block = types.MethodType(fake_research_block, pipeline)
+ pipeline._write_report = types.MethodType(fake_write_report, pipeline)
+
+ result = await _run(pipeline)
+ meta = result["metadata"]
+
+ assert meta["partial"] is False
+ assert meta["failed_block_count"] == 0
+ assert meta["failed_block_titles"] == []
diff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.py
index bbfd2463f..018959c4c 100644
--- a/tests/services/rag/test_lightrag_pipeline.py
+++ b/tests/services/rag/test_lightrag_pipeline.py
@@ -233,6 +233,42 @@ def test_lightrag_vision_adapter_preserves_messages(monkeypatch) -> None:
assert captured["messages"] == [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]
+def test_build_rag_skips_raganything_parser_install_check(monkeypatch) -> None:
+ """Regression for issue #594.
+
+ RAG-Anything validates its *default* parser (``mineru``) at LightRAG-init
+ time, even though DeepTutor only ever inserts a pre-parsed ``content_list``
+ and never uses RAG-Anything's parser. ``build_rag`` must pre-satisfy that
+ check so indexing with a different parse engine (e.g. pymupdf4llm) doesn't
+ hard-fail when MinerU is absent.
+ """
+ captured: dict[str, object] = {}
+
+ class _FakeConfig:
+ def __init__(self, *, working_dir) -> None:
+ self.working_dir = working_dir
+ self.parser = "mineru" # RAG-Anything's default
+
+ class _FakeRagAnything:
+ def __init__(self, *, config, llm_model_func, vision_model_func, embedding_func) -> None:
+ # Mirror the real constructor: the install check starts unsatisfied.
+ self._parser_installation_checked = False
+ captured["config"] = config
+
+ fake_module = types.ModuleType("raganything")
+ fake_module.RAGAnything = _FakeRagAnything
+ fake_module.RAGAnythingConfig = _FakeConfig
+ monkeypatch.setitem(sys.modules, "raganything", fake_module)
+ monkeypatch.setattr(engine, "build_llm_model_func", lambda: "llm")
+ monkeypatch.setattr(engine, "build_vision_model_func", lambda: "vision")
+ monkeypatch.setattr(engine, "build_embedding_func", lambda: "embed")
+
+ rag = engine.build_rag(Path("/tmp/kb-wd")) # noqa: S108
+
+ assert rag._parser_installation_checked is True
+ assert captured["config"].working_dir == "/tmp/kb-wd"
+
+
def test_lightrag_query_initializes_raganything_before_aquery(monkeypatch) -> None:
calls: list[str] = []
diff --git a/tests/services/rag/test_llamaindex_faiss_vector_store.py b/tests/services/rag/test_llamaindex_faiss_vector_store.py
index 0161d7c12..8369208a4 100644
--- a/tests/services/rag/test_llamaindex_faiss_vector_store.py
+++ b/tests/services/rag/test_llamaindex_faiss_vector_store.py
@@ -14,6 +14,7 @@ from pathlib import Path
from llama_index.core import Settings, VectorStoreIndex
from llama_index.core.embeddings import BaseEmbedding
from llama_index.core.schema import ImageNode, TextNode
+import numpy as np
import pytest
from deeptutor.services.rag.pipelines.llamaindex import storage as storage_module
@@ -263,3 +264,62 @@ def test_storage_create_index_persists_faiss_end_to_end(tmp_path: Path) -> None:
assert count == 1
assert vector_store.detect_backend(storage_dir) == vector_store.BACKEND_FAISS
assert storage_module.retrieve_nodes(storage_dir, "probe", top_k=1)
+
+
+def test_faiss_persist_and_load_survive_non_ascii_path(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Persist + load must work on a non-ASCII path (Windows fopen bug).
+
+ Only the *string-path* overload of ``faiss.write_index`` / ``read_index`` is
+ affected: it passes the path to C++ ``fopen``, which on Windows uses the
+ narrow ANSI API and cannot open non-ASCII paths (a Chinese KB name, a
+ ``C:\\Users\\张三`` home) — so index rebuilds crash. The in-memory
+ ``IOWriter`` overload that ``serialize_index`` uses is unaffected, which is
+ exactly why our store routes through it. The guards below mirror that
+ Windows semantics on any platform (fail only when handed a ``str`` path), so
+ this test fails if anything regresses to a path-based call.
+ """
+ real_write, real_read = faiss.write_index, faiss.read_index
+
+ def _guard_write(index: object, target: object, *args: object, **kwargs: object) -> object:
+ if isinstance(target, str):
+ raise RuntimeError("simulated Windows narrow-fopen failure on non-ASCII path")
+ return real_write(index, target, *args, **kwargs)
+
+ def _guard_read(source: object, *args: object, **kwargs: object) -> object:
+ if isinstance(source, str):
+ raise RuntimeError("simulated Windows narrow-fopen failure on non-ASCII path")
+ return real_read(source, *args, **kwargs)
+
+ monkeypatch.setattr(faiss, "write_index", _guard_write)
+ monkeypatch.setattr(faiss, "read_index", _guard_read)
+
+ # A Chinese KB-name segment plus a flat version dir, mirroring real layout.
+ storage_dir = tmp_path / "数学课程" / "version-1"
+ storage_dir.mkdir(parents=True)
+
+ _persist_faiss_index(storage_dir) # write path: would raise via write_index
+ assert vector_store.detect_backend(storage_dir) == vector_store.BACKEND_FAISS
+
+ index = vector_store.load_index(storage_dir) # read path: would raise via read_index
+ results = index.as_retriever(similarity_top_k=2).retrieve("probe")
+ assert [r.node.node_id for r in results] == ["gamma", "alpha"]
+
+
+def test_faiss_index_bytes_stay_cross_readable_with_stock_faiss(tmp_path: Path) -> None:
+ """Our serialize-based IO and stock path-based IO share one on-disk format.
+
+ Guarantees existing indexes (written by an older ``faiss.write_index``) stay
+ loadable, and new ones written by us stay readable by stock FAISS tooling.
+ """
+ idx = faiss.IndexFlatIP(_DIM)
+ idx.add(np.asarray([_VECTORS["alpha"], _VECTORS["beta"]], dtype="float32"))
+
+ ours = tmp_path / "ours.faiss"
+ vector_store.faiss_write_index(idx, str(ours))
+ assert faiss.read_index(str(ours)).ntotal == 2 # stock reader reads our bytes
+
+ stock = tmp_path / "stock.faiss"
+ faiss.write_index(idx, str(stock))
+ assert vector_store.faiss_read_index(str(stock)).ntotal == 2 # our reader reads stock bytes
diff --git a/tests/services/session/test_pocketbase_isolation.py b/tests/services/session/test_pocketbase_isolation.py
new file mode 100644
index 000000000..a49849dff
--- /dev/null
+++ b/tests/services/session/test_pocketbase_isolation.py
@@ -0,0 +1,174 @@
+"""Per-user session isolation on the PocketBase backend (issue #596).
+
+PocketBase is a single shared server with no filesystem-level isolation, so
+``PocketBaseSessionStore`` must scope every session row by ``user_id`` (derived
+from the request-scoped current-user ContextVar). These tests stand up a tiny
+in-memory fake of the PocketBase SDK — the real ``pocketbase`` package is not a
+test dependency — and assert that one user can never see or mutate another
+user's sessions.
+"""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+from pathlib import Path
+import re
+
+import pytest
+
+from deeptutor.multi_user.context import reset_current_user, set_current_user
+from deeptutor.multi_user.models import CurrentUser, UserScope
+from deeptutor.services.session.pocketbase_store import PocketBaseSessionStore
+
+pytestmark = pytest.mark.asyncio
+
+_CLAUSE = re.compile(r'(\w+)\s*=\s*"([^"]*)"')
+
+
+@contextmanager
+def as_user(uid: str, *, role: str = "user"):
+ scope = UserScope(kind=role, user_id=uid, root=Path("/tmp") / uid) # noqa: S108
+ token = set_current_user(CurrentUser(id=uid, username=uid, role=role, scope=scope))
+ try:
+ yield
+ finally:
+ reset_current_user(token)
+
+
+class _Record:
+ def __init__(self, pb_id: str, data: dict) -> None:
+ self.id = pb_id
+ for key, value in data.items():
+ setattr(self, key, value)
+
+
+class _Result:
+ def __init__(self, items: list[_Record]) -> None:
+ self.items = items
+
+
+class _Collection:
+ """In-memory stand-in for a PocketBase collection (equality filters only)."""
+
+ def __init__(self) -> None:
+ self._rows: list[_Record] = []
+ self._seq = 0
+
+ def _matches(self, record: _Record, query_params: dict | None) -> bool:
+ flt = (query_params or {}).get("filter") or ""
+ for field, expected in _CLAUSE.findall(flt):
+ if str(getattr(record, field, "")) != expected:
+ return False
+ return True
+
+ def create(self, data: dict) -> _Record:
+ self._seq += 1
+ record = _Record(f"pb{self._seq:04d}", data)
+ self._rows.append(record)
+ return record
+
+ def get_full_list(self, query_params: dict | None = None) -> list[_Record]:
+ return [r for r in self._rows if self._matches(r, query_params)]
+
+ def get_list(self, page: int, per_page: int, query_params: dict | None = None) -> _Result:
+ matched = self.get_full_list(query_params)
+ start = (page - 1) * per_page
+ return _Result(matched[start : start + per_page])
+
+ def update(self, pb_id: str, data: dict) -> _Record:
+ record = next(r for r in self._rows if r.id == pb_id)
+ for key, value in data.items():
+ setattr(record, key, value)
+ return record
+
+ def delete(self, pb_id: str) -> None:
+ self._rows = [r for r in self._rows if r.id != pb_id]
+
+
+class _FakeClient:
+ def __init__(self) -> None:
+ self._collections: dict[str, _Collection] = {}
+
+ def collection(self, name: str) -> _Collection:
+ return self._collections.setdefault(name, _Collection())
+
+
+def fake_pb(monkeypatch):
+ client = _FakeClient()
+ monkeypatch.setattr(
+ "deeptutor.services.pocketbase_client.get_pb_client", lambda: client, raising=True
+ )
+ return client
+
+
+async def test_create_session_stamps_current_user(fake_pb) -> None:
+ store = PocketBaseSessionStore()
+ with as_user("alice"):
+ await store.create_session(title="A's chat", session_id="s_alice")
+ [row] = fake_pb.collection("sessions").get_full_list()
+ assert row.user_id == "alice"
+ assert row.session_id == "s_alice"
+
+
+async def test_list_sessions_only_returns_own(fake_pb) -> None:
+ store = PocketBaseSessionStore()
+ with as_user("alice"):
+ await store.create_session(title="a1", session_id="s_a1")
+ await store.create_session(title="a2", session_id="s_a2")
+ with as_user("bob"):
+ await store.create_session(title="b1", session_id="s_b1")
+
+ bob_sessions = await store.list_sessions()
+ assert {s["session_id"] for s in bob_sessions} == {"s_b1"}
+
+ with as_user("alice"):
+ alice_sessions = await store.list_sessions()
+ assert {s["session_id"] for s in alice_sessions} == {"s_a1", "s_a2"}
+
+
+async def test_get_session_404s_for_other_user(fake_pb) -> None:
+ store = PocketBaseSessionStore()
+ with as_user("alice"):
+ await store.create_session(title="secret", session_id="s_secret")
+
+ # Bob must not be able to read Alice's session by id.
+ with as_user("bob"):
+ assert await store.get_session("s_secret") is None
+ assert await store.get_session_with_messages("s_secret") is None
+
+ # The owner still reads it fine.
+ with as_user("alice"):
+ own = await store.get_session("s_secret")
+ assert own is not None and own["session_id"] == "s_secret"
+
+
+async def test_mutations_are_scoped_to_owner(fake_pb) -> None:
+ store = PocketBaseSessionStore()
+ with as_user("alice"):
+ await store.create_session(title="orig", session_id="s_m")
+
+ with as_user("bob"):
+ assert await store.update_session_title("s_m", "hijacked") is False
+ assert await store.delete_session("s_m") is False
+ assert await store.update_summary("s_m", "x", 1) is False
+
+ # Alice's row is untouched and still present.
+ with as_user("alice"):
+ assert await store.update_session_title("s_m", "renamed") is True
+ session = await store.get_session("s_m")
+ assert session is not None and session["title"] == "renamed"
+
+
+async def test_create_turn_rejects_foreign_session(fake_pb) -> None:
+ store = PocketBaseSessionStore()
+ with as_user("alice"):
+ await store.create_session(title="orig", session_id="s_t")
+
+ with as_user("bob"):
+ with pytest.raises(ValueError, match="Session not found"):
+ await store.create_turn("s_t")
+
+ with as_user("alice"):
+ turn = await store.create_turn("s_t")
+ assert turn["session_id"] == "s_t"
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index ee706d554..17d5bfee0 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -339,6 +339,19 @@ export default function ChatPage() {
} = useUnifiedChat();
const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
+ // A connected agent to preselect once it loads, from `?agent=<name>` on the
+ // URL (the partner list page links here to drop straight into a chat with a
+ // partner). Captured once at first client render — the URL is rewritten to
+ // `/home/<sessionId>` as soon as the new session is created, dropping the
+ // query — so we can't read it later from the live search params.
+ const pendingAgentRef = useRef<string | null | undefined>(undefined);
+ if (pendingAgentRef.current === undefined) {
+ pendingAgentRef.current =
+ typeof window === "undefined"
+ ? null
+ : new URLSearchParams(window.location.search).get("agent");
+ }
+ const agentPreselectDoneRef = useRef(false);
const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);
const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(
null,
@@ -1610,6 +1623,15 @@ export default function ChatPage() {
},
[setKBs, state.knowledgeBases, agentNameSet],
);
+ // Honor `?agent=<name>` once its connection KB has loaded: preselect it so a
+ // partner opened from the partner list starts the chat already targeting it.
+ useEffect(() => {
+ if (agentPreselectDoneRef.current) return;
+ const name = pendingAgentRef.current;
+ if (!name || !agentNameSet.has(name)) return;
+ agentPreselectDoneRef.current = true;
+ handleSelectAgent(name);
+ }, [agentNameSet, handleSelectAgent]);
// How many times DeepTutor may consult the selected agent this turn. Seeded
// from the configured default; the composer's stepper overrides it per turn
// (sent in the request config, read by the subagent capability).
diff --git a/web/app/(workspace)/partners/page.tsx b/web/app/(workspace)/partners/page.tsx
index d1e516009..68251ce1d 100644
--- a/web/app/(workspace)/partners/page.tsx
+++ b/web/app/(workspace)/partners/page.tsx
@@ -12,7 +12,9 @@ import { HeartHandshake, Loader2, Plus } from "lucide-react";
import { useTranslation } from "react-i18next";
import { listPartners, type PartnerInfo } from "@/lib/partners-api";
import {
+ connectSubagent,
listConnectablePartners,
+ listSubagentConnections,
type ConnectablePartner,
} from "@/lib/subagents-api";
import { useAuthStatus } from "@/hooks/useAuthStatus";
@@ -54,6 +56,51 @@ export default function PartnersPage() {
const { isAdmin, loading: authLoading } = useAuthStatus();
const [partners, setPartners] = useState<PartnerInfo[]>([]);
const [loading, setLoading] = useState(true);
+ const [busyId, setBusyId] = useState<string | null>(null);
+
+ // Clicking a partner card. An admin drills into the management page; a
+ // non-admin can't manage partners — for them a partner is consulted as a
+ // connected agent, so we reuse (or create) that partner's subagent
+ // connection and drop them straight into a fresh chat with it preselected.
+ const openPartner = useCallback(
+ async (partner: PartnerInfo) => {
+ if (isAdmin) {
+ router.push(`/partners/${partner.partner_id}`);
+ return;
+ }
+ setBusyId(partner.partner_id);
+ try {
+ const conns = await listSubagentConnections();
+ const existing = conns.find(
+ (c) =>
+ c.agent_kind === "partner" &&
+ c.partner_id === partner.partner_id,
+ );
+ let name = existing?.name;
+ if (!name) {
+ const taken = new Set(conns.map((c) => c.name));
+ const base = partner.name?.trim() || partner.partner_id;
+ let candidate = base;
+ for (let i = 2; taken.has(candidate); i++) candidate = `${base} (${i})`;
+ name = (
+ await connectSubagent({
+ name: candidate,
+ agent_kind: "partner",
+ partner_id: partner.partner_id,
+ })
+ ).name;
+ }
+ router.push(`/home?agent=${encodeURIComponent(name)}`);
+ } catch {
+ // Couldn't auto-connect (e.g. the name clashes with an existing KB) —
+ // fall back to My Agents, where the partner can be connected by hand.
+ router.push("/agents");
+ } finally {
+ setBusyId(null);
+ }
+ },
+ [isAdmin, router],
+ );
const load = useCallback(async () => {
setLoading(true);
@@ -88,7 +135,7 @@ export default function PartnersPage() {
"Companions with their own soul, library, and channels — reachable from your IM apps.",
)
: t(
- "Partners your administrator has assigned to you. Connect one under My Agents to consult it in chat.",
+ "Partners your administrator has assigned to you. Click one to start chatting with it.",
)}
</p>
</div>
@@ -143,15 +190,9 @@ export default function PartnersPage() {
<button
key={partner.partner_id}
type="button"
- onClick={
- isAdmin
- ? () => router.push(`/partners/${partner.partner_id}`)
- : undefined
- }
- aria-disabled={!isAdmin}
- className={`group flex items-start gap-3 rounded-2xl border border-[var(--border)] p-4 text-left transition-colors ${
- isAdmin ? "hover:border-[var(--ring)]" : "cursor-default"
- }`}
+ onClick={() => void openPartner(partner)}
+ disabled={busyId === partner.partner_id}
+ className="group flex items-start gap-3 rounded-2xl border border-[var(--border)] p-4 text-left transition-colors hover:border-[var(--ring)] disabled:opacity-60"
>
<PartnerAvatar
name={partner.name}
@@ -165,14 +206,18 @@ export default function PartnersPage() {
<span className="truncate text-[14px] font-medium text-[var(--foreground)]">
{partner.name}
</span>
- <span
- title={partner.running ? t("Running") : t("Stopped")}
- className={`h-1.5 w-1.5 shrink-0 rounded-full ${
- partner.running
- ? "bg-emerald-500"
- : "bg-[var(--border)]"
- }`}
- />
+ {busyId === partner.partner_id ? (
+ <Loader2 className="h-3 w-3 shrink-0 animate-spin text-[var(--muted-foreground)]" />
+ ) : (
+ <span
+ title={partner.running ? t("Running") : t("Stopped")}
+ className={`h-1.5 w-1.5 shrink-0 rounded-full ${
+ partner.running
+ ? "bg-emerald-500"
+ : "bg-[var(--border)]"
+ }`}
+ />
+ )}
</div>
{partner.description ? (
<p className="mt-0.5 line-clamp-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index e796439ff..dc8a3ebd2 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2309,6 +2309,9 @@
"Create a partner, give it a soul and a slice of your library, then talk to it here or from Feishu, Telegram, Slack and more.": "Create a partner, give it a soul and a slice of your library, then talk to it here or from Feishu, Telegram, Slack and more.",
"Create your first partner": "Create your first partner",
"No channels connected": "No channels connected",
+ "Partners your administrator has assigned to you. Click one to start chatting with it.": "Partners your administrator has assigned to you. Click one to start chatting with it.",
+ "No partners assigned yet": "No partners assigned yet",
+ "Your administrator hasn't assigned you any partners yet. Once they do, they'll appear here.": "Your administrator hasn't assigned you any partners yet. Once they do, they'll appear here.",
"A companion that lives on your channels and works from its own library.": "A companion that lives on your channels and works from its own library.",
"Identity": "Identity",
"e.g. Ada": "e.g. Ada",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 1aabadd9c..60fbe1a8d 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2309,6 +2309,9 @@
"Create a partner, give it a soul and a slice of your library, then talk to it here or from Feishu, Telegram, Slack and more.": "创建一个伙伴,赋予它灵魂和一部分资料库,然后在这里或飞书、Telegram、Slack 等 IM 中与它对话。",
"Create your first partner": "创建第一个伙伴",
"No channels connected": "未接入频道",
+ "Partners your administrator has assigned to you. Click one to start chatting with it.": "管理员分配给你的伙伴。点击任意一个即可开始与它对话。",
+ "No partners assigned yet": "还没有分配给你的伙伴",
+ "Your administrator hasn't assigned you any partners yet. Once they do, they'll appear here.": "管理员还没有给你分配任何伙伴。一旦分配,它们就会显示在这里。",
"A companion that lives on your channels and works from its own library.": "一个常驻于你频道里的伙伴,用属于它自己的资料库工作。",
"Identity": "身份",
"e.g. Ada": "例如 Ada",