@startsimpli/integrations 0.2.204 → 0.2.205

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,50 +1,37 @@
1
1
  /**
2
- * The Library — the corpus surface, as ONE composer (bd startsim-768w.38.6).
2
+ * The Library — everything pulled in, as ONE table (bd startsim-768w.38.6; table redesign startsim-x3pd3).
3
3
  *
4
- * `<LibraryPage api={corpus} scope={scope} />` is the whole integration. An app
5
- * owns theme classNames and a wrapper of ten lines, the same shape as
6
- * `ConnectionsPage` and for the same reason: shipping primitives and letting
7
- * each app assemble the page just relocates the duplication one level up
8
- * (feedback_share_page_composers_not_just_primitives).
4
+ * `<LibraryPage api={corpus} scope={scope} />` is the whole integration. The screen is a left tree
5
+ * (All documents, then each source with its count and, only where it has folders, its folders), one
6
+ * compact toolbar (search, Type, Date) and the shared DataTable with the shared pagination footer.
7
+ * Connector health lives in the Sources table, not here; no title, no subtitle, no pills.
9
8
  *
10
- * WHAT IT RENDERS, in the order the question is actually asked:
9
+ * EVERY filter, the sort and the page are SERVER parameters (CLAUDE.md rule 8); nothing is filtered
10
+ * in the browser. A filter the server did not apply is said out loud, and a row from another
11
+ * workspace is never drawn (`enforceScope`), whatever the API returned.
11
12
  *
12
- * 1. FRESHNESS per source — when did each one last pull, and did it work. This
13
- * is on the screen, not in a settings page, because a corpus silently four
14
- * days stale is what makes an AI answer confidently wrong.
15
- * 2. FILTERS — search, source, party, date window. Every one of them is a
16
- * SERVER parameter (CLAUDE.md rule 8); nothing is filtered in the browser.
17
- * 3. The LIST, every row wearing its source as a visible badge.
18
- * 4. The DETAIL, with participants as Party links and whatever long-form the
19
- * source attached, under the source's own name for it.
13
+ * LOAD ORDER (the queue order on a server that answers one request at a time): the ROWS first (one
14
+ * documents read, no people), then the people on each row, then the source counts that fill the
15
+ * tree, then the folders of each source one source at a time. Its test is
16
+ * `library-call-shape.test.tsx`.
20
17
  *
21
- * NOTHING HERE NAMES A VENDOR. The standing test for every element below is
22
- * "would this row, badge, filter or empty state still make sense if the only
23
- * connected source were Dropbox?" — so the source list comes from the freshness
24
- * data, the badge renders whatever label the catalog gave it, and long-form text
25
- * is a labelled `section` rather than a transcript. A screen that only works for
26
- * meeting notes is a failed design even though it would demo fine.
18
+ * NOTHING HERE NAMES A VENDOR: sources, types and labels all come from the corpus catalog.
27
19
  */
28
20
  import * as React from 'react';
29
21
 
30
22
  import { LoadError } from '../LoadError';
31
- import { SourcesTable } from './library/SourcesTable';
32
-
33
23
  import { DocumentDetail } from '../DocumentDetail';
34
- import { formatDate, summaryOf } from '../documentText';
35
- import { FolderTree, folderTrail } from '../FolderTree';
36
- import { folderName } from '../../corpus/entities';
24
+ import { folderTrail } from '../FolderTree';
37
25
  import type { FolderTreeSlot } from '../FolderTree';
38
- import { documentPreview as preview, openFailureMessage, readFailureMessage } from '../../corpus/view-text';
26
+ import { DEFAULT_PAGE_SIZE, FilterSelect, TableToolbar, readPageSize, writePageSize } from '../table';
27
+ import type { PageSize, TableSort } from '../table';
39
28
  import { enforceScope } from '../../corpus/retrieval';
40
- import type {
41
- CorpusApi,
42
- CorpusScope,
43
- DocumentQuery,
44
- Party,
45
- SourceDocument,
46
- SourceFreshness,
47
- } from '../../corpus/types';
29
+ import { openFailureMessage, readFailureMessage } from '../../corpus/view-text';
30
+ import type { CorpusApi, CorpusScope, DocumentQuery, SourceDocument, SourceFreshness } from '../../corpus/types';
31
+ import { LibraryTable } from './library/LibraryTable';
32
+ import { LibraryTree } from './library/LibraryTree';
33
+ import type { LibrarySelection } from './library/LibraryTree';
34
+ import { DATE_FILTERS, dateAfter, emptyColumns, orderOf, typeOptions } from './library/library-model';
48
35
 
