@startsimpli/integrations 0.2.160 → 0.2.163

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.
Files changed (54) hide show
  1. package/package.json +6 -6
  2. package/src/__tests__/converse-brain.test.ts +84 -0
  3. package/src/__tests__/converse-client.test.ts +39 -0
  4. package/src/__tests__/converse-config.test.ts +9 -0
  5. package/src/__tests__/converse-extract.test.ts +19 -0
  6. package/src/__tests__/converse-page.test.tsx +104 -0
  7. package/src/__tests__/converse.test.ts +212 -0
  8. package/src/__tests__/corpus-planning.test.tsx +31 -0
  9. package/src/__tests__/measure/notes.ts +28 -0
  10. package/src/__tests__/measure/voice-notes.measure.test.ts +51 -0
  11. package/src/__tests__/question-evidence.test.ts +82 -0
  12. package/src/__tests__/question-voice.test.ts +18 -0
  13. package/src/components/index.ts +2 -0
  14. package/src/components/pages/ConversePage.tsx +184 -0
  15. package/src/components/pages/PlanningPage.tsx +14 -4
  16. package/src/components/pages/converse/silence.ts +20 -0
  17. package/src/components/pages/converse/useRecorder.ts +55 -0
  18. package/src/corpus/converse/brain.ts +84 -0
  19. package/src/corpus/converse/client.ts +64 -0
  20. package/src/corpus/converse/config.ts +21 -0
  21. package/src/corpus/converse/extract.ts +41 -0
  22. package/src/corpus/converse/handle.ts +147 -0
  23. package/src/corpus/converse/index.ts +16 -0
  24. package/src/corpus/converse/respond.ts +88 -0
  25. package/src/corpus/converse/store.ts +74 -0
  26. package/src/corpus/converse/transcript.ts +20 -0
  27. package/src/corpus/converse/types.ts +133 -0
  28. package/src/corpus/index.ts +1 -0
  29. package/src/corpus/llm.ts +3 -2
  30. package/src/corpus/questions/evidence.ts +65 -0
  31. package/src/corpus/questions/index.ts +4 -1
  32. package/src/corpus/questions/items.ts +21 -0
  33. package/src/corpus/questions/learn.ts +16 -0
  34. package/src/corpus/questions/sync.ts +7 -3
  35. package/src/corpus/questions/types.ts +3 -1
  36. package/src/corpus/questions/voice.ts +23 -4
  37. package/src/corpus/voice.ts +5 -2
  38. package/src/native/app/FoundryApp.tsx +2 -2
  39. package/src/native/app/__tests__/launch.test.ts +1 -1
  40. package/src/native/app/config/defaults.ts +3 -2
  41. package/src/native/app/config/types.ts +3 -1
  42. package/src/native/app/converseServices.ts +46 -0
  43. package/src/native/app/launch.ts +4 -0
  44. package/src/native/app/registry.tsx +8 -0
  45. package/src/native/app/services.ts +5 -2
  46. package/src/native/converse/ConverseScreen.tsx +70 -0
  47. package/src/native/converse/__tests__/controller.test.ts +182 -0
  48. package/src/native/converse/api.ts +81 -0
  49. package/src/native/converse/controller.ts +252 -0
  50. package/src/native/converse/fake.ts +34 -0
  51. package/src/native/converse/format.ts +25 -0
  52. package/src/native/converse/index.ts +8 -0
  53. package/src/native/converse/tab.tsx +14 -0
  54. package/src/native/index.ts +1 -0
@@ -5,7 +5,8 @@
5
5
  import type { CorpusHttp } from '../client';
6
6
  import type { CorpusScope } from '../types';
7
7
  import { CLOSED_STATUSES, deriveQuestions, scoreOf } from './derive';
8
- import { readItemViews, readVoiceRecords } from './items';
8
+ import { decideFromCorpus } from './evidence';
9
+ import { readEvidenceEvents, readItemViews, readVoiceRecords } from './items';
9
10
  import { createPreferenceStore, decideFromHabits } from './learn';
10
11
  import { createQuestionStore } from './store';
11
12
  import type { ItemView, OpenQuestion, QuestionResolution } from './types';
@@ -40,6 +41,7 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
40
41
  const existing = new Map((await store.all()).map((q) => [key(q.itemId, q.kind), q]));
41
42
 
42
43
  const prefs = await createPreferenceStore(deps).all().catch(() => []);
44
+ const events = await readEvidenceEvents(deps.http, path).catch(() => []);
43
45
  let opened = 0, resolved = 0, expired = 0, decidedByContext = 0;
44
46
  const wanted = new Set<string>();
45
47
 
@@ -56,11 +58,13 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
56
58
  };
