Skip to content

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

Disable a hidden view card's inputs and share letter keys between cards

klarkxy828f92e104a0
diff --git a/ds-bot/client.js b/ds-bot/client.js
index 662dd1c1..7a636e62 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -3548,15 +3548,19 @@ var import_react5 = require("react");
var keyLetter = (index) => String.fromCharCode(65 + index);
var optionsOf = (question) => (question?.options ?? []).map((option) => typeof option === "string" ? { label: option } : option);
var isTypingTarget = (node) => node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement || node instanceof HTMLSelectElement || node instanceof HTMLElement && node.isContentEditable;
+var optionKeyCards = createSource(0);
function useOptionKeys(count, onPick, ownRef) {
const pick2 = (0, import_react5.useRef)(onPick);
pick2.current = onPick;
+ const listening = (0, import_react5.useSyncExternalStore)(optionKeyCards.subscribe, optionKeyCards.getSnapshot);
(0, import_react5.useEffect)(() => {
if (count === 0) return void 0;
+ optionKeyCards.set((value) => value + 1);
const onKey = (event) => {
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || event.key.length !== 1) return;
if (isTypingTarget(event.target) || isTypingTarget(document.activeElement)) return;
if (document.querySelector('[role="dialog"], [aria-modal="true"]') !== null) return;
+ if (optionKeyCards.getSnapshot() !== 1) return;
const index = event.key.toUpperCase().charCodeAt(0) - 65;
if (index >= 0 && index < count) {
event.preventDefault();
@@ -3567,8 +3571,12 @@ function useOptionKeys(count, onPick, ownRef) {
}
};
document.addEventListener("keydown", onKey, true);
- return () => document.removeEventListener("keydown", onKey, true);
+ return () => {
+ document.removeEventListener("keydown", onKey, true);
+ optionKeyCards.set((value) => value - 1);
+ };
}, [count, ownRef]);
+ return count > 0 && listening <= 1;
}
function QuestionView({ question, onAnswer, onDismiss, onInteract, busy = false, ownAnswer = false, raised = false }) {
const [own, setOwn] = (0, import_react5.useState)("");
@@ -3831,7 +3839,7 @@ function normalizeView(value) {
if (Array.isArray(inner)) return inner;
}
const out = {};
- for (const key of keys) out[key] = normalizeView(value[key]);
+ for (const key of keys) Object.defineProperty(out, key, { value: normalizeView(value[key]), writable: true, enumerable: true, configurable: true });
for (const field of ["value", "percent"]) {
if (typeof out[field] === "string" && out[field].trim() !== "" && !Number.isNaN(Number(out[field]))) out[field] = Number(out[field]);
}
@@ -3842,19 +3850,20 @@ function validateView(view) {
const error = checkNode(view, "view", 1, ctx);
return error === void 0 ? { ok: true, interactive: ctx.interactive } : { ok: false, error };
}
-function checkShownView(title, view) {
+function checkShownView(title, sent) {
let bytes;
try {
- bytes = viewBytes(title, view);
+ bytes = viewBytes(title, sent);
} catch {
return { error: "The view is not JSON data." };
}
if (bytes > VIEW_BYTE_LIMIT) return { error: `The view is ${bytes} bytes; the limit is ${VIEW_BYTE_LIMIT}.` };
const named = String(title ?? "").trim();
if (named === "") return { error: "Give the view a title." };
+ const view = normalizeView(sent);
const checked = validateView(view);
if (!checked.ok) return { error: checked.error };
- return { title: named, interactive: checked.interactive };
+ return { title: named, view, interactive: checked.interactive };
}
function checkNode(node, path, depth, ctx) {
if (!isRecord(node)) return `${path}: expected a component object`;
@@ -4074,11 +4083,12 @@ var countType = (node, type) => {
return (node.type === type ? 1 : 0) + children.reduce((sum, child) => sum + countType(child, type), 0);
};
var answerValues = (answer, node) => answer?.action === node.id ? answer.values : void 0;
-function OptionsInput({ node, onSubmit, keys }) {
+function OptionsInput({ node, onSubmit, keys, busy = false }) {
const [picked, setPicked] = (0, import_react6.useState)([]);
const options = optionsOf2(node);
const multi = node.multi === true;
const choose = (label) => {
+ if (busy) return;
if (multi) {
setPicked((current) => current.includes(label) ? current.filter((item) => item !== label) : [...current, label]);
return;
@@ -4086,10 +4096,10 @@ function OptionsInput({ node, onSubmit, keys }) {
onSubmit?.(node.id, { selected: [label] });
};
const submit = () => {
- if (picked.length > 0) onSubmit?.(node.id, { selected: picked });
+ if (!busy && picked.length > 0) onSubmit?.(node.id, { selected: picked });
};
const ownRef = (0, import_react6.useRef)(null);
- useOptionKeys(keys ? options.length : 0, (index) => choose(options[index].label), ownRef);
+ const hints = useOptionKeys(busy || !keys ? 0 : options.length, (index) => choose(options[index].label), ownRef);
return (0, import_react6.createElement)(
import_react6.Fragment,
null,
@@ -4101,11 +4111,12 @@ function OptionsInput({ node, onSubmit, keys }) {
key: option.label,
type: "button",
className: "bt-q-opt",
+ disabled: busy,
"aria-pressed": multi ? selected : void 0,
- "aria-keyshortcuts": keys ? keyLetter(index).toLowerCase() : void 0,
+ "aria-keyshortcuts": hints ? keyLetter(index).toLowerCase() : void 0,
onClick: () => choose(option.label)
},
- keys ? (0, import_react6.createElement)("span", { className: "bt-key", "aria-hidden": true }, keyLetter(index)) : null,
+ hints ? (0, import_react6.createElement)("span", { className: "bt-key", "aria-hidden": true }, keyLetter(index)) : null,
(0, import_react6.createElement)(
"span",
{ className: "bt-q-body" },
@@ -4118,7 +4129,7 @@ function OptionsInput({ node, onSubmit, keys }) {
multi ? (0, import_react6.createElement)(
"div",
{ className: "bt-q-foot" },
- (0, import_react6.createElement)("button", { type: "button", className: "bt-q-submit", disabled: picked.length === 0, onClick: submit }, t("Submit"))
+ (0, import_react6.createElement)("button", { type: "button", className: "bt-q-submit", disabled: busy || picked.length === 0, onClick: submit }, t("Submit"))
) : null
);
}
@@ -4141,12 +4152,12 @@ function SettledOptions({ node, answer }) {
))
);
}
-function ConfirmInput({ node, onSubmit }) {
+function ConfirmInput({ node, onSubmit, busy = false }) {
return (0, import_react6.createElement)(
"div",
{ className: "bt-q-foot" },
- (0, import_react6.createElement)("button", { type: "button", className: "bt-q-btn", onClick: () => onSubmit?.(node.id, { confirmed: false }) }, node.cancelLabel ?? t("Cancel")),
- (0, import_react6.createElement)("button", { type: "button", className: "bt-q-submit", onClick: () => onSubmit?.(node.id, { confirmed: true }) }, node.confirmLabel ?? t("Confirm"))
+ (0, import_react6.createElement)("button", { type: "button", className: "bt-q-btn", disabled: busy, onClick: () => onSubmit?.(node.id, { confirmed: false }) }, node.cancelLabel ?? t("Cancel")),
+ (0, import_react6.createElement)("button", { type: "button", className: "bt-q-submit", disabled: busy, onClick: () => onSubmit?.(node.id, { confirmed: true }) }, node.confirmLabel ?? t("Confirm"))
);
}
function SettledConfirm({ node, answer }) {
@@ -4162,10 +4173,12 @@ function SettledConfirm({ node, answer }) {
const label = confirmed ? node.confirmLabel ?? t("Confirm") : node.cancelLabel ?? t("Cancel");
return (0, import_react6.createElement)("span", { className: "bt-q-badge" }, label);
}
-function FormInput({ node, onSubmit }) {
+function FormInput({ node, onSubmit, busy = false }) {
const fields = fieldsOf(node);
const [draft, setDraft] = (0, import_react6.useState)({});
- const submit = () => onSubmit?.(node.id, { fields: Object.fromEntries(fields.map((field) => [field.id, draft[field.id] ?? ""])) });
+ const submit = () => {
+ if (!busy) onSubmit?.(node.id, { fields: Object.fromEntries(fields.map((field) => [field.id, draft[field.id] ?? ""])) });
+ };
return (0, import_react6.createElement)(
"form",
{
@@ -4188,9 +4201,12 @@ function FormInput({ node, onSubmit }) {
value: draft[field.id] ?? "",
autoComplete: "off",
spellCheck: false,
+ readOnly: busy,
"aria-label": field.label,
placeholder: field.placeholder ?? void 0,
- onChange: (event) => setDraft((current) => ({ ...current, [field.id]: event.target.value })),
+ onChange: (event) => {
+ if (!busy) setDraft((current) => ({ ...current, [field.id]: event.target.value }));
+ },
onKeyDown: (event) => {
if (event.key !== "Enter" || event.nativeEvent.isComposing) return;
event.preventDefault();
@@ -4199,7 +4215,7 @@ function FormInput({ node, onSubmit }) {
})
)
)),
- (0, import_react6.createElement)("div", { className: "bt-q-foot" }, (0, import_react6.createElement)("button", { type: "submit", className: "bt-q-submit" }, node.submitLabel ?? t("Submit")))
+ (0, import_react6.createElement)("div", { className: "bt-q-foot" }, (0, import_react6.createElement)("button", { type: "submit", className: "bt-q-submit", disabled: busy }, node.submitLabel ?? t("Submit")))
);
}
function SettledForm({ node, answer }) {
@@ -4279,55 +4295,61 @@ function WidgetNode({ node, ctx }) {
case "table":
return (0, import_react6.createElement)(WidgetTable, { node });
case "options":
- return ctx.settled ? (0, import_react6.createElement)(SettledOptions, { node, answer: ctx.answer }) : (0, import_react6.createElement)(OptionsInput, { node, onSubmit: ctx.onSubmit, keys: ctx.keys });
+ return ctx.settled ? (0, import_react6.createElement)(SettledOptions, { node, answer: ctx.answer }) : (0, import_react6.createElement)(OptionsInput, { node, onSubmit: ctx.onSubmit, keys: ctx.keys, busy: ctx.busy });
case "confirm":
- return ctx.settled ? (0, import_react6.createElement)(SettledConfirm, { node, answer: ctx.answer }) : (0, import_react6.createElement)(ConfirmInput, { node, onSubmit: ctx.onSubmit });
+ return ctx.settled ? (0, import_react6.createElement)(SettledConfirm, { node, answer: ctx.answer }) : (0, import_react6.createElement)(ConfirmInput, { node, onSubmit: ctx.onSubmit, busy: ctx.busy });
case "form":
- return ctx.settled ? (0, import_react6.createElement)(SettledForm, { node, answer: ctx.answer }) : (0, import_react6.createElement)(FormInput, { node, onSubmit: ctx.onSubmit });
+ return ctx.settled ? (0, import_react6.createElement)(SettledForm, { node, answer: ctx.answer }) : (0, import_react6.createElement)(FormInput, { node, onSubmit: ctx.onSubmit, busy: ctx.busy });
case "progress":
return (0, import_react6.createElement)(WidgetProgress, { node });
default:
return null;
}
}
-function WidgetView({ view, onSubmit, settled = false, answer = null }) {
- const ctx = { onSubmit, settled, answer, keys: !settled && countType(view, "options") === 1 };
+function WidgetView({ view, onSubmit, settled = false, answer = null, busy = false }) {
+ const ctx = { onSubmit, settled, answer, busy, keys: !settled && countType(view, "options") === 1 };
return (0, import_react6.createElement)(WidgetNode, { node: view, ctx });
}
-function WidgetCard({ title, view, onSubmit, onDismiss, raised = false, settled = false, answer = null }) {
+function WidgetCard({ title, view, onSubmit, onDismiss, busy = false, raised = false, settled = false, answer = null }) {
const titleId = (0, import_react6.useId)();
return (0, import_react6.createElement)(
"div",
{
className: settled ? "bt-q bt-q-settled" : raised ? "bt-q bt-q-raised" : "bt-q",
role: "group",
- "aria-labelledby": titleId
+ "aria-labelledby": titleId,
+ "aria-busy": busy || void 0
},
(0, import_react6.createElement)(
"div",
{ className: "bt-q-head" },
(0, import_react6.createElement)("div", { className: "bt-q-text" }, (0, import_react6.createElement)("p", { className: "bt-q-title", id: titleId }, title)),
(0, import_react6.createElement)("span", { className: "bt-q-badge" }, t("View")),
- onDismiss ? (0, import_react6.createElement)("button", { type: "button", className: "bt-q-x", "aria-label": t("Dismiss view"), title: t("Dismiss"), onClick: onDismiss }, (0, import_react6.createElement)(CloseIcon)) : null
+ onDismiss ? (0, import_react6.createElement)("button", { type: "button", className: "bt-q-x", "aria-label": t("Dismiss view"), title: t("Dismiss"), onClick: onDismiss, disabled: busy }, (0, import_react6.createElement)(CloseIcon)) : null
),
- (0, import_react6.createElement)(WidgetView, { view, onSubmit, settled, answer })
+ (0, import_react6.createElement)(WidgetView, { view, onSubmit, settled, answer, busy })
);
}
function PendingView({ sessionId, view, actions, inline }) {
const [answered, setAnswered] = (0, import_react6.useState)(null);
+ const busyRef = (0, import_react6.useRef)(false);
const hold = useDockHold(sessionId, "view", view.id, actions, inline);
- const onSubmit = (action, values) => {
- setAnswered(view.id);
- void actions.answerView(sessionId, view.id, action, values).catch(() => setAnswered(null));
- };
- const onDismiss = () => {
+ const flying = answered === view.id;
+ const run = (make) => {
+ if (busyRef.current) return;
+ busyRef.current = true;
+ hold();
setAnswered(view.id);
- void Promise.resolve(actions.dismissView(sessionId)).catch(() => setAnswered(null));
+ void Promise.resolve().then(make).catch(() => setAnswered(null)).finally(() => {
+ busyRef.current = false;
+ });
};
+ const onSubmit = (action, values) => run(() => actions.answerView(sessionId, view.id, action, values));
+ const onDismiss = () => run(() => actions.dismissView(sessionId));
return (0, import_react6.createElement)(
"div",
- { className: inline ? "bt-q-inline" : "bt-q-dock", style: answered === view.id ? { display: "none" } : void 0, onFocusCapture: hold, onPointerDownCapture: hold },
- (0, import_react6.createElement)(WidgetCard, { key: view.id, title: view.title ?? "", view: view.view, onSubmit, onDismiss, raised: !inline })
+ { className: inline ? "bt-q-inline" : "bt-q-dock", style: flying ? { display: "none" } : void 0, onFocusCapture: hold, onPointerDownCapture: hold },
+ (0, import_react6.createElement)(WidgetCard, { key: view.id, title: view.title ?? "", view: view.view, onSubmit, onDismiss, busy: flying, raised: !inline })
);
}
function WidgetCell({ sessionId, callId, args, done, isError, roster, actions, heldCards }) {
@@ -4337,12 +4359,11 @@ function WidgetCell({ sessionId, callId, args, done, isError, roster, actions, h
return (0, import_react6.createElement)(PendingView, { sessionId, view: record, actions, inline: true });
}
if (done && isError) return (0, import_react6.createElement)("span", { className: "bt-q-gone", hidden: true });
- const blueprint = normalizeView(args?.value?.("view"));
- const shown = checkShownView(args?.text?.("title"), blueprint);
+ const shown = checkShownView(args?.text?.("title"), args?.value?.("view"));
if (shown.error !== void 0 || shown.interactive || args?.value?.("await_reply") === true) {
return (0, import_react6.createElement)("span", { className: "bt-q-gone", hidden: true });
}
- return (0, import_react6.createElement)("div", { className: "bt-q-inline" }, (0, import_react6.createElement)(WidgetCard, { title: shown.title, view: blueprint }));
+ return (0, import_react6.createElement)("div", { className: "bt-q-inline" }, (0, import_react6.createElement)(WidgetCard, { title: shown.title, view: shown.view }));
}
function WidgetDock({ sessionId, useRoster, useCards, useHeldCards, actions }) {
const view = useRoster((value) => value.views?.[sessionId]);
diff --git a/ds-bot/src/client/questions.js b/ds-bot/src/client/questions.js
index a2f7e0ae..54718bff 100644
--- a/ds-bot/src/client/questions.js
+++ b/ds-bot/src/client/questions.js
@@ -1,8 +1,8 @@
-import { createElement as h, useEffect, useId, useRef, useState } from 'react'
+import { createElement as h, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react'
import { CloseIcon, CheckIcon } from './icons.js'
import { t } from './i18n.js'
import { useDockHold } from './card-hold.js'
-import { heldCardKey } from './sources.js'
+import { createSource, heldCardKey } from './sources.js'
// -------------------------------------------------------------------------
// Question cards. `ask_user` cards sit in the transcript and never block the Bot;
@@ -16,15 +16,22 @@ const isTypingTarget = node => node instanceof HTMLInputElement || node instance
// A bare letter picks that option and the letter after the last one
// jumps to the custom answer; never while typing or while a dialog is open.
+// The listener is document-wide, so two open cards with letter keys would both
+// answer the same key: each card registers here and the keys fire only while it
+// is the sole registered card. The count also drives the key hints.
+const optionKeyCards = createSource(0)
export function useOptionKeys(count, onPick, ownRef) {
const pick = useRef(onPick)
pick.current = onPick
+ const listening = useSyncExternalStore(optionKeyCards.subscribe, optionKeyCards.getSnapshot)
useEffect(() => {
if (count === 0) return undefined
+ optionKeyCards.set(value => value + 1)
const onKey = (event) => {
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || event.key.length !== 1) return
if (isTypingTarget(event.target) || isTypingTarget(document.activeElement)) return
if (document.querySelector('[role="dialog"], [aria-modal="true"]') !== null) return
+ if (optionKeyCards.getSnapshot() !== 1) return
const index = event.key.toUpperCase().charCodeAt(0) - 65
if (index >= 0 && index < count) {
event.preventDefault()
@@ -35,8 +42,14 @@ export function useOptionKeys(count, onPick, ownRef) {
}
}
document.addEventListener('keydown', onKey, true)
- return () => document.removeEventListener('keydown', onKey, true)
+ return () => {
+ document.removeEventListener('keydown', onKey, true)
+ optionKeyCards.set(value => value - 1)
+ }
}, [count, ownRef])
+ // Before the effect runs the card is not counted yet; read that as alone so a
+ // lone card's hints never flicker on mount.
+ return count > 0 && listening <= 1
}
// A question shows two ways: as a bubble in the transcript, and raised when it
diff --git a/ds-bot/src/client/widget-cell.js b/ds-bot/src/client/widget-cell.js
index 1fe33b74..2c6a34cb 100644
--- a/ds-bot/src/client/widget-cell.js
+++ b/ds-bot/src/client/widget-cell.js
@@ -5,7 +5,7 @@ import { t } from './i18n.js'
import { AnsweredCell, keyLetter, useOptionKeys } from './questions.js'
import { useDockHold } from './card-hold.js'
import { heldCardKey } from './sources.js'
-import { checkShownView, normalizeView } from '../shared/views.js'
+import { checkShownView } from '../shared/views.js'
// -------------------------------------------------------------------------
// View cards (show_view): a Bot draws a small declarative blueprint — text,
@@ -32,37 +32,38 @@ const countType = (node, type) => {
// The values an answer carries belong to the component whose id is its action.
const answerValues = (answer, node) => (answer?.action === node.id ? answer.values : undefined)
-function OptionsInput({ node, onSubmit, keys }) {
+function OptionsInput({ node, onSubmit, keys, busy = false }) {
const [picked, setPicked] = useState([])
const options = optionsOf(node)
const multi = node.multi === true
const choose = (label) => {
+ if (busy) return
if (multi) {
setPicked(current => (current.includes(label) ? current.filter(item => item !== label) : [...current, label]))
return
}
onSubmit?.(node.id, { selected: [label] })
}
- const submit = () => { if (picked.length > 0) onSubmit?.(node.id, { selected: picked }) }
+ const submit = () => { if (!busy && picked.length > 0) onSubmit?.(node.id, { selected: picked }) }
const ownRef = useRef(null)
- useOptionKeys(keys ? options.length : 0, index => choose(options[index].label), ownRef)
+ const hints = useOptionKeys(busy || !keys ? 0 : options.length, index => choose(options[index].label), ownRef)
return h(Fragment, null,
h('div', { className: 'bt-q-list', role: 'group' }, options.map((option, index) => {
const selected = multi && picked.includes(option.label)
return h('button', {
- key: option.label, type: 'button', className: 'bt-q-opt',
+ key: option.label, type: 'button', className: 'bt-q-opt', disabled: busy,
'aria-pressed': multi ? selected : undefined,
- 'aria-keyshortcuts': keys ? keyLetter(index).toLowerCase() : undefined,
+ 'aria-keyshortcuts': hints ? keyLetter(index).toLowerCase() : undefined,
onClick: () => choose(option.label),
},
- keys ? h('span', { className: 'bt-key', 'aria-hidden': true }, keyLetter(index)) : null,
+ hints ? h('span', { className: 'bt-key', 'aria-hidden': true }, keyLetter(index)) : null,
h('span', { className: 'bt-q-body' },
h('span', { className: 'bt-q-label' }, option.label),
option.description ? h('span', { className: 'bt-q-desc' }, option.description) : null),
selected ? h('span', { className: 'bt-q-check', title: t('Selected') }, h(CheckIcon)) : null)
})),
multi ? h('div', { className: 'bt-q-foot' },
- h('button', { type: 'button', className: 'bt-q-submit', disabled: picked.length === 0, onClick: submit }, t('Submit'))) : null)
+ h('button', { type: 'button', className: 'bt-q-submit', disabled: busy || picked.length === 0, onClick: submit }, t('Submit'))) : null)
}
function SettledOptions({ node, answer }) {
@@ -76,10 +77,10 @@ function SettledOptions({ node, answer }) {
chosen.includes(option.label) ? h('span', { className: 'bt-q-check', title: t('Selected') }, h(CheckIcon)) : null)))
}
-function ConfirmInput({ node, onSubmit }) {
+function ConfirmInput({ node, onSubmit, busy = false }) {
return h('div', { className: 'bt-q-foot' },
- h('button', { type: 'button', className: 'bt-q-btn', onClick: () => onSubmit?.(node.id, { confirmed: false }) }, node.cancelLabel ?? t('Cancel')),
- h('button', { type: 'button', className: 'bt-q-submit', onClick: () => onSubmit?.(node.id, { confirmed: true }) }, node.confirmLabel ?? t('Confirm')))
+ h('button', { type: 'button', className: 'bt-q-btn', disabled: busy, onClick: () => onSubmit?.(node.id, { confirmed: false }) }, node.cancelLabel ?? t('Cancel')),
+ h('button', { type: 'button', className: 'bt-q-submit', disabled: busy, onClick: () => onSubmit?.(node.id, { confirmed: true }) }, node.confirmLabel ?? t('Confirm')))
}
function SettledConfirm({ node, answer }) {
@@ -93,10 +94,10 @@ function SettledConfirm({ node, answer }) {
return h('span', { className: 'bt-q-badge' }, label)
}
-function FormInput({ node, onSubmit }) {
+function FormInput({ node, onSubmit, busy = false }) {
const fields = fieldsOf(node)
const [draft, setDraft] = useState({})
- const submit = () => onSubmit?.(node.id, { fields: Object.fromEntries(fields.map(field => [field.id, draft[field.id] ?? ''])) })
+ const submit = () => { if (!busy) onSubmit?.(node.id, { fields: Object.fromEntries(fields.map(field => [field.id, draft[field.id] ?? ''])) }) }
return h('form', {
className: 'bt-widget-form',
onSubmit: (event) => { event.preventDefault(); submit() },
@@ -106,16 +107,16 @@ function FormInput({ node, onSubmit }) {
h('span', { className: 'bt-q-field' },
h('input', {
className: 'bt-q-input', type: 'text', value: draft[field.id] ?? '',
- autoComplete: 'off', spellCheck: false,
+ autoComplete: 'off', spellCheck: false, readOnly: busy,
'aria-label': field.label, placeholder: field.placeholder ?? undefined,
- onChange: event => setDraft(current => ({ ...current, [field.id]: event.target.value })),
+ onChange: (event) => { if (!busy) setDraft(current => ({ ...current, [field.id]: event.target.value })) },
onKeyDown: (event) => {
if (event.key !== 'Enter' || event.nativeEvent.isComposing) return
event.preventDefault()
submit()
},
})))),
- h('div', { className: 'bt-q-foot' }, h('button', { type: 'submit', className: 'bt-q-submit' }, node.submitLabel ?? t('Submit'))))
+ h('div', { className: 'bt-q-foot' }, h('button', { type: 'submit', className: 'bt-q-submit', disabled: busy }, node.submitLabel ?? t('Submit'))))
}
function SettledForm({ node, answer }) {
@@ -167,9 +168,9 @@ function WidgetNode({ node, ctx }) {
h('span', { className: 'bt-widget-metric-value' }, node.value))
}
case 'table': return h(WidgetTable, { node })
- case 'options': return ctx.settled ? h(SettledOptions, { node, answer: ctx.answer }) : h(OptionsInput, { node, onSubmit: ctx.onSubmit, keys: ctx.keys })
- case 'confirm': return ctx.settled ? h(SettledConfirm, { node, answer: ctx.answer }) : h(ConfirmInput, { node, onSubmit: ctx.onSubmit })
- case 'form': return ctx.settled ? h(SettledForm, { node, answer: ctx.answer }) : h(FormInput, { node, onSubmit: ctx.onSubmit })
+ case 'options': return ctx.settled ? h(SettledOptions, { node, answer: ctx.answer }) : h(OptionsInput, { node, onSubmit: ctx.onSubmit, keys: ctx.keys, busy: ctx.busy })
+ case 'confirm': return ctx.settled ? h(SettledConfirm, { node, answer: ctx.answer }) : h(ConfirmInput, { node, onSubmit: ctx.onSubmit, busy: ctx.busy })
+ case 'form': return ctx.settled ? h(SettledForm, { node, answer: ctx.answer }) : h(FormInput, { node, onSubmit: ctx.onSubmit, busy: ctx.busy })
case 'progress': return h(WidgetProgress, { node })
default: return null
}
@@ -177,43 +178,48 @@ function WidgetNode({ node, ctx }) {
// A whole blueprint. Letter keys answer a lone options block from the keyboard;
// with more than one in a card the same letter would hit both.
-export function WidgetView({ view, onSubmit, settled = false, answer = null }) {
- const ctx = { onSubmit, settled, answer, keys: !settled && countType(view, 'options') === 1 }
+export function WidgetView({ view, onSubmit, settled = false, answer = null, busy = false }) {
+ const ctx = { onSubmit, settled, answer, busy, keys: !settled && countType(view, 'options') === 1 }
return h(WidgetNode, { node: view, ctx })
}
// The card chrome every view wears, pending or settled: a title bar with a small
// "View" tag, and a dismiss button while the card still waits for an answer.
-function WidgetCard({ title, view, onSubmit, onDismiss, raised = false, settled = false, answer = null }) {
+function WidgetCard({ title, view, onSubmit, onDismiss, busy = false, raised = false, settled = false, answer = null }) {
const titleId = useId()
return h('div', {
className: settled ? 'bt-q bt-q-settled' : raised ? 'bt-q bt-q-raised' : 'bt-q',
- role: 'group', 'aria-labelledby': titleId,
+ role: 'group', 'aria-labelledby': titleId, 'aria-busy': busy || undefined,
},
h('div', { className: 'bt-q-head' },
h('div', { className: 'bt-q-text' }, h('p', { className: 'bt-q-title', id: titleId }, title)),
h('span', { className: 'bt-q-badge' }, t('View')),
- onDismiss ? h('button', { type: 'button', className: 'bt-q-x', 'aria-label': t('Dismiss view'), title: t('Dismiss'), onClick: onDismiss }, h(CloseIcon)) : null),
- h(WidgetView, { view, onSubmit, settled, answer }))
+ onDismiss ? h('button', { type: 'button', className: 'bt-q-x', 'aria-label': t('Dismiss view'), title: t('Dismiss'), onClick: onDismiss, disabled: busy }, h(CloseIcon)) : null),
+ h(WidgetView, { view, onSubmit, settled, answer, busy }))
}
// A view waiting for its answer, inline at its call or raised in the dock. Like a
// pending question it hides on submit and comes back if the reply fails.
export function PendingView({ sessionId, view, actions, inline }) {
const [answered, setAnswered] = useState(null)
+ const busyRef = useRef(false)
const hold = useDockHold(sessionId, 'view', view.id, actions, inline)
- const onSubmit = (action, values) => {
+ const flying = answered === view.id
+ const run = (make) => {
+ // The ref, not the state: two clicks in the same frame both read flying=false.
+ if (busyRef.current) return
+ busyRef.current = true
+ hold()
setAnswered(view.id)
- void actions.answerView(sessionId, view.id, action, values).catch(() => setAnswered(null))
- }
- const onDismiss = () => {
- setAnswered(view.id)
- void Promise.resolve(actions.dismissView(sessionId)).catch(() => setAnswered(null))
+ void Promise.resolve().then(make).catch(() => setAnswered(null)).finally(() => { busyRef.current = false })
}
+ const onSubmit = (action, values) => run(() => actions.answerView(sessionId, view.id, action, values))
+ const onDismiss = () => run(() => actions.dismissView(sessionId))
// Hidden, not unmounted, while the answer is on its way: if it fails the card comes
- // back with what the user had typed or picked.
- return h('div', { className: inline ? 'bt-q-inline' : 'bt-q-dock', style: answered === view.id ? { display: 'none' } : undefined, onFocusCapture: hold, onPointerDownCapture: hold },
- h(WidgetCard, { key: view.id, title: view.title ?? '', view: view.view, onSubmit, onDismiss, raised: !inline }))
+ // back with what the user had typed or picked. The inputs stay busy meanwhile, so a
+ // letter key cannot answer a hidden card.
+ return h('div', { className: inline ? 'bt-q-inline' : 'bt-q-dock', style: flying ? { display: 'none' } : undefined, onFocusCapture: hold, onPointerDownCapture: hold },
+ h(WidgetCard, { key: view.id, title: view.title ?? '', view: view.view, onSubmit, onDismiss, busy: flying, raised: !inline }))
}
// The show_view call in the transcript.
@@ -226,10 +232,9 @@ export function WidgetCell({ sessionId, callId, args, done, isError, roster, act
// A refused call (bad blueprint) drew no card; don't render an empty one.
if (done && isError) return h('span', { className: 'bt-q-gone', hidden: true })
// Display-only cards draw from the recorded call arguments, which keep the
- // provider's encoding: unwrap it the same way the host does before storing. The
- // args accessor reads strings through `text`; `value` drops them.
- const blueprint = normalizeView(args?.value?.('view'))
- const shown = checkShownView(args?.text?.('title'), blueprint)
+ // provider's encoding: checkShownView measures and unwraps them as the host did.
+ // The args accessor reads strings through `text`; `value` drops them.
+ const shown = checkShownView(args?.text?.('title'), args?.value?.('view'))
// A call the host refused — a blueprint it would not show, or a reply it cannot
// wait for — leaves no card; the model's retry then stays the only one. So does
// a settled interactive call: answered, dismissed or replaced, it leaves no gap
@@ -237,7 +242,7 @@ export function WidgetCell({ sessionId, callId, args, done, isError, roster, act
if (shown.error !== undefined || shown.interactive || args?.value?.('await_reply') === true) {
return h('span', { className: 'bt-q-gone', hidden: true })
}
- return h('div', { className: 'bt-q-inline' }, h(WidgetCard, { title: shown.title, view: blueprint }))
+ return h('div', { className: 'bt-q-inline' }, h(WidgetCard, { title: shown.title, view: shown.view }))
}
// Views asked by a call the transcript does not draw wait above the composer,
diff --git a/ds-bot/test/card-hold.test.js b/ds-bot/test/card-hold.test.js
index 4b3c558b..9b9c17ab 100644
--- a/ds-bot/test/card-hold.test.js
+++ b/ds-bot/test/card-hold.test.js
@@ -14,10 +14,12 @@ const { outputFiles } = await build({
"export { useDockHold } from './src/client/card-hold.js'",
"export { PendingQuestion } from './src/client/questions.js'",
"export { SecretCard } from './src/client/secret-card.js'",
+ "export { PendingView } from './src/client/widget-cell.js'",
].join('\n'),
resolveDir: fileURLToPath(new URL('..', import.meta.url)),
},
- bundle: true, format: 'cjs', platform: 'browser', write: false, logLevel: 'silent', external: ['react'],
+ bundle: true, format: 'cjs', platform: 'browser', write: false, logLevel: 'silent',
+ external: ['react', '@deepseek-ai/dsh-client-ui-primitives'],
})
let current
const slot = (make) => {
@@ -39,12 +41,16 @@ const react = {
useRef: initial => slot(() => ({ current: initial })),
useId: () => slot(() => ({ id: 'card-id' })).id,
useEffect: effect, useLayoutEffect: effect,
+ useSyncExternalStore: (subscribe, getSnapshot) => getSnapshot(),
}
const keys = new Set()
const module = { exports: {} }
runInNewContext(outputFiles[0].text, {
module, exports: module.exports,
- require: name => { assert.equal(name, 'react'); return react },
+ require: (name) => {
+ assert.ok(name === 'react' || name === '@deepseek-ai/dsh-client-ui-primitives')
+ return name === 'react' ? react : { MarkdownText: ({ text }) => text }
+ },
document: {
activeElement: null, querySelector: () => null,
addEventListener: (type, listener) => { if (type === 'keydown') keys.add(listener) },
@@ -52,7 +58,7 @@ runInNewContext(outputFiles[0].text, {
},
HTMLInputElement: class {}, HTMLTextAreaElement: class {}, HTMLSelectElement: class {}, HTMLElement: class {},
})
-const { useDockHold, PendingQuestion, SecretCard } = module.exports
+const { useDockHold, PendingQuestion, SecretCard, PendingView } = module.exports
const mount = (Component, props) => {
const instance = {
slots: [], effects: [], props,
@@ -242,3 +248,81 @@ test('secret edits stay local and an in-flight save preserves value and scope fo
card.unmount()
assert.equal(count('chief', 'secret', 'request'), 0)
})
+
+const pendingView = () => ({ id: 'view-1', callId: 'call-1', title: 'Pick', view: { type: 'options', id: 'pick', options: [{ label: 'A' }, { label: 'B' }] } })
+
+test('a pending view hides but stays mounted while its request is in flight', async () => {
+ const { actions, count } = lease()
+ const wait = deferred()
+ const sent = []
+ let result = wait.promise
+ actions.answerView = (...args) => { sent.push(plain(args)); return result }
+ actions.dismissView = () => { sent.push('dismiss'); return result }
+ const pending = mount(PendingView, { actions, sessionId: 'chief', view: pendingView(), inline: false })
+ const card = pending.render()
+ assert.equal(card.props.style, undefined)
+ // A second submit while the first is in flight is swallowed.
+ childOf(card).props.onSubmit('pick', { selected: ['A'] })
+ childOf(card).props.onSubmit('pick', { selected: ['B'] })
+ const flying = pending.render()
+ assert.deepEqual(plain(flying.props.style), { display: 'none' })
+ assert.equal(childOf(flying).props.busy, true)
+ assert.equal(count('chief', 'view', 'view-1'), 1)
+ await tick()
+ assert.deepEqual(sent, [['chief', 'view-1', 'pick', { selected: ['A'] }]])
+ wait.reject(new Error('Temporary failure'))
+ await tick()
+ // The rejection brings the card back, still holding what the user picked.
+ const back = pending.render()
+ assert.equal(back.props.style, undefined)
+ assert.equal(childOf(back).props.busy, false)
+ // A failed dismiss brings the card back too: the server still waits on it.
+ const dismiss = deferred()
+ result = dismiss.promise
+ childOf(pending.render()).props.onDismiss()
+ assert.deepEqual(plain(pending.render().props.style), { display: 'none' })
+ await tick()
+ assert.deepEqual(sent.at(-1), 'dismiss')
+ dismiss.reject(new Error('flush failed'))
+ await tick()
+ assert.equal(pending.render().props.style, undefined)
+ result = Promise.resolve()
+ childOf(pending.render()).props.onSubmit('pick', { selected: ['B'] })
+ await tick()
+ assert.equal(sent.at(-1)[2], 'pick')
+ assert.deepEqual(plain(pending.render().props.style), { display: 'none' })
+ pending.unmount()
+ assert.equal(count('chief', 'view', 'view-1'), 0)
+})
+
+test('letter keys answer a card only while it is the sole open card with keys', async () => {
+ const { actions } = lease()
+ const answers = []
+ actions.answerQuestion = (...args) => { answers.push(plain(args)); return Promise.resolve() }
+ actions.dismissQuestion = () => Promise.resolve()
+ const ask = id => ({ ...question, id, multiSelect: false })
+ const first = mount(PendingQuestion, { actions, sessionId: 'chief', question: ask('first'), inline: false })
+ const second = mount(PendingQuestion, { actions, sessionId: 'chief', question: ask('second'), inline: false })
+ const firstCard = childOf(first.render())
+ const secondCard = childOf(second.render())
+ const firstView = mount(firstCard.type, firstCard.props)
+ const secondView = mount(secondCard.type, secondCard.props)
+ firstView.render()
+ secondView.render()
+ assert.equal(keys.size, 2)
+ const key = () => ({ key: 'a', target: null, preventDefault() { this.defaultPrevented = true } })
+ const shared = key()
+ for (const listener of [...keys]) listener(shared)
+ // Two open cards both stay silent rather than the first listener stealing the key.
+ assert.equal(shared.defaultPrevented, undefined)
+ assert.equal(answers.length, 0)
+ firstView.unmount()
+ assert.equal(keys.size, 1)
+ for (const listener of [...keys]) listener(key())
+ await tick()
+ assert.deepEqual(answers, [['chief', 'second', { selected: ['Short'], custom: '' }]])
+ secondView.unmount()
+ first.unmount()
+ second.unmount()
+ assert.equal(keys.size, 0)
+})
diff --git a/ds-bot/test/tool-cells.test.js b/ds-bot/test/tool-cells.test.js
index 32a43dc7..37cc41d9 100644
--- a/ds-bot/test/tool-cells.test.js
+++ b/ds-bot/test/tool-cells.test.js
@@ -29,6 +29,7 @@ const react = {
useLayoutEffect: (effect) => { effects.push(effect) },
useState: initial => [typeof initial === 'function' ? initial() : initial, value => sets.push(value)],
useMemo: make => make(), useRef: current => ({ current }), useId: () => 'card-id',
+ useSyncExternalStore: (subscribe, getSnapshot) => getSnapshot(),
}
const timers = new Set()
const module = { exports: {} }