@startsimpli/integrations 0.2.102 → 0.2.103

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.102",
3
+ "version": "0.2.103",
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.0",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/ui": "^0.4.170",
54
53
  "@startsimpli/auth": "^0.4.49",
55
- "@startsimpli/utils": "^0.4.17"
54
+ "@startsimpli/utils": "^0.4.17",
55
+ "@startsimpli/ui": "^0.4.170"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -0,0 +1,119 @@
1
+ import { render, screen, waitFor } from '@testing-library/react';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { PlanningPage } from '../components/pages/PlanningPage';
4
+ import { createPlanningApi } from '../corpus/client';
5
+ import { readStandings, standingsFrom } from '../corpus/standings';
6
+ import type { FocusStanding, PlanningApi } from '../corpus/types';
7
+ import { FIXTURE_DOCUMENTS } from '../corpus/fixtures';
8
+ import type { TenantEntity, TenantRelationship } from '../corpus/entities';
9
+ import { createFakeTenantHttp } from '../native/corpus/fake-tenant';
10
+
11
+ const SCOPE = FIXTURE_DOCUMENTS[0].scope;
12
+ const NOW = Date.parse('2026-11-05T00:00:00Z');
13
+
14
+ function countsHttp() {
15
+ const gets: Array<{ path: string; params: Record<string, unknown> }> = [];
16
+ return {
17
+ gets,
18
+ http: {
19
+ async get<T>(path: string, init?: { params?: Record<string, unknown> }): Promise<T> {
20
+ const params = init?.params ?? {};
21
+ gets.push({ path, params });
22
+ if (params.group_by === 'edge:in_focus,attr.status') {
23
+ return { results: [
24
+ { values: ['a', 'open'], count: 2 },
25
+ { values: ['a', 'done'], count: 1 },
26
+ { values: ['b', 'open'], count: 1 },
27
+ ] } as T;
28
+ }
29
+ return { results: [{ values: ['a'], count: 1 }] } as T;
30
+ },
31
+ },
32
+ };
33
+ }
34
+
35
+ describe('readStandings: never a false zero from a truncated page', () => {
36
+ it('reads EVERY page of the grouped answer: 100 projects x 3 statuses is 300 rows', async () => {
37
+ const focuses = Array.from({ length: 100 }, (_, i) => ({ id: `p${String(i).padStart(3, '0')}`, entity_type: 'focus', name: `P${i}`, created_at: '2026-09-01T00:00:00Z', data: {} }));
38
+ const todos: TenantEntity[] = [];
39
+ const edges: TenantRelationship[] = [];
40
+ focuses.forEach((f, i) => (['open', 'done', 'blocked'] as const).forEach((status, k) => {
41
+ const id = `t${i}-${k}`;
42
+ todos.push({ id, entity_type: 'commitment', name: id, created_at: '2026-09-02T00:00:00Z', data: { status } });
43
+ edges.push({ id: `e${id}`, rel_type: 'in_focus', source: id, target: f.id });
44
+ }));
45
+ const tenant = createFakeTenantHttp({ entities: [...(focuses as TenantEntity[]), ...todos], relationships: edges });
46
+ const out = await readStandings(tenant.http as never, focuses.map((f) => f.id), NOW);
47
+ expect(Object.values(out).every((s) => s.total === 3 && s.done === 1)).toBe(true);
48
+ expect(out.p099).toMatchObject({ total: 3, done: 1 });
49
+ // 300 rows at 200 per page: two pages for the status read, one for overdue.
50
+ expect(tenant.requests.filter((r) => r.path.endsWith('counts'))).toHaveLength(3);
51
+ });
52
+ });
53
+
54
+ describe('readStandings: a page of projects in two grouped reads', () => {
55
+ it('computes total, done and overdue and includes every id asked for', async () => {
56
+ const { http, gets } = countsHttp();
57
+ const out = await readStandings(http, ['a', 'b', 'c'], NOW);
58
+ expect(out).toEqual({
59
+ a: { focusId: 'a', total: 3, done: 1, overdue: 1 },
60
+ b: { focusId: 'b', total: 1, done: 0, overdue: 0 },
61
+ c: { focusId: 'c', total: 0, done: 0, overdue: 0 },
62
+ });
63
+ expect(gets).toHaveLength(2);
64
+ expect(gets[0]).toMatchObject({ path: 'api/v1/entities/counts', params: { type: 'commitment', edge_targets: 'a,b,c', group_by: 'edge:in_focus,attr.status' } });
65
+ expect(gets[1].params).toMatchObject({ 'attr.status': 'open', 'attr.due_at__lte': '2026-11-05T00:00:00.000Z', group_by: 'edge:in_focus' });
66
+ });
67
+
68
+ it('more than 200 projects go out in chunks of 200', async () => {
69
+ const { http, gets } = countsHttp();
70
+ const ids = Array.from({ length: 250 }, (_, i) => `f${i}`);
71
+ const out = await readStandings(http, ids, NOW);
72
+ expect(Object.keys(out)).toHaveLength(250);
73
+ expect(gets).toHaveLength(4);
74
+ });
75
+
76
+ it('no projects, no requests; duplicates are asked once', async () => {
77
+ const { http, gets } = countsHttp();
78
+ expect(await readStandings(http, [], NOW)).toEqual({});
79
+ await readStandings(http, ['a', 'a'], NOW);
80
+ expect(gets[0].params.edge_targets).toBe('a');
81
+ });
82
+
83
+ it('createPlanningApi exposes it as focusStandings with its own type key and path', async () => {
84
+ const { http, gets } = countsHttp();
85
+ const api = createPlanningApi({ http: http as never, scope: SCOPE, typeKeys: { commitment: 'todo' }, paths: { entities: 'v1/e' } });
86
+ await api.focusStandings!(['a'], NOW);
87
+ expect(gets[0]).toMatchObject({ path: 'v1/e/counts', params: { type: 'todo' } });
88
+ });
89
+
90
+ it('standingsFrom ignores a group for a project not on the page', () => {
91
+ expect(standingsFrom(['a'], [{ group: { 'edge:in_focus': 'zzz', 'attr.status': 'open' }, count: 5 }], [])).toEqual({ a: { focusId: 'a', total: 0, done: 0, overdue: 0 } });
92
+ });
93
+ });
94
+
95
+ const page = <T,>(results: T[]) => ({ count: results.length, next: null, previous: null, results, appliedFilters: ['status'] });
96
+ const FOCUS = { id: 'f1', title: 'Crochets', status: 'active', scope: SCOPE } as never;
97
+
98
+ function planning(extra: Partial<PlanningApi>): PlanningApi {
99
+ return { listCommitments: async () => page([]), listFocuses: async () => page([FOCUS]), ...extra } as PlanningApi;
100
+ }
101
+
102
+ describe('PlanningPage standings', () => {
103
+ it('uses ONE batched read for every card and never the per-card path', async () => {
104
+ const focusStanding = vi.fn();
105
+ const focusStandings = vi.fn(async (): Promise<Record<string, FocusStanding>> => ({ f1: { focusId: 'f1', total: 40, done: 12, overdue: 3 } }));
106
+ render(<PlanningPage api={planning({ focusStanding, focusStandings })} scope={SCOPE} now={NOW} />);
107
+ await waitFor(() => expect(screen.getByText(/12 of 40 done/)).toBeInTheDocument());
108
+ expect(focusStandings).toHaveBeenCalledTimes(1);
109
+ expect(focusStanding).not.toHaveBeenCalled();
110
+ });
111
+
112
+ it('falls back to a standing per card on a tenant that predates the endpoint', async () => {
113
+ const focusStandings = vi.fn(async () => { throw new Error('400'); });
114
+ const focusStanding = vi.fn(async (focusId: string): Promise<FocusStanding> => ({ focusId, total: 10, done: 5, overdue: 0 }));
115
+ render(<PlanningPage api={planning({ focusStanding, focusStandings })} scope={SCOPE} now={NOW} />);
116
+ await waitFor(() => expect(screen.getByText(/5 of 10 done/)).toBeInTheDocument());
117
+ expect(focusStanding).toHaveBeenCalledTimes(1);
118
+ });
119
+ });
@@ -171,10 +171,22 @@ export function PlanningPage({
171
171
  let live = true;
172
172
  void (async () => {
173
173
  const loaded = await loadFocuses();
174
- if (!live || !apiRef.current.focusStanding) return;
175
- // Bounded fan-out, and the clock is passed IN so "overdue" is computed
176
- // against the frozen mount time rather than a fresh Date.now() per call.
177
- const standing = apiRef.current.focusStanding.bind(apiRef.current);
174
+ if (!live) return;
175
+ const api = apiRef.current;
176
+ // The clock is passed IN so "overdue" is computed against the frozen mount
177
+ // time rather than a fresh Date.now() per call.
178
+ if (api.focusStandings) {
179
+ // The whole page in two grouped reads. A tenant that predates the
180
+ // endpoint refuses it, and the per-card path below still works.
181
+ try {
182
+ const found = await api.focusStandings(loaded.map((f) => f.id), clock);
183
+ if (!live) return;
184
+ setStandings((prev) => ({ ...prev, ...found }));
185
+ return;
186
+ } catch { /* fall through to one standing per card */ }
187
+ }
188
+ if (!api.focusStanding) return;
189
+ const standing = api.focusStanding.bind(api);
178
190
  for (let i = 0; i < loaded.length && live; i += STANDING_CONCURRENCY) {
179
191
  const slice = loaded.slice(i, i + STANDING_CONCURRENCY);
180
192
  const results = await Promise.all(
@@ -30,6 +30,7 @@
30
30
  * second copy of the graph that will drift; the edge is the declared contract,
31
31
  * so the edge is what is read. The join is cached, bounded and fails soft.
32
32
  */
33
+ import { readStandings } from './standings';
33
34
  import {
34
35
  DEFAULT_PARTICIPANT_EDGES,
35
36
  FOLDER_ROOT,
@@ -1449,6 +1450,10 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1449
1450
  return { focusId, total, done, overdue };
1450
1451
  },
1451
1452
 
1453
+ focusStandings: (focusIds, now) => readStandings(http, focusIds, now ?? Date.now(), {
1454
+ commitmentType: types.commitment, entitiesPath: entities,
1455
+ }),
1456
+
1452
1457
  /**
1453
1458
  * The tenant's real members, for the owner picker — what closes the
1454
1459
  * free-text-owner gap (bd startsim-768w.38.29).
@@ -9,8 +9,8 @@
9
9
  *
10
10
  * Server contract: start-simpli-api `tenant-starter/apps/api/filters.py`.
11
11
  * page, page_size (max 200), search, order=recent|oldest|relevance|[-]attr.<name>,
12
- * type, id, id__in (comma list), external_id, external_id__in (REPEATED param),
13
- * source, party, scope, occurred_after/before, created_after/before,
12
+ * type, type__in (comma list), id, id__in (comma list), external_id, external_id__in (REPEATED param),
13
+ * source, party, scope, occurred_after/before, created_after/before, updated_after,
14
14
  * related_to + related_via/related_direction/related_depth,
15
15
  * unrelated_via + unrelated_direction (rows with NO such edge),
16
16
  * attr.<name>[__op] (op: in gt gte lt lte icontains isnull isblank startswith
@@ -31,6 +31,8 @@ export type EntityOrder =
31
31
  export type AttrValue = string | number | boolean | null | undefined;
32
32
 
33
33
  export interface EntityFilters {
34
+ /** Several types in one read (`type__in`): the newest rows across a Home's types. Use instead of `EntityQuery.type`. */
35
+ typeIn?: string[];
34
36
  id?: string;
35
37
  idIn?: string[];
36
38
  externalId?: string;
@@ -43,6 +45,12 @@ export interface EntityFilters {
43
45
  occurredBefore?: string;
44
46
  createdAfter?: string;
45
47
  createdBefore?: string;
48
+ /**
49
+ * Only rows touched strictly AFTER this instant (`updated_after`): pass back the
50
+ * newest `updated_at` held for a cheap refresh. Deletions are not reported; a
51
+ * client reconciles those with a full read.
52
+ */
53
+ updatedAfter?: string;
46
54
  relatedTo?: string;
47
55
  relatedVia?: string | string[];
48
56
  relatedDirection?: 'out' | 'in' | 'any';
@@ -57,7 +65,8 @@ export interface EntityFilters {
57
65
  }
58
66
 
59
67
  export interface EntityQuery {
60
- type: string;
68
+ /** Omit only with `filters.typeIn`. */
69
+ type?: string;
61
70
  search?: string;
62
71
  order?: EntityOrder;
63
72
  filters?: EntityFilters;
@@ -90,6 +99,7 @@ function put(out: Record<string, unknown>, key: string, value: unknown): void {
90
99
  /** Filters that are common to the list and to facets. */
91
100
  export function entityFilterParams(filters: EntityFilters = {}): Record<string, unknown> {
92
101
  const out: Record<string, unknown> = {};
102
+ if (filters.typeIn?.length) out.type__in = filters.typeIn.join(',');
93
103
  put(out, 'id', filters.id);
94
104
  if (filters.idIn?.length) out.id__in = idList('id__in', filters.idIn);
95
105
  put(out, 'external_id', filters.externalId);
@@ -106,6 +116,7 @@ export function entityFilterParams(filters: EntityFilters = {}): Record<string,
106
116
  put(out, 'occurred_before', filters.occurredBefore);
107
117
  put(out, 'created_after', filters.createdAfter);
108
118
  put(out, 'created_before', filters.createdBefore);
119
+ put(out, 'updated_after', filters.updatedAfter);
109
120
  if (filters.relatedTo) {
110
121
  out.related_to = filters.relatedTo;
111
122
  // Companions only ride along with a target: alone the server ignores them.
@@ -138,7 +149,9 @@ export function attrParams(attr: EntityQuery['attr'] = {}): Record<string, unkno
138
149
 
139
150
  /** `EntityQuery` -> the query string parameters of `GET api/v1/entities/`. */
140
151
  export function entityParams(query: EntityQuery): Record<string, unknown> {
141
- const out: Record<string, unknown> = { type: query.type, page: query.page ?? 1 };
152
+ const out: Record<string, unknown> = {};
153
+ put(out, 'type', query.type);
154
+ out.page = query.page ?? 1;
142
155
  if (query.pageSize) out.page_size = Math.min(Math.max(1, query.pageSize), MAX_PAGE_SIZE);
143
156
  const search = query.search?.trim();
144
157
  if (search) out.search = search.slice(0, TEXT_FILTER_MAX);
@@ -164,6 +177,56 @@ export function facetParams(query: FacetQuery): Record<string, unknown> {
164
177
  return out;
165
178
  }
166
179
 
180
+ /**
181
+ * `GET api/v1/entities/counts/`: how many rows, grouped by up to two keys - ONE
182
+ * request for a Home tile row, a filter badge row or a page of project cards.
183
+ * Every list filter narrows it exactly as it narrows the list.
184
+ *
185
+ * Group keys: `type`, `attr.<name>`, `edge:<rel_type>[:out|in]` (the id at the
186
+ * other end of the row's edge; the row is the source for `out`, the default).
187
+ * `edgeTargets` bounds an edge key to one page of far-end ids.
188
+ */
189
+ export type CountGroup = 'type' | `attr.${string}` | `edge:${string}`;
190
+
191
+ export interface CountQuery extends Omit<EntityQuery, 'order'> {
192
+ groupBy: CountGroup[];
193
+ edgeTargets?: string[];
194
+ }
195
+
196
+ /** A group value: an id, a status, a type key; `null` is "none" (unfiled, no status). */
197
+ export type CountValue = string | number | boolean | null;
198
+
199
+ export interface CountRow {
200
+ /** Keyed by the group token the query asked for, e.g. `{ 'edge:in_focus': 'f1', 'attr.status': 'open' }`. */
201
+ group: Record<string, CountValue>;
202
+ count: number;
203
+ }
204
+
205
+ /**
206
+ * What the server sends: values by POSITION (`group_by` order), never keyed by
207
+ * token. A group token is data, and the apps' API client camelCases response
208
+ * KEYS (`edge:in_focus` -> `edge:inFocus`), which would make every lookup miss.
209
+ */
210
+ export interface WireCountRow { values: CountValue[]; count: number }
211
+
212
+ /** Wire rows -> rows keyed by the tokens the CALLER asked for, in that order. */
213
+ export function toCountRows(groupBy: CountGroup[], rows: WireCountRow[] | undefined): CountRow[] {
214
+ return (rows ?? []).map((row) => ({
215
+ group: Object.fromEntries(groupBy.map((token, i) => [token, row.values?.[i] ?? null])),
216
+ count: row.count,
217
+ }));
218
+ }
219
+
220
+ export function countParams(query: CountQuery): Record<string, unknown> {
221
+ if (query.groupBy.length < 1 || query.groupBy.length > 2) {
222
+ throw new Error('groupBy: name one or two keys.');
223
+ }
224
+ const out = entityParams({ ...query, order: undefined });
225
+ out.group_by = query.groupBy.join(',');
226
+ if (query.edgeTargets?.length) out.edge_targets = idList('edge_targets', query.edgeTargets);
227
+ return out;
228
+ }
229
+
167
230
  export interface RelationshipListQuery {
168
231
  source?: string;
169
232
  target?: string;
@@ -262,11 +262,13 @@ export type {
262
262
  VoiceTranscriber,
263
263
  } from './voice';
264
264
 
265
+ export { readStandings, standingsFrom } from './standings';
266
+ export type { StandingsOptions } from './standings';
265
267
  export {
266
- attrParams, entityFilterParams, entityParams, facetParams, reconcileFilters, relationshipParams,
268
+ attrParams, countParams, entityFilterParams, entityParams, facetParams, reconcileFilters, relationshipParams,
267
269
  sentFilterNames, toEntityPage,
268
270
  } from './entity-query';
269
271
  export type {
270
- AttrValue, EntityFilters, EntityOrder, EntityPage, EntityQuery, FacetQuery, FilterReport,
272
+ AttrValue, CountGroup, CountQuery, CountRow, EntityFilters, EntityOrder, EntityPage, EntityQuery, FacetQuery, FilterReport,
271
273
  FilterVerdict, RelationshipListQuery,
272
274
  } from './entity-query';
@@ -0,0 +1,75 @@
1
+ /**
2
+ * "12 of 40 done, 3 overdue" for a PAGE of projects, from two grouped reads of
3
+ * `GET api/v1/entities/counts/` (bd startsim-09zue) - however many projects the
4
+ * page holds. It replaces `focusStanding`'s three count-only reads PER project
5
+ * (a 100-project web page was 300 requests). The web and native Planning screens
6
+ * share this one reader.
7
+ *
8
+ * `all` to-dos per project x status -> total, done
9
+ * `overdue` open to-dos past due, per project -> overdue
10
+ *
11
+ * Every id asked for is in the result, zeros when the project holds nothing, so a
12
+ * card never waits on a count that will not come.
13
+ */
14
+ import { MAX_PAGE_SIZE, countParams, toCountRows, type CountQuery, type CountRow, type WireCountRow } from './entity-query';
15
+ import type { CorpusHttp } from './client';
16
+ import type { FocusStanding } from './types';
17
+ import { MAX_ID_LIST } from './entities';
18
+
19
+ const IN_FOCUS_KEY = 'edge:in_focus';
20
+ const STATUS_KEY = 'attr.status';
21
+
22
+ export interface StandingsOptions {
23
+ /** The tenant's commitment type key (default `commitment`). */
24
+ commitmentType?: string;
25
+ entitiesPath?: string;
26
+ }
27
+
28
+ export function standingsFrom(focusIds: string[], all: CountRow[], overdue: CountRow[]): Record<string, FocusStanding> {
29
+ const out: Record<string, FocusStanding> = {};
30
+ for (const focusId of focusIds) out[focusId] = { focusId, total: 0, done: 0, overdue: 0 };
31
+ for (const row of all) {
32
+ const target = out[String(row.group[IN_FOCUS_KEY])];
33
+ if (!target) continue;
34
+ target.total += row.count;
35
+ if (row.group[STATUS_KEY] === 'done') target.done += row.count;
36
+ }
37
+ for (const row of overdue) {
38
+ const target = out[String(row.group[IN_FOCUS_KEY])];
39
+ if (target) target.overdue += row.count;
40
+ }
41
+ return out;
42
+ }
43
+
44
+ export async function readStandings(
45
+ http: Pick<CorpusHttp, 'get'>,
46
+ focusIds: string[],
47
+ now: number,
48
+ options: StandingsOptions = {},
49
+ ): Promise<Record<string, FocusStanding>> {
50
+ const ids = [...new Set(focusIds)];
51
+ if (!ids.length) return {};
52
+ const path = `${options.entitiesPath ?? 'api/v1/entities'}/counts`;
53
+ const type = options.commitmentType ?? 'commitment';
54
+ const asOf = new Date(now).toISOString();
55
+ // EVERY page of a grouped read: a chunk of ids x their statuses can exceed one
56
+ // page, and a row that is not read becomes a false zero on a project card.
57
+ const rows = async (query: CountQuery): Promise<CountRow[]> => {
58
+ const out: CountRow[] = [];
59
+ for (let page = 1; ; page += 1) {
60
+ const body = await http.get<{ results?: WireCountRow[]; next?: string | null }>(path, { params: countParams({ ...query, page }) });
61
+ out.push(...toCountRows(query.groupBy, body.results));
62
+ if (!body.next) return out;
63
+ }
64
+ };
65
+ const chunks: string[][] = [];
66
+ for (let i = 0; i < ids.length; i += MAX_ID_LIST) chunks.push(ids.slice(i, i + MAX_ID_LIST));
67
+ const parts = await Promise.all(chunks.map(async (edgeTargets) => {
68
+ const [all, overdue] = await Promise.all([
69
+ rows({ type, groupBy: [IN_FOCUS_KEY, STATUS_KEY], edgeTargets, pageSize: MAX_PAGE_SIZE }),
70
+ rows({ type, groupBy: [IN_FOCUS_KEY], edgeTargets, pageSize: MAX_PAGE_SIZE, attr: { status: 'open', due_at__lte: asOf } }),
71
+ ]);
72
+ return standingsFrom(edgeTargets, all, overdue);
73
+ }));
74
+ return Object.assign({}, ...parts);
75
+ }
@@ -1373,6 +1373,12 @@ export interface PlanningApi extends CommitmentApi {
1373
1373
  listChildFocuses?(focusId: string): Promise<CorpusPage<Focus>>;
1374
1374
  /** Counts for one focus, from `count` alone — no row bodies cross the wire. */
1375
1375
  focusStanding?(focusId: string, now?: number): Promise<FocusStanding>;
1376
+ /**
1377
+ * Counts for a whole PAGE of projects in two grouped reads (`entities/counts`),
1378
+ * keyed by focus id. Prefer it over calling `focusStanding` per card; a tenant
1379
+ * that predates the endpoint rejects it and the caller falls back.
1380
+ */
1381
+ focusStandings?(focusIds: string[], now?: number): Promise<Record<string, FocusStanding>>;
1376
1382
  /** The tenant's real members, for the owner picker. Absent when the fork is
1377
1383
  * not wired to central, in which case owners stay free text. */
1378
1384
  listMembers?(): Promise<Array<{ sub: string; email: string; name?: string }>>;
@@ -0,0 +1,82 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { countParams } from '../../../corpus/entity-query';
3
+ import { createFakeNativeCorpusApi } from '../fake';
4
+ import { countsBy } from '../counts';
5
+
6
+ describe('countParams: the grouped-count query spelled for the wire', () => {
7
+ it('spells group_by, edge targets and the shared list filters', () => {
8
+ expect(countParams({
9
+ type: 'commitment', groupBy: ['edge:in_focus', 'attr.status'], edgeTargets: ['f1', 'f2'],
10
+ attr: { status__in: ['open', 'blocked'] }, filters: { updatedAfter: '2026-11-01T00:00:00Z' },
11
+ })).toEqual({
12
+ type: 'commitment', group_by: 'edge:in_focus,attr.status', edge_targets: 'f1,f2',
13
+ 'attr.status__in': 'open,blocked', updated_after: '2026-11-01T00:00:00Z', page: 1,
14
+ });
15
+ });
16
+ it('refuses zero or more than two keys before it reaches the server', () => {
17
+ expect(() => countParams({ groupBy: [] })).toThrow(/one or two/);
18
+ expect(() => countParams({ groupBy: ['type', 'attr.a', 'attr.b'] })).toThrow(/one or two/);
19
+ });
20
+ it('typeIn rides as type__in', () => {
21
+ expect(countParams({ groupBy: ['type'], filters: { typeIn: ['a', 'b'] } })).toMatchObject({ type__in: 'a,b' });
22
+ });
23
+ });
24
+
25
+ describe('entities.counts over the fake tenant', () => {
26
+ it('rows arrive by position and are keyed by the tokens the caller asked for, in order', async () => {
27
+ const api = createFakeNativeCorpusApi();
28
+ const page = await api.entities.counts({ type: 'commitment', groupBy: ['edge:in_focus', 'attr.status'] });
29
+ const first = page.items[0];
30
+ expect(Object.keys(first.group)).toEqual(['edge:in_focus', 'attr.status']);
31
+ // the wire never keys data: a camelCasing client cannot break the lookup
32
+ const wire = await api.http.get<{ results: Array<Record<string, unknown>>; group_by: string[] }>('api/v1/entities/counts', { params: { type: 'commitment', group_by: 'edge:in_focus,attr.status' } });
33
+ expect(wire.group_by).toEqual(['edge:in_focus', 'attr.status']);
34
+ expect(Object.keys(wire.results[0]).sort()).toEqual(['count', 'values']);
35
+ });
36
+
37
+ it('one read gives the count per type', async () => {
38
+ const api = createFakeNativeCorpusApi();
39
+ const page = await api.entities.counts({ groupBy: ['type'] });
40
+ expect(countsBy(page.items, 'type')).toEqual({ commitment: 6, focus: 3, source_document: 3 });
41
+ expect(page.appliedFilters).toContain('group_by');
42
+ expect(api.tenant.requests.filter((r) => r.path.includes('counts'))).toHaveLength(1);
43
+ });
44
+ it('groups to-dos per project, keeping the unfiled bucket under null', async () => {
45
+ const api = createFakeNativeCorpusApi();
46
+ const page = await api.entities.counts({ type: 'commitment', groupBy: ['edge:in_focus'] });
47
+ expect(countsBy(page.items, 'edge:in_focus')).toEqual({ f287: 3, fma: 1, '': 2 });
48
+ });
49
+ it('edgeTargets bounds the answer to the ids asked', async () => {
50
+ const api = createFakeNativeCorpusApi();
51
+ const page = await api.entities.counts({ type: 'commitment', groupBy: ['edge:in_focus'], edgeTargets: ['fma'] });
52
+ expect(countsBy(page.items, 'edge:in_focus')).toEqual({ fma: 1 });
53
+ });
54
+ });
55
+
56
+ describe('entities.list: typeIn and updatedAfter', () => {
57
+ it('one read spans several types', async () => {
58
+ const api = createFakeNativeCorpusApi();
59
+ const page = await api.entities.list({ type: undefined as never, filters: { typeIn: ['commitment', 'focus'] }, order: 'recent' });
60
+ expect(new Set(page.items.map((e) => e.entity_type))).toEqual(new Set(['commitment', 'focus']));
61
+ expect(page.appliedFilters).toContain('type__in');
62
+ });
63
+ });
64
+
65
+ describe('standings: a page of project cards in two reads', () => {
66
+ it('total, done and overdue per project from grouped counts', async () => {
67
+ const api = createFakeNativeCorpusApi();
68
+ const before = api.tenant.requests.length;
69
+ const standings = await api.standings(['f287', 'fma', 'fdbg'], Date.parse('2026-11-05T00:00:00Z'));
70
+ expect(api.tenant.requests.length - before).toBe(2);
71
+ expect(standings).toEqual({
72
+ f287: { focusId: 'f287', total: 3, done: 0, overdue: 1 },
73
+ fma: { focusId: 'fma', total: 1, done: 0, overdue: 0 },
74
+ fdbg: { focusId: 'fdbg', total: 0, done: 0, overdue: 0 },
75
+ });
76
+ });
77
+ it('no ids, no requests', async () => {
78
+ const api = createFakeNativeCorpusApi();
79
+ expect(await api.standings([], 0)).toEqual({});
80
+ expect(api.tenant.requests).toHaveLength(0);
81
+ });
82
+ });
@@ -0,0 +1,37 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { displaysFrom, resolveDisplay } from '../display';
3
+ import { createFakeNativeCorpusApi } from '../fake';
4
+
5
+ const todo = { id: 't1', entity_type: 'todo', name: 'Call Megan', data: { owner: 'Quinn', due_at: '2026-11-05', status: 'blocked' } };
6
+ const config = { title: 'name', subtitle: 'owner', date: 'due_at', status: 'status', tones: { blocked: 'bad', done: 'good' }, icon: 'check-circle' } as const;
7
+
8
+ describe('resolveDisplay', () => {
9
+ it('reads title, subtitle, date, status tone and icon from the declaration', () => {
10
+ expect(resolveDisplay(config, todo)).toEqual({
11
+ title: 'Call Megan', subtitle: 'Quinn', date: '2026-11-05', status: { value: 'blocked', tone: 'bad' }, icon: 'check-circle',
12
+ });
13
+ });
14
+ it('a type that declares nothing reads as its name', () => {
15
+ expect(resolveDisplay(undefined, todo)).toEqual({ title: 'Call Megan', subtitle: null, date: null, status: null, icon: null });
16
+ });
17
+ it('an unmapped status is neutral and a missing attribute is null, never "undefined"', () => {
18
+ expect(resolveDisplay(config, { ...todo, data: { status: 'weird' } })).toMatchObject({ subtitle: null, date: null, status: { value: 'weird', tone: 'neutral' } });
19
+ });
20
+ it('falls back to the external id then the id for a nameless row', () => {
21
+ expect(resolveDisplay(undefined, { id: 'x', external_id: 'ext:1', name: '' }).title).toBe('ext:1');
22
+ expect(resolveDisplay(undefined, { id: 'x' }).title).toBe('x');
23
+ });
24
+ });
25
+
26
+ describe('displaysFrom / api.schema.displays', () => {
27
+ it('keeps only the types that declare a display', () => {
28
+ expect(displaysFrom([{ key: 'a', config: { display: { title: 'name' } } }, { key: 'b', config: {} }, { key: 'c' }])).toEqual({ a: { title: 'name' } });
29
+ });
30
+ it('reads the tenant schema once', async () => {
31
+ const api = createFakeNativeCorpusApi();
32
+ const first = await api.schema.displays();
33
+ expect(first.commitment).toMatchObject({ status: 'status' });
34
+ await api.schema.displays();
35
+ expect(api.tenant.requests.filter((r) => r.path.includes('schema/types'))).toHaveLength(1);
36
+ });
37
+ });
@@ -16,9 +16,13 @@ import { createPlanningApi, type CreateCorpusApiOptions } from '../../corpus/cli
16
16
  import { isRecord, notFound } from '../../corpus/client';
17
17
  import type { TenantEntity, TenantFacetRow, TenantRelationship } from '../../corpus/entities';
18
18
  import {
19
- entityParams, facetParams, relationshipParams, toEntityPage,
20
- type EntityPage, type EntityQuery, type FacetQuery, type RelationshipListQuery,
19
+ MAX_PAGE_SIZE, countParams, entityParams, facetParams, relationshipParams, toCountRows, toEntityPage,
20
+ type CountQuery, type CountRow, type WireCountRow, type EntityPage, type EntityQuery, type FacetQuery, type RelationshipListQuery,
21
21
  } from '../../corpus/entity-query';
22
+ import { DEFAULT_TYPE_KEYS } from '../../corpus/entities';
23
+ import type { FocusStanding } from '../../corpus/types';
24
+ import { readStandings } from '../../corpus/standings';
25
+ import { displaysFrom, type SchemaTypeRow, type TypeDisplayConfig } from './display';
22
26
  import type {
23
27
  Commitment, CommitmentQuery, CommitmentStatus, CorpusAskApi, CorpusPage, CorpusScope,
24
28
  DocumentQuery, Focus, FocusQuery, SourceDocument,
@@ -52,7 +56,19 @@ export interface NativeCorpusApi {
52
56
  list(query: EntityQuery): Promise<EntityPage<TenantEntity>>;
53
57
  get(id: string): Promise<TenantEntity>;
54
58
  facets(query: FacetQuery): Promise<EntityPage<TenantFacetRow>>;
59
+ /** Grouped counts (`entities/counts/`): one read for a row of tiles, badges or cards. */
60
+ counts(query: CountQuery): Promise<EntityPage<CountRow>>;
55
61
  };
62
+ /** The tenant's own schema, for generic rendering. */
63
+ schema: {
64
+ /** `config.display` per type that declares one (see `resolveDisplay`). Read once, then cached. */
65
+ displays(): Promise<Record<string, TypeDisplayConfig>>;
66
+ };
67
+ /**
68
+ * Total / done / overdue to-dos for a PAGE of projects, in two reads however
69
+ * many projects there are. Every id is present in the result, zeros if empty.
70
+ */
71
+ standings(focusIds: string[], now?: number): Promise<Record<string, FocusStanding>>;
56
72
  relationships: { list(query: RelationshipListQuery): Promise<EntityPage<TenantRelationship>> };
57
73
  /** The web composers' api objects, unchanged: Library (documents), Tracker (commitments), Planning (focuses). */
58
74
  corpus: CorpusApi & PlanningApi;
@@ -102,6 +118,7 @@ export function createNativeCorpusApi(deps: NativeCorpusDeps): NativeCorpusApi {
102
118
  const scope = deps.scope ?? ({} as CorpusScope);
103
119
  const corpus = createPlanningApi({ http, scope, ...deps.corpus }) as unknown as CorpusApi & PlanningApi;
104
120
 
121
+ let displays: Promise<Record<string, TypeDisplayConfig>> | null = null;
105
122
  const api: NativeCorpusApi = {
106
123
  http,
107
124
  scope,
@@ -119,7 +136,23 @@ export function createNativeCorpusApi(deps: NativeCorpusDeps): NativeCorpusApi {
119
136
  const params = facetParams(query);
120
137
  return toEntityPage(params, await http.get<{ results?: TenantFacetRow[] }>(`${ENTITIES}/facets`, { params }), (row: TenantFacetRow) => row);
121
138
  },
139
+ async counts(query) {
140
+ const params = countParams(query);
141
+ const page = toEntityPage(params, await http.get<{ results?: WireCountRow[] }>(`${ENTITIES}/counts`, { params }), (row: WireCountRow) => row);
142
+ return { ...page, items: toCountRows(query.groupBy, page.items) };
143
+ },
144
+ },
145
+ schema: {
146
+ displays() {
147
+ displays ??= http.get<{ results?: SchemaTypeRow[] }>('api/v1/schema/types', { params: { page_size: MAX_PAGE_SIZE } })
148
+ .then((page) => displaysFrom(page.results ?? []))
149
+ .catch((e) => { displays = null; throw e; });
150
+ return displays;
151
+ },
122
152
  },
153
+ standings: (focusIds, now = Date.now()) => readStandings(http, focusIds, now, {
154
+ commitmentType: { ...DEFAULT_TYPE_KEYS, ...deps.corpus?.typeKeys }.commitment,
155
+ }),
123
156
  relationships: {
124
157
  async list(query) {
125
158
  const params = relationshipParams(query);
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Reading grouped counts (`entities.counts`): the figures a tile, a badge or a
3
+ * project card shows, from ONE request instead of one per number.
4
+ */
5
+ import type { CountRow } from '../../corpus/entity-query';
6
+
7
+ /** `{ [value]: count }` for one group key; a null group (unfiled, no status) is keyed `''`. */
8
+ export function countsBy(rows: CountRow[], token: string): Record<string, number> {
9
+ const out: Record<string, number> = {};
10
+ for (const row of rows) {
11
+ const key = row.group[token];
12
+ const name = key === null || key === undefined ? '' : String(key);
13
+ out[name] = (out[name] ?? 0) + row.count;
14
+ }
15
+ return out;
16
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * How a row of a type reads, from the tenant's own schema (`config.display` on
3
+ * `GET api/v1/schema/types/`, bd startsim-cmpai) - so ONE generic row and detail
4
+ * renderer serves a type the client has never heard of. A type that declares
5
+ * nothing reads as its name alone.
6
+ *
7
+ * Keys are one lowercase word because the apps' API client camelCases response
8
+ * keys; attribute names and status values travel as VALUES.
9
+ */
10
+ import type { TenantEntity } from '../../corpus/entities';
11
+
12
+ export type DisplayTone = 'good' | 'warn' | 'bad' | 'info' | 'neutral';
13
+
14
+ /** The declaration as stored on `EntityTypeDef.config.display`. */
15
+ export interface TypeDisplayConfig {
16
+ title?: string;
17
+ subtitle?: string;
18
+ date?: string;
19
+ status?: string;
20
+ tones?: Record<string, DisplayTone>;
21
+ icon?: string;
22
+ }
23
+
24
+ /** One row, resolved: what a generic list row / detail header shows. */
25
+ export interface RowDisplay {
26
+ title: string;
27
+ subtitle: string | null;
28
+ date: string | null;
29
+ status: { value: string; tone: DisplayTone } | null;
30
+ icon: string | null;
31
+ }
32
+
33
+ export interface SchemaTypeRow { key: string; label?: string; config?: { display?: TypeDisplayConfig } | null }
34
+
35
+ const dataOf = (e: TenantEntity): Record<string, unknown> => (e.data ?? {}) as Record<string, unknown>;
36
+
37
+ function text(entity: TenantEntity, attribute: string | undefined): string | null {
38
+ if (!attribute) return null;
39
+ const raw = attribute === 'name' ? entity.name : dataOf(entity)[attribute];
40
+ if (raw === undefined || raw === null || raw === '') return null;
41
+ return String(raw);
42
+ }
43
+
44
+ /** `config.display` (may be absent) + a row -> what to show. */
45
+ export function resolveDisplay(config: TypeDisplayConfig | undefined | null, entity: TenantEntity): RowDisplay {
46
+ const title = text(entity, config?.title) ?? (entity.name || String(entity.external_id ?? entity.externalId ?? entity.id));
47
+ const status = text(entity, config?.status);
48
+ return {
49
+ title,
50
+ subtitle: text(entity, config?.subtitle),
51
+ date: text(entity, config?.date),
52
+ status: status ? { value: status, tone: config?.tones?.[status] ?? 'neutral' } : null,
53
+ icon: config?.icon ?? null,
54
+ };
55
+ }
56
+
57
+ /** `schema/types` rows -> `{ [type key]: declaration }` for the types that declare one. */
58
+ export function displaysFrom(rows: SchemaTypeRow[]): Record<string, TypeDisplayConfig> {
59
+ const out: Record<string, TypeDisplayConfig> = {};
60
+ for (const row of rows) if (row.config?.display) out[row.key] = row.config.display;
61
+ return out;
62
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The fake tenant's `GET api/v1/entities/counts` - the same contract as
3
+ * `tenant-starter/apps/api/counts.py`: group the (already filtered) rows by up to
4
+ * two keys - `type`, `attr.<name>`, `edge:<rel>[:out|in]` - and count them.
5
+ * `edge_targets` narrows an edge key to those far-end ids. Rows are `{values, count}` by
6
+ * POSITION with `group_by` echoed, never keyed by token (the apps' client camelCases keys).
7
+ */
8
+ import type { TenantEntity, TenantRelationship } from '../../corpus/entities';
9
+
10
+ type Params = Record<string, unknown>;
11
+
12
+ const dataOf = (e: TenantEntity): Record<string, unknown> => (e.data ?? {}) as Record<string, unknown>;
13
+ const typeOf = (e: TenantEntity) => String(e.entity_type ?? e.entityType ?? '');
14
+ const ids = (v: unknown) => String(v ?? '').split(',').map((s) => s.trim()).filter(Boolean);
15
+
16
+ function keysFor(token: string, entity: TenantEntity, edges: TenantRelationship[], targets: string[] | null): Array<string | number | boolean | null> {
17
+ if (token === 'type') return [typeOf(entity)];
18
+ if (token.startsWith('attr.')) {
19
+ const v = dataOf(entity)[token.slice(5)];
20
+ return [v === undefined || v === '' ? null : (v as string | number | boolean)];
21
+ }
22
+ const [, rel, direction = 'out'] = token.split(':');
23
+ const far = edges
24
+ .filter((r) => String(r.rel_type ?? r.relType) === rel && String(direction === 'out' ? r.source : r.target) === String(entity.id))
25
+ .map((r) => String(direction === 'out' ? r.target : r.source))
26
+ .filter((id) => !targets || targets.includes(id));
27
+ if (targets) return far;
28
+ return far.length ? far : [null];
29
+ }
30
+
31
+ /** `rows` are the entities that passed the list's filters. */
32
+ export function groupCounts(rows: TenantEntity[], edges: TenantRelationship[], params: Params) {
33
+ const tokens = ids(params.group_by);
34
+ if (!tokens.length || tokens.length > 2) throw Object.assign(new Error('group_by: name one or two keys'), { status: 400 });
35
+ const known = (t: string) => t === 'type' || t.startsWith('attr.') || t.startsWith('edge:');
36
+ if (!tokens.every(known)) throw Object.assign(new Error(`group_by: unknown key in ${tokens.join(',')}`), { status: 400 });
37
+ const targets = params.edge_targets !== undefined ? ids(params.edge_targets) : null;
38
+ const hasEdge = tokens.some((t) => t.startsWith('edge:'));
39
+ const tally = new Map<string, { values: Array<string | number | boolean | null>; count: number }>();
40
+ for (const entity of rows) {
41
+ let combos: Array<Array<string | number | boolean | null>> = [[]];
42
+ for (const token of tokens) {
43
+ const keys = keysFor(token, entity, edges, token.startsWith('edge:') ? targets : null);
44
+ combos = combos.flatMap((c) => keys.map((k) => [...c, k]));
45
+ }
46
+ for (const combo of combos) {
47
+ const id = JSON.stringify(combo);
48
+ const hit = tally.get(id) ?? { values: combo, count: 0 };
49
+ hit.count += 1;
50
+ tally.set(id, hit);
51
+ }
52
+ }
53
+ const order = (a: unknown, b: unknown) => (a === null ? 1 : b === null ? -1 : String(a).localeCompare(String(b)));
54
+ const results = [...tally.values()].sort((a, b) => {
55
+ for (let i = 0; i < tokens.length; i += 1) { const c = order(a.values[i], b.values[i]); if (c) return c; }
56
+ return 0;
57
+ });
58
+ return { tokens, results, applied: ['group_by', ...(targets && hasEdge ? ['edge_targets'] : [])], ignored: targets && !hasEdge ? ['edge_targets'] : [] };
59
+ }
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import type { TenantEntity, TenantRelationship } from '../../corpus/entities';
12
12
  import { MAX_PAGE_SIZE } from '../../corpus/entity-query';
13
+ import { groupCounts } from './fake-counts';
13
14
  import { REFRESH_ROW_TITLE } from './fake-scenarios';
14
15
  import type { AuthorizedHttp } from '../voice/http';
15
16
 
@@ -22,6 +23,8 @@ export interface FakeTenantOptions {
22
23
  /** Filter names this "tenant" does not understand: reported ignored, never applied. */
23
24
  unsupported?: string[];
24
25
  onRequest?: (method: string, path: string, params: Params) => void;
26
+ /** Rows of `schema/types` (default: the sample commitment display). */
27
+ schemaTypes?: Array<{ key: string; label?: string; config?: Record<string, unknown> }>;
25
28
  /** Each entity list read a second time (same query) also returns one new row, so a refresh is visible. */
26
29
  newRowOnReread?: boolean;
27
30
  }
@@ -84,6 +87,11 @@ function pageOf<T>(rows: T[], params: Params, fallback: number) {
84
87
  };
85
88
  }
86
89
 
90
+ const SAMPLE_SCHEMA_TYPES = [
91
+ { key: 'commitment', label: 'To-do', config: { display: { title: 'title', subtitle: 'owner_name', date: 'due_at', status: 'status', tones: { done: 'good', blocked: 'bad', open: 'info' }, icon: 'check-circle' } } },
92
+ { key: 'focus', label: 'Project', config: {} },
93
+ ];
94
+
87
95
  export interface FakeTenant {
88
96
  http: AuthorizedHttp;
89
97
  requests: Array<{ method: string; path: string; params: Params }>;
@@ -97,7 +105,7 @@ export function createFakeTenantHttp(options: FakeTenantOptions = {}): FakeTenan
97
105
  const requests: Array<{ method: string; path: string; params: Params }> = [];
98
106
  let seq = 0;
99
107
 
100
- function list(params: Params) {
108
+ function list(params: Params, unpaged = false) {
101
109
  const applied: string[] = [];
102
110
  const ignored: string[] = [];
103
111
  const ok = (key: string) => key in params && !unsupported.has(key);
@@ -105,6 +113,7 @@ export function createFakeTenantHttp(options: FakeTenantOptions = {}): FakeTenan
105
113
  const narrow = (key: string, test: (e: TenantEntity) => boolean) => { rows = rows.filter(test); applied.push(key); };
106
114
 
107
115
  if (ok('type')) narrow('type', (e) => typeOf(e) === String(params.type));
116
+ if (ok('type__in')) { const w = asList(params.type__in); narrow('type__in', (e) => w.includes(typeOf(e))); }
108
117
  if (ok('id')) narrow('id', (e) => String(e.id) === String(params.id));
109
118
  if (ok('id__in')) { const w = asList(params.id__in); narrow('id__in', (e) => w.includes(String(e.id))); }
110
119
  if (ok('external_id')) narrow('external_id', (e) => String(e.external_id ?? e.externalId) === String(params.external_id));
@@ -116,6 +125,10 @@ export function createFakeTenantHttp(options: FakeTenantOptions = {}): FakeTenan
116
125
  ] as const) {
117
126
  if (ok(key)) narrow(key, (e) => { const v = String(dataOf(e)[field] ?? ''); return v !== '' && (after ? v >= String(params[key]) : v <= String(params[key])); });
118
127
  }
128
+ if (ok('updated_after')) {
129
+ const stamp = (e: TenantEntity) => String((e as { updated_at?: string }).updated_at ?? created(e));
130
+ narrow('updated_after', (e) => stamp(e) > String(params.updated_after));
131
+ }
119
132
  for (const [key, after] of [['created_after', true], ['created_before', false]] as const) {
120
133
  if (ok(key)) narrow(key, (e) => (after ? created(e) >= String(params[key]) : created(e) <= String(params[key])));
121
134
  }
@@ -188,11 +201,12 @@ export function createFakeTenantHttp(options: FakeTenantOptions = {}): FakeTenan
188
201
  if (NOT_FILTERS.has(key) || applied.includes(key) || ignored.includes(key)) continue;
189
202
  ignored.push(key);
190
203
  }
191
- return { ...pageOf(rows, params, pageSize), applied_filters: applied, ignored_filters: ignored };
204
+ const everything = unpaged ? { count: rows.length, next: null, previous: null, results: rows } : pageOf(rows, params, pageSize);
205
+ return { ...everything, applied_filters: applied, ignored_filters: ignored };
192
206
  }
193
207
 
194
208
  function facets(params: Params) {
195
- const base = list({ ...params, attr: undefined, under: undefined, page: 1, page_size: MAX_PAGE_SIZE * 1000 } as Params);
209
+ const base = list({ ...params, attr: undefined, under: undefined } as Params, true);
196
210
  // Re-run the row filter over every page: `list` is paged, so ask for it all in-process.
197
211
  const rows = (base as { results: TenantEntity[] }).results;
198
212
  const attr = String(params.attr ?? '');
@@ -218,6 +232,18 @@ export function createFakeTenantHttp(options: FakeTenantOptions = {}): FakeTenan
218
232
  return { ...pageOf(results, params, pageSize), applied_filters: [...base.applied_filters.filter((k) => k !== 'order'), 'attr', 'under'], ignored_filters: [] as string[] };
219
233
  }
220
234
 
235
+ function counts(params: Params) {
236
+ const { group_by: _g, edge_targets: _t, ...filters } = params;
237
+ const base = list(filters as Params, true);
238
+ const grouped = groupCounts((base as { results: TenantEntity[] }).results, relationships, params);
239
+ return {
240
+ ...pageOf(grouped.results, params, pageSize),
241
+ group_by: grouped.tokens,
242
+ applied_filters: [...base.applied_filters.filter((k) => k !== 'order'), ...grouped.applied],
243
+ ignored_filters: [...base.ignored_filters, ...grouped.ignored],
244
+ };
245
+ }
246
+
221
247
  function edges(params: Params) {
222
248
  const applied: string[] = [];
223
249
  const ignored: string[] = [];
@@ -262,6 +288,8 @@ export function createFakeTenantHttp(options: FakeTenantOptions = {}): FakeTenan
262
288
  const p = path.replace(/^\/+|\/+$/g, '');
263
289
  if (p === 'api/v1/relationships') return edges(params) as T;
264
290
  if (p === 'api/v1/entities/facets') return facets(params) as T;
291
+ if (p === 'api/v1/entities/counts') return counts(params) as T;
292
+ if (p === 'api/v1/schema/types') return pageOf(options.schemaTypes ?? SAMPLE_SCHEMA_TYPES, params, pageSize) as T;
265
293
  if (p === 'api/v1/entities') return reread(params, list(params)) as T;
266
294
  const detail = /^api\/v1\/entities\/(.+)$/.exec(p);
267
295
  if (detail) {
@@ -10,17 +10,16 @@ const types = [
10
10
  ];
11
11
 
12
12
  describe('home controller: what has come in', () => {
13
- it('one count per type, read from the server COUNT of a one-row page', async () => {
13
+ it('every type count comes from ONE grouped read', async () => {
14
14
  const api = createFakeNativeCorpusApi();
15
15
  const c = createHomeController({ api, types, now: () => NOW });
16
16
  await c.load();
17
17
  const s = c.getState();
18
18
  expect(s.metrics.map((m) => [m.label, m.count])).toEqual([['To-dos', 6], ['Documents', 3], ['Projects', 3]]);
19
- const counts = api.tenant.requests.filter((r) => r.params?.page_size === 1);
20
- expect(counts).toHaveLength(3);
19
+ expect(api.tenant.requests.filter((r) => r.path.endsWith('entities/counts'))).toHaveLength(1);
21
20
  });
22
21
 
23
- it('latest arrivals: newest first across types, limited, each a bounded server page', async () => {
22
+ it('latest arrivals: newest first across types in ONE bounded read', async () => {
24
23
  const api = createFakeNativeCorpusApi();
25
24
  const c = createHomeController({ api, types, limit: 4, now: () => NOW });
26
25
  await c.load();
@@ -30,21 +29,35 @@ describe('home controller: what has come in', () => {
30
29
  const stamps = s.arrivals.map((a) => a.createdAt);
31
30
  expect([...stamps].sort().reverse()).toEqual(stamps);
32
31
  const pages = api.tenant.requests.filter((r) => r.params?.order === 'recent');
33
- expect(pages.length).toBe(3);
34
- expect(pages.every((r) => r.params?.page_size === 4)).toBe(true);
35
- expect(s.arrivals[0]).toMatchObject({ type: expect.any(String), typeLabel: expect.any(String) });
32
+ expect(pages).toHaveLength(1);
33
+ expect(pages[0].params).toMatchObject({ type__in: 'commitment,source_document,focus', page_size: 4 });
34
+ expect(s.arrivals[0]).toMatchObject({ type: 'commitment', typeLabel: 'To-dos' });
36
35
  });
37
36
 
38
- it('a type that fails shows no count instead of a false zero, and the rest still load', async () => {
39
- const api = createFakeNativeCorpusApi({ onRequest: (_m, _p, params) => { if (params.type === 'focus') throw new Error('boom'); } });
37
+ it('the whole Home is two requests however many types it summarises', async () => {
38
+ const api = createFakeNativeCorpusApi();
39
+ await createHomeController({ api, types, now: () => NOW }).load();
40
+ expect(api.tenant.requests).toHaveLength(2);
41
+ });
42
+
43
+ it('a failed counts read shows no count instead of a false zero; arrivals still load', async () => {
44
+ const api = createFakeNativeCorpusApi({ onRequest: (_m, path) => { if (path.endsWith('counts')) throw new Error('boom'); } });
40
45
  const c = createHomeController({ api, types, now: () => NOW });
41
46
  await c.load();
42
47
  const s = c.getState();
43
- expect(s.metrics.find((m) => m.key === 'focus')?.count).toBeNull();
44
- expect(s.metrics.find((m) => m.key === 'commitment')?.count).toBe(6);
48
+ expect(s.metrics.every((m) => m.count === null)).toBe(true);
49
+ expect(s.arrivals.length).toBeGreaterThan(0);
50
+ expect(s.error).toBeNull();
45
51
  expect(s.loading).toBe(false);
46
52
  });
47
53
 
54
+ it('when both reads fail Home says so', async () => {
55
+ const api = createFakeNativeCorpusApi({ onRequest: () => { throw new Error('boom'); } });
56
+ const c = createHomeController({ api, types, now: () => NOW });
57
+ await c.load();
58
+ expect(c.getState().error).toBe('Could not load your workspace.');
59
+ });
60
+
48
61
  it('refresh reloads', async () => {
49
62
  const api = createFakeNativeCorpusApi();
50
63
  const c = createHomeController({ api, types, now: () => NOW });
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * The Home tab's data: what the web Home shows ("What has come in" metrics and
3
3
  * "Latest arrivals"), as a framework-free controller. Counts are the server's
4
- * COUNT of a one-row page per type; arrivals are the newest page of each type
5
- * (server `order=recent`), merged. Nothing here loads a full list.
4
+ * grouped `entities/counts` read (one request for every type); arrivals are the
5
+ * newest page across the types (`type__in`, server `order=recent`). Two requests
6
+ * for the screen, however many types. Nothing here loads a full list.
6
7
  */
7
8
  import type { TenantEntity } from '../../corpus/entities';
8
9
  import type { NativeCorpusApi } from '../corpus/api';
10
+ import { countsBy } from '../corpus/counts';
9
11
 
10
12
  export interface HomeType { key: string; label: string }
11
13
 
@@ -65,24 +67,28 @@ export function createHomeController({ api, types, limit = 8 }: HomeControllerOp
65
67
  const set = (patch: Partial<HomeState>) => { state = { ...state, ...patch }; listeners.forEach((l) => l()); };
66
68
 
67
69
  async function load() {
68
- const results = await Promise.all(types.map(async (t) => {
69
- const [count, recent] = await Promise.all([
70
- api.entities.list({ type: t.key, pageSize: 1 }).then((p) => p.count ?? null).catch(() => null),
71
- api.entities.list({ type: t.key, order: 'recent', pageSize: limit }).then((p) => p.items).catch(() => [] as TenantEntity[]),
72
- ]);
73
- return { t, count, recent };
74
- }));
75
- const arrivals = results
76
- .flatMap(({ t, recent }) => recent.map((entity): HomeArrival => ({
77
- id: String(entity.id), type: t.key, typeLabel: t.label, title: entity.name || entity.external_id || `#${entity.id}`, createdAt: stamp(entity), entity,
78
- })))
79
- .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
80
- .slice(0, limit);
70
+ // TWO reads for the whole screen, however many types it summarises: the count
71
+ // per type (one grouped read) and the newest rows across those types.
72
+ const [counts, recent] = await Promise.all([
73
+ api.entities.counts({ groupBy: ['type'], filters: { typeIn: types.map((t) => t.key) } })
74
+ .then((p) => countsBy(p.items, 'type')).catch(() => null),
75
+ api.entities.list({ filters: { typeIn: types.map((t) => t.key) }, order: 'recent', pageSize: limit })
76
+ .then((p) => p.items).catch(() => null),
77
+ ]);
78
+ const label = new Map(types.map((t) => [t.key, t.label]));
79
+ const arrivals = (recent ?? []).map((entity): HomeArrival => {
80
+ const type = String(entity.entity_type ?? entity.entityType ?? '');
81
+ return {
82
+ id: String(entity.id), type, typeLabel: label.get(type) ?? type,
83
+ title: entity.name || entity.external_id || `#${entity.id}`, createdAt: stamp(entity), entity,
84
+ };
85
+ });
81
86
  set({
82
87
  loading: false,
83
- metrics: results.map(({ t, count }) => ({ key: t.key, label: t.label, count })),
88
+ // A type with no rows is absent from the grouped answer: zero there, null only when the read failed.
89
+ metrics: types.map((t) => ({ key: t.key, label: t.label, count: counts ? (counts[t.key] ?? 0) : null })),
84
90
  arrivals,
85
- error: results.every((r) => r.count === null) ? 'Could not load your workspace.' : null,
91
+ error: counts === null && recent === null ? 'Could not load your workspace.' : null,
86
92
  });
87
93
  }
88
94
 
@@ -19,6 +19,8 @@ export * from './app';
19
19
  export * from './shell/navigator';
20
20
  export * from './shell/overflow';
21
21
  export * from './corpus/api';
22
+ export * from './corpus/counts';
23
+ export * from './corpus/display';
22
24
  export * from './corpus/ask';
23
25
  export * from './corpus/paged';
24
26
  export * from './corpus/fake';
@@ -47,7 +49,7 @@ export { AskScreen, type AskScreenProps } from './screens/ask/AskScreen';
47
49
  export * from './screens/tabs';
48
50
  // Planning, Connections, Connect Claude (bd startsim-23np6.1.6)
49
51
  export {
50
- createFocusDetailController, createPlanningController, STANDING_CONCURRENCY,
52
+ createFocusDetailController, createPlanningController,
51
53
  type FocusDetailController, type FocusDetailState, type PlanningController, type PlanningScreenApi, type PlanningState,
52
54
  } from './screens/planning/controller';
53
55
  export { createFakePlanningApi } from './screens/planning/fake';
@@ -25,7 +25,7 @@ describe('planning list: focuses with counts from the server', () => {
25
25
  c.stop();
26
26
  });
27
27
 
28
- it('walks the in_focus edges for open/done/overdue counts, as the web card does', async () => {
28
+ it('counts open/done/overdue for the whole page in two grouped reads, not three per card', async () => {
29
29
  const api = fakeApi();
30
30
  const c = createPlanningController({ api, now: () => NOW });
31
31
  await settle(() => Object.keys(c.getState().standings).length === 3);
@@ -33,29 +33,23 @@ describe('planning list: focuses with counts from the server', () => {
33
33
  expect(st.f287).toMatchObject({ total: 3, done: 0, overdue: 1 });
34
34
  expect(st.fma).toMatchObject({ total: 2, done: 1, overdue: 0 });
35
35
  expect(st.fdbg).toMatchObject({ total: 0, done: 0 });
36
- const counts = api.tenant.requests.filter((r) => r.params?.related_via === 'in_focus');
37
- expect(counts.length).toBeGreaterThanOrEqual(9);
38
- expect(counts.every((r) => r.params?.page_size === 1)).toBe(true);
36
+ const counts = api.tenant.requests.filter((r) => r.path.endsWith('entities/counts'));
37
+ expect(counts).toHaveLength(2);
38
+ expect(api.tenant.requests.filter((r) => r.params?.related_via === 'in_focus')).toHaveLength(0);
39
39
  c.stop();
40
40
  });
41
41
 
42
- it('fetches at most four standings at once', async () => {
43
- const api = fakeApi();
44
- let running = 0; let peak = 0;
45
- const real = api.corpus.focusStanding!.bind(api.corpus);
46
- api.corpus.focusStanding = async (id, now) => {
47
- running += 1; peak = Math.max(peak, running);
48
- await tick();
49
- try { return await real(id, now); } finally { running -= 1; }
50
- };
42
+ it('a long page of projects still costs two count reads, plus one more per further page', async () => {
51
43
  const entities = sampleTenantEntities();
52
- for (let i = 0; i < 10; i += 1) entities.push({ id: `x${i}`, entity_type: 'focus', external_id: `focus:x${i}`, name: `X${i}`, created_at: '2026-09-10T00:00:00Z', org_id: 'tandem', data: { title: `X${i}`, status: 'active' } } as never);
44
+ for (let i = 0; i < 30; i += 1) entities.push({ id: `x${i}`, entity_type: 'focus', external_id: `focus:x${i}`, name: `X${i}`, created_at: '2026-09-10T00:00:00Z', org_id: 'tandem', data: { title: `X${i}`, status: 'active' } } as never);
53
45
  const many = createFakeNativeCorpusApi({ entities, relationships: sampleTenantRelationships() });
54
- many.corpus.focusStanding = api.corpus.focusStanding;
55
46
  const c = createPlanningController({ api: many, now: () => NOW });
56
- await settle(() => Object.keys(c.getState().standings).length === 13);
57
- expect(Object.keys(c.getState().standings)).toHaveLength(13);
58
- expect(peak).toBeLessThanOrEqual(4);
47
+ await settle(() => Object.keys(c.getState().standings).length === 25);
48
+ expect(Object.keys(c.getState().standings)).toHaveLength(25);
49
+ expect(many.tenant.requests.filter((r) => r.path.endsWith('entities/counts'))).toHaveLength(2);
50
+ await c.loadMore();
51
+ await settle(() => Object.keys(c.getState().standings).length === 33);
52
+ expect(many.tenant.requests.filter((r) => r.path.endsWith('entities/counts'))).toHaveLength(4);
59
53
  c.stop();
60
54
  });
61
55
 
@@ -67,14 +61,14 @@ describe('planning list: focuses with counts from the server', () => {
67
61
  c.stop();
68
62
  });
69
63
 
70
- it('a standing that fails leaves that card uncounted instead of failing the list', async () => {
64
+ it('standings that fail leave the cards uncounted instead of failing the list', async () => {
71
65
  const api = fakeApi();
72
- const real = api.corpus.focusStanding!.bind(api.corpus);
73
- api.corpus.focusStanding = async (id, now) => { if (id === 'fma') throw new Error('boom'); return real(id, now); };
66
+ api.standings = async () => { throw new Error('boom'); };
74
67
  const c = createPlanningController({ api, now: () => NOW });
75
- await settle(() => Object.keys(c.getState().standings).length === 2);
68
+ await settle(() => !c.getState().focuses.loading);
69
+ await tick();
76
70
  expect(c.getState().focuses.error).toBeNull();
77
- expect(c.getState().standings.fma).toBeUndefined();
71
+ expect(c.getState().standings).toEqual({});
78
72
  c.stop();
79
73
  });
80
74
 
@@ -3,8 +3,8 @@
3
3
  * native corpus api - the same adapters the web `PlanningPage` uses.
4
4
  *
5
5
  * Server-side only: the focus list is one server page at a time (worst-off first,
6
- * the order the stored `progress` buys), each card's counts are `focusStanding`
7
- * (three count-only reads walking the `in_focus` edge, exactly the web card's),
6
+ * the order the stored `progress` buys), each page's card counts are `api.standings`
7
+ * (two grouped `entities/counts` reads for the WHOLE page, not three per card),
8
8
  * and a project's items and documents are server-paged queries filtered by the
9
9
  * focus edge. Nothing loads a list to narrow, sort or page it on the phone.
10
10
  */
@@ -14,10 +14,8 @@ import type { NativeCorpusApi } from '../../corpus/api';
14
14
  import type { PagedList, PagedListState } from '../../corpus/paged';
15
15
  import { createStore, errorMessage } from '../store';
16
16
 
17
- export type PlanningScreenApi = Pick<NativeCorpusApi, 'lists' | 'corpus' | 'entities' | 'scope'>;
17
+ export type PlanningScreenApi = Pick<NativeCorpusApi, 'lists' | 'corpus' | 'entities' | 'scope' | 'standings'>;
18
18
 
19
- /** How many standings are fetched at once - each is three reads, and the tenant pays for every one. */
20
- export const STANDING_CONCURRENCY = 4;
21
19
  export const FOCUS_PAGE_SIZE = 25;
22
20
  export const DOCUMENT_PAGE_SIZE = 10;
23
21
  export const ITEM_PAGE_SIZE = 25;
@@ -46,32 +44,26 @@ export interface PlanningDeps {
46
44
  now?: () => number;
47
45
  }
48
46
 
49
- /** Worker pool that runs standing reads `STANDING_CONCURRENCY` at a time. */
50
- function createStandingFetcher(api: PlanningScreenApi, now: () => number, onResult: (s: FocusStanding) => void) {
47
+ /**
48
+ * Standings for each page of projects as it arrives: ONE batched call per page
49
+ * (two grouped reads, however many cards), never one request set per card.
50
+ */
51
+ function createStandingFetcher(api: PlanningScreenApi, now: () => number, onResult: (s: Record<string, FocusStanding>) => void) {
51
52
  const requested = new Set<string>();
52
- const queue: string[] = [];
53
- let running = 0;
54
53
  let stopped = false;
55
54
 
56
- function pump() {
57
- while (!stopped && running < STANDING_CONCURRENCY && queue.length) {
58
- const id = queue.shift() as string;
59
- running += 1;
60
- Promise.resolve()
61
- .then(() => api.corpus.focusStanding!(id, now()))
62
- .then((s) => { if (!stopped) onResult(s); }, () => { /* uncounted, not a failed list */ })
63
- .finally(() => { running -= 1; pump(); });
64
- }
65
- }
66
-
67
55
  return {
68
56
  request(ids: string[]) {
69
- if (!api.corpus.focusStanding) return;
70
- for (const id of ids) if (!requested.has(id)) { requested.add(id); queue.push(id); }
71
- pump();
57
+ const fresh = ids.filter((id) => !requested.has(id));
58
+ if (!fresh.length) return;
59
+ fresh.forEach((id) => requested.add(id));
60
+ api.standings(fresh, now()).then(
61
+ (found) => { if (!stopped) onResult(found); },
62
+ () => { fresh.forEach((id) => requested.delete(id)); /* uncounted, not a failed list */ },
63
+ );
72
64
  },
73
65
  forget() { requested.clear(); },
74
- stop() { stopped = true; queue.length = 0; },
66
+ stop() { stopped = true; },
75
67
  };
76
68
  }
77
69
 
@@ -80,7 +72,7 @@ export function createPlanningController({ api, now = Date.now }: PlanningDeps):
80
72
  const store = createStore<{ standings: Record<string, FocusStanding>; search: string }>({ standings: {}, search: '' });
81
73
  const listeners = new Set<() => void>();
82
74
  const notify = () => listeners.forEach((l) => l());
83
- const counts = createStandingFetcher(api, now, (s) => store.set({ standings: { ...store.getState().standings, [s.focusId]: s } }));
75
+ const counts = createStandingFetcher(api, now, (found) => store.set({ standings: { ...store.getState().standings, ...found } }));
84
76
 
85
77
  // One cached snapshot, rebuilt only when a part changes: `useSyncExternalStore` loops on a getState that returns a new object each call.
86
78
  let snapshot: PlanningState = { focuses: list.getState(), standings: store.getState().standings, search: store.getState().search };
@@ -147,7 +139,7 @@ export function createFocusDetailController(
147
139
  if (!stopped) store.set({ focus: null, error: errorMessage(e, 'This project could not be loaded.') });
148
140
  }
149
141
  try {
150
- const standing = await api.corpus.focusStanding?.(focusId, now());
142
+ const standing = (await api.standings([focusId], now()))[focusId];
151
143
  if (!stopped && standing) store.set({ standing });
152
144
  } catch { /* the header shows no count rather than a wrong one */ }
153
145
  }
@@ -23,6 +23,23 @@ describe('tracker detail controller', () => {
23
23
  expect(api.tenant.requests.filter((r) => r.params?.type === 'commitment')).toHaveLength(0);
24
24
  });
25
25
 
26
+ it('reads a to-do in two rounds of requests, the source documents in ONE batched read', async () => {
27
+ const { api } = await open('c3');
28
+ const reads = api.tenant.requests.filter((r) => r.method === 'GET');
29
+ // round 1: the to-do + its project edge; round 2: the project + all source documents.
30
+ expect(reads).toHaveLength(4);
31
+ const docs = reads.filter((r) => r.params?.id__in !== undefined);
32
+ expect(docs).toHaveLength(1);
33
+ expect(docs[0].params).toMatchObject({ type: 'source_document', id__in: 'd2' });
34
+ // no per-document GET of /entities/<id> and no participants walk
35
+ expect(reads.filter((r) => /entities\/d2$/.test(r.path))).toHaveLength(0);
36
+ });
37
+
38
+ it('a to-do with no mentions does not ask for documents at all', async () => {
39
+ const { api } = await open('c4');
40
+ expect(api.tenant.requests.filter((r) => r.params?.id__in !== undefined)).toHaveLength(0);
41
+ });
42
+
26
43
  it('titles a non-voice source from its document and does not offer the Notes link', async () => {
27
44
  const { c } = await open('c3');
28
45
  const [src] = c.getState().sources;
@@ -1,10 +1,11 @@
1
1
  /**
2
- * One to-do, read directly (one entity read, its project edge, and the source
3
- * documents its mentions point at) - never by scanning the list. Mark done /
2
+ * One to-do, read directly (the entity and its project edge together, then the
3
+ * project and ALL source documents together) - never by scanning the list and
4
+ * never one read per mention. Mark done /
4
5
  * reopen is optimistic and rolls back with the server's reason.
5
6
  */
6
- import type { Commitment, CommitmentStatus } from '../../corpus/types';
7
- import { toCommitment } from '../../corpus/entities';
7
+ import type { Commitment, CommitmentStatus, SourceDocument } from '../../corpus/types';
8
+ import { DEFAULT_TYPE_KEYS, toCommitment, toSourceDocument } from '../../corpus/entities';
8
9
  import type { NativeCorpusApi } from '../corpus/api';
9
10
  import { statusText } from './format';
10
11
 
@@ -37,7 +38,7 @@ export interface TrackerDetailController {
37
38
  }
38
39
 
39
40
  export interface TrackerDetailOptions {
40
- api: Pick<NativeCorpusApi, 'entities' | 'corpus' | 'relationships' | 'commitments' | 'scope'>;
41
+ api: Pick<NativeCorpusApi, 'entities' | 'relationships' | 'commitments' | 'scope'>;
41
42
  id: string;
42
43
  /** Called after a status write succeeds, so the list can refresh. */
43
44
  onChanged?: () => void;
@@ -56,23 +57,35 @@ export function createTrackerDetailController({ api, id, onChanged }: TrackerDet
56
57
  async load() {
57
58
  set({ loading: true, error: null });
58
59
  try {
59
- const item = toCommitment(await api.entities.get(id), api.scope);
60
- const edge = await api.relationships.list({ relType: 'in_focus', source: id, pageSize: 1 }).catch(() => null);
60
+ // Round 1: the to-do and its project edge are independent. Round 2: the
61
+ // project's name and ALL source documents (one `id__in` read, not one
62
+ // read per mention).
63
+ const [entity, edge] = await Promise.all([
64
+ api.entities.get(id),
65
+ api.relationships.list({ relType: 'in_focus', source: id, pageSize: 1 }).catch(() => null),
66
+ ]);
67
+ const item = toCommitment(entity, api.scope);
61
68
  const focusId = edge?.items[0]?.target;
62
- const [project, sources] = await Promise.all([
69
+ const documentIds = [...new Set(item.mentions.map((m) => m.documentId))];
70
+ const [project, documents] = await Promise.all([
63
71
  focusId ? api.entities.get(String(focusId)).then((f) => f.name || null).catch(() => null) : Promise.resolve(null),
64
- Promise.all(item.mentions.map(async (m): Promise<TrackerSource> => {
65
- const doc = await api.corpus.getDocument?.(m.documentId).catch(() => null);
66
- return {
67
- documentId: m.documentId,
68
- title: doc?.title || item.sourceLabel || 'Source',
69
- quote: m.quote,
70
- occurredAt: m.occurredAt ?? doc?.occurredAt ?? null,
71
- ...(m.section ? { section: m.section } : {}),
72
- isVoiceNote: (doc?.source ?? item.source) === 'voice',
73
- };
74
- })),
72
+ documentIds.length
73
+ ? api.entities.list({ type: DEFAULT_TYPE_KEYS.document, filters: { idIn: documentIds }, pageSize: documentIds.length })
74
+ .then((page) => new Map(page.items.map((e) => [String(e.id), toSourceDocument(e, api.scope)])))
75
+ .catch(() => new Map<string, SourceDocument>())
76
+ : Promise.resolve(new Map<string, SourceDocument>()),
75
77
  ]);
78
+ const sources = item.mentions.map((m): TrackerSource => {
79
+ const doc = documents.get(m.documentId);
80
+ return {
81
+ documentId: m.documentId,
82
+ title: doc?.title || item.sourceLabel || 'Source',
83
+ quote: m.quote,
84
+ occurredAt: m.occurredAt ?? doc?.occurredAt ?? null,
85
+ ...(m.section ? { section: m.section } : {}),
86
+ isVoiceNote: (doc?.source ?? item.source) === 'voice',
87
+ };
88
+ });
76
89
  set({ loading: false, item, projectTitle: project, sources });
77
90
  } catch (e) {
78
91
  set({ loading: false, item: null, error: (e as { status?: number })?.status === 404 ? 'This to-do is no longer available.' : msg(e) });