@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.
@@ -0,0 +1,787 @@
1
+ /**
2
+ * "Set up automatically" (design D3/D5–D11): the secondary entry, the start form,
3
+ * the run progress panel (polls `GET setup/run/:id` every second while live), the
4
+ * human-checkpoint / audience / links / busy prompts and the hand-off notice.
5
+ * The run itself lives in the gmail server; this file only renders its secret-free
6
+ * view and posts the user's answers. "Add account" stays the section's one primary
7
+ * button (it lives in `GmailSettings.tsx`); everything here is secondary.
8
+ * See change: add-gmail-auto-setup.
9
+ */
10
+ import { SettingsNotice, TextField, ToggleField, useT, useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
11
+ import type React from "react";
12
+ import { useCallback, useEffect, useId, useRef, useState } from "react";
13
+ import {
14
+ type Audience,
15
+ type AutoSetupState,
16
+ type CheckpointKind,
17
+ type PublishLinks,
18
+ SETUP_STEP_IDS,
19
+ type SetupDecision,
20
+ type SetupRunRequest,
21
+ type SetupRunState,
22
+ type SetupRunView,
23
+ type SetupStepId,
24
+ type SetupStepStatus,
25
+ } from "../shared/auto-setup.js";
26
+ import { classifyProjectId, isEmail, normalizeEmail, normalizeProjectId } from "../shared/setup.js";
27
+ import { CHECKPOINT_KEY, handoffKey, isLive, LINK_ERROR_KEY, startErrorKey, validateLinks } from "./auto-setup.js";
28
+ import { api, btn, errorText, muted } from "./ui.js";
29
+ import { ERROR_EN } from "./wizard.js";
30
+
31
+ const POLL_MS = 1000;
32
+
33
+ const CHECKPOINT_EN: Record<string, string> = {
34
+ autoCpSignIn:
35
+ "Sign in to Google in the dedicated browser window that just opened, using the owner account. You type the password there yourself; the dashboard never sees it. Setup continues as soon as you are signed in.",
36
+ autoCpTerms: "Google Cloud is asking you to accept its terms of service in the dedicated browser window. Read and accept them there; setup continues afterwards.",
37
+ autoCpPolicy:
38
+ "Tick “I agree to the Google API Services: User Data Policy” in the dedicated browser window yourself. The dashboard never ticks it for you. Setup continues once it is ticked.",
39
+ autoCpPublish:
40
+ "Confirm “Push to production?” in the dedicated browser window. Publishing removes the 7-day token expiry. Setup continues once the app is in production.",
41
+ };
42
+
43
+ const STEP_LABEL: Record<SetupStepId, [key: string, en: string]> = {
44
+ project: ["autoStepProject", "Project"],
45
+ api: ["autoStepApi", "Gmail API"],
46
+ branding: ["autoStepBranding", "Branding"],
47
+ publish: ["autoStepPublish", "Audience + publish"],
48
+ client: ["autoStepClient", "OAuth client"],
49
+ capture: ["autoStepCapture", "Save secret"],
50
+ };
51
+
52
+ const STATUS_LABEL: Record<SetupStepStatus, [key: string, en: string]> = {
53
+ pending: ["autoStatusPending", "waiting"],
54
+ running: ["autoStatusRunning", "in progress"],
55
+ done: ["autoStatusDone", "done"],
56
+ skipped: ["autoStatusSkipped", "already done"],
57
+ handoff: ["autoStatusHandoff", "needs you"],
58
+ };
59
+
60
+ type PollResult = { view: SetupRunView } | { gone: true } | null;
61
+
62
+ /** One poll: the view, `gone` on 404, or `null` for a transient failure (keep polling). */
63
+ async function pollOnce(runId: string): Promise<PollResult> {
64
+ try {
65
+ return { view: await api<SetupRunView>(`/setup/run/${encodeURIComponent(runId)}`) };
66
+ } catch (err) {
67
+ return (err as { status?: number }).status === 404 ? { gone: true } : null;
68
+ }
69
+ }
70
+
71
+ /** Poll the run view every second while the run is live; a 404 means the run is gone. */
72
+ function useSetupRun(runId: string | null): { view: SetupRunView | null; lost: boolean; refresh: () => void } {
73
+ const [view, setView] = useState<SetupRunView | null>(null);
74
+ const [lost, setLost] = useState(false);
75
+ const tickRef = useRef<() => void>(() => {});
76
+ useEffect(() => {
77
+ setView(null);
78
+ setLost(false);
79
+ if (!runId) return;
80
+ let stopped = false;
81
+ let inflight = false;
82
+ let timer: ReturnType<typeof setInterval> | undefined;
83
+ const stop = () => {
84
+ stopped = true;
85
+ if (timer) clearInterval(timer);
86
+ };
87
+ const tick = async (): Promise<void> => {
88
+ if (stopped || inflight) return;
89
+ inflight = true;
90
+ const r = await pollOnce(runId);
91
+ inflight = false;
92
+ if (stopped || !r) return;
93
+ if ("gone" in r) {
94
+ stop();
95
+ setLost(true);
96
+ return;
97
+ }
98
+ setView(r.view);
99
+ if (!isLive(r.view.state)) stop();
100
+ };
101
+ tickRef.current = () => void tick();
102
+ void tick();
103
+ timer = setInterval(() => void tick(), POLL_MS);
104
+ return stop;
105
+ }, [runId]);
106
+ return { view, lost, refresh: useCallback(() => tickRef.current(), []) };
107
+ }
108
+
109
+ /** A refused request as a sentence: known codes are translated, a 400 shows the server's own rule text. */
110
+ function useErrorText() {
111
+ const t = useT();
112
+ return (err: unknown): string => {
113
+ const { code, detail } = err as { code?: string; detail?: string };
114
+ const key = startErrorKey(code);
115
+ if (key) return t(key, undefined, ERROR_EN[key]);
116
+ if (detail) return detail;
117
+ const generic = t("autoErrGeneric", undefined, ERROR_EN.autoErrGeneric);
118
+ return code ? `${generic} (${code})` : generic;
119
+ };
120
+ }
121
+
122
+ const CHIP_TONE = {
123
+ done: "border-[var(--severity-success-border)] bg-[var(--severity-success-bg)] text-[var(--severity-success-fg)]",
124
+ handoff: "border-[var(--severity-warning-border)] bg-[var(--severity-warning-bg)] text-[var(--severity-warning-fg)]",
125
+ current: "border-[var(--tint-blue-border)] bg-[var(--tint-blue-bg)] text-[var(--tint-blue-fg)]",
126
+ idle: "border-[var(--border-secondary)] bg-[var(--bg-tertiary)] text-[var(--text-secondary)]",
127
+ } as const;
128
+
129
+ function chipTone(st: SetupStepStatus, current: boolean): string {
130
+ if (st === "done" || st === "skipped") return CHIP_TONE.done;
131
+ if (st === "handoff") return CHIP_TONE.handoff;
132
+ return current ? CHIP_TONE.current : CHIP_TONE.idle;
133
+ }
134
+
135
+ function StepChip({ id, status, current }: { id: SetupStepId; status: SetupStepStatus; current: boolean }) {
136
+ const t = useT();
137
+ const [labelKey, labelEn] = STEP_LABEL[id];
138
+ const [statusKey, statusEn] = STATUS_LABEL[status];
139
+ return (
140
+ <li
141
+ data-testid={`gmail-setup-step-${id}`}
142
+ data-status={status}
143
+ aria-current={current ? "step" : undefined}
144
+ className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[12px] font-semibold ${chipTone(status, current)}`}
145
+ >
146
+ {status === "done" || status === "skipped" ? <span aria-hidden="true">✓</span> : null}
147
+ {t(labelKey, undefined, labelEn)}
148
+ <span className="sr-only"> — {t(statusKey, undefined, statusEn)}</span>
149
+ </li>
150
+ );
151
+ }
152
+
153
+ function StepChips({ view }: { view: SetupRunView }) {
154
+ const t = useT();
155
+ const live = isLive(view.state);
156
+ const status = new Map(view.steps.map((s) => [s.id, s.status]));
157
+ return (
158
+ <ol className="m-0 flex list-none flex-wrap gap-1.5 p-0" aria-label={t("autoStepsLabel", undefined, "Setup steps")} data-testid="gmail-setup-steps">
159
+ {SETUP_STEP_IDS.map((id) => (
160
+ <StepChip key={id} id={id} status={status.get(id) ?? "pending"} current={live && view.step === id} />
161
+ ))}
162
+ </ol>
163
+ );
164
+ }
165
+
166
+ function AudienceDecision({
167
+ decision,
168
+ busy,
169
+ onChoose,
170
+ }: {
171
+ decision: Extract<SetupDecision, { kind: "audience" }>;
172
+ busy: boolean;
173
+ onChoose: (a: Audience) => void;
174
+ }) {
175
+ const t = useT();
176
+ const internal = decision.detected === "internal";
177
+ const org = decision.org ?? t("autoOrgFallback", undefined, "its organization");
178
+ return (
179
+ <SettingsNotice tone="info" testId="gmail-setup-audience">
180
+ <div className="flex flex-col gap-2">
181
+ <strong>{t("autoAudienceTitle", undefined, "Who will sign in to this app?")}</strong>
182
+ <span>
183
+ {internal
184
+ ? t(
185
+ "autoAudienceInternalHelp",
186
+ { org },
187
+ `Your account belongs to ${org}. Internal admits only accounts of that organization and shows no unverified-app warning. External admits any Google account you add as a test user and shows “Google hasn't verified this app” at sign-in.`,
188
+ )
189
+ : t(
190
+ "autoAudienceExternalOnly",
191
+ undefined,
192
+ "This project has no organization (a personal Google account), so only External is available. At sign-in Google shows “Google hasn't verified this app”: choose Advanced and continue. Publishing removes the 7-day token expiry and admits at most 100 users.",
193
+ )}
194
+ </span>
195
+ <span className="flex flex-wrap gap-2" role="group" aria-label={t("autoAudienceTitle", undefined, "Who will sign in to this app?")}>
196
+ {internal && (
197
+ <button type="button" className={btn} disabled={busy} data-testid="gmail-setup-audience-internal" onClick={() => onChoose("internal")}>
198
+ {t("autoAudienceInternal", undefined, "Internal")}
199
+ </button>
200
+ )}
201
+ <button type="button" className={btn} disabled={busy} data-testid="gmail-setup-audience-external" onClick={() => onChoose("external")}>
202
+ {t("autoAudienceExternal", undefined, "External")}
203
+ </button>
204
+ </span>
205
+ </div>
206
+ </SettingsNotice>
207
+ );
208
+ }
209
+
210
+ function LinksDecision({
211
+ decision,
212
+ busy,
213
+ onConfirm,
214
+ }: {
215
+ decision: Extract<SetupDecision, { kind: "links" }>;
216
+ busy: boolean;
217
+ onConfirm: (links: PublishLinks) => void;
218
+ }) {
219
+ const t = useT();
220
+ const [links, setLinks] = useState<PublishLinks>(decision.links);
221
+ const [confirmed, setConfirmed] = useState(false);
222
+ const errors = validateLinks(links);
223
+ const set = (key: keyof PublishLinks) => (v: string) => setLinks((l) => ({ ...l, [key]: v }));
224
+ const err = (key: keyof PublishLinks): string | null => {
225
+ const e = errors[key];
226
+ return e ? t(LINK_ERROR_KEY[e], undefined, ERROR_EN[LINK_ERROR_KEY[e]]) : null;
227
+ };
228
+ const valid = Object.keys(errors).length === 0;
229
+ return (
230
+ <SettingsNotice tone="info" testId="gmail-setup-links">
231
+ <div className="flex flex-col gap-2">
232
+ <strong>{t("autoLinksTitle", undefined, "Links for Google's consent screen")}</strong>
233
+ <span>
234
+ {t(
235
+ "autoLinksHelp",
236
+ undefined,
237
+ "Google requires a home page, a privacy-policy link and an authorized domain before an External app can be published. They appear on Google's consent screen for every account that signs in. The defaults point at the dashboard's public repository; replace them with your own if you prefer.",
238
+ )}
239
+ </span>
240
+ <TextField
241
+ label={t("autoLinkHome", undefined, "Home page")}
242
+ hint={null}
243
+ mono
244
+ value={links.homePage}
245
+ onChange={set("homePage")}
246
+ error={err("homePage")}
247
+ testIds={{ control: "gmail-setup-link-home", error: "gmail-setup-link-home-error" }}
248
+ />
249
+ <TextField
250
+ label={t("autoLinkPrivacy", undefined, "Privacy policy")}
251
+ hint={null}
252
+ mono
253
+ value={links.privacyPolicy}
254
+ onChange={set("privacyPolicy")}
255
+ error={err("privacyPolicy")}
256
+ testIds={{ control: "gmail-setup-link-privacy", error: "gmail-setup-link-privacy-error" }}
257
+ />
258
+ <TextField
259
+ label={t("autoLinkDomain", undefined, "Authorized domain")}
260
+ hint={null}
261
+ mono
262
+ value={links.authorizedDomain}
263
+ onChange={set("authorizedDomain")}
264
+ error={err("authorizedDomain")}
265
+ testIds={{ control: "gmail-setup-link-domain", error: "gmail-setup-link-domain-error" }}
266
+ />
267
+ <ToggleField
268
+ label={t("autoLinksConfirm", undefined, "I understand these links appear on Google's consent screen for every account, and I want to use them.")}
269
+ hint={null}
270
+ testIds={{ control: "gmail-setup-links-confirm" }}
271
+ value={confirmed}
272
+ onChange={setConfirmed}
273
+ />
274
+ <span>
275
+ <button
276
+ type="button"
277
+ className={btn}
278
+ disabled={busy || !confirmed || !valid}
279
+ data-testid="gmail-setup-links-continue"
280
+ onClick={() => onConfirm({ homePage: links.homePage.trim(), privacyPolicy: links.privacyPolicy.trim(), authorizedDomain: links.authorizedDomain.trim().toLowerCase() })}
281
+ >
282
+ {t("autoLinksContinue", undefined, "Use these links")}
283
+ </button>
284
+ </span>
285
+ </div>
286
+ </SettingsNotice>
287
+ );
288
+ }
289
+
290
+ function BusyNotice({ holder, busy, onTakeover }: { holder?: string; busy: boolean; onTakeover: () => void }) {
291
+ const t = useT();
292
+ const ConfirmDialog = useUiPrimitive("ui:confirm-dialog");
293
+ const [confirming, setConfirming] = useState(false);
294
+ const who = holder ?? t("autoBusyUnknown", undefined, "another session");
295
+ return (
296
+ <SettingsNotice tone="warning" testId="gmail-setup-busy">
297
+ <div className="flex flex-col gap-2">
298
+ <span data-testid="gmail-setup-busy-holder">
299
+ {t("autoBusy", { holder: who }, `The dedicated browser is in use by ${who}. Setup waits until it is free, or you can take it over.`)}
300
+ </span>
301
+ <span>
302
+ <button type="button" className={btn} disabled={busy} data-testid="gmail-setup-takeover" onClick={() => setConfirming(true)}>
303
+ {t("autoTakeover", undefined, "Take over")}
304
+ </button>
305
+ </span>
306
+ </div>
307
+ {confirming && (
308
+ <ConfirmDialog
309
+ message={t(
310
+ "autoTakeoverConfirm",
311
+ { holder: who },
312
+ `Take the dedicated browser over from ${who}? Whatever it is doing there is interrupted.`,
313
+ )}
314
+ confirmLabel={t("autoTakeover", undefined, "Take over")}
315
+ onConfirm={() => {
316
+ setConfirming(false);
317
+ onTakeover();
318
+ }}
319
+ onCancel={() => setConfirming(false)}
320
+ />
321
+ )}
322
+ </SettingsNotice>
323
+ );
324
+ }
325
+
326
+ /** Hand-off: why it stopped, what Google already has, and (capture) how to add a new secret. */
327
+ function HandoffNotice({ view }: { view: SetupRunView }) {
328
+ const t = useT();
329
+ const h = view.handoff;
330
+ if (!h) return null;
331
+ const key = handoffKey(h.reason);
332
+ const projectId = view.created.projectId;
333
+ const clients = view.created.clients;
334
+ const client = clients[clients.length - 1] ?? "";
335
+ return (
336
+ <SettingsNotice tone="warning" testId="gmail-setup-handoff">
337
+ <div className="flex flex-col gap-1.5" data-reason={h.reason} data-step={h.wizardStep}>
338
+ <strong>{t("autoHandoffTitle", undefined, "Automatic setup stopped — finish by hand")}</strong>
339
+ <span data-testid="gmail-setup-handoff-reason">{t(key, undefined, ERROR_EN[key])}</span>
340
+ {h.reason === "domain_blocked" && h.domains && h.domains.length > 0 && (
341
+ <ul className="m-0 list-disc pl-5" data-testid="gmail-setup-handoff-domains">
342
+ {h.domains.map((d) => (
343
+ <li key={d}>
344
+ <code>{d}</code>
345
+ </li>
346
+ ))}
347
+ </ul>
348
+ )}
349
+ <span>
350
+ {t(
351
+ "autoHandoffAt",
352
+ { step: h.wizardStep },
353
+ `Continue at step ${h.wizardStep} of the manual setup below; the project id and owner account are already filled in.`,
354
+ )}
355
+ </span>
356
+ {(projectId || clients.length > 0) && (
357
+ <div data-testid="gmail-setup-created">
358
+ <span>{t("autoCreated", undefined, "Already created in Google Cloud:")}</span>
359
+ <ul className="m-0 list-disc pl-5">
360
+ {projectId && <li>{t("autoCreatedProject", { id: projectId }, `Project ${projectId}`)}</li>}
361
+ {clients.map((c) => (
362
+ <li key={c}>{t("autoCreatedClient", { name: c }, `OAuth client ${c}`)}</li>
363
+ ))}
364
+ </ul>
365
+ </div>
366
+ )}
367
+ {h.reason === "secret_capture_failed" && client && (
368
+ <span data-testid="gmail-setup-secret-help">
369
+ {t(
370
+ "autoSecretHelp",
371
+ { client },
372
+ `Google shows a client secret only once, when the client is created, so ${client} cannot be read back. In the console open APIs & Services → Credentials → ${client}, choose “Add secret”, download the new JSON and upload it in step 5 below.`,
373
+ )}
374
+ </span>
375
+ )}
376
+ </div>
377
+ </SettingsNotice>
378
+ );
379
+ }
380
+
381
+ /** Report a `done` / `handoff` view to the parent once per run state. */
382
+ function useReportTerminal(view: SetupRunView | null, onFinished: (v: SetupRunView) => void): void {
383
+ const latest = useRef(onFinished);
384
+ latest.current = onFinished;
385
+ const reported = useRef("");
386
+ useEffect(() => {
387
+ if (!view || (view.state !== "done" && view.state !== "handoff")) return;
388
+ const key = `${view.runId}:${view.state}`;
389
+ if (reported.current === key) return;
390
+ reported.current = key;
391
+ latest.current(view);
392
+ }, [view]);
393
+ }
394
+
395
+ function CheckpointNotice({ kind, busy, onSignedIn }: { kind: CheckpointKind; busy: boolean; onSignedIn: () => void }) {
396
+ const t = useT();
397
+ return (
398
+ <SettingsNotice tone="info" testId="gmail-setup-checkpoint">
399
+ <div className="flex flex-col gap-2" data-kind={kind}>
400
+ <span>{t(CHECKPOINT_KEY[kind], undefined, CHECKPOINT_EN[CHECKPOINT_KEY[kind]])}</span>
401
+ {kind === "sign_in" && (
402
+ <span>
403
+ <button type="button" className={btn} disabled={busy} data-testid="gmail-setup-signed-in" onClick={onSignedIn}>
404
+ {t("autoSignedIn", undefined, "I've signed in")}
405
+ </button>
406
+ </span>
407
+ )}
408
+ </div>
409
+ </SettingsNotice>
410
+ );
411
+ }
412
+
413
+ function EndNotice({ state }: { state: SetupRunState }) {
414
+ const t = useT();
415
+ if (state === "done") {
416
+ return (
417
+ <SettingsNotice tone="success" testId="gmail-setup-done">
418
+ {t("autoDone", undefined, "Automatic setup finished and the OAuth client is saved. Add your Google account below.")}
419
+ </SettingsNotice>
420
+ );
421
+ }
422
+ if (state !== "cancelled") return null;
423
+ return (
424
+ <SettingsNotice tone="info" testId="gmail-setup-cancelled">
425
+ {t("autoCancelled", undefined, "Automatic setup was cancelled. Anything it already created in Google Cloud is kept.")}
426
+ </SettingsNotice>
427
+ );
428
+ }
429
+
430
+ function LostNotice({ onDismiss }: { onDismiss: () => void }) {
431
+ const t = useT();
432
+ return (
433
+ <SettingsNotice tone="warning" testId="gmail-setup-lost">
434
+ <div className="flex flex-col gap-2">
435
+ <span>
436
+ {t(
437
+ "autoLost",
438
+ undefined,
439
+ "The setup run is no longer available, for example after a dashboard restart. Start it again; it continues from the first unfinished step.",
440
+ )}
441
+ </span>
442
+ <span>
443
+ <button type="button" className={btn} data-testid="gmail-setup-dismiss" onClick={onDismiss}>
444
+ {t("autoDismiss", undefined, "Dismiss")}
445
+ </button>
446
+ </span>
447
+ </div>
448
+ </SettingsNotice>
449
+ );
450
+ }
451
+
452
+ function RunPanel({
453
+ runId,
454
+ onAudience,
455
+ onDismiss,
456
+ onFinished,
457
+ }: {
458
+ runId: string;
459
+ onAudience: (a: Audience) => void;
460
+ onDismiss: () => void;
461
+ /** Run reached `done` or `handoff` (reported once per run state). */
462
+ onFinished: (v: SetupRunView) => void;
463
+ }) {
464
+ const t = useT();
465
+ const errorTextOf = useErrorText();
466
+ const { view, lost, refresh } = useSetupRun(runId);
467
+ const [busy, setBusy] = useState(false);
468
+ const [actionError, setActionError] = useState<string | null>(null);
469
+ const heading = useRef<HTMLHeadingElement>(null);
470
+ useEffect(() => heading.current?.focus(), []);
471
+ useReportTerminal(view, onFinished);
472
+
473
+ const act = async (path: string, init: RequestInit): Promise<boolean> => {
474
+ setActionError(null);
475
+ setBusy(true);
476
+ try {
477
+ await api(`/setup/run/${encodeURIComponent(runId)}${path}`, init);
478
+ refresh();
479
+ return true;
480
+ } catch (err) {
481
+ setActionError(errorTextOf(err));
482
+ return false;
483
+ } finally {
484
+ setBusy(false);
485
+ }
486
+ };
487
+ const post = (path: string, body: object) => act(path, { method: "POST", body: JSON.stringify(body) });
488
+
489
+ if (lost) return <LostNotice onDismiss={onDismiss} />;
490
+ if (!view) {
491
+ return (
492
+ <div role="status" className={muted} data-testid="gmail-setup-loading">
493
+ {t("autoStarting", undefined, "Starting the dedicated browser…")}
494
+ </div>
495
+ );
496
+ }
497
+
498
+ const live = isLive(view.state);
499
+ return (
500
+ <div className="flex flex-col gap-2" data-testid="gmail-setup-run" data-state={view.state} aria-busy={live || undefined}>
501
+ <h4 ref={heading} tabIndex={-1} className="focus-ring m-0 text-xs font-semibold text-[var(--text-primary)]">
502
+ {t("autoRunTitle", undefined, "Automatic setup")}
503
+ </h4>
504
+ <StepChips view={view} />
505
+ {(view.state === "starting" || view.state === "running") && (
506
+ <div role="status" className={muted} data-testid="gmail-setup-working">
507
+ {view.state === "starting"
508
+ ? t("autoStarting", undefined, "Starting the dedicated browser…")
509
+ : t("autoWorking", undefined, "Working in the dedicated browser window. You do not need to do anything yet.")}
510
+ </div>
511
+ )}
512
+ {view.state === "waiting_user" && view.checkpoint && (
513
+ <CheckpointNotice kind={view.checkpoint.kind} busy={busy} onSignedIn={() => void post("/continue", {})} />
514
+ )}
515
+ {view.state === "waiting_decision" && view.decision?.kind === "audience" && (
516
+ <AudienceDecision
517
+ decision={view.decision}
518
+ busy={busy}
519
+ onChoose={(audience) => void post("/continue", { audience }).then((ok) => ok && onAudience(audience))}
520
+ />
521
+ )}
522
+ {view.state === "waiting_decision" && view.decision?.kind === "links" && (
523
+ <LinksDecision
524
+ key={JSON.stringify(view.decision.links)}
525
+ decision={view.decision}
526
+ busy={busy}
527
+ onConfirm={(links) => void post("/continue", { links, confirmLinks: true })}
528
+ />
529
+ )}
530
+ {view.state === "busy" && <BusyNotice holder={view.busy?.holder} busy={busy} onTakeover={() => void act("/takeover", { method: "POST" })} />}
531
+ <EndNotice state={view.state} />
532
+ {view.state === "handoff" && <HandoffNotice view={view} />}
533
+ {actionError && (
534
+ <div role="alert" className={errorText} data-testid="gmail-setup-action-error">
535
+ {actionError}
536
+ </div>
537
+ )}
538
+ <div className="flex flex-wrap gap-2">
539
+ {live ? (
540
+ <button type="button" className={btn} disabled={busy} data-testid="gmail-setup-cancel" onClick={() => void act("", { method: "DELETE" })}>
541
+ {t("autoCancel", undefined, "Cancel setup")}
542
+ </button>
543
+ ) : (
544
+ <button type="button" className={btn} data-testid="gmail-setup-dismiss" onClick={onDismiss}>
545
+ {t("autoDismiss", undefined, "Dismiss")}
546
+ </button>
547
+ )}
548
+ </div>
549
+ </div>
550
+ );
551
+ }
552
+
553
+ function StartForm({
554
+ id,
555
+ defaults,
556
+ starting,
557
+ error,
558
+ onStart,
559
+ onClose,
560
+ }: {
561
+ id: string;
562
+ defaults: { projectId: string; ownerEmail: string };
563
+ starting: boolean;
564
+ error: string | null;
565
+ onStart: (req: SetupRunRequest) => void;
566
+ onClose: () => void;
567
+ }) {
568
+ const t = useT();
569
+ const [mode, setMode] = useState<"new" | "existing">(defaults.projectId ? "existing" : "new");
570
+ const [projectId, setProjectId] = useState(defaults.projectId);
571
+ const [owner, setOwner] = useState(defaults.ownerEmail);
572
+ const [touched, setTouched] = useState({ project: false, owner: false });
573
+ const ownerEmail = normalizeEmail(owner);
574
+ const ownerOk = isEmail(ownerEmail);
575
+ const cls = classifyProjectId(projectId);
576
+ // New mode: an empty id is fine (the run generates one); a typed one must be valid.
577
+ const projectOk = mode === "existing" ? cls === "ok" : projectId.trim() === "" || cls === "ok";
578
+ const ownerErr = touched.owner && !ownerOk ? t("errOwnerInvalid", undefined, "Enter a full email address, for example you@gmail.com.") : null;
579
+ const projectErr =
580
+ touched.project && !projectOk
581
+ ? cls === "looks_like_name"
582
+ ? t("errProjectLooksLikeName", undefined, "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.")
583
+ : t("errProjectInvalid", undefined, "A project id is 6–30 characters: lower-case letters, digits and hyphens, starting with a letter and not ending with a hyphen.")
584
+ : null;
585
+ const submit = () => {
586
+ setTouched({ project: true, owner: true });
587
+ if (!ownerOk || !projectOk) return;
588
+ onStart({
589
+ mode,
590
+ ownerEmail,
591
+ ...(cls === "ok" && projectId.trim() ? { projectId: normalizeProjectId(projectId) } : {}),
592
+ });
593
+ };
594
+ return (
595
+ <div id={id} role="group" aria-label={t("autoRunTitle", undefined, "Automatic setup")} className="flex flex-col gap-2" data-testid="gmail-setup-form">
596
+ <fieldset className="m-0 flex flex-wrap items-center gap-3 border-0 p-0" data-testid="gmail-setup-mode">
597
+ <legend className="sr-only">{t("projectModeLegend", undefined, "Project")}</legend>
598
+ {(["new", "existing"] as const).map((m) => (
599
+ <label key={m} className={`${muted} flex items-center gap-1`}>
600
+ <input
601
+ type="radio"
602
+ name="gmail-setup-mode"
603
+ value={m}
604
+ checked={mode === m}
605
+ onChange={() => setMode(m)}
606
+ className="focus-ring"
607
+ data-testid={`gmail-setup-mode-${m}`}
608
+ />
609
+ {m === "new" ? t("projectModeNew", undefined, "Create a new project") : t("projectModeExisting", undefined, "Use an existing project")}
610
+ </label>
611
+ ))}
612
+ </fieldset>
613
+ <div onBlur={() => setTouched((x) => ({ ...x, project: true }))}>
614
+ <TextField
615
+ label={mode === "new" ? t("autoProjectOptional", undefined, "Project id (optional)") : t("projectId", undefined, "Project id")}
616
+ hint={
617
+ mode === "new"
618
+ ? t("autoProjectNewHint", undefined, "Leave empty and the setup picks a free id like pi-dashboard-ab12cd.")
619
+ : t("autoProjectExistingHint", undefined, "The id of your existing Google Cloud project (the ID column of the console's project list), not its display name.")
620
+ }
621
+ error={projectErr}
622
+ mono
623
+ value={projectId}
624
+ onChange={setProjectId}
625
+ placeholder="my-gmail-agent"
626
+ testIds={{ control: "gmail-setup-project-id", error: "gmail-setup-project-error" }}
627
+ />
628
+ </div>
629
+ <div onBlur={() => setTouched((x) => ({ ...x, owner: true }))}>
630
+ <TextField
631
+ label={t("autoOwnerLabel", undefined, "Google account that owns the project")}
632
+ hint={t("autoOwnerHint", undefined, "You will sign in with this account in the dedicated browser window. The setup never sees its password.")}
633
+ error={ownerErr}
634
+ type="email"
635
+ autoComplete="email"
636
+ value={owner}
637
+ onChange={setOwner}
638
+ placeholder="you@gmail.com"
639
+ testIds={{ control: "gmail-setup-owner", error: "gmail-setup-owner-error" }}
640
+ />
641
+ </div>
642
+ {error && (
643
+ <div role="alert" className={errorText} data-testid="gmail-setup-start-error">
644
+ {error}
645
+ </div>
646
+ )}
647
+ <div className="flex flex-wrap gap-2">
648
+ <button type="button" className={btn} disabled={starting} data-testid="gmail-setup-start" onClick={submit}>
649
+ {t("autoStart", undefined, "Start automatic setup")}
650
+ </button>
651
+ <button type="button" className={btn} data-testid="gmail-setup-close" onClick={onClose}>
652
+ {t("autoClose", undefined, "Close")}
653
+ </button>
654
+ </div>
655
+ </div>
656
+ );
657
+ }
658
+
659
+ export interface AutoSetupSectionProps {
660
+ autoSetup?: AutoSetupState;
661
+ /** Saved setup fields, used to prefill the start form. */
662
+ setup?: { projectId?: string; ownerAccount?: string };
663
+ /** The user picked an audience (feeds the sign-in unverified-app notice, D11). */
664
+ onAudience: (a: Audience) => void;
665
+ /** Run reached `done`: the owner email prefills "Add account". */
666
+ onOwnerEmail: (email: string) => void;
667
+ /** Run reached `handoff` (view) or the hand-off was dismissed / a new run started (null). */
668
+ onHandoff: (v: SetupRunView | null) => void;
669
+ /** Reload `GET state` (the run changed what is configured). */
670
+ onRefresh: () => void;
671
+ }
672
+
673
+ function RemoteNote() {
674
+ const t = useT();
675
+ return (
676
+ <SettingsNotice tone="info" testId="gmail-setup-remote">
677
+ {t(
678
+ "autoRemoteNote",
679
+ undefined,
680
+ "Automatic setup needs a browser window on the computer that runs the dashboard, so it is offered only when you open the dashboard on that computer. Use the manual steps below.",
681
+ )}
682
+ </SettingsNotice>
683
+ );
684
+ }
685
+
686
+ /** The secondary entry button, the replace notice and (when open) the start form. */
687
+ function Entry({
688
+ autoSetup,
689
+ setup,
690
+ starting,
691
+ startError,
692
+ onStart,
693
+ }: {
694
+ autoSetup: AutoSetupState;
695
+ setup: AutoSetupSectionProps["setup"];
696
+ starting: boolean;
697
+ startError: string | null;
698
+ onStart: (req: SetupRunRequest) => void;
699
+ }) {
700
+ const t = useT();
701
+ const formId = useId();
702
+ const [formOpen, setFormOpen] = useState(false);
703
+ return (
704
+ <div className="flex flex-col gap-2" data-testid="gmail-setup-auto">
705
+ <div className="flex flex-wrap items-center gap-2">
706
+ <button
707
+ type="button"
708
+ className={btn}
709
+ data-testid="gmail-setup-entry"
710
+ aria-expanded={formOpen}
711
+ aria-controls={formOpen ? formId : undefined}
712
+ onClick={() => setFormOpen((o) => !o)}
713
+ >
714
+ {t("autoEntry", undefined, "Set up automatically")}
715
+ </button>
716
+ <span className={muted}>
717
+ {t("autoEntryHelp", undefined, "Opens a dedicated browser window on this computer and does the console steps for you. You do the sign-in and the consent clicks yourself.")}
718
+ </span>
719
+ </div>
720
+ {autoSetup.replacesClient && (
721
+ <SettingsNotice tone="warning" testId="gmail-setup-replace">
722
+ {t("autoReplaceNote", undefined, "An OAuth client is already configured, but no account uses it. Automatic setup replaces it with a new client.")}
723
+ </SettingsNotice>
724
+ )}
725
+ {formOpen && (
726
+ <StartForm
727
+ id={formId}
728
+ defaults={{ projectId: setup?.projectId ?? "", ownerEmail: setup?.ownerAccount ?? "" }}
729
+ starting={starting}
730
+ error={startError}
731
+ onStart={onStart}
732
+ onClose={() => setFormOpen(false)}
733
+ />
734
+ )}
735
+ </div>
736
+ );
737
+ }
738
+
739
+ /** Entry (per `autoSetup`) + start form + run panel. Renders nothing when unavailable and no run is shown. */
740
+ export function AutoSetupSection({ autoSetup, setup, onAudience, onOwnerEmail, onHandoff, onRefresh }: AutoSetupSectionProps): React.ReactElement | null {
741
+ const errorTextOf = useErrorText();
742
+ const [runId, setRunId] = useState<string | null>(null);
743
+ const [starting, setStarting] = useState(false);
744
+ const [startError, setStartError] = useState<string | null>(null);
745
+ const dismissed = useRef(new Set<string>());
746
+
747
+ // Re-attach to a run the server still holds (page reload mid-run).
748
+ const attachId = autoSetup?.runId;
749
+ useEffect(() => {
750
+ if (attachId && !runId && !dismissed.current.has(attachId)) setRunId(attachId);
751
+ }, [attachId, runId]);
752
+
753
+ const start = async (req: SetupRunRequest): Promise<void> => {
754
+ setStartError(null);
755
+ setStarting(true);
756
+ try {
757
+ const r = await api<{ runId: string }>("/setup/run", { method: "POST", body: JSON.stringify(req) });
758
+ onHandoff(null);
759
+ setRunId(r.runId);
760
+ } catch (err) {
761
+ setStartError(errorTextOf(err));
762
+ } finally {
763
+ setStarting(false);
764
+ }
765
+ };
766
+ const dismiss = () => {
767
+ if (runId) dismissed.current.add(runId);
768
+ setRunId(null);
769
+ onHandoff(null);
770
+ };
771
+ const finished = (v: SetupRunView) => {
772
+ if (v.state === "done" && v.ownerEmail) onOwnerEmail(v.ownerEmail);
773
+ if (v.state === "handoff") onHandoff(v);
774
+ onRefresh();
775
+ };
776
+
777
+ if (runId) {
778
+ return (
779
+ <div className="flex flex-col gap-2" data-testid="gmail-setup-auto">
780
+ <RunPanel runId={runId} onAudience={onAudience} onDismiss={dismiss} onFinished={finished} />
781
+ </div>
782
+ );
783
+ }
784
+ if (!autoSetup) return null;
785
+ if (autoSetup.available) return <Entry autoSetup={autoSetup} setup={setup} starting={starting} startError={startError} onStart={(req) => void start(req)} />;
786
+ return !autoSetup.local || autoSetup.reason === "remote_dashboard" ? <RemoteNote /> : null;
787
+ }