@startsimpli/integrations 0.2.217 → 0.2.218
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.
- package/package.json +3 -3
- package/src/__tests__/fleet-page.test.tsx +24 -0
- package/src/__tests__/relay-cli.test.ts +1 -1
- package/src/__tests__/share-default-row.test.tsx +44 -0
- package/src/__tests__/shared-with.test.tsx +9 -0
- package/src/__tests__/sync-health.test.ts +70 -0
- package/src/api/_fetch.ts +1 -1
- package/src/api/connections.ts +14 -0
- package/src/components/index.ts +1 -0
- package/src/components/pages/FleetPage.tsx +16 -4
- package/src/components/pages/SyncHealthCard.tsx +42 -0
- package/src/components/pages/connections/ConnectionCard.tsx +5 -0
- package/src/components/pages/connections/ShareDefaultRow.tsx +91 -0
- package/src/components/pages/connections/bound-api.ts +4 -1
- package/src/components/pages/types.ts +11 -0
- package/src/corpus/converse/fleet-view.ts +1 -1
- package/src/corpus/converse/fleet.ts +1 -1
- package/src/corpus/converse/index.ts +2 -0
- package/src/corpus/converse/respond.ts +2 -1
- package/src/corpus/converse/sync-health.ts +96 -0
- package/src/corpus/sharing.ts +9 -6
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.218",
|
|
4
4
|
"description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://startsimpli.com",
|
|
@@ -51,8 +51,8 @@
|
|
|
51
51
|
"@startsimpli/ui-native": ">=0.1.12",
|
|
52
52
|
"react-native-safe-area-context": ">=4.0.0",
|
|
53
53
|
"@startsimpli/ui": "^0.4.208",
|
|
54
|
-
"@startsimpli/
|
|
55
|
-
"@startsimpli/
|
|
54
|
+
"@startsimpli/utils": "^0.4.21",
|
|
55
|
+
"@startsimpli/auth": "^0.4.62"
|
|
56
56
|
},
|
|
57
57
|
"peerDependenciesMeta": {
|
|
58
58
|
"react": {
|
|
@@ -55,3 +55,27 @@ describe('FleetPage', () => {
|
|
|
55
55
|
await waitFor(() => expect(screen.getByTestId('load-error')).toBeTruthy());
|
|
56
56
|
});
|
|
57
57
|
});
|
|
58
|
+
|
|
59
|
+
describe('FleetPage sync health', () => {
|
|
60
|
+
it('shows one row per leg from the connections, with todo-sync from the snapshot', async () => {
|
|
61
|
+
const now = new Date().toISOString();
|
|
62
|
+
const load = async () => payload({ snapshot: { text: 'n', updatedAt: now, view, todoSync: { at: now, ok: false, closed: 0, error: 'relay login expired' } } });
|
|
63
|
+
const loadConnections = async () => ({ results: [{ id: 'lin', connector_name: 'Linear', sync: { state: 'ok' }, sync_status: { status: 'ok', last_pull_at: now, last_push_at: now, pending_count: 3, out_of_sync: true } }] });
|
|
64
|
+
render(<FleetPage load={load} loadConnections={loadConnections} />);
|
|
65
|
+
await waitFor(() => expect(screen.getByTestId('sync-leg-lin:push')).toBeTruthy());
|
|
66
|
+
expect(screen.getByTestId('sync-leg-lin:push').textContent).toContain('3 waiting to send');
|
|
67
|
+
expect(screen.getByTestId('sync-leg-lin:push').getAttribute('data-state')).toBe('behind');
|
|
68
|
+
expect(screen.getByTestId('sync-leg-todo-sync').textContent).toContain('relay login expired');
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('says so when the connections cannot be read', async () => {
|
|
72
|
+
render(<FleetPage load={async () => payload()} loadConnections={async () => { throw new Error('401'); }} />);
|
|
73
|
+
await waitFor(() => expect(screen.getByTestId('sync-health-error').textContent).toContain('401'));
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('shows no sync card when the mount does not pass connections', async () => {
|
|
77
|
+
render(<FleetPage load={async () => payload()} />);
|
|
78
|
+
await waitFor(() => expect(screen.getByTestId('fleet-relay')).toBeTruthy());
|
|
79
|
+
expect(screen.queryByTestId('fleet-sync-health')).toBeNull();
|
|
80
|
+
});
|
|
81
|
+
});
|
|
@@ -32,7 +32,7 @@ describe('fleet inputs for the /fleet page', () => {
|
|
|
32
32
|
it('reads roles.md, the loops ledger and the raw bridge listing; leaves out what is missing', async () => {
|
|
33
33
|
const dir = mkdtempSync(join(tmpdir(), 'rc-'));
|
|
34
34
|
writeFileSync(join(dir, 'roles.md'), '| Role | s | n |');
|
|
35
|
-
const env = { RELAY_ROLES_FILE: join(dir, 'roles.md'), RELAY_LOOPS_FILE: join(dir, 'nope.md'), RELAY_PORTS_FILE: join(dir, 'nope2.md') };
|
|
35
|
+
const env = { RELAY_ROLES_FILE: join(dir, 'roles.md'), RELAY_LOOPS_FILE: join(dir, 'nope.md'), RELAY_PORTS_FILE: join(dir, 'nope2.md'), TODO_SYNC_LAST_RUN: join(dir, 'nope3.json') };
|
|
36
36
|
expect(await readFleetInputs(env, '[live] `a · b · 12345678` g')).toEqual({ roles: '| Role | s | n |', sessions: '[live] `a · b · 12345678` g' });
|
|
37
37
|
});
|
|
38
38
|
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|
3
|
+
import * as React from 'react';
|
|
4
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
|
|
6
|
+
import { ShareDefaultRow, parse, valueOf } from '../components/pages/connections/ShareDefaultRow';
|
|
7
|
+
|
|
8
|
+
afterEach(cleanup);
|
|
9
|
+
const cn = { muted: 'm', error: 'e' };
|
|
10
|
+
const connection = { id: 'c1', share_default: null } as never;
|
|
11
|
+
|
|
12
|
+
describe('ShareDefaultRow', () => {
|
|
13
|
+
it('says only me by default and offers the organisation and its teams', async () => {
|
|
14
|
+
const api = {
|
|
15
|
+
updateConnectionSharing: vi.fn(async () => ({}) as never),
|
|
16
|
+
shareTeams: vi.fn(async () => [{ slug: 'editorial', name: 'Editorial' }]),
|
|
17
|
+
};
|
|
18
|
+
const changed = vi.fn();
|
|
19
|
+
render(<ShareDefaultRow api={api} connection={connection} classNames={cn} onChanged={changed} />);
|
|
20
|
+
expect((screen.getByLabelText('Records are shared with') as HTMLSelectElement).value).toBe('none');
|
|
21
|
+
await waitFor(() => expect(screen.getByText('Editorial (team)')).toBeTruthy());
|
|
22
|
+
fireEvent.change(screen.getByLabelText('Records are shared with'), { target: { value: 'org' } });
|
|
23
|
+
await waitFor(() => expect(api.updateConnectionSharing).toHaveBeenCalledWith('c1', { kind: 'org' }));
|
|
24
|
+
await waitFor(() => expect(changed).toHaveBeenCalled());
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('turns it off with null and shows a failure', async () => {
|
|
28
|
+
const api = { updateConnectionSharing: vi.fn(async () => { throw new Error('tenant down'); }) };
|
|
29
|
+
render(<ShareDefaultRow api={api as never} connection={{ id: 'c1', share_default: { kind: 'org' } } as never} classNames={cn} onChanged={vi.fn()} />);
|
|
30
|
+
fireEvent.change(screen.getByLabelText('Records are shared with'), { target: { value: 'none' } });
|
|
31
|
+
await waitFor(() => expect(api.updateConnectionSharing).toHaveBeenCalledWith('c1', null));
|
|
32
|
+
expect(await screen.findByRole('alert')).toBeTruthy();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('renders nothing for a client without the verb', () => {
|
|
36
|
+
const { container } = render(<ShareDefaultRow api={{}} connection={connection} classNames={cn} onChanged={vi.fn()} />);
|
|
37
|
+
expect(container.textContent).toBe('');
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('maps values both ways', () => {
|
|
41
|
+
expect(parse(valueOf({ kind: 'group', id: 'a:b' }))).toEqual({ kind: 'group', id: 'a:b' });
|
|
42
|
+
expect(parse(valueOf(null))).toBeNull();
|
|
43
|
+
});
|
|
44
|
+
});
|
|
@@ -76,3 +76,12 @@ describe('sharing client', () => {
|
|
|
76
76
|
expect(c.teams).toEqual([]);
|
|
77
77
|
});
|
|
78
78
|
});
|
|
79
|
+
|
|
80
|
+
describe('sharing client with a camelizing http client', () => {
|
|
81
|
+
it('reads mayShare and subjectType', async () => {
|
|
82
|
+
const http = { get: vi.fn(async () => ({ mayShare: true, results: [{ id: '1', subjectType: 'group', subjectId: 'editorial', level: 'viewer' }] })) };
|
|
83
|
+
const r = await listRecordShares(http as never, 'd');
|
|
84
|
+
expect(r.canShare).toBe(true);
|
|
85
|
+
expect(r.shares[0]).toMatchObject({ kind: 'group', subjectId: 'editorial' });
|
|
86
|
+
});
|
|
87
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { buildSyncHealth, type SyncConnectionInput } from '../corpus/converse/sync-health';
|
|
4
|
+
|
|
5
|
+
const NOW = Date.parse('2026-11-26T12:00:00Z');
|
|
6
|
+
const ago = (min: number) => new Date(NOW - min * 60000).toISOString();
|
|
7
|
+
const conn = (over: Partial<SyncConnectionInput>): SyncConnectionInput => ({ id: 'c1', connector_name: 'Gmail', ...over });
|
|
8
|
+
const sync = (over: Record<string, unknown>) => ({ state: 'ok', note: '', records: 10, last_attempt_at: ago(5), last_success_at: ago(5), next_sync_at: new Date(NOW + 600000).toISOString(), interval_minutes: 15, ...over });
|
|
9
|
+
const rows = (c: SyncConnectionInput[], todo: Parameters<typeof buildSyncHealth>[1] = { at: ago(3), ok: true, closed: 0, error: '' }) => buildSyncHealth(c, todo, NOW);
|
|
10
|
+
|
|
11
|
+
describe('buildSyncHealth', () => {
|
|
12
|
+
it('a clean connector is one ok leg with last-success and lag', () => {
|
|
13
|
+
const [leg] = rows([conn({ sync: sync({}) })]).filter((l) => l.key === 'c1');
|
|
14
|
+
expect(leg).toMatchObject({ label: 'Gmail', state: 'ok', lastOkAt: ago(5), lagMs: 5 * 60000, lastError: '' });
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('a failing connector carries the scrubbed last error', () => {
|
|
18
|
+
const [leg] = rows([conn({ sync: sync({ state: 'failing', note: 'The last sync did not finish; it will try again' }), last_error: 'Quota exhausted' })]).filter((l) => l.key === 'c1');
|
|
19
|
+
expect(leg).toMatchObject({ state: 'failing', lastError: 'Quota exhausted' });
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('limited reads as behind with the retry time; reauth and waiting keep their own state', () => {
|
|
23
|
+
const out = rows([
|
|
24
|
+
conn({ id: 'a', sync: sync({ state: 'limited', note: 'The provider is limiting requests' }) }),
|
|
25
|
+
conn({ id: 'b', sync: sync({ state: 'reauth', note: 'Reconnect this account' }) }),
|
|
26
|
+
conn({ id: 'c', sync: sync({ state: 'waiting', last_success_at: null, last_attempt_at: null }) }),
|
|
27
|
+
]);
|
|
28
|
+
const by = Object.fromEntries(out.map((l) => [l.key, l]));
|
|
29
|
+
expect(by.a.state).toBe('behind');
|
|
30
|
+
expect(by.b.state).toBe('reauth');
|
|
31
|
+
expect(by.c).toMatchObject({ state: 'waiting', lastOkAt: null, lagMs: null });
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('an ok connector whose next sync is long overdue is stale, not ok', () => {
|
|
35
|
+
const [leg] = rows([conn({ sync: sync({ next_sync_at: ago(60), interval_minutes: 15 }) })]).filter((l) => l.key === 'c1');
|
|
36
|
+
expect(leg.state).toBe('stale');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('passive connectors are shown but never alarm', () => {
|
|
40
|
+
const [leg] = rows([conn({ sync: sync({ state: 'passive', note: 'Receives data only when sent' }) })]).filter((l) => l.key === 'c1');
|
|
41
|
+
expect(leg.state).toBe('passive');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('a task tracker splits into a pull leg and a push leg with rows behind', () => {
|
|
45
|
+
const out = rows([conn({ id: 'lin', connector_name: 'Linear', sync: sync({}), sync_status: { status: 'ok', last_pull_at: ago(2), last_push_at: ago(40), pending_count: 4, out_of_sync: true, last_error: '', retry_at: null } })]);
|
|
46
|
+
const pull = out.find((l) => l.key === 'lin:pull')!;
|
|
47
|
+
const push = out.find((l) => l.key === 'lin:push')!;
|
|
48
|
+
expect(pull).toMatchObject({ label: 'Linear pull', state: 'ok', lastOkAt: ago(2) });
|
|
49
|
+
expect(push).toMatchObject({ label: 'Linear push', state: 'behind', behind: 4, lastOkAt: ago(40) });
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('a failing task-tracker push shows the error and retry time', () => {
|
|
53
|
+
const out = rows([conn({ id: 'lin', connector_name: 'Linear', sync: sync({}), sync_status: { status: 'error', last_pull_at: ago(1), last_push_at: ago(90), pending_count: 2, out_of_sync: true, last_error: 'HTTP 500', retry_at: ago(-5) } })]);
|
|
54
|
+
expect(out.find((l) => l.key === 'lin:push')).toMatchObject({ state: 'failing', lastError: 'HTTP 500', retryAt: ago(-5), behind: 2 });
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('todo-sync: never reported is waiting, recent is ok, old is stale, failed is failing', () => {
|
|
58
|
+
const t = (todo: Parameters<typeof rows>[1]) => rows([], todo).find((l) => l.key === 'todo-sync')!;
|
|
59
|
+
expect(t(null)).toMatchObject({ state: 'waiting', lastOkAt: null });
|
|
60
|
+
expect(t({ at: ago(4), ok: true, closed: 2, error: '' })).toMatchObject({ state: 'ok', lastOkAt: ago(4), lagMs: 4 * 60000 });
|
|
61
|
+
expect(t({ at: ago(45), ok: true, closed: 0, error: '' }).state).toBe('stale');
|
|
62
|
+
expect(t({ at: ago(2), ok: false, closed: 0, error: 'relay login expired' })).toMatchObject({ state: 'failing', lastError: 'relay login expired' });
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('puts the worst legs first', () => {
|
|
66
|
+
const out = rows([conn({ id: 'ok', sync: sync({}) }), conn({ id: 'bad', sync: sync({ state: 'failing' }) })], null);
|
|
67
|
+
expect(out[0].key).toBe('bad');
|
|
68
|
+
expect(out.at(-1)!.state).not.toBe('failing');
|
|
69
|
+
});
|
|
70
|
+
});
|
package/src/api/_fetch.ts
CHANGED
|
@@ -43,7 +43,7 @@ export function setAuthTokenProvider(
|
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
export interface RequestOptions {
|
|
46
|
-
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
|
46
|
+
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
47
47
|
body?: unknown;
|
|
48
48
|
query?: Record<string, string | number | boolean | undefined | null>;
|
|
49
49
|
headers?: Record<string, string>;
|
package/src/api/connections.ts
CHANGED
|
@@ -45,6 +45,7 @@ import type {
|
|
|
45
45
|
ConnectorCatalogEntry,
|
|
46
46
|
MemberConnectionsApi,
|
|
47
47
|
OAuthStart,
|
|
48
|
+
ShareDefault,
|
|
48
49
|
} from '../components/pages/types';
|
|
49
50
|
import { createRequester, request, type ClientDeps, type Requester } from './_fetch';
|
|
50
51
|
|
|
@@ -217,6 +218,19 @@ function build(request: Requester): MemberConnectionsApi {
|
|
|
217
218
|
});
|
|
218
219
|
},
|
|
219
220
|
|
|
221
|
+
/** Who this account's records are shared with; `null` is private again (Todo ENG-158). */
|
|
222
|
+
updateConnectionSharing(id: string, share: ShareDefault | null): Promise<Connection> {
|
|
223
|
+
return request<Connection>(`${BASE}/${id}/sharing/`, {
|
|
224
|
+
method: 'PUT', body: { share_default: share },
|
|
225
|
+
});
|
|
226
|
+
},
|
|
227
|
+
|
|
228
|
+
/** The teams a default can name: those of the caller's own organisation. */
|
|
229
|
+
async shareTeams(): Promise<Array<{ slug: string; name: string }>> {
|
|
230
|
+
const body = await request<{ results?: Array<{ slug: string; name: string }> }>(`${BASE}/share-teams/`);
|
|
231
|
+
return body.results ?? [];
|
|
232
|
+
},
|
|
233
|
+
|
|
220
234
|
/**
|
|
221
235
|
* DISCONNECT, not delete. One transaction stops the scheduled fetches, revokes
|
|
222
236
|
* every token issued for the account and deletes the stored credential; the
|
package/src/components/index.ts
CHANGED
|
@@ -79,6 +79,7 @@ export { DecisionsPage } from './pages/DecisionsPage';
|
|
|
79
79
|
export type { DecisionsPageProps, DecisionsClassNames } from './pages/DecisionsPage';
|
|
80
80
|
export { FleetPage } from './pages/FleetPage';
|
|
81
81
|
export type { FleetPageProps, FleetPayload } from './pages/FleetPage';
|
|
82
|
+
export { SyncHealthCard } from './pages/SyncHealthCard';
|
|
82
83
|
export type { VoiceRecordButtonProps, VoiceRecordClassNames } from './pages/VoiceRecordButton';
|
|
83
84
|
export * from './pages/home';
|
|
84
85
|
export * from './pages/questions';
|
|
@@ -9,10 +9,17 @@ import * as React from 'react';
|
|
|
9
9
|
|
|
10
10
|
import { ageWords, FLEET_FRESH_MS } from '../../corpus/converse/fleet';
|
|
11
11
|
import type { FleetSession, FleetView } from '../../corpus/converse/fleet-view';
|
|
12
|
+
import { buildSyncHealth, type SyncConnectionInput, type TodoSyncRecord } from '../../corpus/converse/sync-health';
|
|
13
|
+
import { SyncHealthCard } from './SyncHealthCard';
|
|
12
14
|
import { LoadError } from '../LoadError';
|
|
13
15
|
|
|
14
|
-
export interface FleetPayload { snapshot: { text: string; updatedAt: string; view: FleetView | null } | null }
|
|
15
|
-
export interface FleetPageProps {
|
|
16
|
+
export interface FleetPayload { snapshot: { text: string; updatedAt: string; view: FleetView | null; todoSync?: TodoSyncRecord | null } | null }
|
|
17
|
+
export interface FleetPageProps {
|
|
18
|
+
load: () => Promise<FleetPayload>;
|
|
19
|
+
/** The member's own connections (`connectionsMe.connections`); when given, the page shows one Sync health row per leg. */
|
|
20
|
+
loadConnections?: () => Promise<{ results: SyncConnectionInput[] }>;
|
|
21
|
+
refreshMs?: number;
|
|
22
|
+
}
|
|
16
23
|
|
|
17
24
|
function SessionRow({ s, testId }: { s: FleetSession; testId?: string }) {
|
|
18
25
|
return (
|
|
@@ -91,16 +98,21 @@ function FleetBody({ view }: { view: FleetView }) {
|
|
|
91
98
|
);
|
|
92
99
|
}
|
|
93
100
|
|
|
94
|
-
export function FleetPage({ load, refreshMs = 30000 }: FleetPageProps) {
|
|
101
|
+
export function FleetPage({ load, loadConnections, refreshMs = 30000 }: FleetPageProps) {
|
|
95
102
|
const [data, setData] = React.useState<FleetPayload | undefined>();
|
|
103
|
+
const [conns, setConns] = React.useState<SyncConnectionInput[] | undefined>();
|
|
104
|
+
const [connsError, setConnsError] = React.useState<string | null>(null);
|
|
96
105
|
const [error, setError] = React.useState<string | null>(null);
|
|
97
106
|
const [, tick] = React.useState(0);
|
|
98
|
-
const run = React.useCallback(() => { load().then((d) => { setData(d); setError(null); }).catch((e) => setError(e instanceof Error ? e.message : 'Could not load.'));
|
|
107
|
+
const run = React.useCallback(() => { load().then((d) => { setData(d); setError(null); }).catch((e) => setError(e instanceof Error ? e.message : 'Could not load.'));
|
|
108
|
+
loadConnections?.().then((c) => { setConns(c.results); setConnsError(null); }).catch((e) => setConnsError(e instanceof Error ? e.message : 'Could not load.')); }, [load, loadConnections]);
|
|
99
109
|
React.useEffect(() => { run(); const t = setInterval(() => { run(); tick((n) => n + 1); }, refreshMs); return () => clearInterval(t); }, [run, refreshMs]);
|
|
100
110
|
const snap = data?.snapshot;
|
|
101
111
|
const stale = snap ? Date.now() - Date.parse(snap.updatedAt) > FLEET_FRESH_MS : false;
|
|
112
|
+
const legs = React.useMemo(() => (conns ? buildSyncHealth(conns, snap?.todoSync ?? null, Date.now()) : null), [conns, snap, data]);
|
|
102
113
|
return (
|
|
103
114
|
<div className="space-y-4">
|
|
115
|
+
{loadConnections ? <SyncHealthCard legs={legs} error={connsError} /> : null}
|
|
104
116
|
{error ? <LoadError what="the fleet" message={error} onRetry={run} /> : null}
|
|
105
117
|
{data && !snap ? <div className="rounded-xl border border-gray-200 bg-white p-6 text-center" data-testid="fleet-empty"><p className="font-medium text-gray-900">The relay has not posted a fleet snapshot yet.</p></div> : null}
|
|
106
118
|
{snap ? (
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
/** Sync health (Fleet page): one row per sync leg, worst first. Draws `buildSyncHealth`; owns no logic. */
|
|
4
|
+
import * as React from 'react';
|
|
5
|
+
|
|
6
|
+
import type { LegState, SyncLeg } from '../../corpus/converse/sync-health';
|
|
7
|
+
|
|
8
|
+
const DOT: Record<LegState, string> = { ok: 'bg-green-500', behind: 'bg-amber-500', stale: 'bg-amber-500', failing: 'bg-red-500', reauth: 'bg-red-500', waiting: 'bg-gray-300', passive: 'bg-gray-300' };
|
|
9
|
+
const WORD: Record<LegState, string> = { ok: 'OK', behind: 'Behind', stale: 'Overdue', failing: 'Failing', reauth: 'Reconnect', waiting: 'Not run yet', passive: 'Receive-only' };
|
|
10
|
+
|
|
11
|
+
export function lagWords(ms: number | null): string {
|
|
12
|
+
if (ms === null) return 'never';
|
|
13
|
+
const m = Math.round(ms / 60000);
|
|
14
|
+
if (m < 1) return 'just now';
|
|
15
|
+
if (m < 60) return `${m} min ago`;
|
|
16
|
+
const h = Math.round(m / 60);
|
|
17
|
+
return h < 36 ? `${h} h ago` : `${Math.round(h / 24)} d ago`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function SyncHealthCard({ legs, error }: { legs: SyncLeg[] | null; error?: string | null }) {
|
|
21
|
+
const bad = legs?.filter((l) => l.state === 'failing' || l.state === 'reauth' || l.state === 'stale' || l.state === 'behind').length ?? 0;
|
|
22
|
+
return (
|
|
23
|
+
<section className={`rounded-xl border p-4 ${bad ? 'border-amber-300 bg-amber-50' : 'border-gray-200 bg-white'}`} data-testid="fleet-sync-health">
|
|
24
|
+
<h2 className="mb-1 text-sm font-semibold uppercase tracking-wide text-gray-500">Sync health{legs ? ` (${bad ? `${bad} need a look` : 'all fine'})` : ''}</h2>
|
|
25
|
+
{error ? <p className="text-sm text-red-700" data-testid="sync-health-error">Could not read the connections: {error}</p> : null}
|
|
26
|
+
{!legs && !error ? <p className="text-sm text-gray-500">Loading…</p> : null}
|
|
27
|
+
{legs ? (
|
|
28
|
+
<ul className="divide-y divide-gray-100 text-sm">
|
|
29
|
+
{legs.map((l) => (
|
|
30
|
+
<li key={l.key} className="flex flex-wrap items-baseline gap-x-2 py-1.5" data-testid={`sync-leg-${l.key}`} data-state={l.state}>
|
|
31
|
+
<span className={`h-2 w-2 shrink-0 self-center rounded-full ${DOT[l.state]}`} />
|
|
32
|
+
<span className="font-medium text-gray-900">{l.label}</span>
|
|
33
|
+
<span className="text-gray-700">{WORD[l.state]}</span>
|
|
34
|
+
<span className="text-xs text-gray-500">last ok {lagWords(l.lagMs)}{l.behind ? ` · ${l.behind} waiting to send` : ''}{l.retryAt ? ` · retries ${new Date(l.retryAt).toLocaleTimeString()}` : ''}</span>
|
|
35
|
+
{l.lastError ? <span className="w-full pl-4 text-xs text-red-700">{l.lastError}</span> : l.note && l.state !== 'ok' ? <span className="w-full pl-4 text-xs text-gray-500">{l.note}</span> : null}
|
|
36
|
+
</li>
|
|
37
|
+
))}
|
|
38
|
+
</ul>
|
|
39
|
+
) : null}
|
|
40
|
+
</section>
|
|
41
|
+
);
|
|
42
|
+
}
|
|
@@ -9,6 +9,7 @@ import { TaskTrackerSettings } from '../task-tracker/TaskTrackerSettings';
|
|
|
9
9
|
import type { Connection, ConnectionChoice, ConnectionRun, ConnectionTarget, ConnectorAction, ConnectorCatalogEntry } from '../types';
|
|
10
10
|
import { CapabilityPicker, orderCapabilities } from './CapabilityPicker';
|
|
11
11
|
import { ConnectionSettingsForm, ReplaceKeyForm } from './ConnectionForms';
|
|
12
|
+
import { ShareDefaultRow } from './ShareDefaultRow';
|
|
12
13
|
import type { BoundApi } from './bound-api';
|
|
13
14
|
import { DEFAULTS, RUN_KIND_COPY } from './copy';
|
|
14
15
|
|
|
@@ -251,6 +252,10 @@ export function ConnectionCard({
|
|
|
251
252
|
</div>
|
|
252
253
|
</div>
|
|
253
254
|
|
|
255
|
+
{personal && api.updateConnectionSharing ? (
|
|
256
|
+
<ShareDefaultRow api={api} connection={connection} classNames={cn} onChanged={onChanged} />
|
|
257
|
+
) : null}
|
|
258
|
+
|
|
254
259
|
{activityOpen ? (
|
|
255
260
|
<div className="mt-3 space-y-2 border-t pt-3" role="group"
|
|
256
261
|
aria-label="Recent activity">
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WHO THE RECORDS FROM THIS ACCOUNT ARE SHARED WITH (Todo ENG-158).
|
|
3
|
+
*
|
|
4
|
+
* One row on a person's own connection card, not a panel: "Only me", "Everyone in
|
|
5
|
+
* my organisation", or one of the organisation's teams. Changing it applies to
|
|
6
|
+
* what the account already brought in and to everything it brings later; turning
|
|
7
|
+
* it off takes back exactly what it shared, and never a share made by hand.
|
|
8
|
+
*/
|
|
9
|
+
import * as React from 'react';
|
|
10
|
+
|
|
11
|
+
import type { Connection, MemberConnectionsApi, ShareDefault } from '../types';
|
|
12
|
+
|
|
13
|
+
type Slots = Record<'muted' | 'error', string>;
|
|
14
|
+
const SELECT = 'rounded-md border border-gray-300 bg-white px-2 py-1 text-sm text-gray-900';
|
|
15
|
+
|
|
16
|
+
const ONLY_ME = 'none';
|
|
17
|
+
const ORG = 'org';
|
|
18
|
+
|
|
19
|
+
export function valueOf(share: ShareDefault | null | undefined): string {
|
|
20
|
+
if (!share) return ONLY_ME;
|
|
21
|
+
return share.kind === 'org' ? ORG : `group:${share.id}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function parse(value: string): ShareDefault | null {
|
|
25
|
+
if (value === ONLY_ME) return null;
|
|
26
|
+
if (value === ORG) return { kind: 'org' };
|
|
27
|
+
return { kind: 'group', id: value.slice('group:'.length) };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function ShareDefaultRow({
|
|
31
|
+
api, connection, classNames: cn, onChanged,
|
|
32
|
+
}: {
|
|
33
|
+
api: Pick<MemberConnectionsApi, 'updateConnectionSharing' | 'shareTeams'>;
|
|
34
|
+
connection: Connection;
|
|
35
|
+
classNames: Slots;
|
|
36
|
+
onChanged: () => void;
|
|
37
|
+
}) {
|
|
38
|
+
const [teams, setTeams] = React.useState<Array<{ slug: string; name: string }>>([]);
|
|
39
|
+
const [busy, setBusy] = React.useState(false);
|
|
40
|
+
const [error, setError] = React.useState('');
|
|
41
|
+
const apiRef = React.useRef(api);
|
|
42
|
+
apiRef.current = api;
|
|
43
|
+
|
|
44
|
+
React.useEffect(() => {
|
|
45
|
+
let live = true;
|
|
46
|
+
apiRef.current.shareTeams?.()
|
|
47
|
+
.then((rows) => { if (live) setTeams(rows); })
|
|
48
|
+
.catch(() => { /* only the team options are lost */ });
|
|
49
|
+
return () => { live = false; };
|
|
50
|
+
}, []);
|
|
51
|
+
|
|
52
|
+
if (!api.updateConnectionSharing) return null;
|
|
53
|
+
const current = valueOf(connection.share_default);
|
|
54
|
+
const known = connection.share_default?.kind === 'group'
|
|
55
|
+
&& !teams.some((t) => t.slug === (connection.share_default as { id: string }).id);
|
|
56
|
+
|
|
57
|
+
async function change(value: string) {
|
|
58
|
+
setBusy(true);
|
|
59
|
+
setError('');
|
|
60
|
+
try {
|
|
61
|
+
await api.updateConnectionSharing!(connection.id, parse(value));
|
|
62
|
+
onChanged();
|
|
63
|
+
} catch (err) {
|
|
64
|
+
setError((err as { message?: string })?.message || 'Sharing could not be changed.');
|
|
65
|
+
} finally {
|
|
66
|
+
setBusy(false);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return (
|
|
71
|
+
<div className="mt-2 flex flex-wrap items-center gap-2" data-testid="share-default">
|
|
72
|
+
<label className="text-sm font-medium text-gray-900" htmlFor={`share-${connection.id}`}>
|
|
73
|
+
Records are shared with
|
|
74
|
+
</label>
|
|
75
|
+
<select
|
|
76
|
+
id={`share-${connection.id}`}
|
|
77
|
+
className={SELECT}
|
|
78
|
+
disabled={busy}
|
|
79
|
+
value={current}
|
|
80
|
+
onChange={(e) => { void change(e.target.value); }}
|
|
81
|
+
>
|
|
82
|
+
<option value={ONLY_ME}>Only me</option>
|
|
83
|
+
<option value={ORG}>Everyone in my organisation</option>
|
|
84
|
+
{teams.map((t) => <option key={t.slug} value={`group:${t.slug}`}>{t.name} (team)</option>)}
|
|
85
|
+
{known ? <option value={current}>A team</option> : null}
|
|
86
|
+
</select>
|
|
87
|
+
{busy ? <span className={cn.muted}>Updating what it already brought in…</span> : null}
|
|
88
|
+
{error ? <p className={cn.error} role="alert">{error}</p> : null}
|
|
89
|
+
</div>
|
|
90
|
+
);
|
|
91
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The injected api as the connection components use it (slugless), and the page props. Split out of ConnectionsPage (bd startsim-ovq7f) with no behaviour change.
|
|
3
3
|
*/
|
|
4
|
-
import type { Connection, ConnectionChoicePage, ConnectionInvokeResult, ConnectionPermissions, ConnectionRun, ConnectionTarget, ConnectionsApi, ConnectorAction, ConnectorCatalogEntry, MemberConnectionRow, MemberConnectionsApi } from '../types';
|
|
4
|
+
import type { Connection, ConnectionChoicePage, ConnectionInvokeResult, ConnectionPermissions, ConnectionRun, ConnectionTarget, ConnectionsApi, ConnectorAction, ConnectorCatalogEntry, MemberConnectionRow, MemberConnectionsApi, ShareDefault } from '../types';
|
|
5
5
|
|
|
6
6
|
export type ClassNames = Partial<Record<
|
|
7
7
|
'root' | 'section' | 'heading' | 'card' | 'button' | 'muted' | 'error', string
|
|
@@ -71,6 +71,9 @@ export interface BoundApi {
|
|
|
71
71
|
updateConnectionConfig?(
|
|
72
72
|
id: string, config: Record<string, unknown>,
|
|
73
73
|
): Promise<Connection>;
|
|
74
|
+
/** Personal mode only: who this account's records are shared with (Todo ENG-158). */
|
|
75
|
+
updateConnectionSharing?(id: string, share: ShareDefault | null): Promise<Connection>;
|
|
76
|
+
shareTeams?(): Promise<Array<{ slug: string; name: string }>>;
|
|
74
77
|
connectionChoices?(id: string, params?: { kind?: string; cursor?: string }):
|
|
75
78
|
Promise<ConnectionChoicePage>;
|
|
76
79
|
/** Task-tracker connections: sync now (bd startsim-el0zf). */
|
|
@@ -158,6 +158,8 @@ export interface Connection {
|
|
|
158
158
|
sync?: Record<string, unknown>;
|
|
159
159
|
/** Why the newest sync run failed or only partly worked, scrubbed; '' when it was clean. */
|
|
160
160
|
last_error?: string;
|
|
161
|
+
/** Task-tracker connections only: the sync engine's snapshot (pull/push times, rows pending, last error, retry time). */
|
|
162
|
+
sync_status?: Record<string, unknown> | null;
|
|
161
163
|
last_checked_at?: string | null;
|
|
162
164
|
/**
|
|
163
165
|
* WHAT THE SERVER WANTS THE PERSON WHO JUST SAVED TO KNOW. Present on the
|
|
@@ -169,8 +171,13 @@ export interface Connection {
|
|
|
169
171
|
* connector does, so only the server can say it. Rendered verbatim.
|
|
170
172
|
*/
|
|
171
173
|
notices?: string[];
|
|
174
|
+
/** Who this account's records are shared with beyond its owner; absent or null means only the owner. */
|
|
175
|
+
share_default?: ShareDefault | null;
|
|
172
176
|
}
|
|
173
177
|
|
|
178
|
+
/** `org` is the owner's own organisation; `group` is one of its teams (by slug). */
|
|
179
|
+
export type ShareDefault = { kind: 'org' } | { kind: 'group'; id: string };
|
|
180
|
+
|
|
174
181
|
/** What to RENDER, never what to allow. The server refuses on its own. */
|
|
175
182
|
export interface ConnectionPermissions {
|
|
176
183
|
view: boolean;
|
|
@@ -441,6 +448,10 @@ export interface MemberConnectionsApi {
|
|
|
441
448
|
updateConnectionConfig?(
|
|
442
449
|
id: string, config: Record<string, unknown>,
|
|
443
450
|
): Promise<Connection>;
|
|
451
|
+
/** Who this account's records are shared with (Todo ENG-158). `null` makes them private again. Optional for older clients. */
|
|
452
|
+
updateConnectionSharing?(id: string, share: ShareDefault | null): Promise<Connection>;
|
|
453
|
+
/** The teams a default can name (the owner's own organisation). Optional; without it only "my organisation" is offered. */
|
|
454
|
+
shareTeams?(): Promise<Array<{ slug: string; name: string }>>;
|
|
444
455
|
checkConnection(id: string): Promise<{
|
|
445
456
|
ok: boolean; account_label: string; detail: string; reason?: string; next_step?: string;
|
|
446
457
|
}>;
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* `roles.md` (who leads what), the open-loops ledger (what waits on whom) and `bridge find ""` (who is live and what each
|
|
4
4
|
* is for). This module is the ONE parser: relay -> role leads -> the sessions each lead owns, then everyone else.
|
|
5
5
|
*/
|
|
6
|
-
export interface FleetInputs { roles?: string; loops?: string; sessions?: string; ports?: string }
|
|
6
|
+
export interface FleetInputs { roles?: string; loops?: string; sessions?: string; ports?: string; /** JSON: todo-sync's last-run record. */ todo_sync?: string }
|
|
7
7
|
export interface FleetSection { title: string; items: string[] }
|
|
8
8
|
export interface FleetPort { project: string; range: string; base: string; url: string | null; notes: string }
|
|
9
9
|
|
|
@@ -18,7 +18,7 @@ export interface FleetSnapshot { text: string; updatedAt: string; inputs?: Fleet
|
|
|
18
18
|
export function cleanFleetInputs(raw: unknown): FleetInputs | undefined {
|
|
19
19
|
if (!raw || typeof raw !== 'object') return undefined;
|
|
20
20
|
const out: FleetInputs = {};
|
|
21
|
-
for (const k of ['roles', 'loops', 'sessions', 'ports'] as const) {
|
|
21
|
+
for (const k of ['roles', 'loops', 'sessions', 'ports', 'todo_sync'] as const) {
|
|
22
22
|
const v = (raw as Record<string, unknown>)[k];
|
|
23
23
|
if (typeof v === 'string' && v.trim()) out[k] = v.slice(0, MAX_FLEET_INPUT);
|
|
24
24
|
}
|
|
@@ -31,6 +31,8 @@ export { routeUtterance, parseRoute } from './route';
|
|
|
31
31
|
export type { ConverseRoute } from './route';
|
|
32
32
|
export { cleanFleetInputs, saveFleetSnapshot, loadFleetSnapshot, fleetExternalId, FLEET_SOURCE, ageWords, FLEET_FRESH_MS } from './fleet';
|
|
33
33
|
export type { FleetSnapshot } from './fleet';
|
|
34
|
+
export { buildSyncHealth, parseTodoSyncRecord, todoSyncLeg, TODO_SYNC_STALE_MS } from './sync-health';
|
|
35
|
+
export type { LegState, SyncConnectionInput, SyncLeg, TodoSyncRecord } from './sync-health';
|
|
34
36
|
export { buildFleetView, parseBridgeFind, parseLoops, parsePorts, parseRoles } from './fleet-view';
|
|
35
37
|
export type { FleetInputs, FleetLead, FleetPort, FleetSection, FleetSession, FleetView, RoleRow } from './fleet-view';
|
|
36
38
|
export { PASSED_TO_RELAY, NO_FLEET_STATUS, NO_FILLER } from './brain';
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* POST /corpus/converse/end JSON {conversation_id}
|
|
5
5
|
* GET /corpus/converse/<id>/turn/<n>/audio[?who=user] a turn's recording, to its owner only
|
|
6
6
|
*/
|
|
7
|
+
import { parseTodoSyncRecord } from './sync-health';
|
|
7
8
|
import { isTimeZone } from '../spoken-time';
|
|
8
9
|
import { voiceErrorResponse } from '../voice-manage';
|
|
9
10
|
import { handleConverseEnd, handleConverseTurn } from './handle';
|
|
@@ -150,7 +151,7 @@ export async function converseFleetStatusResponse(request: Request, deps: Conver
|
|
|
150
151
|
export async function converseFleetViewResponse(deps: ConverseDeps): Promise<Response> {
|
|
151
152
|
try {
|
|
152
153
|
const snap = await loadFleetSnapshot(deps);
|
|
153
|
-
const body = snap ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view: snap.inputs ? buildFleetView(snap.inputs) : null } } : { snapshot: null };
|
|
154
|
+
const body = snap ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view: snap.inputs ? buildFleetView(snap.inputs) : null, todoSync: parseTodoSyncRecord(snap.inputs?.todo_sync) } } : { snapshot: null };
|
|
154
155
|
return Response.json(body, { headers: { 'cache-control': 'no-store' } });
|
|
155
156
|
} catch (error) {
|
|
156
157
|
return failure(error);
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One row per sync leg for the Fleet page and the `todo-sync health` CLI (bd startsim-nghko.1). A pure fold over state the
|
|
3
|
+
* server already computes: `sync` (sync_summary) and `sync_status` (task_sync snapshot) on each member connection, plus the
|
|
4
|
+
* last-run record todo-sync writes on the Mac. No new alarm: the relay reads it on /fleet.
|
|
5
|
+
*/
|
|
6
|
+
export type LegState = 'ok' | 'behind' | 'stale' | 'failing' | 'reauth' | 'waiting' | 'passive';
|
|
7
|
+
|
|
8
|
+
export interface SyncConnectionInput {
|
|
9
|
+
id: string;
|
|
10
|
+
connector_name?: string;
|
|
11
|
+
last_error?: string;
|
|
12
|
+
sync?: Record<string, unknown> | null;
|
|
13
|
+
sync_status?: Record<string, unknown> | null;
|
|
14
|
+
}
|
|
15
|
+
export interface TodoSyncRecord { at: string; ok: boolean; closed: number; error: string }
|
|
16
|
+
export interface SyncLeg {
|
|
17
|
+
key: string;
|
|
18
|
+
label: string;
|
|
19
|
+
state: LegState;
|
|
20
|
+
lastOkAt: string | null;
|
|
21
|
+
/** Milliseconds since the last success; null when it never succeeded. */
|
|
22
|
+
lagMs: number | null;
|
|
23
|
+
/** Rows still waiting to go out (push legs). */
|
|
24
|
+
behind: number;
|
|
25
|
+
lastError: string;
|
|
26
|
+
retryAt: string | null;
|
|
27
|
+
note: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** todo-sync runs every 10 minutes (LaunchAgent); three missed runs is stale. */
|
|
31
|
+
export const TODO_SYNC_STALE_MS = 30 * 60000;
|
|
32
|
+
const ORDER: LegState[] = ['failing', 'reauth', 'stale', 'behind', 'waiting', 'ok', 'passive'];
|
|
33
|
+
|
|
34
|
+
const str = (v: unknown) => (typeof v === 'string' && v ? v : null);
|
|
35
|
+
const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
36
|
+
const lag = (at: string | null, now: number) => { const t = at ? Date.parse(at) : NaN; return Number.isFinite(t) ? Math.max(0, now - t) : null; };
|
|
37
|
+
const leg = (p: Partial<SyncLeg> & Pick<SyncLeg, 'key' | 'label' | 'state'>, now: number): SyncLeg => ({
|
|
38
|
+
lastOkAt: null, behind: 0, lastError: '', retryAt: null, note: '', ...p, lagMs: lag(p.lastOkAt ?? null, now),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
function connectorLeg(c: SyncConnectionInput, now: number): SyncLeg {
|
|
42
|
+
const s = (c.sync ?? {}) as Record<string, unknown>;
|
|
43
|
+
const label = c.connector_name ?? c.id;
|
|
44
|
+
const lastOkAt = str(s.last_success_at);
|
|
45
|
+
const raw = String(s.state ?? 'waiting');
|
|
46
|
+
let state: LegState = raw === 'limited' ? 'behind' : (['ok', 'failing', 'reauth', 'waiting', 'passive'].includes(raw) ? (raw as LegState) : 'waiting');
|
|
47
|
+
const next = str(s.next_sync_at) ? Date.parse(String(s.next_sync_at)) : NaN;
|
|
48
|
+
const interval = num(s.interval_minutes) * 60000;
|
|
49
|
+
if (state === 'ok' && Number.isFinite(next) && interval && now - next > 2 * interval) state = 'stale';
|
|
50
|
+
return leg({
|
|
51
|
+
key: c.id, label, state, lastOkAt, note: String(s.note ?? ''),
|
|
52
|
+
lastError: state === 'failing' || state === 'reauth' ? (c.last_error || String(s.note ?? '')) : '',
|
|
53
|
+
retryAt: state === 'behind' ? str(s.next_sync_at) : null,
|
|
54
|
+
}, now);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function trackerLegs(c: SyncConnectionInput, now: number): SyncLeg[] {
|
|
58
|
+
const st = c.sync_status as Record<string, unknown>;
|
|
59
|
+
const label = c.connector_name ?? c.id;
|
|
60
|
+
const status = String(st.status ?? 'ok');
|
|
61
|
+
const error = String(st.last_error ?? '');
|
|
62
|
+
const retryAt = str(st.retry_at);
|
|
63
|
+
const pending = num(st.pending_count);
|
|
64
|
+
const broken = status === 'error' || status === 'needs_reauth';
|
|
65
|
+
const paused = status === 'rate_limited';
|
|
66
|
+
const pullAt = str(st.last_pull_at);
|
|
67
|
+
const pushAt = str(st.last_push_at);
|
|
68
|
+
const pull = leg({ key: `${c.id}:pull`, label: `${label} pull`, state: status === 'needs_reauth' ? 'reauth' : paused ? 'behind' : pullAt ? 'ok' : 'waiting', lastOkAt: pullAt, lastError: broken ? error : '', retryAt }, now);
|
|
69
|
+
const pushState: LegState = status === 'needs_reauth' ? 'reauth' : broken ? 'failing' : paused || (pending > 0 && st.out_of_sync) ? 'behind' : pushAt || !pending ? 'ok' : 'waiting';
|
|
70
|
+
const push = leg({ key: `${c.id}:push`, label: `${label} push`, state: pushState, lastOkAt: pushAt, behind: pending, lastError: broken || paused ? error : '', retryAt }, now);
|
|
71
|
+
return [pull, push];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function todoSyncLeg(rec: TodoSyncRecord | null, now: number): SyncLeg {
|
|
75
|
+
const base = { key: 'todo-sync', label: 'todo-sync (to-dos closed by merged PRs)' };
|
|
76
|
+
if (!rec || !Number.isFinite(Date.parse(rec.at))) return leg({ ...base, state: 'waiting', note: 'Has not reported yet' }, now);
|
|
77
|
+
if (!rec.ok) return leg({ ...base, state: 'failing', lastError: rec.error || 'The last run failed', note: `Last tried ${rec.at}` }, now);
|
|
78
|
+
const old = now - Date.parse(rec.at) > TODO_SYNC_STALE_MS;
|
|
79
|
+
return leg({ ...base, state: old ? 'stale' : 'ok', lastOkAt: rec.at, note: old ? 'No run in over 30 minutes; the LaunchAgent may be off' : `Closed ${rec.closed} last run` }, now);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function buildSyncHealth(connections: SyncConnectionInput[], todoSync: TodoSyncRecord | null, now: number): SyncLeg[] {
|
|
83
|
+
const legs = connections.flatMap((c) => (c.sync_status ? trackerLegs(c, now) : [connectorLeg(c, now)]));
|
|
84
|
+
legs.push(todoSyncLeg(todoSync, now));
|
|
85
|
+
return legs.map((l, i) => ({ l, i })).sort((a, b) => ORDER.indexOf(a.l.state) - ORDER.indexOf(b.l.state) || a.i - b.i).map((x) => x.l);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Parse the JSON string the relay sync carries in the fleet snapshot; null when absent or unreadable. */
|
|
89
|
+
export function parseTodoSyncRecord(raw: unknown): TodoSyncRecord | null {
|
|
90
|
+
try {
|
|
91
|
+
const o = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
92
|
+
if (!o || typeof o !== 'object' || typeof (o as TodoSyncRecord).at !== 'string') return null;
|
|
93
|
+
const r = o as TodoSyncRecord;
|
|
94
|
+
return { at: r.at, ok: r.ok !== false, closed: Number(r.closed) || 0, error: String(r.error ?? '').slice(0, 300) };
|
|
95
|
+
} catch { return null; }
|
|
96
|
+
}
|
package/src/corpus/sharing.ts
CHANGED
|
@@ -55,6 +55,9 @@ const DEFAULTS: Required<SharingPaths> = {
|
|
|
55
55
|
|
|
56
56
|
type Obj = Record<string, unknown>;
|
|
57
57
|
const str = (v: unknown) => (typeof v === 'string' ? v : '');
|
|
58
|
+
/** A key as the tenant spells it, or as a camelizing client hands it back. */
|
|
59
|
+
const pick = (row: Obj, snake: string) =>
|
|
60
|
+
row[snake] ?? row[snake.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase())];
|
|
58
61
|
const rows = (body: unknown): Obj[] => {
|
|
59
62
|
const list = Array.isArray(body) ? body : (body as { results?: unknown })?.results;
|
|
60
63
|
return Array.isArray(list) ? (list.filter((r) => r && typeof r === 'object') as Obj[]) : [];
|
|
@@ -67,17 +70,17 @@ export async function listRecordShares(
|
|
|
67
70
|
): Promise<RecordShares> {
|
|
68
71
|
const p = { ...DEFAULTS, ...paths };
|
|
69
72
|
const body = await http.get<unknown>(p.grants, { params: { entity: documentId, page_size: 100 } });
|
|
70
|
-
const envelope = (body ?? {}) as
|
|
73
|
+
const envelope = (body ?? {}) as Obj;
|
|
71
74
|
const shares: RecordShare[] = [];
|
|
72
75
|
for (const row of rows(body)) {
|
|
73
|
-
const kind = str(row
|
|
76
|
+
const kind = str(pick(row, 'subject_type')) as ShareKind;
|
|
74
77
|
if (!KINDS.includes(kind)) continue; // a public link is publishing, not sharing
|
|
75
78
|
shares.push({
|
|
76
|
-
id: str(row.id), kind, subjectId: str(row
|
|
79
|
+
id: str(row.id), kind, subjectId: str(pick(row, 'subject_id')),
|
|
77
80
|
level: str(row.level) === 'editor' ? 'editor' : 'viewer',
|
|
78
81
|
});
|
|
79
82
|
}
|
|
80
|
-
return { shares, canShare: envelope
|
|
83
|
+
return { shares, canShare: pick(envelope, 'may_share') === true, reason: str(pick(envelope, 'may_share_reason')) || undefined };
|
|
81
84
|
}
|
|
82
85
|
|
|
83
86
|
export async function addRecordShare(
|
|
@@ -111,9 +114,9 @@ export async function listShareChoices(
|
|
|
111
114
|
http.get<unknown>(p.teams).catch(() => null),
|
|
112
115
|
]);
|
|
113
116
|
const w = (who ?? {}) as Obj;
|
|
114
|
-
const orgId = str(w
|
|
117
|
+
const orgId = str(pick(w, 'org_id')) || str((w.org as Obj | undefined)?.id) || str(w.org);
|
|
115
118
|
return {
|
|
116
|
-
org: orgId ? { id: orgId, label: str(w
|
|
119
|
+
org: orgId ? { id: orgId, label: str(pick(w, 'org_name')) || 'Everyone in my organisation' } : undefined,
|
|
117
120
|
people: rows(roster).map((r) => ({ id: str(r.sub), label: str(r.label) || str(r.sub) })).filter((r) => r.id),
|
|
118
121
|
teams: rows(teams).map((r) => ({ id: str(r.slug), label: str(r.name) || str(r.slug) })).filter((r) => r.id),
|
|
119
122
|
};
|