diff --git a/apps/desktop/e2e/fixtures.ts b/apps/desktop/e2e/fixtures.ts index 62b6e92c7d..121546ae48 100644 --- a/apps/desktop/e2e/fixtures.ts +++ b/apps/desktop/e2e/fixtures.ts @@ -81,7 +81,7 @@ export async function ensureSidebarExpanded(page: Page): Promise { * Merely mounting the editor does not mean target selection has finished. */ export async function awaitSendReady(page: Page): Promise { - await expect(page.getByRole('button', { name: '发送' })).toBeEnabled({ + await expect(page.getByRole('button', { name: '发送', exact: true })).toBeEnabled({ timeout: 20_000, }); } diff --git a/apps/desktop/e2e/workhub-layout.spec.ts b/apps/desktop/e2e/workhub-layout.spec.ts index ff9364d83f..987bb196b0 100644 --- a/apps/desktop/e2e/workhub-layout.spec.ts +++ b/apps/desktop/e2e/workhub-layout.spec.ts @@ -62,7 +62,13 @@ test('WorkHub uses its coordination model and shared attachment composer', async return conversation.left >= 0 && conversation.right <= innerWidth + 1; })).toBe(true); } - await mainWindow.evaluate((window, bounds) => window.setBounds(bounds), originalBounds); + const restoredContentWidth = await mainWindow.evaluate((window, bounds) => { + window.setBounds(bounds); + return window.getContentSize()[0]; + }, originalBounds); + await expect.poll(() => page.evaluate(() => innerWidth)).toBe(restoredContentWidth); + const restoredDockWidth = await page.locator('.workHubDock').evaluate((element) => Math.round(element.getBoundingClientRect().width)); + await expect.poll(() => workhub.evaluate(() => innerWidth)).toBe(restoredDockWidth); const anchors = workhub.locator('.workhub-anchors'); const draftBeforeOverlays = 'Draft survives main-window overlays and dragging.'; await workhub.locator(COMPOSER_INPUT).fill(draftBeforeOverlays); @@ -349,6 +355,9 @@ test('WorkHub keeps the submitted prompt visible while its agent is still runnin await workhub.getByRole('button', { name: /^(发送|Send)$/ }).click(); await expect(followups).toHaveText([queuedTexts[0]]); await workhub.locator(COMPOSER_INPUT).fill(queuedTexts[1]); + // Queue projection can arrive before the previous send IPC releases admission. + // Keyboard submission must wait for the same readiness as clicking Send. + await awaitSendReady(workhub); await workhub.locator(COMPOSER_INPUT).press('Enter'); await expect(followups).toHaveText(queuedTexts); const shortcuts = workhub.getByRole('button', { name: '发送快捷键', exact: true }); @@ -366,6 +375,7 @@ test('WorkHub keeps the submitted prompt visible while its agent is still runnin } await expect(workhub.locator('.maka-bubble-streaming')).toContainText('Fake backend waiting'); await workhub.locator(COMPOSER_INPUT).fill('立即调整方向,保持当前任务'); + await awaitSendReady(workhub); await workhub.locator(COMPOSER_INPUT).press('Shift+Enter'); await expect(workhub.locator('.maka-bubble-streaming')).toContainText('Acknowledged steering: 立即调整方向,保持当前任务'); const steered = workhub.locator('.maka-user-message').filter({ hasText: '立即调整方向,保持当前任务' }); diff --git a/apps/desktop/renderer-architecture.json b/apps/desktop/renderer-architecture.json index 0dad6f6fa4..e802e9e29a 100644 --- a/apps/desktop/renderer-architecture.json +++ b/apps/desktop/renderer-architecture.json @@ -74,6 +74,7 @@ "src/renderer/locales/settings-bot-copy.ts", "src/renderer/locales/settings-daily-review-copy.ts", "src/renderer/locales/settings-data-copy.ts", + "src/renderer/locales/settings-external-agents-copy.ts", "src/renderer/locales/settings-health-copy.ts", "src/renderer/locales/settings-memory-copy.ts", "src/renderer/locales/settings-navigation-copy.ts", @@ -1623,6 +1624,15 @@ "actionFactories": [], "dependencyPaths": {} }, + "src/renderer/locales/settings-external-agents-copy.ts": { + "bridgePaths": {}, + "environmentCapabilities": {}, + "hookCalls": {}, + "lifecycleMethods": {}, + "unresolvedDependencies": 0, + "actionFactories": [], + "dependencyPaths": {} + }, "src/renderer/locales/settings-health-copy.ts": { "bridgePaths": {}, "environmentCapabilities": {}, @@ -2311,15 +2321,6 @@ "actionFactories": [], "dependencyPaths": {} }, - "src/renderer/settings/action-guard.ts": { - "bridgePaths": {}, - "environmentCapabilities": {}, - "hookCalls": {}, - "lifecycleMethods": {}, - "unresolvedDependencies": 0, - "actionFactories": [], - "dependencyPaths": {} - }, "src/renderer/settings/appearance-settings-page.tsx": { "bridgePaths": { "window.maka.app.iconPreviews": 2, @@ -2833,7 +2834,9 @@ "lifecycleMethods": {}, "unresolvedDependencies": 0, "actionFactories": [], - "dependencyPaths": {} + "dependencyPaths": { + "../application/contracts/settings-presentation/oauth-login-flow-guard.js": 1 + } }, "src/renderer/settings/optimistic-settings-draft-controller.ts": { "bridgePaths": {}, @@ -3416,15 +3419,12 @@ "src/renderer/settings/runtime-host-settings-target.tsx": { "bridgePaths": {}, "environmentCapabilities": {}, - "hookCalls": { - "useToast": 1 - }, + "hookCalls": {}, "lifecycleMethods": {}, "unresolvedDependencies": 0, "actionFactories": [], "dependencyPaths": { - "@maka/ui": 1, - "react": 1 + "../application/contracts/settings-presentation/runtime-host-settings-target.js": 1 } }, "src/renderer/settings/runtime-host-ssh-terminal-dialog.tsx": { @@ -3563,8 +3563,7 @@ "unresolvedDependencies": 0, "actionFactories": [], "dependencyPaths": { - "@astryxdesign/core": 1, - "@maka/ui/icons": 1 + "../application/contracts/settings-presentation/settings-route-header.js": 1 } }, "src/renderer/settings/settings-rows.tsx": { @@ -3586,8 +3585,7 @@ "unresolvedDependencies": 0, "actionFactories": [], "dependencyPaths": { - "@astryxdesign/core": 1, - "@maka/ui": 1 + "../application/contracts/settings-presentation/settings-section.js": 1 } }, "src/renderer/settings/settings-skeleton.tsx": { @@ -3669,6 +3667,7 @@ "../../shared/settings-ownership.js": 1, "../browser-storage": 1, "../features/connection-settings": 1, + "../features/external-agent-settings/index.js": 1, "../features/session-bundle": 1, "../locales/settings-navigation-copy.js": 1, "../locales/settings-shared-copy.js": 1, @@ -3818,17 +3817,12 @@ "src/renderer/settings/use-action-guard.ts": { "bridgePaths": {}, "environmentCapabilities": {}, - "hookCalls": { - "useEffect": 2, - "useRef": 2 - }, + "hookCalls": {}, "lifecycleMethods": {}, "unresolvedDependencies": 0, "actionFactories": [], "dependencyPaths": { - "./action-guard.js": 1, - "./oauth-login-flow-guard.js": 1, - "react": 1 + "../application/contracts/settings-presentation/use-action-guard.js": 1 } }, "src/renderer/settings/use-connection-detail.ts": { diff --git a/apps/desktop/resources/licenses/npm/THIRD_PARTY_NOTICES.txt b/apps/desktop/resources/licenses/npm/THIRD_PARTY_NOTICES.txt index 3922353f03..ddad9c74a8 100644 --- a/apps/desktop/resources/licenses/npm/THIRD_PARTY_NOTICES.txt +++ b/apps/desktop/resources/licenses/npm/THIRD_PARTY_NOTICES.txt @@ -10,6 +10,205 @@ Policy: every package must resolve to an ASF-compatible SPDX license. Compound expressions record the compatible selected license. Packages without a shipped license file require an exact name@version text override in the generator. +Package: @agentclientprotocol/sdk@1.4.0 +Declared license: Apache-2.0 +Selected license: Apache-2.0 +Repository: git+https://github.com/agentclientprotocol/typescript-sdk.git + +--- LICENSE --- +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2025 Zed Industries, Inc. and contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +================================================================================ + Package: @ai-sdk/anthropic@4.0.46 Declared license: Apache-2.0 Selected license: Apache-2.0 diff --git a/apps/desktop/src/main/__tests__/external-agent-setup-ipc.test.ts b/apps/desktop/src/main/__tests__/external-agent-setup-ipc.test.ts new file mode 100644 index 0000000000..c8b601315b --- /dev/null +++ b/apps/desktop/src/main/__tests__/external-agent-setup-ipc.test.ts @@ -0,0 +1,179 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import type { IpcMainInvokeEvent } from 'electron'; +import { registerExternalAgentSetupIpc } from '../external-agent-setup-ipc-main.js'; +import { RuntimeHostOAuthPresentation } from '../runtime-host-oauth-presentation.js'; +import type { ExternalAgentSetupProjection } from '@maka/runtime-host/protocol'; + +test('external setup shares browser presentation without accepting a stale attempt URL', async () => { + const opened: string[] = []; + const presentation = new RuntimeHostOAuthPresentation(async (url) => { + opened.push(url); + }); + const pending = presentation.expect('new-attempt', 'new-attempt'); + await assert.rejects( + presentation.openExternal( + 'https://accounts.google.com/old', + 'old-attempt', + new AbortController().signal, + ), + ); + assert.deepEqual(opened, []); + await presentation.openExternal( + 'https://accounts.google.com/new', + 'new-attempt', + new AbortController().signal, + ); + assert.deepEqual(await pending.presented, { stateHint: 'new-attempt' }); + assert.deepEqual(opened, ['https://accounts.google.com/new']); +}); +test('setup IPC registers an expectation before start and releases it on terminal result or cancel', async () => { + type Handler = Parameters< + Parameters[0]['ipcMain']['handle'] + >[1]; + const handlers = new Map(); + const opened: string[] = []; + const presentation = new RuntimeHostOAuthPresentation(async (url) => { + opened.push(url); + }); + let phase: ExternalAgentSetupProjection['phase'] = 'connecting'; + let attempts = 0; + const input = { attemptId: 'attempt-1', action: 'login' as const, expectedExecutable: '/agent' }; + registerExternalAgentSetupIpc({ + selectExecutable: async () => "/existing/agy_acp_server.par", + ipcMain: { + handle: (channel, listener) => { + handlers.set(channel, listener); + }, + }, + presentation, + client: { + startExternalAgentSetup: async (value) => { + attempts++; + await presentation.openExternal( + 'https://accounts.google.com/test', + value.attemptId, + new AbortController().signal, + ); + return { ...value, phase }; + }, + queryExternalAgentSetup: async () => ({ ...input, phase }), + cancelExternalAgentSetup: async () => ({ ...input, phase: 'cancelled' }), + }, + }); + const invoke = (channel: string, input: unknown) => + handlers.get(channel)!({} as IpcMainInvokeEvent, input); + assert.equal(await invoke('external-agents:select-executable', undefined), '/existing/agy_acp_server.par'); + assert.deepEqual(opened, []); + await invoke('external-agents:setup:start', input); + assert.equal(attempts, 1); + assert.equal(opened.length, 1); + // A query after presentation must not recreate a setup slot or interfere + // with a regular model OAuth expectation. + const concurrent = presentation.expect('model-after-presentation'); + await invoke('external-agents:setup:query', { attemptId: input.attemptId }); + concurrent.cancel(); + phase = 'succeeded'; + await invoke('external-agents:setup:query', { attemptId: input.attemptId }); + await invoke('external-agents:setup:start', { ...input, attemptId: 'attempt-2' }); + await invoke('external-agents:setup:cancel', { attemptId: 'attempt-2' }); + const next = presentation.expect('regular-oauth'); + next.cancel(); +}); + +test('setup accepts a delayed authorization link and clears terminal, cancelled and abandoned expectations', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + type Handler = Parameters[0]['ipcMain']['handle']>[1]; + const handlers = new Map(); + const opened: string[] = []; + const presentation = new RuntimeHostOAuthPresentation(async (url) => { opened.push(url); }); + let input = { attemptId: 'slow-login', action: 'login' as const, expectedExecutable: '/agent' }; + let phase: ExternalAgentSetupProjection['phase'] = 'connecting'; + registerExternalAgentSetupIpc({ + ipcMain: { handle: (channel, listener) => { handlers.set(channel, listener); } }, + presentation, + client: { + startExternalAgentSetup: async (value) => ({ ...value, phase }), + queryExternalAgentSetup: async () => ({ ...input, phase }), + cancelExternalAgentSetup: async () => ({ ...input, phase: 'cancelled' }), + }, + }); + const invoke = (channel: string) => handlers.get(channel)!({} as IpcMainInvokeEvent, + channel === 'external-agents:setup:start' ? input : { attemptId: input.attemptId }); + const present = () => presentation.openExternal('https://accounts.google.com/delayed', input.attemptId, new AbortController().signal); + await invoke('external-agents:setup:start'); + // Active renderer polling keeps the presentation lease alive while the Host + // initializes and waits for authentication. + for (let elapsed = 0; elapsed < 320_000; elapsed += 20_000) { + t.mock.timers.tick(20_000); + await invoke('external-agents:setup:query'); + } + await present(); + assert.equal(opened.length, 1); + const concurrent = presentation.expect('model-after-presentation'); + await invoke('external-agents:setup:query'); + concurrent.cancel(); + phase = 'succeeded'; + await invoke('external-agents:setup:query'); + for (const terminal of ['failed', 'cancelled'] as const) { + input = { ...input, attemptId: terminal }; + phase = 'connecting'; + await invoke('external-agents:setup:start'); + t.mock.timers.tick(20_000); + if (terminal === 'cancelled') await invoke('external-agents:setup:cancel'); + else { phase = 'failed'; await invoke('external-agents:setup:query'); } + await assert.rejects(present(), /no matching OAuth presentation/); + } + input = { ...input, attemptId: 'abandoned' }; + phase = 'connecting'; + await invoke('external-agents:setup:start'); + t.mock.timers.tick(20_000); + await handlers.get('external-agents:setup:query')!( + {} as IpcMainInvokeEvent, + { attemptId: 'unrelated-attempt' }, + ); + t.mock.timers.tick(10_000); + await assert.rejects(present(), /no matching OAuth presentation/); + // A late query for the expired setup cannot renew or cancel a newer slot; + // state binding also prevents the stale setup URL from consuming it. + const next = presentation.expect('next-model', 'next-model'); + await invoke('external-agents:setup:query'); + await assert.rejects(present(), /belongs to another attempt/); + await invoke('external-agents:setup:cancel'); + await presentation.openExternal( + 'https://accounts.google.com/next', + 'next-model', + new AbortController().signal, + ); + assert.deepEqual(await next.presented, { stateHint: 'next-model' }); + input = { ...input, attemptId: 'next-setup' }; + await invoke('external-agents:setup:start'); + t.mock.timers.tick(30_000); + await Promise.resolve(); + input = { ...input, attemptId: 'setup-after-abandonment' }; + await invoke('external-agents:setup:start'); + await invoke('external-agents:setup:cancel'); + const regular = presentation.expect('regular-oauth'); + t.mock.timers.tick(30_000); + await assert.rejects(regular.presented, /did not present OAuth authorization/); + assert.equal(opened.length, 2); +}); diff --git a/apps/desktop/src/main/__tests__/external-agents-settings-page.test.ts b/apps/desktop/src/main/__tests__/external-agents-settings-page.test.ts new file mode 100644 index 0000000000..cb68ae0b8a --- /dev/null +++ b/apps/desktop/src/main/__tests__/external-agents-settings-page.test.ts @@ -0,0 +1,351 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import assert from 'node:assert/strict'; +import { afterEach, test } from 'node:test'; +import { parseHTML } from 'linkedom'; +import { act, createElement } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { AstryxLocaleProvider, LocaleProvider } from '@maka/ui'; +import { createDefaultSettings } from '@maka/core/settings'; +import type { UiLocale } from '@maka/core/ui-locale'; +import type { + ExternalAgentSetupProjection, + ExternalAgentSetupStart, +} from '@maka/runtime-host/protocol'; +import { + ExternalAgentsSettingsPage, + ExternalAgentSettingsServicesProvider, +} from '../../renderer/features/external-agent-settings/index.js'; +import { createDesktopExternalAgentSettingsServices } from '../../renderer/platform/desktop/create-external-agent-settings-services.js'; +import { RuntimeHostSettingsTarget } from '../../renderer/settings/runtime-host-settings-target.js'; + +let root: Root | undefined; +const globals = [ + 'window', + 'document', + 'HTMLElement', + 'HTMLIFrameElement', + 'Node', + 'Event', + 'CSS', + 'matchMedia', + 'getComputedStyle', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'IS_REACT_ACT_ENVIRONMENT', +]; +const original = Object.fromEntries(globals.map((key) => [key, Reflect.get(globalThis, key)])); +afterEach(async () => { + if (root) await act(() => root!.unmount()); + root = undefined; + Object.assign(globalThis, original); +}); +async function mount( + input: { + locale?: UiLocale; + list?: boolean; + executable?: string; + remote?: boolean; + start?: (value: ExternalAgentSetupStart) => Promise; + } = {}, +) { + const { document, window } = parseHTML('
'); + const matchMedia = (media: string) => ({ + matches: false, + media, + onchange: null, + addListener() {}, + removeListener() {}, + addEventListener() {}, + removeEventListener() {}, + dispatchEvent: () => false, + }); + const getComputedStyle = () => ({ + direction: 'ltr', + writingMode: 'horizontal-tb', + getPropertyValue: () => '', + }); + Object.assign(window, { matchMedia, getComputedStyle }); + Object.assign(globalThis, { + document, + window, + matchMedia, + getComputedStyle, + HTMLElement: window.HTMLElement, + HTMLIFrameElement: window.HTMLIFrameElement ?? class {}, + Node: window.Node, + Event: window.Event, + CSS: { escape: (value: string) => value }, + requestAnimationFrame: () => 0, + cancelAnimationFrame() {}, + IS_REACT_ACT_ENVIRONMENT: true, + }); + const starts: ExternalAgentSetupStart[] = []; + const updates: string[] = []; + const updateGuards: Array< + import('@maka/core/settings').RuntimeHostSettingsUpdateGuard | undefined + > = []; + const cancels: string[] = []; + Object.assign(window, { + maka: { + app: { info: async () => ({ platform: 'darwin', arch: 'arm64' }) }, + runtimeHostProfiles: { + getSnapshot: async () => ({ + entries: [{ profile: { id: 'local', kind: input.remote ? 'remote' : 'local' } }], + }), + }, + externalAgents: { + selectExecutable: async () => '/existing/agy_acp_server.par', + start: async (value: ExternalAgentSetupStart) => { + starts.push(value); + return input.start ? input.start(value) : { ...value, phase: 'succeeded' }; + }, + query: async () => ({ ...starts[0], phase: 'succeeded' }), + cancel: async (id: string) => { + cancels.push(id); + return { ...starts[0], phase: 'cancelled' }; + }, + }, + }, + }); + const settings = createDefaultSettings(); + settings.externalAgents.antigravity.executable = input.executable ?? '/agent/agy_acp_server.par'; + root = createRoot(document.getElementById('root')!); + const services = createDesktopExternalAgentSettingsServices(); + const render = async ( + generation: string, + executable = settings.externalAgents.antigravity.executable, + ) => { + await act(async () => + root!.render( + createElement(LocaleProvider, { + locale: input.locale ?? 'en', + children: createElement(AstryxLocaleProvider, { + children: createElement(RuntimeHostSettingsTarget, { + host: { profileId: 'local', hostId: 'host-1' }, + generation, + children: createElement(ExternalAgentSettingsServicesProvider, { + services, + children: createElement(ExternalAgentsSettingsPage, { + settings: { ...settings, externalAgents: { antigravity: { executable } } }, + onUpdate: async ( + patch: import('@maka/core/settings').UpdateAppSettingsInput, + guard?: import('@maka/core/settings').RuntimeHostSettingsUpdateGuard, + ) => { + const executable = patch.externalAgents?.antigravity.executable ?? settings.externalAgents.antigravity.executable; + updates.push(executable); + updateGuards.push(guard); + return { settings: { ...settings, externalAgents: { antigravity: { executable } } } }; + }, + }), + }), + }), + }), + }), + ), + ); + }; + await render('generation-1'); + if (!input.list) + await act(async () => { + const entry = [...document.querySelectorAll('button')].find((button) => + button.textContent?.includes('Antigravity'), + ); + assert.ok(entry); + entry.click(); + }); + return { + document, + starts, + updates, + updateGuards, + cancels, + render, + button: (label: string) => { + const button = [...document.querySelectorAll('button')].find( + (button) => button.textContent?.trim() === label, + ); + assert.ok(button, label); + return button; + }, + }; +} +for (const [locale, label] of [ + ['en', 'Check connection'], + ['zh-CN', '检查连接'], + ['zh-TW', '檢查連線'], +] as const) { + test(`${locale}: setup is available through the existing Settings controls`, async () => { + const page = await mount({ locale }); + assert.equal(page.button(label).disabled, false); + await act(async () => { + page.button(label).click(); + page.button(label).click(); + }); + assert.equal(page.starts.length, 1, 'synchronous action guard prevents double start'); + assert.equal(page.starts[0].action, 'check'); + assert.match(page.document.body.textContent ?? '', /Connection successful|连接成功|連線成功/); + assert.doesNotMatch( + page.document.body.textContent ?? '', + /Google sign-in verified for this attempt|本次 Google 登录验证成功|本次 Google 登入驗證成功/, + ); + }); +} +test('remote targets cannot start an external agent', async () => { + const page = await mount({ remote: true }); + assert.equal(page.button('Check connection').disabled, true); + assert.match(page.document.body.textContent ?? '', /local macOS Apple Silicon/); +}); +test('Host generation change cancels an in-flight start and ignores its late response', async () => { + let finish!: (value: ExternalAgentSetupProjection) => void; + const pending = new Promise((resolve) => { + finish = resolve; + }); + const page = await mount({ start: () => pending }); + await act(async () => page.button('Sign in with Google').click()); + assert.equal(page.starts.length, 1); + await page.render('generation-2'); + assert.equal(page.cancels.length, 1); + await act(async () => { + finish({ ...page.starts[0], phase: 'succeeded' }); + await pending; + }); + assert.equal(page.cancels.length, 2, 'cancel again after delayed admission'); + assert.doesNotMatch(page.document.body.textContent ?? '', /Google sign-in verified for this attempt/); +}); +test('changing saved configuration clears the previous success', async () => { + const page = await mount(); + await act(async () => page.button('Check connection').click()); + await page.render('generation-1', '/another/agent'); + assert.doesNotMatch(page.document.body.textContent ?? '', /Connection successful/); +}); + +test('browser failure can retry with a fresh attempt and authenticate independently of check', async () => { + let count = 0; + const page = await mount({ + start: async (input) => + ++count === 1 + ? { ...input, phase: 'failed', failure: 'browser_failed' } + : { ...input, phase: 'succeeded' }, + }); + await act(async () => page.button('Sign in with Google').click()); + assert.match(page.document.body.textContent ?? '', /sign-in link could not be opened/i); + await act(async () => page.button('Retry').click()); + assert.equal(page.starts.length, 2); + assert.notEqual(page.starts[0].attemptId, page.starts[1].attemptId); + assert.equal(page.starts[1].action, 'login'); + assert.match(page.document.body.textContent ?? '', /Google sign-in verified for this attempt/); +}); + +test('clearing the saved configuration disables setup', async () => { + const page = await mount(); + await page.render('generation-1', ''); + assert.equal(page.button('Install').disabled, false); + assert.equal(page.button('Sign in with Google').disabled, true); + assert.equal(page.starts.length, 0); +}); + +test('changing configuration away and back still invalidates an older attempt', async () => { + let finish!: (value: ExternalAgentSetupProjection) => void; + const pending = new Promise((resolve) => { + finish = resolve; + }); + const page = await mount({ start: () => pending }); + await act(async () => page.button('Check connection').click()); + await page.render('generation-1', '/another/agent'); + await page.render('generation-1', '/agent/agy_acp_server.par'); + await act(async () => { + finish({ ...page.starts[0], phase: 'succeeded' }); + await pending; + }); + assert.doesNotMatch(page.document.body.textContent ?? '', /Connection successful/); +}); + +test('agent list uses a brand mark and opens a setup detail with a back action', async () => { + const page = await mount({ list: true }); + assert.equal(page.document.querySelectorAll('input').length, 0); + assert.match(page.document.querySelector('img')?.getAttribute('src') ?? '', /antigravity.svg/); + const row = [...page.document.querySelectorAll('button')].find((button) => + button.textContent?.includes('Antigravity'), + )!; + await act(async () => row.click()); + assert.equal(page.button('Check connection').disabled, false); + const back = page.document.querySelector( + 'button[aria-label="Back to external agents"]', + ); + assert.ok(back); + await act(async () => back.click()); + assert.equal(page.document.querySelectorAll('input').length, 0); +}); + +test('saved program exposes file selection without an advanced path editor', async () => { + const page = await mount(); + assert.equal(page.document.querySelectorAll('input').length, 0); + assert.equal(page.document.querySelector('details'), null); + assert.equal(page.button('Choose existing program').closest('details'), null); + assert.match(page.document.body.textContent ?? '', /Already have ACP/); + await act(async () => page.button('Choose existing program').click()); + assert.equal(page.document.querySelectorAll('input').length, 0); + assert.deepEqual(page.updates, ['/existing/agy_acp_server.par']); + assert.equal(page.starts.length, 0); +}); + +test('first setup offers managed install and an official source without exposing a path editor', async () => { + const page = await mount({ executable: '' }); + assert.match(page.document.body.textContent ?? '', /configure its path automatically/); + assert.ok(page.document.querySelector('a[href*="dl.google.com/agy-extensions/"]')); + assert.equal(page.document.querySelector('input'), null); + assert.equal(page.button('Install').disabled, false); + assert.equal(page.button('Choose existing program').disabled, false); + assert.equal(page.button('Sign in with Google').disabled, true); +}); + +test('installed output is saved through existing settings mutation, then connection becomes verified', async () => { + const path = '/managed/agy_acp_server.par'; + const page = await mount({ executable: '', start: async (input) => ({ ...input, phase: 'succeeded', installedExecutable: path }) }); + await act(async () => { page.button('Install').click(); page.button('Install').click(); }); + assert.equal(page.starts.length, 1); + assert.equal(page.starts[0].action, 'install'); + assert.equal(page.starts[0].expectedExecutable, ''); + assert.deepEqual(page.updates, [path]); + assert.deepEqual(page.updateGuards, [{ expectedExternalAgentExecutable: '' }]); + await page.render('generation-1', path); + assert.match(page.document.body.textContent ?? '', /Connection successful/); + assert.equal(page.button('Sign in with Google').disabled, false); +}); + +test('a late installed result never overwrites a newer saved configuration', async () => { + let finish!: (value: ExternalAgentSetupProjection) => void; + const pending = new Promise(r => { finish = r; }); + const page = await mount({ executable: '', start: () => pending }); + await act(async () => page.button('Install').click()); + await page.render('generation-1', '/chosen/agy_acp_server.par'); + await act(async () => { finish({ ...page.starts[0], phase: 'succeeded', installedExecutable: '/managed/agy_acp_server.par' }); await pending; }); + assert.deepEqual(page.updates, []); +}); + +test('choosing an existing executable saves it without installing', async () => { + const page = await mount(); + assert.equal(page.button('Choose existing program').closest('details'), null); + await act(async () => page.button('Choose existing program').click()); + assert.deepEqual(page.updates, ['/existing/agy_acp_server.par']); + assert.equal(page.document.querySelector('input'), null); + assert.deepEqual(page.starts, []); +}); diff --git a/apps/desktop/src/main/__tests__/runtime-host-client-operations.test.ts b/apps/desktop/src/main/__tests__/runtime-host-client-operations.test.ts index 9d0a0b5447..8f16a512c7 100644 --- a/apps/desktop/src/main/__tests__/runtime-host-client-operations.test.ts +++ b/apps/desktop/src/main/__tests__/runtime-host-client-operations.test.ts @@ -394,6 +394,33 @@ test('rebuilds a Runtime Policy mutation from each fresh CAS projection', async ); }); +test('stops a guarded Runtime Policy retry after its semantic basis changes', async () => { + const initial = createDefaultRuntimePolicy(); + const changed = { + ...initial, + externalAgents: { antigravity: { executable: '/chosen/by/another/client' } }, + }; + const { client, requests } = clientWithResponses([ + { revision: 1, policy: initial }, + { kind: 'revision_conflict', expectedRevision: 1, actualRevision: 2 }, + { revision: 2, policy: changed }, + ]); + + const result = await client.updateRuntimePolicyIf( + (policy) => policy.externalAgents.antigravity.executable === '', + () => ({ + kind: 'set_external_agents', + value: { antigravity: { executable: '/managed/agent' } }, + }), + ); + + assert.deepEqual(result, { revision: 2, policy: changed }); + assert.equal( + requests.filter(({ operation }) => operation === 'runtime.policy.mutate').length, + 1, + ); +}); + test('treats empty configuration patches as read-only lookups', async () => { const unlocked = session('session-1', 10, { connectionLocked: false }); const { client, requests } = clientWithResponses([ diff --git a/apps/desktop/src/main/__tests__/runtime-host-settings-ipc-main.test.ts b/apps/desktop/src/main/__tests__/runtime-host-settings-ipc-main.test.ts index 63bd715226..3901456cc9 100644 --- a/apps/desktop/src/main/__tests__/runtime-host-settings-ipc-main.test.ts +++ b/apps/desktop/src/main/__tests__/runtime-host-settings-ipc-main.test.ts @@ -145,6 +145,21 @@ function createModuleFixture(options: { policyRevision += 1; return { revision: policyRevision, policy }; }, + async updateRuntimePolicyIf( + accepts: (value: RuntimePolicy) => boolean, + createMutation: (value: RuntimePolicy) => { + kind: string; + value: RuntimePolicy["externalAgents"]; + }, + ) { + if (!accepts(policy)) return { revision: policyRevision, policy }; + const mutation = createMutation(policy); + if (mutation.kind === "set_external_agents") { + policy = { ...policy, externalAgents: mutation.value }; + } + policyRevision += 1; + return { revision: policyRevision, policy }; + }, async updateNetworkProxy(input: UpdateNetworkProxyInput) { if (input.expectedPolicyRevision !== policyRevision) { return { @@ -265,6 +280,22 @@ test("runtime settings project credential status without a password value", asyn assert.equal("password" in settings.network.proxy, false); }); +test("external agent update does not retry past a changed executable", async () => { + const fixture = createModuleFixture(); + + const unchanged = await fixture.module.update( + { externalAgents: { antigravity: { executable: "/managed/agent" } } }, + { expectedExternalAgentExecutable: "/changed/by/another/client" }, + ); + assert.equal(unchanged.externalAgents.antigravity.executable, ""); + + const committed = await fixture.module.update( + { externalAgents: { antigravity: { executable: "/managed/agent" } } }, + { expectedExternalAgentExecutable: "" }, + ); + assert.equal(committed.externalAgents.antigravity.executable, "/managed/agent"); +}); + test("spread-back derived and legacy password fields never enter Runtime policy", async () => { const fixture = createModuleFixture({ configured: true }); diff --git a/apps/desktop/src/main/external-agent-setup-ipc-main.ts b/apps/desktop/src/main/external-agent-setup-ipc-main.ts new file mode 100644 index 0000000000..cf1febd90a --- /dev/null +++ b/apps/desktop/src/main/external-agent-setup-ipc-main.ts @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + decodeExternalAgentSetupStart, + decodeExternalAgentSetupAttempt, +} from '@maka/runtime-host/protocol'; +import type { DesktopRuntimeHostClient } from './runtime-host-client.js'; +import { handleReconnectableRead, type ReconnectableReadIpcMain } from './ipc-reconnect-policy.js'; +import type { + RuntimeHostOAuthPresentation, + OAuthPresentationExpectation, +} from './runtime-host-oauth-presentation.js'; + +export function registerExternalAgentSetupIpc(deps: { + ipcMain: ReconnectableReadIpcMain; + client: Pick< + DesktopRuntimeHostClient, + 'startExternalAgentSetup' | 'queryExternalAgentSetup' | 'cancelExternalAgentSetup' + >; + presentation: RuntimeHostOAuthPresentation; + selectExecutable?: () => Promise; +}): void { + deps.ipcMain.handle('external-agents:select-executable', () => deps.selectExecutable?.()); + let pending: { id: string; expectation: OAuthPresentationExpectation } | undefined; + const clear = (id: string) => { + if (pending?.id !== id) return; + pending.expectation.cancel(); + pending = undefined; + }; + deps.ipcMain.handle('external-agents:setup:start', async (_event, raw: unknown) => { + const input = decodeExternalAgentSetupStart(raw); + if (input.action === 'login' && pending?.id !== input.attemptId) { + if (pending) throw new Error('Another external agent login is in progress'); + const login = { + id: input.attemptId, + expectation: deps.presentation.expect(input.attemptId, input.attemptId), + }; + pending = login; + const release = () => { + if (pending === login) clear(login.id); + }; + void login.expectation.presented.then(release, release); + } + try { + const result = await deps.client.startExternalAgentSetup(input); + if (['succeeded', 'failed', 'cancelled'].includes(result.phase)) clear(input.attemptId); + return result; + } catch (error) { + clear(input.attemptId); + throw error; + } + }); + handleReconnectableRead( + deps.ipcMain, + 'external-agents:setup:query', + async (_event, raw: unknown) => { + const { attemptId } = decodeExternalAgentSetupAttempt(raw); + // Renderer liveness renews this exact slot. A consumed or expired slot is + // never recreated, and an unrelated query cannot extend it. + if (pending?.id === attemptId) pending.expectation.renew(); + try { + const result = await deps.client.queryExternalAgentSetup(attemptId); + if (['succeeded', 'failed', 'cancelled'].includes(result.phase)) clear(attemptId); + return result; + } catch (error) { + clear(attemptId); + throw error; + } + }, + ); + deps.ipcMain.handle('external-agents:setup:cancel', async (_event, raw: unknown) => { + const { attemptId } = decodeExternalAgentSetupAttempt(raw); + clear(attemptId); + return deps.client.cancelExternalAgentSetup(attemptId); + }); +} diff --git a/apps/desktop/src/main/runtime-host-boot.ts b/apps/desktop/src/main/runtime-host-boot.ts index a13ffee8e2..5a95237d2e 100644 --- a/apps/desktop/src/main/runtime-host-boot.ts +++ b/apps/desktop/src/main/runtime-host-boot.ts @@ -237,6 +237,7 @@ import { createDesktopRuntimeHostOnboarding } from "./runtime-host-onboarding.js import { createDesktopRuntimeHostManagement } from "./runtime-host-management.js"; import { createDesktopRuntimeHostLocalManagement } from './runtime-host-local-management.js'; import { createDesktopRuntimeHostPeerMeshManagement } from './runtime-host-peer-mesh-management.js'; +import { registerExternalAgentSetupIpc } from "./external-agent-setup-ipc-main.js"; import { registerRuntimeHostOAuthIpc } from "./runtime-host-oauth-ipc-main.js"; import { RuntimeHostOAuthPresentation } from "./runtime-host-oauth-presentation.js"; import { registerRuntimeHostPermissionsIpc } from "./runtime-host-permissions-ipc-main.js"; @@ -1642,6 +1643,12 @@ function registerHostClientIpc( mainWindowController, showItemInFolder: (path) => shell.showItemInFolder(path), }); + registerExternalAgentSetupIpc({ ipcMain: scopedIpc, client, presentation: oauthPresentation, + selectExecutable: async () => { + const result = await mainWindowController.showOpenDialog({ properties: ['openFile'] }); + return result.canceled ? undefined : result.filePaths[0]; + }, + }); registerRuntimeHostOAuthIpc({ ipcMain: scopedIpc, client, diff --git a/apps/desktop/src/main/runtime-host-client.ts b/apps/desktop/src/main/runtime-host-client.ts index 0b877254c3..1bf8458f62 100644 --- a/apps/desktop/src/main/runtime-host-client.ts +++ b/apps/desktop/src/main/runtime-host-client.ts @@ -434,9 +434,17 @@ export class DesktopRuntimeHostClient { async updateRuntimePolicy( buildOperation: (policy: RuntimePolicy) => RuntimePolicyMutation, + ): Promise> { + return this.updateRuntimePolicyIf(() => true, buildOperation); + } + + async updateRuntimePolicyIf( + accepts: (policy: RuntimePolicy) => boolean, + buildOperation: (policy: RuntimePolicy) => RuntimePolicyMutation, ): Promise> { for (let attempt = 0; attempt < MAX_OPTIMISTIC_ATTEMPTS; attempt += 1) { const current = await this.queryRuntimePolicy(); + if (!accepts(current.policy)) return current; const result = await this.request("runtime.policy.mutate", { expectedRevision: current.revision, operation: buildOperation(current.policy), @@ -546,6 +554,18 @@ export class DesktopRuntimeHostClient { return this.request("connection.onboarding.save", input); } + startExternalAgentSetup(input: OperationInput<"external_agents.setup.start">): Promise> { + return this.request("external_agents.setup.start", input); + } + + queryExternalAgentSetup(attemptId: string): Promise> { + return this.request("external_agents.setup.query", { attemptId }); + } + + cancelExternalAgentSetup(attemptId: string): Promise> { + return this.request("external_agents.setup.cancel", { attemptId }); + } + startOAuthLogin( attemptId: string, target: OperationInput<"oauth.login.start">["target"], diff --git a/apps/desktop/src/main/runtime-host-oauth-presentation.ts b/apps/desktop/src/main/runtime-host-oauth-presentation.ts index 779e8e3a0e..55f4e726a2 100644 --- a/apps/desktop/src/main/runtime-host-oauth-presentation.ts +++ b/apps/desktop/src/main/runtime-host-oauth-presentation.ts @@ -27,6 +27,7 @@ export interface OAuthExternalPresentation { export interface OAuthPresentationExpectation { readonly presented: Promise; + renew(): void; cancel(reason?: unknown): void; } @@ -36,7 +37,7 @@ export class RuntimeHostOAuthPresentation implements OAuthPresentationBackend { constructor(private readonly openSystemBrowser: (url: string) => Promise) {} - expect(attemptId: string): OAuthPresentationExpectation { + expect(attemptId: string, expectedStateHint?: string): OAuthPresentationExpectation { if (this.#pending) throw new Error('Another OAuth login is already in progress'); let resolvePresented!: (presentation: OAuthExternalPresentation) => void; let rejectPresented!: (reason?: unknown) => void; @@ -48,13 +49,15 @@ export class RuntimeHostOAuthPresentation implements OAuthPresentationBackend { // The timeout can fire before waitForPresentation attaches. Keep a no-op // handler; the real waiter still observes the same rejection. void presented.catch(() => undefined); - const timer = setTimeout(() => { - if (this.#pending?.attemptId !== attemptId) return; + const expire = () => { + if (this.#pending !== pending) return; this.#pending = undefined; rejectPresented(new Error('Runtime Host did not present OAuth authorization')); - }, PRESENTATION_TIMEOUT_MS); + }; + let timer = setTimeout(expire, PRESENTATION_TIMEOUT_MS); const pending: PendingPresentation = { attemptId, + expectedStateHint, resolve: (presentation) => { clearTimeout(timer); presentedSettled = true; @@ -70,6 +73,11 @@ export class RuntimeHostOAuthPresentation implements OAuthPresentationBackend { this.#pending = pending; return { presented, + renew: () => { + if (this.#pending !== pending) return; + clearTimeout(timer); + timer = setTimeout(expire, PRESENTATION_TIMEOUT_MS); + }, cancel: (reason = new Error('OAuth presentation cancelled')) => { if (this.#pending === pending) pending.reject(reason); }, @@ -86,6 +94,9 @@ export class RuntimeHostOAuthPresentation implements OAuthPresentationBackend { if (!pending || !stateHint) { throw new Error('Desktop has no matching OAuth presentation request'); } + if (pending.expectedStateHint !== undefined && pending.expectedStateHint !== stateHint) { + throw new Error('Desktop OAuth presentation belongs to another attempt'); + } try { await this.openSystemBrowser(url); signal.throwIfAborted(); @@ -103,6 +114,7 @@ export class RuntimeHostOAuthPresentation implements OAuthPresentationBackend { interface PendingPresentation { readonly attemptId: string; + readonly expectedStateHint?: string; resolve(presentation: OAuthExternalPresentation): void; reject(reason?: unknown): void; } diff --git a/apps/desktop/src/main/runtime-host-settings-ipc-main.ts b/apps/desktop/src/main/runtime-host-settings-ipc-main.ts index 369ec810e0..1afdb3dbd0 100644 --- a/apps/desktop/src/main/runtime-host-settings-ipc-main.ts +++ b/apps/desktop/src/main/runtime-host-settings-ipc-main.ts @@ -20,6 +20,7 @@ import type { AppSettings, RuntimeHostAppSettings, + RuntimeHostSettingsUpdateGuard, SettingsTestResult, UpdateAppSettingsInput, UpdateAppSettingsResult, @@ -59,6 +60,7 @@ type RuntimeHostSettingsClient = Pick< | "testNetworkProxy" | "updateNetworkProxy" | "updateRuntimePolicy" + | "updateRuntimePolicyIf" >; const PROXY_CREDENTIAL: CredentialLocator = { @@ -85,7 +87,10 @@ export type RuntimeHostSettingsModuleDeps = Omit< export interface RuntimeHostSettingsModule { get(): Promise; - update(patch: UpdateAppSettingsInput): Promise; + update( + patch: UpdateAppSettingsInput, + guard?: RuntimeHostSettingsUpdateGuard, + ): Promise; testNetworkProxy(input?: TestProxyInput): Promise; } @@ -132,9 +137,9 @@ export function createRuntimeHostSettingsModule( const module: RuntimeHostSettingsModule = { get: () => enqueue(() => loadRuntimeHostSettingsWithoutLane(deps)), - update: (patch) => + update: (patch, guard) => enqueue(() => - updateRuntimeHostSettingsForImportWithoutLane(deps, patch).then( + updateRuntimeHostSettingsForImportWithoutLane(deps, patch, guard).then( (result) => result.settings, ), ), @@ -188,8 +193,9 @@ export function registerRuntimeHostSettingsIpc( async ( _event, patch: UpdateAppSettingsInput, + guard?: RuntimeHostSettingsUpdateGuard, ): Promise> => { - const settings = await module.update(patch); + const settings = await module.update(patch, guard); return buildSettingsUpdateResult(settings, patch); }, ); @@ -282,6 +288,7 @@ async function loadRuntimeHostSettingsWithoutLane( workspaceInstructions: policy.workspaceInstructions, privacy: policy.privacy, chatDefaults: policy.chatDefaults, + externalAgents: policy.externalAgents, shell: policy.shell, webSearch: { ...local.webSearch, @@ -297,9 +304,10 @@ async function loadRuntimeHostSettingsWithoutLane( async function updateRuntimeHostSettingsForImportWithoutLane( deps: RuntimeHostSettingsModuleDeps, patch: UpdateAppSettingsInput, + guard?: RuntimeHostSettingsUpdateGuard, ): Promise { validateProxyPatch(patch.network?.proxy); - const skippedCredentials = await applyHostPatchWithoutLane(deps.client, patch); + const skippedCredentials = await applyHostPatchWithoutLane(deps.client, patch, guard); const clientPatch = clientOwnedSettingsPatch(patch); const local = hasSettingsPatch(clientPatch) ? await deps.settingsStore.update(clientPatch) @@ -336,6 +344,7 @@ function projectWebSearchCredential( async function applyHostPatchWithoutLane( client: RuntimeHostSettingsClient, patch: UpdateAppSettingsInput, + guard?: RuntimeHostSettingsUpdateGuard, ): Promise { let skippedCredentials = 0; if (patch.network?.proxy) { @@ -380,6 +389,22 @@ async function applyHostPatchWithoutLane( "set_chat_defaults", ); } + if (patch.externalAgents) { + const mutation = () => ({ + kind: "set_external_agents" as const, + value: patch.externalAgents!, + }); + if (guard?.expectedExternalAgentExecutable === undefined) { + await client.updateRuntimePolicy(mutation); + } else { + await client.updateRuntimePolicyIf( + (policy) => + policy.externalAgents.antigravity.executable === + guard.expectedExternalAgentExecutable, + mutation, + ); + } + } if (patch.shell) { await mergePolicy(client, "shell", patch.shell, "set_shell"); } diff --git a/apps/desktop/src/preload/bridge-contract.d.ts b/apps/desktop/src/preload/bridge-contract.d.ts index 00791158b8..6a2a61e56e 100644 --- a/apps/desktop/src/preload/bridge-contract.d.ts +++ b/apps/desktop/src/preload/bridge-contract.d.ts @@ -33,6 +33,7 @@ import type { AppIconTarget, AppSettings, RuntimeHostAppSettings, + RuntimeHostSettingsUpdateGuard, ChatDefaultsSettings, SettingsTestResult, UpdateAppSettingsInput, @@ -1450,11 +1451,21 @@ export interface MakaBridge { logout(serverId: string, host?: DesktopRuntimeHostRef): Promise; subscribeChanges(handler: (statuses: McpServerStatus[]) => void): () => void; }; + externalAgents: { + selectExecutable(host: DesktopRuntimeHostRef): Promise; + start(input: OperationInput<'external_agents.setup.start'>, host: DesktopRuntimeHostRef): Promise>; + query(attemptId: string, host: DesktopRuntimeHostRef): Promise>; + cancel(attemptId: string, host: DesktopRuntimeHostRef): Promise>; + }; settings: { getClient(): Promise; get(host?: DesktopRuntimeHostRef): Promise; updateClient(patch: UpdateAppSettingsInput): Promise; - update(patch: UpdateAppSettingsInput, host?: DesktopRuntimeHostRef): Promise>; + update( + patch: UpdateAppSettingsInput, + host?: DesktopRuntimeHostRef, + guard?: RuntimeHostSettingsUpdateGuard, + ): Promise>; subscribeClientChanged(handler: () => void): () => void; subscribeExternalChanged(handler: () => void, host?: DesktopRuntimeHostRef): () => void; testNetworkProxy(input?: TestProxyInput, host?: DesktopRuntimeHostRef): Promise; diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts index 3b85dc55c6..4f1fd3603f 100644 --- a/apps/desktop/src/preload/preload.ts +++ b/apps/desktop/src/preload/preload.ts @@ -120,6 +120,7 @@ import type { AppIconTarget, AppSettings, RuntimeHostAppSettings, + RuntimeHostSettingsUpdateGuard, SettingsTestResult, UpdateAppSettingsInput, UpdateAppSettingsResult, @@ -3311,6 +3312,12 @@ const makaBridge = { ); }, }, + externalAgents: { + selectExecutable(host) { return invokeSelectedRuntimeHost(host, 'external-agents:select-executable'); }, + start(input, host) { return invokeSelectedRuntimeHost(host, 'external-agents:setup:start', input); }, + query(attemptId, host) { return invokeSelectedRuntimeHost(host, 'external-agents:setup:query', { attemptId }); }, + cancel(attemptId, host) { return invokeSelectedRuntimeHost(host, 'external-agents:setup:cancel', { attemptId }); }, + }, settings: { getClient(): Promise { return ipcRenderer.invoke('settings:client:get'); @@ -3321,8 +3328,12 @@ const makaBridge = { updateClient(patch: UpdateAppSettingsInput): Promise { return ipcRenderer.invoke('settings:client:update', patch); }, - update(patch: UpdateAppSettingsInput, host?: DesktopRuntimeHostRef): Promise> { - return invokeSelectedRuntimeHost(host, 'settings:update', patch); + update( + patch: UpdateAppSettingsInput, + host?: DesktopRuntimeHostRef, + guard?: RuntimeHostSettingsUpdateGuard, + ): Promise> { + return invokeSelectedRuntimeHost(host, 'settings:update', patch, guard); }, subscribeClientChanged(handler: () => void): () => void { const listener = () => handler(); diff --git a/apps/desktop/src/renderer/application/contracts/settings-presentation/action-guard.ts b/apps/desktop/src/renderer/application/contracts/settings-presentation/action-guard.ts new file mode 100644 index 0000000000..6469751ab1 --- /dev/null +++ b/apps/desktop/src/renderer/application/contracts/settings-presentation/action-guard.ts @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// Framework-free keyed one-shot action guard: the multi-latch sibling of +// oauth-login-flow-guard.ts's createOneShotActionGuard for components that +// hold several independent action latches at once (the connection detail +// sheet's six mutually excluding actions and the memory controller's per-row +// action keys). Kept React-free so its behavior is +// unit-testable without a DOM (see action-guard.test.ts) and so the desktop +// test runner can import it without pulling React into its program. +// +// The check stays synchronous — a second concurrent action is rejected before +// React can re-render the disabled button, never subject to render batching. +export interface KeyedActionGuard { + /** Acquire `key`; returns its release function, or null when already held. */ + begin(key: Key): (() => void) | null; + /** Acquire `key` only while no action is in flight; otherwise null. */ + beginExclusive(key: Key): (() => void) | null; + has(key: Key): boolean; + /** Count of in-flight actions, for cross-action exclusion checks. */ + readonly size: number; + /** Drop every hold (teardown). In-flight releases stay safe: see below. */ + reset(): void; +} + +export function createKeyedActionGuard(): KeyedActionGuard { + // key -> owner token. The release closure only drops its own token, so a + // late release settling after reset() + a newer acquire of the same key + // cannot strip the newer action's hold after a StrictMode remount. Tokens + // are monotonic for the guard's lifetime, never + // reused after reset. + const owners = new Map(); + let sequence = 0; + + function acquire(key: Key): () => void { + const owner = ++sequence; + owners.set(key, owner); + return () => { + if (owners.get(key) === owner) owners.delete(key); + }; + } + + return { + begin(key: Key): (() => void) | null { + if (owners.has(key)) return null; + return acquire(key); + }, + beginExclusive(key: Key): (() => void) | null { + if (owners.size > 0) return null; + return acquire(key); + }, + has(key: Key): boolean { + return owners.has(key); + }, + get size(): number { + return owners.size; + }, + reset(): void { + owners.clear(); + }, + }; +} diff --git a/apps/desktop/src/renderer/application/contracts/settings-presentation/index.ts b/apps/desktop/src/renderer/application/contracts/settings-presentation/index.ts new file mode 100644 index 0000000000..4a7399cc40 --- /dev/null +++ b/apps/desktop/src/renderer/application/contracts/settings-presentation/index.ts @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export * from "./settings-section.js"; +export * from "./runtime-host-settings-target.js"; +export * from "./action-guard.js"; +export * from "./oauth-login-flow-guard.js"; +export * from "./use-action-guard.js"; diff --git a/apps/desktop/src/renderer/application/contracts/settings-presentation/oauth-login-flow-guard.ts b/apps/desktop/src/renderer/application/contracts/settings-presentation/oauth-login-flow-guard.ts new file mode 100644 index 0000000000..bbcb03b052 --- /dev/null +++ b/apps/desktop/src/renderer/application/contracts/settings-presentation/oauth-login-flow-guard.ts @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// Framework-free primitives behind useOAuthLoginFlow's async safety. Kept in a +// React-free module so their behavior is unit-testable without a DOM (see +// oauth-login-flow-guard.test.ts) and so the desktop test runner can import +// them without pulling React into its program. + +// Synchronous one-shot action guard: rejects a second concurrent action before +// React can re-render the disabled button. A plain closure (held in a ref by +// the hook) so the check is synchronous, not subject to render batching. +export interface OneShotActionGuard { + begin(action: Action): boolean; + finish(): void; + readonly current: Action | null; +} + +export function createOneShotActionGuard(): OneShotActionGuard { + let current: Action | null = null; + return { + begin(action: Action): boolean { + if (current !== null) return false; + current = action; + return true; + }, + finish(): void { + current = null; + }, + get current(): Action | null { + return current; + }, + }; +} + +// Cancel-on-unmount primitive: cancels a still-pending authorization request +// and clears the holder so a late resolution cannot re-cancel it. No-ops when +// nothing is pending. +export function teardownPendingAuthorization( + holder: { current: string | null }, + cancelAuthorization: (authRequestId: string) => void, +): void { + const pendingAuthRequestId = holder.current; + holder.current = null; + if (pendingAuthRequestId) cancelAuthorization(pendingAuthRequestId); +} diff --git a/apps/desktop/src/renderer/application/contracts/settings-presentation/runtime-host-settings-target.tsx b/apps/desktop/src/renderer/application/contracts/settings-presentation/runtime-host-settings-target.tsx new file mode 100644 index 0000000000..28ca53082b --- /dev/null +++ b/apps/desktop/src/renderer/application/contracts/settings-presentation/runtime-host-settings-target.tsx @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + createContext, + Fragment, + useCallback, + useContext, + useMemo, + type ReactNode, +} from "react"; +import { useToast } from "@maka/ui"; +export interface SettingsHostTarget { readonly profileId: string; readonly hostId: string; } + +interface RuntimeHostSettingsTargetValue { + readonly host: SettingsHostTarget; + /** + * Changes when Desktop replaces the selected Host without changing its + * renderer-facing profileId:hostId pair. Host-owned sub-authorities use this + * key to retire their own async work without remounting the Settings page. + */ + readonly generationKey: string; +} + +const RuntimeHostSettingsTargetContext = + createContext(null); + +export function RuntimeHostSettingsTarget(props: { + readonly host?: SettingsHostTarget; + readonly generation?: string; + readonly children: ReactNode; +}) { + const value = useMemo(() => { + if (!props.host) return null; + return { + host: props.host, + generationKey: + `${props.host.profileId}:${props.host.hostId}@${props.generation ?? "unversioned"}`, + }; + }, [props.generation, props.host]); + return ( + + {props.children} + + ); +} + +export function useRuntimeHostSettingsTarget(): SettingsHostTarget { + const target = useContext(RuntimeHostSettingsTargetContext); + if (!target) throw new Error("Runtime Host Settings target is unavailable"); + return target.host; +} + +export function useOptionalRuntimeHostSettingsTarget(): SettingsHostTarget | undefined { + return useContext(RuntimeHostSettingsTargetContext)?.host; +} + +export function useRuntimeHostSettingsGenerationKey(): string { + const target = useContext(RuntimeHostSettingsTargetContext); + if (!target) throw new Error("Runtime Host Settings target is unavailable"); + return target.generationKey; +} + +/** + * Retires only the Host-owned controller below this boundary when the selected + * Runtime Host enters a new lifecycle generation. Parent route, draft, scroll, + * and focus state remain owned by their existing Settings components. + */ +export function RuntimeHostSettingsGenerationBoundary(props: { + readonly children: ReactNode; +}) { + const generationKey = useRuntimeHostSettingsGenerationKey(); + return {props.children}; +} + +export function useRuntimeHostSettingsErrorReporter() { + const host = useRuntimeHostSettingsTarget(); + const toast = useToast(); + return useCallback( + (title: string, description?: string) => + toast.error(title, description, undefined, { profileId: host.profileId }), + [host.profileId, toast], + ); +} diff --git a/apps/desktop/src/renderer/application/contracts/settings-presentation/settings-route-header.tsx b/apps/desktop/src/renderer/application/contracts/settings-presentation/settings-route-header.tsx new file mode 100644 index 0000000000..3cd6912469 --- /dev/null +++ b/apps/desktop/src/renderer/application/contracts/settings-presentation/settings-route-header.tsx @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// The header of a settings sub-level: back affordance, title, and one quiet +// line of context. +// +// Deliberately a `Toolbar` with everything in `startContent`: the back button, +// the optional logo, and the title block read as one left-aligned cluster, so +// the title sits where the list's rows started and the eye does not travel. +// Modelled on the settings-sidebar template's detail view, which puts this +// same Toolbar inside the content area rather than reaching for a second page +// shell. +import type { ReactNode } from 'react'; +import { Heading, HStack, IconButton, Text, Toolbar, VStack } from '@astryxdesign/core'; +import { ICON_SIZE, ArrowLeft } from '@maka/ui/icons'; + +export function SettingsRouteHeader(props: { + onBack(): void; + backLabel: string; + /** True while a write is in flight: leaving would discard the draft. */ + isBackDisabled?: boolean; + logo?: ReactNode; + title: string; + /** Wire the level's `aria-labelledby` to this heading, so it is announced. */ + titleId?: string; + badge?: ReactNode; + subtitle?: string; +}) { + return ( + +