From bba2f9d7a35ac39abc55aa336f96a706e1ef763a Mon Sep 17 00:00:00 2001 From: Gavin Date: Thu, 26 Nov 2026 10:32:06 +0800 Subject: [PATCH] ci: add automated github pages deployment for PR documentation previews --- .github/workflows/docs.yml | 311 ++++++++++- docs/README.md | 13 + docs/astro.config.mjs | 80 ++- docs/package-lock.json | 21 - docs/package.json | 1 - docs/scripts/capture-guide.mjs | 525 ------------------ docs/scripts/capture-screenshots.mjs | 106 ---- docs/scripts/check_docs.py | 68 ++- docs/scripts/gif/compress-gifs.mjs | 12 +- docs/scripts/gif/webreel-react-type-hook.mjs | 12 +- docs/scripts/seed-guide-book.py | 249 --------- docs/scripts/seed-guide-data.mjs | 354 ------------ docs/scripts/update-gifs.mjs | 16 +- docs/src/components/HomeLanding.astro | 66 +-- docs/src/components/SiteTitle.astro | 3 +- docs/src/components/SocialIcons.astro | 52 +- docs/src/content/docs/self-hosting/docker.md | 4 +- docs/src/content/docs/self-hosting/index.md | 2 +- .../content/docs/zh-cn/get-started/docker.md | 2 +- .../docs/zh-cn/learn/ask-with-a-source.md | 2 +- .../content/docs/zh-cn/self-hosting/docker.md | 2 +- .../content/docs/zh-cn/self-hosting/index.md | 2 +- docs/src/styles/starlight.css | 4 +- 23 files changed, 572 insertions(+), 1335 deletions(-) delete mode 100644 docs/scripts/capture-guide.mjs delete mode 100644 docs/scripts/capture-screenshots.mjs delete mode 100644 docs/scripts/seed-guide-book.py delete mode 100644 docs/scripts/seed-guide-data.mjs diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index b2e12a22d..42f22bfb5 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,6 +1,20 @@ name: Docs +# Builds and verifies the public Astro/Starlight docs site. +# +# Same-repo pull requests also deploy an isolated preview to the `gh-pages` +# branch at `pr-/` and post/update a comment with the preview URL, +# then clean up that directory when the pull request closes. +# +# Repository setup (one-time): +# Settings -> Pages -> Build and deployment -> Deploy from a branch: +# branch `gh-pages`, folder `/ (root)`. +# Optional repository variable: +# DOCS_PREVIEW_SITE — custom origin (e.g. `https://docs.deeptutor.info`) +# if `gh-pages` serves a custom domain without a CNAME file. + on: + workflow_dispatch: push: branches: - main @@ -10,24 +24,32 @@ on: - "docs/**" - "deeptutor/modules/manifests/**" - "deeptutor/api/router_index.json" + - "deeptutor/partners/channels/**" + - "deeptutor/partners/config/schema.py" - "assets/figs/web-dev/**" - ".github/workflows/docs.yml" pull_request: + types: [opened, synchronize, reopened, closed] paths: - "docs/**" - "deeptutor/modules/manifests/**" - "deeptutor/api/router_index.json" + - "deeptutor/partners/channels/**" + - "deeptutor/partners/config/schema.py" - "assets/figs/web-dev/**" - ".github/workflows/docs.yml" -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true +permissions: + contents: read jobs: docs: name: Build and check the docs site + if: github.event_name != 'pull_request' || github.event.action != 'closed' runs-on: ubuntu-latest + concurrency: + group: docs-build-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true defaults: run: working-directory: docs @@ -46,7 +68,7 @@ jobs: working-directory: . run: python3 docs/scripts/check_docs.py - - name: Install and build + - name: Install dependencies run: npm ci env: ASTRO_TELEMETRY_DISABLED: "1" @@ -59,3 +81,284 @@ jobs: - name: Check built links working-directory: . run: python3 docs/scripts/check_docs.py dist + + preview: + name: Deploy PR preview to GitHub Pages + needs: docs + if: >- + github.event_name == 'pull_request' && + github.event.action != 'closed' && + github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + concurrency: + group: docs-gh-pages + cancel-in-progress: false + defaults: + run: + working-directory: docs + steps: + - name: Checkout PR head + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: docs/package-lock.json + + - name: Resolve preview URL and base path + id: meta + working-directory: . + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + REPO_OWNER: ${{ github.repository_owner }} + REPO_NAME: ${{ github.event.repository.name }} + CUSTOM_SITE: ${{ vars.DOCS_PREVIEW_SITE }} + run: | + set -euo pipefail + owner_lower="$(printf '%s' "$REPO_OWNER" | tr '[:upper:]' '[:lower:]')" + preview_dir="pr-${PR_NUMBER}" + + cname="" + if git fetch --depth=1 origin gh-pages 2>/dev/null; then + if git cat-file -e FETCH_HEAD:CNAME 2>/dev/null; then + cname="$(git show FETCH_HEAD:CNAME | tr -d '[:space:]')" + fi + fi + + if [ -n "$CUSTOM_SITE" ]; then + docs_site="${CUSTOM_SITE%/}" + docs_base="/${preview_dir}" + elif [ -n "$cname" ]; then + docs_site="https://${cname}" + docs_base="/${preview_dir}" + elif [ "$(printf '%s' "$REPO_NAME" | tr '[:upper:]' '[:lower:]')" = "${owner_lower}.github.io" ]; then + docs_site="https://${owner_lower}.github.io" + docs_base="/${preview_dir}" + else + docs_site="https://${owner_lower}.github.io" + docs_base="/${REPO_NAME}/${preview_dir}" + fi + + preview_url="${docs_site}${docs_base}/" + { + echo "docs_site=${docs_site}" + echo "docs_base=${docs_base}" + echo "preview_dir=${preview_dir}" + echo "preview_url=${preview_url}" + } >> "$GITHUB_OUTPUT" + + - name: Install dependencies + run: npm ci + env: + ASTRO_TELEMETRY_DISABLED: "1" + + - name: Build preview site + run: npm run build + env: + ASTRO_TELEMETRY_DISABLED: "1" + DOCS_SITE: ${{ steps.meta.outputs.docs_site }} + DOCS_BASE: ${{ steps.meta.outputs.docs_base }} + DOCS_NOINDEX: "1" + + - name: Check preview links + working-directory: . + run: python3 docs/scripts/check_docs.py dist + env: + DOCS_BASE: ${{ steps.meta.outputs.docs_base }} + + - name: Publish preview to gh-pages + working-directory: . + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PREVIEW_DIR: ${{ steps.meta.outputs.preview_dir }} + PREVIEW_URL: ${{ steps.meta.outputs.preview_url }} + run: | + set -euo pipefail + worktree="$(mktemp -d)" + trap 'git worktree remove --force "$worktree" 2>/dev/null || rm -rf "$worktree"' EXIT + + if git ls-remote --exit-code --heads origin gh-pages >/dev/null 2>&1; then + git fetch --depth=1 origin gh-pages + git worktree add --detach "$worktree" FETCH_HEAD + else + git worktree add --orphan -b gh-pages "$worktree" + fi + + touch "${worktree}/.nojekyll" + rm -rf "${worktree:?}/${PREVIEW_DIR}" + mkdir -p "${worktree}/${PREVIEW_DIR}" + cp -R docs/dist/. "${worktree}/${PREVIEW_DIR}/" + + git -C "$worktree" config user.name "github-actions[bot]" + git -C "$worktree" config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git -C "$worktree" add --all -- ".nojekyll" "${PREVIEW_DIR}" + + if git -C "$worktree" diff --cached --quiet; then + echo "Preview content unchanged; skipping push." + else + short_sha="${HEAD_SHA:0:7}" + git -C "$worktree" commit -m "chore(docs): update preview for PR #${PR_NUMBER} (${short_sha})" + for attempt in 1 2 3; do + if git -C "$worktree" push origin HEAD:refs/heads/gh-pages; then + break + fi + if [ "$attempt" -eq 3 ]; then + exit 1 + fi + git -C "$worktree" fetch --depth=1 origin gh-pages + git -C "$worktree" rebase FETCH_HEAD + done + fi + + { + echo "### Docs PR Preview" + echo "" + echo "- English: ${PREVIEW_URL}" + echo "- 简体中文: ${PREVIEW_URL}zh-cn/" + echo "- Commit: \`${HEAD_SHA:0:7}\`" + } >> "$GITHUB_STEP_SUMMARY" + + - name: Comment preview URL on PR + uses: actions/github-script@v7 + env: + PREVIEW_URL: ${{ steps.meta.outputs.preview_url }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + with: + script: | + const marker = ""; + const previewUrl = process.env.PREVIEW_URL; + const shortSha = (process.env.HEAD_SHA || "").slice(0, 7); + const body = [ + marker, + "### Docs Preview", + "", + `- **English**: ${previewUrl}`, + `- **简体中文**: ${previewUrl}zh-cn/`, + "", + `Built from commit \`${shortSha}\`. GitHub Pages may take a minute to publish after this push. The preview directory is removed automatically when this PR closes.`, + ].join("\n"); + + const { owner, repo } = context.repo; + const issue_number = context.issue.number; + const comments = await github.paginate(github.rest.issues.listComments, { + owner, + repo, + issue_number, + per_page: 100, + }); + const existing = comments.find( + (comment) => + comment.user?.type === "Bot" && + typeof comment.body === "string" && + comment.body.includes(marker), + ); + if (existing) { + await github.rest.issues.updateComment({ + owner, + repo, + comment_id: existing.id, + body, + }); + } else { + await github.rest.issues.createComment({ + owner, + repo, + issue_number, + body, + }); + } + + cleanup-preview: + name: Clean up PR preview from GitHub Pages + if: >- + github.event_name == 'pull_request' && + github.event.action == 'closed' && + github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + concurrency: + group: docs-gh-pages + cancel-in-progress: false + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Remove preview directory from gh-pages + id: cleanup + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + set -euo pipefail + preview_dir="pr-${PR_NUMBER}" + + if ! git ls-remote --exit-code --heads origin gh-pages >/dev/null 2>&1; then + echo "removed=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + + git fetch --depth=1 origin gh-pages + worktree="$(mktemp -d)" + trap 'git worktree remove --force "$worktree" 2>/dev/null || rm -rf "$worktree"' EXIT + git worktree add --detach "$worktree" FETCH_HEAD + + if [ ! -d "${worktree}/${preview_dir}" ]; then + echo "removed=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + + rm -rf "${worktree:?}/${preview_dir}" + git -C "$worktree" config user.name "github-actions[bot]" + git -C "$worktree" config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git -C "$worktree" add --all -- "${preview_dir}" + git -C "$worktree" commit -m "chore(docs): remove preview for PR #${PR_NUMBER}" + + for attempt in 1 2 3; do + if git -C "$worktree" push origin HEAD:refs/heads/gh-pages; then + break + fi + if [ "$attempt" -eq 3 ]; then + exit 1 + fi + git -C "$worktree" fetch --depth=1 origin gh-pages + git -C "$worktree" rebase FETCH_HEAD + done + echo "removed=true" >> "$GITHUB_OUTPUT" + + - name: Update preview comment on PR + if: steps.cleanup.outputs.removed == 'true' + uses: actions/github-script@v7 + with: + script: | + const marker = ""; + const { owner, repo } = context.repo; + const issue_number = context.issue.number; + const comments = await github.paginate(github.rest.issues.listComments, { + owner, + repo, + issue_number, + per_page: 100, + }); + const existing = comments.find( + (comment) => + comment.user?.type === "Bot" && + typeof comment.body === "string" && + comment.body.includes(marker), + ); + if (existing) { + await github.rest.issues.updateComment({ + owner, + repo, + comment_id: existing.id, + body: `${marker}\n### Docs Preview\n\nThis PR is closed, so the GitHub Pages preview has been removed.`, + }); + } diff --git a/docs/README.md b/docs/README.md index 259b286be..17bed34fb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -167,3 +167,16 @@ After changing a module manifest or `router_index.json`: ```bash python3 docs/scripts/generate_reference.py ``` + +## PR previews (GitHub Pages) + +Same-repo pull requests that touch docs build a subpath preview and publish it to the `gh-pages` branch under `pr-/`, then post or update a comment on the PR with links to both locales. Closing the PR removes `pr-/` automatically. Fork pull requests still run the build and link checks without pushing to `gh-pages`. + +One-time repository setup: in **Settings → Pages**, set **Source** to **Deploy from a branch**, branch `gh-pages`, folder `/ (root)`. If `gh-pages` uses a custom domain without a committed `CNAME` file, set the repository variable `DOCS_PREVIEW_SITE` (for example `https://docs.deeptutor.info`). + +To test a subpath preview build locally: + +```bash +cd docs && DOCS_BASE=/DeepTutor/pr-1 DOCS_NOINDEX=1 ASTRO_TELEMETRY_DISABLED=1 npm run build && cd .. +DOCS_BASE=/DeepTutor/pr-1 python3 docs/scripts/check_docs.py dist +``` diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index 48e23a308..814643cf4 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -1,14 +1,79 @@ // @ts-check import { defineConfig } from "astro/config"; import starlight from "@astrojs/starlight"; +import { readdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const site = process.env.DOCS_SITE || "https://docs.deeptutor.info"; +const rawBase = (process.env.DOCS_BASE || "/").trim(); +const base = + rawBase === "" || rawBase === "/" + ? "/" + : `/${rawBase.replace(/^\/+|\/+$/g, "")}`; +const noindex = process.env.DOCS_NOINDEX === "1"; + +/** + * When building under a non-root base path (for example GitHub Pages PR + * previews at `//pr-`), prefix root-relative links and static + * asset URLs in the emitted HTML that Markdown/MDX or raw HTML left unprefixed. + */ +function prefixBaseIntegration(basePath) { + return { + name: "deeptutor-prefix-base", + hooks: { + "astro:build:done": async ({ dir }) => { + if (basePath === "/") return; + const root = fileURLToPath(dir); + const prefix = basePath; + const rewriteUrl = (url) => { + if ( + !url.startsWith("/") || + url.startsWith("//") || + url === prefix || + url.startsWith(`${prefix}/`) + ) { + return url; + } + return `${prefix}${url}`; + }; + const walk = async (folder) => { + const entries = await readdir(folder, { withFileTypes: true }); + for (const entry of entries) { + const full = path.join(folder, entry.name); + if (entry.isDirectory()) { + await walk(full); + continue; + } + if (!entry.name.endsWith(".html")) continue; + const original = await readFile(full, "utf8"); + const updated = original + .replace( + /(\b(?:href|src)=["'])(\/[^"']*)(["'])/g, + (_, lead, url, tail) => `${lead}${rewriteUrl(url)}${tail}`, + ) + .replace( + /(]*content=["']\d+;\s*url=)(\/[^"']*)(["'])/gi, + (_, lead, url, tail) => `${lead}${rewriteUrl(url)}${tail}`, + ); + if (updated !== original) { + await writeFile(full, updated, "utf8"); + } + } + }; + await walk(root); + }, + }, + }; +} // i18n — English is the source-of-truth locale. Chinese pages live under // `src/content/docs/zh-cn/` mirroring the English structure. Pages not yet // translated fall back to English automatically. -const zh = "zh-CN"; export default defineConfig({ - site: "https://docs.deeptutor.info", + site, + ...(base !== "/" ? { base } : {}), redirects: { "/tutorbot/": "/channels/", "/tutorbot/discord/": "/channels/international/discord/", @@ -157,6 +222,16 @@ export default defineConfig({ title: "DeepTutor", favicon: "/brand/favicon-32x32.png", description: "Agent-native, open-source personalized tutoring.", + ...(noindex + ? { + head: [ + { + tag: "meta", + attrs: { name: "robots", content: "noindex, nofollow" }, + }, + ], + } + : {}), defaultLocale: "root", locales: { root: { label: "English", lang: "en" }, @@ -332,5 +407,6 @@ export default defineConfig({ }, ], }), + prefixBaseIntegration(base), ], }); diff --git a/docs/package-lock.json b/docs/package-lock.json index 1f5c4177b..b78837d5b 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -13,7 +13,6 @@ "sharp": "^0.34.5" }, "devDependencies": { - "i18n-iso-countries": "^7.14.0", "webreel": "^0.1.4" } }, @@ -2492,13 +2491,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/diacritics": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/diacritics/-/diacritics-1.3.0.tgz", - "integrity": "sha512-wlwEkqcsaxvPJML+rDh/2iS824jbREk6DUMUKkEaSlxdYHeS43cClJtsWglvw2RfeXGm6ohKDqsXteJ5sP5enA==", - "dev": true, - "license": "MIT" - }, "node_modules/diff": { "version": "8.0.4", "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", @@ -3335,19 +3327,6 @@ "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==", "license": "BSD-2-Clause" }, - "node_modules/i18n-iso-countries": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/i18n-iso-countries/-/i18n-iso-countries-7.14.0.tgz", - "integrity": "sha512-nXHJZYtNrfsi1UQbyRqm3Gou431elgLjKl//CYlnBGt5aTWdRPH1PiS2T/p/n8Q8LnqYqzQJik3Q7mkwvLokeg==", - "dev": true, - "license": "MIT", - "dependencies": { - "diacritics": "1.3.0" - }, - "engines": { - "node": ">= 12" - } - }, "node_modules/i18next": { "version": "26.2.0", "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.2.0.tgz", diff --git a/docs/package.json b/docs/package.json index dce161639..db4589a2f 100644 --- a/docs/package.json +++ b/docs/package.json @@ -16,7 +16,6 @@ "sharp": "^0.34.5" }, "devDependencies": { - "i18n-iso-countries": "^7.14.0", "webreel": "^0.1.4" } } diff --git a/docs/scripts/capture-guide.mjs b/docs/scripts/capture-guide.mjs deleted file mode 100644 index 5281fcd35..000000000 --- a/docs/scripts/capture-guide.mjs +++ /dev/null @@ -1,525 +0,0 @@ -// DeepTutor guide screenshots — drives a running DeepTutor web UI and writes -// 1470x836@2x light-theme shots into site/docs/public/screenshots/guide//. -// -// The guide shots (the ones embedded in /explore/* pages) used to be taken by -// hand, which is why they drifted ~25 releases behind the product. This script -// makes a refresh reproducible: pick the jobs you need, re-run, review the diff. -// -// Requires the `playwright` npm package + chromium. It is not a dependency of -// the docs site, so resolve it from wherever it is installed: -// PW_FROM=../../web/package.json node scripts/capture-guide.mjs -// Run with no arguments to list the jobs. -// -// The DeepTutor instance must be running with the interface language set to -// English (the docs are English-source and both locales share the images). -import { createRequire } from "node:module"; -import { mkdir } from "node:fs/promises"; -import { dirname } from "node:path"; - -const require = createRequire( - new URL(process.env.PW_FROM ?? "../../../web/package.json", import.meta.url), -); -const { chromium } = require("playwright"); - -const BASE = process.env.BASE ?? "http://localhost:3784"; -const API_BASE = process.env.API_BASE ?? "http://localhost:8001"; -const EXPECT_VERSION = process.env.EXPECT_VERSION ?? "v1.6.1"; -const OUT = - process.env.OUT ?? new URL("../public/screenshots/guide", import.meta.url).pathname; -const ROOT_OUT = dirname(OUT); - -// The bundled chromium is older than the pdf.js build the reader ships, and -// fails to render a PDF at all (`getOrInsertComputed is not a function`). -// Installed Chrome is current, and playwright still gives it a throwaway -// profile — so the reading shots need `channel: "chrome"` and everything else -// is happy with it too. -const browser = await chromium.launch({ channel: process.env.PW_CHANNEL ?? "chrome" }); -const ctx = await browser.newContext({ - viewport: { width: 1470, height: 836 }, - deviceScaleFactor: 2, - colorScheme: "light", -}); -// Collapse the Recents list: it is the one part of the chrome that renders the -// operator's own session titles into a published image. -await ctx.addInitScript(() => { - try { - localStorage.setItem("deeptutor.sidebar.recentsCollapsed", "1"); - } catch {} -}); -const page = await ctx.newPage(); - -// Settings should demonstrate the memory card without publishing the capture -// machine's RAM size or current process footprint. The values are synthetic, -// stable, and scoped to this disposable browser context. -await page.route("**/api/v1/system/memory", async (route) => { - await route.fulfill({ - status: 200, - contentType: "application/json", - body: JSON.stringify({ - available: true, - total_rss_bytes: 100663296, - limit_bytes: 2147483648, - available_bytes: 1610612736, - limit_source: "cgroup-v2", - usage_ratio: 0.046875, - partial: false, - processes: [{ label: "backend", count: 1, rss_bytes: 100663296 }], - }), - }); -}); - -async function go(path, delay = 1800) { - const response = await page.goto(BASE + path, { - waitUntil: "networkidle", - timeout: 45000, - }); - const landedOnRequestedDocument = page.url().startsWith(BASE + path); - if ((!response && !landedOnRequestedDocument) || (response && response.status() >= 400)) { - throw new Error(`navigation failed for ${path}: ${response?.status() ?? "no response"}`); - } - await page.waitForTimeout(delay); - const hash = path.includes("#") ? path.split("#", 2)[1] : ""; - if (hash) { - const target = page.locator(`#${hash}`); - await target.scrollIntoViewIfNeeded().catch(() => {}); - await page.waitForTimeout(400); - } - await dismissDevOverlay(); -} - -async function dismissDevOverlay() { - await assertNoDevError(); - await page.evaluate(() => { - document.querySelectorAll("nextjs-portal").forEach((node) => node.remove()); - if (!document.querySelector("style[data-docs-capture-clean]")) { - const style = document.createElement("style"); - style.dataset.docsCaptureClean = "true"; - style.textContent = "nextjs-portal{display:none!important;pointer-events:none!important}"; - document.head.appendChild(style); - } - }); -} - -async function assertNoDevError() { - const text = await page.evaluate(() => - Array.from(document.querySelectorAll("nextjs-portal")) - .map((node) => node.shadowRoot?.textContent ?? node.textContent ?? "") - .join("\n"), - ); - if (/\b\d+\s+Issues?\b|Unhandled Runtime Error|Build Error/i.test(text)) { - throw new Error(`Next.js reported a capture-blocking issue: ${text.slice(0, 500)}`); - } -} - -async function assertRelease() { - await go("/home", 500); - const badge = page.locator(`a[title="${EXPECT_VERSION}"]`).first(); - if (!(await badge.isVisible().catch(() => false))) { - const body = (await page.locator("body").innerText()).slice(0, 500); - throw new Error( - `expected ${EXPECT_VERSION} release badge before capture; page starts: ${body}`, - ); - } -} - -async function shot(name, opts = {}) { - const path = `${OUT}/${name}.png`; - await shotTo(path, opts); - console.log("shot", name); -} - -async function shotRoot(name, opts = {}) { - const path = `${ROOT_OUT}/${name}.png`; - await shotTo(path, opts); - console.log("shot", name); -} - -async function shotTo(path, opts = {}) { - await mkdir(dirname(path), { recursive: true }); - // Never publish a screenshot from a page that Next itself considers broken. - // The portal is removed only after this assertion so a real warning cannot - // be silently hidden by the capture harness. - await assertNoDevError(); - await dismissDevOverlay(); - await page.waitForTimeout(100); - await page.screenshot({ path, ...opts }); -} - -/** Screenshot one element plus a margin, for menus and popovers. */ -async function shotRegion(name, selector, pad = 16) { - const target = page.locator(selector).first(); - await target.waitFor({ state: "visible", timeout: 3000 }).catch(() => {}); - const box = await target.boundingBox().catch(() => null); - if (!box) { - // The popup shell changed across releases. A full-page shot still records - // the visible semantic state and is safer than publishing an old image. - await shot(name); - return; - } - const clip = { - x: Math.max(0, box.x - pad), - y: Math.max(0, box.y - pad), - width: Math.min(1470 - Math.max(0, box.x - pad), box.width + pad * 2), - height: Math.min(836 - Math.max(0, box.y - pad), box.height + pad * 2), - }; - await shot(name, { clip }); -} - -// --------------------------------------------------------------------------- -// Jobs -// --------------------------------------------------------------------------- - -/** Plain "navigate and shoot" pages: job -> [route, output name]. */ -const PAGE_JOBS = { - overview: ["/home", "OVERVIEW"], - "home-overview": ["/home", "home/00-overview"], - knowledge: ["/knowledge", "knowledge/00-overview"], - "rag-integrations": ["/knowledge?section=engines", "ecosystem/rag/00-integrations"], - "learning-space": ["/space", "learning-space/00-overview"], - "chat-history": ["/space/chat-history", "learning-space/01-chat-history"], - notebook: ["/notebook", "notebook/00-console"], - questions: ["/space/questions", "learning-space/03-question-bank"], - "ecosystem-overview": ["/space", "ecosystem/OVERVIEW"], - skills: ["/space/skills", "ecosystem/skills/00-overview"], - personas: ["/space/personas", "learning-space/05-personas"], - "mcp-installed": ["/space/mcp", "ecosystem/mcp/00-installed"], - "cli-apps-installed": ["/space/cli-apps", "ecosystem/cli-apps/00-installed"], - mastery: ["/mastery", "mastery-path/00-overview"], - settings: ["/settings", "settings/00-setting-overview"], - "settings-video": ["/settings#video-learning", "settings/04-video-learning"], - "settings-agents": ["/settings#agents", "settings/05-partners-agents"], - "settings-about": ["/settings#about", "settings/06-about-update"], - "settings-appearance": ["/settings/appearance", "settings/01-appearance-settings"], - "settings-chat": ["/settings/chat", "home/11-configure-and-explore-tools"], - "settings-models": ["/settings/models", "home/10-configure-models"], - "settings-starters": ["/settings/starters", "settings/03-starting-points"], - "settings-memory": ["/settings/memory", "memory/02-config-memory-params-in-settings"], - "settings-parsing": [ - "/settings/document-parsing", - "knowledge/03-config-document-parsing-engine-in-settings", - ], - memory: ["/memory", "memory/00-overview"], - "memory-graph": ["/memory/graph", "memory/01-3-layer-memory-graph"], - book: ["/book", "book/00-book-overview"], - "co-writer": ["/co-writer", "co-writer/00-overview"], - agents: ["/agents", "myagents/00-overview"], - partners: ["/partners", "partners/00-partners-overview"], -}; - -/** The composer's capability button — its accessible name is the active mode. */ -const capButton = (label = "Chat") => page.getByRole("button", { name: label, exact: true }); - -/** Open the reader on the most recently read material. */ -async function openReader() { - await go("/reading"); - const collection = page.getByRole("link", { name: /Signal Processing Reading List/ }); - const href = await collection.getAttribute("href"); - if (!href) throw new Error("demo reading collection has no workspace URL"); - await go(href, 3500); -} - -/** Interactive jobs that have to click something first. */ -const FLOW_JOBS = { - // The capability picker, open. Clipped to the popup so the menu is legible. - async capabilities() { - await go("/home"); - await capButton().click(); - await page.waitForTimeout(700); - await shotRegion("home/01-capabilities", ".dt-popup-up", 24); - }, - - // The `+` context menu, open. - async "add-contexts"() { - await go("/home"); - await page.locator('button[aria-label="Add files & context"]').first().click(); - await page.waitForTimeout(700); - await shotRegion("home/02-add-contexts", ".absolute.bottom-full.left-0.z-50 > div", 24); - }, - - // Sticky-context popovers on the right of the composer toolbar. - async knowledge_picker() { - await go("/home"); - await page.locator('button[aria-label="Select knowledge bases"]').click(); - await page.waitForTimeout(700); - await shotRegion("home/04-attatch-knowledge-base", ".dt-popup-up", 24); - }, - async persona_picker() { - await go("/home"); - await page.locator('button[aria-label="Select persona"]').click(); - await page.waitForTimeout(700); - await shotRegion("home/05-customize-persona", ".dt-popup-up", 24); - }, - async model_picker() { - await go("/home"); - await page.locator('button[aria-label="Select model"]').click(); - await page.waitForTimeout(700); - await shotRegion("home/06-switch-model", ".dt-popup-up", 24); - }, - - async activity_panel() { - await go("/home"); - await page.getByRole("button", { name: "Activity", exact: true }).click(); - await page.waitForTimeout(700); - await shot("home/07-side-bar-for-various-activities"); - }, - - async connected_agent_picker() { - await go("/home"); - await page - .getByRole("button", { name: "Select a connected agent", exact: true }) - .click(); - await page.waitForTimeout(500); - await shotRegion("home/03-use-subagent", ".dt-popup-up", 24); - }, - - async agent_mention() { - await go("/home"); - const input = page.getByRole("textbox", { - name: "How can I help you today?", - exact: true, - }); - await input.fill("@"); - await page.getByRole("listbox", { name: "Talk to an agent" }).waitFor(); - await shotRegion("home/03-another-use-subagent", '[role="listbox"]', 24); - }, - - async immersive_watching() { - await go("/home"); - await capButton().click(); - await page.locator(".dt-popup-up").getByRole("button", { name: /^Immersive Watching/ }).click(); - await page.getByPlaceholder("https://youtu.be/…", { exact: true }).waitFor(); - await shot("home/12-immersive-watching"); - }, - - async visualizer_types() { - await go("/home"); - await capButton().click(); - await page.locator(".dt-popup-up").getByRole("button", { name: /^Visualize/ }).click(); - await page.getByText("Visualizer Types", { exact: true }).waitFor(); - await shot("home/13-visualizer-types"); - }, - - async myagents_add() { - await go("/agents"); - await page.getByRole("button", { name: "Add agent", exact: true }).click(); - await page.getByRole("dialog").waitFor(); - await shot("myagents/01-sync-selective-chat-history-from-claude-code-or-codex"); - }, - - async partner_chat() { - await go("/partners/sage"); - await shot("partners/01-chat-with-partners"); - }, - - async partner_channels() { - await go("/partners/sage"); - await page.getByRole("button", { name: "Channels", exact: true }).click(); - await page.waitForTimeout(700); - await shot("partners/02-im-config-for-each-partner"); - }, - - async partner_channel_status() { - await go("/partners/sage"); - await page.getByRole("button", { name: "Channels", exact: true }).click(); - await page.getByRole("button", { name: /^Telegram/ }).click(); - await page.getByText("Status: Configuration required", { exact: true }).waitFor(); - await shot("partners/03-channel-status"); - }, - - async channel_forms() { - const channels = [ - ["WeChat", "weixin"], - ["WeCom", "wecom"], - ["QQ", "qq"], - ["QQ (NapCat)", "napcat"], - ["Telegram", "telegram"], - ["Discord", "discord"], - ["Slack", "slack"], - ["Feishu", "feishu"], - ["DingTalk", "dingtalk"], - ["Zulip", "zulip"], - ["Mattermost", "mattermost"], - ["WhatsApp", "whatsapp"], - ["Email", "email"], - ["Mochat", "mochat"], - ["Microsoft Teams", "msteams"], - ]; - await go("/partners/sage"); - await page.getByRole("button", { name: "Channels", exact: true }).click(); - for (const [label, slug] of channels) { - const prefix = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - await page - .getByRole("button", { name: new RegExp(`^${prefix}(?:\\s+Enabled)?$`) }) - .click(); - await page.waitForTimeout(300); - await shotRoot(`partners-channel-${slug}`); - } - }, - - async multi_user() { - await go("/admin/users"); - await shotRoot("multi-user"); - }, - - async knowledge_create() { - await go("/knowledge"); - await page.getByRole("button", { name: "New knowledge base", exact: true }).click(); - await page.getByRole("dialog").waitFor(); - await shot("knowledge/01-create-knowledge-base"); - }, - - async knowledge_panel() { - await go("/knowledge"); - const kb = page.getByText("Signal Processing Notes", { exact: true }); - await kb.scrollIntoViewIfNeeded(); - await kb.click(); - await page.waitForTimeout(900); - await shot("knowledge/02-panel-for-each-knowledge-base"); - }, - - async mastery_study() { - const response = await fetch(`${API_BASE}/api/v1/learning/topics`); - if (!response.ok) throw new Error(`mastery topic lookup failed: ${response.status}`); - const payload = await response.json(); - const topics = Array.isArray(payload) ? payload : payload.topics ?? payload.data ?? []; - const topic = topics.find((item) => item.name === "Fourier Transform Foundations"); - const pathId = topic?.path_id ?? topic?.book_id ?? topic?.id; - if (!pathId) throw new Error("demo mastery topic was not found"); - await go(`/mastery/${encodeURIComponent(pathId)}/study`, 2500); - const activity = page.getByRole("button", { name: "Activity", exact: true }); - await activity.waitFor(); - await activity.click(); - await page.getByText("Session activity", { exact: true }).waitFor(); - await shot("mastery-path/01-study-workspace"); - }, - - async cowriter_editor() { - await go("/co-writer"); - await page.getByText("Fourier Transform Study Notes", { exact: true }).click(); - await page.waitForTimeout(1000); - await shot("co-writer/01-edit-panel"); - }, - - async book_quiz() { - await go("/book?book=docs_fourier&page=pg_foundations", 2500); - await page.locator('[data-block-id="blk_quiz"]').scrollIntoViewIfNeeded(); - await shot("book/01-book-demo-quiz-card"); - }, - - async book_animation() { - await go("/book?book=docs_fourier&page=pg_visual", 2500); - await page.locator('[data-block-id="blk_animation"]').scrollIntoViewIfNeeded(); - await shot("book/02-book-demo-manim-video"); - }, - - async book_interactive() { - await go("/book?book=docs_fourier&page=pg_interactive", 2500); - await page.locator('[data-block-id="blk_interactive"]').scrollIntoViewIfNeeded(); - await shot("book/03-book-demo-interactive-module"); - }, - - async book_mermaid_chat() { - await go("/book?book=docs_fourier&page=pg_visual", 2500); - await page.locator('[data-block-id="blk_mermaid"]').scrollIntoViewIfNeeded(); - await dismissDevOverlay(); - await page.getByRole("button", { name: "Chat", exact: true }).click({ force: true }); - await page.getByText("Page Chat", { exact: true }).waitFor(); - await shot("book/04-book-demo-side-chat-mermaid"); - }, - - async book_insert_menu() { - await go("/book?book=docs_fourier&page=pg_foundations", 2500); - const button = page.getByRole("button", { name: "Insert block", exact: true }); - await button.scrollIntoViewIfNeeded(); - await button.click(); - await page.waitForTimeout(300); - await shot("book/05-book-add-customize-block-for-chapter"); - }, - - async book_change_type() { - await go("/book?book=docs_fourier&page=pg_foundations", 2500); - const block = page.locator('[data-block-id="blk_intro"]'); - await block.scrollIntoViewIfNeeded(); - await block.hover(); - await page.getByTitle("Change type").first().click(); - await page.waitForTimeout(300); - await shot("book/06-book-switch-the-block-type"); - }, - - // The MCP + CLI stores land on their "Installed" tab; the catalog is behind - // the Store tab, and that is the half worth showing. - async "mcp-store-catalog"() { - await go("/space/mcp"); - await page.getByRole("button", { name: /^Store/ }).click(); - await page.waitForTimeout(1500); - await shot("ecosystem/mcp/00-store"); - }, - async "cli-apps-catalog"() { - await go("/space/cli-apps"); - await page.getByRole("button", { name: /^Store/ }).click(); - await page.waitForTimeout(1500); - await shot("ecosystem/cli-apps/00-store"); - }, - - async "eduhub-catalog"() { - await go("/space/skills"); - await page.getByRole("button", { name: "Import from EduHub", exact: true }).click(); - const dialog = page.getByRole("dialog"); - await dialog.waitFor({ state: "visible", timeout: 10000 }); - await dialog.locator("ul li").first().waitFor({ state: "visible", timeout: 30000 }); - await shot("ecosystem/eduhub/00-skill-catalog"); - }, - - // Immersive Reading: the empty state (what you see on entering the mode), - // then the reader with a document open beside the thread. - async "reading-picker"() { - await go("/reading"); - await shot("reading/01-open-a-document"); - }, - async "reading-open"() { - await openReader(); - await shot("reading/00-overview"); - }, - - // A real grounded turn: ask the open document a question and let the answer - // arrive with its page citations. Costs one LLM call against whatever model - // the instance is configured with. - async "reading-answer"() { - await openReader(); - await page.getByRole("textbox").last().fill( - "What problem does this paper say existing RAG tutoring systems fail at? Cite the page.", - ); - await page.locator('button[aria-label="Send"]').click(); - // Let the turn run to completion (locate pre-pass + model + reader jump). - await page.waitForTimeout(60000); - await shot("reading/02-cited-answer"); - }, -}; - -const args = process.argv.slice(2); -const all = [...Object.keys(PAGE_JOBS), ...Object.keys(FLOW_JOBS)]; -if (args.length === 0) { - console.log("jobs:\n " + all.join("\n ")); -} else { - await assertRelease(); - const wanted = args[0] === "all" ? all : args; - let failed = 0; - for (const job of wanted) { - try { - if (PAGE_JOBS[job]) { - const [route, name] = PAGE_JOBS[job]; - await go(route); - await shot(name); - } else if (FLOW_JOBS[job]) { - await FLOW_JOBS[job](); - } else { - console.error("unknown job", job); - } - } catch (err) { - failed += 1; - console.error("FAILED", job, "-", err.message); - } - } - if (failed) process.exitCode = 1; -} -await browser.close(); diff --git a/docs/scripts/capture-screenshots.mjs b/docs/scripts/capture-screenshots.mjs deleted file mode 100644 index a9fe7900b..000000000 --- a/docs/scripts/capture-screenshots.mjs +++ /dev/null @@ -1,106 +0,0 @@ -// DeepTutor docs screenshot capture — drives a running DeepTutor web UI and -// writes 1470x836@2x light-theme shots into site/public/screenshots/. -// Needs the `playwright` npm package + chromium (npx playwright install chromium). -// Usage: node capture-screenshots.mjs [job ...] (no args = list jobs) -// PARTNER= node capture-screenshots.mjs channels # per-channel cards -import { chromium } from "playwright"; - -const BASE = process.env.BASE ?? "http://localhost:3784"; -const OUT = process.env.OUT ?? new URL("../public/screenshots", import.meta.url).pathname; -const CHANNELS = [ - "weixin", "wecom", "qq", "napcat", "telegram", "discord", "slack", - "feishu", "dingtalk", "matrix", "zulip", "whatsapp", "email", "mochat", "msteams", -]; -const DISPLAY = { - weixin: "WeChat", wecom: "WeCom", qq: "QQ", napcat: "QQ (NapCat)", - telegram: "Telegram", discord: "Discord", slack: "Slack", feishu: "Feishu", - dingtalk: "DingTalk", matrix: "Matrix", zulip: "Zulip", whatsapp: "WhatsApp", - email: "Email", mochat: "Mochat", msteams: "Microsoft Teams", -}; - -const browser = await chromium.launch(); -const ctx = await browser.newContext({ - viewport: { width: 1470, height: 836 }, - deviceScaleFactor: 2, - colorScheme: "light", -}); -// Hide personal session titles in the sidebar on every page. -await ctx.addInitScript(() => { - try { localStorage.setItem("deeptutor.sidebar.recentsCollapsed", "1"); } catch {} -}); -const page = await ctx.newPage(); - -async function go(path, delay = 1500) { - await page.goto(BASE + path, { waitUntil: "networkidle", timeout: 30000 }).catch(() => {}); - await page.waitForTimeout(delay); -} -async function shot(name) { - await page.screenshot({ path: `${OUT}/${name}.png` }); - console.log("shot", name); -} - -const jobs = { - // simple page shots: job name -> [path, file] - partners: ["/partners", "partners"], - "partners-new": ["/partners/new", "partners-new"], - chat: ["/chat", "chat"], - knowledge: ["/knowledge", "knowledge"], - book: ["/book", "book"], - "co-writer": ["/co-writer", "co-writer"], - learning: ["/learning", "learning"], - space: ["/space", "space"], - memory: ["/memory", "memory"], - "memory-graph": ["/memory/graph", "memory-graph"], - "settings-appearance": ["/settings/appearance", "settings-appearance"], - "settings-llm": ["/settings/llm", "settings-llm"], - "settings-embedding": ["/settings/embedding", "settings-embedding"], - "settings-search": ["/settings/search", "settings-search"], - "settings-mineru": ["/settings/mineru", "settings-mineru"], - "settings-capabilities": ["/settings/capabilities", "settings-capabilities"], - "settings-memory": ["/settings/memory", "settings-memory"], - "settings-mcp": ["/settings/mcp", "settings-mcp"], - "settings-tools": ["/settings/tools", "settings-tools"], - "settings-network": ["/settings/network", "settings-network"], - "settings-status": ["/settings/status", "settings-status"], -}; - -async function openPartnerTab(partnerId, tabText) { - await go(`/partners/${partnerId}`); - await page.click(`button:has-text("${tabText}")`); - await page.waitForTimeout(1200); -} - -async function channelShots(partnerId) { - await openPartnerTab(partnerId, "Channels"); - for (const ch of CHANNELS) { - const label = DISPLAY[ch]; - const btn = page.locator("aside button", { hasText: label }).first(); - await btn.click(); - await page.waitForTimeout(900); - await shot(`partners-channel-${ch}`); - } -} - -const args = process.argv.slice(2); -if (args.length === 0) { - console.log("jobs:", [...Object.keys(jobs), "channels", "partner-detail"].join(" ")); -} else { - for (const a of args) { - if (a === "channels") { - await channelShots(process.env.PARTNER ?? "frank"); - } else if (a === "partner-detail") { - const pid = process.env.PARTNER ?? "frank"; - await openPartnerTab(pid, "Configure"); - await shot("partners-configure"); - await openPartnerTab(pid, "Channels"); - await shot("partners-channels"); - } else if (jobs[a]) { - const [path, file] = jobs[a]; - await go(path); - await shot(file); - } else { - console.error("unknown job", a); - } - } -} -await browser.close(); diff --git a/docs/scripts/check_docs.py b/docs/scripts/check_docs.py index 4e3ba6e27..e4fed368c 100644 --- a/docs/scripts/check_docs.py +++ b/docs/scripts/check_docs.py @@ -5,6 +5,7 @@ from __future__ import annotations import ast import hashlib import json +import os import re import sys from pathlib import Path @@ -104,8 +105,22 @@ def check_gifs() -> list[str]: return errors -def dest_exists(url: str) -> bool: +def _normalized_base() -> str: + raw = os.environ.get("DOCS_BASE", "/").strip() + if raw in {"", "/"}: + return "" + return "/" + raw.strip("/") + + +def dest_exists(url: str, base: str = "") -> bool: path = url.split("#", 1)[0].split("?", 1)[0] + if base: + if path == base: + path = "/" + elif path.startswith(f"{base}/"): + path = path[len(base):] + else: + return False if path in {"", "/"}: return (DIST / "index.html").exists() relative = path.lstrip("/") @@ -235,24 +250,69 @@ def check_channel_schema() -> list[str]: return errors +def check_generated_reference() -> list[str]: + """Ensure generated capabilities and HTTP route index pages match source manifests.""" + import importlib.util + + spec = importlib.util.spec_from_file_location( + "generate_reference", Path(__file__).resolve().with_name("generate_reference.py") + ) + if spec is None or spec.loader is None: + return ["unable to load generate_reference.py"] + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + + errors = [] + for locale, folder in (("en", CONTENT), ("zh", CONTENT / "zh-cn")): + cap_path = folder / "developers" / "reference" / "capabilities.md" + expected_cap = mod.capabilities(locale) + if not cap_path.exists() or cap_path.read_text() != expected_cap: + errors.append( + f"{cap_path.relative_to(ROOT)} drifted; run python3 docs/scripts/generate_reference.py" + ) + http_path = folder / "developers" / "reference" / "http-api.md" + if not http_path.exists(): + errors.append(f"{http_path.relative_to(ROOT)} is missing") + continue + actual_http = http_path.read_text() + head = ( + actual_http.split(mod.MARKER, 1)[0].rstrip() + "\n\n" + if mod.MARKER in actual_http + else actual_http.rstrip() + "\n\n" + ) + expected_http = head + mod.route_index(locale) + if actual_http != expected_http: + errors.append( + f"{http_path.relative_to(ROOT)} route index drifted; run python3 docs/scripts/generate_reference.py" + ) + return errors + + def check_links() -> list[str]: if not DIST.exists(): return ["docs/dist is missing; run the docs build first"] + base = _normalized_base() errors = [] for page in DIST.rglob("*.html"): for match in HREF.findall(page.read_text(errors="ignore")): - if match.startswith(("http://", "https://", "mailto:", "data:", "#", "javascript:")): + if match.startswith(("http://", "https://", "mailto:", "data:", "#", "javascript:", "//")): continue if not match.startswith("/"): continue - if not dest_exists(match): + if not dest_exists(match, base): errors.append(f"{page.relative_to(DIST)} -> {match}") return errors def main() -> int: mode = sys.argv[1] if len(sys.argv) > 1 else "source" - errors = check_parity() + check_screenshots() + check_gifs() + check_channel_schema() + errors = ( + check_parity() + + check_screenshots() + + check_gifs() + + check_channel_schema() + + check_generated_reference() + ) if mode == "dist": errors.extend(check_links()) if errors: diff --git a/docs/scripts/gif/compress-gifs.mjs b/docs/scripts/gif/compress-gifs.mjs index f71d99340..ab4130d73 100644 --- a/docs/scripts/gif/compress-gifs.mjs +++ b/docs/scripts/gif/compress-gifs.mjs @@ -18,9 +18,12 @@ function run(command, args) { }); } -export async function compressGifs() { - const names = (await readdir(GIF_DIR)).filter((name) => name.endsWith(".gif")); - for (const name of names) { +export async function compressGifs(targetNames = null) { + const requested = + Array.isArray(targetNames) && targetNames.length > 0 + ? [...new Set(targetNames.map((name) => path.basename(name)).filter((name) => name.endsWith(".gif")))] + : (await readdir(GIF_DIR)).filter((name) => name.endsWith(".gif")); + for (const name of requested) { const input = path.join(GIF_DIR, name); const temp = path.join(GIF_DIR, `.${name}.tmp.gif`); await run("ffmpeg", [ @@ -37,7 +40,8 @@ export async function compressGifs() { } if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) { - compressGifs().catch((error) => { + const cliTargets = process.argv.slice(2); + compressGifs(cliTargets.length > 0 ? cliTargets : null).catch((error) => { console.error(error.message); process.exitCode = 1; }); diff --git a/docs/scripts/gif/webreel-react-type-hook.mjs b/docs/scripts/gif/webreel-react-type-hook.mjs index 03a1a1e98..e1c7fafff 100644 --- a/docs/scripts/gif/webreel-react-type-hook.mjs +++ b/docs/scripts/gif/webreel-react-type-hook.mjs @@ -3,11 +3,17 @@ const MARKER = "for (let i = 0; i < text.length; i++) {\n const char = te const HELPER = `async function syncReactField(client, value) { await client.Runtime.evaluate({ expression: \`(() => { - const fields = [...document.querySelectorAll("textarea")].filter((node) => { + const active = document.activeElement; + const isEditable = (node) => { + if (!(node instanceof HTMLTextAreaElement || node instanceof HTMLInputElement)) return false; const box = node.getBoundingClientRect(); return box.width > 40 && box.height > 16; - }); - const field = fields.sort((left, right) => right.getBoundingClientRect().width - left.getBoundingClientRect().width)[0]; + }; + const field = isEditable(active) + ? active + : [...document.querySelectorAll("textarea")] + .filter(isEditable) + .sort((left, right) => right.getBoundingClientRect().width - left.getBoundingClientRect().width)[0]; if (!field) return; field.focus(); const next = \${JSON.stringify(value)}; diff --git a/docs/scripts/seed-guide-book.py b/docs/scripts/seed-guide-book.py deleted file mode 100644 index f839b48b0..000000000 --- a/docs/scripts/seed-guide-book.py +++ /dev/null @@ -1,249 +0,0 @@ -"""Create a deterministic synthetic Book for v1.6.1 documentation captures. - -Run with the same ``DEEPTUTOR_HOME`` and source checkout as the disposable app: - - PYTHONPATH=/path/to/v1.6.1/source python scripts/seed-guide-book.py - -This bypasses model generation but uses the release's public Book models and -storage layer. It never reads a developer's chats or knowledge bases. -""" - -from __future__ import annotations - -from urllib.parse import quote - -from deeptutor.book.models import ( - Block, - BlockStatus, - BlockType, - Book, - BookInputs, - BookProposal, - BookStatus, - Chapter, - ContentType, - Page, - PageStatus, - Progress, - Spine, -) -from deeptutor.book.storage import BookStorage - - -BOOK_ID = "docs_fourier" - - -def ready(block_type: BlockType, block_id: str, payload: dict) -> Block: - return Block( - id=block_id, - type=block_type, - title="", - status=BlockStatus.READY, - payload=payload, - metadata={"source": "documentation-demo"}, - ) - - -def build_pages() -> list[Page]: - svg = """ - - - - -A signal decomposed into frequencies -Amplitude and phase describe each sinusoidal component. -""" - animation_url = "data:image/svg+xml," + quote(svg) - - interactive = """

