@kabxx/dsh-btw 0.1.0 → 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 CHANGED
@@ -27,12 +27,22 @@ var BTW = (() => {
27
27
  makeController: () => makeController,
28
28
  makeSource: () => makeSource,
29
29
  mountClient: () => mountClient,
30
+ observeSpeech: () => observeSpeech,
30
31
  unwrap: () => unwrap
31
32
  });
32
33
 
33
34
  // src/shared/wire.js
34
35
  var PACKAGE_NAME = "@kabxx/dsh-btw";
35
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
+ });
36
46
  var STATUSES = /* @__PURE__ */ new Set(["generating", "completed", "failed", "interrupted"]);
37
47
  var TOKEN_FIELDS = ["inputTokens", "outputTokens", "totalTokens", "cacheReadTokens", "cacheWriteTokens", "reasoningTokens"];
38
48
  var THREAD_ID = /^btw-[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/u;
@@ -49,6 +59,9 @@ var BTW = (() => {
49
59
  function parseQuestion(value) {
50
60
  return checked(value, typeof value === "string" && value.trim() !== "", "question");
51
61
  }
62
+ function parseSubmissionId(value) {
63
+ return checked(value, typeof value === "string" && /^[\da-f]{32}$/u.test(value), "submissionId");
64
+ }
52
65
  function parseVersion(value) {
53
66
  return checked(value, Number.isSafeInteger(value) && value >= 1, "version");
54
67
  }
@@ -83,8 +96,11 @@ var BTW = (() => {
83
96
  const firstTokenMs = timestamp(value.firstTokenMs);
84
97
  return checked({ requestMs, firstTokenMs }, firstTokenMs <= requestMs, "first token timing");
85
98
  }
99
+ function parseOutputLimit(value) {
100
+ return checked(value.outputLimitReached, value.outputLimitReached === true && value.status === "completed", "output limit");
101
+ }
86
102
  function parseTurn(value) {
87
- object(value, ["question", "reply", "status", "createdAt", "finishedAt", "error", "saveError", "usage", "timing"]);
103
+ object(value, ["question", "reply", "status", "createdAt", "finishedAt", "error", "saveError", "outputLimitReached", "usage", "timing"]);
88
104
  const turn = {
89
105
  question: parseQuestion(value.question),
90
106
  reply: checked(value.reply, typeof value.reply === "string", "reply"),
@@ -95,6 +111,7 @@ var BTW = (() => {
95
111
  else checked(value.finishedAt, value.finishedAt === void 0, "finishedAt");
96
112
  if (value.error !== void 0) turn.error = checked(value.error, typeof value.error === "string", "error");
97
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);
98
115
  if (value.usage !== void 0) turn.usage = parseUsage(value.usage);
99
116
  if (value.timing !== void 0) turn.timing = parseTiming(value.timing);
100
117
  return turn;
@@ -126,21 +143,19 @@ var BTW = (() => {
126
143
  function parsePosition(value) {
127
144
  return checked(value, Number.isSafeInteger(value) && value >= 0, "position");
128
145
  }
129
- function appendTurn(detail2, receipt2) {
130
- if (detail2.id !== receipt2.id || detail2.sessionId !== receipt2.sessionId || receipt2.turnIndex !== detail2.turns.length || receipt2.version <= detail2.version) return detail2;
131
- return { ...detail2, updatedAt: receipt2.updatedAt, version: receipt2.version, turns: [...detail2.turns, receipt2.turn] };
132
- }
133
146
  function applyReply(detail2, turnIndex, update) {
134
147
  const turn = detail2.turns[turnIndex];
135
- if (!turn || turn.status !== "generating" || update.version <= detail2.version) return detail2;
136
- checked(update.offset <= turn.reply.length, "reply offset");
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");
137
151
  const turns = [...detail2.turns];
138
152
  turns[turnIndex] = {
139
- ...turn,
153
+ ...previous,
140
154
  reply: turn.reply.slice(0, update.offset) + update.text,
141
155
  status: update.status,
142
156
  ...update.finishedAt !== void 0 && { finishedAt: update.finishedAt },
143
157
  ...update.error !== void 0 && { error: update.error },
158
+ ...update.outputLimitReached !== void 0 && { outputLimitReached: update.outputLimitReached },
144
159
  ...update.saveError !== void 0 && { saveError: update.saveError },
145
160
  ...update.usage !== void 0 && { usage: update.usage },
146
161
  ...update.timing !== void 0 && { timing: update.timing }
@@ -158,11 +173,9 @@ var BTW = (() => {
158
173
  turn: parseTurn(value.turn)
159
174
  };
160
175
  }
161
- function parseReplyUpdate(value) {
162
- object(value, ["version", "updatedAt", "offset", "text", "status", "finishedAt", "error", "saveError", "usage", "timing"]);
176
+ var replyFields = ["offset", "text", "status", "finishedAt", "error", "saveError", "outputLimitReached", "usage", "timing"];
177
+ function parseReply(value) {
163
178
  const update = {
164
- version: parseVersion(value.version),
165
- updatedAt: timestamp(value.updatedAt),
166
179
  offset: parsePosition(value.offset),
167
180
  text: checked(value.text, typeof value.text === "string", "text"),
168
181
  status: status(value.status)
@@ -170,11 +183,32 @@ var BTW = (() => {
170
183
  if (update.status !== "generating") update.finishedAt = timestamp(value.finishedAt);
171
184
  else checked(value.finishedAt, value.finishedAt === void 0, "finishedAt");
172
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);
173
187
  if (value.saveError !== void 0) update.saveError = checked(value.saveError, typeof value.saveError === "string", "saveError");
174
188
  if (value.usage !== void 0) update.usage = parseUsage(value.usage);
175
189
  if (value.timing !== void 0) update.timing = parseTiming(value.timing);
176
190
  return update;
177
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
+ }
178
212
  var detail = codec(`${PACKAGE_NAME}#Detail`, parseDetail);
179
213
  var receipt = codec(`${PACKAGE_NAME}#FollowupReceipt`, parseReceipt);
180
214
  var replyUpdate = codec(`${PACKAGE_NAME}#ReplyUpdate`, parseReplyUpdate);
@@ -219,8 +253,29 @@ var BTW = (() => {
219
253
  descriptor("watch", [id, version], detail, true),
220
254
  descriptor("watchReply", [id, parameter("turnIndex", parsePosition), version], replyUpdate, true)
221
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
+ }
222
274
  var contextDescriptor = descriptor("contextCapacity", [id], codec(`${PACKAGE_NAME}#ContextWindow`, parseContext));
223
- var TYPERT_REMOTE = Object.freeze({ package: PACKAGE_NAME, descriptors: Object.freeze([...descriptors, contextDescriptor]) });
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]) });
224
279
 
225
280
  // src/client/views.js
226
281
  var styles = String.raw`
@@ -530,9 +585,48 @@ var BTW = (() => {
530
585
  .dsh-btw-context-track, .dsh-btw-context-fill { fill: none; stroke-width: 2; }
531
586
  .dsh-btw-context-track { stroke: var(--dsw-alias-border-l3); }
532
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
+ }
533
597
  .dsh-btw-feedback { margin: 6px 8px; font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-secondary); }
534
598
  .dsh-btw-turn-feedback { margin: 3px 0 0; }
535
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; }
536
630
  .dsh-btw-retry {
537
631
  margin-inline-start: 6px;
538
632
  padding: 2px 6px;
@@ -718,21 +812,72 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
718
812
  function isRunning(status2) {
719
813
  return status2 === "generating" || status2 === "running" || status2 === "streaming" || status2 === "pending";
720
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
+ }
721
867
  function summarizeUsage(turns) {
722
868
  let uncached = 0;
723
869
  let cacheRead = 0;
724
870
  let cacheWrite = 0;
725
871
  let output = 0;
726
- let totalOnly = 0;
872
+ let total = 0;
727
873
  for (const { usage, status: status2 } of turns) {
728
874
  if (!usage || isRunning(status2)) continue;
729
- uncached += usage.inputTokens ?? 0;
730
- cacheRead += usage.cacheReadTokens ?? 0;
731
- cacheWrite += usage.cacheWriteTokens ?? 0;
732
- output += usage.outputTokens ?? 0;
733
- if (usage.inputTokens === void 0 && usage.cacheReadTokens === void 0 && usage.cacheWriteTokens === void 0 && usage.outputTokens === void 0) {
734
- totalOnly += usage.totalTokens ?? 0;
735
- }
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;
736
881
  }
737
882
  const prompt = uncached + cacheRead + cacheWrite;
738
883
  return {
@@ -740,10 +885,25 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
740
885
  cacheRead,
741
886
  cacheWrite,
742
887
  output,
743
- total: prompt + output + totalOnly,
888
+ total,
744
889
  cacheRatio: prompt > 0 ? cacheRead / prompt : null
745
890
  };
746
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
+ }
747
907
  function formatTokenCount(value) {
748
908
  const format = (amount) => String(amount >= 100 ? Math.round(amount) : Math.round(amount * 10) / 10);
749
909
  if (value < 1e3) return String(value);
@@ -900,9 +1060,10 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
900
1060
  } : { subscribe: noSubscribe, getSnapshot: () => emptySnapshot }, [controller]);
901
1061
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
902
1062
  }
903
- function SideQuestionIcon({ className, size = 14 }) {
1063
+ function SideQuestionIcon({ className, size = 14, style }) {
904
1064
  return h("svg", {
905
1065
  className,
1066
+ style,
906
1067
  width: size,
907
1068
  height: size,
908
1069
  viewBox: "0 0 24 24",
@@ -915,6 +1076,10 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
915
1076
  focusable: false
916
1077
  }, sideQuestionPaths.map((path) => h("path", { key: path, d: path })));
917
1078
  }
1079
+ function TabTitle({ useTabInfo }) {
1080
+ const { tab } = useTabInfo();
1081
+ return h(Fragment, null, h(SideQuestionIcon, { size: 16, style: { flex: "none" } }), tab.title);
1082
+ }
918
1083
  function WaitingSpinner() {
919
1084
  return h("svg", {
920
1085
  ref: syncSpinner,
@@ -960,6 +1125,9 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
960
1125
  message ? formatMessageTime(value, language) : date.text
961
1126
  );
962
1127
  }
1128
+ function LoadingNote({ t }) {
1129
+ return h("p", { className: "dsh-btw-loading-note", role: "status" }, t("loading"));
1130
+ }
963
1131
  function Feedback({ text, onRetry, t, error = false, inline = false, id: id2 }) {
964
1132
  return h(
965
1133
  "div",
@@ -968,6 +1136,19 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
968
1136
  onRetry && h("button", { type: "button", className: "dsh-btw-retry", onClick: onRetry }, t("retry"))
969
1137
  );
970
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
+ }
971
1152
  function Markdown({ text, running, renderFactorySlot }) {
972
1153
  const fallback = h("div", { className: "dsh-btw-plain" }, text);
973
1154
  return renderFactorySlot?.("conversation.chat.reasoning.content", { text, running }, { fallback }) ?? fallback;
@@ -1032,11 +1213,11 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1032
1213
  const [open, setOpen] = useState(false);
1033
1214
  const trigger = useRef(null);
1034
1215
  const id2 = useId();
1035
- const { uncached, cacheRead, cacheWrite, output, total, cacheRatio } = summarizeUsage([turn]);
1216
+ const { uncached, cacheRead, cacheWrite, output, total } = summarizeUsage([turn]);
1036
1217
  const enabled = performanceUsage !== "compact" && total > 0;
1037
1218
  const number = new Intl.NumberFormat(language || void 0);
1038
1219
  const reading = t("auditSpent", { total: `${formatTokenCount(total)} tok` });
1039
- const cache = formatCacheRatio(cacheRatio, language, 1);
1220
+ const cache = formatCacheRatio(turnCacheRatio(turn.usage), language, 1);
1040
1221
  const rows = [[t("auditTotal"), number.format(total)]];
1041
1222
  if (cache !== null) rows.push([t("auditCacheHit"), cache]);
1042
1223
  if (turn.usage?.inputTokens !== void 0) rows.push([t("auditInput"), number.format(uncached)]);
@@ -1107,19 +1288,24 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1107
1288
  );
1108
1289
  }
1109
1290
  const overflow = turn?.error === CONTEXT_OVERFLOW;
1110
- const failure = overflow ? "contextOverflow" : state || (!text.trim() ? "replyFailed" : "");
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;
1111
1294
  return h(
1112
1295
  Fragment,
1113
1296
  null,
1114
1297
  text && h(Markdown, { text, running, renderFactorySlot }),
1115
- failure && h(Feedback, {
1298
+ failure && h(ReplyStatus, {
1116
1299
  id: overflow ? overflowNotice : void 0,
1117
- text: t(failure),
1118
- t,
1119
- error: overflow || failure === "replyFailed",
1120
- inline: true
1300
+ title: t(failure),
1301
+ detail: detailKey ? t(detailKey) : void 0
1121
1302
  }),
1122
- turn?.saveError && h(Feedback, { text: t("archiveWriteFailed"), t, error: true, inline: true }),
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") }),
1123
1309
  !inline && !running && text && h(ReplyActions, { turn, t, language, performanceUsage })
1124
1310
  );
1125
1311
  }
@@ -1134,8 +1320,9 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1134
1320
  const current = acceptDetail(liveDetail, detail2.version > liveDetail.version ? detail2 : null);
1135
1321
  const firstTurn = current.turns[0];
1136
1322
  const running = isRunning(firstTurn?.status);
1323
+ const watching = running || Boolean(firstTurn?.saveError);
1137
1324
  useEffect(() => {
1138
- if (!running) return void 0;
1325
+ if (!watching) return void 0;
1139
1326
  let mounted = true;
1140
1327
  let close;
1141
1328
  setFailed(false);
@@ -1154,7 +1341,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1154
1341
  mounted = false;
1155
1342
  close?.();
1156
1343
  };
1157
- }, [controller, id2, retry, running, sessionId]);
1344
+ }, [controller, id2, retry, watching, sessionId]);
1158
1345
  return h(
1159
1346
  "article",
1160
1347
  { className: "dsh-btw-card", "aria-label": t("title") },
@@ -1176,12 +1363,12 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1176
1363
  }),
1177
1364
  h(IconButton, { icon: "open", label: t("openSidebar"), onClick: () => {
1178
1365
  try {
1179
- setSidebarFailed(controller.openDetail(sessionId, id2) === false);
1366
+ setSidebarFailed(!controller.moveCardToSidebar(sessionId, id2));
1180
1367
  } catch {
1181
1368
  setSidebarFailed(true);
1182
1369
  }
1183
1370
  } }),
1184
- h(IconButton, { icon: "close", label: t("dismiss"), onClick: () => controller.dismiss(sessionId) })
1371
+ h(IconButton, { icon: "close", label: t("dismiss"), onClick: () => controller.dismiss(sessionId, id2) })
1185
1372
  )
1186
1373
  ),
1187
1374
  sidebarFailed && h(Feedback, { text: t("sidebarUnavailable"), t, error: true }),
@@ -1190,7 +1377,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1190
1377
  Fragment,
1191
1378
  null,
1192
1379
  firstTurn && h(Reply, { turn: firstTurn, t, renderFactorySlot, inline: true, streamFailed: failed }),
1193
- running && failed && h(Feedback, {
1380
+ (running || firstTurn?.saveError) && failed && h(Feedback, {
1194
1381
  text: t("streamFailed"),
1195
1382
  t,
1196
1383
  inline: true,
@@ -1216,13 +1403,17 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1216
1403
  card && h(DockCard, { key: card.id, detail: card, controller, sessionId, t, renderFactorySlot })
1217
1404
  );
1218
1405
  }
1219
- function List({ controller, sessionId, t, language, focusId, listRevision }) {
1406
+ function List({ controller, sessionId, t, language, focusId, listRevision, onOpen }) {
1220
1407
  const [load, setLoad] = useState({});
1221
1408
  const [retry, setRetry] = useState(0);
1222
1409
  const scroller = useRef(null);
1223
1410
  const positioned = useRef(false);
1224
1411
  const focusTarget = useRef(null);
1412
+ const heading = useRef(null);
1225
1413
  const scopeId = useId();
1414
+ useLayoutEffect(() => {
1415
+ if (focusId) heading.current?.focus({ preventScroll: true });
1416
+ }, [focusId]);
1226
1417
  useEffect(() => {
1227
1418
  let alive = true;
1228
1419
  Promise.resolve().then(() => controller.call("list", sessionId)).then((rows) => {
@@ -1240,7 +1431,8 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1240
1431
  positioned.current = true;
1241
1432
  list.scrollTop = list.scrollHeight;
1242
1433
  const previousRow = focusTarget.current;
1243
- if (focusId && previousRow) {
1434
+ const title = heading.current;
1435
+ if (focusId && previousRow && title?.ownerDocument.activeElement === title) {
1244
1436
  const rowBounds = previousRow.getBoundingClientRect();
1245
1437
  const listBounds = list.getBoundingClientRect();
1246
1438
  const visible = rowBounds.top >= listBounds.top && rowBounds.bottom <= listBounds.bottom;
@@ -1258,20 +1450,19 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1258
1450
  h(
1259
1451
  "header",
1260
1452
  { className: "dsh-btw-bar" },
1261
- h(SideQuestionIcon, { className: "dsh-btw-mark" }),
1262
- h("h2", { id: scopeId, className: "dsh-btw-bar-title" }, t("listTitle"))
1453
+ h("h2", { id: scopeId, ref: heading, tabIndex: -1, className: "dsh-btw-bar-title" }, t("listTitle"))
1263
1454
  ),
1264
1455
  h(
1265
1456
  "section",
1266
1457
  { className: "dsh-btw-list", ref: scroller, "aria-labelledby": scopeId },
1267
- load.failed ? h(Feedback, { text: t("loadFailed"), t, onRetry: reload, error: true }) : !load.rows ? h(Feedback, { text: t("loading"), t }) : load.rows.length === 0 ? h(Feedback, { text: t("emptyList"), t }) : h("ul", { className: "dsh-btw-history" }, load.rows.map((row) => h("li", { key: row.id }, h(
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(
1268
1459
  "button",
1269
1460
  {
1270
1461
  type: "button",
1271
1462
  className: "dsh-btw-row",
1272
1463
  title: row.question,
1273
1464
  ref: focusId === row.id ? focusTarget : null,
1274
- onClick: () => controller.navigate(sessionId, row.id)
1465
+ onClick: () => onOpen(row.id)
1275
1466
  },
1276
1467
  h("span", { className: "dsh-btw-row-text" }, row.question),
1277
1468
  h("span", { className: "dsh-btw-row-time" }, h(Time, { value: row.createdAt ?? row.updatedAt, language })),
@@ -1280,53 +1471,26 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1280
1471
  )
1281
1472
  );
1282
1473
  }
1283
- function useDetail({ controller, sessionId, id: id2, revision, reload }) {
1474
+ function useDetail({ controller, sessionId, id: id2, revision }) {
1284
1475
  const [loaded, setLoaded] = useState(null);
1285
1476
  const [failure, setFailure] = useState("");
1286
1477
  const [contextSample, setContextSample] = useState(null);
1287
- const detail2 = loaded?.revision === revision ? loaded.detail : void 0;
1478
+ const detail2 = loaded?.detail;
1288
1479
  const context = contextSample?.revision === revision ? contextSample.value : null;
1289
- const turnIndex = detail2 ? detail2.turns.length - 1 : -1;
1290
- const running = isRunning(detail2?.turns[turnIndex]?.status);
1291
1480
  useEffect(() => {
1292
- let alive = true;
1293
1481
  setFailure("");
1294
- Promise.resolve().then(() => controller.call("get", sessionId, id2)).then((next) => {
1295
- if (!alive) return;
1296
- if (next?.id === id2 && next.sessionId === sessionId) setLoaded({ detail: next, revision });
1297
- else setFailure("missingThread");
1298
- }, () => {
1299
- if (alive) setFailure("loadFailed");
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
1300
1491
  });
1301
- return () => {
1302
- alive = false;
1303
- };
1304
1492
  }, [controller, id2, revision, sessionId]);
1305
- useEffect(() => {
1306
- if (turnIndex < 0) return void 0;
1307
- const request = new AbortController();
1308
- Promise.resolve().then(() => controller.call("contextCapacity", sessionId, id2, request.signal)).then((result) => {
1309
- if (!request.signal.aborted) setContextSample({ revision, value: result });
1310
- }, () => {
1311
- });
1312
- return () => request.abort();
1313
- }, [controller, id2, revision, running, sessionId, turnIndex]);
1314
- useEffect(() => {
1315
- if (!running) return void 0;
1316
- return controller.watchReply(sessionId, id2, turnIndex, detail2.version, (update) => {
1317
- setLoaded((previous) => previous?.revision === revision ? { ...previous, detail: applyReply(previous.detail, turnIndex, update) } : previous);
1318
- }, () => setFailure("streamFailed"));
1319
- }, [controller, id2, revision, running, sessionId, turnIndex]);
1320
- function accept(receipt2) {
1321
- const next = appendTurn(detail2, receipt2);
1322
- if (next === detail2) {
1323
- reload();
1324
- return;
1325
- }
1326
- setFailure("");
1327
- setLoaded({ detail: next, revision });
1328
- }
1329
- return { detail: detail2, context, failure, accept };
1493
+ return { detail: detail2, context, failure, synchronized: loaded?.revision === revision && !failure };
1330
1494
  }
1331
1495
  function Thread({ detail: detail2, renderFactorySlot, t, language, scrollRef, followRef, streamFailed, performanceUsage, overflowNotice }) {
1332
1496
  useLayoutEffect(() => {
@@ -1370,7 +1534,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1370
1534
  );
1371
1535
  }));
1372
1536
  }
1373
- function useDictation(enabled, controller, insert) {
1537
+ function useDictation(locked, controller, insert) {
1374
1538
  const active = useRef(null);
1375
1539
  const [phase, setPhase] = useState("");
1376
1540
  const stop = useCallback(() => {
@@ -1384,7 +1548,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1384
1548
  setPhase("");
1385
1549
  }, [stop]);
1386
1550
  useEffect(() => {
1387
- if (!enabled) {
1551
+ if (locked) {
1388
1552
  cancel();
1389
1553
  return void 0;
1390
1554
  }
@@ -1409,7 +1573,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1409
1573
  document.removeEventListener("keydown", escape);
1410
1574
  stop();
1411
1575
  };
1412
- }, [enabled, cancel, stop]);
1576
+ }, [locked, cancel, stop]);
1413
1577
  async function finish(capture) {
1414
1578
  if (active.current !== capture || capture.phase !== "micRecording") return;
1415
1579
  capture.phase = "micTranscribing";
@@ -1444,7 +1608,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1444
1608
  }
1445
1609
  }
1446
1610
  async function toggle(selection) {
1447
- if (!enabled) return;
1611
+ if (locked) return;
1448
1612
  if (active.current) {
1449
1613
  if (active.current.phase === "micRecording") await finish(active.current);
1450
1614
  return;
@@ -1506,20 +1670,16 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1506
1670
  dictationAvailable,
1507
1671
  speechMounted,
1508
1672
  speechSettings,
1509
- onSent
1673
+ draftState
1510
1674
  }) {
1511
- const [draft, setDraft] = useState("");
1512
- const [saving, setSaving] = useState(false);
1513
- const [error, setError] = useState("");
1675
+ const { text: draft, saving, error } = draftState;
1514
1676
  const [micHelp, setMicHelp] = useState("");
1515
1677
  const [retainedTranscript, setRetainedTranscript] = useState("");
1516
1678
  const input = useRef(null);
1517
1679
  const form = useRef(null);
1518
- const composing = useRef(false);
1680
+ const [composition] = useState(createCompositionGuard);
1519
1681
  const pendingTranscript = useRef(null);
1520
1682
  const selectionAfterInsert = useRef(null);
1521
- const draftRevision = useRef(0);
1522
- const submitting = useRef(false);
1523
1683
  const live = useRef(false);
1524
1684
  const inputId = useId();
1525
1685
  useEffect(() => {
@@ -1531,11 +1691,11 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1531
1691
  function insertSpeech(text, selection) {
1532
1692
  const node = input.current;
1533
1693
  if (!node || node.disabled) return;
1534
- if (composing.current) {
1694
+ if (composition.active()) {
1535
1695
  pendingTranscript.current = { text, selection };
1536
1696
  return;
1537
1697
  }
1538
- if (selection.revision !== draftRevision.current) {
1698
+ if (selection.revision !== controller.getDraft(sessionId, id2).revision) {
1539
1699
  setRetainedTranscript(text);
1540
1700
  return;
1541
1701
  }
@@ -1547,12 +1707,11 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1547
1707
  return;
1548
1708
  }
1549
1709
  selectionAfterInsert.current = cursor;
1550
- draftRevision.current += 1;
1551
- setDraft(next);
1710
+ controller.setDraft(sessionId, id2, next);
1552
1711
  }
1553
1712
  const canRecord = typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getUserMedia) && typeof MediaRecorder !== "undefined" && typeof OfflineAudioContext !== "undefined";
1554
1713
  const locked = overflowed || error === "contextOverflow";
1555
- const dictation = useDictation(!locked && dictationAvailable && canRecord, controller, insertSpeech);
1714
+ const dictation = useDictation(locked, controller, insertSpeech);
1556
1715
  useEffect(() => {
1557
1716
  if (dictationAvailable) setMicHelp((current) => current === "micSetup" ? "" : current);
1558
1717
  }, [dictationAvailable]);
@@ -1587,27 +1746,11 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1587
1746
  observer.observe(element);
1588
1747
  return () => observer.disconnect();
1589
1748
  }, [resize]);
1590
- async function submit(event) {
1749
+ function submit(event) {
1591
1750
  event.preventDefault();
1592
- if (sendBlocked || submitting.current || composing.current) return;
1593
- const revision = draftRevision.current;
1594
- submitting.current = true;
1595
- setSaving(true);
1596
- setError("");
1597
- try {
1598
- const detail2 = await controller.call("followup", sessionId, id2, draft);
1599
- if (!live.current) return;
1600
- if (draftRevision.current === revision) {
1601
- draftRevision.current += 1;
1602
- setDraft("");
1603
- }
1604
- onSent(detail2);
1605
- } catch (failure) {
1606
- if (live.current) setError(failure?.code === "btw/context-overflow" ? "contextOverflow" : "sendFailed");
1607
- } finally {
1608
- submitting.current = false;
1609
- if (live.current) setSaving(false);
1610
- }
1751
+ if (sendBlocked || composition.blocksSubmit(event)) return;
1752
+ void controller.submitDraft(sessionId, id2).catch(() => {
1753
+ });
1611
1754
  }
1612
1755
  function keyDown(event) {
1613
1756
  if (event.key === "Escape" && dictating) {
@@ -1615,12 +1758,12 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1615
1758
  event.stopPropagation();
1616
1759
  dictation.cancel();
1617
1760
  }
1618
- if (locked || event.key !== "Enter" || event.shiftKey || composing.current || event.nativeEvent.isComposing || event.keyCode === 229) return;
1761
+ if (locked || !isFollowupSubmitKey(event) || composition.blocksSubmit(event)) return;
1619
1762
  event.preventDefault();
1620
1763
  if (!sendBlocked && !event.repeat) form.current?.requestSubmit();
1621
1764
  }
1622
1765
  function finishComposition() {
1623
- composing.current = false;
1766
+ composition.end();
1624
1767
  const pending = pendingTranscript.current;
1625
1768
  pendingTranscript.current = null;
1626
1769
  if (pending && !locked) queueMicrotask(() => {
@@ -1629,6 +1772,10 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1629
1772
  }
1630
1773
  function toggleMic() {
1631
1774
  if (locked || saving) return;
1775
+ if (dictation.phase === "micRecording") {
1776
+ void dictation.toggle();
1777
+ return;
1778
+ }
1632
1779
  if (!dictationAvailable) {
1633
1780
  setMicHelp((current) => current === "micSetup" ? "" : "micSetup");
1634
1781
  return;
@@ -1641,19 +1788,15 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1641
1788
  const node = input.current;
1642
1789
  if (node) {
1643
1790
  setRetainedTranscript("");
1644
- void dictation.toggle({ start: node.selectionStart, end: node.selectionEnd, revision: draftRevision.current });
1791
+ void dictation.toggle({ start: node.selectionStart, end: node.selectionEnd, revision: controller.getDraft(sessionId, id2).revision });
1645
1792
  }
1646
1793
  }
1647
1794
  const composerOverflow = error === "contextOverflow" && !overflowed;
1648
1795
  return h(
1649
1796
  Fragment,
1650
1797
  null,
1651
- error && (!overflowed || error !== "contextOverflow") && h(Feedback, {
1652
- id: composerOverflow ? overflowNotice : void 0,
1653
- text: t(error),
1654
- t,
1655
- error: true
1656
- }),
1798
+ composerOverflow && h(ReplyStatus, { id: overflowNotice, title: t("contextOverflow"), detail: t("contextOverflowHint") }),
1799
+ error && error !== "contextOverflow" && h(Feedback, { text: t(error), t, error: true }),
1657
1800
  !locked && micHelp && h(
1658
1801
  "div",
1659
1802
  { className: "dsh-btw-feedback" },
@@ -1671,7 +1814,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1671
1814
  h("button", { type: "button", className: "dsh-btw-retry", onClick: () => {
1672
1815
  const node = input.current;
1673
1816
  if (!node) return;
1674
- insertSpeech(retainedTranscript, { start: node.selectionStart, end: node.selectionEnd, revision: draftRevision.current });
1817
+ insertSpeech(retainedTranscript, { start: node.selectionStart, end: node.selectionEnd, revision: controller.getDraft(sessionId, id2).revision });
1675
1818
  setRetainedTranscript("");
1676
1819
  } }, t("micInsert"))
1677
1820
  ),
@@ -1698,22 +1841,16 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1698
1841
  placeholder: t("placeholder"),
1699
1842
  value: draft,
1700
1843
  disabled: locked,
1701
- onChange: (event) => {
1702
- draftRevision.current += 1;
1703
- setDraft(event.target.value);
1704
- if (error) setError("");
1705
- },
1844
+ onChange: (event) => controller.setDraft(sessionId, id2, event.target.value),
1706
1845
  onKeyDown: keyDown,
1707
- onCompositionStart: () => {
1708
- composing.current = true;
1709
- },
1846
+ onCompositionStart: composition.start,
1710
1847
  onCompositionEnd: finishComposition
1711
1848
  }),
1712
1849
  h(
1713
1850
  "div",
1714
1851
  { className: "dsh-btw-form-actions" },
1715
1852
  !locked && dictating && h(IconButton, { icon: "close", label: t("micCancel"), onClick: dictation.cancel }),
1716
- speechMounted && h(IconButton, {
1853
+ (speechMounted || dictating) && h(IconButton, {
1717
1854
  className: "dsh-btw-mic",
1718
1855
  icon: dictation.phase === "micRecording" ? "stop" : "mic",
1719
1856
  label: t(dictation.phase === "micRecording" ? "micStop" : dictationAvailable ? "micStart" : "micSettings"),
@@ -1898,16 +2035,27 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1898
2035
  })
1899
2036
  );
1900
2037
  }
1901
- function Chat({ controller, sessionId, id: id2, t, renderFactorySlot, language, dictationAvailable, speechMounted, speechSettings, performanceUsage, focusHeading, onBack }) {
2038
+ function Chat({ controller, sessionId, id: id2, t, renderFactorySlot, language, dictationAvailable, speechMounted, speechSettings, performanceUsage, pane, onBack }) {
1902
2039
  const [revision, setRevision] = useState(0);
1903
2040
  const reload = () => setRevision((value) => value + 1);
1904
- const { detail: detail2, context, failure, accept } = useDetail({ controller, sessionId, id: id2, revision, reload });
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);
1905
2045
  const heading = useRef(null);
1906
2046
  const scroll = useRef(null);
1907
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]);
1908
2056
  useLayoutEffect(() => {
1909
- if (focusHeading) heading.current?.focus({ preventScroll: true });
1910
- }, [focusHeading]);
2057
+ if (!pane.restored) heading.current?.focus({ preventScroll: true });
2058
+ }, [pane]);
1911
2059
  const question2 = detail2?.question ?? t("title");
1912
2060
  const last = detail2?.turns.at(-1);
1913
2061
  const overflowed = last?.error === CONTEXT_OVERFLOW;
@@ -1922,7 +2070,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1922
2070
  h("h2", { className: "dsh-btw-bar-title", ref: heading, tabIndex: -1, title: question2 }, question2)
1923
2071
  ),
1924
2072
  failure && h(Feedback, { text: t(failure), t, error: true, onRetry: reload }),
1925
- !detail2 ? !failure && h(Feedback, { text: t("loading"), t }) : h(
2073
+ !detail2 ? !failure && h("div", { className: "dsh-btw-list" }, h(LoadingNote, { t })) : h(
1926
2074
  Fragment,
1927
2075
  null,
1928
2076
  h(Thread, {
@@ -1944,24 +2092,20 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1944
2092
  sessionId,
1945
2093
  id: id2,
1946
2094
  t,
1947
- busy: isRunning(last?.status),
2095
+ busy: !synchronized || isRunning(last?.status) || (draftState.receipt?.turnIndex ?? -1) >= detail2.turns.length,
1948
2096
  overflowed,
1949
2097
  overflowNotice,
1950
2098
  dictationAvailable,
1951
2099
  speechMounted,
1952
2100
  speechSettings,
1953
- onSent: (receipt2) => {
1954
- follow.current = true;
1955
- accept(receipt2);
1956
- }
2101
+ draftState
1957
2102
  }),
1958
2103
  h(UsageAudit, { turns: detail2.turns, contextSample: context, performanceUsage, t, language })
1959
2104
  )
1960
2105
  )
1961
2106
  );
1962
2107
  }
1963
- function OpenPane({ controller, sessionId, t, renderFactorySlot, pane, dictationAvailable, speechMounted, speechSettings, language, listRevision, performanceUsage }) {
1964
- const focusId = useRef(null);
2108
+ function OpenPane({ controller, sessionId, t, renderFactorySlot, pane, dictationAvailable, speechMounted, speechSettings, language, listRevision, performanceUsage, navigate }) {
1965
2109
  const id2 = pane.id;
1966
2110
  return h(
1967
2111
  "section",
@@ -1972,7 +2116,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1972
2116
  controller,
1973
2117
  sessionId,
1974
2118
  id: id2,
1975
- focusHeading: !pane.restored,
2119
+ pane,
1976
2120
  t,
1977
2121
  renderFactorySlot,
1978
2122
  language,
@@ -1980,24 +2124,33 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
1980
2124
  speechMounted,
1981
2125
  speechSettings,
1982
2126
  performanceUsage,
1983
- onBack: () => {
1984
- focusId.current = id2;
1985
- controller.navigate(sessionId, null);
1986
- }
1987
- }) : h(List, { key: pane.listOpenedAt, controller, sessionId, t, language, focusId: focusId.current, listRevision })
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
+ })
1988
2138
  );
1989
2139
  }
1990
- function Pane({ controller, sessionId, t, renderFactorySlot, language }) {
2140
+ function Pane({ controller, sessionId, t, renderFactorySlot, language, useTabInfo }) {
2141
+ const { tab } = useTabInfo();
1991
2142
  const snapshot = useSnapshot(controller);
1992
- if (!sessionId || snapshot.pane?.sessionId !== sessionId) return null;
2143
+ const pane = snapshot.panes.get(sessionId)?.get(tab.id);
2144
+ if (!pane || snapshot.sessionId !== sessionId) return null;
1993
2145
  return h(OpenPane, {
1994
- key: sessionId,
2146
+ key: tab.id,
1995
2147
  controller,
1996
2148
  sessionId,
1997
2149
  t,
1998
2150
  renderFactorySlot,
1999
2151
  language,
2000
- pane: snapshot.pane,
2152
+ pane,
2153
+ navigate: (id2) => controller.navigate(sessionId, tab.id, id2),
2001
2154
  dictationAvailable: snapshot.dictationAvailable,
2002
2155
  speechMounted: snapshot.speechMounted,
2003
2156
  speechSettings: snapshot.speechSettings,
@@ -2005,7 +2158,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2005
2158
  performanceUsage: snapshot.performanceUsage
2006
2159
  });
2007
2160
  }
2008
- return { Dock, Pane, CommandIcon: SideQuestionIcon };
2161
+ return { Dock, Pane, TabTitle, CommandIcon: SideQuestionIcon };
2009
2162
  }
2010
2163
 
2011
2164
  // locale/en.json
@@ -2038,9 +2191,20 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2038
2191
  missingThread: "Side question not found.",
2039
2192
  retry: "Retry",
2040
2193
  waiting: "Waiting for a reply…",
2041
- interrupted: "Reply interrupted.",
2042
- replyFailed: "Failed to generate reply.",
2043
- contextOverflow: "Context limit reached.",
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.",
2044
2208
  emptyReply: "No text response.",
2045
2209
  history: "Side question messages",
2046
2210
  userMessage: "You",
@@ -2048,7 +2212,9 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2048
2212
  placeholder: "Ask a follow-up…",
2049
2213
  input: "Enter a message",
2050
2214
  send: "Send follow-up",
2051
- sendFailed: "Failed to 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.",
2052
2218
  micStart: "Start recording",
2053
2219
  micStop: "Stop and transcribe",
2054
2220
  micRequesting: "Allow microphone access…",
@@ -2080,7 +2246,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2080
2246
  copy: "Copy",
2081
2247
  copied: "Copied",
2082
2248
  copyFailed: "Copy failed.",
2083
- archiveWriteFailed: "Failed to save reply.",
2249
+ archiveWriteFailed: "Failed to save reply",
2084
2250
  micPermission: "Microphone access is disabled. Allow it in browser or system settings.",
2085
2251
  micMissing: "Microphone unavailable. Check your input device.",
2086
2252
  micInterrupted: "Recording interrupted.",
@@ -2107,7 +2273,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2107
2273
  commandSpelling: "侧问",
2108
2274
  commandDescription: "发起侧问,或查看当前会话的侧问记录",
2109
2275
  sidebarUnavailable: "当前视图无法打开右侧栏。",
2110
- sessionNotSaved: "请先发送一条消息开始侧问",
2276
+ sessionNotSaved: "请先发送一条消息后再发起侧问。",
2111
2277
  modelUnavailable: "当前会话未配置可用模型。",
2112
2278
  saveFailed: "保存侧问失败。",
2113
2279
  textOnly: "侧问不接受附件。",
@@ -2123,9 +2289,20 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2123
2289
  missingThread: "找不到该侧问记录。",
2124
2290
  retry: "重试",
2125
2291
  waiting: "等待回复…",
2126
- interrupted: "回复已中断。",
2127
- replyFailed: "回复生成失败。",
2128
- contextOverflow: "已达上下文上限。",
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: "模型拒绝回答,请调整问题后再试。",
2129
2306
  emptyReply: "模型未返回文本内容。",
2130
2307
  history: "侧问对话记录",
2131
2308
  userMessage: "你",
@@ -2134,6 +2311,8 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2134
2311
  input: "输入消息",
2135
2312
  send: "发送追问",
2136
2313
  sendFailed: "发送失败,请重试。",
2314
+ snapshotUnavailable: "侧问上下文已失效,请发起新的侧问。",
2315
+ stillGenerating: "上一条回复仍在生成。",
2137
2316
  micStart: "开始录音",
2138
2317
  micStop: "停止并识别",
2139
2318
  micRequesting: "请允许使用麦克风…",
@@ -2153,8 +2332,8 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2153
2332
  auditCacheHit: "缓存命中",
2154
2333
  auditTotal: "总计",
2155
2334
  auditInput: "未缓存输入",
2156
- auditCacheRead: "读取缓存",
2157
- auditCacheWrite: "写入缓存",
2335
+ auditCacheRead: "缓存读取",
2336
+ auditCacheWrite: "缓存写入",
2158
2337
  auditOutput: "输出",
2159
2338
  auditTurn: "本轮用量",
2160
2339
  auditSpent: "用量 {total}",
@@ -2165,7 +2344,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2165
2344
  copy: "复制",
2166
2345
  copied: "已复制",
2167
2346
  copyFailed: "复制失败。",
2168
- archiveWriteFailed: "回复保存失败。",
2347
+ archiveWriteFailed: "回复保存失败",
2169
2348
  micPermission: "麦克风权限未开启,请在浏览器或系统设置中允许访问。",
2170
2349
  micMissing: "未检测到可用麦克风,请检查输入设备。",
2171
2350
  micInterrupted: "录音已中断。",
@@ -2186,6 +2365,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2186
2365
  var defaultPerformanceUsage = "detailed";
2187
2366
  var microphonePreference = "dsh.voice-input.microphone";
2188
2367
  var cardPreferencePrefix = "dsh.btw.card.";
2368
+ var emptyDraft = { text: "", revision: 0, saving: false };
2189
2369
  function getMicrophoneDevice() {
2190
2370
  try {
2191
2371
  const device = JSON.parse(globalThis.localStorage?.getItem(microphonePreference) ?? "null");
@@ -2208,13 +2388,24 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2208
2388
  }
2209
2389
  return btoa(binary);
2210
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
+ }
2211
2397
  function makeController(ctx) {
2212
2398
  const sidebar = ctx.sidebarRight;
2213
2399
  const listeners = /* @__PURE__ */ new Set();
2400
+ const draftListeners = /* @__PURE__ */ new Set();
2401
+ const drafts = /* @__PURE__ */ new Map();
2214
2402
  const activeStreams = /* @__PURE__ */ new Set();
2403
+ const threadStreams = /* @__PURE__ */ new Set();
2404
+ let session = sidebar.mounted.getSnapshot();
2215
2405
  let snapshot = {
2406
+ sessionId: session,
2216
2407
  cards: {},
2217
- pane: null,
2408
+ panes: /* @__PURE__ */ new Map(),
2218
2409
  notice: {},
2219
2410
  dictationAvailable: false,
2220
2411
  speechMounted: false,
@@ -2222,9 +2413,9 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2222
2413
  listRevision: 0,
2223
2414
  performanceUsage: defaultPerformanceUsage
2224
2415
  };
2225
- let session = sidebar.mounted.getSnapshot();
2226
2416
  let selectionRevision = 0;
2227
- const panes = /* @__PURE__ */ new Map();
2417
+ let restoreAttempt;
2418
+ let lastListOpen = 0;
2228
2419
  const cardIds = /* @__PURE__ */ new Map();
2229
2420
  const lastAcceptedCards = /* @__PURE__ */ new Map();
2230
2421
  let lastCardRequest = 0;
@@ -2244,7 +2435,11 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2244
2435
  }
2245
2436
  }
2246
2437
  function pruneRestored() {
2247
- if (!disposed && !panes.has(session)) closeTabs(session);
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
+ }
2248
2443
  }
2249
2444
  function queuePrune() {
2250
2445
  if (closeQueued) return;
@@ -2254,17 +2449,37 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2254
2449
  pruneRestored();
2255
2450
  });
2256
2451
  }
2257
- function navigatePane(sessionId, id2) {
2258
- const listRevision = snapshot.listRevision + 1;
2259
- const pane = id2 === null ? { sessionId, id: id2, listOpenedAt: listRevision } : { sessionId, id: id2 };
2260
- panes.set(sessionId, pane);
2261
- publish(id2 === null ? { pane, listRevision } : { pane });
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 });
2262
2476
  }
2263
2477
  function open(sessionId, id2) {
2264
2478
  if (disposed || session !== sessionId) return false;
2265
2479
  sidebar.openTabIn(sessionId, tabKind);
2266
- if (!sidebar.tabsIn(sessionId).some((tab) => tab.kind === tabKind)) return false;
2267
- navigatePane(sessionId, id2);
2480
+ const tab = sidebar.active();
2481
+ if (disposed || session !== sessionId || !sidebar.isExpanded() || tab?.kind !== tabKind) return false;
2482
+ navigatePane(sessionId, tab.id, id2);
2268
2483
  return true;
2269
2484
  }
2270
2485
  function cardIdFor(sessionId) {
@@ -2281,43 +2496,76 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2281
2496
  function rememberCard(sessionId, id2) {
2282
2497
  cardIds.set(sessionId, id2);
2283
2498
  try {
2284
- if (id2 === null) globalThis.localStorage?.removeItem(cardPreferencePrefix + sessionId);
2285
- else globalThis.localStorage?.setItem(cardPreferencePrefix + sessionId, id2);
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);
2286
2509
  } catch {
2287
2510
  }
2288
2511
  }
2289
- async function restoreCard(sessionId) {
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) {
2290
2520
  if (disposed || sessionId === void 0 || session !== sessionId || snapshot.cards[sessionId]) return;
2291
2521
  const id2 = cardIdFor(sessionId);
2292
2522
  if (!id2) return;
2293
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;
2294
2530
  const stillCurrent = () => !disposed && selectionRevision === revision && cardIdFor(sessionId) === id2;
2295
- try {
2296
- const detail2 = unwrap(await ctx.remote.btw.get(sessionId, id2));
2297
- if (stillCurrent() && detail2.id === id2 && detail2.sessionId === sessionId && !snapshot.cards[sessionId]) {
2298
- publish({ cards: { ...snapshot.cards, [sessionId]: detail2 } });
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;
2299
2545
  }
2300
- } catch (error) {
2301
- if (stillCurrent() && error.code === "btw/not-found") rememberCard(sessionId, null);
2302
- }
2546
+ if (failed && attempt.retryOnFailure && stillCurrent()) await restoreCard(sessionId);
2547
+ });
2548
+ return attempt.promise;
2303
2549
  }
2550
+ const disposeConnection = ctx.on("connection/reset", () => {
2551
+ void restoreCard(session, true);
2552
+ });
2304
2553
  const disposeSelection = sidebar.mounted.subscribe(() => {
2305
2554
  const current = sidebar.mounted.getSnapshot();
2306
2555
  if (current === session) return;
2307
2556
  session = current;
2308
2557
  selectionRevision += 1;
2309
- const pane = panes.get(session);
2310
- publish({ cards: {}, pane: pane ? { ...pane, restored: true } : null, notice: {} });
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: {} });
2311
2562
  queuePrune();
2312
2563
  });
2313
2564
  const disposeInventory = sidebar.openTabs.subscribe(() => {
2314
- const openSessions = new Set(sidebar.openTabs.getSnapshot().filter((tab) => tab.kind === tabKind).map((tab) => tab.sessionId));
2315
- for (const id2 of panes.keys()) {
2316
- if (!openSessions.has(id2)) panes.delete(id2);
2317
- }
2318
- if (snapshot.pane && !panes.has(snapshot.pane.sessionId)) publish({ pane: null });
2565
+ syncTabs();
2319
2566
  queuePrune();
2320
2567
  });
2568
+ syncTabs(true);
2321
2569
  queuePrune();
2322
2570
  function observe(start, settled, onNext, onError) {
2323
2571
  const controller = new AbortController();
@@ -2343,27 +2591,71 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2343
2591
  })();
2344
2592
  return () => controller.abort();
2345
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
+ }
2346
2605
  return {
2347
2606
  subscribe(listener) {
2348
2607
  listeners.add(listener);
2349
2608
  return () => listeners.delete(listener);
2350
2609
  },
2351
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
+ },
2352
2640
  openList: (id2) => open(id2, null),
2353
2641
  openDetail: (sessionId, id2) => open(sessionId, id2),
2354
- navigate(sessionId, id2) {
2355
- if (!disposed && session === sessionId && panes.has(sessionId)) navigatePane(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;
2356
2646
  },
2357
- restoreCard,
2358
- dismiss(id2) {
2359
- rememberCard(id2, null);
2360
- const cards = { ...snapshot.cards };
2361
- delete cards[id2];
2362
- publish({ cards });
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
+ }
2363
2652
  },
2653
+ restoreCard,
2654
+ dismiss: dismissCard,
2364
2655
  async createCard(id2, question2) {
2656
+ const submissionId = newSubmissionId();
2365
2657
  const request = ++lastCardRequest;
2366
- const detail2 = unwrap(await ctx.remote.btw.create(id2, question2));
2658
+ const detail2 = unwrap(await ctx.remote.btw.submitCreate(id2, question2, submissionId));
2367
2659
  if (disposed) return;
2368
2660
  const listRevision = snapshot.listRevision + 1;
2369
2661
  if (request <= (lastAcceptedCards.get(id2) ?? 0)) {
@@ -2380,18 +2672,37 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2380
2672
  watch(sessionId, id2, onNext, onError) {
2381
2673
  return observe(
2382
2674
  (signal) => ctx.remote.btw.watch(sessionId, id2, null, signal),
2383
- (detail2) => detail2.turns.at(-1)?.status !== "generating",
2675
+ (detail2) => detail2.turns.at(-1)?.status !== "generating" && !detail2.turns[0]?.saveError,
2384
2676
  onNext,
2385
2677
  onError
2386
2678
  );
2387
2679
  },
2388
- watchReply(sessionId, id2, turnIndex, version2, onNext, onError) {
2389
- return observe(
2390
- (signal) => ctx.remote.btw.watchReply(sessionId, id2, turnIndex, version2, signal),
2391
- (update) => update.status !== "generating",
2392
- onNext,
2393
- onError
2394
- );
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
+ };
2395
2706
  },
2396
2707
  pruneRestored,
2397
2708
  setPerformanceUsage(value) {
@@ -2443,11 +2754,15 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2443
2754
  },
2444
2755
  dispose() {
2445
2756
  disposed = true;
2757
+ disposeConnection();
2446
2758
  disposeSelection();
2447
2759
  disposeInventory();
2448
2760
  closeTabs(session);
2449
2761
  for (const controller of activeStreams) controller.abort();
2762
+ for (const stream of threadStreams) void stream.dispose();
2450
2763
  listeners.clear();
2764
+ draftListeners.clear();
2765
+ drafts.clear();
2451
2766
  }
2452
2767
  };
2453
2768
  }
@@ -2519,17 +2834,56 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2519
2834
  ctx.effect(() => disposeRemote);
2520
2835
  await ctx.inject(["remote", "remote.btw"], (scope) => mountFeatures(scope, React));
2521
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
+ }
2522
2872
  function mountFeatures(ctx, React) {
2523
2873
  ctx.effect(() => ctx.locale.register(namespace, { en: en_default.ui, zh: zh_default.ui }));
2524
2874
  const t = ctx.locale.bind(namespace);
2525
2875
  const controller = makeController(ctx);
2526
2876
  ctx.effect(() => controller.dispose);
2527
- const { Dock, Pane, CommandIcon } = createViews(React);
2877
+ const { Dock, Pane, TabTitle, CommandIcon } = createViews(React);
2528
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)));
2529
2883
  ctx.effect(() => ctx.slots.inject("conversation.input.dock", () => ctx.slots.register({
2530
2884
  name: "conversation.input.dock",
2531
2885
  id: "kabxx-btw-dock",
2532
- order: 30,
2886
+ order: 15,
2533
2887
  locale: namespace
2534
2888
  }, (props) => {
2535
2889
  React.useLayoutEffect(() => {
@@ -2541,14 +2895,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2541
2895
  name: "sidebar.right.pane.tab",
2542
2896
  key: plugin,
2543
2897
  locale: namespace
2544
- }, (props) => {
2545
- const snapshot = React.useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
2546
- React.useLayoutEffect(() => {
2547
- controller.pruneRestored();
2548
- }, [props.sessionId]);
2549
- if (snapshot.pane?.sessionId !== props.sessionId) return null;
2550
- return React.createElement(Pane, { ...props, controller, t: props.t ?? t });
2551
- })));
2898
+ }, (props) => React.createElement(Pane, { ...props, controller, t: props.t ?? t }))));
2552
2899
  ctx.effect(() => ctx.inputTriggers.registerSource(makeSource(controller, t, CommandIcon)));
2553
2900
  ctx.inject(["configForms"], (scope) => {
2554
2901
  scope.effect(() => {
@@ -2570,26 +2917,7 @@ summary.dsh-btw-stat-trigger { cursor: pointer; }
2570
2917
  });
2571
2918
  });
2572
2919
  ctx.inject(["remote.speech"], (scope) => {
2573
- scope.effect(() => {
2574
- const abort = new AbortController();
2575
- const speech = scope.remote.speech;
2576
- controller.setSpeechCatalog(void 0, speech);
2577
- const stream = speech.follow(abort.signal);
2578
- void (async () => {
2579
- try {
2580
- for await (const catalog of stream) {
2581
- if (!abort.signal.aborted) controller.setSpeechCatalog(catalog, speech);
2582
- }
2583
- } catch {
2584
- if (!abort.signal.aborted) controller.setSpeechCatalog(void 0, speech);
2585
- }
2586
- })();
2587
- return () => {
2588
- abort.abort();
2589
- stream.dispose?.();
2590
- controller.setSpeechCatalog(void 0);
2591
- };
2592
- });
2920
+ scope.effect(() => observeSpeech(scope.remote, controller));
2593
2921
  });
2594
2922
  }
2595
2923
  return __toCommonJS(index_exports);