@startsimpli/integrations 0.2.72 → 0.2.73

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/README.md CHANGED
@@ -214,6 +214,8 @@ Rules every list tab follows: one server request per page (never load a list and
214
214
 
215
215
  **Shipped tabs.** `trackerTab({ api, notesKey })` (to-dos: Outstanding / Overdue / Changed this week / Closed, project Select, search, swipe or tap to mark done, detail with the source quote and an "Open note" link) and `homeTab({ api, brand, tabs, recordKey })` (the web Home's counts and latest arrivals, a "Record a note" button). Controllers (`createTrackerController`, `createTrackerDetailController`, `createHomeController`) are pure and tested against `createFakeNativeCorpusApi()`.
216
216
 
217
+ **Library and Ask tabs** (`src/native/screens/`, bd startsim-23np6.1.5): `libraryAskTabs(api)` returns both tabs for the `tabs` array. `libraryTab(api)` is documents list -> document (server-side search, source / type / project filters, newest / oldest, infinite scroll, Markdown body, change project through `corpus/filing.ts`); `askTab(api)` is project-scoped Ask with Markdown answers and citations (a citation calls `openTab('library', id)`). Both are controllers (`createLibraryController`, `createAskController`: pure, vitest) under screens that use `@startsimpli/ui-native` only. The words (failure messages, answer caveats, provenance) live in `corpus/view-text.ts` and are shared with the web `LibraryPage` / `AskPage`. `createFakeLibraryApi()` is the shared fake plus a few extra documents for simulator checks. Generate mode (web AskPage) is not on the phone.
218
+
217
219
  Not wired yet: `mcpTokens` and `connectionsMe` (`src/api/*`) call a module-global `request()` that does not use `authorizedFetch`; the Connections / Connect Claude tabs need a `create*Api(fetch)` factory first.
218
220
 
219
221
  ## Verification
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.72",
3
+ "version": "0.2.73",
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",
@@ -0,0 +1,31 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ askFailureMessage, documentPreview, droppedNotice, openFailureMessage, providerSentence, readFailureMessage, stripMarkdown, unresolvedNotice,
4
+ } from '../corpus/view-text';
5
+
6
+ describe('view-text (shared by the web composers and the native screens)', () => {
7
+ it('flattens markdown', () => {
8
+ expect(stripMarkdown('## Decisions\n\n**$4,800** per [month](http://x)\n- one')).toBe('Decisions\n\n$4,800 per month\none');
9
+ });
10
+ it('names the failure: 401, 403, 404 and the rest each read differently', () => {
11
+ expect(readFailureMessage({ status: 401 })).toContain('Sign in again');
12
+ expect(readFailureMessage({ status: 403 })).toContain('do not have access');
13
+ expect(openFailureMessage({ status: 404 }, 'abc')).toContain('(abc)');
14
+ expect(openFailureMessage(new Error('boom'), 'abc')).toBe('boom');
15
+ expect(askFailureMessage({})).toBe('That question could not be answered right now.');
16
+ });
17
+ it('previews from the summary, flattened and cut', () => {
18
+ const doc = { summary: '# Title\n' + 'word '.repeat(80), body: '', sections: [] } as never;
19
+ const p = documentPreview(doc, 40);
20
+ expect(p.startsWith('Title')).toBe(true);
21
+ expect(p.endsWith('…')).toBe(true);
22
+ });
23
+ it('says who answered, plainly', () => {
24
+ expect(providerSentence({ provider: 'anthropic', model: 'x', live: true })).toBe('Answered by anthropic · x');
25
+ expect(providerSentence({ provider: 'none', model: '', live: false })).toContain('No model is configured');
26
+ });
27
+ it('notices are empty when there is nothing to say', () => {
28
+ expect(unresolvedNotice({ unresolvedCitations: [] } as never)).toBe('');
29
+ expect(droppedNotice({ droppedOutOfScope: 1 } as never)).toBe('1 record from another workspace were returned by the data API and excluded before answering.');
30
+ });
31
+ });
@@ -28,21 +28,7 @@ import * as React from 'react';
28
28
  * For places that need a STRING rather than elements — a truncated one-line
29
29
  * preview, a title, an `aria-label`. Same syntax coverage as the renderer.
30
30
  */
31
- export function stripMarkdown(text: string): string {
32
- if (!text) return '';
33
- return text
34
- .replace(/```[\s\S]*?```/g, (block) => block.replace(/```[^\n]*\n?/g, ''))
35
- .replace(/^\s{0,3}#{1,6}\s+/gm, '')
36
- .replace(/^\s{0,3}([-*_])\s*\1\s*\1[-*_\s]*$/gm, '')
37
- .replace(/^\s{0,3}[-*+]\s+/gm, '')
38
- .replace(/^\s{0,3}>\s?/gm, '')
39
- .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
40
- .replace(/\*\*([^*]+)\*\*/g, '$1')
41
- .replace(/__([^_]+)__/g, '$1')
42
- .replace(/`([^`]+)`/g, '$1')
43
- .replace(/[ \t]+\n/g, '\n')
44
- .trim();
45
- }
31
+ export { stripMarkdown } from '../corpus/view-text';
46
32
 
47
33
  /** `**bold**`, `` `code` `` and `[text](url)` inside one line of text. */
48
34
  function inline(text: string, keyPrefix: string): React.ReactNode[] {
@@ -32,6 +32,10 @@
32
32
  import * as React from 'react';
33
33
 
34
34
  import { Markdown, stripMarkdown } from '../Markdown';
35
+ import {
36
+ UNCITED_NOTICE, askFailureMessage as failureMessage, droppedNotice, freshnessNotice,
37
+ providerSentence, unresolvedNotice, withheldNotice,
38
+ } from '../../corpus/view-text';
35
39
  import type {
36
40
  AskMode,
37
41
  AskRequest,
@@ -94,13 +98,6 @@ const MODE_LABELS: Record<AskMode, { tab: string; prompt: string; action: string
94
98
  },
95
99
  };
96
100
 
97
- function failureMessage(err: unknown): string {
98
- const status = (err as { status?: number })?.status;
99
- if (status === 403) return 'You do not have access to this workspace’s records.';
100
- if (status === 401) return 'Your session has expired. Sign in again.';
101
- return (err as { message?: string })?.message || 'That question could not be answered right now.';
102
- }
103
-
104
101
  export function AskPage({
105
102
  api,
106
103
  scope,
@@ -269,7 +266,9 @@ function AnswerPanel({
269
266
  saveState: 'idle' | 'saving' | 'saved';
270
267
  onSave: () => void;
271
268
  }) {
272
- const unhealthy = (result.freshness ?? []).filter((source) => source.status !== 'ok');
269
+ const freshness = freshnessNotice(result);
270
+ const withheld = withheldNotice(result);
271
+ const unresolved = unresolvedNotice(result);
273
272
 
274
273
  if (result.status === 'no_evidence') {
275
274
  return (
@@ -286,29 +285,16 @@ function AnswerPanel({
286
285
  return (
287
286
  <section className={cn.card} aria-label="Answer">
288
287
  {result.status === 'uncited' ? (
289
- <p className={cn.warning} role="alert">
290
- This answer could not be traced to any of your records, so it is shown as unsourced.
291
- Do not rely on it for anything you would sign.
292
- </p>
288
+ <p className={cn.warning} role="alert">{UNCITED_NOTICE}</p>
293
289
  ) : null}
294
290
 
295
- {unhealthy.length ? (
296
- <p className={cn.warning} role="status">
297
- Answered from a corpus that is not fully current:{' '}
298
- {unhealthy.map((source) => `${source.label} (${source.status})`).join(', ')}.
299
- </p>
300
- ) : null}
291
+ {freshness ? <p className={cn.warning} role="status">{freshness}</p> : null}
301
292
 
302
293
  {/* An answer built from a partly-withheld record has to say so
303
294
  (bd startsim-768w.38.33) — otherwise "your corpus has nothing about
304
295
  that" and "you were not shown the part that does" are the same
305
296
  sentence, and the second one is the dangerous one to believe. */}
306
- {result.withheldFields?.length ? (
307
- <p className={cn.warning} role="status">
308
- Some records were only partly shared with you ({result.withheldFields.join(', ')}),
309
- so this answer may be incomplete.
310
- </p>
311
- ) : null}
297
+ {withheld ? <p className={cn.warning} role="status">{withheld}</p> : null}
312
298
 
313
299
  {/* A model asked for prose answers in Markdown. Rendering it as literal
314
300
  text puts "**$4,800**" on the screen, which reads as the product
@@ -363,13 +349,7 @@ function AnswerPanel({
363
349
  ))}
364
350
  </div>
365
351
 
366
- {result.unresolvedCitations.length ? (
367
- <p className={`mt-3 ${cn.warning}`} role="alert">
368
- The model also cited {result.unresolvedCitations.length} record
369
- {result.unresolvedCitations.length === 1 ? '' : 's'} that were never given to it
370
- ({result.unresolvedCitations.join(', ')}). Those were discarded — treat the answer with care.
371
- </p>
372
- ) : null}
352
+ {unresolved ? <p className={`mt-3 ${cn.warning}`} role="alert">{unresolved}</p> : null}
373
353
 
374
354
  <ConsideredList result={result} classNames={cn} onOpenDocument={onOpenDocument} />
375
355
  <ProvenanceFooter result={result} classNames={cn} />
@@ -417,28 +397,6 @@ function ConsideredList({
417
397
  );
418
398
  }
419
399
 
420
- /**
421
- * Who answered, said plainly.
422
- *
423
- * THREE CASES, not two (bd startsim-768w.38.21). A live model names itself. A
424
- * STUB says it is a stub. And a workspace with NO provider configured is not a
425
- * stub at all — "Answered by a none stub ((provider default))" was neither
426
- * English nor true. Every branch keeps the `live: false` honesty; the point is
427
- * to say the true thing clearly, not to soften it.
428
- */
429
- function providerSentence(provider: AskResult['provider']): string {
430
- const model = provider.model?.trim() ?? '';
431
- if (provider.live) {
432
- return model ? `Answered by ${provider.provider} · ${model}` : `Answered by ${provider.provider}`;
433
- }
434
- if (!provider.provider || provider.provider === 'none') {
435
- return 'No model is configured for this workspace — no live model was called.';
436
- }
437
- return model
438
- ? `Answered by a ${provider.provider} stub (${model}) — no live model was called`
439
- : `Answered by a ${provider.provider} stub — no live model was called`;
440
- }
441
-
442
400
  function ProvenanceFooter({
443
401
  result, classNames: cn,
444
402
  }: { result: AskResult; classNames: Record<AskSlot, string> }) {
@@ -448,12 +406,7 @@ function ProvenanceFooter({
448
406
  {/* A non-zero drop means something upstream returned rows from another
449
407
  workspace. It is stated rather than swallowed, because the guard
450
408
  catching it is good news about the guard and bad news about the API. */}
451
- {result.droppedOutOfScope > 0 ? (
452
- <p className={cn.error} role="status">
453
- {result.droppedOutOfScope} record{result.droppedOutOfScope === 1 ? '' : 's'} from another
454
- workspace were returned by the data API and excluded before answering.
455
- </p>
456
- ) : null}
409
+ {droppedNotice(result) ? <p className={cn.error} role="status">{droppedNotice(result)}</p> : null}
457
410
  </div>
458
411
  );
459
412
  }
@@ -32,7 +32,7 @@ import { formatDate, summaryOf } from '../documentText';
32
32
  import { FolderTree, folderTrail } from '../FolderTree';
33
33
  import { folderName } from '../../corpus/entities';
34
34
  import type { FolderTreeSlot } from '../FolderTree';
35
- import { stripMarkdown } from '../Markdown';
35
+ import { documentPreview as preview, openFailureMessage, readFailureMessage } from '../../corpus/view-text';
36
36
  import { enforceScope } from '../../corpus/retrieval';
37
37
  import type {
38
38
  CorpusApi,
@@ -108,37 +108,6 @@ const DEFAULTS: Record<LibrarySlot, string> = {
108
108
  warning: 'rounded-md border border-amber-300 bg-amber-50 p-2 text-sm text-amber-800',
109
109
  };
110
110
 
111
- /** A refusal must read as a refusal, not as an empty corpus. */
112
- function readFailureMessage(err: unknown): string {
113
- const status = (err as { status?: number })?.status;
114
- if (status === 403) return 'You do not have access to this workspace’s records.';
115
- if (status === 401) return 'Your session has expired. Sign in again.';
116
- return (err as { message?: string })?.message || 'Could not load the library.';
117
- }
118
-
119
- /**
120
- * Why the record the screen was asked to open is not on the screen
121
- * (bd startsim-2lt8y).
122
- *
123
- * FOUR ANSWERS, NOT ONE, and the branch is the point: "sign in again", "you may
124
- * not see this", "that record is not here" and "something went wrong" send the
125
- * reader to four different places, and only one of them is true at a time.
126
- * Calling an expired session a missing record is a different lie from the one
127
- * this bead is fixing, not a smaller version of it.
128
- *
129
- * The id is NAMED because it came out of the address bar. A citation or a
130
- * bookmark that no longer resolves is worth being able to quote back to
131
- * somebody, and "a record" is not quotable.
132
- */
133
- function openFailureMessage(err: unknown, id: string): string {
134
- const status = (err as { status?: number })?.status;
135
- if (status === 404) {
136
- return `That record could not be found in this workspace (${id}). It may have been removed, or it may not be one you can see.`;
137
- }
138
- if (status === 401 || status === 403) return readFailureMessage(err);
139
- return (err as { message?: string })?.message || `That record could not be opened (${id}).`;
140
- }
141
-
142
111
  function relative(value: string | null | undefined, now: number): string {
143
112
  if (!value) return 'never';
144
113
  const at = Date.parse(value);
@@ -151,19 +120,6 @@ function relative(value: string | null | undefined, now: number): string {
151
120
  return `${Math.round(hours / 24)}d ago`;
152
121
  }
153
122
 
154
- /**
155
- * A row's one-line preview. The Markdown is FLATTENED rather than rendered
156
- * here — a truncated heading and half a bold span are worse than plain prose,
157
- * and the row is a summary, not the document.
158
- */
159
- function preview(document: SourceDocument, length = 180): string {
160
- const text = stripMarkdown(
161
- summaryOf(document) || document.body || document.sections[0]?.text || '',
162
- );
163
- if (!text) return '';
164
- return text.length > length ? `${text.slice(0, length).trim()}…` : text;
165
- }
166
-
167
123
  // ---------------------------------------------------------------------------
168
124
 
169
125
  export function LibraryPage({
@@ -287,6 +287,7 @@ const FILTER_PARAMS: Array<[keyof CommitmentQuery, string[]]> = [
287
287
  const DOCUMENT_FILTER_PARAMS: Array<[keyof DocumentQuery, string[]]> = [
288
288
  ['search', ['search']],
289
289
  ['source', ['source', 'attr.source']],
290
+ ['subtype', ['attr.subtype']],
290
291
  ['partyId', ['party', 'related_to']],
291
292
  ['focus', ['related_to']],
292
293
  ['occurredAfter', ['occurred_after', 'attr.occurred_at__gte']],
@@ -386,9 +387,12 @@ function params(query: DocumentQuery, type: string) {
386
387
  // THE FOLDER BOUNDS, and only ever one of them: `attr.path` is the shelf and
387
388
  // `attr.path__under` the subtree; sending both would AND an exact match with
388
389
  // its own subtree. The composer chooses; this refuses to send a contradiction.
389
- attr: query.underFolder
390
- ? { path__under: query.underFolder }
391
- : query.folder ? { path: query.folder } : undefined,
390
+ attr: {
391
+ ...(query.underFolder
392
+ ? { path__under: query.underFolder }
393
+ : query.folder ? { path: query.folder } : {}),
394
+ ...(query.subtype ? { subtype: query.subtype } : {}),
395
+ },
392
396
  });
393
397
  }
394
398
 
@@ -424,7 +428,7 @@ function appliedFilters(
424
428
  supported: Array<string>,
425
429
  ): string[] {
426
430
  const requested = ([
427
- 'search', 'source', 'partyId', 'occurredAfter', 'occurredBefore', 'folder', 'underFolder',
431
+ 'search', 'source', 'subtype', 'partyId', 'occurredAfter', 'occurredBefore', 'folder', 'underFolder',
428
432
  ] as const).filter((key) => Boolean(query[key]));
429
433
  return requested.filter((key) => supported.includes(key));
430
434
  }
@@ -340,6 +340,7 @@ export function toParty(entity: TenantEntity, fallbackScope: CorpusScope): Party
340
340
  ...(emails.length ? { emails } : {}),
341
341
  source: asText(pick(data, 'source', 'source_key', 'sourceKey')) || 'unknown',
342
342
  sourceLabel: asText(pick(data, 'source_label', 'sourceLabel')) || undefined,
343
+ ...(asText(pick(data, 'subtype')) ? { subtype: asText(pick(data, 'subtype')) } : {}),
343
344
  sourceRef:
344
345
  asText(pick(data, 'source_ref', 'sourceRef')) ||
345
346
  asText(entity.external_id ?? entity.externalId) ||
@@ -126,6 +126,8 @@ export interface SourceDocument {
126
126
  source: SourceKey;
127
127
  /** Human name of the source, from the catalog — never hardcoded per vendor. */
128
128
  sourceLabel: string;
129
+ /** What kind of record it is (`voice_note`, `meeting`, `document`), when the source says. */
130
+ subtype?: string;
129
131
  /** The vendor's own id, so a row can be traced back out of the system. */
130
132
  sourceRef: string;
131
133
  /** Deep link into the vendor, when it has one. */
@@ -302,6 +304,8 @@ export interface DocumentQuery {
302
304
  */
303
305
  order?: 'relevance' | 'recent' | 'oldest';
304
306
  source?: SourceKey;
307
+ /** What kind of record: `voice_note`, `meeting`, `document`... Goes out as `?attr.subtype=`. */
308
+ subtype?: string;
305
309
  partyId?: string;
306
310
  /**
307
311
  * THE DOCUMENTS FILED UNDER ONE PROJECT (a focus), via the `about_focus` edge.
@@ -0,0 +1,113 @@
1
+ /**
2
+ * The words the Library and Ask surfaces say, as pure functions, so the web
3
+ * composers (`LibraryPage`, `AskPage`) and the native screens say them the same
4
+ * way instead of each keeping a copy that drifts (bd startsim-23np6.1.5).
5
+ *
6
+ * No React and no DOM in here: the native bundle imports it.
7
+ */
8
+ import { summaryOf } from '../components/documentText';
9
+ import type { AskResult, SourceDocument } from './types';
10
+
11
+ /** Markdown flattened to plain prose, for one-line previews, titles and labels. */
12
+ export function stripMarkdown(text: string): string {
13
+ if (!text) return '';
14
+ return text
15
+ .replace(/```[\s\S]*?```/g, (block) => block.replace(/```[^\n]*\n?/g, ''))
16
+ .replace(/^\s{0,3}#{1,6}\s+/gm, '')
17
+ .replace(/^\s{0,3}([-*_])\s*\1\s*\1[-*_\s]*$/gm, '')
18
+ .replace(/^\s{0,3}[-*+]\s+/gm, '')
19
+ .replace(/^\s{0,3}>\s?/gm, '')
20
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
21
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
22
+ .replace(/__([^_]+)__/g, '$1')
23
+ .replace(/`([^`]+)`/g, '$1')
24
+ .replace(/[ \t]+\n/g, '\n')
25
+ .trim();
26
+ }
27
+
28
+ const statusOf = (err: unknown): number | undefined => (err as { status?: number })?.status;
29
+ const messageOf = (err: unknown): string | undefined => (err as { message?: string })?.message;
30
+
31
+ /** A refusal must read as a refusal, not as an empty corpus. */
32
+ export function readFailureMessage(err: unknown): string {
33
+ const status = statusOf(err);
34
+ if (status === 403) return 'You do not have access to this workspace’s records.';
35
+ if (status === 401) return 'Your session has expired. Sign in again.';
36
+ return messageOf(err) || 'Could not load the library.';
37
+ }
38
+
39
+ /**
40
+ * Why the record the screen was asked to open is not on the screen (bd
41
+ * startsim-2lt8y): four answers, because "sign in again", "you may not see
42
+ * this", "that record is not here" and "something went wrong" send the reader to
43
+ * four different places. The id is named because it came from a link.
44
+ */
45
+ export function openFailureMessage(err: unknown, id: string): string {
46
+ const status = statusOf(err);
47
+ if (status === 404) {
48
+ return `That record could not be found in this workspace (${id}). It may have been removed, or it may not be one you can see.`;
49
+ }
50
+ if (status === 401 || status === 403) return readFailureMessage(err);
51
+ return messageOf(err) || `That record could not be opened (${id}).`;
52
+ }
53
+
54
+ export function askFailureMessage(err: unknown): string {
55
+ const status = statusOf(err);
56
+ if (status === 403) return 'You do not have access to this workspace’s records.';
57
+ if (status === 401) return 'Your session has expired. Sign in again.';
58
+ return messageOf(err) || 'That question could not be answered right now.';
59
+ }
60
+
61
+ /**
62
+ * A row's one-line preview. The Markdown is FLATTENED rather than rendered: a
63
+ * truncated heading and half a bold span are worse than plain prose.
64
+ */
65
+ export function documentPreview(document: SourceDocument, length = 180): string {
66
+ const text = stripMarkdown(summaryOf(document) || document.body || document.sections[0]?.text || '');
67
+ if (!text) return '';
68
+ return text.length > length ? `${text.slice(0, length).trim()}…` : text;
69
+ }
70
+
71
+ /** The caveats an answer carries, each said once and in the same words everywhere. */
72
+ export const UNCITED_NOTICE =
73
+ 'This answer could not be traced to any of your records, so it is shown as unsourced. Do not rely on it for anything you would sign.';
74
+
75
+ export function freshnessNotice(result: AskResult): string {
76
+ const unhealthy = (result.freshness ?? []).filter((source) => source.status !== 'ok');
77
+ if (!unhealthy.length) return '';
78
+ return `Answered from a corpus that is not fully current: ${unhealthy.map((s) => `${s.label} (${s.status})`).join(', ')}.`;
79
+ }
80
+
81
+ export function withheldNotice(result: AskResult): string {
82
+ if (!result.withheldFields?.length) return '';
83
+ return `Some records were only partly shared with you (${result.withheldFields.join(', ')}), so this answer may be incomplete.`;
84
+ }
85
+
86
+ export function unresolvedNotice(result: AskResult): string {
87
+ const n = result.unresolvedCitations.length;
88
+ if (!n) return '';
89
+ return `The model also cited ${n} record${n === 1 ? '' : 's'} that were never given to it (${result.unresolvedCitations.join(', ')}). Those were discarded — treat the answer with care.`;
90
+ }
91
+
92
+ export function droppedNotice(result: AskResult): string {
93
+ const n = result.droppedOutOfScope;
94
+ if (!(n > 0)) return '';
95
+ return `${n} record${n === 1 ? '' : 's'} from another workspace were returned by the data API and excluded before answering.`;
96
+ }
97
+
98
+ /**
99
+ * Who answered, said plainly. A live model names itself, a stub says it is a
100
+ * stub, and a workspace with no provider is not a stub at all.
101
+ */
102
+ export function providerSentence(provider: AskResult['provider']): string {
103
+ const model = provider.model?.trim() ?? '';
104
+ if (provider.live) {
105
+ return model ? `Answered by ${provider.provider} · ${model}` : `Answered by ${provider.provider}`;
106
+ }
107
+ if (!provider.provider || provider.provider === 'none') {
108
+ return 'No model is configured for this workspace — no live model was called.';
109
+ }
110
+ return model
111
+ ? `Answered by a ${provider.provider} stub (${model}) — no live model was called`
112
+ : `Answered by a ${provider.provider} stub — no live model was called`;
113
+ }
@@ -11,13 +11,17 @@ export interface NotesShellProps {
11
11
  goLabel?: string;
12
12
  notesLabel?: string;
13
13
  /** Open on the Notes tab (default GO). For screenshots, deep links and tests. */
14
- initialTab?: 'go' | 'notes';
14
+ initialTab?: string;
15
15
  /** Open straight on one note (implies the Notes tab). */
16
16
  initialNoteId?: string;
17
+ /** More tabs after Notes: `[...libraryAskTabs(api)]`, a Tracker tab, and so on. */
18
+ extraTabs?: FoundryTab[];
19
+ /** Open straight on a detail of any tab (a `-tgTab` / `-tgDetail` launch arg). Wins over `initialNoteId`. */
20
+ initialDetail?: { tab: string; id: string };
17
21
  }
18
22
 
19
23
  /** The first preset of `FoundryTabsShell`: GO (the app's record screen) and Notes (list -> detail). */
20
- export function NotesShell({ go, controller, goLabel = 'GO', notesLabel = 'Notes', initialTab, initialNoteId }: NotesShellProps) {
24
+ export function NotesShell({ go, controller, goLabel = 'GO', notesLabel = 'Notes', initialTab, initialNoteId, extraTabs, initialDetail }: NotesShellProps) {
21
25
  const tabs = useMemo<FoundryTab[]>(() => [
22
26
  { key: 'go', label: goLabel, safeArea: false, render: () => go },
23
27
  {
@@ -26,14 +30,15 @@ export function NotesShell({ go, controller, goLabel = 'GO', notesLabel = 'Notes
26
30
  ? <NoteDetailScreen controller={controller} noteId={route.id} onBack={back} />
27
31
  : <NotesListScreen controller={controller} onOpen={(n) => push(n.id)} />,
28
32
  },
33
+ ...(extraTabs ?? []),
29
34
  // `go` is a fresh element each render; the shell re-renders the tab list every time anyway.
30
35
  // eslint-disable-next-line react-hooks/exhaustive-deps
31
- ], [go, controller, goLabel, notesLabel]);
36
+ ], [go, controller, goLabel, notesLabel, extraTabs]);
32
37
  return (
33
38
  <FoundryTabsShell
34
39
  tabs={tabs}
35
40
  initialTab={initialTab}
36
- initialDetail={initialNoteId ? { tab: 'notes', id: initialNoteId } : undefined}
41
+ initialDetail={initialDetail ?? (initialNoteId ? { tab: 'notes', id: initialNoteId } : undefined)}
37
42
  />
38
43
  );
39
44
  }
@@ -181,10 +181,16 @@ export function createFakeTenantHttp(options: FakeTenantOptions = {}): FakeTenan
181
181
  // Re-run the row filter over every page: `list` is paged, so ask for it all in-process.
182
182
  const rows = (base as { results: TenantEntity[] }).results;
183
183
  const attr = String(params.attr ?? '');
184
+ const flat = params.under === undefined;
184
185
  const under = String(params.under ?? '/').replace(/\/+$/, '');
185
186
  const groups = new Map<string, { count: number; has_children: boolean }>();
186
187
  for (const e of rows) {
187
188
  const value = String(dataOf(e)[attr] ?? '');
189
+ if (flat) {
190
+ // No `under`: a plain distinct-value count (a source or a subtype), not a folder level.
191
+ if (value) { const g = groups.get(value) ?? { count: 0, has_children: false }; g.count += 1; groups.set(value, g); }
192
+ continue;
193
+ }
188
194
  if (!value || (under && value !== under && !value.startsWith(`${under}/`))) continue;
189
195
  const rest = value.slice(under.length).replace(/^\//, '');
190
196
  const first = rest.split('/')[0];
@@ -32,3 +32,12 @@ export { trackerTab, type TrackerTabOptions } from './tracker/tab';
32
32
  export * from './home/controller';
33
33
  export { HomeScreen, type HomeScreenProps } from './home/HomeScreen';
34
34
  export { homeTab, DEFAULT_HOME_TYPES, type HomeTabOptions } from './home/tab';
35
+ export { createStore, errorMessage } from './screens/store';
36
+ export * from './screens/library/controller';
37
+ export * from './screens/library/fake-library';
38
+ export { LibraryListScreen, type LibraryListScreenProps } from './screens/library/LibraryListScreen';
39
+ export { LibraryDetailScreen, type LibraryDetailScreenProps } from './screens/library/LibraryDetailScreen';
40
+ export * from './screens/ask/answer-view';
41
+ export * from './screens/ask/controller';
42
+ export { AskScreen, type AskScreenProps } from './screens/ask/AskScreen';
43
+ export * from './screens/tabs';
@@ -0,0 +1,135 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { AskRequest, AskResult, CorpusAskApi } from '../../../corpus/types';
3
+ import { answerView } from '../ask/answer-view';
4
+ import { createAskController } from '../ask/controller';
5
+ import { createFakeLibraryApi } from '../library/fake-library';
6
+
7
+ const scope = { orgId: 'tandem' };
8
+ const provider = { provider: 'fixture', model: 'fixture-echo', live: false };
9
+ const result = (over: Partial<AskResult> = {}): AskResult => ({
10
+ status: 'answered', answer: 'Acme renews at **$4,800**.', citations: [], considered: [],
11
+ unresolvedCitations: [], droppedOutOfScope: 0, provider, ...over,
12
+ } as AskResult);
13
+
14
+ function scripted(replies: Array<AskResult | Error>) {
15
+ const seen: AskRequest[] = [];
16
+ const api: CorpusAskApi = {
17
+ async ask(request) {
18
+ seen.push(request);
19
+ const next = replies.shift()!;
20
+ if (next instanceof Error) throw next;
21
+ return next;
22
+ },
23
+ };
24
+ return { api, seen };
25
+ }
26
+ const listProjects = async () => [{ id: 'fma', title: 'Marketing agents' }, { id: 'f287', title: '287A' }];
27
+
28
+ describe('ask controller', () => {
29
+ it('sends the question in ask mode with the tenant scope, and shows the answer', async () => {
30
+ const { api, seen } = scripted([result()]);
31
+ const ask = createAskController({ api, scope });
32
+ await ask.send(' What did Acme agree? ');
33
+ expect(seen).toEqual([{ question: 'What did Acme agree?', mode: 'ask', scope }]);
34
+ const [user, assistant] = ask.getState().messages;
35
+ expect(user).toMatchObject({ role: 'user', text: 'What did Acme agree?' });
36
+ expect(assistant).toMatchObject({ role: 'assistant', status: 'done', text: 'Acme renews at **$4,800**.' });
37
+ expect(ask.getState().busy).toBe(false);
38
+ });
39
+
40
+ it('scopes to a project server-side via filters.focus, and back to all projects', async () => {
41
+ const { api, seen } = scripted([result(), result()]);
42
+ const ask = createAskController({ api, scope, listProjects });
43
+ await ask.start();
44
+ expect(ask.getState().projects).toEqual([{ id: 'fma', title: 'Marketing agents' }, { id: 'f287', title: '287A' }]);
45
+ ask.setProject('fma');
46
+ await ask.send('status?');
47
+ expect(seen[0].filters).toEqual({ focus: 'fma' });
48
+ ask.setProject(null);
49
+ await ask.send('and overall?');
50
+ expect(seen[1].filters).toBeUndefined();
51
+ });
52
+
53
+ it('ignores an empty question and a second send while one is in flight', async () => {
54
+ let release!: (r: AskResult) => void;
55
+ const calls: string[] = [];
56
+ const api: CorpusAskApi = { ask: (r) => { calls.push(r.question); return new Promise((res) => { release = res; }); } };
57
+ const ask = createAskController({ api, scope });
58
+ await ask.send(' ');
59
+ expect(calls).toEqual([]);
60
+ const first = ask.send('one');
61
+ expect(ask.getState().busy).toBe(true);
62
+ expect(ask.getState().messages.at(-1)).toMatchObject({ role: 'assistant', status: 'pending' });
63
+ await ask.send('two');
64
+ expect(calls).toEqual(['one']);
65
+ release(result());
66
+ await first;
67
+ expect(ask.getState().busy).toBe(false);
68
+ });
69
+
70
+ it('a failed ask is an error on that answer, with a reason, and retry asks it again', async () => {
71
+ const { api, seen } = scripted([Object.assign(new Error('x'), { status: 403 }), result({ answer: 'Second time.' })]);
72
+ const ask = createAskController({ api, scope });
73
+ await ask.send('who?');
74
+ const failed = ask.getState().messages[1];
75
+ expect(failed).toMatchObject({ status: 'error', error: 'You do not have access to this workspace’s records.' });
76
+ await ask.retry(failed.id);
77
+ expect(seen.map((r) => r.question)).toEqual(['who?', 'who?']);
78
+ const messages = ask.getState().messages;
79
+ expect(messages).toHaveLength(2);
80
+ expect(messages[1]).toMatchObject({ status: 'done', text: 'Second time.' });
81
+ });
82
+
83
+ it('retry uses the project the question was asked under', async () => {
84
+ const { api, seen } = scripted([new Error('boom'), result()]);
85
+ const ask = createAskController({ api, scope, listProjects });
86
+ ask.setProject('fma');
87
+ await ask.send('q');
88
+ ask.setProject(null);
89
+ await ask.retry(ask.getState().messages[1].id);
90
+ expect(seen[1].filters).toEqual({ focus: 'fma' });
91
+ });
92
+
93
+ it('works end to end over the fake tenant: the answer cites the documents it used', async () => {
94
+ const fake = createFakeLibraryApi();
95
+ const ask = createAskController({ api: fake.ask, scope: fake.scope, listProjects: async () => (await fake.corpus.listFocusChoices!()) });
96
+ await ask.start();
97
+ ask.setProject('fma');
98
+ await ask.send('pricing Acme');
99
+ const view = ask.getState().messages[1].view!;
100
+ expect(view.citations.map((c) => c.title)).toEqual(['Pricing call with Acme']);
101
+ expect(view.citations[0].documentId).toBe('d4');
102
+ });
103
+ });
104
+
105
+ describe('answerView: what an answer owes its reader', () => {
106
+ const doc = (id: string, title: string) => ({ id, title, source: 'granola', sourceLabel: 'Granola', occurredAt: '2026-10-20T13:00:00Z' });
107
+ it('lists citations with source, title, date and the model\'s quote flattened', () => {
108
+ const v = answerView(result({ citations: [{ documentId: 'd4', document: doc('d4', 'Pricing call') as never, quote: '**Acme** renews' }] }));
109
+ expect(v.citations).toEqual([{ documentId: 'd4', title: 'Pricing call', sourceLabel: 'Granola', dateLabel: expect.stringContaining('2026'), quote: 'Acme renews' }]);
110
+ expect(v.provider).toBe('Answered by a fixture stub (fixture-echo) — no live model was called');
111
+ });
112
+ it('an uncited answer is shown as unsourced, first', () => {
113
+ const v = answerView(result({ status: 'uncited', unresolvedCitations: ['zz'] }));
114
+ expect(v.notices[0]).toMatchObject({ tone: 'warning', text: expect.stringContaining('could not be traced') });
115
+ expect(v.notices.some((n) => n.text.includes('(zz)'))).toBe(true);
116
+ });
117
+ it('no evidence is its own outcome, not an error', () => {
118
+ const v = answerView(result({ status: 'no_evidence', answer: 'Nothing in your records.' }));
119
+ expect(v).toMatchObject({ status: 'no_evidence', text: 'Nothing in your records.', citations: [] });
120
+ });
121
+ it('states stale sources, withheld fields and out-of-scope drops', () => {
122
+ const v = answerView(result({
123
+ freshness: [{ source: 'granola', label: 'Granola', status: 'stale' } as never],
124
+ withheldFields: ['transcript'], droppedOutOfScope: 2,
125
+ }));
126
+ const text = v.notices.map((n) => n.text).join('|');
127
+ expect(text).toContain('Granola (stale)');
128
+ expect(text).toContain('transcript');
129
+ expect(text).toContain('2 records from another workspace');
130
+ });
131
+ it('counts what was searched but not cited', () => {
132
+ const considered = [{ document: doc('d9', 'Unused') as never, matchedTerms: ['acme'] }];
133
+ expect(answerView(result({ considered: considered as never })).uncited).toEqual([{ documentId: 'd9', title: 'Unused', sourceLabel: 'Granola' }]);
134
+ });
135
+ });