@blackbelt-technology/pi-dashboard-gmail-plugin 0.9.0 → 0.11.0

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.
@@ -12,45 +12,74 @@
12
12
  * overwrite it or re-mount the flow); every flow error rendered as a sentence
13
13
  * (`errorKey` / `ERROR_EN`); Revoke via `ui:confirm-dialog`; alias feedback;
14
14
  * level descriptions; collapsed-summary project/client id.
15
+ *
16
+ * retro-ux-plugin-settings-forms: labelled inputs through the shared settings
17
+ * field family, numbered wizard step chips (`aria-current="step"`, done = check),
18
+ * "Connected" / "Re-auth needed" pills, per-account control names, one primary
19
+ * "Add account" button with a linked disabled reason, flow errors as a severity
20
+ * notice. Immediate-save model unchanged.
15
21
  */
16
- import { oauthFlowClient, useT, useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
22
+ import {
23
+ copyText,
24
+ FieldShell,
25
+ oauthFlowClient,
26
+ SafeLink,
27
+ SelectField,
28
+ SettingsGroup,
29
+ SettingsNotice,
30
+ TextField,
31
+ ToggleField,
32
+ useT,
33
+ useUiPrimitive,
34
+ } from "@blackbelt-technology/dashboard-plugin-runtime";
17
35
  import type React from "react";
18
36
  import { useCallback, useEffect, useId, useRef, useState } from "react";
37
+ import type { Audience, AutoSetupState, SetupRunView } from "../shared/auto-setup.js";
19
38
  import { validateClientJson } from "../shared/client-json.js";
20
39
  import type { AccountInfo } from "../shared/protocol.js";
21
40
  import { TIERS, type Tier } from "../shared/scopes.js";
22
- import { consoleLinks, ERROR_EN, errorKey, errorStep, gcloudCommands, type WizardStep } from "./wizard.js";
23
-
24
- const API = "/api/plugins/gmail";
41
+ import { classifyProjectId, isEmail, normalizeEmail, normalizeProjectId } from "../shared/setup.js";
42
+ import { AutoSetupSection } from "./AutoSetup.js";
43
+ import { showUnverifiedNotice } from "./auto-setup.js";
44
+ import { api, btn, errorText, muted } from "./ui.js";
45
+ import {
46
+ AUDIENCE_HELP_EN,
47
+ CONSENT_HINT_EN,
48
+ consoleLinks,
49
+ ERROR_EN,
50
+ errorKey,
51
+ errorStep,
52
+ gcloudCommands,
53
+ UNVERIFIED_HINT_EN,
54
+ type WizardStep,
55
+ } from "./wizard.js";
25
56
 
26
57
  interface GmailState {
27
58
  client: { configured: boolean; clientId?: string; projectId?: string };
28
59
  accounts: AccountInfo[];
60
+ /** Saved setup fields (`plugins.gmail`); absent from older servers. */
61
+ setup?: { projectId?: string; ownerAccount?: string };
62
+ /** Automatic-setup availability; absent from older servers. See change: add-gmail-auto-setup. */
63
+ autoSetup?: AutoSetupState;
64
+ }
65
+
66
+ interface SavedSetup {
67
+ projectId: string;
68
+ ownerAccount: string;
29
69
  }
30
70
 
31
71
  type FlowState = React.ComponentProps<ReturnType<typeof useUiPrimitive<"ui:oauth-flow">>>["flow"];
32
72
  type FlowStatus = NonNullable<FlowState["status"]>;
33
73
 
34
- async function api<T>(path: string, init?: RequestInit): Promise<T> {
35
- const res = await fetch(`${API}${path}`, {
36
- ...init,
37
- headers: init?.body ? { "content-type": "application/json" } : undefined,
38
- });
39
- const body = (await res.json().catch(() => ({}))) as T & { error?: string };
40
- if (!res.ok) throw Object.assign(new Error(body.error ?? `HTTP ${res.status}`), { code: body.error });
41
- return body;
42
- }
43
-
44
- const btn =
45
- "focus-ring rounded border border-[var(--border-primary)] px-2 py-0.5 text-[12px] hover:bg-[var(--bg-hover)] disabled:opacity-50";
46
- const field = "focus-ring rounded border border-[var(--border-primary)] bg-transparent text-[12px]";
47
- const muted = "text-[12px] text-[var(--text-muted)]";
48
- const errorText = "text-[12px] text-[var(--severity-error-fg)]";
74
+ // The section's one primary action (white on the theme-invariant `--accent-solid`).
75
+ const primaryBtn =
76
+ "focus-ring tap-target rounded-md bg-[var(--accent-solid)] px-3 text-xs font-semibold text-white disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-secondary)]";
77
+ const field =
78
+ "focus-ring rounded border border-[var(--border-secondary)] bg-[var(--bg-tertiary)] px-2 py-1 text-xs text-[var(--text-primary)]";
49
79
  // Static strings: Tailwind cannot see interpolated class names.
50
- const badgeOk =
51
- "rounded border border-[var(--severity-success-border)] bg-[var(--severity-success-bg)] px-1 text-[11px] text-[var(--severity-success-fg)]";
52
- const badgeReauth =
53
- "rounded border border-[var(--severity-warning-border)] bg-[var(--severity-warning-bg)] px-1 text-[11px] text-[var(--severity-warning-fg)]";
80
+ const pillBase = "inline-flex items-center rounded-full border px-1.5 py-px text-[11px] font-semibold";
81
+ const badgeOk = `${pillBase} border-[var(--severity-success-border)] bg-[var(--severity-success-bg)] text-[var(--severity-success-fg)]`;
82
+ const badgeReauth = `${pillBase} border-[var(--severity-warning-border)] bg-[var(--severity-warning-bg)] text-[var(--severity-warning-fg)]`;
54
83
 
55
84
  /** Poll a flow every 500 ms until terminal. */
56
85
  function useFlowPoll(flowId: string | undefined, onPending: (s: FlowStatus) => void, onDone: (err: string | null) => void) {
@@ -82,21 +111,232 @@ function useFlowPoll(flowId: string | undefined, onPending: (s: FlowStatus) => v
82
111
 
83
112
  function Copyable({ value }: { value: string }) {
84
113
  const t = useT();
114
+ const [result, setResult] = useState<"copied" | "failed" | null>(null);
115
+ const seq = useRef(0);
116
+ const copy = async (): Promise<void> => {
117
+ const n = ++seq.current;
118
+ const ok = await copyText(value);
119
+ if (n !== seq.current) return; // a later click superseded this one
120
+ setResult(ok ? "copied" : "failed");
121
+ setTimeout(() => {
122
+ if (n === seq.current) setResult(null);
123
+ }, 1500);
124
+ };
125
+ const label =
126
+ result === "copied" ? t("copied", undefined, "Copied") : result === "failed" ? t("copyFailed", undefined, "Copy failed") : t("copy", undefined, "Copy");
85
127
  return (
86
128
  <div className="flex items-center gap-2">
87
- <code className="flex-1 overflow-x-auto rounded bg-[var(--bg-tertiary)] px-2 py-1 text-[12px]">{value}</code>
88
- <button type="button" className={btn} onClick={() => void navigator.clipboard?.writeText(value)}>
89
- {t("copy", undefined, "Copy")}
129
+ <code className="flex-1 overflow-x-auto rounded bg-[var(--bg-tertiary)] px-2 py-1 font-mono text-[12px] text-[var(--text-primary)]">{value}</code>
130
+ <button type="button" className={btn} onClick={() => void copy()}>
131
+ <span role="status">{label}</span>
90
132
  </button>
91
133
  </div>
92
134
  );
93
135
  }
94
136
 
137
+ /** A project-scoped link, or the "valid project id needed" statement while the id is empty or invalid. */
138
+ function ProjectLink({ href, label, step }: { href: string | null; label: string; step: WizardStep }) {
139
+ const t = useT();
140
+ if (href) return <StepLink href={href} label={label} />;
141
+ return (
142
+ <div className={muted} data-testid={`gmail-need-project-id-step-${step}`}>
143
+ {t("needValidProjectId", undefined, "A valid project id is needed before the project links and commands appear.")}
144
+ </div>
145
+ );
146
+ }
147
+
95
148
  function StepLink({ href, label }: { href: string; label: string }) {
96
149
  return (
97
- <a href={href} target="_blank" rel="noopener noreferrer" className="focus-ring text-[12px] text-[var(--accent-text)] underline">
150
+ <SafeLink href={href} target="_blank" rel="noopener noreferrer" className="focus-ring text-xs text-[var(--accent-text)] underline">
98
151
  {label}
99
- </a>
152
+ </SafeLink>
153
+ );
154
+ }
155
+
156
+ function WizardStepItem({
157
+ n,
158
+ title,
159
+ current,
160
+ done,
161
+ children,
162
+ }: {
163
+ n: WizardStep;
164
+ title: string;
165
+ current: boolean;
166
+ done: boolean;
167
+ children: React.ReactNode;
168
+ }) {
169
+ const t = useT();
170
+ return (
171
+ <li
172
+ className="grid grid-cols-[24px_1fr] gap-2 border-t border-[var(--border-subtle)] py-2 first:border-t-0"
173
+ data-testid={`gmail-step-${n}`}
174
+ aria-current={current ? "step" : undefined}
175
+ data-done={done ? "true" : undefined}
176
+ >
177
+ <span
178
+ className={`flex h-6 w-6 items-center justify-center rounded-full border text-[11px] font-bold ${
179
+ current
180
+ ? "border-[var(--tint-blue-border)] bg-[var(--tint-blue-bg)] text-[var(--tint-blue-fg)]"
181
+ : done
182
+ ? "border-[var(--severity-success-border)] bg-[var(--severity-success-bg)] text-[var(--severity-success-fg)]"
183
+ : "border-[var(--border-secondary)] bg-[var(--bg-tertiary)] text-[var(--text-secondary)]"
184
+ }`}
185
+ >
186
+ {done ? <span aria-hidden="true">✓</span> : n}
187
+ </span>
188
+ <div className="flex min-w-0 flex-col gap-1">
189
+ <div className="text-xs font-semibold text-[var(--text-primary)]">
190
+ {title.replace(/^\d+\.\s*/, "")}
191
+ {done ? <span className="sr-only"> — {t("stepDone", undefined, "done")}</span> : null}
192
+ </div>
193
+ {children}
194
+ </div>
195
+ </li>
196
+ );
197
+ }
198
+
199
+ type Translate = ReturnType<typeof useT>;
200
+
201
+ function currentWizardStep(state: GmailState, focus: WizardStep | null): WizardStep | null {
202
+ return focus ?? (!state.client.configured ? 1 : state.accounts.length === 0 ? 6 : null);
203
+ }
204
+
205
+ function isStepDone(state: GmailState, current: WizardStep | null, n: WizardStep): boolean {
206
+ return n !== current && (state.client.configured ? n <= 5 || state.accounts.length > 0 : current !== null && n < current);
207
+ }
208
+
209
+ /** Flush a valid, unsaved typed project id; resolves false when the save failed. */
210
+ async function flushTypedProjectId(
211
+ projectId: string,
212
+ savedId: string,
213
+ saveSetup: (partial: Partial<SavedSetup>) => Promise<void>,
214
+ ): Promise<boolean> {
215
+ if (classifyProjectId(projectId) !== "ok" || normalizeProjectId(projectId) === savedId) return true;
216
+ try {
217
+ await saveSetup({ projectId: normalizeProjectId(projectId) });
218
+ return true;
219
+ } catch {
220
+ return false;
221
+ }
222
+ }
223
+
224
+ function uploadMessages(t: Translate): Record<string, string> {
225
+ return {
226
+ not_json: t("errNotJson", undefined, "That file is not valid JSON. Upload the client_secret_*.json you downloaded (step 5)."),
227
+ web_client: t("errWebClient", undefined, "This is a Web application client. Create a Desktop app client instead (step 4)."),
228
+ not_installed: t("errNotInstalled", undefined, "No Desktop (`installed`) client in this file. Create a Desktop app client (step 4)."),
229
+ bad_client_id: t("errBadClientId", undefined, "The client id does not end in .apps.googleusercontent.com (step 4)."),
230
+ client_in_use: t(
231
+ "errClientInUse",
232
+ undefined,
233
+ "Accounts are connected with the current client. Revoke them first, then upload a different client.",
234
+ ),
235
+ missing_secret: t("errMissingSecret", undefined, "The file has no client secret. Download it again from the client page (step 5)."),
236
+ setup_save_failed: t("errSetupSave", undefined, "The project id could not be saved, so the upload was not sent. Try again (step 1)."),
237
+ };
238
+ }
239
+
240
+ function projectErrorText(t: Translate, projectErr: "looks_like_name" | "invalid" | null): string | null {
241
+ return (
242
+ projectErr === "looks_like_name"
243
+ ? t(
244
+ "errProjectLooksLikeName",
245
+ undefined,
246
+ "That looks like the project name. The wizard needs the project id (lower-case, for example pidashboard-510015): open the project list and copy the ID column.",
247
+ )
248
+ : projectErr === "invalid"
249
+ ? t(
250
+ "errProjectInvalid",
251
+ undefined,
252
+ "A project id is 6–30 characters: lower-case letters, digits and hyphens, starting with a letter and not ending with a hyphen.",
253
+ )
254
+ : null
255
+ );
256
+ }
257
+
258
+ function ProjectModeLinks({
259
+ mode,
260
+ links,
261
+ cmds,
262
+ }: {
263
+ mode: "new" | "existing";
264
+ links: ReturnType<typeof consoleLinks>;
265
+ cmds: ReturnType<typeof gcloudCommands>;
266
+ }) {
267
+ const t = useT();
268
+ return mode === "new" ? (
269
+ <>
270
+ <div className={muted}>{t("withoutGcloud", undefined, "Without gcloud:")}</div>
271
+ <div className="flex gap-3">
272
+ <StepLink href={links.projectCreate} label={t("createProject", undefined, "Create project")} />
273
+ </div>
274
+ {cmds.create && (
275
+ <>
276
+ <div className={muted}>{t("withGcloud", undefined, "With gcloud (run it yourself):")}</div>
277
+ <Copyable value={cmds.create} />
278
+ </>
279
+ )}
280
+ </>
281
+ ) : (
282
+ <>
283
+ <div className={muted}>{t("findProject", undefined, "Find your project's id:")}</div>
284
+ <div className="flex gap-3">
285
+ <StepLink href={links.projectList} label={t("openProjectList", undefined, "Open the project list")} />
286
+ </div>
287
+ <Copyable value={cmds.projectsList} />
288
+ </>
289
+ );
290
+ }
291
+
292
+ function MismatchNotice({ mismatch, onUse }: { mismatch: { saved: string; json: string }; onUse: () => void }) {
293
+ const t = useT();
294
+ return (
295
+ <SettingsNotice tone="error" testId="gmail-project-mismatch">
296
+ <div className="flex flex-col gap-1">
297
+ <span>
298
+ {t(
299
+ "projectMismatch",
300
+ { saved: mismatch.saved, json: mismatch.json },
301
+ `The uploaded client belongs to project ${mismatch.json}, but the saved project id is ${mismatch.saved}.`,
302
+ )}
303
+ </span>
304
+ <span>
305
+ <button type="button" className={btn} data-testid="gmail-project-mismatch-use" onClick={onUse}>
306
+ {t("projectMismatchUse", { id: mismatch.json }, `Use ${mismatch.json}`)}
307
+ </button>
308
+ </span>
309
+ </div>
310
+ </SettingsNotice>
311
+ );
312
+ }
313
+
314
+ function AuthLoginNote({ cmds }: { cmds: ReturnType<typeof gcloudCommands> }) {
315
+ const t = useT();
316
+ if (!cmds.authLogin) return null;
317
+ return (
318
+ <>
319
+ <div className={muted} data-testid="gmail-auth-login-note">
320
+ {t("authLoginNote", undefined, "Run this once first, so gcloud can act as the owner account:")}
321
+ </div>
322
+ <Copyable value={cmds.authLogin} />
323
+ </>
324
+ );
325
+ }
326
+
327
+ function EnableGmailApi({ links, cmds }: { links: ReturnType<typeof consoleLinks>; cmds: ReturnType<typeof gcloudCommands> }) {
328
+ const t = useT();
329
+ return links.gmailApi && cmds.enable ? (
330
+ <>
331
+ <div className="flex gap-3">
332
+ <StepLink href={links.gmailApi} label={t("enableGmail", undefined, "Enable the Gmail API")} />
333
+ </div>
334
+ <Copyable value={cmds.enable} />
335
+ </>
336
+ ) : (
337
+ <div className={muted} data-testid="gmail-need-project-id">
338
+ {t("needValidProjectId", undefined, "A valid project id is needed before the project links and commands appear.")}
339
+ </div>
100
340
  );
101
341
  }
102
342
 
@@ -110,24 +350,107 @@ export function SetupWizard({
110
350
  onUploaded: () => void;
111
351
  }) {
112
352
  const t = useT();
113
- const [projectId, setProjectId] = useState(state.client.projectId ?? "");
353
+ const savedSetup = useRef<SavedSetup>({
354
+ projectId: state.setup?.projectId ?? "",
355
+ ownerAccount: state.setup?.ownerAccount ?? "",
356
+ });
357
+ const [projectId, setProjectId] = useState(state.setup?.projectId ?? state.client.projectId ?? "");
358
+ const [owner, setOwner] = useState(state.setup?.ownerAccount ?? "");
359
+ // Presentational only (design D2): `existing` by default once a project id is known.
360
+ const [mode, setMode] = useState<"new" | "existing">(state.setup?.projectId || state.client.projectId ? "existing" : "new");
361
+ // Validation errors appear on blur only and clear the moment the value turns valid.
362
+ const [projectErr, setProjectErr] = useState<"looks_like_name" | "invalid" | null>(null);
363
+ const [ownerErr, setOwnerErr] = useState(false);
364
+ const [saveError, setSaveError] = useState<string | null>(null);
365
+ const [mismatch, setMismatch] = useState<{ saved: string; json: string } | null>(null);
114
366
  const [uploadError, setUploadError] = useState<{ code: string; step: WizardStep } | null>(null);
115
- const links = consoleLinks(projectId.trim());
116
- const [cmdCreate, cmdEnable] = gcloudCommands(projectId.trim());
367
+ const links = consoleLinks(projectId, owner);
368
+ const cmds = gcloudCommands(projectId, owner);
117
369
  const [focus, setFocus] = useState<WizardStep | null>(highlight);
118
370
  useEffect(() => setFocus(highlight ?? uploadError?.step ?? null), [highlight, uploadError]);
119
371
 
372
+ /** Persist setup fields; rejects on failure. The reply (normalized values) is what counts as saved. */
373
+ const saveSetup = async (partial: Partial<SavedSetup>): Promise<void> => {
374
+ const r = await api<{ setup?: { projectId?: string; ownerAccount?: string } }>("/setup", {
375
+ method: "PUT",
376
+ body: JSON.stringify(partial),
377
+ });
378
+ savedSetup.current = r.setup
379
+ ? { projectId: r.setup.projectId ?? "", ownerAccount: r.setup.ownerAccount ?? "" }
380
+ : { ...savedSetup.current, ...partial };
381
+ };
382
+ const saveOnBlur = (partial: Partial<SavedSetup>) => {
383
+ setSaveError(null);
384
+ saveSetup(partial).catch((err: unknown) => setSaveError((err as { code?: string }).code ?? (err as Error).message));
385
+ };
386
+
387
+ const onProjectChange = (v: string) => {
388
+ setProjectId(v);
389
+ if (!v.trim() || classifyProjectId(v) === "ok") setProjectErr(null);
390
+ };
391
+ const onProjectBlur = () => {
392
+ const cls = classifyProjectId(projectId);
393
+ if (cls === "looks_like_name" || cls === "invalid") {
394
+ setProjectErr(cls);
395
+ return;
396
+ }
397
+ setProjectErr(null);
398
+ const next = cls === "ok" ? normalizeProjectId(projectId) : "";
399
+ if (next !== savedSetup.current.projectId) saveOnBlur({ projectId: next });
400
+ };
401
+ const onOwnerChange = (v: string) => {
402
+ setOwner(v);
403
+ if (!v.trim() || isEmail(normalizeEmail(v))) setOwnerErr(false);
404
+ };
405
+ const onOwnerBlur = () => {
406
+ const email = normalizeEmail(owner);
407
+ if (email && !isEmail(email)) {
408
+ setOwnerErr(true);
409
+ return;
410
+ }
411
+ setOwnerErr(false);
412
+ if (email !== savedSetup.current.ownerAccount) saveOnBlur({ ownerAccount: email });
413
+ };
414
+ const useJsonProject = () => {
415
+ if (!mismatch) return;
416
+ const id = mismatch.json;
417
+ setMismatch(null);
418
+ setProjectId(id);
419
+ setProjectErr(null);
420
+ saveOnBlur({ projectId: id });
421
+ };
422
+
423
+ const reconcileJsonProject = (jsonId: string | undefined) => {
424
+ if (!jsonId) return;
425
+ const savedId = savedSetup.current.projectId;
426
+ if (!savedId) {
427
+ // Nothing saved yet: adopt the client's project id.
428
+ setProjectId(jsonId);
429
+ setProjectErr(null);
430
+ saveOnBlur({ projectId: jsonId });
431
+ } else if (savedId !== jsonId) {
432
+ setMismatch({ saved: savedId, json: jsonId });
433
+ }
434
+ };
435
+
120
436
  const upload = async (file: File) => {
121
437
  setUploadError(null);
438
+ setMismatch(null);
122
439
  const textContent = await file.text();
123
440
  const local = validateClientJson(textContent);
124
441
  if (!local.ok) {
125
442
  setUploadError({ code: local.error.code, step: local.error.step });
126
443
  return;
127
444
  }
445
+ // Flush a valid, unsaved typed id first (removes the blur/upload race); a failed
446
+ // save aborts the upload so the comparison never runs against a stale id.
447
+ if (!(await flushTypedProjectId(projectId, savedSetup.current.projectId, saveSetup))) {
448
+ setUploadError({ code: "setup_save_failed", step: 1 });
449
+ return;
450
+ }
128
451
  try {
129
- await api("/client", { method: "PUT", body: JSON.stringify({ json: JSON.parse(textContent) }) });
130
- if (local.client.projectId && !projectId) setProjectId(local.client.projectId);
452
+ const reply = await api<{ projectId?: string }>("/client", { method: "PUT", body: JSON.stringify({ json: JSON.parse(textContent) }) });
453
+ reconcileJsonProject(reply.projectId);
131
454
  onUploaded();
132
455
  } catch (err) {
133
456
  const code = (err as { code?: string }).code ?? "upload_failed";
@@ -135,57 +458,94 @@ export function SetupWizard({
135
458
  }
136
459
  };
137
460
 
138
- const stepClass = (n: WizardStep) =>
139
- `rounded border p-2 ${focus === n ? "border-[var(--accent)]" : "border-[var(--border-primary)]"}`;
140
- const uploadMsg: Record<string, string> = {
141
- not_json: t("errNotJson", undefined, "That file is not valid JSON. Upload the client_secret_*.json you downloaded (step 5)."),
142
- web_client: t("errWebClient", undefined, "This is a Web application client. Create a Desktop app client instead (step 4)."),
143
- not_installed: t("errNotInstalled", undefined, "No Desktop (`installed`) client in this file. Create a Desktop app client (step 4)."),
144
- bad_client_id: t("errBadClientId", undefined, "The client id does not end in .apps.googleusercontent.com (step 4)."),
145
- client_in_use: t(
146
- "errClientInUse",
147
- undefined,
148
- "Accounts are connected with the current client. Revoke them first, then upload a different client.",
149
- ),
150
- missing_secret: t("errMissingSecret", undefined, "The file has no client secret. Download it again from the client page (step 5)."),
151
- };
461
+ // Current step: the highlighted one, else the next thing the user has to do.
462
+ const current = currentWizardStep(state, focus);
463
+ const isDone = (n: WizardStep) => isStepDone(state, current, n);
464
+ const uploadMsg = uploadMessages(t);
465
+ const projectErrText = projectErrorText(t, projectErr);
152
466
 
153
467
  return (
154
- <ol className="flex flex-col gap-2" data-testid="gmail-wizard">
155
- <li className={stepClass(1)} data-testid="gmail-step-1">
156
- <div className="font-medium text-[13px]">{t("step1", undefined, "1. Google Cloud project + Gmail API")}</div>
157
- <label className={`${muted} flex items-center gap-2`}>
158
- {t("projectId", undefined, "Project id")}
159
- <input
160
- data-testid="gmail-project-id"
161
- className={`${field} px-1`}
468
+ <ol className="m-0 flex list-none flex-col p-0" data-testid="gmail-wizard">
469
+ <WizardStepItem n={1} title={t("step1", undefined, "1. Google Cloud project + Gmail API")} current={current === 1} done={isDone(1)}>
470
+ <fieldset className="m-0 flex flex-wrap items-center gap-3 border-0 p-0" data-testid="gmail-project-mode">
471
+ <legend className="sr-only">{t("projectModeLegend", undefined, "Project")}</legend>
472
+ {(["new", "existing"] as const).map((m) => (
473
+ <label key={m} className={`${muted} flex items-center gap-1`}>
474
+ <input
475
+ type="radio"
476
+ name="gmail-project-mode"
477
+ value={m}
478
+ checked={mode === m}
479
+ onChange={() => setMode(m)}
480
+ className="focus-ring"
481
+ data-testid={`gmail-project-mode-${m}`}
482
+ />
483
+ {m === "new" ? t("projectModeNew", undefined, "Create a new project") : t("projectModeExisting", undefined, "Use an existing project")}
484
+ </label>
485
+ ))}
486
+ </fieldset>
487
+ <div onBlur={onProjectBlur}>
488
+ <TextField
489
+ label={t("projectId", undefined, "Project id")}
490
+ hint={
491
+ <>
492
+ {t(
493
+ "projectIdHint",
494
+ undefined,
495
+ "The id of your Google Cloud project, not its display name: lower-case letters, digits and hyphens, for example my-gmail-agent. The console's project list shows both; the id is in the ID column.",
496
+ )}
497
+ {projectErr === "looks_like_name" && (
498
+ <>
499
+ {" "}
500
+ <StepLink href={links.projectList} label={t("openProjectList", undefined, "Open the project list")} />
501
+ </>
502
+ )}
503
+ </>
504
+ }
505
+ error={projectErrText}
506
+ mono
162
507
  value={projectId}
163
- onChange={(e) => setProjectId(e.target.value)}
508
+ onChange={onProjectChange}
164
509
  placeholder="my-gmail-agent"
510
+ testIds={{ control: "gmail-project-id", error: "gmail-project-error" }}
511
+ />
512
+ </div>
513
+ <div onBlur={onOwnerBlur}>
514
+ <TextField
515
+ label={t("ownerAccount", undefined, "Owner account (optional)")}
516
+ hint={t(
517
+ "ownerHint",
518
+ undefined,
519
+ "The Google account that owns the project. Console links and gcloud commands then act as this account instead of your browser's default one.",
520
+ )}
521
+ error={ownerErr ? t("errOwnerInvalid", undefined, "Enter a full email address, for example you@gmail.com.") : null}
522
+ value={owner}
523
+ onChange={onOwnerChange}
524
+ placeholder="you@gmail.com"
525
+ testIds={{ control: "gmail-owner-account", error: "gmail-owner-error" }}
165
526
  />
166
- </label>
167
- <div className={muted}>{t("withoutGcloud", undefined, "Without gcloud:")}</div>
168
- <div className="flex gap-3">
169
- <StepLink href={links.projectCreate} label={t("createProject", undefined, "Create project")} />
170
- <StepLink href={links.gmailApi} label={t("enableGmail", undefined, "Enable the Gmail API")} />
171
527
  </div>
172
- <div className={muted}>{t("withGcloud", undefined, "With gcloud (run it yourself):")}</div>
173
- <Copyable value={cmdCreate as string} />
174
- <Copyable value={cmdEnable as string} />
175
- </li>
176
- <li className={stepClass(2)} data-testid="gmail-step-2">
177
- <div className="font-medium text-[13px]">{t("step2", undefined, "2. Branding")}</div>
178
- <StepLink href={links.branding} label={t("openBranding", undefined, "Open Branding")} />
528
+ {saveError && (
529
+ <div role="alert" className={errorText} data-testid="gmail-setup-save-error">
530
+ {t("errSetupSave", undefined, "The project id could not be saved, so the upload was not sent. Try again (step 1).")} ({saveError})
531
+ </div>
532
+ )}
533
+ {mismatch && <MismatchNotice mismatch={mismatch} onUse={useJsonProject} />}
534
+ <AuthLoginNote cmds={cmds} />
535
+ <ProjectModeLinks mode={mode} links={links} cmds={cmds} />
536
+ <EnableGmailApi links={links} cmds={cmds} />
537
+ </WizardStepItem>
538
+ <WizardStepItem n={2} title={t("step2", undefined, "2. Branding")} current={current === 2} done={isDone(2)}>
539
+ <ProjectLink href={links.branding} label={t("openBranding", undefined, "Open Branding")} step={2} />
179
540
  <div className={muted}>{t("fallback2", undefined, "If the link moved: APIs & Services → OAuth consent screen.")}</div>
180
- </li>
181
- <li className={stepClass(3)} data-testid="gmail-step-3">
182
- <div className="font-medium text-[13px]">{t("step3", undefined, "3. Audience + test users")}</div>
183
- <StepLink href={links.audience} label={t("openAudience", undefined, "Open Audience")} />
541
+ </WizardStepItem>
542
+ <WizardStepItem n={3} title={t("step3", undefined, "3. Audience + test users")} current={current === 3} done={isDone(3)}>
543
+ <ProjectLink href={links.audience} label={t("openAudience", undefined, "Open Audience")} step={3} />
184
544
  <div className={muted}>
185
545
  {t(
186
546
  "audienceHelp",
187
547
  undefined,
188
- "Internal admits only accounts of the project's own Workspace organization: choose it only when every account you will connect belongs to that organization. Otherwise choose External and add every address you will connect as a test user. In Testing, tokens expire after 7 days; “Publish app” gives longer-lived tokens with an unverified-app warning.",
548
+ AUDIENCE_HELP_EN,
189
549
  )}
190
550
  </div>
191
551
  <div className={muted}>
@@ -195,42 +555,46 @@ export function SetupWizard({
195
555
  "Google error pages: org_internal = the account is outside the organization, switch to External; access_denied = add the account as a test user; admin_policy_enforced = the account's Workspace admin must trust this OAuth client.",
196
556
  )}
197
557
  </div>
198
- </li>
199
- <li className={stepClass(4)} data-testid="gmail-step-4">
200
- <div className="font-medium text-[13px]">{t("step4", undefined, "4. Desktop OAuth client")}</div>
201
- <StepLink href={links.clientCreate} label={t("openClients", undefined, "Create client")} />
558
+ </WizardStepItem>
559
+ <WizardStepItem n={4} title={t("step4", undefined, "4. Desktop OAuth client")} current={current === 4} done={isDone(4)}>
560
+ <ProjectLink href={links.clientCreate} label={t("openClients", undefined, "Create client")} step={4} />
202
561
  <div className={muted}>
203
562
  {t("clientHelp", undefined, "Application type: Desktop app. Download the JSON. If the link moved: APIs & Services → Credentials.")}
204
563
  </div>
205
- </li>
206
- <li className={stepClass(5)} data-testid="gmail-step-5">
207
- <div className="font-medium text-[13px]">{t("step5", undefined, "5. Upload client_secret_*.json")}</div>
208
- <input
209
- type="file"
210
- className="focus-ring text-[12px]"
211
- accept="application/json,.json"
212
- data-testid="gmail-client-upload"
213
- aria-label={t("uploadLabel", undefined, "Upload the OAuth client JSON")}
214
- onChange={(e) => {
215
- const f = e.target.files?.[0];
216
- if (f) void upload(f);
217
- }}
564
+ </WizardStepItem>
565
+ <WizardStepItem n={5} title={t("step5", undefined, "5. Upload client_secret_*.json")} current={current === 5} done={isDone(5)}>
566
+ <FieldShell
567
+ label={t("uploadLabel", undefined, "Upload the OAuth client JSON")}
568
+ hint={null}
569
+ stacked
570
+ error={uploadError ? (uploadMsg[uploadError.code] ?? uploadError.code) : null}
571
+ testIds={{ error: "gmail-upload-error" }}
572
+ errorAttrs={uploadError ? { "data-step": String(uploadError.step) } : undefined}
573
+ control={({ id, describedBy, invalid }) => (
574
+ <input
575
+ id={id}
576
+ type="file"
577
+ className="focus-ring text-xs text-[var(--text-primary)]"
578
+ accept="application/json,.json"
579
+ data-testid="gmail-client-upload"
580
+ aria-describedby={describedBy}
581
+ aria-invalid={invalid || undefined}
582
+ onChange={(e) => {
583
+ const f = e.target.files?.[0];
584
+ if (f) void upload(f);
585
+ }}
586
+ />
587
+ )}
218
588
  />
219
589
  {state.client.configured && (
220
590
  <div className={muted} data-testid="gmail-client-ok">
221
591
  ✓ {state.client.clientId}
222
592
  </div>
223
593
  )}
224
- {uploadError && (
225
- <div role="alert" className={errorText} data-testid="gmail-upload-error" data-step={uploadError.step}>
226
- {uploadMsg[uploadError.code] ?? uploadError.code}
227
- </div>
228
- )}
229
- </li>
230
- <li className={stepClass(6)} data-testid="gmail-step-6">
231
- <div className="font-medium text-[13px]">{t("step6", undefined, "6. Test sign-in")}</div>
594
+ </WizardStepItem>
595
+ <WizardStepItem n={6} title={t("step6", undefined, "6. Test sign-in")} current={current === 6} done={isDone(6)}>
232
596
  <div className={muted}>{t("step6Help", undefined, "Add your first account below — that is the test sign-in.")}</div>
233
- </li>
597
+ </WizardStepItem>
234
598
  </ol>
235
599
  );
236
600
  }
@@ -242,18 +606,10 @@ const TIER_DESC: Record<Tier, [key: string, en: string]> = {
242
606
  send: ["tierSend", "read, draft, send, reply, labels, archive, trash"],
243
607
  };
244
608
 
245
- /** `<option>`s carrying each level's own description. */
246
- function TierOptions() {
609
+ /** Each level's own description, as a select option list. */
610
+ function useTierOptions(): { value: string; label: string }[] {
247
611
  const t = useT();
248
- return (
249
- <>
250
- {TIERS.map((tier) => (
251
- <option key={tier} value={tier}>
252
- {`${TIER_LABEL[tier]} — ${t(TIER_DESC[tier][0], undefined, TIER_DESC[tier][1])}`}
253
- </option>
254
- ))}
255
- </>
256
- );
612
+ return TIERS.map((tier) => ({ value: tier, label: `${TIER_LABEL[tier]} — ${t(TIER_DESC[tier][0], undefined, TIER_DESC[tier][1])}` }));
257
613
  }
258
614
 
259
615
  /** Codes the user can report from Google's own error page (closed list, design D1). */
@@ -272,10 +628,13 @@ function AccountRow({
272
628
  }) {
273
629
  const t = useT();
274
630
  const ConfirmDialog = useUiPrimitive("ui:confirm-dialog");
631
+ const tierOptions = useTierOptions();
275
632
  const [alias, setAlias] = useState(acct.alias ?? "");
276
633
  const [msg, setMsg] = useState<string | null>(null);
277
634
  const [aliasMsg, setAliasMsg] = useState<{ ok: boolean; text: string } | null>(null);
278
635
  const [confirming, setConfirming] = useState(false);
636
+ const [filtersOn, setFiltersOn] = useState(acct.filters === true);
637
+ useEffect(() => setFiltersOn(acct.filters === true), [acct.filters]);
279
638
  const run = async (fn: () => Promise<void>) => {
280
639
  setMsg(null);
281
640
  try {
@@ -293,6 +652,18 @@ function AccountRow({
293
652
  if (r.flowId) onFlow(r.flowId);
294
653
  else onChanged();
295
654
  });
655
+ const toggleFilters = (enabled: boolean) =>
656
+ run(async () => {
657
+ const r = await api<{ applied?: boolean; flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/filters`, {
658
+ method: "POST",
659
+ body: JSON.stringify({ enabled }),
660
+ });
661
+ if (r.flowId) onFlow(r.flowId);
662
+ else {
663
+ setFiltersOn(enabled);
664
+ onChanged();
665
+ }
666
+ });
296
667
  const saveAlias = async () => {
297
668
  try {
298
669
  await api(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "PATCH", body: JSON.stringify({ alias: alias || null }) });
@@ -317,21 +688,21 @@ function AccountRow({
317
688
  });
318
689
  return (
319
690
  <li
320
- className="flex flex-col gap-1 rounded border border-[var(--border-primary)] p-2"
691
+ className="flex flex-col gap-2 rounded-md border border-[var(--border-secondary)] p-2"
321
692
  data-testid="gmail-account-row"
322
693
  data-email={acct.email}
323
694
  >
324
695
  <div className="flex flex-wrap items-center gap-2">
325
- <span className="font-medium text-[13px]" data-testid="gmail-account-email">
696
+ <span className="text-sm font-semibold text-[var(--text-primary)]" data-testid="gmail-account-email">
326
697
  {acct.email}
327
698
  </span>
328
699
  {acct.status === "ok" ? (
329
700
  <span className={badgeOk} data-testid="gmail-account-status" data-status="ok">
330
- {t("statusOk", undefined, "ok")}
701
+ {t("statusOk", undefined, "Connected")}
331
702
  </span>
332
703
  ) : (
333
704
  <span className={badgeReauth} data-testid="gmail-account-status" data-status="reauth_required">
334
- {t("statusReauth", undefined, "re-auth needed")}
705
+ {t("statusReauth", undefined, "Re-auth needed")}
335
706
  </span>
336
707
  )}
337
708
  {acct.testingHint && (
@@ -340,9 +711,9 @@ function AccountRow({
340
711
  </span>
341
712
  )}
342
713
  <input
343
- aria-label={t("aliasLabel", undefined, "Alias")}
714
+ aria-label={t("aliasFor", { email: acct.email }, `Alias for ${acct.email}`)}
344
715
  data-testid="gmail-account-alias"
345
- className={`${field} w-24 px-1`}
716
+ className={`${field} w-28`}
346
717
  value={alias}
347
718
  placeholder={t("aliasPlaceholder", undefined, "alias")}
348
719
  onChange={(e) => {
@@ -365,18 +736,31 @@ function AccountRow({
365
736
  <label className={muted}>
366
737
  {t("level", undefined, "Level")}{" "}
367
738
  <select
739
+ aria-label={t("levelFor", { email: acct.email }, `Level for ${acct.email}`)}
368
740
  data-testid="gmail-account-level"
369
741
  value={acct.tier}
370
742
  onChange={(e) => void setLevel(e.target.value as Tier)}
371
743
  className={field}
372
744
  >
373
- <TierOptions />
745
+ {tierOptions.map((o) => (
746
+ <option key={o.value} value={o.value}>
747
+ {o.label}
748
+ </option>
749
+ ))}
374
750
  </select>
375
751
  </label>
752
+ <ToggleField
753
+ label={t("filtersFor", { email: acct.email }, `Filters for ${acct.email}`)}
754
+ hint={null}
755
+ testIds={{ control: "gmail-account-filters" }}
756
+ value={filtersOn}
757
+ onChange={(enabled) => void toggleFilters(enabled)}
758
+ />
376
759
  <button
377
760
  type="button"
378
761
  className={btn}
379
762
  data-testid="gmail-account-reauth"
763
+ aria-label={t("reauthFor", { email: acct.email }, `Re-authenticate ${acct.email}`)}
380
764
  onClick={() =>
381
765
  void run(async () => {
382
766
  // Force a fresh consent at the current level (status reset on persist).
@@ -387,7 +771,13 @@ function AccountRow({
387
771
  >
388
772
  {t("reauth", undefined, "Re-authenticate")}
389
773
  </button>
390
- <button type="button" className={btn} data-testid="gmail-account-revoke" onClick={() => setConfirming(true)}>
774
+ <button
775
+ type="button"
776
+ className={btn}
777
+ data-testid="gmail-account-revoke"
778
+ aria-label={t("revokeFor", { email: acct.email }, `Revoke ${acct.email}`)}
779
+ onClick={() => setConfirming(true)}
780
+ >
391
781
  {t("revoke", undefined, "Revoke")}
392
782
  </button>
393
783
  {msg && (
@@ -396,6 +786,13 @@ function AccountRow({
396
786
  </span>
397
787
  )}
398
788
  </div>
789
+ <p className={`${muted} m-0`} data-testid="gmail-account-filters-help">
790
+ {t(
791
+ "filtersHelp",
792
+ undefined,
793
+ "Filters let agents list, create and delete Gmail filters. Turning them on asks Google for one extra permission (gmail.settings.basic); creating and deleting also need level send.",
794
+ )}
795
+ </p>
399
796
  {confirming && (
400
797
  <ConfirmDialog
401
798
  message={t(
@@ -415,16 +812,138 @@ function AccountRow({
415
812
  );
416
813
  }
417
814
 
815
+ function AddAccount({
816
+ configured,
817
+ newTier,
818
+ onTier,
819
+ email,
820
+ onEmail,
821
+ emailError,
822
+ onAdd,
823
+ }: {
824
+ configured: boolean;
825
+ newTier: Tier;
826
+ onTier: (t: Tier) => void;
827
+ email: string;
828
+ onEmail: (v: string) => void;
829
+ emailError: boolean;
830
+ onAdd: () => void;
831
+ }) {
832
+ const t = useT();
833
+ const addReasonId = useId();
834
+ const tierOptions = useTierOptions();
835
+ return (
836
+ <div className="flex flex-col gap-2">
837
+ <SelectField
838
+ label={t("newLevel", undefined, "Level for the new account")}
839
+ hint={null}
840
+ value={newTier}
841
+ options={tierOptions}
842
+ onChange={(v) => onTier(v as Tier)}
843
+ testIds={{ control: "gmail-new-level" }}
844
+ />
845
+ <TextField
846
+ label={t("addEmail", undefined, "Account email (optional)")}
847
+ hint={t("addEmailHint", undefined, "Google then skips its account chooser and signs in as this address.")}
848
+ error={emailError ? t("errOwnerInvalid", undefined, "Enter a full email address, for example you@gmail.com.") : null}
849
+ type="email"
850
+ autoComplete="email"
851
+ value={email}
852
+ onChange={onEmail}
853
+ placeholder="you@gmail.com"
854
+ testIds={{ control: "gmail-add-email", error: "gmail-add-email-error" }}
855
+ />
856
+ <div className="flex flex-wrap items-center gap-2">
857
+ <button
858
+ type="button"
859
+ className={primaryBtn}
860
+ data-testid="gmail-add-account"
861
+ disabled={!configured}
862
+ aria-describedby={configured ? undefined : addReasonId}
863
+ onClick={onAdd}
864
+ >
865
+ {t("addAccount", undefined, "Add account")}
866
+ </button>
867
+ {!configured && (
868
+ <span id={addReasonId} className={muted} data-testid="gmail-add-account-reason">
869
+ {t("addAccountDisabled", undefined, "Upload the OAuth client JSON (step 5 above) to enable this.")}
870
+ </span>
871
+ )}
872
+ </div>
873
+ <p className={`${muted} m-0`} data-testid="gmail-cross-org-hint">
874
+ {t(
875
+ "crossOrgHint",
876
+ undefined,
877
+ "Accounts outside the project's Workspace organization need an External audience, with each account added as a test user (step 3).",
878
+ )}
879
+ </p>
880
+ </div>
881
+ );
882
+ }
883
+
884
+ /** Failed sign-in as a severity notice; the sentence names the wizard step that fixes it. */
885
+ function FlowErrorNotice({ code, step, errKey, clientId }: { code: string; step: WizardStep | null; errKey: string; clientId: string }) {
886
+ const t = useT();
887
+ return (
888
+ <SettingsNotice tone="error">
889
+ <div data-testid="gmail-flow-error" data-step={step ?? ""}>
890
+ {t(errKey, { clientId }, ERROR_EN[errKey])}{" "}
891
+ <span className="text-[var(--severity-error-fg)]" data-testid="gmail-flow-error-code">
892
+ ({code})
893
+ </span>
894
+ </div>
895
+ </SettingsNotice>
896
+ );
897
+ }
898
+
899
+ /** `POST /accounts` body (the optional email becomes `login_hint`); `null` when the email is typed but not an address. */
900
+ function accountRequest(tier: Tier, rawEmail: string): { tier: Tier; email?: string } | null {
901
+ const email = normalizeEmail(rawEmail);
902
+ if (!email) return { tier };
903
+ return isEmail(email) ? { tier, email } : null;
904
+ }
905
+
906
+ /** The wizard's props: a hand-off run overlays its project id / owner account and picks the step (task 4.3). */
907
+ function wizardProps(state: GmailState, handoff: SetupRunView | null, errorStep: WizardStep | null): { state: GmailState; highlight: WizardStep | null } {
908
+ if (!handoff) return { state, highlight: errorStep };
909
+ return {
910
+ state: {
911
+ ...state,
912
+ setup: {
913
+ projectId: handoff.projectId ?? handoff.created.projectId ?? state.setup?.projectId,
914
+ ownerAccount: handoff.ownerEmail ?? state.setup?.ownerAccount,
915
+ },
916
+ },
917
+ highlight: handoff.handoff?.wizardStep ?? errorStep,
918
+ };
919
+ }
920
+
921
+ /** Sign-in notice for an External or unknown audience (design D11). */
922
+ function UnverifiedHint({ audience }: { audience: Audience | null }) {
923
+ const t = useT();
924
+ if (!showUnverifiedNotice(audience)) return null;
925
+ return (
926
+ <p className={`${muted} m-0`} data-testid="gmail-unverified-hint">
927
+ {t("unverifiedHint", undefined, UNVERIFIED_HINT_EN)}
928
+ </p>
929
+ );
930
+ }
931
+
418
932
  export function GmailSettings() {
419
933
  const t = useT();
420
934
  const OAuthFlow = useUiPrimitive("ui:oauth-flow");
421
- const newLevelId = useId();
422
935
  const [state, setState] = useState<GmailState | null>(null);
423
936
  const [loadError, setLoadError] = useState<string | null>(null);
424
937
  const [flow, setFlow] = useState<FlowState | null>(null);
425
938
  const [flowError, setFlowError] = useState<string | null>(null);
426
939
  const [lastRevoke, setLastRevoke] = useState<string | null>(null);
427
940
  const [newTier, setNewTier] = useState<Tier>("readonly");
941
+ const [addEmail, setAddEmail] = useState("");
942
+ const [addEmailError, setAddEmailError] = useState(false);
943
+ // Automatic setup (change: add-gmail-auto-setup): hand-off view for the wizard, audience
944
+ // for the unverified-app notice (null = unknown → the notice shows).
945
+ const [handoff, setHandoff] = useState<SetupRunView | null>(null);
946
+ const [audience, setAudience] = useState<Audience | null>(null);
428
947
  // Latch (design D1): once the user reports a Google-page code, no late poll
429
948
  // result may overwrite it or re-mount the flow view. Reset on a new flow.
430
949
  const reportedRef = useRef<string | null>(null);
@@ -475,11 +994,17 @@ export function GmailSettings() {
475
994
  };
476
995
 
477
996
  const addAccount = async () => {
997
+ const request = accountRequest(newTier, addEmail);
998
+ setAddEmailError(!request);
999
+ if (!request) return;
478
1000
  reportedRef.current = null;
479
1001
  setFlowError(null);
480
1002
  setFlow({ phase: "starting" });
481
1003
  try {
482
- const r = await api<{ flowId: string }>("/accounts", { method: "POST", body: JSON.stringify({ tier: newTier }) });
1004
+ const r = await api<{ flowId: string }>("/accounts", {
1005
+ method: "POST",
1006
+ body: JSON.stringify(request),
1007
+ });
483
1008
  await startFlow(r.flowId);
484
1009
  } catch (err) {
485
1010
  setFlow(null);
@@ -487,12 +1012,24 @@ export function GmailSettings() {
487
1012
  }
488
1013
  };
489
1014
 
490
- if (loadError) return <div role="alert" className={errorText}>{loadError}</div>;
491
- if (!state) return <div className={muted}>{t("loading", undefined, "Loading…")}</div>;
1015
+ if (loadError) {
1016
+ return (
1017
+ <SettingsNotice tone="error" testId="gmail-load-error">
1018
+ {loadError}
1019
+ </SettingsNotice>
1020
+ );
1021
+ }
1022
+ if (!state)
1023
+ return (
1024
+ <div data-testid="gmail-loading" className={muted}>
1025
+ {t("loading", undefined, "Loading…")}
1026
+ </div>
1027
+ );
492
1028
 
493
1029
  const step = errorStep(flowError);
494
1030
  const errKey = errorKey(flowError);
495
1031
  const { client } = state;
1032
+ const wizard = wizardProps(state, handoff, step);
496
1033
  const summary = !client.configured
497
1034
  ? t("summaryNotConfigured", undefined, "not configured")
498
1035
  : client.projectId
@@ -500,19 +1037,34 @@ export function GmailSettings() {
500
1037
  : t("summaryClient", { clientId: client.clientId ?? "" }, `✓ ${client.clientId ?? ""}`);
501
1038
  return (
502
1039
  <section className="flex flex-col gap-3" data-testid="gmail-settings" aria-labelledby="gmail-settings-title">
503
- <h3 id="gmail-settings-title" className="font-semibold text-[14px]">
1040
+ <h3 id="gmail-settings-title" className="m-0 text-sm font-semibold text-[var(--text-primary)]">
504
1041
  {t("title", undefined, "Gmail")}
505
1042
  </h3>
506
- <details open={!client.configured || state.accounts.length === 0 || step !== null}>
507
- <summary className="focus-ring cursor-pointer text-[13px]" data-testid="gmail-setup-summary">
508
- {t("setup", undefined, "Google Cloud setup")} <span className={muted}>{summary}</span>
509
- </summary>
510
- <SetupWizard state={state} highlight={step} onUploaded={() => void refresh()} />
511
- </details>
1043
+ <SettingsGroup
1044
+ title={t("setup", undefined, "Google Cloud setup")}
1045
+ meta={summary}
1046
+ summaryTestId="gmail-setup-summary"
1047
+ defaultOpen={!client.configured || state.accounts.length === 0 || step !== null || handoff !== null}
1048
+ >
1049
+ <AutoSetupSection
1050
+ autoSetup={state.autoSetup}
1051
+ setup={state.setup}
1052
+ onAudience={setAudience}
1053
+ onOwnerEmail={setAddEmail}
1054
+ onHandoff={setHandoff}
1055
+ onRefresh={() => void refresh()}
1056
+ />
1057
+ <SetupWizard
1058
+ key={handoff ? `handoff-${handoff.runId}` : "manual"}
1059
+ state={wizard.state}
1060
+ highlight={wizard.highlight}
1061
+ onUploaded={() => void refresh()}
1062
+ />
1063
+ </SettingsGroup>
512
1064
 
513
1065
  <div className="flex flex-col gap-2" data-testid="gmail-accounts">
514
- <div className="font-medium text-[13px]">{t("accounts", undefined, "Accounts")}</div>
515
- <p className={muted} data-testid="gmail-level-help">
1066
+ <div className="text-sm font-semibold text-[var(--text-primary)]">{t("accounts", undefined, "Accounts")}</div>
1067
+ <p className={`${muted} m-0`} data-testid="gmail-level-help">
516
1068
  {t(
517
1069
  "levelHelp",
518
1070
  undefined,
@@ -520,7 +1072,7 @@ export function GmailSettings() {
520
1072
  )}
521
1073
  </p>
522
1074
  {state.accounts.length === 0 && <div className={muted}>{t("noAccounts", undefined, "No accounts connected.")}</div>}
523
- <ul className="flex flex-col gap-2">
1075
+ <ul className="m-0 flex list-none flex-col gap-2 p-0">
524
1076
  {state.accounts.map((a) => (
525
1077
  <AccountRow
526
1078
  key={a.sub}
@@ -543,13 +1095,14 @@ export function GmailSettings() {
543
1095
  </ul>
544
1096
  {flow ? (
545
1097
  <div className="flex flex-col gap-2">
546
- <p className={muted} data-testid="gmail-consent-hint">
1098
+ <p className={`${muted} m-0`} data-testid="gmail-consent-hint">
547
1099
  {t(
548
1100
  "consentHint",
549
1101
  undefined,
550
- "On Google's consent screen tick every permission (Select all). The Gmail permission may start unticked.",
1102
+ CONSENT_HINT_EN,
551
1103
  )}
552
1104
  </p>
1105
+ <UnverifiedHint audience={audience} />
553
1106
  <OAuthFlow
554
1107
  flow={flow}
555
1108
  onSendInput={(id, value) => oauthFlowClient.input(id, value)}
@@ -559,11 +1112,11 @@ export function GmailSettings() {
559
1112
  />
560
1113
  {flow.phase === "waiting" && (
561
1114
  <details data-testid="gmail-google-error">
562
- <summary className="focus-ring cursor-pointer text-[12px]">
1115
+ <summary className="focus-ring cursor-pointer text-xs text-[var(--text-primary)]">
563
1116
  {t("googleErrorSummary", undefined, "Google showed an error instead of returning here?")}
564
1117
  </summary>
565
1118
  <div className={muted}>{t("googleErrorHelp", undefined, "Pick the error code Google displayed:")}</div>
566
- <div className="flex flex-wrap gap-2">
1119
+ <div className="mt-1 flex flex-wrap gap-2">
567
1120
  {REPORT_CODES.map((code) => (
568
1121
  <button
569
1122
  key={code}
@@ -580,47 +1133,20 @@ export function GmailSettings() {
580
1133
  )}
581
1134
  </div>
582
1135
  ) : (
583
- <div className="flex flex-col gap-1">
584
- <div className="flex items-center gap-2">
585
- <label htmlFor={newLevelId} className={muted}>
586
- {t("newLevel", undefined, "Level for the new account")}
587
- </label>
588
- <select
589
- id={newLevelId}
590
- data-testid="gmail-new-level"
591
- value={newTier}
592
- onChange={(e) => setNewTier(e.target.value as Tier)}
593
- className={field}
594
- >
595
- <TierOptions />
596
- </select>
597
- <button
598
- type="button"
599
- className={btn}
600
- data-testid="gmail-add-account"
601
- disabled={!client.configured}
602
- onClick={() => void addAccount()}
603
- >
604
- {t("addAccount", undefined, "Add account")}
605
- </button>
606
- </div>
607
- <p className={muted} data-testid="gmail-cross-org-hint">
608
- {t(
609
- "crossOrgHint",
610
- undefined,
611
- "Accounts outside the project's Workspace organization need an External audience, with each account added as a test user (step 3).",
612
- )}
613
- </p>
614
- </div>
615
- )}
616
- {flowError && (
617
- <div role="alert" className={errorText} data-testid="gmail-flow-error" data-step={step ?? ""}>
618
- {t(errKey, { clientId: client.clientId ?? "" }, ERROR_EN[errKey])}{" "}
619
- <span className={muted} data-testid="gmail-flow-error-code">
620
- ({flowError})
621
- </span>
622
- </div>
1136
+ <AddAccount
1137
+ configured={client.configured}
1138
+ newTier={newTier}
1139
+ onTier={setNewTier}
1140
+ email={addEmail}
1141
+ onEmail={(v) => {
1142
+ setAddEmail(v);
1143
+ setAddEmailError(false);
1144
+ }}
1145
+ emailError={addEmailError}
1146
+ onAdd={() => void addAccount()}
1147
+ />
623
1148
  )}
1149
+ {flowError && <FlowErrorNotice code={flowError} step={step} errKey={errKey} clientId={client.clientId ?? ""} />}
624
1150
  {lastRevoke && (
625
1151
  <div role="status" className={muted} data-testid="gmail-revoke-result">
626
1152
  {lastRevoke}