dsh-gitnexus-plus 0.0.0-stage → 0.1.1

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.
Files changed (78) hide show
  1. package/LICENSE +38 -0
  2. package/README.md +483 -2
  3. package/cordis.patch.yml +18 -0
  4. package/lib/bin/gitnexus-coverage.d.ts +14 -0
  5. package/lib/bin/gitnexus-coverage.d.ts.map +1 -0
  6. package/lib/bin/gitnexus-coverage.js +171 -0
  7. package/lib/bin/gitnexus-coverage.js.map +1 -0
  8. package/lib/client.js +1642 -0
  9. package/lib/gitnexus/analyze.d.ts +148 -0
  10. package/lib/gitnexus/analyze.d.ts.map +1 -0
  11. package/lib/gitnexus/analyze.js +283 -0
  12. package/lib/gitnexus/analyze.js.map +1 -0
  13. package/lib/gitnexus/commands.d.ts +96 -0
  14. package/lib/gitnexus/commands.d.ts.map +1 -0
  15. package/lib/gitnexus/commands.js +132 -0
  16. package/lib/gitnexus/commands.js.map +1 -0
  17. package/lib/gitnexus/coverage.d.ts +340 -0
  18. package/lib/gitnexus/coverage.d.ts.map +1 -0
  19. package/lib/gitnexus/coverage.js +552 -0
  20. package/lib/gitnexus/coverage.js.map +1 -0
  21. package/lib/gitnexus/format.d.ts +16 -0
  22. package/lib/gitnexus/format.d.ts.map +1 -0
  23. package/lib/gitnexus/format.js +178 -0
  24. package/lib/gitnexus/format.js.map +1 -0
  25. package/lib/gitnexus/git-activity.d.ts +136 -0
  26. package/lib/gitnexus/git-activity.d.ts.map +1 -0
  27. package/lib/gitnexus/git-activity.js +345 -0
  28. package/lib/gitnexus/git-activity.js.map +1 -0
  29. package/lib/gitnexus/git.d.ts +70 -0
  30. package/lib/gitnexus/git.d.ts.map +1 -0
  31. package/lib/gitnexus/git.js +121 -0
  32. package/lib/gitnexus/git.js.map +1 -0
  33. package/lib/gitnexus/index-meta.d.ts +150 -0
  34. package/lib/gitnexus/index-meta.d.ts.map +1 -0
  35. package/lib/gitnexus/index-meta.js +156 -0
  36. package/lib/gitnexus/index-meta.js.map +1 -0
  37. package/lib/gitnexus/install.d.ts +97 -0
  38. package/lib/gitnexus/install.d.ts.map +1 -0
  39. package/lib/gitnexus/install.js +228 -0
  40. package/lib/gitnexus/install.js.map +1 -0
  41. package/lib/gitnexus/languages.d.ts +73 -0
  42. package/lib/gitnexus/languages.d.ts.map +1 -0
  43. package/lib/gitnexus/languages.js +217 -0
  44. package/lib/gitnexus/languages.js.map +1 -0
  45. package/lib/gitnexus/root.d.ts +68 -0
  46. package/lib/gitnexus/root.d.ts.map +1 -0
  47. package/lib/gitnexus/root.js +162 -0
  48. package/lib/gitnexus/root.js.map +1 -0
  49. package/lib/gitnexus/scan.d.ts +67 -0
  50. package/lib/gitnexus/scan.d.ts.map +1 -0
  51. package/lib/gitnexus/scan.js +247 -0
  52. package/lib/gitnexus/scan.js.map +1 -0
  53. package/lib/gitnexus/toolchain.d.ts +136 -0
  54. package/lib/gitnexus/toolchain.d.ts.map +1 -0
  55. package/lib/gitnexus/toolchain.js +251 -0
  56. package/lib/gitnexus/toolchain.js.map +1 -0
  57. package/lib/index.d.ts +79 -0
  58. package/lib/index.d.ts.map +1 -0
  59. package/lib/index.js +211 -0
  60. package/lib/index.js.map +1 -0
  61. package/lib/routes/analyze.d.ts +35 -0
  62. package/lib/routes/analyze.d.ts.map +1 -0
  63. package/lib/routes/analyze.js +71 -0
  64. package/lib/routes/analyze.js.map +1 -0
  65. package/lib/routes/coverage.d.ts +44 -0
  66. package/lib/routes/coverage.d.ts.map +1 -0
  67. package/lib/routes/coverage.js +68 -0
  68. package/lib/routes/coverage.js.map +1 -0
  69. package/lib/routes/guard.d.ts +92 -0
  70. package/lib/routes/guard.d.ts.map +1 -0
  71. package/lib/routes/guard.js +187 -0
  72. package/lib/routes/guard.js.map +1 -0
  73. package/lib/routes/install.d.ts +27 -0
  74. package/lib/routes/install.d.ts.map +1 -0
  75. package/lib/routes/install.js +46 -0
  76. package/lib/routes/install.js.map +1 -0
  77. package/package.json +87 -4
  78. package/scripts/link-runtime.mjs +146 -0
