Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ui): a feature request files as a real issue, right beside a bug
Haraldbe77892650c8
diff --git a/jarvis/ui/web/feedback_routes.py b/jarvis/ui/web/feedback_routes.pyindex cba18b4026..38785e1774 100644--- a/jarvis/ui/web/feedback_routes.py+++ b/jarvis/ui/web/feedback_routes.py@@ -1,18 +1,34 @@-"""REST API for the in-app feedback / bug-report form.+"""REST API for the in-app feedback section — bug reports AND feature requests.Endpoints:GET /api/feedback/status → {"configured": bool, "github_url": str,- "context": {...}}+ "templates": {...}, "context": {...}}+ GET /api/feedback/board → {"available": bool, "ideas": [...],+ "bugs": [...], "detail": str}POST /api/feedback → {"ok": bool, "status": str, "detail": str,"github_url": str | None}-``GET /status`` is the capability probe: the frontend calls it before the user-types anything, so the form can honestly present the path this install really-has — direct dispatch when the operator webhook exists, or a prefilled GitHub-issue otherwise. ``context`` carries the same system fields the POST route-would attach server-side, so the GitHub fallback can include them in the-issue body.+GitHub is the PRIMARY channel for both report kinds, not a fallback: the+repository already carries the two issue forms this section drives+(``.github/ISSUE_TEMPLATE/bug_report.yml`` and ``feature_request.yml``), and+they are what puts the ``bug`` / ``enhancement`` label and the title prefix on+a report. ``GET /status`` therefore hands the frontend the template FILENAMES+(:data:`ISSUE_TEMPLATES`) rather than letting it hardcode them — an issue+opened without ``?template=`` lands as a blank, unlabelled issue that the+maintainer has to sort by hand.++``GET /status`` is also the capability probe. ``configured`` reports whether+this install additionally has the operator's direct dispatch channel (see+below); it is False on every fresh download. ``context`` carries the system+fields the POST route would attach server-side, so a GitHub issue is not a+second-class report — including ``os_choice``, which is pre-matched to the+bug form's operating-system dropdown so the value is accepted verbatim.++``GET /board`` reads the project's OPEN issues from the public GitHub API so+the section can show what other people already asked for. That read needs no+token and no login — the point being that someone who has not signed in still+sees their wish is already tracked, instead of filing a duplicate.The POST endpoint validates the payload, enriches it with system context (appversion, OS, Python, UTC timestamp), and forwards it to a Discord webhook as@@ -40,13 +56,16 @@ report the bug."""from __future__ import annotations+import asyncioimport base64import datetimeimport functoolsimport json as _jsonimport logging+import osimport platformimport re+import timefrom pathlib import Pathfrom typing import Literal@@ -54,7 +73,7 @@ import httpxfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field-from jarvis.core.branding import OFFICIAL_REPO_URL+from jarvis.core.branding import OFFICIAL_REPO_SLUG, OFFICIAL_REPO_URLfrom jarvis.core.config import get_secretlog = logging.getLogger(__name__)@@ -77,11 +96,44 @@ _SCREENSHOT_DECODED_MAX_BYTES = 8 * 1024 * 1024_SECRET_KEY = "discord_feedback_webhook_url" # noqa: S105 — key NAME, not a value_ENV_KEY = "DISCORD_FEEDBACK_WEBHOOK_URL"-# Public fallback for every downloader when the operator-only Discord webhook-# is not configured (the default — that credential belongs to the project-# maintainer, not to the end user running this install).+# The public issues page — the primary destination for both report kinds, and+# the honest answer when the operator-only Discord webhook is absent (the+# default: that credential belongs to the project maintainer, not to the end+# user running this install)._GITHUB_ISSUES_URL = f"{OFFICIAL_REPO_URL}/issues"+#: Report type → issue-form filename under ``.github/ISSUE_TEMPLATE/``.+#: Handed to the frontend so a prefilled issue opens the RIGHT form, which is+#: what applies the ``bug`` / ``enhancement`` label and the title prefix.+#: ``question`` has no form on purpose — questions belong in Discord or+#: Discussions (see ``.github/ISSUE_TEMPLATE/config.yml``), not in the tracker.+ISSUE_TEMPLATES: dict[str, str | None] = {+ "bug": "bug_report.yml",+ "idea": "feature_request.yml",+ "question": None,+}++#: Labels the two issue forms apply, mirrored here so the board can query them.+_LABEL_IDEA = "enhancement"+_LABEL_BUG = "bug"++# --- Board (public issue read) ----------------------------------------------++_GITHUB_API_ISSUES = f"https://api.github.com/repos/{OFFICIAL_REPO_SLUG}/issues"++#: Unauthenticated GitHub API allows 60 requests per hour per IP. One board+#: refresh costs two (one per label), so a 15-minute cache keeps a whole day of+#: normal use inside a fraction of that budget even with several app windows.+_BOARD_CACHE_TTL_SECONDS = 15 * 60++#: Rows per list. A feedback section shows what is popular, not the full+#: tracker — the "see all on GitHub" link covers the rest.+_BOARD_LIMIT = 8++#: The board must never delay the view. A slow GitHub answers with an empty+#: board and a reason, not with a spinner that outlives the user's patience.+_BOARD_TIMEOUT = httpx.Timeout(connect=4.0, read=8.0, write=4.0, pool=4.0)+# ----------------------------------------------------------------------# Request / response models@@ -111,21 +163,65 @@ class FeedbackContext(BaseModel):app_version: stros: strpython: str+ # The same OS, collapsed onto one of the bug form's dropdown options. A+ # GitHub issue form rejects a dropdown prefill that is not an exact option+ # string, so the free-form ``os`` above cannot serve that field.+ os_choice: strclass FeedbackChannelStatus(BaseModel):"""Capability probe result for the feedback form (GET /status)."""# True when this install can dispatch feedback directly (operator webhook- # present). False on every fresh download — the frontend then offers a- # prefilled GitHub issue instead of a submit that would dead-end.+ # present). False on every fresh download — the frontend then opens the+ # report as a prefilled GitHub issue, which is the normal path, not a+ # degraded one.configured: bool# Public issues page of the project — always present so the frontend never# has to hardcode it.github_url: str+ # Report type → issue-form filename (see ISSUE_TEMPLATES). A type mapped to+ # None has no form and must not open the tracker.+ templates: dict[str, str | None]context: FeedbackContext+class BoardEntry(BaseModel):+ """One open issue as the board renders it."""++ number: int+ title: str+ url: str+ # 👍 reactions — the closest thing the tracker has to a vote count, and the+ # reason the idea list is worth showing at all.+ upvotes: int+ comments: int+++class FeedbackBoard(BaseModel):+ """Open issues grouped by kind (GET /board).++ ``available`` is False whenever the lists could not be refreshed AND no+ cached copy exists — the frontend then hides the board instead of showing+ an empty one that reads as "nobody ever asked for anything".+ """++ available: bool+ ideas: list[BoardEntry]+ bugs: list[BoardEntry]+ # Why the board is unavailable, for the log and a muted UI line. Empty on+ # success. Never carries a GitHub error body verbatim.+ detail: str = ""+++# Process-wide board cache. Several desktop windows share one backend, so+# without the lock each open window would spend its own pair of requests from+# the same 60/hour IP budget on the identical refresh.+_board_cache: FeedbackBoard | None = None+_board_cache_at: float = 0.0+_board_lock = asyncio.Lock()++# ----------------------------------------------------------------------# Version helper# ----------------------------------------------------------------------@@ -164,12 +260,38 @@ def _app_version() -> str:return "unknown"+def _os_choice() -> str:+ """Collapse this machine onto one of the bug form's dropdown options.++ The option strings are fixed by ``.github/ISSUE_TEMPLATE/bug_report.yml``;+ GitHub drops a dropdown prefill that does not match one exactly, so this+ must stay in step with that file.++ A Linux box with no display server is reported as the headless option+ rather than plain "Linux": that distinction is the first thing a triage+ question asks, and the box itself knows the answer better than the user.+ """+ system = platform.system()+ if system == "Windows":+ return "Windows"+ if system == "Darwin":+ return "macOS"+ if system == "Linux":+ if os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"):+ return "Linux"+ return "Headless server / VPS"+ # Anything else (BSD, unknown) — "Linux" is the closest option on offer and+ # a wrong dropdown is better than a dropped prefill.+ return "Linux"++def _system_context() -> FeedbackContext:"""Gather the system fields attached to every dispatched report."""return FeedbackContext(app_version=_app_version(),os=platform.platform(),python=platform.python_version(),+ os_choice=_os_choice(),)@@ -180,23 +302,146 @@ def _system_context() -> FeedbackContext:@router.get("/status")async def feedback_status() -> FeedbackChannelStatus:- """Report whether this install can dispatch feedback directly.-- The frontend probes this before rendering the form so it can offer the- honest path up front: direct dispatch when the operator webhook is- configured, or a prefilled GitHub issue otherwise. ``context`` carries- the system fields (app version, OS, Python) so the GitHub fallback can- embed them in the issue body — the same enrichment the POST route- performs server-side.+ """Describe the paths this install has for filing a report.++ The frontend probes this before rendering the form. ``templates`` drives+ the primary path — a prefilled GitHub issue on the right issue form, which+ is what gives the report its label, its title prefix and its structure.+ ``configured`` reports the additional operator-only direct channel; it is+ False on every fresh download, and that is a normal state, not a fault.++ ``context`` carries the system fields (app version, OS, Python, plus the+ dropdown-ready ``os_choice``) so a GitHub issue receives the same+ enrichment the POST route performs server-side."""webhook_url = get_secret(_SECRET_KEY, env_fallback=_ENV_KEY)return FeedbackChannelStatus(configured=bool(webhook_url),github_url=_GITHUB_ISSUES_URL,+ templates=dict(ISSUE_TEMPLATES),context=_system_context(),)+def _entries_from_issues(raw: object) -> list[BoardEntry]:+ """Map a GitHub issues payload onto board rows, most-upvoted first.++ Pull requests are filtered out: ``/issues`` returns them too, and a PR is+ not something a user asked for.+ """+ if not isinstance(raw, list):+ return []+ entries: list[BoardEntry] = []+ for item in raw:+ if not isinstance(item, dict) or "pull_request" in item:+ continue+ number = item.get("number")+ title = item.get("title")+ url = item.get("html_url")+ if not isinstance(number, int) or not isinstance(title, str):+ continue+ if not isinstance(url, str):+ continue+ reactions = item.get("reactions")+ upvotes = 0+ if isinstance(reactions, dict) and isinstance(reactions.get("+1"), int):+ upvotes = reactions["+1"]+ comments = item.get("comments")+ entries.append(+ BoardEntry(+ number=number,+ title=title,+ url=url,+ upvotes=upvotes,+ comments=comments if isinstance(comments, int) else 0,+ )+ )+ entries.sort(key=lambda e: (e.upvotes, e.comments), reverse=True)+ return entries[:_BOARD_LIMIT]+++async def _fetch_label(client: httpx.AsyncClient, label: str) -> list[BoardEntry]:+ """Fetch one label's open issues. Raises on transport / HTTP failure."""+ resp = await client.get(+ _GITHUB_API_ISSUES,+ params={+ "state": "open",+ "labels": label,+ # Fetched wide and ranked locally: the issues API cannot sort by+ # reactions (only the search API can, at a far tighter rate limit),+ # and one page covers this tracker comfortably.+ "per_page": 50,+ "sort": "updated",+ "direction": "desc",+ },+ headers={+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ # GitHub rejects an API request without a User-Agent.+ "User-Agent": f"PersonalJarvis/{_app_version()}",+ },+ )+ resp.raise_for_status()+ return _entries_from_issues(resp.json())++[email protected]("/board")+async def feedback_board() -> FeedbackBoard:+ """List the project's open feature requests and bugs.++ Public, unauthenticated read — no token, no GitHub login, so it works for+ everyone including someone who has no account at all. That is the point:+ seeing an idea already tracked prevents the duplicate that the same person+ would otherwise file.++ Cached for 15 minutes process-wide. On a failed refresh the last good+ lists are served instead of an empty board, because a rate limit or a+ network blip is no reason to tell the user nobody ever asked for anything.+ """+ global _board_cache, _board_cache_at++ async with _board_lock:+ now = time.monotonic()+ if _board_cache is not None and now - _board_cache_at < _BOARD_CACHE_TTL_SECONDS:+ return _board_cache++ try:+ async with httpx.AsyncClient(timeout=_BOARD_TIMEOUT) as client:+ ideas = await _fetch_label(client, _LABEL_IDEA)+ bugs = await _fetch_label(client, _LABEL_BUG)+ except httpx.HTTPStatusError as exc:+ # 403 here is virtually always the unauthenticated rate limit.+ reason = (+ "rate_limited"+ if exc.response.status_code in (403, 429)+ else f"http_{exc.response.status_code}"+ )+ log.info("feedback: board refresh failed (%s)", reason)+ return _stale_or_empty(reason)+ except httpx.HTTPError as exc:+ log.info("feedback: board unreachable — %s", type(exc).__name__)+ return _stale_or_empty("unreachable")+ except ValueError as exc: # malformed JSON body+ log.warning("feedback: board payload was not valid JSON — %s", exc)+ return _stale_or_empty("bad_payload")++ _board_cache = FeedbackBoard(available=True, ideas=ideas, bugs=bugs)+ _board_cache_at = now+ return _board_cache+++def _stale_or_empty(reason: str) -> FeedbackBoard:+ """Serve the last good board after a failed refresh, else an empty one.++ Called with ``_board_lock`` held. The cache timestamp is deliberately NOT+ advanced: the next request retries rather than sitting on stale data for a+ full TTL after a one-off blip.+ """+ if _board_cache is not None:+ return _board_cache+ return FeedbackBoard(available=False, ideas=[], bugs=[], detail=reason)++@router.post("")async def submit_feedback(body: FeedbackPayload) -> FeedbackResult:"""Submit user feedback or a bug report to the configured Discord webhook.diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 6c43d944e2..17d0054cd9 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -3188,33 +3188,45 @@"subtitle": "Telegram-Bot + lokaler Friend-Registry. Du entscheidest, was Friends sehen."},"feedback": {- "discord_cta_title": "Auf unserem Discord melden",- "discord_cta_subtitle": "Öffne #report-a-bug und poste deinen Fehler, deine Idee oder Frage direkt.",- "discord_cta_button": "#report-a-bug öffnen",- "discord_join_button": "Zuerst Discord beitreten",- "or_send_here": "oder hier direkt senden",- "github_hint": "Diese Installation hat keinen direkten Feedback-Kanal — der Button öffnet deinen Bericht als vorausgefülltes GitHub-Issue im Browser.",- "github_submit": "Vorausgefülltes GitHub-Issue öffnen",- "subtitle": "Öffne unseren Discord, um Fehler zu melden, Ideen zu teilen oder Fragen zu stellen.",- "type_label": "Typ",- "type_bug": "Bug",- "type_idea": "Idee",+ "subtitle": "Melde einen Fehler oder schlag ein Feature vor — beides landet direkt auf GitHub.",+ "type_label": "Worum geht es?",+ "type_bug": "Fehler",+ "type_idea": "Feature","type_question": "Frage","title_label": "Titel",- "title_placeholder": "Kurze Zusammenfassung deines Feedbacks",- "description_label": "Beschreibung",- "description_placeholder": "Beschreib es genauer — Schritte zur Reproduktion, Kontext, Erwartetes vs. Tatsächliches Verhalten…",+ "title_placeholder": "Eine Zeile, in einfachen Worten",+ "bug_what_label": "Was ist passiert?",+ "bug_what_placeholder": "Beschreib den Fehler und was du stattdessen erwartet hast.",+ "bug_steps_label": "Schritte zum Nachstellen",+ "bug_steps_placeholder": "1. …\n2. …\n3. Der Fehler erscheint",+ "idea_problem_label": "Welches Problem löst das?",+ "idea_problem_placeholder": "Was möchtest du tun, das heute nicht geht?",+ "idea_solution_label": "Wie sollte es funktionieren?",+ "idea_solution_placeholder": "Ein Sprachbefehl, eine Einstellung, eine neue Ansicht?",+ "github_submit_bug": "Fehler auf GitHub melden",+ "github_submit_idea": "Feature auf GitHub vorschlagen",+ "send_without_github": "Ohne GitHub-Konto senden",+ "github_login_note": "Öffnet GitHub mit deinem ausgefüllten Bericht. Dafür brauchst du ein kostenloses GitHub-Konto — bist du nicht angemeldet, fragt GitHub danach und bringt dich anschließend zurück zu deinem Text.",+ "sending": "Sende…","screenshot_label": "Screenshot (optional)","screenshot_pick": "Klicken, um einen Screenshot anzuhängen","screenshot_preview_alt": "Screenshot-Vorschau","screenshot_remove": "Screenshot entfernen","screenshot_too_large": "Der Screenshot ist größer als 8 MB — bitte wähle ein kleineres Bild.",- "submit": "Senden",- "sending": "Sende…",- "result_sent": "Danke — wurde an unseren Discord gesendet!",- "result_not_configured": "Feedback-Kanal ist noch nicht eingerichtet — es wurde nichts gesendet.",- "result_error": "Discord nicht erreichbar, bitte später erneut versuchen.",- "result_github_opened": "Im Browser geöffnet — prüfe und sende das Issue auf GitHub ab."+ "result_sent": "Danke — ist angekommen!",+ "result_not_configured": "Der direkte Weg ist nicht mehr verfügbar — nutz den GitHub-Button.",+ "result_error": "Konnte nicht senden, bitte später erneut versuchen.",+ "result_github_opened": "Im Browser geöffnet — prüf den Bericht und schick ihn auf GitHub ab.",+ "result_github_trimmed": "Im Browser geöffnet. Dein Text war zu lang für die Adresszeile und liegt vollständig in der Zwischenablage — füg ihn auf GitHub ein.",+ "board_ideas_title": "Das wünschen sich andere",+ "board_bugs_title": "Bekannte Fehler",+ "board_see_all": "Alle auf GitHub ansehen",+ "board_upvotes": "Stimmen",+ "question_title": "Fragen beantworten wir im Discord",+ "question_hint": "Dort bekommst du meist am selben Tag eine Antwort — schneller als über den Fehler-Tracker.",+ "question_discord_button": "Discord öffnen",+ "community_hint": "Lieber im Discord besprechen?",+ "community_open": "Öffnen"},"ultrawiki": {"people": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 5f055959e7..9fca0d82f0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -3188,33 +3188,45 @@"subtitle": "Telegram bot + local friend registry. You decide what friends see."},"feedback": {- "discord_cta_title": "Report on our Discord",- "discord_cta_subtitle": "Open #report-a-bug and post your bug, idea, or question directly.",- "discord_cta_button": "Open #report-a-bug",- "discord_join_button": "Join Discord first",- "or_send_here": "or send it from here",- "github_hint": "This install has no direct feedback channel — the button opens your report as a prefilled GitHub issue in your browser.",- "github_submit": "Open a prefilled GitHub issue",- "subtitle": "Open our Discord to report a bug, share an idea, or ask a question.",- "type_label": "Type",+ "subtitle": "Report a bug or suggest a feature — both go straight to GitHub.",+ "type_label": "What is it?","type_bug": "Bug",- "type_idea": "Idea",+ "type_idea": "Feature","type_question": "Question","title_label": "Title",- "title_placeholder": "Short summary of your feedback",- "description_label": "Description",- "description_placeholder": "Tell us more — steps to reproduce, context, expected vs. actual behaviour…",+ "title_placeholder": "One line, in plain words",+ "bug_what_label": "What happened?",+ "bug_what_placeholder": "Describe the bug and what you expected instead.",+ "bug_steps_label": "Steps to reproduce",+ "bug_steps_placeholder": "1. …\n2. …\n3. The error appears",+ "idea_problem_label": "What problem does this solve?",+ "idea_problem_placeholder": "What are you trying to do that Jarvis can't do today?",+ "idea_solution_label": "How should it work?",+ "idea_solution_placeholder": "A spoken command, a setting, a new view?",+ "github_submit_bug": "Report the bug on GitHub",+ "github_submit_idea": "Suggest the feature on GitHub",+ "send_without_github": "Send without a GitHub account",+ "github_login_note": "Opens GitHub with your report filled in. You need a free GitHub account — if you're signed out, GitHub asks first and brings you straight back to your text.",+ "sending": "Sending…","screenshot_label": "Screenshot (optional)","screenshot_pick": "Click to attach a screenshot","screenshot_preview_alt": "Screenshot preview","screenshot_remove": "Remove screenshot","screenshot_too_large": "Screenshot is larger than 8 MB — please choose a smaller image.",- "submit": "Submit",- "sending": "Sending…",- "result_sent": "Thanks — sent to our Discord!",- "result_not_configured": "Feedback channel isn't set up yet — nothing was sent.",- "result_error": "Couldn't reach Discord, please try again later.",- "result_github_opened": "Opened in your browser — review and submit the issue on GitHub."+ "result_sent": "Thanks — that arrived!",+ "result_not_configured": "The direct channel is gone — use the GitHub button.",+ "result_error": "Couldn't send it, please try again later.",+ "result_github_opened": "Opened in your browser — review it and submit the issue on GitHub.",+ "result_github_trimmed": "Opened in your browser. Your text was too long for the address bar and is on your clipboard in full — paste it on GitHub.",+ "board_ideas_title": "What others are asking for",+ "board_bugs_title": "Known bugs",+ "board_see_all": "See all on GitHub",+ "board_upvotes": "votes",+ "question_title": "Questions get answered on Discord",+ "question_hint": "Usually the same day — faster than the issue tracker.",+ "question_discord_button": "Open Discord",+ "community_hint": "Rather talk it through on Discord?",+ "community_open": "Open"},"ultrawiki": {"people": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 5159a9b5b0..d9c595b201 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -3188,33 +3188,45 @@"subtitle": "Bot de Telegram + registro local de amigos. Tú decides qué ven los amigos."},"feedback": {- "discord_cta_title": "Repórtalo en nuestro Discord",- "discord_cta_subtitle": "Abre #report-a-bug y publica tu error, idea o pregunta directamente.",- "discord_cta_button": "Abrir #report-a-bug",- "discord_join_button": "Unirse primero a Discord",- "or_send_here": "o envíalo desde aquí",- "github_hint": "Esta instalación no tiene un canal de comentarios directo — el botón abre tu informe como una incidencia de GitHub rellenada en tu navegador.",- "github_submit": "Abrir una incidencia de GitHub rellenada",- "subtitle": "Abre nuestro Discord para reportar un error, compartir una idea o hacer una pregunta.",- "type_label": "Tipo",+ "subtitle": "Informa de un error o propón una función — ambos van directos a GitHub.",+ "type_label": "¿De qué se trata?","type_bug": "Error",- "type_idea": "Idea",+ "type_idea": "Función","type_question": "Pregunta","title_label": "Título",- "title_placeholder": "Resumen breve de tus comentarios",- "description_label": "Descripción",- "description_placeholder": "Cuéntanos más — pasos para reproducir, contexto, comportamiento esperado vs. real…",+ "title_placeholder": "Una línea, en palabras sencillas",+ "bug_what_label": "¿Qué ha pasado?",+ "bug_what_placeholder": "Describe el error y qué esperabas en su lugar.",+ "bug_steps_label": "Pasos para reproducirlo",+ "bug_steps_placeholder": "1. …\n2. …\n3. Aparece el error",+ "idea_problem_label": "¿Qué problema resuelve?",+ "idea_problem_placeholder": "¿Qué intentas hacer que Jarvis no puede hacer hoy?",+ "idea_solution_label": "¿Cómo debería funcionar?",+ "idea_solution_placeholder": "¿Un comando de voz, un ajuste, una vista nueva?",+ "github_submit_bug": "Informar del error en GitHub",+ "github_submit_idea": "Proponer la función en GitHub",+ "send_without_github": "Enviar sin cuenta de GitHub",+ "github_login_note": "Abre GitHub con tu informe ya rellenado. Necesitas una cuenta gratuita de GitHub — si no has iniciado sesión, GitHub te lo pedirá y luego te devolverá a tu texto.",+ "sending": "Enviando…","screenshot_label": "Captura de pantalla (opcional)","screenshot_pick": "Haz clic para adjuntar una captura","screenshot_preview_alt": "Vista previa de la captura","screenshot_remove": "Eliminar captura","screenshot_too_large": "La captura supera los 8 MB — elige una imagen más pequeña.",- "submit": "Enviar",- "sending": "Enviando…",- "result_sent": "¡Gracias — enviado a nuestro Discord!",- "result_not_configured": "El canal de comentarios aún no está configurado — no se envió nada.",- "result_error": "No se pudo llegar a Discord, inténtalo de nuevo más tarde.",- "result_github_opened": "Abierto en tu navegador — revisa y envía la incidencia en GitHub."+ "result_sent": "¡Gracias, ha llegado!",+ "result_not_configured": "El canal directo ya no está disponible — usa el botón de GitHub.",+ "result_error": "No se pudo enviar, inténtalo de nuevo más tarde.",+ "result_github_opened": "Abierto en tu navegador — revísalo y envía la incidencia en GitHub.",+ "result_github_trimmed": "Abierto en tu navegador. Tu texto era demasiado largo para la barra de direcciones y está completo en el portapapeles — pégalo en GitHub.",+ "board_ideas_title": "Lo que piden otros",+ "board_bugs_title": "Errores conocidos",+ "board_see_all": "Ver todo en GitHub",+ "board_upvotes": "votos",+ "question_title": "Las preguntas se responden en Discord",+ "question_hint": "Normalmente el mismo día — más rápido que el gestor de incidencias.",+ "question_discord_button": "Abrir Discord",+ "community_hint": "¿Prefieres hablarlo en Discord?",+ "community_open": "Abrir"},"ultrawiki": {"people": {diff --git a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsxindex e25bce5f20..fe36244d08 100644--- a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx@@ -1,14 +1,16 @@/*** Component tests for FeedbackView.*- * The Feedback section offers two honest paths:- * 1. Discord (primary): a button straight to the #report-a-bug forum plus a- * permanent invite, both via {@link openExternalUrl} — NOT a bare anchor,- * because the desktop WebView2 shell drops target="_blank".- * 2. An in-app form (secondary) that probes GET /api/feedback/status first:- * - webhook configured → POST /api/feedback (direct dispatch).- * - not configured → the submit button opens a PREFILLED GitHub- * issue with the typed report + system context instead.+ * The section files bugs AND feature requests, both as real GitHub issues on+ * the repository's own issue forms. What the tests below protect is the wiring+ * that is invisible when it breaks: an issue opened without `?template=` still+ * opens — it just lands blank, unlabelled and unstructured, and nothing in the+ * UI looks wrong. Same for a prefilled field id that no longer exists: GitHub+ * drops it silently and that part of the report is simply gone.+ *+ * Also covered: the URL budget (a long report must not produce a dead link),+ * the account note (said before the user hits a login wall), and the board,+ * which reads open issues without any login at all.*/import { afterEach, describe, expect, it, vi } from "vitest";import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";@@ -16,26 +18,50 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/reimport { FeedbackView } from "@/views/feedback/FeedbackView";import * as openExternal from "@/lib/openExternal";+const ISSUES_URL = "https://github.com/PersonalJarvis/PersonalJarvis/issues";+const STATUS_NOT_CONFIGURED = {configured: false,- github_url: "https://github.com/PersonalJarvis/PersonalJarvis/issues",- context: { app_version: "1.0.8", os: "TestOS-1.0", python: "3.11.0" },+ github_url: ISSUES_URL,+ templates: {+ bug: "bug_report.yml",+ idea: "feature_request.yml",+ question: null,+ },+ context: {+ app_version: "1.0.8",+ os: "TestOS-1.0",+ python: "3.11.0",+ os_choice: "Windows",+ },};const STATUS_CONFIGURED = { ...STATUS_NOT_CONFIGURED, configured: true };-/** Stub fetch: GET /status returns `status`, POST /api/feedback returns `postResult`. */-function stubFeedbackApi(status: object, postResult?: object) {+const EMPTY_BOARD = { available: false, ideas: [], bugs: [], detail: "unreachable" };++const FULL_BOARD = {+ available: true,+ ideas: [{ number: 12, title: "Offline mode", url: `${ISSUES_URL}/12`, upvotes: 7, comments: 2 }],+ bugs: [{ number: 34, title: "Crash on startup", url: `${ISSUES_URL}/34`, upvotes: 3, comments: 1 }],+ detail: "",+};++/** Stub fetch for the three feedback endpoints. */+function stubFeedbackApi(status: object, opts: { board?: object; postResult?: object } = {}) {const fetchMock = vi.fn(async (url: unknown, init?: RequestInit) => {const href = String(url);if (href.includes("/api/feedback/status")) {return { ok: true, json: async () => status } as Response;}+ if (href.includes("/api/feedback/board")) {+ return { ok: true, json: async () => opts.board ?? EMPTY_BOARD } as Response;+ }if (href.includes("/api/feedback") && init?.method === "POST") {return {ok: true,json: async () =>- postResult ?? { ok: true, status: "sent", detail: "", github_url: null },+ opts.postResult ?? { ok: true, status: "sent", detail: "", github_url: null },} as Response;}return { ok: false, status: 404, statusText: "Not Found", json: async () => ({}) } as Response;@@ -44,13 +70,15 @@ function stubFeedbackApi(status: object, postResult?: object) {return fetchMock;}-function fillForm() {- fireEvent.change(screen.getByLabelText("Title"), {- target: { value: "Something broke" },- });- fireEvent.change(screen.getByLabelText("Description"), {- target: { value: "It broke when I clicked the button." },- });+function fillBugForm(what = "It broke when I clicked the button.", steps = "1. Click it") {+ fireEvent.change(screen.getByLabelText("Title"), { target: { value: "Something broke" } });+ fireEvent.change(screen.getByLabelText("What happened?"), { target: { value: what } });+ fireEvent.change(screen.getByLabelText("Steps to reproduce"), { target: { value: steps } });+}++/** Decode a query value the way a server would (`+` is a space in a query). */+function param(url: string, key: string): string | null {+ return new URL(url).searchParams.get(key);}afterEach(() => {@@ -60,135 +88,182 @@ afterEach(() => {});describe("FeedbackView", () => {- /** Wait for the mount-time status probe so state settles inside act(). */+ /** Wait for the mount-time probe so state settles inside act(). */async function probeSettled() {- await screen.findByRole("button", { name: "Open a prefilled GitHub issue" });+ await screen.findByRole("button", { name: "Report the bug on GitHub" });}- it("renders the Discord call-to-action with a forward button", async () => {+ it("offers both report kinds plus a question route", async () => {stubFeedbackApi(STATUS_NOT_CONFIGURED);render(<FeedbackView />);- expect(- screen.getByRole("button", { name: "Open #report-a-bug" }),- ).toBeTruthy();- expect(- screen.getByRole("button", { name: "Join Discord first" }),- ).toBeTruthy();+ expect(screen.getByRole("radiogroup", { name: "What is it?" })).toBeTruthy();+ expect(screen.getByRole("radio", { name: "Bug" })).toBeTruthy();+ expect(screen.getByRole("radio", { name: "Feature" })).toBeTruthy();+ expect(screen.getByRole("radio", { name: "Question" })).toBeTruthy();await probeSettled();});- it("opens the bug forum directly via the external-open bridge", async () => {+ it("opens a bug on the bug issue form with every field prefilled", async () => {stubFeedbackApi(STATUS_NOT_CONFIGURED);- const openSpy = vi- .spyOn(openExternal, "openExternalUrl")- .mockResolvedValue(undefined);+ const openSpy = vi.spyOn(openExternal, "openExternalUrl").mockResolvedValue(undefined);render(<FeedbackView />);- fireEvent.click(- screen.getByRole("button", { name: "Open #report-a-bug" }),- );-- expect(openSpy).toHaveBeenCalledTimes(1);- expect(openSpy).toHaveBeenCalledWith(- "https://discord.com/channels/1511102439066177656/1521522036709789736",- );- await probeSettled();+ const submit = await screen.findByRole("button", { name: "Report the bug on GitHub" });+ fillBugForm();+ fireEvent.click(submit);++ await waitFor(() => expect(openSpy).toHaveBeenCalledTimes(1));+ const url = String(openSpy.mock.calls[0][0]);+ expect(url.startsWith(`${ISSUES_URL}/new?`)).toBe(true);+ // Without the template the issue lands blank and unlabelled.+ expect(param(url, "template")).toBe("bug_report.yml");+ // Passing `title` overrides the form's own default prefix, so it is set here.+ expect(param(url, "title")).toBe("[Bug]: Something broke");+ expect(param(url, "what-happened")).toBe("It broke when I clicked the button.");+ expect(param(url, "steps")).toBe("1. Click it");+ // Both taken from the running install so nobody has to look them up.+ expect(param(url, "os")).toBe("Windows");+ expect(param(url, "python")).toBe("3.11.0");});- it("keeps a permanent server invite for people who have not joined yet", async () => {+ it("opens a feature request on the feature issue form", async () => {stubFeedbackApi(STATUS_NOT_CONFIGURED);- const openSpy = vi- .spyOn(openExternal, "openExternalUrl")- .mockResolvedValue(undefined);+ const openSpy = vi.spyOn(openExternal, "openExternalUrl").mockResolvedValue(undefined);render(<FeedbackView />);- fireEvent.click(- screen.getByRole("button", { name: "Join Discord first" }),- );-- expect(openSpy).toHaveBeenCalledTimes(1);- expect(openSpy).toHaveBeenCalledWith("https://discord.gg/x7USduHxbc");await probeSettled();+ fireEvent.click(screen.getByRole("radio", { name: "Feature" }));++ fireEvent.change(screen.getByLabelText("Title"), { target: { value: "Offline mode" } });+ fireEvent.change(screen.getByLabelText("What problem does this solve?"), {+ target: { value: "I travel without internet." },+ });+ fireEvent.change(screen.getByLabelText("How should it work?"), {+ target: { value: "Queue everything locally." },+ });+ fireEvent.click(screen.getByRole("button", { name: "Suggest the feature on GitHub" }));++ await waitFor(() => expect(openSpy).toHaveBeenCalledTimes(1));+ const url = String(openSpy.mock.calls[0][0]);+ expect(param(url, "template")).toBe("feature_request.yml");+ expect(param(url, "title")).toBe("[Feature]: Offline mode");+ expect(param(url, "problem")).toBe("I travel without internet.");+ expect(param(url, "solution")).toBe("Queue everything locally.");+ // The bug form's fields must not leak into a feature request.+ expect(param(url, "what-happened")).toBeNull();+ expect(param(url, "os")).toBeNull();});- it("renders the in-app form below the Discord card", async () => {+ it("keeps a long report inside the URL budget and saves the full text", async () => {stubFeedbackApi(STATUS_NOT_CONFIGURED);+ const openSpy = vi.spyOn(openExternal, "openExternalUrl").mockResolvedValue(undefined);+ const writeText = vi.fn(async (_text: string) => undefined);+ vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });+render(<FeedbackView />);+ const submit = await screen.findByRole("button", { name: "Report the bug on GitHub" });+ // Percent-encoding roughly triples a newline-heavy body, so this alone+ // would push the URL far past what GitHub accepts.+ const huge = "line of detail\n".repeat(400);+ fillBugForm(huge, huge);+ fireEvent.click(submit);- expect(screen.getByLabelText("Title")).toBeTruthy();- expect(screen.getByLabelText("Description")).toBeTruthy();- expect(screen.getByRole("radiogroup", { name: "Type" })).toBeTruthy();- expect(screen.getByRole("radio", { name: "Bug" })).toBeTruthy();- expect(screen.getByRole("radio", { name: "Idea" })).toBeTruthy();- expect(screen.getByRole("radio", { name: "Question" })).toBeTruthy();+ await waitFor(() => expect(openSpy).toHaveBeenCalledTimes(1));+ expect(String(openSpy.mock.calls[0][0]).length).toBeLessThanOrEqual(6000);+ // Nothing the user wrote may be lost: the untrimmed report goes to the+ // clipboard, and they are told so.+ await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1));+ expect(String(writeText.mock.calls[0][0])).toContain(huge.trim());+ expect(screen.getByRole("status").textContent).toContain("clipboard");+ });++ it("does not open the tracker for a question", async () => {+ stubFeedbackApi(STATUS_NOT_CONFIGURED);+ const openSpy = vi.spyOn(openExternal, "openExternalUrl").mockResolvedValue(undefined);++ render(<FeedbackView />);await probeSettled();+ fireEvent.click(screen.getByRole("radio", { name: "Question" }));++ // A question has no issue form — the form is replaced, not just relabelled.+ expect(screen.queryByLabelText("Title")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Open Discord" }));+ expect(openSpy).toHaveBeenCalledWith("https://discord.gg/x7USduHxbc");});- it("opens a prefilled GitHub issue when no feedback channel is configured", async () => {+ it("states the account requirement before the user hits the login wall", async () => {stubFeedbackApi(STATUS_NOT_CONFIGURED);- const openSpy = vi- .spyOn(openExternal, "openExternalUrl")- .mockResolvedValue(undefined);+ render(<FeedbackView />);+ await probeSettled();++ expect(screen.getByText(/free GitHub account/)).toBeTruthy();+ });++ it("shows what others already asked for, without any login", async () => {+ stubFeedbackApi(STATUS_NOT_CONFIGURED, { board: FULL_BOARD });+ const openSpy = vi.spyOn(openExternal, "openExternalUrl").mockResolvedValue(undefined);render(<FeedbackView />);- // The probe resolves → the submit button flips to GitHub mode.- const submit = await screen.findByRole("button", {- name: "Open a prefilled GitHub issue",- });- fillForm();- fireEvent.click(submit);+ await screen.findByText("What others are asking for");+ expect(screen.getByText("Known bugs")).toBeTruthy();+ expect(screen.getByText("Offline mode")).toBeTruthy();- await waitFor(() => expect(openSpy).toHaveBeenCalledTimes(1));- const url = String(openSpy.mock.calls[0][0]);- expect(url).toContain(- "https://github.com/PersonalJarvis/PersonalJarvis/issues/new?",- );- expect(url).toContain("Something+broke");- // System context from the status probe rides along in the issue body.- expect(decodeURIComponent(url.replace(/\+/g, " "))).toContain(- "App version: 1.0.8",- );+ fireEvent.click(screen.getByText("Offline mode"));+ expect(openSpy).toHaveBeenCalledWith(`${ISSUES_URL}/12`);});- it("hides the screenshot picker in GitHub mode (a URL cannot carry an image)", async () => {- stubFeedbackApi(STATUS_NOT_CONFIGURED);+ it("hides the board entirely when nothing could be loaded", async () => {+ stubFeedbackApi(STATUS_NOT_CONFIGURED, { board: EMPTY_BOARD });render(<FeedbackView />);+ await probeSettled();- await screen.findByRole("button", { name: "Open a prefilled GitHub issue" });- expect(screen.queryByText("Click to attach a screenshot")).toBeNull();+ // An empty list would read as "nobody ever asked for anything".+ expect(screen.queryByText("What others are asking for")).toBeNull();+ expect(screen.queryByText("See all on GitHub")).toBeNull();});- it("dispatches through POST /api/feedback when the channel is configured", async () => {+ it("adds the account-free direct path only on an operator install", async () => {const fetchMock = stubFeedbackApi(STATUS_CONFIGURED);render(<FeedbackView />);- // Configured mode keeps the plain submit label and shows the picker.+ // The screenshot picker rides with the direct channel — a GitHub issue URL+ // cannot carry an image.await screen.findByText("Click to attach a screenshot");- fillForm();- fireEvent.click(screen.getByRole("button", { name: "Submit" }));+ fillBugForm();+ fireEvent.click(screen.getByRole("button", { name: "Send without a GitHub account" }));- await screen.findByText("Thanks — sent to our Discord!");+ await screen.findByText("Thanks — that arrived!");const post = fetchMock.mock.calls.find(([, init]) => init?.method === "POST");- expect(post).toBeTruthy();const body = JSON.parse(String(post?.[1]?.body)) as Record<string, unknown>;- expect(body).toMatchObject({- type: "bug",- title: "Something broke",- description: "It broke when I clicked the button.",- });+ expect(body).toMatchObject({ type: "bug", title: "Something broke" });+ // Both fields reach the direct channel, which has no separate steps field.+ expect(String(body.description)).toContain("It broke when I clicked the button.");+ expect(String(body.description)).toContain("1. Click it");});- it("keeps submit disabled until title and description are filled", async () => {- stubFeedbackApi(STATUS_CONFIGURED);+ it("offers no direct path and no screenshot picker on a plain install", async () => {+ stubFeedbackApi(STATUS_NOT_CONFIGURED);render(<FeedbackView />);+ await probeSettled();- const submit = screen.getByRole("button", { name: "Submit" });+ expect(screen.queryByRole("button", { name: "Send without a GitHub account" })).toBeNull();+ expect(screen.queryByText("Click to attach a screenshot")).toBeNull();+ });++ it("keeps submit disabled until the title and the first field are filled", async () => {+ stubFeedbackApi(STATUS_NOT_CONFIGURED);+ render(<FeedbackView />);++ const submit = await screen.findByRole("button", { name: "Report the bug on GitHub" });expect((submit as HTMLButtonElement).disabled).toBe(true);- fillForm();- await waitFor(() =>- expect((submit as HTMLButtonElement).disabled).toBe(false),- );++ fireEvent.change(screen.getByLabelText("Title"), { target: { value: "Something broke" } });+ // Title alone is not a report.+ expect((submit as HTMLButtonElement).disabled).toBe(true);++ fireEvent.change(screen.getByLabelText("What happened?"), { target: { value: "It broke." } });+ await waitFor(() => expect((submit as HTMLButtonElement).disabled).toBe(false));});});diff --git a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsxindex bcb73b3c77..3526deaa6d 100644--- a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx+++ b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx@@ -1,11 +1,13 @@-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {+ ArrowUpRight,Bug,ExternalLink,HelpCircle,ImagePlus,Lightbulb,MessageSquareWarning,+ ThumbsUp,X,} from "lucide-react";@@ -13,29 +15,51 @@ import { ViewHeader } from "@/views/ChatsView";import { useT } from "@/i18n";import { openExternalUrl } from "@/lib/openExternal";import {+ fetchFeedbackBoard,fetchFeedbackStatus,submitFeedback,+ type BoardEntry,+ type FeedbackBoard,type FeedbackChannelStatus,type FeedbackType,} from "@/views/feedback/api";/**- * The Feedback section — Discord stays the primary channel (the forum button- * plus a permanent invite), and below it an in-app form covers everyone the- * Discord path loses. The form probes GET /api/feedback/status first and- * presents the ONE path this install really has:+ * The Feedback section — one place for both report kinds, GitHub as the spine.*- * - webhook configured (operator install) → direct dispatch with optional- * screenshot, enriched server-side with app version / OS / Python.- * - not configured (every fresh download) → the submit button opens the- * report as a PREFILLED GitHub issue instead, system context included, so- * the form is never a dead end and nothing has to be retyped.+ * A bug and a feature request are the same act here: pick the kind, write two+ * fields, and the button opens the matching GitHub issue form with everything+ * already filled in. The report type selects the form+ * (`?template=bug_report.yml` / `feature_request.yml`), and THAT is what puts+ * the `bug` / `enhancement` label, the title prefix and the structure on the+ * issue. Opening `/issues/new` without a template — what this view used to do+ * — lands a blank, unlabelled issue that has to be triaged by hand.+ *+ * Three things this deliberately gets right:+ *+ * - **GitHub is the normal path, not a fallback.** The direct-dispatch+ * webhook is the maintainer's own operator credential, so `configured` is+ * false on every download. Presenting GitHub as what happens "because+ * this install has no channel" told 100 % of users their copy was+ * defective. When the webhook DOES exist it adds a second button, because+ * that path is the only one that works without a GitHub account.+ * - **The login question is answered up front.** Filing needs a free GitHub+ * account. If the user is signed out, GitHub asks and then returns them to+ * the prefilled report — nothing is retyped. Saying so beats a surprise+ * login wall.+ * - **A long report cannot be lost.** A prefilled issue travels in the URL,+ * and browsers/GitHub stop accepting one somewhere past ~8 KB. Anything+ * over the budget is trimmed for the URL and the FULL text is put on the+ * clipboard, with the user told to paste it.+ *+ * The board below reads open issues from the public GitHub API (no token, no+ * login) so someone sees their idea is already tracked instead of filing the+ * duplicate. Empty lists are not rendered: on a young tracker "0 requests"+ * reads as "nobody cares", which is both discouraging and untrue.** All external links go through {@link openExternalUrl} rather than a bare* `<a target="_blank">`, because the desktop shell (WebView2) silently drops- * `target="_blank"` / `window.open` — the new tab never appears. The bridge- * asks the backend to open the OS default browser instead (and falls back to- * `window.open` on a remote/VPS browser).+ * `target="_blank"` / `window.open` — the new tab never appears.*/// Discord's Community onboarding redirects invite links to #welcome even when@@ -53,9 +77,22 @@ const SCREENSHOT_MAX_BYTES = 8 * 1024 * 1024;// Matches the backend's Pydantic field constraints.const TITLE_MAX = 200;-const DESCRIPTION_MAX = 4000;+const FIELD_MAX = 4000;-type ResultKind = "sent" | "error" | "not_configured" | "github_opened";+/**+ * Budget for a prefilled issue URL. GitHub answers a request whose URL grows+ * past roughly 8 KB with an error instead of the form, and percent-encoding+ * can triple a character, so a 4 000-character field alone can blow it. Well+ * under the ceiling on purpose — the cost of being wrong is a dead link.+ */+const URL_MAX_CHARS = 6000;++type ResultKind =+ | "sent"+ | "error"+ | "not_configured"+ | "github_opened"+ | "github_opened_trimmed";const INPUT_CLS ="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground " +@@ -72,39 +109,137 @@ function DiscordIcon({ className }: { className?: string }) {}/**- * Compose the `/issues/new` URL with the report prefilled. System context- * comes from the status probe — the same fields the backend would attach on a- * direct dispatch, so a GitHub issue is not a second-class report.+ * The composed issue URL, plus whether anything had to be trimmed to fit.+ * `trimmed` is not cosmetic — it is the signal that the user's full text now+ * lives only on their clipboard.+ */+interface ComposedIssue {+ url: string;+ trimmed: boolean;+}++/**+ * Compose a prefilled issue URL for one of the repository's issue forms.+ *+ * Issue-form prefill works by FIELD ID: `?template=<file>&<field-id>=<value>`.+ * GitHub ignores an unknown id silently, and rejects a dropdown value that is+ * not an exact option — which is why the OS comes from the backend's+ * `os_choice` rather than the free-form platform string.+ *+ * The title prefix is applied here: passing `title` overrides the form's own+ * default (`"[Bug]: "`), so without this every report would lose it.+ *+ * If the result exceeds {@link URL_MAX_CHARS} the two long fields are trimmed,+ * longest first, until it fits. The caller is expected to hand the untrimmed+ * text to the user another way.*/-function buildGithubIssueUrl(+function buildIssueUrl(channel: FeedbackChannelStatus,type: FeedbackType,title: string,- description: string,+ primary: string,+ secondary: string,+): ComposedIssue | null {+ const template = channel.templates[type];+ if (!template) return null;++ const prefix = type === "bug" ? "[Bug]: " : "[Feature]: ";+ const base = `${channel.github_url}/new`;++ const compose = (a: string, b: string): string => {+ const params = new URLSearchParams({ template });+ params.set("title", `${prefix}${title.trim()}`);+ if (type === "bug") {+ params.set("what-happened", a);+ if (b) params.set("steps", b);+ // Both prefilled from the running install, so nobody has to look them up.+ params.set("os", channel.context.os_choice);+ params.set("python", channel.context.python);+ } else {+ params.set("problem", a);+ if (b) params.set("solution", b);+ }+ return `${base}?${params.toString()}`;+ };++ let a = primary.trim();+ let b = secondary.trim();+ let url = compose(a, b);+ if (url.length <= URL_MAX_CHARS) return { url, trimmed: false };++ // Shave the longer field repeatedly rather than truncating one to nothing:+ // a report keeps more of its meaning when both halves survive.+ const ELLIPSIS = "\n\n[…]";+ while (url.length > URL_MAX_CHARS && (a.length > 40 || b.length > 40)) {+ const step = Math.max(50, Math.ceil((url.length - URL_MAX_CHARS) / 6));+ if (a.length >= b.length) a = a.slice(0, Math.max(40, a.length - step));+ else b = b.slice(0, Math.max(40, b.length - step));+ url = compose(a ? a + ELLIPSIS : a, b ? b + ELLIPSIS : b);+ }+ return { url, trimmed: true };+}++/** The plain-text report, used for the clipboard when the URL had to trim. */+function composePlainText(+ type: FeedbackType,+ title: string,+ primary: string,+ secondary: string,+ channel: FeedbackChannelStatus | null,): string {- const body = [- description.trim(),- "",- "---",- `- Type: ${type}`,- `- App version: ${channel.context.app_version}`,- `- OS: ${channel.context.os}`,- `- Python: ${channel.context.python}`,- ].join("\n");- const params = new URLSearchParams({ title: title.trim(), body });- return `${channel.github_url}/new?${params.toString()}`;+ const lines = [title.trim(), "", primary.trim()];+ if (secondary.trim()) lines.push("", secondary.trim());+ if (channel) {+ lines.push(+ "",+ "---",+ `- Type: ${type}`,+ `- App version: ${channel.context.app_version}`,+ `- OS: ${channel.context.os}`,+ `- Python: ${channel.context.python}`,+ );+ }+ return lines.join("\n");+}++/** One board row: an open issue with its 👍 count. */+function BoardRow({ entry, label }: { entry: BoardEntry; label: string }) {+ return (+ <li>+ <button+ type="button"+ onClick={() => void openExternalUrl(entry.url)}+ className="group flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition hover:bg-muted/50"+ >+ <span+ className="flex shrink-0 items-center gap-1 rounded-md border border-border px-1.5 py-0.5 text-xs tabular-nums text-muted-foreground"+ aria-label={`${entry.upvotes} ${label}`}+ >+ <ThumbsUp className="h-3 w-3" aria-hidden="true" />+ {entry.upvotes}+ </span>+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">{entry.title}</span>+ <ArrowUpRight+ className="h-3.5 w-3.5 shrink-0 text-muted-foreground opacity-0 transition group-hover:opacity-100"+ aria-hidden="true"+ />+ </button>+ </li>+ );}export function FeedbackView() {const t = useT();- // null = probe pending or failed → default to the in-app submit path (its- // own error handling covers a server that is actually down).+ // null = probe pending or failed. The GitHub path needs the probe (it+ // carries the template names), so the form stays disabled until it lands.const [channel, setChannel] = useState<FeedbackChannelStatus | null>(null);+ const [board, setBoard] = useState<FeedbackBoard | null>(null);const [type, setType] = useState<FeedbackType>("bug");const [title, setTitle] = useState("");- const [description, setDescription] = useState("");+ const [primary, setPrimary] = useState("");+ const [secondary, setSecondary] = useState("");const [screenshot, setScreenshot] = useState<string | null>(null);const [screenshotTooLarge, setScreenshotTooLarge] = useState(false);const [sending, setSending] = useState(false);@@ -118,14 +253,25 @@ export function FeedbackView() {if (!cancelled) setChannel(status);}).catch(() => {- /* probe unreachable — keep the in-app path as default */+ /* probe unreachable — the form reports it on submit */+ });+ fetchFeedbackBoard()+ .then((data) => {+ if (!cancelled) setBoard(data);+ })+ .catch(() => {+ /* board is optional context, never an error the user must see */});return () => {cancelled = true;};}, []);- const githubMode = channel !== null && !channel.configured;+ // The operator webhook exists → offer direct dispatch as a second path. It+ // is the only one that works without a GitHub account, so it is worth its+ // own button rather than replacing the primary one.+ const canDispatchDirect = channel?.configured === true;+ const isQuestion = type === "question";const onPickScreenshot = useCallback((ev: React.ChangeEvent<HTMLInputElement>) => {const file = ev.target.files?.[0];@@ -144,52 +290,71 @@ export function FeedbackView() {reader.readAsDataURL(file);}, []);- const canSubmit = title.trim().length > 0 && description.trim().length > 0 && !sending;+ const canSubmit =+ title.trim().length > 0 && primary.trim().length > 0 && !sending && channel !== null;- const onSubmit = useCallback(- async (ev: React.FormEvent) => {- ev.preventDefault();- if (!canSubmit) return;- setResult(null);+ const resetForm = useCallback(() => {+ setTitle("");+ setPrimary("");+ setSecondary("");+ setScreenshot(null);+ }, []);- if (githubMode && channel) {- await openExternalUrl(buildGithubIssueUrl(channel, type, title, description));- setResult("github_opened");- return;- }+ /** Primary path: open the matching issue form with everything prefilled. */+ const onOpenGithub = useCallback(async () => {+ if (!canSubmit || !channel) return;+ setResult(null);+ const composed = buildIssueUrl(channel, type, title, primary, secondary);+ if (!composed) return;- setSending(true);+ if (composed.trimmed) {+ // The URL could not carry the whole report. Put the full text on the+ // clipboard BEFORE navigating, so nothing the user wrote is lost.try {- const res = await submitFeedback({- type,- title: title.trim(),- description: description.trim(),- screenshot,- });- if (res.status === "sent") {- setResult("sent");- setTitle("");- setDescription("");- setScreenshot(null);- } else if (res.status === "not_configured") {- // The probe said "configured" but the dispatch disagreed (webhook- // removed meanwhile). Flip to GitHub mode so the button becomes the- // working path instead of a repeat failure.- setResult("not_configured");- if (channel && res.github_url) {- setChannel({ ...channel, configured: false, github_url: res.github_url });- }- } else {- setResult("error");- }+ await navigator.clipboard.writeText(+ composePlainText(type, title, primary, secondary, channel),+ );} catch {+ // No clipboard permission — the trimmed issue still opens, and the+ // text remains in the form fields behind it.+ }+ }+ await openExternalUrl(composed.url);+ setResult(composed.trimmed ? "github_opened_trimmed" : "github_opened");+ }, [canSubmit, channel, primary, secondary, title, type]);++ /** Secondary path (operator installs only): straight to the webhook. */+ const onSendDirect = useCallback(async () => {+ if (!canSubmit) return;+ setResult(null);+ setSending(true);+ try {+ const description = secondary.trim()+ ? `${primary.trim()}\n\n${secondary.trim()}`+ : primary.trim();+ const res = await submitFeedback({+ type,+ title: title.trim(),+ description,+ screenshot,+ });+ if (res.status === "sent") {+ setResult("sent");+ resetForm();+ } else if (res.status === "not_configured") {+ // The probe said "configured" but the dispatch disagreed (webhook+ // removed meanwhile). Drop the direct button; GitHub still works.+ setResult("not_configured");+ if (channel) setChannel({ ...channel, configured: false });+ } else {setResult("error");- } finally {- setSending(false);}- },- [canSubmit, channel, description, githubMode, screenshot, title, type],- );+ } catch {+ setResult("error");+ } finally {+ setSending(false);+ }+ }, [canSubmit, channel, primary, resetForm, screenshot, secondary, title, type]);const typeOptions: Array<{ value: FeedbackType; label: string; icon: typeof Bug }> = [{ value: "bug", label: t("feedback.type_bug"), icon: Bug },@@ -197,25 +362,50 @@ export function FeedbackView() {{ value: "question", label: t("feedback.type_question"), icon: HelpCircle },];+ const fieldLabels = useMemo(() => {+ if (type === "bug") {+ return {+ primary: t("feedback.bug_what_label"),+ primaryPh: t("feedback.bug_what_placeholder"),+ secondary: t("feedback.bug_steps_label"),+ secondaryPh: t("feedback.bug_steps_placeholder"),+ };+ }+ return {+ primary: t("feedback.idea_problem_label"),+ primaryPh: t("feedback.idea_problem_placeholder"),+ secondary: t("feedback.idea_solution_label"),+ secondaryPh: t("feedback.idea_solution_placeholder"),+ };+ }, [t, type]);+const resultBanner: Record<ResultKind, { text: string; cls: string }> = {sent: {text: t("feedback.result_sent"),- cls: "border-emerald-500/40 bg-emerald-500/10 text-emerald-400",+ cls: "border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",},error: {text: t("feedback.result_error"),- cls: "border-red-500/40 bg-red-500/10 text-red-400",+ cls: "border-red-500/40 bg-red-500/10 text-red-600 dark:text-red-400",},not_configured: {text: t("feedback.result_not_configured"),- cls: "border-amber-500/40 bg-amber-500/10 text-amber-400",+ cls: "border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400",},github_opened: {text: t("feedback.result_github_opened"),cls: "border-border bg-muted/30 text-muted-foreground",},+ github_opened_trimmed: {+ text: t("feedback.result_github_trimmed"),+ cls: "border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400",+ },};+ const ideas = board?.available ? board.ideas : [];+ const bugs = board?.available ? board.bugs : [];+ const hasBoard = ideas.length > 0 || bugs.length > 0;+return (<div className="flex h-full flex-col overflow-y-auto scrollbar-jarvis"><ViewHeader@@ -226,193 +416,281 @@ export function FeedbackView() {<div className="flex flex-1 justify-center p-6"><div className="w-full max-w-md space-y-6 pb-8">- {/* Primary path: the Discord community. */}- <div className="rounded-2xl border border-[#5865F2]/40 bg-[#5865F2]/10 p-8 text-center">- <div className="mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-2xl bg-[#5865F2]/20">- <DiscordIcon className="h-9 w-9 text-[#5865F2]" />+ {/* What kind of report — this also picks the GitHub issue form. */}+ <div>+ <span+ id="feedback-type-label"+ className="mb-1.5 block text-xs font-medium text-muted-foreground"+ >+ {t("feedback.type_label")}+ </span>+ <div+ role="radiogroup"+ aria-labelledby="feedback-type-label"+ className="grid grid-cols-3 gap-2"+ >+ {typeOptions.map(({ value, label, icon: Icon }) => (+ <button+ key={value}+ type="button"+ role="radio"+ aria-checked={type === value}+ onClick={() => {+ setType(value);+ setResult(null);+ }}+ className={+ "flex items-center justify-center gap-1.5 rounded-lg border px-2 py-2 text-sm transition " ++ (type === value+ ? "border-primary/60 bg-primary/15 font-medium text-foreground"+ : "border-border text-muted-foreground hover:border-primary/40 hover:text-foreground")+ }+ >+ <Icon className="h-4 w-4" aria-hidden="true" />+ {label}+ </button>+ ))}</div>- <h2 className="mb-2 text-lg font-semibold text-foreground">- {t("feedback.discord_cta_title")}- </h2>- <p className="mb-6 text-sm text-muted-foreground">- {t("feedback.discord_cta_subtitle")}- </p>- <div className="space-y-3">- <button- type="button"- onClick={() => void openExternalUrl(DISCORD_BUG_FORUM_URL)}- className="w-full rounded-lg bg-[#5865F2] px-4 py-3 text-sm font-semibold text-white transition hover:bg-[#4752c4]"- >- {t("feedback.discord_cta_button")}- </button>+ </div>++ {isQuestion ? (+ /* A question is not a tracker item — it belongs where people+ answer, so this branch has no form at all. */+ <div className="space-y-3 rounded-2xl border border-[#5865F2]/40 bg-[#5865F2]/10 p-6 text-center">+ <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-[#5865F2]/20">+ <DiscordIcon className="h-7 w-7 text-[#5865F2]" />+ </div>+ <h2 className="text-base font-semibold text-foreground">+ {t("feedback.question_title")}+ </h2>+ <p className="pb-1 text-sm text-muted-foreground">+ {t("feedback.question_hint")}+ </p><buttontype="button"onClick={() => void openExternalUrl(DISCORD_INVITE_URL)}- className="w-full rounded-lg border border-[#5865F2]/40 px-4 py-2.5 text-sm font-medium text-[#8b94ff] transition hover:border-[#5865F2]/70 hover:bg-[#5865F2]/10"+ className="w-full rounded-lg bg-[#5865F2] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-[#4752c4]">- {t("feedback.discord_join_button")}+ {t("feedback.question_discord_button")}</button></div>- </div>-- <div className="flex items-center gap-3" aria-hidden="true">- <div className="h-px flex-1 bg-border" />- <span className="text-xs uppercase tracking-wider text-muted-foreground">- {t("feedback.or_send_here")}- </span>- <div className="h-px flex-1 bg-border" />- </div>-- {/* Secondary path: the in-app form (direct dispatch or GitHub issue). */}- <form- onSubmit={(ev) => void onSubmit(ev)}- className="space-y-4 rounded-2xl border border-border bg-card/60 p-6"- >- <div>- <span- id="feedback-type-label"- className="mb-1.5 block text-xs font-medium text-muted-foreground"- >- {t("feedback.type_label")}- </span>- <div- role="radiogroup"- aria-labelledby="feedback-type-label"- className="grid grid-cols-3 gap-2"- >- {typeOptions.map(({ value, label, icon: Icon }) => (- <button- key={value}- type="button"- role="radio"- aria-checked={type === value}- onClick={() => setType(value)}- className={- "flex items-center justify-center gap-1.5 rounded-lg border px-2 py-2 text-sm transition " +- (type === value- ? "border-primary/60 bg-primary/15 font-medium text-foreground"- : "border-border text-muted-foreground hover:border-primary/40 hover:text-foreground")- }- >- <Icon className="h-4 w-4" aria-hidden="true" />- {label}- </button>- ))}+ ) : (+ <form+ onSubmit={(ev) => {+ ev.preventDefault();+ void onOpenGithub();+ }}+ className="space-y-4 rounded-2xl border border-border bg-card/60 p-6"+ >+ <div>+ <label+ htmlFor="feedback-title"+ className="mb-1.5 block text-xs font-medium text-muted-foreground"+ >+ {t("feedback.title_label")}+ </label>+ <input+ id="feedback-title"+ type="text"+ value={title}+ maxLength={TITLE_MAX}+ onChange={(ev) => setTitle(ev.target.value)}+ placeholder={t("feedback.title_placeholder")}+ className={INPUT_CLS}+ /></div>- </div>-- <div>- <label- htmlFor="feedback-title"- className="mb-1.5 block text-xs font-medium text-muted-foreground"- >- {t("feedback.title_label")}- </label>- <input- id="feedback-title"- type="text"- value={title}- maxLength={TITLE_MAX}- onChange={(ev) => setTitle(ev.target.value)}- placeholder={t("feedback.title_placeholder")}- className={INPUT_CLS}- />- </div>- <div>- <label- htmlFor="feedback-description"- className="mb-1.5 block text-xs font-medium text-muted-foreground"- >- {t("feedback.description_label")}- </label>- <textarea- id="feedback-description"- rows={5}- value={description}- maxLength={DESCRIPTION_MAX}- onChange={(ev) => setDescription(ev.target.value)}- placeholder={t("feedback.description_placeholder")}- className={`${INPUT_CLS} resize-y`}- />- </div>+ <div>+ <label+ htmlFor="feedback-primary"+ className="mb-1.5 block text-xs font-medium text-muted-foreground"+ >+ {fieldLabels.primary}+ </label>+ <textarea+ id="feedback-primary"+ rows={4}+ value={primary}+ maxLength={FIELD_MAX}+ onChange={(ev) => setPrimary(ev.target.value)}+ placeholder={fieldLabels.primaryPh}+ className={`${INPUT_CLS} resize-y`}+ />+ </div>- {/* A GitHub issue URL cannot carry an image, so the screenshot- picker only appears when the direct channel exists. */}- {channel?.configured ? (<div>- <span className="mb-1.5 block text-xs font-medium text-muted-foreground">- {t("feedback.screenshot_label")}- </span>- {screenshot ? (- <div className="relative overflow-hidden rounded-lg border border-border">- <img- src={screenshot}- alt={t("feedback.screenshot_preview_alt")}- className="max-h-48 w-full bg-background object-contain"- />+ <label+ htmlFor="feedback-secondary"+ className="mb-1.5 block text-xs font-medium text-muted-foreground"+ >+ {fieldLabels.secondary}+ </label>+ <textarea+ id="feedback-secondary"+ rows={3}+ value={secondary}+ maxLength={FIELD_MAX}+ onChange={(ev) => setSecondary(ev.target.value)}+ placeholder={fieldLabels.secondaryPh}+ className={`${INPUT_CLS} resize-y`}+ />+ </div>++ {/* A GitHub issue URL cannot carry an image, so the screenshot+ picker only appears when the direct channel exists. */}+ {canDispatchDirect ? (+ <div>+ <span className="mb-1.5 block text-xs font-medium text-muted-foreground">+ {t("feedback.screenshot_label")}+ </span>+ {screenshot ? (+ <div className="relative overflow-hidden rounded-lg border border-border">+ <img+ src={screenshot}+ alt={t("feedback.screenshot_preview_alt")}+ className="max-h-48 w-full bg-background object-contain"+ />+ <button+ type="button"+ onClick={() => setScreenshot(null)}+ aria-label={t("feedback.screenshot_remove")}+ className="absolute right-2 top-2 rounded-md bg-background/80 p-1 text-muted-foreground transition hover:text-foreground"+ >+ <X className="h-4 w-4" aria-hidden="true" />+ </button>+ </div>+ ) : (<buttontype="button"- onClick={() => setScreenshot(null)}- aria-label={t("feedback.screenshot_remove")}- className="absolute right-2 top-2 rounded-md bg-background/80 p-1 text-muted-foreground transition hover:text-foreground"+ onClick={() => fileRef.current?.click()}+ className="flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-border px-3 py-4 text-sm text-muted-foreground transition hover:border-primary/50 hover:text-foreground">- <X className="h-4 w-4" aria-hidden="true" />+ <ImagePlus className="h-4 w-4" aria-hidden="true" />+ {t("feedback.screenshot_pick")}</button>- </div>- ) : (+ )}+ <input+ ref={fileRef}+ type="file"+ accept="image/*"+ className="hidden"+ onChange={onPickScreenshot}+ />+ {screenshotTooLarge ? (+ <p className="mt-1.5 text-xs text-red-500" role="alert">+ {t("feedback.screenshot_too_large")}+ </p>+ ) : null}+ </div>+ ) : null}++ {result ? (+ <p+ role="status"+ className={`rounded-lg border px-3 py-2 text-sm ${resultBanner[result].cls}`}+ >+ {resultBanner[result].text}+ </p>+ ) : null}++ <div className="space-y-2">+ <button+ type="submit"+ disabled={!canSubmit}+ className="flex w-full items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"+ >+ <ExternalLink className="h-4 w-4" aria-hidden="true" />+ {type === "bug"+ ? t("feedback.github_submit_bug")+ : t("feedback.github_submit_idea")}+ </button>++ {canDispatchDirect ? (<buttontype="button"- onClick={() => fileRef.current?.click()}- className="flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-border px-3 py-4 text-sm text-muted-foreground transition hover:border-primary/50 hover:text-foreground"+ onClick={() => void onSendDirect()}+ disabled={!canSubmit}+ className="w-full rounded-lg border border-border px-4 py-2 text-sm font-medium text-muted-foreground transition hover:border-primary/40 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50">- <ImagePlus className="h-4 w-4" aria-hidden="true" />- {t("feedback.screenshot_pick")}+ {sending ? t("feedback.sending") : t("feedback.send_without_github")}</button>- )}- <input- ref={fileRef}- type="file"- accept="image/*"- className="hidden"- onChange={onPickScreenshot}- />- {screenshotTooLarge ? (- <p className="mt-1.5 text-xs text-red-400" role="alert">- {t("feedback.screenshot_too_large")}- </p>) : null}</div>- ) : null}- {githubMode ? (+ {/* The account requirement, said before they hit the wall. */}<p className="text-xs leading-relaxed text-muted-foreground">- {t("feedback.github_hint")}+ {t("feedback.github_login_note")}</p>- ) : null}+ </form>+ )}++ {/* What is already tracked — public read, no login required. */}+ {hasBoard ? (+ <div className="space-y-4 rounded-2xl border border-border bg-card/40 p-5">+ {ideas.length > 0 ? (+ <div>+ <h3 className="mb-1 px-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">+ {t("feedback.board_ideas_title")}+ </h3>+ <ul>+ {ideas.map((entry) => (+ <BoardRow+ key={entry.number}+ entry={entry}+ label={t("feedback.board_upvotes")}+ />+ ))}+ </ul>+ </div>+ ) : null}++ {bugs.length > 0 ? (+ <div>+ <h3 className="mb-1 px-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">+ {t("feedback.board_bugs_title")}+ </h3>+ <ul>+ {bugs.map((entry) => (+ <BoardRow+ key={entry.number}+ entry={entry}+ label={t("feedback.board_upvotes")}+ />+ ))}+ </ul>+ </div>+ ) : null}- {result ? (- <p- role="status"- className={`rounded-lg border px-3 py-2 text-sm ${resultBanner[result].cls}`}+ <button+ type="button"+ onClick={() => void openExternalUrl(channel?.github_url ?? "")}+ className="flex w-full items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-xs font-medium text-muted-foreground transition hover:border-primary/40 hover:text-foreground">- {resultBanner[result].text}- </p>- ) : null}-- <button- type="submit"- disabled={!canSubmit}- className="flex w-full items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"- >- {githubMode ? <ExternalLink className="h-4 w-4" aria-hidden="true" /> : null}- {sending- ? t("feedback.sending")- : githubMode- ? t("feedback.github_submit")- : t("feedback.submit")}- </button>- </form>+ {t("feedback.board_see_all")}+ <ArrowUpRight className="h-3 w-3" aria-hidden="true" />+ </button>+ </div>+ ) : null}++ {/* The community, kept as a quiet footer rather than the headline:+ it is where conversation happens, not where reports are filed. */}+ {!isQuestion ? (+ <div className="flex items-center justify-between gap-3 rounded-xl border border-border bg-card/30 px-4 py-3">+ <div className="flex min-w-0 items-center gap-2.5">+ <DiscordIcon className="h-5 w-5 shrink-0 text-[#5865F2]" />+ <span className="truncate text-sm text-muted-foreground">+ {t("feedback.community_hint")}+ </span>+ </div>+ <button+ type="button"+ onClick={() => void openExternalUrl(DISCORD_BUG_FORUM_URL)}+ className="shrink-0 text-sm font-medium text-[#5865F2] transition hover:underline"+ >+ {t("feedback.community_open")}+ </button>+ </div>+ ) : null}</div></div></div>diff --git a/jarvis/ui/web/frontend/src/views/feedback/api.ts b/jarvis/ui/web/frontend/src/views/feedback/api.tsindex aeb941b445..d344d996d5 100644--- a/jarvis/ui/web/frontend/src/views/feedback/api.ts+++ b/jarvis/ui/web/frontend/src/views/feedback/api.ts@@ -3,6 +3,11 @@* Plain fetch — mirrors the pattern in views/socials/api.ts.*/+/**+ * The three kinds of report the section handles. `bug` and `idea` are both+ * first-class GitHub issues on their own issue form; `question` deliberately+ * has no form and is routed to the community instead of the tracker.+ */export type FeedbackType = "bug" | "idea" | "question";export interface FeedbackPayload {@@ -28,19 +33,57 @@ export interface FeedbackContext {app_version: string;os: string;python: string;+ /**+ * The same OS collapsed onto one of the bug form's dropdown options. GitHub+ * drops a dropdown prefill that is not an exact option string, so the+ * free-form `os` above cannot serve that field.+ */+ os_choice: string;}/**- * Capability probe (GET /api/feedback/status). `configured: false` is the- * default on every fresh install — the operator webhook is the maintainer's- * own credential — and the form then routes to a prefilled GitHub issue.+ * Capability probe (GET /api/feedback/status).+ *+ * `templates` is the primary path: it names the issue form each report type+ * opens, which is what applies the `bug` / `enhancement` label and the title+ * prefix. A type mapped to `null` has no form and must not open the tracker.+ *+ * `configured: false` is the default on every fresh install — the direct+ * dispatch webhook is the maintainer's own operator credential — and that is+ * a normal state, not a fault.*/export interface FeedbackChannelStatus {configured: boolean;github_url: string;+ templates: Partial<Record<FeedbackType, string | null>>;context: FeedbackContext;}+/** One open issue as the board renders it. */+export interface BoardEntry {+ number: number;+ title: string;+ url: string;+ /** 👍 reactions — the tracker's closest thing to a vote count. */+ upvotes: number;+ comments: number;+}++/**+ * Open issues grouped by kind (GET /api/feedback/board). Read from the public+ * GitHub API, so it needs no token and no login.+ *+ * `available: false` means the lists could not be loaded at all — the view+ * hides the board rather than rendering an empty one, which would read as+ * "nobody ever asked for anything".+ */+export interface FeedbackBoard {+ available: boolean;+ ideas: BoardEntry[];+ bugs: BoardEntry[];+ detail: string;+}+const BASE = "/api/feedback";export async function fetchFeedbackStatus(): Promise<FeedbackChannelStatus> {@@ -49,6 +92,12 @@ export async function fetchFeedbackStatus(): Promise<FeedbackChannelStatus> {return (await res.json()) as FeedbackChannelStatus;}+export async function fetchFeedbackBoard(): Promise<FeedbackBoard> {+ const res = await fetch(`${BASE}/board`, { cache: "no-store" });+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);+ return (await res.json()) as FeedbackBoard;+}+export async function submitFeedback(payload: FeedbackPayload): Promise<FeedbackResult> {const res = await fetch(BASE, {method: "POST",diff --git a/tests/unit/ui/web/test_feedback_routes.py b/tests/unit/ui/web/test_feedback_routes.pyindex a9d8eb270d..e60090f55c 100644--- a/tests/unit/ui/web/test_feedback_routes.py+++ b/tests/unit/ui/web/test_feedback_routes.py@@ -97,8 +97,9 @@ def test_status_not_configured_offers_github_fallback(client: TestClient, monkeybody = resp.json()assert body["configured"] is Falseassert body["github_url"] == GITHUB_ISSUES_URL- # The same system fields the POST route would attach server-side.- assert set(body["context"]) == {"app_version", "os", "python"}+ # The same system fields the POST route would attach server-side, plus the+ # dropdown-ready OS the bug form needs.+ assert set(body["context"]) == {"app_version", "os", "python", "os_choice"}assert all(isinstance(v, str) and v for v in body["context"].values())@@ -169,3 +170,263 @@ def test_app_version_pyproject_fallback_reads_repo_root() -> None:root = Path(feedback_routes.__file__).resolve().parents[3]assert (root / "pyproject.toml").is_file()+++# ----------------------------------------------------------------------+# Issue-form wiring+#+# The section's primary path is a PREFILLED GitHub issue on one of the repo's+# issue forms. That is what applies the `bug` / `enhancement` label and the+# title prefix; an issue opened without `?template=` lands blank, unlabelled,+# and gets sorted by hand. The wiring is therefore a contract between three+# files that nothing else checks: feedback_routes.py, the two YAML forms, and+# the frontend that composes the URL from `templates` + `context`.+# ----------------------------------------------------------------------+++def _template_dir() -> Path:+ import jarvis.ui.web.feedback_routes as feedback_routes++ root = Path(feedback_routes.__file__).resolve().parents[3]+ return root / ".github" / "ISSUE_TEMPLATE"+++def test_status_names_the_issue_forms(client: TestClient) -> None:+ """Every report type maps to a form (or to None, meaning 'not the tracker')."""+ resp = client.get("/api/feedback/status")++ assert resp.status_code == 200+ assert resp.json()["templates"] == {+ "bug": "bug_report.yml",+ "idea": "feature_request.yml",+ "question": None,+ }+++def test_named_issue_forms_exist_in_the_repo() -> None:+ """A renamed or deleted form would silently dead-end the primary path:+ GitHub answers `?template=<missing>` with the plain blank-issue editor and+ every prefilled field is dropped."""+ from jarvis.ui.web.feedback_routes import ISSUE_TEMPLATES++ for report_type, filename in ISSUE_TEMPLATES.items():+ if filename is None:+ continue+ assert (_template_dir() / filename).is_file(), (+ f"{report_type} points at a missing issue form: {filename}"+ )+++def test_prefilled_field_ids_exist_in_their_forms() -> None:+ """The frontend prefills by FIELD ID. GitHub ignores an unknown id without+ an error, so a renamed field loses that part of the report silently."""+ yaml = pytest.importorskip("yaml")++ expected: dict[str, set[str]] = {+ # Mirrors the field ids FeedbackView.tsx composes into the issue URL.+ "bug_report.yml": {"what-happened", "steps", "os", "python"},+ "feature_request.yml": {"problem", "solution"},+ }+ for filename, field_ids in expected.items():+ form = yaml.safe_load((_template_dir() / filename).read_text(encoding="utf-8"))+ present = {b["id"] for b in form["body"] if "id" in b}+ missing = field_ids - present+ assert not missing, f"{filename} lost prefilled field(s): {sorted(missing)}"+++def test_os_choice_matches_a_dropdown_option_of_the_bug_form() -> None:+ """GitHub drops a dropdown prefill that is not an EXACT option string, so+ the OS silently vanishes from the report if either side drifts."""+ yaml = pytest.importorskip("yaml")+ from jarvis.ui.web.feedback_routes import _os_choice++ form = yaml.safe_load((_template_dir() / "bug_report.yml").read_text(encoding="utf-8"))+ options = next(b["attributes"]["options"] for b in form["body"] if b.get("id") == "os")++ assert _os_choice() in options+++def test_os_choice_covers_every_platform(monkeypatch) -> None:+ """Each supported platform maps onto an option — including the headless+ Linux box, which is the distinction triage asks about first."""+ yaml = pytest.importorskip("yaml")+ import jarvis.ui.web.feedback_routes as feedback_routes++ form = yaml.safe_load((_template_dir() / "bug_report.yml").read_text(encoding="utf-8"))+ options = next(b["attributes"]["options"] for b in form["body"] if b.get("id") == "os")++ for system, expected in [("Windows", "Windows"), ("Darwin", "macOS")]:+ monkeypatch.setattr(feedback_routes.platform, "system", lambda s=system: s)+ assert feedback_routes._os_choice() == expected+ assert expected in options++ monkeypatch.setattr(feedback_routes.platform, "system", lambda: "Linux")+ monkeypatch.setenv("DISPLAY", ":0")+ assert feedback_routes._os_choice() == "Linux"++ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)+ headless = feedback_routes._os_choice()+ assert headless == "Headless server / VPS"+ assert headless in options+++# ----------------------------------------------------------------------+# GET /api/feedback/board — the public read of open issues+#+# No token and no GitHub login: someone without an account still sees their+# idea is already tracked, which is what prevents the duplicate they would+# otherwise file. The 60/hour unauthenticated IP budget makes the cache and+# the stale-on-failure behaviour part of the contract, not an optimisation.+# ----------------------------------------------------------------------++[email protected](autouse=True)+def _reset_board_cache():+ """The board cache is process-wide; leaking it across tests would let one+ test's fixture answer another's request."""+ import jarvis.ui.web.feedback_routes as feedback_routes++ feedback_routes._board_cache = None+ feedback_routes._board_cache_at = 0.0+ yield+ feedback_routes._board_cache = None+ feedback_routes._board_cache_at = 0.0+++def _issue(number: int, title: str, *, upvotes: int = 0, comments: int = 0) -> dict:+ return {+ "number": number,+ "title": title,+ "html_url": f"{GITHUB_ISSUES_URL}/{number}",+ "reactions": {"+1": upvotes},+ "comments": comments,+ }+++def test_board_drops_pull_requests() -> None:+ """/issues returns pull requests too, and a PR is not something a user+ asked for."""+ from jarvis.ui.web.feedback_routes import _entries_from_issues++ raw = [_issue(1, "A real request"), {**_issue(2, "A PR"), "pull_request": {"url": "x"}}]++ entries = _entries_from_issues(raw)++ assert [e.number for e in entries] == [1]+++def test_board_ranks_by_upvotes() -> None:+ """The 👍 count is the closest thing the tracker has to a vote, and the+ only reason the list is worth showing."""+ from jarvis.ui.web.feedback_routes import _entries_from_issues++ raw = [_issue(1, "meh", upvotes=1), _issue(2, "popular", upvotes=9), _issue(3, "new")]++ entries = _entries_from_issues(raw)++ assert [e.number for e in entries] == [2, 1, 3]+ assert entries[0].upvotes == 9+++def test_board_survives_a_malformed_row() -> None:+ """A row missing the fields the board renders is skipped, not fatal — one+ odd item must never blank the whole list."""+ from jarvis.ui.web.feedback_routes import _entries_from_issues++ raw = [{"number": "not-an-int", "title": "broken"}, {}, _issue(7, "fine")]++ assert [e.number for e in _entries_from_issues(raw)] == [7]+++def test_board_caches_between_requests(client: TestClient, monkeypatch) -> None:+ """Several desktop windows share one backend; without the cache each open+ window would spend its own pair of requests from the same IP budget."""+ import jarvis.ui.web.feedback_routes as feedback_routes++ calls: list[str] = []++ async def _fake_fetch(_client: object, label: str) -> list:+ calls.append(label)+ return [feedback_routes.BoardEntry(+ number=1, title=label, url=GITHUB_ISSUES_URL, upvotes=0, comments=0+ )]++ monkeypatch.setattr(feedback_routes, "_fetch_label", _fake_fetch)++ first = client.get("/api/feedback/board").json()+ second = client.get("/api/feedback/board").json()++ assert first["available"] is True+ assert first == second+ # One refresh only: two labels, fetched once.+ assert calls == ["enhancement", "bug"]+++def test_board_serves_the_last_good_lists_after_a_failed_refresh(+ client: TestClient, monkeypatch+) -> None:+ """A rate limit or a network blip is no reason to tell the user nobody+ ever asked for anything."""+ import jarvis.ui.web.feedback_routes as feedback_routes++ feedback_routes._board_cache = feedback_routes.FeedbackBoard(+ available=True,+ ideas=[feedback_routes.BoardEntry(+ number=5, title="Dark mode", url=GITHUB_ISSUES_URL, upvotes=3, comments=1+ )],+ bugs=[],+ )+ # Expired, so the route attempts a refresh — which fails.+ feedback_routes._board_cache_at = 0.0++ async def _boom(_client: object, _label: str) -> list:+ raise feedback_routes.httpx.ConnectError("no network")++ monkeypatch.setattr(feedback_routes, "_fetch_label", _boom)++ body = client.get("/api/feedback/board").json()++ assert body["available"] is True+ assert [e["title"] for e in body["ideas"]] == ["Dark mode"]+++def test_board_unavailable_when_it_never_loaded(client: TestClient, monkeypatch) -> None:+ """With no cached copy the board reports unavailable WITH a reason, so the+ frontend hides it instead of rendering an empty list that reads as+ 'nobody ever asked for anything'."""+ import jarvis.ui.web.feedback_routes as feedback_routes++ async def _boom(_client: object, _label: str) -> list:+ raise feedback_routes.httpx.ConnectError("no network")++ monkeypatch.setattr(feedback_routes, "_fetch_label", _boom)++ body = client.get("/api/feedback/board").json()++ assert body["available"] is False+ assert body["detail"] == "unreachable"+ assert body["ideas"] == [] and body["bugs"] == []+++def test_board_failure_does_not_freeze_out_the_next_retry(+ client: TestClient, monkeypatch+) -> None:+ """A failed refresh must not advance the cache timestamp — otherwise one+ blip would serve stale lists for a full TTL."""+ import jarvis.ui.web.feedback_routes as feedback_routes++ state = {"fail": True}++ async def _flaky(_client: object, label: str) -> list:+ if state["fail"]:+ raise feedback_routes.httpx.ConnectError("no network")+ return [feedback_routes.BoardEntry(+ number=2, title=label, url=GITHUB_ISSUES_URL, upvotes=1, comments=0+ )]++ monkeypatch.setattr(feedback_routes, "_fetch_label", _flaky)++ assert client.get("/api/feedback/board").json()["available"] is False+ state["fail"] = False+ assert client.get("/api/feedback/board").json()["available"] is True