mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-03 09:20:08 +08:00
ci: add automated github pages deployment for PR documentation previews
This commit is contained in:
311
.github/workflows/docs.yml
vendored
311
.github/workflows/docs.yml
vendored
@@ -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-<number>/` 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 = "<!-- deeptutor-docs-preview -->";
|
||||
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 = "<!-- deeptutor-docs-preview -->";
|
||||
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.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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-<number>/`, then post or update a comment on the PR with links to both locales. Closing the PR removes `pr-<number>/` 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
|
||||
```
|
||||
|
||||
@@ -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 `/<repo>/pr-<number>`), 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(
|
||||
/(<meta\s+http-equiv=["']refresh["'][^>]*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),
|
||||
],
|
||||
});
|
||||
|
||||
21
docs/package-lock.json
generated
21
docs/package-lock.json
generated
@@ -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",
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
"sharp": "^0.34.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"i18n-iso-countries": "^7.14.0",
|
||||
"webreel": "^0.1.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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/<dir>/.
|
||||
//
|
||||
// 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 <job ...>
|
||||
// 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();
|
||||
@@ -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=<id> 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();
|
||||
@@ -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:
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -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)};
|
||||
|
||||
@@ -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 = """<svg xmlns='http://www.w3.org/2000/svg' width='960' height='420' viewBox='0 0 960 420'>
|
||||
<defs><linearGradient id='g' x1='0' x2='1'><stop stop-color='#dbeafe'/><stop offset='1' stop-color='#ede9fe'/></linearGradient></defs>
|
||||
<rect width='960' height='420' rx='24' fill='url(#g)'/>
|
||||
<path d='M70 230 C150 80 230 80 310 230 S470 380 550 230 S710 80 790 230 S870 380 930 250' fill='none' stroke='#2563eb' stroke-width='8'/>
|
||||
<circle cx='310' cy='230' r='11' fill='#7c3aed'/><circle cx='550' cy='230' r='11' fill='#7c3aed'/>
|
||||
<text x='55' y='70' font-family='sans-serif' font-size='34' fill='#172554'>A signal decomposed into frequencies</text>
|
||||
<text x='55' y='115' font-family='sans-serif' font-size='20' fill='#475569'>Amplitude and phase describe each sinusoidal component.</text>
|
||||
</svg>"""
|
||||
animation_url = "data:image/svg+xml," + quote(svg)
|
||||
|
||||
interactive = """<!doctype html><html><head><meta charset='utf-8'><style>
|
||||
body{font-family:system-ui;margin:0;background:#f8fafc;color:#172554}.card{padding:22px}
|
||||
h2{margin:0 0 8px}.plot{height:130px;border-radius:14px;background:linear-gradient(90deg,#dbeafe,#ede9fe);display:grid;place-items:center;margin:18px 0;font-size:34px;color:#2563eb}
|
||||
input{width:100%}.row{display:flex;justify-content:space-between;color:#475569}
|
||||
</style></head><body><div class='card'><h2>Explore sampling frequency</h2><p>Move the slider to compare the sample rate with a 20 Hz signal.</p><div id='plot' class='plot'>5 × signal frequency</div><input id='rate' type='range' min='1' max='10' value='5'><div class='row'><span>20 Hz signal</span><strong id='label'>100 Hz sampling</strong></div></div><script>
|
||||
const r=document.querySelector('#rate'),p=document.querySelector('#plot'),l=document.querySelector('#label');r.oninput=()=>{p.textContent=r.value+' × signal frequency';l.textContent=(20*r.value)+' Hz sampling'};
|
||||
</script></body></html>"""
|
||||
|
||||
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()
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -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 = `<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-
|
||||
</defs>
|
||||
<path d="M3 11 L11.2 4.4 Q12 3.7 12.8 4.4 L21 11 M5.6 9.6 L5.6 19 Q5.6 20 6.6 20 L17.4 20 Q18.4 20 18.4 19 L18.4 9.6 M9.8 20 L9.8 15.6 Q9.8 13.6 12 13.6 Q14.2 13.6 14.2 15.6 L14.2 20" stroke="url(#dt-home-grad)" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</svg>
|
||||
<img class="nav-brand-mark" src="/brand/color-logo.png" alt="" aria-hidden="true" />
|
||||
<img class="nav-brand-wordmark" src="/brand/color-word.png" alt="DeepTutor" />
|
||||
<img class="nav-brand-mark" src={`${base}/brand/color-logo.png`} alt="" aria-hidden="true" />
|
||||
<img class="nav-brand-wordmark" src={`${base}/brand/color-word.png`} alt="DeepTutor" />
|
||||
</a>
|
||||
<nav class="nav-links">
|
||||
<a class="nav-text" href={`${root}/welcome/`}>{copy.docs}</a>
|
||||
@@ -253,9 +248,9 @@ const arrow = `<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-
|
||||
</label>
|
||||
<label class="nav-tool" aria-label={copy.language}>
|
||||
<svg class="nav-tool-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9.5"></circle><path d="M2.5 12h19"></path><path d="M12 2.5a14 14 0 0 1 4 9.5 14 14 0 0 1-4 9.5 14 14 0 0 1-4-9.5 14 14 0 0 1 4-9.5z"></path></svg>
|
||||
<select class="nav-select" data-locale-select aria-label={copy.language}>
|
||||
<option value="/" selected={!zh}>English</option>
|
||||
<option value="/zh-cn/" selected={zh}>简体中文</option>
|
||||
<select class="nav-select" data-locale-select data-base={base} aria-label={copy.language}>
|
||||
<option value={`${base}/`} selected={!zh}>English</option>
|
||||
<option value={`${base}/zh-cn/`} selected={zh}>简体中文</option>
|
||||
</select>
|
||||
<svg class="nav-tool-caret" width="10" height="10" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 4.5 6 7.5 9 4.5"></polyline></svg>
|
||||
</label>
|
||||
@@ -266,7 +261,7 @@ const arrow = `<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-
|
||||
<main>
|
||||
<section class="hero">
|
||||
<div class="hero-bg" aria-hidden="true"></div>
|
||||
<img class="hero-wordmark" src="/brand/color-word.png" alt="DeepTutor" />
|
||||
<img class="hero-wordmark" src={`${base}/brand/color-word.png`} alt="DeepTutor" />
|
||||
<h1 class="hero-tagline">{copy.taglineLead}<br /><em>{copy.taglineEm}</em></h1>
|
||||
<p class="hero-sub">{copy.subLead}<br />{copy.subRest}</p>
|
||||
<div class="hero-actions">
|
||||
@@ -284,7 +279,7 @@ const arrow = `<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-
|
||||
|
||||
<section class="showcase">
|
||||
<div class="showcase-frame">
|
||||
<img class="showcase-shot" src="/screenshots/dev/overview.png" alt={copy.shotAlt} loading="eager" decoding="async" />
|
||||
<img class="showcase-shot" src={`${base}/screenshots/dev/overview.png`} alt={copy.shotAlt} loading="eager" decoding="async" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -341,7 +336,7 @@ const arrow = `<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-
|
||||
<footer class="footer">
|
||||
<div class="footer-inner">
|
||||
<a class="footer-brand" href={`${root}/`}>
|
||||
<img src="/brand/color-logo.png" alt="" />
|
||||
<img src={`${base}/brand/color-logo.png`} alt="" />
|
||||
<span>DeepTutor</span>
|
||||
</a>
|
||||
<div class="footer-cols">
|
||||
@@ -371,15 +366,6 @@ const arrow = `<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-
|
||||
<div class="footer-rule"></div>
|
||||
<div class="footer-credo">
|
||||
<p class="footer-tagline">{copy.footerLead}<em>{copy.footerEm1}</em>{copy.footerMid}<em>{copy.footerEm2}</em>{copy.footerEnd}</p>
|
||||
<div class="footer-pulse" id="footer-pulse" data-hidden="true" aria-live="polite">
|
||||
<span class="footer-pulse-dot" aria-hidden="true"></span>
|
||||
{copy.footerLatest}
|
||||
<a class="footer-pulse-tag" href="https://github.com/HKUDS/DeepTutor/releases">—</a>
|
||||
<span class="sep">·</span>
|
||||
<span class="num">— {copy.visits}</span>
|
||||
<span class="sep">·</span>
|
||||
<span class="num">— {copy.requests}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer-fine">
|
||||
<span class="footer-fine-credit">© 2026 <a href="https://github.com/HKUDS" target="_blank" rel="noopener">{copy.credit}</a></span>
|
||||
@@ -391,14 +377,19 @@ const arrow = `<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-
|
||||
<script>
|
||||
const themeKey = "starlight-theme";
|
||||
const themeSelect = document.querySelector("[data-theme-select]");
|
||||
const stored = localStorage.getItem(themeKey);
|
||||
let stored = null;
|
||||
try {
|
||||
stored = localStorage.getItem(themeKey);
|
||||
} catch {}
|
||||
const current = stored === "light" || stored === "dark" ? stored : "auto";
|
||||
if (themeSelect instanceof HTMLSelectElement) {
|
||||
themeSelect.value = current;
|
||||
themeSelect.addEventListener("change", () => {
|
||||
const value = themeSelect.value;
|
||||
if (value === "auto") localStorage.removeItem(themeKey);
|
||||
else localStorage.setItem(themeKey, value);
|
||||
try {
|
||||
if (value === "auto") localStorage.removeItem(themeKey);
|
||||
else localStorage.setItem(themeKey, value);
|
||||
} catch {}
|
||||
const dark = value === "dark" || (value === "auto" && matchMedia("(prefers-color-scheme: dark)").matches);
|
||||
document.documentElement.dataset.theme = dark ? "dark" : "light";
|
||||
});
|
||||
@@ -407,9 +398,20 @@ const arrow = `<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-
|
||||
const localeSelect = document.querySelector("[data-locale-select]");
|
||||
if (localeSelect instanceof HTMLSelectElement) {
|
||||
localeSelect.addEventListener("change", () => {
|
||||
const base = (localeSelect.dataset.base || "").replace(/\/$/, "");
|
||||
const next = localeSelect.value;
|
||||
const path = location.pathname.replace(/^\/zh-cn(?=\/|$)/, "") || "/";
|
||||
location.href = next === "/zh-cn/" ? `/zh-cn${path === "/" ? "/" : path}` : path;
|
||||
const isZhTarget = next === `${base}/zh-cn/`;
|
||||
try {
|
||||
localStorage.setItem("dt-lang", isZhTarget ? "zh" : "en");
|
||||
} catch {}
|
||||
const stripped =
|
||||
base && location.pathname.startsWith(base)
|
||||
? location.pathname.slice(base.length) || "/"
|
||||
: location.pathname;
|
||||
const path = stripped.replace(/^\/zh-cn(?=\/|$)/, "") || "/";
|
||||
location.href = isZhTarget
|
||||
? `${base}/zh-cn${path === "/" ? "/" : path}`
|
||||
: `${base}${path}`;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import config from "virtual:starlight/user-config";
|
||||
// (home 图标让可点性更明显)。紧邻其右是 EduHub 入口——原在左侧栏,移到顶部。
|
||||
const LANDING_URL = "https://deeptutor.info";
|
||||
const EDUHUB_URL = "https://eduhub.deeptutor.info";
|
||||
const base = import.meta.env.BASE_URL.replace(/\/$/, "");
|
||||
---
|
||||
|
||||
<div class="dt-brand sl-flex">
|
||||
@@ -43,7 +44,7 @@ const EDUHUB_URL = "https://eduhub.deeptutor.info";
|
||||
/>
|
||||
)
|
||||
}
|
||||
<img class="site-title-wordmark" src="/brand/color-word.png" alt="DeepTutor" />
|
||||
<img class="site-title-wordmark" src={`${base}/brand/color-word.png`} alt="DeepTutor" />
|
||||
</a>
|
||||
<a class="dt-eduhub" href={EDUHUB_URL} target="_blank" rel="noopener">EduHub</a>
|
||||
</div>
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
// Social icons rendered from the SAME custom marks used on eduhub, at matching
|
||||
// optical sizes (GitHub fills its 16-viewBox → 17px; Discord/WeChat sit in a
|
||||
// 24-viewBox with vertical padding → 23px) so all three sites look identical.
|
||||
const path = Astro.url.pathname;
|
||||
const pageURL = `https://deeptutor.info${path}`;
|
||||
const base = import.meta.env.BASE_URL.replace(/\/$/, "");
|
||||
const pageURL = new URL(
|
||||
Astro.url.pathname,
|
||||
Astro.site ?? "https://docs.deeptutor.info",
|
||||
).toString();
|
||||
const issueURL = `https://github.com/HKUDS/DeepTutor/issues/new?template=docs.yml&page=${encodeURIComponent(
|
||||
pageURL,
|
||||
)}`;
|
||||
@@ -69,20 +72,33 @@ const wechatURL = "https://github.com/HKUDS/DeepTutor/issues/78";
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script is:inline>
|
||||
<script is:inline define:vars={{ base }}>
|
||||
(() => {
|
||||
if (window.__dtLocaleSwitcherPatched) return;
|
||||
window.__dtLocaleSwitcherPatched = true;
|
||||
|
||||
const basePrefix = (base || "").replace(/\/$/, "");
|
||||
const zhPrefix = "/zh-cn";
|
||||
const isZhPath = (path) => path === zhPrefix || path.startsWith(`${zhPrefix}/`);
|
||||
const stripBase = (path) => {
|
||||
if (basePrefix && (path === basePrefix || path.startsWith(`${basePrefix}/`))) {
|
||||
return path.slice(basePrefix.length) || "/";
|
||||
}
|
||||
return path;
|
||||
};
|
||||
const addBase = (path) => (basePrefix ? `${basePrefix}${path}` : path);
|
||||
const isZhPath = (path) => {
|
||||
const rel = stripBase(path);
|
||||
return rel === zhPrefix || rel.startsWith(`${zhPrefix}/`);
|
||||
};
|
||||
const toEnglishPath = (path) => {
|
||||
if (path === zhPrefix || path === `${zhPrefix}/`) return "/";
|
||||
return isZhPath(path) ? path.slice(zhPrefix.length) || "/" : path;
|
||||
const rel = stripBase(path);
|
||||
if (rel === zhPrefix || rel === `${zhPrefix}/`) return addBase("/");
|
||||
return addBase(isZhPath(path) ? rel.slice(zhPrefix.length) || "/" : rel);
|
||||
};
|
||||
const toChinesePath = (path) => {
|
||||
if (isZhPath(path)) return path;
|
||||
return path === "/" ? `${zhPrefix}/` : `${zhPrefix}${path}`;
|
||||
const rel = stripBase(path);
|
||||
if (rel === zhPrefix || rel.startsWith(`${zhPrefix}/`)) return addBase(rel);
|
||||
return addBase(rel === "/" ? `${zhPrefix}/` : `${zhPrefix}${rel}`);
|
||||
};
|
||||
const withCurrentSuffix = (path) =>
|
||||
`${path}${window.location.search}${window.location.hash}`;
|
||||
@@ -97,20 +113,22 @@ const wechatURL = "https://github.com/HKUDS/DeepTutor/issues/78";
|
||||
}
|
||||
};
|
||||
|
||||
// Auto-detect — first visit with no stored choice follows the browser
|
||||
// locale; an explicit switch always wins. Runs before the selects sync.
|
||||
// Auto-detect — on first visit with no stored choice, redirect English
|
||||
// routes to /zh-cn/ for zh browsers without overriding an explicit /zh-cn/
|
||||
// URL. Once the user picks a language, that preference always wins.
|
||||
(() => {
|
||||
const current = window.location.pathname;
|
||||
const stored = readLangPreference();
|
||||
const want = stored
|
||||
? stored
|
||||
: (navigator.language || "").toLowerCase().startsWith("zh")
|
||||
? "zh"
|
||||
: "en";
|
||||
if (want === "zh" && !isZhPath(current)) {
|
||||
if (stored === "zh" && !isZhPath(current)) {
|
||||
window.location.replace(withCurrentSuffix(toChinesePath(current)));
|
||||
} else if (want === "en" && isZhPath(current)) {
|
||||
} else if (stored === "en" && isZhPath(current)) {
|
||||
window.location.replace(withCurrentSuffix(toEnglishPath(current)));
|
||||
} else if (
|
||||
!stored &&
|
||||
!isZhPath(current) &&
|
||||
(navigator.language || "").toLowerCase().startsWith("zh")
|
||||
) {
|
||||
window.location.replace(withCurrentSuffix(toChinesePath(current)));
|
||||
}
|
||||
})();
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ docker run --rm --name deeptutor \
|
||||
ghcr.io/hkuds/deeptutor:latest
|
||||
```
|
||||
|
||||
Then in **Settings → LLM** (or **Embedding**), point the provider Base URL at `host.docker.internal`:
|
||||
Then in **Settings → Models & services**, point the LLM (or Embedding) provider Base URL at `host.docker.internal`:
|
||||
|
||||
| Service | Base URL |
|
||||
|---------|----------|
|
||||
@@ -185,4 +185,4 @@ More: [**Troubleshooting**](/self-hosting/troubleshooting/).
|
||||
## Next
|
||||
|
||||
- [**Multi-User Deployment**](/self-hosting/multi-user/) — team setup
|
||||
- [**Explore DeepTutor**](/explore/) — tour the running app
|
||||
- [**Explore DeepTutor**](/learning-workspace/) — tour the running app
|
||||
|
||||
@@ -14,7 +14,7 @@ Process environment variables override only a few startup values, such as the po
|
||||
|
||||
| Path | When it fits | Page |
|
||||
| --- | --- | --- |
|
||||
| PyPI | Published packages, full app after 1.7.0 | [PyPI](/self-hosting/pypi/) |
|
||||
| PyPI | Published packages, modular 1.7+ full app | [PyPI](/self-hosting/pypi/) |
|
||||
| Source | Current dev checkout | [From source](/self-hosting/source/) |
|
||||
| Docker | One published container | [Docker tutorial](/get-started/docker/) and [operations](/self-hosting/docker/) |
|
||||
| CLI only | No web frontend | [CLI only](/self-hosting/cli-only/) |
|
||||
|
||||
@@ -18,7 +18,7 @@ docker run --rm --name deeptutor \
|
||||
ghcr.io/hkuds/deeptutor:latest
|
||||
```
|
||||
|
||||
> **只需要映射 `3782`。** 浏览器只跟前端 origin 通信;容器里的 Next.js 中间件(`web/proxy.ts`)会把每个 `/api/*` 和 `/ws/*` 请求**在容器内部**转发给 FastAPI 后端,所以为了让 UI 正常工作,你不需要把 `8001` 暴露到宿主机。映射它(`-p 127.0.0.1:8001:8001`)是可选的 —— 只在你想用 curl 或脚本直接调 API 时才有用。
|
||||
> **映射 `3782` 即可。** 浏览器只跟前端 origin 通信;容器里的 Next.js 中间件(`web/proxy.ts`)会把每个 `/api/*` 和 `/ws/*` 请求**在容器内部**转发给 FastAPI 后端,所以为了让 UI 正常工作,你不需要把 `8001` 暴露到宿主机。映射它(`-p 127.0.0.1:8001:8001`)是可选的 —— 只在你想用 curl 或脚本直接调 API 时才有用。
|
||||
|
||||
打开 <http://127.0.0.1:3782>。容器首次启动时会创建 `/app/data/user/settings/*.json`;从 Web 的设置页面里配置模型 provider。配置、API key、日志、默认内容工作区、记忆、知识库、Partner 工作区(`data/partners/<id>/`)全部持久化在 `deeptutor-data` volume 里。可选依赖声明在部署上,别钻进容器里装:设好 `DEEPTUTOR_EXTRAS`(系统库用 `DEEPTUTOR_APT_PACKAGES`),每个容器启动时自动补齐。
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ quadrant: tutorial
|
||||
|
||||
## 1. 在项目工作区新建对话
|
||||
|
||||
选中这个项目的工作区。打开**主页 → 聊天**,新建一段对话。
|
||||
选中这个项目的工作区。打开**主页 → 对话**,新建一段对话。
|
||||
|
||||
输入框是空的,侧栏顶部的名称就是你选中的工作区。
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ docker run --rm --name deeptutor \
|
||||
ghcr.io/hkuds/deeptutor:latest
|
||||
```
|
||||
|
||||
然后在 **设置 → LLM**(或 **Embedding**)里,把 provider Base URL 指到 `host.docker.internal`:
|
||||
然后在 **设置 → 模型与服务** 里,把语言模型(或 Embedding)的 provider Base URL 指到 `host.docker.internal`:
|
||||
|
||||
| 服务 | Base URL |
|
||||
|------|----------|
|
||||
|
||||
@@ -14,7 +14,7 @@ quadrant: explanation
|
||||
|
||||
| 路径 | 适合 | 页面 |
|
||||
| --- | --- | --- |
|
||||
| PyPI | 已发布的包,1.7.0 之后的完整应用 | [PyPI](/zh-cn/self-hosting/pypi/) |
|
||||
| PyPI | 已发布的包(1.7+ 模块化安装) | [PyPI](/zh-cn/self-hosting/pypi/) |
|
||||
| 源码 | 当前 dev 检出 | [从源码运行](/zh-cn/self-hosting/source/) |
|
||||
| Docker | 一个已发布容器 | [Docker 教程](/zh-cn/get-started/docker/) 和 [运维](/zh-cn/self-hosting/docker/) |
|
||||
| 纯 CLI | 不要 Web 前端 | [纯 CLI](/zh-cn/self-hosting/cli-only/) |
|
||||
|
||||
@@ -395,8 +395,8 @@ dialog[aria-label="Search"] .dialog-frame {
|
||||
|
||||
/* Brand icons (channel/provider) embedded in tables and lists: keep them
|
||||
inline and vertically centred against the text baseline. */
|
||||
.sl-markdown-content img[src^="/channel-icons/"],
|
||||
.sl-markdown-content img[src^="/provider-icons/"] {
|
||||
.sl-markdown-content img[src*="/channel-icons/"],
|
||||
.sl-markdown-content img[src*="/provider-icons/"] {
|
||||
display: inline-block;
|
||||
vertical-align: -0.2em;
|
||||
margin: 0;
|
||||
|
||||
Reference in New Issue
Block a user