Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Sync DS Bot main: handoff headings, official voice input, DSH update sync, one reasoning row per Turn, Bot thinking level

Fei24117602415eadb4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 42851734..587a5b35 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ All notable changes to DS Bot are listed here. The format follows [Keep a Change
### Fixed
- Group the first model choices by provider, so models with the same name can be distinguished. Providers with the same display name also show their provider IDs.
+- A turn with many steps shows one "Thought it through" row instead of one per step. The row holds the thinking of every step in order.
## [0.1.0] - 2026-10-10
diff --git a/NOTICE b/NOTICE
index 58282005..4d997611 100644
--- a/NOTICE
+++ b/NOTICE
@@ -65,3 +65,7 @@ their ideas; it does not contain their code.
when to condense a long conversation, and what a handoff note holds.
- obelisk (https://github.com/tommy0103/obelisk), AGPL-3.0:
searching a Bot's own chat with a SQLite FTS5 index ranked by BM25.
+ - DeepSeek Harness Voice Input plugin
+ (packages/experimental/client-ui-voice-input), MIT: the voice chat
+ records with the same steps (record, resample to 16 kHz mono, PCM16 WAV)
+ before it calls the plugin's speech service.
diff --git a/ds-bot/README.md b/ds-bot/README.md
index 04180074..2488f872 100644
--- a/ds-bot/README.md
+++ b/ds-bot/README.md
@@ -77,6 +77,8 @@ Options go in the profile's `cordis.patch.yml`, under the `bot` entry. All of th
**Updates**: when a window opens, DS Bot asks where it was installed from for a newer release: the npm registry (the one the DSH plugin manager installs from, then its fallbacks), or the latest GitHub release for a `github:…#vX.Y.Z` install. A newer version shows a cloud button at the top right of the sidebar; **Update** reinstalls DS Bot through the DSH plugin manager, and the new version runs from the next DSH start. A linked or local checkout is never offered an update.
+The same card carries DSH itself: every DS Bot release names the DSH release it was verified against (`dsBot.verifiedDsh` in its `package.json`), and only that version is offered — running something newer is a downgrade offer too. A DSH installed from npm is swapped by `npm install -g @deepseek-ai/dsh@<version>`; a packaged app owns its runtime, so the card shows its current and verified versions and opens the app's own update panel. A release may raise the floor with `dsBot.minBot`: until the bot itself is that new, the DSH row waits.
+
## Models
Model providers are set up with dsh's `llm-pi-ai` plugin in `cordis.patch.yml`. Every Bot runs on one model of its own, from the models DSH serves. A new team's first Main Bot has none: its chat opens on a model card and it greets the user only after a pick. The Create Bot form starts on the DSH default model. The Bot's details panel and settings (or a Main Bot's `update_bot`) change it; a Bot whose model is no longer served shows the card again. A team saved by an older version keeps the model each Bot last ran on.
diff --git a/ds-bot/client.js b/ds-bot/client.js
index daee45f8..ca3dba6f 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -245,6 +245,7 @@ var ZH = {
Create: "创建",
// Model menu
Default: "默认",
+ "Thinking level": "思考强度",
"Model: {model}": "模型:{model}",
none: "无",
"Choose a model": "选择模型",
@@ -368,6 +369,13 @@ var ZH = {
"The update did not finish: {reason}": "更新没有完成:{reason}",
"What's new": "更新说明",
"Updating…": "正在更新…",
+ "DSH {version} is available": "DSH {version} 可以更新",
+ "Updating DSH…": "正在更新 DSH…",
+ "DSH update": "DSH 更新",
+ "DSH {version}": "DSH {version}",
+ "Restart DSH to start using DSH {version}.": "重启 DSH 后开始使用 DSH {version}。",
+ "Update DS Bot {version} first.": "先更新 DS Bot {version}。",
+ "Open updates": "打开更新",
// Command palette
Messages: "消息",
Commands: "命令",
@@ -601,6 +609,10 @@ var ZH = {
"Resume listening": "继续听",
Pause: "暂停",
"End voice chat": "结束语音对话",
+ "Recognizing…": "识别中…",
+ "Voice input needs its speech model": "语音输入还没有语音模型",
+ "Set up voice input": "设置语音输入",
+ "That was too long to recognize": "这段太长了,识别不了",
// Usage page
"24 hours": "24 小时",
"7 days": "7 天",
@@ -2113,6 +2125,8 @@ button.bt-set-row:hover{background:var(--bt-hover)}
.bt-voice-status{font-size:13px;line-height:18px;color:var(--bt-ink-2);min-height:18px}
.bt-voice-caption{min-height:44px;font-size:15px;line-height:22px;color:var(--bt-ink);animation:bt-blur-in .25s ease-out;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}
.bt-voice-note{font-size:12px;color:#e02135}
+.bt-voice-setup{height:32px;padding:0 14px;border-radius:16px;border:0;background:var(--bt-hover);color:var(--bt-ink);font:inherit;font-size:13px;cursor:pointer;transition:background-color .15s ease}
+.bt-voice-setup:hover{background:var(--bt-active)}
.bt-voice-bar{display:flex;gap:16px;padding:0 0 32px}
.bt-voice-btn{position:relative;width:52px;height:52px;border-radius:50%;border:0;background:var(--bt-hover);color:var(--bt-ink);display:grid;place-items:center;cursor:pointer;transition:background-color .15s ease,transform .12s ease}
.bt-voice-btn:hover{background:var(--bt-active)}
@@ -3513,12 +3527,22 @@ var SECRET_CSS = `
@media (prefers-reduced-motion:reduce){.bt-secret-glide{transition:none}.bt-secret-check,.bt-secret-done,.bt-secret-ok,.bt-secret-edit{animation:none}}
`;
+// src/client/turn-reasoning.js
+function turnReasoning(steps, current) {
+ const members = steps.length ? steps : [current];
+ if (members.find((step) => stepReasoning(step) !== "")?.step !== current.step) return "";
+ return members.filter((step) => !thinkingLive(step)).map(stepReasoning).filter(Boolean).join("\n\n");
+}
+var texts = (step) => step.blocks.filter((block) => block.kind === "text" && block.text.trim() !== "");
+var thinkingLive = (step) => step.status === "running" && texts(step).length === 0 && step.blocks.some((block) => block.kind === "reasoning");
+var stepReasoning = (step) => step.blocks.filter((block) => block.kind === "reasoning").map((block) => block.text).join("\n").trim();
+
// src/client/cells.js
var import_react6 = require("react");
var import_react_dom = require("react-dom");
var import_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
var mdLabels = () => ({ code: { copyLabel: t("Copy"), copiedLabel: t("Copied") }, footnotes: t("Footnotes") });
-function Bubbles({ texts, roster, selfId, actions, streaming, sessionId, msgKey, useUi, lead }) {
+function Bubbles({ texts: texts2, roster, selfId, actions, streaming, sessionId, msgKey, useUi, lead }) {
const onClick = (event) => {
const target = mentionTarget(event);
if (target === null) return;
@@ -3530,10 +3554,10 @@ function Bubbles({ texts, roster, selfId, actions, streaming, sessionId, msgKey,
return (0, import_react6.createElement)(
"div",
{ className: "bt-astack", "data-lead": lead ? "" : void 0, onClickCapture: onClick },
- texts.map((text, index) => {
+ texts2.map((text, index) => {
const key = msgKey ? `${msgKey}:${index}` : void 0;
const picked = key ? reactions?.[index] ?? [] : [];
- const last = index === texts.length - 1;
+ const last = index === texts2.length - 1;
const live = streaming && last;
return (0, import_react6.createElement)(
"div",
@@ -3638,8 +3662,7 @@ function MessageTools({ text, name, sessionId, react, actions }) {
), document.body) : null
);
}
-function ThinkingRow({ text, running }) {
- if (running || !text) return null;
+function ThinkingRow({ text }) {
return (0, import_react6.createElement)(
"details",
{ className: "bt-think" },
@@ -3647,22 +3670,22 @@ function ThinkingRow({ text, running }) {
(0, import_react6.createElement)("div", { className: "bt-think-text" }, text)
);
}
-function AssistantCell({ node, groupPart, sessionId, useRoster, useUi, actions }) {
+function AssistantCell({ node, groupPart, sessionId, useRoster, useUi, useTurnSteps, actions }) {
const roster = useRoster((value) => value);
const data = node.data;
+ const steps = useTurnSteps(String(data.turn));
const hidden = Boolean(roster.roomsById[sessionId]) || isHiddenTurn(roster, sessionId, data.turn);
- const texts = groupPart === "reasoning" ? [] : data.blocks.filter((block) => block.kind === "text" && block.text.trim() !== "").map((block) => block.text);
+ const texts2 = groupPart === "reasoning" ? [] : data.blocks.filter((block) => block.kind === "text" && block.text.trim() !== "").map((block) => block.text);
const running = data.status === "running";
- useLiveNote(actions, sessionId, `text:${node.key ?? data.seq}`, !hidden && running && texts.length > 0 ? { text: true } : null);
+ useLiveNote(actions, sessionId, `text:${node.key ?? data.seq}`, !hidden && running && texts2.length > 0 ? { text: true } : null);
if (hidden) return null;
- const reasoning = groupPart === "response" ? "" : data.blocks.filter((block) => block.kind === "reasoning").map((block) => block.text).join("\n").trim();
- const thinkingLive = running && texts.length === 0 && data.blocks.some((block) => block.kind === "reasoning");
- if (texts.length === 0 && !reasoning) return null;
+ const reasoning = groupPart === "response" ? "" : turnReasoning(steps, data);
+ if (texts2.length === 0 && !reasoning) return null;
return (0, import_react6.createElement)(
import_react6.Fragment,
null,
- reasoning ? (0, import_react6.createElement)(ThinkingRow, { text: reasoning, running: thinkingLive }) : null,
- texts.length ? (0, import_react6.createElement)(Bubbles, { texts, roster, selfId: roster.byId[sessionId]?.id ?? sessionId, actions, streaming: running, sessionId, msgKey: `${sessionId}:${data.turn}:${node.key ?? data.seq ?? ""}`, useUi }) : null
+ reasoning ? (0, import_react6.createElement)(ThinkingRow, { text: reasoning }) : null,
+ texts2.length ? (0, import_react6.createElement)(Bubbles, { texts: texts2, roster, selfId: roster.byId[sessionId]?.id ?? sessionId, actions, streaming: running, sessionId, msgKey: `${sessionId}:${data.turn}:${node.key ?? data.seq ?? ""}`, useUi }) : null
);
}
function EventLine({ prefix, bots, joiner = t("and"), onOpen }) {
@@ -4667,6 +4690,7 @@ function UpdateButton({ useUpdate, actions }) {
const [open, setOpen] = (0, import_react8.useState)(false);
const [box, setBox] = (0, import_react8.useState)(null);
const [error, setError] = (0, import_react8.useState)("");
+ const [dshError, setDshError] = (0, import_react8.useState)("");
const button = (0, import_react8.useRef)(null);
(0, import_react8.useEffect)(() => {
if (!open) return void 0;
@@ -4689,7 +4713,11 @@ function UpdateButton({ useUpdate, actions }) {
};
}, [open]);
const phase = update?.phase ?? "idle";
- if (!update?.available && phase === "idle") return null;
+ const dsh = update?.dsh;
+ const dshPhase = dsh?.phase ?? "idle";
+ const dshRow = dsh && dsh.verified && dsh.current && dsh.verified !== dsh.current;
+ if (!update?.available && !dshRow && phase === "idle" && dshPhase === "idle") return null;
+ const cloudPhase = phase === "installing" || dshPhase === "installing" ? "installing" : phase !== "idle" ? phase : dshPhase;
const toggle = () => {
const rect = button.current?.getBoundingClientRect();
if (rect) setBox({ left: Math.max(8, Math.min(rect.left, window.innerWidth - 288)), top: rect.bottom + 6 });
@@ -4699,8 +4727,14 @@ function UpdateButton({ useUpdate, actions }) {
setError("");
void actions.installUpdate().catch((failure) => setError(hostText(failure?.message ?? String(failure))));
};
- const label = phase === "installing" ? t("Updating DS Bot…") : phase === "installed" ? t("DS Bot {version} is installed. Restart DSH to use it.", { version: update.installed ?? update.latest }) : t("DS Bot {version} is available", { version: update.latest });
+ const startDsh = () => {
+ setDshError("");
+ void actions.installDshUpdate().catch((failure) => setDshError(hostText(failure?.message ?? String(failure))));
+ };
+ const label = phase === "installing" ? t("Updating DS Bot…") : dshPhase === "installing" ? t("Updating DSH…") : phase === "installed" ? t("DS Bot {version} is installed. Restart DSH to use it.", { version: update.installed ?? update.latest }) : dshPhase === "installed" ? t("Restart DSH to start using DSH {version}.", { version: dsh.installed ?? dsh.verified }) : update?.available ? t("DS Bot {version} is available", { version: update.latest }) : t("DSH {version} is available", { version: dsh?.verified });
const message = error || (phase === "failed" ? update.error : "");
+ const dshMessage = dshError || (dshPhase === "failed" ? dsh?.error : "");
+ const dshText = dshPhase === "installed" ? t("Restart DSH to start using DSH {version}.", { version: dsh.installed ?? dsh.verified }) : dsh?.available === false && dsh?.blockedBy && dsh.kind === "npm" ? t("Update DS Bot {version} first.", { version: dsh.blockedBy }) : t("You have {version}.", { version: dsh?.current });
return (0, import_react8.createElement)(
import_react8.Fragment,
null,
@@ -4708,30 +4742,51 @@ function UpdateButton({ useUpdate, actions }) {
ref: button,
type: "button",
className: "bt-round bt-update",
- "data-phase": phase,
+ "data-phase": cloudPhase,
"aria-label": label,
title: label,
"aria-haspopup": "dialog",
"aria-expanded": open,
onClick: toggle
- }, (0, import_react8.createElement)(CloudDownloadIcon, { done: phase === "installed" }), phase === "failed" ? (0, import_react8.createElement)("span", { className: "bt-update-dot", "aria-hidden": true }) : null),
+ }, (0, import_react8.createElement)(CloudDownloadIcon, { done: phase === "installed" }), phase === "failed" || dshPhase === "failed" ? (0, import_react8.createElement)("span", { className: "bt-update-dot", "aria-hidden": true }) : null),
open && box ? (0, import_react_dom3.createPortal)((0, import_react8.createElement)(
"div",
- { className: "bt-update-pop", role: "dialog", "aria-label": t("DS Bot update"), style: box },
- (0, import_react8.createElement)("div", { className: "bt-update-title" }, phase === "installed" ? t("Update installed") : t("DS Bot {version}", { version: update.latest })),
- (0, import_react8.createElement)("div", { className: "bt-update-text" }, phase === "installed" ? t("Restart DSH to start using DS Bot {version}.", { version: update.installed ?? update.latest }) : t("You have {version}.", { version: update.current })),
- message ? (0, import_react8.createElement)("div", { className: "bt-update-error", role: "alert" }, t("The update did not finish: {reason}", { reason: message })) : null,
- (0, import_react8.createElement)(
+ { className: "bt-update-pop", role: "dialog", "aria-label": update?.available || phase !== "idle" ? t("DS Bot update") : t("DSH update"), style: box },
+ update?.available || phase !== "idle" ? (0, import_react8.createElement)(
+ import_react8.Fragment,
+ null,
+ (0, import_react8.createElement)("div", { className: "bt-update-title" }, phase === "installed" ? t("Update installed") : t("DS Bot {version}", { version: update.latest })),
+ (0, import_react8.createElement)("div", { className: "bt-update-text" }, phase === "installed" ? t("Restart DSH to start using DS Bot {version}.", { version: update.installed ?? update.latest }) : t("You have {version}.", { version: update.current })),
+ message ? (0, import_react8.createElement)("div", { className: "bt-update-error", role: "alert" }, t("The update did not finish: {reason}", { reason: message })) : null,
+ (0, import_react8.createElement)(
+ "div",
+ { className: "bt-update-actions" },
+ update.notesUrl ? (0, import_react8.createElement)("a", { className: "bt-update-notes", href: update.notesUrl, target: "_blank", rel: "noopener noreferrer" }, t("What's new")) : null,
+ phase === "installed" ? null : (0, import_react8.createElement)("button", {
+ type: "button",
+ className: "bt-update-go",
+ disabled: phase === "installing",
+ onClick: start
+ }, phase === "installing" ? t("Updating…") : phase === "failed" ? t("Try again") : t("Update"))
+ )
+ ) : null,
+ dshRow ? (0, import_react8.createElement)(
"div",
- { className: "bt-update-actions" },
- update.notesUrl ? (0, import_react8.createElement)("a", { className: "bt-update-notes", href: update.notesUrl, target: "_blank", rel: "noopener noreferrer" }, t("What's new")) : null,
- phase === "installed" ? null : (0, import_react8.createElement)("button", {
- type: "button",
- className: "bt-update-go",
- disabled: phase === "installing",
- onClick: start
- }, phase === "installing" ? t("Updating…") : phase === "failed" ? t("Try again") : t("Update"))
- )
+ { className: "bt-update-dsh" },
+ (0, import_react8.createElement)("div", { className: "bt-update-title" }, t("DSH {version}", { version: dsh.verified })),
+ (0, import_react8.createElement)("div", { className: "bt-update-text" }, dshText),
+ dshMessage ? (0, import_react8.createElement)("div", { className: "bt-update-error", role: "alert" }, t("The update did not finish: {reason}", { reason: dshMessage })) : null,
+ (0, import_react8.createElement)(
+ "div",
+ { className: "bt-update-actions" },
+ dsh.kind === "app" ? (0, import_react8.createElement)("button", { type: "button", className: "bt-update-go", onClick: () => actions.openAppUpdates() }, t("Open updates")) : !dsh.available && dshPhase === "idle" ? null : dshPhase === "installed" ? null : (0, import_react8.createElement)("button", {
+ type: "button",
+ className: "bt-update-go",
+ disabled: dshPhase === "installing",
+ onClick: startDsh
+ }, dshPhase === "installing" ? t("Updating…") : dshPhase === "failed" ? t("Try again") : t("Update"))
+ )
+ ) : null
), document.body) : null
);
}
@@ -5027,6 +5082,7 @@ var SIDEBAR_CSS = `
.bt-update-go:hover:not(:disabled){opacity:.9}
.bt-update-go:active:not(:disabled){transform:scale(.96)}
.bt-update-go:disabled{opacity:.6;cursor:default}
+.bt-update-dsh{margin-top:12px;padding-top:12px;border-top:.5px solid var(--bt-line-2)}
@media (prefers-reduced-motion:reduce){.bt-round.bt-update,.bt-update-pop,.bt-update .bt-cloud-arrow{animation:none}}
/* The DSH Agent row and its expanding Session list. The black whale is the
@@ -5354,10 +5410,11 @@ function ComposerVoice({ sessionId, inputActions, actions, useUi }) {
}
}, [quote?.token]);
if (sessionId === void 0) return null;
+ const pluginMic = actions.speech() !== void 0;
return (0, import_react10.createElement)(
import_react10.Fragment,
null,
- (0, import_react10.createElement)("button", {
+ pluginMic ? null : (0, import_react10.createElement)("button", {
type: "button",
className: "bt-mic",
"aria-label": dictation.listening ? t("Stop dictation") : t("Dictate"),
@@ -5449,6 +5506,132 @@ function ComposerPlus({ sessionId, useRoster, actions }) {
);
}
+// src/client/speech.js
+var VOICE_BUNDLE = "@deepseek-ai/dsh-experimental-voice-input-bundle";
+var USABLE = /* @__PURE__ */ new Set(["ready", "standby", "waking"]);
+async function speechCatalog(speech) {
+ const result = await speech.catalog();
+ if (!result?.ok) throw new Error(result?.error?.message ?? "Speech catalog failed");
+ const catalog = result.value;
+ const provider = catalog.providers.find((item) => item.id === catalog.selection.providerId);
+ return { catalog, usable: USABLE.has(provider?.preparation?.phase) };
+}
+function waveBytes(samples, rate = 16e3) {
+ const bytes = new Uint8Array(44 + samples.length * 2);
+ const view = new DataView(bytes.buffer);
+ const ascii = (at, text) => {
+ for (let index = 0; index < text.length; index += 1) bytes[at + index] = text.charCodeAt(index);
+ };
+ ascii(0, "RIFF");
+ view.setUint32(4, 36 + samples.length * 2, true);
+ ascii(8, "WAVEfmt ");
+ view.setUint32(16, 16, true);
+ view.setUint16(20, 1, true);
+ view.setUint16(22, 1, true);
+ view.setUint32(24, rate, true);
+ view.setUint32(28, rate * 2, true);
+ view.setUint16(32, 2, true);
+ view.setUint16(34, 16, true);
+ ascii(36, "data");
+ view.setUint32(40, samples.length * 2, true);
+ samples.forEach((sample, index) => {
+ const value = Math.max(-1, Math.min(1, sample));
+ view.setInt16(44 + index * 2, value < 0 ? Math.round(value * 32768) : Math.round(value * 32767), true);
+ });
+ return bytes;
+}
+function base64Of(bytes) {
+ let text = "";
+ for (let index = 0; index < bytes.length; index += 32768) text += String.fromCharCode(...bytes.subarray(index, index + 32768));
+ return btoa(text);
+}
+var captureError = (kind, cause) => Object.assign(new Error(kind), { kind, cause });
+async function openCapture() {
+ const devices = navigator.mediaDevices;
+ if (!devices?.getUserMedia || typeof MediaRecorder === "undefined") throw captureError("unavailable");
+ let stream;
+ try {
+ stream = await devices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true }, video: false });
+ } catch (error) {
+ throw captureError(error?.name === "NotAllowedError" ? "blocked" : "failed", error);
+ }
+ const audio = new AudioContext();
+ const analyser = audio.createAnalyser();
+ analyser.fftSize = 512;
+ audio.createMediaStreamSource(stream).connect(analyser);
+ const frame = new Float32Array(analyser.fftSize);
+ const recorder = new MediaRecorder(stream);
+ const chunks = [];
+ recorder.ondataavailable = (event) => {
+ if (event.data.size > 0) chunks.push(event.data);
+ };
+ recorder.start();
+ let closed = false;
+ const close = () => {
+ if (closed) return;
+ closed = true;
+ if (recorder.state !== "inactive") recorder.stop();
+ stream.getTracks().forEach((track) => track.stop());
+ void audio.close().catch(() => {
+ });
+ };
+ return {
+ level() {
+ if (closed) return 0;
+ analyser.getFloatTimeDomainData(frame);
+ let sum = 0;
+ for (const sample of frame) sum += sample * sample;
+ return Math.min(1, Math.sqrt(sum / frame.length) * 4);
+ },
+ cancel: close,
+ async finish(maxSeconds) {
+ if (closed || recorder.state === "inactive") {
+ close();
+ return null;
+ }
+ try {
+ await new Promise((resolve) => {
+ recorder.onstop = resolve;
+ recorder.stop();
+ });
+ stream.getTracks().forEach((track) => track.stop());
+ const blob = new Blob(chunks, { type: recorder.mimeType });
+ if (blob.size === 0) return null;
+ const decoded = await audio.decodeAudioData(await blob.arrayBuffer());
+ const length = Math.max(1, Math.floor(Math.min(decoded.duration, maxSeconds) * 16e3));
+ const offline = new OfflineAudioContext(1, length, 16e3);
+ const source = offline.createBufferSource();
+ source.buffer = decoded;
+ source.connect(offline.destination);
+ source.start();
+ return waveBytes((await offline.startRendering()).getChannelData(0));
+ } finally {
+ close();
+ }
+ }
+ };
+}
+async function transcribeWave(speech, catalog, wave, signal) {
+ if (wave.byteLength > catalog.maxAudioBytes) throw captureError("too-long");
+ const result = await speech.transcribe({ audioBase64: base64Of(wave), ...catalog.selection }, signal);
+ if (!result?.ok) throw Object.assign(new Error(result?.error?.message ?? "Transcription failed"), { kind: "service" });
+ return String(result.value?.text ?? "").trim();
+}
+function turnDetector({ loud = 0.12, quiet = 0.06, quietMs = 1200 } = {}) {
+ let spokeAt = 0;
+ let quietSince = 0;
+ return (level, now) => {
+ if (level >= loud) {
+ spokeAt ||= now;
+ quietSince = 0;
+ return "speech";
+ }
+ if (!spokeAt) return "waiting";
+ if (level < quiet) quietSince ||= now;
+ return quietSince && now - quietSince >= quietMs ? "done" : "speech";
+ };
+}
+
// src/client/overlay-hooks.js
var import_react11 = require("react");
var escapeLayers = [];
@@ -5702,6 +5885,53 @@ function modelOf(bot, roster) {
const [provider, ...rest] = ref.split("/");
return { ref, name: served?.name ?? rest.join("/"), provider: served?.providerName ?? provider, served: served !== void 0 };
}
+var effortCache = /* @__PURE__ */ new Map();
+function useEfforts(served, ref, actions) {
+ const [fetched, setFetched] = (0, import_react13.useState)(void 0);
+ (0, import_react13.useEffect)(() => {
+ setFetched(void 0);
+ if (ref === void 0 || served?.reasoning !== void 0 || actions?.efforts === void 0) return void 0;
+ let live = true;
+ if (effortCache.has(ref)) setFetched(effortCache.get(ref));
+ else void Promise.resolve(actions.efforts(ref)).then((value) => {
+ const reasoning = value?.efforts ? value : null;
+ effortCache.set(ref, reasoning);
+ if (live) setFetched(reasoning);
+ }).catch(() => {
+ });
+ return () => {
+ live = false;
+ };
+ }, [ref, served?.reasoning !== void 0, actions]);
+ return served?.reasoning ?? fetched;
+}
+function effortRows(reasoning) {
+ if (reasoning?.efforts === void 0 || reasoning.efforts.length === 0) return [];
+ return [
+ { effort: void 0, label: t("Default") },
+ ...reasoning.efforts.map((effort) => ({ effort: effort.id, label: effort.name }))
+ ];
+}
+function EffortRows({ reasoning, current, onPick }) {
+ return (0, import_react13.createElement)(
+ import_react13.Fragment,
+ null,
+ (0, import_react13.createElement)("div", { className: "bt-menu-sep", role: "separator" }),
+ (0, import_react13.createElement)("div", { className: "bt-model-group", role: "presentation" }, t("Thinking level")),
+ effortRows(reasoning).map((row) => (0, import_react13.createElement)(
+ "button",
+ {
+ key: row.effort ?? "default",
+ type: "button",
+ role: "menuitemradio",
+ "aria-checked": row.effort === current,
+ onClick: () => onPick(row.effort)
+ },
+ (0, import_react13.createElement)("span", { className: "bt-menu-label" }, row.label),
+ (0, import_react13.createElement)("span", { className: "bt-model-tick", "aria-hidden": true }, row.effort === current ? (0, import_react13.createElement)(CheckIcon) : null)
+ ))
+ );
+}
function ModelRows({ roster, current, onPick }) {
return groupModels(roster.models).map(([provider, list]) => (0, import_react13.createElement)(
import_react13.Fragment,
@@ -5723,13 +5953,18 @@ function ModelRows({ roster, current, onPick }) {
))
));
}
-function ModelMenu({ bot, roster, actions, run, wide = false, onPick }) {
+function ModelMenu({ bot, roster, actions, run, wide = false, onPick, onPickEffort }) {
const [place, setPlace] = (0, import_react13.useState)(null);
const [shownPlace, leaving] = useLinger(place, MENU_EXIT_MS);
const button = (0, import_react13.useRef)(null);
const menu = (0, import_react13.useRef)(null);
const shown = modelOf(bot, roster);
const current = bot.model ?? bot.appliedModel;
+ const served = servedOf(roster, current);
+ const reasoning = useEfforts(served, current, actions);
+ const picked = reasoning?.efforts?.some((effort) => effort.id === bot.effort) ? bot.effort : void 0;
+ const currentEffort = picked ?? reasoning?.defaultEffort;
+ const effortLabel = currentEffort === void 0 ? reasoning?.efforts?.length > 0 ? t("Default") : void 0 : reasoning.efforts.find((effort) => effort.id === currentEffort)?.name ?? currentEffort;
const close = () => setPlace(null);
(0, import_react13.useEffect)(() => {
if (place === null) return void 0;
@@ -5773,6 +6008,11 @@ function ModelMenu({ bot, roster, actions, run, wide = false, onPick }) {
if (onPick) onPick(ref);
else if (ref !== current || !bot.model) void run(actions.updateBot(bot.id, { model: ref }));
};
+ const pickEffort = (effort) => {
+ close();
+ if (onPickEffort) onPickEffort(effort);
+ else if (effort !== bot.effort) void run(actions.updateBot(bot.id, { effort: effort ?? null }));
+ };
const models = roster.models ?? [];
return (0, import_react13.createElement)(
import_react13.Fragment,
@@ -5794,7 +6034,7 @@ function ModelMenu({ bot, roster, actions, run, wide = false, onPick }) {
"span",
{ className: "bt-model-copy" },
(0, import_react13.createElement)("span", { className: "bt-model-name" }, shown?.name ?? t("Choose a model")),
- shown ? (0, import_react13.createElement)("span", { className: "bt-model-provider" }, shown.served || models.length === 0 ? shown.provider : t("{provider} · not available", { provider: shown.provider })) : null
+ shown ? (0, import_react13.createElement)("span", { className: "bt-model-provider" }, shown.served || models.length === 0 ? effortLabel === void 0 ? shown.provider : `${shown.provider} · ${effortLabel}` : t("{provider} · not available", { provider: shown.provider })) : null
),
(0, import_react13.createElement)("svg", { className: "bt-model-caret", width: 12, height: 12, viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true }, (0, import_react13.createElement)("path", { d: "M5.5 8l4.5 4.5L14.5 8" }))
),
@@ -5802,6 +6042,7 @@ function ModelMenu({ bot, roster, actions, run, wide = false, onPick }) {
"div",
{ ref: menu, className: `bt-menu bt-model-menu${shownPlace.bottom !== void 0 ? " bt-menu-up" : ""}`, role: "menu", "aria-label": t("Model for {name}", { name: bot.name }), style: shownPlace, "data-leaving": leaving || void 0 },
models.length > 0 ? (0, import_react13.createElement)(ModelRows, { roster, current, onPick: pick2 }) : (0, import_react13.createElement)("div", { className: "bt-model-none" }, t("No models are set up in DeepSeek Harness yet.")),
+ effortRows(reasoning).length > 0 ? (0, import_react13.createElement)(EffortRows, { reasoning, current: picked, onPick: pickEffort }) : null,
(0, import_react13.createElement)("div", { className: "bt-menu-sep", role: "separator" }),
(0, import_react13.createElement)("button", { type: "button", role: "menuitem", onClick: () => {
close();
@@ -7049,9 +7290,10 @@ function startModel(roster) {
const models = roster.models ?? [];
return (models.find((model) => model.ref === roster.defaultModel) ?? models[0])?.ref ?? "";
}
-function createPayload({ name, look, image, model, brief }) {
+function createPayload({ name, look, image, model, effort, brief }) {
const payload = { name, color: look.color, avatar: image ? { shape: look.shape, image } : { shape: look.shape } };
if (model) payload.model = model;
+ if (effort) payload.effort = effort;
if (brief) payload.brief = brief;
return payload;
}
@@ -7069,6 +7311,7 @@ function CreateBot({ roster, actions, start, brief = "", onBack, canGoBack, onCr
const [image, setImage] = (0, import_react17.useState)(null);
const [name, setName] = (0, import_react17.useState)(start?.name ?? "");
const [model, setModel] = (0, import_react17.useState)(() => startModel(roster));
+ const [effort, setEffort] = (0, import_react17.useState)(void 0);
const [busy, setBusy] = (0, import_react17.useState)(false);
const [error, setError] = (0, import_react17.useState)("");
const fileRef = (0, import_react17.useRef)(null);
@@ -7085,7 +7328,7 @@ function CreateBot({ roster, actions, start, brief = "", onBack, canGoBack, onCr
setError("");
setBusy(true);
try {
- const bot = await actions.createBot(createPayload({ name: finalName, look, image, model, brief }));
+ const bot = await actions.createBot(createPayload({ name: finalName, look, image, model, effort, brief }));
onCreated(bot);
} catch (failure) {
setError(failure?.message ?? String(failure));
@@ -7169,7 +7412,10 @@ function CreateBot({ roster, actions, start, brief = "", onBack, canGoBack, onCr
"div",
{ className: "bt-field" },
(0, import_react17.createElement)("span", { className: "bt-field-label" }, t("Model")),
- (0, import_react17.createElement)(ModelMenu, { bot: { id: "new-bot", name: finalName, model: model || void 0 }, roster, actions, wide: true, onPick: setModel }),
+ (0, import_react17.createElement)(ModelMenu, { bot: { id: "new-bot", name: finalName, model: model || void 0, effort }, roster, actions, wide: true, onPick: (ref) => {
+ setModel(ref);
+ setEffort(void 0);
+ }, onPickEffort: setEffort }),
(0, import_react17.createElement)("span", { className: "bt-note" }, (roster.models ?? []).length > 0 ? t("The Bot runs on this model. You can change it later in its details.") : t("Add a provider and a model in DeepSeek Harness first, or pick one in the Bot's chat later."))
),
error ? (0, import_react17.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null,
@@ -7531,7 +7777,15 @@ function ExchangeDialog({ pair, roster, actions }) {
// src/client/voice.js
var import_react20 = require("react");
var plainSpeech = (text) => stripHeader(text).replace(/```[\s\S]*?```/g, " ").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[*_`#>|~-]+/g, " ").replace(/\s+/g, " ").trim();
-var VOICE_LABELS = { listening: "Listening", thinking: "Thinking", speaking: "Speaking", paused: "Paused", unsupported: "Voice chat is not available in this browser" };
+var VOICE_LABELS = {
+ listening: "Listening",
+ thinking: "Thinking",
+ speaking: "Speaking",
+ paused: "Paused",
+ setup: "Voice input needs its speech model",
+ unsupported: "Voice chat is not available in this browser"
+};
+var CAPTURE_NOTES = { blocked: "Microphone access is blocked", unavailable: "Voice chat is not available in this browser", "too-long": "That was too long to recognize" };
function useMicLevel(enabled) {
const [level, setLevel] = (0, import_react20.useState)(0);
(0, import_react20.useEffect)(() => {
@@ -7584,27 +7838,59 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus }
const entry = Array.isArray(outline) ? outline[outline.length - 1] : void 0;
return entry ? `${outline.length}|${entry.response ?? ""}` : "0|";
});
- const [phase, setPhase] = (0, import_react20.useState)(speechApi() ? "listening" : "unsupported");
+ const [speech] = (0, import_react20.useState)(() => actions.speech());
+ const [phase, setPhase] = (0, import_react20.useState)(speech ? "starting" : speechApi() ? "listening" : "unsupported");
+ const [catalog, setCatalog] = (0, import_react20.useState)(null);
const [heard, setHeard] = (0, import_react20.useState)("");
const [said, setSaid] = (0, import_react20.useState)("");
+ const [note, setNote] = (0, import_react20.useState)("");
+ const [serviceLevel, setServiceLevel] = (0, import_react20.useState)(0);
+ const [cycle, setCycle] = (0, import_react20.useState)(0);
const waiting = (0, import_react20.useRef)(null);
+ const reply = (0, import_react20.useRef)(lastReply);
+ reply.current = lastReply;
+ const turn = (0, import_react20.useRef)(0);
const paneLeft = usePaneLeft();
const close = () => {
+ turn.current += 1;
window.speechSynthesis?.cancel();
actions.closeVoice();
};
useEscape(close);
+ const submit = (text) => {
+ setHeard(text);
+ setPhase("thinking");
+ waiting.current = reply.current.split("|")[0];
+ void actions.send(sessionId, text.trim()).catch(() => setPhase("listening"));
+ };
const dictation = useDictation((text, final) => {
setHeard(text);
if (!final) return;
dictation.stop();
- setPhase("thinking");
- waiting.current = lastReply.split("|")[0];
- void actions.send(sessionId, text.trim()).catch(() => setPhase("listening"));
+ submit(text);
});
+ (0, import_react20.useEffect)(() => {
+ if (!note) return void 0;
+ const timer = setTimeout(() => setNote(""), 2600);
+ return () => clearTimeout(timer);
+ }, [note]);
+ (0, import_react20.useEffect)(() => {
+ if (!speech) return void 0;
+ let live = true;
+ speechCatalog(speech).then(({ catalog: next, usable }) => {
+ if (!live) return;
+ setCatalog(next);
+ setPhase(usable ? "listening" : "setup");
+ }, () => {
+ if (live) setPhase("setup");
+ });
+ return () => {
+ live = false;
+ };
+ }, [speech]);
const listen = phase === "listening";
(0, import_react20.useEffect)(() => {
- if (!listen || dictation.listening) return void 0;
+ if (speech || !listen || dictation.listening) return void 0;
const timer = setTimeout(() => dictation.start({ continuous: false, onEnd: () => {
} }), 250);
return () => clearTimeout(timer);
@@ -7612,20 +7898,82 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus }
(0, import_react20.useEffect)(() => {
if (phase !== "listening") dictation.stop();
}, [phase]);
+ (0, import_react20.useEffect)(() => {
+ if (!speech || !catalog || !listen) return void 0;
+ const own = turn.current;
+ let capture = null;
+ let frame = 0;
+ let stopped = false;
+ let smooth = 0;
+ const detect = turnDetector();
+ const limit = Math.max(1, catalog.maxDurationSeconds - 1) * 1e3;
+ const finish = async (current) => {
+ setPhase("transcribing");
+ try {
+ const wave = await current.finish(catalog.maxDurationSeconds);
+ const text = wave ? await transcribeWave(speech, catalog, wave, new AbortController().signal) : "";
+ if (turn.current !== own) return;
+ if (text) submit(text);
+ else setPhase("listening");
+ } catch (error) {
+ if (turn.current !== own) return;
+ setNote(t(CAPTURE_NOTES[error?.kind] ?? "Couldn't hear that"));
+ setPhase("listening");
+ }
+ };
+ openCapture().then((opened) => {
+ if (stopped) {
+ opened.cancel();
+ return;
+ }
+ capture = opened;
+ const began = performance.now();
+ const tick = () => {
+ const now = performance.now();
+ const level2 = capture.level();
+ smooth = smooth * 0.8 + level2 * 0.2;
+ setServiceLevel(Math.round(smooth * 100) / 100);
+ const state = detect(level2, now);
+ if (state === "done" || state === "speech" && now - began >= limit) {
+ const current = capture;
+ capture = null;
+ setServiceLevel(0);
+ void finish(current);
+ return;
+ }
+ if (state === "waiting" && now - began >= limit) {
+ setCycle((value) => value + 1);
+ return;
+ }
+ frame = requestAnimationFrame(tick);
+ };
+ tick();
+ }, (error) => {
+ if (stopped) return;
+ setNote(t(CAPTURE_NOTES[error?.kind] ?? "Couldn't hear that"));
+ setPhase("paused");
+ });
+ return () => {
+ stopped = true;
+ cancelAnimationFrame(frame);
+ capture?.cancel();
+ setServiceLevel(0);
+ };
+ }, [speech, catalog, listen, cycle]);
(0, import_react20.useEffect)(() => {
if (phase !== "thinking" || running || waiting.current === null) return;
const [count, text] = [lastReply.slice(0, lastReply.indexOf("|")), lastReply.slice(lastReply.indexOf("|") + 1)];
if (count === waiting.current || !text.trim()) return;
waiting.current = null;
- const speech = plainSpeech(text);
- setSaid(speech);
+ const spoken = plainSpeech(text);
+ setSaid(spoken);
setHeard("");
- if (!window.speechSynthesis || !speech) {
+ if (!window.speechSynthesis || !spoken) {
setPhase("listening");
return;
}
- const utterance = new SpeechSynthesisUtterance(speech);
- utterance.lang = /[\u3400-\u9fff]/.test(speech) ? "zh-CN" : "en-US";
+ const utterance = new SpeechSynthesisUtterance(spoken);
+ utterance.lang = /[\u3400-\u9fff]/.test(spoken) ? "zh-CN" : "en-US";
utterance.onend = () => setPhase((current) => current === "speaking" ? "listening" : current);
utterance.onerror = utterance.onend;
setPhase("speaking");
@@ -7633,23 +7981,28 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus }
window.speechSynthesis.speak(utterance);
}, [phase, running, lastReply]);
(0, import_react20.useEffect)(() => () => window.speechSynthesis?.cancel(), []);
- const level = useMicLevel(phase === "listening" && dictation.listening);
- const markState = phase === "thinking" ? "thinking" : phase === "speaking" ? "sending" : "idle";
+ const micLevel = useMicLevel(!speech && phase === "listening" && dictation.listening);
+ const level = speech ? serviceLevel : micLevel;
+ const markState = phase === "thinking" || phase === "transcribing" ? "thinking" : phase === "speaking" ? "sending" : "idle";
+ const blocked = phase === "unsupported" || phase === "setup" || phase === "starting";
const togglePause = () => {
if (phase === "paused") {
setPhase("listening");
return;
}
+ turn.current += 1;
window.speechSynthesis?.cancel();
setPhase("paused");
};
+ const openSetup = phase === "setup" ? actions.voiceSetup() : null;
const caption = phase === "speaking" ? said : heard;
+ const shownNote = note || dictation.note;
return (0, import_react20.createElement)(
"div",
{ className: "bt-pane bt-voice-pane", style: { left: paneLeft } },
(0, import_react20.createElement)(
"div",
- { className: "bt-voice-stage", role: "dialog", "aria-label": t("Voice chat with {name}", { name }), "data-phase": phase },
+ { className: "bt-voice-stage", role: "dialog", "aria-label": t("Voice chat with {name}", { name }), "data-phase": phase === "transcribing" ? "thinking" : phase },
(0, import_react20.createElement)(
"div",
{ className: "bt-voice-orb", style: { "--bt-level": level } },
@@ -7661,10 +8014,14 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus }
(0, import_react20.createElement)(
"div",
{ className: "bt-voice-status", role: "status" },
- phase === "thinking" ? (0, import_react20.createElement)(Shimmer, null, t("Thinking…")) : VOICE_LABELS[phase] ? t(VOICE_LABELS[phase]) : ""
+ phase === "thinking" ? (0, import_react20.createElement)(Shimmer, null, t("Thinking…")) : phase === "transcribing" ? (0, import_react20.createElement)(Shimmer, null, t("Recognizing…")) : VOICE_LABELS[phase] ? t(VOICE_LABELS[phase]) : ""
),
(0, import_react20.createElement)("div", { className: "bt-voice-caption", key: `${phase}:${caption.slice(0, 12)}` }, caption),
- dictation.note ? (0, import_react20.createElement)("div", { className: "bt-voice-note" }, dictation.note) : null
+ openSetup ? (0, import_react20.createElement)("button", { type: "button", className: "bt-voice-setup", onClick: () => {
+ close();
+ openSetup();
+ } }, t("Set up voice input")) : null,
+ shownNote ? (0, import_react20.createElement)("div", { className: "bt-voice-note" }, shownNote) : null
),
(0, import_react20.createElement)(
"div",
@@ -7673,7 +8030,7 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus }
type: "button",
className: "bt-voice-btn",
"aria-pressed": phase === "paused",
- disabled: phase === "unsupported",
+ disabled: blocked,
"aria-label": phase === "paused" ? t("Resume listening") : t("Pause"),
onClick: togglePause
}, (0, import_react20.createElement)(MicIcon, { size: 20 }), phase === "paused" ? (0, import_react20.createElement)("span", { className: "bt-voice-slash", "aria-hidden": true }) : null),
@@ -11380,7 +11737,7 @@ function writeMode(mode, storage = globalThis.localStorage) {
}
// src/client/index.js
-var inject = ["sessions", "uiWorkspace", "slots", "theme", "layout", "configForms"];
+var inject = ["sessions", "uiWorkspace", "uiConversation", "slots", "theme", "layout", "configForms"];
function apply(ctx) {
ctx.effect(() => installLocale(ctx.get("locale")), "ds-bot: interface copy");
const roster = createSource(EMPTY_ROSTER);
@@ -11551,7 +11908,7 @@ function apply(ctx) {
const value = await call("update-check", { fresh: false }).catch(() => null);
if (stopped) return;
if (value) update.set(value);
- timer = setTimeout(loop, value?.phase === "installing" ? 2e3 : 60 * 6e4);
+ timer = setTimeout(loop, value?.phase === "installing" || value?.dsh?.phase === "installing" ? 2e3 : 60 * 6e4);
};
wakeUpdate = loop;
void loop();
@@ -11924,6 +12281,7 @@ function apply(ctx) {
updateBot: (id, patch) => after(call("update-bot", { id, ...patch })),
refreshModels: () => after(call("models")).catch(() => {
}),
+ efforts: (ref) => call("efforts", { ref }),
deleteBot: (id) => after(call("delete-bot", { id })),
duplicateBot: (id) => after(call("duplicate-bot", { id })),
setPrefs: (prefs) => after(call("set-prefs", prefs)),
@@ -12010,11 +12368,23 @@ function apply(ctx) {
actions.signIn = () => ui.set((state) => ({ ...state, signIn: (state.signIn ?? 0) + 1 }));
actions.closeSignIn = () => ui.set((state) => ({ ...state, signIn: null }));
actions.accountT = () => ctx.get("locale").bind("settings.account");
+ actions.speech = () => ctx.get("remote.speech") ?? void 0;
+ actions.voiceSetup = () => {
+ const navigation = ctx.get("pluginNavigation");
+ return navigation ? () => navigation.openBundle(VOICE_BUNDLE) : null;
+ };
actions.seatAccount = (on) => ui.set((state) => state.accountSeated === on ? state : { ...state, accountSeated: on });
actions.installUpdate = async () => {
- update.set(await call("update-install"));
+ const value = await call("update-install");
+ update.set((previous) => ({ ...previous, ...value }));
+ wakeUpdate();
+ };
+ actions.installDshUpdate = async () => {
+ const dsh = await call("dsh-update-install");
+ update.set((previous) => ({ ...previous, dsh }));
wakeUpdate();
};
+ actions.openAppUpdates = () => window.dshDesktop?.updates?.open?.();
actions.noteTurnTime = (sessionId, turn, key, time) => {
if (sessionId === void 0 || !Number.isFinite(turn) || !Number.isFinite(time)) return;
turnClock.set((state) => {
@@ -12055,6 +12425,18 @@ function apply(ctx) {
const browserPages = browsers?.pages ?? createSource({});
const browserTabs = browsers?.tabs ?? createSource({});
const face = () => ({ actions, hooks: { roster, ui, activity, memoryNews, registry, turnClock, live, browserPages, browserTabs, surface, update } });
+ const assistantFace = (sessionId) => {
+ const binding = ctx.sessions.binding(sessionId);
+ if (binding === void 0) throw new Error(`ds-bot: unknown session "${sessionId}"`);
+ const chat = ctx.uiConversation.binding(binding).target("chat");
+ return { ...face(), keyedHooks: {
+ turnSteps: (turn) => {
+ const snapshot = chat.getSnapshot();
+ if (snapshot === void 0) throw new Error("ds-bot: Chat target is unavailable");
+ return snapshot.nodes.turnDataSource(Number(turn), "assistant-step");
+ }
+ } };
+ };
const shadow = (name, options, component) => ctx.slots.inject(name, () => ctx.slots.register({ name, ...options }, component));
const installShell = () => [
installCompiledStyles(SHELL_CSS, "shell"),
@@ -12089,7 +12471,7 @@ function apply(ctx) {
// the mode is held at `verbose` while this group is mounted.
holdFlatTranscript(ctx.configForms.get("ui-chat")),
shadow("conversation.session.header", { priority: -10, inject: face }, HeaderPill),
- shadow("conversation.chat.node", { key: "assistant-step", priority: -10, locale: "chat", inject: face }, AssistantCell),
+ shadow("conversation.chat.node", { key: "assistant-step", priority: -10, locale: "chat", inject: assistantFace }, AssistantCell),
shadow("conversation.chat.node", { key: "turn-trigger", priority: -10, locale: "chat", inject: face }, TriggerCell),
shadow("conversation.chat.node", { key: "tool-call", priority: -10, locale: "chat", inject: face }, ToolCell),
shadow("conversation.chat.node", { key: "turn-process", priority: -10, locale: "chat", inject: face }, TurnProcessCell),
diff --git a/ds-bot/index.js b/ds-bot/index.js
index 807833f7..b639f9fc 100644
--- a/ds-bot/index.js
+++ b/ds-bot/index.js
@@ -23,6 +23,7 @@ import * as connectors from './src/host/connectors.js'
import * as schedules from './src/host/schedules.js'
import * as usage from './src/host/usage.js'
import * as update from './src/host/update.js'
+import * as dshUpdate from './src/host/dsh-update.js'
import * as channel from './src/host/channel.js'
export { COLORS } from './src/host/constants.js'
@@ -34,7 +35,7 @@ export const inject = ['llm', 'tools', 'systemPrompt', 'sessionController', 'ses
// the functions other modules call; they call them through `rt` at run time, never during
// install. Listeners run and tools are listed in registration order, so this order holds:
// usage meters model requests after every listener that rewrites them.
-const MODULES = [diagnostics, store, models, turns, delivery, roster, agents, prompt, tools, chatIndex, groups, memory, parts, images, secrets, connectors, schedules, browser, usage, update, channel]
+const MODULES = [diagnostics, store, models, turns, delivery, roster, agents, prompt, tools, chatIndex, groups, memory, parts, images, secrets, connectors, schedules, browser, usage, update, dshUpdate, channel]
export function apply(ctx, config = {}) {
const home = config.home ?? join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'bot')
diff --git a/ds-bot/package.json b/ds-bot/package.json
index caa26d25..4282ffdc 100644
--- a/ds-bot/package.json
+++ b/ds-bot/package.json
@@ -58,6 +58,9 @@
"patch": "./cordis.patch.yml"
}
},
+ "dsBot": {
+ "verifiedDsh": "0.2.1-alpha.1"
+ },
"devDependencies": {
"esbuild": "0.28.2"
}
diff --git a/ds-bot/src/client/bot-draft.js b/ds-bot/src/client/bot-draft.js
index 280fd5d7..bc8d5645 100644
--- a/ds-bot/src/client/bot-draft.js
+++ b/ds-bot/src/client/bot-draft.js
@@ -15,9 +15,10 @@ export function startModel(roster) {
}
// The model is always sent: the host fixes it on the Bot at creation.
-export function createPayload({ name, look, image, model, brief }) {
+export function createPayload({ name, look, image, model, effort, brief }) {
const payload = { name, color: look.color, avatar: image ? { shape: look.shape, image } : { shape: look.shape } }
if (model) payload.model = model
+ if (effort) payload.effort = effort
if (brief) payload.brief = brief
return payload
}
diff --git a/ds-bot/src/client/cells.js b/ds-bot/src/client/cells.js
index 88b05eea..aa809c2a 100644
--- a/ds-bot/src/client/cells.js
+++ b/ds-bot/src/client/cells.js
@@ -9,6 +9,7 @@ import { AnsweredCell, SettledQuestion, PendingQuestion } from './questions.js'
import { SecretToolCell } from './secret-card.js'
import { dateLocale, t } from './i18n.js'
import { failureLabel } from './diagnostics.js'
+import { turnReasoning } from './turn-reasoning.js'
// -------------------------------------------------------------------------
// Chat cells
@@ -99,28 +100,26 @@ function MessageTools({ text, name, sessionId, react, actions }) {
item(t('Copy'), CopyIcon, copy), item(t('Download'), DownloadIcon, download)), document.body) : null)
}
-// Live reasoning shows only as the activity row's phrase.
-function ThinkingRow({ text, running }) {
- if (running || !text) return null
+function ThinkingRow({ text }) {
return h('details', { className: 'bt-think' },
h('summary', null, t('Thought it through')),
h('div', { className: 'bt-think-text' }, text))
}
-export function AssistantCell({ node, groupPart, sessionId, useRoster, useUi, actions }) {
+export function AssistantCell({ node, groupPart, sessionId, useRoster, useUi, useTurnSteps, actions }) {
const roster = useRoster(value => value)
const data = node.data
+ const steps = useTurnSteps(String(data.turn))
const hidden = Boolean(roster.roomsById[sessionId]) || isHiddenTurn(roster, sessionId, data.turn)
const texts = groupPart === 'reasoning' ? [] : data.blocks.filter(block => block.kind === 'text' && block.text.trim() !== '').map(block => block.text)
const running = data.status === 'running'
// A streaming reply stands in for the activity row.
useLiveNote(actions, sessionId, `text:${node.key ?? data.seq}`, !hidden && running && texts.length > 0 ? { text: true } : null)
if (hidden) return null
- const reasoning = groupPart === 'response' ? '' : data.blocks.filter(block => block.kind === 'reasoning').map(block => block.text).join('\n').trim()
- const thinkingLive = running && texts.length === 0 && data.blocks.some(block => block.kind === 'reasoning')
+ const reasoning = groupPart === 'response' ? '' : turnReasoning(steps, data)
if (texts.length === 0 && !reasoning) return null
return h(Fragment, null,
- reasoning ? h(ThinkingRow, { text: reasoning, running: thinkingLive }) : null,
+ reasoning ? h(ThinkingRow, { text: reasoning }) : null,
texts.length ? h(Bubbles, { texts, roster, selfId: roster.byId[sessionId]?.id ?? sessionId, actions, streaming: running, sessionId, msgKey: `${sessionId}:${data.turn}:${node.key ?? data.seq ?? ''}`, useUi }) : null)
}
diff --git a/ds-bot/src/client/composer.js b/ds-bot/src/client/composer.js
index 62eff5d3..d9c97901 100644
--- a/ds-bot/src/client/composer.js
+++ b/ds-bot/src/client/composer.js
@@ -73,8 +73,10 @@ export function ComposerVoice({ sessionId, inputActions, actions, useUi }) {
}
}, [quote?.token])
if (sessionId === undefined) return null
+ // With the Voice Input plugin on, its own microphone sits in this composer.
+ const pluginMic = actions.speech() !== undefined
return h(Fragment, null,
- h('button', {
+ pluginMic ? null : h('button', {
type: 'button', className: 'bt-mic', 'aria-label': dictation.listening ? t('Stop dictation') : t('Dictate'),
'aria-pressed': dictation.listening, title: dictation.listening ? t('Stop dictation') : t('Dictate'),
onMouseDown: keepComposerFocus, onClick: () => (dictation.listening ? dictation.stop() : dictation.start()),
diff --git a/ds-bot/src/client/create-bot.js b/ds-bot/src/client/create-bot.js
index a7271786..55b7ba4a 100644
--- a/ds-bot/src/client/create-bot.js
+++ b/ds-bot/src/client/create-bot.js
@@ -22,6 +22,7 @@ export function CreateBot({ roster, actions, start, brief = '', onBack, canGoBac
const [image, setImage] = useState(null)
const [name, setName] = useState(start?.name ?? '')
const [model, setModel] = useState(() => startModel(roster))
+ const [effort, setEffort] = useState(undefined)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const fileRef = useRef(null)
@@ -37,7 +38,7 @@ export function CreateBot({ roster, actions, start, brief = '', onBack, canGoBac
setError('')
setBusy(true)
try {
- const bot = await actions.createBot(createPayload({ name: finalName, look, image, model, brief }))
+ const bot = await actions.createBot(createPayload({ name: finalName, look, image, model, effort, brief }))
onCreated(bot)
} catch (failure) {
setError(failure?.message ?? String(failure))
@@ -78,7 +79,7 @@ export function CreateBot({ roster, actions, start, brief = '', onBack, canGoBac
clash ? h('span', { className: 'bt-note bt-danger' }, t('A Bot named {name} already exists', { name: finalName })) : null),
h('div', { className: 'bt-field' },
h('span', { className: 'bt-field-label' }, t('Model')),
- h(ModelMenu, { bot: { id: 'new-bot', name: finalName, model: model || undefined }, roster, actions, wide: true, onPick: setModel }),
+ h(ModelMenu, { bot: { id: 'new-bot', name: finalName, model: model || undefined, effort }, roster, actions, wide: true, onPick: ref => { setModel(ref); setEffort(undefined) }, onPickEffort: setEffort }),
h('span', { className: 'bt-note' }, (roster.models ?? []).length > 0
? t('The Bot runs on this model. You can change it later in its details.')
: t('Add a provider and a model in DeepSeek Harness first, or pick one in the Bot\'s chat later.'))),
diff --git a/ds-bot/src/client/i18n.js b/ds-bot/src/client/i18n.js
index f0bbf96a..305ff84e 100644
--- a/ds-bot/src/client/i18n.js
+++ b/ds-bot/src/client/i18n.js
@@ -226,6 +226,7 @@ const ZH = {
// Model menu
Default: '默认',
+ 'Thinking level': '思考强度',
'Model: {model}': '模型:{model}',
none: '无',
'Choose a model': '选择模型',
@@ -318,6 +319,13 @@ const ZH = {
'The update did not finish: {reason}': '更新没有完成:{reason}',
"What's new": '更新说明',
'Updating…': '正在更新…',
+ 'DSH {version} is available': 'DSH {version} 可以更新',
+ 'Updating DSH…': '正在更新 DSH…',
+ 'DSH update': 'DSH 更新',
+ 'DSH {version}': 'DSH {version}',
+ 'Restart DSH to start using DSH {version}.': '重启 DSH 后开始使用 DSH {version}。',
+ 'Update DS Bot {version} first.': '先更新 DS Bot {version}。',
+ 'Open updates': '打开更新',
// Command palette
Messages: '消息',
@@ -560,6 +568,10 @@ const ZH = {
'Resume listening': '继续听',
Pause: '暂停',
'End voice chat': '结束语音对话',
+ 'Recognizing…': '识别中…',
+ 'Voice input needs its speech model': '语音输入还没有语音模型',
+ 'Set up voice input': '设置语音输入',
+ 'That was too long to recognize': '这段太长了,识别不了',
// Usage page
'24 hours': '24 小时',
diff --git a/ds-bot/src/client/index.js b/ds-bot/src/client/index.js
index 5e2a6f53..58201330 100644
--- a/ds-bot/src/client/index.js
+++ b/ds-bot/src/client/index.js
@@ -9,6 +9,7 @@ import { lookOf } from './mark.js'
import { TeamSidebar, ConnectPlugins, YouAvatar, AccountLauncher, FooterAccount, BrandMark, BrandName, BotReturn, SIDEBAR_CSS, RETURN_CSS, holdShellShortcuts } from './sidebar.js'
import { HeaderPill } from './header.js'
import { ComposerPlus, ComposerVoice } from './composer.js'
+import { VOICE_BUNDLE } from './speech.js'
import { AnsweredCell, QuestionCard, QuestionDock } from './questions.js'
import { AssistantCell, TriggerCell, TurnProcessCell, Nothing, TurnTailCell, ToolCell } from './cells.js'
import { Overlays } from './overlays.js'
@@ -27,7 +28,7 @@ import { installLocale, language } from './i18n.js'
import { noteClientError, quietly } from './diagnostics.js'
import { ErrorToast, FEEDBACK_CSS } from './feedback.js'
-export const inject = ['sessions', 'uiWorkspace', 'slots', 'theme', 'layout', 'configForms']
+export const inject = ['sessions', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout', 'configForms']
export function apply(ctx) {
ctx.effect(() => installLocale(ctx.get('locale')), 'ds-bot: interface copy')
@@ -181,7 +182,7 @@ export function apply(ctx) {
const value = await call('update-check', { fresh: false }).catch(() => null)
if (stopped) return
if (value) update.set(value)
- timer = setTimeout(loop, value?.phase === 'installing' ? 2000 : 60 * 60_000)
+ timer = setTimeout(loop, value?.phase === 'installing' || value?.dsh?.phase === 'installing' ? 2000 : 60 * 60_000)
}
wakeUpdate = loop
void loop()
@@ -504,6 +505,7 @@ export function apply(ctx) {
createRoom: (members, options = {}) => after(call('create-room', { members, ...options })),
updateBot: (id, patch) => after(call('update-bot', { id, ...patch })),
refreshModels: () => after(call('models')).catch(() => {}),
+ efforts: ref => call('efforts', { ref }),
deleteBot: id => after(call('delete-bot', { id })),
duplicateBot: id => after(call('duplicate-bot', { id })),
setPrefs: prefs => after(call('set-prefs', prefs)),
@@ -590,12 +592,27 @@ export function apply(ctx) {
actions.signIn = () => ui.set(state => ({ ...state, signIn: (state.signIn ?? 0) + 1 }))
actions.closeSignIn = () => ui.set(state => ({ ...state, signIn: null }))
actions.accountT = () => ctx.get('locale').bind('settings.account')
+ // The Voice Input plugin's speech Remote; absent while that plugin is off.
+ actions.speech = () => ctx.get('remote.speech') ?? undefined
+ actions.voiceSetup = () => {
+ const navigation = ctx.get('pluginNavigation')
+ return navigation ? () => navigation.openBundle(VOICE_BUNDLE) : null
+ }
actions.seatAccount = on => ui.set(state => (state.accountSeated === on ? state : { ...state, accountSeated: on }))
// The install runs on the host; the check loop follows it every two seconds.
actions.installUpdate = async () => {
- update.set(await call('update-install'))
+ const value = await call('update-install')
+ update.set(previous => ({ ...previous, ...value }))
+ wakeUpdate()
+ }
+ // The DSH the newest released DS Bot verified installs the same way.
+ actions.installDshUpdate = async () => {
+ const dsh = await call('dsh-update-install')
+ update.set(previous => ({ ...previous, dsh }))
wakeUpdate()
}
+ // A packaged DSH only updates inside its app; the button opens the app's panel.
+ actions.openAppUpdates = () => window.dshDesktop?.updates?.open?.()
actions.noteTurnTime = (sessionId, turn, key, time) => {
if (sessionId === undefined || !Number.isFinite(turn) || !Number.isFinite(time)) return
turnClock.set((state) => {
@@ -636,6 +653,18 @@ export function apply(ctx) {
const browserPages = browsers?.pages ?? createSource({})
const browserTabs = browsers?.tabs ?? createSource({})
const face = () => ({ actions, hooks: { roster, ui, activity, memoryNews, registry, turnClock, live, browserPages, browserTabs, surface, update } })
+ const assistantFace = (sessionId) => {
+ const binding = ctx.sessions.binding(sessionId)
+ if (binding === undefined) throw new Error(`ds-bot: unknown session "${sessionId}"`)
+ const chat = ctx.uiConversation.binding(binding).target('chat')
+ return { ...face(), keyedHooks: {
+ turnSteps: (turn) => {
+ const snapshot = chat.getSnapshot()
+ if (snapshot === undefined) throw new Error('ds-bot: Chat target is unavailable')
+ return snapshot.nodes.turnDataSource(Number(turn), 'assistant-step')
+ },
+ } }
+ }
const shadow = (name, options, component) => ctx.slots.inject(name, () => ctx.slots.register({ name, ...options }, component))
@@ -675,7 +704,7 @@ export function apply(ctx) {
// the mode is held at `verbose` while this group is mounted.
holdFlatTranscript(ctx.configForms.get('ui-chat')),
shadow('conversation.session.header', { priority: -10, inject: face }, HeaderPill),
- shadow('conversation.chat.node', { key: 'assistant-step', priority: -10, locale: 'chat', inject: face }, AssistantCell),
+ shadow('conversation.chat.node', { key: 'assistant-step', priority: -10, locale: 'chat', inject: assistantFace }, AssistantCell),
shadow('conversation.chat.node', { key: 'turn-trigger', priority: -10, locale: 'chat', inject: face }, TriggerCell),
shadow('conversation.chat.node', { key: 'tool-call', priority: -10, locale: 'chat', inject: face }, ToolCell),
shadow('conversation.chat.node', { key: 'turn-process', priority: -10, locale: 'chat', inject: face }, TurnProcessCell),
diff --git a/ds-bot/src/client/model-menu.js b/ds-bot/src/client/model-menu.js
index 15185252..75c57c45 100644
--- a/ds-bot/src/client/model-menu.js
+++ b/ds-bot/src/client/model-menu.js
@@ -42,6 +42,48 @@ export function modelOf(bot, roster) {
return { ref, name: served?.name ?? rest.join('/'), provider: served?.providerName ?? provider, served: served !== undefined }
}
+// The thinking levels of one model, `{efforts, defaultEffort?}` or undefined when it
+// has none. The catalog carries them for models Bots use; any other ref asks the host.
+const effortCache = new Map()
+function useEfforts(served, ref, actions) {
+ const [fetched, setFetched] = useState(undefined)
+ useEffect(() => {
+ setFetched(undefined)
+ if (ref === undefined || served?.reasoning !== undefined || actions?.efforts === undefined) return undefined
+ let live = true
+ if (effortCache.has(ref)) setFetched(effortCache.get(ref))
+ else void Promise.resolve(actions.efforts(ref)).then((value) => {
+ const reasoning = value?.efforts ? value : null
+ effortCache.set(ref, reasoning)
+ if (live) setFetched(reasoning)
+ }).catch(() => {})
+ return () => { live = false }
+ }, [ref, served?.reasoning !== undefined, actions])
+ return served?.reasoning ?? fetched
+}
+
+// The rows of the Thinking section: a Default row that clears the Bot's pick, then every
+// level the model serves.
+export function effortRows(reasoning) {
+ if (reasoning?.efforts === undefined || reasoning.efforts.length === 0) return []
+ return [
+ { effort: undefined, label: t('Default') },
+ ...reasoning.efforts.map(effort => ({ effort: effort.id, label: effort.name })),
+ ]
+}
+
+function EffortRows({ reasoning, current, onPick }) {
+ return h(Fragment, null,
+ h('div', { className: 'bt-menu-sep', role: 'separator' }),
+ h('div', { className: 'bt-model-group', role: 'presentation' }, t('Thinking level')),
+ effortRows(reasoning).map(row => h('button', {
+ key: row.effort ?? 'default', type: 'button', role: 'menuitemradio', 'aria-checked': row.effort === current,
+ onClick: () => onPick(row.effort),
+ },
+ h('span', { className: 'bt-menu-label' }, row.label),
+ h('span', { className: 'bt-model-tick', 'aria-hidden': true }, row.effort === current ? h(CheckIcon) : null))))
+}
+
function ModelRows({ roster, current, onPick }) {
return groupModels(roster.models).map(([provider, list]) => h(Fragment, { key: list[0].provider ?? provider },
h('div', { className: 'bt-model-group', role: 'presentation' }, provider),
@@ -55,15 +97,24 @@ function ModelRows({ roster, current, onPick }) {
}
// The trigger shows the model name over its provider; the menu opens under it, or
-// above when the window has no room below.
-// `onPick` replaces saving to the Bot, for a Bot that does not exist yet.
-export function ModelMenu({ bot, roster, actions, run, wide = false, onPick }) {
+// above when the window has no room below. A Thinking section lists the levels of
+// the shown model when it has them.
+// `onPick`/`onPickEffort` replace saving to the Bot, for a Bot that does not exist yet.
+export function ModelMenu({ bot, roster, actions, run, wide = false, onPick, onPickEffort }) {
const [place, setPlace] = useState(null)
const [shownPlace, leaving] = useLinger(place, MENU_EXIT_MS)
const button = useRef(null)
const menu = useRef(null)
const shown = modelOf(bot, roster)
const current = bot.model ?? bot.appliedModel
+ const served = servedOf(roster, current)
+ const reasoning = useEfforts(served, current, actions)
+ // The level the Bot runs on: its pick when the model serves it, else the model's own.
+ const picked = reasoning?.efforts?.some(effort => effort.id === bot.effort) ? bot.effort : undefined
+ const currentEffort = picked ?? reasoning?.defaultEffort
+ const effortLabel = currentEffort === undefined
+ ? (reasoning?.efforts?.length > 0 ? t('Default') : undefined)
+ : reasoning.efforts.find(effort => effort.id === currentEffort)?.name ?? currentEffort
const close = () => setPlace(null)
useEffect(() => {
if (place === null) return undefined
@@ -99,6 +150,11 @@ export function ModelMenu({ bot, roster, actions, run, wide = false, onPick }) {
if (onPick) onPick(ref)
else if (ref !== current || !bot.model) void run(actions.updateBot(bot.id, { model: ref }))
}
+ const pickEffort = (effort) => {
+ close()
+ if (onPickEffort) onPickEffort(effort)
+ else if (effort !== bot.effort) void run(actions.updateBot(bot.id, { effort: effort ?? null }))
+ }
const models = roster.models ?? []
return h(Fragment, null,
h('button', {
@@ -108,11 +164,14 @@ export function ModelMenu({ bot, roster, actions, run, wide = false, onPick }) {
},
h('span', { className: 'bt-model-copy' },
h('span', { className: 'bt-model-name' }, shown?.name ?? t('Choose a model')),
- shown ? h('span', { className: 'bt-model-provider' }, shown.served || models.length === 0 ? shown.provider : t('{provider} · not available', { provider: shown.provider })) : null),
+ shown ? h('span', { className: 'bt-model-provider' }, shown.served || models.length === 0
+ ? (effortLabel === undefined ? shown.provider : `${shown.provider} · ${effortLabel}`)
+ : t('{provider} · not available', { provider: shown.provider })) : null),
h('svg', { className: 'bt-model-caret', width: 12, height: 12, viewBox: '0 0 20 20', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, h('path', { d: 'M5.5 8l4.5 4.5L14.5 8' }))),
shownPlace ? createPortal(h('div', { ref: menu, className: `bt-menu bt-model-menu${shownPlace.bottom !== undefined ? ' bt-menu-up' : ''}`, role: 'menu', 'aria-label': t('Model for {name}', { name: bot.name }), style: shownPlace, 'data-leaving': leaving || undefined },
models.length > 0 ? h(ModelRows, { roster, current, onPick: pick })
: h('div', { className: 'bt-model-none' }, t('No models are set up in DeepSeek Harness yet.')),
+ effortRows(reasoning).length > 0 ? h(EffortRows, { reasoning, current: picked, onPick: pickEffort }) : null,
h('div', { className: 'bt-menu-sep', role: 'separator' }),
h('button', { type: 'button', role: 'menuitem', onClick: () => { close(); openHarnessSettings() } }, h(SlidersIcon), h('span', { className: 'bt-menu-label' }, t('Models and providers…')))), document.body) : null)
}
diff --git a/ds-bot/src/client/sidebar.js b/ds-bot/src/client/sidebar.js
index 9d29358f..ee9ec0ee 100644
--- a/ds-bot/src/client/sidebar.js
+++ b/ds-bot/src/client/sidebar.js
@@ -260,14 +260,16 @@ export function TeamSidebar(props) {
: h(AgentRow, { key: entry.item.id, ...rowProps, agent: entry.item, marked: markedUnread[entry.item.id] === true })))))
}
-// The update button at the sidebar's top right: a cloud while a newer DS Bot is
-// available, then the install's progress and result. It opens a small card with
-// the versions, a link to the release notes, and the Update button.
+// The update button at the sidebar's top right: a cloud while a newer DS Bot —
+// or a newer verified DSH — is available, then the install's progress and
+// result. Its card has one row each for the bot and DSH, with their versions,
+// the release notes link, and each row's own button.
function UpdateButton({ useUpdate, actions }) {
const update = useUpdate(value => value)
const [open, setOpen] = useState(false)
const [box, setBox] = useState(null)
const [error, setError] = useState('')
+ const [dshError, setDshError] = useState('')
const button = useRef(null)
useEffect(() => {
if (!open) return undefined
@@ -281,7 +283,13 @@ function UpdateButton({ useUpdate, actions }) {
return () => { window.removeEventListener('mousedown', onDown); window.removeEventListener('keydown', onKey, true) }
}, [open])
const phase = update?.phase ?? 'idle'
- if (!update?.available && phase === 'idle') return null
+ const dsh = update?.dsh
+ const dshPhase = dsh?.phase ?? 'idle'
+ // The DSH row shows while its verified version differs from what is running —
+ // offered, gated on a newer bot first, or owned by the app's own updater.
+ const dshRow = dsh && dsh.verified && dsh.current && dsh.verified !== dsh.current
+ if (!update?.available && !dshRow && phase === 'idle' && dshPhase === 'idle') return null
+ const cloudPhase = phase === 'installing' || dshPhase === 'installing' ? 'installing' : phase !== 'idle' ? phase : dshPhase
const toggle = () => {
const rect = button.current?.getBoundingClientRect()
if (rect) setBox({ left: Math.max(8, Math.min(rect.left, window.innerWidth - 288)), top: rect.bottom + 6 })
@@ -291,26 +299,51 @@ function UpdateButton({ useUpdate, actions }) {
setError('')
void actions.installUpdate().catch(failure => setError(hostText(failure?.message ?? String(failure))))
}
+ const startDsh = () => {
+ setDshError('')
+ void actions.installDshUpdate().catch(failure => setDshError(hostText(failure?.message ?? String(failure))))
+ }
const label = phase === 'installing' ? t('Updating DS Bot…')
- : phase === 'installed' ? t('DS Bot {version} is installed. Restart DSH to use it.', { version: update.installed ?? update.latest })
- : t('DS Bot {version} is available', { version: update.latest })
+ : dshPhase === 'installing' ? t('Updating DSH…')
+ : phase === 'installed' ? t('DS Bot {version} is installed. Restart DSH to use it.', { version: update.installed ?? update.latest })
+ : dshPhase === 'installed' ? t('Restart DSH to start using DSH {version}.', { version: dsh.installed ?? dsh.verified })
+ : update?.available ? t('DS Bot {version} is available', { version: update.latest })
+ : t('DSH {version} is available', { version: dsh?.verified })
const message = error || (phase === 'failed' ? update.error : '')
+ const dshMessage = dshError || (dshPhase === 'failed' ? dsh?.error : '')
+ const dshText = dshPhase === 'installed'
+ ? t('Restart DSH to start using DSH {version}.', { version: dsh.installed ?? dsh.verified })
+ : dsh?.available === false && dsh?.blockedBy && dsh.kind === 'npm'
+ ? t('Update DS Bot {version} first.', { version: dsh.blockedBy })
+ : t('You have {version}.', { version: dsh?.current })
return h(Fragment, null,
h('button', {
- ref: button, type: 'button', className: 'bt-round bt-update', 'data-phase': phase, 'aria-label': label, title: label,
+ ref: button, type: 'button', className: 'bt-round bt-update', 'data-phase': cloudPhase, 'aria-label': label, title: label,
'aria-haspopup': 'dialog', 'aria-expanded': open, onClick: toggle,
- }, h(CloudDownloadIcon, { done: phase === 'installed' }), phase === 'failed' ? h('span', { className: 'bt-update-dot', 'aria-hidden': true }) : null),
- open && box ? createPortal(h('div', { className: 'bt-update-pop', role: 'dialog', 'aria-label': t('DS Bot update'), style: box },
- h('div', { className: 'bt-update-title' }, phase === 'installed' ? t('Update installed') : t('DS Bot {version}', { version: update.latest })),
- h('div', { className: 'bt-update-text' }, phase === 'installed'
- ? t('Restart DSH to start using DS Bot {version}.', { version: update.installed ?? update.latest })
- : t('You have {version}.', { version: update.current })),
- message ? h('div', { className: 'bt-update-error', role: 'alert' }, t('The update did not finish: {reason}', { reason: message })) : null,
- h('div', { className: 'bt-update-actions' },
- update.notesUrl ? h('a', { className: 'bt-update-notes', href: update.notesUrl, target: '_blank', rel: 'noopener noreferrer' }, t("What's new")) : null,
- phase === 'installed' ? null : h('button', {
- type: 'button', className: 'bt-update-go', disabled: phase === 'installing', onClick: start,
- }, phase === 'installing' ? t('Updating…') : phase === 'failed' ? t('Try again') : t('Update')))), document.body) : null)
+ }, h(CloudDownloadIcon, { done: phase === 'installed' }), phase === 'failed' || dshPhase === 'failed' ? h('span', { className: 'bt-update-dot', 'aria-hidden': true }) : null),
+ open && box ? createPortal(h('div', { className: 'bt-update-pop', role: 'dialog', 'aria-label': update?.available || phase !== 'idle' ? t('DS Bot update') : t('DSH update'), style: box },
+ update?.available || phase !== 'idle' ? h(Fragment, null,
+ h('div', { className: 'bt-update-title' }, phase === 'installed' ? t('Update installed') : t('DS Bot {version}', { version: update.latest })),
+ h('div', { className: 'bt-update-text' }, phase === 'installed'
+ ? t('Restart DSH to start using DS Bot {version}.', { version: update.installed ?? update.latest })
+ : t('You have {version}.', { version: update.current })),
+ message ? h('div', { className: 'bt-update-error', role: 'alert' }, t('The update did not finish: {reason}', { reason: message })) : null,
+ h('div', { className: 'bt-update-actions' },
+ update.notesUrl ? h('a', { className: 'bt-update-notes', href: update.notesUrl, target: '_blank', rel: 'noopener noreferrer' }, t("What's new")) : null,
+ phase === 'installed' ? null : h('button', {
+ type: 'button', className: 'bt-update-go', disabled: phase === 'installing', onClick: start,
+ }, phase === 'installing' ? t('Updating…') : phase === 'failed' ? t('Try again') : t('Update')))) : null,
+ dshRow ? h('div', { className: 'bt-update-dsh' },
+ h('div', { className: 'bt-update-title' }, t('DSH {version}', { version: dsh.verified })),
+ h('div', { className: 'bt-update-text' }, dshText),
+ dshMessage ? h('div', { className: 'bt-update-error', role: 'alert' }, t('The update did not finish: {reason}', { reason: dshMessage })) : null,
+ h('div', { className: 'bt-update-actions' },
+ dsh.kind === 'app' ? h('button', { type: 'button', className: 'bt-update-go', onClick: () => actions.openAppUpdates() }, t('Open updates'))
+ : !dsh.available && dshPhase === 'idle' ? null
+ : dshPhase === 'installed' ? null
+ : h('button', {
+ type: 'button', className: 'bt-update-go', disabled: dshPhase === 'installing', onClick: startDsh,
+ }, dshPhase === 'installing' ? t('Updating…') : dshPhase === 'failed' ? t('Try again') : t('Update')))) : null), document.body) : null)
}
// The footer entry to the shell's plugin panel, marked as not yet adapted: the red
@@ -576,6 +609,7 @@ export const SIDEBAR_CSS = `
.bt-update-go:hover:not(:disabled){opacity:.9}
.bt-update-go:active:not(:disabled){transform:scale(.96)}
.bt-update-go:disabled{opacity:.6;cursor:default}
+.bt-update-dsh{margin-top:12px;padding-top:12px;border-top:.5px solid var(--bt-line-2)}
@media (prefers-reduced-motion:reduce){.bt-round.bt-update,.bt-update-pop,.bt-update .bt-cloud-arrow{animation:none}}
/* The DSH Agent row and its expanding Session list. The black whale is the
diff --git a/ds-bot/src/client/speech.js b/ds-bot/src/client/speech.js
new file mode 100644
index 00000000..bd9b7efc
--- /dev/null
+++ b/ds-bot/src/client/speech.js
@@ -0,0 +1,121 @@
+// The recognizer of DSH's Voice Input plugin (local SenseVoice). Its `speech` Remote
+// exists only while that plugin is on; the browser's own speech service stays the
+// fallback. The plugin takes one complete 16 kHz mono PCM16 WAV per request.
+export const VOICE_BUNDLE = '@deepseek-ai/dsh-experimental-voice-input-bundle'
+const USABLE = new Set(['ready', 'standby', 'waking'])
+
+export async function speechCatalog(speech) {
+ const result = await speech.catalog()
+ if (!result?.ok) throw new Error(result?.error?.message ?? 'Speech catalog failed')
+ const catalog = result.value
+ const provider = catalog.providers.find(item => item.id === catalog.selection.providerId)
+ return { catalog, usable: USABLE.has(provider?.preparation?.phase) }
+}
+
+export function waveBytes(samples, rate = 16000) {
+ const bytes = new Uint8Array(44 + samples.length * 2)
+ const view = new DataView(bytes.buffer)
+ const ascii = (at, text) => { for (let index = 0; index < text.length; index += 1) bytes[at + index] = text.charCodeAt(index) }
+ ascii(0, 'RIFF')
+ view.setUint32(4, 36 + samples.length * 2, true)
+ ascii(8, 'WAVEfmt ')
+ view.setUint32(16, 16, true)
+ view.setUint16(20, 1, true)
+ view.setUint16(22, 1, true)
+ view.setUint32(24, rate, true)
+ view.setUint32(28, rate * 2, true)
+ view.setUint16(32, 2, true)
+ view.setUint16(34, 16, true)
+ ascii(36, 'data')
+ view.setUint32(40, samples.length * 2, true)
+ samples.forEach((sample, index) => {
+ const value = Math.max(-1, Math.min(1, sample))
+ view.setInt16(44 + index * 2, value < 0 ? Math.round(value * 0x8000) : Math.round(value * 0x7fff), true)
+ })
+ return bytes
+}
+
+export function base64Of(bytes) {
+ let text = ''
+ for (let index = 0; index < bytes.length; index += 0x8000) text += String.fromCharCode(...bytes.subarray(index, index + 0x8000))
+ return btoa(text)
+}
+
+const captureError = (kind, cause) => Object.assign(new Error(kind), { kind, cause })
+
+// One microphone recording. level() reads the live loudness (0–1); finish() returns
+// the WAV, or null when nothing was recorded; cancel() drops it.
+export async function openCapture() {
+ const devices = navigator.mediaDevices
+ if (!devices?.getUserMedia || typeof MediaRecorder === 'undefined') throw captureError('unavailable')
+ let stream
+ try {
+ stream = await devices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true }, video: false })
+ } catch (error) {
+ throw captureError(error?.name === 'NotAllowedError' ? 'blocked' : 'failed', error)
+ }
+ const audio = new AudioContext()
+ const analyser = audio.createAnalyser()
+ analyser.fftSize = 512
+ audio.createMediaStreamSource(stream).connect(analyser)
+ const frame = new Float32Array(analyser.fftSize)
+ const recorder = new MediaRecorder(stream)
+ const chunks = []
+ recorder.ondataavailable = (event) => { if (event.data.size > 0) chunks.push(event.data) }
+ recorder.start()
+ let closed = false
+ const close = () => {
+ if (closed) return
+ closed = true
+ if (recorder.state !== 'inactive') recorder.stop()
+ stream.getTracks().forEach(track => track.stop())
+ void audio.close().catch(() => {})
+ }
+ return {
+ level() {
+ if (closed) return 0
+ analyser.getFloatTimeDomainData(frame)
+ let sum = 0
+ for (const sample of frame) sum += sample * sample
+ return Math.min(1, Math.sqrt(sum / frame.length) * 4)
+ },
+ cancel: close,
+ async finish(maxSeconds) {
+ if (closed || recorder.state === 'inactive') { close(); return null }
+ try {
+ await new Promise((resolve) => { recorder.onstop = resolve; recorder.stop() })
+ stream.getTracks().forEach(track => track.stop())
+ const blob = new Blob(chunks, { type: recorder.mimeType })
+ if (blob.size === 0) return null
+ const decoded = await audio.decodeAudioData(await blob.arrayBuffer())
+ const length = Math.max(1, Math.floor(Math.min(decoded.duration, maxSeconds) * 16000))
+ const offline = new OfflineAudioContext(1, length, 16000)
+ const source = offline.createBufferSource()
+ source.buffer = decoded
+ source.connect(offline.destination)
+ source.start()
+ return waveBytes((await offline.startRendering()).getChannelData(0))
+ } finally { close() }
+ },
+ }
+}
+
+export async function transcribeWave(speech, catalog, wave, signal) {
+ if (wave.byteLength > catalog.maxAudioBytes) throw captureError('too-long')
+ const result = await speech.transcribe({ audioBase64: base64Of(wave), ...catalog.selection }, signal)
+ if (!result?.ok) throw Object.assign(new Error(result?.error?.message ?? 'Transcription failed'), { kind: 'service' })
+ return String(result.value?.text ?? '').trim()
+}
+
+// Voice activity on the loudness of each animation frame: speech starts above
+// `loud`, and the turn ends after `quietMs` below `quiet`.
+export function turnDetector({ loud = 0.12, quiet = 0.06, quietMs = 1200 } = {}) {
+ let spokeAt = 0
+ let quietSince = 0
+ return (level, now) => {
+ if (level >= loud) { spokeAt ||= now; quietSince = 0; return 'speech' }
+ if (!spokeAt) return 'waiting'
+ if (level < quiet) quietSince ||= now
+ return quietSince && now - quietSince >= quietMs ? 'done' : 'speech'
+ }
+}
diff --git a/ds-bot/src/client/styles.js b/ds-bot/src/client/styles.js
index 6a4e0687..db538520 100644
--- a/ds-bot/src/client/styles.js
+++ b/ds-bot/src/client/styles.js
@@ -501,6 +501,8 @@ button.bt-set-row:hover{background:var(--bt-hover)}
.bt-voice-status{font-size:13px;line-height:18px;color:var(--bt-ink-2);min-height:18px}
.bt-voice-caption{min-height:44px;font-size:15px;line-height:22px;color:var(--bt-ink);animation:bt-blur-in .25s ease-out;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}
.bt-voice-note{font-size:12px;color:#e02135}
+.bt-voice-setup{height:32px;padding:0 14px;border-radius:16px;border:0;background:var(--bt-hover);color:var(--bt-ink);font:inherit;font-size:13px;cursor:pointer;transition:background-color .15s ease}
+.bt-voice-setup:hover{background:var(--bt-active)}
.bt-voice-bar{display:flex;gap:16px;padding:0 0 32px}
.bt-voice-btn{position:relative;width:52px;height:52px;border-radius:50%;border:0;background:var(--bt-hover);color:var(--bt-ink);display:grid;place-items:center;cursor:pointer;transition:background-color .15s ease,transform .12s ease}
.bt-voice-btn:hover{background:var(--bt-active)}
diff --git a/ds-bot/src/client/turn-reasoning.js b/ds-bot/src/client/turn-reasoning.js
new file mode 100644
index 00000000..8caa04b9
--- /dev/null
+++ b/ds-bot/src/client/turn-reasoning.js
@@ -0,0 +1,14 @@
+// Settled reasoning of every loaded step in a Turn, shown once on the first step that has
+// reasoning: only steps with reasoning get a reasoning part to render it. A step still
+// thinking stays out until it settles; the activity row shows it meanwhile.
+export function turnReasoning(steps, current) {
+ const members = steps.length ? steps : [current]
+ if (members.find(step => stepReasoning(step) !== '')?.step !== current.step) return ''
+ return members.filter(step => !thinkingLive(step)).map(stepReasoning).filter(Boolean).join('\n\n')
+}
+
+const texts = step => step.blocks.filter(block => block.kind === 'text' && block.text.trim() !== '')
+
+const thinkingLive = step => step.status === 'running' && texts(step).length === 0 && step.blocks.some(block => block.kind === 'reasoning')
+
+const stepReasoning = step => step.blocks.filter(block => block.kind === 'reasoning').map(block => block.text).join('\n').trim()
diff --git a/ds-bot/src/client/voice.js b/ds-bot/src/client/voice.js
index 3cc5c6bb..d68e6b6f 100644
--- a/ds-bot/src/client/voice.js
+++ b/ds-bot/src/client/voice.js
@@ -6,12 +6,18 @@ import { speechApi, useDictation } from './composer.js'
import { Shimmer } from './cells.js'
import { useEscape, usePaneLeft } from './overlay-hooks.js'
import { t } from './i18n.js'
+import { openCapture, speechCatalog, transcribeWave, turnDetector } from './speech.js'
// Voice chat: listen, send what the user said, read the Bot's answer aloud, listen
-// again. Browser speech recognition and synthesis only; nothing leaves the browser
-// except through the browser's own speech service.
+// again. With DSH's Voice Input plugin on, its recognizer hears the user: one
+// recording ends after a pause and is transcribed whole. Otherwise the browser's
+// own speech recognition does. The browser's speech synthesis reads the answer.
const plainSpeech = text => stripHeader(text).replace(/```[\s\S]*?```/g, ' ').replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/[*_`#>|~-]+/g, ' ').replace(/\s+/g, ' ').trim()
-const VOICE_LABELS = { listening: 'Listening', thinking: 'Thinking', speaking: 'Speaking', paused: 'Paused', unsupported: 'Voice chat is not available in this browser' }
+const VOICE_LABELS = {
+ listening: 'Listening', thinking: 'Thinking', speaking: 'Speaking', paused: 'Paused',
+ setup: 'Voice input needs its speech model', unsupported: 'Voice chat is not available in this browser',
+}
+const CAPTURE_NOTES = { blocked: 'Microphone access is blocked', unavailable: 'Voice chat is not available in this browser', 'too-long': 'That was too long to recognize' }
function useMicLevel(enabled) {
const [level, setLevel] = useState(0)
@@ -61,24 +67,53 @@ export function VoiceMode({ sessionId, roster, actions, useSessions, useSessionS
const entry = Array.isArray(outline) ? outline[outline.length - 1] : undefined
return entry ? `${outline.length}|${entry.response ?? ''}` : '0|'
})
- const [phase, setPhase] = useState(speechApi() ? 'listening' : 'unsupported')
+ // The Voice Input plugin's Remote, read once: the engine does not change mid-chat.
+ const [speech] = useState(() => actions.speech())
+ const [phase, setPhase] = useState(speech ? 'starting' : speechApi() ? 'listening' : 'unsupported')
+ const [catalog, setCatalog] = useState(null)
const [heard, setHeard] = useState('')
const [said, setSaid] = useState('')
+ const [note, setNote] = useState('')
+ const [serviceLevel, setServiceLevel] = useState(0)
+ const [cycle, setCycle] = useState(0)
const waiting = useRef(null)
+ const reply = useRef(lastReply)
+ reply.current = lastReply
+ // Bumped on pause and close, so a transcript that arrives later is dropped.
+ const turn = useRef(0)
const paneLeft = usePaneLeft()
- const close = () => { window.speechSynthesis?.cancel(); actions.closeVoice() }
+ const close = () => { turn.current += 1; window.speechSynthesis?.cancel(); actions.closeVoice() }
useEscape(close)
+ const submit = (text) => {
+ setHeard(text)
+ setPhase('thinking')
+ waiting.current = reply.current.split('|')[0]
+ void actions.send(sessionId, text.trim()).catch(() => setPhase('listening'))
+ }
const dictation = useDictation((text, final) => {
setHeard(text)
if (!final) return
dictation.stop()
- setPhase('thinking')
- waiting.current = lastReply.split('|')[0]
- void actions.send(sessionId, text.trim()).catch(() => setPhase('listening'))
+ submit(text)
})
+ useEffect(() => {
+ if (!note) return undefined
+ const timer = setTimeout(() => setNote(''), 2600)
+ return () => clearTimeout(timer)
+ }, [note])
+ useEffect(() => {
+ if (!speech) return undefined
+ let live = true
+ speechCatalog(speech).then(({ catalog: next, usable }) => {
+ if (!live) return
+ setCatalog(next)
+ setPhase(usable ? 'listening' : 'setup')
+ }, () => { if (live) setPhase('setup') })
+ return () => { live = false }
+ }, [speech])
const listen = phase === 'listening'
useEffect(() => {
- if (!listen || dictation.listening) return undefined
+ if (speech || !listen || dictation.listening) return undefined
const timer = setTimeout(() => dictation.start({ continuous: false, onEnd: () => {} }), 250)
return () => clearTimeout(timer)
}, [listen, dictation.listening])
@@ -86,17 +121,75 @@ export function VoiceMode({ sessionId, roster, actions, useSessions, useSessionS
useEffect(() => {
if (phase !== 'listening') dictation.stop()
}, [phase])
+ // The plugin's recognizer: record one utterance, end it after a pause, transcribe it.
+ useEffect(() => {
+ if (!speech || !catalog || !listen) return undefined
+ const own = turn.current
+ let capture = null
+ let frame = 0
+ let stopped = false
+ let smooth = 0
+ const detect = turnDetector()
+ const limit = Math.max(1, catalog.maxDurationSeconds - 1) * 1000
+ const finish = async (current) => {
+ setPhase('transcribing')
+ try {
+ const wave = await current.finish(catalog.maxDurationSeconds)
+ const text = wave ? await transcribeWave(speech, catalog, wave, new AbortController().signal) : ''
+ if (turn.current !== own) return
+ if (text) submit(text)
+ else setPhase('listening')
+ } catch (error) {
+ if (turn.current !== own) return
+ setNote(t(CAPTURE_NOTES[error?.kind] ?? "Couldn't hear that"))
+ setPhase('listening')
+ }
+ }
+ openCapture().then((opened) => {
+ if (stopped) { opened.cancel(); return }
+ capture = opened
+ const began = performance.now()
+ const tick = () => {
+ const now = performance.now()
+ const level = capture.level()
+ smooth = smooth * 0.8 + level * 0.2
+ setServiceLevel(Math.round(smooth * 100) / 100)
+ const state = detect(level, now)
+ if (state === 'done' || (state === 'speech' && now - began >= limit)) {
+ const current = capture
+ capture = null
+ setServiceLevel(0)
+ void finish(current)
+ return
+ }
+ // Nothing said for a whole recording: start a fresh one.
+ if (state === 'waiting' && now - began >= limit) { setCycle(value => value + 1); return }
+ frame = requestAnimationFrame(tick)
+ }
+ tick()
+ }, (error) => {
+ if (stopped) return
+ setNote(t(CAPTURE_NOTES[error?.kind] ?? "Couldn't hear that"))
+ setPhase('paused')
+ })
+ return () => {
+ stopped = true
+ cancelAnimationFrame(frame)
+ capture?.cancel()
+ setServiceLevel(0)
+ }
+ }, [speech, catalog, listen, cycle])
useEffect(() => {
if (phase !== 'thinking' || running || waiting.current === null) return
const [count, text] = [lastReply.slice(0, lastReply.indexOf('|')), lastReply.slice(lastReply.indexOf('|') + 1)]
if (count === waiting.current || !text.trim()) return
waiting.current = null
- const speech = plainSpeech(text)
- setSaid(speech)
+ const spoken = plainSpeech(text)
+ setSaid(spoken)
setHeard('')
- if (!window.speechSynthesis || !speech) { setPhase('listening'); return }
- const utterance = new SpeechSynthesisUtterance(speech)
- utterance.lang = /[\u3400-\u9fff]/.test(speech) ? 'zh-CN' : 'en-US'
+ if (!window.speechSynthesis || !spoken) { setPhase('listening'); return }
+ const utterance = new SpeechSynthesisUtterance(spoken)
+ utterance.lang = /[\u3400-\u9fff]/.test(spoken) ? 'zh-CN' : 'en-US'
utterance.onend = () => setPhase(current => (current === 'speaking' ? 'listening' : current))
utterance.onerror = utterance.onend
setPhase('speaking')
@@ -104,28 +197,36 @@ export function VoiceMode({ sessionId, roster, actions, useSessions, useSessionS
window.speechSynthesis.speak(utterance)
}, [phase, running, lastReply])
useEffect(() => () => window.speechSynthesis?.cancel(), [])
- const level = useMicLevel(phase === 'listening' && dictation.listening)
- const markState = phase === 'thinking' ? 'thinking' : phase === 'speaking' ? 'sending' : 'idle'
+ const micLevel = useMicLevel(!speech && phase === 'listening' && dictation.listening)
+ const level = speech ? serviceLevel : micLevel
+ const markState = phase === 'thinking' || phase === 'transcribing' ? 'thinking' : phase === 'speaking' ? 'sending' : 'idle'
+ const blocked = phase === 'unsupported' || phase === 'setup' || phase === 'starting'
const togglePause = () => {
if (phase === 'paused') { setPhase('listening'); return }
+ turn.current += 1
window.speechSynthesis?.cancel()
setPhase('paused')
}
+ const openSetup = phase === 'setup' ? actions.voiceSetup() : null
const caption = phase === 'speaking' ? said : heard
+ const shownNote = note || dictation.note
return h('div', { className: 'bt-pane bt-voice-pane', style: { left: paneLeft } },
- h('div', { className: 'bt-voice-stage', role: 'dialog', 'aria-label': t('Voice chat with {name}', { name }), 'data-phase': phase },
+ h('div', { className: 'bt-voice-stage', role: 'dialog', 'aria-label': t('Voice chat with {name}', { name }), 'data-phase': phase === 'transcribing' ? 'thinking' : phase },
h('div', { className: 'bt-voice-orb', style: { '--bt-level': level } },
h('span', { className: 'bt-voice-ring', 'aria-hidden': true }),
h('span', { className: 'bt-voice-ring bt-voice-ring-2', 'aria-hidden': true }),
bot ? h(BotMark, { bot, size: 112, state: markState, live: true, gaze: phase === 'listening' }) : room ? h(RoomAvatar, { room, roster, size: 112 }) : null),
h('div', { className: 'bt-voice-name' }, name),
h('div', { className: 'bt-voice-status', role: 'status' },
- phase === 'thinking' ? h(Shimmer, null, t('Thinking…')) : VOICE_LABELS[phase] ? t(VOICE_LABELS[phase]) : ''),
+ phase === 'thinking' ? h(Shimmer, null, t('Thinking…'))
+ : phase === 'transcribing' ? h(Shimmer, null, t('Recognizing…'))
+ : VOICE_LABELS[phase] ? t(VOICE_LABELS[phase]) : ''),
h('div', { className: 'bt-voice-caption', key: `${phase}:${caption.slice(0, 12)}` }, caption),
- dictation.note ? h('div', { className: 'bt-voice-note' }, dictation.note) : null),
+ openSetup ? h('button', { type: 'button', className: 'bt-voice-setup', onClick: () => { close(); openSetup() } }, t('Set up voice input')) : null,
+ shownNote ? h('div', { className: 'bt-voice-note' }, shownNote) : null),
h('div', { className: 'bt-voice-bar' },
h('button', {
- type: 'button', className: 'bt-voice-btn', 'aria-pressed': phase === 'paused', disabled: phase === 'unsupported',
+ type: 'button', className: 'bt-voice-btn', 'aria-pressed': phase === 'paused', disabled: blocked,
'aria-label': phase === 'paused' ? t('Resume listening') : t('Pause'), onClick: togglePause,
}, h(MicIcon, { size: 20 }), phase === 'paused' ? h('span', { className: 'bt-voice-slash', 'aria-hidden': true }) : null),
h('button', { type: 'button', className: 'bt-voice-btn bt-voice-end', 'aria-label': t('End voice chat'), onClick: close }, h(CloseIcon))))
diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.js
index 38aafd61..00723261 100644
--- a/ds-bot/src/host/channel.js
+++ b/ds-bot/src/host/channel.js
@@ -27,7 +27,7 @@ export function install(rt) {
const fail = (message, code = 'bot/error') => ({ ok: false, error: { code, message, details: {} } })
// Models come from DSH, not state.json, so a provider added in Harness settings
// changes the view without a new revision.
- const modelsKey = () => `${rt.cachedCatalog().map(entry => entry.ref).join(',')}|${rt.cachedDefault() ?? ''}`
+ const modelsKey = () => `${rt.cachedCatalog().map(entry => entry.reasoning ? `${entry.ref}:${JSON.stringify(entry.reasoning)}` : entry.ref).join(',')}|${rt.cachedDefault() ?? ''}`
const view = () => ({
revision: state.revision,
workspaceId: state.workspaceId ?? null,
@@ -70,7 +70,7 @@ export function install(rt) {
const live = () => ({ activity: rt.activityView(), memoryNews: rt.memoryNews(), memoryReviews: rt.memoryReviews(), connectors: rt.connectorsView() })
// What a host that only reads the team may still answer.
// Updates change the dsh profile, not the team, so a reading host may run them too.
- const READS = new Set(['state', 'models', 'earlier', 'room-progress', 'exchange', 'usage', 'schedules', 'memory-view', 'browser-wait', 'browser-result', 'diagnostics', 'diagnostics-log', 'diagnostics-clear', 'update-check', 'update-install'])
+ const READS = new Set(['state', 'models', 'efforts', 'earlier', 'room-progress', 'exchange', 'usage', 'schedules', 'memory-view', 'browser-wait', 'browser-result', 'diagnostics', 'diagnostics-log', 'diagnostics-clear', 'update-check', 'update-install', 'dsh-update-install'])
function setPrefs(body) {
if (body.theme !== undefined) {
@@ -107,6 +107,8 @@ export function install(rt) {
case 'models':
await rt.catalog({ fresh: true })
return ok({ modelsKey: modelsKey() })
+ case 'efforts':
+ return ok(await rt.reasoningOf(String(body.ref ?? '')) ?? { efforts: [] })
case 'duplicate-bot':
await rt.load()
return ok(await rt.duplicateBot(body.id))
@@ -129,7 +131,7 @@ export function install(rt) {
return ok([...rt.roomProgress.entries()].filter(([, entry]) => entry.roomId === body.roomId).map(([callId, entry]) => ({ callId, replies: entry.replies, speaking: entry.speaking ?? null })))
case 'create-bot': {
await rt.bootstrap()
- const bot = await rt.createBot({ name: body.name, role: body.role, color: body.color, instructions: body.instructions, brief: body.brief, avatar: body.avatar, model: body.model })
+ const bot = await rt.createBot({ name: body.name, role: body.role, color: body.color, instructions: body.instructions, brief: body.brief, avatar: body.avatar, model: body.model, effort: body.effort })
return ok(bot)
}
case 'update-bot':
@@ -259,10 +261,14 @@ export function install(rt) {
}, AbortSignal.timeout(30_000))
return ok(true)
}
- case 'update-check':
- return ok(await rt.updateCheck({ fresh: body.fresh === true }))
+ case 'update-check': {
+ const fresh = body.fresh === true
+ return ok({ ...(await rt.updateCheck({ fresh })), dsh: (await rt.dshUpdateCheck?.({ fresh })) ?? null })
+ }
case 'update-install':
return ok(rt.updateStart())
+ case 'dsh-update-install':
+ return ok(rt.dshUpdateStart?.())
// The Desktop window's long poll for read_browser, and its answers.
case 'browser-wait': {
if (rt.browserChannel === undefined) return fail('Bot browsers are off on this host', 'bot/browser-off')
diff --git a/ds-bot/src/host/dsh-update.js b/ds-bot/src/host/dsh-update.js
new file mode 100644
index 00000000..641bf389
--- /dev/null
+++ b/ds-bot/src/host/dsh-update.js
@@ -0,0 +1,168 @@
+// DSH updates: every released DS Bot names the DSH release it was verified
+// against (`dsBot.verifiedDsh` in package.json). The newest released bot wins:
+// offering that version and nothing newer keeps the update path away from DSH
+// releases we have not checked. A DSH installed from npm swaps with
+// `npm i -g`; a packaged app's runtime lives inside its bundle, so the card
+// there only reports current and verified — its own updater chooses versions.
+import { spawn } from 'node:child_process'
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+
+import {
+ CHECK_TTL_MS, cleanVersion, encodeName, fetchJson, installSpecOf,
+ newer, registryPlan, repoSlug, sourceOf,
+} from './update.js'
+
+const PKG = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
+const APP_BOOT = '@deepseek-ai/dsh-app-boot'
+const DSH_PACKAGE = '@deepseek-ai/dsh'
+
+export function install(rt) {
+ const { ctx, config } = rt
+ const enabled = config.updateCheck !== false
+
+ const status = {
+ current: null, verified: null, kind: 'npm', blockedBy: null,
+ checkedAt: 0, phase: 'idle', installed: null, error: null,
+ }
+ let target = null
+ let checking = null
+ let running = null
+
+ // A newer `minBot` than the running bot gates the offer: the bot goes first.
+ const blocked = () => status.blockedBy !== null && newer(status.blockedBy, PKG.version)
+
+ const view = () => ({
+ current: status.current, verified: status.verified, kind: status.kind, blockedBy: status.blockedBy,
+ checkedAt: status.checkedAt, phase: status.phase, installed: status.installed, error: status.error,
+ // Nothing is offered without a current version to compare against.
+ available: status.phase !== 'installed' && target !== null && status.current !== null
+ && status.verified !== null && status.verified !== status.current && !blocked(),
+ })
+
+ // The version of the DSH that is running us: the app-boot export, or — where
+ // that import cannot see it — the nearest @deepseek-ai package.json above the
+ // entry script.
+ async function currentDsh() {
+ try {
+ const loader = ctx.get?.('loader')
+ const loaded = await loader?.import?.(APP_BOOT)
+ const appBoot = loader?.unwrapExports?.(loaded) ?? loaded?.default ?? loaded
+ const version = cleanVersion(appBoot?.getDshRuntimeVersion?.())
+ if (version) return version
+ } catch { /* the export is not visible here: read the install instead */ }
+ let dir = dirname(String(process.argv[1] ?? ''))
+ for (let depth = 0; depth < 12; depth += 1) {
+ try {
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'))
+ if (manifest?.name?.startsWith?.('@deepseek-ai/')) {
+ const version = cleanVersion(manifest.version)
+ if (version) return version
+ }
+ } catch { /* not a package directory */ }
+ const parent = dirname(dir)
+ if (parent === dir) break
+ dir = parent
+ }
+ return null
+ }
+
+ // A bundled package manager means the runtime came with the app and only the
+ // app's own updater can move it.
+ const installKind = () =>
+ typeof ctx.get?.('profileContext')?.packageManager?.command === 'string' ? 'app' : 'npm'
+
+ // The newest released DS Bot's `dsBot` block, through the same channel the bot
+ // itself updates from: its registry, or the public repo's latest release.
+ async function releasedDeclaration(source) {
+ if (source.kind === 'registry') {
+ for (const registry of await registryPlan(config, ctx.get?.('pluginManager'))) {
+ try {
+ const manifest = await fetchJson(`${registry}${encodeName(PKG.name)}/latest`)
+ if (manifest?.dsBot?.verifiedDsh) return manifest.dsBot
+ } catch { /* unreachable or not published there: ask the next one */ }
+ }
+ return null
+ }
+ const repo = repoSlug()
+ if (!repo) return null
+ try {
+ const release = await fetchJson(`https://api.github.com/repos/${repo}/releases/latest`, { 'user-agent': `${PKG.name}/${PKG.version}` })
+ const tag = cleanVersion(release?.tag_name)
+ if (!tag) return null
+ const manifest = await fetchJson(`https://raw.githubusercontent.com/${repo}/${release.tag_name}/ds-bot/package.json`, { 'user-agent': `${PKG.name}/${PKG.version}` })
+ return manifest?.dsBot?.verifiedDsh ? manifest.dsBot : null
+ } catch { return null }
+ }
+
+ async function runCheck() {
+ try {
+ status.current = await currentDsh()
+ status.kind = installKind()
+ // The release the running package itself verified stays the floor: a bot
+ // older than its own declaration has nothing newer to offer.
+ const declared = [{ verifiedDsh: PKG.dsBot?.verifiedDsh }]
+ const released = await releasedDeclaration(sourceOf(await installSpecOf(ctx)))
+ if (released) declared.push(released)
+ const newestDeclared = declared
+ .filter(entry => cleanVersion(entry.verifiedDsh))
+ .sort((a, b) => (newer(cleanVersion(a.verifiedDsh), cleanVersion(b.verifiedDsh)) ? -1 : 1))[0]
+ status.verified = cleanVersion(newestDeclared?.verifiedDsh)
+ // A release may gate the DSH update on a newer bot: offer nothing until
+ // the bot itself is at least `minBot`.
+ status.blockedBy = cleanVersion(newestDeclared?.minBot)
+ target = status.current !== null && status.verified !== null && status.verified !== status.current
+ ? { version: status.verified }
+ : null
+ status.error = null
+ } catch (error) {
+ rt.warn('ds-bot: dsh update check failed: %s', error?.message ?? error)
+ status.verified = null
+ status.blockedBy = null
+ target = null
+ }
+ status.checkedAt = Date.now()
+ }
+
+ /** Read current and verified DSH versions; a fresh check ignores the last answer. */
+ async function check({ fresh = false } = {}) {
+ if (!enabled) return view()
+ if (checking) return checking
+ if (!fresh && Date.now() - status.checkedAt < CHECK_TTL_MS) return view()
+ checking = runCheck().finally(() => { checking = null })
+ await checking
+ return view()
+ }
+
+ /** Swap an npm-installed DSH for the verified version; the answer comes back through `check`. */
+ function start() {
+ if (status.phase === 'installing') return view()
+ if (target === null || blocked()) throw new Error('No DSH update is available')
+ if (status.kind !== 'npm') throw new Error('This DSH updates with its app')
+ const chosen = target
+ Object.assign(status, { phase: 'installing', error: null })
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'
+ const args = ['install', '-g', `${DSH_PACKAGE}@${chosen.version}`]
+ const runner = rt.dshSpawn ?? ((command, argv, options) => spawn(command, argv, options))
+ running = runner(npm, args, { windowsHide: true })
+ let output = ''
+ running.stdout?.on?.('data', chunk => { output = `${output}${chunk}`.slice(-4000) })
+ running.stderr?.on?.('data', chunk => { output = `${output}${chunk}`.slice(-4000) })
+ const done = new Promise((resolve, reject) => {
+ running.once?.('error', reject)
+ running.once?.('close', code => (code === 0 ? resolve() : reject(new Error(`npm exited ${code}`))))
+ })
+ void done
+ .then(() => Object.assign(status, { phase: 'installed', installed: chosen.version }))
+ .catch((error) => {
+ rt.warn('ds-bot: dsh update to %s failed: %s', chosen.version, error?.message ?? error)
+ Object.assign(status, { phase: 'failed', error: `${error?.message ?? error}${output ? ` — ${output.trim().slice(-400)}` : ''}`.slice(0, 600) })
+ })
+ return view()
+ }
+
+ // Whatever npm is still running when the plugin unloads dies with it.
+ ctx.effect(() => () => running?.kill?.(), 'ds-bot: dsh update install')
+
+ Object.assign(rt, { dshUpdateCheck: check, dshUpdateStart: start, dshUpdateView: view })
+}
diff --git a/ds-bot/src/host/models.js b/ds-bot/src/host/models.js
index ad153260..598f38cb 100644
--- a/ds-bot/src/host/models.js
+++ b/ds-bot/src/host/models.js
@@ -11,10 +11,29 @@ export function install(rt) {
let modelsSynced = null
let catalogCache = { at: 0, value: [] }
- ctx.on?.('llm/adapters-updated', () => { catalogCache = { at: 0, value: [] } })
+ // A model's thinking levels, resolved once and kept for a short while: they change
+ // only with the provider, which also drops the catalog cache.
+ const reasoningCache = new Map()
+ ctx.on?.('llm/adapters-updated', () => { catalogCache = { at: 0, value: [] }; reasoningCache.clear() })
+
+ // The thinking levels a model serves: `{efforts: [{id, name, description?}],
+ // defaultEffort?}`, or undefined when it has none or the provider cannot say.
+ async function reasoningOf(ref) {
+ const cached = reasoningCache.get(ref)
+ if (cached !== undefined && Date.now() - cached.at < CATALOG_TTL_MS) return cached.value
+ const route = splitRef(ref)
+ const info = route === undefined ? undefined : await ctx.llm.resolveModelInfo?.(route.provider, route.model).catch(() => undefined)
+ const value = info?.reasoning === undefined ? undefined : {
+ efforts: (info.reasoning.efforts ?? []).map(effort => ({ id: effort.id, name: effort.name ?? effort.id, ...(effort.description ? { description: effort.description } : {}) })),
+ ...(info.reasoning.defaultEffort === undefined ? {} : { defaultEffort: info.reasoning.defaultEffort }),
+ }
+ reasoningCache.set(ref, { at: Date.now(), value })
+ return value
+ }
// A provider's model list can change in DSH settings without any event, so a picker
- // that is about to be used asks for a `fresh` one.
+ // that is about to be used asks for a `fresh` one. Entries for models a Bot uses
+ // also carry their `reasoning`, so the picker can offer thinking levels.
async function catalog({ fresh = false } = {}) {
if (!fresh && Date.now() - catalogCache.at < CATALOG_TTL_MS && catalogCache.value.length > 0) return catalogCache.value
const entries = []
@@ -32,6 +51,11 @@ export function install(rt) {
})
}
}
+ const used = new Set(Object.values(state.bots ?? {}).flatMap(bot => [bot.model, bot.appliedModel].filter(Boolean)))
+ await Promise.all(entries.filter(entry => used.has(entry.ref)).map(async (entry) => {
+ const reasoning = await reasoningOf(entry.ref)
+ if (reasoning !== undefined) entry.reasoning = reasoning
+ }))
catalogCache = { at: Date.now(), value: entries }
return entries
}
@@ -72,17 +96,43 @@ export function install(rt) {
return [bot.model, bot.appliedModel].find(ref => ref && served.has(ref)) ?? pickDefault(entries)
}
+ // The thinking level a Bot asked for, when the model it runs on serves it; else the
+ // model's own default applies. A level the model does not have is ignored, never
+ // sent: an explicit effort a provider does not know is a hard refusal there.
+ async function desiredEffort(bot, ref) {
+ if (bot.effort === undefined || ref === undefined) return undefined
+ const reasoning = await reasoningOf(ref)
+ return reasoning?.efforts?.some(effort => effort.id === bot.effort) ? bot.effort : undefined
+ }
+
+ // A thinking level id, or a name only one level of the model has, like resolveModel.
+ async function resolveEffort(ref, text) {
+ const wanted = String(text ?? '').trim()
+ if (wanted === '') return undefined
+ const reasoning = await reasoningOf(ref)
+ const efforts = reasoning?.efforts ?? []
+ if (efforts.length === 0) throw new Error(`Model ${ref} has no thinking levels`)
+ const key = normalize(wanted)
+ const named = efforts.filter(effort => normalize(effort.id) === key || normalize(effort.name) === key)
+ if (named.length === 1) return named[0].id
+ throw new Error(`Thinking level ${wanted} is not available for ${ref}. Available: ${efforts.map(effort => effort.name).join(', ')}`)
+ }
+
// DSH's selectModel also saves the selection as the profile default model, in the
// background. A Bot's model is its own, so the user's default is written back after
// it. Selections run one at a time and wait for the write-back: profile writes land in
// submission order, so the next one reads the user's default, not a Bot's.
let selecting = Promise.resolve()
- function selectSessionModel(sessionId, { provider, model }) {
+ function selectSessionModel(sessionId, { provider, model, reasoningEffort }) {
const run = selecting.then(async () => {
const defaults = ctx.get?.('agentDefaultModel')
const before = defaults?.currentSelection?.()
- const result = await ctx.sessionController.selectModel({ sessionId, provider, model })
- if (before?.provider && before?.model && (before.provider !== provider || before.model !== model)) {
+ const result = await ctx.sessionController.selectModel({
+ sessionId, provider, model,
+ ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
+ })
+ const saved = result?.selected ?? { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) }
+ if (before?.provider && before?.model && !sameSelection(before, saved)) {
await defaults.saveSelection(before).catch(error => rt.warn('ds-bot: the default model was not restored: %s', error))
}
return result
@@ -91,18 +141,24 @@ export function install(rt) {
return run
}
+ const sameSelection = (a, b) => a.provider === b.provider && a.model === b.model && a.reasoningEffort === b.reasoningEffort
+
// `force` re-selects even when the record says it is applied: the composer's own
// model picker can move the Session without telling this plugin.
async function applyModel(bot, { force = false } = {}) {
const ref = await desiredModel(bot)
- if (ref === undefined || (!force && bot.appliedModel === ref)) return ref
- const route = splitRef(ref)
+ if (ref === undefined) return ref
+ const effort = await desiredEffort(bot, ref)
+ if (!force && bot.appliedModel === ref && (bot.appliedEffort ?? undefined) === effort) return ref
+ const route = { ...splitRef(ref), ...(effort === undefined ? {} : { reasoningEffort: effort }) }
await selectSessionModel(rt.chatOf(bot.id), route)
for (const sessionId of rt.groupSessionsOf(bot.id)) {
await selectSessionModel(sessionId, route)
.catch(error => rt.warn('ds-bot: model for %s in a group not applied: %s', bot.name, error))
}
bot.appliedModel = ref
+ if (effort === undefined) delete bot.appliedEffort
+ else bot.appliedEffort = effort
await rt.save()
return ref
}
@@ -140,6 +196,7 @@ export function install(rt) {
Object.assign(rt, {
catalog, cachedCatalog: () => catalogCache.value, cachedDefault: () => pickDefault(catalogCache.value),
- defaultRef, defaultModel, resolveModel, desiredModel, selectSessionModel, applyModel, waitForModel, syncModels,
+ defaultRef, defaultModel, resolveModel, desiredModel, reasoningOf, resolveEffort, desiredEffort,
+ selectSessionModel, applyModel, waitForModel, syncModels,
})
}
diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js
index b48bfe39..5c862ea5 100644
--- a/ds-bot/src/host/parts.js
+++ b/ds-bot/src/host/parts.js
@@ -107,6 +107,19 @@ export function historyEntry(event, group) {
return { answer: false, who: ours ? 'bot' : 'user', text: skipped ? '' : text, keepAnswers: !skipped || (ours && source.resume === true) }
}
+// A note with every heading in order but some translated (e.g. "## 目标" for "## Goals")
+// gets the headings as written, so the note is not thrown away over its headings alone.
+// A known heading in another place (repeated or out of order) keeps the note as it is.
+export function canonicalHeadings(note, names) {
+ const lines = note.split('\n')
+ const at = lines.flatMap((line, index) => /^##\s+\S/.test(line) ? [index] : [])
+ const heading = index => lines[index].replace(/^##\s+/, '').trim()
+ if (at.length !== names.length || at.every((index, n) => heading(index) === names[n])) return note
+ if (at.some((index, n) => names.includes(heading(index)) && heading(index) !== names[n])) return note
+ at.forEach((index, n) => { lines[index] = `## ${names[n]}` })
+ return lines.join('\n')
+}
+
export function install(rt) {
const { ctx, config, state } = rt
@@ -301,7 +314,7 @@ export function install(rt) {
'',
...NOTE_SECTIONS.flatMap(([name, what]) => [`## ${name}`, `- [${what}]`, '']),
'Rules:',
- '- Do not make anything up. Leave a detail out rather than guess it. Keep identifiers, quotes, and numbers exact.',
+ '- Do not make anything up. Leave a detail out rather than guess it. Keep identifiers, quotes, and numbers exact, and write every file path in full, as it first appeared: never shorten it.',
'- When a newer message contradicts an older one, the newer one wins; drop what is stale.',
'- Your latest messages travel to the fresh conversation word for word, and in your own chat so does every message the user and other Bots sent you (long ones cut). Do not copy them whole; record what they mean and what they rely on. Still put in the facts, quotes, and error messages from them that the work needs: the move after this one leaves them behind.',
'- If the conversation starts with a "[Handoff · part N]" message, it holds your previous note, and a "[Checkpoint N]" summary holds a condensed stretch of this part. Merge them: keep what is still true, drop what is stale, and add what is new. Nothing in them survives unless this note keeps it.',
@@ -342,7 +355,8 @@ export function install(rt) {
})) assembler.push(chunk)
const finish = assembler.finish
if (finish.kind === 'error' || finish.kind === 'aborted') throw new Error(finish.failure?.message ?? finish.kind)
- const note = assembler.blocks().filter(block => block.type === 'text').map(block => block.text).join('\n').trim()
+ const text = assembler.blocks().filter(block => block.type === 'text').map(block => block.text).join('\n').trim()
+ const note = missingSections(text).length > 0 ? canonicalHeadings(text, NOTE_SECTIONS.map(([name]) => name)) : text
const missing = missingSections(note)
if (finish.kind === 'max-tokens') {
problem = 'it was cut off at the output limit'
diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.js
index d2a5ce94..b52cb586 100644
--- a/ds-bot/src/host/roster.js
+++ b/ds-bot/src/host/roster.js
@@ -54,13 +54,14 @@ export function install(rt) {
// `pickModel` leaves the model to the user: the chat opens on a model card, and the
// greeting waits until a model is chosen. So does a Bot made when no model is served.
- async function createBot({ name: botName, role = '', instructions = '', color, brief = '', createdBy, main = false, avatar, model, copyOf, pickModel = false }) {
+ async function createBot({ name: botName, role = '', instructions = '', color, brief = '', createdBy, main = false, avatar, model, effort, copyOf, pickModel = false }) {
const cleanName = String(botName ?? '').trim().slice(0, 40)
if (cleanName === '') throw new Error('A Bot needs a name')
if (rt.findBot(cleanName)) throw new Error(`A Bot named ${cleanName} already exists`)
const cleanAvatarValue = cleanAvatar(avatar)
// The model is fixed at creation, so a later change of the DSH default leaves it alone.
const modelRef = model ? await rt.resolveModel(model) : pickModel ? undefined : await rt.defaultModel()
+ const effortId = modelRef !== undefined && effort !== undefined ? await rt.resolveEffort(modelRef, effort) : undefined
const id = await createSession(cleanName)
state.bots[id] = {
id,
@@ -70,6 +71,7 @@ export function install(rt) {
...(isColor(currentColor(color)) ? { color: currentColor(color) } : {}),
...(cleanAvatarValue ? { avatar: cleanAvatarValue } : {}),
...(modelRef ? { model: modelRef } : {}),
+ ...(effortId ? { effort: effortId } : {}),
instructions: String(instructions).trim(),
createdAt: Date.now(),
createdBy: createdBy ?? null,
@@ -126,6 +128,7 @@ export function install(rt) {
color: bot.color,
avatar: bot.avatar,
model: served ? bot.model : undefined,
+ effort: served ? bot.effort : undefined,
copyOf: bot.id,
})
}
@@ -159,6 +162,15 @@ export function install(rt) {
else bot.model = await rt.resolveModel(patch.model)
modelChanged = true
}
+ if (patch.effort !== undefined) {
+ if (patch.effort === null || patch.effort === '') delete bot.effort
+ else {
+ const ref = bot.model ?? bot.appliedModel
+ if (ref === undefined) throw new Error('Pick a model before choosing a thinking level')
+ bot.effort = await rt.resolveEffort(ref, patch.effort)
+ }
+ modelChanged = true
+ }
await rt.save()
if (modelChanged) await rt.applyModel(bot, { force: true })
if (bot.model && bot.kickoff !== undefined) {
diff --git a/ds-bot/src/host/update.js b/ds-bot/src/host/update.js
index c52e25f5..9c56f996 100644
--- a/ds-bot/src/host/update.js
+++ b/ds-bot/src/host/update.js
@@ -7,10 +7,10 @@ import { join } from 'node:path'
const PKG = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
export const OFFICIAL_REGISTRY = 'https://registry.npmjs.org/'
-const MIRROR_REGISTRY = 'https://registry.npmmirror.com/'
+export const MIRROR_REGISTRY = 'https://registry.npmmirror.com/'
// Every window that opens asks; within this long the last answer stands.
-const CHECK_TTL_MS = 10 * 60_000
-const FETCH_TIMEOUT_MS = 8000
+export const CHECK_TTL_MS = 10 * 60_000
+export const FETCH_TIMEOUT_MS = 8000
// The first check waits until the host has settled its own start.
const STARTUP_DELAY_MS = 15_000
const VERSION = /^v?(\d+\.\d+\.\d+(?:-[\w.]+)?)(?:\+[\w.]+)?$/
@@ -60,10 +60,47 @@ export function sourceOf(spec) {
}
const normalizeRegistry = url => `${String(url).trim().replace(/\/+$/, '')}/`
-const encodeName = name => (name.startsWith('@') ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name))
-// The project page of the releases, for the "what's new" link.
+export const encodeName = name => (name.startsWith('@') ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name))
+
+export const fetchJson = async (url, headers = {}) => {
+ const response = await fetch(url, { headers: { accept: 'application/json', ...headers }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`)
+ return response.json()
+}
+
+// The registries the plugin manager installs from, in its order: its configured
+// first one (else pnpm's own), then the fallbacks, unless that first one is private.
+export async function registryPlan(config, manager) {
+ if (typeof config.updateRegistry === 'string' && config.updateRegistry !== '') return [normalizeRegistry(config.updateRegistry)]
+ const configured = await Promise.resolve(manager?.registries?.()).catch(() => null)
+ if (!configured) return [OFFICIAL_REGISTRY, MIRROR_REGISTRY]
+ const fallbacks = (configured.fallbackRegistries ?? []).map(normalizeRegistry)
+ const own = configured.resolved ? normalizeRegistry(configured.resolved) : null
+ const first = configured.registry ? normalizeRegistry(configured.registry) : own ?? OFFICIAL_REGISTRY
+ const isPublic = first === OFFICIAL_REGISTRY || fallbacks.includes(first)
+ return isPublic ? [...new Set([first, ...fallbacks])] : [first]
+}
+
+// The plugin manager's `source` for this package; DSH releases before it reported
+// one leave the profile's own dependency entry to say the same.
+export async function installSpecOf(ctx) {
+ const manager = ctx.get?.('pluginManager')
+ const bundles = await Promise.resolve(manager?.listBundles?.()).catch(() => null)
+ const own = Array.isArray(bundles) ? bundles.find(bundle => bundle.name === PKG.name) : undefined
+ if (typeof own?.source === 'string') return own.source
+ const dir = ctx.get?.('profileContext')?.dir
+ if (typeof dir !== 'string') return undefined
+ try {
+ return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).dependencies?.[PKG.name]
+ } catch { return undefined }
+}
+
+// The public repository the releases live in, for tags and the "what's new" link.
+export const repoSlug = () =>
+ /github\.com[/:]([\w.-]+\/[\w.-]+?)(?:\.git)?$/i.exec(String(PKG.repository?.url ?? PKG.repository ?? ''))?.[1] ?? null
+
const releasesUrl = () => {
- const repo = /github\.com[/:]([\w.-]+\/[\w.-]+?)(?:\.git)?$/i.exec(String(PKG.repository?.url ?? PKG.repository ?? ''))?.[1]
+ const repo = repoSlug()
return repo ? `https://github.com/${repo}/releases` : (PKG.homepage ?? null)
}
@@ -86,27 +123,8 @@ export function install(rt) {
available: status.phase !== 'installed' && target !== null && status.latest !== null && newer(status.latest, status.current),
})
- const fetchJson = async (url, headers = {}) => {
- const response = await fetch(url, { headers: { accept: 'application/json', ...headers }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
- if (!response.ok) throw new Error(`${url} answered ${response.status}`)
- return response.json()
- }
-
- // The registries the plugin manager installs from, in its order: its configured
- // first one (else pnpm's own), then the fallbacks, unless that first one is private.
- async function registryPlan() {
- if (typeof config.updateRegistry === 'string' && config.updateRegistry !== '') return [normalizeRegistry(config.updateRegistry)]
- const configured = await Promise.resolve(manager()?.registries?.()).catch(() => null)
- if (!configured) return [OFFICIAL_REGISTRY, MIRROR_REGISTRY]
- const fallbacks = (configured.fallbackRegistries ?? []).map(normalizeRegistry)
- const own = configured.resolved ? normalizeRegistry(configured.resolved) : null
- const first = configured.registry ? normalizeRegistry(configured.registry) : own ?? OFFICIAL_REGISTRY
- const isPublic = first === OFFICIAL_REGISTRY || fallbacks.includes(first)
- return isPublic ? [...new Set([first, ...fallbacks])] : [first]
- }
-
async function newestFromRegistry() {
- for (const registry of await registryPlan()) {
+ for (const registry of await registryPlan(config, manager())) {
try {
const version = cleanVersion((await fetchJson(`${registry}${encodeName(PKG.name)}/latest`)).version)
if (version) return { version, spec: `${PKG.name}@${version}`, registry }
@@ -124,21 +142,8 @@ export function install(rt) {
return { version, spec: `github:${source.owner}/${source.repo}#${fragment}` }
}
- // The plugin manager's `source` for this package; DSH releases before it reported
- // one leave the profile's own dependency entry to say the same.
- async function installSpec() {
- const bundles = await Promise.resolve(manager()?.listBundles?.()).catch(() => null)
- const own = Array.isArray(bundles) ? bundles.find(bundle => bundle.name === PKG.name) : undefined
- if (typeof own?.source === 'string') return own.source
- const dir = ctx.get?.('profileContext')?.dir
- if (typeof dir !== 'string') return undefined
- try {
- return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).dependencies?.[PKG.name]
- } catch { return undefined }
- }
-
async function runCheck() {
- const source = sourceOf(await installSpec())
+ const source = sourceOf(await installSpecOf(ctx))
status.source = source.kind
let found = null
try {
diff --git a/ds-bot/test/client-bundle.test.js b/ds-bot/test/client-bundle.test.js
index 503af98c..6ef95cbf 100644
--- a/ds-bot/test/client-bundle.test.js
+++ b/ds-bot/test/client-bundle.test.js
@@ -35,5 +35,5 @@ test('client.js registers a factory that exports apply and inject', () => {
assert.equal(Object.prototype.toString.call(exports), '[object Module]')
assert.deepEqual(Object.keys(exports), ['apply', 'inject'])
assert.equal(typeof exports.apply, 'function')
- assert.deepEqual(Array.from(exports.inject), ['sessions', 'uiWorkspace', 'slots', 'theme', 'layout', 'configForms'])
+ assert.deepEqual(Array.from(exports.inject), ['sessions', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout', 'configForms'])
})
diff --git a/ds-bot/test/dsh-update.test.js b/ds-bot/test/dsh-update.test.js
new file mode 100644
index 00000000..54f8e80f
--- /dev/null
+++ b/ds-bot/test/dsh-update.test.js
@@ -0,0 +1,145 @@
+import assert from 'node:assert/strict'
+import { EventEmitter } from 'node:events'
+import { readFileSync } from 'node:fs'
+import { afterEach, test } from 'node:test'
+import { install } from '../src/host/dsh-update.js'
+
+const PKG = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
+const VERIFIED = PKG.dsBot.verifiedDsh
+const flush = async () => { for (let index = 0; index < 8; index += 1) await Promise.resolve() }
+const realFetch = globalThis.fetch
+afterEach(() => { globalThis.fetch = realFetch })
+
+// The dsh-update module alone: a stub loader says the running DSH version, a
+// stub plugin manager says how the bot was installed, and fetch is scripted.
+function start({ current = '0.2.0-rc.2', source, answers = {}, app = false, spawn, config = {}, profileDir }) {
+ const fetched = []
+ const spawns = []
+ const warnings = []
+ globalThis.fetch = async (url) => {
+ fetched.push(url)
+ const answer = answers[url]
+ if (answer === undefined) return { ok: false, status: 404, json: async () => ({}) }
+ if (answer instanceof Error) throw answer
+ return { ok: true, status: 200, json: async () => answer }
+ }
+ const loader = current === null ? undefined : {
+ import: async name => (name === '@deepseek-ai/dsh-app-boot' ? { getDshRuntimeVersion: () => current } : {}),
+ unwrapExports: exports => exports,
+ }
+ const profileContext = app ? { dir: profileDir, packageManager: { command: 'pnpm' } } : { dir: profileDir }
+ const pluginManager = {
+ listBundles: async () => (source === undefined ? [] : [{ name: PKG.name, source }]),
+ registries: async () => ({ registry: null, fallbackRegistries: ['https://registry.npmmirror.com/'], resolved: 'https://registry.npmjs.org/' }),
+ }
+ const rt = {
+ ctx: { get: name => ({ loader, pluginManager, profileContext })[name], effect() {} },
+ config,
+ warn: (...args) => warnings.push(args),
+ dshSpawn: spawn ?? ((command, argv) => { spawns.push([command, argv]); return fakeChild(0) }),
+ }
+ install(rt)
+ return { rt, fetched, spawns, warnings }
+}
+
+function fakeChild(code) {
+ const child = new EventEmitter()
+ child.stdout = new EventEmitter()
+ child.stderr = new EventEmitter()
+ queueMicrotask(() => child.emit('close', code))
+ return child
+}
+
+const registryLatest = dsBot => ({ [`https://registry.npmjs.org/${PKG.name}/latest`]: { version: PKG.version, dsBot } })
+const githubLatest = (tag, manifest) => ({
+ 'https://api.github.com/repos/FeiZhuLulu/DeepSeek-Bot/releases/latest': { tag_name: tag },
+ [`https://raw.githubusercontent.com/FeiZhuLulu/DeepSeek-Bot/${tag}/ds-bot/package.json`]: manifest,
+})
+
+test('the newest released bot declares the verified DSH, offered to an older npm install', async () => {
+ const { rt, spawns } = start({ source: `${PKG.name}@^${PKG.version}`, answers: registryLatest({ verifiedDsh: '9.9.9' }) })
+ const view = await rt.dshUpdateCheck()
+ assert.equal(view.current, '0.2.0-rc.2')
+ assert.equal(view.verified, '9.9.9')
+ assert.equal(view.kind, 'npm')
+ assert.equal(view.available, true)
+ assert.equal(rt.dshUpdateStart().phase, 'installing')
+ await flush()
+ assert.deepEqual(spawns.map(([, argv]) => argv), [['install', '-g', '@deepseek-ai/[email protected]']])
+ assert.equal((await rt.dshUpdateCheck()).phase, 'installed')
+ assert.equal((await rt.dshUpdateCheck()).installed, '9.9.9')
+})
+
+test('a verified version older than the running one is still offered, for a broken release', async () => {
+ const { rt } = start({ current: '9.9.9', source: `${PKG.name}@^${PKG.version}`, answers: registryLatest({ verifiedDsh: '0.2.1-alpha.1' }) })
+ const view = await rt.dshUpdateCheck()
+ assert.equal(view.verified, '0.2.1-alpha.1')
+ assert.equal(view.available, true)
+})
+
+test('without a newer released declaration the installed package\'s own stands as the floor', async () => {
+ const { rt } = start({ source: `${PKG.name}@^${PKG.version}` })
+ const view = await rt.dshUpdateCheck()
+ assert.equal(view.verified, VERIFIED)
+ assert.equal(view.available, true)
+})
+
+test('the running version matching the verified one offers nothing', async () => {
+ const { rt } = start({ current: VERIFIED, source: `${PKG.name}@^${PKG.version}` })
+ assert.equal((await rt.dshUpdateCheck()).available, false)
+ assert.throws(() => rt.dshUpdateStart(), /No DSH update/)
+})
+
+test('a minBot newer than the running bot gates the DSH update until the bot goes first', async () => {
+ const { rt } = start({ source: `${PKG.name}@^${PKG.version}`, answers: registryLatest({ verifiedDsh: '9.9.9', minBot: '9.9.9' }) })
+ const view = await rt.dshUpdateCheck()
+ assert.equal(view.available, false)
+ assert.equal(view.blockedBy, '9.9.9')
+ assert.throws(() => rt.dshUpdateStart(), /No DSH update/)
+})
+
+test('a git or local install asks the public repo\'s latest release for its declaration', async () => {
+ for (const source of ['github:FeiZhuLulu/DeepSeek-Bot#v0.1.0&path:/ds-bot', 'link:/work/ds-bot', undefined]) {
+ const { rt, fetched } = start({ source, answers: githubLatest('v9.0.0', { dsBot: { verifiedDsh: '8.8.8' } }) })
+ const view = await rt.dshUpdateCheck()
+ assert.equal(view.verified, '8.8.8')
+ assert.deepEqual(fetched, [
+ 'https://api.github.com/repos/FeiZhuLulu/DeepSeek-Bot/releases/latest',
+ 'https://raw.githubusercontent.com/FeiZhuLulu/DeepSeek-Bot/v9.0.0/ds-bot/package.json',
+ ])
+ }
+})
+
+test('a bundled package manager means the app owns the runtime: report only, never install', async () => {
+ const { rt } = start({ app: true, source: `${PKG.name}@^${PKG.version}`, answers: registryLatest({ verifiedDsh: '9.9.9' }) })
+ const view = await rt.dshUpdateCheck()
+ assert.equal(view.kind, 'app')
+ assert.equal(view.available, true)
+ assert.throws(() => rt.dshUpdateStart(), /updates with its app/)
+})
+
+test('without a running version there is nothing to compare against', async () => {
+ const { rt } = start({ current: null, source: `${PKG.name}@^${PKG.version}` })
+ const view = await rt.dshUpdateCheck()
+ assert.equal(view.current, null)
+ assert.equal(view.available, false)
+})
+
+test('a failed npm install reports why and can be tried again', async () => {
+ let attempt = 0
+ const { rt } = start({
+ source: `${PKG.name}@^${PKG.version}`,
+ answers: registryLatest({ verifiedDsh: '9.9.9' }),
+ spawn: () => { attempt += 1; return fakeChild(attempt === 1 ? 1 : 0) },
+ })
+ await rt.dshUpdateCheck()
+ rt.dshUpdateStart()
+ await flush()
+ const failed = await rt.dshUpdateCheck()
+ assert.equal(failed.phase, 'failed')
+ assert.match(failed.error, /npm exited 1/)
+ assert.equal(failed.available, true)
+ rt.dshUpdateStart()
+ await flush()
+ assert.equal((await rt.dshUpdateCheck()).phase, 'installed')
+})
diff --git a/ds-bot/test/history.test.js b/ds-bot/test/history.test.js
index 2089b407..75d3a74d 100644
--- a/ds-bot/test/history.test.js
+++ b/ds-bot/test/history.test.js
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { termQuery } from '../src/host/chat-index.js'
-import { cardText, historyEntry, questionReply, readReply, replyText } from '../src/host/parts.js'
+import { canonicalHeadings, cardText, historyEntry, questionReply, readReply, replyText } from '../src/host/parts.js'
test('cardText shows a question card as the user saw it', () => {
const card = { question: ' Start where? ', detail: 'pick one', options: [{ label: 'Plan' }, { label: ' ' }, { label: 'Draft' }] }
@@ -64,3 +64,19 @@ test('a card answer keeps several picks and the user\'s own words', () => {
assert.equal(questionReply(question, { selected: ['Z'], custom: '' }), undefined)
assert.equal(replyText('plain words'), 'plain words')
})
+
+test('canonicalHeadings restores translated note headings only when every heading is there', () => {
+ const names = ['Goals', 'Next step']
+ assert.equal(canonicalHeadings('## 目标\n- a\n## 下一步\n- b', names), '## Goals\n- a\n## Next step\n- b')
+ assert.equal(canonicalHeadings('## 目标\n- a', names), '## 目标\n- a')
+ assert.equal(canonicalHeadings('## Goals\n- a\n## Next step\n- b\n## extra', names), '## Goals\n- a\n## Next step\n- b\n## extra')
+})
+
+test('canonicalHeadings keeps a note whose known headings are repeated or out of order', () => {
+ const names = ['Goals', 'Progress', 'Decisions']
+ const repeated = '## 目标\n- a\n## Progress\n- b\n## Progress\n- c'
+ assert.equal(canonicalHeadings(repeated, names), repeated)
+ const swapped = '## Progress\n- b\n## 目标\n- a\n## 决定\n- c'
+ assert.equal(canonicalHeadings(swapped, names), swapped)
+ assert.equal(canonicalHeadings('## 目标\n- a\n## Progress\n- b\n## 决定\n- c', names), '## Goals\n- a\n## Progress\n- b\n## Decisions\n- c')
+})
diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.js
index aa8e6bdd..528cd09e 100644
--- a/ds-bot/test/install.test.js
+++ b/ds-bot/test/install.test.js
@@ -78,6 +78,7 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => {
'effect ds-bot: usage ledger',
'on llm/stream',
'effect ds-bot: update check',
+ 'effect ds-bot: dsh update install',
'effect ds-bot: api route',
'route POST /api/bot',
'effect ds-bot: load state',
diff --git a/ds-bot/test/model-menu.test.js b/ds-bot/test/model-menu.test.js
index 12033230..5fc9e627 100644
--- a/ds-bot/test/model-menu.test.js
+++ b/ds-bot/test/model-menu.test.js
@@ -26,7 +26,7 @@ runInNewContext(bundle.outputFiles[0].text, {
return platform[name]
},
})
-const { groupModels, ModelChoiceDock } = module.exports
+const { groupModels, ModelChoiceDock, effortRows } = module.exports
function nodes(tree, match) {
if (!tree || typeof tree !== 'object') return []
@@ -92,3 +92,10 @@ test('an empty catalog offers setup choices, and a ready model needs no choice d
assert.equal(dock(models, { model: models[0].ref }).tree, null)
assert.equal(dock(models, { ready: false }).tree, null)
})
+
+test('the Thinking section always offers Default, so a picked level can be cleared', () => {
+ const efforts = [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }]
+ assert.deepEqual([...effortRows({ efforts, defaultEffort: 'high' }).map(row => row.effort)], [undefined, 'low', 'high'])
+ assert.deepEqual([...effortRows({ efforts }).map(row => row.effort)], [undefined, 'low', 'high'])
+ assert.equal(effortRows({ efforts: [] }).length, 0)
+})
diff --git a/ds-bot/test/models.test.js b/ds-bot/test/models.test.js
index da5bfbd9..248b3b6f 100644
--- a/ds-bot/test/models.test.js
+++ b/ds-bot/test/models.test.js
@@ -76,7 +76,7 @@ test('a Bot with no model yet changes nothing until the user picks one', async (
// A runtime with two providers, a DSH default, and a session controller that, like
// DSH, saves every Session selection as the default.
-function bench({ providers = { deepseek: ['v4-flash'], stepfun: ['step-5'] }, fallback = { provider: 'stepfun', model: 'step-5' } } = {}) {
+function bench({ providers = { deepseek: ['v4-flash'], stepfun: ['step-5'] }, fallback = { provider: 'stepfun', model: 'step-5' }, reasoning = {} } = {}) {
let current = { ...fallback }
const selected = []
const saved = []
@@ -89,10 +89,11 @@ function bench({ providers = { deepseek: ['v4-flash'], stepfun: ['step-5'] }, fa
llm: {
listProviders: () => Object.keys(providers).map(id => ({ id, name: id.toUpperCase() })),
listModels: async id => providers[id].map(model => ({ id: model, name: model, inputModalities: ['text'] })),
+ resolveModelInfo: async (provider, model) => reasoning[`${provider}/${model}`] ?? {},
},
sessionController: {
- selectModel: async ({ sessionId, provider, model }) => {
- selected.push(`${sessionId}:${provider}/${model}`)
+ selectModel: async ({ sessionId, provider, model, reasoningEffort }) => {
+ selected.push(`${sessionId}:${provider}/${model}${reasoningEffort === undefined ? '' : `:${reasoningEffort}`}`)
current = { provider, model }
},
},
@@ -127,6 +128,42 @@ test('applying a Bot model leaves the DSH default as the user set it', async ()
assert.equal(bot.appliedModel, 'deepseek/v4-flash')
})
+test('a Bot model applies its thinking level, and only re-selects on a change', async () => {
+ const { rt, selected } = bench({ reasoning: { 'deepseek/v4-flash': { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], defaultEffort: 'high' } } } })
+ const bot = { id: 'b1', model: 'deepseek/v4-flash', effort: 'low' }
+ await rt.applyModel(bot)
+ assert.deepEqual(selected, ['b1:deepseek/v4-flash:low'])
+ assert.equal(bot.appliedEffort, 'low')
+ await rt.applyModel(bot)
+ assert.equal(selected.length, 1)
+
+ // A level the model does not serve is never sent: the model's default applies.
+ bot.effort = 'max'
+ await rt.applyModel(bot)
+ assert.deepEqual(selected.at(-1), 'b1:deepseek/v4-flash')
+ assert.equal(bot.appliedEffort, undefined)
+})
+
+test('resolveEffort takes an id or a name, and refuses what the model has not', async () => {
+ const { rt } = bench({ reasoning: {
+ 'deepseek/v4-flash': { reasoning: { efforts: [{ id: 'off', name: 'Off' }, { id: 'high', name: 'High' }] } },
+ 'stepfun/step-5': {},
+ } })
+ assert.equal(await rt.resolveEffort('deepseek/v4-flash', 'high'), 'high')
+ assert.equal(await rt.resolveEffort('deepseek/v4-flash', ' Off '), 'off')
+ assert.equal(await rt.resolveEffort('deepseek/v4-flash', ''), undefined)
+ await assert.rejects(rt.resolveEffort('stepfun/step-5', 'high'), /no thinking levels/)
+ await assert.rejects(rt.resolveEffort('deepseek/v4-flash', 'max'), /not available for deepseek\/v4-flash\. Available: Off, High/)
+})
+
+test('the catalog attaches thinking levels to models a Bot uses', async () => {
+ const { rt } = bench({ reasoning: { 'deepseek/v4-flash': { reasoning: { efforts: [{ id: 'high', name: 'High' }], defaultEffort: 'high' } } } })
+ rt.state.bots.b1 = { id: 'b1', model: 'deepseek/v4-flash' }
+ const entries = await rt.catalog()
+ assert.deepEqual(entries.find(entry => entry.ref === 'deepseek/v4-flash')?.reasoning, { efforts: [{ id: 'high', name: 'High' }], defaultEffort: 'high' })
+ assert.equal(entries.find(entry => entry.ref === 'stepfun/step-5')?.reasoning, undefined)
+})
+
test('a greeting waits for the provider of its Bot model to register', async () => {
const { rt, providers, listeners } = bench({ providers: {} })
const waiting = rt.waitForModel({ model: 'stepfun/step-5' }, 5000)
@@ -137,3 +174,15 @@ test('a greeting waits for the provider of its Bot model to register', async ()
assert.equal(await waiting, 'stepfun/step-5')
assert.equal(await rt.waitForModel({}, 5000), undefined)
})
+
+test('a Bot on the default model with its own thinking level leaves the default level as it was', async () => {
+ const fallback = { provider: 'deepseek', model: 'v4-flash', reasoningEffort: 'high' }
+ const { rt, current } = bench({ fallback, reasoning: { 'deepseek/v4-flash': { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], defaultEffort: 'high' } } } })
+ rt.ctx.sessionController.selectModel = async ({ provider, model, reasoningEffort }) => {
+ const selected = { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) }
+ await rt.ctx.get('agentDefaultModel').saveSelection(selected)
+ return { selected }
+ }
+ await rt.applyModel({ id: 'b1', model: 'deepseek/v4-flash', effort: 'low' })
+ assert.deepEqual(current(), fallback)
+})
diff --git a/ds-bot/test/roster.test.js b/ds-bot/test/roster.test.js
index 68781460..89cd9d88 100644
--- a/ds-bot/test/roster.test.js
+++ b/ds-bot/test/roster.test.js
@@ -7,7 +7,7 @@ import { apply } from '../index.js'
import { fakeContext } from './fake-ctx.js'
// Enough of the dsh services for the roster to make Sessions; kickoff messages are dropped.
-function start(team, { models = [] } = {}) {
+function start(team, { models = [], reasoning = {} } = {}) {
const home = mkdtempSync(join(tmpdir(), 'ds-bot-roster-'))
if (team !== undefined) writeFileSync(join(home, 'state.json'), JSON.stringify(team))
const ctx = fakeContext()
@@ -19,6 +19,7 @@ function start(team, { models = [] } = {}) {
llm: {
listProviders: () => (models.length > 0 ? [{ id: 'deepseek', name: 'DeepSeek' }] : []),
listModels: async () => models.map(id => ({ id })),
+ resolveModelInfo: async (provider, model) => reasoning[`${provider}/${model}`] ?? {},
},
workspaceRegistry: {
get: id => workspaces.get(id),
@@ -130,6 +131,35 @@ test('a group the user makes without a first message opens with its admin asking
assert.deepEqual(saved.log, [])
})
+test('a Bot takes a thinking level its model serves, applied with the model', async (t) => {
+ const reasoning = { 'deepseek/deepseek-v4-flash': { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], defaultEffort: 'high' } } }
+ const { call, stop, selected } = start(undefined, { models: ['deepseek-v4-flash'], reasoning })
+ t.after(stop)
+ const chief = (await call('state', {})).value.mainBotId
+ await call('update-bot', { id: chief, model: 'deepseek/deepseek-v4-flash' })
+ await settle()
+ assert.equal((await call('update-bot', { id: chief, effort: 'low' })).ok, true)
+ await settle()
+ const main = (await call('state', {})).value.bots.find(bot => bot.id === chief)
+ assert.equal(main.effort, 'low')
+ assert.equal(main.appliedEffort, 'low')
+ assert.equal(selected.at(-1).reasoningEffort, 'low')
+
+ // A level the model does not serve is refused; null clears the pick.
+ assert.equal((await call('update-bot', { id: chief, effort: 'max' })).ok, false)
+ assert.equal((await call('update-bot', { id: chief, effort: null })).ok, true)
+ await settle()
+ const cleared = (await call('state', {})).value.bots.find(bot => bot.id === chief)
+ assert.equal(cleared.effort, undefined)
+ assert.equal(cleared.appliedEffort, undefined)
+
+ // Creating a Bot with a level stores and applies it.
+ const writer = (await call('create-bot', { name: 'Writer', model: 'deepseek/deepseek-v4-flash', effort: 'high' })).value
+ await settle()
+ assert.equal(writer.effort, 'high')
+ assert.equal(selected.at(-1).reasoningEffort, 'high')
+})
+
test('the state reports a changed model list without a new revision', async (t) => {
const { call, stop } = start(undefined, { models: ['deepseek-v4-flash'] })
t.after(stop)
diff --git a/ds-bot/test/speech.test.js b/ds-bot/test/speech.test.js
new file mode 100644
index 00000000..b0d6b156
--- /dev/null
+++ b/ds-bot/test/speech.test.js
@@ -0,0 +1,64 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { base64Of, speechCatalog, transcribeWave, turnDetector, waveBytes } from '../src/client/speech.js'
+
+const catalog = (phase, extra = {}) => ({
+ providers: [{ id: 'sensevoice', preparation: { phase } }],
+ selection: { providerId: 'sensevoice', language: 'auto' },
+ maxAudioBytes: 1000,
+ maxDurationSeconds: 30,
+ ...extra,
+})
+
+test('waveBytes writes a 16 kHz mono PCM16 WAV', () => {
+ const bytes = waveBytes(new Float32Array([0, 1, -1, 2]))
+ const view = new DataView(bytes.buffer)
+ const text = (at, length) => String.fromCharCode(...bytes.subarray(at, at + length))
+ assert.equal(bytes.length, 44 + 8)
+ assert.equal(text(0, 4), 'RIFF')
+ assert.equal(text(8, 8), 'WAVEfmt ')
+ assert.equal(view.getUint16(20, true), 1)
+ assert.equal(view.getUint16(22, true), 1)
+ assert.equal(view.getUint32(24, true), 16000)
+ assert.equal(view.getUint16(34, true), 16)
+ assert.equal(view.getUint32(40, true), 8)
+ assert.deepEqual([0, 1, 2, 3].map(index => view.getInt16(44 + index * 2, true)), [0, 32767, -32768, 32767])
+})
+
+test('base64Of matches Buffer for large input', () => {
+ const bytes = new Uint8Array(100000).map((_, index) => index % 251)
+ assert.equal(base64Of(bytes), Buffer.from(bytes).toString('base64'))
+})
+
+test('speechCatalog is usable only when the selected provider is ready', async () => {
+ for (const [phase, usable] of [['ready', true], ['standby', true], ['waking', true], ['missing', false], ['preparing', false]]) {
+ const speech = { catalog: async () => ({ ok: true, value: catalog(phase) }) }
+ assert.equal((await speechCatalog(speech)).usable, usable, phase)
+ }
+ await assert.rejects(speechCatalog({ catalog: async () => ({ ok: false, error: { message: 'down' } }) }), /down/)
+})
+
+test('transcribeWave sends the selection and returns trimmed text', async () => {
+ let sent
+ const speech = { transcribe: async (request) => { sent = request; return { ok: true, value: { text: ' 你好 ' } } } }
+ const text = await transcribeWave(speech, catalog('ready'), new Uint8Array([1, 2, 3]), new AbortController().signal)
+ assert.equal(text, '你好')
+ assert.deepEqual(sent, { audioBase64: 'AQID', providerId: 'sensevoice', language: 'auto' })
+})
+
+test('transcribeWave rejects audio over the limit and service failures', async () => {
+ const speech = { transcribe: async () => ({ ok: false, error: { message: 'busy' } }) }
+ await assert.rejects(transcribeWave(speech, catalog('ready'), new Uint8Array(1001)), error => error.kind === 'too-long')
+ await assert.rejects(transcribeWave(speech, catalog('ready'), new Uint8Array(10)), error => error.kind === 'service')
+})
+
+test('turnDetector ends a turn after a pause that follows speech', () => {
+ const detect = turnDetector({ loud: 0.1, quiet: 0.05, quietMs: 1000 })
+ assert.equal(detect(0.01, 0), 'waiting')
+ assert.equal(detect(0.3, 100), 'speech')
+ assert.equal(detect(0.01, 200), 'speech')
+ assert.equal(detect(0.01, 1100), 'speech')
+ assert.equal(detect(0.3, 1150), 'speech')
+ assert.equal(detect(0.01, 1200), 'speech')
+ assert.equal(detect(0.01, 2200), 'done')
+})
diff --git a/ds-bot/test/turn-reasoning.test.js b/ds-bot/test/turn-reasoning.test.js
new file mode 100644
index 00000000..0dcc8995
--- /dev/null
+++ b/ds-bot/test/turn-reasoning.test.js
@@ -0,0 +1,32 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { turnReasoning } from '../src/client/turn-reasoning.js'
+
+const step = (n, blocks, status = 'settled') => ({ turn: 1, step: n, status, blocks })
+const think = text => ({ kind: 'reasoning', text })
+const tool = { kind: 'tool-call', name: 'read' }
+
+test('a long tool Turn shows its reasoning once, on the first step, in order', () => {
+ const steps = Array.from({ length: 24 }, (_, i) => step(i + 1, [think(`Reasoning ${i + 1}`), tool]))
+ const shown = steps.map(current => turnReasoning(steps, current))
+ assert.equal(shown.filter(Boolean).length, 1)
+ assert.equal(shown[0], steps.map((_, i) => `Reasoning ${i + 1}`).join('\n\n'))
+})
+
+test('the row sits on the first step with reasoning', () => {
+ const steps = [step(1, [{ kind: 'text', text: 'Looking' }, tool]), step(2, [think('B'), tool]), step(3, [think('C'), { kind: 'text', text: 'Done' }])]
+ assert.deepEqual(steps.map(current => turnReasoning(steps, current)), ['', 'B\n\nC', ''])
+})
+
+test('reasoning still in progress stays out until its step settles', () => {
+ const steps = [step(1, [think('A'), tool]), step(2, [think('B')], 'running')]
+ assert.equal(turnReasoning(steps, steps[0]), 'A')
+ assert.equal(turnReasoning([step(1, [think('A')], 'running')], step(1, [think('A')], 'running')), '')
+ steps[1].blocks.push({ kind: 'text', text: 'Reply' })
+ assert.equal(turnReasoning(steps, steps[0]), 'A\n\nB')
+})
+
+test('a step outside the loaded Turn list shows only its own reasoning', () => {
+ const current = step(1, [think(' A ')])
+ assert.equal(turnReasoning([], current), 'A')
+})