@blackbelt-technology/pi-dashboard-gmail-plugin 0.10.0 → 0.12.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.
@@ -1,757 +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
- SelectField,
27
- SettingsGroup,
28
- SettingsNotice,
29
- TextField,
30
- useT,
31
- useUiPrimitive,
32
- } from "@blackbelt-technology/dashboard-plugin-runtime";
33
- import type React from "react";
34
- import { useCallback, useEffect, useId, useRef, useState } from "react";
35
- import { validateClientJson } from "../shared/client-json.js";
36
- import type { AccountInfo } from "../shared/protocol.js";
37
- import { TIERS, type Tier } from "../shared/scopes.js";
38
- import { consoleLinks, ERROR_EN, errorKey, errorStep, gcloudCommands, type WizardStep } from "./wizard.js";
7
+ import { SafeLink, SettingsNotice, useT } from "@blackbelt-technology/dashboard-plugin-runtime";
39
8
 
40
- const API = "/api/plugins/gmail";
9
+ import { useEffect, useState } from "react";
41
10
 
42
- interface GmailState {
43
- client: { configured: boolean; clientId?: string; projectId?: string };
44
- accounts: AccountInfo[];
45
- }
11
+ /** The dashboard route of the Google plugin's settings page. */
12
+ const GOOGLE_SETTINGS_PATH = "/settings/plugins/google";
46
13
 
47
- type FlowState = React.ComponentProps<ReturnType<typeof useUiPrimitive<"ui:oauth-flow">>>["flow"];
48
- type FlowStatus = NonNullable<FlowState["status"]>;
14
+ type Moved = "usable" | "unavailable";
49
15
 
50
- async function api<T>(path: string, init?: RequestInit): Promise<T> {
51
- const res = await fetch(`${API}${path}`, {
52
- ...init,
53
- headers: init?.body ? { "content-type": "application/json" } : undefined,
54
- });
55
- const body = (await res.json().catch(() => ({}))) as T & { error?: string };
56
- if (!res.ok) throw Object.assign(new Error(body.error ?? `HTTP ${res.status}`), { code: body.error });
57
- return body;
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"));
58
22
  }
59
23
 
