@startsimpli/integrations 0.2.133 → 0.2.135

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.
Files changed (31) hide show
  1. package/package.json +1 -1
  2. package/src/__tests__/corpus-planning.test.tsx +13 -3
  3. package/src/__tests__/corpus-tracker.test.tsx +53 -69
  4. package/src/__tests__/focus-standings.test.tsx +3 -1
  5. package/src/__tests__/home-brief.test.tsx +84 -0
  6. package/src/__tests__/project-surfaces.test.tsx +1 -1
  7. package/src/__tests__/work-groups.test.ts +181 -0
  8. package/src/components/index.ts +1 -0
  9. package/src/components/pages/ConnectionsPage.tsx +7 -1402
  10. package/src/components/pages/PlanningPage.tsx +129 -67
  11. package/src/components/pages/TrackerPage.tsx +174 -149
  12. package/src/components/pages/connections/CapabilityPicker.tsx +75 -0
  13. package/src/components/pages/connections/CatalogCard.tsx +300 -0
  14. package/src/components/pages/connections/ConnectionCard.tsx +489 -0
  15. package/src/components/pages/connections/ConnectionForms.tsx +215 -0
  16. package/src/components/pages/connections/MemberPolicyToggle.tsx +106 -0
  17. package/src/components/pages/connections/bound-api.ts +175 -0
  18. package/src/components/pages/connections/copy.ts +74 -0
  19. package/src/components/pages/home/BriefCard.tsx +84 -0
  20. package/src/components/pages/home/CompactItemRow.tsx +61 -0
  21. package/src/components/pages/home/DueAcrossProjects.tsx +74 -0
  22. package/src/components/pages/home/HomeBriefPage.tsx +112 -0
  23. package/src/components/pages/home/RecentNotes.tsx +69 -0
  24. package/src/components/pages/home/index.ts +10 -0
  25. package/src/components/pages/home/useProjectNames.ts +23 -0
  26. package/src/components/pages/work-items.tsx +15 -9
  27. package/src/corpus/due-groups.ts +81 -0
  28. package/src/corpus/focus-overview.ts +54 -0
  29. package/src/corpus/index.ts +10 -0
  30. package/src/corpus/note-actions.ts +44 -0
  31. package/src/corpus/tracker-groups.ts +84 -0
@@ -34,271 +34,15 @@
34
34
  */
35
35
  import * as React from 'react';
36
36
 
37
- import {
38
- CredentialSchemaForm,
39
- isSecret,
40
- missingRequired,
41
- patternWarnings,
42
- schemaFields,
43
- } from '../CredentialSchemaForm';
44
- import type {
45
- Connection,
46
- ConnectionChoice,
47
- ConnectionChoicePage,
48
- ConnectionInvokeResult,
49
- ConnectionPermissions,
50
- ConnectionRun,
51
- ConnectionTarget,
52
- ConnectorAction,
53
- ConnectorCatalogEntry,
54
- ConnectorFieldSpec,
55
- ConnectionsApi,
56
- MemberConnectionRow,
57
- MemberConnectionsApi,
58
- } from './types';
37
+ import type { Connection, ConnectionPermissions, ConnectorCatalogEntry } from './types';
59
38
  import { MemberConnectionRoster } from './MemberConnectionRoster';
60
- import { TaskTrackerSettings } from './task-tracker/TaskTrackerSettings';
61
39
  import { connectableEntries } from './connectable-entries';
