@startsimpli/integrations 0.2.162 → 0.2.164
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 +4 -4
- package/src/__tests__/converse-brain.test.ts +101 -0
- package/src/__tests__/converse-client.test.ts +39 -0
- package/src/__tests__/converse-config.test.ts +9 -0
- package/src/__tests__/converse-extract.test.ts +19 -0
- package/src/__tests__/converse-page.test.tsx +104 -0
- package/src/__tests__/converse.test.ts +212 -0
- package/src/components/index.ts +2 -0
- package/src/components/pages/ConversePage.tsx +184 -0
- package/src/components/pages/converse/silence.ts +20 -0
- package/src/components/pages/converse/useRecorder.ts +55 -0
- package/src/corpus/converse/brain.ts +89 -0
- package/src/corpus/converse/client.ts +64 -0
- package/src/corpus/converse/config.ts +21 -0
- package/src/corpus/converse/extract.ts +41 -0
- package/src/corpus/converse/handle.ts +147 -0
- package/src/corpus/converse/index.ts +17 -0
- package/src/corpus/converse/respond.ts +88 -0
- package/src/corpus/converse/store.ts +74 -0
- package/src/corpus/converse/transcript.ts +20 -0
- package/src/corpus/converse/types.ts +133 -0
- package/src/corpus/index.ts +1 -0
- package/src/native/app/FoundryApp.tsx +2 -2
- package/src/native/app/__tests__/launch.test.ts +1 -1
- package/src/native/app/config/defaults.ts +3 -2
- package/src/native/app/config/types.ts +3 -1
- package/src/native/app/converseServices.ts +48 -0
- package/src/native/app/launch.ts +8 -0
- package/src/native/app/registry.tsx +8 -0
- package/src/native/app/services.ts +5 -2
- package/src/native/converse/ConverseScreen.tsx +70 -0
- package/src/native/converse/__tests__/controller.test.ts +189 -0
- package/src/native/converse/api.ts +91 -0
- package/src/native/converse/controller.ts +252 -0
- package/src/native/converse/fake.ts +34 -0
- package/src/native/converse/format.ts +25 -0
- package/src/native/converse/index.ts +8 -0
- package/src/native/converse/tab.tsx +14 -0
- package/src/native/index.ts +1 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetch-`Response` wrappers for the tenant frontend's route files:
|
|
3
|
+
* POST /corpus/converse multipart (audio | text, conversation_id, timeZone, turn_id) or JSON
|
|
4
|
+
* POST /corpus/converse/end JSON {conversation_id}
|
|
5
|
+
* GET /corpus/converse/<id>/turn/<n>/audio[?who=user] a turn's recording, to its owner only
|
|
6
|
+
*/
|
|
7
|
+
import { isTimeZone } from '../spoken-time';
|
|
8
|
+
import { voiceErrorResponse } from '../voice-manage';
|
|
9
|
+
import { handleConverseEnd, handleConverseTurn } from './handle';
|
|
10
|
+
import { createEntityConversationStore } from './store';
|
|
11
|
+
import { CLIENT_ID, ConverseError, MAX_CONVERSE_AUDIO_BYTES, type ConverseDeps, type ConverseTurnRequest } from './types';
|
|
12
|
+
|
|
13
|
+
const str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
|
|
14
|
+
|
|
15
|
+
async function fieldsOf(request: Request): Promise<{ fields: Record<string, unknown>; audio?: ConverseTurnRequest['audio'] }> {
|
|
16
|
+
const type = request.headers.get('content-type') ?? '';
|
|
17
|
+
if (type.includes('multipart/form-data')) {
|
|
18
|
+
const form = (await request.formData().catch(() => { throw new ConverseError('Send multipart form data or JSON.', 400); })) as unknown as {
|
|
19
|
+
entries(): Iterable<[string, unknown]>;
|
|
20
|
+
get(name: string): unknown;
|
|
21
|
+
};
|
|
22
|
+
const fields = Object.fromEntries([...form.entries()].filter(([, v]) => typeof v === 'string'));
|
|
23
|
+
const file = form.get('audio');
|
|
24
|
+
if (file instanceof Blob && file.size > 0) {
|
|
25
|
+
if (file.size > MAX_CONVERSE_AUDIO_BYTES) throw new ConverseError('That recording is too long for one turn.', 413);
|
|
26
|
+
return { fields, audio: { audio: new Uint8Array(await file.arrayBuffer()), mimeType: file.type || 'audio/mp4' } };
|
|
27
|
+
}
|
|
28
|
+
return { fields };
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
const fields = JSON.parse((await request.text()) || '{}');
|
|
32
|
+
if (!fields || typeof fields !== 'object') throw new Error('shape');
|
|
33
|
+
return { fields };
|
|
34
|
+
} catch {
|
|
35
|
+
throw new ConverseError('Send JSON, or multipart with the recording.', 400);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const failure = (error: unknown) =>
|
|
40
|
+
error instanceof ConverseError
|
|
41
|
+
? Response.json({ detail: error.message, ...(error.code ? { code: error.code } : {}) }, { status: error.status })
|
|
42
|
+
: voiceErrorResponse(error);
|
|
43
|
+
|
|
44
|
+
export async function converseResponse(request: Request, deps: ConverseDeps): Promise<Response> {
|
|
45
|
+
try {
|
|
46
|
+
const { fields, audio } = await fieldsOf(request);
|
|
47
|
+
const zone = str(fields.timeZone);
|
|
48
|
+
return Response.json(await handleConverseTurn(deps, {
|
|
49
|
+
conversationId: str(fields.conversation_id ?? fields.conversationId),
|
|
50
|
+
turnId: str(fields.turn_id ?? fields.turnId),
|
|
51
|
+
...(str(fields.text) ? { text: str(fields.text) } : {}),
|
|
52
|
+
...(audio ? { audio } : {}),
|
|
53
|
+
...(zone && isTimeZone(zone) ? { timeZone: zone } : {}),
|
|
54
|
+
}));
|
|
55
|
+
} catch (error) {
|
|
56
|
+
return failure(error);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function converseEndResponse(request: Request, deps: ConverseDeps): Promise<Response> {
|
|
61
|
+
try {
|
|
62
|
+
const { fields } = await fieldsOf(request);
|
|
63
|
+
return Response.json(await handleConverseEnd(deps, { conversationId: str(fields.conversation_id ?? fields.conversationId) ?? '' }));
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return failure(error);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A turn's recording. The conversation is read as the caller, so anyone else's id is a 404. */
|
|
70
|
+
export async function converseAudioResponse(
|
|
71
|
+
conversationId: string,
|
|
72
|
+
n: number,
|
|
73
|
+
who: 'user' | 'reply',
|
|
74
|
+
deps: Pick<ConverseDeps, 'http' | 'ownerSub' | 'store'> & { audio?: ConverseDeps['audio'] },
|
|
75
|
+
): Promise<Response> {
|
|
76
|
+
const notFound = () => Response.json({ detail: 'Not found.' }, { status: 404 });
|
|
77
|
+
if (!CLIENT_ID.test(conversationId) || !Number.isInteger(n) || n < 1 || !deps.audio) return notFound();
|
|
78
|
+
try {
|
|
79
|
+
const store = deps.store ?? createEntityConversationStore(deps.http, deps.ownerSub);
|
|
80
|
+
const turn = (await store.get(conversationId))?.turns.find((t) => t.n === n);
|
|
81
|
+
const ref = who === 'user' ? turn?.user.audio_ref : turn?.assistant.audio_ref;
|
|
82
|
+
if (!ref) return notFound();
|
|
83
|
+
const { audio, mimeType } = await deps.audio.get(ref);
|
|
84
|
+
return new Response(audio as BodyInit, { headers: { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'content-length': String(audio.byteLength) } });
|
|
85
|
+
} catch (error) {
|
|
86
|
+
return failure(error);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a conversation is kept: ONE tenant row per conversation, keyed `conversation:<id>:<owner>`.
|
|
3
|
+
*
|
|
4
|
+
* A generic `source_document` with source `conversation` (CLAUDE.md rule 5: no new table). It carries NO
|
|
5
|
+
* `body` while it is open, so nothing can mistake a half-finished talk for a finished document; End
|
|
6
|
+
* writes the transcript into `body`. Owner scope is checked HERE as well as by the tenant: the lookup key
|
|
7
|
+
* carries the owner and a row whose `owner_sub` is not the caller's is treated as absent.
|
|
8
|
+
*/
|
|
9
|
+
import type { TenantEntity } from '../entities';
|
|
10
|
+
import { CONVERSATION_SOURCE, type ConversationRecord, type ConversationStore, type ConverseDeps, type ConverseTurn } from './types';
|
|
11
|
+
|
|
12
|
+
export const conversationExternalId = (conversationId: string, ownerSub: string) => `conversation:${conversationId}:${ownerSub}`;
|
|
13
|
+
|
|
14
|
+
const text = (v: unknown) => (typeof v === 'string' ? v : '');
|
|
15
|
+
const list = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : []);
|
|
16
|
+
|
|
17
|
+
function toRecord(entity: TenantEntity): ConversationRecord {
|
|
18
|
+
const d = (entity.data ?? {}) as Record<string, unknown>;
|
|
19
|
+
return {
|
|
20
|
+
id: String(entity.id),
|
|
21
|
+
conversationId: text(d.conversation_id),
|
|
22
|
+
externalId: text(entity.external_id ?? entity.externalId),
|
|
23
|
+
status: d.status === 'ended' ? 'ended' : 'open',
|
|
24
|
+
startedAt: text(d.started_at),
|
|
25
|
+
...(d.ended_at ? { endedAt: text(d.ended_at) } : {}),
|
|
26
|
+
...(d.time_zone ? { timeZone: text(d.time_zone) } : {}),
|
|
27
|
+
title: text(d.title),
|
|
28
|
+
turns: Array.isArray(d.turns) ? (d.turns as ConverseTurn[]) : [],
|
|
29
|
+
...(d.body ? { body: text(d.body) } : {}),
|
|
30
|
+
...(d.asks ? { asks: list(d.asks) } : {}),
|
|
31
|
+
...(d.decisions ? { decisions: list(d.decisions) } : {}),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createEntityConversationStore(http: ConverseDeps['http'], ownerSub: string): ConversationStore {
|
|
36
|
+
return {
|
|
37
|
+
async get(conversationId) {
|
|
38
|
+
const externalId = conversationExternalId(conversationId, ownerSub);
|
|
39
|
+
const page = await http.get<{ results?: TenantEntity[] }>('api/v1/entities', {
|
|
40
|
+
params: { type: 'source_document', external_id__in: externalId, page_size: 5 },
|
|
41
|
+
});
|
|
42
|
+
const hit = (page.results ?? []).find((r) => {
|
|
43
|
+
const data = (r.data ?? {}) as Record<string, unknown>;
|
|
44
|
+
return (r.external_id ?? r.externalId) === externalId && data.owner_sub === ownerSub && data.source === CONVERSATION_SOURCE;
|
|
45
|
+
});
|
|
46
|
+
return hit ? toRecord(hit) : null;
|
|
47
|
+
},
|
|
48
|
+
async save(record) {
|
|
49
|
+
const row = await http.post<TenantEntity>('api/v1/entities/upsert', {
|
|
50
|
+
entity_type: 'source_document',
|
|
51
|
+
external_id: conversationExternalId(record.conversationId, ownerSub),
|
|
52
|
+
name: record.title,
|
|
53
|
+
data: {
|
|
54
|
+
title: record.title,
|
|
55
|
+
source: CONVERSATION_SOURCE,
|
|
56
|
+
source_label: 'Conversation',
|
|
57
|
+
source_ref: conversationExternalId(record.conversationId, ownerSub),
|
|
58
|
+
occurred_at: record.startedAt,
|
|
59
|
+
owner_sub: ownerSub,
|
|
60
|
+
conversation_id: record.conversationId,
|
|
61
|
+
status: record.status,
|
|
62
|
+
started_at: record.startedAt,
|
|
63
|
+
ended_at: record.endedAt ?? '',
|
|
64
|
+
time_zone: record.timeZone ?? '',
|
|
65
|
+
turns: record.turns,
|
|
66
|
+
...(record.body !== undefined ? { body: record.body } : {}),
|
|
67
|
+
...(record.asks ? { asks: record.asks } : {}),
|
|
68
|
+
...(record.decisions ? { decisions: record.decisions } : {}),
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
return { ...record, id: String(row.id) };
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** A conversation as a document: what is saved as the record's `body` at End. Pure. */
|
|
2
|
+
import type { ConversationRecord } from './types';
|
|
3
|
+
|
|
4
|
+
export function renderTranscript(record: Pick<ConversationRecord, 'turns' | 'startedAt' | 'timeZone' | 'asks' | 'decisions'>): string {
|
|
5
|
+
const lines: string[] = [];
|
|
6
|
+
if (record.asks?.length) lines.push('## Asks', ...record.asks.map((a) => `- ${a}`), '');
|
|
7
|
+
if (record.decisions?.length) lines.push('## Decisions', ...record.decisions.map((d) => `- ${d}`), '');
|
|
8
|
+
lines.push('## Transcript');
|
|
9
|
+
for (const turn of record.turns) {
|
|
10
|
+
lines.push('', `**You:** ${turn.user.text}`, '', `**Tandem:** ${turn.assistant.text}`);
|
|
11
|
+
if (turn.did?.length) lines.push('', ...turn.did.map((d) => `_${d}_`));
|
|
12
|
+
}
|
|
13
|
+
return lines.join('\n').trim();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function titleFor(startedAt: string, firstWords: string): string {
|
|
17
|
+
const day = startedAt.slice(0, 10);
|
|
18
|
+
const words = firstWords.replace(/\s+/g, ' ').trim().split(' ').slice(0, 7).join(' ');
|
|
19
|
+
return words ? `Conversation ${day}: ${words}` : `Conversation ${day}`;
|
|
20
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE CONVERSE ENDPOINT'S SHAPES (bd startsim-wc67c, startsim-kufsm).
|
|
3
|
+
*
|
|
4
|
+
* One turn = one thing said + one thing said back. The conversation (its turns, both recordings,
|
|
5
|
+
* the transcript) is ONE owner-only tenant record, saved after EVERY turn: a drive ends without
|
|
6
|
+
* anyone pressing End, and the recording is half of what was asked to be kept.
|
|
7
|
+
*
|
|
8
|
+
* Field names on the wire are the iOS app's contract: `conversation_id` (snake), `timeZone` (camel).
|
|
9
|
+
*/
|
|
10
|
+
import type { CorpusHttp } from '../client';
|
|
11
|
+
import type { BriefingAudio, BriefingSynthesize } from '../briefing/generate';
|
|
12
|
+
|
|
13
|
+
export type ConverseRole = 'user' | 'assistant';
|
|
14
|
+
export interface HistoryLine { role: ConverseRole; text: string }
|
|
15
|
+
|
|
16
|
+
export interface ConverseSide {
|
|
17
|
+
text: string;
|
|
18
|
+
audio_ref?: string;
|
|
19
|
+
audio_mime?: string;
|
|
20
|
+
/** Why there is no audio for this side, when there should have been. */
|
|
21
|
+
audio_reason?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ConverseTurn {
|
|
25
|
+
n: number;
|
|
26
|
+
/** The client's id for this press: sending it again replays the turn. */
|
|
27
|
+
turn_id: string;
|
|
28
|
+
at: string;
|
|
29
|
+
user: ConverseSide;
|
|
30
|
+
assistant: ConverseSide;
|
|
31
|
+
/** What the assistant did to the person's items this turn, in words. */
|
|
32
|
+
did?: string[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ConversationRecord {
|
|
36
|
+
/** Tenant row id. */
|
|
37
|
+
id: string;
|
|
38
|
+
/** The id the client holds. */
|
|
39
|
+
conversationId: string;
|
|
40
|
+
externalId: string;
|
|
41
|
+
status: 'open' | 'ended';
|
|
42
|
+
startedAt: string;
|
|
43
|
+
endedAt?: string;
|
|
44
|
+
timeZone?: string;
|
|
45
|
+
title: string;
|
|
46
|
+
turns: ConverseTurn[];
|
|
47
|
+
/** Set at End: the transcript as a document, and what the handoff pulled out of it. */
|
|
48
|
+
body?: string;
|
|
49
|
+
asks?: string[];
|
|
50
|
+
decisions?: string[];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ConversationStore {
|
|
54
|
+
/** One of the caller's own conversations by the client's id; null for anyone else's or none. */
|
|
55
|
+
get(conversationId: string): Promise<ConversationRecord | null>;
|
|
56
|
+
save(record: Omit<ConversationRecord, 'id'> & { id?: string }): Promise<ConversationRecord>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** What the assistant works out for one utterance. */
|
|
60
|
+
export interface ConverseBrainInput {
|
|
61
|
+
utterance: string;
|
|
62
|
+
history: HistoryLine[];
|
|
63
|
+
timeZone: string;
|
|
64
|
+
now: number;
|
|
65
|
+
}
|
|
66
|
+
export interface ConverseBrainOutput {
|
|
67
|
+
/** What is said back. Plain sentences: it is read aloud. */
|
|
68
|
+
text: string;
|
|
69
|
+
/** What it did to items, in words (kept on the turn). */
|
|
70
|
+
did?: string[];
|
|
71
|
+
}
|
|
72
|
+
export type ConverseBrain = (input: ConverseBrainInput) => Promise<ConverseBrainOutput>;
|
|
73
|
+
|
|
74
|
+
export interface ConverseTurnRequest {
|
|
75
|
+
/** Absent on the first turn. */
|
|
76
|
+
conversationId?: string;
|
|
77
|
+
text?: string;
|
|
78
|
+
audio?: { audio: Uint8Array; mimeType: string };
|
|
79
|
+
timeZone?: string;
|
|
80
|
+
/** Fresh per press; optional. */
|
|
81
|
+
turnId?: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The 200 body. */
|
|
85
|
+
export interface ConverseTurnResult {
|
|
86
|
+
conversation_id: string;
|
|
87
|
+
turn_id: string;
|
|
88
|
+
turn: number;
|
|
89
|
+
transcript: string;
|
|
90
|
+
reply_text: string;
|
|
91
|
+
/** Owner-checked, relative to the tenant; GET with the bearer. Null when only text is available. */
|
|
92
|
+
audio_url: string | null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface ConverseEndResult {
|
|
96
|
+
saved: true;
|
|
97
|
+
conversation_id: string;
|
|
98
|
+
/** The record's row id, for Library/MCP lookups. */
|
|
99
|
+
record_id: string;
|
|
100
|
+
turns: number;
|
|
101
|
+
asks: string[];
|
|
102
|
+
decisions: string[];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ConverseDeps {
|
|
106
|
+
http: Pick<CorpusHttp, 'get'> & { post<T>(path: string, body?: unknown): Promise<T> };
|
|
107
|
+
ownerSub: string;
|
|
108
|
+
brain: ConverseBrain;
|
|
109
|
+
synthesize?: BriefingSynthesize;
|
|
110
|
+
audio?: Pick<BriefingAudio, 'put'> & { get(audioRef: string): Promise<{ audio: Uint8Array; mimeType: string }> };
|
|
111
|
+
transcribe?: (input: { audio: Uint8Array; mimeType: string; hints: string[] }) => Promise<string>;
|
|
112
|
+
/** Pulls asks and decisions out of a finished conversation. Default: none. */
|
|
113
|
+
extract?: (input: { transcript: string }) => Promise<{ asks: string[]; decisions: string[] }>;
|
|
114
|
+
store?: ConversationStore;
|
|
115
|
+
now?: () => number;
|
|
116
|
+
newId?: () => string;
|
|
117
|
+
/** How many earlier lines the brain sees. Default 24. */
|
|
118
|
+
historyLines?: number;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** An error the route turns into a status; `code` lets the app choose its message. */
|
|
122
|
+
export class ConverseError extends Error {
|
|
123
|
+
constructor(message: string, readonly status: number, readonly code?: string) {
|
|
124
|
+
super(message);
|
|
125
|
+
this.name = 'ConverseError';
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export const CONVERSATION_SOURCE = 'conversation';
|
|
130
|
+
export const MAX_CONVERSE_AUDIO_BYTES = 25 * 1024 * 1024;
|
|
131
|
+
export const CLIENT_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
132
|
+
export const turnAudioPath = (conversationId: string, n: number, who: 'user' | 'reply' = 'reply') =>
|
|
133
|
+
`/corpus/converse/${encodeURIComponent(conversationId)}/turn/${n}/audio${who === 'user' ? '?who=user' : ''}`;
|
package/src/corpus/index.ts
CHANGED
|
@@ -287,6 +287,7 @@ export { dueDay, localDate, selectToday, todayKind } from './today';
|
|
|
287
287
|
export type { TodayEntry, TodayItem, TodayKind, TodayRule } from './today';
|
|
288
288
|
// Daily briefing: what is on one person's plate today (bd startsim-kgkp1).
|
|
289
289
|
export * from './briefing';
|
|
290
|
+
export * from './converse';
|
|
290
291
|
|
|
291
292
|
// Spoken time -> due dates, and the per-field guesses extraction reports (bd startsim-b7kir).
|
|
292
293
|
export { isTimeZone, noteWideWhen, resolveSpokenTime } from './spoken-time';
|
|
@@ -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, fakeConverseSound: launch.fakeConverseSound, 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, fakeConverseSound: 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,48 @@
|
|
|
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
|
+
/** The fake speaks its replies (the bundled clip). Off: text only, silent. */
|
|
28
|
+
fakeSound?: boolean;
|
|
29
|
+
}) {
|
|
30
|
+
const { config, device, session, diag, fake, fakeSound } = deps;
|
|
31
|
+
const rec = device.recording;
|
|
32
|
+
if (!rec) throw new Error('features.converse needs the recording bindings (features.recording on, device.recording supplied)');
|
|
33
|
+
const dev = device.briefing;
|
|
34
|
+
if (!dev) throw new Error('features.converse needs a playback driver (device.briefing.driver)');
|
|
35
|
+
const inspector = dev.session ?? rec.session;
|
|
36
|
+
const player = createAudioPlayer({ driver: dev.driver, session: inspector, diag, poll: tick, sleep: wait });
|
|
37
|
+
const audio = createRecorderAudio({
|
|
38
|
+
driver: rec.driver, session: rec.session, fs: { size: rec.fileSize }, poll: tick, sleep: wait, diag, onInterrupted: () => undefined,
|
|
39
|
+
});
|
|
40
|
+
const permissions = createPermissionFlow({ perms: rec.permissions, openSettings: rec.openSettings, log: diag.log });
|
|
41
|
+
const api = fake
|
|
42
|
+
? createFakeConverseApi({ ...(fakeSound && dev.fixture ? { fixture: dev.fixture } : {}) })
|
|
43
|
+
: createConverseApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer, filePart: rec.filePart });
|
|
44
|
+
const controller = createConverseController({
|
|
45
|
+
api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, newId: newTurnId, diag, allowSilence: fake,
|
|
46
|
+
});
|
|
47
|
+
return { controller, player };
|
|
48
|
+
}
|
package/src/native/app/launch.ts
CHANGED
|
@@ -13,6 +13,8 @@ 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)
|
|
17
|
+
* -tgFakeConverseSound 1 with -tgFakeConverse: speak the replies with the bundled clip (audible: opt-in only)
|
|
16
18
|
* -tgHapticProbe 1 fire one haptic per interaction through the real engine; the diagnostics log shows each call and the engine's answer
|
|
17
19
|
* -tgScheme light|dark override the config's theme mode (simulator checks of the light theme)
|
|
18
20
|
*/
|
|
@@ -29,6 +31,10 @@ export interface LaunchArgs {
|
|
|
29
31
|
fakeBriefing: boolean;
|
|
30
32
|
/** `-tgFakeReply "a|b"`: what each recorded reply is taken to say, in order. */
|
|
31
33
|
fakeReply: string[];
|
|
34
|
+
/** `-tgFakeConverse 1`: the Converse tab talks to a scripted assistant (and speaks with the bundled clip). */
|
|
35
|
+
fakeConverse: boolean;
|
|
36
|
+
/** `-tgFakeConverseSound 1`: the fake assistant's replies are spoken with the bundled clip. Off by default so simulator runs are silent. */
|
|
37
|
+
fakeConverseSound: boolean;
|
|
32
38
|
}
|
|
33
39
|
|
|
34
40
|
export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAppConfig, 'tabs'>): LaunchArgs {
|
|
@@ -50,6 +56,8 @@ export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAp
|
|
|
50
56
|
scenario: readFakeScenario((k) => str(k)),
|
|
51
57
|
target,
|
|
52
58
|
autostop: Number.isFinite(n) && n > 0 ? n : null,
|
|
59
|
+
fakeConverse: str('tgFakeConverse') === '1',
|
|
60
|
+
fakeConverseSound: str('tgFakeConverseSound') === '1',
|
|
53
61
|
hapticProbe: str('tgHapticProbe') === '1',
|
|
54
62
|
fakeBriefing: str('tgFakeBriefing') === '1',
|
|
55
63
|
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; fakeConverseSound?: 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), fakeSound: Boolean(deps.fakeConverseSound) }) : 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
|
+
}
|