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

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,1158 +1,73 @@
1
1
  /**
2
- * Gmail settings section (design D7 wizard + accounts panel). Renders the
3
- * 6-step Google Cloud setup wizard (deep links, copyable gcloud commands,
4
- * client-JSON upload, sign-in error → step mapping) and the accounts panel
5
- * (add / re-auth / level / alias / revoke, status badges, honest scope limit).
6
- * Sign-in flows render through the host `ui:oauth-flow` primitive.
7
- * See change: add-gmail-plugin.
8
- *
9
- * improve-gmail-settings-ux: declared theme tokens + `.focus-ring` on every
10
- * control; consent hint + "Google showed an error?" disclosure while a sign-in
11
- * waits (reported code latched via `reportedRef`, so neither poll callback can
12
- * overwrite it or re-mount the flow); every flow error rendered as a sentence
13
- * (`errorKey` / `ERROR_EN`); Revoke via `ui:confirm-dialog`; alias feedback;
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.
2
+ * Settings → Gmail: a pointer notice. Account, client and setup management moved to Settings → Google accounts
3
+ * (change: add-google-connect). `GET /api/plugins/gmail/state` answers `{ moved: true }` while Google Connect is
4
+ * usable and `{ moved: false, googleConnect: "unavailable" }` while it is not — either way this section holds no
5
+ * account or client forms and no Connect button. See change: add-google-connect.
21
6
  */
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";
35
- import type React from "react";
36
- import { useCallback, useEffect, useId, useRef, useState } from "react";
37
- import type { Audience, AutoSetupState, SetupRunView } from "../shared/auto-setup.js";
38
- import { validateClientJson } from "../shared/client-json.js";
39
- import type { AccountInfo } from "../shared/protocol.js";
40
- import { TIERS, type Tier } from "../shared/scopes.js";
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";
7
+ import { SafeLink, SettingsNotice, useT } from "@blackbelt-technology/dashboard-plugin-runtime";
56
8
 