57
59
  if (!have && d.assumed) {
58
60
  // Context first: a learned habit that agrees with the guess settles it, and the row says why.
59
- const hit = decideFromHabits({ kind: d.kind, title: byId.get(d.itemId)?.title ?? '', assumed: d.assumed }, prefs, (deps.now ?? Date.now)(), deps.timeZone ?? 'UTC');
61
+ const item = byId.get(d.itemId);
62
+ const hit = decideFromHabits({ kind: d.kind, title: item?.title ?? '', assumed: d.assumed }, prefs, (deps.now ?? Date.now)(), deps.timeZone ?? 'UTC')
63
+ ?? (item ? decideFromCorpus({ kind: d.kind, item, assumed: d.assumed }, { items, events }) : null);
60
64
  if (hit) {
61
65
  await store.put(d.itemId, d.kind, d.question, {
62
66
  ...body, status: 'resolved', resolution: 'context', resolved_at: iso(), created_at: iso(), updated_at: iso(),
63
- answer: JSON.stringify({ value: d.assumed.value ?? '', label: `learned: ${hit.evidence}` }),
67
+ answer: JSON.stringify({ value: d.assumed.value ?? '', label: `${'source' in hit ? 'found' : 'learned'}: ${hit.evidence}` }),
64
68
  });
65
69
  decidedByContext += 1;
66
70
  continue;
@@ -62,7 +62,7 @@ export interface QuestionAnswer {
62
62
  /** Set when the answer was spoken: the press that gave it, so a repeat press does nothing twice. */
63
63
  via?: string;
64
64
  /** What the item held before, so a spoken "undo" can put it back. */
65
- prior?: { dueAt?: string | null };
65
+ prior?: { dueAt?: string | null; focusId?: string | null; ownerSub?: string; ownerName?: string };
66
66
  }
67
67
 
68
68
  /** What the queue needs to know about an item (from its commitment row). */
@@ -75,6 +75,8 @@ export interface ItemView {
75
75
  ownerName: string;
76
76
  ownerSub: string;
77
77
  noteId?: string;
78
+ /** The Linear issue key when the item is synced to one. */
79
+ linearKey?: string;
78
80
  openKind: string;
79
81
  openText: string;
80
82
  }
@@ -15,6 +15,7 @@ import type { BriefingAudio, BriefingSynthesize } from '../briefing/generate';
15
15
  import { speakDatesIn, speakable } from '../briefing/speak';
16
16
  import { localDate } from '../today';
17
17
  import { answerQuestion, type AnswerDeps } from './answer';
18
+ import { readItemViews } from './items';
18
19
  import { close, listOpenQuestions, storeFor } from './sync';
19
20
  import type { OpenQuestion, QuestionAnswer } from './types';
20
21
  import { parseSpokenAnswer, type AnswerOption } from './voice-parse';
@@ -112,12 +113,19 @@ async function undoLast(deps: VoiceAnswerDeps, now: number): Promise<{ text: str
112
113
  .filter((q) => q.resolution === 'answered' && q.answer?.via && q.resolvedAt && now - Date.parse(q.resolvedAt) <= UNDO_WINDOW_MS)
113
114
  .sort((a, b) => (b.resolvedAt ?? '').localeCompare(a.resolvedAt ?? ''))[0];
114
115
  if (!last) return { text: 'There is nothing to undo.', question: null };
115
- if (last.kind !== 'due_date' || !last.answer?.prior) {
116
+ const prior = last.answer?.prior;
117
+ // A team answer also released the item to the tracker, so it cannot be quietly taken back.
118
+ if (!prior || !['due_date', 'project', 'ownership'].includes(last.kind)) {
116
119
  return { text: 'I cannot undo that one by voice. You can change it on the item.', question: last };
117
120
  }
118
121
  const item = await deps.seam.load(last.itemId);
119
122
  if (!item) return { text: 'That item is gone, so there is nothing to put back.', question: last };
120
- await deps.seam.update(item, { dueAt: last.answer.prior.dueAt ?? null });
123
+ if (last.kind === 'due_date') await deps.seam.update(item, { dueAt: prior.dueAt ?? null });
124
+ else if (last.kind === 'project') {
125
+ if (!deps.fileItem) return { text: 'I cannot undo that one by voice. You can change it on the item.', question: last };
126
+ await deps.fileItem(last.itemId, prior.focusId ?? null);
127
+ await deps.patchItem(last.itemId, { external_focus_id: prior.focusId ?? '' });
128
+ } else await deps.patchItem(last.itemId, { owner_sub: prior.ownerSub ?? '', owner_name: prior.ownerName ?? '' });
121
129
  const at = new Date(now).toISOString();
122
130
  const reopened = await storeFor(deps).put(last.itemId, last.kind, last.question, {
123
131
  status: 'open', resolution: '', resolved_at: '', answer: '', updated_at: at,
@@ -222,6 +230,17 @@ export async function answerQuestionByVoice(deps: VoiceAnswerDeps, req: VoiceAns
222
230
 
223
231
  /** Apply the answer, remembering what a due date was so "undo" can put it back. */
224
232
  async function applyAnswer(deps: VoiceAnswerDeps, q: OpenQuestion, answer: QuestionAnswer): Promise<OpenQuestion> {
225
- const prior = q.kind === 'due_date' ? await deps.seam.load(q.itemId).catch(() => null) : null;
226
- return answerQuestion(deps, q.id, prior ? { ...answer, prior: { dueAt: prior.dueAt ?? null } } : answer);
233
+ const prior = await priorOf(deps, q);
234
+ return answerQuestion(deps, q.id, prior ? { ...answer, prior } : answer);
235
+ }
236
+
237
+ async function priorOf(deps: VoiceAnswerDeps, q: OpenQuestion): Promise<QuestionAnswer['prior'] | null> {
238
+ if (q.kind === 'due_date') {
239
+ const item = await deps.seam.load(q.itemId).catch(() => null);
240
+ return item ? { dueAt: item.dueAt ?? null } : null;
241
+ }
242
+ if (q.kind !== 'project' && q.kind !== 'ownership') return null;
243
+ const view = (await readItemViews(deps.http, deps.scope, deps.entitiesPath ?? 'api/v1/entities').catch(() => [])).find((i) => i.id === q.itemId);
244
+ if (!view) return null;
245
+ return q.kind === 'project' ? { focusId: view.focusId || null } : { ownerSub: view.ownerSub, ownerName: view.ownerName };
227
246
  }
@@ -105,7 +105,7 @@ export interface VoiceUsage {
105
105
 
106
106
  export interface VoiceAnalyzer {
107
107
  /** `now` is when the note was recorded and `timeZone` the speaker's: the model is shown them so "today" means something. */
108
- analyze(input: { transcript: string; focuses: FocusChoice[]; now?: number; timeZone?: string }): Promise<VoiceAnalysis>;
108
+ analyze(input: { transcript: string; focuses: FocusChoice[]; now?: number; timeZone?: string; habits?: string[] }): Promise<VoiceAnalysis>;
109
109
  }
110
110
 
111
111
  export interface VoiceTranscriber {
@@ -214,6 +214,8 @@ export interface VoiceDeps {
214
214
  analyzer: VoiceAnalyzer;
215
215
  store: VoiceAudioStore;
216
216
  listFocuses(): Promise<FocusChoice[]>;
217
+ /** Learned project habits as prompt hints (bd startsim-tmrvi.18); best effort. */
218
+ listHabits?(focuses: FocusChoice[]): Promise<string[]>;
217
219
  now?: () => Date;
218
220
  }
219
221
 
@@ -323,7 +325,8 @@ export async function finishVoiceNote(
323
325
  const recordedAt = submission.recordedAt ? Date.parse(submission.recordedAt) : at.getTime();
324
326
  const timeZone = isTimeZone(submission.timeZone) ? submission.timeZone : 'UTC';
325
327
  const now = Number.isNaN(recordedAt) ? at.getTime() : recordedAt;
326
- const heardAnalysis = await deps.analyzer.analyze({ transcript, focuses, now, timeZone });
328
+ const habits = deps.listHabits ? await deps.listHabits(focuses).catch(() => [] as string[]) : [];
329
+ const heardAnalysis = await deps.analyzer.analyze({ transcript, focuses, now, timeZone, ...(habits.length ? { habits } : {}) });
327
330
  // Dates are computed HERE from what was said, whatever the model did: its `when` words are
328
331
  // resolved against the recording time and the speaker's zone, and a note-wide "plan for the
329
332
  // day" fills the rest. The summary is re-rendered so each to-do carries its due date.
@@ -56,7 +56,7 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
56
56
  );
57
57
  const { banners, services } = useMemo(() => {
58
58
  const b = createBanners();
59
- return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeBriefing: launch.fakeBriefing ? { corpus: fakeCorpus as FakeNativeCorpusApi, script: launch.fakeReply } : null }) };
59
+ return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeConverse: launch.fakeConverse, fakeBriefing: launch.fakeBriefing ? { corpus: fakeCorpus as FakeNativeCorpusApi, script: launch.fakeReply } : null }) };
60
60
  }, [config, device, strings, launch, fakeCorpus]);
61
61
  // The engine is the device's; a haptic that throws (no taptic hardware, simulator) never breaks a screen.
62
62
  // Every call is logged to the diagnostics (`haptic`, then `haptic.result`) so a device run proves the engine was invoked.
@@ -149,7 +149,7 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
149
149
  const recordRef = useRef<ReactNode>(record);
150
150
  recordRef.current = record;
151
151
  const tabs = useMemo(
152
- () => buildFoundryTabs({ config: appConfig, corpus: data.corpus, notes: data.notes, record: () => recordRef.current, member: data.member, itemsChanged: services.briefing?.itemsChanged, openUrl: data.openUrl ?? ((url) => Linking.openURL(url)) }, registry),
152
+ () => buildFoundryTabs({ config: appConfig, corpus: data.corpus, notes: data.notes, record: () => recordRef.current, member: data.member, itemsChanged: services.briefing?.itemsChanged, converse: services.converse?.controller ?? null, openUrl: data.openUrl ?? ((url) => Linking.openURL(url)) }, registry),
153
153
  [appConfig, data, registry],
154
154
  );
155
155
 
@@ -7,7 +7,7 @@ const args = (o: Record<string, string>) => (k: string) => o[k];
7
7
 
8
8
  describe('readLaunch', () => {
9
9
  it('a plain launch is real mode with nothing to open', () => {
10
- expect(readLaunch(args({}), config)).toEqual({ fake: false, scenario: 'normal', target: null, autostop: null, scheme: null, hapticProbe: false, fakeBriefing: false, fakeReply: [] });
10
+ expect(readLaunch(args({}), config)).toEqual({ fake: false, scenario: 'normal', target: null, autostop: null, scheme: null, hapticProbe: false, fakeBriefing: false, fakeConverse: false, fakeReply: [] });
11
11
  });
12
12
  it('-tgFakeTabs with -tgTab and -tgDetail', () => {
13
13
  expect(readLaunch(args({ tgFakeTabs: '1', tgTab: 'tracker', tgDetail: 'c1' }), config)).toMatchObject({ fake: true, target: { tab: 'tracker', id: 'c1' } });
@@ -3,13 +3,13 @@ import { BUILTIN_SCREENS, type FoundryAppConfig, type FoundryFeatures, type Foun
3
3
  export const DEFAULT_CENTRAL_URL = 'https://api.startsimpli.com';
4
4
 
5
5
  export const DEFAULT_FEATURES: FoundryFeatures = {
6
- recording: true, notes: true, tracker: true, library: true, ask: true, planning: true, connections: true, connectClaude: true, briefing: false,
6
+ recording: true, notes: true, tracker: true, library: true, ask: true, planning: true, connections: true, connectClaude: true, briefing: false, converse: false,
7
7
  };
8
8
 
9
9
  /** The feature a built-in screen needs. `home` and `entity` need none. */
10
10
  export const SCREEN_FEATURE: Partial<Record<string, keyof FoundryFeatures>> = {
11
11
  record: 'recording', notes: 'notes', tracker: 'tracker', library: 'library', ask: 'ask',
12
- planning: 'planning', connections: 'connections', 'connect-claude': 'connectClaude',
12
+ planning: 'planning', connections: 'connections', 'connect-claude': 'connectClaude', converse: 'converse',
13
13
  };
14
14
 
15
15
  /** Entity types a built-in screen shows (the `entity` screen names its own in `options.entityType`). */
@@ -34,6 +34,7 @@ export const SCREEN_DEFAULTS: Record<string, { label: string; description?: stri
34
34
  planning: { label: 'Planning', icon: 'planning', description: 'Focuses and items' },
35
35
  connections: { label: 'Connections', icon: 'link', description: 'Accounts and data sources' },
36
36
  'connect-claude': { label: 'Claude', icon: 'sparkle', description: 'Use your workspace from Claude' },
37
+ converse: { label: 'Converse', icon: 'mic', description: 'Talk it through with your assistant', priority: 85 },
37
38
  entity: { label: 'Records', icon: 'list' },
38
39
  };
39
40
 
@@ -5,7 +5,7 @@
5
5
 
6
6
  /** Screen kinds the shell ships. An app can add or override kinds through a screen registry. */
7
7
  export const BUILTIN_SCREENS = [
8
- 'home', 'record', 'notes', 'tracker', 'library', 'ask', 'planning', 'connections', 'connect-claude', 'entity',
8
+ 'home', 'record', 'notes', 'tracker', 'library', 'ask', 'planning', 'connections', 'connect-claude', 'converse', 'entity',
9
9
  ] as const;
10
10
  export type BuiltinScreen = (typeof BUILTIN_SCREENS)[number];
11
11
 
@@ -25,6 +25,8 @@ export interface FoundryFeatures {
25
25
  connectClaude: boolean;
26
26
  /** 'What's on the plate' on the GO screen (needs the tenant's /corpus/briefing routes). Off by default. */
27
27
  briefing: boolean;
28
+ /** The Converse tab: tap-to-talk voice conversation (needs the tenant's /corpus/converse routes, the recording bindings and a playback driver). Off by default. */
29
+ converse: boolean;
28
30
  }
29
31
 
30
32
  /** What the briefing does beyond playing. `features.briefing` takes `true`, or an object with any of these. */
@@ -0,0 +1,46 @@
1
+ import { createAudioPlayer } from '../briefing/audioPlayer';
2
+ import { createConverseApi } from '../converse/api';
3
+ import { createConverseController } from '../converse/controller';
4
+ import { createFakeConverseApi } from '../converse/fake';
5
+ import { createDiagnostics } from '../recording/diagnostics';
6
+ import { createPermissionFlow } from '../recording/permissions';
7
+ import { createRecorderAudio } from '../recording/recorderAudio';
8
+ import type { createSession } from '../recording/session';
9
+ import type { FoundryAppConfig } from './config/types';
10
+ import type { FoundryDevice } from './device';
11
+
12
+ const newTurnId = () => `cv-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
13
+ const tick = (fn: () => void, ms: number) => { const h = setInterval(fn, ms); return () => clearInterval(h); };
14
+ const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
15
+
16
+ /**
17
+ * The Converse tab's services: its own recorder audio (a turn is never a voice note, so it never reaches the upload queue)
18
+ * and its own player over the device's playback driver, sharing the recorder's audio-session inspector so the
19
+ * playback <-> playAndRecord handoff is the same proven one the briefing reply uses.
20
+ */
21
+ export function createConverse(deps: {
22
+ config: FoundryAppConfig;
23
+ device: FoundryDevice;
24
+ session: ReturnType<typeof createSession>;
25
+ diag: ReturnType<typeof createDiagnostics>;
26
+ fake: boolean;
27
+ }) {
28
+ const { config, device, session, diag, fake } = deps;
29
+ const rec = device.recording;
30
+ if (!rec) throw new Error('features.converse needs the recording bindings (features.recording on, device.recording supplied)');
31
+ const dev = device.briefing;
32
+ if (!dev) throw new Error('features.converse needs a playback driver (device.briefing.driver)');
33
+ const inspector = dev.session ?? rec.session;
34
+ const player = createAudioPlayer({ driver: dev.driver, session: inspector, diag, poll: tick, sleep: wait });
35
+ const audio = createRecorderAudio({
36
+ driver: rec.driver, session: rec.session, fs: { size: rec.fileSize }, poll: tick, sleep: wait, diag, onInterrupted: () => undefined,
37
+ });
38
+ const permissions = createPermissionFlow({ perms: rec.permissions, openSettings: rec.openSettings, log: diag.log });
39
+ const api = fake
40
+ ? createFakeConverseApi({ ...(dev.fixture ? { fixture: dev.fixture } : {}) })
41
+ : createConverseApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer, filePart: rec.filePart });
42
+ const controller = createConverseController({
43
+ api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, newId: newTurnId, diag, allowSilence: fake,
44
+ });
45
+ return { controller, player };
46
+ }
@@ -13,6 +13,7 @@ import type { FoundryAppConfig } from './config/types';
13
13
  * -tgAutostop N start a timed recording after sign-in
14
14
  * -tgFakeBriefing 1 'What's on the plate' plays a bundled clip over a fixed briefing: no server, no sign-in (add -tgFakeTabs 1)
15
15
  * -tgFakeReply "a|b" what the fake reply 'hears' on each hold-to-talk, in order (needs -tgFakeBriefing); default "move this one to later"
16
+ * -tgFakeConverse 1 the Converse tab talks to a scripted assistant: no server, no sign-in (add -tgFakeTabs 1)
16
17
  * -tgHapticProbe 1 fire one haptic per interaction through the real engine; the diagnostics log shows each call and the engine's answer
17
18
  * -tgScheme light|dark override the config's theme mode (simulator checks of the light theme)
18
19
  */
@@ -29,6 +30,8 @@ export interface LaunchArgs {
29
30
  fakeBriefing: boolean;
30
31
  /** `-tgFakeReply "a|b"`: what each recorded reply is taken to say, in order. */
31
32
  fakeReply: string[];
33
+ /** `-tgFakeConverse 1`: the Converse tab talks to a scripted assistant (and speaks with the bundled clip). */
34
+ fakeConverse: boolean;
32
35
  }
33
36
 
34
37
  export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAppConfig, 'tabs'>): LaunchArgs {
@@ -50,6 +53,7 @@ export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAp
50
53
  scenario: readFakeScenario((k) => str(k)),
51
54
  target,
52
55
  autostop: Number.isFinite(n) && n > 0 ? n : null,
56
+ fakeConverse: str('tgFakeConverse') === '1',
53
57
  hapticProbe: str('tgHapticProbe') === '1',
54
58
  fakeBriefing: str('tgFakeBriefing') === '1',
55
59
  fakeReply: str('tgFakeReply').split('|').map((l) => l.trim()).filter(Boolean),
@@ -11,6 +11,8 @@ import { createConnectionsTab } from '../screens/connections/tab';
11
11
  import { createPlanningTab } from '../screens/planning/tab';
12
12
  import { askTab, libraryTab } from '../screens/tabs';
13
13
  import { trackerTab } from '../tracker/tab';
14
+ import type { ConverseController } from '../converse/controller';
15
+ import { converseTab } from '../converse/tab';
14
16
  import type { VoiceNotesController } from '../voice/controller';
15
17
  import { SCREEN_DEFAULTS } from './config/defaults';
16
18
  import { shellLabel, tabForEntityType, tabLabel } from './config/validate';
@@ -31,6 +33,8 @@ export interface ScreenDeps {
31
33
  /** Opens a URL outside the app (`Linking.openURL`): a vendor's sign-in page, a tracker item. Absent in tests. */
32
34
  openUrl?: (url: string) => Promise<unknown>;
33
35
  /** Fires when something outside a list changed its items (a spoken reply to the briefing): lists re-read. */
36
+ /** The Converse conversation; null when `features.converse` is off. */
37
+ converse?: ConverseController | null;
34
38
  itemsChanged?: { subscribe(listener: () => void): () => void };
35
39
  }
36
40
 
@@ -69,6 +73,10 @@ export const BUILTIN_FACTORIES: Record<string, ScreenFactory> = {
69
73
  planning: ({ config, corpus }, tab) => createPlanningTab({ api: corpus, key: tab.key, label: tabLabel(tab), documentTab: firstKey(config, 'library') }),
70
74
  connections: ({ config, member, openUrl }, tab) => createConnectionsTab({ api: member.connections, key: tab.key, label: tabLabel(tab), openUrl, returnTo: `${config.app.scheme}://${tab.key}` }),
71
75
  'connect-claude': ({ member }, tab) => createConnectClaudeTab({ api: member.mcpTokens, key: tab.key, label: tab.label ?? `Claude` }),
76
+ converse: ({ converse }, tab) => {
77
+ if (!converse) throw new Error(`tab "${tab.key}": the converse screen needs features.converse on`);
78
+ return converseTab(converse, { key: tab.key, label: tabLabel(tab) });
79
+ },
72
80
  entity: ({ config, corpus }, tab) => {
73
81
  const type = String(tab.options?.entityType);
74
82
  // A type the config does not describe is labelled from its key until the tenant schema fills it in.
@@ -14,6 +14,7 @@ import { createLinkResolver } from './config/links';
14
14
  import type { FoundryAppConfig } from './config/types';
15
15
  import type { FoundryDevice, RecordingDevice } from './device';
16
16
  import { createBriefing, type FakeBriefingDeps } from './briefingServices';
17
+ import { createConverse } from './converseServices';
17
18
  import type { FoundryStrings } from './strings';
18
19
 
19
20
  const newId = () => `fa-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
@@ -104,7 +105,7 @@ function createRecording(deps: { config: FoundryAppConfig; device: FoundryDevice
104
105
  * The composition root: session (sign-in, refresh, sign-out), diagnostics, the link router and, when recording is on,
105
106
  * the recorder with its upload queue. The app shell passes the device bindings; nothing here is Foundry-specific.
106
107
  */
107
- export function createFoundryServices(deps: { config: FoundryAppConfig; device: FoundryDevice; banners: Banners; strings: FoundryStrings; /** `-tgFakeBriefing`: a fixed briefing and the device's bundled clip over the fake tenant (and `-tgFakeReply`'s script). */ fakeBriefing?: FakeBriefingDeps | null }) {
108
+ export function createFoundryServices(deps: { config: FoundryAppConfig; device: FoundryDevice; banners: Banners; strings: FoundryStrings; /** `-tgFakeBriefing`: a fixed briefing and the device's bundled clip over the fake tenant (and `-tgFakeReply`'s script). */ fakeBriefing?: FakeBriefingDeps | null; /** `-tgFakeConverse`: the Converse tab talks to a scripted assistant. */ fakeConverse?: boolean }) {
108
109
  const { config, device, banners } = deps;
109
110
  const diagPath = device.documentUri('diagnostics.json');
110
111
  const diag = createDiagnostics({
@@ -127,6 +128,8 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
127
128
 
128
129
  const briefing = config.features.briefing ? createBriefing({ config, device, session, diag, strings: deps.strings, fake: deps.fakeBriefing ?? null }) : null;
129
130
 
131
+ const converse = config.features.converse ? createConverse({ config, device, session, diag, fake: Boolean(deps.fakeConverse) }) : null;
132
+
130
133
  let open: (tab: string, id?: string) => void = () => undefined;
131
134
  const goTab = config.tabs.find((t) => t.screen === 'record')?.key;
132
135
  const deepLink = createDeepLink({
@@ -146,7 +149,7 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
146
149
  AppState.addEventListener('change', (state) => diag.log('app.state', { state }));
147
150
 
148
151
  return {
149
- diag, session, deepLink, recording, briefing,
152
+ diag, session, deepLink, recording, briefing, converse,
150
153
  /** The shell navigator calls this once it exists, so warm links can open tabs. */
151
154
  bindOpen(fn: (tab: string, id?: string) => void) { open = fn; },
152
155
  /** After sign-in/restore. */
@@ -0,0 +1,70 @@
1
+ import { useRef } from 'react';
2
+ import { FlatList, Pressable, Text as RNText, View } from 'react-native';
3
+ import { Alert, Button, EmptyState, Header, MessageBubble, Spinner, useHaptics, useTheme } from '@startsimpli/ui-native';
4
+ import { useControllerState } from '../components/useControllerState';
5
+ import type { ConverseController, ConverseTurn } from './controller';
6
+ import { buttonLabel, statusLine } from './format';
7
+
8
+ const BIG = 176;
9
+
10
+ /**
11
+ * Converse: one big tap-to-talk button for the car. Tap to start, tap to send, the reply plays by itself. Repeat says
12
+ * the last reply again; End saves the conversation. The transcript is there to glance at, never needed to use it.
13
+ */
14
+ export function ConverseScreen({ controller }: { controller: ConverseController }) {
15
+ const theme = useTheme();
16
+ const haptic = useHaptics();
17
+ const s = useControllerState(controller);
18
+ const list = useRef<FlatList<ConverseTurn>>(null);
19
+ const live = s.phase === 'recording';
20
+ const busy = s.phase === 'sending' || s.phase === 'saving' || s.phase === 'starting';
21
+ const color = live ? theme.colors.destructive : theme.colors.primary;
22
+
23
+ return (
24
+ <View style={{ flex: 1 }} testID="converse-screen">
25
+ <Header large testID="converse-header" title="Converse" subtitle={s.conversationId ? 'Conversation in progress' : 'Talk it through'} />
26
+ <FlatList
27
+ ref={list}
28
+ testID="converse-transcript"
29
+ style={{ flex: 1 }}
30
+ data={s.turns}
31
+ keyExtractor={(t) => t.id}
32
+ onContentSizeChange={() => list.current?.scrollToEnd?.({ animated: true })}
33
+ contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md, flexGrow: 1 }}
34
+ ListEmptyComponent={
35
+ <EmptyState icon="ask" title={s.saved ? 'Saved' : 'Make a plan out loud'} description={s.saved ? 'The conversation is saved. Tap to start a new one.' : 'Tap the big button, say what is on your mind, tap again to send. The answer plays back.'} />
36
+ }
37
+ renderItem={({ item }) => <MessageBubble role={item.role === 'you' ? 'user' : 'assistant'} text={item.text} testID={`converse-turn-${item.id}`} />}
38
+ />
39
+ <View style={{ alignItems: 'center', gap: theme.spacing.md, paddingBottom: theme.spacing.lg, paddingHorizontal: theme.spacing.lg }}>
40
+ {s.error ? (
41
+ <View style={{ gap: theme.spacing.sm, alignSelf: 'stretch' }} testID="converse-error">
42
+ <Alert variant="destructive">{s.error}</Alert>
43
+ <View style={{ flexDirection: 'row', gap: theme.spacing.sm }}>
44
+ {s.retryable ? <Button testID="converse-retry" title="Retry" variant="outline" onPress={() => { haptic('light', 'converse.retry'); void controller.retry(); }} /> : null}
45
+ <Button testID="converse-dismiss" title="Dismiss" variant="outline" onPress={() => { void controller.dismissError(); }} />
46
+ </View>
47
+ </View>
48
+ ) : null}
49
+ <Pressable
50
+ testID="converse-talk"
51
+ accessibilityRole="button"
52
+ accessibilityLabel={live ? 'Send' : 'Talk'}
53
+ accessibilityHint={statusLine(s.phase, s.elapsedSec)}
54
+ disabled={busy}
55
+ onPress={() => { haptic(live ? 'success' : 'medium', 'converse.talk'); void controller.tap(); }}
56
+ style={{ width: BIG, height: BIG, borderRadius: BIG / 2, backgroundColor: color, alignItems: 'center', justifyContent: 'center', opacity: busy ? 0.6 : 1 }}
57
+ >
58
+ {busy ? <Spinner /> : <RNText style={{ color: theme.colors.primaryForeground, fontSize: 32, fontWeight: '800' }}>{buttonLabel(s.phase)}</RNText>}
59
+ </Pressable>
60
+ <RNText testID="converse-status" style={{ color: theme.colors.foreground, fontSize: theme.fontSizes.lg, fontWeight: '600', textAlign: 'center' }}>
61
+ {statusLine(s.phase, s.elapsedSec)}
62
+ </RNText>
63
+ <View style={{ flexDirection: 'row', gap: theme.spacing.md }}>
64
+ <Button testID="converse-repeat" title="Repeat" variant="outline" size="lg" disabled={!s.canRepeat || busy || live} onPress={() => { haptic('light', 'converse.repeat'); void controller.repeat(); }} />
65
+ <Button testID="converse-end" title="End" variant="outline" size="lg" disabled={busy || (!s.conversationId && !live)} onPress={() => { haptic('warning', 'converse.end'); void controller.end(); }} />
66
+ </View>
67
+ </View>
68
+ </View>
69
+ );
70
+ }
@@ -0,0 +1,182 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import type { PlayerState } from '../../briefing/audioPlayer';
3
+ import type { ConverseReply } from '../api';
4
+ import { createConverseController } from '../controller';
5
+ import { createConverseApi } from '../api';
6
+ import { createFakeConverseApi } from '../fake';
7
+
8
+ const reply = (over: Partial<ConverseReply> = {}): ConverseReply => ({ conversationId: 'c1', transcript: 'plan my day', replyText: 'Three things today.', audioUrl: '/corpus/converse/c1/audio', ...over });
9
+
10
+ function setup(opts: { permission?: 'granted' | 'denied'; api?: Record<string, unknown>; file?: Record<string, unknown> } = {}) {
11
+ const order: string[] = [];
12
+ let n = 0;
13
+ const audio = {
14
+ start: vi.fn(async () => { order.push('audio.start'); }),
15
+ stop: vi.fn(async () => ({ uri: 'file:///t.m4a', durationMs: 2000, bytes: 9000, peakDb: -10, ...opts.file })),
16
+ };
17
+ const api = {
18
+ send: vi.fn(async () => reply()),
19
+ end: vi.fn(async () => undefined),
20
+ replySource: vi.fn(async (r: ConverseReply) => (r.audioUrl ? { uri: `http://x${r.audioUrl}` } : null)),
21
+ ...opts.api,
22
+ };
23
+ let ps: PlayerState = { phase: 'idle', positionMillis: 0, durationMillis: 0 };
24
+ const ls = new Set<(s: PlayerState) => void>();
25
+ const speaker = {
26
+ getState: () => ps,
27
+ subscribe: (cb: (s: PlayerState) => void) => { ls.add(cb); return () => ls.delete(cb); },
28
+ play: vi.fn(async () => { order.push('speak'); }),
29
+ stop: vi.fn(async () => undefined),
30
+ handoffToRecording: vi.fn(async () => { order.push('handoff'); }),
31
+ };
32
+ const end = (phase: PlayerState['phase']) => { ps = { ...ps, phase }; ls.forEach((l) => l(ps)); };
33
+ const removeFile = vi.fn(async () => undefined);
34
+ const c = createConverseController({
35
+ api: api as never, audio, speaker, removeFile, ensurePermission: async () => opts.permission ?? 'granted',
36
+ newId: () => `t${++n}`, tick: () => () => undefined,
37
+ });
38
+ return { c, order, audio, api, speaker, removeFile, end };
39
+ }
40
+
41
+ describe('tap to talk', () => {
42
+ it('records on the first tap, sends on the second, shows both sides and speaks the reply', async () => {
43
+ const s = setup();
44
+ await s.c.tap();
45
+ expect(s.c.getState().phase).toBe('recording');
46
+ await s.c.tap();
47
+ expect(s.api.send).toHaveBeenCalledWith({ conversationId: null, turnId: 't1', recording: { uri: 'file:///t.m4a', durationMs: 2000 } });
48
+ expect(s.c.getState().turns.map((t) => [t.role, t.text])).toEqual([['you', 'plan my day'], ['assistant', 'Three things today.']]);
49
+ expect(s.order).toEqual(['handoff', 'audio.start', 'speak']);
50
+ expect(s.c.getState()).toMatchObject({ phase: 'speaking', conversationId: 'c1', canRepeat: true });
51
+ expect(s.removeFile).toHaveBeenCalledWith('file:///t.m4a');
52
+ });
53
+
54
+ it('goes back to idle when the reply finishes, and the next turn carries the conversation id', async () => {
55
+ const s = setup();
56
+ await s.c.tap(); await s.c.tap();
57
+ s.end('ended');
58
+ expect(s.c.getState().phase).toBe('idle');
59
+ await s.c.tap(); await s.c.tap();
60
+ expect(s.api.send).toHaveBeenLastCalledWith(expect.objectContaining({ conversationId: 'c1' }));
61
+ expect(s.c.getState().turns).toHaveLength(4);
62
+ });
63
+
64
+ it('talking over the reply is allowed: a tap while speaking starts recording', async () => {
65
+ const s = setup();
66
+ await s.c.tap(); await s.c.tap();
67
+ expect(s.c.getState().phase).toBe('speaking');
68
+ await s.c.tap();
69
+ expect(s.c.getState().phase).toBe('recording');
70
+ expect(s.speaker.handoffToRecording).toHaveBeenCalledTimes(2);
71
+ });
72
+
73
+ it('a text-only reply is shown and not spoken', async () => {
74
+ const s = setup({ api: { send: vi.fn(async () => reply({ audioUrl: null })) } });
75
+ await s.c.tap(); await s.c.tap();
76
+ expect(s.speaker.play).not.toHaveBeenCalled();
77
+ expect(s.c.getState()).toMatchObject({ phase: 'idle', canRepeat: false });
78
+ });
79
+
80
+ it('repeat says the last reply again', async () => {
81
+ const s = setup();
82
+ await s.c.tap(); await s.c.tap(); s.end('ended');
83
+ await s.c.repeat();
84
+ expect(s.speaker.play).toHaveBeenCalledTimes(2);
85
+ });
86
+
87
+ it('refuses a too-short or silent take without sending', async () => {
88
+ const short = setup({ file: { durationMs: 100 } });
89
+ await short.c.tap(); await short.c.tap();
90
+ expect(short.api.send).not.toHaveBeenCalled();
91
+ expect(short.c.getState()).toMatchObject({ phase: 'error', retryable: false });
92
+ expect(short.removeFile).toHaveBeenCalled();
93
+ const silent = setup({ file: { peakDb: -90 } });
94
+ await silent.c.tap(); await silent.c.tap();
95
+ expect(silent.api.send).not.toHaveBeenCalled();
96
+ });
97
+
98
+ it('denied microphone is an error, not a recording', async () => {
99
+ const s = setup({ permission: 'denied' });
100
+ await s.c.tap();
101
+ expect(s.c.getState().phase).toBe('error');
102
+ expect(s.audio.start).not.toHaveBeenCalled();
103
+ });
104
+
105
+ it('a network failure keeps the take for a retry; the retry sends the same recording', async () => {
106
+ const send = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce(reply());
107
+ const s = setup({ api: { send } });
108
+ await s.c.tap(); await s.c.tap();
109
+ expect(s.c.getState()).toMatchObject({ phase: 'error', retryable: true });
110
+ expect(s.removeFile).not.toHaveBeenCalled();
111
+ await s.c.retry();
112
+ expect(send).toHaveBeenCalledTimes(2);
113
+ expect(send.mock.calls[1][0]).toEqual(send.mock.calls[0][0]);
114
+ expect(s.removeFile).toHaveBeenCalledWith('file:///t.m4a');
115
+ expect(s.c.getState().turns).toHaveLength(2);
116
+ });
117
+
118
+ it('transcription_failed is retryable with its own message', async () => {
119
+ const s = setup({ api: { send: vi.fn(async () => { throw Object.assign(new Error('x'), { code: 'transcription_failed', status: 422 }); }) } });
120
+ await s.c.tap(); await s.c.tap();
121
+ expect(s.c.getState()).toMatchObject({ phase: 'error', retryable: true });
122
+ });
123
+
124
+ it('End saves the conversation and the next tap starts a new one', async () => {
125
+ const s = setup();
126
+ await s.c.tap(); await s.c.tap(); s.end('ended');
127
+ await s.c.end();
128
+ expect(s.api.end).toHaveBeenCalledWith('c1');
129
+ expect(s.c.getState()).toMatchObject({ phase: 'idle', conversationId: null, turns: [], saved: true });
130
+ await s.c.tap(); await s.c.tap();
131
+ expect(s.api.send).toHaveBeenLastCalledWith(expect.objectContaining({ conversationId: null }));
132
+ });
133
+
134
+ it('a failed save keeps the conversation and says so', async () => {
135
+ const s = setup({ api: { end: vi.fn(async () => { throw new Error('no'); }) } });
136
+ await s.c.tap(); await s.c.tap();
137
+ await s.c.end();
138
+ expect(s.c.getState()).toMatchObject({ phase: 'error', conversationId: 'c1' });
139
+ expect(s.c.getState().turns).toHaveLength(2);
140
+ });
141
+
142
+ it('stop drops a take in progress without sending it', async () => {
143
+ const s = setup();
144
+ await s.c.tap();
145
+ await s.c.stop();
146
+ expect(s.api.send).not.toHaveBeenCalled();
147
+ expect(s.removeFile).toHaveBeenCalledWith('file:///t.m4a');
148
+ expect(s.c.getState().phase).toBe('idle');
149
+ });
150
+ });
151
+
152
+ describe('converse api', () => {
153
+ it('posts audio and conversation_id as multipart and maps the answer; end posts JSON', async () => {
154
+ const fetchMock = vi.fn(async (url: string) => new Response(JSON.stringify(url.endsWith('/end') ? { saved: true } : { conversation_id: 'c9', transcript: 'hi', reply_text: 'hello', audio_url: '/a.mp3' }), { status: 200 }));
155
+ const form = new FormData();
156
+ const api = createConverseApi({ tandemUrl: 'http://t/', authorizedFetch: fetchMock as never, bearer: async () => 'tok', filePart: () => new Blob(['x']), createForm: () => form, timeZone: 'UTC' });
157
+ const r = await api.send({ conversationId: 'c9', turnId: 'turn-123456', recording: { uri: 'file:///a.m4a', durationMs: 1000 } });
158
+ expect(r).toEqual({ conversationId: 'c9', transcript: 'hi', replyText: 'hello', audioUrl: '/a.mp3' });
159
+ expect(fetchMock.mock.calls[0][0]).toBe('http://t/corpus/converse');
160
+ expect(form.get('conversation_id')).toBe('c9');
161
+ expect(form.get('timeZone')).toBe('UTC');
162
+ expect(form.get('turn_id')).toBe('turn-123456');
163
+ expect(form.has('audio')).toBe(true);
164
+ expect(await api.replySource(r)).toEqual({ uri: 'http://t/a.mp3', headers: { authorization: 'Bearer tok' } });
165
+ await api.end('c9');
166
+ expect(fetchMock.mock.calls[1][0]).toBe('http://t/corpus/converse/end');
167
+ expect(JSON.parse((fetchMock.mock.calls[1][1] as RequestInit).body as string)).toEqual({ conversation_id: 'c9' });
168
+ });
169
+
170
+ it('throws the route status and code on a refusal', async () => {
171
+ const api = createConverseApi({ tandemUrl: 'http://t', authorizedFetch: (async () => new Response(JSON.stringify({ detail: 'nope', code: 'transcription_failed' }), { status: 422 })) as never, bearer: async () => null, createForm: () => new FormData() });
172
+ await expect(api.send({ conversationId: null, text: 'x' })).rejects.toMatchObject({ status: 422, code: 'transcription_failed', message: 'nope' });
173
+ });
174
+
175
+ it('the fake cycles its script and records ended conversations', async () => {
176
+ const f = createFakeConverseApi({ heard: ['a'], replies: ['one', 'two'] });
177
+ expect((await f.send({ conversationId: null })).replyText).toBe('one');
178
+ expect((await f.send({ conversationId: 'fake-conversation' })).replyText).toBe('two');
179
+ await f.end('fake-conversation');
180
+ expect(f.ended).toEqual(['fake-conversation']);
181
+ });
182
+ });