62
- import { isTaskTracker } from '../../task-tracker/sync-config';
63
-
64
- type ClassNames = Partial<Record<
65
- 'root' | 'section' | 'heading' | 'card' | 'button' | 'muted' | 'error', string
66
- >>;
67
-
68
- /**
69
- * TWO SURFACES, ONE COMPOSER (bd startsim-768w.22.25.6).
70
- *
71
- * A discriminated union rather than an optional slug, because the two modes do
72
- * not merely differ in their arguments — `personal` has no slug ANYWHERE, which
73
- * is the member surface's whole security property (see `MemberConnectionsApi`).
74
- * Making `foundrySlug` optional would let a personal mount pass one and read as
75
- * though it meant something.
76
- */
77
- export type ConnectionsPageProps =
78
- | {
79
- mode?: 'foundry';
80
- api: ConnectionsApi;
81
- foundrySlug: string;
82
- classNames?: ClassNames;
83
- }
84
- | {
85
- mode: 'personal';
86
- api: MemberConnectionsApi;
87
- /** There is no slug on this surface. The token's audience names the foundry. */
88
- foundrySlug?: never;
89
- classNames?: ClassNames;
90
- };
91
-
92
- /**
93
- * The api as the components below use it: SLUGLESS, because the slug is a
94
- * property of the mount and not of any control on the page.
95
- *
96
- * The foundry-level verbs are optional, and that is what gates the UI. A control
97
- * renders when the verb behind it exists, so personal mode cannot render a
98
- * button whose handler would be `undefined` — the type checker, not a
99
- * `mode === 'personal'` sprinkled through nine call sites, is what keeps the
100
- * two surfaces honest.
101
- */
102
- interface BoundApi {
103
- connectorCatalog(): Promise<{ results: ConnectorCatalogEntry[] }>;
104
- connections(): Promise<{ results: Connection[]; permissions: ConnectionPermissions }>;
105
- connect(input: {
106
- connector_key: string;
107
- name?: string;
108
- credentials?: Record<string, unknown>;
109
- config?: Record<string, unknown>;
110
- capabilities_enabled?: string[];
111
- }): Promise<Connection>;
112
- checkConnection(id: string): Promise<{ ok: boolean; account_label: string; detail: string }>;
113
- rotateCredential(id: string, credentials: Record<string, unknown>): Promise<Connection>;
114
- disconnect(id: string): Promise<void>;
115
- updateConnection?(id: string, input: {
116
- name?: string; capabilities_enabled?: string[]; config?: Record<string, unknown>;
117
- }): Promise<Connection>;
118
- /**
119
- * SETTINGS ALONE, and separate from `updateConnection` on purpose
120
- * (bd startsim-sfms2).
121
- *
122
- * Both surfaces have it; only the control plane has `updateConnection`. A
123
- * personal connection's config is the MEMBER's privacy boundary — which of
124
- * their own files this platform reads — while its name and what it may DO are
125
- * the foundry's. One verb carrying all three would have made the Settings
126
- * control and the capability Save appear together, so opening the first would
127
- * have opened the second by accident.
128
- */
129
- updateConnectionConfig?(
130
- id: string, config: Record<string, unknown>,
131
- ): Promise<Connection>;
132
- connectionChoices?(id: string, params?: { kind?: string; cursor?: string }):
133
- Promise<ConnectionChoicePage>;
134
- /** Task-tracker connections: sync now (bd startsim-el0zf). */
135
- syncConnectionNow?(id: string): Promise<{ queued: boolean }>;
136
- wireTarget?(id: string, input: {
137
- choice_id: string; name?: string; options?: Record<string, unknown>;
138
- }): Promise<ConnectionTarget>;
139
- confirmTarget?(id: string, destinationId: string): Promise<ConnectionTarget>;
140
- connectionActions?(id: string): Promise<{ results: ConnectorAction[] }>;
141
- invokeConnectionAction?(id: string, action: string, input: {
142
- destination_id: string; record_type?: string; records?: unknown[];
143
- }): Promise<ConnectionInvokeResult>;
144
- /**
145
- * RECENT ACTIVITY on both legs (bd startsim-ei8gm.2). Required on both
146
- * injected interfaces and, until this bead, called by nothing — so the reason
147
- * a run failed reached the payload and never a pixel.
148
- *
149
- * Optional HERE for the reason every other verb on this type is: an app
150
- * pinned to an older `@startsimpli/api` keeps type-checking, and the card
151
- * renders no control rather than a button whose handler is `undefined`.
152
- */
153
- connectionRuns?(id: string): Promise<{ results: ConnectionRun[] }>;
154
- /** Per-member governance (bd startsim-768w.22.25.8). Foundry mode only, and
155
- absent on an api that predates the endpoints — see `ConnectionsApi`. */
156
- /** The OAuth hand-off (bd startsim-768w.22.25.14/.23). Optional: an app on an
157
- older client keeps type-checking, and the card renders the connector as
158
- not-connectable-here rather than offering a button that cannot fire. */
159
- startOAuth?(input: {
160
- connector_key: string;
161
- name?: string;
162
- config?: Record<string, unknown>;
163
- capabilities_enabled?: string[];
164
- return_to?: string;
165
- }): Promise<{ authorization_url: string; state: string; redirect_uri: string }>;
166
- setMemberConnectorPolicy?(connectorKey: string, allowed: boolean): Promise<unknown>;
167
- memberConnections?(): Promise<{
168
- results: MemberConnectionRow[]; permissions: ConnectionPermissions;
169
- }>;
170
- disconnectMemberConnection?(id: string): Promise<void>;
171
- }
172
-
173
- function bindApi(props: ConnectionsPageProps): BoundApi {
174
- if (props.mode === 'personal') {
175
- // Already slugless. Passed through rather than wrapped, so nothing here can
176
- // grow a slug argument by accident.
177
- return props.api;
178
- }
179
- const { api, foundrySlug: slug } = props;
180
- // Bound only when the injected client HAS them, so `verb in api` stays the
181
- // test the components run — a wrapper that always exists and throws inside
182
- // would render the control and fail on click.
183
- const memberPolicy = api.setMemberConnectorPolicy
184
- ? { setMemberConnectorPolicy: (key: string, allowed: boolean) =>
185
- api.setMemberConnectorPolicy!(slug, key, allowed) }
186
- : {};
187
- const oauth = api.startOAuth
188
- ? { startOAuth: (input: Parameters<NonNullable<BoundApi['startOAuth']>>[0]) =>
189
- api.startOAuth!(slug, input) }
190
- : {};
191
- const roster = api.memberConnections
192
- ? { memberConnections: () => api.memberConnections!(slug) }
193
- : {};
194
- const cutMember = api.disconnectMemberConnection
195
- ? { disconnectMemberConnection: (id: string) =>
196
- api.disconnectMemberConnection!(slug, id) }
197
- : {};
198
- // Bound only when the injected client HAS it, even though `ConnectionsApi`
199
- // declares it required: apps consume `@startsimpli/*` as PUBLISHED packages,
200
- // so a runtime object that predates the verb is a real state the TYPE cannot
201
- // see (bd startsim-ei8gm.2). Same rule as the four above — a wrapper that
202
- // always exists and throws inside would render the control and fail on click.
203
- const runs = api.connectionRuns
204
- ? { connectionRuns: (id: string) => api.connectionRuns(slug, id) }
205
- : {};
206
- return {
207
- ...runs,
208
- ...memberPolicy,
209
- ...oauth,
210
- ...roster,
211
- ...cutMember,
212
- connectorCatalog: () => api.connectorCatalog(slug),
213
- connections: () => api.connections(slug),
214
- connect: (input) => api.connect(slug, input),
215
- checkConnection: (id) => api.checkConnection(slug, id),
216
- rotateCredential: (id, credentials) => api.rotateCredential(slug, id, credentials),
217
- disconnect: (id) => api.disconnect(slug, id),
218
- updateConnection: (id, input) => api.updateConnection(slug, id, input),
219
- // The control plane reaches settings through the same PATCH it reaches
220
- // everything else with; the narrow verb is a property of the MEMBER router,
221
- // not of the form. Both modes therefore satisfy the same bound signature and
222
- // the settings form never learns which surface it is on.
223
- updateConnectionConfig: (id, config) =>
224
- api.updateConnection(slug, id, { config }),
225
- connectionChoices: (id, params) => api.connectionChoices(slug, id, params),
226
- wireTarget: (id, input) => api.wireTarget(slug, id, input),
227
- confirmTarget: (id, destinationId) => api.confirmTarget(slug, id, destinationId),
228
- connectionActions: (id) => api.connectionActions(slug, id),
229
- invokeConnectionAction: (id, action, input) =>
230
- api.invokeConnectionAction(slug, id, action, input),
231
- };
232
- }
233
-
234
- const DEFAULTS = {
235
- root: 'space-y-8',
236
- section: 'space-y-3',
237
- heading: 'text-lg font-semibold text-gray-900',
238
- card: 'rounded-lg border border-gray-200 p-4',
239
- button: 'rounded-md bg-gray-900 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50',
240
- muted: 'text-sm text-gray-500',
241
- error: 'text-sm text-red-600',
242
- };
243
-
244
- /**
245
- * WHICH LEG A RUN BELONGS TO, in a reader's words (bd startsim-ei8gm.2).
246
- *
247
- * The card merges three tables — `SourceRun`, `DestinationRun` and
248
- * `DestinationWebhookEvent` — into one list, and "failed" means a different
249
- * thing and needs a different action on each. Data with a fall-through to the
250
- * raw key, the same rule `CAPABILITY_COPY` below states: a `kind` this bundle
251
- * has never heard of renders as itself rather than vanishing from the list.
252
- */
253
- const RUN_KIND_COPY: Record<string, string> = {
254
- source_run: 'Fetched in',
255
- destination_run: 'Sent out',
256
- webhook_event: 'Received',
257
- };
258
-
259
- /**
260
- * WHAT AN ADMIN IS AGREEING TO, in their words rather than the wire's.
261
- *
262
- * Data, not a branch: an unknown key falls through to the key itself, because
263
- * the capability vocabulary lives in the connector package and will outrun this
264
- * bundle exactly the way the credential schema does. A capability this build has
265
- * never heard of must render as a choice, not vanish from the list.
266
- */
267
- const CAPABILITY_COPY: Record<string, string> = {
268
- poll: 'Fetch new records on a schedule',
269
- webhook_in: 'Receive events pushed to us',
270
- action: 'Let us run actions in this account',
271
- writeback_credential: 'Issue a token this vendor uses to call us',
272
- };
273
-
274
- /**
275
- * A refusal must read as a refusal, not as an empty page — and it must name the
276
- * refusal that actually happened. This runs in ONE place: the catch around the
277
- * two GETs `reload` makes. So trace which 403 can reach here on each surface.
278
- *
279
- * Control plane: the caller lacks the connections permission on this foundry.
280
- *
281
- * Member surface: `IsSeatedMember` denied — no ACTIVE `CompanyMembership` and
282
- * not the org's `owner`. That is the ONLY 403 either GET produces;
283
- * `MyConnectorCatalogView` answers a foundry that has allowed nothing with
284
- * `{results: []}` and a 200, and `MyConnectionsView.get` runs no per-connector
285
- * policy at all. The allowlist refusal (`_NOT_ALLOWED`) is raised by the POST,
286
- * lands in `CatalogCard`'s own catch, and renders the server's wording verbatim.
287
- * Blaming the allowlist here would send someone whose SEAT is gone to ask an
288
- * admin to allow a connector — the admin could allow every one of them and this
289
- * page would still refuse.
290
- */
291
- function readFailureMessage(err: unknown, personal: boolean): string {
292
- const status = (err as { status?: number })?.status;
293
- if (status === 403) {
294
- return personal
295
- ? 'You are not a member of this foundry, or your access to it has ended. Ask an admin to add you.'
296
- : 'You do not have access to this foundry’s connections. Ask an admin for the connections permission.';
297
- }
298
- if (status === 401) return 'Your session has expired. Sign in again.';
299
- const message = (err as { message?: string })?.message;
300
- return message || 'Could not load connections.';
301
- }
40
+ import { bindApi } from './connections/bound-api';
41
+ import { DEFAULTS, readFailureMessage } from './connections/copy';
42
+ import { CatalogCard } from './connections/CatalogCard';
43
+ import { ConnectionCard } from './connections/ConnectionCard';
44
+ import type { ConnectionsPageProps } from './connections/bound-api';
45
+ export type { ConnectionsPageProps } from './connections/bound-api';
302
46
 
303
47
  export function ConnectionsPage(props: ConnectionsPageProps) {
304
48
  const { classNames = {} } = props;
@@ -441,1142 +185,3 @@ export function ConnectionsPage(props: ConnectionsPageProps) {
441
185
  </div>
442
186
  );
443
187
  }
