@startsimpli/integrations 0.2.216 → 0.2.217

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.216",
3
+ "version": "0.2.217",
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,7 +50,7 @@
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.207",
53
+ "@startsimpli/ui": "^0.4.208",
54
54
  "@startsimpli/auth": "^0.4.62",
55
55
  "@startsimpli/utils": "^0.4.21"
56
56
  },
@@ -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.207",
102
+ "@startsimpli/ui": "0.4.208",
103
103
  "@startsimpli/ui-native": "0.1.15",
104
104
  "@startsimpli/auth": "0.4.62",
105
105
  "@startsimpli/utils": "0.4.21"
@@ -0,0 +1,56 @@
1
+ /**
2
+ * A caller that sends no timeZone must not move the user's briefing to the UTC day.
3
+ * The zone the owner's last briefing was made in is remembered and reused.
4
+ */
5
+ import { describe, expect, it, vi } from 'vitest';
6
+ import { generateBriefing, type BriefingDeps } from '../corpus/briefing';
7
+
8
+ function tenant(shared = new Map<string, any>()) {
9
+ let seq = 0;
10
+ return {
11
+ rows: shared,
12
+ http: {
13
+ get: vi.fn(async (_p: string, o?: { params?: Record<string, unknown> }) => {
14
+ const ext = String(o?.params?.external_id__in ?? '');
15
+ return { results: [...shared.values()].filter((r) => r.external_id === ext) };
16
+ }),
17
+ post: vi.fn(async (_p: string, b: any) => {
18
+ const row = { id: ++seq, owner_sub: 'me', external_id: b.external_id, name: b.name, data: { ...(shared.get(b.external_id)?.data ?? {}), ...b.data } };
19
+ shared.set(b.external_id, row);
20
+ return row;
21
+ }),
22
+ },
23
+ };
24
+ }
25
+
26
+ const depsFor = (t: ReturnType<typeof tenant>, now: string, timeZone?: string): BriefingDeps => ({
27
+ http: t.http as never, orgId: 'org', ownerSub: 'me',
28
+ loadItems: async () => [{ id: 'a', title: 'Do a', status: 'open', ownerSub: 'me', dueAt: '2026-11-05', priority: 2 }],
29
+ synthesize: async () => ({ audio: new Uint8Array([1]), mimeType: 'audio/mpeg', model: 'm', provider: 'p', usage: {} }),
30
+ scriptLlm: null,
31
+ audio: { put: async () => 's3://b/k.mp3', url: async () => '/a' },
32
+ now: () => Date.parse(now),
33
+ ...(timeZone ? { timeZone } : {}),
34
+ });
35
+
36
+ describe('a briefing request with no timeZone', () => {
37
+ it('test_reuses_the_zone_of_the_owners_last_briefing_so_the_day_does_not_flip_to_UTC', async () => {
38
+ const t = tenant();
39
+ // Yesterday, the web sent its zone: Nov 4 in New York.
40
+ await generateBriefing(depsFor(t, '2026-11-04T15:00:00Z', 'America/New_York'), {});
41
+ // 22:00 New York on Nov 5 is already Nov 6 in UTC; this caller sends no zone.
42
+ const out = await generateBriefing(depsFor(t, '2026-11-06T03:00:00Z'), {});
43
+ expect(out.context.localDate).toBe('2026-11-05');
44
+ expect(out.context.timeZone).toBe('America/New_York');
45
+ });
46
+ it('test_falls_back_to_UTC_only_when_the_owner_has_no_history', async () => {
47
+ const out = await generateBriefing(depsFor(tenant(), '2026-11-06T03:00:00Z'), {});
48
+ expect(out.context.timeZone).toBe('UTC');
49
+ });
50
+ it('test_an_explicit_zone_always_wins', async () => {
51
+ const t = tenant();
52
+ await generateBriefing(depsFor(t, '2026-11-04T15:00:00Z', 'America/New_York'), {});
53
+ const out = await generateBriefing(depsFor(t, '2026-11-06T03:00:00Z', 'Asia/Tokyo'), {});
54
+ expect(out.context.timeZone).toBe('Asia/Tokyo');
55
+ });
56
+ });
@@ -354,6 +354,12 @@ describe('listCommitments speaks the tenant data API’s own filter language', (
354
354
  });
355
355
  });
356
356
 
