dsh-background-by-model 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,385 @@
1
+ /**
2
+ * The host self-check's own tests — run with
3
+ *
4
+ * pnpm test
5
+ *
6
+ * Three things are covered, and they are the three that can rot silently:
7
+ *
8
+ * 1. **The contract table holds together** — unique ids, machine-checkable
9
+ * sources, a known criticality, and at least one check or an explicit
10
+ * "documentation only" marker. A contract point added without a source would
11
+ * otherwise be invisible to the offline scan.
12
+ * 2. **The probe reports what is actually there** — the whole probe is driven
13
+ * against a fixture written in the shape of a host DOM, so "the host renamed
14
+ * `--dsw-specific-menu`" produces exactly the failure the panel claims, and a
15
+ * surface that is merely off screen produces `n/a` rather than a false alarm.
16
+ * 3. **The UI stylesheet, and the one piece of version logic** — every `dab-*`
17
+ * class a component uses is defined in it, and the floor comparison is exact
18
+ * on the release triple.
19
+ *
20
+ * The tests run against the BUILT node entries (`lib/testing.js`), not the
21
+ * TypeScript sources: `node --test` cannot resolve extensionless relative imports
22
+ * inside a `.ts` file, and asserting on the shipped bundle is the more honest
23
+ * target anyway. `pnpm test` bundles first.
24
+ */
25
+ import { test } from 'node:test'
26
+ import assert from 'node:assert/strict'
27
+ import { dirname, join, resolve } from 'node:path'
28
+ import { fileURLToPath, pathToFileURL } from 'node:url'
29
+
30
+ const here = dirname(fileURLToPath(import.meta.url))
31
+ const pluginDir = resolve(here, '..')
32
+ const testingPath = join(pluginDir, 'lib', 'testing.js')
33
+
34
+ const { HOST_CONTRACTS, DSH_FLOOR, probeContracts, verdictOf, meetsFloor, UI_CSS, OWN_SHEET_ATTR, OWN_SHEET_DATASET } =
35
+ await import(pathToFileURL(testingPath).href)
36
+
37
+ const { readFile, readdir } = await import('node:fs/promises')
38
+
39
+ // ── 1. the contract table ────────────────────────────────────────────────────
40
+
41
+ test('contract ids are unique and non-empty', () => {
42
+ const seen = new Set()
43
+ for (const c of HOST_CONTRACTS) {
44
+ assert.ok(c.id.length > 0, 'a contract has an empty id')
45
+ assert.ok(!seen.has(c.id), `duplicate contract id ${c.id}`)
46
+ seen.add(c.id)
47
+ }
48
+ })
49
+
50
+ test('every contract is machine-checkable', () => {
51
+ for (const c of HOST_CONTRACTS) {
52
+ assert.ok(c.target.length > 0, `${c.id} has no target`)
53
+ assert.ok(c.sources.length > 0, `${c.id} declares no source, so the offline scan cannot see it`)
54
+ assert.ok(c.usedBy.length > 0, `${c.id} does not say which plugin file reads it`)
55
+ assert.ok(['core', 'looks', 'label'].includes(c.criticality), `${c.id} has an unknown criticality`)
56
+ assert.ok(['<=0.1.6', '0.1.7'].includes(c.since), `${c.id} has an unknown "since"`)
57
+ for (const s of c.sources) {
58
+ assert.ok(s.literal.length > 0, `${c.id} has a source without a literal`)
59
+ assert.ok(!s.path.includes('\\'), `${c.id} source path must use forward slashes: ${s.path}`)
60
+ if (s.path === '.') assert.equal(s.root, 'frontend', `${c.id}: "." only makes sense for the frontend root`)
61
+ }
62
+ if (c.checks.length === 0) {
63
+ // Documentation-only entries are allowed (a legacy alias we still accept),
64
+ // but they must be the minority and must not claim to be checkable.
65
+ assert.ok(c.criticality !== 'core', `${c.id} is critical but has no check`)
66
+ }
67
+ }
68
+ })
69
+
70
+ test('critical contracts carry a check that can fail', () => {
71
+ const critical = HOST_CONTRACTS.filter(c => c.criticality === 'core')
72
+ assert.ok(critical.length >= 4, 'the model hop and the menu split should be critical')
73
+ for (const c of critical) {
74
+ assert.ok(c.checks.length > 0, `${c.id} is critical but nothing verifies it at runtime`)
75
+ }
76
+ })
77
+
78
+ // ── 2. the probe, against a fixture in the shape of a host DOM ───────────────
79
+
80
+ /** A DOM stand-in with just enough selector support for the contract checks. */
81
+ function makeDom(host) {
82
+ /** `selector → present`, including attribute and comma-OR forms. */
83
+ const matches = sel => {
84
+ for (const part of sel.split(',').map(p => p.trim())) {
85
+ if (host.has(part)) return true
86
+ const attr = /^\[([a-z-]+)\]$/.exec(part)
87
+ if (attr !== null && host.has(`[${attr[1]}]`)) return true
88
+ }
89
+ return false
90
+ }
91
+ return {
92
+ querySelector: sel => (matches(sel) ? { style: {} } : null),
93
+ // Where the host publishes its palette: `body` in the real client, and the
94
+ // fixture models exactly that. Reading the document element instead is what
95
+ // made seven healthy tokens report as empty.
96
+ tokenRoot: () => ({ style: {} }),
97
+ // `on` is null for an unscoped token check (the probe reads it off the token
98
+ // root) and the resolved element otherwise. The fixture answers from its own
99
+ // table either way — whether a value is readable is the host's own business,
100
+ // and that is exactly what the table stands in for.
101
+ computedValue: (token, _on) => (host.get(`computed:${token}`) ?? ''),
102
+ styleSheets: () => [],
103
+ }
104
+ }
105
+
106
+ /** Selectors for the surfaces that are on screen in every fixture. */
107
+ const CORE_PRESENT = [
108
+ 'div[data-sidebar-right-panel]',
109
+ 'div[role="dialog"][aria-modal="true"][aria-labelledby]',
110
+ '[data-shell-overlay]',
111
+ '[data-composer-card]',
112
+ '[data-cordis-panel]',
113
+ '[data-chat-flow]',
114
+ '[data-conversation-scroll]',
115
+ '[data-conversation-composer-overlay]',
116
+ '.dab-root',
117
+ '[data-dockkit-strip]',
118
+ ]
119
+
120
+ /** Every design token the contracts read; each one resolves in a healthy host. */
121
+ const PRESENT_TOKENS = [
122
+ '--dsw-alias-bg-base',
123
+ '--dsw-alias-bg-layer-1',
124
+ '--dsw-alias-bg-layer-2',
125
+ '--dsw-alias-bg-layer-3',
126
+ '--dsw-specific-menu',
127
+ '--dsw-menu-surface-fill',
128
+ '--dsw-specific-sidebar-fill',
129
+ '--dsw-specific-input-major',
130
+ '--dsw-alias-label-caption',
131
+ ]
132
+
133
+ /**
134
+ * The literals the HOST's stylesheets declare. The two halves of a token
135
+ * contract ask different questions — `rule` = "does the host still declare this
136
+ * name", `computed` = "does it resolve to a value" — so both are listed.
137
+ */
138
+ const HOST_RULES = [
139
+ '--dsw-menu-surface-fill', '--dsw-specific-menu', '--dsw-specific-sidebar-fill',
140
+ '--dsw-specific-input-major', '--dsw-alias-bg-base', '--dsw-alias-bg-layer-1',
141
+ '--dsw-alias-label-caption',
142
+ '.md-table-wide', '[data-dockkit-content]', '[data-dockkit-empty]',
143
+ '[data-dockkit-float]', '[data-sidebar-right-open]', 'data-ds-dark-theme',
144
+ ]
145
+
146
+ /** The one literal only THIS plugin's stylesheet declares (`.dab-card`, `side: 'own'`). */
147
+ const OWN_RULES = ['.dab-card']
148
+
149
+ /**
150
+ * A stylesheet the probe may read.
151
+ *
152
+ * `own: true` writes this plugin's marker — the ONLY thing that tells our sheets
153
+ * apart from the host's, since the host's own CSS modules set `data-plugin` on
154
+ * theirs, so a probe keying off that skips the entire host theme.
155
+ *
156
+ * The fixture exposes the attribute the way a REAL element does: `getAttribute`
157
+ * answers the dashed name, and `dataset` only the camel-cased key. Modelling this
158
+ * wrong is how a probe that reads `dataset['data-dab-side']` passes here and
159
+ * silently fails in a browser.
160
+ */
161
+ function sheet(literals, own = false) {
162
+ const attrs = {}
163
+ const dataset = {}
164
+ if (own) {
165
+ attrs[OWN_SHEET_ATTR] = 'own'
166
+ dataset[OWN_SHEET_DATASET] = 'own'
167
+ }
168
+ return {
169
+ ownerNode: {
170
+ dataset,
171
+ getAttribute: name => (name in attrs ? attrs[name] : null),
172
+ setAttribute: (name, value) => { attrs[name] = value },
173
+ },
174
+ cssRules: literals.map(l => ({ cssText: `.x{color:red}/* ${l} */` })),
175
+ }
176
+ }
177
+
178
+ /** The host's sheets plus our own, minus whatever a test removes. */
179
+ function hostStyles(literals = HOST_RULES, ownLiterals = OWN_RULES) {
180
+ const sheets = [sheet(literals)]
181
+ if (ownLiterals.length > 0) sheets.push(sheet(ownLiterals, true))
182
+ return sheets
183
+ }
184
+
185
+ /**
186
+ * A fixture host: `selectors` are the ones that match, `rules` the literals the
187
+ * host stylesheet declares, and every token in `PRESENT_TOKENS` resolves unless
188
+ * the caller drops it.
189
+ */
190
+ function hostEnv({ ctx, selectors = CORE_PRESENT, rules = HOST_RULES, tokens = PRESENT_TOKENS }) {
191
+ // A Map, not a Set: the fixture must answer with the token's VALUE, and only a
192
+ // Map carries one (a Set has no `get`).
193
+ const host = new Map()
194
+ for (const s of selectors) host.set(s, true)
195
+ for (const t of tokens) host.set(`computed:${t}`, '#123456')
196
+ return { ...makeDom(host), styleSheets: () => hostStyles(rules), ctx }
197
+ }
198
+
199
+ /** The healthy fixture: nothing missing, every service published. */
200
+ const healthyEnv = () => hostEnv({ ctx: healthyCtx() })
201
+
202
+ /** A context publishing the four services the model hop needs. */
203
+ function healthyCtx(overrides = {}) {
204
+ const face = { subscribe: () => () => {}, getSnapshot: () => ({}) }
205
+ const services = {
206
+ sessions: { list: face, binding: () => ({}) },
207
+ uiSession: { current: face },
208
+ modelDirectories: { directoryFor: () => ({ store: face }) },
209
+ ...overrides,
210
+ }
211
+ return { get: id => services[id] }
212
+ }
213
+
214
+ test('a healthy host passes every contract', () => {
215
+ const results = probeContracts(healthyEnv(), 'en')
216
+ const failed = results.filter(r => r.status === 'fail')
217
+ assert.deepEqual(failed.map(r => r.id), [], `unexpected failures: ${failed.map(r => `${r.id}: ${r.reason}`).join('; ')}`)
218
+ assert.equal(verdictOf({ results, summary: { pass: results.length, fail: 0, skip: 0, total: results.length } }), 'ok')
219
+ })
220
+
221
+ test('a renamed menu token fails exactly that contract, and names the symptom', () => {
222
+ // The 0.1.8 rename: the host stops declaring the token the sticky group
223
+ // headings paint from. Everything else still answers.
224
+ const env = hostEnv({ ctx: healthyCtx(), rules: HOST_RULES.filter(l => l !== '--dsw-menu-surface-fill') })
225
+ const results = probeContracts(env, 'en')
226
+ const failed = results.filter(r => r.status === 'fail').map(r => r.id)
227
+ assert.deepEqual(failed, ['token.menuSurface'])
228
+ const row = results.find(r => r.id === 'token.menuSurface')
229
+ assert.match(row.reason, /--dsw-menu-surface-fill/)
230
+ assert.match(row.symptom, /solid band|white band|sticky/i)
231
+ })
232
+
233
+ test('a renamed token the host still aliases is caught by the rule half', () => {
234
+ // The 0.1.7 menu split in reverse: the host keeps the OLD name working (aliased)
235
+ // but stops declaring the new one. `computed` still answers — which is exactly
236
+ // how that bug stayed silent — so the `rule` half is the only thing that can
237
+ // tell "renamed" from "still there".
238
+ const env = hostEnv({
239
+ ctx: healthyCtx(),
240
+ rules: HOST_RULES.filter(l => l !== '--dsw-menu-surface-fill'),
241
+ })
242
+ const results = probeContracts(env, 'en')
243
+ const row = results.find(r => r.id === 'token.menuSurface')
244
+ assert.equal(row.status, 'fail')
245
+ // The computed half would have passed: the token still resolves a value.
246
+ assert.match(row.detail, /host stylesheet includes/)
247
+ })
248
+
249
+ test('a host that stops publishing the palette fails the computed half', () => {
250
+ // The other failure shape: the name is still declared somewhere, but body no
251
+ // longer carries a value — the case that made 7 healthy tokens look empty when
252
+ // the probe read the wrong element.
253
+ const env = hostEnv({
254
+ ctx: healthyCtx(),
255
+ tokens: PRESENT_TOKENS.filter(t => t !== '--dsw-alias-bg-base'),
256
+ })
257
+ const results = probeContracts(env, 'en')
258
+ const row = results.find(r => r.id === 'token.bgBase')
259
+ assert.equal(row.status, 'fail')
260
+ assert.match(row.reason, /--dsw-alias-bg-base/)
261
+ })
262
+
263
+ test('a dropped session service fails the model hop', () => {
264
+ const env = hostEnv({ ctx: healthyCtx({ sessions: undefined }) })
265
+ const results = probeContracts(env, 'en')
266
+ assert.equal(results.find(r => r.id === 'sessions.list').status, 'fail')
267
+ assert.equal(results.find(r => r.id === 'sessions.binding.projections').status, 'skip')
268
+ })
269
+
270
+ test('the plugin\'s own token stylesheet cannot make a host check pass', () => {
271
+ // The situation that produced the 0.1.7 white band: the plugin re-emits the
272
+ // menu fill itself, so its own sheet declares the token. That re-emission must
273
+ // never be accepted as evidence about the HOST — otherwise the check is green
274
+ // by construction on exactly the host where the token was renamed away.
275
+ const env = hostEnv({
276
+ ctx: healthyCtx(),
277
+ // The host sheet is readable but has moved on: it no longer declares the
278
+ // menu fill under this name.
279
+ rules: [],
280
+ })
281
+ env.styleSheets = () => [
282
+ sheet([]), // the host's own, readable, declaring nothing
283
+ sheet(['--dsw-menu-surface-fill', '--dsw-specific-menu', '.dab-card'], true),
284
+ ]
285
+ const results = probeContracts(env, 'en')
286
+ const byId = id => results.find(r => r.id === id)
287
+ assert.equal(byId('token.menuSurface').status, 'fail')
288
+ assert.match(byId('token.menuSurface').reason, /no host stylesheet declares/)
289
+ assert.equal(byId('token.menuAlias').status, 'fail')
290
+ // …while the contract whose other half IS our own sheet still passes: this is
291
+ // what `side: 'own'` is for, and why the two sides must never be merged.
292
+ assert.equal(byId('settings.card').status, 'pass')
293
+ })
294
+
295
+ test('a host sheet carrying data-plugin is not mistaken for ours', () => {
296
+ // Regression for the probe bug that reported 7 healthy tokens as renamed: the
297
+ // host's CSS modules ALSO set `data-plugin` on their <style> elements, so a
298
+ // probe that skips "sheets with data-plugin" skips the host's whole theme.
299
+ const hostSheet = sheet(['--dsw-alias-bg-base'])
300
+ hostSheet.ownerNode.dataset.plugin = '@deepseek-ai/dsh-client-ui-theme'
301
+ const env = hostEnv({ ctx: healthyCtx(), rules: [] })
302
+ env.styleSheets = () => [hostSheet]
303
+ const results = probeContracts(env, 'en')
304
+ assert.equal(results.find(r => r.id === 'token.bgBase').status, 'pass')
305
+ })
306
+
307
+ test('a surface that is merely off screen is n/a, not a failure', () => {
308
+ // The app frame and every service are up (the settings section is rendered
309
+ // inside the frame, so the frame is always there) — but the conversation view,
310
+ // the right panel and the Cordis panel are not. Nothing is broken; those
311
+ // surfaces simply are not there to observe.
312
+ const env = hostEnv({
313
+ ctx: healthyCtx(),
314
+ selectors: ['.dab-root', 'div[role="dialog"][aria-modal="true"][aria-labelledby]', '[data-shell-overlay]'],
315
+ })
316
+ const results = probeContracts(env, 'en')
317
+ const byId = id => results.find(r => r.id === id)
318
+ assert.equal(byId('chat.flow').status, 'skip')
319
+ assert.equal(byId('conversation.scroll').status, 'skip')
320
+ assert.equal(byId('trajectory.root').status, 'skip')
321
+ assert.equal(byId('rightbar.panel').status, 'skip')
322
+ assert.equal(byId('cordis.panel').status, 'skip')
323
+ assert.equal(byId('composer.card').status, 'skip')
324
+ assert.equal(byId('settings.dialog').status, 'pass')
325
+ assert.deepEqual(results.filter(r => r.status === 'fail').map(r => r.id), [])
326
+ })
327
+
328
+ test('a mounted but marker-less surface is a failure, not n/a', () => {
329
+ // The dialog is open, so the right panel's anchor is off screen — but the
330
+ // dialog's own selector still matches. A surface whose anchor IS on screen and
331
+ // whose selector is not is a rename, and must not read as "not observable".
332
+ const env = hostEnv({
333
+ ctx: healthyCtx(),
334
+ // The dock chrome is mounted (the panel container exists) but the panel
335
+ // attribute the contract names is gone.
336
+ selectors: ['.dab-root', '[data-dockkit-strip]'],
337
+ })
338
+ const results = probeContracts(env, 'en')
339
+ const byId = id => results.find(r => r.id === id)
340
+ assert.equal(byId('rightbar.panel').status, 'fail')
341
+ assert.match(byId('rightbar.panel').reason, /data-sidebar-right-panel/)
342
+ assert.equal(byId('chat.flow').status, 'skip')
343
+ })
344
+
345
+ // ── 3. the settings UI's own stylesheet ──────────────────────────────────────
346
+
347
+ test('every dab-* class a component uses is defined in the UI stylesheet', async () => {
348
+ const dir = join(pluginDir, 'src', 'client')
349
+ const files = []
350
+ const walk = async d => {
351
+ for (const entry of await readdir(d, { withFileTypes: true })) {
352
+ const p = join(d, entry.name)
353
+ if (entry.isDirectory()) await walk(p)
354
+ else if (entry.name.endsWith('.tsx')) files.push(p)
355
+ }
356
+ }
357
+ await walk(dir)
358
+ assert.ok(files.length > 0, 'no component sources found')
359
+
360
+ const missing = []
361
+ for (const file of files) {
362
+ const text = await readFile(file, 'utf8')
363
+ for (const m of text.matchAll(/(?<![\w-])dab-[a-z0-9-]+/g)) {
364
+ const cls = m[0]
365
+ // `--dab-mono` and friends are this plugin's own CSS VARIABLES, not classes.
366
+ if (text.slice(Math.max(0, m.index - 2), m.index) === '--') continue
367
+ if (UI_CSS.includes(`.${cls}`)) continue
368
+ if (missing.some(x => x.cls === cls && x.file === file)) continue
369
+ missing.push({ cls, file: file.slice(pluginDir.length + 1) })
370
+ }
371
+ }
372
+ assert.deepEqual(missing, [], `classes used but never styled: ${missing.map(m => `${m.cls} (${m.file})`).join(', ')}`)
373
+ })
374
+
375
+ // ── 4. the floor comparison ──────────────────────────────────────────────────
376
+
377
+ test('the floor comparison is coarse on purpose and exact on the triple', () => {
378
+ assert.equal(meetsFloor('0.1.7-rc.2', DSH_FLOOR), true, 'the floor itself satisfies the floor')
379
+ assert.equal(meetsFloor('0.1.7', DSH_FLOOR), true)
380
+ assert.equal(meetsFloor('0.2.0', DSH_FLOOR), true)
381
+ assert.equal(meetsFloor('1.0.0', DSH_FLOOR), true)
382
+ assert.equal(meetsFloor('0.1.6', DSH_FLOOR), false)
383
+ assert.equal(meetsFloor('0.1.0', DSH_FLOOR), false)
384
+ assert.equal(meetsFloor('not-a-version', DSH_FLOOR), null)
385
+ })