Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(ai-edition): stop prompting for the macOS Keychain on every launch
Etienne Lescotbc07f6eed082
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 77d2cac1b..5e0c3af82 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -3562,11 +3562,25 @@ export function registerIpcHandlers(// project through a per-INSTANCE queue (see its writeProject comment — this// race destroyed two real project files), so a second instance means a second// queue racing for the same path: temp+rename still keeps the file valid, but- // a save can land under a concurrent one and be silently lost. LlmConfigStore- // is hoisted for a duller reason: its constructor does two sync readFileSync- // plus a safeStorage decrypt, and it was running on every chat message.+ // a save can land under a concurrent one and be silently lost.const aiEditionDocuments = new DocumentService(path.join(app.getPath("userData"), "projects"));- const aiEditionLlmConfig = new LlmConfigStore(app.getPath("userData"));++ // LlmConfigStore is single-instance for a duller reason — its constructor does+ // two sync readFileSync plus a safeStorage decrypt, and it was running on every+ // chat message. But it must also stay UNBUILT until something actually needs it:+ // on macOS that decrypt is backed by a Keychain item, so constructing it at+ // startup made every launch prompt for Keychain access, including for users who+ // never open the AI layer at all. (The prompt repeats because an unsigned or+ // ad-hoc-signed build has no stable code identity for the item's ACL to trust —+ // signing is the other half of that fix, and is not this function's business.)+ // Memoised, so the "one instance" guarantee above still holds.+ let aiEditionLlmConfigInstance: LlmConfigStore | null = null;+ const getAiEditionLlmConfig = (): LlmConfigStore => {+ if (!aiEditionLlmConfigInstance) {+ aiEditionLlmConfigInstance = new LlmConfigStore(app.getPath("userData"));+ }+ return aiEditionLlmConfigInstance;+ };registerNativeBridgeHandlers({getPlatform: () => process.platform,@@ -3602,9 +3616,9 @@ export function registerIpcHandlers(}},getAiEditionDocuments: () => aiEditionDocuments,- getAiEditionLlmConfig: () => aiEditionLlmConfig,+ getAiEditionLlmConfig,runAiEditionChat: (projectId, sessionId, message, document, sink) =>- runChat(projectId, sessionId, message, aiEditionLlmConfig, document, sink, {+ runChat(projectId, sessionId, message, getAiEditionLlmConfig(), document, sink, {cursor: agentCursorTelemetryReader,}),undoAiEditionToolBatch: (_projectId, _sessionId) => ({@@ -3614,7 +3628,7 @@ export function registerIpcHandlers(rewindToMessage: (projectId, sessionId, messageId) =>rewindToMessage(projectId, sessionId, messageId),compactNow: (projectId, sessionId) =>- compactSessionNow(projectId, sessionId, aiEditionLlmConfig),+ compactSessionNow(projectId, sessionId, getAiEditionLlmConfig()),getContextUsage: getSessionContextUsage,listAiEditionChatSessions: (projectId) => listSessions(projectId),createAiEditionChatSession: (projectId, title) => createSession(projectId, title),diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.tsindex c99126b64..47d66e270 100644--- a/electron/ipc/nativeBridge.ts+++ b/electron/ipc/nativeBridge.ts@@ -223,7 +223,9 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {const compositorViewService = new CompositorViewService();const aiEditionService = new AiEditionService({documents: context.getAiEditionDocuments(),- llmConfig: context.getAiEditionLlmConfig(),+ // Passed uncalled on purpose — invoking it here would build the store (and+ // hit the macOS Keychain) while wiring the bridge at startup.+ llmConfig: context.getAiEditionLlmConfig,runChat: context.runAiEditionChat,undoLastToolBatch: context.undoAiEditionToolBatch,rewindToMessage: context.rewindToMessage,diff --git a/electron/native-bridge/services/aiEditionService.lazyLlmConfig.test.ts b/electron/native-bridge/services/aiEditionService.lazyLlmConfig.test.tsnew file mode 100644index 000000000..0935f0db3--- /dev/null+++ b/electron/native-bridge/services/aiEditionService.lazyLlmConfig.test.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "vitest";+import type { LlmConfigStore } from "../../ai-edition/llm-config-store";+import { AiEditionService, type AiEditionServiceOptions } from "./aiEditionService";++/**+ * `LlmConfigStore`'s constructor does two sync readFileSync plus a `safeStorage`+ * decrypt. On macOS that decrypt is backed by a Keychain item, so building the+ * store during startup made every launch prompt for Keychain access — including+ * for the majority of users who never open the AI layer at all.+ *+ * The fix is that `AiEditionServiceOptions.llmConfig` is a factory the service+ * calls on first use, and `registerNativeBridgeHandlers` passes it uncalled.+ * That is a startup-timing property: reintroducing the eager form (a stray `()`+ * at the wiring site) breaks nothing that any other test observes, the app still+ * works, and the only symptom is a Keychain prompt on a machine the author may+ * not have. Hence a test that asserts on *when* the factory runs.+ */++/** Enough of the store for the methods exercised here; unused members stay absent. */+function storeStub(): LlmConfigStore {+ return {+ getConfig: () => null,+ getCredential: () => null,+ } as unknown as LlmConfigStore;+}++function serviceWithCountingFactory(): { service: AiEditionService; builds: () => number } {+ let builds = 0;+ const store = storeStub();+ const options = {+ documents: {+ listProjects: async () => [],+ },+ llmConfig: () => {+ builds += 1;+ return store;+ },+ } as unknown as AiEditionServiceOptions;+ return { service: new AiEditionService(options), builds: () => builds };+}++describe("AiEditionService — LLM store resolution is deferred", () => {+ it("does not build the store while the service is constructed", () => {+ const { builds } = serviceWithCountingFactory();+ expect(builds()).toBe(0);+ });++ it("does not build the store for work that has nothing to do with the LLM", async () => {+ const { service, builds } = serviceWithCountingFactory();+ await service.listProjects();+ expect(builds()).toBe(0);+ });++ it("builds it once on the first call that needs it, and holds it after", async () => {+ const { service, builds } = serviceWithCountingFactory();++ // llmGetSnapshot reads the store once per provider definition, so this+ // also pins the memoisation: without it the factory ran nine times here.+ await service.llmGetSnapshot();+ expect(builds()).toBe(1);++ await service.llmGetSnapshot();+ expect(builds()).toBe(1);+ });+});diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.tsindex 5d4d12caa..0fbbccc9c 100644--- a/electron/native-bridge/services/aiEditionService.ts+++ b/electron/native-bridge/services/aiEditionService.ts@@ -34,7 +34,16 @@ import { PROVIDER_DEFINITIONS } from "../../ai-edition/provider-registry";export interface AiEditionServiceOptions {documents: DocumentService;- llmConfig: LlmConfigStore;+ /**+ * A factory, not an instance: building `LlmConfigStore` does two sync+ * readFileSync plus a `safeStorage` decrypt, and on macOS that decrypt is+ * backed by a Keychain item — so resolving it while wiring the bridge made+ * every app launch prompt for Keychain access, including for users who never+ * open the AI layer. The caller memoises, so this still yields one instance.+ * Nothing here may call it at construction time; every use sits behind a+ * method the renderer has to invoke first.+ */+ llmConfig: () => LlmConfigStore;runChat: (projectId: string,sessionId: string,@@ -76,6 +85,19 @@ export interface AiEditionServiceOptions {export class AiEditionService {constructor(private readonly options: AiEditionServiceOptions) {}+ private llmConfigInstance: LlmConfigStore | null = null;++ /**+ * Resolves the store on first use, then holds it — `llmGetSnapshot` alone+ * reads it once per provider definition. See `AiEditionServiceOptions.llmConfig`.+ */+ private get llmConfig(): LlmConfigStore {+ if (!this.llmConfigInstance) {+ this.llmConfigInstance = this.options.llmConfig();+ }+ return this.llmConfigInstance;+ }+async listProjects(): Promise<AiEditionProjectSummary[]> {return this.options.documents.listProjects();}@@ -141,11 +163,11 @@ export class AiEditionService {}async llmGetSnapshot(): Promise<AiEditionLlmSnapshot> {- const config = this.options.llmConfig.getConfig();+ const config = this.llmConfig.getConfig();const credentialSummary: AiEditionLlmSnapshot["credentialSummary"] = [];const connectedProviders: string[] = [];for (const def of PROVIDER_DEFINITIONS) {- const resolved = this.options.llmConfig.getCredential(def.id, def.envKeys);+ const resolved = this.llmConfig.getCredential(def.id, def.envKeys);const connected = Boolean(resolved);if (connected) connectedProviders.push(def.id);credentialSummary.push({@@ -169,7 +191,7 @@ export class AiEditionService {async llmSetConfig(config: AiEditionLlmConfig): Promise<AiEditionDocumentResult> {try {- await this.options.llmConfig.setConfig(config);+ await this.llmConfig.setConfig(config);return { success: true };} catch (error) {return { success: false, error: error instanceof Error ? error.message : String(error) };@@ -179,7 +201,7 @@ export class AiEditionService {async llmSetApiKey(providerId: string, apiKey: string): Promise<AiEditionDocumentResult> {try {const entry: LlmCredential = { kind: "api-key", apiKey };- await this.options.llmConfig.setCredential(providerId, entry);+ await this.llmConfig.setCredential(providerId, entry);return { success: true };} catch (error) {return { success: false, error: error instanceof Error ? error.message : String(error) };@@ -188,7 +210,7 @@ export class AiEditionService {async llmRemoveApiKey(providerId: string): Promise<AiEditionDocumentResult> {try {- await this.options.llmConfig.removeCredential(providerId);+ await this.llmConfig.removeCredential(providerId);return { success: true };} catch (error) {return { success: false, error: error instanceof Error ? error.message : String(error) };@@ -196,10 +218,10 @@ export class AiEditionService {}async llmDisconnect(providerId: string): Promise<AiEditionLlmDisconnectResult> {- await this.options.llmConfig.removeCredential(providerId);- const active = this.options.llmConfig.getConfig();+ await this.llmConfig.removeCredential(providerId);+ const active = this.llmConfig.getConfig();if (active?.provider === providerId) {- await this.options.llmConfig.setConfig({+ await this.llmConfig.setConfig({provider: "",model: "",});@@ -211,9 +233,9 @@ export class AiEditionService {try {const def = PROVIDER_DEFINITIONS.find((d) => d.id === providerId);if (!def) return { models: [], error: `Unknown provider ${providerId}` };- const cred = this.options.llmConfig.getCredential(providerId, def.envKeys);+ const cred = this.llmConfig.getCredential(providerId, def.envKeys);if (!cred) return { models: [], error: "Not connected" };- const config = this.options.llmConfig.getConfig();+ const config = this.llmConfig.getConfig();const baseUrl = (config?.provider === providerId ? config.baseUrl : undefined) ?? def.baseUrl;if (providerId === "anthropic") {@@ -331,7 +353,7 @@ export class AiEditionService {targetLanguage: string;sourceLanguage?: string;}): Promise<AiEditionCaptionTranslateResult> {- const config = this.options.llmConfig.getConfig();+ const config = this.llmConfig.getConfig();if (!config) {return {success: false,@@ -340,7 +362,7 @@ export class AiEditionService {};}const def = PROVIDER_DEFINITIONS.find((d) => d.id === config.provider);- const credential = def ? this.options.llmConfig.getCredential(def.id, def.envKeys) : null;+ const credential = def ? this.llmConfig.getCredential(def.id, def.envKeys) : null;const result = await translateCaptionSegments({segments: input.segments,targetLanguage: input.targetLanguage,