package/lib/client.js ADDED
@@ -0,0 +1,1642 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-gitnexus-plus",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ "use strict";
7
+ /**
8
+ * dsh-gitnexus-plus — browser half.
9
+ *
10
+ * Plain CommonJS on purpose. The in-tree client preset (`packages/client/tsdown.client.ts`)
11
+ * is unpublished, so an out-of-tree plugin must reproduce its output format with
12
+ * its own toolchain — and the honest minimum here is no toolchain at all: this
13
+ * module's only imports are platform baseline modules, so it can be wrapped into
14
+ * the loader's factory verbatim by `scripts/build-client.mjs`, with no bundler and
15
+ * no node_modules in the loop.
16
+ *
17
+ * UI COMES FROM THE SHARED PRIMITIVES PACKAGE
18
+ * -------------------------------------------
19
+ * An earlier revision hand-rolled every control with inline styles, on the
20
+ * reasoning that `@deepseek-ai/dsh-client-ui-primitives` ships no JS in the
21
+ * installed runtime and its exports therefore could not be verified. That
22
+ * reasoning was wrong twice over. The package's own README states the rule —
23
+ * "plugins cannot import another plugin's components, so this package is the one
24
+ * place controls can be shared; reuse them" — and the installed plugin
25
+ * `dsh-context` declares it as a peer dependency, which is exactly how a plugin is
26
+ * meant to get a native look.
27
+ *
28
+ * Every prop used below was read off a real call site in an installed plugin
29
+ * bundle rather than inferred from prose, because a wrong prop name fails
30
+ * silently: React renders the component with its defaults and nothing throws.
31
+ *
32
+ * Button variant: "ghost" | "outline" | "primary" | "toolbar"
33
+ * StateDot state: "done" | "warning" | "error" | "idle" | "ongoing"
34
+ * Tag tone: "neutral" | "solid" | "outline" | "info"
35
+ * PathLabel path
36
+ * FileTypeIcon path | kind (from classifyFileType) , size, className
37
+ * Tooltip label, side, delayMs, portal — wraps a single child
38
+ *
39
+ * WHAT THE PANEL SHOWS, AND WHY
40
+ * -----------------------------
41
+ * GitNexus prints skipped files once, to stderr, and never exposes them again. The
42
+ * panel keeps that visible: the bar answers "how much of this repository does the
43
+ * index actually represent?", the warning block says what was dropped, and the
44
+ * file list says whether what was dropped is source or build output.
45
+ */
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ // Namespace imports, not `require` and not default imports. `tsconfig.client.json`
48
+ // runs with `esModuleInterop: false`, under which `import * as React from 'react'`
49
+ // compiles to a bare `const React = require("react")` — exactly the form the loader
50
+ // factory provides, with no `__importStar` helper riding along into every page load.
51
+ // It is also the only form that gives `React.ReactNode` and `React.CSSProperties`
52
+ // as usable type namespaces.
53
+ const React = require("react");
54
+ const primitives = require("@deepseek-ai/dsh-client-ui-primitives");
55
+ const { Button, FileTypeIcon, PathLabel, SegmentedControl, StateDot, Tag, Tooltip, IconRefreshOutlineRegular, classifyFileType, } = primitives;
56
+ const h = React.createElement;
57
+ /** Must match the `id` in the loader factory written by scripts/build-client.mjs. */
58
+ const PLUGIN_ID = 'dsh-gitnexus-plus';
59
+ /** The sidebar-right tab type this plugin contributes. */
60
+ const TAB_KIND = 'gitnexus';
61
+ /**
62
+ * How a run's state reads at a glance.
63
+ *
64
+ * Typed to the primitive's own union rather than `string`, so a state added to
65
+ * `ClientAnalyzeRun` without a mapping here fails to compile instead of rendering a
66
+ * dot the primitive silently falls back on.
67
+ */
68
+ function runStateTone(state) {
69
+ switch (state) {
70
+ case 'done':
71
+ return 'done';
72
+ case 'running':
73
+ // The primitive spells this `ongoing`; the host calls it `running`.
74
+ return 'ongoing';
75
+ case 'cancelled':
76
+ return 'idle';
77
+ // Not errors: the sandbox did its job, and the operator's next step is to run the
78
+ // command themselves rather than to investigate a failure.
79
+ case 'denied':
80
+ case 'unavailable':
81
+ return 'warning';
82
+ default:
83
+ return 'error';
84
+ }
85
+ }
86
+ function runStateLabel(state) {
87
+ switch (state) {
88
+ case 'unavailable':
89
+ return '无法执行';
90
+ case 'running':
91
+ return '刷新中';
92
+ case 'done':
93
+ return '已完成';
94
+ case 'failed':
95
+ return '失败';
96
+ case 'timed-out':
97
+ return '超时终止';
98
+ case 'cancelled':
99
+ return '已取消';
100
+ case 'denied':
101
+ return '沙箱拒绝';
102
+ }
103
+ }
104
+ /**
105
+ * Empty blocks used to narrow a report past the point where an index is known to
106
+ * exist. Zeros rather than absent fields, so a partially-populated report from an
107
+ * older index still renders numbers instead of `undefined`.
108
+ */
109
+ const ZERO_TOTALS = {
110
+ scanned: 0,
111
+ selected: 0,
112
+ indexedInGraph: 0,
113
+ large: 0,
114
+ largeBytes: 0,
115
+ suppressedDeclarations: 0,
116
+ };
117
+ const ZERO_CAP = { text: '—', source: 'default', maxText: '—' };
118
+ const ZERO_ANALYZER = {
119
+ gitnexusVersion: null,
120
+ primitives: 'unknown',
121
+ };
122
+ // ---------------------------------------------------------------------------
123
+ // Routes
124
+ // ---------------------------------------------------------------------------
125
+ /**
126
+ * Resolve one of this plugin's host routes against the PAGE's own base.
127
+ *
128
+ * Two failures are avoided here. A leading slash pins a URL to the origin root,
129
+ * which walks out of any reverse-proxy directory prefix. And resolving against
130
+ * `location.host` breaks on the desktop shell, whose page origin is `dsh-app://app`
131
+ * — a hostname that never completes a DNS lookup.
132
+ *
133
+ * @param {string} path
134
+ * @returns {string}
135
+ */
136
+ function routeUrl(path) {
137
+ const raw = typeof document !== 'undefined' && typeof document.baseURI === 'string' ? document.baseURI : '';
138
+ const placeholder = 'http://dsh.invalid/';
139
+ const url = new URL(raw === '' ? placeholder : raw, placeholder);
140
+ url.search = '';
141
+ url.hash = '';
142
+ if (!url.pathname.endsWith('/'))
143
+ url.pathname += '/';
144
+ return new URL(path.replace(/^\/+/, ''), url.href).href;
145
+ }
146
+ // ---------------------------------------------------------------------------
147
+ // Pure view-model helpers (exported for tests)
148
+ // ---------------------------------------------------------------------------
149
+ /**
150
+ * Fall back to local formatting unless the primitives package exposes its own.
151
+ * `fileSizeText` was present in the export surface of installed bundles but never
152
+ * observed at a call site, so it is used opportunistically rather than assumed.
153
+ * @param {number} bytes
154
+ */
155
+ function fileSize(bytes) {
156
+ if (typeof primitives.fileSizeText === 'function')
157
+ return primitives.fileSizeText(bytes);
158
+ return formatBytes(bytes);
159
+ }
160
+ function formatBytes(bytes) {
161
+ if (!Number.isFinite(bytes) || bytes < 0)
162
+ return '—';
163
+ if (bytes < 1024)
164
+ return `${bytes} B`;
165
+ if (bytes < 1024 * 1024)
166
+ return `${(bytes / 1024).toFixed(1)} KB`;
167
+ if (bytes < 1024 * 1024 * 1024)
168
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
169
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
170
+ }
171
+ /**
172
+ * Percentage of a whole, as a number in [0, 100].
173
+ * @param {number} part
174
+ * @param {number} whole
175
+ */
176
+ function percent(part, whole) {
177
+ if (!Number.isFinite(part) || !Number.isFinite(whole) || whole <= 0)
178
+ return 0;
179
+ return (part / whole) * 100;
180
+ }
181
+ function fixed(value, digits) {
182
+ return Number.isFinite(value) ? value.toFixed(digits) : '0.0';
183
+ }
184
+ /**
185
+ * Turn language rows into stack segments whose widths sum to exactly 100.
186
+ *
187
+ * Rounding each share independently leaves a visible gap or overflow in a stacked
188
+ * bar, so the largest segment absorbs the residual. The metric is a parameter
189
+ * because "what is this repository written in" has two defensible answers — bytes
190
+ * for weight of code, files for breadth of surface — and they disagree often enough
191
+ * that showing only one invites the wrong conclusion.
192
+ */
193
+ function stackSegments(rows, totalBytes, totalFiles, metric = 'bytes') {
194
+ if (!Array.isArray(rows) || rows.length === 0)
195
+ return [];
196
+ const whole = metric === 'files' ? totalFiles : totalBytes;
197
+ const valueOf = (row) => (metric === 'files' ? row.files : row.bytes);
198
+ const shares = rows.map((row) => ({
199
+ key: row.key,
200
+ label: row.label,
201
+ color: row.color,
202
+ percent: percent(valueOf(row), whole),
203
+ }));
204
+ const sum = shares.reduce((acc, s) => acc + s.percent, 0);
205
+ if (sum > 0 && Math.abs(sum - 100) > 0.005) {
206
+ let biggest = 0;
207
+ for (let i = 1; i < shares.length; i += 1) {
208
+ if (shares[i].percent > shares[biggest].percent)
209
+ biggest = i;
210
+ }
211
+ shares[biggest].percent += 100 - sum;
212
+ }
213
+ return shares;
214
+ }
215
+ /**
216
+ * Split the report's warnings by severity.
217
+ *
218
+ * Warnings arrive as structured records rather than prose so that a caller (the
219
+ * model, via the tool) can act on `code`. The panel only renders them, but keeps
220
+ * the split: `warn` is what the reader must not miss, `info` is context.
221
+ *
222
+ * @param {Array<{level:string,code:string,message:string}>} warnings
223
+ */
224
+ function splitWarnings(warnings) {
225
+ const list = Array.isArray(warnings) ? warnings : [];
226
+ return {
227
+ notable: list.filter((w) => w.level === 'warn'),
228
+ context: list.filter((w) => w.level !== 'warn'),
229
+ };
230
+ }
231
+ /**
232
+ * Derive the header's one-line summary from a report.
233
+ * @param {any} report
234
+ * @returns {string}
235
+ */
236
+ function summaryLine(report) {
237
+ if (report === null || typeof report !== 'object')
238
+ return '';
239
+ // Optional-chained per read rather than `report.totals ?? {}`: an empty object
240
+ // literal would erase the field types and every read below would be `unknown`.
241
+ const totals = report.totals;
242
+ const parts = [
243
+ `扫描 ${totals?.scanned ?? 0}`,
244
+ `选中 ${totals?.selected ?? 0}`,
245
+ `图内 ${totals?.indexedInGraph ?? 0}`,
246
+ ];
247
+ const large = totals?.large ?? 0;
248
+ if (large > 0)
249
+ parts.push(`跳过 ${large}`);
250
+ const suppressed = totals?.suppressedDeclarations ?? 0;
251
+ if (suppressed > 0)
252
+ parts.push(`声明抑制 ${suppressed}`);
253
+ return parts.join(' · ');
254
+ }
255
+ /**
256
+ * Fraction of scanned files the index covers, in [0, 1], or `null` when there is
257
+ * nothing to divide by — so the UI can omit rather than print a fabricated 0/100.
258
+ * @param {any} report
259
+ * @returns {number | null}
260
+ */
261
+ function coverageRatio(report) {
262
+ const scanned = report?.totals?.scanned;
263
+ const indexed = report?.totals?.indexedInGraph;
264
+ // Explicit `typeof` guards rather than `Number.isFinite` alone: `isFinite` takes
265
+ // `unknown` and does not narrow, so the division below would still be typed
266
+ // against a possibly-absent value.
267
+ if (typeof scanned !== 'number' || typeof indexed !== 'number')
268
+ return null;
269
+ if (!Number.isFinite(scanned) || !Number.isFinite(indexed) || scanned <= 0)
270
+ return null;
271
+ return Math.max(0, Math.min(1, indexed / scanned));
272
+ }
273
+ /**
274
+ * Index health as a `StateDot` state.
275
+ *
276
+ * `error` is reserved for an index that is absent or badly behind; `warning` for
277
+ * one that is usable but has dropped files worth knowing about.
278
+ * @param {any} report
279
+ * @returns {'done' | 'warning' | 'error' | 'idle'}
280
+ */
281
+ function healthState(report) {
282
+ if (report === null || report?.repo?.indexed !== true)
283
+ return 'error';
284
+ const ratio = coverageRatio(report);
285
+ const skipped = report?.totals?.large ?? 0;
286
+ if (skipped > 0)
287
+ return 'warning';
288
+ if (ratio !== null && ratio < 0.9)
289
+ return 'warning';
290
+ return 'done';
291
+ }
292
+ /**
293
+ * Staleness as a dot state plus a sentence.
294
+ *
295
+ * `diverged` is deliberately not folded into `behind`: when HEAD has moved off the
296
+ * indexed commit, the distance between them does not measure how much of the index
297
+ * is wrong, so the UI must not imply a count it cannot give. Measured on a real
298
+ * repository, the panel had been showing the indexed commit as though it were
299
+ * current while HEAD was already one commit ahead on a different line.
300
+ *
301
+ * @param {any} staleness
302
+ * @returns {{ state: 'done' | 'warning' | 'error' | 'idle', text: string }}
303
+ */
304
+ function stalenessView(staleness) {
305
+ if (!staleness || staleness.gitAvailable !== true) {
306
+ return { state: 'idle', text: 'git 不可用,无法判断新鲜度' };
307
+ }
308
+ const short = (sha) => (typeof sha === 'string' && sha !== '' ? sha.slice(0, 8) : '?');
309
+ const head = short(staleness.headCommit);
310
+ const indexed = short(staleness.indexedCommit);
311
+ const dirtyCount = typeof staleness.dirtyCount === 'number' ? staleness.dirtyCount : 0;
312
+ const dirty = dirtyCount > 0 ? `,工作区 ${dirtyCount} 处未提交改动` : '';
313
+ switch (staleness.state) {
314
+ case 'current':
315
+ return { state: 'done', text: `current · HEAD ${head} 与索引一致${dirty}` };
316
+ case 'behind': {
317
+ const ahead = staleness.aheadBehind?.ahead ?? 0;
318
+ // Says where the action lives, not that one is available nearby. The previous
319
+ // wording — "可直接增量刷新" — sat directly under the panel's refresh button and
320
+ // read as an instruction to press it, while that control only re-reads the
321
+ // report and never touches the index. Pointing at the maintenance commands
322
+ // costs one clause and stops the panel promising something it does not do.
323
+ return {
324
+ state: 'warning',
325
+ text: `behind · 索引落后 ${ahead} 个提交(${indexed} → ${head})· 重建见下方「维护命令」${dirty}`,
326
+ };
327
+ }
328
+ case 'diverged': {
329
+ // Diverged means the *indexed* commit holds work HEAD no longer reaches —
330
+ // not merely that HEAD is ahead. The distinction decides whether an
331
+ // incremental refresh is enough or a rebuild is required, so the wording
332
+ // must not blur it.
333
+ const indexedSide = staleness.aheadBehind?.behind ?? 0;
334
+ return {
335
+ state: 'warning',
336
+ text: `diverged · HEAD ${head} 已偏离索引提交 ${indexed}(索引侧另有 ${indexedSide} 个提交不在 HEAD 上)` +
337
+ `${dirty}`,
338
+ };
339
+ }
340
+ default:
341
+ return { state: 'idle', text: `unknown · 无法比对 ${indexed} 与 ${head}${dirty}` };
342
+ }
343
+ }
344
+ /**
345
+ * Capability rows for the query surfaces, in a fixed order so the panel does not
346
+ * reshuffle between repositories.
347
+ *
348
+ * A capability whose provider reports `unavailable` still gets a row: "no keyword
349
+ * search" is information, and hiding it is how a reader concludes the graph can do
350
+ * something it cannot.
351
+ *
352
+ * @param {any} capabilities
353
+ * @returns {Array<{ key: string, label: string, ok: boolean, provider: string, note: string }>}
354
+ */
355
+ const CAPABILITY_KEYS = ['graph', 'fts', 'vectorSearch'];
356
+ function capabilityRows(capabilities) {
357
+ const caps = capabilities ?? {};
358
+ // Keyed by the same literal union the loop walks, so the lookup is checked rather
359
+ // than an index-signature read that would silently yield `undefined`.
360
+ const labels = {
361
+ graph: '图查询',
362
+ fts: '关键词搜索',
363
+ vectorSearch: '语义搜索',
364
+ };
365
+ return CAPABILITY_KEYS.map((key) => {
366
+ const entry = caps[key] ?? {};
367
+ const ok = entry.status === 'available';
368
+ return {
369
+ key,
370
+ label: labels[key],
371
+ ok,
372
+ provider: typeof entry.provider === 'string' ? entry.provider : 'unknown',
373
+ note: ok ? '' : String(entry.skipReason ?? entry.status ?? 'unavailable'),
374
+ };
375
+ });
376
+ }
377
+ /**
378
+ * Summarise the resolver's untyped receiver sites.
379
+ *
380
+ * GitNexus publishes this so `impact` and `context` can report `exact` versus
381
+ * `lower-bound`; the panel surfaces it because it is the honest caveat on every
382
+ * other number here.
383
+ */
384
+ function graphQualitySummary(graphQuality) {
385
+ const counts = graphQuality?.counts;
386
+ if (counts === null || counts === undefined || typeof counts !== 'object')
387
+ return null;
388
+ const names = Object.entries(counts)
389
+ // Narrow to numbers here rather than at the `.sort` below: the counts come from
390
+ // an external manifest, so a non-numeric entry is possible and would otherwise
391
+ // reach the comparator as `unknown`.
392
+ .filter((pair) => typeof pair[1] === 'number' && Number.isFinite(pair[1]))
393
+ .map(([name, count]) => ({ name, count }))
394
+ .sort((a, b) => b.count - a.count);
395
+ const total = typeof graphQuality?.totalSites === 'number' && Number.isFinite(graphQuality.totalSites)
396
+ ? graphQuality.totalSites
397
+ : names.reduce((sum, entry) => sum + entry.count, 0);
398
+ return { total, names };
399
+ }
400
+ /**
401
+ * Compact a count for a dense row: 26788 → "26.8k", 2366932 → "2.4M".
402
+ *
403
+ * One decimal is kept all the way up, matching how the product's own dashboards
404
+ * render counts. Rounding 26 788 to a bare "27k" discards the digits a reader is
405
+ * actually comparing between repositories.
406
+ */
407
+ function compactNumber(value) {
408
+ if (!Number.isFinite(value))
409
+ return '—';
410
+ if (value < 1000)
411
+ return String(value);
412
+ if (value < 1_000_000)
413
+ return `${(value / 1000).toFixed(1)}k`;
414
+ return `${(value / 1_000_000).toFixed(1)}M`;
415
+ }
416
+ // ---------------------------------------------------------------------------
417
+ // Presentation
418
+ // ---------------------------------------------------------------------------
419
+ const MUTED = { opacity: 0.62 };
420
+ const HAIRLINE = '1px solid color-mix(in srgb, currentColor 16%, transparent)';
421
+ const SOFT_BG = 'color-mix(in srgb, currentColor 6%, transparent)';
422
+ /** Layout only. Appearance belongs to the primitives, which read `--dsw-*` tokens. */
423
+ /**
424
+ * Layout.
425
+ *
426
+ * The panel is a CARD GRID, not a vertical stack: the surface it lives in can be
427
+ * narrow (a docked sidebar) or very wide (a maximised pane), and a single column of
428
+ * full-width cards reads as broken at the wide end — every metric row stretches
429
+ * across a metre of empty space.
430
+ *
431
+ * Column count is content-driven rather than media-queried, because an inline-styled
432
+ * plugin has no stylesheet to put a breakpoint in: `auto-fit` with a 620px floor
433
+ * yields two columns once the pane can hold them and one column below that. A
434
+ * card that needs the full width says so with `gridColumn: '1 / -1'`, which is
435
+ * column-count agnostic — unlike `span 2`, which would overflow a single column.
436
+ */
437
+ const styles = {
438
+ root: {
439
+ display: 'grid',
440
+ gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 620px), 1fr))',
441
+ // No `alignItems: start`: grid items stretch to the row height by default, so
442
+ // two cards sharing a row end level. With `start` each card took its natural
443
+ // height and the row showed a ragged bottom edge.
444
+ gap: '10px',
445
+ padding: '12px',
446
+ fontSize: '12px',
447
+ lineHeight: 1.5,
448
+ overflowY: 'auto',
449
+ height: '100%',
450
+ boxSizing: 'border-box',
451
+ },
452
+ /**
453
+ * A card that takes one grid column.
454
+ *
455
+ * Flex column, not block. A card stretched by the grid has a definite height, and
456
+ * its body needs to grow into that height — which `height: 100%` on the body gets
457
+ * wrong: a percentage height is resolved from the parent, so the body's own
458
+ * content stops contributing to the row's intrinsic height, the row is sized too
459
+ * short, and the body spills past the border. `flex: 1` on the body grows it
460
+ * without breaking the content-based sizing.
461
+ */
462
+ card: {
463
+ border: HAIRLINE,
464
+ borderRadius: '8px',
465
+ padding: '10px',
466
+ minWidth: 0,
467
+ display: 'flex',
468
+ flexDirection: 'column',
469
+ },
470
+ /** A card that spans every column. */
471
+ cardWide: {
472
+ border: HAIRLINE,
473
+ borderRadius: '8px',
474
+ padding: '10px',
475
+ minWidth: 0,
476
+ gridColumn: '1 / -1',
477
+ display: 'flex',
478
+ flexDirection: 'column',
479
+ },
480
+ row: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' },
481
+ bar: { display: 'flex', height: '10px', borderRadius: '5px', overflow: 'hidden', background: SOFT_BG },
482
+ mono: { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace' },
483
+ fileRow: { display: 'flex', alignItems: 'center', gap: '8px', padding: '3px 0' },
484
+ fileMeta: { marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: '6px', flexShrink: 0 },
485
+ };
486
+ function Section({ title, meta, wide = false, children, style }) {
487
+ return h('section', { style: { ...(wide ? styles.cardWide : styles.card), ...style } }, title === undefined
488
+ ? null
489
+ : h('div', { style: { marginBottom: '8px', display: 'flex', alignItems: 'center', gap: '8px', minWidth: 0 } }, typeof title === 'string' ? h('span', { style: MUTED }, title) : title, h('span', { style: { flex: 1 } }), meta ?? null), children);
490
+ }
491
+ function Row({ children, style }) {
492
+ return h('div', { style: { ...styles.row, ...style } }, children);
493
+ }
494
+ /**
495
+ * One file's flags, as native tags.
496
+ */
497
+ function FileFlags({ file }) {
498
+ const flags = [];
499
+ if (file.minified?.binary) {
500
+ flags.push(h(Tag, { key: 'bin', tone: 'neutral' }, '二进制'));
501
+ }
502
+ else if (file.minified?.suspect) {
503
+ flags.push(h(Tag, { key: 'min', tone: 'info' }, `单行 ~${Math.round(file.minified.avgLineLength)}`));
504
+ }
505
+ if (file.generatedHint) {
506
+ flags.push(h(Tag, { key: 'gen', tone: 'outline' }, '构建产物'));
507
+ }
508
+ if (flags.length === 0)
509
+ return null;
510
+ return h('span', { style: { display: 'inline-flex', gap: '4px', flexShrink: 0 } }, flags);
511
+ }
512
+ function Ring({ ratio, caption, tone = 'currentColor', size = 76 }) {
513
+ const clamped = Math.max(0, Math.min(1, Number.isFinite(ratio) ? ratio : 0));
514
+ const stroke = 8;
515
+ const radius = (size - stroke) / 2;
516
+ const circumference = 2 * Math.PI * radius;
517
+ const dash = circumference * clamped;
518
+ return h('div', { style: { position: 'relative', width: `${size}px`, height: `${size}px`, flexShrink: 0 } }, h('svg', { width: size, height: size, viewBox: `0 0 ${size} ${size}`, role: 'img', 'aria-label': caption }, h('circle', {
519
+ cx: size / 2,
520
+ cy: size / 2,
521
+ r: radius,
522
+ fill: 'none',
523
+ stroke: 'currentColor',
524
+ strokeOpacity: 0.15,
525
+ strokeWidth: stroke,
526
+ }), h('circle', {
527
+ cx: size / 2,
528
+ cy: size / 2,
529
+ r: radius,
530
+ fill: 'none',
531
+ stroke: tone,
532
+ strokeWidth: stroke,
533
+ strokeLinecap: 'round',
534
+ strokeDasharray: `${dash} ${circumference - dash}`,
535
+ // Start the arc at twelve o'clock rather than three.
536
+ transform: `rotate(-90 ${size / 2} ${size / 2})`,
537
+ })), h('div', {
538
+ style: {
539
+ position: 'absolute',
540
+ inset: 0,
541
+ display: 'flex',
542
+ flexDirection: 'column',
543
+ alignItems: 'center',
544
+ justifyContent: 'center',
545
+ gap: '1px',
546
+ },
547
+ }, h('span', { style: { fontSize: '15px', fontWeight: 600, ...styles.mono } }, `${fixed(clamped * 100, 1)}%`), h('span', { style: { fontSize: '10px', ...MUTED } }, caption)));
548
+ }
549
+ function MetricGrid({ items }) {
550
+ return h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '4px 16px' } }, items.map((item) => h('div', { key: item.label, style: { display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0 } }, item.state !== undefined
551
+ ? h(StateDot, { state: item.state })
552
+ : h('span', {
553
+ style: {
554
+ width: '8px',
555
+ height: '8px',
556
+ borderRadius: '50%',
557
+ background: item.color ?? 'currentColor',
558
+ opacity: item.color === undefined ? 0.4 : 1,
559
+ flexShrink: 0,
560
+ },
561
+ }),
562
+ // Label and value sit ADJACENT. A flex spacer between them was a bug that
563
+ // only showed on a wide pane: the cell stretched and pushed the two ends
564
+ // hundreds of pixels apart, so a row read as two unrelated columns of text
565
+ // rather than one metric.
566
+ h('span', { style: { ...MUTED, whiteSpace: 'nowrap' } }, item.label), h('span', { style: { fontWeight: 600, ...styles.mono, whiteSpace: 'nowrap' } }, item.value), item.hint !== undefined ? h('span', { style: { ...MUTED, fontSize: '10px' } }, item.hint) : null)));
567
+ }
568
+ function Histogram({ histogram, height = 54 }) {
569
+ const buckets = histogram?.buckets ?? [];
570
+ if (buckets.length === 0)
571
+ return null;
572
+ const max = Math.max(...buckets.map((b) => b.commits), 1);
573
+ const bucketDays = histogram.bucketDays ?? 1;
574
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '3px' } }, h('div', {
575
+ style: { display: 'flex', alignItems: 'flex-end', gap: '1px', height: `${height}px` },
576
+ role: 'img',
577
+ 'aria-label': `提交活动,每${bucketDays === 7 ? '周' : '天'}一柱`,
578
+ }, buckets.map((bucket, index) => h(Tooltip, {
579
+ key: `${bucket.label}-${index}`,
580
+ label: `${bucket.label} · ${bucket.commits} 提交 · +${bucket.insertions}/-${bucket.deletions}`,
581
+ side: 'bottom',
582
+ }, h('div', {
583
+ style: {
584
+ flex: '1 1 0',
585
+ // A zero bucket keeps a visible floor so a gap reads as "no commits"
586
+ // rather than as missing data.
587
+ height: `${Math.max(2, (bucket.commits / max) * height)}px`,
588
+ background: bucket.commits === 0 ? 'currentColor' : 'var(--dsw-color-accent, currentColor)',
589
+ opacity: bucket.commits === 0 ? 0.16 : 0.75,
590
+ borderRadius: '1px',
591
+ alignSelf: 'flex-end',
592
+ },
593
+ })))), h('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: '10px', ...MUTED } }, h('span', null, buckets[0]?.label ?? ''), h('span', null, `每${bucketDays === 7 ? '周' : '天'} · 峰值 ${max}`), h('span', null, buckets[buckets.length - 1]?.label ?? '')));
594
+ }
595
+ function LanguageBar({ rows, totalBytes, totalFiles = 0, metric = 'bytes' }) {
596
+ const segments = stackSegments(rows, totalBytes, totalFiles, metric);
597
+ if (segments.length === 0)
598
+ return null;
599
+ const visible = segments.filter((s) => s.percent >= 0.05);
600
+ const hidden = segments.length - visible.length;
601
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, h('div', { style: styles.bar, role: 'img', 'aria-label': '语言分布' }, segments.map((segment, index) => h(Tooltip, { key: `${segment.key}-${index}`, label: `${segment.label} ${fixed(segment.percent, 1)}%`, side: 'bottom' }, h('div', {
602
+ // A floor keeps a 0.01% language visible; the flex ratio keeps the
603
+ // major segments proportional.
604
+ style: { width: `${Math.max(0.4, segment.percent)}%`, background: segment.color, flexShrink: 0 },
605
+ })))), h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: '4px 12px' } }, visible.map((segment) => h('span', { key: segment.key, style: { display: 'inline-flex', gap: '5px', alignItems: 'center' } }, h('span', {
606
+ style: {
607
+ width: '8px',
608
+ height: '8px',
609
+ borderRadius: '50%',
610
+ background: segment.color,
611
+ display: 'inline-block',
612
+ flexShrink: 0,
613
+ },
614
+ }), h('span', null, segment.label), h('span', { style: MUTED }, `${fixed(segment.percent, 1)}%`))), hidden > 0 ? h('span', { style: MUTED }, `…另有 ${hidden} 种`) : null));
615
+ }
616
+ /**
617
+ * Language distribution, with the metric switchable.
618
+ *
619
+ * The toggle earns its place because bytes and files disagree in a way that
620
+ * changes the answer: a repository can be 70 % TypeScript by bytes while being
621
+ * mostly Markdown by file count, and either statement alone is misleading. The
622
+ * control is a stateful wrapper so `CoverageView` stays a pure function of its
623
+ * props and can still be rendered against a fixture.
624
+ *
625
+ * @param {{languages: {rows: any[], totalBytes: number, totalFiles: number}}} props
626
+ */
627
+ function LanguageSection({ languages }) {
628
+ const [metric, setMetric] = React.useState('bytes');
629
+ const unit = metric === 'files' ? '文件' : '字节';
630
+ return h(Section, {
631
+ title: `语言分布 · ${languages.rows.length} 种`,
632
+ meta: h(SegmentedControl, {
633
+ id: 'gitnexus-language-metric',
634
+ label: '语言分布统计口径',
635
+ value: metric,
636
+ // The control's API is string-valued; narrowing here rather than widening the
637
+ // state keeps the union intact downstream, where `stackSegments` switches on
638
+ // it — a widened state would let a typo like `'bytse'` compile.
639
+ onChange: (next) => setMetric(next === 'files' ? 'files' : 'bytes'),
640
+ options: [
641
+ { value: 'bytes', label: '按字节' },
642
+ { value: 'files', label: '按文件' },
643
+ ],
644
+ }),
645
+ // The card stretches to the row height beside the overview card; the footnote
646
+ // below uses `marginTop: auto` to sit at the foot of that height.
647
+ }, h(LanguageBar, {
648
+ rows: languages.rows,
649
+ totalBytes: languages.totalBytes,
650
+ totalFiles: languages.totalFiles,
651
+ metric,
652
+ }), h('div', { style: { marginTop: 'auto', paddingTop: '8px', fontSize: '10px', ...MUTED } }, `按${unit}计的占比;GitNexus 只解析其中一部分语言,其余仅作为文件节点存在`));
653
+ }
654
+ /**
655
+ * The files the size cap dropped.
656
+ *
657
+ * `FileTypeIcon` + `PathLabel` replace a hand-rolled row: the icon makes a `.glb`
658
+ * or a `.ts` readable at a glance, and `PathLabel` dims the directories, keeps the
659
+ * filename at full strength, and preserves the tail on overflow — which is what a
660
+ * path needs and what raw truncation destroys.
661
+ * @param {{files: any[]}} props
662
+ */
663
+ function LargeFileList({ files }) {
664
+ return h('div', { style: { display: 'flex', flexDirection: 'column' } }, files.map((file) => h('div', { key: file.path, style: styles.fileRow }, h(FileTypeIcon, { path: file.path, size: 16 }), h('span', { style: { minWidth: 0, flex: '1 1 auto' } }, h(PathLabel, { path: file.path })), h('span', { style: styles.fileMeta }, h('span', { style: { ...MUTED, whiteSpace: 'nowrap' } }, file.sizeText), h(FileFlags, { file }), h('span', { style: { ...MUTED, whiteSpace: 'nowrap' } }, `${fixed((file.shareOfLanguage ?? 0) * 100, 0)}% ${file.language?.label ?? ''}`)))));
665
+ }
666
+ /**
667
+ * Which query surfaces are live.
668
+ * @param {{capabilities: any}} props
669
+ */
670
+ function CapabilityStrip({ capabilities }) {
671
+ const rows = capabilityRows(capabilities);
672
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '3px' } }, rows.map((row) => h('div', { key: row.key, style: { display: 'flex', alignItems: 'center', gap: '6px' } }, h(StateDot, { state: row.ok ? 'done' : 'idle' }), h('span', { style: { minWidth: '68px' } }, row.label), row.ok
673
+ ? h('span', { style: MUTED }, row.provider)
674
+ : h(Tag, { tone: 'outline' }, row.note))));
675
+ }
676
+ /**
677
+ * Resolver confidence and analysis provenance.
678
+ *
679
+ * Body only — the surrounding `Section` card supplies the border and the heading.
680
+ *
681
+ * @param {{quality: any, provenance: any}} props
682
+ */
683
+ function ProvenanceBlock({ quality, provenance }) {
684
+ const summary = graphQualitySummary(quality);
685
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px', paddingTop: '4px', flex: '1 1 auto' } }, summary === null
686
+ ? h('div', { style: MUTED }, '该索引未记录未解析接收者统计(旧版本写入)')
687
+ : h('div', null, h('div', null, `未解析接收者 ${compactNumber(summary.total)} 处——存在这些位置时,impact / context 的结果是下界而非精确值`), h('div', { style: { ...MUTED, marginTop: '3px' } }, summary.names
688
+ .slice(0, 6)
689
+ .map((entry) => `${entry.name} ${entry.count}`)
690
+ .join(' · '))), provenance === null
691
+ ? null
692
+ : h('div',
693
+ // Pushed to the bottom: this card shares a row with the caveats card and
694
+ // stretches to its height, so anchoring the metrics at the foot turns the
695
+ // leftover space into a gap between two groups rather than a void below.
696
+ { style: { marginTop: 'auto', paddingTop: '8px' } }, h(MetricGrid, {
697
+ items: [
698
+ { label: 'schema', value: provenance.schemaFingerprint ?? '—' },
699
+ { label: '内容保留', value: provenance.contentRetention ?? '—' },
700
+ { label: 'FTS 配置', value: provenance.ftsProfile ?? '—' },
701
+ { label: '跨语言属性', value: compactNumber(provenance.crossLanguageProperties ?? 0) },
702
+ { label: '分析器', value: provenance.runnerCliVersion ?? '—' },
703
+ ],
704
+ })));
705
+ }
706
+ /** Collapsed summary for the provenance card's header. */
707
+ function provenanceCollapsed(quality) {
708
+ const summary = graphQualitySummary(quality);
709
+ return summary === null ? '无未解析接收者记录' : `未解析接收者 ${compactNumber(summary.total)} 处`;
710
+ }
711
+ /** Collapsed summary for the activity card's header. */
712
+ function activityCollapsed(activity) {
713
+ const view = activityView(activity);
714
+ if (view === null)
715
+ return '不可用';
716
+ const missing = view.verdicts.find((v) => v.key === 'missing')?.value ?? 0;
717
+ if (missing > 0)
718
+ return `${missing} 个活跃文件不在索引中`;
719
+ return `活跃文件均在索引中${view.truncated ? ' · 窗口已截断' : ''}`;
720
+ }
721
+ /**
722
+ * All activity numbers in one place, so the view stays a layout decision.
723
+ * @param {any} activity
724
+ * @returns {null | { window: string, totals: string, verdicts: Array<{key:string,label:string,value:number,tone:string}> }}
725
+ */
726
+ function activityView(activity) {
727
+ if (activity === null || typeof activity !== 'object')
728
+ return null;
729
+ const t = activity.totals ?? {};
730
+ const v = t.verdicts ?? { indexed: 0, excluded: 0, missing: 0 };
731
+ return {
732
+ window: `近 ${activity.window?.sinceDays ?? '?'} 天`,
733
+ truncated: activity.window?.truncated === true,
734
+ totals: `${t.commits ?? 0} 提交 · ${t.authors ?? 0} 作者 · ${compactNumber(t.insertions ?? 0)} 增 / ${compactNumber(t.deletions ?? 0)} 删`,
735
+ // Ordered so the actionable verdict is first: "missing" is the only one that
736
+ // means the index is behind. "excluded" next to it, because a reader who sees
737
+ // only "not indexed" will otherwise read it as a defect.
738
+ verdicts: [
739
+ { key: 'indexed', label: '已索引', value: v.indexed, tone: 'done' },
740
+ { key: 'missing', label: '索引缺失', value: v.missing, tone: v.missing > 0 ? 'warning' : 'idle' },
741
+ { key: 'excluded', label: '有意排除', value: v.excluded, tone: 'idle' },
742
+ ],
743
+ };
744
+ }
745
+ /**
746
+ * One touched file, with its verdict as a tag.
747
+ *
748
+ * The verdict tag is the whole point of the row: a path alone cannot tell a reader
749
+ * whether the graph knows about it.
750
+ * @param {{file: any}} props
751
+ */
752
+ function ActivityFileRow({ file }) {
753
+ const tone = file.verdict === 'indexed' ? 'solid' : file.verdict === 'missing' ? 'outline' : 'neutral';
754
+ const label = file.verdict === 'indexed' ? '已索引' : file.verdict === 'missing' ? '缺失' : '排除';
755
+ return h('div', { style: styles.fileRow }, h(FileTypeIcon, { path: file.path, size: 16 }), h('span', { style: { minWidth: 0, flex: '1 1 auto' } }, h(PathLabel, { path: file.path })), h('span', { style: styles.fileMeta }, h(Tag, { tone }, label), h('span', { style: { ...MUTED, whiteSpace: 'nowrap' } }, `${file.changes}×`)));
756
+ }
757
+ /**
758
+ * Git activity, crossed with the index.
759
+ *
760
+ * Body only — the card and its disclosure header come from `CollapsibleCard`. The
761
+ * header's collapsed line still carries the number that matters, so a reader who
762
+ * never expands it learns whether recent work is visible to the graph.
763
+ * @param {{activity: any}} props
764
+ */
765
+ function GitActivitySection({ activity: rawActivity }) {
766
+ // Narrowed to a local const before use. `activityView` returns null for an absent
767
+ // activity, but TypeScript cannot carry that back to the parameter, so every later
768
+ // read would need its own guard — and a guard per read is how one gets forgotten.
769
+ const activity = rawActivity;
770
+ const view = activityView(activity);
771
+ if (view === null || activity === null || activity === undefined) {
772
+ return h('div', { style: { ...MUTED } }, 'Git 活动不可用');
773
+ }
774
+ const missing = view.verdicts.find((v) => v.key === 'missing')?.value ?? 0;
775
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px', paddingTop: '4px' } }, h('div', { style: MUTED }, view.totals), view.truncated
776
+ ? h('div', { style: MUTED }, `活动窗口达到提交上限,更早的改动未统计`)
777
+ : null, h(MetricGrid, {
778
+ items: view.verdicts.map((v) => ({ label: v.label, value: compactNumber(v.value), state: v.tone })),
779
+ }),
780
+ // Commit activity over time. Placed above the file lists because "when" is
781
+ // what makes the rest legible: a hot file means something different in a
782
+ // burst week than in a slow one.
783
+ activity.histogram !== undefined && activity.histogram !== null
784
+ ? h(Histogram, { histogram: activity.histogram })
785
+ : null,
786
+ // Missing files come from their own list, not from the display-capped
787
+ // by-changes slice — otherwise the summary can report a count with no rows.
788
+ missing > 0 && Array.isArray(activity.missingFiles) && activity.missingFiles.length > 0
789
+ ? h('div', null, h('div', { style: { ...MUTED, marginBottom: '4px' } }, '应被索引却缺失'), activity.missingFiles
790
+ .slice(0, 8)
791
+ .map((file) => h(ActivityFileRow, { key: file.path, file })))
792
+ : null, Array.isArray(activity.byChanges) && activity.byChanges.length > 0
793
+ ? h('div', null, h('div', { style: { ...MUTED, marginBottom: '4px' } }, '改动最频繁'), activity.byChanges
794
+ .filter((f) => f.verdict !== 'excluded')
795
+ .slice(0, 8)
796
+ .map((file) => h(ActivityFileRow, { key: file.path, file })))
797
+ : null, Array.isArray(activity.byRecency) && activity.byRecency.length > 0
798
+ ? h('div', null, h('div', { style: { ...MUTED, marginBottom: '4px' } }, '最近改动'), activity.byRecency
799
+ .filter((f) => f.verdict !== 'excluded')
800
+ .slice(0, 5)
801
+ .map((file) => h(ActivityFileRow, { key: file.path, file })))
802
+ : null, Array.isArray(activity.authors) && activity.authors.length > 0
803
+ ? h('div', null, h('div', { style: { ...MUTED, marginBottom: '4px' } }, '提交者'), activity.authors.slice(0, 6).map((author) => h('div', { key: `${author.name}-${author.email}`, style: styles.fileRow }, h('span', { style: { minWidth: 0, flex: '1 1 auto' } }, author.name), h('span', { style: styles.fileMeta }, author.bot ? h(Tag, { tone: 'neutral' }, 'bot') : null, h('span', { style: { ...MUTED, whiteSpace: 'nowrap' } }, `${author.commits} 提交`), h('span', { style: { ...MUTED, whiteSpace: 'nowrap' } }, `${author.files} 文件`)))))
804
+ : null, Array.isArray(activity.branches) && activity.branches.length > 0
805
+ ? h('div', null, h('div', { style: { ...MUTED, marginBottom: '4px' } }, `分支 · ${activity.branches.length}`), activity.branches.slice(0, 6).map((branch) => h('div', { key: branch.name, style: styles.fileRow }, h('span', { style: { minWidth: 0, flex: '1 1 auto', ...styles.mono } }, branch.name), h('span', { style: styles.fileMeta }, branch.current ? h(Tag, { tone: 'solid' }, '当前') : null, h('span', { style: { ...MUTED, whiteSpace: 'nowrap' } }, branch.lastCommitDate ? branch.lastCommitDate.slice(0, 10) : '')))))
806
+ : null);
807
+ }
808
+ /**
809
+ * Resolve the project this panel is about.
810
+ *
811
+ * The panel shows the project the operator is *in*, not a global list of indexed
812
+ * repositories. A registry-driven picker was the first design and it was wrong for
813
+ * the job: it made `~/.gitnexus/registry.json` a hard dependency, so a fresh clone,
814
+ * a second working tree, or an index built with `GITNEXUS_HOME` redirected simply
815
+ * could not be shown — which is exactly when a coverage panel is most useful.
816
+ *
817
+ * The path comes from the session's own `cwd`, selected out of the session snapshot:
818
+ *
819
+ * useSessions((sessions) => sessions.byId[sessionId]?.cwd)
820
+ *
821
+ * That is the shipped pattern, read off `dsh-client-ui-sidebar-files`, whose body
822
+ * sits in this same slot and needs the same answer. An earlier revision guessed at
823
+ * `useWorkspaces` and the panel rendered "未解析到工作区" — a hook that exists is not
824
+ * the same as the hook that carries this value.
825
+ *
826
+ * @param {{ params?: {repo?: string}, sessionId?: string, useSessions?: Function, useWorkspaces?: Function }} props
827
+ * @returns {string | null}
828
+ */
829
+ function useProjectPath(props) {
830
+ // A caller that opened the tab with an explicit repo wins, so `openTab` stays
831
+ // usable for previewing a project other than the session's.
832
+ const explicit = props?.params?.repo;
833
+ const sessionId = props?.sessionId;
834
+ // Hooks must be called unconditionally: a host that supplies neither still needs
835
+ // the calls to happen, so a no-op of the same shape stands in rather than a
836
+ // branch around the hook.
837
+ const selectSession = typeof props?.useSessions === 'function' ? props.useSessions : () => null;
838
+ const fromSession = selectSession((sessions) => typeof sessionId === 'string' ? sessions?.byId?.[sessionId]?.cwd ?? null : null);
839
+ const selectWorkspace = typeof props?.useWorkspaces === 'function' ? props.useWorkspaces : () => null;
840
+ const fromWorkspace = selectWorkspace((snapshot) => {
841
+ const list = snapshot?.workspaces;
842
+ if (!Array.isArray(list) || typeof sessionId !== 'string')
843
+ return null;
844
+ const mine = list.find((w) => Array.isArray(w?.sessionIds) && w.sessionIds.includes(sessionId));
845
+ return typeof mine?.cwd === 'string' && mine.cwd !== '' ? mine.cwd : null;
846
+ });
847
+ if (typeof explicit === 'string' && explicit !== '')
848
+ return explicit;
849
+ if (typeof fromSession === 'string' && fromSession !== '')
850
+ return fromSession;
851
+ return typeof fromWorkspace === 'string' && fromWorkspace !== '' ? fromWorkspace : null;
852
+ }
853
+ /**
854
+ * Which context props actually arrived.
855
+ *
856
+ * Rendered only when the project could not be resolved. Without it the panel can
857
+ * only say "no project", which is a dead end for whoever has to fix it — with it,
858
+ * one screenshot names the missing input.
859
+ *
860
+ * @param {any} props
861
+ * @returns {string[]}
862
+ */
863
+ function contextDiagnostic(props) {
864
+ const present = [];
865
+ const absent = [];
866
+ const note = (name, ok) => {
867
+ (ok ? present : absent).push(name);
868
+ };
869
+ note('sessionId', typeof props?.sessionId === 'string' && props.sessionId !== '');
870
+ note('useSessions', typeof props?.useSessions === 'function');
871
+ note('useWorkspaces', typeof props?.useWorkspaces === 'function');
872
+ note('useTabInfo', typeof props?.useTabInfo === 'function');
873
+ note('params.repo', typeof props?.params?.repo === 'string');
874
+ return { present, absent };
875
+ }
876
+ /**
877
+ * The maintenance commands, shown verbatim rather than executed.
878
+ *
879
+ * The plugin deliberately does not run these. Spawning `gitnexus analyze` from a
880
+ * plugin bypasses the host's permission system: nothing would ask the operator
881
+ * whether a thirty-minute write against their working tree was intended. Handing
882
+ * over the exact command keeps the decision — and the approval — on the path the
883
+ * product already audits.
884
+ *
885
+ * Which one is *relevant* depends on whether an index exists, so the applicable
886
+ * command is marked. Presenting both with equal weight on an already-indexed
887
+ * project reads as "you may need to initialize this", which is not true.
888
+ *
889
+ * @param {{maintenance: any, projectPath: string | null, indexed: boolean}} props
890
+ */
891
+ /**
892
+ * What the panel says when GitNexus is not on this machine.
893
+ *
894
+ * THE ORDER IS THE DESIGN
895
+ * -----------------------
896
+ * The install command comes first and is copyable, because that is the answer for most
897
+ * operators: they know their network, their registry and their toolchain, and a command
898
+ * they can run is more useful than a download this plugin performs on their behalf. The
899
+ * plugin-install option is second and behind a confirmation, because making a
900
+ * several-hundred-megabyte download the path of least resistance would be the wrong
901
+ * default for a panel whose job is to report, not to act.
902
+ *
903
+ * Nothing renders when the verdict is `ready` — a permanent "GitNexus is fine" banner is
904
+ * noise in a panel whose whole purpose is to surface problems.
905
+ */
906
+ function ToolchainNotice({ toolchain, run, runError, now, onInstall, onCancelInstall, }) {
907
+ const [copied, setCopied] = React.useState(false);
908
+ const [confirming, setConfirming] = React.useState(false);
909
+ const [acknowledged, setAcknowledged] = React.useState(false);
910
+ if (toolchain === undefined || toolchain === null || toolchain.verdict === 'ready')
911
+ return null;
912
+ const activeRun = run ?? null;
913
+ const installing = activeRun?.state === 'running';
914
+ const at = typeof now === 'number' ? now : Date.now();
915
+ const elapsed = activeRun === null ? 0 : Math.max(0, Math.round(((activeRun.finishedAt ?? at) - activeRun.startedAt) / 1000));
916
+ const libraryOnly = toolchain.verdict === 'library-only';
917
+ const command = 'npm install -g gitnexus';
918
+ const copy = () => {
919
+ const write = typeof primitives.writeClipboard === 'function'
920
+ ? primitives.writeClipboard
921
+ : (text) => navigator.clipboard?.writeText(text);
922
+ try {
923
+ const outcome = write(command);
924
+ if (outcome && typeof outcome.then === 'function')
925
+ outcome.then(() => setCopied(true)).catch(() => setCopied(false));
926
+ else
927
+ setCopied(true);
928
+ }
929
+ catch {
930
+ setCopied(false);
931
+ }
932
+ };
933
+ return h(Section, { wide: true, title: libraryOnly ? '缺少 gitnexus 命令' : '本机没有 GitNexus' }, h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px', paddingTop: '4px' } }, h('div', { style: { ...MUTED, display: 'flex', gap: '6px', alignItems: 'flex-start' } }, h(StateDot, { state: 'warning' }), h('span', null, libraryOnly
934
+ ? '找到了 GitNexus 的库,但没有可执行的 gitnexus 命令(可能只作为依赖安装、未全局链接)。读取不受影响;修复后即可执行增量刷新。'
935
+ : '本插件读取 .gitnexus/gitnexus.json —— 那份文件由 GitNexus 分析仓库产生,包含每个函数定义、符号关系与执行流。没有它就没什么可展示的。')), h('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } }, h('div', { style: { fontWeight: 600 } }, '① 自己安装(推荐)'), h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px' } }, h('code', {
936
+ style: {
937
+ ...styles.mono,
938
+ flex: '1 1 auto',
939
+ padding: '6px 8px',
940
+ border: HAIRLINE,
941
+ borderRadius: '6px',
942
+ background: SOFT_BG,
943
+ wordBreak: 'break-all',
944
+ userSelect: 'all',
945
+ },
946
+ }, command), h(Button, { variant: 'ghost', onClick: copy }, copied ? '已复制' : '复制')), h('div', { style: MUTED }, '用你能访问到的源安装即可 —— 本插件不假设任何网络,也不会自行下载。')), h('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } }, h('div', { style: { fontWeight: 600 } }, '② 授权本插件安装'), h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' } }, installing
947
+ ? h(Button, { variant: 'ghost', onClick: onCancelInstall }, `取消(已进行 ${elapsed}s)`)
948
+ : h(Button, { variant: 'ghost', onClick: () => setConfirming(true) }, '授权并安装'), h('span', { style: MUTED }, '装到插件自己的目录,用你已配置的 npm 源,不改全局前缀、不需要管理员权限。')), activeRun === null
949
+ ? null
950
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '3px', paddingTop: '2px' } }, h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px' } }, h(StateDot, { state: runStateTone(activeRun.state) }), h('span', { style: { fontWeight: 600 } }, runStateLabel(activeRun.state)), h('span', { style: MUTED }, installing ? `已运行 ${elapsed}s` : `${elapsed}s`)), activeRun.message === null ? null : h('div', { style: MUTED }, activeRun.message), activeRun.output === ''
951
+ ? null
952
+ : h('pre', { style: { ...styles.mono, margin: 0, whiteSpace: 'pre-wrap', maxHeight: '9em', overflow: 'auto' } }, activeRun.output)), runError === null ? null : h('div', { style: { ...MUTED, color: 'var(--dsw-color-danger, inherit)' } }, runError)), h(primitives.RiskConfirmation, {
953
+ open: confirming,
954
+ title: '授权本插件安装 GitNexus?',
955
+ description: '本插件将执行:\n\nnpm install --prefix <插件数据目录>/gitnexus gitnexus@^1.6.12\n\n' +
956
+ '· 从你已配置的 npm 源下载约 500 MB ~ 1 GB\n' +
957
+ '· 需要几分钟;网络慢或需要本地编译时更久\n' +
958
+ '· 会在本机运行这些包的安装期构建脚本(原生数据库与解析器需要本地编译)\n' +
959
+ '· 安装到插件自己的目录,不改动你的全局 npm 前缀\n\n' +
960
+ '命令走 DSH 的 shell 执行器,沙箱与其它命令一致 —— 本插件不申请扩权。',
961
+ acknowledgeLabel: '我已了解这会下载数百 MB 并在本机编译原生模块',
962
+ cancelLabel: '取消',
963
+ confirmLabel: '授权并开始',
964
+ closeLabel: '关闭',
965
+ acknowledged,
966
+ onAcknowledgedChange: setAcknowledged,
967
+ onCancel: () => {
968
+ setConfirming(false);
969
+ setAcknowledged(false);
970
+ },
971
+ onConfirm: () => {
972
+ setConfirming(false);
973
+ setAcknowledged(false);
974
+ onInstall();
975
+ },
976
+ })));
977
+ }
978
+ function MaintenanceSection({ maintenance, projectPath, indexed, run, runError, now, onStartRun, onCancelRun, }) {
979
+ // `projectPath` is part of the prop set for the header, which builds the commands
980
+ // from it; the body does not read it.
981
+ void projectPath;
982
+ const [copied, setCopied] = React.useState(null);
983
+ const [confirming, setConfirming] = React.useState(false);
984
+ // `RiskConfirmation`'s checkbox is controlled, so the tick has to live here. Without
985
+ // this the box renders but never moves, which is how it looked the first time.
986
+ const [acknowledged, setAcknowledged] = React.useState(false);
987
+ const commands = Array.isArray(maintenance?.commands) ? maintenance.commands : [];
988
+ if (commands.length === 0)
989
+ return null;
990
+ const applicable = indexed ? 'full' : 'init';
991
+ // Normalised rather than trusted. The declared type says `ClientAnalyzeRun | null`,
992
+ // but a React element built without the prop arrives as `undefined` — which is
993
+ // exactly what happened the first time this component was rendered by a caller that
994
+ // predated the prop. `run === null` alone crashed on it.
995
+ const activeRun = run ?? null;
996
+ const running = activeRun?.state === 'running';
997
+ const at = typeof now === 'number' ? now : Date.now();
998
+ const elapsed = activeRun === null ? 0 : Math.max(0, Math.round(((activeRun.finishedAt ?? at) - activeRun.startedAt) / 1000));
999
+ const copy = (command) => {
1000
+ const write = typeof primitives.writeClipboard === 'function'
1001
+ ? primitives.writeClipboard
1002
+ : (text) => navigator.clipboard?.writeText(text);
1003
+ try {
1004
+ const outcome = write(command.shell);
1005
+ if (outcome && typeof outcome.then === 'function') {
1006
+ outcome.then(() => setCopied(command.mode)).catch(() => setCopied(null));
1007
+ }
1008
+ else {
1009
+ setCopied(command.mode);
1010
+ }
1011
+ }
1012
+ catch {
1013
+ setCopied(null);
1014
+ }
1015
+ };
1016
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px', paddingTop: '4px' } },
1017
+ // The old line said "复制后到会话执行". That stopped being the whole story once the
1018
+ // plugin could start the run itself, so the sentence says which parts it runs and
1019
+ // which it only hands over.
1020
+ h('div', { style: MUTED }, '增量刷新可直接执行(走 DSH 的 shell 执行器,沙箱与其它命令一致,本插件不申请扩权);其余命令复制后到会话执行。'),
1021
+ // The run sits above the commands rather than under one of them: the host holds a
1022
+ // single run per repository, and nesting it would imply the two variants have
1023
+ // separate ones.
1024
+ activeRun === null
1025
+ ? null
1026
+ : h('div', {
1027
+ style: {
1028
+ display: 'flex',
1029
+ flexDirection: 'column',
1030
+ gap: '4px',
1031
+ padding: '6px 8px',
1032
+ border: HAIRLINE,
1033
+ borderRadius: '6px',
1034
+ background: SOFT_BG,
1035
+ },
1036
+ }, h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px' } }, h(StateDot, { state: runStateTone(activeRun.state) }), h('span', { style: { fontWeight: 600 } }, runStateLabel(activeRun.state)), h('span', { style: MUTED }, activeRun.state === 'running' ? `已运行 ${elapsed}s` : `${elapsed}s`), h('span', { style: { flex: 1 } }), running
1037
+ ? h(Button, { variant: 'ghost', onClick: onCancelRun }, '取消')
1038
+ : h(Button, { variant: 'ghost', onClick: onStartRun }, '再次执行')), activeRun.message === null ? null : h('div', { style: MUTED }, activeRun.message),
1039
+ // The output is the evidence. A run that reports success with a warning in
1040
+ // its log is a different outcome from one that does not, and hiding the text
1041
+ // would leave the panel's own verdict as the only thing to check.
1042
+ activeRun.output === ''
1043
+ ? null
1044
+ : h('pre', {
1045
+ style: {
1046
+ ...styles.mono,
1047
+ margin: 0,
1048
+ whiteSpace: 'pre-wrap',
1049
+ maxHeight: '9em',
1050
+ overflow: 'auto',
1051
+ },
1052
+ }, activeRun.output)), runError === null
1053
+ ? null
1054
+ : h('div', { style: { ...MUTED, color: 'var(--dsw-color-danger, inherit)' } }, runError), commands.map((command) => h('div', {
1055
+ key: command.mode,
1056
+ style: {
1057
+ display: 'flex',
1058
+ flexDirection: 'column',
1059
+ gap: '3px',
1060
+ // The inapplicable one stays visible — an operator may still want the
1061
+ // text — but recedes.
1062
+ opacity: command.mode === applicable ? 1 : 0.55,
1063
+ },
1064
+ }, h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px' } }, h('span', { style: { fontWeight: 600 } }, command.label), command.mode === applicable ? h(Tag, { tone: 'solid' }, '当前适用') : null, command.destructive ? h(Tag, { tone: 'outline' }, '破坏性') : null, h('span', { style: { flex: 1 } }),
1065
+ // Only the incremental command gets a button, and only because it is the one
1066
+ // the host route implements. A button on `--force` would quietly run
1067
+ // something other than what its label says.
1068
+ command.mode === 'init'
1069
+ ? h(Button, { variant: 'ghost', disabled: running, onClick: () => setConfirming(true) }, running ? '运行中' : '执行增量刷新')
1070
+ : null, h(Button, { variant: 'ghost', onClick: () => copy(command) }, copied === command.mode ? '已复制' : '复制')), h('code', {
1071
+ style: {
1072
+ ...styles.mono,
1073
+ display: 'block',
1074
+ padding: '6px 8px',
1075
+ border: HAIRLINE,
1076
+ borderRadius: '6px',
1077
+ background: SOFT_BG,
1078
+ wordBreak: 'break-all',
1079
+ userSelect: 'all',
1080
+ },
1081
+ }, command.shell), h('div', { style: MUTED }, command.when), command.caveat !== null && command.caveat !== undefined
1082
+ ? h('div', { style: MUTED }, command.caveat)
1083
+ : null)), Array.isArray(maintenance?.rationale) && maintenance.rationale.length > 0
1084
+ ? h('div', { style: { ...MUTED, display: 'flex', flexDirection: 'column', gap: '2px' } }, maintenance.rationale.map((note, index) => h('div', { key: index }, `· ${note}`)))
1085
+ : null,
1086
+ // The confirmation. Everything the operator needs before a process touches their
1087
+ // working tree goes in `description`, because that is the prop the modal renders:
1088
+ // an earlier revision passed this as children and the dialog opened with an empty
1089
+ // body and two unlabelled buttons.
1090
+ h(primitives.RiskConfirmation, {
1091
+ open: confirming,
1092
+ title: '执行增量刷新?',
1093
+ description: '将在项目目录下运行:\n\n' +
1094
+ (commands.find((c) => c.mode === 'init')?.shell ?? 'gitnexus analyze --index-only') +
1095
+ '\n\n' +
1096
+ '只写入 .gitnexus/,不改动任何源文件,也不会重写 AGENTS.md / CLAUDE.md。' +
1097
+ '耗时取决于改动量:无改动时约 7 秒,改动几个文件时实测可到 3 分钟,' +
1098
+ '大仓库的全量重建可能更久(上限 10 分钟,可随时取消)。' +
1099
+ '命令由 DSH 的 shell 执行器运行,沙箱与其它命令一致 —— 本插件不申请扩权。',
1100
+ acknowledgeLabel: '我了解这会运行一个进程并写入 .gitnexus/',
1101
+ cancelLabel: '取消',
1102
+ confirmLabel: '执行',
1103
+ closeLabel: '关闭',
1104
+ // The checkbox is controlled, so it needs state of its own, and it is reset on
1105
+ // close: the acknowledgement is per-action rather than remembered.
1106
+ acknowledged,
1107
+ onAcknowledgedChange: setAcknowledged,
1108
+ onCancel: () => {
1109
+ setConfirming(false);
1110
+ setAcknowledged(false);
1111
+ },
1112
+ onConfirm: () => {
1113
+ setConfirming(false);
1114
+ setAcknowledged(false);
1115
+ onStartRun();
1116
+ },
1117
+ }));
1118
+ }
1119
+ function CoverageView({ report, maintenance, projectPath, context, busy, error, readAt, run, runError, now, onRefresh, onStartRun, onCancelRun, installRun, installError, onInstall, onCancelInstall, }) {
1120
+ // Whether an index exists decides which maintenance command is applicable. When
1121
+ // the project could not even be identified there is nothing to claim, so it is
1122
+ // false rather than assumed.
1123
+ const indexed = report?.repo?.indexed === true;
1124
+ const header = h(Row, null, report !== null && report.repo?.indexed ? h(StateDot, { state: healthState(report) }) : null, h('span', { style: { fontWeight: 600 } }, 'GitNexus 索引'),
1125
+ // The project, not a picker. Shown so the reader can confirm which tree the
1126
+ // numbers describe — a path is the only unambiguous answer to that.
1127
+ projectPath === null
1128
+ ? h('span', { style: MUTED }, '未解析到工作区')
1129
+ : h('span', { style: { minWidth: 0, flex: '1 1 auto' } }, h(PathLabel, { path: projectPath })), h('span', { style: { flex: 1 } }),
1130
+ // The label states the scope. "刷新" alone next to a staleness warning reads as
1131
+ // "rebuild the index", which this control has never done and — by design, since
1132
+ // the plugin spawns nothing — cannot do.
1133
+ h(Button, {
1134
+ variant: 'ghost',
1135
+ onClick: onRefresh,
1136
+ disabled: busy,
1137
+ title: '重新读取报告(不会重建索引;重建见下方「维护命令」)',
1138
+ 'aria-label': '重新读取报告',
1139
+ }, h(IconRefreshOutlineRegular, { size: 14 })));
1140
+ // "I cannot tell which project this is" and "this project has no index" are
1141
+ // different facts, and the first revision conflated them: an unresolved project
1142
+ // fell through to the no-index branch and told the operator to initialise an
1143
+ // index for a project it had not identified. The diagnostic exists so that state
1144
+ // is actionable rather than a dead end.
1145
+ if (projectPath === null) {
1146
+ return h('div', { style: styles.root }, header, h(Section, { wide: true, style: { display: 'flex', gap: '8px', alignItems: 'flex-start' } }, h(StateDot, { state: 'warning' }), h('span', null, '未能确定当前项目路径。')), context === null || context === undefined
1147
+ ? null
1148
+ : h(Section, { wide: true, title: '面板收到的上下文' }, h('div', { style: { display: 'flex', flexDirection: 'column', gap: '3px' } }, h('div', null, `存在:${context.present.length > 0 ? context.present.join('、') : '(无)'}`), h('div', null, `缺失:${context.absent.length > 0 ? context.absent.join('、') : '(无)'}`))));
1149
+ }
1150
+ if (error !== null) {
1151
+ return h('div', { style: styles.root }, header, h(Section, { wide: true, style: { display: 'flex', gap: '8px', alignItems: 'flex-start' } }, h(StateDot, { state: 'error' }), h('span', null, error)), maintenance === null || maintenance === undefined
1152
+ ? null
1153
+ : h(Section, {
1154
+ wide: true,
1155
+ title: '维护命令',
1156
+ meta: h('span', { style: { ...MUTED, fontSize: '11px' } }, '复制后到会话执行(沙箱与提权由 DSH 处理)'),
1157
+ }, h(MaintenanceSection, { maintenance, projectPath, indexed: false, run, runError, now, onStartRun, onCancelRun })));
1158
+ }
1159
+ if (report === null) {
1160
+ return h('div', { style: styles.root }, header, h('div', { style: MUTED }, '正在读取索引…'));
1161
+ }
1162
+ // No index yet. This is the state the initialize command exists for, so the
1163
+ // panel leads with the command rather than an error.
1164
+ if (report.repo?.indexed !== true) {
1165
+ return h('div', { style: styles.root }, header, h(Section, { wide: true, style: { display: 'flex', gap: '8px', alignItems: 'flex-start' } }, h(StateDot, { state: 'idle' }), h('span', null, '该项目还没有 GitNexus 索引。')), maintenance === null || maintenance === undefined
1166
+ ? null
1167
+ : h(Section, {
1168
+ wide: true,
1169
+ title: '初始化索引',
1170
+ meta: h('span', { style: { ...MUTED, fontSize: '11px' } }, '复制后到会话执行(沙箱与提权由 DSH 处理)'),
1171
+ }, h(MaintenanceSection, { maintenance, projectPath, indexed, run, runError, now, onStartRun, onCancelRun })));
1172
+ }
1173
+ // Past this point an index exists, and the host builds these blocks
1174
+ // unconditionally for one. Defaulting them once here beats a `?? []` at each of
1175
+ // twenty read sites — and a default repeated twenty times is one that will
1176
+ // eventually be forgotten at the twenty-first.
1177
+ const totals = report.totals ?? ZERO_TOTALS;
1178
+ const cap = report.cap ?? ZERO_CAP;
1179
+ const analyzer = report.analyzer ?? ZERO_ANALYZER;
1180
+ const largeFiles = report.largeFiles ?? [];
1181
+ const { notable, context: contextWarnings } = splitWarnings(report.warnings);
1182
+ const ratio = coverageRatio(report);
1183
+ const languages = report.languages ?? null;
1184
+ return h('div', { style: styles.root },
1185
+ // The header and the two status lines span everything: they describe the whole
1186
+ // panel, so giving them a column would make them look like one card's heading.
1187
+ h('div', { style: { gridColumn: '1 / -1', display: 'flex', flexDirection: 'column', gap: '6px' } }, header),
1188
+ // Immediately after the header, before any index content. If GitNexus is missing,
1189
+ // that single fact explains everything the panel is about to show or fail to show,
1190
+ // so it belongs above the numbers rather than beside them.
1191
+ h(ToolchainNotice, {
1192
+ toolchain: report.toolchain,
1193
+ run: installRun,
1194
+ runError: installError,
1195
+ now,
1196
+ onInstall,
1197
+ onCancelInstall,
1198
+ }), h('div', { style: { gridColumn: '1 / -1', display: 'flex', flexDirection: 'column', gap: '3px' } }, h('div', { style: MUTED }, `${report.repo.indexedAt ?? '未知时间'} · ${report.repo.branch ?? 'unknown'}@${String(report.repo.lastCommit ?? '').slice(0, 8)}` +
1199
+ ` · manifest ${report.repo.metaFile ?? '?'} · GitNexus ${analyzer.gitnexusVersion}` +
1200
+ // The read time is the only thing on screen a refresh can change when the
1201
+ // repository has not moved, so without it the control reads as broken.
1202
+ (readAt === null ? '' : ` · 读取于 ${String(readAt).slice(11, 19)}Z`)),
1203
+ // Freshness against HEAD. The line above states the *indexed* commit, which
1204
+ // reads as current unless this one says otherwise.
1205
+ report.staleness === undefined
1206
+ ? null
1207
+ : (() => {
1208
+ const s = stalenessView(report.staleness);
1209
+ return h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px' } }, h(StateDot, { state: s.state }), h('span', null, s.text));
1210
+ })()),
1211
+ // One card for the whole "what is this index" question — file coverage and
1212
+ // graph contents together.
1213
+ //
1214
+ // They were two cards. Side by side, the ring made the coverage card tall while
1215
+ // its three metrics stayed short, so the card carried a band of dead space; and
1216
+ // splitting them forced a reader to assemble one answer from two boxes. They are
1217
+ // the same fact at two resolutions: what went in, and what came out.
1218
+ h(Section, {
1219
+ title: '索引概览',
1220
+ meta: report.graph === null || report.graph === undefined
1221
+ ? null
1222
+ : h('span', { style: { ...MUTED, fontSize: '11px' } }, `${fixed(report.graph.edgesPerNode, 2)} 边/符号`),
1223
+ }, h('div', { style: { display: 'flex', gap: '16px', alignItems: 'flex-start' } }, ratio === null
1224
+ ? null
1225
+ : h(Ring, {
1226
+ ratio,
1227
+ caption: '覆盖',
1228
+ tone: ratio >= 0.9 ? 'var(--dsw-color-success, #3fb950)' : 'var(--dsw-color-warning, #d9a441)',
1229
+ }), h('div', { style: { display: 'flex', flexDirection: 'column', gap: '9px', minWidth: 0, flex: '1 1 auto' } }, h('div', { style: MUTED }, summaryLine(report)),
1230
+ // Files in, graph out — the two halves sit side by side so the wide card
1231
+ // is used rather than merely filled.
1232
+ h('div', { style: { display: 'flex', gap: '24px', flexWrap: 'wrap', alignItems: 'flex-start' } }, h('div', { style: { minWidth: '200px', flex: '1 1 auto' } }, h('div', { style: { ...MUTED, marginBottom: '5px' } }, '文件'), h(MetricGrid, {
1233
+ items: [
1234
+ { label: '大小上限', value: cap.text, hint: cap.source },
1235
+ { label: '跳过合计', value: fileSize(totals.largeBytes) },
1236
+ { label: '超限文件', value: compactNumber(totals.large) },
1237
+ ],
1238
+ })), report.graph === null || report.graph === undefined
1239
+ ? null
1240
+ : h('div', { style: { minWidth: '240px', flex: '1 1 auto' } }, h('div', { style: { ...MUTED, marginBottom: '5px' } }, '图谱'), h(MetricGrid, {
1241
+ items: [
1242
+ { label: '符号', value: compactNumber(report.graph.nodes) },
1243
+ { label: '边', value: compactNumber(report.graph.edges) },
1244
+ { label: '社区', value: compactNumber(report.graph.communities) },
1245
+ { label: '流程', value: compactNumber(report.graph.processes) },
1246
+ { label: '向量', value: compactNumber(report.graph.embeddings) },
1247
+ ],
1248
+ }))), h('div', { style: { borderTop: HAIRLINE, paddingTop: '8px' } }, h('div', { style: { ...MUTED, marginBottom: '5px' } }, '查询能力'), h(CapabilityStrip, { capabilities: report.capabilities }))))),
1249
+ // Shares a row with the overview card: a bar plus its legend is a proportional
1250
+ // reading, and pairing it with the coverage figure puts the two "how much of
1251
+ // this repository" answers side by side. Order matters — it must directly
1252
+ // follow the overview for the grid to place them in the same row.
1253
+ languages !== null && languages.rows.length > 0 ? h(LanguageSection, { languages }) : null,
1254
+ // Caveats, in one card, sharing a row with the provenance card.
1255
+ //
1256
+ // `notable` and `contextWarnings` were two cards — one amber, one an untitled
1257
+ // list of `·` lines. They are the same thing at two volumes: both say "this
1258
+ // index does not line up with the working tree". Splitting them made the reader
1259
+ // check two boxes to answer one question, and the untitled one had no heading
1260
+ // to say what it was.
1261
+ notable.length > 0 || contextWarnings.length > 0
1262
+ ? h(Section, {
1263
+ title: `需要注意 · ${notable.length + contextWarnings.length}`,
1264
+ style: { display: 'flex', flexDirection: 'column', gap: '8px' },
1265
+ }, notable.map((warning, index) => h('div', {
1266
+ key: `${warning.code}-${index}`,
1267
+ style: {
1268
+ display: 'flex',
1269
+ gap: '7px',
1270
+ alignItems: 'flex-start',
1271
+ padding: '6px 8px',
1272
+ border: '1px solid color-mix(in srgb, #d9a441 45%, transparent)',
1273
+ background: 'color-mix(in srgb, #d9a441 9%, transparent)',
1274
+ borderRadius: '6px',
1275
+ },
1276
+ }, h(StateDot, { state: 'warning' }), h('span', { style: { minWidth: 0 } }, warning.message))),
1277
+ // The milder ones stay quiet rows: giving every item an amber box would
1278
+ // make a stale-index count look as urgent as a truncated activity window.
1279
+ contextWarnings.length === 0
1280
+ ? null
1281
+ : h('div', {
1282
+ style: {
1283
+ display: 'flex',
1284
+ flexDirection: 'column',
1285
+ gap: '4px',
1286
+ ...MUTED,
1287
+ ...(notable.length > 0 ? { borderTop: HAIRLINE, paddingTop: '8px' } : {}),
1288
+ },
1289
+ }, contextWarnings.map((warning, index) => h('div', { key: `${warning.code}-${index}` }, `· ${warning.message}`))))
1290
+ : null,
1291
+ // Shares the row above. Resolver confidence is what makes the counts above it
1292
+ // lower bounds, so it belongs beside the caveats rather than after the charts.
1293
+ h(Section, {
1294
+ title: '解析质量与溯源',
1295
+ meta: h('span', { style: { ...MUTED, fontSize: '11px' } }, provenanceCollapsed(report.graphQuality ?? null)),
1296
+ }, h(ProvenanceBlock, {
1297
+ quality: report.graphQuality ?? null,
1298
+ provenance: report.provenance ?? null,
1299
+ })),
1300
+ // Wide: file paths must keep their tails.
1301
+ largeFiles.length > 0
1302
+ ? h(Section, {
1303
+ wide: true,
1304
+ title: `被跳过的超大文件 · ${largeFiles.length} 个 · ${fileSize(totals.largeBytes)}`,
1305
+ }, h(LargeFileList, { files: largeFiles.slice(0, 40) }), largeFiles.length > 40
1306
+ ? h('div', { style: { ...MUTED, marginTop: '6px' } }, `…另有 ${largeFiles.length - 40} 个未显示`)
1307
+ : null)
1308
+ : null, report.activity === undefined || report.activity === null
1309
+ ? null
1310
+ : h(Section, {
1311
+ wide: true,
1312
+ title: `Git 活动 · ${activityView(report.activity)?.window ?? ''}`,
1313
+ meta: h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: '5px', ...MUTED, fontSize: '11px' } }, h(StateDot, {
1314
+ state: activityView(report.activity)?.verdicts.find((v) => v.key === 'missing')?.tone ?? 'done',
1315
+ }), activityCollapsed(report.activity)),
1316
+ }, h(GitActivitySection, { activity: report.activity })),
1317
+ // Wide, and always open: the commands are the action this panel offers.
1318
+ maintenance === null || maintenance === undefined
1319
+ ? null
1320
+ : h(Section, {
1321
+ wide: true,
1322
+ title: '维护命令',
1323
+ meta: h('span', { style: { ...MUTED, fontSize: '11px' } }, `${maintenance.commands?.length ?? 0} 条 · 复制后到会话执行(沙箱与提权由 DSH 处理)`),
1324
+ }, h(MaintenanceSection, { maintenance, projectPath, indexed, run, runError, now, onStartRun, onCancelRun })));
1325
+ }
1326
+ /**
1327
+ * Stateful wrapper: resolves the current project, loads its coverage.
1328
+ *
1329
+ * No repository list and no picker. The panel answers for the project the operator
1330
+ * is in; a project with no index is a normal state that leads with the command to
1331
+ * create one, not an error.
1332
+ *
1333
+ * @param {{params?: {repo?: string}, sessionId?: string, useWorkspaces?: Function}} props
1334
+ */
1335
+ function CoveragePanel(props) {
1336
+ const projectPath = useProjectPath(props);
1337
+ const [report, setReport] = React.useState(null);
1338
+ const [maintenance, setMaintenance] = React.useState(null);
1339
+ const [error, setError] = React.useState(null);
1340
+ const [busy, setBusy] = React.useState(false);
1341
+ const [reloadToken, setReloadToken] = React.useState(0);
1342
+ // When the report on screen was read. Without it a refresh of an unchanged
1343
+ // repository produces a byte-identical panel, so the control looks inert even
1344
+ // when it did precisely what it was asked to do.
1345
+ const [readAt, setReadAt] = React.useState(null);
1346
+ // Only a manual refresh bypasses the host's cache; the initial load does not.
1347
+ const wantsFresh = reloadToken > 0;
1348
+ // The refresh run, and the tick that makes its elapsed time advance. `run` is null
1349
+ // until something is started in this host's lifetime — a state the card renders as
1350
+ // "not run yet" rather than as a failure.
1351
+ const [run, setRun] = React.useState(null);
1352
+ const [runError, setRunError] = React.useState(null);
1353
+ const [tick, setTick] = React.useState(0);
1354
+ const running = run?.state === 'running';
1355
+ /**
1356
+ * Poll while a run is in flight.
1357
+ *
1358
+ * Deliberately not an always-on interval: a panel left open on an idle project should
1359
+ * make no requests at all, and the host keeps one run per repository, so a missed
1360
+ * poll costs nothing but a second.
1361
+ */
1362
+ React.useEffect(() => {
1363
+ if (projectPath === null || !running)
1364
+ return undefined;
1365
+ let cancelled = false;
1366
+ const poll = async () => {
1367
+ try {
1368
+ const res = await fetch(routeUrl(`/api/gitnexus/analyze?repo=${encodeURIComponent(projectPath)}`));
1369
+ const body = await res.json().catch(() => null);
1370
+ if (cancelled || !body?.ok)
1371
+ return;
1372
+ const next = body.run ?? null;
1373
+ setRun(next);
1374
+ // A finished run changed the index, so the report on screen is now a reading of
1375
+ // the previous one. This is the whole reason the run was started.
1376
+ if (next !== null && next.state !== 'running')
1377
+ setReloadToken((n) => n + 1);
1378
+ }
1379
+ catch {
1380
+ /* a dropped poll is not worth surfacing; the next one reports the state */
1381
+ }
1382
+ };
1383
+ const id = setInterval(() => {
1384
+ setTick((n) => n + 1);
1385
+ void poll();
1386
+ }, 1000);
1387
+ return () => {
1388
+ cancelled = true;
1389
+ clearInterval(id);
1390
+ };
1391
+ }, [projectPath, running]);
1392
+ const startRun = React.useCallback(async () => {
1393
+ if (projectPath === null)
1394
+ return;
1395
+ setRunError(null);
1396
+ try {
1397
+ const res = await fetch(routeUrl(`/api/gitnexus/analyze?repo=${encodeURIComponent(projectPath)}`), {
1398
+ method: 'POST',
1399
+ });
1400
+ const body = await res.json().catch(() => null);
1401
+ if (!body?.ok)
1402
+ throw new Error(body?.message ?? `请求失败 (${res.status})`);
1403
+ setRun(body.run ?? null);
1404
+ setTick(0);
1405
+ }
1406
+ catch (cause) {
1407
+ setRunError(String(cause?.message ?? cause));
1408
+ }
1409
+ }, [projectPath]);
1410
+ const cancelRun = React.useCallback(async () => {
1411
+ if (projectPath === null)
1412
+ return;
1413
+ try {
1414
+ const res = await fetch(routeUrl(`/api/gitnexus/analyze?repo=${encodeURIComponent(projectPath)}`), {
1415
+ method: 'DELETE',
1416
+ });
1417
+ const body = await res.json().catch(() => null);
1418
+ if (body?.ok)
1419
+ setRun(body.run ?? null);
1420
+ }
1421
+ catch (cause) {
1422
+ setRunError(String(cause?.message ?? cause));
1423
+ }
1424
+ }, [projectPath]);
1425
+ // The GitNexus install. Its own state because it is not tied to a repository: the
1426
+ // install target is one directory per machine, and the operator may have several
1427
+ // projects open across a session.
1428
+ const [installRun, setInstallRun] = React.useState(null);
1429
+ const [installError, setInstallError] = React.useState(null);
1430
+ const installing = installRun?.state === 'running';
1431
+ React.useEffect(() => {
1432
+ if (!installing)
1433
+ return undefined;
1434
+ let cancelled = false;
1435
+ const poll = async () => {
1436
+ try {
1437
+ const res = await fetch(routeUrl('/api/gitnexus/install'));
1438
+ const body = await res.json().catch(() => null);
1439
+ if (cancelled || !body?.ok)
1440
+ return;
1441
+ const next = body.run ?? null;
1442
+ setInstallRun(next);
1443
+ // A finished install changes what this machine can do, so re-read the report:
1444
+ // the toolchain verdict is computed per read, so this is what clears the notice.
1445
+ if (next !== null && next.state !== 'running')
1446
+ setReloadToken((n) => n + 1);
1447
+ }
1448
+ catch {
1449
+ /* a dropped poll is not worth surfacing */
1450
+ }
1451
+ };
1452
+ const id = setInterval(() => {
1453
+ setTick((n) => n + 1);
1454
+ void poll();
1455
+ }, 1000);
1456
+ return () => {
1457
+ cancelled = true;
1458
+ clearInterval(id);
1459
+ };
1460
+ }, [installing]);
1461
+ const startInstall = React.useCallback(async () => {
1462
+ setInstallError(null);
1463
+ try {
1464
+ const res = await fetch(routeUrl('/api/gitnexus/install'), { method: 'POST' });
1465
+ const body = await res.json().catch(() => null);
1466
+ if (!body?.ok)
1467
+ throw new Error(body?.message ?? `请求失败 (${res.status})`);
1468
+ setInstallRun(body.run ?? null);
1469
+ setTick(0);
1470
+ }
1471
+ catch (cause) {
1472
+ setInstallError(String(cause?.message ?? cause));
1473
+ }
1474
+ }, []);
1475
+ const cancelInstall = React.useCallback(async () => {
1476
+ try {
1477
+ const res = await fetch(routeUrl('/api/gitnexus/install'), { method: 'DELETE' });
1478
+ const body = await res.json().catch(() => null);
1479
+ if (body?.ok)
1480
+ setInstallRun(body.run ?? null);
1481
+ }
1482
+ catch (cause) {
1483
+ setInstallError(String(cause?.message ?? cause));
1484
+ }
1485
+ }, []);
1486
+ React.useEffect(() => {
1487
+ if (projectPath === null)
1488
+ return undefined;
1489
+ const controller = new AbortController();
1490
+ setBusy(true);
1491
+ setError(null);
1492
+ const query = `/api/gitnexus/coverage?repo=${encodeURIComponent(projectPath)}` + (wantsFresh ? '&refresh=1' : '');
1493
+ fetch(routeUrl(query), {
1494
+ signal: controller.signal,
1495
+ })
1496
+ .then(async (res) => ({ status: res.status, body: await res.json().catch(() => null) }))
1497
+ .then(({ status, body }) => {
1498
+ // `not-indexed` is a state the panel renders, not a failure: the whole
1499
+ // point of leading with the initialize command is that reaching it is
1500
+ // expected on a project that has never been analysed.
1501
+ if (status === 404 && body?.code === 'not-indexed') {
1502
+ setReport({ repo: { indexed: false, path: projectPath } });
1503
+ setMaintenance(null);
1504
+ setReadAt(body?.readAt ?? new Date().toISOString());
1505
+ return;
1506
+ }
1507
+ if (!body?.ok)
1508
+ throw new Error(body?.message ?? `请求失败 (${status})`);
1509
+ setReport(body.report);
1510
+ setMaintenance(body.maintenance ?? null);
1511
+ setReadAt(typeof body.readAt === 'string' ? body.readAt : new Date().toISOString());
1512
+ })
1513
+ .catch((cause) => {
1514
+ if (cause?.name !== 'AbortError')
1515
+ setError(String(cause?.message ?? cause));
1516
+ })
1517
+ .finally(() => setBusy(false));
1518
+ return () => controller.abort();
1519
+ }, [projectPath, reloadToken]);
1520
+ const fallbackMaintenance = React.useMemo(() => (maintenance === null && projectPath !== null ? { commands: [], rationale: [] } : maintenance), [maintenance, projectPath]);
1521
+ return h(CoverageView, {
1522
+ report,
1523
+ maintenance: fallbackMaintenance,
1524
+ projectPath,
1525
+ context: projectPath === null ? contextDiagnostic(props) : null,
1526
+ busy,
1527
+ error,
1528
+ readAt,
1529
+ run,
1530
+ runError,
1531
+ // `tick` is read here rather than inside the card, so elapsed seconds re-render
1532
+ // even when the host reports nothing new — a run with no output for a minute
1533
+ // otherwise looks frozen.
1534
+ now: Date.now() + tick * 0,
1535
+ onRefresh: () => setReloadToken((n) => n + 1),
1536
+ onStartRun: () => void startRun(),
1537
+ onCancelRun: () => void cancelRun(),
1538
+ installRun,
1539
+ installError,
1540
+ onInstall: () => void startInstall(),
1541
+ onCancelInstall: () => void cancelInstall(),
1542
+ });
1543
+ }
1544
+ /** The tab chip's live title. */
1545
+ function CoverageTitle() {
1546
+ return h('span', null, 'GitNexus');
1547
+ }
1548
+ // ---------------------------------------------------------------------------
1549
+ // Plugin
1550
+ // ---------------------------------------------------------------------------
1551
+ /**
1552
+ * Declared, not guessed: the loader hands `apply` a context carrying exactly
1553
+ * these, and reading anything else off `ctx` throws.
1554
+ *
1555
+ * `sidebarRightTabs` is deliberately absent and reached through `ctx.inject`
1556
+ * instead — it is an optional capability (a headless or TUI profile has no right
1557
+ * sidebar at all), and naming it here would leave this plugin permanently pending
1558
+ * on those profiles rather than simply contributing nothing.
1559
+ */
1560
+ const inject = ['slots'];
1561
+ function apply(ctx) {
1562
+ const safe = (tag, fn) => {
1563
+ try {
1564
+ fn();
1565
+ }
1566
+ catch (cause) {
1567
+ // One unknown slot name must not take the rest of the surface down with it.
1568
+ console.warn(`[${PLUGIN_ID}] client surface '${tag}' failed:`, cause);
1569
+ }
1570
+ };
1571
+ safe('sidebarRightTabs', () => {
1572
+ ctx.inject(['sidebarRightTabs'], (svcCtx) => {
1573
+ ctx.effect(() => svcCtx.sidebarRightTabs.register({
1574
+ id: PLUGIN_ID,
1575
+ kind: TAB_KIND,
1576
+ title: () => 'GitNexus',
1577
+ // The guide page is how a user discovers a contributed page type: it
1578
+ // renders one entry box per `guide` entry, and picking one opens this
1579
+ // kind. Without it the panel would be reachable only by a caller that
1580
+ // already knew the kind name.
1581
+ guide: [
1582
+ {
1583
+ id: `${PLUGIN_ID}:coverage`,
1584
+ order: 40,
1585
+ title: () => 'GitNexus 索引',
1586
+ description: () => '查看索引覆盖:被跳过的超大文件与语言分布',
1587
+ },
1588
+ ],
1589
+ }), `${PLUGIN_ID}: tab type`);
1590
+ });
1591
+ });
1592
+ safe('sidebar.right.pane.tab', () => {
1593
+ ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: PLUGIN_ID }, CoveragePanel));
1594
+ });
1595
+ safe('sidebar.right.pane.tab.title', () => {
1596
+ ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: PLUGIN_ID }, CoverageTitle));
1597
+ });
1598
+ }
1599
+ module.exports = {
1600
+ inject,
1601
+ apply,
1602
+ __internals: {
1603
+ PLUGIN_ID,
1604
+ TAB_KIND,
1605
+ routeUrl,
1606
+ formatBytes,
1607
+ fileSize,
1608
+ percent,
1609
+ stackSegments,
1610
+ splitWarnings,
1611
+ summaryLine,
1612
+ coverageRatio,
1613
+ healthState,
1614
+ stalenessView,
1615
+ capabilityRows,
1616
+ graphQualitySummary,
1617
+ activityView,
1618
+ compactNumber,
1619
+ useProjectPath,
1620
+ contextDiagnostic,
1621
+ CoveragePanel,
1622
+ CoverageView,
1623
+ CoverageTitle,
1624
+ LanguageBar,
1625
+ LanguageSection,
1626
+ LargeFileList,
1627
+ Ring,
1628
+ MetricGrid,
1629
+ Histogram,
1630
+ GitActivitySection,
1631
+ ProvenanceBlock,
1632
+ MaintenanceSection,
1633
+ CapabilityStrip,
1634
+ Section,
1635
+ classifyFileType,
1636
+ IconRefreshOutlineRegular,
1637
+ },
1638
+ };
1639
+
1640
+ return module.exports;
1641
+ }
1642
+ });