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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions apps/desktop/src/main/__tests__/oauth-relogin-device-code.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* 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 { strict as assert } from 'node:assert';
import { afterEach, describe, it } from 'node:test';
import type { DesktopRuntimeHostRef } from '../../preload/bridge-contract.js';
import { oauthLoginServiceFor } from '../../renderer/settings/oauth-relogin-service.js';

// Pins the per-service device-code contract behind the connection detail's
// 重新登录 notice. Codex's device-authorization page has no code in its URL —
// the user must type the `stateHint` the flow surfaces, so the notice must
// render it (it silently dropped it before this pin existed). xAI's page
// needs no manual code, matching the catalog panel's `!isXai` guard.

const HOST: DesktopRuntimeHostRef = { profileId: 'default', hostId: 'host-a' };

type MakaWindow = { maka: Record<string, unknown> };
const previousWindow = (globalThis as { window?: unknown }).window;

function installBridgeStubs(): { codexCalls: string[] } {
const codexCalls: string[] = [];
const codexStub = new Proxy(
{},
{
get:
(_target, method: string) =>
(...args: unknown[]) => {
codexCalls.push(`${method}:${JSON.stringify(args)}`);
return Promise.resolve({ ok: true });
},
},
);
(globalThis as unknown as { window: MakaWindow }).window = {
maka: { openAiCodex: codexStub, xaiOAuth: {} },
};
return { codexCalls };
}

afterEach(() => {
(globalThis as { window?: unknown }).window = previousWindow;
});

describe('oauthLoginServiceFor device-code contract', () => {
it('marks Codex as needing the device sign-in code shown', () => {
installBridgeStubs();
const service = oauthLoginServiceFor('openai-codex', HOST);
assert.ok(service, 'codex must be re-login capable');
assert.equal(service.showsDeviceCode, true);
});

it('keeps xAI on the no-code browser flow', () => {
installBridgeStubs();
const service = oauthLoginServiceFor('xai-oauth', HOST);
assert.ok(service, 'xai must be re-login capable');
assert.equal(service.showsDeviceCode, false);
});

it('returns null for providers without a browser-assisted re-login', () => {
installBridgeStubs();
assert.equal(oauthLoginServiceFor('openai-compatible', HOST), null);
assert.equal(oauthLoginServiceFor('claude-subscription', HOST), null);
});

it('routes the codex bridge through the host-scoped preload surface', async () => {
const { codexCalls } = installBridgeStubs();
const service = oauthLoginServiceFor('openai-codex', HOST);
assert.ok(service);
await service.bridge.getAccountState();
assert.deepEqual(codexCalls, [`getAccountState:${JSON.stringify([HOST])}`]);
});
});
63 changes: 63 additions & 0 deletions apps/desktop/src/renderer/settings/oauth-relogin-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* 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 type { ProviderType } from '@maka/core/llm-connections';
import type { DesktopRuntimeHostRef } from '../../preload/bridge-contract.js';
import { runtimeHostOAuthLoginBridge } from './runtime-host-settings-bridge.js';
import type { OAuthLoginFlowBridge } from './use-oauth-login-flow.js';

// Maps an OAuth model-connection provider type to the browser-assisted login
// service that can re-run its authorization from inside the connection dialog. Only
// the browser-assisted services (Codex and xAI) are one-button-drivable
// here; plain API-key providers return null so the notice falls back to
// prose instead of rendering a dead button.
//
// A leaf module (no React, no hook imports) so the mapping stays loadable by
// the node:test suite that pins the device-code contract.
export interface OAuthLoginService {
bridge: OAuthLoginFlowBridge;
display: { name: string; shortName: string };
// Codex's device-authorization page requires the user to type the code the
// flow surfaces as `stateHint` — the verification URL does not embed it, so
// the notice must show it or the login cannot be completed. xAI's page
// needs no manual code, mirroring the catalog panel's `!isXai` guard.
showsDeviceCode: boolean;
}

