@startsimpli/integrations 0.2.101 → 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.
@@ -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;