Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

plugin-hotpaths.test.ts

157 lines5.2 KB

1import { mkdtemp, rm, utimes, writeFile } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, describe, expect, it, vi } from 'vitest'
5import { memoryPersistence } from '@tanstack/ai-persistence'
6import {
7 createExtensionPoint,
8 createHarnessHost,
9 defineCommand,
10 defineHarness,
11 definePlugin,
12} from '../src'
13import { decidePermission } from '../src/first-party/permissions'
14import { projectInstructions } from '../src/first-party/node'
15import { mockAdapter, text } from './helpers'
16import type { HarnessHost, HarnessPlugin } from '../src'
17import type { PermissionRule } from '../src/first-party/permissions'
18import type * as NodeFs from 'node:fs'
19​
20// The sync calls a turn must not make. They wrap the real ones.
21const sync = vi.hoisted(() => ({
22 statSync: vi.fn(),
23 readFileSync: vi.fn(),
24}))
25vi.mock('node:fs', async (importOriginal) => {
26 const fs = await importOriginal<typeof NodeFs>()
27 sync.statSync.mockImplementation(fs.statSync)
28 sync.readFileSync.mockImplementation(fs.readFileSync)
29 return { ...fs, statSync: sync.statSync, readFileSync: sync.readFileSync }
30})
31​
32const hosts: Array<HarnessHost> = []
33afterEach(async () => {
34 vi.restoreAllMocks()
35 await Promise.all(hosts.splice(0).map((host) => host.close()))
36})
37​
38/** Open a session whose plugin list the test can change before a reload. */
39async function open(plugins: Array<HarnessPlugin>) {
40 const { adapter, calls } = mockAdapter(() => text('ok'))
41 const host = createHarnessHost({ persistence: memoryPersistence() })
42 hosts.push(host)
43 const session = await host.open(
44 defineHarness({
45 name: 'test/hotpaths',
46 adapter,
47 plugins: () => [...plugins],
48 }),
49 { threadId: 't' },
50 )
51 return { session, calls }
53​
54describe('ctx.collect', () => {
55 const Rules = createExtensionPoint<{ tool: string }>('test/hot-rules')
56 const writer = (name: string, tool: string) =>
57 definePlugin({
58 name,
59 setup: () => ({ contribute: [Rules.item({ tool })] }),
60 })
61​
62 it('gives the same array at run time until the contributions change', async () => {
63 let view: ReadonlyArray<{ tool: string }> = []
64 const reader = definePlugin({
65 name: 'test/reader',
66 setup: (ctx) => {
67 view = ctx.collect(Rules)
68 return {
69 commands: {
70 snap: defineCommand({
71 description: 'Collect the rules',
72 run: () => ctx.collect(Rules),
73 }),
74 },
75 }
76 },
77 })
78 const plugins = [reader, writer('test/a', 'bash')]
79 const { session } = await open(plugins)
80​
81 const first = await session.runCommand({ name: 'snap' })
82 const second = await session.runCommand({ name: 'snap' })
83 expect(second).toBe(first)
84 expect(first).toEqual([{ tool: 'bash' }])
85 // The view from setup filled as the later plugin set up.
86 expect([...view]).toEqual([{ tool: 'bash' }])
87​
88 plugins.push(writer('test/b', 'write_file'))
89 await session.reloadPlugins()
90 const changed = await session.runCommand({ name: 'snap' })
91 expect(changed).not.toBe(first)
92 expect(changed).toEqual([{ tool: 'bash' }, { tool: 'write_file' }])
93 })
94})
95​
96describe('permission rule patterns', () => {
97 it('compiles each rule pattern once for many calls', () => {
98 // Patterns no other test uses, so the cache has none of them yet.
99 const rules: Array<PermissionRule> = [
100 { tool: 'bash', decision: 'allow', resource: 'hotpath-tool *' },
101 { tool: 'edit_file', decision: 'allow', resource: 'hotpath/**/*.ts' },
102 ]
103 const call = () => [
104 decidePermission(rules, 'bash', 'default', {
105 resources: { commands: ['hotpath-tool run'] },
106 fallback: 'ask',
107 }),
108 decidePermission(rules, 'edit_file', 'default', {
109 resources: { paths: ['/root/hotpath/src/a.ts'] },
110 root: '/root',
111 fallback: 'ask',
112 }),
113 ]
114 expect(call()).toEqual(['allow', 'allow'])
115​
116 const compiled = vi.spyOn(globalThis, 'RegExp')
117 const results = Array.from({ length: 50 }, call)
118 const compiledCount = compiled.mock.calls.length
119 compiled.mockRestore()
120​
121 expect(compiledCount).toBe(0)
122 expect(new Set(results.map((result) => result.join()))).toEqual(
123 new Set(['allow,allow']),
124 )
125 })
126})
127​
128describe('projectInstructions file checks', () => {
129 let dir = ''
130 afterEach(async () => {
131 await rm(dir, { recursive: true, force: true })
132 })
133​
134 it('finds a changed file with no sync file call in a turn', async () => {
135 dir = await mkdtemp(join(tmpdir(), 'harness-hotpaths-'))
136 const file = join(dir, 'AGENTS.md')
137 await writeFile(file, 'Use tabs.')
138 const { session, calls } = await open([
139 projectInstructions({ root: dir, env: false }),
140 ])
141 sync.statSync.mockClear()
142 sync.readFileSync.mockClear()
143​
144 await session.send('one')
145 await writeFile(file, 'Use spaces.')
146 const later = Date.now() / 1000 + 60
147 await utimes(file, later, later)
148 await session.send('two')
149​
150 expect(calls[1].systemPrompts).toEqual([
151 'Project instructions from AGENTS.md:\nUse tabs.',
152 'Project instructions from AGENTS.md changed. Follow this text instead:\nUse spaces.',
153 ])
154 expect(sync.statSync).not.toHaveBeenCalled()
155 expect(sync.readFileSync).not.toHaveBeenCalled()
156 })
157})