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
41 changes: 41 additions & 0 deletions desktop/App.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { forwardRef, useImperativeHandle } from "react";
import {
act,
cleanup,
render,
screen,
Expand Down Expand Up @@ -73,6 +74,7 @@ vi.mock("./bridge", () => ({
status: vi.fn(),
restoreSession: vi.fn(),
cloudRunStatus: vi.fn(),
confirmCloudRun: vi.fn(),
chooseWorkspace: vi.fn(),
closeWorkspace: vi.fn(),
cancelLocal: vi.fn(),
Expand Down Expand Up @@ -378,3 +380,42 @@ it("keeps the launch dialog and stops the run when saving fails", async () => {
).toBeDefined();
expect(desktop.analyseLocalFolder).not.toHaveBeenCalled();
});

it("shows the reviewed quote in the global toast and dismisses its expiry notice", async () => {
const expiry = Date.now() + 60_000;
vi.mocked(desktop.cloudRunStatus).mockResolvedValue({
phase: "quoted",
org: "quote-org",
job: "job-42",
ctu: 0,
deadline: new Date(expiry).toISOString(),
});
const user = userEvent.setup();
render(
<ConfirmProvider>
<App />
</ConfirmProvider>,
);
expect(
(await screen.findByText(/0 CTU seront débités/)).textContent,
).toBeDefined();
expect(
screen.getByText(/Organisation : quote-org.*Valable jusqu’au/),
).toBeDefined();
const now = vi.spyOn(Date, "now").mockReturnValue(expiry);
try {
await act(() => window.dispatchEvent(new Event("focus")));
} finally {
now.mockRestore();
}
vi.mocked(desktop.cloudRunStatus).mockResolvedValue({
phase: "expired",
org: "quote-org",
job: "job-42",
});
const expired = await screen.findByText(/Le devis pour quote-org a expiré/);
expect(screen.queryByText(/0 CTU seront débités/)).toBeNull();
expect(desktop.confirmCloudRun).not.toHaveBeenCalled();
await user.click(screen.getByRole("button", { name: "Fermer le message" }));
expect(expired.isConnected).toBe(false);
});
53 changes: 27 additions & 26 deletions desktop/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { desktop, errorMessage, native, type AnalyserStatus } from "./bridge";
import { Dialog, useConfirm } from "./components/Dialog";
import { isLocalSource } from "./launch";
import { AnalysisLaunch, type LaunchTarget } from "./features/AnalysisLaunch";
import { describe, running, useCloudRun } from "./useCloudRun";
import { describe, quoteDetails, running, useCloudRun } from "./useCloudRun";
import { Login } from "./components/Login";
import { Dashboard } from "./features/Dashboard";
import { Repositories } from "./features/Repositories";
Expand Down Expand Up @@ -219,6 +219,7 @@ export default function App() {
});
const editor = useRef<EditorHandle>(null);
const confirm = useConfirm();
const quote = cloudRun.phase.phase === "quoted" ? cloudRun.phase : undefined;
const orgRef = useRef(cloud.org);
orgRef.current = cloud.org;
useEffect(() => {
Expand Down Expand Up @@ -816,7 +817,7 @@ export default function App() {
<button
className="text-button"
disabled={cloudRun.busy}
onClick={() => void cloudRun.cancel(cloud.org)}
onClick={() => void cloudRun.cancel()}
>
Annuler
</button>
Expand Down Expand Up @@ -851,30 +852,30 @@ export default function App() {
</div>
{/* A quote is a decision, not news: nothing is spent until it is taken,
so it is offered wherever the reader happens to be. */}
{cloudRun.phase.phase === "quoted" &&
(page !== "analyses" || selectedJob) && (
<div className="toast decision" role="alert">
<span>
<strong>
{cloudRun.phase.ctu.toLocaleString("fr-FR")} CTU seront débités
</strong>
<small>Rien n’a encore été débité pour cette analyse.</small>
</span>
<button
className="primary"
disabled={cloudRun.busy}
onClick={() => void cloudRun.approve(cloud.org)}
>
Lancer l’analyse
</button>
<button
disabled={cloudRun.busy}
onClick={() => void cloudRun.cancel(cloud.org)}
>
Refuser
</button>
</div>
)}
{quote && (page !== "analyses" || selectedJob) && (
<div className="toast decision" role="alert">
<span>
<strong>
{quote.ctu.toLocaleString("fr-FR")} CTU seront débités
</strong>
<small>Rien n’a encore été débité pour cette analyse.</small>
<small>{quoteDetails(quote)}</small>
</span>
<button
className="primary"
disabled={cloudRun.busy}
onClick={() => void cloudRun.approve(quote.job)}
>
Lancer l’analyse
</button>
<button
disabled={cloudRun.busy}
onClick={() => void cloudRun.cancel(quote.job)}
>
Refuser
</button>
</div>
)}
{finishedJob &&
visibleCloudTarget &&
(page !== "analyses" || selectedJob) && (
Expand Down
4 changes: 2 additions & 2 deletions desktop/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ export const desktop = {
call<void>("cloud_run_start", { workspaceId, org, tools }),
cloudRunStatus: () => call<CloudPhase>("cloud_run_status"),
/** Approves the quote. This is the call that spends CTU. */
confirmCloudRun: (org: string) => call<void>("cloud_run_confirm", { org }),
confirmCloudRun: (job: string) => call<void>("cloud_run_confirm", { job }),
/** Stops a run, or refuses its quote; the organisation names the job. */
cancelCloudRun: (org?: string) => call<void>("cloud_run_cancel", { org }),
cancelCloudRun: (job?: string) => call<void>("cloud_run_cancel", { job }),
/** The folders and ctrace executable the previous session left behind. */
restoreSession: () =>
call<{ workspaces: Workspace[]; analyser: string | null }>(
Expand Down
59 changes: 59 additions & 0 deletions desktop/features/Analyses.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ it("renders report messages as text and sends a location to the editor", async (
/>,
);
expect(document.querySelector("img")).toBeNull();
expect(screen.queryByRole("navigation")).toBeNull();
// The whole row is the target now; its name carries the location first.
await userEvent.click(
screen.getByRole("button", { name: /src\/main\.c:14/ }),
Expand Down Expand Up @@ -226,6 +227,64 @@ it("counts what the search actually shows", async () => {
expect(screen.getByRole("heading", { name: /1 sur 3/ })).toBeDefined();
});

it("keeps a 5,000-finding report bounded while paging and searching", async () => {
const findings = Array.from({ length: 5_000 }, (_, i) => ({
rule: i >= 4_876 ? "late-match" : "ordinary",
level: i < 53 ? "error" : "warning",
path: "src/large.c",
line: i + 1,
message: `Diagnostic ${i + 1}`,
})).reverse();
const open = vi.fn();
const { container } = render(<Findings findings={findings} open={open} />);
const user = userEvent.setup();
const pagination = screen.getByRole("navigation", {
name: "Pagination des résultats",
});
const next = within(pagination).getByRole("button", { name: "Suivant" });
const previous = within(pagination).getByRole("button", {
name: "Précédent",
});
const expectPage = (range: string, rows = 50) => {
expect(within(pagination).getByRole("status").textContent).toBe(range);
expect(container.querySelectorAll("button.finding")).toHaveLength(rows);
};

expect(screen.getByRole("heading", { name: "Résultats 5000" })).toBeDefined();
expect(screen.getByRole("heading", { name: "Erreurs · 53" })).toBeDefined();
expect(screen.queryByText("Diagnostic 5000")).toBeNull();
expect(previous.getAttribute("aria-disabled")).toBe("true");
expectPage("1–50 sur 5000");
next.focus();
await user.keyboard("{Enter}");
expect(document.activeElement).toBe(next);
expectPage("51–100 sur 5000");
expect(screen.getByRole("heading", { name: "Erreurs · 53" })).toBeDefined();
expect(
screen.getByRole("heading", { name: "Avertissements · 4947" }),
).toBeDefined();
await user.click(next);
expectPage("101–150 sur 5000");
await user.click(previous);
expectPage("51–100 sur 5000");

await user.type(screen.getByLabelText("Filtrer les résultats"), "late-match");
expect(
screen.getByRole("heading", { name: "Résultats 124 sur 5000" }),
).toBeDefined();
expectPage("1–50 sur 124");
await user.click(screen.getByRole("button", { name: /src\/large\.c:5000/ }));
expect(open).toHaveBeenCalledWith("src/large.c", 5000);
await user.click(next);
await user.click(next);
expectPage("101–124 sur 124", 24);
expect(next.getAttribute("aria-disabled")).toBe("true");
await user.keyboard("{Enter}");
expectPage("101–124 sur 124", 24);
await user.click(screen.getByRole("button", { name: "Effacer le filtre" }));
expectPage("1–50 sur 5000");
});

it("marks a level with its letter, not its name", () => {
render(
<Findings
Expand Down
116 changes: 82 additions & 34 deletions desktop/features/Analyses.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ const GROUP: Record<string, string> = {
other: "Autres",
};

const FINDINGS_PER_PAGE = 50;

/** Reports of finished runs, which are immutable once written. */
const reportCache = new Map<string, string>();

Expand All @@ -70,11 +72,43 @@ export function Findings({
loading?: boolean;
}) {
const [search, setSearch] = useState("");
const filtered = findings.filter((f) =>
`${f.message} ${f.rule} ${f.path}`
.toLowerCase()
.includes(search.trim().toLowerCase()),
);
const [page, setPage] = useState(0);
const query = search.trim().toLowerCase();
const { groups, matchCount } = useMemo(() => {
const bySeverity = new Map<string, Finding[]>(
Object.keys(GROUP).map((level) => [level, []]),
);
const other: Finding[] = [];
bySeverity.set("other", other);
for (const finding of findings) {
if (
query &&
!`${finding.message} ${finding.rule} ${finding.path}`
.toLowerCase()
.includes(query)
) {
continue;
}
const group = bySeverity.get(finding.level) ?? other;
group.push(finding);
}
let count = 0;
const groups = Array.from(bySeverity, ([level, findings]) => {
const start = count;
count += findings.length;
return { level, findings, start };
});
return { groups, matchCount: count };
}, [findings, query]);

const lastPage = Math.max(0, Math.ceil(matchCount / FINDINGS_PER_PAGE) - 1);
const currentPage = Math.min(page, lastPage);
const start = currentPage * FINDINGS_PER_PAGE;
const end = Math.min(start + FINDINGS_PER_PAGE, matchCount);
const updateSearch = (value: string) => {
setSearch(value);
setPage(0);
};
return (
<section>
<div className="section-heading">
Expand All @@ -83,8 +117,8 @@ export function Findings({
<span className="muted">
{loading
? "…"
: search.trim()
? `${filtered.length} sur ${findings.length}`
: query
? `${matchCount} sur ${findings.length}`
: findings.length}
</span>
</h2>
Expand All @@ -94,11 +128,11 @@ export function Findings({
aria-label="Filtrer les résultats"
placeholder="Fichier, règle, message…"
value={search}
onChange={(e) => setSearch(e.target.value)}
onChange={(e) => updateSearch(e.target.value)}
/>
</label>
{search && (
<button onClick={() => setSearch("")}>Effacer le filtre</button>
<button onClick={() => updateSearch("")}>Effacer le filtre</button>
)}
</div>
{loading &&
Expand All @@ -115,35 +149,48 @@ export function Findings({
<p className="skeleton line" />
</article>
))}
{!loading && lastPage > 0 && (
<nav
className="findings-pagination inline"
aria-label="Pagination des résultats"
>
<button
type="button"
aria-disabled={currentPage === 0}
onClick={() => {
if (currentPage > 0) setPage(currentPage - 1);
}}
>
Précédent
</button>
<span className="muted small" role="status">
{start + 1}–{end} sur {matchCount}
</span>
<button
type="button"
aria-disabled={currentPage === lastPage}
onClick={() => {
if (currentPage < lastPage) setPage(currentPage + 1);
}}
>
Suivant
</button>
</nav>
)}
{!loading &&
// Grouped by severity: a reader scanning a long list wants the errors
// first, and the level was otherwise only a small mark on each row.
(
[
...["error", "warning", "note", "info"].map(
(level): [string, Finding[]] => [
level,
filtered.filter((f) => f.level === level),
],
),
[
"other",
filtered.filter(
(f) => !["error", "warning", "note", "info"].includes(f.level),
),
] as [string, Finding[]],
] as [string, Finding[]][]
)
.filter(([, group]) => group.length > 0)
.map(([level, group]) => (
groups.map(({ level, findings: group, start: groupStart }) => {
const first = Math.max(0, start - groupStart);
const last = Math.min(group.length, end - groupStart);
if (first >= last) return null;
return (
<div className="finding-group" key={level}>
<h3 className="muted small">
{GROUP[level] ?? level} · {group.length}
{GROUP[level]} · {group.length}
</h3>
{group.map((f, i) => (
{group.slice(first, last).map((f, i) => (
<button
className={`finding ${f.level}`}
key={`${f.path}-${f.line}-${i}`}
key={`${f.path}-${f.line}-${first + i}`}
disabled={!f.path}
title={f.path ? "Ouvrir dans l’éditeur" : "Aucun emplacement"}
onClick={() => open(f.path, f.line)}
Expand Down Expand Up @@ -173,8 +220,9 @@ export function Findings({
</button>
))}
</div>
))}
{!loading && !filtered.length && (
);
})}
{!loading && !matchCount && (
<p className="muted">
{findings.length
? "Aucun résultat ne correspond au filtre."
Expand Down
Loading
Loading