@startsimpli/integrations 0.2.67 → 0.2.69

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.
@@ -1,8 +1,6 @@
1
- import { useState, type ReactNode } from 'react';
2
- import { View } from 'react-native';
3
- import { useSafeAreaInsets } from 'react-native-safe-area-context';
4
- import { TabBar, useTheme } from '@startsimpli/ui-native';
1
+ import { useMemo, type ReactNode } from 'react';
5
2
  import type { VoiceNotesController } from '../voice/controller';
3
+ import { FoundryTabsShell, type FoundryTab } from './FoundryTabsShell';
6
4
  import { NoteDetailScreen } from './NoteDetailScreen';
7
5
  import { NotesListScreen } from './NotesListScreen';
8
6
 
@@ -18,29 +16,24 @@ export interface NotesShellProps {
18
16
  initialNoteId?: string;
19
17
  }
20
18
 
21
- /** Two tabs: GO (the app's record screen) and Notes (list -> detail). */
19
+ /** The first preset of `FoundryTabsShell`: GO (the app's record screen) and Notes (list -> detail). */
22
20
  export function NotesShell({ go, controller, goLabel = 'GO', notesLabel = 'Notes', initialTab, initialNoteId }: NotesShellProps) {
23
- const theme = useTheme();
24
- const insets = useSafeAreaInsets();
25
- const [tab, setTab] = useState<'go' | 'notes'>(initialTab ?? (initialNoteId ? 'notes' : 'go'));
26
- const [openId, setOpenId] = useState<string | null>(initialNoteId ?? null);
21
+ const tabs = useMemo<FoundryTab[]>(() => [
22
+ { key: 'go', label: goLabel, safeArea: false, render: () => go },
23
+ {
24
+ key: 'notes', label: notesLabel, resetOnLeave: true,
25
+ render: ({ route, push, back }) => route
26
+ ? <NoteDetailScreen controller={controller} noteId={route.id} onBack={back} />
27
+ : <NotesListScreen controller={controller} onOpen={(n) => push(n.id)} />,
28
+ },
29
+ // `go` is a fresh element each render; the shell re-renders the tab list every time anyway.
30
+ // eslint-disable-next-line react-hooks/exhaustive-deps
31
+ ], [go, controller, goLabel, notesLabel]);
27
32
  return (
28
- <View style={{ flex: 1, backgroundColor: theme.colors.background }}>
29
- <View style={{ flex: 1, display: tab === 'go' ? 'flex' : 'none' }}>{go}</View>
30
- {tab === 'notes' ? (
31
- <View style={{ flex: 1, paddingTop: insets.top }}>
32
- {openId ? (
33
- <NoteDetailScreen controller={controller} noteId={openId} onBack={() => setOpenId(null)} />
34
- ) : (
35
- <NotesListScreen controller={controller} onOpen={(n) => setOpenId(n.id)} />
36
- )}
37
- </View>
38
- ) : null}
39
- <TabBar
40
- items={[{ key: 'go', label: goLabel }, { key: 'notes', label: notesLabel }]}
41
- activeKey={tab}
42
- onChange={(k) => { setTab(k as 'go' | 'notes'); if (k === 'go') setOpenId(null); }}
43
- />
44
- </View>
33
+ <FoundryTabsShell
34
+ tabs={tabs}
35
+ initialTab={initialTab}
36
+ initialDetail={initialNoteId ? { tab: 'notes', id: initialNoteId } : undefined}
37
+ />
45
38
  );
46
39
  }
