@remit/web-client 0.0.341 → 0.0.343

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import type { RemitImapThreadMessageResponse } from "@remit/api-http-client/types.gen.ts";
2
+ import { type SpamAction } from "@remit/ui";
2
3
  import type { OpenThreadTarget } from "../../routing";
3
4
  import type { ReplyWithText } from "../compose/reply-with-times";
4
5
  export interface IntelligencePaneProps {
@@ -35,18 +36,16 @@ export interface IntelligencePaneProps {
35
36
  onOpenThread?: (target: OpenThreadTarget) => void;
36
37
  }
37
38
  /**
38
- * Decide which spam quick-action to offer for the current message (issue #648).
39
+ * Decide which spam quick-action to offer for the current message.
39
40
  *
40
- * Driven entirely by `Message.spamReport`, never by which mailbox the message
41
- * is currently in: reporting a message that's already in Junk (the provider's
42
- * own filter put it there) is a real, no-op-move case, so mailbox membership
43
- * cannot stand in for "has this been reported". A message that carries a
44
- * report offers the undo ("Not spam"); everything else offers "Report spam".
45
- * Pure so the wiring decision can be unit-tested without rendering.
41
+ * A message that carries a spam report offers the undo (issue #648). An
42
+ * unreported message in Junk offers "Not spam", which moves the thread's Junk
43
+ * messages out and trusts the sender (reader#1553). Everything else offers
44
+ * "Report spam".
46
45
  */
47
46
  export declare const resolveSpamAction: (thread: {
48
47
  spamReport?: unknown;
49
- }) => "notSpam" | "reportSpam";
48
+ }, inJunk: boolean) => SpamAction;
50
49
  /**
51
50
  * Pane 4 of the 4-pane shell: the intelligence sidebar. Wired to real data via
52
51
  * `useIntelligenceData`; renders the `IntelligencePanel` from `@remit/ui`.
@@ -1,7 +1,10 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { threadDetailOperationsListThreadMessagesOptions } from "@remit/api-http-client/@tanstack/react-query.gen.ts";
2
3
  import { CATEGORY_PRESENTATION, categoryLabels, DialogBackdrop, IntelligencePanel, useModalFocus, } from "@remit/ui";
4
+ import { useQueryClient } from "@tanstack/react-query";
3
5
  import { Sparkles } from "lucide-react";
4
- import { useCallback, useRef, useState } from "react";
6
+ import { useCallback, useMemo, useRef, useState } from "react";
7
+ import { useJunkMailbox } from "../../hooks/useArchiveMailbox";
5
8
  import { useIntelligenceCalendar } from "../../hooks/useIntelligenceCalendar";
6
9
  import { useIntelligenceData } from "../../hooks/useIntelligenceData";
7
10
  import { useReportSpam } from "../../hooks/useReportSpam";
@@ -12,16 +15,20 @@ import { useTelemetry } from "../../lib/telemetry-context";
12
15
  const isCategoryOverride = (category) => category !== "uncategorized";
13
16
  const CATEGORY_OVERRIDES = CATEGORY_PRESENTATION.map((entry) => entry.category).filter(isCategoryOverride);
14
17
  /**
15
- * Decide which spam quick-action to offer for the current message (issue #648).
18
+ * Decide which spam quick-action to offer for the current message.
16
19
  *
17
- * Driven entirely by `Message.spamReport`, never by which mailbox the message
18
- * is currently in: reporting a message that's already in Junk (the provider's
19
- * own filter put it there) is a real, no-op-move case, so mailbox membership
20
- * cannot stand in for "has this been reported". A message that carries a
21
- * report offers the undo ("Not spam"); everything else offers "Report spam".
22
- * Pure so the wiring decision can be unit-tested without rendering.
20
+ * A message that carries a spam report offers the undo (issue #648). An
21
+ * unreported message in Junk offers "Not spam", which moves the thread's Junk
22
+ * messages out and trusts the sender (reader#1553). Everything else offers
23
+ * "Report spam".
23
24
  */
