permission-policy-context.e2e.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // Web acceptance for current sandbox-policy context. A real Chromium drives
  2. // the shipped /permission command through all three presets; record mode uses
  3. // the real provider, while replay keeps the same provider-authored behavior
  4. // keyless. Assertions read the exact durable header, runtime-context messages,
  5. // and tool calls, so assistant prose alone cannot satisfy the scenario.
  6. import { readFile } from 'node:fs/promises'
  7. import { join } from 'node:path'
  8. import { fileURLToPath } from 'node:url'
  9. import type { Browser, Page } from 'playwright'
  10. import { chromium } from 'playwright'
  11. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  12. import { canonicalPath } from '@deepseek-ai/dsh-sandbox'
  13. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  14. import {
  15. assertFixtureInventory, fixtureUserPrompts, launchWebScaffold, recordFixture,
  16. watchConsole, webSnapshotMode, type WebScaffold,
  17. } from './scaffold.ts'
  18. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  19. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/permission-policy-context', import.meta.url))
  20. const FIXTURE = fileURLToPath(new URL('./snapshots/permission-policy-context/session.jsonl', import.meta.url))
  21. const MODE = webSnapshotMode()
  22. const PROMPTS = [
  23. 'Can you create or edit a normal file right now under the current policy? Answer directly in one sentence. Do not call a tool just to discover the policy.',
  24. 'Does the DSH file sandbox currently restrict file operations? Answer directly in one sentence. Do not call tools.',
  25. 'Reply with exactly WORKSPACE_POLICY_SEEN. Do not call tools.',
  26. 'Create the relative path policy-neutral.txt in the current workspace containing exactly POLICY_NEUTRAL_OK, verify its contents, then report completion.',
  27. ] as const
  28. const PRESET_LABELS = ['Read Only', 'Full access', 'Workspace Write'] as const
  29. function requestSystems(events: readonly SessionEvent[]): string[] {
  30. return events.flatMap((event) => {
  31. if (event.type !== 'request/header') return []
  32. return typeof event.data.header.system === 'string' ? [event.data.header.system] : []
  33. })
  34. }
  35. function runtimeContexts(events: readonly SessionEvent[]): string[] {
  36. return events.flatMap((event) => {
  37. if (event.type !== 'user/message'
  38. || event.data.source.kind !== 'plugin'
  39. || event.data.source.plugin !== '@deepseek-ai/dsh-system-prompt') return []
  40. return event.data.content.flatMap(block => block.type === 'text' ? [block.text] : [])
  41. })
  42. }
  43. function assistantTexts(events: readonly SessionEvent[]): string[] {
  44. return events.flatMap((event) => {
  45. if (event.type !== 'assistant/message') return []
  46. const text = event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('').replaceAll('**', '')
  47. return text.length === 0 ? [] : [text]
  48. })
  49. }
  50. function callArgs(event: Extract<SessionEvent, { type: 'tool/call' }>): Record<string, unknown> {
  51. return JSON.parse(event.data.arguments) as Record<string, unknown>
  52. }
  53. describe('web e2e: current sandbox policy reaches the model before tools', () => {
  54. let scaffold: WebScaffold
  55. let browser: Browser
  56. let page: Page
  57. let tripwire: ReturnType<typeof watchConsole>
  58. let disposeApproval: (() => void) | undefined
  59. let sessionWorkspace: string | undefined
  60. const sessionEvents: SessionEvent[] = []
  61. beforeAll(async () => {
  62. scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE })
  63. disposeApproval = scaffold.ctx.on('approval/request', () => Promise.resolve('allowed-once'), { prepend: true })
  64. scaffold.ctx.on('session/event', (session, event: SessionEvent) => {
  65. sessionWorkspace = session.header.cwd
  66. sessionEvents.push(event)
  67. })
  68. browser = await chromium.launch()
  69. page = await newEnglishPage(browser)
  70. tripwire = watchConsole(page)
  71. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  72. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  73. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  74. }, 120_000)
  75. afterAll(async () => {
  76. await browser?.close()
  77. disposeApproval?.()
  78. await scaffold?.close()
  79. })
  80. it('switches read-only, danger-full-access, and workspace-write through the real GUI command path', async () => {
  81. onTestFailed(() => saveFailureShot(page, 'web-e2e-permission-policy-context'))
  82. if (MODE !== 'record') {
  83. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual(PROMPTS)
  84. }
  85. const input = page.locator('textarea').first()
  86. let sessionId: Awaited<ReturnType<WebScaffold['whenTurnSettled']>> | undefined
  87. for (const [index, preset] of ['read-only', 'danger-full-access', 'workspace-write'].entries()) {
  88. await input.fill(`/permission ${preset}`)
  89. await input.press('Enter')
  90. await page.getByRole('button', { name: `Access mode, current: ${PRESET_LABELS[index]}` })
  91. .waitFor({ timeout: 10_000 })
  92. const settled = scaffold.whenTurnSettled()
  93. await input.fill(PROMPTS[index] as string)
  94. await input.press('Enter')
  95. sessionId = await settled
  96. await expect.poll(() => input.isEnabled(), { timeout: 10_000 }).toBe(true)
  97. }
  98. await input.fill('/permission read-only')
  99. await input.press('Enter')
  100. await page.getByRole('button', { name: 'Access mode, current: Read Only' }).waitFor({ timeout: 10_000 })
  101. const settled = scaffold.whenTurnSettled()
  102. await input.fill(PROMPTS[3])
  103. await input.press('Enter')
  104. sessionId = await settled
  105. if (sessionId === undefined) throw new Error('permission-policy scenario completed no model turn')
  106. if (MODE === 'record') await recordFixture(scaffold, sessionId, FIXTURE)
  107. }, 240_000)
  108. it.skipIf(MODE === 'record')('records cache-safe current policy before the corresponding model behavior', async () => {
  109. const systems = requestSystems(sessionEvents)
  110. expect(systems).toHaveLength(1)
  111. expect(systems[0]).not.toContain('Current DSH file policy:')
  112. expect(systems[0]).not.toContain('Approval policy:')
  113. expect(systems[0]).not.toContain('Approval prompts are disabled in this session')
  114. const contexts = runtimeContexts(sessionEvents)
  115. expect(contexts).toHaveLength(4)
  116. expect(contexts[0]).toContain('Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode.')
  117. expect(contexts[0]).toContain('Do not refuse a required modification from this policy alone')
  118. expect(contexts[0]).toContain('Approval policy: ask.')
  119. expect(contexts[1]).toContain('Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.')
  120. expect(contexts[1]).toContain('Approval prompts are disabled in this session')
  121. if (sessionWorkspace === undefined) throw new Error('permission-policy scenario observed no session workspace')
  122. expect(contexts[2]).toContain(`Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: ${JSON.stringify(canonicalPath(sessionWorkspace))}. Some platform temporary areas may also be writable.`)
  123. expect(contexts[2]).toContain('Approval policy: ask.')
  124. expect(contexts[2]).not.toContain('Approval prompts are disabled in this session')
  125. expect(contexts[3]).toContain('Current DSH file policy: read-only.')
  126. const answers = assistantTexts(sessionEvents)
  127. expect(answers.length).toBeGreaterThanOrEqual(4)
  128. expect(answers[0]).toMatch(/read-only.*(?:denied|cannot modify|cannot create or edit)/i)
  129. expect(answers[1]).toMatch(/does not restrict.*(?:file operations|(?:write\/edit tools|write and edit tools).*one-shot bash commands)/i)
  130. expect(answers[2]).toBe('WORKSPACE_POLICY_SEEN')
  131. const calls = sessionEvents.filter(
  132. (event): event is Extract<SessionEvent, { type: 'tool/call' }> => event.type === 'tool/call',
  133. )
  134. expect(calls.every(call => call.data.turn === 4)).toBe(true)
  135. expect(calls.length).toBeGreaterThanOrEqual(2)
  136. const firstCall = calls[0]
  137. if (firstCall === undefined) throw new Error('neutral policy task produced no tool call')
  138. expect(callArgs(firstCall)['sandbox_permissions']).toBeUndefined()
  139. expect(calls.some(call => callArgs(call)['sandbox_permissions'] !== undefined)).toBe(true)
  140. expect(sessionEvents.some(event => event.type === 'tool/result'
  141. && JSON.stringify(event.data).includes('[sandbox: file access denied under read-only mode]'))).toBe(true)
  142. expect(sessionEvents.some(event => event.type === 'approval/asked')).toBe(true)
  143. if (sessionWorkspace === undefined) throw new Error('permission-policy scenario observed no session workspace')
  144. expect(await readFile(join(sessionWorkspace, 'policy-neutral.txt'), 'utf8')).toBe('POLICY_NEUTRAL_OK')
  145. })
  146. it.skipIf(MODE === 'record')('stays clean and keeps the fixture inventory closed', async () => {
  147. expect(tripwire.pageErrors).toEqual([])
  148. expect(tripwire.warnings).toEqual([])
  149. await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl'])
  150. })
  151. })