60
- // Secondary button recipe (`ui-contract.md`); `tap-target` = 44 px touch, 32 px from sm.
61
- const btn =
62
- "focus-ring tap-target rounded-md border border-[var(--border-secondary)] bg-[var(--bg-tertiary)] px-2.5 text-xs font-semibold text-[var(--text-primary)] hover:bg-[var(--bg-hover)] disabled:opacity-50";
63
- // The section's one primary action (white on the theme-invariant `--accent-solid`).
64
- const primaryBtn =
65
- "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)]";
66
- const field =
67
- "focus-ring rounded border border-[var(--border-secondary)] bg-[var(--bg-tertiary)] px-2 py-1 text-xs text-[var(--text-primary)]";
68
- const muted = "text-xs text-[var(--text-secondary)]";
69
- const errorText = "text-xs text-[var(--severity-error-fg)]";
70
- // Static strings: Tailwind cannot see interpolated class names.
71
- const pillBase = "inline-flex items-center rounded-full border px-1.5 py-px text-[11px] font-semibold";
72
- const badgeOk = `${pillBase} border-[var(--severity-success-border)] bg-[var(--severity-success-bg)] text-[var(--severity-success-fg)]`;
73
- const badgeReauth = `${pillBase} border-[var(--severity-warning-border)] bg-[var(--severity-warning-bg)] text-[var(--severity-warning-fg)]`;
24
+ export function GmailSettings() {
25
+ const t = useT();
26
+ const [moved, setMoved] = useState<Moved | null>(null);
27
+ const [error, setError] = useState<string | null>(null);
74
28
 
75
- /** Poll a flow every 500 ms until terminal. */
76
- function useFlowPoll(flowId: string | undefined, onPending: (s: FlowStatus) => void, onDone: (err: string | null) => void) {
77
- const pending = useRef(onPending);
78
- const done = useRef(onDone);
79
- pending.current = onPending;
80
- done.current = onDone;
81
29
  useEffect(() => {
82
- if (!flowId) return;
83
- let stopped = false;
84
- const timer = setInterval(() => {
85
- oauthFlowClient.status(flowId).then(
86
- (s) => {
87
- if (stopped) return;
88
- if (s.status === "pending") pending.current(s);
89
- else done.current(s.status === "complete" ? null : (s.error ?? s.status));
90
- },
91
- (err: unknown) => {
92
- if (!stopped) done.current(err instanceof Error ? err.message : String(err));
93
- },
94
- );
95
- }, 500);
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)));
96
38
  return () => {
97
- stopped = true;
98
- clearInterval(timer);
39
+ live = false;
99
40
  };
100
- }, [flowId]);
101
- }
102
-
103
- function Copyable({ value }: { value: string }) {
104
- const t = useT();
105
- const [result, setResult] = useState<"copied" | "failed" | null>(null);
106
- const seq = useRef(0);
107
- const copy = async (): Promise<void> => {
108
- const n = ++seq.current;
109
- const ok = await copyText(value);
110
- if (n !== seq.current) return; // a later click superseded this one
111
- setResult(ok ? "copied" : "failed");
112
- setTimeout(() => {
113
- if (n === seq.current) setResult(null);
114
- }, 1500);
115
- };
116
- const label =
117
- result === "copied" ? t("copied", undefined, "Copied") : result === "failed" ? t("copyFailed", undefined, "Copy failed") : t("copy", undefined, "Copy");
118
- return (
119
- <div className="flex items-center gap-2">
120
- <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>
121
- <button type="button" className={btn} onClick={() => void copy()}>
122
- <span role="status">{label}</span>
123
- </button>
124
- </div>
125
- );
126
- }
127
-
128
- function StepLink({ href, label }: { href: string; label: string }) {
129
- return (
130
- <a href={href} target="_blank" rel="noopener noreferrer" className="focus-ring text-xs text-[var(--accent-text)] underline">
131
- {label}
132
- </a>
133
- );
134
- }
135
-
136
- function WizardStepItem({
137
- n,
138
- title,
139
- current,
140
- done,
141
- children,
142
- }: {
143
- n: WizardStep;
144
- title: string;
145
- current: boolean;
146
- done: boolean;
147
- children: React.ReactNode;
148
- }) {
149
- const t = useT();
150
- return (
151
- <li
152
- className="grid grid-cols-[24px_1fr] gap-2 border-t border-[var(--border-subtle)] py-2 first:border-t-0"
153
- data-testid={`gmail-step-${n}`}
154
- aria-current={current ? "step" : undefined}
155
- data-done={done ? "true" : undefined}
156
- >
157
- <span
158
- className={`flex h-6 w-6 items-center justify-center rounded-full border text-[11px] font-bold ${
159
- current
160
- ? "border-[var(--tint-blue-border)] bg-[var(--tint-blue-bg)] text-[var(--tint-blue-fg)]"
161
- : done
162
- ? "border-[var(--severity-success-border)] bg-[var(--severity-success-bg)] text-[var(--severity-success-fg)]"
163
- : "border-[var(--border-secondary)] bg-[var(--bg-tertiary)] text-[var(--text-secondary)]"
164
- }`}
165
- >
166
- {done ? <span aria-hidden="true">✓</span> : n}
167
- </span>
168
- <div className="flex min-w-0 flex-col gap-1">
169
- <div className="text-xs font-semibold text-[var(--text-primary)]">
170
- {title.replace(/^\d+\.\s*/, "")}
171
- {done ? <span className="sr-only"> — {t("stepDone", undefined, "done")}</span> : null}
172
- </div>
173
- {children}
174
- </div>
175
- </li>
176
- );
177
- }
178
-
179
- export function SetupWizard({
180
- state,
181
- highlight,
182
- onUploaded,
183
- }: {
184
- state: GmailState;
185
- highlight: WizardStep | null;
186
- onUploaded: () => void;
187
- }) {
188
- const t = useT();
189
- const [projectId, setProjectId] = useState(state.client.projectId ?? "");
190
- const [uploadError, setUploadError] = useState<{ code: string; step: WizardStep } | null>(null);
191
- const links = consoleLinks(projectId.trim());
192
- const [cmdCreate, cmdEnable] = gcloudCommands(projectId.trim());
193
- const [focus, setFocus] = useState<WizardStep | null>(highlight);
194
- useEffect(() => setFocus(highlight ?? uploadError?.step ?? null), [highlight, uploadError]);
195
-
196
- const upload = async (file: File) => {
197
- setUploadError(null);
198
- const textContent = await file.text();
199
- const local = validateClientJson(textContent);
200
- if (!local.ok) {
201
- setUploadError({ code: local.error.code, step: local.error.step });
202
- return;
203
- }
204
- try {
205
- await api("/client", { method: "PUT", body: JSON.stringify({ json: JSON.parse(textContent) }) });
206
- if (local.client.projectId && !projectId) setProjectId(local.client.projectId);
207
- onUploaded();
208
- } catch (err) {
209
- const code = (err as { code?: string }).code ?? "upload_failed";
210
- setUploadError({ code, step: errorStep(code) ?? 5 });
211
- }
212
- };
213
-
214
- // Current step: the highlighted one, else the next thing the user has to do.
215
- const current: WizardStep | null =
216
- focus ?? (!state.client.configured ? 1 : state.accounts.length === 0 ? 6 : null);
217
- const isDone = (n: WizardStep) =>
218
- n !== current && (state.client.configured ? n <= 5 || state.accounts.length > 0 : current !== null && n < current);
219
- const uploadMsg: Record<string, string> = {
220
- not_json: t("errNotJson", undefined, "That file is not valid JSON. Upload the client_secret_*.json you downloaded (step 5)."),
221
- web_client: t("errWebClient", undefined, "This is a Web application client. Create a Desktop app client instead (step 4)."),
222
- not_installed: t("errNotInstalled", undefined, "No Desktop (`installed`) client in this file. Create a Desktop app client (step 4)."),
223
- bad_client_id: t("errBadClientId", undefined, "The client id does not end in .apps.googleusercontent.com (step 4)."),
224
- client_in_use: t(
225
- "errClientInUse",
226
- undefined,
227
- "Accounts are connected with the current client. Revoke them first, then upload a different client.",
228
- ),
229
- missing_secret: t("errMissingSecret", undefined, "The file has no client secret. Download it again from the client page (step 5)."),
230
- };
231
-
232
- return (
233
- <ol className="m-0 flex list-none flex-col p-0" data-testid="gmail-wizard">
234
- <WizardStepItem n={1} title={t("step1", undefined, "1. Google Cloud project + Gmail API")} current={current === 1} done={isDone(1)}>
235
- <TextField
236
- label={t("projectId", undefined, "Project id")}
237
- hint={null}
238
- mono
239
- value={projectId}
240
- onChange={setProjectId}
241
- placeholder="my-gmail-agent"
242
- testIds={{ control: "gmail-project-id" }}
243
- />
244
- <div className={muted}>{t("withoutGcloud", undefined, "Without gcloud:")}</div>
245
- <div className="flex gap-3">
246
- <StepLink href={links.projectCreate} label={t("createProject", undefined, "Create project")} />
247
- <StepLink href={links.gmailApi} label={t("enableGmail", undefined, "Enable the Gmail API")} />
248
- </div>
249
- <div className={muted}>{t("withGcloud", undefined, "With gcloud (run it yourself):")}</div>
250
- <Copyable value={cmdCreate as string} />
251
- <Copyable value={cmdEnable as string} />
252
- </WizardStepItem>
253
- <WizardStepItem n={2} title={t("step2", undefined, "2. Branding")} current={current === 2} done={isDone(2)}>
254
- <StepLink href={links.branding} label={t("openBranding", undefined, "Open Branding")} />
255
- <div className={muted}>{t("fallback2", undefined, "If the link moved: APIs & Services → OAuth consent screen.")}</div>
256
- </WizardStepItem>
257
- <WizardStepItem n={3} title={t("step3", undefined, "3. Audience + test users")} current={current === 3} done={isDone(3)}>
258
- <StepLink href={links.audience} label={t("openAudience", undefined, "Open Audience")} />
259
- <div className={muted}>
260
- {t(
261
- "audienceHelp",
262
- undefined,
263
- "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.",
264
- )}
265
- </div>
266
- <div className={muted}>
267
- {t(
268
- "audienceErrors",
269
- undefined,
270
- "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.",
271
- )}
272
- </div>
273
- </WizardStepItem>
274
- <WizardStepItem n={4} title={t("step4", undefined, "4. Desktop OAuth client")} current={current === 4} done={isDone(4)}>
275
- <StepLink href={links.clientCreate} label={t("openClients", undefined, "Create client")} />
276
- <div className={muted}>
277
- {t("clientHelp", undefined, "Application type: Desktop app. Download the JSON. If the link moved: APIs & Services → Credentials.")}
278
- </div>
279
- </WizardStepItem>
280
- <WizardStepItem n={5} title={t("step5", undefined, "5. Upload client_secret_*.json")} current={current === 5} done={isDone(5)}>
281
- <FieldShell
282
- label={t("uploadLabel", undefined, "Upload the OAuth client JSON")}
283
- hint={null}
284
- stacked
285
- error={uploadError ? (uploadMsg[uploadError.code] ?? uploadError.code) : null}
286
- testIds={{ error: "gmail-upload-error" }}
287
- errorAttrs={uploadError ? { "data-step": String(uploadError.step) } : undefined}
288
- control={({ id, describedBy, invalid }) => (
289
- <input
290
- id={id}
291
- type="file"
292
- className="focus-ring text-xs text-[var(--text-primary)]"
293
- accept="application/json,.json"
294
- data-testid="gmail-client-upload"
295
- aria-describedby={describedBy}
296
- aria-invalid={invalid || undefined}
297
- onChange={(e) => {
298
- const f = e.target.files?.[0];
299
- if (f) void upload(f);
300
- }}
301
- />
302
- )}
303
- />
304
- {state.client.configured && (
305
- <div className={muted} data-testid="gmail-client-ok">
306
- ✓ {state.client.clientId}
307
- </div>
308
- )}
309
- </WizardStepItem>
310
- <WizardStepItem n={6} title={t("step6", undefined, "6. Test sign-in")} current={current === 6} done={isDone(6)}>
311
- <div className={muted}>{t("step6Help", undefined, "Add your first account below — that is the test sign-in.")}</div>
312
- </WizardStepItem>
313
- </ol>
314
- );
315
- }
316
-
317
- const TIER_LABEL: Record<Tier, string> = { readonly: "readonly", draft: "draft", send: "send" };
318
- const TIER_DESC: Record<Tier, [key: string, en: string]> = {
319
- readonly: ["tierReadonly", "read mail"],
320
- draft: ["tierDraft", "read + create drafts"],
321
- send: ["tierSend", "read, draft, send, reply, labels, archive, trash"],
322
- };
323
-
324
- /** Each level's own description, as a select option list. */
325
- function useTierOptions(): { value: string; label: string }[] {
326
- const t = useT();
327
- return TIERS.map((tier) => ({ value: tier, label: `${TIER_LABEL[tier]} — ${t(TIER_DESC[tier][0], undefined, TIER_DESC[tier][1])}` }));
328
- }
329
-
330
- /** Codes the user can report from Google's own error page (closed list, design D1). */
331
- const REPORT_CODES = ["org_internal", "access_denied", "admin_policy_enforced", "other"] as const;
332
-
333
- function AccountRow({
334
- acct,
335
- onChanged,
336
- onFlow,
337
- onRevoked,
338
- }: {
339
- acct: AccountInfo;
340
- onChanged: () => void;
341
- onFlow: (flowId: string) => void;
342
- onRevoked: (email: string, remoteRevoked: boolean) => void;
343
- }) {
344
- const t = useT();
345
- const ConfirmDialog = useUiPrimitive("ui:confirm-dialog");
346
- const tierOptions = useTierOptions();
347
- const [alias, setAlias] = useState(acct.alias ?? "");
348
- const [msg, setMsg] = useState<string | null>(null);
349
- const [aliasMsg, setAliasMsg] = useState<{ ok: boolean; text: string } | null>(null);
350
- const [confirming, setConfirming] = useState(false);
351
- const run = async (fn: () => Promise<void>) => {
352
- setMsg(null);
353
- try {
354
- await fn();
355
- } catch (err) {
356
- setMsg((err as { code?: string }).code ?? (err as Error).message);
357
- }
358
- };
359
- const setLevel = (tier: Tier) =>
360
- run(async () => {
361
- const r = await api<{ applied?: boolean; flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/level`, {
362
- method: "POST",
363
- body: JSON.stringify({ tier }),
364
- });
365
- if (r.flowId) onFlow(r.flowId);
366
- else onChanged();
367
- });
368
- const saveAlias = async () => {
369
- try {
370
- await api(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "PATCH", body: JSON.stringify({ alias: alias || null }) });
371
- setAliasMsg({ ok: true, text: t("aliasSaved", undefined, "Saved") });
372
- onChanged();
373
- } catch (err) {
374
- const code = (err as { code?: string }).code ?? (err as Error).message;
375
- const text =
376
- code === "alias_taken"
377
- ? t("errAliasTaken", undefined, "That alias is already used by another account.")
378
- : code === "invalid_alias"
379
- ? t("errInvalidAlias", undefined, "Aliases are 1–40 letters, digits, '.', '_' or '-'.")
380
- : code;
381
- setAliasMsg({ ok: false, text });
382
- }
383
- };
384
- const revoke = () =>
385
- run(async () => {
386
- const r = await api<{ remoteRevoked: boolean }>(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "DELETE" });
387
- onRevoked(acct.email, r.remoteRevoked);
388
- onChanged();
389
- });
390
- return (
391
- <li
392
- className="flex flex-col gap-2 rounded-md border border-[var(--border-secondary)] p-2"
393
- data-testid="gmail-account-row"
394
- data-email={acct.email}
395
- >
396
- <div className="flex flex-wrap items-center gap-2">
397
- <span className="text-sm font-semibold text-[var(--text-primary)]" data-testid="gmail-account-email">
398
- {acct.email}
399
- </span>
400
- {acct.status === "ok" ? (
401
- <span className={badgeOk} data-testid="gmail-account-status" data-status="ok">
402
- {t("statusOk", undefined, "Connected")}
403
- </span>
404
- ) : (
405
- <span className={badgeReauth} data-testid="gmail-account-status" data-status="reauth_required">
406
- {t("statusReauth", undefined, "Re-auth needed")}
407
- </span>
408
- )}
409
- {acct.testingHint && (
410
- <span className={muted} title={t("testingHint", undefined, "Testing-mode app: Google expires this grant after 7 days.")}>
411
- {t("testingBadge", undefined, "testing: 7-day")}
412
- </span>
413
- )}
414
- <input
415
- aria-label={t("aliasFor", { email: acct.email }, `Alias for ${acct.email}`)}
416
- data-testid="gmail-account-alias"
417
- className={`${field} w-28`}
418
- value={alias}
419
- placeholder={t("aliasPlaceholder", undefined, "alias")}
420
- onChange={(e) => {
421
- setAlias(e.target.value);
422
- setAliasMsg(null);
423
- }}
424
- onBlur={() => alias !== (acct.alias ?? "") && void saveAlias()}
425
- />
426
- {aliasMsg && (
427
- <span
428
- role={aliasMsg.ok ? "status" : "alert"}
429
- className={aliasMsg.ok ? muted : errorText}
430
- data-testid="gmail-alias-feedback"
431
- >
432
- {aliasMsg.text}
433
- </span>
434
- )}
435
- </div>
436
- <div className="flex flex-wrap items-center gap-2">
437
- <label className={muted}>
438
- {t("level", undefined, "Level")}{" "}
439
- <select
440
- aria-label={t("levelFor", { email: acct.email }, `Level for ${acct.email}`)}
441
- data-testid="gmail-account-level"
442
- value={acct.tier}
443
- onChange={(e) => void setLevel(e.target.value as Tier)}
444
- className={field}
445
- >
446
- {tierOptions.map((o) => (
447
- <option key={o.value} value={o.value}>
448
- {o.label}
449
- </option>
450
- ))}
451
- </select>
452
- </label>
453
- <button
454
- type="button"
455
- className={btn}
456
- data-testid="gmail-account-reauth"
457
- aria-label={t("reauthFor", { email: acct.email }, `Re-authenticate ${acct.email}`)}
458
- onClick={() =>
459
- void run(async () => {
460
- // Force a fresh consent at the current level (status reset on persist).
461
- const r = await api<{ flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/reauth`, { method: "POST" });
462
- if (r.flowId) onFlow(r.flowId);
463
- })
464
- }
465
- >
466
- {t("reauth", undefined, "Re-authenticate")}
467
- </button>
468
- <button
469
- type="button"
470
- className={btn}
471
- data-testid="gmail-account-revoke"
472
- aria-label={t("revokeFor", { email: acct.email }, `Revoke ${acct.email}`)}
473
- onClick={() => setConfirming(true)}
474
- >
475
- {t("revoke", undefined, "Revoke")}
476
- </button>
477
- {msg && (
478
- <span role="alert" className={errorText}>
479
- {msg}
480
- </span>
481
- )}
482
- </div>
483
- {confirming && (
484
- <ConfirmDialog
485
- message={t(
486
- "revokeConfirm",
487
- { email: acct.email },
488
- `Revoke ${acct.email}? The dashboard forgets the account and asks Google to revoke its access.`,
489
- )}
490
- confirmLabel={t("revoke", undefined, "Revoke")}
491
- onConfirm={() => {
492
- setConfirming(false);
493
- void revoke();
494
- }}
495
- onCancel={() => setConfirming(false)}
496
- />
497
- )}
498
- </li>
499
- );
500
- }
501
-
502
- function AddAccount({
503
- configured,
504
- newTier,
505
- onTier,
506
- onAdd,
507
- }: {
508
- configured: boolean;
509
- newTier: Tier;
510
- onTier: (t: Tier) => void;
511
- onAdd: () => void;
512
- }) {
513
- const t = useT();
514
- const addReasonId = useId();
515
- const tierOptions = useTierOptions();
516
- return (
517
- <div className="flex flex-col gap-2">
518
- <SelectField
519
- label={t("newLevel", undefined, "Level for the new account")}
520
- hint={null}
521
- value={newTier}
522
- options={tierOptions}
523
- onChange={(v) => onTier(v as Tier)}
524
- testIds={{ control: "gmail-new-level" }}
525
- />
526
- <div className="flex flex-wrap items-center gap-2">
527
- <button
528
- type="button"
529
- className={primaryBtn}
530
- data-testid="gmail-add-account"
531
- disabled={!configured}
532
- aria-describedby={configured ? undefined : addReasonId}
533
- onClick={onAdd}
534
- >
535
- {t("addAccount", undefined, "Add account")}
536
- </button>
537
- {!configured && (
538
- <span id={addReasonId} className={muted} data-testid="gmail-add-account-reason">
539
- {t("addAccountDisabled", undefined, "Upload the OAuth client JSON (step 5 above) to enable this.")}
540
- </span>
541
- )}
542
- </div>
543
- <p className={`${muted} m-0`} data-testid="gmail-cross-org-hint">
544
- {t(
545
- "crossOrgHint",
546
- undefined,
547
- "Accounts outside the project's Workspace organization need an External audience, with each account added as a test user (step 3).",
548
- )}
549
- </p>
550
- </div>
551
- );
552
- }
553
-
554
- /** Failed sign-in as a severity notice; the sentence names the wizard step that fixes it. */
555
- function FlowErrorNotice({ code, step, errKey, clientId }: { code: string; step: WizardStep | null; errKey: string; clientId: string }) {
556
- const t = useT();
557
- return (
558
- <SettingsNotice tone="error">
559
- <div data-testid="gmail-flow-error" data-step={step ?? ""}>
560
- {t(errKey, { clientId }, ERROR_EN[errKey])}{" "}
561
- <span className="text-[var(--severity-error-fg)]" data-testid="gmail-flow-error-code">
562
- ({code})
563
- </span>
564
- </div>
565
- </SettingsNotice>
566
- );
567
- }
568
-
569
- export function GmailSettings() {
570
- const t = useT();
571
- const OAuthFlow = useUiPrimitive("ui:oauth-flow");
572
- const [state, setState] = useState<GmailState | null>(null);
573
- const [loadError, setLoadError] = useState<string | null>(null);
574
- const [flow, setFlow] = useState<FlowState | null>(null);
575
- const [flowError, setFlowError] = useState<string | null>(null);
576
- const [lastRevoke, setLastRevoke] = useState<string | null>(null);
577
- const [newTier, setNewTier] = useState<Tier>("readonly");
578
- // Latch (design D1): once the user reports a Google-page code, no late poll
579
- // result may overwrite it or re-mount the flow view. Reset on a new flow.
580
- const reportedRef = useRef<string | null>(null);
581
-
582
- const refresh = useCallback(async () => {
583
- try {
584
- setState(await api<GmailState>("/state"));
585
- setLoadError(null);
586
- } catch (err) {
587
- setLoadError((err as Error).message);
588
- }
589
41
  }, []);
590
- useEffect(() => {
591
- void refresh();
592
- }, [refresh]);
593
-
594
- const startFlow = async (flowId: string) => {
595
- reportedRef.current = null;
596
- setFlowError(null);
597
- try {
598
- setFlow({ phase: "waiting", status: await oauthFlowClient.status(flowId) });
599
- } catch (err) {
600
- setFlow(null);
601
- setFlowError(err instanceof Error ? err.message : String(err));
602
- }
603
- };
604
- useFlowPoll(
605
- flow?.status?.flowId,
606
- (status) => {
607
- if (reportedRef.current) return;
608
- setFlow({ phase: "waiting", status });
609
- },
610
- (err) => {
611
- if (reportedRef.current) return;
612
- setFlow(null);
613
- setFlowError(err);
614
- void refresh();
615
- },
616
- );
617
42
 
618
- /** Order is load-bearing (design D1): latch, then clear, then cancel. */
619
- const report = (code: string) => {
620
- const flowId = flow?.status?.flowId;
621
- reportedRef.current = code;
622
- setFlow(null);
623
- setFlowError(code);
624
- if (flowId) void oauthFlowClient.cancel(flowId).catch(() => {});
625
- };
626
-
627
- const addAccount = async () => {
628
- reportedRef.current = null;
629
- setFlowError(null);
630
- setFlow({ phase: "starting" });
631
- try {
632
- const r = await api<{ flowId: string }>("/accounts", { method: "POST", body: JSON.stringify({ tier: newTier }) });
633
- await startFlow(r.flowId);
634
- } catch (err) {
635
- setFlow(null);
636
- setFlowError((err as { code?: string }).code ?? (err as Error).message);
637
- }
638
- };
639
-
640
- if (loadError) {
641
- return (
642
- <SettingsNotice tone="error" testId="gmail-load-error">
643
- {loadError}
644
- </SettingsNotice>
645
- );
646
- }
647
- if (!state)
648
- return (
649
- <div data-testid="gmail-loading" className={muted}>
650
- {t("loading", undefined, "Loading…")}
651
- </div>
652
- );
653
-
654
- const step = errorStep(flowError);
655
- const errKey = errorKey(flowError);
656
- const { client } = state;
657
- const summary = !client.configured
658
- ? t("summaryNotConfigured", undefined, "not configured")
659
- : client.projectId
660
- ? t("summaryProject", { projectId: client.projectId }, `✓ project ${client.projectId}`)
661
- : t("summaryClient", { clientId: client.clientId ?? "" }, `✓ ${client.clientId ?? ""}`);
662
43
  return (
663
44
  <section className="flex flex-col gap-3" data-testid="gmail-settings" aria-labelledby="gmail-settings-title">
664
45
  <h3 id="gmail-settings-title" className="m-0 text-sm font-semibold text-[var(--text-primary)]">
665
46
  {t("title", undefined, "Gmail")}
666
47
  </h3>
667
- <SettingsGroup
668
- title={t("setup", undefined, "Google Cloud setup")}
669
- meta={summary}
670
- summaryTestId="gmail-setup-summary"
671
- defaultOpen={!client.configured || state.accounts.length === 0 || step !== null}
672
- >
673
- <SetupWizard state={state} highlight={step} onUploaded={() => void refresh()} />
674
- </SettingsGroup>
675
-
676
- <div className="flex flex-col gap-2" data-testid="gmail-accounts">
677
- <div className="text-sm font-semibold text-[var(--text-primary)]">{t("accounts", undefined, "Accounts")}</div>
678
- <p className={`${muted} m-0`} data-testid="gmail-level-help">
679
- {t(
680
- "levelHelp",
681
- undefined,
682
- "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.",
683
- )}
684
- </p>
685
- {state.accounts.length === 0 && <div className={muted}>{t("noAccounts", undefined, "No accounts connected.")}</div>}
686
- <ul className="m-0 flex list-none flex-col gap-2 p-0">
687
- {state.accounts.map((a) => (
688
- <AccountRow
689
- key={a.sub}
690
- acct={a}
691
- onChanged={() => void refresh()}
692
- onFlow={(id) => void startFlow(id)}
693
- onRevoked={(email, remote) =>
694
- setLastRevoke(
695
- remote
696
- ? t("revokedOk", { email }, `${email} removed and access revoked at Google.`)
697
- : t(
698
- "revokeManual",
699
- { email },
700
- `${email} removed locally, but Google could not be reached. Revoke access at myaccount.google.com/permissions.`,
701
- ),
702
- )
703
- }
704
- />
705
- ))}
706
- </ul>
707
- {flow ? (
708
- <div className="flex flex-col gap-2">
709
- <p className={`${muted} m-0`} data-testid="gmail-consent-hint">
710
- {t(
711
- "consentHint",
712
- undefined,
713
- "On Google's consent screen tick every permission (Select all). The Gmail permission may start unticked.",
714
- )}
715
- </p>
716
- <OAuthFlow
717
- flow={flow}
718
- onSendInput={(id, value) => oauthFlowClient.input(id, value)}
719
- onCancel={(id) => {
720
- void oauthFlowClient.cancel(id);
721
- }}
722
- />
723
- {flow.phase === "waiting" && (
724
- <details data-testid="gmail-google-error">
725
- <summary className="focus-ring cursor-pointer text-xs text-[var(--text-primary)]">
726
- {t("googleErrorSummary", undefined, "Google showed an error instead of returning here?")}
727
- </summary>
728
- <div className={muted}>{t("googleErrorHelp", undefined, "Pick the error code Google displayed:")}</div>
729
- <div className="mt-1 flex flex-wrap gap-2">
730
- {REPORT_CODES.map((code) => (
731
- <button
732
- key={code}
733
- type="button"
734
- className={btn}
735
- data-testid={`gmail-report-${code}`}
736
- onClick={() => report(code)}
737
- >
738
- {code === "other" ? t("reportOther", undefined, "Something else") : code}
739
- </button>
740
- ))}
741
- </div>
742
- </details>
743
- )}
744
- </div>
745
- ) : (
746
- <AddAccount configured={client.configured} newTier={newTier} onTier={setNewTier} onAdd={() => void addAccount()} />
747
- )}
748
- {flowError && <FlowErrorNotice code={flowError} step={step} errKey={errKey} clientId={client.clientId ?? ""} />}
749
- {lastRevoke && (
750
- <div role="status" className={muted} data-testid="gmail-revoke-result">
751
- {lastRevoke}
752
- </div>
753
- )}
754
- </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
+ )}
755
71
  </section>
756
72
  );
757
73
  }