@startsimpli/integrations 0.2.219 → 0.2.221

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.219",
3
+ "version": "0.2.221",
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",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/utils": "^0.4.21",
53
+ "@startsimpli/ui": "^0.4.208",
54
54
  "@startsimpli/auth": "^0.4.62",
55
- "@startsimpli/ui": "^0.4.208"
55
+ "@startsimpli/utils": "^0.4.21"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -0,0 +1,57 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { generateBriefing, type BriefingDeps, type BriefingItem } from '../corpus/briefing';
4
+
5
+ /**
6
+ * startsim-nghko.40: a cold first briefing (no zone sent, none remembered) spent its
7
+ * time in serial tenant round trips BEFORE any model call: up to 5 sequential
8
+ * remembered-zone lookups, then loadItems, then unsureCount, then the cache find.
9
+ * Every tenant call here costs LATENCY ms; the independent ones must overlap.
10
+ */
11
+ const LATENCY = 100;
12
+ const NOW = Date.parse('2026-11-05T14:00:00Z');
13
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
14
+ const item: BriefingItem = { id: 'a', title: 'Do a', status: 'open', ownerSub: 'me', dueAt: '2026-11-05', priority: 2 };
15
+
16
+ function coldDeps(): { deps: BriefingDeps; gets: ReturnType<typeof vi.fn> } {
17
+ const gets = vi.fn(async () => { await sleep(LATENCY); return { results: [] }; });
18
+ const deps: BriefingDeps = {
19
+ http: { get: gets, post: vi.fn(async (_p: string, body: any) => { await sleep(LATENCY); return { id: 1, ...body }; }) } as never,
20
+ orgId: 'org',
21
+ ownerSub: 'me',
22
+ loadItems: async () => { await sleep(LATENCY); return [item]; },
23
+ unsureCount: async () => { await sleep(LATENCY); return 0; },
24
+ synthesize: async () => ({ audio: new Uint8Array([1]), mimeType: 'audio/mpeg', model: 'm', provider: 'p', usage: {} }),
25
+ scriptLlm: null,
26
+ audio: { put: async () => 's3://x', url: async () => 'https://signed.example/x' },
27
+ now: () => NOW,
28
+ name: 'Quinn',
29
+ };
30
+ return { deps, gets };
31
+ }
32
+
33
+ describe('briefing cold-path latency', () => {
34
+ it('overlaps the independent tenant reads: before the script, a cold call costs ~3 round trips, not ~8', async () => {
35
+ const { deps } = coldDeps();
36
+ const started = Date.now();
37
+ await generateBriefing(deps, {});
38
+ const elapsed = Date.now() - started;
39
+ // reads: (zone x5 | items | unsure) in parallel, then the cache find; then save + nothing else serial.
40
+ // 3 reads-phases + 1 save = 4 round trips = ~400ms. Serial was 8 reads + 1 save = ~900ms.
41
+ expect(elapsed).toBeLessThan(LATENCY * 5.5);
42
+ });
43
+
44
+ it('still falls back to UTC-free behaviour: a remembered zone from the nearest day wins', async () => {
45
+ const { deps, gets } = coldDeps();
46
+ gets.mockImplementation(async (_p: string, o: any) => {
47
+ await sleep(5);
48
+ const ext = String(o?.params?.external_id__in ?? '');
49
+ // only the day before `now` (UTC) has a stored row, in Tokyo
50
+ return ext.includes('2026-11-04')
51
+ ? { results: [{ id: 9, external_id: ext, owner_sub: 'me', data: { briefing_context: { timeZone: 'Asia/Tokyo' } } }] }
52
+ : { results: [] };
53
+ });
54
+ const result = await generateBriefing(deps, {});
55
+ expect(result.context.timeZone).toBe('Asia/Tokyo');
56
+ });
57
+ });
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The Connections page paints as each request lands (bd startsim-nghko.37).
3
+ *
4
+ * It used to wait on `Promise.all([catalog, connections])`: the slowest leg held the whole page on
5
+ * "Loading…", and either leg failing replaced everything with one error. These pin the replacement:
6
+ * the connected accounts show the moment THEY arrive, the catalog fills in on its own clock, and each
7
+ * leg fails and retries by itself.
8
+ */
9
+ import { describe, expect, it, vi } from 'vitest';
10
+ import { render, screen, waitFor, within } from '@testing-library/react';
11
+ import userEvent from '@testing-library/user-event';
12
+
13
+ import { ConnectionsPage } from '../components/pages/ConnectionsPage';
14
+ import type { MemberConnectionsApi } from '../components/pages/types';
15
+
16
+ const GOOGLE = {
17
+ id: 'g1', public_id: 'pub-g1', name: 'Google', connector_key: 'google', connector_name: 'Google',
18
+ external_account_id: '', account_label: '', capabilities_enabled: [], config: {}, status: 'connected',
19
+ health: 'ok', auth_mode: 'oauth',
20
+ sync: { state: 'ok', note: '', records: 72, last_attempt_at: null, last_success_at: null,
21
+ next_sync_at: null, interval_minutes: 10, window_days: 14 },
22
+ };
23
+ const CATALOG_ROW = {
24
+ key: 'granola', name: 'Granola', description: 'Meeting notes', auth_mode: 'api_key', allowed: true,
25
+ availability: { available: true, reason: '' }, capabilities: ['poll'], credential_schema: [{ key: 'api_key', label: 'API key', type: 'secret', required: true }],
26
+ };
27
+ const PERMS = { view: true, manage: true, issue_tokens: false };
28
+
29
+ function deferred<T>() {
30
+ let resolve!: (v: T) => void;
31
+ let reject!: (e: unknown) => void;
32
+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
33
+ return { promise, resolve, reject };
34
+ }
35
+
36
+ function api(over: Partial<MemberConnectionsApi>): MemberConnectionsApi {
37
+ return {
38
+ connectorCatalog: vi.fn().mockResolvedValue({ results: [CATALOG_ROW] }),
39
+ connections: vi.fn().mockResolvedValue({ results: [GOOGLE], permissions: PERMS }),
40
+ ...over,
41
+ } as unknown as MemberConnectionsApi;
42
+ }
43
+
44
+ describe('ConnectionsPage — each request paints on its own', () => {
45
+ it('shows the connected accounts while the catalog is still in flight', async () => {
46
+ const catalog = deferred<{ results: unknown[] }>();
47
+ const a = api({ connectorCatalog: vi.fn().mockReturnValue(catalog.promise) as never });
48
+ render(<ConnectionsPage mode="personal" api={a} />);
49
+
50
+ const table = await screen.findByRole('region', { name: 'Source freshness' });
51
+ expect(within(table).getByText('Google')).toBeInTheDocument();
52
+ // The catalog has not answered: its section says so, and does NOT claim nothing is connectable.
53
+ expect(screen.queryByText(/has not opened any connector/i)).toBeNull();
54
+ expect(screen.getByText(/Loading connectors/i)).toBeInTheDocument();
55
+
56
+ catalog.resolve({ results: [CATALOG_ROW] });
57
+ expect(await screen.findByText('Granola')).toBeInTheDocument();
58
+ expect(screen.queryByText(/Loading connectors/i)).toBeNull();
59
+ });
60
+
61
+ it('shows the catalog while the connections are still in flight', async () => {
62
+ const conns = deferred<{ results: unknown[]; permissions: unknown }>();
63
+ const a = api({ connections: vi.fn().mockReturnValue(conns.promise) as never });
64
+ render(<ConnectionsPage mode="personal" api={a} />);
65
+
66
+ expect(await screen.findByText('Granola')).toBeInTheDocument();
67
+ expect(screen.getByText(/Loading your accounts/i)).toBeInTheDocument();
68
+ expect(screen.queryByText(/You have not connected an account yet/i)).toBeNull();
69
+
70
+ conns.resolve({ results: [GOOGLE], permissions: PERMS });
71
+ expect(await screen.findByRole('region', { name: 'Source freshness' })).toBeInTheDocument();
72
+ });
73
+
74
+ it('a failed catalog keeps the accounts and retries only the catalog', async () => {
75
+ const user = userEvent.setup();
76
+ const connectorCatalog = vi.fn()
77
+ .mockRejectedValueOnce(new Error('catalog is down'))
78
+ .mockResolvedValue({ results: [CATALOG_ROW] });
79
+ const connections = vi.fn().mockResolvedValue({ results: [GOOGLE], permissions: PERMS });
80
+ render(<ConnectionsPage mode="personal" api={api({ connectorCatalog, connections } as never)} />);
81
+
82
+ expect(await screen.findByRole('region', { name: 'Source freshness' })).toBeInTheDocument();
83
+ const alert = await screen.findByRole('alert');
84
+ expect(alert).toHaveTextContent(/catalog is down/);
85
+ await user.click(within(alert).getByRole('button', { name: /try again/i }));
86
+
87
+ expect(await screen.findByText('Granola')).toBeInTheDocument();
88
+ expect(connectorCatalog).toHaveBeenCalledTimes(2);
89
+ expect(connections).toHaveBeenCalledTimes(1);
90
+ });
91
+
92
+ it('failed accounts keep the catalog and retry only the accounts', async () => {
93
+ const user = userEvent.setup();
94
+ const connections = vi.fn()
95
+ .mockRejectedValueOnce(new Error('accounts are down'))
96
+ .mockResolvedValue({ results: [GOOGLE], permissions: PERMS });
97
+ const connectorCatalog = vi.fn().mockResolvedValue({ results: [CATALOG_ROW] });
98
+ render(<ConnectionsPage mode="personal" api={api({ connectorCatalog, connections } as never)} />);
99
+
100
+ expect(await screen.findByText('Granola')).toBeInTheDocument();
101
+ const alert = await screen.findByRole('alert');
102
+ expect(alert).toHaveTextContent(/accounts are down/);
103
+ await user.click(within(alert).getByRole('button', { name: /try again/i }));
104
+
105
+ expect(await screen.findByRole('region', { name: 'Source freshness' })).toBeInTheDocument();
106
+ expect(connections).toHaveBeenCalledTimes(2);
107
+ expect(connectorCatalog).toHaveBeenCalledTimes(1);
108
+ });
109
+
110
+ it('LATENCY BUDGET: first content waits on the accounts leg only, never on the slowest request', async () => {
111
+ const slowCatalog = deferred<{ results: unknown[] }>(); // never answers inside this test
112
+ const a = api({ connectorCatalog: vi.fn().mockReturnValue(slowCatalog.promise) as never });
113
+ const t0 = performance.now();
114
+ render(<ConnectionsPage mode="personal" api={a} />);
115
+ await screen.findByRole('region', { name: 'Source freshness' });
116
+ // The accounts mock answers at once; with the catalog hung forever the page must still be useful.
117
+ expect(performance.now() - t0).toBeLessThan(1000);
118
+ await waitFor(() => expect(screen.queryByText(/Loading your accounts/i)).toBeNull());
119
+ });
120
+ });
@@ -39,6 +39,35 @@ const MICROSOFT = connection('m1', 'Microsoft', {
39
39
  last_success_at: null, next_sync_at: null, interval_minutes: null, window_days: 14 },
40
40
  });