49
36
  export interface LibraryPageProps {
50
37
  api: CorpusApi;
@@ -60,49 +47,17 @@ export interface LibraryPageProps {
60
47
  initialFolder?: string;
61
48
  /** Told whenever the open folder changes, so an app can put it in the URL. */
62
49
  onSelectFolder?: (folder: string | null) => void;
63
- /**
64
- * PULL THE TEXT OF ONE RECORD. Supply it and the control on a text-less row is
65
- * live; leave it out and the same control is there and DISABLED.
66
- *
67
- * IT IS A CONTROL EITHER WAY, and that is the whole point of the seam
68
- * (Quinn, 2026-08-27, on the sentence this replaced: "don't say stupid shit
69
- * like 'no text blah blah'. either have a button to pull the text, or have it
70
- * grayed out if we can't do the action. simple ui."). A sentence in the place
71
- * a control belongs tells a reader what happened; a greyed-out control tells
72
- * them what they may do, which is the question they were actually asking.
73
- *
74
- * NOTHING SUPPLIES IT TODAY, and that is correct rather than a stub. Content
75
- * is OPT-IN and never the default (bd startsim-h6xnu): the index owes what
76
- * exists, where it lives and findability, and pulling the bytes of every file
77
- * is the expensive, privacy-loaded half nobody asked for. The route that would
78
- * fill this in is bd startsim-99g8.2 and it is deliberately unshipped, so on
79
- * today's tenant the control is disabled — which is the honest answer to "can
80
- * I read this .ttf".
81
- */
82
- onRequestText?: (document: SourceDocument) => void | Promise<void>;
50
+ /** Rows per page when the reader has not chosen one (the footer remembers their choice). */
83
51
  pageSize?: number;
84
- /** Opens the connection behind a source row (its Reconnect / Manage action). Omit to show no action. */
85
- onManageSource?: (source: string) => void;
86
52
  classNames?: Partial<Record<LibrarySlot, string>>;
87
- /** Theme slots for the folder tree, passed straight through. */
53
+ /** Theme slots for the folder rows, passed straight through. */
88
54
  folderClassNames?: Partial<Record<FolderTreeSlot, string>>;
89
55
  }
90
56
 
91
- type LibrarySlot =
92
- | 'root'
93
- | 'section'
94
- | 'heading'
95
- | 'card'
96
- | 'row'
97
- | 'badge'
98
- | 'button'
99
- | 'input'
100
- | 'muted'
101
- | 'error'
102
- | 'warning';
57
+ type LibrarySlot = 'root' | 'section' | 'heading' | 'card' | 'row' | 'badge' | 'button' | 'input' | 'muted' | 'error' | 'warning';
103
58
 
104
59
  const DEFAULTS: Record<LibrarySlot, string> = {
105
- root: 'space-y-6',
60
+ root: 'space-y-4',
106
61
  section: 'space-y-3',
107
62
  heading: 'text-lg font-semibold text-gray-900',
108
63
  card: 'rounded-lg border border-gray-200 p-4',
@@ -115,141 +70,97 @@ const DEFAULTS: Record<LibrarySlot, string> = {
115
70
  warning: 'rounded-md border border-amber-300 bg-amber-50 p-2 text-sm text-amber-800',
116
71
  };
117
72
 
118
- // ---------------------------------------------------------------------------
73
+ const SEARCH_DEBOUNCE_MS = 300;
119
74
 
120
75
  export function LibraryPage({
121
- api,
122
- onOpenPlan,
123
- scope,
124
- initialDocumentId,
125
- onSelectDocument,
126
- initialFolder,
127
- onSelectFolder,
128
- onRequestText,
129
- onManageSource,
130
- pageSize = 20,
131
- classNames = {},
132
- folderClassNames = {},
76
+ api, onOpenPlan, scope, initialDocumentId, onSelectDocument, initialFolder, onSelectFolder, pageSize, classNames = {},
133
77
  }: LibraryPageProps) {
134
78
  const cn = { ...DEFAULTS, ...classNames };
135
79
 
136
- const [filters, setFilters] = React.useState<DocumentQuery>({ page: 1, pageSize });
137
- /**
138
- * THE OPEN FOLDER, or `null` for the whole corpus.
139
- *
140
- * `null` IS NOT A BUCKET AND MUST NOT BECOME ONE. The facet read enumerates
141
- * values of `path` and skips records that have none, so a meeting note and an
142
- * email are in NO folder — which on today's tandem is most of the corpus. The
143
- * top of the tree therefore clears the path filter rather than narrowing to
144
- * some invented "unfiled", and every record stays one click from the top the
145
- * way it is in any file browser.
146
- */
147
- const [folder, setFolder] = React.useState<string | null>(initialFolder ?? null);
148
- /** Set once the corpus proves it cannot enumerate folders; see `FolderTree`. */
149
- const [noTree, setNoTree] = React.useState(false);
150
- /**
151
- * Whether an open folder means IT AND EVERYTHING BELOW IT. Default yes, and
152
- * the default is the whole point.
153
- *
154
- * THE NUMBER THE READER JUST CLICKED HAS TO BE THE LIST THEY GET. A folder's
155
- * count is DESCENDANTS — the tenant says so outright, because that is the
156
- * number a person reading a collapsed folder wants — so a list bounded to the
157
- * exact shelf disagrees with it the moment a folder is a container. On the
158
- * live tandem corpus that is the two biggest folders: `/ERA22 Shared` (142)
159
- * and `/Demo Day Presentations` (37) both hold their documents in subfolders.
160
- * Bounded exactly, clicking either showed "0 records" beside a sidebar reading
161
- * 142, under the sentence "Nothing matches those filters. Clear them to see
162
- * everything." — filters the reader never set, in the place a control belongs.
163
- * That is the same fault as the row sentence this screen just removed.
164
- *
165
- * IT IS A CONTROL, so the other reading stays available: uncheck it and the
166
- * list is the shelf. What it is not is a hidden mode — the bound used to
167
- * depend on whether the search box had a term in it, which meant the same
168
- * click answered two different questions depending on state the reader was not
169
- * looking at.
170
- */
171
- const [includeSubfolders, setIncludeSubfolders] = React.useState(true);
80
+ // THE VIEW — everything the server query is made of. One object, so a change to any of it is one query.
172
81
  const [draftSearch, setDraftSearch] = React.useState('');
82
+ const [search, setSearch] = React.useState('');
83
+ const [subtype, setSubtype] = React.useState('');
84
+ const [date, setDate] = React.useState<{ key: string; after?: string }>({ key: '' });
85
+ const [sort, setSort] = React.useState<TableSort | null>(null);
86
+ const [selection, setSelection] = React.useState<LibrarySelection>({ source: null, folder: initialFolder ?? null });
87
+ const [partyFilter, setPartyFilter] = React.useState<{ id: string; name: string } | null>(null);
88
+ const [page, setPage] = React.useState(1);
89
+ const [size, setSize] = React.useState<PageSize>(() => (pageSize ? (pageSize as PageSize) : readPageSize('library')));
90
+
173
91
  const [documents, setDocuments] = React.useState<SourceDocument[]>([]);
174
92
  const [count, setCount] = React.useState(0);
175
93
  const [applied, setApplied] = React.useState<string[] | undefined>(undefined);
176
94
  const [sources, setSources] = React.useState<SourceFreshness[]>([]);
177
- /** Per-source totals, held apart from the cards so a late count patches a card, never replaces it. */
178
95
  const [sourceCounts, setSourceCounts] = React.useState<Map<string, number | null>>(new Map());
179
- /** True once the first list read has settled; the reads that are not the rows wait for it. */
96
+ const [seenTypes, setSeenTypes] = React.useState<string[]>([]);
97
+ /** True once the first list read has settled; every read that is not the rows waits for it. */
180
98
  const [firstPaint, setFirstPaint] = React.useState(false);
181
- const defer = typeof api.participantsFor === 'function';
182
- const shownSources = React.useMemo(
183
- () => (sourceCounts.size === 0
184
- ? sources
185
- : sources.map((source) => (sourceCounts.has(source.source)
186
- ? { ...source, documentCount: sourceCounts.get(source.source) ?? null }
187
- : source))),
188
- [sources, sourceCounts],
189
- );
190
- const [parties, setParties] = React.useState<Party[]>([]);
99
+ /** The people on the rows arrive after the rows; until they have, `Who` is not judged empty. */
100
+ const [peopleSettled, setPeopleSettled] = React.useState(false);
101
+ const [sourcesLoaded, setSourcesLoaded] = React.useState(false);
102
+ const [noTree, setNoTree] = React.useState(false);
191
103
  const [selectedId, setSelectedId] = React.useState<string | null>(initialDocumentId ?? null);
192
104
  const [selected, setSelected] = React.useState<SourceDocument | null>(null);
193
- /**
194
- * Why the open record is not open. Held separately from `loadError`, which is
195
- * about the LIST: a Library that loaded fine and a citation that no longer
196
- * resolves are different facts, and blanking the list for the second one would
197
- * be a worse answer than the silence this replaces.
198
- */
199
105
  const [selectError, setSelectError] = React.useState('');
200
106
  const [loading, setLoading] = React.useState(true);
201
107
  const [loadError, setLoadError] = React.useState('');
202
108
  const [attempt, setAttempt] = React.useState(0);
203
- /**
204
- * LATCHED, not per-page. "The data API returned another workspace's rows" is a
205
- * fact about the API, and paging forward past the offending page must not make
206
- * the warning disappear as though it were fixed.
207
- */
109
+ /** LATCHED: "the API returned another workspace's rows" is a fact about the API, and paging past it does not fix it. */
208
110
  const [droppedOutOfScope, setDroppedOutOfScope] = React.useState(0);
111
+ const defer = typeof api.participantsFor === 'function';
209
112
 
210
- /**
211
- * The list query: the filter bar PLUS the open folder, bounded the way the
212
- * reader asked for it — see `includeSubfolders` for why the default is the
213
- * subtree and not the shelf.
214
- */
215
- const query = React.useMemo<DocumentQuery>(() => {
216
- if (!folder) return filters;
217
- // ONE OF THE TWO, NEVER BOTH: the list endpoint ANDs its filters, so sending
218
- // both would intersect a folder with its own subtree and quietly answer with
219
- // the shelf.
220
- return includeSubfolders ? { ...filters, underFolder: folder } : { ...filters, folder };
221
- }, [filters, folder, includeSubfolders]);
113
+ // Debounced search: typing is not a query until the reader pauses.
114
+ React.useEffect(() => {
115
+ if (draftSearch === search) return undefined;
116
+ const handle = setTimeout(() => { setSearch(draftSearch); setPage(1); }, SEARCH_DEBOUNCE_MS);
117
+ return () => clearTimeout(handle);
118
+ }, [draftSearch, search]);
119
+
120
+ const query = React.useMemo<DocumentQuery>(() => ({
121
+ page,
122
+ pageSize: size,
123
+ ...(search ? { search } : {}),
124
+ ...(selection.source ? { source: selection.source } : {}),
125
+ ...(subtype ? { subtype } : {}),
126
+ ...(date.after ? { occurredAfter: date.after } : {}),
127
+ ...(partyFilter ? { partyId: partyFilter.id } : {}),
128
+ // A folder means it AND everything below it. The list endpoint ANDs its filters, so exactly one of folder / underFolder.
129
+ ...(selection.folder ? { underFolder: selection.folder } : {}),
130
+ ...(orderOf(sort) ? { order: orderOf(sort) } : {}),
131
+ }), [page, size, search, selection, subtype, date.after, partyFilter, sort]);
132
+ const queryKey = JSON.stringify(query);
222
133
 
223
134
  React.useEffect(() => {
224
135
  let live = true;
225
136
  setLoading(true);
137
+ setPeopleSettled(false);
226
138
  void (async () => {
227
139
  try {
228
- // ROWS FIRST. With an adapter that can fetch participants separately the
229
- // list waits for ONE read — the documents page — and the people on each
230
- // row are patched in below. Behind a slow or single-file backend the
231
- // edge read and the six-page roster walk were the page (2026-11-20).
232
- const page = await api.listDocuments(query, defer ? { participants: false } : undefined);
140
+ // ROWS FIRST: with an adapter that can fetch people separately the list waits for ONE read.
141
+ const result = await api.listDocuments(query, defer ? { participants: false } : undefined);
233
142
  if (!live) return;
234
- // THE GUARD RUNS ON THE LIST, not only on the detail panel. A row from
235
- // another workspace is a leak the moment it is drawn — its title and its
236
- // preview text are already on the screen, and nobody has to click. The
237
- // API scopes reads and RLS scopes them again; this is the third check,
238
- // and a non-zero drop is stated rather than absorbed.
239
- const { kept, dropped } = enforceScope(page.results ?? [], scope);
143
+ const { kept, dropped } = enforceScope(result.results ?? [], scope);
240
144
  setDocuments(kept);
241
145
  setDroppedOutOfScope((seen) => seen + dropped.length);
242
- setCount(Math.max(0, (page.count ?? 0) - dropped.length));
243
- setApplied(page.appliedFilters);
146
+ setCount(Math.max(0, (result.count ?? 0) - dropped.length));
147
+ setApplied(result.appliedFilters);
244
148
  setLoadError('');
149
+ setSeenTypes((prev) => {
150
+ const next = new Set(prev);
151
+ kept.forEach((d) => { if (d.subtype) next.add(d.subtype); });
152
+ return next.size === prev.length ? prev : Array.from(next);
153
+ });
245
154
  if (defer && api.participantsFor && kept.length) {
246
- void api.participantsFor(kept.map((document) => document.id)).then((people) => {
155
+ void api.participantsFor(kept.map((d) => d.id)).then((people) => {
247
156
  if (!live) return;
248
- setDocuments((current) => current.map((document) => {
249
- const found = people.get(String(document.id));
250
- return found ? { ...document, participants: found } : document;
157
+ setDocuments((current) => current.map((d) => {
158
+ const found = people.get(String(d.id));
159
+ return found ? { ...d, participants: found } : d;
251
160
  }));
252
- }).catch(() => { /* the rows stand without their people, as before */ });
161
+ }).catch(() => { /* the rows stand without their people */ }).finally(() => { if (live) setPeopleSettled(true); });
162
+ } else {
163
+ setPeopleSettled(true);
253
164
  }
254
165
  } catch (err) {
255
166
  if (live) setLoadError(readFailureMessage(err));
@@ -258,55 +169,40 @@ export function LibraryPage({
258
169
  }
259
170
  })();
260
171
  return () => { live = false; };
261
- }, [api, query, scope, attempt]);
172
+ // `queryKey` stands for `query`: a re-render with an equal query must not ask again.
173
+ // eslint-disable-next-line react-hooks/exhaustive-deps
174
+ }, [api, queryKey, scope, attempt]);
262
175
 
263
- // The reference-only surfaces (which sources exist, which parties exist) load
264
- // once. They are what makes the filter controls DATA rather than a hardcoded
265
- // vendor list — add a connector and its option appears with no code change.
266
- //
267
- // IN QUEUE ORDER, because the queue is the bottleneck: the documents effect
268
- // above asked first, the source CARDS ask next (they are above the fold), and
269
- // everything that is not on the first screen — the per-source counts, the
270
- // party filter, the people on each row — waits its turn behind the rows.
176
+ // The sources (and their counts) fill the tree. They come after the rows, which asked first.
271
177
  React.useEffect(() => {
178
+ if (!firstPaint) return undefined;
272
179
  let live = true;
273
180
  void (async () => {
274
181
  const freshness = await api
275
182
  .listSources({ onCounts: (counts) => { if (live) setSourceCounts(counts); } })
276
183
  .catch(() => [] as SourceFreshness[]);
277
- if (live) setSources(freshness);
278
- })();
279
- return () => { live = false; };
280
- }, [api]);
281
-
282
- React.useEffect(() => {
283
- if (!firstPaint) return undefined;
284
- let live = true;
285
- void (async () => {
286
- const partyPage = await api.listParties({ page: 1, pageSize: 100 }).catch(() => ({
287
- count: 0, next: null, previous: null, results: [] as Party[],
288
- }));
289
- if (live) setParties(partyPage.results ?? []);
184
+ if (live) { setSources(freshness); setSourcesLoaded(true); }
290
185
  })();
291
186
  return () => { live = false; };
292
187
  }, [api, firstPaint]);
293
188
 
189
+ const shownSources = React.useMemo(
190
+ () => (sourceCounts.size === 0
191
+ ? sources
192
+ : sources.map((s) => (sourceCounts.has(s.source) ? { ...s, documentCount: sourceCounts.get(s.source) ?? null } : s))),
193
+ [sources, sourceCounts],
194
+ );
195
+
294
196
  React.useEffect(() => {
295
- if (!selectedId) { setSelected(null); setSelectError(''); return; }
197
+ if (!selectedId) { setSelected(null); setSelectError(''); return undefined; }
296
198
  let live = true;
297
199
  void (async () => {
298
- // Prefer the row already on screen; fall back to a fetch so a citation
299
- // deep-link opens a record that is not on the current page.
300
- const onPage = documents.find((document) => document.id === selectedId);
200
+ const onPage = documents.find((d) => d.id === selectedId);
301
201
  if (onPage) { setSelected(onPage); setSelectError(''); return; }
302
202
  try {
303
203
  const fetched = await api.getDocument(selectedId);
304
204
  if (live) { setSelected(fetched); setSelectError(''); }
305
205
  } catch (err) {
306
- // THE REPORTED BUG (bd startsim-4s4um). This was `setSelected(null)` and
307
- // nothing else, so `?doc=<id>` in the address bar produced a Library
308
- // with no record and no explanation — the one outcome a reader cannot
309
- // act on, and indistinguishable from a page that simply ignored them.
310
206
  if (live) { setSelected(null); setSelectError(openFailureMessage(err, selectedId)); }
311
207
  }
312
208
  })();
@@ -319,377 +215,110 @@ export function LibraryPage({
319
215
  onSelectDocument?.(id);
320
216
  }, [onSelectDocument]);
321
217
 
322
- const update = React.useCallback((patch: Partial<DocumentQuery>) => {
323
- // Any filter change resets to page 1 — page 3 of the old result set is not
324
- // page 3 of the new one, and silently keeping it shows an empty list.
325
- setFilters((prev) => ({ ...prev, ...patch, page: patch.page ?? 1 }));
326
- }, []);
327
-
328
- /**
329
- * Move to a folder. Same page-1 reset as any other narrowing, and for the
330
- * same reason: page 3 of `/Contracts` is not page 3 of the corpus.
331
- */
332
- const openFolder = React.useCallback((next: string | null) => {
333
- setFolder(next);
334
- setFilters((prev) => ({ ...prev, page: 1 }));
335
- // AND THE BOUND RESETS WITH IT. "Only this shelf" is a thing the reader
336
- // wanted to know about THAT folder, not a mode they signed up to carry
337
- // around: left sticky, unchecking it on a container like `/Decks` and then
338
- // clicking `/Contracts` — which does have files of its own — lists 2 of its
339
- // 7 under a sidebar reading 7, which is the disagreement this screen just
340
- // spent a commit removing, reachable in two clicks. Same reasoning as the
341
- // page reset above: the answer to the old question is not the answer to the
342
- // new one, and the control is one click away for anyone who wants it back.
343
- setIncludeSubfolders(true);
344
- onSelectFolder?.(next);
218
+ const choose = React.useCallback((next: LibrarySelection) => {
219
+ setSelection(next);
220
+ setPage(1);
221
+ onSelectFolder?.(next.folder);
345
222
  }, [onSelectFolder]);
346
223
 
347
- const page = filters.page ?? 1;
348
- const size = filters.pageSize ?? pageSize;
349
- const lastPage = Math.max(1, Math.ceil(count / size));
350
- const now = Date.now();
351
-
352
- /**
353
- * A filter the SERVER did not apply. Rendering the unfiltered list under a
354
- * filled-in search box is a lie the user cannot catch, so it is stated.
355
- */
224
+ /** A filter the SERVER did not apply: rendering the unfiltered list under a filled-in box is a lie. */
356
225
  const ignored = React.useMemo(() => {
357
- if (!applied) return [] as string[];
358
- const requested: Array<[string, unknown]> = [
359
- ['search', filters.search],
360
- ['source', filters.source],
361
- ['party', filters.partyId],
362
- ['date', filters.occurredAfter || filters.occurredBefore],
363
- // THE ONE THAT MATTERS MOST HERE. A tree the server cannot narrow by is
364
- // worse than no tree: the reader clicks `/Contracts`, the list does not
365
- // change, and nothing on the screen says why. Same rule as the search box.
366
- ['folder', query.folder || query.underFolder],
226
+ // `applied` describes the PREVIOUS answer while a new one is on its way; judging the new query by it flashes a false warning.
227
+ if (!applied || loading) return [] as string[];
228
+ const requested: Array<[string, unknown, string[]]> = [
229
+ ['search', query.search, ['search']],
230
+ ['source', query.source, ['source']],
231
+ ['type', query.subtype, ['subtype']],
232
+ ['person', query.partyId, ['partyId']],
233
+ ['date', query.occurredAfter, ['occurredAfter', 'occurredBefore']],
234
+ ['folder', query.folder || query.underFolder, ['folder', 'underFolder']],
235
+ ['sort', query.order, ['order']],
367
236
  ];
368
- const keyFor: Record<string, string[]> = {
369
- search: ['search'], source: ['source'], party: ['partyId'],
370
- date: ['occurredAfter', 'occurredBefore'],
371
- folder: ['folder', 'underFolder'],
372
- };
373
- return requested
374
- .filter(([name, value]) => value && !keyFor[name].some((key) => applied.includes(key)))
375
- .map(([name]) => name);
376
- }, [applied, filters, query]);
237
+ return requested.filter(([, value, keys]) => value && !keys.some((key) => applied.includes(key))).map(([name]) => name);
238
+ }, [applied, query, loading]);
377
239
 
378
- const hasFilters = Boolean(filters.source || filters.partyId || filters.occurredAfter || filters.occurredBefore);
240
+ const hasFilters = Boolean(search || selection.source || selection.folder || subtype || date.after || partyFilter);
379
241
 
380
242
  if (loadError) {
381
243
  return <LoadError what="the library" message={loadError} onRetry={() => { setLoadError(''); setAttempt((n) => n + 1); }} />;
382
244
  }
383
245
 
246
+ const emptyMessage = hasFilters
247
+ ? 'Nothing matches.'
248
+ : sourcesLoaded && sources.length === 0
249
+ ? 'Nothing has been pulled in yet. Connect a source and its records appear here.'
250
+ : 'Nothing has arrived yet.';
251
+
384
252
  return (
385
253
  <div className={cn.root}>
386
- <SourcesTable sources={shownSources} now={now} onManage={onManageSource} classNames={cn} />
387
-
388
- <section className={cn.section}>
389
- <form
390
- className="flex flex-wrap items-end gap-2"
391
- onSubmit={(event) => { event.preventDefault(); update({ search: draftSearch || undefined }); }}
392
- >
393
- <label className="flex min-w-0 flex-1 flex-col gap-1">
394
- <span className="text-xs font-medium text-gray-700">Search</span>
395
- <input
396
- className={`${cn.input} w-full`}
397
- type="search"
398
- value={draftSearch}
399
- placeholder="Search everything pulled in"
400
- onChange={(event) => setDraftSearch(event.target.value)}
254
+ <div className={noTree ? '' : 'grid gap-4 md:grid-cols-[minmax(0,13rem)_minmax(0,1fr)]'}>
255
+ <aside className="h-max min-w-0 rounded-lg border border-gray-200 bg-white p-2 dark:border-gray-700 dark:bg-gray-900">
256
+ <LibraryTree
257
+ api={api}
258
+ sources={shownSources}
259
+ sourcesLoaded={sourcesLoaded}
260
+ selection={selection}
261
+ onSelect={choose}
262
+ hold={!firstPaint || noTree}
263
+ onUnavailable={() => setNoTree(true)}
264
+ />
265
+ </aside>
266
+
267
+ <section className="min-w-0 space-y-3">
268
+ <TableToolbar search={draftSearch} onSearch={setDraftSearch} searchLabel="Search the library" searchPlaceholder="Search everything pulled in">
269
+ {seenTypes.length > 0 || subtype ? (
270
+ <FilterSelect label="Type" value={subtype} options={typeOptions(seenTypes, subtype)} onChange={(value) => { setSubtype(value); setPage(1); }} />
271
+ ) : null}
272
+ <FilterSelect
273
+ label="Date"
274
+ value={date.key}
275
+ options={DATE_FILTERS}
276
+ onChange={(key) => { setDate({ key, after: dateAfter(key, Date.now()) }); setPage(1); }}
401
277
  />
402
- </label>
403
-
404
- <button type="submit" className={cn.button}>Search</button>
405
-
406
- {/* The rest of the filters fold away: a phone should see the search box first, not a form a third of the screen tall. */}
407
- <details className="w-full rounded-lg border border-gray-200 bg-white px-3 py-2" open={hasFilters}>
408
- <summary className="cursor-pointer text-sm font-medium text-gray-700">Filters{hasFilters ? ' (on)' : ''}</summary>
409
- <div className="mt-3 flex flex-wrap items-end gap-2">
410
- <label className="flex flex-col gap-1">
411
- <span className="text-xs font-medium text-gray-700">Source</span>
412
- <select
413
- className={cn.input}
414
- value={filters.source ?? ''}
415
- onChange={(event) => update({ source: event.target.value || undefined })}
416
- >
417
- <option value="">All sources</option>
418
- {/* Options are DATA. A fourth connector appears here by existing. */}
419
- {shownSources.map((source) => (
420
- <option key={source.source} value={source.source}>{source.label}</option>
421
- ))}
422
- </select>
423
- </label>
424
-
425
- <label className="flex flex-col gap-1">
426
- <span className="text-xs font-medium text-gray-700">Party</span>
427
- <select
428
- className={cn.input}
429
- value={filters.partyId ?? ''}
430
- onChange={(event) => update({ partyId: event.target.value || undefined })}
431
- >
432
- <option value="">Anyone</option>
433
- {parties.map((party) => (
434
- <option key={party.id} value={party.id}>{party.name}</option>
435
- ))}
436
- </select>
437
- </label>
438
-
439
- <label className="flex flex-col gap-1">
440
- <span className="text-xs font-medium text-gray-700">From</span>
441
- <input
442
- className={cn.input}
443
- type="date"
444
- value={(filters.occurredAfter ?? '').slice(0, 10)}
445
- onChange={(event) => update({
446
- occurredAfter: event.target.value ? `${event.target.value}T00:00:00Z` : undefined,
447
- })}
448
- />
449
- </label>
450
-
451
- <label className="flex flex-col gap-1">
452
- <span className="text-xs font-medium text-gray-700">To</span>
453
- <input
454
- className={cn.input}
455
- type="date"
456
- value={(filters.occurredBefore ?? '').slice(0, 10)}
457
- onChange={(event) => update({
458
- occurredBefore: event.target.value ? `${event.target.value}T23:59:59Z` : undefined,
459
- })}
460
- />
461
- </label>
462
-
463
- <button
464
- type="button"
465
- className={cn.button}
466
- onClick={() => {
467
- setDraftSearch('');
468
- setFilters({ page: 1, pageSize: size });
469
- setIncludeSubfolders(true);
470
- // "Clear" resets the VIEW, and the open folder is part of the view
471
- // a reader is looking at. Leaving them inside a folder with an
472
- // emptied filter bar is the same half-answer as leaving the search
473
- // term in the box.
474
- openFolder(null);
475
- }}
476
- >
477
- Clear
478
- </button>
479
- </div>
480
- </details>
481
- </form>
482
-
483
- {ignored.length ? (
484
- <p className={cn.warning} role="status">
485
- This workspace’s data API does not filter by {ignored.join(', ')} yet, so the list below
486
- is not narrowed by {ignored.length > 1 ? 'those' : 'that'}.
487
- </p>
488
- ) : null}
489
-
490
- {droppedOutOfScope > 0 ? (
491
- // Good news about the guard, bad news about the API. Both are worth
492
- // seeing: a data plane returning other workspaces' rows is a bug that
493
- // silence would let run for months.
494
- <p className={cn.error} role="alert">
495
- This workspace’s data API returned {droppedOutOfScope} record
496
- {droppedOutOfScope === 1 ? '' : 's'} belonging to another workspace. They were hidden,
497
- and the record counts below exclude them.
498
- </p>
499
- ) : null}
500
- </section>
501
-
502
- {/* ONE LIST, CATEGORISED BY FOLDER STRUCTURE (bd startsim-nbhno). The tree
503
- is not a second surface and not a second taxonomy — it is the shelf the
504
- one list is standing on, which is the arrangement every computer user
505
- already knows. When the corpus cannot enumerate folders the aside
506
- simply is not there and this is the single-column list it has always
507
- been; a half-drawn tree would be worse than none. */}
508
- <div className={noTree ? '' : 'grid gap-6 md:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]'}>
509
- {noTree ? null : (
510
- <aside className={`${cn.card} h-max`}>
511
- <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">
512
- Folders
513
- </h2>
514
- <FolderTree
515
- api={api}
516
- selected={folder}
517
- onSelect={openFolder}
518
- classNames={folderClassNames}
519
- onUnavailable={() => setNoTree(true)}
520
- hold={!firstPaint}
521
- />
522
- </aside>
523
- )}
524
-
525
- <section className={cn.section}>
526
- <div className="flex items-baseline justify-between gap-4">
527
- <h2 className={cn.heading}>{folder ? folderName(folder) : 'All documents'}</h2>
528
- <p className={cn.muted}>
529
- {count} record{count === 1 ? '' : 's'}
530
- {count > 0 ? ` · page ${page} of ${lastPage}` : ''}
531
- </p>
532
- </div>
533
-
534
- {/* WHERE YOU ARE. Derived from the open path, which the server returned;
535
- every crumb re-asks the server for that container rather than
536
- reusing anything already on screen. */}
537
- {folder ? (
538
- <nav aria-label="Folder path" className="flex flex-wrap items-center gap-1 text-sm">
539
- <button
540
- type="button"
541
- className="text-gray-500 underline underline-offset-2 hover:text-gray-900"
542
- onClick={() => openFolder(null)}
543
- >
544
- All documents
545
- </button>
546
- {folderTrail(folder).map((crumb, index, all) => (
547
- <React.Fragment key={crumb.path}>
548
- <span aria-hidden="true" className="text-gray-300">/</span>
549
- {index === all.length - 1 ? (
550
- <span className="font-medium text-gray-900" aria-current="page">{crumb.name}</span>
551
- ) : (
552
- <button
553
- type="button"
554
- className="text-gray-500 underline underline-offset-2 hover:text-gray-900"
555
- onClick={() => openFolder(crumb.path)}
556
- >
557
- {crumb.name}
558
- </button>
559
- )}
560
- </React.Fragment>
561
- ))}
562
- {/* THE CONTROL THAT MAKES THE BOUND VISIBLE, rather than a mode the
563
- reader has to infer. Checked, the count beside the folder in the
564
- tree is the count above the list; unchecked, the list is the
565
- shelf and the difference is on screen as a thing they did. */}
566
- <label className="ml-3 flex items-center gap-1.5 text-xs text-gray-600">
567
- <input
568
- type="checkbox"
569
- checked={includeSubfolders}
570
- onChange={(event) => {
571
- setIncludeSubfolders(event.target.checked);
572
- // A narrowing is a filter change: page 3 of the subtree is not
573
- // page 3 of the shelf.
574
- setFilters((prev) => ({ ...prev, page: 1 }));
575
- }}
576
- />
577
- Include subfolders
578
- </label>
579
- </nav>
580
- ) : null}
581
-
582
- {loading && documents.length === 0 ? <p className={cn.muted}>Loading…</p> : null}
583
-
584
- {!loading && documents.length === 0 ? (
585
- // A FOLDER THAT HOLDS ITS DOCUMENTS ONE LEVEL DOWN, with the reader
586
- // having narrowed to the shelf. Zero is the true answer to what they
587
- // asked, but "Nothing matches those filters. Clear them to see
588
- // everything." is the wrong advice — there is no filter to clear, and
589
- // the remedy is one specific thing. So the remedy IS what stands here:
590
- // the control, in the place the sentence was. Same rule as the row's
591
- // Get text button, and the same reason.
592
- folder && !includeSubfolders ? (
593
- <button
594
- type="button"
595
- className={cn.button}
596
- onClick={() => {
597
- setIncludeSubfolders(true);
598
- setFilters((prev) => ({ ...prev, page: 1 }));
599
- }}
600
- >
601
- Include subfolders
602
- </button>
603
- ) : (
604
- <EmptyState
605
- hasFilters={Boolean(
606
- filters.search || filters.source || filters.partyId
607
- || filters.occurredAfter || filters.occurredBefore || folder,
608
- )}
609
- sources={shownSources}
610
- classNames={cn}
611
- />
612
- )
613
- ) : null}
614
-
615
- <div className="space-y-2">
616
- {documents.map((document) => (
617
- // A DIV WRAPPING TWO BUTTONS, not one button wrapping everything.
618
- // The row now carries an action of its own, and a button inside a
619
- // button is invalid HTML that browsers resolve by dropping one of
620
- // them — usually the one you wanted.
621
- <div key={document.id} className={`${cn.row} flex items-start gap-3`}>
622
- <button
623
- type="button"
624
- className="min-w-0 flex-1 text-left"
625
- aria-expanded={selectedId === document.id}
626
- onClick={() => select(selectedId === document.id ? null : document.id)}
627
- >
628
- <div className="flex flex-wrap items-center gap-2">
629
- {/* The source is a BADGE on every row, never a hidden column:
630
- "the AI learned this from a meeting" and "…from a contract
631
- in Drive" are different claims to whoever reads a draft
632
- later. */}
633
- <span className={cn.badge}>{document.sourceLabel || document.source}</span>
634
- <span className="font-medium text-gray-900">{document.title}</span>
635
- </div>
636
- <p className={cn.muted}>
637
- {formatDate(document.occurredAt)}
638
- {document.participants.length
639
- ? ` · ${document.participants.map((party) => party.name).join(', ')}`
640
- : ''}
641
- {document.sections.length
642
- ? ` · ${document.sections.map((section) => section.label).join(', ')}`
643
- : ''}
644
- </p>
645
- {preview(document) ? (
646
- <p className="mt-1 text-sm text-gray-600">{preview(document)}</p>
647
- ) : null}
648
- </button>
649
-
650
- {/* WHERE THE SENTENCE USED TO BE. A row with no captured text said
651
- "No text was captured for this record." — an explanation
652
- standing in the place a control belongs, which tells a reader
653
- what happened and not what they may do. It is a BUTTON now,
654
- and it is disabled when the action genuinely cannot be
655
- performed. Quinn, 2026-08-27: "either have a button to pull the
656
- text, or have it grayed out if we can't do the action. simple
657
- ui." */}
658
- {preview(document) ? null : (
659
- <GetTextButton
660
- document={document}
661
- className={cn.button}
662
- onRequestText={onRequestText}
663
- />
664
- )}
665
- </div>
666
- ))}
667
- </div>
668
-
669
- {count > size ? (
670
- <div className="flex items-center gap-2">
671
- <button
672
- type="button"
673
- className={cn.button}
674
- disabled={page <= 1 || loading}
675
- onClick={() => setFilters((prev) => ({ ...prev, page: Math.max(1, page - 1) }))}
676
- >
677
- Previous
678
- </button>
679
- <button
680
- type="button"
681
- className={cn.button}
682
- disabled={page >= lastPage || loading}
683
- onClick={() => setFilters((prev) => ({ ...prev, page: page + 1 }))}
684
- >
685
- Next
686
- </button>
687
- {/* Paging is a SERVER round trip (CLAUDE.md rule 8) — the browser
688
- never holds the corpus, so this keeps working at any size. */}
689
- <span className={cn.muted}>Page {page} of {lastPage}</span>
690
- </div>
691
- ) : null}
692
- </section>
278
+ </TableToolbar>
279
+
280
+ {selection.folder ? (
281
+ <p className="text-xs text-gray-500" aria-label="Folder path">
282
+ {folderTrail(selection.folder).map((crumb) => crumb.name).join(' / ')}
283
+ </p>
284
+ ) : null}
285
+
286
+ {partyFilter ? (
287
+ <p className="text-xs text-gray-600">
288
+ With {partyFilter.name}{' '}
289
+ <button type="button" className="underline" onClick={() => { setPartyFilter(null); setPage(1); }}>Show everyone</button>
290
+ </p>
291
+ ) : null}
292
+
293
+ {ignored.length ? (
294
+ <p className={cn.warning} role="status">
295
+ This workspace’s data API does not filter by {ignored.join(', ')} yet, so the list below
296
+ is not narrowed by {ignored.length > 1 ? 'those' : 'that'}.
297
+ </p>
298
+ ) : null}
299
+
300
+ {droppedOutOfScope > 0 ? (
301
+ <p className={cn.error} role="alert">
302
+ This workspace’s data API returned {droppedOutOfScope} record{droppedOutOfScope === 1 ? '' : 's'} belonging to
303
+ another workspace. They were hidden, and the record counts below exclude them.
304
+ </p>
305
+ ) : null}
306
+
307
+ <LibraryTable
308
+ rows={documents}
309
+ hidden={emptyColumns(documents, peopleSettled)}
310
+ onOpen={(id) => select(selectedId === id ? null : id)}
311
+ sort={sort}
312
+ onSort={(next) => { setSort(next); setPage(1); }}
313
+ page={page}
314
+ pageSize={size}
315
+ total={count}
316
+ onPage={setPage}
317
+ onPageSize={(next) => { setSize(next); writePageSize('library', next); setPage(1); }}
318
+ loading={loading}
319
+ emptyMessage={loading && documents.length === 0 ? 'Loading…' : emptyMessage}
320
+ />
321
+ </section>
693
322
  </div>
694
323
 
695
324
  {selected ? (
@@ -699,12 +328,16 @@ export function LibraryPage({
699
328
  api={api}
700
329
  classNames={cn}
701
330
  onClose={() => select(null)}
702
- onFilterByParty={(partyId) => update({ partyId })}
331
+ onFilterByParty={(partyId) => {
332
+ const person = selected.participants.find((p) => String(p.id) === String(partyId));
333
+ setPartyFilter({ id: partyId, name: person?.name ?? 'this person' });
334
+ setPage(1);
335
+ select(null);
336
+ }}
703
337
  onOpenPlan={onOpenPlan}
704
338
  />
705
339
  ) : null}
706
340
 
707
- {/* Asked for, and not shown — said out loud rather than left blank. */}
708
341
  {!selected && selectError ? (
709
342
  <section className={cn.card} aria-label="Record">
710
343
  <div className="flex items-start justify-between gap-4">
@@ -716,95 +349,3 @@ export function LibraryPage({
716
349
  </div>
717
350
  );
718
351
  }
719
-
720
- // ---------------------------------------------------------------------------
721
- // the row's own action
722
- // ---------------------------------------------------------------------------
723
-
724
- /**
725
- * "Get text" on a record that has none — ENABLED when the corpus can fetch it,
726
- * GREYED OUT when it cannot (bd startsim-ei8gm.5).
727
- *
728
- * THIS REPLACED A SENTENCE, and the swap is the point. The row used to read
729
- * "No text was captured for this record." in exactly this slot. That is an
730
- * explanation where a control belongs: it answers "what happened" when the
731
- * reader was asking "what can I do", and it is the thing Quinn objected to in
732
- * those words — "don't say stupid shit like 'no text blah blah'. either have a
733
- * button to pull the text, or have it grayed out if we can't do the action.
734
- * simple ui." A disabled control answers the real question in the standard
735
- * vocabulary of every desktop application ever written.
736
- *
737
- * DISABLED IS THE HONEST STATE TODAY, not a placeholder. Content is opt-in and
738
- * never the default (bd startsim-h6xnu) — the corpus owes what exists, where it
739
- * lives and findability, and pulling every file's bytes is the expensive,
740
- * privacy-loaded half that was deliberately not built. The route that would make
741
- * this live is bd startsim-99g8.2. When it lands, an app passes `onRequestText`
742
- * and the same control wakes up; nothing here changes.
743
- *
744
- * `title` CARRIES THE WHY, and a tooltip on a control is not the sentence that
745
- * was removed: it is attached to the thing it is about, costs no row space, and
746
- * a reader who does not care never reads it. `aria-disabled` is not used in its
747
- * place — a genuinely inert control should not be focusable-and-lying.
748
- */
749
- function GetTextButton({
750
- document, className, onRequestText,
751
- }: {
752
- document: SourceDocument;
753
- className: string;
754
- onRequestText?: (document: SourceDocument) => void | Promise<void>;
755
- }) {
756
- const [busy, setBusy] = React.useState(false);
757
- const [failed, setFailed] = React.useState('');
758
- const can = Boolean(onRequestText);
759
-
760
- return (
761
- <button
762
- type="button"
763
- className={`${className} shrink-0 self-start`}
764
- disabled={!can || busy}
765
- title={
766
- can
767
- ? `Fetch the text of ${document.title}`
768
- : 'This workspace does not pull file contents. Nothing has been extracted from this record.'
769
- }
770
- onClick={() => {
771
- if (!onRequestText) return;
772
- setBusy(true);
773
- setFailed('');
774
- void Promise.resolve(onRequestText(document))
775
- .catch((err: unknown) => setFailed(
776
- (err as { message?: string })?.message || 'Could not fetch the text.',
777
- ))
778
- .finally(() => setBusy(false));
779
- }}
780
- >
781
- {busy ? 'Getting…' : failed ? 'Retry' : 'Get text'}
782
- </button>
783
- );
784
- }
785
-
786
- // ---------------------------------------------------------------------------
787
- // empty state
788
- // ---------------------------------------------------------------------------
789
-
790
- /**
791
- * Three different nothings, because they need three different actions: no
792
- * sources connected, sources connected but nothing arrived, and a filter that
793
- * matched nothing. One generic "No results" would send the user to the wrong
794
- * place in two of the three.
795
- */
796
- function EmptyState({
797
- hasFilters, sources, classNames: cn,
798
- }: { hasFilters: boolean; sources: SourceFreshness[]; classNames: Record<LibrarySlot, string> }) {
799
- if (hasFilters) {
800
- return <p className={cn.muted}>Nothing matches those filters. Clear them to see everything.</p>;
801
- }
802
- if (sources.length === 0) {
803
- return (
804
- <p className={cn.muted}>
805
- Nothing has been pulled in yet. Connect a source and its records appear here.
806
- </p>
807
- );
808
- }
809
- return <p className={cn.muted}>Nothing has arrived yet. The table above shows when each source syncs next.</p>;
810
- }