Add an Explain button that has Claude explain a problem
When stuck, the admin can ask Claude for an intuitive explanation of a problem. It is committed as explain.md and shown as folded sections, so the reader opens only as much as they need: the key observation, hints that get stronger, the approach, a walkthrough with an SVG diagram per step, complexity, pitfalls and a pseudocode sketch. - internal/claude: streamed call with a JSON-schema reply, high effort, the server-side refusal fallback, fixed error messages and logged token usage. CLAUDE_API_KEY and CLAUDE_MODEL (default claude-opus-5-5); without a key only this feature is off. - internal/explain: the prompt, the schema, rendering to markdown, and a per-problem job tracker. The request starts a job and the page polls, since a call outlasts nginx's 120s timeout. - internal/statement: fetches statements from LeetCode's GraphQL API and USACO's problem pages. Others (Codeforces is behind Cloudflare) are pasted. - problem.md holds the statement, editable from the meta editor and shown only to the admin. Diagrams are sanitized with DOMPurify. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Generated
+17
@@ -8,6 +8,7 @@
|
||||
"name": "usaco-site-web",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"dompurify": "^3.4.17",
|
||||
"highlight.js": "^11.11.1",
|
||||
"markdown-it": "^14.1.0",
|
||||
"vue": "^3.5.22",
|
||||
@@ -1267,6 +1268,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/trusted-types": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/@vitejs/plugin-vue": {
|
||||
"version": "6.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.10.tgz",
|
||||
@@ -1422,6 +1430,15 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/dompurify": {
|
||||
"version": "3.4.17",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz",
|
||||
"integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/enhanced-resolve": {
|
||||
"version": "5.26.0",
|
||||
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz",
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"dompurify": "^3.4.17",
|
||||
"highlight.js": "^11.11.1",
|
||||
"markdown-it": "^14.1.0",
|
||||
"vue": "^3.5.22",
|
||||
|
||||
@@ -35,3 +35,7 @@ export const getProblem = (name) => request("GET", `/problems/${encodeURICompone
|
||||
export const updateMeta = (name, meta) => request("PUT", `/problems/${encodeURIComponent(name)}/meta`, meta);
|
||||
export const setStatus = (name, to) => request("POST", `/problems/${encodeURIComponent(name)}/status`, { to });
|
||||
export const getMe = () => request("GET", "/me");
|
||||
export const fetchStatement = (name, url) =>
|
||||
request("GET", `/problems/${encodeURIComponent(name)}/statement/fetch?url=${encodeURIComponent(url || "")}`);
|
||||
export const startExplain = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/explain`, body);
|
||||
export const explainStatus = (name) => request("GET", `/problems/${encodeURIComponent(name)}/explain`);
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<script setup>
|
||||
/**
|
||||
* explain.md, laid out as the ladder it was written to be: every "## "
|
||||
* section folded away so the reader opens only as much as they need (the
|
||||
* observation, then one hint at a time, ...). The line above the first
|
||||
* section (who wrote it, when) stays visible.
|
||||
*
|
||||
* Markdown is rendered with html: false like the notes. The one exception
|
||||
* is ```svg fences, the walkthrough's diagrams: they are inserted as SVG
|
||||
* after DOMPurify's SVG profile has stripped scripts, event handlers and
|
||||
* anything else that is not drawing. Claude wrote them, the admin can edit
|
||||
* them, and the public sees them once the problem is solved.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import MarkdownIt from "markdown-it";
|
||||
import DOMPurify from "dompurify";
|
||||
|
||||
const props = defineProps({ source: { type: String, required: true } });
|
||||
|
||||
const md = new MarkdownIt({ html: false, linkify: true });
|
||||
const fence = md.renderer.rules.fence;
|
||||
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
|
||||
const t = tokens[idx];
|
||||
if (t.info.trim() !== "svg") return fence(tokens, idx, options, env, self);
|
||||
const clean = DOMPurify.sanitize(t.content, { USE_PROFILES: { svg: true, svgFilters: true } });
|
||||
return `<figure class="diagram">${clean}</figure>`;
|
||||
};
|
||||
|
||||
// Split on "## " headings outside code fences.
|
||||
const parts = computed(() => {
|
||||
const intro = [];
|
||||
const sections = [];
|
||||
let inFence = false;
|
||||
for (const line of props.source.split("\n")) {
|
||||
if (line.startsWith("```")) inFence = !inFence;
|
||||
if (!inFence && line.startsWith("## ")) {
|
||||
sections.push({ title: line.slice(3).trim(), lines: [] });
|
||||
} else {
|
||||
(sections.length ? sections[sections.length - 1].lines : intro).push(line);
|
||||
}
|
||||
}
|
||||
return {
|
||||
intro: md.render(intro.join("\n")),
|
||||
sections: sections.map((s) => ({ title: s.title, html: md.render(s.lines.join("\n")) })),
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="explanation">
|
||||
<div v-if="parts.intro.trim()" class="intro muted prose" v-html="parts.intro"></div>
|
||||
<details v-for="(s, i) in parts.sections" :key="i + s.title" class="step card">
|
||||
<summary>{{ s.title }}</summary>
|
||||
<div class="body prose" v-html="s.html"></div>
|
||||
</details>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.explanation {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.intro {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.step summary {
|
||||
padding: 8px 14px;
|
||||
cursor: pointer;
|
||||
font-weight: bold;
|
||||
}
|
||||
.step[open] summary {
|
||||
border-bottom: 1px solid var(--color-line-soft);
|
||||
}
|
||||
.body {
|
||||
padding: 12px 16px 16px;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.body :deep(.diagram) {
|
||||
margin: 12px 0;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--color-line-soft);
|
||||
border-radius: 4px;
|
||||
background: var(--color-paper);
|
||||
color: var(--color-ink);
|
||||
}
|
||||
.body :deep(.diagram svg) {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-width: 640px;
|
||||
height: auto;
|
||||
margin: 0 auto;
|
||||
}
|
||||
</style>
|
||||
@@ -1,15 +1,18 @@
|
||||
<script setup>
|
||||
/**
|
||||
* One problem: its solution files, sample input, saved tests, notes and git
|
||||
* history. The admin also gets the status buttons and the link/notes editor;
|
||||
* each edit is a commit the server pushes, and the response is the problem
|
||||
* as it is afterwards, so the page just takes it.
|
||||
* One problem: its solution files, sample input, saved tests, notes,
|
||||
* explanation and git history. The admin also gets the status buttons, the
|
||||
* link/statement/notes editor and the Explain panel; each edit is a commit
|
||||
* the server pushes, and the response is the problem as it is afterwards, so
|
||||
* the page just takes it. An explanation takes minutes, so starting one only
|
||||
* queues it and the page polls until it is committed.
|
||||
*/
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { computed, onUnmounted, ref, watch } from "vue";
|
||||
import { RouterLink } from "vue-router";
|
||||
import MarkdownIt from "markdown-it";
|
||||
import CodeBlock from "@/components/CodeBlock.vue";
|
||||
import { getMe, getProblem, setStatus, updateMeta } from "@/api";
|
||||
import Explanation from "@/components/Explanation.vue";
|
||||
import { explainStatus, fetchStatement, getMe, getProblem, setStatus, startExplain, updateMeta } from "@/api";
|
||||
import { LANG_LABELS, STATUS_LABELS, formatDate, title } from "@/format";
|
||||
|
||||
const props = defineProps({ name: { type: String, required: true } });
|
||||
@@ -31,6 +34,7 @@ async function load() {
|
||||
const [p, me] = await Promise.all([getProblem(props.name), getMe().catch(() => ({ admin: false }))]);
|
||||
problem.value = p;
|
||||
admin.value = me.admin;
|
||||
if (me.admin) checkExplain();
|
||||
} catch (e) {
|
||||
problem.value = null;
|
||||
error.value = e.status === 404 ? "No such problem." : e.message;
|
||||
@@ -41,6 +45,7 @@ async function load() {
|
||||
watch(() => props.name, load, { immediate: true });
|
||||
|
||||
const notesHtml = computed(() => (problem.value?.notes ? md.render(problem.value.notes) : ""));
|
||||
const statementHtml = computed(() => (problem.value?.statement ? md.render(problem.value.statement) : ""));
|
||||
const file = computed(() => problem.value?.files[activeFile.value]);
|
||||
|
||||
// ---- admin edits ----
|
||||
@@ -49,10 +54,13 @@ const editError = ref("");
|
||||
const editing = ref(false);
|
||||
const draftUrl = ref("");
|
||||
const draftNotes = ref("");
|
||||
const draftStatement = ref("");
|
||||
const fetching = ref(false);
|
||||
|
||||
function startEdit() {
|
||||
draftUrl.value = problem.value.url || "";
|
||||
draftNotes.value = problem.value.notes || "";
|
||||
draftStatement.value = problem.value.statement || "";
|
||||
editError.value = "";
|
||||
editing.value = true;
|
||||
}
|
||||
@@ -72,11 +80,67 @@ async function run(action) {
|
||||
}
|
||||
|
||||
async function saveMeta() {
|
||||
if (await run(() => updateMeta(props.name, { url: draftUrl.value, notes: draftNotes.value }))) {
|
||||
const meta = { url: draftUrl.value, notes: draftNotes.value, statement: draftStatement.value };
|
||||
if (await run(() => updateMeta(props.name, meta))) {
|
||||
editing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Fills the statement box for review; nothing is saved until Save.
|
||||
async function fillStatement() {
|
||||
fetching.value = true;
|
||||
editError.value = "";
|
||||
try {
|
||||
draftStatement.value = (await fetchStatement(props.name, draftUrl.value)).statement;
|
||||
} catch (e) {
|
||||
editError.value = e.message;
|
||||
} finally {
|
||||
fetching.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- explanations ----
|
||||
const stuckNote = ref("");
|
||||
const includeCode = ref(true);
|
||||
const job = ref({ state: "idle" });
|
||||
let poll = null;
|
||||
|
||||
function stopPolling() {
|
||||
clearTimeout(poll);
|
||||
poll = null;
|
||||
}
|
||||
onUnmounted(stopPolling);
|
||||
watch(() => props.name, stopPolling);
|
||||
|
||||
async function checkExplain() {
|
||||
stopPolling();
|
||||
const name = props.name;
|
||||
try {
|
||||
const s = await explainStatus(name);
|
||||
if (name !== props.name) return;
|
||||
const finished = job.value.state === "running" && s.state === "done";
|
||||
job.value = s;
|
||||
if (s.state === "running") {
|
||||
poll = setTimeout(checkExplain, 3000);
|
||||
} else if (finished) {
|
||||
problem.value = await getProblem(name);
|
||||
}
|
||||
} catch (e) {
|
||||
job.value = { state: "error", error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
async function explain() {
|
||||
try {
|
||||
job.value = await startExplain(props.name, { note: stuckNote.value, includeCode: includeCode.value });
|
||||
poll = setTimeout(checkExplain, 3000);
|
||||
} catch (e) {
|
||||
job.value = { state: "error", error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
const canExplain = computed(() => !!(problem.value?.statement || problem.value?.url));
|
||||
|
||||
const moves = computed(() => {
|
||||
const s = problem.value?.status;
|
||||
return [
|
||||
@@ -115,7 +179,7 @@ const moves = computed(() => {
|
||||
<button v-for="m in moves" :key="m.to" class="btn" :disabled="saving" @click="run(() => setStatus(problem.name, m.to))">
|
||||
{{ m.label }}
|
||||
</button>
|
||||
<button v-if="!editing" class="btn" :disabled="saving" @click="startEdit">Edit link and notes</button>
|
||||
<button v-if="!editing" class="btn" :disabled="saving" @click="startEdit">Edit link, statement and notes</button>
|
||||
<span v-if="saving" class="muted">Saving to git…</span>
|
||||
</div>
|
||||
<form v-if="editing" class="editor" @submit.prevent="saveMeta">
|
||||
@@ -123,6 +187,15 @@ const moves = computed(() => {
|
||||
Problem link
|
||||
<input v-model="draftUrl" type="url" placeholder="https://usaco.org/index.php?page=viewproblem2&cpid=…" />
|
||||
</label>
|
||||
<label>
|
||||
<span class="label-row">
|
||||
Problem statement (markdown, shown only to you and Claude)
|
||||
<button class="btn small" type="button" :disabled="fetching || !draftUrl" @click="fillStatement">
|
||||
{{ fetching ? "Fetching…" : "Fetch from link" }}
|
||||
</button>
|
||||
</span>
|
||||
<textarea v-model="draftStatement" rows="8" placeholder="Paste the statement, or fetch it from a LeetCode or USACO link"></textarea>
|
||||
</label>
|
||||
<label>
|
||||
Notes (markdown)
|
||||
<textarea v-model="draftNotes" rows="8" placeholder="Approach, complexity, what tripped you up…"></textarea>
|
||||
@@ -135,8 +208,36 @@ const moves = computed(() => {
|
||||
<p v-if="editError" class="error">{{ editError }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="admin" class="stuck card">
|
||||
<h2>Stuck?</h2>
|
||||
<p class="muted">
|
||||
Claude writes an intuitive explanation with diagrams, laid out as hints you open one at a time. It takes a
|
||||
minute or two and is committed as <code>explain.md</code>.
|
||||
</p>
|
||||
<textarea v-model="stuckNote" rows="3" placeholder="Optional: what you've tried and where you're stuck"></textarea>
|
||||
<div class="admin-row">
|
||||
<label class="check"><input v-model="includeCode" type="checkbox" /> Include my current code</label>
|
||||
<button class="btn primary" :disabled="job.state === 'running' || !canExplain" @click="explain">
|
||||
{{ problem.explanation ? "Explain again" : "Explain" }}
|
||||
</button>
|
||||
<span v-if="job.state === 'running'" class="muted">Claude is writing it…</span>
|
||||
<span v-else-if="!canExplain" class="muted">Add a link or the statement first.</span>
|
||||
</div>
|
||||
<p v-if="job.state === 'error'" class="error">{{ job.error }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="notesHtml" class="notes card prose" v-html="notesHtml"></section>
|
||||
|
||||
<section v-if="problem.explanation">
|
||||
<h2>Explanation</h2>
|
||||
<Explanation :source="problem.explanation" />
|
||||
</section>
|
||||
|
||||
<details v-if="admin && statementHtml" class="statement card">
|
||||
<summary>Problem statement</summary>
|
||||
<div class="prose" v-html="statementHtml"></div>
|
||||
</details>
|
||||
|
||||
<section>
|
||||
<h2>Solution</h2>
|
||||
<p v-if="!problem.files.length" class="muted">No solution file yet.</p>
|
||||
@@ -267,6 +368,55 @@ h2 {
|
||||
.notes {
|
||||
padding: 16px 20px;
|
||||
}
|
||||
.label-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
.btn.small {
|
||||
padding: 2px 10px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.stuck {
|
||||
padding: 12px 16px 16px;
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
.stuck h2 {
|
||||
margin: 0;
|
||||
}
|
||||
.stuck p {
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.stuck code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.85em;
|
||||
}
|
||||
.stuck textarea {
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: 4px;
|
||||
font-size: 0.9rem;
|
||||
color: var(--color-ink);
|
||||
background: var(--color-paper);
|
||||
}
|
||||
.check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.statement summary {
|
||||
padding: 8px 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.statement .prose {
|
||||
padding: 4px 20px 16px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.file-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
Reference in New Issue
Block a user