Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ repos:
- id: check-toml
- id: check-added-large-files
args: ['--maxkb=1024']
# dist/ is committed on purpose (see src/profiles/web/.gitignore):
# the built frontend ships with the package, and the minified
# bundle legitimately exceeds 1 MB.
exclude: ^src/profiles/web/dist/

# Ruff - Linter et formatter
- repo: https://github.com/astral-sh/ruff-pre-commit
Expand Down
25 changes: 25 additions & 0 deletions src/profiles/core/telemetry/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,31 @@ def web_client_left(logger: logging.Logger, *, ip: str, idle_s: int) -> None:
logger.info('WEB_CLIENT event="disconnected" ip="%s" idle_s=%d', ip, idle_s)


def toast(
logger: logging.Logger,
*,
source: str,
kind: str,
message: str,
applied: bool | None = None,
) -> None:
"""Emit TOAST — a UI toast notification mirrored into the log (issue #194).

DEBUG by design ("nice to have, zero noise"): the record reaches
``profiles.log`` only when the config's ``verbose`` is ``DEBUG``.
``source`` distinguishes server-buffered events (``server``, logged at
the :meth:`ServerState.record_external_event` choke point) from
frontend toasts relayed by ``POST /api/logs/client`` (``web``).
``applied`` is only emitted when known — server handoff events carry
it, frontend toasts do not.
"""
parts = [f"source={_quote(source)}", f"kind={_quote(kind)}"]
if applied is not None:
parts.append(f"applied={_bool(applied)}")
parts.append(f"msg={_quote(message)}")
logger.debug("TOAST %s", " ".join(parts))


def bind_changed(logger: logging.Logger, *, host: str, lan: bool) -> None:
"""Emit BIND_CHANGED — the server rebound between LAN exposure and loopback."""
logger.info('BIND_CHANGED host="%s" lan=%s', host, "true" if lan else "false")
Expand Down
33 changes: 32 additions & 1 deletion src/profiles/server/routes/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,35 @@

from __future__ import annotations

import logging
from typing import Literal

from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field

from profiles.core.telemetry import log_viewer
from profiles.core.telemetry import events, log_viewer
from profiles.core.telemetry.diagnostics import default_log_path

router = APIRouter(prefix="/api/logs", tags=["logs"])

# Server-side telemetry logger (the "profiles" logger writes profiles.log);
# same module-level lookup as server/app.py.
_LOGGER = logging.getLogger("profiles")

# Matches the default used by ProFileApp; overridable per request.
_DEFAULT_LOG_PATH = default_log_path()

# Frontend toasts are one-liners by construction; the cap keeps a stray or
# hostile client (the server can be LAN-exposed) from flooding profiles.log.
_MAX_CLIENT_MESSAGE_LENGTH = 500


class ClientLogRequest(BaseModel):
"""Body of ``POST /api/logs/client`` — a frontend toast mirror (issue #194)."""

message: str = Field(min_length=1, max_length=_MAX_CLIENT_MESSAGE_LENGTH)
kind: Literal["info", "error"] = "info"


@router.get("")
async def get_logs(
Expand Down Expand Up @@ -60,3 +79,15 @@ async def get_logs(
for entry in entries
],
}


@router.post("/client")
async def post_client_log(payload: ClientLogRequest) -> dict:
"""Mirror a frontend toast into ``profiles.log`` at DEBUG (issue #194).

Logging only, fire-and-forget from the client's perspective: failures
here must never surface in the UI, and this endpoint must never buffer
an external event (no toast feedback loop).
"""
events.toast(_LOGGER, source="web", kind=payload.kind, message=payload.message)
return {"status": "ok"}
17 changes: 17 additions & 0 deletions src/profiles/server/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@

from __future__ import annotations

import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Protocol

from profiles.core.config.io.yaml_io import PRIMARY_CONFIG_NAME, find_config_file
from profiles.core.config.models import AppConfig
from profiles.core.telemetry import events

_MAX_EXTERNAL_EVENTS = 50

# Server-side telemetry logger (the "profiles" logger writes profiles.log);
# same module-level lookup as server/app.py.
_LOGGER = logging.getLogger("profiles")


