mirror of
https://github.com/Stirling-Tools/Stirling-PDF.git
synced 2026-09-03 05:10:16 +03:00
Surface recorded failures in a notification bell (Review Flow PR 4) (#7478)
Review Flow PR 4. Stacked on #7477. Recorded failures appear in a notification bell, showing each reader the failures they are allowed to see and the actions they can actually take. Scope is deliberately viewing and routing only. Resolving a failure — retry, decrypt-and-retry — is #7479, which also brings the write path for it; nothing resolution-shaped ships here, not even dark. ## What's added **A notification bell** in the editor and the processor shell. Polls `GET /api/v1/notifications` every 30 seconds, shows an unread badge, and lists open failures newest first. Each row shows the failure's title, its message with **Copy error** and **Show full message** chips, an occurrence count, and its available actions. **A notification API** (`stirling.software.proprietary.notification`), derived from failures on read rather than stored in its own table: | Route | Purpose | |---|---| | `GET /api/v1/notifications` | the caller's open failures, newest first | Read-only by design: every action the bell offers is one the client runs on its own device, so there is nothing to post back. Every id is prefixed (`failure:<uuid>`), so the bell never holds a raw failure id it could hand to a failure endpoint. **Per-reader actions.** A `FailureKind` declares each action with an audience (`OWNER`, `TEAM_REVIEWER`, `ANYONE_WHO_SEES`). The server resolves that against the reader and derives `Ownership` (`MINE` / `THEIRS` / `UNOWNED`) from the row's actor, so an admin reviewing someone else's failure is not offered a document their browser does not hold. Adding a failure kind requires no frontend change. **Server-run and client-run actions are distinguished.** `FailureActionId` carries an `Execution` facet; the registry requires a bean only for server actions, and dispatching a client action on the failure surface returns 400. The notification projection goes further: it carries only client-run offers, so the bell cannot be sent a button it would refuse to draw. **Actions in the bell:** at most two. The owner of the document gets **View file** (opens it in the editor); a team reviewer gets **View in processor** (dev builds only). Dismiss stays on the failure queue in `/processor/documents` — deciding a failure's fate belongs to the review surface, not the panel that announces it. An action id the build has not wired is skipped rather than rendered dead, so the server can ship new kinds ahead of the clients that understand them. **Attended policy runs record their document.** `POST /api/v1/policies/{id}/run` accepts an optional opaque `fileId`, recorded when the run carries exactly one primary document. This is what lets a repeat fold onto one incident instead of opening a new one per upload, lets deleting the file clear its failure, and lets the owner open the document from the row. ## Behaviour changes - **The bell re-reads as soon as a failure you caused is recorded**, rather than leaving you to wait out a poll interval for news of your own upload. Applies to a failed tool run and to a policy run reaching `FAILED`. Other people's failures still arrive on the poll, which is what it is for. - **An action the reader cannot use is not rendered.** Where the server gave a reason for withholding it, that reason appears as the row's one-line note. An action that was never offered to that reader produces no note. - **Deleting a document closes every incident about it that the deleter caused**, including a failed policy run on their own upload, so a user's own errors leave the bell with the file rather than lingering with a dead button. - **The failures list in `/processor/documents` stays behind `import.meta.env.DEV`**, and View in processor is gated to match so it cannot navigate to a section that is not mounted. Both lift when failures get their own review screen. - **One poll for all bells.** The bell is mounted in three places; the list, document lookups and read marker are shared, so mounting more than one does not multiply requests. - `ACKNOWLEDGE` is no longer offered by any kind. The id, bean and status remain so existing rows stay readable. ## Known limits - The poll does not pause when the tab is hidden. - No retention or per-team cap on `file_run_events`. ## How to test Needs a proprietary or SaaS build with login enabled. `task dev:all`, then sign in. 1. **Create a failure.** Add a password-protected PDF to the editor and choose **Skip for now** when it asks to unlock. The upload starts a policy run that fails on it. 2. **Watch the bell.** The badge should appear within a second or two, not after 30 — this is the refresh-on-failure path. Open it: a row titled "Password-protected document" with the error message and the two chips. 3. **The buttons should be View file and View in processor, nothing else.** No Dismiss and no retries: dispositions live on the review surface, resolutions in #7479. 4. **View file** closes the panel and selects that document in the editor. 5. **Dismiss from the queue instead.** Open `/processor/documents` (dev build), find the row in the failures list and dismiss it there; the bell drops it on its next read. 6. **Confirm the local-document probe.** Create a second failure, then delete that file from the editor and reload. Its incident closes with it; a row whose document is still present keeps **View file**. 7. **Confirm attribution end to end.** Sign in as a plain member, run a shared policy on your own upload so it fails. The member sees their own row in the bell. Sign in as the team leader: they see it too, but with **View in processor** instead of **View file**, because the document is not in their browser. 8. **Confirm folding.** Add the same locked PDF again and skip again. The existing row's occurrence count increases rather than a second row appearing. 9. **Confirm one poll for many bells.** Open the editor and the processor in two tabs. Each tab issues its own poll, but within a tab the several mounted bells share one — the Network tab should show one `GET /api/v1/notifications` per 30s per tab, not three. ## Migration None. No new column and no new value in any CHECK-constrained enum; `CheckConstrainedEnumsTest` fails if that changes.
This commit is contained in:
@@ -5187,6 +5187,30 @@ openProcessor = "Open PDF Processor"
|
||||
count = "{{remaining}} of {{total}}"
|
||||
label = "Free credits"
|
||||
|
||||
[notifications]
|
||||
empty = "Nothing to report."
|
||||
handoffUnavailable = "This browser will not let the processor pass the document to the editor. Open it from the editor instead."
|
||||
noDocumentLinked = "This failure is not linked to a specific document, so there is nothing to open here."
|
||||
notOnThisDevice = "This document is not on this device, so it cannot be opened here."
|
||||
occurrences = "{{count}} times"
|
||||
open = "Notifications"
|
||||
title = "Notifications"
|
||||
unread = "Unread"
|
||||
|
||||
[notifications.action]
|
||||
failed = "That did not work. Try again in a moment."
|
||||
unavailable = "Not available for this notification."
|
||||
|
||||
[notifications.detail]
|
||||
copied = "Copied"
|
||||
copy = "Copy error"
|
||||
less = "Show less"
|
||||
more = "Show full message"
|
||||
|
||||
[notifications.section]
|
||||
earlier = "Earlier"
|
||||
new = "New"
|
||||
|
||||
[oauth.error]
|
||||
message = "Authentication was not successful. You can close this window and try again."
|
||||
title = "Authentication Failed"
|
||||
@@ -7506,6 +7530,8 @@ acknowledge = "Acknowledge"
|
||||
confirm = "Are you sure?"
|
||||
dismiss = "Dismiss"
|
||||
dismissSkipFile = "Skip this file"
|
||||
viewFile = "View file"
|
||||
viewInProcessor = "View in processor"
|
||||
|
||||
[portal.failures.debug]
|
||||
copyJson = "Copy JSON"
|
||||
@@ -7517,6 +7543,8 @@ showJson = "Show raw JSON ({{total}})"
|
||||
|
||||
[portal.failures.disabled]
|
||||
closed = "This failure is already closed."
|
||||
noDocument = "This failure was not recorded against a specific document, so there is nothing here to open."
|
||||
unattended = "This file was fed by a folder, bucket or webhook, so nobody's browser is holding it to open."
|
||||
unavailable = "Not available for this failure."
|
||||
|
||||
[portal.failures.empty]
|
||||
|
||||
@@ -22,6 +22,7 @@ import WorkbenchFloatingSearch from "@app/components/shared/WorkbenchFloatingSea
|
||||
import LandingPage from "@app/components/shared/LandingPage";
|
||||
import DismissAllErrorsButton from "@app/components/shared/DismissAllErrorsButton";
|
||||
import { ChatFAB } from "@app/components/chat/ChatFAB";
|
||||
import { NotificationBell } from "@app/components/notifications/NotificationBell";
|
||||
|
||||
// Workbench panels are loaded on demand. Viewer pulls in pdfjs-dist and the
|
||||
// full @embedpdf plugin set; FileEditor/PageEditor are only needed once a file
|
||||
@@ -248,6 +249,15 @@ export default function Workbench() {
|
||||
data-tour="workbench"
|
||||
style={{ backgroundColor: "var(--c-bg)", minWidth: 0 }}
|
||||
>
|
||||
{/* The bell normally rides in the workbench bar. Wherever that bar is not shown - My Files,
|
||||
an empty workbench, a custom view without top controls - it gets its own corner, rather
|
||||
than those being the places a user cannot see that something of theirs failed. */}
|
||||
{!showWorkbenchBar && (
|
||||
<div style={{ position: "absolute", top: 12, right: 12, zIndex: 20 }}>
|
||||
<NotificationBell />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showWorkbenchBar && (
|
||||
<div className={styles.workbenchBarShell}>
|
||||
<div className={styles.workbenchBarWrapper}>
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
.notification-bell {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.notification-bell__trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
padding: var(--sp-2, 0.5rem);
|
||||
border: none;
|
||||
border-radius: var(--radius-md, 0.375rem);
|
||||
background: transparent;
|
||||
color: var(--c-text-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.notification-bell__trigger:hover {
|
||||
background: var(--c-hover);
|
||||
color: var(--c-text);
|
||||
}
|
||||
|
||||
.notification-bell__badge {
|
||||
position: absolute;
|
||||
top: 0.125rem;
|
||||
right: 0.125rem;
|
||||
min-width: 1rem;
|
||||
padding: 0 0.25rem;
|
||||
border-radius: 999px;
|
||||
background: var(--c-danger);
|
||||
color: var(--c-text-on-danger);
|
||||
font-size: 0.625rem;
|
||||
line-height: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.notification-bell__panel {
|
||||
position: fixed;
|
||||
z-index: var(--z-popover, 60);
|
||||
width: min(22rem, calc(100vw - 2rem));
|
||||
max-height: 24rem;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-3, 0.75rem);
|
||||
border: 1px solid var(--c-border);
|
||||
border-radius: var(--radius-lg, 0.5rem);
|
||||
background: var(--c-surface);
|
||||
box-shadow: 0 10px 30px rgb(0 0 0 / 25%);
|
||||
}
|
||||
|
||||
.notification-bell__heading {
|
||||
margin: 0 0 var(--sp-2, 0.5rem);
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--c-text);
|
||||
}
|
||||
|
||||
.notification-bell__empty {
|
||||
margin: 0;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--c-text-muted);
|
||||
}
|
||||
|
||||
.notification-bell__list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2, 0.5rem);
|
||||
}
|
||||
|
||||
.notification-bell__item {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0 var(--sp-2, 0.5rem);
|
||||
padding: var(--sp-2, 0.5rem);
|
||||
border-radius: var(--radius-md, 0.375rem);
|
||||
background: var(--c-surface-sunken);
|
||||
}
|
||||
|
||||
/* Wraps rather than crowds: a row can carry three buttons, and the panel is narrow. */
|
||||
.notification-bell__actions {
|
||||
grid-column: 2;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: var(--sp-1, 0.25rem);
|
||||
margin-top: var(--sp-2, 0.5rem);
|
||||
}
|
||||
|
||||
.notification-bell__dot {
|
||||
grid-row: 1;
|
||||
align-self: center;
|
||||
width: 0.5rem;
|
||||
height: 0.5rem;
|
||||
border-radius: 999px;
|
||||
background: var(--c-danger);
|
||||
}
|
||||
|
||||
.notification-bell__item-title {
|
||||
grid-column: 2;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--c-text);
|
||||
}
|
||||
|
||||
.notification-bell__count,
|
||||
.notification-bell__detail {
|
||||
grid-column: 2;
|
||||
font-size: 0.75rem;
|
||||
color: var(--c-text-muted);
|
||||
}
|
||||
|
||||
.notification-bell__detail {
|
||||
overflow: hidden;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Expanded, the message is the point of the row, so let it run and scroll rather than clamp. */
|
||||
.notification-bell__detail--full {
|
||||
display: block;
|
||||
max-height: 10rem;
|
||||
overflow-y: auto;
|
||||
-webkit-line-clamp: none;
|
||||
}
|
||||
|
||||
.notification-bell__chrome {
|
||||
grid-column: 2;
|
||||
display: flex;
|
||||
gap: var(--sp-1, 0.25rem);
|
||||
margin-top: var(--sp-1, 0.25rem);
|
||||
}
|
||||
|
||||
/* Reading aids for the message, tinted rather than filled: they sit next to the row's real actions
|
||||
and must not read as one of them. */
|
||||
.notification-bell__chip {
|
||||
padding: 0.0625rem 0.375rem;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm, 0.25rem);
|
||||
background: var(--c-primary-subtle);
|
||||
color: var(--c-accent-fg, var(--c-primary));
|
||||
font-size: 0.6875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.notification-bell__chip:hover,
|
||||
.notification-bell__chip:focus-visible {
|
||||
background: var(--c-hover);
|
||||
}
|
||||
|
||||
/* Why the actions this row could have had are absent. Muted: it explains, it does not warn. */
|
||||
.notification-bell__note {
|
||||
grid-column: 2;
|
||||
margin-top: var(--sp-1, 0.25rem);
|
||||
font-size: 0.75rem;
|
||||
color: var(--c-text-subtle);
|
||||
}
|
||||
|
||||
.notification-bell__message {
|
||||
grid-column: 2;
|
||||
margin-top: var(--sp-1, 0.25rem);
|
||||
font-size: 0.75rem;
|
||||
color: var(--c-danger);
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
fireEvent,
|
||||
render as baseRender,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import type {
|
||||
AppNotification,
|
||||
NotificationActionOffer,
|
||||
} from "@app/services/notifications";
|
||||
|
||||
// @app/ui Button is a Mantine wrapper, so it needs the provider in the tree.
|
||||
const render = (ui: Parameters<typeof baseRender>[0]) =>
|
||||
baseRender(ui, { wrapper: MantineProvider });
|
||||
|
||||
/**
|
||||
* Two things are the bell's own and worth pinning: which notifications the user has already looked
|
||||
* at, and how a row behaves around an action.
|
||||
*/
|
||||
|
||||
const fetchNotifications = vi.fn();
|
||||
|
||||
vi.mock("@app/services/notifications", () => ({
|
||||
fetchNotifications: (...args: unknown[]) => fetchNotifications(...args),
|
||||
}));
|
||||
|
||||
// IndexedDB, which jsdom has none of. Answered here so availability is a fact of the test.
|
||||
const h = vi.hoisted(() => ({
|
||||
hasLocalFile: true,
|
||||
// This build has the notifications API, except in the one test about the build that does not.
|
||||
notificationsAvailable: true,
|
||||
specs: {} as Record<
|
||||
string,
|
||||
{
|
||||
available: (context: unknown) => boolean;
|
||||
run: (context: unknown, password?: string) => unknown;
|
||||
closesPanel?: boolean;
|
||||
}
|
||||
>,
|
||||
}));
|
||||
|
||||
vi.mock("@app/services/localFilePresence", () => ({
|
||||
hasLocalFile: () => Promise.resolve(h.hasLocalFile),
|
||||
}));
|
||||
|
||||
vi.mock("@app/components/notifications/useNotificationsAvailable", () => ({
|
||||
useNotificationsAvailable: () => h.notificationsAvailable,
|
||||
}));
|
||||
|
||||
// Core's own registry is empty, so without this there are no client actions to test.
|
||||
vi.mock("@app/components/notifications/notificationActions", () => ({
|
||||
useNotificationActions: () => h.specs,
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
// A string fallback, or an options object with defaultValue plus what it interpolates.
|
||||
t: (key: string, fallback?: unknown) => {
|
||||
if (typeof fallback === "string") return fallback;
|
||||
if (fallback && typeof fallback === "object") {
|
||||
const options = fallback as Record<string, unknown>;
|
||||
const template = options.defaultValue;
|
||||
if (typeof template !== "string") return key;
|
||||
return template.replace(/{{(\w+)}}/g, (_match, name: string) =>
|
||||
String(options[name] ?? ""),
|
||||
);
|
||||
}
|
||||
return key;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
const { NotificationBell } =
|
||||
await import("@app/components/notifications/NotificationBell");
|
||||
|
||||
function offer(
|
||||
id: string,
|
||||
overrides: Partial<NotificationActionOffer> = {},
|
||||
): NotificationActionOffer {
|
||||
return {
|
||||
id,
|
||||
labelKey: `portal.failures.action.${id.toLowerCase()}`,
|
||||
defaultLabel: id,
|
||||
enabled: true,
|
||||
disabledReasonKey: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function notification(
|
||||
id: string,
|
||||
title = "Unrecognised failure",
|
||||
overrides: Partial<AppNotification> = {},
|
||||
): AppNotification {
|
||||
return {
|
||||
id,
|
||||
source: "FAILURE",
|
||||
kindId: "UNKNOWN",
|
||||
origin: "TOOL",
|
||||
ownership: "MINE",
|
||||
severity: "ERROR",
|
||||
status: "NEW",
|
||||
titleKey: `portal.failures.kind.${id}.title`,
|
||||
defaultTitle: title,
|
||||
detail: "boom",
|
||||
fileId: "f-1",
|
||||
sourceId: null,
|
||||
policyId: null,
|
||||
occurrences: 1,
|
||||
createdAt: "2026-08-05T00:00:00Z",
|
||||
lastSeenAt: "2026-08-05T00:00:00Z",
|
||||
actions: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function openPanel() {
|
||||
fireEvent.click(await screen.findByRole("button"));
|
||||
}
|
||||
|
||||
describe("NotificationBell", () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
fetchNotifications.mockReset().mockResolvedValue([]);
|
||||
h.hasLocalFile = true;
|
||||
h.notificationsAvailable = true;
|
||||
h.specs = {};
|
||||
});
|
||||
|
||||
it("mounts nothing at all in a build with no notifications API", async () => {
|
||||
// No bell and, above all, no poll: an OSS build must not sit on a timer collecting 404s.
|
||||
h.notificationsAvailable = false;
|
||||
|
||||
render(<NotificationBell />);
|
||||
|
||||
await Promise.resolve();
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
expect(fetchNotifications).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows no badge when there is nothing to report", async () => {
|
||||
render(<NotificationBell />);
|
||||
|
||||
await waitFor(() => expect(fetchNotifications).toHaveBeenCalled());
|
||||
expect(screen.queryByText("1")).toBeNull();
|
||||
});
|
||||
|
||||
it("counts everything as unread the first time, since nothing has been seen", async () => {
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a"),
|
||||
notification("b"),
|
||||
]);
|
||||
|
||||
render(<NotificationBell />);
|
||||
|
||||
expect(await screen.findByText("2")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("clears the badge once the user opens the panel", async () => {
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a"),
|
||||
notification("b"),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
// Opening marks them read: waiting for the close would leave the badge lit.
|
||||
await waitFor(() => expect(screen.queryByText("2")).toBeNull());
|
||||
});
|
||||
|
||||
it("divides what is new from what the user has already seen", async () => {
|
||||
// "b" was the newest last time, so "a" is the only new one.
|
||||
window.localStorage.setItem("stirling.notifications.lastSeenId", "b");
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a"),
|
||||
notification("b"),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
expect(await screen.findByText("New")).toBeTruthy();
|
||||
expect(screen.getByText("Earlier")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("keeps the division on screen after opening marks them read", async () => {
|
||||
// Frozen on open: read live it would collapse the moment the badge cleared.
|
||||
window.localStorage.setItem("stirling.notifications.lastSeenId", "b");
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a"),
|
||||
notification("b"),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
await waitFor(() => expect(screen.queryByText("1")).toBeNull());
|
||||
expect(screen.getByText("New")).toBeTruthy();
|
||||
expect(screen.getByText("Earlier")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does not divide a list with nothing new in it", async () => {
|
||||
window.localStorage.setItem("stirling.notifications.lastSeenId", "a");
|
||||
fetchNotifications.mockResolvedValue([notification("a")]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
// A lone "Earlier" heading over everything says nothing the empty badge has not.
|
||||
expect(await screen.findByText("Unrecognised failure")).toBeTruthy();
|
||||
expect(screen.queryByText("Earlier")).toBeNull();
|
||||
expect(screen.queryByText("New")).toBeNull();
|
||||
});
|
||||
|
||||
it("labels an all-new list without inventing an earlier section", async () => {
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a"),
|
||||
notification("b"),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
expect(await screen.findByText("New")).toBeTruthy();
|
||||
expect(screen.queryByText("Earlier")).toBeNull();
|
||||
});
|
||||
|
||||
it("marks only what arrived since the user last looked", async () => {
|
||||
fetchNotifications.mockResolvedValue([notification("a")]);
|
||||
const first = render(<NotificationBell />);
|
||||
await openPanel();
|
||||
await waitFor(() => expect(screen.queryByText("1")).toBeNull());
|
||||
first.unmount();
|
||||
|
||||
// A newer one arrives above the one already seen.
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("b"),
|
||||
notification("a"),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
|
||||
expect(await screen.findByText("1")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("treats everything as unread when the last seen one is gone", async () => {
|
||||
// We cannot tell how far the user got, so show them rather than marking the lot read.
|
||||
window.localStorage.setItem(
|
||||
"stirling.notifications.lastSeenId",
|
||||
"vanished",
|
||||
);
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a"),
|
||||
notification("b"),
|
||||
]);
|
||||
|
||||
render(<NotificationBell />);
|
||||
|
||||
expect(await screen.findByText("2")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders the server's title and repeat count without knowing the source", async () => {
|
||||
fetchNotifications.mockResolvedValue([
|
||||
{ ...notification("a", "Password-protected document"), occurrences: 3 },
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
expect(screen.getByText("Password-protected document")).toBeTruthy();
|
||||
expect(screen.getByText("3 times")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("puts every one of the row's actions on the row", async () => {
|
||||
h.specs = {
|
||||
VIEW_IN_PROCESSOR: {
|
||||
available: () => true,
|
||||
run: vi.fn(),
|
||||
closesPanel: true,
|
||||
},
|
||||
VIEW_FILE: { available: () => true, run: vi.fn(), closesPanel: true },
|
||||
};
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Unrecognised failure", {
|
||||
actions: [offer("VIEW_IN_PROCESSOR"), offer("VIEW_FILE")],
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
// Named for their row: every button in the list says the same thing.
|
||||
for (const id of ["VIEW_IN_PROCESSOR", "VIEW_FILE"])
|
||||
expect(
|
||||
screen.getByRole("button", { name: `${id}: Unrecognised failure` }),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("runs whichever of the row's actions is pressed", async () => {
|
||||
const run = vi.fn();
|
||||
h.specs = {
|
||||
VIEW_IN_PROCESSOR: { available: () => true, run: vi.fn() },
|
||||
VIEW_FILE: { available: () => true, run },
|
||||
};
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Unrecognised failure", {
|
||||
actions: [offer("VIEW_IN_PROCESSOR"), offer("VIEW_FILE")],
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole("button", { name: "VIEW_FILE: Unrecognised failure" }),
|
||||
);
|
||||
|
||||
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
|
||||
expect(screen.getByText("Unrecognised failure")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("closes the panel on its way to a destination behind it", async () => {
|
||||
const run = vi.fn();
|
||||
h.specs = { VIEW_FILE: { available: () => true, run, closesPanel: true } };
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Password-protected document", {
|
||||
actions: [offer("VIEW_FILE")],
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole("button", {
|
||||
name: "VIEW_FILE: Password-protected document",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText("Password-protected document")).toBeNull(),
|
||||
);
|
||||
});
|
||||
|
||||
it("skips an action id this build has never heard of", async () => {
|
||||
// A new failure kind can ship with new actions; an unwired button would be worse than none.
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Unrecognised failure", {
|
||||
actions: [offer("QUARANTINE")],
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
expect(screen.getByText("Unrecognised failure")).toBeTruthy();
|
||||
expect(screen.queryByRole("button", { name: /QUARANTINE/ })).toBeNull();
|
||||
});
|
||||
|
||||
it("drops an action the device cannot perform, and says why the row is thin", async () => {
|
||||
h.hasLocalFile = false;
|
||||
h.specs = {
|
||||
VIEW_FILE: {
|
||||
available: (context) =>
|
||||
(context as { hasLocalFile: boolean }).hasLocalFile,
|
||||
run: vi.fn(),
|
||||
},
|
||||
};
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Unrecognised failure", {
|
||||
actions: [offer("VIEW_FILE")],
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByText(
|
||||
"This document is not on this device, so it cannot be opened here.",
|
||||
),
|
||||
).toBeTruthy(),
|
||||
);
|
||||
expect(screen.queryByRole("button", { name: /VIEW_FILE/ })).toBeNull();
|
||||
});
|
||||
|
||||
it("says a row was never linked to a document, rather than that the document is missing", async () => {
|
||||
h.hasLocalFile = false;
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Unrecognised failure", { fileId: null }),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
expect(
|
||||
await screen.findByText(
|
||||
"This failure is not linked to a specific document, so there is nothing to open here.",
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("claims nothing about a device for a row it never looks up", async () => {
|
||||
// Never on any device, so never probed, and an absent lookup is not an absent document.
|
||||
h.hasLocalFile = false;
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Password-protected document", {
|
||||
origin: "POLICY",
|
||||
sourceId: "src-s3-invoices",
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
expect(await screen.findByText("Password-protected document")).toBeTruthy();
|
||||
expect(
|
||||
screen.queryByText(
|
||||
/not on this device|not linked to a specific document/,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("renders no button for an action the server would refuse, and says why in words", async () => {
|
||||
// A greyed button that can never work is false hope, so the reason becomes the row's note.
|
||||
h.specs = {
|
||||
VIEW_FILE: { available: () => true, run: vi.fn() },
|
||||
VIEW_IN_PROCESSOR: { available: () => true, run: vi.fn() },
|
||||
};
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Unrecognised failure", {
|
||||
ownership: "UNOWNED",
|
||||
actions: [
|
||||
offer("VIEW_FILE", {
|
||||
enabled: false,
|
||||
disabledReasonKey: "portal.failures.disabled.unattended",
|
||||
}),
|
||||
offer("VIEW_IN_PROCESSOR"),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
expect(screen.queryByRole("button", { name: /VIEW_FILE/ })).toBeNull();
|
||||
expect(
|
||||
screen.getByRole("button", {
|
||||
name: "VIEW_IN_PROCESSOR: Unrecognised failure",
|
||||
}),
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
screen.getByText("Not available for this notification."),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("leaves a closed row with no buttons rather than a row of dead ones", async () => {
|
||||
h.specs = {
|
||||
VIEW_IN_PROCESSOR: { available: () => true, run: vi.fn() },
|
||||
VIEW_FILE: { available: () => true, run: vi.fn() },
|
||||
};
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Unrecognised failure", {
|
||||
actions: [
|
||||
offer("VIEW_IN_PROCESSOR", {
|
||||
enabled: false,
|
||||
disabledReasonKey: "portal.failures.disabled.closed",
|
||||
}),
|
||||
offer("VIEW_FILE", {
|
||||
enabled: false,
|
||||
disabledReasonKey: "portal.failures.disabled.closed",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
// The message and its chips remain, so the row still reads as a row.
|
||||
expect(screen.getByText("Unrecognised failure")).toBeTruthy();
|
||||
expect(
|
||||
screen.getByText("Not available for this notification."),
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /VIEW_IN_PROCESSOR|VIEW_FILE/ }),
|
||||
).toBeNull();
|
||||
expect(document.querySelector(".notification-bell__actions")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a failed action in the row instead of leaving the user guessing", async () => {
|
||||
h.specs = {
|
||||
VIEW_FILE: {
|
||||
available: () => true,
|
||||
run: () => Promise.resolve({ ok: false, message: "Could not open" }),
|
||||
},
|
||||
};
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Password-protected document", {
|
||||
actions: [offer("VIEW_FILE")],
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole("button", {
|
||||
name: "VIEW_FILE: Password-protected document",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(await screen.findByRole("alert")).toHaveProperty(
|
||||
"textContent",
|
||||
"Could not open",
|
||||
);
|
||||
// Still on screen, so the row remains actionable.
|
||||
expect(screen.getByText("Password-protected document")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("expands the message without touching the row's actions", async () => {
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", "Unrecognised failure", {
|
||||
detail: "org.apache.pdfbox.InvalidPasswordException",
|
||||
}),
|
||||
]);
|
||||
render(<NotificationBell />);
|
||||
await openPanel();
|
||||
|
||||
const expand = screen.getByRole("button", {
|
||||
name: "Show full message: Unrecognised failure",
|
||||
});
|
||||
fireEvent.click(expand);
|
||||
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Show less: Unrecognised failure" }),
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Copy error: Unrecognised failure" }),
|
||||
).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import {
|
||||
Fragment,
|
||||
useEffect,
|
||||
useId,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { BellIcon, Button } from "@app/ui";
|
||||
import DividerWithText from "@app/components/shared/DividerWithText";
|
||||
import { useNotifications } from "@app/hooks/useNotifications";
|
||||
import { useNotificationActions } from "@app/components/notifications/notificationActions";
|
||||
import { NotificationItem } from "@app/components/notifications/NotificationItem";
|
||||
import { useNotificationsAvailable } from "@app/components/notifications/useNotificationsAvailable";
|
||||
import "@app/components/notifications/NotificationBell.css";
|
||||
|
||||
/**
|
||||
* Renders whatever the server sends without knowing which subsystem produced it or what its actions
|
||||
* mean, so a new source or failure kind needs no change here. In core because both shells mount it.
|
||||
*/
|
||||
export function NotificationBell() {
|
||||
// A build with no notifications API gets no bell at all, rather than one that polls a
|
||||
// nonexistent endpoint forever to show nothing.
|
||||
const available = useNotificationsAvailable();
|
||||
if (!available) return null;
|
||||
return <MountedNotificationBell />;
|
||||
}
|
||||
|
||||
function MountedNotificationBell() {
|
||||
const { t } = useTranslation();
|
||||
const { notifications, unreadCount, documentStateFor, markAllSeen } =
|
||||
useNotifications();
|
||||
const registry = useNotificationActions();
|
||||
const [open, setOpen] = useState(false);
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const headingId = useId();
|
||||
// Where the new ones stop, frozen when the panel opens (opening marks everything read).
|
||||
const [firstSeenId, setFirstSeenId] = useState<string | null>(null);
|
||||
// Viewport-fixed, because the workbench bar clips its own overflow.
|
||||
const [anchor, setAnchor] = useState<{ top: number; right: number } | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open) return;
|
||||
const measure = () => {
|
||||
const rect = container.current?.getBoundingClientRect();
|
||||
if (!rect) return;
|
||||
setAnchor({
|
||||
top: rect.bottom + 8,
|
||||
right: Math.max(8, window.innerWidth - rect.right),
|
||||
});
|
||||
};
|
||||
measure();
|
||||
window.addEventListener("resize", measure);
|
||||
window.addEventListener("scroll", measure, true);
|
||||
return () => {
|
||||
window.removeEventListener("resize", measure);
|
||||
window.removeEventListener("scroll", measure, true);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
// Opening marks them read, not closing: waiting would leave the badge lit while they read.
|
||||
const toggle = () => {
|
||||
setOpen((wasOpen) => {
|
||||
if (!wasOpen) {
|
||||
// Before marking, or there is nothing left to read.
|
||||
setFirstSeenId(notifications[unreadCount]?.id ?? null);
|
||||
markAllSeen();
|
||||
}
|
||||
return !wasOpen;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* How many count as new. No boundary id means all of them were; one that has since left the list
|
||||
* leaves nothing to divide on, so it reads as none rather than guessing at a row.
|
||||
*/
|
||||
const boundaryIndex = firstSeenId
|
||||
? notifications.findIndex((notification) => notification.id === firstSeenId)
|
||||
: notifications.length;
|
||||
const dividedAt = Math.max(0, boundaryIndex);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const closeOnOutside = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement;
|
||||
if (!container.current?.contains(target)) setOpen(false);
|
||||
};
|
||||
const closeOnEscape = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setOpen(false);
|
||||
};
|
||||
document.addEventListener("mousedown", closeOnOutside);
|
||||
document.addEventListener("keydown", closeOnEscape);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", closeOnOutside);
|
||||
document.removeEventListener("keydown", closeOnEscape);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<div className="notification-bell" ref={container}>
|
||||
<Button
|
||||
variant="quiet"
|
||||
size="md"
|
||||
shape="circle"
|
||||
className="notification-bell__trigger"
|
||||
aria-label={t("notifications.open", "Notifications")}
|
||||
aria-expanded={open}
|
||||
onClick={toggle}
|
||||
>
|
||||
<BellIcon />
|
||||
{unreadCount > 0 && (
|
||||
<span className="notification-bell__badge" aria-hidden>
|
||||
{unreadCount > 9 ? "9+" : unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{open && (
|
||||
<div
|
||||
className="notification-bell__panel"
|
||||
role="dialog"
|
||||
// Named by its own heading: a dialog with no accessible name is announced as just "dialog".
|
||||
aria-labelledby={headingId}
|
||||
style={anchor ? { top: anchor.top, right: anchor.right } : undefined}
|
||||
>
|
||||
<h2 className="notification-bell__heading" id={headingId}>
|
||||
{t("notifications.title", "Notifications")}
|
||||
</h2>
|
||||
|
||||
{notifications.length === 0 ? (
|
||||
<p className="notification-bell__empty">
|
||||
{t("notifications.empty", "Nothing to report.")}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="notification-bell__list">
|
||||
{notifications.map((notification, index) => (
|
||||
<Fragment key={notification.id}>
|
||||
{index === 0 && dividedAt > 0 && (
|
||||
<li aria-hidden>
|
||||
<DividerWithText
|
||||
text={t("notifications.section.new", "New")}
|
||||
/>
|
||||
</li>
|
||||
)}
|
||||
{/* Only with something on both sides: a lone "Earlier" over everything says
|
||||
nothing the empty badge has not. */}
|
||||
{index === dividedAt && dividedAt > 0 && (
|
||||
<li aria-hidden>
|
||||
<DividerWithText
|
||||
text={t("notifications.section.earlier", "Earlier")}
|
||||
/>
|
||||
</li>
|
||||
)}
|
||||
<NotificationItem
|
||||
notification={notification}
|
||||
unread={index < dividedAt}
|
||||
documentState={documentStateFor(notification)}
|
||||
registry={registry}
|
||||
onDismissPanel={() => setOpen(false)}
|
||||
/>
|
||||
</Fragment>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import { useState } from "react";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@app/ui";
|
||||
import { isResolvableHere } from "@app/hooks/useNotifications";
|
||||
import type { NotificationDocumentState } from "@app/hooks/useNotifications";
|
||||
import type {
|
||||
ClientActionRegistry,
|
||||
NotificationActionContext,
|
||||
} from "@app/components/notifications/notificationActions";
|
||||
import type {
|
||||
AppNotification,
|
||||
NotificationActionOffer,
|
||||
} from "@app/services/notifications";
|
||||
|
||||
/**
|
||||
* The server's reason wins, being about the failure rather than this browser. Otherwise only what we
|
||||
* actually looked up, so a row we never probed is never called absent.
|
||||
*/
|
||||
function noteFor(
|
||||
notification: AppNotification,
|
||||
documentState: NotificationDocumentState,
|
||||
withheldReasonKey: string | null,
|
||||
t: TFunction,
|
||||
): string | null {
|
||||
if (withheldReasonKey)
|
||||
return t(withheldReasonKey, {
|
||||
defaultValue: t(
|
||||
"notifications.action.unavailable",
|
||||
"Not available for this notification.",
|
||||
),
|
||||
});
|
||||
if (notification.ownership !== "MINE" || documentState.hasLocalFile)
|
||||
return null;
|
||||
if (!notification.fileId)
|
||||
return t(
|
||||
"notifications.noDocumentLinked",
|
||||
"This failure is not linked to a specific document, so there is nothing to open here.",
|
||||
);
|
||||
return isResolvableHere(notification)
|
||||
? t(
|
||||
"notifications.notOnThisDevice",
|
||||
"This document is not on this device, so it cannot be opened here.",
|
||||
)
|
||||
: null;
|
||||
}
|
||||
|
||||
interface NotificationItemProps {
|
||||
notification: AppNotification;
|
||||
unread: boolean;
|
||||
documentState: NotificationDocumentState;
|
||||
registry: ClientActionRegistry;
|
||||
onDismissPanel: () => void;
|
||||
}
|
||||
|
||||
/** Its own component because the last attempt's message and its expanded state are per-row. */
|
||||
export function NotificationItem({
|
||||
notification,
|
||||
unread,
|
||||
documentState,
|
||||
registry,
|
||||
onDismissPanel,
|
||||
}: NotificationItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const title = t(notification.titleKey, notification.defaultTitle);
|
||||
const context: NotificationActionContext = {
|
||||
notification,
|
||||
hasLocalFile: documentState.hasLocalFile,
|
||||
};
|
||||
|
||||
// An id this build has never heard of is skipped rather than rendered unwired: the server ships
|
||||
// new kinds, and new actions, ahead of the clients that understand them.
|
||||
const usable = notification.actions.filter((offer) => {
|
||||
if (!offer.enabled) return false;
|
||||
const spec = registry[offer.id];
|
||||
return spec ? spec.available(context) : false;
|
||||
});
|
||||
|
||||
// Only from an action this build would otherwise have rendered: a reason about one it cannot
|
||||
// perform anyway is not this row's explanation.
|
||||
const withheldReasonKey =
|
||||
notification.actions.find(
|
||||
(offer) =>
|
||||
!offer.enabled &&
|
||||
offer.disabledReasonKey !== null &&
|
||||
registry[offer.id] !== undefined,
|
||||
)?.disabledReasonKey ?? null;
|
||||
|
||||
const labelOf = (offer: NotificationActionOffer) =>
|
||||
t(offer.labelKey, offer.defaultLabel);
|
||||
|
||||
const run = async (offer: NotificationActionOffer) => {
|
||||
if (busy) return;
|
||||
setMessage(null);
|
||||
|
||||
const spec = registry[offer.id];
|
||||
if (!spec) return;
|
||||
|
||||
setBusy(offer.id);
|
||||
const outcome = await spec.run(context);
|
||||
setBusy(null);
|
||||
if (outcome && !outcome.ok) {
|
||||
setMessage(
|
||||
outcome.message ??
|
||||
t(
|
||||
"notifications.action.failed",
|
||||
"That did not work. Try again in a moment.",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (spec.closesPanel) onDismissPanel();
|
||||
};
|
||||
|
||||
const copyDetail = async () => {
|
||||
if (!notification.detail) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(notification.detail);
|
||||
setCopied(true);
|
||||
} catch {
|
||||
// No clipboard permission, and the message is on screen and selectable anyway.
|
||||
}
|
||||
};
|
||||
|
||||
const note = noteFor(notification, documentState, withheldReasonKey, t);
|
||||
|
||||
return (
|
||||
<li
|
||||
className="notification-bell__item"
|
||||
data-severity={notification.severity.toLowerCase()}
|
||||
>
|
||||
{unread && (
|
||||
<span
|
||||
className="notification-bell__dot"
|
||||
aria-label={t("notifications.unread", "Unread")}
|
||||
/>
|
||||
)}
|
||||
<span className="notification-bell__item-title">{title}</span>
|
||||
{notification.occurrences > 1 && (
|
||||
<span className="notification-bell__count">
|
||||
{t("notifications.occurrences", {
|
||||
count: notification.occurrences,
|
||||
defaultValue: "{{count}} times",
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{notification.detail && (
|
||||
<>
|
||||
<span
|
||||
className={
|
||||
expanded
|
||||
? "notification-bell__detail notification-bell__detail--full"
|
||||
: "notification-bell__detail"
|
||||
}
|
||||
>
|
||||
{notification.detail}
|
||||
</span>
|
||||
<span className="notification-bell__chrome">
|
||||
<button
|
||||
type="button"
|
||||
className="notification-bell__chip"
|
||||
aria-label={`${t("notifications.detail.copy", "Copy error")}: ${title}`}
|
||||
onClick={() => void copyDetail()}
|
||||
>
|
||||
{copied
|
||||
? t("notifications.detail.copied", "Copied")
|
||||
: t("notifications.detail.copy", "Copy error")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="notification-bell__chip"
|
||||
aria-expanded={expanded}
|
||||
aria-label={`${
|
||||
expanded
|
||||
? t("notifications.detail.less", "Show less")
|
||||
: t("notifications.detail.more", "Show full message")
|
||||
}: ${title}`}
|
||||
onClick={() => setExpanded((wasExpanded) => !wasExpanded)}
|
||||
>
|
||||
{expanded
|
||||
? t("notifications.detail.less", "Show less")
|
||||
: t("notifications.detail.more", "Show full message")}
|
||||
</button>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
|
||||
{note && <span className="notification-bell__note">{note}</span>}
|
||||
|
||||
{/* In the kind's declared order, the first leading. */}
|
||||
{usable.length > 0 && (
|
||||
<span className="notification-bell__actions">
|
||||
{usable.map((offer, index) => (
|
||||
<ActionButton
|
||||
key={offer.id}
|
||||
variant={index === 0 ? "primary" : "secondary"}
|
||||
rowTitle={title}
|
||||
label={labelOf(offer)}
|
||||
busy={busy === offer.id}
|
||||
onRun={() => void run(offer)}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{message && (
|
||||
<span className="notification-bell__message" role="alert">
|
||||
{message}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
interface ActionButtonProps {
|
||||
variant: "primary" | "secondary";
|
||||
rowTitle: string;
|
||||
label: string;
|
||||
busy: boolean;
|
||||
onRun: () => void;
|
||||
}
|
||||
|
||||
function ActionButton({
|
||||
variant,
|
||||
rowTitle,
|
||||
label,
|
||||
busy,
|
||||
onRun,
|
||||
}: ActionButtonProps) {
|
||||
return (
|
||||
<Button
|
||||
variant={variant}
|
||||
size="sm"
|
||||
fontSize="xs"
|
||||
className="notification-bell__cta"
|
||||
disabled={busy}
|
||||
// Every row's buttons read alike, so the label alone would not say which failure this acts on.
|
||||
aria-label={`${label}: ${rowTitle}`}
|
||||
onClick={onRun}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { AppNotification } from "@app/services/notifications";
|
||||
|
||||
/**
|
||||
* Keyed by action rather than by row, because the server decides what a kind offers: adding a kind is
|
||||
* no frontend change, and adding a button is one entry here.
|
||||
*/
|
||||
|
||||
export interface NotificationActionContext {
|
||||
notification: AppNotification;
|
||||
/** Whether the document is still in this browser, which is what most actions hinge on. */
|
||||
hasLocalFile: boolean;
|
||||
}
|
||||
|
||||
/** `void` means it did what it said; a failed outcome carries the message the row shows. */
|
||||
export interface ClientActionOutcome {
|
||||
ok: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface ClientActionSpec {
|
||||
/** Asked per row, never during a request. */
|
||||
available(context: NotificationActionContext): boolean;
|
||||
run(
|
||||
context: NotificationActionContext,
|
||||
): ClientActionOutcome | void | Promise<ClientActionOutcome | void>;
|
||||
/** Whether the panel should get out of the way, the destination being behind it. */
|
||||
closesPanel?: boolean;
|
||||
}
|
||||
|
||||
/** An id with no entry is skipped rather than rendered unwired. */
|
||||
export type ClientActionRegistry = Readonly<
|
||||
Record<string, ClientActionSpec | undefined>
|
||||
>;
|
||||
|
||||
const NONE: ClientActionRegistry = {};
|
||||
|
||||
/** Every destination ships in a higher layer, so this build's rows carry no buttons. */
|
||||
export function useNotificationActions(): ClientActionRegistry {
|
||||
return NONE;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Whether this build has a notifications API to read. When it does not, the bell must not
|
||||
* mount at all: an unconditional mount would poll an endpoint that does not exist, leaving a
|
||||
* permanent timer and a 404 in the network log for nothing it could ever show.
|
||||
*
|
||||
* Core has no failure registry and no notification routes, so the answer here is no; a build
|
||||
* that ships them overrides this to say so.
|
||||
*/
|
||||
export function useNotificationsAvailable(): boolean {
|
||||
return false;
|
||||
}
|
||||
@@ -59,6 +59,7 @@ import { renderWithTooltip } from "@app/components/shared/workbenchBar/workbench
|
||||
import { WorkbenchBarActionsProps } from "@app/components/shared/workbenchBar/types";
|
||||
import { useIsMobile } from "@app/hooks/useIsMobile";
|
||||
import "@app/components/shared/WorkbenchBar.css";
|
||||
import { NotificationBell } from "@app/components/notifications/NotificationBell";
|
||||
|
||||
const SECTION_ORDER: WorkbenchBarSection[] = ["top", "middle", "bottom"];
|
||||
|
||||
@@ -602,6 +603,9 @@ export default function WorkbenchBar({
|
||||
enforcingProgress={enforcingProgress}
|
||||
/>
|
||||
)}
|
||||
{/* Last in the globals, so it is the rightmost control. */}
|
||||
<div className="workbench-bar-divider workbench-bar-globals-sep" />
|
||||
<NotificationBell />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -611,9 +611,11 @@ function FileContextInner({
|
||||
// Remove from memory and cleanup resources
|
||||
lifecycleManager.removeFiles(fileIds, stateRef);
|
||||
|
||||
// Any failure recorded against these stops needing attention: the document is gone.
|
||||
// Fire-and-forget, so a server that cannot be told never blocks the delete.
|
||||
void reportFilesRemoved(fileIds);
|
||||
// Only a real delete closes a failure: most callers pass false and mean "take it out of the
|
||||
// workbench", leaving the document, and its failures, very much alive.
|
||||
if (deleteFromStorage !== false) {
|
||||
void reportFilesRemoved(fileIds);
|
||||
}
|
||||
|
||||
// Remove from IndexedDB if enabled
|
||||
if (indexedDB && enablePersistence && deleteFromStorage !== false) {
|
||||
|
||||
@@ -132,7 +132,11 @@ export interface NavigationContextActionsValue {
|
||||
const NavigationStateContext = createContext<
|
||||
NavigationContextStateValue | undefined
|
||||
>(undefined);
|
||||
const NavigationActionsContext = createContext<
|
||||
/**
|
||||
* Exported like {@link FileActionsContext}: a component mounting in both shells must ask whether
|
||||
* these exist, and {@link useNavigationActions} throws when they do not.
|
||||
*/
|
||||
export const NavigationActionsContext = createContext<
|
||||
NavigationContextActionsValue | undefined
|
||||
>(undefined);
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, act } from "@testing-library/react";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { FileContextProvider } from "@app/contexts/FileContext";
|
||||
import { useFileActions } from "@app/contexts/file/fileHooks";
|
||||
import type { FileContextActions } from "@app/types/fileContext";
|
||||
import type { FileId } from "@app/types/file";
|
||||
|
||||
/**
|
||||
* `removeFiles` deletes a document or merely takes it out of the workbench, told apart only by
|
||||
* `deleteFromStorage`. Reporting both closed the user's own notifications as they opened files.
|
||||
*/
|
||||
|
||||
const reportFilesRemoved = vi.fn();
|
||||
vi.mock("@app/services/failureReporting", () => ({
|
||||
reportFilesRemoved: (fileIds: string[]) => reportFilesRemoved(fileIds),
|
||||
reportToolFailure: vi.fn(),
|
||||
}));
|
||||
|
||||
// IndexedDB, which jsdom has none of. Stubbed so the delete branch can run to the end.
|
||||
vi.mock("@app/services/fileStorage", () => ({
|
||||
// FileContext subscribes to this to drop files whose bytes are unreadable.
|
||||
onRecordUnreadable: () => () => {},
|
||||
fileStorage: {
|
||||
init: vi.fn().mockResolvedValue(undefined),
|
||||
deleteMultipleStirlingFiles: vi.fn().mockResolvedValue(undefined),
|
||||
getAllStirlingFileStubs: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
}));
|
||||
|
||||
const FILE_ID = "f-1" as FileId;
|
||||
|
||||
let actionsRef: FileContextActions | null = null;
|
||||
|
||||
function Controller() {
|
||||
actionsRef = useFileActions().actions;
|
||||
return null;
|
||||
}
|
||||
|
||||
function setup() {
|
||||
render(
|
||||
<MantineProvider>
|
||||
<FileContextProvider>
|
||||
<Controller />
|
||||
</FileContextProvider>
|
||||
</MantineProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
reportFilesRemoved.mockReset();
|
||||
actionsRef = null;
|
||||
});
|
||||
|
||||
describe("removeFiles and the failure queue", () => {
|
||||
it("tells the server when a document is actually deleted", async () => {
|
||||
setup();
|
||||
|
||||
await act(async () => {
|
||||
await actionsRef?.removeFiles([FILE_ID], true);
|
||||
});
|
||||
|
||||
expect(reportFilesRemoved).toHaveBeenCalledWith([FILE_ID]);
|
||||
});
|
||||
|
||||
it("says nothing when the file is only closed in the workbench", async () => {
|
||||
// Closing a tab or unchecking it leaves the document on the device, failures and all.
|
||||
setup();
|
||||
|
||||
await act(async () => {
|
||||
await actionsRef?.removeFiles([FILE_ID], false);
|
||||
});
|
||||
|
||||
expect(reportFilesRemoved).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("treats an unspecified removal as a delete, the way the storage path does", async () => {
|
||||
// Same default as the IndexedDB branch: only an explicit false means keep.
|
||||
setup();
|
||||
|
||||
await act(async () => {
|
||||
await actionsRef?.removeFiles([FILE_ID]);
|
||||
});
|
||||
|
||||
expect(reportFilesRemoved).toHaveBeenCalledWith([FILE_ID]);
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
} from "@app/types/fileContext";
|
||||
import { FILE_EVENTS } from "@app/services/errorUtils";
|
||||
import { reportToolFailure } from "@app/services/failureReporting";
|
||||
import { refreshNotificationsNow } from "@app/hooks/useNotifications";
|
||||
import { zipFileService } from "@app/services/zipFileService";
|
||||
import { getFilenameWithoutExtension } from "@app/utils/fileUtils";
|
||||
import {
|
||||
@@ -606,11 +607,12 @@ export const useToolOperation = <TParams>(
|
||||
|
||||
// Report it so a leader sees the failure too, then carry on with the user's
|
||||
// own error handling. Fire-and-forget: the reporter swallows its own errors.
|
||||
// Chained, not fired alongside: the re-read must happen after the row exists.
|
||||
void reportToolFailure({
|
||||
operation: config.operationType,
|
||||
error,
|
||||
fileIds: validFiles.map((file) => file.fileId),
|
||||
});
|
||||
}).then(refreshNotificationsNow);
|
||||
|
||||
const errorMessage =
|
||||
config.getErrorMessage?.(error) || extractErrorMessage(error);
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import type { AppNotification } from "@app/services/notifications";
|
||||
|
||||
/**
|
||||
* The bell is mounted several times over, so what is pinned here is that they share one read: one
|
||||
* poll, one set of lookups, one marker, and no timer left running once the last has gone.
|
||||
*/
|
||||
|
||||
const fetchNotifications = vi.fn();
|
||||
|
||||
vi.mock("@app/services/notifications", () => ({
|
||||
fetchNotifications: (...args: unknown[]) => fetchNotifications(...args),
|
||||
}));
|
||||
|
||||
// Counted here so "resolved once per list, not once per row" is observable.
|
||||
const hasLocalFile = vi.fn((_fileId: string) => Promise.resolve(true));
|
||||
|
||||
vi.mock("@app/services/localFilePresence", () => ({
|
||||
hasLocalFile: (fileId: string) => hasLocalFile(fileId),
|
||||
}));
|
||||
|
||||
const { useNotifications, refreshNotificationsNow } =
|
||||
await import("@app/hooks/useNotifications");
|
||||
|
||||
function notification(
|
||||
id: string,
|
||||
overrides: Partial<AppNotification> = {},
|
||||
): AppNotification {
|
||||
return {
|
||||
id,
|
||||
source: "FAILURE",
|
||||
kindId: "UNKNOWN",
|
||||
origin: "TOOL",
|
||||
ownership: "MINE",
|
||||
severity: "ERROR",
|
||||
status: "NEW",
|
||||
titleKey: `portal.failures.kind.${id}.title`,
|
||||
defaultTitle: id,
|
||||
detail: "boom",
|
||||
fileId: "f-1",
|
||||
sourceId: null,
|
||||
policyId: null,
|
||||
occurrences: 1,
|
||||
createdAt: "2026-08-05T00:00:00Z",
|
||||
lastSeenAt: "2026-08-05T00:00:00Z",
|
||||
actions: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("useNotifications", () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
fetchNotifications.mockReset().mockResolvedValue([]);
|
||||
hasLocalFile.mockClear();
|
||||
});
|
||||
|
||||
it("reads the list once however many bells are mounted", async () => {
|
||||
fetchNotifications.mockResolvedValue([notification("a")]);
|
||||
|
||||
const first = renderHook(() => useNotifications());
|
||||
const second = renderHook(() => useNotifications());
|
||||
|
||||
await waitFor(() =>
|
||||
expect(first.result.current.notifications).toHaveLength(1),
|
||||
);
|
||||
expect(second.result.current.notifications).toHaveLength(1);
|
||||
expect(fetchNotifications).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("looks a document up once for the list, not once per row", async () => {
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("a", { fileId: "f-1" }),
|
||||
notification("b", { fileId: "f-1" }),
|
||||
notification("c", { fileId: "f-2" }),
|
||||
]);
|
||||
|
||||
const { result } = renderHook(() => useNotifications());
|
||||
|
||||
await waitFor(() => expect(result.current.notifications).toHaveLength(3));
|
||||
expect(hasLocalFile).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("looks up an attended run's document but never an unattended run's", async () => {
|
||||
// Asking storage about a source's hash can only miss, and would then be shown as "not on this
|
||||
// device" about a document that never was.
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("attended", {
|
||||
origin: "POLICY",
|
||||
sourceId: null,
|
||||
fileId: "editor-file-1",
|
||||
}),
|
||||
notification("unattended", {
|
||||
origin: "POLICY",
|
||||
sourceId: "src-s3-invoices",
|
||||
fileId: "hashed-identity",
|
||||
}),
|
||||
]);
|
||||
|
||||
const { result } = renderHook(() => useNotifications());
|
||||
|
||||
await waitFor(() => expect(result.current.notifications).toHaveLength(2));
|
||||
expect(hasLocalFile).toHaveBeenCalledTimes(1);
|
||||
expect(hasLocalFile).toHaveBeenCalledWith("editor-file-1");
|
||||
expect(
|
||||
result.current.documentStateFor(result.current.notifications[0])
|
||||
.hasLocalFile,
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.current.documentStateFor(result.current.notifications[1])
|
||||
.hasLocalFile,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("polls on one timer and stops it when the last bell unmounts", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const first = renderHook(() => useNotifications());
|
||||
const second = renderHook(() => useNotifications());
|
||||
await act(async () => {});
|
||||
expect(fetchNotifications).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Two bells, one tick: a timer per subscriber would read twice here.
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(30_000);
|
||||
});
|
||||
expect(fetchNotifications).toHaveBeenCalledTimes(2);
|
||||
|
||||
first.unmount();
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(30_000);
|
||||
});
|
||||
expect(fetchNotifications).toHaveBeenCalledTimes(3);
|
||||
|
||||
second.unmount();
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(120_000);
|
||||
});
|
||||
expect(fetchNotifications).toHaveBeenCalledTimes(3);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("marks every bell read, not just the one the user opened", async () => {
|
||||
fetchNotifications.mockResolvedValue([
|
||||
notification("b"),
|
||||
notification("a"),
|
||||
]);
|
||||
const first = renderHook(() => useNotifications());
|
||||
const second = renderHook(() => useNotifications());
|
||||
await waitFor(() => expect(first.result.current.unreadCount).toBe(2));
|
||||
expect(second.result.current.unreadCount).toBe(2);
|
||||
|
||||
// Async because subscribers are told on a microtask: a bell marks the list read while rendering.
|
||||
await act(async () => first.result.current.markAllSeen());
|
||||
|
||||
expect(first.result.current.unreadCount).toBe(0);
|
||||
expect(second.result.current.unreadCount).toBe(0);
|
||||
expect(
|
||||
window.localStorage.getItem("stirling.notifications.lastSeenId"),
|
||||
).toBe("b");
|
||||
});
|
||||
|
||||
it("chains one fresh read behind the read in flight rather than joining it", async () => {
|
||||
// A refresh exists to observe a write the caller just made. The read in flight may have
|
||||
// started before that write, so joining it would report the world without it - and the
|
||||
// caller would wait a whole poll interval for news of their own action.
|
||||
let release: (listed: AppNotification[]) => void = () => {};
|
||||
fetchNotifications.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<AppNotification[]>((resolve) => {
|
||||
release = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
const first = renderHook(() => useNotifications());
|
||||
expect(fetchNotifications).toHaveBeenCalledTimes(1);
|
||||
|
||||
// A refresh from a row, twice over, and a second bell mounting - all mid-read. The
|
||||
// refreshes share ONE chained read; the mount joins what is already there.
|
||||
fetchNotifications.mockResolvedValue([notification("a")]);
|
||||
act(() => {
|
||||
first.result.current.refresh();
|
||||
first.result.current.refresh();
|
||||
});
|
||||
const second = renderHook(() => useNotifications());
|
||||
expect(fetchNotifications).toHaveBeenCalledTimes(1);
|
||||
|
||||
// The stale read lands empty; the chained fresh read is what delivers the row.
|
||||
await act(async () => release([]));
|
||||
await waitFor(() => expect(fetchNotifications).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() =>
|
||||
expect(first.result.current.notifications).toHaveLength(1),
|
||||
);
|
||||
expect(second.result.current.notifications).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("shows a just-reported failure without waiting for the poll", async () => {
|
||||
const hook = renderHook(() => useNotifications());
|
||||
await waitFor(() => expect(fetchNotifications).toHaveBeenCalledTimes(1));
|
||||
expect(hook.result.current.unreadCount).toBe(0);
|
||||
|
||||
// The failure report chain: row recorded server-side, then the re-read.
|
||||
fetchNotifications.mockResolvedValue([notification("a")]);
|
||||
act(() => refreshNotificationsNow());
|
||||
|
||||
await waitFor(() => expect(hook.result.current.unreadCount).toBe(1));
|
||||
});
|
||||
|
||||
it("still lands the row when the refresh races a poll read already in flight", async () => {
|
||||
let releaseStale: (listed: AppNotification[]) => void = () => {};
|
||||
fetchNotifications.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<AppNotification[]>((resolve) => {
|
||||
releaseStale = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
const hook = renderHook(() => useNotifications());
|
||||
expect(fetchNotifications).toHaveBeenCalledTimes(1);
|
||||
|
||||
// The failure is recorded while a poll's read is still in flight, then its refresh fires.
|
||||
// Joining that stale read would miss the row until the next poll interval.
|
||||
fetchNotifications.mockResolvedValue([notification("a")]);
|
||||
act(() => refreshNotificationsNow());
|
||||
await act(async () => releaseStale([]));
|
||||
|
||||
await waitFor(() => expect(hook.result.current.unreadCount).toBe(1));
|
||||
});
|
||||
|
||||
it("keeps its own list rather than one left by a bell that has gone", async () => {
|
||||
fetchNotifications.mockResolvedValue([notification("a")]);
|
||||
const first = renderHook(() => useNotifications());
|
||||
await waitFor(() =>
|
||||
expect(first.result.current.notifications).toHaveLength(1),
|
||||
);
|
||||
first.unmount();
|
||||
|
||||
// It must not show the old row while its own read is in flight.
|
||||
fetchNotifications.mockResolvedValue([]);
|
||||
const second = renderHook(() => useNotifications());
|
||||
|
||||
expect(second.result.current.notifications).toHaveLength(0);
|
||||
await waitFor(() => expect(fetchNotifications).toHaveBeenCalledTimes(2));
|
||||
expect(second.result.current.notifications).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,240 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import {
|
||||
fetchNotifications,
|
||||
type AppNotification,
|
||||
} from "@app/services/notifications";
|
||||
import { hasLocalFile } from "@app/services/localFilePresence";
|
||||
|
||||
/**
|
||||
* One polled store for however many bells are mounted. A module store rather than a context because
|
||||
* the portal mounts its bell as a sibling of AppProviders, so there is no single tree to provide in.
|
||||
*/
|
||||
|
||||
// TODO: read state is per-browser. Move it server-side when notifications get their own table.
|
||||
const POLL_INTERVAL_MS = 30_000;
|
||||
const SEEN_STORAGE_KEY = "stirling.notifications.lastSeenId";
|
||||
|
||||
function readLastSeenId(): string | null {
|
||||
try {
|
||||
return window.localStorage.getItem(SEEN_STORAGE_KEY);
|
||||
} catch {
|
||||
// Private mode: everything reads as unseen, which errs towards showing failures.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeLastSeenId(id: string): void {
|
||||
try {
|
||||
window.localStorage.setItem(SEEN_STORAGE_KEY, id);
|
||||
} catch {
|
||||
// The marker just will not survive a reload.
|
||||
}
|
||||
}
|
||||
|
||||
export interface NotificationDocumentState {
|
||||
hasLocalFile: boolean;
|
||||
}
|
||||
|
||||
const NO_DOCUMENT: NotificationDocumentState = {
|
||||
hasLocalFile: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether this browser could resolve the document a row names. Two id spaces share `fileId`: an
|
||||
* attended run reports the id its editor minted, a source-fed one a hash that was never on a device.
|
||||
*/
|
||||
export function isResolvableHere(notification: AppNotification): boolean {
|
||||
return (notification.sourceId ?? null) === null;
|
||||
}
|
||||
|
||||
interface NotificationsSnapshot {
|
||||
notifications: AppNotification[];
|
||||
/** Keyed by fileId, so several rows about one document cost one lookup. */
|
||||
documents: Record<string, NotificationDocumentState>;
|
||||
lastSeenId: string | null;
|
||||
}
|
||||
|
||||
const NOTHING_LOADED: NotificationsSnapshot = {
|
||||
notifications: [],
|
||||
documents: {},
|
||||
lastSeenId: null,
|
||||
};
|
||||
|
||||
let snapshot: NotificationsSnapshot = NOTHING_LOADED;
|
||||
const subscribers = new Set<() => void>();
|
||||
let pollTimer: number | null = null;
|
||||
let inFlight: Promise<void> | null = null;
|
||||
/** Bumped when polling starts or stops, so a read from a finished cycle cannot write. */
|
||||
let cycle = 0;
|
||||
let notifyQueued = false;
|
||||
|
||||
function getSnapshot(): NotificationsSnapshot {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribers told on a microtask: a bell marks the list read from inside its own state updater, and
|
||||
* re-rendering the others from there is the render-phase update React refuses.
|
||||
*/
|
||||
function publish(next: NotificationsSnapshot): void {
|
||||
snapshot = next;
|
||||
if (notifyQueued) return;
|
||||
notifyQueued = true;
|
||||
queueMicrotask(() => {
|
||||
notifyQueued = false;
|
||||
subscribers.forEach((notify) => notify());
|
||||
});
|
||||
}
|
||||
|
||||
async function read(forCycle: number): Promise<void> {
|
||||
const listed = await fetchNotifications();
|
||||
if (forCycle !== cycle) return;
|
||||
|
||||
const fileIds = [
|
||||
...new Set(
|
||||
listed
|
||||
.filter(isResolvableHere)
|
||||
.map((notification) => notification.fileId)
|
||||
.filter((fileId): fileId is string => fileId !== null),
|
||||
),
|
||||
];
|
||||
const resolved = await Promise.all(
|
||||
fileIds.map(
|
||||
async (fileId) =>
|
||||
[
|
||||
fileId,
|
||||
{
|
||||
hasLocalFile: await hasLocalFile(fileId),
|
||||
},
|
||||
] as const,
|
||||
),
|
||||
);
|
||||
if (forCycle !== cycle) return;
|
||||
|
||||
publish({
|
||||
...snapshot,
|
||||
notifications: listed,
|
||||
documents: Object.fromEntries(resolved),
|
||||
});
|
||||
}
|
||||
|
||||
/** A caller arriving mid-read joins the one already running. */
|
||||
function load(): Promise<void> {
|
||||
if (inFlight) return inFlight;
|
||||
const pending = read(cycle).finally(() => {
|
||||
if (inFlight === pending) inFlight = null;
|
||||
});
|
||||
inFlight = pending;
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Set while a fresh read is chained behind the one in flight, so callers share it. */
|
||||
let freshReadQueued = false;
|
||||
|
||||
/**
|
||||
* A read that must observe a write the caller just made. It never joins a read already in
|
||||
* flight, because that read may have started before the write and would report the world
|
||||
* without it; a fresh read is chained behind it instead. Callers arriving in the same
|
||||
* window share the one chained read.
|
||||
*/
|
||||
function loadFresh(): void {
|
||||
const inFlightRead = inFlight;
|
||||
if (!inFlightRead) {
|
||||
void load();
|
||||
return;
|
||||
}
|
||||
if (freshReadQueued) return;
|
||||
freshReadQueued = true;
|
||||
void inFlightRead.finally(() => {
|
||||
freshReadQueued = false;
|
||||
// The last bell may have unmounted while the stale read was landing.
|
||||
if (subscribers.size === 0) return;
|
||||
void load();
|
||||
});
|
||||
}
|
||||
|
||||
function startPolling(): void {
|
||||
cycle += 1;
|
||||
// From disk, not memory: another tab may have moved the marker on.
|
||||
snapshot = { ...NOTHING_LOADED, lastSeenId: readLastSeenId() };
|
||||
pollTimer = window.setInterval(() => void load(), POLL_INTERVAL_MS);
|
||||
void load();
|
||||
}
|
||||
|
||||
function stopPolling(): void {
|
||||
if (pollTimer !== null) {
|
||||
window.clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
// Drop anything in flight: its cycle has nobody watching it.
|
||||
cycle += 1;
|
||||
inFlight = null;
|
||||
snapshot = NOTHING_LOADED;
|
||||
}
|
||||
|
||||
/** Polling lives exactly as long as there is a bell to show it. */
|
||||
function subscribe(onStoreChange: () => void): () => void {
|
||||
subscribers.add(onStoreChange);
|
||||
if (subscribers.size === 1) startPolling();
|
||||
return () => {
|
||||
subscribers.delete(onStoreChange);
|
||||
if (subscribers.size === 0) stopPolling();
|
||||
};
|
||||
}
|
||||
|
||||
function markAllSeen(): void {
|
||||
const newest = snapshot.notifications[0];
|
||||
if (!newest || snapshot.lastSeenId === newest.id) return;
|
||||
writeLastSeenId(newest.id);
|
||||
publish({ ...snapshot, lastSeenId: newest.id });
|
||||
}
|
||||
|
||||
function refresh(): void {
|
||||
// A row calls this after changing something server-side, so the read must be fresh.
|
||||
loadFresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-read now, for a caller that just caused a notification: without it the person who triggered a
|
||||
* failure waits a whole poll interval to hear about their own action. A no-op with no bell mounted.
|
||||
*/
|
||||
export function refreshNotificationsNow(): void {
|
||||
if (subscribers.size === 0) return;
|
||||
loadFresh();
|
||||
}
|
||||
|
||||
export interface NotificationsState {
|
||||
notifications: AppNotification[];
|
||||
/** Read before {@link markAllSeen}, which zeroes it. */
|
||||
unreadCount: number;
|
||||
documentStateFor: (
|
||||
notification: AppNotification,
|
||||
) => NotificationDocumentState;
|
||||
markAllSeen: () => void;
|
||||
refresh: () => void;
|
||||
}
|
||||
|
||||
export function useNotifications(): NotificationsState {
|
||||
const { notifications, documents, lastSeenId } = useSyncExternalStore(
|
||||
subscribe,
|
||||
getSnapshot,
|
||||
getSnapshot,
|
||||
);
|
||||
|
||||
// A marker no longer in the list means we cannot tell how far the user got, so everything reads
|
||||
// as unread rather than being silently marked seen.
|
||||
const seenIndex = lastSeenId
|
||||
? notifications.findIndex((n) => n.id === lastSeenId)
|
||||
: -1;
|
||||
const unreadCount = seenIndex === -1 ? notifications.length : seenIndex;
|
||||
|
||||
return {
|
||||
notifications,
|
||||
unreadCount,
|
||||
documentStateFor: (notification) =>
|
||||
(notification.fileId ? documents[notification.fileId] : null) ??
|
||||
NO_DOCUMENT,
|
||||
markAllSeen,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -115,6 +115,9 @@ export const I18N_PROJECTS: TranslationProject[] = [
|
||||
// invisible to the static scan. The raw catalogue value is the fallback.
|
||||
/^policies\.field\./,
|
||||
/^policyOption\./,
|
||||
// A failure's disabled reason arrives from the server as a key and is rendered with
|
||||
// t(thatKey), so nothing in source names it, but the copy still has to exist.
|
||||
/^portal\.failures\.disabled\./,
|
||||
],
|
||||
minUsedKeys: 100,
|
||||
minLocaleKeys: 100,
|
||||
|
||||
@@ -5,3 +5,9 @@
|
||||
* portal (core, desktop, prototypes) must never resolve @portal.
|
||||
*/
|
||||
export const PORTAL_BASENAME = "/processor";
|
||||
|
||||
/**
|
||||
* The recorded-failures section of the portal's Documents view. Here because whoever links to it and
|
||||
* whoever renders it are in different layers.
|
||||
*/
|
||||
export const PORTAL_FAILURES_ANCHOR = "failures";
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import "fake-indexeddb/auto";
|
||||
|
||||
/**
|
||||
* Tests for the one thing the bell asks about a failed document here: whether it is
|
||||
* still in this browser, which is what decides if it can be opened.
|
||||
*/
|
||||
|
||||
const getStirlingFileStub = vi.fn();
|
||||
|
||||
vi.mock("@app/services/fileStorage", () => ({
|
||||
fileStorage: {
|
||||
getStirlingFileStub: (...args: unknown[]) => getStirlingFileStub(...args),
|
||||
},
|
||||
}));
|
||||
|
||||
const { hasLocalFile } = await import("@app/services/localFilePresence");
|
||||
|
||||
beforeEach(() => {
|
||||
getStirlingFileStub.mockReset().mockResolvedValue(null);
|
||||
});
|
||||
|
||||
describe("hasLocalFile", () => {
|
||||
it("is false once the document has left this browser", async () => {
|
||||
getStirlingFileStub.mockResolvedValue(null);
|
||||
|
||||
await expect(hasLocalFile("f-1")).resolves.toBe(false);
|
||||
await expect(hasLocalFile(null)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("is true while the document is still stored here", async () => {
|
||||
getStirlingFileStub.mockResolvedValue({ id: "f-1", name: "doc.pdf" });
|
||||
|
||||
await expect(hasLocalFile("f-1")).resolves.toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { fileStorage } from "@app/services/fileStorage";
|
||||
import type { FileId } from "@app/types/file";
|
||||
|
||||
/** Whether the document is still in this browser. The id is this workspace's own, so only it can say. */
|
||||
export async function hasLocalFile(fileId: string | null): Promise<boolean> {
|
||||
if (!isUsableId(fileId)) return false;
|
||||
|
||||
try {
|
||||
const stub = await fileStorage.getStirlingFileStub(fileId as FileId);
|
||||
return stub !== null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isUsableId(fileId: string | null | undefined): fileId is string {
|
||||
return typeof fileId === "string" && fileId.trim() !== "";
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import apiClient from "@app/services/apiClient";
|
||||
|
||||
// Derived server-side from whatever produces them, so this client knows nothing about failures.
|
||||
const NOTIFICATIONS_PATH = "/api/v1/notifications";
|
||||
|
||||
export type NotificationSource = "FAILURE";
|
||||
|
||||
export type NotificationSeverity = "ERROR" | "WARNING" | "INFO";
|
||||
|
||||
export type NotificationOrigin = "TOOL" | "POLICY" | "PIPELINE";
|
||||
|
||||
/** From this reader's point of view. `UNOWNED` is an unattended run: nobody holds the file. */
|
||||
export type NotificationOwnership = "MINE" | "THEIRS" | "UNOWNED";
|
||||
|
||||
/** `id` is an open string, not a union: the server may know actions this build does not. */
|
||||
export interface NotificationActionOffer {
|
||||
id: string;
|
||||
labelKey: string;
|
||||
/** English fallback, for a build with no copy for `labelKey`. */
|
||||
defaultLabel: string;
|
||||
/** False renders no button in the bell, and a disabled one in the portal's queue. */
|
||||
enabled: boolean;
|
||||
disabledReasonKey: string | null;
|
||||
}
|
||||
|
||||
export interface AppNotification {
|
||||
/** Prefixed with its source (`failure:<uuid>`), so it is never an id a per-source endpoint takes. */
|
||||
id: string;
|
||||
source: NotificationSource;
|
||||
/** Open string, e.g. `INPUT_PASSWORD_PROTECTED`: the server adds kinds without a client change. */
|
||||
kindId: string;
|
||||
origin: NotificationOrigin;
|
||||
ownership: NotificationOwnership;
|
||||
severity: NotificationSeverity;
|
||||
status: string;
|
||||
titleKey: string;
|
||||
defaultTitle: string;
|
||||
detail: string | null;
|
||||
/** Two id spaces share this field, and `sourceId` says which: see `isResolvableHere`. */
|
||||
fileId: string | null;
|
||||
/** Which folder, bucket or webhook fed the run, and null for an attended one. */
|
||||
sourceId: string | null;
|
||||
policyId: string | null;
|
||||
occurrences: number;
|
||||
createdAt: string;
|
||||
lastSeenAt: string;
|
||||
actions: NotificationActionOffer[];
|
||||
}
|
||||
|
||||
interface NotificationsResponse {
|
||||
notifications: AppNotification[];
|
||||
}
|
||||
|
||||
/** Newest first. Empty rather than throwing: a bell that cannot load is an empty bell, not an error. */
|
||||
export async function fetchNotifications(
|
||||
limit = 20,
|
||||
): Promise<AppNotification[]> {
|
||||
try {
|
||||
const response = await apiClient.get<NotificationsResponse>(
|
||||
`${NOTIFICATIONS_PATH}?limit=${limit}`,
|
||||
);
|
||||
return response?.data?.notifications ?? [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -273,6 +273,12 @@ export async function mockAppApis(
|
||||
await page.route("**/api/v1/policies/runs", (route: Route) =>
|
||||
route.fulfill({ json: [] }),
|
||||
);
|
||||
|
||||
// The bell polls this on load. The hook swallows the failure, but the browser still logs the
|
||||
// request, which the console-hygiene guard counts.
|
||||
await page.route("**/api/v1/notifications*", (route: Route) =>
|
||||
route.fulfill({ json: { notifications: [] } }),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -38,6 +38,7 @@ html[data-app-theme="light"] {
|
||||
|
||||
--c-success: var(--p-green-600);
|
||||
--c-danger: var(--p-red-600);
|
||||
--c-text-on-danger: var(--p-white);
|
||||
--c-warning: var(--p-amber-600);
|
||||
/* Solid fills that carry a white label. Deeper than the --c-<tone> values
|
||||
above, which are picked for surfaces, borders and icons where the 3:1
|
||||
@@ -169,6 +170,7 @@ html[data-app-theme="midnight"] {
|
||||
|
||||
--c-success: var(--p-green-500);
|
||||
--c-danger: var(--p-red-500);
|
||||
--c-text-on-danger: var(--p-white);
|
||||
--c-warning: var(--p-amber-500);
|
||||
|
||||
/* Themed decorative dark overrides (see :root for light + rationale). */
|
||||
@@ -371,6 +373,7 @@ html[data-app-theme="custom"][data-mantine-color-scheme="dark"] {
|
||||
/* Dark-tuned status shades (lighter than the light-theme :root values). */
|
||||
--c-success: var(--p-green-500);
|
||||
--c-danger: var(--p-red-400);
|
||||
--c-text-on-danger: var(--p-white);
|
||||
--c-warning: var(--p-amber-500);
|
||||
|
||||
/* Themed decorative dark overrides (see :root for light + rationale). */
|
||||
|
||||
@@ -337,6 +337,11 @@ export interface FileContextActions {
|
||||
insertAfterPageId?: string;
|
||||
selectFiles?: boolean;
|
||||
skipUploadTracking?: boolean;
|
||||
/**
|
||||
* Produced in-app rather than uploaded, which stops the policy auto-run enforcing an upload
|
||||
* policy on it. Set by anything adding a file already through a policy or a tool.
|
||||
*/
|
||||
derivedFromTool?: boolean;
|
||||
},
|
||||
) => Promise<StirlingFile[]>;
|
||||
addFilesWithOptions: (
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* An outline bell. The bundled Material Symbols set only carries the filled variant,
|
||||
* which reads as permanently ringing.
|
||||
*/
|
||||
export function BellIcon({ size = 18 }: { size?: number }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.75"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
|
||||
<path d="M13.73 21a2 2 0 0 1-3.46 0" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export * from "@app/ui/Button";
|
||||
export * from "@app/ui/ActionIcon";
|
||||
export * from "@app/ui/BellIcon";
|
||||
export * from "@app/ui/Logo";
|
||||
export * from "@app/ui/FilePicker";
|
||||
export * from "@app/ui/SegmentedControl";
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
color: var(--c-text-muted);
|
||||
}
|
||||
|
||||
/* Anchors .portal-shell__notifications without disturbing the column's flow. */
|
||||
.portal-shell__main {
|
||||
position: relative;
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -69,3 +71,12 @@
|
||||
animation: fadeIn var(--motion-fast) both;
|
||||
}
|
||||
}
|
||||
|
||||
/* Sits over the main area's top-right corner. Outside .portal-shell__view so it stays put while
|
||||
the view scrolls, and inside .portal-shell__main so it never overlaps the sidebar. */
|
||||
.portal-shell__notifications {
|
||||
position: absolute;
|
||||
top: var(--sp-3, 0.75rem);
|
||||
right: var(--sp-4, 1rem);
|
||||
z-index: var(--z-sticky, 30);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useUI } from "@portal/contexts/UIContext";
|
||||
import { MenuIcon, SearchIcon } from "@portal/components/icons";
|
||||
import { Logo } from "@app/ui/Logo";
|
||||
import "@portal/components/AppShell.css";
|
||||
import { NotificationBell } from "@app/components/notifications/NotificationBell";
|
||||
|
||||
/**
|
||||
* Compact header shown only under the mobile breakpoint (CSS-hidden on
|
||||
@@ -89,6 +90,9 @@ export function AppShell({ children }: { children: ReactNode }) {
|
||||
<div className="portal-shell__main">
|
||||
<MobileTopbar />
|
||||
<PortalSearchBar />
|
||||
<div className="portal-shell__notifications">
|
||||
<NotificationBell />
|
||||
</div>
|
||||
<main className="portal-shell__view">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render as baseRender, screen, waitFor } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { PortalTestProviders } from "@portal/test/TestQueryProvider";
|
||||
import type { FileRunEvent } from "@portal/api/fileRunEvents";
|
||||
|
||||
/**
|
||||
* Tests for the list: the states it survives (loading, empty, no registry, refused),
|
||||
* plus replacing a row in place after acting and re-reading when the server refuses.
|
||||
* plus replacing a row in place after acting, re-reading when the server refuses, and
|
||||
* bringing itself into view when a notification links to it.
|
||||
*/
|
||||
|
||||
// jsdom does no layout and so implements no scrollIntoView.
|
||||
const scrollIntoView = vi.fn();
|
||||
Element.prototype.scrollIntoView = scrollIntoView;
|
||||
|
||||
const fetchFileRunEvents = vi.fn();
|
||||
const applyFileRunEventAction = vi.fn();
|
||||
|
||||
@@ -55,9 +61,19 @@ vi.mock("react-i18next", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
// The list reads through the shared query hooks, and @app/ui needs Mantine.
|
||||
const render = (ui: Parameters<typeof baseRender>[0]) =>
|
||||
baseRender(ui, { wrapper: PortalTestProviders });
|
||||
// The list reads through the shared query hooks, @app/ui needs Mantine, and the section reads
|
||||
// the location to know whether it was linked to.
|
||||
const render = (
|
||||
ui: Parameters<typeof baseRender>[0],
|
||||
at = "/processor/documents",
|
||||
) =>
|
||||
baseRender(ui, {
|
||||
wrapper: ({ children }) => (
|
||||
<PortalTestProviders>
|
||||
<MemoryRouter initialEntries={[at]}>{children}</MemoryRouter>
|
||||
</PortalTestProviders>
|
||||
),
|
||||
});
|
||||
|
||||
const { FileRunEventList } =
|
||||
await import("@portal/components/failures/FileRunEventList");
|
||||
@@ -101,6 +117,7 @@ describe("FileRunEventList", () => {
|
||||
beforeEach(() => {
|
||||
fetchFileRunEvents.mockReset();
|
||||
applyFileRunEventAction.mockReset();
|
||||
scrollIntoView.mockReset();
|
||||
// The dev-panel test stubs import.meta.env.DEV, which would otherwise persist
|
||||
// into every test after it.
|
||||
vi.unstubAllEnvs();
|
||||
@@ -215,6 +232,24 @@ describe("FileRunEventList", () => {
|
||||
expect(fetchFileRunEvents).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("brings itself into view when a notification links to it", async () => {
|
||||
// It sits below the review queue, so landing on the page is not the same as seeing it.
|
||||
fetchFileRunEvents.mockResolvedValue([event()]);
|
||||
|
||||
render(<FileRunEventList />, "/processor/documents#failures");
|
||||
|
||||
await waitFor(() => expect(scrollIntoView).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it("stays where it is on an ordinary visit to the page", async () => {
|
||||
fetchFileRunEvents.mockResolvedValue([event()]);
|
||||
|
||||
render(<FileRunEventList />);
|
||||
|
||||
await screen.findByText("Password-protected document");
|
||||
expect(scrollIntoView).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("re-reads from the server when an action is refused", async () => {
|
||||
// A 409 means someone else closed it first; the server's view wins.
|
||||
fetchFileRunEvents.mockResolvedValue([event()]);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button, EmptyState, Skeleton, StatusBadge } from "@app/ui";
|
||||
import { PORTAL_FAILURES_ANCHOR } from "@app/routes/portalBasename";
|
||||
import type { FileRunEvent, FailureSeverity } from "@portal/api/fileRunEvents";
|
||||
import {
|
||||
useFileRunEvents,
|
||||
@@ -30,6 +32,15 @@ export function FileRunEventList() {
|
||||
const [busy, setBusy] = useState<{ id: string; action: string } | null>(null);
|
||||
const [showJson, setShowJson] = useState(false);
|
||||
const [clearing, setClearing] = useState(false);
|
||||
const section = useRef<HTMLElement>(null);
|
||||
const { hash, key } = useLocation();
|
||||
|
||||
// A fragment is only honoured on a real page load, not a client-side route change. Keyed on the
|
||||
// navigation too: a second notification changes neither the path nor the hash.
|
||||
useEffect(() => {
|
||||
if (hash !== `#${PORTAL_FAILURES_ANCHOR}`) return;
|
||||
section.current?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
}, [hash, key]);
|
||||
|
||||
// A build without the proprietary module has no such route, and a caller who is
|
||||
// not a team leader gets a 403. Both mean there is nothing to show.
|
||||
@@ -122,7 +133,11 @@ export function FileRunEventList() {
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="portal-failures">
|
||||
<section
|
||||
className="portal-failures"
|
||||
id={PORTAL_FAILURES_ANCHOR}
|
||||
ref={section}
|
||||
>
|
||||
<h2 className="portal-failures__heading">
|
||||
{t("portal.failures.title", "Failures")}
|
||||
</h2>
|
||||
|
||||
@@ -107,9 +107,13 @@ export function Documents() {
|
||||
|
||||
<ReviewQueue documents={documents} loading={state.loading} />
|
||||
|
||||
{/* Recorded policy-run failures. Not mounted outside dev: the endpoints are live and
|
||||
gated, but the surface itself is unfinished (no polling, no paging, no filters).
|
||||
Vite folds this to false in a build, so neither the view nor its fetch ships. */}
|
||||
{/* Recorded policy, pipeline and editor failures. DEV ONLY, deliberately: this list is a
|
||||
stand-in until failures get their own review screen, and it is not the surface we want to
|
||||
ship. The endpoints behind it are live and gated, so nothing here is load-bearing.
|
||||
|
||||
Vite folds this to false in a build, so neither the section nor its fetch ships. The bell's
|
||||
"View in processor" action is gated the same way and for the same reason - lift both
|
||||
together when the review screen lands, or that button navigates nowhere. */}
|
||||
{import.meta.env.DEV && <FileRunEventList />}
|
||||
</div>
|
||||
);
|
||||
|
||||
+271
@@ -0,0 +1,271 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import type {
|
||||
AppNotification,
|
||||
NotificationActionOffer,
|
||||
} from "@app/services/notifications";
|
||||
import type { NotificationActionContext } from "@core/components/notifications/notificationActions";
|
||||
|
||||
/**
|
||||
* Where each action sends the reader. Only the editor has the workbench contexts above it, so the two
|
||||
* shells are the interesting cases: opening the document, or handing it over.
|
||||
*/
|
||||
|
||||
const navigate = vi.fn();
|
||||
vi.mock("react-router-dom", async () => ({
|
||||
...(await vi.importActual<typeof import("react-router-dom")>(
|
||||
"react-router-dom",
|
||||
)),
|
||||
useNavigate: () => navigate,
|
||||
}));
|
||||
|
||||
// No i18n instance here, and the plugin is stubbed because the contexts below reach `core/i18n`.
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (_key: string, fallback: string) => fallback,
|
||||
}),
|
||||
initReactI18next: { type: "3rdParty", init: () => {} },
|
||||
}));
|
||||
|
||||
// IndexedDB, which jsdom has none of. Answered here so presence is a fact of the test.
|
||||
const h = vi.hoisted(() => ({
|
||||
stub: { id: "f-1" } as unknown,
|
||||
getStirlingFileStub: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@app/services/fileStorage", () => ({
|
||||
fileStorage: {
|
||||
getStirlingFileStub: (fileId: string) => h.getStirlingFileStub(fileId),
|
||||
},
|
||||
}));
|
||||
|
||||
const { FileActionsContext, FileStoreContext } =
|
||||
await import("@app/contexts/file/contexts");
|
||||
const { NavigationActionsContext } =
|
||||
await import("@app/contexts/NavigationContext");
|
||||
const { ViewerContext } = await import("@app/contexts/ViewerContext");
|
||||
const { useNotificationActions } =
|
||||
await import("@app/components/notifications/notificationActions");
|
||||
|
||||
const addStirlingFileStubs = vi.fn();
|
||||
const setActiveFileId = vi.fn();
|
||||
const setWorkbench = vi.fn();
|
||||
/** What the workbench already holds, so the "do not add it twice" path can be exercised. */
|
||||
let openFileIds: string[] = [];
|
||||
|
||||
function notification(
|
||||
overrides: Partial<AppNotification> = {},
|
||||
): AppNotification {
|
||||
return {
|
||||
id: "failure:evt-1",
|
||||
source: "FAILURE",
|
||||
kindId: "INPUT_PASSWORD_PROTECTED",
|
||||
origin: "TOOL",
|
||||
ownership: "MINE",
|
||||
severity: "ERROR",
|
||||
status: "NEW",
|
||||
titleKey: "portal.failures.kind.inputPasswordProtected.title",
|
||||
defaultTitle: "Password-protected document",
|
||||
detail: "The PDF Document is passworded",
|
||||
fileId: "f-1",
|
||||
sourceId: null,
|
||||
policyId: null,
|
||||
occurrences: 3,
|
||||
createdAt: "2026-08-06T00:00:00Z",
|
||||
lastSeenAt: "2026-08-06T00:00:00Z",
|
||||
actions: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function offer(id: string): NotificationActionOffer {
|
||||
return {
|
||||
id,
|
||||
labelKey: `portal.failures.action.${id.toLowerCase()}`,
|
||||
defaultLabel: id,
|
||||
enabled: true,
|
||||
disabledReasonKey: null,
|
||||
};
|
||||
}
|
||||
|
||||
function context(
|
||||
overrides: Partial<NotificationActionContext> = {},
|
||||
): NotificationActionContext {
|
||||
return {
|
||||
notification: notification(),
|
||||
hasLocalFile: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** The editor shell: the workbench's providers all sit above the bell. */
|
||||
const inEditor = ({ children }: { children: ReactNode }) => (
|
||||
<MemoryRouter>
|
||||
<FileActionsContext.Provider
|
||||
value={{
|
||||
actions: { addStirlingFileStubs } as never,
|
||||
dispatch: vi.fn(),
|
||||
}}
|
||||
>
|
||||
<FileStoreContext.Provider
|
||||
value={
|
||||
{
|
||||
getState: () => ({ files: { ids: openFileIds } }),
|
||||
subscribe: () => () => {},
|
||||
selectors: {},
|
||||
} as never
|
||||
}
|
||||
>
|
||||
<NavigationActionsContext.Provider
|
||||
value={{ actions: { setWorkbench } } as never}
|
||||
>
|
||||
<ViewerContext.Provider value={{ setActiveFileId } as never}>
|
||||
{children}
|
||||
</ViewerContext.Provider>
|
||||
</NavigationActionsContext.Provider>
|
||||
</FileStoreContext.Provider>
|
||||
</FileActionsContext.Provider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
/** The processor shell: the portal mounts above the app's providers, so there is none. */
|
||||
const inProcessor = ({ children }: { children: ReactNode }) => (
|
||||
<MemoryRouter>{children}</MemoryRouter>
|
||||
);
|
||||
|
||||
function registry(wrapper = inEditor) {
|
||||
return renderHook(() => useNotificationActions(), { wrapper }).result.current;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
navigate.mockReset();
|
||||
addStirlingFileStubs.mockReset().mockResolvedValue([]);
|
||||
setActiveFileId.mockReset();
|
||||
setWorkbench.mockReset();
|
||||
h.getStirlingFileStub.mockReset().mockResolvedValue(h.stub);
|
||||
openFileIds = [];
|
||||
window.sessionStorage.clear();
|
||||
window.history.pushState({}, "", "/");
|
||||
});
|
||||
|
||||
describe("useNotificationActions", () => {
|
||||
it("offers to open the document only while it is still in this browser", () => {
|
||||
const actions = registry();
|
||||
|
||||
expect(actions.VIEW_FILE?.available(context())).toBe(true);
|
||||
expect(actions.VIEW_FILE?.available(context({ hasLocalFile: false }))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves View file as the only usable offer when the server offers actions this build cannot run", () => {
|
||||
// An id this build wires nothing for drops out rather than rendering dead.
|
||||
const actions = registry();
|
||||
const usable = [offer("QUARANTINE"), offer("VIEW_FILE")].filter(
|
||||
(candidate) => actions[candidate.id]?.available(context()) ?? false,
|
||||
);
|
||||
|
||||
expect(usable.map((candidate) => candidate.id)).toEqual(["VIEW_FILE"]);
|
||||
});
|
||||
|
||||
it("opens the document into the viewer when an editor is above", async () => {
|
||||
await registry().VIEW_FILE?.run(context());
|
||||
|
||||
// Selecting alone shows nothing: the workbench holds neither the file nor the viewer yet.
|
||||
expect(addStirlingFileStubs).toHaveBeenCalledWith([h.stub]);
|
||||
expect(setActiveFileId).toHaveBeenCalledWith("f-1");
|
||||
expect(setWorkbench).toHaveBeenCalledWith("viewer");
|
||||
});
|
||||
|
||||
it("stays where it is rather than routing through the role-based root", async () => {
|
||||
// "/" lands on a page chosen by the reader's role, which reads as the app reloading.
|
||||
await registry().VIEW_FILE?.run(context());
|
||||
|
||||
expect(window.location.pathname).toBe("/");
|
||||
expect(navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not add a document the workbench is already holding", async () => {
|
||||
openFileIds = ["f-1"];
|
||||
|
||||
await registry().VIEW_FILE?.run(context());
|
||||
|
||||
expect(addStirlingFileStubs).not.toHaveBeenCalled();
|
||||
// Still brought to the front: the point of the click is to look at it.
|
||||
expect(setActiveFileId).toHaveBeenCalledWith("f-1");
|
||||
expect(setWorkbench).toHaveBeenCalledWith("viewer");
|
||||
});
|
||||
|
||||
it("reports a document that has gone from storage instead of opening nothing", async () => {
|
||||
h.getStirlingFileStub.mockResolvedValue(null);
|
||||
|
||||
const outcome = await registry().VIEW_FILE?.run(context());
|
||||
|
||||
expect(outcome).toEqual({ ok: false });
|
||||
expect(setWorkbench).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("hands the document over to the editor when there is no workbench above it", async () => {
|
||||
await registry(inProcessor).VIEW_FILE?.run(context());
|
||||
|
||||
// The intent outlives the navigation that mounts the editor.
|
||||
expect(
|
||||
window.sessionStorage.getItem("stirling.notifications.pendingSelection"),
|
||||
).toBe("f-1");
|
||||
// The editor's own URL, not the role router at "/".
|
||||
expect(window.location.pathname).toBe("/editor");
|
||||
});
|
||||
|
||||
it("picks up a handed-over document as soon as an editor is there", async () => {
|
||||
window.sessionStorage.setItem(
|
||||
"stirling.notifications.pendingSelection",
|
||||
"f-9",
|
||||
);
|
||||
|
||||
registry();
|
||||
await vi.waitFor(() => expect(setActiveFileId).toHaveBeenCalledWith("f-9"));
|
||||
|
||||
expect(setWorkbench).toHaveBeenCalledWith("viewer");
|
||||
// One-shot: a later mount must not reopen a document the user has moved on from.
|
||||
expect(
|
||||
window.sessionStorage.getItem("stirling.notifications.pendingSelection"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("says it cannot hand the document over rather than navigating to nothing", async () => {
|
||||
// Spied on the prototype: jsdom's storage is a proxy, so an own-property spy does not take.
|
||||
const setItem = vi
|
||||
.spyOn(Storage.prototype, "setItem")
|
||||
.mockImplementation(() => {
|
||||
throw new Error("denied");
|
||||
});
|
||||
|
||||
const outcome = await registry(inProcessor).VIEW_FILE?.run(context());
|
||||
|
||||
expect(outcome).toEqual({
|
||||
ok: false,
|
||||
message:
|
||||
"This browser will not let the processor pass the document to the editor. Open it from the editor instead.",
|
||||
});
|
||||
// Still on the page it started on, so the failure is visible.
|
||||
expect(window.location.pathname).toBe("/");
|
||||
setItem.mockRestore();
|
||||
});
|
||||
|
||||
it("links to the recorded failures section of the processor", () => {
|
||||
registry().VIEW_IN_PROCESSOR?.run(context());
|
||||
|
||||
expect(navigate).toHaveBeenCalledWith("/processor/documents#failures");
|
||||
});
|
||||
|
||||
it("offers the processor link whenever the server did", () => {
|
||||
// The server only sends it to someone it will let read the queue.
|
||||
expect(
|
||||
registry(inProcessor).VIEW_IN_PROCESSOR?.available(
|
||||
context({ hasLocalFile: false }),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useCallback, useContext, useEffect, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { withBasePath } from "@app/constants/app";
|
||||
import {
|
||||
FileActionsContext,
|
||||
FileStoreContext,
|
||||
} from "@app/contexts/file/contexts";
|
||||
import { NavigationActionsContext } from "@app/contexts/NavigationContext";
|
||||
import { ViewerContext } from "@app/contexts/ViewerContext";
|
||||
import {
|
||||
PORTAL_BASENAME,
|
||||
PORTAL_FAILURES_ANCHOR,
|
||||
} from "@app/routes/portalBasename";
|
||||
import { EDITOR_BASENAME } from "@app/routes/editorBasename";
|
||||
import { fileStorage } from "@app/services/fileStorage";
|
||||
import type { FileId } from "@app/types/file";
|
||||
import {
|
||||
type ClientActionOutcome,
|
||||
type ClientActionRegistry,
|
||||
type ClientActionSpec,
|
||||
type NotificationActionContext,
|
||||
} from "@core/components/notifications/notificationActions";
|
||||
|
||||
export {
|
||||
type ClientActionOutcome,
|
||||
type ClientActionRegistry,
|
||||
type ClientActionSpec,
|
||||
type NotificationActionContext,
|
||||
};
|
||||
|
||||
/**
|
||||
* The portal mounts as a sibling of `AppProviders`, so in the processor shell none of the workbench
|
||||
* contexts exist above this hook. That is why contexts are read raw and a document is handed over.
|
||||
*/
|
||||
|
||||
const HANDOFF_KEY = "stirling.notifications.pendingSelection";
|
||||
|
||||
const FAILURES_DESTINATION = `${PORTAL_BASENAME}/documents#${PORTAL_FAILURES_ANCHOR}`;
|
||||
|
||||
/** False when storage refused it: navigating anyway lands the user in an editor with nothing open. */
|
||||
function stashSelection(fileId: string): boolean {
|
||||
try {
|
||||
window.sessionStorage.setItem(HANDOFF_KEY, fileId);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function takeSelection(): string | null {
|
||||
try {
|
||||
const fileId = window.sessionStorage.getItem(HANDOFF_KEY);
|
||||
if (fileId !== null) window.sessionStorage.removeItem(HANDOFF_KEY);
|
||||
return fileId;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Not the router's `navigate`: the editor reads its tool from the URL on mount and on a history pop,
|
||||
* and a router push is neither, so the address would change and the workbench would not.
|
||||
*/
|
||||
function goToEditor(path: string): void {
|
||||
window.history.pushState({}, "", withBasePath(path));
|
||||
window.dispatchEvent(new PopStateEvent("popstate"));
|
||||
}
|
||||
|
||||
export function useNotificationActions(): ClientActionRegistry {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
// Raw, because the hooks that wrap these throw when there is no provider, and in the processor
|
||||
// shell there is none. All four are present together or not at all.
|
||||
const fileContext = useContext(FileActionsContext);
|
||||
const fileStore = useContext(FileStoreContext);
|
||||
const navigation = useContext(NavigationActionsContext);
|
||||
const viewer = useContext(ViewerContext);
|
||||
const canOpenHere = Boolean(fileContext && fileStore && navigation && viewer);
|
||||
|
||||
/**
|
||||
* Opens the way the file sidebar does. Selecting alone shows nothing: an id the workbench does not
|
||||
* hold has nothing to render, and the workbench keeps whatever view it was on.
|
||||
*/
|
||||
const openInWorkbench = useCallback(
|
||||
async (fileId: string): Promise<boolean> => {
|
||||
if (!fileContext || !fileStore || !navigation || !viewer) return false;
|
||||
|
||||
const stub = await fileStorage.getStirlingFileStub(fileId as FileId);
|
||||
if (!stub) return false;
|
||||
|
||||
const alreadyOpen = fileStore
|
||||
.getState()
|
||||
.files.ids.some((id) => (id as string) === fileId);
|
||||
if (!alreadyOpen) {
|
||||
await fileContext.actions.addStirlingFileStubs([stub]);
|
||||
}
|
||||
viewer.setActiveFileId(fileId);
|
||||
navigation.actions.setWorkbench("viewer");
|
||||
return true;
|
||||
},
|
||||
[fileContext, fileStore, navigation, viewer],
|
||||
);
|
||||
|
||||
// One-shot: read and cleared, so a later render cannot reopen a file the user has moved on from.
|
||||
useEffect(() => {
|
||||
if (!canOpenHere) return;
|
||||
const fileId = takeSelection();
|
||||
if (fileId) void openInWorkbench(fileId);
|
||||
}, [canOpenHere, openInWorkbench]);
|
||||
|
||||
return useMemo<ClientActionRegistry>(() => {
|
||||
const openDocument = async (
|
||||
fileId: string | null,
|
||||
): Promise<ClientActionOutcome | void> => {
|
||||
if (!fileId) return;
|
||||
|
||||
// In place, with no navigation: "/" is the role-based router, so going there reads as the app
|
||||
// reloading and lands the user wherever their role says rather than on their document.
|
||||
if (canOpenHere) {
|
||||
return (await openInWorkbench(fileId)) ? undefined : { ok: false };
|
||||
}
|
||||
|
||||
if (!stashSelection(fileId)) {
|
||||
return {
|
||||
ok: false,
|
||||
message: t(
|
||||
"notifications.handoffUnavailable",
|
||||
"This browser will not let the processor pass the document to the editor. Open it from the editor instead.",
|
||||
),
|
||||
};
|
||||
}
|
||||
goToEditor(EDITOR_BASENAME);
|
||||
};
|
||||
|
||||
const viewFile: ClientActionSpec = {
|
||||
available: (context) => context.hasLocalFile,
|
||||
closesPanel: true,
|
||||
run: (context) => openDocument(context.notification.fileId),
|
||||
};
|
||||
|
||||
const viewInProcessor: ClientActionSpec = {
|
||||
// Its destination is dev-only until failures get a review screen; the other half of this gate
|
||||
// is in portal/views/Documents, and both lift together.
|
||||
available: () => import.meta.env.DEV,
|
||||
closesPanel: true,
|
||||
run: () => navigate(FAILURES_DESTINATION),
|
||||
};
|
||||
|
||||
return {
|
||||
VIEW_FILE: viewFile,
|
||||
VIEW_IN_PROCESSOR: viewInProcessor,
|
||||
};
|
||||
}, [canOpenHere, openInWorkbench, navigate, t]);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* This build ships the failure registry and the notification routes, so the bell has
|
||||
* something to read and may mount.
|
||||
*/
|
||||
export function useNotificationsAvailable(): boolean {
|
||||
return true;
|
||||
}
|
||||
+34
-4
@@ -91,7 +91,12 @@ describe("auto-run ordered chaining", () => {
|
||||
|
||||
// The first policy (order 0) runs on the upload; the second waits for the chain.
|
||||
expect(runStored).toHaveBeenCalledTimes(1);
|
||||
expect(runStored).toHaveBeenCalledWith("backend-sec", [{ size: 100 }]);
|
||||
// Recorded against a document this browser can resolve, which is what makes its failure actionable.
|
||||
expect(runStored).toHaveBeenCalledWith(
|
||||
"backend-sec",
|
||||
[{ size: 100 }],
|
||||
"file-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("chains the next policy onto a completed run's output", async () => {
|
||||
@@ -120,8 +125,12 @@ describe("auto-run ordered chaining", () => {
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
});
|
||||
|
||||
// The next policy (order 1) fires on the first policy's output, not the original.
|
||||
expect(runStored).toHaveBeenCalledWith("backend-cls", [{ size: 100 }]);
|
||||
// Fires on the first policy's output and reports that output's own id, not the original's.
|
||||
expect(runStored).toHaveBeenCalledWith(
|
||||
"backend-cls",
|
||||
[{ size: 100 }],
|
||||
"file-1-v2",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps classification out of the server chain when the AI engine is off", async () => {
|
||||
@@ -136,10 +145,31 @@ describe("auto-run ordered chaining", () => {
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
});
|
||||
|
||||
expect(runStored).toHaveBeenCalledWith("backend-sec", [{ size: 100 }]);
|
||||
expect(runStored).toHaveBeenCalledWith(
|
||||
"backend-sec",
|
||||
[{ size: 100 }],
|
||||
"file-1",
|
||||
);
|
||||
expect(runStored).not.toHaveBeenCalledWith(
|
||||
"backend-cls",
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("never dispatches on a file marked derivedFromTool", async () => {
|
||||
// A policy run is billed, so this gate is what stops `importOutputs` re-enforcing a policy on
|
||||
// its own output forever. If this fails, fix the gate rather than the test.
|
||||
setFileStubs([
|
||||
{ id: "file-1", name: "unlocked.pdf", derivedFromTool: true },
|
||||
]);
|
||||
runStored.mockResolvedValue("run-sec");
|
||||
|
||||
renderHook(() => usePolicyAutoRun());
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
});
|
||||
|
||||
expect(runStored).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -113,7 +113,13 @@ describe("auto-run queue-rejection retry", () => {
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(6000);
|
||||
});
|
||||
expect(runStored).toHaveBeenCalledWith("backend-1", [{ size: 1234 }]);
|
||||
// The workspace id travels with the retry too, so a failure of it can still name the
|
||||
// document this browser is holding.
|
||||
expect(runStored).toHaveBeenCalledWith(
|
||||
"backend-1",
|
||||
[{ size: 1234 }],
|
||||
"file-1",
|
||||
);
|
||||
expect(getRun("run-1")).toBeUndefined();
|
||||
expect(getRun("run-2")?.status).toBe("RUNNING");
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
useFileContext,
|
||||
} from "@app/contexts/FileContext";
|
||||
import { fileStorage } from "@app/services/fileStorage";
|
||||
import { refreshNotificationsNow } from "@app/hooks/useNotifications";
|
||||
import { useIndexedDB } from "@app/contexts/IndexedDBContext";
|
||||
import i18n from "@app/i18n";
|
||||
import {
|
||||
@@ -241,6 +242,8 @@ export function usePolicyAutoRun(): void {
|
||||
dispatchKey(finished.categoryId, finished.fileId),
|
||||
);
|
||||
}
|
||||
// Read now rather than leaving them a poll interval to hear about their own upload.
|
||||
if (view.status === "FAILED") refreshNotificationsNow();
|
||||
const code = view.errorCode;
|
||||
if (code !== "PAYG_LIMIT_REACHED" && code !== "FEATURE_DEGRADED") return;
|
||||
if (firedLimitModal.current.has(view.runId)) return;
|
||||
@@ -881,7 +884,9 @@ async function runPolicyOnFile(
|
||||
await acquireDispatchSlot(priority);
|
||||
try {
|
||||
const target = resolvePolicyRunTarget();
|
||||
const runId = await runStoredPolicy(backendId, [file]);
|
||||
// Recorded against a document this browser can resolve. One file per run, which is the only
|
||||
// shape the server keeps a reference for.
|
||||
const runId = await runStoredPolicy(backendId, [file], fileId);
|
||||
// recordRunStart marks this (policy, file) dispatched as it records the run.
|
||||
recordRunStart({
|
||||
runId,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* Only the document reference is pinned, being the one field with a rule attached: a filename here
|
||||
* would reach a table that deliberately has nowhere to keep one.
|
||||
*/
|
||||
|
||||
const post = vi.fn().mockResolvedValue({ data: { jobId: "run-1" } });
|
||||
|
||||
vi.mock("@app/services/apiClient", () => ({
|
||||
default: { post: (...args: unknown[]) => post(...args) },
|
||||
}));
|
||||
|
||||
const { runStoredPolicy } = await import("@app/services/policyApi");
|
||||
|
||||
/** The multipart body the last call sent. */
|
||||
function sentForm(): FormData {
|
||||
return post.mock.calls.at(-1)?.[1] as FormData;
|
||||
}
|
||||
|
||||
const document = () =>
|
||||
new File(["%PDF-1.7"], "quarterly-report.pdf", { type: "application/pdf" });
|
||||
|
||||
describe("runStoredPolicy", () => {
|
||||
beforeEach(() => {
|
||||
post.mockClear();
|
||||
});
|
||||
|
||||
it("sends the workspace id of the document it is running on", async () => {
|
||||
await runStoredPolicy("policy-1", [document()], "editor-file-1");
|
||||
|
||||
expect(post.mock.calls.at(-1)?.[0]).toBe("/api/v1/policies/policy-1/run");
|
||||
expect(sentForm().get("fileId")).toBe("editor-file-1");
|
||||
});
|
||||
|
||||
it("sends no reference when the caller has none", async () => {
|
||||
// The export path can enforce on bytes with no workspace document behind them.
|
||||
await runStoredPolicy("policy-1", [document()]);
|
||||
|
||||
expect(sentForm().has("fileId")).toBe(false);
|
||||
});
|
||||
|
||||
it("never sends the document's name as the reference", async () => {
|
||||
await runStoredPolicy("policy-1", [document()], "editor-file-1");
|
||||
|
||||
expect(sentForm().get("fileId")).not.toContain("quarterly-report");
|
||||
});
|
||||
});
|
||||
@@ -60,13 +60,18 @@ export async function reorderPolicies(orderedIds: string[]): Promise<void> {
|
||||
await apiClient.put("/api/v1/policies/order", orderedIds);
|
||||
}
|
||||
|
||||
/** Run a stored policy by id on the supplied files; returns the run id. */
|
||||
/**
|
||||
* Run a stored policy by id; returns the run id. `fileId` is this workspace's own opaque id, recorded
|
||||
* against any failure of the run. Only honoured for a single-document run, and never a filename.
|
||||
*/
|
||||
export async function runStoredPolicy(
|
||||
id: string,
|
||||
files: File[],
|
||||
fileId?: string,
|
||||
): Promise<string> {
|
||||
const form = new FormData();
|
||||
for (const file of files) form.append("fileInput", file);
|
||||
if (fileId) form.append("fileId", fileId);
|
||||
// Don't set Content-Type: the HTTP client must generate multipart/form-data
|
||||
// WITH its boundary from the FormData body. A manual boundary-less header makes
|
||||
// the server reject the request ("no multipart boundary parameter").
|
||||
|
||||
Reference in New Issue
Block a user