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.

feat(web): publish to repowise.dev from the local UI, with dismissible tips (#3007)

Swati Ahujacd5f3a7e7d9e
diff --git a/packages/api-client/package.json b/packages/api-client/package.json
index 451e7bd00..65bbef744 100644
--- a/packages/api-client/package.json
+++ b/packages/api-client/package.json
@@ -39,6 +39,7 @@
"./pagination": "./src/pagination.ts",
"./owners": "./src/owners.ts",
"./pages": "./src/pages.ts",
+ "./platform": "./src/platform.ts",
"./providers": "./src/providers.ts",
"./refactoring": "./src/refactoring.ts",
"./repos": "./src/repos.ts",
diff --git a/packages/api-client/src/platform.ts b/packages/api-client/src/platform.ts
new file mode 100644
index 000000000..4a4926632
--- /dev/null
+++ b/packages/api-client/src/platform.ts
@@ -0,0 +1,31 @@
+/**
+ * repowise.dev from the local server: who is using this install, and the
+ * one-click publish that runs `repowise publish` for a repo.
+ */
+
+import type { IdentityResponse } from "@repowise-dev/types/generated/http";
+import { apiGet, apiPost } from "./client";
+
+export type HostedIdentity = IdentityResponse;
+
+/** `repowise publish --format json`, passed through unchanged. */
+export interface PublishResult {
+ /** `published | curated | needs_app | needs_plan | cap | too_big |
+ * rate_limited | not_github | signed_out | offline | error`. */
+ outcome: string;
+ message: string;
+ /** The one link to act on next, if any. */
+ url: string | null;
+ details: string[];
+ open_url: string | null;
+ /** `owner/name` once the remote was read. */
+ repo: string | null;
+}
+
+export async function getHostedIdentity(): Promise<HostedIdentity> {
+ return apiGet<HostedIdentity>("/api/platform/identity");
+}
+
+export async function publishRepo(repoId: string): Promise<PublishResult> {
+ return apiPost<PublishResult>("/api/platform/publish", { repo_id: repoId });
+}
diff --git a/packages/core/src/repowise/core/platform/account.py b/packages/core/src/repowise/core/platform/account.py
new file mode 100644
index 000000000..8939bca08
--- /dev/null
+++ b/packages/core/src/repowise/core/platform/account.py
@@ -0,0 +1,36 @@
+"""Read-only facts about the local repowise.dev account and hint preference.
+
+The CLI owns both files (``repowise login`` writes ``credentials.json``,
+``repowise config hints`` writes ``platform.json``); this module only reads
+them, so the server can answer "signed in?" without importing ``repowise.cli``.
+No network calls: a signed-in answer means a token is on disk, not that it
+still works.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from repowise.core.platform.telemetry import _env_truthy, _load_state
+
+
+def _credentials_path() -> Path:
+ """The ``~/.repowise/credentials.json`` that ``repowise login`` writes."""
+ return Path.home() / ".repowise" / "credentials.json"
+
+
+def is_signed_in() -> bool:
+ """A stored access token that a failed refresh has not marked stale."""
+ try:
+ creds = json.loads(_credentials_path().read_text(encoding="utf-8"))
+ except Exception:
+ return False
+ return isinstance(creds, dict) and bool(creds.get("access_token")) and not creds.get("stale")
+
+
+def hints_enabled() -> bool:
+ """The CLI's switch for repowise.dev tips, shared by the local web UI."""
+ if _env_truthy("REPOWISE_NO_HINTS") or _env_truthy("DO_NOT_TRACK"):
+ return False
+ return _load_state().get("hints_enabled") is not False
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 0d00ff1d0..d219736ad 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -63,6 +63,7 @@ from repowise.server.routers import (
overview,
owners,
pages,
+ platform,
providers,
refactoring,
repos,
@@ -388,6 +389,7 @@ _ROUTERS = (
external_systems,
feedback,
actions,
+ platform,
)
diff --git a/packages/server/src/repowise/server/routers/platform.py b/packages/server/src/repowise/server/routers/platform.py
new file mode 100644
index 000000000..2fc49ccf4
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/platform.py
@@ -0,0 +1,103 @@
+"""``/api/platform`` endpoints: who is using this install, and publishing to repowise.dev.
+
+``/identity`` lets the web UI decide whether to show repowise.dev tips and
+whether its publish button can run, from local files only (no network).
+``/publish`` runs ``repowise publish --format json`` for one repo, so the button
+and the CLI share one decision and one set of messages. The server never
+imports ``repowise.cli``; it runs the CLI in a child process instead.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import subprocess
+import sys
+
+from fastapi import APIRouter, Depends, HTTPException, Request
+from pydantic import BaseModel, Field
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from repowise.core.platform import account
+from repowise.server.deps import resolve_session_factory, verify_api_key
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(
+ prefix="/api/platform", tags=["platform"], dependencies=[Depends(verify_api_key)]
+)
+
+#: Credits the links in the CLI's answer to this button.
+_SRC = "local_web_publish"
+
+#: The CLI waits up to 60 s on repowise.dev; leave room for start-up on top.
+_TIMEOUT_SECONDS = 90.0
+
+_CANT_RUN = "Couldn't run repowise publish here. Run it in a terminal: repowise publish"
+
+
+class IdentityResponse(BaseModel):
+ signed_in: bool
+ hints_enabled: bool
+
+
+class PublishRequest(BaseModel):
+ repo_id: str = Field(..., min_length=1)
+
+
[email protected]("/identity", response_model=IdentityResponse)
+async def get_identity() -> IdentityResponse:
+ """Sign-in state and the tips switch, read from ``~/.repowise``."""
+ return IdentityResponse(
+ signed_in=account.is_signed_in(),
+ hints_enabled=account.hints_enabled(),
+ )
+
+
+def _run_publish(local_path: str) -> dict:
+ """Run the CLI and return its JSON answer, or an ``error`` outcome."""
+ argv = [
+ sys.executable,
+ "-m",
+ "repowise.cli.main",
+ "publish",
+ local_path,
+ "--format",
+ "json",
+ "--no-open",
+ "--src",
+ _SRC,
+ ]
+ try:
+ # Exit code 1 still prints the answer (a refusal, signed out, ...), so
+ # the code is ignored and stdout decides.
+ proc = subprocess.run(
+ argv, capture_output=True, text=True, timeout=_TIMEOUT_SECONDS, check=False
+ )
+ result = json.loads(proc.stdout)
+ if isinstance(result, dict) and isinstance(result.get("outcome"), str):
+ return result
+ logger.warning("repowise publish printed no outcome: %r", proc.stdout[:200])
+ except Exception as exc:
+ logger.warning("repowise publish could not run: %s", exc)
+ return {
+ "outcome": "error",
+ "message": _CANT_RUN,
+ "url": None,
+ "details": [],
+ "open_url": None,
+ "repo": None,
+ }
+
+
[email protected]("/publish")
+async def publish(body: PublishRequest, request: Request) -> dict:
+ """Publish one indexed repo on repowise.dev, answering with the CLI's result."""
+ factory = resolve_session_factory(request.app.state, body.repo_id)
+ async with get_session(factory) as session:
+ repo = await crud.get_repository(session, body.repo_id)
+ if repo is None or not repo.local_path:
+ raise HTTPException(status_code=404, detail="Repository not found")
+ return await asyncio.to_thread(_run_publish, repo.local_path)
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 496553f6c..8bfb0668b 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2042,6 +2042,11 @@ export interface HotspotResponse {
original_path?: string | null;
}
+export interface IdentityResponse {
+ signed_in: boolean;
+ hints_enabled: boolean;
+}
+
/** One file on the impact / effort plane. */
export interface ImpactEffortPoint {
file_path: string;
@@ -2638,6 +2643,10 @@ export interface ProviderValidationResponse {
error?: string | null;
}
+export interface PublishRequest {
+ repo_id: string;
+}
+
/** What the ``fix_first`` scope leaves out of a page's filtered set. */
export interface RefactoringHiddenCounts {
total?: number;
diff --git a/packages/ui/__tests__/shared/hosted-nudge.test.tsx b/packages/ui/__tests__/shared/hosted-nudge.test.tsx
new file mode 100644
index 000000000..698c8391c
--- /dev/null
+++ b/packages/ui/__tests__/shared/hosted-nudge.test.tsx
@@ -0,0 +1,57 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+
+import { HostedNudge } from "../../src/shared/hosted-nudge";
+
+const KEY = "repowise:hosted-nudge-dismissed:mcp";
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ window.localStorage.clear();
+});
+
+function renderNudge() {
+ return render(
+ <HostedNudge
+ id="mcp"
+ text="Use this repo inside Claude.ai."
+ href="https://repowise.dev/hosted?src=x#mcp"
+ action={<button type="button">Publish it free</button>}
+ />,
+ );
+}
+
+describe("HostedNudge", () => {
+ it("shows the sentence, the action and a See how link that opens in a new tab", async () => {
+ renderNudge();
+ expect(await screen.findByText("Use this repo inside Claude.ai.")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Publish it free" })).toBeInTheDocument();
+ const link = screen.getByRole("link", { name: "See how" });
+ expect(link).toHaveAttribute("href", "https://repowise.dev/hosted?src=x#mcp");
+ expect(link).toHaveAttribute("target", "_blank");
+ expect(link).toHaveAttribute("rel", "noopener noreferrer");
+ });
+
+ it("remembers a dismissal across mounts", async () => {
+ const { unmount } = renderNudge();
+ fireEvent.click(await screen.findByRole("button", { name: /dismiss this repowise\.dev tip/i }));
+ expect(screen.queryByText("Use this repo inside Claude.ai.")).not.toBeInTheDocument();
+ expect(window.localStorage.getItem(KEY)).toBe("1");
+ unmount();
+
+ renderNudge();
+ expect(screen.queryByText("Use this repo inside Claude.ai.")).not.toBeInTheDocument();
+ });
+
+ it("renders and dismisses when storage throws", async () => {
+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
+ throw new Error("blocked");
+ });
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new Error("blocked");
+ });
+ renderNudge();
+ fireEvent.click(await screen.findByRole("button", { name: /dismiss this repowise\.dev tip/i }));
+ expect(screen.queryByText("Use this repo inside Claude.ai.")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/shared/hosted-nudge.tsx b/packages/ui/src/shared/hosted-nudge.tsx
new file mode 100644
index 000000000..8aa3f4f25
--- /dev/null
+++ b/packages/ui/src/shared/hosted-nudge.tsx
@@ -0,0 +1,73 @@
+"use client";
+
+import * as React from "react";
+
+import { DismissibleNotice } from "./dismissible-notice";
+
+const STORAGE_PREFIX = "repowise:hosted-nudge-dismissed:";
+
+export interface HostedNudgeProps {
+ /** Remembers the dismissal, per browser. */
+ id: string;
+ /** One sentence on what repowise.dev adds here. */
+ text: React.ReactNode;
+ /** The "See how" link. Opens in a new tab. */
+ href: string;
+ /** The free next step, rendered before "See how". */
+ action?: React.ReactNode;
+ className?: string;
+}
+
+/**
+ * A dismissible tip about repowise.dev. Dismissal is kept in `localStorage`;
+ * when storage is unavailable the tip still renders and a dismissal lasts
+ * until the page reloads.
+ */
+export function HostedNudge({ id, text, href, action, className }: HostedNudgeProps) {
+ // Hidden until the mount effect reads storage, so SSR and the first client
+ // render agree and a dismissed tip never flashes.
+ const [dismissed, setDismissed] = React.useState(true);
+
+ React.useEffect(() => {
+ try {
+ setDismissed(window.localStorage.getItem(STORAGE_PREFIX + id) === "1");
+ } catch {
+ setDismissed(false);
+ }
+ }, [id]);
+
+ if (dismissed) return null;
+
+ const dismiss = () => {
+ try {
+ window.localStorage.setItem(STORAGE_PREFIX + id, "1");
+ } catch {
+ /* Storage unavailable: hide for this page only. */
+ }
+ setDismissed(true);
+ };
+
+ return (
+ <DismissibleNotice
+ tone="info"
+ onDismiss={dismiss}
+ dismissLabel="Dismiss this repowise.dev tip"
+ {...(className ? { className } : {})}
+ action={
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
+ {action}
+ <a
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ See how
+ </a>
+ </div>
+ }
+ >
+ {text}
+ </DismissibleNotice>
+ );
+}
diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.ts
index 4055b3fcc..5dd7cabc5 100644
--- a/packages/ui/src/shared/index.ts
+++ b/packages/ui/src/shared/index.ts
@@ -31,6 +31,7 @@ export {
type DismissibleNoticeProps,
type NoticeTone,
} from "./dismissible-notice";
+export { HostedNudge, type HostedNudgeProps } from "./hosted-nudge";
export { InfoTip, type InfoTipProps } from "./info-tip";
export { OwlLoader, type OwlLoaderProps } from "./owl-loader";
export {
diff --git a/packages/web/src/app/repos/[id]/docs/coverage/page.tsx b/packages/web/src/app/repos/[id]/docs/coverage/page.tsx
index ed3590097..d0cff3780 100644
--- a/packages/web/src/app/repos/[id]/docs/coverage/page.tsx
+++ b/packages/web/src/app/repos/[id]/docs/coverage/page.tsx
@@ -8,6 +8,7 @@ import type { DocPage } from "@repowise-dev/types/docs";
import { MetricCard } from "@repowise-dev/ui/shared/metric-card";
import { listAllPages } from "@/lib/api/pages";
import { formatNumber } from "@repowise-dev/ui/lib/format";
+import { HostedNudgeSlot } from "@/components/hosted/hosted-nudge-slot";
export const metadata: Metadata = { title: "Doc freshness" };
@@ -97,6 +98,7 @@ export default async function CoveragePage({
)}
<DriftBanner pages={pages as DocPage[]} />
+ <HostedNudgeSlot candidates={[stale + outdated > 0 && "stale"]} repoId={id} />
{pages.length > 0 && (
<ConfidenceVsFreshnessMatrix pages={pages as DocPage[]} />
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index c8668bf38..c32ea3efa 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -9,8 +9,10 @@ import { FirstIndexExperience } from "@/components/repos/first-index-experience"
import { QuickActionsWrapper } from "@/components/dashboard/quick-actions-wrapper";
import { AskAnythingRow } from "@/components/overview/ask-anything-row";
import { NextActionsPanel } from "@/components/overview/next-actions-panel";
+import { PublishOverviewSection } from "@/components/hosted/publish";
import {
OverviewBody,
+ OverviewSection,
RepoIdentityHeader,
type OverviewRoutes,
type RepoIdentityMeta,
@@ -138,6 +140,7 @@ export default async function OverviewPage({ params }: Props) {
slots={{
header,
ask: <AskAnythingRow repoId={id} />,
+ beforeExplore: <PublishOverviewSection repoId={id} />,
// A server that predates actions returns 404; the page then keeps the
// attention areas in their old place rather than showing an empty list.
actions: actions ? (
diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsx
index 462e0164b..c7a2ce378 100644
--- a/packages/web/src/app/repos/[id]/settings/page.tsx
+++ b/packages/web/src/app/repos/[id]/settings/page.tsx
@@ -12,6 +12,7 @@ import { RepoSettingsFormWrapper as RepoSettingsForm } from "@/components/repos/
import { CoordinatorHealthPanel } from "@/components/repos/coordinator-health-panel";
import { DeleteRepoButton } from "@/components/repos/delete-repo-button";
import { OperationsPanel } from "@/components/repos/operations-panel";
+import { PublishPanel } from "@/components/hosted/publish";
interface Props {
params: Promise<{ id: string }>;
@@ -101,6 +102,13 @@ export default async function RepoSettingsPage({ params }: Props) {
<CoordinatorHealthPanel repoId={id} initial={coordinatorHealth} />
</OverviewSection>
+ <OverviewSection
+ title="Publish on repowise.dev"
+ description="Put this repository on repowise.dev, indexed from its GitHub remote. Nothing on this machine is uploaded."
+ >
+ <PublishPanel repoId={id} />
+ </OverviewSection>
+
{/* Not a tinted card. A destructive action earns emphasis on the verb and
the sentence, not on a coloured ground the eye reads before either. */}
<section className="flex flex-col gap-3 border-t border-[var(--color-border-default)] pt-6 sm:pt-8">
diff --git a/packages/web/src/app/settings/page.tsx b/packages/web/src/app/settings/page.tsx
index 89a5b39d0..99618fc09 100644
--- a/packages/web/src/app/settings/page.tsx
+++ b/packages/web/src/app/settings/page.tsx
@@ -7,6 +7,7 @@ import { WebhookSection } from "@/components/settings/webhook-section";
import { McpSection } from "@/components/settings/mcp-section";
import { McpToolsSection } from "@/components/settings/mcp-tools-section";
import { DisplaySection } from "@/components/settings/display-section";
+import { HostedNudgeSlot } from "@/components/hosted/hosted-nudge-slot";
export const metadata: Metadata = { title: "Settings" };
@@ -31,6 +32,7 @@ export default function SettingsPage() {
<ConnectionSection />
<ProviderSection />
<DisplaySection />
+ <HostedNudgeSlot candidates={["mcp"]} />
<McpSection />
<McpToolsSection />
<WebhookSection />
diff --git a/packages/web/src/components/docs/docs-explorer.tsx b/packages/web/src/components/docs/docs-explorer.tsx
index 3d3f8412c..29c4cc81d 100644
--- a/packages/web/src/components/docs/docs-explorer.tsx
+++ b/packages/web/src/components/docs/docs-explorer.tsx
@@ -31,6 +31,7 @@ import {
} from "./docs-page-actions";
import { PageGenerateButton } from "./page-generate-button";
import { BulkGenerateButton } from "./bulk-generate-button";
+import { HostedNudgeSlot } from "@/components/hosted/hosted-nudge-slot";
import { isModelWrittenType, isStubPage } from "@repowise-dev/ui/lib/page-types";
import { search as searchPages } from "@/lib/api/search";
import { getPageById, listAllPages } from "@/lib/api/pages";
@@ -402,6 +403,13 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {
)}
</DocsHeader>
+ {/* Only while pages are still rendered from structure. */}
+ <HostedNudgeSlot
+ candidates={[hasStubs && "docs"]}
+ repoId={repoId}
+ className="mx-3 mt-2 sm:mx-6"
+ />
+
<div className="flex-1 min-h-0">{body}</div>
</div>
diff --git a/packages/web/src/components/hosted/hosted-nudge-slot.test.tsx b/packages/web/src/components/hosted/hosted-nudge-slot.test.tsx
new file mode 100644
index 000000000..c8eff9129
--- /dev/null
+++ b/packages/web/src/components/hosted/hosted-nudge-slot.test.tsx
@@ -0,0 +1,93 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ identity: vi.fn(),
+ publishRepo: vi.fn(),
+}));
+
+vi.mock("@/lib/hooks/use-hosted-identity", () => ({
+ useHostedIdentity: () => ({ identity: mocks.identity() }),
+}));
+vi.mock("@/lib/api/platform", () => ({ publishRepo: mocks.publishRepo }));
+
+import { config } from "@/lib/config";
+import { HostedNudgeSlot } from "./hosted-nudge-slot";
+
+const MCP = "Use this repo inside Claude.ai or ChatGPT. Local MCP only works in desktop tools.";
+const DOCS = "Want AI-written docs without an API key? repowise.dev includes the model.";
+
+beforeEach(() => {
+ window.localStorage.clear();
+ mocks.identity.mockReturnValue({ signed_in: false, hints_enabled: true });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("HostedNudgeSlot", () => {
+ it("shows one tip, linking to its moment with its source only", async () => {
+ render(<HostedNudgeSlot candidates={["docs", "mcp"]} repoId="r1" />);
+ expect(await screen.findByText(DOCS)).toBeTruthy();
+ expect(screen.queryByText(MCP)).toBeNull();
+ expect(screen.getAllByRole("link", { name: "See how" })).toHaveLength(1);
+ expect(screen.getByRole("link", { name: "See how" }).getAttribute("href")).toBe(
+ "https://repowise.dev/hosted?src=local_web_docs#keys",
+ );
+ });
+
+ it("shows nothing for a signed-in user", async () => {
+ mocks.identity.mockReturnValue({ signed_in: true, hints_enabled: true });
+ render(<HostedNudgeSlot candidates={["mcp"]} repoId="r1" />);
+ await Promise.resolve();
+ expect(screen.queryByText(MCP)).toBeNull();
+ });
+
+ it("shows nothing when the local tips switch is off", async () => {
+ config.setHostedTipsHidden(true);
+ render(<HostedNudgeSlot candidates={["mcp"]} repoId="r1" />);
+ await Promise.resolve();
+ expect(screen.queryByText(MCP)).toBeNull();
+ });
+
+ it("stays dismissed on the next visit", async () => {
+ const first = render(<HostedNudgeSlot candidates={["mcp"]} repoId="r1" />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /dismiss this repowise\.dev tip/i }),
+ );
+ expect(screen.queryByText(MCP)).toBeNull();
+ first.unmount();
+
+ render(<HostedNudgeSlot candidates={["mcp"]} repoId="r1" />);
+ await Promise.resolve();
+ expect(screen.queryByText(MCP)).toBeNull();
+ });
+
+ it("publishes from its free action on a repo page once confirmed", async () => {
+ mocks.publishRepo.mockResolvedValue({
+ outcome: "signed_out",
+ message: "Sign in to repowise.dev first: repowise login",
+ url: null,
+ details: [],
+ open_url: null,
+ repo: "o/n",
+ });
+ render(<HostedNudgeSlot candidates={["mcp"]} repoId="r1" />);
+ fireEvent.click(await screen.findByRole("button", { name: "Publish it free" }));
+ expect(mocks.publishRepo).not.toHaveBeenCalled();
+ fireEvent.click(await screen.findByRole("button", { name: "Publish" }));
+ expect(await screen.findByText("Sign in to repowise.dev first: repowise login")).toBeTruthy();
+ expect(mocks.publishRepo).toHaveBeenCalledWith("r1");
+ });
+
+ it("names the CLI command where no repo is known", async () => {
+ render(<HostedNudgeSlot candidates={["mcp"]} />);
+ expect(await screen.findByText("repowise publish")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Publish it free" })).toBeNull();
+ });
+});
diff --git a/packages/web/src/components/hosted/hosted-nudge-slot.tsx b/packages/web/src/components/hosted/hosted-nudge-slot.tsx
new file mode 100644
index 000000000..f2f80b500
--- /dev/null
+++ b/packages/web/src/components/hosted/hosted-nudge-slot.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { HostedNudge } from "@repowise-dev/ui/shared/hosted-nudge";
+import { config } from "@/lib/config";
+import { NUDGES, hostedLink, pickNudge, type NudgeId } from "@/lib/hosted";
+import { useHostedIdentity } from "@/lib/hooks/use-hosted-identity";
+import { PublishItFree } from "./publish";
+
+interface Props {
+ /** Tips whose moment applies here, most specific first. A page mounts one
+ * slot, so it shows at most one tip. */
+ candidates: readonly (NudgeId | false | null | undefined)[];
+ /** The repo the page is about; without one the action is the CLI command. */
+ repoId?: string;
+ className?: string;
+}
+
+export function HostedNudgeSlot({ candidates, repoId, className }: Props) {
+ const { identity } = useHostedIdentity();
+ // Off until read after mount, so SSR and the first client render agree.
+ const [tipsShown, setTipsShown] = useState(false);
+ useEffect(() => setTipsShown(!config.getHostedTipsHidden()), []);
+
+ const id = pickNudge(candidates, identity, tipsShown);
+ if (!id) return null;
+ const nudge = NUDGES[id];
+
+ return (
+ <HostedNudge
+ id={id}
+ text={nudge.text}
+ href={hostedLink(nudge.surface, nudge.moment)}
+ className={className}
+ action={
+ repoId ? (
+ <PublishItFree repoId={repoId} />
+ ) : (
+ <span>
+ Publish it free:{" "}
+ <code className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5">
+ repowise publish
+ </code>
+ </span>
+ )
+ }
+ />
+ );
+}
diff --git a/packages/web/src/components/hosted/publish.test.tsx b/packages/web/src/components/hosted/publish.test.tsx
new file mode 100644
index 000000000..d313fb451
--- /dev/null
+++ b/packages/web/src/components/hosted/publish.test.tsx
@@ -0,0 +1,114 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ identity: vi.fn(),
+ publishRepo: vi.fn(),
+}));
+
+vi.mock("@/lib/hooks/use-hosted-identity", () => ({
+ useHostedIdentity: () => ({ identity: mocks.identity() }),
+}));
+vi.mock("@/lib/api/platform", () => ({ publishRepo: mocks.publishRepo }));
+
+import { PublishPanel } from "./publish";
+
+const BUTTON = "Publish to repowise.dev";
+
+/** The panel's button, then the confirmation's. */
+async function publish() {
+ fireEvent.click(screen.getByRole("button", { name: BUTTON }));
+ fireEvent.click(await screen.findByRole("button", { name: "Publish" }));
+}
+
+beforeEach(() => {
+ mocks.identity.mockReturnValue({ signed_in: true, hints_enabled: true });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("PublishPanel", () => {
+ it("asks a signed-out user to sign in from a terminal instead of offering the button", () => {
+ mocks.identity.mockReturnValue({ signed_in: false, hints_enabled: true });
+ render(<PublishPanel repoId="r1" />);
+ expect(screen.queryByRole("button", { name: BUTTON })).toBeNull();
+ expect(screen.getByText(/Sign in first: run/).textContent).toContain(
+ "Sign in first: run repowise login in a terminal.",
+ );
+ expect(screen.getByText(/Only what's pushed to GitHub is published/)).toBeTruthy();
+ });
+
+ it("is busy while publishing, then shows the message, the link and the details", async () => {
+ let resolve!: (v: unknown) => void;
+ mocks.publishRepo.mockReturnValue(new Promise((r) => (resolve = r)));
+ render(<PublishPanel repoId="r1" />);
+
+ await publish();
+ const busy = screen.getByRole("button", { name: "Publishing…" }) as HTMLButtonElement;
+ expect(busy.disabled).toBe(true);
+ expect(mocks.publishRepo).toHaveBeenCalledWith("r1");
+
+ resolve({
+ outcome: "published",
+ message: "Your repo is being indexed:",
+ url: "https://repowise.dev/s/abc/indexing",
+ details: ["A hosted index usually takes about 10 minutes."],
+ open_url: "https://repowise.dev/s/abc/indexing",
+ repo: "o/n",
+ });
+
+ expect(await screen.findByText("Your repo is being indexed:")).toBeTruthy();
+ const link = screen.getByRole("link", { name: "https://repowise.dev/s/abc/indexing" });
+ expect(link.getAttribute("target")).toBe("_blank");
+ expect(link.getAttribute("rel")).toBe("noopener noreferrer");
+ expect(screen.getByText("A hosted index usually takes about 10 minutes.")).toBeTruthy();
+ expect(screen.getByRole("button", { name: BUTTON })).toBeTruthy();
+ });
+
+ it("shows a refusal's message and link", async () => {
+ mocks.publishRepo.mockResolvedValue({
+ outcome: "needs_app",
+ message: "Install the GitHub app first:",
+ url: "https://github.com/apps/repowise-app/installations/new",
+ details: [],
+ open_url: null,
+ repo: "o/n",
+ });
+ render(<PublishPanel repoId="r1" />);
+ await publish();
+
+ expect(await screen.findByText("Install the GitHub app first:")).toBeTruthy();
+ expect(
+ screen.getByRole("link", {
+ name: "https://github.com/apps/repowise-app/installations/new",
+ }),
+ ).toBeTruthy();
+ });
+
+ it("asks first, says nothing local is uploaded, and does nothing on cancel", async () => {
+ render(<PublishPanel repoId="r1" />);
+ fireEvent.click(screen.getByRole("button", { name: BUTTON }));
+ expect(await screen.findByText(/nothing on this machine is uploaded/)).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(mocks.publishRepo).not.toHaveBeenCalled();
+ });
+
+ it("states the free limits as a free account's, since the plan is unknown here", () => {
+ render(<PublishPanel repoId="r1" />);
+ const note = screen.getByText(/Only what's pushed to GitHub is published/).textContent ?? "";
+ expect(note).toContain("On a free account, public repos are free (up to 2)");
+ expect(note).toContain("free for 10 days, card required");
+ });
+
+ it("renders nothing while identity is unknown", () => {
+ mocks.identity.mockReturnValue(null);
+ const { container } = render(<PublishPanel repoId="r1" />);
+ expect(container.textContent).toBe("");
+ });
+});
diff --git a/packages/web/src/components/hosted/publish.tsx b/packages/web/src/components/hosted/publish.tsx
new file mode 100644
index 000000000..2ff85fbe0
--- /dev/null
+++ b/packages/web/src/components/hosted/publish.tsx
@@ -0,0 +1,152 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { OverviewSection } from "@repowise-dev/ui/overview";
+import { Button } from "@repowise-dev/ui/ui/button";
+import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";
+import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+import { publishRepo, type PublishResult } from "@/lib/api/platform";
+import { config } from "@/lib/config";
+import { useHostedIdentity } from "@/lib/hooks/use-hosted-identity";
+
+/** Runs `repowise publish` for one repo through the local server, after the
+ * person confirms. The CLI owns the decision and every message; this only
+ * holds the request state and the confirmation. */
+function usePublish(repoId: string) {
+ const [busy, setBusy] = useState(false);
+ const [confirming, setConfirming] = useState(false);
+ const [result, setResult] = useState<PublishResult | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ async function run() {
+ setConfirming(false);
+ setBusy(true);
+ setError(null);
+ try {
+ setResult(await publishRepo(repoId));
+ } catch (e) {
+ setResult(null);
+ setError(toFriendlyMessage(e));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const confirmDialog = (
+ <ConfirmDialog
+ open={confirming}
+ onOpenChange={setConfirming}
+ title="Publish to repowise.dev?"
+ description="repowise.dev will index this repo from its GitHub remote. Only what's pushed to GitHub is used; nothing on this machine is uploaded."
+ confirmLabel="Publish"
+ onConfirm={run}
+ />
+ );
+
+ return { busy, result, error, ask: () => setConfirming(true), confirmDialog };
+}
+
+function PublishOutcome({ result, error }: { result: PublishResult | null; error: string | null }) {
+ if (error) {
+ return (
+ <p role="status" className="text-xs text-[var(--color-error)]">
+ {error}
+ </p>
+ );
+ }
+ if (!result) return null;
+ return (
+ <div role="status" className="flex flex-col gap-1 text-xs text-[var(--color-text-secondary)]">
+ <p className="text-[var(--color-text-primary)]">{result.message}</p>
+ {result.url && (
+ <a
+ href={result.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="break-all text-[var(--color-accent-primary)] hover:underline"
+ >
+ {result.url}
+ </a>
+ )}
+ {result.details.map((line) => (
+ <p key={line} className="break-words text-[var(--color-text-tertiary)]">
+ {line}
+ </p>
+ ))}
+ </div>
+ );
+}
+
+const SIGN_IN_FIRST = (
+ <>
+ Sign in first: run{" "}
+ <code className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs">
+ repowise login
+ </code>{" "}
+ in a terminal.
+ </>
+);
+
+/** The "Publish to repowise.dev" button with its result, for a repo page. */
+export function PublishPanel({ repoId }: { repoId: string }) {
+ const { identity } = useHostedIdentity();
+ const { busy, result, error, ask, confirmDialog } = usePublish(repoId);
+ // A server without the endpoint answers nothing; no button beats a broken one.
+ if (!identity) return null;
+
+ return (
+ <div className="flex flex-col gap-3">
+ {identity.signed_in ? (
+ <div>
+ <Button size="sm" onClick={ask} disabled={busy}>
+ {busy ? "Publishing…" : "Publish to repowise.dev"}
+ </Button>
+ </div>
+ ) : (
+ <p className="text-sm text-[var(--color-text-secondary)]">{SIGN_IN_FIRST}</p>
+ )}
+ <PublishOutcome result={result} error={error} />
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {/* True on every plan: the panel doesn't know which one this account has. */}
+ Only what&apos;s pushed to GitHub is published. On a free account, public repos are
+ free (up to 2); private repos and more repos need Pro, free for 10 days, card required.
+ </p>
+ {confirmDialog}
+ </div>
+ );
+}
+
+/** The panel as a repo overview section. Unlike repo settings, the overview
+ * is not where someone goes to publish, so it follows the tips switches. */
+export function PublishOverviewSection({ repoId }: { repoId: string }) {
+ const { identity } = useHostedIdentity();
+ // Off until read after mount, so SSR and the first client render agree.
+ const [tipsShown, setTipsShown] = useState(false);
+ useEffect(() => setTipsShown(!config.getHostedTipsHidden()), []);
+ if (!identity?.hints_enabled || !tipsShown) return null;
+
+ return (
+ <OverviewSection title="Publish on repowise.dev">
+ <PublishPanel repoId={repoId} />
+ </OverviewSection>
+ );
+}
+
+/** A tip's free next step on a repo page: the same publish, confirmed first. */
+export function PublishItFree({ repoId }: { repoId: string }) {
+ const { busy, result, error, ask, confirmDialog } = usePublish(repoId);
+ return (
+ <span className="flex flex-col gap-1">
+ <button
+ type="button"
+ onClick={ask}
+ disabled={busy}
+ className="self-start font-medium text-[var(--color-accent-primary)] hover:underline disabled:opacity-60"
+ >
+ {busy ? "Publishing…" : "Publish it free"}
+ </button>
+ <PublishOutcome result={result} error={error} />
+ {confirmDialog}
+ </span>
+ );
+}
diff --git a/packages/web/src/components/settings/display-section.tsx b/packages/web/src/components/settings/display-section.tsx
index fa2a03823..ea730d78c 100644
--- a/packages/web/src/components/settings/display-section.tsx
+++ b/packages/web/src/components/settings/display-section.tsx
@@ -64,12 +64,14 @@ export function DisplaySection() {
ask: true,
selection: true,
});
+ const [tipsShown, setTipsShown] = useState(true);
const [saveState, setSaveState] = useState<SaveState>("idle");
const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Read after mount so SSR and the first client render agree.
useEffect(() => {
setWeekend(config.getWeekend() || DEFAULT_WEEKEND_PRESET.id);
+ setTipsShown(!config.getHostedTipsHidden());
}, []);
// The same two listeners the affordances themselves use: `storage` covers
@@ -110,6 +112,12 @@ export function DisplaySection() {
markSaved();
}
+ function handleTipsChange(shown: boolean) {
+ setTipsShown(shown);
+ config.setHostedTipsHidden(!shown);
+ markSaved();
+ }
+
function handleChatChange(
entry: (typeof CHAT_SWITCHES)[number],
shown: boolean,
@@ -169,6 +177,16 @@ export function DisplaySection() {
</SettingsRow>
);
})}
+ <SettingsRow
+ label="Show repowise.dev tips"
+ hint="An occasional one-line tip about what repowise.dev adds, at most one per page. Never shown once you have signed in with repowise login."
+ >
+ <Switch
+ checked={tipsShown}
+ onCheckedChange={handleTipsChange}
+ aria-label="Show repowise.dev tips"
+ />
+ </SettingsRow>
</SettingsRows>
</OverviewSection>
);
diff --git a/packages/web/src/lib/api/platform.ts b/packages/web/src/lib/api/platform.ts
new file mode 100644
index 000000000..afe68f932
--- /dev/null
+++ b/packages/web/src/lib/api/platform.ts
@@ -0,0 +1,3 @@
+import "./client";
+
+export * from "@repowise-dev/api-client/platform";
diff --git a/packages/web/src/lib/config.ts b/packages/web/src/lib/config.ts
index ba7ec1a95..9f6105f25 100644
--- a/packages/web/src/lib/config.ts
+++ b/packages/web/src/lib/config.ts
@@ -15,6 +15,7 @@ const KEYS = {
chatAskControlsHidden: "repowise_chat_ask_controls_hidden",
chatSelectionAskHidden: "repowise_chat_selection_ask_hidden",
chatHintSeen: "repowise_chat_hint_seen",
+ hostedTipsHidden: "repowise_hosted_tips_hidden",
} as const;
function read(key: string): string {
@@ -72,6 +73,24 @@ export const config = {
/** Whether the pill has already introduced itself once in this browser. */
getChatHintSeen: () => read(KEYS.chatHintSeen) === "1",
setChatHintSeen: () => write(KEYS.chatHintSeen, "1"),
+
+ /** Whether the repowise.dev tips are hidden. Storage can throw (private
+ * window, blocked site data): a failed read means shown, a failed write
+ * keeps the choice until reload. */
+ getHostedTipsHidden: () => {
+ try {
+ return read(KEYS.hostedTipsHidden) === "1";
+ } catch {
+ return false;
+ }
+ },
+ setHostedTipsHidden: (v: boolean) => {
+ try {
+ write(KEYS.hostedTipsHidden, v ? "1" : "");
+ } catch {
+ /* Storage unavailable. */
+ }
+ },
};
/** Fires when any chat affordance's visibility changes in this tab.
diff --git a/packages/web/src/lib/hooks/use-hosted-identity.ts b/packages/web/src/lib/hooks/use-hosted-identity.ts
new file mode 100644
index 000000000..27a808640
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-hosted-identity.ts
@@ -0,0 +1,18 @@
+"use client";
+
+import useSWR from "swr";
+import { getHostedIdentity } from "@/lib/api/platform";
+
+/**
+ * Sign-in state and tips switch, fetched once per session and
+ * shared by every tip and publish button. `null` while loading or when the
+ * server predates the endpoint, which callers treat as "show nothing".
+ */
+export function useHostedIdentity() {
+ const { data } = useSWR("platform-identity", getHostedIdentity, {
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ shouldRetryOnError: false,
+ });
+ return { identity: data ?? null };
+}
diff --git a/packages/web/src/lib/hosted.test.ts b/packages/web/src/lib/hosted.test.ts
new file mode 100644
index 000000000..3e2998963
--- /dev/null
+++ b/packages/web/src/lib/hosted.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import { hostedLink, pickNudge } from "./hosted";
+
+const signedOut = { signed_in: false, hints_enabled: true };
+
+describe("hostedLink", () => {
+ it("carries the surface and the moment, nothing else", () => {
+ expect(hostedLink("mcp", "mcp")).toBe("https://repowise.dev/hosted?src=local_web_mcp#mcp");
+ });
+});
+
+describe("pickNudge", () => {
+ it("shows only the first tip that applies", () => {
+ expect(pickNudge([false, "docs", "mcp"], signedOut, true)).toBe("docs");
+ expect(pickNudge([null, undefined, false], signedOut, true)).toBeNull();
+ });
+
+ it("shows nothing for a signed-in user", () => {
+ expect(pickNudge(["mcp"], { ...signedOut, signed_in: true }, true)).toBeNull();
+ });
+
+ it("shows nothing when the CLI's hints switch is off", () => {
+ expect(pickNudge(["mcp"], { ...signedOut, hints_enabled: false }, true)).toBeNull();
+ });
+
+ it("shows nothing when the local tips switch is off", () => {
+ expect(pickNudge(["mcp"], signedOut, false)).toBeNull();
+ });
+
+ it("shows nothing while identity is unknown", () => {
+ expect(pickNudge(["mcp"], null, true)).toBeNull();
+ });
+});
diff --git a/packages/web/src/lib/hosted.ts b/packages/web/src/lib/hosted.ts
new file mode 100644
index 000000000..3c1ea52d7
--- /dev/null
+++ b/packages/web/src/lib/hosted.ts
@@ -0,0 +1,61 @@
+/**
+ * repowise.dev tips for the local dashboard: the links, the sentences, and
+ * which one (if any) a page shows.
+ *
+ * Plain outbound links only: nothing here sends an event to repowise.dev.
+ */
+
+import type { HostedIdentity } from "@/lib/api/platform";
+
+const HOSTED_URL = "https://repowise.dev/hosted";
+
+/** `https://repowise.dev/hosted?src=local_web_<surface>#<moment>`. Only
+ * `src`: a link someone opens never carries an install id. */
+export function hostedLink(surface: string, moment: string): string {
+ const params = new URLSearchParams({ src: `local_web_${surface}` });
+ return `${HOSTED_URL}?${params.toString()}#${moment}`;
+}
+
+export interface Nudge {
+ text: string;
+ /** Becomes `src=local_web_<surface>`. */
+ surface: string;
+ /** The section of the hosted page the link opens. */
+ moment: string;
+}
+
+/** Publishing a public repo is free; anything about private repos or more
+ * repos says "free for 10 days, card required", never just "free". */
+export const NUDGES = {
+ mcp: {
+ text: "Use this repo inside Claude.ai or ChatGPT. Local MCP only works in desktop tools.",
+ surface: "mcp",
+ moment: "mcp",
+ },
+ stale: {
+ text: "Keep this up to date automatically on every push.",
+ surface: "stale",
+ moment: "sync",
+ },
+ docs: {
+ text: "Want AI-written docs without an API key? repowise.dev includes the model.",
+ surface: "docs",
+ moment: "keys",
+ },
+} satisfies Record<string, Nudge>;
+
+export type NudgeId = keyof typeof NUDGES;
+
+/**
+ * The one tip a page shows, or none. `candidates` are the tips whose moment
+ * applies on this page, most specific first. Nothing shows while identity is
+ * unknown, for a signed-in user, or when tips are off on the CLI or here.
+ */
+export function pickNudge(
+ candidates: readonly (NudgeId | false | null | undefined)[],
+ identity: HostedIdentity | null,
+ tipsShown: boolean,
+): NudgeId | null {
+ if (!identity || identity.signed_in || !identity.hints_enabled || !tipsShown) return null;
+ return candidates.find((c): c is NudgeId => Boolean(c)) ?? null;
+}
diff --git a/tests/unit/server/test_platform_route.py b/tests/unit/server/test_platform_route.py
new file mode 100644
index 000000000..ea6bc6da1
--- /dev/null
+++ b/tests/unit/server/test_platform_route.py
@@ -0,0 +1,206 @@
+"""/api/platform: identity from ~/.repowise, and publish through the CLI."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.platform import telemetry
+from repowise.server.routers import platform
+from tests.unit.server.conftest import create_test_repo
+
+
+def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """A fake home with an empty ~/.repowise, and no consent env vars."""
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ for name in ("DO_NOT_TRACK", "REPOWISE_TELEMETRY_DISABLED", "REPOWISE_NO_HINTS"):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setattr(telemetry, "_state_cache", None)
+ (tmp_path / ".repowise").mkdir()
+ return tmp_path
+
+
+async def platform_client(app, client: AsyncClient) -> AsyncClient:
+ app.include_router(platform.router)
+ return client
+
+
+def _write(home: Path, name: str, data: object) -> None:
+ (home / ".repowise" / name).write_text(json.dumps(data), encoding="utf-8")
+
+
+async def _identity(client: AsyncClient) -> dict:
+ resp = await client.get("/api/platform/identity")
+ assert resp.status_code == 200
+ return resp.json()
+
+
+async def test_identity_with_nothing_stored(platform_client: AsyncClient, home: Path) -> None:
+ assert await _identity(platform_client) == {
+ "signed_in": False,
+ "hints_enabled": True,
+ }
+ # Read-only: answering must not mint an id the CLI would then disagree with.
+ assert not (home / ".repowise" / "platform.json").exists()
+
+
+async def test_identity_never_carries_the_install_id(
+ platform_client: AsyncClient, home: Path
+) -> None:
+ # The UI's links carry their source only, so the id has no reason to leave.
+ _write(home, "platform.json", {"anon_id": "abc123"})
+ assert "anon_id" not in await _identity(platform_client)
+
+
+ ("creds", "signed_in"),
+ [
+ ({"access_token": "tok"}, True),
+ ({"access_token": "tok", "stale": True}, False),
+ ({"refresh_token": "only"}, False),
+ (["not", "a", "dict"], False),
+ ],
+)
+async def test_identity_signed_in(
+ platform_client: AsyncClient, home: Path, creds: object, signed_in: bool
+) -> None:
+ _write(home, "credentials.json", creds)
+ assert (await _identity(platform_client))["signed_in"] is signed_in
+
+
+async def test_identity_hints_off_in_platform_json(
+ platform_client: AsyncClient, home: Path
+) -> None:
+ _write(home, "platform.json", {"hints_enabled": False})
+ assert (await _identity(platform_client))["hints_enabled"] is False
+
+
[email protected]("var", ["REPOWISE_NO_HINTS", "DO_NOT_TRACK"])
+async def test_identity_hints_off_by_env(
+ platform_client: AsyncClient, home: Path, monkeypatch: pytest.MonkeyPatch, var: str
+) -> None:
+ monkeypatch.setenv(var, "1")
+ assert (await _identity(platform_client))["hints_enabled"] is False
+
+
+_PUBLISHED = {
+ "outcome": "published",
+ "message": "Your repo is being indexed:",
+ "url": "https://repowise.dev/s/x/indexing?src=local_web_publish",
+ "details": ["line"],
+ "open_url": "https://repowise.dev/s/x/indexing?src=local_web_publish",
+ "repo": "o/n",
+}
+
+
+async def test_publish_runs_the_cli_and_returns_its_answer(
+ platform_client: AsyncClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ repo = await create_test_repo(platform_client)
+ calls: list[list[str]] = []
+
+ def fake_run(argv, **kwargs):
+ calls.append(argv)
+ assert kwargs["timeout"] == platform._TIMEOUT_SECONDS
+ return subprocess.CompletedProcess(argv, 0, stdout=json.dumps(_PUBLISHED), stderr="")
+
+ monkeypatch.setattr(platform.subprocess, "run", fake_run)
+ resp = await platform_client.post("/api/platform/publish", json={"repo_id": repo["id"]})
+
+ assert resp.status_code == 200
+ assert resp.json() == _PUBLISHED
+ assert calls == [
+ [
+ sys.executable,
+ "-m",
+ "repowise.cli.main",
+ "publish",
+ repo["local_path"],
+ "--format",
+ "json",
+ "--no-open",
+ "--src",
+ "local_web_publish",
+ ]
+ ]
+
+
+async def test_publish_passes_a_refusal_through(
+ platform_client: AsyncClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ repo = await create_test_repo(platform_client)
+ refusal = {**_PUBLISHED, "outcome": "signed_out", "message": "Sign in first", "url": None}
+ monkeypatch.setattr(
+ platform.subprocess,
+ "run",
+ lambda argv, **kw: subprocess.CompletedProcess(argv, 1, json.dumps(refusal), ""),
+ )
+ resp = await platform_client.post("/api/platform/publish", json={"repo_id": repo["id"]})
+ assert resp.status_code == 200
+ assert resp.json() == refusal
+
+
+ "failure",
+ [
+ FileNotFoundError("no python"),
+ subprocess.TimeoutExpired(["repowise"], 90),
+ "not json at all",
+ "[1, 2]",
+ ],
+)
+async def test_publish_answers_error_when_the_cli_cannot_run(
+ platform_client: AsyncClient, monkeypatch: pytest.MonkeyPatch, failure: object
+) -> None:
+ repo = await create_test_repo(platform_client)
+
+ def fake_run(argv, **kwargs):
+ if isinstance(failure, Exception):
+ raise failure
+ return subprocess.CompletedProcess(argv, 1, stdout=failure, stderr="Traceback")
+
+ monkeypatch.setattr(platform.subprocess, "run", fake_run)
+ resp = await platform_client.post("/api/platform/publish", json={"repo_id": repo["id"]})
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["outcome"] == "error"
+ assert "repowise publish" in body["message"]
+
+
+async def test_publish_unknown_repo_is_404(
+ platform_client: AsyncClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(platform.subprocess, "run", lambda *a, **k: pytest.fail("ran the CLI"))
+ resp = await platform_client.post("/api/platform/publish", json={"repo_id": "nope"})
+ assert resp.status_code == 404
+
+
+def test_cli_main_runs_as_a_module() -> None:
+ """The argv above relies on ``python -m repowise.cli.main`` running the CLI."""
+ proc = subprocess.run(
+ [sys.executable, "-m", "repowise.cli.main", "publish", "--help"],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ check=False,
+ )
+ assert proc.returncode == 0, proc.stderr
+ assert "--format" in proc.stdout