diff --git a/desktop/App.test.tsx b/desktop/App.test.tsx
index 8cb3458..f7e5bcc 100644
--- a/desktop/App.test.tsx
+++ b/desktop/App.test.tsx
@@ -1,5 +1,6 @@
import { forwardRef, useImperativeHandle } from "react";
import {
+ act,
cleanup,
render,
screen,
@@ -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(),
@@ -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(
+
+
+ ,
+ );
+ 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);
+});
diff --git a/desktop/App.tsx b/desktop/App.tsx
index bd8cd3e..cd08b1f 100644
--- a/desktop/App.tsx
+++ b/desktop/App.tsx
@@ -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";
@@ -219,6 +219,7 @@ export default function App() {
});
const editor = useRef(null);
const confirm = useConfirm();
+ const quote = cloudRun.phase.phase === "quoted" ? cloudRun.phase : undefined;
const orgRef = useRef(cloud.org);
orgRef.current = cloud.org;
useEffect(() => {
@@ -816,7 +817,7 @@ export default function App() {
@@ -851,30 +852,30 @@ export default function App() {
{/* 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) && (
-
-
-
- {cloudRun.phase.ctu.toLocaleString("fr-FR")} CTU seront débités
-
- Rien n’a encore été débité pour cette analyse.
-
-
-
-
- )}
+ {quote && (page !== "analyses" || selectedJob) && (
+
+
+
+ {quote.ctu.toLocaleString("fr-FR")} CTU seront débités
+
+ Rien n’a encore été débité pour cette analyse.
+ {quoteDetails(quote)}
+
+
+
+
+ )}
{finishedJob &&
visibleCloudTarget &&
(page !== "analyses" || selectedJob) && (
diff --git a/desktop/bridge.ts b/desktop/bridge.ts
index b58e714..7032c1a 100644
--- a/desktop/bridge.ts
+++ b/desktop/bridge.ts
@@ -41,9 +41,9 @@ export const desktop = {
call("cloud_run_start", { workspaceId, org, tools }),
cloudRunStatus: () => call("cloud_run_status"),
/** Approves the quote. This is the call that spends CTU. */
- confirmCloudRun: (org: string) => call("cloud_run_confirm", { org }),
+ confirmCloudRun: (job: string) => call("cloud_run_confirm", { job }),
/** Stops a run, or refuses its quote; the organisation names the job. */
- cancelCloudRun: (org?: string) => call("cloud_run_cancel", { org }),
+ cancelCloudRun: (job?: string) => call("cloud_run_cancel", { job }),
/** The folders and ctrace executable the previous session left behind. */
restoreSession: () =>
call<{ workspaces: Workspace[]; analyser: string | null }>(
diff --git a/desktop/features/Analyses.test.tsx b/desktop/features/Analyses.test.tsx
index f9f34d6..822eea0 100644
--- a/desktop/features/Analyses.test.tsx
+++ b/desktop/features/Analyses.test.tsx
@@ -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/ }),
@@ -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();
+ 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(
= {
other: "Autres",
};
+const FINDINGS_PER_PAGE = 50;
+
/** Reports of finished runs, which are immutable once written. */
const reportCache = new Map();
@@ -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(
+ 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 (
@@ -83,8 +117,8 @@ export function Findings({
{loading
? "…"
- : search.trim()
- ? `${filtered.length} sur ${findings.length}`
+ : query
+ ? `${matchCount} sur ${findings.length}`
: findings.length}
@@ -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)}
/>
{search && (
-
+
)}
{loading &&
@@ -115,35 +149,48 @@ export function Findings({
))}
+ {!loading && lastPage > 0 && (
+
+ )}
{!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 (
- {GROUP[level] ?? level} · {group.length}
+ {GROUP[level]} · {group.length}
- {group.map((f, i) => (
+ {group.slice(first, last).map((f, i) => (
))}
- ))}
- {!loading && !filtered.length && (
+ );
+ })}
+ {!loading && !matchCount && (
{findings.length
? "Aucun résultat ne correspond au filtre."
diff --git a/desktop/features/CloudRun.test.tsx b/desktop/features/CloudRun.test.tsx
index 6f0de78..31f9990 100644
--- a/desktop/features/CloudRun.test.tsx
+++ b/desktop/features/CloudRun.test.tsx
@@ -41,6 +41,7 @@ function show(onFinished = vi.fn()) {
it("shows the cost and waits for explicit approval in the run panel", async () => {
vi.mocked(desktop.cloudRunStatus).mockResolvedValue({
phase: "quoted",
+ org: "quoted-org",
job: "job-1",
ctu: 4000,
deadline: "2030-01-01T00:00:00Z",
@@ -49,8 +50,29 @@ it("shows the cost and waits for explicit approval in the run panel", async () =
const price = await screen.findByText(/4\s?000 CTU/);
expect(price.textContent).toContain("Rien n’a encore été débité");
expect(
- screen.getByRole("button", { name: "Confirmer le devis" }),
+ screen.getByText(/Organisation : quoted-org.*Valable jusqu’au/),
).toBeDefined();
+ const confirm = screen.getByRole("button", { name: "Confirmer le devis" });
+ expect(desktop.confirmCloudRun).not.toHaveBeenCalled();
+ await userEvent.click(confirm);
+ expect(desktop.confirmCloudRun).toHaveBeenCalledWith("job-1");
+});
+
+it("shows that a quote expired and allows a new run", async () => {
+ vi.mocked(desktop.cloudRunStatus).mockResolvedValue({
+ phase: "expired",
+ job: "job-1",
+ org: "alpha",
+ });
+ show();
+ expect(await screen.findByText(/Le devis pour alpha a expiré/)).toBeDefined();
+ expect(
+ screen.queryByRole("button", { name: "Confirmer le devis" }),
+ ).toBeNull();
+ await userEvent.click(
+ screen.getByRole("button", { name: "Analyser dans le cloud" }),
+ );
+ expect(desktop.startCloudRun).toHaveBeenCalledWith("C:/work/app", "alpha");
expect(desktop.confirmCloudRun).not.toHaveBeenCalled();
});
diff --git a/desktop/features/CloudRun.tsx b/desktop/features/CloudRun.tsx
index 3df027c..591a149 100644
--- a/desktop/features/CloudRun.tsx
+++ b/desktop/features/CloudRun.tsx
@@ -3,6 +3,8 @@ import {
type CloudRunModel,
describe,
elapsed,
+ quoteDetails,
+ quoteExpiredMessage,
running as active,
} from "../useCloudRun";
@@ -45,7 +47,8 @@ export function CloudRun({
}) {
const { phase, seconds, busy } = run;
const startRun = () => void run.start(workspace, org);
- const stop = () => void run.cancel(org);
+ const stop = () =>
+ void run.cancel(phase.phase === "quoted" ? phase.job : undefined);
// Nothing has happened and this panel cannot start anything: showing an
// empty box headed "Analyser dans le cloud" only competes with the button
@@ -62,7 +65,7 @@ export function CloudRun({
)}
- {showStart && phase.phase === "idle" && (
+ {showStart && (phase.phase === "idle" || phase.phase === "expired") && (
)}
+ {phase.phase === "expired" && (
+ {quoteExpiredMessage(phase.org)}
+ )}
+
{phase.phase === "running" && (
{" "}
@@ -133,9 +141,9 @@ export function CloudRun({
)}
{(active(phase) || phase.phase === "quoted") && (
- void stop()}>
+
- Annuler
+ {phase.phase === "quoted" ? "Refuser" : "Annuler"}
)}
diff --git a/desktop/styles.css b/desktop/styles.css
index fb79ea6..12babe6 100644
--- a/desktop/styles.css
+++ b/desktop/styles.css
@@ -1446,6 +1446,13 @@ dialog label {
/* Findings grouped by severity: the heading separates the groups without
turning each into a boxed section. */
+.findings-pagination {
+ margin-bottom: 12px;
+}
+.findings-pagination button[aria-disabled="true"] {
+ opacity: 0.5;
+ cursor: default;
+}
.finding-group + .finding-group {
margin-top: 18px;
}
diff --git a/desktop/types.ts b/desktop/types.ts
index dc1bd50..0f4f225 100644
--- a/desktop/types.ts
+++ b/desktop/types.ts
@@ -88,7 +88,14 @@ export type CloudPhase =
| { phase: "uploading"; files: number; total: number }
| { phase: "verifying" }
| { phase: "quoting" }
- | { phase: "quoted"; job: string; ctu: number; deadline: string }
+ | {
+ phase: "quoted";
+ job: string;
+ ctu: number;
+ org: string;
+ deadline: string | null;
+ }
+ | { phase: "expired"; job: string; org: string }
| { phase: "running"; job: string }
| { phase: "done"; job: string }
| { phase: "failed"; reason: string }
diff --git a/desktop/useCloudRun.test.ts b/desktop/useCloudRun.test.ts
index 115ad05..69e2f3b 100644
--- a/desktop/useCloudRun.test.ts
+++ b/desktop/useCloudRun.test.ts
@@ -1,5 +1,208 @@
-import { describe as suite, expect, it } from "vitest";
-import { describe, elapsed, running } from "./useCloudRun";
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, describe as suite, expect, it, vi } from "vitest";
+import { desktop } from "./bridge";
+import type { CloudPhase } from "./types";
+import { describe, elapsed, running, useCloudRun } from "./useCloudRun";
+
+vi.mock("./bridge", () => ({
+ native: true,
+ desktop: {
+ cloudRunStatus: vi.fn(),
+ startCloudRun: vi.fn(),
+ confirmCloudRun: vi.fn(),
+ cancelCloudRun: vi.fn(),
+ },
+ errorMessage: (error: unknown) => String(error),
+}));
+
+afterEach(() => {
+ cleanup();
+ vi.resetAllMocks();
+ vi.useRealTimers();
+});
+
+async function advance(ms: number) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms);
+ });
+}
+
+suite("useCloudRun", () => {
+ it("retries attachment, ticks through changing progress, and resets at phase transitions", async () => {
+ vi.useFakeTimers();
+ const status = vi.mocked(desktop.cloudRunStatus);
+ let phase: CloudPhase = { phase: "packing", files: 1, bytes: 42 };
+ status
+ .mockRejectedValueOnce(new Error("Native unavailable"))
+ .mockImplementationOnce(
+ () => new Promise((resolve) => setTimeout(() => resolve(phase), 250)),
+ )
+ .mockImplementation(async () => ({ ...phase }));
+ const observe = vi.fn();
+ const { result } = renderHook(() => {
+ observe();
+ return useCloudRun({ notify: vi.fn(), onFinished: vi.fn() });
+ });
+
+ await advance(1000);
+ await advance(250);
+ expect(result.current.phase).toEqual(phase);
+ expect(result.current.seconds).toBe(0);
+
+ phase = { phase: "packing", files: 2, bytes: 84 };
+ await advance(1000);
+ expect(result.current.phase).toEqual(phase);
+ expect(result.current.seconds).toBe(1);
+ await advance(1000);
+ expect(result.current.seconds).toBe(2);
+
+ phase = { phase: "verifying" };
+ await advance(1000);
+ expect(result.current.phase).toEqual(phase);
+ expect(result.current.seconds).toBe(0);
+ await advance(1000);
+ expect(result.current.seconds).toBe(1);
+
+ phase = { phase: "idle" };
+ await advance(1000);
+ expect(result.current.seconds).toBe(0);
+ const polls = status.mock.calls.length;
+ const renders = observe.mock.calls.length;
+ await advance(10000);
+ expect(status).toHaveBeenCalledTimes(polls);
+ expect(observe).toHaveBeenCalledTimes(renders);
+ });
+
+ it("watches a start and approval while native commands are still pending", async () => {
+ vi.useFakeTimers();
+ const status = vi.mocked(desktop.cloudRunStatus);
+ const onFinished = vi.fn();
+ let phase: CloudPhase = { phase: "idle" };
+ status.mockImplementation(async () => ({ ...phase }));
+ let resolveStart = () => {};
+ let resolveConfirm = () => {};
+ vi.mocked(desktop.startCloudRun).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveStart = resolve;
+ }),
+ );
+ vi.mocked(desktop.confirmCloudRun).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveConfirm = resolve;
+ }),
+ );
+ const { result } = renderHook(() =>
+ useCloudRun({ notify: vi.fn(), onFinished }),
+ );
+ await advance(0);
+ await advance(5000);
+ expect(status).toHaveBeenCalledTimes(1);
+
+ let start: Promise;
+ act(() => {
+ start = result.current.start("workspace", "org");
+ });
+ phase = { phase: "packing", files: 0, bytes: 0 };
+ await advance(1000);
+ expect(result.current.phase).toEqual(phase);
+ expect(result.current.busy).toBe(true);
+
+ phase = { phase: "quoted", job: "job", org: "org", ctu: 1, deadline: null };
+ await act(async () => {
+ resolveStart();
+ expect(await start).toBe(true);
+ });
+ expect(result.current.phase).toEqual(phase);
+ const quotePolls = status.mock.calls.length;
+ await advance(5000);
+ expect(status).toHaveBeenCalledTimes(quotePolls);
+
+ let confirm: Promise;
+ act(() => {
+ confirm = result.current.approve("job");
+ });
+ phase = { phase: "running", job: "job" };
+ await advance(1000);
+ expect(result.current.phase).toEqual(phase);
+ await advance(1000);
+ expect(result.current.seconds).toBe(1);
+ expect(result.current.busy).toBe(true);
+
+ phase = { phase: "done", job: "job" };
+ await act(async () => {
+ resolveConfirm();
+ expect(await confirm).toBe(true);
+ });
+ expect(result.current.phase).toEqual(phase);
+ expect(result.current.busy).toBe(false);
+ expect(onFinished).toHaveBeenCalledExactlyOnceWith("job");
+ const donePolls = status.mock.calls.length;
+ await advance(5000);
+ expect(status).toHaveBeenCalledTimes(donePolls);
+ });
+
+ it("expires a parked quote at the deadline without polling for it", async () => {
+ vi.useFakeTimers();
+ const status = vi.mocked(desktop.cloudRunStatus).mockResolvedValue({
+ phase: "quoted",
+ org: "alpha",
+ job: "job-1",
+ ctu: 0,
+ deadline: new Date(Date.now() + 3000).toISOString(),
+ });
+ const notify = vi.fn();
+ const { result } = renderHook(() =>
+ useCloudRun({ notify, onFinished: vi.fn() }),
+ );
+ await advance(0);
+ await advance(2999);
+ expect(result.current.phase.phase).toBe("quoted");
+ await advance(1);
+ expect(result.current.phase).toEqual({
+ phase: "expired",
+ org: "alpha",
+ job: "job-1",
+ });
+ expect(notify).toHaveBeenCalledTimes(1);
+ expect(status).toHaveBeenCalledTimes(1);
+ });
+
+ it("recovers a failed status refresh after cancelling a parked quote", async () => {
+ vi.useFakeTimers();
+ const status = vi.mocked(desktop.cloudRunStatus);
+ const quote = {
+ phase: "quoted",
+ job: "job",
+ ctu: 1,
+ org: "org",
+ deadline: null,
+ } as const;
+ const cancelled = { phase: "cancelled", spent: false } as const;
+ status
+ .mockResolvedValueOnce(quote)
+ .mockRejectedValueOnce(new Error("Native unavailable"))
+ .mockResolvedValue(cancelled);
+ vi.mocked(desktop.cancelCloudRun).mockResolvedValue(undefined);
+ const { result } = renderHook(() =>
+ useCloudRun({ notify: vi.fn(), onFinished: vi.fn() }),
+ );
+ await advance(0);
+ expect(result.current.phase).toEqual(quote);
+
+ await act(async () => {
+ expect(await result.current.cancel("job")).toBe(true);
+ });
+ expect(result.current.phase).toEqual(quote);
+ expect(result.current.busy).toBe(false);
+ await advance(1000);
+ expect(result.current.phase).toEqual(cancelled);
+
+ await advance(5000);
+ expect(status).toHaveBeenCalledTimes(3);
+ });
+});
suite("describe", () => {
it("names every working phase with a figure that changes", () => {
@@ -32,9 +235,15 @@ suite("describe", () => {
it("says nothing when nothing is happening", () => {
expect(describe({ phase: "idle" }, 0)).toBeNull();
expect(describe({ phase: "done", job: "j" }, 0)).toBeNull();
- expect(running({ phase: "quoted", job: "j", ctu: 1, deadline: "" })).toBe(
- false,
- );
+ expect(
+ running({
+ phase: "quoted",
+ job: "j",
+ ctu: 1,
+ org: "alpha",
+ deadline: null,
+ }),
+ ).toBe(false);
expect(elapsed(0)).toBe("0 s");
});
});
diff --git a/desktop/useCloudRun.ts b/desktop/useCloudRun.ts
index b21b87a..86a17e0 100644
--- a/desktop/useCloudRun.ts
+++ b/desktop/useCloudRun.ts
@@ -23,8 +23,8 @@ export type CloudRunModel = {
/** Each resolves to whether the platform accepted the action; the reason
for a refusal has already been shown. */
start: (workspace: string, org: string) => Promise;
- approve: (org: string) => Promise;
- cancel: (org?: string) => Promise;
+ approve: (job: string) => Promise;
+ cancel: (job?: string) => Promise;
};
/**
@@ -42,10 +42,19 @@ export function useCloudRun({
/** Called once per run, when its results are ready to be opened. */
onFinished: (job: string) => void;
}): CloudRunModel {
- const [phase, setPhase] = useState(IDLE);
- const [busy, setBusy] = useState(false);
- const [seconds, setSeconds] = useState(0);
- const startedAt = useRef(Date.now());
+ const [status, setStatus] = useState<{
+ phase: CloudPhase;
+ startedAt: number;
+ needsRefresh: boolean;
+ } | null>(null);
+ const [pending, setPending] = useState(0);
+ const [clock, setClock] = useState(0);
+ const statusRequest = useRef(0);
+ const phase = status?.phase ?? IDLE;
+ const startedAt = running(phase) ? status?.startedAt : undefined;
+ const busy = pending > 0;
+ const watching =
+ status === null || status.needsRefresh || busy || startedAt !== undefined;
// Runs already announced. A run finishes once, however many times the status
// is polled afterwards.
const announced = useRef(new Set());
@@ -53,35 +62,78 @@ export function useCloudRun({
finished.current = onFinished;
const poll = useCallback(async () => {
+ const request = ++statusRequest.current;
try {
- setPhase(await desktop.cloudRunStatus());
+ const next = await desktop.cloudRunStatus();
+ if (request !== statusRequest.current) return;
+ const observedAt = Date.now();
+ setStatus((current) => {
+ if (
+ current &&
+ current.phase.phase === next.phase &&
+ Object.entries(next).every(
+ ([key, value]) => Reflect.get(current.phase, key) === value,
+ )
+ ) {
+ return current.needsRefresh
+ ? { ...current, needsRefresh: false }
+ : current;
+ }
+ const samePhase =
+ current?.phase.phase === next.phase &&
+ (next.phase !== "running" ||
+ (current.phase.phase === "running" &&
+ current.phase.job === next.job));
+ return {
+ phase: next,
+ startedAt: samePhase ? current.startedAt : observedAt,
+ needsRefresh: false,
+ };
+ });
} catch {
- // A status that cannot be read is not worth interrupting the run for.
+ if (request !== statusRequest.current) return;
+ // Keep watching for the next update, even after an action settles.
+ setStatus((current) =>
+ current && !current.needsRefresh
+ ? { ...current, needsRefresh: true }
+ : current,
+ );
}
}, []);
useEffect(() => {
if (!native) return;
void poll();
- const timer = setInterval(() => void poll(), 1000);
- return () => clearInterval(timer);
+ return () => {
+ statusRequest.current++;
+ };
}, [poll]);
useEffect(() => {
- if (!running(phase)) {
- setSeconds(0);
- startedAt.current = Date.now();
- return;
- }
+ if (!native || !watching) return;
+ let active = true;
+ let timer: ReturnType;
+ const schedule = () => {
+ timer = setTimeout(async () => {
+ await poll();
+ if (active) schedule();
+ }, 1000);
+ };
+ schedule();
+ return () => {
+ active = false;
+ clearTimeout(timer);
+ };
+ }, [poll, watching]);
+
+ useEffect(() => {
+ if (startedAt === undefined) return;
// Animations may be switched off system-wide, and then nothing can turn. A
// count that ticks every second is motion the reader can trust: it is the
// real elapsed time, not decoration.
- const tick = setInterval(
- () => setSeconds(Math.floor((Date.now() - startedAt.current) / 1000)),
- 1000,
- );
+ const tick = setInterval(() => setClock(Date.now()), 1000);
return () => clearInterval(tick);
- }, [phase]);
+ }, [startedAt]);
useEffect(() => {
if (phase.phase === "done" && !announced.current.has(phase.job)) {
@@ -90,9 +142,49 @@ export function useCloudRun({
}
}, [phase]);
+ const quoteJob = phase.phase === "quoted" ? phase.job : null;
+ const quoteOrg = phase.phase === "quoted" ? phase.org : null;
+ const deadline = phase.phase === "quoted" ? phase.deadline : null;
+ useEffect(() => {
+ if (!quoteJob || quoteOrg === null || !deadline) return;
+ let timer: ReturnType;
+ const check = () => {
+ clearTimeout(timer);
+ const remaining = Date.parse(deadline) - Date.now();
+ if (remaining <= 0) {
+ setStatus((current) =>
+ current?.phase.phase === "quoted" && current.phase.job === quoteJob
+ ? {
+ ...current,
+ phase: { phase: "expired", job: quoteJob, org: quoteOrg },
+ }
+ : current,
+ );
+ } else {
+ timer = setTimeout(check, Math.min(remaining, 2_147_483_647));
+ }
+ };
+ check();
+ window.addEventListener("focus", check);
+ document.addEventListener("visibilitychange", check);
+ return () => {
+ clearTimeout(timer);
+ window.removeEventListener("focus", check);
+ document.removeEventListener("visibilitychange", check);
+ };
+ }, [quoteJob, quoteOrg, deadline]);
+
+ const lastExpiredJob = useRef(null);
+ useEffect(() => {
+ if (phase.phase === "expired" && lastExpiredJob.current !== phase.job) {
+ lastExpiredJob.current = phase.job;
+ notify(quoteExpiredMessage(phase.org));
+ }
+ }, [phase, notify]);
+
const guard = useCallback(
async (action: () => Promise) => {
- setBusy(true);
+ setPending((count) => count + 1);
try {
await action();
return true;
@@ -100,8 +192,8 @@ export function useCloudRun({
notify(errorMessage(e));
return false;
} finally {
- setBusy(false);
await poll();
+ setPending((count) => count - 1);
}
},
[notify, poll],
@@ -109,15 +201,33 @@ export function useCloudRun({
return {
phase,
- seconds,
+ seconds:
+ startedAt === undefined
+ ? 0
+ : Math.max(0, Math.floor((clock - startedAt) / 1000)),
busy,
start: (workspace, org) =>
guard(() => desktop.startCloudRun(workspace, org)),
- approve: (org) => guard(() => desktop.confirmCloudRun(org)),
- cancel: (org) => guard(() => desktop.cancelCloudRun(org)),
+ approve: (job) => guard(() => desktop.confirmCloudRun(job)),
+ cancel: (job) => guard(() => desktop.cancelCloudRun(job)),
};
}
+export function quoteDetails({
+ org,
+ deadline,
+}: Extract): string {
+ return `Organisation : ${org} · ${
+ deadline
+ ? `Valable jusqu’au ${new Date(deadline).toLocaleString("fr-FR")}`
+ : "Échéance non communiquée"
+ }`;
+}
+
+export function quoteExpiredMessage(org: string): string {
+ return `Le devis pour ${org} a expiré. Relancez l’analyse pour obtenir un nouveau devis.`;
+}
+
function megabytes(bytes: number): string {
return bytes < 1024 * 1024
? `${Math.max(1, Math.round(bytes / 1024))} Ko`
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 1d8faa0..df12a1e 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -429,6 +429,7 @@ dependencies = [
name = "coretrace-desktop"
version = "6.0.0-beta.4"
dependencies = [
+ "chrono",
"flate2",
"keyring",
"open",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index df9df65..3deee04 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -13,6 +13,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2", features = [] }
[dependencies]
+chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] }
tauri = { version = "2", features = [] }
tauri-plugin-dialog = "2"
serde = { version = "1", features = ["derive"] }
diff --git a/src-tauri/src/cloud_run.rs b/src-tauri/src/cloud_run.rs
index f0726e9..1fb8671 100644
--- a/src-tauri/src/cloud_run.rs
+++ b/src-tauri/src/cloud_run.rs
@@ -1,9 +1,10 @@
use crate::cloud::{Cloud, Session};
use crate::pack::{pack, Packed};
use crate::workspace::{root, WorkspaceState};
+use chrono::{DateTime, Utc};
use reqwest::Method;
use serde::Serialize;
-use serde_json::json;
+use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
@@ -28,7 +29,12 @@ pub enum Phase {
Quoted {
job: String,
ctu: i64,
- deadline: String,
+ org: String,
+ deadline: Option>,
+ },
+ Expired {
+ job: String,
+ org: String,
},
Running {
job: String,
@@ -52,7 +58,6 @@ pub struct RunState {
confirmed: AtomicBool,
phase: Mutex