class BindableServer(Protocol):
"""The subset of ``BackgroundServer`` the route layer touches.
Expand Down Expand Up @@ -76,6 +82,10 @@ def record_external_event(

The buffer is capped so a long-lived server cannot grow it
without bound even when no client is polling.

Every event is also mirrored to the logger as a DEBUG TOAST
record (issue #194): the single choke point covers all current
and future producers (odoc applier, instance handoff route).
"""
self._external_event_seq += 1
self._external_events.append(
Expand All @@ -89,6 +99,13 @@ def record_external_event(
if len(self._external_events) > _MAX_EXTERNAL_EVENTS:
excess = len(self._external_events) - _MAX_EXTERNAL_EVENTS
del self._external_events[:excess]
events.toast(
_LOGGER,
source="server",
kind=kind,
message=message,
applied=config_applied,
)
return self._external_event_seq

def external_events_after(self, after_id: int) -> list[dict[str, Any]]:
Expand Down
1 change: 0 additions & 1 deletion src/profiles/web/dist/assets/index-CUYujBAx.css

This file was deleted.

448 changes: 0 additions & 448 deletions src/profiles/web/dist/assets/index-C_WnxvAZ.js

This file was deleted.

1 change: 1 addition & 0 deletions src/profiles/web/dist/assets/index-DTCv5-8y.css

Large diffs are not rendered by default.

458 changes: 458 additions & 0 deletions src/profiles/web/dist/assets/index-Dsvw1NQU.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/profiles/web/dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ProFiles</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<script type="module" crossorigin src="/assets/index-C_WnxvAZ.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-CUYujBAx.css">
<script type="module" crossorigin src="/assets/index-Dsvw1NQU.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DTCv5-8y.css">
<link rel="manifest" href="/manifest.webmanifest"><script id="vite-plugin-pwa:register-sw" src="/registerSW.js"></script></head>
<body class="antialiased selection:bg-indigo-500 selection:text-white">
<div id="root"></div>
Expand Down
2 changes: 1 addition & 1 deletion src/profiles/web/dist/sw.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions src/profiles/web/src/api/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
fetchConfigContent,
fetchConfigTemplate,
fetchNotifications,
postClientLog,
reloadConfig,
saveConfigFile,
saveConfigFileAs,
Expand Down Expand Up @@ -434,3 +435,38 @@ describe("saveConfigFileAs", () => {
expect(err.message).toContain("already exists");
});
});

describe("postClientLog", () => {
afterEach(() => {
vi.unstubAllGlobals();
});

it("POSTs the toast to /api/logs/client", async () => {
const fetchMock = vi.fn(
async () => new Response(JSON.stringify({ status: "ok" }), { status: 200 }),
);
vi.stubGlobal("fetch", fetchMock);

postClientLog("URL copied to clipboard.", "info");

expect(fetchMock).toHaveBeenCalledWith("/api/logs/client", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "URL copied to clipboard.", kind: "info" }),
});
});

it("swallows fetch rejections — logging must never break the UI", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => {
throw new Error("server unreachable");
}),
);

expect(() => postClientLog("Boom", "error")).not.toThrow();

// Flush the microtask queue: an unhandled rejection would fail the run.
await new Promise((resolve) => setTimeout(resolve, 0));
});
});
17 changes: 17 additions & 0 deletions src/profiles/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,23 @@ export async function fetchNotifications(afterId: number): Promise<{ events: Ext
return res.json();
}

/**
* Mirror a UI toast into the server log at DEBUG (issue #194).
*
* Fire-and-forget by contract: telemetry must never break the UI, so the
* call is not awaited and every failure is swallowed silently — a toast
* already served its purpose on screen before this fires.
*/
export function postClientLog(message: string, kind: "info" | "error"): void {
void fetch("/api/logs/client", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message, kind }),
}).catch(() => {
// Server unreachable — nothing to recover; the log record is best-effort.
});
}

