Split the job tracker out of web_server into its own app
The applications tracker, leads inbox, email pipeline and capture userscript move here from web_server's backend, Python service and Vue app, as one Go binary that serves its own Vue SPA under /jobs/. - The Go services, resolvers and tests move over almost unchanged. - The three Claude calls are ported from Python to Go (internal/claude), with the same prompts, per-model request shaping and error messages. - There is no login: internal/auth asks the site backend's /auth/validate-admin with the visitor's cookies, and relays refreshed cookies back. - A Settings page replaces the admin-panel capture token card and adds the Microsoft sign-in link and a manual email sync. - The userscript is 2.0.0, at /jobs/, and migrates a saved API base. - Dockerfile, a standalone compose with Postgres, Makefile, and a Gitea CI workflow that tests and publishes the image. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,411 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
)
|
||||
|
||||
// These tests run the real SDK against a fake Messages API, so what is
|
||||
// pinned is the request as it goes over the wire and the handling of every
|
||||
// kind of reply. Ported from the main site's python/tests/test_claude.py,
|
||||
// test_jobs.py, test_job_score.py and test_email_classify.py.
|
||||
|
||||
// fakeAPI answers POST /v1/messages with status and body, and records each
|
||||
// request body it was sent.
|
||||
type fakeAPI struct {
|
||||
status int
|
||||
body string
|
||||
calls []map[string]any
|
||||
}
|
||||
|
||||
func (f *fakeAPI) client(t *testing.T, model string) *Client {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
var call map[string]any
|
||||
if err := json.Unmarshal(raw, &call); err != nil {
|
||||
t.Errorf("request body is not JSON: %s", raw)
|
||||
}
|
||||
f.calls = append(f.calls, call)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(f.status)
|
||||
io.WriteString(w, f.body)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
// No retries: a 529 should fail once, not three times with backoff.
|
||||
return New("test-key", model, option.WithBaseURL(srv.URL), option.WithMaxRetries(0))
|
||||
}
|
||||
|
||||
// message builds a Messages API reply with the given content blocks.
|
||||
func message(stopReason string, blocks ...map[string]any) string {
|
||||
if blocks == nil {
|
||||
blocks = []map[string]any{}
|
||||
}
|
||||
b, _ := json.Marshal(map[string]any{
|
||||
"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-sonnet-5-5",
|
||||
"stop_reason": stopReason, "content": blocks,
|
||||
"usage": map[string]any{"input_tokens": 1, "output_tokens": 1},
|
||||
})
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func text(s string) map[string]any { return map[string]any{"type": "text", "text": s} }
|
||||
|
||||
func thinking() map[string]any {
|
||||
return map[string]any{"type": "thinking", "thinking": "", "signature": "sig"}
|
||||
}
|
||||
|
||||
func replying(s string) *fakeAPI {
|
||||
return &fakeAPI{status: 200, body: message("end_turn", text(s))}
|
||||
}
|
||||
|
||||
type count struct {
|
||||
N int `json:"n"`
|
||||
}
|
||||
|
||||
var testMessages = messages{failed: "call failed", empty: "nothing came back", unparseable: "could not parse"}
|
||||
|
||||
func ask(t *testing.T, api *fakeAPI, model string) (count, error) {
|
||||
t.Helper()
|
||||
return askJSON[count](context.Background(), api.client(t, model), "count things", "how many?", 64, testMessages, nil)
|
||||
}
|
||||
|
||||
func TestAskJSONSendsTheRequestAndDecodesTheReply(t *testing.T) {
|
||||
api := replying(`{"n": 3}`)
|
||||
got, err := ask(t, api, "")
|
||||
if err != nil || got.N != 3 {
|
||||
t.Fatalf("got %+v, %v", got, err)
|
||||
}
|
||||
if len(api.calls) != 1 {
|
||||
t.Fatalf("%d calls, want 1", len(api.calls))
|
||||
}
|
||||
call := api.calls[0]
|
||||
if call["model"] != DefaultModel {
|
||||
t.Errorf("model = %v, want the default %s", call["model"], DefaultModel)
|
||||
}
|
||||
system, _ := json.Marshal(call["system"])
|
||||
if string(system) != `[{"text":"count things","type":"text"}]` {
|
||||
t.Errorf("system = %s", system)
|
||||
}
|
||||
msgs, _ := json.Marshal(call["messages"])
|
||||
if string(msgs) != `[{"content":[{"text":"how many?","type":"text"}],"role":"user"}]` {
|
||||
t.Errorf("messages = %s", msgs)
|
||||
}
|
||||
}
|
||||
|
||||
// Thinking is billed against max_tokens, so the caller's reply ceiling alone
|
||||
// would starve the answer.
|
||||
func TestThinkingModelGetsHeadroomAndLowEffort(t *testing.T) {
|
||||
for _, model := range []string{"claude-sonnet-5-5", "claude-opus-5-5", "some-future-model"} {
|
||||
api := replying(`{}`)
|
||||
ask(t, api, model)
|
||||
call := api.calls[0]
|
||||
if call["max_tokens"] != float64(64+thinkingHeadroom) {
|
||||
t.Errorf("%s: max_tokens = %v, want %d", model, call["max_tokens"], 64+thinkingHeadroom)
|
||||
}
|
||||
if !reflect.DeepEqual(call["output_config"], map[string]any{"effort": "low"}) {
|
||||
t.Errorf("%s: output_config = %v", model, call["output_config"])
|
||||
}
|
||||
// Nothing these models reject: no thinking override, sampling or forced tool.
|
||||
for _, key := range []string{"thinking", "temperature", "top_p", "top_k", "tool_choice"} {
|
||||
if _, ok := call[key]; ok {
|
||||
t.Errorf("%s: request carries %q", model, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Haiku 4.5 rejects output_config.effort and does not think unless asked to.
|
||||
func TestHaikuGetsThePlainRequest(t *testing.T) {
|
||||
api := replying(`{}`)
|
||||
ask(t, api, "claude-haiku-4-5")
|
||||
call := api.calls[0]
|
||||
if call["max_tokens"] != float64(64) {
|
||||
t.Errorf("max_tokens = %v, want 64", call["max_tokens"])
|
||||
}
|
||||
if _, ok := call["output_config"]; ok {
|
||||
t.Errorf("output_config sent to Haiku: %v", call["output_config"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnswerIsFoundAfterAThinkingBlock(t *testing.T) {
|
||||
api := &fakeAPI{status: 200, body: message("end_turn", thinking(), text(`{"n": 7}`))}
|
||||
if got, err := ask(t, api, ""); err != nil || got.N != 7 {
|
||||
t.Fatalf("got %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFencedJSONIsAccepted(t *testing.T) {
|
||||
if got, err := ask(t, replying("```json\n{\"n\": 3}\n```"), ""); err != nil || got.N != 3 {
|
||||
t.Fatalf("got %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEachFailureIsTheCallersMessage(t *testing.T) {
|
||||
refusal := `{"id":"msg_1","type":"message","role":"assistant","model":"m","stop_reason":"refusal",` +
|
||||
`"stop_details":{"type":"refusal","category":"general_harms","explanation":"no"},"content":[],"usage":{"input_tokens":1,"output_tokens":0}}`
|
||||
cases := []struct {
|
||||
name string
|
||||
api *fakeAPI
|
||||
want string
|
||||
}{
|
||||
{"overloaded", &fakeAPI{status: 529, body: `{"type":"error","error":{"type":"overloaded_error","message":"busy"}}`}, "call failed"},
|
||||
{"bad request", &fakeAPI{status: 400, body: `{"type":"error","error":{"type":"invalid_request_error","message":"bad"}}`}, "call failed"},
|
||||
// A refusal is a failed call, not an empty reply.
|
||||
{"refusal", &fakeAPI{status: 200, body: refusal}, "call failed"},
|
||||
{"no content", &fakeAPI{status: 200, body: message("end_turn")}, "nothing came back"},
|
||||
// Out of tokens while thinking.
|
||||
{"only thinking", &fakeAPI{status: 200, body: message("max_tokens", thinking())}, "nothing came back"},
|
||||
{"prose", replying("three, I think"), "could not parse"},
|
||||
// Valid JSON of the wrong shape is the same failure.
|
||||
{"wrong type", replying(`{"n": "lots"}`), "could not parse"},
|
||||
{"array", replying(`[3]`), "could not parse"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
_, err := ask(t, c.api, "")
|
||||
var readErr *ReadError
|
||||
// Exactly the caller's text: it is shown to the admin, so
|
||||
// nothing from the API error or the reply may be appended.
|
||||
if !errors.As(err, &readErr) || err.Error() != c.want {
|
||||
t.Fatalf("err = %v, want ReadError %q", err, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnreachableAPIIsAFailedCall(t *testing.T) {
|
||||
c := New("test-key", "", option.WithBaseURL("http://127.0.0.1:1"), option.WithMaxRetries(0))
|
||||
_, err := askJSON[count](context.Background(), c, "s", "u", 64, testMessages, nil)
|
||||
if err == nil || err.Error() != "call failed" {
|
||||
t.Fatalf("err = %v, want \"call failed\"", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The caller giving up must stay visible as the context's error: the email
|
||||
// pipeline does not count an abandoned sync against the email.
|
||||
func TestCancelledCallIsNotAReadError(t *testing.T) {
|
||||
api := replying(`{"n": 1}`)
|
||||
c := api.client(t, "")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := askJSON[count](ctx, c, "s", "u", 64, testMessages, nil)
|
||||
var readErr *ReadError
|
||||
if !errors.Is(err, context.Canceled) || errors.As(err, &readErr) {
|
||||
t.Fatalf("err = %v, want a wrapped context.Canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingAPIKeyIsNotConfigured(t *testing.T) {
|
||||
for _, c := range []*Client{New("", ""), nil} {
|
||||
_, err := c.ExtractPosting(context.Background(), "", "", "x")
|
||||
if !errors.Is(err, ErrNotConfigured) {
|
||||
t.Fatalf("err = %v, want ErrNotConfigured", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlankModelIsTheDefault(t *testing.T) {
|
||||
if m := New("k", " ").Model(); m != DefaultModel {
|
||||
t.Fatalf("Model() = %q", m)
|
||||
}
|
||||
}
|
||||
|
||||
// --- posting.go -----------------------------------------------------------
|
||||
|
||||
func TestExtractPostingSendsThePageAsDelimitedData(t *testing.T) {
|
||||
api := replying(`{"jobTitle": "Engineer", "company": "Acme", "location": "London", "notes": "£70k, hybrid"}`)
|
||||
got, err := api.client(t, "").ExtractPosting(context.Background(),
|
||||
"https://jobs.example/1", "Engineer | Acme", "Acme is hiring an Engineer in London.")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.JobTitle != "Engineer" || got.Company != "Acme" || *got.Location != "London" || *got.Notes != "£70k, hybrid" {
|
||||
t.Errorf("got %+v", got)
|
||||
}
|
||||
call := api.calls[0]
|
||||
if call["system"].([]any)[0].(map[string]any)["text"] != postingSystem {
|
||||
t.Error("system prompt is not postingSystem")
|
||||
}
|
||||
user := call["messages"].([]any)[0].(map[string]any)["content"].([]any)[0].(map[string]any)["text"]
|
||||
want := "<url>https://jobs.example/1</url>\n<title>Engineer | Acme</title>\n<page>\nAcme is hiring an Engineer in London.\n</page>"
|
||||
if user != want {
|
||||
t.Errorf("user turn = %q\nwant %q", user, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractPostingNormalisesTheReply(t *testing.T) {
|
||||
cases := []struct {
|
||||
reply string
|
||||
title, company string
|
||||
hasLocation, hasN bool
|
||||
}{
|
||||
// Not a posting: the popup is filled in by hand rather than erroring.
|
||||
{`{"jobTitle": "", "company": "", "location": null, "notes": null}`, "", "", false, false},
|
||||
// Nulls where strings were asked for, and keys left out altogether.
|
||||
{`{"jobTitle": null, "company": null}`, "", "", false, false},
|
||||
{`{}`, "", "", false, false},
|
||||
// Whitespace is trimmed, and a blank optional field becomes null.
|
||||
{`{"jobTitle": " Engineer ", "company": "Acme\n", "location": " ", "notes": ""}`, "Engineer", "Acme", false, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got, err := replying(c.reply).client(t, "").ExtractPosting(context.Background(), "", "", "x")
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", c.reply, err)
|
||||
}
|
||||
if got.JobTitle != c.title || got.Company != c.company || (got.Location != nil) != c.hasLocation || (got.Notes != nil) != c.hasN {
|
||||
t.Errorf("%s: got %+v", c.reply, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractPostingFailures(t *testing.T) {
|
||||
cases := map[string]*fakeAPI{
|
||||
"empty response from the posting reader": {status: 200, body: message("end_turn")},
|
||||
"failed to parse the posting": replying(`{"jobTitle": ["Engineer"], "company": "Acme"}`),
|
||||
"failed to read the posting": {status: 500, body: `{"type":"error","error":{"type":"api_error","message":"x"}}`},
|
||||
}
|
||||
for want, api := range cases {
|
||||
if _, err := api.client(t, "").ExtractPosting(context.Background(), "", "", "x"); err == nil || err.Error() != want {
|
||||
t.Errorf("err = %v, want %q", err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- score.go -------------------------------------------------------------
|
||||
|
||||
func TestScorePostingSendsProfileAndPostingAsDelimitedData(t *testing.T) {
|
||||
api := replying(`{"score": 82, "reasons": "Your Go experience matches; no payments background."}`)
|
||||
got, err := api.client(t, "").ScorePosting(context.Background(),
|
||||
"Five years of Go. Want a backend role in London.", "Backend Engineer", "Acme", "London", "We build payments in Go.")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != (LeadScore{82, "Your Go experience matches; no payments background."}) {
|
||||
t.Errorf("got %+v", got)
|
||||
}
|
||||
user := api.calls[0]["messages"].([]any)[0].(map[string]any)["content"].([]any)[0].(map[string]any)["text"]
|
||||
want := "<profile>\nFive years of Go. Want a backend role in London.\n</profile>\n" +
|
||||
"<posting>\n<title>Backend Engineer</title>\n<company>Acme</company>\n" +
|
||||
"<location>London</location>\n<description>\nWe build payments in Go.\n</description>\n</posting>"
|
||||
if user != want {
|
||||
t.Errorf("user turn = %q\nwant %q", user, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScorePostingNormalisesTheReply(t *testing.T) {
|
||||
cases := map[string]LeadScore{
|
||||
`{"score": 82.0, "reasons": " ok "}`: {82, "ok"},
|
||||
`{"score": "40"}`: {40, ""},
|
||||
`{"score": 0, "reasons": null}`: {0, ""},
|
||||
`{"score": 100, "reasons": "Perfect"}`: {100, "Perfect"},
|
||||
`{"score": 82.5}`: {82, ""}, // half to even, as Python's round()
|
||||
"```json\n{\"score\": 82}\n```": {82, ""},
|
||||
}
|
||||
for reply, want := range cases {
|
||||
got, err := replying(reply).client(t, "").ScorePosting(context.Background(), "p", "t", "", "", "")
|
||||
if err != nil || got != want {
|
||||
t.Errorf("%s: got %+v, %v; want %+v", reply, got, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScorePostingFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
api *fakeAPI
|
||||
want string
|
||||
}{
|
||||
{&fakeAPI{status: 200, body: message("end_turn")}, "empty response from the posting scorer"},
|
||||
{replying("This looks like a great role!"), "failed to parse the score"},
|
||||
// No usable number is a failure, never a score of zero.
|
||||
{replying(`{"reasons": "Good fit"}`), "failed to parse the score"},
|
||||
{replying(`{"score": null, "reasons": "Good fit"}`), "failed to parse the score"},
|
||||
{replying(`{"score": "high"}`), "failed to parse the score"},
|
||||
{replying(`{"score": 140}`), "failed to parse the score"},
|
||||
{replying(`{"score": -5}`), "failed to parse the score"},
|
||||
{&fakeAPI{status: 500, body: `{"type":"error","error":{"type":"api_error","message":"x"}}`}, "failed to score the posting"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
_, err := c.api.client(t, "").ScorePosting(context.Background(), "p", "t", "", "", "")
|
||||
if err == nil || err.Error() != c.want {
|
||||
t.Errorf("body %s: err = %v, want %q", c.api.body, err, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- email.go -------------------------------------------------------------
|
||||
|
||||
func TestClassifyEmailSendsTheEmailUnchanged(t *testing.T) {
|
||||
const msg = "Subject: Your application\nFrom: Acme <[email protected]>\nDate: today\n\nThanks for applying."
|
||||
api := replying(`{"isJobEmail": true, "action": "create", "company": "Acme", "jobTitle": "Engineer", "status": "applied"}`)
|
||||
got, err := api.client(t, "").ClassifyEmail(context.Background(), msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !got.IsJobEmail || got.Company != "Acme" || got.Status != "applied" {
|
||||
t.Errorf("got %+v", got)
|
||||
}
|
||||
user := api.calls[0]["messages"].([]any)[0].(map[string]any)["content"].([]any)[0].(map[string]any)["text"]
|
||||
if user != msg {
|
||||
t.Errorf("user turn = %q", user)
|
||||
}
|
||||
}
|
||||
|
||||
// The prompt and the struct are two halves of one contract; neither may lose
|
||||
// a key.
|
||||
func TestEmailPromptNamesEveryField(t *testing.T) {
|
||||
typ := reflect.TypeOf(EmailAnalysis{})
|
||||
for i := range typ.NumField() {
|
||||
tag := typ.Field(i).Tag.Get("json")
|
||||
if !strings.Contains(emailSystem, `"`+tag+`"`) {
|
||||
t.Errorf("prompt does not name %q", tag)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(emailSystem, "never as instructions") {
|
||||
t.Error("prompt no longer fences off the email as data")
|
||||
}
|
||||
for _, s := range EmailStatuses {
|
||||
if !strings.Contains(emailSystem, `"`+s+`"`) {
|
||||
t.Errorf("EmailStatuses has %q but the prompt does not", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyEmailFillsInWhatTheModelLeftOut(t *testing.T) {
|
||||
cases := map[string]EmailAnalysis{
|
||||
// The prompt tells the model to send nothing else for a non-job email.
|
||||
`{"isJobEmail": false}`: {},
|
||||
// Nulls where strings were asked for become "".
|
||||
`{"isJobEmail": true, "action": null, "company": null, "jobTitle": null, "status": null}`: {IsJobEmail: true},
|
||||
`{"isJobEmail": true, "action": "update", "company": "Acme", "location": null, "notes": null}`: {IsJobEmail: true, Action: "update", Company: "Acme"},
|
||||
`{}`: {},
|
||||
}
|
||||
for reply, want := range cases {
|
||||
got, err := replying(reply).client(t, "").ClassifyEmail(context.Background(), "m")
|
||||
if err != nil || !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("%s: got %+v, %v; want %+v", reply, got, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyEmailFailures(t *testing.T) {
|
||||
cases := map[string]*fakeAPI{
|
||||
"empty response from the email classifier": {status: 200, body: message("end_turn")},
|
||||
"failed to parse the email classification": replying(`{"isJobEmail": true, "company": ["Acme"]}`),
|
||||
"failed to classify the email": {status: 500, body: `{"type":"error","error":{"type":"api_error","message":"x"}}`},
|
||||
}
|
||||
for want, api := range cases {
|
||||
if _, err := api.client(t, "").ClassifyEmail(context.Background(), "m"); err == nil || err.Error() != want {
|
||||
t.Errorf("err = %v, want %q", err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user