Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 24 additions & 31 deletions apps/desktop/electron/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@ import {
type KeybindingOverrides,
type PlanExecutionFinishStatus,
} from "@pi-desktop/shared";
import {
genericModelConfig,
summarizeSessionTitle,
} from "@pi-desktop/agent-runtime";
import { summarizeSessionTitle } from "@pi-desktop/agent-runtime";
import { AgentExtensionBridge } from "./agent-extensions";
import { registerAgentExtensionIpc } from "./agent-extensions-ipc";
import { isTemplateName, scaffold } from "@pi-desktop/plugin-devkit";
Expand All @@ -56,11 +53,8 @@ import { installMainProcessErrorHandlers } from "./main-process-errors";
import {
isDbSchemaTooNewError,
} from "./host-boot-diagnostics";
import {
ModelsDevCatalog,
modelConfigFromModelsDev,
} from "./models-dev-catalog";
import { VendorOAuth } from "./oauth";
import { ModelsDevCatalog } from "./models-dev-catalog";
import { createVendorAccounts } from "./runtime/vendor-accounts";
import { AppUpdaterController } from "./updater";
import { catalogs, resolveLocale } from "@pi-desktop/i18n";
import {
Expand Down Expand Up @@ -120,6 +114,7 @@ import {
import { registerApplicationActivation } from "./bootstrap/app-activation";
import type { RuntimeState } from "./runtime/context";
import { createHostRuntime } from "./runtime/host";
import { createPermissionReviewResolver } from "./services/permission-review";
import { createSidecarRuntime } from "./runtime/sidecar";
import { createEventPersistence } from "./runtime/event-persistence";
import { createPlanRuntime, type PlanRuntimeState } from "./runtime/plans";
Expand Down Expand Up @@ -607,27 +602,8 @@ const modelsDevCatalog = new ModelsDevCatalog({
: join(app.getAppPath(), "resources", "models.dev", "api.json"),
});

const vendorOAuth = new VendorOAuth({
call: <T,>(method: string, params?: unknown): Promise<T> => {
if (!host) throw new Error("host unavailable");
return host.call<T>(method, params);
},
emit: (event) => sendToRenderer(IPC.event.providersOauth, event),
openExternal: async (url) => {
await safeOpenExternal(url);
},
log: (level, message, data) => logger.app("provider", level, message, { data }),
modelConfigFor: async ({ vendorKey, option }) => {
await modelsDevCatalog.ensureLoaded();
const model = modelsDevCatalog.findModel({
vendorKey,
baseUrl: option.baseUrl,
modelId: option.modelId,
});
return model
? modelConfigFromModelsDev(model, option.baseUrl)
: genericModelConfig(option.modelId, option.baseUrl);
},
const vendorOAuth = createVendorAccounts({
getHost: () => host, sendToRenderer, safeOpenExternal, logger, modelsDevCatalog,
});

let sessionLaunchRuntime: ReturnType<typeof createSessionLaunchRuntime> | null = null;
Expand Down Expand Up @@ -1061,6 +1037,7 @@ const {
isTurnDispatchable,
isSessionBusy,
isStaleTerminalEvent,
isStaleRuntimeActivity,
} = sessionCoordination;

async function withGitBranch<T extends { path?: string; name?: string } | null | undefined>(
Expand Down Expand Up @@ -1171,18 +1148,21 @@ const eventPersistence = createEventPersistence({
});
const { persistAgentEvent } = eventPersistence;

let cancelReviewForEvent: (envelope: AgentEventEnvelope) => void = () => {};
const sidecarRuntime = createSidecarRuntime({
runtimeState,
steeringReplies,
logger,
sendToRenderer,
persistAgentEvent,
onAgentEvent: (envelope) => cancelReviewForEvent(envelope),
activeTurns,
approvedExecutionIdsBySession,
claimedExecutionSessions,
inflightCheckpointer,
finishTurn,
isStaleTerminalEvent,
isStaleRuntimeActivity,
finishApprovedExecution,
superviseRestart,
isQuitting: () => quitting,
Expand All @@ -1203,7 +1183,8 @@ const sidecarRuntime = createSidecarRuntime({
emitAgentEvent = sidecarRuntime.emitAgentEvent;
const { wireSidecar, startSidecar } = sidecarRuntime;

const { wireHost, startHost } = createHostRuntime({
const { wireHost, startHost, cancelReviewForEvent: cancelHostReviewForEvent,
cancelReviewForSession, takeOverSessionReviews } = createHostRuntime({
runtimeState,
dataDir,
logger,
Expand All @@ -1226,7 +1207,17 @@ const { wireHost, startHost } = createHostRuntime({
importLegacyScheduled,
superviseRestart,
isQuitting: () => quitting,
settleExternalApproval: (requestId, decision) => {
agentHostBridge?.settleApproval(requestId, { decision });
},
reviewPermission: createPermissionReviewResolver({
getHost: () => runtimeState.host,
modelsDevCatalog,
vendorOAuth,
report: (code) => logger.app("permission", "warn", "review model unavailable", { data: { code } }),
}),
});
cancelReviewForEvent = cancelHostReviewForEvent;

runtimeLifecycle = createRuntimeLifecycle({
runtimeState,
Expand All @@ -1248,6 +1239,8 @@ const { bootHostStatus, runtimeArch, bootBackends } = runtimeLifecycle;

function registerIpc() {
return registerIpcHandlers({
cancelReviewForSession,
takeOverSessionReviews,
traySessions: applicationLifecycle!.traySessions,
ipcMain,
getMainWindow: () => mainWindow,
Expand Down
55 changes: 50 additions & 5 deletions apps/desktop/electron/main/ipc/agent-ipc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IPC, ErrorCodes, compactionRecordId, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";
import { IPC, ErrorCodes, compactionRecordId, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, type ToolPermissionResolution, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";
import type { FinishTurn } from "../runtime/plans";
import { expandSlashInvocation, enhancePromptDraft, summarizeSessionTitle, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";
import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";
Expand All @@ -13,6 +13,7 @@ import type { PersistenceOutbox } from "../persistence-outbox";
import type { ComposerCommandService } from "./composer-ipc";
import type { IpcRegistrar } from "./types";
import { withPromptEnhancementTimeout } from "../prompt-enhancement-timeout";
import { isRemoteSessionId, parseRemoteApprovalRequestId } from "../remote/backend-router";

export type AgentIpcDependencies = {
registrar: IpcRegistrar;
Expand All @@ -23,6 +24,7 @@ export type AgentIpcDependencies = {
vendorOAuth: VendorOAuth;
agentExtensions: AgentExtensionBridge;
cancelSessionTools: (sessionId: string, reason?: string) => void;
takeOverSessionReviews: (sessionId: string) => Promise<void>;
persistenceOutbox: PersistenceOutbox;
dataDir: string;
activeTurns: Map<string, string>;
Expand Down Expand Up @@ -56,6 +58,14 @@ function rejectNativeAgentOperation(sessionId: string): void {
}
}

function rejectRemotePermissionOperation(sessionId: string): void {
if (isRemoteSessionId(sessionId)) {
throw Object.assign(new Error("Permission review and grants are unavailable on remote sessions"), {
errorCode: ErrorCodes.CAPABILITY_UNAVAILABLE,
});
}
}

/** Register prompt, agent lifecycle, queue, approval and plan channels. */
export function registerAgentIpc({
registrar,
Expand All @@ -66,6 +76,7 @@ export function registerAgentIpc({
vendorOAuth,
agentExtensions,
cancelSessionTools,
takeOverSessionReviews,
persistenceOutbox,
dataDir,
activeTurns,
Expand Down Expand Up @@ -712,6 +723,7 @@ export function registerAgentIpc({

handle(IPC.invoke.agentStop, async (req: AgentStopRequest) => {
if (!sidecar) throw new Error("sidecar unavailable");
await takeOverSessionReviews(req.sessionId);
logger.app("session", "info", "prompt graceful stop requested", {
sessionId: req.sessionId,
});
Expand Down Expand Up @@ -760,10 +772,7 @@ export function registerAgentIpc({
},
);

handle(IPC.invoke.toolResolvePermission, async (resolution: {
requestId: string;
decision: string;
}) => {
handle(IPC.invoke.toolResolvePermission, async (resolution: ToolPermissionResolution) => {
if (!host) throw new Error("host unavailable");
logger.app("permission", "info", "permission resolved", {
data: { requestId: resolution.requestId, decision: resolution.decision },
Expand All @@ -779,6 +788,42 @@ export function registerAgentIpc({
return resolved;
});

handle(IPC.invoke.permissionTakeoverReview, async ({ requestId }: { requestId: string }) => {
if (!requestId?.trim()) throw new Error("requestId required");
const remoteRequest = parseRemoteApprovalRequestId(requestId);
if (remoteRequest) rejectRemotePermissionOperation(remoteRequest.remoteSessionId);
if (!host) throw new Error("host unavailable");
return host.call("permissions.takeoverReview", { requestId });
});

handle(IPC.invoke.permissionListSessionGrants, async ({ sessionId }: { sessionId: string }) => {
if (!sessionId?.trim()) throw new Error("sessionId required");
rejectRemotePermissionOperation(sessionId);
if (!host) throw new Error("host unavailable");
return host.call("permissions.listSessionGrants", { sessionId });
});

handle(IPC.invoke.permissionRevokeSessionGrant, async ({ sessionId, grantId }: { sessionId: string; grantId: string }) => {
if (!sessionId?.trim() || !grantId?.trim()) throw new Error("sessionId and grantId required");
rejectRemotePermissionOperation(sessionId);
if (!host) throw new Error("host unavailable");
return host.call("permissions.revokeSessionGrant", { sessionId, grantId });
});

handle(IPC.invoke.permissionClearSessionGrants, async ({ sessionId }: { sessionId: string }) => {
if (!sessionId?.trim()) throw new Error("sessionId required");
rejectRemotePermissionOperation(sessionId);
if (!host) throw new Error("host unavailable");
return host.call("permissions.clearSessionGrants", { sessionId });
});

handle(IPC.invoke.permissionListReviewHistory, async ({ sessionId }: { sessionId: string }) => {
if (!sessionId?.trim()) throw new Error("sessionId required");
rejectRemotePermissionOperation(sessionId);
if (!host) throw new Error("host unavailable");
return host.call("permissions.listReviewHistory", { sessionId });
});

handle(IPC.invoke.askToolResolve, async (resolution: AskToolResolution) => {
if (!sidecar) throw new Error("sidecar unavailable");
const sessionId = String(resolution?.sessionId ?? "").trim();
Expand Down
10 changes: 9 additions & 1 deletion apps/desktop/electron/main/ipc/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ import type { IpcRegistrar } from "./types";
import type { createTraySessions } from "../tray-sessions";

export type RegisterIpcDependencies = {
cancelReviewForSession?: (sessionId: string) => void;
takeOverSessionReviews?: (sessionId: string) => Promise<void>;
isQuitting: () => boolean;
ipcMain: IpcMain;
getMainWindow: () => BrowserWindow | null;
Expand Down Expand Up @@ -76,6 +78,8 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getHost,
getSidecar,
getAgentHostBridge,
cancelReviewForSession,
takeOverSessionReviews,
getBackendRouter,
getNotificationViewingSessionId,
setNotificationViewingSessionId,
Expand Down Expand Up @@ -355,10 +359,14 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
});
registerAgentIpc({
registrar,
takeOverSessionReviews: (sessionId: string) => takeOverSessionReviews?.(sessionId) ?? Promise.resolve(),
getHost,
getSidecar,
getAgentHostBridge,
cancelSessionTools: (sessionId: string, reason?: string) => plugins.cancelSessionTools(sessionId, reason),
cancelSessionTools: (sessionId: string, reason?: string) => {
cancelReviewForSession?.(sessionId);
plugins.cancelSessionTools(sessionId, reason);
},
logger,
vendorOAuth,
agentExtensions,
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/electron/main/ipc/session-ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,7 @@ export function registerSessionIpc({
modelId?: string;
thinkingLevel?: SessionThinkingLevel;
permissionMode?: "inherit" | "ask" | "accept-edits" | "auto";
approvalReviewer?: "inherit" | "user" | "auto_review";
},
) => {
rejectNativeMutation(id, "configuration");
Expand Down
Loading
Loading