24
- export const resolveSpamAction = (thread) => (thread.spamReport ? "notSpam" : "reportSpam");
25
+ export const resolveSpamAction = (thread, inJunk) => {
26
+ if (thread.spamReport)
27
+ return "undoSpamReport";
28
+ if (inJunk)
29
+ return "notSpam";
30
+ return "reportSpam";
31
+ };
25
32
  function IntelligenceSkeleton() {
26
33
  return (_jsxs("aside", { className: "flex h-full w-full flex-col bg-surface-sunken", children: [_jsxs("header", { className: "flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset", children: [_jsx(Sparkles, { className: "size-3.5 text-fg-subtle" }), _jsx("span", { className: "text-2xs font-semibold uppercase tracking-wider text-fg-subtle", children: "Intelligence" })] }), _jsxs("div", { className: "flex-1 animate-pulse space-y-4 p-4", children: [_jsxs("div", { className: "space-y-2", children: [_jsx("div", { className: "h-2.5 rounded bg-surface w-1/4" }), _jsxs("div", { className: "flex gap-3", children: [_jsx("div", { className: "size-10 rounded-full bg-surface shrink-0" }), _jsxs("div", { className: "flex-1 space-y-1.5", children: [_jsx("div", { className: "h-3 rounded bg-surface w-3/4" }), _jsx("div", { className: "h-2.5 rounded bg-surface w-1/2" })] })] })] }), _jsxs("div", { className: "space-y-2", children: [_jsx("div", { className: "h-2.5 rounded bg-surface w-1/4" }), _jsx("div", { className: "h-8 rounded bg-surface" })] }), _jsxs("div", { className: "space-y-2", children: [_jsx("div", { className: "h-2.5 rounded bg-surface w-1/4" }), _jsx("div", { className: "flex gap-1.5 flex-wrap", children: Array.from({ length: 5 }).map((_, i) => (
27
34
  // biome-ignore lint/suspicious/noArrayIndexKey: list is static, no stable id
@@ -47,7 +54,9 @@ function ReclassifyDialog({ isOpen, current, hasOverride, onSelect, onClear, onC
47
54
  * Inner panel that resolves intelligence data and wires quick-action mutations.
48
55
  */
49
56
  function WiredPanel({ thread, onClose, accountId, hideCloseButton, onAfterOptimisticRemove, onReplyWithText, onOpenThread, }) {
50
- const { data, address, addressId } = useIntelligenceData(thread);
57
+ const { data: threadData, address, addressId } = useIntelligenceData(thread);
58
+ const { junkMailboxId } = useJunkMailbox(accountId);
59
+ const queryClient = useQueryClient();
51
60
  const calendar = useIntelligenceCalendar(thread, onReplyWithText, onOpenThread);
52
61
  const [reclassifyOpen, setReclassifyOpen] = useState(false);
53
62
  const senderEmail = thread.fromEmail ?? undefined;
@@ -55,19 +64,41 @@ function WiredPanel({ thread, onClose, accountId, hideCloseButton, onAfterOptimi
55
64
  addressId,
56
65
  senderEmail,
57
66
  });
58
- // "Report spam" / "Not spam" are a contextual pair, decided by whether the
59
- // message carries a spam report — never by the mailbox it's in (issue #648).
60
- const { reportSpam, notSpam, isReporting, isRestoring } = useReportSpam({
67
+ const { reportSpam, notSpam, moveOutOfSpam, isReporting, isRestoring } = useReportSpam({
61
68
  mailboxId: thread.mailboxId,
62
69
  threadId: thread.threadId,
63
70
  accountId,
64
71
  onAfterOptimisticRemove,
65
72
  });
66
73
  const telemetry = useTelemetry();
67
- const spamAction = resolveSpamAction(thread);
74
+ const spamAction = resolveSpamAction(thread, junkMailboxId !== undefined && thread.mailboxId === junkMailboxId);
75
+ const data = useMemo(() => (threadData ? { ...threadData, spamAction } : null), [threadData, spamAction]);
68
76
  const handleNotSpam = useCallback(() => {
69
- notSpam([thread.messageId]);
70
- }, [notSpam, thread.messageId]);
77
+ if (spamAction === "undoSpamReport") {
78
+ notSpam([thread.messageId]);
79
+ return;
80
+ }
81
+ void queryClient
82
+ .ensureQueryData(threadDetailOperationsListThreadMessagesOptions({
83
+ path: { threadId: thread.threadId },
84
+ }))
85
+ .then(({ items }) => {
86
+ const ids = new Set([thread.messageId]);
87
+ for (const message of items) {
88
+ if (message.mailboxId === junkMailboxId)
89
+ ids.add(message.messageId);
90
+ }
91
+ moveOutOfSpam([...ids]);
92
+ });
93
+ }, [
94
+ notSpam,
95
+ moveOutOfSpam,
96
+ queryClient,
97
+ spamAction,
98
+ thread.messageId,
99
+ thread.threadId,
100
+ junkMailboxId,
101
+ ]);
71
102
  const handleReportSpam = useCallback(() => {
72
103
  recordRescueSentToJunk(telemetry, {
73
104
  count: 1,
@@ -101,7 +132,7 @@ function WiredPanel({ thread, onClose, accountId, hideCloseButton, onAfterOptimi
101
132
  onToggleVip: canUpdateFlags ? handleToggleVip : undefined,
102
133
  onToggleMute: canUpdateFlags ? handleToggleMute : undefined,
103
134
  onReclassify: canUpdateFlags ? () => setReclassifyOpen(true) : undefined,
104
- onNotSpam: spamAction === "notSpam" ? handleNotSpam : undefined,
135
+ onNotSpam: spamAction === "reportSpam" ? undefined : handleNotSpam,
105
136
  onReportSpam: spamAction === "reportSpam" ? handleReportSpam : undefined,
106
137
  };
107
138
  if (!data) {
@@ -1,23 +1,34 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
2
  import { configOperationsGetConfigOptions } from "@remit/api-http-client/@tanstack/react-query.gen.ts";
3
+ import { ClassificationUnrunnableReason } from "@remit/domain-enums";
3
4
  import { Badge, Banner, Button, Switch } from "@remit/ui";
4
5
  import { useQuery } from "@tanstack/react-query";
5
6
  import { useId, useRef, useState } from "react";
6
7
  import { useClassificationSettings, useSaveClassification, } from "../../../hooks/useClassificationSettings";
7
- import { isCapped, resetTime, usageCost } from "../../../lib/classification";
8
+ import { isCapped, resetTime, usageCost, withSourceNote, } from "../../../lib/classification";
8
9
  import { DailyLimitCard } from "./DailyLimitCard";
9
10
  import { FailureBanner } from "./FailureBanner";
10
11
  import { ProviderCard } from "./ProviderCard";
11
12
  const LOAD_FAILED = "Mail classification settings did not load";
13
+ const UNRUNNABLE_PIECE = {
14
+ [ClassificationUnrunnableReason.NoBaseUrl]: "a base URL",
15
+ [ClassificationUnrunnableReason.NoApiKey]: "an API key",
16
+ };
12
17
  const switchNote = (settings) => {
13
18
  if (settings.state === "NotConfigured") {
14
19
  return "Save a provider below first. Until then, built-in rules label your mail.";
15
20
  }
16
- if (settings.enabled) {
17
- return "New mail goes to the model. A failed call falls back to built-in rules.";
21
+ if (settings.state === "Unrunnable") {
22
+ return "The provider cannot run yet. Built-in rules label your mail.";
18
23
  }
19
- return "Provider saved. Built-in rules label your mail until you switch this on.";
24
+ const base = settings.enabled
25
+ ? "New mail goes to the model. A failed call falls back to built-in rules."
26
+ : "Provider saved. Built-in rules label your mail until you switch this on.";
27
+ return withSourceNote(base, settings.sources.enabled);
20
28
  };
29
+ function UnrunnableNotice({ settings, }) {
30
+ return (_jsxs(Banner, { tone: "warning", variant: "soft", children: [_jsxs("p", { className: "font-medium", children: ["Classification cannot run without ", UNRUNNABLE_PIECE[settings.reason]] }), _jsxs("p", { className: "mt-0.5 text-fg-muted", children: ["Add ", UNRUNNABLE_PIECE[settings.reason], " below and save. Until then, built-in rules label your mail."] })] }));
31
+ }
21
32
  const namesOf = (accounts) => (accountId) => {
22
33
  const account = accounts.find((entry) => entry.accountId === accountId);
23
34
  return account?.displayName?.trim() || account?.email || accountId;
@@ -50,7 +61,7 @@ function StatusCard({ settings, presets, nameOf, onRaiseLimit, }) {
50
61
  setRefusal(null);
51
62
  toggle.mutate({ body: { classificationEnabled: !on } }, { onError: setRefusal });
52
63
  };
53
- return (_jsxs("section", { "aria-labelledby": `${ids}-title`, className: "space-y-3", children: [_jsx("h2", { id: `${ids}-title`, className: "text-xs font-semibold uppercase tracking-wider text-fg-subtle", children: "Status" }), _jsxs("div", { className: "flex min-h-11 items-center gap-3", children: [_jsxs("span", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("span", { id: `${ids}-label`, className: "text-sm text-fg", children: "Use the model" }), _jsx("span", { id: `${ids}-note`, className: "text-xs text-fg-subtle", children: switchNote(settings) })] }), _jsx(StatusBadge, { on: on, capped: firstCapped !== undefined }), _jsx(Switch, { checked: on, "aria-labelledby": `${ids}-label`, "aria-describedby": `${ids}-note`, "aria-disabled": !configured || toggle.isPending, "aria-busy": toggle.isPending, onToggle: flip })] }), firstCapped && (_jsx(CapBanner, { first: firstCapped, capped: capped, nameOf: nameOf, onRaiseLimit: onRaiseLimit })), configured && (_jsx(UsageRows, { usage: settings.usage, preset: presets.find((preset) => preset.presetId === settings.presetId), nameOf: nameOf })), refusal !== null && (_jsx(FailureBanner, { failure: {
64
+ return (_jsxs("section", { "aria-labelledby": `${ids}-title`, className: "space-y-3", children: [_jsx("h2", { id: `${ids}-title`, className: "text-xs font-semibold uppercase tracking-wider text-fg-subtle", children: "Status" }), _jsxs("div", { className: "flex min-h-11 items-center gap-3", children: [_jsxs("span", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("span", { id: `${ids}-label`, className: "text-sm text-fg", children: "Use the model" }), _jsx("span", { id: `${ids}-note`, className: "text-xs text-fg-subtle", children: switchNote(settings) })] }), _jsx(StatusBadge, { on: on, capped: firstCapped !== undefined }), _jsx(Switch, { checked: on, "aria-labelledby": `${ids}-label`, "aria-describedby": `${ids}-note`, "aria-disabled": !configured || toggle.isPending, "aria-busy": toggle.isPending, onToggle: flip })] }), settings.state === "Unrunnable" && (_jsx(UnrunnableNotice, { settings: settings })), firstCapped && (_jsx(CapBanner, { first: firstCapped, capped: capped, nameOf: nameOf, onRaiseLimit: onRaiseLimit })), configured && (_jsx(UsageRows, { usage: settings.usage, preset: presets.find((preset) => preset.presetId === settings.presetId), nameOf: nameOf })), refusal !== null && (_jsx(FailureBanner, { failure: {
54
65
  title: on
55
66
  ? "Classification was not switched off"
56
67
  : "Classification was not switched on",
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Button, Input } from "@remit/ui";
3
3
  import { useId, useState } from "react";
4
4
  import { useSaveClassification } from "../../../hooks/useClassificationSettings";
5
- import { parseDailyLimit, resetTime } from "../../../lib/classification";
5
+ import { parseDailyLimit, resetTime, withSourceNote, } from "../../../lib/classification";
6
6
  import { FailureBanner } from "./FailureBanner";
7
7
  import { describedBy, Field } from "./Field";
8
8
  export function DailyLimitCard({ settings, inputRef, onAnnounce, }) {
@@ -28,7 +28,7 @@ export function DailyLimitCard({ settings, inputRef, onAnnounce, }) {
28
28
  onError: (cause) => setFailure({ title: "The daily limit was not saved", error: cause }),
29
29
  });
30
30
  };
31
- return (_jsxs("section", { "aria-labelledby": `${ids}-title`, className: "space-y-4", children: [_jsx("h2", { id: `${ids}-title`, className: "text-xs font-semibold uppercase tracking-wider text-fg-subtle", children: "Daily limit" }), _jsx(Field, { id: inputId, label: "Calls per account per day", hint: `${reset}Past the limit, that account's new mail uses built-in rules.`, error: error, children: _jsx(Input, { id: inputId, ref: inputRef, className: "h-11", inputMode: "numeric", value: value, autoComplete: "off", "aria-invalid": error !== undefined, "aria-describedby": describedBy(inputId, true, error !== undefined), onChange: (event) => {
31
+ return (_jsxs("section", { "aria-labelledby": `${ids}-title`, className: "space-y-4", children: [_jsx("h2", { id: `${ids}-title`, className: "text-xs font-semibold uppercase tracking-wider text-fg-subtle", children: "Daily limit" }), _jsx(Field, { id: inputId, label: "Calls per account per day", hint: withSourceNote(`${reset}Past the limit, that account's new mail uses built-in rules.`, settings.sources.dailyLimit), error: error, children: _jsx(Input, { id: inputId, ref: inputRef, className: "h-11", inputMode: "numeric", value: value, autoComplete: "off", "aria-invalid": error !== undefined, "aria-describedby": describedBy(inputId, true, error !== undefined), onChange: (event) => {
32
32
  setValue(event.target.value);
33
33
  setError(undefined);
34
34
  onAnnounce("");
@@ -1,9 +1,9 @@
1
1
  import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { ClassificationValueSource } from "@remit/domain-enums";
2
3
  import { Banner, Button, ConfirmDialog, Input, PasswordInput, Select, } from "@remit/ui";
3
4
  import { useEffect, useId, useRef, useState } from "react";
4
5
  import { useClearClassification, useSaveClassification, useTestClassification, } from "../../../hooks/useClassificationSettings";
5
- import { classificationReportHref, draftForPreset, draftFromSettings, groupPresets, hasSavedKey, needsBaseUrl, presetNote, providerSave, switchingFrom, testFailureHeadline, } from "../../../lib/classification";
6
- import { formatDatePreset } from "../../../lib/format";
6
+ import { classificationReportHref, draftForPreset, draftFromSettings, effectiveValue, groupPresets, hasSavedProvider, isKeyRequiredRefusal, needsBaseUrl, PASTE_KEY, presetNote, providerSave, settingsSources, sourcesFor, switchingFrom, testFailureHeadline, withSourceNote, } from "../../../lib/classification";
7
7
  import { ReportLink } from "../ReportLink";
8
8
  import { FailureBanner } from "./FailureBanner";
9
9
  import { describedBy, Field } from "./Field";
@@ -22,13 +22,11 @@ function TestOutcome({ result, presetLabel, onFix, shown, }) {
22
22
  }
23
23
  function PresetForm({ preset, settings, onAnnounce }) {
24
24
  const save = useSaveClassification();
25
- const clear = useClearClassification();
26
25
  const test = useTestClassification();
27
26
  const [draft, setDraft] = useState(() => draftForPreset(preset, settings));
28
27
  const [fieldError, setFieldError] = useState(null);
29
28
  const [testResult, setTestResult] = useState(null);
30
29
  const [replacing, setReplacing] = useState(false);
31
- const [confirmClear, setConfirmClear] = useState(false);
32
30
  const [failure, setFailure] = useState(null);
33
31
  const [focusTarget, setFocusTarget] = useState(null);
34
32
  const modelRef = useRef(null);
@@ -50,10 +48,11 @@ function PresetForm({ preset, settings, onAnnounce }) {
50
48
  };
51
49
  refs[focusTarget.target].current?.focus();
52
50
  }, [focusTarget]);
53
- const savedKey = preset.needsKey && hasSavedKey(settings, preset.presetId)
54
- ? settings
55
- : undefined;
56
- const showKeyInput = preset.needsKey && (savedKey === undefined || replacing);
51
+ const sources = sourcesFor(settings, preset.presetId);
52
+ const keySource = sources?.apiKey ?? ClassificationValueSource.Default;
53
+ const keyInUse = preset.needsKey && keySource !== ClassificationValueSource.Default;
54
+ const keyInherited = keySource === ClassificationValueSource.Deployment;
55
+ const showKeyInput = preset.needsKey && (!keyInUse || replacing);
57
56
  const shown = {
58
57
  ApiKey: preset.needsKey,
59
58
  Model: true,
@@ -80,7 +79,7 @@ function PresetForm({ preset, settings, onAnnounce }) {
80
79
  focus("Replace");
81
80
  };
82
81
  const fixField = (field) => {
83
- if (field === "ApiKey" && savedKey) {
82
+ if (field === "ApiKey" && keyInUse) {
84
83
  startReplace();
85
84
  return;
86
85
  }
@@ -90,7 +89,7 @@ function PresetForm({ preset, settings, onAnnounce }) {
90
89
  const result = providerSave(draft, preset, settings);
91
90
  if (!result.ok) {
92
91
  setFieldError({ field: result.field, message: result.message });
93
- focus(result.field);
92
+ fixField(result.field);
94
93
  return;
95
94
  }
96
95
  setFailure(null);
@@ -104,7 +103,14 @@ function PresetForm({ preset, settings, onAnnounce }) {
104
103
  if (wasReplacing)
105
104
  focus("Replace");
106
105
  },
107
- onError: (error) => setFailure({ title: `${preset.label} was not saved`, error }),
106
+ onError: (error) => {
107
+ if (isKeyRequiredRefusal(error)) {
108
+ setFieldError({ field: "ApiKey", message: PASTE_KEY });
109
+ fixField("ApiKey");
110
+ return;
111
+ }
112
+ setFailure({ title: `${preset.label} was not saved`, error });
113
+ },
108
114
  });
109
115
  };
110
116
  const onTest = () => {
@@ -128,22 +134,14 @@ function PresetForm({ preset, settings, onAnnounce }) {
128
134
  }),
129
135
  });
130
136
  };
131
- const onClear = () => {
132
- clear.mutate({}, {
133
- onError: (error) => {
134
- setConfirmClear(false);
135
- setFailure({
136
- title: `The ${preset.label} key was not cleared`,
137
- error,
138
- });
139
- },
140
- });
141
- };
142
- const enabled = settings.state === "Configured" && settings.enabled;
137
+ const modelPlaceholder = effectiveValue(settings, preset.presetId, "model") ?? preset.defaultModel;
138
+ const baseUrlPlaceholder = effectiveValue(settings, preset.presetId, "baseUrl") ??
139
+ preset.defaultBaseUrl ??
140
+ "http://localhost:11434/v1";
143
141
  const keyError = errorFor("ApiKey");
144
- return (_jsxs(_Fragment, { children: [_jsx(Field, { id: modelId, label: "Model", hint: `Empty uses ${preset.defaultModel}.`, error: errorFor("Model"), children: _jsx(Input, { id: modelId, ref: modelRef, className: "h-11", value: draft.model, placeholder: preset.defaultModel, autoComplete: "off", spellCheck: false, "aria-invalid": invalid("Model"), "aria-describedby": describedBy(modelId, true, errorFor("Model") !== undefined), onChange: (event) => edit("Model", { model: event.target.value }) }) }), _jsx(Field, { id: baseUrlId, label: "Base URL", hint: "Remit's server calls this URL.", error: errorFor("BaseUrl"), children: _jsx(Input, { id: baseUrlId, ref: baseUrlRef, className: "h-11", type: "url", inputMode: "url", value: draft.baseUrl, placeholder: preset.defaultBaseUrl ?? "http://localhost:11434/v1", autoComplete: "off", spellCheck: false, required: needsBaseUrl(preset), "aria-invalid": invalid("BaseUrl"), "aria-describedby": describedBy(baseUrlId, true, errorFor("BaseUrl") !== undefined), onChange: (event) => edit("BaseUrl", { baseUrl: event.target.value }) }) }), savedKey && !replacing && (_jsxs("div", { children: [_jsx("p", { className: "mb-1 text-xs font-medium text-fg-muted", children: "API key" }), _jsxs("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-2", children: [_jsx("span", { className: invalid("ApiKey") ? "text-sm text-danger" : "text-sm text-fg", children: "set" }), _jsxs("span", { className: "text-sm text-fg-muted", children: ["saved ", formatDatePreset(savedKey.savedAt, "short")] }), _jsx("span", { className: "flex-1" }), _jsx(Button, { ref: replaceRef, variant: "secondary", className: "min-h-11", "aria-invalid": invalid("ApiKey"), onClick: startReplace, children: "Replace" }), _jsx(Button, { variant: "secondary", className: "min-h-11", onClick: () => setConfirmClear(true), children: "Clear" })] })] })), showKeyInput && (_jsx(Field, { id: keyId, label: replacing ? "New API key" : "API key", hint: replacing
145
- ? "The saved key stays in use until you press Save."
146
- : undefined, error: keyError, children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(PasswordInput, { id: keyId, ref: keyRef, className: "h-11 flex-1", value: draft.apiKey, placeholder: replacing ? "Paste the new key" : "Paste the key", autoComplete: "off", spellCheck: false, "aria-invalid": invalid("ApiKey"), "aria-describedby": describedBy(keyId, replacing, keyError !== undefined), onChange: (event) => edit("ApiKey", { apiKey: event.target.value }), onKeyDown: (event) => {
142
+ return (_jsxs(_Fragment, { children: [_jsx(Field, { id: modelId, label: "Model", hint: withSourceNote(`Empty uses ${modelPlaceholder}.`, sources?.model), error: errorFor("Model"), children: _jsx(Input, { id: modelId, ref: modelRef, className: "h-11", value: draft.model, placeholder: modelPlaceholder, autoComplete: "off", spellCheck: false, "aria-invalid": invalid("Model"), "aria-describedby": describedBy(modelId, true, errorFor("Model") !== undefined), onChange: (event) => edit("Model", { model: event.target.value }) }) }), _jsx(Field, { id: baseUrlId, label: "Base URL", hint: withSourceNote("Remit's server calls this URL.", sources?.baseUrl), error: errorFor("BaseUrl"), children: _jsx(Input, { id: baseUrlId, ref: baseUrlRef, className: "h-11", type: "url", inputMode: "url", value: draft.baseUrl, placeholder: baseUrlPlaceholder, autoComplete: "off", spellCheck: false, required: needsBaseUrl(preset), "aria-invalid": invalid("BaseUrl"), "aria-describedby": describedBy(baseUrlId, true, errorFor("BaseUrl") !== undefined), onChange: (event) => edit("BaseUrl", { baseUrl: event.target.value }) }) }), keyInUse && !replacing && (_jsxs("div", { children: [_jsx("p", { className: "mb-1 text-xs font-medium text-fg-muted", children: "API key" }), _jsxs("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-2", children: [keyInherited ? (_jsx("span", { className: invalid("ApiKey")
143
+ ? "text-sm text-danger"
144
+ : "text-sm text-fg-muted", children: "provided by the deployment" })) : (_jsx("span", { className: invalid("ApiKey") ? "text-sm text-danger" : "text-sm text-fg", children: "set" })), _jsx("span", { className: "flex-1" }), _jsx(Button, { ref: replaceRef, variant: "secondary", className: "min-h-11", "aria-invalid": invalid("ApiKey"), onClick: startReplace, children: keyInherited ? "Use your own key" : "Replace" })] })] })), showKeyInput && (_jsx(Field, { id: keyId, label: replacing ? "New API key" : "API key", hint: replacing ? "The key in use stays until you press Save." : undefined, error: keyError, children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(PasswordInput, { id: keyId, ref: keyRef, className: "h-11 flex-1", value: draft.apiKey, placeholder: replacing ? "Paste the new key" : "Paste the key", autoComplete: "off", spellCheck: false, "aria-invalid": invalid("ApiKey"), "aria-describedby": describedBy(keyId, replacing, keyError !== undefined), onChange: (event) => edit("ApiKey", { apiKey: event.target.value }), onKeyDown: (event) => {
147
145
  if (event.key === "Escape" && replacing) {
148
146
  event.preventDefault();
149
147
  event.stopPropagation();
@@ -152,17 +150,40 @@ function PresetForm({ preset, settings, onAnnounce }) {
152
150
  } }), replacing && (_jsx(Button, { variant: "ghost", className: "min-h-11", onClick: cancelReplace, children: "Cancel" }))] }) })), _jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsx(Button, { variant: "primary", className: "min-h-11", "aria-disabled": save.isPending, onClick: () => {
153
151
  if (!save.isPending)
154
152
  onSave();
155
- }, children: save.isPending ? "Saving…" : "Save" }), _jsx(Button, { variant: "secondary", className: "min-h-11", "aria-disabled": test.isPending, "aria-busy": test.isPending, onClick: onTest, children: test.isPending ? "Testing…" : "Test connection" })] }), _jsx("p", { "aria-live": "polite", className: "text-sm text-fg-muted empty:hidden", children: test.isPending ? `Sending one sample message to ${preset.label}` : "" }), testResult && (_jsx(TestOutcome, { result: testResult, presetLabel: preset.label, onFix: fixField, shown: shown })), failure && _jsx(FailureBanner, { failure: failure }), _jsx(ConfirmDialog, { isOpen: confirmClear, title: `Clear the ${preset.label} key?`, description: enabled
156
- ? `Classification is on. Clearing the key switches it off, and new mail goes back to built-in rules. To use ${preset.label} again you paste the key again.`
157
- : `To use ${preset.label} again you paste the key again.`, confirmLabel: "Clear key", destructive: true, isBusy: clear.isPending, onConfirm: onClear, onCancel: () => setConfirmClear(false) })] }));
153
+ }, children: save.isPending ? "Saving…" : "Save" }), _jsx(Button, { variant: "secondary", className: "min-h-11", "aria-disabled": test.isPending, "aria-busy": test.isPending, onClick: onTest, children: test.isPending ? "Testing…" : "Test connection" })] }), _jsx("p", { "aria-live": "polite", className: "text-sm text-fg-muted empty:hidden", children: test.isPending ? `Sending one sample message to ${preset.label}` : "" }), testResult && (_jsx(TestOutcome, { result: testResult, presetLabel: preset.label, onFix: fixField, shown: shown })), failure && _jsx(FailureBanner, { failure: failure })] }));
158
154
  }
159
155
  export function ProviderCard({ presets, settings, onAnnounce, }) {
160
156
  const [presetId, setPresetId] = useState(() => draftFromSettings(settings).presetId);
157
+ const clear = useClearClassification();
158
+ const [confirmClear, setConfirmClear] = useState(false);
159
+ const [cleared, setCleared] = useState(0);
160
+ const [clearFailure, setClearFailure] = useState(null);
161
161
  const presetFieldId = useId();
162
162
  const preset = presets.find((entry) => entry.presetId === presetId);
163
163
  const from = switchingFrom(settings, presetId, presets);
164
- return (_jsxs("section", { className: "space-y-4", children: [_jsx("h2", { className: "text-xs font-semibold uppercase tracking-wider text-fg-subtle", children: "Provider" }), _jsx(Field, { id: presetFieldId, label: "Provider", hint: preset ? presetNote(preset) : undefined, children: _jsxs(Select, { id: presetFieldId, className: "h-11", value: presetId ?? "", onChange: (event) => setPresetId(presets.find((entry) => entry.presetId === event.target.value)
165
- ?.presetId), "aria-describedby": describedBy(presetFieldId, preset !== undefined, false), children: [_jsx("option", { value: "", disabled: true, children: "Choose a provider" }), groupPresets(presets).map((group) => (_jsx("optgroup", { label: group.label, children: group.presets.map((entry) => (_jsx("option", { value: entry.presetId, children: entry.label }, entry.presetId))) }, group.group)))] }) }), from && (_jsxs("p", { className: "text-sm text-warning", children: ["Saving switches from ", from.label, settings.state === "Configured" && settings.apiKeySaved
164
+ const enabled = settings.state === "Configured" && settings.enabled;
165
+ const onClear = () => {
166
+ setClearFailure(null);
167
+ clear.mutate({}, {
168
+ onSuccess: (response) => {
169
+ setConfirmClear(false);
170
+ setPresetId(draftFromSettings(response.classification).presetId);
171
+ setCleared((count) => count + 1);
172
+ },
173
+ onError: (error) => {
174
+ setConfirmClear(false);
175
+ setClearFailure({
176
+ title: "The provider settings were not cleared",
177
+ error,
178
+ });
179
+ },
180
+ });
181
+ };
182
+ return (_jsxs("section", { className: "space-y-4", children: [_jsxs("div", { className: "flex min-h-11 items-center gap-3", children: [_jsx("h2", { className: "flex-1 text-xs font-semibold uppercase tracking-wider text-fg-subtle", children: "Provider" }), hasSavedProvider(settings) && (_jsx(Button, { variant: "secondary", className: "min-h-11", onClick: () => setConfirmClear(true), children: "Clear" }))] }), clearFailure && _jsx(FailureBanner, { failure: clearFailure }), _jsx(Field, { id: presetFieldId, label: "Provider", hint: preset ? presetNote(preset) : undefined, children: _jsxs(Select, { id: presetFieldId, className: "h-11", value: presetId ?? "", onChange: (event) => setPresetId(presets.find((entry) => entry.presetId === event.target.value)
183
+ ?.presetId), "aria-describedby": describedBy(presetFieldId, preset !== undefined, false), children: [_jsx("option", { value: "", disabled: true, children: "Choose a provider" }), groupPresets(presets).map((group) => (_jsx("optgroup", { label: group.label, children: group.presets.map((entry) => (_jsx("option", { value: entry.presetId, children: entry.label }, entry.presetId))) }, group.group)))] }) }), from && (_jsxs("p", { className: "text-sm text-warning", children: ["Saving switches from ", from.label, settingsSources(settings).sources?.apiKey ===
184
+ ClassificationValueSource.Saved
166
185
  ? " and deletes its saved key."
167
- : "."] })), preset && (_jsx(PresetForm, { preset: preset, settings: settings, onAnnounce: onAnnounce }, preset.presetId))] }));
186
+ : "."] })), preset && (_jsx(PresetForm, { preset: preset, settings: settings, onAnnounce: onAnnounce }, `${preset.presetId}-${cleared}`)), _jsx(ConfirmDialog, { isOpen: confirmClear, title: "Clear the provider settings?", description: enabled
187
+ ? "Classification is on. Clearing the provider switches it off, and new mail goes back to built-in rules. Every field returns to the deployment default."
188
+ : "Clearing the provider returns every field to the deployment default.", confirmLabel: "Clear", destructive: true, isBusy: clear.isPending, onConfirm: onClear, onCancel: () => setConfirmClear(false) })] }));
168
189
  }
@@ -1,5 +1,5 @@
1
1
  import type { RemitImapAddressResponse, RemitImapThreadMessageResponse } from "@remit/api-http-client/types.gen.ts";
2
- import type { AuthenticityIntel, IntelligenceData, SenderIntel } from "@remit/ui";
2
+ import type { AuthenticityIntel, IntelligenceData, PlacementIntel, SenderIntel } from "@remit/ui";
3
3
  /**
4
4
  * A sender address we cannot read: empty, missing the `@`, or whose domain
5
5
  * part carries no dot (catches placeholders like `missing_domain` and other
@@ -27,8 +27,9 @@ export declare function buildCategoryIntel(thread: RemitImapThreadMessageRespons
27
27
  export declare function buildSenderIntel(thread: RemitImapThreadMessageResponse, address: RemitImapAddressResponse | undefined): SenderIntel;
28
28
  /** Build authenticity intel from the thread message's authenticity field. */
29
29
  export declare function buildAuthenticityIntel(thread: RemitImapThreadMessageResponse): AuthenticityIntel;
30
+ export declare function buildPlacementIntel(thread: RemitImapThreadMessageResponse): PlacementIntel | undefined;
30
31
  export interface UseIntelligenceDataResult {
31
- data: IntelligenceData | null;
32
+ data: Omit<IntelligenceData, "spamAction"> | null;
32
33
  /**
33
34
  * True when the address lookup failed with a fatal first-party 5xx. The panel
34
35
  * must not silently render the sender's flags (VIP/muted/blocked) as absent —
@@ -206,6 +206,18 @@ export function buildAuthenticityIntel(thread) {
206
206
  summary,
207
207
  };
208
208
  }
209
+ export function buildPlacementIntel(thread) {
210
+ const verdict = thread.placementVerdict;
211
+ if (!verdict)
212
+ return undefined;
213
+ return {
214
+ action: verdict.action,
215
+ confidence: verdict.confidence,
216
+ fromPlacement: verdict.fromPlacement,
217
+ reasons: verdict.reasons,
218
+ dryRun: verdict.dryRun,
219
+ };
220
+ }
209
221
  /**
210
222
  * Maps a `RemitImapThreadMessageResponse` into `IntelligenceData` for the
211
223
  * `IntelligencePanel` component. Two data sources:
@@ -232,7 +244,13 @@ export function useIntelligenceData(thread) {
232
244
  const authenticity = buildAuthenticityIntel(thread);
233
245
  const category = buildCategoryIntel(thread, address);
234
246
  const flags = buildSenderFlags(address);
235
- return { sender, authenticity, category, flags };
247
+ return {
248
+ sender,
249
+ authenticity,
250
+ category,
251
+ flags,
252
+ placement: buildPlacementIntel(thread),
253
+ };
236
254
  }, [thread, address]);
237
255
  return {
238
256
  data,
@@ -1,4 +1,5 @@
1
1
  import type { RemitImapSpamReportBulkResult } from "@remit/api-http-client/types.gen.ts";
2
+ import { ApiError } from "../lib/api";
2
3
  interface UseReportSpamOptions {
3
4
  /** The mailbox the message currently sits in — scopes which list caches settle-time invalidation reaches. */
4
5
  mailboxId: string;
@@ -52,9 +53,9 @@ export declare const humanizeSpamFailureReason: (reason: string, messageId: stri
52
53
  * call — a partial (or total) failure is not a thrown error on the wire. The
53
54
  * generated mutation helpers only ever reject on a non-2xx response, so
54
55
  * without this the hook would report success for a message whose report or
55
- * undo never actually happened. Every caller here sends exactly one message
56
- * per call, so surfacing the first failure's reason is surfacing the whole
57
- * story, not truncating a real batch.
56
+ * undo never actually happened. The thrown error carries the batch's
57
+ * `failureCount` for the banner title and the first failure's reason as its
58
+ * message.
58
59
  *
59
60
  * Throws `ApiError` — not a bare `Error` — carrying a 4xx status. The
60
61
  * client's fail-fast contract (`lib/error-classifier.ts`'s `shouldEscalate`,
@@ -70,15 +71,18 @@ export declare const humanizeSpamFailureReason: (reason: string, messageId: stri
70
71
  * like this one; this is the one place synthesizing a failure from a 200
71
72
  * body, so it has to synthesize both.
72
73
  */
74
+ export declare class SpamBulkFailureError extends ApiError {
75
+ readonly failureCount: number;
76
+ constructor(message: string, failureCount: number);
77
+ }
73
78
  export declare const throwOnBulkFailure: (data: RemitImapSpamReportBulkResult) => void;
74
79
  /**
75
- * Composes `POST /messages/report-spam` and `POST /messages/not-spam`
76
- * (issue #648). Both fold the sender-flag write, the Junk move and the
77
- * `$Junk` keyword marker into one server-side operation
78
- * (`SpamReportService`) — the client only sends `messageIds` and reflects the
79
- * result, it does not sequence the three writes itself, and it never derives
80
- * "reported" from placement (a report on a message already in Junk — the
81
- * provider's own filter put it there — is a real, no-op-move case).
80
+ * Composes `POST /messages/report-spam` and `POST /messages/not-spam`. Both
81
+ * fold the sender-flag write, the mailbox move and the `$Junk` keyword marker
82
+ * into one server-side operation (`SpamReportService`); the client only sends
83
+ * `messageIds` and reflects the result. `notSpam` undoes a spam report;
84
+ * `moveOutOfSpam` sends the same request for unreported Junk messages and
85
+ * differs only in its failure copy.
82
86
  *
83
87
  * No optimistic cache patch, unlike `useMoveMessages`/`useDeleteMessages`:
84
88
  * neither endpoint's response says whether the message actually changed
@@ -86,7 +90,8 @@ export declare const throwOnBulkFailure: (data: RemitImapSpamReportBulkResult) =
86
90
  * silent no-op), so predicting the row should vanish would flicker it back
87
91
  * on invalidation for a no-op — worst on `notSpam`, whose R2 wait can run
88
92
  * several seconds before the row "pops back". The list settles from
89
- * `onSuccess`'s invalidation instead, which is always correct. `isReporting`/
93
+ * `onSettled`'s invalidation instead, which also runs on a partial failure so
94
+ * the messages that did move leave the list. `isReporting`/
90
95
  * `isRestoring` below exist to pay for the UX this trades away: without them
91
96
  * a press produces no visible change at all until the request lands — the
92
97
  * caller wires them into the quick action's pending state.
@@ -94,6 +99,7 @@ export declare const throwOnBulkFailure: (data: RemitImapSpamReportBulkResult) =
94
99
  export declare function useReportSpam({ mailboxId, threadId, accountId, onAfterOptimisticRemove, }: UseReportSpamOptions): {
95
100
  reportSpam: (messageIds: string[]) => void;
96
101
  notSpam: (messageIds: string[]) => void;
102
+ moveOutOfSpam: (messageIds: string[]) => void;
97
103
  /** True while a report is in flight — wire into the "Report spam" quick action's pending state; a press with no visible response is the dead-button failure mode. */
98
104
  isReporting: boolean;
99
105
  /** True while an undo is in flight — wire into the "Not spam" quick action's pending state. */
@@ -38,9 +38,9 @@ export const humanizeSpamFailureReason = (reason, messageId) => reason.replace(`
38
38
  * call — a partial (or total) failure is not a thrown error on the wire. The
39
39
  * generated mutation helpers only ever reject on a non-2xx response, so
40
40
  * without this the hook would report success for a message whose report or
41
- * undo never actually happened. Every caller here sends exactly one message
42
- * per call, so surfacing the first failure's reason is surfacing the whole
43
- * story, not truncating a real batch.
41
+ * undo never actually happened. The thrown error carries the batch's
42
+ * `failureCount` for the banner title and the first failure's reason as its
43
+ * message.
44
44
  *
45
45
  * Throws `ApiError` — not a bare `Error` — carrying a 4xx status. The
46
46
  * client's fail-fast contract (`lib/error-classifier.ts`'s `shouldEscalate`,
@@ -56,6 +56,13 @@ export const humanizeSpamFailureReason = (reason, messageId) => reason.replace(`
56
56
  * like this one; this is the one place synthesizing a failure from a 200
57
57
  * body, so it has to synthesize both.
58
58
  */
59
+ export class SpamBulkFailureError extends ApiError {
60
+ failureCount;
61
+ constructor(message, failureCount) {
62
+ super(message, 422);
63
+ this.failureCount = failureCount;
64
+ }
65
+ }
59
66
  export const throwOnBulkFailure = (data) => {
60
67
  if (data.failureCount === 0)
61
68
  return;
@@ -64,16 +71,15 @@ export const throwOnBulkFailure = (data) => {
64
71
  const message = failure
65
72
  ? humanizeSpamFailureReason(reason, failure.messageId)
66
73
  : reason;
67
- throw new ApiError(message, 422);
74
+ throw new SpamBulkFailureError(message, data.failureCount);
68
75
  };
69
76
  /**
70
- * Composes `POST /messages/report-spam` and `POST /messages/not-spam`
71
- * (issue #648). Both fold the sender-flag write, the Junk move and the
72
- * `$Junk` keyword marker into one server-side operation
73
- * (`SpamReportService`) — the client only sends `messageIds` and reflects the
74
- * result, it does not sequence the three writes itself, and it never derives
75
- * "reported" from placement (a report on a message already in Junk — the
76
- * provider's own filter put it there — is a real, no-op-move case).
77
+ * Composes `POST /messages/report-spam` and `POST /messages/not-spam`. Both
78
+ * fold the sender-flag write, the mailbox move and the `$Junk` keyword marker
79
+ * into one server-side operation (`SpamReportService`); the client only sends
80
+ * `messageIds` and reflects the result. `notSpam` undoes a spam report;
81
+ * `moveOutOfSpam` sends the same request for unreported Junk messages and
82
+ * differs only in its failure copy.
77
83
  *
78
84
  * No optimistic cache patch, unlike `useMoveMessages`/`useDeleteMessages`:
79
85
  * neither endpoint's response says whether the message actually changed
@@ -81,7 +87,8 @@ export const throwOnBulkFailure = (data) => {
81
87
  * silent no-op), so predicting the row should vanish would flicker it back
82
88
  * on invalidation for a no-op — worst on `notSpam`, whose R2 wait can run
83
89
  * several seconds before the row "pops back". The list settles from
84
- * `onSuccess`'s invalidation instead, which is always correct. `isReporting`/
90
+ * `onSettled`'s invalidation instead, which also runs on a partial failure so
91
+ * the messages that did move leave the list. `isReporting`/
85
92
  * `isRestoring` below exist to pay for the UX this trades away: without them
86
93
  * a press produces no visible change at all until the request lands — the
87
94
  * caller wires them into the quick action's pending state.
@@ -106,17 +113,27 @@ export function useReportSpam({ mailboxId, threadId, accountId, onAfterOptimisti
106
113
  });
107
114
  }
108
115
  };
109
- const buildOnSuccess = () => (_data, variables) => {
110
- invalidateAffectedQueries();
116
+ const onSuccess = (_data, variables) => {
111
117
  onAfterOptimisticRemove?.(variables.body.messageIds);
112
118
  };
113
119
  const buildOnError = (failureTitle) => (err, vars) => {
120
+ const count = err instanceof SpamBulkFailureError
121
+ ? err.failureCount
122
+ : vars.body.messageIds.length;
114
123
  pushError({
115
- title: failureTitle(vars.body.messageIds.length),
124
+ title: failureTitle(count),
116
125
  detail: formatErrorDetail(err),
117
126
  error: err,
118
127
  });
119
128
  };
129
+ const sendNotSpam = async (variables) => {
130
+ const { data } = await messageBulkOperationsNotSpam({
131
+ ...variables,
132
+ throwOnError: true,
133
+ });
134
+ throwOnBulkFailure(data);
135
+ return data;
136
+ };
120
137
  const report = useMutation({
121
138
  mutationFn: async (variables) => {
122
139
  const { data } = await messageBulkOperationsReportSpam({
@@ -132,26 +149,30 @@ export function useReportSpam({ mailboxId, threadId, accountId, onAfterOptimisti
132
149
  // isn't enough: `shouldEscalate` defaults to escalate for a non-5xx that
133
150
  // doesn't opt out here.
134
151
  meta: { softError: true },
135
- onSuccess: buildOnSuccess(),
152
+ onSuccess,
153
+ onSettled: invalidateAffectedQueries,
136
154
  onError: buildOnError((count) => count > 1
137
155
  ? `Couldn't report ${count} messages as spam`
138
156
  : "Couldn't report this message as spam"),
139
157
  });
140
158
  const restore = useMutation({
141
- mutationFn: async (variables) => {
142
- const { data } = await messageBulkOperationsNotSpam({
143
- ...variables,
144
- throwOnError: true,
145
- });
146
- throwOnBulkFailure(data);
147
- return data;
148
- },
159
+ mutationFn: sendNotSpam,
149
160
  meta: { softError: true },
150
- onSuccess: buildOnSuccess(),
161
+ onSuccess,
162
+ onSettled: invalidateAffectedQueries,
151
163
  onError: buildOnError((count) => count > 1
152
164
  ? `Couldn't undo the spam report for ${count} messages`
153
165
  : "Couldn't undo the spam report"),
154
166
  });
167
+ const moveOut = useMutation({
168
+ mutationFn: sendNotSpam,
169
+ meta: { softError: true },
170
+ onSuccess,
171
+ onSettled: invalidateAffectedQueries,
172
+ onError: buildOnError((count) => count > 1
173
+ ? `Couldn't move ${count} messages out of Spam`
174
+ : "Couldn't move this message out of Spam"),
175
+ });
155
176
  const reportSpam = useCallback((messageIds) => {
156
177
  if (messageIds.length === 0)
157
178
  return;
@@ -162,12 +183,18 @@ export function useReportSpam({ mailboxId, threadId, accountId, onAfterOptimisti
162
183
  return;
163
184
  void runChunkedMutation(messageIds, (chunk) => restore.mutateAsync({ body: { messageIds: chunk } }));
164
185
  }, [restore.mutateAsync]);
186
+ const moveOutOfSpam = useCallback((messageIds) => {
187
+ if (messageIds.length === 0)
188
+ return;
189
+ void runChunkedMutation(messageIds, (chunk) => moveOut.mutateAsync({ body: { messageIds: chunk } }));
190
+ }, [moveOut.mutateAsync]);
165
191
  return {
166
192
  reportSpam,
167
193
  notSpam,
194
+ moveOutOfSpam,
168
195
  /** True while a report is in flight — wire into the "Report spam" quick action's pending state; a press with no visible response is the dead-button failure mode. */
169
196
  isReporting: report.isPending,
170
197
  /** True while an undo is in flight — wire into the "Not spam" quick action's pending state. */
171
- isRestoring: restore.isPending,
198
+ isRestoring: restore.isPending || moveOut.isPending,
172
199
  };
173
200
  }
@@ -1,4 +1,4 @@
1
- import type { RemitImapClassificationConfigured, RemitImapClassificationField, RemitImapClassificationPreset, RemitImapClassificationPresetGroup, RemitImapClassificationPresetId, RemitImapClassificationSettings, RemitImapClassificationTestFailed, RemitImapClassificationUsage, RemitImapUpdateUserSettingsInput } from "@remit/api-http-client/types.gen.ts";
1
+ import type { RemitImapClassificationField, RemitImapClassificationPreset, RemitImapClassificationPresetGroup, RemitImapClassificationPresetId, RemitImapClassificationSettings, RemitImapClassificationSources, RemitImapClassificationTestFailed, RemitImapClassificationUsage, RemitImapClassificationValueSource, RemitImapUpdateUserSettingsInput } from "@remit/api-http-client/types.gen.ts";
2
2
  export declare const classificationQueryMeta: {
3
3
  softErrorStatuses: number[];
4
4
  };
@@ -13,8 +13,17 @@ export interface ProviderDraft {
13
13
  baseUrl: string;
14
14
  apiKey: string;
15
15
  }
16
+ export interface SettingsSources {
17
+ presetId: RemitImapClassificationPresetId | undefined;
18
+ sources: RemitImapClassificationSources | undefined;
19
+ }
20
+ export declare const settingsSources: (settings: RemitImapClassificationSettings) => SettingsSources;
21
+ export declare const sourcesFor: (settings: RemitImapClassificationSettings, presetId: RemitImapClassificationPresetId) => RemitImapClassificationSources | undefined;
22
+ type ProviderValueField = "model" | "baseUrl";
23
+ export declare const effectiveValue: (settings: RemitImapClassificationSettings, presetId: RemitImapClassificationPresetId, field: ProviderValueField) => string | undefined;
16
24
  export declare const draftFromSettings: (settings: RemitImapClassificationSettings) => ProviderDraft;
17
25
  export declare const draftForPreset: (preset: RemitImapClassificationPreset, settings: RemitImapClassificationSettings) => ProviderDraft;
26
+ export declare const hasSavedProvider: (settings: RemitImapClassificationSettings) => boolean;
18
27
  export interface PresetGroup {
19
28
  group: RemitImapClassificationPresetGroup;
20
29
  label: string;
@@ -22,7 +31,7 @@ export interface PresetGroup {
22
31
  }
23
32
  export declare const groupPresets: (presets: readonly RemitImapClassificationPreset[]) => PresetGroup[];
24
33
  export declare const needsBaseUrl: (preset: RemitImapClassificationPreset) => boolean;
25
- export declare const hasSavedKey: (settings: RemitImapClassificationSettings, presetId: RemitImapClassificationPresetId | undefined) => settings is RemitImapClassificationConfigured;
34
+ export declare const withSourceNote: (text: string, source: RemitImapClassificationValueSource | undefined) => string;
26
35
  export type ProviderSave = {
27
36
  ok: true;
28
37
  body: RemitImapUpdateUserSettingsInput;
@@ -32,6 +41,7 @@ export type ProviderSave = {
32
41
  message: string;
33
42
  };
34
43
  export declare const PASTE_KEY = "Paste an API key";
44
+ export declare const isKeyRequiredRefusal: (error: unknown) => boolean;
35
45
  export declare const BAD_URL = "Enter a URL that starts with http:// or https://";
36
46
  export declare const providerSave: (draft: ProviderDraft, preset: RemitImapClassificationPreset, settings: RemitImapClassificationSettings) => ProviderSave;
37
47
  export declare const switchingFrom: (settings: RemitImapClassificationSettings, presetId: RemitImapClassificationPresetId | undefined, presets: readonly RemitImapClassificationPreset[]) => RemitImapClassificationPreset | undefined;
@@ -50,3 +60,4 @@ export declare const parseDailyLimit: (value: string) => DailyLimitInput;
50
60
  export declare const isCapped: (usage: RemitImapClassificationUsage) => boolean;
51
61
  export declare const usageCost: (usage: RemitImapClassificationUsage, preset: RemitImapClassificationPreset | undefined) => string;
52
62
  export declare const resetTime: (resetsAt: string) => string;
63
+ export {};
@@ -1,3 +1,5 @@
1
+ import { ClassificationValueSource } from "@remit/domain-enums";
2
+ import { codedApiErrorBody } from "./api";
1
3
  import { buildBugReportContext, buildGitHubIssueUrl } from "./bug-report";
2
4
  import { getErrorStatus, ownsServerErrorsMeta, softErrorStatuses, } from "./error-classifier";
3
5
  import { formatDate } from "./format";
@@ -7,27 +9,43 @@ export const classificationActionMeta = {
7
9
  ...ownsServerErrorsMeta,
8
10
  };
9
11
  export const isClassificationSignedOut = (error) => getErrorStatus(error) === 403;
10
- export const draftFromSettings = (settings) => settings.state === "Configured"
11
- ? {
12
- presetId: settings.presetId,
13
- model: settings.model,
14
- baseUrl: settings.baseUrl,
15
- apiKey: "",
12
+ export const settingsSources = (settings) => {
13
+ if (settings.state === "NotConfigured") {
14
+ return { presetId: undefined, sources: undefined };
16
15
  }
17
- : { presetId: undefined, model: "", baseUrl: "", apiKey: "" };
18
- export const draftForPreset = (preset, settings) => {
19
- const draft = settings.state === "Configured" && settings.presetId === preset.presetId
20
- ? draftFromSettings(settings)
21
- : {
22
- presetId: preset.presetId,
23
- model: "",
24
- baseUrl: "",
25
- apiKey: "",
26
- };
27
- return {
28
- ...draft,
29
- baseUrl: draft.baseUrl === "" ? (preset.defaultBaseUrl ?? "") : draft.baseUrl,
30
- };
16
+ if (settings.state === "Unrunnable") {
17
+ return { presetId: settings.presetId, sources: undefined };
18
+ }
19
+ return { presetId: settings.presetId, sources: settings.sources };
20
+ };
21
+ export const sourcesFor = (settings, presetId) => {
22
+ const current = settingsSources(settings);
23
+ return current.presetId === presetId ? current.sources : undefined;
24
+ };
25
+ const savedValue = (settings, field) => settings.state === "Configured" &&
26
+ settings.sources[field] === ClassificationValueSource.Saved
27
+ ? settings[field]
28
+ : "";
29
+ export const effectiveValue = (settings, presetId, field) => settings.state === "Configured" &&
30
+ settings.presetId === presetId &&
31
+ settings[field] !== ""
32
+ ? settings[field]
33
+ : undefined;
34
+ export const draftFromSettings = (settings) => ({
35
+ presetId: settingsSources(settings).presetId,
36
+ model: savedValue(settings, "model"),
37
+ baseUrl: savedValue(settings, "baseUrl"),
38
+ apiKey: "",
39
+ });
40
+ export const draftForPreset = (preset, settings) => settingsSources(settings).presetId === preset.presetId
41
+ ? draftFromSettings(settings)
42
+ : { presetId: preset.presetId, model: "", baseUrl: "", apiKey: "" };
43
+ export const hasSavedProvider = (settings) => {
44
+ if (settings.state === "Unrunnable")
45
+ return true;
46
+ if (settings.state === "NotConfigured")
47
+ return false;
48
+ return Object.values(settings.sources).includes(ClassificationValueSource.Saved);
31
49
  };
32
50
  const GROUP_LABELS = {
33
51
  Hosted: "Hosted",
@@ -51,10 +69,17 @@ export const groupPresets = (presets) => {
51
69
  return groups;
52
70
  };
53
71
  export const needsBaseUrl = (preset) => preset.defaultBaseUrl === undefined;
54
- export const hasSavedKey = (settings, presetId) => settings.state === "Configured" &&
55
- settings.presetId === presetId &&
56
- settings.apiKeySaved;
72
+ export const withSourceNote = (text, source) => {
73
+ if (source === ClassificationValueSource.Saved) {
74
+ return `${text} Saved by you.`;
75
+ }
76
+ if (source === ClassificationValueSource.Deployment) {
77
+ return `${text} Provided by the deployment.`;
78
+ }
79
+ return text;
80
+ };
57
81
  export const PASTE_KEY = "Paste an API key";
82
+ export const isKeyRequiredRefusal = (error) => codedApiErrorBody(error)?.code === "ClassificationApiKeyRequired";
58
83
  export const BAD_URL = "Enter a URL that starts with http:// or https://";
59
84
  const isHttpUrl = (value) => {
60
85
  if (!URL.canParse(value))
@@ -65,18 +90,22 @@ const isHttpUrl = (value) => {
65
90
  export const providerSave = (draft, preset, settings) => {
66
91
  const baseUrl = draft.baseUrl.trim();
67
92
  const apiKey = draft.apiKey.trim();
93
+ const sources = sourcesFor(settings, preset.presetId);
68
94
  if (baseUrl !== "" && !isHttpUrl(baseUrl)) {
69
95
  return { ok: false, field: "BaseUrl", message: BAD_URL };
70
96
  }
71
- if (baseUrl === "" && needsBaseUrl(preset)) {
97
+ if (baseUrl === "" &&
98
+ needsBaseUrl(preset) &&
99
+ effectiveValue(settings, preset.presetId, "baseUrl") === undefined) {
72
100
  return { ok: false, field: "BaseUrl", message: BAD_URL };
73
101
  }
102
+ const keySource = sources?.apiKey ?? ClassificationValueSource.Default;
74
103
  if (preset.needsKey &&
75
104
  apiKey === "" &&
76
- !hasSavedKey(settings, preset.presetId)) {
105
+ keySource === ClassificationValueSource.Default) {
77
106
  return { ok: false, field: "ApiKey", message: PASTE_KEY };
78
107
  }
79
- const switching = settings.state !== "Configured" || settings.presetId !== preset.presetId;
108
+ const switching = settingsSources(settings).presetId !== preset.presetId;
80
109
  return {
81
110
  ok: true,
82
111
  body: {
@@ -90,12 +119,12 @@ export const providerSave = (draft, preset, settings) => {
90
119
  };
91
120
  };
92
121
  export const switchingFrom = (settings, presetId, presets) => {
93
- if (settings.state !== "Configured" || presetId === undefined) {
122
+ const current = settingsSources(settings).presetId;
123
+ if (current === undefined || presetId === undefined)
94
124
  return undefined;
95
- }
96
- if (settings.presetId === presetId)
125
+ if (current === presetId)
97
126
  return undefined;
98
- return presets.find((preset) => preset.presetId === settings.presetId);
127
+ return presets.find((preset) => preset.presetId === current);
99
128
  };
100
129
  export const testFailureHeadline = (failure) => {
101
130
  const answer = failure.status === undefined ? failure.kind : `${failure.status}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remit/web-client",
3
- "version": "0.0.341",
3
+ "version": "0.0.343",
4
4
  "type": "module",
5
5
  "description": "Remit web client, published as composable primitives — the app shell, auth shells, and runtime config. A distributor imports what it composes and bundles it.",
6
6
  "exports": {
@@ -91,7 +91,7 @@
91
91
  },
92
92
  "dependencies": {
93
93
  "@hookform/resolvers": "5.4.0",
94
- "@remit/ui": "0.0.233",
94
+ "@remit/ui": "0.0.234",
95
95
  "@tanstack/react-query": "5.101.2",
96
96
  "@tanstack/react-query-devtools": "5.101.2",
97
97
  "@tanstack/react-router": "1.170.18",