Open History to see the last commit
1import { tmpdir } from 'node:os'
2import * as nodePath from 'node:path'
3import { describe, expect, it, vi } from 'vitest'
4import { memoryPersistence } from '@tanstack/ai-persistence'
5import { createHarnessHost, defineHarness, definePlugin } from '../src'
6import { workspaceTools } from '../src/first-party/coding'
7import {
8 listSavedPermissions,
9 permissions,
10} from '../src/first-party/permissions'
11import {
12 FormatFailed,
13 formatter,
14 projectFormatters,
15} from '../src/first-party/coding/formatter'
16import { FileChanged, FormatterRewrote } from '../src/first-party/coding/events'
17import { mockAdapter, questionsOf, text, toolCall } from './helpers'
18import type { HarnessSession } from '../src'
19import type { PluginEvent } from '../src/extensions'
20import type { PermissionRule } from '../src/first-party/permissions'
21import type { WorkspaceBackend } from '../src/first-party/coding/backend'
22import type {
23 FormatFailure,
24 Formatter,
25 FormatterOptions,
26} from '../src/first-party/coding/formatter'
27
28// Coverage runs in CI are slow, so polled checks wait up to 5 s.
29const waitFor = <T>(
30 check: () => T | Promise<T>,
31 options?: { timeout?: number; interval?: number },
32) => vi.waitFor(check, { timeout: 5_000, ...options })
33
34const { join, posix, resolve } = nodePath
35const root = resolve(tmpdir(), 'harness-format')
36const encoder = new TextEncoder()
37const decoder = new TextDecoder()
38
39type Exec = (command: string) => Awaited<ReturnType<WorkspaceBackend['exec']>>
40
41const ok: Exec = () => ({ exitCode: 0, stdout: '', stderr: '' })
42
43/** `path` from the root, as the fake POSIX shell gets it. */
44const quoted = (path: string) => `'${join(root, path)}'`
45
46/**
47 * A project in memory that starts as `files`, by path from its root. `exec`
48 * answers each command. `runs` lists each command with its options. With
49 * `shell: 'sh'`, the project is at `/workspace` with POSIX paths, like a
50 * Linux sandbox. Else it is at `root` on this machine.
51 */
52function project(files: Record<string, string>, exec: Exec = ok, shell?: 'sh') {
53 const paths = shell === 'sh' ? posix : nodePath
54 const base = shell === 'sh' ? '/workspace' : root
55 const store = new Map<string, Uint8Array>()
56 const put = (path: string, content: string) =>
57 store.set(paths.join(base, path), encoder.encode(content))
58 for (const [path, content] of Object.entries(files)) put(path, content)
59 const runs: Array<{ command: string; cwd?: string; timeoutMs?: number }> = []
60 const backend: WorkspaceBackend = {
61 shell,
62 readFile: async (path) => {
63 const data = store.get(path)
64 if (!data) throw new Error(`No file ${path}`)
65 return data
66 },
67 writeFile: async (path, data) => {
68 store.set(path, typeof data === 'string' ? encoder.encode(data) : data)
69 },
70 stat: async (path) => {
71 const data = store.get(path)
72 return data && { type: 'file', size: data.length, mtimeMs: 0 }
73 },
74 // No links: each path is its own real path.
75 realpath: async (path) => path,
76 readdir: async (dir) =>
77 [...store.keys()]
78 .filter((path) => paths.dirname(path) === dir)
79 .map((path) => ({ name: paths.basename(path), type: 'file' as const })),
80 exec: async (command, options) => {
81 runs.push({ command, cwd: options?.cwd, timeoutMs: options?.timeoutMs })
82 return exec(command)
83 },
84 }
85 const read = (path: string) =>
86 decoder.decode(store.get(paths.join(base, path)))
87 return { backend, runs, put, read }
88}
89
90/** Run the hook once for `path` in a project of `files`. */
91async function formatIn(
92 files: Record<string, string>,
93 path: string,
94 options: Omit<FormatterOptions, 'root' | 'backend'> = {},
95 exec: Exec = ok,
96) {
97 const { backend, runs } = project(files, exec)
98 const failures: Array<FormatFailure> = []
99 const { afterWrite } = projectFormatters(
100 { root, backend, ...options },
101 { onFailure: (failure) => failures.push(failure) },
102 )
103 await afterWrite(join(root, path))
104 return { runs, commands: runs.map((run) => run.command), failures }
105}
106
107const prettier = { '.prettierrc': '{}' }
108const mine: Formatter = {
109 name: 'mine',
110 extensions: ['.ts'],
111 command: (file) => `mine ${file}`,
112}
113
114describe('projectFormatters', () => {
115 it.each([
116 ['.prettierrc', prettier, 'a.ts', 'npx --no-install prettier --write'],
117 [
118 'prettier.config.js',
119 { 'prettier.config.js': '' },
120 'a.css',
121 'npx --no-install prettier --write',
122 ],
123 [
124 'a prettier key in package.json',
125 { 'package.json': '{"prettier": {}}' },
126 'a.md',
127 'npx --no-install prettier --write',
128 ],
129 [
130 'biome.json',
131 { 'biome.json': '{}' },
132 'a.tsx',
133 'npx --no-install biome format --write',
134 ],
135 [
136 '.oxfmtrc.json',
137 { '.oxfmtrc.json': '{}' },
138 'a.ts',
139 'npx --no-install oxfmt',
140 ],
141 [
142 'oxfmt in devDependencies',
143 { 'package.json': '{"devDependencies": {"oxfmt": "^0.59.0"}}' },
144 'a.json',
145 'npx --no-install oxfmt',
146 ],
147 ['ruff.toml', { 'ruff.toml': '' }, 'a.py', 'ruff format'],
148 [
149 '[tool.ruff] in pyproject.toml',
150 { 'pyproject.toml': '[tool.ruff]\nline-length = 88\n' },
151 'a.py',
152 'ruff format',
153 ],
154 ['go.mod', { 'go.mod': 'module a\n' }, 'main.go', 'gofmt -w'],
155 ['Cargo.toml', { 'Cargo.toml': '' }, 'src/main.rs', 'rustfmt'],
156 ])(
157 'detects %s and runs its command in the root',
158 async (_, files, path, command) => {
159 const { runs } = await formatIn(files, path)
160 expect(runs).toEqual([
161 { command: `${command} ${quoted(path)}`, cwd: root, timeoutMs: 20_000 },
162 ])
163 },
164 )
165
166 it.each([
167 ['no config file', {}, 'a.ts'],
168 [
169 'a pyproject.toml without ruff',
170 { 'pyproject.toml': '[project]\n' },
171 'a.py',
172 ],
173 ['a file type no formatter takes', { 'go.mod': 'module a\n' }, 'a.ts'],
174 ['a package.json that is not JSON', { 'package.json': '{' }, 'a.ts'],
175 ])('runs nothing for %s', async (_, files, path) => {
176 expect(await formatIn(files, path)).toEqual({
177 runs: [],
178 commands: [],
179 failures: [],
180 })
181 })
182
183 it('quotes the path, so a space and a & stay in one argument', async () => {
184 const { commands } = await formatIn(prettier, 'src/my file & co.ts')
185 expect(commands).toEqual([
186 `npx --no-install prettier --write '${join(root, 'src', 'my file & co.ts')}'`,
187 ])
188 })
189
190 it('runs a user formatter before the built-in one', async () => {
191 const { commands } = await formatIn(prettier, 'a.ts', {
192 formatters: [mine],
193 })
194 expect(commands).toEqual([`mine ${quoted('a.ts')}`])
195 })
196
197 it('reads the root files for when, and skips a formatter that says no', async () => {
198 const taplo: Formatter = {
199 name: 'taplo',
200 extensions: ['.toml'],
201 command: (file) => `taplo fmt ${file}`,
202 when: async (project) =>
203 (await project.read('taplo.toml')).includes('[formatting]'),
204 }
205 const used = await formatIn({ 'taplo.toml': '[formatting]\n' }, 'a.toml', {
206 formatters: [taplo],
207 })
208 const skipped = await formatIn({}, 'a.toml', { formatters: [taplo] })
209 expect(used.commands).toEqual([`taplo fmt ${quoted('a.toml')}`])
210 expect(skipped.commands).toEqual([])
211 })
212
213 it('keeps POSIX paths in a sandbox, also on a Windows host', async () => {
214 const { backend, runs } = project(prettier, ok, 'sh')
215 const { afterWrite } = projectFormatters(
216 { root: '/workspace', backend },
217 { onFailure: () => undefined },
218 )
219 await afterWrite('/workspace/src/a.ts')
220 expect(runs).toEqual([
221 {
222 command: `npx --no-install prettier --write '/workspace/src/a.ts'`,
223 cwd: '/workspace',
224 timeoutMs: 20_000,
225 },
226 ])
227 })
228
229 it('runs no built-in formatter with builtins: false', async () => {
230 const { commands } = await formatIn(prettier, 'a.ts', { builtins: false })
231 expect(commands).toEqual([])
232 })
233
234 it('checks the project again at the next write when the check failed', async () => {
235 const { backend, runs } = project(prettier)
236 const readdir = backend.readdir
237 let fail = true
238 backend.readdir = async (dir) => {
239 if (fail) throw new Error('EBUSY')
240 return readdir(dir)
241 }
242 const failures: Array<FormatFailure> = []
243 const { afterWrite } = projectFormatters(
244 { root, backend },
245 { onFailure: (failure) => failures.push(failure) },
246 )
247 await afterWrite(join(root, 'a.ts'))
248 fail = false
249 await afterWrite(join(root, 'a.ts'))
250 expect(failures).toEqual([{ path: join(root, 'a.ts'), message: 'EBUSY' }])
251 expect(runs).toHaveLength(1)
252 })
253
254 it('checks the config files once, at the first write', async () => {
255 const { backend, runs, put } = project({})
256 const { afterWrite } = projectFormatters(
257 { root, backend },
258 { onFailure: () => undefined },
259 )
260 await afterWrite(join(root, 'a.ts'))
261 put('.prettierrc', '{}')
262 await afterWrite(join(root, 'a.ts'))
263 expect(runs).toEqual([])
264 })
265
266 it.each([
267 [
268 'a non-zero exit, with the first stderr line',
269 { exitCode: 2, stdout: '', stderr: '[error] a.ts: SyntaxError\nat 1:1' },
270 'prettier failed: [error] a.ts: SyntaxError',
271 ],
272 [
273 'a missing formatter, with the exit code',
274 { exitCode: 127, stdout: '', stderr: '' },
275 'prettier failed: exit code 127',
276 ],
277 [
278 'a timeout',
279 { exitCode: 124, stdout: '', stderr: '' },
280 'prettier failed: it took longer than 5 seconds',
281 ],
282 ])('reports %s, and does not throw', async (_, result, message) => {
283 const { runs, failures } = await formatIn(
284 prettier,
285 'a.ts',
286 { timeoutMs: 5000 },
287 () => result,
288 )
289 expect(runs[0]?.timeoutMs).toBe(5000)
290 expect(failures).toEqual([{ path: join(root, 'a.ts'), message }])
291 })
292
293 it.each([
294 [
295 'changed',
296 'let a = 1\n',
297 [{ path: join(root, 'a.ts'), formatter: 'prettier' }],
298 ],
299 ['kept', 'let a=1', []],
300 ])(
301 'reports a rewrite only when the formatter changed the file (%s)',
302 async (_, formatted, expected) => {
303 // The fake prettier writes `formatted` to the file.
304 const files = project({ ...prettier, 'a.ts': 'let a=1' }, () => {
305 files.put('a.ts', formatted)
306 return { exitCode: 0, stdout: '', stderr: '' }
307 })
308 const rewrites: Array<{ path: string; formatter: string }> = []
309 const { afterWrite } = projectFormatters(
310 { root, backend: files.backend },
311 {
312 onFailure: () => undefined,
313 onRewrite: (rewrite) => rewrites.push(rewrite),
314 },
315 )
316 await afterWrite(join(root, 'a.ts'))
317 expect(rewrites).toEqual(expected)
318 },
319 )
320
321 it('reports a backend that throws, and does not throw', async () => {
322 const { failures } = await formatIn(prettier, 'a.ts', {}, () => {
323 throw new Error('spawn sh ENOENT')
324 })
325 expect(failures).toEqual([
326 { path: join(root, 'a.ts'), message: 'spawn sh ENOENT' },
327 ])
328 })
329})
330
331describe('formatter', () => {
332 it('formats after write_file and edit_file, and a failure keeps the file and the tool result', async () => {
333 const { backend, runs, read } = project(prettier, () => ({
334 exitCode: 2,
335 stdout: '',
336 stderr: 'SyntaxError',
337 }))
338 const failures: Array<FormatFailure> = []
339 const listener = definePlugin({
340 name: 'test/listener',
341 setup: (ctx) => {
342 ctx.on(FormatFailed, (failure) => failures.push(failure))
343 },
344 })
345 const { adapter, calls } = mockAdapter([
346 () => toolCall('write_file', { path: 'a.ts', content: 'let a=1' }, 'c1'),
347 () =>
348 toolCall('edit_file', { path: 'a.ts', old: 'a=1', new: 'a=2' }, 'c2'),
349 () => text('done'),
350 ])
351 const host = createHarnessHost({ persistence: memoryPersistence() })
352 const session = await host.open(
353 defineHarness({
354 name: 'test/formatter',
355 adapter,
356 plugins: () => [
357 workspaceTools({ root, backend }),
358 formatter({ root, backend }),
359 listener,
360 ],
361 }),
362 {
363 threadId: 't',
364 },
365 )
366
367 await session.send('work')
368 await host.close()
369
370 const command = `npx --no-install prettier --write ${quoted('a.ts')}`
371 const failure = {
372 path: join(root, 'a.ts'),
373 message: 'prettier failed: SyntaxError',
374 }
375 expect(runs.map((run) => run.command)).toEqual([command, command])
376 expect(failures).toEqual([failure, failure])
377 expect(read('a.ts')).toBe('let a=2')
378 expect(JSON.stringify(calls[2].messages)).toContain(
379 'Edited a.ts (1 change).',
380 )
381 })
382})
383
384describe('formatter with a workspace for each thread', () => {
385 it('runs in the workspace that bind gave the thread, also with permissions()', async () => {
386 // A Linux sandbox at /workspace, with a prettier config.
387 const { backend, runs } = project(prettier, ok, 'sh')
388 const { adapter } = mockAdapter([
389 () => toolCall('write_file', { path: 'a.ts', content: 'let a=1' }, 'c1'),
390 () => text('done'),
391 ])
392 const host = createHarnessHost({ persistence: memoryPersistence() })
393 const session = await host.open(
394 defineHarness({
395 name: 'test/formatter-bind',
396 adapter,
397 plugins: () => [
398 permissions({ rules: [{ tool: 'formatter:*', decision: 'allow' }] }),
399 workspaceTools({
400 workspace: {
401 bind: async () => ({ ...backend, root: '/workspace' }),
402 },
403 }),
404 formatter({}),
405 ],
406 }),
407 { threadId: 't' },
408 )
409 // Not bypass: the rules check the formatter of the call before it runs.
410 await session.runCommand({ name: 'mode', input: 'acceptEdits' })
411
412 await session.send('write it')
413 expect(session.snapshot().pendingWaits).toEqual([])
414 await host.close()
415
416 expect(runs).toEqual([
417 {
418 command: `npx --no-install prettier --write '/workspace/a.ts'`,
419 cwd: '/workspace',
420 timeoutMs: 20_000,
421 },
422 ])
423 })
424})
425
426describe('formatter events', () => {
427 /**
428 * A session writes `let a=1` to `a.ts`, and a fake prettier puts spaces
429 * around `=`. Resolves to the values of `event` that a plugin got, and
430 * the file at the end.
431 */
432 async function writeAndFormat<T>(event: PluginEvent<T>) {
433 const files = project(prettier, () => {
434 files.put('a.ts', files.read('a.ts').replace('=', ' = '))
435 return { exitCode: 0, stdout: '', stderr: '' }
436 })
437 const values: Array<T> = []
438 const listener = definePlugin({
439 name: 'test/listener',
440 setup: (ctx) => {
441 ctx.on(event, (value) => values.push(value))
442 },
443 })
444 const { adapter } = mockAdapter([
445 () => toolCall('write_file', { path: 'a.ts', content: 'let a=1' }, 'c1'),
446 () => text('done'),
447 ])
448 const host = createHarnessHost({ persistence: memoryPersistence() })
449 const session = await host.open(
450 defineHarness({
451 name: 'test/formatter-events',
452 adapter,
453 plugins: () => [
454 workspaceTools({ root, backend: files.backend }),
455 formatter({ root, backend: files.backend }),
456 listener,
457 ],
458 }),
459 { threadId: 't' },
460 )
461
462 await session.send('work')
463 await host.close()
464 return { values, file: files.read('a.ts') }
465 }
466
467 it('sends tanstack/formatter:rewrote when the formatter changed the written file', async () => {
468 const { values, file } = await writeAndFormat(FormatterRewrote)
469 expect(file).toBe('let a = 1')
470 expect(values).toEqual([
471 { path: join(root, 'a.ts'), formatter: 'prettier' },
472 ])
473 })
474
475 it('sends FileChanged after the formatter, so the patch has the formatted text', async () => {
476 const { values } = await writeAndFormat(FileChanged)
477 expect(values).toEqual([
478 {
479 path: join(root, 'a.ts'),
480 change: 'created',
481 patch: [
482 'diff --git a/a.ts b/a.ts',
483 'new file mode 100644',
484 '--- /dev/null',
485 '+++ b/a.ts',
486 '@@ -0,0 +1 @@',
487 '+let a = 1',
488 '\\ No newline at end of file',
489 '',
490 ].join('\n'),
491 additions: 1,
492 deletions: 0,
493 toolCallId: 'c1',
494 },
495 ])
496 })
497})
498
499describe('formatter with permissions()', () => {
500 /**
501 * A session with the workspace tools, the formatter, and `permissions()`
502 * in `mode`, in a project of `files`. Each reply writes a file. `runs`
503 * lists the formatter runs.
504 */
505 async function openWith(
506 mode: string,
507 paths: Array<string>,
508 persistence = memoryPersistence(),
509 files: Record<string, string> = {},
510 rules: Array<PermissionRule> = [],
511 /** The start of the tool call ids. A thread needs new ids on each host. */
512 ids = 'c',
513 ) {
514 const { backend, runs } = project(files)
515 const { adapter, calls } = mockAdapter([
516 ...paths.map(
517 (path, index) => () =>
518 toolCall('write_file', { path, content: '' }, `${ids}${index}`),
519 ),
520 () => text('done'),
521 ])
522 const host = createHarnessHost({ persistence })
523 const session = await host.open(
524 defineHarness({
525 name: 'test/formatter-permissions',
526 adapter,
527 plugins: () => [
528 permissions({ root, rules }),
529 workspaceTools({ root, backend }),
530 formatter({ root, backend }),
531 ],
532 }),
533 {
534 threadId: 't',
535 },
536 )
537 await session.runCommand({ name: 'mode', input: mode })
538 return { host, session, runs, calls, backend }
539 }
540
541 /**
542 * Wait for the one open approval of the turn, then answer it, and wait
543 * for the turn that resumes. Returns its message.
544 */
545 async function answer(session: HarnessSession, value: unknown) {
546 await waitFor(
547 () => expect(session.snapshot().pendingWaits).toHaveLength(1),
548 { timeout: 5_000 },
549 )
550 const [wait] = session.snapshot().pendingWaits
551 if (!wait) throw new Error('No approval.')
552 const inputId = `answer:${wait.waitId}`
553 await session.resolve({
554 resume: [
555 { interruptId: wait.waitId, status: 'resolved', payload: value },
556 ],
557 inputId,
558 })
559 await session.settled({ inputId })
560 return wait.message ?? ''
561 }
562
563 it('in acceptEdits, asks before the write of prettier.config.js, for the write and prettier', async () => {
564 const { host, session, runs, calls, backend } = await openWith(
565 'acceptEdits',
566 ['prettier.config.js'],
567 )
568
569 await session.send('change the config')
570 const message = await answer(session, { answer: 'reject' })
571
572 // The approval came before the call: a reject refuses the write too.
573 expect(message).toContain('Allow write_file')
574 expect(runs).toEqual([])
575 expect(await backend.stat(join(root, 'prettier.config.js'))).toBe(undefined)
576 expect(JSON.stringify(calls[1].messages)).toContain(
577 'The user denied this tool call.',
578 )
579 await host.close()
580 })
581
582 it('keeps the write and skips the formatter that a rule denies', async () => {
583 const { host, session, runs, calls } = await openWith(
584 'acceptEdits',
585 ['a.ts'],
586 memoryPersistence(),
587 prettier,
588 [{ tool: 'formatter:prettier', decision: 'deny' }],
589 )
590
591 await session.send('write it')
592
593 expect(session.snapshot().pendingWaits).toEqual([])
594 expect(runs).toEqual([])
595 expect(JSON.stringify(calls[1].messages)).toContain(
596 'Wrote a.ts.\\nThe formatter prettier did not run: it is not allowed.',
597 )
598 await host.close()
599 })
600
601 it('stops asking after an always answer, also in a new session', async () => {
602 const persistence = memoryPersistence()
603 const first = await openWith(
604 'acceptEdits',
605 ['prettier.config.js', 'a.ts'],
606 persistence,
607 )
608 await first.session.send('write twice')
609 await answer(first.session, { answer: 'always' })
610 expect(first.runs.map((run) => run.command)).toEqual([
611 `npx --no-install prettier --write ${quoted('prettier.config.js')}`,
612 `npx --no-install prettier --write ${quoted('a.ts')}`,
613 ])
614 expect(questionsOf(first.session.snapshot())).toHaveLength(0)
615 await first.host.close()
616
617 const second = await openWith('acceptEdits', ['b.ts'], persistence, {
618 'prettier.config.js': '',
619 })
620 await second.session.send('write again')
621 expect(second.runs.map((run) => run.command)).toEqual([
622 `npx --no-install prettier --write ${quoted('b.ts')}`,
623 ])
624 await second.host.close()
625 })
626
627 it('asks again after an always answer when the formatter config changed', async () => {
628 const persistence = memoryPersistence()
629 const first = await openWith('acceptEdits', ['a.ts'], persistence, {
630 'prettier.config.js': 'export default {}',
631 })
632 await first.session.send('write it')
633 await answer(first.session, { answer: 'always' })
634 expect(first.runs).toHaveLength(1)
635 await first.host.close()
636
637 // The config now loads a plugin: its code runs with the formatter.
638 const second = await openWith(
639 'acceptEdits',
640 ['b.ts'],
641 persistence,
642 { 'prettier.config.js': "export default { plugins: ['./evil.js'] }" },
643 [],
644 'second-',
645 )
646 await second.session.send('write again')
647 const message = await answer(second.session, { answer: 'once' })
648 expect(message).toContain('Allow write_file')
649 expect(second.runs.map((run) => run.command)).toEqual([
650 `npx --no-install prettier --write ${quoted('b.ts')}`,
651 ])
652 await second.host.close()
653 })
654
655 it('asks again after an always answer for a write of a config below the root', async () => {
656 const persistence = memoryPersistence()
657 const first = await openWith('acceptEdits', ['a.ts'], persistence, prettier)
658 await first.session.send('write it')
659 await answer(first.session, { answer: 'always' })
660 await first.host.close()
661
662 // Prettier loads the nested config, and runs its code. The root
663 // config did not change.
664 const second = await openWith(
665 'acceptEdits',
666 ['src/prettier.config.js'],
667 persistence,
668 prettier,
669 [],
670 'second-',
671 )
672 await second.session.send('write the nested config')
673 const message = await answer(second.session, { answer: 'once' })
674 expect(message).toContain('Allow write_file')
675 await second.host.close()
676 })
677
678 it('saves no rule for the formatter of a nested config on an always answer', async () => {
679 const persistence = memoryPersistence()
680 const { host, session } = await openWith(
681 'acceptEdits',
682 ['src/prettier.config.js'],
683 persistence,
684 prettier,
685 )
686 await session.send('write the nested config')
687
688 await answer(session, { answer: 'always' })
689
690 const saved = await listSavedPermissions(persistence.stores, root)
691 expect(saved.map((rule) => rule.tool)).toContain('formatter:prettier')
692 expect(saved.some((rule) => rule.tool.includes('@unsaved:'))).toBe(false)
693 await host.close()
694 })
695
696 it('runs with no question in bypass', async () => {
697 const { host, session, runs } = await openWith('bypass', [
698 'prettier.config.js',
699 ])
700 await session.send('change the config')
701 expect(runs.map((run) => run.command)).toEqual([
702 `npx --no-install prettier --write ${quoted('prettier.config.js')}`,
703 ])
704 expect(questionsOf(session.snapshot())).toHaveLength(0)
705 await host.close()
706 })
707
708 it('runs with no question and no note without permissions()', async () => {
709 const { backend, runs } = project({})
710 const { adapter, calls } = mockAdapter([
711 () => toolCall('write_file', { path: 'prettier.config.js', content: '' }),
712 () => text('done'),
713 ])
714 const host = createHarnessHost({ persistence: memoryPersistence() })
715 const session = await host.open(
716 defineHarness({
717 name: 'test/formatter-no-permissions',
718 adapter,
719 plugins: () => [
720 workspaceTools({ root, backend }),
721 formatter({ root, backend }),
722 ],
723 }),
724 {
725 threadId: 't',
726 },
727 )
728 await session.send('change the config')
729 expect(runs.map((run) => run.command)).toEqual([
730 `npx --no-install prettier --write ${quoted('prettier.config.js')}`,
731 ])
732 expect(JSON.stringify(calls[1].messages)).not.toContain('did not run')
733 await host.close()
734 })
735})