Skip to content

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

Merge remote-tracking branch 'origin/dev' into HEAD

Fei24110cae9aa6f4aa
diff --cc ds-bot/client.js
index 3706d6a6,e415f1a9..f4c8dada
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@@ -12927,2816 -12557,1658 +12956,2833 @@@ function MessageTools({ text, name, ses
), document.body) : null
);
}
-
-// src/client/at-menu.js
-var BOTS_SOURCE = "ds-bot";
-var CHATS_SOURCE = "ds-bot-chats";
-var ROOM_ALL = ["all", "everyone", "所有人", "全体"];
-var OTHER_CHATS_MAX = 8;
-var conversationOf = (roster, sessionId) => {
- if (!roster.ready) return null;
- const room2 = roster.roomsById[sessionId];
- if (room2) return { room: room2 };
- const self = roster.byId[sessionId];
- return self ? { self } : null;
-};
-function mentionRows(roster, sessionId, query = "") {
- const here = conversationOf(roster, sessionId);
- if (here === null) return null;
- const bots = here.room ? here.room.members.map((id) => roster.byId[id]).filter(Boolean) : roster.bots.filter((bot) => bot.id !== here.self.id);
- const needle = query.trim().toLowerCase();
- const rows2 = bots.filter((bot) => bot.name.toLowerCase().includes(needle)).map((bot) => ({ bot, text: `@${bot.name} ` }));
- const everyone = t("Everyone");
- if (here.room && bots.length > 1 && [everyone, ...ROOM_ALL].some((word) => word.toLowerCase().startsWith(needle))) {
- rows2.push({ room: here.room, text: `@${everyone} ` });
- }
- return rows2;
+var thinkingTimes = /* @__PURE__ */ new Map();
+function useThinkingMs({ sessionId, turn, settledSteps, skip }) {
+ const key = `${sessionId}:${turn}:${settledSteps}`;
+ const [ms, setMs] = (0, import_react30.useState)(() => thinkingTimes.get(key));
+ (0, import_react30.useEffect)(() => {
+ if (skip || thinkingTimes.has(key)) {
+ setMs(thinkingTimes.get(key));
+ return void 0;
+ }
+ const control = new AbortController();
+ call("thinking", { sessionId, turn }, control.signal).then((value) => {
+ thinkingTimes.set(key, value?.ms);
+ setMs(value?.ms);
+ }).catch(() => {
+ });
+ return () => control.abort();
+ }, [key, skip]);
+ return ms;
}
-function chatRows(roster, list, sessionId) {
- const here = conversationOf(roster, sessionId);
- if (here === null) return [];
- const byId = list?.byId ?? {};
- const bots = roster.bots.filter((bot) => bot.id !== here.self?.id).map((bot) => {
- const id = currentPart(bot);
- return { sessionId: id, label: t("Chat with {name}", { name: bot.name }), bot, updatedAt: byId[id]?.updatedAt };
+var rowViews = /* @__PURE__ */ new Map();
+function ThinkingRow({ text, live, at, ms, viewKey }) {
+ const box = (0, import_react30.useRef)(null);
+ const view = (0, import_react30.useRef)(rowViews.get(viewKey));
+ const atEnd = (0, import_react30.useRef)(view.current?.atEnd ?? true);
+ const [open, setOpen] = (0, import_react30.useState)(view.current?.open ?? false);
+ const [fade, setFade] = (0, import_react30.useState)(void 0);
+ const remember = (patch) => {
+ if (viewKey !== void 0) rowViews.set(viewKey, { ...rowViews.get(viewKey), ...patch });
+ };
+ const measure = () => {
+ const el = box.current;
+ atEnd.current = el.scrollHeight - el.scrollTop - el.clientHeight < 2;
+ remember({ atEnd: atEnd.current, top: el.scrollTop });
+ const above = el.scrollTop > 0;
+ setFade(above && !atEnd.current ? "both" : above ? "top" : !atEnd.current ? "bottom" : void 0);
+ };
+ const toggle = (event) => {
+ const next = event.currentTarget.open;
+ if (next) atEnd.current = true;
+ remember({ open: next });
+ setOpen(next);
+ };
+ (0, import_react30.useLayoutEffect)(() => {
+ if (!open) return;
+ const el = box.current;
+ const restore = view.current;
+ view.current = void 0;
+ if (atEnd.current) el.scrollTop = el.scrollHeight;
+ else if (restore?.top !== void 0) el.scrollTop = restore.top;
+ measure();
+ }, [text, open]);
+ const title = live ? t("Thinking") : t("Thought it through");
+ return (0, import_react30.createElement)(
+ "details",
+ { className: "bt-think", open, onToggle: toggle },
+ (0, import_react30.createElement)(
+ "summary",
+ null,
+ title,
+ live && at !== void 0 ? (0, import_react30.createElement)(Elapsed, { at, className: "bt-think-time" }) : null,
+ !live && ms !== void 0 ? (0, import_react30.createElement)("span", { className: "bt-think-time" }, `· ${elapsedLabel(Math.max(1e3, ms))}`) : null
+ ),
+ (0, import_react30.createElement)("div", { ref: box, className: "bt-think-text", role: "region", "aria-label": title, tabIndex: 0, "data-fade": fade, onScroll: measure }, text)
+ );
+}
+function useFileMentions({ node, openFile, fileMentions, useTurnData }) {
+ const tail = useTurnData?.("turn-tail");
+ const location2 = node.location;
+ const turn = location2?.kind === "turn" || location2?.kind === "step" ? location2.turn : void 0;
+ const seq = node.data.finalNode?.seq;
+ return (0, import_react30.useMemo)(() => {
+ if (typeof fileMentions !== "function" || turn?.status !== "closed" || seq === void 0) return void 0;
+ return tail?.closing?.finalNode.seq === seq ? fileMentions({ turn, seq, openFile }) : void 0;
+ }, [fileMentions, openFile, seq, tail, turn]);
+}
+function AssistantCell({ node, groupPart, sessionId, openFile, fileMentions, useTurnData, useRoster, useUi, useTurnSteps, useTurnContext, actions }) {
+ const roster = useRoster((value) => value);
+ const data = node.data;
+ const steps = useTurnSteps(String(data.turn));
+ const contexts = useTurnContext(String(data.turn));
+ const mentions = useFileMentions({ node, openFile, fileMentions, useTurnData });
+ const hidden = Boolean(roster.roomsById[sessionId]) || isHiddenTurn(roster, sessionId, data.turn);
+ const texts2 = groupPart === "reasoning" ? [] : data.blocks.filter((block) => block.kind === "text" && block.text.trim() !== "").map((block) => block.text);
+ const running = data.status === "running";
+ const members = steps.length ? steps : [data];
+ const shown = thinkingShown(roster.prefs);
+ const reasoning = groupPart === "response" || !shown ? "" : turnReasoning(steps, data);
+ const thinking = groupPart === "response" || !shown ? void 0 : thinkingStep(members);
+ const ms = useThinkingMs({ sessionId, turn: data.turn, settledSteps: members.filter((step) => step.status !== "running").length, skip: hidden || reasoning === "" });
+ useLiveNote(actions, sessionId, `text:${node.key ?? data.seq}`, !hidden && running && texts2.length > 0 ? { text: true } : null);
+ if (hidden) return (0, import_react30.createElement)(CellEmpty);
+ const relays = relayPart(data, groupPart) ? relaysBefore(contexts, steps, data) : [];
+ if (texts2.length === 0 && !reasoning && relays.length === 0) return (0, import_react30.createElement)(CellEmpty);
+ const selfId = roster.byId[sessionId]?.id ?? sessionId;
+ const speaker = layoutOf(roster.prefs) === "flat" ? roster.byId[sessionId] : void 0;
+ const head = speaker !== void 0 && opensReply(steps, data, shown) && (reasoning !== "" || texts2.length > 0 && !(groupPart === "response" && shown && turnReasoning(steps, data) !== ""));
+ return (0, import_react30.createElement)(
+ import_react30.Fragment,
+ null,
+ relays.map((relay) => {
+ const source = relay.source;
+ const sender = roster.byId[source.senderSessionId] ?? { id: source.senderSessionId, name: source.senderName ?? t("a Bot"), color: "gray" };
+ return (0, import_react30.createElement)(EventLine, {
+ key: relay.seq,
+ prefix: source.role === "stopped" ? t("Stopped by") : source.role === "reply" ? t("Reply from") : t("Message from"),
+ bots: [sender],
+ onOpen: () => {
+ if (sender.id) actions.openExchange(selfId, sender.id);
+ },
+ whole: true
+ });
+ }),
+ head ? (0, import_react30.createElement)(SpeakerHead, { bot: speaker, time: data.time }) : null,
+ reasoning ? (0, import_react30.createElement)(ThinkingRow, {
+ text: reasoning,
+ live: thinking !== void 0,
+ viewKey: `${sessionId}:${data.turn}`,
+ // The live clock counts the settled steps too: backing `at` by the settled
+ // time makes one Elapsed show settled + running.
+ ...thinking !== void 0 ? { at: typeof thinking.time === "number" ? thinking.time - (ms ?? 0) : void 0 } : { ms }
+ }) : null,
+ texts2.length ? (0, import_react30.createElement)(Bubbles, { texts: texts2, roster, selfId, actions, streaming: running, sessionId, msgKey: `${sessionId}:${data.turn}:${node.key ?? data.seq ?? ""}`, useUi, mentions, fold: FOLD_HUGE, time: speaker === void 0 ? data.time : void 0 }) : null
+ );
+}
+function EventLine({ prefix, bots, joiner = t("and"), onOpen, whole = false }) {
+ if (whole && bots.length === 1) {
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-event" },
+ (0, import_react30.createElement)(
+ "button",
+ { type: "button", className: "bt-event-whole", title: bots[0].name, onClick: () => onOpen?.(bots[0]) },
+ (0, import_react30.createElement)("span", null, prefix),
+ (0, import_react30.createElement)(BotMark, { bot: bots[0], size: 16 }),
+ (0, import_react30.createElement)("span", { className: "bt-event-name" }, bots[0].name)
+ )
+ );
+ }
+ const parts = [];
+ parts.push((0, import_react30.createElement)("span", { key: "p" }, prefix));
+ bots.forEach((bot, index) => {
+ if (index > 0) parts.push((0, import_react30.createElement)("span", { key: `j${index}` }, joiner));
+ parts.push((0, import_react30.createElement)(
+ "button",
+ { key: bot.id ?? index, type: "button", onClick: () => onOpen?.(bot) },
+ (0, import_react30.createElement)(BotMark, { bot, size: 16 }),
+ bot.name
+ ));
});
- const team = /* @__PURE__ */ new Set([
- ...roster.bots.flatMap((bot) => [bot.id, currentPart(bot), ...bot.parts ?? []]),
- ...roster.rooms.flatMap((room2) => [room2.id, room2.sessionId, ...room2.ownParts ?? [], ...room2.parts ?? []].filter((id) => id !== void 0))
- ]);
- const others = (list?.ids ?? []).map((id) => byId[id]).filter((row) => row !== void 0 && row.id !== sessionId && !team.has(row.id) && row.origin !== "subagent" && row.blank !== true).sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0)).slice(0, OTHER_CHATS_MAX).map((row) => ({ sessionId: row.id, label: row.displayTitle || row.title || row.id, updatedAt: row.updatedAt }));
- return [...bots, ...others];
-}
-function sessionMention(sessionId, label) {
- let binary2 = "";
- for (const byte of new TextEncoder().encode(JSON.stringify(sessionId))) binary2 += String.fromCharCode(byte);
- const payload = btoa(binary2).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
- return `@[${label.replace(/[\\\]]/g, (mark) => `\\${mark}`)}](dsh-session:${payload})`;
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, parts);
}
-function atSources({ roster, sessions, launched, iconFor }) {
- const bots = {
- trigger: "@",
- name: BOTS_SOURCE,
- order: -20,
- showGroupTitle: false,
- async candidates(session, { query }) {
- return (mentionRows(roster.getSnapshot(), session.sessionId, query) ?? []).map((row) => ({
- name: row.bot ? row.bot.name : t("Everyone"),
- ...row.bot?.role ? { description: row.bot.role } : {},
- ...row.room ? { description: t("{count} members", { count: row.room.members.length }) } : {},
- icon: iconFor(row),
- section: t("Bots"),
- value: row.text
- }));
- },
- onPick: ({ candidate }) => candidate.value ? { text: candidate.value } : void 0
- };
- const chats = {
- trigger: "@",
- name: CHATS_SOURCE,
- order: -10,
- showGroupTitle: false,
- async candidates(session) {
- if (!launched(session.sessionId)) return [];
- return chatRows(roster.getSnapshot(), sessions.list.getSnapshot(), session.sessionId).map((row) => ({
- name: row.bot ? row.bot.name : row.label,
- ...row.updatedAt ? { description: relativeShort(row.updatedAt) } : {},
- icon: row.bot ? iconFor(row) : "session",
- section: row.bot ? t("Bots") : t("Conversations"),
- value: JSON.stringify({ sessionId: row.sessionId, label: row.label })
- }));
- },
- onPick({ candidate }) {
- const { sessionId, label } = JSON.parse(candidate.value);
- const mention = sessionMention(sessionId, label);
- return { insert: { source: CHATS_SOURCE, ref: mention, label, appearance: "session", clipboardText: mention } };
- },
- codec: { clipboardText: (ref) => ref, serialize: (ref) => Promise.resolve(ref) }
- };
- return [bots, chats];
+function SpeakerHead({ bot, time }) {
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-group-name" },
+ (0, import_react30.createElement)("span", { className: "bt-lead" }, (0, import_react30.createElement)(BotMark, { bot, size: 22 })),
+ bot.name,
+ Number.isFinite(time) ? (0, import_react30.createElement)("span", { className: "bt-group-time", title: clockLabel(time) }, messageClock(time)) : null
+ );
}
-
-// src/client/side-model.js
-var SIDE_SOURCE = "ds-bot-side";
-var SIDE_TOKEN = "/side ";
-var GROUP_REFUSAL = "Side chat is only available in a Bot's private chat.";
-var ATTACHMENT_REFUSAL = "/side does not take attachments.";
-var EMPTY_REFUSAL = "Write a question after /side.";
-var LOADING_REFUSAL = "DS Bot is still loading this chat.";
-function sideSurface(roster, sessionId) {
- if (!roster?.ready) return "unknown";
- if (roster.roomsById?.[sessionId]) return "group";
- if (roster.byId?.[sessionId]) return "bot";
- return "other";
+var CHAIN_BREAK_SEL = ".bt-group-msg, .bt-umsg, .bt-urow, [data-chat-flow-kind=user], [data-chat-flow-kind=command-input], .bt-q-inline, .bt-event, .bt-time-sep, .bt-new-sep, .bt-part-line, .bt-btw-card, .bt-learn-card";
+function syncGroupChains(flow) {
+ const items = [...flow.querySelectorAll(CHAIN_BREAK_SEL)];
+ for (let i = 0; i < items.length; i += 1) {
+ const curr = items[i];
+ if (!curr.classList.contains("bt-group-msg")) continue;
+ const prev = items[i - 1];
+ const next = items[i + 1];
+ const botId = curr.dataset.botId;
+ const chainPrev = Boolean(botId && prev?.classList.contains("bt-group-msg") && prev.dataset.botId === botId);
+ const chainNext = Boolean(botId && next?.classList.contains("bt-group-msg") && next.dataset.botId === botId);
+ if (chainPrev) curr.dataset.chainPrev = "";
+ else delete curr.dataset.chainPrev;
+ if (chainNext) curr.dataset.chainNext = "";
+ else delete curr.dataset.chainNext;
+ const turn = curr.closest("[data-chat-group-key]");
+ if (turn) {
+ if (chainPrev) turn.dataset.btChainPrev = "";
+ else delete turn.dataset.btChainPrev;
+ if (chainNext) turn.dataset.btChainNext = "";
+ else delete turn.dataset.btChainNext;
+ }
+ }
}
-function sideChatsOf(roster, botId) {
- const chats = roster?.sideChats?.[botId];
- return Array.isArray(chats) ? chats : [];
+var pendingFlows = /* @__PURE__ */ new WeakSet();
+function scheduleGroupChains(flow) {
+ if (!flow || pendingFlows.has(flow)) return;
+ pendingFlows.add(flow);
+ queueMicrotask(() => {
+ pendingFlows.delete(flow);
+ if (flow.isConnected !== false) syncGroupChains(flow);
+ });
}
-function parseSideLine(line) {
- const trimmed2 = String(line ?? "").trim();
- if (!trimmed2.startsWith("/")) return null;
- const gap = trimmed2.search(/\s/);
- const token = gap === -1 ? trimmed2 : trimmed2.slice(0, gap);
- if (token !== "/side") return null;
- const args = gap === -1 ? "" : trimmed2.slice(gap + 1);
- return { args, bare: args.trim() === "" };
+function GroupMessage({ bot, text, texts: texts2 = [text], room: room2, roster, actions, msgKey, useUi, whole, time, duration }) {
+ const ref = (0, import_react30.useRef)(null);
+ (0, import_react30.useLayoutEffect)(() => {
+ const el = ref.current;
+ if (!el?.closest) return void 0;
+ const flow = el.closest("[data-chat-flow]");
+ if (!flow) return void 0;
+ scheduleGroupChains(flow);
+ return () => scheduleGroupChains(flow);
+ }, [bot.id]);
+ const lead = (0, import_react30.createElement)(
+ "button",
+ { type: "button", className: "bt-lead", "aria-label": t("Open {name}'s chat", { name: bot.name }), onClick: () => actions.openSession(bot.id) },
+ (0, import_react30.createElement)(BotMark, { bot, size: 22 })
+ );
+ const flat = layoutOf(roster.prefs) === "flat";
+ const took = Number.isFinite(duration) && duration >= 1e3 ? elapsedLabel(duration) : void 0;
+ return (0, import_react30.createElement)(
+ "div",
+ { ref, className: "bt-group-msg", "data-bot-id": bot.id },
+ (0, import_react30.createElement)(
+ "span",
+ { className: "bt-group-name", style: flat ? void 0 : { color: inkText(colorOf(bot)) } },
+ flat ? lead : null,
+ bot.name,
+ room2?.admin === bot.id ? (0, import_react30.createElement)("span", { className: "bt-group-role" }, t("Admin")) : null,
+ Number.isFinite(time) ? (0, import_react30.createElement)("span", { className: "bt-group-time", title: clockLabel(time) }, messageClock(time)) : null,
+ took ? (0, import_react30.createElement)("span", { className: "bt-group-took", title: t("Ran for {duration}", { duration: took }) }, took) : null
+ ),
+ (0, import_react30.createElement)(Bubbles, { texts: texts2, roster, selfId: bot.id, actions, sessionId: room2?.id, msgKey, useUi, lead: flat ? null : lead, whole })
+ );
}
-function sideQueryMatches(query) {
- const head = String(query ?? "").trim().toLowerCase().split(/\s/, 1)[0] ?? "";
- return head === "" || "side".startsWith(head);
+function GroupEvent({ prefix, room: room2, name, roster, actions }) {
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-event" },
+ (0, import_react30.createElement)("span", null, prefix),
+ room2 ? (0, import_react30.createElement)("button", { type: "button", onClick: () => actions.openSession(room2.id) }, (0, import_react30.createElement)(RoomAvatar, { room: room2, roster, size: 16 }), room2.name) : name ? (0, import_react30.createElement)("span", null, name) : null
+ );
}
-function matchSideSpace(roster, sessionId, token) {
- if (token !== "/side" || sideSurface(roster, sessionId) !== "bot") return void 0;
- return { claim: true };
+var MEMORY_SAVED = /^(Saved to|Updated in|Removed from) /;
+var MEMORY_ALREADY = /^Already in /;
+var MEMORY_TEAM = /^(team|团队|共享)$/i;
+var MEMORY_OWN = /^(own|me|mine|self|yours?|自己|我)$/i;
+var MEMORY_GROUP = /^(group|this group|群|本群|群聊)$/i;
+function memoryFailure(code) {
+ if (!code) return void 0;
+ switch (code) {
+ case "memory/empty":
+ return t("Write something to save");
+ case "memory/no-match":
+ return t("No saved entry matched");
+ case "memory/refused":
+ case "memory/denied":
+ return t("The memory refused this change");
+ // A write that broke, and any failure this interface does not know.
+ default:
+ return t("The memory could not be changed");
+ }
}
-function matchSideClaim(roster, sessionId, token) {
- if (token !== "/side" || sideSurface(roster, sessionId) !== "bot") return void 0;
- return true;
+function MemoryEvent({ sessionId, scope, tool, result, failed, code, roster, actions, findBot }) {
+ const self = roster.byId[sessionId];
+ const room2 = roster.roomsById[sessionId];
+ const named = String(scope ?? "").trim();
+ const team = MEMORY_TEAM.test(named);
+ const other = team || named === "" ? void 0 : findBot(named);
+ const target = other && other.id !== self?.id ? other : self;
+ const panel = team ? self?.id : MEMORY_OWN.test(named) ? self?.id : MEMORY_GROUP.test(named) ? room2?.id : named === "" ? room2?.id ?? self?.id : other?.id;
+ if (!failed && MEMORY_ALREADY.test(result)) {
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-event" },
+ panel === void 0 ? (0, import_react30.createElement)("span", null, (0, import_react30.createElement)(MemoryIcon), t("Already saved")) : (0, import_react30.createElement)("button", { type: "button", onClick: () => actions.openMemory(panel) }, (0, import_react30.createElement)(MemoryIcon), t("Already saved"))
+ );
+ }
+ if (!failed && MEMORY_SAVED.test(result)) {
+ if (!target) return (0, import_react30.createElement)(CellEmpty);
+ const label2 = team ? t("Team memory updated") : target === self ? t("Memory updated") : t("Updated {name}'s memory", { name: target.name });
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-event" },
+ (0, import_react30.createElement)("button", { type: "button", title: result, onClick: () => actions.openMemory(target.id) }, (0, import_react30.createElement)(MemoryIcon), label2)
+ );
+ }
+ const reason = memoryFailure(code);
+ const label = failed ? tool === "forget" ? t("Couldn't remove from memory") : t("Couldn't save to memory") : t("Memory not changed");
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-event bt-event-error", role: "status", title: code },
+ (0, import_react30.createElement)("span", null, (0, import_react30.createElement)(MemoryIcon), label),
+ reason ? (0, import_react30.createElement)("span", null, ` · ${reason}`) : null,
+ panel === void 0 ? null : (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => actions.openMemory(panel) }, t("Manage"))
+ );
}
-function liveRoster(roster) {
- if (typeof roster?.getSnapshot === "function" && typeof roster?.subscribe === "function") return roster;
- return void 0;
+function PartLine({ time }) {
+ return (0, import_react30.createElement)("div", { className: "bt-part-line", role: "separator" }, Number.isFinite(time) ? (0, import_react30.createElement)("span", null, dayLabel(time)) : null);
}
-function readRoster(roster) {
- const live = liveRoster(roster);
- return live ? live.getSnapshot() : roster;
+var scrollParent = (node) => {
+ for (let at = node.parentElement; at; at = at.parentElement) {
+ if (/(auto|scroll)/.test(getComputedStyle(at).overflowY)) return at;
+ }
+ return null;
+};
+function EarlierUser({ row, actions }) {
+ const { shown, folded, control, code, codeHead } = useFold(row.text ?? "");
+ const body = row.text && shown !== "" ? (0, import_react30.createElement)(import_dsh_client_ui_primitives.MarkdownText, { text: shown, labels: mdLabels3(), variant: "compact" }) : null;
+ const area = foldArea(body, code, codeHead, actions);
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-urow" },
+ (0, import_react30.createElement)(
+ "div",
+ { className: "bt-ububble", "data-folded": folded || void 0 },
+ control ? (0, import_react30.createElement)("div", { className: "bt-fold-body" }, area) : area,
+ control,
+ row.images ? (0, import_react30.createElement)("span", { className: "bt-uimages" }, row.images === 1 ? t("1 image") : t("{count} images", { count: row.images })) : null
+ ),
+ row.via ? (0, import_react30.createElement)("div", { className: "bt-utime" }, (0, import_react30.createElement)(ViaTag, { via: row.via }), Number.isFinite(row.time) ? messageClock(row.time) : null) : null
+ );
}
-function abortError(signal) {
- if (signal?.reason instanceof Error) return signal.reason;
- return new Error("slash adjudication aborted");
+function EarlierParts({ sessionId, roster, actions }) {
+ const [view, setView] = (0, import_react30.useState)({ pages: [], cursor: void 0, loading: true, failed: false, startedAt: null });
+ const top = (0, import_react30.useRef)(null);
+ const busy = (0, import_react30.useRef)(false);
+ const generation = (0, import_react30.useRef)(0);
+ const restore = (0, import_react30.useRef)(null);
+ const load = (cursor) => {
+ if (busy.current) return;
+ const mine = generation.current;
+ const room2 = roster.roomsById[sessionId];
+ const owner = roster.byId[sessionId] ?? (room2 === void 0 ? void 0 : { parts: room2.ownParts, sessionId: room2.sessionId });
+ const partIndex = partIndexOf(owner, sessionId, cursor);
+ busy.current = true;
+ setView((current) => ({ ...current, loading: true, failed: false }));
+ actions.earlier(sessionId, cursor).then((page) => {
+ if (mine !== generation.current) return;
+ busy.current = false;
+ const scroller = top.current && scrollParent(top.current);
+ if (scroller) restore.current = { scroller, fromEnd: scroller.scrollHeight - scroller.scrollTop };
+ const incoming = Array.isArray(page.items) ? page.items : [];
+ setView((current) => {
+ const pages = current.pages.slice();
+ const at = pages.findIndex((entry) => entry.partIndex === partIndex);
+ const btw = Array.isArray(page.btw) ? page.btw : at >= 0 ? pages[at].btw : [];
+ if (at >= 0) pages[at] = { partIndex, items: [...incoming, ...pages[at].items], btw };
+ else pages.push({ partIndex, items: incoming, btw });
+ pages.sort((a, b) => a.partIndex - b.partIndex);
+ return { pages, cursor: page.cursor, loading: false, failed: false, startedAt: page.startedAt ?? current.startedAt };
+ });
+ }, () => {
+ if (mine !== generation.current) return;
+ busy.current = false;
+ setView((current) => ({ ...current, loading: false, failed: true }));
+ });
+ };
+ (0, import_react30.useEffect)(() => {
+ generation.current += 1;
+ busy.current = false;
+ setView({ pages: [], cursor: void 0, loading: true, failed: false, startedAt: null });
+ load(void 0);
+ return () => {
+ generation.current += 1;
+ };
+ }, [sessionId]);
+ (0, import_react30.useLayoutEffect)(() => {
+ const pending = restore.current;
+ restore.current = null;
+ if (pending) pending.scroller.scrollTop = pending.scroller.scrollHeight - pending.fromEnd;
+ }, [view.pages]);
+ (0, import_react30.useEffect)(() => {
+ const node = top.current;
+ if (!node || view.loading || view.failed || !view.cursor || typeof IntersectionObserver !== "function") return void 0;
+ const observer = new IntersectionObserver((entries2) => {
+ if (entries2.some((entry) => entry.isIntersecting)) load(view.cursor);
+ }, { root: scrollParent(node), rootMargin: "600px 0px 0px 0px" });
+ observer.observe(node);
+ return () => observer.disconnect();
+ }, [view.cursor, view.loading, view.failed]);
+ const removeBtw = (cardId) => setView((current) => ({
+ ...current,
+ pages: current.pages.map((page) => ({ ...page, btw: page.btw.filter((card) => card?.id !== cardId) }))
+ }));
+ const items = [];
+ for (const page of view.pages) items.push(...withBtwRows(page.items, page.btw));
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-earlier", role: "feed", "aria-label": t("Earlier messages"), "aria-busy": view.loading },
+ (0, import_react30.createElement)(
+ "div",
+ { ref: top, className: "bt-earlier-top" },
+ view.loading ? (0, import_react30.createElement)(Shimmer, null, t("Loading earlier messages…")) : view.failed ? (0, import_react30.createElement)("button", { type: "button", className: "bt-soft", onClick: () => load(view.cursor) }, t("Couldn’t load earlier messages · Retry")) : view.cursor ? (0, import_react30.createElement)("button", { type: "button", className: "bt-soft", onClick: () => load(view.cursor) }, t("Load earlier")) : null
+ ),
+ (0, import_react30.createElement)(ChatRows, { items, sessionId, roster, actions, onBtwDelete: removeBtw }),
+ (0, import_react30.createElement)(PartLine, { time: view.startedAt })
+ );
}
-function whenRosterReady(roster, signal) {
- const current = readRoster(roster);
- if (current?.ready) return Promise.resolve(current);
- const live = liveRoster(roster);
- if (!live) return Promise.reject(new Error(t(LOADING_REFUSAL)));
- return new Promise((resolve2, reject) => {
- if (signal?.aborted) {
- reject(abortError(signal));
- return;
+function ChatRows({ items, sessionId, roster, actions, useUi, clock: clock4 = false, onBtwDelete }) {
+ const selfId = roster.byId[sessionId]?.id;
+ const rows2 = [];
+ for (const item of items) {
+ const last = rows2.at(-1);
+ if (item.kind === "bot" && last?.kind === "bot") {
+ last.texts.push(item.text);
+ last.end = item.time;
+ } else rows2.push(item.kind === "bot" ? { kind: "bot", texts: [item.text], time: item.time, end: item.time } : item);
+ }
+ let before;
+ return rows2.flatMap((row, index) => {
+ const key = rows2.length - index;
+ const shown = chatRow(row, key, { sessionId, selfId, roster, actions, useUi, onBtwDelete });
+ if (row.kind === "divider") {
+ before = void 0;
+ return [shown];
}
- let gate = true;
- let off = () => {
- };
- const stop = () => {
- off();
- off = () => {
- };
- signal?.removeEventListener("abort", onAbort);
- };
- const finish = () => {
- const next = live.getSnapshot();
- if (!next?.ready) return;
- stop();
- resolve2(next);
- };
- const onAbort = () => {
- stop();
- reject(abortError(signal));
- };
- if (signal) signal.addEventListener("abort", onAbort, { once: true });
- off = live.subscribe(() => {
- if (!gate) finish();
- });
- gate = false;
- finish();
+ const pause = clock4 && Number.isFinite(row.time) && (before === void 0 || row.time - before >= SEPARATOR_GAP_MS);
+ if (Number.isFinite(row.end ?? row.time)) before = row.end ?? row.time;
+ return pause ? [(0, import_react30.createElement)("div", { key: `${key}:clock`, className: "bt-time-sep", role: "separator" }, clockLabel(row.time)), shown] : [shown];
});
}
-async function matchSideEnter(roster, sessionId, line, envelope, signal) {
- const parsed = parseSideLine(line);
- if (!parsed) return void 0;
- const snap = readRoster(roster)?.ready ? readRoster(roster) : await whenRosterReady(roster, signal);
- const surface = sideSurface(snap, sessionId);
- if (surface === "other") return void 0;
- if (surface === "group") throw new Error(t(GROUP_REFUSAL));
- if (surface !== "bot") throw new Error(t(LOADING_REFUSAL));
- if ((envelope?.attachments ?? 0) > 0) throw new Error(t(ATTACHMENT_REFUSAL));
- if (parsed.bare) throw new Error(t(EMPTY_REFUSAL));
- return { claim: true };
+function chatRow(row, key, { sessionId, selfId, roster, actions, useUi, onBtwDelete }) {
+ switch (row.kind) {
+ case "divider":
+ return (0, import_react30.createElement)(PartLine, { key, time: row.time });
+ case "user":
+ return (0, import_react30.createElement)(EarlierUser, { key, row, actions });
+ case "answer":
+ return (0, import_react30.createElement)(AnsweredReply, { key, node: { data: row } });
++ // A question or view card closed without an answer on it.
++ case "closed":
++ return row.view === void 0 ? (0, import_react30.createElement)("div", { key, className: "bt-q-inline" }, (0, import_react30.createElement)(SettledQuestion, { question: row.question, closed: row.closed })) : (0, import_react30.createElement)(ClosedView, { key, title: row.title, view: row.view, closed: row.closed });
+ // A display-only view replays from the blueprint the host kept on the call.
+ case "view":
+ return (0, import_react30.createElement)(WidgetCell, { key, sessionId, callId: row.callId, args: { text: (name) => name === "title" ? row.title : void 0, value: (name) => name === "view" ? row.view : void 0 }, done: true, isError: false, roster, actions });
+ case "bot": {
+ const bubbles = (0, import_react30.createElement)(Bubbles, { key, texts: row.texts, roster, selfId, actions, sessionId: useUi ? sessionId : void 0, msgKey: useUi ? `${sessionId}:${row.time}` : void 0, useUi, fold: FOLD_HUGE });
+ const speaker = layoutOf(roster.prefs) === "flat" ? roster.byId[selfId] : void 0;
+ return speaker ? (0, import_react30.createElement)(import_react30.Fragment, { key }, (0, import_react30.createElement)(SpeakerHead, { bot: speaker, time: row.time }), bubbles) : bubbles;
+ }
+ case "btw":
+ return (0, import_react30.createElement)(BtwCardView, { key, card: row.card, sessionId, actions, onDeleted: onBtwDelete });
+ case "post": {
+ const poster = roster.byId[row.botId] ?? { id: row.botId, name: row.name ?? t("a Bot"), color: "gray" };
+ return (0, import_react30.createElement)(GroupMessage, {
+ key,
+ bot: poster,
+ text: row.file ? stripLongNote(row.text) : row.text,
+ texts: row.texts,
+ room: roster.roomsById[sessionId],
+ roster,
+ actions,
+ msgKey: `${sessionId}:post:${row.seq ?? row.time}`,
+ time: row.time,
+ duration: row.duration,
+ whole: row.file ? { length: row.length, load: () => actions.fileText(row.file) } : void 0
+ });
+ }
+ case "relay": {
+ const reply = row.reply;
+ const speaker = roster.byId[reply.botId] ?? { id: reply.botId, name: reply.name ?? t("a Bot"), color: reply.color ?? "gray" };
+ return (0, import_react30.createElement)(RelayEvent, { key, reply, bot: speaker, sessionId, actions });
+ }
+ case "event": {
+ if (row.role === "report") return (0, import_react30.createElement)(GroupEvent, { key, prefix: t("Replies from"), room: roster.roomsById[row.roomId], name: t("a group chat"), roster, actions });
+ const other = roster.byId[row.botId] ?? { id: row.botId, name: row.name ?? t("a Bot"), color: "gray" };
+ const prefix = { stopped: t("Stopped by"), reply: t("Reply from") }[row.role] ?? t("Message from");
+ return (0, import_react30.createElement)(EventLine, { key, prefix, bots: [other], onOpen: () => {
+ if (selfId && other.id) actions.openExchange(selfId, other.id);
+ }, whole: true });
+ }
+ default:
+ return null;
+ }
}
-async function submitSide({ call: call2, roster, sessionId, args, attachments, open }) {
- const text = String(args ?? "").trim();
- if (sideSurface(roster, sessionId) === "group") throw new Error(t(GROUP_REFUSAL));
- if (Array.isArray(attachments) && attachments.length > 0) throw new Error(t(ATTACHMENT_REFUSAL));
- if (text === "") throw new Error(t(EMPTY_REFUSAL));
- const value = await call2("side-ask", { sessionId, recent: true, text });
- open?.(value?.chatId);
- return { kind: "success" };
+function TriggerCell({ node, sessionId, useRoster, useSessions, useTurnClock, useUi, actions }) {
+ const roster = useRoster((value) => value);
+ const data = node.data;
+ const source = data.source !== null && typeof data.source === "object" ? data.source : {};
+ const selfId = roster.byId[sessionId]?.id ?? sessionId;
+ const deferred = source.kind === "bot" && source.deferred === true;
+ const relayed = isRelayContext(data);
+ const turn = node.location?.turn?.turn ?? data.turn;
+ (0, import_react30.useLayoutEffect)(() => {
+ if (relayed) actions.noteTurnPeer(sessionId, turn, source.senderSessionId);
+ }, [relayed, sessionId, turn, source.senderSessionId]);
+ const order = useSessions((list) => {
+ const outline = list.projectionsBySession?.[sessionId]?.values?.turnOutline ?? list.byId[sessionId]?.projectionValues?.turnOutline;
+ return Array.isArray(outline) ? outline.map((entry) => entry.turn).join(",") : "";
+ });
+ const peers = useTurnClock((state) => {
+ if (!relayed) return "";
+ const turns = state[sessionId] ?? {};
+ return Object.keys(turns).filter((key) => turns[key].peer !== void 0).map((key) => `${key}:${turns[key].peer}`).join(",");
+ });
+ const visit = useUi((state) => state.visits?.[sessionId]);
+ const hiddenTurns = roster.exchangeTurns[sessionId];
+ const unreadOpening = useTurnClock((state) => {
+ const first = openingTurn(state[sessionId], order, hiddenTurns);
+ return first?.turn === turn && unseenSince(visit, first.start) ? clockLabel(first.start) : "";
+ });
+ const body = triggerBody();
+ return unreadOpening ? (0, import_react30.createElement)(import_react30.Fragment, null, (0, import_react30.createElement)("div", { className: "bt-open-new" }, (0, import_react30.createElement)(NewDivider), (0, import_react30.createElement)("div", { className: "bt-time-sep", role: "separator" }, unreadOpening)), body) : body ?? (0, import_react30.createElement)(CellEmpty);
+ function triggerBody() {
+ if (source.kind === "bot") {
+ if (source.handoff === true) return (0, import_react30.createElement)(EarlierParts, { sessionId, roster, actions });
+ if (source.role === "kickoff" || source.role === "room" || source.role === "goal") return null;
+ if (source.role === "secret" || deferred) return null;
+ if (source.role === "update") return (0, import_react30.createElement)("div", { className: "bt-event" }, t("Profile updated"));
+ if (source.role === "post") {
+ if (source.logged !== void 0) return null;
+ if (source.failed !== void 0 || source.resumed === true || source.stopped === true || source.done === true) return null;
+ const room2 = roster.roomsById[sessionId];
+ const poster = roster.byId[source.senderSessionId] ?? { id: source.senderSessionId, name: source.senderName ?? t("a Bot"), color: "gray" };
+ const file = source.length === void 0 ? void 0 : (data.content ?? []).find((block) => block?.type === "file")?.attachment;
+ const text = stripHeader(contentText(data.content));
+ return (0, import_react30.createElement)(GroupMessage, {
+ bot: poster,
+ text: file ? stripLongNote(text) : text,
+ room: room2,
+ roster,
+ actions,
+ msgKey: `${sessionId}:post:${data.seq ?? node.key}`,
+ useUi,
+ time: data.time,
+ whole: file ? { length: source.length, load: () => actions.fileText(file) } : void 0
+ });
+ }
+ if (source.role === "report") {
+ return (0, import_react30.createElement)(GroupEvent, { prefix: t("Replies from"), room: roster.roomsById[source.roomId], name: t("a group chat"), roster, actions });
+ }
+ if (source.role === "resume" || source.resumed === true) return (0, import_react30.createElement)("div", { className: "bt-event" }, t("Picked up its work after a restart"));
+ if (source.role === "retry" || source.retried === true) return (0, import_react30.createElement)("div", { className: "bt-event" }, t("Asked to make the tool call it wrote as text"));
+ if (source.role === "continue") return (0, import_react30.createElement)("div", { className: "bt-event" }, t("Went on after the failed turn"));
+ const run2 = relayed ? commRunOf(
+ order.split(",").filter(Boolean).map(Number),
+ Object.fromEntries(peers.split(",").filter(Boolean).map((pair) => [Number(pair.slice(0, pair.indexOf(":"))), pair.slice(pair.indexOf(":") + 1)])),
+ turn,
+ hiddenTurns
+ ) : null;
+ if (run2 === "folded") return null;
+ const sender = roster.byId[source.senderSessionId] ?? { id: source.senderSessionId, name: source.senderName ?? t("a Bot"), color: "gray" };
+ const count = run2?.count ?? (isHiddenTurn(roster, sessionId, turn) ? 2 : 1);
+ const bots = [sender];
+ for (const peer of (run2?.peerIds ?? []).map((id) => roster.byId[id]).filter(Boolean)) {
+ if (!bots.some((bot) => bot.id === peer.id)) bots.push(peer);
+ }
+ return (0, import_react30.createElement)(EventLine, {
+ prefix: source.role === "stopped" ? t("Stopped by") : count > 1 ? t("{count} messages with", { count }) : t("Message from"),
+ bots,
+ onOpen: (bot) => actions.openExchange(selfId, bot.id),
+ whole: true
+ });
+ }
+ if (source.kind === "schedule") {
+ const prompts = reminderPrompts(contentText(data.content));
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, prompts.length > 0 ? t("Scheduled task: {text}", { text: prompts.join(" · ").slice(0, 80) }) : t("Routine started"));
+ }
+ if (source.kind === "user-question-reply" || source.kind === "goal") return null;
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, contentText(data.content).slice(0, 80) || t("Update"));
+ }
}
-var panelHasStrip = (canBrowse, tabCount, sideCount) => canBrowse === true && tabCount > 0 || sideCount > 0;
-function stripMenuKeys({ canBrowse, canTerminal, canFiles }) {
- const keys = [];
- if (canBrowse === true) keys.push("new-tab");
- keys.push("side");
- const tail = [];
- if (canTerminal === true) tail.push("terminal");
- if (canFiles === true) tail.push("files");
- if (tail.length > 0) keys.push("sep");
- return [...keys, ...tail];
+function NewDivider() {
+ return (0, import_react30.createElement)("div", { className: "bt-new-sep", role: "separator", "aria-label": t("New messages") }, (0, import_react30.createElement)("span", null, t("New")));
}
-function drawerMenuKeys({ bot, room: room2, canBrowse, canTerminal, canFiles }) {
- const keys = [];
- if (bot === true && canBrowse === true) keys.push("browser");
- if (bot === true) keys.push("side");
- const tail = [];
- if (bot === true || room2 === true) {
- if (canTerminal === true) tail.push("terminal");
- if (canFiles === true) tail.push("files");
+function TurnProcessCell({ node, sessionId, turnProcess, useRoster, useUi, useTurnClock, actions }) {
+ const open = turnProcess === void 0 || !turnProcess.foldable || turnProcess.open;
+ (0, import_react30.useEffect)(() => {
+ if (!open) turnProcess.setOpen(true);
+ }, [open, turnProcess]);
+ const turn = node?.location?.turn?.turn ?? node?.data?.turn;
+ const start = node?.location?.turn?.start?.time;
+ const hidden = useRoster((roster) => isHiddenTurn(roster, sessionId, turn));
+ (0, import_react30.useEffect)(() => {
+ actions.noteTurnTime(sessionId, turn, "first", start);
+ }, [sessionId, turn, start]);
+ const visit = useUi((state) => state.visits?.[sessionId]);
+ const fresh = useTurnClock((state) => {
+ const own = state[sessionId]?.[turn];
+ return !hidden && typeof visit?.seen === "number" && own?.first !== void 0 && own.first <= visit.seen && own.end !== void 0 && own.end > visit.seen && own.end <= visit.entered;
+ });
+ return fresh ? (0, import_react30.createElement)(NewDivider) : (0, import_react30.createElement)(CellEmpty);
+}
+function Nothing() {
+ return null;
+}
+var SEPARATOR_GAP_MS = 30 * 60 * 1e3;
+function nextTurnStart(turns, turn) {
+ let next;
+ for (const key in turns) {
+ const candidate = Number(key);
+ if (candidate > turn && turns[key].first !== void 0 && (next === void 0 || candidate < next)) next = candidate;
}
- if (keys.length > 0 && tail.length > 0) keys.push("sep");
- return [...keys, ...tail];
+ return next === void 0 ? void 0 : turns[next].first;
}
-
-// src/client/side-chat.js
-var import_react26 = require("react");
-function SideEntry({ chatId, entry, actions }) {
- const [cancelling, setCancelling] = (0, import_react26.useState)(false);
- const question = typeof entry.question === "string" ? entry.question : "";
- const answer = typeof entry.answer === "string" ? entry.answer : "";
- const cancel = () => {
- if (cancelling || typeof actions?.cancelSide !== "function") return;
- setCancelling(true);
- Promise.resolve(actions.cancelSide(chatId, entry.id)).catch(() => {
- }).finally(() => setCancelling(false));
- };
- return (0, import_react26.createElement)(
- "div",
- { className: "bt-side-pair", "data-status": entry.status },
- (0, import_react26.createElement)("div", { className: "bt-side-qrow" }, (0, import_react26.createElement)("div", { className: "bt-side-q" }, question)),
- entry.status === "answering" ? (0, import_react26.createElement)(
- "div",
- { className: "bt-side-a" },
- (0, import_react26.createElement)("span", { className: "bt-shimmer" }, t("Answering…")),
- (0, import_react26.createElement)("button", {
- type: "button",
- className: "bt-soft bt-soft-sm",
- disabled: cancelling,
- title: t("Cancel this side question"),
- "aria-label": t("Cancel this side question"),
- onClick: cancel
- }, t("Cancel"))
- ) : (0, import_react26.createElement)(
- "div",
- { className: "bt-side-a" },
- entry.status === "cancelled" ? (0, import_react26.createElement)("p", { className: "bt-side-status" }, t("Cancelled")) : null,
- entry.status === "failed" ? (0, import_react26.createElement)("p", { className: "bt-side-fail" }, failureText(entry)) : null,
- answer !== "" ? (0, import_react26.createElement)(import_dsh_client_ui_primitives.MarkdownText, { text: answer, labels: mdLabels2(), variant: "compact" }) : null
- )
- );
+function openingTurn(turns, firstTurns, hiddenTurns) {
+ if (!turns || !firstTurns) return null;
+ const start = nextTurnStart(turns, -Infinity);
+ if (start === void 0) return null;
+ const turn = Number(Object.keys(turns).filter((key) => turns[key].first === start)[0]);
+ const listed = firstTurns.split(",").map(Number);
+ const earlier = listed.filter((entry) => entry < turn);
+ return listed.includes(turn) && earlier.every((entry) => hiddenTurns?.includes(entry)) ? { turn, start } : null;
}
-function SideChatView({ subject, chat, roster, actions }) {
- const scroll = (0, import_react26.useRef)(null);
- const [draft, setDraft] = (0, import_react26.useState)("");
- const [fail2, setFail] = (0, import_react26.useState)(null);
- const entries2 = Array.isArray(chat?.entries) ? chat.entries : [];
- const busy = entries2.some((entry) => entry?.status === "answering");
- const last = entries2.at(-1);
- (0, import_react26.useEffect)(() => {
- const node = scroll.current;
- if (node) node.scrollTop = node.scrollHeight;
- }, [chat?.id, entries2.length, last?.status]);
- if (!chat) return null;
- const ask = () => {
- const text = draft.trim();
- if (text === "" || busy || typeof actions?.askSide !== "function") return;
- setDraft("");
- setFail(null);
- Promise.resolve(actions.askSide(subject, chat.id, text)).catch((error) => {
- setDraft((value) => value === "" ? text : value);
- setFail(hostText(error?.message ?? ""));
- });
- };
- return (0, import_react26.createElement)(
- "div",
- { className: "bt-side" },
- (0, import_react26.createElement)("p", { className: "bt-side-note" }, t("Answered from progress so far; nothing was run")),
- (0, import_react26.createElement)(
- "div",
- { className: "bt-side-scroll", ref: scroll },
- entries2.map((entry) => (0, import_react26.createElement)(SideEntry, { key: entry.id, chatId: chat.id, entry, actions }))
- ),
- (0, import_react26.createElement)(
- "div",
- { className: "bt-side-form" },
- (0, import_react26.createElement)("textarea", {
- className: "bt-side-input",
- rows: 1,
- value: draft,
- disabled: busy,
- placeholder: t("Ask about the work so far"),
- "aria-label": t("Ask about the work so far"),
- onChange: (event) => {
- setDraft(event.target.value);
- if (fail2 !== null) setFail(null);
- },
- onKeyDown: (event) => {
- if (event.key !== "Enter" || !sendsOnEnter(roster?.prefs) || event.shiftKey || event.nativeEvent?.isComposing) return;
- event.preventDefault();
- ask();
- }
- }),
- // With Enter sending off this is the only way to ask; on, it sends the same.
- (0, import_react26.createElement)("button", {
- type: "button",
- className: "bt-side-send",
- "aria-label": t("Send message"),
- disabled: busy || draft.trim() === "" || typeof actions?.askSide !== "function",
- onClick: ask
- }, (0, import_react26.createElement)(ArrowUpIcon)),
- fail2 !== null ? (0, import_react26.createElement)("p", { className: "bt-side-fail" }, fail2) : null
- )
+var unseenSince = (visit, time) => typeof visit?.seen === "number" && time > visit.seen && time <= visit.entered;
+function TurnTailCell({ turn: location2, sessionId, useTurnClock, useUi, actions }) {
+ const turn = location2.turn;
+ const time = location2.end.time;
+ (0, import_react30.useEffect)(() => {
+ actions.noteTurnTime(sessionId, turn, "end", time);
+ }, [sessionId, turn, time]);
+ const label = useTurnClock((state) => {
+ const start = nextTurnStart(state[sessionId] ?? {}, turn);
+ return start !== void 0 && start - time >= SEPARATOR_GAP_MS ? clockLabel(start) : "";
+ });
+ const visit = useUi((state) => state.visits?.[sessionId]);
+ const fresh = useTurnClock((state) => {
+ if (typeof visit?.seen !== "number" || time > visit.seen) return false;
+ const start = nextTurnStart(state[sessionId] ?? {}, turn);
+ return start !== void 0 && start > visit.seen && start <= visit.entered;
+ });
+ if (!label && !fresh) return null;
+ return (0, import_react30.createElement)(
+ import_react30.Fragment,
+ null,
+ label ? (0, import_react30.createElement)("div", { className: "bt-time-sep", role: "separator" }, label) : null,
+ fresh ? (0, import_react30.createElement)(NewDivider) : null
);
}
-function sideSource({ roster, actions }) {
- const claimFor = (sessionId) => ({
- name: "side",
- token: SIDE_TOKEN,
- hint: t("Ask about the work so far"),
- submit: (args, actx, attachments) => {
- void actx;
- return submitSide({
- call: actions?.sideCall ?? call,
- roster: roster.getSnapshot(),
- sessionId,
- args,
- attachments,
- open: (chatId) => actions?.openSideChat(sessionId, chatId)
- });
- }
- });
- return {
- trigger: "/",
- name: SIDE_SOURCE,
- order: -50,
- showGroupTitle: false,
- async candidates(session, req) {
- if (req?.position === "inline") return [];
- if (sideSurface(roster.getSnapshot(), session.sessionId) !== "bot") return [];
- if (!sideQueryMatches(req?.query)) return [];
- return [{ name: "side", description: t("Ask without interrupting"), value: "side" }];
- },
- onPick(pick2) {
- if (pick2?.action === "drill") return void 0;
- if (sideSurface(roster.getSnapshot(), pick2.session.sessionId) !== "bot") return void 0;
- return { claim: claimFor(pick2.session.sessionId) };
- },
- matchSpace(session, token) {
- const outcome = matchSideSpace(roster.getSnapshot(), session.sessionId, token);
- return outcome === void 0 ? void 0 : { claim: claimFor(session.sessionId) };
- },
- matchEnter(session, line, signal, envelope) {
- return matchSideEnter(roster, session.sessionId, line, envelope, signal).then((outcome) => {
- if (outcome === void 0) return void 0;
- return { claim: claimFor(session.sessionId) };
- });
- },
- async matchClaim(session, token) {
- return matchSideClaim(roster.getSnapshot(), session.sessionId, token) ? claimFor(session.sessionId) : void 0;
- }
- };
+function Shimmer({ children }) {
+ return (0, import_react30.createElement)("span", { className: "bt-shimmer" }, children);
}
-var SIDE_CSS = `
-.bt-side{flex:1;min-height:0;display:flex;flex-direction:column;animation:bt-panel-view-in .22s cubic-bezier(.16,1,.3,1)}
-.bt-side-note{flex:none;margin:0;padding:10px 16px 8px;font-size:12px;line-height:17px;color:var(--bt-ink-3);border-bottom:.5px solid var(--bt-line)}
-.bt-side-scroll{flex:1;min-height:0;overflow-y:auto;display:flex;flex-direction:column;gap:14px;padding:14px 16px}
-.bt-side-pair{display:flex;flex-direction:column;gap:8px}
-.bt-side-qrow{display:flex;justify-content:flex-end}
-.bt-side-q{max-width:85%;padding:7px 12px;border-radius:18px;background:var(--bt-user);color:var(--bt-user-ink);font-size:13px;line-height:19px;box-sizing:border-box;overflow-wrap:anywhere;white-space:pre-wrap}
-.bt-side-a{display:flex;flex-direction:column;gap:8px;align-items:flex-start;font-size:13px;line-height:19px;color:var(--bt-ink)}
-.bt-side-status{margin:0;font-size:12px;color:var(--bt-ink-3)}
-.bt-side-fail{margin:0;font-size:12px;line-height:17px;color:var(--bt-danger)}
-.bt-side-form{flex:none;padding:10px 14px 14px;border-top:.5px solid var(--bt-line);display:flex;flex-wrap:wrap;align-items:flex-end;gap:8px}
-.bt-side-form>.bt-side-fail{flex-basis:100%}
-.bt-side-send{width:36px;height:36px;border-radius:50%;border:0;background:var(--bt-accent);color:var(--bt-accent-ink);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;flex:none}
-.bt-side-send:disabled{opacity:.3;cursor:default}
-.bt-side-input{display:block;flex:1;min-width:0;box-sizing:border-box;min-height:36px;max-height:120px;padding:8px 12px;border:.5px solid var(--bt-line-2);border-radius:12px;background:var(--bt-main);color:var(--bt-ink);font:inherit;font-size:13px;line-height:19px;resize:none;outline:none;field-sizing:content}
-.bt-side-input::placeholder{color:var(--bt-ink-3)}
-.bt-side-input:focus{border-color:var(--bt-accent)}
-.bt-side-input:disabled{opacity:.6}
-.bt-pmenu{position:relative;display:inline-flex;flex:none}
-.bt-pmenu-pop{position:absolute;top:calc(100% + 6px);right:0;z-index:6;min-width:172px;padding:6px;border-radius:12px;background:var(--bt-glass-bg);-webkit-backdrop-filter:blur(24px) saturate(180%);backdrop-filter:blur(24px) saturate(180%);border:.5px solid var(--bt-glass-rim);box-shadow:var(--bt-glass-shadow);display:flex;flex-direction:column;gap:2px;transform-origin:top right;animation:bt-pop-drop .18s cubic-bezier(.16,1,.3,1),bt-fade .14s ease-out}
-.bt-pmenu-pop[data-leaving]{animation:bt-pop-out .12s cubic-bezier(.4,0,1,1) forwards;pointer-events:none}
-.bt-pmenu-item{display:flex;align-items:center;gap:9px;width:100%;min-width:0;padding:7px 10px;border:0;border-radius:8px;background:none;color:var(--bt-ink);font:inherit;font-size:12px;line-height:17px;text-align:left;cursor:pointer}
-.bt-pmenu-item:hover{background:var(--bt-hover)}
-.bt-pmenu-item:focus-visible{outline:2px solid var(--bt-accent);outline-offset:-2px}
-.bt-pmenu-item svg{flex:none;width:15px;height:15px;color:var(--bt-ink-3)}
-.bt-pmenu-sep{height:.5px;flex:none;margin:4px 8px;background:var(--bt-line-2)}
-`;
-
-// 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 Elapsed({ at, className }) {
+ const [now, setNow] = (0, import_react30.useState)(Date.now);
+ (0, import_react30.useEffect)(() => {
+ let timer = 0;
+ const tick = () => {
+ const time = Date.now();
+ setNow(time);
+ timer = setTimeout(tick, 1e3 - ((time - at) % 1e3 + 1e3) % 1e3);
+ };
+ tick();
+ return () => clearTimeout(timer);
+ }, [at]);
+ return (0, import_react30.createElement)("span", { className }, `· ${elapsedLabel(Math.max(1e3, now - at))}`);
+}
+var PHRASES = {
+ thinking: ["Thinking about it", "Weighing the options", "Working out a plan", "Sorting out the details"],
+ working: ["On it", "Busy with it", "Moving ahead", "Taking care of it", "Making headway"]
+};
+var TOOL_PHRASES = [
+ [/^cua(_driver_native__|$)|^computer_/, "Using the computer"],
+ [/web_?search|search_?web/i, "Searching online"],
+ [/fetch|browse|browser|web/i, "Reading a page"],
+ [/shell|bash|pwsh|powershell|exec|command|terminal/i, "Running shell commands"],
+ [/^(read|view|cat)\b|read_/i, "Opening a file"],
+ [/grep|glob|list_dir|^ls$|find|search/i, "Looking through files"],
+ [/write|edit|patch|apply|replace/i, "Writing changes"],
+ [/image|photo|draw/i, "Working on an image"]
+];
+var GROUP_PHRASES = { create_group: "Creating a group", update_group: "Updating the group", delete_group: "Deleting the group", post_to_group: "Posting in the group" };
+function toolActivity(name, arg, findBot, self) {
+ switch (name) {
+ case "ask_user":
+ return null;
+ case "request_secret":
+ return null;
+ case "list_secrets":
+ return { label: t("Checking the keys"), state: "searching" };
+ case "ask_user_question":
+ return { label: t("Waiting for your answer"), state: "alert" };
+ case "group_relay":
+ return { relay: true, state: "orbit" };
+ case "message_bot": {
+ const target = findBot(arg("to"));
+ return { label: target ? t("Asking {name}", { name: target.name }) : t("Asking another Bot"), state: "sending" };
+ }
+ case "stop_bot": {
+ const target = findBot(arg("bot"));
+ return { label: target ? t("Stopping {name}", { name: target.name }) : t("Stopping another Bot"), state: "sending" };
+ }
+ case "create_bot":
+ return { label: t("Creating {name}", { name: arg("name") ?? t("a Bot") }), state: "sending" };
+ case "update_bot": {
+ const target = findBot(arg("name")) ?? findBot(arg("bot")) ?? (arg("bot") ? void 0 : self);
+ return { label: t("Updating {name}", { name: target?.name ?? t("a Bot") }), state: "sending" };
+ }
+ case "list_bots":
+ return { label: t("Checking the team"), state: "searching" };
+ case "read_group_chat":
+ return { label: t("Reading {name}", { name: arg("group") ?? t("a group chat") }), state: "searching" };
+ case "read_own_chat":
+ return { label: t("Looking back through the chat"), state: "searching" };
+ case "remember":
+ return { label: t("Saving to memory"), state: "working" };
+ case "forget":
+ return { label: t("Updating memory"), state: "working" };
+ case "recall":
+ return { label: t("Checking memory"), state: "searching" };
+ default:
+ if (GROUP_PHRASES[name]) return { label: t(GROUP_PHRASES[name]), state: "sending" };
+ const phrase = TOOL_PHRASES.find(([pattern]) => pattern.test(name))?.[1];
+ return { label: phrase ? t(phrase) : null, state: toolState(name) };
+ }
}
-async function requestPreparation(speech, providerId) {
- try {
- const result = await speech.prepare(providerId);
- return result?.ok !== false;
- } catch {
- return false;
+function workPhrase(doing) {
+ const { tool, said, note, target, switching, folder } = typeof doing === "string" ? { tool: doing } : doing ?? {};
+ if (switching) return folder === true ? t("Switching working folder") : t("Moving to a fresh conversation");
+ const own = (said || note)?.replace(/[\s.。…]+$/u, "");
+ if (own) return own;
+ if (!tool) return t("Thinking about it");
+ const label = toolActivity(tool, () => void 0, () => void 0)?.label ?? t("On it");
+ return target ? `${label} · ${target}` : label;
+}
+function useLiveNote(actions, sessionId, id, entry) {
+ const key = entry ? JSON.stringify(entry) : "";
+ (0, import_react30.useEffect)(() => {
+ if (!key) return void 0;
+ actions.noteLive(sessionId, id, JSON.parse(key));
+ return () => actions.noteLive(sessionId, id, null);
+ }, [sessionId, id, key]);
+}
+function RelayEvent({ reply, bot, sessionId, actions }) {
+ if (reply.kind === "failed") {
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-event bt-event-error", role: "status", title: [reply.code, reply.status, reply.text].filter(Boolean).join(" · ") },
+ t("{name} could not answer: {reason}", { name: bot.name, reason: failureLabel(reply.code, reply.text) })
+ );
+ }
+ if (reply.kind === "lookup") {
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-event" },
+ reply.text ? t("{name} looked up its own chat for “{text}”", { name: bot.name, text: reply.text }) : t("{name} looked up its own chat", { name: bot.name })
+ );
+ }
+ if (reply.kind === "missed") {
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, t("{name} didn't answer in time", { name: bot.name }));
+ }
+ if (reply.kind === "admin-passed") {
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-event" },
+ t("{name} did not answer or call anyone; call a member with @Name", { name: bot.name })
+ );
+ }
+ if (reply.kind === "paused") {
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, reply.idle ? t("{names} went back and forth {count} times without progress and paused. Write here to go on", { count: reply.count, names: [bot.name, ...reply.names ?? []].join(t(" and ")) }) : t("Paused after {count} Bot relays. Waiting: {names}", { count: reply.count, names: (reply.names ?? []).join(t(" and ")) }));
+ }
+ if (reply.kind === "resumed") {
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, t("{name} was cut off by a restart and picked its work back up", { name: bot.name }));
+ }
+ if (reply.kind === "cut") {
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, t("{name} was cut off by a restart again and stopped", { name: bot.name }));
+ }
+ if (reply.kind === "approval" || reply.kind === "working") {
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-event" },
+ (0, import_react30.createElement)(
+ "button",
+ { type: "button", className: "bt-event-whole", onClick: () => actions.showDetails(sessionId) },
+ (0, import_react30.createElement)(BotMark, { bot, size: 16 }),
+ (0, import_react30.createElement)("span", { className: "bt-event-name" }, t(reply.kind === "working" ? "{name} started on it" : "{name} paused for your approval", { name: bot.name }))
+ )
+ );
+ }
+ if (reply.kind === "folder") {
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, reply.text);
+ }
+ if (reply.kind === "stopped") {
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, t("You stopped {name}'s work", { name: bot.name }));
+ }
+ if (reply.kind === "done") {
+ return (0, import_react30.createElement)("div", { className: "bt-event" }, t("{name} finished its work", { name: bot.name }));
}
+ return null;
}
-function preparationStep(catalog) {
- const preparation = catalog.providers.find((item) => item.id === catalog.selection.providerId)?.preparation;
- if (preparation === void 0) return { state: "done", failed: false };
- if (USABLE.has(preparation.phase)) return { state: "usable" };
- if (preparation.phase === "failed" || preparation.phase === "cancelled" || preparation.phase === "unprepared") {
- return { state: "done", failed: preparation.phase === "failed" };
+function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi, useWork }) {
+ const [live, setLive] = (0, import_react30.useState)({ replies: [], speaking: [] });
+ (0, import_react30.useEffect)(() => {
+ if (done) return void 0;
+ let stop = false;
+ let timer;
+ let seen = "";
+ const tick = async () => {
+ const result = await actions.roomProgress(sessionId);
+ if (stop) return;
+ const entry = (result ?? []).find((item) => item.callId === callId) ?? (result ?? [])[0];
+ const key = entry ? JSON.stringify([entry.replies, entry.speaking]) : "";
+ if (entry && key !== seen) {
+ seen = key;
+ setLive({ replies: entry.replies ?? [], speaking: [entry.speaking ?? []].flat() });
+ }
+ timer = setTimeout(tick, document.hidden ? 5e3 : 1e3);
+ };
+ void tick();
+ return () => {
+ stop = true;
+ clearTimeout(timer);
+ };
+ }, [done, sessionId, callId]);
+ let replies = live.replies;
+ let broken = false;
+ if (done) {
+ const parsed = parseReplies(contentText(content));
+ replies = parsed.replies.length ? parsed.replies : live.replies;
+ broken = parsed.broken;
}
- const pct = preparation.phase === "downloading" && preparation.totalBytes ? Math.floor(preparation.completedBytes / preparation.totalBytes * 100) : void 0;
- return { state: "waiting", pct };
+ const pending = done ? [] : live.speaking;
+ const doing = JSON.parse(useWork?.((work) => JSON.stringify(pending.map((id) => {
+ const tool = work.bots?.[id]?.tool;
+ return tool ? [tool, workPhrase(work.bots[id])] : [];
+ }))) ?? "[]");
+ if (replies.length === 0 && pending.length === 0) {
+ return broken ? (0, import_react30.createElement)("div", { className: "bt-group-replies" }, (0, import_react30.createElement)("div", { className: "bt-event" }, t("The group replies could not be shown"))) : (0, import_react30.createElement)(CellEmpty);
+ }
+ const room2 = roster.roomsById[sessionId];
+ return (0, import_react30.createElement)(
+ "div",
+ { className: "bt-group-replies" },
+ stackReplies(replies).map(({ reply, index, texts: texts2, time, duration }) => {
+ const bot = roster.byId[reply.botId] ?? { id: reply.botId, name: reply.name, color: reply.color ?? "gray" };
+ if (reply.kind === "user") {
+ return (0, import_react30.createElement)(
+ "div",
+ { key: `user-${index}`, className: "bt-urow" },
+ (0, import_react30.createElement)("div", { className: "bt-ububble" }, (0, import_react30.createElement)(import_dsh_client_ui_primitives.MarkdownText, { text: reply.text, labels: mdLabels3(), variant: "compact" })),
+ reply.via !== void 0 || Number.isFinite(time) ? (0, import_react30.createElement)("div", { className: "bt-utime", title: clockLabel(time) }, ...reply.via !== void 0 ? [(0, import_react30.createElement)(ViaTag, { key: "via", via: reply.via })] : [], Number.isFinite(time) ? messageClock(time) : null) : null
+ );
+ }
+ if (reply.kind !== void 0) {
+ return (0, import_react30.createElement)(RelayEvent, { key: `${reply.botId ?? reply.kind}-${index}`, reply, bot, sessionId, actions });
+ }
+ if (reply.kind === "goal") {
+ return (0, import_react30.createElement)(
+ "div",
+ { key: `goal-${index}`, className: "bt-event", title: reply.text || void 0 },
+ (0, import_react30.createElement)("span", { className: "bt-event-ico", "aria-hidden": true }, (0, import_react30.createElement)(GoalIcon)),
+ goalEventText(reply)
+ );
+ }
+ return (0, import_react30.createElement)(GroupMessage, { key: `${reply.botId}-${index}`, bot, texts: texts2, room: room2, roster, actions, msgKey: callId ? `${sessionId}:${callId}:${index}` : void 0, useUi, time, duration });
+ }),
+ pending.map((id, at) => {
+ const bot = roster.byId[id];
+ if (!bot) return null;
+ const [tool, phrase] = doing[at] ?? [];
+ return (0, import_react30.createElement)(
+ "div",
+ { key: `pending-${id}`, className: "bt-activity" },
+ (0, import_react30.createElement)(BotMark, { bot, size: 22, state: tool ? toolState(tool) : "thinking" }),
+ (0, import_react30.createElement)(Shimmer, null, phrase ? `${bot.name} · ${phrase}…` : t("{name} is typing…", { name: bot.name }))
+ );
+ })
+ );
}
-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);
+var isComputerCall = (name) => name === "cua" || name?.startsWith("cua_driver_native__") === true;
+var DRAWN = /* @__PURE__ */ new Set(["message_bot", "stop_bot", "create_bot", "update_bot", "group_relay", "create_group", "update_group", "delete_group", "post_to_group", "ask_user", "request_secret", "request_connector", "mail_send", "ask_user_question", "show_view", "browser_handoff", "read_group_chat", "remember", "forget"]);
+var CARDS = /* @__PURE__ */ new Set(["ask_user", "request_secret", "request_connector", "mail_send", "show_view", "browser_handoff", "computer_handoff"]);
+function callTree(root) {
+ const calls = [];
+ const seen = /* @__PURE__ */ new Set();
+ const visit = (call2) => {
+ const id = call2.callId ?? call2;
+ if (seen.has(id)) return;
+ seen.add(id);
+ calls.push(call2);
+ for (const child of call2.subCalls ?? []) visit(child);
};
- 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;
+ visit(root);
+ return calls;
+}
+function useShownCards(actions, sessionId, callIds) {
+ const key = JSON.stringify(callIds);
+ (0, import_react30.useLayoutEffect)(() => {
+ const ids = JSON.parse(key);
+ if (ids.length === 0 || !actions.noteCards) return void 0;
+ actions.noteCards(sessionId, ids, 1);
+ return () => actions.noteCards(sessionId, ids, -1);
+ }, [sessionId, key]);
+}
+function renderCall(call2, { sessionId, roster, actions, useUi, useWork, findBot, heldCards, hooks }) {
+ const tool = toolName(call2);
+ const done = call2.kind === "tool-result";
+ const { text: arg, value: argValue } = toolArgs(call2);
+ const self = roster.byId[sessionId];
+ switch (tool) {
+ case "message_bot": {
+ const target = findBot(arg("to")) ?? { name: arg("to") ?? "…", color: "gray" };
+ if (done && call2.isError) return (0, import_react30.createElement)("div", { className: "bt-event" }, t("Couldn't message {name}", { name: target.name }));
+ return (0, import_react30.createElement)(EventLine, { prefix: t("Messaged"), bots: [target], onOpen: (bot) => bot.id && actions.openExchange(self?.id ?? sessionId, bot.id), whole: true });
+ }
+ case "stop_bot": {
+ const target = findBot(arg("bot")) ?? { name: arg("bot") ?? "…", color: "gray" };
+ if (done && call2.isError) return (0, import_react30.createElement)("div", { className: "bt-event" }, t("Couldn't stop {name}", { name: target.name }));
+ return (0, import_react30.createElement)(EventLine, { prefix: t("Stopped"), bots: [target], onOpen: (bot) => bot.id && actions.openExchange(self?.id ?? sessionId, bot.id), whole: true });
+ }
+ case "create_bot": {
+ const created = findBot(arg("name"));
+ if (!done || created === void 0) return (0, import_react30.createElement)(CellEmpty);
+ return (0, import_react30.createElement)(EventLine, { prefix: t("Created"), bots: [created], onOpen: (bot) => actions.openSession(bot.id) });
+ }
+ case "update_bot": {
+ const target = findBot(arg("name")) ?? findBot(arg("bot")) ?? (arg("bot") ? void 0 : self);
+ return done && target ? (0, import_react30.createElement)(EventLine, { prefix: t("Updated"), bots: [target], onOpen: (bot) => actions.openSession(bot.id) }) : (0, import_react30.createElement)(CellEmpty);
+ }
+ case "group_relay":
+ return (0, import_react30.createElement)(GroupReplies, { sessionId, callId: call2.callId, done, content: call2.content, roster, actions, useUi, useWork });
+ case "create_group":
+ case "update_group":
+ case "delete_group":
+ case "post_to_group": {
+ const verbs = {
+ create_group: ["Created group", "Couldn't create the group"],
+ update_group: ["Updated group", "Couldn't update the group"],
+ delete_group: ["Deleted group", "Couldn't delete the group"],
+ post_to_group: ["Posted in", "Couldn't post in the group"]
+ }[tool];
+ if (!done) return (0, import_react30.createElement)(CellEmpty);
+ const result = contentText(call2.content);
+ const named = /^(Created group|Updated|Nothing changed in|Deleted|Posted in) "([^"]+)"/.exec(result);
+ if (call2.isError || !named) return (0, import_react30.createElement)("div", { className: "bt-event", title: result }, t(verbs[1]));
+ const name = named[2];
+ const room2 = roster.rooms.find((entry) => entry.name === name);
+ return (0, import_react30.createElement)(GroupEvent, { prefix: t(verbs[0]), room: tool === "delete_group" ? void 0 : room2, name, roster, actions });
+ }
+ case "ask_user": {
+ const question = roster.questions?.[sessionId];
- if (!question || question.callId !== call2.callId) return (0, import_react30.createElement)(CellEmpty, { className: "bt-q-gone" });
++ if (!question || question.callId !== call2.callId) {
++ const closed = roster.closedCards?.[sessionId]?.[call2.callId];
++ if (closed === void 0) return (0, import_react30.createElement)(CellEmpty, { className: "bt-q-gone" });
++ const asked = { question: arg("question") ?? "", detail: arg("detail"), options: argValue("options") ?? [], multiSelect: argValue("multiSelect") === true };
++ return (0, import_react30.createElement)("div", { className: "bt-q-inline" }, (0, import_react30.createElement)(SettledQuestion, { question: asked, closed }));
++ }
+ if (heldCards?.[heldCardKey("question", question.id)] > 0) return (0, import_react30.createElement)(CellEmpty);
+ return (0, import_react30.createElement)(PendingQuestion, { key: JSON.stringify([sessionId, question.id]), sessionId, question, actions, inline: true, enterToSend: sendsOnEnter(roster.prefs) });
+ }
+ case "show_view":
+ return (0, import_react30.createElement)(WidgetCell, { sessionId, callId: call2.callId, args: { text: arg, value: argValue }, done, isError: call2.isError, roster, actions, heldCards });
+ case "request_secret":
+ return (0, import_react30.createElement)(SecretToolCell, { sessionId, callId: call2.callId, name: arg("name"), done, content: call2.content, roster, actions, heldCards });
+ case "request_connector":
+ return (0, import_react30.createElement)(ConnectorToolCell, { sessionId, callId: call2.callId, done, content: call2.content, roster, actions, heldCards });
+ case "mail_send":
+ return (0, import_react30.createElement)(MailToolCell, { sessionId, callId: call2.callId, done, content: call2.content, roster, actions, heldCards });
+ case "browser_handoff":
+ return (0, import_react30.createElement)(HandoffCall, { sessionId, callId: call2.callId, roster, actions, heldCards, hooks });
+ case "computer_handoff":
+ return (0, import_react30.createElement)(ComputerHandoffCall, { sessionId, callId: call2.callId, roster, actions, heldCards, hooks });
+ case "ask_user_question": {
+ if (!done) return (0, import_react30.createElement)(CellEmpty);
+ let parsed = null;
+ try {
+ parsed = JSON.parse(contentText(call2.content));
+ } catch {
+ parsed = null;
+ }
+ const answer = parsed?.answers?.[0];
+ const question = argValue("questions")?.[0];
+ if (!answer) return (0, import_react30.createElement)(CellEmpty);
+ return (0, import_react30.createElement)("div", { className: "bt-q-inline" }, (0, import_react30.createElement)(SettledQuestion, { question, answer }));
+ }
+ case "read_group_chat": {
+ if (!done) return (0, import_react30.createElement)(CellEmpty);
+ const room2 = roster.rooms.find((entry) => entry.name === arg("group"));
+ return room2 ? (0, import_react30.createElement)(GroupEvent, { prefix: t("Read"), room: room2, roster, actions }) : (0, import_react30.createElement)(CellEmpty);
+ }
+ case "remember":
+ case "forget":
+ return done ? (0, import_react30.createElement)(MemoryEvent, { sessionId, scope: arg("scope"), tool, result: contentText(call2.content), failed: call2.isError === true, code: call2.error?.code, roster, actions, findBot }) : (0, import_react30.createElement)(CellEmpty);
+ default:
+ if (isComputerCall(tool)) {
+ return (0, import_react30.createElement)(
+ import_react30.Fragment,
+ null,
+ (0, import_react30.createElement)(ComputerCallRow, { sessionId, call: call2, roster, actions, hooks }),
+ (0, import_react30.createElement)(AppAccessCall, { sessionId, callId: call2.callId, roster, actions, heldCards, hooks })
+ );
+ }
+ return (0, import_react30.createElement)(CellEmpty);
+ }
}
-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);
+function ToolCell({ node, sessionId, useRoster, useUi, useWork, useHeldCards, useBrowserHolds, useBrowserTabs, useBrowserPages, useComputer, actions }) {
+ const roster = useRoster((value) => value);
+ const heldCards = useHeldCards?.((state) => state[sessionId]);
+ const root = node.data.root;
+ const turn = node.location?.turn?.turn ?? root.turn;
+ const hidden = isHiddenTurn(roster, sessionId, turn);
+ const findBot = (nameOrId) => roster.byId[nameOrId] ?? roster.bots.find((bot) => bot.name.toLowerCase() === String(nameOrId ?? "").toLowerCase());
+ const calls = hidden ? [] : callTree(root);
+ const drawn = calls.filter((call2) => DRAWN.has(toolName(call2)) || isComputerCall(toolName(call2)));
+ const running = root.kind === "tool-result" ? void 0 : calls.findLast((call2) => call2.kind !== "tool-result");
+ const note = running ? toolActivity(toolName(running), toolArgs(running).text, findBot, roster.byId[sessionId]) : null;
+ useLiveNote(actions, sessionId, `tool:${root.callId ?? node.key}`, note);
+ useShownCards(actions, sessionId, drawn.filter((call2) => (CARDS.has(toolName(call2)) || isComputerCall(toolName(call2))) && call2.callId).map((call2) => call2.callId));
+ if (drawn.length === 0) return (0, import_react30.createElement)(CellEmpty);
+ const env = { sessionId, roster, actions, useUi, useWork, findBot, heldCards, hooks: { useBrowserHolds, useBrowserTabs, useBrowserPages, useComputer } };
+ return (0, import_react30.createElement)(import_react30.Fragment, null, drawn.map((call2, index) => (0, import_react30.createElement)(import_react30.Fragment, { key: call2.callId ?? index }, renderCall(call2, env))));
}
-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);
+
+// src/client/activity-row.js
+var import_react31 = require("react");
+var import_react_dom4 = require("react-dom");
+var PHRASE_HOLD_MS = 800;
+var drawPhrase = (pool) => t(pool[Math.min(pool.length - 1, Math.floor(Math.random() * pool.length))]);
+var rowVisible = ({ running, streaming, tools, relaying, bot, room: room2 }) => running && (!streaming || tools.length > 0) && !relaying && (bot !== void 0 || room2 !== void 0);
+var freshInputAt = (submissions, steeredAt) => Math.max(
+ 0,
+ steeredAt ?? 0,
+ ...(submissions ?? []).filter((sub) => sub.placement !== "queued").map((sub) => sub.time)
+);
+var mountMissed = false;
+function findHost() {
+ const node = document.querySelector("[data-chat-flow] [data-chat-running]") ?? document.querySelector("[data-chat-flow]");
+ if (node === null && !mountMissed) {
+ mountMissed = true;
+ noteClientError("activity row", new Error("[data-chat-flow] not found"));
}
- 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 node;
+}
+function useRunningHost(active) {
+ const [host, setHost] = (0, import_react31.useState)(null);
+ (0, import_react31.useEffect)(() => {
+ if (!active) {
+ setHost(null);
+ return void 0;
+ }
+ let frame = 0;
+ const find = () => {
+ frame = 0;
+ setHost((prev) => {
+ const node = findHost();
+ return prev === node ? prev : node;
+ });
+ };
+ const observer = new MutationObserver(() => {
+ if (!frame) frame = requestAnimationFrame(find);
});
- };
- 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;
+ observer.observe(document.querySelector("[data-conversation-scroll]") ?? document.body, { childList: true, subtree: true });
+ find();
+ return () => {
+ cancelAnimationFrame(frame);
+ observer.disconnect();
+ };
+ }, [active]);
+ return host;
+}
+function useRowEntrances(replacing) {
+ const check = (0, import_react31.useRef)(replacing);
+ check.current = replacing;
+ (0, import_react31.useEffect)(() => {
+ const seen = /* @__PURE__ */ new WeakSet();
+ const started = Date.now();
+ let column = null;
+ let frame = 0;
+ const settle = (event) => {
+ if (event.target !== event.currentTarget || !/^bt-row/.test(event.animationName)) return;
+ delete event.currentTarget.dataset.btEnter;
+ event.currentTarget.removeEventListener("animationend", settle);
+ };
+ const scan = () => {
+ frame = 0;
+ const next = document.querySelector("[data-chat-flow]");
+ if (next !== column) {
+ observer.disconnect();
+ column = next;
+ if (column) observer.observe(column, { childList: true, subtree: true });
}
- try {
- await new Promise((resolve2) => {
- recorder.onstop = resolve2;
- 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();
+ if (!column) return;
+ const items = [...column.querySelectorAll(":scope > [data-chat-flow-key]")];
+ let last = -1;
+ items.forEach((item, index) => {
+ if (seen.has(item)) last = index;
+ });
+ const fresh = items.filter((item) => !seen.has(item) && item.offsetHeight > 0);
+ for (const item of fresh) seen.add(item);
+ if (last < 0 || Date.now() - started < 800 || fresh.length > 3) return;
+ for (const item of fresh) {
+ if (items.indexOf(item) < last) continue;
+ const reply = [void 0, "assistant-step", "tool-call"].includes(item.dataset.chatFlowKind);
+ item.dataset.btEnter = reply && check.current() ? "after-collapse" : "new";
+ item.addEventListener("animationend", settle);
}
- }
- };
-}
-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();
+ };
+ const observer = new MutationObserver(() => {
+ if (!frame) frame = requestAnimationFrame(scan);
+ });
+ scan();
+ return () => {
+ cancelAnimationFrame(frame);
+ observer.disconnect();
+ };
+ }, []);
}
-function closingReplyText(chat, turn) {
- const location2 = chat?.timeline?.turns?.get(turn);
- if (location2 === void 0) return void 0;
- const closing = location2.data?.get("turn-tail")?.closing;
- if (closing === void 0) return void 0;
- if (closing === null) return "";
- return (closing.blocks ?? []).filter((block) => block.kind === "text" && block.text.trim() !== "").map((block) => block.text).join("\n\n");
+function ActivityIndicator({ sessionId, useRoster, useSessionStatus, useLive, useSession, useWork, actions }) {
+ const roster = useRoster((value) => value);
+ const running = useSessionStatus((map) => map.get(sessionId)?.running === true);
+ const turnAt = useWork?.((work) => work.turns?.[sessionId]);
+ const runAt = (0, import_react31.useRef)(0);
+ if (!running) runAt.current = 0;
+ else if (runAt.current === 0) runAt.current = Date.now();
+ const liveKey = useLive((state) => JSON.stringify(state[sessionId] ?? {}));
+ const steeredAt = useWork?.((work) => work.steered?.[sessionId]);
+ const pendingInput = useSession((snapshot) => freshInputAt(snapshot?.pendingSubmissions, steeredAt));
+ const bot = roster.byId[sessionId];
+ const room2 = roster.roomsById[sessionId];
+ const moveAt = useWork?.((work) => {
+ const entry = bot !== void 0 ? work.bots?.[bot.id] : room2 !== void 0 ? work.rooms?.[room2.id]?.find((item) => item.self === true) : void 0;
+ return entry?.switching === true && entry.folder === true && entry.roomId === void 0 ? entry.since : 0;
+ }) ?? 0;
+ const entries2 = (0, import_react31.useMemo)(() => Object.values(JSON.parse(liveKey)), [liveKey]);
+ const streaming = entries2.some((entry) => entry.text);
+ const tools = entries2.filter((entry) => !entry.text).sort((a, b) => a.at - b.at);
+ const relaying = tools.some((entry) => entry.relay);
+ const visible = moveAt !== 0 || rowVisible({ running, streaming, tools, relaying, bot, room: room2 });
+ const tool = tools.at(-1);
+ const inputRef = (0, import_react31.useRef)(0);
+ const inputAt = Math.max(inputRef.current, pendingInput);
+ inputRef.current = inputAt;
+ const want = !visible ? null : moveAt !== 0 ? { key: "move", label: t("Switching working folder"), state: "thinking" } : inputAt > (tool?.at ?? 0) ? { key: `input:${inputAt}`, pool: PHRASES.thinking, state: "thinking" } : tool ? { key: tool.label ? `tool:${tool.label}` : "working", label: tool.label, pool: PHRASES.working, state: tool.state ?? "working" } : { key: "thinking", pool: PHRASES.thinking, state: "thinking" };
+ const [shown, setShown] = (0, import_react31.useState)(null);
+ const wantKey = want?.key ?? null;
+ const markState = (0, import_react31.useRef)("thinking");
+ if (want) markState.current = want.state;
+ (0, import_react31.useEffect)(() => {
+ if (wantKey === null || shown?.key === wantKey) return void 0;
+ const make = () => setShown({ key: wantKey, text: want.label ?? drawPhrase(want.pool), at: Date.now() });
+ const wait = shown ? shown.at + PHRASE_HOLD_MS - Date.now() : 0;
+ if (wait <= 0) {
+ make();
+ return void 0;
+ }
+ const timer = setTimeout(make, wait);
+ return () => clearTimeout(timer);
+ }, [wantKey, shown]);
+ const [phase, setPhase] = (0, import_react31.useState)(null);
+ const endedAt = (0, import_react31.useRef)(0);
+ const shift = (0, import_react31.useRef)(null);
+ const leaving = (0, import_react31.useRef)(false);
+ leaving.current = phase !== null && !visible;
+ (0, import_react31.useEffect)(() => {
+ if (visible) {
+ setPhase("in");
+ return void 0;
+ }
+ setPhase((current) => current === "in" ? "out" : current);
+ const timer = setTimeout(() => {
+ shift.current = document.querySelector("[data-conversation-scroll]")?.scrollTop ?? null;
+ setPhase((current) => current === "out" ? null : current);
+ }, 140);
+ return () => clearTimeout(timer);
+ }, [visible]);
+ (0, import_react31.useLayoutEffect)(() => {
+ if (phase !== null) return;
+ endedAt.current = Date.now();
+ setShown(null);
+ const before = shift.current;
+ shift.current = null;
+ const scroller = document.querySelector("[data-conversation-scroll]");
+ if (before === null || !scroller || reducedMotion()) return;
+ const delta = before - scroller.scrollTop;
+ if (delta > 0) scroller.querySelector("[data-chat-flow]")?.animate([{ transform: `translateY(${-delta}px)` }, { transform: "none" }], { duration: 140, easing: "cubic-bezier(.23,1,.32,1)" });
+ }, [phase]);
+ (0, import_react31.useEffect)(() => {
+ if (!running) actions.clearLive(sessionId);
+ }, [running, sessionId]);
+ useRowEntrances(() => leaving.current || Date.now() - endedAt.current < 300);
+ const host = useRunningHost(running || moveAt !== 0);
+ if (!host || phase === null || !shown) return null;
+ return (0, import_react_dom4.createPortal)((0, import_react31.createElement)(
+ "div",
+ { className: "bt-typing", "data-exiting": phase === "out" ? "" : void 0, "aria-hidden": true },
+ bot ? (0, import_react31.createElement)(BotMark, { bot, size: 28, state: markState.current, live: true, pokeable: true }) : (0, import_react31.createElement)(RoomAvatar, { room: room2, roster, size: 28 }),
+ (0, import_react31.createElement)(
+ "span",
+ { className: "bt-typing-text" },
+ (0, import_react31.createElement)("span", { key: `${shown.key}:${shown.at}`, className: "bt-typing-label" }, (0, import_react31.createElement)(Shimmer, null, `${shown.text}…`)),
+ (0, import_react31.createElement)(Elapsed, { at: moveAt !== 0 ? moveAt : Math.max(turnAt ?? runAt.current, inputAt), className: "bt-typing-time" })
+ )
+ ), host);
}
-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/dsh-offer.js
+var APP_OFFER = /* @__PURE__ */ new Set(["available", "downloading", "verifying", "installing", "ready"]);
+var bare = (value) => String(value ?? "").trim().replace(/^v/i, "").split("+")[0];
+var sameVersion = (a, b) => bare(a) !== "" && bare(a) === bare(b);
+function showsDshRow(dsh, app) {
+ if (!dsh?.verified || !dsh.current || sameVersion(dsh.verified, dsh.current)) return false;
+ if (dsh.kind === "npm") return true;
+ return dsh.kind === "app" && APP_OFFER.has(app?.phase) && sameVersion(app.version, dsh.verified);
}
-// src/client/surface.js
-function groupsFor({ mode, plain = false }) {
- return { shell: mode === "bot", conversation: mode === "bot" && !plain };
+// src/client/storage.js
+var STORAGE = {
+ unread: "ds-bot:unread",
+ reactions: "ds-bot:reactions",
+ seen: "ds-bot:seen",
+ prefs: "ds-bot:prefs",
+ surface: "ds-bot:surface",
+ agentSessions: "ds-bot:agent-sessions",
+ browserWidth: "ds-bot:browser-width",
+ sidebar: "ds-bot:sidebar",
+ browsers: "ds-bot.browser.v2"
+};
+var LEGACY_PREFIXES = ["dsh-bot:", "dsh-bot-team:"];
+var LEGACY_BROWSER_KEYS = ["ds-bot.browser.v1", "dsh-bot.browser.v1"];
+var LEGACY_THEMES = { grok: "mono" };
+function legacyKeys(key) {
+ if (key === STORAGE.browsers) return LEGACY_BROWSER_KEYS;
+ const name = key.slice(key.indexOf(":") + 1);
+ return LEGACY_PREFIXES.map((prefix) => `${prefix}${name}`);
}
-var GROUPS = ["shell", "conversation"];
-function disposeAll(disposers, label) {
- for (const dispose of [...disposers].reverse()) {
- try {
- dispose?.();
- } catch (error) {
- console.warn(`[ds-bot] ${label}`, error);
- }
+var migrateBrowsers = (storage) => {
+ if (storage.getItem(STORAGE.browsers) !== null) {
+ for (const key of LEGACY_BROWSER_KEYS) storage.removeItem(key);
+ return;
}
-}
-function surfaceGroups(install, { onError } = {}) {
- const mounted = { shell: [], conversation: [] };
- const withdraw = (group) => {
- const disposers = mounted[group];
- mounted[group] = [];
- disposeAll(disposers, `withdraw ${group}`);
- };
- const mount = (group) => {
- const disposers = [];
+ for (const key of LEGACY_BROWSER_KEYS) {
try {
- for (const step of install[group]()) if (step) disposers.push(step());
- mounted[group] = disposers;
- return true;
- } catch (error) {
- disposeAll(disposers, `roll back ${group}`);
- console.warn(`[ds-bot] install ${group}`, error);
- onError?.(group, error);
- return false;
+ const value = storage.getItem(key);
+ if (value === null) continue;
+ const previous = JSON.parse(value) ?? {};
+ const tabs = Object.fromEntries(Object.entries(previous).filter(([, page]) => page && typeof page === "object").map(([botId, page]) => {
+ const tab = { id: `v1-${botId}`, url: page.url ?? "", title: page.title ?? "" };
+ return [botId, { tabs: [tab], active: tab.id }];
+ }));
+ storage.setItem(STORAGE.browsers, JSON.stringify(tabs));
+ for (const earlier of LEGACY_BROWSER_KEYS) storage.removeItem(earlier);
+ return;
+ } catch {
}
- };
- let lastWanted = {};
- const api = {
- reconcile(wanted) {
- lastWanted = wanted;
- for (const group of [...GROUPS].reverse()) if (!wanted[group]) withdraw(group);
- for (const group of GROUPS) {
- if (!wanted[group] || mounted[group].length > 0) continue;
- if (!mount(group)) break;
+ }
+};
+function migrateStorage(storage = globalThis.localStorage) {
+ for (const key of Object.values(STORAGE)) {
+ if (key === STORAGE.browsers) continue;
+ for (const legacy of legacyKeys(key)) {
+ try {
+ const value = storage.getItem(legacy);
+ if (value !== null && storage.getItem(key) === null) storage.setItem(key, value);
+ storage.removeItem(legacy);
+ } catch {
}
- },
- // A step can go on with nothing actually contributed — a slot inject whose
- // callback threw inside the host still returns its disposer. remount takes
- // the group off and lets the reconcile put it back, so a caller that
- // notices the contribution is missing can retry instead of trusting
- // `mounted`. Groups that lean on it (the conversation on the shell's
- // styles) come off first and go back only through the reconcile — a
- // failed remount never leaves one stranded.
- remount(group, wanted = lastWanted) {
- if (!GROUPS.includes(group)) return;
- for (const later of GROUPS.slice(GROUPS.indexOf(group) + 1)) withdraw(later);
- withdraw(group);
- api.reconcile(wanted);
- },
- dispose() {
- for (const group of [...GROUPS].reverse()) withdraw(group);
}
- };
- return api;
-}
-function freePriority(entries2, { priority, key, id }) {
- if (priority === void 0) return void 0;
- const taken = entries2.filter((entry) => (key === void 0 || entry.options?.key === key) && (id === void 0 || entry.options?.id === id)).map((entry) => (entry.options?.priority ?? 0) - 1);
- return Math.min(priority, ...taken);
-}
-function readMode(storage = globalThis.localStorage) {
- try {
- return storage.getItem(STORAGE.surface) === "agent" ? "agent" : "bot";
- } catch {
- return "bot";
}
-}
-function writeMode(mode, storage = globalThis.localStorage) {
try {
- storage.setItem(STORAGE.surface, mode);
+ migrateBrowsers(storage);
} catch {
}
-}
-
-// src/client/header-navigation.js
-var navigationEntry = (entries2) => entries2.find((entry) => entry.store && typeof entry.inject === "function");
-function headerNavigation(entries2, face) {
- const source = navigationEntry(entries2);
- return {
- ...source ? { store: source.store } : {},
- inject: (...args) => {
- const navigation = source?.inject(...args) ?? {};
- const own = face();
- return { ...navigation, ...own, hooks: { ...navigation.hooks, ...own.hooks } };
- }
- };
-}
-function installHeaderNavigation(slots, face, component, priority) {
- const name = "conversation.session.header";
- let source;
- let dispose;
- const refresh = () => {
- const entries2 = slots.entries(name).filter((entry) => entry.component !== component);
- const next = navigationEntry(entries2);
- if (dispose && source === next) return;
- dispose?.();
- source = next;
- dispose = slots.register({ name, priority: freePriority(entries2, { priority }), ...headerNavigation(entries2, face) }, component);
- };
- const unsubscribe = slots.subscribe(name, refresh);
try {
- refresh();
- } catch (error) {
- unsubscribe();
- throw error;
+ const prefs = JSON.parse(storage.getItem(STORAGE.prefs) ?? "null");
+ if (prefs && Object.hasOwn(LEGACY_THEMES, prefs.theme ?? "")) {
+ storage.setItem(STORAGE.prefs, JSON.stringify({ ...prefs, theme: LEGACY_THEMES[prefs.theme] }));
+ }
+ } catch {
}
- return () => {
- unsubscribe();
- dispose?.();
- };
}
-// src/client/model-menu.js
-var import_react27 = require("react");
-var import_react_dom6 = require("react-dom");
-var MENU_EXIT_MS = 120;
-function groupModels(models) {
- const groups = /* @__PURE__ */ new Map();
- for (const model of models ?? []) {
- const provider = model.provider ?? model.providerName ?? model.ref.split("/")[0];
- if (!groups.has(provider)) groups.set(provider, []);
- groups.get(provider).push(model);
- }
- const names = /* @__PURE__ */ new Map();
- for (const [provider, list] of groups) {
- const name = list[0].providerName ?? provider;
- names.set(name, (names.get(name) ?? 0) + 1);
- }
- return [...groups].map(([provider, list]) => {
- const name = list[0].providerName ?? provider;
- return [names.get(name) > 1 ? `${name} (${provider})` : name, list];
- });
-}
-var servedOf = (roster, ref) => (roster.models ?? []).find((model) => model.ref === ref);
-function modelOf(bot, roster) {
- const ref = bot.model ?? bot.appliedModel;
- if (!ref) return void 0;
- const served = servedOf(roster, ref);
- 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_react27.useState)(void 0);
- (0, import_react27.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;
+// src/client/frame-layout.js
+var MIN_CHAT = 420;
+var RAIL_WIDTH = 88;
+var PANEL_MIN = { details: 320, browser: 360, side: 320 };
+var DSH_NARROW = 1024;
+var SIDEBAR_MIN = 264;
+var SIDEBAR_MAX = 420;
+var FALLBACK_SIDEBAR_WIDTH = 280;
+var RAIL_SNAP = (RAIL_WIDTH + SIDEBAR_MIN) / 2;
+function frameLayout({ viewport, sidebarWidth, pref, drawer = false, panel = null }) {
+ const fits = pref === "open" && viewport >= sidebarWidth + MIN_CHAT;
+ let left = pref === "hidden" ? "hidden" : fits ? "open" : drawer && pref === "open" ? "drawer" : "rail";
+ let occupied = left === "open" ? sidebarWidth : left === "hidden" ? 0 : RAIL_WIDTH;
+ let panelState = "none";
+ if (panel !== null) {
+ const need = (PANEL_MIN[panel.view] ?? PANEL_MIN.details) + MIN_CHAT;
+ if (occupied + need <= viewport) panelState = "shown";
+ else if (panel.yielded === true) {
+ if (left !== "hidden") {
+ left = "rail";
+ occupied = RAIL_WIDTH;
+ }
+ panelState = occupied + need <= viewport ? "shown" : "overlay";
+ } else panelState = "folded";
+ }
+ return { left, panel: panelState, room: Math.max(0, viewport - occupied) };
}
-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 dragColumn(x, viewport) {
+ if (x < RAIL_SNAP) return { left: "rail", width: RAIL_WIDTH };
+ const docks = viewport >= SIDEBAR_MIN + MIN_CHAT;
+ const high = docks ? Math.max(SIDEBAR_MIN, Math.min(SIDEBAR_MAX, viewport - MIN_CHAT)) : SIDEBAR_MAX;
+ return { left: docks ? "open" : "drawer", width: Math.round(Math.max(SIDEBAR_MIN, Math.min(x, high))) };
}
-function effortStops(reasoning) {
- const efforts = reasoning?.efforts ?? [];
- if (efforts.length === 0) return [];
- const hasDefault = efforts.some((effort) => effort.id === reasoning.defaultEffort);
- return hasDefault ? efforts.map((effort) => ({ effort: effort.id, label: effort.name })) : [{ effort: void 0, label: t("Default") }, ...efforts.map((effort) => ({ effort: effort.id, label: effort.name }))];
+var toggledPref = (pref, shown) => pref === "hidden" ? shown : "hidden";
+var RESIZE_SETTLE_MS = 500;
+var userSidebarToggle = ({ before, after, requested = false, sinceResize = Infinity }) => before.collapsed !== after.collapsed && !requested && sinceResize >= RESIZE_SETTLE_MS && before.viewport < DSH_NARROW === after.viewport < DSH_NARROW;
+var PREFS = ["open", "rail", "hidden"];
+function readSidebar(storage = globalThis.localStorage) {
+ try {
+ const saved = JSON.parse(storage.getItem(STORAGE.sidebar) ?? "null");
+ const pref = PREFS.includes(saved?.pref) ? saved.pref : "open";
+ const shown = saved?.shown === "rail" ? "rail" : "open";
+ const width = Number.isFinite(saved?.width) ? Math.max(SIDEBAR_MIN, Math.min(SIDEBAR_MAX, saved.width)) : FALLBACK_SIDEBAR_WIDTH;
+ return { pref, shown, width };
+ } catch {
+ return { pref: "open", shown: "open", width: FALLBACK_SIDEBAR_WIDTH };
+ }
}
-var ResetIcon = () => (0, import_react27.createElement)(
- "svg",
- { width: 12, height: 12, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true },
- (0, import_react27.createElement)("path", { d: "M2.8 6.5A5.5 5.5 0 1 1 4 11.8" }),
- (0, import_react27.createElement)("path", { d: "M2.5 3.2v3.4h3.4" })
-);
-function EffortBar({ reasoning, current, onPick }) {
- const stops = effortStops(reasoning);
- const track = (0, import_react27.useRef)(null);
- const drag = (0, import_react27.useRef)(null);
- const [picked, setPicked] = (0, import_react27.useState)(current);
- const [dragRatio, setDragRatio] = (0, import_react27.useState)(null);
- (0, import_react27.useEffect)(() => {
- if (!drag.current) setPicked(current);
- }, [current]);
- if (stops.length === 0) return null;
- const hasDefault = (reasoning?.efforts ?? []).some((effort) => effort.id === reasoning?.defaultEffort);
- const activeEffort = picked ?? (hasDefault ? reasoning.defaultEffort : void 0);
- const activeIndex = Math.max(0, stops.findIndex((stop) => (stop.effort ?? null) === (activeEffort ?? null)));
- const active = stops[activeIndex];
- const stopRatio = stops.length <= 1 ? 1 : activeIndex / (stops.length - 1);
- const ratio = dragRatio ?? stopRatio;
- const commit = (effort) => {
- setPicked(effort);
- if ((effort ?? null) !== (current ?? null)) onPick(effort);
- };
- const ratioAt = (clientX) => {
- const rect = track.current?.getBoundingClientRect();
- if (!rect || stops.length <= 1) return 1;
- const span = Math.max(1, rect.width - 22);
- return Math.max(0, Math.min(1, (clientX - rect.left - 11) / span));
- };
- const nearestStop = (r) => stops[Math.round(r * (stops.length - 1))] ?? stops[0];
- const onPointerDown = (event) => {
- if (event.button !== 0) return;
- event.preventDefault();
- try {
- event.currentTarget.setPointerCapture?.(event.pointerId);
- } catch {
+function writeSidebar(value, storage = globalThis.localStorage) {
+ try {
+ storage.setItem(STORAGE.sidebar, JSON.stringify(value));
+ } catch {
+ }
+}
+
+// src/client/frame-watch.js
+var sidebarTrackWidth = () => typeof document === "undefined" ? null : document.querySelector('[class*="_sidebarCol"]')?.getBoundingClientRect().width ?? null;
+var dshCollapsed = () => {
+ if (typeof document === "undefined") return null;
+ const column = document.querySelector('[class*="_sidebarCol"]');
+ return column ? column.parentElement?.hasAttribute("data-sidebar-collapsed") ?? false : null;
+};
+var collapsedTrackWidth = () => document.documentElement.hasAttribute("data-windows-titlebar") || document.documentElement.dataset.platform === "darwin" ? 0 : 56;
+var room = { rule: null, selector: "" };
+var roomRule = () => {
+ const live = room.rule?.parentStyleSheet?.ownerNode?.isConnected;
+ if (live && room.selector) return room.rule;
+ const column = document.querySelector('[class*="_centerCol"]');
+ const selector = column ? [...column.classList].filter((name) => name.includes("_centerCol")).map((name) => `.${CSS.escape(name)}`).join(",") : "";
+ if (live && !selector) return room.rule;
+ const declarations2 = room.rule?.style.cssText ?? "";
+ room.rule?.parentStyleSheet?.ownerNode?.remove();
+ const style = installStyles(`${selector || '[class*="_centerCol"]'}{${declarations2}}`, "chat-room");
+ room.rule = style.sheet.cssRules[0];
+ room.selector = selector;
+ return room.rule;
+};
+var margin = (side, width, style) => {
+ if (width === null) style.removeProperty(`margin-${side}`);
+ else style.setProperty(`margin-${side}`, `${width}px`, "important");
+};
+var roomHold = 0;
+var chatRoom = {
+ /** The margin the Bot panel takes on the right, in px, or null for the shell's own. */
+ setRight(width) {
+ margin("right", width, roomRule().style);
+ },
+ /** The margin our own left column takes while the shell sidebar is collapsed. */
+ setLeft(width) {
+ margin("left", width, roomRule().style);
+ },
+ /** While on, a margin change lands at once instead of gliding. */
+ hold(on) {
+ cancelAnimationFrame(roomHold);
+ if (on) {
+ roomRule().style.setProperty("transition", "none", "important");
+ return;
}
- const r = ratioAt(event.clientX);
- const next = nearestStop(r);
- drag.current = { id: event.pointerId, startX: event.clientX, moved: false, effort: next?.effort };
- if (next) setPicked(next.effort);
+ roomHold = requestAnimationFrame(() => {
+ roomHold = requestAnimationFrame(() => roomRule().style.removeProperty("transition"));
+ });
+ },
+ /** The columns themselves, for a drag's per-frame writes. */
+ columns() {
+ roomRule();
+ return room.selector ? [...document.querySelectorAll(room.selector)] : [];
+ }
+};
+function installFrameWatch(frame) {
+ let collapsedWidth = collapsedTrackWidth();
+ let raf = 0;
+ const watched = /* @__PURE__ */ new Set();
+ const observer = typeof ResizeObserver === "function" ? new ResizeObserver(() => schedule()) : null;
+ const read = () => {
+ const column = document.querySelector('[class*="_sidebarCol"]');
+ const animating = column?.closest("[data-animating]") != null;
+ const width = animating ? null : sidebarTrackWidth();
+ const collapsed = dshCollapsed();
+ if (width !== null && collapsed === true) collapsedWidth = width;
+ frame.set((state) => {
+ const next = { ...state, viewport: window.innerWidth, collapsedWidth, collapsed: collapsed === true };
+ return state.viewport === next.viewport && state.collapsedWidth === next.collapsedWidth && state.collapsed === next.collapsed ? state : next;
+ });
};
- const onPointerMove = (event) => {
- const state = drag.current;
- if (!state || state.id !== event.pointerId) return;
- if (!state.moved && Math.abs(event.clientX - state.startX) > 2) state.moved = true;
- const r = ratioAt(event.clientX);
- const next = nearestStop(r);
- if (state.moved) setDragRatio(r);
- if (next) {
- state.effort = next.effort;
- setPicked(next.effort);
+ const measure = () => {
+ for (const selector of ['[class*="_sidebarCol"]', '[class*="_centerCol"]']) {
+ for (const column of document.querySelectorAll(selector)) {
+ if (!watched.has(column)) {
+ watched.add(column);
+ observer?.observe(column);
+ }
+ }
}
+ read();
};
- const finishDrag = (event) => {
- const state = drag.current;
- if (!state || event && state.id !== event.pointerId) return;
- drag.current = null;
- setDragRatio(null);
- commit(state.effort);
+ const schedule = () => {
+ if (raf === 0) raf = requestAnimationFrame(() => {
+ raf = 0;
+ measure();
+ });
};
- const onKeyDown = (event) => {
- if (!["ArrowLeft", "ArrowDown", "ArrowRight", "ArrowUp", "Home", "End"].includes(event.key)) return;
- event.preventDefault();
- event.stopPropagation();
- const nextIndex = event.key === "Home" ? 0 : event.key === "End" ? stops.length - 1 : event.key === "ArrowLeft" || event.key === "ArrowDown" ? Math.max(0, activeIndex - 1) : Math.min(stops.length - 1, activeIndex + 1);
- const next = stops[nextIndex];
- if (next) commit(next.effort);
+ measure();
+ const mutations = new MutationObserver(schedule);
+ mutations.observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-sidebar-collapsed", "data-animating"] });
+ window.addEventListener("resize", schedule);
+ return () => {
+ cancelAnimationFrame(raf);
+ mutations.disconnect();
+ observer?.disconnect();
+ window.removeEventListener("resize", schedule);
};
- return (0, import_react27.createElement)(
- "div",
- { className: "bt-effort-bar", role: "group", "aria-label": t("Thinking level") },
- (0, import_react27.createElement)(
- "div",
- { className: "bt-effort-head" },
- (0, import_react27.createElement)("span", { className: "bt-effort-label" }, t("Thinking level")),
- (0, import_react27.createElement)(
- "span",
- { className: "bt-effort-meta" },
- picked === void 0 && hasDefault ? (0, import_react27.createElement)("span", { className: "bt-effort-tag" }, t("Default")) : null,
- (0, import_react27.createElement)("span", { className: "bt-effort-val" }, active.label),
- picked !== void 0 || !hasDefault ? (0, import_react27.createElement)("button", {
- type: "button",
- className: "bt-effort-reset",
- "aria-label": t("Default"),
- title: t("Default"),
- disabled: picked === void 0,
- onClick: () => commit(void 0)
- }, (0, import_react27.createElement)(ResetIcon)) : null
- )
- ),
- (0, import_react27.createElement)(
- "div",
- {
- ref: track,
- className: "bt-effort-track",
- role: "slider",
- tabIndex: 0,
- "aria-label": t("Thinking level"),
- "aria-valuemin": 0,
- "aria-valuemax": stops.length - 1,
- "aria-valuenow": activeIndex,
- "aria-valuetext": active.label,
- "data-dragging": dragRatio !== null ? "" : void 0,
- style: { "--bt-effort-p": ratio },
- onPointerDown,
- onPointerMove,
- onPointerUp: finishDrag,
- onPointerCancel: finishDrag,
- onLostPointerCapture: finishDrag,
- onKeyDown
- },
- (0, import_react27.createElement)("span", { className: "bt-effort-fill", "aria-hidden": true }),
- stops.map((stop, index) => {
- const dotRatio = stops.length <= 1 ? 1 : index / (stops.length - 1);
- return (0, import_react27.createElement)("span", {
- key: stop.effort ?? "default",
- className: "bt-effort-dot",
- "data-filled": dotRatio <= ratio + 1e-3 || void 0,
- style: { "--bt-dot-p": dotRatio },
- title: stop.label,
- "aria-hidden": true
- });
- }),
- (0, import_react27.createElement)("span", { className: "bt-effort-knob", "aria-hidden": true })
- )
- );
}
-function ModelRows({ roster, current, onPick }) {
- return groupModels(roster.models).map(([provider, list]) => (0, import_react27.createElement)(
- import_react27.Fragment,
- { key: list[0].provider ?? provider },
- (0, import_react27.createElement)("div", { className: "bt-model-group", role: "presentation" }, provider),
- list.map((model) => (0, import_react27.createElement)(
+
+// src/client/sidebar.js
+var import_react32 = require("react");
+var import_react_dom5 = require("react-dom");
+function useMarkedUnread(id, active, marked, actions) {
+ (0, import_react32.useEffect)(() => {
+ if (active && marked) actions.clearUnread(id);
+ }, [active, marked]);
+}
+var PinMark = () => (0, import_react32.createElement)("span", { className: "bt-pin", "aria-hidden": true }, (0, import_react32.createElement)(PinMarkIcon));
+var nameIfCut = (event) => {
+ const row = event.currentTarget;
+ const name = row.querySelector(".bt-row-title");
+ if (name && name.scrollWidth > name.clientWidth) row.title = name.textContent;
+ else row.removeAttribute("title");
+};
+var useApproval = (useWork, match) => useWork ? useWork((work) => (work.approvals ?? []).some(match)) : false;
+var useGroupWork = (useWork, pick2) => {
+ const raw = useWork ? useWork((work) => JSON.stringify(pick2(work.rooms ?? {}))) : "[]";
+ return (0, import_react32.useMemo)(() => JSON.parse(raw), [raw]);
+};
+var doingOf = ({ tool, said, note, target, switching }) => ({ tool, said, note, target, switching });
+var workLine = (lead, doing, more) => (0, import_react32.createElement)(Shimmer, null, `${lead} · ${workPhrase(doing)}…${more > 0 ? ` +${more}` : ""}`);
+var doingLine = (doing) => (0, import_react32.createElement)(Shimmer, null, `${workPhrase(doing)}…`);
+var waitingFor = (roster, waits) => {
+ const names = [...(waits?.bots ?? []).map((id) => roster.byId[id]?.name), ...(waits?.rooms ?? []).map((id) => roster.roomsById[id]?.name)].filter(Boolean);
+ return names.length === 0 ? "" : t("Waiting for {names}", { names: names.join(t(" and ")) });
+};
+function BotRow({ bot, roster, actions, useSessions, useSessionStatus, useSessionRetainInfo, useActivity, useWork, wide, marked }) {
+ const id = bot.id;
+ const part = currentPart(bot);
+ const preview = useSessions((list) => previewOf(list, part, roster.exchangeTurns[part]));
+ const running = useSessionStatus((map) => map.get(part)?.running === true);
+ const active = useSessionRetainInfo(part, (info) => (info?.retainedBy?.mainView ?? 0) > 0);
+ const unread = useSessionStatus((map) => map.get(part)?.completionUnread === true || map.get(part)?.pendingInteraction !== void 0) || marked && !active;
+ useMarkedUnread(id, active, marked, actions);
+ const main = isMainOf(roster, id);
+ const tile = roster.mainBotId === id;
+ const approval = useApproval(useWork, (entry) => entry.botId === id);
+ const alert = roster.questions?.[part] !== void 0 || approval;
+ const doing = useActivity((map) => map[id]);
+ const groups = useGroupWork(useWork, (rooms) => Object.entries(rooms).flatMap(([roomId, entries2]) => entries2.filter((entry) => entry.botId === id).map((entry) => ({ id: roomId, ...doingOf(entry) }))));
+ const away = !running && groups.length > 0;
+ const state = botState(running || away, doing, alert);
+ const runningLine = running && doing ? doingLine(doing) : null;
+ const awayLine = away ? workLine(roster.roomsById[groups[0].id]?.name ?? t("a group chat"), groups[0], groups.length - 1) : null;
+ const waitsRaw = useWork ? useWork((work) => JSON.stringify(work.waiting?.[id] ?? null)) : "null";
+ const waits = (0, import_react32.useMemo)(() => JSON.parse(waitsRaw), [waitsRaw]);
+ const waitsFor = state === "waiting" ? waitingFor(roster, waits) : "";
+ if (bot.hidden && !active && !main) return null;
+ const onContextMenu = (event) => {
+ event.preventDefault();
+ actions.openMenu({ kind: "bot", id, x: event.clientX, y: event.clientY });
+ };
+ const pinned = bot.pinned === true && !tile;
+ const label = [bot.name, main ? t("Main Bot") : "", pinned ? t("Pinned") : "", running || away ? t("Working") : "", waitsFor, approval ? t("Waiting for your approval") : alert ? t("Waiting for your answer") : "", unread ? t("Unread activity") : ""].filter(Boolean).join(", ");
+ if (tile && wide) {
+ return (0, import_react32.createElement)("div", { className: "bt-tile-wrap" }, (0, import_react32.createElement)(
"button",
{
- key: model.ref,
type: "button",
- role: "menuitemradio",
- "aria-checked": model.ref === current,
- title: model.ref,
- onClick: () => onPick(model.ref)
+ className: "bt-tile",
+ "aria-label": label,
+ "aria-current": active ? "page" : void 0,
+ "data-bot-id": id,
+ title: preview || bot.name,
+ onClick: () => actions.openSession(id),
+ onContextMenu
},
- (0, import_react27.createElement)("span", { className: "bt-menu-label" }, model.name),
- model.ref === roster.defaultModel ? (0, import_react27.createElement)("span", { className: "bt-menu-hint" }, t("Default")) : null,
- (0, import_react27.createElement)("span", { className: "bt-model-tick", "aria-hidden": true }, model.ref === current ? (0, import_react27.createElement)(CheckIcon) : null)
- ))
- ));
+ (0, import_react32.createElement)(BotAvatar, { bot, size: 60, state, main: true }),
+ (0, import_react32.createElement)("span", { className: "bt-tile-name" }, bot.name),
+ bot.role ? (0, import_react32.createElement)("span", { className: "bt-chip" }, bot.role) : null
+ ));
+ }
+ return (0, import_react32.createElement)(
+ "button",
+ {
+ type: "button",
+ className: "bt-row",
+ "aria-label": label,
+ "aria-current": active ? "page" : void 0,
+ "data-bot-id": id,
+ title: wide ? void 0 : bot.name,
+ onMouseEnter: wide ? nameIfCut : void 0,
+ onClick: () => actions.openSession(id),
+ onContextMenu
+ },
+ (0, import_react32.createElement)(BotAvatar, { bot, size: wide ? 36 : 44, state, main }),
+ pinned && !wide ? (0, import_react32.createElement)(PinMark) : null,
+ wide ? (0, import_react32.createElement)(
+ "span",
+ { className: "bt-row-body" },
+ (0, import_react32.createElement)("span", { className: "bt-row-name" }, (0, import_react32.createElement)("span", { className: "bt-row-title" }, bot.name), pinned ? (0, import_react32.createElement)(PinMark) : null),
+ runningLine ? (0, import_react32.createElement)("span", { className: "bt-row-preview" }, runningLine) : awayLine ? (0, import_react32.createElement)("span", { className: "bt-row-preview" }, awayLine) : waitsFor ? (0, import_react32.createElement)("span", { className: "bt-row-preview" }, waitsFor) : preview ? (0, import_react32.createElement)("span", { className: "bt-row-preview" }, preview) : null
+ ) : null,
+ wide && unread && !active ? (0, import_react32.createElement)("span", { className: "bt-unread", "aria-hidden": true }) : !wide && !active && (alert || unread) ? (0, import_react32.createElement)("span", { className: `bt-dot${alert ? " bt-dot-wait" : ""}`, "aria-hidden": true }) : null
+ );
}
-var Caret = () => (0, import_react27.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_react27.createElement)("path", { d: "M5.5 8l4.5 4.5L14.5 8" }));
-function useAnchoredMenu() {
- const [anchor, setAnchor] = (0, import_react27.useState)(null);
- const [place, setPlace] = (0, import_react27.useState)(null);
- const [shownPlace, leaving] = useLinger(place, MENU_EXIT_MS);
- const button = (0, import_react27.useRef)(null);
- const menu = (0, import_react27.useRef)(null);
- const tick = useViewport();
- const close = () => {
- setAnchor(null);
- setPlace(null);
- };
- (0, import_react27.useEffect)(() => {
- if (place === null) return void 0;
- const onDown = (event) => {
- if (menu.current?.contains(event.target) || button.current?.contains(event.target)) return;
- close();
+function RoomRow({ room: room2, roster, actions, useSessions, useSessionStatus, useSessionRetainInfo, useWork, wide, marked }) {
+ const id = room2.id;
+ const sessionId = room2.sessionId ?? id;
+ const fallback = useSessions((list) => previewOf(list, sessionId));
+ const preview = room2.preview?.replace(/\s+/g, " ").trim() || fallback;
+ const active = useSessionRetainInfo(sessionId, (info) => (info?.retainedBy?.mainView ?? 0) > 0);
+ const unread = useSessionStatus((map) => map.get(sessionId)?.completionUnread === true) || marked && !active;
+ useMarkedUnread(id, active, marked, actions);
+ const approval = useApproval(useWork, (entry) => entry.roomId === id);
+ const members = useGroupWork(useWork, (rooms) => (rooms[id] ?? []).filter((entry) => entry.botId !== void 0).map((entry) => ({ id: entry.botId, ...doingOf(entry) })));
+ const first = roster.byId[members[0]?.id];
+ const workingLine = first ? workLine(first.name, members[0], members.length - 1) : null;
+ if (room2.hidden && !active) return null;
+ const pinned = room2.pinned === true;
+ const label = [room2.name, pinned ? t("Pinned") : "", members.length > 0 ? t("Working") : "", approval ? t("Waiting for your approval") : ""].filter(Boolean).join(", ");
+ return (0, import_react32.createElement)(
+ "button",
+ {
+ type: "button",
+ className: "bt-row",
+ "aria-label": label,
+ "aria-current": active ? "page" : void 0,
+ "data-room-id": id,
+ title: wide ? void 0 : room2.name,
+ onMouseEnter: wide ? nameIfCut : void 0,
+ onClick: () => actions.openSession(id),
+ onContextMenu: (event) => {
+ event.preventDefault();
+ actions.openMenu({ kind: "room", id, x: event.clientX, y: event.clientY });
+ }
+ },
+ (0, import_react32.createElement)(RoomAvatar, { room: room2, roster, size: wide ? 36 : 44 }),
+ pinned && !wide ? (0, import_react32.createElement)(PinMark) : null,
+ wide ? (0, import_react32.createElement)(
+ "span",
+ { className: "bt-row-body" },
+ (0, import_react32.createElement)("span", { className: "bt-row-name" }, (0, import_react32.createElement)("span", { className: "bt-row-title" }, room2.name), pinned ? (0, import_react32.createElement)(PinMark) : null),
+ workingLine ? (0, import_react32.createElement)("span", { className: "bt-row-preview" }, workingLine) : preview ? (0, import_react32.createElement)("span", { className: "bt-row-preview" }, preview) : null
+ ) : null,
+ wide && approval && !active ? (0, import_react32.createElement)("span", { className: "bt-unread bt-unread-wait", "aria-hidden": true }) : wide && unread && !active ? (0, import_react32.createElement)("span", { className: "bt-unread", "aria-hidden": true }) : !wide && !active && (approval || unread) ? (0, import_react32.createElement)("span", { className: `bt-dot${approval ? " bt-dot-wait" : ""}`, "aria-hidden": true }) : null
+ );
+}
+var agentSessionTitle = (session) => session.title === "" ? t("New session") : session.title;
+function AgentSessionRow({ session, agent, actions, renaming, index }) {
+ const input = (0, import_react32.useRef)(null);
+ (0, import_react32.useLayoutEffect)(() => {
+ if (!renaming) return;
+ input.current?.focus();
+ input.current?.select();
+ }, [renaming]);
+ if (renaming) {
+ const commit = (keep) => {
+ const value = input.current?.value ?? "";
+ if (!keep || value.trim() === "" || value.trim() === session.title) {
+ actions.endAgentRename();
+ return;
+ }
+ void (async () => {
+ try {
+ await actions.renameAgentSession(agent.id, session.id, value);
+ actions.endAgentRename();
+ } catch (error) {
+ actions.reportError(error, "agent-rename");
+ }
+ })();
};
- const onKey = (event) => {
- if (stepMenuFocus(menu.current, event, button.current)) return;
- if (event.key === "Escape") {
+ return (0, import_react32.createElement)(
+ "div",
+ { className: "bt-agent-sub-row bt-agent-edit", style: { "--i": index } },
+ (0, import_react32.createElement)("input", {
+ ref: input,
+ defaultValue: session.title,
+ "aria-label": t("Rename"),
+ onKeyDown: (event) => {
+ if (event.nativeEvent.isComposing) return;
+ if (event.key === "Enter") commit(true);
+ else if (event.key === "Escape") commit(false);
+ },
+ onBlur: () => commit(true)
+ })
+ );
+ }
+ return (0, import_react32.createElement)(
+ "button",
+ {
+ type: "button",
+ className: "bt-agent-sub-row",
+ "aria-current": session.active ? "page" : void 0,
+ style: { "--i": index },
+ onClick: () => actions.openAgentSession(session.id),
+ onContextMenu: (event) => {
+ event.preventDefault();
event.stopPropagation();
- close();
- button.current?.focus();
+ actions.openMenu({ kind: "agent-session", id: session.id, agentId: agent.id, x: event.clientX, y: event.clientY });
}
- };
- const onScroll = (event) => {
- if (!menu.current?.contains(event.target)) close();
- };
- window.addEventListener("mousedown", onDown);
- window.addEventListener("keydown", onKey, true);
- window.addEventListener("scroll", onScroll, true);
- return () => {
- window.removeEventListener("mousedown", onDown);
- window.removeEventListener("keydown", onKey, true);
- window.removeEventListener("scroll", onScroll, true);
- };
- }, [place]);
- const open = () => setAnchor({});
- (0, import_react27.useLayoutEffect)(() => {
- if (anchor === null || !button.current) return;
- const rect = button.current.getBoundingClientRect();
- const width = Math.max(240, rect.width);
- const left = Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8));
- const below = viewBottom() - rect.bottom;
- setPlace(below >= 260 || below >= rect.top ? { left, width, top: rect.bottom + 4, maxHeight: below - 16, "--bt-origin": "top right" } : { left, width, bottom: viewBottom() - rect.top + 4, maxHeight: rect.top - 16, "--bt-origin": "bottom right" });
- }, [anchor, tick]);
- return { isOpen: place !== null, shownPlace, leaving, button, menu, open, close };
+ },
+ (0, import_react32.createElement)("span", { className: "bt-agent-sub-title" }, agentSessionTitle(session)),
+ (0, import_react32.createElement)("span", { className: "bt-agent-sub-time" }, session.at > 0 ? relativeShort(session.at) : "")
+ );
}
-function ModelMenu({ bot, roster, actions, run: run2, wide = false, onPick, onPickEffort, withEfforts = true }) {
- const { isOpen, shownPlace, leaving, button, menu, open, close } = useAnchoredMenu();
- const shown = modelOf(bot, roster);
- const current = bot.model ?? bot.appliedModel;
- const served = servedOf(roster, current);
- const reasoning = useEfforts(served, withEfforts ? current : void 0, 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 toggle = () => {
- if (isOpen) {
- close();
- return;
- }
- void actions?.refreshModels?.();
- open();
- };
- const pick2 = (ref) => {
- close();
- if (onPick) onPick(ref);
- else if (ref !== current || !bot.model) void run2(actions.updateBot(bot.id, { model: ref }));
- };
- const pickEffort = (effort) => {
- if (onPickEffort) onPickEffort(effort);
- else if (effort !== bot.effort) void run2(actions.updateBot(bot.id, { effort: effort ?? null }));
- };
- const models = roster.models ?? [];
- const manage = manageModels(actions);
- const hasEfforts = withEfforts && effortStops(reasoning).length > 0;
- return (0, import_react27.createElement)(
- import_react27.Fragment,
- null,
- (0, import_react27.createElement)(
+function AgentRow({ agent, actions, useSessions, useSessionStatus, useUi, wide, marked }) {
+ const info = useSessions((list) => JSON.stringify(agent.sessions.map((id) => {
+ const row = list.byId[id];
+ return {
+ id,
+ // A blank Session's title is the workspace folder name; show the label instead.
+ title: row?.blank === true ? "" : row?.displayTitle ?? row?.title ?? "",
+ at: row?.updatedAt ?? 0,
+ running: row?.running === true,
+ active: (row?.retainedBy?.mainView ?? 0) > 0
+ };
+ }).sort((a, b) => b.at - a.at)));
+ const statusInfo = useSessionStatus((map) => JSON.stringify(agent.sessions.map((id) => ({
+ id,
+ running: map.get(id)?.running === true,
+ unread: map.get(id)?.completionUnread === true
+ }))));
+ const sessions = (0, import_react32.useMemo)(() => {
+ const statuses = Object.fromEntries(JSON.parse(statusInfo).map((entry) => [entry.id, entry]));
+ return JSON.parse(info).map((session) => ({
+ ...session,
+ running: statuses[session.id]?.running ?? session.running,
+ unread: statuses[session.id]?.unread ?? false
+ }));
+ }, [info, statusInfo]);
+ const renaming = useUi((value) => value.renameAgent);
+ const active = sessions.some((session) => session.active);
+ const running = sessions.some((session) => session.running);
+ const unread = sessions.some((session) => session.unread) || marked && !active;
+ useMarkedUnread(agent.id, active, marked, actions);
+ const preview = sessions[0] === void 0 ? t("New session") : agentSessionTitle(sessions[0]);
+ const label = ["DSH Agent", running ? t("Working") : "", unread ? t("Unread activity") : ""].filter(Boolean).join(", ");
+ const open = active && wide;
+ return (0, import_react32.createElement)(
+ "div",
+ { className: "bt-agent" },
+ (0, import_react32.createElement)(
"button",
{
- ref: button,
type: "button",
- className: "bt-model-trigger",
- "data-wide": wide || void 0,
- "aria-haspopup": "menu",
- "aria-expanded": isOpen,
- "aria-label": t("Model: {model}", { model: shown?.name ?? t("none") }),
- "data-missing": shown !== void 0 && !shown.served && models.length > 0 ? "" : void 0,
- onClick: toggle
+ className: "bt-row",
+ "aria-label": label,
+ "aria-current": active ? "page" : void 0,
+ "data-agent-id": agent.id,
+ title: wide ? void 0 : "DSH Agent",
+ onClick: () => actions.openAgent(agent.id),
+ onContextMenu: (event) => {
+ event.preventDefault();
+ actions.openMenu({ kind: "agent", id: agent.id, x: event.clientX, y: event.clientY });
+ }
},
- (0, import_react27.createElement)(
+ (0, import_react32.createElement)("span", { className: `bt-agent-ava${running ? " bt-run" : ""}` }, (0, import_react32.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: wide ? 22 : 24 })),
+ wide ? (0, import_react32.createElement)(
"span",
- { className: "bt-model-copy" },
- (0, import_react27.createElement)("span", { className: "bt-model-name" }, shown?.name ?? t("Choose a model")),
- shown ? (0, import_react27.createElement)("span", { className: "bt-model-provider" }, shown.served || models.length === 0 ? !withEfforts || effortLabel === void 0 ? shown.provider : `${shown.provider} · ${effortLabel}` : t("{provider} · not available", { provider: shown.provider })) : null
- ),
- (0, import_react27.createElement)(Caret)
+ { className: "bt-row-body" },
+ (0, import_react32.createElement)("span", { className: "bt-row-name" }, "DSH Agent"),
+ preview ? (0, import_react32.createElement)("span", { className: "bt-row-preview" }, preview) : null
+ ) : null,
+ wide && unread && !active ? (0, import_react32.createElement)("span", { className: "bt-unread", "aria-hidden": true }) : !wide && unread && !active ? (0, import_react32.createElement)("span", { className: "bt-dot", "aria-hidden": true }) : null
),
- shownPlace ? (0, import_react_dom6.createPortal)((0, import_react27.createElement)(
+ (0, import_react32.createElement)(
"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 },
- (0, import_react27.createElement)(
- "div",
- { className: "bt-model-scroll" },
- models.length > 0 ? (0, import_react27.createElement)(ModelRows, { roster, current, onPick: pick2 }) : (0, import_react27.createElement)("div", { className: "bt-model-none" }, t("No models are set up in DeepSeek Harness yet."))
- ),
- hasEfforts || manage ? (0, import_react27.createElement)(
+ { className: "bt-agent-sub", "data-open": open || void 0 },
+ (0, import_react32.createElement)(
"div",
- { className: "bt-model-foot" },
- hasEfforts ? (0, import_react27.createElement)(EffortBar, { reasoning, current: picked, onPick: pickEffort }) : null,
- hasEfforts && manage ? (0, import_react27.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null,
- manage ? (0, import_react27.createElement)("button", { type: "button", role: "menuitem", onClick: () => {
- close();
- manage();
- } }, (0, import_react27.createElement)(SlidersIcon), (0, import_react27.createElement)("span", { className: "bt-menu-label" }, t("Models and providers…"))) : null
- ) : null
- ), document.body) : null
+ { className: "bt-agent-sub-in" },
+ (0, import_react32.createElement)(
+ "button",
+ { type: "button", className: "bt-agent-sub-row bt-agent-new", style: { "--i": 0 }, onClick: () => {
+ void actions.newAgentSession(agent.id).catch((error) => actions.reportError(error, "agent-session"));
+ } },
+ (0, import_react32.createElement)(PlusIcon),
+ (0, import_react32.createElement)("span", { className: "bt-agent-sub-title" }, t("New session"))
+ ),
+ sessions.map((session, index) => (0, import_react32.createElement)(AgentSessionRow, {
+ key: session.id,
+ session,
+ agent,
+ actions,
+ index: index + 1,
+ renaming: renaming === session.id
+ }))
+ )
+ )
);
}
-function ModelChoiceDock({ sessionId, useRoster, actions }) {
+function useListGlide(listRef, layout, key) {
+ const tops = (0, import_react32.useRef)({ layout, map: /* @__PURE__ */ new Map() });
+ (0, import_react32.useLayoutEffect)(() => {
+ const list = listRef.current;
+ if (!list) return;
+ const next = /* @__PURE__ */ new Map();
+ const still = reducedMotion() || tops.current.layout !== layout;
+ for (const row of list.querySelectorAll("[data-bot-id],[data-room-id],[data-agent-id]")) {
+ const id = row.dataset.botId ?? row.dataset.roomId ?? row.dataset.agentId;
+ const top = row.offsetTop;
+ next.set(id, top);
+ const before = tops.current.map.get(id);
+ if (!still && before !== void 0 && Math.abs(before - top) > 0.5) {
+ row.animate([{ transform: `translateY(${before - top}px)` }, { transform: "none" }], SPRING_GLIDE);
+ }
+ }
+ tops.current = { layout, map: next };
+ }, [layout, key]);
+}
+function LeftColumn({ mode, width, onGrip, leaving, children }) {
+ return (0, import_react_dom5.createPortal)((0, import_react32.createElement)(
+ "div",
+ { className: "bt-leftcol", "data-left": mode, "data-leaving": leaving || void 0, "aria-hidden": leaving || void 0, style: { width: `${width}px` } },
+ children,
+ (0, import_react32.createElement)("div", { className: "bt-leftcol-grip", role: "separator", "aria-orientation": "vertical", "aria-label": t("Resize sidebar"), title: t("Resize sidebar"), onPointerDown: onGrip })
+ ), document.body);
+}
+function TitleToggle({ hidden, onToggle }) {
+ if (typeof document === "undefined") return null;
+ const titlebar = document.documentElement.hasAttribute("data-windows-titlebar");
+ if (!titlebar && !hidden) return null;
+ const label = t(hidden ? "Expand sidebar" : "Collapse sidebar");
+ return (0, import_react_dom5.createPortal)((0, import_react32.createElement)("button", {
+ type: "button",
+ className: titlebar ? "bt-title-toggle" : "bt-round bt-title-toggle",
+ "aria-label": label,
+ title: label,
+ onClick: onToggle
+ }, (0, import_react32.createElement)(SidebarIcon)), document.body);
+}
+var bootHint = () => {
+ const last = clientErrors().at(-1)?.text;
+ return last === void 0 ? t("The Bot team could not start. The engine’s startup output — its console, or the app’s startup error box — has the cause.") : t("The Bot team could not start. {error}. The engine’s startup output — its console, or the app’s startup error box — has the cause.", { error: last });
+};
+function TeamSidebar(props) {
+ const { wide, useRoster, useUi, useSessions, actions } = props;
+ const listRef = (0, import_react32.useRef)(null);
const roster = useRoster((value) => value);
- const bot = roster.byId[sessionId];
- const [busy, setBusy] = (0, import_react27.useState)("");
- const [error, setError] = (0, import_react27.useState)("");
- const shown = Boolean(bot) && currentPart(bot) === sessionId && roster.ready;
- (0, import_react27.useEffect)(() => {
- if (shown) void actions.refreshModels?.();
- }, [shown, sessionId]);
- if (!bot || currentPart(bot) !== sessionId || !roster.ready) return null;
- const models = roster.models ?? [];
- const usable = models.filter((model) => !model.needsKey);
- const lost = bot.model ? !models.some((model) => model.ref === bot.model) : false;
- if (bot.model && (!lost || models.length === 0)) return null;
- const keyFor = usable.length === 0 && actions.setProviderKey ? models.find((model) => model.needsKey) : void 0;
- const manage = manageModels(actions);
- const pick2 = (ref) => {
- setBusy(ref);
- setError("");
- void Promise.resolve(actions.updateBot(bot.id, { model: ref })).catch((failure) => {
- setError(failure?.message ?? String(failure));
- void actions.refreshModels?.();
- }).finally(() => setBusy(""));
+ const markedUnread = useUi((value) => value.unread);
+ const leftDrawer = useUi((value) => value.leftDrawer === true);
+ const details = useUi((value) => value.details ?? null);
+ const view = useUi((value) => value.view ?? "details");
+ const panelYield = useUi((value) => value.panelYield === true);
+ const bootFailed = useUi((value) => value.bootFailed === true);
+ props.useRegistry((value) => value);
+ const frameSnap = props.useFrame ? props.useFrame((value) => value) : { viewport: typeof window === "undefined" ? 0 : window.innerWidth, sidebarWidth: FALLBACK_SIDEBAR_WIDTH, collapsedWidth: 0 };
+ const pref = props.useSidebarPref ? props.useSidebarPref((value) => value) : "open";
+ const layout = frameLayout({
+ viewport: frameSnap.viewport,
+ sidebarWidth: frameSnap.sidebarWidth,
+ pref,
+ drawer: leftDrawer,
+ panel: details ? { view, yielded: panelYield } : null
+ });
+ const [drag, setDrag] = (0, import_react32.useState)(null);
+ const mode = drag?.left ?? layout.left;
+ const [held, leaving] = useLinger(mode === "hidden" ? null : mode, SPRING_SHAPE.duration);
+ const shown = held ?? mode;
+ const wideContent = shown !== "rail";
+ const updated = useSessions((list) => {
+ const stamps = {};
+ for (const id of list.ids) stamps[id] = list.byId[id]?.updatedAt ?? 0;
+ return JSON.stringify(stamps);
+ });
+ const order = (0, import_react32.useMemo)(() => {
+ const stamps = JSON.parse(updated);
+ const entries2 = [
+ ...roster.bots.filter((bot) => bot.id !== roster.mainBotId).map((bot) => ({ kind: "bot", item: bot, at: stamps[currentPart(bot)] ?? bot.createdAt })),
+ ...roster.rooms.map((room2) => ({ kind: "room", item: room2, at: stamps[room2.id] ?? room2.createdAt })),
+ // The Agent sorts by its most recent Session, falling back to when it was added.
+ ...(roster.agents ?? []).map((agent) => ({ kind: "agent", item: agent, at: Math.max(0, ...agent.sessions.map((id) => stamps[id] ?? 0)) || agent.createdAt }))
+ ];
+ return entries2.sort((a, b) => Number(Boolean(b.item.pinned)) - Number(Boolean(a.item.pinned)) || b.at - a.at);
+ }, [roster, updated]);
+ const main = roster.byId[roster.mainBotId];
+ useListGlide(listRef, wideContent, order.map((entry) => entry.item.id).join(","));
+ useLandOnMainBot(roster, useSessions, actions);
+ useReportReady(roster.ready, roster);
+ const openWidth = drag?.width ?? frameSnap.sidebarWidth;
+ const ourWidth = shown === "rail" ? RAIL_WIDTH : openWidth;
+ const pushed = mode === "open" ? openWidth : mode === "hidden" ? 0 : RAIL_WIDTH;
+ (0, import_react32.useLayoutEffect)(() => {
+ if (typeof document === "undefined") return;
+ chatRoom.setLeft(Math.max(0, pushed - (frameSnap.collapsedWidth ?? 0)));
+ }, [pushed, frameSnap.collapsedWidth]);
+ (0, import_react32.useEffect)(() => () => {
+ if (typeof document !== "undefined") chatRoom.setLeft(null);
+ }, []);
+ const settleTimer = (0, import_react32.useRef)(0);
+ const springTimer = (0, import_react32.useRef)(0);
+ const startDrag = (event) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ clearTimeout(settleTimer.current);
+ clearTimeout(springTimer.current);
+ const grip = event.currentTarget;
+ const column = grip.parentElement;
+ delete column.dataset.folding;
+ grip.setPointerCapture?.(event.pointerId);
+ chatRoom.hold(true);
+ const columns2 = chatRoom.columns();
+ for (const col of columns2) col.style.setProperty("transition", "none", "important");
+ const offLeft = frameSnap.collapsedWidth ?? 0;
+ let last = null;
+ let liveLeft = mode;
+ let done = false;
+ const write = (at) => {
+ const width = at.left === "rail" ? RAIL_WIDTH : at.width;
+ column.style.width = `${width}px`;
+ column.style.setProperty("--bt-lc-w", `${width}px`);
+ const push = Math.max(0, (at.left === "open" ? width : RAIL_WIDTH) - offLeft);
+ for (const col of columns2) col.style.setProperty("margin-left", `${push}px`, "important");
+ };
+ let springUntil = 0;
+ const springOff = () => {
+ springUntil = 0;
+ delete column.dataset.folding;
+ for (const col of columns2) col.style.setProperty("transition", "none", "important");
+ };
+ const springOn = () => {
+ column.dataset.folding = "";
+ for (const col of columns2) col.style.setProperty("transition", `margin-left ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing}`, "important");
+ springUntil = performance.now() + SPRING_SHAPE.duration;
+ clearTimeout(springTimer.current);
+ springTimer.current = setTimeout(springOff, SPRING_SHAPE.duration);
+ };
+ const track = (x) => {
+ last = dragColumn(x, window.innerWidth);
+ if (last.left !== liveLeft) {
+ liveLeft = last.left;
+ if (!reducedMotion()) springOn();
+ setDrag(last);
+ }
+ write(last);
+ };
+ const onMove = (move) => track(move.clientX);
+ const finish = () => {
+ clearTimeout(springTimer.current);
+ if (column.isConnected && last !== null) chatRoom.setLeft(Math.max(0, (last.left === "open" ? last.width : RAIL_WIDTH) - offLeft));
+ for (const col of columns2) {
+ col.style.removeProperty("margin-left");
+ col.style.removeProperty("transition");
+ }
+ column.style.removeProperty("--bt-lc-w");
+ delete column.dataset.folding;
+ chatRoom.hold(false);
+ };
+ const ends = ["pointerup", "pointercancel", "lostpointercapture"];
+ const onEnd = (end) => {
+ if (done) return;
+ done = true;
+ if (end.type === "pointerup") track(end.clientX);
+ grip.removeEventListener("pointermove", onMove);
+ for (const name of ends) grip.removeEventListener(name, onEnd);
+ setDrag(null);
+ if (last === null) {
+ finish();
+ return;
+ }
+ actions.setPanelYield?.(false);
+ if (last.left === "rail") {
+ actions.setLeftDrawer?.(false);
+ actions.setSidebarPref?.("rail");
+ } else {
+ actions.setSidebarWidth?.(last.width);
+ actions.setSidebarPref?.("open");
+ actions.setLeftDrawer?.(last.left === "drawer");
+ }
+ if (springUntil === 0) finish();
+ else settleTimer.current = setTimeout(finish, Math.max(0, springUntil - performance.now()) + 60);
+ };
+ grip.addEventListener("pointermove", onMove);
+ for (const name of ends) grip.addEventListener(name, onEnd);
+ };
+ const dsh = (0, import_react32.useRef)(null);
+ const requested = (0, import_react32.useRef)(false);
+ const requestLapse = (0, import_react32.useRef)(0);
+ const [lapsed, setLapsed] = (0, import_react32.useState)(0);
+ (0, import_react32.useEffect)(() => () => clearTimeout(requestLapse.current), []);
+ const resizedAt = (0, import_react32.useRef)(0);
+ (0, import_react32.useEffect)(() => {
+ const onResize = () => {
+ resizedAt.current = performance.now();
+ };
+ window.addEventListener("resize", onResize);
+ return () => window.removeEventListener("resize", onResize);
+ }, []);
+ const quiet = (on) => {
+ if (on) document.documentElement.setAttribute("data-bt-collapsing", "");
+ else document.documentElement.removeAttribute("data-bt-collapsing");
+ };
+ (0, import_react32.useEffect)(() => () => quiet(false), []);
+ (0, import_react32.useLayoutEffect)(() => {
+ if (typeof document === "undefined" || typeof actions.toggleSidebar !== "function") return void 0;
+ const collapsed = dshCollapsed() ?? !wide;
+ const prev = dsh.current;
+ const viewport = window.innerWidth;
+ dsh.current = { collapsed, viewport };
+ if (prev !== null && collapsed !== prev.collapsed) {
+ if (requested.current) requested.current = false;
+ else if (!collapsed && userSidebarToggle({ before: prev, after: { collapsed, viewport }, sinceResize: performance.now() - resizedAt.current })) {
+ toggleRef.current();
+ }
+ }
+ if (collapsed) {
+ requested.current = false;
+ quiet(false);
+ return void 0;
+ }
+ if (requested.current) return void 0;
+ requested.current = true;
+ quiet(true);
+ actions.toggleSidebar();
+ clearTimeout(requestLapse.current);
+ requestLapse.current = setTimeout(() => {
+ requested.current = false;
+ quiet(false);
+ setLapsed((value) => value + 1);
+ }, 300);
+ return void 0;
+ }, [wide, frameSnap.viewport, lapsed]);
+ (0, import_react32.useEffect)(() => {
+ if (mode !== "drawer") return void 0;
+ const onDown = (event) => {
+ if (event.target instanceof Element && event.target.closest(".bt-leftcol")) return;
+ actions.setLeftDrawer?.(false);
+ };
+ const onKey = (event) => {
+ if (event.key !== "Escape") return;
+ event.stopPropagation();
+ actions.setLeftDrawer?.(false);
+ };
+ window.addEventListener("mousedown", onDown);
+ window.addEventListener("keydown", onKey, true);
+ return () => {
+ window.removeEventListener("mousedown", onDown);
+ window.removeEventListener("keydown", onKey, true);
+ };
+ }, [mode]);
+ const navigate = (open, id) => {
+ const result = open(id);
+ if (leftDrawer) actions.setLeftDrawer?.(false);
+ return result;
};
- const text = lost ? t("{model} is not available anymore. Pick another model for me.", { model: bot.model.split("/").slice(1).join("/") }) : keyFor ? t("Hi, I'm {name}. I need a {provider} API key before I can start.", { name: bot.name, provider: keyFor.providerName ?? keyFor.provider }) : usable.length === 0 ? t("Hi, I'm {name}. I don't have a model yet. How do you want to set one up?", { name: bot.name }) : t("Hi, I'm {name}. Pick a model for me first. You can change it later in my details.", { name: bot.name });
- const choices = usable.length === 0 ? setupChoices(actions).map(([label, run2]) => (0, import_react27.createElement)("button", { key: label, type: "button", className: "bt-model-chip", onClick: run2 }, label)) : [
- ...groupModels(usable).map(([provider, list]) => (0, import_react27.createElement)(
- "div",
- { key: list[0].provider ?? provider, className: "bt-model-choice-group", role: "group", "aria-label": provider },
- (0, import_react27.createElement)("div", { className: "bt-model-choice-provider", "aria-hidden": true }, provider),
- (0, import_react27.createElement)("div", { className: "bt-model-choice-chips" }, list.map((model) => (0, import_react27.createElement)("button", {
- key: model.ref,
- type: "button",
- className: "bt-model-chip",
- disabled: busy !== "",
- "aria-busy": busy === model.ref || void 0,
- "aria-label": `${model.name} · ${provider}`,
- title: model.ref === roster.defaultModel ? `${model.ref} · ${t("Harness default")}` : model.ref,
- onClick: () => pick2(model.ref)
- }, model.name, busy === model.ref ? (0, import_react27.createElement)("span", { className: "bt-model-spin", "aria-label": t("Saving…") }) : null)))
- )),
- manage ? (0, import_react27.createElement)("button", { key: "manage", type: "button", className: "bt-model-chip bt-model-chip-quiet", onClick: manage }, (0, import_react27.createElement)(SlidersIcon), t("Manage models")) : null
- ];
- return (0, import_react27.createElement)(
- "div",
- { className: "bt-model-dock" },
- (0, import_react27.createElement)(
- "div",
- { className: "bt-astack", "data-lead": "" },
- (0, import_react27.createElement)(
- "div",
- { className: "bt-msg" },
- (0, import_react27.createElement)(
- "div",
- { className: "bt-msg-line" },
- (0, import_react27.createElement)(BotMark, { bot, size: 22 }),
- (0, import_react27.createElement)("div", { className: "bt-bubble" }, text)
- )
- )
- ),
- keyFor ? (0, import_react27.createElement)(ModelKeyCard, { key: keyFor.provider, model: keyFor, actions }) : (0, import_react27.createElement)("div", { className: "bt-model-chips", role: "group", "aria-label": t("Choose a model") }, choices),
- error ? (0, import_react27.createElement)("div", { className: "bt-secret-error bt-model-error", role: "alert" }, error) : null
- );
-}
-var DEEPSEEK_KEYS_URL = "https://platform.deepseek.com/api_keys";
-function ModelKeyCard({ model, actions, onSaved }) {
- const [value, setValue] = (0, import_react27.useState)("");
- const [busy, setBusy] = (0, import_react27.useState)(false);
- const [error, setError] = (0, import_react27.useState)("");
- const label = t("{provider} API key", { provider: model.providerName ?? model.provider });
- const ready = value.trim() !== "" && !busy;
- const save = () => {
- if (!ready) return;
- setBusy(true);
- setError("");
- void Promise.resolve(actions.setProviderKey(model.provider, value)).then(() => {
- setValue("");
- onSaved?.();
- }, (failure) => setError(hostText(failure?.message ?? String(failure)))).finally(() => setBusy(false));
+ const rowActions = {
+ ...actions,
+ openSession: (id) => navigate(actions.openSession, id),
+ openAgent: (id) => navigate(actions.openAgent, id),
+ openAgentSession: (id) => navigate(actions.openAgentSession, id),
+ newAgentSession: (id) => navigate(actions.newAgentSession, id)
};
- const official = model.provider === "deepseek-official";
- return (0, import_react27.createElement)(
+ const rowProps = { roster, actions: rowActions, useSessions, useUi, useSessionStatus: props.useSessionStatus, useSessionRetainInfo: props.useSessionRetainInfo, useActivity: props.useActivity, useWork: props.useWork, wide: wideContent };
+ const typeToSearch = (event) => {
+ if (event.defaultPrevented || event.key.length !== 1 || event.key === " " || event.metaKey || event.ctrlKey || event.altKey || event.nativeEvent.isComposing) return;
+ if (event.target instanceof Element && event.target.closest("input,textarea,[contenteditable]")) return;
+ event.preventDefault();
+ actions.openPalette(event.key);
+ };
+ const onToggle = () => actions.toggleLeftHidden?.();
+ const toggleRef = (0, import_react32.useRef)(onToggle);
+ toggleRef.current = onToggle;
+ (0, import_react32.useEffect)(() => {
+ const onKey = (event) => {
+ if (event.defaultPrevented || event.isComposing || !pressesShellShortcut(event, "sidebar.left.toggle")) return;
+ if (event.target instanceof Element && event.target.closest(".xterm")) return;
+ if (document.querySelector('[aria-modal="true"]')) return;
+ event.preventDefault();
+ event.stopPropagation();
+ toggleRef.current();
+ };
+ document.addEventListener("keydown", onKey, true);
+ return () => document.removeEventListener("keydown", onKey, true);
+ }, []);
+ const top = wideContent ? (0, import_react32.createElement)(
"div",
- { className: "bt-q bt-model-key", role: "group", "aria-label": label },
- (0, import_react27.createElement)("div", { className: "bt-model-key-title" }, (0, import_react27.createElement)(KeyIcon), label),
- (0, import_react27.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react27.createElement)(MaskedInput, { value, onChange: setValue, onEnter: save, label, autoFocus: true })),
- official ? (0, import_react27.createElement)(
- "div",
- { className: "bt-model-key-help" },
- (0, import_react27.createElement)("a", { className: "bt-model-key-link", href: DEEPSEEK_KEYS_URL, target: "_blank", rel: "noopener noreferrer" }, t("Create a key on the DeepSeek platform ↗")),
- (0, import_react27.createElement)("span", { className: "bt-model-key-note" }, t("The API is billed by usage; the account needs a balance first."))
- ) : null,
- error ? (0, import_react27.createElement)("div", { className: "bt-secret-error", role: "alert" }, error) : null,
- (0, import_react27.createElement)(
- "div",
- { className: "bt-q-foot" },
- actions.openModels ? (0, import_react27.createElement)("button", { type: "button", className: "bt-q-btn bt-model-key-other", onClick: actions.openModels }, t("Another provider")) : null,
- (0, import_react27.createElement)("button", { type: "button", className: "bt-q-submit", disabled: !ready, onClick: save }, busy ? t("Saving…") : t("Save"))
- )
+ { className: "bt-side-top" },
+ (0, import_react32.createElement)("span", { className: "bt-brand" }, (0, import_react32.createElement)(BrandName)),
+ (0, import_react32.createElement)(UpdateButton, { useUpdate: props.useUpdate, actions }),
+ (0, import_react32.createElement)("button", { type: "button", className: "bt-round", "aria-label": t("Search"), title: t("Search"), onClick: () => actions.openPalette() }, (0, import_react32.createElement)(SearchIcon)),
+ (0, import_react32.createElement)("button", { type: "button", className: "bt-round", "aria-label": t("New…"), title: t("New…"), onClick: () => actions.openNewChat("new") }, (0, import_react32.createElement)(PlusIcon)),
+ (0, import_react32.createElement)("button", { type: "button", className: "bt-round bt-side-collapse", "aria-label": t("Collapse sidebar"), title: t("Collapse sidebar"), onClick: onToggle }, (0, import_react32.createElement)(SidebarIcon))
+ ) : (0, import_react32.createElement)(
+ "div",
+ { className: "bt-rail-top" },
+ (0, import_react32.createElement)(UpdateButton, { useUpdate: props.useUpdate, actions }),
+ (0, import_react32.createElement)("button", { type: "button", className: "bt-round bt-side-collapse", "aria-label": t("Collapse sidebar"), title: t("Collapse sidebar"), onClick: onToggle }, (0, import_react32.createElement)(SidebarIcon)),
+ main ? (0, import_react32.createElement)(BotRow, { ...rowProps, bot: main, marked: markedUnread[main.id] === true }) : roster.ready ? null : (0, import_react32.createElement)("div", { className: "bt-hint" }, bootFailed ? bootHint() : t("Setting up your Main Bot…")),
+ (0, import_react32.createElement)("span", { className: "bt-rail-sep", "aria-hidden": true })
+ );
+ const foot = wideContent ? (0, import_react32.createElement)("div", { className: "bt-leftcol-foot" }, (0, import_react32.createElement)(AccountLauncher, { seat: false, actions })) : (0, import_react32.createElement)(
+ "div",
+ { className: "bt-leftcol-foot bt-leftcol-foot-rail" },
+ (0, import_react32.createElement)("button", { type: "button", className: "bt-round", "aria-label": t("New…"), title: t("New…"), onClick: () => actions.openNewChat("new") }, (0, import_react32.createElement)(PlusIcon)),
+ (0, import_react32.createElement)(AccountLauncher, { seat: false, actions })
+ );
+ const content = (0, import_react32.createElement)(
+ "div",
+ { className: wideContent ? "bt-side" : "bt-side bt-rail", onKeyDown: typeToSearch },
+ top,
+ wideContent && roster.readOnly ? (0, import_react32.createElement)("div", { className: "bt-hint bt-read-only", role: "status" }, hostText(roster.readOnly)) : null,
+ (0, import_react32.createElement)(
+ "div",
+ { ref: listRef, className: "bt-list", role: "region", "aria-label": t("Bot list") },
+ wideContent ? main ? (0, import_react32.createElement)(BotRow, { ...rowProps, bot: main, marked: markedUnread[main.id] === true }) : roster.ready ? null : (0, import_react32.createElement)("div", { className: "bt-hint" }, bootFailed ? bootHint() : t("Setting up your Main Bot…")) : null,
+ order.map((entry) => entry.kind === "bot" ? (0, import_react32.createElement)(BotRow, { key: entry.item.id, ...rowProps, bot: entry.item, marked: markedUnread[entry.item.id] === true }) : entry.kind === "room" ? (0, import_react32.createElement)(RoomRow, { key: entry.item.id, ...rowProps, room: entry.item, marked: markedUnread[entry.item.id] === true }) : (0, import_react32.createElement)(AgentRow, { key: entry.item.id, ...rowProps, agent: entry.item, marked: markedUnread[entry.item.id] === true }))
+ ),
+ foot
+ );
+ return (0, import_react32.createElement)(
+ import_react32.Fragment,
+ null,
+ (0, import_react32.createElement)(TitleToggle, { hidden: mode === "hidden", onToggle }),
+ shown === "hidden" ? null : (0, import_react32.createElement)(LeftColumn, { mode: shown, width: ourWidth, onGrip: startDrag, leaving }, content)
);
}
-var manageModels = (actions) => actions.openModels ?? actions.openHarnessModels ?? actions.openHarnessSettings;
-function setupChoices(actions) {
- const custom = manageModels(actions);
- return [
- actions.canSignIn?.() ? [t("Sign in to DeepSeek"), () => actions.signIn()] : null,
- actions.openHarnessOnboarding ? [t("Enter a DeepSeek API key"), () => actions.openHarnessOnboarding("deepseek-official")] : null,
- custom ? [t("Open settings to set up a custom model"), () => custom()] : null
- ].filter(Boolean);
-}
-function DeepSeekSignIn({ useUi, actions }) {
- const open = useUi((state) => state.signIn);
- const entry = open ? actions.signInEntry?.() : null;
- if (!entry) return null;
- return (0, import_react27.createElement)(SignInHost, { key: open, entry, actions });
-}
-function SignInHost({ entry, actions }) {
- const [ops] = (0, import_react27.useState)(() => entry.inject?.() ?? {});
- const close = () => actions.closeSignIn();
- const useHook = (source) => (selector) => (0, import_react27.useSyncExternalStore)(source.subscribe, () => selector(source.getSnapshot()));
- const [hooks] = (0, import_react27.useState)(() => ({ useAccount: useHook(ops.hooks.account), useTheme: useHook(ops.hooks.theme) }));
- return (0, import_react27.createElement)(entry.component, {
- ...ops,
- ...hooks,
- t: actions.accountT(),
- complete: close,
- useApiKey: () => {
- close();
- actions.openHarnessOnboarding("deepseek-official");
- }
- });
-}
-var MODEL_CSS = `
-.bt-model-trigger{display:inline-flex;align-items:center;gap:8px;max-width:100%;min-width:0;height:auto;min-height:32px;padding:4px 8px 4px 10px;border:0;border-radius:8px;background:var(--bt-hover);color:var(--bt-ink);font:inherit;text-align:left;cursor:pointer;transition:background-color .12s ease}
-.bt-model-trigger:hover,.bt-model-trigger[aria-expanded=true]{background:var(--bt-active)}
-.bt-model-trigger:focus-visible{outline:2px solid var(--bt-accent);outline-offset:1px}
-.bt-model-trigger[data-missing] .bt-model-provider{color:var(--bt-danger)}
-.bt-model-trigger[data-wide]{display:flex;width:100%;min-height:48px;padding:7px 12px;justify-content:space-between;border-radius:12px;background:var(--bt-card);box-shadow:inset 0 0 0 1px var(--bt-line)}
-.bt-model-trigger[data-wide]:hover,.bt-model-trigger[data-wide][aria-expanded=true]{background:var(--bt-hover)}
-.bt-model-copy{display:flex;flex-direction:column;min-width:0}
-.bt-model-name{font-size:13px;line-height:18px;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
-.bt-model-provider{font-size:11px;line-height:14px;color:var(--bt-ink-3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
-.bt-model-caret{flex:none;color:var(--bt-ink-3);transition:${spring(SPRING_SHAPE, "transform")}}
-.bt-model-trigger[aria-expanded=true] .bt-model-caret{transform:rotate(180deg)}
-.bt-model-menu{overflow-y:auto;scrollbar-width:thin}
-.bt-model-menu:not(.bt-folder-menu){padding:0;overflow:hidden;display:flex;flex-direction:column;gap:0}
-.bt-model-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;scrollbar-width:thin;overscroll-behavior:contain;padding:6px;display:flex;flex-direction:column;gap:2px}
-.bt-model-foot{flex:none;display:flex;flex-direction:column;gap:2px;padding:4px 6px 6px;border-top:.5px solid var(--bt-line-2)}
-.bt-effort-bar{display:flex;flex-direction:column;gap:6px;padding:4px 6px 5px}
-.bt-effort-head{display:flex;align-items:center;justify-content:space-between;gap:8px;height:18px;padding:0 2px}
-.bt-effort-label{font-size:11px;line-height:14px;font-weight:500;color:var(--bt-ink-3)}
-.bt-effort-meta{display:inline-flex;align-items:center;gap:5px;min-width:0}
-.bt-effort-tag{font-size:11px;line-height:14px;color:var(--bt-ink-3)}
-.bt-effort-val{font-size:12px;line-height:16px;font-weight:600;color:var(--bt-accent);white-space:nowrap}
-.bt-menu button.bt-effort-reset{flex:none;position:relative;width:28px;height:28px;min-height:0;margin:-5px;padding:0;border:0;border-radius:50%;background:transparent;color:var(--bt-ink-2);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;animation:bt-check-pop ${SPRING_POP.duration}ms ${SPRING_POP.easing};transition:color .12s ease}
-.bt-menu button.bt-effort-reset::before{content:"";position:absolute;inset:5px;border-radius:50%;background:var(--bt-hover);transition:background-color .12s ease}
-.bt-menu button.bt-effort-reset svg{position:relative;width:11px;height:11px;margin:0}
-.bt-menu button.bt-effort-reset:hover:not(:disabled){color:var(--bt-ink)}
-.bt-menu button.bt-effort-reset:hover:not(:disabled)::before{background:var(--bt-active)}
-.bt-menu button.bt-effort-reset:disabled{opacity:.35;cursor:default}
-.bt-menu button.bt-effort-reset:disabled::before{background:none}
-.bt-menu button.bt-effort-reset:focus-visible{outline:2px solid var(--bt-accent);outline-offset:1px}
-.bt-effort-track{position:relative;height:28px;margin:-3px 0;border-radius:999px;cursor:pointer;user-select:none;touch-action:none}
-.bt-effort-track::before{content:"";position:absolute;left:0;right:0;top:3px;bottom:3px;border-radius:999px;background:var(--bt-hover);box-shadow:inset 0 0 0 .5px var(--bt-line)}
-.bt-effort-track:focus-visible{outline:2px solid var(--bt-accent);outline-offset:2px}
-.bt-effort-fill{position:absolute;left:0;top:3px;bottom:3px;width:calc(22px + (100% - 22px) * var(--bt-effort-p,0));border-radius:999px;background:linear-gradient(90deg,color-mix(in srgb,var(--bt-accent) 76%,var(--bt-main)),var(--bt-accent));transition:${spring(SPRING_TAP, "width")}}
-.bt-effort-dot{position:absolute;top:50%;left:calc(11px + (100% - 22px) * var(--bt-dot-p,0));width:4px;height:4px;margin:-2px 0 0 -2px;border-radius:50%;background:color-mix(in srgb,var(--bt-ink-3) 45%,transparent);pointer-events:none;transition:background-color .12s ease}
-.bt-effort-dot[data-filled]{background:color-mix(in srgb,var(--bt-accent-ink) 65%,transparent)}
-.bt-effort-knob{position:absolute;top:5px;left:calc(11px + (100% - 22px) * var(--bt-effort-p,0) - 9px);width:18px;height:18px;border-radius:50%;background:var(--bt-accent-ink);box-shadow:0 1px 3px rgba(0,0,0,.2),0 0 0 .5px rgba(0,0,0,.06);pointer-events:none;transition:${spring(SPRING_TAP, "left")},${spring(SPRING_TAP, "scale")}}
-.bt-effort-track[data-dragging] .bt-effort-fill,.bt-effort-track[data-dragging] .bt-effort-knob{transition:none}
-.bt-effort-track:hover .bt-effort-knob,.bt-effort-track[data-dragging] .bt-effort-knob{scale:1.08}
-.bt-model-group{flex:none;padding:8px 8px 2px;font-size:11px;line-height:14px;font-weight:500;color:var(--bt-ink-3);text-transform:none}
-.bt-model-group:first-child{padding-top:2px}
-.bt-model-tick{flex:none;width:16px;height:16px;display:inline-flex;color:var(--bt-ink-2)}
-.bt-model-tick svg{animation:bt-check-pop ${SPRING_POP.duration}ms ${SPRING_POP.easing} 60ms backwards}
-.bt-model-none{padding:8px;font-size:13px;line-height:18px;color:var(--bt-ink-2)}
-/* DSH centers the message column inside its scroll padding, which can sit a few px off this dock's center; the side shadows keep the band over the column's edges. */
-.bt-model-dock{width:100%;max-width:var(--dsh-chat-content-width,748px);margin:0 auto;display:flex;flex-direction:column;align-items:flex-start;gap:8px;padding:0 0 10px;box-sizing:border-box;background:var(--bt-main);box-shadow:-12px 0 0 var(--bt-main),12px 0 0 var(--bt-main);animation:bt-model-in ${SPRING_POP.duration}ms ${SPRING_POP.easing} backwards}
-/* The scroll box clips at its padding edge, so 3px of padding keeps the chips' focus rings visible; the negative margins cancel it so the chips stay in place. */
-.bt-model-chips{display:flex;flex-wrap:wrap;gap:6px;box-sizing:border-box;padding:3px;margin:-3px 0 -3px 27px;max-width:min(566px,calc(100% - 27px));max-height:min(246px,calc(36vh + 6px));max-height:min(246px,calc(36dvh + 6px));overflow-y:auto;scrollbar-width:thin}
-.bt-model-choice-group{display:flex;flex-direction:column;gap:6px;width:100%;min-width:0}
-.bt-model-choice-provider{padding-top:4px;font-size:12px;line-height:16px;font-weight:500;color:var(--bt-ink-2);overflow-wrap:anywhere}
-.bt-model-choice-chips{display:flex;flex-wrap:wrap;gap:6px}
-.bt-model-chip{display:inline-flex;align-items:center;gap:6px;min-height:30px;padding:5px 12px;border:.5px solid var(--bt-line-2);border-radius:999px;background:var(--bt-surface,transparent);color:var(--bt-ink);font:inherit;font-size:13px;line-height:18px;cursor:pointer;transition:background-color .12s ease,border-color .12s ease}
-.bt-model-chip:hover:not(:disabled){background:var(--bt-hover)}
-.bt-model-chip:focus-visible{outline:2px solid var(--bt-accent);outline-offset:1px}
-.bt-model-chip-quiet{color:var(--bt-ink-2)}
-.bt-model-chip svg{width:14px;height:14px}
-.bt-model-chip:disabled{cursor:default}
-.bt-model-chip:disabled:not([aria-busy]){opacity:.5}
-.bt-model-error{margin-left:30px}
-.bt-q.bt-model-key{margin:0 0 0 30px;width:min(480px,calc(100% - 30px));gap:10px}
-.bt-model-key-title{display:flex;align-items:center;gap:6px;font-size:13px;line-height:18px;font-weight:500;color:var(--bt-ink-2)}
-.bt-model-key-title svg{flex:none;width:16px;height:16px}
-.bt-model-key .bt-q-foot{margin-top:2px}
-.bt-model-key-help{display:flex;flex-direction:column;gap:2px;font-size:12px;line-height:17px;color:var(--bt-ink-2)}
-.bt-model-key-link{align-self:flex-start;color:var(--bt-ink);text-decoration:underline;text-decoration-color:var(--bt-line-2);text-underline-offset:2px}
-.bt-model-key-link:hover{text-decoration-color:currentColor}
-.bt-model-key-link:focus-visible{outline:2px solid var(--bt-accent);outline-offset:1px;border-radius:4px}
-.bt-model-key-other{margin-right:auto}
-@keyframes bt-model-in{from{opacity:0;transform:translateY(6px)}}
-.bt-model-spin{flex:none;width:14px;height:14px;border-radius:50%;border:1.5px solid var(--bt-line-2);border-top-color:var(--bt-ink-2);animation:bt-model-spin .7s linear infinite}
-@keyframes bt-model-spin{to{transform:rotate(360deg)}}
-@media (prefers-reduced-motion:reduce){.bt-model-dock{animation:none}.bt-model-spin{animation-duration:2s}.bt-model-caret,.bt-effort-fill,.bt-effort-knob{transition:none}.bt-model-tick svg{animation:none}}
-`;
-
-// src/client/turn-error.js
-var import_react28 = require("react");
-var OFFICIAL = "deepseek-official";
-var ACCOUNT = "deepseek-account";
-var TOP_UP_URL = "https://platform.deepseek.com/top_up";
-var ACCOUNT_MODELS_WAIT_MS = 2e4;
-var SIGNED_OUT = /* @__PURE__ */ new Set(["ACCOUNT_SIGN_IN_REQUIRED", "ACCOUNT_SIGNED_OUT", "ACCOUNT_TOKEN_INVALID"]);
-var KEY_CODES = /* @__PURE__ */ new Set(["MISSING_CREDENTIAL", "INVALID_CREDENTIAL", "AUTH"]);
-var CREDENTIAL_CODES = /* @__PURE__ */ new Set([...KEY_CODES, ...SIGNED_OUT]);
-function failureText2(code, { name, provider, status }) {
- switch (code) {
- case "MISSING_CREDENTIAL":
- return t("{name}'s model has no API key yet.", { name });
- case "INVALID_CREDENTIAL":
- return t("This API key is not in the right format.");
- case "AUTH":
- return status === void 0 ? t("{provider} did not accept the current API key.", { provider }) : t("{provider} did not accept the current API key ({status}).", { provider, status });
- case "QUOTA":
- return status === void 0 ? t("{provider} is out of balance or quota.", { provider }) : t("{provider} is out of balance or quota ({status}).", { provider, status });
- case "ACCOUNT_QUOTA":
- return t("The DeepSeek account balance is too low.");
- case "ACCOUNT_SIGN_IN_REQUIRED":
- case "ACCOUNT_SIGNED_OUT":
- case "ACCOUNT_TOKEN_INVALID":
- return t("The DeepSeek account sign-in has expired.");
- case "TRANSPORT":
- case "TIMEOUT":
- return t("Could not reach the model service.");
- case "RATE_LIMIT":
- return t("Too many requests. Wait a moment, then try again.");
- case "SERVER":
- return t("The model service failed.");
- case "INTERRUPTED":
- return t("DeepSeek Harness stopped before this turn finished.");
- default:
- return knownFailure(code) ?? t("This turn failed.");
- }
-}
-function fixesFor(code, { canSignIn, official, topUp, onAccount = false }) {
- if (onAccount && KEY_CODES.has(code)) return [];
- if (SIGNED_OUT.has(code)) return canSignIn ? ["sign-in-again"] : ["model"];
- switch (code) {
- case "MISSING_CREDENTIAL":
- return ["key", canSignIn ? "sign-in" : null, "model"].filter(Boolean);
- case "INVALID_CREDENTIAL":
- return ["rekey", "model"];
- case "AUTH":
- return ["rekey", canSignIn ? "use-account" : null, "model"].filter(Boolean);
- case "QUOTA":
- return official ? ["top-up"] : [];
- case "ACCOUNT_QUOTA":
- return topUp ? ["top-up"] : [];
- default:
- return [];
- }
+function UpdateButton({ useUpdate, actions }) {
+ const update = useUpdate((value) => value);
+ const [open, setOpen] = (0, import_react32.useState)(false);
+ const [shown, leaving] = useLinger(open, 120);
+ const [box, setBox] = (0, import_react32.useState)(null);
+ const [error, setError] = (0, import_react32.useState)("");
+ const [dshError, setDshError] = (0, import_react32.useState)("");
+ const button = (0, import_react32.useRef)(null);
+ (0, import_react32.useEffect)(() => {
+ if (!open) return void 0;
+ const onDown = (event) => {
+ if (event.target instanceof Element && (event.target.closest(".bt-update-pop") || button.current?.contains(event.target))) return;
+ setOpen(false);
+ };
+ const onKey = (event) => {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ setOpen(false);
+ button.current?.focus();
+ }
+ };
+ window.addEventListener("mousedown", onDown);
+ window.addEventListener("keydown", onKey, true);
+ return () => {
+ window.removeEventListener("mousedown", onDown);
+ window.removeEventListener("keydown", onKey, true);
+ };
+ }, [open]);
+ const phase = update?.phase ?? "idle";
+ const dsh = update?.dsh;
+ const dshPhase = dsh?.phase ?? "idle";
+ const dshRow = showsDshRow(dsh, update?.app);
+ const tick = useViewport();
+ (0, import_react32.useLayoutEffect)(() => {
+ if (!open) return;
+ const rect = button.current?.getBoundingClientRect();
+ if (rect) setBox({ left: Math.max(8, Math.min(rect.left, window.innerWidth - 288)), top: rect.bottom + 6 });
+ }, [open, tick]);
+ if (!update?.available && !dshRow && phase === "idle" && dshPhase === "idle") return null;
+ const cloudPhase = phase === "installing" || dshPhase === "installing" ? "installing" : phase !== "idle" ? phase : dshPhase;
+ const toggle = () => setOpen((value) => !value);
+ const start = () => {
+ 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…") : dshPhase === "installing" ? t("Updating DSH…") : phase === "installed" ? t("DS Bot {version} is installed. Restart DSH to use it.", { version: update.installed ?? update.latest }) : phase === "updated" ? t("DS Bot {version} is installed.", { 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 ? t("Update DS Bot {version} first.", { version: dsh.blockedBy }) : t("You have {version}.", { version: dsh?.current });
+ return (0, import_react32.createElement)(
+ import_react32.Fragment,
+ null,
+ (0, import_react32.createElement)("button", {
+ 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
+ }, (0, import_react32.createElement)(CloudDownloadIcon, { done: phase === "installed" || phase === "updated" }), phase === "failed" || dshPhase === "failed" ? (0, import_react32.createElement)("span", { className: "bt-update-dot", "aria-hidden": true }) : null),
+ shown && box ? (0, import_react_dom5.createPortal)((0, import_react32.createElement)(
+ "div",
+ { className: "bt-update-pop", role: "dialog", "aria-label": update?.available || phase !== "idle" ? t("DS Bot update") : t("DSH update"), style: box, "data-leaving": leaving || void 0 },
+ update?.available || phase !== "idle" ? (0, import_react32.createElement)(
+ import_react32.Fragment,
+ null,
+ (0, import_react32.createElement)("div", { className: "bt-update-title" }, phase === "installed" || phase === "updated" ? t("Update installed") : t("DS Bot {version}", { version: update.latest })),
+ (0, import_react32.createElement)("div", { className: "bt-update-text" }, phase === "installed" ? t("Restart DSH to start using DS Bot {version}.", { version: update.installed ?? update.latest }) : phase === "updated" ? t("DS Bot {version} is installed.", { version: update.installed ?? update.latest }) : t("You have {version}.", { version: update.current })),
+ message ? (0, import_react32.createElement)("div", { className: "bt-update-error", role: "alert" }, t("The update did not finish: {reason}", { reason: message })) : null,
+ (0, import_react32.createElement)(
+ "div",
+ { className: "bt-update-actions" },
+ update.notesUrl ? (0, import_react32.createElement)("a", { className: "bt-update-notes", href: update.notesUrl, target: "_blank", rel: "noopener noreferrer" }, t("What's new")) : null,
+ phase === "installed" || phase === "updated" ? null : (0, import_react32.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_react32.createElement)(
+ "div",
+ { className: "bt-update-dsh" },
+ (0, import_react32.createElement)("div", { className: "bt-update-title" }, t("DSH {version}", { version: dsh.verified })),
+ (0, import_react32.createElement)("div", { className: "bt-update-text" }, dshText),
+ dshMessage ? (0, import_react32.createElement)("div", { className: "bt-update-error", role: "alert" }, t("The update did not finish: {reason}", { reason: dshMessage })) : null,
+ (0, import_react32.createElement)(
+ "div",
+ { className: "bt-update-actions" },
+ dsh.kind === "app" ? dsh.available ? (0, import_react32.createElement)("button", { type: "button", className: "bt-update-go", onClick: () => void actions.openAppUpdates(dsh.verified).catch(() => {
+ }) }, t("Open updates")) : null : !dsh.available && dshPhase === "idle" ? null : dshPhase === "installed" ? null : (0, import_react32.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
+ );
}
-var retryShown = (code, blocked) => !CREDENTIAL_CODES.has(code) || blocked === void 0;
-var FIX_LABELS = {
- key: () => t("Enter API key"),
- rekey: () => t("Enter the key again"),
- "sign-in": (signedIn) => signedIn ? t("Use the DeepSeek account") : t("Sign in with a DeepSeek account"),
- "use-account": () => t("Use a DeepSeek account instead"),
- "sign-in-again": () => t("Sign in again"),
- model: () => t("Pick another model"),
- "top-up": () => t("Top up ↗")
-};
-var NO_SUBSCRIBE2 = () => () => {
-};
-var NO_VIEW = () => null;
-function useAccountView(actions) {
- const entry = actions.signInEntry?.() ?? null;
- const ops = (0, import_react28.useMemo)(() => entry?.inject?.() ?? {}, [entry]);
- const source = ops.hooks?.account;
- const read = source ? () => source.getSnapshot()?.view ?? null : NO_VIEW;
- return (0, import_react28.useSyncExternalStore)(source?.subscribe ?? NO_SUBSCRIBE2, read, read);
+function YouAvatar() {
+ return (0, import_react32.createElement)(
+ "span",
+ { className: "bt-you-wrap" },
+ (0, import_react32.createElement)("span", { className: "bt-you", "aria-hidden": true }, (0, import_react32.createElement)(GearIcon)),
+ (0, import_react32.createElement)("span", { style: { position: "absolute", width: 1, height: 1, overflow: "hidden", clip: "rect(0 0 0 0)" } }, t("Settings"))
+ );
}
-var topUpOf = (view) => {
- const url = view?.links?.topUpUrl;
- return typeof url === "string" && url.startsWith("https://") ? url : void 0;
-};
-function accountModel(roster) {
- const models = (roster.models ?? []).filter((model) => model.provider === ACCOUNT);
- return (models.find((model) => model.ref === roster.defaultModel) ?? models[0])?.ref;
+var openShellSettings = null;
+var openShellOnboarding = null;
+var shellShortcuts = null;
+function holdShellShortcuts(shortcuts) {
+ shellShortcuts = shortcuts;
+ return () => {
+ if (shellShortcuts === shortcuts) shellShortcuts = null;
+ };
}
-var providerOf = (bot, roster) => {
- const ref = bot?.model ?? bot?.appliedModel;
- if (!ref) return void 0;
- return (roster.models ?? []).find((model) => model.ref === ref)?.provider ?? ref.split("/")[0];
-};
-var KNOWN_PROVIDERS = { "deepseek-official": "DeepSeek", "deepseek-account": "DeepSeek account" };
-var providerName = (roster, provider) => provider === void 0 ? t("The model service") : (roster.models ?? []).find((model) => model.provider === provider)?.providerName ?? (KNOWN_PROVIDERS[provider] ? t(KNOWN_PROVIDERS[provider]) : provider);
-function failureFacts(data, blocked) {
- const facts = [];
- if (data.code) facts.push(["Code", t("Code"), data.code]);
- if (blocked?.status !== void 0) facts.push(["HTTP status", t("HTTP status"), String(blocked.status)]);
- if (blocked?.requestId) facts.push(["Request ID", t("Request ID"), blocked.requestId]);
- if (data.code !== "AUTH" && data.message) facts.push(["Message", t("Provider message"), data.message]);
- return facts;
+function openHarnessSettings() {
+ requestAnimationFrame(() => {
+ if (openShellSettings) {
+ openShellSettings();
+ return;
+ }
+ const desktop = document.querySelector('button[aria-haspopup="menu"][data-signed-out]');
+ if (desktop) openThroughMenu(desktop);
+ else pressSettingsShortcut();
+ });
}
-function TechnicalDetails({ facts }) {
- const [copied, setCopied] = (0, import_react28.useState)(false);
- if (facts.length === 0) return null;
- const copy2 = () => {
- const text = facts.map(([name, , value]) => `${name}: ${value}`).join("\n");
- void navigator.clipboard?.writeText(text).then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 1e3);
- }).catch(() => {
- });
+function openHarnessOnboarding(id) {
+ requestAnimationFrame(() => {
+ if (openShellOnboarding) openShellOnboarding(id);
+ else openHarnessSettings();
+ });
+}
+var MODELS_STEP = "ds-bot-models";
+var MODELS_STEP_ORDER = 1e3;
+function OpenModelsStep({ explicit, complete, openSection }) {
+ (0, import_react32.useEffect)(() => {
+ if (explicit) {
+ if (typeof openSection === "function") openSection("models");
+ else openHarnessSettings();
+ }
+ complete();
+ }, [explicit]);
+ return null;
+}
+function openThroughMenu(trigger) {
+ const before = new Set(document.querySelectorAll('[role="menu"]'));
+ trigger.click();
+ let frames = 0;
+ const look = () => {
+ const menu = [...document.querySelectorAll('[role="menu"]')].find((node) => !before.has(node));
+ const item = menu?.querySelector('button[role="menuitem"]');
+ if (item) item.click();
+ else if (++frames < 30) requestAnimationFrame(look);
+ else pressSettingsShortcut();
};
- return (0, import_react28.createElement)(
- "details",
- { className: "bt-fail-tech" },
- (0, import_react28.createElement)("summary", null, t("Technical details")),
- (0, import_react28.createElement)("dl", null, facts.map(([name, label, value]) => [(0, import_react28.createElement)("dt", { key: `${name}:t` }, label), (0, import_react28.createElement)("dd", { key: `${name}:d` }, value)])),
- (0, import_react28.createElement)("button", { type: "button", className: "bt-mini bt-fail-copy", onClick: copy2 }, copied ? (0, import_react28.createElement)(CheckIcon) : (0, import_react28.createElement)(CopyIcon), copied ? t("Copied") : t("Copy"))
- );
+ requestAnimationFrame(look);
}
-function FailureCell({ node, sessionId, useRoster, useTurnClock, actions }) {
- const roster = useRoster((value) => value);
- const data = node?.data ?? {};
- const bot = roster.byId?.[sessionId];
- const later = useTurnClock((state) => Object.keys(state[sessionId] ?? {}).some((turn) => Number(turn) > data.turn));
- const account = useAccountView(actions);
- const signedIn = account?.status === "credential-stored";
- const topUp = topUpOf(account);
- const [keying, setKeying] = (0, import_react28.useState)(false);
- const [retry, setRetry] = (0, import_react28.useState)("idle");
- const [error, setError] = (0, import_react28.useState)("");
- const [joining, setJoining] = (0, import_react28.useState)(null);
- const blocked = bot?.blocked?.code === data.code ? bot.blocked : void 0;
- const provider = blocked?.provider ?? providerOf(bot, roster);
- const text = failureText2(data.code, { name: bot?.name ?? t("This Bot"), provider: providerName(roster, provider), status: blocked?.status });
- const facts = failureFacts(data, blocked);
- const current = bot !== void 0 && currentPart(bot) === sessionId && !later;
- const moveToAccount = () => {
- const model = accountModel(roster);
- if (model === void 0) {
- actions.showDetails?.(sessionId);
- return;
+function pressSettingsShortcut() {
+ const binding = shellShortcuts?.catalog.getSnapshot().find((row) => row.id === "settings.open")?.binding;
+ if (!binding) return;
+ const held = new Set(binding.modifiers);
+ window.dispatchEvent(new KeyboardEvent("keydown", {
+ code: binding.code,
+ key: binding.code === "Comma" ? "," : "",
+ bubbles: true,
+ cancelable: true,
+ ctrlKey: held.has("control"),
+ altKey: held.has("alt"),
+ shiftKey: held.has("shift"),
+ metaKey: held.has("meta")
+ }));
+}
+function pressesShellShortcut(event, id) {
+ const binding = shellShortcuts?.catalog.getSnapshot().find((row) => row.id === id)?.binding;
+ if (!binding) return false;
+ const held = new Set(binding.modifiers);
+ return event.code === binding.code && event.ctrlKey === held.has("control") && event.altKey === held.has("alt") && event.shiftKey === held.has("shift") && event.metaKey === held.has("meta");
+}
+var NO_SUBSCRIBE = () => () => {
+};
+var NO_SNAPSHOT = () => null;
+function AccountLauncher({ seat = true, settingsOpen, openSettings, openOnboarding, actions }) {
+ const [open, setOpen] = (0, import_react32.useState)(false);
+ (0, import_react32.useLayoutEffect)(() => {
+ if (!seat) return void 0;
+ actions.seatAccount(true);
+ return () => actions.seatAccount(false);
+ }, [seat]);
+ const [box, setBox] = (0, import_react32.useState)(null);
+ const button = (0, import_react32.useRef)(null);
+ const menuRef = (0, import_react32.useRef)(null);
+ (0, import_react32.useEffect)(() => {
+ if (settingsOpen) setOpen(false);
+ }, [settingsOpen]);
+ (0, import_react32.useEffect)(() => {
+ if (!openSettings) return void 0;
+ openShellSettings = openSettings;
+ return () => {
+ if (openShellSettings === openSettings) openShellSettings = null;
+ };
+ }, [openSettings]);
+ (0, import_react32.useEffect)(() => {
+ if (!openOnboarding) return void 0;
+ openShellOnboarding = openOnboarding;
+ return () => {
+ if (openShellOnboarding === openOnboarding) openShellOnboarding = null;
+ };
+ }, [openOnboarding]);
+ (0, import_react32.useEffect)(() => {
+ if (!open) return void 0;
+ const onDown = (event) => {
+ if (event.target instanceof Element && (event.target.closest(".bt-account-menu") || button.current?.contains(event.target))) return;
+ setOpen(false);
+ };
+ const onKey = (event) => {
+ if (stepMenuFocus(menuRef.current, event, button.current)) return;
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ setOpen(false);
+ button.current?.focus();
+ }
+ };
+ window.addEventListener("mousedown", onDown);
+ window.addEventListener("keydown", onKey, true);
+ return () => {
+ window.removeEventListener("mousedown", onDown);
+ window.removeEventListener("keydown", onKey, true);
+ };
+ }, [open]);
+ const signIn = actions.signInEntry?.() ?? null;
+ const ops = (0, import_react32.useMemo)(() => signIn?.inject?.() ?? {}, [signIn]);
+ const accountSource = ops.hooks?.account;
+ const account = (0, import_react32.useSyncExternalStore)(accountSource?.subscribe ?? NO_SUBSCRIBE, accountSource ? () => accountSource.getSnapshot() : NO_SNAPSHOT);
+ const signedIn = signIn !== null && typeof ops.signOut === "function" && account?.view?.status === "credential-stored";
+ const signedOut = signIn !== null && typeof actions.signIn === "function" && account?.view?.status === "signed-out";
+ const accountT = actions.accountT?.() ?? ((key) => key);
+ const [confirm, setConfirm] = (0, import_react32.useState)(null);
+ const [busy, setBusy] = (0, import_react32.useState)(false);
+ const [signOutError, setSignOutError] = (0, import_react32.useState)("");
+ const askSignOut = async () => {
+ setSignOutError("");
+ let state = "none";
+ try {
+ if (await ops.hasRunningAccountTasks?.()) state = "running";
+ } catch {
+ state = "unknown";
}
- if (model === bot.model) return;
- setError("");
- void Promise.resolve(actions.updateBot(bot.id, { model })).catch((failure) => setError(hostText(failure?.message ?? String(failure))));
+ setConfirm(state);
};
- const listed = accountModel(roster);
- (0, import_react28.useEffect)(() => {
- if (joining === null || !signedIn) return void 0;
- if (bot === void 0 || bot.model !== joining.from) {
- setJoining(null);
- return void 0;
- }
- if (listed !== void 0) {
- setJoining(null);
- moveToAccount();
- return void 0;
- }
- void actions.refreshModels?.();
- const timer = setTimeout(() => {
- setJoining(null);
- actions.showDetails?.(sessionId);
- }, ACCOUNT_MODELS_WAIT_MS);
- return () => clearTimeout(timer);
- }, [joining, signedIn, listed]);
- const settled = () => (0, import_react28.createElement)(
- "div",
- { className: "bt-fail", "data-settled": "", role: "status" },
- (0, import_react28.createElement)("div", { className: "bt-fail-head" }, (0, import_react28.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react28.createElement)("span", { className: "bt-fail-text" }, text)),
- (0, import_react28.createElement)(TechnicalDetails, { facts })
- );
- if (!current) return settled();
- const official = provider === OFFICIAL;
- const canSignIn = typeof actions.signIn === "function" && actions.canSignIn?.() === true;
- const keyHere = typeof actions.setProviderKey === "function" && provider !== void 0;
- const keyElsewhere = official && actions.openHarnessOnboarding ? () => actions.openHarnessOnboarding(OFFICIAL) : manageModels(actions);
- const viaAccount = () => {
- if (signedIn) {
- moveToAccount();
- return;
+ const cancelSignOut = () => {
+ setConfirm(null);
+ setSignOutError("");
+ };
+ const runSignOut = async () => {
+ setBusy(true);
+ setSignOutError("");
+ try {
+ await ops.signOut();
+ setConfirm(null);
+ setOpen(false);
+ } catch (error) {
+ setSignOutError(String(error?.message ?? error));
+ } finally {
+ setBusy(false);
}
- setJoining({ from: bot.model });
- actions.signIn();
};
- const runs = {
- key: keyHere ? () => setKeying((value) => !value) : keyElsewhere,
- rekey: keyHere ? () => setKeying((value) => !value) : keyElsewhere,
- "sign-in": viaAccount,
- "use-account": viaAccount,
- "sign-in-again": () => actions.signIn(),
- model: actions.showDetails ? () => actions.showDetails(sessionId) : void 0
+ const tick = useViewport();
+ const anchor = () => {
+ const rect = button.current?.getBoundingClientRect();
+ if (rect) setBox({ left: rect.left, bottom: viewBottom() - rect.top + 5 });
};
- const fixes = fixesFor(data.code, { canSignIn, official, topUp: topUp !== void 0, onAccount: provider === ACCOUNT }).filter((fix) => fix === "top-up" || runs[fix] !== void 0);
- const asked = isHiddenTurn(roster, sessionId, data.turn);
- const retrying = !asked && typeof actions.resume === "function" && retryShown(data.code, blocked);
- const retryFirst = retrying && (fixes.length === 0 || CREDENTIAL_CODES.has(data.code));
- const resume = () => {
- setRetry("busy");
- setError("");
- void Promise.resolve(actions.resume(bot.id)).then(() => setRetry("sent"), (failure) => {
- setRetry("idle");
- setError(hostText(failure?.message ?? String(failure)));
- });
+ (0, import_react32.useLayoutEffect)(() => {
+ if (open) anchor();
+ }, [open, tick]);
+ const toggle = () => {
+ if (!open) anchor();
+ setOpen((value) => !value);
};
- const button = (fix, primary) => {
- const className = primary ? "bt-send bt-fail-go" : "bt-soft bt-soft-sm";
- if (fix === "top-up") {
- return (0, import_react28.createElement)("a", { key: fix, className: `${className} bt-fail-link`, href: data.code === "ACCOUNT_QUOTA" ? topUp : TOP_UP_URL, target: "_blank", rel: "noopener noreferrer" }, FIX_LABELS[fix]());
+ (0, import_react32.useEffect)(() => {
+ if (open) return;
+ setConfirm(null);
+ setSignOutError("");
+ setBusy(false);
+ }, [open]);
+ const openModels = actions.providers ? actions.openModels : actions.openHarnessModels;
+ const groups = [
+ [
+ [t("Usage"), GaugeIcon, () => actions.openSettings("usage")],
+ openModels ? [t("Models and API keys"), SlidersIcon, () => openModels()] : null,
+ [t("Connectors"), ConnectorIcon, () => actions.openConnectors()],
+ [t("Automation tasks"), ClockIcon, () => actions.selectPanel("schedules")],
+ [t("Bot settings"), GearIcon, () => actions.openSettings("general")]
+ ].filter(Boolean)
+ ];
+ if (signedIn) groups.push([[accountT("signOut"), SignOutIcon, askSignOut, void 0, true]]);
+ else if (signedOut) groups.push([[t("Sign in to DeepSeek"), SignInIcon, () => actions.signIn()]]);
+ return (0, import_react32.createElement)(
+ import_react32.Fragment,
+ null,
+ (0, import_react32.createElement)(
+ "button",
+ { ref: button, type: "button", className: "bt-account", "aria-label": t("Account"), "aria-haspopup": "menu", "aria-expanded": open, onClick: toggle },
+ (0, import_react32.createElement)("span", { className: "bt-you", "aria-hidden": true }, (0, import_react32.createElement)(GearIcon))
+ ),
+ open && box ? (0, import_react_dom5.createPortal)((0, import_react32.createElement)(
+ "div",
+ { ref: menuRef, className: "bt-menu bt-menu-up bt-account-menu", role: "menu", "aria-label": t("Account"), style: box },
+ confirm !== null ? (0, import_react32.createElement)(
+ "div",
+ { className: "bt-confirm", role: "alertdialog", "aria-label": accountT("signOut") },
+ (0, import_react32.createElement)("p", { className: "bt-confirm-text" }, accountT(confirm === "running" ? "signOutRunningDescription" : confirm === "unknown" ? "signOutUnknownDescription" : "signOutDescription")),
+ signOutError !== "" ? (0, import_react32.createElement)("p", { className: "bt-confirm-error", role: "alert" }, signOutError) : null,
+ (0, import_react32.createElement)(
+ "div",
+ { className: "bt-confirm-row" },
+ (0, import_react32.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: cancelSignOut }, t("Cancel")),
+ (0, import_react32.createElement)("button", { type: "button", className: "bt-confirm-go", disabled: busy, onClick: () => {
+ void runSignOut();
+ } }, accountT("signOut"))
+ )
+ ) : groups.map((group, index) => (0, import_react32.createElement)(
+ import_react32.Fragment,
+ { key: index },
+ index > 0 ? (0, import_react32.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null,
+ group.map(([label, Icon, run2, hint, stay]) => (0, import_react32.createElement)("button", {
+ key: label,
+ type: "button",
+ role: "menuitem",
+ onClick: () => {
+ if (stay !== true) setOpen(false);
+ void Promise.resolve(run2()).catch((error) => actions.reportError(error, "menu"));
+ }
+ }, (0, import_react32.createElement)(Icon), (0, import_react32.createElement)("span", { className: "bt-menu-label" }, label), hint ? (0, import_react32.createElement)("span", { className: "bt-menu-hint" }, hint) : null))
+ ))
+ ), document.body) : null
+ );
+}
+var readyReported = false;
+function useReportReady(drawn, roster) {
+ (0, import_react32.useEffect)(() => {
+ if (!drawn || readyReported) return;
+ readyReported = true;
+ void Promise.resolve().then(() => {
+ const app = globalThis.dsBotApp;
+ if (typeof app?.ready !== "function") return void 0;
+ let place;
+ try {
+ place = mainAvatarPlace(roster);
+ } catch {
+ place = void 0;
+ }
+ if (place === void 0) return app.ready();
+ const mainId = roster.mainBotId;
+ app.onHandoff?.((from) => {
+ try {
+ glideOnto(mainMarkOf(mainId), from);
+ } catch (error) {
+ quietly("handoff")(error);
+ }
+ });
+ return app.ready(place);
+ }).catch(quietly("app ready"));
+ }, [drawn]);
+}
+function mainMarkOf(id) {
+ if (typeof document === "undefined") return null;
+ const key = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(id) : id;
+ return document.querySelector(`.bt-side [data-bot-id="${key}"] .bt-mark`);
+}
+function mainAvatarPlace(roster) {
+ const main = roster?.byId?.[roster.mainBotId];
+ if (main === void 0 || main.avatar?.image || typeof document === "undefined") return void 0;
+ const look = lookOf(main);
+ if (look.shape !== MAIN_LOOK.shape || look.color !== MAIN_LOOK.color) return void 0;
+ const mark2 = mainMarkOf(main.id);
+ if (!mark2 || mark2.checkVisibility?.({ visibilityProperty: true }) === false) return void 0;
- const box = mark2.getBoundingClientRect();
++ const box = restingBox(mark2);
+ const view = document.documentElement;
+ return { x: box.left, y: box.top, width: box.width, height: box.height, viewportWidth: globalThis.innerWidth ?? view.clientWidth, viewportHeight: globalThis.innerHeight ?? view.clientHeight };
+}
++function restingBox(mark2) {
++ const box = mark2.getBoundingClientRect();
++ const column = mark2.closest?.(".bt-leftcol");
++ if (!column) return box;
++ const now = column.getBoundingClientRect();
++ const dx = column.offsetLeft - now.left;
++ const dy = column.offsetTop - now.top;
++ return { left: box.left + dx, top: box.top + dy, width: box.width, height: box.height };
++}
+var GLIDE_MS = 460;
+function glideOnto(mark2, from) {
+ if (!mark2 || reducedMotion()) return;
- const box = mark2.getBoundingClientRect();
++ const box = restingBox(mark2);
+ if (!box.width) return;
+ const outer = document.createElement("div");
+ const inner = document.createElement("div");
+ const copy2 = mark2.cloneNode(true);
+ copy2.removeAttribute("data-live");
+ Object.assign(outer.style, { position: "fixed", left: `${box.left}px`, top: `${box.top}px`, width: `${box.width}px`, height: `${box.height}px`, zIndex: "2147483647", pointerEvents: "none" });
+ Object.assign(inner.style, { width: "100%", height: "100%", transformOrigin: "0 0" });
+ Object.assign(copy2.style, { width: "100%", height: "100%" });
+ copy2.style.setProperty("--bt-ink-deepseek", getComputedStyle(mark2).getPropertyValue("--bt-ink-deepseek"));
+ inner.append(copy2);
+ outer.append(inner);
+ outer.setAttribute("aria-hidden", "true");
+ document.body.append(outer);
+ mark2.style.opacity = "0";
+ const timing = { delay: Math.max(0, Number(from.hold) || 0), duration: GLIDE_MS, fill: "both" };
+ outer.animate([{ transform: `translateX(${from.x - box.left}px)` }, { transform: "none" }], { ...timing, easing: "cubic-bezier(.45,0,.25,1)" });
+ const glide = inner.animate([{ transform: `translateY(${from.y - box.top}px) scale(${from.size / box.width})` }, { transform: "none" }], { ...timing, easing: "cubic-bezier(.2,.65,.3,1)" });
+ let landed = false;
+ const land = () => {
+ if (landed) return;
+ landed = true;
+ outer.remove();
+ mark2.style.opacity = "";
+ mark2.animate([{ transform: "scale(1.08, .92)" }, { transform: "none" }], { duration: SPRING_POP.duration, easing: SPRING_POP.easing });
+ };
+ glide.finished.then(land, land);
+ setTimeout(land, timing.delay + GLIDE_MS + 500);
+}
+function useLandOnMainBot(roster, useSessions, actions) {
+ const mainView = useSessions((list) => {
+ const row = Object.values(list.byId).find((session) => (session?.retainedBy?.mainView ?? 0) > 0);
+ return row ? `${row.id}|${row.blank ? 1 : 0}` : "";
+ });
+ const lastBot = (0, import_react32.useRef)(null);
+ (0, import_react32.useEffect)(() => {
+ if (!roster.ready || !roster.mainBotId) return void 0;
+ const [id, blank3] = mainView.split("|");
+ const bot = id === "" ? void 0 : roster.byId[id];
+ if (bot !== void 0) {
+ lastBot.current = { botId: bot.id, sessionId: id };
+ if (currentPart(bot) !== id) actions.landOn(bot.id);
+ return void 0;
}
- const toggles = keyHere && (fix === "key" || fix === "rekey");
- return (0, import_react28.createElement)("button", { key: fix, type: "button", className, "aria-expanded": toggles ? keying : void 0, onClick: () => runs[fix]() }, FIX_LABELS[fix](signedIn));
- };
- const retryButton = (primary) => (0, import_react28.createElement)("button", { key: "retry", type: "button", className: primary ? "bt-send bt-fail-go" : "bt-soft bt-soft-sm", disabled: retry !== "idle", onClick: resume }, retry === "idle" ? t("Retry") : t("Retrying…"));
- const row = retryFirst ? [retryButton(true), ...fixes.map((fix) => button(fix, false))] : [...fixes.map((fix, index) => button(fix, index === 0)), retrying ? retryButton(false) : null];
- if (!row.some(Boolean)) return settled();
- return (0, import_react28.createElement)(
- "div",
- { className: "bt-fail", role: "status" },
- (0, import_react28.createElement)("div", { className: "bt-fail-head" }, (0, import_react28.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react28.createElement)("span", { className: "bt-fail-text" }, text)),
- (0, import_react28.createElement)("div", { className: "bt-fail-actions" }, row),
- keying && keyHere ? (0, import_react28.createElement)(ModelKeyCard, { model: { provider, providerName: providerName(roster, provider) }, actions, onSaved: () => setKeying(false) }) : null,
- error ? (0, import_react28.createElement)("div", { className: "bt-fail-error", role: "alert" }, error) : null,
- (0, import_react28.createElement)(TechnicalDetails, { facts })
+ const room2 = id === "" ? void 0 : roster.roomsById[id];
+ if (room2 !== void 0) {
+ lastBot.current = null;
+ if ((room2.sessionId ?? room2.id) !== id) actions.openSession(room2.id);
+ return void 0;
+ }
+ if (id !== "" && ((actions.isAgentSession?.(id) ?? roster.agentOf[id] !== void 0) || blank3 !== "1")) {
+ lastBot.current = null;
+ return void 0;
+ }
+ const last = lastBot.current;
+ const timer = setTimeout(() => actions.landOn(roster.mainBotId, last), last ? 0 : 400);
+ return () => clearTimeout(timer);
+ }, [mainView, roster]);
+}
+function FooterAccount(props) {
+ const seated = props.useUi((value) => value.accountSeated === true);
+ if (seated) return null;
+ return (0, import_react32.createElement)("span", { className: "bt-foot-account" }, (0, import_react32.createElement)(AccountLauncher, { ...props, seat: false }));
+}
+function BotReturn({ wide, useSurface, useRoster, actions }) {
+ const mode = useSurface((value) => value.mode);
+ const ready = useRoster((value) => value.ready);
+ useReportReady(mode === "agent" && ready);
+ if (mode !== "agent") return null;
+ return (0, import_react32.createElement)(
+ "button",
+ { type: "button", className: "bt-return", "aria-label": t("DS Bot"), title: t("DS Bot"), onClick: () => actions.setSurface("bot") },
+ (0, import_react32.createElement)(BotMark, { look: MAIN_LOOK, size: 20 }),
+ wide ? (0, import_react32.createElement)("span", { className: "bt-return-name" }, t("DS Bot")) : null
);
}
-var TURN_ERROR_CSS = `
-.bt-fail{display:flex;flex-direction:column;gap:10px;margin:4px 0 6px;width:max-content;max-width:min(550px,86%);padding:12px 14px;border-radius:16px;background:var(--bt-card);box-shadow:inset 0 0 0 1px var(--bt-line);box-sizing:border-box;color:var(--bt-ink);font-size:14px;line-height:20px}
-.bt-fail[data-settled]{gap:4px;padding:2px 0;background:none;box-shadow:none;color:var(--bt-ink-2);font-size:13px;line-height:18px}
-.bt-fail-head{display:flex;align-items:flex-start;gap:8px;min-width:0}
-.bt-fail-dot{flex:none;width:7px;height:7px;margin-top:6.5px;border-radius:50%;background:var(--bt-danger)}
-.bt-fail[data-settled] .bt-fail-dot{margin-top:5.5px}
-.bt-fail-text{min-width:0;overflow-wrap:anywhere}
-.bt-fail-actions{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-left:15px}
-.bt-fail-actions .bt-fail-go{height:28px;padding:0 12px;font:inherit;font-size:12px}
-.bt-fail-link{display:inline-flex;align-items:center;box-sizing:border-box;text-decoration:none}
-.bt-fail:has(.bt-model-key){width:min(480px,86%)}
-.bt-fail .bt-q.bt-model-key{margin:0 0 0 15px;width:auto;padding:0;background:none;box-shadow:none;border-radius:0;animation:none}
-.bt-fail-error{margin-left:15px;font-size:12px;line-height:17px;color:var(--bt-danger);overflow-wrap:anywhere}
-.bt-fail-tech{margin-left:15px;font-size:12px;line-height:17px;color:var(--bt-ink-2)}
-.bt-fail-tech summary{width:max-content;cursor:pointer;color:var(--bt-ink-3)}
-.bt-fail-tech summary:hover{color:var(--bt-ink-2)}
-.bt-fail-tech dl{display:grid;grid-template-columns:auto minmax(0,1fr);gap:2px 10px;margin:6px 0}
-.bt-fail-tech dt{color:var(--bt-ink-3)}
-.bt-fail-tech dd{margin:0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11.5px;overflow-wrap:anywhere;white-space:pre-wrap;user-select:text}
-.bt-fail-copy{display:inline-flex;align-items:center;gap:4px}
-.bt-fail-copy svg{width:13px;height:13px}
+var RETURN_CSS = `
+.bt-return{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:36px;padding:0 14px;border:0;border-radius:999px;background:none;color:inherit;font:inherit;font-size:14px;line-height:20px;cursor:pointer;transition:background-color .12s ease}
+.bt-return:hover{background:rgba(127,127,127,.14)}
+.bt-return:active{transform:scale(.96)}
+.bt-return .bt-mark{display:inline-flex;flex:none;line-height:0}
+.bt-return .bt-mark svg{width:100%;height:100%;overflow:visible}
+/* Shell styles carry --bt-ink-deepseek and Agent mode withdraws them; pin it here. */
+.bt-return .bt-mark{--bt-ink-deepseek:#4D6BFE}
+.bt-return-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
`;
+function BrandMark({ size = 24 }) {
+ return (0, import_react32.createElement)("span", { className: "bt-brand-whale" }, (0, import_react32.createElement)(BotMark, { look: MAIN_LOOK, size }));
+}
+function BrandName() {
+ return (0, import_react32.createElement)("span", { style: { fontWeight: 600, fontSize: 14 } }, "DS Bot");
+}
+var SIDEBAR_CSS = `
+.bt-confirm{width:260px;max-width:72vw;padding:10px 12px 12px;display:flex;flex-direction:column;gap:10px}
+.bt-confirm-text{margin:0;font-size:13px;line-height:19px;color:var(--bt-ink-2)}
+.bt-confirm-error{margin:0;font-size:12px;line-height:17px;color:var(--bt-danger);overflow-wrap:anywhere}
+.bt-confirm-row{display:flex;justify-content:flex-end;gap:8px}
+.bt-menu .bt-confirm button{width:auto;min-height:0}
+.bt-confirm-go{height:28px;padding:0 14px;border:0;border-radius:999px;background:var(--bt-accent);color:var(--bt-accent-ink);font:inherit;font-size:13px;font-weight:500;cursor:pointer;transition:opacity .12s ease}
+.bt-confirm-go:hover:not(:disabled){opacity:.9}
+.bt-confirm-go:disabled{opacity:.6;cursor:default}
+.bt-side-top .bt-brand{cursor:default;padding-left:6px}
+.bt-side-top .bt-brand:hover{background:none}
+.bt-brand .bt-mark{flex:none}
+.bt-pin{flex:none;display:inline-flex;color:var(--bt-ink-3)}
+.bt-rail .bt-row{position:relative}
+.bt-rail .bt-pin{position:absolute;top:1px;left:calc(50% + 14px)}
+.bt-side .bt-read-only{margin:4px 8px 6px;padding:8px 10px;border-radius:10px;background:var(--bt-hover);font-size:12px;line-height:1.45;text-align:left}
+[class*="_footArea"]:has(.bt-foot-account){grid-template-columns:auto minmax(0,1fr) auto;column-gap:6px}
+[class*="_footArea"]>[class*="_footerActions"]>div>.bt-foot-account{grid-column:1;order:1;display:inline-flex}
+[class*="_footArea"]:has(.bt-foot-account)>[class*="_settingsArea"]{grid-column:3}
+[class*="_footArea"]:has(.bt-foot-account)>[class*="_settingsArea"] button[class*="_trigger"] [class*="_label"]{display:none!important}
-// src/client/palette.js
-var import_react29 = require("react");
-var PALETTE_EXIT_MS = 160;
-function CommandPalette({ start, token, roster, actions, useSessions }) {
- const [query, setQuery] = (0, import_react29.useState)(start ?? "");
- const [cursor, setCursor] = (0, import_react29.useState)(0);
- const [leaving, setLeaving] = (0, import_react29.useState)(false);
- const wanted = query.trim().toLowerCase();
- const close = () => {
- if (leaving) return;
- setLeaving(true);
- setTimeout(() => actions.closePalette(token), PALETTE_EXIT_MS);
- };
- useEscape(close);
- const ids = [...roster.bots.map(currentPart), ...roster.rooms.map((item) => item.id)];
- const found = useSessions((list) => {
- if (wanted.length < 2) return "[]";
- const hits = [];
- for (const id of ids) {
- const outline = list.projectionsBySession?.[id]?.values?.turnOutline ?? list.byId[id]?.projectionValues?.turnOutline;
- if (!Array.isArray(outline)) continue;
- const hidden = roster.exchangeTurns[id] ?? [];
- for (let index2 = outline.length - 1; index2 >= 0 && hits.length < 30; index2 -= 1) {
- const entry = outline[index2];
- if (hidden.includes(entry.turn)) continue;
- for (const raw of [entry.response, entry.prompt]) {
- const text = stripHeader(raw ?? "").replace(/\s+/g, " ").trim();
- const at = text.toLowerCase().indexOf(wanted);
- if (at < 0) continue;
- const from = Math.max(0, at - 24);
- hits.push([id, entry.turn, (from > 0 ? "…" : "") + text.slice(from, at + wanted.length + 60)]);
- break;
- }
+/* The update cloud springs in when a newer DS Bot shows up; its arrow drops in a
+ loop while the install runs. */
+.bt-round.bt-update{position:relative;color:var(--bt-accent,#4D6BFE);animation:bt-update-in ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing}}
+.bt-round.bt-update svg{width:17px;height:17px}
+.bt-round.bt-update[data-phase=installed]{color:var(--bt-ink-2)}
+@keyframes bt-update-in{from{opacity:0;transform:scale(.6);filter:blur(4px)}}
+.bt-update[data-phase=installing] .bt-cloud-arrow{animation:bt-cloud-drop 1.1s cubic-bezier(.45,0,.55,1) infinite}
+@keyframes bt-cloud-drop{0%{transform:translateY(-3px);opacity:0}35%{opacity:1}70%{transform:translateY(1px);opacity:1}100%{transform:translateY(2px);opacity:0}}
+.bt-update-dot{position:absolute;top:6px;right:6px;width:7px;height:7px;border-radius:50%;background:#E5484D;box-shadow:0 0 0 1.5px var(--bt-sidebar)}
+.bt-update-pop{position:fixed;z-index:60;width:280px;padding:14px 14px 12px;border-radius:16px;background:var(--bt-glass-bg);-webkit-backdrop-filter:blur(24px) saturate(180%);backdrop-filter:blur(24px) saturate(180%);border:.5px solid var(--bt-glass-rim);box-shadow:var(--bt-glass-shadow);color:var(--bt-ink);box-sizing:border-box;transform-origin:top left;font-family:var(--bt-font);animation:bt-update-pop ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing}}
+.bt-update-pop[data-leaving]{animation:bt-pop-out .12s cubic-bezier(.4,0,1,1) forwards;pointer-events:none}
+@keyframes bt-update-pop{from{opacity:0;transform:scale(.96);filter:blur(4px)}}
+.bt-update-title{font-size:14px;line-height:20px;font-weight:600}
+.bt-update-text{margin-top:2px;font-size:12px;line-height:18px;color:var(--bt-ink-2)}
+.bt-update-error{margin-top:8px;font-size:12px;line-height:17px;color:var(--bt-danger);overflow-wrap:anywhere;max-height:90px;overflow:auto}
+.bt-update-actions{display:flex;align-items:center;justify-content:flex-end;gap:10px;margin-top:12px}
+.bt-update-notes{margin-right:auto;font-size:12px;color:var(--bt-ink-2);text-decoration:none}
+.bt-update-notes:hover{color:var(--bt-ink);text-decoration:underline}
+.bt-update-go{height:30px;padding:0 14px;border:0;border-radius:999px;background:var(--bt-accent,#4D6BFE);color:var(--bt-accent-ink,#fff);font:inherit;font-size:13px;font-weight:500;cursor:pointer;transition:opacity .12s ease,transform .12s ease}
+.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:not(:first-child){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
+ harness's own mark, so the row reads as "plain dsh" next to the Bot marks. */
+.bt-agent-ava{flex:none;width:36px;height:36px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;background:var(--bt-hover);color:var(--bt-ink)}
+.bt-agent-ava.bt-run{animation:bt-agent-pulse 1.4s ease-in-out infinite}
+@keyframes bt-agent-pulse{0%,100%{opacity:1}50%{opacity:.55}}
+.bt-agent-sub{display:grid;grid-template-rows:0fr;transition:grid-template-rows ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing}}
+.bt-agent-sub[data-open]{grid-template-rows:1fr}
+.bt-agent-sub-in{overflow:hidden;min-height:0;margin-left:44px}
+.bt-agent-sub-row{display:flex;align-items:center;gap:8px;width:100%;padding:5px 10px 5px 8px;border:0;border-radius:8px;background:none;color:var(--bt-ink-2);font:inherit;font-size:13px;line-height:20px;text-align:left;cursor:pointer}
+.bt-agent-sub-row:hover{background:var(--bt-hover);color:var(--bt-ink)}
+.bt-agent-sub-row[aria-current=page]{background:var(--bt-hover);color:var(--bt-ink);font-weight:500}
+/* .bt-agent-sub-in clips for the expand animation and the rows touch its edges, so the ring goes inside. */
+.bt-agent-sub-row:focus-visible{outline:2px solid var(--bt-accent);outline-offset:-2px}
+.bt-agent-sub-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.bt-agent-sub-time{flex:none;font-size:11px;color:var(--bt-ink-3)}
+.bt-agent-new{color:var(--bt-ink-3)}
+.bt-agent-new svg{width:14px;height:14px;flex:none}
+.bt-agent-edit{padding:3px 10px 3px 4px}
+.bt-agent-edit input{width:100%;border:0;border-radius:6px;background:var(--bt-hover);color:var(--bt-ink);font:inherit;font-size:13px;line-height:20px;padding:2px 8px;outline:none;box-shadow:inset 0 0 0 .5px var(--bt-line-2)}
+.bt-agent-sub[data-open] .bt-agent-sub-row{animation:bt-agent-row-in .24s ease both;animation-delay:calc(var(--i, 0)*30ms)}
+@keyframes bt-agent-row-in{from{opacity:0;filter:blur(4px)}to{opacity:1;filter:blur(0)}}
+@media (prefers-reduced-motion:reduce){.bt-agent-sub{transition:none}.bt-agent-sub .bt-agent-sub-row{animation:none}}
+`;
+
+// src/client/header.js
+var import_react33 = require("react");
+var import_react_dom6 = require("react-dom");
+var GoArrow = () => (0, import_react33.createElement)("svg", { width: 14, height: 14, viewBox: "-12 -12 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true }, (0, import_react33.createElement)("path", { d: "M-7 0H7M2 -5L7 0L2 5" }));
+var MEMORY_NOTICE_MS = 3200;
+var noNews = (select) => select({});
+function useMemoryNotice(ids, useMemoryNews) {
+ const seen = useMemoryNews((map) => Math.max(0, ...ids.map((id) => map?.[id]?.seen ?? 0)));
+ const [shown, setShown] = (0, import_react33.useState)(false);
+ (0, import_react33.useEffect)(() => {
+ const left = seen + MEMORY_NOTICE_MS - Date.now();
+ setShown(seen > 0 && left > 0);
+ if (seen === 0 || left <= 0) return void 0;
+ const timer = setTimeout(() => setShown(false), left);
+ return () => clearTimeout(timer);
+ }, [seen]);
+ return shown;
+}
+function MemoryNotice({ shown }) {
+ const inner = (0, import_react33.useRef)(null);
+ const [width, setWidth] = (0, import_react33.useState)(0);
+ const label = t("Memory updated");
+ (0, import_react33.useLayoutEffect)(() => {
+ if (shown) setWidth(inner.current?.scrollWidth ?? 0);
+ }, [label, shown]);
+ return (0, import_react33.createElement)(
+ "span",
+ { className: "bt-pill-mem", "aria-hidden": true, style: { "--bt-mem-w": `${width}px` } },
+ (0, import_react33.createElement)("span", { className: "bt-pill-mem-in", ref: inner }, (0, import_react33.createElement)("span", { className: "bt-pill-mem-ico" }, (0, import_react33.createElement)(MemoryIcon)), label)
+ );
+}
+function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus, useSession, useActivity, useMemoryNews, useTurnClock, useUi, useLive, useWork, useStore, useConversationViews, selectView, actions }) {
+ const roster = useRoster((value) => value);
+ const selectedView = useStore?.((state) => state.view);
+ const away = useConversationViews?.((views) => views.some((view2) => view2.id === selectedView && view2.id !== "chat")) === true && typeof selectView === "function";
+ const title = useSessions((list) => list.byId[sessionId]?.displayTitle ?? list.byId[sessionId]?.title ?? "");
+ const firstTurns = useSessions((list) => {
+ const outline = list.projectionsBySession?.[sessionId]?.values?.turnOutline ?? list.byId[sessionId]?.projectionValues?.turnOutline;
+ return Array.isArray(outline) ? outline.slice(0, 8).map((entry) => entry.turn).join(",") : "";
+ });
+ const hiddenTurns = roster.exchangeTurns?.[sessionId];
+ const visit = useUi((state) => state.visits?.[sessionId]);
+ const opening = useTurnClock((state) => {
+ const first = openingTurn(state[sessionId], firstTurns, hiddenTurns);
+ return first && !unseenSince(visit, first.start) ? clockLabel(first.start) : "";
+ });
+ (0, import_react33.useEffect)(() => {
+ if (opening) document.body.style.setProperty("--bt-first-sep", JSON.stringify(opening));
+ else document.body.style.removeProperty("--bt-first-sep");
+ return () => document.body.style.removeProperty("--bt-first-sep");
+ }, [opening]);
+ const running = useSessionStatus((map) => map.get(sessionId)?.running === true);
+ const owner = roster.byId[sessionId]?.id ?? sessionId;
+ const doing = useActivity((map) => map[owner]);
+ const bot = roster.byId[sessionId];
+ const room2 = roster.roomsById[sessionId];
+ const goal = room2?.goal;
+ const goalCompose = useUi((state) => state.goalCompose === sessionId);
+ const goalOpen = useUi((state) => state.goalOpen === sessionId);
+ const roomWorkKey = useWork?.((work) => room2 ? JSON.stringify(work.rooms?.[sessionId] ?? []) : "") ?? "[]";
+ const roomWork = room2 ? JSON.parse(roomWorkKey || "[]") : [];
+ const view = goal ? goalView(goal, { roster, roomWork }) : null;
+ const goalShown = room2 !== void 0 && !away && goal !== void 0;
+ const detailsOpen = useUi((state) => state.details === sessionId);
+ const name = bot?.name ?? room2?.name ?? "";
+ const useNews = useMemoryNews ?? noNews;
+ const memoryIds = bot ? [bot.id] : room2 ? [room2.id, ...room2.members] : [];
+ const notice = useMemoryNotice(memoryIds, useNews);
+ const changed = useNews((map) => latestMemoryChange(map, memoryIds));
+ (0, import_react33.useEffect)(() => {
+ document.body.style.setProperty("--bt-placeholder", JSON.stringify(name ? t("Message {name}", { name }) : t("Message")));
+ }, [name, t("Message")]);
+ (0, import_react33.useEffect)(() => {
+ document.body.style.setProperty("--bt-steer-unread", JSON.stringify(t("Not read yet")));
+ }, [t("Not read yet")]);
+ (0, import_react33.useEffect)(() => {
+ actions.beginVisit(sessionId);
+ return () => actions.endVisit(sessionId);
+ }, [sessionId]);
+ (0, import_react33.useEffect)(() => {
+ if (room2) document.body.dataset.btRoom = "";
+ else delete document.body.dataset.btRoom;
+ return () => {
+ delete document.body.dataset.btRoom;
+ };
+ }, [Boolean(room2)]);
+ const memoryNotice = !away && notice && changed !== null && roster.memory !== false;
+ const showGoal = room2 !== void 0 && !away && (goal !== void 0 || goalCompose);
+ (0, import_react33.useEffect)(() => {
+ if (showGoal) document.body.dataset.btGoal = "";
+ else delete document.body.dataset.btGoal;
+ return () => {
+ delete document.body.dataset.btGoal;
+ };
+ }, [showGoal]);
+ const pill = (0, import_react33.createElement)(
+ "button",
+ {
+ type: "button",
+ className: "bt-pill",
+ "aria-expanded": away ? void 0 : detailsOpen,
+ "data-memory": memoryNotice ? "updated" : void 0,
+ "aria-label": away ? t("Back to chat") : memoryNotice ? t("Memory updated. Open {name}'s memory", { name: roster.byId[changed]?.name ?? name }) : t("View conversation details"),
+ title: away ? name : void 0,
+ onClick: () => away ? selectView("chat") : memoryNotice ? actions.openMemory(changed) : actions.toggleDetails(sessionId)
+ },
+ bot ? (0, import_react33.createElement)(BotAvatar, { bot, size: 24, state: botState(running, doing, roster.questions?.[currentPart(bot)] !== void 0), badge: false }) : room2 ? (0, import_react33.createElement)(RoomAvatar, { room: room2, roster, size: 24 }) : null,
+ goalShown ? (0, import_react33.createElement)(
+ "span",
+ { className: "bt-pill-swap" },
+ (0, import_react33.createElement)("span", { className: "bt-pill-goal" }, (0, import_react33.createElement)("span", { className: "bt-pill-ico", "aria-hidden": true }, (0, import_react33.createElement)(GoalIcon)), (0, import_react33.createElement)("span", { className: "bt-pill-title" }, view.title)),
+ (0, import_react33.createElement)("span", { className: "bt-pill-name" }, name)
+ ) : (0, import_react33.createElement)("span", { className: "bt-pill-name" }, away ? t("Back to chat") : bot?.name ?? room2?.name ?? (title || t("New chat"))),
+ goalShown && view?.number !== void 0 ? (0, import_react33.createElement)("span", { className: "bt-pill-count" }, `${view.number}/${view.count}`) : null,
+ (0, import_react33.createElement)(MemoryNotice, { shown: memoryNotice }),
+ (0, import_react33.createElement)("span", { className: "bt-pill-go", "aria-hidden": true }, (0, import_react33.createElement)(GoArrow))
+ );
+ return (0, import_react33.createElement)(
+ "div",
+ { className: "bt-head" },
+ showGoal ? (0, import_react33.createElement)(GoalIsland, { room: room2, goal, view, open: goalOpen, composing: goalCompose, roomWork, roster, actions, pill }) : pill,
+ (0, import_react33.createElement)("span", { className: "bt-sr", role: "status" }, memoryNotice ? t("Memory updated") : ""),
+ (0, import_react33.createElement)(NewMessagePills, { key: sessionId, sessionId, useSessions, useUi, useTurnClock }),
+ (0, import_react33.createElement)(ActivityIndicator, { key: `activity:${sessionId}`, sessionId, useRoster, useSessionStatus, useSession, useLive, useWork, actions })
+ );
+}
+function useTranscriptView() {
+ const [view, setView] = (0, import_react33.useState)(null);
+ (0, import_react33.useEffect)(() => {
+ let frame = 0;
+ let watched = null;
+ const observer = new MutationObserver(() => schedule());
+ const measure = () => {
+ frame = 0;
+ const scroller = document.querySelector("[data-conversation-scroll]");
+ if (scroller !== watched) {
+ observer.disconnect();
+ watched = scroller;
+ if (scroller) observer.observe(scroller, { childList: true, subtree: true });
}
- }
- return JSON.stringify(hits);
- });
- const matchesName = (...fields) => wanted === "" || fields.some((field) => (field ?? "").toLowerCase().includes(wanted));
- const sections = [];
- const people = [
- ...roster.bots.filter((bot) => matchesName(bot.name, bot.role)).map((bot) => ({
- key: bot.id,
- avatar: (0, import_react29.createElement)(BotAvatar, { bot, size: 24, badge: false, live: false }),
- title: bot.name,
- subtitle: [bot.role, isMainOf(roster, bot.id) ? t("Main Bot") : ""].filter(Boolean).join(" · "),
- badge: bot.hidden ? t("Hidden") : void 0,
- run: async () => {
- if (bot.hidden) await actions.setFlags(bot.id, { hidden: false });
- actions.openSession(bot.id);
+ if (!scroller) {
+ setView(null);
+ return;
}
- })),
- ...roster.rooms.filter((room2) => matchesName(room2.name)).map((room2) => ({
- key: room2.id,
- avatar: (0, import_react29.createElement)(RoomAvatar, { room: room2, roster, size: 24 }),
- title: room2.name,
- subtitle: t("{count} members", { count: room2.members.length }),
- badge: room2.hidden ? t("Hidden") : void 0,
- run: async () => {
- if (room2.hidden) await actions.setFlags(room2.id, { hidden: false });
- actions.openSession(room2.id);
+ const box = scroller.getBoundingClientRect();
+ const headerBottom = document.querySelector('header[class*="_header"]')?.getBoundingClientRect().bottom ?? box.top + 50;
+ const sep = scroller.querySelector(".bt-new-sep");
+ let divider = null;
+ if (sep) {
+ const at = sep.getBoundingClientRect();
+ divider = at.bottom <= headerBottom ? "above" : at.top >= box.bottom ? "below" : "in-view";
}
- }))
- ];
- if (people.length) sections.push([t("Bots"), people]);
- const agents = (roster.agents ?? []).filter(() => matchesName("DSH Agent")).map((agent) => ({
- key: agent.id,
- avatar: (0, import_react29.createElement)("span", { className: "bt-palette-agent" }, (0, import_react29.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: 18 })),
- title: "DSH Agent",
- subtitle: t("Plain dsh session"),
- run: () => actions.openAgent(agent.id)
- }));
- if (agents.length) sections.push(["DSH Agent", agents]);
- const messages = JSON.parse(found).map(([id, turn, snippet]) => {
- const bot = roster.byId[id];
- const room2 = roster.roomsById[id];
- return {
- key: `${id}:${turn}`,
- title: bot?.name ?? room2?.name ?? t("Bot"),
- subtitle: snippet,
- avatar: bot ? (0, import_react29.createElement)(BotAvatar, { bot, size: 24, badge: false, live: false }) : (0, import_react29.createElement)(RoomAvatar, { room: room2, roster, size: 24 }),
- run: () => actions.openSession(id)
+ const composer = parseFloat(getComputedStyle(scroller).getPropertyValue("--dsh-composer-height")) || 152;
+ const next = {
+ unpinned: scroller.querySelector('[class*="_toBottomSlot"]>button') !== null,
+ divider,
+ center: Math.round(box.left + box.width / 2),
+ top: Math.round(headerBottom + 8),
+ bottom: Math.round(viewBottom() - box.bottom + composer + 8)
+ };
+ setView((prev) => prev && Object.keys(next).every((key) => prev[key] === next[key]) ? prev : next);
+ };
+ const schedule = () => {
+ if (!frame) frame = requestAnimationFrame(measure);
+ };
+ document.addEventListener("scroll", schedule, true);
+ window.addEventListener("resize", schedule);
+ window.visualViewport?.addEventListener("resize", schedule);
+ window.visualViewport?.addEventListener("scroll", schedule);
+ schedule();
+ return () => {
+ cancelAnimationFrame(frame);
+ observer.disconnect();
+ document.removeEventListener("scroll", schedule, true);
+ window.removeEventListener("resize", schedule);
+ window.visualViewport?.removeEventListener("resize", schedule);
+ window.visualViewport?.removeEventListener("scroll", schedule);
};
+ }, []);
+ return view;
+}
+function NewMessagePills({ sessionId, useSessions, useUi, useTurnClock }) {
+ const replies = useSessions((list) => {
+ const outline = list.projectionsBySession?.[sessionId]?.values?.turnOutline ?? list.byId[sessionId]?.projectionValues?.turnOutline;
+ return Array.isArray(outline) ? outline.reduce((count, entry) => count + (entry.response ? 1 : 0), 0) : 0;
});
- if (messages.length) sections.push([t("Messages"), messages]);
- const commands = [
- { key: "cmd:new", icon: (0, import_react29.createElement)(PlusIcon), title: t("New chat"), run: () => actions.openNewChat("new") },
- { key: "cmd:bot", icon: (0, import_react29.createElement)(PlusIcon), title: t("Create Bot"), run: () => actions.openNewChat("create") },
- { key: "cmd:group", icon: (0, import_react29.createElement)(PeopleIcon), title: t("Create group chat"), run: () => actions.openNewChat("group") },
- { key: "cmd:settings", icon: (0, import_react29.createElement)(GearIcon), title: t("Bot settings"), run: () => actions.openSettings("general") }
- ].filter((command) => matchesName(command.title));
- if (commands.length) sections.push([t("Commands"), commands]);
- const rows2 = sections.flatMap(([, items]) => items);
- const active = Math.min(cursor, Math.max(rows2.length - 1, 0));
- const shown = rows2.map((row) => row.key).join("\n");
- const glide = useGlide(`${active}
-${shown}`, { axis: "y", ...QUICK_EDGES });
- const listRef = glide.box;
- useFlip(listRef, shown, "[data-flip]");
- (0, import_react29.useEffect)(() => {
- listRef.current?.querySelector("[aria-selected=true]")?.scrollIntoView({ block: "nearest" });
- }, [active, query]);
- const choose = (row) => {
- if (!row || leaving) return;
- void Promise.resolve(row.run()).catch((error) => actions.reportError(error, "menu"));
- close();
- };
- let index = -1;
- return (0, import_react29.createElement)(
+ const visit = useUi((state) => state.visits?.[sessionId]);
+ const unread = useTurnClock((state) => {
+ if (typeof visit?.seen !== "number") return 0;
+ let count = 0;
+ for (const entry of Object.values(state[sessionId] ?? {})) {
+ if (entry.first !== void 0 && entry.first > visit.seen && entry.first <= visit.entered) count += 1;
+ }
+ return count;
+ });
+ const view = useTranscriptView();
+ const unpinned = view?.unpinned === true;
+ const [release, setRelease] = (0, import_react33.useState)({ base: null, dismissed: false });
+ const [above, setAbove] = (0, import_react33.useState)({ seen: false, dismissed: false });
+ (0, import_react33.useEffect)(() => {
+ setRelease({ base: unpinned ? replies : null, dismissed: false });
+ }, [unpinned]);
+ (0, import_react33.useEffect)(() => {
+ if (view?.divider === "in-view") setAbove((state) => state.seen ? state : { ...state, seen: true });
+ }, [view?.divider]);
+ const fresh = release.base === null ? 0 : replies - release.base;
+ const showDown = unpinned && fresh > 0 && !release.dismissed;
+ const showUp = view?.divider === "above" && !above.seen && !above.dismissed;
+ (0, import_react33.useEffect)(() => {
+ const scroller = document.querySelector("[data-conversation-scroll]");
+ if (!scroller) return void 0;
+ scroller.toggleAttribute("data-bt-news", showDown);
+ return () => scroller.removeAttribute("data-bt-news");
+ }, [showDown]);
+ if (!view || !showDown && !showUp) return null;
+ const label = (count) => count === 1 ? t("1 new message") : count > 0 ? t("{count} new messages", { count }) : t("New messages");
+ const pill = (direction, count, style, onJump, onDismiss) => (0, import_react33.createElement)(
"div",
- { className: "bt-palette-layer", "data-leaving": leaving || void 0 },
- (0, import_react29.createElement)("div", { className: "bt-backdrop", onMouseDown: close }),
- (0, import_react29.createElement)(
- "div",
- { className: "bt-palette", role: "dialog", "aria-label": t("Search"), "aria-modal": true },
- (0, import_react29.createElement)(
- "div",
- { className: "bt-palette-head" },
- (0, import_react29.createElement)("span", { className: "bt-palette-glyph", "aria-hidden": true }, (0, import_react29.createElement)(SearchIcon)),
- (0, import_react29.createElement)("input", {
- autoFocus: true,
- value: query,
- placeholder: t("Search Bots, chats and messages"),
- "aria-label": t("Search"),
- role: "combobox",
- "aria-expanded": true,
- "aria-controls": "bt-palette-list",
- onChange: (event) => {
- setQuery(event.target.value);
- setCursor(0);
- },
- onKeyDown: (event) => {
- if (event.nativeEvent.isComposing) return;
- if (event.key === "ArrowDown") {
- event.preventDefault();
- setCursor(Math.min(active + 1, rows2.length - 1));
- } else if (event.key === "ArrowUp") {
- event.preventDefault();
- setCursor(Math.max(active - 1, 0));
- } else if (event.key === "Enter") {
- event.preventDefault();
- choose(rows2[active]);
- }
- }
- }),
- query ? (0, import_react29.createElement)("button", { type: "button", className: "bt-palette-clear", "aria-label": t("Clear search"), onClick: () => {
- setQuery("");
- setCursor(0);
- } }, (0, import_react29.createElement)(CloseIcon)) : null
- ),
- (0, import_react29.createElement)(
- "div",
- { ref: listRef, id: "bt-palette-list", className: "bt-palette-list", role: "listbox", "aria-label": t("Results") },
- (0, import_react29.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }),
- rows2.length === 0 ? (0, import_react29.createElement)(
- "div",
- { className: "bt-palette-empty" },
- (0, import_react29.createElement)("span", { className: "bt-palette-empty-icon", "aria-hidden": true }, (0, import_react29.createElement)(SearchIcon)),
- (0, import_react29.createElement)("span", { className: "bt-palette-empty-label" }, t("No results")),
- (0, import_react29.createElement)("span", { className: "bt-palette-empty-hint" }, t("Try a Bot name or words from a message"))
- ) : sections.map(([title, items]) => (0, import_react29.createElement)(
- import_react29.Fragment,
- { key: title },
- (0, import_react29.createElement)("div", { className: "bt-palette-section", role: "presentation", "data-flip": `section:${title}` }, title),
- items.map((row) => {
- index += 1;
- const at = index;
- return (0, import_react29.createElement)(
- "button",
- {
- key: row.key,
- type: "button",
- role: "option",
- className: "bt-palette-row",
- "aria-selected": at === active,
- "data-flip": row.key,
- onMouseMove: () => {
- if (cursor !== at) setCursor(at);
- },
- onClick: () => choose(row)
- },
- (0, import_react29.createElement)("span", { className: "bt-palette-lead" }, row.avatar ?? (0, import_react29.createElement)("span", { className: "bt-palette-cmd" }, row.icon)),
- (0, import_react29.createElement)(
- "span",
- { className: "bt-palette-text" },
- (0, import_react29.createElement)("span", { className: "bt-palette-title" }, row.title),
- row.subtitle ? (0, import_react29.createElement)("span", { className: "bt-palette-sub" }, row.subtitle) : null
- ),
- row.badge ? (0, import_react29.createElement)("span", { className: "bt-palette-badge" }, row.badge) : null
- );
- })
- ))
- )
- )
+ { className: "bt-news", "data-direction": direction, style },
+ (0, import_react33.createElement)(
+ "button",
+ { type: "button", className: "bt-news-jump", onClick: onJump },
+ (0, import_react33.createElement)("span", { className: "bt-news-ico" }, (0, import_react33.createElement)(direction === "up" ? ArrowUpIcon : ArrowDownIcon)),
+ label(count)
+ ),
+ (0, import_react33.createElement)("button", {
+ type: "button",
+ className: "bt-news-x",
+ "aria-label": t("Dismiss new messages"),
+ onClick: (event) => {
+ event.stopPropagation();
+ onDismiss();
+ }
+ }, (0, import_react33.createElement)(CloseIcon))
+ );
+ const toLatest = () => {
+ const scroller = document.querySelector("[data-conversation-scroll]");
+ const back = scroller?.querySelector('[class*="_toBottomSlot"]>button');
+ if (back) back.click();
+ else scroller?.scrollTo({ top: scroller.scrollHeight, behavior: "smooth" });
+ };
+ const toDivider = () => document.querySelector("[data-conversation-scroll] .bt-new-sep")?.scrollIntoView({ block: "center", behavior: "smooth" });
+ return (0, import_react_dom6.createPortal)(
+ (0, import_react33.createElement)(
+ import_react33.Fragment,
+ null,
+ showUp ? pill("up", unread, { left: view.center, top: view.top }, toDivider, () => setAbove((state) => ({ ...state, dismissed: true }))) : null,
+ showDown ? pill("down", fresh, { left: view.center, bottom: view.bottom }, toLatest, () => setRelease((state) => ({ ...state, dismissed: true }))) : null
+ ),
+ document.body
);
}
@@@ -25400,13 -24367,14 +25448,14 @@@ function lineDiff(before, after)
}
// src/client/learning-card.js
-var import_react56 = require("react");
+var import_react57 = require("react");
var failedAnswers = /* @__PURE__ */ new Map();
function ProposalCard({ proposal, initialError = "", onFailure, onResolved, actions }) {
+ const outcome = proposal.outcome;
- const [busy, setBusy] = (0, import_react56.useState)(false);
- const [error, setError] = (0, import_react56.useState)(initialError);
- const busyRef = (0, import_react56.useRef)(false);
- const titleId = (0, import_react56.useId)();
+ const [busy, setBusy] = (0, import_react57.useState)(false);
+ const [error, setError] = (0, import_react57.useState)(initialError);
+ const busyRef = (0, import_react57.useRef)(false);
+ const titleId = (0, import_react57.useId)();
const answer = (approve) => {
if (busyRef.current) return;
busyRef.current = true;
@@@ -25428,41 -24396,41 +25477,41 @@@
...(edit.op === "add" ? [] : editLines(edit.old)).map((line) => ({ kind: "removed", line })),
...(edit.op === "remove" ? [] : editLines(edit.text)).map((line) => ({ kind: "added", line }))
]);
- return (0, import_react56.createElement)(
+ return (0, import_react57.createElement)(
"section",
- { className: "bt-q bt-learning-card", role: "group", "aria-labelledby": titleId, "aria-busy": busy },
- (0, import_react57.createElement)(ProposalHead, { titleId, icon: PencilIcon, title: t("AGENTS.md update") }),
+ { className: "bt-q bt-learning-card", role: "group", "aria-labelledby": titleId, "aria-busy": busy, "data-outcome": outcome },
- (0, import_react56.createElement)(ProposalHead, { titleId, icon: PencilIcon, title: t("AGENTS.md update"), outcome }),
- (0, import_react56.createElement)(FileBox, { name: "AGENTS.md", path: proposal.folder, state: proposal.exists === false ? "Added" : "Modified", blocks }),
- proposal.edits.map((edit, index) => edit.why ? (0, import_react56.createElement)("p", { className: "bt-learning-why", key: index }, edit.why) : null),
- error ? (0, import_react56.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null,
- outcome ? null : (0, import_react56.createElement)(ProposalFoot, { busy, answer })
++ (0, import_react57.createElement)(ProposalHead, { titleId, icon: PencilIcon, title: t("AGENTS.md update"), outcome }),
+ (0, import_react57.createElement)(FileBox, { name: "AGENTS.md", path: proposal.folder, state: proposal.exists === false ? "Added" : "Modified", blocks }),
+ proposal.edits.map((edit, index) => edit.why ? (0, import_react57.createElement)("p", { className: "bt-learning-why", key: index }, edit.why) : null),
+ error ? (0, import_react57.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null,
- (0, import_react57.createElement)(ProposalFoot, { busy, answer })
++ outcome ? null : (0, import_react57.createElement)(ProposalFoot, { busy, answer })
);
}
const oldDetail = update && typeof proposal.previous?.description === "string" && proposal.previous.description !== proposal.description ? proposal.previous.description : void 0;
- return (0, import_react56.createElement)(
+ return (0, import_react57.createElement)(
"section",
- { className: "bt-q bt-learning-card", role: "group", "aria-labelledby": titleId, "aria-busy": busy },
- (0, import_react57.createElement)(ProposalHead, { titleId, title: proposal.name, kind: t(update ? "Skill update" : "New skill"), detail: proposal.description, oldDetail }),
+ { className: "bt-q bt-learning-card", role: "group", "aria-labelledby": titleId, "aria-busy": busy, "data-outcome": outcome },
- (0, import_react56.createElement)(ProposalHead, { titleId, title: proposal.name, kind: t(update ? "Skill update" : "New skill"), detail: proposal.description, oldDetail, outcome }),
- (0, import_react56.createElement)(FileBox, { name: "SKILL.md", path: `skills/${proposal.name}`, state: update ? "Updated" : "Added", blocks: [rows2] }),
- proposal.why ? (0, import_react56.createElement)("p", { className: "bt-learning-why" }, proposal.why) : null,
- error ? (0, import_react56.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null,
- outcome ? null : (0, import_react56.createElement)(ProposalFoot, { busy, answer })
++ (0, import_react57.createElement)(ProposalHead, { titleId, title: proposal.name, kind: t(update ? "Skill update" : "New skill"), detail: proposal.description, oldDetail, outcome }),
+ (0, import_react57.createElement)(FileBox, { name: "SKILL.md", path: `skills/${proposal.name}`, state: update ? "Updated" : "Added", blocks: [rows2] }),
+ proposal.why ? (0, import_react57.createElement)("p", { className: "bt-learning-why" }, proposal.why) : null,
+ error ? (0, import_react57.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null,
- (0, import_react57.createElement)(ProposalFoot, { busy, answer })
++ outcome ? null : (0, import_react57.createElement)(ProposalFoot, { busy, answer })
);
}
- function ProposalHead({ titleId, icon: icon2 = MemoryIcon, title, kind, detail, oldDetail }) {
+ function ProposalHead({ titleId, icon: icon2 = MemoryIcon, title, kind, detail, oldDetail, outcome }) {
- return (0, import_react56.createElement)(
+ return (0, import_react57.createElement)(
"div",
{ className: "bt-q-head" },
- (0, import_react56.createElement)("span", { className: "bt-learning-icon", "aria-hidden": true }, (0, import_react56.createElement)(icon2)),
- (0, import_react56.createElement)(
+ (0, import_react57.createElement)("span", { className: "bt-learning-icon", "aria-hidden": true }, (0, import_react57.createElement)(icon2)),
+ (0, import_react57.createElement)(
"div",
{ className: "bt-q-text" },
- (0, import_react56.createElement)("p", { className: "bt-q-title", id: titleId }, title),
- kind ? (0, import_react56.createElement)("div", { className: "bt-q-detail" }, kind) : null,
- oldDetail ? (0, import_react56.createElement)("p", { className: "bt-learning-description bt-learning-old" }, (0, import_react56.createElement)("del", null, oldDetail)) : null,
- detail ? (0, import_react56.createElement)("p", { className: "bt-learning-description" }, detail) : null
+ (0, import_react57.createElement)("p", { className: "bt-q-title", id: titleId }, title),
+ kind ? (0, import_react57.createElement)("div", { className: "bt-q-detail" }, kind) : null,
+ oldDetail ? (0, import_react57.createElement)("p", { className: "bt-learning-description bt-learning-old" }, (0, import_react57.createElement)("del", null, oldDetail)) : null,
+ detail ? (0, import_react57.createElement)("p", { className: "bt-learning-description" }, detail) : null
),
- (0, import_react57.createElement)("span", { className: "bt-q-badge bt-learning-status" }, (0, import_react57.createElement)("span", { className: "bt-learning-dot", "aria-hidden": true }), t("Awaiting approval"))
- outcome ? (0, import_react56.createElement)("span", { className: "bt-q-badge" }, t(outcome === "approved" ? "Approved" : "Declined")) : (0, import_react56.createElement)("span", { className: "bt-q-badge bt-learning-status" }, (0, import_react56.createElement)("span", { className: "bt-learning-dot", "aria-hidden": true }), t("Awaiting approval"))
++ outcome ? (0, import_react57.createElement)("span", { className: "bt-q-badge" }, t(outcome === "approved" ? "Approved" : "Declined")) : (0, import_react57.createElement)("span", { className: "bt-q-badge bt-learning-status" }, (0, import_react57.createElement)("span", { className: "bt-learning-dot", "aria-hidden": true }), t("Awaiting approval"))
);
}
function ProposalFoot({ busy, answer }) {
diff --cc ds-bot/src/client/cells.js
index 60c08a46,eb468da9..13642d5e
--- a/ds-bot/src/client/cells.js
+++ b/ds-bot/src/client/cells.js
@@@ -9,9 -9,8 +9,9 @@@ import { colorOf, toolState, BotMark, R
import { CellEmpty } from './cell-empty.js'
import { sendsOnEnter } from './enter-key.js'
import { SettledQuestion, PendingQuestion } from './questions.js'
- import { AnsweredReply, WidgetCell } from './widget-cell.js'
+ import { AnsweredReply, ClosedView, WidgetCell } from './widget-cell.js'
import { SecretToolCell } from './secret-card.js'
+import { ConnectorToolCell, MailToolCell } from './connectors.js'
import { HandoffCall } from './handoff-card.js'
import { AppAccessCall, ComputerCallRow, ComputerHandoffCall } from './computer.js'
import { t } from './i18n.js'