57
- interface GmailState {
58
- client: { configured: boolean; clientId?: string; projectId?: string };
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;
69
- }
70
-
71
- type FlowState = React.ComponentProps<ReturnType<typeof useUiPrimitive<"ui:oauth-flow">>>["flow"];
72
- type FlowStatus = NonNullable<FlowState["status"]>;
73
-
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)]";
79
- // Static strings: Tailwind cannot see interpolated class names.
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)]`;
83
-
84
- /** Poll a flow every 500 ms until terminal. */
85
- function useFlowPoll(flowId: string | undefined, onPending: (s: FlowStatus) => void, onDone: (err: string | null) => void) {
86
- const pending = useRef(onPending);
87
- const done = useRef(onDone);
88
- pending.current = onPending;
89
- done.current = onDone;
90
- useEffect(() => {
91
- if (!flowId) return;
92
- let stopped = false;
93
- const timer = setInterval(() => {
94
- oauthFlowClient.status(flowId).then(
95
- (s) => {
96
- if (stopped) return;
97
- if (s.status === "pending") pending.current(s);
98
- else done.current(s.status === "complete" ? null : (s.error ?? s.status));
99
- },
100
- (err: unknown) => {
101
- if (!stopped) done.current(err instanceof Error ? err.message : String(err));
102
- },
103
- );
104
- }, 500);
105
- return () => {
106
- stopped = true;
107
- clearInterval(timer);
108
- };
109
- }, [flowId]);
110
- }
111
-
112
- function Copyable({ value }: { value: string }) {
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");
127
- return (
128
- <div className="flex items-center gap-2">
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>
132
- </button>
133
- </div>
134
- );
135
- }
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
-
148
- function StepLink({ href, label }: { href: string; label: string }) {
149
- return (
150
- <SafeLink href={href} target="_blank" rel="noopener noreferrer" className="focus-ring text-xs text-[var(--accent-text)] underline">
151
- {label}
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
- }
9
+ import { useEffect, useState } from "react";
326
10
 
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>
340
- );
341
- }
342
-
343
- export function SetupWizard({
344
- state,
345
- highlight,
346
- onUploaded,
347
- }: {
348
- state: GmailState;
349
- highlight: WizardStep | null;
350
- onUploaded: () => void;
351
- }) {
352
- const t = useT();
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);
366
- const [uploadError, setUploadError] = useState<{ code: string; step: WizardStep } | null>(null);
367
- const links = consoleLinks(projectId, owner);
368
- const cmds = gcloudCommands(projectId, owner);
369
- const [focus, setFocus] = useState<WizardStep | null>(highlight);
370
- useEffect(() => setFocus(highlight ?? uploadError?.step ?? null), [highlight, uploadError]);
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
- };
11
+ /** The dashboard route of the Google plugin's settings page. */
12
+ const GOOGLE_SETTINGS_PATH = "/settings/plugins/google";
435
13
 
436
- const upload = async (file: File) => {
437
- setUploadError(null);
438
- setMismatch(null);
439
- const textContent = await file.text();
440
- const local = validateClientJson(textContent);
441
- if (!local.ok) {
442
- setUploadError({ code: local.error.code, step: local.error.step });
443
- return;
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
- }
451
- try {
452
- const reply = await api<{ projectId?: string }>("/client", { method: "PUT", body: JSON.stringify({ json: JSON.parse(textContent) }) });
453
- reconcileJsonProject(reply.projectId);
454
- onUploaded();
455
- } catch (err) {
456
- const code = (err as { code?: string }).code ?? "upload_failed";
457
- setUploadError({ code, step: errorStep(code) ?? 5 });
458
- }
459
- };
14
+ type Moved = "usable" | "unavailable";
460
15
 
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);
466
-
467
- return (
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
507
- value={projectId}
508
- onChange={onProjectChange}
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" }}
526
- />
527
- </div>
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} />
540
- <div className={muted}>{t("fallback2", undefined, "If the link moved: APIs & Services → OAuth consent screen.")}</div>
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} />
544
- <div className={muted}>
545
- {t(
546
- "audienceHelp",
547
- undefined,
548
- AUDIENCE_HELP_EN,
549
- )}
550
- </div>
551
- <div className={muted}>
552
- {t(
553
- "audienceErrors",
554
- undefined,
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.",
556
- )}
557
- </div>
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} />
561
- <div className={muted}>
562
- {t("clientHelp", undefined, "Application type: Desktop app. Download the JSON. If the link moved: APIs & Services → Credentials.")}
563
- </div>
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
- )}
588
- />
589
- {state.client.configured && (
590
- <div className={muted} data-testid="gmail-client-ok">
591
- ✓ {state.client.clientId}
592
- </div>
593
- )}
594
- </WizardStepItem>
595
- <WizardStepItem n={6} title={t("step6", undefined, "6. Test sign-in")} current={current === 6} done={isDone(6)}>
596
- <div className={muted}>{t("step6Help", undefined, "Add your first account below — that is the test sign-in.")}</div>
597
- </WizardStepItem>
598
- </ol>
599
- );
600
- }
601
-
602
- const TIER_LABEL: Record<Tier, string> = { readonly: "readonly", draft: "draft", send: "send" };
603
- const TIER_DESC: Record<Tier, [key: string, en: string]> = {
604
- readonly: ["tierReadonly", "read mail"],
605
- draft: ["tierDraft", "read + create drafts"],
606
- send: ["tierSend", "read, draft, send, reply, labels, archive, trash"],
607
- };
608
-
609
- /** Each level's own description, as a select option list. */
610
- function useTierOptions(): { value: string; label: string }[] {
611
- const t = useT();
612
- return TIERS.map((tier) => ({ value: tier, label: `${TIER_LABEL[tier]} — ${t(TIER_DESC[tier][0], undefined, TIER_DESC[tier][1])}` }));
613
- }
614
-
615
- /** Codes the user can report from Google's own error page (closed list, design D1). */
616
- const REPORT_CODES = ["org_internal", "access_denied", "admin_policy_enforced", "other"] as const;
617
-
618
- function AccountRow({
619
- acct,
620
- onChanged,
621
- onFlow,
622
- onRevoked,
623
- }: {
624
- acct: AccountInfo;
625
- onChanged: () => void;
626
- onFlow: (flowId: string) => void;
627
- onRevoked: (email: string, remoteRevoked: boolean) => void;
628
- }) {
629
- const t = useT();
630
- const ConfirmDialog = useUiPrimitive("ui:confirm-dialog");
631
- const tierOptions = useTierOptions();
632
- const [alias, setAlias] = useState(acct.alias ?? "");
633
- const [msg, setMsg] = useState<string | null>(null);
634
- const [aliasMsg, setAliasMsg] = useState<{ ok: boolean; text: string } | null>(null);
635
- const [confirming, setConfirming] = useState(false);
636
- const [filtersOn, setFiltersOn] = useState(acct.filters === true);
637
- useEffect(() => setFiltersOn(acct.filters === true), [acct.filters]);
638
- const run = async (fn: () => Promise<void>) => {
639
- setMsg(null);
640
- try {
641
- await fn();
642
- } catch (err) {
643
- setMsg((err as { code?: string }).code ?? (err as Error).message);
644
- }
645
- };
646
- const setLevel = (tier: Tier) =>
647
- run(async () => {
648
- const r = await api<{ applied?: boolean; flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/level`, {
649
- method: "POST",
650
- body: JSON.stringify({ tier }),
651
- });
652
- if (r.flowId) onFlow(r.flowId);
653
- else onChanged();
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
- });
667
- const saveAlias = async () => {
668
- try {
669
- await api(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "PATCH", body: JSON.stringify({ alias: alias || null }) });
670
- setAliasMsg({ ok: true, text: t("aliasSaved", undefined, "Saved") });
671
- onChanged();
672
- } catch (err) {
673
- const code = (err as { code?: string }).code ?? (err as Error).message;
674
- const text =
675
- code === "alias_taken"
676
- ? t("errAliasTaken", undefined, "That alias is already used by another account.")
677
- : code === "invalid_alias"
678
- ? t("errInvalidAlias", undefined, "Aliases are 1–40 letters, digits, '.', '_' or '-'.")
679
- : code;
680
- setAliasMsg({ ok: false, text });
681
- }
682
- };
683
- const revoke = () =>
684
- run(async () => {
685
- const r = await api<{ remoteRevoked: boolean }>(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "DELETE" });
686
- onRevoked(acct.email, r.remoteRevoked);
687
- onChanged();
688
- });
689
- return (
690
- <li
691
- className="flex flex-col gap-2 rounded-md border border-[var(--border-secondary)] p-2"
692
- data-testid="gmail-account-row"
693
- data-email={acct.email}
694
- >
695
- <div className="flex flex-wrap items-center gap-2">
696
- <span className="text-sm font-semibold text-[var(--text-primary)]" data-testid="gmail-account-email">
697
- {acct.email}
698
- </span>
699
- {acct.status === "ok" ? (
700
- <span className={badgeOk} data-testid="gmail-account-status" data-status="ok">
701
- {t("statusOk", undefined, "Connected")}
702
- </span>
703
- ) : (
704
- <span className={badgeReauth} data-testid="gmail-account-status" data-status="reauth_required">
705
- {t("statusReauth", undefined, "Re-auth needed")}
706
- </span>
707
- )}
708
- {acct.testingHint && (
709
- <span className={muted} title={t("testingHint", undefined, "Testing-mode app: Google expires this grant after 7 days.")}>
710
- {t("testingBadge", undefined, "testing: 7-day")}
711
- </span>
712
- )}
713
- <input
714
- aria-label={t("aliasFor", { email: acct.email }, `Alias for ${acct.email}`)}
715
- data-testid="gmail-account-alias"
716
- className={`${field} w-28`}
717
- value={alias}
718
- placeholder={t("aliasPlaceholder", undefined, "alias")}
719
- onChange={(e) => {
720
- setAlias(e.target.value);
721
- setAliasMsg(null);
722
- }}
723
- onBlur={() => alias !== (acct.alias ?? "") && void saveAlias()}
724
- />
725
- {aliasMsg && (
726
- <span
727
- role={aliasMsg.ok ? "status" : "alert"}
728
- className={aliasMsg.ok ? muted : errorText}
729
- data-testid="gmail-alias-feedback"
730
- >
731
- {aliasMsg.text}
732
- </span>
733
- )}
734
- </div>
735
- <div className="flex flex-wrap items-center gap-2">
736
- <label className={muted}>
737
- {t("level", undefined, "Level")}{" "}
738
- <select
739
- aria-label={t("levelFor", { email: acct.email }, `Level for ${acct.email}`)}
740
- data-testid="gmail-account-level"
741
- value={acct.tier}
742
- onChange={(e) => void setLevel(e.target.value as Tier)}
743
- className={field}
744
- >
745
- {tierOptions.map((o) => (
746
- <option key={o.value} value={o.value}>
747
- {o.label}
748
- </option>
749
- ))}
750
- </select>
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
- />
759
- <button
760
- type="button"
761
- className={btn}
762
- data-testid="gmail-account-reauth"
763
- aria-label={t("reauthFor", { email: acct.email }, `Re-authenticate ${acct.email}`)}
764
- onClick={() =>
765
- void run(async () => {
766
- // Force a fresh consent at the current level (status reset on persist).
767
- const r = await api<{ flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/reauth`, { method: "POST" });
768
- if (r.flowId) onFlow(r.flowId);
769
- })
770
- }
771
- >
772
- {t("reauth", undefined, "Re-authenticate")}
773
- </button>
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
- >
781
- {t("revoke", undefined, "Revoke")}
782
- </button>
783
- {msg && (
784
- <span role="alert" className={errorText}>
785
- {msg}
786
- </span>
787
- )}
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>
796
- {confirming && (
797
- <ConfirmDialog
798
- message={t(
799
- "revokeConfirm",
800
- { email: acct.email },
801
- `Revoke ${acct.email}? The dashboard forgets the account and asks Google to revoke its access.`,
802
- )}
803
- confirmLabel={t("revoke", undefined, "Revoke")}
804
- onConfirm={() => {
805
- setConfirming(false);
806
- void revoke();
807
- }}
808
- onCancel={() => setConfirming(false)}
809
- />
810
- )}
811
- </li>
812
- );
813
- }
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
- );
16
+ function openGoogleSettings(e: React.MouseEvent<HTMLElement>): void {
17
+ // SPA navigation (wouter listens to history events); a modified click keeps the browser's own behaviour.
18
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
19
+ e.preventDefault();
20
+ window.history.pushState(null, "", GOOGLE_SETTINGS_PATH);
21
+ window.dispatchEvent(new PopStateEvent("popstate"));
930
22
  }
931
23
 
932
24
  export function GmailSettings() {
933
25
  const t = useT();
934
- const OAuthFlow = useUiPrimitive("ui:oauth-flow");
935
- const [state, setState] = useState<GmailState | null>(null);
936
- const [loadError, setLoadError] = useState<string | null>(null);
937
- const [flow, setFlow] = useState<FlowState | null>(null);
938
- const [flowError, setFlowError] = useState<string | null>(null);
939
- const [lastRevoke, setLastRevoke] = useState<string | null>(null);
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);
947
- // Latch (design D1): once the user reports a Google-page code, no late poll
948
- // result may overwrite it or re-mount the flow view. Reset on a new flow.
949
- const reportedRef = useRef<string | null>(null);
26
+ const [moved, setMoved] = useState<Moved | null>(null);
27
+ const [error, setError] = useState<string | null>(null);
950
28
 
951
- const refresh = useCallback(async () => {
952
- try {
953
- setState(await api<GmailState>("/state"));
954
- setLoadError(null);
955
- } catch (err) {
956
- setLoadError((err as Error).message);
957
- }
958
- }, []);
959
29
  useEffect(() => {
960
- void refresh();
961
- }, [refresh]);
962
-
963
- const startFlow = async (flowId: string) => {
964
- reportedRef.current = null;
965
- setFlowError(null);
966
- try {
967
- setFlow({ phase: "waiting", status: await oauthFlowClient.status(flowId) });
968
- } catch (err) {
969
- setFlow(null);
970
- setFlowError(err instanceof Error ? err.message : String(err));
971
- }
972
- };
973
- useFlowPoll(
974
- flow?.status?.flowId,
975
- (status) => {
976
- if (reportedRef.current) return;
977
- setFlow({ phase: "waiting", status });
978
- },
979
- (err) => {
980
- if (reportedRef.current) return;
981
- setFlow(null);
982
- setFlowError(err);
983
- void refresh();
984
- },
985
- );
986
-
987
- /** Order is load-bearing (design D1): latch, then clear, then cancel. */
988
- const report = (code: string) => {
989
- const flowId = flow?.status?.flowId;
990
- reportedRef.current = code;
991
- setFlow(null);
992
- setFlowError(code);
993
- if (flowId) void oauthFlowClient.cancel(flowId).catch(() => {});
994
- };
995
-
996
- const addAccount = async () => {
997
- const request = accountRequest(newTier, addEmail);
998
- setAddEmailError(!request);
999
- if (!request) return;
1000
- reportedRef.current = null;
1001
- setFlowError(null);
1002
- setFlow({ phase: "starting" });
1003
- try {
1004
- const r = await api<{ flowId: string }>("/accounts", {
1005
- method: "POST",
1006
- body: JSON.stringify(request),
1007
- });
1008
- await startFlow(r.flowId);
1009
- } catch (err) {
1010
- setFlow(null);
1011
- setFlowError((err as { code?: string }).code ?? (err as Error).message);
1012
- }
1013
- };
1014
-
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
- );
30
+ let live = true;
31
+ fetch("/api/plugins/gmail/state")
32
+ .then(async (res) => {
33
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
34
+ return (await res.json()) as { moved?: boolean };
35
+ })
36
+ .then((body) => live && setMoved(body.moved === true ? "usable" : "unavailable"))
37
+ .catch((err: unknown) => live && setError(err instanceof Error ? err.message : String(err)));
38
+ return () => {
39
+ live = false;
40
+ };
41
+ }, []);
1028
42
 
1029
- const step = errorStep(flowError);
1030
- const errKey = errorKey(flowError);
1031
- const { client } = state;
1032
- const wizard = wizardProps(state, handoff, step);
1033
- const summary = !client.configured
1034
- ? t("summaryNotConfigured", undefined, "not configured")
1035
- : client.projectId
1036
- ? t("summaryProject", { projectId: client.projectId }, `✓ project ${client.projectId}`)
1037
- : t("summaryClient", { clientId: client.clientId ?? "" }, `✓ ${client.clientId ?? ""}`);
1038
43
  return (
1039
44
  <section className="flex flex-col gap-3" data-testid="gmail-settings" aria-labelledby="gmail-settings-title">
1040
45
  <h3 id="gmail-settings-title" className="m-0 text-sm font-semibold text-[var(--text-primary)]">
1041
46
  {t("title", undefined, "Gmail")}
1042
47
  </h3>
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>
1064
-
1065
- <div className="flex flex-col gap-2" data-testid="gmail-accounts">
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">
1068
- {t(
1069
- "levelHelp",
1070
- undefined,
1071
- "Levels are enforced by this plugin, not by Google: a token carries every scope Google granted (draft-level compose access could technically send), so a level limits what the agent's tools may do. Any session on this dashboard can use every account within its level.",
1072
- )}
1073
- </p>
1074
- {state.accounts.length === 0 && <div className={muted}>{t("noAccounts", undefined, "No accounts connected.")}</div>}
1075
- <ul className="m-0 flex list-none flex-col gap-2 p-0">
1076
- {state.accounts.map((a) => (
1077
- <AccountRow
1078
- key={a.sub}
1079
- acct={a}
1080
- onChanged={() => void refresh()}
1081
- onFlow={(id) => void startFlow(id)}
1082
- onRevoked={(email, remote) =>
1083
- setLastRevoke(
1084
- remote
1085
- ? t("revokedOk", { email }, `${email} removed and access revoked at Google.`)
1086
- : t(
1087
- "revokeManual",
1088
- { email },
1089
- `${email} removed locally, but Google could not be reached. Revoke access at myaccount.google.com/permissions.`,
1090
- ),
1091
- )
1092
- }
1093
- />
1094
- ))}
1095
- </ul>
1096
- {flow ? (
1097
- <div className="flex flex-col gap-2">
1098
- <p className={`${muted} m-0`} data-testid="gmail-consent-hint">
1099
- {t(
1100
- "consentHint",
1101
- undefined,
1102
- CONSENT_HINT_EN,
1103
- )}
1104
- </p>
1105
- <UnverifiedHint audience={audience} />
1106
- <OAuthFlow
1107
- flow={flow}
1108
- onSendInput={(id, value) => oauthFlowClient.input(id, value)}
1109
- onCancel={(id) => {
1110
- void oauthFlowClient.cancel(id);
1111
- }}
1112
- />
1113
- {flow.phase === "waiting" && (
1114
- <details data-testid="gmail-google-error">
1115
- <summary className="focus-ring cursor-pointer text-xs text-[var(--text-primary)]">
1116
- {t("googleErrorSummary", undefined, "Google showed an error instead of returning here?")}
1117
- </summary>
1118
- <div className={muted}>{t("googleErrorHelp", undefined, "Pick the error code Google displayed:")}</div>
1119
- <div className="mt-1 flex flex-wrap gap-2">
1120
- {REPORT_CODES.map((code) => (
1121
- <button
1122
- key={code}
1123
- type="button"
1124
- className={btn}
1125
- data-testid={`gmail-report-${code}`}
1126
- onClick={() => report(code)}
1127
- >
1128
- {code === "other" ? t("reportOther", undefined, "Something else") : code}
1129
- </button>
1130
- ))}
1131
- </div>
1132
- </details>
1133
- )}
1134
- </div>
1135
- ) : (
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
- />
1148
- )}
1149
- {flowError && <FlowErrorNotice code={flowError} step={step} errKey={errKey} clientId={client.clientId ?? ""} />}
1150
- {lastRevoke && (
1151
- <div role="status" className={muted} data-testid="gmail-revoke-result">
1152
- {lastRevoke}
1153
- </div>
1154
- )}
1155
- </div>
48
+ {error && (
49
+ <SettingsNotice tone="error" testId="gmail-load-error">
50
+ {error}
51
+ </SettingsNotice>
52
+ )}
53
+ {moved === "usable" && (
54
+ <SettingsNotice tone="info" testId="gmail-moved">
55
+ {t("movedNotice", undefined, "Gmail accounts are now managed under Settings → Google accounts. Nothing to reconnect.")}{" "}
56
+ <SafeLink
57
+ href={GOOGLE_SETTINGS_PATH}
58
+ data-testid="gmail-open-google"
59
+ className="focus-ring text-[var(--accent-text)] underline"
60
+ onClick={openGoogleSettings}
61
+ >
62
+ {t("movedLink", undefined, "Open Google accounts")}
63
+ </SafeLink>
64
+ </SettingsNotice>
65
+ )}
66
+ {moved === "unavailable" && (
67
+ <SettingsNotice tone="info" testId="gmail-google-off">
68
+ {t("googleOff", undefined, "Turn on Google accounts to manage Gmail accounts")}
69
+ </SettingsNotice>
70
+ )}
1156
71
  </section>
1157
72
  );
1158
73
  }