Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): frontmatter schema globs read as authored, edit in place, and carry their own problems (PRD-7647) (#3078)
serafin-garciafdbf3320210c
diff --git a/.changeset/glob-pill-editing.md b/.changeset/glob-pill-editing.mdnew file mode 100644index 000000000..85df3d090--- /dev/null+++ b/.changeset/glob-pill-editing.md@@ -0,0 +1,11 @@+---+'@inkeep/open-knowledge': minor+---++Editing the globs that scope a frontmatter schema to a set of docs got three fixes, all from the same root: once you pressed Enter, the pattern became something you could neither read accurately nor change.++**Patterns read as you typed them.** A committed pattern was displayed in capitals — `blog/**` rendered as `BLOG/**`. The pattern on disk was always correct, so nothing was ever scoped wrong by this, but globs are case-sensitive and the display gave you no way to confirm what you had actually saved. The same fix reaches every place these value pills are used, including the schema editor's "Allowed values", where an enum of `Draft` / `Published` was shown as `DRAFT` / `PUBLISHED`.++**Double-click a pattern to edit it.** Correcting `blog` to `blog/**` meant deleting the entry and retyping it from scratch. Double-clicking a pattern now lifts it back into the input with the text selected; the corrected pattern is written back in its original position, so an exclude that only applies to the includes before it stays where you put it. Enter or Space does the same thing from the keyboard, and Escape cancels.++**Problems point at the glob that caused them.** A pattern matching zero docs was reported in a "Configuration problems" list that named the pattern but not which schema's input it came from — with several schemas and several globs each, you could see something was wrong without being able to tell what to fix. The offending pattern is now marked on the input itself, with the reason on hover, and that is its only home. Deleting a flagged pattern no longer flashes a warning about it on the way out: the problems channel is composed from the file on disk and briefly lags the edit, so a pattern you just removed still had a live finding for a moment. Problems about the schema file rather than a glob still appear in the list.diff --git a/packages/app/src/components/settings/FrontmatterPluginSection.dom.test.tsx b/packages/app/src/components/settings/FrontmatterPluginSection.dom.test.tsxindex b9e8e549a..8f2c01023 100644--- a/packages/app/src/components/settings/FrontmatterPluginSection.dom.test.tsx+++ b/packages/app/src/components/settings/FrontmatterPluginSection.dom.test.tsx@@ -76,6 +76,20 @@ vi.doMock('@/editor/lint-config-client', () => ({}));const { FrontmatterPluginSection } = await import('./LintingSection.tsx');+const { TooltipProvider } = await import('@/components/ui/tooltip');++/**+ * The real app mounts a single TooltipProvider at the root (`main.tsx`), so a+ * flagged pill's tooltip has a provider in production; rendering the section+ * bare does not. Wrap here rather than in each test.+ */+function renderSection() {+ return render(+ <TooltipProvider>+ <FrontmatterPluginSection />+ </TooltipProvider>,+ );+}// Real module on purpose: the tests assert the banked Fields-view intent the// schema editor consumes on mount.const { consumeSchemaFieldsView } = await import('@/lib/schema-fields-view-intent');@@ -129,7 +143,7 @@ describe('FrontmatterPluginSection — schema browser', () => {});test('renders one toggleable row per discovered file', () => {- render(<FrontmatterPluginSection />);+ renderSection();const mapped = screen.getByTestId('frontmatter-schema-row-.ok/schemas/doc.schema.json');expect(mapped).toBeTruthy();expect(screen.getByTestId('frontmatter-schema-row-schemas/local.schema.json')).toBeTruthy();@@ -143,7 +157,7 @@ describe('FrontmatterPluginSection — schema browser', () => {});test('toggling an unmapped file on appends an enabled mapping', () => {- render(<FrontmatterPluginSection />);+ renderSection();fireEvent.click(screen.getByTestId('frontmatter-schema-toggle-schemas/local.schema.json'));expect(lastSchemas()).toEqual([{ appliesTo: ['docs/**'], file: '.ok/schemas/doc.schema.json', enabled: true },@@ -153,7 +167,7 @@ describe('FrontmatterPluginSection — schema browser', () => {});test('toggling a mapped file off keeps the mapping with enabled: false', () => {- render(<FrontmatterPluginSection />);+ renderSection();fireEvent.click(screen.getByTestId('frontmatter-schema-toggle-.ok/schemas/doc.schema.json'));expect(lastSchemas()).toEqual([{ appliesTo: ['docs/**'], file: '.ok/schemas/doc.schema.json', enabled: false },@@ -162,7 +176,7 @@ describe('FrontmatterPluginSection — schema browser', () => {test('a config-mapped file missing from discovery still renders (stays toggleable)', () => {mockProjectConfig = configWithMappings([{ file: 'gone/away.schema.json', enabled: true }]);- render(<FrontmatterPluginSection />);+ renderSection();expect(screen.getByTestId('frontmatter-schema-row-gone/away.schema.json')).toBeTruthy();});@@ -170,7 +184,7 @@ describe('FrontmatterPluginSection — schema browser', () => {mockProjectConfig = configWithMappings([{ appliesTo: ['docs/**'], file: '.ok/schemas/doc.schema.json', enabled: false },]);- render(<FrontmatterPluginSection />);+ renderSection();fireEvent.click(screen.getByTestId('frontmatter-schema-toggle-.ok/schemas/doc.schema.json'));expect(lastSchemas()).toEqual([{ appliesTo: ['docs/**'], file: '.ok/schemas/doc.schema.json', enabled: true },@@ -184,7 +198,7 @@ describe('FrontmatterPluginSection — schema browser', () => {mockProjectConfig = configWithMappings([{ appliesTo: ['docs/**'], file: '.ok/schemas/doc.schema.json' },]);- render(<FrontmatterPluginSection />);+ renderSection();const toggle = screen.getByTestId('frontmatter-schema-toggle-.ok/schemas/doc.schema.json',) as HTMLButtonElement;@@ -196,7 +210,7 @@ describe('FrontmatterPluginSection — schema browser', () => {});test('the toggle is the only control — no Modified badge, no reset', () => {- render(<FrontmatterPluginSection />);+ renderSection();expect(screen.queryByTestId('frontmatter-schema-modified-.ok/schemas/doc.schema.json'),).toBeNull();@@ -206,7 +220,7 @@ describe('FrontmatterPluginSection — schema browser', () => {});test('editing appliesTo writes the globs on the file mapping', () => {- render(<FrontmatterPluginSection />);+ renderSection();const input = document.getElementById('frontmatter-schema-applies-.ok/schemas/doc.schema.json',) as HTMLInputElement;@@ -216,7 +230,7 @@ describe('FrontmatterPluginSection — schema browser', () => {});test('search filters the rows', () => {- render(<FrontmatterPluginSection />);+ renderSection();fireEvent.change(screen.getByTestId('frontmatter-schema-search'), {target: { value: 'local' },});@@ -232,14 +246,14 @@ describe('FrontmatterPluginSection — schema browser', () => {});test('the Edit button opens the file via hash and banks the Fields-view intent', () => {- render(<FrontmatterPluginSection />);+ renderSection();fireEvent.click(screen.getByTestId('frontmatter-schema-edit-.ok/schemas/doc.schema.json'));expect(window.location.hash).toBe('#/__asset__/.ok/schemas/doc.schema.json');expect(consumeSchemaFieldsView('.ok/schemas/doc.schema.json')).toBe(true);});test('the schema name is plain text — Edit is the only way into the file', () => {- render(<FrontmatterPluginSection />);+ renderSection();expect(screen.queryByTestId('frontmatter-schema-open-schemas/local.schema.json')).toBeNull();fireEvent.click(screen.getByTestId('frontmatter-schema-edit-schemas/local.schema.json'));expect(window.location.hash).toBe('#/__asset__/schemas/local.schema.json');@@ -247,7 +261,7 @@ describe('FrontmatterPluginSection — schema browser', () => {});test('the section header carries the feature-beta tag', () => {- render(<FrontmatterPluginSection />);+ renderSection();const header = document.getElementById('settings-plugin-frontmatter-title')?.parentElement;expect(header?.textContent).toContain('Beta');});@@ -256,14 +270,14 @@ describe('FrontmatterPluginSection — schema browser', () => {mockProjectConfig = configWithMappings([{ file: '.ok/schemas/doc.schema.json', enabled: true },]);- render(<FrontmatterPluginSection />);+ renderSection();const input = document.getElementById('frontmatter-schema-applies-.ok/schemas/doc.schema.json');expect(input?.getAttribute('placeholder')).toContain('guides/**/*');expect(input?.getAttribute('placeholder')).toContain('pattern');});test('create-schema creates the file in .ok/schemas and maps it enabled', async () => {- render(<FrontmatterPluginSection />);+ renderSection();fireEvent.click(screen.getByTestId('frontmatter-create-schema'));fireEvent.change(screen.getByTestId('frontmatter-create-schema-name'), {target: { value: 'release' },@@ -287,16 +301,17 @@ describe('FrontmatterPluginSection — schema browser', () => {'[.markdownlint.json] malformed markdownlint config',],};- render(<FrontmatterPluginSection />);+ renderSection();const box = screen.getByTestId('frontmatter-config-problems');expect(box.textContent).toContain('doc.schema.json');- expect(box.textContent).toContain('matches no docs');expect(box.textContent).not.toContain('unmapped.json');expect(box.textContent).not.toContain('markdownlint config');+ // Glob findings are shown on the glob, never here — see the suite below.+ expect(box.textContent).not.toContain('matches no docs');});test('the trash affordance confirms, deletes the file, and wipes its mapping', async () => {- render(<FrontmatterPluginSection />);+ renderSection();fireEvent.click(screen.getByTestId('frontmatter-schema-delete-.ok/schemas/doc.schema.json'));// Nothing happens until the dialog confirms.expect(deleted).toEqual([]);@@ -315,7 +330,7 @@ describe('FrontmatterPluginSection — schema browser', () => {enabled: true,},]);- render(<FrontmatterPluginSection />);+ renderSection();const summary = screen.getByTestId('frontmatter-schema-applies-summary-.ok/schemas/doc.schema.json',);@@ -329,7 +344,7 @@ describe('FrontmatterPluginSection — schema browser', () => {mockProjectConfig = configWithMappings([{ file: '.ok/schemas/doc.schema.json', enabled: true },]);- render(<FrontmatterPluginSection />);+ renderSection();expect(screen.getByTestId('frontmatter-schema-applies-summary-.ok/schemas/doc.schema.json').textContent,@@ -339,9 +354,183 @@ describe('FrontmatterPluginSection — schema browser', () => {test('empty state renders when no schemas exist anywhere', () => {mockDiscovered = [];mockProjectConfig = configWithMappings([]);- render(<FrontmatterPluginSection />);+ renderSection();expect(screen.getByTestId('frontmatter-schemas-empty').textContent).toContain('No schema files in this project yet',);});});++describe('FrontmatterPluginSection — glob problems ride on the glob', () => {+ const UNMATCHED_DOCS =+ 'unmatched appliesTo glob "docs/**" — matches no docs in this project (frontmatter mapping for .ok/schemas/doc.schema.json)';++ test('an authored pattern carries its own finding instead of the flat list', () => {+ mockLintData = { effective: null, configProblems: [UNMATCHED_DOCS] };+ renderSection();++ const row = screen.getByTestId('frontmatter-schema-row-.ok/schemas/doc.schema.json');+ const flagged = row.querySelectorAll('[data-tag-problem="true"]');+ expect(flagged).toHaveLength(1);+ expect(flagged[0]?.textContent).toContain('docs/**');+ // Shown on the glob, so the list that couldn't say WHICH glob is gone.+ expect(screen.queryByTestId('frontmatter-config-problems')).toBeNull();+ });++ test('schema-level problems still use the list alongside an inline glob finding', () => {+ mockLintData = {+ effective: null,+ configProblems: [+ UNMATCHED_DOCS,+ 'frontmatter schema .ok/schemas/doc.schema.json: cannot read (ENOENT)',+ ],+ };+ renderSection();++ const box = screen.getByTestId('frontmatter-config-problems');+ expect(box.textContent).toContain('cannot read');+ expect(box.textContent).not.toContain('matches no docs');+ });++ test('a glob finding never falls back to the list when its row is off screen', () => {+ // One home per finding. Search is transient and author-driven — clearing+ // it brings the pill (and its warning) straight back.+ mockLintData = { effective: null, configProblems: [UNMATCHED_DOCS] };+ renderSection();+ fireEvent.change(screen.getByTestId('frontmatter-schema-search'), {+ target: { value: 'local' },+ });++ expect(screen.queryByTestId('frontmatter-schema-row-.ok/schemas/doc.schema.json')).toBeNull();+ expect(screen.queryByTestId('frontmatter-config-problems')).toBeNull();+ });++ test('a finding for a glob that is no longer authored stays out of the list', () => {+ // The reported bug: deleting a red glob removed the pill, and the finding+ // — still live because the config channel is composed from the on-disk+ // config.yml and lags the CRDT write — surfaced in the list for a moment+ // before the next lint cleared it. It read as a warning about a pattern+ // that no longer existed. This is that window: config already has the+ // glob gone, the server has not caught up.+ mockProjectConfig = configWithMappings([+ { appliesTo: ['other/**'], file: '.ok/schemas/doc.schema.json', enabled: true },+ ]);+ mockLintData = { effective: null, configProblems: [UNMATCHED_DOCS] };+ renderSection();++ expect(screen.queryByTestId('frontmatter-config-problems')).toBeNull();+ const row = screen.getByTestId('frontmatter-schema-row-.ok/schemas/doc.schema.json');+ expect(row.querySelectorAll('[data-tag-problem="true"]')).toHaveLength(0);+ });++ test('a stale finding does not redden whichever glob happens to remain', () => {+ // Matching is by exact pattern, so the surviving entry must not inherit a+ // deleted sibling's warning.+ mockProjectConfig = configWithMappings([+ { appliesTo: ['other/**'], file: '.ok/schemas/doc.schema.json', enabled: true },+ ]);+ mockLintData = { effective: null, configProblems: [UNMATCHED_DOCS] };+ renderSection();++ const row = screen.getByTestId('frontmatter-schema-row-.ok/schemas/doc.schema.json');+ const pills = [...row.querySelectorAll('[data-slot="tag-pill-input"] button')].filter(+ (el) => el.textContent !== '',+ );+ expect(pills.map((p) => p.textContent)).toEqual(['other/**']);+ expect(row.querySelector('[data-tag-problem="true"]')).toBeNull();+ });++ test('editing a flagged glob writes the corrected pattern in place', () => {+ mockProjectConfig = configWithMappings([+ {+ appliesTo: ['blog', '!blog/drafts/**'],+ file: '.ok/schemas/doc.schema.json',+ enabled: true,+ },+ ]);+ mockLintData = {+ effective: null,+ configProblems: [+ 'unmatched appliesTo glob "blog" — matches no docs in this project (frontmatter mapping for .ok/schemas/doc.schema.json)',+ ],+ };+ renderSection();++ const row = screen.getByTestId('frontmatter-schema-row-.ok/schemas/doc.schema.json');+ // Not `[data-slot="badge"] span`: a flagged pill is wrapped in a Radix+ // TooltipTrigger with `asChild`, whose own data-slot replaces the badge's.+ const pill = [...row.querySelectorAll('[data-slot="tag-pill-input"] button')].find(+ (el) => el.textContent === 'blog',+ ) as HTMLElement;+ fireEvent.doubleClick(pill);+ const input = row.querySelector('input') as HTMLInputElement;+ expect(input.value).toBe('blog');+ fireEvent.change(input, { target: { value: 'blog/**' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(lastSchemas()).toEqual([+ {+ appliesTo: ['blog/**', '!blog/drafts/**'],+ file: '.ok/schemas/doc.schema.json',+ enabled: true,+ },+ ]);+ });+});++describe('FrontmatterPluginSection — findings with no pill to land on', () => {+ // A row binds to the FIRST mapping for its file and only mounts the glob+ // input when that mapping is enabled, but the server reports problems per+ // mapping entry. These shapes have no pill that can ever carry the finding,+ // so suppressing them would silently unvalidate docs that are governed.+ const UNMATCHED_B =+ 'unmatched appliesTo glob "b/**" — matches no docs in this project (frontmatter mapping for .ok/schemas/doc.schema.json)';++ test('a second mapping for the same file keeps its finding in the list', () => {+ mockProjectConfig = configWithMappings([+ { appliesTo: ['a/**'], file: '.ok/schemas/doc.schema.json', enabled: true },+ { appliesTo: ['b/**'], file: '.ok/schemas/doc.schema.json', enabled: true },+ ]);+ mockLintData = { effective: null, configProblems: [UNMATCHED_B] };+ renderSection();++ const row = screen.getByTestId('frontmatter-schema-row-.ok/schemas/doc.schema.json');+ expect(row.textContent).toContain('a/**');+ expect(row.textContent).not.toContain('b/**');+ expect(screen.getByTestId('frontmatter-config-problems').textContent).toContain(+ 'matches no docs',+ );+ });++ test('an enabled mapping behind a disabled first one keeps its finding in the list', () => {+ // The row binds to the disabled mapping, so the glob input never mounts.+ mockProjectConfig = configWithMappings([+ { file: '.ok/schemas/doc.schema.json', enabled: false },+ { appliesTo: ['b/**'], file: '.ok/schemas/doc.schema.json', enabled: true },+ ]);+ mockLintData = { effective: null, configProblems: [UNMATCHED_B] };+ renderSection();++ const row = screen.getByTestId('frontmatter-schema-row-.ok/schemas/doc.schema.json');+ expect(row.querySelector('[data-slot="tag-pill-input"]')).toBeNull();+ expect(screen.getByTestId('frontmatter-config-problems').textContent).toContain(+ 'matches no docs',+ );+ });++ test('a pattern the bound enabled mapping carries stays out of the list', () => {+ // The pill is where this finding lives — including while search hides the+ // row, which is the trade-off this surface deliberately keeps.+ mockProjectConfig = configWithMappings([+ { appliesTo: ['b/**'], file: '.ok/schemas/doc.schema.json', enabled: true },+ ]);+ mockLintData = { effective: null, configProblems: [UNMATCHED_B] };+ renderSection();+ expect(screen.queryByTestId('frontmatter-config-problems')).toBeNull();++ fireEvent.change(screen.getByTestId('frontmatter-schema-search'), {+ target: { value: 'local' },+ });+ expect(screen.queryByTestId('frontmatter-config-problems')).toBeNull();+ });+});diff --git a/packages/app/src/components/settings/LintingSection.tsx b/packages/app/src/components/settings/LintingSection.tsxindex 88b392105..48f9e7fc6 100644--- a/packages/app/src/components/settings/LintingSection.tsx+++ b/packages/app/src/components/settings/LintingSection.tsx@@ -41,6 +41,7 @@ import { useConfigContext } from '@/lib/config-provider';import { hashFromAssetPath } from '@/lib/doc-hash';import { dispatchExternalLinkClick } from '@/lib/external-link';import { requestSchemaFieldsView } from '@/lib/schema-fields-view-intent';+import { indexGlobProblemsByFile, parseAppliesToGlobProblem } from './applies-to-glob-problems';import { LINT_PLUGIN_META } from './lint-plugin-meta';import { MarkdownlintRuleBrowser } from './markdownlint-rule-browser';import { PluginBetaBadge } from './PluginBetaBadge';@@ -419,6 +420,7 @@ function SchemaFileRow({file,mapping,disabled,+ globProblems,onToggle,onAppliesToChange,onDelete,@@ -426,6 +428,7 @@ function SchemaFileRow({file: string;mapping: FrontmatterSchemaMapping | undefined;disabled: boolean;+ globProblems: ReadonlyMap<string, string> | undefined;onToggle: (on: boolean) => void;onAppliesToChange: (globs: string[]) => void;onDelete: (() => void) | null;@@ -493,6 +496,7 @@ function SchemaFileRow({value={appliesToList(mapping?.appliesTo)}grammar="free-text"disabled={disabled}+ entryProblems={globProblems}onChange={onAppliesToChange}placeholder={t`Add file or folder pattern, e.g. guides/**/*`}aria-label={t`Glob patterns this schema applies to`}@@ -534,7 +538,7 @@ export function FrontmatterPluginSection() {// persistence debounce). The prefix strings are the compose contract in the// server's frontmatter-schemas.ts — keep in sync on either-side change.const mappedFiles = new Set(mappings.map((m) => m.file));- const problems = (data?.configProblems ?? []).filter((p) => {+ const scopedProblems = (data?.configProblems ?? []).filter((p) => {if (p.startsWith('frontmatter schema ')) {return [...mappedFiles].some((file) => p.startsWith(`frontmatter schema ${file}:`));}@@ -562,6 +566,42 @@ export function FrontmatterPluginSection() {const query = search.trim().toLowerCase();const visible = files.filter((f) => query === '' || f.toLowerCase().includes(query));+ // Glob problems belong to the glob that caused them, so a pattern whose pill+ // can carry its finding is dropped from this list — including when the search+ // box happens to be hiding that row, since the pill is still where the+ // finding lives.+ //+ // Two cases keep the list, and they are decided against the authored config+ // rather than against what is currently rendered:+ //+ // - A pattern absent from every mapping is stale. The config channel is+ // composed from the on-disk config.yml and lags a just-committed CRDT+ // edit by the persistence debounce, so a glob the author has already+ // deleted still has a live problem for a moment. Suppressed, or removing+ // a flagged glob would flash a warning about a pattern that no longer+ // exists on its way out.+ // - A pattern authored in a mapping that no pill can ever reach is listed.+ // A row binds to the FIRST mapping for its file (duplicates are a+ // supported hand-authored shape) and only mounts the glob input when that+ // mapping is enabled — so a second mapping's globs, or any mapping behind+ // a disabled first one, have nowhere to render. The server reports those+ // per mapping entry; dropping them would silently unvalidate docs that+ // are actively governed.+ const globProblemsByFile = indexGlobProblemsByFile(scopedProblems);+ const problems = scopedProblems.filter((p) => {+ const parsed = parseAppliesToGlobProblem(p);+ if (parsed === null) return true;+ const bound = mappings.find((m) => m.file === parsed.file);+ const carriedByPill =+ bound !== undefined &&+ mappingEnabled(bound) &&+ appliesToList(bound.appliesTo).includes(parsed.pattern);+ const authoredSomewhere = mappings.some(+ (m) => m.file === parsed.file && appliesToList(m.appliesTo).includes(parsed.pattern),+ );+ return !carriedByPill && authoredSomewhere;+ });+function toggleFile(file: string, on: boolean): void {if (!mappings.some((m) => m.file === file)) {if (on) writeMappings([...mappings, { file, enabled: true }]);@@ -716,6 +756,7 @@ export function FrontmatterPluginSection() {file={file}mapping={mappings.find((m) => m.file === file)}disabled={!bindingReady}+ globProblems={globProblemsByFile.get(file)}onToggle={(on) => toggleFile(file, on)}onAppliesToChange={(globs) => setAppliesTo(file, globs)}onDelete={isFrontmatterSchemaAsset(file) ? () => setDeleteTarget(file) : null}diff --git a/packages/app/src/components/settings/applies-to-glob-problems.test.ts b/packages/app/src/components/settings/applies-to-glob-problems.test.tsnew file mode 100644index 000000000..f21c89077--- /dev/null+++ b/packages/app/src/components/settings/applies-to-glob-problems.test.ts@@ -0,0 +1,99 @@+/**+ * The parser reads strings composed by the server's `lint/frontmatter-schemas.ts`.+ * Every literal here is the shape that file emits — if these fail after a+ * server-side wording change, the settings panel has stopped attributing glob+ * findings to their globs and the two sides need re-syncing.+ */++import { describe, expect, test } from 'vitest';+import { indexGlobProblemsByFile, parseAppliesToGlobProblem } from './applies-to-glob-problems';++const UNMATCHED =+ 'unmatched appliesTo glob "specs/**" — matches no docs in this project (frontmatter mapping for .ok/schemas/doc.schema.json)';+const SUSPICIOUS =+ 'suspicious appliesTo glob "blog/" — a trailing slash can never match (doc paths have no trailing slash) (frontmatter mapping for .ok/schemas/blog.schema.json)';+const INVALID =+ 'invalid appliesTo glob "[" — Unterminated character class (frontmatter mapping for schemas/local.schema.json)';++describe('parseAppliesToGlobProblem', () => {+ test('splits an unmatched problem into kind, pattern, detail, and file', () => {+ expect(parseAppliesToGlobProblem(UNMATCHED)).toEqual({+ kind: 'unmatched',+ pattern: 'specs/**',+ detail: 'matches no docs in this project',+ file: '.ok/schemas/doc.schema.json',+ });+ });++ test('keeps a detail that itself contains parentheses intact', () => {+ // The mapping suffix is matched from the right precisely so this detail+ // (the real trailing-slash wording) survives.+ expect(parseAppliesToGlobProblem(SUSPICIOUS)).toEqual({+ kind: 'suspicious',+ pattern: 'blog/',+ detail: 'a trailing slash can never match (doc paths have no trailing slash)',+ file: '.ok/schemas/blog.schema.json',+ });+ });++ test('parses the invalid kind', () => {+ expect(parseAppliesToGlobProblem(INVALID)?.kind).toBe('invalid');+ expect(parseAppliesToGlobProblem(INVALID)?.pattern).toBe('[');+ });++ test('unquotes a pattern carrying JSON escapes', () => {+ const problem =+ 'unmatched appliesTo glob "a\\"b/**" — matches no docs in this project (frontmatter mapping for s.json)';+ expect(parseAppliesToGlobProblem(problem)?.pattern).toBe('a"b/**');+ });++ test('returns null for problems that are not glob findings', () => {+ for (const other of [+ 'frontmatter schema .ok/schemas/doc.schema.json: cannot read (ENOENT)',+ '[.markdownlint.json] malformed markdownlint config',+ '',+ ]) {+ expect(parseAppliesToGlobProblem(other)).toBeNull();+ }+ });++ test('returns null on a recognized prefix with an unrecognized tail', () => {+ // Degrading to null keeps the finding in the flat list rather than+ // dropping it, so a server-side reword loses attribution, not the signal.+ for (const malformed of [+ 'unmatched appliesTo glob specs/** — no quotes (frontmatter mapping for s.json)',+ 'unmatched appliesTo glob "specs/**" — missing the mapping suffix',+ 'unmatched appliesTo glob "specs/**" (frontmatter mapping for s.json)',+ 'unmatched appliesTo glob "specs/**" — detail (frontmatter mapping for )',+ ]) {+ expect(parseAppliesToGlobProblem(malformed)).toBeNull();+ }+ });+});++describe('indexGlobProblemsByFile', () => {+ test('groups parseable problems by file then pattern, skipping the rest', () => {+ const index = indexGlobProblemsByFile([UNMATCHED, INVALID, 'unrelated problem']);+ expect([...index.keys()].sort()).toEqual([+ '.ok/schemas/doc.schema.json',+ 'schemas/local.schema.json',+ ]);+ expect(index.get('.ok/schemas/doc.schema.json')?.get('specs/**')).toBe(+ 'matches no docs in this project',+ );+ });++ test('joins several findings on one pattern so the tooltip reports all of them', () => {+ const index = indexGlobProblemsByFile([+ 'suspicious appliesTo glob "blog/" — a trailing slash can never match (doc paths have no trailing slash) (frontmatter mapping for s.json)',+ 'unmatched appliesTo glob "blog/" — matches no docs in this project (frontmatter mapping for s.json)',+ ]);+ expect(index.get('s.json')?.get('blog/')).toBe(+ 'a trailing slash can never match (doc paths have no trailing slash); matches no docs in this project',+ );+ });++ test('is empty when nothing parses', () => {+ expect(indexGlobProblemsByFile(['[.markdownlint.json] malformed'])).toEqual(new Map());+ });+});diff --git a/packages/app/src/components/settings/applies-to-glob-problems.ts b/packages/app/src/components/settings/applies-to-glob-problems.tsnew file mode 100644index 000000000..e4ed661d3--- /dev/null+++ b/packages/app/src/components/settings/applies-to-glob-problems.ts@@ -0,0 +1,100 @@+/**+ * Parses the config channel's `appliesTo` glob problems back into their parts+ * so each one can be shown on the glob it belongs to, rather than in a flat+ * list that names the pattern but not which input produced it.+ *+ * The wire shape is composed in the server's `lint/frontmatter-schemas.ts`:+ *+ * <kind> appliesTo glob "<pattern>" — <detail> (frontmatter mapping for <file>)+ *+ * where `<pattern>` is `JSON.stringify`d. That string is the compose contract+ * between the two files — keep in sync on either-side change. A shape this+ * parser doesn't recognize returns null and stays in the flat list, so a+ * server-side wording change degrades to the old surface instead of silently+ * dropping the problem.+ */++const KINDS = ['unmatched', 'invalid', 'suspicious'] as const;++type AppliesToGlobProblemKind = (typeof KINDS)[number];++export interface AppliesToGlobProblem {+ kind: AppliesToGlobProblemKind;+ /** The authored pattern, unquoted — matches the pill's value verbatim. */+ pattern: string;+ /** Why it's a problem, without the kind prefix or the mapping suffix. */+ detail: string;+ /** Schema file whose mapping carries the pattern. */+ file: string;+}++const GLOB_MARKER = ' appliesTo glob ';+const MAPPING_MARKER = ' (frontmatter mapping for ';+const DETAIL_SEPARATOR = ' — ';++/** Reads the leading `"..."` off `text`, honoring JSON escapes. */+function readQuoted(text: string): { value: string; rest: string } | null {+ if (!text.startsWith('"')) return null;+ for (let i = 1; i < text.length; i++) {+ const ch = text[i];+ if (ch === '\\') {+ i++;+ continue;+ }+ if (ch !== '"') continue;+ try {+ return { value: JSON.parse(text.slice(0, i + 1)) as string, rest: text.slice(i + 1) };+ } catch {+ return null;+ }+ }+ return null;+}++export function parseAppliesToGlobProblem(problem: string): AppliesToGlobProblem | null {+ const kind = KINDS.find((k) => problem.startsWith(`${k}${GLOB_MARKER}`));+ if (kind === undefined) return null;++ const quoted = readQuoted(problem.slice(kind.length + GLOB_MARKER.length));+ if (quoted === null) return null;++ // The mapping suffix is matched from the right: a detail can legitimately+ // contain parentheses, but the suffix is always last.+ const suffixAt = quoted.rest.lastIndexOf(MAPPING_MARKER);+ if (suffixAt === -1 || !quoted.rest.endsWith(')')) return null;+ const file = quoted.rest.slice(suffixAt + MAPPING_MARKER.length, -1);+ if (file === '') return null;++ const middle = quoted.rest.slice(0, suffixAt);+ if (!middle.startsWith(DETAIL_SEPARATOR)) return null;+ const detail = middle.slice(DETAIL_SEPARATOR.length);+ if (detail === '') return null;++ return { kind, pattern: quoted.value, detail, file };+}++/**+ * Groups parseable glob problems as file → pattern → detail. Several problems+ * can name one pattern (invalid and unmatched both fire on a bad glob); the+ * details join so the pill's tooltip reports all of them.+ */+export function indexGlobProblemsByFile(+ problems: readonly string[],+): ReadonlyMap<string, ReadonlyMap<string, string>> {+ const byFile = new Map<string, Map<string, string>>();+ for (const problem of problems) {+ const parsed = parseAppliesToGlobProblem(problem);+ if (parsed === null) continue;+ let byPattern = byFile.get(parsed.file);+ if (byPattern === undefined) {+ byPattern = new Map<string, string>();+ byFile.set(parsed.file, byPattern);+ }+ const existing = byPattern.get(parsed.pattern);+ byPattern.set(+ parsed.pattern,+ existing === undefined ? parsed.detail : `${existing}; ${parsed.detail}`,+ );+ }+ return byFile;+}diff --git a/packages/app/src/components/ui/tag-pill-input.dom.test.tsx b/packages/app/src/components/ui/tag-pill-input.dom.test.tsxindex 4d74f0ac4..47b0d973d 100644--- a/packages/app/src/components/ui/tag-pill-input.dom.test.tsx+++ b/packages/app/src/components/ui/tag-pill-input.dom.test.tsx@@ -378,3 +378,452 @@ describe('TagPillInput — a11y id wiring (regression: PR #1288 review findings)expect(wrapper?.getAttribute('aria-invalid')).toBe('true');});});++describe('TagPillInput — pills read as authored', () => {+ afterEach(() => {+ cleanup();+ });++ test('pills do not inherit the Badge uppercase transform', () => {+ // Badge's base class uppercases; these entries are case-sensitive values+ // (globs, tags, markdownlint option strings) and a pill that renders+ // BLOG/** for `blog/**` reads as corruption of a pattern that is fine.+ // twMerge resolves the conflict, so `uppercase` should be gone entirely.+ const { container } = render(+ <TooltipProvider>+ <TagPillInput value={['blog/**']} onChange={() => {}} grammar="free-text" />+ </TooltipProvider>,+ );+ const pill = container.querySelector('[data-slot="badge"]') ?? container.querySelector('span');+ expect(pill?.className).toContain('normal-case');+ expect(pill?.className).not.toContain('uppercase');+ });+});++describe('TagPillInput — per-entry problems', () => {+ afterEach(() => {+ cleanup();+ });++ function renderWithProblems(problems: [string, string][], value: string[]) {+ return render(+ <TooltipProvider>+ <TagPillInput+ value={value}+ onChange={() => {}}+ grammar="free-text"+ entryProblems={new Map(problems)}+ />+ </TooltipProvider>,+ );+ }++ test('flags only the entry named by a problem', () => {+ const { container } = renderWithProblems(+ [['specs/**', 'matches no docs in this project']],+ ['docs/**', 'specs/**'],+ );+ const flagged = container.querySelectorAll('[data-tag-problem="true"]');+ expect(flagged).toHaveLength(1);+ expect(flagged[0]?.textContent).toContain('specs/**');+ });++ test('a flagged entry is tooltip-wrapped so the message is reachable on hover', () => {+ const { container } = renderWithProblems(+ [['specs/**', 'matches no docs in this project']],+ ['specs/**'],+ );+ const badge = container.querySelector('[data-tag-problem="true"]');+ expect(badge?.getAttribute('data-state')).toBe('closed');+ });++ test('entries with no problem stay unflagged and untooltipped', () => {+ const { container } = renderWithProblems([['specs/**', 'nope']], ['docs/**']);+ expect(container.querySelectorAll('[data-tag-problem="true"]')).toHaveLength(0);+ expect(container.querySelector('[data-slot="badge"]')?.getAttribute('data-state')).toBeNull();+ });++ test('free-text entries are not flagged by the tag grammar (problems are the only source)', () => {+ const { container } = renderWithProblems([], ['## Summary']);+ expect(container.querySelectorAll('[data-tag-invalid="true"]')).toHaveLength(0);+ expect(container.querySelectorAll('[data-tag-problem="true"]')).toHaveLength(0);+ });++ test('double-clicking a flagged entry lifts it into the input for correction', () => {+ // The flagged path is structurally different from an unflagged pill: a+ // flagged pill is tooltip-wrapped, so `[data-slot="badge"] button` cannot+ // reach it. Query through the wrapper so this exercises the real flagged+ // structure, not the unflagged one the double-click block covers.+ const { container } = renderWithProblems(+ [['specs/**', 'matches no docs in this project']],+ ['specs/**'],+ );+ const editButton = [...container.querySelectorAll('[data-slot="tag-pill-input"] button')].find(+ (el) => el.textContent === 'specs/**',+ ) as HTMLElement;+ fireEvent.doubleClick(editButton);+ const input = container.querySelector('input') as HTMLInputElement;+ expect(input.value).toBe('specs/**');+ expect(document.activeElement).toBe(input);+ });++ test('the tooltip on a flagged entry reports the problem detail', async () => {+ // The tooltip is the only place the "why" of a problem now lives, so the+ // detail text — not merely the presence of a tooltip — is the contract.+ const { container, findByRole } = renderWithProblems(+ [['specs/**', 'matches no docs in this project']],+ ['specs/**'],+ );+ fireEvent.focus(container.querySelector('[data-tag-problem="true"]') as HTMLElement);+ const tooltip = await findByRole('tooltip');+ expect(tooltip.textContent).toContain('matches no docs in this project');+ });++ test('a flagged entry drops the native edit title so tooltips do not compete', () => {+ // The flagged pill already shows a Radix tooltip with the problem detail;+ // the native `title` on the edit button would stack a second, competing+ // tooltip. Unflagged pills keep the affordance hint.+ const { container } = renderWithProblems(+ [['specs/**', 'matches no docs in this project']],+ ['docs/**', 'specs/**'],+ );+ const buttons = [...container.querySelectorAll('[data-slot="tag-pill-input"] button')];+ const flaggedEdit = buttons.find((el) => el.textContent === 'specs/**') as HTMLElement;+ const okEdit = buttons.find((el) => el.textContent === 'docs/**') as HTMLElement;+ expect(flaggedEdit.getAttribute('title')).toBeNull();+ expect(okEdit.getAttribute('title')).toBe('Double-click to edit');+ });+});++describe('TagPillInput — double-click to edit', () => {+ afterEach(() => {+ cleanup();+ });++ function renderEditable(value: string[], onChange = vi.fn(() => {})) {+ const result = render(+ <TooltipProvider>+ <TagPillInput value={value} onChange={onChange} grammar="free-text" />+ </TooltipProvider>,+ );+ const input = result.container.querySelector('input') as HTMLInputElement;+ // The pill label is a button (keyboard parity for the edit gesture); the+ // sibling remove button has no text, so matching on textContent is exact.+ const label = (text: string) =>+ [...result.container.querySelectorAll('[data-slot="badge"] button')].find(+ (el) => el.textContent === text,+ ) as HTMLElement;+ return { ...result, onChange, input, label };+ }++ test('lifts the entry into the input and takes it off the row', () => {+ const { input, label, container } = renderEditable(['blog', 'docs/**']);+ fireEvent.doubleClick(label('blog'));+ expect(input.value).toBe('blog');+ // The entry lives in the input now — showing both would read as a duplicate.+ expect(container.textContent).not.toMatch(/blog(?!\/)/);+ expect(document.activeElement).toBe(input);+ });++ test('commits in place so the entry keeps its position', () => {+ // Order carries meaning for globs: an exclude only subtracts from the+ // includes before it, so a corrected pattern must not jump to the end.+ const { input, label, onChange } = renderEditable(['blog', '!blog/drafts/**', 'docs/**']);+ fireEvent.doubleClick(label('blog'));+ fireEvent.change(input, { target: { value: 'blog/**' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledWith(['blog/**', '!blog/drafts/**', 'docs/**']);+ });++ test('Escape abandons the edit and restores the entry untouched', () => {+ const { input, label, onChange, container } = renderEditable(['blog']);+ fireEvent.doubleClick(label('blog'));+ fireEvent.change(input, { target: { value: 'blo' } });+ fireEvent.keyDown(input, { key: 'Escape' });+ expect(onChange).not.toHaveBeenCalled();+ expect(input.value).toBe('');+ expect(container.textContent).toContain('blog');+ });++ test('clearing the text and committing deletes the entry', () => {+ const { input, label, onChange } = renderEditable(['blog', 'docs/**']);+ fireEvent.doubleClick(label('blog'));+ fireEvent.change(input, { target: { value: '' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledWith(['docs/**']);+ });++ test('Backspace on an emptied edit box does not also eat the previous entry', () => {+ const { input, label, onChange } = renderEditable(['blog', 'docs/**']);+ fireEvent.doubleClick(label('docs/**'));+ fireEvent.change(input, { target: { value: '' } });+ fireEvent.keyDown(input, { key: 'Backspace' });+ expect(onChange).not.toHaveBeenCalled();+ });++ test('blur commits the edit', () => {+ const { input, label, onChange } = renderEditable(['blog']);+ fireEvent.doubleClick(label('blog'));+ fireEvent.change(input, { target: { value: 'blog/**' } });+ fireEvent.blur(input);+ expect(onChange).toHaveBeenCalledWith(['blog/**']);+ });++ test('blur on an emptied edit box deletes the entry', () => {+ // Pins the `|| editingEntry !== null` guard in onBlur. Simplifying that+ // condition to `if (draft.trim())` would silently break delete-by-clearing.+ const { input, label, onChange } = renderEditable(['blog', 'docs/**']);+ fireEvent.doubleClick(label('blog'));+ fireEvent.change(input, { target: { value: '' } });+ fireEvent.blur(input);+ expect(onChange).toHaveBeenCalledWith(['docs/**']);+ });++ test('editing an entry into another entry collapses the pair', () => {+ const { input, label, onChange } = renderEditable(['blog', 'docs/**']);+ fireEvent.doubleClick(label('blog'));+ fireEvent.change(input, { target: { value: 'docs/**' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledWith(['docs/**']);+ });++ test('a draft in flight is committed rather than dropped when a pill is double-clicked', () => {+ const { input, label, onChange } = renderEditable(['blog']);+ fireEvent.change(input, { target: { value: 'specs/**' } });+ fireEvent.doubleClick(label('blog'));+ expect(onChange).toHaveBeenCalledWith(['blog', 'specs/**']);+ expect(input.value).toBe('blog');+ });++ test('ArrowLeft then Enter reaches the same edit from the keyboard', () => {+ const { input } = renderEditable(['blog', 'docs/**']);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(input.value).toBe('blog');+ expect(document.activeElement).toBe(input);+ });++ test('Space activates the edit on a highlighted entry (keyboard parity with Enter)', () => {+ // The changeset promises "Enter or Space does the same thing from the+ // keyboard". Space must lift the highlighted entry into the input without+ // inserting a stray space character.+ const { input } = renderEditable(['blog', 'docs/**']);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: ' ' });+ expect(input.value).toBe('blog');+ expect(document.activeElement).toBe(input);+ });++ test('the pill label carries an accessible name naming the action', () => {+ const { label } = renderEditable(['blog']);+ expect(label('blog').getAttribute('aria-label')).toBe('Edit blog');+ });++ test('double-click is inert while disabled', () => {+ const { container } = render(+ <TooltipProvider>+ <TagPillInput value={['blog']} onChange={() => {}} grammar="free-text" disabled />+ </TooltipProvider>,+ );+ const label = container.querySelector('[data-slot="badge"] button') as HTMLElement;+ fireEvent.doubleClick(label);+ expect((container.querySelector('input') as HTMLInputElement).value).toBe('');+ });+});++describe('TagPillInput — roving highlight', () => {+ afterEach(() => {+ cleanup();+ });++ function renderRoving(value: string[], onChange = vi.fn(() => {})) {+ const result = render(+ <TooltipProvider>+ <TagPillInput value={value} onChange={onChange} grammar="free-text" id="globs" />+ </TooltipProvider>,+ );+ const input = result.container.querySelector('input') as HTMLInputElement;+ const highlighted = () => result.container.querySelector('[data-highlighted="true"]');+ return { ...result, onChange, input, highlighted };+ }++ test('entries are not tab stops — the pill label is removed from the tab order', () => {+ // The whole point of the roving model: reaching the input should not mean+ // tabbing past every entry already in the list.+ const { container } = renderRoving(['a', 'b', 'c']);+ const labels = [...container.querySelectorAll('[data-slot="badge"] button')].filter(+ (el) => el.textContent !== '',+ );+ expect(labels).toHaveLength(3);+ for (const label of labels) expect(label.getAttribute('tabindex')).toBe('-1');+ });++ test('ArrowLeft at the start of the input highlights the last entry', () => {+ const { input, highlighted } = renderRoving(['a', 'b']);+ expect(highlighted()).toBeNull();+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ expect(highlighted()?.textContent).toContain('b');+ });++ test('ArrowLeft does not leave the text while the caret is mid-draft', () => {+ // Arrowing through what you are typing has to keep working.+ const { input, highlighted } = renderRoving(['a']);+ fireEvent.change(input, { target: { value: 'draft' } });+ input.setSelectionRange(3, 3);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ expect(highlighted()).toBeNull();+ });++ test('Left and Right walk the highlight, and Right past the end returns to the input', () => {+ const { input, highlighted } = renderRoving(['a', 'b', 'c']);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ expect(highlighted()?.textContent).toContain('c');+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ expect(highlighted()?.textContent).toContain('b');+ fireEvent.keyDown(input, { key: 'ArrowRight' });+ expect(highlighted()?.textContent).toContain('c');+ fireEvent.keyDown(input, { key: 'ArrowRight' });+ expect(highlighted()).toBeNull();+ });++ test('Home and End jump the highlight to the ends', () => {+ const { input, highlighted } = renderRoving(['a', 'b', 'c']);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: 'Home' });+ expect(highlighted()?.textContent).toContain('a');+ fireEvent.keyDown(input, { key: 'End' });+ expect(highlighted()?.textContent).toContain('c');+ });++ test('the highlight is reported through aria-activedescendant', () => {+ const { input, highlighted } = renderRoving(['a', 'b']);+ expect(input.getAttribute('aria-activedescendant')).toBeNull();+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ expect(input.getAttribute('aria-activedescendant')).toBe(highlighted()?.id);+ });++ test('Backspace removes the highlighted entry and steps backward', () => {+ const { input, onChange, highlighted } = renderRoving(['a', 'b', 'c']);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: 'Backspace' });+ expect(onChange).toHaveBeenCalledWith(['a', 'c']);+ expect(highlighted()?.textContent).toContain('a');+ });++ test('Delete removes the highlighted entry and steps forward', () => {+ const { input, onChange, highlighted } = renderRoving(['a', 'b', 'c']);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: 'Delete' });+ expect(onChange).toHaveBeenCalledWith(['a', 'c']);+ expect(highlighted()?.textContent).toContain('c');+ });++ test('Backspace with nothing highlighted still removes the last entry', () => {+ // The pre-existing shortcut has to survive the new branch above it.+ const { input, onChange } = renderRoving(['a', 'b']);+ fireEvent.keyDown(input, { key: 'Backspace' });+ expect(onChange).toHaveBeenCalledWith(['a']);+ });++ test('Escape and typing both drop the highlight', () => {+ const { input, highlighted } = renderRoving(['a', 'b']);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ fireEvent.keyDown(input, { key: 'Escape' });+ expect(highlighted()).toBeNull();++ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ expect(highlighted()).not.toBeNull();+ fireEvent.change(input, { target: { value: 'x' } });+ expect(highlighted()).toBeNull();+ });++ test('no highlight is reachable in an empty list', () => {+ const { input, highlighted } = renderRoving([]);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ expect(highlighted()).toBeNull();+ expect(input.getAttribute('aria-activedescendant')).toBeNull();+ });+});++describe('TagPillInput — abandoning an edit', () => {+ afterEach(() => {+ cleanup();+ });++ test('a blur that fails the grammar gate returns the entry to the row', () => {+ // The rejection path commits nothing. If `editingEntry` survived the blur,+ // the render filter would keep hiding the entry while `value` still holds+ // it — the pill would be invisible until the author clicked back in.+ const onChange = vi.fn(() => {});+ const { container } = render(+ <TooltipProvider>+ <TagPillInput value={['keeper']} onChange={onChange} />+ </TooltipProvider>,+ );+ const input = container.querySelector('input') as HTMLInputElement;+ const label = [...container.querySelectorAll('[data-slot="badge"] button')].find(+ (el) => el.textContent === 'keeper',+ ) as HTMLElement;++ fireEvent.doubleClick(label);+ expect(input.value).toBe('keeper');+ fireEvent.change(input, { target: { value: 'has spaces' } });+ fireEvent.blur(input);++ expect(onChange).not.toHaveBeenCalled();+ expect(container.textContent).toContain('keeper');+ });++ test('Escape with only a highlight active keeps the typed draft', () => {+ // Navigating away from the draft and back must not destroy it; Escape+ // clears the selection, not the text.+ const { input, highlighted } = (() => {+ const result = render(+ <TooltipProvider>+ <TagPillInput value={['a', 'b']} onChange={() => {}} grammar="free-text" />+ </TooltipProvider>,+ );+ const el = result.container.querySelector('input') as HTMLInputElement;+ return {+ input: el,+ highlighted: () => result.container.querySelector('[data-highlighted="true"]'),+ };+ })();++ fireEvent.change(input, { target: { value: 'spec' } });+ input.setSelectionRange(0, 0);+ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ expect(highlighted()).not.toBeNull();++ fireEvent.keyDown(input, { key: 'Escape' });+ expect(highlighted()).toBeNull();+ expect(input.value).toBe('spec');+ });++ test('Escape during a real edit still abandons it', () => {+ const { input, container } = (() => {+ const result = render(+ <TooltipProvider>+ <TagPillInput value={['blog']} onChange={() => {}} grammar="free-text" />+ </TooltipProvider>,+ );+ return {+ input: result.container.querySelector('input') as HTMLInputElement,+ container: result.container,+ };+ })();+ const label = [...container.querySelectorAll('[data-slot="badge"] button')].find(+ (el) => el.textContent === 'blog',+ ) as HTMLElement;++ fireEvent.doubleClick(label);+ fireEvent.change(input, { target: { value: 'blo' } });+ fireEvent.keyDown(input, { key: 'Escape' });+ expect(input.value).toBe('');+ expect(container.textContent).toContain('blog');+ });+});diff --git a/packages/app/src/components/ui/tag-pill-input.tsx b/packages/app/src/components/ui/tag-pill-input.tsxindex 6dcf572c0..77fb9bbb1 100644--- a/packages/app/src/components/ui/tag-pill-input.tsx+++ b/packages/app/src/components/ui/tag-pill-input.tsx@@ -6,7 +6,7 @@ import {} from '@inkeep/open-knowledge-core';import { useLingui } from '@lingui/react/macro';import { XIcon } from 'lucide-react';-import { type Ref, useId, useState } from 'react';+import { type Ref, useEffect, useId, useRef, useState } from 'react';import { Badge } from '@/components/ui/badge';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { cn } from '@/lib/utils';@@ -30,6 +30,14 @@ interface TagPillInputProps {* reject, and whose leading `#` must survive).*/grammar?: 'frontmatter-tag' | 'free-text';+ /**+ * Per-entry problems keyed by the entry's exact value: flags that pill+ * destructive and puts the message in its tooltip. This carries findings for+ * callers whose entries are validated elsewhere — a glob is only known to+ * match nothing once the server has walked the project — so the finding can+ * be shown on the entry that caused it rather than in a list beside it.+ */+ entryProblems?: ReadonlyMap<string, string>;/*** Forwarded onto the inner `<input>` so RHF's `form.setFocus(name)`* resolves through `Controller.field.ref`. Without this, `setFocus` on@@ -42,13 +50,30 @@ interface TagPillInputProps {/*** String-array editor rendering each entry as a removable Badge pill plus- * a native input for adding new entries. Used by FoldersSection for- * `folders[].frontmatter.tags`.+ * a native input for adding new entries. Consumers are the settings surfaces:+ * markdownlint option lists (`rule-option-field`), a frontmatter schema's+ * `appliesTo` globs (`LintingSection`), and a schema field's allowed values —+ * both the field's own and an array field's element values+ * (`frontmatter-schema-field-editor`). All four pass `grammar="free-text"`.+ * The `frontmatter-tag` default is still the grammar a `tags:` editor would+ * want, but nothing binds it today.** Commit triggers: Enter, comma, Tab (with non-empty draft — Tab on empty* preserves default focus shift), and blur. Backspace on an empty draft* removes the last pill. Duplicates are silently deduped.*+ * Double-clicking a pill lifts it back into the input with its text selected,+ * so correcting one character doesn't mean deleting the entry and retyping it.+ * The edit is tracked by the entry's value rather than its index, and commits+ * in place: entry order is meaningful to some callers (in a glob list an+ * exclude only subtracts from the includes before it). Escape cancels.+ *+ * Keyboard route to the same thing: ArrowLeft from the start of the input+ * highlights the last entry, Left/Right/Home/End move the highlight, Enter or+ * Space edits it, Backspace/Delete remove it. DOM focus stays on the input and+ * the highlight is reported via `aria-activedescendant`, so the edit affordance+ * adds no tab stops — the only per-entry tab stop is each pill's remove button.+ ** The wrapper carries the focus-ring and aria-invalid styling (matches the* shadcn `Input` look). The inner `<input>` accepts `id` so a* `<FormLabel htmlFor={id}>` resolves to a focusable element; `aria-invalid`@@ -63,12 +88,31 @@ function TagPillInput({id,disabled,grammar = 'frontmatter-tag',+ entryProblems,'aria-describedby': ariaDescribedBy,'aria-invalid': ariaInvalid,ref,}: TagPillInputProps) {const { t } = useLingui();const [draft, setDraft] = useState('');+ // The entry currently lifted into the input for editing, held by value (not+ // index) so a concurrent commit that reorders or dedupes the list can't+ // retarget the edit onto a different pill.+ const [editingEntry, setEditingEntry] = useState<string | null>(null);+ // Roving highlight: DOM focus stays on the input and arrow keys move a+ // visual selection across the committed entries, which is how Zag/Ark,+ // Dice UI and Reka all model this. Keeping entries out of the tab order+ // matters — a per-entry tab stop would put N stops between the author and+ // the box they are typing in.+ const [highlightedEntry, setHighlightedEntry] = useState<string | null>(null);+ const inputRef = useRef<HTMLInputElement | null>(null);+ // The caller's ref still has to reach the input (RHF resolves setFocus+ // through it), so both are attached.+ const attachInput = (node: HTMLInputElement | null) => {+ inputRef.current = node;+ if (typeof ref === 'function') ref(node);+ else if (ref) ref.current = node;+ };// Same shape as PropertyWidgets.ListWidget — when an author types an// invalid tag and tries to commit, keep the draft on screen with the// destructive ring + grammar hint instead of silently dropping@@ -82,16 +126,36 @@ function TagPillInput({// the helper stays attached to the same field; fall back to a// self-generated useId for standalone callers.const grammarHintId = `${id ?? fallbackId}-grammar-hint`;+ // Highlighted entries are announced through `aria-activedescendant` on the+ // input, which owns DOM focus the whole time — without it the highlight is+ // a purely visual state that a screen reader never reports.+ const pillIdBase = `${id ?? fallbackId}-pill`;const resolvedPlaceholder = placeholder ?? t`Add tag`;const tagGrammar = grammar === 'frontmatter-tag';- const addTag = (raw: string) => {+ const clearDraft = () => {+ setDraft('');+ setDraftRejected(false);+ setEditingEntry(null);+ };++ /** Returns false when the grammar gate rejected the draft (nothing committed). */+ const addTag = (raw: string): boolean => {const tag = raw.trim();- if (!tag) return;+ // Index is resolved at commit time — the pill may have moved since the+ // edit began. A vanished entry falls back to the append path.+ const editIndex = editingEntry === null ? -1 : value.indexOf(editingEntry);+ if (!tag) {+ // Only reachable mid-edit: emptying a pill's text is how you delete it+ // from inside the input.+ if (editIndex !== -1) onChange(value.filter((_, i) => i !== editIndex));+ if (editingEntry !== null) clearDraft();+ return true;+ }if (tagGrammar && !isValidFrontmatterTagValue(tag)) {setDraftRejected(true);- return;+ return false;}// Normalize leading `#` (tag grammar only). `isValidFrontmatterTagValue`// strips a single leading `#` for paste tolerance (Obsidian-shape@@ -102,20 +166,52 @@ function TagPillInput({// miss the duplicate `#showcase` / `showcase` pair. Free-text// entries commit verbatim (`## Summary` keeps its `#`s).const normalized = tagGrammar && tag.startsWith('#') ? tag.slice(1) : tag;- if (value.includes(normalized)) {- setDraft('');- setDraftRejected(false);- return;+ const duplicateAt = value.indexOf(normalized);+ if (editIndex === -1) {+ if (duplicateAt === -1) onChange([...value, normalized]);+ clearDraft();+ return true;}- setDraftRejected(false);- onChange([...value, normalized]);- setDraft('');+ // Write in place so the entry keeps its position. Editing one entry into+ // another's value collapses the pair rather than committing a duplicate.+ const next = value.map((entry, i) => (i === editIndex ? normalized : entry));+ onChange(+ duplicateAt === -1 || duplicateAt === editIndex+ ? next+ : next.filter((_, i) => i !== editIndex),+ );+ clearDraft();+ return true;};const removeAt = (i: number) => {onChange(value.filter((_, idx) => idx !== i));};+ const beginEdit = (entry: string) => {+ if (disabled) return;+ // Whatever is already in the box is committed rather than dropped —+ // double-clicking a pill mid-typing shouldn't discard the draft.+ if (draft.trim() !== '') addTag(draft);+ setDraft(entry);+ setDraftRejected(false);+ setHighlightedEntry(null);+ setEditingEntry(entry);+ };++ const highlightedIndex = highlightedEntry === null ? -1 : value.indexOf(highlightedEntry);+ const highlightAt = (index: number | null) => {+ setHighlightedEntry(index === null ? null : (value[index] ?? null));+ };++ // Focus + select once the lifted text has rendered, so the whole entry is+ // replaceable by typing but a single character is still reachable.+ useEffect(() => {+ if (editingEntry === null) return;+ inputRef.current?.focus();+ inputRef.current?.select();+ }, [editingEntry]);+return (<divdata-slot="tag-pill-input"@@ -132,22 +228,57 @@ function TagPillInput({)}>{value.map((tag, i) => {+ // The entry being edited lives in the input, not on the row.+ if (tag === editingEntry) return null;// Pills that fail the grammar gate are arriving from the// source-mode editor (or programmatic seed) — surface them// with a destructive variant + grammar-hint tooltip so the// author can find and clean them up without context-switching.// Free-text mode has no grammar, so nothing to flag.const invalid = tagGrammar && !isValidFrontmatterTagValue(tag);+ const problem = entryProblems?.get(tag);+ const flagged = invalid || problem !== undefined;+ const hint = problem ?? (invalid ? FRONTMATTER_TAG_GRAMMAR_HINT : undefined);+ const highlighted = tag === highlightedEntry;const badge = (<Badge// Tags are unique within the list (dedup above) — `tag` itself// is a stable key that survives reorders.key={tag}- variant={invalid ? 'destructive' : 'secondary'}+ id={`${pillIdBase}-${i}`}+ variant={flagged ? 'destructive' : 'secondary'}data-tag-invalid={invalid ? 'true' : undefined}- className={cn('gap-1 pl-2 pr-1', invalid && 'ring-1 ring-destructive/40')}+ data-tag-problem={problem !== undefined ? 'true' : undefined}+ data-highlighted={highlighted ? 'true' : undefined}+ // Badge uppercases by default; these entries are case-sensitive+ // values (globs, tags, option strings) and must read as authored.+ className={cn(+ 'gap-1 pl-2 pr-1 normal-case',+ flagged && 'ring-1 ring-destructive/40',+ highlighted && 'ring-2 ring-ring/70',+ )}>- <span className="font-mono">{tag}</span>+ {/*+ * A button rather than a styled span so the double-click handler+ * sits on something interactive, but `tabIndex={-1}` keeps it out+ * of the tab order: the keyboard route in is the roving highlight+ * on the input (arrow keys, then Enter), not a stop per entry.+ */}+ <button+ type="button"+ tabIndex={-1}+ className="cursor-pointer rounded-sm font-mono"+ onDoubleClick={() => beginEdit(tag)}+ disabled={disabled}+ aria-label={t`Edit ${tag}`}+ // Suppress the native hint on a flagged pill: its Badge already+ // carries a Radix tooltip with the problem detail, and two+ // tooltips on one control stack and compete. The aria-label still+ // conveys the edit affordance.+ title={hint === undefined ? t`Double-click to edit` : undefined}+ >+ {tag}+ </button><buttontype="button"onClick={() => removeAt(i)}@@ -159,26 +290,73 @@ function TagPillInput({</button></Badge>);- if (!invalid) return badge;+ if (hint === undefined) return badge;return (<Tooltip key={tag}><TooltipTrigger asChild>{badge}</TooltipTrigger>- <TooltipContent>{FRONTMATTER_TAG_GRAMMAR_HINT}</TooltipContent>+ <TooltipContent>{hint}</TooltipContent></Tooltip>);})}<inputid={id}- ref={ref}+ ref={attachInput}type="text"value={draft}onChange={(e) => {setDraft(e.target.value);if (draftRejected) setDraftRejected(false);+ // Typing is unambiguously about the draft, not the highlighted entry.+ if (highlightedEntry !== null) setHighlightedEntry(null);}}onKeyDown={(e) => {+ const el = e.currentTarget;+ // Left only spills out of the text once the caret is already at the+ // start, so arrowing through what you are typing still works.+ const caretAtStart = el.selectionStart === 0 && el.selectionEnd === 0;+ if (editingEntry === null && value.length > 0) {+ if (e.key === 'ArrowLeft' && (highlightedIndex !== -1 || caretAtStart)) {+ e.preventDefault();+ highlightAt(+ highlightedIndex === -1 ? value.length - 1 : Math.max(0, highlightedIndex - 1),+ );+ return;+ }+ if (e.key === 'ArrowRight' && highlightedIndex !== -1) {+ e.preventDefault();+ // Past the last entry the highlight drops and the caret is live.+ highlightAt(highlightedIndex === value.length - 1 ? null : highlightedIndex + 1);+ return;+ }+ if ((e.key === 'Home' || e.key === 'End') && highlightedIndex !== -1) {+ e.preventDefault();+ highlightAt(e.key === 'Home' ? 0 : value.length - 1);+ return;+ }+ }+ if (highlightedIndex !== -1 && editingEntry === null) {+ // Space activates like Enter (roving-item convention). preventDefault+ // stops the space from being typed into the draft — a highlighted+ // entry means the input is in navigation mode, not text entry.+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ const entry = value[highlightedIndex];+ if (entry !== undefined) beginEdit(entry);+ return;+ }+ if (e.key === 'Backspace' || e.key === 'Delete') {+ e.preventDefault();+ // Neighbours are captured by value: the indices shift under the+ // removal, the values do not.+ const before = value[highlightedIndex - 1] ?? null;+ const after = value[highlightedIndex + 1] ?? null;+ removeAt(highlightedIndex);+ setHighlightedEntry(e.key === 'Backspace' ? (before ?? after) : (after ?? before));+ return;+ }+ }if (e.key === 'Enter') {- if (draft.trim()) {+ if (draft.trim() || editingEntry !== null) {e.preventDefault();addTag(draft);}@@ -197,20 +375,43 @@ function TagPillInput({addTag(draft);}// Empty draft: let default Tab focus-shift behavior run.- } else if (e.key === 'Backspace' && draft === '' && value.length > 0) {+ } else if (+ e.key === 'Backspace' &&+ draft === '' &&+ value.length > 0 &&+ // Mid-edit the box is empty because the author cleared it, not+ // because there is nothing to commit — don't also eat a pill.+ editingEntry === null+ ) {e.preventDefault();removeAt(value.length - 1);} else if (e.key === 'Escape') {- // Esc clears any in-flight rejection state without committing —- // matches the PropertyWidgets ListWidget pattern.- if (draftRejected) {+ // Esc abandons an in-flight edit (the pill returns untouched),+ // drops the highlight, and otherwise clears rejection state+ // without committing — matches the PropertyWidgets ListWidget.+ if (editingEntry !== null || draftRejected) {+ e.preventDefault();+ clearDraft();+ setHighlightedEntry(null);+ } else if (highlightedIndex !== -1) {+ // Highlight-only Escape drops the selection and leaves the draft+ // alone — the author was navigating, not editing.e.preventDefault();- setDraftRejected(false);+ setHighlightedEntry(null);}}}}onBlur={() => {- if (draft.trim()) addTag(draft);+ // An emptied edit box still commits, since that is the delete+ // gesture; an empty add box has nothing to do.+ if (draft.trim() || editingEntry !== null) {+ // A grammar rejection commits nothing. Focus has already left, so+ // the edit is abandoned and the entry returns to the row — leaving+ // `editingEntry` set would keep filtering it out of the render+ // while `value` still holds it, hiding it entirely.+ if (!addTag(draft) && editingEntry !== null) clearDraft();+ }+ setHighlightedEntry(null);onBlur?.();}}placeholder={value.length === 0 ? resolvedPlaceholder : ''}@@ -227,6 +428,9 @@ function TagPillInput({// Either the RHF-bound `ariaInvalid` or the grammar-gate flag// surfaces destructive affordances on the wrapper + input.aria-invalid={draftRejected ? 'true' : ariaInvalid}+ aria-activedescendant={+ highlightedIndex === -1 ? undefined : `${pillIdBase}-${highlightedIndex}`+ }disabled={disabled}className={cn('min-w-[8ch] flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed',diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 7f85f99c5..5dc94a198 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -1421,6 +1421,7 @@"NeQ_0G": ["Work through these comments"],"NgZwB0": [["enabledCount"], "/", ["0"], " on"],"NjrIak": ["File: <0>", ["fixedName"], ".md</0>"],+ "NkNfSr": ["Edit ", ["tag"]],"NkXEFS": ["Restore failed — document unchanged"],"NmPNJJ": ["Copy code"],"Nn4GgW": ["Will be created as <0>", ["sanitizedName"], "</0>"],@@ -3484,6 +3485,7 @@"vF68cg": ["Fields"],"vGQxBT": ["Updates from the source apply automatically (unless edited locally)"],"vGeNNQ": ["Copy a prompt and paste it into your agent to set up your project."],+ "vHlhDc": ["Double-click to edit"],"vIxrEk": ["Fit width"],"vLyv1R": ["Hide"],"vPF04k": ["Start a new chat"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex b39430f18..14eca36a2 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -3854,6 +3854,10 @@ msgstr "Done"msgid "Done."msgstr "Done."+#: src/components/ui/tag-pill-input.tsx+msgid "Double-click to edit"+msgstr "Double-click to edit"+#. placeholder {0}: item.displayName#: src/components/acp/ThreadView.tsxmsgid "Download {0}"@@ -3977,6 +3981,10 @@ msgstr "Edit {0} source"msgid "Edit {keyName}"msgstr "Edit {keyName}"+#: src/components/ui/tag-pill-input.tsx+msgid "Edit {tag}"+msgstr "Edit {tag}"+#: src/components/SkillPreviewTab.tsxmsgid "Edit a copy"msgstr "Edit a copy"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex e9a410097..337953fc6 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -1421,6 +1421,7 @@"NeQ_0G": ["Ŵōŕķ ţĥŕōũĝĥ ţĥēśē ćōḿḿēńţś"],"NgZwB0": [["enabledCount"], "/", ["0"], " ōń"],"NjrIak": ["Ƒĩĺē: <0>", ["fixedName"], ".ḿď</0>"],+ "NkNfSr": ["Ēďĩţ ", ["tag"]],"NkXEFS": ["Ŕēśţōŕē ƒàĩĺēď — ďōćũḿēńţ ũńćĥàńĝēď"],"NmPNJJ": ["Ćōƥŷ ćōďē"],"Nn4GgW": ["Ŵĩĺĺ ƀē ćŕēàţēď àś <0>", ["sanitizedName"], "</0>"],@@ -3484,6 +3485,7 @@"vF68cg": ["Ƒĩēĺďś"],"vGQxBT": ["Ũƥďàţēś ƒŕōḿ ţĥē śōũŕćē àƥƥĺŷ àũţōḿàţĩćàĺĺŷ (ũńĺēśś ēďĩţēď ĺōćàĺĺŷ)"],"vGeNNQ": ["Ćōƥŷ à ƥŕōḿƥţ àńď ƥàśţē ĩţ ĩńţō ŷōũŕ àĝēńţ ţō śēţ ũƥ ŷōũŕ ƥŕōĴēćţ."],+ "vHlhDc": ["Ďōũƀĺē-ćĺĩćķ ţō ēďĩţ"],"vIxrEk": ["Ƒĩţ ŵĩďţĥ"],"vLyv1R": ["Ĥĩďē"],"vPF04k": ["Śţàŕţ à ńēŵ ćĥàţ"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex fed329ddf..e33c4e52e 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -3850,6 +3850,10 @@ msgstr ""msgid "Done."msgstr ""+#: src/components/ui/tag-pill-input.tsx+msgid "Double-click to edit"+msgstr ""+#. placeholder {0}: item.displayName#: src/components/acp/ThreadView.tsxmsgid "Download {0}"@@ -3973,6 +3977,10 @@ msgstr ""msgid "Edit {keyName}"msgstr ""+#: src/components/ui/tag-pill-input.tsx+msgid "Edit {tag}"+msgstr ""+#: src/components/SkillPreviewTab.tsxmsgid "Edit a copy"msgstr ""