@startsimpli/integrations 0.2.229 → 0.2.231

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 +4 -4
  2. package/src/__tests__/corpus-ask-lookup.test.ts +70 -0
  3. package/src/__tests__/today-agenda-list.test.tsx +96 -0
  4. package/src/__tests__/today-agenda-route.test.ts +41 -0
  5. package/src/__tests__/today-agenda.test.ts +143 -0
  6. package/src/comms/__tests__/email-auth.test.tsx +173 -0
  7. package/src/comms/api/comms.ts +21 -0
  8. package/src/comms/components/EmailAuthApply.tsx +83 -0
  9. package/src/comms/components/EmailAuthPanel.tsx +140 -0
  10. package/src/comms/components/SendingDomain.tsx +3 -0
  11. package/src/comms/components/index.ts +1 -0
  12. package/src/comms/hooks/index.ts +38 -0
  13. package/src/comms/types/index.ts +77 -0
  14. package/src/components/pages/home/BriefCard.tsx +5 -3
  15. package/src/components/pages/home/HomeBriefPage.tsx +17 -6
  16. package/src/components/pages/home/TodayAgendaList.tsx +115 -0
  17. package/src/components/pages/home/index.ts +2 -0
  18. package/src/corpus/ask-items.ts +15 -5
  19. package/src/corpus/converse/brain.ts +3 -3
  20. package/src/corpus/give-up.ts +4 -0
  21. package/src/corpus/index.ts +4 -0
  22. package/src/corpus/llm.ts +5 -1
  23. package/src/corpus/today-agenda-route.ts +80 -0
  24. package/src/corpus/today-agenda.ts +144 -0
  25. package/src/native/home/AgendaSection.tsx +40 -0
  26. package/src/native/home/HomeScreen.tsx +14 -9
  27. package/src/native/home/__tests__/agenda-controller.test.ts +54 -0
  28. package/src/native/home/__tests__/home-agenda.test.tsx +42 -0
  29. package/src/native/home/agenda-controller.ts +46 -0
  30. package/src/native/home/tab.tsx +5 -1
  31. package/src/native/index.ts +2 -0
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Publish the missing SPF / DKIM / DMARC records for the sending domain instead of
3
+ * copying them by hand (bd startsim-7p3vi.9). Folded into the email security
4
+ * section: with a Namecheap account connected the primary action is "Publish
5
+ * these records" (plus Undo); without one, a short connect form takes its place.
6
+ */
7
+ import { useState, type ReactElement } from 'react';
8
+ import { Button, Input, Label } from '@startsimpli/ui';
9
+
10
+ import type { CommsApi } from '../api/comms';
11
+ import { useConnectNamecheap, useDnsConnection, useEmailAuthChange } from '../hooks/index';
12
+ import { ErrorNotice, Note } from './_shared';
13
+
14
+ function ConnectForm({ api, domain }: { api: CommsApi; domain: string }): ReactElement {
15
+ const connect = useConnectNamecheap(api);
16
+ const [open, setOpen] = useState(false);
17
+ const [f, setF] = useState({ api_user: '', api_key: '', client_ip: '', username: '' });
18
+ const set = (k: keyof typeof f) => (e: { target: { value: string } }) => setF({ ...f, [k]: e.target.value });
19
+ if (!open) {
20
+ return (
21
+ <Button type="button" variant="outline" size="sm" onClick={() => setOpen(true)}>
22
+ Connect Namecheap to publish these for me
23
+ </Button>
24
+ );
25
+ }
26
+ return (
27
+ <form
28
+ className="space-y-2"
29
+ aria-label="Connect Namecheap"
30
+ onSubmit={(e) => {
31
+ e.preventDefault();
32
+ connect.mutate({ ...f, username: f.username || undefined, zone_name: domain });
33
+ }}
34
+ >
35
+ <Note>
36
+ Namecheap API access must be on, with this machine&apos;s IP allowlisted. The key is stored encrypted and never shown again.
37
+ </Note>
38
+ {(
39
+ [['api_user', 'API user'], ['api_key', 'API key'], ['client_ip', 'Allowlisted IP'], ['username', 'Username (if different)']] as const
40
+ ).map(([k, label]) => (
41
+ <div key={k} className="space-y-1">
42
+ <Label htmlFor={`nc-${k}`}>{label}</Label>
43
+ <Input
44
+ id={`nc-${k}`}
45
+ type={k === 'api_key' ? 'password' : 'text'}
46
+ autoComplete="off"
47
+ value={f[k]}
48
+ onChange={set(k)}
49
+ />
50
+ </div>
51
+ ))}
52
+ <ErrorNotice error={connect.error} />
53
+ <Button type="submit" size="sm" disabled={connect.isPending || !f.api_user || !f.api_key || !f.client_ip}>
54
+ {connect.isPending ? 'Checking…' : 'Connect'}
55
+ </Button>
56
+ </form>
57
+ );
58
+ }
59
+
60
+ export function EmailAuthApply({ api, domain }: { api: CommsApi; domain: string }): ReactElement | null {
61
+ const { data: conn, isLoading } = useDnsConnection(api);
62
+ const apply = useEmailAuthChange(api, 'apply');
63
+ const undo = useEmailAuthChange(api, 'rollback');
64
+ if (isLoading || !conn) return null;
65
+ if (!conn.connected) return <ConnectForm api={api} domain={domain} />;
66
+ return (
67
+ <div className="space-y-2" data-testid="email-auth-apply">
68
+ <div className="flex items-center gap-2">
69
+ <Button type="button" size="sm" disabled={apply.isPending} onClick={() => apply.mutate()}>
70
+ {apply.isPending ? 'Publishing…' : 'Publish these records'}
71
+ </Button>
72
+ <Button type="button" variant="outline" size="sm" disabled={undo.isPending} onClick={() => undo.mutate()}>
73
+ Undo last publish
74
+ </Button>
75
+ </div>
76
+ <ErrorNotice error={apply.error ?? undo.error} />
77
+ {apply.data ? (
78
+ <Note>{apply.data.applied ? `Published: ${apply.data.records.join(', ')}.` : 'Nothing needed publishing.'}</Note>
79
+ ) : null}
80
+ {undo.data ? <Note>{undo.data.rolled_back ? 'Restored the zone as it was before.' : 'Nothing to undo.'}</Note> : null}
81
+ </div>
82
+ );
83
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Live SPF / DKIM / DMARC diagnosis of the sending domain (bd startsim-7p3vi.8),
3
+ * shown inside the sending-domain panel: per record a status, the plain reason,
4
+ * and the exact record to publish when something needs to change. Publishing goes through EmailAuthApply.
5
+ */
6
+ import { useState, type ReactElement } from 'react';
7
+ import { Badge, Button } from '@startsimpli/ui';
8
+
9
+ import type { CommsApi } from '../api/comms';
10
+ import { useDmarcReports, useEmailAuth } from '../hooks/index';
11
+ import type { DmarcLadder, EmailAuthRecord,EmailAuthStatus as Status } from '../types/index';
12
+ import { EmailAuthApply } from './EmailAuthApply';
13
+ import { ErrorNotice, Note } from './_shared';
14
+
15
+ const LABEL: Record<Status, string> = { ok: 'OK', warn: 'Tighten', fail: 'Fix', missing: 'Missing' };
16
+ const NAME: Record<string, string> = { spf: 'SPF', dkim: 'DKIM', dmarc: 'DMARC' };
17
+
18
+ function Row({ r }: { r: EmailAuthRecord }): ReactElement {
19
+ const [copied, setCopied] = useState(false);
20
+ return (
21
+ <li className="space-y-1 rounded-md border p-3 text-sm" data-testid={`email-auth-${r.purpose}`}>
22
+ <div className="flex items-center gap-2">
23
+ <span className="font-medium">{NAME[r.purpose] ?? r.purpose}</span>
24
+ <Badge variant={r.status === 'ok' ? 'default' : r.status === 'warn' ? 'secondary' : 'destructive'}>
25
+ {LABEL[r.status]}
26
+ </Badge>
27
+ </div>
28
+ <p className="text-muted-foreground">{r.reason}</p>
29
+ {r.recommended && r.status !== 'ok' ? (
30
+ <div className="space-y-1">
31
+ <Note>
32
+ Publish a {r.type} record at <span className="break-all font-mono text-xs">{r.host}</span>:
33
+ </Note>
34
+ <div className="flex items-start gap-2">
35
+ <code className="break-all rounded bg-muted px-2 py-1 text-xs">{r.recommended}</code>
36
+ <Button
37
+ type="button"
38
+ variant="outline"
39
+ size="sm"
40
+ onClick={() => {
41
+ void navigator.clipboard?.writeText(r.recommended).then(() => setCopied(true));
42
+ }}
43
+ >
44
+ {copied ? 'Copied' : 'Copy'}
45
+ </Button>
46
+ </div>
47
+ </div>
48
+ ) : null}
49
+ </li>
50
+ );
51
+ }
52
+
53
+ function Reports({ api }: { api: CommsApi }): ReactElement | null {
54
+ const { data } = useDmarcReports(api);
55
+ if (!data) return null;
56
+ if (data.reports === 0) {
57
+ return <Note>No DMARC reports received yet. Mailbox providers send them daily once DMARC is published.</Note>;
58
+ }
59
+ const bad = data.sources.filter((s) => s.dmarc_fail > 0);
60
+ return (
61
+ <div className="space-y-1 text-sm" data-testid="dmarc-reports">
62
+ <p>
63
+ Last {data.days} days: {data.messages} messages from {data.reports} reports,{' '}
64
+ {data.pass_rate === null ? 'n/a' : `${Math.round(data.pass_rate * 100)}%`} passed DMARC.
65
+ </p>
66
+ {bad.length ? (
67
+ <ul className="space-y-0.5">
68
+ {bad.map((s) => (
69
+ <li key={s.source_ip} className="text-muted-foreground">
70
+ <span className="font-mono text-xs">{s.source_ip}</span>: {s.dmarc_fail} of {s.messages} failed
71
+ {' '}(seen by {s.reporters.join(', ')})
72
+ </li>
73
+ ))}
74
+ </ul>
75
+ ) : null}
76
+ </div>
77
+ );
78
+ }
79
+
80
+ function Ladder({ l, host }: { l: DmarcLadder; host: string }): ReactElement | null {
81
+ const [copied, setCopied] = useState(false);
82
+ if (!l.next) return null;
83
+ const e = l.evidence;
84
+ return (
85
+ <div className="space-y-1 rounded-md border p-3 text-sm" data-testid="dmarc-ladder">
86
+ {l.ready ? (
87
+ <>
88
+ <p>Last {e.days} days clean ({e.messages} messages, none failed DMARC): move to p={l.next}.</p>
89
+ <Note>
90
+ Replace the DMARC record at <span className="break-all font-mono text-xs">{host}</span>:
91
+ </Note>
92
+ <div className="flex items-start gap-2">
93
+ <code className="break-all rounded bg-muted px-2 py-1 text-xs">{l.recommended}</code>
94
+ <Button
95
+ type="button"
96
+ variant="outline"
97
+ size="sm"
98
+ onClick={() => {
99
+ void navigator.clipboard?.writeText(l.recommended).then(() => setCopied(true));
100
+ }}
101
+ >
102
+ {copied ? 'Copied' : 'Copy'}
103
+ </Button>
104
+ </div>
105
+ </>
106
+ ) : (
107
+ <p className="text-muted-foreground">
108
+ Not ready for p={l.next}:{' '}
109
+ {e.reports === 0
110
+ ? 'no DMARC reports yet, so there is no evidence.'
111
+ : `${e.dmarc_fail} of ${e.messages} messages failed DMARC in the last ${e.days} days.`}
112
+ </p>
113
+ )}
114
+ </div>
115
+ );
116
+ }
117
+
118
+ export function EmailAuthPanel({ api, domain }: { api: CommsApi; domain: string }): ReactElement | null {
119
+ const { data, error, isLoading } = useEmailAuth(api, Boolean(domain));
120
+ if (!domain) return null;
121
+ return (
122
+ <section className="space-y-2" aria-label="Email security">
123
+ <h3 className="text-sm font-medium">Email security for {domain}</h3>
124
+ {isLoading ? <Note>Checking DNS…</Note> : null}
125
+ <ErrorNotice error={error} />
126
+ {data ? (
127
+ <ul className="space-y-2">
128
+ {data.records.map((r) => (
129
+ <Row key={r.purpose} r={r} />
130
+ ))}
131
+ </ul>
132
+ ) : null}
133
+ {data?.records.some((r) => r.status !== 'ok' && r.recommended) ? <EmailAuthApply api={api} domain={domain} /> : null}
134
+ {data ? <Reports api={api} /> : null}
135
+ {data?.ladder ? (
136
+ <Ladder l={data.ladder} host={data.records.find((r) => r.purpose === 'dmarc')?.host ?? `_dmarc.${domain}`} />
137
+ ) : null}
138
+ </section>
139
+ );
140
+ }
@@ -20,6 +20,7 @@ import {
20
20
  import type { CommsApi } from '../api/comms';
21
21
  import { useCheckDomain, useCommsSettings, useConnectDomain } from '../hooks/index';
22
22
  import type { DomainRecord, DomainStatus } from '../types/index';
23
+ import { EmailAuthPanel } from './EmailAuthPanel';
23
24
  import { ErrorNotice, Note, formatDate, useFieldId } from './_shared';
24
25
 
25
26
  export interface SendingDomainProps {
@@ -108,6 +109,8 @@ export function SendingDomain({ api }: SendingDomainProps): ReactElement | null
108
109
  </Table>
109
110
  ) : null}
110
111
 
112
+ {settings.sending_domain ? <EmailAuthPanel api={api} domain={settings.sending_domain} /> : null}
113
+
111
114
  <Note>
112
115
  {verified
113
116
  ? `Mail goes out from ${settings.from_address ?? settings.sending_domain}.`
@@ -6,6 +6,7 @@ export * from './EmailPreviewPage';
6
6
  export * from './ApprovalModeSetting';
7
7
  export * from './VoiceSettings';
8
8
  export * from './DefaultTimeZoneSetting';
9
+ export * from './EmailAuthPanel';
9
10
  export * from './SendingDomain';
10
11
  export * from './ProductUpdates';
11
12
  export * from './DraftReview';
@@ -26,6 +26,11 @@ import type {
26
26
  CommsMetrics,
27
27
  CommsProgram,
28
28
  CommsSettings,
29
+ DmarcReportSummary,
30
+ DnsConnection,
31
+ EmailAuthChange,
32
+ EmailAuthDiagnosis,
33
+ NamecheapConnectInput,
29
34
  CommsSettingsPatch,
30
35
  Draft,
31
36
  DraftAudience,
@@ -49,6 +54,9 @@ import type {
49
54
  export const commsKeys = {
50
55
  all: (slug: string) => ['startsimpli', 'comms', slug] as const,
51
56
  settings: (slug: string) => ['startsimpli', 'comms', slug, 'settings'] as const,
57
+ dmarcReports: (slug: string) => ['startsimpli', 'comms', slug, 'settings', 'dmarc-reports'] as const,
58
+ dnsConnection: (slug: string) => ['startsimpli', 'comms', slug, 'dns-connection'] as const,
59
+ emailAuth: (slug: string) => ['startsimpli', 'comms', slug, 'settings', 'email-auth'] as const,
52
60
  programs: (slug: string) => ['startsimpli', 'comms', slug, 'programs'] as const,
53
61
  generation: (slug: string, key: string, step: number) =>
54
62
  ['startsimpli', 'comms', slug, 'generation', key, step] as const,
@@ -122,6 +130,36 @@ export function useConnectDomain(api: CommsApi): UseMutationResult<CommsSettings
122
130
  return useSettingsWrite(api, (domain: string) => api.connectDomain(domain));
123
131
  }
124
132
 
133
+ /** Live diagnosis; sits under the settings key, so connecting or re-checking the domain refetches it. */
134
+ export function useDmarcReports(api: CommsApi, enabled = true): UseQueryResult<DmarcReportSummary> {
135
+ return useQuery({ queryKey: commsKeys.dmarcReports(api.slug), queryFn: () => api.getDmarcReports(), enabled, staleTime: 60_000 });
136
+ }
137
+
138
+ export function useEmailAuth(api: CommsApi, enabled = true): UseQueryResult<EmailAuthDiagnosis> {
139
+ return useQuery({ queryKey: commsKeys.emailAuth(api.slug), queryFn: () => api.getEmailAuth(), enabled, staleTime: 60_000 });
140
+ }
141
+
142
+ export function useDnsConnection(api: CommsApi, enabled = true): UseQueryResult<DnsConnection> {
143
+ return useQuery({ queryKey: commsKeys.dnsConnection(api.slug), queryFn: () => api.getDnsConnection(), enabled });
144
+ }
145
+
146
+ export function useConnectNamecheap(api: CommsApi): UseMutationResult<DnsConnection, Error, NamecheapConnectInput> {
147
+ const qc = useQueryClient();
148
+ return useMutation<DnsConnection, Error, NamecheapConnectInput>({
149
+ mutationFn: (input) => api.connectNamecheap(input),
150
+ onSuccess: () => qc.invalidateQueries({ queryKey: commsKeys.dnsConnection(api.slug) }),
151
+ });
152
+ }
153
+
154
+ /** Apply or undo a DNS publish; either way the live diagnosis is stale, so refetch it. */
155
+ export function useEmailAuthChange(api: CommsApi, kind: 'apply' | 'rollback'): UseMutationResult<EmailAuthChange, Error, void> {
156
+ const qc = useQueryClient();
157
+ return useMutation<EmailAuthChange, Error, void>({
158
+ mutationFn: () => (kind === 'apply' ? api.applyEmailAuth() : api.rollbackEmailAuth()),
159
+ onSuccess: () => qc.invalidateQueries({ queryKey: commsKeys.emailAuth(api.slug) }),
160
+ });
161
+ }
162
+
125
163
  export function useCheckDomain(api: CommsApi): UseMutationResult<CommsSettings, Error, void> {
126
164
  return useSettingsWrite(api, () => api.checkDomain());
127
165
  }
@@ -35,6 +35,83 @@ export interface DomainRecord {
35
35
  purpose?: DomainRecordPurpose;
36
36
  }
37
37
 
38
+ /** One record of the live SPF / DKIM / DMARC diagnosis (GET settings/domain/email-auth/). */
39
+ export type EmailAuthStatus = 'ok' | 'warn' | 'fail' | 'missing';
40
+
41
+ export interface EmailAuthRecord {
42
+ purpose: DomainRecordPurpose;
43
+ type: string;
44
+ host: string;
45
+ status: EmailAuthStatus;
46
+ /** Plain-language why. */
47
+ reason: string;
48
+ /** What DNS holds now ('' if nothing). */
49
+ current: string;
50
+ /** The value to publish ('' when nothing needs to change). */
51
+ recommended: string;
52
+ policy?: string;
53
+ inherited_from?: string;
54
+ }
55
+
56
+ export interface DmarcSource {
57
+ source_ip: string;
58
+ messages: number;
59
+ dmarc_fail: number;
60
+ reporters: string[];
61
+ }
62
+
63
+ export interface DmarcReportSummary {
64
+ days: number;
65
+ reports: number;
66
+ messages: number;
67
+ dmarc_fail: number;
68
+ pass_rate: number | null;
69
+ last_report_at: string | null;
70
+ sources: DmarcSource[];
71
+ }
72
+
73
+ /** Where the DMARC policy can go next, with the evidence that says whether it is safe. */
74
+ export interface DmarcLadder {
75
+ policy: string;
76
+ /** Next policy step, null at p=reject or when there is no DMARC record. */
77
+ next: 'quarantine' | 'reject' | null;
78
+ ready: boolean;
79
+ /** The full record with the next policy substituted ('' when there is no next step). */
80
+ recommended: string;
81
+ evidence: { days: number; reports: number; messages: number; dmarc_fail: number };
82
+ }
83
+
84
+ export interface EmailAuthDiagnosis {
85
+ domain: string;
86
+ /** The worst record status. */
87
+ status: EmailAuthStatus;
88
+ records: EmailAuthRecord[];
89
+ ladder?: DmarcLadder;
90
+ }
91
+
92
+ /** The foundry's registrar DNS account (GET/PUT foundry/tenants/{slug}/dns-connection/). Secrets are never returned. */
93
+ export interface DnsConnection {
94
+ provider: 'namecheap' | 'cloudflare';
95
+ connected: boolean;
96
+ zone_name: string;
97
+ has_token: boolean;
98
+ }
99
+
100
+ export interface NamecheapConnectInput {
101
+ api_user: string;
102
+ api_key: string;
103
+ client_ip: string;
104
+ username?: string;
105
+ zone_name: string;
106
+ }
107
+
108
+ /** POST email-auth/apply/ and /rollback/. */
109
+ export interface EmailAuthChange {
110
+ applied: boolean;
111
+ rolled_back?: boolean;
112
+ records: string[];
113
+ }
114
+
38
115
  export interface SourceRepo {
39
116
  provider: 'github';
40
117
  owner: string;
@@ -39,9 +39,11 @@ export interface BriefCardProps {
39
39
  onDemand?: boolean;
40
40
  /** The weekly brief, offered inside this card as one text link instead of a second card. */
41
41
  week?: BriefCardApi;
42
+ /** Do not draw the brief's text (the page already lists the same items); Play and the week stay. */
43
+ hideText?: boolean;
42
44
  }
43
45
 
44
- export function BriefCard({ api, onAsk, title = 'Today’s brief', showTitle = true, onDemand = false, week }: BriefCardProps) {
46
+ export function BriefCard({ api, onAsk, title = 'Today’s brief', showTitle = true, onDemand = false, week, hideText = false }: BriefCardProps) {
45
47
  const apiRef = React.useRef(api);
46
48
  apiRef.current = api;
47
49
  const [state, setState] = React.useState<State>(onDemand ? { phase: 'idle' } : { phase: 'loading' });
@@ -75,7 +77,7 @@ export function BriefCard({ api, onAsk, title = 'Today’s brief', showTitle = t
75
77
  };
76
78
 
77
79
  return (
78
- <section aria-label={title} className="rounded-lg border border-gray-200 bg-white p-4 shadow-sm" data-testid="brief-card">
80
+ <section aria-label={title} className={hideText ? 'px-1' : 'rounded-lg border border-gray-200 bg-white p-4 shadow-sm'} data-testid="brief-card">
79
81
  <div className="flex items-center gap-2">
80
82
  {showTitle ? <h2 className="text-sm font-semibold uppercase tracking-wide text-gray-500">{title}</h2> : null}
81
83
  <div className="ml-auto flex items-center gap-2">
@@ -96,7 +98,7 @@ export function BriefCard({ api, onAsk, title = 'Today’s brief', showTitle = t
96
98
  {state.message} <button type="button" className="underline" onClick={() => void load()}>Try again</button>
97
99
  </p>
98
100
  ) : null}
99
- {state.phase === 'ready' ? (
101
+ {state.phase === 'ready' && !hideText ? (
100
102
  <>
101
103
  {state.result.markdown ? (
102
104
  <div className="mt-3" data-testid="brief-text"><MiniMarkdown text={state.result.markdown} /></div>
@@ -1,21 +1,32 @@
1
1
  /**
2
- * TODAY — the morning brief and the way to the week, nothing else. The to-do list lives in Plan and the
3
- * questions in Decisions: Today draws neither (no due counts, no "Open plan", no Needs your call).
2
+ * TODAY: the ranked list of what the person must do today (`TodayAgendaList`), then the brief as Play and the week.
3
+ * This supersedes the earlier "Today draws no to-dos and no Needs your call": the list IS Today now, and it is
4
+ * the same flow, not a panel beside it. With an `agenda` the brief's own text is not drawn a second time (it
5
+ * said the same overdue items); Play still reads it aloud.
4
6
  *
5
- * `<HomeBriefPage brief={...} />` is the whole integration; an app adds a heading. The brief is a short
6
- * structured view of the same items the voice reads (see `BriefCard`).
7
+ * `<HomeBriefPage brief={...} agenda={...} />` is the whole integration; an app adds a heading. Without an
8
+ * `agenda` the page is the brief and the week, as before.
7
9
  */
8
10
  import * as React from 'react';
9
11
 
10
12
  import { BriefCard, type BriefCardApi } from './BriefCard';
13
+ import { TodayAgendaList, type TodayAgendaApi } from './TodayAgendaList';
11
14
 
12
15
  export interface HomeBriefPageProps {
13
16
  brief: BriefCardApi;
14
17
  /** The weekly summary, shown on demand under the daily brief. Absent = no weekly card. */
15
18
  weekly?: BriefCardApi;
19
+ /** The ranked do-now list. Absent = the brief alone. */
20
+ agenda?: TodayAgendaApi;
16
21
  onAsk?: () => void;
17
22
  }
18
23
 
19
- export function HomeBriefPage({ brief, weekly, onAsk }: HomeBriefPageProps) {
20
- return <BriefCard api={brief} showTitle={false} onAsk={onAsk} week={weekly} />;
24
+ export function HomeBriefPage({ brief, weekly, agenda, onAsk }: HomeBriefPageProps) {
25
+ if (!agenda) return <BriefCard api={brief} showTitle={false} onAsk={onAsk} week={weekly} />;
26
+ return (
27
+ <div className="space-y-4">
28
+ <TodayAgendaList api={agenda} />
29
+ <BriefCard api={brief} showTitle={false} onAsk={onAsk} week={weekly} hideText />
30
+ </div>
31
+ );
21
32
  }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * THE TODAY LIST (ASK 2): what the person must do today, ranked, each row with the reason it is today and ONE action.
3
+ * Done items leave at once (and are put back with a plain message if the save fails). The first `cap` rows are
4
+ * "do now"; the rest wait behind one "N more" link. What shipped since yesterday is a quiet footer.
5
+ */
6
+ import * as React from 'react';
7
+
8
+ import type { AgendaAction, AgendaItem, TodayAgenda } from '../../../corpus/today-agenda';
9
+
10
+ export interface TodayAgendaApi {
11
+ load(): Promise<TodayAgenda>;
12
+ /** Record his answer to a question (a relay item or decision id). Rejects when it could not be saved. */
13
+ answer(id: string, answer: string): Promise<void>;
14
+ /** Close these to-dos (a recurring to-do passes every copy). Rejects when it could not be saved. */
15
+ complete(todoIds: string[]): Promise<void>;
16
+ }
17
+
18
+ type State = { phase: 'loading' } | { phase: 'error'; message: string } | { phase: 'ready'; agenda: TodayAgenda };
19
+ const BTN = 'rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm font-medium text-gray-900';
20
+
21
+ export function TodayAgendaList({ api }: { api: TodayAgendaApi }) {
22
+ const apiRef = React.useRef(api);
23
+ apiRef.current = api;
24
+ const [state, setState] = React.useState<State>({ phase: 'loading' });
25
+ const [gone, setGone] = React.useState<Set<string>>(new Set());
26
+ const [showRest, setShowRest] = React.useState(false);
27
+ const [notice, setNotice] = React.useState('');
28
+
29
+ const load = React.useCallback(async () => {
30
+ setState({ phase: 'loading' });
31
+ try { setState({ phase: 'ready', agenda: await apiRef.current.load() }); setGone(new Set()); }
32
+ catch (e) { setState({ phase: 'error', message: (e as Error)?.message || 'Today could not be loaded.' }); }
33
+ }, []);
34
+ React.useEffect(() => { void load(); }, [load]);
35
+
36
+ const settle = async (id: string, save: () => Promise<void>) => {
37
+ setNotice('');
38
+ setGone((g) => new Set(g).add(id));
39
+ try { await save(); }
40
+ catch {
41
+ setGone((g) => { const n = new Set(g); n.delete(id); return n; });
42
+ setNotice('That did not save. It is back in your list; try again.');
43
+ }
44
+ };
45
+
46
+ if (state.phase === 'loading') return <p className="text-sm text-gray-500" data-testid="today-agenda">Putting your day together…</p>;
47
+ if (state.phase === 'error') {
48
+ return <p className="text-sm text-red-600" role="alert">{state.message} <button type="button" className="underline" onClick={() => void load()}>Try again</button></p>;
49
+ }
50
+
51
+ const live = (list: AgendaItem[]) => list.filter((i) => !gone.has(i.id));
52
+ const doNow = live(state.agenda.doNow);
53
+ const rest = live(state.agenda.rest);
54
+ const row = (i: AgendaItem) => (
55
+ <li key={i.id} className="flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-gray-100 py-3 last:border-b-0">
56
+ <div className="min-w-0 flex-1">
57
+ <p className="text-base font-medium text-gray-900">{i.title}</p>
58
+ <p className="text-sm text-gray-500">{i.reason}</p>
59
+ </div>
60
+ <Action item={i} onAnswer={(a) => void settle(i.id, () => apiRef.current.answer(i.action.kind === 'answer' ? i.action.questionId : i.id, a))}
61
+ onComplete={(ids) => void settle(i.id, () => apiRef.current.complete(ids))} />
62
+ </li>
63
+ );
64
+
65
+ return (
66
+ <section aria-label="What to do today" className="rounded-lg border border-gray-200 bg-white px-4 shadow-sm" data-testid="today-agenda">
67
+ {notice ? <p className="py-2 text-sm text-gray-700" role="alert">{notice}</p> : null}
68
+ {doNow.length === 0 && rest.length === 0 ? <p className="py-4 text-sm text-gray-500">Nothing needs you today.</p> : null}
69
+ {doNow.length ? <ul>{doNow.map(row)}</ul> : null}
70
+ {rest.length ? (
71
+ <>
72
+ {showRest ? <ul>{rest.map(row)}</ul> : null}
73
+ <p className="py-3">
74
+ <button type="button" className="text-sm text-blue-700 underline" onClick={() => setShowRest(!showRest)}>
75
+ {showRest ? 'Show fewer' : `${rest.length} more`}
76
+ </button>
77
+ </p>
78
+ </>
79
+ ) : null}
80
+ {state.agenda.shipped.length ? (
81
+ <div className="border-t border-gray-100 py-3">
82
+ <h3 className="text-xs font-semibold uppercase tracking-wide text-gray-500">Shipped since yesterday</h3>
83
+ <ul className="mt-1 space-y-0.5 text-sm text-gray-700">
84
+ {state.agenda.shipped.map((s) => <li key={s.id}>{s.link ? <a className="underline" href={s.link}>{s.text}</a> : s.text}</li>)}
85
+ </ul>
86
+ </div>
87
+ ) : null}
88
+ </section>
89
+ );
90
+ }
91
+
92
+ function Action({ item, onAnswer, onComplete }: { item: AgendaItem; onAnswer(answer: string): void; onComplete(ids: string[]): void }) {
93
+ const a: AgendaAction = item.action;
94
+ if (a.kind === 'open') {
95
+ return <a className={BTN} href={a.href} target={a.href.startsWith('http') ? '_blank' : undefined} rel="noreferrer">{a.label}</a>;
96
+ }
97
+ if (a.kind === 'complete') return <button type="button" className={BTN} onClick={() => onComplete(a.todoIds)}>{a.label}</button>;
98
+ if (a.freeform) return <FreeAnswer title={item.title} onSend={onAnswer} />;
99
+ const options = a.options.length ? a.options : ['Yes', 'No'];
100
+ return (
101
+ <div className="flex flex-wrap gap-2">
102
+ {options.map((o) => <button key={o} type="button" className={BTN} onClick={() => onAnswer(o)}>{o}</button>)}
103
+ </div>
104
+ );
105
+ }
106
+
107
+ function FreeAnswer({ title, onSend }: { title: string; onSend(answer: string): void }) {
108
+ const [text, setText] = React.useState('');
109
+ return (
110
+ <form className="flex gap-2" onSubmit={(e) => { e.preventDefault(); if (text.trim()) onSend(text.trim()); }}>
111
+ <input aria-label={`Answer: ${title}`} className="w-56 rounded-md border border-gray-300 px-2 py-1.5 text-sm" value={text} onChange={(e) => setText(e.target.value)} />
112
+ <button type="submit" className={BTN} disabled={!text.trim()}>Send</button>
113
+ </form>
114
+ );
115
+ }
@@ -6,3 +6,5 @@ export { dueSoonText } from './dueSoonText';
6
6
  export { HomeBriefPage } from './HomeBriefPage';
7
7
  export type { HomeBriefPageProps } from './HomeBriefPage';
8
8
  export { useProjectNames } from './useProjectNames';
9
+ export { TodayAgendaList } from './TodayAgendaList';
10
+ export type { TodayAgendaApi } from './TodayAgendaList';
@@ -79,7 +79,13 @@ export function selectItems(items: Commitment[], intent: ItemIntent, ctx: ItemCo
79
79
  (dueDay(a.dueAt, zone) ?? '9999').localeCompare(dueDay(b.dueAt, zone) ?? '9999') || (a.priority ?? 9) - (b.priority ?? 9));
80
80
  }
81
81
 
82
- /** Items for a question: read, scope-check, select, convert. Empty when it is not an item question. */
82
+ /** Tracker keys a question names ("What is ENG-141 about?"): whole keys, upper-cased, in order, deduped. */
83
+ export function itemKeysIn(question: string): string[] {
84
+ const found = question.match(/(?<![A-Za-z0-9-])[A-Za-z][A-Za-z0-9]{1,9}-\d{1,6}(?![A-Za-z0-9-])/g) ?? [];
85
+ return [...new Set(found.map((k) => k.toUpperCase()))];
86
+ }
87
+
88
+ /** Items for a question: read, scope-check, select, convert. Empty when it is not an item question. A question that names an item by its key reads that item, whatever its words or dates. */
83
89
  export async function retrieveItems(
84
90
  question: string,
85
91
  api: Pick<CommitmentApi, 'listCommitments'> | undefined,
@@ -88,16 +94,20 @@ export async function retrieveItems(
88
94
  limit: number,
89
95
  ): Promise<{ intent: ItemIntent | null; retrieved: RetrievedDocument[]; matched: number }> {
90
96
  const intent = itemIntent(question, ctx.now, ctx.timeZone);
91
- if (!intent || !api) return { intent: null, retrieved: [], matched: 0 };
97
+ const keys = itemKeysIn(question);
98
+ if ((!intent && !keys.length) || !api) return { intent: null, retrieved: [], matched: 0 };
92
99
  const page = await api.listCommitments({ pageSize: 200, sort: 'due', withFocus: true }).catch(() => null);
93
- if (!page) return { intent, retrieved: [], matched: 0 };
100
+ if (!page) return { intent: intent ?? null, retrieved: [], matched: 0 };
94
101
  // The project names load beside the item list (the caller starts both), so they are awaited only now.
95
102
  const names = await Promise.resolve(ctx.focusNames).catch(() => undefined);
96
103
  const resolved = { ...ctx, focusNames: names };
97
- const selected = selectItems(page.results.filter((item) => isInScope(item, scope)), intent, resolved);
104
+ const inScope = page.results.filter((item) => isInScope(item, scope));
105
+ // Named by key: exactly those items, finished ones included (that is what was asked for). No such key: fall back to the intent.
106
+ const named = keys.length ? inScope.filter((item) => item.sync?.key && keys.includes(item.sync.key.toUpperCase())) : [];
107
+ const selected = named.length || !intent ? named : selectItems(inScope, intent, resolved);
98
108
  const retrieved = selected.slice(0, limit).map((item): RetrievedDocument => {
99
109
  const document = itemAsDocument(item, resolved);
100
110
  return { document, score: 1, matchedTerms: [], snippet: document.body.split('\n').slice(0, 2).join(' · ') };
101
111
  });
102
- return { intent, retrieved, matched: selected.length };
112
+ return { intent: intent ?? null, retrieved, matched: selected.length };
103
113
  }