41
41
 
42
+ const CONNECTING = connection('m2', 'Outlook', {
43
+ status: 'needs_reauth',
44
+ sync: { state: 'connecting', note: 'Finish signing in with the provider to connect', records: 0, last_attempt_at: null,
45
+ last_success_at: null, next_sync_at: null, interval_minutes: null, window_days: 14 },
46
+ });
47
+ const REFUSED = connection('m3', 'Outlook work', {
48
+ status: 'needs_reauth',
49
+ sync: { state: 'reauth', note: "Microsoft refused this sign-in: StartSimpli's Microsoft app is not set up for accounts outside its own organization yet.",
50
+ records: 0, last_attempt_at: null, last_success_at: null, next_sync_at: null, interval_minutes: null, window_days: 14 },
51
+ });
52
+
53
+ describe('ConnectionsPage — a connect that has not finished', () => {
54
+ it('says Connecting, not Reconnect needed, while the member is still at the provider', async () => {
55
+ render(<ConnectionsPage mode="personal" api={api([CONNECTING])} />);
56
+ const table = await screen.findByRole('region', { name: 'Source freshness' });
57
+ const row = within(table).getByText('Outlook').closest('tr')!;
58
+ expect(within(row).getByText('Connecting…')).toBeInTheDocument();
59
+ expect(within(row).queryByText('Reconnect needed')).toBeNull();
60
+ });
61
+
62
+ it('shows why a refused connect needs reconnecting', async () => {
63
+ render(<ConnectionsPage mode="personal" api={api([REFUSED])} />);
64
+ const table = await screen.findByRole('region', { name: 'Source freshness' });
65
+ const row = within(table).getByText('Outlook work').closest('tr')!;
66
+ expect(within(row).getByText('Reconnect needed')).toBeInTheDocument();
67
+ expect(within(row).getByText(/not set up for accounts outside its own organization/)).toBeInTheDocument();
68
+ });
69
+ });
70
+
42
71
  describe('ConnectionsPage — the sources sync table', () => {
43
72
  it('lists each synced connection as a row: status, records with its window, last and next sync', async () => {
44
73
  render(<ConnectionsPage mode="personal" api={api([GOOGLE, MICROSOFT])} />);
@@ -0,0 +1,67 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { dueCell } from '../components/table/todo-model';
3
+ import { resolveStatedDate } from '../corpus/stated-date';
4
+
5
+ const DAY = 86_400_000;
6
+ const NOW = Date.parse('2026-11-27T15:00:00Z');
7
+ const CALL = '2026-11-25T17:00:00Z'; // the call, two days ago
8
+
9
+ describe('a suggested to-do is never "late"', () => {
10
+ it('shows the date, not N days late, and no overdue tone', () => {
11
+ const cell = dueCell({ dueAt: new Date(NOW - 26 * DAY).toISOString(), status: 'suggested' }, NOW, 'UTC');
12
+ expect(cell.text).not.toMatch(/late/);
13
+ expect(cell.tone).toBe('plain');
14
+ });
15
+ it('an unknown due date stays empty', () => {
16
+ expect(dueCell({ dueAt: null, status: 'suggested' }, NOW, 'UTC')).toMatchObject({ text: '–', tone: 'none' });
17
+ });
18
+ it('an accepted open to-do still says how late', () => {
19
+ expect(dueCell({ dueAt: new Date(NOW - 3 * DAY).toISOString(), status: 'open' }, NOW, 'UTC')).toMatchObject({ text: '3 days late', tone: 'overdue' });
20
+ });
21
+ });
22
+
23
+ describe('relative phrases resolve from the call date (Wed 2026-11-25), not today', () => {
24
+ const day = (t: string) => resolveStatedDate(t, CALL)?.date ?? null;
25
+ it('today / tomorrow / weekday / in N days', () => {
26
+ expect(day('send it today')).toBe('2026-11-25');
27
+ expect(day('send it tomorrow')).toBe('2026-11-26');
28
+ expect(day('send it by Sunday')).toBe('2026-11-29');
29
+ expect(day('review it in 3 days')).toBe('2026-11-28');
30
+ });
31
+ it('absolute dates keep year logic', () => {
32
+ expect(day('due by Nov 24')).toBe('2026-11-24'); // said as a deadline, so kept even though it is before the call
33
+ expect(day('due by 2027-01-05')).toBe('2027-01-05');
34
+ });
35
+ it('unknown / vague stays empty', () => {
36
+ expect(day('sometime next week')).toBeNull();
37
+ expect(day('we should follow up')).toBeNull();
38
+ });
39
+ });
40
+
41
+ import { isOverdue } from '../corpus/work-item-logic';
42
+ import { dueLabel } from '../components/pages/home/CompactItemRow';
43
+ describe('other "late" surfaces', () => {
44
+ it('a suggestion is never overdue', () => {
45
+ expect(isOverdue({ dueAt: new Date(NOW - 5 * DAY).toISOString(), status: 'suggested' }, NOW)).toBe(false);
46
+ expect(isOverdue({ dueAt: new Date(NOW - 5 * DAY).toISOString(), status: 'open' }, NOW)).toBe(true);
47
+ });
48
+ it('compact row label for a suggestion is a date', () => {
49
+ expect(dueLabel(-26, '2026-11-01', 'suggested')).toBe('Nov 1');
50
+ expect(dueLabel(-2, '2026-11-25', 'open')).toBe('2d late');
51
+ });
52
+ });
53
+
54
+ describe('a date before the call is history, not a deadline', () => {
55
+ const day = (t: string) => resolveStatedDate(t, CALL)?.date ?? null;
56
+ it('absolute dates earlier than the call day stay empty', () => {
57
+ expect(day('Follow up on the invoice we sent Oct 31')).toBeNull();
58
+ expect(day('Review the 2026-09-18 draft')).toBeNull();
59
+ });
60
+ it('a past date said as a deadline is kept (it really is overdue)', () => {
61
+ expect(day('signed by 29th Oct')).toBe('2026-10-29');
62
+ });
63
+ it('the call day itself and later dates still resolve', () => {
64
+ expect(day('finish it by Nov 25')).toBe('2026-11-25');
65
+ expect(day('finish it by Dec 3')).toBe('2026-12-03');
66
+ });
67
+ });
@@ -69,33 +69,57 @@ export function ConnectionsPage(props: ConnectionsPageProps) {
69
69
  const [permissions, setPermissions] = React.useState<ConnectionPermissions>({
70
70
  view: true, manage: false, issue_tokens: false,
71
71
  });
72
- const [loadError, setLoadError] = React.useState<string>('');
73
- const [loading, setLoading] = React.useState(true);
72
+ // TWO LEGS, TWO CLOCKS (bd startsim-nghko.37). The accounts list and the catalog are separate
73
+ // requests with separate failure modes: each paints when it lands, fails on its own, and retries
74
+ // alone. Gating the page on both (`Promise.all`) made the slowest request the page's latency and let
75
+ // either failure blank the other half.
76
+ const [catalogError, setCatalogError] = React.useState<string>('');
77
+ const [connectionsError, setConnectionsError] = React.useState<string>('');
78
+ const [catalogLoading, setCatalogLoading] = React.useState(true);
79
+ const [connectionsLoading, setConnectionsLoading] = React.useState(true);
74
80
  /** The synced connection whose own card is open (the table's one action). */
75
81
  const [openId, setOpenId] = React.useState<string | null>(null);
76
82
 
77
- const reload = React.useCallback(async () => {
78
- setLoading(true);
83
+ const loadCatalog = React.useCallback(async () => {
84
+ setCatalogLoading(true);
79
85
  try {
80
- const [cat, conns] = await Promise.all([
81
- // In personal mode this is the ALLOWED catalog, already narrowed by the
82
- // foundry's policy server-side. Rendered as handed: filtering here would
83
- // put the withheld connectors in the browser to be filtered out of.
84
- api.connectorCatalog(),
85
- api.connections(),
86
- ]);
86
+ // In personal mode this is the ALLOWED catalog, already narrowed by the
87
+ // foundry's policy server-side. Rendered as handed: filtering here would
88
+ // put the withheld connectors in the browser to be filtered out of.
89
+ const cat = await api.connectorCatalog();
87
90
  setCatalog(cat.results ?? []);
91
+ setCatalogError('');
92
+ } catch (err) {
93
+ setCatalogError(readFailureMessage(err, personal));
94
+ } finally {
95
+ setCatalogLoading(false);
96
+ }
97
+ }, [api, personal]);
98
+
99
+ const loadConnections = React.useCallback(async () => {
100
+ setConnectionsLoading(true);
101
+ try {
102
+ const conns = await api.connections();
88
103
  setConnections(conns.results ?? []);
89
104
  setPermissions(conns.permissions ?? { view: true, manage: false, issue_tokens: false });
90
- setLoadError('');
105
+ setConnectionsError('');
91
106
  } catch (err) {
92
- setLoadError(readFailureMessage(err, personal));
107
+ setConnectionsError(readFailureMessage(err, personal));
93
108
  } finally {
94
- setLoading(false);
109
+ setConnectionsLoading(false);
95
110
  }
96
111
  }, [api, personal]);
97
112
 
98
- React.useEffect(() => { void reload(); }, [reload]);
113
+ /** After a change (connect, rotate, disconnect, policy flip): both halves can have moved. */
114
+ const reload = React.useCallback(async () => {
115
+ await Promise.all([loadCatalog(), loadConnections()]);
116
+ }, [loadCatalog, loadConnections]);
117
+
118
+ React.useEffect(() => { void loadConnections(); }, [loadConnections]);
119
+ React.useEffect(() => { void loadCatalog(); }, [loadCatalog]);
120
+ /** Still waiting for the FIRST answer; a refresh after a change keeps what is on screen. */
121
+ const loading = connectionsLoading;
122
+ const catalogPending = catalogLoading && catalog.length === 0;
99
123
 
100
124
  const syncRows: SourceFreshness[] = connections.flatMap((connection) => {
101
125
  const sync = readSync(connection as unknown as Record<string, unknown>);
@@ -112,10 +136,6 @@ export function ConnectionsPage(props: ConnectionsPageProps) {
112
136
  } as SourceFreshness];
113
137
  });
114
138
 
115
- if (loadError) {
116
- return <LoadError what="your connections" message={loadError} onRetry={() => { setLoadError(''); void reload(); }} />;
117
- }
118
-
119
139
  return (
120
140
  <div className={cn.root}>
121
141
  <section className={cn.section}>
@@ -126,8 +146,14 @@ export function ConnectionsPage(props: ConnectionsPageProps) {
126
146
  <h2 className={cn.heading}>
127
147
  {personal ? 'Your connected accounts' : 'Connected accounts'}
128
148
  </h2>
129
- {loading && connections.length === 0 ? <p className={cn.muted}>Loading…</p> : null}
130
- {!loading && connections.length === 0 ? (
149
+ {connectionsError ? (
150
+ <LoadError what="your connections" message={connectionsError}
151
+ onRetry={() => { setConnectionsError(''); void loadConnections(); }} />
152
+ ) : null}
153
+ {loading && connections.length === 0 && !connectionsError ? (
154
+ <p className={cn.muted}>{personal ? 'Loading your accounts…' : 'Loading connected accounts…'}</p>
155
+ ) : null}
156
+ {!loading && !connectionsError && connections.length === 0 ? (
131
157
  <p className={cn.muted}>
132
158
  {personal
133
159
  ? 'You have not connected an account yet.'
@@ -163,12 +189,18 @@ export function ConnectionsPage(props: ConnectionsPageProps) {
163
189
  </section>
164
190
 
165
191
  {/* Nothing to offer is no section: a heading over a blank gap reads as a broken page. */}
166
- {(personal ? connectableEntries(catalog, connections) : catalog).length > 0 || (personal && !loading && catalog.length === 0) ? (
192
+ {(personal ? connectableEntries(catalog, connections) : catalog).length > 0 || catalogPending || catalogError
193
+ || (personal && !catalogLoading && catalog.length === 0) ? (
167
194
  <section className={cn.section}>
168
195
  <h2 className={cn.heading}>
169
196
  {personal ? 'Connect your own account' : 'Available connectors'}
170
197
  </h2>
171
- {personal && !loading && catalog.length === 0 ? (
198
+ {catalogError ? (
199
+ <LoadError what="the connector list" message={catalogError}
200
+ onRetry={() => { setCatalogError(''); void loadCatalog(); }} />
201
+ ) : null}
202
+ {catalogPending && !catalogError ? <p className={cn.muted}>Loading connectors…</p> : null}
203
+ {personal && !catalogLoading && !catalogError && catalog.length === 0 ? (
172
204
  <p className={cn.muted}>
173
205
  Your foundry has not opened any connector to members yet. An admin
174
206
  decides which ones you may connect your own account on.
@@ -12,8 +12,9 @@ import { ExternalLinkChip } from '../task-tracker/ExternalLinkChip';
12
12
  import type { Commitment } from '../../../corpus/types';
13
13
 
14
14
  /** "2d late", "today", "tomorrow", "in 3d", else a short date. */
15
- export function dueLabel(days: number | null, due: string | null): string {
15
+ export function dueLabel(days: number | null, due: string | null, status?: string): string {
16
16
  if (days === null || !due) return '';
17
+ if (days < 0 && status === 'suggested') return new Date(`${due}T00:00:00Z`).toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' });
17
18
  if (days < 0) return `${-days}d late`;
18
19
  if (days === 0) return 'today';
19
20
  if (days === 1) return 'tomorrow';
@@ -56,8 +57,8 @@ function MeetingEvidence({ item }: { item: Commitment }) {
56
57
  }
57
58
 
58
59
  export function CompactItemRow({ item, days, due, project, trackerName, onOpen, actions, showStatus = true, guessedDue, below }: CompactItemRowProps) {
59
- const late = days !== null && days < 0 && item.status !== 'done';
60
- const label = dueLabel(days, due);
60
+ const late = days !== null && days < 0 && item.status !== 'done' && item.status !== 'suggested';
61
+ const label = dueLabel(days, due, item.status);
61
62
  return (
62
63
  <li className="flex items-center gap-3 border-b border-gray-100 py-2 last:border-b-0" data-testid="item-row">
63
64
  <div className="min-w-0 flex-1">
@@ -17,9 +17,18 @@ const SYNC_WORDS: Record<string, string> = {
17
17
  limited: 'Slowed by the provider',
18
18
  failing: 'Not syncing',
19
19
  reauth: 'Reconnect needed',
20
+ connecting: 'Connecting…',
21
+ syncing: 'Syncing…',
20
22
  waiting: 'Waiting for first sync',
21
23
  };
22
24
 
25
+ /** Why a card needs attention, in the server's own sentence; '' when the status word says it all. */
26
+ export function reasonText(source: SourceFreshness): string {
27
+ const sync = source.sync;
28
+ if (!sync || (sync.state !== 'reauth' && sync.state !== 'connecting')) return '';
29
+ return sync.note === 'Reconnect this account to resume syncing' ? '' : sync.note;
30
+ }
31
+
23
32
  export function statusText(source: SourceFreshness): string {
24
33
  const sync = source.sync;
25
34
  if (sync?.state === 'passive') return sync.note;
@@ -67,6 +76,7 @@ function nextSyncText(source: SourceFreshness, now: number): string {
67
76
  const state = source.sync?.state;
68
77
  if (state === 'passive') return '—';
69
78
  if (state === 'reauth') return 'After you reconnect';
79
+ if (state === 'connecting') return '—';
70
80
  if (source.sync && !source.sync.nextSyncAt) return 'Not scheduled';
71
81
  return ahead(source.sync?.nextSyncAt, now);
72
82
  }
@@ -104,7 +114,13 @@ export function SourcesTable({
104
114
  return (
105
115
  <tr key={source.source}>
106
116
  <th scope="row" className={`${td} text-left font-medium`}>{source.label}</th>
107
- <td className={attention ? `${td} font-medium text-amber-700 dark:text-amber-400` : td}>{statusText(source)}</td>
117
+ <td className={attention ? `${td} font-medium text-amber-700 dark:text-amber-400` : td}>{statusText(source)}
118
+ {reasonText(source) ? (
119
+ <span className="block max-w-xs whitespace-normal text-xs font-normal text-gray-600 dark:text-gray-300" data-sync-reason>
120
+ {reasonText(source)}
121
+ </span>
122
+ ) : null}
123
+ </td>
108
124
  <td className={`${td} text-right tabular-nums`}>{records === null ? '—' : records}
109
125
  {source.sync?.windowDays ? (
110
126
  <span className="block whitespace-nowrap text-xs font-normal text-gray-500 dark:text-gray-400">last {source.sync.windowDays} days</span>
@@ -36,7 +36,10 @@ export function dueCell(item: Pick<Commitment, 'dueAt' | 'status'>, now: number,
36
36
  if (!day) return { text: '–', tone: 'none' };
37
37
  const days = daysBetween(localDate(now, timeZone), day);
38
38
  const finished = item.status === 'done' || item.status === 'dropped';
39
+ // A suggestion is the engine's guess, not a commitment: it is never "late", only dated.
40
+ const suggested = item.status === 'suggested';
39
41
  const date = new Date(`${day}T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
42
+ if (suggested) return { text: date, tone: 'plain', exact: day };
40
43
  if (days < 0) return { text: finished ? date : `${plural(-days, 'day')} late`, tone: finished ? 'plain' : 'overdue', exact: day };
41
44
  if (days === 0) return { text: 'Today', tone: 'plain', exact: day };
42
45
  if (days === 1) return { text: 'Tomorrow', tone: 'plain', exact: day };
@@ -95,10 +95,17 @@ export async function generateBriefing(deps: BriefingDeps, request: BriefingRequ
95
95
  const now = clock();
96
96
  const ttl = Math.min(deps.audioTtlSeconds ?? DEFAULT_TTL, 600);
97
97
  const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
98
- const timeZone = request.timeZone ?? deps.timeZone ?? (await rememberedTimeZone(store, deps.ownerSub, now)) ?? 'UTC';
98
+ // The zone lookup, the to-do read and the open-question count do not depend on each other:
99
+ // overlap them so a cold call pays one tenant round trip here, not three-plus.
100
+ const givenZone = request.timeZone ?? deps.timeZone;
101
+ const [rememberedZone, items, unsure] = await Promise.all([
102
+ givenZone ? undefined : rememberedTimeZone(store, deps.ownerSub, now),
103
+ deps.loadItems(),
104
+ deps.unsureCount?.().catch(() => 0) ?? 0,
105
+ ]);
106
+ const timeZone = givenZone ?? rememberedZone ?? 'UTC';
99
107
 
100
- const composed = composeBriefing(await deps.loadItems(), { ownerSub: deps.ownerSub, now, timeZone });
101
- const unsure = await deps.unsureCount?.().catch(() => 0) ?? 0;
108
+ const composed = composeBriefing(items, { ownerSub: deps.ownerSub, now, timeZone });
102
109
  const briefing = unsure > 0 ? { ...composed, unsure } : composed;
103
110
  const hash = briefingContentHash(briefing);
104
111
  const externalId = briefingExternalId(deps.ownerSub, briefing.context.localDate);
@@ -13,12 +13,12 @@ const utcDate = (ms: number) => new Date(ms).toISOString().slice(0, 10);
13
13
  export async function rememberedTimeZone(
14
14
  store: Pick<BriefingStore, 'find'>, ownerSub: string, now: number,
15
15
  ): Promise<string | undefined> {
16
- for (const offset of [1, 0, -1, -2, -3]) {
16
+ // Looked up together (one round trip of wall time, not five); the nearest day with a zone still wins.
17
+ const zones = await Promise.all([1, 0, -1, -2, -3].map(async (offset) => {
17
18
  try {
18
19
  const row = await store.find(briefingExternalId(ownerSub, utcDate(now + offset * DAY)));
19
- const zone = row?.context?.timeZone;
20
- if (zone) return zone;
21
- } catch { /* a lookup failure only costs the fallback */ }
22
- }
23
- return undefined;
20
+ return row?.context?.timeZone as string | undefined;
21
+ } catch { return undefined; /* a lookup failure only costs the fallback */ }
22
+ }));
23
+ return zones.find(Boolean);
24
24
  }
@@ -15,7 +15,7 @@
15
15
  * said on that same weekday (today or a week on?), "next <weekday>" (two
16
16
  * readings), past references ("last Friday", "3 days ago"), a bare month,
17
17
  * an impossible date, a yearless date that is far from the meeting (the year
18
- * would be a guess), and any text that states two DIFFERENT dates.
18
+ * would be a guess), a date before the meeting day, and any text that states two DIFFERENT dates.
19
19
  *
20
20
  * Distinct from `spoken-time.ts`, which resolves a voice note's phrases for the
21
21
  * speaker and is deliberately willing to approximate ("next week" -> Friday).
@@ -143,6 +143,12 @@ function relativeHits(text: string, today: string): Hit[] {
143
143
  /** Past references anywhere in the text make a relative phrase's tense uncertain. */
144
144
  const PAST_REFERENCE = /\b(?:last|previous|yesterday|ago)\b/;
145
145
 
146
+ const DEADLINE_CUE = /(?:\b(?:by|before|until|till|due|deadline|no later than)\b[ :,]*(?:on |the )?)$/;
147
+ function hasDeadlineCue(lower: string, phrase: string): boolean {
148
+ const at = lower.indexOf(phrase.toLowerCase());
149
+ return at >= 0 && DEADLINE_CUE.test(lower.slice(0, at).trimEnd() + ' ');
150
+ }
151
+
146
152
  export function resolveStatedDate(text: string, anchor: string | number | Date | null | undefined, options: StatedDateOptions = {}): StatedDate | null {
147
153
  const flat = (text ?? '').replace(/\*\*/g, '').replace(/\s+/g, ' ').trim();
148
154
  if (!flat) return null;
@@ -162,6 +168,10 @@ export function resolveStatedDate(text: string, anchor: string | number | Date |
162
168
  const dates = new Set(hits.map((h) => h.date));
163
169
  if (dates.size > 1) return null;
164
170
 
171
+ // A date before the meeting is history ("sent Oct 31") unless the words make it a deadline
172
+ // ("signed by 29th July"): otherwise it would show as late on day one.
173
+ if (today && hits.some((h) => h.date < today && !hasDeadlineCue(lower, h.phrase))) return null;
174
+
165
175
  const top = hits.sort((a, b) => b.confidence - a.confidence)[0];
166
176
  const instant = new Date(zonedInstant(top.date, '23:59', timeZone) + 59_000).toISOString().replace('.000Z', 'Z');
167
177
  return {
@@ -193,7 +193,7 @@ export interface MoneyEvent {
193
193
  * wrong, so the Library states it per source and the Ask surface repeats it.
194
194
  */
195
195
  export interface SourceSync {
196
- state: 'ok' | 'limited' | 'failing' | 'reauth' | 'waiting' | 'passive';
196
+ state: 'ok' | 'limited' | 'failing' | 'reauth' | 'connecting' | 'syncing' | 'waiting' | 'passive';
197
197
  /** One sentence the server wrote; '' when there is nothing to add. */
198
198
  note: string;
199
199
  records: number;
@@ -27,6 +27,8 @@ export function priorityLabel(priority?: number): string | null {
27
27
  export function isOverdue(item: Pick<Commitment, 'dueAt' | 'status'>, now: number): boolean {
28
28
  if (!item.dueAt) return false;
29
29
  if (item.status === 'done' || item.status === 'dropped') return false;
30
+ // A suggestion is a guess, not something owed: it is never overdue.
31
+ if (item.status === 'suggested') return false;
30
32
  return Date.parse(item.dueAt) < now;
31
33
  }
32
34