@surfaces-ui/chat 0.0.0-stage → 0.3.0
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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +43 -2
- package/dist/AnalyticsChat.d.ts +82 -0
- package/dist/AnalyticsChat.js +168 -0
- package/dist/AnalyticsChat.js.map +1 -0
- package/dist/Approval.d.ts +18 -0
- package/dist/Approval.js +116 -0
- package/dist/Approval.js.map +1 -0
- package/dist/Chat.d.ts +112 -0
- package/dist/Chat.js +119 -0
- package/dist/Chat.js.map +1 -0
- package/dist/ChatComposer.d.ts +117 -0
- package/dist/ChatComposer.js +186 -0
- package/dist/ChatComposer.js.map +1 -0
- package/dist/ChatPanels.d.ts +34 -0
- package/dist/ChatPanels.js +75 -0
- package/dist/ChatPanels.js.map +1 -0
- package/dist/DataPanel.d.ts +19 -0
- package/dist/DataPanel.js +20 -0
- package/dist/DataPanel.js.map +1 -0
- package/dist/Menu.d.ts +37 -0
- package/dist/Menu.js +85 -0
- package/dist/Menu.js.map +1 -0
- package/dist/PageStudio.d.ts +103 -0
- package/dist/PageStudio.js +166 -0
- package/dist/PageStudio.js.map +1 -0
- package/dist/SessionList.d.ts +64 -0
- package/dist/SessionList.js +225 -0
- package/dist/SessionList.js.map +1 -0
- package/dist/appComponents.d.ts +6 -0
- package/dist/appComponents.js +100 -0
- package/dist/appComponents.js.map +1 -0
- package/dist/conversation.d.ts +66 -0
- package/dist/conversation.js +119 -0
- package/dist/conversation.js.map +1 -0
- package/dist/icons.d.ts +33 -0
- package/dist/icons.js +34 -0
- package/dist/icons.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/dist/selectors.d.ts +106 -0
- package/dist/selectors.js +160 -0
- package/dist/selectors.js.map +1 -0
- package/dist/sessions.d.ts +71 -0
- package/dist/sessions.js +194 -0
- package/dist/sessions.js.map +1 -0
- package/dist/speech.d.ts +43 -0
- package/dist/speech.js +89 -0
- package/dist/speech.js.map +1 -0
- package/dist/thread.d.ts +199 -0
- package/dist/thread.js +225 -0
- package/dist/thread.js.map +1 -0
- package/dist/useChat.d.ts +121 -0
- package/dist/useChat.js +293 -0
- package/dist/useChat.js.map +1 -0
- package/dist/voice.d.ts +41 -0
- package/dist/voice.js +128 -0
- package/dist/voice.js.map +1 -0
- package/package.json +72 -3
package/dist/useChat.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { approvalDigest, errorEvent } from "@surfaces-ui/agent";
|
|
2
|
+
import { upgradeMessage } from "@surfaces-ui/spec";
|
|
3
|
+
import { surfaceSnapshot } from "@surfaces-ui/spec/react";
|
|
4
|
+
import { decodeState, encodeState } from "@surfaces-ui/state";
|
|
5
|
+
import { ObjectKind } from "@surfaces-ui/proto";
|
|
6
|
+
import { newHolder, recordMessage, traceAgent } from "@surfaces-ui/trace";
|
|
7
|
+
import { useRecorder } from "@surfaces-ui/trace/react";
|
|
8
|
+
import { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from "react";
|
|
9
|
+
/** The most notes kept for one surface between turns; the oldest go first. */
|
|
10
|
+
const MAX_ACTIVITY = 40;
|
|
11
|
+
/** A reference as the contract carries it. */
|
|
12
|
+
const objectRef = (ref) => ({
|
|
13
|
+
sourceId: ref.sourceId,
|
|
14
|
+
kind: ref.kind === "file" ? ObjectKind.FILE : ref.column ? ObjectKind.COLUMN : ObjectKind.TABLE,
|
|
15
|
+
catalog: ref.catalog ?? "",
|
|
16
|
+
schema: ref.schema ?? "",
|
|
17
|
+
table: ref.table,
|
|
18
|
+
column: ref.column ?? "",
|
|
19
|
+
path: ref.path ?? "",
|
|
20
|
+
});
|
|
21
|
+
import { agentSurfaceId, emptyThread, parseThread, reduceThread } from "./thread.js";
|
|
22
|
+
/** The parts of a turn request that carry a person's choices. */
|
|
23
|
+
export function settingsRequest(settings, agentId) {
|
|
24
|
+
const chosen = settings?.skillIds !== undefined || settings?.connectorIds !== undefined;
|
|
25
|
+
return {
|
|
26
|
+
agentId: settings?.agentId || agentId || "",
|
|
27
|
+
// A model picked under a provider is the host's to hand its own backend, which is the one that knows it.
|
|
28
|
+
model: settings?.provider ? "" : (settings?.model ?? ""),
|
|
29
|
+
...(chosen ? { choicesSet: true, skillIds: settings?.skillIds ?? [], connectorIds: settings?.connectorIds ?? [] } : {}),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Runs a conversation against any AgentBackend and keeps its thread. One
|
|
34
|
+
* turn streams at a time; starting another stops the one in progress.
|
|
35
|
+
*/
|
|
36
|
+
export function useChat(given, options) {
|
|
37
|
+
const { catalog, agentId, contextPackId, user, storage, storageKey = "surfaces.chat" } = options;
|
|
38
|
+
// Dev tools: with a recorder above, each turn is one trace and each surface message is recorded. Without one, nothing here runs.
|
|
39
|
+
const recorder = useRecorder();
|
|
40
|
+
const agent = useMemo(() => (recorder ? traceAgent(given, recorder) : given), [given, recorder]);
|
|
41
|
+
const holder = useRef(undefined);
|
|
42
|
+
const [thread, send_] = useReducer((state, action) => reduceThread(state, action, catalog), options.initial ?? emptyThread);
|
|
43
|
+
const controller = useRef(undefined);
|
|
44
|
+
const sessionId = useRef("");
|
|
45
|
+
sessionId.current = thread.sessionId;
|
|
46
|
+
const settings = useRef(options.settings);
|
|
47
|
+
settings.current = options.settings;
|
|
48
|
+
const latest = useRef(thread);
|
|
49
|
+
latest.current = thread;
|
|
50
|
+
// The thread as it stands after every action so far, kept only while tracing: what the reducer made of a
|
|
51
|
+
// surface message (which surface it changed, or why it was refused) is read from it as the message arrives.
|
|
52
|
+
const shadow = useRef(undefined);
|
|
53
|
+
const dispatch = useCallback((action) => {
|
|
54
|
+
if (recorder) {
|
|
55
|
+
const before = shadow.current ?? latest.current;
|
|
56
|
+
const after = reduceThread(before, action, catalog);
|
|
57
|
+
shadow.current = after;
|
|
58
|
+
const prefix = `${(holder.current ??= newHolder("c"))}:`;
|
|
59
|
+
if (action.type === "event" && action.event.event.case === "surface") {
|
|
60
|
+
const raw = action.event.event.value;
|
|
61
|
+
const key = Object.keys(after.surfaces).find((k) => after.surfaces[k] !== before.surfaces[k]) ?? Object.keys(before.surfaces).find((k) => !(k in after.surfaces));
|
|
62
|
+
const refused = after.messages.at(-1)?.parts.at(-1);
|
|
63
|
+
const error = key === undefined && refused?.kind === "error" && refused !== before.messages.at(-1)?.parts.at(-1) ? { code: refused.code, message: refused.message } : undefined;
|
|
64
|
+
const event = recordMessage(recorder, { format: "a2ui", key: `${prefix}${key ?? ""}`, raw, message: upgradeMessage(raw), issues: catalog.validateMessage(raw), applied: key !== undefined, ...(error ? { error } : {}) });
|
|
65
|
+
if (error)
|
|
66
|
+
recorder.record({ kind: "problem", name: error.code, status: "error", surfaceId: event.surfaceId, detail: { code: error.code, path: "/", message: error.message } }, { traceId: event.traceId, spanId: event.spanId });
|
|
67
|
+
}
|
|
68
|
+
else if (action.type === "reset" || action.type === "restore")
|
|
69
|
+
recorder.record({ kind: "state", name: "reset", detail: { prefix } });
|
|
70
|
+
}
|
|
71
|
+
else
|
|
72
|
+
shadow.current = undefined;
|
|
73
|
+
send_(action);
|
|
74
|
+
}, [recorder, catalog]);
|
|
75
|
+
if (recorder)
|
|
76
|
+
for (const [key, surface] of Object.entries(thread.surfaces))
|
|
77
|
+
recorder.tag(surface, `${(holder.current ??= newHolder("c"))}:${key}`);
|
|
78
|
+
// A surface that came with the thread (a saved or written conversation) has no recorded messages: it is recorded whole.
|
|
79
|
+
useLayoutEffect(() => {
|
|
80
|
+
if (!recorder)
|
|
81
|
+
return;
|
|
82
|
+
for (const [key, surface] of Object.entries(thread.surfaces)) {
|
|
83
|
+
const traced = `${(holder.current ??= newHolder("c"))}:${key}`;
|
|
84
|
+
if (!recorder.surfaceScope(traced))
|
|
85
|
+
recordMessage(recorder, { format: "surface", key: traced, raw: surfaceSnapshot(surface), snapshot: true, name: "surface" });
|
|
86
|
+
}
|
|
87
|
+
}, [recorder, thread.surfaces]);
|
|
88
|
+
// Where each surface stands on this page, and problems not yet told to the agent.
|
|
89
|
+
const states = useRef(new Map());
|
|
90
|
+
const pending = useRef([]);
|
|
91
|
+
const toldErrors = useRef(0);
|
|
92
|
+
const [ready, setReady] = useState(!storage);
|
|
93
|
+
// Load a kept conversation once, then keep it after every change.
|
|
94
|
+
useEffect(() => {
|
|
95
|
+
if (!storage)
|
|
96
|
+
return;
|
|
97
|
+
let live = true;
|
|
98
|
+
void (async () => {
|
|
99
|
+
try {
|
|
100
|
+
const text = await storage.load(storageKey);
|
|
101
|
+
const saved = text ? decodeState(text) : undefined;
|
|
102
|
+
const restored = saved?.version === STORE_VERSION ? parseThread(saved.thread) : undefined;
|
|
103
|
+
if (live && restored && latest.current.messages.length === 0) {
|
|
104
|
+
dispatch({ type: "restore", thread: restored });
|
|
105
|
+
if (saved?.states && typeof saved.states === "object")
|
|
106
|
+
states.current = new Map(Object.entries(saved.states));
|
|
107
|
+
if (Array.isArray(saved?.pending))
|
|
108
|
+
pending.current = saved.pending;
|
|
109
|
+
if (typeof saved?.toldErrors === "number")
|
|
110
|
+
toldErrors.current = saved.toldErrors;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
// A kept conversation that cannot be read is ignored, not fatal.
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
if (live)
|
|
118
|
+
setReady(true);
|
|
119
|
+
}
|
|
120
|
+
})();
|
|
121
|
+
return () => {
|
|
122
|
+
live = false;
|
|
123
|
+
};
|
|
124
|
+
}, [storage, storageKey]);
|
|
125
|
+
const save = useCallback(() => {
|
|
126
|
+
if (!storage)
|
|
127
|
+
return;
|
|
128
|
+
const record = { version: STORE_VERSION, thread: latest.current, states: Object.fromEntries(states.current), pending: pending.current, toldErrors: toldErrors.current };
|
|
129
|
+
void storage.save(storageKey, encodeState(record));
|
|
130
|
+
}, [storage, storageKey]);
|
|
131
|
+
useEffect(() => {
|
|
132
|
+
if (!ready || !storage)
|
|
133
|
+
return;
|
|
134
|
+
const timer = setTimeout(save, thread.status === "streaming" ? 500 : 0);
|
|
135
|
+
return () => clearTimeout(timer);
|
|
136
|
+
}, [thread, ready, storage, save]);
|
|
137
|
+
const run = useCallback((input, resume = false, references = []) => {
|
|
138
|
+
controller.current?.abort();
|
|
139
|
+
const current = new AbortController();
|
|
140
|
+
controller.current = current;
|
|
141
|
+
dispatch({ type: "begin", resume });
|
|
142
|
+
void (async () => {
|
|
143
|
+
try {
|
|
144
|
+
const { surfaces, surfaceErrors } = takeState(latest.current, states.current, pending, toldErrors);
|
|
145
|
+
for await (const event of agent.send({ sessionId: sessionId.current, ...settingsRequest(settings.current, agentId), contextPackId, input, surfaces, surfaceErrors, references: references.map(objectRef) }, { signal: current.signal })) {
|
|
146
|
+
if (current.signal.aborted)
|
|
147
|
+
break;
|
|
148
|
+
dispatch({ type: "event", event });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
if (!current.signal.aborted)
|
|
153
|
+
dispatch({ type: "event", event: errorEvent(error) });
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
if (controller.current === current) {
|
|
157
|
+
controller.current = undefined;
|
|
158
|
+
dispatch({ type: "end" });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
})();
|
|
162
|
+
}, [agent, agentId, contextPackId, dispatch]);
|
|
163
|
+
useEffect(() => () => controller.current?.abort(), []);
|
|
164
|
+
const send = useCallback((text, references = []) => {
|
|
165
|
+
const trimmed = text.trim();
|
|
166
|
+
if (!trimmed)
|
|
167
|
+
return;
|
|
168
|
+
dispatch({ type: "user", text: trimmed, references });
|
|
169
|
+
run({ case: "text", value: trimmed }, false, references);
|
|
170
|
+
}, [run, dispatch]);
|
|
171
|
+
const answer = useCallback((id, reply) => {
|
|
172
|
+
const approval = latest.current.messages.flatMap((m) => m.parts).find((p) => p.kind === "approval" && p.approval.id === id);
|
|
173
|
+
const request = approval?.kind === "approval" ? approval.approval : undefined;
|
|
174
|
+
void (async () => {
|
|
175
|
+
// The digest of what the person approved: their edited version when they changed it.
|
|
176
|
+
const digest = await approvalDigest({ sql: reply.editedSql ?? request?.sql, subject: reply.editedSubject ?? request?.subject });
|
|
177
|
+
const decided = {
|
|
178
|
+
allow: reply.allow,
|
|
179
|
+
text: reply.text ?? "",
|
|
180
|
+
reason: reply.reason?.trim() ?? "",
|
|
181
|
+
at: new Date().toISOString(),
|
|
182
|
+
digest,
|
|
183
|
+
...(user ? { by: user } : {}),
|
|
184
|
+
...(reply.editedSql !== undefined ? { editedSql: reply.editedSql } : {}),
|
|
185
|
+
...(reply.editedSubject ? { editedSubject: reply.editedSubject } : {}),
|
|
186
|
+
};
|
|
187
|
+
dispatch({ type: "answered", id, answer: decided });
|
|
188
|
+
run({
|
|
189
|
+
case: "approval",
|
|
190
|
+
value: {
|
|
191
|
+
id,
|
|
192
|
+
allow: decided.allow,
|
|
193
|
+
answer: decided.text,
|
|
194
|
+
reason: decided.reason,
|
|
195
|
+
decidedAt: decided.at,
|
|
196
|
+
digest,
|
|
197
|
+
...(user ? { decidedBy: user } : {}),
|
|
198
|
+
...(decided.editedSql !== undefined ? { editedSql: decided.editedSql } : {}),
|
|
199
|
+
...(decided.editedSubject ? { editedSubject: decided.editedSubject } : {}),
|
|
200
|
+
},
|
|
201
|
+
}, true);
|
|
202
|
+
})();
|
|
203
|
+
}, [run, user, dispatch]);
|
|
204
|
+
const act = useCallback((action) => run({
|
|
205
|
+
case: "action",
|
|
206
|
+
value: {
|
|
207
|
+
name: action.name,
|
|
208
|
+
surfaceId: agentSurfaceId(action.surfaceId),
|
|
209
|
+
sourceComponentId: action.sourceComponentId,
|
|
210
|
+
timestamp: action.timestamp,
|
|
211
|
+
// Values travel as JSON; anything that is not JSON (a bigint) is sent as text.
|
|
212
|
+
context: asJson(action.context),
|
|
213
|
+
...(action.dataModel !== undefined ? { dataModel: asJson(action.dataModel) } : {}),
|
|
214
|
+
...(user ? { actor: user } : {}),
|
|
215
|
+
},
|
|
216
|
+
}), [run, user]);
|
|
217
|
+
const report = useCallback((key, state) => {
|
|
218
|
+
const entry = states.current.get(key) ?? { controls: {} };
|
|
219
|
+
if (state.data !== undefined)
|
|
220
|
+
entry.data = state.data;
|
|
221
|
+
if (state.componentId && state.controls)
|
|
222
|
+
entry.controls[state.componentId] = state.controls;
|
|
223
|
+
if (state.componentId && state.note) {
|
|
224
|
+
// What a person did, for the agent's context on its next turn. The same thing twice in a row is told once.
|
|
225
|
+
const last = entry.activity?.at(-1);
|
|
226
|
+
if (!(last && last.componentId === state.componentId && last.kind === state.note.kind && last.summary === state.note.summary)) {
|
|
227
|
+
entry.activity = [...(entry.activity ?? []), { componentId: state.componentId, kind: state.note.kind, summary: state.note.summary, ...(state.note.subject ? { subject: state.note.subject } : {}), at: new Date().toISOString() }].slice(-MAX_ACTIVITY);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
states.current.set(key, entry);
|
|
231
|
+
save();
|
|
232
|
+
}, [save]);
|
|
233
|
+
const problem = useCallback((key, p) => {
|
|
234
|
+
const message = { surfaceId: agentSurfaceId(key), code: p.code, path: p.path, message: p.message };
|
|
235
|
+
// The same problem is reported once, however often the surface is drawn.
|
|
236
|
+
if (!pending.current.some((e) => e.surfaceId === message.surfaceId && e.path === message.path && e.message === message.message))
|
|
237
|
+
pending.current.push(message);
|
|
238
|
+
save();
|
|
239
|
+
}, [save]);
|
|
240
|
+
const stop = useCallback(() => {
|
|
241
|
+
controller.current?.abort();
|
|
242
|
+
controller.current = undefined;
|
|
243
|
+
dispatch({ type: "end" });
|
|
244
|
+
}, [dispatch]);
|
|
245
|
+
const reset = useCallback(() => {
|
|
246
|
+
controller.current?.abort();
|
|
247
|
+
controller.current = undefined;
|
|
248
|
+
states.current = new Map();
|
|
249
|
+
pending.current = [];
|
|
250
|
+
toldErrors.current = 0;
|
|
251
|
+
dispatch({ type: "reset" });
|
|
252
|
+
}, [dispatch]);
|
|
253
|
+
return { thread, send, answer, act, report, problem, stop, reset, ready };
|
|
254
|
+
}
|
|
255
|
+
/** Bump when the kept shape changes; older conversations are then dropped. */
|
|
256
|
+
const STORE_VERSION = 1;
|
|
257
|
+
/** Values travel as JSON; anything that is not JSON (a bigint) is sent as text. */
|
|
258
|
+
const asJson = (value) => {
|
|
259
|
+
const plain = JSON.parse(JSON.stringify(value ?? {}, (_, v) => (typeof v === "bigint" ? String(v) : v)));
|
|
260
|
+
return plain && typeof plain === "object" && !Array.isArray(plain) ? plain : { value: plain };
|
|
261
|
+
};
|
|
262
|
+
/**
|
|
263
|
+
* What goes with every turn: each agent surface as it now stands (the
|
|
264
|
+
* latest one for each of the agent's surface IDs), and problems not yet
|
|
265
|
+
* reported, including views the chat refused to draw.
|
|
266
|
+
*/
|
|
267
|
+
function takeState(thread, states, pending, toldErrors) {
|
|
268
|
+
const latestKey = new Map();
|
|
269
|
+
for (const key of Object.keys(thread.surfaces))
|
|
270
|
+
latestKey.set(agentSurfaceId(key), key);
|
|
271
|
+
const surfaces = [...latestKey.entries()].map(([surfaceId, key]) => {
|
|
272
|
+
const surface = thread.surfaces[key];
|
|
273
|
+
const local = states.get(key);
|
|
274
|
+
return {
|
|
275
|
+
surfaceId,
|
|
276
|
+
dataModel: asJson(local?.data ?? surface.data),
|
|
277
|
+
controls: Object.fromEntries(Object.entries(local?.controls ?? {}).map(([id, c]) => [id, asJson(c)])),
|
|
278
|
+
expects: Object.entries(surface.expects ?? {}).map(([event, schema]) => ({ event, schema: asJson(schema) })),
|
|
279
|
+
activity: (local?.activity ?? []).map((a) => ({ componentId: a.componentId, kind: a.kind, summary: a.summary, at: a.at, ...(a.subject ? { subject: asJson(a.subject) } : {}) })),
|
|
280
|
+
};
|
|
281
|
+
});
|
|
282
|
+
// Told once: what was done before this turn is not repeated on the next.
|
|
283
|
+
for (const local of states.values())
|
|
284
|
+
if (local.activity?.length)
|
|
285
|
+
local.activity = [];
|
|
286
|
+
const refused = thread.messages.flatMap((m) => m.parts.flatMap((p) => (p.kind === "error" && p.code === "INVALID_SURFACE" ? [p.message] : [])));
|
|
287
|
+
const fresh = refused.slice(toldErrors.current).map((message) => ({ surfaceId: "", code: "INVALID_MESSAGE", path: "/", message }));
|
|
288
|
+
toldErrors.current = refused.length;
|
|
289
|
+
const surfaceErrors = [...pending.current, ...fresh];
|
|
290
|
+
pending.current = [];
|
|
291
|
+
return { surfaces, surfaceErrors };
|
|
292
|
+
}
|
|
293
|
+
//# sourceMappingURL=useChat.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useChat.js","sourceRoot":"","sources":["../src/useChat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoC,cAAc,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAElG,OAAO,EAAoC,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACrF,OAAO,EAAyC,eAAe,EAAE,MAAM,yBAAyB,CAAC;AACjG,OAAO,EAAqB,WAAW,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjF,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAkBvG,8EAA8E;AAC9E,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB,8CAA8C;AAC9C,MAAM,SAAS,GAAG,CAAC,GAAY,EAAE,EAAE,CAAC,CAAC;IACnC,QAAQ,EAAE,GAAG,CAAC,QAAQ;IACtB,IAAI,EAAE,GAAG,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,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C,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,IAAI,CAAC,CAAC,IAAI,KAAK,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAChJ,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;IACnI,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IACpC,MAAM,aAAa,GAAG,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,GAAG,KAAK,CAAC,CAAC;IACrD,OAAO,CAAC,OAAO,GAAG,EAAE,CAAC;IACrB,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;AACrC,CAAC","sourcesContent":["import { type AgentBackend, type SendInit, approvalDigest, errorEvent } from \"@surfaces-ui/agent\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\nimport { type Catalog, type SurfaceAction, upgradeMessage } from \"@surfaces-ui/spec\";\nimport { type SurfaceNote, type SurfaceProblem, surfaceSnapshot } from \"@surfaces-ui/spec/react\";\nimport { type StateStorage, decodeState, encodeState } from \"@surfaces-ui/state\";\nimport type { DataRef } from \"@surfaces-ui/components\";\nimport { ObjectKind } from \"@surfaces-ui/proto\";\nimport { newHolder, recordMessage, traceAgent } from \"@surfaces-ui/trace\";\nimport { useRecorder } from \"@surfaces-ui/trace/react\";\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from \"react\";\n\n/** One thing a person did in a surface, kept until the agent's next turn. */\nexport interface ChatActivity {\n componentId: string;\n kind: string;\n summary: string;\n subject?: Record<string, unknown>;\n at: string;\n}\n\n/** Where a surface stands on this page, and what a person has done in it that the agent has not been told. */\ninterface SurfaceLocal {\n data?: unknown;\n controls: Record<string, Record<string, unknown>>;\n activity?: ChatActivity[];\n}\n\n/** The most notes kept for one surface between turns; the oldest go first. */\nconst MAX_ACTIVITY = 40;\n\n/** A reference as the contract carries it. */\nconst objectRef = (ref: DataRef) => ({\n sourceId: ref.sourceId,\n kind: ref.kind === \"file\" ? ObjectKind.FILE : ref.column ? ObjectKind.COLUMN : ObjectKind.TABLE,\n catalog: ref.catalog ?? \"\",\n schema: ref.schema ?? \"\",\n table: ref.table,\n column: ref.column ?? \"\",\n path: ref.path ?? \"\",\n});\nimport { type ChatAction, type ChatActor, type ChatApprovalAnswer, type ChatThread, agentSurfaceId, emptyThread, parseThread, reduceThread } from \"./thread.js\";\n\nexport interface UseChatOptions {\n /** The catalog agent-drawn components are checked against. */\n catalog: Catalog;\n /** Which agent to talk to, when the backend has several. */\n agentId?: string;\n /** Limit the agent to the data in this saved context pack. */\n contextPackId?: string;\n /**\n * Who is using the chat, from the host's own sign-in. Recorded on every\n * approval answer (`decided_by`). A backend must still check it against\n * its own session.\n */\n user?: ChatActor;\n /**\n * Where to keep the conversation so it survives a reload: the thread,\n * where each surface stands, and approvals still waiting. Use\n * `browserStorage()` from `@surfaces-ui/state` for this browser, or your own\n * `StateStorage` over a server so another person can pick up a waiting\n * approval. Nothing is kept without it.\n */\n storage?: StateStorage;\n /** The key the conversation is kept under. Defaults to \"surfaces.chat\". */\n storageKey?: string;\n /**\n * The thread to open with: a saved conversation (`conversationThread`) or a\n * written one (`scriptThread`). Read once; a kept conversation in `storage`\n * does not replace it.\n */\n initial?: ChatThread;\n /**\n * What the person chose for this conversation: the agent, the model, and\n * the skills and connectors that are on. Sent with every turn; the backend\n * refuses anything it does not offer. Leave it out to use the agent's defaults.\n */\n settings?: ChatSettings;\n}\n\n/** A person's choices for a conversation, as plain JSON a host or a saved conversation can hold. */\nexport interface ChatSettings {\n agentId?: string;\n /** Empty or left out: the agent's default. */\n model?: string;\n /**\n * Where the model runs, when the host offers several (`ChatProvider`): the\n * host turns it into its own backend. Neither it nor the model picked under\n * it is sent with a turn: the host passes the model to that backend.\n */\n provider?: string;\n /** Given: exactly these are on. Left out: each one's default. */\n skillIds?: string[];\n connectorIds?: string[];\n /** The data connection the person browses and attaches from. Not sent: what the agent sees is what they attach. */\n sourceId?: string;\n}\n\n/** The parts of a turn request that carry a person's choices. */\nexport function settingsRequest(settings: ChatSettings | undefined, agentId?: string) {\n const chosen = settings?.skillIds !== undefined || settings?.connectorIds !== undefined;\n return {\n agentId: settings?.agentId || agentId || \"\",\n // A model picked under a provider is the host's to hand its own backend, which is the one that knows it.\n model: settings?.provider ? \"\" : (settings?.model ?? \"\"),\n ...(chosen ? { choicesSet: true, skillIds: settings?.skillIds ?? [], connectorIds: settings?.connectorIds ?? [] } : {}),\n };\n}\n\n/** A person's answer to an approval. */\nexport interface ApprovalReply {\n allow: boolean;\n /** The chosen option or typed answer. */\n text?: string;\n /** Why, in their words. */\n reason?: string;\n /** Their version of the SQL, when the request was editable. */\n editedSql?: string;\n /** Their version of the subject, when the request was editable. */\n editedSubject?: JsonObject;\n}\n\nexport interface UseChat {\n thread: ChatThread;\n /** Sends what the person typed, with any tables and columns they attached. */\n send(text: string, references?: DataRef[]): void;\n /** Answers an approval the agent is waiting on, recording who, when and why, and the digest of what was approved. */\n answer(id: string, reply: ApprovalReply): void;\n /** Sends an event from a control on an agent-drawn component. */\n act(action: SurfaceAction): void;\n /**\n * Records where an agent-drawn surface stands: its data model after a\n * person typed, or one component's controls. Nothing is sent now; every\n * later turn carries it (`SendRequest.surfaces`).\n */\n report(surfaceKey: string, state: { data?: unknown; componentId?: string; controls?: Record<string, unknown>; note?: SurfaceNote }): void;\n /** Records a problem with an agent-drawn surface, to tell the agent on the next turn (`SendRequest.surface_errors`). */\n problem(surfaceKey: string, problem: SurfaceProblem): void;\n /** Stops the reply in progress. */\n stop(): void;\n /** Starts a new conversation, forgetting the kept one too. */\n reset(): void;\n /** False until a kept conversation has been loaded (always true without `storage`). */\n ready: boolean;\n}\n\n/**\n * Runs a conversation against any AgentBackend and keeps its thread. One\n * turn streams at a time; starting another stops the one in progress.\n */\nexport function useChat(given: AgentBackend, options: UseChatOptions): UseChat {\n const { catalog, agentId, contextPackId, user, storage, storageKey = \"surfaces.chat\" } = options;\n // Dev tools: with a recorder above, each turn is one trace and each surface message is recorded. Without one, nothing here runs.\n const recorder = useRecorder();\n const agent = useMemo(() => (recorder ? traceAgent(given, recorder) : given), [given, recorder]);\n const holder = useRef<string | undefined>(undefined);\n const [thread, send_] = useReducer((state: ChatThread, action: ChatAction) => reduceThread(state, action, catalog), options.initial ?? emptyThread);\n const controller = useRef<AbortController | undefined>(undefined);\n const sessionId = useRef(\"\");\n sessionId.current = thread.sessionId;\n const settings = useRef(options.settings);\n settings.current = options.settings;\n const latest = useRef(thread);\n latest.current = thread;\n // The thread as it stands after every action so far, kept only while tracing: what the reducer made of a\n // surface message (which surface it changed, or why it was refused) is read from it as the message arrives.\n const shadow = useRef<ChatThread | undefined>(undefined);\n const dispatch = useCallback(\n (action: ChatAction) => {\n if (recorder) {\n const before = shadow.current ?? latest.current;\n const after = reduceThread(before, action, catalog);\n shadow.current = after;\n const prefix = `${(holder.current ??= newHolder(\"c\"))}:`;\n if (action.type === \"event\" && action.event.event.case === \"surface\") {\n const raw = action.event.event.value;\n const key = Object.keys(after.surfaces).find((k) => after.surfaces[k] !== before.surfaces[k]) ?? Object.keys(before.surfaces).find((k) => !(k in after.surfaces));\n const refused = after.messages.at(-1)?.parts.at(-1);\n const error = key === undefined && refused?.kind === \"error\" && refused !== before.messages.at(-1)?.parts.at(-1) ? { code: refused.code, message: refused.message } : undefined;\n const event = recordMessage(recorder, { format: \"a2ui\", key: `${prefix}${key ?? \"\"}`, raw, message: upgradeMessage(raw), issues: catalog.validateMessage(raw), applied: key !== undefined, ...(error ? { error } : {}) });\n if (error) recorder.record({ kind: \"problem\", name: error.code, status: \"error\", surfaceId: event.surfaceId, detail: { code: error.code, path: \"/\", message: error.message } }, { traceId: event.traceId, spanId: event.spanId });\n } else if (action.type === \"reset\" || action.type === \"restore\") recorder.record({ kind: \"state\", name: \"reset\", detail: { prefix } });\n } else shadow.current = undefined;\n send_(action);\n },\n [recorder, catalog],\n );\n if (recorder) for (const [key, surface] of Object.entries(thread.surfaces)) recorder.tag(surface, `${(holder.current ??= newHolder(\"c\"))}:${key}`);\n // A surface that came with the thread (a saved or written conversation) has no recorded messages: it is recorded whole.\n useLayoutEffect(() => {\n if (!recorder) return;\n for (const [key, surface] of Object.entries(thread.surfaces)) {\n const traced = `${(holder.current ??= newHolder(\"c\"))}:${key}`;\n if (!recorder.surfaceScope(traced)) recordMessage(recorder, { format: \"surface\", key: traced, raw: surfaceSnapshot(surface), snapshot: true, name: \"surface\" });\n }\n }, [recorder, thread.surfaces]);\n // Where each surface stands on this page, and problems not yet told to the agent.\n const states = useRef(new Map<string, SurfaceLocal>());\n const pending = useRef<{ surfaceId: string; code: string; path: string; message: string }[]>([]);\n const toldErrors = useRef(0);\n const [ready, setReady] = useState(!storage);\n\n // Load a kept conversation once, then keep it after every change.\n useEffect(() => {\n if (!storage) return;\n let live = true;\n void (async () => {\n try {\n const text = await storage.load(storageKey);\n const saved = text ? (decodeState(text) as { version?: number; thread?: unknown; states?: unknown; pending?: unknown; toldErrors?: unknown }) : undefined;\n const restored = saved?.version === STORE_VERSION ? parseThread(saved.thread) : undefined;\n if (live && restored && latest.current.messages.length === 0) {\n dispatch({ type: \"restore\", thread: restored });\n if (saved?.states && typeof saved.states === \"object\") states.current = new Map(Object.entries(saved.states as Record<string, SurfaceLocal>));\n if (Array.isArray(saved?.pending)) pending.current = saved.pending as typeof pending.current;\n if (typeof saved?.toldErrors === \"number\") toldErrors.current = saved.toldErrors;\n }\n } catch {\n // A kept conversation that cannot be read is ignored, not fatal.\n } finally {\n if (live) setReady(true);\n }\n })();\n return () => {\n live = false;\n };\n }, [storage, storageKey]);\n const save = useCallback(() => {\n if (!storage) return;\n const record = { version: STORE_VERSION, thread: latest.current, states: Object.fromEntries(states.current), pending: pending.current, toldErrors: toldErrors.current };\n void storage.save(storageKey, encodeState(record));\n }, [storage, storageKey]);\n useEffect(() => {\n if (!ready || !storage) return;\n const timer = setTimeout(save, thread.status === \"streaming\" ? 500 : 0);\n return () => clearTimeout(timer);\n }, [thread, ready, storage, save]);\n\n const run = useCallback(\n (input: NonNullable<SendInit[\"input\"]>, resume = false, references: DataRef[] = []) => {\n controller.current?.abort();\n const current = new AbortController();\n controller.current = current;\n dispatch({ type: \"begin\", resume });\n void (async () => {\n try {\n const { surfaces, surfaceErrors } = takeState(latest.current, states.current, pending, toldErrors);\n for await (const event of agent.send({ sessionId: sessionId.current, ...settingsRequest(settings.current, agentId), contextPackId, input, surfaces, surfaceErrors, references: references.map(objectRef) }, { signal: current.signal })) {\n if (current.signal.aborted) break;\n dispatch({ type: \"event\", event });\n }\n } catch (error) {\n if (!current.signal.aborted) dispatch({ type: \"event\", event: errorEvent(error) });\n } finally {\n if (controller.current === current) {\n controller.current = undefined;\n dispatch({ type: \"end\" });\n }\n }\n })();\n },\n [agent, agentId, contextPackId, dispatch],\n );\n\n useEffect(() => () => controller.current?.abort(), []);\n\n const send = useCallback(\n (text: string, references: DataRef[] = []) => {\n const trimmed = text.trim();\n if (!trimmed) return;\n dispatch({ type: \"user\", text: trimmed, references });\n run({ case: \"text\", value: trimmed }, false, references);\n },\n [run, dispatch],\n );\n const answer = useCallback(\n (id: string, reply: ApprovalReply) => {\n const approval = latest.current.messages.flatMap((m) => m.parts).find((p) => p.kind === \"approval\" && p.approval.id === id);\n const request = approval?.kind === \"approval\" ? approval.approval : undefined;\n void (async () => {\n // The digest of what the person approved: their edited version when they changed it.\n const digest = await approvalDigest({ sql: reply.editedSql ?? request?.sql, subject: reply.editedSubject ?? request?.subject });\n const decided: ChatApprovalAnswer = {\n allow: reply.allow,\n text: reply.text ?? \"\",\n reason: reply.reason?.trim() ?? \"\",\n at: new Date().toISOString(),\n digest,\n ...(user ? { by: user } : {}),\n ...(reply.editedSql !== undefined ? { editedSql: reply.editedSql } : {}),\n ...(reply.editedSubject ? { editedSubject: reply.editedSubject } : {}),\n };\n dispatch({ type: \"answered\", id, answer: decided });\n run(\n {\n case: \"approval\",\n value: {\n id,\n allow: decided.allow,\n answer: decided.text,\n reason: decided.reason,\n decidedAt: decided.at,\n digest,\n ...(user ? { decidedBy: user } : {}),\n ...(decided.editedSql !== undefined ? { editedSql: decided.editedSql } : {}),\n ...(decided.editedSubject ? { editedSubject: decided.editedSubject } : {}),\n },\n },\n true,\n );\n })();\n },\n [run, user, dispatch],\n );\n const act = useCallback(\n (action: SurfaceAction) =>\n run({\n case: \"action\",\n value: {\n name: action.name,\n surfaceId: agentSurfaceId(action.surfaceId),\n sourceComponentId: action.sourceComponentId,\n timestamp: action.timestamp,\n // Values travel as JSON; anything that is not JSON (a bigint) is sent as text.\n context: asJson(action.context),\n ...(action.dataModel !== undefined ? { dataModel: asJson(action.dataModel) } : {}),\n ...(user ? { actor: user } : {}),\n },\n }),\n [run, user],\n );\n const report = useCallback<UseChat[\"report\"]>((key, state) => {\n const entry = states.current.get(key) ?? { controls: {} };\n if (state.data !== undefined) entry.data = state.data;\n if (state.componentId && state.controls) entry.controls[state.componentId] = state.controls;\n if (state.componentId && state.note) {\n // What a person did, for the agent's context on its next turn. The same thing twice in a row is told once.\n const last = entry.activity?.at(-1);\n if (!(last && last.componentId === state.componentId && last.kind === state.note.kind && last.summary === state.note.summary)) {\n entry.activity = [...(entry.activity ?? []), { componentId: state.componentId, kind: state.note.kind, summary: state.note.summary, ...(state.note.subject ? { subject: state.note.subject } : {}), at: new Date().toISOString() }].slice(-MAX_ACTIVITY);\n }\n }\n states.current.set(key, entry);\n save();\n }, [save]);\n const problem = useCallback<UseChat[\"problem\"]>((key, p) => {\n const message = { surfaceId: agentSurfaceId(key), code: p.code, path: p.path, message: p.message };\n // The same problem is reported once, however often the surface is drawn.\n if (!pending.current.some((e) => e.surfaceId === message.surfaceId && e.path === message.path && e.message === message.message)) pending.current.push(message);\n save();\n }, [save]);\n const stop = useCallback(() => {\n controller.current?.abort();\n controller.current = undefined;\n dispatch({ type: \"end\" });\n }, [dispatch]);\n const reset = useCallback(() => {\n controller.current?.abort();\n controller.current = undefined;\n states.current = new Map();\n pending.current = [];\n toldErrors.current = 0;\n dispatch({ type: \"reset\" });\n }, [dispatch]);\n\n return { thread, send, answer, act, report, problem, stop, reset, ready };\n}\n\n/** Bump when the kept shape changes; older conversations are then dropped. */\nconst STORE_VERSION = 1;\n\n/** Values travel as JSON; anything that is not JSON (a bigint) is sent as text. */\nconst asJson = (value: unknown): JsonObject => {\n const plain = JSON.parse(JSON.stringify(value ?? {}, (_, v) => (typeof v === \"bigint\" ? String(v) : v))) as unknown;\n return plain && typeof plain === \"object\" && !Array.isArray(plain) ? (plain as JsonObject) : { value: plain as JsonObject[string] };\n};\n\n/**\n * What goes with every turn: each agent surface as it now stands (the\n * latest one for each of the agent's surface IDs), and problems not yet\n * reported, including views the chat refused to draw.\n */\nfunction takeState(\n thread: ChatThread,\n states: Map<string, SurfaceLocal>,\n pending: { current: { surfaceId: string; code: string; path: string; message: string }[] },\n toldErrors: { current: number },\n): Pick<SendInit, \"surfaces\" | \"surfaceErrors\"> {\n const latestKey = new Map<string, string>();\n for (const key of Object.keys(thread.surfaces)) latestKey.set(agentSurfaceId(key), key);\n const surfaces = [...latestKey.entries()].map(([surfaceId, key]) => {\n const surface = thread.surfaces[key]!;\n const local = states.get(key);\n return {\n surfaceId,\n dataModel: asJson(local?.data ?? surface.data),\n controls: Object.fromEntries(Object.entries(local?.controls ?? {}).map(([id, c]) => [id, asJson(c)])),\n expects: Object.entries(surface.expects ?? {}).map(([event, schema]) => ({ event, schema: asJson(schema) })),\n activity: (local?.activity ?? []).map((a) => ({ componentId: a.componentId, kind: a.kind, summary: a.summary, at: a.at, ...(a.subject ? { subject: asJson(a.subject) } : {}) })),\n };\n });\n // Told once: what was done before this turn is not repeated on the next.\n for (const local of states.values()) if (local.activity?.length) local.activity = [];\n const refused = thread.messages.flatMap((m) => m.parts.flatMap((p) => (p.kind === \"error\" && p.code === \"INVALID_SURFACE\" ? [p.message] : [])));\n const fresh = refused.slice(toldErrors.current).map((message) => ({ surfaceId: \"\", code: \"INVALID_MESSAGE\", path: \"/\", message }));\n toldErrors.current = refused.length;\n const surfaceErrors = [...pending.current, ...fresh];\n pending.current = [];\n return { surfaces, surfaceErrors };\n}\n"]}
|
package/dist/voice.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type SpeechAdapter } from "./speech.js";
|
|
2
|
+
/** Where the voice controls stand. */
|
|
3
|
+
export type VoiceState = "off" | "dictating" | "listening" | "thinking" | "speaking";
|
|
4
|
+
/** The latest reply, as the voice loop needs it. */
|
|
5
|
+
export interface VoiceReply {
|
|
6
|
+
id: string;
|
|
7
|
+
text: string;
|
|
8
|
+
/** "waiting": the reply asks a person to decide something, which needs their hands. */
|
|
9
|
+
status: "streaming" | "idle" | "waiting";
|
|
10
|
+
}
|
|
11
|
+
export interface UseVoiceOptions {
|
|
12
|
+
speech?: SpeechAdapter;
|
|
13
|
+
/** Words heard so far, to show in the message box. */
|
|
14
|
+
onText(text: string): void;
|
|
15
|
+
/** A finished turn in a conversation, to send. */
|
|
16
|
+
onSend(text: string): void;
|
|
17
|
+
reply?: VoiceReply;
|
|
18
|
+
/** Quiet after speech, in ms, before a conversation sends what was said. Default 1200. */
|
|
19
|
+
silenceMs?: number;
|
|
20
|
+
/** Quiet with nothing said, in ms, before a conversation stops listening. Default 30000. */
|
|
21
|
+
idleMs?: number;
|
|
22
|
+
}
|
|
23
|
+
export interface Voice {
|
|
24
|
+
state: VoiceState;
|
|
25
|
+
/** Says what is happening, for the status line. */
|
|
26
|
+
status: string;
|
|
27
|
+
supported: boolean;
|
|
28
|
+
/** One phrase into the message box. */
|
|
29
|
+
dictate(): void;
|
|
30
|
+
/** Talk back and forth: listen, send after a pause, read the reply, listen again. */
|
|
31
|
+
converse(): void;
|
|
32
|
+
stop(reason?: string): void;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Dictation and hands-free conversation over a `SpeechAdapter`. A
|
|
36
|
+
* conversation sends what was said once the person pauses, reads the reply's
|
|
37
|
+
* words aloud when it is done, and listens again. It stops when the reply
|
|
38
|
+
* needs a decision (an approval needs the person's hands), on `stop`, or
|
|
39
|
+
* after a long silence.
|
|
40
|
+
*/
|
|
41
|
+
export declare function useVoice(options: UseVoiceOptions): Voice;
|
package/dist/voice.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
import { speakableText } from "./speech.js";
|
|
3
|
+
/**
|
|
4
|
+
* Dictation and hands-free conversation over a `SpeechAdapter`. A
|
|
5
|
+
* conversation sends what was said once the person pauses, reads the reply's
|
|
6
|
+
* words aloud when it is done, and listens again. It stops when the reply
|
|
7
|
+
* needs a decision (an approval needs the person's hands), on `stop`, or
|
|
8
|
+
* after a long silence.
|
|
9
|
+
*/
|
|
10
|
+
export function useVoice(options) {
|
|
11
|
+
const { speech, silenceMs = 1200, idleMs = 30_000 } = options;
|
|
12
|
+
const [state, setState] = useState("off");
|
|
13
|
+
const [note, setNote] = useState("");
|
|
14
|
+
const live = useRef(options);
|
|
15
|
+
live.current = options;
|
|
16
|
+
const stopListening = useRef(undefined);
|
|
17
|
+
const heard = useRef("");
|
|
18
|
+
const timers = useRef({});
|
|
19
|
+
const mode = useRef("off");
|
|
20
|
+
const awaiting = useRef(undefined);
|
|
21
|
+
const supported = !!speech?.supported();
|
|
22
|
+
const set = (next, message = "") => {
|
|
23
|
+
mode.current = next;
|
|
24
|
+
setState(next);
|
|
25
|
+
setNote(message);
|
|
26
|
+
};
|
|
27
|
+
const clearTimers = () => {
|
|
28
|
+
clearTimeout(timers.current.silence);
|
|
29
|
+
clearTimeout(timers.current.idle);
|
|
30
|
+
};
|
|
31
|
+
const stop = useCallback((reason = "") => {
|
|
32
|
+
clearTimers();
|
|
33
|
+
stopListening.current?.();
|
|
34
|
+
stopListening.current = undefined;
|
|
35
|
+
speech?.cancelSpeech?.();
|
|
36
|
+
awaiting.current = undefined;
|
|
37
|
+
set("off", reason);
|
|
38
|
+
}, [speech]);
|
|
39
|
+
const listen = useCallback((continuous) => {
|
|
40
|
+
if (!speech)
|
|
41
|
+
return;
|
|
42
|
+
heard.current = "";
|
|
43
|
+
set(continuous ? "listening" : "dictating");
|
|
44
|
+
const armIdle = () => {
|
|
45
|
+
clearTimeout(timers.current.idle);
|
|
46
|
+
if (continuous)
|
|
47
|
+
timers.current.idle = setTimeout(() => stop("Stopped listening after a long silence."), idleMs);
|
|
48
|
+
};
|
|
49
|
+
armIdle();
|
|
50
|
+
stopListening.current = speech.listen({
|
|
51
|
+
continuous,
|
|
52
|
+
onPartial(text) {
|
|
53
|
+
live.current.onText([heard.current, text].filter(Boolean).join(" "));
|
|
54
|
+
if (continuous && text)
|
|
55
|
+
clearTimeout(timers.current.silence);
|
|
56
|
+
},
|
|
57
|
+
onFinal(text) {
|
|
58
|
+
if (!text)
|
|
59
|
+
return;
|
|
60
|
+
heard.current = [heard.current, text].filter(Boolean).join(" ");
|
|
61
|
+
live.current.onText(heard.current);
|
|
62
|
+
armIdle();
|
|
63
|
+
if (!continuous)
|
|
64
|
+
return;
|
|
65
|
+
clearTimeout(timers.current.silence);
|
|
66
|
+
timers.current.silence = setTimeout(() => {
|
|
67
|
+
const said = heard.current.trim();
|
|
68
|
+
if (!said || mode.current !== "listening")
|
|
69
|
+
return;
|
|
70
|
+
stopListening.current?.();
|
|
71
|
+
stopListening.current = undefined;
|
|
72
|
+
clearTimeout(timers.current.idle);
|
|
73
|
+
heard.current = "";
|
|
74
|
+
// The next reply after this one is the answer to read aloud.
|
|
75
|
+
awaiting.current = live.current.reply?.id ?? "";
|
|
76
|
+
set("thinking");
|
|
77
|
+
live.current.onSend(said);
|
|
78
|
+
}, silenceMs);
|
|
79
|
+
},
|
|
80
|
+
onEnd() {
|
|
81
|
+
if (mode.current === "dictating")
|
|
82
|
+
set("off");
|
|
83
|
+
// A browser ends recognition on its own after a while; a conversation keeps going.
|
|
84
|
+
else if (mode.current === "listening" && stopListening.current) {
|
|
85
|
+
stopListening.current = undefined;
|
|
86
|
+
listen(true);
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
onError(message) {
|
|
90
|
+
stop(message);
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
}, [speech, silenceMs, idleMs, stop]);
|
|
94
|
+
// A conversation waits for the reply to its turn, reads it, then listens again.
|
|
95
|
+
const { reply } = options;
|
|
96
|
+
useEffect(() => {
|
|
97
|
+
if (mode.current !== "thinking" || !reply || awaiting.current === undefined)
|
|
98
|
+
return;
|
|
99
|
+
if (reply.id === awaiting.current || reply.status === "streaming")
|
|
100
|
+
return;
|
|
101
|
+
awaiting.current = undefined;
|
|
102
|
+
if (reply.status === "waiting") {
|
|
103
|
+
stop("Paused: the reply needs your decision.");
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const words = speakableText(reply.text);
|
|
107
|
+
if (!speech?.speak || !words) {
|
|
108
|
+
listen(true);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
set("speaking");
|
|
112
|
+
void speech.speak(words).then(() => {
|
|
113
|
+
if (mode.current === "speaking")
|
|
114
|
+
listen(true);
|
|
115
|
+
});
|
|
116
|
+
}, [reply, speech, listen, stop]);
|
|
117
|
+
useEffect(() => () => stop(), [stop]);
|
|
118
|
+
const STATUS = { off: note, dictating: "Listening… speak, then pause.", listening: "Listening. Pause when you are done.", thinking: "Sent. Waiting for the reply…", speaking: "Reading the reply aloud." };
|
|
119
|
+
return {
|
|
120
|
+
state,
|
|
121
|
+
status: STATUS[state],
|
|
122
|
+
supported,
|
|
123
|
+
dictate: () => (mode.current === "off" ? listen(false) : stop()),
|
|
124
|
+
converse: () => (mode.current === "off" ? listen(true) : stop()),
|
|
125
|
+
stop,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=voice.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"voice.js","sourceRoot":"","sources":["../src/voice.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EAAsB,aAAa,EAAE,MAAM,aAAa,CAAC;AAsChE;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAAC,OAAwB;IAC/C,MAAM,EAAE,MAAM,EAAE,SAAS,GAAG,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC;IAC9D,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,QAAQ,CAAa,KAAK,CAAC,CAAC;IACtD,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC;IACrC,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACvB,MAAM,aAAa,GAAG,MAAM,CAA2B,SAAS,CAAC,CAAC;IAClE,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;IACzB,MAAM,MAAM,GAAG,MAAM,CAAoF,EAAE,CAAC,CAAC;IAC7G,MAAM,IAAI,GAAG,MAAM,CAAa,KAAK,CAAC,CAAC;IACvC,MAAM,QAAQ,GAAG,MAAM,CAAqB,SAAS,CAAC,CAAC;IACvD,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC;IAExC,MAAM,GAAG,GAAG,CAAC,IAAgB,EAAE,OAAO,GAAG,EAAE,EAAE,EAAE;QAC7C,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,QAAQ,CAA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AC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE;YACjC,IAAI,IAAI,CAAC,OAAO,KAAK,UAAU;gBAAE,MAAM,CAAC,IAAI,CAAC,CAAC;QAChD,CAAC,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;IAElC,SAAS,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;IAEtC,MAAM,MAAM,GAA+B,EAAE,GAAG,EAAE,IAAI,EAAE,SAAS,EAAE,+BAA+B,EAAE,SAAS,EAAE,qCAAqC,EAAE,QAAQ,EAAE,8BAA8B,EAAE,QAAQ,EAAE,0BAA0B,EAAE,CAAC;IACvO,OAAO;QACL,KAAK;QACL,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC;QACrB,SAAS;QACT,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAChE,QAAQ,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAChE,IAAI;KACL,CAAC;AACJ,CAAC","sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { type SpeechAdapter, speakableText } from \"./speech.js\";\n\n/** Where the voice controls stand. */\nexport type VoiceState = \"off\" | \"dictating\" | \"listening\" | \"thinking\" | \"speaking\";\n\n/** The latest reply, as the voice loop needs it. */\nexport interface VoiceReply {\n id: string;\n text: string;\n /** \"waiting\": the reply asks a person to decide something, which needs their hands. */\n status: \"streaming\" | \"idle\" | \"waiting\";\n}\n\nexport interface UseVoiceOptions {\n speech?: SpeechAdapter;\n /** Words heard so far, to show in the message box. */\n onText(text: string): void;\n /** A finished turn in a conversation, to send. */\n onSend(text: string): void;\n reply?: VoiceReply;\n /** Quiet after speech, in ms, before a conversation sends what was said. Default 1200. */\n silenceMs?: number;\n /** Quiet with nothing said, in ms, before a conversation stops listening. Default 30000. */\n idleMs?: number;\n}\n\nexport interface Voice {\n state: VoiceState;\n /** Says what is happening, for the status line. */\n status: string;\n supported: boolean;\n /** One phrase into the message box. */\n dictate(): void;\n /** Talk back and forth: listen, send after a pause, read the reply, listen again. */\n converse(): void;\n stop(reason?: string): void;\n}\n\n/**\n * Dictation and hands-free conversation over a `SpeechAdapter`. A\n * conversation sends what was said once the person pauses, reads the reply's\n * words aloud when it is done, and listens again. It stops when the reply\n * needs a decision (an approval needs the person's hands), on `stop`, or\n * after a long silence.\n */\nexport function useVoice(options: UseVoiceOptions): Voice {\n const { speech, silenceMs = 1200, idleMs = 30_000 } = options;\n const [state, setState] = useState<VoiceState>(\"off\");\n const [note, setNote] = useState(\"\");\n const live = useRef(options);\n live.current = options;\n const stopListening = useRef<(() => void) | undefined>(undefined);\n const heard = useRef(\"\");\n const timers = useRef<{ silence?: ReturnType<typeof setTimeout>; idle?: ReturnType<typeof setTimeout> }>({});\n const mode = useRef<VoiceState>(\"off\");\n const awaiting = useRef<string | undefined>(undefined);\n const supported = !!speech?.supported();\n\n const set = (next: VoiceState, message = \"\") => {\n mode.current = next;\n setState(next);\n setNote(message);\n };\n const clearTimers = () => {\n clearTimeout(timers.current.silence);\n clearTimeout(timers.current.idle);\n };\n\n const stop = useCallback(\n (reason = \"\") => {\n clearTimers();\n stopListening.current?.();\n stopListening.current = undefined;\n speech?.cancelSpeech?.();\n awaiting.current = undefined;\n set(\"off\", reason);\n },\n [speech],\n );\n\n const listen = useCallback(\n (continuous: boolean) => {\n if (!speech) return;\n heard.current = \"\";\n set(continuous ? \"listening\" : \"dictating\");\n const armIdle = () => {\n clearTimeout(timers.current.idle);\n if (continuous) timers.current.idle = setTimeout(() => stop(\"Stopped listening after a long silence.\"), idleMs);\n };\n armIdle();\n stopListening.current = speech.listen({\n continuous,\n onPartial(text) {\n live.current.onText([heard.current, text].filter(Boolean).join(\" \"));\n if (continuous && text) clearTimeout(timers.current.silence);\n },\n onFinal(text) {\n if (!text) return;\n heard.current = [heard.current, text].filter(Boolean).join(\" \");\n live.current.onText(heard.current);\n armIdle();\n if (!continuous) return;\n clearTimeout(timers.current.silence);\n timers.current.silence = setTimeout(() => {\n const said = heard.current.trim();\n if (!said || mode.current !== \"listening\") return;\n stopListening.current?.();\n stopListening.current = undefined;\n clearTimeout(timers.current.idle);\n heard.current = \"\";\n // The next reply after this one is the answer to read aloud.\n awaiting.current = live.current.reply?.id ?? \"\";\n set(\"thinking\");\n live.current.onSend(said);\n }, silenceMs);\n },\n onEnd() {\n if (mode.current === \"dictating\") set(\"off\");\n // A browser ends recognition on its own after a while; a conversation keeps going.\n else if (mode.current === \"listening\" && stopListening.current) {\n stopListening.current = undefined;\n listen(true);\n }\n },\n onError(message) {\n stop(message);\n },\n });\n },\n [speech, silenceMs, idleMs, stop],\n );\n\n // A conversation waits for the reply to its turn, reads it, then listens again.\n const { reply } = options;\n useEffect(() => {\n if (mode.current !== \"thinking\" || !reply || awaiting.current === undefined) return;\n if (reply.id === awaiting.current || reply.status === \"streaming\") return;\n awaiting.current = undefined;\n if (reply.status === \"waiting\") {\n stop(\"Paused: the reply needs your decision.\");\n return;\n }\n const words = speakableText(reply.text);\n if (!speech?.speak || !words) {\n listen(true);\n return;\n }\n set(\"speaking\");\n void speech.speak(words).then(() => {\n if (mode.current === \"speaking\") listen(true);\n });\n }, [reply, speech, listen, stop]);\n\n useEffect(() => () => stop(), [stop]);\n\n const STATUS: Record<VoiceState, string> = { off: note, dictating: \"Listening… speak, then pause.\", listening: \"Listening. Pause when you are done.\", thinking: \"Sent. Waiting for the reply…\", speaking: \"Reading the reply aloud.\" };\n return {\n state,\n status: STATUS[state],\n supported,\n dictate: () => (mode.current === \"off\" ? listen(false) : stop()),\n converse: () => (mode.current === \"off\" ? listen(true) : stop()),\n stop,\n };\n}\n"]}
|