Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(web): show sync failures and provider problems with a way to fix them (#3838)

Raghav Chamadiya77513067ca72
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.md
index bcdcc5d64..22cdc71ca 100644
--- a/docs/reference/API_REFERENCE.md
+++ b/docs/reference/API_REFERENCE.md
@@ -444,6 +444,14 @@ Six job modes exist (`job_executor.py`, `VALID_JOB_MODES`): `sync`,
are not addressable by name over HTTP; each is the engine behind the endpoints
in section 1. The mode is visible in `GET /api/jobs/{id}` under `config.mode`.
+A job can complete while its provider failed: each page it could not write
+counts in `failed_pages`, and `config.provider_issue` (`{kind, message}` plus
+optional `provider`, `model`, `target`, or `null`) names a shared cause such as
+a rejected API key (`auth`), a rate limit, an unreachable base URL, a missing
+model or path, or docs skipped because a configured provider would not load
+(`docs_skipped`; a repo with no provider at all is not reported). A job that
+fails on a recognised provider error stores the same hint as its `error_message`.
+
One job per repository may be `pending` or `running` at a time. A second launch
is `409`. On startup, the server marks any job left `running` or `pending` by a
previous process as `failed`, with the message `Server restarted — job
diff --git a/packages/api-client/src/repos.ts b/packages/api-client/src/repos.ts
index 4ec146081..98be5653f 100644
--- a/packages/api-client/src/repos.ts
+++ b/packages/api-client/src/repos.ts
@@ -4,7 +4,6 @@ import type {
RepoCreate,
RepoUpdate,
RepoResponse,
- JobResponse,
RepoStatsResponse,
PreflightResponse,
GenerateRequest,
@@ -35,20 +34,23 @@ export async function updateRepo(repoId: string, data: RepoUpdate): Promise<Repo
return apiPatch<RepoResponse>(`/api/repos/${repoId}`, data);
}
-export async function syncRepo(repoId: string): Promise<JobResponse> {
- return apiPost<JobResponse>(`/api/repos/${repoId}/sync`);
+/** POST a repo job endpoint that answers 202 with `{job_id, stream_token}`. */
+function launchRepoJob(repoId: string, action: string): Promise<JobLaunchResponse> {
+ return apiPost<JobLaunchResponse>(`/api/repos/${repoId}/${action}`);
}
-export async function fullResyncRepo(repoId: string): Promise<JobResponse> {
- return apiPost<JobResponse>(`/api/repos/${repoId}/full-resync`);
+export async function syncRepo(repoId: string): Promise<JobLaunchResponse> {
+ return launchRepoJob(repoId, "sync");
+}
+
+export async function fullResyncRepo(repoId: string): Promise<JobLaunchResponse> {
+ return launchRepoJob(repoId, "full-resync");
}
/** Start the first full index (docs included) for a registered repo.
* Returns 409 when a job is already active for it. */
-export async function startIndexJob(
- repoId: string,
-): Promise<{ job_id: string; status: string }> {
- return apiPost<{ job_id: string; status: string }>(`/api/repos/${repoId}/index`);
+export async function startIndexJob(repoId: string): Promise<JobLaunchResponse> {
+ return launchRepoJob(repoId, "index");
}
/** Provider connectivity smoke test + page/cost estimate for a first index. */
diff --git a/packages/core/src/repowise/core/generation/models.py b/packages/core/src/repowise/core/generation/models.py
index 39d267798..d2a6d0643 100644
--- a/packages/core/src/repowise/core/generation/models.py
+++ b/packages/core/src/repowise/core/generation/models.py
@@ -595,6 +595,10 @@ MODEL_WRITTEN_PAGE_TYPES: frozenset[str] = frozenset(
# failed while still handing back a row.
STUB_FALLBACK_ERROR = "stub_fallback_error"
+# Metadata key holding the user-facing hint (``{"kind", "message"}``) for a
+# stub whose error was a recognised provider failure, such as a rejected key.
+STUB_FALLBACK_HINT = "stub_fallback_hint"
+
def is_stub_fallback(page: Any) -> bool:
"""True when *page* is a stub standing in for a failed provider call."""
@@ -613,6 +617,23 @@ def count_stub_fallbacks(pages: Iterable[Any]) -> int:
return sum(1 for page in pages if is_stub_fallback(page))
+def dominant_stub_fallback_hint(pages: Iterable[Any]) -> dict | None:
+ """The provider hint most of *pages*' failed stubs share, or ``None``.
+
+ One rejected key fails every page the same way, so the most common hint
+ is the one worth showing for the whole run.
+ """
+ counts: dict[tuple[tuple[str, str], ...], int] = {}
+ for page in pages:
+ hint = (getattr(page, "metadata", None) or {}).get(STUB_FALLBACK_HINT)
+ if isinstance(hint, dict) and hint.get("message"):
+ key = tuple(sorted((str(k), str(v)) for k, v in hint.items()))
+ counts[key] = counts.get(key, 0) + 1
+ if not counts:
+ return None
+ return dict(max(counts, key=counts.__getitem__))
+
+
def member_structural_key(members: Iterable[str], *, prefix: str) -> str:
"""Return a stable identity for a page defined by the files it covers.
diff --git a/packages/core/src/repowise/core/generation/page_generator/pertype.py b/packages/core/src/repowise/core/generation/page_generator/pertype.py
index 78efe623d..10bb00cee 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -17,6 +17,7 @@ from typing import Any
import structlog
from repowise.core.ingestion.models import ParsedFile, RepoStructure
+from repowise.core.providers.llm.error_hints import describe_provider_error
from .. import onboarding as _onboarding
from ..agent_digest import MODULE_SIGNALS_KEY, module_signals, split_questions
@@ -34,6 +35,7 @@ from ..context_assembler import FilePageContext
from ..models import (
GENERATION_LEVELS,
STUB_FALLBACK_ERROR,
+ STUB_FALLBACK_HINT,
STUB_PAGE_CONFIDENCE,
GeneratedPage,
compute_page_id,
@@ -77,6 +79,9 @@ def _stub_fallback(page: GeneratedPage, page_type: str, exc: Exception) -> Gener
page it had, which is all of them.
"""
page.metadata[STUB_FALLBACK_ERROR] = str(exc)[:500]
+ hint = describe_provider_error(exc)
+ if hint is not None:
+ page.metadata[STUB_FALLBACK_HINT] = hint.as_dict()
page.confidence = STUB_PAGE_CONFIDENCE
log.warning(
"page_generation.stub_fallback",
diff --git a/packages/core/src/repowise/core/providers/llm/error_hints.py b/packages/core/src/repowise/core/providers/llm/error_hints.py
new file mode 100644
index 000000000..9125139c7
--- /dev/null
+++ b/packages/core/src/repowise/core/providers/llm/error_hints.py
@@ -0,0 +1,148 @@
+"""Turn a provider failure into a short hint a person can act on.
+
+Raw provider errors are long SDK strings ("Error code: 401 - {'type': ...}")
+that say what broke but not what to do. Job records, the web UI and the CLI
+show the hint instead; the raw error stays in the log. Hints never quote the
+error text, so a key echoed back by a provider cannot leak through them.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal
+from urllib.parse import urlsplit
+
+from repowise.core.providers.llm.base import ProviderError, RateLimitError
+
+ProviderIssueKind = Literal["auth", "rate_limit", "unreachable", "model_not_found", "not_found"]
+
+# Status-less SDK and HTTP-client connect failures (openai/anthropic
+# APIConnectionError, httpx ConnectError/ConnectTimeout), matched by name so
+# the check needs no SDK installed. A reset or broken pipe means the server
+# was reached, so it is not "unreachable".
+_CONNECT_ERROR_NAMES = frozenset({"APIConnectionError", "ConnectError", "ConnectTimeout"})
+
+
+@dataclass(frozen=True)
+class ProviderErrorHint:
+ kind: ProviderIssueKind
+ message: str
+ #: Values the message names, so a client can word it in its own language.
+ provider: str | None = None
+ model: str | None = None
+ target: str | None = None
+
+ def as_dict(self) -> dict[str, str]:
+ fields = {"provider": self.provider, "model": self.model, "target": self.target}
+ return {"kind": self.kind, "message": self.message} | {
+ k: v for k, v in fields.items() if v
+ }
+
+
+def describe_provider_error(
+ exc: BaseException, *, model: str | None = None
+) -> ProviderErrorHint | None:
+ """The actionable hint for *exc*, or ``None`` when it is not a provider
+ failure this recognises (an unknown error keeps its own text)."""
+ chain = _exception_chain(exc)
+ error = next((e for e in chain if isinstance(e, ProviderError)), None)
+ for classify in (_rate_limit_hint, _auth_hint, _not_found_hint, _unreachable_hint):
+ hint = classify(chain, error, model)
+ if hint is not None:
+ return hint
+ return None
+
+
+def _provider(error: ProviderError | None) -> tuple[str | None, str]:
+ """The provider's name if known, and how a message names it either way."""
+ known = error.provider if error is not None else None
+ return known, known or "the provider"
+
+
+def _rate_limit_hint(
+ chain: list[BaseException], error: ProviderError | None, model: str | None
+) -> ProviderErrorHint | None:
+ if not any(isinstance(e, RateLimitError) for e in chain) and _status(error) != 429:
+ return None
+ known, name = _provider(error)
+ return ProviderErrorHint(
+ "rate_limit",
+ f"{name} is rate limiting requests. Wait a few minutes, then run it again.",
+ provider=known,
+ )
+
+
+def _auth_hint(
+ chain: list[BaseException], error: ProviderError | None, model: str | None
+) -> ProviderErrorHint | None:
+ if _status(error) not in (401, 403):
+ return None
+ known, name = _provider(error)
+ return ProviderErrorHint(
+ "auth", f"API key rejected by {name}. Update it in Settings.", provider=known
+ )
+
+
+def _not_found_hint(
+ chain: list[BaseException], error: ProviderError | None, model: str | None
+) -> ProviderErrorHint | None:
+ if _status(error) != 404:
+ return None
+ known, name = _provider(error)
+ named = f"Model {model}" if model else "The configured model"
+ # A bare 404 is as often a wrong base URL path as a missing model.
+ if "model" in str(error).lower():
+ kind: ProviderIssueKind = "model_not_found"
+ message = f"{named} was not found at {name}. Choose another model in Settings."
+ else:
+ kind = "not_found"
+ message = f"{named} or the base URL path was not found at {name}. Check both in Settings."
+ return ProviderErrorHint(kind, message, provider=known, model=model)
+
+
+def _unreachable_hint(
+ chain: list[BaseException], error: ProviderError | None, model: str | None
+) -> ProviderErrorHint | None:
+ if not any(_is_connect_error(e) for e in chain):
+ return None
+ known, name = _provider(error)
+ target = next((url for e in chain if (url := _request_origin(e))), None)
+ return ProviderErrorHint(
+ "unreachable",
+ f"Could not reach {target or name}. Is the server running and the base URL correct?",
+ provider=known,
+ target=target,
+ )
+
+
+def _exception_chain(exc: BaseException) -> list[BaseException]:
+ chain: list[BaseException] = []
+ current: BaseException | None = exc
+ while current is not None and current not in chain and len(chain) < 8:
+ chain.append(current)
+ current = current.__cause__ or current.__context__
+ return chain
+
+
+def _status(exc: ProviderError | None) -> int | None:
+ return exc.status_code if exc is not None else None
+
+
+def _is_connect_error(exc: BaseException) -> bool:
+ return isinstance(exc, ConnectionRefusedError) or type(exc).__name__ in _CONNECT_ERROR_NAMES
+
+
+def _request_origin(exc: BaseException) -> str | None:
+ """``scheme://host:port`` of the request *exc* failed on, without the
+ path, query or credentials a full URL can carry. IPv6 hosts keep their
+ brackets."""
+ try:
+ parts = urlsplit(str(exc.request.url)) # type: ignore[attr-defined]
+ # No request attached (AttributeError; httpx raises RuntimeError when
+ # unset) or an unparseable URL (ValueError).
+ except (AttributeError, RuntimeError, ValueError):
+ return None
+ host = parts.netloc.rpartition("@")[2]
+ if not parts.scheme or not host:
+ return None
+ return f"{parts.scheme}://{host}"
diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.py
index aa077ba36..68ab254a0 100644
--- a/packages/server/src/repowise/server/job_executor.py
+++ b/packages/server/src/repowise/server/job_executor.py
@@ -48,7 +48,12 @@ from repowise.server.job_incremental import (
_incremental_page_regen,
_plan_incremental_page_regen, # noqa: F401
)
-from repowise.server.job_records import _complete_job_row, _finalize_job_status
+from repowise.server.job_records import (
+ _complete_job_row,
+ _failure_fields,
+ _finalize_job_status,
+ _provider_issue,
+)
from repowise.server.job_state import (
_load_state, # noqa: F401
_persist_initial_index_state,
@@ -430,12 +435,7 @@ async def execute_job(
except Exception as exc:
logger.exception("job_failed", job_id=job_id, error=str(exc))
await _finalize_job_status(
- app_state,
- session_factory,
- progress,
- job_id,
- status="failed",
- error_message=str(exc)[:500],
+ app_state, session_factory, progress, job_id, status="failed", **_failure_fields(exc)
)
finally:
get_cancel_tokens(app_state).pop(job_id, None)
@@ -676,6 +676,27 @@ async def _refresh_fts(fts: Any, swept_page_ids: Any, pages: list) -> None:
await fts.index_pages(pages)
+def _provider_failed_to_load(run: _JobRun) -> bool:
+ """Docs were skipped although a provider is configured for the repo.
+
+ A repo with no provider at all is keyless on purpose, and a keyless first
+ index writes templates by design; neither skip is a problem to report.
+ """
+ spec = run.spec
+ if run.docs_skip_reason is None or spec.is_initial_index:
+ return False
+ try:
+ from repowise.server.provider_config import get_active_provider
+
+ provider_id, _ = get_active_provider(repo_id=spec.repo_id, repo_path=spec.repo_path)
+ except Exception:
+ # Best-effort reporting: an unreadable provider config must not fail
+ # a job that already finished its work.
+ logger.debug("provider_config_unreadable", job_id=spec.job_id, exc_info=True)
+ return False
+ return provider_id is not None
+
+
async def _record_index_completion(
run: _JobRun, result: Any, all_pages: list, elapsed: float
) -> int:
@@ -698,6 +719,9 @@ async def _record_index_completion(
"file_count": result.file_count,
"symbol_count": result.symbol_count,
"pages_generated": pages_generated,
+ "provider_issue": _provider_issue(
+ all_pages, docs_skipped=_provider_failed_to_load(run)
+ ),
},
completed_pages=(
pages_generated - stub_fallbacks if pages_generated else result.file_count
diff --git a/packages/server/src/repowise/server/job_generate.py b/packages/server/src/repowise/server/job_generate.py
index 6f096b34c..166b2f4ce 100644
--- a/packages/server/src/repowise/server/job_generate.py
+++ b/packages/server/src/repowise/server/job_generate.py
@@ -16,7 +16,7 @@ from typing import TYPE_CHECKING, Any
import structlog
from repowise.core.persistence.database import get_session
-from repowise.server.job_records import _complete_job_row
+from repowise.server.job_records import _complete_job_row, _provider_issue
from repowise.server.job_state import _load_state, _persist_generate_job_state
if TYPE_CHECKING:
@@ -260,6 +260,7 @@ async def _run_generate_job(
"pages_marked_stale": marked_stale,
# On the job record so the UI can report an id that resolved to nothing.
"unknown_page_ids": list(plan.unknown_page_ids),
+ "provider_issue": _provider_issue(generated_pages),
},
completed_pages=pages_generated - stub_fallbacks,
failed_pages=stub_fallbacks,
diff --git a/packages/server/src/repowise/server/job_records.py b/packages/server/src/repowise/server/job_records.py
index 3834020b7..2895a2619 100644
--- a/packages/server/src/repowise/server/job_records.py
+++ b/packages/server/src/repowise/server/job_records.py
@@ -19,6 +19,27 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
+#: Shown when a provider is configured but could not be loaded. Fixed text:
+#: the load error itself can be long and is in the server log.
+DOCS_SKIPPED_MESSAGE = (
+ "A model provider is configured but could not be loaded, so documentation "
+ "was not updated. Check it in Settings."
+)
+
+
+def _provider_issue(pages: list, *, docs_skipped: bool = False) -> dict | None:
+ """What the UI shows when a completed run still went wrong with the provider:
+ the hint its failed pages share, else that docs were skipped."""
+ from repowise.core.generation.models import dominant_stub_fallback_hint
+
+ hint = dominant_stub_fallback_hint(pages)
+ if hint is not None:
+ return hint
+ if docs_skipped:
+ return {"kind": "docs_skipped", "message": DOCS_SKIPPED_MESSAGE}
+ return None
+
+
async def _complete_job_row(
session: Any,
job_id: str,
@@ -46,6 +67,28 @@ async def _complete_job_row(
)
+def _failure_fields(exc: BaseException) -> dict[str, Any]:
+ """The failed job's ``error_message`` and ``provider_issue``: the hint for a
+ recognised provider failure (the raw error is already logged), else the
+ error's own text."""
+ from repowise.core.providers.llm.error_hints import describe_provider_error
+
+ hint = describe_provider_error(exc)
+ if hint is None:
+ return {"error_message": str(exc)[:500], "provider_issue": None}
+ return {"error_message": hint.message, "provider_issue": hint.as_dict()}
+
+
+async def _record_provider_issue(session: Any, job_id: str, provider_issue: dict) -> None:
+ """Add ``provider_issue`` to the job's config, beside its run summary."""
+ job = await get_generation_job(session, job_id)
+ if job is None:
+ return
+ config = json.loads(job.config_json or "{}")
+ config["provider_issue"] = provider_issue
+ job.config_json = json.dumps(config)
+
+
async def _finalize_job_status(
app_state: Any,
session_factory: Any,
@@ -54,6 +97,7 @@ async def _finalize_job_status(
*,
status: str,
error_message: str,
+ provider_issue: dict | None = None,
) -> None:
"""Best-effort terminal status write shared by the failure and cancel paths.
@@ -73,6 +117,8 @@ async def _finalize_job_status(
return
try:
async with get_session(recovery_factory) as session:
+ if provider_issue is not None:
+ await _record_provider_issue(session, job_id, provider_issue)
await update_job_status(
session,
job_id,
diff --git a/packages/ui/__tests__/dashboard/active-job-banner.test.tsx b/packages/ui/__tests__/dashboard/active-job-banner.test.tsx
index 16e41c02b..d0856b93a 100644
--- a/packages/ui/__tests__/dashboard/active-job-banner.test.tsx
+++ b/packages/ui/__tests__/dashboard/active-job-banner.test.tsx
@@ -1,5 +1,5 @@
-import { describe, it, expect } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { describe, it, expect, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
import { ActiveJobBanner } from "../../src/dashboard/active-job-banner.js";
import type { Job } from "@repowise-dev/types/jobs";
@@ -61,4 +61,55 @@ describe("ActiveJobBanner", () => {
);
expect(screen.getByText("Details")).toBeInTheDocument();
});
+
+ it("shows a completed sync that lost pages to the provider as a warning with a settings link", () => {
+ const onDismiss = vi.fn();
+ render(
+ <ActiveJobBanner
+ job={makeJob({
+ status: "completed",
+ completed_pages: 0,
+ failed_pages: 10,
+ finished_at: "2026-01-01T00:01:00Z",
+ config: {
+ mode: "sync",
+ provider_issue: { kind: "auth", message: "API key rejected by openai. Update it in Settings." },
+ },
+ })}
+ settingsHref="/repos/r1/settings#provider"
+ onDismiss={onDismiss}
+ />,
+ );
+ expect(screen.getByRole("status")).toHaveTextContent("Sync finished with problems");
+ expect(screen.queryByText("Sync complete")).not.toBeInTheDocument();
+ expect(screen.getByText(/API key rejected by openai/)).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: /Provider settings/ })).toHaveAttribute(
+ "href",
+ "/repos/r1/settings#provider",
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
+ expect(onDismiss).toHaveBeenCalled();
+ });
+
+ it("links provider settings on a failure only when the provider caused it", () => {
+ const { rerender } = render(
+ <ActiveJobBanner
+ job={makeJob({ status: "failed", error_message: "Repository not found" })}
+ settingsHref="/s"
+ />,
+ );
+ expect(screen.getByRole("alert")).toHaveTextContent("Repository not found");
+ expect(screen.queryByRole("link", { name: /Provider settings/ })).not.toBeInTheDocument();
+ rerender(
+ <ActiveJobBanner
+ job={makeJob({
+ status: "failed",
+ error_message: "Could not reach http://localhost:11434.",
+ config: { mode: "sync", provider_issue: { kind: "unreachable", message: "x" } },
+ })}
+ settingsHref="/s"
+ />,
+ );
+ expect(screen.getByRole("link", { name: /Provider settings/ })).toBeInTheDocument();
+ });
});
diff --git a/packages/ui/__tests__/jobs/generation-progress.test.tsx b/packages/ui/__tests__/jobs/generation-progress.test.tsx
index b1f5291a4..505251b92 100644
--- a/packages/ui/__tests__/jobs/generation-progress.test.tsx
+++ b/packages/ui/__tests__/jobs/generation-progress.test.tsx
@@ -172,6 +172,111 @@ describe("GenerationProgress", () => {
expect(screen.getByRole("link", { name: /Provider settings/ })).toBeTruthy();
});
+ it("shows a completed run whose key was rejected as a warning, with its fixes", () => {
+ const onDismiss = vi.fn();
+ render(
+ <GenerationProgress
+ job={{
+ id: "j1",
+ status: "completed",
+ total_pages: 4,
+ completed_pages: 0,
+ failed_pages: 4,
+ config: {
+ provider_issue: {
+ kind: "auth",
+ message: "API key rejected by openai. Update it in Settings.",
+ },
+ },
+ }}
+ log={[]}
+ elapsed={10_000}
+ actualCost={null}
+ stuckPending={false}
+ cancelling={false}
+ onCancel={vi.fn()}
+ onRetry={vi.fn()}
+ onDismiss={onDismiss}
+ settingsHref="/repos/r1/settings#provider"
+ />,
+ );
+ expect(screen.getByText("Finished with problems")).toBeTruthy();
+ expect(screen.queryByText("Generation complete")).toBeNull();
+ expect(screen.getByText("No documentation pages were written.")).toBeTruthy();
+ expect(screen.getByText(/API key rejected by openai/)).toBeTruthy();
+ expect(screen.getByRole("link", { name: /Provider settings/ })).toHaveAttribute(
+ "href",
+ "/repos/r1/settings#provider",
+ );
+ fireEvent.click(screen.getByRole("button", { name: /Dismiss/ }));
+ expect(onDismiss).toHaveBeenCalled();
+ });
+
+ it("counts partly failed pages without offering provider settings it cannot justify", () => {
+ render(
+ <GenerationProgress
+ job={{ id: "j1", status: "completed", total_pages: 10, completed_pages: 7, failed_pages: 3 }}
+ log={[]}
+ elapsed={10_000}
+ actualCost={null}
+ stuckPending={false}
+ cancelling={false}
+ onCancel={vi.fn()}
+ settingsHref="/settings"
+ labels={{ somePagesFailed: (f, t) => `${f}/${t} lost` }}
+ />,
+ );
+ expect(screen.getByText("3/10 lost")).toBeTruthy();
+ expect(screen.queryByRole("link", { name: /Provider settings/ })).toBeNull();
+ });
+
+ it("offers settings, not a retry, when docs were skipped, worded by the host", () => {
+ render(
+ <GenerationProgress
+ job={{
+ id: "j1",
+ status: "completed",
+ total_pages: 0,
+ completed_pages: 0,
+ failed_pages: 0,
+ config: { provider_issue: { kind: "docs_skipped", message: "English text" } },
+ }}
+ log={[]}
+ elapsed={10_000}
+ actualCost={null}
+ stuckPending={false}
+ cancelling={false}
+ onCancel={vi.fn()}
+ onRetry={vi.fn()}
+ onDismiss={vi.fn()}
+ settingsHref="/s"
+ formatIssue={(issue) => `localized ${issue.kind}`}
+ />,
+ );
+ expect(screen.getByText("Documentation was not updated.")).toBeTruthy();
+ expect(screen.getByText("localized docs_skipped")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: /Retry/ })).toBeNull();
+ expect(screen.getByRole("button", { name: /Dismiss/ })).toBeTruthy();
+ expect(screen.getByRole("link", { name: /Provider settings/ })).toBeTruthy();
+ });
+
+ it("keeps a clean run quiet", () => {
+ render(
+ <GenerationProgress
+ job={{ id: "j1", status: "completed", total_pages: 5, completed_pages: 5, failed_pages: 0 }}
+ log={[]}
+ elapsed={10_000}
+ actualCost={null}
+ stuckPending={false}
+ cancelling={false}
+ onCancel={vi.fn()}
+ onDismiss={vi.fn()}
+ />,
+ );
+ expect(screen.getByText("Generation complete")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: /Dismiss/ })).toBeNull();
+ });
+
it("tints warning log lines", () => {
// jsdom has no scrollIntoView; the JobLog autoscroll calls it on mount.
window.HTMLElement.prototype.scrollIntoView = vi.fn();
diff --git a/packages/ui/src/dashboard/active-job-banner.tsx b/packages/ui/src/dashboard/active-job-banner.tsx
index 522909a31..633f60688 100644
--- a/packages/ui/src/dashboard/active-job-banner.tsx
+++ b/packages/ui/src/dashboard/active-job-banner.tsx
@@ -1,10 +1,11 @@
"use client";
-import { CheckCircle, XCircle, ExternalLink } from "lucide-react";
+import { AlertTriangle, CheckCircle, XCircle, ExternalLink, Settings, X } from "lucide-react";
import { Spinner } from "../ui/spinner";
import { Progress } from "../ui/progress";
import { formatNumber, formatRelativeTime } from "../lib/format";
import type { Job } from "@repowise-dev/types/jobs";
+import { jobOutcome, providerIssue, type ProviderIssue } from "../jobs/job-outcome";
export interface ActiveJobBannerProps {
/**
@@ -19,21 +20,55 @@ export interface ActiveJobBannerProps {
* If omitted, the link is suppressed.
*/
detailsHref?: string;
+ /** Where the repo's provider is set up; linked when a failure or warning
+ * is the provider's. */
+ settingsHref?: string;
+ /** Hides a failed or warning banner; a clean finish fades on its own. */
+ onDismiss?: () => void;
+ /** Words a provider issue in the host's language; defaults to its message. */
+ formatIssue?: (issue: ProviderIssue) => string;
+ labels?: Partial<ActiveJobBannerLabels>;
}
+export interface ActiveJobBannerLabels {
+ finishedWithProblems: (action: string) => string;
+ pagesFailed: (count: number) => string;
+ providerSettings: string;
+ dismiss: string;
+}
+
+export const DEFAULT_ACTIVE_JOB_BANNER_LABELS: ActiveJobBannerLabels = {
+ finishedWithProblems: (action) => `${action} finished with problems`,
+ pagesFailed: (count) => `${formatNumber(count)} pages not written`,
+ providerSettings: "Provider settings",
+ dismiss: "Dismiss",
+};
+
const PHASE_LABELS: Record<number, string> = {
0: "Indexing",
1: "Analysing",
2: "Generating docs",
};
-export function ActiveJobBanner({ job, detailsHref }: ActiveJobBannerProps) {
+export function ActiveJobBanner({
+ job,
+ detailsHref,
+ settingsHref,
+ onDismiss,
+ formatIssue = (issue) => issue.message,
+ labels,
+}: ActiveJobBannerProps) {
if (!job) return null;
if (job.status === "pending") return null;
+ const l = { ...DEFAULT_ACTIVE_JOB_BANNER_LABELS, ...labels };
+ const outcome = jobOutcome(job);
const isRunning = job.status === "running";
- const isDone = job.status === "completed";
- const isFailed = job.status === "failed";
+ const isDone = outcome === "completed";
+ const isWarning = outcome === "warning";
+ const isFailed = outcome === "failed";
+ const issue = providerIssue(job);
+ const isProblem = isFailed || isWarning;
const progress =
job.total_pages > 0
@@ -45,15 +80,18 @@ export function ActiveJobBanner({ job, detailsHref }: ActiveJobBannerProps) {
const phaseLabel = PHASE_LABELS[job.current_level ?? 0] ?? "Processing";
return (
- <div className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 sm:px-[var(--page-pad)]">
+ <div
+ // A failure interrupts; a warning is announced politely.
+ role={isFailed ? "alert" : isWarning ? "status" : undefined}
+ className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 sm:px-[var(--page-pad)]"
+ >
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
- {isRunning && <Spinner size="sm" className="text-[var(--color-text-tertiary)]" />}
- {isDone && <CheckCircle className="h-3.5 w-3.5 text-[var(--color-success)] shrink-0" />}
- {isFailed && <XCircle className="h-3.5 w-3.5 text-[var(--color-error)] shrink-0" />}
+ {isRunning ? <Spinner size="sm" className="text-[var(--color-text-tertiary)]" /> : <OutcomeIcon outcome={outcome} />}
<span className="text-xs text-[var(--color-text-secondary)]">
{isRunning && `${label} · ${phaseLabel}…`}
{isDone && `${label} complete`}
+ {isWarning && l.finishedWithProblems(label)}
{isFailed && `${label} failed`}
</span>
@@ -74,9 +112,19 @@ export function ActiveJobBanner({ job, detailsHref }: ActiveJobBannerProps) {
{job.finished_at && <> · {formatRelativeTime(job.finished_at)}</>}
</>
)}
- {isFailed && (job.error_message ?? "Unknown error")}
+ {isWarning && (issue ? formatIssue(issue) : l.pagesFailed(job.failed_pages))}
+ {isFailed && (issue ? formatIssue(issue) : (job.error_message ?? "Unknown error"))}
</span>
+ {isProblem && issue && settingsHref && (
+ <a
+ href={settingsHref}
+ className="text-[10px] text-[var(--color-accent-primary)] hover:underline flex items-center gap-0.5 shrink-0"
+ >
+ <Settings className="h-2.5 w-2.5" /> {l.providerSettings}
+ </a>
+ )}
+
{isDone && job.completed_pages > 0 && detailsHref && (
<a
href={detailsHref}
@@ -85,7 +133,35 @@ export function ActiveJobBanner({ job, detailsHref }: ActiveJobBannerProps) {
Details <ExternalLink className="h-2.5 w-2.5" />
</a>
)}
+
+ {isProblem && onDismiss && <DismissButton label={l.dismiss} onDismiss={onDismiss} />}
</div>
</div>
);
}
+
+function OutcomeIcon({ outcome }: { outcome: ReturnType<typeof jobOutcome> }) {
+ if (outcome === "completed") {
+ return <CheckCircle className="h-3.5 w-3.5 text-[var(--color-success)] shrink-0" />;
+ }
+ if (outcome === "warning") {
+ return <AlertTriangle className="h-3.5 w-3.5 text-[var(--color-warning)] shrink-0" />;
+ }
+ if (outcome === "failed") {
+ return <XCircle className="h-3.5 w-3.5 text-[var(--color-error)] shrink-0" />;
+ }
+ return null;
+}
+
+function DismissButton({ label, onDismiss }: { label: string; onDismiss: () => void }) {
+ return (
+ <button
+ type="button"
+ onClick={onDismiss}
+ aria-label={label}
+ className="ml-auto rounded p-0.5 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent-primary)]"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ );
+}
diff --git a/packages/ui/src/dashboard/quick-actions.tsx b/packages/ui/src/dashboard/quick-actions.tsx
index 5d20925a5..e73b8ac3f 100644
--- a/packages/ui/src/dashboard/quick-actions.tsx
+++ b/packages/ui/src/dashboard/quick-actions.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, useState, type ReactNode, type ComponentType } from "react";
+import { useEffect, useMemo, useState, type ReactNode, type ComponentType } from "react";
import { RefreshCw, Trash2, AlertTriangle, Zap, MoreHorizontal } from "lucide-react";
import { Button } from "../ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
@@ -108,6 +108,11 @@ export interface QuickActionsProps {
* the same weight made the destructive one as easy to hit as the safe one.
*/
variant?: "row" | "header";
+ /** Open an action as if its button were clicked, confirm step included (a
+ * retry after a failure). The shell calls `onConfirmRequestHandled` once
+ * it has, so the host can clear the request. */
+ confirmRequest?: QuickActionKey | null;
+ onConfirmRequestHandled?: () => void;
}
export function QuickActions({
@@ -121,12 +126,23 @@ export function QuickActions({
costPer1k,
activeJobSlot,
variant = "row",
+ confirmRequest,
+ onConfirmRequestHandled,
}: QuickActionsProps) {
const [internalLoading, setInternalLoading] = useState<QuickActionKey | null>(null);
const [pendingAction, setPendingAction] = useState<QuickActionDef | null>(null);
const [menuOpen, setMenuOpen] = useState(false);
const loading = loadingKey !== undefined ? loadingKey : internalLoading;
+ useEffect(() => {
+ if (!confirmRequest) return;
+ const action = actions.find((a) => a.key === confirmRequest);
+ onConfirmRequestHandled?.();
+ if (action) handleClick(action);
+ // Fires per request; `handleClick` is recreated every render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [confirmRequest]);
+
const estimate = useMemo(() => {
if (!pendingAction || pendingAction.key === "dead-code" || pageCount <= 0 || !costPer1k) {
return null;
diff --git a/packages/ui/src/jobs/generation-progress.tsx b/packages/ui/src/jobs/generation-progress.tsx
index 1ec904938..2da7842e6 100644
--- a/packages/ui/src/jobs/generation-progress.tsx
+++ b/packages/ui/src/jobs/generation-progress.tsx
@@ -8,6 +8,7 @@ import { ActivityDot } from "../ui/activity-dot";
import { Button } from "../ui/button";
import { JobLog, type JobLogEntry } from "./job-log";
import { formatTokens, formatNumber } from "../lib/format";
+import { jobOutcome, providerIssue, type ProviderIssue } from "./job-outcome";
/** Subset of the Job shape this presentational shell renders. */
export interface GenerationProgressJob {
@@ -40,8 +41,38 @@ export interface GenerationProgressProps {
onRetry?: () => void;
/** Where provider/API-key settings live; offered as a failure recovery path. */
settingsHref?: string;
+ /** Clears a finished panel. Without it a failure would vanish unread. */
+ onDismiss?: () => void;
+ /** Words a provider issue in the host's language; defaults to its message. */
+ formatIssue?: (issue: ProviderIssue) => string;
+ labels?: Partial<GenerationProgressLabels>;
}
+export interface GenerationProgressLabels {
+ /** Heading for a run that completed but lost pages or skipped docs. */
+ warningTitle: string;
+ /** No page was written; every one fell back to a placeholder. */
+ noPagesWritten: string;
+ somePagesFailed: (failed: number, total: number) => string;
+ docsSkipped: string;
+ retry: string;
+ startAgain: string;
+ providerSettings: string;
+ dismiss: string;
+}
+
+export const DEFAULT_GENERATION_PROGRESS_LABELS: GenerationProgressLabels = {
+ warningTitle: "Finished with problems",
+ noPagesWritten: "No documentation pages were written.",
+ somePagesFailed: (failed, total) =>
+ `${formatNumber(failed)} of ${formatNumber(total)} pages could not be written. Run it again to retry them.`,
+ docsSkipped: "Documentation was not updated.",
+ retry: "Retry",
+ startAgain: "Start again",
+ providerSettings: "Provider settings",
+ dismiss: "Dismiss",
+};
+
const PHASE_LABELS: Record<number, string> = {
0: "Indexing",
1: "Analysing",
@@ -65,7 +96,11 @@ export function GenerationProgress({
phase,
onRetry,
settingsHref,
+ onDismiss,
+ formatIssue = (issue) => issue.message,
+ labels,
}: GenerationProgressProps) {
+ const l = { ...DEFAULT_GENERATION_PROGRESS_LABELS, ...labels };
const rawProgress = job?.total_pages && job.total_pages > 0
? Math.round((job.completed_pages / job.total_pages) * 100)
: 0;
@@ -77,9 +112,17 @@ export function GenerationProgress({
const isPending = job?.status === "pending";
const isRunning = job?.status === "running";
const isInflight = isPending || isRunning;
- const isDone = job?.status === "completed";
+ const outcome = jobOutcome(job);
+ const isDone = outcome === "completed";
+ const isWarning = outcome === "warning";
+ const issue = isWarning || job?.status === "failed" ? providerIssue(job) : null;
+ const failedPages = job?.failed_pages ?? 0;
const isFailed = job?.status === "failed";
const isCancelled = job?.status === "cancelled";
+ // A failure may be the provider's; a warning only offers it when it was.
+ const showSettings = isFailed || issue !== null;
+ // Rerunning only helps a warning that lost pages; skipped docs need setup.
+ const showRetry = Boolean(onRetry) && (isFailed || isCancelled || failedPages > 0);
const phaseLabel = phase
? humanizePhase(phase)
: job?.current_level == null
@@ -91,6 +134,7 @@ export function GenerationProgress({
<div className="flex items-center gap-2">
{isInflight && <Spinner className="text-[var(--color-model)]" />}
{isDone && <CheckCircle className="h-4 w-4 text-[var(--color-fresh)] shrink-0" />}
+ {isWarning && <AlertTriangle className="h-4 w-4 text-[var(--color-warning)] shrink-0" />}
{isFailed && <XCircle className="h-4 w-4 text-[var(--color-outdated)] shrink-0" />}
{isCancelled && <Ban className="h-4 w-4 text-[var(--color-text-tertiary)] shrink-0" />}
@@ -98,6 +142,7 @@ export function GenerationProgress({
{isPending && "Queued — waiting for worker…"}
{isRunning && `${phaseLabel}…`}
{isDone && "Generation complete"}
+ {isWarning && l.warningTitle}
{isFailed && "Generation failed"}
{isCancelled && "Cancelled"}
</span>
@@ -139,6 +184,7 @@ export function GenerationProgress({
value={progress}
{...(isFailed ? { indicatorClassName: "bg-[var(--color-outdated)]" } : {})}
{...(isCancelled ? { indicatorClassName: "bg-[var(--color-text-tertiary)]" } : {})}
+ {...(isWarning ? { indicatorClassName: "bg-[var(--color-warning)]" } : {})}
/>
<div className="flex justify-between text-xs text-[var(--color-text-tertiary)]">
<span>
@@ -166,7 +212,28 @@ export function GenerationProgress({
</div>
)}
- {isDone && job && (
+ {isWarning && job && (
+ <div
+ role="status"
+ className="flex items-start gap-2 rounded-md border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-3 py-2 text-xs text-[var(--color-text-primary)]"
+ >
+ <AlertTriangle className="h-4 w-4 shrink-0 mt-0.5 text-[var(--color-warning)]" />
+ <div className="flex-1 space-y-0.5">
+ <p className="font-medium">
+ {failedPages > 0
+ ? job.completed_pages > 0
+ ? l.somePagesFailed(failedPages, job.total_pages)
+ : l.noPagesWritten
+ : l.docsSkipped}
+ </p>
+ {issue && (
+ <p className="text-[var(--color-text-secondary)] break-words">{formatIssue(issue)}</p>
+ )}
+ </div>
+ </div>
+ )}
+
+ {(isDone || isWarning) && job && (
<div className="grid grid-cols-3 gap-2">
<div className="rounded border border-[var(--color-border-default)] p-2 text-center">
<p className="text-lg font-semibold text-[var(--color-text-primary)]">
@@ -189,8 +256,10 @@ export function GenerationProgress({
</div>
)}
- {isFailed && job?.error_message && (
- <p className="text-sm text-[var(--color-outdated)] break-words">{job.error_message}</p>
+ {isFailed && (issue || job?.error_message) && (
+ <p className="text-sm text-[var(--color-outdated)] break-words">
+ {issue ? formatIssue(issue) : job?.error_message}
+ </p>
)}
{isCancelled && (
@@ -200,22 +269,29 @@ export function GenerationProgress({
</p>
)}
- {(isFailed || isCancelled) && (onRetry || (isFailed && settingsHref)) && (
+ {(isFailed || isCancelled || isWarning) &&
+ (showRetry || onDismiss || (showSettings && settingsHref)) && (
<div className="flex flex-wrap gap-2">
- {onRetry && (
+ {showRetry && (
<Button size="sm" variant="outline" onClick={onRetry} className="h-7 px-2 text-xs">
<RotateCw className="h-3.5 w-3.5 mr-1" />
- {isCancelled ? "Start again" : "Retry"}
+ {isCancelled ? l.startAgain : l.retry}
</Button>
)}
- {isFailed && settingsHref && (
+ {showSettings && settingsHref && (
<Button size="sm" variant="ghost" asChild className="h-7 px-2 text-xs">
<a href={settingsHref}>
<Settings className="h-3.5 w-3.5 mr-1" />
- Provider settings
+ {l.providerSettings}
</a>
</Button>
)}
+ {onDismiss && (
+ <Button size="sm" variant="ghost" onClick={onDismiss} className="h-7 px-2 text-xs">
+ <X className="h-3.5 w-3.5 mr-1" />
+ {l.dismiss}
+ </Button>
+ )}
</div>
)}
diff --git a/packages/ui/src/jobs/index.ts b/packages/ui/src/jobs/index.ts
index 359f4a704..6fbb42e24 100644
--- a/packages/ui/src/jobs/index.ts
+++ b/packages/ui/src/jobs/index.ts
@@ -1,2 +1,3 @@
export * from "./job-log";
export * from "./generation-progress";
+export * from "./job-outcome";
diff --git a/packages/ui/src/jobs/job-outcome.ts b/packages/ui/src/jobs/job-outcome.ts
new file mode 100644
index 000000000..ad0d1a3ae
--- /dev/null
+++ b/packages/ui/src/jobs/job-outcome.ts
@@ -0,0 +1,55 @@
+/**
+ * How a finished job turned out, beyond its status. A job can complete while
+ * its provider rejected every page (each falls back to a placeholder), or
+ * while docs were skipped because no provider could be loaded. The server
+ * records that as `config.provider_issue`; these helpers read it.
+ */
+
+export interface ProviderIssue {
+ /** "auth" | "rate_limit" | "unreachable" | "model_not_found" | "not_found" |
+ * "docs_skipped"; a client words known kinds itself and shows `message`
+ * for any other. */
+ kind: string;
+ /** Plain English hint saying what went wrong and what to do. */
+ message: string;
+ /** Values the message names, for a client that words it itself. */
+ provider?: string | undefined;
+ model?: string | undefined;
+ target?: string | undefined;
+}
+
+interface OutcomeJob {
+ status: string;
+ failed_pages?: number;
+ config?: Record<string, unknown> | null;
+}
+
+export type JobOutcome = "completed" | "warning" | "failed" | "cancelled";
+
+export function providerIssue(job: OutcomeJob | null | undefined): ProviderIssue | null {
+ const raw = job?.config?.provider_issue;
+ if (!raw || typeof raw !== "object") return null;
+ const { kind, message, provider, model, target } = raw as Record<string, unknown>;
+ if (typeof message !== "string" || !message) return null;
+ const text = (v: unknown) => (typeof v === "string" && v ? v : undefined);
+ return {
+ kind: text(kind) ?? "",
+ message,
+ provider: text(provider),
+ model: text(model),
+ target: text(target),
+ };
+}
+
+/** The terminal outcome, or `null` while the job is still pending or running. */
+export function jobOutcome(job: OutcomeJob | null | undefined): JobOutcome | null {
+ switch (job?.status) {
+ case "completed":
+ return (job.failed_pages ?? 0) > 0 || providerIssue(job) ? "warning" : "completed";
+ case "failed":
+ case "cancelled":
+ return job.status;
+ default:
+ return null;
+ }
+}
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 4442a3558..9866c87b0 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -946,7 +946,33 @@
"cancelled": "Job cancelled",
"cancelledDescription": "The pipeline was stopped before completion.",
"cancelFailed": "Couldn't cancel job",
- "progressCount": "{completed}/{total} pages"
+ "progressCount": "{completed}/{total} pages",
+ "completedWithProblems": "Finished with problems{name}",
+ "pagesFailed": "{count} pages could not be written.",
+ "progress": {
+ "warningTitle": "Finished with problems",
+ "noPagesWritten": "No documentation pages were written.",
+ "somePagesFailed": "{failed} of {total} pages could not be written. Run it again to retry them.",
+ "docsSkipped": "Documentation was not updated.",
+ "retry": "Retry",
+ "startAgain": "Start again",
+ "providerSettings": "Provider settings",
+ "dismiss": "Dismiss"
+ },
+ "issue": {
+ "auth": "API key rejected by {provider}. Update it in Settings.",
+ "rate_limit": "{provider} is rate limiting requests. Wait a few minutes, then run it again.",
+ "model_not_found": "Model {model} was not found at {provider}. Choose another model in Settings.",
+ "not_found": "Model {model} or the base URL path was not found at {provider}. Check both in Settings.",
+ "unreachable": "Could not reach {target}. Is the server running and the base URL correct?",
+ "docs_skipped": "A model provider is configured but could not be loaded, so documentation was not updated. Check it in Settings."
+ },
+ "banner": {
+ "finishedWithProblems": "{action} finished with problems",
+ "pagesFailed": "{count} pages not written",
+ "providerSettings": "Provider settings",
+ "dismiss": "Dismiss"
+ }
},
"overview": {
"ask": {
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index d9c0be4cd..d0719eb26 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -946,7 +946,33 @@
"cancelled": "任务已取消",
"cancelledDescription": "流水线在完成之前就被停止了。",
"cancelFailed": "无法取消任务",
- "progressCount": "{completed}/{total} 个页面"
+ "progressCount": "{completed}/{total} 个页面",
+ "completedWithProblems": "已完成,但存在问题{name}",
+ "pagesFailed": "有 {count} 个页面未能写入。",
+ "progress": {
+ "warningTitle": "已完成,但存在问题",
+ "noPagesWritten": "没有写入任何文档页面。",
+ "somePagesFailed": "{total} 个页面中有 {failed} 个未能写入。再次运行即可重试这些页面。",
+ "docsSkipped": "文档未更新。",
+ "retry": "重试",
+ "startAgain": "重新开始",
+ "providerSettings": "模型提供方设置",
+ "dismiss": "关闭"
+ },
+ "issue": {
+ "auth": "{provider} 拒绝了 API 密钥。请在设置中更新。",
+ "rate_limit": "{provider} 正在限制请求频率。请等待几分钟后再运行。",
+ "model_not_found": "在 {provider} 上找不到模型 {model}。请在设置中选择其他模型。",
+ "not_found": "在 {provider} 上找不到模型 {model} 或基础 URL 路径。请在设置中检查这两项。",
+ "unreachable": "无法连接到 {target}。请确认服务器正在运行且基础 URL 正确。",
+ "docs_skipped": "已配置模型提供方,但无法加载,因此文档未更新。请在设置中检查。"
+ },
+ "banner": {
+ "finishedWithProblems": "{action}已完成,但存在问题",
+ "pagesFailed": "{count} 个页面未写入",
+ "providerSettings": "模型提供方设置",
+ "dismiss": "关闭"
+ }
},
"overview": {
"ask": {
diff --git a/packages/web/src/components/dashboard/active-job-banner-wrapper.test.tsx b/packages/web/src/components/dashboard/active-job-banner-wrapper.test.tsx
new file mode 100644
index 000000000..6447ac7bf
--- /dev/null
+++ b/packages/web/src/components/dashboard/active-job-banner-wrapper.test.tsx
@@ -0,0 +1,65 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ActiveJobBannerWrapper } from "./active-job-banner-wrapper";
+
+const mocks = vi.hoisted(() => ({ jobs: [] as Record<string, unknown>[] }));
+
+vi.mock("swr", () => ({ default: () => ({ data: mocks.jobs }) }));
+
+const HOUR = 60 * 60_000;
+
+function failedJob(finishedAgoMs: number) {
+ return {
+ id: "j1",
+ repository_id: "r1",
+ status: "failed",
+ total_pages: 0,
+ completed_pages: 0,
+ failed_pages: 0,
+ current_level: 0,
+ error_message: "API key rejected by openai. Update it in Settings.",
+ config: {
+ mode: "sync",
+ provider_issue: { kind: "auth", message: "API key rejected by openai.", provider: "openai" },
+ },
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ started_at: "2026-01-01T00:00:00Z",
+ finished_at: new Date(Date.now() - finishedAgoMs).toISOString(),
+ };
+}
+
+describe("ActiveJobBannerWrapper", () => {
+ beforeEach(() => window.localStorage.clear());
+ afterEach(cleanup);
+
+ it("keeps a failure up for a day, past the one minute a clean finish gets", () => {
+ mocks.jobs = [failedJob(2 * HOUR)];
+ render(<ActiveJobBannerWrapper repoId="r1" />);
+ expect(screen.getByRole("alert").textContent).toContain("Sync failed");
+ expect(screen.getByRole("link", { name: /Provider settings/ }).getAttribute("href")).toBe(
+ "/repos/r1/settings#provider",
+ );
+ });
+
+ it("drops a failure older than a day", () => {
+ mocks.jobs = [failedJob(25 * HOUR)];
+ render(<ActiveJobBannerWrapper repoId="r1" />);
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+
+ it("remembers a dismissal across reloads, per repo", async () => {
+ mocks.jobs = [failedJob(HOUR)];
+ const first = render(<ActiveJobBannerWrapper repoId="r1" />);
+ await act(async () => fireEvent.click(screen.getByRole("button", { name: "Dismiss" })));
+ expect(screen.queryByRole("alert")).toBeNull();
+ first.unmount();
+
+ render(<ActiveJobBannerWrapper repoId="r1" />);
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(window.localStorage.getItem("repowise:job-banner-dismissed:r1")).toBe("j1");
+ });
+});
diff --git a/packages/web/src/components/dashboard/active-job-banner-wrapper.tsx b/packages/web/src/components/dashboard/active-job-banner-wrapper.tsx
index afa8b02f9..81d06a3a3 100644
--- a/packages/web/src/components/dashboard/active-job-banner-wrapper.tsx
+++ b/packages/web/src/components/dashboard/active-job-banner-wrapper.tsx
@@ -1,15 +1,55 @@
"use client";
+import { useEffect, useMemo, useState } from "react";
import useSWR from "swr";
-import { ActiveJobBanner as ActiveJobBannerShell } from "@repowise-dev/ui/dashboard/active-job-banner";
+import { useTranslations } from "next-intl";
+import {
+ ActiveJobBanner as ActiveJobBannerShell,
+ type ActiveJobBannerLabels,
+} from "@repowise-dev/ui/dashboard/active-job-banner";
+import { jobOutcome } from "@repowise-dev/ui/jobs";
import { listJobs } from "@/lib/api/jobs";
+import { providerSetupHref } from "@/lib/utils/page-href";
+import { useIssueText } from "@/lib/jobs/use-issue-text";
+import { formatNumber } from "@repowise-dev/ui/lib/format";
import type { Job } from "@repowise-dev/types/jobs";
interface Props {
repoId: string;
}
+/** A clean finish is an acknowledgement; a problem stays until it is read. */
+const DONE_WINDOW_MS = 60_000;
+const PROBLEM_WINDOW_MS = 24 * 60 * 60_000;
+
+/** Per-repo storage key holding the id of the job whose banner was dismissed,
+ * so a dismissal survives reloads. Storage can be unavailable (private mode,
+ * blocked site data); dismissal then lasts only for this page. */
+const dismissedKey = (repoId: string) => `repowise:job-banner-dismissed:${repoId}`;
+
+function readDismissed(repoId: string): string | null {
+ try {
+ return window.localStorage.getItem(dismissedKey(repoId));
+ } catch {
+ // Storage unavailable: nothing was remembered, so show the banner.
+ return null;
+ }
+}
+
+function writeDismissed(repoId: string, jobId: string): void {
+ try {
+ window.localStorage.setItem(dismissedKey(repoId), jobId);
+ } catch {
+ // Storage unavailable: the in-memory dismissal still hides it for now.
+ }
+}
+
export function ActiveJobBannerWrapper({ repoId }: Props) {
+ const t = useTranslations("jobs.banner");
+ const [dismissedId, setDismissedId] = useState<string | null>(null);
+ const issueText = useIssueText();
+ // Read after mount: the server render has no storage to agree with.
+ useEffect(() => setDismissedId(readDismissed(repoId)), [repoId]);
const { data: jobs } = useSWR<Job[]>(
`/api/jobs?repo_id=${repoId}&limit=1`,
() => listJobs({ repo_id: repoId, limit: 1 }),
@@ -21,19 +61,38 @@ export function ActiveJobBannerWrapper({ repoId }: Props) {
},
},
);
+ const labels = useMemo<Partial<ActiveJobBannerLabels>>(
+ () => ({
+ finishedWithProblems: (action) => t("finishedWithProblems", { action }),
+ pagesFailed: (count) => t("pagesFailed", { count: formatNumber(count) }),
+ providerSettings: t("providerSettings"),
+ dismiss: t("dismiss"),
+ }),
+ [t],
+ );
const job = jobs?.[0] ?? null;
- if (!job) return null;
+ if (!job || job.id === dismissedId) return null;
- // Drop completed/failed banners after a 60s freshness window — matches the
- // pre-extraction inline behaviour.
- if (job.status !== "running" && job.status !== "completed" && job.status !== "failed") {
- return null;
- }
- if (job.status !== "running") {
+ const outcome = job.status === "running" ? "running" : jobOutcome(job);
+ if (outcome === null || outcome === "cancelled") return null;
+ if (outcome !== "running") {
const finishedAt = job.finished_at ? new Date(job.finished_at).getTime() : 0;
- if (Date.now() - finishedAt > 60_000) return null;
+ const visibleFor = outcome === "completed" ? DONE_WINDOW_MS : PROBLEM_WINDOW_MS;
+ if (Date.now() - finishedAt > visibleFor) return null;
}
- return <ActiveJobBannerShell job={job} detailsHref={`/repos/${repoId}/overview`} />;
+ return (
+ <ActiveJobBannerShell
+ job={job}
+ detailsHref={`/repos/${repoId}/overview`}
+ settingsHref={providerSetupHref(repoId)}
+ onDismiss={() => {
+ writeDismissed(repoId, job.id);
+ setDismissedId(job.id);
+ }}
+ formatIssue={issueText}
+ labels={labels}
+ />
+ );
}
diff --git a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx b/packages/web/src/components/dashboard/quick-actions-wrapper.tsx
index 1b3951710..75b6a35f1 100644
--- a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx
+++ b/packages/web/src/components/dashboard/quick-actions-wrapper.tsx
@@ -13,6 +13,8 @@ import { syncRepo, fullResyncRepo } from "@/lib/api/repos";
import { listJobs } from "@/lib/api/jobs";
import { analyzeDeadCode } from "@/lib/api/dead-code";
import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";
+import { useWatchedJob } from "@/lib/hooks/use-watched-job";
+import type { JobOutcome } from "@repowise-dev/ui/jobs";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
import { useTranslations } from "next-intl";
@@ -34,6 +36,22 @@ function labelFor(key: QuickActionKey): string {
return DEFAULT_QUICK_ACTIONS.find((a) => a.key === key)?.label ?? key;
}
+/** The endpoint each action starts its job through. */
+const LAUNCH: Record<QuickActionKey, (repoId: string) => Promise<{ job_id: string }>> = {
+ sync: syncRepo,
+ resync: fullResyncRepo,
+ "dead-code": analyzeDeadCode,
+};
+
+/** The repo's running or queued job, if any. */
+async function findInflightJob(repoId: string): Promise<{ id: string } | undefined> {
+ const [running, pending] = await Promise.all([
+ listJobs({ repo_id: repoId, status: "running", limit: 1 }),
+ listJobs({ repo_id: repoId, status: "pending", limit: 1 }),
+ ]);
+ return running[0] ?? pending[0];
+}
+
export function QuickActionsWrapper({
repoId,
repoName,
@@ -55,23 +73,20 @@ export function QuickActionsWrapper({
: key === "dead-code"
? t("quickActions.deadCode")
: labelFor(key);
- const [activeJobId, setActiveJobId] = useState<string | null>(null);
- // Which action started the job on screen, so its completion can be reported
- // and refreshed in its own terms rather than as a generic doc generation.
- const [activeKey, setActiveKey] = useState<QuickActionKey | null>(null);
+ // The job on screen and which action started it, so its completion is
+ // reported in its own terms and a retry re-runs the same action.
+ const { watched, watch: startWatching, watchIfIdle, settle, dismiss } =
+ useWatchedJob<QuickActionKey>();
+ // Set by a retry; the shell opens that action as if clicked.
+ const [confirmRequest, setConfirmRequest] = useState<QuickActionKey | null>(null);
// Hydrate from any in-flight job so refreshes don't lose progress visibility.
useEffect(() => {
let cancelled = false;
(async () => {
try {
- const [running, pending] = await Promise.all([
- listJobs({ repo_id: repoId, status: "running", limit: 1 }),
- listJobs({ repo_id: repoId, status: "pending", limit: 1 }),
- ]);
- if (cancelled) return;
- const inflight = running[0] ?? pending[0];
- if (inflight) setActiveJobId(inflight.id);
+ const inflight = await findInflightJob(repoId);
+ if (!cancelled && inflight) watchIfIdle(inflight.id);
} catch {
// best-effort
}
@@ -79,59 +94,45 @@ export function QuickActionsWrapper({
return () => {
cancelled = true;
};
- }, [repoId]);
-
- function startWatching(jobId: string, key: QuickActionKey | null) {
- setActiveJobId(jobId);
- setActiveKey(key);
- }
+ }, [repoId, watchIfIdle]);
- function handleJobDone(status: "completed" | "failed" | "cancelled") {
- const key = activeKey;
- setActiveJobId(null);
- setActiveKey(null);
+ function handleJobDone(outcome: JobOutcome) {
+ const key = watched?.action;
+ settle(outcome);
if (key === "dead-code") {
- if (status === "completed") toast.success(t("quickActions.deadCodeFinished"));
- else if (status === "failed") toast.error(t("quickActions.deadCodeFailed"));
+ if (outcome === "completed") toast.success(t("quickActions.deadCodeFinished"));
+ else if (outcome === "failed") toast.error(t("quickActions.deadCodeFailed"));
}
// This page is server-rendered: without a refresh the "Dead Exports" tile
// the scan exists to move keeps showing its pre-scan number, and the same
// goes for every stat a sync, re-index or bulk generate just changed.
- if (status === "completed") router.refresh();
+ if (outcome === "completed" || outcome === "warning") router.refresh();
+ }
+
+ function startedMessage(key: QuickActionKey): string {
+ const name = repoName ? ` — ${repoName}` : "";
+ if (key === "sync") return t("quickActions.syncStarted", { name });
+ if (key === "resync") return t("quickActions.resyncStarted", { name });
+ return t("quickActions.deadCodeStarted");
+ }
+
+ // A retry goes back through the action's own confirm step, which the shell
+ // renders once the panel is gone.
+ function requestRetry(key: QuickActionKey) {
+ dismiss();
+ setConfirmRequest(key);
}
async function handleAction(key: QuickActionKey) {
try {
- if (key === "sync") {
- const job = await syncRepo(repoId);
- startWatching(job.id, key);
- toast.info(
- t("quickActions.syncStarted", {
- name: repoName ? ` — ${repoName}` : "",
- }),
- );
- } else if (key === "resync") {
- const job = await fullResyncRepo(repoId);
- startWatching(job.id, key);
- toast.info(
- t("quickActions.resyncStarted", {
- name: repoName ? ` — ${repoName}` : "",
- }),
- );
- } else if (key === "dead-code") {
- const { job_id } = await analyzeDeadCode(repoId);
- startWatching(job_id, key);
- toast.info(t("quickActions.deadCodeStarted"));
- }
+ const { job_id } = await LAUNCH[key](repoId);
+ startWatching(job_id, key);
+ toast.info(startedMessage(key));
} catch (e) {
const msg = toFriendlyMessage(e);
if (/already in progress/i.test(msg)) {
try {
- const [running, pending] = await Promise.all([
- listJobs({ repo_id: repoId, status: "running", limit: 1 }),
- listJobs({ repo_id: repoId, status: "pending", limit: 1 }),
- ]);
- const inflight = running[0] ?? pending[0];
+ const inflight = await findInflightJob(repoId);
if (inflight) {
// Someone else's job: watch it, but do not claim it as this action.
startWatching(inflight.id, null);
@@ -148,15 +149,20 @@ export function QuickActionsWrapper({
}
}
- const activeSlot = activeJobId ? (
+ const retryAction = watched?.action;
+ const activeSlot = watched ? (
<GenerationProgressWrapper
- jobId={activeJobId}
+ // A fresh instance per job, so a retry reports its own outcome.
+ key={watched.id}
+ jobId={watched.id}
repoName={repoName}
// A dead-code scan runs the index-only pipeline, so the generic
// "Documentation updated - 0 pages generated" toast would describe it
// wrongly. It reports itself below instead.
- quiet={activeKey === "dead-code"}
+ quiet={retryAction === "dead-code"}
onDone={handleJobDone}
+ onRetry={retryAction ? () => requestRetry(retryAction) : undefined}
+ onDismiss={dismiss}
/>
) : null;
@@ -170,6 +176,8 @@ export function QuickActionsWrapper({
modelName={modelName}
costPer1k={costPer1k}
activeJobSlot={activeSlot}
+ confirmRequest={confirmRequest}
+ onConfirmRequestHandled={() => setConfirmRequest(null)}
variant={variant}
/>
);
diff --git a/packages/web/src/components/docs/bulk-generate-button.tsx b/packages/web/src/components/docs/bulk-generate-button.tsx
index 64e96be5e..6dd775ca8 100644
--- a/packages/web/src/components/docs/bulk-generate-button.tsx
+++ b/packages/web/src/components/docs/bulk-generate-button.tsx
@@ -61,8 +61,17 @@ export function BulkGenerateButton({
</DialogHeader>
{bulk.jobId != null && (
<GenerationProgressWrapper
+ key={bulk.jobId}
jobId={bulk.jobId}
- onDone={() => onGenerated?.()}
+ onDone={(outcome) => {
+ bulk.settle(outcome);
+ onGenerated?.();
+ }}
+ onRetry={() => {
+ bulk.clearJob();
+ bulk.open();
+ }}
+ onDismiss={bulk.clearJob}
/>
)}
</DialogContent>
diff --git a/packages/web/src/components/docs/page-generate-button.tsx b/packages/web/src/components/docs/page-generate-button.tsx
index 31dddfaf0..03c25cece 100644
--- a/packages/web/src/components/docs/page-generate-button.tsx
+++ b/packages/web/src/components/docs/page-generate-button.tsx
@@ -10,6 +10,7 @@ import {
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
import { isStubPage } from "@repowise-dev/ui/lib/page-types";
import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";
+import { useWatchedJob } from "@/lib/hooks/use-watched-job";
import { regeneratePage } from "@/lib/api/pages";
import { generateEstimate } from "@/lib/api/repos";
import { formatEstimateCost } from "@/lib/generate-format";
@@ -48,7 +49,8 @@ export function PageGenerateButton({
const [estimateLoading, setEstimateLoading] = useState(false);
const [estimateError, setEstimateError] = useState<string | null>(null);
const [launching, setLaunching] = useState(false);
- const [jobId, setJobId] = useState<string | null>(null);
+ const { watched, watch, settle, dismiss } = useWatchedJob<"page">();
+ const jobId = watched?.id ?? null;
// Cache estimates per cascade so toggling the choice back doesn't refetch the
// heavy /generate/estimate endpoint.
@@ -104,7 +106,7 @@ export function PageGenerateButton({
setLaunching(true);
try {
const res = await regeneratePage(page.id, { cascade, repoId });
- setJobId(res.job_id);
+ watch(res.job_id, "page");
setConfirmOpen(false);
} catch (e) {
toast.error(t("pageGenerate.failed"), {
@@ -125,12 +127,21 @@ export function PageGenerateButton({
onRegenerate={openConfirm}
isLoading={launching && !jobId}
isInProgress={jobId != null}
- onDialogClose={() => setJobId(null)}
+ onDialogClose={dismiss}
jobSlot={
jobId != null ? (
<GenerationProgressWrapper
+ key={jobId}
jobId={jobId}
- onDone={() => onGenerated?.()}
+ onDone={(outcome) => {
+ settle(outcome);
+ onGenerated?.();
+ }}
+ onRetry={() => {
+ dismiss();
+ openConfirm();
+ }}
+ onDismiss={dismiss}
/>
) : null
}
diff --git a/packages/web/src/components/jobs/generation-progress-wrapper.test.tsx b/packages/web/src/components/jobs/generation-progress-wrapper.test.tsx
new file mode 100644
index 000000000..53dc208d0
--- /dev/null
+++ b/packages/web/src/components/jobs/generation-progress-wrapper.test.tsx
@@ -0,0 +1,82 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { GenerationProgressWrapper } from "./generation-progress-wrapper";
+
+const mocks = vi.hoisted(() => ({
+ state: null as unknown as { job: Record<string, unknown>; isActive: boolean },
+ toast: { success: vi.fn(), warning: vi.fn(), error: vi.fn(), info: vi.fn() },
+}));
+
+vi.mock("sonner", () => ({ toast: mocks.toast }));
+vi.mock("@/lib/hooks/use-job", () => ({
+ useJob: () => ({ ...mocks.state, sse: { data: null }, messages: [], phase: null }),
+}));
+
+function job(overrides: Record<string, unknown>) {
+ return {
+ id: "j1",
+ repository_id: "r1",
+ status: "completed",
+ total_pages: 4,
+ completed_pages: 0,
+ failed_pages: 4,
+ error_message: null,
+ config: {
+ provider_issue: { kind: "auth", message: "API key rejected by openai. Update it in Settings." },
+ },
+ created_at: "2026-01-01T00:00:00Z",
+ started_at: "2026-01-01T00:00:00Z",
+ finished_at: "2026-01-01T00:01:00Z",
+ ...overrides,
+ };
+}
+
+describe("GenerationProgressWrapper", () => {
+ afterEach(cleanup);
+ beforeEach(() => {
+ Object.values(mocks.toast).forEach((fn) => fn.mockReset());
+ });
+
+ it("waits for the fetched job before settling, so the run summary is known", () => {
+ mocks.state = { job: job({}), isActive: true };
+ const onDone = vi.fn();
+
+ render(<GenerationProgressWrapper jobId="j1" onDone={onDone} />);
+
+ expect(onDone).not.toHaveBeenCalled();
+ expect(mocks.toast.success).not.toHaveBeenCalled();
+ });
+
+ it("reports a run that lost every page to a rejected key as a warning", () => {
+ mocks.state = { job: job({}), isActive: false };
+ const onDone = vi.fn();
+
+ render(<GenerationProgressWrapper jobId="j1" onDone={onDone} onDismiss={vi.fn()} />);
+
+ expect(onDone).toHaveBeenCalledWith("warning");
+ expect(mocks.toast.success).not.toHaveBeenCalled();
+ expect(mocks.toast.warning).toHaveBeenCalledWith(
+ "Finished with problems",
+ expect.objectContaining({ description: "API key rejected by openai. Update it in Settings." }),
+ );
+ expect(screen.getByRole("link", { name: /Provider settings/ }).getAttribute("href")).toBe(
+ "/repos/r1/settings#provider",
+ );
+ });
+
+ it("keeps a clean run a success", () => {
+ mocks.state = {
+ job: job({ completed_pages: 4, failed_pages: 0, config: {} }),
+ isActive: false,
+ };
+ const onDone = vi.fn();
+
+ render(<GenerationProgressWrapper jobId="j1" onDone={onDone} />);
+
+ expect(onDone).toHaveBeenCalledWith("completed");
+ expect(mocks.toast.success).toHaveBeenCalled();
+ });
+});
diff --git a/packages/web/src/components/jobs/generation-progress-wrapper.tsx b/packages/web/src/components/jobs/generation-progress-wrapper.tsx
index 187a2a867..d202557a4 100644
--- a/packages/web/src/components/jobs/generation-progress-wrapper.tsx
+++ b/packages/web/src/components/jobs/generation-progress-wrapper.tsx
@@ -2,22 +2,33 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
-import { GenerationProgress } from "@repowise-dev/ui/jobs/generation-progress";
+import {
+ GenerationProgress,
+ jobOutcome,
+ providerIssue,
+ type GenerationProgressLabels,
+ type JobOutcome,
+} from "@repowise-dev/ui/jobs";
import { useJob } from "@/lib/hooks/use-job";
import { cancelJob } from "@/lib/api/jobs";
import { formatNumber } from "@repowise-dev/ui/lib/format";
import { computeElapsedMs } from "@/lib/jobs/progress";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+import { providerSetupHref } from "@/lib/utils/page-href";
+import { useIssueText } from "@/lib/jobs/use-issue-text";
import { useTranslations } from "next-intl";
interface Props {
jobId: string;
repoName?: string;
- /** Fired once the job reaches a terminal state, with which one it reached
- * so the host can tell "finished" from "failed" without re-reading the job. */
- onDone?: (status: "completed" | "failed" | "cancelled") => void;
+ /** Fired once the job reaches a terminal state, with how it turned out so
+ * the host can tell "finished" from "finished with problems" or "failed"
+ * without re-reading the job. */
+ onDone?: (outcome: JobOutcome) => void;
/** Start a fresh run after a failure or cancellation. */
onRetry?: () => void;
+ /** Offered on a finished panel; hosts that keep failures on screen clear it here. */
+ onDismiss?: () => void;
/** Suppress the completion/failure toasts (when the host surface renders
* its own completion moment). */
quiet?: boolean;
@@ -25,9 +36,17 @@ interface Props {
const PENDING_STUCK_THRESHOLD_MS = 30_000;
-export function GenerationProgressWrapper({ jobId, repoName, onDone, onRetry, quiet }: Props) {
+export function GenerationProgressWrapper({
+ jobId,
+ repoName,
+ onDone,
+ onRetry,
+ onDismiss,
+ quiet,
+}: Props) {
const t = useTranslations("jobs");
- const { job, sse, messages, phase } = useJob(jobId);
+ const { job, sse, messages, phase, isActive } = useJob(jobId);
+ const issueText = useIssueText();
const [elapsed, setElapsed] = useState(0);
const [actualCost, setActualCost] = useState<number | null>(null);
const [cancelling, setCancelling] = useState(false);
@@ -50,47 +69,52 @@ export function GenerationProgressWrapper({ jobId, repoName, onDone, onRetry, qu
[messages],
);
+ // Settle on the fetched job, not the stream's "done" frame: only the fetch
+ // carries the run summary that says whether pages failed.
+ const outcome = isActive ? null : jobOutcome(job);
useEffect(() => {
- if (notifiedRef.current) return;
- if (job?.status === "completed") {
- notifiedRef.current = true;
- if (!quiet) {
- toast.success(
- t("completed", { name: repoName ? ` — ${repoName}` : "" }),
- {
- description: t("pagesGenerated", {
- count: formatNumber(job.completed_pages),
- }),
- },
- );
- }
- onDone?.("completed");
- } else if (job?.status === "failed") {
- notifiedRef.current = true;
- if (!quiet) {
- toast.error(t("failed"), {
- description: job.error_message ?? t("unknownError"),
+ if (notifiedRef.current || !outcome || !job) return;
+ notifiedRef.current = true;
+ const issue = providerIssue(job);
+ if (!quiet) {
+ if (outcome === "completed") {
+ toast.success(t("completed", { name: repoName ? ` — ${repoName}` : "" }), {
+ description: t("pagesGenerated", { count: formatNumber(job.completed_pages) }),
});
- }
- onDone?.("failed");
- } else if (job?.status === "cancelled") {
- notifiedRef.current = true;
- if (!quiet) {
- toast.info(t("cancelled"), {
- description: t("cancelledDescription"),
+ } else if (outcome === "warning") {
+ toast.warning(t("completedWithProblems", { name: repoName ? ` (${repoName})` : "" }), {
+ description: issue
+ ? issueText(issue)
+ : t("pagesFailed", { count: formatNumber(job.failed_pages) }),
});
+ } else if (outcome === "failed") {
+ toast.error(t("failed"), {
+ description: issue ? issueText(issue) : (job.error_message ?? t("unknownError")),
+ });
+ } else {
+ toast.info(t("cancelled"), { description: t("cancelledDescription") });
}
- onDone?.("cancelled");
}
- }, [
- job?.status,
- job?.completed_pages,
- job?.error_message,
- repoName,
- onDone,
- quiet,
- t,
- ]);
+ onDone?.(outcome);
+ }, [outcome, job, repoName, onDone, quiet, t, issueText]);
+
+ const labels = useMemo<Partial<GenerationProgressLabels>>(
+ () => ({
+ warningTitle: t("progress.warningTitle"),
+ noPagesWritten: t("progress.noPagesWritten"),
+ somePagesFailed: (failed, total) =>
+ t("progress.somePagesFailed", {
+ failed: formatNumber(failed),
+ total: formatNumber(total),
+ }),
+ docsSkipped: t("progress.docsSkipped"),
+ retry: t("progress.retry"),
+ startAgain: t("progress.startAgain"),
+ providerSettings: t("progress.providerSettings"),
+ dismiss: t("progress.dismiss"),
+ }),
+ [t],
+ );
const isPending = job?.status === "pending";
const stuckPending =
@@ -125,7 +149,10 @@ export function GenerationProgressWrapper({ jobId, repoName, onDone, onRetry, qu
onCancel={handleCancel}
phase={phase}
onRetry={onRetry}
- settingsHref="/settings"
+ onDismiss={onDismiss}
+ settingsHref={job ? providerSetupHref(job.repository_id) : undefined}
+ labels={labels}
+ formatIssue={issueText}
/>
);
}
diff --git a/packages/web/src/components/repos/operations-panel.test.tsx b/packages/web/src/components/repos/operations-panel.test.tsx
new file mode 100644
index 000000000..97b5eccc9
--- /dev/null
+++ b/packages/web/src/components/repos/operations-panel.test.tsx
@@ -0,0 +1,63 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { OperationsPanel } from "./operations-panel";
+
+const mocks = vi.hoisted(() => ({
+ jobs: {} as Record<string, Record<string, unknown>>,
+ syncRepo: vi.fn(),
+ toast: { success: vi.fn(), warning: vi.fn(), error: vi.fn(), info: vi.fn() },
+}));
+
+vi.mock("sonner", () => ({ toast: mocks.toast }));
+vi.mock("@/lib/api/repos", () => ({ syncRepo: mocks.syncRepo, fullResyncRepo: vi.fn() }));
+vi.mock("@/lib/hooks/use-job", () => ({
+ useJob: (id: string) => ({
+ job: mocks.jobs[id],
+ isActive: false,
+ sse: { data: null },
+ messages: [],
+ phase: null,
+ }),
+}));
+
+function job(id: string, status: string, extra: Record<string, unknown> = {}) {
+ return {
+ id,
+ repository_id: "r1",
+ status,
+ total_pages: 3,
+ completed_pages: status === "completed" ? 3 : 0,
+ failed_pages: 0,
+ error_message: status === "failed" ? "boom" : null,
+ config: {},
+ created_at: "2026-01-01T00:00:00Z",
+ started_at: "2026-01-01T00:00:00Z",
+ finished_at: "2026-01-01T00:01:00Z",
+ ...extra,
+ };
+}
+
+describe("OperationsPanel", () => {
+ afterEach(cleanup);
+
+ it("keeps a failed sync on screen, and a retry reports its own outcome once", async () => {
+ mocks.jobs = { j1: job("j1", "failed"), j2: job("j2", "completed") };
+ mocks.syncRepo.mockResolvedValueOnce({ job_id: "j1" }).mockResolvedValueOnce({ job_id: "j2" });
+
+ render(<OperationsPanel repoId="r1" repoName="demo" />);
+ await act(async () => fireEvent.click(screen.getByRole("button", { name: /Sync/ })));
+
+ expect(screen.getByText("Generation failed")).toBeTruthy();
+ expect(mocks.toast.error).toHaveBeenCalledTimes(1);
+
+ await act(async () => fireEvent.click(screen.getByRole("button", { name: /Retry/ })));
+
+ // A fresh panel for the new job: its clean finish toasts once and clears.
+ expect(mocks.toast.success).toHaveBeenCalledTimes(1);
+ expect(mocks.toast.error).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText("Generation failed")).toBeNull();
+ });
+});
diff --git a/packages/web/src/components/repos/operations-panel.tsx b/packages/web/src/components/repos/operations-panel.tsx
index 5440e6b7e..5bbacd870 100644
--- a/packages/web/src/components/repos/operations-panel.tsx
+++ b/packages/web/src/components/repos/operations-panel.tsx
@@ -14,6 +14,7 @@ import {
DialogFooter,
} from "@repowise-dev/ui/ui/dialog";
import { GenerationProgressWrapper as GenerationProgress } from "@/components/jobs/generation-progress-wrapper";
+import { useWatchedJob } from "@/lib/hooks/use-watched-job";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
import { useTranslations } from "next-intl";
@@ -25,15 +26,15 @@ interface Props {
export function OperationsPanel({ repoId, repoName }: Props) {
const t = useTranslations("repos");
const tc = useTranslations("common");
- const [activeJobId, setActiveJobId] = useState<string | null>(null);
+ const { watched, watch, settle, dismiss } = useWatchedJob<"sync" | "resync">();
const [confirmResync, setConfirmResync] = useState(false);
const [loading, setLoading] = useState<"sync" | "resync" | null>(null);
async function handleSync() {
setLoading("sync");
try {
- const job = await syncRepo(repoId);
- setActiveJobId(job.id);
+ const { job_id } = await syncRepo(repoId);
+ watch(job_id, "sync");
toast.info(t("ops.syncStarted", { name: repoName }));
} catch (e) {
toast.error(t("ops.syncFailed"), {
@@ -48,8 +49,8 @@ export function OperationsPanel({ repoId, repoName }: Props) {
setConfirmResync(false);
setLoading("resync");
try {
- const job = await fullResyncRepo(repoId);
- setActiveJobId(job.id);
+ const { job_id } = await fullResyncRepo(repoId);
+ watch(job_id, "resync");
toast.info(t("ops.resyncStarted", { name: repoName }));
} catch (e) {
toast.error(t("ops.resyncFailed"), {
@@ -60,10 +61,6 @@ export function OperationsPanel({ repoId, repoName }: Props) {
}
}
- function handleJobDone() {
- setActiveJobId(null);
- }
-
return (
<>
<Card>
@@ -73,16 +70,20 @@ export function OperationsPanel({ repoId, repoName }: Props) {
<CardContent id="operations-panel-content" className="space-y-4">
{/* Active job progress */}
- {activeJobId && (
+ {watched && (
<GenerationProgress
- jobId={activeJobId}
+ key={watched.id}
+ jobId={watched.id}
repoName={repoName}
- onDone={handleJobDone}
+ onDone={settle}
+ // A full re-index retry goes back through its confirmation.
+ onRetry={watched.action === "resync" ? () => setConfirmResync(true) : handleSync}
+ onDismiss={dismiss}
/>
)}
{/* Action buttons */}
- {!activeJobId && (
+ {!watched && (
<div className="flex gap-2">
<Button
variant="default"
diff --git a/packages/web/src/lib/hooks/use-bulk-generate.ts b/packages/web/src/lib/hooks/use-bulk-generate.ts
index 75981ffc2..4e6c3cab1 100644
--- a/packages/web/src/lib/hooks/use-bulk-generate.ts
+++ b/packages/web/src/lib/hooks/use-bulk-generate.ts
@@ -5,6 +5,7 @@ import { toast } from "sonner";
import type { RegenerateCascade } from "@repowise-dev/ui/wiki/regenerate-button";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
import { generateEstimate, generatePages } from "@/lib/api/repos";
+import { useWatchedJob } from "./use-watched-job";
import type { GenerateEstimate, GenerateSelection } from "@/lib/api/types";
// One bulk action: write every subsystem page a model has not written yet.
@@ -26,7 +27,8 @@ export function useBulkGenerate(repoId: string) {
const [estimateLoading, setEstimateLoading] = useState(false);
const [estimateError, setEstimateError] = useState<string | null>(null);
const [launching, setLaunching] = useState(false);
- const [jobId, setJobId] = useState<string | null>(null);
+ const { watched, watch, settle, dismiss: clearJob } = useWatchedJob<"bulk">();
+ const jobId = watched?.id ?? null;
// Estimate cache keyed by cascade so toggling the choice back to a value
// already priced doesn't refetch the heavy endpoint. The cascade the UI wants
@@ -83,16 +85,14 @@ export function useBulkGenerate(repoId: string) {
setLaunching(true);
try {
const res = await generatePages(repoId, { selection: SELECTION, cascade });
- setJobId(res.job_id);
+ watch(res.job_id, "bulk");
setConfirmOpen(false);
} catch (e) {
toast.error("Couldn't start generation", { description: toFriendlyMessage(e) });
} finally {
setLaunching(false);
}
- }, [repoId, cascade]);
-
- const clearJob = useCallback(() => setJobId(null), []);
+ }, [repoId, cascade, watch]);
const noProvider = !!estimate && estimate.provider.name == null;
@@ -109,6 +109,7 @@ export function useBulkGenerate(repoId: string) {
jobId,
open,
confirm,
+ settle,
clearJob,
};
}
diff --git a/packages/web/src/lib/hooks/use-watched-job.test.ts b/packages/web/src/lib/hooks/use-watched-job.test.ts
new file mode 100644
index 000000000..73055745a
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-watched-job.test.ts
@@ -0,0 +1,34 @@
+// @vitest-environment jsdom
+
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { useWatchedJob } from "./use-watched-job";
+
+describe("useWatchedJob", () => {
+ it.each(["warning", "failed"] as const)("keeps a %s run on screen until dismissed", (outcome) => {
+ const { result } = renderHook(() => useWatchedJob<"sync">());
+ act(() => result.current.watch("j1", "sync"));
+
+ act(() => result.current.settle(outcome));
+ expect(result.current.watched).toEqual({ id: "j1", action: "sync" });
+
+ act(() => result.current.dismiss());
+ expect(result.current.watched).toBeNull();
+ });
+
+ it.each(["completed", "cancelled"] as const)("clears a %s run", (outcome) => {
+ const { result } = renderHook(() => useWatchedJob<"sync">());
+ act(() => result.current.watch("j1", "sync"));
+
+ act(() => result.current.settle(outcome));
+ expect(result.current.watched).toBeNull();
+ });
+
+ it("does not let a late lookup replace a job the user just started", () => {
+ const { result } = renderHook(() => useWatchedJob<"sync">());
+ act(() => result.current.watch("mine", "sync"));
+
+ act(() => result.current.watchIfIdle("found-later"));
+ expect(result.current.watched?.id).toBe("mine");
+ });
+});
diff --git a/packages/web/src/lib/hooks/use-watched-job.ts b/packages/web/src/lib/hooks/use-watched-job.ts
new file mode 100644
index 000000000..18cada699
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-watched-job.ts
@@ -0,0 +1,31 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import type { JobOutcome } from "@repowise-dev/ui/jobs";
+
+export interface WatchedJob<K extends string> {
+ id: string;
+ /** The action that started it, or `null` for a job found already running. */
+ action: K | null;
+}
+
+/**
+ * The job a panel shows in place of its action buttons. A clean finish clears
+ * it; a failure or a finish with problems stays until dismissed, so its reason
+ * and the retry and settings actions are not lost to a toast.
+ */
+export function useWatchedJob<K extends string>() {
+ const [watched, setWatched] = useState<WatchedJob<K> | null>(null);
+ const watch = useCallback((id: string, action: K | null) => setWatched({ id, action }), []);
+ /** Watch a job found by a background lookup, unless the user started one
+ * meanwhile: a late lookup must not replace the job they just launched. */
+ const watchIfIdle = useCallback(
+ (id: string) => setWatched((current) => current ?? { id, action: null }),
+ [],
+ );
+ const dismiss = useCallback(() => setWatched(null), []);
+ const settle = useCallback((outcome: JobOutcome) => {
+ if (outcome === "completed" || outcome === "cancelled") setWatched(null);
+ }, []);
+ return { watched, watch, watchIfIdle, settle, dismiss };
+}
diff --git a/packages/web/src/lib/jobs/use-issue-text.ts b/packages/web/src/lib/jobs/use-issue-text.ts
new file mode 100644
index 000000000..3a3f78e8e
--- /dev/null
+++ b/packages/web/src/lib/jobs/use-issue-text.ts
@@ -0,0 +1,33 @@
+"use client";
+
+import { useCallback } from "react";
+import { useTranslations } from "next-intl";
+import type { ProviderIssue } from "@repowise-dev/ui/jobs";
+
+/** The values each known issue kind names; a missing one falls back to the
+ * server's English message so no sentence renders with a hole in it. */
+const REQUIRED: Record<string, (keyof ProviderIssue)[]> = {
+ auth: ["provider"],
+ rate_limit: ["provider"],
+ model_not_found: ["provider", "model"],
+ not_found: ["provider", "model"],
+ unreachable: ["target"],
+ docs_skipped: [],
+};
+
+/** Words a job's provider issue in the active locale, by its kind. */
+export function useIssueText(): (issue: ProviderIssue) => string {
+ const t = useTranslations("jobs.issue");
+ return useCallback(
+ (issue: ProviderIssue) => {
+ const needs = REQUIRED[issue.kind];
+ if (!needs || needs.some((field) => !issue[field])) return issue.message;
+ return t(issue.kind, {
+ provider: issue.provider ?? "",
+ model: issue.model ?? "",
+ target: issue.target ?? "",
+ });
+ },
+ [t],
+ );
+}
diff --git a/tests/providers/test_error_hints.py b/tests/providers/test_error_hints.py
new file mode 100644
index 000000000..10a228ab6
--- /dev/null
+++ b/tests/providers/test_error_hints.py
@@ -0,0 +1,94 @@
+"""Provider failures map to a hint a person can act on, without the raw text."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.providers.llm.base import ProviderError, RateLimitError
+from repowise.core.providers.llm.error_hints import describe_provider_error
+
+
+def _raised_from(outer: BaseException, cause: BaseException) -> BaseException:
+ outer.__cause__ = cause
+ return outer
+
+
[email protected]("status", [401, 403])
+def test_rejected_key_names_the_provider_and_the_fix(status):
+ exc = ProviderError("anthropic", "Error code: 401 - invalid x-api-key sk-ant-secret", status)
+
+ hint = describe_provider_error(exc)
+
+ assert hint is not None and hint.kind == "auth"
+ assert hint.message == "API key rejected by anthropic. Update it in Settings."
+ assert "sk-ant" not in hint.message
+
+
+def test_rate_limit():
+ hint = describe_provider_error(RateLimitError("openai", "slow down"))
+
+ assert hint is not None and hint.kind == "rate_limit"
+ assert "openai" in hint.message
+
+
+def test_missing_model_names_the_model_when_known():
+ exc = ProviderError("ollama", "model 'llama9' not found", 404)
+
+ hint = describe_provider_error(exc, model="llama9")
+
+ assert hint.kind == "model_not_found"
+ assert hint.message.startswith("Model llama9 was not found at ollama.")
+ assert hint.as_dict()["model"] == "llama9"
+
+
+def test_a_bare_404_also_points_at_the_base_url_path():
+ exc = ProviderError("litellm", "Error code: 404 - Not Found", 404)
+
+ hint = describe_provider_error(exc, model="gpt-x")
+
+ assert hint.kind == "not_found"
+ assert hint.message.startswith("Model gpt-x or the base URL path was not found at litellm.")
+
+
+def test_ipv6_origin_keeps_its_brackets():
+ class ConnectError(Exception):
+ request = SimpleNamespace(url="http://[::1]:8000/v1/chat")
+
+ hint = describe_provider_error(_raised_from(ProviderError("vllm", "x"), ConnectError()))
+
+ assert hint.as_dict()["target"] == "http://[::1]:8000"
+
+
+def test_unreachable_local_server_names_its_origin_without_path_or_credentials():
+ class APIConnectionError(Exception):
+ request = SimpleNamespace(url="http://user:pw@localhost:11434/v1/chat/completions?k=1")
+
+ exc = _raised_from(ProviderError("ollama", "Connection error."), APIConnectionError())
+
+ hint = describe_provider_error(exc)
+
+ assert hint is not None and hint.kind == "unreachable"
+ assert "Could not reach http://localhost:11434." in hint.message
+ assert "pw" not in hint.message and "chat" not in hint.message
+
+
+def test_connection_refused_without_a_request_falls_back_to_the_provider():
+ exc = _raised_from(ProviderError("litellm", "boom"), ConnectionRefusedError())
+
+ assert describe_provider_error(exc).message.startswith("Could not reach litellm.")
+
+
+ "exc",
+ [
+ ValueError("artifact check rejected the page"),
+ ProviderError("openai", "server error", 500),
+ # The server was reached; a dropped connection is not "unreachable".
+ _raised_from(ProviderError("openai", "x"), ConnectionResetError()),
+ _raised_from(ProviderError("openai", "x"), BrokenPipeError()),
+ ],
+)
+def test_unrecognised_errors_get_no_hint(exc):
+ assert describe_provider_error(exc) is None
diff --git a/tests/unit/generation/test_count_stub_fallbacks.py b/tests/unit/generation/test_count_stub_fallbacks.py
index 474472ae3..2d1a619d9 100644
--- a/tests/unit/generation/test_count_stub_fallbacks.py
+++ b/tests/unit/generation/test_count_stub_fallbacks.py
@@ -72,3 +72,27 @@ def test_tolerates_a_page_without_metadata():
pass
assert count_stub_fallbacks([_Bare()]) == 0
+
+
+def test_dominant_hint_is_the_one_most_failed_pages_share():
+ from repowise.core.generation.models import STUB_FALLBACK_HINT, dominant_stub_fallback_hint
+
+ auth = {"kind": "auth", "message": "API key rejected by openai. Update it in Settings."}
+ pages = [_page("a", stub_error="401"), _page("b", stub_error="401"), _page("c", stub_error="x")]
+ pages[0].metadata[STUB_FALLBACK_HINT] = auth
+ pages[1].metadata[STUB_FALLBACK_HINT] = auth
+
+ assert dominant_stub_fallback_hint(pages) == auth
+ assert dominant_stub_fallback_hint([_page("d"), pages[2]]) is None
+
+
+def test_a_stub_for_a_rejected_key_carries_the_hint():
+ from repowise.core.generation.models import STUB_FALLBACK_HINT
+ from repowise.core.generation.page_generator.pertype import _stub_fallback
+ from repowise.core.providers.llm.base import ProviderError
+
+ page = _stub_fallback(_page("a"), "module_page", ProviderError("openai", "bad key", 401))
+ plain = _stub_fallback(_page("b"), "module_page", ValueError("artifact check"))
+
+ assert page.metadata[STUB_FALLBACK_HINT]["kind"] == "auth"
+ assert STUB_FALLBACK_HINT not in plain.metadata
diff --git a/tests/unit/server/test_job_provider_issue.py b/tests/unit/server/test_job_provider_issue.py
new file mode 100644
index 000000000..0df4fa31e
--- /dev/null
+++ b/tests/unit/server/test_job_provider_issue.py
@@ -0,0 +1,180 @@
+"""A job that went wrong with its provider says so on the job record.
+
+Per-page provider errors leave stubs and the job still completes, and a
+provider that cannot be built skips docs; both used to read as a clean run.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from repowise.core.generation.models import (
+ STUB_FALLBACK_ERROR,
+ STUB_FALLBACK_HINT,
+ GeneratedPage,
+)
+from repowise.core.persistence.crud import (
+ get_generation_job,
+ upsert_generation_job,
+ upsert_repository,
+)
+from repowise.core.providers.llm.base import ProviderError
+from repowise.server.job_executor import execute_job
+
+_AUTH = {
+ "kind": "auth",
+ "message": "API key rejected by openai. Update it in Settings.",
+ "provider": "openai",
+}
+
+
+def _page(target: str, hint: dict | None = None) -> GeneratedPage:
+ now = datetime.now(UTC).isoformat()
+ page = GeneratedPage(
+ page_id=f"module_page:{target}",
+ page_type="module_page",
+ title=target,
+ content="body",
+ source_hash="x" * 64,
+ model_name="gpt-x",
+ provider_name="openai",
+ input_tokens=0,
+ output_tokens=0,
+ cached_tokens=0,
+ generation_level=4,
+ target_path=target,
+ created_at=now,
+ updated_at=now,
+ )
+ if hint is not None:
+ page.metadata[STUB_FALLBACK_ERROR] = "Error code: 401"
+ page.metadata[STUB_FALLBACK_HINT] = hint
+ return page
+
+
+def _result(pages: list) -> SimpleNamespace:
+ return SimpleNamespace(generated_pages=pages, parsed_files=[], file_count=1, symbol_count=2)
+
+
+async def _seed(session_factory, repo_path, mode: str) -> str:
+ async with session_factory() as session:
+ repo = await upsert_repository(session, name="r", local_path=str(repo_path), settings={})
+ job = await upsert_generation_job(session, repository_id=repo.id, config={"mode": mode})
+ await session.commit()
+ return job.id
+
+
+async def _run(session_factory, job_id, *, pipeline, provider):
+ app_state = SimpleNamespace(session_factory=session_factory, fts=None, vector_store=None)
+ provider_patch = (
+ patch("repowise.server.provider_config.get_chat_provider_instance", return_value=provider)
+ if provider is not None
+ else patch(
+ "repowise.server.provider_config.get_chat_provider_instance",
+ side_effect=RuntimeError("No active provider configured."),
+ )
+ )
+ with (
+ patch("repowise.server.job_executor.run_pipeline", pipeline),
+ patch("repowise.server.job_executor.persist_pipeline_result", AsyncMock()),
+ patch("repowise.server.job_executor._persist_initial_index_state"),
+ provider_patch,
+ ):
+ await execute_job(job_id, app_state)
+ async with session_factory() as session:
+ job = await get_generation_job(session, job_id)
+ return job, json.loads(job.config_json)
+
+
+_PROVIDER = SimpleNamespace(provider_name="openai", model_name="gpt-x")
+
+
+async def test_pages_lost_to_a_rejected_key_complete_with_the_hint(session_factory, tmp_path):
+ job_id = await _seed(session_factory, tmp_path, "full_resync")
+ pages = [_page("a", _AUTH), _page("b", _AUTH)]
+
+ job, config = await _run(
+ session_factory, job_id, pipeline=AsyncMock(return_value=_result(pages)), provider=_PROVIDER
+ )
+
+ assert job.status == "completed"
+ assert (job.completed_pages, job.failed_pages) == (0, 2)
+ assert config["provider_issue"] == _AUTH
+
+
+async def test_a_clean_run_records_no_issue(session_factory, tmp_path):
+ job_id = await _seed(session_factory, tmp_path, "full_resync")
+
+ _, config = await _run(
+ session_factory,
+ job_id,
+ pipeline=AsyncMock(return_value=_result([_page("a")])),
+ provider=_PROVIDER,
+ )
+
+ assert config["provider_issue"] is None
+
+
[email protected]("mode", ["sync", "full_resync"])
+async def test_a_configured_provider_that_will_not_load_is_reported(
+ session_factory, tmp_path, mode
+):
+ job_id = await _seed(session_factory, tmp_path, mode)
+
+ with patch(
+ "repowise.server.provider_config.get_active_provider", return_value=("openai", None)
+ ):
+ _, config = await _run(
+ session_factory, job_id, pipeline=AsyncMock(return_value=_result([])), provider=None
+ )
+
+ assert config["provider_issue"]["kind"] == "docs_skipped"
+ # Fixed copy, never the raw load error.
+ assert "No active provider" not in config["provider_issue"]["message"]
+
+
[email protected]("mode", ["sync", "full_resync"])
+async def test_a_deliberately_keyless_repo_is_not_a_problem(session_factory, tmp_path, mode):
+ job_id = await _seed(session_factory, tmp_path, mode)
+
+ with patch("repowise.server.provider_config.get_active_provider", return_value=(None, None)):
+ _, config = await _run(
+ session_factory, job_id, pipeline=AsyncMock(return_value=_result([])), provider=None
+ )
+
+ assert config["provider_issue"] is None
+
+
+async def test_a_keyless_first_index_is_not_a_problem(session_factory, tmp_path):
+ job_id = await _seed(session_factory, tmp_path, "initial_index")
+
+ _, config = await _run(
+ session_factory, job_id, pipeline=AsyncMock(return_value=_result([])), provider=None
+ )
+
+ assert config["provider_issue"] is None
+
+
+async def test_a_job_failing_on_the_provider_records_the_hint_not_the_raw_error(
+ session_factory, tmp_path
+):
+ job_id = await _seed(session_factory, tmp_path, "full_resync")
+ pipeline = AsyncMock(side_effect=ProviderError("openai", "Incorrect API key sk-live", 401))
+
+ job, config = await _run(session_factory, job_id, pipeline=pipeline, provider=_PROVIDER)
+
+ assert job.status == "failed"
+ assert job.error_message == _AUTH["message"]
+ assert config["provider_issue"] == _AUTH
+ assert config["mode"] == "full_resync"