From 4e3759f455727695e6549b0e95ac28bc8893901d Mon Sep 17 00:00:00 2001 From: shookapic Date: Tue, 1 Dec 2026 15:56:04 +0100 Subject: [PATCH 1/4] Fix cloud phase timing and suspend settled polling (#126) --- desktop/useCloudRun.test.ts | 180 +++++++++++++++++++++++++++++++++++- desktop/useCloudRun.ts | 97 ++++++++++++++----- 2 files changed, 254 insertions(+), 23 deletions(-) diff --git a/desktop/useCloudRun.test.ts b/desktop/useCloudRun.test.ts index 115ad05..afba942 100644 --- a/desktop/useCloudRun.test.ts +++ b/desktop/useCloudRun.test.ts @@ -1,5 +1,181 @@ -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", ctu: 1, deadline: "" }; + 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("org"); + }); + 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("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, + deadline: "", + } 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("org")).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", () => { diff --git a/desktop/useCloudRun.ts b/desktop/useCloudRun.ts index b21b87a..4c0f85a 100644 --- a/desktop/useCloudRun.ts +++ b/desktop/useCloudRun.ts @@ -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)) { @@ -92,7 +144,7 @@ export function useCloudRun({ const guard = useCallback( async (action: () => Promise) => { - setBusy(true); + setPending((count) => count + 1); try { await action(); return true; @@ -100,8 +152,8 @@ export function useCloudRun({ notify(errorMessage(e)); return false; } finally { - setBusy(false); await poll(); + setPending((count) => count - 1); } }, [notify, poll], @@ -109,7 +161,10 @@ 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)), From 20d2373a62deb05642f05f8094e66e226dc43df0 Mon Sep 17 00:00:00 2001 From: shookapic Date: Tue, 1 Dec 2026 15:56:04 +0100 Subject: [PATCH 2/4] Paginate findings across severity groups (#129) --- desktop/features/Analyses.test.tsx | 59 +++++++++++++++ desktop/features/Analyses.tsx | 116 ++++++++++++++++++++--------- desktop/styles.css | 7 ++ 3 files changed, 148 insertions(+), 34 deletions(-) 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/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; } From 0dda644278e0133022a95a6258edc7f59977596a Mon Sep 17 00:00:00 2001 From: shookapic Date: Tue, 1 Dec 2026 15:59:41 +0100 Subject: [PATCH 3/4] Validate cloud quotes and bind decisions to the reviewed job (#128) --- desktop/App.test.tsx | 41 +++++ desktop/App.tsx | 52 +++--- desktop/bridge.ts | 4 +- desktop/features/CloudRun.test.tsx | 24 ++- desktop/features/CloudRun.tsx | 20 ++- desktop/types.ts | 9 +- desktop/useCloudRun.test.ts | 12 +- desktop/useCloudRun.ts | 60 ++++++- src-tauri/Cargo.lock | 1 + src-tauri/Cargo.toml | 1 + src-tauri/src/cloud_run.rs | 243 +++++++++++++++++++++++------ 11 files changed, 374 insertions(+), 93 deletions(-) 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..48910be 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,29 @@ 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 + + {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/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") && ( - )}

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 afba942..d0e6cef 100644 --- a/desktop/useCloudRun.test.ts +++ b/desktop/useCloudRun.test.ts @@ -208,9 +208,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 4c0f85a..ed71a3c 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; }; /** @@ -142,6 +142,43 @@ 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) { + setPhase((current) => + current.phase === "quoted" && current.job === quoteJob + ? { 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) => { setPending((count) => count + 1); @@ -168,11 +205,26 @@ export function useCloudRun({ 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>, archive: Mutex>, - job: Mutex>, } /// Clears the run when it ends, however it ends: the flag, the cancellation, @@ -62,15 +67,24 @@ pub struct Running<'a>(&'a RunState); impl Drop for Running<'_> { fn drop(&mut self) { - self.0.running.store(false, Ordering::Release); self.0.cancel.store(false, Ordering::Release); *self.0.archive.lock().unwrap() = None; + self.0.running.store(false, Ordering::Release); } } impl RunState { pub fn phase(&self) -> Phase { - self.phase.lock().unwrap().clone().unwrap_or(Phase::Idle) + let phase = self.phase.lock().unwrap().clone().unwrap_or(Phase::Idle); + match phase { + Phase::Quoted { + job, + org, + deadline: Some(deadline), + .. + } if deadline <= Utc::now() => Phase::Expired { job, org }, + phase => phase, + } } fn set(&self, phase: Phase) { @@ -79,13 +93,21 @@ impl RunState { /// Takes the run, or says why it cannot. The words match the ones a local /// analysis uses, because to the reader it is the same refusal. - pub fn begin(&self) -> Result, String> { + fn acquire(&self) -> Result<(), String> { self.running .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) - .map_err(|_| "An analysis is already running".to_string())?; + .map(|_| ()) + .map_err(|_| "An analysis is already running".to_string()) + } + + pub fn begin(&self) -> Result, String> { + self.acquire()?; + if matches!(self.phase(), Phase::Quoted { .. }) { + self.running.store(false, Ordering::Release); + return Err("An analysis is already running".into()); + } self.cancel.store(false, Ordering::Release); self.confirmed.store(false, Ordering::Release); - *self.job.lock().unwrap() = None; Ok(Running(self)) } @@ -103,10 +125,6 @@ impl RunState { self.confirmed.load(Ordering::Acquire) } - pub fn job(&self) -> Option { - self.job.lock().unwrap().clone() - } - #[cfg(test)] fn archive_path(&self) -> Option { self.archive @@ -304,7 +322,6 @@ async fn run_until_quote( .as_str() .ok_or("The platform created no job")? .to_owned(); - *state.job.lock().unwrap() = Some(id.clone()); // The job is created before it is priced: the meter runs, then the job // parks at awaiting_confirmation carrying its quote. Reading the cost off @@ -319,14 +336,10 @@ async fn run_until_quote( .await?; match job["status"].as_str().unwrap_or_default() { "awaiting_confirmation" => { - state.set(Phase::Quoted { - job: id, - ctu: job["reserved_ctu"].as_i64().unwrap_or(0), - deadline: job["confirm_deadline"] - .as_str() - .unwrap_or_default() - .to_owned(), - }); + if state.cancelled() { + return Err("Cancelled".into()); + } + state.set(parse_quote(&job, id, org)?); return Ok(()); } "rejected" => { @@ -345,25 +358,82 @@ async fn run_until_quote( Err("The platform has not priced this analysis yet.".into()) } +fn parse_quote(job: &Value, id: String, org: &str) -> Result { + let ctu = job["reserved_ctu"] + .as_i64() + // The frontend must be able to display the exact amount as a JS number. + .filter(|ctu| (0..=9_007_199_254_740_991).contains(ctu)) + .ok_or("La plateforme n’a pas fourni un montant CTU valide. Relancez l’analyse pour obtenir un nouveau devis.")?; + let mut deadline = None; + for field in ["confirm_deadline", "quote_expires_at"] { + if let Some(value) = job.get(field).filter(|value| !value.is_null()) { + let time = value + .as_str() + .and_then(|value| DateTime::parse_from_rfc3339(value).ok()) + .map(|value| value.with_timezone(&Utc)) + .ok_or("La plateforme a fourni une échéance de devis invalide. Relancez l’analyse pour obtenir un nouveau devis.")?; + deadline = Some(deadline.map_or(time, |current: DateTime| current.min(time))); + } + } + Ok(Phase::Quoted { + job: id, + ctu, + org: org.to_owned(), + deadline, + }) +} + /// Approves the quote and follows the job to its conclusion. This is the call /// that spends CTU; nothing before it does. pub(crate) async fn confirm( state: &RunState, session: &mut Session, - org: &str, + reviewed_job: &str, ) -> Result<(), String> { - let id = state.job().ok_or("No run is waiting for approval")?; - session + state.acquire()?; + let _running = Running(state); + let (id, org) = match state.phase() { + Phase::Quoted { job, org, .. } if job == reviewed_job => (job, org), + Phase::Expired { .. } => return Err("Le devis a expiré. Relancez l’analyse.".into()), + _ => return Err("Ce devis n’est plus disponible.".into()), + }; + if state.cancelled() { + return Err("Cancelled".into()); + } + state.set(Phase::Running { job: id.clone() }); + if let Err(reason) = session .request( Method::POST, &format!("/jobs/{id}/confirm"), - Some(org), + Some(&org), None, ) - .await?; + .await + { + state.set(Phase::Failed { + reason: reason.clone(), + }); + return Err(reason); + } state.confirmed.store(true, Ordering::Release); - state.set(Phase::Running { job: id.clone() }); + let outcome = follow_confirmed_job(state, session, &org, id).await; + if let Err(reason) = &outcome { + if matches!(state.phase(), Phase::Running { .. }) { + state.set(Phase::Failed { + reason: reason.clone(), + }); + } + } + outcome +} + +async fn follow_confirmed_job( + state: &RunState, + session: &mut Session, + org: &str, + id: String, +) -> Result<(), String> { for _ in 0..900 { if state.cancelled() { let _ = session @@ -399,9 +469,11 @@ pub async fn cloud_run_start( tools: Vec, ) -> Result<(), String> { let folder = root(&workspace, &workspace_id)?; - let _running = run.begin()?; + let running = run.begin()?; let mut session = cloud.0.lock().await; - start(&run, &mut session, folder, &org, tools).await + let outcome = start(&run, &mut session, folder, &org, tools).await; + drop(running); + outcome } #[tauri::command] @@ -413,18 +485,10 @@ pub fn cloud_run_status(run: tauri::State<'_, RunState>) -> Phase { pub async fn cloud_run_confirm( cloud: tauri::State<'_, Cloud>, run: tauri::State<'_, RunState>, - org: String, + job: String, ) -> Result<(), String> { let mut session = cloud.0.lock().await; - let outcome = confirm(&run, &mut session, &org).await; - if let Err(reason) = &outcome { - if reason != "Cancelled" { - run.set(Phase::Failed { - reason: reason.clone(), - }); - } - } - outcome + confirm(&run, &mut session, &job).await } /// Refuses a quote. While the run is packing, uploading or executing, a loop @@ -434,11 +498,21 @@ pub async fn cloud_run_confirm( pub(crate) async fn refuse( state: &RunState, session: &mut Session, - org: &str, + reviewed_job: &str, ) -> Result<(), String> { - let id = state.job().ok_or("No run is waiting for approval")?; + let Phase::Quoted { job, org, .. } = state.phase() else { + return Ok(()); + }; + if job != reviewed_job { + return Ok(()); + } session - .request(Method::POST, &format!("/jobs/{id}/cancel"), Some(org), None) + .request( + Method::POST, + &format!("/jobs/{job}/cancel"), + Some(&org), + None, + ) .await?; state.set(Phase::Cancelled { spent: false }); Ok(()) @@ -448,14 +522,13 @@ pub(crate) async fn refuse( pub async fn cloud_run_cancel( cloud: tauri::State<'_, Cloud>, run: tauri::State<'_, RunState>, - org: Option, + job: Option, ) -> Result<(), String> { - run.request_cancel(); - if let Phase::Quoted { .. } = run.phase() { - let org = org.ok_or("Choose an organisation")?; + if let Some(job) = job { let mut session = cloud.0.lock().await; - refuse(&run, &mut session, &org).await?; + return refuse(&run, &mut session, &job).await; } + run.request_cancel(); Ok(()) } @@ -694,7 +767,7 @@ mod tests { .unwrap(); assert!(matches!(state.phase(), Phase::Quoted { .. })); - refuse(&state, &mut stub.session(), "alpha").await.unwrap(); + refuse(&state, &mut stub.session(), "job-1").await.unwrap(); assert!( matches!(state.phase(), Phase::Cancelled { spent: false }), @@ -740,6 +813,69 @@ mod tests { } } + #[test] + fn only_a_valid_explicit_amount_can_be_quoted() { + for quote in [ + json!({}), + json!({"reserved_ctu": null}), + json!({"reserved_ctu": "0"}), + json!({"reserved_ctu": -1}), + json!({"reserved_ctu": 1.5}), + json!({"reserved_ctu": 9_007_199_254_740_993_i64}), + ] { + assert!( + parse_quote("e, "job-1".into(), "alpha").is_err(), + "{quote}" + ); + } + let zero = parse_quote( + &json!({"reserved_ctu": 0, "confirm_deadline": null}), + "job-1".into(), + "alpha", + ); + assert!(matches!( + zero, + Ok(Phase::Quoted { + ctu: 0, + deadline: None, + .. + }) + )); + assert!(parse_quote( + &json!({"reserved_ctu": 0, "confirm_deadline": "tomorrow"}), + "job-1".into(), + "alpha", + ) + .is_err()); + } + + #[tokio::test] + async fn confirmation_cannot_send_a_stale_or_expired_quote() { + let stub = stub_platform(vec![]); + let state = RunState::default(); + let quote = |job| parse_quote(&job, "job-1".into(), "alpha").unwrap(); + state.set(quote(json!({"reserved_ctu": 300}))); + let mut session = stub.session(); + assert!(confirm(&state, &mut session, "old-job").await.is_err()); + assert!(matches!(state.phase(), Phase::Quoted { .. })); + + state.set(quote(json!({ + "reserved_ctu": 300, + "confirm_deadline": "2099-01-01T00:00:00Z", + "quote_expires_at": "2000-01-01T00:00:00Z", + }))); + assert_eq!( + state.phase(), + Phase::Expired { + job: "job-1".into(), + org: "alpha".into(), + } + ); + assert!(confirm(&state, &mut session, "job-1").await.is_err()); + assert!(state.begin().is_ok(), "an expired quote permits a new run"); + assert!(stub.seen().is_empty()); + } + #[tokio::test] async fn a_refused_analysis_says_why_instead_of_quoting_nothing() { let stub = stub_platform(vec![ @@ -794,8 +930,15 @@ mod tests { ), ]); let state = RunState::default(); - *state.job.lock().unwrap() = Some("job-1".into()); - confirm(&state, &mut stub.session(), "alpha").await.unwrap(); + state.set( + parse_quote( + &serde_json::from_str(QUOTED_JOB).unwrap(), + "job-1".into(), + "alpha", + ) + .unwrap(), + ); + confirm(&state, &mut stub.session(), "job-1").await.unwrap(); assert_eq!( state.phase(), Phase::Done { From 6b83dfaacee1e88bbcdade5cb9f5208127cca548 Mon Sep 17 00:00:00 2001 From: shookapic Date: Tue, 1 Dec 2026 16:01:16 +0100 Subject: [PATCH 4/4] Keep parked quotes expiring while status polling is suspended --- desktop/App.tsx | 1 + desktop/useCloudRun.test.ts | 35 +++++++++++++++++++++++++++++++---- desktop/useCloudRun.ts | 9 ++++++--- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/desktop/App.tsx b/desktop/App.tsx index 48910be..cd08b1f 100644 --- a/desktop/App.tsx +++ b/desktop/App.tsx @@ -858,6 +858,7 @@ export default function App() { {quote.ctu.toLocaleString("fr-FR")} CTU seront débités + Rien n’a encore été débité pour cette analyse. {quoteDetails(quote)}