web-agent-presets.e2e.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { fileURLToPath } from 'node:url'
  4. import { dirname, join } from 'node:path'
  5. import { Context } from 'cordis'
  6. import { boot, healProfilesModuleFallback, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot'
  7. import { SessionId } from '@deepseek-ai/dsh-session'
  8. import type { Agent } from '@deepseek-ai/dsh-agent'
  9. import type { PatchOptions } from '@cordisjs/plugin-include'
  10. import { beforeAll, describe, expect, it } from 'vitest'
  11. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  12. import { SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-agent-presets'
  13. import type {} from '@deepseek-ai/dsh-tools'
  14. const CONFIG_DIR = fileURLToPath(new URL('../config/', import.meta.url))
  15. const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
  16. /** The shipped Web surface: the dsh-base and dsh-web-app bundle patches over an empty preset root. */
  17. const BASE_PATCH = join(REPO_ROOT, 'packages/bundle/base/cordis.patch.yml')
  18. const WEB_PATCH = join(REPO_ROOT, 'packages/bundle/web-app/cordis.patch.yml')
  19. /** The installation anchor whose dependency surface the preset module fallback mirrors. */
  20. const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json')
  21. /**
  22. * Boot the shipped Web composition, minus the rows that would bind a port,
  23. * touch the network, or write outside the test. Everything that decides an
  24. * agent's capabilities is the real thing, including both shipped presets.
  25. */
  26. async function bootWeb(settingsFile: string): Promise<Context> {
  27. const patches: PatchOptions[] = [
  28. ...loadOverlayPatches('dsh-test', BASE_PATCH),
  29. ...loadOverlayPatches('dsh-test', WEB_PATCH),
  30. // The settings row defaults to `$DSH_HOME/settings.yaml`. Left alone it
  31. // reads the developer's own document — and since the default preset is a
  32. // setting, a stored `agent-presets.default` would decide this file's
  33. // outcome. Point it at a temp file for the same reason the roster below
  34. // names only the shipped root.
  35. { id: 'settings', config: { path: settingsFile, watch: false } },
  36. // Host rows with side effects outside this process: a bound port, a
  37. // served asset tree, a telemetry exporter.
  38. { id: 'webserver', disabled: true },
  39. // Waits for `httpServer`, which the disabled webserver above provides.
  40. { id: 'web-runtime', disabled: true },
  41. { id: 'telemetry-otel', disabled: true },
  42. { id: 'modules', disabled: true },
  43. { id: 'connection', disabled: true },
  44. // NOT a side-effect row: the api-proxy cannot mount in THIS layer at all,
  45. // because it injects `subagents` and the subagent registry moved into the
  46. // presets here. That is the breakage a later layer returns to the host
  47. // plane; when it does, this line comes out and the boot audit covers the
  48. // whole host-plane injection graph again.
  49. { id: 'api-gateway', disabled: true },
  50. { id: 'directory-picker', disabled: true },
  51. // The roster AppCLIEntry would patch in; only the shipped root, so a
  52. // developer's own `~/.dsh/.preset` cannot change this test's outcome.
  53. // `default` here is the COMPOSITION default — the base layer the settings
  54. // document overrides.
  55. {
  56. id: 'agent-presets',
  57. config: { default: 'standard', roots: [{ path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' }] },
  58. },
  59. ]
  60. // The composition boots from an empty preset root, exactly as `dsh web`
  61. // does: the root's own directory is outside this workspace, so bare plugin
  62. // names cannot resolve by Node's upward walk. The flat fallback the preset
  63. // boot maintains is what makes them resolvable — the same mechanism, not a
  64. // test-only shim. It links each package's published entry, so this file
  65. // consumes the ARTIFACT plane and lives in the lane that builds.
  66. const home = dirname(settingsFile)
  67. healProfilesModuleFallback(INSTALL_ANCHOR, home)
  68. const presetDir = join(home, 'profiles', 'spec')
  69. await mkdir(presetDir, { recursive: true })
  70. const rootConfig = join(presetDir, 'cordis.yml')
  71. await writeFile(rootConfig, '[]\n')
  72. return await boot('dsh-test', rootConfig, patches)
  73. }
  74. const toolNames = (ctx: Context, agent?: Agent): string[] =>
  75. ctx.tools.schemas(agent).map(schema => schema.name).sort()
  76. let ctx: Context
  77. beforeAll(async () => {
  78. const settingsFile = join(await mkdtemp(join(tmpdir(), 'dsh-web-presets-')), 'settings.yaml')
  79. await writeFile(settingsFile, '{}\n')
  80. ctx = await bootWeb(settingsFile)
  81. }, 120_000)
  82. describe('the shipped Web composition', () => {
  83. it('leaves the global tool layer empty', () => {
  84. // Every model-facing tool belongs to a preset, `ask_user_question`
  85. // included: a tool in the global layer reaches EVERY agent regardless of
  86. // which preset composed it, so a two-tool benchmark surface would really
  87. // present three. A regression here means an agent-plane row came back to
  88. // the host composition.
  89. expect(toolNames(ctx)).toEqual([])
  90. })
  91. it('supplies both shipped presets, and only those, from the system root', async () => {
  92. const listed = await ctx.agentPresets.list()
  93. expect(listed.map(preset => preset.id).sort()).toEqual(['core-web', 'standard'])
  94. expect(listed.every(preset => preset.trust === 'system')).toBe(true)
  95. expect(ctx.agentPresets.defaultId).toBe('standard')
  96. })
  97. it('composes the full agent from `standard`', async () => {
  98. const handle = await ctx.agents.create({
  99. sessionId: SessionId('preset-standard'),
  100. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  101. })
  102. try {
  103. // The EXACT catalog, not a spot-check: an omission is this design's
  104. // quietest failure mode, because a row that registers into the wrong
  105. // layer mounts cleanly and simply contributes nothing. `glob`/`grep` are
  106. // excluded for the reason the TUI composition e2e excludes them — they
  107. // depend on ripgrep being present on the machine.
  108. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([
  109. 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode',
  110. 'get_goal', 'list_agents', 'ralph', 'read', 'send_message', 'skill',
  111. 'str_replace_editor', 'subagent', 'subagent_fork', 'task_kill',
  112. 'task_list', 'task_output', 'todo_write', 'update_goal', 'web_search',
  113. 'workflow', 'write',
  114. ])
  115. } finally {
  116. await handle.dispose()
  117. }
  118. })
  119. it('composes exactly two tools from `core-web`', async () => {
  120. const handle = await ctx.agents.create({
  121. sessionId: SessionId('preset-core-web'),
  122. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  123. })
  124. try {
  125. // Exactly what the preset lists — nothing arrives from the host.
  126. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  127. } finally {
  128. await handle.dispose()
  129. }
  130. })
  131. it('keeps two differently composed sessions independent', async () => {
  132. const full = await ctx.agents.create({
  133. sessionId: SessionId('preset-both-full'),
  134. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  135. })
  136. const minimal = await ctx.agents.create({
  137. sessionId: SessionId('preset-both-minimal'),
  138. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  139. })
  140. try {
  141. expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'str_replace_editor'])
  142. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  143. await minimal.dispose()
  144. // Tearing the minimal session down leaves the full one whole.
  145. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  146. expect(toolNames(ctx)).toEqual([])
  147. } finally {
  148. await full.dispose()
  149. }
  150. })
  151. it('never rewrites the preset file it composed from', async () => {
  152. // The Loader persists a tree whose plugin self-disposed, and tearing an
  153. // agent down disposes its whole subtree. Inherited, that rewrote the
  154. // shipped composition — truncating it to `[]` the first time a session
  155. // ended — so `PresetTree` refuses to write at all.
  156. const path = join(CONFIG_DIR, 'agent-presets', 'standard', 'agent.cordis.yml')
  157. const before = await readFile(path, 'utf8')
  158. const handle = await ctx.agents.create({
  159. sessionId: SessionId('preset-readonly'),
  160. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  161. })
  162. await handle.dispose()
  163. // Slack, not a race the number has to win. The write is driven by the
  164. // Loader's fiber-unload listener, which fires as the subtree's fibers
  165. // settle rather than when `dispose()` resolves, and the Loader exposes no
  166. // flush to await. A regression writes synchronously inside that listener,
  167. // so any wait past settlement fails; a longer one only slows the test.
  168. await new Promise(resolve => setTimeout(resolve, 50))
  169. expect(await readFile(path, 'utf8')).toBe(before)
  170. })
  171. it('gives each session its own persona', async () => {
  172. const handle = await ctx.agents.create({
  173. sessionId: SessionId('preset-persona'),
  174. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  175. })
  176. try {
  177. const assembly = await ctx.systemPrompt.assemble({ scope: handle.agent })
  178. expect(assembly.sections.find(section => section.name === 'deployment:persona')?.text)
  179. .toContain('You are a coding agent powered by')
  180. } finally {
  181. await handle.dispose()
  182. }
  183. })
  184. })
  185. describe('a forked session', () => {
  186. it('inherits the composition its seeded history was produced under', async () => {
  187. const parent = await ctx.agents.create({
  188. sessionId: SessionId('preset-fork-parent'),
  189. meta: { agentPreset: 'core-web' },
  190. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  191. })
  192. const inherited = parent.agent.session.header.agentPreset
  193. const child = await ctx.agents.create({
  194. sessionId: SessionId('preset-fork-child'),
  195. meta: {
  196. parentSession: SessionId('preset-fork-parent'),
  197. seedLength: 0,
  198. ...inherited === undefined ? {} : { agentPreset: inherited },
  199. },
  200. setup: agentCtx => ctx.agentPresets.mount(agentCtx, inherited).then(() => undefined),
  201. })
  202. try {
  203. // Composing nothing would leave the child empty: this layer moved every
  204. // model-facing row out of the host plane, so there is nothing to inherit
  205. // for free any more.
  206. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  207. expect(toolNames(ctx, child.agent).length).toBeGreaterThan(0)
  208. } finally {
  209. await child.dispose()
  210. await parent.dispose()
  211. }
  212. })
  213. })
  214. /**
  215. * Which preset an unnamed session gets is a user setting layered over the
  216. * composition's own default. The package suite proves the layering against a
  217. * hand-built context; this proves it through the shipped `cordis.yml` — that
  218. * the roster and the settings provider are actually wired to each other, and
  219. * that the id the setting names is the one a session composes from.
  220. */
  221. describe('the default preset as a user setting', () => {
  222. it('composes an unnamed session from the stored default, not the composed one', async () => {
  223. expect(ctx.agentPresets.defaultId).toBe('standard')
  224. await ctx.settings.update(settingsNamespace(SETTINGS_NAMESPACE), { default: 'core-web' })
  225. try {
  226. expect(ctx.agentPresets.defaultId).toBe('core-web')
  227. const handle = await ctx.agents.create({
  228. sessionId: SessionId('preset-user-default'),
  229. setup: agentCtx => ctx.agentPresets.mount(agentCtx).then(() => undefined),
  230. })
  231. try {
  232. // `mount()` with no id resolves the effective default. Two tools, not
  233. // `standard`'s catalog: the setting decided the composition.
  234. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  235. } finally {
  236. await handle.dispose()
  237. }
  238. } finally {
  239. // The context is shared with the rest of the file. `replace({})` drops
  240. // the user section wholesale so the field re-inherits the composition
  241. // base; `update` merges, and would leave the override standing.
  242. await ctx.settings.replace(settingsNamespace(SETTINGS_NAMESPACE), {})
  243. }
  244. expect(ctx.agentPresets.defaultId).toBe('standard')
  245. })
  246. })
  247. describe('a session keeps the preset it was created with', () => {
  248. it('records the preset the gateway guard reads', async () => {
  249. const handle = await ctx.agents.create({
  250. sessionId: SessionId('preset-locked'),
  251. meta: { agentPreset: 'core-web' },
  252. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  253. })
  254. try {
  255. // The api-proxy guard reads exactly this: the header records what the
  256. // session runs, so naming anything else is a caller error rather than a
  257. // switch. Its history was produced under `core-web`'s two tools.
  258. expect(handle.agent.session.header.agentPreset).toBe('core-web')
  259. } finally {
  260. await handle.dispose()
  261. }
  262. })
  263. })