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
@@ -6,6 +6,7 @@ import { useProjectsStore } from '@/stores/useProjectsStore';
|
||||
import { useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore';
|
||||
import { useAutoReviewStore } from '@/stores/useAutoReviewStore';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { usePermissionStore } from '@/stores/permissionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { resetStreamingState } from '@/sync/streaming';
|
||||
|
||||
@@ -43,6 +44,7 @@ export const resetAppForRuntimeEndpointChange = (detail: RuntimeEndpointChangedD
|
||||
// Cross-project session list (mobile sessions sheet & co) belongs to the
|
||||
// previous instance — drop it so stale sessions can't linger after a switch.
|
||||
useGlobalSessionsStore.getState().resetForRuntimeSwitch();
|
||||
usePermissionStore.getState().reset();
|
||||
useSessionUIStore.getState().restoreForRuntimeSwitch(detail.runtimeKey);
|
||||
useUIStore.getState().restoreForRuntimeSwitch(detail.runtimeKey);
|
||||
resetStreamingState();
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { beforeEach, describe, expect, mock, test } from 'bun:test';
|
||||
|
||||
let fetchImpl: (input: string, init?: RequestInit) => Promise<Response>;
|
||||
mock.module('@/lib/runtime-fetch', () => ({
|
||||
runtimeFetch: (input: string, init?: RequestInit) => fetchImpl(input, init),
|
||||
}));
|
||||
mock.module('@/sync/sync-refs', () => ({ getAllSyncSessions: () => [] }));
|
||||
mock.module('@/sync/session-ui-store', () => ({
|
||||
useSessionUIStore: { getState: () => ({ getDirectoryForSession: () => '/project' }) },
|
||||
}));
|
||||
mock.module('@/lib/opencode/client', () => ({
|
||||
opencodeClient: { getDirectory: () => '/fallback' },
|
||||
}));
|
||||
|
||||
const { usePermissionStore } = await import('./permissionStore');
|
||||
const json = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status });
|
||||
|
||||
describe('permission store server policy', () => {
|
||||
beforeEach(() => {
|
||||
usePermissionStore.getState().reset();
|
||||
fetchImpl = async () => json({ sessions: {} });
|
||||
});
|
||||
|
||||
test('hydrates the authoritative server snapshot', async () => {
|
||||
fetchImpl = async () => json({ sessions: { root: true } });
|
||||
await usePermissionStore.getState().hydrate();
|
||||
expect(usePermissionStore.getState().autoAccept).toEqual({ root: true });
|
||||
});
|
||||
|
||||
test('preserves previous state when hydration fails', async () => {
|
||||
usePermissionStore.setState({ autoAccept: { root: true }, loaded: true });
|
||||
fetchImpl = async () => json({}, 503);
|
||||
await expect(usePermissionStore.getState().hydrate()).rejects.toThrow();
|
||||
expect(usePermissionStore.getState().autoAccept).toEqual({ root: true });
|
||||
});
|
||||
|
||||
test('updates local state only after server persistence succeeds', async () => {
|
||||
fetchImpl = async () => json({}, 500);
|
||||
await expect(usePermissionStore.getState().setSessionAutoAccept('root', true)).rejects.toThrow();
|
||||
expect(usePermissionStore.getState().autoAccept).toEqual({});
|
||||
});
|
||||
|
||||
test('sends the session directory for immediate pending reconciliation', async () => {
|
||||
let body: unknown;
|
||||
fetchImpl = async (_input, init) => {
|
||||
body = JSON.parse(String(init?.body));
|
||||
return json({ sessions: { root: true } });
|
||||
};
|
||||
await usePermissionStore.getState().setSessionAutoAccept('root', true);
|
||||
expect(body).toEqual({ enabled: true, directory: '/project' });
|
||||
});
|
||||
|
||||
test('migrates a legacy local policy when the server has no policy yet', async () => {
|
||||
usePermissionStore.setState({ autoAccept: { root: true } });
|
||||
const requests: string[] = [];
|
||||
fetchImpl = async (input) => {
|
||||
requests.push(input);
|
||||
return input.includes('/sessions/')
|
||||
? json({ sessions: { root: true } })
|
||||
: json({ sessions: {} });
|
||||
};
|
||||
await usePermissionStore.getState().hydrate();
|
||||
expect(requests).toEqual(['/api/permission-auto-accept', '/api/permission-auto-accept/sessions/root']);
|
||||
expect(usePermissionStore.getState().autoAccept).toEqual({ root: true });
|
||||
});
|
||||
});
|
||||
@@ -1,372 +1,120 @@
|
||||
import { create } from "zustand";
|
||||
import { devtools, persist } from "zustand/middleware";
|
||||
import { persist } from "zustand/middleware";
|
||||
import type { Session } from "@opencode-ai/sdk/v2/client";
|
||||
import {
|
||||
autoRespondsPermission,
|
||||
type PermissionAutoAcceptMap,
|
||||
} from "./utils/permissionAutoAccept";
|
||||
import { createDeferredSafeJSONStorage } from "./utils/safeStorage";
|
||||
import { getAllSyncSessions, getSyncChildStores } from "@/sync/sync-refs";
|
||||
import { opencodeClient } from "@/lib/opencode/client";
|
||||
import { respondToPermission } from "@/sync/session-actions";
|
||||
import { useSessionUIStore } from "@/sync/session-ui-store";
|
||||
import { autoRespondsPermission, type PermissionAutoAcceptMap } from "./utils/permissionAutoAccept";
|
||||
import { getAllSyncSessions } from "@/sync/sync-refs";
|
||||
import { runtimeFetch } from "@/lib/runtime-fetch";
|
||||
import { isVSCodeRuntime } from "@/lib/desktop";
|
||||
import { createDeferredSafeJSONStorage } from "./utils/safeStorage";
|
||||
import { useSessionUIStore } from "@/sync/session-ui-store";
|
||||
import { opencodeClient } from "@/lib/opencode/client";
|
||||
|
||||
interface PermissionState {
|
||||
type PermissionPolicySnapshot = {
|
||||
sessions: PermissionAutoAcceptMap;
|
||||
};
|
||||
|
||||
interface PermissionStore {
|
||||
autoAccept: PermissionAutoAcceptMap;
|
||||
}
|
||||
|
||||
interface PermissionActions {
|
||||
loaded: boolean;
|
||||
saving: boolean;
|
||||
hydrate: () => Promise<void>;
|
||||
applySnapshot: (snapshot: PermissionPolicySnapshot) => void;
|
||||
reset: () => void;
|
||||
isSessionAutoAccepting: (sessionId: string) => boolean;
|
||||
setSessionAutoAccept: (sessionId: string, enabled: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
type PermissionStore = PermissionState & PermissionActions;
|
||||
|
||||
const coerceAutoAcceptValue = (value: unknown): boolean => {
|
||||
if (typeof value === "boolean") {
|
||||
return value;
|
||||
const readSnapshot = async (response: Response): Promise<PermissionPolicySnapshot> => {
|
||||
if (!response.ok) throw new Error(`Permission auto-accept request failed (${response.status})`);
|
||||
const payload = await response.json() as Partial<PermissionPolicySnapshot>;
|
||||
if (!payload.sessions || typeof payload.sessions !== "object") {
|
||||
throw new Error("Invalid permission auto-accept response");
|
||||
}
|
||||
|
||||
if (typeof value === "string") {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (normalized === "true") {
|
||||
return true;
|
||||
}
|
||||
if (normalized === "false") {
|
||||
return false;
|
||||
}
|
||||
const sessions: PermissionAutoAcceptMap = {};
|
||||
for (const [sessionId, enabled] of Object.entries(payload.sessions)) {
|
||||
if (sessionId && typeof enabled === "boolean") sessions[sessionId] = enabled;
|
||||
}
|
||||
|
||||
if (typeof value === "number") {
|
||||
return value === 1;
|
||||
}
|
||||
|
||||
return false;
|
||||
return { sessions };
|
||||
};
|
||||
|
||||
const isLegacyDirectoryAutoAcceptKey = (key: string): boolean => key.endsWith("/*");
|
||||
const requestSnapshot = async (path: string, init?: RequestInit) => readSnapshot(await runtimeFetch(path, init));
|
||||
|
||||
const extractSessionIdFromLegacyKey = (key: string): string | null => {
|
||||
const trimmed = key.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
const lastSlash = trimmed.lastIndexOf("/");
|
||||
if (lastSlash === -1 || lastSlash === trimmed.length - 1) {
|
||||
return trimmed;
|
||||
}
|
||||
return trimmed.slice(lastSlash + 1);
|
||||
};
|
||||
const isAutoAccepting = (autoAccept: PermissionAutoAcceptMap, sessions: Session[], sessionId: string) =>
|
||||
autoRespondsPermission({ autoAccept, sessions, sessionID: sessionId });
|
||||
|
||||
const resolveSessionScope = (sessionID: string, sessions: Session[]): Set<string> => {
|
||||
const map = new Map<string, Session>();
|
||||
const children = new Map<string, string[]>();
|
||||
for (const session of sessions) {
|
||||
map.set(session.id, session);
|
||||
if (session.parentID) {
|
||||
const list = children.get(session.parentID);
|
||||
if (list) {
|
||||
list.push(session.id);
|
||||
} else {
|
||||
children.set(session.parentID, [session.id]);
|
||||
export const usePermissionStore = create<PermissionStore>()(persist((set, get) => ({
|
||||
autoAccept: {},
|
||||
loaded: false,
|
||||
saving: false,
|
||||
|
||||
hydrate: async () => {
|
||||
let snapshot = await requestSnapshot("/api/permission-auto-accept");
|
||||
const legacyEntries = Object.entries(get().autoAccept)
|
||||
.filter(([sessionId, enabled]) => !sessionId.includes("/") && typeof enabled === "boolean");
|
||||
if (Object.keys(snapshot.sessions).length === 0 && legacyEntries.length > 0) {
|
||||
for (const [sessionId, enabled] of legacyEntries) {
|
||||
if (!sessionId || typeof enabled !== "boolean") continue;
|
||||
snapshot = await requestSnapshot(
|
||||
`/api/permission-auto-accept/sessions/${encodeURIComponent(sessionId)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ enabled }),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
set({ autoAccept: snapshot.sessions, loaded: true });
|
||||
},
|
||||
|
||||
if (!map.has(sessionID)) {
|
||||
return new Set([sessionID]);
|
||||
}
|
||||
reset: () => set({ autoAccept: {}, loaded: false, saving: false }),
|
||||
|
||||
const result = new Set<string>();
|
||||
const seen = new Set<string>();
|
||||
const queue = [sessionID];
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift();
|
||||
if (!current || seen.has(current)) {
|
||||
continue;
|
||||
applySnapshot: (snapshot) => {
|
||||
const sessions: PermissionAutoAcceptMap = {};
|
||||
for (const [sessionId, enabled] of Object.entries(snapshot.sessions ?? {})) {
|
||||
if (sessionId && typeof enabled === "boolean") sessions[sessionId] = enabled;
|
||||
}
|
||||
seen.add(current);
|
||||
result.add(current);
|
||||
const nextChildren = children.get(current);
|
||||
if (!nextChildren || nextChildren.length === 0) {
|
||||
continue;
|
||||
set({ autoAccept: sessions, loaded: true });
|
||||
},
|
||||
|
||||
isSessionAutoAccepting: (sessionId) => {
|
||||
if (!sessionId) return false;
|
||||
return isAutoAccepting(get().autoAccept, getAllSyncSessions(), sessionId);
|
||||
},
|
||||
|
||||
setSessionAutoAccept: async (sessionId, enabled) => {
|
||||
if (!sessionId) return;
|
||||
if (isVSCodeRuntime()) {
|
||||
const response = await runtimeFetch("/api/notifications/auto-accept", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sessionId, enabled }),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Permission auto-accept request failed (${response.status})`);
|
||||
set((state) => ({ autoAccept: { ...state.autoAccept, [sessionId]: enabled }, loaded: true }));
|
||||
return;
|
||||
}
|
||||
for (const child of nextChildren) {
|
||||
if (!seen.has(child)) {
|
||||
queue.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const normalizeDirectoryCandidate = (value: unknown): string | null => {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
};
|
||||
|
||||
const collectPendingFromSyncStores = (): Array<{ id: string; sessionID: string }> => {
|
||||
try {
|
||||
const stores = getSyncChildStores();
|
||||
const pending: Array<{ id: string; sessionID: string }> = [];
|
||||
for (const store of stores.children.values()) {
|
||||
const permissionMap = store.getState().permission ?? {};
|
||||
for (const [sessionId, entries] of Object.entries(permissionMap)) {
|
||||
for (const permission of entries ?? []) {
|
||||
if (!permission?.id) continue;
|
||||
pending.push({ id: permission.id, sessionID: permission.sessionID || sessionId });
|
||||
}
|
||||
}
|
||||
}
|
||||
return pending;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const sessionBelongsToScope = async (
|
||||
sessionID: string,
|
||||
rootSessionID: string,
|
||||
knownSessions: Session[],
|
||||
directories: string[],
|
||||
): Promise<boolean> => {
|
||||
if (sessionID === rootSessionID) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const knownById = new Map<string, Session>();
|
||||
for (const session of knownSessions) {
|
||||
knownById.set(session.id, session);
|
||||
}
|
||||
|
||||
const fetchedById = new Map<string, Session>();
|
||||
const fetchSession = async (id: string): Promise<Session | null> => {
|
||||
const known = knownById.get(id) ?? fetchedById.get(id);
|
||||
if (known) return known;
|
||||
|
||||
for (const directory of directories) {
|
||||
try {
|
||||
const result = await opencodeClient.getScopedSdkClient(directory).session.get({
|
||||
sessionID: id,
|
||||
directory,
|
||||
});
|
||||
if (result.data) {
|
||||
fetchedById.set(id, result.data);
|
||||
return result.data;
|
||||
}
|
||||
} catch {
|
||||
// Try the next known project directory.
|
||||
}
|
||||
}
|
||||
|
||||
set({ saving: true });
|
||||
try {
|
||||
const result = await opencodeClient.getSdkClient().session.get({ sessionID: id });
|
||||
if (result.data) {
|
||||
fetchedById.set(id, result.data);
|
||||
return result.data;
|
||||
}
|
||||
} catch {
|
||||
// Missing session metadata means we cannot safely inherit the parent setting.
|
||||
const directory = useSessionUIStore.getState().getDirectoryForSession(sessionId)
|
||||
?? opencodeClient.getDirectory()
|
||||
?? undefined;
|
||||
const snapshot = await requestSnapshot(
|
||||
`/api/permission-auto-accept/sessions/${encodeURIComponent(sessionId)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ enabled, directory }),
|
||||
},
|
||||
);
|
||||
set({ autoAccept: snapshot.sessions, loaded: true });
|
||||
} finally {
|
||||
set({ saving: false });
|
||||
}
|
||||
},
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const seen = new Set<string>();
|
||||
let current: string | undefined = sessionID;
|
||||
while (current && !seen.has(current)) {
|
||||
if (current === rootSessionID) {
|
||||
return true;
|
||||
}
|
||||
seen.add(current);
|
||||
const session = await fetchSession(current);
|
||||
current = session?.parentID ?? undefined;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const autoRespondsPermissionBySession = (
|
||||
autoAccept: PermissionAutoAcceptMap,
|
||||
sessions: Session[],
|
||||
sessionID: string,
|
||||
): boolean => {
|
||||
return autoRespondsPermission({
|
||||
autoAccept,
|
||||
sessionID,
|
||||
sessions,
|
||||
});
|
||||
};
|
||||
|
||||
const getStorage = () => createDeferredSafeJSONStorage();
|
||||
|
||||
export const usePermissionStore = create<PermissionStore>()(
|
||||
devtools(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
autoAccept: {},
|
||||
|
||||
isSessionAutoAccepting: (sessionId: string) => {
|
||||
if (!sessionId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const sessions = getAllSyncSessions();
|
||||
return autoRespondsPermissionBySession(get().autoAccept, sessions, sessionId);
|
||||
},
|
||||
|
||||
setSessionAutoAccept: async (sessionId: string, enabled: boolean) => {
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessions = getAllSyncSessions();
|
||||
|
||||
set((state) => {
|
||||
const autoAccept = { ...state.autoAccept };
|
||||
autoAccept[sessionId] = enabled;
|
||||
return { autoAccept };
|
||||
});
|
||||
|
||||
const sessionScope = resolveSessionScope(sessionId, sessions);
|
||||
|
||||
// Mirror inherited state to the server so it can suppress
|
||||
// permission notifications before the client auto-response
|
||||
// round-trip. Send known descendants too; server-side
|
||||
// ancestry lookup can lag OpenCode session indexing.
|
||||
for (const scopedSessionId of sessionScope) {
|
||||
void runtimeFetch('/api/notifications/auto-accept', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: scopedSessionId, enabled }),
|
||||
}).catch(() => { /* best-effort */ });
|
||||
}
|
||||
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionDirectory = useSessionUIStore.getState().getDirectoryForSession(sessionId);
|
||||
const directories = new Set<string>();
|
||||
const currentDirectory = normalizeDirectoryCandidate(opencodeClient.getDirectory());
|
||||
if (currentDirectory) {
|
||||
directories.add(currentDirectory);
|
||||
}
|
||||
const mappedSessionDirectory = normalizeDirectoryCandidate(sessionDirectory);
|
||||
if (mappedSessionDirectory) {
|
||||
directories.add(mappedSessionDirectory);
|
||||
}
|
||||
for (const scopedSessionId of sessionScope) {
|
||||
const mapped = normalizeDirectoryCandidate(useSessionUIStore.getState().getDirectoryForSession(scopedSessionId));
|
||||
if (mapped) {
|
||||
directories.add(mapped);
|
||||
}
|
||||
}
|
||||
|
||||
const directoryList = Array.from(directories);
|
||||
const pendingFromStores = collectPendingFromSyncStores();
|
||||
// Best-effort: if listPendingPermissions throws (transient fetch failure),
|
||||
// proceed with whatever sync-store snapshots gave us. The next SSE event
|
||||
// or reconnect resync will auto-accept anything we missed.
|
||||
const pendingFromApi = await opencodeClient
|
||||
.listPendingPermissions({ directories: Array.from(directories) })
|
||||
.catch(() => []);
|
||||
const mergedPending = new Map<string, { id: string; sessionID: string }>();
|
||||
|
||||
for (const permission of pendingFromStores) {
|
||||
if (sessionScope.has(permission.sessionID)) {
|
||||
mergedPending.set(permission.id, permission);
|
||||
continue;
|
||||
}
|
||||
if (await sessionBelongsToScope(permission.sessionID, sessionId, sessions, directoryList)) {
|
||||
mergedPending.set(permission.id, permission);
|
||||
}
|
||||
}
|
||||
for (const permission of pendingFromApi) {
|
||||
if (!permission?.id || !permission?.sessionID) {
|
||||
continue;
|
||||
}
|
||||
if (!sessionScope.has(permission.sessionID)) {
|
||||
const belongsToScope = await sessionBelongsToScope(permission.sessionID, sessionId, sessions, directoryList);
|
||||
if (!belongsToScope) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
mergedPending.set(permission.id, { id: permission.id, sessionID: permission.sessionID });
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
Array.from(mergedPending.values())
|
||||
.map((permission) => respondToPermission(permission.sessionID, permission.id, "once").catch(() => undefined)),
|
||||
);
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: "permission-store",
|
||||
storage: getStorage(),
|
||||
partialize: (state) => ({ autoAccept: state.autoAccept }),
|
||||
merge: (persistedState, currentState) => {
|
||||
const merged = {
|
||||
...currentState,
|
||||
...(persistedState as Partial<PermissionStore>),
|
||||
};
|
||||
|
||||
const persisted = Object.entries(merged.autoAccept || {});
|
||||
const nextAutoAccept: PermissionAutoAcceptMap = {};
|
||||
|
||||
for (const [rawKey, rawEnabled] of persisted) {
|
||||
if (rawKey.includes("/") || isLegacyDirectoryAutoAcceptKey(rawKey)) {
|
||||
continue;
|
||||
}
|
||||
nextAutoAccept[rawKey] = coerceAutoAcceptValue(rawEnabled);
|
||||
}
|
||||
|
||||
for (const [rawKey, rawEnabled] of persisted) {
|
||||
if (isLegacyDirectoryAutoAcceptKey(rawKey)) {
|
||||
continue;
|
||||
}
|
||||
if (!rawKey.includes("/")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const sessionId = extractSessionIdFromLegacyKey(rawKey);
|
||||
if (!sessionId) {
|
||||
continue;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(nextAutoAccept, sessionId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalized = coerceAutoAcceptValue(rawEnabled);
|
||||
const existing = nextAutoAccept[sessionId];
|
||||
nextAutoAccept[sessionId] = existing === true ? true : normalized;
|
||||
}
|
||||
|
||||
return {
|
||||
...merged,
|
||||
autoAccept: nextAutoAccept,
|
||||
};
|
||||
},
|
||||
onRehydrateStorage: () => (state) => {
|
||||
if (!state) return;
|
||||
// Re-broadcast auto-accept state to the server after
|
||||
// rehydration so server-side notification suppression
|
||||
// survives page reloads / server restarts.
|
||||
for (const [sid, enabled] of Object.entries(state.autoAccept || {})) {
|
||||
if (enabled === true) {
|
||||
void runtimeFetch('/api/notifications/auto-accept', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sessionId: sid, enabled: true }),
|
||||
}).catch(() => { /* best-effort */ });
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
),
|
||||
{ name: "permission-store" }
|
||||
)
|
||||
);
|
||||
}), {
|
||||
name: "permission-store",
|
||||
storage: createDeferredSafeJSONStorage(),
|
||||
partialize: (state) => ({ autoAccept: state.autoAccept }),
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { PermissionRequest } from '@/types/permission';
|
||||
import { showPermissionNeededToast } from './permission-toast';
|
||||
|
||||
const permission = {
|
||||
id: 'permission-1',
|
||||
sessionID: 'inactive-session',
|
||||
permission: 'bash',
|
||||
} as PermissionRequest;
|
||||
|
||||
describe('permission needed toast', () => {
|
||||
test('shows for an inactive session and opens that session', () => {
|
||||
const shown: Array<{ title: string; options: Parameters<Parameters<typeof showPermissionNeededToast>[0]['show']>[1] }> = [];
|
||||
const opened: Array<[string, string]> = [];
|
||||
const show: Parameters<typeof showPermissionNeededToast>[0]['show'] = (title, options) => { shown.push({ title, options }); };
|
||||
const openSession = (sessionId: string, directory: string) => { opened.push([sessionId, directory]); };
|
||||
const pendingIds = new Set<string>();
|
||||
|
||||
expect(showPermissionNeededToast({
|
||||
permission,
|
||||
directory: '/project',
|
||||
isViewed: false,
|
||||
pendingIds,
|
||||
show,
|
||||
openSession,
|
||||
})).toBe(true);
|
||||
|
||||
expect(shown.length).toBe(1);
|
||||
const { options } = shown[0];
|
||||
expect(options.id).toBe('permission-inactive-session:permission-1');
|
||||
expect(options.description).toBe('bash');
|
||||
options.action.onClick();
|
||||
expect(opened).toEqual([['inactive-session', '/project']]);
|
||||
});
|
||||
|
||||
test('does not show for the viewed session or duplicate a pending toast', () => {
|
||||
const shown: string[] = [];
|
||||
const show: Parameters<typeof showPermissionNeededToast>[0]['show'] = (title) => { shown.push(title); };
|
||||
const openSession: Parameters<typeof showPermissionNeededToast>[0]['openSession'] = () => {};
|
||||
const pendingIds = new Set<string>();
|
||||
const base = { permission, directory: '/project', pendingIds, show, openSession };
|
||||
|
||||
expect(showPermissionNeededToast({ ...base, isViewed: true })).toBe(false);
|
||||
expect(showPermissionNeededToast({ ...base, isViewed: false })).toBe(true);
|
||||
expect(showPermissionNeededToast({ ...base, isViewed: false })).toBe(false);
|
||||
expect(shown.length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { PermissionRequest } from '@/types/permission';
|
||||
|
||||
type PermissionToastOptions = {
|
||||
permission: PermissionRequest;
|
||||
directory: string;
|
||||
isViewed: boolean;
|
||||
pendingIds: Set<string>;
|
||||
show: (title: string, options: {
|
||||
id: string;
|
||||
description: string;
|
||||
action: { label: string; onClick: () => void };
|
||||
}) => void;
|
||||
openSession: (sessionId: string, directory: string) => void;
|
||||
};
|
||||
|
||||
export const getPermissionToastKey = (sessionId?: string, requestId?: string) => {
|
||||
if (!sessionId || !requestId) return null;
|
||||
return `${sessionId}:${requestId}`;
|
||||
};
|
||||
|
||||
export const showPermissionNeededToast = ({
|
||||
permission,
|
||||
directory,
|
||||
isViewed,
|
||||
pendingIds,
|
||||
show,
|
||||
openSession,
|
||||
}: PermissionToastOptions): boolean => {
|
||||
const key = getPermissionToastKey(permission.sessionID, permission.id);
|
||||
if (isViewed || !key || pendingIds.has(key)) return false;
|
||||
|
||||
pendingIds.add(key);
|
||||
const description = typeof permission.permission === 'string' && permission.permission.trim().length > 0
|
||||
? permission.permission
|
||||
: 'Agent needs your approval';
|
||||
show('Permission needed', {
|
||||
id: `permission-${key}`,
|
||||
description,
|
||||
action: {
|
||||
label: 'Open session',
|
||||
onClick: () => openSession(permission.sessionID, directory),
|
||||
},
|
||||
});
|
||||
return true;
|
||||
};
|
||||
@@ -42,6 +42,7 @@ import type { QuestionRequest } from "@/types/question"
|
||||
import * as sessionActions from "./session-actions"
|
||||
import { getSessionMaterializationStatus, materializeSessionSnapshots } from "./materialization"
|
||||
import { openSessionFromToast } from "./session-navigation"
|
||||
import { getPermissionToastKey, showPermissionNeededToast } from "./permission-toast"
|
||||
import { getRuntimeLiveStatusSeed, LIVE_STATUS_TTL_MS } from "./runtime-live-memory"
|
||||
import { getRuntimeKey } from "@/lib/runtime-switch"
|
||||
import { getRegisteredRuntimeAPIs } from "@/contexts/runtimeAPIRegistry"
|
||||
@@ -320,11 +321,6 @@ const getQuestionToastKey = (sessionID?: string, requestID?: string) => {
|
||||
return `${sessionID}:${requestID}`
|
||||
}
|
||||
|
||||
const getPermissionToastKey = (sessionID?: string, requestID?: string) => {
|
||||
if (!sessionID || !requestID) return null
|
||||
return `${sessionID}:${requestID}`
|
||||
}
|
||||
|
||||
type UiNotificationPayload = {
|
||||
title?: unknown
|
||||
body?: unknown
|
||||
@@ -1135,7 +1131,9 @@ export async function resyncBlockingRequestsForDirectory(
|
||||
}
|
||||
|
||||
const permissionStore = usePermissionStore.getState()
|
||||
const autoAcceptingSessionIds = Object.keys(grouped).filter((sessionId) => permissionStore.isSessionAutoAccepting(sessionId))
|
||||
const autoAcceptingSessionIds = isVSCodeRuntime()
|
||||
? Object.keys(grouped).filter((sessionId) => permissionStore.isSessionAutoAccepting(sessionId))
|
||||
: []
|
||||
|
||||
if (autoAcceptingSessionIds.length > 0) {
|
||||
const acceptedIdsBySession = new Map<string, Set<string>>()
|
||||
@@ -1198,19 +1196,13 @@ export async function resyncBlockingRequestsForDirectory(
|
||||
if (isViewed) continue
|
||||
for (const permission of permissions) {
|
||||
if (knownIds.has(permission.id)) continue
|
||||
const toastKey = getPermissionToastKey(sessionId, permission.id)
|
||||
if (!toastKey || pendingPermissionToastIds.has(toastKey)) continue
|
||||
pendingPermissionToastIds.add(toastKey)
|
||||
const description = typeof permission.permission === "string" && permission.permission.trim().length > 0
|
||||
? permission.permission
|
||||
: "Agent needs your approval"
|
||||
toast.info("Permission needed", {
|
||||
id: `permission-${toastKey}`,
|
||||
description,
|
||||
action: {
|
||||
label: "Open session",
|
||||
onClick: () => openSessionFromToast(sessionId, directory),
|
||||
},
|
||||
showPermissionNeededToast({
|
||||
permission,
|
||||
directory,
|
||||
isViewed,
|
||||
pendingIds: pendingPermissionToastIds,
|
||||
show: (title, options) => toast.info(title, options),
|
||||
openSession: openSessionFromToast,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1336,6 +1328,19 @@ function handleEvent(
|
||||
childStores: ChildStoreManager,
|
||||
routingIndex: EventRoutingIndex,
|
||||
) {
|
||||
if ((payload as { type?: unknown }).type === "openchamber:permission-auto-accept.updated") {
|
||||
const properties = (payload as unknown as { properties?: unknown }).properties
|
||||
if (properties && typeof properties === "object") {
|
||||
const snapshot = properties as { sessions?: unknown }
|
||||
if (snapshot.sessions && typeof snapshot.sessions === "object") {
|
||||
usePermissionStore.getState().applySnapshot({
|
||||
sessions: snapshot.sessions as Record<string, boolean>,
|
||||
})
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const directory = resolveDirectoryFromRoutingIndex(routingIndex, rawDirectory, payload, childStores)
|
||||
|
||||
if (handleUiNotificationEvent(payload, directory)) {
|
||||
@@ -1421,26 +1426,21 @@ function handleEvent(
|
||||
const permissionStore = usePermissionStore.getState()
|
||||
if (permissionStore.isSessionAutoAccepting(permission.sessionID)) {
|
||||
updateRoutingIndexFromEvent(routingIndex, resolvedDirectory, payload)
|
||||
void sessionActions.respondToPermission(permission.sessionID, permission.id, "once").catch(() => undefined)
|
||||
if (isVSCodeRuntime()) {
|
||||
void sessionActions.respondToPermission(permission.sessionID, permission.id, "once").catch(() => undefined)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const toastKey = getPermissionToastKey(permission.sessionID, permission.id)
|
||||
const isViewed = isViewedInCurrentSession(resolvedDirectory, permission.sessionID)
|
||||
if (!isViewed && toastKey && !pendingPermissionToastIds.has(toastKey)) {
|
||||
pendingPermissionToastIds.add(toastKey)
|
||||
const description = typeof permission.permission === "string" && permission.permission.trim().length > 0
|
||||
? permission.permission
|
||||
: "Agent needs your approval"
|
||||
toast.info("Permission needed", {
|
||||
id: `permission-${toastKey}`,
|
||||
description,
|
||||
action: {
|
||||
label: "Open session",
|
||||
onClick: () => openSessionFromToast(permission.sessionID, resolvedDirectory),
|
||||
},
|
||||
})
|
||||
}
|
||||
showPermissionNeededToast({
|
||||
permission,
|
||||
directory: resolvedDirectory,
|
||||
isViewed,
|
||||
pendingIds: pendingPermissionToastIds,
|
||||
show: (title, options) => toast.info(title, options),
|
||||
openSession: openSessionFromToast,
|
||||
})
|
||||
}
|
||||
|
||||
if (payload.type === "permission.replied") {
|
||||
@@ -1732,6 +1732,11 @@ export function SyncProvider(props: {
|
||||
}, [childStores, routingIndex])
|
||||
|
||||
// Configure child store manager
|
||||
useEffect(() => {
|
||||
if (isVSCodeRuntime()) return
|
||||
void usePermissionStore.getState().hydrate().catch(() => undefined)
|
||||
}, [props.sdk])
|
||||
|
||||
useEffect(() => {
|
||||
const bootingDirs = new Set<string>()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user