Explore sampling frequency

Move the slider to compare the sample rate with a 20 Hz signal.

5 × signal frequency
20 Hz signal100 Hz sampling
""" - - return [ - Page( - id="pg_foundations", - book_id=BOOK_ID, - chapter_id="ch_foundations", - title="From signals to spectra", - learning_objectives=[ - "Connect a waveform with its frequency components", - "Interpret amplitude and phase", - ], - content_type=ContentType.THEORY, - status=PageStatus.READY, - order=0, - blocks=[ - ready( - BlockType.SECTION, - "blk_intro", - { - "intro": "The Fourier transform gives us a second view of the same signal: not how it changes over time, but which frequencies build it.", - "subsections": [ - { - "body": "## Two complementary views\n\nA time-domain plot makes transients easy to see. A frequency-domain plot makes periodic structure, bandwidth, and filtering easier to reason about. Neither view replaces the other.", - } - ], - "key_takeaway": "A Fourier transform changes the representation, not the underlying signal.", - }, - ), - ready( - BlockType.QUIZ, - "blk_quiz", - { - "questions": [ - { - "question_id": "book-q1", - "question": "What does a peak in the magnitude spectrum indicate?", - "question_type": "multiple_choice", - "options": { - "A": "A prominent frequency component", - "B": "A missing time sample", - "C": "A change in units", - "D": "A guaranteed phase shift", - }, - "correct_answer": "A", - "explanation": "Magnitude shows how strongly each frequency contributes.", - "difficulty": "introductory", - } - ] - }, - ), - ], - ), - Page( - id="pg_visual", - book_id=BOOK_ID, - chapter_id="ch_visual", - title="A visual transform pipeline", - learning_objectives=["Follow the path from samples to a spectrum"], - content_type=ContentType.CONCEPT, - status=PageStatus.READY, - order=1, - blocks=[ - ready( - BlockType.FIGURE, - "blk_mermaid", - { - "render_type": "mermaid", - "code": { - "language": "mermaid", - "content": "flowchart LR\n A[Sampled signal] --> B[Window]\n B --> C[FFT]\n C --> D[Magnitude spectrum]\n C --> E[Phase spectrum]", - }, - "description": "A compact map of the transform workflow.", - }, - ), - ready( - BlockType.ANIMATION, - "blk_animation", - { - "video_url": animation_url, - "description": "An animation block can make periodic structure and phase relationships concrete.", - }, - ), - ], - ), - Page( - id="pg_interactive", - book_id=BOOK_ID, - chapter_id="ch_interactive", - title="Sampling without aliasing", - learning_objectives=["Apply the Nyquist criterion"], - content_type=ContentType.PRACTICE, - status=PageStatus.READY, - order=2, - blocks=[ - ready( - BlockType.INTERACTIVE, - "blk_interactive", - { - "code": {"language": "html", "content": interactive}, - "description": "Adjust the sampling-rate ratio and observe the resulting scale.", - }, - ), - ready( - BlockType.CALLOUT, - "blk_callout", - { - "label": "Nyquist checkpoint", - "body": "Sample above twice the highest frequency you need to preserve.", - }, - ), - ], - ), - ] - - -def main() -> None: - storage = BookStorage() - if storage.book_exists(BOOK_ID): - print(f"book already exists: {BOOK_ID}") - return - - pages = build_pages() - chapters = [ - Chapter( - id="ch_foundations", - title="From signals to spectra", - order=0, - content_type=ContentType.THEORY, - learning_objectives=pages[0].learning_objectives, - page_ids=[pages[0].id], - summary="Build an intuitive time-to-frequency mental model.", - ), - Chapter( - id="ch_visual", - title="A visual transform pipeline", - order=1, - content_type=ContentType.CONCEPT, - learning_objectives=pages[1].learning_objectives, - page_ids=[pages[1].id], - summary="See the FFT workflow as a sequence of transformations.", - ), - Chapter( - id="ch_interactive", - title="Sampling without aliasing", - order=2, - content_type=ContentType.PRACTICE, - learning_objectives=pages[2].learning_objectives, - page_ids=[pages[2].id], - summary="Practice the Nyquist criterion with an interactive control.", - ), - ] - storage.save_book( - Book( - id=BOOK_ID, - title="Fourier Transform: An Interactive Primer", - description="Signals, spectra, filtering, and sampling through explanations and interactive blocks.", - status=BookStatus.READY, - proposal=BookProposal( - title="Fourier Transform: An Interactive Primer", - description="A visual and practical introduction.", - target_level="Undergraduate", - estimated_chapters=3, - ), - language="en", - page_count=len(pages), - chapter_count=len(chapters), - metadata={"source": "documentation-demo"}, - ) - ) - storage.save_inputs( - BOOK_ID, - BookInputs( - user_intent="Learn the Fourier transform with visual and interactive examples.", - language="en", - ), - ) - storage.save_spine(Spine(book_id=BOOK_ID, chapters=chapters)) - storage.save_progress(Progress(book_id=BOOK_ID, current_page_id=pages[0].id)) - for page in pages: - storage.save_page(page) - print(f"seeded book: {BOOK_ID}") - - -if __name__ == "__main__": - main() diff --git a/docs/scripts/seed-guide-data.mjs b/docs/scripts/seed-guide-data.mjs deleted file mode 100644 index eab3c9c17..000000000 --- a/docs/scripts/seed-guide-data.mjs +++ /dev/null @@ -1,354 +0,0 @@ -// Seed a disposable DeepTutor instance with synthetic, non-personal content -// before capturing the user guide. Run this only against an isolated -// DEEPTUTOR_HOME; it intentionally creates visible product data. -// -// API_BASE=http://127.0.0.1:18701 node scripts/seed-guide-data.mjs - -// The script calls public v1.6.1 APIs instead of copying a developer's local -// database, so published screenshots contain no account names, private chats, -// tokens, or API keys. - -const API = process.env.API_BASE ?? "http://127.0.0.1:8001"; - -async function request(path, init = {}) { - const response = await fetch(`${API}${path}`, init); - const body = await response.text(); - let data = body; - try { - data = body ? JSON.parse(body) : null; - } catch {} - if (!response.ok) { - throw new Error(`${init.method ?? "GET"} ${path}: ${response.status} ${body}`); - } - return data; -} - -const json = (method, body) => ({ - method, - headers: { "content-type": "application/json" }, - body: JSON.stringify(body), -}); - -function rows(payload, key) { - if (Array.isArray(payload)) return payload; - if (Array.isArray(payload?.[key])) return payload[key]; - if (Array.isArray(payload?.data)) return payload.data; - return []; -} - -async function seedPartner() { - const existing = rows(await request("/api/v1/partners"), "partners"); - if (existing.some((partner) => partner.id === "sage" || partner.partner_id === "sage")) { - return; - } - await request( - "/api/v1/partners", - json("POST", { - partner_id: "sage", - name: "Sage", - description: "A calm study partner for explaining concepts and planning reviews.", - emoji: "🌿", - color: "#4F8A6B", - language: "en", - enabled_tools: ["web_search", "paper_search", "reason"], - start: false, - }), - ); -} - -async function seedPartnerChannelStatus() { - await request( - "/api/v1/partners/sage", - json("PATCH", { - channels: { - telegram: { - enabled: true, - token: "", - allow_from: ["docs-user"], - }, - }, - }), - ); - await request("/api/v1/partners/sage/start", json("POST", {})); -} - -async function seedSafeNetworkDisplay() { - const current = await request("/api/v1/settings/network"); - const settings = current.settings ?? {}; - await request( - "/api/v1/settings/network", - json("PUT", { - backend_port: settings.backend_port ?? 8001, - frontend_port: settings.frontend_port ?? 3782, - public_api_base: "http://localhost:8001", - cors_origins: [], - }), - ); -} - -async function seedCoWriter() { - const existing = rows(await request("/api/v1/co_writer/documents"), "documents"); - if (existing.some((document) => document.title === "Fourier Transform Study Notes")) { - return; - } - await request( - "/api/v1/co_writer/documents", - json("POST", { - title: "Fourier Transform Study Notes", - content: [ - "# Fourier Transform Study Notes", - "", - "## Core idea", - "The Fourier transform represents a signal as a weighted combination of frequencies.", - "", - "## Review checklist", - "- Relate time-domain features to the frequency domain.", - "- Explain amplitude and phase spectra.", - "- Practice the convolution theorem with one worked example.", - ].join("\n"), - }), - ); -} - -async function seedNotebook() { - const existing = rows(await request("/api/v1/notebook/list"), "notebooks"); - let notebook = existing.find((item) => item.name === "Signal Processing Lab"); - if (!notebook) { - const created = await request( - "/api/v1/notebook/create", - json("POST", { - name: "Signal Processing Lab", - description: "Key explanations, examples, and follow-up questions.", - color: "#6366F1", - icon: "book-open", - }), - ); - notebook = created.notebook; - } - if (!notebook?.id) throw new Error("Notebook seed did not return an id."); - const detail = await request(`/api/v1/notebook/${notebook.id}`); - const records = rows(detail?.notebook ?? detail, "records"); - if (records.length === 0) { - await request( - "/api/v1/notebook/add_record", - json("POST", { - notebook_ids: [notebook.id], - record_type: "chat", - title: "Why frequency-domain views help", - summary: "A compact comparison of time-domain and frequency-domain reasoning.", - user_query: "When is the frequency domain more useful than the time domain?", - output: - "The frequency domain makes periodic structure, bandwidth, filtering, and convolution easier to inspect. The time domain remains best for timing and transient behavior.", - metadata: { source: "documentation-demo" }, - }), - ); - await request( - "/api/v1/notebook/add_record", - json("POST", { - notebook_ids: [notebook.id], - record_type: "solve", - title: "Convolution theorem", - summary: "Convolution in time corresponds to multiplication in frequency.", - user_query: "State the convolution theorem.", - output: "If y(t) = x(t) * h(t), then Y(f) = X(f)H(f).", - metadata: { source: "documentation-demo" }, - }), - ); - } -} - -async function seedQuestionBank() { - const existing = rows(await request("/api/v1/question-notebook/entries?limit=100"), "entries"); - if (existing.some((entry) => entry.question_id === "docs-fourier-1")) return; - const workspaces = rows(await request("/api/v1/reading/workspaces"), "workspaces"); - const workspace = workspaces.find( - (item) => item.title === "Signal Processing Reading List", - ); - if (!workspace?.workspace_id) { - throw new Error("Create the demo reading workspace before the question bank."); - } - const linked = rows( - await request(`/api/v1/reading/workspaces/${workspace.workspace_id}/sessions`), - "sessions", - ); - let session = linked.find((item) => item.title === "Fourier practice review"); - if (!session) { - const created = await request( - `/api/v1/reading/workspaces/${workspace.workspace_id}/sessions`, - json("POST", { - title: "Fourier practice review", - active_material_id: workspace.active_material_id, - }), - ); - session = created.session; - } - await request( - "/api/v1/question-notebook/entries/upsert", - json("POST", { - session_id: session.session_id, - turn_id: "docs-demo-turn", - question_id: "docs-fourier-1", - question: "Which operation in the frequency domain corresponds to convolution in time?", - question_type: "multiple_choice", - options: { - A: "Addition", - B: "Multiplication", - C: "Differentiation", - D: "Time reversal", - }, - correct_answer: "B", - explanation: "The convolution theorem maps time-domain convolution to multiplication.", - difficulty: "medium", - user_answer: "B", - is_correct: true, - }), - ); -} - -async function seedMasteryPath() { - const existing = rows(await request("/api/v1/learning/topics"), "topics"); - if (existing.some((topic) => topic.name === "Fourier Transform Foundations")) return; - await request( - "/api/v1/learning/topics", - json("POST", { - name: "Fourier Transform Foundations", - goal: "Build an intuitive and practical understanding of frequency-domain analysis.", - description: "A guided route from signals and sinusoids to filtering and convolution.", - emoji: "〰️", - modules: [ - { - name: "Signals and frequency", - knowledge_points: [ - { name: "Sinusoids, amplitude, and phase", type: "concept" }, - { name: "Time-domain and frequency-domain views", type: "concept" }, - ], - }, - { - name: "Transform toolkit", - knowledge_points: [ - { name: "Fourier transform pairs", type: "memory" }, - { name: "Convolution theorem", type: "procedure" }, - ], - }, - { - name: "Apply and explain", - knowledge_points: [ - { name: "Design a simple frequency filter", type: "design" }, - { name: "Explain spectral leakage", type: "concept" }, - ], - }, - ], - }), - ); -} - -async function seedReading() { - const existing = rows(await request("/api/v1/reading/library/materials"), "materials"); - let material = existing.find((item) => item.filename === "fourier-primer.md"); - if (!material) { - const form = new FormData(); - form.set( - "file", - new Blob( - [ - "# Fourier Transform Primer\n\n", - "A signal can be described by how it changes over time or by the frequencies it contains.\n\n", - "## Convolution theorem\n\n", - "Convolution in the time domain becomes multiplication in the frequency domain. ", - "This is why many filters are easier to analyze after a Fourier transform.\n\n", - "## Sampling\n\n", - "To avoid aliasing, a sampling rate must exceed twice the highest frequency of interest.\n", - ], - { type: "text/markdown" }, - ), - "fourier-primer.md", - ); - material = await request("/api/v1/reading/materials", { method: "POST", body: form }); - } - const materialId = material.material_id ?? material.id; - if (!materialId) throw new Error("Reading material seed did not return an id."); - const workspaces = rows(await request("/api/v1/reading/workspaces"), "workspaces"); - if (!workspaces.some((workspace) => workspace.title === "Signal Processing Reading List")) { - await request( - "/api/v1/reading/workspaces", - json("POST", { - title: "Signal Processing Reading List", - description: "A small collection for reviewing transforms, filtering, and sampling.", - material_ids: [materialId], - }), - ); - } -} - -async function seedKnowledgeSpace() { - const existing = rows(await request("/api/v1/knowledge/list"), "knowledge_bases"); - if (existing.some((kb) => kb.name === "Signal Processing Notes")) return; - const form = new FormData(); - form.set("name", "Signal Processing Notes"); - form.set("rag_provider", "llamaindex"); - await request("/api/v1/knowledge/create", { method: "POST", body: form }); -} - -async function seedModelCatalog() { - const current = await request("/api/v1/settings/catalog"); - const catalog = current.catalog; - const service = catalog.services.llm; - if (service.profiles.some((profile) => profile.id === "docs-local-llm")) return; - service.active_profile_id = "docs-local-llm"; - service.active_model_id = "docs-local-model"; - service.profiles.push({ - id: "docs-local-llm", - name: "Local study model", - binding: "llama_cpp", - base_url: "http://127.0.0.1:8080/v1", - api_key: "", - api_version: "", - extra_headers: {}, - models: [ - { - id: "docs-local-model", - name: "Documentation Demo Model", - model: "demo-instruct", - context_window: 32768, - }, - ], - }); - await request("/api/v1/settings/catalog", json("PUT", { catalog })); -} - -async function seedConnectedAgent() { - const existing = rows(await request("/api/v1/subagents/connections"), "connections"); - if (existing.some((connection) => connection.name === "Sage")) return; - await request( - "/api/v1/subagents/connections", - json("POST", { - name: "Sage", - agent_kind: "partner", - partner_id: "sage", - }), - ); -} - -const tasks = [ - ["partner", seedPartner], - ["partner channel status", seedPartnerChannelStatus], - ["co-writer", seedCoWriter], - ["notebook", seedNotebook], - ["mastery path", seedMasteryPath], - ["immersive reading", seedReading], - ["question bank", seedQuestionBank], - ["knowledge space", seedKnowledgeSpace], - ["model catalog", seedModelCatalog], - ["connected agent", seedConnectedAgent], - ["safe network display", seedSafeNetworkDisplay], -]; - -for (const [label, task] of tasks) { - try { - await task(); - console.log(`seeded ${label}`); - } catch (error) { - console.error(`FAILED ${label}: ${error.message}`); - process.exitCode = 1; - } -} diff --git a/docs/scripts/update-gifs.mjs b/docs/scripts/update-gifs.mjs index 50e3138e8..7e105df02 100644 --- a/docs/scripts/update-gifs.mjs +++ b/docs/scripts/update-gifs.mjs @@ -1,6 +1,7 @@ import { spawn } from "node:child_process"; +import { readFileSync } from "node:fs"; import path from "node:path"; -import { fileURLToPath } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { compressGifs } from "./gif/compress-gifs.mjs"; @@ -8,6 +9,13 @@ const DOCS_ROOT = path.resolve(fileURLToPath(new URL("..", import.meta.url))); const hook = path.join(DOCS_ROOT, "scripts", "gif", "webreel-react-type.mjs"); const names = process.argv.slice(2); +const config = JSON.parse(readFileSync(path.join(DOCS_ROOT, "webreel.config.json"), "utf8")); +const videos = config.videos ?? {}; +const targets = + names.length > 0 + ? names.map((name) => videos[name]?.output ?? `${name}.gif`) + : Object.entries(videos).map(([name, spec]) => spec?.output ?? `${name}.gif`); + const child = spawn( path.join(DOCS_ROOT, "node_modules", ".bin", "webreel"), ["record", "-c", "webreel.config.json", ...names], @@ -16,7 +24,9 @@ const child = spawn( stdio: "inherit", env: { ...process.env, - NODE_OPTIONS: [process.env.NODE_OPTIONS, `--import ${hook}`].filter(Boolean).join(" "), + NODE_OPTIONS: [process.env.NODE_OPTIONS, `--import=${pathToFileURL(hook).href}`] + .filter(Boolean) + .join(" "), }, }, ); @@ -26,7 +36,7 @@ child.on("close", (code) => { process.exitCode = code ?? 1; return; } - compressGifs().catch((error) => { + compressGifs(targets).catch((error) => { console.error(error.message); process.exitCode = 1; }); diff --git a/docs/src/components/HomeLanding.astro b/docs/src/components/HomeLanding.astro index 71c173483..b182a886f 100644 --- a/docs/src/components/HomeLanding.astro +++ b/docs/src/components/HomeLanding.astro @@ -5,7 +5,8 @@ interface Props { const { locale = "en" } = Astro.props; const zh = locale === "zh"; -const root = zh ? "/zh-cn" : ""; +const base = import.meta.env.BASE_URL.replace(/\/$/, ""); +const root = zh ? `${base}/zh-cn` : base; const copy = zh ? { @@ -44,9 +45,6 @@ const copy = zh footerMid: ",连接", footerEm2: "世界", footerEnd: "。", - footerLatest: "最新:", - visits: "次访问", - requests: "次请求", credit: "香港大学数据智能实验室", license: "基于 Apache 2.0 协议发布", } @@ -87,9 +85,6 @@ const copy = zh footerMid: ", to ", footerEm2: "the world", footerEnd: ".", - footerLatest: "Latest:", - visits: "Visits", - requests: "Requests", credit: "Data Intelligence Lab @ The University of Hong Kong", license: "Released under the Apache 2.0 License", }; @@ -123,7 +118,7 @@ const installs = zh mark: "I", name: "PyPI", tag: "推荐", - blurb: "1.7.0 发布后的完整 Web 应用 + CLI 安装方式。现在体验 dev 请选源码。", + blurb: "已发布的完整 Web 应用 + CLI 包(1.7+ 模块化安装)。需要最新 dev 请选源码。", code: `# 1. 准备运行数据目录\nmkdir -p my-deeptutor && cd my-deeptutor\n\n# 2. 安装、配置、启动\npip install -U "deeptutor[full]"\ndeeptutor init\ndeeptutor start`, note: "然后打开 127.0.0.1:3782", href: `${root}/self-hosting/pypi/`, @@ -164,8 +159,8 @@ const installs = zh id: "pypi", mark: "I", name: "PyPI", - tag: "After 1.7.0", - blurb: "Full Web app + CLI after 1.7.0 publication. Use Source to try the current dev now.", + tag: "Recommended", + blurb: "Published full Web app + CLI package (modular 1.7+ layout). Use Source to run current dev.", code: `# 1. Choose a runtime-home directory\nmkdir -p my-deeptutor && cd my-deeptutor\n\n# 2. Install, configure, launch\npip install -U "deeptutor[full]"\ndeeptutor init\ndeeptutor start`, note: "Then open 127.0.0.1:3782", href: `${root}/self-hosting/pypi/`, @@ -220,8 +215,8 @@ const arrow = ` - - DeepTutor + + DeepTutor