@startsimpli/integrations 0.2.150 → 0.2.152

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 (36) hide show
  1. package/package.json +7 -7
  2. package/src/__tests__/briefing-script.test.ts +26 -0
  3. package/src/__tests__/helpers/question-tenant.ts +45 -0
  4. package/src/__tests__/question-checkin.test.ts +139 -0
  5. package/src/__tests__/question-learn.test.ts +124 -0
  6. package/src/__tests__/question-voice-parse.test.ts +110 -0
  7. package/src/__tests__/question-voice.test.ts +225 -0
  8. package/src/__tests__/tracker-done-stamp.test.ts +42 -0
  9. package/src/__tests__/tracker-timeline-component.test.tsx +81 -0
  10. package/src/__tests__/tracker-timeline-reader.test.ts +94 -0
  11. package/src/__tests__/tracker-timeline.test.ts +209 -0
  12. package/src/__tests__/voice-due-inherited.test.ts +37 -0
  13. package/src/components/pages/TrackerPage.tsx +8 -0
  14. package/src/components/pages/tracker/TrackerTimeline.tsx +123 -0
  15. package/src/corpus/briefing/cache-key.ts +2 -2
  16. package/src/corpus/briefing/generate.ts +5 -1
  17. package/src/corpus/briefing/script.ts +12 -3
  18. package/src/corpus/briefing/speak.ts +8 -0
  19. package/src/corpus/briefing/types.ts +2 -0
  20. package/src/corpus/client.ts +12 -1
  21. package/src/corpus/questions/answer.ts +11 -1
  22. package/src/corpus/questions/checkin-handle.ts +67 -0
  23. package/src/corpus/questions/checkin.ts +103 -0
  24. package/src/corpus/questions/index.ts +11 -0
  25. package/src/corpus/questions/learn.ts +135 -0
  26. package/src/corpus/questions/respond.ts +76 -0
  27. package/src/corpus/questions/store.ts +5 -1
  28. package/src/corpus/questions/sync.ts +20 -3
  29. package/src/corpus/questions/types.ts +10 -2
  30. package/src/corpus/questions/voice-parse.ts +98 -0
  31. package/src/corpus/questions/voice.ts +227 -0
  32. package/src/corpus/tracker-timeline-client.ts +117 -0
  33. package/src/corpus/tracker-timeline.ts +228 -0
  34. package/src/corpus/types.ts +10 -0
  35. package/src/corpus/voice-due.ts +29 -4
  36. package/src/corpus/work-item-logic.ts +1 -1
