@kabxx/dsh-btw 0.0.0-stage → 0.1.1

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