// Feature 2 (permission policy) unit tests with a fake DOM + fake sessions. import assert from 'node:assert/strict' import { test } from 'vitest' import { AUTO_REVIEW_PRESET, FULL_ACCESS_PRESET, HANDLED_STORAGE_KEY, currentPreset, installPermissionPolicy, isAutoSwitchEligible, isFullAccessLabel, liveSessions, pruneFullAccess, shouldAutoSwitch, } from '../../src/client/chat/permission-policy.ts' import { apply as applyHost, applyHostAutoReview, isFreshAutoEligibleSession } from '../../src/host.ts' ;(globalThis as any).MutationObserver = class { observe() {} disconnect() {} } test('preset machine values match the host catalog', () => { assert.equal(FULL_ACCESS_PRESET, 'danger-full-access') assert.equal(AUTO_REVIEW_PRESET, 'auto') }) test('isFullAccessLabel matches zh/en labels at the start only', () => { assert.equal(isFullAccessLabel('完全权限'), true) assert.equal(isFullAccessLabel('完全权限 让代理不受限制地执行'), true) assert.equal(isFullAccessLabel('Full access'), true) assert.equal(isFullAccessLabel('自动审查'), false) assert.equal(isFullAccessLabel('仅可查看'), false) assert.equal(isFullAccessLabel('工作区内修改'), false) assert.equal(isFullAccessLabel(''), false) assert.equal(isFullAccessLabel(null), false) }) test('shouldAutoSwitch: only known non-auto presets, once', () => { assert.equal(shouldAutoSwitch('workspace-write', false), true) assert.equal(shouldAutoSwitch('danger-full-access', false), true) assert.equal(shouldAutoSwitch('auto', false), false) assert.equal(shouldAutoSwitch(undefined, false), false) assert.equal(shouldAutoSwitch('workspace-write', true), false) }) function fakeEl(text: string) { return { textContent: text, removed: false, remove(this: any) { this.removed = true } } } test('pruneFullAccess removes full-access from selects, listboxes and menus', () => { const opts = [fakeEl('仅可查看'), fakeEl('完全权限'), fakeEl('工作区内修改')] const items = [fakeEl('自动审查EXP'), fakeEl('完全权限'), fakeEl('Full access'), fakeEl('仅可查看')] const doc = { querySelectorAll(sel: string) { if (sel === 'option') return opts if (sel.includes('listbox')) return items return [] }, } assert.equal(pruneFullAccess(doc as any), 3) assert.deepEqual(opts.map((o) => o.removed), [false, true, false]) assert.deepEqual(items.map((o) => o.removed), [false, true, true, false]) }) test('liveSessions: keys+binding, ClientSessions list.getSnapshot/scopes, list() fallback, hostile shapes', () => { const live = { sessionId: 's1' } const viaKeys = liveSessions({ keys: () => ['s1', 's2'], binding: (id: string) => (id === 's1' ? { session: live } : undefined) }) assert.deepEqual(viaKeys.map((x) => x.id), ['s1']) const live2 = { sessionId: 's2' } const viaClientSessions = liveSessions({ list: { getSnapshot: () => ({ ids: ['s1', 's2'], byId: { s1: { id: 's1' }, s2: { id: 's2' } } }) }, binding: (id: string) => (id === 's2' ? { session: live2 } : undefined), }) assert.deepEqual(viaClientSessions.map((x) => x.id), ['s2']) const scopes = new Map([['s3', { binding: { session: { sessionId: 's3' } } }]]) const viaScopes = liveSessions({ scopes, list: { getSnapshot: () => ({ ids: [], byId: {} }) }, binding: (id: string) => scopes.get(id)?.binding, }) assert.deepEqual(viaScopes.map((x) => x.id), ['s3']) const viaList = liveSessions({ list: () => [{ sessionId: 'a' }, { nope: 1 }] }) assert.deepEqual(viaList.map((x) => x.id), ['a']) assert.deepEqual(liveSessions({ keys: () => { throw new Error('x') } }), []) assert.deepEqual(liveSessions(undefined), []) assert.deepEqual(liveSessions(42), []) }) test('currentPreset reads both string and { currentValue } permissions projections defensively', () => { const strLive = { projections: { faceOf: (n: string) => (n === 'permissions' ? { getSnapshot: () => 'workspace-write' } : undefined) } } assert.equal(currentPreset(strLive), 'workspace-write') const objLive = { projections: { faceOf: (n: string) => (n === 'permissions' ? { getSnapshot: () => ({ currentValue: 'auto' }) } : undefined) } } assert.equal(currentPreset(objLive), 'auto') assert.equal(currentPreset({}), undefined) assert.equal(currentPreset({ projections: { faceOf: () => { throw new Error('x') } } }), undefined) }) function fakeTimers() { const intervals = new Map void>() let next = 1 return { setInterval(fn: () => void) { const id = next++; intervals.set(id, fn); return id }, clearInterval(id: number) { intervals.delete(id) }, setTimeout(fn: () => void) { fn(); return 0 }, clearTimeout() {}, async runIntervals() { for (const fn of [...intervals.values()]) await fn() }, get size() { return intervals.size }, } } function fakeLive(preset: string | { currentValue: string }, fail = false, blank?: boolean) { const calls: string[] = [] return { calls, ...(blank === undefined ? {} : { getSnapshot: () => ({ blank }) }), projections: { faceOf: () => ({ getSnapshot: () => preset }) }, async command(text: string) { calls.push(text) if (fail) return { ok: false, error: { code: 'unavailable' } } return { ok: true, value: { matched: true } } }, } } function fakeStorage() { const map = new Map() return { getItem: (k: string) => map.get(k) ?? null, setItem: (k: string, v: string) => { map.set(k, v) }, } } test('policy: first sight of a new blank session switches it to auto once', async () => { const timers = fakeTimers() const live = fakeLive({ currentValue: 'workspace-write' }, false, true) const sessions = { list: { getSnapshot: () => ({ ids: ['s1'], byId: { s1: { id: 's1', blank: true } } }) }, binding: (id: string) => (id === 's1' ? { session: live } : undefined), } const doc = { body: {}, querySelectorAll: () => [] } const dispose = installPermissionPolicy(doc as any, () => sessions, timers as any) await timers.runIntervals() await timers.runIntervals() assert.deepEqual(live.calls, ['/permission auto']) dispose() assert.equal(timers.size, 0) }) test('policy: already-auto sessions are left alone; failures are not retried', async () => { const timers = fakeTimers() const autoLive = fakeLive('auto') const failLive = fakeLive('read-only', true) const sessions = { keys: () => ['a', 'b'], binding: (id: string) => ({ session: id === 'a' ? autoLive : failLive }), } const doc = { body: {}, querySelectorAll: () => [] } const dispose = installPermissionPolicy(doc as any, () => sessions, timers as any) await timers.runIntervals() await timers.runIntervals() assert.deepEqual(autoLive.calls, []) assert.deepEqual(failLive.calls, ['/permission auto']) dispose() }) test('policy: existing non-blank sessions and refreshed handled sessions are never overwritten', async () => { const localStorage = fakeStorage() const doc = { body: {}, defaultView: { localStorage }, querySelectorAll: () => [] } // 1) An existing conversation (blank: false) is never switched on load. const existingLive = fakeLive({ currentValue: 'read-only' }, false, false) // 2) A brand-new blank session is switched once on first sight. let blankPreset = 'workspace-write' const blankCalls: string[] = [] const blankLive = { getSnapshot: () => ({ blank: true }), projections: { faceOf: () => ({ getSnapshot: () => ({ currentValue: blankPreset }) }) }, async command(text: string) { blankCalls.push(text) blankPreset = 'auto' return { ok: true, value: { matched: true } } }, } const sessions = { list: { getSnapshot: () => ({ ids: ['existing-1', 'blank-1'], byId: { 'existing-1': { id: 'existing-1', blank: false }, 'blank-1': { id: 'blank-1', blank: true }, }, }), }, binding: (id: string) => { if (id === 'existing-1') return { session: existingLive } if (id === 'blank-1') return { session: blankLive } return undefined }, } const timers1 = fakeTimers() const dispose1 = installPermissionPolicy(doc as any, () => sessions, timers1 as any) await timers1.runIntervals() assert.deepEqual(existingLive.calls, [], '已有对话(blank=false)不得被自动切到 auto') assert.deepEqual(blankCalls, ['/permission auto'], '新建空白会话首次见到时应切到 auto') dispose1() // User manually switches blank-1 to read-only, then reloads the page (second mount). blankPreset = 'read-only' assert.ok(localStorage.getItem(HANDLED_STORAGE_KEY)?.includes('blank-1')) const timers2 = fakeTimers() const dispose2 = installPermissionPolicy(doc as any, () => sessions, timers2 as any) await timers2.runIntervals() assert.deepEqual(blankCalls, ['/permission auto'], '刷新后不得覆盖用户手动改过的会话权限') assert.equal(isAutoSwitchEligible('sub-1', {}, { list: { getSnapshot: () => ({ byId: { 'sub-1': { origin: 'subagent' } } }) } }), false) dispose2() }) test('host auto-review default: switches fresh blank sessions and skips used/subagent/manual sessions', () => { assert.equal(isFreshAutoEligibleSession({ header: { id: 's1' }, snapshotEvents: () => [{ type: 'permission/preset', data: { preset: 'workspace-write' } }] }), true) assert.equal(isFreshAutoEligibleSession({ header: { id: 's2', origin: 'subagent' }, snapshotEvents: () => [] }), false) assert.equal(isFreshAutoEligibleSession({ header: { id: 's3', isSeeded: true }, snapshotEvents: () => [] }), false) assert.equal(isFreshAutoEligibleSession({ header: { id: 's4' }, snapshotEvents: () => [{ type: 'turn/start' }] }), false) assert.equal(isFreshAutoEligibleSession({ header: { id: 's5' }, snapshotEvents: () => [{ type: 'command/run', data: { name: 'permission' } }] }), false) const setCalls: Array<[string, string]> = [] let catalogNames = ['read-only', 'workspace-write'] let currentPresetVal = 'workspace-write' const listeners = new Map void>() const session1 = { id: 'fresh-1', header: { id: 'fresh-1' }, snapshotEvents: () => [{ type: 'permission/preset', data: { preset: 'workspace-write' } }], } const permissionPresets = { get names() { return catalogNames }, current: () => currentPresetVal, set: (s: any, name: string) => { setCalls.push([s.id, name]) currentPresetVal = name }, } const agents = { list: () => [{ session: session1 }] } // Cordis 只在 inject 声明的服务可用时才把带服务的上下文交给回调;这里同步调用 // 即可复现实机行为。直接读 ctx.permissionPresets 会在真实 Context 上抛 // `cannot get property "permissionPresets" without inject`。 const ctxStub: any = { permissionPresets, agents, effect(run: () => void) { run() }, on(event: string, fn: (payload?: any) => void) { listeners.set(event, fn) return () => { listeners.delete(event) } }, inject(_deps: string[], callback: (child: any) => void) { callback(ctxStub) }, } applyHost(ctxStub, { flags: { readerEnabled: false } }) // Before 'auto' is registered in permissionPresets.names, nothing is switched yet. assert.deepEqual(setCalls, []) // Once auto-review registers 'auto' and emits catalog-changed, fresh-1 is switched to 'auto'. catalogNames = ['read-only', 'workspace-write', 'auto'] listeners.get('permission-presets/catalog-changed')?.() assert.deepEqual(setCalls, [['fresh-1', 'auto']]) // User later switches fresh-1 to read-only; another catalog-changed or agent/created does not overwrite it. currentPresetVal = 'read-only' listeners.get('permission-presets/catalog-changed')?.() assert.deepEqual(setCalls, [['fresh-1', 'auto']]) // A new agent/created with a fresh session is switched immediately. const session2 = { id: 'fresh-2', header: { id: 'fresh-2' }, snapshotEvents: () => [] } listeners.get('agent/created')?.({ agent: { session: session2 } }) assert.deepEqual(setCalls, [['fresh-1', 'auto'], ['fresh-2', 'auto']]) // Direct helper coverage when already auto. assert.equal(applyHostAutoReview(permissionPresets, session2, new Set()), false) })