@@ -0,0 +1,155 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createAuthorizedCorpusHttp } from '../../voice/http';
3
+ import { createNativeCorpusApi } from '../api';
4
+ import { createFakeTenantHttp } from '../fake-tenant';
5
+ import { createFakeNativeCorpusApi } from '../fake';
6
+
7
+ function fake(opts: Parameters<typeof createFakeTenantHttp>[0] = {}) {
8
+ const api = createFakeNativeCorpusApi(opts);
9
+ return { tenant: api.tenant, api };
10
+ }
11
+
12
+ describe('authorized http transport', () => {
13
+ it('repeats an array parameter instead of comma-joining it', async () => {
14
+ const f = vi.fn(async () => new Response('{}'));
15
+ const http = createAuthorizedCorpusHttp({ baseUrl: 'http://t', authorizedFetch: f });
16
+ await http.get('api/v1/entities', { params: { type: 'x', external_id__in: ['a,b', 'c'] } });
17
+ expect(f).toHaveBeenCalledWith('http://t/api/v1/entities?type=x&external_id__in=a%2Cb&external_id__in=c', expect.anything());
18
+ });
19
+ });
20
+
21
+ describe('entities.list: generic, server-side', () => {
22
+ it('returns {items,next,appliedFilters} for a typed query and sends every parameter to the server', async () => {
23
+ const { tenant, api } = fake();
24
+ const page = await api.entities.list({
25
+ type: 'commitment', order: 'attr.due_at', pageSize: 2, search: 'the',
26
+ attr: { status: 'open' }, filters: { createdAfter: '2020-01-01T00:00:00Z' },
27
+ });
28
+ expect(tenant.requests.at(-1)?.params).toMatchObject({
29
+ type: 'commitment', order: 'attr.due_at', page_size: 2, search: 'the', 'attr.status': 'open', created_after: '2020-01-01T00:00:00Z', page: 1,
30
+ });
31
+ expect(page.items.length).toBeLessThanOrEqual(2);
32
+ expect(page.count).toBeGreaterThan(2);
33
+ expect(page.next).toBeTruthy();
34
+ expect(page.appliedFilters).toEqual(expect.arrayContaining(['type', 'order', 'search', 'attr.status']));
35
+ expect(page.ignoredFilters).toEqual([]);
36
+ });
37
+ it('orders by due date on the server, undated last', async () => {
38
+ const { api } = fake();
39
+ const page = await api.entities.list({ type: 'commitment', order: 'attr.due_at', attr: { status: 'open' } });
40
+ expect(page.items.map((e) => e.id)).toEqual(['c2', 'c1', 'c4', 'c3']);
41
+ });
42
+ it('detects a filter the server ignored instead of presenting the list as filtered', async () => {
43
+ const { api } = fake({ unsupported: ['attr.status'] });
44
+ const page = await api.entities.list({ type: 'commitment', attr: { status: 'done' } });
45
+ expect(page.count).toBe(6); // the server did not narrow
46
+ expect(page.ignoredFilters).toEqual(['attr.status']);
47
+ });
48
+ it('walks the pages with the server cursor', async () => {
49
+ const { tenant, api } = fake();
50
+ const seen: string[] = [];
51
+ let next: number | null = 1;
52
+ while (next) {
53
+ const page = await api.entities.list({ type: 'commitment', pageSize: 4, page: next, order: 'oldest' });
54
+ seen.push(...page.items.map((e) => String(e.id)));
55
+ next = page.nextPage;
56
+ }
57
+ expect(seen).toEqual(['c5', 'c6', 'c1', 'c2', 'c3', 'c4']);
58
+ expect(tenant.requests.filter((r) => r.method === 'GET')).toHaveLength(2);
59
+ });
60
+ it('gets one record, refusing a page that answers in its place', async () => {
61
+ const { api } = fake();
62
+ expect((await api.entities.get('c1')).id).toBe('c1');
63
+ await expect(api.entities.get('nope')).rejects.toMatchObject({ status: 404 });
64
+ const lying = createNativeCorpusApi({ http: { get: async () => ({ count: 3, results: [] }) } as never, scope: { orgId: 'x' } });
65
+ await expect(lying.entities.get('c1')).rejects.toMatchObject({ status: 404 });
66
+ });
67
+ it('facets: distinct values of an attribute, paged', async () => {
68
+ const { api } = fake();
69
+ const res = await api.entities.facets({ type: 'source_document', facetAttr: 'path', under: '/' });
70
+ expect(res.items.map((f) => f.value)).toEqual(['/Debug']);
71
+ expect(res.appliedFilters).toEqual(expect.arrayContaining(['attr', 'under']));
72
+ });
73
+ it('relationships.list filters and reports', async () => {
74
+ const { api } = fake();
75
+ const res = await api.relationships.list({ relType: 'in_focus', target: 'f287' });
76
+ expect(res.items.map((e) => e.source).sort()).toEqual(['c1', 'c2', 'c6']);
77
+ expect(res.ignoredFilters).toEqual([]);
78
+ });
79
+ });
80
+
81
+ describe('the web composers\' apis, over the same http', () => {
82
+ it('commitments: filter by project and status, server-side; the item carries the right fields', async () => {
83
+ const { api } = fake();
84
+ const page = await api.corpus.listCommitments({ focus: 'f287', status: 'open' });
85
+ expect(page.results.map((c) => c.id)).toEqual(['c2', 'c1']);
86
+ expect(page.results[0]).toMatchObject({ title: 'Call Megan about the filing receipt', status: 'open', ownerName: 'Quinn' });
87
+ expect(page.appliedFilters).toEqual(expect.arrayContaining(['focus', 'status']));
88
+ });
89
+ it('setStatus writes through and the next read reflects it', async () => {
90
+ const { api } = fake();
91
+ const before = (await api.corpus.listCommitments({ focus: 'f287', status: 'open' })).results[0];
92
+ const done = await api.commitments.setStatus(before, 'done');
93
+ expect(done.status).toBe('done');
94
+ const open = await api.corpus.listCommitments({ focus: 'f287', status: 'open' });
95
+ expect(open.results.map((c) => c.id)).toEqual(['c1']);
96
+ });
97
+ it('documents (library): search and project filter are server-side', async () => {
98
+ const { api } = fake();
99
+ const inProject = await api.corpus.listDocuments!({ focus: 'fma' });
100
+ expect(inProject.results.map((d) => d.id)).toEqual(['d2']);
101
+ const found = await api.corpus.listDocuments!({ search: 'checklist', order: 'recent' });
102
+ expect(found.results.map((d) => d.id)).toEqual(['d3']);
103
+ });
104
+ it('focuses (projects) and the items under one', async () => {
105
+ const { api } = fake();
106
+ const focuses = await api.corpus.listFocuses({ orderBy: 'title' });
107
+ expect(focuses.results.map((f) => f.title)).toEqual(['287A', 'Debug', 'Marketing agents']);
108
+ const items = await api.corpus.listCommitments({ focus: 'fma' });
109
+ expect(items.results.map((c) => c.id)).toEqual(['c3']);
110
+ });
111
+ it('filing a document moves it between projects', async () => {
112
+ const { api } = fake();
113
+ await api.corpus.fileDocument!('d2', 'fdbg');
114
+ const moved = await api.corpus.listDocuments!({ focus: 'fdbg' });
115
+ expect(moved.results.map((d) => d.id).sort()).toEqual(['d2', 'd3']);
116
+ });
117
+ });
118
+
119
+ describe('PagedList adapters', () => {
120
+ it('commitmentsList pages the server and exposes ignored filters', async () => {
121
+ const { api } = fake();
122
+ const list = api.lists.commitments({ status: 'open' }, 2);
123
+ await list.refresh();
124
+ expect(list.getState().items).toHaveLength(2);
125
+ expect(list.getState().hasMore).toBe(true);
126
+ await list.loadMore();
127
+ expect(list.getState().items.map((c) => c.id)).toEqual(['c2', 'c1', 'c4', 'c3']);
128
+ expect(list.getState().items).toHaveLength(4);
129
+ expect(list.getState().hasMore).toBe(false);
130
+ expect(list.getState().ignoredFilters).toEqual([]);
131
+ });
132
+ it('flags an ignored status filter through the composer vocabulary', async () => {
133
+ const { api } = fake({ unsupported: ['attr.status', 'attr.status__in'] });
134
+ const list = api.lists.commitments({ status: 'done' }, 10);
135
+ await list.refresh();
136
+ expect(list.getState().ignoredFilters).toEqual(['status']);
137
+ });
138
+ });
139
+
140
+ describe('ask', () => {
141
+ it('POSTs the request to the tenant frontend route and returns its result', async () => {
142
+ const post = vi.fn(async () => ({ status: 'answered', answer: 'x', citations: [], considered: [], unresolvedCitations: [], droppedOutOfScope: 0, provider: { provider: 'p', model: 'm', live: true } }));
143
+ const api = createNativeCorpusApi({ http: { get: vi.fn(), post } as never, scope: { orgId: 'tandem' } });
144
+ const res = await api.ask.ask({ question: 'q', mode: 'ask', scope: { orgId: 'tandem' }, filters: { focus: 'f1' } });
145
+ expect(post).toHaveBeenCalledWith('corpus/ask', { question: 'q', mode: 'ask', scope: { orgId: 'tandem' }, filters: { focus: 'f1' } });
146
+ expect(res.answer).toBe('x');
147
+ });
148
+ it('the fake answers from the fake corpus with citations, scoped to a project', async () => {
149
+ const { api } = fake();
150
+ const res = await api.ask.ask({ question: 'What is happening with the hearing?', mode: 'ask', scope: { orgId: 'tandem' }, filters: { focus: 'f287' } });
151
+ expect(res.status).toBe('answered');
152
+ expect(res.citations.map((c) => c.documentId)).toEqual(['d1']);
153
+ expect(res.provider.live).toBe(false);
154
+ });
155
+ });
@@ -0,0 +1,123 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { TenantEntity, TenantRelationship } from '../../../corpus/entities';
3
+ import { entityParams, facetParams, relationshipParams, reconcileFilters } from '../../../corpus/entity-query';
4
+ import { createFakeTenantHttp } from '../fake-tenant';
5
+
6
+ const row = (id: string, type: string, name: string, data: Record<string, unknown>, createdAt: string, external?: string): TenantEntity =>
7
+ ({ id, entity_type: type, name, data, created_at: createdAt, external_id: external ?? `${type}:${id}` });
8
+
9
+ const rows: TenantEntity[] = [
10
+ row('c1', 'commitment', 'Send exhibit list', { status: 'open', due_at: '2026-11-05', owner_name: 'Rae', path: '/287a/prep' }, '2026-11-01T00:00:00Z'),
11
+ row('c2', 'commitment', 'Book dentist', { status: 'done', due_at: '2026-11-02', owner_name: 'Quinn', path: '/personal' }, '2026-11-02T00:00:00Z'),
12
+ row('c3', 'commitment', 'Move weekly report', { status: 'open', owner_name: 'Quinn', path: '/ma' }, '2026-11-03T00:00:00Z'),
13
+ row('c4', 'commitment', 'Call Megan about filing', { status: 'blocked', due_at: '2026-11-01', path: '/287a' }, '2026-10-30T00:00:00Z'),
14
+ row('f1', 'focus', '287A', { title: '287A' }, '2026-10-01T00:00:00Z'),
15
+ row('d1', 'source_document', 'Hearing prep', { source: 'voice', occurred_at: '2026-11-03T10:00:00Z', summary: 'exhibit list for the hearing' }, '2026-11-03T10:00:00Z'),
16
+ ];
17
+ const edges: TenantRelationship[] = [
18
+ { id: 'e1', rel_type: 'in_focus', source: 'c1', target: 'f1' },
19
+ { id: 'e2', rel_type: 'in_focus', source: 'c4', target: 'f1' },
20
+ { id: 'e3', rel_type: 'about_focus', source: 'd1', target: 'f1' },
21
+ ];
22
+
23
+ function list(params: Record<string, unknown>, opts: Parameters<typeof createFakeTenantHttp>[0] = {}) {
24
+ const { http } = createFakeTenantHttp({ entities: rows, relationships: edges, ...opts });
25
+ return http.get<any>('api/v1/entities', { params });
26
+ }
27
+ const ids = (r: any) => r.results.map((x: TenantEntity) => x.id);
28
+
29
+ describe('fake tenant http honours the entities contract', () => {
30
+ it('filters by type and paginates server-side with next links, capped at 200', async () => {
31
+ const first = await list(entityParams({ type: 'commitment', pageSize: 3, order: 'oldest' }));
32
+ expect(first.count).toBe(4);
33
+ expect(ids(first)).toEqual(['c4', 'c1', 'c2']);
34
+ expect(first.next).toBeTruthy();
35
+ const second = await list(entityParams({ type: 'commitment', pageSize: 3, page: 2, order: 'oldest' }));
36
+ expect(ids(second)).toEqual(['c3']);
37
+ expect(second.next).toBeNull();
38
+ });
39
+ it('orders recent by default and by attribute with undated rows last in both directions', async () => {
40
+ expect(ids(await list(entityParams({ type: 'commitment' })))).toEqual(['c3', 'c2', 'c1', 'c4']);
41
+ expect(ids(await list(entityParams({ type: 'commitment', order: 'attr.due_at' })))).toEqual(['c4', 'c2', 'c1', 'c3']);
42
+ expect(ids(await list(entityParams({ type: 'commitment', order: '-attr.due_at' })))).toEqual(['c1', 'c2', 'c4', 'c3']);
43
+ });
44
+ it('applies attribute operators', async () => {
45
+ const q = (attr: any) => list(entityParams({ type: 'commitment', attr, order: 'oldest' })).then(ids);
46
+ expect(await q({ status: 'open' })).toEqual(['c1', 'c3']);
47
+ expect(await q({ status__in: ['open', 'blocked'] })).toEqual(['c4', 'c1', 'c3']);
48
+ expect(await q({ due_at__lte: '2026-11-02' })).toEqual(['c4', 'c2']);
49
+ expect(await q({ owner_name__icontains: 'qui' })).toEqual(['c2', 'c3']);
50
+ expect(await q({ due_at__isnull: true })).toEqual(['c3']);
51
+ expect(await q({ path__under: '/287a' })).toEqual(['c4', 'c1']);
52
+ expect(await q({ path__startswith: '/p' })).toEqual(['c2']);
53
+ });
54
+ it('walks an edge with the row at the source end (direction out)', async () => {
55
+ const out = await list(entityParams({ type: 'commitment', order: 'oldest', filters: { relatedTo: 'f1', relatedVia: 'in_focus', relatedDirection: 'out' } }));
56
+ expect(ids(out)).toEqual(['c4', 'c1']);
57
+ const wrong = await list(entityParams({ type: 'commitment', filters: { relatedTo: 'f1', relatedVia: 'in_focus', relatedDirection: 'in' } }));
58
+ expect(ids(wrong)).toEqual([]);
59
+ });
60
+ it('filters by id, id__in, external_id, external_id__in, created and occurred bounds', async () => {
61
+ expect(ids(await list(entityParams({ type: 'commitment', filters: { id: 'c2' } })))).toEqual(['c2']);
62
+ expect(ids(await list(entityParams({ type: 'commitment', order: 'oldest', filters: { idIn: ['c1', 'c3'] } })))).toEqual(['c1', 'c3']);
63
+ expect(ids(await list(entityParams({ type: 'commitment', filters: { externalId: 'commitment:c4' } })))).toEqual(['c4']);
64
+ expect(ids(await list(entityParams({ type: 'commitment', order: 'oldest', filters: { externalIdIn: ['commitment:c1', 'commitment:c2'] } })))).toEqual(['c1', 'c2']);
65
+ expect(ids(await list(entityParams({ type: 'commitment', filters: { createdAfter: '2026-11-02T12:00:00Z' } })))).toEqual(['c3']);
66
+ expect(ids(await list(entityParams({ type: 'commitment', filters: { createdBefore: '2026-10-31T00:00:00Z' } })))).toEqual(['c4']);
67
+ expect(ids(await list(entityParams({ type: 'source_document', filters: { occurredAfter: '2026-11-01T00:00:00Z', source: 'voice' } })))).toEqual(['d1']);
68
+ expect(ids(await list(entityParams({ type: 'source_document', filters: { occurredBefore: '2026-11-01T00:00:00Z' } })))).toEqual([]);
69
+ });
70
+ it('searches text, and relevance ranks by hits', async () => {
71
+ expect(ids(await list(entityParams({ type: 'commitment', search: 'weekly' })))).toEqual(['c3']);
72
+ const ranked = await list(entityParams({ type: 'commitment', search: 'quinn', order: 'relevance' }));
73
+ expect(ids(ranked).sort()).toEqual(['c2', 'c3']);
74
+ });
75
+ it('reports applied_filters for everything it honoured', async () => {
76
+ const params = entityParams({
77
+ type: 'commitment', search: 'a', order: 'attr.due_at', attr: { status: 'open' },
78
+ filters: { relatedTo: 'f1', relatedVia: 'in_focus', relatedDirection: 'out', createdAfter: '2020-01-01' },
79
+ });
80
+ const res = await list(params);
81
+ expect(reconcileFilters(params, res).ignored).toEqual([]);
82
+ });
83
+ it('reports a filter it was told to treat as unknown as ignored, and does NOT narrow by it', async () => {
84
+ const params = entityParams({ type: 'commitment', attr: { status: 'open' } });
85
+ const res = await list(params, { unsupported: ['attr.status'] });
86
+ expect(res.count).toBe(4);
87
+ expect(res.ignored_filters).toContain('attr.status');
88
+ expect(reconcileFilters(params, res).ignored).toEqual(['attr.status']);
89
+ });
90
+ it('an unknown parameter is ignored and reported, never silently applied', async () => {
91
+ const res = await list({ type: 'commitment', page: 1, bogus: 'x' });
92
+ expect(res.ignored_filters).toContain('bogus');
93
+ });
94
+ it('relevance with no search is reported ignored, as the server does', async () => {
95
+ const res = await list({ type: 'commitment', page: 1, order: 'relevance' });
96
+ expect(res.ignored_filters).toContain('order');
97
+ });
98
+ it('serves a single record and 404s a missing one', async () => {
99
+ const { http } = createFakeTenantHttp({ entities: rows, relationships: edges });
100
+ expect((await http.get<TenantEntity>('api/v1/entities/c2')).id).toBe('c2');
101
+ await expect(http.get('api/v1/entities/nope')).rejects.toMatchObject({ status: 404 });
102
+ });
103
+ it('lists relationships with filters and edge paging', async () => {
104
+ const { http } = createFakeTenantHttp({ entities: rows, relationships: edges });
105
+ const res = await http.get<any>('api/v1/relationships', { params: relationshipParams({ relType: 'in_focus', targetIn: ['f1'], pageSize: 1 }) });
106
+ expect(res.count).toBe(2);
107
+ expect(res.results).toHaveLength(1);
108
+ expect(res.next).toBeTruthy();
109
+ expect(res.applied_filters).toEqual(expect.arrayContaining(['rel_type', 'target__in']));
110
+ });
111
+ it('facets enumerate distinct child values under a subtree', async () => {
112
+ const { http } = createFakeTenantHttp({ entities: rows, relationships: edges });
113
+ const res = await http.get<any>('api/v1/entities/facets', { params: facetParams({ type: 'commitment', facetAttr: 'path', under: '/' }) });
114
+ expect(res.results.map((r: any) => r.value).sort()).toEqual(['/287a', '/ma', '/personal']);
115
+ expect(res.applied_filters).toEqual(expect.arrayContaining(['attr', 'under']));
116
+ });
117
+ it('upserts by external_id, shallow-merging data', async () => {
118
+ const { http } = createFakeTenantHttp({ entities: rows.map((r) => ({ ...r, data: { ...r.data } })), relationships: edges });
119
+ const out = await http.post<TenantEntity>('api/v1/entities/upsert', { entity_type: 'commitment', external_id: 'commitment:c1', data: { status: 'done' } });
120
+ expect(out.data).toMatchObject({ status: 'done', owner_name: 'Rae' });
121
+ expect((await http.get<TenantEntity>('api/v1/entities/c1')).data?.status).toBe('done');
122
+ });
123
+ });
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createPagedList } from '../paged';
3
+
4
+ const pageOf = (n: number, size: number, total: number) => ({
5
+ items: Array.from({ length: Math.min(size, total - (n - 1) * size) }, (_, i) => `r${(n - 1) * size + i + 1}`),
6
+ count: total, nextPage: n * size < total ? n + 1 : null, ignoredFilters: [] as string[],
7
+ });
8
+
9
+ describe('createPagedList', () => {
10
+ it('loads page 1, then appends each next page until the server says there is none', async () => {
11
+ const fetchPage = vi.fn(async (page: number) => pageOf(page, 2, 5));
12
+ const list = createPagedList({ fetchPage });
13
+ await list.refresh();
14
+ expect(list.getState().items).toEqual(['r1', 'r2']);
15
+ expect(list.getState().hasMore).toBe(true);
16
+ await list.loadMore();
17
+ await list.loadMore();
18
+ expect(list.getState().items).toEqual(['r1', 'r2', 'r3', 'r4', 'r5']);
19
+ expect(list.getState().hasMore).toBe(false);
20
+ await list.loadMore(); // nothing more: no request
21
+ expect(fetchPage.mock.calls.map((c) => c[0])).toEqual([1, 2, 3]);
22
+ expect(list.getState().count).toBe(5);
23
+ });
24
+ it('never fires two loads at once', async () => {
25
+ let release!: () => void;
26
+ const gate = new Promise<void>((r) => { release = r; });
27
+ const fetchPage = vi.fn(async (page: number) => { await gate; return pageOf(page, 2, 6); });
28
+ const list = createPagedList({ fetchPage });
29
+ const a = list.refresh();
30
+ void list.refresh();
31
+ void list.loadMore();
32
+ release();
33
+ await a;
34
+ expect(fetchPage).toHaveBeenCalledTimes(1);
35
+ });
36
+ it('refresh restarts from page 1 and replaces the items', async () => {
37
+ const fetchPage = vi.fn(async (page: number) => pageOf(page, 2, 4));
38
+ const list = createPagedList({ fetchPage });
39
+ await list.refresh();
40
+ await list.loadMore();
41
+ await list.refresh();
42
+ expect(list.getState().items).toEqual(['r1', 'r2']);
43
+ });
44
+ it('surfaces a filter the server ignored, and clears it on the next clean load', async () => {
45
+ let ignored = ['attr.status'];
46
+ const list = createPagedList({ fetchPage: async () => ({ ...pageOf(1, 2, 2), ignoredFilters: ignored }) });
47
+ await list.refresh();
48
+ expect(list.getState().ignoredFilters).toEqual(['attr.status']);
49
+ ignored = [];
50
+ await list.refresh();
51
+ expect(list.getState().ignoredFilters).toEqual([]);
52
+ });
53
+ it('keeps loaded rows and reports the error when a next page fails, and can retry', async () => {
54
+ let fail = true;
55
+ const list = createPagedList({
56
+ fetchPage: async (page) => {
57
+ if (page === 2 && fail) throw new Error('boom');
58
+ return pageOf(page, 2, 4);
59
+ },
60
+ });
61
+ await list.refresh();
62
+ await list.loadMore();
63
+ expect(list.getState().error).toBe('boom');
64
+ expect(list.getState().items).toEqual(['r1', 'r2']);
65
+ fail = false;
66
+ await list.loadMore();
67
+ expect(list.getState().error).toBeNull();
68
+ expect(list.getState().items).toHaveLength(4);
69
+ });
70
+ it('a query change discards a stale in-flight response', async () => {
71
+ const resolvers: Array<() => void> = [];
72
+ const list = createPagedList<string, { q: string }>({
73
+ query: { q: 'old' },
74
+ fetchPage: (page, q) => new Promise((res) => { resolvers.push(() => res({ ...pageOf(page, 2, 2), items: [q.q] })); }),
75
+ });
76
+ const first = list.refresh();
77
+ const second = list.setQuery({ q: 'new' });
78
+ resolvers[1]();
79
+ await second;
80
+ resolvers[0]();
81
+ await first;
82
+ expect(list.getState().items).toEqual(['new']);
83
+ });
84
+ it('notifies subscribers', async () => {
85
+ const list = createPagedList({ fetchPage: async (p) => pageOf(p, 2, 2) });
86
+ const fn = vi.fn();
87
+ list.subscribe(fn);
88
+ await list.refresh();
89
+ expect(fn).toHaveBeenCalled();
90
+ });
91
+ });
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The native data layer for every Tandem tab: the SAME adapters the web composers
3
+ * use (`createPlanningApi` -> documents, commitments, focuses; `askCorpus`'s
4
+ * route), over an authorized fetch instead of a browser client - plus the one
5
+ * generic entities/relationships/facets query the tabs share.
6
+ *
7
+ * Nothing here loads a whole list and narrows it locally: each call is one
8
+ * server page. `entityParams` (shared with the web adapter) spells the query and
9
+ * `reconcileFilters` reads the server's `applied_filters`, so a filter the
10
+ * endpoint ignored comes back as `ignoredFilters` instead of looking applied.
11
+ *
12
+ * Not used from here: `mcpTokens` / `connectionsMe` (api/*) call a module-global
13
+ * `request()` that bypasses `authorizedFetch`; the Connections / Connect Claude
14
+ * tabs need a `create*Api(fetch)` factory first (see the README).
15
+ */
16
+ import { createPlanningApi, type CreateCorpusApiOptions } from '../../corpus/client';
17
+ import { isRecord, notFound } from '../../corpus/client';
18
+ import type { TenantEntity, TenantFacetRow, TenantRelationship } from '../../corpus/entities';
19
+ import {
20
+ entityParams, facetParams, relationshipParams, toEntityPage,
21
+ type EntityPage, type EntityQuery, type FacetQuery, type RelationshipListQuery,
22
+ } from '../../corpus/entity-query';
23
+ import type {
24
+ Commitment, CommitmentQuery, CommitmentStatus, CorpusAskApi, CorpusPage, CorpusScope,
25
+ DocumentQuery, Focus, FocusQuery, SourceDocument,
26
+ } from '../../corpus/types';
27
+ import type { CorpusApi, PlanningApi } from '../../corpus/types';
28
+ import { createAuthorizedCorpusHttp, type AuthorizedFetch, type AuthorizedHttp } from '../voice/http';
29
+ import { createRemoteAskApi } from './ask';
30
+ import { createPagedList, type PageResult, type PagedList } from './paged';
31
+
32
+ const ENTITIES = 'api/v1/entities';
33
+ const RELATIONSHIPS = 'api/v1/relationships';
34
+
35
+ export interface NativeCorpusDeps {
36
+ /** Either an already-built http (fakes, tests)... */
37
+ http?: AuthorizedHttp;
38
+ /** ...or the pieces to build one: the app's authorized fetch and the tenant origin. */
39
+ baseUrl?: string;
40
+ authorizedFetch?: AuthorizedFetch;
41
+ /** Row-mapping fallback scope. Defaults to `{}`: the tenant's own row scope wins. */
42
+ scope?: CorpusScope;
43
+ /** Override where ask goes (default: POST `corpus/ask`). */
44
+ ask?: CorpusAskApi;
45
+ askPath?: string;
46
+ corpus?: Partial<Omit<CreateCorpusApiOptions, 'http' | 'scope'>>;
47
+ }
48
+
49
+ export interface NativeCorpusApi {
50
+ http: AuthorizedHttp;
51
+ scope: CorpusScope;
52
+ entities: {
53
+ list(query: EntityQuery): Promise<EntityPage<TenantEntity>>;
54
+ get(id: string): Promise<TenantEntity>;
55
+ facets(query: FacetQuery): Promise<EntityPage<TenantFacetRow>>;
56
+ };
57
+ relationships: { list(query: RelationshipListQuery): Promise<EntityPage<TenantRelationship>> };
58
+ /** The web composers' api objects, unchanged: Library (documents), Tracker (commitments), Planning (focuses). */
59
+ corpus: CorpusApi & PlanningApi;
60
+ commitments: {
61
+ /** A person changing a to-do's status (mark done, reopen, block, drop). */
62
+ setStatus(item: Commitment, status: CommitmentStatus, reason?: string): Promise<Commitment>;
63
+ };
64
+ ask: CorpusAskApi;
65
+ /** Server-paged list controllers over the above, for screens: load, loadMore, refresh, setQuery. */
66
+ lists: {
67
+ entities(query: Omit<EntityQuery, 'page'>): PagedList<TenantEntity, Omit<EntityQuery, 'page'>>;
68
+ commitments(query?: Omit<CommitmentQuery, 'page' | 'pageSize'>, pageSize?: number): PagedList<Commitment, Omit<CommitmentQuery, 'page' | 'pageSize'>>;
69
+ documents(query?: Omit<DocumentQuery, 'page' | 'pageSize'>, pageSize?: number): PagedList<SourceDocument, Omit<DocumentQuery, 'page' | 'pageSize'>>;
70
+ focuses(query?: Omit<FocusQuery, 'page' | 'pageSize'>, pageSize?: number): PagedList<Focus, Omit<FocusQuery, 'page' | 'pageSize'>>;
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Query keys the caller set that the server did not confirm. The composer pages
76
+ * (`CorpusPage`) report `appliedFilters` in the query's own vocabulary, so the
77
+ * verdict is "requested and not in that list".
78
+ */
79
+ export function unappliedFilters(query: object, applied: string[] | undefined): string[] {
80
+ if (!applied) return [];
81
+ const confirmed = new Set(applied);
82
+ return Object.entries(query as Record<string, unknown>)
83
+ .filter(([key, value]) => !['page', 'pageSize', 'order', 'orderBy'].includes(key)
84
+ && (Array.isArray(value) ? value.length > 0 : Boolean(value)))
85
+ .map(([key]) => key)
86
+ .filter((key) => !confirmed.has(key));
87
+ }
88
+
89
+ function fromCorpusPage<T>(page: CorpusPage<T>, query: object, number: number): PageResult<T> {
90
+ return {
91
+ items: page.results,
92
+ count: page.count,
93
+ nextPage: page.next ? number + 1 : null,
94
+ ignoredFilters: unappliedFilters(query, page.appliedFilters),
95
+ };
96
+ }
97
+
98
+ export function createNativeCorpusApi(deps: NativeCorpusDeps): NativeCorpusApi {
99
+ const http = deps.http ?? (() => {
100
+ if (!deps.baseUrl || !deps.authorizedFetch) throw new Error('createNativeCorpusApi needs an http, or baseUrl + authorizedFetch.');
101
+ return createAuthorizedCorpusHttp({ baseUrl: deps.baseUrl, authorizedFetch: deps.authorizedFetch });
102
+ })();
103
+ const scope = deps.scope ?? ({} as CorpusScope);
104
+ const corpus = createPlanningApi({ http, scope, ...deps.corpus }) as unknown as CorpusApi & PlanningApi;
105
+
106
+ const api: NativeCorpusApi = {
107
+ http,
108
+ scope,
109
+ entities: {
110
+ async list(query) {
111
+ const params = entityParams(query);
112
+ return toEntityPage(params, await http.get<{ results?: TenantEntity[] }>(ENTITIES, { params }), (row: TenantEntity) => row);
113
+ },
114
+ async get(id) {
115
+ const found = await http.get<unknown>(`${ENTITIES}/${encodeURIComponent(id)}`);
116
+ if (!isRecord(found, id)) throw notFound(id);
117
+ return found;
118
+ },
119
+ async facets(query) {
120
+ const params = facetParams(query);
121
+ return toEntityPage(params, await http.get<{ results?: TenantFacetRow[] }>(`${ENTITIES}/facets`, { params }), (row: TenantFacetRow) => row);
122
+ },
123
+ },
124
+ relationships: {
125
+ async list(query) {
126
+ const params = relationshipParams(query);
127
+ return toEntityPage(params, await http.get<{ results?: TenantRelationship[] }>(RELATIONSHIPS, { params }), (row: TenantRelationship) => row);
128
+ },
129
+ },
130
+ corpus,
131
+ commitments: {
132
+ setStatus(item, status, reason) {
133
+ if (!corpus.updateCommitment) throw new Error('This workspace cannot update to-dos.');
134
+ return corpus.updateCommitment(item, { status, ...(reason ? { statusReason: reason } : {}) });
135
+ },
136
+ },
137
+ ask: deps.ask ?? createRemoteAskApi(http, deps.askPath),
138
+ lists: {
139
+ entities: (query) => createPagedList<TenantEntity, Omit<EntityQuery, 'page'>>({
140
+ query,
141
+ async fetchPage(page, q) {
142
+ const result = await api.entities.list({ ...q, page });
143
+ return { items: result.items, count: result.count, nextPage: result.nextPage, ignoredFilters: result.ignoredFilters };
144
+ },
145
+ }),
146
+ commitments: (query = {}, pageSize = 25) => createPagedList({
147
+ query,
148
+ async fetchPage(page, q) { return fromCorpusPage(await corpus.listCommitments({ ...q, page, pageSize }), q, page); },
149
+ }),
150
+ documents: (query = {}, pageSize = 25) => createPagedList({
151
+ query,
152
+ async fetchPage(page, q) { return fromCorpusPage(await corpus.listDocuments!({ ...q, page, pageSize }), q, page); },
153
+ }),
154
+ focuses: (query = {}, pageSize = 25) => createPagedList({
155
+ query,
156
+ async fetchPage(page, q) { return fromCorpusPage(await corpus.listFocuses({ ...q, page, pageSize }), q, page); },
157
+ }),
158
+ },
159
+ };
160
+ return api;
161
+ }
@@ -0,0 +1,16 @@
1
+ import type { AskRequest, AskResult, CorpusAskApi } from '../../corpus/types';
2
+ import type { AuthorizedHttp } from '../voice/http';
3
+
4
+ /**
5
+ * Ask over the tenant frontend's own `/corpus/ask` route - the same route the
6
+ * web `AskPage` talks to. The model call and its key stay server-side
7
+ * (`askCorpus` runs there); the app only sends the question, mode, scope and the
8
+ * project filter and gets back the answer with its citations.
9
+ */
10
+ export function createRemoteAskApi(http: Pick<AuthorizedHttp, 'post'>, path = 'corpus/ask'): CorpusAskApi {
11
+ return {
12
+ ask(request: AskRequest): Promise<AskResult> {
13
+ return http.post<AskResult>(path, request);
14
+ },
15
+ };
16
+ }