@startsimpli/integrations 0.2.230 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.230",
3
+ "version": "0.2.231",
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",
@@ -98,11 +98,11 @@
98
98
  "vitest": "^3.0.0",
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
- "@startsimpli/ui": "0.4.211",
101
+ "@startsimpli/llm": "0.4.33",
102
102
  "@startsimpli/ui-native": "0.1.15",
103
103
  "@startsimpli/auth": "0.4.64",
104
- "@startsimpli/utils": "0.4.23",
105
- "@startsimpli/llm": "0.4.32"
104
+ "@startsimpli/ui": "0.4.211",
105
+ "@startsimpli/utils": "0.4.23"
106
106
  },
107
107
  "scripts": {
108
108
  "type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
@@ -0,0 +1,96 @@
1
+ import * as React from 'react';
2
+ import { render, screen, within, waitFor } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { describe, expect, it, vi } from 'vitest';
5
+
6
+ import { HomeBriefPage, TodayAgendaList } from '../components/pages/home';
7
+ import type { TodayAgenda, AgendaItem } from '../corpus/today-agenda';
8
+
9
+ const item = (o: Partial<AgendaItem> & { id: string }): AgendaItem => ({
10
+ source: 'todo', title: o.id, reason: 'Due today', score: 1,
11
+ action: { kind: 'complete', label: 'Mark done', todoIds: [o.id.replace('todo:', '')] }, ...o,
12
+ } as AgendaItem);
13
+ const agenda = (doNow: AgendaItem[], rest: AgendaItem[] = [], shipped: TodayAgenda['shipped'] = []): TodayAgenda =>
14
+ ({ doNow, rest, shipped, total: doNow.length + rest.length, empty: doNow.length + rest.length === 0 });
15
+ const api = (a: TodayAgenda) => ({ load: vi.fn(async () => a), answer: vi.fn(async () => undefined), complete: vi.fn(async () => undefined) });
16
+
17
+ describe('TodayAgendaList', () => {
18
+ it('shows each item with its reason and exactly one action control', async () => {
19
+ const a = agenda([item({ id: 'todo:t1', title: 'Send invoice', reason: 'Overdue since Nov 20' })]);
20
+ render(<TodayAgendaList api={api(a)} />);
21
+ const row = (await screen.findByText('Send invoice')).closest('li')!;
22
+ expect(within(row).getByText('Overdue since Nov 20')).toBeInTheDocument();
23
+ expect(within(row).getAllByRole('button')).toHaveLength(1);
24
+ });
25
+
26
+ it('completing a to-do closes it through the api and the row disappears at once', async () => {
27
+ const a = agenda([item({ id: 'todo:t1', title: 'Send invoice', action: { kind: 'complete', label: 'Mark done', todoIds: ['t1', 't2'] } })]);
28
+ const x = api(a);
29
+ render(<TodayAgendaList api={x} />);
30
+ await userEvent.click(await screen.findByRole('button', { name: 'Mark done' }));
31
+ expect(screen.queryByText('Send invoice')).toBeNull();
32
+ expect(x.complete).toHaveBeenCalledWith(['t1', 't2']);
33
+ });
34
+
35
+ it('puts the row back with a plain message when the save fails', async () => {
36
+ const x = api(agenda([item({ id: 'todo:t1', title: 'Send invoice' })]));
37
+ x.complete.mockRejectedValueOnce(new Error('nope'));
38
+ render(<TodayAgendaList api={x} />);
39
+ await userEvent.click(await screen.findByRole('button', { name: 'Mark done' }));
40
+ expect(await screen.findByText('Send invoice')).toBeInTheDocument();
41
+ expect(screen.getByRole('alert').textContent).toMatch(/did not save/i);
42
+ });
43
+
44
+ it('answers a question with its own options, and falls back to Yes / No', async () => {
45
+ const q = (id: string, options: string[]) => item({ id, source: 'decision', title: `Q ${id}`, reason: 'Only you can decide', action: { kind: 'answer', label: 'Choose', questionId: id, options, freeform: false } });
46
+ const x = api(agenda([q('relay:a', ['schedule', 'manual']), q('relay:b', [])]));
47
+ render(<TodayAgendaList api={x} />);
48
+ await userEvent.click(await screen.findByRole('button', { name: 'manual' }));
49
+ expect(x.answer).toHaveBeenCalledWith('relay:a', 'manual');
50
+ expect(screen.getByRole('button', { name: 'Yes' })).toBeInTheDocument();
51
+ expect(screen.getByRole('button', { name: 'No' })).toBeInTheDocument();
52
+ });
53
+
54
+ it('an open question takes a typed answer with one Send button', async () => {
55
+ const x = api(agenda([item({ id: 'relay:c', source: 'decision', title: 'Who owns the site?', reason: 'Waiting on your answer', action: { kind: 'answer', label: 'Answer', questionId: 'relay:c', options: [], freeform: true } })]));
56
+ render(<TodayAgendaList api={x} />);
57
+ await userEvent.type(await screen.findByRole('textbox', { name: /answer/i }), 'Marketing');
58
+ await userEvent.click(screen.getByRole('button', { name: 'Send' }));
59
+ expect(x.answer).toHaveBeenCalledWith('relay:c', 'Marketing');
60
+ expect(screen.queryByText('Who owns the site?')).toBeNull();
61
+ });
62
+
63
+ it('opens a link action as a link', async () => {
64
+ const a = agenda([item({ id: 'draft:d1', source: 'draft', title: 'Reply to Kevin', action: { kind: 'open', label: 'Review and send', href: 'https://mail.example/d1' } })]);
65
+ render(<TodayAgendaList api={api(a)} />);
66
+ expect((await screen.findByRole('link', { name: 'Review and send' })).getAttribute('href')).toBe('https://mail.example/d1');
67
+ });
68
+
69
+ it('keeps the rest collapsed until asked, and lists shipped lines under a quiet heading', async () => {
70
+ const a = agenda([item({ id: 'todo:a', title: 'A' })], [item({ id: 'todo:b', title: 'B' })], [{ id: 's1', text: 'Talk key fixed', at: '2026-12-01T10:00:00Z' }]);
71
+ render(<TodayAgendaList api={api(a)} />);
72
+ await screen.findByText('A');
73
+ expect(screen.queryByText('B')).toBeNull();
74
+ await userEvent.click(screen.getByRole('button', { name: /1 more/ }));
75
+ expect(screen.getByText('B')).toBeInTheDocument();
76
+ expect(screen.getByText('Talk key fixed')).toBeInTheDocument();
77
+ });
78
+
79
+ it('says plainly when nothing is waiting, and when it cannot load', async () => {
80
+ const { unmount } = render(<TodayAgendaList api={api(agenda([]))} />);
81
+ expect(await screen.findByText(/Nothing needs you today/)).toBeInTheDocument();
82
+ unmount();
83
+ render(<TodayAgendaList api={{ ...api(agenda([])), load: vi.fn(async () => { throw new Error('boom'); }) }} />);
84
+ expect(await screen.findByRole('alert')).toBeInTheDocument();
85
+ });
86
+ });
87
+
88
+ describe('HomeBriefPage with an agenda', () => {
89
+ it('shows the agenda as the main list and the brief only as Play and the week, with no second list', async () => {
90
+ const RESULT = { briefingId: 'b1', text: 'Good morning. Three things overdue.', markdown: '## Overdue\n- **Dup**', audioUrl: null, items: [], remaining: 0 } as never;
91
+ render(<HomeBriefPage brief={{ fetch: async () => RESULT, loadAudio: async () => null }} agenda={api(agenda([item({ id: 'todo:t1', title: 'Send invoice' })]))} />);
92
+ expect(await screen.findByText('Send invoice')).toBeInTheDocument();
93
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Play' })).toBeInTheDocument());
94
+ expect(screen.queryByTestId('brief-text')).toBeNull();
95
+ });
96
+ });
@@ -0,0 +1,41 @@
1
+ // @vitest-environment node
2
+ /** The Today agenda's server side: build from the real needs-you queue, record an answer so the item leaves (ASK 2). */
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import { postRelayItems } from '../corpus/notify/relay-items';
5
+ import { answerTodayItem, loadTodayAgenda } from '../corpus/today-agenda-route';
6
+
7
+ const NOW = '2026-12-01T17:00:00Z';
8
+ function tenant() {
9
+ const rows = new Map<string, any>();
10
+ let seq = 0;
11
+ const http = {
12
+ get: vi.fn(async (_p: string, o?: { params?: Record<string, unknown> }) => ({ results: [...rows.values()].filter((r) => r.external_id === o?.params?.external_id__in) })),
13
+ post: vi.fn(async (_p: string, b: any) => { const row = { id: String(++seq), external_id: b.external_id, data: b.data }; rows.set(b.external_id, row); return row; }),
14
+ };
15
+ return { http: http as never, ownerSub: 'me', now: () => Date.parse(NOW), loadTodos: async () => [{ id: 't1', title: 'Send invoice', status: 'open', dueAt: '2026-12-01' }] };
16
+ }
17
+
18
+ describe('today agenda route', () => {
19
+ it('puts a relay question first, then the to-do, and a failing optional source does not blank the list', async () => {
20
+ const deps = { ...tenant(), loadDrafts: async () => { throw new Error('mail down'); } };
21
+ await postRelayItems(deps, { items: [{ id: 'go-live', text: 'CROCHETS: go live with v8?', options: ['yes', 'no'] }] });
22
+ const a = await loadTodayAgenda(deps, { timeZone: 'America/Los_Angeles' });
23
+ expect(a.doNow.map((i) => i.id)).toEqual(['relay:go-live', 'todo:t1']);
24
+ });
25
+
26
+ it('answering a question records it, tells the relay, and the item disappears', async () => {
27
+ const deliverRelay = vi.fn(async () => undefined);
28
+ const deps = { ...tenant(), deliverRelay };
29
+ await postRelayItems(deps, { items: [{ id: 'go-live', text: 'CROCHETS: go live with v8?', options: ['yes', 'no'] }] });
30
+ await answerTodayItem(deps, { id: 'relay:go-live', answer: 'yes' });
31
+ expect(deliverRelay).toHaveBeenCalledWith(expect.objectContaining({ id: 'go-live', answer: 'yes' }));
32
+ const a = await loadTodayAgenda(deps, { timeZone: 'America/Los_Angeles' });
33
+ expect(a.doNow.map((i) => i.id)).toEqual(['todo:t1']);
34
+ });
35
+
36
+ it('rejects an answer for an item that is not in the queue (404) and an empty answer (400)', async () => {
37
+ const deps = tenant();
38
+ await expect(answerTodayItem(deps, { id: 'relay:nope', answer: 'yes' })).rejects.toMatchObject({ status: 404 });
39
+ await expect(answerTodayItem(deps, { id: 'relay:nope', answer: ' ' })).rejects.toMatchObject({ status: 400 });
40
+ });
41
+ });
@@ -0,0 +1,143 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { buildTodayAgenda } from '../corpus/today-agenda';
3
+ import type { QueuedItem } from '../corpus/attention/types';
4
+
5
+ const now = Date.parse('2026-12-01T17:00:00Z'); // 09:00 in Los Angeles
6
+ const base = { now, timeZone: 'America/Los_Angeles' };
7
+ const q = (o: Partial<QueuedItem> & { id: string; text: string }): QueuedItem =>
8
+ ({ source: 'relay', class: 'needs-answer', importance: 50, ...o }) as QueuedItem;
9
+
10
+ describe('today agenda (ASK 2)', () => {
11
+ it('a fleet line that is a question is his decision, not a blocker; only PR, credential and approval lines are blockers', () => {
12
+ const a = buildTodayAgenda({ ...base, needsYou: [
13
+ q({ id: 'f1', text: 'Tandem sidebar name: "Plan" or "Strategy"?', source: 'fleet' }),
14
+ q({ id: 'f2', text: 'Need your GitHub token for the deploy', source: 'fleet' }),
15
+ ] });
16
+ expect(a.doNow.find((i) => i.id === 'f1')!.source).toBe('decision');
17
+ expect(a.doNow.find((i) => i.id === 'f2')!.source).toBe('blocked');
18
+ });
19
+
20
+ it('a question with no options is yes/no only when it reads as one; otherwise the answer is typed', () => {
21
+ const a = buildTodayAgenda({ ...base, needsYou: [
22
+ q({ id: 'a', text: 'Hard per-task memory limits? yes/no', source: 'fleet' }),
23
+ q({ id: 'b', text: 'Should we ship the pricing page?', source: 'fleet' }),
24
+ q({ id: 'c', text: 'Who owns the debugg.ai site?', source: 'fleet' }),
25
+ ] });
26
+ const act = (id: string) => a.doNow.find((i) => i.id === id)!.action as { kind: 'answer'; freeform: boolean };
27
+ expect(act('a').freeform).toBe(false);
28
+ expect(act('b').freeform).toBe(false);
29
+ expect(act('c').freeform).toBe(true);
30
+ });
31
+
32
+ it('ranks his decisions above due to-dos and gives each item a reason and exactly one action', () => {
33
+ const a = buildTodayAgenda({
34
+ ...base,
35
+ needsYou: [q({ id: 'relay:r1', text: 'CROCHETS: go live with v8?', options: ['yes', 'no'] })],
36
+ todos: [{ id: 't1', title: 'Send invoice', status: 'open', dueAt: '2026-12-01' }],
37
+ });
38
+ expect(a.doNow.map((i) => i.id)).toEqual(['relay:r1', 'todo:t1']);
39
+ for (const i of a.doNow) {
40
+ expect(i.reason.length).toBeGreaterThan(3);
41
+ expect(i.action.label.length).toBeGreaterThan(1);
42
+ }
43
+ expect(a.doNow[0].action).toMatchObject({ kind: 'answer', options: ['yes', 'no'] });
44
+ expect(a.doNow[1].action).toMatchObject({ kind: 'complete', todoIds: ['t1'] });
45
+ });
46
+
47
+ it('caps do-now at 5 and keeps the rest collapsed, in order', () => {
48
+ const todos = Array.from({ length: 8 }, (_, n) => ({ id: `t${n}`, title: `Task ${n}`, status: 'open', dueAt: '2026-12-01' }));
49
+ const a = buildTodayAgenda({ ...base, todos });
50
+ expect(a.doNow).toHaveLength(5);
51
+ expect(a.rest).toHaveLength(3);
52
+ expect(a.total).toBe(8);
53
+ });
54
+
55
+ it('drops done, dropped, undated and future to-dos and answered questions', () => {
56
+ const a = buildTodayAgenda({
57
+ ...base,
58
+ todos: [
59
+ { id: 'a', title: 'Done', status: 'done', dueAt: '2026-11-30' },
60
+ { id: 'b', title: 'Dropped', status: 'dropped', dueAt: '2026-11-30' },
61
+ { id: 'c', title: 'Someday', status: 'open' },
62
+ { id: 'd', title: 'Later', status: 'open', dueAt: '2026-12-09' },
63
+ ],
64
+ });
65
+ expect(a.total).toBe(0);
66
+ expect(a.empty).toBe(true);
67
+ });
68
+
69
+ it('collapses a recurring overdue to-do into one line that closes every copy', () => {
70
+ const todos = ['2026-11-20', '2026-11-21', '2026-11-22'].map((d, n) => ({ id: `r${n}`, title: '10 lovable / v0 builders reach out', status: 'open', dueAt: d }));
71
+ const a = buildTodayAgenda({ ...base, todos });
72
+ expect(a.total).toBe(1);
73
+ expect(a.doNow[0].reason).toMatch(/overdue since Nov 20/i);
74
+ expect(a.doNow[0].reason).toMatch(/3 times/);
75
+ expect(a.doNow[0].action).toMatchObject({ kind: 'complete', todoIds: ['r0', 'r1', 'r2'] });
76
+ });
77
+
78
+ it('puts an urgent blocker first and a PR waiting on him ahead of a plain question', () => {
79
+ const a = buildTodayAgenda({
80
+ ...base,
81
+ needsYou: [
82
+ q({ id: 'x1', text: 'Which tagline do you prefer?', importance: 30 }),
83
+ q({ id: 'x2', text: 'PR #935 waits for your merge approval', source: 'fleet', importance: 60, link: 'https://github.com/o/r/pull/935' }),
84
+ q({ id: 'x3', text: 'Prod is down', class: 'urgent', importance: 100 }),
85
+ ],
86
+ });
87
+ expect(a.doNow.map((i) => i.id)).toEqual(['x3', 'x2', 'x1']);
88
+ expect(a.doNow[1].action).toMatchObject({ kind: 'open', href: 'https://github.com/o/r/pull/935' });
89
+ expect(a.doNow[1].source).toBe('blocked');
90
+ });
91
+
92
+ it('lists drafts waiting to send and the next calendar events with a time reason', () => {
93
+ const a = buildTodayAgenda({
94
+ ...base,
95
+ drafts: [{ id: 'd1', title: 'Reply to Kevin', to: 'kevin@example.com', link: 'https://mail.example/d1' }],
96
+ events: [
97
+ { id: 'e1', title: 'Investor call', startsAt: '2026-12-01T19:00:00Z' },
98
+ { id: 'e0', title: 'Yesterday standup', startsAt: '2026-11-30T19:00:00Z' },
99
+ ],
100
+ });
101
+ const ids = a.doNow.map((i) => i.id);
102
+ expect(ids).toContain('draft:d1');
103
+ expect(ids).toContain('event:e1');
104
+ expect(ids).not.toContain('event:e0');
105
+ expect(a.doNow.find((i) => i.id === 'event:e1')!.reason).toMatch(/11:00 AM/);
106
+ expect(a.doNow.find((i) => i.id === 'draft:d1')!.action).toMatchObject({ kind: 'open', label: 'Review and send' });
107
+ });
108
+
109
+ it('merges a fleet line and a to-do that name the same thing into one item', () => {
110
+ const a = buildTodayAgenda({
111
+ ...base,
112
+ needsYou: [q({ id: 'f1', text: 'Send the invoice', source: 'fleet' })],
113
+ todos: [{ id: 't1', title: 'Send the invoice', status: 'open', dueAt: '2026-12-01' }],
114
+ });
115
+ expect(a.total).toBe(1);
116
+ });
117
+
118
+ it('shows what shipped since yesterday, one line each, newest first, capped', () => {
119
+ const a = buildTodayAgenda({
120
+ ...base,
121
+ shipped: [
122
+ { id: 's1', text: 'Needs-you push merged', at: '2026-11-30T20:00:00Z' },
123
+ { id: 's2', text: 'Old thing', at: '2026-11-20T20:00:00Z' },
124
+ { id: 's3', text: 'Talk key lookup fixed', at: '2026-12-01T10:00:00Z' },
125
+ ],
126
+ });
127
+ expect(a.shipped.map((s) => s.id)).toEqual(['s3', 's1']);
128
+ expect(a.empty).toBe(true); // shipped is a footer, not work
129
+ });
130
+
131
+ it('an optional or on-hold question waits behind a to-do that is due', () => {
132
+ const a = buildTodayAgenda({ ...base,
133
+ needsYou: [q({ id: 'd1', text: 'Search Console numbers (optional)', class: 'digest', importance: 10 })],
134
+ todos: [{ id: 't1', title: 'Send invoice', status: 'open', dueAt: '2026-12-01' }] });
135
+ expect(a.doNow.map((i) => i.id)).toEqual(['todo:t1', 'd1']);
136
+ expect(a.doNow[1].reason).toMatch(/can wait/i);
137
+ });
138
+
139
+ it('is stable for ties (same input, same order)', () => {
140
+ const todos = [{ id: 'b', title: 'B', status: 'open', dueAt: '2026-12-01' }, { id: 'a', title: 'A', status: 'open', dueAt: '2026-12-01' }];
141
+ expect(buildTodayAgenda({ ...base, todos }).doNow.map((i) => i.id)).toEqual(['todo:a', 'todo:b']);
142
+ });
143
+ });
@@ -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';
@@ -289,6 +289,10 @@ export type {
289
289
  // Today, defined once (bd startsim-cqeho): the date helpers and the selector the briefing composes on.
290
290
  export { dueDay, localDate, selectToday, todayKind } from './today';
291
291
  export type { TodayEntry, TodayItem, TodayKind, TodayRule } from './today';
292
+ export { buildTodayAgenda } from './today-agenda';
293
+ export type { AgendaAction, AgendaDraft, AgendaEvent, AgendaItem, AgendaShipped, AgendaSource, AgendaTodo, TodayAgenda, TodayAgendaInput } from './today-agenda';
294
+ export { answerTodayItem, loadTodayAgenda } from './today-agenda-route';
295
+ export type { TodayAgendaDeps } from './today-agenda-route';
292
296
  // Daily briefing: what is on one person's plate today (bd startsim-kgkp1).
293
297
  export * from './briefing';
294
298
  export * from './converse';
@@ -0,0 +1,80 @@
1
+ /**
2
+ * THE TODAY AGENDA'S SERVER SIDE (ASK 2). Request-free like the briefing and notify logic, so a Next route is a few
3
+ * lines. Every optional source is best-effort: a failing read leaves that source out, never the list.
4
+ *
5
+ * load = needs-you queue (relay items, decisions, fleet lines, orgs) + to-dos + drafts + events + shipped -> agenda
6
+ * answer = record his answer on a queue item (it leaves the queue), tell the relay, answer a one-question decision
7
+ */
8
+ import { buildNeedsYou, loadOrgItems, policyFrom } from './attention';
9
+ import type { OrgItem } from './attention/orgs';
10
+ import { buildFleetView } from './converse/fleet-view';
11
+ import { loadFleetSnapshot } from './converse/fleet';
12
+ import { answerDecision, getDecision } from './notify/handle';
13
+ import { loadState, saveState } from './notify/state';
14
+ import { NotifyError, type NotifyDeps } from './notify/types';
15
+ import { buildTodayAgenda, type AgendaDraft, type AgendaEvent, type AgendaShipped, type AgendaTodo, type TodayAgenda } from './today-agenda';
16
+
17
+ export interface TodayAgendaDeps {
18
+ http: NotifyDeps['http'];
19
+ ownerSub: string;
20
+ now?: () => number;
21
+ orgs?: () => Promise<OrgItem[]>;
22
+ /** The person's live to-dos (the same read the briefing uses). */
23
+ loadTodos(): Promise<AgendaTodo[]>;
24
+ /** Optional sources. A tenant that cannot read one omits it; nothing is invented in its place. */
25
+ loadDrafts?(): Promise<AgendaDraft[]>;
26
+ loadEvents?(): Promise<AgendaEvent[]>;
27
+ loadShipped?(): Promise<AgendaShipped[]>;
28
+ /** Hands an answer to a relay question back to the relay. */
29
+ deliverRelay?(d: { id: string; text: string; answer: string; source?: string; link?: string }): Promise<void>;
30
+ }
31
+
32
+ const soft = async <T>(read: (() => Promise<T[]>) | undefined): Promise<T[]> => {
33
+ if (!read) return [];
34
+ try { return await read(); } catch (e) { console.error('[today] a source could not be read', e); return []; }
35
+ };
36
+
37
+ async function queueFor(deps: TodayAgendaDeps) {
38
+ const [snap, state] = await Promise.all([loadFleetSnapshot(deps as never).catch(() => null), loadState(deps)]);
39
+ const queue = buildNeedsYou({
40
+ view: snap?.inputs ? buildFleetView(snap.inputs) : null,
41
+ decisions: state.decisions, policy: policyFrom(state.attention), answered: state.answered,
42
+ relay: state.relay_items, orgs: await soft(deps.orgs),
43
+ });
44
+ return { queue, state };
45
+ }
46
+
47
+ export async function loadTodayAgenda(deps: TodayAgendaDeps, opts: { timeZone?: string } = {}): Promise<TodayAgenda> {
48
+ const [{ queue }, todos, drafts, events, shipped] = await Promise.all([
49
+ queueFor(deps), soft(deps.loadTodos), soft(deps.loadDrafts), soft(deps.loadEvents), soft(deps.loadShipped),
50
+ ]);
51
+ return buildTodayAgenda({ now: (deps.now ?? Date.now)(), timeZone: opts.timeZone, needsYou: queue.items, todos, drafts, events, shipped });
52
+ }
53
+
54
+ /** Records his answer to one queue item. The item leaves the queue because `state.answered` now names it. */
55
+ export async function answerTodayItem(deps: TodayAgendaDeps, req: { id?: unknown; answer?: unknown }): Promise<{ id: string }> {
56
+ const id = String(req.id ?? '');
57
+ const answer = String(req.answer ?? '').replace(/\s+/g, ' ').trim().slice(0, 500);
58
+ if (!answer) throw new NotifyError('An answer is needed.', 400);
59
+ const { queue, state } = await queueFor(deps);
60
+ const item = queue.items.find((i) => i.id === id);
61
+ if (!item) throw new NotifyError('That is no longer waiting on you.', 404);
62
+ const relayItem = id.startsWith('relay:') ? (state.relay_items ?? []).find((r) => `relay:${r.id}` === id) : undefined;
63
+ let delivered: 'decision' | 'relay' | undefined;
64
+ let deliveryFailed = false;
65
+ if (relayItem && deps.deliverRelay) {
66
+ try { await deps.deliverRelay({ id: relayItem.id, text: relayItem.text, answer, ...(relayItem.source ? { source: relayItem.source } : {}), ...(relayItem.link ? { link: relayItem.link } : {}) }); delivered = 'relay'; }
67
+ catch (e) { deliveryFailed = true; console.error('[today] could not tell the relay his answer (kept for it to read back)', e); }
68
+ }
69
+ if (item.ref) {
70
+ try {
71
+ const d = await getDecision(deps as NotifyDeps, item.ref);
72
+ if (d.questions.length === 1) { await answerDecision(deps as NotifyDeps, item.ref, { answer }); delivered = 'decision'; }
73
+ } catch (e) { console.error('[today] could not deliver the answer to its decision', e); }
74
+ }
75
+ let answered = { ...state.answered, [id]: { answer, at: new Date((deps.now ?? Date.now)()).toISOString(), conversation_id: 'today', ...(item.ref ? { ref: item.ref } : {}), ...(delivered ? { delivered } : {}), ...(relayItem ? { source: 'relay' as const } : {}), ...(deliveryFailed ? { delivery_failed: true } : {}) } };
76
+ const keys = Object.keys(answered);
77
+ if (keys.length > 300) answered = Object.fromEntries(keys.slice(-300).map((k) => [k, (answered as Record<string, never>)[k]]));
78
+ await saveState(deps, { ...state, answered });
79
+ return { id };
80
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * THE TODAY AGENDA (ASK 2): a short ranked list of what the person must do today, each item with the reason it is
3
+ * today and ONE action. Provider independent and PURE: `now` and the person's zone come in, and every source is an
4
+ * optional input (a source that has nothing, or failed to read, is simply an empty list).
5
+ *
6
+ * Sources: (1) questions only he can answer and (4) agent work blocked on him, both from the needs-you queue;
7
+ * (2) drafts waiting for him to send; (3) due and overdue to-dos and today's calendar; (5) what shipped since yesterday.
8
+ * It supersedes "Today draws no to-dos and no Needs your call": one list, one flow, nothing new beside it.
9
+ */
10
+ import type { QueuedItem } from './attention/types';
11
+ import { dueDay, localDate } from './today';
12
+ import { isLiveStatus } from './item-status';
13
+
14
+ export interface AgendaTodo { id: string; title: string; status: string; dueAt?: string | null; priority?: number }
15
+ export interface AgendaDraft { id: string; title: string; to?: string; link?: string }
16
+ export interface AgendaEvent { id: string; title: string; startsAt: string; endsAt?: string; link?: string }
17
+ export interface AgendaShipped { id: string; text: string; at: string; link?: string }
18
+
19
+ export type AgendaSource = 'decision' | 'blocked' | 'draft' | 'todo' | 'event';
20
+ export type AgendaAction =
21
+ | { kind: 'answer'; label: string; questionId: string; options: string[]; /** An open question: the answer is typed, not Yes / No. */ freeform: boolean }
22
+ | { kind: 'complete'; label: string; todoIds: string[] }
23
+ | { kind: 'open'; label: string; href: string };
24
+
25
+ export interface AgendaItem { id: string; source: AgendaSource; title: string; reason: string; action: AgendaAction; score: number }
26
+ export interface TodayAgenda {
27
+ /** At most `cap` items: what to do now. */
28
+ doNow: AgendaItem[];
29
+ /** Everything else that is today, collapsed by default. */
30
+ rest: AgendaItem[];
31
+ /** One line each, newest first. A footer, not work. */
32
+ shipped: AgendaShipped[];
33
+ /** Items in doNow + rest. */
34
+ total: number;
35
+ /** Nothing to do (shipped lines do not count). */
36
+ empty: boolean;
37
+ }
38
+
39
+ export interface TodayAgendaInput {
40
+ now: number;
41
+ timeZone?: string;
42
+ needsYou?: QueuedItem[];
43
+ todos?: AgendaTodo[];
44
+ drafts?: AgendaDraft[];
45
+ events?: AgendaEvent[];
46
+ shipped?: AgendaShipped[];
47
+ cap?: number;
48
+ /** Shipped lines kept (default 5). */
49
+ shippedMax?: number;
50
+ }
51
+
52
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
53
+ const monthDay = (day: string) => `${MONTHS[Number(day.slice(5, 7)) - 1]} ${Number(day.slice(8, 10))}`;
54
+ const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
55
+ const clock = (iso: string, timeZone: string) =>
56
+ new Intl.DateTimeFormat('en-US', { timeZone, hour: 'numeric', minute: '2-digit' }).format(new Date(iso));
57
+ /** A line that is agent work waiting on him (a PR, a credential, an approval), not a question. */
58
+ const YES_NO = /yes\s*\/\s*no|^\s*(should|shall|can|may|do|does|did|is|are|will|would|ok|okay)\b/i;
59
+ const BLOCKED = /\b(pr|pull request|merge|credentials?|api key|token|password|login|approv\w*|sign[- ]?off|permission|access)\b/i;
60
+
61
+ // Base scores: an urgent blocker first, then blocked agents, then his decisions, then the clock, then drafts and to-dos.
62
+ const BASE = { urgent: 1000, blocked: 800, decision: 600, event: 500, draft: 400, overdue: 300, digest: 150, dueToday: 200 };
63
+
64
+ function fromNeedsYou(q: QueuedItem): AgendaItem {
65
+ const blocked = q.source === 'org' || BLOCKED.test(q.text);
66
+ const source: AgendaSource = blocked ? 'blocked' : 'decision';
67
+ const urgent = q.class === 'urgent';
68
+ const digest = q.class === 'digest' && !blocked;
69
+ const reason = urgent ? 'Urgent: waiting on you now'
70
+ : digest ? `Can wait: optional or on hold${q.from ? ` (${q.from})` : ''}`
71
+ : blocked ? `Work is blocked until you act${q.from ? ` (${q.from})` : ''}`
72
+ : `Waiting on your answer${q.from ? ` (${q.from})` : ''}`;
73
+ const action: AgendaAction = q.link && blocked
74
+ ? { kind: 'open', label: 'Open it', href: q.link }
75
+ : { kind: 'answer', label: q.options?.length ? 'Choose' : 'Answer', questionId: q.id, options: q.options ?? [], freeform: !q.options?.length && !YES_NO.test(q.text) };
76
+ return { id: q.id, source, title: q.text, reason, action, score: (urgent ? BASE.urgent : blocked ? BASE.blocked : digest ? BASE.digest : BASE.decision) + q.importance / 10 };
77
+ }
78
+
79
+ export function buildTodayAgenda(input: TodayAgendaInput): TodayAgenda {
80
+ const timeZone = input.timeZone ?? 'UTC';
81
+ const today = localDate(input.now, timeZone);
82
+ const items: AgendaItem[] = (input.needsYou ?? []).filter((q) => q.class !== 'noise').map(fromNeedsYou);
83
+
84
+ // To-dos: due on or before today, live, grouped by title so a recurring overdue to-do is one line that closes every copy.
85
+ const groups = new Map<string, { todos: AgendaTodo[]; days: string[] }>();
86
+ for (const t of input.todos ?? []) {
87
+ if (!isLiveStatus(t.status) || t.status === 'blocked') continue;
88
+ const day = dueDay(t.dueAt, timeZone);
89
+ if (!day || day > today) continue;
90
+ const g = groups.get(norm(t.title)) ?? { todos: [], days: [] };
91
+ g.todos.push(t); g.days.push(day);
92
+ groups.set(norm(t.title), g);
93
+ }
94
+ for (const g of groups.values()) {
95
+ const first = [...g.days].sort()[0];
96
+ const overdue = first < today;
97
+ const times = g.todos.length > 1 ? `, ${g.todos.length} times` : '';
98
+ items.push({
99
+ id: `todo:${g.todos[0].id}`, source: 'todo', title: g.todos[0].title,
100
+ reason: overdue ? `Overdue since ${monthDay(first)}${times}` : 'Due today',
101
+ action: { kind: 'complete', label: g.todos.length > 1 ? 'Done, close all' : 'Mark done', todoIds: g.todos.map((t) => t.id) },
102
+ score: (overdue ? BASE.overdue : BASE.dueToday) - Math.min(...g.todos.map((t) => t.priority ?? 4)),
103
+ });
104
+ }
105
+
106
+ for (const d of input.drafts ?? []) {
107
+ items.push({
108
+ id: `draft:${d.id}`, source: 'draft', title: d.title,
109
+ reason: d.to ? `Drafted for ${d.to}, waiting for you to send` : 'Drafted and waiting for you to send',
110
+ action: { kind: 'open', label: 'Review and send', href: d.link ?? '#' }, score: BASE.draft,
111
+ });
112
+ }
113
+
114
+ for (const e of input.events ?? []) {
115
+ const t = Date.parse(e.startsAt);
116
+ if (Number.isNaN(t) || localDate(t, timeZone) !== today) continue;
117
+ const end = e.endsAt ? Date.parse(e.endsAt) : t + 3600_000;
118
+ if (end < input.now) continue; // already over
119
+ items.push({
120
+ id: `event:${e.id}`, source: 'event', title: e.title,
121
+ reason: t <= input.now ? 'On now' : `Today at ${clock(e.startsAt, timeZone)}`,
122
+ action: { kind: 'open', label: 'Open event', href: e.link ?? '#' },
123
+ score: BASE.event + Math.max(0, 100 - Math.max(0, (t - input.now) / 3600_000) * 5),
124
+ });
125
+ }
126
+
127
+ // The same thing named twice (a fleet line and the to-do) is one item: keep the higher-ranked one.
128
+ const seen = new Map<string, AgendaItem>();
129
+ for (const i of [...items].sort(byRank)) if (!seen.has(norm(i.title))) seen.set(norm(i.title), i);
130
+ const ranked = [...seen.values()].sort(byRank);
131
+
132
+ const cap = input.cap ?? 5;
133
+ const yesterday = shiftDay(today, -1);
134
+ const shipped = [...(input.shipped ?? [])]
135
+ .filter((s) => !Number.isNaN(Date.parse(s.at)) && localDate(Date.parse(s.at), timeZone) >= yesterday)
136
+ .sort((a, b) => Date.parse(b.at) - Date.parse(a.at))
137
+ .slice(0, input.shippedMax ?? 5);
138
+ return { doNow: ranked.slice(0, cap), rest: ranked.slice(cap), shipped, total: ranked.length, empty: ranked.length === 0 };
139
+ }
140
+
141
+ const byRank = (a: AgendaItem, b: AgendaItem) => b.score - a.score || a.id.localeCompare(b.id);
142
+ function shiftDay(day: string, by: number): string {
143
+ const d = new Date(`${day}T00:00:00Z`); d.setUTCDate(d.getUTCDate() + by); return d.toISOString().slice(0, 10);
144
+ }
@@ -0,0 +1,40 @@
1
+ import { Linking, View } from 'react-native';
2
+ import { Alert, Button, ListRow, Skeleton, Text, useTheme } from '@startsimpli/ui-native';
3
+ import { useControllerState } from '../components/useControllerState';
4
+ import type { AgendaItem } from '../../corpus/today-agenda';
5
+ import type { AgendaController } from './agenda-controller';
6
+
7
+ /** Today's ranked list on the phone: each row is its title, the reason it is today, and ONE action. */
8
+ export function AgendaSection({ controller }: { controller: AgendaController }) {
9
+ const theme = useTheme();
10
+ const s = useControllerState(controller);
11
+ if (s.loading && !s.agenda) return <Skeleton height={120} />;
12
+ if (s.error && !s.agenda) return <Alert variant="destructive">{s.error}</Alert>;
13
+ const items = s.agenda ? [...s.agenda.doNow] : [];
14
+ const rest = s.agenda?.rest.length ?? 0;
15
+ return (
16
+ <View testID="home-agenda" style={{ gap: theme.spacing.xs }}>
17
+ {s.notice ? <Alert variant="destructive">{s.notice}</Alert> : null}
18
+ {items.length === 0 ? <Text variant="callout">Nothing needs you today.</Text> : items.map((i) => <Row key={i.id} item={i} controller={controller} />)}
19
+ {rest > 0 ? <Text variant="footnote" testID="home-agenda-rest">{rest} more on the web</Text> : null}
20
+ </View>
21
+ );
22
+ }
23
+
24
+ function Row({ item, controller }: { item: AgendaItem; controller: AgendaController }) {
25
+ const a = item.action;
26
+ return (
27
+ <ListRow
28
+ testID={`home-agenda-${item.id}`}
29
+ title={item.title}
30
+ subtitle={a.kind === 'answer' && a.freeform ? `${item.reason}. Answer in Talk.` : item.reason}
31
+ footer={
32
+ <>
33
+ {a.kind === 'answer' && a.freeform ? null : a.kind === 'answer' ? (a.options.length ? a.options : ['Yes', 'No']).map((o) => <Button key={o} testID={`home-agenda-answer-${o}`} title={o} size="sm" onPress={() => void controller.answer(item, o)} />)
34
+ : a.kind === 'complete' ? <Button testID="home-agenda-complete" title={a.label} size="sm" onPress={() => void controller.complete(item)} />
35
+ : <Button testID="home-agenda-open" title={a.label} size="sm" onPress={() => { void Linking.openURL(a.href); }} />}
36
+ </>
37
+ }
38
+ />
39
+ );
40
+ }
@@ -4,6 +4,8 @@ import { Alert, Button, EmptyState, Text, Header, IconTile, ListRow, SectionHead
4
4
  import { iconName, toneKey } from '../screens/shared/displayView';
5
5
  import { useControllerState } from '../components/useControllerState';
6
6
  import { timeAgo, type HomeArrival, type HomeController } from './controller';
7
+ import type { AgendaController } from './agenda-controller';
8
+ import { AgendaSection } from './AgendaSection';
7
9
 
8
10
  export interface HomeScreenProps {
9
11
  controller: HomeController;
@@ -25,35 +27,38 @@ export interface HomeScreenProps {
25
27
  /** False while another tab is showing; the counts reload each time Home comes back. Default true. */
26
28
  active?: boolean;
27
29
  now?: () => number;
30
+ /** The ranked do-now list. When given it IS Today: it replaces "What has come in" and "Latest arrivals" (opt-in; other tenants keep them). */
31
+ agenda?: AgendaController;
28
32
  }
29
33
 
30
34
  /** The front door, as the web Home draws it: brand, "What has come in" counts, "Latest arrivals". */
31
- export function HomeScreen({ controller, brand, tagline, onTalk, onOpenPlan, briefing, title, subtitle, onOpenType, onOpenArrival, active = true, now = Date.now }: HomeScreenProps) {
35
+ export function HomeScreen({ controller, brand, tagline, onTalk, onOpenPlan, briefing, title, subtitle, onOpenType, onOpenArrival, active = true, now = Date.now, agenda }: HomeScreenProps) {
32
36
  const theme = useTheme();
33
37
  const haptic = useHaptics();
34
38
  const s = useControllerState(controller);
35
- useEffect(() => { if (active) void controller.load(); }, [controller, active]);
39
+ useEffect(() => { if (active) void (agenda ? agenda.load() : controller.load()); }, [controller, agenda, active]);
36
40
  return (
37
41
  <View style={{ flex: 1 }}>
38
42
  <Header large testID="home-header" title={title ?? brand} subtitle={title ? undefined : (subtitle ?? tagline)} />
39
43
  <FlatList
40
44
  testID="home-list"
41
- data={s.arrivals}
45
+ data={agenda ? [] : s.arrivals}
42
46
  keyExtractor={(a) => `${a.type}-${a.id}`}
43
47
  refreshControl={<RefreshControl refreshing={false} onRefresh={() => { haptic('light', 'pull-to-refresh'); void controller.refresh(); }} tintColor={theme.colors.mutedForeground} />}
44
48
  contentContainerStyle={{ paddingHorizontal: theme.layout.gutter, paddingBottom: theme.spacing.xl, flexGrow: 1 }}
45
49
  ListHeaderComponent={
46
50
  <View style={{ gap: theme.spacing.xs, paddingBottom: theme.spacing.xs }}>
47
51
  {briefing ? <View testID="home-briefing" style={{ marginTop: theme.spacing.sm, paddingBottom: theme.spacing.sm }}>{briefing}</View> : null}
48
- {s.dueSoon ? (
52
+ {agenda ? <AgendaSection controller={agenda} /> : null}
53
+ {!agenda && s.dueSoon ? (
49
54
  <Pressable accessibilityRole="button" accessibilityLabel={`${s.dueSoon}. Open Plan`} disabled={!onOpenPlan} onPress={onOpenPlan} testID="home-due-soon" hitSlop={8}>
50
55
  <Text variant="callout">{s.dueSoon}{onOpenPlan ? ' ›' : ''}</Text>
51
56
  </Pressable>
52
57
  ) : null}
53
58
  {onTalk ? <Button testID="home-talk" title="Talk to Tandem" size="lg" style={{ marginTop: theme.spacing.sm }} onPress={onTalk} /> : null}
54
59
  {s.error ? <Alert variant="destructive">{s.error}</Alert> : null}
55
- <SectionHeader title="What has come in" />
56
- <View style={{ flexDirection: 'row', gap: theme.spacing.sm }}>
60
+ {agenda ? null : <SectionHeader title="What has come in" />}
61
+ {agenda ? null : <View style={{ flexDirection: 'row', gap: theme.spacing.sm }}>
57
62
  {s.metrics.map((m) => (
58
63
  <View key={m.key} style={{ flex: 1, minWidth: 0 }} testID={`home-metric-${m.key}`}>
59
64
  {s.loading ? <Skeleton height={72} /> : (
@@ -63,11 +68,11 @@ export function HomeScreen({ controller, brand, tagline, onTalk, onOpenPlan, bri
63
68
  )}
64
69
  </View>
65
70
  ))}
66
- </View>
67
- <SectionHeader title="Latest arrivals" />
71
+ </View>}
72
+ {agenda ? null : <SectionHeader title="Latest arrivals" />}
68
73
  </View>
69
74
  }
70
- ListEmptyComponent={s.loading ? null : <EmptyState icon="note" title="No records yet" description="Record a note to get started." />}
75
+ ListEmptyComponent={agenda || s.loading ? null : <EmptyState icon="note" title="No records yet" description="Record a note to get started." />}
71
76
  renderItem={({ item }) => (
72
77
  <ListRow
73
78
  leading={<IconTile icon={iconName(item.display.icon)} tone={item.display.status ? toneKey(item.display.status.tone) : 'info'} />}
@@ -0,0 +1,54 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createAgendaController } from '../agenda-controller';
3
+ import type { AgendaItem, TodayAgenda } from '../../../corpus/today-agenda';
4
+
5
+ const todo = (id: string): AgendaItem => ({ id: `todo:${id}`, source: 'todo', title: id, reason: 'Due today', score: 1, action: { kind: 'complete', label: 'Mark done', todoIds: [id] } });
6
+ const q = (id: string): AgendaItem => ({ id, source: 'decision', title: id, reason: 'Only you can decide', score: 2, action: { kind: 'answer', label: 'Choose', questionId: id, options: ['yes', 'no'], freeform: false } });
7
+ const agenda = (doNow: AgendaItem[], rest: AgendaItem[] = []): TodayAgenda => ({ doNow, rest, shipped: [], total: doNow.length + rest.length, empty: !doNow.length && !rest.length });
8
+ const api = (a: TodayAgenda) => ({ load: vi.fn(async () => a), answer: vi.fn(async () => undefined), complete: vi.fn(async () => undefined) });
9
+
10
+ describe('native agenda controller', () => {
11
+ it('loads the agenda once and exposes it', async () => {
12
+ const c = createAgendaController({ api: api(agenda([todo('a')])) });
13
+ expect(c.getState().loading).toBe(true);
14
+ await c.load();
15
+ expect(c.getState()).toMatchObject({ loading: false, error: null });
16
+ expect(c.getState().agenda!.doNow).toHaveLength(1);
17
+ });
18
+
19
+ it('completing removes the item at once, saves through the api, and a later rest item moves up to fill do-now', async () => {
20
+ const x = api(agenda([todo('a')], [todo('b')]));
21
+ const c = createAgendaController({ api: x, cap: 1 });
22
+ await c.load();
23
+ const p = c.complete(c.getState().agenda!.doNow[0]);
24
+ expect(c.getState().agenda!.doNow.map((i) => i.id)).toEqual(['todo:b']);
25
+ await p;
26
+ expect(x.complete).toHaveBeenCalledWith(['a']);
27
+ });
28
+
29
+ it('answering saves the answer under the question id and removes the item', async () => {
30
+ const x = api(agenda([q('relay:r1')]));
31
+ const c = createAgendaController({ api: x });
32
+ await c.load();
33
+ await c.answer(c.getState().agenda!.doNow[0], 'yes');
34
+ expect(x.answer).toHaveBeenCalledWith('relay:r1', 'yes');
35
+ expect(c.getState().agenda!.doNow).toHaveLength(0);
36
+ });
37
+
38
+ it('puts the item back with a plain notice when the save fails', async () => {
39
+ const x = api(agenda([todo('a')]));
40
+ x.complete.mockRejectedValueOnce(new Error('offline'));
41
+ const c = createAgendaController({ api: x });
42
+ await c.load();
43
+ await c.complete(c.getState().agenda!.doNow[0]);
44
+ expect(c.getState().agenda!.doNow.map((i) => i.id)).toEqual(['todo:a']);
45
+ expect(c.getState().notice).toMatch(/did not save/i);
46
+ });
47
+
48
+ it('a failed load is an error message, not a crash', async () => {
49
+ const x = { ...api(agenda([])), load: vi.fn(async () => { throw new Error('boom'); }) };
50
+ const c = createAgendaController({ api: x });
51
+ await c.load();
52
+ expect(c.getState().error).toBeTruthy();
53
+ });
54
+ });
@@ -0,0 +1,42 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ vi.mock('react-native', async () => {
4
+ const stub = await import('../../../../../ui-native/test/rn-stub');
5
+ return { ...stub, Linking: { openURL: async () => {} } };
6
+ });
7
+
8
+ import { act, allText, hostById, press, render } from '../../../../../ui-native/test/render';
9
+ import { createFakeNativeCorpusApi } from '../../corpus/fake';
10
+ import { createHomeController } from '../controller';
11
+ import { createAgendaController } from '../agenda-controller';
12
+ import { HomeScreen } from '../HomeScreen';
13
+ import type { TodayAgenda } from '../../../corpus/today-agenda';
14
+
15
+ const agenda: TodayAgenda = {
16
+ doNow: [{ id: 'todo:t1', source: 'todo', title: 'Send invoice', reason: 'Overdue since Nov 20', score: 1, action: { kind: 'complete', label: 'Mark done', todoIds: ['t1'] } }],
17
+ rest: [], shipped: [], total: 1, empty: false,
18
+ };
19
+ const tick = () => act(async () => { await new Promise((res) => setTimeout(res, 20)); });
20
+
21
+ describe('HomeScreen with an agenda', () => {
22
+ it('shows the ranked list instead of the counts and arrivals, and marking done closes the to-do', async () => {
23
+ const api = { load: async () => agenda, answer: vi.fn(async () => {}), complete: vi.fn(async () => {}) };
24
+ const home = createHomeController({ api: createFakeNativeCorpusApi(), types: [{ key: 'commitment', label: 'To-dos' }] });
25
+ const r = render(<HomeScreen controller={home} brand="Tandem" title="Today" agenda={createAgendaController({ api })} />);
26
+ await tick();
27
+ const text = allText(r);
28
+ expect(text).toContain('Send invoice');
29
+ expect(text).toContain('Overdue since Nov 20');
30
+ expect(text).not.toContain('What has come in');
31
+ expect(text).not.toContain('Latest arrivals');
32
+ await press(hostById(r, 'home-agenda-complete'));
33
+ expect(api.complete).toHaveBeenCalledWith(['t1']);
34
+ });
35
+
36
+ it('without an agenda it is unchanged: counts and arrivals', async () => {
37
+ const home = createHomeController({ api: createFakeNativeCorpusApi(), types: [{ key: 'commitment', label: 'To-dos' }] });
38
+ const r = render(<HomeScreen controller={home} brand="Tandem" title="Today" />);
39
+ await tick();
40
+ expect(allText(r)).toContain('What has come in');
41
+ });
42
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The Today list's state on the phone (ASK 2): the same `TodayAgenda` the web list draws, as a framework-free
3
+ * controller. Done items leave at once; a failed save puts the item back with a plain notice.
4
+ */
5
+ import type { TodayAgendaApi } from '../../components/pages/home/TodayAgendaList';
6
+ import type { AgendaItem, TodayAgenda } from '../../corpus/today-agenda';
7
+
8
+ export interface AgendaState { loading: boolean; agenda: TodayAgenda | null; error: string | null; notice: string | null }
9
+ export interface AgendaController {
10
+ getState(): AgendaState;
11
+ subscribe(listener: () => void): () => void;
12
+ load(): Promise<void>;
13
+ answer(item: AgendaItem, answer: string): Promise<void>;
14
+ complete(item: AgendaItem): Promise<void>;
15
+ }
16
+
17
+ const without = (a: TodayAgenda, id: string, cap: number): TodayAgenda => {
18
+ const all = [...a.doNow, ...a.rest].filter((i) => i.id !== id);
19
+ return { ...a, doNow: all.slice(0, cap), rest: all.slice(cap), total: all.length, empty: all.length === 0 };
20
+ };
21
+
22
+ export function createAgendaController({ api, cap = 5 }: { api: TodayAgendaApi; cap?: number }): AgendaController {
23
+ let state: AgendaState = { loading: true, agenda: null, error: null, notice: null };
24
+ const listeners = new Set<() => void>();
25
+ const set = (patch: Partial<AgendaState>) => { state = { ...state, ...patch }; listeners.forEach((l) => l()); };
26
+
27
+ async function settle(item: AgendaItem, save: () => Promise<void>) {
28
+ const before = state.agenda;
29
+ if (!before) return;
30
+ set({ agenda: without(before, item.id, cap), notice: null });
31
+ try { await save(); }
32
+ catch { set({ agenda: before, notice: 'That did not save. It is back in your list; try again.' }); }
33
+ }
34
+
35
+ return {
36
+ getState: () => state,
37
+ subscribe(l) { listeners.add(l); return () => { listeners.delete(l); }; },
38
+ async load() {
39
+ set({ loading: true });
40
+ try { set({ loading: false, agenda: await api.load(), error: null }); }
41
+ catch (e) { set({ loading: false, error: (e as Error)?.message || 'Today could not be loaded.' }); }
42
+ },
43
+ answer: (item, answer) => settle(item, () => api.answer(item.action.kind === 'answer' ? item.action.questionId : item.id, answer)),
44
+ complete: (item) => settle(item, () => api.complete(item.action.kind === 'complete' ? item.action.todoIds : [])),
45
+ };
46
+ }
@@ -6,6 +6,7 @@ import type { FoundryTab } from '../components/FoundryTabsShell';
6
6
  import type { NativeCorpusApi } from '../corpus/api';
7
7
  import { createHomeController, type HomeController, type HomeType } from './controller';
8
8
  import { HomeScreen } from './HomeScreen';
9
+ import type { AgendaController } from './agenda-controller';
9
10
 
10
11
  export interface HomeTabOptions {
11
12
  api: Pick<NativeCorpusApi, 'entities'> & Partial<Pick<NativeCorpusApi, 'schema' | 'corpus'>>;
@@ -27,6 +28,8 @@ export interface HomeTabOptions {
27
28
  /** The Today framing: its title and one plain line (`TAB_COPY.today`). Absent: the brand and tagline. */
28
29
  copy?: { label: string; subtitle: string };
29
30
  timeZone?: string;
31
+ /** The ranked do-now list (ASK 2). When given, Today shows it instead of the counts and arrivals. */
32
+ agenda?: AgendaController;
30
33
  }
31
34
 
32
35
  /** The to-dos counted on the due-soon line: one server page of what is still owed. */
@@ -40,7 +43,7 @@ function dueSoonReader(api: HomeTabOptions['api'], timeZone?: string) {
40
43
  }
41
44
 
42
45
  /** The Home tab as one `FoundryTabsShell` entry. */
43
- export function homeTab({ api, brand, tagline, key = 'home', label = 'Home', types, controller = createHomeController({ api, types, displays: api.schema ? () => api.schema!.displays() : undefined, dueSoon: dueSoonReader(api), hideArrivals: ['commitment'] }), tabs = {}, talkKey, planKey, briefing, copy }: HomeTabOptions): FoundryTab {
46
+ export function homeTab({ api, brand, tagline, key = 'home', label = 'Home', types, controller = createHomeController({ api, types, displays: api.schema ? () => api.schema!.displays() : undefined, dueSoon: dueSoonReader(api), hideArrivals: ['commitment'] }), tabs = {}, talkKey, planKey, briefing, copy, agenda }: HomeTabOptions): FoundryTab {
44
47
  return {
45
48
  key, label,
46
49
  render: ({ openTab, active }) => (
@@ -51,6 +54,7 @@ export function homeTab({ api, brand, tagline, key = 'home', label = 'Home', typ
51
54
  tagline={tagline}
52
55
  title={copy?.label}
53
56
  briefing={briefing?.()}
57
+ agenda={agenda}
54
58
  onTalk={talkKey ? () => openTab(talkKey) : undefined}
55
59
  onOpenPlan={planKey ? () => openTab(planKey) : undefined}
56
60
  onOpenType={(type) => { if (tabs[type]) openTab(tabs[type]); }}
@@ -40,6 +40,8 @@ export { TrackerListScreen, type TrackerListScreenProps } from './tracker/Tracke
40
40
  export { TrackerDetailScreen, type TrackerDetailScreenProps } from './tracker/TrackerDetailScreen';
41
41
  export { trackerTab, type TrackerTabOptions } from './tracker/tab';
42
42
  export * from './home/controller';
43
+ export { createAgendaController } from './home/agenda-controller';
44
+ export type { AgendaController, AgendaState } from './home/agenda-controller';
43
45
  export { HomeScreen, type HomeScreenProps } from './home/HomeScreen';
44
46
  export { homeTab, type HomeTabOptions } from './home/tab';
45
47
  export { createStore, errorMessage } from './screens/store';