export async function openLogFile(): Promise<{ status: string; message: string }> {
const res = await fetch("/api/actions/open-log", {
method: "POST",
Expand Down
10 changes: 5 additions & 5 deletions src/profiles/web/src/hooks/useExternalEvents.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ describe("useExternalEvents", () => {
expect(fetchNotificationsSpy).toHaveBeenCalledTimes(1);
expect(fetchNotificationsSpy).toHaveBeenNthCalledWith(1, 0);
expect(showToast).toHaveBeenCalledTimes(2);
expect(showToast).toHaveBeenNthCalledWith(1, "First handoff");
expect(showToast).toHaveBeenNthCalledWith(2, "Second handoff");
expect(showToast).toHaveBeenNthCalledWith(1, "First handoff", "info", { mirror: false });
expect(showToast).toHaveBeenNthCalledWith(2, "Second handoff", "info", { mirror: false });

// The interval re-arms: the next tick polls again (4000ms later).
fetchNotificationsSpy.mockResolvedValueOnce({ events: [] });
Expand Down Expand Up @@ -156,7 +156,7 @@ describe("useExternalEvents", () => {
await vi.advanceTimersByTimeAsync(4000);
});
expect(showToast).toHaveBeenCalledTimes(1);
expect(showToast).toHaveBeenCalledWith("Recovered");
expect(showToast).toHaveBeenCalledWith("Recovered", "info", { mirror: false });
});

it("onConfigApplied failures are swallowed; the toast still fires", async () => {
Expand All @@ -172,7 +172,7 @@ describe("useExternalEvents", () => {
});
expect(onConfigApplied).toHaveBeenCalledTimes(1);
expect(showToast).toHaveBeenCalledTimes(1);
expect(showToast).toHaveBeenCalledWith("Applied anyway");
expect(showToast).toHaveBeenCalledWith("Applied anyway", "info", { mirror: false });
});

it("uses the latest onConfigApplied identity without re-subscribing", async () => {
Expand Down Expand Up @@ -204,7 +204,7 @@ describe("useExternalEvents", () => {
// The LATEST identity is the one invoked.
expect(latestApply).toHaveBeenCalledTimes(1);
expect(firstApply).not.toHaveBeenCalled();
expect(latestToast).toHaveBeenCalledWith("Handoff");
expect(latestToast).toHaveBeenCalledWith("Handoff", "info", { mirror: false });
setIntervalSpy.mockRestore();
});

Expand Down
8 changes: 6 additions & 2 deletions src/profiles/web/src/hooks/useExternalEvents.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useRef } from "react";
import { fetchNotifications } from "../api/client";
import type { ExternalEvent } from "../api/types";
import type { ShowToast } from "./useToast";

/** Poll interval for server-side UI events (config handoff toasts). */
const NOTIFICATION_POLL_MS = 4000;
Expand All @@ -20,7 +21,7 @@ const NOTIFICATION_POLL_MS = 4000;
*/
export function useExternalEvents(deps: {
onConfigApplied: () => Promise<void>;
showToast: (msg: string, kind?: "info" | "error") => void;
showToast: ShowToast;
}): void {
const lastEventIdRef = useRef(0);
// Latest deps for the interval callback (avoids stale closures — the
Expand Down Expand Up @@ -48,7 +49,10 @@ export function useExternalEvents(deps: {
// Re-applying is best-effort; the toast still explains what happened.
}
}
depsRef.current.showToast(evt.message);
// mirror: false — the server already logged this event as a TOAST
// record at the record_external_event choke point (issue #194);
// relaying it back through POST /api/logs/client would duplicate it.
depsRef.current.showToast(evt.message, "info", { mirror: false });
}
};
const id = setInterval(() => void poll(), NOTIFICATION_POLL_MS);
Expand Down
45 changes: 43 additions & 2 deletions src/profiles/web/src/hooks/useToast.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, renderHook } from "@testing-library/react";

/**
Expand All @@ -8,9 +8,21 @@ import { act, cleanup, renderHook } from "@testing-library/react";
* auto-dismiss, the error toast's longer 10000ms lifetime, the empty-message
* guard (never blank an existing toast), the pending-timer replacement when a
* new toast arrives, the immediate `dismissToast` clearing, and the default
* `info` kind.
* `info` kind. Issue #194 adds the profiles.log mirror: every toast is
* relayed to `POST /api/logs/client` unless suppressed with `mirror: false`.
*/
import { useToast } from "./useToast";
import { postClientLog } from "../api/client";

vi.mock("../api/client", () => ({
postClientLog: vi.fn(),
}));

const postClientLogSpy = vi.mocked(postClientLog);

beforeEach(() => {
vi.clearAllMocks();
});

afterEach(() => {
cleanup();
Expand Down Expand Up @@ -105,4 +117,33 @@ describe("useToast", () => {
act(() => result.current.showToast("Default"));
expect(result.current.toastMessage).toEqual({ message: "Default", kind: "info" });
});

// -----------------------------------------------------------------
// profiles.log mirror (issue #194)
// -----------------------------------------------------------------

it("showToast mirrors to the client-log endpoint", () => {
const { result } = renderHook(() => useToast());
act(() => result.current.showToast("Logged please"));
expect(postClientLogSpy).toHaveBeenCalledWith("Logged please", "info");
});

it("error toasts are mirrored with their kind", () => {
const { result } = renderHook(() => useToast());
act(() => result.current.showToast("Boom", "error"));
expect(postClientLogSpy).toHaveBeenCalledWith("Boom", "error");
});

it("mirror is suppressed with { mirror: false } (server-originated toasts)", () => {
const { result } = renderHook(() => useToast());
act(() => result.current.showToast("Handoff", "info", { mirror: false }));
expect(result.current.toastMessage).toEqual({ message: "Handoff", kind: "info" });
expect(postClientLogSpy).not.toHaveBeenCalled();
});

it("empty messages are not mirrored", () => {
const { result } = renderHook(() => useToast());
act(() => result.current.showToast(""));
expect(postClientLogSpy).not.toHaveBeenCalled();
});
});
Loading