feat: persist permission auto-accept on server (#2158)
Move per-session permission auto-accept policy ownership from the UI to the OpenChamber server so enabled sessions continue running when clients disconnect or the server restarts. - persist explicit per-session policies in OpenChamber settings - inherit the nearest explicit policy across subagent session hierarchies - allow child sessions to opt out of an inherited parent policy - immediately accept matching global and directory-scoped pending requests - process future requests without requiring a connected UI client - reconcile pending permissions after startup and event-stream reconnects - deduplicate concurrent requests and retry transient reply failures - synchronize policy updates across connected clients - migrate existing browser-persisted policies to server storage - suppress auto-accepted permission cards before they enter UI state - show deduplicated permission toasts for inactive sessions - preserve foreground-only permission handling in VS Code - integrate directory-aware notification routing from main - add coverage for persistence, inheritance, retries, reconciliation, pending requests, client hydration, and inactive-session toasts
This commit is contained in:
committed by
GitHub
parent
3d90eddcaf
commit
d738d41574
@@ -85,6 +85,7 @@ import { createNotificationTriggerRuntime } from './lib/notifications/runtime.js
|
||||
import { createPushRuntime } from './lib/notifications/push-runtime.js';
|
||||
import { createApnsRuntime } from './lib/notifications/apns-runtime.js';
|
||||
import { createNotificationTemplateRuntime } from './lib/notifications/template-runtime.js';
|
||||
import { createPermissionAutoAcceptRuntime } from './lib/permission-auto-accept/runtime.js';
|
||||
import { createGracefulShutdownRuntime } from './lib/opencode/shutdown-runtime.js';
|
||||
import { createProjectConfigRuntime } from './lib/projects/project-config.js';
|
||||
import { createRemoteClientAuthRuntime } from './lib/client-auth/remote-clients.js';
|
||||
@@ -716,7 +717,7 @@ const notificationTriggerRuntime = createNotificationTriggerRuntime({
|
||||
});
|
||||
|
||||
const maybeSendPushForTrigger = (...args) => notificationTriggerRuntime.maybeSendPushForTrigger(...args);
|
||||
const setAutoAcceptSession = (...args) => notificationTriggerRuntime.setAutoAcceptSession(...args);
|
||||
const setAutoAcceptSession = (sessionId, enabled) => permissionAutoAcceptRuntime.setSessionPolicy(sessionId, enabled);
|
||||
clearPendingPushBadge = () => notificationTriggerRuntime.clearPendingPushBadge();
|
||||
|
||||
const sessionAssistRuntime = createSessionAssistRuntime({
|
||||
@@ -771,6 +772,19 @@ const globalMessageStreamHub = createGlobalMessageStreamHub({
|
||||
upstreamStallTimeoutMs: getUpstreamStallTimeoutMs,
|
||||
});
|
||||
|
||||
const permissionAutoAcceptRuntime = createPermissionAutoAcceptRuntime({
|
||||
globalEventHub: globalMessageStreamHub,
|
||||
buildOpenCodeUrl,
|
||||
getOpenCodeAuthHeaders,
|
||||
readSettingsFromDiskMigrated,
|
||||
persistSettings,
|
||||
broadcastGlobalUiEvent,
|
||||
});
|
||||
permissionAutoAcceptRuntime.start();
|
||||
notificationTriggerRuntime.setGetIsSessionAutoAccepting(
|
||||
(sessionId, directory) => permissionAutoAcceptRuntime.isSessionAutoAccepting(sessionId, directory),
|
||||
);
|
||||
|
||||
const openCodeWatcherRuntime = createOpenCodeWatcherRuntime({
|
||||
waitForOpenCodePort: (...args) => waitForOpenCodePort(...args),
|
||||
buildOpenCodeUrl,
|
||||
@@ -1470,6 +1484,7 @@ async function main(options = {}) {
|
||||
scheduledTasksRuntime,
|
||||
getOpenChamberEventClients: () => uiOpenChamberEventClients,
|
||||
writeSseEvent,
|
||||
permissionAutoAcceptRuntime,
|
||||
});
|
||||
|
||||
const previewProxyRuntime = createPreviewProxyRuntime({
|
||||
|
||||
@@ -45,7 +45,7 @@ This module provides notification message preparation utilities for the web serv
|
||||
- Returned API:
|
||||
- `maybeSendPushForTrigger(payload)`
|
||||
- Owns:
|
||||
- completion/error/question/permission trigger routing
|
||||
- completion/error/question/permission trigger routing; permission suppression consults the authoritative permission-auto-accept runtime
|
||||
- session parent cache for subtask suppression
|
||||
- template resolution and fallback behavior
|
||||
- native notification fanout and web push payload fanout
|
||||
|
||||
@@ -15,6 +15,10 @@ export const createNotificationTriggerRuntime = (deps) => {
|
||||
buildOpenCodeUrl,
|
||||
getOpenCodeAuthHeaders,
|
||||
} = deps;
|
||||
let getIsSessionAutoAccepting = deps.getIsSessionAutoAccepting;
|
||||
const setGetIsSessionAutoAccepting = (resolver) => {
|
||||
getIsSessionAutoAccepting = typeof resolver === 'function' ? resolver : undefined;
|
||||
};
|
||||
|
||||
// App-icon badge for native push: the set of DISTINCT collapse-ids (the push
|
||||
// `tag`, e.g. `ready-<sessionId>` / `permission-<requestKey>`) we've sent since
|
||||
@@ -609,7 +613,8 @@ export const createNotificationTriggerRuntime = (deps) => {
|
||||
// Client may be in Permission Auto-Accept for this session (or any
|
||||
// ancestor). Skip the whole notification path — the client responds
|
||||
// directly and the user has opted out of approval prompts.
|
||||
if (await isSessionAutoAccepting(sessionId, notificationDirectory)) {
|
||||
if (await (getIsSessionAutoAccepting?.(sessionId, notificationDirectory)
|
||||
?? isSessionAutoAccepting(sessionId, notificationDirectory))) {
|
||||
if (requestKey) notifiedPermissionRequests.add(requestKey);
|
||||
return;
|
||||
}
|
||||
@@ -622,7 +627,8 @@ export const createNotificationTriggerRuntime = (deps) => {
|
||||
const timer = setTimeout(async () => {
|
||||
pushPermissionDebounceTimers.delete(sessionId);
|
||||
|
||||
if (await isSessionAutoAccepting(sessionId, notificationDirectory)) {
|
||||
if (await (getIsSessionAutoAccepting?.(sessionId, notificationDirectory)
|
||||
?? isSessionAutoAccepting(sessionId, notificationDirectory))) {
|
||||
if (requestKey) notifiedPermissionRequests.add(requestKey);
|
||||
return;
|
||||
}
|
||||
@@ -742,6 +748,7 @@ export const createNotificationTriggerRuntime = (deps) => {
|
||||
maybeSendPushForTrigger,
|
||||
setAutoAcceptSession,
|
||||
setGetIsWindowFocused,
|
||||
setGetIsSessionAutoAccepting,
|
||||
clearPendingPushBadge,
|
||||
sendGoalSettlePush,
|
||||
};
|
||||
|
||||
@@ -166,6 +166,7 @@ This module provides OpenCode server integration utilities for the web server ru
|
||||
- `readSettingsFromDiskMigrated()`
|
||||
- `writeSettingsToDisk(settings)`
|
||||
- `persistSettings(changes)`
|
||||
- Persistent permission auto-accept policy is stored under `permissionAutoAccept`; execution ownership lives in `lib/permission-auto-accept/`.
|
||||
|
||||
## Public exports (settings-helpers.js)
|
||||
- `createSettingsHelpers(dependencies)`: creates settings helper runtime for settings request/response shaping.
|
||||
|
||||
@@ -998,6 +998,7 @@ export const registerCommonRequestMiddleware = (app, dependencies) => {
|
||||
req.path.startsWith('/api/opencode') ||
|
||||
req.path.startsWith('/api/push') ||
|
||||
req.path.startsWith('/api/notifications') ||
|
||||
req.path.startsWith('/api/permission-auto-accept') ||
|
||||
req.path.startsWith('/api/session-folders') ||
|
||||
req.path.startsWith('/api/small-model') ||
|
||||
req.path.startsWith('/api/goals') ||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { registerGitHubRoutes } from '../github/routes.js';
|
||||
import { registerGitRoutes } from '../git/routes.js';
|
||||
import { registerMagicPromptRoutes } from '../magic-prompts/routes.js';
|
||||
import { registerSessionFoldersRoutes } from '../session-folders/routes.js';
|
||||
import { registerPermissionAutoAcceptRoutes } from '../permission-auto-accept/runtime.js';
|
||||
import { registerConfigEntityRoutes } from './config-entity-routes.js';
|
||||
import { registerSettingsUtilityRoutes } from './core-routes.js';
|
||||
import { registerProjectIconRoutes } from './project-icon-routes.js';
|
||||
@@ -98,6 +99,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
||||
scheduledTasksRuntime,
|
||||
getOpenChamberEventClients,
|
||||
writeSseEvent,
|
||||
permissionAutoAcceptRuntime,
|
||||
} = routeDependencies;
|
||||
|
||||
registerSettingsUtilityRoutes(app, {
|
||||
@@ -106,6 +108,8 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
||||
clientReloadDelayMs,
|
||||
});
|
||||
|
||||
registerPermissionAutoAcceptRoutes(app, permissionAutoAcceptRuntime);
|
||||
|
||||
registerOpenCodeRoutes(app, {
|
||||
crypto,
|
||||
clientReloadDelayMs,
|
||||
|
||||
@@ -184,6 +184,18 @@ export const createSettingsHelpers = (dependencies) => {
|
||||
if (typeof candidate.desktopMinimizeToTrayEnabled === 'boolean') {
|
||||
result.desktopMinimizeToTrayEnabled = candidate.desktopMinimizeToTrayEnabled;
|
||||
}
|
||||
if (candidate.permissionAutoAccept && typeof candidate.permissionAutoAccept === 'object' && !Array.isArray(candidate.permissionAutoAccept)) {
|
||||
const sessions = {};
|
||||
const sourceSessions = candidate.permissionAutoAccept.sessions;
|
||||
if (sourceSessions && typeof sourceSessions === 'object' && !Array.isArray(sourceSessions)) {
|
||||
for (const [sessionId, enabled] of Object.entries(sourceSessions)) {
|
||||
if (sessionId && typeof enabled === 'boolean') sessions[sessionId] = enabled;
|
||||
}
|
||||
}
|
||||
result.permissionAutoAccept = {
|
||||
sessions,
|
||||
};
|
||||
}
|
||||
if (typeof candidate.desktopUiPassword === 'string') {
|
||||
result.desktopUiPassword = candidate.desktopUiPassword.trim();
|
||||
}
|
||||
|
||||
@@ -111,6 +111,20 @@ describe('settings helpers', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('sanitizes the persisted permission auto-accept policy', () => {
|
||||
const helpers = createTestHelpers();
|
||||
|
||||
expect(helpers.sanitizeSettingsUpdate({
|
||||
permissionAutoAccept: {
|
||||
sessions: { root: true, child: false, invalid: 'true' },
|
||||
},
|
||||
})).toEqual({
|
||||
permissionAutoAccept: {
|
||||
sessions: { root: true, child: false },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts desktopUiPassword as a persisted shared setting', () => {
|
||||
const helpers = createTestHelpers();
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Permission Auto-Accept
|
||||
|
||||
## Purpose
|
||||
|
||||
This module owns the authoritative permission auto-accept policy for web, desktop, and mobile runtimes. Policy is persisted in OpenChamber settings so permission handling survives UI disconnects and server restarts.
|
||||
|
||||
## Policy
|
||||
|
||||
`permissionAutoAccept.sessions` contains explicit per-session boolean policies.
|
||||
|
||||
Policy inheritance uses the nearest explicit session value. A child `false` therefore overrides a parent `true`; descendants without an explicit value inherit from their nearest configured ancestor.
|
||||
|
||||
## Runtime
|
||||
|
||||
`createPermissionAutoAcceptRuntime` loads and serializes policy writes, subscribes to the global OpenCode event hub, caches session lineage, retries transient replies, and reconciles pending permissions after startup, reconnect, and policy enablement. Enabling Auto-Accept for a session immediately accepts matching pending requests and keeps handling future requests without requiring a connected UI.
|
||||
|
||||
Unknown lineage and failed policy loads fail closed. A failed pending-permission fetch is distinct from an empty successful response and never clears policy state.
|
||||
|
||||
## Routes
|
||||
|
||||
- `GET /api/permission-auto-accept`
|
||||
- `PUT /api/permission-auto-accept/sessions/:sessionId`
|
||||
|
||||
These are normal authenticated OpenChamber runtime routes. They must not be added to browser URL-token allowlists.
|
||||
|
||||
## UI ownership
|
||||
|
||||
`packages/ui/src/stores/permissionStore.ts` is a projection of server policy and does not persist an independent policy. The server is the sole responder and the UI renders pending requests until the authoritative `permission.replied` event arrives.
|
||||
|
||||
VS Code retains its foreground-only implementation because it does not run the web server runtime.
|
||||
|
||||
## Tests
|
||||
|
||||
`runtime.test.js` covers restart persistence, nearest explicit subagent inheritance, missing-lineage lookup, retry/deduplication, and reconnect reconciliation.
|
||||
@@ -0,0 +1,263 @@
|
||||
const SETTINGS_KEY = 'permissionAutoAccept';
|
||||
const RETRY_DELAYS_MS = [0, 250, 1000];
|
||||
const REQUEST_TIMEOUT_MS = 5000;
|
||||
const SESSION_CACHE_LIMIT = 10000;
|
||||
|
||||
const normalizePolicy = (value) => {
|
||||
const source = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
||||
const sessions = {};
|
||||
const entries = source.sessions && typeof source.sessions === 'object' && !Array.isArray(source.sessions)
|
||||
? Object.entries(source.sessions)
|
||||
: [];
|
||||
for (const [sessionId, enabled] of entries) {
|
||||
if (sessionId && typeof enabled === 'boolean') sessions[sessionId] = enabled;
|
||||
}
|
||||
return { sessions };
|
||||
};
|
||||
|
||||
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
export function createPermissionAutoAcceptRuntime({
|
||||
globalEventHub,
|
||||
buildOpenCodeUrl,
|
||||
getOpenCodeAuthHeaders,
|
||||
readSettingsFromDiskMigrated,
|
||||
persistSettings,
|
||||
broadcastGlobalUiEvent,
|
||||
fetchImpl = fetch,
|
||||
retryDelaysMs = RETRY_DELAYS_MS,
|
||||
requestTimeoutMs = REQUEST_TIMEOUT_MS,
|
||||
}) {
|
||||
let policy = normalizePolicy();
|
||||
let loaded = false;
|
||||
let loadPromise = null;
|
||||
let writePromise = Promise.resolve();
|
||||
const sessions = new Map();
|
||||
const inFlight = new Map();
|
||||
const reconcilePromises = new Map();
|
||||
|
||||
const snapshot = () => ({
|
||||
sessions: { ...policy.sessions },
|
||||
});
|
||||
|
||||
const load = async () => {
|
||||
if (loaded) return snapshot();
|
||||
if (!loadPromise) {
|
||||
loadPromise = readSettingsFromDiskMigrated()
|
||||
.then((settings) => {
|
||||
policy = normalizePolicy(settings?.[SETTINGS_KEY]);
|
||||
loaded = true;
|
||||
return snapshot();
|
||||
})
|
||||
.finally(() => { loadPromise = null; });
|
||||
}
|
||||
return loadPromise;
|
||||
};
|
||||
|
||||
const persistUpdate = (update) => {
|
||||
writePromise = writePromise.then(async () => {
|
||||
const next = update(policy);
|
||||
await persistSettings({ [SETTINGS_KEY]: next });
|
||||
policy = next;
|
||||
loaded = true;
|
||||
broadcastGlobalUiEvent?.({
|
||||
type: 'openchamber:permission-auto-accept.updated',
|
||||
properties: snapshot(),
|
||||
});
|
||||
return snapshot();
|
||||
});
|
||||
return writePromise;
|
||||
};
|
||||
|
||||
const setSessionPolicy = async (sessionId, enabled, directory) => {
|
||||
if (typeof sessionId !== 'string' || !sessionId.trim()) throw new TypeError('sessionId is required');
|
||||
if (typeof enabled !== 'boolean') throw new TypeError('enabled must be a boolean');
|
||||
await load();
|
||||
const result = await persistUpdate((current) => ({
|
||||
...current,
|
||||
sessions: { ...current.sessions, [sessionId.trim()]: enabled },
|
||||
}));
|
||||
if (enabled) await reconcilePending({ directories: [directory] });
|
||||
return result;
|
||||
};
|
||||
|
||||
const rememberSession = (info, directoryHint) => {
|
||||
if (!info || typeof info.id !== 'string' || !info.id) return;
|
||||
sessions.set(info.id, {
|
||||
parentID: typeof info.parentID === 'string' && info.parentID ? info.parentID : null,
|
||||
directory: typeof info.directory === 'string' && info.directory ? info.directory : directoryHint,
|
||||
});
|
||||
if (sessions.size > SESSION_CACHE_LIMIT) {
|
||||
sessions.delete(sessions.keys().next().value);
|
||||
}
|
||||
};
|
||||
|
||||
const request = async (path, { directory, method = 'GET', body } = {}) => {
|
||||
const url = new URL(buildOpenCodeUrl(path, ''));
|
||||
if (directory) url.searchParams.set('directory', directory);
|
||||
const response = await fetchImpl(url, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
...getOpenCodeAuthHeaders(),
|
||||
},
|
||||
...(body ? { body: JSON.stringify(body) } : {}),
|
||||
signal: AbortSignal.timeout(requestTimeoutMs),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const error = new Error(`OpenCode request failed (${response.status})`);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return response.json().catch(() => null);
|
||||
};
|
||||
|
||||
const getSession = async (sessionId, directory) => {
|
||||
const cached = sessions.get(sessionId);
|
||||
if (cached) return cached;
|
||||
const info = await request(`/session/${encodeURIComponent(sessionId)}`, { directory });
|
||||
rememberSession(info?.data ?? info, directory);
|
||||
return sessions.get(sessionId) ?? null;
|
||||
};
|
||||
|
||||
const isSessionAutoAccepting = async (sessionId, directory) => {
|
||||
await load();
|
||||
const seen = new Set();
|
||||
let current = sessionId;
|
||||
let currentDirectory = directory;
|
||||
while (current && !seen.has(current)) {
|
||||
if (Object.hasOwn(policy.sessions, current)) return policy.sessions[current] === true;
|
||||
seen.add(current);
|
||||
let info;
|
||||
try {
|
||||
info = await getSession(current, currentDirectory);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
current = info?.parentID ?? null;
|
||||
currentDirectory = info?.directory ?? currentDirectory;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const replyOnce = async (permission, directory) => {
|
||||
if (!permission?.id || !permission?.sessionID) return false;
|
||||
await load();
|
||||
if (!(await isSessionAutoAccepting(permission.sessionID, directory))) return false;
|
||||
await request(`/permission/${encodeURIComponent(permission.id)}/reply`, {
|
||||
directory,
|
||||
method: 'POST',
|
||||
body: { reply: 'once' },
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
const processPermission = (permission, directory) => {
|
||||
if (!permission?.id) return Promise.resolve(false);
|
||||
const key = permission.id;
|
||||
const existing = inFlight.get(key);
|
||||
if (existing) return existing;
|
||||
const task = (async () => {
|
||||
for (const delay of retryDelaysMs) {
|
||||
if (delay > 0) await wait(delay);
|
||||
try {
|
||||
return await replyOnce(permission, directory);
|
||||
} catch (error) {
|
||||
if (error?.status === 404) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
})().finally(() => inFlight.delete(key));
|
||||
inFlight.set(key, task);
|
||||
return task;
|
||||
};
|
||||
|
||||
async function reconcilePending({ directories = [] } = {}) {
|
||||
const normalizedDirectories = Array.from(new Set(
|
||||
directories.filter((directory) => typeof directory === 'string' && directory.trim()).map((directory) => directory.trim()),
|
||||
));
|
||||
const key = normalizedDirectories.length > 0 ? normalizedDirectories.join('\n') : 'all';
|
||||
const existing = reconcilePromises.get(key);
|
||||
if (existing) return existing;
|
||||
const task = (async () => {
|
||||
await load();
|
||||
const scopes = [undefined, ...normalizedDirectories];
|
||||
const pendingById = new Map();
|
||||
for (const directory of scopes) {
|
||||
let payload;
|
||||
try {
|
||||
payload = await request('/permission', { directory });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const pending = Array.isArray(payload) ? payload : Array.isArray(payload?.data) ? payload.data : null;
|
||||
if (!pending) continue;
|
||||
for (const permission of pending) {
|
||||
if (!permission?.id) continue;
|
||||
pendingById.set(permission.id, { permission, directory: permission.directory ?? directory });
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from(pendingById.values()).map(({ permission, directory }) =>
|
||||
processPermission(permission, directory)));
|
||||
})().finally(() => { reconcilePromises.delete(key); });
|
||||
reconcilePromises.set(key, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
const processEvent = (event) => {
|
||||
const raw = event?.payload;
|
||||
const payload = raw?.payload && typeof raw.payload === 'object' ? raw.payload : raw;
|
||||
const directory = typeof event?.directory === 'string' && event.directory !== 'global' ? event.directory : undefined;
|
||||
if (payload?.type === 'session.created' || payload?.type === 'session.updated') {
|
||||
rememberSession(payload.properties?.info, directory);
|
||||
return;
|
||||
}
|
||||
if (payload?.type === 'permission.asked') {
|
||||
void processPermission(payload.properties, directory);
|
||||
}
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
const unsubscribeEvent = globalEventHub.subscribeEvent(processEvent);
|
||||
const unsubscribeStatus = globalEventHub.subscribeStatus((status) => {
|
||||
if (status?.type === 'connect') void reconcilePending();
|
||||
});
|
||||
void load().then(() => reconcilePending()).catch((error) => {
|
||||
console.warn('[permission-auto-accept] failed to load policy:', error?.message ?? error);
|
||||
});
|
||||
return () => {
|
||||
unsubscribeEvent();
|
||||
unsubscribeStatus();
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
snapshot,
|
||||
load,
|
||||
setSessionPolicy,
|
||||
isSessionAutoAccepting,
|
||||
processPermission,
|
||||
reconcilePending,
|
||||
start,
|
||||
};
|
||||
}
|
||||
|
||||
export function registerPermissionAutoAcceptRoutes(app, runtime) {
|
||||
app.get('/api/permission-auto-accept', async (_req, res) => {
|
||||
try {
|
||||
res.json(await runtime.load());
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error?.message ?? 'Failed to load permission auto-accept policy' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/permission-auto-accept/sessions/:sessionId', async (req, res) => {
|
||||
try {
|
||||
const directory = typeof req.body?.directory === 'string' ? req.body.directory : undefined;
|
||||
res.json(await runtime.setSessionPolicy(req.params.sessionId, req.body?.enabled, directory));
|
||||
} catch (error) {
|
||||
res.status(error instanceof TypeError ? 400 : 500).json({ error: error?.message });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { createPermissionAutoAcceptRuntime } from './runtime.js';
|
||||
|
||||
const createRuntime = ({ stored, fetchImpl, retryDelaysMs = [0] } = {}) => {
|
||||
let settings = stored ?? { permissionAutoAccept: { sessions: {} } };
|
||||
let eventHandler;
|
||||
let statusHandler;
|
||||
const runtime = createPermissionAutoAcceptRuntime({
|
||||
globalEventHub: {
|
||||
subscribeEvent(handler) { eventHandler = handler; return () => {}; },
|
||||
subscribeStatus(handler) { statusHandler = handler; return () => {}; },
|
||||
},
|
||||
buildOpenCodeUrl: (path) => `http://opencode.test${path}`,
|
||||
getOpenCodeAuthHeaders: () => ({}),
|
||||
readSettingsFromDiskMigrated: async () => settings,
|
||||
persistSettings: async (changes) => { settings = { ...settings, ...changes }; },
|
||||
fetchImpl: fetchImpl ?? vi.fn(async () => new Response('[]')),
|
||||
retryDelaysMs,
|
||||
});
|
||||
runtime.start();
|
||||
return {
|
||||
runtime,
|
||||
getSettings: () => settings,
|
||||
emit: (payload, directory = '/project') => eventHandler({ payload, directory }),
|
||||
connect: () => statusHandler({ type: 'connect' }),
|
||||
};
|
||||
};
|
||||
|
||||
const flush = async () => {
|
||||
for (let index = 0; index < 20; index += 1) await Promise.resolve();
|
||||
};
|
||||
|
||||
describe('permission auto-accept runtime', () => {
|
||||
it('persists explicit session policies across runtime restarts', async () => {
|
||||
const first = createRuntime();
|
||||
await first.runtime.setSessionPolicy('root', true);
|
||||
|
||||
const second = createRuntime({ stored: first.getSettings() });
|
||||
await expect(second.runtime.load()).resolves.toEqual({
|
||||
sessions: { root: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('uses nearest explicit ancestor policy for subagents', async () => {
|
||||
const { runtime, emit } = createRuntime({
|
||||
stored: { permissionAutoAccept: { sessions: { root: true, child: false } } },
|
||||
});
|
||||
emit({ type: 'session.created', properties: { info: { id: 'child', parentID: 'root' } } });
|
||||
emit({ type: 'session.created', properties: { info: { id: 'grandchild', parentID: 'child' } } });
|
||||
await expect(runtime.isSessionAutoAccepting('grandchild', '/project')).resolves.toBe(false);
|
||||
await runtime.setSessionPolicy('child', true);
|
||||
await expect(runtime.isSessionAutoAccepting('grandchild', '/project')).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('fetches missing subagent lineage before replying', async () => {
|
||||
const fetchImpl = vi.fn(async (url, init = {}) => {
|
||||
const path = new URL(url).pathname;
|
||||
if (path === '/permission') return new Response('[]');
|
||||
if (path === '/session/child') return Response.json({ id: 'child', parentID: 'root', directory: '/project' });
|
||||
if (init.method === 'POST') return Response.json({});
|
||||
return new Response('', { status: 404 });
|
||||
});
|
||||
const { runtime } = createRuntime({
|
||||
stored: { permissionAutoAccept: { sessions: { root: true } } },
|
||||
fetchImpl,
|
||||
});
|
||||
await expect(runtime.processPermission({ id: 'perm', sessionID: 'child' }, '/project')).resolves.toBe(true);
|
||||
expect(fetchImpl.mock.calls.some(([url, init]) => new URL(url).pathname === '/permission/perm/reply' && init.method === 'POST')).toBe(true);
|
||||
});
|
||||
|
||||
it('retries a transient reply failure and deduplicates concurrent events', async () => {
|
||||
let replyAttempts = 0;
|
||||
const fetchImpl = vi.fn(async (url, init = {}) => {
|
||||
const path = new URL(url).pathname;
|
||||
if (path === '/permission') return new Response('[]');
|
||||
if (path === '/permission/perm/reply' && init.method === 'POST') {
|
||||
replyAttempts += 1;
|
||||
return replyAttempts === 1 ? new Response('', { status: 503 }) : Response.json({});
|
||||
}
|
||||
return Response.json({ id: 'root' });
|
||||
});
|
||||
const { runtime } = createRuntime({
|
||||
stored: { permissionAutoAccept: { sessions: { root: true } } },
|
||||
fetchImpl,
|
||||
retryDelaysMs: [0, 0],
|
||||
});
|
||||
const permission = { id: 'perm', sessionID: 'root' };
|
||||
const first = runtime.processPermission(permission, '/project');
|
||||
const second = runtime.processPermission(permission, '/project');
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([true, true]);
|
||||
expect(replyAttempts).toBe(2);
|
||||
});
|
||||
|
||||
it('reconciles pending permissions after reconnect', async () => {
|
||||
const fetchImpl = vi.fn(async (url, init = {}) => {
|
||||
const path = new URL(url).pathname;
|
||||
if (path === '/permission') return Response.json([{ id: 'pending', sessionID: 'root' }]);
|
||||
if (path === '/permission/pending/reply' && init.method === 'POST') return Response.json({});
|
||||
return Response.json({ id: 'root' });
|
||||
});
|
||||
const { connect } = createRuntime({
|
||||
stored: { permissionAutoAccept: { sessions: { root: true } } },
|
||||
fetchImpl,
|
||||
});
|
||||
connect();
|
||||
await flush();
|
||||
expect(fetchImpl.mock.calls.some(([url]) => new URL(url).pathname === '/permission/pending/reply')).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts existing pending permissions when a session policy is enabled', async () => {
|
||||
const fetchImpl = vi.fn(async (url, init = {}) => {
|
||||
const parsed = new URL(url);
|
||||
const path = parsed.pathname;
|
||||
if (path === '/permission') {
|
||||
return parsed.searchParams.get('directory') === '/project'
|
||||
? Response.json([
|
||||
{ id: 'root-pending', sessionID: 'root' },
|
||||
{ id: 'other-pending', sessionID: 'other' },
|
||||
])
|
||||
: Response.json([]);
|
||||
}
|
||||
if (path === '/permission/root-pending/reply' && init.method === 'POST') return Response.json({});
|
||||
if (path === '/session/other') return Response.json({ id: 'other' });
|
||||
return new Response('', { status: 404 });
|
||||
});
|
||||
const { runtime } = createRuntime({ fetchImpl });
|
||||
|
||||
await runtime.setSessionPolicy('root', true, '/project');
|
||||
|
||||
const replyPaths = fetchImpl.mock.calls
|
||||
.filter(([, init]) => init?.method === 'POST')
|
||||
.map(([url]) => new URL(url).pathname);
|
||||
expect(replyPaths).toEqual(['/permission/root-pending/reply']);
|
||||
expect(fetchImpl.mock.calls.some(([url]) => new URL(url).searchParams.get('directory') === '/project')).toBe(true);
|
||||
expect(await runtime.load()).toEqual({ sessions: { root: true } });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user