A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Mark DS Bot's style tags as its own and put them back when removed
Fei2411cd2e63389839
diff --git a/ds-bot/client.js b/ds-bot/client.jsindex 484938ff..43ac6ee9 100644--- a/ds-bot/client.js+++ b/ds-bot/client.js@@ -3067,9 +3067,11 @@ div:has(> nav [class*="_marks"]){display:none!important}.bt-part-line{display:flex;align-items:center;gap:10px;margin:10px 0 6px;font-size:11px;line-height:14px;color:var(--bt-ink-3)}.bt-part-line::before,.bt-part-line::after{content:"";flex:1;height:1px;background:var(--bt-line)}`;+var PLUGIN_ID = "ds-bot";function installStyles(text, tag) {const style = document.createElement("style");style.dataset.dshBot = tag;+ style.dataset.plugin = PLUGIN_ID;style.textContent = text;document.head.appendChild(style);return style;@@ -3103,8 +3105,11 @@ function compileFragmentSelectors(text, names) {}function installCompiledStyles(text, tag) {const style = installStyles("", tag);+ let disposed = false;const cache = /* @__PURE__ */ new WeakMap();const render = () => {+ if (disposed) return;+ if (!style.isConnected) document.head.appendChild(style);const names = /* @__PURE__ */ new Set();for (const sheet of document.styleSheets) {if (sheet.ownerNode?.dataset?.dshBot) continue;@@ -3129,11 +3134,13 @@ function installCompiledStyles(text, tag) {};const shell = (node) => node.dataset?.dshBot === void 0;const observer = new MutationObserver((records) => {+ if (records.some((record) => [...record.removedNodes].includes(style))) render();if (records.some((record) => [...record.addedNodes, ...record.removedNodes].some(shell))) schedule();});observer.observe(document.head, { childList: true });document.addEventListener("load", onLoad, true);return () => {+ disposed = true;observer.disconnect();document.removeEventListener("load", onLoad, true);clearTimeout(timer);@@ -12186,10 +12193,7 @@ var roomRule = () => {if (live && !selector) return room.rule;const declarations2 = room.rule?.style.cssText ?? "";room.rule?.parentStyleSheet?.ownerNode?.remove();- const style = document.createElement("style");- style.dataset.dshBot = "chat-room";- style.textContent = `${selector || '[class*="_centerCol"]'}{${declarations2}}`;- document.head.append(style);+ const style = installStyles(`${selector || '[class*="_centerCol"]'}{${declarations2}}`, "chat-room");room.rule = style.sheet.cssRules[0];room.selector = selector;return room.rule;@@ -14492,10 +14496,7 @@ function apply(ctx) {() => shadow("conversation.input.dock", { id: "bot-question", order: -100, inject: face }, QuestionDock),() => shadow("conversation.input.dock", { id: "bot-secret", order: -90, inject: face }, SecretDock)];- ctx.effect(() => {- const style = installStyles(RETURN_CSS, "return");- return () => style.remove();- }, "ds-bot: return styles");+ ctx.effect(() => installCompiledStyles(RETURN_CSS, "return"), "ds-bot: return styles");shadow("sidebar.footer.action", { id: "bot-return", order: -300, inject: face }, BotReturn);ctx.effect(() => {let previous;diff --git a/ds-bot/src/client/browser-pane.js b/ds-bot/src/client/browser-pane.jsindex 81a600df..e1db51b2 100644--- a/ds-bot/src/client/browser-pane.js+++ b/ds-bot/src/client/browser-pane.js@@ -7,6 +7,7 @@ import { createElement as h, useEffect, useLayoutEffect, useRef, useState } fromimport { createPortal } from 'react-dom'import { BotMark } from './mark.js'import { STORAGE } from './storage.js'+import { installStyles } from './styles.js'import { SPRING_SHAPE, springEasing } from './motion.js'import { DetailsDrawer } from './details-drawer.js'import { t } from './i18n.js'@@ -77,10 +78,7 @@ const roomRule = () => {if (live && !selector) return room.ruleconst declarations = room.rule?.style.cssText ?? ''room.rule?.parentStyleSheet?.ownerNode?.remove()- const style = document.createElement('style')- style.dataset.dshBot = 'chat-room'- style.textContent = `${selector || '[class*="_centerCol"]'}{${declarations}}`- document.head.append(style)+ const style = installStyles(`${selector || '[class*="_centerCol"]'}{${declarations}}`, 'chat-room')room.rule = style.sheet.cssRules[0]room.selector = selectorreturn room.rulediff --git a/ds-bot/src/client/index.js b/ds-bot/src/client/index.jsindex 68081c62..c4127b07 100644--- a/ds-bot/src/client/index.js+++ b/ds-bot/src/client/index.js@@ -690,10 +690,7 @@ export function apply(ctx) {() => shadow('conversation.input.dock', { id: 'bot-secret', order: -90, inject: face }, SecretDock),]// The return button belongs to neither group: it renders only in Agent mode.- ctx.effect(() => {- const style = installStyles(RETURN_CSS, 'return')- return () => style.remove()- }, 'ds-bot: return styles')+ ctx.effect(() => installCompiledStyles(RETURN_CSS, 'return'), 'ds-bot: return styles')shadow('sidebar.footer.action', { id: 'bot-return', order: -300, inject: face }, BotReturn)// The main view decides `plain`: a DSH Agent Session keeps the Bot shell butdiff --git a/ds-bot/src/client/styles.js b/ds-bot/src/client/styles.jsindex e0ab6b95..2ff9f1f9 100644--- a/ds-bot/src/client/styles.js+++ b/ds-bot/src/client/styles.js@@ -1008,9 +1008,15 @@ div:has(> nav [class*="_marks"]){display:none!important}// -------------------------------------------------------------------------+// DSH's ClientModuleSystem claims every <style> without a `data-plugin` for the module+// it is materializing and deletes a module's styles when it unloads. Ours carry our+// module id from the start, so another plugin's claim or teardown never takes them.+const PLUGIN_ID = 'ds-bot'+export function installStyles(text, tag) {const style = document.createElement('style')style.dataset.dshBot = tag+ style.dataset.plugin = PLUGIN_IDstyle.textContent = textdocument.head.appendChild(style)return style@@ -1050,8 +1056,12 @@ function compileFragmentSelectors(text, names) {export function installCompiledStyles(text, tag) {const style = installStyles('', tag)+ let disposed = falseconst cache = new WeakMap()const render = () => {+ if (disposed) return+ // A tag removed out from under us (not by the module system, which owns it) goes back.+ if (!style.isConnected) document.head.appendChild(style)const names = new Set()for (const sheet of document.styleSheets) {if (sheet.ownerNode?.dataset?.dshBot) continue@@ -1068,14 +1078,17 @@ export function installCompiledStyles(text, tag) {const schedule = () => { clearTimeout(timer); timer = setTimeout(render, 120) }const onLoad = (event) => { if (event.target instanceof HTMLLinkElement) schedule() }// Our own sheets name no shell classes, so adding one (the panel's first open adds the- // chat column's rule) recompiles nothing.+ // chat column's rule) recompiles nothing. Our own node coming out is a removal to undo,+ // which render sees without a recompile.const shell = node => node.dataset?.dshBot === undefinedconst observer = new MutationObserver((records) => {+ if (records.some(record => [...record.removedNodes].includes(style))) render()if (records.some(record => [...record.addedNodes, ...record.removedNodes].some(shell))) schedule()})observer.observe(document.head, { childList: true })document.addEventListener('load', onLoad, true)return () => {+ disposed = trueobserver.disconnect()document.removeEventListener('load', onLoad, true)clearTimeout(timer)diff --git a/ds-bot/test/styles.test.js b/ds-bot/test/styles.test.jsnew file mode 100644index 00000000..502f997a--- /dev/null+++ b/ds-bot/test/styles.test.js@@ -0,0 +1,163 @@+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { createRequire } from 'node:module'+import { dirname, join } from 'node:path'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { runInNewContext } from 'node:vm'+import { build } from 'esbuild'++// jsdom and the real client module system come from the harness, as the dsh packages do.+const PLUGIN = dirname(dirname(fileURLToPath(import.meta.url)))+const harness = process.env.DSH_HARNESS ?? join(PLUGIN, '..', 'deepseek-harness')+const requireHarness = createRequire(join(harness, 'package.json'))+const { JSDOM } = requireHarness('jsdom')++// The style helpers and the CSS they ship, bundled once with a minimal React for+// motion.js; they run in each test's jsdom document through the vm context.+const { outputFiles } = await build({+ stdin: {+ contents: "export { installStyles, installCompiledStyles } from './src/client/styles.js'",+ resolveDir: PLUGIN,+ },+ bundle: true, format: 'cjs', platform: 'browser', write: false, logLevel: 'silent',+ external: ['react', 'react-dom', '@deepseek-ai/dsh-client-ui-primitives'],+})+const react = {+ createElement: (type, props, ...children) => ({ type, props: { ...props, children } }), Fragment: Symbol('Fragment'),+ useEffect() {}, useLayoutEffect() {}, useState: initial => [initial, () => {}],+ useMemo: make => make(), useRef: current => ({ current }), useId: () => 'id',+}++const tick = () => new Promise(resolve => setImmediate(resolve))++// The client-modules bundle registers itself through the page's __ModuleLoader__+// facade when it loads; capture that registration once to reach its exports.+const clientModules = (() => {+ const { window } = new JSDOM('<!doctype html><html><head></head><body></body></html>')+ let registration+ const previousWindow = globalThis.window+ globalThis.window = window+ window.__ModuleLoader__ = { load: (record) => { registration = record } }+ try {+ requireHarness('@deepseek-ai/dsh-client-modules/client')+ } finally {+ globalThis.window = previousWindow+ }+ return registration.factory((spec) => { throw new Error(`no seed module ${spec}`) })+})()+const { createClientModuleSystem, parseBootManifest } = clientModules++// A fresh jsdom document, the bundled style helpers bound to it, and a real+// ClientModuleSystem that materializes the pretend modules named in `rows`.+const bench = (rows) => {+ const { window } = new JSDOM('<!doctype html><html><head></head><body></body></html>')+ const module = { exports: {} }+ runInNewContext(outputFiles[0].text, {+ module, exports: module.exports,+ document: window.document,+ MutationObserver: window.MutationObserver,+ HTMLLinkElement: window.HTMLLinkElement,+ setTimeout, clearTimeout,+ require: name => (name === 'react' ? react : {}),+ })+ // The client module system reads the page's globals when it claims and removes.+ const previousGlobals = { window: globalThis.window, document: globalThis.document }+ const inside = (fn) => {+ globalThis.window = window+ globalThis.document = window.document+ try { return fn() } finally { globalThis.window = previousGlobals.window; globalThis.document = previousGlobals.document }+ }+ const boot = (rev) => ({+ rev,+ entries: rows.map(id => ({ id, url: `/modules/${id}.js?rev=${rev}`, rev })),+ batches: rows.length ? [{ phase: 'application', url: `/boot.js?rev=${rev}`, rev, entries: [...rows] }] : [],+ })+ // A bench with no modules never builds the system; the helpers stay undefined.+ const system = rows.length === 0 ? undefined : inside(() => {+ window.__ModuleLoader__ = { mode: 'queue', pendingQueue: [], load() {} }+ return createClientModuleSystem(window.__ModuleLoader__, { id: 'shell', exports: {} }, {+ boot: boot('r1'),+ staticModules: {},+ })+ })+ const materialize = id => inside(() => system.materialize(id))+ const update = (rev, managed = new Map()) => inside(() => system.updateManifest(parseBootManifest(boot(rev)), managed))+ const register = (id, factory) => inside(() => window.__ModuleLoader__.load({ id, factory }))+ return { window, module, materialize, register, update }+}++// #228: our style tags carry the client module id, so another module's materialization+// cannot claim them and its teardown cannot delete them.+test('every DS Bot style is owned by the ds-bot client module', async () => {+ const { window, module, register, materialize, update } = bench(['other'])+ const { installStyles, installCompiledStyles } = module.exports+ const { document } = window+ register('other', () => ({}))++ const plain = installStyles('a{color:red}', 'mentions')+ installCompiledStyles('.b{position:fixed}', 'shell')+ const compiled = document.querySelector('style[data-dsh-bot="shell"]')+ const stray = document.createElement('style')+ stray.textContent = 'stray{}'+ document.head.appendChild(stray)+ for (const style of [plain, compiled]) {+ assert.equal(style.dataset.dshBot !== undefined, true)+ assert.equal(style.dataset.plugin, 'ds-bot')+ assert.equal(style.matches('style:not([data-plugin])'), false)+ }++ // Another module materializing claims only untagged styles; ours keep their owner.+ materialize('other')+ assert.equal(stray.dataset.plugin, 'other')+ assert.equal(plain.dataset.plugin, 'ds-bot')+ assert.equal(compiled.dataset.plugin, 'ds-bot')++ // A newer revision of that module replaces it: its owned styles go, ours stay.+ update('r2')+ await tick()+ assert.equal(stray.isConnected, false)+ assert.equal(plain.isConnected, true)+ assert.equal(compiled.isConnected, true)+})++test('a compiled style removed from outside comes back, until its cleanup runs', async () => {+ const { window, module } = bench([])+ const { installCompiledStyles } = module.exports+ const { document } = window+ const dispose = installCompiledStyles('.b{position:fixed}', 'shell')+ const style = document.querySelector('style[data-dsh-bot="shell"]')+ assert.ok(style.isConnected)++ style.remove()+ await tick()+ assert.equal(style.isConnected, true, 'the observer puts a removed node back')++ dispose()+ await tick()+ assert.equal(style.isConnected, false)+ // Later page changes cannot resurrect it.+ const late = document.createElement('style')+ document.head.appendChild(late)+ await tick()+ assert.equal(style.isConnected, false)+})++test('mounting and unmounting compiled styles twice leaves no extra nodes', async () => {+ const { window, module } = bench([])+ const { installCompiledStyles } = module.exports+ const { document } = window+ for (let round = 0; round < 2; round += 1) {+ const dispose = installCompiledStyles('.b{position:fixed}', 'shell')+ await tick()+ dispose()+ }+ await tick()+ assert.equal(document.querySelectorAll('style[data-dsh-bot]').length, 0)+})++test('the chat-room rule is installed through installStyles, so it is owned too', () => {+ const pane = readFileSync(new URL('../src/client/browser-pane.js', import.meta.url), 'utf8')+ assert.match(pane, /installStyles\(.*'chat-room'/)+ assert.equal(pane.includes("dataset.dshBot = 'chat-room'"), false)+})