Add repos from the page, answer actions in place, Expo-style redesign
Add repository: - New remote verb `add-repo KEY OWNER/NAME`. Off unless config.toml has [repo_add] (base_url + owners). Only listed owners; the dev box builds the URL itself, checks it with `git ls-remote` (bot access), then appends to [repos] under the lock. No URL crosses the SSH link. - `repos` also reports where adding is allowed, so the page shows the form only when it's on and rejects other hosts before calling SSH. - set_toml_string inserts after the section's last key, not after trailing blank lines / the next section's comments. Responsiveness: - web/static/app.js (progressive enhancement; every form still works without JS): forms go via fetch and get a JSON answer instead of POST-redirect-GET; buttons/cards show the change immediately; the list refreshes itself (15 s, 3 s while something is starting). - `repos` is cached for 5 min (refreshed on add-repo), so a page view is one SSH call instead of two. - `list` reads all unit states with one `systemctl show` instead of one per session: 676 -> 374 ms on the dev box with 21 sessions. - Static assets are content-hashed and cached immutably. Design: slate greys, hairline borders, black primary action, tinted status badges, monospace repo/branch, two columns on desktop, stacked on phones, light and dark. Docs: README security model, AGENTS.md (JS convention, add-repo invariant), config.example.toml. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MCUMXh8zZConC75Mptbeou
This commit is contained in:
parent
39997de1e8
commit
1b3172bd50
10 changed files with 1084 additions and 92 deletions
248
web/app.py
248
web/app.py
|
|
@ -24,6 +24,7 @@ from __future__ import annotations
|
|||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
|
|
@ -33,7 +34,10 @@ import signal
|
|||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
|
|
@ -164,100 +168,216 @@ def allowed_user(user: str, allowed: set[str]) -> bool:
|
|||
return bool(user) and (not allowed or user in allowed)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- repo input
|
||||
|
||||
|
||||
# What the "Add repository" box accepts: OWNER/NAME, or a clone URL of the
|
||||
# git host the dev box adds from (ssh://, https:// or scp-style git@host:).
|
||||
REPO_INPUT_RE = re.compile(
|
||||
r"(?:(?P<scheme>ssh|https?)://(?:[A-Za-z0-9._-]+@)?(?P<host>[A-Za-z0-9.-]+)(?::\d+)?/"
|
||||
r"|git@(?P<scp_host>[A-Za-z0-9.-]+):)?"
|
||||
r"(?P<owner>[A-Za-z0-9][A-Za-z0-9._-]{0,39})/(?P<repo>[A-Za-z0-9][A-Za-z0-9._-]{0,99}?)(?:\.git)?/?"
|
||||
)
|
||||
|
||||
|
||||
def parse_repo_input(text: str, base_url: str) -> tuple[str, str]:
|
||||
"""'ssh://git@host:14922/team/App.git' -> ('team', 'App'). Raises ValueError.
|
||||
|
||||
A URL must point at the same host as the dev box's base_url, because the
|
||||
dev box only ever builds URLs on that host: pasting a GitHub URL must fail
|
||||
loudly rather than silently add the same path from the git host.
|
||||
"""
|
||||
m = REPO_INPUT_RE.fullmatch(text.strip())
|
||||
if not m or ".." in m["repo"]:
|
||||
raise ValueError("enter OWNER/NAME or the repo's clone URL")
|
||||
host = m["host"] or m["scp_host"]
|
||||
if host and host.lower() != (urllib.parse.urlsplit(base_url).hostname or "").lower():
|
||||
raise ValueError(f"only repos on {urllib.parse.urlsplit(base_url).hostname} can be added")
|
||||
return m["owner"], m["repo"]
|
||||
|
||||
|
||||
def key_from_repo(repo: str) -> str:
|
||||
"""'My_App.v2' -> 'my-app-v2': the allowlist key the page offers by default."""
|
||||
return re.sub(r"[^a-z0-9]+", "-", repo.lower()).strip("-")[:32].rstrip("-")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- HTML
|
||||
|
||||
CSS = """
|
||||
:root{--bg:#f6f5f2;--fg:#1d1d1b;--muted:#6b6a65;--card:#fff;--line:#e3e1db;--accent:#b4532a;--ok:#2f7d4f;--warn:#a06a00;--bad:#b3261e}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#161615;--fg:#ecebe6;--muted:#9c9a93;--card:#1f1f1d;--line:#34332f;--accent:#e08a5c;--ok:#6cc08f;--warn:#e0b050;--bad:#f08a80}}
|
||||
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.45 system-ui,-apple-system,sans-serif}
|
||||
main{max-width:720px;margin:0 auto;padding:20px 16px 48px}
|
||||
header{display:flex;justify-content:space-between;align-items:baseline;gap:12px;margin-bottom:16px}
|
||||
h1{font-size:1.3rem;margin:0}h2{font-size:1rem;margin:28px 0 10px;color:var(--muted);font-weight:600;text-transform:uppercase;letter-spacing:.04em}
|
||||
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:14px 16px;margin-bottom:10px}
|
||||
.row{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}
|
||||
.name{font-weight:600;font-size:1.05rem}.meta{color:var(--muted);font-size:.88rem}
|
||||
.pill{font-size:.78rem;padding:2px 8px;border-radius:99px;border:1px solid currentColor}
|
||||
.active{color:var(--ok)}.activating,.deactivating{color:var(--warn)}.inactive,.failed,.unknown{color:var(--bad)}
|
||||
.actions{display:flex;gap:8px;margin-top:10px;flex-wrap:wrap}
|
||||
button,.btn{font:inherit;padding:8px 14px;border-radius:8px;border:1px solid var(--line);background:var(--card);color:var(--fg);cursor:pointer;text-decoration:none;display:inline-block}
|
||||
.primary{background:var(--accent);border-color:var(--accent);color:#fff}
|
||||
form.inline{display:inline}label{display:block;font-size:.88rem;color:var(--muted);margin:10px 0 4px}
|
||||
input,select{font:inherit;width:100%;padding:9px 10px;border-radius:8px;border:1px solid var(--line);background:var(--bg);color:var(--fg)}
|
||||
.flash{padding:10px 14px;border-radius:8px;margin-bottom:14px;border:1px solid}.flash.err{color:var(--bad)}.flash.ok{color:var(--ok)}
|
||||
.warn{color:var(--warn);font-size:.9rem;margin-top:6px}a{color:var(--accent)}
|
||||
details>summary{cursor:pointer;list-style:none}details>summary::-webkit-details-marker{display:none}
|
||||
details>summary h2::before{content:"▸ "}details[open]>summary h2::before{content:"▾ "}
|
||||
.card.archived{opacity:.75}
|
||||
"""
|
||||
STATIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
|
||||
|
||||
|
||||
def _static(name: str) -> bytes:
|
||||
with open(os.path.join(STATIC, name), "rb") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
ASSETS = {"/app.css": (_static("app.css"), "text/css; charset=utf-8"),
|
||||
"/app.js": (_static("app.js"), "text/javascript; charset=utf-8")}
|
||||
# Asset URLs carry a content hash, so they can be cached forever and a deploy
|
||||
# still takes effect on the next page load.
|
||||
ASSET_VERSION = hashlib.sha256(b"".join(b for b, _ in ASSETS.values())).hexdigest()[:10]
|
||||
|
||||
STATE_LABEL = {"active": "Running", "activating": "Starting", "deactivating": "Stopping",
|
||||
"reloading": "Reloading", "inactive": "Stopped", "failed": "Failed"}
|
||||
|
||||
MARK = ('<svg class="mark" viewBox="0 0 24 24" aria-hidden="true"><rect width="24" height="24" rx="6"/>'
|
||||
'<path d="M7 8l4 4-4 4M13 16h4" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>')
|
||||
|
||||
|
||||
def page(title: str, body: str) -> bytes:
|
||||
return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>{html.escape(title)}</title><link rel="stylesheet" href="/app.css"></head>
|
||||
<body><main>{body}</main></body></html>""".encode()
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>{html.escape(title)}</title><link rel="stylesheet" href="/app.css?v={ASSET_VERSION}">
|
||||
<script src="/app.js?v={ASSET_VERSION}" defer></script></head>
|
||||
<body>{body}</body></html>""".encode()
|
||||
|
||||
|
||||
def e(v) -> str:
|
||||
return html.escape(str(v if v is not None else ""))
|
||||
|
||||
|
||||
def action(verb: str, name: str) -> str:
|
||||
def action(verb: str, name: str, cls: str = "") -> str:
|
||||
return (f'<form method="post" action="/{verb}" class="inline">'
|
||||
f'<input type="hidden" name="name" value="{e(name)}"><button>{verb.title()}</button></form>')
|
||||
f'<input type="hidden" name="name" value="{e(name)}">'
|
||||
f'<button class="btn {cls}">{verb.title()}</button></form>')
|
||||
|
||||
|
||||
def badge(state: str) -> str:
|
||||
return f'<span class="badge {e(state)}"><i></i>{e(STATE_LABEL.get(state, state.title()))}</span>'
|
||||
|
||||
|
||||
def session_card(s: dict, actions: str, cls: str = "") -> str:
|
||||
warn = f'<div class="warn">⚠ {e(s["needs_attention"])}</div>' if s.get("needs_attention") else ""
|
||||
warn = f'<div class="warn">{e(s["needs_attention"])}</div>' if s.get("needs_attention") else ""
|
||||
restarts = f' · restarted {e(s["restarts"])}×' if s.get("restarts") else ""
|
||||
return f"""<div class="card {cls}"><div class="row"><span class="name">{e(s.get("title") or s["name"])}</span>
|
||||
<span class="pill {e(s["state"])}">{e(s["state"])}</span></div>
|
||||
<div class="meta">{e(s["repo"])} · {e(s["branch"])} · since {e(s["created_at"][:16].replace("T", " "))}{restarts}</div>{warn}
|
||||
<div class="actions">{actions}</div></div>"""
|
||||
linked = " data-linked" if s.get("remote_control_url") else ""
|
||||
created = e(s["created_at"])
|
||||
return f"""<article class="card {cls}" data-name="{e(s["name"])}" data-state="{e(s["state"])}"{linked}>
|
||||
<div class="card-top"><h3 class="title">{e(s.get("title") or s["name"])}</h3>{badge(s["state"])}</div>
|
||||
<div class="meta"><span class="mono">{e(s["repo"])}</span><span class="dim">/</span><span class="mono">{e(s["branch"])}</span></div>
|
||||
<div class="meta dim">Created <time datetime="{created}">{e(s["created_at"][:16].replace("T", " "))}</time>{restarts}</div>{warn}
|
||||
<div class="actions">{actions}</div></article>"""
|
||||
|
||||
|
||||
def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes:
|
||||
parts = [f'<header><h1>Sessions</h1><span class="meta">{e(user)}</span></header>']
|
||||
if flash:
|
||||
parts.append(f'<div class="flash {e(flash[0])}">{e(flash[1])}</div>')
|
||||
def live_section(listing: dict) -> str:
|
||||
"""The part of the page that changes on its own; app.js re-fetches and swaps it."""
|
||||
parts = []
|
||||
if not listing.get("ok"):
|
||||
parts.append(f'<div class="flash err">{e(listing.get("error", "dev box error"))}</div>')
|
||||
parts.append(f'<div class="callout err">{e(listing.get("error", "dev box error"))}</div>')
|
||||
sessions = [s for s in listing.get("sessions", []) if not s.get("archived")]
|
||||
archived = [s for s in listing.get("sessions", []) if s.get("archived")]
|
||||
running = sum(1 for s in sessions if s["state"] == "active")
|
||||
parts.append(f'<h2>Running {running} of {e(listing.get("max_running", "?"))}</h2>')
|
||||
if not sessions and listing.get("ok"):
|
||||
parts.append('<p class="meta">No sessions yet.</p>')
|
||||
parts.append(f'<div class="section-head"><h2>Active</h2>'
|
||||
f'<span class="counter">{running} of {e(listing.get("max_running", "?"))} running</span></div>')
|
||||
cards = []
|
||||
for s in sessions:
|
||||
link = (f'<a class="btn primary" href="{e(s["remote_control_url"])}" rel="noopener">Open in Claude</a>'
|
||||
if s.get("remote_control_url") and s["state"] == "active" else "")
|
||||
verb = "stop" if s["enabled"] else "start"
|
||||
parts.append(session_card(s, link + action(verb, s["name"]) + action("archive", s["name"])))
|
||||
cards.append(session_card(s, link + action(verb, s["name"], "secondary")
|
||||
+ action("archive", s["name"], "ghost")))
|
||||
if not sessions and listing.get("ok"):
|
||||
cards.append('<div class="empty"><strong>No sessions yet</strong>'
|
||||
'<span>Create one and it shows up here and in the Claude app.</span></div>')
|
||||
parts.append(f'<div class="list">{"".join(cards)}</div>')
|
||||
if archived:
|
||||
cards = "".join(session_card(s, action("unarchive", s["name"]), "archived") for s in archived)
|
||||
parts.append(f'<details><summary><h2>Archived ({len(archived)})</h2></summary>{cards}</details>')
|
||||
old = "".join(session_card(s, action("unarchive", s["name"], "secondary"), "archived") for s in archived)
|
||||
parts.append(f'<details class="archive"><summary>Archived <span class="count">{len(archived)}</span></summary>'
|
||||
f'<div class="list">{old}</div></details>')
|
||||
return f'<div id="live">{"".join(parts)}</div>'
|
||||
|
||||
|
||||
def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes:
|
||||
toast = f'<div class="toast {e(flash[0])}" role="status">{e(flash[1])}</div>' if flash else ""
|
||||
options = "".join(f'<option value="{e(r)}">{e(r)}</option>' for r in repos.get("repos", []))
|
||||
parts.append(f"""<h2>New session</h2><form method="post" action="/create" class="card">
|
||||
add = repos.get("add")
|
||||
add_form = ""
|
||||
if add:
|
||||
host = urllib.parse.urlsplit(add["base_url"]).hostname or ""
|
||||
owners = ", ".join(e(o) for o in add["owners"])
|
||||
add_form = f"""<details class="panel" id="add-panel"><summary><h2>Add repository</h2></summary>
|
||||
<form method="post" action="/add-repo" id="add-repo">
|
||||
<label for="repo-url">Clone URL or owner/name</label>
|
||||
<input id="repo-url" name="url" required maxlength="200" placeholder="{e(add["owners"][0])}/my-app" autocapitalize="none" autocomplete="off" spellcheck="false">
|
||||
<label for="repo-key">Short name <span class="opt">optional</span></label>
|
||||
<input id="repo-key" name="key" maxlength="32" pattern="[a-z0-9][a-z0-9\\-]{{0,31}}" placeholder="from the repo name" autocapitalize="none" autocomplete="off" spellcheck="false">
|
||||
<p class="hint">Repos on {e(host)} owned by {owners}. The bot account must already have access. Sessions run with no permission prompts, so add only repos you trust.</p>
|
||||
<div class="actions"><button class="btn secondary">Add repository</button></div></form></details>"""
|
||||
|
||||
body = f"""<header class="top"><div class="wrap top-inner">
|
||||
<a class="brand" href="/">{MARK}<span>Sessions</span></a><span class="user">{e(user)}</span></div></header>
|
||||
<div id="toasts" aria-live="polite">{toast}</div>
|
||||
<main class="wrap grid">
|
||||
<section class="col-main">
|
||||
<div class="intro"><h1>Sessions</h1><p>Claude Code on the dev box, with Remote Control.</p></div>
|
||||
{live_section(listing)}
|
||||
</section>
|
||||
<aside class="col-side">
|
||||
<form method="post" action="/create" class="panel" id="create">
|
||||
<h2>New session</h2>
|
||||
<label for="name">Name</label><input id="name" name="name" required maxlength="48" pattern="[A-Za-z0-9][A-Za-z0-9 \\-]{{0,47}}" placeholder="Fix login bug" autocomplete="off">
|
||||
<label for="repo">Repository</label><select id="repo" name="repo" required>{options}</select>
|
||||
<label for="base">Start from branch (optional)</label><input id="base" name="base" placeholder="default branch" autocapitalize="none" autocomplete="off">
|
||||
<div class="actions"><button class="primary">Create</button><a class="btn" href="/">Refresh</a></div></form>
|
||||
<p class="meta">A session runs Claude Code on the dev box with Remote Control on. Give it instructions from the Claude app or the “Open in Claude” link — never from this page.</p>""")
|
||||
return page("Sessions", "".join(parts))
|
||||
<label for="base">Start from branch <span class="opt">optional</span></label><input id="base" name="base" placeholder="default branch" autocapitalize="none" autocomplete="off" spellcheck="false">
|
||||
<div class="actions"><button class="btn primary wide">Create session</button><a class="btn ghost" href="/" data-refresh>Refresh</a></div>
|
||||
</form>
|
||||
{add_form}
|
||||
<p class="note">Give a session instructions from the Claude app or the “Open in Claude” link — never from this page.</p>
|
||||
</aside>
|
||||
</main>"""
|
||||
return page("Sessions", body)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- server
|
||||
|
||||
# Buttons that take just a session name, and what the page says afterwards.
|
||||
DONE = {"/start": "started", "/stop": "stopped", "/archive": "stopped and archived", "/unarchive": "unarchived"}
|
||||
DONE = {"/start": "Started", "/stop": "Stopped", "/archive": "Archived", "/unarchive": "Restored"}
|
||||
|
||||
|
||||
class App:
|
||||
REPOS_TTL = 300 # the allowlist rarely changes; add-repo refreshes it at once
|
||||
|
||||
def __init__(self, env: dict, dev: DevBox):
|
||||
self.dev = dev
|
||||
self.auth_header = env.get("SESSIONS_AUTH_HEADER", "Remote-User")
|
||||
self.allowed_users = {u.strip() for u in env.get("SESSIONS_ALLOWED_USERS", "").split(",") if u.strip()}
|
||||
self._repos: dict | None = None
|
||||
self._repos_at = 0.0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def repos(self) -> dict:
|
||||
"""The `repos` answer, cached so a page view costs one SSH call, not two."""
|
||||
with self._lock:
|
||||
if self._repos and time.monotonic() - self._repos_at < self.REPOS_TTL:
|
||||
return self._repos
|
||||
r = self.dev.call("repos")
|
||||
if r.get("ok"):
|
||||
self.set_repos(r)
|
||||
return r
|
||||
|
||||
def set_repos(self, r: dict) -> None:
|
||||
with self._lock:
|
||||
self._repos, self._repos_at = r, time.monotonic()
|
||||
|
||||
def page_data(self) -> tuple[dict, dict]:
|
||||
"""`list` and (on a cache miss) `repos`, side by side over the shared connection."""
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
repos = pool.submit(self.repos)
|
||||
listing = self.dev.call("list")
|
||||
return listing, (repos.result() if listing.get("ok") else {})
|
||||
|
||||
def add_repo(self, f: dict) -> tuple[dict, str]:
|
||||
add = self.repos().get("add")
|
||||
if not add:
|
||||
return {"ok": False, "error": "adding repos is turned off on the dev box ([repo_add] in config.toml)"}, ""
|
||||
try:
|
||||
owner, repo = parse_repo_input(f.get("url", ""), add["base_url"])
|
||||
except ValueError as err:
|
||||
return {"ok": False, "error": str(err)}, ""
|
||||
key = f.get("key", "").strip() or key_from_repo(repo)
|
||||
r = self.dev.call("add-repo", key, f"{owner}/{repo}", timeout=60)
|
||||
if r.get("ok"):
|
||||
self.set_repos({"ok": True, "repos": r["repos"], "add": add})
|
||||
return r, f"Added {key} — it's now in the Repository list"
|
||||
|
||||
|
||||
def make_handler(app: App):
|
||||
|
|
@ -271,12 +391,15 @@ def make_handler(app: App):
|
|||
def log_message(self, fmt, *args):
|
||||
sys.stderr.write(f"{self.user() or '-'} {fmt % args}\n")
|
||||
|
||||
def send(self, status: int, body: bytes = b"", ctype: str = "text/html; charset=utf-8", headers: dict | None = None):
|
||||
def send(self, status: int, body: bytes = b"", ctype: str = "text/html; charset=utf-8",
|
||||
headers: dict | None = None, cache: str = "no-store"):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Security-Policy", "default-src 'none'; style-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'")
|
||||
self.send_header("Cache-Control", cache)
|
||||
self.send_header("Content-Security-Policy",
|
||||
"default-src 'none'; style-src 'self'; script-src 'self'; connect-src 'self'; "
|
||||
"form-action 'self'; frame-ancestors 'none'; base-uri 'none'")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
for k, v in (headers or {}).items():
|
||||
|
|
@ -312,8 +435,9 @@ def make_handler(app: App):
|
|||
return self.send(200, b"ok\n", "text/plain")
|
||||
if self.refuse_unauthenticated():
|
||||
return
|
||||
if path == "/app.css":
|
||||
return self.send(200, CSS.encode(), "text/css")
|
||||
if path in ASSETS:
|
||||
body, ctype = ASSETS[path]
|
||||
return self.send(200, body, ctype, cache="private, max-age=31536000, immutable")
|
||||
if path != "/":
|
||||
return self.send(404, b"not found\n", "text/plain")
|
||||
flash = None
|
||||
|
|
@ -322,8 +446,7 @@ def make_handler(app: App):
|
|||
flash = ("ok", q["ok"][0][:200])
|
||||
elif "err" in q:
|
||||
flash = ("err", q["err"][0][:300])
|
||||
listing = app.dev.call("list")
|
||||
repos = app.dev.call("repos") if listing.get("ok") else {}
|
||||
listing, repos = app.page_data()
|
||||
self.send(200, dashboard(listing, repos, self.user(), flash))
|
||||
|
||||
def do_POST(self):
|
||||
|
|
@ -338,13 +461,22 @@ def make_handler(app: App):
|
|||
if f.get("base", "").strip():
|
||||
args.append(f["base"].strip())
|
||||
r = app.dev.call("create", *args, timeout=330)
|
||||
done = f"created {args[0]} — it will appear in the Claude app in a few seconds"
|
||||
done = f"Created {args[0]} — it appears in the Claude app in a few seconds"
|
||||
elif path == "/add-repo":
|
||||
r, done = app.add_repo(f)
|
||||
elif path in DONE:
|
||||
r = app.dev.call(path[1:], f.get("name", ""))
|
||||
done = f"{DONE[path]} {f.get('name', '')}"
|
||||
else:
|
||||
return self.send(404, b"not found\n", "text/plain")
|
||||
self.log_message("%s %s -> %s", path, f.get("name", ""), "ok" if r.get("ok") else r.get("error"))
|
||||
self.log_message("%s %s -> %s", path, f.get("name", "") or f.get("url", ""),
|
||||
"ok" if r.get("ok") else r.get("error"))
|
||||
if "application/json" in self.headers.get("Accept", ""):
|
||||
# app.js: answer in place; the page updates without a reload.
|
||||
out = {"ok": True, "message": done} if r.get("ok") else {"ok": False, "error": r.get("error", "failed")}
|
||||
if r.get("ok") and "repos" in r:
|
||||
out["repos"] = r["repos"]
|
||||
return self.send(200, json.dumps(out).encode(), "application/json")
|
||||
key, msg = ("ok", done) if r.get("ok") else ("err", r.get("error", "failed"))
|
||||
self.send(HTTPStatus.SEE_OTHER, headers={"Location": "/?" + urllib.parse.urlencode({key: msg})})
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue