@startsimpli/integrations 0.2.180 → 0.2.182

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.180",
3
+ "version": "0.2.182",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,8 +50,8 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/ui": "^0.4.186",
54
53
  "@startsimpli/utils": "^0.4.20",
54
+ "@startsimpli/ui": "^0.4.186",
55
55
  "@startsimpli/auth": "^0.4.53"
56
56
  },
57
57
  "peerDependenciesMeta": {
@@ -100,6 +100,60 @@ describe('converse brain', () => {
100
100
  });
101
101
  });
102
102
 
103
+ describe('a question never edits an item', () => {
104
+ it('"what did I do about the bench" is answered, not read as "I did the bench" (it once marked a real item done)', async () => {
105
+ const s = setup();
106
+ const brain = createConverseBrain({ ...s.deps, routeLlm: null, intentLlm: null });
107
+ const out = await brain({ utterance: "What did I do about dad's bench yesterday?", history: [], timeZone: TZ, now: NOW });
108
+ expect(out.did).toBeUndefined();
109
+ expect(s.ask).toHaveBeenCalledTimes(1);
110
+ expect(s.rows?.get('item:bench')?.data.status).toBe('open');
111
+ });
112
+ });
113
+
114
+ describe('fast paths', () => {
115
+ const llmSaying = (route: string) => ({ write: vi.fn(async () => `{"route": "${route}"}`) });
116
+ const input = (utterance: string) => ({ utterance, history: [], timeZone: TZ, now: NOW });
117
+ it('answers small talk with no model call and no search', async () => {
118
+ const s = setup();
119
+ const llm = llmSaying('other');
120
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llm });
121
+ for (const [said, reply] of [['Hello there!', 'Hi. What would you like to do?'], ['thanks', "You're welcome."], ['You there?', "Yes, I'm here."], ['okay', 'Okay.']] as const) {
122
+ expect((await brain(input(said))).text).toBe(reply);
123
+ }
124
+ expect(llm.write).not.toHaveBeenCalled();
125
+ expect(s.ask).not.toHaveBeenCalled();
126
+ });
127
+
128
+ it('does not treat a real request as small talk', async () => {
129
+ const s = setup();
130
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llmSaying('other') });
131
+ const out = await brain(input('hello, what is due today'));
132
+ expect(s.ask).toHaveBeenCalledTimes(1);
133
+ expect(out.text).toContain('bench');
134
+ });
135
+
136
+ it('a wh-question skips the edit path (no items load, no intent model) and still gets routed and answered', async () => {
137
+ const s = setup();
138
+ const loads: string[] = [];
139
+ const llm = { write: vi.fn(async () => '{"route":"other"}') };
140
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llm as never, loadItems: async () => { loads.push('items'); return s.deps.loadItems(); } });
141
+ const out = await brain(input('what is due today?'));
142
+ expect(loads).toEqual([]);
143
+ expect(llm.write).toHaveBeenCalledTimes(1);
144
+ expect(out.text).toContain('bench');
145
+ });
146
+
147
+ it('a yes/no question still reaches the edit path, with the routing model started alongside', async () => {
148
+ const s = setup();
149
+ const llm = { write: vi.fn(async () => '{"route":"other"}') };
150
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llm as never });
151
+ await brain(input('is the bench due today?'));
152
+ expect(llm.write).toHaveBeenCalledTimes(1);
153
+ expect(s.ask).toHaveBeenCalledTimes(1);
154
+ });
155
+ });
156
+
103
157
  describe('routing: work for the relay, fleet status, no filler', () => {
104
158
  const llmSaying = (route: string) => ({ write: vi.fn(async () => `{"route": "${route}"}`) });
105
159
  const input = (utterance: string) => ({ utterance, history: [], timeZone: TZ, now: NOW });
@@ -56,6 +56,20 @@ function setup(over: Partial<ConverseDeps> = {}, owner = 'me') {
56
56
  return { t, deps, brain, synthesize, put, transcribe, kept };
57
57
  }
58
58
 
59
+ describe('where the time went', () => {
60
+ it('reports each step of a fresh turn, with the brain steps, once, and not on a replay', async () => {
61
+ const { deps } = setup();
62
+ const seen: Array<Record<string, number>> = [];
63
+ const withTiming = { ...deps, onTiming: (t: Record<string, number>) => { seen.push(t); }, brain: async () => ({ text: 'ok', timings: { items: 5, ask: 7 } }) };
64
+ const first = await handleConverseTurn(withTiming, { text: 'plan my friday', turnId: 'turn-aaaa1' });
65
+ expect(seen).toHaveLength(1);
66
+ expect(Object.keys(seen[0])).toEqual(expect.arrayContaining(['stt', 'brain', 'brain.items', 'brain.ask', 'tts', 'save', 'total']));
67
+ expect(seen[0]['brain.items']).toBe(5);
68
+ await handleConverseTurn(withTiming, { text: 'plan my friday', turnId: 'turn-aaaa1', conversationId: first.conversation_id });
69
+ expect(seen).toHaveLength(1);
70
+ });
71
+ });
72
+
59
73
  describe('one text turn', () => {
60
74
  it('starts a conversation, answers, and keeps the turn in an owner-only record', async () => {
61
75
  const { t, deps, brain } = setup();
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Ask over projects (found on the live QA tenant, 2026-11-16): "What projects are active?" searched only
3
+ * documents, so a workspace with 64 projects and 9 briefing/conversation records answered "none of them
4
+ * matched". Projects are records an answer can cite, selected by status in code, like tracked items.
5
+ */
6
+ import { describe, expect, it } from 'vitest';
7
+
8
+ import { askCorpus } from '../corpus/ask';
9
+ import { projectIntent, selectProjects } from '../corpus/ask-projects';
10
+ import { createFixtureCorpusApi, FIXTURE_ORG } from '../corpus/fixtures';
11
+ import type { AnswerDraft, AnswerRequest, CorpusLlm, Focus } from '../corpus/types';
12
+
13
+ const SCOPE = { orgId: FIXTURE_ORG };
14
+ const focus = (id: string, title: string, status: Focus['status']): Focus =>
15
+ ({ id, externalId: `focus:${id}`, title, detail: '', status, scope: SCOPE }) as Focus;
16
+ const FOCUSES = [
17
+ focus('a', 'Crochets V2 launch', 'active'),
18
+ focus('b', 'Pre-seed fundraise', 'at_risk'),
19
+ focus('c', 'Scope & Plan Team', 'draft'),
20
+ focus('d', 'Old sales target', 'cancelled'),
21
+ focus('e', 'Onboarding', 'on_track'),
22
+ ];
23
+ const projects = { listFocuses: async () => ({ count: FOCUSES.length, next: null, previous: null, results: FOCUSES }) };
24
+
25
+ function llmCiting(ids: string[], calls: AnswerRequest[] = []): CorpusLlm {
26
+ return {
27
+ describe: () => ({ provider: 'scripted', model: 's', live: false }),
28
+ async answer(input): Promise<AnswerDraft> { calls.push(input); return { answer: 'ok', citations: ids.map((documentId) => ({ documentId })) }; },
29
+ };
30
+ }
31
+
32
+ describe('projectIntent', () => {
33
+ it('is null for a question that is not about projects or goals', () => {
34
+ expect(projectIntent('what did Acme say about pricing')).toBeNull();
35
+ });
36
+ it('reads "active" as everything in play, and a named status as that status', () => {
37
+ expect(projectIntent('What projects are active?')!.statuses).toEqual(['active', 'on_track', 'at_risk', 'off_track']);
38
+ expect(projectIntent('which goals are at risk')!.statuses).toEqual(['at_risk']);
39
+ expect(projectIntent('list my draft projects')!.statuses).toEqual(['draft']);
40
+ expect(projectIntent('what projects did we finish')!.statuses).toEqual(['completed']);
41
+ });
42
+ it('with no status word, everything but cancelled', () => {
43
+ expect(projectIntent('what projects do we have')!.statuses).toEqual(['draft', 'active', 'on_track', 'at_risk', 'off_track', 'completed']);
44
+ });
45
+ });
46
+
47
+ describe('Ask over projects', () => {
48
+ it('selects by status', () => {
49
+ const intent = projectIntent('What projects are active?')!;
50
+ expect(selectProjects(FOCUSES, intent).map((f) => f.title)).toEqual(['Crochets V2 launch', 'Onboarding', 'Pre-seed fundraise']);
51
+ });
52
+
53
+ it('answers a project question from the projects, cites them, and never says "none of them matched"', async () => {
54
+ const calls: AnswerRequest[] = [];
55
+ const result = await askCorpus(
56
+ { question: 'What projects are active?', mode: 'ask', scope: SCOPE },
57
+ { corpus: createFixtureCorpusApi({ documents: [] } as never), llm: llmCiting(['project:a', 'project:e'], calls), projects },
58
+ );
59
+ expect(result.status).toBe('answered');
60
+ expect(result.citations.map((c) => c.documentId)).toEqual(['project:a', 'project:e']);
61
+ expect(result.answer).not.toMatch(/none of them matched/);
62
+ expect(JSON.stringify(calls[0])).toContain('Pre-seed fundraise');
63
+ expect(JSON.stringify(calls[0])).not.toContain('Old sales target');
64
+ });
65
+
66
+ it('a question that is not about projects does not read them', async () => {
67
+ let read = 0;
68
+ await askCorpus(
69
+ { question: 'what did Acme say about pricing', mode: 'ask', scope: SCOPE },
70
+ { corpus: createFixtureCorpusApi(), llm: llmCiting([]), projects: { listFocuses: async () => { read += 1; return { count: 0, next: null, previous: null, results: [] }; } } },
71
+ );
72
+ expect(read).toBe(0);
73
+ });
74
+ });
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Records filed before the Plan change keep their text: a Conversation lists its asks under "## Asks" (or
3
+ * "Next steps"), a note under "Next steps". Render time, text-based: any such section becomes "N to-dos ... in Plan".
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ import { withoutNextSteps } from '../components/documentText';
8
+
9
+ describe('withoutNextSteps covers every to-do list heading', () => {
10
+ it.each(['Asks', 'Next steps', 'Next Steps', 'Action items', 'To-dos', 'Todos', 'Follow-ups'])('strips a "%s" section and counts its bullets', (heading) => {
11
+ const out = withoutNextSteps(`We talked.\n\n## ${heading}\n\n- Send the deck\n- Book the room\n\n## Decisions\n\nShip Friday.`);
12
+ expect(out.todos).toBe(2);
13
+ expect(out.text).toContain('We talked.');
14
+ expect(out.text).toContain('Ship Friday.');
15
+ expect(out.text).not.toContain('Send the deck');
16
+ });
17
+
18
+ it('works on a bold-title bullet list and an "Asks:" colon heading line', () => {
19
+ const out = withoutNextSteps('Hi.\n\n**Asks**\n\n- **Call Dana**\n- **Email Rae**');
20
+ expect(out.todos).toBe(2);
21
+ expect(out.text).toBe('Hi.');
22
+ });
23
+
24
+ it('leaves a record without such a section untouched', () => {
25
+ expect(withoutNextSteps('Just prose.\n\n## Decisions\n\n- Ship')).toEqual({ text: 'Just prose.\n\n## Decisions\n\n- Ship', todos: 0 });
26
+ });
27
+ });
@@ -30,9 +30,15 @@ export function fullTextOf(document: SourceDocument): string {
30
30
  return body && body !== summaryOf(document) ? body : '';
31
31
  }
32
32
 
33
+ /** Headings that introduce a note's list of to-dos: a Conversation's "Asks", a note's "Next steps", and their cousins. */
34
+ const TODO_HEADING = /^(?:next\s+steps?|asks?|action\s+items?|to-?dos?|follow-?\s?ups?)$/i;
35
+ const BULLET = /^\s*(?:[-*+]|\d+[.)])\s+\S/;
36
+
33
37
  /**
34
- * A note's markdown without its "Next steps" section, and how many to-dos that section held. The to-dos
35
- * live only in Plan (Quinn, 2026-11-16): a note shows its prose and a link, never a second to-do list.
38
+ * A record's markdown without its to-do list, and how many to-dos that list held. The to-dos live only in Plan
39
+ * (Quinn, 2026-11-16): a record shows its prose and a link, never a second to-do list. TEXT-BASED and applied when
40
+ * rendering, so a record filed before that change shows it too. A list is introduced by a markdown heading
41
+ * (`## Asks`), a bold line (`**Next steps**`) or a colon line (`Asks:`) and runs until the next heading.
36
42
  */
37
43
  export function withoutNextSteps(markdown: string): { text: string; todos: number } {
38
44
  const lines = (markdown ?? '').split('\n');
@@ -41,9 +47,12 @@ export function withoutNextSteps(markdown: string): { text: string; todos: numbe
41
47
  let todos = 0;
42
48
  for (const line of lines) {
43
49
  const heading = line.match(/^\s*#{1,6}\s+(.+?)\s*$/);
44
- if (heading) skipping = /^next\s+steps?$/i.test(heading[1]);
50
+ const bold = line.match(/^\s*\*\*(.+?)\*\*:?\s*$/);
51
+ const colon = line.match(/^\s*([A-Za-z][A-Za-z -]{1,24}):\s*$/);
52
+ const title = (heading ?? bold ?? colon)?.[1]?.replace(/:$/, '').trim();
53
+ if (heading || ((bold || colon) && title && TODO_HEADING.test(title))) skipping = Boolean(title && TODO_HEADING.test(title));
45
54
  if (skipping) {
46
- if (/^\s*[-*]\s+\S/.test(line)) todos += 1;
55
+ if (BULLET.test(line)) todos += 1;
47
56
  continue;
48
57
  }
49
58
  out.push(line);
@@ -32,6 +32,7 @@
32
32
  import * as React from 'react';
33
33
 
34
34
  import { itemIdOf } from '../../corpus/ask-items';
35
+ import { projectIdOf } from '../../corpus/ask-projects';
35
36
  import { Markdown, stripMarkdown } from '../Markdown';
36
37
  import {
37
38
  UNCITED_NOTICE, askFailureMessage as failureMessage, droppedNotice, freshnessNotice,
@@ -53,6 +54,8 @@ export interface AskPageProps {
53
54
  onOpenDocument?: (documentId: string) => void;
54
55
  /** Click-through from a cited TRACKED ITEM (an `item:` record) to the item, by its external id. */
55
56
  onOpenItem?: (itemId: string) => void;
57
+ /** Click-through from a cited PROJECT (a `project:` record) to the project, by its id. */
58
+ onOpenProject?: (projectId: string) => void;
56
59
  /** Prefill, e.g. from a `?q=` param. */
57
60
  initialQuestion?: string;
58
61
  initialMode?: AskMode;
@@ -106,6 +109,7 @@ export function AskPage({
106
109
  scope,
107
110
  onOpenDocument,
108
111
  onOpenItem,
112
+ onOpenProject,
109
113
  initialQuestion = '',
110
114
  initialMode = 'ask',
111
115
  listProjects,
@@ -235,6 +239,7 @@ export function AskPage({
235
239
  classNames={cn}
236
240
  onOpenDocument={onOpenDocument}
237
241
  onOpenItem={onOpenItem}
242
+ onOpenProject={onOpenProject}
238
243
  canSave={canSave}
239
244
  saveState={saveState}
240
245
  onSave={async () => {
@@ -262,12 +267,13 @@ export function AskPage({
262
267
  // ---------------------------------------------------------------------------
263
268
 
264
269
  function AnswerPanel({
265
- result, classNames: cn, onOpenDocument, onOpenItem, canSave, saveState, onSave,
270
+ result, classNames: cn, onOpenDocument, onOpenItem, onOpenProject, canSave, saveState, onSave,
266
271
  }: {
267
272
  result: AskResult;
268
273
  classNames: Record<AskSlot, string>;
269
274
  onOpenDocument?: (documentId: string) => void;
270
275
  onOpenItem?: (itemId: string) => void;
276
+ onOpenProject?: (projectId: string) => void;
271
277
  canSave: boolean;
272
278
  saveState: 'idle' | 'saving' | 'saved';
273
279
  onSave: () => void;
@@ -335,7 +341,9 @@ function AnswerPanel({
335
341
  className="text-sm font-medium text-blue-700 underline"
336
342
  onClick={() => {
337
343
  const itemId = itemIdOf(citation.documentId);
344
+ const projectId = projectIdOf(citation.documentId);
338
345
  if (itemId) onOpenItem?.(itemId);
346
+ else if (projectId) onOpenProject?.(projectId);
339
347
  else onOpenDocument?.(citation.documentId);
340
348
  }}
341
349
  >
@@ -34,6 +34,7 @@ import * as React from 'react';
34
34
  import { displayProgress, focusStatusLabel, standingLabel } from '../../corpus/planning';
35
35
  import { FocusDocuments } from '../FocusDocuments';
36
36
  import { FocusProgressHistory } from './goals/FocusProgressHistory';
37
+ import { ProjectTimeline } from './goals/ProjectTimeline';
37
38
  import {
38
39
  WorkItemRow,
39
40
  compareForScreen,
@@ -401,6 +402,7 @@ export function PlanningPage({
401
402
  onSelect={() => { setSelected(null); setShowDone(false); }}
402
403
  />
403
404
  <FocusProgressHistory focus={selectedFocus} api={api} />
405
+ <ProjectTimeline focus={selectedFocus} className={`${cn.card}`} />
404
406
  {error ? <p className={cn.error} role="alert">{error}</p> : null}
405
407
  </section>
406
408
 
@@ -0,0 +1,44 @@
1
+ 'use client';
2
+
3
+ /** Milestones and status updates of a project focus, when its source gave any. */
4
+ import * as React from 'react';
5
+
6
+ import type { Focus } from '../../../corpus/types';
7
+ import { projectMilestones, projectUpdates } from './project-timeline';
8
+
9
+ const day = (iso: string | null) => (iso ? iso.slice(0, 10) : 'No date');
10
+
11
+ export function ProjectTimeline({ focus, className }: { focus: Focus; className?: string }) {
12
+ const milestones = projectMilestones(focus);
13
+ const updates = projectUpdates(focus);
14
+ if (milestones.length === 0 && updates.length === 0) return null;
15
+ return (
16
+ <div className={className} data-testid="project-timeline">
17
+ {milestones.length > 0 ? (
18
+ <section aria-label="Milestones">
19
+ <h4 className="text-sm font-medium text-gray-900">Milestones</h4>
20
+ <ul className="mt-1 space-y-1">
21
+ {milestones.map((m) => (
22
+ <li key={m.id} className="flex justify-between gap-3 text-sm text-gray-700">
23
+ <span>{m.name}</span><span className="text-gray-500">{day(m.date)}</span>
24
+ </li>
25
+ ))}
26
+ </ul>
27
+ </section>
28
+ ) : null}
29
+ {updates.length > 0 ? (
30
+ <section aria-label="Project updates" className={milestones.length ? 'mt-4' : ''}>
31
+ <h4 className="text-sm font-medium text-gray-900">Updates</h4>
32
+ <ul className="mt-1 space-y-2">
33
+ {updates.map((u, i) => (
34
+ <li key={`${u.at ?? 'u'}-${i}`} className="text-sm text-gray-700">
35
+ <span className="text-gray-500">{day(u.at)}{u.health ? ` · ${u.health}` : ''}</span>
36
+ <p className="whitespace-pre-line">{u.body}</p>
37
+ </li>
38
+ ))}
39
+ </ul>
40
+ </section>
41
+ ) : null}
42
+ </div>
43
+ );
44
+ }
@@ -0,0 +1,15 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { projectMilestones, projectUpdates } from '../project-timeline';
3
+
4
+ describe('project timeline', () => {
5
+ it('orders milestones soonest first, undated last, drops nameless', () => {
6
+ const params = { milestones: [{ id: 'b', name: 'Beta', date: '2026-12-01' }, { id: 'n', name: 'Later' }, { id: 'a', name: 'Alpha', date: '2026-11-01' }, { id: 'x', name: '' }, 'junk'] };
7
+ expect(projectMilestones({ params }).map((m) => m.name)).toEqual(['Alpha', 'Beta', 'Later']);
8
+ });
9
+ it('orders updates newest first and tolerates missing params', () => {
10
+ const params = { updates: [{ body: 'old', at: '2026-10-01' }, { body: 'new', health: 'onTrack', at: '2026-11-01' }, { body: '' }] };
11
+ expect(projectUpdates({ params }).map((u) => u.body)).toEqual(['new', 'old']);
12
+ expect(projectUpdates({})).toEqual([]);
13
+ expect(projectMilestones({})).toEqual([]);
14
+ });
15
+ });
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Reads the milestones and status updates a connected tracker stores on a
3
+ * project focus (`focus.params.milestones` / `focus.params.updates`). Pure:
4
+ * malformed entries are dropped, nothing is invented.
5
+ */
6
+ import type { Focus } from '../../../corpus/types';
7
+
8
+ export interface ProjectMilestone { id: string; name: string; date: string | null }
9
+ export interface ProjectUpdate { body: string; health: string | null; at: string | null }
10
+
11
+ const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
12
+ const list = (v: unknown): Record<string, unknown>[] =>
13
+ Array.isArray(v) ? v.filter((x): x is Record<string, unknown> => !!x && typeof x === 'object') : [];
14
+
15
+ /** Dated milestones soonest first, undated last. */
16
+ export function projectMilestones(focus: Pick<Focus, 'params'>): ProjectMilestone[] {
17
+ return list(focus.params?.milestones)
18
+ .map((m, i) => ({ id: str(m.id) || `m${i}`, name: str(m.name), date: str(m.date) || null }))
19
+ .filter((m) => m.name)
20
+ .sort((a, b) => (a.date && b.date ? a.date.localeCompare(b.date) : a.date ? -1 : b.date ? 1 : 0));
21
+ }
22
+
23
+ /** Status updates newest first. */
24
+ export function projectUpdates(focus: Pick<Focus, 'params'>): ProjectUpdate[] {
25
+ return list(focus.params?.updates)
26
+ .map((u) => ({ body: str(u.body), health: str(u.health) || null, at: str(u.at) || null }))
27
+ .filter((u) => u.body)
28
+ .sort((a, b) => (b.at ?? '').localeCompare(a.at ?? ''));
29
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Projects (focuses, goals) as ANSWERABLE, CITABLE records, the way tracked items are (bd startsim-tmrvi).
3
+ *
4
+ * Ask used to retrieve documents only. "What projects are active?" therefore searched a workspace's briefings and
5
+ * conversations for the word "projects" and answered "none of them matched" while 64 projects existed (live QA
6
+ * tenant, 2026-11-16). A project question is a question about states, which a keyword ranker over documents cannot
7
+ * answer: the projects are selected by status here, in code, and the model only phrases what it was handed.
8
+ * The id is `project:<id>`, which can never collide with a document or an `item:` id.
9
+ */
10
+ import { displayProgress, focusStatusLabel } from './planning';
11
+ import { isInScope } from './retrieval';
12
+ import type { CorpusScope, Focus, FocusStatus, PlanningApi, RetrievedDocument, SourceDocument } from './types';
13
+
14
+ export const PROJECT_ID_PREFIX = 'project:';
15
+ /** The project id behind a cited record id, or null when it is a document or an item. */
16
+ export const projectIdOf = (documentId: string): string | null =>
17
+ documentId.startsWith(PROJECT_ID_PREFIX) ? documentId.slice(PROJECT_ID_PREFIX.length) : null;
18
+ export const PROJECT_SUBTYPE = 'project';
19
+
20
+ const PROJECT_WORDS = /\b(projects?|goals?|initiatives?|objectives?|okrs?)\b/i;
21
+ const IN_PLAY: FocusStatus[] = ['active', 'on_track', 'at_risk', 'off_track'];
22
+ const NOT_CANCELLED: FocusStatus[] = ['draft', 'active', 'on_track', 'at_risk', 'off_track', 'completed'];
23
+
24
+ export interface ProjectIntent { statuses: FocusStatus[] }
25
+
26
+ /** The intent, or null when the question is not about projects or goals at all. */
27
+ export function projectIntent(question: string): ProjectIntent | null {
28
+ const q = question.toLowerCase();
29
+ if (!PROJECT_WORDS.test(q)) return null;
30
+ let statuses: FocusStatus[] = NOT_CANCELLED;
31
+ if (/\bat[\s-]risk\b/.test(q)) statuses = ['at_risk'];
32
+ else if (/\boff[\s-]track\b|\bbehind\b|\bslipping\b/.test(q)) statuses = ['off_track'];
33
+ else if (/\bon[\s-]track\b/.test(q)) statuses = ['on_track'];
34
+ else if (/\bdraft(?:s|ed)?\b|\bplanned\b|\bnot started\b/.test(q)) statuses = ['draft'];
35
+ else if (/\b(complete[d]?|finish(?:ed)?|done|achieved|shipped)\b/.test(q)) statuses = ['completed'];
36
+ else if (/\b(cancel(?:l)?ed|dropped|abandoned)\b/.test(q)) statuses = ['cancelled'];
37
+ else if (/\b(active|current(?:ly)?|open|in progress|running|live|underway|ongoing)\b/.test(q)) statuses = IN_PLAY;
38
+ return { statuses };
39
+ }
40
+
41
+ /** One project as a record the model can read and the screen can cite. */
42
+ export function projectAsDocument(focus: Focus): SourceDocument {
43
+ const progress = displayProgress(focus, null);
44
+ const lines = [
45
+ `Status: ${focusStatusLabel(focus.status)}`,
46
+ // "Active" in a question means in play: on track, at risk and off track projects are all active.
47
+ `Active (in play): ${IN_PLAY.includes(focus.status) ? 'yes' : 'no'}`,
48
+ focus.category ? `Category: ${focus.category}` : '',
49
+ focus.endDate ? `Due: ${focus.endDate.slice(0, 10)}` : '',
50
+ progress !== null && progress !== undefined ? `Progress: ${Math.round(progress * 100)}%` : '',
51
+ focus.targetValue ? `Target: ${focus.currentValue ?? 0} of ${focus.targetValue}${focus.unit ? ` ${focus.unit}` : ''}` : '',
52
+ focus.detail ? `Detail: ${focus.detail}` : '',
53
+ ].filter(Boolean);
54
+ return {
55
+ id: `${PROJECT_ID_PREFIX}${focus.id}`,
56
+ title: focus.title,
57
+ body: lines.join('\n'),
58
+ sections: [],
59
+ occurredAt: focus.startDate ?? null,
60
+ source: 'planning',
61
+ sourceLabel: 'Project',
62
+ subtype: PROJECT_SUBTYPE,
63
+ sourceRef: focus.id,
64
+ participants: [],
65
+ scope: focus.scope,
66
+ };
67
+ }
68
+
69
+ /** Which of `focuses` the intent asks about, in the order worth reading. Pure. */
70
+ export function selectProjects(focuses: Focus[], intent: ProjectIntent): Focus[] {
71
+ const wanted = new Set(intent.statuses);
72
+ return focuses
73
+ .filter((f) => wanted.has(f.status))
74
+ .sort((a, b) => a.title.localeCompare(b.title));
75
+ }
76
+
77
+ /** Projects for a question: read, scope-check, select, convert. Empty when it is not a project question. */
78
+ export async function retrieveProjects(
79
+ question: string,
80
+ api: Pick<PlanningApi, 'listFocuses'> | undefined,
81
+ scope: CorpusScope,
82
+ limit: number,
83
+ ): Promise<{ intent: ProjectIntent | null; retrieved: RetrievedDocument[]; matched: number }> {
84
+ const intent = projectIntent(question);
85
+ if (!intent || !api) return { intent: null, retrieved: [], matched: 0 };
86
+ const page = await api.listFocuses({ pageSize: 200 }).catch(() => null);
87
+ if (!page) return { intent, retrieved: [], matched: 0 };
88
+ const selected = selectProjects(page.results.filter((f) => isInScope(f, scope)), intent);
89
+ const retrieved = selected.slice(0, limit).map((focus): RetrievedDocument => {
90
+ const document = projectAsDocument(focus);
91
+ return { document, score: 1, matchedTerms: [], snippet: document.body.split('\n').slice(0, 2).join(' · ') };
92
+ });
93
+ return { intent, retrieved, matched: selected.length };
94
+ }
package/src/corpus/ask.ts CHANGED
@@ -19,6 +19,7 @@
19
19
  * given has invented a source, and the only safe rendering of that is to say so.
20
20
  */
21
21
  import { retrieveItems } from './ask-items';
22
+ import { retrieveProjects } from './ask-projects';
22
23
  import { moneyEventAsDocument } from './entities';
23
24
  import { retrieveForQuestion, searchTermFor } from './retrieval';
24
25
  import { documentText } from './text';
@@ -30,6 +31,7 @@ import type {
30
31
  CommitmentApi,
31
32
  CorpusApi,
32
33
  CorpusLlm,
34
+ PlanningApi,
33
35
  PromptDocument,
34
36
  RetrievedDocument,
35
37
  SourceDocument,
@@ -349,7 +351,7 @@ function noEvidenceCopy(total: number): string {
349
351
  */
350
352
  export async function askCorpus(
351
353
  request: AskRequest,
352
- deps: { corpus: CorpusApi; llm: CorpusLlm; commitments?: Pick<CommitmentApi, 'listCommitments'> },
354
+ deps: { corpus: CorpusApi; llm: CorpusLlm; commitments?: Pick<CommitmentApi, 'listCommitments'>; /** Lets a project or goal question be answered from the projects themselves. */ projects?: Pick<PlanningApi, 'listFocuses'> },
353
355
  options: AskCorpusOptions = {},
354
356
  ): Promise<AskResult> {
355
357
  const { candidateLimit, contextLimit, maxCharsPerDocument, itemLimit } = { ...DEFAULTS, ...options };
@@ -384,10 +386,27 @@ export async function askCorpus(
384
386
  itemLimit,
385
387
  )
386
388
  : { intent: null, retrieved: [], matched: 0 };
387
- const retrieved = [...items.retrieved, ...documents];
389
+ // PROJECTS, the same way: a question about them is answered from their status, not from document text.
390
+ const projectHits = request.mode === 'ask'
391
+ ? await retrieveProjects(request.question, deps.projects, request.scope, itemLimit)
392
+ : { intent: null, retrieved: [], matched: 0 };
393
+ const retrieved = [...items.retrieved, ...projectHits.retrieved, ...documents];
388
394
 
389
395
  const freshness = await corpus.listSources().catch(() => [] as SourceFreshness[]);
390
396
 
397
+ if (retrieved.length === 0 && projectHits.intent && deps.projects) {
398
+ return {
399
+ status: 'no_evidence',
400
+ answer: 'No projects match that, and no documents do either.',
401
+ citations: [],
402
+ considered: [],
403
+ unresolvedCitations: [],
404
+ droppedOutOfScope,
405
+ provider: llm.describe(),
406
+ freshness,
407
+ };
408
+ }
409
+
391
410
  if (retrieved.length === 0 && items.intent && deps.commitments) {
392
411
  return {
393
412
  status: 'no_evidence',
@@ -42,6 +42,30 @@ export interface ConverseBrainDeps {
42
42
  answerFrom?(input: { question: string; material: string }): Promise<string>;
43
43
  }
44
44
 
45
+ /**
46
+ * Small talk gets a one-line answer with NO model call and NO search: "hello" used to take about 9 s (intent model, routing
47
+ * model, then Ask with retrieval) to answer a greeting. Only exact short phrases match, so nothing real is swallowed.
48
+ */
49
+ const SMALL_TALK: Array<[RegExp, string]> = [
50
+ [/^(hi|hello|hey|hiya|yo|good (morning|afternoon|evening))( there| tandem)?$/, 'Hi. What would you like to do?'],
51
+ [/^(you there|are you there|are you listening|can you hear me|test|testing|testing one two|mic check)$/, "Yes, I'm here."],
52
+ [/^(thanks|thank you|thank you very much|thanks a lot|cheers|appreciate it)( tandem)?$/, "You're welcome."],
53
+ [/^(ok|okay|cool|great|nice|got it|alright|all right|perfect|sounds good)$/, 'Okay.'],
54
+ [/^(never ?mind|forget it|cancel that)$/, 'Okay, forgetting it.'],
55
+ ];
56
+ /** A who/what/when/where/why/how question, or "tell/show/give me": answered, never acted on as an item edit. */
57
+ const ASKING = /^(what|what's|whats|how|when|where|who|why|which|tell me|give me|show me)\b/i;
58
+
59
+ /** Reads as a question: a question word first, or a question mark. */
60
+ const QUESTION = /^(what|what's|whats|how|when|where|who|why|which|is|are|do|does|did|can|could|should|will|would|have|has|tell me|give me|show me|read|list|any)\b|\?\s*$/i;
61
+
62
+ export function smallTalkReply(utterance: string): string | null {
63
+ const t = utterance.toLowerCase().replace(/[^a-z0-9' ]+/g, ' ').replace(/\s+/g, ' ').trim();
64
+ if (!t || t.length > 40) return null;
65
+ for (const [pattern, reply] of SMALL_TALK) if (pattern.test(t)) return reply;
66
+ return null;
67
+ }
68
+
45
69
  export const PASSED_TO_RELAY = 'Done, I have passed that to the relay.';
46
70
  export const NO_FLEET_STATUS = 'I do not have a fleet status yet. I have asked the relay to send one.';
47
71
  /** A line that names the relay or the agent team is routed BEFORE the item rules, so "add a to-do for the relay" is for the relay. */
@@ -72,18 +96,29 @@ export function speakableAnswer(answer: string): string {
72
96
  export const CANNOT_SEE = 'I could not find anything about that in your items or notes. You can ask what is due this week, or tell me what to add.';
73
97
  const GIVE_UP = /^\W*(unanswerable|unknown|n\/a|none|null|undefined)\W*$/i;
74
98
 
99
+ /** Times each awaited step into `timings` (a step that runs twice adds up). */
100
+ function stopwatch() {
101
+ const timings: Record<string, number> = {};
102
+ const timed = async <T,>(name: string, fn: () => Promise<T>): Promise<T> => {
103
+ const started = Date.now();
104
+ try { return await fn(); } finally { timings[name] = (timings[name] ?? 0) + (Date.now() - started); }
105
+ };
106
+ return { timings, timed };
107
+ }
108
+
75
109
  export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
76
110
  /** work -> the relay; status -> the snapshot, said with its age; other -> null (carry on). */
77
- async function viaRoute(utterance: string, history: HistoryLine[], now: number) {
111
+ type Timed = <T>(name: string, fn: () => Promise<T>) => Promise<T>;
112
+ async function viaRoute(utterance: string, history: HistoryLine[], now: number, timed: Timed, early?: Promise<Awaited<ReturnType<typeof routeUtterance>>>) {
78
113
  const recent = history.slice(-6).map((l) => `${l.role === 'user' ? 'Me' : 'You'}: ${l.text}`).join('\n');
79
- const route = await routeUtterance(deps.routeLlm, utterance, recent);
114
+ const route = await (early ?? timed('route', () => routeUtterance(deps.routeLlm, utterance, recent)));
80
115
  if (route === 'work') return { text: PASSED_TO_RELAY, forRelay: true };
81
116
  if (route !== 'status') return null;
82
- const snap = await deps.loadFleetStatus?.().catch(() => null);
117
+ const snap = await timed('fleet', async () => deps.loadFleetStatus?.().catch(() => null));
83
118
  if (!snap || !deps.answerFrom) return { text: NO_FLEET_STATUS, forRelay: true };
84
119
  const at = Date.parse(snap.updatedAt);
85
120
  const stale = !Number.isFinite(at) || now - at > FLEET_FRESH_MS;
86
- const said = await deps.answerFrom({ question: `${utterance}\n\n${NO_FILLER}`, material: `Fleet status as of ${snap.updatedAt || 'an unknown time'}:\n${snap.text}` }).catch(() => '');
121
+ const said = await timed('answer', () => deps.answerFrom!({ question: `${utterance}\n\n${NO_FILLER}`, material: `Fleet status as of ${snap.updatedAt || 'an unknown time'}:\n${snap.text}` }).catch(() => ''));
87
122
  const spoken = speakableAnswer(said);
88
123
  const body = !spoken || GIVE_UP.test(spoken) ? speakableAnswer(snap.text.split('\n').filter((l) => l.trim() && !l.startsWith('#')).slice(0, 4).join(' ')) : spoken;
89
124
  if (!stale) return { text: body };
@@ -92,37 +127,56 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
92
127
  return { text: `This is from the relay's last snapshot${age ? `, ${age}` : ''}, not live. ${body} I have asked the relay for a current one.`, forRelay: true };
93
128
  }
94
129
 
95
- return async ({ utterance, history, timeZone, now }) => {
130
+ async function run({ utterance, history, timeZone, now }: Parameters<ConverseBrain>[0], timed: Timed): ReturnType<ConverseBrain> {
96
131
  // Lines that name the relay go first, so "add a to-do for the relay" is for the relay, not a plan item.
97
132
  if (ADDRESSES_RELAY.test(utterance)) {
98
- const routed = await viaRoute(utterance, history, now);
133
+ const routed = await viaRoute(utterance, history, now, timed);
99
134
  if (routed) return routed;
100
135
  }
101
- const open = (await deps.loadItems().catch(() => [] as BriefingItem[])).map(intentItem);
102
- const log = await deps.log.load().catch(() => null);
103
- const intent = await resolveVoiceIntent(
136
+ const small = smallTalkReply(utterance);
137
+ if (small) return { text: small };
138
+ // A QUESTION is almost never an item edit, and the routing model does not depend on the intent model: start it now so a
139
+ // question pays for one wait, not two. An instruction ("mark ... done") still never wakes the routing model.
140
+ const recentLines = history.slice(-6).map((l) => `${l.role === 'user' ? 'Me' : 'You'}: ${l.text}`).join('\n');
141
+ const earlyRoute = deps.routeLlm && QUESTION.test(utterance.trim()) ? timed('route', () => routeUtterance(deps.routeLlm, utterance, recentLines)) : undefined;
142
+ earlyRoute?.catch(() => undefined);
143
+ // "What did I do yesterday?" is a question, never an edit: the rules read "did" as "I did it" and once marked a real item
144
+ // done. A who/what/when/how question skips the edit path altogether (which also saves the intent model's wait).
145
+ const asking = ASKING.test(utterance.trim());
146
+ const [openRows, log] = asking ? [[] as BriefingItem[], null] : await Promise.all([
147
+ timed('items', () => deps.loadItems().catch(() => [] as BriefingItem[])),
148
+ timed('log', () => deps.log.load().catch(() => null)),
149
+ ]);
150
+ const open = openRows.map(intentItem);
151
+ const intent = asking ? null : await timed('intent', () => resolveVoiceIntent(
104
152
  { utterance, now, timeZone, briefed: [], open, readingId: null, hasUndo: Boolean(log?.stack.length) },
105
153
  { llm: deps.intentLlm ?? null, ...(deps.intentTimeoutMs ? { timeoutMs: deps.intentTimeoutMs } : {}) },
106
- ).catch(() => null);
154
+ ).catch(() => null));
107
155
 
108
156
  const real = intent?.actions.filter((a) => a.type !== 'clarify' && a.type !== 'none') ?? [];
109
157
  const sure = intent && real.length === intent.actions.length && real.length > 0 && (intent.confidence ?? 1) >= (deps.minAutoConfidence ?? MIN_AUTO);
110
158
  if (intent && sure) {
111
- const outcome = await executeVoiceActions({
159
+ const outcome = await timed('act', () => executeVoiceActions({
112
160
  actions: intent.actions, clientActionId: `converse-${now}-${Math.abs(hash(utterance))}`.slice(0, 64), seam: deps.seam, log: deps.log,
113
161
  ownerSub: deps.ownerSub, now: () => now, timeZone,
114
- });
162
+ }));
115
163
  return { text: outcome.text, did: outcome.results.map((r) => r.spoken).filter(Boolean) };
116
164
  }
117
165
 
118
166
  if (!ADDRESSES_RELAY.test(utterance)) {
119
- const routed = await viaRoute(utterance, history, now);
167
+ const routed = await viaRoute(utterance, history, now, timed, earlyRoute);
120
168
  if (routed) return routed;
121
169
  }
122
170
 
123
- const answered = await deps.ask({ question: `${questionWithHistory(utterance, history)}\n\n${NO_FILLER}`, timeZone, now });
171
+ const answered = await timed('ask', () => deps.ask({ question: `${questionWithHistory(utterance, history)}\n\n${NO_FILLER}`, timeZone, now }));
124
172
  const spoken = speakableAnswer(answered.answer ?? '');
125
173
  return { text: !spoken || GIVE_UP.test(spoken) ? CANNOT_SEE : spoken };
174
+ }
175
+
176
+ return async (input) => {
177
+ const { timings, timed } = stopwatch();
178
+ const out = await run(input, timed);
179
+ return { ...out, timings };
126
180
  };
127
181
  }
128
182
 
@@ -63,6 +63,10 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
63
63
  const timeZone = req.timeZone || record?.timeZone || 'UTC';
64
64
  const hints = (record?.turns ?? []).slice(-3).map((t) => t.user.text);
65
65
 
66
+ const clock = { t0: Date.now(), last: Date.now() };
67
+ const timing: Record<string, number> = {};
68
+ const lap = (name: string) => { const n = Date.now(); timing[name] = (timing[name] ?? 0) + (n - clock.last); clock.last = n; };
69
+
66
70
  // 1. Words.
67
71
  let utterance = req.text?.trim() ?? '';
68
72
  if (req.audio) {
@@ -73,6 +77,7 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
73
77
  throw new ConverseError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
74
78
  }
75
79
  }
80
+ lap('stt');
76
81
 
77
82
  // 2. Answer.
78
83
  let replyText = NOT_HEARD;
@@ -86,6 +91,8 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
86
91
  replyText = out.text.trim() || NOT_HEARD;
87
92
  did = out.did?.length ? out.did : undefined;
88
93
  forRelay = Boolean(out.forRelay);
94
+ lap('brain');
95
+ for (const [k, v] of Object.entries(out.timings ?? {})) timing[`brain.${k}`] = v;
89
96
  } catch (error) {
90
97
  console.error('[converse] brain failed (turn kept)', error);
91
98
  replyText = BRAIN_FAILED;
@@ -102,7 +109,9 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
102
109
  user.audio_reason = error instanceof Error ? error.message : String(error);
103
110
  }
104
111
  }
112
+ lap('keep_user_audio');
105
113
  const assistant = await speakSide(deps, `${conversationId}-t${n}-reply`, replyText);
114
+ lap('tts');
106
115
 
107
116
  // 4. Save.
108
117
  const turn: ConverseTurn = { n, turn_id: turnId, at: new Date(now).toISOString(), user, assistant, ...(did ? { did } : {}), ...(forRelay ? { for_relay: true } : {}) };
@@ -116,6 +125,9 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
116
125
  });
117
126
  // The relay finds its work in one list, so a passed-on turn is also recorded there. Never allowed to lose the turn.
118
127
  if (forRelay) await addRelayOrder(deps, { conversation_id: conversationId, turn: n, text: utterance, at: turn.at }).catch((e) => console.error('[converse] relay inbox write failed', e));
128
+ lap('save');
129
+ timing.total = Date.now() - clock.t0;
130
+ deps.onTiming?.(timing, { conversationId, turn: n });
119
131
  return resultOf(conversationId, turn);
120
132
  }
121
133
 
@@ -76,6 +76,8 @@ export interface ConverseBrainOutput {
76
76
  did?: string[];
77
77
  /** The utterance is an instruction for the relay: the turn is marked so the relay's poll finds it. */
78
78
  forRelay?: boolean;
79
+ /** Milliseconds spent in each step of the brain (items, intent, route, ask...): measured, never spoken. */
80
+ timings?: Record<string, number>;
79
81
  }
80
82
  export type ConverseBrain = (input: ConverseBrainInput) => Promise<ConverseBrainOutput>;
81
83
 
@@ -158,6 +160,8 @@ export interface ConverseDeps {
158
160
  newId?: () => string;
159
161
  /** How many earlier lines the brain sees. Default 24. */
160
162
  historyLines?: number;
163
+ /** Told where the time went after every fresh turn, so a slow turn can be read off a log line. */
164
+ onTiming?: (timing: Record<string, number>, info: { conversationId: string; turn: number }) => void;
161
165
  /** Called when the relay answers a conversation the person has already ended, so they can be told (a push). Errors are ignored. */
162
166
  onRelayReplyAfterEnd?: (info: { conversationId: string; text: string }) => Promise<void>;
163
167
  }
@@ -330,3 +330,6 @@ export * from './liability-plan';
330
330
  export * from './liability-client';
331
331
  // Tab names and one-line subtitles shared by the web and iPhone shells.
332
332
  export * from './nav-copy';
333
+
334
+ // Projects as answerable records for Ask.
335
+ export { PROJECT_ID_PREFIX, projectIdOf, projectIntent, retrieveProjects, selectProjects } from './ask-projects';
@@ -95,7 +95,7 @@ export const BUILTIN_FACTORIES: Record<string, ScreenFactory> = {
95
95
  },
96
96
  tracker: ({ config, corpus, member, openUrl, itemsChanged }, tab) => trackerTab({ api: corpus, itemsChanged, key: tab.key, label: tabLabel(tab), notesKey: firstKey(config, 'notes'), memberConnections: member.connections, openUrl }),
97
97
  plan: ({ config, corpus, member, openUrl, itemsChanged }, tab) => planTab({ api: corpus, key: tab.key, label: tabLabel(tab), notesKey: firstKey(config, 'notes'), documentTab: firstKey(config, 'library'), memberConnections: member.connections, openUrl, itemsChanged }),
98
- talk: ({ config, corpus, converse, converseSpeed }, tab) => talkTab({ api: corpus, converse, speed: converseSpeed, key: tab.key, label: tabLabel(tab), libraryKey: firstKey(config, 'library') }),
98
+ talk: ({ config, corpus, converse, converseSpeed }, tab) => talkTab({ api: corpus, converse, speed: converseSpeed, key: tab.key, label: tabLabel(tab), libraryKey: firstKey(config, 'library'), planKey: firstKey(config, 'plan') }),
99
99
  library: ({ config, corpus }, tab) => libraryTab(corpus, { key: tab.key, label: tabLabel(tab), planKey: firstKey(config, 'plan') }),
100
100
  ask: ({ corpus }, tab) => askTab(corpus, { key: tab.key, label: tabLabel(tab) }),
101
101
  planning: ({ config, corpus }, tab) => createPlanningTab({ api: corpus, key: tab.key, label: tabLabel(tab), documentTab: firstKey(config, 'library') }),
@@ -2,6 +2,7 @@ import { useMemo, useState } from 'react';
2
2
  import { View } from 'react-native';
3
3
  import { Header, SegmentedControl, Text, useTheme } from '@startsimpli/ui-native';
4
4
  import { TAB_COPY, TALK_MODES, type TalkMode } from '../../corpus/nav-copy';
5
+ import { projectIdOf } from '../../corpus/ask-projects';
5
6
  import type { MeetingController } from '../../corpus/converse/meeting';
6
7
  import type { FoundryTab, TabContext } from '../components/FoundryTabsShell';
7
8
  import type { NativeCorpusApi } from '../corpus/api';
@@ -21,11 +22,13 @@ export interface TalkTabOptions {
21
22
  label?: string;
22
23
  /** The Library tab, where a cited source opens. */
23
24
  libraryKey?: string;
25
+ /** The Plan tab, where a cited PROJECT opens. */
26
+ planKey?: string;
24
27
  }
25
28
 
26
29
  function TalkBody({ opts, ctx }: { opts: TalkTabOptions; ctx: TabContext }) {
27
30
  const theme = useTheme();
28
- const { api, converse, speed, libraryKey = 'library' } = opts;
31
+ const { api, converse, speed, libraryKey = 'library', planKey } = opts;
29
32
  const modes = TALK_MODES.filter((m) => m.key === 'ask' || converse);
30
33
  // `-tgTab talk -tgDetail ask` (and a link) land on Ask.
31
34
  const [mode, setMode] = useState<TalkMode>(ctx.route?.id === 'ask' || !converse ? 'ask' : 'talk');
@@ -47,7 +50,7 @@ function TalkBody({ opts, ctx }: { opts: TalkTabOptions; ctx: TabContext }) {
47
50
  </View>
48
51
  ) : null}
49
52
  <View style={{ flex: 1, display: current.key === 'ask' ? 'flex' : 'none' }}>
50
- <AskScreen controller={ask} onOpenDocument={(id) => ctx.openTab(libraryKey, id)} embedded />
53
+ <AskScreen controller={ask} onOpenDocument={(id) => { const project = projectIdOf(id); if (project && planKey) ctx.openTab(planKey, `project/${project}`); else ctx.openTab(libraryKey, id); }} embedded />
51
54
  </View>
52
55
  </View>
53
56
  );