@kabxx/dsh-btw 0.0.0-stage → 0.1.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/NOTICE +50 -0
- package/README.md +48 -2
- package/cordis.patch.yml +3 -0
- package/dist/client.js +2600 -0
- package/icon.svg +8 -0
- package/locale/en.json +83 -0
- package/locale/zh.json +83 -0
- package/package.json +37 -4
- package/src/host/index.js +783 -0
- package/src/host/session-store.js +79 -0
- package/src/host/typert.js +9 -0
- package/src/shared/wire.js +212 -0
package/dist/client.js
ADDED
|
@@ -0,0 +1,2600 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: "@kabxx/dsh-btw",
|
|
3
|
+
factory(require) {
|
|
4
|
+
var BTW = (() => {
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
7
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __export = (target, all) => {
|
|
10
|
+
for (var name in all)
|
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
12
|
+
};
|
|
13
|
+
var __copyProps = (to, from, except, desc) => {
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (let key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
17
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
18
|
+
}
|
|
19
|
+
return to;
|
|
20
|
+
};
|
|
21
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
22
|
+
|
|
23
|
+
// src/client/index.js
|
|
24
|
+
var index_exports = {};
|
|
25
|
+
__export(index_exports, {
|
|
26
|
+
inject: () => inject,
|
|
27
|
+
makeController: () => makeController,
|
|
28
|
+
makeSource: () => makeSource,
|
|
29
|
+
mountClient: () => mountClient,
|
|
30
|
+
unwrap: () => unwrap
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// src/shared/wire.js
|
|
34
|
+
var PACKAGE_NAME = "@kabxx/dsh-btw";
|
|
35
|
+
var CONTEXT_OVERFLOW = "context-window-exceeded";
|
|
36
|
+
var STATUSES = /* @__PURE__ */ new Set(["generating", "completed", "failed", "interrupted"]);
|
|
37
|
+
var TOKEN_FIELDS = ["inputTokens", "outputTokens", "totalTokens", "cacheReadTokens", "cacheWriteTokens", "reasoningTokens"];
|
|
38
|
+
var THREAD_ID = /^btw-[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/u;
|
|
39
|
+
function checked(value, condition, field) {
|
|
40
|
+
if (!condition) throw new TypeError(`Invalid BTW ${field}`);
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function parseSessionId(value) {
|
|
44
|
+
return checked(value, typeof value === "string" && value.length > 0, "sessionId");
|
|
45
|
+
}
|
|
46
|
+
function parseThreadId(value) {
|
|
47
|
+
return checked(value, typeof value === "string" && THREAD_ID.test(value), "id");
|
|
48
|
+
}
|
|
49
|
+
function parseQuestion(value) {
|
|
50
|
+
return checked(value, typeof value === "string" && value.trim() !== "", "question");
|
|
51
|
+
}
|
|
52
|
+
function parseVersion(value) {
|
|
53
|
+
return checked(value, Number.isSafeInteger(value) && value >= 1, "version");
|
|
54
|
+
}
|
|
55
|
+
function timestamp(value) {
|
|
56
|
+
return checked(value, Number.isSafeInteger(value) && value >= 0, "timestamp");
|
|
57
|
+
}
|
|
58
|
+
function object(value, fields) {
|
|
59
|
+
return checked(value, value !== null && typeof value === "object" && !Array.isArray(value) && [null, Object.prototype].includes(Object.getPrototypeOf(value)) && Object.keys(value).every((key) => fields.includes(key)), "record shape");
|
|
60
|
+
}
|
|
61
|
+
function common(value) {
|
|
62
|
+
return {
|
|
63
|
+
id: parseThreadId(value.id),
|
|
64
|
+
sessionId: parseSessionId(value.sessionId),
|
|
65
|
+
question: parseQuestion(value.question),
|
|
66
|
+
createdAt: timestamp(value.createdAt),
|
|
67
|
+
updatedAt: timestamp(value.updatedAt),
|
|
68
|
+
version: parseVersion(value.version)
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
var commonFields = ["id", "sessionId", "question", "createdAt", "updatedAt", "version"];
|
|
72
|
+
function status(value) {
|
|
73
|
+
return checked(value, STATUSES.has(value), "status");
|
|
74
|
+
}
|
|
75
|
+
function parseUsage(usage) {
|
|
76
|
+
object(usage, TOKEN_FIELDS);
|
|
77
|
+
return Object.fromEntries(Object.entries(usage).map(([key, value]) => [key, parsePosition(value)]));
|
|
78
|
+
}
|
|
79
|
+
function parseTiming(value) {
|
|
80
|
+
object(value, ["requestMs", "firstTokenMs"]);
|
|
81
|
+
const requestMs = timestamp(value.requestMs);
|
|
82
|
+
if (value.firstTokenMs === void 0) return { requestMs };
|
|
83
|
+
const firstTokenMs = timestamp(value.firstTokenMs);
|
|
84
|
+
return checked({ requestMs, firstTokenMs }, firstTokenMs <= requestMs, "first token timing");
|
|
85
|
+
}
|
|
86
|
+
function parseTurn(value) {
|
|
87
|
+
object(value, ["question", "reply", "status", "createdAt", "finishedAt", "error", "saveError", "usage", "timing"]);
|
|
88
|
+
const turn = {
|
|
89
|
+
question: parseQuestion(value.question),
|
|
90
|
+
reply: checked(value.reply, typeof value.reply === "string", "reply"),
|
|
91
|
+
status: status(value.status),
|
|
92
|
+
createdAt: timestamp(value.createdAt)
|
|
93
|
+
};
|
|
94
|
+
if (turn.status !== "generating") turn.finishedAt = timestamp(value.finishedAt);
|
|
95
|
+
else checked(value.finishedAt, value.finishedAt === void 0, "finishedAt");
|
|
96
|
+
if (value.error !== void 0) turn.error = checked(value.error, typeof value.error === "string", "error");
|
|
97
|
+
if (value.saveError !== void 0) turn.saveError = checked(value.saveError, typeof value.saveError === "string", "saveError");
|
|
98
|
+
if (value.usage !== void 0) turn.usage = parseUsage(value.usage);
|
|
99
|
+
if (value.timing !== void 0) turn.timing = parseTiming(value.timing);
|
|
100
|
+
return turn;
|
|
101
|
+
}
|
|
102
|
+
function parseDetail(value) {
|
|
103
|
+
object(value, [...commonFields, "turns"]);
|
|
104
|
+
checked(value.turns, Array.isArray(value.turns) && value.turns.length > 0, "turns");
|
|
105
|
+
return { ...common(value), turns: value.turns.map(parseTurn) };
|
|
106
|
+
}
|
|
107
|
+
function parseContext(value) {
|
|
108
|
+
object(value, ["contextWindow", "estimatedTokens"]);
|
|
109
|
+
const capacity = value.contextWindow;
|
|
110
|
+
const contextWindow = checked(capacity, capacity === null || Number.isSafeInteger(capacity) && capacity > 0, "contextWindow");
|
|
111
|
+
return {
|
|
112
|
+
contextWindow,
|
|
113
|
+
...value.estimatedTokens !== void 0 && { estimatedTokens: parsePosition(value.estimatedTokens) }
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function parseSummaries(values) {
|
|
117
|
+
checked(values, Array.isArray(values), "summaries");
|
|
118
|
+
return values.map((value) => {
|
|
119
|
+
object(value, [...commonFields, "status"]);
|
|
120
|
+
return { ...common(value), status: status(value.status) };
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
function codec(typeSymbol, parse) {
|
|
124
|
+
return Object.freeze({ mode: "strict", typeSymbol, create: () => ({ parse }) });
|
|
125
|
+
}
|
|
126
|
+
function parsePosition(value) {
|
|
127
|
+
return checked(value, Number.isSafeInteger(value) && value >= 0, "position");
|
|
128
|
+
}
|
|
129
|
+
function appendTurn(detail2, receipt2) {
|
|
130
|
+
if (detail2.id !== receipt2.id || detail2.sessionId !== receipt2.sessionId || receipt2.turnIndex !== detail2.turns.length || receipt2.version <= detail2.version) return detail2;
|
|
131
|
+
return { ...detail2, updatedAt: receipt2.updatedAt, version: receipt2.version, turns: [...detail2.turns, receipt2.turn] };
|
|
132
|
+
}
|
|
133
|
+
function applyReply(detail2, turnIndex, update) {
|
|
134
|
+
const turn = detail2.turns[turnIndex];
|
|
135
|
+
if (!turn || turn.status !== "generating" || update.version <= detail2.version) return detail2;
|
|
136
|
+
checked(update.offset <= turn.reply.length, "reply offset");
|
|
137
|
+
const turns = [...detail2.turns];
|
|
138
|
+
turns[turnIndex] = {
|
|
139
|
+
...turn,
|
|
140
|
+
reply: turn.reply.slice(0, update.offset) + update.text,
|
|
141
|
+
status: update.status,
|
|
142
|
+
...update.finishedAt !== void 0 && { finishedAt: update.finishedAt },
|
|
143
|
+
...update.error !== void 0 && { error: update.error },
|
|
144
|
+
...update.saveError !== void 0 && { saveError: update.saveError },
|
|
145
|
+
...update.usage !== void 0 && { usage: update.usage },
|
|
146
|
+
...update.timing !== void 0 && { timing: update.timing }
|
|
147
|
+
};
|
|
148
|
+
return { ...detail2, updatedAt: update.updatedAt, version: update.version, turns };
|
|
149
|
+
}
|
|
150
|
+
function parseReceipt(value) {
|
|
151
|
+
object(value, ["id", "sessionId", "updatedAt", "version", "turnIndex", "turn"]);
|
|
152
|
+
return {
|
|
153
|
+
id: parseThreadId(value.id),
|
|
154
|
+
sessionId: parseSessionId(value.sessionId),
|
|
155
|
+
updatedAt: timestamp(value.updatedAt),
|
|
156
|
+
version: parseVersion(value.version),
|
|
157
|
+
turnIndex: parsePosition(value.turnIndex),
|
|
158
|
+
turn: parseTurn(value.turn)
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
function parseReplyUpdate(value) {
|
|
162
|
+
object(value, ["version", "updatedAt", "offset", "text", "status", "finishedAt", "error", "saveError", "usage", "timing"]);
|
|
163
|
+
const update = {
|
|
164
|
+
version: parseVersion(value.version),
|
|
165
|
+
updatedAt: timestamp(value.updatedAt),
|
|
166
|
+
offset: parsePosition(value.offset),
|
|
167
|
+
text: checked(value.text, typeof value.text === "string", "text"),
|
|
168
|
+
status: status(value.status)
|
|
169
|
+
};
|
|
170
|
+
if (update.status !== "generating") update.finishedAt = timestamp(value.finishedAt);
|
|
171
|
+
else checked(value.finishedAt, value.finishedAt === void 0, "finishedAt");
|
|
172
|
+
if (value.error !== void 0) update.error = checked(value.error, typeof value.error === "string", "error");
|
|
173
|
+
if (value.saveError !== void 0) update.saveError = checked(value.saveError, typeof value.saveError === "string", "saveError");
|
|
174
|
+
if (value.usage !== void 0) update.usage = parseUsage(value.usage);
|
|
175
|
+
if (value.timing !== void 0) update.timing = parseTiming(value.timing);
|
|
176
|
+
return update;
|
|
177
|
+
}
|
|
178
|
+
var detail = codec(`${PACKAGE_NAME}#Detail`, parseDetail);
|
|
179
|
+
var receipt = codec(`${PACKAGE_NAME}#FollowupReceipt`, parseReceipt);
|
|
180
|
+
var replyUpdate = codec(`${PACKAGE_NAME}#ReplyUpdate`, parseReplyUpdate);
|
|
181
|
+
var summaryList = codec(`${PACKAGE_NAME}#SummaryList`, parseSummaries);
|
|
182
|
+
var agent = Object.freeze({
|
|
183
|
+
name: "agent",
|
|
184
|
+
wire: "agentId",
|
|
185
|
+
source: "lookup",
|
|
186
|
+
lookup: "agent",
|
|
187
|
+
codec: codec("@deepseek-ai/dsh-session/types#SessionId", parseSessionId)
|
|
188
|
+
});
|
|
189
|
+
function parameter(name, parse, acceptsUndefined) {
|
|
190
|
+
return Object.freeze({
|
|
191
|
+
name,
|
|
192
|
+
wire: name,
|
|
193
|
+
source: "json",
|
|
194
|
+
codec: codec(`${PACKAGE_NAME}#${name}`, parse),
|
|
195
|
+
...acceptsUndefined ? { acceptsUndefined: true } : {}
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
var id = parameter("id", parseThreadId);
|
|
199
|
+
var question = parameter("question", parseQuestion);
|
|
200
|
+
var version = parameter("version", (value) => value == null ? void 0 : parseVersion(value), true);
|
|
201
|
+
function descriptor(method, parameters, result, stream = false) {
|
|
202
|
+
return Object.freeze({
|
|
203
|
+
id: `${PACKAGE_NAME}#btw/${method}`,
|
|
204
|
+
service: "btw",
|
|
205
|
+
namespace: "btw",
|
|
206
|
+
method,
|
|
207
|
+
invocation: { kind: "direct" },
|
|
208
|
+
parameters: Object.freeze([agent, ...parameters]),
|
|
209
|
+
cancellation: { parameter: "signal" },
|
|
210
|
+
result,
|
|
211
|
+
...stream ? { mode: "stream" } : {}
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
var descriptors = Object.freeze([
|
|
215
|
+
descriptor("create", [question], detail),
|
|
216
|
+
descriptor("list", [], summaryList),
|
|
217
|
+
descriptor("get", [id], detail),
|
|
218
|
+
descriptor("followup", [id, question], receipt),
|
|
219
|
+
descriptor("watch", [id, version], detail, true),
|
|
220
|
+
descriptor("watchReply", [id, parameter("turnIndex", parsePosition), version], replyUpdate, true)
|
|
221
|
+
]);
|
|
222
|
+
var contextDescriptor = descriptor("contextCapacity", [id], codec(`${PACKAGE_NAME}#ContextWindow`, parseContext));
|
|
223
|
+
var TYPERT_REMOTE = Object.freeze({ package: PACKAGE_NAME, descriptors: Object.freeze([...descriptors, contextDescriptor]) });
|
|
224
|
+
|
|
225
|
+
// src/client/views.js
|
|
226
|
+
var styles = String.raw`
|
|
227
|
+
.dsh-btw-dock {
|
|
228
|
+
box-sizing: border-box;
|
|
229
|
+
width: calc(100% - 2 * var(--dsh-composer-side-clearance, 0px) - 4 * var(--dsh-composer-dock-inset, 4px));
|
|
230
|
+
max-width: calc(var(--dsh-composer-card-max-width, 100%) - 4 * var(--dsh-composer-dock-inset, 4px));
|
|
231
|
+
min-width: 0;
|
|
232
|
+
margin-inline: auto;
|
|
233
|
+
}
|
|
234
|
+
.dsh-btw-card {
|
|
235
|
+
--dsw-elevation-stroke-color: var(--dsw-alias-border-l1);
|
|
236
|
+
position: relative;
|
|
237
|
+
isolation: isolate;
|
|
238
|
+
border-radius: var(--dsw-radius-md);
|
|
239
|
+
box-shadow: var(--dsw-elevation-panel);
|
|
240
|
+
color: var(--dsw-alias-label-secondary);
|
|
241
|
+
}
|
|
242
|
+
.dsh-btw-card::before {
|
|
243
|
+
position: absolute;
|
|
244
|
+
z-index: -1;
|
|
245
|
+
inset: 0;
|
|
246
|
+
border-radius: inherit;
|
|
247
|
+
background: var(--dsw-specific-menu);
|
|
248
|
+
backdrop-filter: var(--dsw-menu-backdrop-filter);
|
|
249
|
+
content: '';
|
|
250
|
+
pointer-events: none;
|
|
251
|
+
}
|
|
252
|
+
.dsh-btw-card-bar {
|
|
253
|
+
box-sizing: border-box;
|
|
254
|
+
display: flex;
|
|
255
|
+
align-items: center;
|
|
256
|
+
gap: 10px;
|
|
257
|
+
min-height: 36px;
|
|
258
|
+
padding: 4px 5px 4px 12px;
|
|
259
|
+
}
|
|
260
|
+
.dsh-btw-mark { display: block; flex: none; color: var(--dsw-alias-label-tertiary); }
|
|
261
|
+
.dsh-btw-title-label {
|
|
262
|
+
flex: none;
|
|
263
|
+
max-width: 35%;
|
|
264
|
+
overflow: hidden;
|
|
265
|
+
color: var(--dsw-alias-label-primary);
|
|
266
|
+
font-size: 13px;
|
|
267
|
+
line-height: 24px;
|
|
268
|
+
font-weight: 500;
|
|
269
|
+
text-overflow: ellipsis;
|
|
270
|
+
white-space: nowrap;
|
|
271
|
+
}
|
|
272
|
+
.dsh-btw-question {
|
|
273
|
+
flex: 1 1 auto;
|
|
274
|
+
min-width: 0;
|
|
275
|
+
margin: 0;
|
|
276
|
+
overflow: hidden;
|
|
277
|
+
color: var(--dsw-alias-label-primary-dimmed);
|
|
278
|
+
font-size: 13px;
|
|
279
|
+
font-weight: 400;
|
|
280
|
+
line-height: 20px;
|
|
281
|
+
text-overflow: ellipsis;
|
|
282
|
+
white-space: nowrap;
|
|
283
|
+
}
|
|
284
|
+
.dsh-btw-actions { display: flex; flex: none; align-items: center; gap: 8px; }
|
|
285
|
+
@media (max-width: 420px) { .dsh-btw-actions { gap: 4px; } }
|
|
286
|
+
.dsh-btw-icon-button {
|
|
287
|
+
display: inline-flex;
|
|
288
|
+
flex: none;
|
|
289
|
+
width: 28px;
|
|
290
|
+
height: 28px;
|
|
291
|
+
align-items: center;
|
|
292
|
+
justify-content: center;
|
|
293
|
+
padding: 0;
|
|
294
|
+
border: 0;
|
|
295
|
+
border-radius: 50%;
|
|
296
|
+
corner-shape: round;
|
|
297
|
+
background: transparent;
|
|
298
|
+
color: var(--dsw-alias-label-tertiary);
|
|
299
|
+
cursor: pointer;
|
|
300
|
+
}
|
|
301
|
+
.dsh-btw-icon-button:disabled { opacity: .4; cursor: default; }
|
|
302
|
+
.dsh-btw-icon-button:focus-visible, .dsh-btw-row:focus-visible, .dsh-btw-retry:focus-visible {
|
|
303
|
+
outline: 2px solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
|
|
304
|
+
outline-offset: -2px;
|
|
305
|
+
}
|
|
306
|
+
@media (hover: hover) {
|
|
307
|
+
.dsh-btw-icon-button:hover:not(:disabled), .dsh-btw-row:hover, .dsh-btw-retry:hover {
|
|
308
|
+
background: var(--dsw-alias-interactive-bg-hover);
|
|
309
|
+
color: var(--dsw-alias-label-primary);
|
|
310
|
+
}
|
|
311
|
+
.dsh-btw-card .dsh-btw-icon-button:hover:not(:disabled) { color: var(--dsw-alias-label-secondary); }
|
|
312
|
+
}
|
|
313
|
+
.dsh-btw-inline-reply {
|
|
314
|
+
--dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
|
|
315
|
+
--dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
|
|
316
|
+
max-height: min(220px, 29dvh);
|
|
317
|
+
overflow: auto;
|
|
318
|
+
overscroll-behavior: contain;
|
|
319
|
+
padding: 5px 12px 8px;
|
|
320
|
+
color: var(--dsw-alias-label-primary);
|
|
321
|
+
font-size: var(--dsh-content-font-size-secondary, 13px);
|
|
322
|
+
line-height: calc(20px + var(--dsh-content-font-delta, 0px));
|
|
323
|
+
overflow-wrap: anywhere;
|
|
324
|
+
}
|
|
325
|
+
.dsh-btw-inline-rule { margin-inline: 12px; border-top: 1px solid var(--dsw-alias-border-l1); }
|
|
326
|
+
.dsh-btw-waiting {
|
|
327
|
+
display: flex;
|
|
328
|
+
align-items: center;
|
|
329
|
+
gap: 6px;
|
|
330
|
+
color: var(--dsw-alias-label-secondary);
|
|
331
|
+
}
|
|
332
|
+
/* DSH 0.2.2-rc.5 StateDot ongoing styles, scoped to BTW (see NOTICE). */
|
|
333
|
+
.dsh-btw-waiting-spinner { flex: none; color: var(--dsw-alias-label-tertiary); }
|
|
334
|
+
.dsh-btw-spinner-motion {
|
|
335
|
+
transform-origin: center;
|
|
336
|
+
animation: dsh-btw-spinner-spin 1.5s linear infinite;
|
|
337
|
+
}
|
|
338
|
+
.dsh-btw-spinner-track, .dsh-btw-spinner-arc {
|
|
339
|
+
fill: none;
|
|
340
|
+
stroke: currentColor;
|
|
341
|
+
stroke-width: 2;
|
|
342
|
+
stroke-linecap: round;
|
|
343
|
+
}
|
|
344
|
+
.dsh-btw-spinner-track { opacity: .25; }
|
|
345
|
+
.dsh-btw-spinner-arc {
|
|
346
|
+
stroke-dasharray: 12 150;
|
|
347
|
+
animation: dsh-btw-spinner-dash 1.5s ease-in-out infinite;
|
|
348
|
+
}
|
|
349
|
+
@keyframes dsh-btw-spinner-spin { to { transform: rotate(360deg); } }
|
|
350
|
+
@keyframes dsh-btw-spinner-dash {
|
|
351
|
+
0% { stroke-dasharray: 12 150; stroke-dashoffset: 0; }
|
|
352
|
+
50% { stroke-dasharray: 24 150; stroke-dashoffset: -6; }
|
|
353
|
+
to { stroke-dasharray: 12 150; stroke-dashoffset: 0; }
|
|
354
|
+
}
|
|
355
|
+
@media (prefers-reduced-motion: reduce) {
|
|
356
|
+
.dsh-btw-spinner-motion, .dsh-btw-spinner-arc { animation: none; }
|
|
357
|
+
.dsh-btw-spinner-arc { stroke-dasharray: 18 150; stroke-dashoffset: -3; }
|
|
358
|
+
}
|
|
359
|
+
.dsh-btw-inline-reply [data-markdown-variant='compact'],
|
|
360
|
+
.dsh-btw-message-assistant [data-markdown-variant='compact'] {
|
|
361
|
+
color: var(--dsw-alias-label-primary);
|
|
362
|
+
font-size: inherit;
|
|
363
|
+
line-height: inherit;
|
|
364
|
+
}
|
|
365
|
+
.dsh-btw-plain { white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
366
|
+
.dsh-btw-pane {
|
|
367
|
+
box-sizing: border-box;
|
|
368
|
+
display: flex;
|
|
369
|
+
flex: 1 1 0;
|
|
370
|
+
flex-direction: column;
|
|
371
|
+
width: 100%;
|
|
372
|
+
min-height: 0;
|
|
373
|
+
min-width: 0;
|
|
374
|
+
color: var(--dsw-alias-label-primary);
|
|
375
|
+
background: var(--dsw-alias-bg-base);
|
|
376
|
+
container: dsh-btw-side / inline-size;
|
|
377
|
+
}
|
|
378
|
+
.dsh-btw-bar {
|
|
379
|
+
display: flex;
|
|
380
|
+
flex: none;
|
|
381
|
+
align-items: center;
|
|
382
|
+
gap: 8px;
|
|
383
|
+
min-height: 38px;
|
|
384
|
+
padding-inline: 10px;
|
|
385
|
+
border-bottom: 1px solid var(--dsw-alias-border-l1);
|
|
386
|
+
}
|
|
387
|
+
.dsh-btw-bar-title {
|
|
388
|
+
min-width: 0;
|
|
389
|
+
margin: 0;
|
|
390
|
+
overflow: hidden;
|
|
391
|
+
font-size: var(--dsh-content-font-size-secondary, 13px);
|
|
392
|
+
font-weight: 500;
|
|
393
|
+
line-height: 1.5;
|
|
394
|
+
text-overflow: ellipsis;
|
|
395
|
+
white-space: nowrap;
|
|
396
|
+
}
|
|
397
|
+
.dsh-btw-list, .dsh-btw-thread {
|
|
398
|
+
flex: 1 1 0;
|
|
399
|
+
min-width: 0;
|
|
400
|
+
min-height: 0;
|
|
401
|
+
overflow: auto;
|
|
402
|
+
overscroll-behavior: contain;
|
|
403
|
+
}
|
|
404
|
+
.dsh-btw-list { padding: 10px 8px 12px; }
|
|
405
|
+
.dsh-btw-history { display: grid; gap: 2px; margin: 0; padding: 0; list-style: none; }
|
|
406
|
+
.dsh-btw-row {
|
|
407
|
+
display: grid;
|
|
408
|
+
width: 100%;
|
|
409
|
+
min-height: 36px;
|
|
410
|
+
grid-template-columns: minmax(0, 1fr) auto 12px;
|
|
411
|
+
align-items: center;
|
|
412
|
+
gap: 8px;
|
|
413
|
+
padding: 5px 8px;
|
|
414
|
+
border: 0;
|
|
415
|
+
border-radius: var(--dsw-radius-sm);
|
|
416
|
+
background: transparent;
|
|
417
|
+
color: var(--dsw-alias-label-primary);
|
|
418
|
+
text-align: start;
|
|
419
|
+
font: inherit;
|
|
420
|
+
font-size: var(--dsh-content-font-size-secondary, 13px);
|
|
421
|
+
cursor: pointer;
|
|
422
|
+
}
|
|
423
|
+
.dsh-btw-row-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
424
|
+
.dsh-btw-row > svg, .dsh-btw-time { color: var(--dsw-alias-label-tertiary); }
|
|
425
|
+
.dsh-btw-time { font-size: 11px; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
|
426
|
+
.dsh-btw-row { box-sizing: border-box; }
|
|
427
|
+
@container dsh-btw-side (max-width: 240px) {
|
|
428
|
+
.dsh-btw-row { grid-template-columns: minmax(0, 1fr) 12px; column-gap: 5px; row-gap: 1px; }
|
|
429
|
+
.dsh-btw-row-time { grid-column: 1; grid-row: 2; min-width: 0; }
|
|
430
|
+
.dsh-btw-row-time .dsh-btw-time { white-space: normal; overflow-wrap: anywhere; }
|
|
431
|
+
.dsh-btw-row > svg { grid-column: 2; grid-row: 1 / 3; }
|
|
432
|
+
}
|
|
433
|
+
.dsh-btw-thread { padding: 14px 12px; }
|
|
434
|
+
.dsh-btw-turn { display: flex; min-width: 0; flex-direction: column; align-items: stretch; gap: 12px; }
|
|
435
|
+
.dsh-btw-turn + .dsh-btw-turn { margin-top: 16px; }
|
|
436
|
+
.dsh-btw-message-user { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; min-width: 0; }
|
|
437
|
+
.dsh-btw-user-fallback {
|
|
438
|
+
box-sizing: border-box;
|
|
439
|
+
max-width: 100%;
|
|
440
|
+
border-radius: var(--dsw-radius-xl);
|
|
441
|
+
corner-shape: superellipse(1.5);
|
|
442
|
+
padding: 10px 16px;
|
|
443
|
+
background: var(--dsw-specific-bubble);
|
|
444
|
+
font-size: var(--dsh-content-font-size, 14px);
|
|
445
|
+
line-height: calc(22px + var(--dsh-content-font-delta, 0px));
|
|
446
|
+
}
|
|
447
|
+
.dsh-btw-message-assistant {
|
|
448
|
+
min-width: 0;
|
|
449
|
+
color: var(--dsw-alias-label-primary);
|
|
450
|
+
font-size: var(--dsh-content-font-size, 14px);
|
|
451
|
+
line-height: calc(24px + var(--dsh-content-font-delta, 0px));
|
|
452
|
+
overflow-wrap: anywhere;
|
|
453
|
+
}
|
|
454
|
+
.dsh-btw-message-actions {
|
|
455
|
+
display: flex;
|
|
456
|
+
align-items: center;
|
|
457
|
+
height: calc(28px + var(--dsh-content-font-delta, 0px));
|
|
458
|
+
gap: 8px;
|
|
459
|
+
color: var(--dsw-alias-label-tertiary);
|
|
460
|
+
}
|
|
461
|
+
.dsh-btw-message-actions .dsh-btw-icon-button {
|
|
462
|
+
width: calc(28px + var(--dsh-content-font-delta, 0px));
|
|
463
|
+
height: calc(28px + var(--dsh-content-font-delta, 0px));
|
|
464
|
+
padding: 6px;
|
|
465
|
+
border-radius: var(--dsw-radius-sm);
|
|
466
|
+
corner-shape: inherit;
|
|
467
|
+
}
|
|
468
|
+
.dsh-btw-message-actions .dsh-btw-icon-button:hover:not(:disabled) { color: var(--dsw-alias-label-secondary); }
|
|
469
|
+
.dsh-btw-message-actions .dsh-btw-time {
|
|
470
|
+
font-size: var(--dsh-content-font-size-secondary, 13px);
|
|
471
|
+
line-height: calc(24px + var(--dsh-content-font-delta, 0px));
|
|
472
|
+
font-variant-numeric: normal;
|
|
473
|
+
}
|
|
474
|
+
.dsh-btw-message-user .dsh-btw-message-actions { justify-content: flex-end; }
|
|
475
|
+
.dsh-btw-message-user .dsh-btw-time { padding-inline-end: 12px; }
|
|
476
|
+
.dsh-btw-message-assistant .dsh-btw-message-actions { margin-block-start: 16px; margin-inline-start: -6px; }
|
|
477
|
+
.dsh-btw-message-end-info { display: inline-flex; align-items: center; gap: 8px; min-width: 0; margin-inline-start: 8px; }
|
|
478
|
+
.dsh-btw-message-end-info .dsh-btw-time { color: inherit; font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px); }
|
|
479
|
+
@media (hover: hover) {
|
|
480
|
+
[data-btw-actions-reveal='hover']:not(:hover):not(:focus-within) .dsh-btw-message-actions:not(:has([aria-expanded='true'])) { opacity: 0; }
|
|
481
|
+
}
|
|
482
|
+
@media (hover: hover) and (prefers-reduced-motion: no-preference) {
|
|
483
|
+
[data-btw-actions-reveal='hover'] .dsh-btw-message-actions { transition: opacity 80ms ease; }
|
|
484
|
+
}
|
|
485
|
+
.dsh-btw-message-user .dsh-btw-icon-button svg {
|
|
486
|
+
width: calc(15px + var(--dsh-content-font-delta, 0px));
|
|
487
|
+
height: calc(15px + var(--dsh-content-font-delta, 0px));
|
|
488
|
+
}
|
|
489
|
+
.dsh-btw-message-assistant .dsh-btw-icon-button svg {
|
|
490
|
+
width: calc(17px + var(--dsh-content-font-delta, 0px));
|
|
491
|
+
height: calc(17px + var(--dsh-content-font-delta, 0px));
|
|
492
|
+
}
|
|
493
|
+
.dsh-btw-turn-usage {
|
|
494
|
+
display: inline-flex;
|
|
495
|
+
align-items: center;
|
|
496
|
+
gap: 4px;
|
|
497
|
+
min-width: 0;
|
|
498
|
+
height: calc(28px + var(--dsh-content-font-delta, 0px));
|
|
499
|
+
padding: 6px 8px;
|
|
500
|
+
border: 0;
|
|
501
|
+
border-radius: var(--dsw-radius-sm);
|
|
502
|
+
background: transparent;
|
|
503
|
+
color: inherit;
|
|
504
|
+
cursor: pointer;
|
|
505
|
+
font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px);
|
|
506
|
+
font-variant-numeric: tabular-nums;
|
|
507
|
+
line-height: calc(24px + var(--dsh-content-font-delta, 0px));
|
|
508
|
+
white-space: nowrap;
|
|
509
|
+
}
|
|
510
|
+
.dsh-btw-turn-usage:focus-visible {
|
|
511
|
+
outline: 2px solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
|
|
512
|
+
outline-offset: -2px;
|
|
513
|
+
}
|
|
514
|
+
.dsh-btw-turn-usage svg {
|
|
515
|
+
flex: none;
|
|
516
|
+
width: calc(15px + var(--dsh-content-font-delta, 0px));
|
|
517
|
+
height: calc(15px + var(--dsh-content-font-delta, 0px));
|
|
518
|
+
}
|
|
519
|
+
.dsh-btw-turn-usage span { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
520
|
+
.dsh-btw-turn-usage[aria-expanded='true'] { background: var(--dsw-alias-interactive-bg-hover); }
|
|
521
|
+
@media (hover: hover) {
|
|
522
|
+
.dsh-btw-turn-usage:hover { background: var(--dsw-alias-interactive-bg-hover); }
|
|
523
|
+
}
|
|
524
|
+
@container dsh-btw-side (max-width: 300px) {
|
|
525
|
+
.dsh-btw-turn-usage { justify-content: center; width: calc(28px + var(--dsh-content-font-delta, 0px)); padding: 6px; }
|
|
526
|
+
.dsh-btw-turn-usage span { display: none; }
|
|
527
|
+
}
|
|
528
|
+
.dsh-btw-turn-usage-panel { margin: 6px 0 0; border-radius: var(--dsw-radius-sm); }
|
|
529
|
+
.dsh-btw-turn-usage-panel .dsh-btw-stat-details { padding: 8px 10px; font-size: var(--dsh-content-font-size-secondary, 13px); }
|
|
530
|
+
.dsh-btw-context-track, .dsh-btw-context-fill { fill: none; stroke-width: 2; }
|
|
531
|
+
.dsh-btw-context-track { stroke: var(--dsw-alias-border-l3); }
|
|
532
|
+
.dsh-btw-context-fill { stroke: var(--dsw-alias-label-tertiary); stroke-linecap: round; }
|
|
533
|
+
.dsh-btw-feedback { margin: 6px 8px; font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-secondary); }
|
|
534
|
+
.dsh-btw-turn-feedback { margin: 3px 0 0; }
|
|
535
|
+
.dsh-btw-failure { color: var(--dsw-alias-state-error-primary); }
|
|
536
|
+
.dsh-btw-retry {
|
|
537
|
+
margin-inline-start: 6px;
|
|
538
|
+
padding: 2px 6px;
|
|
539
|
+
border: 0;
|
|
540
|
+
border-radius: var(--dsw-radius-sm);
|
|
541
|
+
background: transparent;
|
|
542
|
+
color: var(--dsw-alias-state-business-primary);
|
|
543
|
+
font: inherit;
|
|
544
|
+
cursor: pointer;
|
|
545
|
+
}
|
|
546
|
+
.dsh-btw-reply-dock { box-sizing: border-box; flex: none; min-width: 0; padding: 0 10px max(4px, env(safe-area-inset-bottom)); }
|
|
547
|
+
.dsh-btw-audit {
|
|
548
|
+
position: relative;
|
|
549
|
+
display: flex;
|
|
550
|
+
align-items: center;
|
|
551
|
+
justify-content: center;
|
|
552
|
+
flex-wrap: wrap;
|
|
553
|
+
gap: 0 12px;
|
|
554
|
+
min-height: calc(22px + var(--dsh-content-font-delta-secondary, 0px));
|
|
555
|
+
max-width: 100%;
|
|
556
|
+
padding-top: 4px;
|
|
557
|
+
font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px);
|
|
558
|
+
line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px));
|
|
559
|
+
font-variant-numeric: tabular-nums;
|
|
560
|
+
}
|
|
561
|
+
.dsh-btw-stat { display: flex; min-width: 0; max-width: 100%; }
|
|
562
|
+
.dsh-btw-stat-trigger {
|
|
563
|
+
display: inline-flex;
|
|
564
|
+
align-items: center;
|
|
565
|
+
gap: 6px;
|
|
566
|
+
min-width: 0;
|
|
567
|
+
max-width: 100%;
|
|
568
|
+
box-sizing: border-box;
|
|
569
|
+
padding: 1px 8px;
|
|
570
|
+
border: 0;
|
|
571
|
+
border-radius: var(--dsw-radius-sm);
|
|
572
|
+
background: transparent;
|
|
573
|
+
color: var(--dsw-alias-label-tertiary);
|
|
574
|
+
font: inherit;
|
|
575
|
+
white-space: nowrap;
|
|
576
|
+
}
|
|
577
|
+
summary.dsh-btw-stat-trigger { cursor: pointer; }
|
|
578
|
+
.dsh-btw-stat-trigger::-webkit-details-marker { display: none; }
|
|
579
|
+
.dsh-btw-stat-trigger:focus-visible {
|
|
580
|
+
outline: 2px solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
|
|
581
|
+
outline-offset: -2px;
|
|
582
|
+
}
|
|
583
|
+
.dsh-btw-stat-trigger svg { flex: none; display: block; }
|
|
584
|
+
.dsh-btw-stat[open] > .dsh-btw-stat-trigger {
|
|
585
|
+
background: var(--dsw-alias-interactive-bg-hover);
|
|
586
|
+
color: var(--dsw-alias-label-secondary);
|
|
587
|
+
}
|
|
588
|
+
@media (hover: hover) {
|
|
589
|
+
summary.dsh-btw-stat-trigger:hover {
|
|
590
|
+
background: var(--dsw-alias-interactive-bg-hover);
|
|
591
|
+
color: var(--dsw-alias-label-secondary);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
.dsh-btw-stat-label { min-width: 0; text-align: start; white-space: normal; overflow-wrap: anywhere; }
|
|
595
|
+
.dsh-btw-stat-reading { display: inline-block; max-width: 100%; }
|
|
596
|
+
.dsh-btw-stat-sep { margin-inline: 6px; color: var(--dsw-alias-separator-primary); }
|
|
597
|
+
.dsh-btw-stat-panel {
|
|
598
|
+
position: absolute;
|
|
599
|
+
z-index: 1;
|
|
600
|
+
inset-inline: 0;
|
|
601
|
+
bottom: calc(100% + 8px);
|
|
602
|
+
box-sizing: border-box;
|
|
603
|
+
width: min(100%, 440px);
|
|
604
|
+
max-height: 45dvh;
|
|
605
|
+
margin-inline: auto;
|
|
606
|
+
overflow: auto;
|
|
607
|
+
padding: 16px;
|
|
608
|
+
border-radius: var(--dsw-radius-lg);
|
|
609
|
+
background: var(--dsw-specific-menu);
|
|
610
|
+
backdrop-filter: var(--dsw-menu-backdrop-filter);
|
|
611
|
+
--dsw-elevation-stroke-color: var(--dsw-alias-border-l1);
|
|
612
|
+
box-shadow: var(--dsw-elevation-prominent);
|
|
613
|
+
color: var(--dsw-alias-label-secondary);
|
|
614
|
+
line-height: 18px;
|
|
615
|
+
}
|
|
616
|
+
.dsh-btw-stat-heading {
|
|
617
|
+
display: flex;
|
|
618
|
+
align-items: center;
|
|
619
|
+
gap: 6px;
|
|
620
|
+
margin: 0 0 10px;
|
|
621
|
+
padding-bottom: 8px;
|
|
622
|
+
border-bottom: 0.5px solid var(--dsw-alias-border-l2);
|
|
623
|
+
color: var(--dsw-alias-label-primary);
|
|
624
|
+
font: inherit;
|
|
625
|
+
font-weight: 500;
|
|
626
|
+
}
|
|
627
|
+
.dsh-btw-stat-heading svg { flex: none; }
|
|
628
|
+
.dsh-btw-stat-details {
|
|
629
|
+
display: grid;
|
|
630
|
+
grid-template-columns: minmax(0, 1fr) auto;
|
|
631
|
+
gap: 6px 16px;
|
|
632
|
+
margin: 0;
|
|
633
|
+
color: var(--dsw-alias-label-tertiary);
|
|
634
|
+
}
|
|
635
|
+
.dsh-btw-stat-details dd { margin: 0; text-align: end; color: var(--dsw-alias-label-secondary); }
|
|
636
|
+
@container dsh-btw-side (max-width: 300px) {
|
|
637
|
+
.dsh-btw-audit { gap: 0 4px; }
|
|
638
|
+
.dsh-btw-stat-trigger { padding-inline: 4px; }
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
.dsh-btw-form {
|
|
642
|
+
box-sizing: border-box;
|
|
643
|
+
display: flex;
|
|
644
|
+
flex-direction: column;
|
|
645
|
+
gap: 12px;
|
|
646
|
+
width: 100%;
|
|
647
|
+
padding-top: 8px;
|
|
648
|
+
border: 0;
|
|
649
|
+
--dsw-elevation-stroke-color: var(--dsw-alias-border-l2);
|
|
650
|
+
border-radius: var(--dsw-radius-panel);
|
|
651
|
+
corner-shape: superellipse(1.5);
|
|
652
|
+
background: var(--dsw-specific-input-major);
|
|
653
|
+
box-shadow: var(--dsw-elevation-soft);
|
|
654
|
+
font-size: var(--dsh-content-font-size, 14px);
|
|
655
|
+
line-height: calc(24px + var(--dsh-content-font-delta, 0px));
|
|
656
|
+
--dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
|
|
657
|
+
--dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
|
|
658
|
+
}
|
|
659
|
+
.dsh-btw-input {
|
|
660
|
+
display: block;
|
|
661
|
+
box-sizing: border-box;
|
|
662
|
+
width: calc(100% - 4px);
|
|
663
|
+
min-height: 36px;
|
|
664
|
+
max-height: min(var(--dsh-composer-text-max-height, 336px), max(42px, 28dvh));
|
|
665
|
+
margin-inline-end: 4px;
|
|
666
|
+
padding: 4px 8px 0 14px;
|
|
667
|
+
resize: none;
|
|
668
|
+
border: none;
|
|
669
|
+
background: transparent;
|
|
670
|
+
color: inherit;
|
|
671
|
+
caret-color: var(--dsw-alias-state-business-primary);
|
|
672
|
+
font: inherit;
|
|
673
|
+
font-weight: 400;
|
|
674
|
+
}
|
|
675
|
+
.dsh-btw-input:focus { outline: none; }
|
|
676
|
+
.dsh-btw-input:disabled { color: var(--dsw-alias-label-tertiary); opacity: .6; }
|
|
677
|
+
@supports (field-sizing: content) { .dsh-btw-input { field-sizing: content; } }
|
|
678
|
+
.dsh-btw-input::placeholder { color: var(--dsw-alias-label-caption); font: inherit; opacity: 1; }
|
|
679
|
+
@media (pointer: coarse) {
|
|
680
|
+
.dsh-btw-form { font-size: max(16px, var(--dsh-content-font-size, 14px)); }
|
|
681
|
+
.dsh-btw-input { max-height: min(var(--dsh-composer-text-max-height, 336px), max(42px, 22dvh)); }
|
|
682
|
+
}
|
|
683
|
+
.dsh-btw-form-actions { display: flex; justify-content: flex-end; align-items: center; gap: 8px; padding: 2px 8px 6px; }
|
|
684
|
+
.dsh-btw-mic { color: var(--dsw-alias-label-primary); }
|
|
685
|
+
.dsh-btw-mic[data-recording='true'] { background: var(--dsw-alias-interactive-bg-hover); }
|
|
686
|
+
.dsh-btw-send {
|
|
687
|
+
width: 34px;
|
|
688
|
+
height: 34px;
|
|
689
|
+
color: var(--dsw-alias-label-on-color);
|
|
690
|
+
background: var(--dsw-alias-button-info-fill);
|
|
691
|
+
transform: translateY(-2px);
|
|
692
|
+
}
|
|
693
|
+
.dsh-btw-send:disabled[data-sending='true'] { opacity: 1; cursor: progress; }
|
|
694
|
+
@media (hover: hover) {
|
|
695
|
+
.dsh-btw-send:hover:not(:disabled) { color: var(--dsw-alias-label-on-color); background: var(--dsw-alias-button-info-hover); }
|
|
696
|
+
}
|
|
697
|
+
.dsh-btw-sr {
|
|
698
|
+
position: absolute;
|
|
699
|
+
width: 1px;
|
|
700
|
+
height: 1px;
|
|
701
|
+
padding: 0;
|
|
702
|
+
border: 0;
|
|
703
|
+
overflow: hidden;
|
|
704
|
+
clip-path: inset(50%);
|
|
705
|
+
white-space: nowrap;
|
|
706
|
+
}
|
|
707
|
+
`;
|
|
708
|
+
var emptyRecord = Object.freeze({});
|
|
709
|
+
var emptySnapshot = Object.freeze({ cards: emptyRecord, pane: null, notice: emptyRecord });
|
|
710
|
+
var noSubscribe = () => () => {
|
|
711
|
+
};
|
|
712
|
+
var noImage = async () => void 0;
|
|
713
|
+
var emptyContent = Object.freeze([]);
|
|
714
|
+
var alwaysNearBottom = 42;
|
|
715
|
+
function orderHistory(rows) {
|
|
716
|
+
return [...rows].sort((left, right) => left.createdAt - right.createdAt || left.id.localeCompare(right.id));
|
|
717
|
+
}
|
|
718
|
+
function isRunning(status2) {
|
|
719
|
+
return status2 === "generating" || status2 === "running" || status2 === "streaming" || status2 === "pending";
|
|
720
|
+
}
|
|
721
|
+
function summarizeUsage(turns) {
|
|
722
|
+
let uncached = 0;
|
|
723
|
+
let cacheRead = 0;
|
|
724
|
+
let cacheWrite = 0;
|
|
725
|
+
let output = 0;
|
|
726
|
+
let totalOnly = 0;
|
|
727
|
+
for (const { usage, status: status2 } of turns) {
|
|
728
|
+
if (!usage || isRunning(status2)) continue;
|
|
729
|
+
uncached += usage.inputTokens ?? 0;
|
|
730
|
+
cacheRead += usage.cacheReadTokens ?? 0;
|
|
731
|
+
cacheWrite += usage.cacheWriteTokens ?? 0;
|
|
732
|
+
output += usage.outputTokens ?? 0;
|
|
733
|
+
if (usage.inputTokens === void 0 && usage.cacheReadTokens === void 0 && usage.cacheWriteTokens === void 0 && usage.outputTokens === void 0) {
|
|
734
|
+
totalOnly += usage.totalTokens ?? 0;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
const prompt = uncached + cacheRead + cacheWrite;
|
|
738
|
+
return {
|
|
739
|
+
uncached,
|
|
740
|
+
cacheRead,
|
|
741
|
+
cacheWrite,
|
|
742
|
+
output,
|
|
743
|
+
total: prompt + output + totalOnly,
|
|
744
|
+
cacheRatio: prompt > 0 ? cacheRead / prompt : null
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
function formatTokenCount(value) {
|
|
748
|
+
const format = (amount) => String(amount >= 100 ? Math.round(amount) : Math.round(amount * 10) / 10);
|
|
749
|
+
if (value < 1e3) return String(value);
|
|
750
|
+
if (value < 1e6) return `${format(value / 1e3)}K`;
|
|
751
|
+
return `${format(value / 1e6)}M`;
|
|
752
|
+
}
|
|
753
|
+
function contextReading(context) {
|
|
754
|
+
const { estimatedTokens: used, contextWindow } = context ?? {};
|
|
755
|
+
if (!Number.isSafeInteger(contextWindow) || contextWindow <= 0 || !Number.isSafeInteger(used) || used < 0) return null;
|
|
756
|
+
return { used, contextWindow, percent: Math.min(100, Math.round(used / contextWindow * 100)) };
|
|
757
|
+
}
|
|
758
|
+
function formatMessageTime(value, language, now = Date.now()) {
|
|
759
|
+
if (value === void 0 || value === null) return null;
|
|
760
|
+
const date = new Date(value);
|
|
761
|
+
if (!Number.isFinite(date.getTime())) return null;
|
|
762
|
+
const today = new Date(now);
|
|
763
|
+
const pad = (number) => String(number).padStart(2, "0");
|
|
764
|
+
const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
765
|
+
if (date.toDateString() === today.toDateString()) return clock;
|
|
766
|
+
const year = date.getFullYear();
|
|
767
|
+
const month = date.getMonth() + 1;
|
|
768
|
+
const day = date.getDate();
|
|
769
|
+
const sameYear = year === today.getFullYear();
|
|
770
|
+
const label = language?.startsWith("zh") ? `${sameYear ? "" : `${year}年`}${month}月${day}日` : sameYear ? `${month}/${day}` : `${year}-${month}-${day}`;
|
|
771
|
+
return `${label} ${clock}`;
|
|
772
|
+
}
|
|
773
|
+
function formatCacheRatio(ratio, language, decimals = 0) {
|
|
774
|
+
if (ratio === null) return null;
|
|
775
|
+
const format = (digits) => new Intl.NumberFormat(language || void 0, { style: "percent", maximumFractionDigits: digits }).format(ratio);
|
|
776
|
+
const rounded = format(decimals);
|
|
777
|
+
if (ratio === 1 || rounded !== new Intl.NumberFormat(language || void 0, { style: "percent" }).format(1)) return rounded;
|
|
778
|
+
return format(Math.min(15, Math.max(decimals + 1, Math.ceil(-Math.log10((1 - ratio) * 100)))));
|
|
779
|
+
}
|
|
780
|
+
function turnStatus(status2) {
|
|
781
|
+
if (status2 === "interrupted" || status2 === "cancelled") return "interrupted";
|
|
782
|
+
if (status2 === "error" || status2 === "failed") return "replyFailed";
|
|
783
|
+
return "";
|
|
784
|
+
}
|
|
785
|
+
function acceptDetail(previous, next) {
|
|
786
|
+
if (!next || !Array.isArray(next.turns)) return previous;
|
|
787
|
+
if (previous && next.version < previous.version) return previous;
|
|
788
|
+
return next;
|
|
789
|
+
}
|
|
790
|
+
function formatTime(value, language) {
|
|
791
|
+
if (value === void 0 || value === null) return null;
|
|
792
|
+
const date = new Date(value);
|
|
793
|
+
if (!Number.isFinite(date.getTime())) return null;
|
|
794
|
+
const full = { dateStyle: "medium", timeStyle: "short" };
|
|
795
|
+
const short = { month: "numeric", day: "numeric", hour: "numeric", minute: "2-digit" };
|
|
796
|
+
const options = date.getFullYear() === (/* @__PURE__ */ new Date()).getFullYear() ? short : full;
|
|
797
|
+
return {
|
|
798
|
+
dateTime: date.toISOString(),
|
|
799
|
+
text: date.toLocaleString(language || void 0, options),
|
|
800
|
+
title: date.toLocaleString(language || void 0, full)
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
function releaseCapture(active) {
|
|
804
|
+
if (!active) return;
|
|
805
|
+
clearTimeout(active.timer);
|
|
806
|
+
const { recorder, stream } = active;
|
|
807
|
+
if (recorder?.state === "recording") {
|
|
808
|
+
try {
|
|
809
|
+
recorder.stop();
|
|
810
|
+
} catch {
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
stream?.getTracks().forEach((track) => track.stop());
|
|
814
|
+
}
|
|
815
|
+
async function transcodeWav(blob, maxDurationSeconds, signal) {
|
|
816
|
+
const rate = 16e3;
|
|
817
|
+
const context = new OfflineAudioContext(1, 1, rate);
|
|
818
|
+
const decoded = await context.decodeAudioData(await blob.arrayBuffer());
|
|
819
|
+
signal.throwIfAborted();
|
|
820
|
+
const count = Math.min(decoded.length, Math.floor(rate * maxDurationSeconds));
|
|
821
|
+
if (!count) throw new Error("empty");
|
|
822
|
+
const offline = new OfflineAudioContext(1, count, rate);
|
|
823
|
+
const source = offline.createBufferSource();
|
|
824
|
+
source.buffer = decoded;
|
|
825
|
+
source.connect(offline.destination);
|
|
826
|
+
source.start();
|
|
827
|
+
const mono = (await offline.startRendering()).getChannelData(0);
|
|
828
|
+
signal.throwIfAborted();
|
|
829
|
+
const bytes = new Uint8Array(44 + mono.length * 2);
|
|
830
|
+
const view = new DataView(bytes.buffer);
|
|
831
|
+
const writeAscii = (offset, text) => {
|
|
832
|
+
for (let index = 0; index < text.length; index += 1) bytes[offset + index] = text.charCodeAt(index);
|
|
833
|
+
};
|
|
834
|
+
writeAscii(0, "RIFF");
|
|
835
|
+
view.setUint32(4, bytes.length - 8, true);
|
|
836
|
+
writeAscii(8, "WAVEfmt ");
|
|
837
|
+
view.setUint32(16, 16, true);
|
|
838
|
+
view.setUint16(20, 1, true);
|
|
839
|
+
view.setUint16(22, 1, true);
|
|
840
|
+
view.setUint32(24, rate, true);
|
|
841
|
+
view.setUint32(28, rate * 2, true);
|
|
842
|
+
view.setUint16(32, 2, true);
|
|
843
|
+
view.setUint16(34, 16, true);
|
|
844
|
+
writeAscii(36, "data");
|
|
845
|
+
view.setUint32(40, mono.length * 2, true);
|
|
846
|
+
for (let index = 0; index < mono.length; index += 1) {
|
|
847
|
+
const sample = Math.max(-1, Math.min(1, mono[index]));
|
|
848
|
+
view.setInt16(44 + index * 2, Math.round(sample * (sample < 0 ? 32768 : 32767)), true);
|
|
849
|
+
}
|
|
850
|
+
return new Blob([bytes], { type: "audio/wav" });
|
|
851
|
+
}
|
|
852
|
+
var sideQuestionPaths = [
|
|
853
|
+
"M15.02 19.52c-2.341 .736 -5 .606 -7.32 -.52l-4.7 1l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c1.649 1.407 2.575 3.253 2.742 5.152",
|
|
854
|
+
"M19 22v.01",
|
|
855
|
+
"M19 19a2.003 2.003 0 0 0 .914 -3.782a1.98 1.98 0 0 0 -2.414 .483"
|
|
856
|
+
];
|
|
857
|
+
var glyphs = {
|
|
858
|
+
up: ["chevron-up-outline-regular", 14],
|
|
859
|
+
down: ["chevron-down-outline-regular", 14],
|
|
860
|
+
right: ["chevron-right-outline-regular", 14],
|
|
861
|
+
back: ["chevron-left-outline-regular", 14],
|
|
862
|
+
close: ["close-outline-regular", 14],
|
|
863
|
+
open: ["share-outline-regular", 14],
|
|
864
|
+
copy: ["copy-outline-regular", 14],
|
|
865
|
+
check: ["check-outline-regular", 14],
|
|
866
|
+
mic: ["microphone-outline-regular", 18],
|
|
867
|
+
stop: ["stop-fill-regular", 14],
|
|
868
|
+
send: ["send-outline-medium", 16],
|
|
869
|
+
database: ["database-outline-regular", 14],
|
|
870
|
+
gauge: ["gauge-outline-regular", 14]
|
|
871
|
+
};
|
|
872
|
+
function pinSpinner(element) {
|
|
873
|
+
for (const animation of element.getAnimations?.({ subtree: true }) ?? []) animation.startTime = 0;
|
|
874
|
+
}
|
|
875
|
+
function syncSpinner(element) {
|
|
876
|
+
if (!element) return;
|
|
877
|
+
pinSpinner(element);
|
|
878
|
+
element.addEventListener("animationstart", restartSpinner);
|
|
879
|
+
}
|
|
880
|
+
function restartSpinner(event) {
|
|
881
|
+
pinSpinner(event.currentTarget);
|
|
882
|
+
}
|
|
883
|
+
function createViews(React) {
|
|
884
|
+
const {
|
|
885
|
+
Fragment,
|
|
886
|
+
createElement: h,
|
|
887
|
+
useCallback,
|
|
888
|
+
useEffect,
|
|
889
|
+
useId,
|
|
890
|
+
useLayoutEffect,
|
|
891
|
+
useMemo,
|
|
892
|
+
useRef,
|
|
893
|
+
useState,
|
|
894
|
+
useSyncExternalStore
|
|
895
|
+
} = React;
|
|
896
|
+
function useSnapshot(controller) {
|
|
897
|
+
const { subscribe, getSnapshot } = useMemo(() => controller ? {
|
|
898
|
+
subscribe: (listener) => controller.subscribe(listener),
|
|
899
|
+
getSnapshot: () => controller.getSnapshot()
|
|
900
|
+
} : { subscribe: noSubscribe, getSnapshot: () => emptySnapshot }, [controller]);
|
|
901
|
+
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
902
|
+
}
|
|
903
|
+
function SideQuestionIcon({ className, size = 14 }) {
|
|
904
|
+
return h("svg", {
|
|
905
|
+
className,
|
|
906
|
+
width: size,
|
|
907
|
+
height: size,
|
|
908
|
+
viewBox: "0 0 24 24",
|
|
909
|
+
fill: "none",
|
|
910
|
+
stroke: "currentColor",
|
|
911
|
+
strokeWidth: 2,
|
|
912
|
+
strokeLinecap: "round",
|
|
913
|
+
strokeLinejoin: "round",
|
|
914
|
+
"aria-hidden": true,
|
|
915
|
+
focusable: false
|
|
916
|
+
}, sideQuestionPaths.map((path) => h("path", { key: path, d: path })));
|
|
917
|
+
}
|
|
918
|
+
function WaitingSpinner() {
|
|
919
|
+
return h("svg", {
|
|
920
|
+
ref: syncSpinner,
|
|
921
|
+
className: "dsh-btw-waiting-spinner",
|
|
922
|
+
"data-state": "ongoing",
|
|
923
|
+
width: 14,
|
|
924
|
+
height: 14,
|
|
925
|
+
viewBox: "0 0 24 24",
|
|
926
|
+
"aria-hidden": true
|
|
927
|
+
}, h(
|
|
928
|
+
"g",
|
|
929
|
+
{ className: "dsh-btw-spinner-motion" },
|
|
930
|
+
h("circle", { className: "dsh-btw-spinner-track", cx: 12, cy: 12, r: 9.5 }),
|
|
931
|
+
h("circle", { className: "dsh-btw-spinner-arc", cx: 12, cy: 12, r: 9.5 })
|
|
932
|
+
));
|
|
933
|
+
}
|
|
934
|
+
function Icon({ name, className, size }) {
|
|
935
|
+
const [symbol, edge] = glyphs[name];
|
|
936
|
+
return h("svg", {
|
|
937
|
+
className,
|
|
938
|
+
width: size ?? edge,
|
|
939
|
+
height: size ?? edge,
|
|
940
|
+
"data-icon": symbol,
|
|
941
|
+
"aria-hidden": true,
|
|
942
|
+
focusable: false
|
|
943
|
+
}, h("use", { href: `#dsw-icon-${symbol}` }));
|
|
944
|
+
}
|
|
945
|
+
function IconButton({ icon, label, className, children, ...props }) {
|
|
946
|
+
return h("button", {
|
|
947
|
+
type: "button",
|
|
948
|
+
className: `dsh-btw-icon-button${className ? ` ${className}` : ""}`,
|
|
949
|
+
"aria-label": label,
|
|
950
|
+
title: label,
|
|
951
|
+
...props
|
|
952
|
+
}, children ?? h(Icon, { name: icon }));
|
|
953
|
+
}
|
|
954
|
+
function Time({ value, language, message = false }) {
|
|
955
|
+
const date = formatTime(value, language);
|
|
956
|
+
if (!date) return null;
|
|
957
|
+
return h(
|
|
958
|
+
"time",
|
|
959
|
+
{ className: "dsh-btw-time", dateTime: date.dateTime, title: date.title },
|
|
960
|
+
message ? formatMessageTime(value, language) : date.text
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
function Feedback({ text, onRetry, t, error = false, inline = false, id: id2 }) {
|
|
964
|
+
return h(
|
|
965
|
+
"div",
|
|
966
|
+
{ id: id2, className: `dsh-btw-feedback${error ? " dsh-btw-failure" : ""}${inline ? " dsh-btw-turn-feedback" : ""}`, role: "status" },
|
|
967
|
+
text,
|
|
968
|
+
onRetry && h("button", { type: "button", className: "dsh-btw-retry", onClick: onRetry }, t("retry"))
|
|
969
|
+
);
|
|
970
|
+
}
|
|
971
|
+
function Markdown({ text, running, renderFactorySlot }) {
|
|
972
|
+
const fallback = h("div", { className: "dsh-btw-plain" }, text);
|
|
973
|
+
return renderFactorySlot?.("conversation.chat.reasoning.content", { text, running }, { fallback }) ?? fallback;
|
|
974
|
+
}
|
|
975
|
+
function UserMessage({ turn, t, language, renderFactorySlot, actionsReveal }) {
|
|
976
|
+
const text = turn.question;
|
|
977
|
+
const fallback = h("div", { className: "dsh-btw-plain dsh-btw-user-fallback" }, text);
|
|
978
|
+
const bubble = renderFactorySlot?.("conversation.chat.user.content", {
|
|
979
|
+
content: { text, attachments: emptyContent, extraBlocks: emptyContent },
|
|
980
|
+
loadImage: noImage,
|
|
981
|
+
facts: emptyRecord,
|
|
982
|
+
interactive: false
|
|
983
|
+
}, { fallback }) ?? fallback;
|
|
984
|
+
return h(
|
|
985
|
+
"div",
|
|
986
|
+
{
|
|
987
|
+
className: "dsh-btw-message-user",
|
|
988
|
+
role: "group",
|
|
989
|
+
"aria-label": t("userMessage"),
|
|
990
|
+
"data-btw-actions-reveal": actionsReveal
|
|
991
|
+
},
|
|
992
|
+
bubble,
|
|
993
|
+
h(
|
|
994
|
+
"div",
|
|
995
|
+
{ className: "dsh-btw-message-actions" },
|
|
996
|
+
h(Time, { value: turn.createdAt, language, message: true }),
|
|
997
|
+
h(CopyMessage, { text, t })
|
|
998
|
+
)
|
|
999
|
+
);
|
|
1000
|
+
}
|
|
1001
|
+
function CopyMessage({ text, t }) {
|
|
1002
|
+
const [result, setResult] = useState("");
|
|
1003
|
+
const live = useRef(false);
|
|
1004
|
+
const timeout = useRef();
|
|
1005
|
+
useEffect(() => {
|
|
1006
|
+
live.current = true;
|
|
1007
|
+
return () => {
|
|
1008
|
+
live.current = false;
|
|
1009
|
+
clearTimeout(timeout.current);
|
|
1010
|
+
};
|
|
1011
|
+
}, []);
|
|
1012
|
+
async function copy() {
|
|
1013
|
+
let next = "copied";
|
|
1014
|
+
try {
|
|
1015
|
+
await navigator.clipboard.writeText(text);
|
|
1016
|
+
} catch {
|
|
1017
|
+
next = "copyFailed";
|
|
1018
|
+
}
|
|
1019
|
+
if (!live.current) return;
|
|
1020
|
+
clearTimeout(timeout.current);
|
|
1021
|
+
setResult(next);
|
|
1022
|
+
timeout.current = setTimeout(() => setResult(""), 1800);
|
|
1023
|
+
}
|
|
1024
|
+
return h(
|
|
1025
|
+
Fragment,
|
|
1026
|
+
null,
|
|
1027
|
+
h(IconButton, { icon: result === "copied" ? "check" : "copy", label: t(result || "copy"), onClick: copy }),
|
|
1028
|
+
result && h("span", { className: "dsh-btw-sr", role: "status" }, t(result))
|
|
1029
|
+
);
|
|
1030
|
+
}
|
|
1031
|
+
function ReplyActions({ turn, t, language, performanceUsage }) {
|
|
1032
|
+
const [open, setOpen] = useState(false);
|
|
1033
|
+
const trigger = useRef(null);
|
|
1034
|
+
const id2 = useId();
|
|
1035
|
+
const { uncached, cacheRead, cacheWrite, output, total, cacheRatio } = summarizeUsage([turn]);
|
|
1036
|
+
const enabled = performanceUsage !== "compact" && total > 0;
|
|
1037
|
+
const number = new Intl.NumberFormat(language || void 0);
|
|
1038
|
+
const reading = t("auditSpent", { total: `${formatTokenCount(total)} tok` });
|
|
1039
|
+
const cache = formatCacheRatio(cacheRatio, language, 1);
|
|
1040
|
+
const rows = [[t("auditTotal"), number.format(total)]];
|
|
1041
|
+
if (cache !== null) rows.push([t("auditCacheHit"), cache]);
|
|
1042
|
+
if (turn.usage?.inputTokens !== void 0) rows.push([t("auditInput"), number.format(uncached)]);
|
|
1043
|
+
if (turn.usage?.cacheReadTokens !== void 0) rows.push([t("auditCacheRead"), number.format(cacheRead)]);
|
|
1044
|
+
if (turn.usage?.cacheWriteTokens !== void 0) rows.push([t("auditCacheWrite"), number.format(cacheWrite)]);
|
|
1045
|
+
if (turn.usage?.outputTokens !== void 0) rows.push([t("auditOutput"), number.format(output)]);
|
|
1046
|
+
if (turn.usage?.reasoningTokens !== void 0) rows.push([t("auditReasoning"), number.format(turn.usage.reasoningTokens)]);
|
|
1047
|
+
useEffect(() => {
|
|
1048
|
+
if (!enabled) setOpen(false);
|
|
1049
|
+
}, [enabled]);
|
|
1050
|
+
return h(
|
|
1051
|
+
"div",
|
|
1052
|
+
{ onKeyDown: (event) => {
|
|
1053
|
+
if (event.key === "Escape" && open) {
|
|
1054
|
+
event.stopPropagation();
|
|
1055
|
+
setOpen(false);
|
|
1056
|
+
trigger.current?.focus();
|
|
1057
|
+
}
|
|
1058
|
+
} },
|
|
1059
|
+
h(
|
|
1060
|
+
"div",
|
|
1061
|
+
{ className: "dsh-btw-message-actions" },
|
|
1062
|
+
h(CopyMessage, { text: turn.reply, t }),
|
|
1063
|
+
h(
|
|
1064
|
+
"span",
|
|
1065
|
+
{ className: "dsh-btw-message-end-info" },
|
|
1066
|
+
enabled && h(
|
|
1067
|
+
"button",
|
|
1068
|
+
{
|
|
1069
|
+
type: "button",
|
|
1070
|
+
className: "dsh-btw-turn-usage",
|
|
1071
|
+
ref: trigger,
|
|
1072
|
+
title: reading,
|
|
1073
|
+
"aria-label": `${t("auditTurn")} · ${reading}`,
|
|
1074
|
+
"aria-expanded": open,
|
|
1075
|
+
"aria-controls": open ? id2 : void 0,
|
|
1076
|
+
onClick: () => setOpen((value) => !value)
|
|
1077
|
+
},
|
|
1078
|
+
h(Icon, { name: "database" }),
|
|
1079
|
+
h("span", null, reading)
|
|
1080
|
+
),
|
|
1081
|
+
h(Time, { value: turn.finishedAt, language, message: true })
|
|
1082
|
+
)
|
|
1083
|
+
),
|
|
1084
|
+
enabled && open && h(
|
|
1085
|
+
"div",
|
|
1086
|
+
{ id: id2, className: "dsh-btw-turn-usage-panel" },
|
|
1087
|
+
h("dl", { className: "dsh-btw-stat-details" }, rows.map(([title, value]) => h(
|
|
1088
|
+
Fragment,
|
|
1089
|
+
{ key: title },
|
|
1090
|
+
h("dt", null, title),
|
|
1091
|
+
h("dd", null, value)
|
|
1092
|
+
)))
|
|
1093
|
+
)
|
|
1094
|
+
);
|
|
1095
|
+
}
|
|
1096
|
+
function Reply({ turn, t, renderFactorySlot, inline = false, language, performanceUsage, streamFailed = false, overflowNotice }) {
|
|
1097
|
+
const running = !turn || isRunning(turn.status);
|
|
1098
|
+
const text = turn?.reply ?? "";
|
|
1099
|
+
const state = turnStatus(turn?.status);
|
|
1100
|
+
if (running && !text.trim()) {
|
|
1101
|
+
if (streamFailed) return null;
|
|
1102
|
+
return h(
|
|
1103
|
+
"div",
|
|
1104
|
+
{ className: "dsh-btw-waiting", role: "status" },
|
|
1105
|
+
h(WaitingSpinner),
|
|
1106
|
+
h("span", null, t("waiting"))
|
|
1107
|
+
);
|
|
1108
|
+
}
|
|
1109
|
+
const overflow = turn?.error === CONTEXT_OVERFLOW;
|
|
1110
|
+
const failure = overflow ? "contextOverflow" : state || (!text.trim() ? "replyFailed" : "");
|
|
1111
|
+
return h(
|
|
1112
|
+
Fragment,
|
|
1113
|
+
null,
|
|
1114
|
+
text && h(Markdown, { text, running, renderFactorySlot }),
|
|
1115
|
+
failure && h(Feedback, {
|
|
1116
|
+
id: overflow ? overflowNotice : void 0,
|
|
1117
|
+
text: t(failure),
|
|
1118
|
+
t,
|
|
1119
|
+
error: overflow || failure === "replyFailed",
|
|
1120
|
+
inline: true
|
|
1121
|
+
}),
|
|
1122
|
+
turn?.saveError && h(Feedback, { text: t("archiveWriteFailed"), t, error: true, inline: true }),
|
|
1123
|
+
!inline && !running && text && h(ReplyActions, { turn, t, language, performanceUsage })
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
function DockCard({ detail: detail2, controller, sessionId, t, renderFactorySlot }) {
|
|
1127
|
+
const [expanded, setExpanded] = useState(true);
|
|
1128
|
+
const [liveDetail, setLiveDetail] = useState(detail2);
|
|
1129
|
+
const [failed, setFailed] = useState(false);
|
|
1130
|
+
const [sidebarFailed, setSidebarFailed] = useState(false);
|
|
1131
|
+
const [retry, setRetry] = useState(0);
|
|
1132
|
+
const contentId = useId();
|
|
1133
|
+
const id2 = detail2.id;
|
|
1134
|
+
const current = acceptDetail(liveDetail, detail2.version > liveDetail.version ? detail2 : null);
|
|
1135
|
+
const firstTurn = current.turns[0];
|
|
1136
|
+
const running = isRunning(firstTurn?.status);
|
|
1137
|
+
useEffect(() => {
|
|
1138
|
+
if (!running) return void 0;
|
|
1139
|
+
let mounted = true;
|
|
1140
|
+
let close;
|
|
1141
|
+
setFailed(false);
|
|
1142
|
+
try {
|
|
1143
|
+
close = controller.watch(sessionId, id2, (next) => {
|
|
1144
|
+
if (mounted && next?.sessionId === sessionId && next.id === id2) {
|
|
1145
|
+
setLiveDetail((previous) => acceptDetail(previous, next));
|
|
1146
|
+
}
|
|
1147
|
+
}, () => {
|
|
1148
|
+
if (mounted) setFailed(true);
|
|
1149
|
+
});
|
|
1150
|
+
} catch {
|
|
1151
|
+
setFailed(true);
|
|
1152
|
+
}
|
|
1153
|
+
return () => {
|
|
1154
|
+
mounted = false;
|
|
1155
|
+
close?.();
|
|
1156
|
+
};
|
|
1157
|
+
}, [controller, id2, retry, running, sessionId]);
|
|
1158
|
+
return h(
|
|
1159
|
+
"article",
|
|
1160
|
+
{ className: "dsh-btw-card", "aria-label": t("title") },
|
|
1161
|
+
h(
|
|
1162
|
+
"header",
|
|
1163
|
+
{ className: "dsh-btw-card-bar" },
|
|
1164
|
+
h(SideQuestionIcon, { className: "dsh-btw-mark" }),
|
|
1165
|
+
h("span", { className: "dsh-btw-title-label" }, t("title")),
|
|
1166
|
+
h("div", { className: "dsh-btw-question", title: detail2.question }, detail2.question),
|
|
1167
|
+
h(
|
|
1168
|
+
"div",
|
|
1169
|
+
{ className: "dsh-btw-actions" },
|
|
1170
|
+
h(IconButton, {
|
|
1171
|
+
icon: expanded ? "up" : "down",
|
|
1172
|
+
label: t(expanded ? "collapse" : "expand"),
|
|
1173
|
+
"aria-expanded": expanded,
|
|
1174
|
+
"aria-controls": contentId,
|
|
1175
|
+
onClick: () => setExpanded((value) => !value)
|
|
1176
|
+
}),
|
|
1177
|
+
h(IconButton, { icon: "open", label: t("openSidebar"), onClick: () => {
|
|
1178
|
+
try {
|
|
1179
|
+
setSidebarFailed(controller.openDetail(sessionId, id2) === false);
|
|
1180
|
+
} catch {
|
|
1181
|
+
setSidebarFailed(true);
|
|
1182
|
+
}
|
|
1183
|
+
} }),
|
|
1184
|
+
h(IconButton, { icon: "close", label: t("dismiss"), onClick: () => controller.dismiss(sessionId) })
|
|
1185
|
+
)
|
|
1186
|
+
),
|
|
1187
|
+
sidebarFailed && h(Feedback, { text: t("sidebarUnavailable"), t, error: true }),
|
|
1188
|
+
expanded && h("div", { className: "dsh-btw-inline-rule", "aria-hidden": true }),
|
|
1189
|
+
h("div", { id: contentId, hidden: !expanded, className: expanded ? "dsh-btw-inline-reply" : void 0 }, expanded && h(
|
|
1190
|
+
Fragment,
|
|
1191
|
+
null,
|
|
1192
|
+
firstTurn && h(Reply, { turn: firstTurn, t, renderFactorySlot, inline: true, streamFailed: failed }),
|
|
1193
|
+
running && failed && h(Feedback, {
|
|
1194
|
+
text: t("streamFailed"),
|
|
1195
|
+
t,
|
|
1196
|
+
inline: true,
|
|
1197
|
+
error: true,
|
|
1198
|
+
onRetry: () => setRetry((value) => value + 1)
|
|
1199
|
+
})
|
|
1200
|
+
))
|
|
1201
|
+
);
|
|
1202
|
+
}
|
|
1203
|
+
function Dock({ controller, sessionId, t, renderFactorySlot }) {
|
|
1204
|
+
const snapshot = useSnapshot(controller);
|
|
1205
|
+
useEffect(() => {
|
|
1206
|
+
void controller.restoreCard(sessionId);
|
|
1207
|
+
}, [controller, sessionId]);
|
|
1208
|
+
const card = snapshot.cards?.[sessionId];
|
|
1209
|
+
const notice = snapshot.notice?.[sessionId];
|
|
1210
|
+
if (!sessionId || !card && !notice) return null;
|
|
1211
|
+
return h(
|
|
1212
|
+
"div",
|
|
1213
|
+
{ className: "dsh-btw-dock" },
|
|
1214
|
+
h("style", null, styles),
|
|
1215
|
+
notice && h(Feedback, { text: t(notice), t, error: true }),
|
|
1216
|
+
card && h(DockCard, { key: card.id, detail: card, controller, sessionId, t, renderFactorySlot })
|
|
1217
|
+
);
|
|
1218
|
+
}
|
|
1219
|
+
function List({ controller, sessionId, t, language, focusId, listRevision }) {
|
|
1220
|
+
const [load, setLoad] = useState({});
|
|
1221
|
+
const [retry, setRetry] = useState(0);
|
|
1222
|
+
const scroller = useRef(null);
|
|
1223
|
+
const positioned = useRef(false);
|
|
1224
|
+
const focusTarget = useRef(null);
|
|
1225
|
+
const scopeId = useId();
|
|
1226
|
+
useEffect(() => {
|
|
1227
|
+
let alive = true;
|
|
1228
|
+
Promise.resolve().then(() => controller.call("list", sessionId)).then((rows) => {
|
|
1229
|
+
if (alive) setLoad({ rows: orderHistory(rows ?? []) });
|
|
1230
|
+
}, () => {
|
|
1231
|
+
if (alive) setLoad({ failed: true });
|
|
1232
|
+
});
|
|
1233
|
+
return () => {
|
|
1234
|
+
alive = false;
|
|
1235
|
+
};
|
|
1236
|
+
}, [controller, sessionId, retry, listRevision]);
|
|
1237
|
+
useLayoutEffect(() => {
|
|
1238
|
+
const list = scroller.current;
|
|
1239
|
+
if (!load.rows || !list || positioned.current) return;
|
|
1240
|
+
positioned.current = true;
|
|
1241
|
+
list.scrollTop = list.scrollHeight;
|
|
1242
|
+
const previousRow = focusTarget.current;
|
|
1243
|
+
if (focusId && previousRow) {
|
|
1244
|
+
const rowBounds = previousRow.getBoundingClientRect();
|
|
1245
|
+
const listBounds = list.getBoundingClientRect();
|
|
1246
|
+
const visible = rowBounds.top >= listBounds.top && rowBounds.bottom <= listBounds.bottom;
|
|
1247
|
+
const target = visible ? previousRow : list.querySelector("li:last-child > button");
|
|
1248
|
+
target?.focus({ preventScroll: true });
|
|
1249
|
+
}
|
|
1250
|
+
}, [focusId, load.rows]);
|
|
1251
|
+
const reload = () => {
|
|
1252
|
+
setLoad({});
|
|
1253
|
+
setRetry((value) => value + 1);
|
|
1254
|
+
};
|
|
1255
|
+
return h(
|
|
1256
|
+
Fragment,
|
|
1257
|
+
null,
|
|
1258
|
+
h(
|
|
1259
|
+
"header",
|
|
1260
|
+
{ className: "dsh-btw-bar" },
|
|
1261
|
+
h(SideQuestionIcon, { className: "dsh-btw-mark" }),
|
|
1262
|
+
h("h2", { id: scopeId, className: "dsh-btw-bar-title" }, t("listTitle"))
|
|
1263
|
+
),
|
|
1264
|
+
h(
|
|
1265
|
+
"section",
|
|
1266
|
+
{ className: "dsh-btw-list", ref: scroller, "aria-labelledby": scopeId },
|
|
1267
|
+
load.failed ? h(Feedback, { text: t("loadFailed"), t, onRetry: reload, error: true }) : !load.rows ? h(Feedback, { text: t("loading"), t }) : load.rows.length === 0 ? h(Feedback, { text: t("emptyList"), t }) : h("ul", { className: "dsh-btw-history" }, load.rows.map((row) => h("li", { key: row.id }, h(
|
|
1268
|
+
"button",
|
|
1269
|
+
{
|
|
1270
|
+
type: "button",
|
|
1271
|
+
className: "dsh-btw-row",
|
|
1272
|
+
title: row.question,
|
|
1273
|
+
ref: focusId === row.id ? focusTarget : null,
|
|
1274
|
+
onClick: () => controller.navigate(sessionId, row.id)
|
|
1275
|
+
},
|
|
1276
|
+
h("span", { className: "dsh-btw-row-text" }, row.question),
|
|
1277
|
+
h("span", { className: "dsh-btw-row-time" }, h(Time, { value: row.createdAt ?? row.updatedAt, language })),
|
|
1278
|
+
h(Icon, { name: "right" })
|
|
1279
|
+
))))
|
|
1280
|
+
)
|
|
1281
|
+
);
|
|
1282
|
+
}
|
|
1283
|
+
function useDetail({ controller, sessionId, id: id2, revision, reload }) {
|
|
1284
|
+
const [loaded, setLoaded] = useState(null);
|
|
1285
|
+
const [failure, setFailure] = useState("");
|
|
1286
|
+
const [contextSample, setContextSample] = useState(null);
|
|
1287
|
+
const detail2 = loaded?.revision === revision ? loaded.detail : void 0;
|
|
1288
|
+
const context = contextSample?.revision === revision ? contextSample.value : null;
|
|
1289
|
+
const turnIndex = detail2 ? detail2.turns.length - 1 : -1;
|
|
1290
|
+
const running = isRunning(detail2?.turns[turnIndex]?.status);
|
|
1291
|
+
useEffect(() => {
|
|
1292
|
+
let alive = true;
|
|
1293
|
+
setFailure("");
|
|
1294
|
+
Promise.resolve().then(() => controller.call("get", sessionId, id2)).then((next) => {
|
|
1295
|
+
if (!alive) return;
|
|
1296
|
+
if (next?.id === id2 && next.sessionId === sessionId) setLoaded({ detail: next, revision });
|
|
1297
|
+
else setFailure("missingThread");
|
|
1298
|
+
}, () => {
|
|
1299
|
+
if (alive) setFailure("loadFailed");
|
|
1300
|
+
});
|
|
1301
|
+
return () => {
|
|
1302
|
+
alive = false;
|
|
1303
|
+
};
|
|
1304
|
+
}, [controller, id2, revision, sessionId]);
|
|
1305
|
+
useEffect(() => {
|
|
1306
|
+
if (turnIndex < 0) return void 0;
|
|
1307
|
+
const request = new AbortController();
|
|
1308
|
+
Promise.resolve().then(() => controller.call("contextCapacity", sessionId, id2, request.signal)).then((result) => {
|
|
1309
|
+
if (!request.signal.aborted) setContextSample({ revision, value: result });
|
|
1310
|
+
}, () => {
|
|
1311
|
+
});
|
|
1312
|
+
return () => request.abort();
|
|
1313
|
+
}, [controller, id2, revision, running, sessionId, turnIndex]);
|
|
1314
|
+
useEffect(() => {
|
|
1315
|
+
if (!running) return void 0;
|
|
1316
|
+
return controller.watchReply(sessionId, id2, turnIndex, detail2.version, (update) => {
|
|
1317
|
+
setLoaded((previous) => previous?.revision === revision ? { ...previous, detail: applyReply(previous.detail, turnIndex, update) } : previous);
|
|
1318
|
+
}, () => setFailure("streamFailed"));
|
|
1319
|
+
}, [controller, id2, revision, running, sessionId, turnIndex]);
|
|
1320
|
+
function accept(receipt2) {
|
|
1321
|
+
const next = appendTurn(detail2, receipt2);
|
|
1322
|
+
if (next === detail2) {
|
|
1323
|
+
reload();
|
|
1324
|
+
return;
|
|
1325
|
+
}
|
|
1326
|
+
setFailure("");
|
|
1327
|
+
setLoaded({ detail: next, revision });
|
|
1328
|
+
}
|
|
1329
|
+
return { detail: detail2, context, failure, accept };
|
|
1330
|
+
}
|
|
1331
|
+
function Thread({ detail: detail2, renderFactorySlot, t, language, scrollRef, followRef, streamFailed, performanceUsage, overflowNotice }) {
|
|
1332
|
+
useLayoutEffect(() => {
|
|
1333
|
+
const thread = scrollRef.current;
|
|
1334
|
+
if (thread && followRef.current) thread.scrollTop = thread.scrollHeight;
|
|
1335
|
+
}, [detail2, followRef, scrollRef]);
|
|
1336
|
+
return h("div", {
|
|
1337
|
+
className: "dsh-btw-thread",
|
|
1338
|
+
ref: scrollRef,
|
|
1339
|
+
role: "region",
|
|
1340
|
+
"aria-label": t("history"),
|
|
1341
|
+
tabIndex: 0,
|
|
1342
|
+
onScroll: (event) => {
|
|
1343
|
+
const node = event.currentTarget;
|
|
1344
|
+
followRef.current = node.scrollHeight - node.scrollTop - node.clientHeight <= alwaysNearBottom;
|
|
1345
|
+
}
|
|
1346
|
+
}, detail2.turns.map((turn, index) => {
|
|
1347
|
+
const latest = index === detail2.turns.length - 1;
|
|
1348
|
+
return h(
|
|
1349
|
+
"div",
|
|
1350
|
+
{ className: "dsh-btw-turn", key: index },
|
|
1351
|
+
h(UserMessage, { turn, t, language, renderFactorySlot, actionsReveal: latest ? "always" : "hover" }),
|
|
1352
|
+
h(
|
|
1353
|
+
"div",
|
|
1354
|
+
{
|
|
1355
|
+
className: "dsh-btw-message-assistant",
|
|
1356
|
+
role: "group",
|
|
1357
|
+
"aria-label": t("assistantMessage"),
|
|
1358
|
+
"data-btw-actions-reveal": latest && turn.status === "completed" && turn.reply.trim() ? "always" : "hover"
|
|
1359
|
+
},
|
|
1360
|
+
h(Reply, {
|
|
1361
|
+
turn,
|
|
1362
|
+
renderFactorySlot,
|
|
1363
|
+
t,
|
|
1364
|
+
language,
|
|
1365
|
+
performanceUsage,
|
|
1366
|
+
streamFailed: streamFailed && latest,
|
|
1367
|
+
overflowNotice: latest ? overflowNotice : void 0
|
|
1368
|
+
})
|
|
1369
|
+
)
|
|
1370
|
+
);
|
|
1371
|
+
}));
|
|
1372
|
+
}
|
|
1373
|
+
function useDictation(enabled, controller, insert) {
|
|
1374
|
+
const active = useRef(null);
|
|
1375
|
+
const [phase, setPhase] = useState("");
|
|
1376
|
+
const stop = useCallback(() => {
|
|
1377
|
+
const capture = active.current;
|
|
1378
|
+
active.current = null;
|
|
1379
|
+
capture?.abort.abort();
|
|
1380
|
+
releaseCapture(capture);
|
|
1381
|
+
}, []);
|
|
1382
|
+
const cancel = useCallback(() => {
|
|
1383
|
+
stop();
|
|
1384
|
+
setPhase("");
|
|
1385
|
+
}, [stop]);
|
|
1386
|
+
useEffect(() => {
|
|
1387
|
+
if (!enabled) {
|
|
1388
|
+
cancel();
|
|
1389
|
+
return void 0;
|
|
1390
|
+
}
|
|
1391
|
+
const blur = () => {
|
|
1392
|
+
if (active.current?.phase === "micRecording") cancel();
|
|
1393
|
+
};
|
|
1394
|
+
const visibility = () => {
|
|
1395
|
+
if (document.hidden && active.current && active.current.phase !== "micTranscribing") cancel();
|
|
1396
|
+
};
|
|
1397
|
+
const escape = (event) => {
|
|
1398
|
+
if (event.key === "Escape" && active.current) {
|
|
1399
|
+
event.preventDefault();
|
|
1400
|
+
cancel();
|
|
1401
|
+
}
|
|
1402
|
+
};
|
|
1403
|
+
window.addEventListener("blur", blur);
|
|
1404
|
+
document.addEventListener("visibilitychange", visibility);
|
|
1405
|
+
document.addEventListener("keydown", escape);
|
|
1406
|
+
return () => {
|
|
1407
|
+
window.removeEventListener("blur", blur);
|
|
1408
|
+
document.removeEventListener("visibilitychange", visibility);
|
|
1409
|
+
document.removeEventListener("keydown", escape);
|
|
1410
|
+
stop();
|
|
1411
|
+
};
|
|
1412
|
+
}, [enabled, cancel, stop]);
|
|
1413
|
+
async function finish(capture) {
|
|
1414
|
+
if (active.current !== capture || capture.phase !== "micRecording") return;
|
|
1415
|
+
capture.phase = "micTranscribing";
|
|
1416
|
+
setPhase(capture.phase);
|
|
1417
|
+
clearTimeout(capture.timer);
|
|
1418
|
+
try {
|
|
1419
|
+
const blob = await new Promise((resolve, reject) => {
|
|
1420
|
+
const { recorder, abort } = capture;
|
|
1421
|
+
abort.signal.addEventListener("abort", () => reject(abort.signal.reason), { once: true });
|
|
1422
|
+
recorder.onstop = () => resolve(new Blob(capture.chunks, { type: recorder.mimeType }));
|
|
1423
|
+
recorder.onerror = reject;
|
|
1424
|
+
recorder.stop();
|
|
1425
|
+
});
|
|
1426
|
+
releaseCapture(capture);
|
|
1427
|
+
if (capture.abort.signal.aborted) return;
|
|
1428
|
+
if (!blob.size) {
|
|
1429
|
+
setPhase("micEmpty");
|
|
1430
|
+
return;
|
|
1431
|
+
}
|
|
1432
|
+
const wav = await transcodeWav(blob, capture.dictation.maxDurationSeconds, capture.abort.signal);
|
|
1433
|
+
const text = await capture.dictation.transcribe(wav, capture.abort.signal);
|
|
1434
|
+
if (active.current !== capture) return;
|
|
1435
|
+
if (typeof text === "string" && text.trim()) {
|
|
1436
|
+
insert(text, capture.selection);
|
|
1437
|
+
setPhase("");
|
|
1438
|
+
} else setPhase("micEmpty");
|
|
1439
|
+
} catch (failure) {
|
|
1440
|
+
if (active.current === capture) setPhase(failure?.code === "btw/recording-too-large" ? "micTooLarge" : "micFailed");
|
|
1441
|
+
} finally {
|
|
1442
|
+
if (active.current === capture) active.current = null;
|
|
1443
|
+
releaseCapture(capture);
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
async function toggle(selection) {
|
|
1447
|
+
if (!enabled) return;
|
|
1448
|
+
if (active.current) {
|
|
1449
|
+
if (active.current.phase === "micRecording") await finish(active.current);
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
const dictation = controller.beginDictation();
|
|
1453
|
+
if (!dictation) {
|
|
1454
|
+
setPhase("micFailed");
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
const capture = { abort: new AbortController(), chunks: [], selection, dictation, phase: "micRequesting" };
|
|
1458
|
+
active.current = capture;
|
|
1459
|
+
setPhase(capture.phase);
|
|
1460
|
+
try {
|
|
1461
|
+
capture.stream = await navigator.mediaDevices.getUserMedia(dictation.constraints);
|
|
1462
|
+
if (active.current !== capture) {
|
|
1463
|
+
releaseCapture(capture);
|
|
1464
|
+
return;
|
|
1465
|
+
}
|
|
1466
|
+
const interrupted = () => {
|
|
1467
|
+
if (active.current !== capture || capture.phase === "micTranscribing") return;
|
|
1468
|
+
stop();
|
|
1469
|
+
setPhase("micInterrupted");
|
|
1470
|
+
};
|
|
1471
|
+
for (const track of capture.stream.getTracks()) track.addEventListener("ended", interrupted, { signal: capture.abort.signal });
|
|
1472
|
+
const recorder = new MediaRecorder(capture.stream);
|
|
1473
|
+
capture.recorder = recorder;
|
|
1474
|
+
recorder.ondataavailable = (event) => {
|
|
1475
|
+
if (event.data.size && !capture.abort.signal.aborted) capture.chunks.push(event.data);
|
|
1476
|
+
};
|
|
1477
|
+
recorder.onerror = interrupted;
|
|
1478
|
+
recorder.onstop = interrupted;
|
|
1479
|
+
recorder.start();
|
|
1480
|
+
capture.phase = "micRecording";
|
|
1481
|
+
setPhase(capture.phase);
|
|
1482
|
+
capture.timer = setTimeout(() => {
|
|
1483
|
+
void finish(capture);
|
|
1484
|
+
}, capture.dictation.maxDurationSeconds * 1e3);
|
|
1485
|
+
} catch (failure) {
|
|
1486
|
+
if (active.current !== capture) {
|
|
1487
|
+
releaseCapture(capture);
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
stop();
|
|
1491
|
+
if (failure?.name === "NotAllowedError") setPhase("micPermission");
|
|
1492
|
+
else if (["NotFoundError", "OverconstrainedError"].includes(failure?.name)) setPhase("micMissing");
|
|
1493
|
+
else setPhase("micFailed");
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
return { toggle, phase, cancel };
|
|
1497
|
+
}
|
|
1498
|
+
function Composer({
|
|
1499
|
+
controller,
|
|
1500
|
+
sessionId,
|
|
1501
|
+
id: id2,
|
|
1502
|
+
t,
|
|
1503
|
+
busy,
|
|
1504
|
+
overflowed,
|
|
1505
|
+
overflowNotice,
|
|
1506
|
+
dictationAvailable,
|
|
1507
|
+
speechMounted,
|
|
1508
|
+
speechSettings,
|
|
1509
|
+
onSent
|
|
1510
|
+
}) {
|
|
1511
|
+
const [draft, setDraft] = useState("");
|
|
1512
|
+
const [saving, setSaving] = useState(false);
|
|
1513
|
+
const [error, setError] = useState("");
|
|
1514
|
+
const [micHelp, setMicHelp] = useState("");
|
|
1515
|
+
const [retainedTranscript, setRetainedTranscript] = useState("");
|
|
1516
|
+
const input = useRef(null);
|
|
1517
|
+
const form = useRef(null);
|
|
1518
|
+
const composing = useRef(false);
|
|
1519
|
+
const pendingTranscript = useRef(null);
|
|
1520
|
+
const selectionAfterInsert = useRef(null);
|
|
1521
|
+
const draftRevision = useRef(0);
|
|
1522
|
+
const submitting = useRef(false);
|
|
1523
|
+
const live = useRef(false);
|
|
1524
|
+
const inputId = useId();
|
|
1525
|
+
useEffect(() => {
|
|
1526
|
+
live.current = true;
|
|
1527
|
+
return () => {
|
|
1528
|
+
live.current = false;
|
|
1529
|
+
};
|
|
1530
|
+
}, []);
|
|
1531
|
+
function insertSpeech(text, selection) {
|
|
1532
|
+
const node = input.current;
|
|
1533
|
+
if (!node || node.disabled) return;
|
|
1534
|
+
if (composing.current) {
|
|
1535
|
+
pendingTranscript.current = { text, selection };
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
if (selection.revision !== draftRevision.current) {
|
|
1539
|
+
setRetainedTranscript(text);
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
const { start, end } = selection;
|
|
1543
|
+
const next = `${node.value.slice(0, start)}${text}${node.value.slice(end)}`;
|
|
1544
|
+
const cursor = start + text.length;
|
|
1545
|
+
if (next === node.value) {
|
|
1546
|
+
node.setSelectionRange(cursor, cursor);
|
|
1547
|
+
return;
|
|
1548
|
+
}
|
|
1549
|
+
selectionAfterInsert.current = cursor;
|
|
1550
|
+
draftRevision.current += 1;
|
|
1551
|
+
setDraft(next);
|
|
1552
|
+
}
|
|
1553
|
+
const canRecord = typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getUserMedia) && typeof MediaRecorder !== "undefined" && typeof OfflineAudioContext !== "undefined";
|
|
1554
|
+
const locked = overflowed || error === "contextOverflow";
|
|
1555
|
+
const dictation = useDictation(!locked && dictationAvailable && canRecord, controller, insertSpeech);
|
|
1556
|
+
useEffect(() => {
|
|
1557
|
+
if (dictationAvailable) setMicHelp((current) => current === "micSetup" ? "" : current);
|
|
1558
|
+
}, [dictationAvailable]);
|
|
1559
|
+
const dictating = ["micRequesting", "micRecording", "micTranscribing"].includes(dictation.phase);
|
|
1560
|
+
const sendBlocked = locked || busy || saving || dictating || !draft.trim();
|
|
1561
|
+
const resize = useCallback(() => {
|
|
1562
|
+
if (globalThis.CSS?.supports("field-sizing", "content")) return;
|
|
1563
|
+
const node = input.current;
|
|
1564
|
+
if (!node) return;
|
|
1565
|
+
const scrollTop = node.scrollTop;
|
|
1566
|
+
node.style.height = "0px";
|
|
1567
|
+
node.style.height = `${node.scrollHeight}px`;
|
|
1568
|
+
if (scrollTop) node.scrollTop = scrollTop;
|
|
1569
|
+
}, []);
|
|
1570
|
+
useLayoutEffect(() => {
|
|
1571
|
+
resize();
|
|
1572
|
+
if (selectionAfterInsert.current !== null) {
|
|
1573
|
+
input.current?.setSelectionRange(selectionAfterInsert.current, selectionAfterInsert.current);
|
|
1574
|
+
selectionAfterInsert.current = null;
|
|
1575
|
+
}
|
|
1576
|
+
}, [draft, resize]);
|
|
1577
|
+
useEffect(() => {
|
|
1578
|
+
const element = form.current;
|
|
1579
|
+
if (typeof ResizeObserver === "undefined" || !element) return void 0;
|
|
1580
|
+
let lastWidth;
|
|
1581
|
+
const observer = new ResizeObserver(([entry]) => {
|
|
1582
|
+
if (lastWidth !== entry.contentRect.width) {
|
|
1583
|
+
lastWidth = entry.contentRect.width;
|
|
1584
|
+
resize();
|
|
1585
|
+
}
|
|
1586
|
+
});
|
|
1587
|
+
observer.observe(element);
|
|
1588
|
+
return () => observer.disconnect();
|
|
1589
|
+
}, [resize]);
|
|
1590
|
+
async function submit(event) {
|
|
1591
|
+
event.preventDefault();
|
|
1592
|
+
if (sendBlocked || submitting.current || composing.current) return;
|
|
1593
|
+
const revision = draftRevision.current;
|
|
1594
|
+
submitting.current = true;
|
|
1595
|
+
setSaving(true);
|
|
1596
|
+
setError("");
|
|
1597
|
+
try {
|
|
1598
|
+
const detail2 = await controller.call("followup", sessionId, id2, draft);
|
|
1599
|
+
if (!live.current) return;
|
|
1600
|
+
if (draftRevision.current === revision) {
|
|
1601
|
+
draftRevision.current += 1;
|
|
1602
|
+
setDraft("");
|
|
1603
|
+
}
|
|
1604
|
+
onSent(detail2);
|
|
1605
|
+
} catch (failure) {
|
|
1606
|
+
if (live.current) setError(failure?.code === "btw/context-overflow" ? "contextOverflow" : "sendFailed");
|
|
1607
|
+
} finally {
|
|
1608
|
+
submitting.current = false;
|
|
1609
|
+
if (live.current) setSaving(false);
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
function keyDown(event) {
|
|
1613
|
+
if (event.key === "Escape" && dictating) {
|
|
1614
|
+
event.preventDefault();
|
|
1615
|
+
event.stopPropagation();
|
|
1616
|
+
dictation.cancel();
|
|
1617
|
+
}
|
|
1618
|
+
if (locked || event.key !== "Enter" || event.shiftKey || composing.current || event.nativeEvent.isComposing || event.keyCode === 229) return;
|
|
1619
|
+
event.preventDefault();
|
|
1620
|
+
if (!sendBlocked && !event.repeat) form.current?.requestSubmit();
|
|
1621
|
+
}
|
|
1622
|
+
function finishComposition() {
|
|
1623
|
+
composing.current = false;
|
|
1624
|
+
const pending = pendingTranscript.current;
|
|
1625
|
+
pendingTranscript.current = null;
|
|
1626
|
+
if (pending && !locked) queueMicrotask(() => {
|
|
1627
|
+
if (live.current && !input.current?.disabled) insertSpeech(pending.text, pending.selection);
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
function toggleMic() {
|
|
1631
|
+
if (locked || saving) return;
|
|
1632
|
+
if (!dictationAvailable) {
|
|
1633
|
+
setMicHelp((current) => current === "micSetup" ? "" : "micSetup");
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
if (!canRecord) {
|
|
1637
|
+
setMicHelp("micUnavailable");
|
|
1638
|
+
return;
|
|
1639
|
+
}
|
|
1640
|
+
setMicHelp("");
|
|
1641
|
+
const node = input.current;
|
|
1642
|
+
if (node) {
|
|
1643
|
+
setRetainedTranscript("");
|
|
1644
|
+
void dictation.toggle({ start: node.selectionStart, end: node.selectionEnd, revision: draftRevision.current });
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
const composerOverflow = error === "contextOverflow" && !overflowed;
|
|
1648
|
+
return h(
|
|
1649
|
+
Fragment,
|
|
1650
|
+
null,
|
|
1651
|
+
error && (!overflowed || error !== "contextOverflow") && h(Feedback, {
|
|
1652
|
+
id: composerOverflow ? overflowNotice : void 0,
|
|
1653
|
+
text: t(error),
|
|
1654
|
+
t,
|
|
1655
|
+
error: true
|
|
1656
|
+
}),
|
|
1657
|
+
!locked && micHelp && h(
|
|
1658
|
+
"div",
|
|
1659
|
+
{ className: "dsh-btw-feedback" },
|
|
1660
|
+
h("span", { role: "status" }, t(micHelp)),
|
|
1661
|
+
micHelp === "micSetup" && speechSettings && h("button", {
|
|
1662
|
+
type: "button",
|
|
1663
|
+
className: "dsh-btw-retry",
|
|
1664
|
+
onClick: speechSettings
|
|
1665
|
+
}, t("micSettings"))
|
|
1666
|
+
),
|
|
1667
|
+
!locked && retainedTranscript && h(
|
|
1668
|
+
"div",
|
|
1669
|
+
{ className: "dsh-btw-feedback" },
|
|
1670
|
+
h("span", { role: "status" }, t("micChanged")),
|
|
1671
|
+
h("button", { type: "button", className: "dsh-btw-retry", onClick: () => {
|
|
1672
|
+
const node = input.current;
|
|
1673
|
+
if (!node) return;
|
|
1674
|
+
insertSpeech(retainedTranscript, { start: node.selectionStart, end: node.selectionEnd, revision: draftRevision.current });
|
|
1675
|
+
setRetainedTranscript("");
|
|
1676
|
+
} }, t("micInsert"))
|
|
1677
|
+
),
|
|
1678
|
+
!locked && dictation.phase && h(Feedback, {
|
|
1679
|
+
text: t(dictation.phase),
|
|
1680
|
+
t,
|
|
1681
|
+
error: ["micFailed", "micMissing", "micPermission", "micTooLarge", "micInterrupted"].includes(dictation.phase)
|
|
1682
|
+
}),
|
|
1683
|
+
h(
|
|
1684
|
+
"form",
|
|
1685
|
+
{
|
|
1686
|
+
className: "dsh-btw-form",
|
|
1687
|
+
ref: form,
|
|
1688
|
+
onSubmit: submit,
|
|
1689
|
+
"aria-busy": saving,
|
|
1690
|
+
"aria-describedby": locked ? overflowNotice : void 0
|
|
1691
|
+
},
|
|
1692
|
+
h("label", { className: "dsh-btw-sr", htmlFor: inputId }, t("input")),
|
|
1693
|
+
h("textarea", {
|
|
1694
|
+
id: inputId,
|
|
1695
|
+
ref: input,
|
|
1696
|
+
className: "dsh-btw-input",
|
|
1697
|
+
rows: 1,
|
|
1698
|
+
placeholder: t("placeholder"),
|
|
1699
|
+
value: draft,
|
|
1700
|
+
disabled: locked,
|
|
1701
|
+
onChange: (event) => {
|
|
1702
|
+
draftRevision.current += 1;
|
|
1703
|
+
setDraft(event.target.value);
|
|
1704
|
+
if (error) setError("");
|
|
1705
|
+
},
|
|
1706
|
+
onKeyDown: keyDown,
|
|
1707
|
+
onCompositionStart: () => {
|
|
1708
|
+
composing.current = true;
|
|
1709
|
+
},
|
|
1710
|
+
onCompositionEnd: finishComposition
|
|
1711
|
+
}),
|
|
1712
|
+
h(
|
|
1713
|
+
"div",
|
|
1714
|
+
{ className: "dsh-btw-form-actions" },
|
|
1715
|
+
!locked && dictating && h(IconButton, { icon: "close", label: t("micCancel"), onClick: dictation.cancel }),
|
|
1716
|
+
speechMounted && h(IconButton, {
|
|
1717
|
+
className: "dsh-btw-mic",
|
|
1718
|
+
icon: dictation.phase === "micRecording" ? "stop" : "mic",
|
|
1719
|
+
label: t(dictation.phase === "micRecording" ? "micStop" : dictationAvailable ? "micStart" : "micSettings"),
|
|
1720
|
+
disabled: locked || saving || dictation.phase === "micRequesting" || dictation.phase === "micTranscribing",
|
|
1721
|
+
"data-recording": dictation.phase === "micRecording",
|
|
1722
|
+
onMouseDown: (event) => event.preventDefault(),
|
|
1723
|
+
onClick: toggleMic
|
|
1724
|
+
}),
|
|
1725
|
+
h(IconButton, {
|
|
1726
|
+
className: "dsh-btw-send",
|
|
1727
|
+
icon: "send",
|
|
1728
|
+
label: t("send"),
|
|
1729
|
+
type: "submit",
|
|
1730
|
+
disabled: sendBlocked,
|
|
1731
|
+
"data-sending": saving,
|
|
1732
|
+
"aria-busy": saving
|
|
1733
|
+
})
|
|
1734
|
+
)
|
|
1735
|
+
)
|
|
1736
|
+
);
|
|
1737
|
+
}
|
|
1738
|
+
function ContextRing({ percent }) {
|
|
1739
|
+
const circumference = 2 * Math.PI * 5.5;
|
|
1740
|
+
return h(
|
|
1741
|
+
"svg",
|
|
1742
|
+
{ width: 14, height: 14, viewBox: "0 0 14 14", "aria-hidden": true, focusable: false },
|
|
1743
|
+
h("circle", { className: "dsh-btw-context-track", cx: 7, cy: 7, r: 5.5 }),
|
|
1744
|
+
percent > 0 && h("circle", {
|
|
1745
|
+
className: "dsh-btw-context-fill",
|
|
1746
|
+
cx: 7,
|
|
1747
|
+
cy: 7,
|
|
1748
|
+
r: 5.5,
|
|
1749
|
+
strokeDasharray: `${circumference * percent / 100} ${circumference}`,
|
|
1750
|
+
transform: "rotate(-90 7 7)"
|
|
1751
|
+
})
|
|
1752
|
+
);
|
|
1753
|
+
}
|
|
1754
|
+
function AuditPill({ icon, iconElement, title, headline, secondary, rows, group }) {
|
|
1755
|
+
const disclosure = useRef(null);
|
|
1756
|
+
const trigger = useRef(null);
|
|
1757
|
+
const [open, setOpen] = useState(false);
|
|
1758
|
+
useEffect(() => {
|
|
1759
|
+
if (!open) return;
|
|
1760
|
+
const root = disclosure.current;
|
|
1761
|
+
if (!root) return;
|
|
1762
|
+
const closeOutside = (event) => {
|
|
1763
|
+
if (!event.composedPath().includes(root)) root.open = false;
|
|
1764
|
+
};
|
|
1765
|
+
const document2 = root.ownerDocument;
|
|
1766
|
+
document2.addEventListener("pointerdown", closeOutside, true);
|
|
1767
|
+
return () => document2.removeEventListener("pointerdown", closeOutside, true);
|
|
1768
|
+
}, [open]);
|
|
1769
|
+
const label = headline + (secondary ? ` · ${secondary}` : "");
|
|
1770
|
+
const marker = iconElement ?? h(Icon, { name: icon });
|
|
1771
|
+
const content = h(
|
|
1772
|
+
Fragment,
|
|
1773
|
+
null,
|
|
1774
|
+
marker,
|
|
1775
|
+
h(
|
|
1776
|
+
"span",
|
|
1777
|
+
{ className: "dsh-btw-stat-label" },
|
|
1778
|
+
h("span", { className: "dsh-btw-stat-reading" }, headline),
|
|
1779
|
+
secondary && h(
|
|
1780
|
+
"span",
|
|
1781
|
+
{ className: "dsh-btw-stat-reading" },
|
|
1782
|
+
h("span", { className: "dsh-btw-stat-sep", "aria-hidden": true }, "·"),
|
|
1783
|
+
secondary
|
|
1784
|
+
)
|
|
1785
|
+
)
|
|
1786
|
+
);
|
|
1787
|
+
if (!rows.length) return h("span", { className: "dsh-btw-stat-trigger", title: label }, content);
|
|
1788
|
+
return h(
|
|
1789
|
+
"details",
|
|
1790
|
+
{
|
|
1791
|
+
className: "dsh-btw-stat",
|
|
1792
|
+
name: group,
|
|
1793
|
+
ref: disclosure,
|
|
1794
|
+
onToggle: (event) => setOpen(event.currentTarget.open),
|
|
1795
|
+
onBlur: (event) => {
|
|
1796
|
+
if (event.relatedTarget && !event.currentTarget.contains(event.relatedTarget)) event.currentTarget.open = false;
|
|
1797
|
+
},
|
|
1798
|
+
onKeyDown: (event) => {
|
|
1799
|
+
if (event.key !== "Escape" || !event.currentTarget.open) return;
|
|
1800
|
+
event.stopPropagation();
|
|
1801
|
+
event.currentTarget.open = false;
|
|
1802
|
+
trigger.current?.focus();
|
|
1803
|
+
}
|
|
1804
|
+
},
|
|
1805
|
+
h("summary", {
|
|
1806
|
+
ref: trigger,
|
|
1807
|
+
className: "dsh-btw-stat-trigger",
|
|
1808
|
+
title: label,
|
|
1809
|
+
"aria-label": `${title} · ${label}`
|
|
1810
|
+
}, content),
|
|
1811
|
+
h(
|
|
1812
|
+
"div",
|
|
1813
|
+
{ className: "dsh-btw-stat-panel" },
|
|
1814
|
+
h("h3", { className: "dsh-btw-stat-heading" }, marker, title),
|
|
1815
|
+
h("dl", { className: "dsh-btw-stat-details" }, rows.map(([title2, value]) => h(
|
|
1816
|
+
Fragment,
|
|
1817
|
+
{ key: title2 },
|
|
1818
|
+
h("dt", null, title2),
|
|
1819
|
+
h("dd", null, value)
|
|
1820
|
+
)))
|
|
1821
|
+
)
|
|
1822
|
+
);
|
|
1823
|
+
}
|
|
1824
|
+
function UsageAudit({ turns, contextSample, performanceUsage, t, language }) {
|
|
1825
|
+
const group = useId();
|
|
1826
|
+
const compact = performanceUsage === "compact";
|
|
1827
|
+
const settled = turns.filter((turn) => !isRunning(turn.status));
|
|
1828
|
+
const { uncached, cacheRead, cacheWrite, output, total, cacheRatio } = summarizeUsage(settled);
|
|
1829
|
+
let modelMs = 0;
|
|
1830
|
+
let firstMs = 0;
|
|
1831
|
+
let firstCount = 0;
|
|
1832
|
+
let decodeMs = 0;
|
|
1833
|
+
let decodeTokens = 0;
|
|
1834
|
+
for (const { timing, usage, status: status2 } of settled) {
|
|
1835
|
+
if (!timing || status2 !== "completed") continue;
|
|
1836
|
+
modelMs += timing.requestMs;
|
|
1837
|
+
if (timing.firstTokenMs === void 0) continue;
|
|
1838
|
+
firstCount += 1;
|
|
1839
|
+
firstMs += timing.firstTokenMs;
|
|
1840
|
+
const elapsed = timing.requestMs - timing.firstTokenMs;
|
|
1841
|
+
if (usage?.outputTokens !== void 0) {
|
|
1842
|
+
decodeMs += elapsed;
|
|
1843
|
+
decodeTokens += usage.outputTokens;
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
const locale = language || void 0;
|
|
1847
|
+
const number = new Intl.NumberFormat(locale);
|
|
1848
|
+
const duration = (ms) => {
|
|
1849
|
+
if (ms < 6e4) return t("auditSeconds", { seconds: Math.round(ms / 100) / 10 });
|
|
1850
|
+
const seconds = Math.round(ms / 1e3);
|
|
1851
|
+
return t("auditMinutes", { minutes: Math.floor(seconds / 60), seconds: seconds % 60 });
|
|
1852
|
+
};
|
|
1853
|
+
const tokensPerSecond = decodeTokens * 1e3 / decodeMs;
|
|
1854
|
+
const speed = decodeMs > 0 ? `${tokensPerSecond >= 10 ? Math.round(tokensPerSecond) : Math.round(tokensPerSecond * 10) / 10} tok/s` : null;
|
|
1855
|
+
const cache = formatCacheRatio(cacheRatio, locale);
|
|
1856
|
+
const cacheText = cache === null ? null : `${t("auditCacheHit")} ${cache}`;
|
|
1857
|
+
const counts = `${number.format(settled.length)} ${t("auditRounds")}`;
|
|
1858
|
+
const activityRows = [];
|
|
1859
|
+
if (modelMs > 0) activityRows.push([t("auditModelTime"), duration(modelMs)]);
|
|
1860
|
+
if (firstCount) activityRows.push([t("auditFirstToken"), duration(firstMs / firstCount)]);
|
|
1861
|
+
if (speed !== null) activityRows.push([t("auditRate"), speed]);
|
|
1862
|
+
const usageRows = [[t("auditTotal"), number.format(total)]];
|
|
1863
|
+
if (cache !== null) usageRows.push([t("auditCacheHit"), cache]);
|
|
1864
|
+
if (cacheRatio !== null) {
|
|
1865
|
+
usageRows.push([t("auditInput"), number.format(uncached)], [t("auditCacheRead"), number.format(cacheRead)]);
|
|
1866
|
+
if (cacheWrite > 0) usageRows.push([t("auditCacheWrite"), number.format(cacheWrite)]);
|
|
1867
|
+
}
|
|
1868
|
+
if (cacheRatio !== null || output > 0) usageRows.push([t("auditOutput"), number.format(output)]);
|
|
1869
|
+
const context = contextReading(contextSample);
|
|
1870
|
+
return h(
|
|
1871
|
+
"div",
|
|
1872
|
+
{ className: "dsh-btw-audit" },
|
|
1873
|
+
(compact ? speed !== null : settled.length > 0) && h(AuditPill, {
|
|
1874
|
+
icon: "gauge",
|
|
1875
|
+
title: t("auditActivity"),
|
|
1876
|
+
headline: compact ? speed : counts,
|
|
1877
|
+
secondary: compact ? null : speed,
|
|
1878
|
+
rows: compact ? [] : activityRows,
|
|
1879
|
+
group
|
|
1880
|
+
}),
|
|
1881
|
+
(compact ? cacheText !== null : total > 0) && h(AuditPill, {
|
|
1882
|
+
icon: "database",
|
|
1883
|
+
title: t("audit"),
|
|
1884
|
+
headline: compact ? cacheText : `${formatTokenCount(total)} tok`,
|
|
1885
|
+
secondary: compact ? null : cacheText,
|
|
1886
|
+
rows: compact ? [] : usageRows,
|
|
1887
|
+
group
|
|
1888
|
+
}),
|
|
1889
|
+
context && h(AuditPill, {
|
|
1890
|
+
title: t("auditContext"),
|
|
1891
|
+
headline: `${context.percent}%`,
|
|
1892
|
+
iconElement: h(ContextRing, { percent: context.percent }),
|
|
1893
|
+
group,
|
|
1894
|
+
rows: [
|
|
1895
|
+
[t("auditContextInput"), `${number.format(context.used)} tok`],
|
|
1896
|
+
[t("auditContextWindow"), `${number.format(context.contextWindow)} tok`]
|
|
1897
|
+
]
|
|
1898
|
+
})
|
|
1899
|
+
);
|
|
1900
|
+
}
|
|
1901
|
+
function Chat({ controller, sessionId, id: id2, t, renderFactorySlot, language, dictationAvailable, speechMounted, speechSettings, performanceUsage, focusHeading, onBack }) {
|
|
1902
|
+
const [revision, setRevision] = useState(0);
|
|
1903
|
+
const reload = () => setRevision((value) => value + 1);
|
|
1904
|
+
const { detail: detail2, context, failure, accept } = useDetail({ controller, sessionId, id: id2, revision, reload });
|
|
1905
|
+
const heading = useRef(null);
|
|
1906
|
+
const scroll = useRef(null);
|
|
1907
|
+
const follow = useRef(true);
|
|
1908
|
+
useLayoutEffect(() => {
|
|
1909
|
+
if (focusHeading) heading.current?.focus({ preventScroll: true });
|
|
1910
|
+
}, [focusHeading]);
|
|
1911
|
+
const question2 = detail2?.question ?? t("title");
|
|
1912
|
+
const last = detail2?.turns.at(-1);
|
|
1913
|
+
const overflowed = last?.error === CONTEXT_OVERFLOW;
|
|
1914
|
+
const overflowNotice = useId();
|
|
1915
|
+
return h(
|
|
1916
|
+
Fragment,
|
|
1917
|
+
null,
|
|
1918
|
+
h(
|
|
1919
|
+
"header",
|
|
1920
|
+
{ className: "dsh-btw-bar" },
|
|
1921
|
+
h(IconButton, { icon: "back", label: t("back"), onClick: onBack }),
|
|
1922
|
+
h("h2", { className: "dsh-btw-bar-title", ref: heading, tabIndex: -1, title: question2 }, question2)
|
|
1923
|
+
),
|
|
1924
|
+
failure && h(Feedback, { text: t(failure), t, error: true, onRetry: reload }),
|
|
1925
|
+
!detail2 ? !failure && h(Feedback, { text: t("loading"), t }) : h(
|
|
1926
|
+
Fragment,
|
|
1927
|
+
null,
|
|
1928
|
+
h(Thread, {
|
|
1929
|
+
detail: detail2,
|
|
1930
|
+
renderFactorySlot,
|
|
1931
|
+
t,
|
|
1932
|
+
language,
|
|
1933
|
+
scrollRef: scroll,
|
|
1934
|
+
followRef: follow,
|
|
1935
|
+
performanceUsage,
|
|
1936
|
+
streamFailed: failure === "streamFailed",
|
|
1937
|
+
overflowNotice
|
|
1938
|
+
}),
|
|
1939
|
+
h(
|
|
1940
|
+
"div",
|
|
1941
|
+
{ className: "dsh-btw-reply-dock" },
|
|
1942
|
+
h(Composer, {
|
|
1943
|
+
controller,
|
|
1944
|
+
sessionId,
|
|
1945
|
+
id: id2,
|
|
1946
|
+
t,
|
|
1947
|
+
busy: isRunning(last?.status),
|
|
1948
|
+
overflowed,
|
|
1949
|
+
overflowNotice,
|
|
1950
|
+
dictationAvailable,
|
|
1951
|
+
speechMounted,
|
|
1952
|
+
speechSettings,
|
|
1953
|
+
onSent: (receipt2) => {
|
|
1954
|
+
follow.current = true;
|
|
1955
|
+
accept(receipt2);
|
|
1956
|
+
}
|
|
1957
|
+
}),
|
|
1958
|
+
h(UsageAudit, { turns: detail2.turns, contextSample: context, performanceUsage, t, language })
|
|
1959
|
+
)
|
|
1960
|
+
)
|
|
1961
|
+
);
|
|
1962
|
+
}
|
|
1963
|
+
function OpenPane({ controller, sessionId, t, renderFactorySlot, pane, dictationAvailable, speechMounted, speechSettings, language, listRevision, performanceUsage }) {
|
|
1964
|
+
const focusId = useRef(null);
|
|
1965
|
+
const id2 = pane.id;
|
|
1966
|
+
return h(
|
|
1967
|
+
"section",
|
|
1968
|
+
{ className: "dsh-btw-pane", "aria-label": t("title"), lang: language },
|
|
1969
|
+
h("style", null, styles),
|
|
1970
|
+
id2 ? h(Chat, {
|
|
1971
|
+
key: id2,
|
|
1972
|
+
controller,
|
|
1973
|
+
sessionId,
|
|
1974
|
+
id: id2,
|
|
1975
|
+
focusHeading: !pane.restored,
|
|
1976
|
+
t,
|
|
1977
|
+
renderFactorySlot,
|
|
1978
|
+
language,
|
|
1979
|
+
dictationAvailable,
|
|
1980
|
+
speechMounted,
|
|
1981
|
+
speechSettings,
|
|
1982
|
+
performanceUsage,
|
|
1983
|
+
onBack: () => {
|
|
1984
|
+
focusId.current = id2;
|
|
1985
|
+
controller.navigate(sessionId, null);
|
|
1986
|
+
}
|
|
1987
|
+
}) : h(List, { key: pane.listOpenedAt, controller, sessionId, t, language, focusId: focusId.current, listRevision })
|
|
1988
|
+
);
|
|
1989
|
+
}
|
|
1990
|
+
function Pane({ controller, sessionId, t, renderFactorySlot, language }) {
|
|
1991
|
+
const snapshot = useSnapshot(controller);
|
|
1992
|
+
if (!sessionId || snapshot.pane?.sessionId !== sessionId) return null;
|
|
1993
|
+
return h(OpenPane, {
|
|
1994
|
+
key: sessionId,
|
|
1995
|
+
controller,
|
|
1996
|
+
sessionId,
|
|
1997
|
+
t,
|
|
1998
|
+
renderFactorySlot,
|
|
1999
|
+
language,
|
|
2000
|
+
pane: snapshot.pane,
|
|
2001
|
+
dictationAvailable: snapshot.dictationAvailable,
|
|
2002
|
+
speechMounted: snapshot.speechMounted,
|
|
2003
|
+
speechSettings: snapshot.speechSettings,
|
|
2004
|
+
listRevision: snapshot.listRevision,
|
|
2005
|
+
performanceUsage: snapshot.performanceUsage
|
|
2006
|
+
});
|
|
2007
|
+
}
|
|
2008
|
+
return { Dock, Pane, CommandIcon: SideQuestionIcon };
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
// locale/en.json
|
|
2012
|
+
var en_default = {
|
|
2013
|
+
meta: {
|
|
2014
|
+
title: "dsh-btw",
|
|
2015
|
+
description: "Use /btw to ask side questions above the input, or view history and follow up in the right sidebar."
|
|
2016
|
+
},
|
|
2017
|
+
ui: {
|
|
2018
|
+
title: "Side question",
|
|
2019
|
+
listTitle: "Side questions",
|
|
2020
|
+
commandHint: "ask a question, or press Enter for history",
|
|
2021
|
+
commandLabel: "Side question",
|
|
2022
|
+
commandSpelling: "btw",
|
|
2023
|
+
commandDescription: "Ask a side question or view history",
|
|
2024
|
+
sidebarUnavailable: "Sidebar is unavailable in this view.",
|
|
2025
|
+
sessionNotSaved: "Send a message first to ask a side question.",
|
|
2026
|
+
modelUnavailable: "No model is configured for this conversation.",
|
|
2027
|
+
saveFailed: "Failed to save the side question.",
|
|
2028
|
+
textOnly: "/btw does not accept attachments.",
|
|
2029
|
+
collapse: "Collapse reply",
|
|
2030
|
+
expand: "Expand reply",
|
|
2031
|
+
openSidebar: "Open in sidebar",
|
|
2032
|
+
dismiss: "Close",
|
|
2033
|
+
back: "Back to list",
|
|
2034
|
+
emptyList: "No side questions yet",
|
|
2035
|
+
loading: "Loading…",
|
|
2036
|
+
loadFailed: "Failed to load side question.",
|
|
2037
|
+
streamFailed: "Connection lost.",
|
|
2038
|
+
missingThread: "Side question not found.",
|
|
2039
|
+
retry: "Retry",
|
|
2040
|
+
waiting: "Waiting for a reply…",
|
|
2041
|
+
interrupted: "Reply interrupted.",
|
|
2042
|
+
replyFailed: "Failed to generate reply.",
|
|
2043
|
+
contextOverflow: "Context limit reached.",
|
|
2044
|
+
emptyReply: "No text response.",
|
|
2045
|
+
history: "Side question messages",
|
|
2046
|
+
userMessage: "You",
|
|
2047
|
+
assistantMessage: "Assistant",
|
|
2048
|
+
placeholder: "Ask a follow-up…",
|
|
2049
|
+
input: "Enter a message",
|
|
2050
|
+
send: "Send follow-up",
|
|
2051
|
+
sendFailed: "Failed to send follow-up.",
|
|
2052
|
+
micStart: "Start recording",
|
|
2053
|
+
micStop: "Stop and transcribe",
|
|
2054
|
+
micRequesting: "Allow microphone access…",
|
|
2055
|
+
micRecording: "Recording…",
|
|
2056
|
+
micTranscribing: "Transcribing…",
|
|
2057
|
+
micFailed: "Speech recognition failed.",
|
|
2058
|
+
micEmpty: "No speech recognized.",
|
|
2059
|
+
micSetup: "Voice input not ready",
|
|
2060
|
+
micSettings: "Voice input settings",
|
|
2061
|
+
micUnavailable: "Audio recording is not supported in this browser.",
|
|
2062
|
+
audit: "Usage",
|
|
2063
|
+
auditActivity: "Time and speed",
|
|
2064
|
+
auditRounds: "turns",
|
|
2065
|
+
auditModelTime: "Model time",
|
|
2066
|
+
auditFirstToken: "Avg time to first token (TTFT)",
|
|
2067
|
+
auditRate: "Output speed (TPS)",
|
|
2068
|
+
auditCacheHit: "Cache hit",
|
|
2069
|
+
auditTotal: "Total",
|
|
2070
|
+
auditInput: "Uncached input",
|
|
2071
|
+
auditCacheRead: "Cache read",
|
|
2072
|
+
auditCacheWrite: "Cache write",
|
|
2073
|
+
auditOutput: "Output",
|
|
2074
|
+
auditTurn: "Turn usage",
|
|
2075
|
+
auditSpent: "Usage {total}",
|
|
2076
|
+
auditReasoning: "Reasoning tokens",
|
|
2077
|
+
auditContext: "Context usage",
|
|
2078
|
+
auditContextInput: "Estimated context used",
|
|
2079
|
+
auditContextWindow: "Model context window",
|
|
2080
|
+
copy: "Copy",
|
|
2081
|
+
copied: "Copied",
|
|
2082
|
+
copyFailed: "Copy failed.",
|
|
2083
|
+
archiveWriteFailed: "Failed to save reply.",
|
|
2084
|
+
micPermission: "Microphone access is disabled. Allow it in browser or system settings.",
|
|
2085
|
+
micMissing: "Microphone unavailable. Check your input device.",
|
|
2086
|
+
micInterrupted: "Recording interrupted.",
|
|
2087
|
+
micTooLarge: "Recording exceeds size limit.",
|
|
2088
|
+
auditSeconds: "{seconds}s",
|
|
2089
|
+
auditMinutes: "{minutes}m{seconds}s",
|
|
2090
|
+
micChanged: "Draft changed",
|
|
2091
|
+
micInsert: "Insert text",
|
|
2092
|
+
micCancel: "Cancel recording"
|
|
2093
|
+
}
|
|
2094
|
+
};
|
|
2095
|
+
|
|
2096
|
+
// locale/zh.json
|
|
2097
|
+
var zh_default = {
|
|
2098
|
+
meta: {
|
|
2099
|
+
title: "dsh-btw",
|
|
2100
|
+
description: "通过 /侧问 或 /btw 围绕当前对话提问,在输入框上方查看回答,或在右侧栏查看记录并继续追问。"
|
|
2101
|
+
},
|
|
2102
|
+
ui: {
|
|
2103
|
+
title: "侧问",
|
|
2104
|
+
listTitle: "侧问记录",
|
|
2105
|
+
commandHint: "输入问题,或按 Enter 查看记录",
|
|
2106
|
+
commandLabel: "侧问",
|
|
2107
|
+
commandSpelling: "侧问",
|
|
2108
|
+
commandDescription: "发起侧问,或查看当前会话的侧问记录",
|
|
2109
|
+
sidebarUnavailable: "当前视图无法打开右侧栏。",
|
|
2110
|
+
sessionNotSaved: "请先发送一条消息开始侧问",
|
|
2111
|
+
modelUnavailable: "当前会话未配置可用模型。",
|
|
2112
|
+
saveFailed: "保存侧问失败。",
|
|
2113
|
+
textOnly: "侧问不接受附件。",
|
|
2114
|
+
collapse: "收起回复",
|
|
2115
|
+
expand: "展开回复",
|
|
2116
|
+
openSidebar: "在侧栏打开",
|
|
2117
|
+
dismiss: "关闭",
|
|
2118
|
+
back: "返回列表",
|
|
2119
|
+
emptyList: "暂无侧问记录",
|
|
2120
|
+
loading: "加载中…",
|
|
2121
|
+
loadFailed: "加载侧问失败。",
|
|
2122
|
+
streamFailed: "连接已断开。",
|
|
2123
|
+
missingThread: "找不到该侧问记录。",
|
|
2124
|
+
retry: "重试",
|
|
2125
|
+
waiting: "等待回复…",
|
|
2126
|
+
interrupted: "回复已中断。",
|
|
2127
|
+
replyFailed: "回复生成失败。",
|
|
2128
|
+
contextOverflow: "已达上下文上限。",
|
|
2129
|
+
emptyReply: "模型未返回文本内容。",
|
|
2130
|
+
history: "侧问对话记录",
|
|
2131
|
+
userMessage: "你",
|
|
2132
|
+
assistantMessage: "模型",
|
|
2133
|
+
placeholder: "继续追问…",
|
|
2134
|
+
input: "输入消息",
|
|
2135
|
+
send: "发送追问",
|
|
2136
|
+
sendFailed: "发送失败,请重试。",
|
|
2137
|
+
micStart: "开始录音",
|
|
2138
|
+
micStop: "停止并识别",
|
|
2139
|
+
micRequesting: "请允许使用麦克风…",
|
|
2140
|
+
micRecording: "录音中…",
|
|
2141
|
+
micTranscribing: "识别中…",
|
|
2142
|
+
micFailed: "语音识别失败。",
|
|
2143
|
+
micEmpty: "未识别到语音。",
|
|
2144
|
+
micSetup: "语音输入尚未就绪",
|
|
2145
|
+
micSettings: "语音输入设置",
|
|
2146
|
+
micUnavailable: "当前浏览器不支持录音。",
|
|
2147
|
+
audit: "用量",
|
|
2148
|
+
auditActivity: "耗时与速度",
|
|
2149
|
+
auditRounds: "轮",
|
|
2150
|
+
auditModelTime: "模型用时",
|
|
2151
|
+
auditFirstToken: "平均首 token 延迟(TTFT)",
|
|
2152
|
+
auditRate: "输出速度(TPS)",
|
|
2153
|
+
auditCacheHit: "缓存命中",
|
|
2154
|
+
auditTotal: "总计",
|
|
2155
|
+
auditInput: "未缓存输入",
|
|
2156
|
+
auditCacheRead: "读取缓存",
|
|
2157
|
+
auditCacheWrite: "写入缓存",
|
|
2158
|
+
auditOutput: "输出",
|
|
2159
|
+
auditTurn: "本轮用量",
|
|
2160
|
+
auditSpent: "用量 {total}",
|
|
2161
|
+
auditReasoning: "推理 token",
|
|
2162
|
+
auditContext: "上下文占用",
|
|
2163
|
+
auditContextInput: "已用上下文估算",
|
|
2164
|
+
auditContextWindow: "模型上下文窗口",
|
|
2165
|
+
copy: "复制",
|
|
2166
|
+
copied: "已复制",
|
|
2167
|
+
copyFailed: "复制失败。",
|
|
2168
|
+
archiveWriteFailed: "回复保存失败。",
|
|
2169
|
+
micPermission: "麦克风权限未开启,请在浏览器或系统设置中允许访问。",
|
|
2170
|
+
micMissing: "未检测到可用麦克风,请检查输入设备。",
|
|
2171
|
+
micInterrupted: "录音已中断。",
|
|
2172
|
+
micTooLarge: "录音超出大小限制。",
|
|
2173
|
+
auditSeconds: "{seconds}秒",
|
|
2174
|
+
auditMinutes: "{minutes}分{seconds}秒",
|
|
2175
|
+
micChanged: "草稿已变更",
|
|
2176
|
+
micInsert: "插入文字",
|
|
2177
|
+
micCancel: "取消录音"
|
|
2178
|
+
}
|
|
2179
|
+
};
|
|
2180
|
+
|
|
2181
|
+
// src/client/index.js
|
|
2182
|
+
var plugin = PACKAGE_NAME;
|
|
2183
|
+
var tabKind = "kabxx-btw";
|
|
2184
|
+
var namespace = "dshBtw";
|
|
2185
|
+
var voiceBundle = "@deepseek-ai/dsh-experimental-voice-input-bundle";
|
|
2186
|
+
var defaultPerformanceUsage = "detailed";
|
|
2187
|
+
var microphonePreference = "dsh.voice-input.microphone";
|
|
2188
|
+
var cardPreferencePrefix = "dsh.btw.card.";
|
|
2189
|
+
function getMicrophoneDevice() {
|
|
2190
|
+
try {
|
|
2191
|
+
const device = JSON.parse(globalThis.localStorage?.getItem(microphonePreference) ?? "null");
|
|
2192
|
+
if (typeof device?.id === "string" && typeof device.label === "string") return device.id;
|
|
2193
|
+
} catch {
|
|
2194
|
+
}
|
|
2195
|
+
return "";
|
|
2196
|
+
}
|
|
2197
|
+
var inject = ["slots", "locale", "remote", "inputTriggers", "sidebarRightTabs", "sidebarRight"];
|
|
2198
|
+
function unwrap(result) {
|
|
2199
|
+
if (result.ok) return result.value;
|
|
2200
|
+
const error = new Error(result.error?.message ?? "BTW request failed");
|
|
2201
|
+
error.code = result.error?.code;
|
|
2202
|
+
throw error;
|
|
2203
|
+
}
|
|
2204
|
+
function base64(bytes) {
|
|
2205
|
+
let binary = "";
|
|
2206
|
+
for (let offset = 0; offset < bytes.length; offset += 8192) {
|
|
2207
|
+
binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
|
|
2208
|
+
}
|
|
2209
|
+
return btoa(binary);
|
|
2210
|
+
}
|
|
2211
|
+
function makeController(ctx) {
|
|
2212
|
+
const sidebar = ctx.sidebarRight;
|
|
2213
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2214
|
+
const activeStreams = /* @__PURE__ */ new Set();
|
|
2215
|
+
let snapshot = {
|
|
2216
|
+
cards: {},
|
|
2217
|
+
pane: null,
|
|
2218
|
+
notice: {},
|
|
2219
|
+
dictationAvailable: false,
|
|
2220
|
+
speechMounted: false,
|
|
2221
|
+
speechSettings: null,
|
|
2222
|
+
listRevision: 0,
|
|
2223
|
+
performanceUsage: defaultPerformanceUsage
|
|
2224
|
+
};
|
|
2225
|
+
let session = sidebar.mounted.getSnapshot();
|
|
2226
|
+
let selectionRevision = 0;
|
|
2227
|
+
const panes = /* @__PURE__ */ new Map();
|
|
2228
|
+
const cardIds = /* @__PURE__ */ new Map();
|
|
2229
|
+
const lastAcceptedCards = /* @__PURE__ */ new Map();
|
|
2230
|
+
let lastCardRequest = 0;
|
|
2231
|
+
let speechCatalog;
|
|
2232
|
+
let speechRemote;
|
|
2233
|
+
let disposed = false;
|
|
2234
|
+
let closeQueued = false;
|
|
2235
|
+
function publish(next) {
|
|
2236
|
+
if (disposed) return;
|
|
2237
|
+
snapshot = { ...snapshot, ...next };
|
|
2238
|
+
for (const listener of [...listeners]) listener();
|
|
2239
|
+
}
|
|
2240
|
+
function closeTabs(id2) {
|
|
2241
|
+
if (id2 === void 0) return;
|
|
2242
|
+
for (const tab of sidebar.tabsIn(id2)) {
|
|
2243
|
+
if (tab.kind === tabKind) sidebar.closeIn(id2, tab.id);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
function pruneRestored() {
|
|
2247
|
+
if (!disposed && !panes.has(session)) closeTabs(session);
|
|
2248
|
+
}
|
|
2249
|
+
function queuePrune() {
|
|
2250
|
+
if (closeQueued) return;
|
|
2251
|
+
closeQueued = true;
|
|
2252
|
+
queueMicrotask(() => {
|
|
2253
|
+
closeQueued = false;
|
|
2254
|
+
pruneRestored();
|
|
2255
|
+
});
|
|
2256
|
+
}
|
|
2257
|
+
function navigatePane(sessionId, id2) {
|
|
2258
|
+
const listRevision = snapshot.listRevision + 1;
|
|
2259
|
+
const pane = id2 === null ? { sessionId, id: id2, listOpenedAt: listRevision } : { sessionId, id: id2 };
|
|
2260
|
+
panes.set(sessionId, pane);
|
|
2261
|
+
publish(id2 === null ? { pane, listRevision } : { pane });
|
|
2262
|
+
}
|
|
2263
|
+
function open(sessionId, id2) {
|
|
2264
|
+
if (disposed || session !== sessionId) return false;
|
|
2265
|
+
sidebar.openTabIn(sessionId, tabKind);
|
|
2266
|
+
if (!sidebar.tabsIn(sessionId).some((tab) => tab.kind === tabKind)) return false;
|
|
2267
|
+
navigatePane(sessionId, id2);
|
|
2268
|
+
return true;
|
|
2269
|
+
}
|
|
2270
|
+
function cardIdFor(sessionId) {
|
|
2271
|
+
if (!cardIds.has(sessionId)) {
|
|
2272
|
+
let id2 = null;
|
|
2273
|
+
try {
|
|
2274
|
+
id2 = globalThis.localStorage?.getItem(cardPreferencePrefix + sessionId) ?? null;
|
|
2275
|
+
} catch {
|
|
2276
|
+
}
|
|
2277
|
+
cardIds.set(sessionId, id2);
|
|
2278
|
+
}
|
|
2279
|
+
return cardIds.get(sessionId);
|
|
2280
|
+
}
|
|
2281
|
+
function rememberCard(sessionId, id2) {
|
|
2282
|
+
cardIds.set(sessionId, id2);
|
|
2283
|
+
try {
|
|
2284
|
+
if (id2 === null) globalThis.localStorage?.removeItem(cardPreferencePrefix + sessionId);
|
|
2285
|
+
else globalThis.localStorage?.setItem(cardPreferencePrefix + sessionId, id2);
|
|
2286
|
+
} catch {
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
async function restoreCard(sessionId) {
|
|
2290
|
+
if (disposed || sessionId === void 0 || session !== sessionId || snapshot.cards[sessionId]) return;
|
|
2291
|
+
const id2 = cardIdFor(sessionId);
|
|
2292
|
+
if (!id2) return;
|
|
2293
|
+
const revision = selectionRevision;
|
|
2294
|
+
const stillCurrent = () => !disposed && selectionRevision === revision && cardIdFor(sessionId) === id2;
|
|
2295
|
+
try {
|
|
2296
|
+
const detail2 = unwrap(await ctx.remote.btw.get(sessionId, id2));
|
|
2297
|
+
if (stillCurrent() && detail2.id === id2 && detail2.sessionId === sessionId && !snapshot.cards[sessionId]) {
|
|
2298
|
+
publish({ cards: { ...snapshot.cards, [sessionId]: detail2 } });
|
|
2299
|
+
}
|
|
2300
|
+
} catch (error) {
|
|
2301
|
+
if (stillCurrent() && error.code === "btw/not-found") rememberCard(sessionId, null);
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
const disposeSelection = sidebar.mounted.subscribe(() => {
|
|
2305
|
+
const current = sidebar.mounted.getSnapshot();
|
|
2306
|
+
if (current === session) return;
|
|
2307
|
+
session = current;
|
|
2308
|
+
selectionRevision += 1;
|
|
2309
|
+
const pane = panes.get(session);
|
|
2310
|
+
publish({ cards: {}, pane: pane ? { ...pane, restored: true } : null, notice: {} });
|
|
2311
|
+
queuePrune();
|
|
2312
|
+
});
|
|
2313
|
+
const disposeInventory = sidebar.openTabs.subscribe(() => {
|
|
2314
|
+
const openSessions = new Set(sidebar.openTabs.getSnapshot().filter((tab) => tab.kind === tabKind).map((tab) => tab.sessionId));
|
|
2315
|
+
for (const id2 of panes.keys()) {
|
|
2316
|
+
if (!openSessions.has(id2)) panes.delete(id2);
|
|
2317
|
+
}
|
|
2318
|
+
if (snapshot.pane && !panes.has(snapshot.pane.sessionId)) publish({ pane: null });
|
|
2319
|
+
queuePrune();
|
|
2320
|
+
});
|
|
2321
|
+
queuePrune();
|
|
2322
|
+
function observe(start, settled, onNext, onError) {
|
|
2323
|
+
const controller = new AbortController();
|
|
2324
|
+
activeStreams.add(controller);
|
|
2325
|
+
void (async () => {
|
|
2326
|
+
let stream;
|
|
2327
|
+
let last;
|
|
2328
|
+
try {
|
|
2329
|
+
stream = start(controller.signal);
|
|
2330
|
+
for await (const value of stream) {
|
|
2331
|
+
last = value;
|
|
2332
|
+
if (!controller.signal.aborted) onNext(value);
|
|
2333
|
+
}
|
|
2334
|
+
if (!controller.signal.aborted && (!last || !settled(last))) {
|
|
2335
|
+
onError?.(new Error("BTW stream ended before the reply settled"));
|
|
2336
|
+
}
|
|
2337
|
+
} catch (error) {
|
|
2338
|
+
if (!controller.signal.aborted) onError?.(error);
|
|
2339
|
+
} finally {
|
|
2340
|
+
activeStreams.delete(controller);
|
|
2341
|
+
stream?.dispose?.();
|
|
2342
|
+
}
|
|
2343
|
+
})();
|
|
2344
|
+
return () => controller.abort();
|
|
2345
|
+
}
|
|
2346
|
+
return {
|
|
2347
|
+
subscribe(listener) {
|
|
2348
|
+
listeners.add(listener);
|
|
2349
|
+
return () => listeners.delete(listener);
|
|
2350
|
+
},
|
|
2351
|
+
getSnapshot: () => snapshot,
|
|
2352
|
+
openList: (id2) => open(id2, null),
|
|
2353
|
+
openDetail: (sessionId, id2) => open(sessionId, id2),
|
|
2354
|
+
navigate(sessionId, id2) {
|
|
2355
|
+
if (!disposed && session === sessionId && panes.has(sessionId)) navigatePane(sessionId, id2);
|
|
2356
|
+
},
|
|
2357
|
+
restoreCard,
|
|
2358
|
+
dismiss(id2) {
|
|
2359
|
+
rememberCard(id2, null);
|
|
2360
|
+
const cards = { ...snapshot.cards };
|
|
2361
|
+
delete cards[id2];
|
|
2362
|
+
publish({ cards });
|
|
2363
|
+
},
|
|
2364
|
+
async createCard(id2, question2) {
|
|
2365
|
+
const request = ++lastCardRequest;
|
|
2366
|
+
const detail2 = unwrap(await ctx.remote.btw.create(id2, question2));
|
|
2367
|
+
if (disposed) return;
|
|
2368
|
+
const listRevision = snapshot.listRevision + 1;
|
|
2369
|
+
if (request <= (lastAcceptedCards.get(id2) ?? 0)) {
|
|
2370
|
+
if (session === id2) publish({ listRevision });
|
|
2371
|
+
return;
|
|
2372
|
+
}
|
|
2373
|
+
lastAcceptedCards.set(id2, request);
|
|
2374
|
+
rememberCard(id2, detail2.id);
|
|
2375
|
+
if (session === id2) publish({ cards: { ...snapshot.cards, [id2]: detail2 }, listRevision });
|
|
2376
|
+
},
|
|
2377
|
+
async call(name, ...args) {
|
|
2378
|
+
return unwrap(await ctx.remote.btw[name](...args));
|
|
2379
|
+
},
|
|
2380
|
+
watch(sessionId, id2, onNext, onError) {
|
|
2381
|
+
return observe(
|
|
2382
|
+
(signal) => ctx.remote.btw.watch(sessionId, id2, null, signal),
|
|
2383
|
+
(detail2) => detail2.turns.at(-1)?.status !== "generating",
|
|
2384
|
+
onNext,
|
|
2385
|
+
onError
|
|
2386
|
+
);
|
|
2387
|
+
},
|
|
2388
|
+
watchReply(sessionId, id2, turnIndex, version2, onNext, onError) {
|
|
2389
|
+
return observe(
|
|
2390
|
+
(signal) => ctx.remote.btw.watchReply(sessionId, id2, turnIndex, version2, signal),
|
|
2391
|
+
(update) => update.status !== "generating",
|
|
2392
|
+
onNext,
|
|
2393
|
+
onError
|
|
2394
|
+
);
|
|
2395
|
+
},
|
|
2396
|
+
pruneRestored,
|
|
2397
|
+
setPerformanceUsage(value) {
|
|
2398
|
+
const performanceUsage = value === "compact" ? value : defaultPerformanceUsage;
|
|
2399
|
+
if (performanceUsage !== snapshot.performanceUsage) publish({ performanceUsage });
|
|
2400
|
+
},
|
|
2401
|
+
setSpeechCatalog(catalog, remote) {
|
|
2402
|
+
speechCatalog = catalog;
|
|
2403
|
+
speechRemote = remote;
|
|
2404
|
+
const model = catalog?.selection?.providerId;
|
|
2405
|
+
const provider = catalog?.providers?.find((item) => item.id === model);
|
|
2406
|
+
const available = provider !== void 0 && ["ready", "standby", "waking"].includes(provider.preparation?.phase);
|
|
2407
|
+
const speechMounted = remote !== void 0;
|
|
2408
|
+
if (available !== snapshot.dictationAvailable || speechMounted !== snapshot.speechMounted) {
|
|
2409
|
+
publish({ dictationAvailable: available, speechMounted });
|
|
2410
|
+
}
|
|
2411
|
+
},
|
|
2412
|
+
setSpeechSettings(speechSettings) {
|
|
2413
|
+
publish({ speechSettings });
|
|
2414
|
+
},
|
|
2415
|
+
beginDictation() {
|
|
2416
|
+
const catalog = speechCatalog;
|
|
2417
|
+
const speech = speechRemote;
|
|
2418
|
+
if (!speech || !catalog?.selection || !snapshot.dictationAvailable) return void 0;
|
|
2419
|
+
const { selection, maxDurationSeconds, maxAudioBytes } = catalog;
|
|
2420
|
+
const microphoneId = getMicrophoneDevice();
|
|
2421
|
+
return {
|
|
2422
|
+
maxDurationSeconds,
|
|
2423
|
+
constraints: {
|
|
2424
|
+
audio: {
|
|
2425
|
+
echoCancellation: true,
|
|
2426
|
+
noiseSuppression: true,
|
|
2427
|
+
...microphoneId && { deviceId: { exact: microphoneId } }
|
|
2428
|
+
},
|
|
2429
|
+
video: false
|
|
2430
|
+
},
|
|
2431
|
+
async transcribe(blob, signal) {
|
|
2432
|
+
if (blob.size > maxAudioBytes) {
|
|
2433
|
+
const error = new Error("Recording is too large");
|
|
2434
|
+
error.code = "btw/recording-too-large";
|
|
2435
|
+
throw error;
|
|
2436
|
+
}
|
|
2437
|
+
signal.throwIfAborted();
|
|
2438
|
+
const audioBase64 = base64(new Uint8Array(await blob.arrayBuffer()));
|
|
2439
|
+
signal.throwIfAborted();
|
|
2440
|
+
return unwrap(await speech.transcribe({ audioBase64, ...selection }, signal)).text;
|
|
2441
|
+
}
|
|
2442
|
+
};
|
|
2443
|
+
},
|
|
2444
|
+
dispose() {
|
|
2445
|
+
disposed = true;
|
|
2446
|
+
disposeSelection();
|
|
2447
|
+
disposeInventory();
|
|
2448
|
+
closeTabs(session);
|
|
2449
|
+
for (const controller of activeStreams) controller.abort();
|
|
2450
|
+
listeners.clear();
|
|
2451
|
+
}
|
|
2452
|
+
};
|
|
2453
|
+
}
|
|
2454
|
+
function makeSource(controller, t, icon) {
|
|
2455
|
+
const command = "btw";
|
|
2456
|
+
const localizedCommand = "侧问";
|
|
2457
|
+
const supportedCommands = /* @__PURE__ */ new Set([command, localizedCommand]);
|
|
2458
|
+
const claim = (sessionId, spelling) => ({
|
|
2459
|
+
claim: {
|
|
2460
|
+
name: command,
|
|
2461
|
+
token: `/${spelling} `,
|
|
2462
|
+
hint: t("commandHint"),
|
|
2463
|
+
attachments: false,
|
|
2464
|
+
async submit(args) {
|
|
2465
|
+
const question2 = args.trim();
|
|
2466
|
+
if (question2) {
|
|
2467
|
+
try {
|
|
2468
|
+
await controller.createCard(sessionId, question2);
|
|
2469
|
+
} catch (error) {
|
|
2470
|
+
switch (error?.code) {
|
|
2471
|
+
case "btw/session-not-saved":
|
|
2472
|
+
return { kind: "error", text: t("sessionNotSaved") };
|
|
2473
|
+
case "btw/model-unavailable":
|
|
2474
|
+
return { kind: "error", text: t("modelUnavailable") };
|
|
2475
|
+
case "btw/save-failed":
|
|
2476
|
+
return { kind: "error", text: t("saveFailed") };
|
|
2477
|
+
default:
|
|
2478
|
+
throw error;
|
|
2479
|
+
}
|
|
2480
|
+
}
|
|
2481
|
+
} else if (!controller.openList(sessionId)) {
|
|
2482
|
+
return { kind: "error", text: t("sidebarUnavailable") };
|
|
2483
|
+
}
|
|
2484
|
+
return { kind: "success" };
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
});
|
|
2488
|
+
return {
|
|
2489
|
+
trigger: "/",
|
|
2490
|
+
name: plugin,
|
|
2491
|
+
showGroupTitle: false,
|
|
2492
|
+
async candidates(_session, { query, position }) {
|
|
2493
|
+
const label = t("commandLabel");
|
|
2494
|
+
const search = query.toLowerCase();
|
|
2495
|
+
return position === "leading" && (command.startsWith(search) || label.toLowerCase().startsWith(search)) ? [{ name: command, label, description: t("commandDescription"), icon }] : [];
|
|
2496
|
+
},
|
|
2497
|
+
onPick({ session, position, candidate }) {
|
|
2498
|
+
if (position === "leading" && candidate.name === command) {
|
|
2499
|
+
const preferred = t("commandSpelling");
|
|
2500
|
+
return claim(session.sessionId, supportedCommands.has(preferred) ? preferred : command);
|
|
2501
|
+
}
|
|
2502
|
+
},
|
|
2503
|
+
async matchClaim(session, token, signal) {
|
|
2504
|
+
signal.throwIfAborted();
|
|
2505
|
+
const spelling = token.slice(1);
|
|
2506
|
+
if (token.startsWith("/") && supportedCommands.has(spelling)) return claim(session.sessionId, spelling).claim;
|
|
2507
|
+
},
|
|
2508
|
+
async matchEnter(session, line, signal, envelope) {
|
|
2509
|
+
const spelling = /^\/(\S+)/u.exec(line)?.[1];
|
|
2510
|
+
if (!supportedCommands.has(spelling)) return void 0;
|
|
2511
|
+
signal.throwIfAborted();
|
|
2512
|
+
if (envelope.attachments) throw new Error(t("textOnly"));
|
|
2513
|
+
return claim(session.sessionId, spelling);
|
|
2514
|
+
}
|
|
2515
|
+
};
|
|
2516
|
+
}
|
|
2517
|
+
async function mountClient(ctx, React) {
|
|
2518
|
+
const disposeRemote = await ctx.remote.$mount(TYPERT_REMOTE);
|
|
2519
|
+
ctx.effect(() => disposeRemote);
|
|
2520
|
+
await ctx.inject(["remote", "remote.btw"], (scope) => mountFeatures(scope, React));
|
|
2521
|
+
}
|
|
2522
|
+
function mountFeatures(ctx, React) {
|
|
2523
|
+
ctx.effect(() => ctx.locale.register(namespace, { en: en_default.ui, zh: zh_default.ui }));
|
|
2524
|
+
const t = ctx.locale.bind(namespace);
|
|
2525
|
+
const controller = makeController(ctx);
|
|
2526
|
+
ctx.effect(() => controller.dispose);
|
|
2527
|
+
const { Dock, Pane, CommandIcon } = createViews(React);
|
|
2528
|
+
ctx.effect(() => ctx.sidebarRightTabs.register({ id: plugin, kind: tabKind, title: () => t("title") }));
|
|
2529
|
+
ctx.effect(() => ctx.slots.inject("conversation.input.dock", () => ctx.slots.register({
|
|
2530
|
+
name: "conversation.input.dock",
|
|
2531
|
+
id: "kabxx-btw-dock",
|
|
2532
|
+
order: 30,
|
|
2533
|
+
locale: namespace
|
|
2534
|
+
}, (props) => {
|
|
2535
|
+
React.useLayoutEffect(() => {
|
|
2536
|
+
controller.pruneRestored();
|
|
2537
|
+
}, [props.sessionId]);
|
|
2538
|
+
return React.createElement(Dock, { ...props, controller, t: props.t ?? t });
|
|
2539
|
+
})));
|
|
2540
|
+
ctx.effect(() => ctx.slots.inject("sidebar.right.pane.tab", () => ctx.slots.register({
|
|
2541
|
+
name: "sidebar.right.pane.tab",
|
|
2542
|
+
key: plugin,
|
|
2543
|
+
locale: namespace
|
|
2544
|
+
}, (props) => {
|
|
2545
|
+
const snapshot = React.useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
|
|
2546
|
+
React.useLayoutEffect(() => {
|
|
2547
|
+
controller.pruneRestored();
|
|
2548
|
+
}, [props.sessionId]);
|
|
2549
|
+
if (snapshot.pane?.sessionId !== props.sessionId) return null;
|
|
2550
|
+
return React.createElement(Pane, { ...props, controller, t: props.t ?? t });
|
|
2551
|
+
})));
|
|
2552
|
+
ctx.effect(() => ctx.inputTriggers.registerSource(makeSource(controller, t, CommandIcon)));
|
|
2553
|
+
ctx.inject(["configForms"], (scope) => {
|
|
2554
|
+
scope.effect(() => {
|
|
2555
|
+
const chatSettings = scope.configForms.get("ui-chat");
|
|
2556
|
+
const sync = () => controller.setPerformanceUsage(chatSettings.getSnapshot().value?.performanceUsage);
|
|
2557
|
+
const unsubscribe = chatSettings.subscribe(sync);
|
|
2558
|
+
sync();
|
|
2559
|
+
return () => {
|
|
2560
|
+
unsubscribe();
|
|
2561
|
+
controller.setPerformanceUsage(defaultPerformanceUsage);
|
|
2562
|
+
};
|
|
2563
|
+
});
|
|
2564
|
+
});
|
|
2565
|
+
ctx.inject(["pluginNavigation"], (scope) => {
|
|
2566
|
+
scope.effect(() => {
|
|
2567
|
+
const navigation = scope.pluginNavigation;
|
|
2568
|
+
controller.setSpeechSettings(() => navigation.openBundle(voiceBundle));
|
|
2569
|
+
return () => controller.setSpeechSettings(null);
|
|
2570
|
+
});
|
|
2571
|
+
});
|
|
2572
|
+
ctx.inject(["remote.speech"], (scope) => {
|
|
2573
|
+
scope.effect(() => {
|
|
2574
|
+
const abort = new AbortController();
|
|
2575
|
+
const speech = scope.remote.speech;
|
|
2576
|
+
controller.setSpeechCatalog(void 0, speech);
|
|
2577
|
+
const stream = speech.follow(abort.signal);
|
|
2578
|
+
void (async () => {
|
|
2579
|
+
try {
|
|
2580
|
+
for await (const catalog of stream) {
|
|
2581
|
+
if (!abort.signal.aborted) controller.setSpeechCatalog(catalog, speech);
|
|
2582
|
+
}
|
|
2583
|
+
} catch {
|
|
2584
|
+
if (!abort.signal.aborted) controller.setSpeechCatalog(void 0, speech);
|
|
2585
|
+
}
|
|
2586
|
+
})();
|
|
2587
|
+
return () => {
|
|
2588
|
+
abort.abort();
|
|
2589
|
+
stream.dispose?.();
|
|
2590
|
+
controller.setSpeechCatalog(void 0);
|
|
2591
|
+
};
|
|
2592
|
+
});
|
|
2593
|
+
});
|
|
2594
|
+
}
|
|
2595
|
+
return __toCommonJS(index_exports);
|
|
2596
|
+
})();
|
|
2597
|
+
|
|
2598
|
+
return { inject: BTW.inject, apply: ctx => BTW.mountClient(ctx, require('react')) };
|
|
2599
|
+
},
|
|
2600
|
+
});
|