@@ -0,0 +1,225 @@
1
+ // @vitest-environment node
2
+ /**
3
+ * Answering the clarifying-question queue by voice (bd startsim-tmrvi.5): one press answers the best open
4
+ * question, says it back, and asks the next. Real parser, real queue, real answer path, in-memory tenant.
5
+ */
6
+ import { describe, expect, it, vi } from 'vitest';
7
+
8
+ import { commitmentEditSeam } from '../corpus/briefing/actions/seam';
9
+ import { createMemoryActionLog } from '../corpus/briefing/actions/log';
10
+ import { createPlanningApi } from '../corpus/client';
11
+ import { guessOf, unknownGuess } from '../corpus/extraction-fields';
12
+ import { listOpenQuestions, syncOpenQuestions } from '../corpus/questions';
13
+ import { storeFor } from '../corpus/questions/sync';
14
+ import { answerQuestionByVoice, VoiceAnswerError, type VoiceAnswerDeps } from '../corpus/questions/voice';
15
+ import { tenant } from './helpers/question-tenant';
16
+
17
+ const SCOPE = { orgId: 'o' } as never;
18
+ const ME = 'user-me';
19
+ const NOW = Date.parse('2026-11-04T15:00:00Z'); // Wednesday, 10:00 in New York
20
+ const TZ = 'America/New_York';
21
+
22
+ const item = (id: string, data: Record<string, unknown> = {}) => ({
23
+ id, entity_type: 'commitment', external_id: `commit:${id}`, name: String(data.title ?? id),
24
+ data: { title: `Item ${id}`, status: 'open', mentions: [{ document_id: 'note1', quote: 'q' }], ...data },
25
+ });
26
+ const held = (id: string, title: string) => item(id, {
27
+ title, sync_state: 'needs_team', open_question_kind: 'team', open_question: 'Which team is this for?',
28
+ });
29
+ const fields = (over: object) => ({
30
+ due: unknownGuess('x'), project: unknownGuess('x'), owner: unknownGuess('x'), priority: unknownGuess('x'), estimate: unknownGuess('x'), ...over,
31
+ });
32
+ const note = (records: unknown[]) => ({
33
+ id: 'note1', entity_type: 'source_document', external_id: 'voice:n1', name: 'Voice note',
34
+ data: { source: 'voice', title: 'Voice note', voice_items: JSON.stringify(records) },
35
+ });
36
+
37
+ const TEAMS = [{ value: 'team-eng', label: 'Engineering' }, { value: 'team-ops', label: 'Operations' }];
38
+
39
+ function setup(rows: Parameters<typeof tenant>[0], extra: Partial<VoiceAnswerDeps> = {}) {
40
+ const t = tenant(rows);
41
+ const api = createPlanningApi({ http: t.http, scope: SCOPE, supportedFilters: [], resolveParticipants: false } as never);
42
+ const clock = { now: NOW };
43
+ const deps: VoiceAnswerDeps = {
44
+ http: t.http, scope: SCOPE, ownerSub: ME, now: () => clock.now, timeZone: TZ,
45
+ seam: commitmentEditSeam({ api, http: t.http, scope: SCOPE }),
46
+ patchItem: vi.fn(async (id: string, wire: Record<string, unknown>) => { const r = t.rows.get(id)!; r.data = { ...r.data, ...wire }; }),
47
+ fileItem: vi.fn(async () => undefined),
48
+ setPersonalContainer: vi.fn(async () => undefined),
49
+ options: async (q) => (q.kind === 'team' ? TEAMS : []),
50
+ log: createMemoryActionLog(),
51
+ ...extra,
52
+ };
53
+ return { t, deps, clock };
54
+ }
55
+
56
+ const vet = () => [
57
+ item('vet', { title: 'Call the vet', due_at: '2026-11-06' }),
58
+ note([{ section: 's', title: 'Call the vet', fields: fields({
59
+ due: guessOf('2026-11-06', 0.5, 'assumed', 'said Friday on a Friday', { question: 'Did you mean today or next Friday?' }),
60
+ }) }]),
61
+ ];
62
+
63
+ let press = 0;
64
+ const say = (deps: VoiceAnswerDeps, utterance: string, over: object = {}) =>
65
+ answerQuestionByVoice(deps, { clientActionId: `press-${String(++press).padStart(4, '0')}`, utterance, ...over });
66
+
67
+ describe('answerQuestionByVoice', () => {
68
+ it('answers a due date, says it back, and asks the next question', async () => {
69
+ const { t, deps } = setup([...vet(), held('bench', "Order dad's bench")]);
70
+ await syncOpenQuestions(deps);
71
+ // the team question outranks the due date, so it is asked first
72
+ const first = await say(deps, 'operations');
73
+ expect(first).toMatchObject({ kind: 'answered' });
74
+ expect(first.spoken).toMatch(/Operations/);
75
+ expect(first.next?.kind).toBe('due_date');
76
+ expect(first.spoken).toMatch(/Call the vet/);
77
+ expect(deps.patchItem).toHaveBeenCalledWith('bench', expect.objectContaining({ external_container_id: 'team-ops' }));
78
+
79
+ const second = await say(deps, 'tomorrow');
80
+ expect(second).toMatchObject({ kind: 'answered', next: null, remaining: 0 });
81
+ expect(second.spoken).toMatch(/due tomorrow/);
82
+ expect(second.spoken).toMatch(/everything/i);
83
+ expect(String(t.rows.get('vet')!.data.due_at)).toContain('2026-11-05');
84
+ });
85
+
86
+ it('a repeat press does nothing twice', async () => {
87
+ const { t, deps } = setup(vet());
88
+ await syncOpenQuestions(deps);
89
+ const a = await answerQuestionByVoice(deps, { clientActionId: 'press-repeat-1', utterance: 'today' });
90
+ const writes = [...t.rows.values()].map((r) => r.version).join(',');
91
+ const b = await answerQuestionByVoice(deps, { clientActionId: 'press-repeat-1', utterance: 'today' });
92
+ expect(b.replayed).toBe(true);
93
+ expect(b.spoken).toBe(a.spoken);
94
+ expect([...t.rows.values()].map((r) => r.version).join(',')).toBe(writes);
95
+ });
96
+
97
+ it('yes keeps the guess and confirms the item', async () => {
98
+ const { t, deps } = setup(vet());
99
+ await syncOpenQuestions(deps);
100
+ const out = await say(deps, 'yes keep it');
101
+ expect(out.kind).toBe('accepted');
102
+ expect(String(t.rows.get('vet')!.data.due_at)).toContain('2026-11-06');
103
+ expect(await listOpenQuestions(deps)).toEqual([]);
104
+ });
105
+
106
+ it('never says an id aloud when keeping a guess', async () => {
107
+ const { deps } = setup([held('bench', "Order dad's bench")]);
108
+ await syncOpenQuestions(deps);
109
+ const q = (await listOpenQuestions(deps))[0];
110
+ await storeFor(deps).put(q.itemId, q.kind, q.question, { assumed: JSON.stringify({ value: 'team-ops', confidence: 0.5, reason: 'r' }) });
111
+ const out = await say(deps, 'yes');
112
+ expect(out.kind).toBe('accepted');
113
+ expect(out.spoken).toMatch(/Operations/);
114
+ expect(out.spoken).not.toMatch(/team-ops/);
115
+ });
116
+
117
+ it('skip leaves the item alone and does not ask again until later', async () => {
118
+ const { t, deps, clock } = setup([held('bench', "Order dad's bench")]);
119
+ await syncOpenQuestions(deps);
120
+ const out = await say(deps, 'skip it');
121
+ expect(out.kind).toBe('skipped');
122
+ expect(t.rows.get('bench')!.data.status).toBe('open'); // not dropped
123
+ await syncOpenQuestions(deps);
124
+ expect(await listOpenQuestions(deps)).toEqual([]); // snoozed
125
+ clock.now += 13 * 3_600_000;
126
+ await syncOpenQuestions(deps);
127
+ expect(await listOpenQuestions(deps)).toHaveLength(1); // a held item is asked again
128
+ });
129
+
130
+ it('asks back instead of guessing, and keeps the question open', async () => {
131
+ const { deps } = setup([held('bench', "Order dad's bench")]);
132
+ await syncOpenQuestions(deps);
133
+ const out = await say(deps, 'the purple one');
134
+ expect(out.kind).toBe('clarify');
135
+ expect(out.spoken).toMatch(/Engineering/);
136
+ expect(out.next).toBeNull();
137
+ expect(await listOpenQuestions(deps)).toHaveLength(1);
138
+ });
139
+
140
+ it('undo puts a due date back and reopens the question', async () => {
141
+ const { t, deps } = setup(vet());
142
+ await syncOpenQuestions(deps);
143
+ await say(deps, 'next week');
144
+ expect(String(t.rows.get('vet')!.data.due_at)).toContain('2026-11-09');
145
+ const out = await say(deps, 'undo that');
146
+ expect(out.kind).toBe('undone');
147
+ expect(String(t.rows.get('vet')!.data.due_at)).toContain('2026-11-06');
148
+ expect(await listOpenQuestions(deps)).toHaveLength(1);
149
+ });
150
+
151
+ it('says plainly when an answer cannot be undone by voice', async () => {
152
+ const { deps } = setup([held('bench', "Order dad's bench")]);
153
+ await syncOpenQuestions(deps);
154
+ await say(deps, 'engineering');
155
+ const out = await say(deps, 'undo');
156
+ expect(out.kind).toBe('clarify');
157
+ expect(out.spoken).toMatch(/cannot undo/);
158
+ });
159
+
160
+ it('says so when nothing is waiting', async () => {
161
+ const { deps } = setup([item('plain')]);
162
+ await syncOpenQuestions(deps);
163
+ expect((await say(deps, 'today')).kind).toBe('nothing');
164
+ });
165
+
166
+ it('answers a named question, not just the best one', async () => {
167
+ const { deps } = setup([...vet(), held('bench', "Order dad's bench")]);
168
+ await syncOpenQuestions(deps);
169
+ const due = (await listOpenQuestions(deps)).find((q) => q.kind === 'due_date')!;
170
+ const out = await say(deps, 'today', { questionId: due.id });
171
+ expect(out.question?.id).toBe(due.id);
172
+ expect(out.next?.kind).toBe('team');
173
+ });
174
+
175
+ it('transcribes a recording, offering the choices as vocabulary', async () => {
176
+ const transcribe = vi.fn(async () => 'engineering');
177
+ const { deps } = setup([held('bench', "Order dad's bench")], { transcribe });
178
+ await syncOpenQuestions(deps);
179
+ const out = await answerQuestionByVoice(deps, { clientActionId: 'press-audio-01', audio: { audio: new Uint8Array([1]), mimeType: 'audio/mp4' } });
180
+ expect(out.kind).toBe('answered');
181
+ expect(transcribe).toHaveBeenCalledWith(expect.objectContaining({ hints: ['Engineering', 'Operations'] }));
182
+ });
183
+
184
+ it('speaks the reply when speech is configured, and still answers in text when it fails', async () => {
185
+ const put = vi.fn(async () => 'ref-1');
186
+ const ok = setup([held('bench', "Order dad's bench")], {
187
+ synthesize: async () => ({ audio: new Uint8Array([1, 2]), mimeType: 'audio/mpeg', model: 'm', provider: 'p', usage: {} }),
188
+ audio: { put }, audioPath: (id) => `/corpus/questions/audio/${id}`,
189
+ });
190
+ await syncOpenQuestions(ok.deps);
191
+ const spoken = await say(ok.deps, 'engineering');
192
+ expect(spoken.audioUrl).toMatch(/\/corpus\/questions\/audio\/press-/);
193
+
194
+ const bad = setup([held('bench', "Order dad's bench")], {
195
+ synthesize: async () => { throw new Error('quota'); }, audio: { put }, audioPath: (id) => `/a/${id}`,
196
+ });
197
+ await syncOpenQuestions(bad.deps);
198
+ const text = await say(bad.deps, 'engineering');
199
+ expect(text.audioUrl).toBeNull();
200
+ expect(text.kind).toBe('answered');
201
+ });
202
+
203
+ it('rejects a bad press id and an empty request', async () => {
204
+ const { deps } = setup([]);
205
+ await expect(answerQuestionByVoice(deps, { clientActionId: 'x', utterance: 'hi' })).rejects.toBeInstanceOf(VoiceAnswerError);
206
+ await expect(answerQuestionByVoice(deps, { clientActionId: 'press-empty-1' })).rejects.toMatchObject({ status: 400 });
207
+ });
208
+ });
209
+
210
+ describe('what is read aloud', () => {
211
+ it('never says a numeric date: the next question is spoken with the day named', async () => {
212
+ const { deps } = setup([
213
+ held('bench', "Order dad's bench"),
214
+ item('t', { title: 'Buy a present', due_at: '2026-11-13' }),
215
+ note([{ section: 's', title: 'Buy a present', fields: fields({
216
+ due: guessOf('2026-11-13', 0.5, 'assumed', 'r', { question: 'Is "Buy a present" due 2026-11-13 too, or does it have no date?' }),
217
+ }) }]),
218
+ ]);
219
+ await syncOpenQuestions(deps);
220
+ const out = await say(deps, 'engineering');
221
+ expect(out.next?.kind).toBe('due_date');
222
+ expect(out.spoken).not.toMatch(/2026-11-13/);
223
+ expect(out.spoken).toMatch(/Friday the thirteenth/);
224
+ });
225
+ });
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Marking a to-do done stamps WHEN (`resolved_at`), so the Tracker timeline's
3
+ * "done per day" is a real date and not a guess. Only the transition to done
4
+ * stamps, and a value the caller supplied is never overwritten.
5
+ */
6
+ import { describe, expect, it, vi } from 'vitest';
7
+
8
+ import { createPlanningApi } from '../corpus/client';
9
+ import type { Commitment } from '../corpus/types';
10
+
11
+ const NOW = Date.parse('2026-11-07T15:00:00Z');
12
+ const scope = { orgId: 'o' } as never;
13
+
14
+ function api() {
15
+ const post = vi.fn().mockResolvedValue({ id: 'c1', external_id: 'item:c1', data: { title: 'x', status: 'done' } });
16
+ return { post, api: createPlanningApi({ http: { get: vi.fn(), post } as never, scope, now: () => NOW }) };
17
+ }
18
+ const sent = (post: ReturnType<typeof vi.fn>) => post.mock.calls[0][1].data as Record<string, unknown>;
19
+ const row = (status: Commitment['status']) => ({ id: 'c1', externalId: 'item:c1', status }) as Commitment;
20
+
21
+ describe('updateCommitment stamps resolved_at', () => {
22
+ it('when an open item becomes done', async () => {
23
+ const { post, api: a } = api();
24
+ await a.updateCommitment!(row('open'), { status: 'done' });
25
+ expect(sent(post).resolved_at).toBe('2026-11-07T15:00:00.000Z');
26
+ });
27
+ it('never overwrites a value the caller supplied', async () => {
28
+ const { post, api: a } = api();
29
+ await a.updateCommitment!(row('open'), { status: 'done', resolvedAt: '2026-11-01T00:00:00Z' });
30
+ expect(sent(post).resolved_at).toBe('2026-11-01T00:00:00Z');
31
+ });
32
+ it('does not re-stamp an item that was already done', async () => {
33
+ const { post, api: a } = api();
34
+ await a.updateCommitment!(row('done'), { status: 'done', title: 'renamed' });
35
+ expect(sent(post)).not.toHaveProperty('resolved_at');
36
+ });
37
+ it('does not stamp other status changes', async () => {
38
+ const { post, api: a } = api();
39
+ await a.updateCommitment!(row('open'), { status: 'blocked' });
40
+ expect(sent(post)).not.toHaveProperty('resolved_at');
41
+ });
42
+ });
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The strip on the Tracker: it reads once per real input, one range picker
3
+ * state drives chart and table, and an empty window says so.
4
+ */
5
+ import * as React from 'react';
6
+ import { act, render, screen, waitFor } from '@testing-library/react';
7
+ import userEvent from '@testing-library/user-event';
8
+ import { describe, expect, it, vi } from 'vitest';
9
+
10
+ import { TrackerTimeline } from '../components/pages/tracker/TrackerTimeline';
11
+ import type { TimelineRead } from '../corpus/tracker-timeline-client';
12
+
13
+ // Recharts measures a real layout box; jsdom has none.
14
+ vi.mock('recharts', async () => {
15
+ const actual = await vi.importActual<Record<string, unknown>>('recharts');
16
+ return { ...actual, ResponsiveContainer: ({ children }: { children: React.ReactNode }) => <div data-testid="chart">{children}</div> };
17
+ });
18
+
19
+ const NOW = Date.parse('2026-11-07T15:00:00Z');
20
+ const read = (over: Partial<TimelineRead> = {}): TimelineRead => ({
21
+ anchor: '2026-11-07', created: [], done: [], overdue: [], items: [], truncated: false, ...over,
22
+ });
23
+
24
+ describe('TrackerTimeline', () => {
25
+ it('reads once, not once per render', async () => {
26
+ const timeline = vi.fn().mockResolvedValue(read());
27
+ const { rerender } = render(<TrackerTimeline api={{ timeline }} orgId="o" now={NOW} filter={{}} />);
28
+ await screen.findByText('No to-dos in this window.');
29
+ for (let i = 0; i < 5; i += 1) rerender(<TrackerTimeline api={{ timeline }} orgId="o" now={NOW} filter={{}} />);
30
+ expect(timeline).toHaveBeenCalledTimes(1);
31
+ });
32
+
33
+ it('re-reads when a filter really changes, and debounces typing', async () => {
34
+ vi.useFakeTimers({ shouldAdvanceTime: true });
35
+ const timeline = vi.fn().mockResolvedValue(read());
36
+ const { rerender } = render(<TrackerTimeline api={{ timeline }} orgId="o" now={NOW} filter={{}} debounceMs={300} />);
37
+ await vi.waitFor(() => expect(timeline).toHaveBeenCalledTimes(1));
38
+ for (const s of ['i', 'in', 'inv']) rerender(<TrackerTimeline api={{ timeline }} orgId="o" now={NOW} filter={{ search: s }} debounceMs={300} />);
39
+ expect(timeline).toHaveBeenCalledTimes(1);
40
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
41
+ expect(timeline).toHaveBeenCalledTimes(2);
42
+ expect(timeline.mock.calls[1][0]).toMatchObject({ search: 'inv' });
43
+ vi.useRealTimers();
44
+ });
45
+
46
+ it('lists the to-dos behind the numbers and flags estimated completions', async () => {
47
+ const timeline = vi.fn().mockResolvedValue(read({
48
+ items: [
49
+ { id: 'a', title: 'Send the proposal', status: 'open', dueAt: '2026-11-04', firstSeenAt: '2026-11-01', resolvedAt: null, updatedAt: null },
50
+ { id: 'b', title: 'Book the venue', status: 'done', dueAt: null, firstSeenAt: null, resolvedAt: null, updatedAt: '2026-11-06T09:00:00Z' },
51
+ ],
52
+ }));
53
+ render(<TrackerTimeline api={{ timeline }} orgId="o" now={NOW} filter={{}} />);
54
+ // created on the 1st and overdue since the 4th: two rows for one to-do
55
+ expect(await screen.findAllByText('Send the proposal')).toHaveLength(2);
56
+ expect(screen.getAllByText('Overdue').length).toBeGreaterThan(0);
57
+ expect(screen.getByText('Book the venue')).toBeInTheDocument();
58
+ expect(screen.getByTestId('timeline-estimated')).toHaveTextContent('1 done to-do has no completion date');
59
+ });
60
+
61
+ it('one range choice drives the table too', async () => {
62
+ const timeline = vi.fn().mockResolvedValue(read({
63
+ items: [
64
+ { id: 'old', title: 'Old thing', status: 'open', dueAt: null, firstSeenAt: '2026-09-20', resolvedAt: null, updatedAt: null },
65
+ { id: 'new', title: 'New thing', status: 'open', dueAt: null, firstSeenAt: '2026-11-05', resolvedAt: null, updatedAt: null },
66
+ ],
67
+ }));
68
+ render(<TrackerTimeline api={{ timeline }} orgId="o" now={NOW} filter={{}} />);
69
+ expect(await screen.findByText('New thing')).toBeInTheDocument();
70
+ expect(screen.queryByText('Old thing')).not.toBeInTheDocument(); // default 30D
71
+ await userEvent.click(screen.getByRole('tab', { name: '90 days' }));
72
+ await waitFor(() => expect(screen.getByText('Old thing')).toBeInTheDocument());
73
+ expect(timeline).toHaveBeenCalledTimes(1); // the range is a view, not a read
74
+ });
75
+
76
+ it('says plainly when the read fails', async () => {
77
+ const timeline = vi.fn().mockRejectedValue(Object.assign(new Error('x'), { status: 403 }));
78
+ render(<TrackerTimeline api={{ timeline }} orgId="o" now={NOW} filter={{}} />);
79
+ expect(await screen.findByRole('alert')).toHaveTextContent('do not have access');
80
+ });
81
+ });
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The timeline's server reads. The point of every case: the browser asks the
3
+ * tenant for GROUPED COUNTS and one capped page of rows per series, and never
4
+ * walks the whole list.
5
+ */
6
+ import { describe, expect, it, vi } from 'vitest';
7
+
8
+ import { createTimelineReader } from '../corpus/tracker-timeline-client';
9
+
10
+ const NOW = Date.parse('2026-11-07T15:00:00Z');
11
+ const clock = { now: NOW, timeZone: 'UTC' };
12
+
13
+ type Call = { path: string; params: Record<string, unknown> };
14
+
15
+ function fakeHttp(counts: Record<string, Array<[string | null, number]>> = {}, rows: Array<Record<string, unknown>> = []) {
16
+ const calls: Call[] = [];
17
+ const get = vi.fn(async (path: string, opts?: { params?: Record<string, unknown> }) => {
18
+ const params = opts?.params ?? {};
19
+ calls.push({ path, params });
20
+ if (path.endsWith('/counts')) {
21
+ const all = counts[String(params.group_by)] ?? [];
22
+ const page = Number(params.page ?? 1);
23
+ const slice = all.slice((page - 1) * 2, page * 2);
24
+ return { results: slice.map(([v, c]) => ({ values: [v], count: c })), next: page * 2 < all.length ? 'more' : null, groupBy: [params.group_by] };
25
+ }
26
+ return { count: rows.length, results: rows, next: null };
27
+ });
28
+ return { http: { get } as never, calls };
29
+ }
30
+
31
+ const read = (http: never, filter = {}) =>
32
+ createTimelineReader({ http, type: 'commitment' })(filter, clock);
33
+
34
+ describe('createTimelineReader', () => {
35
+ it('asks for a grouped count per series on the counts endpoint', async () => {
36
+ const { http, calls } = fakeHttp({ 'attr.first_seen_at': [['2026-11-05T10:00:00Z', 3]] });
37
+ const out = await read(http);
38
+ const counted = calls.filter((c) => c.path === 'api/v1/entities/counts').map((c) => c.params.group_by).sort();
39
+ expect(counted).toEqual(['attr.due_at', 'attr.first_seen_at', 'attr.resolved_at']);
40
+ expect(calls.every((c) => c.params.type === 'commitment')).toBe(true);
41
+ expect(out.created).toEqual([{ value: '2026-11-05T10:00:00Z', count: 3 }]);
42
+ expect(out.anchor).toBe('2026-11-07');
43
+ });
44
+
45
+ it('follows the counts pages, not just the first', async () => {
46
+ const many: Array<[string, number]> = ['2026-11-01', '2026-11-02', '2026-11-03', '2026-11-04', '2026-11-05'].map((d) => [d, 1]);
47
+ const { http, calls } = fakeHttp({ 'attr.due_at': many });
48
+ const out = await read(http);
49
+ expect(out.overdue).toHaveLength(5);
50
+ expect(calls.filter((c) => c.params.group_by === 'attr.due_at')).toHaveLength(3);
51
+ });
52
+
53
+ it('reads at most one capped page of rows per series, never everything', async () => {
54
+ const { http, calls } = fakeHttp();
55
+ await read(http);
56
+ const lists = calls.filter((c) => c.path === 'api/v1/entities');
57
+ expect(lists.length).toBe(4); // created, done, estimated done, overdue
58
+ expect(lists.every((c) => Number(c.params.page_size) <= 200 && c.params.page === undefined)).toBe(true);
59
+ });
60
+
61
+ it('looks for already-done rows with no resolved_at, windowed by their last update', async () => {
62
+ const { http, calls } = fakeHttp();
63
+ await read(http);
64
+ const est = calls.find((c) => c.params['attr.resolved_at__isnull'] === 'true')!;
65
+ expect(est.params).toMatchObject({ 'attr.status': 'done' });
66
+ expect(est.params.updated_after).toBeDefined();
67
+ expect(est.params.group_by).toBeUndefined();
68
+ });
69
+
70
+ it('maps rows to timeline items, with updated_at for the estimate', async () => {
71
+ const { http } = fakeHttp({}, [
72
+ { id: 'c1', name: 'Send proposal', updated_at: '2026-11-06T09:00:00Z', data: { title: 'Send proposal', status: 'done', first_seen_at: '2026-11-01', due_at: null } },
73
+ ]);
74
+ const out = await read(http);
75
+ expect(out.items).toEqual([
76
+ { id: 'c1', title: 'Send proposal', status: 'done', dueAt: null, firstSeenAt: '2026-11-01', resolvedAt: null, updatedAt: '2026-11-06T09:00:00Z' },
77
+ ]);
78
+ });
79
+
80
+ it('makes no request for a series the filter empties, and carries the filter to the rest', async () => {
81
+ const { http, calls } = fakeHttp();
82
+ await read(http, { status: 'blocked', search: 'invoice' });
83
+ expect(calls.some((c) => c.params.group_by === 'attr.resolved_at')).toBe(false);
84
+ expect(calls.some((c) => c.params['attr.resolved_at__isnull'] === 'true')).toBe(false);
85
+ expect(calls.every((c) => c.params.search === 'invoice')).toBe(true);
86
+ });
87
+
88
+ it('says when a series had more rows than the page it read', async () => {
89
+ const http = { get: vi.fn(async (path: string) => (path.endsWith('/counts')
90
+ ? { results: [], next: null }
91
+ : { count: 450, results: [], next: 'x' })) } as never;
92
+ expect((await read(http)).truncated).toBe(true);
93
+ });
94
+ });
@@ -0,0 +1,209 @@
1
+ /**
2
+ * The Tracker timeline's arithmetic: which day a thing lands on, what counts as
3
+ * overdue, and what an empty window looks like. Pure, so every case here is a
4
+ * way the strip could draw a wrong number while the data underneath is fine.
5
+ */
6
+ import { describe, expect, it } from 'vitest';
7
+
8
+ import {
9
+ TIMELINE_DAYS,
10
+ bucketCounts,
11
+ buildTimeline,
12
+ completionOf,
13
+ dayOf,
14
+ timelineParams,
15
+ windowDayList,
16
+ type TimelineItem,
17
+ } from '../corpus/tracker-timeline';
18
+
19
+ const NOW = Date.parse('2026-11-07T15:00:00Z');
20
+
21
+ describe('dayOf', () => {
22
+ it('keeps a date-only value as it is', () => {
23
+ expect(dayOf('2026-11-03', 'America/Los_Angeles')).toBe('2026-11-03');
24
+ });
25
+ it('puts an instant on the reader’s local day, not UTC', () => {
26
+ // 02:00Z on the 4th is still the evening of the 3rd in Los Angeles.
27
+ expect(dayOf('2026-11-04T02:00:00Z', 'America/Los_Angeles')).toBe('2026-11-03');
28
+ expect(dayOf('2026-11-04T02:00:00Z', 'UTC')).toBe('2026-11-04');
29
+ });
30
+ it('is null for nothing or nonsense', () => {
31
+ expect(dayOf(null)).toBeNull();
32
+ expect(dayOf('not a date')).toBeNull();
33
+ });
34
+ });
35
+
36
+ describe('windowDayList', () => {
37
+ it('is the anchor day and the days before it, oldest first', () => {
38
+ expect(windowDayList('2026-11-07', 3)).toEqual(['2026-11-05', '2026-11-06', '2026-11-07']);
39
+ });
40
+ it('crosses a month boundary', () => {
41
+ expect(windowDayList('2026-03-01', 2)).toEqual(['2026-02-28', '2026-03-01']);
42
+ });
43
+ });
44
+
45
+ describe('bucketCounts', () => {
46
+ it('merges distinct timestamps that fall on one local day', () => {
47
+ const out = bucketCounts(
48
+ [
49
+ { value: '2026-11-04T02:00:00Z', count: 2 },
50
+ { value: '2026-11-03T20:00:00Z', count: 3 },
51
+ { value: '2026-11-04T09:00:00Z', count: 1 },
52
+ { value: null, count: 9 },
53
+ ],
54
+ 'America/Los_Angeles',
55
+ );
56
+ expect(out.get('2026-11-03')).toBe(5);
57
+ expect(out.get('2026-11-04')).toBe(1);
58
+ expect(out.size).toBe(2);
59
+ });
60
+ });
61
+
62
+ const item = (over: Partial<TimelineItem> & { id: string }): TimelineItem => ({
63
+ title: `Item ${over.id}`,
64
+ status: 'open',
65
+ dueAt: null,
66
+ firstSeenAt: null,
67
+ resolvedAt: null,
68
+ updatedAt: null,
69
+ ...over,
70
+ });
71
+
72
+ describe('completionOf', () => {
73
+ it('uses resolved_at when the item has one', () => {
74
+ expect(completionOf(item({ id: 'a', status: 'done', resolvedAt: '2026-11-05T10:00:00Z', updatedAt: '2026-11-06T10:00:00Z' }), 'UTC'))
75
+ .toEqual({ day: '2026-11-05', estimated: false });
76
+ });
77
+ it('falls back to updated_at and says it is an estimate', () => {
78
+ expect(completionOf(item({ id: 'a', status: 'done', updatedAt: '2026-11-06T10:00:00Z' }), 'UTC'))
79
+ .toEqual({ day: '2026-11-06', estimated: true });
80
+ });
81
+ it('is null for an item that is not done', () => {
82
+ expect(completionOf(item({ id: 'a', status: 'open', resolvedAt: '2026-11-05T10:00:00Z' }), 'UTC')).toBeNull();
83
+ });
84
+ });
85
+
86
+ describe('buildTimeline', () => {
87
+ const empty = { created: [], done: [], overdue: [], items: [] };
88
+
89
+ it('is a zero-filled series for every day of the window when nothing happened', () => {
90
+ const t = buildTimeline({ ...empty, anchor: '2026-11-07' }, NOW, 'UTC');
91
+ expect(t.series.map((s) => s.id)).toEqual(['created', 'done', 'overdue']);
92
+ for (const s of t.series) {
93
+ expect(s.points).toHaveLength(TIMELINE_DAYS);
94
+ expect(s.points.every((p) => p.value === 0)).toBe(true);
95
+ expect(s.points[TIMELINE_DAYS - 1].date).toBe('2026-11-07');
96
+ }
97
+ expect(t.points).toEqual([]);
98
+ expect(t.estimatedDone).toBe(0);
99
+ });
100
+
101
+ it('puts counts on their day', () => {
102
+ const t = buildTimeline(
103
+ {
104
+ ...empty, anchor: '2026-11-07',
105
+ created: [{ value: '2026-11-05T10:00:00Z', count: 4 }],
106
+ done: [{ value: '2026-11-06', count: 2 }],
107
+ overdue: [{ value: '2026-11-01', count: 1 }],
108
+ },
109
+ NOW, 'UTC',
110
+ );
111
+ const at = (id: string, d: string) => t.series.find((s) => s.id === id)!.points.find((p) => p.date === d)!.value;
112
+ expect(at('created', '2026-11-05')).toBe(4);
113
+ expect(at('done', '2026-11-06')).toBe(2);
114
+ expect(at('overdue', '2026-11-01')).toBe(1);
115
+ expect(at('overdue', '2026-11-05')).toBe(0);
116
+ });
117
+
118
+ it('ignores counts older than the longest window', () => {
119
+ const t = buildTimeline({ ...empty, anchor: '2026-11-07', created: [{ value: '2026-01-01', count: 7 }] }, NOW, 'UTC');
120
+ expect(t.series[0].points.reduce((s, p) => s + p.value, 0)).toBe(0);
121
+ });
122
+
123
+ it('adds estimated completions to the done series and reports how many', () => {
124
+ const t = buildTimeline(
125
+ {
126
+ ...empty, anchor: '2026-11-07',
127
+ done: [{ value: '2026-11-06', count: 1 }],
128
+ items: [item({ id: 'old', status: 'done', updatedAt: '2026-11-06T09:00:00Z' })],
129
+ },
130
+ NOW, 'UTC',
131
+ );
132
+ const done = t.series.find((s) => s.id === 'done')!;
133
+ expect(done.points.find((p) => p.date === '2026-11-06')!.value).toBe(2);
134
+ expect(t.estimatedDone).toBe(1);
135
+ });
136
+
137
+ describe('overdue rule', () => {
138
+ const events = (items: TimelineItem[]) =>
139
+ buildTimeline({ ...empty, anchor: '2026-11-07', items }, NOW, 'UTC').points.flatMap((p) => p.events ?? []);
140
+
141
+ it('lists an open item past its date as overdue on its due day', () => {
142
+ const ev = events([item({ id: 'a', dueAt: '2026-11-02' })]);
143
+ expect(ev).toHaveLength(1);
144
+ expect(ev[0]).toMatchObject({ id: 'overdue:a', category: 'overdue', status: 'Overdue', delta: 0, tone: 'down' });
145
+ });
146
+ it('never lists a done or dropped item as overdue', () => {
147
+ expect(events([item({ id: 'a', status: 'done', dueAt: '2026-11-02' })]).filter((e) => e.category === 'overdue')).toEqual([]);
148
+ expect(events([item({ id: 'b', status: 'dropped', dueAt: '2026-11-02' })]).filter((e) => e.category === 'overdue')).toEqual([]);
149
+ });
150
+ it('does not list an item due in the future', () => {
151
+ expect(events([item({ id: 'a', dueAt: '2026-11-20' })]).filter((e) => e.category === 'overdue')).toEqual([]);
152
+ });
153
+ });
154
+
155
+ it('lists the to-dos as events and groups them under their day', () => {
156
+ const t = buildTimeline(
157
+ {
158
+ ...empty, anchor: '2026-11-07',
159
+ items: [
160
+ item({ id: 'a', firstSeenAt: '2026-11-05T10:00:00Z' }),
161
+ item({ id: 'b', firstSeenAt: '2026-11-05T12:00:00Z', status: 'done', resolvedAt: '2026-11-06T08:00:00Z' }),
162
+ ],
163
+ },
164
+ NOW, 'UTC',
165
+ );
166
+ const day5 = t.points.find((p) => p.date === '2026-11-05')!;
167
+ expect(day5.events!.map((e) => e.id).sort()).toEqual(['created:a', 'created:b']);
168
+ expect(day5.value).toBe(2);
169
+ expect(t.points.find((p) => p.date === '2026-11-06')!.events![0]).toMatchObject({ id: 'done:b', status: 'Done', tone: 'up' });
170
+ });
171
+ });
172
+
173
+ describe('timelineParams', () => {
174
+ const base = { now: NOW, timeZone: 'UTC' };
175
+
176
+ it('asks the server for each series, windowed and grouped by the date attribute', () => {
177
+ const p = timelineParams('created', {}, base);
178
+ expect(p).toMatchObject({ group_by: 'attr.first_seen_at' });
179
+ expect(p['attr.first_seen_at__gte']).toBe('2026-08-09');
180
+ });
181
+
182
+ it('counts only done items for the done series', () => {
183
+ expect(timelineParams('done', {}, base)).toMatchObject({ group_by: 'attr.resolved_at', 'attr.status': 'done' });
184
+ });
185
+
186
+ it('counts only owed items past their date for the overdue series', () => {
187
+ const p = timelineParams('overdue', {}, base);
188
+ expect(p).toMatchObject({ group_by: 'attr.due_at', 'attr.status__in': 'open,in_progress,blocked' });
189
+ expect(p['attr.due_at__lt']).toBe('2026-11-07T15:00:00.000Z');
190
+ });
191
+
192
+ it('carries the page’s filters to every series', () => {
193
+ const p = timelineParams('created', { search: 'proposal', owner: 'Rae' }, base);
194
+ expect(p).toMatchObject({ search: 'proposal', 'attr.owner_name__icontains': 'Rae' });
195
+ });
196
+
197
+ it('narrows to the chosen status, and a done-only series has nothing under a blocked chip', () => {
198
+ expect(timelineParams('created', { status: 'blocked' }, base)).toMatchObject({ 'attr.status': 'blocked' });
199
+ expect(timelineParams('done', { status: 'blocked' }, base)).toBeNull();
200
+ expect(timelineParams('overdue', { status: 'blocked' }, base)).toMatchObject({ 'attr.status': 'blocked' });
201
+ });
202
+
203
+ it('the overdue chip narrows every series to owed items past their date', () => {
204
+ const c = timelineParams('created', { overdueOnly: true }, base);
205
+ expect(c).toMatchObject({ 'attr.status__in': 'open,in_progress,blocked' });
206
+ expect(c!['attr.due_at__lt']).toBe('2026-11-07T15:00:00.000Z');
207
+ expect(timelineParams('done', { overdueOnly: true }, base)).toBeNull();
208
+ });
209
+ });