Skip to content

Commit e30e827

Browse files
Darshan M Uclaude
andcommitted
Probe the docs site's own origin for chat only when codewiki serve served it
The viewer always probed <its origin>/api/health first, which on GitHub Pages is a 404 logged in the browser console on every chat open. `codewiki serve` now marks the HTML it serves with <meta name="codewiki-serve">, and the viewer probes its own origin only when that mark is present. Older servers are still found through the 127.0.0.1 port list; older pages ignore the mark. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CXRqeijND7XPq2srGHndRd
1 parent 4b09125 commit e30e827

4 files changed

Lines changed: 56 additions & 3 deletions

File tree

‎codewiki/src/be/qa/server.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,20 @@
1616
import json
1717
import logging
1818
import os
19+
import re
1920
import socket
2021
import threading
2122
from collections.abc import Iterable
2223
from urllib.parse import urlparse
2324

2425
from fastapi import FastAPI, HTTPException, Request
25-
from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse
26+
from fastapi.responses import (
27+
FileResponse,
28+
HTMLResponse,
29+
JSONResponse,
30+
Response,
31+
StreamingResponse,
32+
)
2633
from pydantic import BaseModel, Field
2734

2835
from codewiki import __version__
@@ -34,6 +41,7 @@
3441

3542
# Never served: the dependency graph / caches under temp/ and dotfiles.
3643
_HIDDEN_PREFIXES = ("temp/", ".")
44+
SERVE_MARKER = '<meta name="codewiki-serve" content="1">'
3745

3846

3947
class AskRequest(BaseModel):
@@ -241,6 +249,19 @@ def static(path: str):
241249
full = os.path.realpath(os.path.join(docs_dir, rel))
242250
if not full.startswith(os.path.realpath(docs_dir) + os.sep) or not os.path.isfile(full):
243251
raise HTTPException(404)
252+
if full.endswith(".html"):
253+
# Tell the page it is served by `codewiki serve`, so its chat uses this origin.
254+
# Elsewhere (GitHub Pages) probing the own origin's /api/health only 404s.
255+
with open(full, encoding="utf-8") as f:
256+
html = f.read()
257+
html = re.sub(
258+
r"<head(?:\s[^>]*)?>",
259+
lambda m: m.group(0) + SERVE_MARKER,
260+
html,
261+
count=1,
262+
flags=re.I,
263+
)
264+
return HTMLResponse(html)
244265
return FileResponse(full)
245266

246267
return app

‎codewiki/templates/github_pages/viewer_template.html‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3493,8 +3493,9 @@ <h4>Generation Info</h4>
34933493

34943494
function chatCandidates() {
34953495
const out = [];
3496-
// Served by `codewiki serve` itself: same origin, no cross-site request.
3497-
if (location.protocol === 'http:' || location.protocol === 'https:') out.push(location.origin);
3496+
// Served by `codewiki serve` itself (it marks the page): same origin, no cross-site
3497+
// request. Elsewhere, e.g. GitHub Pages, /api/health on this origin is only a 404.
3498+
if (document.querySelector('meta[name="codewiki-serve"]')) out.push(location.origin);
34983499
(CHAT_CONFIG.endpoints || ['http://127.0.0.1:8765']).forEach(function(e) {
34993500
const base = String(e).replace(/\/+$/, '');
35003501
if (out.indexOf(base) === -1) out.push(base);

‎tests/test_qa_server.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,3 +302,20 @@ def test_missing_graph_is_rebuilt_from_the_repo(tmp_path):
302302
shutil.rmtree(docs_dir / "temp") # a fresh clone: docs/temp/ is git-ignored
303303
index = QAIndex(str(docs_dir))
304304
assert index.code, "code search is off without a graph"
305+
306+
307+
def test_serve_marks_the_pages_it_serves(tmp_path):
308+
"""The docs site probes its own origin's /api/health only when `codewiki serve` served it;
309+
on GitHub Pages that probe was always a 404 in the console."""
310+
_, docs_dir = build(tmp_path)
311+
(docs_dir / "index.html").write_text(
312+
"<html><head lang=en><title>t</title></head><body><header>x</header>"
313+
)
314+
c = TestClient(create_app(str(docs_dir), set()))
315+
html = c.get("/").text
316+
assert html.count('name="codewiki-serve"') == 1
317+
assert html.index('name="codewiki-serve"') < html.index(
318+
"<title>"
319+
) # inside <head>, not <header>
320+
page = c.get("/overview.md")
321+
assert "codewiki-serve" not in page.text and page.status_code == 200

‎tests/test_viewer_browser.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,3 +390,17 @@ def test_chat_says_when_the_browser_blocks_localhost(site, browser):
390390
ctx.close()
391391
finally:
392392
public.close()
393+
394+
395+
def test_a_site_not_served_by_codewiki_does_not_probe_its_own_origin(site, browser):
396+
ctx = browser.new_context()
397+
pg = ctx.new_page()
398+
probes = []
399+
pg.on("request", lambda r: probes.append(r.url) if r.url.endswith("/api/health") else None)
400+
pg.goto(site + "/")
401+
pg.wait_for_selector(".nav-item")
402+
pg.click("#chat-trigger")
403+
pg.wait_for_selector(".chat-offline")
404+
assert probes, "the configured localhost ports are still probed"
405+
assert not [u for u in probes if u.startswith(site + "/")] # no 404 on the site's own origin
406+
ctx.close()

0 commit comments

Comments
 (0)