@startsimpli/integrations 0.2.150 → 0.2.151

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.150",
3
+ "version": "0.2.151",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/ui": "^0.4.172",
53
+ "@startsimpli/auth": "^0.4.50",
54
54
  "@startsimpli/utils": "^0.4.18",
55
- "@startsimpli/auth": "^0.4.50"
55
+ "@startsimpli/ui": "^0.4.173"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -99,7 +99,7 @@
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
101
  "@startsimpli/llm": "0.4.31",
102
- "@startsimpli/ui": "0.4.172",
102
+ "@startsimpli/ui": "0.4.173",
103
103
  "@startsimpli/ui-native": "0.1.14",
104
104
  "@startsimpli/auth": "0.4.50",
105
105
  "@startsimpli/utils": "0.4.18"
@@ -0,0 +1,45 @@
1
+ import { expect } from 'vitest';
2
+ import type { CorpusHttp } from '../../corpus/client';
3
+
4
+ export interface Row { id: string; entity_type: string; external_id: string; name: string; data: Record<string, unknown>; version: number }
5
+
6
+ /** A tenant in memory: list/get, shallow-merging upsert, and the PATCH door. */
7
+ export function tenant(seed: Array<Omit<Row, 'version'>> = []) {
8
+ const rows = new Map<string, Row>(seed.map((r) => [r.id, { ...r, version: 1 }]));
9
+ let next = 1000;
10
+ const http: CorpusHttp & { post: NonNullable<CorpusHttp['post']>; patch: NonNullable<CorpusHttp['patch']> } = {
11
+ async get(path, options) {
12
+ const clean = path.replace(/\/+$/, '');
13
+ if (clean === 'api/v1/entities') {
14
+ const type = String(options?.params?.type ?? '');
15
+ const all = [...rows.values()].filter((r) => r.entity_type === type);
16
+ return { results: all, next: null } as never;
17
+ }
18
+ const row = rows.get(decodeURIComponent(clean.split('/').pop() as string));
19
+ if (!row) throw Object.assign(new Error('nf'), { status: 404 });
20
+ return structuredClone(row) as never;
21
+ },
22
+ async post(path, body) {
23
+ const b = body as { entity_type: string; external_id: string; name?: string; data: Record<string, unknown> };
24
+ expect(path).toContain('upsert');
25
+ const hit = [...rows.values()].find((r) => r.entity_type === b.entity_type && r.external_id === b.external_id);
26
+ if (hit) {
27
+ hit.data = { ...hit.data, ...b.data };
28
+ if (b.name) hit.name = b.name;
29
+ hit.version += 1;
30
+ return structuredClone(hit) as never;
31
+ }
32
+ const row: Row = { id: `e${next++}`, entity_type: b.entity_type, external_id: b.external_id, name: b.name ?? '', data: { ...b.data }, version: 1 };
33
+ rows.set(row.id, row);
34
+ return structuredClone(row) as never;
35
+ },
36
+ async patch(path, body) {
37
+ const row = rows.get(decodeURIComponent(path.replace(/\/+$/, '').split('/').pop() as string)) as Row;
38
+ row.data = (body as { data: Record<string, unknown> }).data;
39
+ row.version += 1;
40
+ return structuredClone(row) as never;
41
+ },
42
+ };
43
+ return { rows, http };
44
+ }
45
+
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The check-in: "there are N things I am unsure about" (bd startsim-tmrvi.4). Grouped, most important first,
3
+ * each with the guess Tandem is acting on, in words fit to be read aloud.
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ import { composeCheckIn } from '../corpus/questions/checkin';
8
+ import type { OpenQuestion } from '../corpus/questions';
9
+
10
+ const NOW = Date.parse('2026-11-04T15:00:00Z');
11
+ const TZ = 'America/New_York';
12
+ const q = (id: string, itemId: string, over: Partial<OpenQuestion>): OpenQuestion => ({
13
+ id, itemId, kind: 'due_date', question: 'When is this due?', status: 'open', candidates: [], score: 70, ownerSub: 'me', createdAt: '', updatedAt: '', ...over,
14
+ });
15
+ const titles = new Map([['a', 'Call the vet'], ['b', "Order dad's bench"], ['c', 'Pay LIN-123 invoice'], ['d', 'Plan offsite'], ['e', 'Email Sam'], ['f', 'Renew passport']]);
16
+ const make = (qs: OpenQuestion[], over = {}) => composeCheckIn(qs, { titles, now: NOW, timeZone: TZ, ...over });
17
+
18
+ describe('composeCheckIn', () => {
19
+ it('says nothing when nothing is open', () => {
20
+ const out = make([]);
21
+ expect(out.empty).toBe(true);
22
+ expect(out.text).toBe('');
23
+ });
24
+
25
+ it('counts the doubts and reads the best first, with its guess', () => {
26
+ const out = make([
27
+ q('1', 'b', { kind: 'team', question: 'Which team is this for?', score: 100 }),
28
+ q('2', 'a', { assumed: { value: '2026-11-06', confidence: 0.5, reason: 'said Friday on a Friday' }, score: 80 }),
29
+ ]);
30
+ expect(out.total).toBe(2);
31
+ expect(out.text).toMatch(/^I am not sure about two things\./);
32
+ expect(out.text.indexOf("Order dad's bench")).toBeLessThan(out.text.indexOf('Call the vet'));
33
+ expect(out.text).toMatch(/Friday the sixth/);
34
+ expect(out.entries[1].guess).toBe('Friday the sixth');
35
+ expect(out.entries[0].guess).toBeNull();
36
+ });
37
+
38
+ it('offers how to answer once, not per item', () => {
39
+ const out = make([q('1', 'a', {}), q('2', 'b', {})]);
40
+ expect(out.text.match(/say yes to keep/gi)?.length).toBe(1);
41
+ });
42
+
43
+ it('never reads ticket codes, markup or numeric dates aloud', () => {
44
+ const out = make([q('1', 'c', { assumed: { value: '2026-11-06', confidence: 0.5, reason: 'r' } })]);
45
+ expect(out.text).not.toMatch(/LIN-123|2026-11|\d{4}/);
46
+ });
47
+
48
+ it('speaks a project guess by its name', () => {
49
+ const out = make([q('1', 'a', { kind: 'project', question: 'Which project?', assumed: { value: 'f1', display: 'Marketing', confidence: 0.4, reason: 'r' } })]);
50
+ expect(out.text).toMatch(/Marketing/);
51
+ });
52
+
53
+ it('keeps it short: five items, then how many more', () => {
54
+ const many = ['a', 'b', 'c', 'd', 'e', 'f'].map((id, n) => q(String(n), id, { score: 70 - n }));
55
+ const out = make(many);
56
+ expect(out.entries).toHaveLength(5);
57
+ expect(out.remaining).toBe(1);
58
+ expect(out.text).toMatch(/one more/);
59
+ expect(out.text).toMatch(/six things/);
60
+ });
61
+
62
+ it('segments point at the question each stretch is about, so a reply can be resolved by position', () => {
63
+ const out = make([q('1', 'a', {}), q('2', 'b', {})]);
64
+ const ids = out.segments.filter((s) => s.id).map((s) => s.id);
65
+ expect(ids).toEqual(['1', '2']);
66
+ for (const s of out.segments) expect(out.text.slice(s.start, s.end).length).toBeGreaterThan(0);
67
+ });
68
+
69
+ it('says one thing in the singular', () => {
70
+ expect(make([q('1', 'a', {})]).text).toMatch(/^I am not sure about one thing\./);
71
+ });
72
+ });
73
+
74
+ import { vi } from 'vitest';
75
+ import { buildCheckIn } from '../corpus/questions/checkin-handle';
76
+ import { syncOpenQuestions } from '../corpus/questions';
77
+ import { createMemoryActionLog } from '../corpus/briefing/actions/log';
78
+ import { commitmentEditSeam } from '../corpus/briefing/actions/seam';
79
+ import { createPlanningApi } from '../corpus/client';
80
+ import { tenant } from './helpers/question-tenant';
81
+
82
+ describe('buildCheckIn', () => {
83
+ const SCOPE = { orgId: 'o' } as never;
84
+ const held = (id: string, title: string) => ({
85
+ id, entity_type: 'commitment', external_id: `commit:${id}`, name: title,
86
+ data: { title, status: 'open', open_question_kind: 'team', open_question: 'Which team is this for?', sync_state: 'needs_team' },
87
+ });
88
+ function setup(synth = true) {
89
+ const t = tenant([held('x', "Order dad's bench"), held('y', 'Call the vet')]);
90
+ const api = createPlanningApi({ http: t.http, scope: SCOPE, supportedFilters: [], resolveParticipants: false } as never);
91
+ const synthesize = vi.fn(async () => ({ audio: new Uint8Array([1]), mimeType: 'audio/mpeg', model: 'm', provider: 'p', usage: {} }));
92
+ const put = vi.fn(async () => 'ref-1');
93
+ const deps = {
94
+ http: t.http, scope: SCOPE, ownerSub: 'me', now: () => NOW, timeZone: TZ,
95
+ seam: commitmentEditSeam({ api, http: t.http, scope: SCOPE }),
96
+ patchItem: vi.fn(), options: async () => [], log: createMemoryActionLog(),
97
+ ...(synth ? { synthesize, audio: { put }, audioPath: (id: string) => `/a/${id}` } : {}),
98
+ };
99
+ return { deps, synthesize };
100
+ }
101
+
102
+ it('reads the queue with the item titles and offers the first question to answer', async () => {
103
+ const { deps } = setup(false);
104
+ const out = await buildCheckIn(deps);
105
+ expect(out.total).toBe(2);
106
+ expect(out.text).toMatch(/Order dad's bench|Call the vet/);
107
+ expect(out.firstQuestionId).toBe(out.entries[0].questionId);
108
+ expect(out.audioUrl).toBeNull();
109
+ });
110
+
111
+ it('speaks it once: asking again for the same words does not synthesize again', async () => {
112
+ const { deps, synthesize } = setup(true);
113
+ const a = await buildCheckIn(deps);
114
+ const b = await buildCheckIn(deps);
115
+ expect(a.audioUrl).toMatch(/^\/a\/checkin-/);
116
+ expect(b.audioUrl).toBe(a.audioUrl);
117
+ expect(synthesize).toHaveBeenCalledTimes(1);
118
+ });
119
+
120
+ it('is empty and silent when nothing is open', async () => {
121
+ const t = tenant([]);
122
+ const api = createPlanningApi({ http: t.http, scope: SCOPE, supportedFilters: [], resolveParticipants: false } as never);
123
+ const out = await buildCheckIn({
124
+ http: t.http, scope: SCOPE, ownerSub: 'me', now: () => NOW, seam: commitmentEditSeam({ api, http: t.http, scope: SCOPE }),
125
+ patchItem: vi.fn(), options: async () => [], log: createMemoryActionLog(),
126
+ } as never);
127
+ expect(out).toMatchObject({ empty: true, audioUrl: null, firstQuestionId: null });
128
+ void syncOpenQuestions;
129
+ });
130
+ });
131
+
132
+ describe('a guess stored as an id', () => {
133
+ it('is said by name when the name is known, and not at all when it is not', () => {
134
+ const unnamed = make([q('1', 'a', { kind: 'project', question: 'Which project?', assumed: { value: '854c5d84-d879', confidence: 0.4, reason: 'r' } })]);
135
+ expect(unnamed.text).not.toMatch(/854c/);
136
+ expect(unnamed.entries[0].guess).toBeNull();
137
+ expect(unnamed.text).toMatch(/which project/i);
138
+ });
139
+ });
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Answering a clarifying question by voice (bd startsim-tmrvi.5). The words people
3
+ * actually say to "When is this due?" / "Which project?" become one answer, or a
4
+ * short question back. Never a briefing action: "skip it" must not drop a to-do.
5
+ */
6
+ import { describe, expect, it } from 'vitest';
7
+
8
+ import { parseSpokenAnswer } from '../corpus/questions/voice-parse';
9
+ import type { OpenQuestion } from '../corpus/questions';
10
+
11
+ const NOW = Date.parse('2026-11-04T15:00:00Z'); // Wednesday 10:00 in New York
12
+ const TZ = 'America/New_York';
13
+
14
+ const q = (over: Partial<OpenQuestion>): OpenQuestion => ({
15
+ id: 'q1', itemId: 'i1', kind: 'due_date', question: 'When is this due?', status: 'open', candidates: [],
16
+ score: 70, ownerSub: 'me', createdAt: '', updatedAt: '', ...over,
17
+ });
18
+ const ctx = (options: Array<{ value: string; label: string }> = []) => ({ now: NOW, timeZone: TZ, options });
19
+
20
+ const PROJECTS = [
21
+ { value: 'f-mkt', label: 'Marketing' },
22
+ { value: 'f-web', label: 'Website redesign' },
23
+ { value: 'f-ops', label: 'Operations' },
24
+ ];
25
+
26
+ describe('parseSpokenAnswer: due date', () => {
27
+ const due = q({ assumed: { value: '2026-11-06', confidence: 0.5, reason: 'by Friday' } });
28
+
29
+ it.each([
30
+ ['today', '2026-11-04'],
31
+ ['tomorrow', '2026-11-05'],
32
+ ['next week', '2026-11-09'],
33
+ ['make it Friday please', '2026-11-06'],
34
+ ["let's say next Tuesday", '2026-11-10'],
35
+ ])('%s -> %s', (said, date) => {
36
+ const out = parseSpokenAnswer(due, said, ctx());
37
+ expect(out).toMatchObject({ kind: 'answer', value: date });
38
+ });
39
+
40
+ it('later clears the due date', () => {
41
+ expect(parseSpokenAnswer(due, 'someday', ctx())).toMatchObject({ kind: 'answer', value: '' });
42
+ });
43
+
44
+ it('keeps the guess on a yes', () => {
45
+ for (const said of ['yes', 'yeah that is right', 'keep it', 'sounds good', "that's fine"]) {
46
+ expect(parseSpokenAnswer(due, said, ctx())).toEqual({ kind: 'accept' });
47
+ }
48
+ });
49
+
50
+ it('skip is a skip, not a drop', () => {
51
+ for (const said of ['skip it', 'not now', 'ask me later', 'pass']) {
52
+ expect(parseSpokenAnswer(due, said, ctx())).toEqual({ kind: 'skip' });
53
+ }
54
+ });
55
+
56
+ it('asks again on something that is not a date', () => {
57
+ const out = parseSpokenAnswer(due, 'banana', ctx());
58
+ expect(out.kind).toBe('unclear');
59
+ });
60
+
61
+ it('undo is its own thing', () => {
62
+ expect(parseSpokenAnswer(due, 'undo that', ctx())).toEqual({ kind: 'undo' });
63
+ });
64
+
65
+ it('a yes with no guess to keep asks for the answer', () => {
66
+ const out = parseSpokenAnswer(q({}), 'yes', ctx());
67
+ expect(out.kind).toBe('unclear');
68
+ });
69
+ });
70
+
71
+ describe('parseSpokenAnswer: a choice (project, team, owner)', () => {
72
+ const project = q({ kind: 'project', question: 'Which project is this for?', candidates: [
73
+ { value: 'f-mkt', confidence: 0.5, reason: '' }, { value: 'f-web', confidence: 0.4, reason: '' },
74
+ ] });
75
+
76
+ it("that's the marketing project", () => {
77
+ expect(parseSpokenAnswer(project, "that's the marketing project", ctx(PROJECTS))).toMatchObject({ kind: 'answer', value: 'f-mkt', label: 'Marketing' });
78
+ });
79
+
80
+ it('picks by position among the options just offered', () => {
81
+ expect(parseSpokenAnswer(project, 'the second one', ctx(PROJECTS))).toMatchObject({ kind: 'answer', value: 'f-web' });
82
+ expect(parseSpokenAnswer(project, 'the first', ctx(PROJECTS))).toMatchObject({ kind: 'answer', value: 'f-mkt' });
83
+ });
84
+
85
+ it('names an option that was not among the candidates', () => {
86
+ expect(parseSpokenAnswer(project, 'operations', ctx(PROJECTS))).toMatchObject({ kind: 'answer', value: 'f-ops' });
87
+ });
88
+
89
+ it('asks which one when the words fit two', () => {
90
+ const two = [{ value: 'a', label: 'Marketing site' }, { value: 'b', label: 'Marketing email' }];
91
+ const out = parseSpokenAnswer(project, 'marketing', ctx(two));
92
+ expect(out).toMatchObject({ kind: 'unclear' });
93
+ expect((out as { question: string }).question).toMatch(/Marketing site/);
94
+ });
95
+
96
+ it('offers the candidates when nothing fits', () => {
97
+ const out = parseSpokenAnswer(project, 'the purple thing', ctx(PROJECTS));
98
+ expect(out.kind).toBe('unclear');
99
+ expect((out as { question: string }).question).toMatch(/Marketing/);
100
+ });
101
+
102
+ it('accepts the guess on a yes', () => {
103
+ const guessed = q({ kind: 'project', assumed: { value: 'f-mkt', display: 'Marketing', confidence: 0.6, reason: '' } });
104
+ expect(parseSpokenAnswer(guessed, 'yes', ctx(PROJECTS))).toEqual({ kind: 'accept' });
105
+ });
106
+
107
+ it('skip works here too', () => {
108
+ expect(parseSpokenAnswer(project, 'skip it', ctx(PROJECTS))).toEqual({ kind: 'skip' });
109
+ });
110
+ });
@@ -0,0 +1,208 @@
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
+ });
@@ -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
+ });