444
-
445
- // --------------------------------------------------------------------------
446
- // the capability choice (bd startsim-768w.22.22)
447
- // --------------------------------------------------------------------------
448
-
449
- /**
450
- * WHICH VERBS THIS ACCOUNT IS ALLOWED — the control this page did not have.
451
- *
452
- * `POST /connections/` and `PATCH /connections/<id>/` have both accepted
453
- * `capabilities_enabled[]` since the endpoints were designed. Nothing here ever
454
- * sent one, so every connection made through the product was stored with an
455
- * EMPTY list, and an empty list enables nothing: the card goes green on a real
456
- * `check()` and can then do none of the things it advertises. That is how a
457
- * connected Granola account on a live foundry ingested nothing forever.
458
- *
459
- * Rendered from `entry.capabilities` — the connector's own declaration, off the
460
- * catalog row — so a new vendor's verbs appear here with no code change, and a
461
- * verb this build has never heard of still renders.
462
- */
463
- function CapabilityPicker({
464
- scope, declared, selected, disabled, idPrefix, onToggle, classNames: cn, children,
465
- }: {
466
- scope: 'catalog' | 'connection';
467
- declared: string[];
468
- selected: string[];
469
- disabled: boolean;
470
- idPrefix: string;
471
- onToggle: (capability: string, on: boolean) => void;
472
- classNames: typeof DEFAULTS;
473
- /** Whatever COMMITS the choice — inline, so the control and the thing that
474
- saves it are one region for a screen reader and for a test. */
475
- children?: React.ReactNode;
476
- }) {
477
- if (declared.length === 0) return null;
478
- return (
479
- <fieldset data-capabilities={scope} className="mt-3 space-y-1 border-0 p-0">
480
- <legend className="text-sm font-medium text-gray-900">What this account may do</legend>
481
- {declared.map((capability) => {
482
- const id = `${idPrefix}-cap-${capability}`;
483
- return (
484
- <label key={capability} htmlFor={id} className="flex items-start gap-2 text-sm">
485
- <input
486
- id={id}
487
- type="checkbox"
488
- value={capability}
489
- className="mt-0.5"
490
- checked={selected.includes(capability)}
491
- disabled={disabled}
492
- onChange={(event) => onToggle(capability, event.target.checked)}
493
- />
494
- <span>
495
- <span className="text-gray-900">{capability}</span>
496
- <span className={`ml-2 ${cn.muted}`}>
497
- {CAPABILITY_COPY[capability] ?? ''}
498
- </span>
499
- </span>
500
- </label>
501
- );
502
- })}
503
- {children}
504
- </fieldset>
505
- );
506
- }
507
-
508
- /** Declaration order is the render order, and the wire order. */
509
- function orderCapabilities(declared: string[], selected: Iterable<string>): string[] {
510
- const set = new Set(selected);
511
- return declared.filter((capability) => set.has(capability));
512
- }
513
-
514
- // --------------------------------------------------------------------------
515
- // catalog
516
- // --------------------------------------------------------------------------
517
-
518
- function CatalogCard({
519
- api, personal, entry, existing, canManage, classNames: cn, onConnected,
520
- onPolicyChanged,
521
- }: {
522
- api: BoundApi;
523
- personal: boolean;
524
- entry: ConnectorCatalogEntry;
525
- /** Cards already held on this connector — the foundry's, or the member's own. */
526
- existing: Connection[];
527
- canManage: boolean;
528
- classNames: typeof DEFAULTS;
529
- onConnected: () => void;
530
- /** Re-read the catalog after the member toggle is written. Foundry mode only. */
531
- onPolicyChanged?: () => void;
532
- }) {
533
- const [open, setOpen] = React.useState(false);
534
- const [values, setValues] = React.useState<Record<string, unknown>>({});
535
- const [busy, setBusy] = React.useState(false);
536
- const [error, setError] = React.useState('');
537
- // Every declared capability starts ON. Not because "on" is a safe default in
538
- // general, but because the alternative here is a connection that can do
539
- // nothing — and the list is right there, unchecked with one click, before
540
- // anything is saved. The privacy control that is genuinely opt-in lives one
541
- // level down (a connector's own config, e.g. whether a poll fetches meeting
542
- // transcript bytes at all) and is unaffected by this box.
543
- const [capabilities, setCapabilities] = React.useState<string[]>(entry.capabilities);
544
-
545
- // THE ONE THING THIS CARD BRANCHES ON (bd startsim-768w.22.25.14/.23).
546
- // `schema.auth_mode_for` derives it server-side and its docstring says so;
547
- // this component had no reference to it at all, so an OAuth connector got the
548
- // same credential form as everything else — which on the admin catalog meant
549
- // the product asking a human to paste a refresh token, the exact thing
550
- // `auth_mode` exists to prevent.
551
- const isOAuth = entry.auth_mode === 'oauth';
552
- // A stale client is not a dead button. The verb is optional on both api
553
- // shapes, so an app pinned to an older `@startsimpli/api` says the connector
554
- // cannot be connected from here instead of rendering a hand-off that throws.
555
- const canHandOff = isOAuth && typeof api.startOAuth === 'function';
556
-
557
- // NO credential fields in OAuth mode. Not hidden — never collected: the whole
558
- // point is that the token comes back from the vendor, and a form that
559
- // "helpfully" accepted one would keep the paste-a-refresh-token path alive
560
- // beside the consent flow that replaced it.
561
- const credentialFields = isOAuth ? [] : schemaFields(entry.credential_schema);
562
- // Config IS still asked for, in both modes. It is the folder a Dropbox card
563
- // will poll, it is not a secret, and dropping it here would mean asking for it
564
- // again after the round trip.
565
- const configFields = schemaFields(entry.config_schema);
566
- const fields = [...credentialFields, ...configFields];
567
- const warnings = patternWarnings(fields, values);
568
- const missing = missingRequired(fields, values);
569
-
570
- /** Collect the config fields the form did gather. Shared by both submits. */
571
- function collectConfig(): Record<string, unknown> {
572
- const config: Record<string, unknown> = {};
573
- for (const spec of configFields) {
574
- const v = values[isSecret(spec) ? `${spec.key}__draft` : spec.key];
575
- if (typeof v === 'boolean' || typeof v === 'number' || v) config[spec.key] = v;
576
- }
577
- return config;
578
- }
579
-
580
- /**
581
- * Hand the browser to the vendor (bd startsim-768w.22.25.21/.22).
582
- *
583
- * ONE call: the server writes the shell card AND returns the consent URL,
584
- * because neither half is usable alone. The URL is opened VERBATIM — it is
585
- * already complete, and this client has no `client_id` to add to it and must
586
- * not have one to choose.
587
- *
588
- * `return_to` is where the member should land afterwards. It is sent, not
589
- * trusted: the server validates it against this tenant's own recorded origins
590
- * before folding it into the signed state, because the callback is an
591
- * anonymous browser mid-redirect from the vendor's domain.
592
- *
593
- * `location.assign`, not a new tab. A vendor consent screen that opens in a
594
- * popup is the one an ad blocker eats, and the whole point of the round trip
595
- * is that the browser comes BACK here.
596
- */
597
- async function handOff() {
598
- setBusy(true);
599
- setError('');
600
- try {
601
- const { authorization_url: url } = await api.startOAuth!({
602
- connector_key: entry.key,
603
- name: entry.name,
604
- config: collectConfig(),
605
- capabilities_enabled: orderCapabilities(entry.capabilities, capabilities),
606
- return_to: typeof window !== 'undefined' ? window.location.href : undefined,
607
- });
608
- if (typeof window !== 'undefined') window.location.assign(url);
609
- } catch (err) {
610
- setError((err as { message?: string })?.message || 'Could not start sign-in.');
611
- setBusy(false);
612
- }
613
- }
614
-
615
- async function submit() {
616
- setBusy(true);
617
- setError('');
618
- try {
619
- const credentials: Record<string, unknown> = {};
620
- const config: Record<string, unknown> = {};
621
- for (const spec of credentialFields) {
622
- const v = values[isSecret(spec) ? `${spec.key}__draft` : spec.key];
623
- if (v) credentials[spec.key] = v;
624
- }
625
- for (const spec of configFields) {
626
- const v = values[isSecret(spec) ? `${spec.key}__draft` : spec.key];
627
- // `if (v)` DROPPED A FALSE, which for a checkbox makes "off" and
628
- // "untouched" the same request. Harmless while every config field was a
629
- // string; not harmless once one of them decides whether verbatim
630
- // recordings are stored.
631
- if (typeof v === 'boolean' || typeof v === 'number' || v) config[spec.key] = v;
632
- }
633
- await api.connect({
634
- connector_key: entry.key, name: entry.name, credentials, config,
635
- // Always sent. Leaving it off is what wrote the inert cards.
636
- capabilities_enabled: orderCapabilities(entry.capabilities, capabilities),
637
- });
638
- setOpen(false);
639
- setValues({});
640
- setCapabilities(entry.capabilities);
641
- onConnected();
642
- } catch (err) {
643
- // The server's typed answer, verbatim. It already scrubbed itself of the
644
- // values just submitted, and it knows things the client cannot guess —
645
- // "the vendor rejected this key" is not "the network failed".
646
- setError((err as { message?: string })?.message || 'Could not connect.');
647
- } finally {
648
- setBusy(false);
649
- }
650
- }
651
-
652
- return (
653
- <div className={cn.card}>
654
- <div className="flex items-start justify-between gap-4">
655
- <div>
656
- <p className="font-medium text-gray-900">{entry.name}</p>
657
- <p className={cn.muted}>{entry.description}</p>
658
- {entry.capabilities.length ? (
659
- <p className="mt-1 text-xs text-gray-400">{entry.capabilities.join(' · ')}</p>
660
- ) : null}
661
- {/* A row whose class will not load says WHY and stays visible. The
662
- catalog is data and outruns deployed bundles; blanking the menu
663
- because one vendor's module moved is the failure this prevents. */}
664
- {!entry.availability.available ? (
665
- <p className={cn.error}>Unavailable: {entry.availability.reason}</p>
666
- ) : null}
667
- </div>
668
- {canManage && entry.availability.available ? (
669
- <button type="button" className={cn.button} onClick={() => setOpen((v) => !v)}>
670
- {open ? 'Cancel' : 'Connect'}
671
- </button>
672
- ) : null}
673
- </div>
674
-
675
- {/* On the card it governs, not on a settings list of its own — an admin
676
- should not have to hold two lists of connectors in their head to know
677
- which ones members can use. */}
678
- {!personal && api.setMemberConnectorPolicy && entry.member_policy ? (
679
- <MemberPolicyToggle
680
- connectorKey={entry.key}
681
- policy={entry.member_policy}
682
- canManage={canManage}
683
- write={api.setMemberConnectorPolicy}
684
- classNames={cn}
685
- onChanged={onPolicyChanged}
686
- />
687
- ) : null}
688
-
689
- {open ? (
690
- <div className="mt-4 space-y-3">
691
- {/* SAID BEFORE THE KEY IS PASTED, not after the server refuses.
692
- Connecting again makes a SECOND account, which is legitimate and
693
- stays available — but it is almost never what an admin holding a
694
- rotated key wants, and it was the only thing this page offered
695
- them. The server now answers the indistinguishable case with a 409
696
- naming the card; this catches it a round trip earlier. */}
697
- {existing.length > 0 ? (
698
- <p className={cn.muted} data-already-connected={entry.key}>
699
- Already connected as{' '}
700
- <strong className="text-gray-900">
701
- {existing.map((c) => c.name).join(', ')}
702
- </strong>
703
- . To install a new key, use <em>Replace key</em> on that
704
- connection — it is tested before it replaces the working one.
705
- Connecting here adds a SECOND account.
706
- </p>
707
- ) : null}
708
- {/* SIGN IN AT THE VENDOR — never a form asking for token material.
709
- `auth_mode: oauth` means the credential schema is `access_token` /
710
- `refresh_token` / `expires_at`, and rendering those as inputs asks
711
- a human to go and mint a refresh token by hand. That is what this
712
- card did to every admin who opened Dropbox. */}
713
- {isOAuth ? (
714
- <div className="space-y-2" data-oauth-connect={entry.key}>
715
- <p className={cn.muted}>
716
- {entry.name} signs you in on its own site. You will be sent there
717
- to approve access and returned here — no keys to copy, and
718
- StartSimpli never sees your password.
719
- </p>
720
- {!canHandOff ? (
721
- <p className={cn.error}>
722
- This app cannot start a {entry.name} sign-in yet. Update it, or
723
- connect {entry.name} from the foundry control plane.
724
- </p>
725
- ) : null}
726
- </div>
727
- ) : (
728
- <CredentialSchemaForm
729
- fields={fields}
730
- values={values}
731
- warnings={warnings}
732
- idPrefix={`connect-${entry.key}`}
733
- onChange={(key, value) => {
734
- const spec = fields.find((f) => f.key === key);
735
- setValues((prev) => ({
736
- ...prev, [spec && isSecret(spec) ? `${key}__draft` : key]: value,
737
- }));
738
- }}
739
- />
740
- )}
741
- {/* Config is asked for in BOTH modes — it is not a secret, and it is
742
- the folder this card will poll. Rendered separately in OAuth mode
743
- because the credential half of the same form is gone. */}
744
- {isOAuth && configFields.length > 0 ? (
745
- <CredentialSchemaForm
746
- fields={configFields}
747
- values={values}
748
- warnings={warnings}
749
- idPrefix={`connect-${entry.key}`}
750
- onChange={(key, value) => {
751
- const spec = configFields.find((f) => f.key === key);
752
- setValues((prev) => ({
753
- ...prev, [spec && isSecret(spec) ? `${key}__draft` : key]: value,
754
- }));
755
- }}
756
- />
757
- ) : null}
758
- <CapabilityPicker
759
- scope="catalog"
760
- declared={entry.capabilities}
761
- selected={capabilities}
762
- disabled={busy}
763
- idPrefix={`connect-${entry.key}`}
764
- onToggle={(capability, on) => setCapabilities((prev) => (
765
- on ? [...prev, capability] : prev.filter((c) => c !== capability)
766
- ))}
767
- classNames={cn}
768
- />
769
- {/* The server refuses an empty list with a 400 rather than storing a
770
- card that can do nothing. Saying so here costs the admin a round
771
- trip instead of a confusing error. */}
772
- {entry.capabilities.length > 0 && capabilities.length === 0 ? (
773
- <p className={cn.error}>
774
- Enable at least one — a connection with nothing enabled can do nothing.
775
- </p>
776
- ) : null}
777
- {error ? <p className={cn.error} role="alert">{error}</p> : null}
778
- <button
779
- type="button"
780
- className={cn.button}
781
- disabled={
782
- busy
783
- // `missing` counts only the fields this mode actually collects.
784
- // In OAuth mode that is config alone — gating the hand-off on a
785
- // required `access_token` would disable the very button whose job
786
- // is to go and get one.
787
- || missing.length > 0
788
- || (isOAuth && !canHandOff)
789
- || (entry.capabilities.length > 0 && capabilities.length === 0)
790
- }
791
- onClick={() => void (isOAuth ? handOff() : submit())}
792
- >
793
- {isOAuth
794
- ? (busy ? 'Redirecting…' : `Continue to ${entry.name}`)
795
- : (busy ? 'Testing…' : 'Test and save')}
796
- </button>
797
- </div>
798
- ) : null}
799
- </div>
800
- );
801
- }
802
-
803
- // --------------------------------------------------------------------------
804
- // who may connect their OWN account (bd startsim-768w.22.25.8)
805
- // --------------------------------------------------------------------------
806
-
807
- /**
808
- * ONE CONNECTOR, ONE DECISION: may this foundry's members connect their own
809
- * account on it?
810
- *
811
- * DEFAULT-DENY, and the copy has to carry that, because the switch is not a
812
- * display preference. Turning it on means members send THEIR vendor data into
813
- * this foundry, under their own credentials, for this foundry to store and
814
- * process — an admin is agreeing to receive that, and is entitled to read it in
815
- * those words before flipping anything.
816
- *
817
- * TURNING IT OFF IS NOT A KILL SWITCH, and saying so in the confirmation rather
818
- * than in a docs page is the point. Off stops NEW personal connections
819
- * immediately; every connection that already exists keeps running, with its
820
- * credential and its scheduled fetches. Ending those is one explicit disconnect
821
- * per person from the roster below — destructive, irreversible, and never a side
822
- * effect of tightening a default. The wording here is the server's own, lifted
823
- * from `apps/connectors/services/policy.py` so the two cannot drift apart.
824
- *
825
- * A connector that CANNOT be opened yet renders disabled WITH the server's
826
- * reason instead of vanishing: an admin who cannot find Dropbox in this list
827
- * would reasonably conclude the catalog is broken, when the real answer is that
828
- * the member surface has no OAuth path yet.
829
- *
830
- * THE THIRD STATE IS THE ONE THAT MATTERS: already allowed, and no longer
831
- * openable — a connector opened while it was an API key that has since moved to
832
- * OAuth, or whose class stopped importing. The server answers `settable: true`
833
- * with a `reason`, because the only move an ON switch offers is OFF and the
834
- * write always accepts that. Disabling it on `reason` alone would draw a switch
835
- * an admin cannot turn off, which is the exact opposite of what a governance
836
- * control is for. It renders live, with the reason as a one-way warning.
837
- */
838
- function MemberPolicyToggle({
839
- connectorKey, policy, canManage, write, classNames: cn, onChanged,
840
- }: {
841
- connectorKey: string;
842
- policy: NonNullable<ConnectorCatalogEntry['member_policy']>;
843
- canManage: boolean;
844
- write: (connectorKey: string, allowed: boolean) => Promise<unknown>;
845
- classNames: typeof DEFAULTS;
846
- onChanged?: () => void;
847
- }) {
848
- const [busy, setBusy] = React.useState(false);
849
- const [error, setError] = React.useState('');
850
- const id = `member-policy-${connectorKey}`;
851
-
852
- async function set(allowed: boolean) {
853
- setBusy(true);
854
- setError('');
855
- try {
856
- await write(connectorKey, allowed);
857
- onChanged?.();
858
- } catch (err) {
859
- setError((err as { message?: string })?.message || 'Could not save that.');
860
- } finally {
861
- setBusy(false);
862
- }
863
- }
864
-
865
- return (
866
- <div className="mt-3 border-t border-gray-100 pt-3" data-member-policy={connectorKey}>
867
- <label htmlFor={id} className="flex items-start gap-2 text-sm">
868
- <input
869
- id={id}
870
- type="checkbox"
871
- className="mt-0.5"
872
- checked={policy.allowed}
873
- disabled={busy || !canManage || !policy.settable}
874
- onChange={(event) => void set(event.target.checked)}
875
- />
876
- <span>
877
- <span className="text-gray-900">Members may connect their own account</span>
878
- <span className={`block ${cn.muted}`}>
879
- {policy.settable
880
- ? 'Each member signs in with their own key, and sees only their own'
881
- + ' data. Allowing this means their vendor data flows into this'
882
- + ' foundry. Turning it off later stops new connections — the ones'
883
- + ' already connected keep running until you disconnect them below.'
884
- : policy.reason}
885
- </span>
886
- {/* Settable AND blocked: open today, unopenable tomorrow. Said next to
887
- the switch rather than after the click, because the click is the
888
- irreversible half. */}
889
- {policy.settable && policy.reason ? (
890
- <span className={`block ${cn.error}`} data-member-policy-oneway={connectorKey}>
891
- This is on, but can no longer be turned back on once off:{' '}
892
- {policy.reason}
893
- </span>
894
- ) : null}
895
- </span>
896
- </label>
897
- {error ? <p className={cn.error} role="alert">{error}</p> : null}
898
- </div>
899
- );
900
- }
901
-
902
- // --------------------------------------------------------------------------
903
- // replacing the key on a connection that already exists
904
- // --------------------------------------------------------------------------
905
-
906
- /**
907
- * ROTATION, rendered from the same schema as the connect form.
908
- *
909
- * Two things make this safe to put in front of a non-engineer, and both are
910
- * properties of the endpoint rather than of this component:
911
- *
912
- * * the pasted credential is run through `check()` against the vendor BEFORE
913
- * anything is written, so a wrong key changes nothing and the working
914
- * connection stays up. That is said in the copy, because someone about to
915
- * paste a production key is entitled to know it;
916
- * * a PARTIAL map is legal. A connector with a url + a key + a select takes
917
- * just the key here, and the stored values fill in the rest — so replacing
918
- * a secret never means re-typing the settings around it.
919
- *
920
- * Only the CREDENTIAL fields render. `config` is not a credential and is edited
921
- * through `ConnectionSettingsForm` below; mixing them here would make a
922
- * rotation quietly a config change.
923
- */
924
- function ReplaceKeyForm({
925
- api, connection, entry, classNames: cn, onDone,
926
- }: {
927
- api: BoundApi;
928
- connection: Connection;
929
- entry?: ConnectorCatalogEntry;
930
- classNames: typeof DEFAULTS;
931
- onDone: () => void;
932
- }) {
933
- const [values, setValues] = React.useState<Record<string, unknown>>({});
934
- const [busy, setBusy] = React.useState(false);
935
- const [error, setError] = React.useState('');
936
-
937
- const fields = schemaFields(entry?.credential_schema);
938
- const warnings = patternWarnings(fields, values);
939
- // NOT `missingRequired`. A rotation is partial by design — the whole point is
940
- // to replace one secret without re-typing the fields around it — so the gate
941
- // is "something was actually typed", and the server decides the rest.
942
- const submitted = React.useMemo(() => {
943
- const out: Record<string, unknown> = {};
944
- for (const spec of fields) {
945
- const value = values[isSecret(spec) ? `${spec.key}__draft` : spec.key];
946
- if (value) out[spec.key] = value;
947
- }
948
- return out;
949
- }, [fields, values]);
950
- const empty = Object.keys(submitted).length === 0;
951
-
952
- return (
953
- <div className="mt-3 space-y-3 border-t pt-3" data-replace-key={connection.id}>
954
- <p className={cn.muted}>
955
- The new key is tested against the vendor before it replaces the current
956
- one. If it is rejected, nothing changes and this connection keeps
957
- working on the key it has.
958
- </p>
959
- {fields.length === 0 ? (
960
- <p className={cn.muted}>
961
- This connector holds no credential of ours, so there is nothing to
962
- replace.
963
- </p>
964
- ) : (
965
- <CredentialSchemaForm
966
- fields={fields}
967
- values={values}
968
- warnings={warnings}
969
- idPrefix={`replace-${connection.id}`}
970
- onChange={(key, value) => {
971
- const spec = fields.find((f) => f.key === key);
972
- setValues((prev) => ({
973
- ...prev, [spec && isSecret(spec) ? `${key}__draft` : key]: value,
974
- }));
975
- }}
976
- />
977
- )}
978
- {error ? <p className={cn.error} role="alert">{error}</p> : null}
979
- <button
980
- type="button"
981
- className={cn.button}
982
- disabled={busy || empty}
983
- onClick={() => {
984
- setBusy(true);
985
- setError('');
986
- api.rotateCredential(connection.id, submitted)
987
- .then(() => { setValues({}); onDone(); })
988
- // The server's typed answer, verbatim: it already scrubbed itself of
989
- // the values just submitted, and "the vendor rejected this key" is
990
- // not something the browser could work out on its own.
991
- .catch((err: unknown) => setError(
992
- (err as { message?: string })?.message || 'Could not replace the key.'))
993
- .finally(() => setBusy(false));
994
- }}
995
- >
996
- {busy ? 'Testing…' : 'Test and replace'}
997
- </button>
998
- </div>
999
- );
1000
- }
1001
-
1002
- // --------------------------------------------------------------------------
1003
- // a connected account: discover -> wire -> confirm -> fire
1004
- // --------------------------------------------------------------------------
1005
-
1006
- /**
1007
- * The connection's own settings — its connector's `config_schema`, for an
1008
- * account that already exists.
1009
- *
1010
- * WHY IT IS A SEPARATE FORM FROM THE CONNECT CARD. Connecting is "here are my
1011
- * credentials, does this work"; this is "change how it behaves". Rotating a key
1012
- * must not quietly change a setting, and changing a setting must not ask for a
1013
- * key. `ReplaceKeyForm` has said as much in its own docstring since it shipped,
1014
- * pointing at a surface that did not exist.
1015
- *
1016
- * IT SENDS ONLY WHAT CHANGED, and the API merges. Two reasons, and the second is
1017
- * the one that bites: resending untouched fields turns "I ticked one box" into
1018
- * "I reassert every setting", which silently overwrites an edit made in another
1019
- * tab — and it is exactly how the retention bound gets reset to whatever this
1020
- * form happened to be showing.
1021
- *
1022
- * A FALSE IS SENT, not omitted. The connect card drops falsy values, which for a
1023
- * checkbox makes "off" indistinguishable from "untouched" — and against a
1024
- * merging API that would make the off position literally unreachable. For
1025
- * `ingest_transcripts` the off position is the whole privacy posture.
1026
- */
1027
- function ConnectionSettingsForm({
1028
- api, connection, fields, classNames: cn, onDone,
1029
- }: {
1030
- api: BoundApi;
1031
- connection: Connection;
1032
- fields: ConnectorFieldSpec[];
1033
- classNames: typeof DEFAULTS;
1034
- /** Handed whatever the SERVER said about the change, so the card can say it. */
1035
- onDone: (notices: string[]) => void;
1036
- }) {
1037
- const stored = React.useMemo(
1038
- () => (connection.config ?? {}) as Record<string, unknown>,
1039
- [connection.config],
1040
- );
1041
- const [edits, setEdits] = React.useState<Record<string, string | boolean>>({});
1042
- const [busy, setBusy] = React.useState(false);
1043
- const [error, setError] = React.useState('');
1044
-
1045
- const values = React.useMemo(() => ({ ...stored, ...edits }), [stored, edits]);
1046
- const warnings = patternWarnings(fields, values);
1047
- const changed = Object.keys(edits);
1048
-
1049
- async function save() {
1050
- setBusy(true);
1051
- setError('');
1052
- try {
1053
- // Numbers go back as numbers. A `number` input hands back a string, and a
1054
- // retention bound stored as "0" rather than 0 is a comparison that quietly
1055
- // stops being true.
1056
- const config: Record<string, unknown> = {};
1057
- for (const key of changed) {
1058
- const spec = fields.find((field) => field.key === key);
1059
- const value = edits[key];
1060
- config[key] =
1061
- spec?.type === 'number' && typeof value === 'string' && value.trim() !== ''
1062
- ? Number(value)
1063
- : value;
1064
- }
1065
- const saved = await api.updateConnectionConfig!(connection.id, config);
1066
- // WHAT THE SERVER WANTS THEM TO KNOW, handed up rather than rendered here.
1067
- // The live case is a scope change restarting the walk, and this file
1068
- // cannot work that out: it names no vendor and therefore cannot know which
1069
- // fields bear the scope. A heuristic on field names would be both a vendor
1070
- // branch and untestable at the level that matters. Handed to the CARD
1071
- // because saving closes this panel, and a sentence that unmounts with the
1072
- // form is one nobody reads.
1073
- onDone(saved?.notices ?? []);
1074
- } catch (err) {
1075
- setError((err as { message?: string })?.message || 'Those settings were not saved.');
1076
- } finally {
1077
- setBusy(false);
1078
- }
1079
- }
1080
-
1081
- return (
1082
- <div className="mt-3 space-y-3 border-t pt-3" role="group" aria-label="Connection settings">
1083
- <CredentialSchemaForm
1084
- fields={fields}
1085
- values={values}
1086
- onChange={(key, value) => setEdits((current) => ({ ...current, [key]: value }))}
1087
- warnings={warnings}
1088
- idPrefix={`settings-${connection.id}`}
1089
- />
1090
- {error ? <p className={cn.error} role="alert">{error}</p> : null}
1091
- <div className="flex items-center gap-2">
1092
- <button
1093
- type="button"
1094
- className={cn.button}
1095
- disabled={busy || changed.length === 0}
1096
- onClick={() => void save()}
1097
- >
1098
- {busy ? 'Saving…' : 'Save settings'}
1099
- </button>
1100
- {changed.length === 0 ? (
1101
- <span className={cn.muted}>Nothing changed yet.</span>
1102
- ) : null}
1103
- </div>
1104
- </div>
1105
- );
1106
- }
1107
-
1108
- function ConnectionCard({
1109
- api, personal, connection, entry, canManage, classNames: cn, onChanged,
1110
- }: {
1111
- api: BoundApi;
1112
- personal: boolean;
1113
- connection: Connection;
1114
- /** This connector's catalog row: its capabilities AND its field schema. */
1115
- entry?: ConnectorCatalogEntry;
1116
- canManage: boolean;
1117
- classNames: typeof DEFAULTS;
1118
- onChanged: () => void;
1119
- }) {
1120
- const [choices, setChoices] = React.useState<ConnectionChoice[] | null>(null);
1121
- const [target, setTarget] = React.useState<ConnectionTarget | null>(null);
1122
- const [actions, setActions] = React.useState<ConnectorAction[]>([]);
1123
- const [busy, setBusy] = React.useState('');
1124
- const [error, setError] = React.useState('');
1125
- const [notice, setNotice] = React.useState('');
1126
- /** Sentences the SERVER wrote about the last settings save. Never composed here. */
1127
- const [notices, setNotices] = React.useState<string[]>([]);
1128
- const [replacing, setReplacing] = React.useState(false);
1129
- const [settingsOpen, setSettingsOpen] = React.useState(false);
1130
- const [confirmingDisconnect, setConfirmingDisconnect] = React.useState(false);
1131
- const [activityOpen, setActivityOpen] = React.useState(false);
1132
- /** `null` is NOT LOADED YET, which reads differently from a connection that
1133
- has never run — the distinction the empty state below turns on. */
1134
- const [runs, setRuns] = React.useState<ConnectionRun[] | null>(null);
1135
-
1136
- const declared = entry?.capabilities;
1137
- const enabled = React.useMemo(
1138
- () => connection.capabilities_enabled ?? [], [connection.capabilities_enabled]);
1139
- // The catalog's declaration first, then anything this connection holds that
1140
- // the catalog no longer offers. A capability an admin cannot SEE is one they
1141
- // cannot turn off, and a catalog row that will not load must not blank the
1142
- // card's own state.
1143
- const offered = React.useMemo(() => {
1144
- const seen = new Set<string>();
1145
- return [...(declared ?? []), ...enabled].filter((capability) => {
1146
- if (seen.has(capability)) return false;
1147
- seen.add(capability);
1148
- return true;
1149
- });
1150
- }, [declared, enabled]);
1151
- const [selected, setSelected] = React.useState<string[]>(enabled);
1152
- React.useEffect(() => { setSelected(enabled); }, [enabled]);
1153
-
1154
- const pending = orderCapabilities(offered, selected);
1155
- const dirty = pending.join(',') !== orderCapabilities(offered, enabled).join(',');
1156
-
1157
- async function guard(label: string, run: () => Promise<void>) {
1158
- setBusy(label);
1159
- setError('');
1160
- try {
1161
- await run();
1162
- } catch (err) {
1163
- setError((err as { message?: string })?.message || 'That did not work.');
1164
- } finally {
1165
- setBusy('');
1166
- }
1167
- }
1168
-
1169
- const configFields = schemaFields(entry?.config_schema);
1170
- // A TASK TRACKER (the catalog says `kind: task_tracker`; no vendor is named here)
1171
- // also gets its sync settings: team, project, personal destination, state mapping.
1172
- const trackerApi = isTaskTracker(entry) && api.connectionChoices && api.updateConnectionConfig
1173
- ? { connectionChoices: api.connectionChoices, updateConnectionConfig: api.updateConnectionConfig,
1174
- ...(api.syncConnectionNow ? { syncConnectionNow: api.syncConnectionNow } : {}) }
1175
- : null;
1176
-
1177
- return (
1178
- <div className={cn.card} data-connection={connection.id}>
1179
- <div className="flex items-start justify-between gap-4">
1180
- <div>
1181
- <p className="font-medium text-gray-900">{connection.name}</p>
1182
- <p className={cn.muted}>
1183
- {connection.connector_name}
1184
- {connection.account_label ? ` · ${connection.account_label}` : ''}
1185
- </p>
1186
- <p className="mt-1 text-xs text-gray-400">{connection.status}</p>
1187
- {connection.check_error ? (
1188
- <p className={cn.error}>{connection.check_error}</p>
1189
- ) : null}
1190
- </div>
1191
- <div className="flex flex-wrap justify-end gap-2">
1192
- {/* ACTIVITY IS OUTSIDE THE MANAGE GATE, and deliberately. Reading the
1193
- run ledger needs `view_connections` server-side, which is what put
1194
- this card on the screen at all — and the person who most needs to
1195
- know WHY a connection is failing is often the one who cannot fix
1196
- it themselves. Gating the answer behind the permission to act
1197
- would leave them with the word "Failing" and nothing else, which
1198
- is the sixteen days this bead is about. */}
1199
- {api.connectionRuns ? (
1200
- <button
1201
- type="button"
1202
- className={cn.button}
1203
- disabled={Boolean(busy)}
1204
- onClick={() => {
1205
- const opening = !activityOpen;
1206
- setActivityOpen(opening);
1207
- if (!opening) return;
1208
- void guard('activity', async () => {
1209
- const page = await api.connectionRuns!(connection.id);
1210
- setRuns(page.results ?? []);
1211
- });
1212
- }}
1213
- >
1214
- {activityOpen ? 'Hide activity' : 'Activity'}
1215
- </button>
1216
- ) : null}
1217
- {canManage ? (
1218
- <>
1219
- <button
1220
- type="button"
1221
- className={cn.button}
1222
- disabled={Boolean(busy)}
1223
- onClick={() => void guard('check', async () => {
1224
- const res = await api.checkConnection(connection.id);
1225
- setNotice(res.detail || (res.ok ? 'Connection is healthy.' : ''));
1226
- onChanged();
1227
- })}
1228
- >
1229
- Test
1230
- </button>
1231
- {/* THE CONTROL THIS PAGE WAS MISSING. A vendor key gets rotated —
1232
- that is normal operations, not an exception — and the only place
1233
- to put the new one was a form that creates a second account. */}
1234
- <button
1235
- type="button"
1236
- className={cn.button}
1237
- disabled={Boolean(busy)}
1238
- onClick={() => {
1239
- setConfirmingDisconnect(false);
1240
- setError('');
1241
- setReplacing((v) => !v);
1242
- }}
1243
- >
1244
- {replacing ? 'Cancel' : 'Replace key'}
1245
- </button>
1246
- {/* DISCOVER -> WIRE -> FIRE is foundry-level and stays there. The
1247
- member router serves no choices, targets or actions at all, so
1248
- the control is gated on the verb EXISTING rather than on a mode
1249
- flag — there is no way to render a button here whose handler is
1250
- undefined. */}
1251
- {api.connectionChoices && api.connectionActions ? (
1252
- <button
1253
- type="button"
1254
- className={cn.button}
1255
- disabled={Boolean(busy)}
1256
- onClick={() => void guard('discover', async () => {
1257
- const page = await api.connectionChoices!(connection.id);
1258
- setChoices(page.results ?? []);
1259
- const available = await api.connectionActions!(connection.id);
1260
- setActions(available.results ?? []);
1261
- })}
1262
- >
1263
- {busy === 'discover' ? 'Loading…' : 'Workflows'}
1264
- </button>
1265
- ) : null}
1266
- {/* SETTINGS, which this card has never had. A connector's
1267
- `config_schema` ships on every catalog row and was rendered
1268
- exactly once — on the connect form, before the account existed.
1269
- After that a setting could not be changed from the product at
1270
- all, which for Granola means the switch deciding whether verbatim
1271
- recordings of people's conversations are stored was reachable
1272
- only by editing the database. `ReplaceKeyForm` already pointed at
1273
- "the connection's own settings" as if this existed.
1274
-
1275
- GATED ON THE SETTINGS VERB, not on the general one (bd
1276
- startsim-sfms2). The member surface has `updateConnectionConfig`
1277
- and deliberately not `updateConnection`, because a personal
1278
- connection's config is the MEMBER's privacy boundary while its
1279
- name and what it may do stay the foundry's. One gate for both
1280
- would have made opening this control open the capability Save
1281
- beside it, which is a decision this change did not make. */}
1282
- {(configFields.length || trackerApi) && api.updateConnectionConfig ? (
1283
- <button
1284
- type="button"
1285
- className={cn.button}
1286
- disabled={Boolean(busy) || confirmingDisconnect}
1287
- onClick={() => {
1288
- setReplacing(false);
1289
- setError('');
1290
- setSettingsOpen((v) => !v);
1291
- }}
1292
- >
1293
- {settingsOpen ? 'Close settings' : 'Settings'}
1294
- </button>
1295
- ) : null}
1296
- <button
1297
- type="button"
1298
- className={cn.button}
1299
- disabled={Boolean(busy) || confirmingDisconnect}
1300
- onClick={() => {
1301
- setReplacing(false);
1302
- setSettingsOpen(false);
1303
- setError('');
1304
- setConfirmingDisconnect(true);
1305
- }}
1306
- >
1307
- Disconnect
1308
- </button>
1309
- </>
1310
- ) : null}
1311
- </div>
1312
- </div>
1313
-
1314
- {activityOpen ? (
1315
- <div className="mt-3 space-y-2 border-t pt-3" role="group"
1316
- aria-label="Recent activity">
1317
- {/* THE FIELD NOTHING HAS EVER READ. `ConnectionRun.error_message` has
1318
- been declared in this package's types since the endpoint existed;
1319
- until #375 the server answered `""` for every source run ever
1320
- recorded, and even after it did not, no component asked. A failed
1321
- run rendered as a status word, which is a fact the reader already
1322
- had from the card above it.
1323
-
1324
- RENDERED AS THE SERVER WROTE IT. The text is scrubbed against this
1325
- connection's stored credential and the platform app_secret before
1326
- it leaves Django (`surface.py::_reason_reader`), and a reason that
1327
- could not be scrubbed arrives as a sentence saying so. There is
1328
- one redaction path in this estate and it is not in the browser —
1329
- which does not hold the secrets to run it. */}
1330
- {busy === 'activity' && runs === null ? (
1331
- <p className={cn.muted}>Loading recent activity…</p>
1332
- ) : null}
1333
- {runs !== null && runs.length === 0 ? (
1334
- <p className={cn.muted}>No runs yet for this connection.</p>
1335
- ) : null}
1336
- {(runs ?? []).map((run) => (
1337
- <div key={run.id} data-run={run.id}>
1338
- <p className={cn.muted}>
1339
- <span className="font-medium text-gray-900">
1340
- {RUN_KIND_COPY[run.kind] ?? run.kind}
1341
- </span>
1342
- {run.name ? ` · ${run.name}` : ''}
1343
- {` · ${run.status}`}
1344
- {run.occurred_at ? ` · ${new Date(run.occurred_at).toLocaleString()}` : ''}
1345
- </p>
1346
- {run.error_message ? (
1347
- <p className={cn.error}>{run.error_message}</p>
1348
- ) : null}
1349
- </div>
1350
- ))}
1351
- </div>
1352
- ) : null}
1353
-
1354
- {settingsOpen && trackerApi ? (
1355
- <TaskTrackerSettings
1356
- api={trackerApi}
1357
- connection={connection}
1358
- classNames={cn}
1359
- onSaved={() => { setNotice('Sync settings saved.'); onChanged(); }}
1360
- />
1361
- ) : null}
1362
-
1363
- {settingsOpen && configFields.length ? (
1364
- <ConnectionSettingsForm
1365
- api={api}
1366
- connection={connection}
1367
- fields={configFields}
1368
- classNames={cn}
1369
- onDone={(said) => {
1370
- setSettingsOpen(false);
1371
- setNotice('Settings saved.');
1372
- setNotices(said);
1373
- onChanged();
1374
- }}
1375
- />
1376
- ) : null}
1377
-
1378
- {replacing ? (
1379
- <ReplaceKeyForm
1380
- api={api}
1381
- connection={connection}
1382
- entry={entry}
1383
- classNames={cn}
1384
- onDone={() => { setReplacing(false); setNotice('New key installed.'); onChanged(); }}
1385
- />
1386
- ) : null}
1387
-
1388
- {confirmingDisconnect ? (
1389
- <div className="mt-3 space-y-2 border-t pt-3" role="group"
1390
- aria-label="Confirm disconnect">
1391
- {/* Disconnect is one sentence to an admin and four writes to the
1392
- server, three of which cannot be undone by reconnecting: the
1393
- tokens this vendor holds against us are revoked and the stored
1394
- credential is deleted. Naming them is the difference between a
1395
- control someone uses deliberately and one they regret. */}
1396
- <p className={cn.muted}>
1397
- Disconnecting <strong className="text-gray-900">{connection.name}</strong>{' '}
1398
- will stop its scheduled fetches, stop anything it sends out, revoke
1399
- every token issued for it and delete the stored key. The card stays
1400
- here, marked disabled, and you can connect it again later with a new
1401
- key.
1402
- </p>
1403
- {trackerApi ? (
1404
- <p className={cn.muted}>
1405
- {`Your to-dos stay in Tandem. Nothing is deleted in ${connection.connector_name}; they simply stop syncing.`}
1406
- </p>
1407
- ) : null}
1408
- <div className="flex gap-2">
1409
- <button
1410
- type="button"
1411
- className={cn.button}
1412
- disabled={Boolean(busy)}
1413
- onClick={() => void guard('disconnect', async () => {
1414
- await api.disconnect(connection.id);
1415
- setConfirmingDisconnect(false);
1416
- setNotice('Disconnected.');
1417
- onChanged();
1418
- })}
1419
- >
1420
- {busy === 'disconnect' ? 'Disconnecting…' : 'Yes, disconnect'}
1421
- </button>
1422
- <button
1423
- type="button"
1424
- className={cn.button}
1425
- disabled={Boolean(busy)}
1426
- onClick={() => setConfirmingDisconnect(false)}
1427
- >
1428
- Cancel
1429
- </button>
1430
- </div>
1431
- </div>
1432
- ) : null}
1433
-
1434
- {/* THE FIX FOR THE CARDS THAT ALREADY EXIST. A connection written before
1435
- the connect form asked holds an empty list and can do nothing; the
1436
- connect form can never reach it. Turning `poll` on here is what makes
1437
- the server create the scheduled ingest leg. */}
1438
- <CapabilityPicker
1439
- scope="connection"
1440
- declared={offered}
1441
- selected={selected}
1442
- // On the member surface there is no PATCH, so the picker is
1443
- // INFORMATIONAL rather than absent. A member chose these at connect time
1444
- // and `POST` accepted them; hiding the list afterwards would make that
1445
- // choice look like it never happened, and leave them unable to see what
1446
- // their own account is doing.
1447
- disabled={!canManage || !api.updateConnection || Boolean(busy)}
1448
- idPrefix={`connection-${connection.id}`}
1449
- onToggle={(capability, on) => setSelected((prev) => (
1450
- on ? [...prev, capability] : prev.filter((c) => c !== capability)
1451
- ))}
1452
- classNames={cn}
1453
- >
1454
- {canManage && api.updateConnection ? (
1455
- <div className="mt-2 flex items-center gap-3">
1456
- <button
1457
- type="button"
1458
- className={cn.button}
1459
- disabled={!dirty || pending.length === 0 || Boolean(busy)}
1460
- onClick={() => void guard('capabilities', async () => {
1461
- await api.updateConnection!(connection.id, {
1462
- capabilities_enabled: pending,
1463
- });
1464
- setNotice('Saved.');
1465
- onChanged();
1466
- })}
1467
- >
1468
- {busy === 'capabilities' ? 'Saving…' : 'Save'}
1469
- </button>
1470
- {pending.length === 0 ? (
1471
- <span className={cn.error}>
1472
- Enable at least one, or disconnect the account.
1473
- </span>
1474
- ) : null}
1475
- </div>
1476
- ) : personal ? (
1477
- <p className={cn.muted}>
1478
- Chosen when you connected. Ask an admin to change what this account
1479
- may do, or disconnect it and connect again.
1480
- </p>
1481
- ) : null}
1482
- </CapabilityPicker>
1483
-
1484
- {notice ? <p className={cn.muted}>{notice}</p> : null}
1485
- {/* WHAT THE CHANGE COSTS, in the server's words. Rendered verbatim: this
1486
- file names no vendor and cannot know which settings restart a walk. */}
1487
- {notices.map((said) => (
1488
- <p key={said} className={cn.muted}>{said}</p>
1489
- ))}
1490
- {error ? <p className={cn.error} role="alert">{error}</p> : null}
1491
-
1492
- {choices ? (
1493
- <div className="mt-4 space-y-2">
1494
- <p className="text-sm font-medium text-gray-900">What this account can reach</p>
1495
- {choices.length === 0 ? <p className={cn.muted}>Nothing to wire yet.</p> : null}
1496
- {choices.map((choice) => (
1497
- <div key={choice.id} className="flex items-start justify-between gap-3 border-t pt-2">
1498
- <div>
1499
- <p className={choice.selectable ? 'text-sm text-gray-900' : 'text-sm text-gray-400'}>
1500
- {choice.label}
1501
- </p>
1502
- {/* An unpickable row is GREYED and says why — never dropped. A
1503
- picker that hides them looks broken with no way to tell. */}
1504
- {!choice.selectable ? (
1505
- <p className="text-xs text-gray-500">
1506
- {choice.reason}
1507
- {choice.remediation ? ` — ${choice.remediation}` : ''}
1508
- </p>
1509
- ) : null}
1510
- </div>
1511
- {choice.selectable ? (
1512
- <button
1513
- type="button"
1514
- className={cn.button}
1515
- disabled={Boolean(busy)}
1516
- onClick={() => void guard('wire', async () => {
1517
- setTarget(await api.wireTarget!(connection.id, {
1518
- choice_id: choice.id,
1519
- }));
1520
- })}
1521
- >
1522
- Wire
1523
- </button>
1524
- ) : null}
1525
- </div>
1526
- ))}
1527
- </div>
1528
- ) : null}
1529
-
1530
- {target ? (
1531
- <div className="mt-4 space-y-2 border-t pt-3">
1532
- <p className="text-sm font-medium text-gray-900">{target.name}</p>
1533
- {/* The admin CONFIRMS what discovery proposed. Showing the derived
1534
- config is not a detail — nobody can confirm a URL they were never
1535
- shown, and a confidently wrong one only fails at 3am. */}
1536
- <pre className="overflow-x-auto rounded bg-gray-50 p-2 text-xs text-gray-700">
1537
- {JSON.stringify(target.destination_config, null, 2)}
1538
- </pre>
1539
- {!target.verified ? (
1540
- <button
1541
- type="button"
1542
- className={cn.button}
1543
- disabled={Boolean(busy)}
1544
- onClick={() => void guard('confirm', async () => {
1545
- setTarget(await api.confirmTarget!(connection.id, target.id));
1546
- })}
1547
- >
1548
- Confirm this target
1549
- </button>
1550
- ) : (
1551
- <div className="flex flex-wrap gap-2">
1552
- <p className={cn.muted}>Confirmed.</p>
1553
- {actions.map((available) => (
1554
- <button
1555
- key={available.name}
1556
- type="button"
1557
- className={cn.button}
1558
- disabled={Boolean(busy)}
1559
- onClick={() => void guard('invoke', async () => {
1560
- const result = await api.invokeConnectionAction!(
1561
- connection.id, available.name,
1562
- { destination_id: target.id, records: [] },
1563
- );
1564
- // `accepted` is not `completed`. Saying "done" here would
1565
- // render a success the vendor never reported.
1566
- setNotice(
1567
- result.run_status === 'completed'
1568
- ? 'Finished.'
1569
- : `Accepted — run is ${result.run_status}.`,
1570
- );
1571
- })}
1572
- >
1573
- {available.label}
1574
- </button>
1575
- ))}
1576
- </div>
1577
- )}
1578
- </div>
1579
- ) : null}
1580
- </div>
1581
- );
1582
- }