From 526c8257c1b6359c3de32ea8323090d042276bd0 Mon Sep 17 00:00:00 2001 From: sungl <81428141+Sun-GLiang@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:33:10 +0800 Subject: [PATCH 01/15] feat(desktop): configure Antigravity ACP through Settings Reuse RuntimePolicy, Host setup operations and OAuth presentation for local macOS arm64 connection checks and Google sign-in. Add process cleanup, setup safeguards and branded Settings UI. Record the official account eligibility blocker for successful-login acceptance. Generated-by: Codex --- apps/desktop/renderer-architecture.json | 55 +-- .../licenses/npm/THIRD_PARTY_NOTICES.txt | 199 +++++++++ .../external-agent-setup-ipc.test.ts | 93 +++++ .../external-agents-settings-page.test.ts | 307 ++++++++++++++ .../src/main/external-agent-setup-ipc-main.ts | 83 ++++ apps/desktop/src/main/runtime-host-boot.ts | 2 + apps/desktop/src/main/runtime-host-client.ts | 12 + .../main/runtime-host-oauth-presentation.ts | 7 +- .../main/runtime-host-settings-ipc-main.ts | 4 + apps/desktop/src/preload/bridge-contract.d.ts | 5 + apps/desktop/src/preload/preload.ts | 5 + .../settings-presentation/action-guard.ts | 78 ++++ .../contracts/settings-presentation/index.ts | 24 ++ .../oauth-login-flow-guard.ts | 61 +++ .../runtime-host-settings-target.tsx | 100 +++++ .../settings-expandable-row.tsx | 173 ++++++++ .../settings-route-header.tsx | 73 ++++ .../settings-section.tsx | 190 +++++++++ .../settings-presentation/use-action-guard.ts | 75 ++++ .../assets/provider-brands/antigravity.svg | 1 + .../composition/desktop-feature-services.tsx | 5 + .../features/external-agent-settings/index.ts | 22 + .../features/external-agent-settings/page.tsx | 380 ++++++++++++++++++ .../external-agent-settings/services.ts | 43 ++ .../locales/settings-external-agents-copy.ts | 202 ++++++++++ .../locales/settings-navigation-copy.ts | 3 + .../src/renderer/locales/shell-copy.ts | 2 + ...create-external-agent-settings-services.ts | 45 +++ .../renderer/public/THIRD_PARTY_LICENSES.txt | 4 + .../src/renderer/settings/action-guard.ts | 60 +-- .../settings/oauth-login-flow-guard.ts | 43 +- .../settings/runtime-host-settings-target.tsx | 82 +--- .../settings/settings-expandable-row.tsx | 155 +------ .../src/renderer/settings/settings-nav.ts | 2 + .../settings/settings-route-header.tsx | 55 +-- .../renderer/settings/settings-section.tsx | 172 +------- .../renderer/settings/settings-surface.tsx | 5 +- .../src/renderer/settings/use-action-guard.ts | 57 +-- apps/desktop/src/shared/settings-ownership.ts | 1 + docs/antigravity-acp-settings.md | 51 +++ docs/images/pr/antigravity-agent-list.png | Bin 0 -> 499599 bytes docs/images/pr/antigravity-agent-setup.png | Bin 0 -> 600406 bytes package-lock.json | 1 + packages/core/src/runtime-policy.ts | 4 + .../core/src/runtime-policy/policy-codec.ts | 44 +- packages/core/src/settings.ts | 14 + packages/runtime-host/package.json | 1 + .../src/__tests__/external-agent-acp.test.ts | 236 +++++++++++ .../external-agent-setup-coordinator.test.ts | 233 +++++++++++ .../src/protocol/external-agent-setup.ts | 164 ++++++++ packages/runtime-host/src/protocol/index.ts | 2 +- .../runtime-host/src/protocol/operations.ts | 3 + .../src/server/acp/antigravity.ts | 171 ++++++++ .../runtime-host/src/server/acp/connection.ts | 127 ++++++ .../src/server/execution-composition.ts | 19 +- .../external-agent-setup-coordinator.ts | 207 ++++++++++ .../__tests__/runtime-policy-stores.test.ts | 42 +- .../src/runtime-policy/policy-document.ts | 15 +- 58 files changed, 3559 insertions(+), 660 deletions(-) create mode 100644 apps/desktop/src/main/__tests__/external-agent-setup-ipc.test.ts create mode 100644 apps/desktop/src/main/__tests__/external-agents-settings-page.test.ts create mode 100644 apps/desktop/src/main/external-agent-setup-ipc-main.ts create mode 100644 apps/desktop/src/renderer/application/contracts/settings-presentation/action-guard.ts create mode 100644 apps/desktop/src/renderer/application/contracts/settings-presentation/index.ts create mode 100644 apps/desktop/src/renderer/application/contracts/settings-presentation/oauth-login-flow-guard.ts create mode 100644 apps/desktop/src/renderer/application/contracts/settings-presentation/runtime-host-settings-target.tsx create mode 100644 apps/desktop/src/renderer/application/contracts/settings-presentation/settings-expandable-row.tsx create mode 100644 apps/desktop/src/renderer/application/contracts/settings-presentation/settings-route-header.tsx create mode 100644 apps/desktop/src/renderer/application/contracts/settings-presentation/settings-section.tsx create mode 100644 apps/desktop/src/renderer/application/contracts/settings-presentation/use-action-guard.ts create mode 100644 apps/desktop/src/renderer/assets/provider-brands/antigravity.svg create mode 100644 apps/desktop/src/renderer/features/external-agent-settings/index.ts create mode 100644 apps/desktop/src/renderer/features/external-agent-settings/page.tsx create mode 100644 apps/desktop/src/renderer/features/external-agent-settings/services.ts create mode 100644 apps/desktop/src/renderer/locales/settings-external-agents-copy.ts create mode 100644 apps/desktop/src/renderer/platform/desktop/create-external-agent-settings-services.ts create mode 100644 docs/antigravity-acp-settings.md create mode 100644 docs/images/pr/antigravity-agent-list.png create mode 100644 docs/images/pr/antigravity-agent-setup.png create mode 100644 packages/runtime-host/src/__tests__/external-agent-acp.test.ts create mode 100644 packages/runtime-host/src/__tests__/external-agent-setup-coordinator.test.ts create mode 100644 packages/runtime-host/src/protocol/external-agent-setup.ts create mode 100644 packages/runtime-host/src/server/acp/antigravity.ts create mode 100644 packages/runtime-host/src/server/acp/connection.ts create mode 100644 packages/runtime-host/src/server/external-agent-setup-coordinator.ts diff --git a/apps/desktop/renderer-architecture.json b/apps/desktop/renderer-architecture.json index d24cb05c29..02251af046 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", @@ -1624,6 +1625,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": {}, @@ -2312,15 +2322,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": { @@ -3475,17 +3475,12 @@ "src/renderer/settings/settings-expandable-row.tsx": { "bridgePaths": {}, "environmentCapabilities": {}, - "hookCalls": { - "useEffect": 1, - "useRef": 3 - }, + "hookCalls": {}, "lifecycleMethods": {}, "unresolvedDependencies": 0, "actionFactories": [], "dependencyPaths": { - "./settings-section": 1, - "@astryxdesign/core": 1, - "react": 1 + "../application/contracts/settings-presentation/settings-expandable-row.js": 1 } }, "src/renderer/settings/settings-modal.tsx": { @@ -3563,8 +3558,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 +3580,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 +3662,7 @@ "../../shared/settings-ownership.js": 1, "../browser-storage": 1, "../features/connection-settings": 1, + "../features/external-agent-settings/index.js": 1, "../locales/settings-navigation-copy.js": 1, "../locales/settings-shared-copy.js": 1, "./about-settings-page": 1, @@ -3817,17 +3811,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..22a99a0716 --- /dev/null +++ b/apps/desktop/src/main/__tests__/external-agent-setup-ipc.test.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 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({ + 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); + await invoke('external-agents:setup:start', input); + assert.equal(attempts, 1); + assert.equal(opened.length, 1); + 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(); +}); 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..53096e4442 --- /dev/null +++ b/apps/desktop/src/main/__tests__/external-agents-settings-page.test.ts @@ -0,0 +1,307 @@ +/* + * 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 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: { + 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 () => ({ settings }), + }), + }), + }), + }), + }), + ), + ); + }; + 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, + 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 completed|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 completed/); +}); +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 completed/); +}); + +test('clearing the saved configuration disables setup', async () => { + const page = await mount(); + await page.render('generation-1', ''); + assert.equal(page.button('Check connection').disabled, true); + 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 uses the model detail edit row and disables setup while editing', async () => { + const page = await mount(); + assert.equal(page.document.querySelectorAll('input').length, 0); + assert.match(page.document.body.textContent ?? '', /Program path/); + await act(async () => page.button('Change').click()); + assert.equal(page.document.querySelector('input')?.value, '/agent/agy_acp_server.par'); + assert.equal(page.button('Check connection').disabled, true); + assert.equal(page.button('Sign in with Google').disabled, true); + await act(async () => page.button('Cancel').click()); + assert.equal(page.document.querySelectorAll('input').length, 0); + assert.equal(page.button('Check connection').disabled, false); + assert.equal(page.starts.length, 0); +}); + +test('first setup explains the separate program and offers the official download', async () => { + const page = await mount({ executable: '' }); + assert.match(page.document.body.textContent ?? '', /desktop app alone is not enough/); + const download = page.document.querySelector('a[href*="dl.google.com/agy-extensions/"]'); + assert.ok(download); + assert.match(download.textContent ?? '', /macOS Apple Silicon/); + assert.ok(page.document.querySelector('input')); + assert.equal(page.button('Save').disabled, true); + assert.equal(page.button('Check connection').disabled, true); + assert.equal(page.button('Sign in with Google').disabled, 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..d83772b4d1 --- /dev/null +++ b/apps/desktop/src/main/external-agent-setup-ipc-main.ts @@ -0,0 +1,83 @@ +/* + * 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; +}): void { + 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'); + pending = { + id: input.attemptId, + expectation: deps.presentation.expect(input.attemptId, input.attemptId), + }; + } + 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); + 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 df1792febf..efb4b14a75 100644 --- a/apps/desktop/src/main/runtime-host-boot.ts +++ b/apps/desktop/src/main/runtime-host-boot.ts @@ -236,6 +236,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"; @@ -1634,6 +1635,7 @@ function registerHostClientIpc( mainWindowController, showItemInFolder: (path) => shell.showItemInFolder(path), }); + registerExternalAgentSetupIpc({ ipcMain: scopedIpc, client, presentation: oauthPresentation }); 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 7fcf4a57e8..9c319284bc 100644 --- a/apps/desktop/src/main/runtime-host-client.ts +++ b/apps/desktop/src/main/runtime-host-client.ts @@ -546,6 +546,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..59a1c537ee 100644 --- a/apps/desktop/src/main/runtime-host-oauth-presentation.ts +++ b/apps/desktop/src/main/runtime-host-oauth-presentation.ts @@ -36,7 +36,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; @@ -55,6 +55,7 @@ export class RuntimeHostOAuthPresentation implements OAuthPresentationBackend { }, PRESENTATION_TIMEOUT_MS); const pending: PendingPresentation = { attemptId, + expectedStateHint, resolve: (presentation) => { clearTimeout(timer); presentedSettled = true; @@ -86,6 +87,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 +107,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..35e59574ee 100644 --- a/apps/desktop/src/main/runtime-host-settings-ipc-main.ts +++ b/apps/desktop/src/main/runtime-host-settings-ipc-main.ts @@ -282,6 +282,7 @@ async function loadRuntimeHostSettingsWithoutLane( workspaceInstructions: policy.workspaceInstructions, privacy: policy.privacy, chatDefaults: policy.chatDefaults, + externalAgents: policy.externalAgents, shell: policy.shell, webSearch: { ...local.webSearch, @@ -380,6 +381,9 @@ async function applyHostPatchWithoutLane( "set_chat_defaults", ); } + if (patch.externalAgents) { + await client.updateRuntimePolicy(() => ({ kind: "set_external_agents", value: patch.externalAgents! })); + } 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 e389b888b4..bb13be727e 100644 --- a/apps/desktop/src/preload/bridge-contract.d.ts +++ b/apps/desktop/src/preload/bridge-contract.d.ts @@ -1400,6 +1400,11 @@ export interface MakaBridge { logout(serverId: string, host?: DesktopRuntimeHostRef): Promise; subscribeChanges(handler: (statuses: McpServerStatus[]) => void): () => void; }; + externalAgents: { + 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; diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts index f3c89333c6..855a9fdcbd 100644 --- a/apps/desktop/src/preload/preload.ts +++ b/apps/desktop/src/preload/preload.ts @@ -3236,6 +3236,11 @@ const makaBridge = { ); }, }, + externalAgents: { + 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'); 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-expandable-row.tsx b/apps/desktop/src/renderer/application/contracts/settings-presentation/settings-expandable-row.tsx new file mode 100644 index 0000000000..8605fffb2d --- /dev/null +++ b/apps/desktop/src/renderer/application/contracts/settings-presentation/settings-expandable-row.tsx @@ -0,0 +1,173 @@ +/* + * 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 { useEffect, useRef, type ReactNode } from 'react'; +import { Button, HStack, Text } from '@astryxdesign/core'; +import { SettingsField, SettingsRow } from './settings-section.js'; + +/** + * A settled value that becomes a form only when the user asks it to. + * + * The shape is Astryx's own — the `settings-sidebar` template's ExpandableRow + * (`@astryxdesign/cli/templates/pages/settings-sidebar/page.tsx:140-193`): a + * row reports its label and current value with one affordance to change it, + * and swaps in place for the editor plus Save / Cancel. At most one row in a + * group is open at a time, which is the caller's `expandedRow` state. + * + * The shape is copied; the template's implementation is not, because it has + * three problems this component exists to not have: + * + * 1. The template's trigger is `` with `preventDefault`. That + * announces itself as a link, ignores Space, and points nowhere. Opening a + * form is a button. + * + * 2. The template has no focus management at all. Expanding moves focus into + * the editor here, and Save / Cancel return it to the trigger the user came + * from — otherwise collapsing drops focus to the top of the document and a + * keyboard user loses their place in the list. + * + * 3. The template's Cancel only closes; its fields edit live, so there is + * nothing to discard. Ours is a real discard: the caller reverts its draft + * in `onCancel`, which is what makes Cancel mean anything. + * + * Built on `SettingsRow` rather than a bare HStack so the collapsed row keeps + * the Item vocabulary the rest of the surface uses — the `settingsRowEnd` + * width ceiling and the container queries in rows.css apply here too. The + * expanded editor sits in a `SettingsField`, the same full-width block a + * permanently-open input would use. + */ +export function SettingsExpandableRow(props: { + label: ReactNode; + assistantTarget?: string; + /** The settled value, shown while collapsed. */ + value: ReactNode; + /** Label for the affordance that opens the editor (更改 / 设置 / 编辑). + * Unused when `end` supplies the row's own cluster. */ + actionLabel?: string; + /** A specific accessible name when neighboring rows share the same visible action label. */ + actionAriaLabel?: string; + /** + * Replaces the built-in 更改 trigger for rows that already own their end + * slot — a project row carries a default Badge, a 设为默认 button and a … + * menu, and editing is reached from that menu rather than from a second + * button competing with them. The editor, its focus move, and the + * save/cancel pair stay identical either way, which is the whole reason + * this lives here instead of being hand-rolled per page. + */ + end?: ReactNode; + /** + * Content that sits beside the built-in trigger while collapsed — a model + * row's enable switch, say. Unlike `end`, this keeps the trigger and the + * focus return that goes with it. + */ + beforeAction?: ReactNode; + isEditing: boolean; + isDisabled?: boolean; + /** Save stays disabled until the draft actually differs from the value. */ + canSave?: boolean; + saveLabel: string; + cancelLabel: string; + onEdit(): void; + onCancel(): void; + onSave(): void | Promise; + children: ReactNode; +}) { + const triggerRef = useRef(null); + const editorRef = useRef(null); + // Only pull focus for a transition the user drove. Without this the row + // would grab focus on first paint whenever a caller mounts already-expanded. + const wasEditingRef = useRef(props.isEditing); + + useEffect(() => { + const opened = props.isEditing && !wasEditingRef.current; + const closed = !props.isEditing && wasEditingRef.current; + wasEditingRef.current = props.isEditing; + if (opened) { + // The first control the editor renders, whatever the caller put there. + const first = editorRef.current?.querySelector( + 'input, textarea, select, button, [contenteditable="true"], [tabindex]:not([tabindex="-1"])', + ); + first?.focus(); + return; + } + if (closed) triggerRef.current?.focus(); + }, [props.isEditing]); + + // The collapsed row carries no aria-expanded / aria-controls on purpose. + // Those describe a disclosure — a trigger that stays put while a region + // beside it opens — and this is a mode swap: the trigger unmounts when the + // editor replaces it, so aria-expanded could never reach true and + // aria-controls would name a node that does not exist while collapsed. + // Declaring a contract the DOM never honours is worse than declaring none; + // the focus move is what tells assistive tech the mode changed, and that + // part is measured rather than assumed. + if (!props.isEditing) { + return ( + + {props.beforeAction} +