357
+ it('filters by owner member as a server parameter on the declared attr.owner_sub', async () => {
358
+ const { api, seen } = client([]);
359
+ await api.listCommitments({ ownerSub: 'u-jade' });
360
+ expect(seen[0].params['attr.owner_sub']).toBe('u-jade');
361
+ });
362
+
357
363
  it('caps a text filter at the length the server documents', async () => {
358
364
  const { api, seen } = client([]);
359
365
  await api.listCommitments({ owner: 'x'.repeat(900), search: 'y'.repeat(900) });
@@ -609,6 +609,18 @@ describe('TrackerPage — adding a to-do', () => {
609
609
  await vi.waitFor(() => expect(calls).toBeGreaterThan(1));
610
610
  });
611
611
 
612
+ it('opens the new to-do straight away when the host can open items', async () => {
613
+ const created = commitment({ externalId: 'commit:new1', title: 'Call the notary' });
614
+ const createCommitment = vi.fn(async () => created);
615
+ const onOpenItem = vi.fn();
616
+ const api = { ...makeApi(), createCommitment } as CommitmentTrackerApi;
617
+ render(<TrackerPage api={api} scope={SCOPE} onOpenItem={onOpenItem} />);
618
+ await screen.findByText('Chase the inventor for comments on 2148');
619
+ await userEvent.click(screen.getByRole('button', { name: /Add to-do/ }));
620
+ await userEvent.type(screen.getByRole('textbox', { name: 'New to-do title' }), 'Call the notary{Enter}');
621
+ await vi.waitFor(() => expect(onOpenItem).toHaveBeenCalledWith(expect.objectContaining({ externalId: 'commit:new1' })));
622
+ });
623
+
612
624
  it('offers no quick-add when the api cannot create', async () => {
613
625
  render(<TrackerPage api={makeApi()} scope={SCOPE} />);
614
626
  await screen.findByText('Chase the inventor for comments on 2148');
@@ -687,3 +699,28 @@ describe('TrackerPage with the scheduled pass (bd startsim-vrmx5)', () => {
687
699
  expect(screen.queryByRole('button', { name: /Pull from meetings/i })).not.toBeInTheDocument();
688
700
  });
689
701
  });
702
+
703
+ describe('TrackerPage — Owner filter', () => {
704
+ const MEMBERS = [
705
+ { sub: 'u-jade', email: 'jade@x.test', name: 'Jade' },
706
+ { sub: 'u-john', email: 'john@x.test', name: 'John' },
707
+ ];
708
+ const withMembers = (queries: CommitmentQuery[]) =>
709
+ ({ ...makeApi({ onQuery: (q) => queries.push(q) }), listMembers: async () => MEMBERS }) as CommitmentTrackerApi;
710
+
711
+ it('is a third dropdown, listing only the roster the server returns, and sends a server filter', async () => {
712
+ const queries: CommitmentQuery[] = [];
713
+ render(<TrackerPage api={withMembers(queries)} scope={SCOPE} now={NOW} />);
714
+ const owner = await screen.findByRole('combobox', { name: 'Owner' });
715
+ expect(within(owner).getAllByRole('option').map((o) => o.textContent)).toEqual(['All owners', 'Jade', 'John']);
716
+ await userEvent.selectOptions(owner, 'u-jade');
717
+ await vi.waitFor(() => expect(queries.at(-1)?.ownerSub).toBe('u-jade'));
718
+ expect(queries.at(-1)?.page).toBe(1);
719
+ });
720
+
721
+ it('is absent when the api has no roster', async () => {
722
+ render(<TrackerPage api={makeApi()} scope={SCOPE} now={NOW} />);
723
+ await screen.findByText('Chase the inventor for comments on 2148');
724
+ expect(screen.queryByRole('combobox', { name: 'Owner' })).toBeNull();
725
+ });
726
+ });
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Near matches and stated dates go through the decision policy (bd startsim-81mzy, Todo: ENG-151).
3
+ */
4
+ import { describe, expect, it } from 'vitest';
5
+
6
+ import { commitmentIdentity, mergeDrafts, reconcile } from '../corpus/commitments';
7
+ import { applyPolicy } from '../corpus/engine/apply';
8
+ import { acceptPatch, rejectPatch } from '../components/pages/tracker/Suggestion';
9
+ import { FIXTURE_ORG, FIXTURE_TRACKED_DOCUMENTS } from '../corpus/fixtures';
10
+ import type { Commitment, CommitmentDraft, SourceDocument } from '../corpus/types';
11
+
12
+ const OWNER = 'usr_dana';
13
+ const SCOPE = { orgId: FIXTURE_ORG, ownerSub: OWNER };
14
+ const doc = (id: string): SourceDocument => ({ ...FIXTURE_TRACKED_DOCUMENTS[0], id, scope: SCOPE, source: 'granola' } as SourceDocument);
15
+ const DOCS = [doc('d1'), doc('d2'), doc('d3')];
16
+ const ENGINE = { ownerSub: OWNER };
17
+
18
+ const draft = (documentId: string, title: string, extra: Partial<CommitmentDraft> = {}): CommitmentDraft => ({
19
+ documentId, originKey: `${documentId}:${title}`, subtype: 'action', title, detail: '', status: 'open',
20
+ subject: 'matter 2040-01', quote: title, extractor: 'model', ...extra,
21
+ });
22
+
23
+ const run = (existing: Commitment[], drafts: CommitmentDraft[], engine: typeof ENGINE | null = ENGINE) =>
24
+ reconcile(existing, mergeDrafts(drafts), { scope: SCOPE, documents: DOCS, ...(engine ? { engine } : {}) });
25
+
26
+ const first = () => run([], [draft('d1', 'Set a drafting deadline for matter 2040-01')]).commitments.map((c) => ({ ...c, scope: SCOPE }));
27
+
28
+ describe('a near match is proposed, never merged silently', () => {
29
+ const NEAR = 'Deadline needs to be set on 2040-01';
30
+
31
+ it('an identical statement still merges by itself', () => {
32
+ const existing = first();
33
+ const again = run(existing, [draft('d2', 'Set a drafting deadline for matter 2040-01')]);
34
+ expect(again.created).toBe(0);
35
+ expect(again.merged).toBe(1);
36
+ });
37
+
38
+ it('wording that is only near becomes its own row, with the match reported', () => {
39
+ const existing = first();
40
+ expect(commitmentIdentity({ title: NEAR, subject: 'matter 2040-01' }).dedupeKey).not.toBe(existing[0].dedupeKey);
41
+ const result = run(existing, [draft('d2', NEAR)]);
42
+ expect(result.created).toBe(1);
43
+ expect(result.merged).toBe(0);
44
+ const row = result.commitments.find((c) => c.externalId !== existing[0].externalId)!;
45
+ expect(result.matches[row.externalId]).toMatchObject({ itemId: existing[0].externalId, strength: 'anchored', title: existing[0].title });
46
+ expect(result.commitments.find((c) => c.externalId === existing[0].externalId)!.mentions).toHaveLength(1);
47
+ });
48
+
49
+ it('without the engine the old merge is untouched', () => {
50
+ const result = run(first(), [draft('d2', NEAR)], null);
51
+ expect(result.created).toBe(0);
52
+ expect(result.merged).toBe(1);
53
+ });
54
+
55
+ it('the policy turns it into a suggestion that names the item and carries its id', () => {
56
+ const existing = first();
57
+ const result = run(existing, [draft('d2', NEAR)]);
58
+ const fresh = result.commitments.filter((c) => c.externalId !== existing[0].externalId);
59
+ const out = applyPolicy(fresh, { scope: { ownerSub: OWNER, ownerNames: [] }, documents: DOCS, matches: result.matches });
60
+ expect(out.kept[0].status).toBe('suggested');
61
+ expect(out.kept[0].suggestion).toMatchObject({ rule: 'L-NEAR', mode: 'propose', targetId: existing[0].externalId });
62
+ expect(out.kept[0].suggestion!.reason).toContain(existing[0].title);
63
+ });
64
+
65
+ it('never proposes a merge onto another person’s item', () => {
66
+ const theirs = first().map((c) => ({ ...c, scope: { ...SCOPE, ownerSub: 'usr_other' } }));
67
+ const result = run(theirs, [draft('d2', NEAR)]);
68
+ expect(result.matches).toEqual({});
69
+ });
70
+
71
+ it('a second run after the suggestion exists is a no-op, and so is one after "keep separate"', () => {
72
+ const existing = first();
73
+ const one = run(existing, [draft('d2', NEAR)]);
74
+ const suggested = applyPolicy(one.commitments.filter((c) => c.externalId !== existing[0].externalId),
75
+ { scope: { ownerSub: OWNER, ownerNames: [] }, documents: DOCS, matches: one.matches }).kept;
76
+ const stored = [...existing, ...suggested.map((c) => ({ ...c, scope: SCOPE }))];
77
+ const two = run(stored, [draft('d2', NEAR)]);
78
+ expect(two.created).toBe(0);
79
+ expect(two.touched).toEqual([]);
80
+ const separate = stored.map((c) => (c.suggestion ? { ...c, ...rejectPatch(c) } as Commitment : c));
81
+ expect(separate.find((c) => c.suggestion)!.status).toBe('open');
82
+ const three = run(separate, [draft('d2', NEAR)]);
83
+ expect(three.created).toBe(0);
84
+ expect(three.touched).toEqual([]);
85
+ });
86
+
87
+ it('"same item" drops the duplicate and the next pass moves its quotes onto the original', () => {
88
+ const existing = first();
89
+ const one = run(existing, [draft('d2', NEAR)]);
90
+ const suggested = applyPolicy(one.commitments.filter((c) => c.externalId !== existing[0].externalId),
91
+ { scope: { ownerSub: OWNER, ownerNames: [] }, documents: DOCS, matches: one.matches }).kept;
92
+ const accepted = suggested.map((c) => ({ ...c, scope: SCOPE, ...acceptPatch(c) } as Commitment));
93
+ expect(accepted[0].status).toBe('dropped');
94
+ const next = run([...existing, ...accepted], []);
95
+ const target = next.commitments.find((c) => c.externalId === existing[0].externalId)!;
96
+ expect(target.mentions.map((m) => m.documentId).sort()).toEqual(['d1', 'd2']);
97
+ expect(next.touched).toEqual([existing[0].externalId]);
98
+ expect(run(next.commitments, []).touched).toEqual([]);
99
+ });
100
+ });
101
+
102
+ describe('a stated date is proposed, never silently set or dropped', () => {
103
+ const TITLE = 'Set a drafting deadline for matter 2040-01';
104
+ const withDue = (dueAt: string) => ({ dueAt, quote: 'due on the 12th' } as Partial<CommitmentDraft>);
105
+
106
+ it('a different date is kept on the item as a proposal; dueAt stays', () => {
107
+ const existing = first().map((c) => ({ ...c, dueAt: '2026-12-01T00:00:00.000Z' }));
108
+ const result = run(existing, [draft('d2', TITLE, withDue('2026-12-12T00:00:00.000Z'))]);
109
+ const item = result.commitments[0];
110
+ expect(item.dueAt).toBe('2026-12-01T00:00:00.000Z');
111
+ expect(item.proposedDue).toEqual([{ dueAt: '2026-12-12T00:00:00.000Z', documentId: 'd2', quote: 'due on the 12th', state: 'pending' }]);
112
+ expect(result.touched).toContain(item.externalId);
113
+ });
114
+
115
+ it('a date for an undated item is proposed too, not backfilled', () => {
116
+ const result = run(first(), [draft('d2', TITLE, withDue('2026-12-12T00:00:00.000Z'))]);
117
+ expect(result.commitments[0].dueAt).toBeFalsy();
118
+ expect(result.commitments[0].proposedDue).toHaveLength(1);
119
+ });
120
+
121
+ it('the same date, a date a person set, and a repeat of the same document are all left alone', () => {
122
+ const base = first().map((c) => ({ ...c, dueAt: '2026-12-01T00:00:00.000Z' }));
123
+ expect(run(base, [draft('d2', TITLE, withDue('2026-12-01T09:00:00.000Z'))]).commitments[0].proposedDue).toBeUndefined();
124
+ const byPerson = base.map((c) => ({ ...c, dueSetByPerson: true }));
125
+ expect(run(byPerson, [draft('d2', TITLE, withDue('2026-12-12T00:00:00.000Z'))]).commitments[0].proposedDue).toBeUndefined();
126
+ const once = run(base, [draft('d2', TITLE, withDue('2026-12-12T00:00:00.000Z'))]);
127
+ expect(run(once.commitments, [draft('d2', TITLE, withDue('2026-12-12T00:00:00.000Z'))]).touched).toEqual([]);
128
+ const declined = once.commitments.map((c) => ({ ...c, proposedDue: c.proposedDue!.map((p) => ({ ...p, state: 'dismissed' as const })) }));
129
+ expect(run(declined, [draft('d2', TITLE, withDue('2026-12-12T00:00:00.000Z'))]).touched).toEqual([]);
130
+ });
131
+
132
+ it('without the engine a stated date still backfills an undated item', () => {
133
+ const result = run(first(), [draft('d2', TITLE, withDue('2026-12-12T00:00:00.000Z'))], null);
134
+ expect(result.commitments[0].dueAt).toBe('2026-12-12T00:00:00.000Z');
135
+ });
136
+ });
@@ -0,0 +1,74 @@
1
+ /** "Same item?" and "New date" in the existing notes, no new panel (bd startsim-81mzy). */
2
+ import * as React from 'react';
3
+ import { render, screen, waitFor, within } from '@testing-library/react';
4
+ import userEvent from '@testing-library/user-event';
5
+ import { describe, expect, it, vi } from 'vitest';
6
+
7
+ import { TrackerPage } from '../components/pages/TrackerPage';
8
+ import type { Commitment, CommitmentTrackerApi } from '../corpus/types';
9
+
10
+ const NOW = Date.parse('2026-11-24T12:00:00Z');
11
+ const SCOPE = { orgId: 'tandem' };
12
+ const item = (externalId: string, title: string, extra: Partial<Commitment> = {}): Commitment => ({
13
+ id: externalId, externalId, dedupeKey: externalId, subtype: 'action', title, detail: '', status: 'open',
14
+ subjectKey: '', actionKey: '', mentions: [], firstSeenAt: '2026-11-20T00:00:00Z', lastSeenAt: '2026-11-20T00:00:00Z',
15
+ extractorVersion: 'x', source: 'granola', sourceLabel: 'Granola', scope: SCOPE, ...extra,
16
+ });
17
+ function api(rows: Commitment[]) {
18
+ const updateCommitment = vi.fn(async (it: Commitment, patch: object) => {
19
+ const i = rows.findIndex((r) => r.externalId === it.externalId);
20
+ rows[i] = { ...rows[i], ...patch } as Commitment;
21
+ return rows[i];
22
+ });
23
+ return {
24
+ updateCommitment,
25
+ api: { listCommitments: vi.fn(async () => ({ count: rows.length, next: null, previous: null, results: [...rows], appliedFilters: [] })), updateCommitment } as unknown as CommitmentTrackerApi,
26
+ };
27
+ }
28
+
29
+ describe('near-match suggestion', () => {
30
+ const near = item('commit:n', 'Deadline needs to be set', {
31
+ status: 'suggested',
32
+ suggestion: { rule: 'L-NEAR', mode: 'propose', confidence: 0.8, reason: 'Looks like “Set a drafting deadline”: same subject, nearly the same wording.', documentId: 'm2', quote: 'deadline', targetId: 'commit:o' },
33
+ });
34
+
35
+ it('"Same item" drops the duplicate as accepted', async () => {
36
+ const { api: a, updateCommitment } = api([near, item('commit:o', 'Set a drafting deadline')]);
37
+ render(<TrackerPage api={a} scope={SCOPE} now={NOW} />);
38
+ const note = await screen.findByTestId('suggestion');
39
+ expect(note).toHaveTextContent(/Looks like “Set a drafting deadline”/);
40
+ await userEvent.click(within(note).getByRole('button', { name: 'Same item' }));
41
+ await waitFor(() => expect(updateCommitment).toHaveBeenCalledWith(expect.objectContaining({ externalId: 'commit:n' }),
42
+ expect.objectContaining({ status: 'dropped', suggestion: expect.objectContaining({ outcome: 'accepted', targetId: 'commit:o' }) })));
43
+ });
44
+
45
+ it('"Keep separate" opens it as its own item and records the rejection', async () => {
46
+ const { api: a, updateCommitment } = api([near, item('commit:o', 'Set a drafting deadline')]);
47
+ render(<TrackerPage api={a} scope={SCOPE} now={NOW} />);
48
+ await userEvent.click(within(await screen.findByTestId('suggestion')).getByRole('button', { name: 'Keep separate' }));
49
+ await waitFor(() => expect(updateCommitment).toHaveBeenCalledWith(expect.objectContaining({ externalId: 'commit:n' }),
50
+ expect.objectContaining({ status: 'open', suggestion: expect.objectContaining({ outcome: 'rejected' }) })));
51
+ });
52
+ });
53
+
54
+ describe('proposed date', () => {
55
+ const dated = () => item('commit:d', 'Send the deck', { dueAt: '2026-12-01T00:00:00Z', proposedDue: [{ dueAt: '2026-12-12T00:00:00Z', documentId: 'm3', quote: 'by the 12th', state: 'pending' }] });
56
+
57
+ it('Use it sets the date and settles the proposal', async () => {
58
+ const { api: a, updateCommitment } = api([dated()]);
59
+ render(<TrackerPage api={a} scope={SCOPE} now={NOW} />);
60
+ const note = await screen.findByTestId('proposed-due');
61
+ expect(note).toHaveTextContent(/New date: a later note says .*“by the 12th”/);
62
+ await userEvent.click(within(note).getByRole('button', { name: 'Use it' }));
63
+ await waitFor(() => expect(updateCommitment).toHaveBeenCalledWith(expect.anything(),
64
+ expect.objectContaining({ dueAt: '2026-12-12T00:00:00Z', proposedDue: [expect.objectContaining({ state: 'dismissed' })] })));
65
+ await waitFor(() => expect(screen.queryByTestId('proposed-due')).toBeNull());
66
+ });
67
+
68
+ it('Keep mine leaves the date and remembers the answer', async () => {
69
+ const { api: a, updateCommitment } = api([dated()]);
70
+ render(<TrackerPage api={a} scope={SCOPE} now={NOW} />);
71
+ await userEvent.click(within(await screen.findByTestId('proposed-due')).getByRole('button', { name: 'Keep mine' }));
72
+ await waitFor(() => expect(updateCommitment).toHaveBeenCalledWith(expect.anything(), { proposedDue: [expect.objectContaining({ state: 'dismissed' })] }));
73
+ });
74
+ });
@@ -0,0 +1,78 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import * as React from 'react';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ import { SharedWith } from '../components/SharedWith';
7
+ import { addRecordShare, listRecordShares, listShareChoices } from '../corpus/sharing';
8
+
9
+ afterEach(cleanup);
10
+ const cn = { badge: 'b', input: 'i', muted: 'm', error: 'e' };
11
+ const choices = async () => ({
12
+ org: { id: 'acme', label: 'Everyone in my organisation' },
13
+ people: [{ id: 'u1', label: 'Ada' }, { id: 'u2', label: 'Ben' }],
14
+ teams: [{ id: 'editorial', label: 'Editorial' }],
15
+ });
16
+
17
+ describe('SharedWith', () => {
18
+ it('says "Only you" for a private record and offers org, team and people', async () => {
19
+ const api = {
20
+ listRecordShares: vi.fn(async () => ({ shares: [], canShare: true })),
21
+ listShareChoices: choices,
22
+ addRecordShare: vi.fn(async () => undefined),
23
+ removeRecordShare: vi.fn(async () => undefined),
24
+ };
25
+ render(<SharedWith api={api} documentId="d" classNames={cn} />);
26
+ expect(await screen.findByText('Only you')).toBeTruthy();
27
+ await waitFor(() => expect(screen.getByText('Editorial (team)')).toBeTruthy());
28
+ expect(screen.getByText('Everyone in my organisation')).toBeTruthy();
29
+ fireEvent.change(screen.getByLabelText('Share with'), { target: { value: 'group:editorial' } });
30
+ await waitFor(() => expect(api.addRecordShare).toHaveBeenCalledWith('d', { kind: 'group', subjectId: 'editorial', level: 'viewer' }));
31
+ });
32
+
33
+ it('shows the line without the menu when the caller may not share', async () => {
34
+ const api = {
35
+ listRecordShares: vi.fn(async () => ({
36
+ shares: [{ id: 'g1', kind: 'org' as const, subjectId: 'acme', level: 'viewer' as const }], canShare: false,
37
+ })),
38
+ listShareChoices: choices,
39
+ addRecordShare: vi.fn(), removeRecordShare: vi.fn(),
40
+ };
41
+ render(<SharedWith api={api} documentId="d" classNames={cn} />);
42
+ expect(await screen.findByText(/Everyone in my organisation/)).toBeTruthy();
43
+ expect(screen.queryByLabelText('Share with')).toBeNull();
44
+ });
45
+
46
+ it('renders nothing when the client cannot read shares', () => {
47
+ const { container } = render(<SharedWith api={{}} documentId="d" classNames={cn} />);
48
+ expect(container.textContent).toBe('');
49
+ });
50
+ });
51
+
52
+ describe('sharing client', () => {
53
+ it('reads shares and ignores a public link', async () => {
54
+ const http = { get: vi.fn(async () => ({
55
+ may_share: true,
56
+ results: [
57
+ { id: '1', subject_type: 'user', subject_id: 'u1', level: 'editor' },
58
+ { id: '2', subject_type: 'public', subject_id: '', level: 'viewer' },
59
+ ] })) };
60
+ const r = await listRecordShares(http as never, 'd');
61
+ expect(r.canShare).toBe(true);
62
+ expect(r.shares).toEqual([{ id: '1', kind: 'user', subjectId: 'u1', level: 'editor' }]);
63
+ });
64
+
65
+ it('writes a grant naming the record, the kind and the level', async () => {
66
+ const post = vi.fn(async () => ({}));
67
+ await addRecordShare({ get: vi.fn(), post } as never, 'd', { kind: 'org', subjectId: 'acme' });
68
+ expect(post).toHaveBeenCalledWith('/api/v1/grants/', { entity: 'd', subject_type: 'org', subject_id: 'acme', level: 'viewer' });
69
+ });
70
+
71
+ it('survives a failing picker list', async () => {
72
+ const http = { get: vi.fn(async (p: string) => { if (p.includes('teams')) throw new Error('x'); return p.includes('whoami') ? { org_id: 'acme' } : { results: [{ sub: 'u1', label: 'Ada' }] }; }) };
73
+ const c = await listShareChoices(http as never);
74
+ expect(c.org?.id).toBe('acme');
75
+ expect(c.people).toEqual([{ id: 'u1', label: 'Ada' }]);
76
+ expect(c.teams).toEqual([]);
77
+ });
78
+ });
@@ -40,7 +40,7 @@ describe('TaskDetailPage', () => {
40
40
  const onBack = vi.fn();
41
41
  render(<TaskDetailPage api={apiWith([make('a')])} scope={scope} itemId="commit:zzz" onBack={onBack} />);
42
42
  expect(await screen.findByText(/couldn.t find that to-do/i)).toBeInTheDocument();
43
- fireEvent.click(screen.getByRole('button', { name: /back to tracker/i }));
43
+ fireEvent.click(screen.getByRole('button', { name: /back to to-dos/i }));
44
44
  expect(onBack).toHaveBeenCalled();
45
45
  });
46
46
 
@@ -7,6 +7,7 @@ import * as React from 'react';
7
7
 
8
8
  import { Markdown } from './Markdown';
9
9
  import { FiledUnder } from './FiledUnder';
10
+ import { SharedWith } from './SharedWith';
10
11
  import { formatDate, fullTextOf, summaryOf, todosInPlanText, withoutNextSteps } from './documentText';
11
12
  import type { CorpusApi, CorpusScope, SourceDocument } from '../corpus/types';
12
13
 
@@ -66,6 +67,8 @@ export function DocumentDetail({
66
67
 
67
68
  <FiledUnder api={api} documentId={document.id} classNames={cn} />
68
69
 
70
+ <SharedWith api={api} documentId={document.id} classNames={cn} />
71
+
69
72
  {document.participants.length ? (
70
73
  <div className="mt-3">
71
74
  <p className="text-sm font-medium text-gray-900">Parties</p>
@@ -0,0 +1,140 @@
1
+ /**
2
+ * WHO CAN SEE THIS RECORD, on the open record in the Library (Todo ENG-158).
3
+ *
4
+ * A record is private to whoever it belongs to until they share it. This is the
5
+ * one place that says so and changes it: a line of who it is shared with, and one
6
+ * menu to add a person, a team, or the whole organisation. It hides itself when
7
+ * the host's client cannot read shares, and shows the line without the menu when
8
+ * the caller may read the record but not change who else can.
9
+ */
10
+ import * as React from 'react';
11
+
12
+ import type { CorpusApi } from '../corpus/types';
13
+ import type { RecordShare, RecordShares, ShareChoices, ShareKind, ShareLevel } from '../corpus/sharing';
14
+
15
+ type Slots = Record<'badge' | 'input' | 'muted' | 'error', string>;
16
+
17
+ type SharingApi = Pick<CorpusApi, 'listRecordShares' | 'listShareChoices' | 'addRecordShare' | 'removeRecordShare'>;
18
+
19
+ const ORG_OPTION = 'org:';
20
+
21
+ export function labelFor(share: RecordShare, choices: ShareChoices): string {
22
+ if (share.kind === 'org') return choices.org?.label ?? 'Everyone in my organisation';
23
+ const pool = share.kind === 'group' ? choices.teams : choices.people;
24
+ return pool.find((c) => c.id === share.subjectId)?.label ?? (share.kind === 'group' ? 'A team' : 'A colleague');
25
+ }
26
+
27
+ export function SharedWith({
28
+ api, documentId, classNames: cn,
29
+ }: {
30
+ api: SharingApi;
31
+ documentId: string;
32
+ classNames: Slots;
33
+ }) {
34
+ const apiRef = React.useRef(api);
35
+ apiRef.current = api;
36
+ const [state, setState] = React.useState<RecordShares | undefined>(undefined);
37
+ const [choices, setChoices] = React.useState<ShareChoices>({ people: [], teams: [] });
38
+ const [level, setLevel] = React.useState<ShareLevel>('viewer');
39
+ const [busy, setBusy] = React.useState(false);
40
+ const [error, setError] = React.useState('');
41
+ const canRead = Boolean(api.listRecordShares);
42
+
43
+ const load = React.useCallback(async () => {
44
+ try {
45
+ setState(await apiRef.current.listRecordShares!(documentId));
46
+ } catch {
47
+ setState(undefined);
48
+ setError('Who this is shared with could not be read.');
49
+ }
50
+ }, [documentId]);
51
+
52
+ React.useEffect(() => {
53
+ if (!canRead) return;
54
+ setState(undefined);
55
+ setError('');
56
+ void load();
57
+ }, [canRead, load]);
58
+
59
+ const canEdit = Boolean(state?.canShare && api.addRecordShare && api.removeRecordShare && api.listShareChoices);
60
+ React.useEffect(() => {
61
+ if (!canEdit) return undefined;
62
+ let live = true;
63
+ apiRef.current.listShareChoices!()
64
+ .then((result) => { if (live) setChoices(result); })
65
+ .catch(() => { /* the line still shows; only the menu is lost */ });
66
+ return () => { live = false; };
67
+ }, [canEdit]);
68
+
69
+ if (!canRead) return null;
70
+
71
+ async function act(work: () => Promise<void>) {
72
+ setBusy(true);
73
+ setError('');
74
+ try {
75
+ await work();
76
+ await load();
77
+ } catch (err) {
78
+ setError((err as { message?: string })?.message || 'Sharing could not be changed.');
79
+ } finally {
80
+ setBusy(false);
81
+ }
82
+ }
83
+
84
+ function add(value: string) {
85
+ if (!value) return;
86
+ const [kind, ...rest] = value.split(':');
87
+ const subjectId = rest.join(':');
88
+ void act(() => apiRef.current.addRecordShare!(documentId, { kind: kind as ShareKind, subjectId, level }));
89
+ }
90
+
91
+ const taken = new Set((state?.shares ?? []).map((s) => `${s.kind}:${s.subjectId}`));
92
+ const orgTaken = (state?.shares ?? []).some((s) => s.kind === 'org');
93
+
94
+ return (
95
+ <div className="mt-3 flex flex-wrap items-center gap-2" data-testid="shared-with">
96
+ <p className="text-sm font-medium text-gray-900">Shared with</p>
97
+ {state === undefined && !error ? <span className={cn.muted}>…</span> : null}
98
+ {state && state.shares.length === 0 ? <span className={cn.muted}>Only you</span> : null}
99
+ {state?.shares.map((share) => (
100
+ <span key={share.id} className={cn.badge}>
101
+ {labelFor(share, choices)}{share.level === 'editor' ? ' · can edit' : ''}
102
+ {canEdit ? (
103
+ <button
104
+ type="button"
105
+ className="ml-1"
106
+ aria-label={`Stop sharing with ${labelFor(share, choices)}`}
107
+ disabled={busy}
108
+ onClick={() => { void act(() => apiRef.current.removeRecordShare!(share.id)); }}
109
+ >×</button>
110
+ ) : null}
111
+ </span>
112
+ ))}
113
+ {canEdit ? (
114
+ <>
115
+ <label>
116
+ <span className="sr-only">Share with</span>
117
+ <select className={cn.input} disabled={busy} value="" onChange={(e) => add(e.target.value)}>
118
+ <option value="">Share with…</option>
119
+ {choices.org && !orgTaken ? <option value={`${ORG_OPTION}${choices.org.id}`}>{choices.org.label}</option> : null}
120
+ {choices.teams.filter((t) => !taken.has(`group:${t.id}`)).map((t) => (
121
+ <option key={`g${t.id}`} value={`group:${t.id}`}>{t.label} (team)</option>
122
+ ))}
123
+ {choices.people.filter((p) => !taken.has(`user:${p.id}`)).map((p) => (
124
+ <option key={`u${p.id}`} value={`user:${p.id}`}>{p.label}</option>
125
+ ))}
126
+ </select>
127
+ </label>
128
+ <label>
129
+ <span className="sr-only">Access</span>
130
+ <select className={cn.input} disabled={busy} value={level} onChange={(e) => setLevel(e.target.value as ShareLevel)}>
131
+ <option value="viewer">Can view</option>
132
+ <option value="editor">Can edit</option>
133
+ </select>
134
+ </label>
135
+ </>
136
+ ) : null}
137
+ {error ? <p className={cn.error} role="alert">{error}</p> : null}
138
+ </div>
139
+ );
140
+ }
@@ -23,7 +23,7 @@ import type { RosterMember } from '../../corpus/owner-link';
23
23
  import { ExternalLinkChip } from './task-tracker/ExternalLinkChip';
24
24
  import { failureMessage } from './work-items';
25
25
  import { ProjectGuess } from './task-tracker/ProjectGuess';
26
- import { PossiblyDoneNote, markDonePatch, notDonePatch } from './tracker/PossiblyDone';
26
+ import { PossiblyDoneNote, keepDuePatch, markDonePatch, notDonePatch, setDuePatch } from './tracker/PossiblyDone';
27
27
  import { EngineReason, SuggestionNote, acceptPatch, rejectPatch } from './tracker/Suggestion';
28
28
  import { SUGGESTED_STATUS } from '../../corpus/item-status';
29
29
  import type { MemberConnectionsApi } from './types';
@@ -219,7 +219,7 @@ export function TaskDetailPage({
219
219
  };
220
220
 
221
221
  const back = onBack ? (
222
- <button type="button" className="text-sm text-blue-700 underline" onClick={onBack}>← Back to Tracker</button>
222
+ <button type="button" className="text-sm text-blue-700 underline" onClick={onBack}>← Back to to-dos</button>
223
223
  ) : null;
224
224
 
225
225
  if (loading) return <div className={cn.root}>{back}<p className={cn.muted}>Loading…</p></div>;
@@ -311,6 +311,8 @@ export function TaskDetailPage({
311
311
  item={item} disabled={busy}
312
312
  onMarkDone={(it, c) => void patchItem(markDonePatch(c))}
313
313
  onNotDone={(it, c) => void patchItem(notDonePatch(it, c))}
314
+ onSetDue={(it, p) => void patchItem(setDuePatch(it, p))}
315
+ onKeepDue={(it, p) => void patchItem(keepDuePatch(it, p))}
314
316
  />
315
317
  ) : null}
316
318
  {item.statusReason ? (