Skip to content

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

feat: integrate Dito navigation with existing learning and partner workflows

Bingxi Zhao (Frank)90c070d77b51
diff --git a/artifacts/dito-preview/dt-exp-partners.png b/artifacts/dito-preview/dt-exp-partners.png
new file mode 100644
index 000000000..1f3be095c
Binary files /dev/null and b/artifacts/dito-preview/dt-exp-partners.png differ
diff --git a/artifacts/dito-preview/dt-exp-practice.png b/artifacts/dito-preview/dt-exp-practice.png
new file mode 100644
index 000000000..3fa9e0104
Binary files /dev/null and b/artifacts/dito-preview/dt-exp-practice.png differ
diff --git a/artifacts/dito-preview/dt-exp-writer.png b/artifacts/dito-preview/dt-exp-writer.png
new file mode 100644
index 000000000..456af2bb4
Binary files /dev/null and b/artifacts/dito-preview/dt-exp-writer.png differ
diff --git a/artifacts/dito-preview/home-desktop.jpg b/artifacts/dito-preview/home-desktop.jpg
new file mode 100644
index 000000000..067144dd2
Binary files /dev/null and b/artifacts/dito-preview/home-desktop.jpg differ
diff --git a/artifacts/dito-preview/learning-v2.jpg b/artifacts/dito-preview/learning-v2.jpg
new file mode 100644
index 000000000..f7aa0a2bb
Binary files /dev/null and b/artifacts/dito-preview/learning-v2.jpg differ
diff --git a/artifacts/dito-preview/mobile-home.jpg b/artifacts/dito-preview/mobile-home.jpg
new file mode 100644
index 000000000..588020e77
Binary files /dev/null and b/artifacts/dito-preview/mobile-home.jpg differ
diff --git a/artifacts/dito-preview/partners-v2.jpg b/artifacts/dito-preview/partners-v2.jpg
new file mode 100644
index 000000000..1e552c5ea
Binary files /dev/null and b/artifacts/dito-preview/partners-v2.jpg differ
diff --git a/artifacts/dito-preview/reader-desktop.jpg b/artifacts/dito-preview/reader-desktop.jpg
new file mode 100644
index 000000000..05be3b1e0
Binary files /dev/null and b/artifacts/dito-preview/reader-desktop.jpg differ
diff --git a/artifacts/dito-preview/writer-desktop.jpg b/artifacts/dito-preview/writer-desktop.jpg
new file mode 100644
index 000000000..7a53cfeaf
Binary files /dev/null and b/artifacts/dito-preview/writer-desktop.jpg differ
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 0b63eff22..1246facbd 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -706,6 +706,11 @@ async def require_learning_surface(
"""Second-stage default-deny guard for configured learning accounts."""
from deeptutor.multi_user.learning_access import assert_learning_surface
+ # This aggregate filters each source by the current policy itself. Exact
+ # GET only: it must never open the rest of the dashboard to learners.
+ if request.method == "GET" and request.url.path == "/api/dashboard/learning-index":
+ return
+
try:
assert_learning_surface(
_learning_surface_for_path(
diff --git a/deeptutor/api/routers/dashboard.py b/deeptutor/api/routers/dashboard.py
index 36585c3a6..7f0151e1f 100644
--- a/deeptutor/api/routers/dashboard.py
+++ b/deeptutor/api/routers/dashboard.py
@@ -82,6 +82,7 @@ async def get_learning_index():
from deeptutor.api.routers.book import list_books
from deeptutor.api.routers.mastery_path import list_topics
from deeptutor.api.routers.reading import list_workspaces
+ from deeptutor.multi_user.learning_access import current_learning_policy
from deeptutor.services.workspace.navigation import read_workspace_indexes
async def books():
@@ -93,9 +94,14 @@ async def get_learning_index():
async def reading():
return (await list_workspaces(search=""))["workspaces"]
- result = {}
+ policy = current_learning_policy()
+ allowed = set(policy.get("allowed_surfaces") or ["chat", "reading"]) if policy is not None else None
+ result = {"books": [], "mastery": [], "reading": [], "watching": [], "practice": []}
failed = []
for kind, reader in (("books", books), ("mastery", mastery), ("reading", reading)):
+ surface = "chat" if kind == "mastery" else kind
+ if allowed is not None and surface not in allowed:
+ continue
result[kind], unavailable = await read_workspace_indexes(reader)
if unavailable:
failed.append(kind)
@@ -107,13 +113,26 @@ async def get_learning_index():
return [
row
for row in rows
- if (row.get("preferences") or {}).get("workspace_mode") == "immersive_watching"
- or (row.get("preferences") or {}).get("capability") == "immersive_watching"
+ if not (row.get("preferences") or {}).get("archived")
+ and (
+ (row.get("preferences") or {}).get("workspace_mode") == "immersive_watching"
+ or (row.get("preferences") or {}).get("capability") == "immersive_watching"
+ )
]
- result["watching"], unavailable = await read_workspace_indexes(watching)
- if unavailable:
- failed.append("watching")
+ if allowed is None or "reading" in allowed:
+ result["watching"], unavailable = await read_workspace_indexes(watching)
+ if unavailable:
+ failed.append("watching")
+ if allowed is None or "chat" in allowed:
+ async def practice():
+ from deeptutor.services.session import get_sqlite_session_store
+
+ return await get_sqlite_session_store().list_notebook_navigation()
+
+ result["practice"], unavailable = await read_workspace_indexes(practice)
+ if unavailable:
+ failed.append("practice")
return {"sources": result, "failed": failed}
diff --git a/deeptutor/api/routers/partners.py b/deeptutor/api/routers/partners.py
index 27ebf6a25..0f1b1982f 100644
--- a/deeptutor/api/routers/partners.py
+++ b/deeptutor/api/routers/partners.py
@@ -13,6 +13,7 @@ import asyncio
import base64
import binascii
from contextlib import nullcontext
+from datetime import datetime
import json
import logging
from typing import Any, AsyncGenerator, Literal
@@ -644,6 +645,78 @@ async def list_partners():
return visible_partners()
+class NavigationSession(BaseModel):
+ kind: Literal["partner", "group"]
+ owner_id: str
+ owner_name: str
+ session_key: str
+ title: str
+ updated_at: float
+
+
+class PartnerNavigation(BaseModel):
+ partners: list[dict[str, Any]]
+ groups: list[dict[str, Any]]
+ sessions: list[NavigationSession]
+ unavailable: list[str]
+
+
+def _navigation_timestamp(value: Any) -> float:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ try:
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp()
+ except ValueError:
+ return 0.0
+
+
[email protected]("/navigation", response_model=PartnerNavigation)
+async def partner_navigation():
+ """Read existing identities and actor-scoped sessions without moving data.
+
+ Never enumerate the manager's global partner directories or shared channel
+ history here. Visibility and transcript ownership match the detail APIs.
+ """
+ from deeptutor.services.partner_groups import get_partner_group_manager
+
+ partners = [
+ {key: row.get(key) for key in (
+ "partner_id", "name", "description", "emoji", "color", "avatar", "can_manage", "running",
+ )}
+ for row in visible_partners()
+ ]
+ group_manager = get_partner_group_manager()
+ groups = group_manager.list_groups()
+ sessions: list[NavigationSession] = []
+ unavailable: list[str] = []
+ manager = get_partner_manager()
+ for kind, owners in (("partner", partners), ("group", groups)):
+ for owner in owners:
+ owner_id = owner[f"{kind}_id"]
+ try:
+ rows = (
+ manager.session_store(owner_id).list_sessions()
+ if kind == "partner" else group_manager.list_sessions(owner_id)
+ )
+ for row in rows:
+ if row.get("archived"):
+ continue
+ sessions.append(NavigationSession(
+ kind=kind,
+ owner_id=owner_id,
+ owner_name=owner["name"],
+ session_key=row["session_key"],
+ title=str(row.get("title") or row.get("last_message") or "")[:160],
+ updated_at=_navigation_timestamp(row.get("updated_at")),
+ ))
+ except Exception:
+ logger.warning("Partner navigation unavailable: %s/%s", kind, owner_id, exc_info=True)
+ unavailable.append(f"{kind}:{owner_id}")
+ sessions.sort(key=lambda row: (-row.updated_at, row.kind, row.owner_id, row.session_key))
+ return PartnerNavigation(partners=partners, groups=groups, sessions=sessions, unavailable=unavailable)
+
+
@router.get("/consultation-session")
async def get_partner_consultation_session(chat_session_id: str, partner_name: str):
"""Recover native identity for older consultation traces in this user's registry."""
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index e26881b7c..5087e85ac 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -4064,6 +4064,23 @@ class SQLiteSessionStore:
item["practice"] = practice.get(int(item["id"]))
return {"items": items, "total": total}
+ async def list_notebook_navigation(self) -> list[dict[str, Any]]:
+ """Read small question identities for navigation, without hydrating answers.
+
+ Uses the same recycle predicate as the Question Bank. No new schema or
+ migration: old entry IDs remain the IDs used by practice and review.
+ """
+ def read() -> list[dict[str, Any]]:
+ with self._connect() as conn:
+ return [dict(row) for row in conn.execute(
+ "SELECT id, substr(question, 1, 160) AS question, created_at, updated_at "
+ "FROM notebook_entries WHERE "
+ + _NOT_RECYCLED_ENTRY_SQL.format(entries="notebook_entries")
+ + " ORDER BY updated_at DESC, id DESC"
+ ).fetchall()]
+
+ return await self._run(read)
+
async def list_notebook_entries(
self,
category_id: int | None = None,
diff --git a/tests/multi_user/test_learning_policy_http.py b/tests/multi_user/test_learning_policy_http.py
index 6dbe9ff78..154267ede 100644
--- a/tests/multi_user/test_learning_policy_http.py
+++ b/tests/multi_user/test_learning_policy_http.py
@@ -222,3 +222,16 @@ def test_dashboard_learning_library_follows_the_policy(learner_client, as_user):
denied = client.get(f"/api/dashboard/learning-library/{kind}")
assert denied.status_code == 403
assert "reading surface" in denied.json()["detail"]
+
+
+def test_learning_navigation_index_filters_sources_without_opening_dashboard(learner_client, as_user):
+ client, learner, current_user, tmp_path = learner_client
+ with as_user(current_user.id, username="student"):
+ material = _seed_material(tmp_path, "navigation.txt", "Assigned reading.")
+ _save_learner_grant(learner["id"], material.material_id, allowed_surfaces=["reading"])
+
+ response = client.get("/api/dashboard/learning-index")
+ assert response.status_code == 200, response.text
+ sources = response.json()["sources"]
+ assert sources["books"] == sources["mastery"] == sources["practice"] == []
+ assert client.get("/api/dashboard/overview").status_code == 403
diff --git a/tests/services/workspace/test_navigation_compatibility.py b/tests/services/workspace/test_navigation_compatibility.py
new file mode 100644
index 000000000..d30584bcd
--- /dev/null
+++ b/tests/services/workspace/test_navigation_compatibility.py
@@ -0,0 +1,127 @@
+"""Navigation reads legacy stores in place; IDs, content and ownership survive."""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from deeptutor.api.routers import dashboard, partners
+from deeptutor.book.models import Book
+from deeptutor.book.storage import get_book_storage
+from deeptutor.services.path_service import get_path_service
+from deeptutor.services.session import get_sqlite_session_store
+from deeptutor.services.workspace.context import current_workspace_id, workspace_context
+from tests.services.workspace.test_data_scope import account as account
+from tests.services.workspace.test_learning_sources_review import seed_question
+
+
+async def test_learning_index_preserves_equal_ids_and_existing_bytes(account):
+ other = account.create_workspace("Other")["workspace_id"]
+ originals = {}
+ questions = {}
+ for origin in ("", other):
+ with workspace_context(origin):
+ book = Book(id="bk_legacy", title=f"Book {origin}", metadata={"legacy_extra": "keep"})
+ store = get_book_storage()
+ store.save_book(book)
+ manifest = get_path_service().get_book_manifest_file(book.id)
+ originals[manifest] = manifest.read_bytes()
+ questions[origin] = await seed_question(origin, f"Question {origin}")
+ with workspace_context(other):
+ result = await dashboard.get_learning_index()
+ assert current_workspace_id() == other
+ assert result["failed"] == []
+ assert {row["content_workspace_id"] for row in result["sources"]["books"]} == {"", other}
+ assert {row["id"] for row in result["sources"]["books"]} == {"bk_legacy"}
+ assert {row["content_workspace_id"] for row in result["sources"]["practice"]} == {"", other}
+ assert len(result["sources"]["practice"]) == 2
+ for origin in ("", other):
+ with workspace_context(origin):
+ current = await get_sqlite_session_store().find_notebook_entry("lesson", "q1")
+ assert current == questions[origin]
+ assert get_book_storage().load_book("bk_legacy").metadata == {"legacy_extra": "keep"}
+ assert all(path.read_bytes() == data for path, data in originals.items())
+
+
+async def test_learning_index_never_reads_disallowed_sources(account, monkeypatch):
+ from deeptutor.api.routers import book, mastery_path, reading
+ from deeptutor.multi_user import learning_access
+
+ monkeypatch.setattr(
+ learning_access, "current_learning_policy", lambda: {"allowed_surfaces": ["reading"]}
+ )
+ denied = AsyncMock(side_effect=AssertionError("denied source read"))
+ monkeypatch.setattr(book, "list_books", denied)
+ monkeypatch.setattr(mastery_path, "list_topics", denied)
+ monkeypatch.setattr(type(get_sqlite_session_store()), "list_notebook_navigation", denied)
+ monkeypatch.setattr(reading, "list_workspaces", AsyncMock(return_value={"workspaces": []}))
+ result = await dashboard.get_learning_index()
+ denied.assert_not_called()
+ assert (
+ result["sources"]["books"]
+ == result["sources"]["mastery"]
+ == result["sources"]["practice"]
+ == []
+ )
+
+
+async def test_partner_index_uses_visible_actor_stores_and_keeps_archives(account, monkeypatch):
+ from deeptutor.services import partner_groups
+
+ rows = [
+ {
+ "session_key": "web-old",
+ "title": "Old conversation",
+ "updated_at": "2026-10-01T12:00:00Z",
+ },
+ {
+ "session_key": "archive",
+ "title": "Archived",
+ "archived": True,
+ "updated_at": "2026-10-02T12:00:00Z",
+ },
+ ]
+ accessed = []
+
+ def session_store(partner_id):
+ accessed.append(partner_id)
+ assert partner_id == "visible"
+ return SimpleNamespace(list_sessions=lambda: rows)
+
+ monkeypatch.setattr(
+ partners,
+ "visible_partners",
+ lambda: [
+ {
+ "partner_id": "visible",
+ "name": "Tutor",
+ "soul": "never return",
+ "channels": {"secret": "never return"},
+ }
+ ],
+ )
+ monkeypatch.setattr(
+ partners, "get_partner_manager", lambda: SimpleNamespace(session_store=session_store)
+ )
+ monkeypatch.setattr(
+ partner_groups,
+ "get_partner_group_manager",
+ lambda: SimpleNamespace(
+ list_groups=lambda: [{"group_id": "group-a", "name": "Group"}],
+ list_sessions=lambda gid: [
+ {
+ "session_key": "default",
+ "title": "Old group",
+ "updated_at": "2026-10-02T12:00:00Z",
+ }
+ ],
+ ),
+ )
+ result = await partners.partner_navigation()
+ assert accessed == ["visible"]
+ assert [row.session_key for row in result.sessions] == ["default", "web-old"]
+ assert "soul" not in result.partners[0] and "channels" not in result.partners[0]
+ assert rows[1]["archived"] is True and len(rows) == 2
diff --git a/web/app/(workspace)/kanban/page.tsx b/web/app/(workspace)/kanban/page.tsx
index 22d9c04df..6f9f5195a 100644
--- a/web/app/(workspace)/kanban/page.tsx
+++ b/web/app/(workspace)/kanban/page.tsx
@@ -1,417 +1 @@
-'use client'
-
-import { FeaturePage, pageGridClass } from '@/components/layout/FeaturePage'
-import { useRef, useState } from 'react'
-import {
- Archive,
- ArrowLeft,
- ArrowRight,
- Check,
- ChevronDown,
- CircleCheck,
- CircleDashed,
- CircleDot,
- Folder,
- Plus,
- RotateCcw,
- X,
-} from 'lucide-react'
-import { useTranslation } from 'react-i18next'
-import SpaceSectionHeader from '@/components/space/SpaceSectionHeader'
-import Tooltip from '@/shared/ui/Tooltip'
-import TaskColorPicker from '@/components/tasks/TaskColorPicker'
-
-import {
- createTaskCard,
- updateTaskColors,
- DEFAULT_TASK_COLORS,
- updateTaskCard,
- type TaskBoard,
- type TaskCard,
- type TaskStatus,
-} from '@/lib/task-board-api'
-
-import { useTaskBoard, refreshTaskBoard } from '@/lib/task-board-store'
-import { useChatWorkspaces } from '@/hooks/useChatWorkspaces'
-
-const columns = [
- { id: 'todo', title: 'kanban.todo', hint: 'kanban.todoHint', icon: CircleDashed },
- { id: 'doing', title: 'kanban.doing', hint: 'kanban.doingHint', icon: CircleDot },
- { id: 'done', title: 'kanban.done', hint: 'kanban.doneHint', icon: CircleCheck },
-] as const
-
-export default function KanbanPage() {
- const { t } = useTranslation()
- const { board, error: loadError } = useTaskBoard()
- const { workspaces } = useChatWorkspaces()
- const [title, setTitle] = useState('')
- const [editing, setEditing] = useState<string | null>(null)
- const [draftTitle, setDraftTitle] = useState('')
- const [draftNote, setDraftNote] = useState('')
- const [busy, setBusy] = useState(false)
- const [error, setError] = useState('')
- const [dragged, setDragged] = useState<string | null>(null)
- const [dropTarget, setDropTarget] = useState<TaskStatus | null>(null)
-
- const pending = useRef(false)
- const [showArchived, setShowArchived] = useState(false)
- async function act(operation: () => Promise<TaskBoard>, onSuccess?: () => void) {
- if (pending.current || !board) return
- pending.current = true
- setBusy(true)
- setError('')
- try {
- await operation()
- onSuccess?.()
- } catch {
- setError('kanban.saveError')
- } finally {
- pending.current = false
- setBusy(false)
- }
- }
-
- function startEdit(card: TaskCard) {
- setEditing(card.id)
- setDraftTitle(card.title)
- setDraftNote(card.note)
- }
-
- const active = board?.cards.filter(card => !card.archived) ?? []
- const visible = board?.cards.filter(card => card.archived === showArchived) ?? []
- const count = (status: TaskStatus) => visible.filter(card => card.status === status).length
-
- return (
- <FeaturePage>
- <SpaceSectionHeader
- title={t('Task Board')}
- description={t('kanban.intro')}
- action={
- <div className="flex items-center gap-1">
- <TaskColorPicker
- colors={board?.colors ?? DEFAULT_TASK_COLORS}
- disabled={!board}
- busy={busy}
- error={error ? t(error) : undefined}
- onSave={(colors, onSuccess) => void act(() => updateTaskColors(colors), onSuccess)}
- />
- <button
- type="button"
- aria-pressed={showArchived}
- disabled={busy}
- onClick={() => {
- setShowArchived(value => !value)
- setEditing(null)
- }}
- className={`inline-flex h-9 items-center gap-2 rounded-lg px-3 text-[13px] font-medium transition-colors disabled:opacity-40 ${showArchived ? 'bg-muted text-foreground' : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground'}`}
- >
- <Archive size={15} strokeWidth={1.7} />
- {t(showArchived ? 'kanban.showActive' : 'kanban.showArchived')}
- </button>
- </div>
- }
- meta={
- <span className="rounded-md bg-muted/65 px-2 py-0.5 font-sans text-[11px] font-medium text-muted-foreground">
- {active.filter(card => card.status === 'doing').length} {t('kanban.working')}
- </span>
- }
- />
-
- <form
- className="mb-6 flex items-center gap-2 rounded-xl border border-border/80 bg-card p-1.5 transition-[border-color,box-shadow] focus-within:border-primary/40 focus-within:ring-[3px] focus-within:ring-primary/5"
- onSubmit={event => {
- event.preventDefault()
- if (title.trim())
- void act(
- () => createTaskCard(title),
- () => {
- setTitle('')
- setShowArchived(false)
- }
- )
- }}
- >
- <input
- disabled={!board || busy}
- aria-label={t('kanban.newTask')}
- className="min-w-0 flex-1 bg-transparent px-3 py-2 text-[13px] outline-none placeholder:text-muted-foreground/75 focus-visible:outline-none"
- placeholder={t('kanban.placeholder')}
- maxLength={160}
- value={title}
- onChange={event => setTitle(event.target.value)}
- />
- <button
- disabled={busy || !board || !title.trim()}
- className="flex shrink-0 items-center gap-1.5 rounded-lg bg-primary px-3.5 py-2 text-[13px] font-medium text-primary-foreground transition-colors hover:opacity-90 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-60"
- type="submit"
- >
- <Plus size={15} strokeWidth={1.8} /> {t('kanban.add')}
- </button>
- </form>
- {!board && !error && !loadError && (
- <p role="status" className="mb-5 text-sm text-muted-foreground">
- {t('kanban.loading')}
- </p>
- )}
- {(error || loadError) && (
- <p role="alert" className="mb-5 rounded-xl bg-secondary p-3 text-sm text-destructive">
- {t(error || 'kanban.loadError')}
- {!board && (
- <button
- type="button"
- className="ml-3 underline"
- onClick={() => {
- setError('')
- void refreshTaskBoard()
- }}
- >
- {t('kanban.retry')}
- </button>
- )}
- </p>
- )}
-
- <div aria-busy={busy || !board} className={pageGridClass('board')}>
- {columns.map((column, index) => (
- <section
- key={column.id}
- aria-label={t(column.title)}
- onDragOver={event => {
- event.preventDefault()
- if (dragged && !showArchived) setDropTarget(column.id)
- }}
- onDragLeave={event => {
- if (!event.currentTarget.contains(event.relatedTarget as Node | null))
- setDropTarget(null)
- }}
- onDrop={event => {
- event.preventDefault()
- if (dragged && !showArchived)
- void act(() => updateTaskCard(dragged, { status: column.id }))
- setDragged(null)
- setDropTarget(null)
- }}
- className={`min-h-[12rem] rounded-2xl border p-3 transition-colors sm:p-3.5 lg:min-h-[24rem] ${dropTarget === column.id ? 'border-primary/35 bg-primary/5 ring-2 ring-primary/10' : 'border-border/45 bg-secondary/65'}`}
- >
- <div className="mb-3 flex items-center justify-between px-1 py-1.5">
- <div className="flex items-start gap-2.5">
- <span
- className="mt-1.5 h-2 w-2 shrink-0 rounded-full"
- style={{
- backgroundColor: board?.colors[column.id] ?? DEFAULT_TASK_COLORS[column.id],
- }}
- />
- <div>
- <h2 className="text-[13px] font-semibold leading-5">{t(column.title)}</h2>
- <p className="mt-0.5 text-[11px] leading-4 text-muted-foreground">
- {t(column.hint)}
- </p>
- </div>
- </div>
- <span className="self-start px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-muted-foreground">
- {count(column.id)}
- </span>
- </div>
- <div className="space-y-2.5">
- {visible
- .filter(card => card.status === column.id)
- .map(card => (
- <article
- key={card.id}
- draggable={!busy && !showArchived && editing !== card.id}
- onDragStart={event => {
- event.dataTransfer.setData('text/plain', card.id)
- event.dataTransfer.effectAllowed = 'move'
- setDragged(card.id)
- }}
- onDragEnd={() => {
- setDragged(null)
- setDropTarget(null)
- }}
- className={`group/kanban-card rounded-xl border border-border/75 bg-card px-3.5 py-3 shadow-[0_1px_2px_rgba(0,0,0,0.025)] transition-[border-color,box-shadow,opacity] hover:border-border hover:shadow-[0_2px_8px_rgba(0,0,0,0.045)] ${dragged === card.id ? 'opacity-45' : ''}`}
- >
- {editing === card.id ? (
- <form
- onSubmit={event => {
- event.preventDefault()
- if (draftTitle.trim())
- void act(
- () =>
- updateTaskCard(card.id, { title: draftTitle, note: draftNote }),
- () => setEditing(null)
- )
- }}
- >
- <input
- aria-label={t('kanban.taskTitle')}
- className="w-full rounded-lg border border-border bg-background px-2.5 py-2 text-[13px] font-medium text-foreground focus:border-primary/40 focus:outline-none focus:ring-2 focus:ring-primary/10"
- maxLength={160}
- value={draftTitle}
- onChange={event => setDraftTitle(event.target.value)}
- />
- <textarea
- aria-label={t('kanban.taskNote')}
- className="mt-2 w-full resize-y rounded-lg border border-border bg-background px-2.5 py-2 text-xs leading-5 text-foreground focus:border-primary/40 focus:outline-none focus:ring-2 focus:ring-primary/10"
- placeholder={t('kanban.notePlaceholder')}
- rows={3}
- maxLength={2000}
- value={draftNote}
- onChange={event => setDraftNote(event.target.value)}
- />
- <div className="mt-2 flex gap-2">
- <button
- disabled={busy || !draftTitle.trim()}
- className="flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-xs font-semibold text-primary-foreground disabled:opacity-40"
- type="submit"
- >
- <Check size={14} /> {t('kanban.save')}
- </button>
- <button
- className="flex items-center gap-1 rounded-lg px-2 py-1.5 text-xs text-muted-foreground"
- type="button"
- onClick={() => setEditing(null)}
- >
- <X size={14} /> {t('kanban.cancel')}
- </button>
- </div>
- </form>
- ) : (
- <div className="relative">
- <button
- type="button"
- aria-label={card.title}
- disabled={busy}
- className="block w-full text-left"
- onClick={() => startEdit(card)}
- >
- <strong className="block break-words text-[13px] font-medium leading-6">
- {card.title}
- </strong>
- {card.note && (
- <p className="mt-1.5 whitespace-pre-wrap break-words text-xs leading-5 text-muted-foreground">
- {card.note}
- </p>
- )}
- </button>
- <label className="relative mt-3 inline-flex max-w-full items-center gap-1.5 rounded-md bg-muted/50 px-2 py-1 text-[11px] leading-4 text-muted-foreground transition-colors hover:bg-muted focus-within:ring-2 focus-within:ring-ring/40">
- <Folder aria-hidden size={11} strokeWidth={1.7} className="shrink-0" />
- <span className="truncate">
- {card.workspace_id === null
- ? t('tasks.unassigned')
- : card.workspace_id === ''
- ? t('General workspace')
- : (workspaces.find(row => row.workspace_id === card.workspace_id)
- ?.display_name ?? t('tasks.assign'))}
- </span>
- <ChevronDown
- aria-hidden
- size={11}
- strokeWidth={1.7}
- className="shrink-0 opacity-60"
- />
- <select
- aria-label={`${card.title}: ${t('tasks.assign')}`}
- disabled={busy}
- value={card.workspace_id ?? '__unassigned__'}
- onChange={event =>
- void act(() =>
- updateTaskCard(card.id, {
- workspace_id:
- event.target.value === '__unassigned__'
- ? null
- : event.target.value,
- })
- )
- }
- className="absolute inset-0 h-full w-full cursor-pointer opacity-0 disabled:cursor-default"
- >
- <option value="__unassigned__">{t('tasks.unassigned')}</option>
- <option value="">{t('General workspace')}</option>
- {workspaces
- .filter(row => row.kind === 'workspace')
- .map(row => (
- <option
- key={row.workspace_id}
- value={row.workspace_id}
- disabled={row.archived || row.status !== 'ready'}
- >
- {row.display_name}
- </option>
- ))}
- </select>
- </label>
- <div className="pointer-events-none absolute -right-0.5 -top-0.5 flex items-center gap-0.5 rounded-r-md bg-gradient-to-l from-popover from-80% to-transparent pl-4 opacity-0 transition-opacity duration-150 group-hover/kanban-card:pointer-events-auto group-hover/kanban-card:opacity-100 group-has-[:focus-visible]/kanban-card:pointer-events-auto group-has-[:focus-visible]/kanban-card:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
- {!showArchived && index > 0 && (
- <Tooltip label={t('kanban.back')}>
- <button
- disabled={busy}
- aria-label={`${card.title}: ${t('kanban.moveTo')} ${t(columns[index - 1].title)}`}
- className="rounded-lg p-1.5 text-muted-foreground hover:bg-accent"
- onClick={() =>
- void act(() =>
- updateTaskCard(card.id, { status: columns[index - 1].id })
- )
- }
- >
- <ArrowLeft size={16} />
- </button>
- </Tooltip>
- )}
- {!showArchived && index < 2 && (
- <Tooltip label={t('kanban.forward')}>
- <button
- disabled={busy}
- aria-label={`${card.title}: ${t('kanban.moveTo')} ${t(columns[index + 1].title)}`}
- className="rounded-lg p-1.5 text-muted-foreground hover:bg-accent"
- onClick={() =>
- void act(() =>
- updateTaskCard(card.id, { status: columns[index + 1].id })
- )
- }
- >
- <ArrowRight size={16} />
- </button>
- </Tooltip>
- )}
- <Tooltip label={t(card.archived ? 'kanban.restore' : 'kanban.archive')}>
- <button
- disabled={busy}
- aria-label={`${card.title}: ${t(card.archived ? 'kanban.restore' : 'kanban.archive')}`}
- className="rounded-lg p-1.5 text-muted-foreground hover:bg-accent"
- onClick={() =>
- void act(() =>
- updateTaskCard(card.id, { archived: !card.archived })
- )
- }
- >
- {card.archived ? <RotateCcw size={15} /> : <Archive size={15} />}
- </button>
- </Tooltip>
- </div>
- </div>
- )}
- </article>
- ))}
- {board && count(column.id) === 0 && (
- <div className="flex min-h-28 flex-col items-center justify-center gap-2.5 rounded-xl border border-dashed border-border/65 px-4 py-6 text-center">
- <column.icon
- aria-hidden
- size={20}
- strokeWidth={1.3}
- className="text-muted-foreground/40"
- />
- <p className="text-[11px] text-muted-foreground">
- {t(showArchived ? 'kanban.emptyArchive' : 'kanban.empty')}
- </p>
- </div>
- )}
- </div>
- </section>
- ))}
- </div>
- <p className="mt-5 px-1 text-[11px] leading-5 text-muted-foreground">
- {t('kanban.footer')}
- </p>
- </FeaturePage>
- )
-}
+export { default } from '@/features/tasks/components/KanbanBoard'
diff --git a/web/app/(workspace)/partners/[partnerId]/page.tsx b/web/app/(workspace)/partners/[partnerId]/page.tsx
index 43d6423eb..6b9292ec9 100644
--- a/web/app/(workspace)/partners/[partnerId]/page.tsx
+++ b/web/app/(workspace)/partners/[partnerId]/page.tsx
@@ -200,7 +200,7 @@ function PartnerDetail() {
selectionEpochRef.current += 1;
setSessionKey(key);
if (continuityEnabled) {
- if (alreadySaved) return;
+ if (alreadySaved) return key;
selectionMutationRef.current = true;
setSwitchingSession(true);
try {
@@ -209,9 +209,11 @@ function PartnerDetail() {
session_key: key,
});
if (state.session_key && state.session_key !== key) setSessionKey(state.session_key);
+ return state.session_key || key;
} catch (error) {
setToast(error instanceof Error ? error.message : t("Action failed"));
await reconcileSelection();
+ return null;
} finally {
selectionMutationRef.current = false;
setSwitchingSession(false);
@@ -219,11 +221,45 @@ function PartnerDetail() {
} else {
if (accountId) persistPartnerSessionKey(partnerId, key, accountId);
setLocalSessionKey(key);
+ return key;
}
},
[partnerId, continuityEnabled, accountId, reconcileSelection, t],
);
+ // Sidebar links name an existing actor-owned conversation. Resolve it through
+ // the same selection path as Archive/Resume, preserving web continuity locks.
+ const requestedSession = searchParams.get("session") || "";
+ const requestedSelection = useRef("");
+ const selectionQuery = searchParams.toString();
+ const selectSessionKey = useCallback(async (key: string, alreadySaved = false) => {
+ const selected = await changeSessionKey(key, alreadySaved);
+ if (!selected) return;
+ requestedSelection.current = `${partnerId}:${selected}`;
+ const query = new URLSearchParams(selectionQuery);
+ query.set("session", selected);
+ query.delete("tab");
+ router.replace(`/partners/${encodeURIComponent(partnerId)}?${query}`, { scroll: false });
+ }, [changeSessionKey, partnerId, router, selectionQuery]);
+ useEffect(() => {
+ if (!requestedSession) { requestedSelection.current = ""; return; }
+ if (!continuityReady) return;
+ const identity = `${partnerId}:${requestedSession}`;
+ if (requestedSelection.current === identity) return;
+ let alive = true;
+ void getPartnerSessions(partnerId).then(async rows => {
+ if (!alive) return;
+ requestedSelection.current = identity;
+ if (!rows.some(row => row.session_key === requestedSession && !row.archived)) {
+ setToast(t("navigation.sessionUnavailable"));
+ return;
+ }
+ setTab("chat");
+ await changeSessionKey(requestedSession);
+ }).catch(() => { if (alive) setToast(t("navigation.loadError")); });
+ return () => { alive = false; };
+ }, [requestedSession, continuityReady, partnerId, changeSessionKey, t]);
+
const toggleContinuity = useCallback(async () => {
if (!continuityReady || continuityBusy || switchingSession || runtimeContinuityError || chatBusy || !sessionKey) return;
selectionEpochRef.current += 1;
@@ -334,10 +370,10 @@ function PartnerDetail() {
const result = await archivePartnerSession(partnerId, sessionKey);
setChatMessages([]);
if (continuityEnabled) {
- if (result.active_session_key) changeSessionKey(result.active_session_key, true);
+ if (result.active_session_key) selectSessionKey(result.active_session_key, true);
else await reconcileSelection();
} else {
- changeSessionKey(freshPartnerSessionKey());
+ selectSessionKey(freshPartnerSessionKey());
}
setToast(t("Archived conversation"));
} catch (error) {
@@ -347,7 +383,7 @@ function PartnerDetail() {
}
}, [
archiveBusy,
- changeSessionKey,
+ selectSessionKey,
chatMessages.length,
continuityEnabled,
partnerId,
@@ -658,7 +694,7 @@ function PartnerDetail() {
color={partner.color}
avatar={partner.avatar}
sessionKey={sessionKey}
- onSessionKeyChange={changeSessionKey}
+ onSessionKeyChange={selectSessionKey}
onToast={setToast}
onMessagesChange={setChatMessages}
onRuntimeReady={handleRuntimeReady}
@@ -677,18 +713,18 @@ function PartnerDetail() {
onMessagesChange={setArchiveMessages}
onDeleted={(deletedKey, activeKey) => {
if (continuityEnabled) {
- if (activeKey) changeSessionKey(activeKey, true);
+ if (activeKey) selectSessionKey(activeKey, true);
else if (deletedKey === sessionKey) void reconcileSelection();
} else if (deletedKey === sessionKey) {
- changeSessionKey(freshPartnerSessionKey());
+ selectSessionKey(freshPartnerSessionKey());
}
}}
onResume={(key, activeKey, didCallResume) => {
if (continuityEnabled && didCallResume) {
- if (activeKey) changeSessionKey(activeKey, true);
+ if (activeKey) selectSessionKey(activeKey, true);
else void reconcileSelection();
} else {
- changeSessionKey(key);
+ selectSessionKey(key);
}
setTab("chat");
}}
diff --git a/web/app/(workspace)/partners/groups/[groupId]/page.tsx b/web/app/(workspace)/partners/groups/[groupId]/page.tsx
index dba56622f..26a069de0 100644
--- a/web/app/(workspace)/partners/groups/[groupId]/page.tsx
+++ b/web/app/(workspace)/partners/groups/[groupId]/page.tsx
@@ -2,7 +2,7 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
-import { useParams, useRouter } from "next/navigation";
+import { useParams, useRouter, useSearchParams } from "next/navigation";
import {
ArrowLeft,
Download,
@@ -23,6 +23,7 @@ import DiscussionModePicker, {
import {
deletePartnerGroup,
getPartnerGroup,
+ listPartnerGroupSessions,
updatePartnerGroup,
createPartnerGroupSessionKey,
partnerGroupSessionKey,
@@ -39,6 +40,8 @@ export default function PartnerGroupPage() {
const params = useParams<{ groupId: string }>();
const router = useRouter();
const groupId = decodeURIComponent(params.groupId);
+ const requestedSession = useSearchParams().get("session") || "";
+ const [selectionError, setSelectionError] = useState("");
const modeLabel = useDiscussionModeLabel();
const [group, setGroup] = useState<PartnerGroup | null>(null);
@@ -81,6 +84,22 @@ export default function PartnerGroupPage() {
void load();
}, [load]);
+ useEffect(() => {
+ if (loading || !group || !requestedSession) return;
+ let alive = true;
+ void listPartnerGroupSessions(groupId).then(rows => {
+ if (!alive) return;
+ const selected = rows.find(row => row.session_key === requestedSession);
+ if (!selected) { setSelectionError(t("navigation.sessionUnavailable")); return; }
+ setSelectionError("");
+ setGroupMessages([]);
+ setPartnerGroupSessionKey(groupId, selected.session_key);
+ setSessionKey(selected.session_key);
+ setSessionTitle(selected.title);
+ }).catch(() => { if (alive) setSelectionError(t("navigation.loadError")); });
+ return () => { alive = false; };
+ }, [groupId, group, loading, requestedSession, t]);
+
if (loading) {
return (
<div className="flex h-full items-center justify-center">
@@ -104,6 +123,7 @@ export default function PartnerGroupPage() {
return (
<div className="flex h-full min-h-0 flex-col">
+ {selectionError && <div role="alert" className="border-b border-border px-6 py-2 text-xs text-destructive">{selectionError}</div>}
<header className="flex shrink-0 items-center justify-between gap-4 border-b border-[var(--border)] px-4 py-3 sm:px-6">
<div className="flex min-w-0 items-center gap-3">
<Link
@@ -155,10 +175,12 @@ export default function PartnerGroupPage() {
setGroupMessages([]);
setPartnerGroupSessionKey(groupId, key);
setSessionKey(key);
+ router.replace(`/partners/groups/${encodeURIComponent(groupId)}?${new URLSearchParams({ session: key })}`, { scroll: false });
}}
onCreate={() => {
setGroupMessages([]);
setSessionKey(createPartnerGroupSessionKey(groupId));
+ router.replace(`/partners/groups/${encodeURIComponent(groupId)}`, { scroll: false });
}}
onTitleChange={setSessionTitle}
/>
diff --git a/web/app/globals.css b/web/app/globals.css
index 0c23a6d12..21e2894d5 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -1454,3 +1454,41 @@ a[href^="#dt-locator-"]:hover {
visibility: hidden;
pointer-events: none;
}
+
+/* dt-exp: the same application, with four contextual navigation shelves. */
+.dt-product-sidebar { container-type: inline-size; border-right: 1px solid var(--border); }
+.dt-product-sidebar .dt-category-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 10px 10px; flex-shrink: 0; }
+.dt-category-bar [role="tablist"] { display: flex; flex: 1; align-items: center; min-width: 0; gap: 1px; }
+.dt-category-bar [role="tab"] { position: relative; display: flex; align-items: center; justify-content: center; flex: 1; min-width: 30px; height: 36px; gap: 7px; padding: 0 7px; color: var(--muted-foreground); border-radius: 20px; transition: color 140ms, background-color 140ms; }
+.dt-category-bar [role="tab"] > svg, .dt-category-bar [role="tab"] > span:not(.dt-category-pill) { position: relative; z-index: 1; flex-shrink: 0; }
+.dt-category-bar [role="tab"] > span:not(.dt-category-pill) { display: none; font-size: 13px; font-weight: 600; white-space: nowrap; }
+.dt-category-bar [role="tab"].is-active { flex: 1.9; color: var(--foreground); }
+.dt-category-bar [role="tab"].is-active > span:not(.dt-category-pill) { display: inline; }
+.dt-category-pill { position: absolute; inset: 0; border-radius: 20px; background: var(--accent); }
+.dt-category-bar [role="tab"]:not(.is-active):hover, .dt-nav-icon:hover { background: var(--accent); color: var(--foreground); }
+.dt-nav-icon { display: inline-flex; flex-shrink: 0; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 6px; color: var(--muted-foreground); transition: background-color 140ms, color 140ms; }
+.dt-category-bar button:focus-visible, .dt-navigation-row:focus-visible, .dt-nav-icon:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
+.dt-product-sidebar .dt-category-bar.is-collapsed { flex-direction: column; padding: 4px; }
+.dt-category-bar.is-collapsed [role="tablist"] { flex-direction: column; gap: 5px; }
+.dt-category-bar.is-collapsed [role="tab"] { width: 38px; height: 38px; flex: none; }
+.dt-category-bar.is-collapsed [role="tab"] > span:not(.dt-category-pill) { display: none; }
+.dt-nav-search { width: 100%; margin-top: 8px; height: 32px; background: var(--background); border: 1px solid var(--border); border-radius: 7px; padding: 0 9px; font-size: 12px; outline: none; }
+.dt-nav-search:focus { border-color: var(--ring); }
+.dt-category-content { padding: 0 8px 16px; animation: dt-shelf-enter 160ms ease-out; }
+.dt-navigation-section { margin-top: 17px; }
+.dt-navigation-heading { display: flex; justify-content: space-between; align-items: center; min-height: 28px; margin-bottom: 4px; padding: 0 9px; font-size: 11px; font-weight: 600; color: var(--muted-foreground); }
+.dt-navigation-row { display: flex; align-items: center; gap: 9px; min-height: 36px; padding: 7px 9px; border-radius: 7px; text-align: left; color: var(--muted-foreground); font-size: 13px; transition: background-color 130ms, color 130ms; }
+.dt-navigation-row > svg { flex-shrink: 0; opacity: .85; }
+.dt-navigation-row:hover, .dt-navigation-row.is-active { background: var(--accent); color: var(--foreground); }
+.dt-navigation-row.is-active { font-weight: 500; }
+.dt-navigation-empty { padding: 6px 9px; font-size: 11.5px; line-height: 1.7; color: var(--muted-foreground); }
+.dt-partner-roster { display: flex; flex-wrap: wrap; gap: 10px; padding: 5px 5px 10px; }
+.dt-partner-roster-item { display: flex; align-items: center; flex-direction: column; gap: 7px; padding: 6px 3px; width: 66px; border-radius: 10px; transition: background-color 140ms; }
+.dt-partner-roster-item:hover { background: var(--accent); }
+.dt-partner-roster-item > span:last-child { font-size: 11px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; max-width: 100%; color: var(--muted-foreground); }
+.dt-partner-add { display: flex; align-items: center; justify-content: center; width: 42px; height: 42px; border: 1px dashed var(--border); border-radius: 50%; color: var(--muted-foreground); }
+.dt-new-conversation { display: flex; align-items: center; justify-content: center; gap: 9px; min-height: 40px; margin: 4px 3px 8px; border: 1px solid var(--border); border-radius: 22px; background: var(--background); font-size: 13px; font-weight: 500; box-shadow: 0 2px 5px rgb(0 0 0 / .025); transition: background-color 140ms, box-shadow 140ms; }
+.dt-new-conversation:hover { background: var(--accent); box-shadow: 0 2px 8px rgb(0 0 0 / .045); }
+@container (max-width: 240px) { .dt-category-bar [role="tab"] { padding: 0 4px; gap: 4px; } .dt-category-bar [role="tab"] > span:not(.dt-category-pill) { font-size: 12px; } }
+@keyframes dt-shelf-enter { from { opacity: .45; transform: translateY(3px); } to { opacity: 1; transform: translateY(0); } }
+@media (prefers-reduced-motion: reduce) { .dt-category-content { animation: none; } .dt-product-sidebar * { transition-duration: 0ms !important; } }
diff --git a/web/app/preview/PreviewClient.tsx b/web/app/preview/PreviewClient.tsx
new file mode 100644
index 000000000..a36ac7aea
--- /dev/null
+++ b/web/app/preview/PreviewClient.tsx
@@ -0,0 +1,13 @@
+'use client'
+import dynamic from 'next/dynamic'
+import { installDemoTransport } from '@/features/preview/demo-transport'
+import 'katex/dist/katex.min.css'
+import './preview.css'
+
+installDemoTransport()
+const PreviewWorkspace = dynamic(() => import('@/features/preview/PreviewWorkspace'), {
+ ssr: false,
+})
+export default function PreviewClient() {
+ return <PreviewWorkspace />
+}
diff --git a/web/app/preview/page.tsx b/web/app/preview/page.tsx
new file mode 100644
index 000000000..46e977d6b
--- /dev/null
+++ b/web/app/preview/page.tsx
@@ -0,0 +1,7 @@
+import PreviewClient from './PreviewClient'
+
+export const metadata = { title: 'DeepTutor · Dito 前端预览' }
+
+export default function PreviewPage() {
+ return <PreviewClient />
+}
diff --git a/web/app/preview/preview.css b/web/app/preview/preview.css
new file mode 100644
index 000000000..9e24e4c71
--- /dev/null
+++ b/web/app/preview/preview.css
@@ -0,0 +1,1582 @@
+/* Layout exploration only. Reader, editor, composer, cards, dialogs, themes,
+ typography, icons and responsive shell come from the existing WebUI. */
+.dito-preview {
+ height: 100dvh;
+ color: var(--foreground);
+}
+.dito-preview button {
+ -webkit-tap-highlight-color: transparent;
+}
+.dito-preview button:focus-visible,
+.dito-preview input:focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 3px;
+}
+.preview-sidebar-head {
+ padding: 10px 8px 0;
+}
+.preview-sidebar-body {
+ padding: 4px 8px;
+}
+.preview-nav-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-height: 35px;
+ width: 100%;
+ padding: 7px 10px;
+ border-radius: 7px;
+ font-size: 13px;
+ color: var(--muted-foreground);
+ text-align: left;
+ transition:
+ background 120ms,
+ color 120ms;
+}
+.preview-nav-row > svg {
+ flex-shrink: 0;
+}
+.preview-nav-row > span {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.preview-nav-row:hover {
+ background: color-mix(in srgb, var(--foreground) 4%, transparent);
+ color: var(--foreground);
+}
+.preview-nav-row.is-active {
+ background: color-mix(in srgb, var(--foreground) 6%, transparent);
+ color: var(--foreground);
+ font-weight: 500;
+}
+.preview-nav-row kbd {
+ font: 10px inherit;
+ color: var(--muted-foreground);
+ opacity: 0.7;
+ white-space: nowrap;
+}
+.preview-nav-row.is-collapsed {
+ padding: 10px;
+ justify-content: center;
+}
+.preview-nav-label {
+ padding: 24px 10px 8px;
+ font-size: 11px;
+ font-weight: 500;
+ color: var(--muted-foreground);
+ opacity: 0.75;
+}
+.preview-sidebar-note {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 28px 10px;
+ color: var(--muted-foreground);
+ font-size: 11px;
+}
+.preview-sidebar-note > svg {
+ margin-left: auto;
+}
+.preview-small-dot {
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: var(--primary);
+ opacity: 0.5;
+}
+.preview-sidebar-footer {
+ width: 100%;
+ padding: 8px 8px 14px;
+}
+.preview-new-chat {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ margin-top: 8px;
+ padding: 10px 12px;
+ border: 1px solid var(--border);
+ border-radius: 9px;
+ background: var(--background);
+ font-size: 12px;
+ box-shadow: 0 2px 4px #00000003;
+}
+.preview-new-chat span {
+ flex: 1;
+ text-align: left;
+}
+.preview-new-chat.is-collapsed {
+ padding: 10px;
+ justify-content: center;
+}
+.preview-new-chat:hover {
+ border-color: var(--muted-foreground);
+}
+.preview-topbar {
+ height: 52px;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 14px;
+ padding: 0 25px;
+}
+.preview-breadcrumb {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ min-width: 0;
+ font-size: 12px;
+}
+.preview-breadcrumb button,
+.preview-breadcrumb > svg {
+ color: var(--muted-foreground);
+ flex-shrink: 0;
+}
+.preview-breadcrumb span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.preview-top-actions {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-shrink: 0;
+}
+.preview-badge {
+ font-size: 10px;
+ color: var(--muted-foreground);
+ padding: 3px 7px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ margin-right: 8px;
+}
+.preview-icon {
+ display: flex;
+ width: 28px;
+ height: 28px;
+ align-items: center;
+ justify-content: center;
+ border-radius: 5px;
+ color: var(--muted-foreground);
+}
+.preview-icon:hover,
+.preview-icon.is-active {
+ background: var(--muted);
+ color: var(--foreground);
+}
+.preview-icon.is-active > svg {
+ fill: color-mix(in srgb, var(--primary) 20%, transparent);
+ color: var(--primary);
+}
+.preview-dito-toggle {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 9px;
+ font-size: 12px;
+ border-radius: 6px;
+ border: 1px solid var(--border);
+}
+.preview-dito-toggle.is-active {
+ background: var(--muted);
+}
+.preview-work-area {
+ display: flex;
+ flex: 1;
+ min-height: 0;
+ min-width: 0;
+ overflow: hidden;
+}
+.preview-main {
+ flex: 1;
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+}
+.preview-home-inner {
+ max-width: 830px;
+ margin: 22px auto 0;
+}
+.preview-eyebrow {
+ font-size: 11px;
+ letter-spacing: 0.025em;
+ color: var(--muted-foreground);
+ margin-bottom: 12px;
+}
+.preview-home [data-page-header] {
+ margin-bottom: 25px;
+}
+.preview-home .dt-page-title {
+ font-size: 30px;
+}
+.preview-home-composer {
+ margin: 0 -2px;
+}
+.preview-quick-actions {
+ display: flex;
+ gap: 9px;
+ margin-top: 15px;
+ flex-wrap: wrap;
+}
+.preview-quick-actions button {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12px;
+ color: var(--muted-foreground);
+ padding: 6px 10px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ transition: background 120ms;
+}
+.preview-quick-actions button:hover {
+ color: var(--foreground);
+ background: var(--muted);
+}
+.preview-quick-actions button > svg:last-child {
+ opacity: 0.4;
+ margin-left: 5px;
+}
+.preview-section {
+ margin-top: 45px;
+}
+.preview-section-title {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 14px;
+}
+.preview-section-title h2 {
+ font-size: 13px;
+ font-weight: 600;
+}
+.preview-section-title button {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.preview-resume-list {
+ border-top: 1px solid var(--border);
+}
+.preview-content-row {
+ display: flex;
+ width: 100%;
+ min-width: 0;
+ align-items: center;
+ gap: 13px;
+ padding: 16px 3px;
+ text-align: left;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 60%, transparent);
+ border-radius: 3px;
+ transition: background 120ms;
+}
+.preview-content-row:hover {
+ background: color-mix(in srgb, var(--muted) 60%, transparent);
+}
+.preview-review {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ margin-top: 28px;
+ padding: 18px 20px;
+ border-radius: 10px;
+ background: color-mix(in srgb, var(--secondary) 70%, var(--background));
+}
+.preview-review-icon {
+ color: var(--muted-foreground);
+}
+.preview-review > div:nth-child(2) {
+ flex: 1;
+}
+.preview-review h3 {
+ font-size: 12.5px;
+ font-weight: 500;
+}
+.preview-review p {
+ margin-top: 5px;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.preview-home-footnote {
+ margin: 25px 0 10px;
+ font-size: 10.5px;
+ color: var(--muted-foreground);
+ text-align: center;
+ opacity: 0.75;
+}
+.preview-filters {
+ display: flex;
+ gap: 6px;
+ border-bottom: 1px solid var(--border);
+ padding-bottom: 10px;
+ overflow-x: auto;
+}
+.preview-filters button {
+ font-size: 12px;
+ color: var(--muted-foreground);
+ padding: 6px 12px;
+ border-radius: 6px;
+ white-space: nowrap;
+}
+.preview-filters button.is-active {
+ background: var(--muted);
+ color: var(--foreground);
+}
+.preview-learning-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(270px, 1fr));
+ gap: 16px;
+}
+.preview-learning-card {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 12px;
+ padding: 22px;
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ text-align: left;
+ transition: background 120ms;
+}
+.preview-learning-card:hover {
+ background: var(--secondary);
+}
+.preview-card-meta {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ width: 100%;
+ font-size: 11px;
+ color: var(--muted-foreground);
+ margin-bottom: 10px;
+}
+.preview-library-callout {
+ display: flex;
+ gap: 16px;
+ align-items: center;
+ padding: 24px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+}
+.preview-library-callout > div {
+ flex: 1;
+}
+.preview-library-callout h3 {
+ font-size: 13px;
+}
+.preview-library-callout p {
+ font-size: 12px;
+ color: var(--muted-foreground);
+ margin-top: 6px;
+}
+.preview-library-label,
+.preview-library-row {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 130px 80px;
+ gap: 20px;
+ width: 100%;
+ padding: 16px 10px;
+ border-bottom: 1px solid var(--border);
+ text-align: left;
+}
+.preview-library-label {
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.preview-library-row {
+ font-size: 13px;
+ align-items: center;
+}
+.preview-library-row:hover {
+ background: var(--secondary);
+}
+.preview-library-row > span:first-child {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+.preview-library-row > span:first-child > svg {
+ flex-shrink: 0;
+ color: var(--muted-foreground);
+}
+.preview-library-row > span:not(:first-child) {
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.preview-library-summary {
+ padding: 16px 10px;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.preview-search-field {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ border: 1px solid var(--border);
+ padding: 8px 11px;
+ border-radius: 7px;
+ color: var(--muted-foreground);
+}
+.preview-search-field input {
+ width: 100%;
+ background: transparent;
+ outline: none;
+ font-size: 12px;
+ color: var(--foreground);
+}
+.preview-search-field.large {
+ padding: 12px;
+}
+.preview-search-field.large input {
+ font-size: 14px;
+}
+.preview-search-field kbd {
+ font-size: 10px;
+}
+.preview-search-results {
+ margin-top: 15px;
+}
+.preview-reading-surface {
+ height: 100%;
+ display: flex;
+ min-width: 0;
+}
+.preview-reading-outline {
+ width: 172px;
+ flex-shrink: 0;
+ padding: 5px 10px;
+ border-top: 1px solid var(--border);
+}
+.preview-reading-outline button {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ width: 100%;
+ padding: 10px 8px;
+ text-align: left;
+ color: var(--muted-foreground);
+ font-size: 11px;
+ border-radius: 5px;
+}
+.preview-reading-outline button > span {
+ font-size: 10px;
+ opacity: 0.5;
+}
+.preview-reading-outline button.is-active {
+ color: var(--foreground);
+ background: var(--secondary);
+}
+.preview-reader {
+ flex: 1;
+ min-width: 0;
+ height: 100%;
+}
+.preview-assistant {
+ width: 360px;
+ flex-shrink: 0;
+ border-left: 1px solid var(--border);
+ display: flex;
+ flex-direction: column;
+ background: var(--background);
+}
+.preview-assistant > header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ height: 44px;
+ padding: 0 15px;
+ border-top: 1px solid var(--border);
+}
+.preview-assistant > header strong {
+ font-size: 13px;
+ font-weight: 500;
+}
+.preview-assistant > header > span {
+ font-size: 10px;
+ color: var(--muted-foreground);
+ flex: 1;
+}
+.preview-context-chip {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 10px;
+ margin: 8px 14px 0;
+ border-radius: 6px;
+ background: var(--secondary);
+ font-size: 10px;
+ color: var(--muted-foreground);
+}
+.preview-context-chip > span:first-of-type {
+ flex: 1;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+.preview-context-chip > span:last-child {
+ font-size: 9px;
+ opacity: 0.6;
+ flex-shrink: 0;
+}
+.preview-conversation {
+ overflow-y: auto;
+ min-height: 0;
+ flex: 1;
+ padding: 24px;
+ scroll-behavior: smooth;
+}
+.preview-conversation-empty {
+ padding-top: 45px;
+}
+.preview-conversation-empty h2 {
+ font-size: 20px;
+ font-weight: 500;
+ margin-top: 15px;
+}
+.preview-conversation-empty p {
+ font-size: 12px;
+ color: var(--muted-foreground);
+ line-height: 1.8;
+ margin-top: 8px;
+}
+.preview-conversation-empty > div {
+ margin-top: 25px;
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ align-items: flex-start;
+}
+.preview-conversation-empty button {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ border: 1px solid var(--border);
+ padding: 8px 11px;
+ border-radius: 6px;
+ font-size: 11px;
+ text-align: left;
+}
+.preview-conversation-empty button:hover {
+ background: var(--secondary);
+}
+.preview-message {
+ margin-bottom: 26px;
+ font-size: 13px;
+}
+.preview-message-label {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ margin-bottom: 8px;
+ font-size: 11px;
+ font-weight: 500;
+}
+.preview-message-label > span {
+ font-size: 9px;
+ font-weight: 400;
+ color: var(--muted-foreground);
+}
+.preview-message.user {
+ padding: 12px 14px;
+ background: var(--secondary);
+ border-radius: 9px;
+}
+.preview-message p {
+ font-size: 13px;
+ line-height: 1.85;
+}
+.preview-result-link {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ text-align: left;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ margin-top: 18px;
+ font-size: 12px;
+}
+.preview-result-link span {
+ flex: 1;
+}
+.preview-result-link:hover {
+ background: var(--secondary);
+}
+.preview-panel-composer {
+ padding: 8px 12px 14px;
+}
+.preview-panel-composer > p,
+.preview-chat-composer > p {
+ text-align: center;
+ font-size: 9px;
+ color: var(--muted-foreground);
+ margin-top: 8px;
+}
+.preview-quote {
+ display: flex;
+ gap: 8px;
+ align-items: flex-start;
+ padding: 8px 12px;
+ border-left: 2px solid var(--primary);
+ margin: 10px 12px 0;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.preview-quote > span {
+ flex: 1;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.preview-chat-page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ width: 100%;
+ max-width: 850px;
+ margin: auto;
+}
+.preview-chat-heading {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 16px 25px;
+}
+.preview-chat-heading h1 {
+ font-size: 16px;
+ font-weight: 500;
+}
+.preview-chat-heading span {
+ flex: 1;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.preview-chat-heading button {
+ padding: 6px;
+}
+.preview-chat-composer {
+ padding: 12px 25px 20px;
+}
+.preview-thinking {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.preview-thinking span {
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: var(--primary);
+ animation: preview-pulse 1s ease-in-out infinite;
+}
+@keyframes preview-pulse {
+ 50% {
+ opacity: 0.25;
+ }
+}
+.preview-mastery-layout {
+ display: flex;
+ gap: 40px;
+}
+.preview-objectives {
+ width: 195px;
+ flex-shrink: 0;
+}
+.preview-objectives .preview-nav-label {
+ padding: 0 0 16px;
+}
+.preview-objectives button {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 12px 6px;
+ width: 100%;
+ text-align: left;
+ font-size: 11px;
+ color: var(--muted-foreground);
+ border-radius: 5px;
+}
+.preview-objectives button.is-active {
+ color: var(--foreground);
+ background: var(--secondary);
+}
+.preview-objectives button > span {
+ width: 18px;
+ font-size: 10px;
+}
+.preview-lesson {
+ flex: 1;
+ min-width: 0;
+ max-width: 650px;
+}
+.preview-lesson h2 {
+ font-family: var(--font-serif);
+ font-size: 24px;
+ font-weight: 500;
+}
+.preview-lesson-intro {
+ margin: 18px 0 30px;
+ font-size: 13px;
+ line-height: 2;
+ color: var(--muted-foreground);
+}
+.preview-lesson-next {
+ display: flex;
+ gap: 10px;
+ margin-top: 25px;
+}
+.preview-start-auto {
+ display: flex;
+ align-items: center;
+ gap: 15px;
+ width: 100%;
+ padding: 20px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ text-align: left;
+}
+.preview-start-auto > div {
+ flex: 1;
+}
+.preview-start-auto strong {
+ font-size: 14px;
+ font-weight: 500;
+}
+.preview-start-auto p {
+ margin-top: 5px;
+ font-size: 12px;
+ color: var(--muted-foreground);
+}
+.preview-start-auto:hover {
+ background: var(--secondary);
+}
+.preview-theme-options {
+ display: flex;
+ gap: 10px;
+}
+.preview-theme-options button {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 18px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ font-size: 13px;
+}
+.preview-theme-options button.is-active {
+ border-color: var(--primary);
+}
+.preview-about p {
+ font-size: 13px;
+ line-height: 1.9;
+ margin-bottom: 15px;
+}
+@media (min-width: 1600px) {
+ .preview-home-inner {
+ margin-top: 50px;
+ }
+ .preview-assistant {
+ width: 390px;
+ }
+}
+@media (max-width: 1250px) {
+ .preview-reading-outline {
+ display: none;
+ }
+ .preview-assistant {
+ width: 335px;
+ }
+ .preview-mastery-layout {
+ gap: 22px;
+ }
+ .preview-objectives {
+ width: 150px;
+ }
+}
+@media (max-width: 900px) {
+ .preview-assistant {
+ position: fixed;
+ right: 0;
+ bottom: 0;
+ top: 52px;
+ z-index: 40;
+ width: min(390px, 100vw);
+ box-shadow: -12px 0 40px #0000000b;
+ }
+}
+@media (max-width: 767px) {
+ .preview-topbar {
+ height: 42px;
+ padding: 0 16px;
+ }
+ .preview-breadcrumb > button,
+ .preview-breadcrumb > svg,
+ .preview-badge {
+ display: none;
+ }
+ .preview-home-inner {
+ margin-top: 5px;
+ }
+ .preview-home .dt-page-title {
+ font-size: 27px;
+ }
+ .preview-home-footnote {
+ line-height: 1.8;
+ }
+ .preview-section {
+ margin-top: 30px;
+ }
+ .preview-review {
+ padding: 14px;
+ flex-wrap: wrap;
+ }
+ .preview-review > button {
+ width: 100%;
+ }
+ .preview-library-callout {
+ align-items: flex-start;
+ flex-wrap: wrap;
+ }
+ .preview-library-callout > button {
+ width: 100%;
+ }
+ .preview-library-label,
+ .preview-library-row {
+ grid-template-columns: minmax(0, 1fr) 80px;
+ gap: 12px;
+ }
+ .preview-library-label > span:last-child,
+ .preview-library-row > span:last-child {
+ display: none;
+ }
+ .preview-mastery-layout {
+ flex-direction: column;
+ }
+ .preview-objectives {
+ display: flex;
+ width: 100%;
+ overflow: auto;
+ gap: 5px;
+ }
+ .preview-objectives .preview-nav-label {
+ display: none;
+ }
+ .preview-objectives button {
+ white-space: nowrap;
+ width: auto;
+ padding: 9px 12px;
+ }
+ .preview-assistant {
+ top: 48px;
+ }
+ .preview-quick-actions {
+ gap: 6px;
+ }
+ .preview-quick-actions button {
+ font-size: 11px;
+ }
+ .preview-quick-actions button > svg:last-child {
+ display: none;
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .dito-preview * {
+ scroll-behavior: auto !important;
+ animation: none !important;
+ transition: none !important;
+ }
+}
+
+.preview-home-composer > div,
+.preview-panel-composer > div,
+.preview-chat-composer > div {
+ max-width: none;
+ padding: 0;
+}
+
+.preview-layout {
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.preview-assistant > header > button {
+ font-size: 12px;
+}
+@media (max-width: 767px) {
+ .preview-nav-row {
+ min-height: 44px;
+ }
+}
+
+/* Category navigation: a stable document canvas with four sidebar contexts. */
+.dito-preview {
+ --preview-sidebar: #f8f7f5;
+ font-family:
+ var(--font-sans),
+ -apple-system,
+ BlinkMacSystemFont,
+ 'Segoe UI',
+ 'PingFang SC',
+ sans-serif;
+}
+.dito-preview aside[style*='--sidebar-width'] {
+ background: var(--preview-sidebar);
+ border-right: 1px solid color-mix(in srgb, var(--foreground) 5%, transparent);
+}
+.dark .dito-preview {
+ --preview-sidebar: #222220;
+}
+.dito-preview .dt-page-title {
+ font-family: inherit;
+ font-weight: 650;
+ letter-spacing: -0.035em;
+}
+.preview-category-bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+ padding: 9px 12px 8px;
+ flex-shrink: 0;
+}
+.preview-category-bar [role='tablist'] {
+ display: flex;
+ align-items: center;
+ gap: 3px;
+}
+.preview-category-bar [role='tab'] {
+ display: flex;
+ position: relative;
+ align-items: center;
+ justify-content: center;
+ height: 35px;
+ padding: 0 8px;
+ border-radius: 22px;
+ color: color-mix(in srgb, var(--foreground) 52%, transparent);
+ transition:
+ color 130ms,
+ background 130ms,
+ transform 130ms;
+}
+.preview-category-bar [role='tab'] > svg,
+.preview-category-name {
+ position: relative;
+ z-index: 1;
+ flex-shrink: 0;
+}
+.preview-category-bar [role='tab']:hover {
+ background: color-mix(in srgb, var(--foreground) 4%, transparent);
+ color: var(--foreground);
+}
+.preview-category-bar [role='tab']:active {
+ transform: scale(0.96);
+}
+.preview-category-bar [role='tab'].is-active {
+ color: var(--foreground);
+}
+.preview-category-pill {
+ position: absolute;
+ inset: 0;
+ border-radius: 22px;
+ background: color-mix(in srgb, var(--foreground) 6%, transparent);
+}
+.preview-category-name {
+ font-size: 14px;
+ font-weight: 600;
+ overflow: hidden;
+ white-space: nowrap;
+ transition:
+ max-width 0.22s cubic-bezier(0.22, 1, 0.36, 1),
+ opacity 0.13s,
+ margin-left 0.22s;
+}
+.preview-category-bar [role='tab'].is-active .preview-category-name {
+ margin-left: 7px;
+}
+.preview-category-search {
+ display: flex;
+ height: 34px;
+ width: 30px;
+ flex-shrink: 0;
+ justify-content: center;
+ align-items: center;
+ color: var(--muted-foreground);
+ border-radius: 7px;
+ transition:
+ background 140ms,
+ color 140ms;
+}
+.preview-category-search:hover {
+ background: color-mix(in srgb, var(--foreground) 5%, transparent);
+ color: var(--foreground);
+}
+.preview-category-bar.is-collapsed,
+.preview-category-bar.is-collapsed [role='tablist'] {
+ flex-direction: column;
+}
+.preview-category-bar.is-collapsed {
+ padding: 10px 4px;
+}
+.preview-category-bar.is-collapsed .preview-category-name {
+ display: none;
+}
+.preview-category-content {
+ padding: 0 9px 30px;
+ animation: preview-category-enter 0.18s ease-out;
+}
+@keyframes preview-category-enter {
+ from {
+ opacity: 0.25;
+ transform: translateY(3px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+.preview-sidebar-section-label {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 25px 10px 7px;
+ color: color-mix(in srgb, var(--foreground) 42%, transparent);
+ font-size: 11.5px;
+ font-weight: 550;
+}
+.preview-sidebar-section-label button {
+ display: grid;
+ place-items: center;
+ height: 24px;
+ width: 24px;
+ border-radius: 5px;
+ transition:
+ color 130ms,
+ background 130ms;
+}
+.preview-sidebar-section-label button:hover {
+ color: var(--foreground);
+ background: color-mix(in srgb, var(--foreground) 6%, transparent);
+}
+.preview-nav-row {
+ min-height: 36px;
+ font-size: 13.5px;
+ gap: 10px;
+ border-radius: 6px;
+ padding: 8px 10px;
+ color: color-mix(in srgb, var(--foreground) 73%, transparent);
+ transition:
+ background 140ms,
+ color 140ms,
+ transform 100ms;
+}
+.preview-nav-row > svg {
+ color: color-mix(in srgb, var(--foreground) 45%, transparent);
+}
+.preview-nav-row:active {
+ transform: scale(0.987);
+}
+.preview-nav-row small {
+ color: var(--muted-foreground);
+ font-size: 11px;
+}
+.preview-nav-row .preview-row-reveal {
+ opacity: 0;
+ transition:
+ opacity 120ms,
+ transform 120ms;
+ transform: translateX(-2px);
+}
+.preview-nav-row:hover .preview-row-reveal,
+.preview-nav-row:focus-visible .preview-row-reveal {
+ opacity: 1;
+ transform: translateX(0);
+}
+.preview-sidebar-add {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 9px 10px;
+ margin-top: 8px;
+ color: var(--muted-foreground);
+ font-size: 13px;
+ width: 100%;
+ border-radius: 6px;
+ transition: background 140ms;
+}
+.preview-sidebar-add:hover {
+ background: color-mix(in srgb, var(--foreground) 4%, transparent);
+}
+.preview-sidebar-footer {
+ padding: 8px 12px 16px;
+}
+.preview-new-chat {
+ justify-content: center;
+ height: 43px;
+ border-radius: 24px;
+ background: var(--background);
+ box-shadow:
+ 0 2px 3px #00000003,
+ 0 4px 9px #00000004;
+ transition:
+ box-shadow 150ms,
+ transform 120ms,
+ background 150ms;
+}
+.preview-new-chat:hover {
+ transform: translateY(-1px);
+ box-shadow: 0 3px 12px #0000000b;
+}
+.preview-new-chat:active {
+ transform: translateY(0);
+}
+.preview-partner-roster {
+ display: flex;
+ gap: 5px;
+ padding: 12px 5px 18px;
+ overflow-x: auto;
+ scrollbar-width: thin;
+}
+.preview-partner-roster > button {
+ width: 68px;
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 9px;
+ padding: 7px 3px;
+ border-radius: 9px;
+ transition:
+ background 130ms,
+ transform 130ms;
+}
+.preview-partner-roster > button:hover {
+ background: color-mix(in srgb, var(--foreground) 4%, transparent);
+ transform: translateY(-2px);
+}
+.preview-partner-roster > button.is-active {
+ background: color-mix(in srgb, var(--foreground) 6%, transparent);
+}
+.preview-partner-roster > button > span:last-child {
+ font-size: 10.5px;
+ width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ color: var(--muted-foreground);
+}
+.preview-add-avatar {
+ height: 45px;
+ width: 45px;
+ border: 1.5px dashed var(--border);
+ border-radius: 50%;
+ display: grid;
+ place-items: center;
+ color: var(--muted-foreground);
+}
+.preview-filter-bar {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+}
+.preview-filter-bar button {
+ padding: 7px 12px;
+ border-radius: 6px;
+ font-size: 12px;
+ color: var(--muted-foreground);
+ transition:
+ background 140ms,
+ color 140ms;
+}
+.preview-filter-bar button:hover,
+.preview-filter-bar .is-active {
+ background: var(--muted);
+ color: var(--foreground);
+}
+.preview-new-learning-row {
+ display: flex;
+ align-items: center;
+ width: 100%;
+ gap: 15px;
+ margin-top: 22px;
+ border: 1px dashed var(--border);
+ padding: 20px;
+ border-radius: 10px;
+ text-align: left;
+ color: var(--muted-foreground);
+ transition: background 140ms;
+}
+.preview-new-learning-row:hover {
+ background: color-mix(in srgb, var(--muted) 40%, transparent);
+}
+.preview-new-learning-row span {
+ font-size: 13px;
+ font-weight: 500;
+}
+.preview-new-learning-row strong {
+ display: block;
+ font-size: 11px;
+ font-weight: 400;
+ margin-top: 4px;
+ opacity: 0.75;
+}
+.preview-create-form {
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+}
+.preview-create-form label,
+.preview-field {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ font-size: 12px;
+ font-weight: 500;
+}
+.preview-create-form input:not([type='checkbox']),
+.preview-create-form textarea,
+.preview-field input,
+.preview-field textarea {
+ display: block;
+ width: 100%;
+ border: 1px solid var(--border);
+ background: var(--background);
+ padding: 10px 12px;
+ border-radius: 7px;
+ font-size: 13px;
+ font-weight: 400;
+ outline: none;
+ resize: vertical;
+}
+.preview-create-form input:focus,
+.preview-create-form textarea:focus,
+.preview-field input:focus,
+.preview-field textarea:focus {
+ border-color: color-mix(in srgb, var(--foreground) 35%, transparent);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--foreground) 4%, transparent);
+}
+.preview-kind-picker {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 9px;
+}
+.preview-kind-picker button {
+ display: flex;
+ gap: 12px;
+ padding: 16px 12px;
+ text-align: left;
+ border: 1px solid var(--border);
+ border-radius: 9px;
+ align-items: center;
+ color: var(--muted-foreground);
+ transition:
+ background 130ms,
+ border-color 130ms;
+}
+.preview-kind-picker button span {
+ flex: 1;
+ font-size: 13px;
+ color: var(--foreground);
+}
+.preview-kind-picker small {
+ display: block;
+ font-size: 11px;
+ margin-top: 5px;
+ color: var(--muted-foreground);
+ line-height: 1.5;
+}
+.preview-kind-picker button.is-active {
+ border-color: color-mix(in srgb, var(--foreground) 45%, transparent);
+ background: var(--muted);
+}
+.preview-kind-picker button:hover {
+ background: var(--muted);
+}
+.preview-form-footer {
+ display: flex;
+ gap: 15px;
+ align-items: center;
+ justify-content: space-between;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.preview-back-link {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--muted-foreground);
+ margin-bottom: 24px;
+}
+.preview-back-link:hover {
+ color: var(--foreground);
+}
+.preview-record-draft {
+ max-width: 760px;
+ display: flex;
+ flex-direction: column;
+ gap: 22px;
+}
+.preview-draft-status {
+ display: flex;
+ align-items: center;
+ gap: 13px;
+ padding: 16px;
+ border: 1px solid var(--border);
+ border-radius: 9px;
+ color: var(--muted-foreground);
+}
+.preview-draft-status strong {
+ font-size: 13px;
+ color: var(--foreground);
+}
+.preview-draft-status p {
+ font-size: 12px;
+ margin-top: 4px;
+}
+.preview-note-render {
+ padding: 24px;
+ border-radius: 9px;
+ border: 1px solid var(--border);
+}
+.preview-local-note {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+ color: var(--muted-foreground);
+ font-size: 11px;
+ margin-top: 12px;
+}
+.preview-record-practice {
+ max-width: 760px;
+}
+.preview-partner-cards {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 12px;
+}
+.preview-partner-cards > button {
+ display: flex;
+ align-items: flex-start;
+ gap: 16px;
+ text-align: left;
+ padding: 25px 20px;
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ transition:
+ background 140ms,
+ border-color 140ms;
+}
+.preview-partner-cards > button:hover {
+ background: var(--muted);
+ border-color: color-mix(in srgb, var(--foreground) 20%, transparent);
+}
+.preview-partner-cards button > div {
+ flex: 1;
+}
+.preview-partner-cards h3 {
+ font-size: 15px;
+ font-weight: 600;
+}
+.preview-partner-cards p {
+ font-size: 12px;
+ color: var(--muted-foreground);
+ line-height: 1.8;
+ margin: 8px 0 13px;
+}
+.preview-partner-cards small {
+ font-size: 10px;
+ color: var(--muted-foreground);
+}
+.preview-group-row {
+ display: flex;
+ align-items: center;
+ gap: 17px;
+ width: 100%;
+ padding: 18px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ text-align: left;
+ transition: background 140ms;
+ margin-bottom: 8px;
+}
+.preview-group-row:hover {
+ background: var(--muted);
+}
+.preview-group-row > span {
+ flex: 1;
+}
+.preview-group-row strong {
+ font-size: 13px;
+ font-weight: 500;
+}
+.preview-group-row small {
+ display: block;
+ font-size: 11px;
+ color: var(--muted-foreground);
+ margin-top: 6px;
+}
+.preview-session-row {
+ display: flex;
+ align-items: center;
+ width: 100%;
+ padding: 13px 10px;
+ gap: 13px;
+ text-align: left;
+ border-radius: 7px;
+ transition: background 130ms;
+ font-size: 13px;
+}
+.preview-session-row span {
+ flex: 1;
+}
+.preview-session-row small {
+ color: var(--muted-foreground);
+ font-size: 11px;
+}
+.preview-session-row svg {
+ color: var(--muted-foreground);
+}
+.preview-session-row:hover {
+ background: var(--muted);
+}
+.preview-partner-detail {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 20px;
+ padding: 25px 0 55px;
+}
+.preview-partner-detail h2 {
+ font-size: 22px;
+ font-weight: 600;
+}
+.preview-partner-detail p {
+ color: var(--muted-foreground);
+ font-size: 13px;
+}
+.preview-partner-chat {
+ max-width: 760px;
+ margin: 20px auto;
+}
+.preview-partner-message {
+ padding: 18px 0;
+}
+.preview-partner-message > small {
+ color: var(--muted-foreground);
+ display: block;
+ margin-bottom: 10px;
+}
+.preview-partner-message.user {
+ padding: 15px 20px;
+ border-radius: 12px;
+ background: var(--muted);
+}
+.preview-partner-chat form {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ padding: 12px;
+ margin-top: 25px;
+}
+.preview-partner-chat form input {
+ flex: 1;
+ background: transparent;
+ outline: none;
+ padding: 5px;
+ min-width: 0;
+ font-size: 13px;
+}
+.preview-partner-empty,
+.preview-resource-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 15px;
+ padding: 60px 20px;
+ text-align: center;
+}
+.preview-partner-empty h2,
+.preview-resource-empty h2 {
+ font-size: 20px;
+ font-weight: 600;
+}
+.preview-partner-empty p,
+.preview-resource-empty p {
+ font-size: 13px;
+ color: var(--muted-foreground);
+}
+.preview-resource-empty small {
+ max-width: 380px;
+ font-size: 11px;
+ color: var(--muted-foreground);
+ line-height: 1.8;
+}
+.preview-create-form .preview-member-choice {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 0;
+}
+.preview-resource-entry {
+ border-bottom: 1px solid var(--border);
+}
+@media (max-width: 767px) {
+ .dito-preview aside[style*='--sidebar-width'] {
+ width: 272px;
+ }
+ .preview-partner-cards {
+ grid-template-columns: 1fr;
+ }
+ .preview-kind-picker {
+ grid-template-columns: 1fr;
+ }
+ .preview-form-footer {
+ flex-wrap: wrap;
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .dito-preview *,
+ .dito-preview *::before,
+ .dito-preview *::after {
+ animation-duration: 0.001ms !important;
+ transition-duration: 0.001ms !important;
+ scroll-behavior: auto !important;
+ }
+}
+.dito-preview aside[style*='--sidebar-width'] {
+ container-type: inline-size;
+}
+@container (max-width: 245px) {
+ .preview-category-bar {
+ padding-inline: 8px;
+ gap: 2px;
+ }
+ .preview-category-bar [role='tablist'] {
+ gap: 0;
+ }
+ .preview-category-bar [role='tab'] {
+ padding-inline: 5px;
+ }
+ .preview-category-search {
+ width: 26px;
+ }
+ .preview-category-bar [role='tab'].is-active .preview-category-name {
+ margin-left: 4px;
+ }
+}
diff --git a/web/components/chat/home/HomeShortcuts.tsx b/web/components/chat/home/HomeShortcuts.tsx
new file mode 100644
index 000000000..725c58a13
--- /dev/null
+++ b/web/components/chat/home/HomeShortcuts.tsx
@@ -0,0 +1,34 @@
+'use client'
+import Link from 'next/link'
+import { Columns3, PenLine, Bot } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { useAuthStatus } from '@/hooks/useAuthStatus'
+import { navVisibleUnderPolicy } from '@/components/sidebar/nav-entries'
+export function HomeShortcuts() {
+ const { t } = useTranslation()
+ const { learningPolicy } = useAuthStatus()
+ return (
+ <nav
+ aria-label={t('navigation.workspace')}
+ className="mt-6 flex flex-wrap justify-center gap-2"
+ >
+ {[
+ { href: '/kanban', title: 'Task Board', icon: Columns3 },
+ { href: '/co-writer', title: 'Co-Writer', icon: PenLine },
+ { href: '/agents', title: 'My Agents', icon: Bot },
+ ]
+ .filter(item => navVisibleUnderPolicy(item.href, learningPolicy?.allowedSurfaces ?? null))
+ .map(item => (
+ <Link
+ key={item.href}
+ href={item.href}
+ prefetch={false}
+ className="inline-flex items-center gap-2 rounded-full bg-muted/50 px-4 py-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ >
+ <item.icon size={15} strokeWidth={1.6} />
+ {t(item.title)}
+ </Link>
+ ))}
+ </nav>
+ )
+}
diff --git a/web/components/layout/AppShell.tsx b/web/components/layout/AppShell.tsx
index 7d3ce05ce..bd35c7bbb 100644
--- a/web/components/layout/AppShell.tsx
+++ b/web/components/layout/AppShell.tsx
@@ -28,6 +28,7 @@ export function useSidebarDrawer() {
interface AppShellProps {
/** The route group's sidebar (workspace or utility). */
sidebar: ReactNode;
+ homeHref?: string;
children: ReactNode;
}
@@ -47,7 +48,7 @@ interface AppShellProps {
* the very first server-rendered paint is already correct on a phone. JS only
* owns the part that is stateful anyway: whether the drawer is open.
*/
-export default function AppShell({ sidebar, children }: AppShellProps) {
+export default function AppShell({ sidebar, children, homeHref = "/" }: AppShellProps) {
const { t } = useTranslation();
const pathname = usePathname();
const { isMobile } = useDevice();
@@ -110,7 +111,7 @@ export default function AppShell({ sidebar, children }: AppShellProps) {
>
<Menu size={18} strokeWidth={1.7} />
</button>
- <Link href="/" className="flex items-center gap-1.5">
+ <Link href={homeHref} className="flex items-center gap-1.5">
<Image
src="/logo.png"
alt="DeepTutor"
diff --git a/web/components/layout/FeaturePage.tsx b/web/components/layout/FeaturePage.tsx
index 3ac5cb1e1..a4c973576 100644
--- a/web/components/layout/FeaturePage.tsx
+++ b/web/components/layout/FeaturePage.tsx
@@ -3,7 +3,7 @@ import type { ComponentPropsWithRef, ReactNode, Ref, UIEventHandler } from 'reac
/** Feature page standard, based on Personalized Learning:
* - Centered 1180px outer box; horizontal gutters 24px, 36px from 768px.
* - Vertical padding 28px, 36px from 1024px; 24px from header to content.
- * - Serif page title 27px / 30px at 640px of usable content; no title icon.
+ * - Sans page title 27px / 30px at 640px of usable content; no title icon.
* - Sans description 12.5px, section label 13.5px; one h1 per page.
* - Actions stack below the title under 640px of content and wrap in order.
* - Grids share 520 / 800 / 1040px container breakpoints and a 12px gap.
@@ -51,7 +51,7 @@ export function FeaturePage({
)
}
-export const PAGE_TITLE_CLASS = 'dt-page-title min-w-0 break-words font-serif font-semibold leading-normal tracking-[-0.02em] text-[var(--foreground)]'
+export const PAGE_TITLE_CLASS = 'dt-page-title min-w-0 break-words font-sans font-semibold leading-normal tracking-[-0.02em] text-[var(--foreground)]'
export const PAGE_DESCRIPTION_CLASS = 'mt-1.5 max-w-2xl text-[12.5px] leading-relaxed text-[var(--muted-foreground)]'
export const PAGE_SECTION_TITLE_CLASS = 'text-[13.5px] font-semibold text-[var(--foreground)]'
diff --git a/web/components/learning/LearningCreateMenu.tsx b/web/components/learning/LearningCreateMenu.tsx
new file mode 100644
index 000000000..034d3a97a
--- /dev/null
+++ b/web/components/learning/LearningCreateMenu.tsx
@@ -0,0 +1,104 @@
+'use client'
+import { useState } from 'react'
+import { useRouter } from 'next/navigation'
+import { Plus } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import Tooltip from '@/shared/ui/Tooltip'
+import { Dialog } from '@/shared/ui/Dialog'
+import { LEARNING_SURFACES } from './surfaces'
+import { useChatWorkspaces } from '@/hooks/useChatWorkspaces'
+import { useAuthStatus } from '@/hooks/useAuthStatus'
+import { activeWorkspaceId, navigateTask, scopedUrl } from '@/lib/workspace-scope'
+import { pageActionClass } from '@/components/layout/FeaturePage'
+import { useSidebarDrawer } from '@/components/layout/AppShell'
+
+export function LearningCreateMenu({ compact = false }: { compact?: boolean }) {
+ const { t } = useTranslation()
+ const router = useRouter()
+ const drawer = useSidebarDrawer()
+ const [open, setOpen] = useState(false)
+ const [destination, setDestination] = useState(activeWorkspaceId)
+ const { workspaces, error } = useChatWorkspaces()
+ const { learningPolicy } = useAuthStatus()
+ const surfaces = LEARNING_SURFACES.filter(
+ item =>
+ !learningPolicy ||
+ learningPolicy.allowedSurfaces.includes(
+ item.kind === 'mastery' || item.kind === 'practice' ? 'chat' : item.kind
+ )
+ )
+ return (
+ <>
+ <Tooltip label={t('navigation.createLearning')} suppressed={open}>
+ <button
+ type="button"
+ aria-label={t('navigation.createLearning')}
+ onClick={() => {
+ setDestination(activeWorkspaceId())
+ setOpen(true)
+ }}
+ className={compact ? 'dt-nav-icon' : pageActionClass()}
+ >
+ <Plus size={compact ? 17 : 15} />
+ {!compact && t('navigation.createLearning')}
+ </button>
+ </Tooltip>
+ <Dialog
+ open={open}
+ onClose={() => setOpen(false)}
+ title={t('navigation.createLearning')}
+ description={t('navigation.createLearningDescription')}
+ closeLabel={t('Close')}
+ >
+ <div className="mb-5">
+ <label
+ className="text-xs text-muted-foreground"
+ htmlFor={compact ? 'sidebar-create-workspace' : 'page-create-workspace'}
+ >
+ {t('Save to workspace')}
+ </label>
+ <select
+ id={compact ? 'sidebar-create-workspace' : 'page-create-workspace'}
+ value={destination}
+ onChange={event => setDestination(event.target.value)}
+ className="mt-2 h-10 w-full rounded-lg border border-border bg-background px-3 text-sm"
+ >
+ <option value="">{t('Default workspace')}</option>
+ {workspaces
+ .filter(row => !row.archived && row.status === 'ready')
+ .map(row => (
+ <option key={row.workspace_id} value={row.workspace_id}>
+ {row.display_name}
+ </option>
+ ))}
+ </select>
+ {error && (
+ <p role="alert" className="mt-2 text-xs text-destructive">
+ {error}
+ </p>
+ )}
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ {surfaces.map(item => (
+ <button
+ key={item.kind}
+ type="button"
+ className="rounded-xl border border-border p-4 text-left transition-colors hover:bg-muted/60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"
+ onClick={() => {
+ setOpen(false)
+ drawer?.close()
+ navigateTask(scopedUrl(`${item.href}?create=1`, destination), router.push)
+ }}
+ >
+ <item.icon size={22} strokeWidth={1.6} className="mb-3 text-muted-foreground" />
+ <span className="block text-sm font-medium">{t(item.title)}</span>
+ <span className="mt-1 block text-xs leading-relaxed text-muted-foreground">
+ {t(item.description)}
+ </span>
+ </button>
+ ))}
+ </div>
+ </Dialog>
+ </>
+ )
+}
diff --git a/web/components/learning/LearningDashboard.tsx b/web/components/learning/LearningDashboard.tsx
index a67ce67aa..e14bad2fa 100644
--- a/web/components/learning/LearningDashboard.tsx
+++ b/web/components/learning/LearningDashboard.tsx
@@ -1,10 +1,12 @@
'use client'
import { pageGridClass } from '@/components/layout/FeaturePage'
-import { useEffect, useState } from 'react'
+import Link from 'next/link'
+import { useState } from 'react'
import { BookOpen, Route } from 'lucide-react'
import { useTranslation } from 'react-i18next'
-import { apiFetch, apiUrl } from '@/lib/api'
+import { useLearningIndex } from '@/hooks/useLearningIndex'
+import { LearningCreateMenu } from './LearningCreateMenu'
import { scopedUrl } from '@/lib/workspace-scope'
import { bookRoute } from '@/lib/learning-routes'
import {
@@ -15,9 +17,8 @@ import {
import { setPendingPrompt } from '@/lib/pending-prompt'
import {
learningTodos,
- recentLearningActivity,
+ allLearningActivity,
type LearningKind,
- type LearningSources,
} from '@/lib/learning-dashboard'
import {
LearningShell,
@@ -31,76 +32,37 @@ import { LEARNING_SURFACES, learningSurface } from './surfaces'
export function LearningDashboard() {
const { t } = useTranslation()
- const [sources, setSources] = useState<LearningSources>({
- books: [],
- mastery: [],
- reading: [],
- watching: [],
- })
- const [failed, setFailed] = useState<LearningKind[]>([])
- const [loading, setLoading] = useState(true)
- const [reload, setReload] = useState(0)
-
- useEffect(() => {
- let alive = true
- let busy = false
- const refresh = async () => {
- if (busy || document.visibilityState === 'hidden') return
- busy = true
- let failures: LearningKind[] = []
- let result: LearningSources = { books: [], mastery: [], reading: [], watching: [] }
- try {
- const response = await apiFetch(apiUrl(scopedUrl('/api/dashboard/learning-index', '')), { signal: AbortSignal.timeout(20000) })
- if (!response.ok) throw new Error('Learning index unavailable')
- const payload = await response.json() as { sources: LearningSources; failed: LearningKind[] }
- result = payload.sources
- failures = payload.failed
- } catch { failures = ['books', 'mastery', 'reading', 'watching'] }
- const { books, mastery, reading, watching } = result
- if (alive) {
- // Preserve previously loaded content if a refresh fails.
- setSources(previous => ({
- books: failures.includes('books') && !books.length ? previous.books : books,
- mastery: failures.includes('mastery') && !mastery.length ? previous.mastery : mastery,
- reading: failures.includes('reading') && !reading.length ? previous.reading : reading,
- watching: failures.includes('watching') && !watching.length ? previous.watching : watching,
- }))
- setFailed(failures)
- setLoading(false)
- }
- busy = false
- }
- void refresh()
- window.addEventListener('focus', refresh)
- document.addEventListener('visibilitychange', refresh)
- const timer = window.setInterval(refresh, 30_000)
- return () => {
- alive = false
- window.clearInterval(timer)
- window.removeEventListener('focus', refresh)
- document.removeEventListener('visibilitychange', refresh)
- }
- }, [reload])
+ const { sources, failed, loading, retry } = useLearningIndex()
+ const [kind, setKind] = useState<LearningKind | 'all'>('all')
+ const [query, setQuery] = useState('')
+ const [limit, setLimit] = useState(24)
+ const selectedSurface = LEARNING_SURFACES.find(surface => surface.kind === kind)
const todos = learningTodos(sources)
- const recent = recentLearningActivity(sources)
+ const all = allLearningActivity(sources)
+ const recent = all.filter(item => (kind === 'all' || item.kind === kind || (kind === 'reading' && item.kind === 'watching')) && item.title.toLocaleLowerCase().includes(query.toLocaleLowerCase()))
return (
<LearningShell
back={false}
- title={t('Personalized Learning')}
- subtitle={t('One tutor, your own way to learn.')}
+ title={t('navigation.learning')}
+ subtitle={t('navigation.learningDescription')}
+ action={<LearningCreateMenu />}
>
- {/* The ways in lead the page: everything below them assumes you already
- chose one. Each opens its own introduction before it commits you. */}
- <LearningWays />
+ <div className="mb-6 flex flex-wrap items-center gap-2">
+ <div className="flex flex-wrap gap-1" role="group" aria-label={t('navigation.learningFilter')}>
+ {[{ kind: 'all', title: 'navigation.allLearning' }, ...LEARNING_SURFACES].map(surface => <button key={surface.kind} type="button" aria-pressed={kind === surface.kind} onClick={() => { setKind(surface.kind as LearningKind | 'all'); setLimit(24) }} className={`rounded-full px-3 py-1.5 text-xs transition-colors ${kind === surface.kind ? 'bg-muted text-foreground' : 'text-muted-foreground hover:bg-muted/60'}`}>{t(surface.title)}</button>)}
+ </div>
+ <input aria-label={t('navigation.searchLearning')} placeholder={t('navigation.searchLearning')} value={query} onChange={event => { setQuery(event.target.value); setLimit(24) }} className="ml-auto h-9 rounded-lg border border-border bg-transparent px-3 text-xs outline-none focus:border-ring" />
+ </div>
+ {selectedSurface && <Link href={scopedUrl(selectedSurface.href)} prefetch={false} className="mb-5 inline-flex items-center gap-2 text-sm text-muted-foreground transition-colors hover:text-foreground">{t('Open')} {t(selectedSurface.title)} <span aria-hidden>↗</span></Link>}
{failed.length > 0 && (
<LearningErrorState
message={t('Some learning activity could not be loaded: {{sources}}.', {
- sources: LEARNING_SURFACES.filter(surface => surface.kind !== "practice" && failed.includes(surface.kind))
+ sources: LEARNING_SURFACES.filter(surface => failed.includes(surface.kind))
.map(surface => t(surface.title))
.join(t('source list separator')),
})}
- onRetry={() => setReload(value => value + 1)}
+ onRetry={retry}
/>
)}
{loading ? (
@@ -157,10 +119,10 @@ export function LearningDashboard() {
{recent.length > 0 && (
<section aria-labelledby="learning-recent">
<h2 id="learning-recent" className="mb-3 text-[13.5px] font-semibold">
- {t('Recent activity')}
+ {t('navigation.learningRecords')}
</h2>
<div className={pageGridClass(2)}>
- {recent.map(item => {
+ {recent.slice(0, limit).map(item => {
const surface = learningSurface(item.kind)
return (
<LearningCard
@@ -177,9 +139,11 @@ export function LearningDashboard() {
</div>
</section>
)}
+ {recent.length > limit && <button className="mt-5 rounded-lg border border-border px-4 py-2 text-sm" onClick={() => setLimit(value => value + 24)}>{t('Show more')}</button>}
+ {!all.length && failed.length === 0 && <LearningWays />}
{!recent.length && failed.length === 0 && (
<LearningEmptyState
- title={t('Your next learning journey starts here')}
+ title={t(all.length ? 'navigation.noResults' : 'Your next learning journey starts here')}
description={t('Choose a book, a topic, a collection or a video to begin.')}
/>
)}
diff --git a/web/components/sidebar/CategoryNavigation.tsx b/web/components/sidebar/CategoryNavigation.tsx
new file mode 100644
index 000000000..9e65fb117
--- /dev/null
+++ b/web/components/sidebar/CategoryNavigation.tsx
@@ -0,0 +1,225 @@
+'use client'
+
+import { useId, useState, type ReactNode } from 'react'
+import dynamic from 'next/dynamic'
+import { usePathname, useRouter } from 'next/navigation'
+import { m, useReducedMotion } from 'framer-motion'
+import {
+ BookOpen,
+ Home,
+ Library,
+ MessageCircle,
+ Search,
+ Settings,
+ Columns3,
+ PenLine,
+ Bot,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import Tooltip from '@/shared/ui/Tooltip'
+import { categoryForPath, type NavigationCategory } from '@/lib/navigation'
+import { navVisibleUnderPolicy } from './nav-entries'
+import { useAuthStatus } from '@/hooks/useAuthStatus'
+import { navigateTask } from '@/lib/workspace-scope'
+import { NavigationRow, Section, matches } from './NavigationPrimitives'
+
+// Feature libraries load when their category opens, not in every workspace.
+const LearningNavigation = dynamic(() =>
+ import('./LearningNavigation').then(module => module.LearningNavigation)
+)
+const PartnerNavigation = dynamic(() =>
+ import('./PartnerNavigation').then(module => module.PartnerNavigation)
+)
+const ResourcesNavigation = dynamic(() =>
+ import('./ResourcesNavigation').then(module => module.ResourcesNavigation)
+)
+
+export const CATEGORIES = [
+ { id: 'home', label: 'navigation.home', icon: Home, href: '/chat' },
+ { id: 'partners', label: 'navigation.partners', icon: MessageCircle, href: '/partners' },
+ { id: 'learning', label: 'navigation.learning', icon: BookOpen, href: '/learning' },
+ { id: 'resources', label: 'navigation.resources', icon: Library, href: '/space' },
+] as const
+
+export function useCategoryNavigation() {
+ const pathname = usePathname()
+ const { learningPolicy } = useAuthStatus()
+ const categories = CATEGORIES.filter(item =>
+ navVisibleUnderPolicy(item.href, learningPolicy?.allowedSurfaces ?? null)
+ )
+ const [selection, setSelection] = useState<{
+ pathname: string
+ category: NavigationCategory
+ } | null>(null)
+ const [query, setQuery] = useState('')
+ const [searchOpen, setSearchOpen] = useState(false)
+ const desired = selection?.pathname === pathname ? selection.category : categoryForPath(pathname)
+ const category = categories.find(item => item.id === desired)?.id ?? categories[0]?.id ?? 'home'
+ return {
+ category,
+ categories,
+ query,
+ setQuery,
+ searchOpen,
+ setSearchOpen,
+ select: (next: NavigationCategory) => {
+ setSelection({ pathname, category: next })
+ setQuery('')
+ },
+ allowedSurfaces: learningPolicy?.allowedSurfaces ?? null,
+ }
+}
+type Navigation = ReturnType<typeof useCategoryNavigation>
+
+export function CategoryTabs({ nav, collapsed }: { nav: Navigation; collapsed: boolean }) {
+ const { t } = useTranslation()
+ const router = useRouter()
+ const id = useId()
+ const reduced = useReducedMotion()
+ const select = (category: (typeof CATEGORIES)[number]) => {
+ nav.select(category.id)
+ if (collapsed) navigateTask(category.href, router.push)
+ }
+ return (
+ <div className={`dt-category-bar ${collapsed ? 'is-collapsed' : ''}`}>
+ <div
+ role="tablist"
+ aria-label={t('navigation.categories')}
+ aria-orientation={collapsed ? 'vertical' : 'horizontal'}
+ >
+ {nav.categories.map((item, index) => (
+ <Tooltip key={item.id} label={t(item.label)} side={collapsed ? 'right' : 'bottom'}>
+ <button
+ id={`category-${item.id}`}
+ type="button"
+ role="tab"
+ aria-controls="category-content"
+ aria-label={t(item.label)}
+ aria-selected={nav.category === item.id}
+ tabIndex={nav.category === item.id ? 0 : -1}
+ onKeyDown={event => {
+ const delta = ['ArrowRight', 'ArrowDown'].includes(event.key)
+ ? 1
+ : ['ArrowLeft', 'ArrowUp'].includes(event.key)
+ ? -1
+ : 0
+ if (!delta && !['Home', 'End'].includes(event.key)) return
+ event.preventDefault()
+ const next =
+ event.key === 'Home'
+ ? 0
+ : event.key === 'End'
+ ? nav.categories.length - 1
+ : (index + delta + nav.categories.length) % nav.categories.length
+ select(nav.categories[next])
+ event.currentTarget
+ .closest('[role="tablist"]')
+ ?.querySelectorAll<HTMLButtonElement>('[role="tab"]')
+ [next]?.focus()
+ }}
+ onClick={() => select(item)}
+ className={nav.category === item.id ? 'is-active' : ''}
+ >
+ {nav.category === item.id && (
+ <m.span
+ layoutId={`category-pill-${id}`}
+ className="dt-category-pill"
+ transition={{ duration: reduced ? 0 : 0.22, ease: [0.22, 1, 0.36, 1] }}
+ />
+ )}
+ <item.icon size={20} strokeWidth={1.65} />
+ <span>{t(item.label)}</span>
+ </button>
+ </Tooltip>
+ ))}
+ </div>
+ <Tooltip label={t('navigation.search')} side={collapsed ? 'right' : 'bottom'}>
+ <button
+ type="button"
+ className="dt-nav-icon"
+ aria-label={t('navigation.search')}
+ aria-expanded={nav.searchOpen}
+ onClick={() => {
+ if (collapsed) navigateTask('/space/chat-history', router.push)
+ else nav.setSearchOpen(!nav.searchOpen)
+ }}
+ >
+ <Search size={19} strokeWidth={1.65} />
+ </button>
+ </Tooltip>
+ {!collapsed && nav.searchOpen && (
+ <input
+ autoFocus
+ aria-label={t('navigation.search')}
+ placeholder={t('navigation.search')}
+ value={nav.query}
+ onChange={event => nav.setQuery(event.target.value)}
+ onKeyDown={event => {
+ if (event.key === 'Escape') {
+ nav.setQuery('')
+ nav.setSearchOpen(false)
+ }
+ }}
+ className="dt-nav-search"
+ />
+ )}
+ </div>
+ )
+}
+
+export function CategoryBody({
+ nav,
+ collapsed,
+ sessions,
+}: {
+ nav: Navigation
+ collapsed: boolean
+ sessions: ReactNode
+}) {
+ const { t } = useTranslation()
+ if (collapsed) return null
+ return (
+ <div
+ id="category-content"
+ role="tabpanel"
+ aria-labelledby={`category-${nav.category}`}
+ className="dt-category-content"
+ key={nav.category}
+ >
+ {nav.category === 'home' && (
+ <>
+ <Section title={t('navigation.workspace')}>
+ {[
+ { href: '/chat', label: 'Dito', icon: MessageCircle },
+ { href: '/kanban', label: 'Task Board', icon: Columns3 },
+ { href: '/co-writer', label: 'Co-Writer', icon: PenLine },
+ { href: '/agents', label: 'My Agents', icon: Bot },
+ ]
+ .filter(
+ item =>
+ navVisibleUnderPolicy(item.href, nav.allowedSurfaces) &&
+ matches(t(item.label), nav.query)
+ )
+ .map(item => (
+ <NavigationRow
+ key={item.href}
+ href={item.href}
+ label={t(item.label)}
+ icon={item.icon}
+ />
+ ))}
+ </Section>
+ {sessions}
+ </>
+ )}
+ {nav.category === 'learning' && <LearningNavigation query={nav.query} sessions={sessions} />}
+ {nav.category === 'partners' && <PartnerNavigation query={nav.query} />}
+ {nav.category === 'resources' && <ResourcesNavigation query={nav.query} />}
+ {nav.searchOpen && matches(t('Settings'), nav.query) && (
+ <Section title={t('Settings')}>
+ <NavigationRow href="/settings" label={t('Settings')} icon={Settings} />
+ </Section>
+ )}
+ </div>
+ )
+}
diff --git a/web/components/sidebar/LearningNavigation.tsx b/web/components/sidebar/LearningNavigation.tsx
new file mode 100644
index 000000000..6cda6ad60
--- /dev/null
+++ b/web/components/sidebar/LearningNavigation.tsx
@@ -0,0 +1,52 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { NavigationRow, Section, Status, matches } from './NavigationPrimitives'
+import { useState, type ReactNode } from 'react'
+import { LayoutGrid, ChevronDown } from 'lucide-react'
+import { LearningCreateMenu } from '@/components/learning/LearningCreateMenu'
+import { learningSurface } from '@/components/learning/surfaces'
+import { allLearningActivity } from '@/lib/learning-dashboard'
+import { useLearningIndex } from '@/hooks/useLearningIndex'
+
+export function LearningNavigation({ query, sessions }: { query: string; sessions: ReactNode }) {
+ const { t } = useTranslation()
+ const { sources, loading, failed, retry } = useLearningIndex()
+ const [limit, setLimit] = useState(30)
+ const rows = allLearningActivity(sources).filter(row =>
+ matches(`${row.title} ${row.workspaceName ?? ''}`, query)
+ )
+ return (
+ <>
+ <Section title={t('navigation.learning')} action={<LearningCreateMenu compact />}>
+ <NavigationRow href="/learning" label={t('navigation.allLearning')} icon={LayoutGrid} />
+ </Section>
+ <Section title={t('navigation.learningRecords')}>
+ <Status loading={loading} error={failed.length > 0} retry={retry} />
+ {rows.slice(0, limit).map(row => (
+ <NavigationRow
+ key={row.key}
+ href={row.href}
+ label={row.title}
+ detail={row.workspaceName}
+ icon={learningSurface(row.kind).icon}
+ />
+ ))}
+ {!loading && !rows.length && !failed.length && (
+ <p className="dt-navigation-empty">
+ {t(query ? 'navigation.noResults' : 'navigation.noLearning')}
+ </p>
+ )}
+ {rows.length > limit && (
+ <button
+ className="dt-navigation-row w-full"
+ onClick={() => setLimit(value => value + 30)}
+ >
+ <ChevronDown size={15} />
+ {t('Show more')}
+ </button>
+ )}
+ </Section>
+ {sessions}
+ </>
+ )
+}
diff --git a/web/components/sidebar/NavigationPrimitives.tsx b/web/components/sidebar/NavigationPrimitives.tsx
new file mode 100644
index 000000000..d28bd5a12
--- /dev/null
+++ b/web/components/sidebar/NavigationPrimitives.tsx
@@ -0,0 +1,102 @@
+'use client'
+import type { ReactNode } from 'react'
+import Link from 'next/link'
+import { usePathname, useSearchParams } from 'next/navigation'
+import type { LucideIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import Tooltip from '@/shared/ui/Tooltip'
+import { useSidebarDrawer } from '@/components/layout/AppShell'
+
+export function NavigationRow({
+ href,
+ label,
+ icon: Icon,
+ detail,
+ active,
+ children,
+}: {
+ href: string
+ label: string
+ icon?: LucideIcon
+ detail?: string
+ active?: boolean
+ children?: ReactNode
+}) {
+ const drawer = useSidebarDrawer()
+ const pathname = usePathname()
+ const search = useSearchParams()
+ const target = new URL(href, 'http://localhost')
+ const workspace = target.searchParams.get('dt_workspace') ?? target.searchParams.get('workspace')
+ const currentWorkspace = search.get('dt_workspace') ?? search.get('workspace') ?? ''
+ const selected =
+ active ??
+ ((pathname === target.pathname || pathname.startsWith(`${target.pathname}/`)) &&
+ (workspace === null || workspace === currentWorkspace))
+ return (
+ <Tooltip label={label} description={detail} as="div" side="right">
+ <Link
+ href={href}
+ prefetch={false}
+ onClick={event => {
+ if (!event.metaKey && !event.ctrlKey && !event.shiftKey) drawer?.close()
+ }}
+ aria-current={selected ? 'page' : undefined}
+ className={`dt-navigation-row ${selected ? 'is-active' : ''}`}
+ >
+ {children ?? (Icon && <Icon size={18} strokeWidth={1.6} />)}
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ {detail && (
+ <span className="max-w-[34%] truncate text-[11px] text-muted-foreground">{detail}</span>
+ )}
+ </Link>
+ </Tooltip>
+ )
+}
+export function Section({
+ title,
+ action,
+ children,
+}: {
+ title: string
+ action?: ReactNode
+ children: ReactNode
+}) {
+ return (
+ <section className="dt-navigation-section">
+ <div className="dt-navigation-heading">
+ <span>{title}</span>
+ {action}
+ </div>
+ {children}
+ </section>
+ )
+}
+export function Status({
+ loading,
+ error,
+ retry,
+}: {
+ loading: boolean
+ error: boolean
+ retry: () => void
+}) {
+ const { t } = useTranslation()
+ if (loading)
+ return (
+ <div aria-busy="true" className="space-y-3 px-3 py-4">
+ {[0, 1, 2].map(value => (
+ <div key={value} className="h-3 w-4/5 animate-pulse rounded bg-muted" />
+ ))}
+ </div>
+ )
+ return error ? (
+ <div className="px-3 py-2 text-xs text-muted-foreground" role="status">
+ {t('navigation.loadError')}{' '}
+ <button className="underline" onClick={retry}>
+ {t('Retry')}
+ </button>
+ </div>
+ ) : null
+}
+export const matches = (label: string, query: string) =>
+ label.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())
diff --git a/web/components/sidebar/PartnerNavigation.tsx b/web/components/sidebar/PartnerNavigation.tsx
new file mode 100644
index 000000000..1115c88d6
--- /dev/null
+++ b/web/components/sidebar/PartnerNavigation.tsx
@@ -0,0 +1,126 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { NavigationRow, Section, Status, matches } from './NavigationPrimitives'
+import { useState } from 'react'
+import Link from 'next/link'
+import { usePathname, useSearchParams } from 'next/navigation'
+import { Plus, ChevronDown, Users, MessageCircle } from 'lucide-react'
+import Tooltip from '@/shared/ui/Tooltip'
+import PartnerAvatar from '@/components/partners/PartnerAvatar'
+import { usePartnerNavigation } from '@/hooks/usePartnerNavigation'
+import { partnerSessionHref } from '@/lib/navigation'
+
+export function PartnerNavigation({ query }: { query: string }) {
+ const { t } = useTranslation()
+ const search = useSearchParams()
+ const pathname = usePathname()
+ const { data, loading, error, retry } = usePartnerNavigation(true)
+ const [limit, setLimit] = useState(30)
+ const sessions = data.sessions.filter(row => matches(`${row.title} ${row.owner_name}`, query))
+ return (
+ <>
+ <Section
+ title={t('navigation.partners')}
+ action={
+ <Link
+ prefetch={false}
+ href="/partners/new"
+ aria-label={t('New partner')}
+ className="dt-nav-icon"
+ >
+ <Plus size={16} />
+ </Link>
+ }
+ >
+ <div className="dt-partner-roster">
+ {data.partners
+ .filter(row => matches(row.name, query))
+ .map(partner => (
+ <Tooltip key={partner.partner_id} label={partner.name} side="right">
+ <Link
+ href={`/partners/${encodeURIComponent(partner.partner_id)}`}
+ prefetch={false}
+ className="dt-partner-roster-item"
+ >
+ <PartnerAvatar
+ name={partner.name}
+ emoji={partner.emoji}
+ image={partner.avatar}
+ color={partner.color}
+ size={42}
+ />
+ <span>{partner.name}</span>
+ </Link>
+ </Tooltip>
+ ))}
+ <Link prefetch={false} href="/partners/new" className="dt-partner-roster-item">
+ <span className="dt-partner-add">
+ <Plus size={22} strokeWidth={1.5} />
+ </span>
+ <span>{t('New partner')}</span>
+ </Link>
+ </div>
+ <NavigationRow href="/partners" label={t('navigation.allPartners')} icon={Users} />
+ </Section>
+ <Status loading={loading} error={error || data.unavailable.length > 0} retry={retry} />
+ <Section
+ title={t('Groups')}
+ action={
+ data.partners.length >= 2 ? (
+ <Link
+ prefetch={false}
+ className="dt-nav-icon"
+ href="/partners/groups/new"
+ aria-label={t('New group')}
+ >
+ <Plus size={16} />
+ </Link>
+ ) : null
+ }
+ >
+ {data.groups
+ .filter(row => matches(row.name, query))
+ .map(group => (
+ <NavigationRow
+ key={group.group_id}
+ href={`/partners/groups/${encodeURIComponent(group.group_id)}`}
+ label={group.name}
+ icon={Users}
+ />
+ ))}
+ {!loading && !data.groups.length && (
+ <p className="dt-navigation-empty">{t('navigation.noGroups')}</p>
+ )}
+ </Section>
+ <Section title={t('navigation.partnerSessions')}>
+ {sessions.slice(0, limit).map(row => {
+ const href = partnerSessionHref(row)
+ return (
+ <NavigationRow
+ key={`${row.kind}:${row.owner_id}:${row.session_key}`}
+ href={href}
+ label={row.title || t('New conversation')}
+ detail={row.owner_name}
+ icon={MessageCircle}
+ active={pathname === href.split('?')[0] && search.get('session') === row.session_key}
+ />
+ )
+ })}
+ {!loading && !sessions.length && !error && (
+ <p className="dt-navigation-empty">
+ {t(query ? 'navigation.noResults' : 'navigation.noSessions')}
+ </p>
+ )}
+ {sessions.length > limit && (
+ <button
+ className="dt-navigation-row w-full"
+ onClick={() => setLimit(value => value + 30)}
+ >
+ <ChevronDown size={15} />
+ {t('Show more')}
+ </button>
+ )}
+ </Section>
+ </>
+ )
+}
diff --git a/web/components/sidebar/ResourcesNavigation.tsx b/web/components/sidebar/ResourcesNavigation.tsx
new file mode 100644
index 000000000..3a7492a9c
--- /dev/null
+++ b/web/components/sidebar/ResourcesNavigation.tsx
@@ -0,0 +1,35 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { NavigationRow, Section, matches } from './NavigationPrimitives'
+import { Library } from 'lucide-react'
+import { DASHBOARD_GROUPS, visibleGroups } from '@/components/space/SpaceDashboard'
+import { useCapabilityFilter } from '@/features/capabilities/useCapabilityCatalog'
+import { scopedUrl } from '@/lib/workspace-scope'
+
+export function ResourcesNavigation({ query }: { query: string }) {
+ const { t, i18n } = useTranslation()
+ const available = useCapabilityFilter()
+ const zh = i18n.language.startsWith('zh')
+ const groups = visibleGroups(DASHBOARD_GROUPS, available)
+ return (
+ <>
+ <Section title={t('navigation.resources')}>
+ <NavigationRow href="/space" label={t('navigation.allResources')} icon={Library} />
+ </Section>
+ {groups.map(group => (
+ <Section key={group.label.en} title={zh ? group.label.zh : group.label.en}>
+ {group.items
+ .filter(row => matches(zh ? row.title.zh : row.title.en, query))
+ .map(row => (
+ <NavigationRow
+ key={row.key}
+ href={scopedUrl(row.href)}
+ label={zh ? row.title.zh : row.title.en}
+ icon={row.icon}
+ />
+ ))}
+ </Section>
+ ))}
+ </>
+ )
+}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index e343cd52f..6cf2028b3 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -14,10 +14,10 @@ import {
type CSSProperties,
} from "react";
import { useAppShell } from "@/context/AppShellContext";
-import { PanelLeftClose, PanelLeftOpen } from "lucide-react";
+import { MessageCircle, PanelLeftClose, PanelLeftOpen } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useChatWorkspaces } from "@/hooks/useChatWorkspaces";
-import SessionList from "@/components/SessionList";
+
import { useSidebarDrawer } from "@/components/layout/AppShell";
import { useDevice } from "@/hooks/useDevice";
import { VersionBadge } from "@/components/sidebar/VersionBadge";
@@ -29,7 +29,8 @@ import type { MasteryTopicLabel } from "@/lib/learning-api";
import type { ReadingCollectionLabel } from "@/lib/reading-workspace-api";
import type { StudyCourse } from "@/lib/courses-api";
import { useSidebarResize } from "@/hooks/useSidebarResize";
-import { SidebarHome, SidebarNav } from "@/components/sidebar/SidebarNav";
+import { CategoryBody, CategoryTabs, useCategoryNavigation } from "@/components/sidebar/CategoryNavigation";
+import { isLearningSession } from "@/lib/navigation";
import { SECONDARY_NAV, isNavActive } from "@/components/sidebar/nav-entries";
import Tooltip from "@/shared/ui/Tooltip";
import {
@@ -38,6 +39,9 @@ import {
writeSessionOrder,
} from "@/lib/sidebar-layout";
+// The fallback history list is needed only by shells without organization.
+const SessionList = dynamic(() => import("@/components/SessionList"), { ssr: false });
+
// Session data arrives after mount; defer its organization UI with it so
// every workspace route does not download it as part of the initial shell.
const OrganizedSessionList = dynamic(
@@ -58,6 +62,13 @@ const OrganizedSessionList = dynamic(
);
interface SidebarShellProps {
+ /** Reuse the shell's resizing/collapse behavior with embedded navigation. */
+ homeSlot?: (collapsed: boolean) => ReactNode;
+ bodySlot?: (collapsed: boolean) => ReactNode;
+ footerOverride?: (collapsed: boolean) => ReactNode;
+ brandHref?: string;
+ initialWidth?: number;
+ widthStorageKey?: string;
sessions?: SessionSummary[];
activeSessionId?: string | null;
/** Conversations the caller is streaming right now; they sort to the top. */
@@ -89,6 +100,12 @@ interface SidebarShellProps {
}
export function SidebarShell({
+ homeSlot,
+ bodySlot,
+ footerOverride,
+ brandHref = "/",
+ initialWidth = 272,
+ widthStorageKey,
sessions = [],
activeSessionId = null,
liveSessionIds,
@@ -105,6 +122,7 @@ export function SidebarShell({
footerSlot,
}: SidebarShellProps) {
const pathname = usePathname();
+ const categoryNav = useCategoryNavigation();
const router = useRouter();
const { t } = useTranslation();
const { sidebarCollapsed, setSidebarCollapsed: setCollapsed } = useAppShell();
@@ -119,7 +137,7 @@ export function SidebarShell({
// already hidden when you don't want it, so it always opens fully expanded
// regardless of the persisted desktop preference.
const collapsed = sidebarCollapsed && !isMobile;
- const resize = useSidebarResize(collapsed || isMobile);
+ const resize = useSidebarResize(collapsed || isMobile, initialWidth, widthStorageKey);
/** Dismiss the drawer on nav clicks that actually navigate in-place. */
const closeDrawerOnNav = (event: React.MouseEvent) => {
@@ -178,17 +196,81 @@ export function SidebarShell({
// rendering and exposes older conversations through Show more.
const visibleSessions = sessions.filter(
(session) =>
- !session.preferences?.archived && !session.preferences?.parent_session_id,
+ !session.preferences?.archived && !session.preferences?.parent_session_id &&
+ (!bodySlot ? (categoryNav.category === "learning" ? isLearningSession(session) : !isLearningSession(session)) : true) &&
+ (!categoryNav.query || session.title.toLocaleLowerCase().includes(categoryNav.query.toLocaleLowerCase())),
);
+ const sessionContent = <>
+{/* Conversation history follows the module entries in the same scroller. */}
+ {showSessions &&
+ (categoryNav.category !== "learning" || loadingSessions || visibleSessions.length > 0) &&
+ onSelectSession &&
+ onRenameSession &&
+ onDeleteSession ? (
+ <section className="mt-3 px-2 pt-0.5">
+ {!onOrganizeSession && <div className="mb-2 px-2 text-xs text-[var(--muted-foreground)]">{t("Recent")}</div>}
+ {loadingSessions ? (
+ <SessionList
+ sessions={[]}
+ activeSessionId={activeSessionId}
+ loading
+ onSelect={onSelectSession}
+ onRename={onRenameSession}
+ onDelete={onDeleteSession}
+ compact
+ />
+ ) : onOrganizeSession ? (
+ <OrganizedSessionList
+ sessions={visibleSessions}
+ // Course grouping temporarily hidden pending further product
+ // work; passing [] keeps the list flat without touching the
+ // course data callers still fetch.
+ courses={[]}
+ workspaces={workspaces}
+ groupWorkspaces
+ onNewWorkspaceChat={onNewWorkspaceChat}
+ masteryTopics={masteryTopics}
+ readingCollections={readingCollections}
+ activeSessionId={activeSessionId}
+ liveSessionIds={liveSessionIds}
+ manualOrder={sessionOrder}
+ onReorder={handleReorderSessions}
+ onResetOrder={handleResetSessionOrder}
+ scrollRef={recentsScrollRef}
+ onSelect={(sessionId) => {
+ drawer?.close();
+ return onSelectSession(sessionId);
+ }}
+ onRename={onRenameSession}
+ onDelete={onDeleteSession}
+ onOrganize={onOrganizeSession}
+ />
+ ) : (
+ <SessionList
+ sessions={visibleSessions}
+ activeSessionId={activeSessionId}
+ onSelect={(sessionId) => {
+ drawer?.close();
+ return onSelectSession(sessionId);
+ }}
+ onRename={onRenameSession}
+ onDelete={onDeleteSession}
+ compact
+ />
+ )}
+ </section>
+ ) : null}
+</>;
+
/* ---- Collapsed state ---- */
if (collapsed) {
return (
- <aside className="group/sb relative flex h-dvh w-[60px] shrink-0 flex-col items-center bg-[var(--secondary)] py-3 transition-all duration-200">
+ <aside className={`${bodySlot ? "" : "dt-product-sidebar"} group/sb relative flex h-dvh w-[60px] shrink-0 flex-col items-center bg-[var(--secondary)] py-3 transition-all duration-200`}>
{/* Header: logo + collapse toggle (toggle replaces logo on hover) */}
<div className="relative mb-2 flex h-9 w-9 items-center justify-center">
<Link
- href="/"
+ href={brandHref}
prefetch={false}
aria-label="DeepTutor"
className="flex items-center justify-center transition-opacity duration-150 group-hover/sb:opacity-0"
@@ -210,17 +292,14 @@ export function SidebarShell({
</button>
</div>
- <SidebarHome collapsed onHomeClick={handleHomeClick} />
+ {homeSlot ? homeSlot(true) : <CategoryTabs nav={categoryNav} collapsed />}
<div className="min-h-0 w-full flex-1 overflow-y-auto overscroll-contain">
- <SidebarNav
- collapsed
- onHomeClick={handleHomeClick}
- onNavigate={closeDrawerOnNav}
- />
+ {bodySlot ? bodySlot(true) : <CategoryBody nav={categoryNav} collapsed sessions={null} />}
</div>
{/* Secondary nav + footer */}
- <div className="flex w-full shrink-0 flex-col items-center gap-1 px-1.5">
+ {footerOverride ? footerOverride(true) : <div className="flex w-full shrink-0 flex-col items-center gap-1 px-1.5">
+ <Tooltip label={t("navigation.newChat")} side="right"><Link prefetch={false} href="/chat" onClick={handleHomeClick} aria-label={t("navigation.newChat")} className="dt-nav-icon"><MessageCircle size={20} /></Link></Tooltip>
<div className="my-1 h-px w-7 bg-border/40" />
{SECONDARY_NAV.map((item) => {
const active = isNavActive(pathname, item.href);
@@ -243,7 +322,7 @@ export function SidebarShell({
})}
{renderedFooter}
<VersionBadge onNavigate={closeDrawerOnNav} />
- </div>
+ </div>}
</aside>
);
}
@@ -252,11 +331,11 @@ export function SidebarShell({
return (
<aside
style={{ "--sidebar-width": `${resize.width}px` } as CSSProperties}
- className="relative flex h-dvh w-[var(--sidebar-width)] max-w-[45vw] shrink-0 flex-col bg-[var(--secondary)] max-md:w-[220px] max-md:max-w-[85vw]"
+ className={`${bodySlot ? "" : "dt-product-sidebar"} relative flex h-dvh w-[var(--sidebar-width)] max-w-[45vw] shrink-0 flex-col bg-[var(--secondary)] max-md:w-[220px] max-md:max-w-[85vw]`}
>
{/* Header: logo + collapse toggle */}
<div className="flex h-[52px] shrink-0 items-center justify-between px-4">
- <Link href="/" prefetch={false} className="group flex items-center gap-1.5">
+ <Link href={brandHref} prefetch={false} className="group flex items-center gap-1.5">
<Image
src="/logo.png"
alt="DeepTutor"
@@ -284,82 +363,19 @@ export function SidebarShell({
</button>
</div>
- <SidebarHome onHomeClick={handleHomeClick} />
+ {homeSlot ? homeSlot(false) : <CategoryTabs nav={categoryNav} collapsed={false} />}
{/* Modules and conversations share one scroll region below Home. */}
<div
ref={recentsScrollRef}
className="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-2"
>
- <SidebarNav
- scrollRef={recentsScrollRef}
- collapsed={false}
- onHomeClick={handleHomeClick}
- onNavigate={closeDrawerOnNav}
- />
-
- {/* Conversation history follows the module entries in the same scroller. */}
- {showSessions &&
- onSelectSession &&
- onRenameSession &&
- onDeleteSession ? (
- <section className="mt-3 px-2 pt-0.5">
- {!onOrganizeSession && <div className="mb-2 px-2 text-xs text-[var(--muted-foreground)]">{t("Recent")}</div>}
- {loadingSessions ? (
- <SessionList
- sessions={[]}
- activeSessionId={activeSessionId}
- loading
- onSelect={onSelectSession}
- onRename={onRenameSession}
- onDelete={onDeleteSession}
- compact
- />
- ) : onOrganizeSession ? (
- <OrganizedSessionList
- sessions={visibleSessions}
- // Course grouping temporarily hidden pending further product
- // work; passing [] keeps the list flat without touching the
- // course data callers still fetch.
- courses={[]}
- workspaces={workspaces}
- groupWorkspaces
- onNewWorkspaceChat={onNewWorkspaceChat}
- masteryTopics={masteryTopics}
- readingCollections={readingCollections}
- activeSessionId={activeSessionId}
- liveSessionIds={liveSessionIds}
- manualOrder={sessionOrder}
- onReorder={handleReorderSessions}
- onResetOrder={handleResetSessionOrder}
- scrollRef={recentsScrollRef}
- onSelect={(sessionId) => {
- drawer?.close();
- return onSelectSession(sessionId);
- }}
- onRename={onRenameSession}
- onDelete={onDeleteSession}
- onOrganize={onOrganizeSession}
- />
- ) : (
- <SessionList
- sessions={visibleSessions}
- activeSessionId={activeSessionId}
- onSelect={(sessionId) => {
- drawer?.close();
- return onSelectSession(sessionId);
- }}
- onRename={onRenameSession}
- onDelete={onDeleteSession}
- compact
- />
- )}
- </section>
- ) : null}
+ {bodySlot ? bodySlot(false) : <CategoryBody nav={categoryNav} collapsed={false} sessions={sessionContent} />}
</div>
{/* Secondary nav + footer */}
- <div className="shrink-0 border-t border-border/40 px-2 py-2">
+ {footerOverride ? footerOverride(false) : <div className="shrink-0 px-2 py-2">
+ <Link prefetch={false} href="/chat" onClick={handleHomeClick} className="dt-new-conversation"><MessageCircle size={18} strokeWidth={1.6} /><span>{t("navigation.newChat")}</span></Link>
{renderedFooter}
<div className="flex items-center gap-1">
{SECONDARY_NAV.map((item) => {
@@ -383,7 +399,7 @@ export function SidebarShell({
})}
<VersionBadge onNavigate={closeDrawerOnNav} />
</div>
- </div>
+ </div>}
{!isMobile && (
<div
role="separator"
diff --git a/web/components/sidebar/UtilitySidebar.tsx b/web/components/sidebar/UtilitySidebar.tsx
index 0e25fe367..0928c0052 100644
--- a/web/components/sidebar/UtilitySidebar.tsx
+++ b/web/components/sidebar/UtilitySidebar.tsx
@@ -12,7 +12,7 @@ import { ProfileLink } from "@/components/auth/ProfileLink";
import { useAppShell } from "@/context/AppShellContext";
import {
deleteSession,
- listSessions,
+ listAllSessions,
updateSessionOrganization,
updateSessionTitle,
type SessionOrganizationPatch,
@@ -51,7 +51,7 @@ export default function UtilitySidebar() {
// Labels only name a heading, so losing them costs grouping, not the list.
const [nextSessions, nextCourses, nextTopics, nextCollections] =
await Promise.all([
- listSessions(50, 0, { force: true, allWorkspaces: true }),
+ listAllSessions({ force: true, allWorkspaces: true }),
listCourses({ force: true }).catch(() => [] as StudyCourse[]),
fetchMasteryTopicIndex().catch(() => [] as MasteryTopicLabel[]),
fetchReadingCollectionIndex().catch(() => [] as ReadingCollectionLabel[]),
diff --git a/web/components/space/SpaceDashboard.tsx b/web/components/space/SpaceDashboard.tsx
index 340323174..345807978 100644
--- a/web/components/space/SpaceDashboard.tsx
+++ b/web/components/space/SpaceDashboard.tsx
@@ -280,8 +280,16 @@ export function visibleGroups(
export { GROUPS as DASHBOARD_GROUPS };
-export default function SpaceDashboard() {
- const { i18n } = useTranslation();
+export default function SpaceDashboard({
+ title,
+ description,
+ onNavigate,
+}: {
+ title?: string;
+ description?: string;
+ onNavigate?: (href: string) => void;
+} = {}) {
+ const { t, i18n } = useTranslation();
const zh = i18n.language?.toLowerCase().startsWith("zh");
const tr = useCallback((l: Lang) => (zh ? l.zh : l.en), [zh]);
@@ -316,8 +324,8 @@ export default function SpaceDashboard() {
return (
<div>
<PageHeader
- title={tr({ zh: "学习空间", en: "Learning Space" })}
- description={tr({
+ title={title ?? t("navigation.resources")}
+ description={description ?? tr({
zh: "你的对话、智能体、笔记与题目,集中在一处 —— 从这里进入。",
en: "Your conversations, agents, notebooks, and questions in one place — enter from here.",
})}
@@ -335,6 +343,7 @@ export default function SpaceDashboard() {
key={item.key}
item={item}
count={counts[item.key]}
+ onNavigate={onNavigate}
tr={tr}
/>
))}
@@ -350,9 +359,11 @@ function DashboardCard({
item,
count,
tr,
+ onNavigate,
}: {
item: DashboardItem;
count: number | undefined;
+ onNavigate?: (href: string) => void;
tr: (l: Lang) => string;
}) {
const Icon = item.icon;
@@ -364,7 +375,11 @@ function DashboardCard({
return (
<Link
- href={item.key === "journal" ? scopedUrl(item.href) : item.href}
+ href={onNavigate ? `/preview#resource/${encodeURIComponent(item.href)}` : item.key === "journal" ? scopedUrl(item.href) : item.href}
+ onClick={onNavigate ? event => {
+ event.preventDefault();
+ onNavigate(item.href);
+ } : undefined}
className="group relative flex flex-col rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 transition-all duration-150 hover:-translate-y-0.5 hover:border-[var(--foreground)]/20 hover:shadow-[0_6px_20px_-12px_rgba(0,0,0,0.25)]"
>
<div className="flex items-start gap-3">
diff --git a/web/components/space/SpaceMain.tsx b/web/components/space/SpaceMain.tsx
index 0b26ddbdd..fab86d471 100644
--- a/web/components/space/SpaceMain.tsx
+++ b/web/components/space/SpaceMain.tsx
@@ -22,7 +22,7 @@ function BackToHub() {
strokeWidth={1.8}
className="transition-transform group-hover:-translate-x-0.5"
/>
- {t("Learning Space")}
+ {t("navigation.resources")}
</Link>
);
}
diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.ts
index 1c2d25e92..2862929af 100644
--- a/web/contracts/generated/api.ts
+++ b/web/contracts/generated/api.ts
@@ -5811,6 +5811,29 @@ export interface paths {
readonly patch?: never;
readonly trace?: never;
};
+ readonly "/api/partners/navigation": {
+ readonly parameters: {
+ readonly query?: never;
+ readonly header?: never;
+ readonly path?: never;
+ readonly cookie?: never;
+ };
+ /**
+ * Partner Navigation
+ * @description Read existing identities and actor-scoped sessions without moving data.
+ *
+ * Never enumerate the manager's global partner directories or shared channel
+ * history here. Visibility and transcript ownership match the detail APIs.
+ */
+ readonly get: operations["partner_navigation_api_partners_navigation_get"];
+ readonly put?: never;
+ readonly post?: never;
+ readonly delete?: never;
+ readonly options?: never;
+ readonly head?: never;
+ readonly patch?: never;
+ readonly trace?: never;
+ };
readonly "/api/partners/recent": {
readonly parameters: {
readonly query?: never;
@@ -14170,6 +14193,24 @@ export interface components {
/** Target Notebook Id */
readonly target_notebook_id: string;
};
+ /** NavigationSession */
+ readonly NavigationSession: {
+ /**
+ * Kind
+ * @enum {string}
+ */
+ readonly kind: "partner" | "group";
+ /** Owner Id */
+ readonly owner_id: string;
+ /** Owner Name */
+ readonly owner_name: string;
+ /** Session Key */
+ readonly session_key: string;
+ /** Title */
+ readonly title: string;
+ /** Updated At */
+ readonly updated_at: number;
+ };
/** NetworkSettingsUpdate */
readonly NetworkSettingsUpdate: {
/** Backend Port */
@@ -14515,6 +14556,21 @@ export interface components {
*/
readonly session_key: string;
};
+ /** PartnerNavigation */
+ readonly PartnerNavigation: {
+ /** Groups */
+ readonly groups: readonly {
+ readonly [key: string]: unknown;
+ }[];
+ /** Partners */
+ readonly partners: readonly {
+ readonly [key: string]: unknown;
+ }[];
+ /** Sessions */
+ readonly sessions: readonly components["schemas"]["NavigationSession"][];
+ /** Unavailable */
+ readonly unavailable: readonly string[];
+ };
/** PartnerSeatRetryRequest */
readonly PartnerSeatRetryRequest: {
/** Session Key */
@@ -17481,6 +17537,8 @@ export type SchemaMoveBlockRequest = components["schemas"]["MoveBlockRequest"];
export type SchemaMoveFilePayload = components["schemas"]["MoveFilePayload"];
export type SchemaMoveRecordRequest =
components["schemas"]["MoveRecordRequest"];
+export type SchemaNavigationSession =
+ components["schemas"]["NavigationSession"];
export type SchemaNetworkSettingsUpdate =
components["schemas"]["NetworkSettingsUpdate"];
export type SchemaNotebookCaptureRequest =
@@ -17507,6 +17565,8 @@ export type SchemaPartnerGroupMessageRequest =
components["schemas"]["PartnerGroupMessageRequest"];
export type SchemaPartnerInvocationActionRequest =
components["schemas"]["PartnerInvocationActionRequest"];
+export type SchemaPartnerNavigation =
+ components["schemas"]["PartnerNavigation"];
export type SchemaPartnerSeatRetryRequest =
components["schemas"]["PartnerSeatRetryRequest"];
export type SchemaPauseBookRequest = components["schemas"]["PauseBookRequest"];
@@ -30345,6 +30405,39 @@ export interface operations {
};
};
};
+ readonly partner_navigation_api_partners_navigation_get: {
+ readonly parameters: {
+ readonly query?: never;
+ readonly header?: {
+ readonly Authorization?: string | null;
+ };
+ readonly path?: never;
+ readonly cookie?: {
+ readonly dt_token?: string | null;
+ };
+ };
+ readonly requestBody?: never;
+ readonly responses: {
+ /** @description Successful Response */
+ readonly 200: {
+ headers: {
+ readonly [name: string]: unknown;
+ };
+ content: {
+ readonly "application/json": components["schemas"]["PartnerNavigation"];
+ };
+ };
+ /** @description Validation Error */
+ readonly 422: {
+ headers: {
+ readonly [name: string]: unknown;
+ };
+ content: {
+ readonly "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
readonly recent_partners_api_partners_recent_get: {
readonly parameters: {
readonly query?: {
diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.json
index e371c204d..386396d4b 100644
--- a/web/contracts/schema/openapi.json
+++ b/web/contracts/schema/openapi.json
@@ -6590,6 +6590,48 @@
"title": "MoveRecordRequest",
"type": "object"
},
+ "NavigationSession": {
+ "properties": {
+ "kind": {
+ "enum": [
+ "partner",
+ "group"
+ ],
+ "title": "Kind",
+ "type": "string"
+ },
+ "owner_id": {
+ "title": "Owner Id",
+ "type": "string"
+ },
+ "owner_name": {
+ "title": "Owner Name",
+ "type": "string"
+ },
+ "session_key": {
+ "title": "Session Key",
+ "type": "string"
+ },
+ "title": {
+ "title": "Title",
+ "type": "string"
+ },
+ "updated_at": {
+ "title": "Updated At",
+ "type": "number"
+ }
+ },
+ "required": [
+ "kind",
+ "owner_id",
+ "owner_name",
+ "session_key",
+ "title",
+ "updated_at"
+ ],
+ "title": "NavigationSession",
+ "type": "object"
+ },
"NetworkSettingsUpdate": {
"properties": {
"backend_port": {
@@ -7230,6 +7272,48 @@
"title": "PartnerInvocationActionRequest",
"type": "object"
},
+ "PartnerNavigation": {
+ "properties": {
+ "groups": {
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "title": "Groups",
+ "type": "array"
+ },
+ "partners": {
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "title": "Partners",
+ "type": "array"
+ },
+ "sessions": {
+ "items": {
+ "$ref": "#/components/schemas/NavigationSession"
+ },
+ "title": "Sessions",
+ "type": "array"
+ },
+ "unavailable": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Unavailable",
+ "type": "array"
+ }
+ },
+ "required": [
+ "partners",
+ "groups",
+ "sessions",
+ "unavailable"
+ ],
+ "title": "PartnerNavigation",
+ "type": "object"
+ },
"PartnerSeatRetryRequest": {
"properties": {
"session_key": {
@@ -36936,6 +37020,72 @@
]
}
},
+ "/api/partners/navigation": {
+ "get": {
+ "description": "Read existing identities and actor-scoped sessions without moving data.\n\nNever enumerate the manager's global partner directories or shared channel\nhistory here. Visibility and transcript ownership match the detail APIs.",
+ "operationId": "partner_navigation_api_partners_navigation_get",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "Authorization",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Authorization"
+ }
+ },
+ {
+ "in": "cookie",
+ "name": "dt_token",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Dt Token"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PartnerNavigation"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Partner Navigation",
+ "tags": [
+ "partners"
+ ]
+ }
+ },
"/api/partners/recent": {
"get": {
"operationId": "recent_partners_api_partners_recent_get",
diff --git a/web/features/capabilities/presentation.tsx b/web/features/capabilities/presentation.tsx
index 64f641ea3..5a8a4962e 100644
--- a/web/features/capabilities/presentation.tsx
+++ b/web/features/capabilities/presentation.tsx
@@ -68,7 +68,7 @@ export interface ChatCapabilityDef extends CapabilityDef {
export const CHAT_CAPABILITIES: ChatCapabilityDef[] = [
{
value: "",
- label: "Chat",
+ label: "Auto",
description: "Flexible conversation with any tool",
icon: MessageSquare,
allowedTools: [
diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsx
index 9cae05f61..4cc1c54e6 100644
--- a/web/features/chat/components/ChatWorkspace.tsx
+++ b/web/features/chat/components/ChatWorkspace.tsx
@@ -35,6 +35,7 @@ import { useTranslation } from "react-i18next";
import type { SelectedRecord } from "@/lib/notebook-selection-types";
import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";
import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";
+
import ChatComposer from "@/components/chat/home/ChatComposer";
import { ChatMessageList } from "@/features/chat/messages";
import { TurnNavigator } from "@/components/chat/home/TurnNavigator";
@@ -154,6 +155,8 @@ import {
} from "@/lib/selection-tutor";
import { shouldReturnToChatAfterResearch } from "@/lib/deep-research-report";
+const HomeShortcuts = dynamic(() => import("@/components/chat/home/HomeShortcuts").then(module => module.HomeShortcuts));
+
const NotebookRecordPicker = dynamic(
() => import("@/components/notebook/NotebookRecordPicker"),
{
@@ -2498,7 +2501,7 @@ export default function ChatWorkspace() {
</div>
) : !hasMessages ? (
<div className="flex w-full flex-1 min-h-0 items-end justify-center pb-14 animate-fade-in px-6">
- <div className="w-full max-w-[960px] flex items-center justify-center gap-4">
+ <div className="w-full max-w-[960px] flex flex-col items-center justify-center gap-4">
<img
src="/logo_black.png"
alt="DeepTutor"
@@ -2507,7 +2510,8 @@ export default function ChatWorkspace() {
className="h-10 w-10 select-none"
draggable={false}
/>
- <h1 className="font-serif text-[40px] font-medium leading-[1.1] tracking-[-0.015em] text-[var(--foreground)]">
+ <p className="text-sm font-medium text-muted-foreground">Dito</p>
+ <h1 className="font-sans text-[36px] font-medium leading-[1.1] tracking-[-0.015em] text-[var(--foreground)]">
{t(welcomeGreeting)}
</h1>
</div>
@@ -2788,6 +2792,7 @@ export default function ChatWorkspace() {
inputPlaceholder={askHint || undefined}
inputPlaceholderCompletion={askHint}
/>
+ {!hasMessages && !state.workspaceMode && <HomeShortcuts />}
{/* Starter chips sit between the composer and the spacer, so they
ride up with the composer on the empty screen and disappear the
moment the conversation has a first message. Clicking one sends
diff --git a/web/features/co-writer/components/CoWriterWorkspace.tsx b/web/features/co-writer/components/CoWriterWorkspace.tsx
index 706c45ede..9fdeb93f0 100644
--- a/web/features/co-writer/components/CoWriterWorkspace.tsx
+++ b/web/features/co-writer/components/CoWriterWorkspace.tsx
@@ -175,9 +175,11 @@ interface StreamEditResult {
export interface CoWriterWorkspaceProps {
docId: string;
+ /** Let embedded workspaces return to their own library. */
+ onBack?: () => void;
}
-export default function CoWriterWorkspace({ docId }: CoWriterWorkspaceProps) {
+export default function CoWriterWorkspace({ docId, onBack }: CoWriterWorkspaceProps) {
const { t } = useTranslation();
const router = useRouter();
const draftRevisionRef = useRef(0);
@@ -1677,7 +1679,7 @@ export default function CoWriterWorkspace({ docId }: CoWriterWorkspaceProps) {
</p>
<button
type="button"
- onClick={() => router.push("/co-writer")}
+ onClick={() => onBack ? onBack() : router.push("/co-writer")}
className="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)] transition-opacity hover:opacity-90"
>
<ChevronLeft size={14} />
@@ -1704,7 +1706,7 @@ export default function CoWriterWorkspace({ docId }: CoWriterWorkspaceProps) {
<Tooltip label={t("Back to documents")}>
<button
type="button"
- onClick={() => router.push("/co-writer")}
+ onClick={() => onBack ? onBack() : router.push("/co-writer")}
className="inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5 text-xs font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
aria-label={t("Back to documents")}
>
diff --git a/web/features/preview/CollectionSurfaces.tsx b/web/features/preview/CollectionSurfaces.tsx
new file mode 100644
index 000000000..4d062cfa9
--- /dev/null
+++ b/web/features/preview/CollectionSurfaces.tsx
@@ -0,0 +1,739 @@
+'use client'
+import { useState } from 'react'
+import {
+ ArrowLeft,
+ ArrowRight,
+ Check,
+ Plus,
+ Settings2,
+ Users,
+ MessageCircle,
+ Sparkles,
+} from 'lucide-react'
+import { FeaturePage, PageHeader, pageActionClass } from '@/components/layout/FeaturePage'
+import { LearningShell } from '@/components/learning/LearningShell'
+import { LearningCardContent } from '@/components/learning/LearningCard'
+import PartnerAvatar from '@/components/partners/PartnerAvatar'
+import { Dialog } from '@/shared/ui/Dialog'
+import MarkdownRenderer from '@/components/common/MarkdownRenderer'
+import { MasteryQuestionCard } from '@/components/chat/home/MasteryQuestionCard'
+import type { MasteryGradeResult } from '@/lib/mastery-question'
+import { DASHBOARD_GROUPS } from '@/components/space/SpaceDashboard'
+import {
+ learningKinds,
+ type Collections,
+ type LearningKind,
+ type LearningRecord,
+} from './collections'
+import { question } from './fixtures'
+import { readDemo, writeDemo } from './demo-transport'
+
+export function LearningOverview({
+ collections,
+ onOpen,
+ onCreate,
+}: {
+ collections: Collections
+ onOpen: (r: LearningRecord) => void
+ onCreate: () => void
+}) {
+ const [kind, setKind] = useState('all')
+ return (
+ <LearningShell
+ back={false}
+ title="学习"
+ subtitle="你的书籍、精通之路、练习和阅读,都在这里。"
+ action={
+ <button className={pageActionClass()} onClick={onCreate}>
+ <Plus size={15} />
+ 新建学习
+ </button>
+ }
+ tabs={
+ <div className="preview-filter-bar">
+ {[{ id: 'all', label: '全部' }, ...learningKinds].map(k => (
+ <button
+ key={k.id}
+ aria-pressed={kind === k.id}
+ className={kind === k.id ? 'is-active' : ''}
+ onClick={() => setKind(k.id)}
+ >
+ {k.label}
+ </button>
+ ))}
+ </div>
+ }
+ >
+ <div className="preview-learning-grid">
+ {collections.learning
+ .filter(r => kind === 'all' || r.kind === kind)
+ .map(r => {
+ const type = learningKinds.find(k => k.id === r.kind)!
+ return (
+ <button key={r.id} className="preview-learning-card" onClick={() => onOpen(r)}>
+ <div className="preview-card-meta">
+ <span>{type.label}</span>
+ <ArrowRight size={15} />
+ </div>
+ <LearningCardContent
+ title={r.title}
+ subtitle={r.detail}
+ icon={<type.icon size={23} strokeWidth={1.5} />}
+ />
+ </button>
+ )
+ })}
+ </div>
+ <button className="preview-new-learning-row" onClick={onCreate}>
+ <Plus size={20} />
+ <span>
+ 开始一段新的学习<strong>选择一种方式,留下你的学习记录</strong>
+ </span>
+ </button>
+ </LearningShell>
+ )
+}
+export function CreateLearningDialog({
+ open,
+ onClose,
+ onCreate,
+}: {
+ open: boolean
+ onClose: () => void
+ onCreate: (r: LearningRecord) => void
+}) {
+ const [kind, setKind] = useState<LearningKind>('book')
+ const [title, setTitle] = useState('')
+ const [goal, setGoal] = useState('')
+ return (
+ <Dialog
+ open={open}
+ onClose={onClose}
+ title="新建学习"
+ description="选一种适合你的方式,之后都可以从学习记录里继续。"
+ closeLabel="关闭"
+ size="lg"
+ >
+ <form
+ className="preview-create-form"
+ onSubmit={e => {
+ e.preventDefault()
+ if (!title.trim()) return
+ onCreate({
+ id: crypto.randomUUID(),
+ title: title.trim(),
+ kind,
+ detail: '刚刚创建 · 草稿',
+ notes: goal,
+ })
+ setTitle('')
+ setGoal('')
+ }}
+ >
+ <div className="preview-kind-picker">
+ {learningKinds.map(k => (
+ <button
+ type="button"
+ key={k.id}
+ aria-pressed={kind === k.id}
+ onClick={() => setKind(k.id)}
+ className={kind === k.id ? 'is-active' : ''}
+ >
+ <k.icon size={22} strokeWidth={1.5} />
+ <span>
+ {k.label}
+ <small>{k.description}</small>
+ </span>
+ {kind === k.id && <Check size={15} />}
+ </button>
+ ))}
+ </div>
+ <label>
+ 名称
+ <input
+ data-autofocus
+ required
+ maxLength={100}
+ value={title}
+ onChange={e => setTitle(e.target.value)}
+ placeholder="例如:从直觉理解概率论"
+ />
+ </label>
+ <label>
+ {kind === 'reading' ? '阅读材料或笔记' : '你想学会什么?'}
+ <textarea
+ value={goal}
+ onChange={e => setGoal(e.target.value)}
+ placeholder={
+ kind === 'reading'
+ ? '粘贴想阅读的内容,也可以稍后添加…'
+ : '写下你的目标,或留给之后慢慢补充…'
+ }
+ rows={3}
+ />
+ </label>
+ <div className="preview-form-footer">
+ <span>预览中创建本地草稿,保存在此浏览器。</span>
+ <button className={pageActionClass()} type="submit" disabled={!title.trim()}>
+ 创建{learningKinds.find(k => k.id === kind)?.label}
+ <ArrowRight size={14} />
+ </button>
+ </div>
+ </form>
+ </Dialog>
+ )
+}
+const bookChapters = [
+ {
+ title: '从不确定性开始',
+ text: '# 从不确定性开始\n\n概率是我们描述不确定性的一种语言。\n\n想象抛一枚均匀的硬币:下一次的结果未知,但我们可以描述长期重复后,正面大约会占一半。\n\n## 一个事件,一种可能\n\n样本空间包含所有可能的结果。事件则是其中的一部分。\n\n- 抛硬币:样本空间是正面与反面。\n- 掷骰子:样本空间包含 1 到 6。\n- 掷出偶数:事件包含 2、4、6。\n\n> 先把所有可能列清楚,再讨论其中哪些结果满足条件。',
+ },
+ {
+ title: '条件改变了什么',
+ text: '# 条件改变了什么\n\n已知骰子掷出的点数是偶数,它等于 6 的概率是多少?\n\n原来的六种可能,现在只剩下 2、4、6。我们把讨论的范围缩小到了已知条件之内。\n\n$$P(A\\mid B)=\\frac{P(A\\cap B)}{P(B)}$$\n\n条件概率关心的是:在 B 已经发生的世界里,A 出现的比例。',
+ },
+ {
+ title: '用新证据更新判断',
+ text: '# 用新证据更新判断\n\n贝叶斯公式让我们在看到新证据后更新判断。\n\n$$P(A\\mid B)=\\frac{P(B\\mid A)P(A)}{P(B)}$$\n\n先验表达看到证据之前的判断。似然表达假设成立时,看到当前证据有多自然。两者一起帮助我们形成新的判断。\n\n## 试着思考\n\n当一种疾病非常罕见时,为什么阳性的检测结果仍然需要进一步确认?',
+ },
+]
+export function LearningRecordSurface({
+ record,
+ onChange,
+ onBack,
+}: {
+ record: LearningRecord
+ onChange: (r: LearningRecord) => void
+ onBack: () => void
+}) {
+ const [chapter, setChapter] = useState(() => readDemo(`chapter-${record.id}`, 0))
+ const [grade, setGrade] = useState<MasteryGradeResult | null>(() =>
+ readDemo(`practice-${record.id}`, null)
+ )
+ const kind = learningKinds.find(k => k.id === record.kind)!
+ return (
+ <FeaturePage>
+ <button className="preview-back-link" onClick={onBack}>
+ <ArrowLeft size={14} />
+ 所有学习
+ </button>
+ <PageHeader
+ title={record.title}
+ description={`${kind.label} · ${record.sample ? '示例内容' : '草稿已保存在此浏览器'}`}
+ />
+ {record.sample && record.kind === 'book' ? (
+ <div className="preview-mastery-layout">
+ <nav className="preview-objectives" aria-label="书籍章节">
+ <div className="preview-nav-label">目录</div>
+ {bookChapters.map((c, i) => (
+ <button
+ key={c.title}
+ className={chapter === i ? 'is-active' : ''}
+ onClick={() => {
+ setChapter(i)
+ writeDemo(`chapter-${record.id}`, i)
+ }}
+ >
+ <span>{String(i + 1).padStart(2, '0')}</span>
+ {c.title}
+ </button>
+ ))}
+ </nav>
+ <article className="preview-lesson">
+ <MarkdownRenderer content={bookChapters[chapter].text} />
+ </article>
+ </div>
+ ) : record.sample && record.kind === 'practice' ? (
+ <div className="preview-record-practice">
+ <div className="preview-section-title">
+ <span>巩固练习</span>
+ <small>{grade ? '已完成 1 / 1' : '第 1 / 1 题'}</small>
+ </div>
+ <MasteryQuestionCard
+ question={question}
+ grade={grade}
+ answered={!!grade}
+ submittedAnswer={grade?.learnerAnswer || ''}
+ onSubmit={p => {
+ const answer = p.answers?.[0]?.text || p.text || ''
+ const result: MasteryGradeResult = {
+ questionId: question.questionId,
+ learnerAnswer: answer,
+ isCorrect: answer === 'B',
+ correctLabel: 'B',
+ correctBody: '(1, 0) 和 (0, 1)',
+ explanation: '两个向量线性无关,且能够张成二维空间。',
+ result: answer === 'B' ? 'correct' : 'incorrect',
+ }
+ setGrade(result)
+ writeDemo(`practice-${record.id}`, result)
+ return true
+ }}
+ />
+ {grade && (
+ <button
+ className={pageActionClass('secondary')}
+ onClick={() => {
+ setGrade(null)
+ writeDemo(`practice-${record.id}`, null)
+ }}
+ >
+ 再练一次
+ </button>
+ )}
+ </div>
+ ) : (
+ <div className="preview-record-draft">
+ <div className="preview-draft-status">
+ <kind.icon size={20} />
+ <div>
+ <strong>你的{kind.label}已创建</strong>
+ <p>可以先整理目标和材料。自动生成内容需要接入模型。</p>
+ </div>
+ </div>
+ <label className="preview-field">
+ 名称
+ <input
+ value={record.title}
+ onChange={e => onChange({ ...record, title: e.target.value })}
+ />
+ </label>
+ <label className="preview-field">
+ {record.kind === 'reading' ? '阅读材料' : '目标与笔记'}
+ <textarea
+ rows={10}
+ value={record.notes}
+ onChange={e => onChange({ ...record, notes: e.target.value })}
+ placeholder="在这里补充内容…"
+ />
+ </label>
+ {record.notes && (
+ <div className="preview-note-render">
+ <MarkdownRenderer content={record.notes} />
+ </div>
+ )}
+ <p className="preview-local-note">
+ <Check size={12} />
+ 修改自动保存在此浏览器
+ </p>
+ </div>
+ )}
+ </FeaturePage>
+ )
+}
+
+export type PartnerModal = 'partner' | 'group' | null
+export function PartnerSurface({
+ collections: c,
+ selected,
+ onSelect,
+ modal,
+ setModal,
+}: {
+ collections: Collections
+ selected: string
+ onSelect: (id: string) => void
+ modal: PartnerModal
+ setModal: (m: PartnerModal) => void
+}) {
+ const [name, setName] = useState('')
+ const [description, setDescription] = useState('')
+ const [members, setMembers] = useState<string[]>([])
+ const [editing, setEditing] = useState(false)
+ const [input, setInput] = useState('')
+ const session = c.sessions.find(s => s.id === selected)
+ const owner = session?.owner || selected
+ const partner = c.partners.find(p => p.id === owner)
+ const group = c.groups.find(g => g.id === owner)
+ const title = session?.title || partner?.name || group?.name || '伙伴'
+ function createSession() {
+ const id = crypto.randomUUID()
+ c.setSessions(s => [
+ { id, title: `与 ${partner?.name || group?.name} 的新会话`, owner, messages: [] },
+ ...s,
+ ])
+ onSelect(id)
+ }
+ function configure() {
+ setName(partner?.name || group?.name || '')
+ setDescription(partner?.description || '')
+ setMembers(group?.members || [])
+ setEditing(true)
+ setModal(partner ? 'partner' : 'group')
+ }
+ return (
+ <>
+ <FeaturePage>
+ <PageHeader
+ title={title}
+ description={
+ session
+ ? `${partner?.name || group?.name} · 会话记录`
+ : partner?.description ||
+ (group ? '让不同的伙伴,一起参与同一个问题。' : '选择一位伙伴,或让他们一起讨论。')
+ }
+ action={
+ selected ? (
+ <div className="flex gap-2">
+ <button className={pageActionClass('secondary')} onClick={() => onSelect('')}>
+ <ArrowLeft size={14} />
+ 所有伙伴
+ </button>
+ <button className={pageActionClass('secondary')} onClick={configure}>
+ <Settings2 size={14} />
+ 配置
+ </button>
+ {!session && (
+ <button className={pageActionClass()} onClick={createSession}>
+ <Plus size={14} />
+ 新会话
+ </button>
+ )}
+ </div>
+ ) : (
+ <button
+ className={pageActionClass()}
+ onClick={() => {
+ setEditing(false)
+ setName('')
+ setDescription('')
+ setModal('partner')
+ }}
+ >
+ <Plus size={14} />
+ 新建伙伴
+ </button>
+ )
+ }
+ />
+ {!selected ? (
+ <>
+ <div className="preview-section-title">
+ <h2>我的伙伴</h2>
+ <span>{c.partners.length} 位</span>
+ </div>
+ <div className="preview-partner-cards">
+ {c.partners.map(p => (
+ <button key={p.id} onClick={() => onSelect(p.id)}>
+ <PartnerAvatar name={p.name} color={p.color} size={50} />
+ <div>
+ <h3>{p.name}</h3>
+ <p>{p.description}</p>
+ <small>本地预览</small>
+ </div>
+ <ArrowRight size={16} />
+ </button>
+ ))}
+ </div>
+ <div className="preview-section-title mt-9">
+ <h2>群组</h2>
+ <button
+ onClick={() => {
+ setEditing(false)
+ setName('')
+ setModal('group')
+ }}
+ >
+ <Plus size={14} />
+ 新建群组
+ </button>
+ </div>
+ {c.groups.map(g => (
+ <button key={g.id} className="preview-group-row" onClick={() => onSelect(g.id)}>
+ <Users size={23} strokeWidth={1.5} />
+ <span>
+ <strong>{g.name}</strong>
+ <small>
+ {g.members.map(id => c.partners.find(p => p.id === id)?.name).join('、')}
+ </small>
+ </span>
+ <ArrowRight size={15} />
+ </button>
+ ))}
+ <div className="preview-section-title mt-9">
+ <h2>最近会话</h2>
+ </div>
+ {c.sessions.map(s => (
+ <button className="preview-session-row" key={s.id} onClick={() => onSelect(s.id)}>
+ <MessageIcon />
+ <span>{s.title}</span>
+ <small>
+ {c.partners.find(p => p.id === s.owner)?.name ||
+ c.groups.find(g => g.id === s.owner)?.name}
+ </small>
+ <ArrowRight size={14} />
+ </button>
+ ))}
+ </>
+ ) : session ? (
+ <div className="preview-partner-chat">
+ {session.messages.length ? (
+ session.messages.map((m, i) => (
+ <div key={i} className={`preview-partner-message ${m.role}`}>
+ <small>{m.role === 'user' ? '你' : partner?.name || group?.name}</small>
+ <MarkdownRenderer content={m.text} />
+ </div>
+ ))
+ ) : (
+ <div className="preview-partner-empty">
+ <Sparkles size={27} strokeWidth={1.4} />
+ <h2>从一个问题开始</h2>
+ <p>这段会话会保留在伙伴栏,随时可以继续。</p>
+ </div>
+ )}
+ <form
+ onSubmit={e => {
+ e.preventDefault()
+ if (!input.trim()) return
+ const text = input.trim()
+ c.setSessions(all =>
+ all.map(s =>
+ s.id !== session.id
+ ? s
+ : {
+ ...s,
+ title: s.messages.length ? s.title : text.slice(0, 30),
+ messages: [
+ ...s.messages,
+ { role: 'user', text },
+ {
+ role: 'assistant',
+ text: `已收到「${text}」。这是会话交互示例;接入模型后,${partner?.name || '群组成员'}会在这里继续回应。`,
+ },
+ ],
+ }
+ )
+ )
+ setInput('')
+ }}
+ >
+ <input
+ aria-label="发送给伙伴"
+ value={input}
+ onChange={e => setInput(e.target.value)}
+ placeholder={`与 ${partner?.name || group?.name} 聊聊…`}
+ />
+ <button disabled={!input.trim()} aria-label="发送" className={pageActionClass()}>
+ <ArrowRight size={17} />
+ </button>
+ </form>
+ <p className="preview-local-note">示例对话 · 未连接模型或外部渠道</p>
+ </div>
+ ) : (
+ <>
+ <div className="preview-partner-detail">
+ {partner ? (
+ <PartnerAvatar name={partner.name} color={partner.color} size={70} />
+ ) : (
+ <Users size={50} strokeWidth={1.2} />
+ )}
+ <h2>{partner?.name || group?.name}</h2>
+ <p>
+ {partner?.description ||
+ group?.members.map(id => c.partners.find(p => p.id === id)?.name).join(' · ')}
+ </p>
+ <button className={pageActionClass()} onClick={createSession}>
+ <Plus size={14} />
+ 开始新会话
+ </button>
+ </div>
+ <div className="preview-section-title">
+ <h2>会话记录</h2>
+ </div>
+ {c.sessions
+ .filter(s => s.owner === owner)
+ .map(s => (
+ <button className="preview-session-row" key={s.id} onClick={() => onSelect(s.id)}>
+ <MessageIcon />
+ <span>{s.title}</span>
+ <ArrowRight size={14} />
+ </button>
+ ))}
+ </>
+ )}
+ </FeaturePage>
+ <Dialog
+ open={!!modal}
+ onClose={() => {
+ setModal(null)
+ setEditing(false)
+ setName('')
+ setDescription('')
+ setMembers([])
+ }}
+ title={`${editing ? '配置' : '新建'}${modal === 'group' ? '群组' : '伙伴'}`}
+ closeLabel="关闭"
+ >
+ <form
+ className="preview-create-form"
+ onSubmit={e => {
+ e.preventDefault()
+ if (!name.trim()) return
+ const id = editing ? owner : crypto.randomUUID()
+ if (modal === 'partner') {
+ const p = { id, name: name.trim(), description, color: partner?.color || '#7a8d75' }
+ c.setPartners(all =>
+ editing ? all.map(old => (old.id === id ? p : old)) : [...all, p]
+ )
+ } else {
+ const g = { id, name: name.trim(), members }
+ c.setGroups(all =>
+ editing ? all.map(old => (old.id === id ? g : old)) : [...all, g]
+ )
+ }
+ setModal(null)
+ setEditing(false)
+ setName('')
+ setDescription('')
+ setMembers([])
+ onSelect(id)
+ }}
+ >
+ <label>
+ 名称
+ <input
+ required
+ maxLength={70}
+ value={name}
+ onChange={e => setName(e.target.value)}
+ data-autofocus
+ />
+ </label>
+ {modal === 'partner' ? (
+ <label>
+ 伙伴的角色
+ <textarea
+ rows={4}
+ value={description}
+ onChange={e => setDescription(e.target.value)}
+ placeholder="这位伙伴擅长什么,怎样与你交流?"
+ />
+ </label>
+ ) : (
+ <fieldset>
+ <legend>选择成员(至少 2 位)</legend>
+ {c.partners.map(p => (
+ <label className="preview-member-choice" key={p.id}>
+ <input
+ type="checkbox"
+ checked={members.includes(p.id)}
+ onChange={() =>
+ setMembers(all =>
+ all.includes(p.id) ? all.filter(id => id !== p.id) : [...all, p.id]
+ )
+ }
+ />
+ <PartnerAvatar name={p.name} color={p.color} size={24} />
+ {p.name}
+ </label>
+ ))}
+ </fieldset>
+ )}
+ <div className="preview-form-footer">
+ <span>配置保存在本地预览中</span>
+ <button
+ className={pageActionClass()}
+ disabled={!name.trim() || (modal === 'group' && members.length < 2)}
+ >
+ 保存
+ </button>
+ </div>
+ </form>
+ </Dialog>
+ </>
+ )
+}
+function MessageIcon() {
+ return <MessageCircle size={17} strokeWidth={1.5} />
+}
+
+export function ResourceSurface({ href, onBack }: { href: string; onBack: () => void }) {
+ const item = DASHBOARD_GROUPS.flatMap(g => g.items).find(i => i.href === href)!
+ const [rows, setRows] = useState<{ id: string; name: string; text: string }[]>(() =>
+ readDemo(`resources-${href}`, [])
+ )
+ const [adding, setAdding] = useState(false)
+ const [name, setName] = useState('')
+ const [text, setText] = useState('')
+ const [selected, setSelected] = useState<string | null>(null)
+ function save(next: typeof rows) {
+ setRows(next)
+ writeDemo(`resources-${href}`, next)
+ }
+ return (
+ <FeaturePage>
+ <button className="preview-back-link" onClick={onBack}>
+ <ArrowLeft size={14} />
+ 资料总览
+ </button>
+ <PageHeader
+ title={item.title.zh}
+ description={item.blurb.zh}
+ action={
+ <button className={pageActionClass('secondary')} onClick={() => setAdding(true)}>
+ <Plus size={14} />
+ 添加示例条目
+ </button>
+ }
+ />
+ {rows.length ? (
+ rows.map(r => (
+ <div className="preview-resource-entry" key={r.id}>
+ <button
+ className="preview-session-row"
+ onClick={() => setSelected(selected === r.id ? null : r.id)}
+ >
+ <item.icon size={18} />
+ <span>{r.name}</span>
+ <ArrowRight size={14} />
+ </button>
+ {selected === r.id && (
+ <div className="p-5">
+ <MarkdownRenderer content={r.text || '尚未添加说明。'} />
+ </div>
+ )}
+ </div>
+ ))
+ ) : (
+ <div className="preview-resource-empty">
+ <item.icon size={32} strokeWidth={1.2} />
+ <h2>{item.title.zh}</h2>
+ <p>{item.blurb.zh}</p>
+ <small>这里继承学习空间的资源分类。预览使用独立的本地示例,不读取你的实际资料。</small>
+ </div>
+ )}
+ <Dialog
+ open={adding}
+ title={`添加${item.title.zh}示例`}
+ closeLabel="关闭"
+ onClose={() => setAdding(false)}
+ >
+ <form
+ className="preview-create-form"
+ onSubmit={e => {
+ e.preventDefault()
+ const id = crypto.randomUUID()
+ save([...rows, { id, name: name.trim(), text }])
+ setSelected(id)
+ setAdding(false)
+ setName('')
+ setText('')
+ }}
+ >
+ <label>
+ 名称
+ <input required value={name} onChange={e => setName(e.target.value)} />
+ </label>
+ <label>
+ 说明
+ <textarea rows={4} value={text} onChange={e => setText(e.target.value)} />
+ </label>
+ <p className="preview-local-note">用于体验资源的组织方式,不创建真实服务或连接。</p>
+ <button className={pageActionClass()} disabled={!name.trim()}>
+ 添加
+ </button>
+ </form>
+ </Dialog>
+ </FeaturePage>
+ )
+}
diff --git a/web/features/preview/PreviewNavigation.tsx b/web/features/preview/PreviewNavigation.tsx
new file mode 100644
index 000000000..50bc47d2c
--- /dev/null
+++ b/web/features/preview/PreviewNavigation.tsx
@@ -0,0 +1,359 @@
+'use client'
+import { useId, type ReactNode } from 'react'
+import { m, useReducedMotion } from 'framer-motion'
+import {
+ Home,
+ MessageCircle,
+ BookOpen,
+ Library,
+ Search,
+ Plus,
+ LayoutGrid,
+ Columns3,
+ PenLine,
+ Bot,
+ ChevronRight,
+ Users,
+ type LucideIcon,
+} from 'lucide-react'
+import Tooltip from '@/shared/ui/Tooltip'
+import PartnerAvatar from '@/components/partners/PartnerAvatar'
+import { useSidebarDrawer } from '@/components/layout/AppShell'
+import { DASHBOARD_GROUPS } from '@/components/space/SpaceDashboard'
+import { learningKinds, type Category, type Collections, type LearningRecord } from './collections'
+import type { PreviewView } from './fixtures'
+
+const categories = [
+ { id: 'home', label: '主页', icon: Home },
+ { id: 'partners', label: '伙伴', icon: MessageCircle },
+ { id: 'learning', label: '学习', icon: BookOpen },
+ { id: 'library', label: '资料', icon: Library },
+] as const
+export function CategoryTabs({
+ category,
+ collapsed,
+ onChange,
+ onSearch,
+}: {
+ category: Category
+ collapsed: boolean
+ onChange: (c: Category) => void
+ onSearch: () => void
+}) {
+ const reduce = useReducedMotion()
+ const id = useId()
+ return (
+ <div className={`preview-category-bar ${collapsed ? 'is-collapsed' : ''}`}>
+ <div
+ role="tablist"
+ aria-label="主要栏目"
+ aria-orientation={collapsed ? 'vertical' : 'horizontal'}
+ >
+ {categories.map((item, index) => (
+ <Tooltip key={item.id} label={item.label} side="bottom">
+ <button
+ role="tab"
+ aria-label={item.label}
+ aria-selected={category === item.id}
+ aria-controls="preview-category-content"
+ tabIndex={category === item.id ? 0 : -1}
+ onKeyDown={event => {
+ const delta =
+ event.key === 'ArrowRight' || event.key === 'ArrowDown'
+ ? 1
+ : event.key === 'ArrowLeft' || event.key === 'ArrowUp'
+ ? -1
+ : 0
+ if (!delta && event.key !== 'Home' && event.key !== 'End') return
+ event.preventDefault()
+ const next =
+ event.key === 'Home' ? 0 : event.key === 'End' ? 3 : (index + delta + 4) % 4
+ onChange(categories[next].id)
+ const buttons = event.currentTarget
+ .closest('[role=tablist]')
+ ?.querySelectorAll<HTMLButtonElement>('[role=tab]')
+ buttons?.[next].focus()
+ }}
+ onClick={() => onChange(item.id)}
+ className={category === item.id ? 'is-active' : ''}
+ >
+ {category === item.id && (
+ <m.span
+ layoutId={`category-pill-${id}`}
+ className="preview-category-pill"
+ transition={{ duration: reduce ? 0 : 0.22, ease: [0.22, 1, 0.36, 1] }}
+ />
+ )}
+ <item.icon size={20} strokeWidth={1.65} />
+ <span
+ className="preview-category-name"
+ style={{
+ maxWidth: category === item.id && !collapsed ? 36 : 0,
+ opacity: category === item.id && !collapsed ? 1 : 0,
+ }}
+ >
+ {item.label}
+ </span>
+ </button>
+ </Tooltip>
+ ))}
+ </div>
+ <Tooltip label="搜索 · ⌘ K" side="bottom">
+ <button className="preview-category-search" aria-label="搜索" onClick={onSearch}>
+ <Search size={20} strokeWidth={1.65} />
+ </button>
+ </Tooltip>
+ </div>
+ )
+}
+export function SidebarRow({
+ icon: Icon,
+ label,
+ active,
+ onClick,
+ trailing,
+}: {
+ icon: LucideIcon
+ label: string
+ active?: boolean
+ onClick: () => void
+ trailing?: ReactNode
+}) {
+ const drawer = useSidebarDrawer()
+ return (
+ <button
+ className={`preview-nav-row ${active ? 'is-active' : ''}`}
+ aria-current={active ? 'page' : undefined}
+ onClick={() => {
+ onClick()
+ drawer?.close()
+ }}
+ >
+ <Icon size={18} strokeWidth={1.6} />
+ <span>{label}</span>
+ {trailing}
+ </button>
+ )
+}
+function SectionLabel({
+ label,
+ action,
+ onAction,
+}: {
+ label: string
+ action?: string
+ onAction?: () => void
+}) {
+ return (
+ <div className="preview-sidebar-section-label">
+ <span>{label}</span>
+ {onAction && (
+ <Tooltip label={action || '新建'}>
+ <button aria-label={action || '新建'} onClick={onAction}>
+ <Plus size={17} />
+ </button>
+ </Tooltip>
+ )}
+ </div>
+ )
+}
+export function CategoryBody({
+ category,
+ collapsed,
+ view,
+ collections,
+ activeRecord,
+ activePartner,
+ resourceHref,
+ onGo,
+ onRecord,
+ onCreate,
+ onPartner,
+ onNewPartner,
+ onNewGroup,
+ onResource,
+}: {
+ category: Category
+ collapsed: boolean
+ view: PreviewView
+ collections: Collections
+ activeRecord: string
+ activePartner: string
+ resourceHref: string
+ onGo: (v: PreviewView) => void
+ onRecord: (r: LearningRecord) => void
+ onCreate: () => void
+ onPartner: (id: string) => void
+ onNewPartner: () => void
+ onNewGroup: () => void
+ onResource: (href: string) => void
+}) {
+ const drawer = useSidebarDrawer()
+ const create = () => {
+ onCreate()
+ drawer?.close()
+ }
+ const createPartner = () => {
+ onNewPartner()
+ drawer?.close()
+ }
+ const createGroup = () => {
+ onNewGroup()
+ drawer?.close()
+ }
+ const selectPartner = (id: string) => {
+ onPartner(id)
+ drawer?.close()
+ }
+ if (collapsed) return null
+ return (
+ <div
+ key={category}
+ id="preview-category-content"
+ role="tabpanel"
+ aria-label={`${categories.find(c => c.id === category)?.label}栏目`}
+ className="preview-category-content"
+ >
+ {category === 'home' && (
+ <>
+ <SectionLabel label="我的空间" />
+ <SidebarRow
+ icon={Home}
+ label="主页"
+ active={view === 'home'}
+ onClick={() => onGo('home')}
+ />
+ <SidebarRow
+ icon={Columns3}
+ label="任务看板"
+ active={view === 'kanban'}
+ onClick={() => onGo('kanban')}
+ />
+ <SidebarRow
+ icon={PenLine}
+ label="智能写作"
+ active={view === 'writing'}
+ onClick={() => onGo('writing')}
+ />
+ <SidebarRow
+ icon={Bot}
+ label="智能体"
+ active={view === 'agents'}
+ onClick={() => onGo('agents')}
+ />
+ <SectionLabel label="最近对话" />
+ <SidebarRow
+ icon={MessageCircle}
+ label="与 Dito 对话"
+ active={view === 'chat'}
+ onClick={() => onGo('chat')}
+ />
+ </>
+ )}
+ {category === 'partners' && (
+ <>
+ <SectionLabel label="我的伙伴" action="新建伙伴" onAction={createPartner} />
+ <div className="preview-partner-roster">
+ {collections.partners.map(p => (
+ <button
+ key={p.id}
+ aria-label={`打开伙伴 ${p.name}`}
+ className={activePartner === p.id && view === 'partners' ? 'is-active' : ''}
+ onClick={() => selectPartner(p.id)}
+ >
+ <PartnerAvatar name={p.name} color={p.color} size={45} />
+ <span>{p.name}</span>
+ </button>
+ ))}
+ <button onClick={createPartner} aria-label="添加伙伴">
+ <span className="preview-add-avatar">
+ <Plus size={23} strokeWidth={1.5} />
+ </span>
+ <span>新伙伴</span>
+ </button>
+ </div>
+ <SidebarRow
+ icon={LayoutGrid}
+ label="所有伙伴"
+ onClick={() => onPartner('')}
+ active={view === 'partners' && !activePartner}
+ />
+ <SectionLabel label="群组" action="新建群组" onAction={createGroup} />
+ {collections.groups.map(g => (
+ <SidebarRow
+ key={g.id}
+ icon={Users}
+ label={g.name}
+ active={view === 'partners' && activePartner === g.id}
+ onClick={() => onPartner(g.id)}
+ trailing={<small>{g.members.length}</small>}
+ />
+ ))}
+ <SectionLabel label="最近会话" />
+ {collections.sessions.map(s => (
+ <SidebarRow
+ key={s.id}
+ icon={MessageCircle}
+ label={s.title}
+ active={view === 'partners' && activePartner === s.id}
+ onClick={() => onPartner(s.id)}
+ />
+ ))}
+ </>
+ )}
+ {category === 'learning' && (
+ <>
+ <SectionLabel label="个性化学习" action="新建学习" onAction={create} />
+ <SidebarRow
+ icon={LayoutGrid}
+ label="所有学习"
+ onClick={() => onGo('learning')}
+ active={view === 'learning'}
+ />
+ <SectionLabel label="我的学习记录" />
+ {collections.learning.map(r => (
+ <SidebarRow
+ key={r.id}
+ icon={learningKinds.find(k => k.id === r.kind)!.icon}
+ label={r.title}
+ active={activeRecord === r.id && ['record', 'reading', 'mastery'].includes(view)}
+ onClick={() => onRecord(r)}
+ />
+ ))}
+ <button className="preview-sidebar-add" onClick={create}>
+ <Plus size={17} />
+ 新建学习
+ </button>
+ </>
+ )}
+ {category === 'library' && (
+ <>
+ <SectionLabel label="学习空间" />
+ <SidebarRow
+ icon={LayoutGrid}
+ label="资料总览"
+ active={view === 'library'}
+ onClick={() => onGo('library')}
+ />
+ {DASHBOARD_GROUPS.filter(g => g.items.some(i => !i.requiresCapability)).map(g => (
+ <div key={g.label.zh}>
+ <SectionLabel label={g.label.zh} />
+ {g.items
+ .filter(i => !i.requiresCapability)
+ .map(item => (
+ <SidebarRow
+ key={item.key}
+ icon={item.icon}
+ label={item.title.zh}
+ active={view === 'resource' && resourceHref === item.href}
+ onClick={() => onResource(item.href)}
+ trailing={<ChevronRight className="preview-row-reveal" size={13} />}
+ />
+ ))}
+ </div>
+ ))}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/web/features/preview/PreviewWorkspace.tsx b/web/features/preview/PreviewWorkspace.tsx
new file mode 100644
index 000000000..a51373e50
--- /dev/null
+++ b/web/features/preview/PreviewWorkspace.tsx
@@ -0,0 +1,1148 @@
+'use client'
+
+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
+import Image from 'next/image'
+import {
+ ArrowRight,
+ BookOpen,
+ Check,
+ ChevronRight,
+ Compass,
+ FileText,
+ Home,
+ Users,
+ Bot,
+ Columns3,
+ Library,
+ MessageSquare,
+ MoreHorizontal,
+ PenLine,
+ Plus,
+ Search,
+ Settings2,
+ Sparkles,
+ Star,
+ X,
+ type LucideIcon,
+} from 'lucide-react'
+import AppShell, { useSidebarDrawer } from '@/components/layout/AppShell'
+import { SidebarShell } from '@/components/sidebar/SidebarShell'
+import { FeaturePage, PageHeader, pageActionClass } from '@/components/layout/FeaturePage'
+import SpaceDashboard, { DASHBOARD_GROUPS } from '@/components/space/SpaceDashboard'
+import AgentsHub from '@/components/agents/AgentsHub'
+import KanbanBoard from '@/features/tasks/components/KanbanBoard'
+import { startTaskBoardSync } from '@/lib/task-board-store'
+import { CategoryTabs, CategoryBody } from './PreviewNavigation'
+import { useCollections, type Category, type LearningRecord } from './collections'
+import {
+ LearningOverview,
+ CreateLearningDialog,
+ LearningRecordSurface,
+ PartnerSurface,
+ ResourceSurface,
+ type PartnerModal,
+} from './CollectionSurfaces'
+import { LearningCardContent } from '@/components/learning/LearningCard'
+import StandaloneComposer, {
+ type StandaloneComposerSubmission,
+} from '@/components/chat/home/StandaloneComposer'
+import { CHAT_CAPABILITIES } from '@/features/capabilities/presentation'
+import CoWriterWorkspace from '@/features/co-writer/components/CoWriterWorkspace'
+import { ReadingProvider, useReading } from '@/context/ReadingContext'
+import { AnnotationList } from '@/components/reading/AnnotationList'
+import { ReaderPane, READER_ASK_EVENT } from '@/components/reading/ReaderPane'
+import { MasteryQuestionCard } from '@/components/chat/home/MasteryQuestionCard'
+import MarkdownRenderer from '@/components/common/MarkdownRenderer'
+import { Dialog } from '@/shared/ui/Dialog'
+import Tooltip from '@/shared/ui/Tooltip'
+import { useAppShell } from '@/context/AppShellContext'
+import type { MasteryGradeResult } from '@/lib/mastery-question'
+import type { JumpRequest } from '@/components/reading/PdfDocumentView'
+import { material, objectives, previewItems, question, type PreviewView } from './fixtures'
+import { readDemo, writeDemo } from './demo-transport'
+
+const icons: Record<PreviewView, LucideIcon> = {
+ home: Home,
+ learning: Compass,
+ library: Library,
+ reading: BookOpen,
+ writing: PenLine,
+ mastery: Compass,
+ chat: MessageSquare,
+ partners: Users,
+ kanban: Columns3,
+ agents: Bot,
+ resource: Library,
+ record: BookOpen,
+}
+const titles: Record<PreviewView, string> = {
+ home: '主页',
+ learning: '我的学习',
+ library: '资料',
+ partners: '伙伴',
+ kanban: '任务看板',
+ agents: '智能体',
+ resource: '资料',
+ record: '学习记录',
+ reading: material.title,
+ writing: '我的研究计划',
+ mastery: '线性代数,从直觉出发',
+ chat: '与 Dito 对话',
+}
+const caps = CHAT_CAPABILITIES.filter(c =>
+ ['', 'deep_solve', 'ask_questions', 'deep_research', 'visualize'].includes(c.value)
+).map(c =>
+ c.value === ''
+ ? { ...c, label: 'Auto', description: '告诉 Dito 你的目标,由它选择合适的方式', icon: Sparkles }
+ : c
+)
+type Message = {
+ id: string
+ role: 'user' | 'assistant'
+ text: string
+ target?: PreviewView
+ targetLabel?: string
+}
+type Messages = Partial<Record<PreviewView, Message[]>>
+
+function IconAction({
+ label,
+ icon: Icon,
+ onClick,
+ active,
+}: {
+ label: string
+ icon: LucideIcon
+ onClick: () => void
+ active?: boolean
+}) {
+ return (
+ <Tooltip label={label} side="bottom">
+ <button
+ type="button"
+ aria-label={label}
+ aria-pressed={active}
+ onClick={onClick}
+ className={`preview-icon ${active ? 'is-active' : ''}`}
+ >
+ <Icon size={16} strokeWidth={1.6} />
+ </button>
+ </Tooltip>
+ )
+}
+
+function NavRow({
+ icon: Icon,
+ label,
+ active,
+ collapsed,
+ onClick,
+ trailing,
+}: {
+ icon: LucideIcon
+ label: string
+ active?: boolean
+ collapsed?: boolean
+ onClick: () => void
+ trailing?: ReactNode
+}) {
+ const drawer = useSidebarDrawer()
+ const row = (
+ <button
+ className={`preview-nav-row ${active ? 'is-active' : ''} ${collapsed ? 'is-collapsed' : ''}`}
+ aria-current={active ? 'page' : undefined}
+ aria-label={collapsed ? label : undefined}
+ onClick={() => {
+ onClick()
+ drawer?.close()
+ }}
+ >
+ <Icon size={17} strokeWidth={1.65} />
+ {!collapsed && (
+ <>
+ <span>{label}</span>
+ {trailing}
+ </>
+ )}
+ </button>
+ )
+ return collapsed ? (
+ <Tooltip label={label} side="right">
+ {row}
+ </Tooltip>
+ ) : (
+ row
+ )
+}
+
+function ContentRow({
+ item,
+ onOpen,
+}: {
+ item: (typeof previewItems)[number]
+ onOpen: (view: PreviewView) => void
+}) {
+ const Icon = icons[item.view]
+ return (
+ <button className="preview-content-row" onClick={() => onOpen(item.view)}>
+ <LearningCardContent
+ title={item.title}
+ subtitle={item.detail}
+ icon={<Icon size={20} strokeWidth={1.5} />}
+ progress={item.progress}
+ />
+ <ChevronRight size={15} className="text-muted-foreground shrink-0" />
+ </button>
+ )
+}
+
+export default function PreviewWorkspace() {
+ return (
+ <ReadingProvider>
+ <Workspace />
+ </ReadingProvider>
+ )
+}
+
+function Workspace() {
+ useEffect(() => startTaskBoardSync({ stream: false }), [])
+ const [view, setView] = useState<PreviewView>(() => {
+ const hash = location.hash.slice(1).split('/')[0]
+ return hash in titles ? (hash as PreviewView) : 'home'
+ })
+ const collections = useCollections()
+ const [category, setCategory] = useState<Category>(() => readDemo('category', 'home'))
+ const [activeRecord, setActiveRecord] = useState(
+ () =>
+ decodeURIComponent(location.hash.split('/')[1] || '') ||
+ readDemo('active-record', 'attention')
+ )
+ const [activePartner, setActivePartner] = useState(() =>
+ location.hash.startsWith('#partners/')
+ ? decodeURIComponent(location.hash.slice(10))
+ : readDemo('active-partner', '')
+ )
+ const [resourceHref, setResourceHref] = useState(() =>
+ location.hash.startsWith('#resource/')
+ ? decodeURIComponent(location.hash.slice(10))
+ : readDemo('resource-href', '/notebooks')
+ )
+ const [partnerModal, setPartnerModal] = useState<PartnerModal>(null)
+ useEffect(() => writeDemo('category', category), [category])
+ useEffect(() => writeDemo('active-record', activeRecord), [activeRecord])
+ useEffect(() => writeDemo('active-partner', activePartner), [activePartner])
+ useEffect(() => writeDemo('resource-href', resourceHref), [resourceHref])
+ const [assistantOpen, setAssistantOpen] = useState(() => location.hash.startsWith('#reading'))
+ const [dialog, setDialog] = useState<'search' | 'start' | 'settings' | 'about' | null>(null)
+ const [query, setQuery] = useState('')
+ const [favorites, setFavorites] = useState<string[]>(() =>
+ readDemo('favorites', ['attention', 'research'])
+ )
+ const [messages, setMessages] = useState<Messages>(() => readDemo('messages', {}))
+ const [pending, setPending] = useState<PreviewView | null>(null)
+ const [mode, setMode] = useState('')
+ const [quote, setQuote] = useState('')
+ const [panelTab, setPanelTab] = useState<'dito' | 'annotations'>('dito')
+ const [readingJump, setReadingJump] = useState<JumpRequest | null>(null)
+ const [recentIds, setRecentIds] = useState<string[]>(() =>
+ readDemo(
+ 'recent',
+ previewItems.map(item => item.id)
+ )
+ )
+ const [savedContent, setSavedContent] = useState(() => ({
+ title: readDemo('document', { title: '我的研究计划' }).title,
+ locator: readDemo('position', { locator: 1 }).locator,
+ }))
+ const [grade, setGrade] = useState<MasteryGradeResult | null>(() => readDemo('grade', null))
+ const [objective, setObjective] = useState(2)
+ const responseTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const prefillRef = useRef<((text: string) => void) | null>(null)
+ const { theme, setTheme, setLanguage } = useAppShell()
+ const { annotations, removeMark } = useReading()
+ const go = useCallback((next: PreviewView, entity?: string) => {
+ setPanelTab('dito')
+ const item = previewItems.find(item => item.view === next)
+ if (item) setRecentIds(ids => [item.id, ...ids.filter(id => id !== item.id)])
+ setView(next)
+ setCategory(
+ ['learning', 'reading', 'mastery', 'record'].includes(next)
+ ? 'learning'
+ : ['library', 'resource'].includes(next)
+ ? 'library'
+ : next === 'partners'
+ ? 'partners'
+ : 'home'
+ )
+ if (next === 'reading') setActiveRecord('attention')
+ if (next === 'mastery') setActiveRecord('linear')
+ location.hash = next + (entity ? '/' + encodeURIComponent(entity) : '')
+ setDialog(null)
+ setQuote('')
+ setAssistantOpen(next === 'reading')
+ }, [])
+
+ useEffect(() => {
+ setLanguage('zh')
+ const onHash = () => {
+ const [h, raw] = location.hash.slice(1).split('/')
+ const entity = decodeURIComponent(raw || '')
+ if (h in titles) {
+ setView(h as PreviewView)
+ if (h === 'record' && entity) setActiveRecord(entity)
+ if (h === 'partners') setActivePartner(entity)
+ if (h === 'resource' && entity) setResourceHref(entity)
+ }
+ }
+ const onKey = (e: KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
+ e.preventDefault()
+ setDialog(d => (d === 'search' ? null : 'search'))
+ }
+ }
+ const onAsk = (event: Event) => {
+ const data = (event as CustomEvent<{ quote: string; prompt?: string }>).detail
+ setPanelTab('dito')
+ setQuote(data.quote)
+ setAssistantOpen(true)
+ if (data.prompt) requestAnimationFrame(() => prefillRef.current?.(data.prompt || ''))
+ }
+ const onData = (event: Event) => {
+ if (!['document', 'position'].includes((event as CustomEvent<string>).detail)) return
+ setSavedContent({
+ title: readDemo('document', { title: '我的研究计划' }).title,
+ locator: readDemo('position', { locator: 1 }).locator,
+ })
+ }
+ window.addEventListener('dito-preview-data', onData)
+ window.addEventListener('hashchange', onHash)
+ window.addEventListener('keydown', onKey)
+ window.addEventListener(READER_ASK_EVENT, onAsk)
+ return () => {
+ window.removeEventListener('dito-preview-data', onData)
+ window.removeEventListener('hashchange', onHash)
+ window.removeEventListener('keydown', onKey)
+ window.removeEventListener(READER_ASK_EVENT, onAsk)
+ if (responseTimer.current) clearTimeout(responseTimer.current)
+ }
+ }, [setLanguage])
+ useEffect(() => writeDemo('messages', messages), [messages])
+ useEffect(() => writeDemo('favorites', favorites), [favorites])
+ useEffect(() => writeDemo('recent', recentIds), [recentIds])
+ useEffect(() => writeDemo('grade', grade), [grade])
+
+ const cancel = () => {
+ if (responseTimer.current) clearTimeout(responseTimer.current)
+ setPending(null)
+ }
+ function send(submission: StandaloneComposerSubmission, from = view) {
+ if (pending) return
+ const content = submission.content.trim()
+ if (!content && !submission.attachments.length) return
+ const context = from === 'home' ? 'chat' : from
+ const userText = `${quote ? `> ${quote}\n\n` : ''}${content}${submission.attachments.length ? `\n\n(已附 ${submission.attachments.length} 个文件;预览不解析附件)` : ''}`
+ setMessages(m => ({
+ ...m,
+ [context]: [...(m[context] || []), { id: crypto.randomUUID(), role: 'user', text: userText }],
+ }))
+ setQuote('')
+ setPending(context)
+ if (from === 'home') go('chat')
+ const selectedMode = mode
+ responseTimer.current = setTimeout(() => {
+ let text =
+ '我们可以从一个具体问题开始。比如读懂一份材料、解释一个概念,或把一个想法整理成文稿。下面是可以继续体验的学习材料。'
+ let target: PreviewView = 'reading'
+ let targetLabel = '打开注意力机制笔记'
+ if (from === 'reading' || /注意力|transformer|attention/i.test(content)) {
+ text =
+ '理解注意力,可以先记住三步:**匹配、归一化、汇总**。\n\nQuery 表达当前词需要什么,Key 表达其他词能提供什么。两者点积得到匹配分数,经过 softmax 变成权重,再对 Value 加权求和。\n\n缩放因子 $\\sqrt{d_k}$ 用来控制点积分数的波动,避免 softmax 过度集中。\n\n试着用一句话解释:为什么 Key 与 Value 要分开?'
+ } else if (from === 'writing' || /写|文稿|研究计划/.test(content)) {
+ text =
+ '可以把研究计划按 **问题 → 假设 → 验证 → 下一步** 组织。\n\n先写清楚想解决的学习困难,再给出一个能验证的假设。最后列出本周能完成的最小实验,避免文稿只有方向、没有行动。\n\n已准备好一份示例文稿,你可以直接进入 Co-Writer 修改。'
+ target = 'writing'
+ targetLabel = '在 Co-Writer 中打开'
+ } else if (from === 'mastery' || /练习|学习计划|线性|复习/.test(content)) {
+ text =
+ '我们从你已经掌握的向量和矩阵出发,继续理解 **线性无关与基**。\n\n一组基需要满足两点:能组合出空间里的所有向量,并且其中没有多余的向量。先做一道判断题,再根据答案决定下一步。'
+ target = 'mastery'
+ targetLabel = '开始这道练习'
+ }
+ if (selectedMode)
+ text = `已手动选择「${caps.find(c => c.value === selectedMode)?.label}」。以下为流程示例,未执行模型调用。\n\n${text}`
+ setMessages(m => ({
+ ...m,
+ [context]: [
+ ...(m[context] || []),
+ { id: crypto.randomUUID(), role: 'assistant', text, target, targetLabel },
+ ],
+ }))
+ setPending(null)
+ }, 650)
+ }
+
+ const items = previewItems.map(item =>
+ item.view === 'writing'
+ ? { ...item, title: savedContent.title }
+ : item.view === 'reading'
+ ? {
+ ...item,
+ progress: savedContent.locator / 3,
+ detail: `机器学习 · 第 ${savedContent.locator} / 3 节`,
+ }
+ : item.view === 'mastery'
+ ? {
+ ...item,
+ progress: grade?.isCorrect ? 0.5 : 1 / 3,
+ detail: `6 个学习目标 · 已完成 ${grade?.isCorrect ? 3 : 2} 个`,
+ }
+ : {
+ ...item,
+ title:
+ messages.chat
+ ?.find(message => message.role === 'user')
+ ?.text.split('\n')[0]
+ .slice(0, 32) || item.title,
+ }
+ )
+ const currentItem = items.find(i => i.view === view)
+ const currentRecord = collections.learning.find(r => r.id === activeRecord)
+ const currentTitle =
+ view === 'record'
+ ? currentRecord?.title || '学习记录'
+ : view === 'resource'
+ ? DASHBOARD_GROUPS.flatMap(g => g.items).find(i => i.href === resourceHref)?.title.zh ||
+ '资料'
+ : currentItem?.title || titles[view]
+ const openRecord = (record: LearningRecord) => {
+ setActiveRecord(record.id)
+ go(
+ record.sample && (record.kind === 'reading' || record.kind === 'mastery')
+ ? record.kind
+ : 'record',
+ record.id
+ )
+ }
+ const openPartner = (id: string) => {
+ setActivePartner(id)
+ go('partners', id)
+ }
+ const openResource = (href: string) => {
+ setResourceHref(href)
+ go('resource', href)
+ }
+ const isActivity = ['reading', 'writing', 'mastery'].includes(view)
+ const star = () => {
+ if (currentItem)
+ setFavorites(f =>
+ f.includes(currentItem.id) ? f.filter(id => id !== currentItem.id) : [...f, currentItem.id]
+ )
+ }
+ const newChat = () => {
+ cancel()
+ setMessages(m => ({ ...m, chat: [] }))
+ go('chat')
+ }
+ const composer = (context: PreviewView, hasMessages = false) => (
+ <StandaloneComposer
+ onSubmit={s => send(s, context)}
+ onCancelStreaming={cancel}
+ isStreaming={pending !== null}
+ hasMessages={hasMessages}
+ inputPlaceholder={
+ context === 'home'
+ ? '告诉 Dito,你今天想学什么、读什么,或完成什么…'
+ : '问 Dito,或让它帮你继续…'
+ }
+ capabilities={caps}
+ activeCapValue={mode}
+ onSelectCapability={setMode}
+ agentsAvailable={false}
+ prefillInputRef={prefillRef}
+ inputHeader={
+ quote ? (
+ <div className="preview-quote">
+ <span>{quote}</span>
+ <button aria-label="移除引用" onClick={() => setQuote('')}>
+ <X size={13} />
+ </button>
+ </div>
+ ) : undefined
+ }
+ />
+ )
+ const conversation = (context: PreviewView) => (
+ <Conversation
+ messages={messages[context] || []}
+ pending={pending === context}
+ context={context}
+ onOpen={go}
+ onPrompt={text =>
+ send(
+ {
+ content: text,
+ attachments: [],
+ knowledgeBases: [],
+ notebookReferences: [],
+ historyReferences: [],
+ bookReferences: [],
+ questionNotebookReferences: [],
+ memoryReferences: [],
+ persona: null,
+ llmSelection: null,
+ subagentBudget: null,
+ },
+ context
+ )
+ }
+ />
+ )
+
+ return (
+ <div className="dito-preview">
+ <AppShell
+ homeHref="/preview#home"
+ sidebar={
+ <SidebarShell
+ brandHref="/preview#home"
+ initialWidth={272}
+ widthStorageKey="deeptutor.dito-preview.sidebar-width"
+ homeSlot={collapsed => (
+ <CategoryTabs
+ category={category}
+ collapsed={collapsed}
+ onChange={next => {
+ setCategory(next)
+ if (collapsed) go(next)
+ }}
+ onSearch={() => {
+ setQuery('')
+ setDialog('search')
+ }}
+ />
+ )}
+ bodySlot={collapsed => (
+ <CategoryBody
+ category={category}
+ collapsed={collapsed}
+ view={view}
+ collections={collections}
+ activeRecord={activeRecord}
+ activePartner={activePartner}
+ resourceHref={resourceHref}
+ onGo={go}
+ onRecord={openRecord}
+ onCreate={() => setDialog('start')}
+ onPartner={openPartner}
+ onNewPartner={() => {
+ openPartner('')
+ setPartnerModal('partner')
+ }}
+ onNewGroup={() => {
+ openPartner('')
+ setPartnerModal('group')
+ }}
+ onResource={openResource}
+ />
+ )}
+ footerOverride={collapsed => (
+ <div className="preview-sidebar-footer">
+ <NavRow
+ icon={Settings2}
+ label="偏好设置"
+ collapsed={collapsed}
+ onClick={() => setDialog('settings')}
+ />
+ <button
+ aria-label="新对话"
+ className={`preview-new-chat ${collapsed ? 'is-collapsed' : ''}`}
+ onClick={newChat}
+ >
+ <Sparkles size={16} />
+ {!collapsed && (
+ <>
+ <span>找 Dito 聊聊</span>
+ <Plus size={15} />
+ </>
+ )}
+ </button>
+ </div>
+ )}
+ />
+ }
+ >
+ <div className="preview-layout">
+ <header className="preview-topbar">
+ <div className="preview-breadcrumb">
+ <button onClick={() => go('home')}>个人空间</button>
+ <ChevronRight size={12} />
+ <span>{currentTitle}</span>
+ </div>
+ <div className="preview-top-actions">
+ <button className="preview-badge" onClick={() => setDialog('about')}>
+ 交互预览
+ </button>
+ {currentItem && (
+ <IconAction
+ label={favorites.includes(currentItem.id) ? '取消收藏' : '收藏此页'}
+ icon={Star}
+ onClick={star}
+ active={favorites.includes(currentItem.id)}
+ />
+ )}
+ <IconAction
+ label="预览说明"
+ icon={MoreHorizontal}
+ onClick={() => setDialog('about')}
+ />
+ {isActivity && (
+ <button
+ className={`preview-dito-toggle ${assistantOpen ? 'is-active' : ''}`}
+ onClick={() => setAssistantOpen(v => !v)}
+ aria-pressed={assistantOpen}
+ >
+ <Sparkles size={14} />
+ Dito
+ </button>
+ )}
+ </div>
+ </header>
+ <div className="preview-work-area">
+ <div className="preview-main">
+ {view === 'home' && (
+ <FeaturePage className="preview-home">
+ <div className="preview-home-inner">
+ <div className="preview-eyebrow">你的学习,从这里继续</div>
+ <PageHeader title="你好,Frank" description="今天有什么想弄明白的?" />
+ <div className="preview-home-composer">{composer('home')}</div>
+ <div className="preview-quick-actions">
+ {[
+ { label: '任务看板', icon: Columns3, view: 'kanban' },
+ { label: '智能写作', icon: PenLine, view: 'writing' },
+ { label: '智能体', icon: Bot, view: 'agents' },
+ ].map(a => (
+ <button key={a.label} onClick={() => go(a.view as PreviewView)}>
+ <a.icon size={15} />
+ {a.label}
+ <ArrowRight size={12} />
+ </button>
+ ))}
+ </div>
+ <section className="preview-section">
+ <div className="preview-section-title">
+ <h2>继续上次的学习</h2>
+ <button onClick={() => go('learning')}>
+ 查看全部
+ <ArrowRight size={13} />
+ </button>
+ </div>
+ <div className="preview-resume-list">
+ {items.slice(0, 3).map(item => (
+ <ContentRow key={item.id} item={item} onOpen={go} />
+ ))}
+ </div>
+ </section>
+ <section className="preview-review">
+ <div className="preview-review-icon">
+ <Compass size={22} strokeWidth={1.4} />
+ </div>
+ <div>
+ <h3>{grade?.isCorrect ? '今天的复习已完成' : '花几分钟,让理解更扎实'}</h3>
+ <p>
+ {grade?.isCorrect
+ ? '线性无关与基 · 已掌握这道练习'
+ : '线性无关与基 · 1 道待复习练习'}
+ </p>
+ </div>
+ <button
+ className={pageActionClass('secondary')}
+ onClick={() => go('mastery')}
+ >
+ {grade?.isCorrect ? '查看练习' : '开始复习'}
+ <ArrowRight size={14} />
+ </button>
+ </section>
+ <p className="preview-home-footnote">
+ Dito 会陪你阅读、思考和创作。你也可以随时自己选择学习方式。
+ </p>
+ </div>
+ </FeaturePage>
+ )}
+ {view === 'learning' && (
+ <LearningOverview
+ collections={collections}
+ onOpen={openRecord}
+ onCreate={() => setDialog('start')}
+ />
+ )}
+ {view === 'library' && (
+ <FeaturePage>
+ <SpaceDashboard
+ title="资料"
+ description="原来的学习空间。对话、笔记、知识与能力资源,集中在这里。"
+ onNavigate={openResource}
+ />
+ </FeaturePage>
+ )}
+ {view === 'resource' && (
+ <ResourceSurface
+ key={resourceHref}
+ href={resourceHref}
+ onBack={() => go('library')}
+ />
+ )}
+ {view === 'kanban' && <KanbanBoard />}
+ {view === 'agents' && (
+ <FeaturePage>
+ <AgentsHub />
+ </FeaturePage>
+ )}
+ {view === 'partners' && (
+ <PartnerSurface
+ collections={collections}
+ selected={activePartner}
+ onSelect={openPartner}
+ modal={partnerModal}
+ setModal={setPartnerModal}
+ />
+ )}
+ {view === 'record' && currentRecord && (
+ <LearningRecordSurface
+ key={currentRecord.id}
+ record={currentRecord}
+ onBack={() => go('learning')}
+ onChange={record =>
+ collections.setLearning(all => all.map(r => (r.id === record.id ? record : r)))
+ }
+ />
+ )}
+ {view === 'reading' && (
+ <ReadingSurface onClose={() => go('learning')} externalJump={readingJump} />
+ )}
+ {view === 'writing' && (
+ <CoWriterWorkspace docId="preview-research" onBack={() => go('home')} />
+ )}
+ {view === 'mastery' && (
+ <FeaturePage className="preview-mastery">
+ <PageHeader title="线性代数,从直觉出发" description="先建立直觉,再验证理解。" />
+ <div className="preview-mastery-layout">
+ <nav aria-label="学习目标" className="preview-objectives">
+ <div className="preview-nav-label">
+ 学习目标 · {grade?.isCorrect ? 3 : 2} / 6
+ </div>
+ {objectives.map((name, i) => (
+ <button
+ key={name}
+ className={objective === i ? 'is-active' : ''}
+ onClick={() => setObjective(i)}
+ >
+ <span>
+ {i < 2 || (i === 2 && grade?.isCorrect) ? (
+ <Check size={12} />
+ ) : (
+ String(i + 1).padStart(2, '0')
+ )}
+ </span>
+ {name}
+ </button>
+ ))}
+ </nav>
+ <div className="preview-lesson">
+ <div className="preview-eyebrow">
+ 当前目标 {String(objective + 1).padStart(2, '0')}
+ </div>
+ <h2>{objectives[objective]}</h2>
+ {objective === 2 ? (
+ <>
+ <p className="preview-lesson-intro">
+ 想象你要在平面上描述一个位置。两个方向互不重复的向量,就能通过缩放和相加,到达平面上的任意一点。这样的两个向量构成一组基。
+ </p>
+ <MasteryQuestionCard
+ question={question}
+ grade={grade}
+ answered={grade !== null}
+ submittedAnswer={grade?.learnerAnswer || ''}
+ onSubmit={p => {
+ const answer = p.answers?.[0]?.text || p.text || ''
+ setGrade({
+ questionId: question.questionId,
+ learnerAnswer: answer,
+ isCorrect: answer === 'B',
+ correctLabel: 'B',
+ correctBody: '(1, 0) 和 (0, 1)',
+ explanation:
+ '这两个向量线性无关,且可以组合出二维平面中的任意向量。A 的两个向量共线,C 包含零向量,都不能张成整个平面。',
+ result: answer === 'B' ? 'correct' : 'incorrect',
+ })
+ return true
+ }}
+ />
+ {grade && (
+ <div className="preview-lesson-next">
+ <button
+ className={pageActionClass('secondary')}
+ onClick={() => setGrade(null)}
+ >
+ 再试一次
+ </button>
+ <button className={pageActionClass()} onClick={() => setObjective(3)}>
+ 下一目标
+ <ArrowRight size={14} />
+ </button>
+ </div>
+ )}
+ </>
+ ) : (
+ <>
+ <p className="preview-lesson-intro">
+ {
+ [
+ '把向量看成一个方向和一段距离。通过缩放与相加,我们可以组合出新的向量。',
+ '一个矩阵描述了空间如何变换。它的每一列,都告诉你一个基向量被送到了哪里。',
+ '',
+ '有些向量经过变换后方向保持不变,它们就是特征向量。对应的缩放倍数就是特征值。',
+ '正交投影把一个向量分成沿着某个方向的部分,以及与这个方向垂直的部分。',
+ '从一个实际数据问题开始,观察矩阵如何表达关系,投影如何简化信息。',
+ ][objective]
+ }
+ </p>
+ <button
+ className={pageActionClass('secondary')}
+ onClick={() => setAssistantOpen(true)}
+ >
+ <Sparkles size={14} />让 Dito 帮我理解
+ </button>
+ {objective !== 2 && (
+ <button
+ className="ml-3 text-sm underline underline-offset-4"
+ onClick={() => setObjective(2)}
+ >
+ 回到练习
+ </button>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </FeaturePage>
+ )}
+ {view === 'chat' && (
+ <div className="preview-chat-page">
+ <div className="preview-chat-heading">
+ <Sparkles size={17} />
+ <h1>Dito</h1>
+ <span>你的通用学习助手</span>
+ <button onClick={newChat} aria-label="清空并开始新对话">
+ <Plus size={16} />
+ </button>
+ </div>
+ {conversation('chat')}
+ <div className="preview-chat-composer">
+ {composer('chat', !!messages.chat?.length)}
+ <p>示例对话 · 未连接模型</p>
+ </div>
+ </div>
+ )}
+ </div>
+ {isActivity && assistantOpen && (
+ <aside className="preview-assistant" aria-label="Dito 学习助手">
+ <header>
+ <Sparkles size={16} />
+ <button
+ className={panelTab === 'dito' ? 'font-semibold' : 'text-muted-foreground'}
+ onClick={() => setPanelTab('dito')}
+ >
+ Dito
+ </button>
+ {view === 'reading' && (
+ <button
+ className={
+ panelTab === 'annotations' ? 'font-semibold' : 'text-muted-foreground'
+ }
+ onClick={() => setPanelTab('annotations')}
+ >
+ 批注 {annotations.length || ''}
+ </button>
+ )}
+ <span />
+ <IconAction icon={X} label="关闭 Dito" onClick={() => setAssistantOpen(false)} />
+ </header>
+ <div className="preview-context-chip">
+ <FileText size={13} />
+ <span>{currentTitle}</span>
+ <span>当前内容</span>
+ </div>
+ {panelTab === 'annotations' && view === 'reading' ? (
+ <div className="min-h-0 flex-1 mt-3">
+ <AnnotationList
+ annotations={annotations}
+ unit="section"
+ activeId={null}
+ onSelect={mark =>
+ setReadingJump({
+ locator: mark.locator,
+ quote: mark.quote,
+ nonce: Date.now(),
+ })
+ }
+ onDelete={mark => {
+ void removeMark(mark)
+ }}
+ />
+ </div>
+ ) : (
+ <>
+ {conversation(view)}
+ <div className="preview-panel-composer">
+ {composer(view, true)}
+ <p>示例对话 · 未连接模型</p>
+ </div>
+ </>
+ )}
+ </aside>
+ )}
+ </div>
+ </div>
+ </AppShell>
+ <Dialog
+ open={dialog === 'search'}
+ title="搜索你的空间"
+ onClose={() => setDialog(null)}
+ closeLabel="关闭搜索"
+ >
+ <div className="preview-search-field large">
+ <Search size={18} />
+ <input
+ data-autofocus
+ aria-label="搜索内容"
+ placeholder="搜索材料、文稿、学习路径…"
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ />
+ <kbd>Esc</kbd>
+ </div>
+ <div className="preview-search-results">
+ {collections.learning
+ .filter(r => r.title.includes(query) || r.kind.includes(query))
+ .map(r => (
+ <button key={r.id} className="preview-session-row" onClick={() => openRecord(r)}>
+ <BookOpen size={17} />
+ <span>{r.title}</span>
+ <ArrowRight size={14} />
+ </button>
+ ))}
+ {items
+ .filter(i => ['writing', 'chat'].includes(i.view))
+ .filter(
+ i => i.title.toLowerCase().includes(query.toLowerCase()) || i.kind.includes(query)
+ )
+ .map(item => (
+ <ContentRow key={item.id} item={item} onOpen={go} />
+ ))}
+ {!collections.learning.some(r => r.title.includes(query)) &&
+ !items.some(
+ i => i.title.toLowerCase().includes(query.toLowerCase()) || i.kind.includes(query)
+ ) && <p>没有匹配内容</p>}
+ </div>
+ </Dialog>
+ <CreateLearningDialog
+ open={dialog === 'start'}
+ onClose={() => setDialog(null)}
+ onCreate={record => {
+ collections.setLearning(all => [record, ...all])
+ openRecord(record)
+ }}
+ />
+ <Dialog
+ open={dialog === 'settings'}
+ title="偏好设置"
+ description="沿用 DeepTutor 现有的主题与侧栏设置。"
+ onClose={() => setDialog(null)}
+ closeLabel="关闭"
+ >
+ <h3 className="text-sm mb-3">外观</h3>
+ <div className="preview-theme-options">
+ {[
+ { value: 'snow', label: '简白' },
+ { value: 'light', label: '暖纸' },
+ { value: 'dark', label: '深色' },
+ ].map(item => (
+ <button
+ aria-pressed={theme === item.value}
+ key={item.value}
+ onClick={() => setTheme(item.value as typeof theme)}
+ className={theme === item.value ? 'is-active' : ''}
+ >
+ {item.label}
+ {theme === item.value && <Check size={14} />}
+ </button>
+ ))}
+ </div>
+ <p className="mt-6 text-xs text-muted-foreground leading-6">
+ 侧栏支持拖动调整宽度、收起与展开。搜索快捷键为 ⌘ / Ctrl
+ K。文稿、阅读位置、批注、收藏和示例对话保存在当前浏览器。
+ </p>
+ </Dialog>
+ <Dialog
+ open={dialog === 'about'}
+ title="这一版在探索什么"
+ onClose={() => setDialog(null)}
+ closeLabel="关闭"
+ >
+ <div className="preview-about">
+ <p>四个栏目:主页、伙伴、学习、资料。</p>
+ <p>
+ 顶部切换侧栏内容,保留当前正在看的页面。主页放
+ Dito、任务看板、智能写作和智能体;伙伴放配置、群组和会话;学习保留四种学习记录;资料继承学习空间。
+ </p>
+ <p>
+ 这一版直接复用现有 WebUI
+ 的侧栏外壳、页面布局、输入框、沉浸式阅读器、Co-Writer、任务看板、智能体页面、学习空间总览、练习题卡和弹窗。
+ </p>
+ <p className="text-muted-foreground">
+ 这是独立 worktree 中的前端预览。内容是示例,Dito
+ 使用固定演示回复;编辑、阅读、批注和练习可交互。新建学习保存为草稿,资源详情是分类交互示例。模型调用、外部渠道、文件解析和
+ Word 导出尚未连接。
+ </p>
+ </div>
+ </Dialog>
+ </div>
+ )
+}
+
+function Conversation({
+ messages,
+ pending,
+ context,
+ onOpen,
+ onPrompt,
+}: {
+ messages: Message[]
+ pending: boolean
+ context: PreviewView
+ onOpen: (view: PreviewView) => void
+ onPrompt: (text: string) => void
+}) {
+ const end = useRef<HTMLDivElement>(null)
+ useEffect(() => {
+ end.current?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
+ }, [messages, pending])
+ const suggestions =
+ context === 'reading'
+ ? ['解释一下注意力机制', '帮我梳理这份材料']
+ : context === 'writing'
+ ? ['帮我完善研究计划', '这份文稿可以怎么组织?']
+ : context === 'mastery'
+ ? ['用直觉解释线性无关', '我想复习一下']
+ : ['带我读懂注意力机制', '帮我写一份研究计划', '我想复习线性代数']
+ return (
+ <div className="preview-conversation">
+ {!messages.length && (
+ <div className="preview-conversation-empty">
+ <Image src="/logo.png" alt="" width={38} height={38} />
+ <h2>{context === 'chat' ? '想从哪里开始?' : '我就在这里'}</h2>
+ <p>
+ {context === 'chat'
+ ? '提一个问题,或告诉我你想完成什么。'
+ : '围绕当前内容提问,或一起找找下一步。'}
+ </p>
+ <div>
+ {suggestions.map(prompt => (
+ <button key={prompt} onClick={() => onPrompt(prompt)}>
+ {prompt}
+ <ArrowRight size={13} />
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ {messages.map(message => (
+ <div key={message.id} className={`preview-message ${message.role}`}>
+ <div className="preview-message-label">
+ {message.role === 'assistant' ? (
+ <>
+ <Sparkles size={13} />
+ Dito<span>示例回复</span>
+ </>
+ ) : (
+ '你'
+ )}
+ </div>
+ <MarkdownRenderer content={message.text} />
+ {message.target && context !== message.target && (
+ <button className="preview-result-link" onClick={() => onOpen(message.target!)}>
+ <FileText size={17} />
+ <span>{message.targetLabel}</span>
+ <ArrowRight size={15} />
+ </button>
+ )}
+ </div>
+ ))}
+ {pending && (
+ <div className="preview-thinking" role="status">
+ <span />
+ Dito 正在整理示例…
+ </div>
+ )}
+ <div ref={end} />
+ </div>
+ )
+}
+
+function ReadingSurface({
+ onClose,
+ externalJump,
+}: {
+ onClose: () => void
+ externalJump: JumpRequest | null
+}) {
+ const { openMaterial } = useReading()
+ const [jump, setJump] = useState<JumpRequest | null>(() => ({
+ locator: readDemo('position', { locator: 1 }).locator,
+ nonce: Date.now(),
+ }))
+ const [locator, setLocator] = useState(() => readDemo('position', { locator: 1 }).locator)
+ const [ready, setReady] = useState(false)
+ useEffect(() => {
+ let alive = true
+ void openMaterial(material).then(() => {
+ if (alive) setReady(true)
+ })
+ return () => {
+ alive = false
+ }
+ }, [openMaterial])
+ return (
+ <div className="preview-reading-surface">
+ <div className="preview-reading-outline">
+ <div className="preview-nav-label">目录</div>
+ {material.outline.map(row => (
+ <button
+ key={row.locator}
+ className={locator === row.locator ? 'is-active' : ''}
+ onClick={() => setJump({ locator: row.locator, nonce: Date.now() })}
+ >
+ <span>0{row.locator}</span>
+ {row.title}
+ </button>
+ ))}
+ </div>
+ <div className="preview-reader">
+ {ready ? (
+ <ReaderPane
+ onClose={onClose}
+ ownAnnotationList={false}
+ externalJump={
+ externalJump && externalJump.nonce > (jump?.nonce || 0) ? externalJump : jump
+ }
+ onLocatorChange={setLocator}
+ />
+ ) : (
+ <div role="status" className="p-8 text-sm text-muted-foreground">
+ 正在打开阅读材料…
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/web/features/preview/collections.ts b/web/features/preview/collections.ts
new file mode 100644
index 000000000..1be9cee45
--- /dev/null
+++ b/web/features/preview/collections.ts
@@ -0,0 +1,147 @@
+import { useEffect, useState } from 'react'
+import { BookOpen, Compass, ClipboardList, LibraryBig } from 'lucide-react'
+import { readDemo, writeDemo } from './demo-transport'
+
+export type Category = 'home' | 'partners' | 'learning' | 'library'
+export type LearningKind = 'book' | 'mastery' | 'practice' | 'reading'
+export const learningKinds = [
+ { id: 'book', label: '书籍', icon: LibraryBig, description: '把一个主题组织成一本专属的书' },
+ { id: 'mastery', label: '精通之路', icon: Compass, description: '循序渐进,直到真正掌握' },
+ { id: 'practice', label: '练习', icon: ClipboardList, description: '用练习检验理解,安排复习' },
+ {
+ id: 'reading',
+ label: '沉浸式阅读',
+ icon: BookOpen,
+ description: '专注阅读,在原文中提问和批注',
+ },
+] as const
+export type LearningRecord = {
+ id: string
+ title: string
+ kind: LearningKind
+ detail: string
+ notes: string
+ sample?: boolean
+}
+export const initialLearning: LearningRecord[] = [
+ {
+ id: 'attention',
+ title: '理解 Transformer 的注意力机制',
+ kind: 'reading',
+ detail: '机器学习 · 第 1 / 3 节',
+ notes: '',
+ sample: true,
+ },
+ {
+ id: 'linear',
+ title: '线性代数,从直觉出发',
+ kind: 'mastery',
+ detail: '6 个目标 · 已完成 2 个',
+ notes: '',
+ sample: true,
+ },
+ {
+ id: 'book',
+ title: '概率论的直觉',
+ kind: 'book',
+ detail: '书籍 · 3 个章节',
+ notes: '',
+ sample: true,
+ },
+ {
+ id: 'practice',
+ title: '向量与空间 · 巩固练习',
+ kind: 'practice',
+ detail: '练习 · 1 道待复习',
+ notes: '',
+ sample: true,
+ },
+]
+export type DemoPartner = { id: string; name: string; description: string; color: string }
+export type DemoGroup = { id: string; name: string; members: string[] }
+export type DemoSession = {
+ id: string
+ title: string
+ owner: string
+ messages: { role: 'user' | 'assistant'; text: string }[]
+}
+export function useCollections() {
+ const [learning, setLearning] = useState(() => readDemo('learning-records', initialLearning))
+ const [partners, setPartners] = useState<DemoPartner[]>(() =>
+ readDemo('partners', [
+ {
+ id: 'saturday',
+ name: 'Saturday',
+ description: '一起研究、整理想法,推进你的每一天。',
+ color: '#7a8d75',
+ },
+ {
+ id: 'socrates',
+ name: 'Socrates',
+ description: '通过追问,帮你把一个问题想明白。',
+ color: '#b38d73',
+ },
+ ])
+ )
+ const [groups, setGroups] = useState<DemoGroup[]>(() =>
+ readDemo('partner-groups', [
+ { id: 'research', name: '研究讨论室', members: ['saturday', 'socrates'] },
+ ])
+ )
+ const [sessions, setSessions] = useState<DemoSession[]>(() =>
+ readDemo('partner-sessions', [
+ {
+ id: 'session-one',
+ title: '梳理本周的研究方向',
+ owner: 'saturday',
+ messages: [
+ {
+ role: 'assistant',
+ text: '这是一段示例会话。可以继续讨论研究问题,或打开右上角的伙伴配置。',
+ },
+ ],
+ },
+ {
+ id: 'session-two',
+ title: '关于学习反馈的讨论',
+ owner: 'research',
+ messages: [
+ {
+ role: 'assistant',
+ text: '这是研究讨论室的示例记录。Saturday 和 Socrates 将从不同的角度参与讨论。',
+ },
+ ],
+ },
+ ])
+ )
+ useEffect(() => writeDemo('learning-records', learning), [learning])
+ useEffect(() => writeDemo('partners', partners), [partners])
+ useEffect(() => writeDemo('partner-groups', groups), [groups])
+ useEffect(() => writeDemo('partner-sessions', sessions), [sessions])
+ const records = learning.map(record => {
+ if (record.id === 'attention')
+ return {
+ ...record,
+ detail: `机器学习 · 第 ${readDemo('position', { locator: 1 }).locator} / 3 节`,
+ }
+ if (record.id === 'linear')
+ return {
+ ...record,
+ detail: `6 个目标 · 已完成 ${readDemo<{ isCorrect?: boolean } | null>('grade', null)?.isCorrect ? 3 : 2} 个`,
+ }
+ if (record.id === 'practice' && readDemo('practice-practice', null))
+ return { ...record, detail: '练习 · 本轮已完成' }
+ return record
+ })
+ return {
+ learning: records,
+ setLearning,
+ partners,
+ setPartners,
+ groups,
+ setGroups,
+ sessions,
+ setSessions,
+ }
+}
+export type Collections = ReturnType<typeof useCollections>
diff --git a/web/features/preview/demo-transport.ts b/web/features/preview/demo-transport.ts
new file mode 100644
index 000000000..7aefa9b42
--- /dev/null
+++ b/web/features/preview/demo-transport.ts
@@ -0,0 +1,219 @@
+/** Browser-only fixtures for /preview. No request on this route reaches a backend.
+ * Existing reader/editor/composer APIs remain unchanged. Local writes use their
+ * own preview namespace; navigating away restores normal fetch behavior.
+ */
+import { browserStorage } from '@/shared/storage'
+import { initialDocument, material, readingUnits } from './fixtures'
+import { DEFAULT_TASK_COLORS, type TaskBoard } from '@/lib/task-board-api'
+import type { AnnotationItem } from '@/lib/reading-api'
+
+const PREFIX = 'deeptutor.dito-preview.v1.'
+export function readDemo<T>(key: string, fallback: T): T {
+ try {
+ return JSON.parse(browserStorage.readRaw('local', PREFIX + key) || 'null') ?? fallback
+ } catch {
+ return fallback
+ }
+}
+export function writeDemo(key: string, value: unknown) {
+ try {
+ browserStorage.writeRaw('local', PREFIX + key, JSON.stringify(value))
+ window.dispatchEvent(new CustomEvent('dito-preview-data', { detail: key }))
+ } catch {
+ /* Memory-only preview if storage is unavailable. */
+ }
+}
+const json = (value: unknown, status = 200) =>
+ new Response(JSON.stringify(value), { status, headers: { 'Content-Type': 'application/json' } })
+let installed = false
+
+export function installDemoTransport() {
+ if (typeof window === 'undefined' || installed) return
+ installed = true
+ const realFetch = window.fetch.bind(window)
+ window.fetch = async (input, init) => {
+ const url = new URL(input instanceof Request ? input.url : String(input), location.href)
+ if (location.pathname !== '/preview' || !url.pathname.startsWith('/api/'))
+ return realFetch(input, init)
+ const path = url.pathname
+ const method = init?.method || (input instanceof Request ? input.method : 'GET')
+ const rawBody =
+ init?.body ??
+ (input instanceof Request && method !== 'GET' ? await input.clone().text() : undefined)
+ const body = typeof rawBody === 'string' ? JSON.parse(rawBody || '{}') : {}
+ if (path.startsWith('/api/task-board')) {
+ const board = readDemo<TaskBoard>('task-board', {
+ cards: [
+ {
+ id: 'task-1',
+ title: '整理注意力机制的阅读笔记',
+ note: '从 Query、Key、Value 三个角色开始。',
+ status: 'doing',
+ archived: false,
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ workspace_id: null,
+ },
+ {
+ id: 'task-2',
+ title: '完成线性代数巩固练习',
+ note: '',
+ status: 'todo',
+ archived: false,
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ workspace_id: null,
+ },
+ ],
+ colors: DEFAULT_TASK_COLORS,
+ session_links: [],
+ revision: 0,
+ })
+ if (method === 'POST' && path.endsWith('/cards'))
+ board.cards.push({
+ id: crypto.randomUUID(),
+ title: String(body.title),
+ note: '',
+ status: 'todo',
+ archived: false,
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ workspace_id: null,
+ })
+ if (method === 'PATCH')
+ board.cards = board.cards.map(card =>
+ card.id === path.split('/').pop()
+ ? { ...card, ...body, updated_at: new Date().toISOString() }
+ : card
+ )
+ if (method === 'PUT' && path.endsWith('/colors')) board.colors = body.colors
+ if (method !== 'GET') {
+ board.revision++
+ writeDemo('task-board', board)
+ }
+ return json(board)
+ }
+ if (path === '/api/subagents/detect') return json({ backends: [] })
+ if (path === '/api/imports/chat-history') return json({ sessions: [] })
+ if (path === '/api/capabilities/registered') return json({ capabilities: [] })
+ if (path === '/api/skills/list') return json({ skills: [] })
+ if (path === '/api/space/cli-apps/apps')
+ return json({ apps: [], access: { unrestricted: false, exec_denied: true } })
+ if (path.startsWith('/api/space/mcp')) return json({ servers: {}, user: null })
+ if (path === '/api/settings/ui') return json({ language: 'zh', response_language: 'zh' })
+ if (path === '/api/auth/status')
+ return json({ enabled: false, authenticated: true, user_id: 'dito-preview' })
+ if (path === '/api/settings/workspace/registrations') return json({ workspaces: [] })
+ if (path === '/api/settings/llm-options')
+ return json({
+ active: { profile_id: 'preview', model_id: 'demo' },
+ options: [
+ {
+ profile_id: 'preview',
+ model_id: 'demo',
+ model: '示例模型',
+ model_name: '演示模型',
+ profile_name: '本地预览',
+ provider: 'demo',
+ is_active_default: true,
+ },
+ ],
+ })
+ if (path === '/api/knowledge-bases/list') return json([])
+ if (path === '/api/subagents/settings') return json({ backends: {}, default_consult_budget: 3 })
+ if (path === '/api/subagents/connections') return json({ connections: [] })
+ if (path === '/api/settings/chat-attachments')
+ return json({ max_files: 10, max_file_size_mb: 20, max_total_size_mb: 50 })
+ if (path === '/api/notebooks') return json({ notebooks: [] })
+ if (path === '/api/reading/extensions') return json([])
+ if (path.startsWith('/api/reading/materials/preview-attention')) {
+ const suffix = path.replace('/api/reading/materials/preview-attention', '')
+ if (!suffix) return json(material)
+ if (suffix.startsWith('/units/')) {
+ const locator = Number(suffix.split('/').pop())
+ return json({ locator, unit: 'section', text: readingUnits[locator - 1] || '' })
+ }
+ if (suffix === '/media') return json([])
+ if (suffix === '/position') {
+ const previous = readDemo('position', {
+ locator: 1,
+ source_anchor: '',
+ percentage: 0,
+ updated_at: 0,
+ })
+ const position =
+ method === 'PUT' ? { ...previous, ...body, updated_at: Date.now() / 1000 } : previous
+ if (method === 'PUT') writeDemo('position', position)
+ return json(position)
+ }
+ if (suffix.startsWith('/annotations')) {
+ let marks = readDemo<AnnotationItem[]>('annotations', [])
+ if (method === 'PUT') {
+ const mark = {
+ ...body,
+ annotation_id: body.annotation_id || crypto.randomUUID(),
+ author: 'user',
+ created_at: Date.now() / 1000,
+ updated_at: Date.now() / 1000,
+ rects: body.rects || [],
+ source_anchor: body.source_anchor || '',
+ note: body.note || '',
+ } as AnnotationItem
+ marks = [...marks.filter(m => m.annotation_id !== mark.annotation_id), mark]
+ writeDemo('annotations', marks)
+ return json(mark)
+ }
+ if (method === 'DELETE') {
+ writeDemo(
+ 'annotations',
+ marks.filter(m => m.annotation_id !== suffix.split('/').pop())
+ )
+ return json({ deleted: true })
+ }
+ return json(marks)
+ }
+ if (suffix === '/export')
+ return new Response(readingUnits.join('\n\n---\n\n'), {
+ headers: {
+ 'Content-Type': 'text/markdown',
+ 'Content-Disposition': 'attachment; filename="attention-notes.md"',
+ },
+ })
+ if (suffix === '/quiz/rewards') return json({ rewards: [], total_stars: 0 })
+ if (suffix === '/bookmarks') return json({ bookmarks: [] })
+ }
+ if (path === '/api/documents/preview-research') {
+ const doc = readDemo('document', initialDocument)
+ const updated =
+ method === 'PUT'
+ ? {
+ ...doc,
+ ...Object.fromEntries(Object.entries(body).filter(([, v]) => v !== null)),
+ updated_at: Date.now() / 1000,
+ }
+ : doc
+ if (method === 'PUT') writeDemo('document', updated)
+ return json(updated)
+ }
+ if (path.startsWith('/api/documents/actions/')) {
+ // Do not fake LLM edits: existing UI surfaces this actionable response.
+ return json(
+ { detail: '此预览未连接模型。可以直接编辑文稿,或在 Dito 侧栏体验示例对话。' },
+ 501
+ )
+ }
+ if (path === '/api/documents/export/docx')
+ return json({ detail: 'Word 导出需要后端;此预览可以编辑和自动保存文稿。' }, 501)
+ if (method === 'GET' && /personas|memory|sessions|question-notebook|books/.test(path))
+ return json({
+ items: [],
+ sessions: [],
+ personas: [],
+ entries: [],
+ total: 0,
+ books: [],
+ files: [],
+ })
+ return json({ detail: '此功能需要后端服务,当前是前端交互预览。' }, 501)
+ }
+}
diff --git a/web/features/preview/fixtures.ts b/web/features/preview/fixtures.ts
new file mode 100644
index 000000000..0ddb9f250
--- /dev/null
+++ b/web/features/preview/fixtures.ts
@@ -0,0 +1,175 @@
+import type { MaterialDetail } from '@/lib/reading-api'
+import type { MasteryQuestion } from '@/lib/mastery-question'
+
+export type PreviewView =
+ | 'home'
+ | 'learning'
+ | 'library'
+ | 'reading'
+ | 'writing'
+ | 'mastery'
+ | 'chat'
+ | 'partners'
+ | 'kanban'
+ | 'agents'
+ | 'resource'
+ | 'record'
+export const previewItems: {
+ id: string
+ title: string
+ kind: string
+ view: PreviewView
+ detail: string
+ progress?: number
+}[] = [
+ {
+ id: 'attention',
+ title: '理解 Transformer 的注意力机制',
+ kind: '沉浸式阅读',
+ view: 'reading',
+ detail: '机器学习 · 第 1 / 3 节',
+ progress: 0.33,
+ },
+ {
+ id: 'linear',
+ title: '线性代数,从直觉出发',
+ kind: '引导式学习',
+ view: 'mastery',
+ detail: '6 个学习目标 · 已完成 2 个',
+ progress: 0.33,
+ },
+ {
+ id: 'research',
+ title: '我的研究计划',
+ kind: 'Co-Writer',
+ view: 'writing',
+ detail: '研究笔记 · 今天编辑',
+ },
+ {
+ id: 'chat',
+ title: '与 Dito 对话',
+ kind: '对话',
+ view: 'chat',
+ detail: '通用助手 · Auto 模式',
+ },
+]
+
+export const readingUnits = [
+ `# 理解 Transformer 的注意力机制
+
+> 学习笔记 · 从一个句子开始理解注意力
+
+## 01 为什么需要注意力?
+
+读到「小猫没有跨过围栏,因为它太高了」,你会自然地知道「它」指的是围栏。我们理解一个词时,会回看句子中与它相关的部分。
+
+注意力机制做的就是类似的事:让每一个词主动寻找与自己相关的信息,并决定应该关注多少。
+
+## 把句子想成一次讨论
+
+每个词都有三个角色:
+
+- **Query(查询)**:我现在需要什么信息?
+- **Key(键)**:我能提供哪一类信息?
+- **Value(值)**:我实际携带的信息是什么?
+
+Query 与每个 Key 的匹配程度决定关注的权重,再用这些权重对 Value 加权求和。
+
+## 核心公式
+
+$$\\operatorname{Attention}(Q,K,V)=\\operatorname{softmax}\\left(\\frac{QK^T}{\\sqrt{d_k}}\\right)V$$
+
+先匹配,再归一化,最后汇总。把这三步记住,就抓住了注意力机制的主线。
+
+**边读边想**:如果所有词的匹配分数都一样,最后得到的输出会是什么?
+
+你可以选中一句话做批注,也可以直接向右侧的 Dito 提问。`,
+ `# 从匹配分数到注意力权重
+
+## 02 缩放与归一化
+
+Query 和 Key 的点积是匹配分数。当向量的维数变大时,点积的波动也会增大。直接放进 softmax 容易让权重过于集中。
+
+因此我们除以维数的平方根,让分数处于更稳定的范围。
+
+## 一个小例子
+
+假设匹配分数是 2、1、0,经过 softmax 后,权重大约是 0.665、0.245、0.090。
+
+最匹配的词贡献最多,但其他词的信息仍然保留。
+
+## 试着解释
+
+请用自己的话解释:为什么不能直接用原始的点积作为加权系数?`,
+ `# 多头注意力:从不同角度理解
+
+## 03 不同的问题,不同的关注点
+
+同一句话里,一个头可能关注语法依赖,另一个头可能关注语义关系。它们各自在投影后的空间里计算注意力,再把结果组合起来。
+
+## 回顾这条主线
+
+1. 一个词用 Query 表达需求。
+2. 用 Key 匹配其他位置。
+3. 对分数缩放、归一化。
+4. 汇总 Value,得到新的表示。
+
+**下一步**:做一道小练习,看看你能不能把这个过程解释清楚。`,
+]
+
+export const material: MaterialDetail = {
+ material_id: 'preview-attention',
+ filename: 'attention-notes.md',
+ title: previewItems[0].title,
+ unit: 'section',
+ unit_count: 3,
+ mime: 'text/markdown',
+ byte_size: 2400,
+ char_count: 1200,
+ created_at: 1791792000,
+ has_raw_view: false,
+ render_mode: 'text',
+ content_format: 'web_markdown',
+ extractor: 'preview',
+ annotation_count: 0,
+ revision: 1,
+ outline: ['为什么需要注意力?', '缩放与归一化', '多头注意力'].map((title, i) => ({
+ locator: i + 1,
+ title,
+ level: 1,
+ synthesised: false,
+ })),
+ outline_text: '',
+ unit_refs: [],
+}
+
+export const initialDocument = {
+ id: 'preview-research',
+ title: '我的研究计划',
+ created_at: 1791792000,
+ updated_at: 1791792000,
+ content: `# 我的研究计划\n\n## 研究问题\n\n如何帮助学习者把零散的知识,转变成能够解释和应用的理解?\n\n## 初步想法\n\n从阅读一篇材料开始,在关键位置记录疑问,再通过针对性的练习确认理解。让阅读、笔记与练习围绕同一个学习目标展开。\n\n## 本周安排\n\n- [x] 整理注意力机制的阅读笔记\n- [ ] 比较三种学习反馈方式\n- [ ] 完成第一版实验设计\n\n## 需要继续探索\n\n1. 怎样发现学习者真正没理解的地方?\n2. 怎样安排复习,而不打断学习节奏?\n3. 怎样让助手的建议保留足够的自主选择?\n`,
+}
+
+export const objectives = [
+ '向量与线性组合',
+ '矩阵作为一种变换',
+ '线性无关与基',
+ '特征值与特征向量',
+ '正交投影',
+ '把直觉用在实际问题里',
+]
+export const question: MasteryQuestion = {
+ questionId: 'preview-basis',
+ prompt: '在二维平面中,哪一组向量可以构成一组基?',
+ questionType: 'multiple_choice',
+ objectiveName: '线性无关与基',
+ difficulty: 'easy',
+ attempt: 1,
+ allowFreeText: false,
+ options: [
+ { label: 'A', body: '(1, 0) 和 (2, 0)' },
+ { label: 'B', body: '(1, 0) 和 (0, 1)' },
+ { label: 'C', body: '(0, 0) 和 (1, 1)' },
+ ],
+}
diff --git a/web/features/tasks/components/KanbanBoard.tsx b/web/features/tasks/components/KanbanBoard.tsx
new file mode 100644
index 000000000..be2f2fdb0
--- /dev/null
+++ b/web/features/tasks/components/KanbanBoard.tsx
@@ -0,0 +1,417 @@
+'use client'
+
+import { FeaturePage, pageGridClass } from '@/components/layout/FeaturePage'
+import { useRef, useState } from 'react'
+import {
+ Archive,
+ ArrowLeft,
+ ArrowRight,
+ Check,
+ ChevronDown,
+ CircleCheck,
+ CircleDashed,
+ CircleDot,
+ Folder,
+ Plus,
+ RotateCcw,
+ X,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import SpaceSectionHeader from '@/components/space/SpaceSectionHeader'
+import Tooltip from '@/shared/ui/Tooltip'
+import TaskColorPicker from '@/components/tasks/TaskColorPicker'
+
+import {
+ createTaskCard,
+ updateTaskColors,
+ DEFAULT_TASK_COLORS,
+ updateTaskCard,
+ type TaskBoard,
+ type TaskCard,
+ type TaskStatus,
+} from '@/lib/task-board-api'
+
+import { useTaskBoard, refreshTaskBoard } from '@/lib/task-board-store'
+import { useChatWorkspaces } from '@/hooks/useChatWorkspaces'
+
+const columns = [
+ { id: 'todo', title: 'kanban.todo', hint: 'kanban.todoHint', icon: CircleDashed },
+ { id: 'doing', title: 'kanban.doing', hint: 'kanban.doingHint', icon: CircleDot },
+ { id: 'done', title: 'kanban.done', hint: 'kanban.doneHint', icon: CircleCheck },
+] as const
+
+export default function KanbanBoard() {
+ const { t } = useTranslation()
+ const { board, error: loadError } = useTaskBoard()
+ const { workspaces } = useChatWorkspaces()
+ const [title, setTitle] = useState('')
+ const [editing, setEditing] = useState<string | null>(null)
+ const [draftTitle, setDraftTitle] = useState('')
+ const [draftNote, setDraftNote] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const [dragged, setDragged] = useState<string | null>(null)
+ const [dropTarget, setDropTarget] = useState<TaskStatus | null>(null)
+
+ const pending = useRef(false)
+ const [showArchived, setShowArchived] = useState(false)
+ async function act(operation: () => Promise<TaskBoard>, onSuccess?: () => void) {
+ if (pending.current || !board) return
+ pending.current = true
+ setBusy(true)
+ setError('')
+ try {
+ await operation()
+ onSuccess?.()
+ } catch {
+ setError('kanban.saveError')
+ } finally {
+ pending.current = false
+ setBusy(false)
+ }
+ }
+
+ function startEdit(card: TaskCard) {
+ setEditing(card.id)
+ setDraftTitle(card.title)
+ setDraftNote(card.note)
+ }
+
+ const active = board?.cards.filter(card => !card.archived) ?? []
+ const visible = board?.cards.filter(card => card.archived === showArchived) ?? []
+ const count = (status: TaskStatus) => visible.filter(card => card.status === status).length
+
+ return (
+ <FeaturePage>
+ <SpaceSectionHeader
+ title={t('Task Board')}
+ description={t('kanban.intro')}
+ action={
+ <div className="flex items-center gap-1">
+ <TaskColorPicker
+ colors={board?.colors ?? DEFAULT_TASK_COLORS}
+ disabled={!board}
+ busy={busy}
+ error={error ? t(error) : undefined}
+ onSave={(colors, onSuccess) => void act(() => updateTaskColors(colors), onSuccess)}
+ />
+ <button
+ type="button"
+ aria-pressed={showArchived}
+ disabled={busy}
+ onClick={() => {
+ setShowArchived(value => !value)
+ setEditing(null)
+ }}
+ className={`inline-flex h-9 items-center gap-2 rounded-lg px-3 text-[13px] font-medium transition-colors disabled:opacity-40 ${showArchived ? 'bg-muted text-foreground' : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground'}`}
+ >
+ <Archive size={15} strokeWidth={1.7} />
+ {t(showArchived ? 'kanban.showActive' : 'kanban.showArchived')}
+ </button>
+ </div>
+ }
+ meta={
+ <span className="rounded-md bg-muted/65 px-2 py-0.5 font-sans text-[11px] font-medium text-muted-foreground">
+ {active.filter(card => card.status === 'doing').length} {t('kanban.working')}
+ </span>
+ }
+ />
+
+ <form
+ className="mb-6 flex items-center gap-2 rounded-xl border border-border/80 bg-card p-1.5 transition-[border-color,box-shadow] focus-within:border-primary/40 focus-within:ring-[3px] focus-within:ring-primary/5"
+ onSubmit={event => {
+ event.preventDefault()
+ if (title.trim())
+ void act(
+ () => createTaskCard(title),
+ () => {
+ setTitle('')
+ setShowArchived(false)
+ }
+ )
+ }}
+ >
+ <input
+ disabled={!board || busy}
+ aria-label={t('kanban.newTask')}
+ className="min-w-0 flex-1 bg-transparent px-3 py-2 text-[13px] outline-none placeholder:text-muted-foreground/75 focus-visible:outline-none"
+ placeholder={t('kanban.placeholder')}
+ maxLength={160}
+ value={title}
+ onChange={event => setTitle(event.target.value)}
+ />
+ <button
+ disabled={busy || !board || !title.trim()}
+ className="flex shrink-0 items-center gap-1.5 rounded-lg bg-primary px-3.5 py-2 text-[13px] font-medium text-primary-foreground transition-colors hover:opacity-90 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-60"
+ type="submit"
+ >
+ <Plus size={15} strokeWidth={1.8} /> {t('kanban.add')}
+ </button>
+ </form>
+ {!board && !error && !loadError && (
+ <p role="status" className="mb-5 text-sm text-muted-foreground">
+ {t('kanban.loading')}
+ </p>
+ )}
+ {(error || loadError) && (
+ <p role="alert" className="mb-5 rounded-xl bg-secondary p-3 text-sm text-destructive">
+ {t(error || 'kanban.loadError')}
+ {!board && (
+ <button
+ type="button"
+ className="ml-3 underline"
+ onClick={() => {
+ setError('')
+ void refreshTaskBoard()
+ }}
+ >
+ {t('kanban.retry')}
+ </button>
+ )}
+ </p>
+ )}
+
+ <div aria-busy={busy || !board} className={pageGridClass('board')}>
+ {columns.map((column, index) => (
+ <section
+ key={column.id}
+ aria-label={t(column.title)}
+ onDragOver={event => {
+ event.preventDefault()
+ if (dragged && !showArchived) setDropTarget(column.id)
+ }}
+ onDragLeave={event => {
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null))
+ setDropTarget(null)
+ }}
+ onDrop={event => {
+ event.preventDefault()
+ if (dragged && !showArchived)
+ void act(() => updateTaskCard(dragged, { status: column.id }))
+ setDragged(null)
+ setDropTarget(null)
+ }}
+ className={`min-h-[12rem] rounded-2xl border p-3 transition-colors sm:p-3.5 lg:min-h-[24rem] ${dropTarget === column.id ? 'border-primary/35 bg-primary/5 ring-2 ring-primary/10' : 'border-border/45 bg-secondary/65'}`}
+ >
+ <div className="mb-3 flex items-center justify-between px-1 py-1.5">
+ <div className="flex items-start gap-2.5">
+ <span
+ className="mt-1.5 h-2 w-2 shrink-0 rounded-full"
+ style={{
+ backgroundColor: board?.colors[column.id] ?? DEFAULT_TASK_COLORS[column.id],
+ }}
+ />
+ <div>
+ <h2 className="text-[13px] font-semibold leading-5">{t(column.title)}</h2>
+ <p className="mt-0.5 text-[11px] leading-4 text-muted-foreground">
+ {t(column.hint)}
+ </p>
+ </div>
+ </div>
+ <span className="self-start px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-muted-foreground">
+ {count(column.id)}
+ </span>
+ </div>
+ <div className="space-y-2.5">
+ {visible
+ .filter(card => card.status === column.id)
+ .map(card => (
+ <article
+ key={card.id}
+ draggable={!busy && !showArchived && editing !== card.id}
+ onDragStart={event => {
+ event.dataTransfer.setData('text/plain', card.id)
+ event.dataTransfer.effectAllowed = 'move'
+ setDragged(card.id)
+ }}
+ onDragEnd={() => {
+ setDragged(null)
+ setDropTarget(null)
+ }}
+ className={`group/kanban-card rounded-xl border border-border/75 bg-card px-3.5 py-3 shadow-[0_1px_2px_rgba(0,0,0,0.025)] transition-[border-color,box-shadow,opacity] hover:border-border hover:shadow-[0_2px_8px_rgba(0,0,0,0.045)] ${dragged === card.id ? 'opacity-45' : ''}`}
+ >
+ {editing === card.id ? (
+ <form
+ onSubmit={event => {
+ event.preventDefault()
+ if (draftTitle.trim())
+ void act(
+ () =>
+ updateTaskCard(card.id, { title: draftTitle, note: draftNote }),
+ () => setEditing(null)
+ )
+ }}
+ >
+ <input
+ aria-label={t('kanban.taskTitle')}
+ className="w-full rounded-lg border border-border bg-background px-2.5 py-2 text-[13px] font-medium text-foreground focus:border-primary/40 focus:outline-none focus:ring-2 focus:ring-primary/10"
+ maxLength={160}
+ value={draftTitle}
+ onChange={event => setDraftTitle(event.target.value)}
+ />
+ <textarea
+ aria-label={t('kanban.taskNote')}
+ className="mt-2 w-full resize-y rounded-lg border border-border bg-background px-2.5 py-2 text-xs leading-5 text-foreground focus:border-primary/40 focus:outline-none focus:ring-2 focus:ring-primary/10"
+ placeholder={t('kanban.notePlaceholder')}
+ rows={3}
+ maxLength={2000}
+ value={draftNote}
+ onChange={event => setDraftNote(event.target.value)}
+ />
+ <div className="mt-2 flex gap-2">
+ <button
+ disabled={busy || !draftTitle.trim()}
+ className="flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-xs font-semibold text-primary-foreground disabled:opacity-40"
+ type="submit"
+ >
+ <Check size={14} /> {t('kanban.save')}
+ </button>
+ <button
+ className="flex items-center gap-1 rounded-lg px-2 py-1.5 text-xs text-muted-foreground"
+ type="button"
+ onClick={() => setEditing(null)}
+ >
+ <X size={14} /> {t('kanban.cancel')}
+ </button>
+ </div>
+ </form>
+ ) : (
+ <div className="relative">
+ <button
+ type="button"
+ aria-label={card.title}
+ disabled={busy}
+ className="block w-full text-left"
+ onClick={() => startEdit(card)}
+ >
+ <strong className="block break-words text-[13px] font-medium leading-6">
+ {card.title}
+ </strong>
+ {card.note && (
+ <p className="mt-1.5 whitespace-pre-wrap break-words text-xs leading-5 text-muted-foreground">
+ {card.note}
+ </p>
+ )}
+ </button>
+ <label className="relative mt-3 inline-flex max-w-full items-center gap-1.5 rounded-md bg-muted/50 px-2 py-1 text-[11px] leading-4 text-muted-foreground transition-colors hover:bg-muted focus-within:ring-2 focus-within:ring-ring/40">
+ <Folder aria-hidden size={11} strokeWidth={1.7} className="shrink-0" />
+ <span className="truncate">
+ {card.workspace_id === null
+ ? t('tasks.unassigned')
+ : card.workspace_id === ''
+ ? t('General workspace')
+ : (workspaces.find(row => row.workspace_id === card.workspace_id)
+ ?.display_name ?? t('tasks.assign'))}
+ </span>
+ <ChevronDown
+ aria-hidden
+ size={11}
+ strokeWidth={1.7}
+ className="shrink-0 opacity-60"
+ />
+ <select
+ aria-label={`${card.title}: ${t('tasks.assign')}`}
+ disabled={busy}
+ value={card.workspace_id ?? '__unassigned__'}
+ onChange={event =>
+ void act(() =>
+ updateTaskCard(card.id, {
+ workspace_id:
+ event.target.value === '__unassigned__'
+ ? null
+ : event.target.value,
+ })
+ )
+ }
+ className="absolute inset-0 h-full w-full cursor-pointer opacity-0 disabled:cursor-default"
+ >
+ <option value="__unassigned__">{t('tasks.unassigned')}</option>
+ <option value="">{t('General workspace')}</option>
+ {workspaces
+ .filter(row => row.kind === 'workspace')
+ .map(row => (
+ <option
+ key={row.workspace_id}
+ value={row.workspace_id}
+ disabled={row.archived || row.status !== 'ready'}
+ >
+ {row.display_name}
+ </option>
+ ))}
+ </select>
+ </label>
+ <div className="pointer-events-none absolute -right-0.5 -top-0.5 flex items-center gap-0.5 rounded-r-md bg-gradient-to-l from-popover from-80% to-transparent pl-4 opacity-0 transition-opacity duration-150 group-hover/kanban-card:pointer-events-auto group-hover/kanban-card:opacity-100 group-has-[:focus-visible]/kanban-card:pointer-events-auto group-has-[:focus-visible]/kanban-card:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
+ {!showArchived && index > 0 && (
+ <Tooltip label={t('kanban.back')}>
+ <button
+ disabled={busy}
+ aria-label={`${card.title}: ${t('kanban.moveTo')} ${t(columns[index - 1].title)}`}
+ className="rounded-lg p-1.5 text-muted-foreground hover:bg-accent"
+ onClick={() =>
+ void act(() =>
+ updateTaskCard(card.id, { status: columns[index - 1].id })
+ )
+ }
+ >
+ <ArrowLeft size={16} />
+ </button>
+ </Tooltip>
+ )}
+ {!showArchived && index < 2 && (
+ <Tooltip label={t('kanban.forward')}>
+ <button
+ disabled={busy}
+ aria-label={`${card.title}: ${t('kanban.moveTo')} ${t(columns[index + 1].title)}`}
+ className="rounded-lg p-1.5 text-muted-foreground hover:bg-accent"
+ onClick={() =>
+ void act(() =>
+ updateTaskCard(card.id, { status: columns[index + 1].id })
+ )
+ }
+ >
+ <ArrowRight size={16} />
+ </button>
+ </Tooltip>
+ )}
+ <Tooltip label={t(card.archived ? 'kanban.restore' : 'kanban.archive')}>
+ <button
+ disabled={busy}
+ aria-label={`${card.title}: ${t(card.archived ? 'kanban.restore' : 'kanban.archive')}`}
+ className="rounded-lg p-1.5 text-muted-foreground hover:bg-accent"
+ onClick={() =>
+ void act(() =>
+ updateTaskCard(card.id, { archived: !card.archived })
+ )
+ }
+ >
+ {card.archived ? <RotateCcw size={15} /> : <Archive size={15} />}
+ </button>
+ </Tooltip>
+ </div>
+ </div>
+ )}
+ </article>
+ ))}
+ {board && count(column.id) === 0 && (
+ <div className="flex min-h-28 flex-col items-center justify-center gap-2.5 rounded-xl border border-dashed border-border/65 px-4 py-6 text-center">
+ <column.icon
+ aria-hidden
+ size={20}
+ strokeWidth={1.3}
+ className="text-muted-foreground/40"
+ />
+ <p className="text-[11px] text-muted-foreground">
+ {t(showArchived ? 'kanban.emptyArchive' : 'kanban.empty')}
+ </p>
+ </div>
+ )}
+ </div>
+ </section>
+ ))}
+ </div>
+ <p className="mt-5 px-1 text-[11px] leading-5 text-muted-foreground">
+ {t('kanban.footer')}
+ </p>
+ </FeaturePage>
+ )
+}
diff --git a/web/hooks/useLearningIndex.ts b/web/hooks/useLearningIndex.ts
new file mode 100644
index 000000000..0d5c38ae5
--- /dev/null
+++ b/web/hooks/useLearningIndex.ts
@@ -0,0 +1,74 @@
+'use client'
+
+import { useCallback, useEffect, useState } from 'react'
+import { usePathname } from 'next/navigation'
+import { apiFetch, apiUrl } from '@/lib/api'
+import { scopedUrl } from '@/lib/workspace-scope'
+import { subscribeSessionChanges } from '@/lib/session-events'
+import type { LearningKind, LearningSources } from '@/lib/learning-dashboard'
+
+const EMPTY: LearningSources = { books: [], mastery: [], reading: [], watching: [], practice: [] }
+export function useLearningIndex(enabled = true) {
+ const pathname = usePathname()
+ const [sources, setSources] = useState<LearningSources>(EMPTY)
+ const [failed, setFailed] = useState<LearningKind[]>([])
+ const [loading, setLoading] = useState(true)
+ const [revision, setRevision] = useState(0)
+ const retry = useCallback(() => setRevision(value => value + 1), [])
+ useEffect(() => {
+ if (!enabled) return
+ let alive = true
+ let busy = false
+ const controller = new AbortController()
+ const refresh = async () => {
+ if (busy || document.visibilityState === 'hidden') return
+ busy = true
+ try {
+ const response = await apiFetch(apiUrl(scopedUrl('/api/dashboard/learning-index', '')), {
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(20000)]),
+ })
+ if (!response.ok) throw new Error('Learning index unavailable')
+ const payload = (await response.json()) as {
+ sources: LearningSources
+ failed: LearningKind[]
+ }
+ if (alive) {
+ // Keep readable collections during a transient partial outage.
+ setSources(
+ previous =>
+ Object.fromEntries(
+ Object.keys(EMPTY).map(key => {
+ const kind = key as LearningKind
+ const rows = payload.sources[kind] ?? []
+ return [
+ kind,
+ payload.failed.includes(kind) && !rows.length ? previous[kind] : rows,
+ ]
+ })
+ ) as unknown as LearningSources
+ )
+ setFailed(payload.failed)
+ }
+ } catch {
+ if (alive) setFailed(Object.keys(EMPTY) as LearningKind[])
+ } finally {
+ if (alive) setLoading(false)
+ busy = false
+ }
+ }
+ void refresh()
+ const unsubscribe = subscribeSessionChanges(() => void refresh())
+ window.addEventListener('focus', refresh)
+ document.addEventListener('visibilitychange', refresh)
+ const timer = window.setInterval(refresh, 30000)
+ return () => {
+ alive = false
+ controller.abort()
+ unsubscribe()
+ window.clearInterval(timer)
+ window.removeEventListener('focus', refresh)
+ document.removeEventListener('visibilitychange', refresh)
+ }
+ }, [enabled, pathname, revision])
+ return { sources, failed, loading, retry }
+}
diff --git a/web/hooks/usePartnerNavigation.ts b/web/hooks/usePartnerNavigation.ts
new file mode 100644
index 000000000..0a90e04cd
--- /dev/null
+++ b/web/hooks/usePartnerNavigation.ts
@@ -0,0 +1,77 @@
+'use client'
+import { useCallback, useEffect, useState } from 'react'
+import { usePathname } from 'next/navigation'
+import { apiFetch, apiUrl } from '@/lib/api'
+import { subscribeSessionChanges } from '@/lib/session-events'
+import type { PartnerInfo } from '@/lib/partners-api'
+import type { PartnerGroup } from '@/lib/partner-groups-api'
+export interface PartnerNavigationSession {
+ kind: 'partner' | 'group'
+ owner_id: string
+ owner_name: string
+ session_key: string
+ title: string
+ updated_at: number
+}
+export interface PartnerNavigationData {
+ partners: Pick<
+ PartnerInfo,
+ 'partner_id' | 'name' | 'description' | 'emoji' | 'avatar' | 'color' | 'running' | 'can_manage'
+ >[]
+ groups: PartnerGroup[]
+ sessions: PartnerNavigationSession[]
+ unavailable: string[]
+}
+export function usePartnerNavigation(enabled: boolean) {
+ const pathname = usePathname()
+ const [data, setData] = useState<PartnerNavigationData>({
+ partners: [],
+ groups: [],
+ sessions: [],
+ unavailable: [],
+ })
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState(false)
+ const [revision, setRevision] = useState(0)
+ const retry = useCallback(() => setRevision(value => value + 1), [])
+ useEffect(() => {
+ if (!enabled) return
+ let alive = true
+ let busy = false
+ const controller = new AbortController()
+ const refresh = async () => {
+ if (busy || document.visibilityState === 'hidden') return
+ busy = true
+ try {
+ const response = await apiFetch(apiUrl('/api/partners/navigation'), {
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(20000)]),
+ })
+ if (!response.ok) throw new Error('Partner navigation unavailable')
+ const next = (await response.json()) as PartnerNavigationData
+ if (alive) {
+ setData(next)
+ setError(false)
+ }
+ } catch {
+ if (alive) setError(true)
+ } finally {
+ busy = false
+ if (alive) setLoading(false)
+ }
+ }
+ void refresh()
+ const unsubscribe = subscribeSessionChanges(() => void refresh())
+ const timer = window.setInterval(refresh, 15000)
+ window.addEventListener('focus', refresh)
+ document.addEventListener('visibilitychange', refresh)
+ return () => {
+ alive = false
+ controller.abort()
+ unsubscribe()
+ window.clearInterval(timer)
+ window.removeEventListener('focus', refresh)
+ document.removeEventListener('visibilitychange', refresh)
+ }
+ }, [enabled, pathname, revision])
+ return { data, loading, error, retry }
+}
diff --git a/web/hooks/useSidebarResize.ts b/web/hooks/useSidebarResize.ts
index 541c64d1b..78642cd96 100644
--- a/web/hooks/useSidebarResize.ts
+++ b/web/hooks/useSidebarResize.ts
@@ -18,8 +18,12 @@ function clampWidth(width: number, max: number) {
return Math.round(Math.max(MIN_WIDTH, Math.min(max, width)));
}
-export function useSidebarResize(disabled: boolean) {
- const [preferredWidth, setPreferredWidth] = useState(DEFAULT_WIDTH);
+export function useSidebarResize(
+ disabled: boolean,
+ defaultWidth = DEFAULT_WIDTH,
+ storageKey = WIDTH_KEY,
+) {
+ const [preferredWidth, setPreferredWidth] = useState(defaultWidth);
const [max, setMax] = useState(MAX_WIDTH);
const [resizing, setResizing] = useState(false);
const drag = useRef<{
@@ -30,7 +34,7 @@ export function useSidebarResize(disabled: boolean) {
const width = clampWidth(preferredWidth, max);
useEffect(() => {
- const stored = Number(browserStorage.readRaw("local", WIDTH_KEY));
+ const stored = Number(browserStorage.readRaw("local", storageKey));
if (Number.isFinite(stored) && stored > 0) {
// Hydrate after mount to keep the initial render consistent with SSR.
// eslint-disable-next-line react-hooks/set-state-in-effect
@@ -46,7 +50,7 @@ export function useSidebarResize(disabled: boolean) {
updateBounds();
window.addEventListener("resize", updateBounds);
return () => window.removeEventListener("resize", updateBounds);
- }, []);
+ }, [storageKey]);
useEffect(() => {
if (!resizing || disabled) return;
@@ -62,7 +66,7 @@ export function useSidebarResize(disabled: boolean) {
const saveWidth = (next: number) => {
const bounded = clampWidth(next, max);
setPreferredWidth(bounded);
- browserStorage.writeRaw("local", WIDTH_KEY, String(bounded));
+ browserStorage.writeRaw("local", storageKey, String(bounded));
};
const finishDrag = (event: PointerEvent<HTMLDivElement>) => {
if (drag.current?.pointerId !== event.pointerId) return;
@@ -97,7 +101,7 @@ export function useSidebarResize(disabled: boolean) {
onPointerUp: finishDrag,
onPointerCancel: finishDrag,
onLostPointerCapture: finishDrag,
- onDoubleClick: () => saveWidth(DEFAULT_WIDTH),
+ onDoubleClick: () => saveWidth(defaultWidth),
onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => {
if (disabled) return;
const step = event.shiftKey ? 40 : 10;
diff --git a/web/lib/learning-dashboard.ts b/web/lib/learning-dashboard.ts
index 6aa58dcbd..e2ad741b8 100644
--- a/web/lib/learning-dashboard.ts
+++ b/web/lib/learning-dashboard.ts
@@ -3,15 +3,16 @@ import type { Book } from '@/lib/book-types'
import type { MasteryTopic } from '@/lib/learning-api'
import type { ReadingWorkspace } from '@/lib/reading-workspace-api'
import type { SessionSummary } from '@/lib/session-api'
-import { bookRoute, masteryTopicRoute, readingCollectionRoute } from '@/lib/learning-routes'
+import { bookRoute, masteryTopicRoute, readingCollectionRoute, practiceRoute } from '@/lib/learning-routes'
import { sessionRoute } from '@/lib/mastery-session'
-export type LearningKind = 'books' | 'mastery' | 'reading' | 'watching'
+export type LearningKind = 'books' | 'mastery' | 'reading' | 'watching' | 'practice'
export type Located<T> = T & { content_workspace_id?: string; content_workspace_name?: string }
export interface LearningSources {
books: Located<Book>[]
mastery: Located<MasteryTopic>[]
reading: Located<ReadingWorkspace>[]
+ practice?: Located<{ id: number; question: string; created_at: number; updated_at: number }>[]
watching: SessionSummary[]
}
export interface LearningActivity {
@@ -30,8 +31,16 @@ export function isWatchingSession(session: SessionSummary): boolean {
)
}
/** Every activity across the surfaces, newest first. Archived paths are not work in progress. */
-function allLearningActivity(sources: LearningSources): LearningActivity[] {
+export function allLearningActivity(sources: LearningSources): LearningActivity[] {
return [
+ ...(sources.practice ?? []).map(entry => ({
+ key: `practice:${entry.content_workspace_id || ""}:${entry.id}`,
+ kind: 'practice' as const,
+ title: entry.question,
+ href: scopedUrl(practiceRoute(new URLSearchParams({ question: String(entry.id) }), ""), entry.content_workspace_id || ""),
+ updatedAt: entry.updated_at || entry.created_at,
+ workspaceName: entry.content_workspace_name,
+ })),
...sources.books.map(book => ({
key: `book:${book.content_workspace_id || ""}:${book.id}`,
kind: 'books' as const,
@@ -61,7 +70,7 @@ function allLearningActivity(sources: LearningSources): LearningActivity[] {
workspaceName: workspace.content_workspace_name,
})),
...sources.watching.filter(isWatchingSession).map(session => ({
- key: `session:${session.session_id}`,
+ key: `session:${session.content_workspace_id || ""}:${session.session_id}`,
kind: 'watching' as const,
title: session.title,
href: sessionRoute(session),
@@ -85,6 +94,7 @@ export function learningSurfaceStats(
mastery: { count: 0 },
reading: { count: 0 },
watching: { count: 0 },
+ practice: { count: 0 },
}
// Sorted newest first, so the first activity seen for a kind is its latest.
for (const activity of allLearningActivity(sources)) {
diff --git a/web/lib/navigation.ts b/web/lib/navigation.ts
new file mode 100644
index 000000000..486ee6b60
--- /dev/null
+++ b/web/lib/navigation.ts
@@ -0,0 +1,31 @@
+/** Product grouping only. Existing URLs and persisted records remain authoritative. */
+import type { SessionSummary } from '@/lib/session-api'
+import { sessionRoute } from '@/lib/mastery-session'
+export type NavigationCategory = 'home' | 'partners' | 'learning' | 'resources'
+export function categoryForPath(pathname: string): NavigationCategory {
+ if (pathname === '/partners' || pathname.startsWith('/partners/')) return 'partners'
+ if (
+ pathname === '/learning' ||
+ pathname.startsWith('/learning/') ||
+ pathname.startsWith('/courses')
+ )
+ return 'learning'
+ if (
+ ['/space', '/notebooks', '/knowledge-bases', '/memory'].some(
+ root => pathname === root || pathname.startsWith(`${root}/`)
+ )
+ )
+ return 'resources'
+ return 'home'
+}
+export function isLearningSession(session: SessionSummary): boolean {
+ return categoryForPath(sessionRoute(session).split('?')[0]) === 'learning'
+}
+export function partnerSessionHref(session: {
+ kind: 'partner' | 'group'
+ owner_id: string
+ session_key: string
+}): string {
+ const root = session.kind === 'group' ? '/partners/groups' : '/partners'
+ return `${root}/${encodeURIComponent(session.owner_id)}?${new URLSearchParams({ session: session.session_key })}`
+}
diff --git a/web/lib/task-board-store.ts b/web/lib/task-board-store.ts
index 680173465..d6b5a8a2e 100644
--- a/web/lib/task-board-store.ts
+++ b/web/lib/task-board-store.ts
@@ -47,12 +47,12 @@ export async function refreshTaskBoard() {
}
/** One account-level connection, owned by the workspace shell, outside its scope reset. */
-export function startTaskBoardSync() {
+export function startTaskBoardSync({ stream = true }: { stream?: boolean } = {}) {
if (++owners === 1) {
const unsubscribe = subscribeTaskBoardChanges(accept)
void refreshTaskBoard()
const source =
- typeof EventSource !== 'undefined'
+ stream && typeof EventSource !== 'undefined'
? new EventSource(taskBoardUrl('/events'), { withCredentials: true })
: null
let fallback: ReturnType<typeof setInterval> | undefined
@@ -74,7 +74,7 @@ export function startTaskBoardSync() {
clearInterval(fallback)
fallback = undefined
}
- } else startFallback()
+ } else if (stream) startFallback()
const focus = () => {
if (!document.hidden) void refreshTaskBoard()
}
diff --git a/web/locales/de/app.json b/web/locales/de/app.json
index d5fac6c89..6a5ff49bd 100644
--- a/web/locales/de/app.json
+++ b/web/locales/de/app.json
@@ -5512,5 +5512,29 @@
"Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "Gilt für Chat, Problemlösung, Rückfragen, geführtes Lernen, Lesen, Kurslernen und Standardvisualisierungen. Änderungen gelten ab der nächsten Runde.",
"Clear instructions": "Anweisungen leeren",
"{{used}} / {{limit}} characters": "{{used}} / {{limit}} Zeichen",
- "contextBudget.segment.workspace_instructions": "Arbeitsbereichsanweisungen"
+ "contextBudget.segment.workspace_instructions": "Arbeitsbereichsanweisungen",
+ "navigation.home": "Start",
+ "navigation.partners": "Partner",
+ "navigation.learning": "Lernen",
+ "navigation.resources": "Materialien",
+ "navigation.categories": "Main sections",
+ "navigation.search": "Search this section",
+ "navigation.workspace": "Workspace",
+ "navigation.newChat": "New conversation",
+ "navigation.allLearning": "All learning",
+ "navigation.allPartners": "All partners",
+ "navigation.allResources": "All resources",
+ "navigation.learningRecords": "Your learning",
+ "navigation.partnerSessions": "Conversations",
+ "navigation.createLearning": "New learning activity",
+ "navigation.createLearningDescription": "Choose how you want to learn. Your work stays in its workspace.",
+ "navigation.learningDescription": "Your books, paths, practice and reading, all in one place.",
+ "navigation.learningFilter": "Learning type",
+ "navigation.searchLearning": "Search your learning",
+ "navigation.noResults": "No matching records",
+ "navigation.noLearning": "Create a learning activity to begin.",
+ "navigation.noGroups": "Bring two or more partners together.",
+ "navigation.noSessions": "Your conversations will appear here.",
+ "navigation.loadError": "Some records could not be loaded.",
+ "navigation.sessionUnavailable": "This conversation is unavailable or archived. Open history to find it."
}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ccc6056b8..8851e9d73 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -5512,5 +5512,29 @@
"Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.",
"Clear instructions": "Clear instructions",
"{{used}} / {{limit}} characters": "{{used}} / {{limit}} characters",
- "contextBudget.segment.workspace_instructions": "Workspace instructions"
+ "contextBudget.segment.workspace_instructions": "Workspace instructions",
+ "navigation.home": "Home",
+ "navigation.partners": "Partners",
+ "navigation.learning": "Learning",
+ "navigation.resources": "Resources",
+ "navigation.categories": "Main sections",
+ "navigation.search": "Search this section",
+ "navigation.workspace": "Workspace",
+ "navigation.newChat": "New conversation",
+ "navigation.allLearning": "All learning",
+ "navigation.allPartners": "All partners",
+ "navigation.allResources": "All resources",
+ "navigation.learningRecords": "Your learning",
+ "navigation.partnerSessions": "Conversations",
+ "navigation.createLearning": "New learning activity",
+ "navigation.createLearningDescription": "Choose how you want to learn. Your work stays in its workspace.",
+ "navigation.learningDescription": "Your books, paths, practice and reading, all in one place.",
+ "navigation.learningFilter": "Learning type",
+ "navigation.searchLearning": "Search your learning",
+ "navigation.noResults": "No matching records",
+ "navigation.noLearning": "Create a learning activity to begin.",
+ "navigation.noGroups": "Bring two or more partners together.",
+ "navigation.noSessions": "Your conversations will appear here.",
+ "navigation.loadError": "Some records could not be loaded.",
+ "navigation.sessionUnavailable": "This conversation is unavailable or archived. Open history to find it."
}
diff --git a/web/locales/fr/app.json b/web/locales/fr/app.json
index 29ff4e9f4..0091155cd 100644
--- a/web/locales/fr/app.json
+++ b/web/locales/fr/app.json
@@ -5892,5 +5892,29 @@
"Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "S’applique au chat, à la résolution, aux questions, à l’apprentissage guidé, à la lecture, aux cours et aux visualisations standard. Les changements prennent effet au prochain tour.",
"Clear instructions": "Effacer les instructions",
"{{used}} / {{limit}} characters": "{{used}} / {{limit}} caractères",
- "contextBudget.segment.workspace_instructions": "Instructions de l’espace de travail"
+ "contextBudget.segment.workspace_instructions": "Instructions de l’espace de travail",
+ "navigation.home": "Accueil",
+ "navigation.partners": "Partenaires",
+ "navigation.learning": "Apprentissage",
+ "navigation.resources": "Ressources",
+ "navigation.categories": "Main sections",
+ "navigation.search": "Search this section",
+ "navigation.workspace": "Workspace",
+ "navigation.newChat": "New conversation",
+ "navigation.allLearning": "All learning",
+ "navigation.allPartners": "All partners",
+ "navigation.allResources": "All resources",
+ "navigation.learningRecords": "Your learning",
+ "navigation.partnerSessions": "Conversations",
+ "navigation.createLearning": "New learning activity",
+ "navigation.createLearningDescription": "Choose how you want to learn. Your work stays in its workspace.",
+ "navigation.learningDescription": "Your books, paths, practice and reading, all in one place.",
+ "navigation.learningFilter": "Learning type",
+ "navigation.searchLearning": "Search your learning",
+ "navigation.noResults": "No matching records",
+ "navigation.noLearning": "Create a learning activity to begin.",
+ "navigation.noGroups": "Bring two or more partners together.",
+ "navigation.noSessions": "Your conversations will appear here.",
+ "navigation.loadError": "Some records could not be loaded.",
+ "navigation.sessionUnavailable": "This conversation is unavailable or archived. Open history to find it."
}
diff --git a/web/locales/pl/app.json b/web/locales/pl/app.json
index 43806081a..f65da6a26 100644
--- a/web/locales/pl/app.json
+++ b/web/locales/pl/app.json
@@ -5528,5 +5528,29 @@
"Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "Dotyczy czatu, rozwiązywania, pytań, nauki z przewodnikiem, czytania, kursów i standardowych wizualizacji. Zmiany obowiązują od następnej tury.",
"Clear instructions": "Wyczyść instrukcje",
"{{used}} / {{limit}} characters": "{{used}} / {{limit}} znaków",
- "contextBudget.segment.workspace_instructions": "Instrukcje obszaru roboczego"
+ "contextBudget.segment.workspace_instructions": "Instrukcje obszaru roboczego",
+ "navigation.home": "Strona główna",
+ "navigation.partners": "Partnerzy",
+ "navigation.learning": "Nauka",
+ "navigation.resources": "Materiały",
+ "navigation.categories": "Main sections",
+ "navigation.search": "Search this section",
+ "navigation.workspace": "Workspace",
+ "navigation.newChat": "New conversation",
+ "navigation.allLearning": "All learning",
+ "navigation.allPartners": "All partners",
+ "navigation.allResources": "All resources",
+ "navigation.learningRecords": "Your learning",
+ "navigation.partnerSessions": "Conversations",
+ "navigation.createLearning": "New learning activity",
+ "navigation.createLearningDescription": "Choose how you want to learn. Your work stays in its workspace.",
+ "navigation.learningDescription": "Your books, paths, practice and reading, all in one place.",
+ "navigation.learningFilter": "Learning type",
+ "navigation.searchLearning": "Search your learning",
+ "navigation.noResults": "No matching records",
+ "navigation.noLearning": "Create a learning activity to begin.",
+ "navigation.noGroups": "Bring two or more partners together.",
+ "navigation.noSessions": "Your conversations will appear here.",
+ "navigation.loadError": "Some records could not be loaded.",
+ "navigation.sessionUnavailable": "This conversation is unavailable or archived. Open history to find it."
}
diff --git a/web/locales/uk/app.json b/web/locales/uk/app.json
index a75d39e50..f74be8440 100644
--- a/web/locales/uk/app.json
+++ b/web/locales/uk/app.json
@@ -5528,5 +5528,29 @@
"Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "Застосовується до чату, розв’язування, запитань, керованого навчання, читання, курсів і стандартних візуалізацій. Зміни діють із наступного ходу.",
"Clear instructions": "Очистити інструкції",
"{{used}} / {{limit}} characters": "{{used}} / {{limit}} символів",
- "contextBudget.segment.workspace_instructions": "Інструкції робочого простору"
+ "contextBudget.segment.workspace_instructions": "Інструкції робочого простору",
+ "navigation.home": "Головна",
+ "navigation.partners": "Партнери",
+ "navigation.learning": "Навчання",
+ "navigation.resources": "Матеріали",
+ "navigation.categories": "Main sections",
+ "navigation.search": "Search this section",
+ "navigation.workspace": "Workspace",
+ "navigation.newChat": "New conversation",
+ "navigation.allLearning": "All learning",
+ "navigation.allPartners": "All partners",
+ "navigation.allResources": "All resources",
+ "navigation.learningRecords": "Your learning",
+ "navigation.partnerSessions": "Conversations",
+ "navigation.createLearning": "New learning activity",
+ "navigation.createLearningDescription": "Choose how you want to learn. Your work stays in its workspace.",
+ "navigation.learningDescription": "Your books, paths, practice and reading, all in one place.",
+ "navigation.learningFilter": "Learning type",
+ "navigation.searchLearning": "Search your learning",
+ "navigation.noResults": "No matching records",
+ "navigation.noLearning": "Create a learning activity to begin.",
+ "navigation.noGroups": "Bring two or more partners together.",
+ "navigation.noSessions": "Your conversations will appear here.",
+ "navigation.loadError": "Some records could not be loaded.",
+ "navigation.sessionUnavailable": "This conversation is unavailable or archived. Open history to find it."
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index ab2861866..3830f4416 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -5512,5 +5512,29 @@
"Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "适用于对话、解题、主动提问、引导学习、沉浸式阅读、课程学习和常规可视化。从下一轮开始生效。",
"Clear instructions": "清空提示词",
"{{used}} / {{limit}} characters": "{{used}} / {{limit}} 字符",
- "contextBudget.segment.workspace_instructions": "工作区提示词"
+ "contextBudget.segment.workspace_instructions": "工作区提示词",
+ "navigation.home": "主页",
+ "navigation.partners": "伙伴",
+ "navigation.learning": "学习",
+ "navigation.resources": "资料",
+ "navigation.categories": "主要栏目",
+ "navigation.search": "搜索当前栏目",
+ "navigation.workspace": "工作台",
+ "navigation.newChat": "新对话",
+ "navigation.allLearning": "全部学习",
+ "navigation.allPartners": "全部伙伴",
+ "navigation.allResources": "全部资料",
+ "navigation.learningRecords": "学习记录",
+ "navigation.partnerSessions": "会话记录",
+ "navigation.createLearning": "新建学习",
+ "navigation.createLearningDescription": "选择一种学习方式,内容将保存在指定工作区。",
+ "navigation.learningDescription": "书籍、精通之路、练习与阅读,都在这里继续。",
+ "navigation.learningFilter": "学习类型",
+ "navigation.searchLearning": "搜索学习记录",
+ "navigation.noResults": "没有匹配的记录",
+ "navigation.noLearning": "新建一项学习,从这里开始。",
+ "navigation.noGroups": "把两位或更多伙伴组成一个群组。",
+ "navigation.noSessions": "开始对话后,会话会保留在这里。",
+ "navigation.loadError": "部分记录暂时无法加载。",
+ "navigation.sessionUnavailable": "此会话暂不可用或已归档,请在历史记录中查看。"
}
diff --git a/web/tests/learning-dashboard.spec.tsx b/web/tests/learning-dashboard.spec.tsx
index 4359c4d37..b790d57d6 100644
--- a/web/tests/learning-dashboard.spec.tsx
+++ b/web/tests/learning-dashboard.spec.tsx
@@ -1,8 +1,12 @@
import React from 'react'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, expect, it, vi } from 'vitest'
+import { LearningWays } from '@/components/learning/LearningWays'
import { LearningDashboard } from '@/components/learning/LearningDashboard'
+vi.mock('next/navigation', () => ({ usePathname: () => '/learning', useRouter: () => ({ push: vi.fn() }), useSearchParams: () => new URLSearchParams() }))
+vi.mock('@/hooks/useAuthStatus', () => ({ useAuthStatus: () => ({ learningPolicy: null }) }))
+
const mock = vi.hoisted(() => ({
books: vi.fn(),
topics: vi.fn(),
@@ -121,7 +125,7 @@ it('a failed refresh keeps already loaded work visible', async () => {
})
it('a way introduces itself before it commits you, and hands focus back', async () => {
- render(<LearningDashboard />)
+ render(<LearningWays />)
const card = await screen.findByRole('button', { name: /Mastery Path/ })
fireEvent.click(card)
const panel = await screen.findByRole('dialog')
@@ -134,8 +138,7 @@ it('a way introduces itself before it commits you, and hands focus back', async
it('feature introductions do not show personal activity or source failures', async () => {
mock.reading.mockRejectedValue(new Error('offline'))
- render(<LearningDashboard />)
- await screen.findByRole('alert')
+ render(<LearningWays />)
const books = screen.getByRole('button', { name: /Books/ })
expect(books).not.toHaveTextContent('Home')
const reading = screen.getByRole('button', { name: /Immersive Reading/ })
@@ -147,7 +150,7 @@ it('feature introductions do not show personal activity or source failures', asy
})
it('contains focus and restores background interaction on Escape', async () => {
- const { container } = render(<LearningDashboard />)
+ const { container } = render(<LearningWays />)
const card = await screen.findByRole('button', { name: /Mastery Path/ })
fireEvent.click(card)
const panel = screen.getByRole('dialog')
@@ -171,7 +174,7 @@ it.each([
['Mastery Path', '/learning/mastery'],
['Immersive Reading', '/learning/reading'],
])('opens the complete library without assigning a workspace for %s', async (label, route) => {
- render(<LearningDashboard />)
+ render(<LearningWays />)
fireEvent.click(await screen.findByRole('button', { name: new RegExp(label) }))
expect(screen.queryByRole('button', { name: 'Workspace' })).toBeNull()
expect(screen.getByRole('link', { name: 'Start' })).toHaveAttribute('href', route)
diff --git a/web/tests/learning-dashboard.test.ts b/web/tests/learning-dashboard.test.ts
index 61f1a5da9..efb4eb980 100644
--- a/web/tests/learning-dashboard.test.ts
+++ b/web/tests/learning-dashboard.test.ts
@@ -95,7 +95,7 @@ test('surface stats count each kind and name the piece of it touched last', () =
const stats = learningSurfaceStats(sources)
assert.deepEqual(
Object.fromEntries(Object.entries(stats).map(([kind, stat]) => [kind, stat.count])),
- { books: 3, mastery: 1, reading: 1, watching: 2 }
+ { books: 3, mastery: 1, reading: 1, watching: 2, practice: 0 }
)
assert.equal(stats.books.latest?.title, 'c')
assert.equal(stats.watching.latest?.updatedAt, 90)
diff --git a/web/tests/navigation-records.spec.ts b/web/tests/navigation-records.spec.ts
new file mode 100644
index 000000000..acc5c490c
--- /dev/null
+++ b/web/tests/navigation-records.spec.ts
@@ -0,0 +1,59 @@
+import { expect, it } from 'vitest'
+import { allLearningActivity, type LearningSources } from '@/lib/learning-dashboard'
+import { categoryForPath, partnerSessionHref } from '@/lib/navigation'
+
+it('keeps old feature URLs in their new categories', () => {
+ for (const path of ['/chat/old-session', '/co-writer/old-document', '/kanban', '/agents'])
+ expect(categoryForPath(path)).toBe('home')
+ for (const path of ['/learning/books/old-book', '/learning/reading/old-material', '/courses/a'])
+ expect(categoryForPath(path)).toBe('learning')
+ for (const path of [
+ '/space/mcp',
+ '/knowledge-bases/old-kb',
+ '/notebooks/old-notebook',
+ '/memory',
+ ])
+ expect(categoryForPath(path)).toBe('resources')
+ expect(categoryForPath('/partners/groups/old-group')).toBe('partners')
+})
+
+it('retains duplicate question IDs from distinct workspaces and preserves exact origin in links', () => {
+ const sources: LearningSources = {
+ books: [],
+ mastery: [],
+ reading: [],
+ watching: [],
+ practice: [
+ {
+ id: 1,
+ question: 'Original question',
+ updated_at: 20,
+ created_at: 1,
+ content_workspace_id: '',
+ },
+ {
+ id: 1,
+ question: 'Workspace question',
+ updated_at: 30,
+ created_at: 2,
+ content_workspace_id: 'ws_other',
+ },
+ ],
+ }
+ const rows = allLearningActivity(sources)
+ expect(new Set(rows.map(row => row.key)).size).toBe(2)
+ expect(rows.map(row => row.href)).toEqual([
+ '/learning/practice?question=1&dt_workspace=ws_other',
+ '/learning/practice?question=1&dt_workspace=',
+ ])
+ expect(sources.practice?.[0].question).toBe('Original question')
+})
+
+it('encodes partner identities and session keys independently without rewriting them', () => {
+ const url = new URL(
+ partnerSessionHref({ kind: 'partner', owner_id: '研究伙伴', session_key: 'web:old/+?' }),
+ 'https://example.test'
+ )
+ expect(decodeURIComponent(url.pathname)).toBe('/partners/研究伙伴')
+ expect(url.searchParams.get('session')).toBe('web:old/+?')
+})
diff --git a/web/tests/partner-direct-chat.test.ts b/web/tests/partner-direct-chat.test.ts
index b85fbb195..c31b347ad 100644
--- a/web/tests/partner-direct-chat.test.ts
+++ b/web/tests/partner-direct-chat.test.ts
@@ -34,7 +34,7 @@ test("partner tabs use a stable centered header column", () => {
test("partner chat keeps old active and archived conversations reachable", () => {
assert.match(pageSource, /handleArchiveConversation/);
assert.match(pageSource, /archivePartnerSession\(partnerId, sessionKey\)/);
- assert.match(pageSource, /if \(result\.active_session_key\) changeSessionKey\(result\.active_session_key, true\)/);
+ assert.match(pageSource, /if \(result\.active_session_key\) selectSessionKey\(result\.active_session_key, true\)/);
assert.match(archiveSource, /const next = await getPartnerSessions\(partnerId\)/);
assert.match(archiveSource, /resumePartnerSession/);
});
diff --git a/web/tests/partner-group-export-session.spec.tsx b/web/tests/partner-group-export-session.spec.tsx
index 329b7044a..53f4740a2 100644
--- a/web/tests/partner-group-export-session.spec.tsx
+++ b/web/tests/partner-group-export-session.spec.tsx
@@ -6,7 +6,8 @@ import { downloadChatMarkdown } from "@/lib/chat-export";
import type { PartnerGroupMessage } from "@/lib/partner-groups-api";
import { initI18n } from "@/i18n/init";
-vi.mock("next/navigation", () => ({ useParams: () => ({ groupId: "group" }), useRouter: () => ({ push: vi.fn() }) }));
+vi.mock("next/navigation", () => ({
+ useSearchParams: () => new URLSearchParams(), useParams: () => ({ groupId: "group" }), useRouter: () => ({ replace: vi.fn(), push: vi.fn() }) }));
vi.mock("@/components/partners/group/DiscussionModePicker", () => ({ default: () => null, useDiscussionModeLabel: () => () => "Panel" }));
vi.mock("@/lib/chat-export", () => ({ downloadChatMarkdown: vi.fn() }));
vi.mock("@/lib/partner-groups-api", () => ({
diff --git a/web/tests/partner-navigation-session.spec.tsx b/web/tests/partner-navigation-session.spec.tsx
new file mode 100644
index 000000000..07edf63ac
--- /dev/null
+++ b/web/tests/partner-navigation-session.spec.tsx
@@ -0,0 +1,93 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, expect, it, vi } from 'vitest'
+import PartnerDetailPage from '@/app/(workspace)/partners/[partnerId]/page'
+import { loadPartnerSessionKey } from '@/lib/partner-session'
+import { initI18n } from '@/i18n/init'
+
+const state = vi.hoisted(() => ({
+ query: 'session=web-old',
+ router: { replace: vi.fn(), push: vi.fn() },
+ continuity: vi.fn(),
+ select: vi.fn(),
+}))
+vi.mock('next/navigation', () => ({
+ useParams: () => ({ partnerId: 'ada' }),
+ useSearchParams: () => new URLSearchParams(state.query),
+ useRouter: () => state.router,
+}))
+vi.mock('@/hooks/useAuthStatus', () => ({
+ useAuthStatus: () => ({
+ loading: false,
+ enabled: false,
+ userId: 'local-admin',
+ isAdmin: true,
+ statusAvailable: true,
+ }),
+}))
+vi.mock('@/lib/partners-api', () => ({
+ getPartner: async () => ({ partner_id: 'ada', name: 'Ada', running: false, can_manage: false }),
+ getPartnerSessions: async () => [
+ { session_key: 'web-old', title: 'Old', archived: false },
+ { session_key: 'web-other', title: 'Other', archived: false },
+ { session_key: 'web-archived', title: 'Archived', archived: true },
+ ],
+ getPartnerWebContinuity: state.continuity,
+ setPartnerWebContinuity: state.select,
+}))
+vi.mock('@/components/partners/PartnerChat', () => ({
+ default: ({
+ sessionKey,
+ onSessionKeyChange,
+ }: {
+ sessionKey: string
+ onSessionKeyChange: (key: string) => void
+ }) => (
+ <>
+ <output aria-label="Current session">{sessionKey}</output>
+ <button onClick={() => onSessionKeyChange('web-other')}>Choose another session</button>
+ </>
+ ),
+}))
+vi.mock('@/components/partners/PartnerConfigure', () => ({ default: () => null }))
+vi.mock('@/components/partners/PartnerChannels', () => ({ default: () => null }))
+vi.mock('@/components/partners/PartnerArchives', () => ({ default: () => null }))
+vi.mock('@/components/notebook/SaveToNotebookModal', () => ({ default: () => null }))
+initI18n('en')
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ state.query = 'session=web-old'
+ state.continuity.mockResolvedValue({ enabled: false, session_key: null })
+ state.select.mockImplementation(async (_id, selection) => selection)
+})
+
+it('opens the exact linked legacy session and keeps manual selection and reload URL consistent', async () => {
+ render(<PartnerDetailPage />)
+ await waitFor(() => expect(screen.getByLabelText('Current session')).toHaveTextContent('web-old'))
+ expect(loadPartnerSessionKey('ada', 'local-admin')).toBe('web-old')
+ fireEvent.click(screen.getByRole('button', { name: 'Choose another session' }))
+ await waitFor(() =>
+ expect(state.router.replace).toHaveBeenCalledWith('/partners/ada?session=web-other', {
+ scroll: false,
+ })
+ )
+ expect(loadPartnerSessionKey('ada', 'local-admin')).toBe('web-other')
+})
+
+it("rejects unavailable and archived links without replacing the browser's current session", async () => {
+ state.query = 'session=web-archived'
+ render(<PartnerDetailPage />)
+ await screen.findByText('This conversation is unavailable or archived. Open history to find it.')
+ expect(screen.getByLabelText('Current session')).not.toHaveTextContent('web-archived')
+ expect(state.select).not.toHaveBeenCalled()
+})
+
+it('resolves linked sessions through the existing shared-continuity selection API', async () => {
+ state.continuity.mockResolvedValue({ enabled: true, session_key: 'web-other' })
+ render(<PartnerDetailPage />)
+ await waitFor(() =>
+ expect(state.select).toHaveBeenCalledWith('ada', { enabled: true, session_key: 'web-old' })
+ )
+ expect(screen.getByLabelText('Current session')).toHaveTextContent('web-old')
+})
diff --git a/web/tests/sidebar-lazy-history.spec.tsx b/web/tests/sidebar-lazy-history.spec.tsx
index 95e17564a..d066a0f2b 100644
--- a/web/tests/sidebar-lazy-history.spec.tsx
+++ b/web/tests/sidebar-lazy-history.spec.tsx
@@ -19,6 +19,7 @@ vi.mock("@/hooks/useAuthStatus", () => ({
vi.mock("@/hooks/useChatWorkspaces", () => ({ useChatWorkspaces: () => ({ workspaces: [], error: "" }) }));
vi.mock("next/navigation", () => ({
+ useSearchParams: () => new URLSearchParams(),
usePathname: () => "/co-writer",
useRouter: () => ({ push: fixture.push }),
}));
@@ -67,8 +68,6 @@ it("loads conversation history while navigation remains usable, then preserves s
/>,
);
expect(container.querySelector('[aria-busy="true"]')).toBeInTheDocument();
- expect(screen.queryByRole("link", { name: "Co-Writer" })).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: /More/ }));
expect(screen.getByRole("link", { name: "Co-Writer" })).toHaveAttribute(
"href",
"/co-writer",
@@ -77,10 +76,10 @@ it("loads conversation history while navigation remains usable, then preserves s
const history = await screen.findByText("Retained session");
const scroller = history.closest(".overflow-y-auto");
expect(scroller).toContainElement(
- screen.getByRole("link", { name: "Partners" }),
+ screen.getByRole("link", { name: "Co-Writer" }),
);
expect(scroller).not.toContainElement(
- screen.getByRole("link", { name: "Home" }),
+ screen.getByRole("tab", { name: "navigation.home" }),
);
expect(scroller).not.toContainElement(
screen.getByRole("link", { name: "Settings" }),
@@ -114,9 +113,9 @@ it("keeps Home pinned even when a previous layout folded it into More", () => {
}),
);
render(<SidebarShell />);
- expect(screen.getAllByRole("link", { name: "Home" })).toHaveLength(1);
+ expect(screen.getAllByRole("tab", { name: "navigation.home" })).toHaveLength(1);
expect(screen.queryByRole("button", { name: "Arrange Home" })).toBeNull();
- fireEvent.click(screen.getByRole("link", { name: "Home" }));
+ fireEvent.click(screen.getByRole("link", { name: "navigation.newChat" }));
expect(fixture.push).toHaveBeenCalledWith("/chat");
});
@@ -124,16 +123,16 @@ it("resizes with the keyboard, persists across mounts, and resets on double clic
const first = render(<SidebarShell />);
const handle = screen.getByRole("separator", { name: "Resize sidebar" });
fireEvent.keyDown(handle, { key: "ArrowRight" });
- expect(handle).toHaveAttribute("aria-valuenow", "230");
+ expect(handle).toHaveAttribute("aria-valuenow", "282");
expect(
first.container
.querySelector("aside")!
.style.getPropertyValue("--sidebar-width"),
- ).toBe("230px");
+ ).toBe("282px");
first.unmount();
render(<SidebarShell />);
const restored = screen.getByRole("separator", { name: "Resize sidebar" });
- expect(restored).toHaveAttribute("aria-valuenow", "230");
+ expect(restored).toHaveAttribute("aria-valuenow", "282");
fireEvent.keyDown(restored, { key: "Home" });
fireEvent.keyDown(restored, { key: "ArrowLeft" });
expect(restored).toHaveAttribute("aria-valuenow", "220");
@@ -143,5 +142,5 @@ it("resizes with the keyboard, persists across mounts, and resets on double clic
restored.getAttribute("aria-valuemax"),
);
fireEvent.doubleClick(restored);
- expect(restored).toHaveAttribute("aria-valuenow", "220");
+ expect(restored).toHaveAttribute("aria-valuenow", "272");
});
diff --git a/web/tests/sidebar-prefetch.spec.tsx b/web/tests/sidebar-prefetch.spec.tsx
index 90ef72e96..f8af858a3 100644
--- a/web/tests/sidebar-prefetch.spec.tsx
+++ b/web/tests/sidebar-prefetch.spec.tsx
@@ -38,6 +38,7 @@ vi.mock("next/link", () => ({
),
}));
vi.mock("next/navigation", () => ({
+ useSearchParams: () => new URLSearchParams(),
usePathname: () => "/chat",
useRouter: () => ({ push: fixture.push }),
}));