Autocomplete and evaluate solutions on the solve page
Test and publish the site / test (push) Successful in 1m25s
Test and publish the site / publish (push) Successful in 1m51s

The editor's completion popup was on but empty for C++, since
@codemirror/lang-cpp has no completion source. web/src/completions.js
adds one: keywords, the STL, every name in the file (the template's
macros show their expansion, typedefs what they alias), members after
. and ->, and snippets for the loops and lambdas typed over and over.
Python gains the contest standard library and members after ., on top
of lang-python's builtins and local names. Nothing knows types, so
members are the common ones plus those already used in the file.

Evaluate (POST/GET /problems/<name>/evaluate) has Claude judge the
editor's code as a strong competitive programmer would before
submitting. It runs the saved tests on the runner first, as Submit
does, and gives Claude the verdicts and up to three failing cases. The
reply is a verdict, correctness, complexity against the constraints,
line-anchored issues and a traced counterexample (internal/evaluate).
The page shows it in an Evaluation tab of the results panel, marks the
issues in the editor beside the lint's for as long as their lines are
unchanged, and can load the counterexample as the custom input.

It is a background job the page polls, like explanations, but it
commits nothing: the code is a draft. explain.Jobs.StartWith keeps a
finished job's answer in memory until the next one or a restart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-20 12:46:54 +01:00
co-authored by Claude Opus 5.5
parent 34552f2d81
commit d4849859df
18 changed files with 1566 additions and 36 deletions
+1
View File
@@ -19,6 +19,7 @@ One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, al
- **Visibility is decided server-side.** Non-admins see only `solved/`, and an unsolved problem is a 404, not a 403. `auth.Forward` returns false for a request with no cookies without a network call. `problem.md` (the judge's statement) is admin-only even on solved problems.
- **Explanations run in the background.** `POST /explain` starts a job in `explain.Jobs` and returns 202; the job calls Claude (`internal/claude`, streamed, JSON schema) and commits `explain.md` through `Mutate`. Tests fake Claude with `explain.Asker` and the judges with `handlers.Fetcher`; nothing in `go test` hits the network.
- **Recording reviews are the same shape.** `POST /review` takes a multipart upload and starts a job in its own `explain.Jobs`: transcribe (`internal/transcribe`, OpenAI-compatible, raw HTTP), measure (`Transcript.Metrics`), optionally keep the audio (`internal/audiostore`, S3), have Claude review it (`internal/review`) and commit `reviews/<id>.md`. Reviews are admin-only. Tests fake the transcriber and the store with `handlers.Transcriber` and `handlers.AudioStore`.
- **Evaluations are the same shape, but commit nothing.** `POST /evaluate` judges the solve page's draft: it runs the saved tests on the runner, then asks Claude (`internal/evaluate`). It keeps the answer in memory as the job's `Result` (`explain.Jobs.StartWith`), and the page polls for it.
- **Code runs in a separate service, never in the site.** The solve page's run/lint handlers (`handlers/run.go`) read the problem from the clone (`Server.Dir`, not the index, which truncates) and post to `cmd/usacorunner` through `runner.Client`; `internal/runner/types.go` is the contract between them. Tests fake it with `handlers.Runner`. The runner's own tests run real g++/python3/clang-tidy/ruff and skip whichever is missing.
+7 -2
View File
@@ -51,6 +51,7 @@ internal/claude/ the Claude client: streamed call, JSON-schema reply, fixed e
internal/explain/ the explanation prompt and schema, explain.md rendering, the job tracker
internal/transcribe/ OpenAI-compatible speech-to-text client, and pace/pause/filler metrics
internal/review/ the review prompt and schema, reviews/<id>.md rendering
internal/evaluate/ the solve page's evaluation: prompt, schema and the run's verdicts for Claude
internal/audiostore/ optional S3 bucket (Garage) that keeps review recordings for playback
internal/leetcode/ today's daily question, imported by running the clone's lib/leetcode.py
internal/statement/ fetches statements from LeetCode (GraphQL) and USACO (the problem page)
@@ -79,6 +80,8 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro
| `GET /usaco/api/problems/<name>/code` | admin | the solve page's start: `{io, leetcode, languages, default, runner, code: {cpp, python}}`, each language's saved source or a starter from `template.cpp`/`template.py` |
| `POST /usaco/api/problems/<name>/run` | admin | `{lang, source, mode: tests\|custom, input?}`: compiles once and runs the saved tests (or the custom input) on the runner; answers its verdicts. 503 without `RUNNER_URL` |
| `POST /usaco/api/problems/<name>/lint` | admin | `{lang, source}`: the runner's diagnostics (g++ and clang-tidy, or python and ruff) |
| `POST /usaco/api/problems/<name>/evaluate` | admin | `{lang, source, note?}`: runs the saved tests, then has Claude judge the source; answers 202. 409 if one is running, 503 without `CLAUDE_API_KEY` |
| `GET /usaco/api/problems/<name>/evaluate` | admin | the latest evaluation job, shaped like the explain one, with the evaluation as `result` once it is done |
| `PUT /usaco/api/problems/<name>/code` | admin | `{lang, source}`: commits `main.cpp`, or `main.py` (`sol.py` where that is the existing file), as "Edit <name>" |
| `POST /usaco/api/leetcode/daily` | admin | imports today's LeetCode daily question into `solving/` with the CLI's `lib/leetcode.py` and commits it as "Start <slug>", or finds it if it is already a problem; answers `{name, created}`. 502 if LeetCode or the import fails |
| `POST /usaco/api/hooks/gitea` | HMAC (`X-Gitea-Signature`) | queue a pull |
@@ -174,10 +177,12 @@ The "Review my explanation" panel (admin only) takes a recording of the admin ex
## Solve page
`/usaco/p/<name>/solve` (admin only) is a full-width editor: the statement and saved tests on the left; a CodeMirror editor with a C++/Python dropdown, Run (custom input), Submit (the saved tests), Save (commit) and the results on the right. Drafts live in the browser's localStorage per problem and language until saved or reset. LeetCode problems are C++ only, since their tests run through `driver.h`.
`/usaco/p/<name>/solve` (admin only) is a full-width editor: the statement and saved tests on the left; a CodeMirror editor with a C++/Python dropdown, Run (custom input), Submit (the saved tests), Evaluate (Claude), Save (commit) and the results on the right. Drafts live in the browser's localStorage per problem and language until saved or reset. LeetCode problems are C++ only, since their tests run through `driver.h`.
- **The runner is its own service.** The site holds the Claude, Gitea and S3 secrets and shares `app-network` with the database, so it never runs code. `cmd/usacorunner` does, in a container with no environment, on an `internal` network that only the site joins, read-only apart from an exec-able `/tmp` tmpfs, with memory, CPU and pids limits, all capabilities dropped and tini as PID 1 to reap orphans. The site posts to it (`runner.Client`, `RUNNER_URL`); the browser never sees it.
- **Runs copy the CLI.** The same g++ flags as `lib/common.sh` (`-DLOCAL`, with the repo root's `debugging.h` and `leetcode.h`, and a LeetCode problem's `driver.h`, sent along), the program runs in a directory holding `<io>.in` with that file also on stdin, `<io>.out` is its output if it wrote one, and outputs compare as `usaco test` does, ignoring trailing whitespace and trailing blank lines. Unlike the CLI there are limits: CPU time (2 s by default; TLE), 512 MB of address space, 64 MB files, a wall clock, and 60 s for a whole request, which keeps it synchronous under nginx's 120 s.
- **Autocomplete** is in the browser (`web/src/completions.js`), since `@codemirror/lang-cpp` has none. C++ completes keywords, the STL, every name in the file (the template's macros show what they expand to, typedefs what they alias), members after `.` and `->`, and snippets (`for`, `forr`, `foreach`, `lambda`, `dfs`, `sortby`...). Python adds the contest standard library (`heapq`, `bisect`, `collections`...) and members after `.` to lang-python's builtins and local names. Nothing knows types, so members are the common ones plus those already used in the file; clangd would, but it would need a session per editor next to the runner.
- **Evaluate** has Claude judge the code in the editor, as a strong competitive programmer would before submitting (`internal/evaluate`). It first runs the saved tests on the runner, as Submit does, and gives Claude their verdicts, with the input, expected output and actual output of up to three failing tests. It answers with a verdict (looks correct, misses edge cases, wrong, too slow, unfinished), complexity against the constraints, issues tied to source lines and a counterexample it has traced. The page marks the issues in the editor next to the lint's, and keeps a mark on its line for as long as that line's text is unchanged. The counterexample can be loaded as the custom input. It is a job the page polls, like explanations, and costs about the same. Nothing is committed: the result lives in the server's memory until the next evaluation or a restart. A statement it had to fetch is not saved either.
- **Lint.** C++ is g++'s warnings plus clang-tidy with the repo's `.clang-tidy` (bugprone, performance and a few readability checks, tuned so `template.cpp` is clean); the runner embeds a copy, and a test keeps the two equal. Python is `compile()` for syntax errors plus ruff (`E4,E7,E9,F,B`). A missing tool is skipped. The runner image precompiles `bits/stdc++.h` for g++ and clang-tidy (`internal/runner/pch.go`), which on the production host takes a build from about 4 s to 0.6 s and a clang-tidy pass from over 30 s to about 4 s (with Alpine 3.24's clang-tidy 22).
## Things that are easy to get wrong
@@ -185,6 +190,6 @@ The "Review my explanation" panel (admin only) takes a recording of the admin ex
- **`BASE_PATH` and Vite's `base` must agree.** The SPA's asset URLs and router base are fixed at build time.
- **Edits must decide from disk, not the index.** `repo.Mutate` may run an edit twice, the second time on a newer tip. The handlers re-locate the problem in the clone each time with `findOnDisk`.
- **`problem.md` is the judge's text.** `GET /problems/<name>` blanks it for non-admins, so the public site links to the judge instead of republishing it.
- **An explanation or review job lives in memory.** A restart mid-job loses it, and nothing is committed. Start it again (a review needs the recording uploaded again).
- **An explanation, review or evaluation job lives in memory.** A restart mid-job loses it, and nothing is committed. Start it again (a review needs the recording uploaded again).
- **Uploads are capped at 25 MB**, the OpenAI API's limit. nginx's server-wide `client_max_body_size 50M` is above it; lowering that below 25M would turn big recordings into nginx 413s.
- **`tests/*.out` used to be gitignored** by the root `*.out` rule. The root `.gitignore` now re-includes `**/tests/*.out`. A test whose expected output is shown as "Not saved." predates that change or never had one.
+322
View File
@@ -0,0 +1,322 @@
// Package evaluate has Claude judge the code in the solve page's editor, as
// a strong competitive programmer would before submitting it: is it right,
// is it fast enough for the constraints, which lines are wrong, and is
// there a small input that breaks it.
//
// The code is a draft, so unlike an explanation or a review nothing is
// committed. The answer is kept in memory with the source it judged
// (explain.Jobs.StartWith), and the page anchors each issue to its line in
// the editor.
//
// Claude is given the saved tests' verdicts from the runner along with the
// code, because a test that fails is a fact it should not have to work out,
// and one that passes is evidence it can weigh.
package evaluate
import (
"context"
"fmt"
"strings"
"time"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/runner"
)
// Input is what Claude is told.
type Input struct {
Name string
Statement string
Examples []explain.Example
Lang string // runner.Cpp or runner.Python
Source string
LeetCode bool // the source is a class Solution run through driver.h
Note string // what the admin wants checked: "worried about overflow"
// Run is the saved tests' outcome, nil when they were not run; RunNote
// says why not.
Run *runner.RunResponse
RunNote string
}
// Issue is one problem in the code, anchored to a line of it.
type Issue struct {
Line int `json:"line"`
Severity string `json:"severity"`
Title string `json:"title"`
Detail string `json:"detail"`
}
// Counterexample is an input the code gets wrong; all blank when Claude has
// none it is sure of.
type Counterexample struct {
Input string `json:"input"`
Expected string `json:"expected"`
Why string `json:"why"`
}
// Result is the reply's shape; Schema is the same thing for the API.
type Result struct {
Verdict string `json:"verdict"`
Summary string `json:"summary"`
Correctness string `json:"correctness"`
Complexity string `json:"complexity"`
Issues []Issue `json:"issues"`
Counterexample Counterexample `json:"counterexample"`
Style string `json:"style"`
}
// Evaluation is what the job keeps and the page shows: the reply, and the
// source it is about, so the page can tell when the editor has moved on.
type Evaluation struct {
Result
Lang string `json:"lang"`
Source string `json:"source"`
Model string `json:"model"`
At time.Time `json:"at"`
// Tests is the run's one-line outcome ("3/4 passed"), or why there was
// none.
Tests string `json:"tests"`
}
// Verdicts, and how they read on the page.
var Verdicts = map[string]string{
"correct": "Looks correct",
"edge_cases": "Misses edge cases",
"wrong": "Wrong",
"too_slow": "Too slow",
"incomplete": "Unfinished",
}
func str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
// Schema constrains the reply to Result. Structured outputs need every
// object closed and every property required.
var Schema = map[string]any{
"type": "object",
"properties": map[string]any{
"verdict": map[string]any{
"type": "string",
"enum": []string{"correct", "edge_cases", "wrong", "too_slow", "incomplete"},
"description": "correct: you expect it to be accepted. edge_cases: the idea is right but some inputs break it (overflow, empty input, an off-by-one at a boundary). " +
"wrong: the approach itself gives wrong answers. too_slow: right answers, but over the time or memory limit at the largest inputs. " +
"incomplete: it does not compile, or is not a full attempt yet. When several apply, pick the first of wrong, too_slow, edge_cases.",
},
"summary": str("Markdown, one or two sentences: what the code does, as an algorithm, so they can check it was read right."),
"correctness": str("Markdown. Why it is or is not correct. Account for every failing test. If it is wrong, say where the reasoning breaks; if it is right, give the argument briefly, especially for a greedy choice."),
"complexity": str("Markdown. Time and memory as written, against what the constraints allow, with a rough operation count at the largest input."),
"issues": map[string]any{
"type": "array",
"description": "Specific problems, most serious first: bugs, edge cases, overflow, undefined behaviour, needless slowness. Empty if there are none. Not style nitpicks.",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"line": map[string]any{"type": "integer", "description": "The source line it is on, as numbered in <code>. 0 if it is about the program as a whole."},
"severity": map[string]any{"type": "string", "enum": []string{"error", "warning", "info"}, "description": "error: gives a wrong answer, crashes or times out on some valid input. warning: risky or fragile, but may be fine on this problem's tests. info: worth knowing, harmless here."},
"title": str("Plain text, under ten words: shown inline in the editor."),
"detail": str("Markdown. What goes wrong and on what input, and how to fix it. A corrected line or two is fine; never a whole solution."),
},
"required": []string{"line", "severity", "title", "detail"},
"additionalProperties": false,
},
},
"counterexample": map[string]any{
"type": "object",
"description": "A small input this code gets wrong, in exactly the problem's input format. All three blank unless you have traced the code on it and are sure.",
"properties": map[string]any{
"input": str("The input, exactly as the program would read it. Blank for none."),
"expected": str("The correct output for that input, worked out carefully. Blank for none."),
"why": str("Markdown, one or two sentences: what this code outputs instead, and why. Blank for none."),
},
"required": []string{"input", "expected", "why"},
"additionalProperties": false,
},
"style": str("Markdown, two to four sentences: readability and contest habits worth changing, if any. Blank if there is nothing worth saying."),
},
"required": []string{"verdict", "summary", "correctness", "complexity", "issues", "counterexample", "style"},
"additionalProperties": false,
}
// The reply is short; the rest is room for adaptive thinking, which is
// where the tracing happens.
const maxTokens = 24000
// System is the same on every call, so it is cached.
const System = `You are a strong competitive programmer reviewing someone's solution before they submit it. You get the problem, their code, and usually the verdicts from running it on their saved tests. Tell them whether it will be accepted and, if not, exactly why.
How to judge:
- Decide correctness yourself. Trace the code on the examples and on small cases you construct, especially the boundaries: minimum sizes, all-equal values, the largest values, an empty answer.
- The test verdicts are facts. A failing test proves a bug; explain every one. Passing tests are evidence, not proof: samples are small and weak.
- Check the complexity against the constraints in the statement. Assume about 10^8 simple operations per second in C++ and 10^7 in CPython.
- Look hard for what usually breaks accepted-looking code: int overflow where long long is needed, off-by-ones, state not reset between test cases, uninitialised values, out-of-bounds access, wrong output format, recursion depth (in Python especially), comparing floating point exactly, and slow I/O on big input.
- Read the code as written, not as intended. Code that is unfinished or does not compile is incomplete.
Their setup:
- C++ is built with g++ -std=c++17 -O2 -DLOCAL. LOCAL is defined only on their machine, never on the judge, so the DBG and print macros are no-ops there. Their template defines macros and typedefs such as ll, vi, pii, F(i, L, R) for (int i = L; i < R; i++), FE (<=), FD and FDE (counting down), ALL(c), SZ(c), pb, fi and se, REMAX and REMIN, takeI(n) (declares int n and reads it), takeL, takeV(v, n), whileZ (reads T and loops T times), YESNO(b), and STDIO(name), which reads name.in and writes name.out when run locally or on USACO. Treat these as ordinary code.
- A LeetCode problem's code is the class Solution only; a driver reads the tests and calls it, so judge the method, not I/O.
- Python reads with a tokens() helper over sys.stdin.buffer, and a stdio(name) helper redirects to name.in and name.out when that file exists.
How to answer:
- The code is shown with line numbers. Every issue names the line it is on, as numbered there, so it can be marked in their editor.
- Point at fixes; do not write their solution. A corrected line or two is fine.
- Give a counterexample only if you have traced the code on it and are sure it fails, and you have worked out the right answer. Keep it small, and in exactly the input format. Otherwise leave it blank.
- Be direct. If the code is right, say so plainly and keep the rest short; do not invent problems.
- Write in plain prose, using markdown for emphasis, lists and inline code, and LaTeX between $...$ for math such as complexities ($O(n \log n)$); the page typesets it with KaTeX.`
// Prompt is the user message.
func Prompt(in Input) string {
var b strings.Builder
fmt.Fprintf(&b, "<problem name=%q>\n%s\n</problem>\n", in.Name, strings.TrimSpace(in.Statement))
for i, ex := range in.Examples {
fmt.Fprintf(&b, "\n<example n=\"%d\">\n<input>\n%s\n</input>\n", i+1, strings.TrimRight(ex.In, "\n"))
if ex.Out != "" {
fmt.Fprintf(&b, "<output>\n%s\n</output>\n", strings.TrimRight(ex.Out, "\n"))
}
b.WriteString("</example>\n")
}
kind := ""
if in.LeetCode {
kind = " leetcode=\"true\""
}
fmt.Fprintf(&b, "\n<code lang=%q%s>\n%s</code>\n", in.Lang, kind, numbered(in.Source))
b.WriteString("\n<test_run>\n" + runText(in.Run, in.RunNote) + "</test_run>\n")
if note := strings.TrimSpace(in.Note); note != "" {
fmt.Fprintf(&b, "\n<context>\n%s\n</context>\n", note)
}
b.WriteString("\nEvaluate my solution.")
return b.String()
}
// numbered prefixes each line with its number, right-aligned, as an editor
// gutter would show it.
func numbered(src string) string {
lines := strings.Split(strings.TrimRight(src, "\n"), "\n")
w := len(fmt.Sprint(len(lines)))
var b strings.Builder
for i, line := range lines {
fmt.Fprintf(&b, "%*d| %s\n", w, i+1, line)
}
return b.String()
}
// Caps on what a run puts in the prompt. A failing test bigger than
// maxCase is a stress test: its verdict is worth stating, its text is not.
const (
maxCase = 2 << 10
maxShown = 3
maxCompiler = 4 << 10
)
func runText(r *runner.RunResponse, note string) string {
if r == nil {
return note + "\n"
}
var b strings.Builder
if !r.Compile.OK {
b.WriteString("It did not compile:\n" + capped(r.Compile.Output, maxCompiler) + "\n")
return b.String()
}
if len(r.Results) == 0 {
return "It compiled. There are no saved tests to run.\n"
}
fmt.Fprintf(&b, "%s on the saved tests:\n", Outcome(r))
for _, t := range r.Results {
fmt.Fprintf(&b, "- test %s: %s in %d ms", t.Name, t.Verdict, t.TimeMs)
if t.Message != "" {
b.WriteString(" (" + t.Message + ")")
}
b.WriteString("\n")
}
shown := 0
for _, t := range r.Results {
if shown == maxShown {
break
}
if t.Verdict == runner.Accepted || t.Verdict == runner.Unchecked {
continue
}
shown++
fmt.Fprintf(&b, "\n<failed_test name=%q verdict=%q>\n", t.Name, t.Verdict)
if len(t.Input) > maxCase || (t.Expected != nil && len(*t.Expected) > maxCase) {
b.WriteString("(too big to show)\n</failed_test>\n")
continue
}
fmt.Fprintf(&b, "<input>\n%s\n</input>\n", strings.TrimRight(t.Input, "\n"))
if t.Expected != nil {
fmt.Fprintf(&b, "<expected>\n%s\n</expected>\n", strings.TrimRight(*t.Expected, "\n"))
}
fmt.Fprintf(&b, "<got>\n%s\n</got>\n", capped(strings.TrimRight(t.Output, "\n"), maxCase))
if t.Stderr != "" {
fmt.Fprintf(&b, "<stderr>\n%s\n</stderr>\n", capped(strings.TrimRight(t.Stderr, "\n"), maxCase))
}
b.WriteString("</failed_test>\n")
}
return b.String()
}
// Outcome is a run's one-line result: "3/4 passed", or "2 ran" when no
// test had an expected output.
func Outcome(r *runner.RunResponse) string {
if !r.Compile.OK {
return "did not compile"
}
passed, checked := 0, 0
for _, t := range r.Results {
if t.Verdict != runner.Unchecked {
checked++
}
if t.Verdict == runner.Accepted {
passed++
}
}
if checked == 0 {
return fmt.Sprintf("%d ran, unchecked", len(r.Results))
}
return fmt.Sprintf("%d/%d passed", passed, checked)
}
func capped(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "\n(cut)"
}
// Generate asks Claude and returns the evaluation.
func Generate(ctx context.Context, a explain.Asker, in Input, now time.Time) (*Evaluation, error) {
var r Result
err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
if err != nil {
return nil, err
}
tests := in.RunNote
if in.Run != nil {
tests = Outcome(in.Run)
}
return &Evaluation{Result: clean(r, in.Source), Lang: in.Lang, Source: in.Source, Model: a.Model(), At: now, Tests: tests}, nil
}
// clean keeps the reply inside what the page can show: lines that exist,
// severities it knows, and a counterexample only when it is whole.
func clean(r Result, src string) Result {
lines := strings.Count(strings.TrimRight(src, "\n"), "\n") + 1
issues := []Issue{}
for _, is := range r.Issues {
if is.Line < 0 || is.Line > lines {
is.Line = 0
}
switch is.Severity {
case "error", "warning", "info":
default:
is.Severity = "info"
}
if strings.TrimSpace(is.Title) != "" || strings.TrimSpace(is.Detail) != "" {
issues = append(issues, is)
}
}
r.Issues = issues
if strings.TrimSpace(r.Counterexample.Input) == "" || strings.TrimSpace(r.Counterexample.Expected) == "" {
r.Counterexample = Counterexample{}
}
return r
}
+168
View File
@@ -0,0 +1,168 @@
package evaluate
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/explain"
"adam-french.co.uk/usaco-site/internal/runner"
)
func ptr(s string) *string { return &s }
func TestPrompt(t *testing.T) {
run := &runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{
{Name: "1", Verdict: runner.Accepted, TimeMs: 3},
{Name: "2", Verdict: runner.WrongAnswer, TimeMs: 4, Input: "2\n", Output: "5\n", Expected: ptr("4\n")},
{Name: "big", Verdict: runner.TimeLimit, TimeMs: 2000, Message: "exceeded 2s", Input: strings.Repeat("9 ", 2000)},
}}
p := Prompt(Input{
Name: "moocast", Statement: "# Moocast\n\nCows.", Lang: runner.Cpp,
Source: "int main() {\n return 0;\n}\n",
Examples: []explain.Example{{In: "1\n", Out: "2\n"}},
Note: " overflow? ",
Run: run,
})
for _, want := range []string{
"<problem name=\"moocast\">\n# Moocast\n\nCows.\n</problem>",
"<example n=\"1\">\n<input>\n1\n</input>\n<output>\n2\n</output>",
"<code lang=\"cpp\">\n1| int main() {\n2| return 0;\n3| }\n</code>",
"1/3 passed on the saved tests:\n- test 1: AC in 3 ms\n- test 2: WA in 4 ms\n- test big: TLE in 2000 ms (exceeded 2s)\n",
"<failed_test name=\"2\" verdict=\"WA\">\n<input>\n2\n</input>\n<expected>\n4\n</expected>\n<got>\n5\n</got>\n</failed_test>",
"<failed_test name=\"big\" verdict=\"TLE\">\n(too big to show)\n</failed_test>",
"<context>\noverflow?\n</context>",
} {
if !strings.Contains(p, want) {
t.Errorf("prompt is missing %q:\n%s", want, p)
}
}
p = Prompt(Input{Name: "two-sum", Statement: "x", Lang: runner.Cpp, LeetCode: true, Source: "class Solution {};", RunNote: "The tests were not run: the code runner is not configured."})
for _, want := range []string{
"<code lang=\"cpp\" leetcode=\"true\">\n1| class Solution {};\n</code>",
"<test_run>\nThe tests were not run: the code runner is not configured.\n</test_run>",
} {
if !strings.Contains(p, want) {
t.Errorf("prompt is missing %q:\n%s", want, p)
}
}
if strings.Contains(p, "<context>") {
t.Errorf("a blank note still made a context block:\n%s", p)
}
p = Prompt(Input{Name: "x", Lang: runner.Cpp, Source: "int main( {}", Run: &runner.RunResponse{Compile: runner.Compile{Output: "main.cpp:1: error"}}})
if !strings.Contains(p, "It did not compile:\nmain.cpp:1: error\n") {
t.Errorf("a compile error is not in the prompt:\n%s", p)
}
}
func TestNumberedPadsToTheWidestLine(t *testing.T) {
got := numbered(strings.Repeat("x\n", 10))
if !strings.HasPrefix(got, " 1| x\n") || !strings.HasSuffix(got, "10| x\n") {
t.Errorf("numbered = %q", got)
}
}
func TestOutcome(t *testing.T) {
r := &runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{{Verdict: runner.Unchecked}, {Verdict: runner.Unchecked}}}
if got := Outcome(r); got != "2 ran, unchecked" {
t.Errorf("Outcome = %q", got)
}
if got := Outcome(&runner.RunResponse{}); got != "did not compile" {
t.Errorf("Outcome = %q", got)
}
}
// fakeAsker answers with r.
type fakeAsker struct{ r Result }
func (fakeAsker) Model() string { return "fake-model" }
func (f fakeAsker) JSON(_ context.Context, _ claude.Request, out any) error {
*out.(*Result) = f.r
return nil
}
func TestGenerateCleansTheReply(t *testing.T) {
r := Result{
Verdict: "wrong",
Issues: []Issue{
{Line: 2, Severity: "error", Title: "Overflow"},
{Line: 99, Severity: "fatal", Title: "Past the end"},
{Line: 1, Severity: "info"},
},
Counterexample: Counterexample{Input: "3\n", Why: "no expected output"},
}
now := time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC)
run := &runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{{Verdict: runner.Accepted}}}
ev, err := Generate(context.Background(), fakeAsker{r}, Input{Lang: runner.Python, Source: "a\nb\n", Run: run}, now)
if err != nil {
t.Fatal(err)
}
want := []Issue{{Line: 2, Severity: "error", Title: "Overflow"}, {Line: 0, Severity: "info", Title: "Past the end"}}
if len(ev.Issues) != 2 || ev.Issues[0] != want[0] || ev.Issues[1] != want[1] {
t.Errorf("issues = %+v, want %+v", ev.Issues, want)
}
if ev.Counterexample != (Counterexample{}) {
t.Errorf("a counterexample with no expected output was kept: %+v", ev.Counterexample)
}
if ev.Lang != runner.Python || ev.Source != "a\nb\n" || ev.Model != "fake-model" || !ev.At.Equal(now) || ev.Tests != "1/1 passed" {
t.Errorf("evaluation = %+v", ev)
}
// The page reads the reply's fields at the top level, beside lang.
b, _ := json.Marshal(ev)
if !strings.Contains(string(b), `"verdict":"wrong"`) || !strings.Contains(string(b), `"lang":"python"`) {
t.Errorf("JSON = %s", b)
}
}
// Every property must be required and every object closed for structured
// outputs, and the Go struct must read every field the schema asks for.
func TestSchemaMatchesResult(t *testing.T) {
var check func(path string, s map[string]any)
check = func(path string, s map[string]any) {
if s["type"] == "array" {
check(path+"[]", s["items"].(map[string]any))
return
}
if s["type"] != "object" {
return
}
if s["additionalProperties"] != false {
t.Errorf("%s is not closed", path)
}
props := s["properties"].(map[string]any)
req := map[string]bool{}
for _, r := range s["required"].([]string) {
req[r] = true
}
for k, v := range props {
if !req[k] {
t.Errorf("%s.%s is not required", path, k)
}
check(path+"."+k, v.(map[string]any))
}
}
check("", Schema)
b, _ := json.Marshal(Result{Issues: []Issue{{}}})
var got map[string]any
json.Unmarshal(b, &got)
for k := range Schema["properties"].(map[string]any) {
if _, ok := got[k]; !ok {
t.Errorf("Result has no field for %q", k)
}
}
for v := range Verdicts {
found := false
for _, e := range Schema["properties"].(map[string]any)["verdict"].(map[string]any)["enum"].([]string) {
found = found || e == v
}
if !found {
t.Errorf("verdict %q is labelled but not in the schema", v)
}
}
}
+12 -3
View File
@@ -19,6 +19,8 @@ type Status struct {
Error string `json:"error,omitempty"`
Started *time.Time `json:"started,omitempty"`
Finished *time.Time `json:"finished,omitempty"`
// Result is a finished StartWith job's answer.
Result any `json:"result,omitempty"`
}
// Jobs runs at most one explanation per problem at a time. An explanation
@@ -34,6 +36,13 @@ type Jobs struct {
// reports whether it started. fn's error is shown to the admin, so it must
// be a message meant for them.
func (j *Jobs) Start(name string, fn func() error) bool {
return j.StartWith(name, func() (any, error) { return nil, fn() })
}
// StartWith is Start for a job whose answer is kept here rather than
// committed: a done job's Status carries it until the next job for name
// starts, or the server restarts.
func (j *Jobs) StartWith(name string, fn func() (any, error)) bool {
j.mu.Lock()
defer j.mu.Unlock()
if j.m == nil {
@@ -45,13 +54,13 @@ func (j *Jobs) Start(name string, fn func() error) bool {
now := time.Now()
j.m[name] = &Status{State: Running, Started: &now}
go func() {
err := fn()
res, err := fn()
j.mu.Lock()
defer j.mu.Unlock()
end := time.Now()
s := &Status{State: Done, Started: &now, Finished: &end}
s := &Status{State: Done, Started: &now, Finished: &end, Result: res}
if err != nil {
s.State, s.Error = Failed, err.Error()
s.State, s.Error, s.Result = Failed, err.Error(), nil
}
j.m[name] = s
}()
+117
View File
@@ -0,0 +1,117 @@
package handlers
import (
"context"
"errors"
"log"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/evaluate"
"adam-french.co.uk/usaco-site/internal/runner"
)
// The saved tests run first and Claude takes a minute or two after.
const evaluateTimeout = 10 * time.Minute
// startEvaluate starts judging the editor's source and answers at once; the
// page polls evaluateStatus, whose result is the evaluation. Nothing is
// committed: the source is a draft, and the answer is about this version of
// it only.
func (s *Server) startEvaluate(ctx *gin.Context) {
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
return
}
body, p, l, ok := s.readCode(ctx)
if !ok {
return
}
if strings.TrimSpace(body.Source) == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the source is empty"})
return
}
if len(body.Note) > maxNote {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"})
return
}
if strings.TrimSpace(p.Statement) == "" && p.URL == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "add the problem statement or a link to it first"})
return
}
in := evaluate.Input{
Name: p.Name, Statement: p.Statement, Examples: examples(p),
Lang: body.Lang, Source: body.Source, LeetCode: l.leetcode, Note: body.Note,
}
link := p.URL
if !s.evalJobs.StartWith(p.Name, func() (any, error) { return s.evaluate(in, link, l) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "a solution is already being evaluated"})
return
}
ctx.JSON(http.StatusAccepted, s.evalJobs.Get(p.Name))
}
func (s *Server) evaluateStatus(ctx *gin.Context) {
if p, ok := s.lookup(ctx, true); ok {
ctx.JSON(http.StatusOK, s.evalJobs.Get(p.Name))
}
}
// evaluate is one job. Its error is shown to the admin, so every path
// returns a message meant for them and logs the detail.
func (s *Server) evaluate(in evaluate.Input, link string, l *layout) (*evaluate.Evaluation, error) {
ctx, cancel := context.WithTimeout(context.Background(), evaluateTimeout)
defer cancel()
name := in.Name
// A fetched statement is not saved: that would be the only commit an
// evaluation makes. Explain or Edit details keep one.
if _, err := s.ensureStatement(ctx, "evaluate", name, &in.Statement, link); err != nil {
return nil, err
}
in.Run, in.RunNote = s.evaluationRun(ctx, name, in.Lang, in.Source, l)
ev, err := evaluate.Generate(ctx, s.Claude, in, time.Now())
if err != nil {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[evaluate] %s: %s: %v", name, f.Msg, f.Err)
return nil, f
}
log.Printf("[evaluate] %s: %v", name, err)
return nil, errors.New("the evaluation could not be written")
}
return ev, nil
}
// evaluationRun is Submit's run, for Claude to read. A run that cannot
// happen costs the evaluation its test verdicts, not the evaluation: the
// note says why, and goes to Claude in their place.
func (s *Server) evaluationRun(ctx context.Context, name, lang, source string, l *layout) (*runner.RunResponse, string) {
if s.Runner == nil {
return nil, "The tests were not run: the code runner is not configured."
}
tests, err := readRunTests(l)
if err != nil {
log.Printf("[evaluate] %s: reading the tests: %v", name, err)
return nil, "The tests were not run: they could not be read."
}
files, err := s.headers(l, lang)
if err != nil {
log.Printf("[evaluate] %s: reading the headers: %v", name, err)
return nil, "The tests were not run: the headers could not be read."
}
c, cancel := context.WithTimeout(ctx, runTimeout)
defer cancel()
res, err := s.Runner.Run(c, runner.RunRequest{Lang: lang, Source: source, Files: files, IO: l.io, Tests: tests})
if err != nil {
log.Printf("[evaluate] %s: running the tests: %v", name, err)
return nil, "The tests were not run: the code runner failed."
}
return &res, ""
}
+146
View File
@@ -0,0 +1,146 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/evaluate"
"adam-french.co.uk/usaco-site/internal/explain"
)
// fakeEvaluator flags line 1 of whatever it is shown, or fails.
type fakeEvaluator struct {
user string
fail bool
}
func (f *fakeEvaluator) Model() string { return "fake-model" }
func (f *fakeEvaluator) JSON(_ context.Context, req claude.Request, out any) error {
f.user = req.User
if f.fail {
return &claude.Failure{Msg: "Claude declined to answer"}
}
*out.(*evaluate.Result) = evaluate.Result{
Verdict: "edge_cases", Summary: "Prints zero.",
Issues: []evaluate.Issue{{Line: 1, Severity: "error", Title: "Never reads n"}},
}
return nil
}
type evalStatus struct {
State string `json:"state"`
Error string `json:"error"`
Result *evaluate.Evaluation `json:"result"`
}
func waitEvaluate(t *testing.T, r *gin.Engine, name string) evalStatus {
t.Helper()
for range 400 {
var s evalStatus
json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/evaluate", "", true).Body.Bytes(), &s)
if s.State != explain.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("evaluation still running")
return evalStatus{}
}
const evalBody = `{"lang":"cpp","source":"int main() {}\n","note":"is it fast enough?"}`
func TestEvaluateRefusals(t *testing.T) {
r, repo, _ := setupRun(t)
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 503 {
t.Fatalf("no Claude = %d, want 503", rec.Code)
}
repo.srv.Claude = &fakeEvaluator{}
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, false); rec.Code != 401 {
t.Fatalf("public evaluate = %d, want 401", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 400 {
t.Fatalf("no statement or link = %d, want 400: %s", rec.Code, rec.Body)
}
withStatement(t, r)
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", `{"lang":"cpp","source":" \n"}`, true); rec.Code != 400 {
t.Fatalf("empty source = %d, want 400", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", `{"lang":"rust","source":"fn main() {}"}`, true); rec.Code != 400 {
t.Fatalf("rust = %d, want 400", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/problems/two-sum/evaluate", `{"lang":"python","source":"x"}`, true); rec.Code != 400 {
t.Fatalf("python on LeetCode = %d, want 400", rec.Code)
}
}
func TestEvaluateRunsTheTestsAndCommitsNothing(t *testing.T) {
r, repo, fr := setupRun(t)
fc := &fakeEvaluator{}
repo.srv.Claude = fc
withStatement(t, r)
commits := len(repo.msg)
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 202 {
t.Fatalf("evaluate = %d %s", rec.Code, rec.Body)
}
s := waitEvaluate(t, r, "moocast")
if s.State != explain.Done || s.Result == nil {
t.Fatalf("job = %+v", s)
}
ev := s.Result
if ev.Verdict != "edge_cases" || ev.Lang != "cpp" || ev.Source != "int main() {}\n" || ev.Model != "fake-model" || ev.Tests != "1/1 passed" {
t.Errorf("evaluation = %+v", ev)
}
if len(ev.Issues) != 1 || ev.Issues[0].Line != 1 {
t.Errorf("issues = %+v", ev.Issues)
}
// Submit's run: the saved tests, with the headers.
if fr.run == nil || len(fr.run.Tests) != 3 || fr.run.IO != "moocast" || fr.run.Files["debugging.h"] == "" {
t.Errorf("run = %+v", fr.run)
}
for _, want := range []string{"walkie-talkies", "<code lang=\"cpp\">\n1| int main() {}\n</code>", "1/1 passed on the saved tests", "is it fast enough?"} {
if !strings.Contains(fc.user, want) {
t.Errorf("prompt is missing %q:\n%s", want, fc.user)
}
}
if len(repo.msg) != commits {
t.Errorf("an evaluation committed: %v", repo.msg[commits:])
}
}
func TestEvaluateWithoutARunner(t *testing.T) {
r, repo, fr := setupRun(t)
fc := &fakeEvaluator{}
repo.srv.Claude = fc
withStatement(t, r)
// A runner that fails costs the verdicts, not the evaluation.
fr.err = errors.New("runner down")
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
if s := waitEvaluate(t, r, "moocast"); s.State != explain.Done || s.Result.Tests != "The tests were not run: the code runner failed." {
t.Fatalf("with a failing runner = %+v", s)
}
repo.srv.Runner = nil
if c := getCodeReply(t, r, "moocast"); c.Runner {
t.Fatal("runner still reported")
}
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
s := waitEvaluate(t, r, "moocast")
if s.State != explain.Done || !strings.Contains(fc.user, "the code runner is not configured") {
t.Fatalf("with no runner = %+v\n%s", s, fc.user)
}
fc.fail = true
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
if s := waitEvaluate(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" || s.Result != nil {
t.Fatalf("a failed evaluation = %+v", s)
}
}
+7 -5
View File
@@ -1,8 +1,8 @@
// Package handlers is the site's REST API: the problem list and pages (public
// for solved problems, everything for the admin), the admin's edits, the
// Claude explanations (explain.go) and recording reviews (review.go), the
// solve page's code editing and runs (run.go), and the Gitea webhook that
// tells the server to pull.
// solve page's code editing and runs (run.go) and evaluations
// (evaluate.go), and the Gitea webhook that tells the server to pull.
package handlers
import (
@@ -67,9 +67,9 @@ type Server struct {
Runner Runner
idx atomic.Pointer[index.Index]
// Separate, so a review and an explanation of one problem can run at
// the same time.
jobs, reviewJobs explain.Jobs
// Separate, so a review, an explanation and an evaluation of one
// problem can run at the same time.
jobs, reviewJobs, evalJobs explain.Jobs
}
// SetIndex swaps in a freshly built index. repo.Repo calls it (through
@@ -111,6 +111,8 @@ func (s *Server) Routes(api *gin.RouterGroup) {
admin.PUT("/problems/:name/code", s.saveCode)
admin.POST("/problems/:name/run", s.run)
admin.POST("/problems/:name/lint", s.lint)
admin.POST("/problems/:name/evaluate", s.startEvaluate)
admin.GET("/problems/:name/evaluate", s.evaluateStatus)
admin.POST("/leetcode/daily", s.startDaily)
api.POST("/hooks/gitea", s.webhook)
}
+17 -13
View File
@@ -16,6 +16,7 @@ import (
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/index"
"adam-french.co.uk/usaco-site/internal/runner"
)
@@ -159,6 +160,7 @@ func (s *Server) getCode(ctx *gin.Context) {
"languages": l.languages(),
"default": def,
"runner": s.Runner != nil,
"claude": s.Claude != nil,
"code": code,
})
}
@@ -248,44 +250,46 @@ type codeBody struct {
// Mode and Input are for runs only.
Mode string `json:"mode"`
Input string `json:"input"`
// Note is for evaluations only.
Note string `json:"note"`
}
// readCode reads and checks a solve page request against the problem's
// layout. It has answered when ok is false.
func (s *Server) readCode(ctx *gin.Context) (body codeBody, l *layout, ok bool) {
p, ok := s.lookup(ctx, true)
func (s *Server) readCode(ctx *gin.Context) (body codeBody, p *index.Problem, l *layout, ok bool) {
p, ok = s.lookup(ctx, true)
if !ok {
return body, nil, false
return body, nil, nil, false
}
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxRunBody)
if err := ctx.ShouldBindJSON(&body); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the request is over 512 KB"})
return body, nil, false
return body, nil, nil, false
}
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return body, nil, false
return body, nil, nil, false
}
if len(body.Source) > maxSource {
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the source is over 256 KB"})
return body, nil, false
return body, nil, nil, false
}
if body.Lang != runner.Cpp && body.Lang != runner.Python {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "lang must be cpp or python"})
return body, nil, false
return body, nil, nil, false
}
l, err := s.readLayout(p.Status, p.Name)
if err != nil {
log.Printf("[code] %s: %v", p.Name, err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"})
return body, nil, false
return body, nil, nil, false
}
if !l.allows(body.Lang) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "a LeetCode problem runs through its C++ driver only"})
return body, nil, false
return body, nil, nil, false
}
return body, l, true
return body, p, l, true
}
// headers are the files written next to a C++ source; Python needs none.
@@ -333,7 +337,7 @@ func (s *Server) run(ctx *gin.Context) {
if !s.runnerConfigured(ctx) {
return
}
body, l, ok := s.readCode(ctx)
body, _, l, ok := s.readCode(ctx)
if !ok {
return
}
@@ -472,7 +476,7 @@ func (s *Server) lint(ctx *gin.Context) {
if !s.runnerConfigured(ctx) {
return
}
body, l, ok := s.readCode(ctx)
body, _, l, ok := s.readCode(ctx)
if !ok {
return
}
@@ -496,7 +500,7 @@ func (s *Server) lint(ctx *gin.Context) {
// saveCode commits the editor's source as the problem's solution. An
// unchanged source makes no commit: Mutate skips an empty diff.
func (s *Server) saveCode(ctx *gin.Context) {
body, _, ok := s.readCode(ctx)
body, _, _, ok := s.readCode(ctx)
if !ok {
return
}
+1
View File
@@ -8,6 +8,7 @@
"name": "usaco-site-web",
"version": "0.0.0",
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-cpp": "^6.0.3",
"@codemirror/lang-python": "^6.2.1",
+1
View File
@@ -12,6 +12,7 @@
"preview": "vite preview"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-cpp": "^6.0.3",
"@codemirror/lang-python": "^6.2.1",
+5
View File
@@ -60,6 +60,11 @@ export const runCode = (name, body) => request("POST", `/problems/${encodeURICom
export const lintCode = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/lint`, body);
// Commits the source as the problem's solution file in that language.
export const saveCode = (name, body) => request("PUT", `/problems/${encodeURIComponent(name)}/code`, body);
// body: { lang, source, note? }. Starts Claude judging the source (after a
// run of the saved tests) and answers 202; the status's result is the
// evaluation once it is done. Nothing is committed.
export const startEvaluate = (name, body) => request("POST", `/problems/${encodeURIComponent(name)}/evaluate`, body);
export const evaluateStatus = (name) => request("GET", `/problems/${encodeURIComponent(name)}/evaluate`);
// Imports today's LeetCode daily question (or finds it, if it is already a
// problem) and answers { name, created }. It takes a few seconds.
export const startDaily = () => request("POST", "/leetcode/daily");
+258
View File
@@ -0,0 +1,258 @@
/**
* The solve page's autocomplete. CodeMirror's basicSetup already shows
* completions as you type, but @codemirror/lang-cpp offers none, and
* lang-python only keywords, builtins and the names defined in the file.
*
* Both languages get the library a contest solution reaches for, and
* member names after "." (and "->"), which neither language package does.
* Members are the common STL (or list/dict/str) ones plus every member
* already used in the file: without a type checker, that is as close as a
* completion can get to what the object actually has. C++ also gets every
* name in the file, so the template's macros and typedefs (F, takeI, ll)
* come up with what they expand to, and snippets for the loops and lambdas
* that are typed over and over.
*
* A real language server (clangd) would know types, but would have to run
* beside the code runner and hold a session open per editor; this is local
* and instant.
*/
import { completeFromList, ifNotIn, snippetCompletion as snip } from "@codemirror/autocomplete";
import { syntaxTree } from "@codemirror/language";
import { cppLanguage } from "@codemirror/lang-cpp";
import { pythonLanguage } from "@codemirror/lang-python";
// "a b c" as completions of one type, with a detail (the header).
const words = (list, type, detail) => list.trim().split(/\s+/).map((label) => ({ label, type, detail }));
// ---- C++ ----
const CPP_KEYWORDS = words(
`auto bool break case catch char class const constexpr continue default delete do double else enum explicit
extern false float for friend goto if inline int long mutable namespace new noexcept nullptr operator private
protected public return short signed sizeof static static_assert static_cast struct switch template this throw
true try typedef typename union unsigned using virtual void volatile while`,
"keyword",
);
const CPP_LIBRARY = [
...words(
"vector string array deque list map multimap set multiset unordered_map unordered_set unordered_multimap stack queue priority_queue bitset pair tuple optional function",
"type",
"std",
),
...words("int64_t uint64_t int32_t uint32_t size_t __int128", "type"),
...words("greater less hash", "class", "<functional>"),
...words("cin cout cerr endl", "variable", "<iostream>"),
...words("getline to_string stoi stoll stod freopen printf scanf puts", "function", "<string>/<cstdio>"),
...words(
`sort stable_sort reverse min max swap minmax lower_bound upper_bound equal_range binary_search unique fill
find find_if count count_if max_element min_element next_permutation prev_permutation nth_element
partial_sort rotate all_of any_of none_of transform copy remove remove_if shuffle`,
"function",
"<algorithm>",
),
...words("accumulate iota partial_sum adjacent_difference gcd lcm", "function", "<numeric>"),
...words("abs sqrt sqrtl cbrt pow exp log log2 log10 floor ceil round hypot", "function", "<cmath>"),
...words("make_pair make_tuple tie get move distance next prev advance begin end", "function", "std"),
...words("memset memcpy strlen", "function", "<cstring>"),
...words(
"__builtin_popcount __builtin_popcountll __builtin_clz __builtin_clzll __builtin_ctz __builtin_ctzll __lg",
"function",
"builtin",
),
...words("INT_MAX INT_MIN LLONG_MAX LLONG_MIN UINT_MAX", "constant", "<climits>"),
{ label: "numeric_limits", type: "class", detail: "<limits>" },
{ label: "mt19937", type: "class", detail: "<random>" },
{ label: "chrono", type: "namespace" },
{ label: "std", type: "namespace" },
];
// Nothing knows the object's type, so the members used most come first.
const COMMON_MEMBERS = new Set(["push_back", "size", "begin", "end", "first", "second", "back", "pop_back", "insert", "count"]);
const CPP_MEMBERS = words(
`push_back emplace_back pop_back push_front emplace_front pop_front back front size empty clear begin end
rbegin rend insert emplace erase find count lower_bound upper_bound resize reserve assign at data swap
push pop top first second substr length append c_str compare set reset flip test any none all to_string
to_ullong value has_value`,
"method",
).map((c) => (COMMON_MEMBERS.has(c.label) ? { ...c, boost: 1 } : c));
// The template's habits, as snippets. Same-named fields are edited
// together, so typing the loop variable once fills in all three.
const CPP_SNIPPETS = [
snip("for (int ${i} = 0; ${i} < ${n}; ${i}++) {\n\t${}\n}", { label: "for", detail: "loop", type: "keyword" }),
snip("for (int ${i} = ${n} - 1; ${i} >= 0; ${i}--) {\n\t${}\n}", { label: "forr", detail: "loop down", type: "keyword" }),
snip("for (auto &${x} : ${v}) {\n\t${}\n}", { label: "foreach", detail: "range loop", type: "keyword" }),
snip("while (${}) {\n\t${}\n}", { label: "while", detail: "loop", type: "keyword" }),
snip("if (${}) {\n\t${}\n}", { label: "if", detail: "block", type: "keyword" }),
snip("if (${}) {\n\t${}\n} else {\n\t${}\n}", { label: "ifelse", detail: "block", type: "keyword" }),
snip("struct ${Name} {\n\t${}\n};", { label: "struct", detail: "definition", type: "keyword" }),
snip("auto ${f} = [&](${}) {\n\t${}\n};", { label: "lambda", detail: "[&] lambda", type: "keyword" }),
snip("function<void(int)> ${dfs} = [&](int ${u}) {\n\t${}\n};", {
label: "dfs",
detail: "recursive lambda",
type: "keyword",
}),
snip("sort(${a}.begin(), ${a}.end(), [&](const auto &${x}, const auto &${y}) {\n\treturn ${};\n});", {
label: "sortby",
detail: "sort with a comparator",
type: "keyword",
}),
];
// A keyword with a snippet of the same name would hide it behind a plain
// word, so the snippet stands in for it.
const SNIPPED = new Set(CPP_SNIPPETS.map((c) => c.label));
const CPP_FIXED = [...CPP_KEYWORDS.filter((c) => !SNIPPED.has(c.label)), ...CPP_LIBRARY, ...CPP_SNIPPETS];
const CPP_FIXED_LABELS = new Set(CPP_FIXED.map((c) => c.label));
// Comments, strings and #include <...> get no completions.
const CPP_SKIP = new Set(["LineComment", "BlockComment", "String", "RawString", "CharLiteral", "SystemLibString"]);
const CPP_NAMES = new Set(["Identifier", "TypeIdentifier", "NamespaceIdentifier"]);
// "#define F(i, L, R) for (...)": a macro, shown with its parameters and
// what it expands to.
const DEFINE = /^[ \t]*#[ \t]*define[ \t]+([A-Za-z_]\w*)(\([^)]*\))?/dgm;
// "typedef long long ll;" and "using vi = vector<int>;"
const ALIAS = /\btypedef\s+([^;]+?)\s+([A-Za-z_]\w*)\s*;|\busing\s+([A-Za-z_]\w*)\s*=\s*([^;]+);/g;
function brief(s) {
s = s.replace(/\s+/g, " ").trim();
return s.length > 48 ? s.slice(0, 47) + "…" : s;
}
// A macro's body: the rest of its line, and the next while a line ends in
// a backslash.
function macroBody(text, at) {
let body = "";
for (;;) {
const end = text.indexOf("\n", at);
const line = text.slice(at, end < 0 ? text.length : end);
if (!line.endsWith("\\") || end < 0) return body + line;
body += line.slice(0, -1) + " ";
at = end + 1;
}
}
// The file's own names, leaving out the word being typed (at skipFrom):
// otherwise every half-typed name would complete to itself.
function cppFileNames(state, skipFrom) {
const text = state.doc.toString();
const out = new Map();
for (const m of text.matchAll(DEFINE)) {
if (m.indices[1][0] === skipFrom) continue;
const body = brief(macroBody(text, m.index + m[0].length));
// The template defines DBG twice, the #else one empty: keep the one
// that says something.
if (!body && out.has(m[1])) continue;
out.set(m[1], {
label: m[1],
type: m[2] ? "function" : "constant",
detail: m[2] ? m[2].replace(/\s+/g, "") : undefined,
info: body || undefined,
boost: 2,
});
}
for (const m of text.matchAll(ALIAS)) {
const [name, to] = m[2] ? [m[2], m[1]] : [m[3], m[4]];
if (!out.has(name)) out.set(name, { label: name, type: "type", detail: brief(to), boost: 2 });
}
syntaxTree(state).iterate({
enter(n) {
if (CPP_SKIP.has(n.name)) return false;
if (!CPP_NAMES.has(n.name) || n.from === skipFrom) return;
const name = text.slice(n.from, n.to);
if (name.length < 2 || out.has(name) || CPP_FIXED_LABELS.has(name)) return;
out.set(name, { label: name, type: n.name === "TypeIdentifier" ? "type" : "variable", boost: 1 });
},
});
return [...out.values()];
}
// Members already used in the file (x.first, it->second, seg.query).
function fileMembers(state, nodeName, skipFrom, known) {
const out = [];
const seen = new Set(known);
syntaxTree(state).iterate({
enter(n) {
if (n.name !== nodeName || n.from === skipFrom) return;
const name = state.sliceDoc(n.from, n.to);
if (seen.has(name)) return;
seen.add(name);
out.push({ label: name, type: "property" });
},
});
return out;
}
const CPP_MEMBER_LABELS = CPP_MEMBERS.map((c) => c.label);
// Whether the word at from follows a member access: "." but not the one in
// "1." (a number), and in C++ "->" too.
function afterMember(state, from, arrow) {
const text = state.sliceDoc(Math.max(0, from - 32), from);
if (arrow && text.endsWith("->")) return true;
return text.endsWith(".") && !/(^|[^\w])\d+\.$/.test(text);
}
function cppSource(context) {
const node = syntaxTree(context.state).resolveInner(context.pos, -1);
for (let n = node; n; n = n.parent) if (CPP_SKIP.has(n.name)) return null;
const word = context.matchBefore(/[A-Za-z_]\w*/);
const from = word ? word.from : context.pos;
if (afterMember(context.state, from, true)) {
return {
from,
options: [...CPP_MEMBERS, ...fileMembers(context.state, "FieldIdentifier", from, CPP_MEMBER_LABELS)],
validFor: /^\w*$/,
};
}
if (!word && !context.explicit) return null;
return { from, options: [...cppFileNames(context.state, from), ...CPP_FIXED], validFor: /^\w*$/ };
}
export const cppCompletions = () => cppLanguage.data.of({ autocomplete: cppSource });
// ---- Python ----
// The standard library a contest solution imports from. lang-python
// already completes builtins and the file's own names, and has its own
// def/for/class snippets.
const PY_LIBRARY = [
...words("defaultdict Counter deque OrderedDict", "class", "collections"),
...words("heappush heappop heapify heappushpop nlargest nsmallest", "function", "heapq"),
...words("bisect_left bisect_right insort", "function", "bisect"),
...words("lru_cache cache cmp_to_key reduce", "function", "functools"),
...words("accumulate permutations combinations combinations_with_replacement product groupby pairwise", "function", "itertools"),
...words("gcd lcm isqrt comb perm inf sqrt log2 ceil floor", "function", "math"),
...words("setrecursionlimit stdin stdout", "function", "sys"),
snip("sys.setrecursionlimit(${10 ** 6})", { label: "recursionlimit", detail: "sys", type: "keyword" }),
];
const PY_MEMBERS = words(
`append extend insert pop remove clear sort reverse index count copy keys values items get setdefault update
add discard union intersection difference split join strip lstrip rstrip startswith endswith replace find
lower upper isdigit appendleft popleft most_common read readline buffer`,
"method",
);
const PY_MEMBER_LABELS = PY_MEMBERS.map((c) => c.label);
const pyLibrary = completeFromList(PY_LIBRARY);
function pySource(context) {
const word = context.matchBefore(/[A-Za-z_]\w*/);
const from = word ? word.from : context.pos;
if (afterMember(context.state, from, false)) {
return {
from,
options: [...PY_MEMBERS, ...fileMembers(context.state, "PropertyName", from, PY_MEMBER_LABELS)],
validFor: /^\w*$/,
};
}
// lang-python leaves property names alone; everywhere else the library
// joins its builtins.
return pyLibrary(context);
}
export const pythonCompletions = () =>
pythonLanguage.data.of({ autocomplete: ifNotIn(["String", "FormatString", "Comment"], pySource) });
+25 -4
View File
@@ -14,6 +14,9 @@
* is remote and debounced by the page), and are pushed with setDiagnostics
* rather than through a linter() source the editor would schedule itself.
* CodeMirror maps them through later edits until the next set arrives.
*
* Completions come from basicSetup's autocompletion with sources of our own
* (completions.js), since lang-cpp has none.
*/
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { basicSetup } from "codemirror";
@@ -25,6 +28,7 @@ import { lintGutter, setDiagnostics } from "@codemirror/lint";
import { cpp } from "@codemirror/lang-cpp";
import { python } from "@codemirror/lang-python";
import { tags as t } from "@lezer/highlight";
import { cppCompletions, pythonCompletions } from "@/completions";
const props = defineProps({
modelValue: { type: String, required: true },
@@ -37,9 +41,9 @@ const emit = defineEmits(["update:modelValue", "run", "submit", "save"]);
// The workspace's styles: clang-format's two spaces for C++, PEP 8's four.
const LANGS = {
cpp: () => [cpp(), indentUnit.of(" ")],
c: () => [cpp(), indentUnit.of(" ")],
python: () => [python(), indentUnit.of(" ")],
cpp: () => [cpp(), cppCompletions(), indentUnit.of(" ")],
c: () => [cpp(), cppCompletions(), indentUnit.of(" ")],
python: () => [python(), pythonCompletions(), indentUnit.of(" ")],
};
const highlight = HighlightStyle.define([
@@ -95,6 +99,14 @@ const theme = EditorView.theme(
".cm-diagnostic-info": { borderLeftColor: "var(--color-ink-faint)" },
".cm-diagnosticSource": { color: "var(--color-ink-muted)" },
".cm-panels": { backgroundColor: "var(--color-paper-tint)", color: "var(--color-ink)" },
".cm-tooltip.cm-tooltip-autocomplete > ul": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", maxHeight: "16em" },
".cm-tooltip.cm-tooltip-autocomplete > ul > li": { padding: "1px 8px 1px 4px" },
".cm-tooltip-autocomplete ul li[aria-selected]": { backgroundColor: "#d7e6fb", color: "var(--color-ink)" },
".cm-completionMatchedText": { textDecoration: "none", fontWeight: "600" },
".cm-completionDetail": { color: "var(--color-ink-muted)", fontStyle: "normal", marginLeft: "1em" },
".cm-completionIcon": { opacity: "0.55" },
".cm-tooltip.cm-completionInfo": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "4px 8px" },
".cm-snippetField": { backgroundColor: "rgba(0, 0, 0, 0.05)" },
},
{ dark: false },
);
@@ -186,7 +198,16 @@ watch(
);
watch(() => props.diagnostics, () => view && pushDiagnostics());
defineExpose({ focus: () => view?.focus() });
// Puts the cursor at the start of a line's code and shows it.
function goto(line) {
if (!view) return;
const l = view.state.doc.line(Math.min(Math.max(line, 1), view.state.doc.lines));
const at = l.from + (/^\s*/.exec(l.text)?.[0].length || 0);
view.dispatch({ selection: { anchor: at }, effects: EditorView.scrollIntoView(at, { y: "center" }) });
view.focus();
}
defineExpose({ focus: () => view?.focus(), goto });
</script>
<template>
@@ -0,0 +1,280 @@
<script setup>
/**
* The solve page's Evaluation tab: Claude's judgement of the code in the
* editor (internal/evaluate), after a run of the saved tests.
*
* It is about the source it was given, which the editor may have moved on
* from: the report says so rather than hiding, since most of it still
* applies after a small fix. Its issues are also marked in the editor by
* the page, on the lines they were about, for as long as those lines are
* unchanged.
*/
import { computed } from "vue";
import CodeBlock from "@/components/CodeBlock.vue";
import { markdown } from "@/markdown";
import { EVAL_VERDICTS, LANG_LABELS } from "@/format";
const props = defineProps({
// The job: { state: idle | running | done | error, error? }.
job: { type: Object, required: true },
evaluation: { type: Object, default: null },
// The editor's language, and whether its source is still the one judged.
lang: { type: String, required: true },
stale: { type: Boolean, default: false },
// Why Evaluate is off, or "".
disabled: { type: String, default: "" },
note: { type: String, default: "" },
});
defineEmits(["evaluate", "goto", "use-input", "update:note"]);
const md = markdown();
const render = (s) => (s ? md.render(s) : "");
const ev = computed(() => props.evaluation);
const verdict = computed(() => EVAL_VERDICTS[ev.value?.verdict] || { label: ev.value?.verdict, tone: "plain" });
const otherLang = computed(() => !!ev.value && ev.value.lang !== props.lang);
const running = computed(() => props.job.state === "running");
const at = computed(() =>
ev.value ? new Date(ev.value.at).toLocaleString(undefined, { hour: "2-digit", minute: "2-digit", day: "numeric", month: "short" }) : "",
);
const counter = computed(() => (ev.value?.counterexample?.input ? ev.value.counterexample : null));
</script>
<template>
<div class="evaluation">
<form class="ask" @submit.prevent="$emit('evaluate')">
<input
:value="note"
type="text"
maxlength="4000"
placeholder="Anything to check? (optional) e.g. overflow, the n = 1 case"
aria-label="What Claude should look at"
@input="$emit('update:note', $event.target.value)"
/>
<button class="btn" type="submit" :disabled="!!disabled || running" :title="disabled">
{{ running ? "Evaluating…" : ev ? "Evaluate again" : "Evaluate" }}
</button>
</form>
<p v-if="running" class="working" role="status">
Running the saved tests, then Claude reads the code. This takes a minute or two.
</p>
<p v-else-if="job.state === 'error'" class="error" role="status">Evaluation failed: {{ job.error }}</p>
<p v-else-if="!ev" class="muted intro">
Claude judges the code in the editor against the statement and the saved tests' verdicts: whether it will be
accepted, its complexity, the lines that are wrong, and an input that breaks it. Nothing is committed.
</p>
<template v-if="ev">
<p class="facts">
<span class="badge verdict" :class="verdict.tone">{{ verdict.label }}</span>
<span v-if="ev.tests" class="muted">Tests: {{ ev.tests }}</span>
<span class="muted">{{ LANG_LABELS[ev.lang] || ev.lang }} · {{ ev.model }} · {{ at }}</span>
</p>
<p v-if="otherLang" class="stale">
This is about your {{ LANG_LABELS[ev.lang] || ev.lang }} code; its issues are not marked in this editor.
</p>
<p v-else-if="stale" class="stale">
The code has changed since. Issues stay marked on the lines that haven't.
</p>
<div class="prose" v-html="render(ev.summary)"></div>
<section v-if="ev.issues?.length">
<h3>Issues</h3>
<ul class="issues">
<li v-for="(is, i) in ev.issues" :key="i">
<p class="issue-head">
<span class="sev" :class="is.severity" :title="is.severity" aria-hidden="true"></span>
<button v-if="is.line && !otherLang" type="button" class="line" @click="$emit('goto', is.line)">
Line {{ is.line }}
</button>
<span v-else-if="is.line" class="line plain">Line {{ is.line }}</span>
<strong>{{ is.title }}</strong>
<span class="visually-hidden">({{ is.severity }})</span>
</p>
<div class="prose detail" v-html="render(is.detail)"></div>
</li>
</ul>
</section>
<section v-if="counter">
<h3>Counterexample</h3>
<div class="io">
<div>
<p class="filename muted">Input</p>
<CodeBlock :content="counter.input" />
</div>
<div>
<p class="filename muted">Expected</p>
<CodeBlock :content="counter.expected" />
</div>
</div>
<div class="prose" v-html="render(counter.why)"></div>
<button class="btn" type="button" @click="$emit('use-input', counter.input)">Use as custom input</button>
</section>
<section v-if="ev.correctness">
<h3>Correctness</h3>
<div class="prose" v-html="render(ev.correctness)"></div>
</section>
<section v-if="ev.complexity">
<h3>Complexity</h3>
<div class="prose" v-html="render(ev.complexity)"></div>
</section>
<section v-if="ev.style">
<h3>Style</h3>
<div class="prose" v-html="render(ev.style)"></div>
</section>
</template>
</div>
</template>
<style scoped>
.evaluation {
display: grid;
gap: 12px;
min-width: 0;
font-size: 0.9rem;
}
.evaluation > * {
min-width: 0;
}
.ask {
display: flex;
gap: 8px;
}
.ask input {
flex: 1;
min-width: 0;
padding: 6px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
font-size: 0.85rem;
color: var(--color-ink);
background: var(--color-paper);
}
.intro {
font-size: 0.85rem;
}
.facts {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 12px;
font-size: 0.85rem;
}
.verdict {
font-size: 0.8rem;
}
.verdict.ok {
color: var(--color-solved);
border-color: currentColor;
}
.verdict.warn {
color: var(--color-solving);
border-color: currentColor;
}
.verdict.bad {
color: var(--color-ink-danger);
border-color: currentColor;
}
.stale {
font-size: 0.85rem;
color: var(--color-solving);
}
h3 {
font-size: 1.05rem;
margin-bottom: 6px;
}
.issues {
list-style: none;
padding: 0;
margin: 0;
display: grid;
gap: 10px;
}
.issue-head {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 8px;
}
.detail {
margin: 2px 0 0 16px;
}
.sev {
width: 8px;
height: 8px;
border-radius: 50%;
flex: none;
background: var(--color-ink-faint);
}
.sev.error {
background: var(--color-ink-danger);
}
.sev.warning {
background: var(--color-solving);
}
.line {
font-family: var(--font-mono);
font-size: 0.8rem;
padding: 0 6px;
border: 1px solid var(--color-line);
border-radius: 4px;
background: var(--color-paper-tint);
color: var(--color-ink-link);
cursor: pointer;
}
.line.plain {
color: var(--color-ink-muted);
cursor: default;
}
.io {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
margin-bottom: 8px;
}
.io > div {
min-width: 0;
}
.filename {
font-family: var(--font-mono);
font-size: 0.8rem;
margin-bottom: 4px;
}
section > .btn {
margin-top: 8px;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
/* The results panel's pulsing dot: the job is still going. */
.working {
font-size: 0.85rem;
}
.working::before {
content: "";
display: inline-block;
width: 8px;
height: 8px;
margin-right: 8px;
border-radius: 50%;
background: var(--color-solving);
animation: pulse 1.2s ease-in-out infinite;
}
@keyframes pulse {
50% {
opacity: 0.25;
}
}
@media (prefers-reduced-motion: reduce) {
.working::before {
animation: none;
}
}
</style>
+21 -3
View File
@@ -7,6 +7,9 @@
*
* After a run the panel opens the tab worth reading first: the compile
* error, else the first test that failed, else the first test.
*
* With evaluationTab set there is also an Evaluation tab, whose content is
* the page's (the evaluation slot); the page opens it with show().
*/
import { computed, ref, watch } from "vue";
import CodeBlock from "@/components/CodeBlock.vue";
@@ -19,6 +22,8 @@ const props = defineProps({
running: { type: String, default: "" },
error: { type: String, default: "" },
modelValue: { type: String, default: "" },
// { label, tone: ok | warn | bad | plain | "" } for the Evaluation tab.
evaluationTab: { type: Object, default: null },
});
defineEmits(["update:modelValue"]);
@@ -38,6 +43,7 @@ const warnings = computed(() => compile.value?.ok && compile.value.output?.trim(
const tabs = computed(() => {
const out = [{ id: "custom", label: "Custom input" }];
if (props.evaluationTab) out.push({ id: "evaluation", ...props.evaluationTab });
if (compile.value && !compile.value.ok) out.push({ id: "compile", label: "Compile error", verdict: "bad" });
if (warnings.value) out.push({ id: "warnings", label: "Warnings" });
results.value.forEach((r, i) => {
@@ -77,6 +83,8 @@ const summary = computed(() => {
});
const verdictClass = (v) => (v === "AC" ? "ok" : v === "unchecked" || !v ? "plain" : "bad");
defineExpose({ show: (id) => (tab.value = id) });
</script>
<template>
@@ -94,7 +102,12 @@ const verdictClass = (v) => (v === "AC" ? "ok" : v === "unchecked" || !v ? "plai
:class="{ on: tab === tb.id }"
@click="tab = tb.id"
>
<span v-if="tb.verdict" class="dot" :class="verdictClass(tb.verdict)" aria-hidden="true"></span>
<span
v-if="tb.verdict || tb.tone"
class="dot"
:class="tb.tone || verdictClass(tb.verdict)"
aria-hidden="true"
></span>
{{ tb.label }}
</button>
</div>
@@ -105,9 +118,11 @@ const verdictClass = (v) => (v === "AC" ? "ok" : v === "unchecked" || !v ? "plai
</div>
<div id="run-panel" class="body" role="tabpanel" :aria-labelledby="`tab-${tab}`">
<p v-if="error" class="error">{{ error }}</p>
<p v-if="error && tab !== 'evaluation'" class="error">{{ error }}</p>
<label v-if="tab === 'custom'" class="custom">
<slot v-if="tab === 'evaluation'" name="evaluation"></slot>
<label v-else-if="tab === 'custom'" class="custom">
<span class="muted">
Input for Run ({{ MOD_KEY }}+Enter). Submit ({{ MOD_KEY }}+Shift+Enter) runs the saved tests instead.
</span>
@@ -219,6 +234,9 @@ const verdictClass = (v) => (v === "AC" ? "ok" : v === "unchecked" || !v ? "plai
.dot.bad {
background: var(--color-ink-danger);
}
.dot.warn {
background: var(--color-solving);
}
.summary,
.working {
font-size: 0.85rem;
+9
View File
@@ -4,6 +4,15 @@
export const STATUS_LABELS = { solving: "Solving", solved: "Solved", skipped: "Skipped" };
// internal/evaluate's verdicts, with a tone for badges and tab dots.
export const EVAL_VERDICTS = {
correct: { label: "Looks correct", tone: "ok" },
edge_cases: { label: "Misses edge cases", tone: "warn" },
too_slow: { label: "Too slow", tone: "bad" },
wrong: { label: "Wrong", tone: "bad" },
incomplete: { label: "Unfinished", tone: "plain" },
};
export const LANG_LABELS = { cpp: "C++", c: "C", python: "Python", java: "Java", rust: "Rust", go: "Go" };
// "diamond-collector" -> "Diamond Collector"
+169 -6
View File
@@ -2,22 +2,25 @@
/**
* Solve a problem in the browser (admin only): the statement and saved
* tests on the left, an editor on the right with Run (the custom input),
* Submit (the saved tests) and Save (a commit, like the CLI's).
* Submit (the saved tests), Evaluate (Claude's judgement of the code, after
* a run of the tests) and Save (a commit, like the CLI's).
*
* What is typed is kept as a draft in this browser per problem and language
* until it is saved or reset, so leaving the page loses nothing and there
* is no "unsaved changes" prompt. Runs and lints are plain requests to the
* server, which passes them to the code runner: a run answers when it has
* finished, which can take up to a minute.
* finished, which can take up to a minute. An evaluation takes longer
* than nginx waits, so it is a job the page polls, as on the problem page.
*/
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { RouterLink } from "vue-router";
import CodeBlock from "@/components/CodeBlock.vue";
import CodeEditor from "@/components/CodeEditor.vue";
import EvaluationReport from "@/components/EvaluationReport.vue";
import RunResults from "@/components/RunResults.vue";
import { markdown } from "@/markdown";
import { getCode, getMe, getProblem, lintCode, runCode, saveCode } from "@/api";
import { LANG_LABELS, MOD_KEY, STATUS_LABELS, title } from "@/format";
import { evaluateStatus, getCode, getMe, getProblem, lintCode, runCode, saveCode, startEvaluate } from "@/api";
import { EVAL_VERDICTS, LANG_LABELS, MOD_KEY, STATUS_LABELS, title } from "@/format";
const props = defineProps({ name: { type: String, required: true } });
@@ -44,6 +47,15 @@ const diagnostics = ref([]);
const linted = ref(false);
const lintError = ref("");
const editor = ref(null);
const results = ref(null);
const evalJob = ref({ state: "idle" });
const evaluation = ref(null);
const evalNote = ref("");
const evalDiagnostics = ref([]);
// The lint's marks and Claude's together; lintSummary counts the lint's.
const editorDiagnostics = computed(() => [...diagnostics.value, ...evalDiagnostics.value]);
const statementHtml = computed(() => (problem.value?.statement ? md.render(problem.value.statement) : ""));
const current = computed(() => info.value?.code[lang.value]);
const dirty = computed(() => !!current.value && source.value !== current.value.source);
@@ -62,6 +74,7 @@ const codeStatus = computed(() => {
async function load() {
flushDraft();
clearTimeout(lintTimer);
stopEvalPolling();
const name = props.name;
loading.value = true;
error.value = "";
@@ -73,6 +86,10 @@ async function load() {
notice.value = "";
diagnostics.value = [];
linted.value = false;
evalJob.value = { state: "idle" };
evaluation.value = null;
evalNote.value = "";
evalDiagnostics.value = [];
try {
const [p, me] = await Promise.all([getProblem(name), getMe().catch(() => ({ admin: false }))]);
if (name !== props.name) return;
@@ -86,6 +103,8 @@ async function load() {
if (name !== props.name) return;
info.value = c;
open(c.code[c.default] ? c.default : c.languages[0]);
// The server keeps the last evaluation until it restarts.
if (c.claude) checkEvaluate();
} catch (e) {
if (name !== props.name) return;
problem.value = null;
@@ -105,6 +124,7 @@ function open(l) {
lintError.value = "";
notice.value = "";
saveError.value = "";
anchorIssues();
lintSoon();
}
@@ -194,6 +214,8 @@ async function lintNow() {
const r = await lintCode(name, { lang: l, source: src });
if (seq !== lintSeq || name !== props.name || l !== lang.value || src !== source.value) return;
diagnostics.value = r.diagnostics || [];
// Re-placed against the same text, so the two sets agree.
anchorIssues();
linted.value = true;
lintError.value = "";
} catch (e) {
@@ -258,6 +280,114 @@ async function save() {
}
}
// ---- evaluate ----
// Polled every 3 s while it runs, as the problem page's jobs are. A job
// that fails leaves the last evaluation on show under its error.
let evalPoll = null;
function stopEvalPolling() {
clearTimeout(evalPoll);
evalPoll = null;
}
async function checkEvaluate() {
stopEvalPolling();
const name = props.name;
try {
const s = await evaluateStatus(name);
if (name !== props.name) return;
const finished = evalJob.value.state === "running" && s.state !== "running";
evalJob.value = s;
if (s.result) evaluation.value = s.result;
if (s.state === "running") evalPoll = setTimeout(checkEvaluate, 3000);
else if (finished) results.value?.show("evaluation");
} catch (e) {
if (name === props.name) evalJob.value = { state: "error", error: e.message };
}
}
const evalDisabled = computed(() => {
if (!info.value?.claude) return "Claude isn't configured on this server (CLAUDE_API_KEY)";
if (!problem.value?.statement && !problem.value?.url) return "Add the statement or a link on the problem page first";
if (!source.value.trim()) return "The editor is empty";
return "";
});
const evaluating = computed(() => evalJob.value.state === "running");
const canEvaluate = computed(() => !evalDisabled.value && !evaluating.value);
async function evaluate() {
if (!canEvaluate.value) return;
const name = props.name;
results.value?.show("evaluation");
try {
const s = await startEvaluate(name, { lang: lang.value, source: source.value, note: evalNote.value });
if (name !== props.name) return;
evalJob.value = s;
evalPoll = setTimeout(checkEvaluate, 3000);
} catch (e) {
if (name !== props.name) return;
// Started from another tab: follow that one.
if (e.status === 409) checkEvaluate();
else evalJob.value = { state: "error", error: e.message };
}
}
// Whether the editor still holds what was judged. In another language it
// is a different file, which the report says instead.
const evalStale = computed(() => {
const ev = evaluation.value;
return !!ev && ev.lang === lang.value && ev.source !== source.value;
});
const evaluationTab = computed(() => {
if (!info.value?.claude) return null;
if (evaluating.value) return { label: "Evaluation", tone: "plain" };
return { label: "Evaluation", tone: EVAL_VERDICTS[evaluation.value?.verdict]?.tone || "" };
});
// Claude's issues as editor marks, on the lines they were about. Once the
// code has changed, a line is found again by its text, at the copy nearest
// to where it was; a line edited since loses its mark, which is usually
// the fix. Called when the evaluation, the language or the lint changes,
// and CodeMirror moves the marks through edits in between.
function anchorIssues() {
const ev = evaluation.value;
if (!ev || ev.lang !== lang.value) {
evalDiagnostics.value = [];
return;
}
const same = ev.source === source.value;
const was = ev.source.split("\n");
const now = source.value.split("\n");
const out = [];
for (const is of ev.issues || []) {
const text = was[is.line - 1];
if (!is.line || text === undefined) continue;
let line = same ? is.line : 0;
for (let d = 0; !line && text.trim() && d < now.length; d++) {
if (now[is.line - 1 - d] === text) line = is.line - d;
else if (now[is.line - 1 + d] === text) line = is.line + d;
}
if (!line) continue;
out.push({
line,
col: /^\s*/.exec(text)[0].length + 1,
endLine: line,
endCol: text.length + 1,
severity: is.severity,
message: is.detail ? `${is.title}\n\n${is.detail}` : is.title,
source: "Claude",
});
}
evalDiagnostics.value = out;
}
watch(evaluation, anchorIssues);
function useInput(input) {
customInput.value = input;
results.value?.show("custom");
}
// The editor handles these itself while it has focus (and stops them);
// this is for everywhere else on the page, the custom input included.
function onKey(e) {
@@ -280,6 +410,7 @@ onUnmounted(() => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pagehide", flushDraft);
clearTimeout(lintTimer);
stopEvalPolling();
flushDraft();
});
@@ -431,6 +562,15 @@ watch(() => props.name, load, { immediate: true });
>
{{ running === "tests" ? "Submitting…" : "Submit" }}
</button>
<button
class="btn"
type="button"
:disabled="!canEvaluate"
:title="evalDisabled || 'Run the saved tests and have Claude judge this code'"
@click="evaluate"
>
{{ evaluating ? "Evaluating…" : "Evaluate" }}
</button>
<button class="btn" type="button" :disabled="!canSave" :title="`Commit to the repo (${MOD_KEY}+S)`" @click="save">
{{ saving ? "Saving…" : "Save" }}
</button>
@@ -455,17 +595,40 @@ watch(() => props.name, load, { immediate: true });
</p>
<CodeEditor
ref="editor"
v-model="source"
class="code"
:lang="lang"
:diagnostics="diagnostics"
:diagnostics="editorDiagnostics"
:label="`${LANG_LABELS[lang] || lang} solution`"
@run="run('custom')"
@submit="run('tests')"
@save="save"
/>
<RunResults v-model="customInput" class="out" :result="result" :running="running" :error="runError" />
<RunResults
ref="results"
v-model="customInput"
class="out"
:result="result"
:running="running"
:error="runError"
:evaluation-tab="evaluationTab"
>
<template #evaluation>
<EvaluationReport
v-model:note="evalNote"
:job="evalJob"
:evaluation="evaluation"
:lang="lang"
:stale="evalStale"
:disabled="evalDisabled"
@evaluate="evaluate"
@goto="(line) => editor?.goto(line)"
@use-input="useInput"
/>
</template>
</RunResults>
</div>
</div>
</template>