Skip to content

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

fix: partners & multi-user

Bingxi Zhao (Frank)9983c0a3d186
diff --git a/CONTAINERIZATION.md b/CONTAINERIZATION.md
index ff2ea1997..236882217 100644
--- a/CONTAINERIZATION.md
+++ b/CONTAINERIZATION.md
@@ -238,23 +238,29 @@ podman run --rm -d --name deeptutor \
ghcr.io/hkuds/deeptutor:latest
```
-After the container is up, the backend and frontend run as the non-root
-`deeptutor` user — `podman exec deeptutor ps -o user,pid,comm` shows
-`supervisord` as root (PID 1) with its `uvicorn`/`node` children as
-`deeptutor` (UID 1000).
+After the container is up, the backend and frontend always run as the
+non-root `deeptutor` user (UID 1000) — `podman exec deeptutor ps -o user,pid,comm`
+shows the `uvicorn`/`node` children as `deeptutor`. `supervisord` itself
+(PID 1) runs as whatever UID the runtime started it with: root under rootful
+Docker/Podman, or the host user under rootless podman + `userns_mode: keep-id`.
### Supervisord pidfile
-`supervisord` (PID 1) runs as **root**, which owns the `/var/run` tmpfs, so
-it writes `/var/run/supervisord.pid` cleanly even at `mode=0755`. An earlier
-build dropped PID 1 *itself* to the unprivileged `deeptutor` user (via
-`gosu`); that PID 1 couldn't write the root-owned `/var/run` and logged a
-cosmetic `CRIT could not write pidfile /var/run/supervisord.pid` on every
-start under rootless podman. Running supervisord as root and dropping only
-its child programs to `deeptutor` (the `user=` directives above) resolved
-both that CRIT and the fatal `/dev/fd/1,2` EACCES seen under rootful Docker.
-If you ever revert PID 1 to a non-root user, set `/var/run` to `mode=1777`
-(matching `/tmp`) so the pidfile stays writable.
+The `[supervisord]` section carries **no `user=` directive**, so supervisord
+runs as PID 1's UID and never tries to drop its own privilege; only its child
+programs are dropped to `deeptutor` via the per-program `user=` directives.
+Pinning `user=root` here (an earlier design) broke rootless keep-id, where
+PID 1 is the non-root host user and lacks `CAP_SETUID`: supervisord refuses to
+drop privilege and exits at startup with `Can't drop privilege as nonroot
+user` (see supervisord's `options.py`).
+
+The pidfile is written to **`/tmp/supervisord.pid`**. `/tmp` is `mode=1777`
+(world-writable) in every run configuration above, so the pidfile is writable
+whether PID 1 is root or the host UID, and regardless of who owns `/var/run`.
+An earlier build pointed the pidfile at the root-owned `/var/run/supervisord.pid`;
+under rootless keep-id the non-root PID 1 couldn't write it and logged a
+cosmetic `CRIT could not write pidfile` on every start. Putting it in `/tmp`
+removes that dependency on the `/var/run` owner and mode entirely.
---
@@ -321,11 +327,11 @@ you've wired up an external user store.
## Troubleshooting
-**`/var/run/supervisord.pid: Permission denied` on container start.**
-Expected with `read_only: true` and `/var/run` tmpfs at `mode=0755`. The
-supervised children still come up; only the `supervisord` master logs
-this. Fix: change the tmpfs mode to `1777` (match `/tmp`) — see the
-known follow-up note above.
+**`CRIT could not write pidfile /var/run/supervisord.pid` on container start.**
+Only on images built before the pidfile moved to `/tmp/supervisord.pid`
+(`mode=1777`, always writable); current images don't emit it. The supervised
+children come up either way — the line was always cosmetic. Fix: pull a
+current image (or, on an old one, set the `/var/run` tmpfs to `mode=1777`).
**Page loads but Settings says "Backend unreachable".** The UI reaches the
backend through the in-container proxy, not a host port, so this is almost
diff --git a/Dockerfile b/Dockerfile
index 24021fdb6..2024b96da 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -181,26 +181,50 @@ RUN mkdir -p \
data/user/logs \
data/knowledge_bases
-# Bake a non-root user for the supervisord programs. supervisord runs as
-# root (PID 1) and drops each child to this user via the per-program
-# `user=deeptutor` directive, so the backend/frontend processes stay
-# non-root. UID 1000 matches the host user under rootless podman's
-# `userns_mode: keep-id` with a bind mount on ./data.
+# Bake a non-root user (UID 1000) for the supervisord programs. supervisord
+# itself runs as PID 1's UID — root under rootful Docker/Podman, or UID 1000
+# under rootless podman + `userns_mode: keep-id` (where PID 1 is the host
+# user). Each child (backend/frontend) is dropped to this `deeptutor` user via
+# the per-program `user=deeptutor` directive, so the app processes stay
+# non-root in either runtime. UID 1000 also matches the host user under
+# keep-id with a bind mount on ./data.
RUN groupadd --system --gid 1000 deeptutor \
&& useradd --system --uid 1000 --gid 1000 --no-create-home --shell /usr/sbin/nologin deeptutor \
&& chown -R deeptutor:deeptutor /app/data /app/web/.next
-# Create supervisord configuration for running both services
-# Log output goes to stdout/stderr so docker logs can capture them
+# supervisord config is split into two files so the production and development
+# images share one daemon-level [supervisord] section instead of duplicating it:
+# - /etc/supervisor/supervisord.conf — daemon-level settings (shared)
+# - /etc/supervisor/conf.d/programs.conf — the backend/frontend programs
+# Production defines the programs here; the development stage overrides only
+# programs.conf, leaving the shared daemon section untouched.
+# Program output goes to the container's stdout/stderr so `docker logs` captures it.
RUN mkdir -p /etc/supervisor/conf.d
-RUN cat > /etc/supervisor/conf.d/deeptutor.conf <<'EOF'
+# Daemon-level config. No `user=` in [supervisord]: supervisord runs as PID 1's
+# UID (root under rootful; UID 1000 under rootless podman + keep-id, which has
+# no CAP_SETUID and would make a `user=` line fail at startup with
+# "Can't drop privilege as nonroot user" — see supervisord options.py). The
+# pidfile lives in /tmp, which is world-writable, so supervisord can create it
+# whether it runs as root or UID 1000; /var/run is root-owned and not writable
+# by UID 1000 under rootless keep-id.
+RUN cat > /etc/supervisor/supervisord.conf <<'EOF'
[supervisord]
nodaemon=true
logfile=/dev/null
logfile_maxbytes=0
-pidfile=/var/run/supervisord.pid
+pidfile=/tmp/supervisord.pid
+[include]
+files = /etc/supervisor/conf.d/programs.conf
+EOF
+
+RUN sed -i 's/\r$//' /etc/supervisor/supervisord.conf
+
+# Program definitions (production). Each child drops to the unprivileged
+# deeptutor user (UID 1000) via per-program `user=deeptutor`; see the note on
+# the user= design above the daemon config.
+RUN cat > /etc/supervisor/conf.d/programs.conf <<'EOF'
[program:backend]
command=/bin/bash /app/start-backend.sh
directory=/app
@@ -227,7 +251,7 @@ stderr_logfile_maxbytes=0
environment=NODE_ENV="production"
EOF
-RUN sed -i 's/\r$//' /etc/supervisor/conf.d/deeptutor.conf
+RUN sed -i 's/\r$//' /etc/supervisor/conf.d/programs.conf
# Create backend startup script
RUN cat > /app/start-backend.sh <<'EOF'
@@ -358,25 +382,12 @@ echo " - data/user/settings/main.yaml"
echo " - data/user/settings/agents.yaml"
echo "============================================"
-# Run supervisord with PID 1's UID — deliberately omitting `user=` from the
-# [supervisord] section so supervisord inherits whatever UID the container
-# started with (root under rootful Docker/Podman; UID 1000 under rootless
-# podman + userns_mode: keep-id, where PID 1 is the host user).
-#
-# Why no `user=root`: under rootless + keep-id, PID 1 is UID 1000 and has no
-# CAP_SETUID, so forcing `user=root` would make supervisord fail at startup
-# with "Error: Can't drop privilege as nonroot user" (see supervisord
-# options.py — it refuses to drop privileges when not running as root). The
-# previous design with `user=root` worked under rootful but broke rootless.
-#
-# The backend and frontend programs are still dropped to the unprivileged
-# deeptutor user (UID 1000) via per-program `user=deeptutor` in the
-# supervisord config — that setuid works because either (a) PID 1 is root
-# (rootful) and has CAP_SETUID, or (b) PID 1 is already UID 1000 (rootless
-# keep-id) and the setuid is a no-op. /dev/fd/1,2 ownership matches PID 1's
-# UID in both runtimes, so supervisord can write to them without an explicit
-# setuid dance.
-exec /usr/bin/supervisord -c /etc/supervisor/conf.d/deeptutor.conf
+# Hand off to supervisord as PID 1. The daemon-level config deliberately omits
+# `user=` so supervisord inherits PID 1's UID and stays portable across rootful
+# and rootless-keep-id runtimes; children drop to the deeptutor user via
+# per-program `user=`. Full rationale lives next to the [supervisord] section
+# in the build step that writes /etc/supervisor/supervisord.conf.
+exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
EOF
RUN sed -i 's/\r$//' /app/entrypoint.sh && chmod +x /app/entrypoint.sh
@@ -437,15 +448,10 @@ RUN pip install --no-cache-dir \
black \
ruff
-# Override supervisord config for development (with reload)
-# Log output goes to stdout/stderr so docker logs can capture them
-RUN cat > /etc/supervisor/conf.d/deeptutor.conf <<'EOF'
-[supervisord]
-nodaemon=true
-logfile=/dev/null
-logfile_maxbytes=0
-pidfile=/var/run/supervisord.pid
-
+# Development overrides only the program definitions (uvicorn --reload and
+# `next dev`); the shared daemon-level /etc/supervisor/supervisord.conf from
+# the production stage is reused as-is.
+RUN cat > /etc/supervisor/conf.d/programs.conf <<'EOF'
[program:backend]
command=python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port %(ENV_BACKEND_PORT)s --reload --no-access-log
directory=/app
@@ -472,7 +478,7 @@ stderr_logfile_maxbytes=0
environment=NODE_ENV="development"
EOF
-RUN sed -i 's/\r$//' /etc/supervisor/conf.d/deeptutor.conf
+RUN sed -i 's/\r$//' /etc/supervisor/conf.d/programs.conf
# Development ports
EXPOSE 8001 3782
diff --git a/artifacts/deeptutor-poster/deeptutor-technical-poster.html b/artifacts/deeptutor-poster/deeptutor-technical-poster.html
new file mode 100644
index 000000000..fa86b4d43
--- /dev/null
+++ b/artifacts/deeptutor-poster/deeptutor-technical-poster.html
@@ -0,0 +1,912 @@
+<!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>DeepTutor does not hand the model a static toolbox. The visible surface is assembled from learner choices, context flags, active capability tools, and access grants.</p>
+ <div class="mini-list">
+ <div class="mini-item"><span class="dot"></span><span>User-toggled exploration: brainstorm, web search, paper search, deep reasoning.</span></div>
+ <div class="mini-item"><span class="dot blue"></span><span>Context-mounted skills: retrieval, sources, memory, notebooks, workspace actions, follow-up questions.</span></div>
+ <div class="mini-item"><span class="dot rose"></span><span>Capability-owned tools add a deterministic spine only when that mode is active.</span></div>
+ <div class="mini-item"><span class="dot gold"></span><span>Partner and multi-user grants subtract risky tools before the model ever sees them.</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 multi-stage tutoring objective. Most reuse the chat loop; specialist pipelines still emit the same result envelope and event stream.</p>
+ <div class="mini-list">
+ <div class="mini-item"><span class="dot"></span><span>Chat: exploring and responding through one agent loop.</span></div>
+ <div class="mini-item"><span class="dot blue"></span><span>Deep Solve: committed plan, step completion, bounded replans.</span></div>
+ <div class="mini-item"><span class="dot rose"></span><span>Mastery Path: hard per-type gates plus spaced review.</span></div>
+ <div class="mini-item"><span class="dot gold"></span><span>Research, Question, Visualize, and Animator route complex production tasks.</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
new file mode 100644
index 000000000..e7a9fd59d
Binary files /dev/null and b/artifacts/deeptutor-poster/deeptutor-technical-poster.png differ
diff --git a/compose.yaml b/compose.yaml
index 26cb9c8a2..b4acfabd6 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -126,9 +126,10 @@ services:
read_only: true
# Writable surfaces inside the RO rootfs. Each tmpfs is scoped to a
# specific need:
- # /tmp — general scratch for Python, uvicorn, Node, Next.js
+ # /tmp — scratch for Python, uvicorn, Node, Next.js +
+ # supervisord's pidfile (/tmp/supervisord.pid)
# /run — standard Linux runtime dir
- # /var/run — supervisord writes its pidfile here
+ # /var/run — standard runtime dir (kept writable for any tooling)
# /var/log — covers any supervisord child that defaults there
# /root — catches stray $HOME-style writes (image sets
# PYTHONDONTWRITEBYTECODE=1, but be safe)
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index c91e44b33..7d32b0dcd 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -176,7 +176,6 @@ class SupportedFileTypesInfo(BaseModel):
extensions: list[str]
accept: str
max_file_size_bytes: int
- max_pdf_size_bytes: int
IMAGE_ACCEPT_MIME_TYPES = {
@@ -1300,7 +1299,6 @@ async def get_supported_file_types():
extensions=extensions,
accept=",".join(dict.fromkeys(accept_items)),
max_file_size_bytes=DocumentValidator.MAX_FILE_SIZE,
- max_pdf_size_bytes=DocumentValidator.MAX_PDF_SIZE,
)
@@ -1935,15 +1933,10 @@ async def move_kb_file(kb_name: str, payload: MoveFilePayload):
async def serve_kb_raw_file_text_preview(kb_name: str, filename: str):
"""Serve extracted plain text for a raw KB document preview."""
target = _resolve_kb_raw_file_or_404(kb_name, filename)
- max_bytes = (
- DocumentValidator.MAX_PDF_SIZE
- if target.suffix.lower() == ".pdf"
- else DocumentValidator.MAX_FILE_SIZE
- )
try:
text = extract_text_from_path(
target,
- max_bytes=max_bytes,
+ max_bytes=DocumentValidator.MAX_FILE_SIZE,
max_chars=MAX_EXTRACTED_CHARS_PER_DOC,
)
except DocumentExtractionError as exc:
diff --git a/deeptutor/api/routers/subagents.py b/deeptutor/api/routers/subagents.py
index 9f00377fb..2174cf2bb 100644
--- a/deeptutor/api/routers/subagents.py
+++ b/deeptutor/api/routers/subagents.py
@@ -22,9 +22,10 @@ from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
-from deeptutor.api.routers.auth import require_admin, require_auth
+from deeptutor.api.routers.auth import require_admin
from deeptutor.knowledge.kb_types import SUBAGENT_KB_TYPE
from deeptutor.multi_user.knowledge_access import current_kb_manager
+from deeptutor.multi_user.partner_access import assert_partner_allowed, visible_partner_cards
from deeptutor.services.rag.linked_kb import assert_path_allowed
from deeptutor.services.subagent import (
PARTNER_BACKEND_KIND,
@@ -92,6 +93,18 @@ async def sync_backend(kind: str):
return options.to_dict()
[email protected]("/partners")
+async def list_visible_partners():
+ """Partners the current user can connect & consult.
+
+ Returns every partner for an admin, or just the ones an admin has assigned
+ for a non-admin. The partner CRUD API (``/api/v1/partners``) stays fully
+ admin-gated; this is the read surface the connect flow and the partner list
+ page use, so a non-admin sees their assigned partners without a 403.
+ """
+ return {"partners": visible_partner_cards()}
+
+
@router.get("/connections")
async def list_connections():
"""List the current user's connected subagents."""
@@ -116,7 +129,7 @@ async def list_connections():
@router.post("/connections")
-async def create_connection(payload: ConnectSubagentRequest, auth=Depends(require_auth)):
+async def create_connection(payload: ConnectSubagentRequest):
"""Connect a subagent (a local CLI, or one of the user's partners) as a selectable KB.
A partner connection (``agent_kind == "partner"``) binds a ``partner_id``
@@ -134,16 +147,16 @@ async def create_connection(payload: ConnectSubagentRequest, auth=Depends(requir
resolved_cwd = ""
partner_id = ""
if agent_kind == PARTNER_BACKEND_KIND:
- # Partners are anchored to the admin workspace (the whole partners API is
- # admin-gated), and consulting one runs it in that scope. This router is
- # only auth-gated, so gate the partner branch on admin to match — a
- # non-admin must not be able to drive an admin-scoped partner.
- await require_admin(auth)
partner_id = (payload.partner_id or "").strip()
if not partner_id:
raise HTTPException(
status_code=400, detail="A partner_id is required to connect a partner."
)
+ # Partners are admin-managed, but an admin can assign one to a user via
+ # the grant system. An admin may connect any partner; a non-admin only a
+ # partner assigned to them (403 otherwise). The partner still runs in its
+ # own isolated scope — connecting just lets the user consult it in chat.
+ assert_partner_allowed(partner_id)
from deeptutor.services.partners import get_partner_manager
if not get_partner_manager().partner_exists(partner_id):
diff --git a/deeptutor/multi_user/grants.py b/deeptutor/multi_user/grants.py
index 448e15352..b3a11f4c6 100644
--- a/deeptutor/multi_user/grants.py
+++ b/deeptutor/multi_user/grants.py
@@ -20,6 +20,11 @@ def empty_grant(user_id: str) -> dict[str, Any]:
"models": {"llm": []},
"knowledge_bases": [],
"skills": [],
+ # Partners an admin has assigned to this user. Partners stay
+ # admin-managed (the /api/v1/partners CRUD router is admin-gated); a
+ # grant only lets the user *see and consult* the named partners — same
+ # shape as ``skills`` (``[{"partner_id": ...}]``).
+ "partners": [],
# Tool whitelists share the partner-config semantics for built-ins:
# ``enabled_tools=None`` means "default" (every tool in the pool),
# ``[]`` means none, a list is an explicit whitelist. MCP tools can
@@ -64,7 +69,7 @@ def normalize_grant(user_id: str, payload: dict[str, Any] | None) -> dict[str, A
if not isinstance(items, list):
items = []
base["models"]["llm"] = [dict(item) for item in items if isinstance(item, dict)]
- for key in ("knowledge_bases", "skills"):
+ for key in ("knowledge_bases", "skills", "partners"):
values = payload.get(key) if isinstance(payload.get(key), list) else []
base[key] = [dict(item) for item in values if isinstance(item, dict)]
for key in ("enabled_tools", "mcp_tools"):
diff --git a/deeptutor/multi_user/partner_access.py b/deeptutor/multi_user/partner_access.py
new file mode 100644
index 000000000..ca0415c64
--- /dev/null
+++ b/deeptutor/multi_user/partner_access.py
@@ -0,0 +1,85 @@
+"""Partner visibility guards for non-admin users.
+
+Partners are admin-managed, process-wide resources: the whole
+``/api/v1/partners`` CRUD router is admin-gated, and a partner runs in its own
+isolated workspace scope (``data/partners/{id}/``), never the caller's. A
+non-admin can't create or manage partners, but an admin can *assign* specific
+partners to specific users through the grant system — the same mechanism that
+shares knowledge bases and skills.
+
+An assigned user may then see the partner, connect it as a subagent, and
+consult it in chat; the consult still drives the partner in its own scope, so
+the user only ever exchanges messages with it — exactly as when an admin
+consults it. This module is the read-side counterpart of ``skill_access``.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import HTTPException
+
+from .context import get_current_user
+from .grants import load_grant
+
+
+def assigned_partner_ids(user_id: str | None = None) -> set[str]:
+ """The partner ids an admin has assigned to the user (empty for admins)."""
+ user = get_current_user()
+ uid = user_id or user.id
+ return {
+ str(item.get("partner_id") or item.get("id") or "").strip()
+ for item in load_grant(uid).get("partners", []) or []
+ if str(item.get("partner_id") or item.get("id") or "").strip()
+ }
+
+
+def assert_partner_allowed(partner_id: str, user_id: str | None = None) -> None:
+ """Raise 403 when a non-admin tries to use a partner not assigned to them.
+
+ Admins may use any partner; this is a no-op for them (and for single-user
+ deployments, where the current user resolves to the local admin).
+ """
+ user = get_current_user()
+ if user.is_admin:
+ return
+ if str(partner_id or "").strip() not in assigned_partner_ids(user_id or user.id):
+ raise HTTPException(status_code=403, detail="Partner is not assigned to you")
+
+
+# Identity-only card fields a consumer needs (partner list page, connect modal).
+# Deliberately excludes channels / llm_selection / tool config so a non-admin
+# only ever sees a partner's face, never its wiring.
+_CARD_FIELDS = (
+ "partner_id",
+ "name",
+ "description",
+ "emoji",
+ "color",
+ "avatar",
+ "language",
+ "running",
+)
+
+
+def _project_card(partner: dict[str, Any]) -> dict[str, Any]:
+ card = {field: partner.get(field) for field in _CARD_FIELDS}
+ card["partner_id"] = str(partner.get("partner_id") or "")
+ return card
+
+
+def visible_partner_cards() -> list[dict[str, Any]]:
+ """Partners the current user may consult: all for an admin, or just the
+ assigned subset for a non-admin. Returns identity-only card dicts."""
+ from deeptutor.services.partners import get_partner_manager
+
+ everything = get_partner_manager().list_partners()
+ user = get_current_user()
+ if user.is_admin:
+ return [_project_card(item) for item in everything]
+ allowed = assigned_partner_ids(user.id)
+ return [
+ _project_card(item)
+ for item in everything
+ if str(item.get("partner_id") or "") in allowed
+ ]
diff --git a/deeptutor/multi_user/router.py b/deeptutor/multi_user/router.py
index 957d627f5..6a47a6f77 100644
--- a/deeptutor/multi_user/router.py
+++ b/deeptutor/multi_user/router.py
@@ -80,6 +80,23 @@ def _admin_skill_summary() -> list[dict[str, Any]]:
return [item.to_dict() for item in service.list_skills()]
+def _admin_partner_summary() -> list[dict[str, Any]]:
+ """The partners an admin can assign. Partners are process-wide resources
+ anchored at the admin workspace, so this lists them all (identity only — no
+ channel wiring or model selection leaks into the assignable summary)."""
+ from deeptutor.services.partners import get_partner_manager
+
+ return [
+ {
+ "partner_id": str(item.get("partner_id") or ""),
+ "name": item.get("name") or item.get("partner_id") or "",
+ "description": item.get("description") or "",
+ "emoji": item.get("emoji") or "",
+ }
+ for item in get_partner_manager().list_partners()
+ ]
+
+
def _require_assignable_user(user_id: str) -> tuple[str, dict[str, Any]]:
user_record = get_user_by_id(user_id)
if user_record is None:
@@ -104,6 +121,7 @@ async def admin_resources(_: object = Depends(require_admin)) -> dict[str, Any]:
"models": _admin_catalog_summary(),
"knowledge_bases": _admin_kb_summary(),
"skills": _admin_skill_summary(),
+ "partners": _admin_partner_summary(),
"tools": tool_options["tools"],
"mcp_tools": tool_options["mcp_tools"],
}
@@ -133,6 +151,7 @@ async def put_user_grants(
"model_count": len(grant.get("models", {}).get("llm", []) or []),
"kb_count": len(grant.get("knowledge_bases", []) or []),
"skill_count": len(grant.get("skills", []) or []),
+ "partner_count": len(grant.get("partners", []) or []),
"enabled_tools": grant.get("enabled_tools"),
"mcp_tool_count": (
None if grant.get("mcp_tools") is None else len(grant.get("mcp_tools") or [])
diff --git a/deeptutor/services/parsing/engines/text_only/engine.py b/deeptutor/services/parsing/engines/text_only/engine.py
index f890407fd..ae7bc35df 100644
--- a/deeptutor/services/parsing/engines/text_only/engine.py
+++ b/deeptutor/services/parsing/engines/text_only/engine.py
@@ -51,13 +51,10 @@ class TextOnlyParser:
if on_output:
on_output(f"Extracting plain text from {Path(source_path).name}...")
- max_bytes = (
- DocumentValidator.MAX_PDF_SIZE
- if source_path.suffix.lower() == ".pdf"
- else DocumentValidator.MAX_FILE_SIZE
- )
try:
- text = extract_text_from_path(source_path, max_bytes=max_bytes, max_chars=None)
+ text = extract_text_from_path(
+ source_path, max_bytes=DocumentValidator.MAX_FILE_SIZE, max_chars=None
+ )
except (DocumentExtractionError, OSError) as exc:
raise ParserError(
f"text-only extraction failed for {Path(source_path).name}: {exc}"
diff --git a/deeptutor/services/partners/manager.py b/deeptutor/services/partners/manager.py
index 9303ead07..434f18ff4 100644
--- a/deeptutor/services/partners/manager.py
+++ b/deeptutor/services/partners/manager.py
@@ -36,7 +36,7 @@ from deeptutor.services.partners.workspace import (
logger = logging.getLogger(__name__)
_RESERVED_NAMES = {"workspace", "media", "sessions", "_souls"}
-_ID_SAFE_RE = re.compile(r"[^a-z0-9-]+")
+_HYPHEN_RUN_RE = re.compile(r"-+")
LEGACY_GLOBAL_DELIVERY_KEYS = frozenset(
{"send_progress", "send_tool_hints", "sendProgress", "sendToolHints"}
)
@@ -92,7 +92,13 @@ def strip_legacy_global_delivery(channels: dict[str, Any]) -> dict[str, Any]:
def slugify_partner_id(name: str) -> str:
- slug = _ID_SAFE_RE.sub("-", name.strip().lower()).strip("-")
+ # Keep Unicode letters/digits so non-Latin names (e.g. 中文) survive as a
+ # readable id; collapse every other run of characters to a single hyphen.
+ # ``isalnum`` is Unicode-aware and (unlike ``\w``) excludes underscore, so
+ # an id can never collide with the reserved ``_souls`` directory. ASCII is
+ # lower-cased; case-less scripts (CJK, …) pass through unchanged.
+ cleaned = "".join(c if c.isalnum() else "-" for c in name.strip().lower())
+ slug = _HYPHEN_RUN_RE.sub("-", cleaned).strip("-")
return slug or "partner"
diff --git a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
index 2d3323d44..2b93646a5 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
@@ -62,13 +62,10 @@ class LlamaIndexDocumentLoader:
return documents
def _extract_parser_text(self, file_path: Path) -> str:
- max_bytes = (
- DocumentValidator.MAX_PDF_SIZE
- if file_path.suffix.lower() == ".pdf"
- else DocumentValidator.MAX_FILE_SIZE
- )
try:
- return extract_text_from_path(file_path, max_bytes=max_bytes, max_chars=None)
+ return extract_text_from_path(
+ file_path, max_bytes=DocumentValidator.MAX_FILE_SIZE, max_chars=None
+ )
except (DocumentExtractionError, OSError) as exc:
self.logger.error(f"Failed to extract {file_path.name}: {exc}")
return ""
diff --git a/deeptutor/utils/document_validator.py b/deeptutor/utils/document_validator.py
index 442619644..25571dbf1 100644
--- a/deeptutor/utils/document_validator.py
+++ b/deeptutor/utils/document_validator.py
@@ -13,11 +13,8 @@ import unicodedata
class DocumentValidator:
"""Document validation utilities"""
- # Maximum file size in bytes (100MB)
- MAX_FILE_SIZE: ClassVar[int] = 100 * 1024 * 1024
-
- # Maximum file size for PDF processing (50MB to prevent resource exhaustion)
- MAX_PDF_SIZE: ClassVar[int] = 50 * 1024 * 1024
+ # Maximum file size in bytes (200MB), applied uniformly to every format.
+ MAX_FILE_SIZE: ClassVar[int] = 200 * 1024 * 1024
# Allowed file extensions
ALLOWED_EXTENSIONS: ClassVar[set[str]] = {
@@ -96,12 +93,6 @@ class DocumentValidator:
if not safe_name or safe_name in (".", "..") or safe_name.strip("_") == "":
raise ValueError("Invalid filename")
- # Additional size check for PDFs to prevent resource exhaustion
- if ext == ".pdf" and file_size is not None and file_size > DocumentValidator.MAX_PDF_SIZE:
- raise ValueError(
- f"PDF file too large: {file_size} bytes. Maximum allowed for PDFs: {DocumentValidator.MAX_PDF_SIZE} bytes"
- )
-
# Check file extension
exts_to_check = allowed_extensions or DocumentValidator.ALLOWED_EXTENSIONS
if ext not in exts_to_check:
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index 296f0d2c4..0d26bf53f 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -194,7 +194,8 @@ def test_supported_file_types_returns_upload_policy() -> None:
assert ".pptx" in payload["extensions"]
assert ".md" in payload["extensions"]
assert ".png" in payload["extensions"]
- assert payload["max_file_size_bytes"] > payload["max_pdf_size_bytes"] > 0
+ assert payload["max_file_size_bytes"] > 0
+ assert "max_pdf_size_bytes" not in payload
assert ".pdf" in payload["accept"]
assert ".docx" in payload["accept"]
assert ".png" in payload["accept"]
diff --git a/tests/api/test_subagents_router.py b/tests/api/test_subagents_router.py
index b41b5a266..0ba7047da 100644
--- a/tests/api/test_subagents_router.py
+++ b/tests/api/test_subagents_router.py
@@ -161,6 +161,38 @@ def test_connect_partner_binds_partner_id(client, monkeypatch):
assert listed[0]["partner_id"] == "paul"
+def test_list_visible_partners(client, monkeypatch):
+ monkeypatch.setattr(
+ subagents_module,
+ "visible_partner_cards",
+ lambda: [{"partner_id": "p1", "name": "P1", "emoji": "🤖"}],
+ )
+ res = client.get("/api/v1/subagents/partners")
+ assert res.status_code == 200
+ partners = res.json()["partners"]
+ assert partners == [{"partner_id": "p1", "name": "P1", "emoji": "🤖"}]
+
+
+def test_connect_partner_denied_when_not_assigned(client, monkeypatch):
+ # A non-admin connecting an unassigned partner is rejected by the
+ # assignment guard before the connection is created.
+ from fastapi import HTTPException
+
+ _patch_partner_existence(monkeypatch, {"paul"})
+
+ def deny(_pid):
+ raise HTTPException(status_code=403, detail="Partner is not assigned to you")
+
+ monkeypatch.setattr(subagents_module, "assert_partner_allowed", deny)
+ res = client.post(
+ "/api/v1/subagents/connections",
+ json={"name": "Paul", "agent_kind": "partner", "partner_id": "paul"},
+ )
+ assert res.status_code == 403
+ # Nothing was connected.
+ assert client.get("/api/v1/subagents/connections").json()["connections"] == []
+
+
def test_connect_partner_requires_partner_id(client, monkeypatch):
_patch_partner_existence(monkeypatch, {"paul"})
res = client.post(
diff --git a/tests/multi_user/test_partner_access.py b/tests/multi_user/test_partner_access.py
new file mode 100644
index 000000000..8c05a8a94
--- /dev/null
+++ b/tests/multi_user/test_partner_access.py
@@ -0,0 +1,144 @@
+"""Partner assignment / visibility for non-admin users."""
+
+from __future__ import annotations
+
+from fastapi import HTTPException
+import pytest
+
+from deeptutor.multi_user import partner_access
+from deeptutor.multi_user.grants import empty_grant, normalize_grant
+
+
+class _FakeManager:
+ def __init__(self, partners: list[dict]) -> None:
+ self._partners = partners
+
+ def list_partners(self) -> list[dict]:
+ return self._partners
+
+
+def _patch_manager(monkeypatch, partners: list[dict]) -> None:
+ import deeptutor.services.partners as pkg
+
+ monkeypatch.setattr(pkg, "get_partner_manager", lambda: _FakeManager(partners))
+
+
+# ── Grant shape ───────────────────────────────────────────────
+
+
+def test_empty_grant_has_partners_list():
+ assert empty_grant("u")["partners"] == []
+
+
+def test_normalize_grant_round_trips_partners():
+ grant = normalize_grant(
+ "u_alice",
+ {"partners": [{"partner_id": "p1"}, {"id": "p2"}, "not-a-dict", {}]},
+ )
+ # Non-dict entries are dropped; dict entries (even empty) survive.
+ assert grant["partners"] == [{"partner_id": "p1"}, {"id": "p2"}, {}]
+
+
+def test_normalize_grant_missing_partners_defaults_empty():
+ assert normalize_grant("u_alice", {"skills": []})["partners"] == []
+
+
+# ── assigned_partner_ids ──────────────────────────────────────
+
+
+def test_assigned_partner_ids_reads_grant(as_user, monkeypatch):
+ monkeypatch.setattr(
+ partner_access,
+ "load_grant",
+ lambda uid: {"partners": [{"partner_id": "p1"}, {"id": "p2"}, {"partner_id": " "}]},
+ )
+ with as_user("u_alice", role="user"):
+ assert partner_access.assigned_partner_ids() == {"p1", "p2"}
+
+
+# ── assert_partner_allowed ────────────────────────────────────
+
+
+def test_admin_may_use_any_partner(as_user, monkeypatch):
+ # Admin short-circuits before any grant lookup.
+ monkeypatch.setattr(
+ partner_access,
+ "load_grant",
+ lambda uid: (_ for _ in ()).throw(AssertionError("admin must not read grants")),
+ )
+ with as_user("u_admin", role="admin"):
+ partner_access.assert_partner_allowed("anything") # no raise
+
+
+def test_non_admin_allowed_only_for_assigned(as_user, monkeypatch):
+ monkeypatch.setattr(
+ partner_access, "load_grant", lambda uid: {"partners": [{"partner_id": "p1"}]}
+ )
+ with as_user("u_alice", role="user"):
+ partner_access.assert_partner_allowed("p1") # assigned → ok
+ with pytest.raises(HTTPException) as exc:
+ partner_access.assert_partner_allowed("p2")
+ assert exc.value.status_code == 403
+
+
+# ── visible_partner_cards ─────────────────────────────────────
+
+
+def test_admin_sees_all_partners_identity_only(as_user, monkeypatch):
+ _patch_manager(
+ monkeypatch,
+ [
+ {"partner_id": "p1", "name": "P1", "emoji": "🤖", "channels": ["telegram"]},
+ {"partner_id": "p2", "name": "P2", "channels": [], "llm_selection": {"x": "y"}},
+ ],
+ )
+ with as_user("u_admin", role="admin"):
+ cards = partner_access.visible_partner_cards()
+ assert {c["partner_id"] for c in cards} == {"p1", "p2"}
+ # Identity only — channel wiring / model selection must not leak to a card.
+ assert all("channels" not in c and "llm_selection" not in c for c in cards)
+
+
+def test_non_admin_sees_only_assigned_partners(as_user, monkeypatch):
+ _patch_manager(
+ monkeypatch,
+ [{"partner_id": "p1", "name": "P1"}, {"partner_id": "p2", "name": "P2"}],
+ )
+ monkeypatch.setattr(
+ partner_access, "load_grant", lambda uid: {"partners": [{"partner_id": "p2"}]}
+ )
+ with as_user("u_alice", role="user"):
+ cards = partner_access.visible_partner_cards()
+ assert [c["partner_id"] for c in cards] == ["p2"]
+
+
+def test_non_admin_with_no_grant_sees_nothing(as_user, monkeypatch):
+ _patch_manager(monkeypatch, [{"partner_id": "p1", "name": "P1"}])
+ monkeypatch.setattr(partner_access, "load_grant", lambda uid: empty_grant(uid))
+ with as_user("u_alice", role="user"):
+ assert partner_access.visible_partner_cards() == []
+
+
+# ── assignable pool (admin side) ──────────────────────────────
+
+
+def test_admin_partner_summary_is_identity_only(monkeypatch):
+ from deeptutor.multi_user import router
+
+ _patch_manager(
+ monkeypatch,
+ [
+ {
+ "partner_id": "p1",
+ "name": "Tutor",
+ "description": "math",
+ "emoji": "🤖",
+ "channels": ["telegram"],
+ "llm_selection": {"x": "y"},
+ }
+ ],
+ )
+ summary = router._admin_partner_summary()
+ assert summary == [
+ {"partner_id": "p1", "name": "Tutor", "description": "math", "emoji": "🤖"}
+ ]
diff --git a/web/app/(workspace)/partners/page.tsx b/web/app/(workspace)/partners/page.tsx
index c2a520f28..d1e516009 100644
--- a/web/app/(workspace)/partners/page.tsx
+++ b/web/app/(workspace)/partners/page.tsx
@@ -11,6 +11,11 @@ import { useRouter } from "next/navigation";
import { HeartHandshake, Loader2, Plus } from "lucide-react";
import { useTranslation } from "react-i18next";
import { listPartners, type PartnerInfo } from "@/lib/partners-api";
+import {
+ listConnectablePartners,
+ type ConnectablePartner,
+} from "@/lib/subagents-api";
+import { useAuthStatus } from "@/hooks/useAuthStatus";
import ChannelIcon from "@/components/partners/ChannelIcon";
import PartnerAvatar from "@/components/partners/PartnerAvatar";
@@ -23,26 +28,52 @@ function channelNames(partner: PartnerInfo): string[] {
return [];
}
+function asPartnerInfo(card: ConnectablePartner): PartnerInfo {
+ // A non-admin only ever sees identity cards (no channel wiring); normalize
+ // into the shape the card grid renders, with no channels.
+ return {
+ partner_id: card.partner_id,
+ name: card.name,
+ description: card.description || "",
+ channels: [],
+ emoji: card.emoji,
+ color: card.color,
+ avatar: card.avatar,
+ language: card.language,
+ running: Boolean(card.running),
+ started_at: null,
+ };
+}
+
export default function PartnersPage() {
const router = useRouter();
const { t } = useTranslation();
+ // Partners are admin-managed: an admin sees & manages every partner, while a
+ // non-admin sees only the partners assigned to them, read-only (creation and
+ // editing stay admin-only). The list source differs accordingly.
+ const { isAdmin, loading: authLoading } = useAuthStatus();
const [partners, setPartners] = useState<PartnerInfo[]>([]);
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
setLoading(true);
try {
- setPartners(await listPartners());
+ if (isAdmin) {
+ setPartners(await listPartners());
+ } else {
+ setPartners((await listConnectablePartners()).map(asPartnerInfo));
+ }
} catch {
setPartners([]);
} finally {
setLoading(false);
}
- }, []);
+ }, [isAdmin]);
useEffect(() => {
+ if (authLoading) return;
void load();
- }, [load]);
+ }, [authLoading, load]);
return (
<div className="mx-auto h-full max-w-4xl overflow-y-auto px-6 py-8">
@@ -52,18 +83,24 @@ export default function PartnersPage() {
{t("Partners")}
</h1>
<p className="mt-1 text-[12.5px] text-[var(--muted-foreground)]">
- {t(
- "Companions with their own soul, library, and channels — reachable from your IM apps.",
- )}
+ {isAdmin
+ ? t(
+ "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.",
+ )}
</p>
</div>
- <Link
- href="/partners/new"
- className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[12.5px] font-medium text-[var(--primary-foreground)] hover:opacity-90"
- >
- <Plus className="h-3.5 w-3.5" />
- {t("New partner")}
- </Link>
+ {isAdmin ? (
+ <Link
+ href="/partners/new"
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[12.5px] font-medium text-[var(--primary-foreground)] hover:opacity-90"
+ >
+ <Plus className="h-3.5 w-3.5" />
+ {t("New partner")}
+ </Link>
+ ) : null}
</header>
{loading ? (
@@ -77,20 +114,26 @@ export default function PartnersPage() {
strokeWidth={1.5}
/>
<p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("No partners yet")}
+ {isAdmin ? t("No partners yet") : t("No partners assigned yet")}
</p>
<p className="mt-1.5 max-w-sm text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">
- {t(
- "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.",
- )}
+ {isAdmin
+ ? t(
+ "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.",
+ )
+ : t(
+ "Your administrator hasn't assigned you any partners yet. Once they do, they'll appear here.",
+ )}
</p>
- <Link
- href="/partners/new"
- className="mt-4 inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[12.5px] font-medium text-[var(--primary-foreground)]"
- >
- <Plus className="h-3.5 w-3.5" />
- {t("Create your first partner")}
- </Link>
+ {isAdmin ? (
+ <Link
+ href="/partners/new"
+ className="mt-4 inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[12.5px] font-medium text-[var(--primary-foreground)]"
+ >
+ <Plus className="h-3.5 w-3.5" />
+ {t("Create your first partner")}
+ </Link>
+ ) : null}
</div>
) : (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
@@ -100,8 +143,15 @@ export default function PartnersPage() {
<button
key={partner.partner_id}
type="button"
- onClick={() => router.push(`/partners/${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)]"
+ 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"
+ }`}
>
<PartnerAvatar
name={partner.name}
diff --git a/web/components/agents/ConnectedAgents.tsx b/web/components/agents/ConnectedAgents.tsx
index bdbe40850..6e7ea335b 100644
--- a/web/components/agents/ConnectedAgents.tsx
+++ b/web/components/agents/ConnectedAgents.tsx
@@ -7,12 +7,13 @@ import { Cpu, Loader2, Plug, Plus, Trash2, X } from "lucide-react";
import { agentGlyph } from "@/components/agents/agent-icons";
import PartnerAvatar from "@/components/partners/PartnerAvatar";
import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";
-import { listPartners, type PartnerInfo } from "@/lib/partners-api";
import {
connectSubagent,
detectSubagents,
disconnectSubagent,
+ listConnectablePartners,
listSubagentConnections,
+ type ConnectablePartner,
type SubagentBackendInfo,
type SubagentConnection,
} from "@/lib/subagents-api";
@@ -45,7 +46,7 @@ export default function ConnectedAgents() {
const [backends, setBackends] = useState<SubagentBackendInfo[]>([]);
const [connections, setConnections] = useState<SubagentConnection[]>([]);
- const [partners, setPartners] = useState<PartnerInfo[]>([]);
+ const [partners, setPartners] = useState<ConnectablePartner[]>([]);
const [loading, setLoading] = useState(true);
const [modalOpen, setModalOpen] = useState(false);
const [busyName, setBusyName] = useState<string | null>(null);
@@ -56,7 +57,7 @@ export default function ConnectedAgents() {
const [detected, conns, parts] = await Promise.all([
detectSubagents().catch(() => [] as SubagentBackendInfo[]),
listSubagentConnections().catch(() => [] as SubagentConnection[]),
- listPartners().catch(() => [] as PartnerInfo[]),
+ listConnectablePartners().catch(() => [] as ConnectablePartner[]),
]);
setBackends(detected);
setConnections(conns);
@@ -239,7 +240,7 @@ function ConnectModal({
onConnected,
}: {
backends: SubagentBackendInfo[];
- partners: PartnerInfo[];
+ partners: ConnectablePartner[];
existingNames: string[];
tr: (l: Lang) => string;
onClose: () => void;
diff --git a/web/components/knowledge/FileDropZone.tsx b/web/components/knowledge/FileDropZone.tsx
index 4a5feb49d..5eab9eb49 100644
--- a/web/components/knowledge/FileDropZone.tsx
+++ b/web/components/knowledge/FileDropZone.tsx
@@ -224,10 +224,6 @@ export default function FileDropZone({
{uploadPolicy.extensions.length} {t("types")} ·{" "}
{t("Maximum file size: {{size}}", {
size: formatFileSize(uploadPolicy.max_file_size_bytes),
- })}{" "}
- ·{" "}
- {t("PDF limit: {{size}}", {
- size: formatFileSize(uploadPolicy.max_pdf_size_bytes),
})}
</p>
)}
diff --git a/web/features/multi-user/components/GrantEditor.tsx b/web/features/multi-user/components/GrantEditor.tsx
index eb89f0fe3..409842645 100644
--- a/web/features/multi-user/components/GrantEditor.tsx
+++ b/web/features/multi-user/components/GrantEditor.tsx
@@ -14,6 +14,7 @@ function emptyGrant(userId: string): GrantPayload {
models: { llm: [] },
knowledge_bases: [],
skills: [],
+ partners: [],
enabled_tools: null,
mcp_tools: null,
exec_enabled: null,
@@ -176,6 +177,13 @@ export function GrantEditor({ userId }: { userId: string }) {
),
[grant.skills],
);
+ const partnerIds = useMemo(
+ () =>
+ new Set(
+ grant.partners.map((item) => String(item.partner_id || item.id || "")),
+ ),
+ [grant.partners],
+ );
const selectedModelCount = useMemo(
() =>
@@ -244,6 +252,19 @@ export function GrantEditor({ userId }: { userId: string }) {
});
}
+ function togglePartner(partnerId: string, name: string) {
+ setGrant((current) => {
+ const next = structuredClone(current) as GrantPayload;
+ const exists = partnerIds.has(partnerId);
+ next.partners = exists
+ ? next.partners.filter(
+ (item) => String(item.partner_id || item.id || "") !== partnerId,
+ )
+ : [...next.partners, { partner_id: partnerId, name, source: "admin" }];
+ return next;
+ });
+ }
+
function setToolList(
key: "enabled_tools" | "mcp_tools",
value: string[] | null,
@@ -349,6 +370,9 @@ export function GrantEditor({ userId }: { userId: string }) {
<span className="rounded-full bg-[var(--muted)]/60 px-2 py-1">
{skillIds.size} skills
</span>
+ <span className="rounded-full bg-[var(--muted)]/60 px-2 py-1">
+ {partnerIds.size} partners
+ </span>
<span className="rounded-full bg-[var(--muted)]/60 px-2 py-1">
{toolsSummary}
</span>
@@ -424,6 +448,32 @@ export function GrantEditor({ userId }: { userId: string }) {
))}
</div>
</section>
+ <section className="min-w-0">
+ <SectionTitle>Partners</SectionTitle>
+ <div className="space-y-1.5 text-xs">
+ {(resources?.partners || []).length === 0 ? (
+ <p className="px-1 text-[11px] leading-relaxed text-[var(--muted-foreground)]">
+ No partners yet. Create one under Partners to assign it.
+ </p>
+ ) : (
+ (resources?.partners || []).map((partner) => (
+ <CheckRow
+ key={partner.partner_id}
+ label={partner.name || partner.partner_id}
+ description={partner.description}
+ checked={partnerIds.has(partner.partner_id)}
+ disabled={controlsDisabled}
+ onToggle={() =>
+ togglePartner(
+ partner.partner_id,
+ partner.name || partner.partner_id,
+ )
+ }
+ />
+ ))
+ )}
+ </div>
+ </section>
<section className="min-w-0">
<SectionTitle>System tools</SectionTitle>
diff --git a/web/features/multi-user/types.ts b/web/features/multi-user/types.ts
index 1017c170a..c3ccf98c4 100644
--- a/web/features/multi-user/types.ts
+++ b/web/features/multi-user/types.ts
@@ -6,6 +6,8 @@ export type GrantPayload = {
};
knowledge_bases: Array<Record<string, unknown>>;
skills: Array<Record<string, unknown>>;
+ /** Admin-assigned partners the user may see & consult ([{ partner_id }]). */
+ partners: Array<Record<string, unknown>>;
/** null = default (all system tools), [] = none, array = whitelist. */
enabled_tools: string[] | null;
/** null = default (all MCP tools), [] = none, array = whitelist. */
@@ -36,6 +38,7 @@ export type MultiUserResources = {
source: "admin";
}>;
skills: Array<{ name: string; description?: string; tags?: string[] }>;
+ partners: Array<{ partner_id: string; name: string; description?: string }>;
tools: ToolOption[];
mcp_tools: McpToolOption[];
};
diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.ts
index 1562911ad..1efe9749e 100644
--- a/web/lib/knowledge-api.ts
+++ b/web/lib/knowledge-api.ts
@@ -102,7 +102,6 @@ export interface KnowledgeUploadPolicy {
extensions: string[];
accept: string;
max_file_size_bytes: number;
- max_pdf_size_bytes: number;
}
export interface KnowledgeBaseFile {
@@ -160,11 +159,7 @@ function normalizeUploadPolicy(data: unknown): KnowledgeUploadPolicy {
max_file_size_bytes:
typeof payload?.max_file_size_bytes === "number"
? payload.max_file_size_bytes
- : 100 * 1024 * 1024,
- max_pdf_size_bytes:
- typeof payload?.max_pdf_size_bytes === "number"
- ? payload.max_pdf_size_bytes
- : 50 * 1024 * 1024,
+ : 200 * 1024 * 1024,
};
}
diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.ts
index 456502003..939ec1905 100644
--- a/web/lib/knowledge-helpers.ts
+++ b/web/lib/knowledge-helpers.ts
@@ -4,14 +4,12 @@ export interface KnowledgeUploadPolicy {
extensions: string[];
accept: string;
max_file_size_bytes: number;
- max_pdf_size_bytes: number;
}
export const DEFAULT_UPLOAD_POLICY: KnowledgeUploadPolicy = {
extensions: [],
accept: "",
- max_file_size_bytes: 100 * 1024 * 1024,
- max_pdf_size_bytes: 50 * 1024 * 1024,
+ max_file_size_bytes: 200 * 1024 * 1024,
};
export interface ProgressInfo {
@@ -224,13 +222,6 @@ export function validateFiles(
if (allowedExtensions.size > 0 && !allowedExtensions.has(extension)) {
error = t("Unsupported file type");
- } else if (
- extension === ".pdf" &&
- file.size > uploadPolicy.max_pdf_size_bytes
- ) {
- error = t("PDF files must be smaller than {{size}}.", {
- size: formatFileSize(uploadPolicy.max_pdf_size_bytes),
- });
} else if (file.size > uploadPolicy.max_file_size_bytes) {
error = t("This file exceeds the maximum size of {{size}}.", {
size: formatFileSize(uploadPolicy.max_file_size_bytes),
diff --git a/web/lib/proxy-policy.ts b/web/lib/proxy-policy.ts
new file mode 100644
index 000000000..320d3867f
--- /dev/null
+++ b/web/lib/proxy-policy.ts
@@ -0,0 +1,68 @@
+// Pure request-routing policy for the Next.js middleware (web/proxy.ts).
+//
+// This module deliberately carries NO dependency on `next/server`: it answers
+// "what should happen to this request?" as plain, side-effect-free functions,
+// while proxy.ts stays a thin adapter that turns those answers into
+// NextResponse objects. Keeping the policy pure means the routing/auth rules
+// can be unit-tested in the node harness without booting the Next runtime.
+
+export const LOGIN_PATH = "/login";
+export const COOKIE_NAME = "dt_token";
+
+// Paths whose responses come from the backend, not the Next app. The middleware
+// rewrites these to DEEPTUTOR_API_BASE_URL so the browser can use frontend-
+// relative URLs (e.g. `:3782/api/v1/...` or `.../ws`) and let the rewrite
+// bridge the origin gap.
+export function isBackendPath(pathname: string): boolean {
+ return pathname.startsWith("/api/") || pathname.startsWith("/ws/");
+}
+
+// Static assets served straight out of `web/public` (logos, favicons, fonts,
+// provider icons, …). These must bypass the auth gate even in multi-user mode:
+// the Next image optimizer re-fetches a referenced public image over a
+// server-side loopback request that carries NO auth cookie, so gating the path
+// bounces that fetch to /login and the `<Image>` renders as a broken icon
+// (issue #599 — broken logo/banner after login). Public assets are
+// non-sensitive by design, so allowing them through is safe.
+const STATIC_ASSET =
+ /\.(?:png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf|otf|txt|json|map|css|js)$/i;
+
+// Paths the auth gate must never block: the auth pages themselves, Next.js
+// internals, and public static assets (see STATIC_ASSET above).
+export function isAuthExempt(pathname: string): boolean {
+ return (
+ pathname.startsWith(LOGIN_PATH) ||
+ pathname.startsWith("/register") ||
+ pathname.startsWith("/_next") ||
+ pathname.startsWith("/favicon") ||
+ STATIC_ASSET.test(pathname)
+ );
+}
+
+export type TokenState = "missing" | "malformed" | "expired" | "valid";
+
+// Classify the auth cookie WITHOUT trusting its signature — the middleware is a
+// cheap front-line gate, not the authority (the backend does real verification
+// on every API call). `nowMs` is injected rather than read from the clock so
+// the classifier stays pure and testable.
+export function classifyToken(
+ token: string | undefined,
+ nowMs: number,
+): TokenState {
+ if (!token) return "missing";
+
+ // Expect a JWT: header.payload.signature
+ const parts = token.split(".");
+ if (parts.length !== 3) return "malformed";
+
+ try {
+ const payload = JSON.parse(
+ Buffer.from(parts[1], "base64url").toString("utf-8"),
+ );
+ if (payload.exp && nowMs >= payload.exp * 1000) return "expired";
+ } catch {
+ return "malformed";
+ }
+
+ return "valid";
+}
diff --git a/web/lib/subagents-api.ts b/web/lib/subagents-api.ts
index 276ceaa0c..46bcbdaf8 100644
--- a/web/lib/subagents-api.ts
+++ b/web/lib/subagents-api.ts
@@ -21,6 +21,31 @@ export interface SubagentConnection {
updated_at?: string | null;
}
+/**
+ * A partner the current user may connect & consult. Admins get every partner;
+ * non-admins get only the partners an admin has assigned to them. Identity-only
+ * (no channel wiring / model selection) — that's what the connect flow needs.
+ */
+export interface ConnectablePartner {
+ partner_id: string;
+ name: string;
+ description?: string;
+ emoji?: string;
+ color?: string;
+ avatar?: string;
+ language?: string;
+ running?: boolean;
+}
+
+export async function listConnectablePartners(): Promise<ConnectablePartner[]> {
+ const res = await apiFetch(apiUrl("/api/v1/subagents/partners"), {
+ cache: "no-store",
+ });
+ if (!res.ok) throw new Error(`Request failed: ${res.status}`);
+ const data = (await res.json()) as { partners: ConnectablePartner[] };
+ return data.partners ?? [];
+}
+
export async function detectSubagents(): Promise<SubagentBackendInfo[]> {
const res = await apiFetch(apiUrl("/api/v1/subagents/detect"), {
cache: "no-store",
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index b5c974df7..e796439ff 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -1200,7 +1200,6 @@
"Needs attention": "Needs attention",
"Supported formats": "Supported formats",
"Maximum file size: {{size}}": "Maximum file size: {{size}}",
- "PDF limit: {{size}}": "PDF limit: {{size}}",
"types": "types",
"Click to browse supported documents": "Click to browse supported documents",
"This knowledge base needs reindex before it can accept new files.": "This knowledge base needs reindex before it can accept new files.",
@@ -1213,7 +1212,6 @@
"Waiting for live progress...": "Waiting for live progress...",
"Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.": "Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.",
"This file exceeds the maximum size of {{size}}.": "This file exceeds the maximum size of {{size}}.",
- "PDF files must be smaller than {{size}}.": "PDF files must be smaller than {{size}}.",
"Some dragged files are not supported": "Some dragged files are not supported",
"Drop files to add them": "Drop files to add them",
"Release to attach the files": "Release to attach the files",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 2fcfb7e5b..1aabadd9c 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -1301,7 +1301,6 @@
"Needs attention": "需要处理",
"Supported formats": "支持的格式",
"Maximum file size: {{size}}": "单个文件最大:{{size}}",
- "PDF limit: {{size}}": "PDF 限制:{{size}}",
"Click to browse supported documents": "点击选择受支持的文档",
"This knowledge base needs reindex before it can accept new files.": "这个知识库需要先重新索引,之后才能接收新文件。",
"The last processing run failed.": "上一次处理失败了。",
@@ -1313,7 +1312,6 @@
"Waiting for live progress...": "正在等待实时进度…",
"Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.": "知识库初始化完成后,这里会把它当作可复用资源展示,而不是一直保留陈旧的完成提示。",
"This file exceeds the maximum size of {{size}}.": "该文件超过了 {{size}} 的大小限制。",
- "PDF files must be smaller than {{size}}.": "PDF 文件必须小于 {{size}}。",
"Some dragged files are not supported": "拖拽的文件里有不受支持的类型",
"Drop files to add them": "松开即可添加这些文件",
"Release to attach the files": "松开以上传这些文件",
diff --git a/web/next.config.js b/web/next.config.js
index fa5a552ad..218bddfd9 100644
--- a/web/next.config.js
+++ b/web/next.config.js
@@ -91,11 +91,11 @@ const nextConfig = {
// web/proxy.ts (the Next.js middleware) forwards /api/* and /ws/* to the
// backend by buffering and re-issuing the request. Next caps the buffered
// request body at 10MB by default, but the backend accepts uploads up to
- // 100MB (DocumentValidator.MAX_FILE_SIZE). Raise the proxy cap to match (plus
+ // 200MB (DocumentValidator.MAX_FILE_SIZE). Raise the proxy cap to match (plus
// multipart overhead headroom) so knowledge-base document uploads aren't
// silently truncated when they pass through the proxy.
experimental: {
- proxyClientMaxBodySize: 110 * 1024 * 1024,
+ proxyClientMaxBodySize: 210 * 1024 * 1024,
},
// Move dev indicator to bottom-right corner
diff --git a/web/proxy.ts b/web/proxy.ts
index 762d8093e..f758a9c65 100644
--- a/web/proxy.ts
+++ b/web/proxy.ts
@@ -1,8 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { parseAuthEnabled } from "./lib/api";
+import {
+ COOKIE_NAME,
+ LOGIN_PATH,
+ classifyToken,
+ isAuthExempt,
+ isBackendPath,
+} from "./lib/proxy-policy";
-// Backend base URL for `/api/*` and `/ws/*` rewrites. The container
-// entrypoint exports `DEEPTUTOR_API_BASE_URL` from `data/user/settings/system.json`
+// Backend base URL for `/api/*` and `/ws/*` rewrites. The container entrypoint
+// exports `DEEPTUTOR_API_BASE_URL` from `data/user/settings/system.json`
// (preferring `next_public_api_base`, then `next_public_api_base_external`,
// then `http://localhost:${BACKEND_PORT}`). In dev (`deeptutor start`) it
// defaults to `http://localhost:8001`.
@@ -10,76 +17,43 @@ const API_BASE_URL =
process.env.DEEPTUTOR_API_BASE_URL ?? "http://localhost:8001";
const AUTH_ENABLED = parseAuthEnabled(process.env.DEEPTUTOR_AUTH_ENABLED);
-const LOGIN_PATH = "/login";
-const COOKIE_NAME = "dt_token";
-export function proxy(req: NextRequest) {
+// Redirect to the login page, preserving the intended destination in `next`.
+// A present-but-invalid cookie is cleared so the browser stops resending it;
+// when no cookie was sent there is nothing to clear.
+function redirectToLogin(
+ req: NextRequest,
+ { clearCookie }: { clearCookie: boolean },
+): NextResponse {
+ const loginUrl = req.nextUrl.clone();
+ loginUrl.pathname = LOGIN_PATH;
+ loginUrl.searchParams.set("next", req.nextUrl.pathname);
+ const response = NextResponse.redirect(loginUrl);
+ if (clearCookie) response.cookies.delete(COOKIE_NAME);
+ return response;
+}
+
+export function proxy(req: NextRequest): NextResponse {
const { pathname, search } = req.nextUrl;
- // Forward all backend-relative paths to the configured backend. The browser
- // fetches against the frontend origin (e.g. `:3782/api/v1/...` or
- // `:3782/api/v1/.../ws`); the rewrite is what bridges the origin gap and
- // keeps the URL knowledge in one place (the entrypoint + system.json) rather
- // than baked into the frontend bundle.
- if (pathname.startsWith("/api/") || pathname.startsWith("/ws/")) {
+ // 1. Bridge the origin gap: forward backend-relative paths to the API server.
+ // This keeps the URL knowledge in one place (the entrypoint + system.json)
+ // rather than baked into the frontend bundle.
+ if (isBackendPath(pathname)) {
return NextResponse.rewrite(new URL(pathname + search, API_BASE_URL));
}
- // Auth is disabled (default) — let everything else through
- if (!AUTH_ENABLED) return NextResponse.next();
-
- // Always allow auth pages and Next.js internals
- if (
- pathname.startsWith(LOGIN_PATH) ||
- pathname.startsWith("/register") ||
- pathname.startsWith("/_next") ||
- pathname.startsWith("/favicon")
- ) {
+ // 2. Auth gate — multi-user mode only. Disabled by default, and never blocks
+ // auth pages, Next.js internals, or public static assets (see
+ // isAuthExempt: that exemption is what keeps the logo/banner images
+ // loading once login is enabled — issue #599).
+ if (!AUTH_ENABLED || isAuthExempt(pathname)) {
return NextResponse.next();
}
const token = req.cookies.get(COOKIE_NAME)?.value;
-
- // No token — redirect to login, preserving the intended destination
- if (!token) {
- const loginUrl = req.nextUrl.clone();
- loginUrl.pathname = LOGIN_PATH;
- loginUrl.searchParams.set("next", pathname);
- return NextResponse.redirect(loginUrl);
- }
-
- // Verify token structure (JWT: header.payload.signature)
- const parts = token.split(".");
- if (parts.length !== 3) {
- const loginUrl = req.nextUrl.clone();
- loginUrl.pathname = LOGIN_PATH;
- loginUrl.searchParams.set("next", pathname);
- const response = NextResponse.redirect(loginUrl);
- response.cookies.delete(COOKIE_NAME);
- return response;
- }
-
- // Check expiry from payload (base64url-decoded JSON)
- try {
- const payload = JSON.parse(
- Buffer.from(parts[1], "base64url").toString("utf-8"),
- );
- if (payload.exp && Date.now() >= payload.exp * 1000) {
- const loginUrl = req.nextUrl.clone();
- loginUrl.pathname = LOGIN_PATH;
- loginUrl.searchParams.set("next", pathname);
- const response = NextResponse.redirect(loginUrl);
- response.cookies.delete(COOKIE_NAME);
- return response;
- }
- } catch {
- // Malformed payload — treat as invalid
- const loginUrl = req.nextUrl.clone();
- loginUrl.pathname = LOGIN_PATH;
- loginUrl.searchParams.set("next", pathname);
- const response = NextResponse.redirect(loginUrl);
- response.cookies.delete(COOKIE_NAME);
- return response;
+ if (classifyToken(token, Date.now()) !== "valid") {
+ return redirectToLogin(req, { clearCookie: Boolean(token) });
}
return NextResponse.next();
@@ -87,6 +61,9 @@ export function proxy(req: NextRequest) {
export const config = {
// Run on every request except Next.js internals and the favicon. The /api/*
- // and /ws/* paths are explicitly handled above (rewritten to the backend).
+ // and /ws/* paths are explicitly handled above (rewritten to the backend);
+ // the browser's /_next/image optimizer requests are excluded here, while the
+ // optimizer's loopback fetch for the source image (e.g. /logo.png) is let
+ // through the auth gate by isAuthExempt.
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
diff --git a/web/tests/proxy-policy.test.ts b/web/tests/proxy-policy.test.ts
new file mode 100644
index 000000000..3dbc90472
--- /dev/null
+++ b/web/tests/proxy-policy.test.ts
@@ -0,0 +1,74 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+// Unit tests for the pure middleware routing policy (web/lib/proxy-policy.ts).
+// The policy is deliberately decoupled from `next/server`, so it can be
+// exercised here without booting the Next runtime. proxy.ts itself is a thin
+// adapter that maps these decisions onto NextResponse.
+
+import {
+ classifyToken,
+ isAuthExempt,
+ isBackendPath,
+} from "../lib/proxy-policy";
+
+function makeToken(payload: Record<string, unknown>): string {
+ const encode = (value: unknown) =>
+ Buffer.from(JSON.stringify(value)).toString("base64url");
+ return `${encode({ alg: "HS256" })}.${encode(payload)}.signature`;
+}
+
+test("isBackendPath matches /api and /ws paths only", () => {
+ assert.equal(isBackendPath("/api/v1/knowledge/list"), true);
+ assert.equal(isBackendPath("/ws/chat"), true);
+ assert.equal(isBackendPath("/home"), false);
+ assert.equal(isBackendPath("/apidocs"), false); // no trailing slash → not backend
+ assert.equal(isBackendPath("/logo.png"), false);
+});
+
+test("isAuthExempt allows public static assets through the auth gate (issue #599)", () => {
+ // The Next image optimizer re-fetches these over a cookie-less loopback; if
+ // the gate blocked them the sidebar logo/banner would render broken.
+ assert.equal(isAuthExempt("/logo.png"), true);
+ assert.equal(isAuthExempt("/banner.png"), true);
+ assert.equal(isAuthExempt("/logo_black.png"), true);
+ assert.equal(isAuthExempt("/apple-touch-icon.png"), true);
+ assert.equal(isAuthExempt("/provider-icons/openai.svg"), true);
+});
+
+test("isAuthExempt allows auth pages and Next internals", () => {
+ assert.equal(isAuthExempt("/login"), true);
+ assert.equal(isAuthExempt("/register"), true);
+ assert.equal(isAuthExempt("/_next/data/build/home.json"), true);
+ assert.equal(isAuthExempt("/favicon-32x32.png"), true);
+});
+
+test("isAuthExempt does NOT exempt protected app routes", () => {
+ assert.equal(isAuthExempt("/home"), false);
+ assert.equal(isAuthExempt("/dashboard"), false);
+ assert.equal(isAuthExempt("/space/agents"), false);
+ assert.equal(isAuthExempt("/knowledge"), false);
+});
+
+test("classifyToken reports missing for absent or empty cookie", () => {
+ const now = 1_000_000_000_000;
+ assert.equal(classifyToken(undefined, now), "missing");
+ assert.equal(classifyToken("", now), "missing");
+});
+
+test("classifyToken reports malformed for non-JWT shapes", () => {
+ const now = 1_000_000_000_000;
+ assert.equal(classifyToken("a.b", now), "malformed"); // 2 segments
+ assert.equal(classifyToken("a.b.c.d", now), "malformed"); // 4 segments
+ // Valid 3-segment shape but the payload is not JSON → malformed.
+ const notJson = `h.${Buffer.from("not-json").toString("base64url")}.s`;
+ assert.equal(classifyToken(notJson, now), "malformed");
+});
+
+test("classifyToken honors expiry and accepts unexpired / expiry-less tokens", () => {
+ const now = 1_000_000_000_000; // ms
+ const nowSec = now / 1000;
+ assert.equal(classifyToken(makeToken({ exp: nowSec + 3600 }), now), "valid");
+ assert.equal(classifyToken(makeToken({ exp: nowSec - 1 }), now), "expired");
+ assert.equal(classifyToken(makeToken({}), now), "valid"); // no exp claim
+});