diff --git a/src/app/settings/DictationSetting.tsx b/src/app/settings/DictationSetting.tsx index 7f3f8d30..e5575fd2 100644 --- a/src/app/settings/DictationSetting.tsx +++ b/src/app/settings/DictationSetting.tsx @@ -35,12 +35,13 @@ const TIER_LABELS = { /** Characters of the pinned commit shown; the whole hash is in the tooltip. */ const REVISION_CHARS_SHOWN = 7; -export function DictationSetting() { +/** `projectPath`: the project open in this window, whose component names the word list suggests; none on the welcome screen. */ +export function DictationSetting({ projectPath }: { readonly projectPath: string | undefined }) { const store = useVoiceEnvironment().whisper?.store; - return store === undefined ? undefined : ; + return store === undefined ? undefined : ; } -function DictationRows({ store }: { readonly store: DictationStore }) { +function DictationRows({ store, projectPath }: { readonly store: DictationStore; readonly projectPath: string | undefined }) { const translate = useTranslate(); const { formatBytes } = useFormat(); const snapshot = useSyncExternalStore(store.subscribe, store.snapshot); @@ -129,7 +130,7 @@ function DictationRows({ store }: { readonly store: DictationStore }) { onChange={store.setLanguage} /> - + ); } diff --git a/src/app/settings/DictationWords.tsx b/src/app/settings/DictationWords.tsx index b1cba77d..0a485f60 100644 --- a/src/app/settings/DictationWords.tsx +++ b/src/app/settings/DictationWords.tsx @@ -13,7 +13,7 @@ import { type VocabularyEntry, } from '../../../shared/properties/voice/dictationVocabulary'; import { normalizeWords } from '../../../shared/properties/voice/dictationVocabulary'; -import { mentionCandidates } from '../../features/ai/aiStore'; +import { aiMentions } from '../../features/ai/aiBridge'; import { useTranslate } from '../../lib/i18n/useTranslate'; import { confirmDialog } from '../../ui/ConfirmDialog'; import { CloseIcon, PencilIcon, PlusIcon, TrashIcon } from '../../ui/Icons'; @@ -25,12 +25,21 @@ import { SettingsEmpty, SettingsRow } from './SettingsLayout'; /** Project names offered as vocabulary at once. */ const SUGGESTIONS_MAX = 12; -export function DictationWordsRows({ words, onChange }: { readonly words: DictationWords; readonly onChange: (words: DictationWords) => void }) { +export function DictationWordsRows({ + words, + projectPath, + onChange, +}: { + readonly words: DictationWords; + /** The project open in this window, whose component names are suggested; none on the welcome screen. */ + readonly projectPath: string | undefined; + readonly onChange: (words: DictationWords) => void; +}) { const translate = useTranslate(); const [wordOpen, setWordOpen] = useState(false); const [snippetEdit, setSnippetEdit] = useState<{ readonly kind: 'new' } | { readonly kind: 'edit'; readonly snippet: Snippet } | undefined>(undefined); const [search, setSearch] = useState(''); - const suggestions = useProjectNames(words.vocabulary); + const suggestions = useProjectNames(projectPath, words.vocabulary); const addWord = (entry: VocabularyEntry): void => onChange({ ...words, vocabulary: [...words.vocabulary, entry] }); const shown = words.snippets.filter((snippet) => { const query = normalizeWords(search); @@ -164,11 +173,17 @@ export function DictationWordsRows({ words, onChange }: { readonly words: Dictat } // The open project's component names (PascalCase file names), as vocabulary suggestions; none without a project. -function useProjectNames(vocabulary: readonly VocabularyEntry[]): readonly string[] { +// The files are asked of the main process for the project Settings names, not through the AI panel's store: that +// store learns a project only when the panel opens, and asking it before then asserted and took Settings down. +function useProjectNames(projectPath: string | undefined, vocabulary: readonly VocabularyEntry[]): readonly string[] { const [names, setNames] = useState([]); useEffect(() => { + setNames([]); // Another project, or none: the last one's names are not this one's. + if (projectPath === undefined) { + return undefined; + } let live = true; - mentionCandidates('', ['file']) + aiMentions({ projectPath, query: '', kinds: ['file'] }) .then((reply) => { if (!live || !reply.ok) { return; @@ -182,11 +197,11 @@ function useProjectNames(vocabulary: readonly VocabularyEntry[]): readonly strin }); setNames([...new Set(found)]); }) - .catch(() => undefined); + .catch(() => undefined); // Suggestions are a convenience: a failed read leaves none, and the words stay editable. return () => { live = false; }; - }, []); + }, [projectPath]); return useMemo(() => { const known = new Set(vocabulary.map((entry) => entry.word.toLowerCase())); return names.filter((name) => !known.has(name.toLowerCase())).slice(0, SUGGESTIONS_MAX); diff --git a/src/app/settings/Settings.tsx b/src/app/settings/Settings.tsx index ba0156f3..c5b1ac27 100644 --- a/src/app/settings/Settings.tsx +++ b/src/app/settings/Settings.tsx @@ -232,7 +232,7 @@ function SettingsPanel(props: Props & { readonly tab: SettingsTab; readonly onCl const icon = ; switch (props.tab) { case 'editor': - return ; + return ; case 'folders': return props.projectPath ? ( - + Editor > Dictation's word list never takes Settings down, with or without a project, whether or not +// the AI panel has been opened. Its project-name suggestions used to come from the AI panel's store, which learns a +// project only when the panel opens; asking it before then asserted ("aiStore: a project is loaded before the panel +// acts in it") and crashed Settings for anyone who had not opened the AI panel yet, and from the welcome screen. +// Method: the real DictationWordsRows, bundled with esbuild, is mounted in jsdom while the AI store holds no project +// (the crash's condition: nothing here opens the panel). The main process is a stub of `window.avb.aiMentions` that +// records each request and answers with a chosen reply. Checked: no project asks nothing and shows nothing; a project +// asks for its own files and suggests its component names the person does not have yet; a failed or thrown read shows +// nothing and crashes nothing; another project replaces the last one's names. A source check pins that the word list +// no longer reaches into the AI store. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const esbuild = require('esbuild'); +const { JSDOM } = require('jsdom'); +const { ROOT, repoPath } = require('../../helpers/sources.js'); +const { waitFor, waitForSteady } = require('../../helpers/waitFor.js'); + +const directory = repoPath('node_modules/.stacki-test/dictation-words'); +fs.mkdirSync(directory, { recursive: true }); +esbuild.buildSync({ + stdin: { + contents: "export { DictationWordsRows } from './src/app/settings/DictationWords.tsx';", + resolveDir: ROOT, + loader: 'jsx', + }, + outfile: path.join(directory, 'words.js'), + bundle: true, + format: 'cjs', + platform: 'node', + external: ['react', 'react-dom', 'react-dom/client', 'react/jsx-runtime'], + loader: { '.css': 'empty' }, + logLevel: 'silent', +}); + +const WORDS = { vocabulary: [{ word: 'Logo' }], snippets: [] }; +const FILES = [ + { kind: 'file', path: 'src/components/HeroCard.astro', name: 'HeroCard.astro' }, + { kind: 'file', path: 'src/components/Logo.astro', name: 'Logo.astro' }, // Already in the vocabulary. + { kind: 'file', path: 'src/components/Abc.astro', name: 'Abc.astro' }, // Too short to be worth suggesting. + { kind: 'file', path: 'src/pages/index.astro', name: 'index.astro' }, // Not a component name. +]; + +function installDOM(answer) { + const dom = new JSDOM('
', { url: 'http://localhost/', pretendToBeVisual: true }); + const { window } = dom; + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'CustomEvent', 'KeyboardEvent']) { + global[key] = key === 'window' ? window : window[key]; + } + global.requestAnimationFrame = (callback) => setTimeout(callback, 0); + global.cancelAnimationFrame = clearTimeout; + global.IS_REACT_ACT_ENVIRONMENT = true; + const asked = []; + window.avb = { + aiMentions: async (payload) => { + asked.push(payload); + return answer(payload); + }, + }; + return { dom, asked }; +} + +async function mount(projectPath, answer) { + const { dom, asked } = installDOM(answer); + const React = require('react'); + const { act } = React; + const { createRoot } = require('react-dom/client'); + const { DictationWordsRows } = require(path.join(directory, 'words.js')); + const root = createRoot(document.getElementById('root')); + const render = async (nextPath) => { + await act(async () => { + root.render(React.createElement(DictationWordsRows, { words: WORDS, projectPath: nextPath, onChange() {} })); + }); + }; + const suggestions = () => [...document.querySelectorAll('.dictation-words-suggestion')].map((button) => button.textContent.trim()); + await render(projectPath); + return { + asked, + render, + // The reply lands after the render, so each check waits on the suggestions it reads rather than on a guessed delay. + suggestionsBecome: (expected) => + waitFor({ what: `suggestions ${JSON.stringify(expected)}`, read: suggestions, until: (names) => JSON.stringify(names) === JSON.stringify(expected) }), + // An empty list is also the state before any reply, so "none" must hold steady, not merely be seen once. + suggestionsStayEmpty: () => waitForSteady({ what: 'no suggestions', read: suggestions, until: (names) => names.length === 0 }), + asksBecome: (count) => waitFor({ what: `${count} file request(s)`, read: () => asked.length, until: (length) => length === count }), + close: async () => { + await act(async () => root.unmount()); + dom.window.close(); + }, + }; +} + +test('the word list reads project files through the main process, not through the AI panel’s store', () => { + const source = fs.readFileSync(repoPath('src/app/settings/DictationWords.tsx'), 'utf8'); + assert.doesNotMatch(source, /features\/ai\/aiStore/, 'Settings never depends on the AI panel having opened'); + assert.match(source, /aiMentions\(\{ projectPath, query: '', kinds: \['file'\] \}\)/); + const settings = fs.readFileSync(repoPath('src/app/settings/Settings.tsx'), 'utf8'); + assert.match(settings, //, 'Settings passes its own open project'); +}); + +test('with no project open (the welcome screen), the list renders, asks nothing and suggests nothing', async (context) => { + const view = await mount(undefined, () => ({ ok: true, value: FILES })); + context.after(view.close); + await view.suggestionsStayEmpty(); + assert.deepEqual(view.asked, []); +}); + +test('with a project open and the AI panel never opened, the list suggests that project’s new component names', async (context) => { + const view = await mount('/work/site', () => ({ ok: true, value: FILES })); + context.after(view.close); + await view.suggestionsBecome(['HeroCard']); + assert.equal(view.asked.length, 1); + assert.equal(view.asked[0].projectPath, '/work/site'); + assert.equal(view.asked[0].query, ''); + assert.deepEqual([...view.asked[0].kinds], ['file']); +}); + +test('a failed or thrown read leaves no suggestions and no crash', async (context) => { + const failed = await mount('/work/site', () => ({ ok: false, error: { code: 'agent-failed', message: 'the project could not be read' } })); + context.after(failed.close); + await failed.asksBecome(1); + await failed.suggestionsStayEmpty(); + const thrown = await mount('/work/site', () => { + throw new Error('main went away'); + }); + context.after(thrown.close); + await thrown.asksBecome(1); + await thrown.suggestionsStayEmpty(); +}); + +test('another project replaces the last one’s names, and closing the project clears them', async (context) => { + const view = await mount('/work/site', ({ projectPath }) => ({ + ok: true, + value: projectPath === '/work/site' ? FILES : [{ kind: 'file', path: 'src/components/PriceTable.astro', name: 'PriceTable.astro' }], + })); + context.after(view.close); + await view.suggestionsBecome(['HeroCard']); + await view.render('/work/shop'); + await view.suggestionsBecome(['PriceTable']); + assert.equal(view.asked.at(-1).projectPath, '/work/shop'); + await view.render(undefined); + await view.suggestionsStayEmpty(); + assert.equal(view.asked.length, 2, 'closing the project asks nothing more'); +});