export function oauthLoginServiceFor(
providerType: ProviderType,
host: DesktopRuntimeHostRef,
): OAuthLoginService | null {
switch (providerType) {
case 'openai-codex':
return {
bridge: runtimeHostOAuthLoginBridge(window.maka.openAiCodex, host),
display: { name: 'OpenAI Codex', shortName: 'Codex' },
showsDeviceCode: true,
};
case 'xai-oauth':
return {
bridge: runtimeHostOAuthLoginBridge(window.maka.xaiOAuth, host),
display: { name: 'xAI Grok', shortName: 'SuperGrok / X Premium' },
showsDeviceCode: false,
};
default:
return null;
}
}
14 changes: 11 additions & 3 deletions apps/desktop/src/renderer/settings/provider-connection-detail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ import type { StatusSemantic } from '@maka/ui';
import {
useConnectionDetail,
type ConnectionDetailProps,
type OAuthLoginService,
} from './use-connection-detail';
import type { OAuthLoginService } from './oauth-relogin-service.js';
import {
formatRequestBodyOverlay,
parseRequestBodyOverlay,
Expand Down Expand Up @@ -1101,7 +1101,8 @@ function OAuthReloginNoticeForCurrentGeneration(props: {
hasSecret: CredentialPresenceStatus;
onRelogin(): Promise<void>;
}) {
const copy = getProviderSettingsCopy(useUiLocale()).detail;
const providerCopy = getProviderSettingsCopy(useUiLocale());
const copy = providerCopy.detail;
const flow = useOAuthLoginFlow({
bridge: props.service.bridge,
display: props.service.display,
Expand All @@ -1125,11 +1126,18 @@ function OAuthReloginNoticeForCurrentGeneration(props: {
: errored
? copy.oauthUnknownDetail
: copy.oauthStartDetail;
// Codex's device page has no code in its URL — the user must type the
// code shown here, so hiding it makes the re-login impossible to finish.
const deviceCode = props.service.showsDeviceCode ? flow.stateHint : null;
return (
<Banner
status="info"
title={title}
description={detail}
description={deviceCode ? (
<>
{detail} {providerCopy.oauthSection.deviceCode} <code>{deviceCode}</code>
</>
) : detail}
endContent={!loading ? (
<Button
variant="primary"
Expand Down
34 changes: 1 addition & 33 deletions apps/desktop/src/renderer/settings/use-connection-detail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import {
type ConnectionTestResult,
type LlmConnection,
type ModelInfo,
type ProviderType,
} from '@maka/core/llm-connections';
import { PROVIDER_DEFAULTS, connectionEnabledModelIds } from '@maka/core/llm-connections';
import { buildConnectionModelCatalogEntries } from '@maka/core/model-catalog';
Expand All @@ -50,7 +49,7 @@ import { connectionChipStatus } from './provider-connection-status';
import { relayProfileDraftReseedPlan, relayProfileDraftSeed } from './relay-profile-draft';
import { applyBulkThinkingLevel, relayProfileWithThinkingLevels } from './relay-thinking-bulk';
import { useKeyedActionGuard } from './use-action-guard';
import type { OAuthLoginFlowBridge } from './use-oauth-login-flow';
import { oauthLoginServiceFor } from './oauth-relogin-service.js';
import {
connectionLastTestMessageDisplay,
connectionTestFailureMessage,
Expand All @@ -62,37 +61,6 @@ import {
useRuntimeHostSettingsErrorReporter,
useRuntimeHostSettingsTarget,
} from './runtime-host-settings-target.js';
import { runtimeHostOAuthLoginBridge } from './runtime-host-settings-bridge.js';

// Maps an OAuth model-connection provider type to the browser-assisted login
// service that can re-run its authorization from inside the connection dialog. Only
// the browser-assisted services (Codex and xAI) are one-button-drivable
// here; plain API-key providers return null so the notice falls back to
// prose instead of rendering a dead button.
export interface OAuthLoginService {
bridge: OAuthLoginFlowBridge;
display: { name: string; shortName: string };
}

export function oauthLoginServiceFor(
providerType: ProviderType,
host: import('../../preload/bridge-contract.js').DesktopRuntimeHostRef,
): OAuthLoginService | null {
switch (providerType) {
case 'openai-codex':
return {
bridge: runtimeHostOAuthLoginBridge(window.maka.openAiCodex, host),
display: { name: 'OpenAI Codex', shortName: 'Codex' },
};
case 'xai-oauth':
return {
bridge: runtimeHostOAuthLoginBridge(window.maka.xaiOAuth, host),
display: { name: 'xAI Grok', shortName: 'SuperGrok / X Premium' },
};
default:
return null;
}
}

export interface ConnectionDetailProps {
bridge: ConnectionsBridge;
Expand Down
24 changes: 12 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading