Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Keep provider credentials bound to their initiating owner

wyt5e45a09ed5dc
diff --git a/src/main/features/auth.ts b/src/main/features/auth.ts
index 4e02a415..c283210c 100644
--- a/src/main/features/auth.ts
+++ b/src/main/features/auth.ts
@@ -66,7 +66,7 @@ import { userAuthProfilesFile, userLocalConfigDir } from '../paths';
import * as localSecrets from '../util/local-secret-store';
import { isBearerTokenHeaderSafe } from '../util/http-authorization';
import { safeExternalUserActionUrl } from '../util/window-security';
-import { getActiveUserId } from './users';
+import { getActiveUserId, hasActiveUser } from './users';
import {
FEATURED_API_PROVIDERS,
OAUTH_PROVIDERS,
@@ -385,12 +385,12 @@ function decryptProfilesPayload(raw: string, localId: string): { json: string; n
throw new Error('auth-profiles decrypt failed');
}
-function loadProfiles(opts: { throwOnInvalidExisting?: boolean } = {}): ProfilesFile {
+function loadProfiles(opts: { throwOnInvalidExisting?: boolean; userId?: string } = {}): ProfilesFile {
+ const uid = opts.userId ?? getActiveUserId();
try {
- const raw = fs.readFileSync(profilesFile(), 'utf-8');
+ const raw = fs.readFileSync(userAuthProfilesFile(uid), 'utf-8');
// Decrypt current Hosted/Open fallback payloads, or the previous crypto-vault whole-file
// format. Plain JSON is also accepted as a one-shot migration input.
- const uid = getActiveUserId();
const { json, needsRewrite } = decryptProfilesPayload(raw, uid);
let shouldRewrite = needsRewrite;
const data = JSON.parse(json) as Partial<ProfilesFile>;
@@ -490,7 +490,7 @@ function loadProfiles(opts: { throwOnInvalidExisting?: boolean } = {}): Profiles
...(orkasApiCredential ? { orkasApiCredential } : {}),
};
if (shouldRewrite || Number((data as any).version) !== PROFILES_FILE_VERSION) {
- try { saveProfiles(store); }
+ try { saveProfiles(store, uid); }
catch (err) {
// Migration is best-effort: a valid parsed store remains usable when disk writes fail.
log.warn('auth profiles migration rewrite failed; using parsed store', { error: logErrorSummary(err) });
@@ -884,8 +884,8 @@ export function removeOrkasApiCredential(): { removed: boolean } {
return { removed };
}
-function saveProfiles(store: ProfilesFile): void {
- const localId = getActiveUserId();
+function saveProfiles(store: ProfilesFile, userId?: string): void {
+ const localId = userId ?? getActiveUserId();
const target = userAuthProfilesFile(localId);
const targetDir = path.dirname(target);
const tmp = `${target}.tmp`;
@@ -1044,7 +1044,7 @@ function normalizeCustomTokenLimit(
field: 'contextWindow' | 'maxTokens',
): number {
if (raw === undefined || raw === null || raw === '') return fallback;
- const value = Number(raw);
+ const value = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : NaN;
const minimum = field === 'contextWindow' ? 1_024 : 1;
if (!Number.isInteger(value) || value < minimum || value > MAX_CUSTOM_TOKEN_LIMIT) {
throw customConfigError(
@@ -1397,6 +1397,7 @@ export async function addApiKeyEntry(
apiKey: string,
label?: string,
): Promise<{ profileId: string; entryId: string }> {
+ const userId = getActiveUserId();
const id = String(providerId || '').trim();
const model = resolveModelUpgrade(id, String(modelId || '').trim()).modelId;
const key = String(apiKey || '').trim();
@@ -1408,8 +1409,9 @@ export async function addApiKeyEntry(
throw customConfigError('CUSTOM_CONFIG_REQUIRED', 'Use the custom model configuration flow');
}
await assertRuntimeSelectableModel(id, model);
+ assertActiveAuthOwner(userId);
- const store = loadProfiles({ throwOnInvalidExisting: true });
+ const store = loadProfiles({ throwOnInvalidExisting: true, userId });
const chosenLabel = label ? sanitizeLabel(label) : autoLabel(store, id);
const profileId = makeProfileId(id, chosenLabel);
const now = Date.now();
@@ -1437,7 +1439,7 @@ export async function addApiKeyEntry(
createdAt: now,
});
}
- saveProfiles(store);
+ saveProfiles(store, userId);
clearCooldown(profileId);
invalidateCoreAgentRunner();
return { profileId, entryId };
@@ -1484,7 +1486,7 @@ export async function addCustomModelEntry(
);
const hasExplicitMaxTokens = input.maxTokens !== undefined
&& input.maxTokens !== null
- && String(input.maxTokens).trim() !== '';
+ && !(typeof input.maxTokens === 'string' && input.maxTokens.trim() === '');
const maxTokens = hasExplicitMaxTokens
? normalizeCustomTokenLimit(input.maxTokens, DEFAULT_CUSTOM_MAX_TOKENS, 'maxTokens')
: undefined;
@@ -1701,13 +1703,15 @@ export async function addEntry({
model,
profileId,
}: { provider: string; model: string; profileId: string }): Promise<{ entryId: string }> {
+ const userId = getActiveUserId();
const p = String(provider || '').trim();
const m = resolveModelUpgrade(p, String(model || '').trim()).modelId;
const pid = String(profileId || '').trim();
if (!p || !m || !pid) throw new Error('provider / model / profileId required');
assertModelProviderAllowed(p, m);
await assertRuntimeSelectableModel(p, m);
- const store = loadProfiles({ throwOnInvalidExisting: true });
+ assertActiveAuthOwner(userId);
+ const store = loadProfiles({ throwOnInvalidExisting: true, userId });
if (!store.profiles[pid]) throw new Error('profile not found');
if (store.profiles[pid].provider !== p) throw new Error('profile does not belong to provider');
@@ -1727,16 +1731,18 @@ export async function addEntry({
lastUsed: 0,
createdAt: now,
});
- saveProfiles(store);
+ saveProfiles(store, userId);
invalidateCoreAgentRunner();
return { entryId };
}
export async function updateEntryModel(entryId: string, model: string): Promise<{ entryId: string; model: string }> {
+ const userId = getActiveUserId();
const id = String(entryId || '').trim();
const rawModel = String(model || '').trim();
if (!id || !rawModel) throw new Error('entryId and model required');
- const store = loadProfiles({ throwOnInvalidExisting: true });
+ const store = loadProfiles({ throwOnInvalidExisting: true, userId });
+ const snapshot = JSON.stringify(store);
const target = store.entries.find((e) => e.entryId === id);
if (!target) throw new Error('entry not found');
const m = resolveModelUpgrade(target.provider, rawModel).modelId;
@@ -1745,6 +1751,7 @@ export async function updateEntryModel(entryId: string, model: string): Promise<
}
assertModelProviderAllowed(target.provider, m);
await assertRuntimeSelectableModel(target.provider, m);
+ assertAuthStoreUnchanged(userId, snapshot);
// Deduplicate: if another entry with the same (provider, model, profileId)
// already exists, removing the target makes the priority list cleaner.
const collision = store.entries.find(
@@ -1752,7 +1759,7 @@ export async function updateEntryModel(entryId: string, model: string): Promise<
);
if (collision) throw new Error('same (provider, model, profile) entry already exists');
target.model = m;
- saveProfiles(store);
+ saveProfiles(store, userId);
invalidateCoreAgentRunner();
return { entryId: id, model: m };
}
@@ -1770,9 +1777,12 @@ export async function removeEntry(entryId: string): Promise<{ removed: boolean }
}
export async function reorderEntries(orderedIds: string[]): Promise<{ entries: EntryView[] }> {
+ const userId = getActiveUserId();
if (!Array.isArray(orderedIds)) throw new Error('orderedIds must be an array');
- const store = loadProfiles({ throwOnInvalidExisting: true });
+ const store = loadProfiles({ throwOnInvalidExisting: true, userId });
+ const snapshot = JSON.stringify(store);
const runtimeResolvable = await buildRuntimeModelResolver(store.entries);
+ assertAuthStoreUnchanged(userId, snapshot);
const byId = new Map(store.entries.map((e) => [e.entryId, e]));
const reordered: Entry[] = [];
for (const id of orderedIds) {
@@ -1784,7 +1794,7 @@ export async function reorderEntries(orderedIds: string[]): Promise<{ entries: E
if (byId.has(e.entryId)) reordered.push(e);
}
store.entries = reordered;
- saveProfiles(store);
+ saveProfiles(store, userId);
invalidateCoreAgentRunner();
const lookup = await buildModelNameLookup();
return {
@@ -1802,9 +1812,11 @@ export async function selectEntry(
entryId: string,
requestedModel?: string,
): Promise<{ entries: EntryView[] }> {
+ const userId = getActiveUserId();
const id = String(entryId || '').trim();
if (!id) throw new Error('entryId required');
- const store = loadProfiles({ throwOnInvalidExisting: true });
+ const store = loadProfiles({ throwOnInvalidExisting: true, userId });
+ const snapshot = JSON.stringify(store);
const selected = store.entries.find((entry) => entry.entryId === id);
if (!selected) throw modelNotAvailableError();
@@ -1826,6 +1838,7 @@ export async function selectEntry(
selected.model = model;
}
const runtimeResolvable = await buildRuntimeModelResolver(store.entries);
+ assertAuthStoreUnchanged(userId, snapshot);
if (
!isEntryAllowed(store, selected)
|| !runtimeResolvable(selected.provider, selected.model)
@@ -1840,7 +1853,7 @@ export async function selectEntry(
store.entries = store.entries.map((entry) => (
runnableIds.has(entry.entryId) ? ordered[orderedIndex++] : entry
));
- saveProfiles(store);
+ saveProfiles(store, userId);
invalidateCoreAgentRunner();
const lookup = await buildModelNameLookup();
@@ -1863,6 +1876,7 @@ type FlowStatus =
interface Flow {
flowId: string;
+ userId: string;
provider: string;
label: string;
status: FlowStatus;
@@ -1878,6 +1892,31 @@ interface Flow {
const flows = new Map<string, Flow>();
let _flowCounter = 0;
+function isActiveAuthOwner(userId: string): boolean {
+ return hasActiveUser() && getActiveUserId() === userId;
+}
+
+function assertAuthStoreUnchanged(userId: string, snapshot: string): void {
+ assertActiveAuthOwner(userId);
+ const current = loadProfiles({ throwOnInvalidExisting: true, userId });
+ if (JSON.stringify(current) !== snapshot) throw modelNotAvailableError();
+}
+
+function assertActiveAuthOwner(userId: string): void {
+ if (!isActiveAuthOwner(userId)) throw modelNotAvailableError();
+}
+
+function isLiveOAuthFlow(flow: Flow): boolean {
+ return flows.get(flow.flowId) === flow
+ && !flow.abortController.signal.aborted
+ && isActiveAuthOwner(flow.userId);
+}
+
+function ownedOAuthFlow(flowId: string): Flow | undefined {
+ const flow = flows.get(flowId);
+ return flow && isActiveAuthOwner(flow.userId) ? flow : undefined;
+}
+
function nextFlowId(): string {
_flowCounter = (_flowCounter + 1) % 100000;
return `oauth-${Date.now().toString(36)}-${_flowCounter}`;
@@ -1946,10 +1985,12 @@ export async function startOAuth(
providerId: string,
label?: string,
): Promise<{ flowId: string; status: FlowStatus }> {
+ const userId = getActiveUserId();
const id = String(providerId || '').trim();
if (!id) throw new Error('provider required');
const oauth = await piOauth();
const provider = await oauth.getOAuthProvider(id);
+ assertActiveAuthOwner(userId);
if (!provider) {
const hint = _minimaxRegisterError && id.startsWith('minimax-portal')
? t('oauth.minimax.register_error_hint', { message: _minimaxRegisterError })
@@ -1964,6 +2005,7 @@ export async function startOAuth(
const usesCallbackServer = provider.usesCallbackServer !== false;
const flow: Flow = {
flowId,
+ userId,
provider: id,
label: chosenLabel,
status: { kind: 'starting' },
@@ -1975,6 +2017,7 @@ export async function startOAuth(
.login({
signal: flow.abortController.signal,
onAuth: (info) => {
+ if (!isLiveOAuthFlow(flow)) return;
flow.status = {
kind: 'awaiting_auth',
url: info.url,
@@ -1986,6 +2029,7 @@ export async function startOAuth(
openExternalUrl(info.url);
},
onDeviceCode: (info) => {
+ if (!isLiveOAuthFlow(flow)) return;
const details = [`Code: ${info.userCode}`];
if (info.expiresInSeconds) details.push(`Expires in ${info.expiresInSeconds} seconds.`);
flow.status = {
@@ -1997,6 +2041,7 @@ export async function startOAuth(
openExternalUrl(info.verificationUri);
},
onPrompt: async (prompt) => {
+ if (!isLiveOAuthFlow(flow)) return '';
flow.status = {
kind: 'awaiting_input',
prompt: {
@@ -2022,13 +2067,14 @@ export async function startOAuth(
// lets pi-ai drain out of `server.waitForCode()` and reach the
// `finally { server.close() }` block, so port 1455 gets freed
// instead of leaking.
- onManualCodeInput: () => new Promise<string>((resolve) => {
+ onManualCodeInput: () => !isLiveOAuthFlow(flow) ? Promise.resolve('') : new Promise<string>((resolve) => {
flow.manualInputResolver = (val) => {
flow.manualInputResolver = undefined;
resolve(val);
};
}),
onSelect: async (prompt) => {
+ if (!isLiveOAuthFlow(flow)) return undefined;
const selected = prompt.options[0];
flow.status = {
kind: 'progress',
@@ -2037,10 +2083,15 @@ export async function startOAuth(
return selected?.id;
},
onProgress: (message) => {
+ if (!isLiveOAuthFlow(flow)) return;
flow.status = { kind: 'progress', message };
},
})
.then((credentials) => {
+ if (!isLiveOAuthFlow(flow)) {
+ if (!flow.abortController.signal.aborted) flow.status = { kind: 'error', error: 'cancelled' };
+ return;
+ }
const store = loadProfiles({ throwOnInvalidExisting: true });
// Prefer a human-identifiable label from the token if the caller
// didn't supply one — email local-part, then accountId prefix —
@@ -2072,20 +2123,28 @@ export async function startOAuth(
flow.status = { kind: 'done', profileId: pid };
})
.catch((err: unknown) => {
- flow.status = { kind: 'error', error: (err as Error)?.message || String(err) };
+ if (flow.abortController.signal.aborted) return;
+ if (!isActiveAuthOwner(userId)) {
+ flow.status = { kind: 'error', error: 'cancelled' };
+ return;
+ }
+ // Upstream exceptions can contain token responses and redirect data.
+ // An empty detail selects the Renderer's existing localized failure copy.
+ log.warn('oauth authorization failed', { provider: id, error: logErrorSummary(err) });
+ flow.status = { kind: 'error', error: '' };
});
return { flowId, status: flow.status };
}
export function pollOAuthFlow(flowId: string): { status: FlowStatus } {
- const flow = flows.get(flowId);
+ const flow = ownedOAuthFlow(flowId);
if (!flow) return { status: { kind: 'error', error: 'unknown flow' } };
return { status: flow.status };
}
export function submitOAuthInput(flowId: string, value: string): { ok: boolean } {
- const flow = flows.get(flowId);
+ const flow = ownedOAuthFlow(flowId);
if (!flow) return { ok: false };
const val = String(value ?? '');
// Prefer the late-stage `onPrompt` resolver if active (bind failed), else
@@ -2099,7 +2158,7 @@ export function submitOAuthInput(flowId: string, value: string): { ok: boolean }
}
export function cancelOAuthFlow(flowId: string): { ok: boolean } {
- const flow = flows.get(flowId);
+ const flow = ownedOAuthFlow(flowId);
if (!flow) return { ok: false };
try { flow.abortController.abort(); } catch { /* noop */ }
// Resolve both resolvers with empty string so pi-ai's flow drains out,
@@ -2158,7 +2217,8 @@ function groupEntries(entries: Entry[]): Entry[][] {
* Resolve the usable `apiKey` for an entry (returns undefined if the
* profile is gone, the OAuth token expired and refresh fails, etc.).
*/
-async function resolveEntryApiKey(store: ProfilesFile, entry: Entry): Promise<string | undefined> {
+async function resolveEntryApiKey(store: ProfilesFile, entry: Entry, userId: string): Promise<string | undefined> {
+ if (!isActiveAuthOwner(userId)) return undefined;
const prof = store.profiles[entry.profileId];
if (!prof || !isStoredProfileAllowed(prof)) return undefined;
if (prof.type === 'api_key') return prof.key;
@@ -2167,10 +2227,12 @@ async function resolveEntryApiKey(store: ProfilesFile, entry: Entry): Promise<st
return prof.access;
}
try {
- const refreshed = await refreshOAuthProfile(entry.profileId);
+ const refreshed = await refreshOAuthProfile(entry.profileId, userId);
+ if (!isActiveAuthOwner(userId)) return undefined;
if (!refreshed) rememberOAuthRefreshFailure(entry.profileId, prof);
return refreshed;
} catch (err) {
+ if (!isActiveAuthOwner(userId)) return undefined;
rememberOAuthRefreshFailure(entry.profileId, prof);
log.warn('OAuth refresh failed', { profileId: entry.profileId, error: logErrorSummary(err) });
return undefined;
@@ -2264,9 +2326,11 @@ export function bumpEntryLastUsed(entryId: string): void {
* bumps the winning candidate via `onSuccess`).
*/
export async function pickChatEntryGroup(): Promise<ChatEntryChoice[]> {
- const store = loadProfiles();
+ const userId = getActiveUserId();
+ const store = loadProfiles({ userId });
if (store.entries.length === 0) return [];
const runtimeResolvable = await buildRuntimeModelResolver(store.entries);
+ if (!isActiveAuthOwner(userId)) return [];
// Flatten: preserve entries[] order across groups, but within a
// consecutive same-(provider, model) run, sort oldest lastUsed first.
@@ -2291,7 +2355,9 @@ export async function pickChatEntryGroup(): Promise<ChatEntryChoice[]> {
log.info(`skipping cooled-down profile ${entry.profileId}`);
continue;
}
- const apiKey = await resolveEntryApiKey(store, entry);
+ const apiKey = await resolveEntryApiKey(store, entry, userId);
+ // Even an immediately available key crosses an await boundary here.
+ if (!isActiveAuthOwner(userId)) return [];
if (!apiKey) continue;
const customConfig = customRuntimeConfigFromProfile(store.profiles[entry.profileId]);
choices.push({
@@ -2335,7 +2401,8 @@ export async function pickRotationKey(providerId: string): Promise<{
const id = String(providerId || '').trim();
if (!id) return null;
if (!isModelProviderAllowed(id)) return null;
- const store = loadProfiles({ throwOnInvalidExisting: true });
+ const userId = getActiveUserId();
+ const store = loadProfiles({ throwOnInvalidExisting: true, userId });
const candidates = Object.entries(store.profiles)
.filter(([, p]) => p.provider === id)
.sort(([, a], [, b]) => (a.lastUsed || 0) - (b.lastUsed || 0));
@@ -2347,13 +2414,14 @@ export async function pickRotationKey(providerId: string): Promise<{
let apiKey: string | undefined;
if (prof.type === 'api_key') apiKey = prof.key;
else if (Date.now() < prof.expires) apiKey = prof.access;
- else apiKey = await refreshOAuthProfile(pid).catch(() => undefined);
+ else apiKey = await refreshOAuthProfile(pid, userId).catch(() => undefined);
+ if (!isActiveAuthOwner(userId)) return null;
if (!apiKey) continue;
const customConfig = customRuntimeConfigFromProfile(prof);
if (providerUsesCustomOpenAIConfig(id) && !customConfig) continue;
- const fresh = loadProfiles({ throwOnInvalidExisting: true });
+ const fresh = loadProfiles({ throwOnInvalidExisting: true, userId });
const target = fresh.profiles[pid];
- if (target) { target.lastUsed = Date.now(); saveProfiles(fresh); }
+ if (target) { target.lastUsed = Date.now(); saveProfiles(fresh, userId); }
return {
profileId: pid,
provider: id,
@@ -2365,8 +2433,8 @@ export async function pickRotationKey(providerId: string): Promise<{
return null;
}
-async function refreshOAuthProfile(profileId: string): Promise<string | undefined> {
- const store = loadProfiles();
+async function refreshOAuthProfile(profileId: string, userId = getActiveUserId()): Promise<string | undefined> {
+ const store = loadProfiles({ userId });
const prof = store.profiles[profileId];
if (!prof || prof.type !== 'oauth') return undefined;
@@ -2374,12 +2442,12 @@ async function refreshOAuthProfile(profileId: string): Promise<string | undefine
try {
oauth = await piOauth();
} catch (err) {
- rememberOAuthRefreshFailure(profileId, prof);
+ if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof);
throw err;
}
const provider = await oauth.getOAuthProvider(prof.provider);
if (!provider) {
- rememberOAuthRefreshFailure(profileId, prof);
+ if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof);
return undefined;
}
@@ -2397,10 +2465,10 @@ async function refreshOAuthProfile(profileId: string): Promise<string | undefine
try {
newCreds = await provider.refreshToken(creds as any);
} catch (err) {
- rememberOAuthRefreshFailure(profileId, prof);
+ if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof);
throw err;
}
- const fresh = loadProfiles({ throwOnInvalidExisting: true });
+ const fresh = loadProfiles({ throwOnInvalidExisting: true, userId });
const target = fresh.profiles[profileId];
if (target && target.type === 'oauth') {
target.access = newCreds.access;
@@ -2411,9 +2479,9 @@ async function refreshOAuthProfile(profileId: string): Promise<string | undefine
(target as OAuthProfile)[k] = v;
}
}
- saveProfiles(fresh);
+ saveProfiles(fresh, userId);
}
- clearOAuthRefreshFailure(profileId);
+ if (isActiveAuthOwner(userId)) clearOAuthRefreshFailure(profileId);
return provider.getApiKey(newCreds);
}
@@ -2456,7 +2524,9 @@ export async function testConnection(
if (!selectedModel || !isSelectableModel(pid, selectedModel)) {
return { ok: false, error: t('errors.model_not_available') };
}
+ const userId = getActiveUserId();
const mod = await ca();
+ if (!isActiveAuthOwner(userId)) return { ok: false, error: t('errors.model_not_available') };
const resolvedModel = EXTERNAL_API_PROVIDERS.includes(pid)
? null
: resolveConfiguredPiModel(mod, pid, selectedModel);
@@ -2469,12 +2539,12 @@ export async function testConnection(
let customConfig: CustomOpenAICompatibleRuntimeConfig | undefined;
if (chosenProfileId) {
- const store = loadProfiles();
+ const store = loadProfiles({ userId });
const prof = store.profiles[chosenProfileId];
if (!prof || prof.provider !== pid) return { ok: false, error: 'profile not found' };
if (prof.type === 'api_key') apiKey = prof.key;
else if (Date.now() < prof.expires) apiKey = prof.access;
- else apiKey = await refreshOAuthProfile(chosenProfileId).catch(() => undefined);
+ else apiKey = await refreshOAuthProfile(chosenProfileId, userId).catch(() => undefined);
customConfig = customRuntimeConfigFromProfile(prof) || undefined;
} else {
const choice = await pickRotationKey(pid);
@@ -2485,6 +2555,7 @@ export async function testConnection(
}
}
+ if (!isActiveAuthOwner(userId)) return { ok: false, error: t('errors.model_not_available') };
if (!apiKey) return { ok: false, error: 'no credential stored for this provider', profileId: chosenProfileId };
if (providerUsesCustomOpenAIConfig(pid) && !customConfig) {
return { ok: false, error: 'custom model configuration is incomplete', profileId: chosenProfileId };
@@ -2498,6 +2569,7 @@ export async function testConnection(
const t0 = Date.now();
try {
const ext = await import('../model/core-agent/external-providers');
+ if (!isActiveAuthOwner(userId)) return { ok: false, error: t('errors.model_not_available') };
let provider;
let probeModel = modelForTest;
if (pid === 'moonshot') {
@@ -2517,13 +2589,14 @@ export async function testConnection(
} else {
throw new Error(`external provider "${pid}" has no test-connection factory yet`);
}
+ if (!isActiveAuthOwner(userId)) return { ok: false, error: t('errors.model_not_available') };
const msg = await provider.complete({
model: probeModel,
systemPrompt: 'You are a connectivity probe; reply with a single word.',
messages: [{ role: 'user', content: [{ type: 'text', text: 'ping' }] }],
maxTokens: 1,
});
- if (chosenProfileId) clearCooldown(chosenProfileId);
+ if (chosenProfileId && isActiveAuthOwner(userId)) clearCooldown(chosenProfileId);
return { ok: true, durationMs: Date.now() - t0, model: msg.model || probeModel, profileId: chosenProfileId };
} catch (err) {
const errMsg = sanitizeConnectionError(err, { apiKey, customConfig });
@@ -2572,7 +2645,7 @@ export async function testConnection(
messages: [{ role: 'user', content: [{ type: 'text', text: 'ping' }] }],
maxTokens: 1,
});
- if (chosenProfileId) clearCooldown(chosenProfileId);
+ if (chosenProfileId && isActiveAuthOwner(userId)) clearCooldown(chosenProfileId);
return { ok: true, durationMs: Date.now() - t0, model: msg.model || '', profileId: chosenProfileId };
} catch (err) {
return {
diff --git a/src/renderer/modules/composer-model-picker.js b/src/renderer/modules/composer-model-picker.js
index 215edbe1..9595b6a8 100644
--- a/src/renderer/modules/composer-model-picker.js
+++ b/src/renderer/modules/composer-model-picker.js
@@ -4,6 +4,7 @@
// remain owned by Settings > Models.
let _composerModelEntries = [];
+let _composerModelEntriesEpoch = 0;
let _composerModelMenu = null;
let _composerModelOpening = null;
let _composerModelBusy = false;
@@ -193,11 +194,10 @@ function _renderComposerModelChips() {
}
async function _refreshComposerModelEntries() {
+ const epoch = ++_composerModelEntriesEpoch;
try {
const res = await window.orkas.invoke('auth.listComposerEntries');
- if (res && res.ok && Array.isArray(res.entries)) {
- // Managed subscription models do not exist in the open-source build.
- // Keep this boundary defensive so a stale profile cannot surface one.
+ if (epoch === _composerModelEntriesEpoch && res && res.ok && Array.isArray(res.entries)) {
_composerModelEntries = res.entries.filter((entry) => entry && entry.profileType !== 'managed');
}
} catch (_) {
@@ -808,6 +808,7 @@ document.addEventListener('DOMContentLoaded', () => {
window.addEventListener('orkas:model-entries-changed', (event) => {
const entries = event && event.detail && event.detail.entries;
if (Array.isArray(entries)) {
+ _composerModelEntriesEpoch += 1;
_composerModelEntries = entries.filter((entry) => entry && entry.profileType !== 'managed');
_renderComposerModelChips();
} else {
diff --git a/test/e2e/auth_e2e_oauth_error.spec.ts b/test/e2e/auth_e2e_oauth_error.spec.ts
new file mode 100644
index 00000000..3d7ddb32
--- /dev/null
+++ b/test/e2e/auth_e2e_oauth_error.spec.ts
@@ -0,0 +1,40 @@
+import { expect, test } from './fixtures/orkas';
+
+test('shows the existing authorization failure copy without publishing a raw provider response', async ({ orkas: app }, testInfo) => {
+ const page = app.page!;
+ await app.electronApp!.evaluate(async ({ app }) => {
+ const require = (process as any).mainModule.require;
+ await require(`${app.getAppPath()}/test/e2e/fixtures/oauth-owner-main.cjs`)(app.getAppPath());
+ });
+ try {
+ await page.evaluate(async () => {
+ const host = window as any; await host.loadRendererFeature('settings');
+ await host._settingsStartOAuthFlow({ id: 'e2e-auth-owner', label: 'Controlled OAuth fixture' }, 'fixture-model');
+ });
+ await expect.poll(() => app.electronApp!.evaluate(() => (globalThis as any).__oauthOwnerControl.calls)).toBe(1);
+ await app.electronApp!.evaluate(() => {
+ const control = (globalThis as any).__oauthOwnerControl;
+ control.reject(new Error('Token exchange returned invalid JSON. url=https://provider.example.test/token; body={"access_token":"synthetic-native-private-marker","email":"[email protected]"}; details=SyntaxError'));
+ });
+ await expect(page.locator('#oauth-flow-body .oauth-flow-stage.error')).toHaveText('Authorization failed');
+ const observation = await page.evaluate(() => ({
+ text: document.querySelector('#oauth-flow-body')?.textContent,
+ open: document.querySelector('#oauth-flow-modal')?.classList.contains('open'),
+ }));
+ expect(observation).toEqual({ text: 'Authorization failed', open: true });
+ const unchanged = await app.electronApp!.evaluate(() => {
+ const c = (globalThis as any).__oauthOwnerControl;
+ return c.files.map((file: string, index: number) => c.fs.readFileSync(file).equals(c.before[index]));
+ });
+ expect(unchanged).toEqual([true, true]);
+ await page.locator('#oauth-flow-modal').screenshot({ path: testInfo.outputPath('authorization-failed.png') });
+ } finally {
+ await page.locator('#oauth-flow-close-btn').click();
+ await app.electronApp!.evaluate(async () => {
+ const c = (globalThis as any).__oauthOwnerControl;
+ c.users.activateUser(c.owner); c.release();
+ await new Promise(resolve => setImmediate(resolve));
+ c.oauth.unregisterOAuthProvider('e2e-auth-owner'); delete (globalThis as any).__oauthOwnerControl;
+ });
+ }
+});
diff --git a/test/e2e/auth_e2e_oauth_owner.spec.ts b/test/e2e/auth_e2e_oauth_owner.spec.ts
new file mode 100644
index 00000000..9b0f0aff
--- /dev/null
+++ b/test/e2e/auth_e2e_oauth_owner.spec.ts
@@ -0,0 +1,45 @@
+import { expect, test } from './fixtures/orkas';
+
+
+for (const scenario of ['cancelled', 'account-switch'] as const) {
+ test(`discards a late OAuth credential after ${scenario} through actual IPC and encrypted stores`, async ({ orkas: app }) => {
+ // The provider alone is controlled. Actual discovery, login orchestration,
+ // preload/IPC, root activation, cancellation and encrypted files run.
+ await app.electronApp!.evaluate(async ({ app }) => {
+ const require = (process as any).mainModule.require;
+ await require(`${app.getAppPath()}/test/e2e/fixtures/oauth-owner-main.cjs`)(app.getAppPath());
+ });
+ let flowId = '';
+ try {
+ const started = await app.invoke<any>('auth.startOAuth', { provider: 'e2e-auth-owner', label: 'native-owner' });
+ expect(started).toMatchObject({ ok: true, flowId: expect.any(String) });
+ flowId = started.flowId;
+ expect(await app.electronApp!.evaluate(() => (globalThis as any).__oauthOwnerControl.calls)).toBe(1);
+ if (scenario === 'cancelled') {
+ expect(await app.invoke<any>('auth.cancelOAuthFlow', { flowId })).toMatchObject({ ok: true });
+ } else {
+ // Direct root activation is fixture setup, not whole login/logout UI.
+ await app.electronApp!.evaluate(() => {
+ const c = (globalThis as any).__oauthOwnerControl; c.users.activateUser(c.other);
+ });
+ }
+ const result = await app.electronApp!.evaluate(async (_electron, flowId) => {
+ const c = (globalThis as any).__oauthOwnerControl;
+ c.release();
+ // Drain the real login completion chain before observing files.
+ await new Promise(resolve => setImmediate(resolve));
+ return { unchanged: c.files.map((file: string, index: number) => c.fs.readFileSync(file).equals(c.before[index])) };
+ }, flowId);
+ expect(result).toEqual({ unchanged: [true, true] });
+ expect(await app.invoke<any>('auth.pollOAuthFlow', { flowId })).toMatchObject({ status: { kind: 'error' } });
+ } finally {
+ await app.electronApp!.evaluate(async (_electron, flowId) => {
+ const c = (globalThis as any).__oauthOwnerControl;
+ c.users.activateUser(c.owner); c.auth.cancelOAuthFlow(flowId); c.release();
+ await new Promise(resolve => setImmediate(resolve));
+ c.oauth.unregisterOAuthProvider('e2e-auth-owner');
+ delete (globalThis as any).__oauthOwnerControl;
+ }, flowId);
+ }
+ });
+}
diff --git a/test/e2e/fixtures/oauth-owner-main.cjs b/test/e2e/fixtures/oauth-owner-main.cjs
new file mode 100644
index 00000000..74a6cc6b
--- /dev/null
+++ b/test/e2e/fixtures/oauth-owner-main.cjs
@@ -0,0 +1,38 @@
+// Run dynamic imports in a real Node module, outside Playwright's VM evaluator.
+module.exports = async function installOAuthOwnerFixture(root) {
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const os = require('node:os');
+ const workspace = fs.realpathSync(process.env.ORKAS_WORKSPACE_ROOT || '');
+ const relative = path.relative(fs.realpathSync(os.tmpdir()), workspace);
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
+ throw new Error('Isolated native fixture workspace required');
+ }
+ const users = require(`${root}/src/main/features/users`);
+ const auth = require(`${root}/src/main/features/auth`);
+ const { pathToFileURL } = require('node:url');
+ const oauth = await import(pathToFileURL(`${root}/src/core-agent/src/auth/oauth-compat.ts`).href);
+ const paths = require(`${root}/src/main/paths`);
+ const owner = users.getActiveUserId();
+ const other = 'native-oauth-owner-other';
+ for (const uid of [owner, other]) {
+ users.activateUser(uid);
+ await auth.addApiKey('openai', 'synthetic-native-owner-key', 'owner');
+ }
+ users.activateUser(owner);
+ const files = [owner, other].map(uid => paths.userAuthProfilesFile(uid));
+ const before = files.map(file => fs.readFileSync(file));
+ let release, reject;
+ const gate = new Promise((resolve, fail) => { release = resolve; reject = fail; });
+ const control = { owner, other, users, auth, oauth, files, before, fs, release, reject, calls: 0, callbacks: null };
+ oauth.registerOAuthProvider({
+ id: 'e2e-auth-owner', name: 'Controlled OAuth fixture',
+ login(callbacks) {
+ control.calls += 1; control.callbacks = callbacks;
+ return gate.then(() => ({ access: 'synthetic-late-access', refresh: 'synthetic-late-refresh', expires: Date.now() + 3_600_000 }));
+ },
+ refreshToken() { throw new Error('Native fixture must not refresh'); },
+ getApiKey(credentials) { return credentials.access; },
+ });
+ globalThis.__oauthOwnerControl = control;
+};
diff --git a/test/e2e/settings_e2e_modal_lifetime.spec.ts b/test/e2e/settings_e2e_modal_lifetime.spec.ts
new file mode 100644
index 00000000..539f5f46
--- /dev/null
+++ b/test/e2e/settings_e2e_modal_lifetime.spec.ts
@@ -0,0 +1,97 @@
+import { expect, test } from './fixtures/orkas';
+import { holdInvokeResponse } from './fixtures/held-invoke-response';
+
+
+for (const method of ['api_key', 'custom'] as const) {
+ test(`keeps the next credential form open when the previous ${method} write response arrives`, async ({ orkas: app }, testInfo) => {
+ const page = app.page!;
+ const channel = method === 'custom' ? 'auth.addCustomModelEntry' : 'auth.addApiKeyEntry';
+ const provider = method === 'custom' ? 'custom' : 'openai';
+ const previous = (await app.invoke<any>('auth.listEntries', { includeUnavailable: true })).entries.filter((entry: any) => entry.provider === provider).length;
+ await holdInvokeResponse(app.electronApp!, channel);
+ try {
+ await page.evaluate(async method => {
+ const host = window as any; await host.loadRendererFeature('settings');
+ const reload = host._settingsReload;
+ host.__modalSaveSettled = false;
+ host._settingsReload = async (...args: any[]) => {
+ try { return await reload(...args); }
+ finally { host.__modalSaveSettled = true; }
+ };
+ host.restoreModalReload = () => { host._settingsReload = reload; };
+ if (method === 'custom') host._settingsShowCustomModelForm({ id: 'custom', label: 'Custom' });
+ else host._settingsShowApiKeyForm({ id: 'openai', label: 'OpenAI' }, 'gpt-5.6-sol');
+ }, method);
+ const modal = page.locator('#add-account-modal');
+ if (method === 'custom') {
+ await modal.locator('.custom-base-url-input').fill('https://gateway.example.test/v1');
+ await modal.locator('.custom-model-input').fill('fixture-model');
+ }
+ await modal.locator(method === 'custom' ? '.custom-key-input' : '.api-key-input').fill('synthetic-old-form-key');
+ await modal.locator('#add-account-actions .btn-primary').click();
+ await expect(modal.locator('#add-account-actions .btn-primary')).toBeDisabled();
+ await expect.poll(() => app.electronApp!.evaluate(() => (globalThis as any).__heldInvokeResponse.calls)).toBe(1);
+ await modal.locator('#add-account-actions .btn:not(.btn-primary)').click();
+ await expect(modal).not.toHaveClass(/\bopen\b/);
+ await page.evaluate(method => {
+ const host = window as any;
+ if (method === 'custom') host._settingsShowApiKeyForm({ id: 'openai', label: 'OpenAI' }, 'gpt-5.6-sol');
+ else host._settingsShowCustomModelForm({ id: 'custom', label: 'Custom' });
+ }, method);
+ const input = modal.locator(method === 'custom' ? '.api-key-input' : '.custom-key-input');
+ await input.fill('synthetic-unsaved-new-form-key');
+ await app.electronApp!.evaluate(() => (globalThis as any).__heldInvokeResponse.release());
+ // Wait for the real old operation's post-response refresh before observing UI.
+ await expect.poll(() => page.evaluate(() => (window as any).__modalSaveSettled)).toBe(true);
+ await expect.poll(async () => (await app.invoke<any>('auth.listEntries', { includeUnavailable: true })).entries.filter((entry: any) => entry.provider === provider).length).toBe(previous + 1);
+ await expect(modal).toHaveClass(/\bopen\b/);
+ await expect(input).toHaveValue('synthetic-unsaved-new-form-key');
+ await expect(modal.locator('#add-account-actions .btn-primary')).toBeEnabled();
+ await modal.screenshot({ path: testInfo.outputPath(`new-${method}-dialog.png`) });
+ } finally {
+ await page.evaluate(() => (window as any).restoreModalReload?.());
+ await app.electronApp!.evaluate(() => {
+ const control = (globalThis as any).__heldInvokeResponse; control.release(); control.restore();
+ });
+ }
+ });
+}
+
+test('cancels a delayed real OAuth start after the dialog closes without polling or persisting late credentials', async ({ orkas: app }) => {
+ const page = app.page!;
+ await app.electronApp!.evaluate(async ({ app }) => {
+ const require = (process as any).mainModule.require;
+ await require(`${app.getAppPath()}/test/e2e/fixtures/oauth-owner-main.cjs`)(app.getAppPath());
+ });
+ await holdInvokeResponse(app.electronApp!, 'auth.startOAuth');
+ try {
+ await page.evaluate(async () => {
+ const host = window as any; await host.loadRendererFeature('settings');
+ host.__pendingOAuthStart = host._settingsStartOAuthFlow({ id: 'e2e-auth-owner', label: 'Controlled OAuth fixture' }, 'fixture-model');
+ });
+ await expect.poll(() => app.electronApp!.evaluate(() => (globalThis as any).__oauthOwnerControl.calls)).toBe(1);
+ await page.locator('#oauth-flow-close-btn').click();
+ await expect(page.locator('#oauth-flow-modal')).not.toHaveClass(/\bopen\b/);
+ await app.electronApp!.evaluate(() => (globalThis as any).__heldInvokeResponse.release());
+ await page.evaluate(async () => { await (window as any).__pendingOAuthStart; });
+ // Observe two existing400ms poll intervals while the provider stays held.
+ await page.evaluate(() => new Promise(resolve => setTimeout(resolve, 900)));
+ const state = await app.electronApp!.evaluate(async () => {
+ const c = (globalThis as any).__oauthOwnerControl;
+ const aborted = c.callbacks.signal.aborted;
+ c.release(); await new Promise(resolve => setImmediate(resolve));
+ return { aborted, polls: (globalThis as any).__heldInvokeResponse.polls,
+ unchanged: c.files.map((file: string, index: number) => c.fs.readFileSync(file).equals(c.before[index])) };
+ });
+ expect(state).toEqual({ aborted: true, polls: 0, unchanged: [true, true] });
+ await expect(page.locator('#oauth-flow-modal')).not.toHaveClass(/\bopen\b/);
+ } finally {
+ await app.electronApp!.evaluate(async () => {
+ const c = (globalThis as any).__oauthOwnerControl;
+ const held = (globalThis as any).__heldInvokeResponse;
+ c.users.activateUser(c.owner); c.auth.cancelOAuthFlow(held.flowId); c.release(); held.release();
+ await new Promise(resolve => setImmediate(resolve));
+ c.oauth.unregisterOAuthProvider('e2e-auth-owner'); held.restore(); delete (globalThis as any).__oauthOwnerControl;
+ });
+ }
+});
diff --git a/test/e2e/settings_e2e_submit_lifetime.spec.ts b/test/e2e/settings_e2e_submit_lifetime.spec.ts
new file mode 100644
index 00000000..3a804b8f
--- /dev/null
+++ b/test/e2e/settings_e2e_submit_lifetime.spec.ts
@@ -0,0 +1,75 @@
+import { expect, test } from './fixtures/orkas';
+
+
+for (const method of ['api_key', 'custom'] as const) {
+ test(`saves the ${method} credential once when Enter repeats during the actual Main write response`, async ({ orkas: app }) => {
+ const page = app.page!;
+ const provider = method === 'custom' ? 'custom' : 'openai';
+ const channel = method === 'custom' ? 'addCustomModelEntry' : 'addApiKeyEntry';
+ const before = await app.invoke<any>('auth.listEntries', { includeUnavailable: true });
+ const previous = before.entries.filter((entry: any) => entry.provider === provider).length;
+ // Hold delivery only after the real account-scoped encrypted write. No
+ // profile, entry, validation result or persistence response is fabricated.
+ await app.electronApp!.evaluate(({ ipcMain }, { channel }) => {
+ // Electron exposes handler registration publicly but no public getter.
+ // Inspect the pinned test runtime's map, fail explicitly if unavailable,
+ // and forward every original sender/payload through the real handler.
+ const handlers = (ipcMain as any)._invokeHandlers as Map<string, Function>;
+ const original = handlers?.get('orkas.invoke');
+ if (typeof original !== 'function') throw new Error('Native fixture IPC handler seam unavailable');
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const control = { calls: 0, release, restore: () => {
+ if (handlers.get('orkas.invoke') !== wrapped) throw new Error('Native fixture handler owner changed');
+ ipcMain.removeHandler('orkas.invoke'); ipcMain.handle('orkas.invoke', original as any);
+ } };
+ const wrapped = async (event: unknown, request: any) => {
+ if (request?.channel !== `auth.${channel}`) return original(event, request);
+ const call = ++control.calls;
+ const result = await original(event, request);
+ if (call === 1) await gate;
+ return result;
+ };
+ ipcMain.removeHandler('orkas.invoke'); ipcMain.handle('orkas.invoke', wrapped as any);
+ (globalThis as any).__settingsSubmitControl = control;
+ }, { channel });
+ try {
+ await page.evaluate(async method => {
+ const host = window as any;
+ await host.loadRendererFeature('settings');
+ // Form selection is fixture setup; the real dialog, keyboard handler,
+ // preload, IPC, Main validation, encrypted store and UI result run.
+ if (method === 'custom') host._settingsShowCustomModelForm({ id: 'custom', label: 'Custom' });
+ else host._settingsShowApiKeyForm({ id: 'openai', label: 'OpenAI' }, 'gpt-5.6-sol');
+ }, method);
+ const modal = page.locator('#add-account-modal');
+ await expect(modal).toHaveClass(/\bopen\b/);
+ if (method === 'custom') {
+ await modal.locator('.custom-base-url-input').fill('https://gateway.example.test/v1');
+ await modal.locator('.custom-model-input').fill('fixture-model');
+ }
+ const input = modal.locator(method === 'custom' ? '.custom-key-input' : '.api-key-input');
+ await input.fill('synthetic-native-submit-key');
+ await input.press('Enter');
+ const save = modal.locator('#add-account-actions .btn-primary');
+ await expect(save).toBeDisabled();
+ await expect.poll(() => app.electronApp!.evaluate(() => (globalThis as any).__settingsSubmitControl.calls)).toBe(1);
+ await input.press('Enter'); await input.press('Enter');
+ // Same-renderer IPC round trip follows the repeated keyboard events.
+ const pending = await app.invoke<any>('auth.listEntries', { includeUnavailable: true });
+ const calls = await app.electronApp!.evaluate(() => (globalThis as any).__settingsSubmitControl.calls);
+ const persistedRows = pending.entries.filter((entry: any) => entry.provider === provider).length;
+ expect({ calls, persistedRows }).toEqual({ calls: 1, persistedRows: previous + 1 });
+ await app.electronApp!.evaluate(() => (globalThis as any).__settingsSubmitControl.release());
+ await expect(modal).not.toHaveClass(/\bopen\b/);
+ const after = await app.invoke<any>('auth.listEntries', { includeUnavailable: true });
+ expect(after.entries.filter((entry: any) => entry.provider === provider)).toHaveLength(previous + 1);
+ } finally {
+ await app.electronApp!.evaluate(() => {
+ const control = (globalThis as any).__settingsSubmitControl;
+ control?.release(); control?.restore();
+ delete (globalThis as any).__settingsSubmitControl;
+ });
+ }
+ });
+}
diff --git a/test/main/features/auth.test.ts b/test/main/features/auth.test.ts
index 54653fff..86e93915 100644
--- a/test/main/features/auth.test.ts
+++ b/test/main/features/auth.test.ts
@@ -52,6 +52,57 @@ async function setDeepSeekEnabled(enabled: boolean): Promise<void> {
}, `"deepseek-${enabled ? 'on' : 'off'}"`);
}
+async function writeExpiredOAuthEntry({
+ providerId,
+ model,
+ uid = TEST_UID,
+ expires = Date.now() - 1000,
+ access = 'expired-access-token',
+ refresh = 'expired-refresh-token',
+}: {
+ providerId: string;
+ model: string;
+ uid?: string;
+ expires?: number;
+ access?: string;
+ refresh?: string;
+}): Promise<void> {
+ const paths = await import('../../../src/main/paths');
+ const localSecrets = await import('../../../src/main/util/local-secret-store');
+ const file = paths.userAuthProfilesFile(uid);
+ const ctx = { namespace: 'auth.profiles', ownerId: uid, recordId: 'auth-profiles.json' };
+ const profileId = `${providerId}:default`;
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, localSecrets.encryptLocalSecret(ctx, JSON.stringify({
+ version: 4,
+ profiles: {
+ [profileId]: {
+ type: 'oauth',
+ provider: providerId,
+ label: 'default',
+ access,
+ refresh,
+ expires,
+ createdAt: 1,
+ lastUsed: 0,
+ accountId: 'acct-test',
+ },
+ },
+ entries: [{
+ entryId: `entry-${providerId}`,
+ provider: providerId,
+ model,
+ profileId,
+ createdAt: 1,
+ lastUsed: 0,
+ }],
+ searchProfiles: [],
+ imageProfiles: [],
+ videoProfiles: [],
+ ttsProfiles: [],
+ })), 'utf8');
+}
+
describe('auth › maskKey', () => {
it('returns empty for non-string inputs', async () => {
const a = await import('../../../src/main/features/auth');
@@ -628,6 +679,45 @@ describe('auth › custom model configuration', () => {
]);
});
+ it.each([
+ ['contextWindow', [131_072]], ['contextWindow', { value: 131_072 }],
+ ['maxTokens', true], ['maxTokens', []], ['maxTokens', [32_768]],
+ ])('rejects non-scalar %s sizing without overwriting an existing credential (%#)', async (field, invalid) => {
+ const auth = await import('../../../src/main/features/auth');
+ const config = { label: 'typed-sizing', model: 'fixture-model',
+ baseUrl: 'https://fixture.invalid/v1', apiKey: 'synthetic',
+ contextWindow: 131_072, maxTokens: 32_768 };
+ await expect(auth.addCustomModelEntry({ ...config, [field]: invalid } as any))
+ .rejects.toMatchObject({ code: 'CUSTOM_TOKEN_LIMIT_INVALID' });
+ expect((await auth.listEntries({ includeUnavailable: true })).entries).toHaveLength(0);
+ const saved = await auth.addCustomModelEntry(config);
+ const before = await auth.pickChatEntryGroup();
+ await expect(auth.addCustomModelEntry({ ...config, [field]: invalid } as any))
+ .rejects.toMatchObject({ code: 'CUSTOM_TOKEN_LIMIT_INVALID' });
+ expect(await auth.pickChatEntryGroup()).toEqual(before);
+ expect((await auth.listEntries({ includeUnavailable: true })).entries).toHaveLength(1);
+ expect((await auth.pickChatEntryGroup())[0]?.entryId).toBe(saved.entryId);
+ await auth.addCustomModelEntry({ ...config, contextWindow: '131072', maxTokens: '65536' });
+ expect((await auth.pickChatEntryGroup())[0]?.customConfig).toMatchObject({
+ contextWindow: 131_072, maxTokens: 65_536,
+ });
+ });
+
+ it.each([1, 131_072, 16_777_216])('retains a valid output boundary %s without clamping', async maxTokens => {
+ const auth = await import('../../../src/main/features/auth');
+ await auth.addCustomModelEntry({ label: 'sizing-boundary', model: 'fixture-model',
+ baseUrl: 'https://fixture.invalid/v1', apiKey: 'synthetic', contextWindow: 16_777_216, maxTokens });
+ expect((await auth.pickChatEntryGroup())[0]?.customConfig?.maxTokens).toBe(maxTokens);
+ });
+
+ it.each([0, -1, 1.5, 16_777_217])('rejects invalid output boundary %s before saving a credential', async maxTokens => {
+ const auth = await import('../../../src/main/features/auth');
+ await expect(auth.addCustomModelEntry({ label: 'sizing-boundary', model: 'fixture-model',
+ baseUrl: 'https://fixture.invalid/v1', apiKey: 'synthetic', contextWindow: 16_777_216, maxTokens }))
+ .rejects.toMatchObject({ code: 'CUSTOM_TOKEN_LIMIT_INVALID' });
+ expect((await auth.listEntries({ includeUnavailable: true })).entries).toHaveLength(0);
+ });
+
it('rejects API keys that cannot be sent in an Authorization header without a partial credential', async () => {
const a = await import('../../../src/main/features/auth');
@@ -1090,6 +1180,7 @@ describe('auth › hasConfiguredModel', () => {
});
describe('auth › listModels', () => {
+
it('returns the hand-curated list for a known provider', async () => {
const a = await import('../../../src/main/features/auth');
const { models } = await a.listModels('anthropic');
@@ -1552,3 +1643,384 @@ describe('auth › durable shared profile contracts', () => {
});
});
+
+
+describe('auth › user-owned configuration operations', () => {
+ it.each(['addApiKeyEntry', 'addEntry', 'updateEntryModel', 'reorderEntries', 'selectEntry', 'selectVersion'].flatMap(operation =>
+ ['different-account', 'anonymous', ...(['updateEntryModel', 'reorderEntries', 'selectEntry', 'selectVersion'].includes(operation) ? ['credential-added', 'credential-removed'] : [])].map(destination => [operation, destination]),
+ ))('does not publish %s after its metadata wait crosses into %s', async (operation, destination) => {
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let entered = false;
+ vi.doMock('#core-agent', async importOriginal => {
+ entered = true; await gate;
+ return importOriginal();
+ });
+ const auth = await import('../../../src/main/features/auth');
+ const users = await import('../../../src/main/features/users');
+ const paths = await import('../../../src/main/paths');
+ const secrets = await import('../../../src/main/util/local-secret-store');
+ const other = destination === 'anonymous' ? users.ANONYMOUS_LOCAL_ID : 'auth-owner-b';
+ const files = [TEST_UID, other].map(uid => paths.userAuthProfilesFile(uid));
+ for (const uid of [TEST_UID, other]) {
+ users.activateUser(uid);
+ await auth.addApiKey('openai', `synthetic-${uid}-key`, 'owner');
+ const file = paths.userAuthProfilesFile(uid);
+ const context = { namespace: 'auth.profiles', ownerId: uid, recordId: 'auth-profiles.json' };
+ const store = JSON.parse(secrets.decryptLocalSecret(context, fs.readFileSync(file, 'utf8')));
+ store.entries = ['gpt-5.6-sol', 'gpt-5.6-terra'].map((model, index) => ({
+ entryId: `entry-${index}`, provider: 'openai', model, profileId: 'openai:owner', createdAt: 1, lastUsed: 0,
+ }));
+ fs.writeFileSync(file, secrets.encryptLocalSecret(context, JSON.stringify(store)));
+ }
+ users.activateUser(TEST_UID);
+ const before = files.map(file => fs.readFileSync(file, 'utf8'));
+ const run = () => {
+ if (operation === 'addApiKeyEntry') return auth.addApiKeyEntry('openai', 'gpt-5.6-sol', 'synthetic-new-key', 'new');
+ if (operation === 'addEntry') return auth.addEntry({ provider: 'openai', model: 'gpt-6-sol', profileId: 'openai:owner' });
+ if (operation === 'updateEntryModel') return auth.updateEntryModel('entry-0', 'gpt-6-sol');
+ if (operation === 'reorderEntries') return auth.reorderEntries(['entry-1', 'entry-0']);
+ return auth.selectEntry('entry-1', operation === 'selectVersion' ? 'gpt-6-sol' : undefined);
+ };
+ const pending = run().then(() => 'saved', () => 'rejected');
+ try {
+ await vi.waitFor(() => expect(entered).toBe(true));
+ if (destination === 'credential-added') await auth.addApiKey('anthropic', 'synthetic-newer-key', 'newer');
+ else if (destination === 'credential-removed') await auth.removeCredential('openai:owner');
+ else users.activateUser(other);
+ const expected = destination.startsWith('credential-') ? files.map(file => fs.readFileSync(file, 'utf8')) : before;
+ release();
+ const outcome = await pending;
+ expect({ outcome, stores: files.map(file => fs.readFileSync(file, 'utf8')) })
+ .toEqual({ outcome: 'rejected', stores: expected });
+ if (destination === 'credential-removed') return;
+ // A fresh explicit operation in the original account remains usable.
+ users.activateUser(TEST_UID);
+ await run();
+ expect(fs.readFileSync(files[1], 'utf8')).toBe(before[1]);
+ expect(fs.readFileSync(files[0], 'utf8')).not.toBe(before[0]);
+ } finally {
+ release(); await pending;
+ }
+ });
+});
+
+describe('auth › OAuth login ownership and cancellation', () => {
+ async function prepareLogin() {
+ let release!: (credentials: any) => void;
+ let reject!: (error: Error) => void;
+ const gate = new Promise<any>((resolve, fail) => { release = resolve; reject = fail; });
+ let callbacks: any;
+ const login = vi.fn((value: any) => { callbacks = value; return gate; });
+ const provider = { id: 'anthropic', name: 'Anthropic', login, refreshToken: vi.fn(), getApiKey: (value: any) => value.access };
+ const lookup = vi.fn(() => provider);
+ vi.doMock('@earendil-works/pi-ai/oauth', () => ({
+ getOAuthProvider: lookup, getOAuthProviders: () => [provider], registerOAuthProvider: vi.fn(),
+ }));
+ const auth = await import('../../../src/main/features/auth');
+ const users = await import('../../../src/main/features/users');
+ const paths = await import('../../../src/main/paths');
+ const secrets = await import('../../../src/main/util/local-secret-store');
+ const other = 'oauth-login-owner-b';
+ for (const uid of [TEST_UID, other]) {
+ users.activateUser(uid); await auth.addApiKey('openai', `synthetic-${uid}-key`, 'owner');
+ }
+ users.activateUser(TEST_UID);
+ const files = [TEST_UID, other].map(uid => paths.userAuthProfilesFile(uid));
+ const before = files.map(file => fs.readFileSync(file, 'utf8'));
+ const credentials = { access: 'synthetic-login-access', refresh: 'synthetic-login-refresh', expires: Date.now() + 3_600_000 };
+ return { auth, users, secrets, other, files, before, credentials, release, reject, login, lookup, provider, get callbacks() { return callbacks; } };
+ }
+
+ it.each(['success', 'account-switch', 'cancelled-success', 'cancelled-failure'])('preserves credential stores and terminal ownership for %s', async scenario => {
+ const fixture = await prepareLogin();
+ const { auth, users, other, files, before, credentials } = fixture;
+ const { flowId } = await auth.startOAuth('anthropic', 'login');
+ try {
+ if (scenario === 'account-switch') users.activateUser(other);
+ if (scenario.startsWith('cancelled')) {
+ vi.useFakeTimers();
+ expect(auth.cancelOAuthFlow(flowId)).toEqual({ ok: true });
+ expect(fixture.callbacks.signal.aborted).toBe(true);
+ }
+ if (scenario === 'cancelled-failure') fixture.reject(new Error('synthetic provider failure'));
+ else fixture.release(credentials);
+ await new Promise<void>(resolve => queueMicrotask(resolve));
+ await new Promise<void>(resolve => queueMicrotask(resolve));
+ const status = auth.pollOAuthFlow(flowId).status;
+ if (scenario === 'success') {
+ expect(status).toMatchObject({ kind: 'done', profileId: 'anthropic:login' });
+ const saved = JSON.parse(fixture.secrets.decryptLocalSecret({
+ namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json',
+ }, fs.readFileSync(files[0], 'utf8')));
+ expect(saved.profiles['anthropic:login']).toMatchObject(credentials);
+ expect(fs.readFileSync(files[1], 'utf8')).toBe(before[1]);
+ } else {
+ expect({ stores: files.map(file => fs.readFileSync(file, 'utf8')), kind: status.kind })
+ .toEqual({ stores: before, kind: 'error' });
+ if (scenario.startsWith('cancelled')) expect(status).toEqual({ kind: 'error', error: 'cancelled' });
+ }
+ } finally {
+ fixture.release(credentials);
+ await new Promise<void>(resolve => queueMicrotask(resolve));
+ vi.clearAllTimers(); vi.useRealTimers();
+ }
+ });
+
+ it('does not let a different account read, submit to or cancel an existing login', async () => {
+ const fixture = await prepareLogin();
+ const { auth, users, credentials } = fixture;
+ const { flowId } = await auth.startOAuth('anthropic', 'login');
+ const answer = fixture.callbacks.onPrompt({ message: 'synthetic owner-only prompt' });
+ try {
+ users.activateUser(fixture.other);
+ const poll = auth.pollOAuthFlow(flowId).status;
+ const submit = auth.submitOAuthInput(flowId, 'foreign-input');
+ const cancel = auth.cancelOAuthFlow(flowId);
+ expect({ kind: poll.kind, submit, cancel, aborted: fixture.callbacks.signal.aborted })
+ .toEqual({ kind: 'error', submit: { ok: false }, cancel: { ok: false }, aborted: false });
+ expect(JSON.stringify(poll)).not.toContain('synthetic owner-only prompt');
+ users.activateUser(TEST_UID);
+ expect(auth.submitOAuthInput(flowId, 'owner-input')).toEqual({ ok: true });
+ expect(await answer).toBe('owner-input');
+ fixture.release(credentials);
+ await vi.waitFor(() => expect(auth.pollOAuthFlow(flowId).status.kind).toBe('done'));
+ } finally {
+ users.activateUser(TEST_UID); vi.useFakeTimers();
+ auth.cancelOAuthFlow(flowId); fixture.release(credentials);
+ await answer;
+ await new Promise<void>(resolve => queueMicrotask(resolve));
+ vi.clearAllTimers(); vi.useRealTimers();
+ }
+ });
+
+
+ it.each(['http-response', 'exchange-details', 'invalid-json'])('keeps raw %s provider failures out of the OAuth status and diagnostics', async shape => {
+ const fixture = await prepareLogin();
+ const secret = 'synthetic-oauth-private-marker';
+ const body = JSON.stringify({ access_token: secret, email: '[email protected]', request_path: '/Users/test/private/login' });
+ const detail = `HTTP request failed. status=401; url=https://provider.example.test/token?code=${secret}; body=${body}`;
+ // Accepted error formats from the pinned Anthropic OAuth SDK. Its body
+ // may contain arbitrary remote data, so exposing a sanitized substring
+ // does not establish the authorization-failure UI contract.
+ const message = shape === 'http-response' ? detail : shape === 'invalid-json'
+ ? `Token exchange returned invalid JSON. url=https://provider.example.test/token; body=${body}; details=SyntaxError`
+ : `Token exchange request failed. url=https://provider.example.test/token; redirect_uri=http://localhost:1455/callback?code=${secret}; response_type=authorization_code; details=${detail}`;
+ const { flowId } = await fixture.auth.startOAuth('anthropic', 'login');
+ try {
+ fixture.reject(new Error(message));
+ await vi.waitFor(() => expect(fixture.auth.pollOAuthFlow(flowId).status.kind).toBe('error'));
+ const status = fixture.auth.pollOAuthFlow(flowId).status as { kind: string; error?: string };
+ expect(status.error).toBeFalsy(); // Renderer must use its existing localized failure copy.
+ const published = JSON.stringify({ status, warnings: loggerMocks.warn.mock.calls });
+ for (const value of [secret, '[email protected]', '/Users/test/private/login', 'provider.example.test', body]) {
+ expect(published).not.toContain(value);
+ }
+ expect(fixture.files.map(file => fs.readFileSync(file, 'utf8'))).toEqual(fixture.before);
+ } finally {
+ vi.useFakeTimers(); fixture.auth.cancelOAuthFlow(flowId); fixture.release(fixture.credentials);
+ await Promise.resolve(); vi.clearAllTimers(); vi.useRealTimers();
+ }
+ });
+
+ it('does not start a provider login when account ownership changes during provider discovery', async () => {
+ const fixture = await prepareLogin();
+ let entered = false;
+ let releaseLookup!: () => void;
+ const gate = new Promise<void>(resolve => { releaseLookup = resolve; });
+ fixture.lookup.mockImplementation((async () => { entered = true; await gate; return fixture.provider; }) as any);
+ const pending = fixture.auth.startOAuth('anthropic', 'login').then(() => 'started', () => 'rejected');
+ try {
+ await vi.waitFor(() => expect(entered).toBe(true));
+ fixture.users.activateUser(fixture.other);
+ releaseLookup(); fixture.release(fixture.credentials);
+ const result = await pending;
+ await new Promise<void>(resolve => queueMicrotask(resolve));
+ expect({ result, calls: fixture.login.mock.calls.length, stores: fixture.files.map(file => fs.readFileSync(file, 'utf8')) })
+ .toEqual({ result: 'rejected', calls: 0, stores: fixture.before });
+ } finally {
+ releaseLookup(); fixture.release(fixture.credentials); await pending;
+ }
+ });
+});
+
+
+describe('auth › interrupted connection and rotation ownership', () => {
+ const probes = ['metadata', 'refresh', 'discovery', 'factory', 'stream'].flatMap(stage => ['explicit', 'rotation'].flatMap(mode =>
+ ['same-account', 'different-account', 'anonymous'].map(destination => [stage, mode, destination]),
+ ));
+ probes.push(...['same-account', 'different-account', 'anonymous'].map(destination => ['refresh', 'rotation-key', destination]));
+ it.each(probes)('keeps %s %s work within its initiating account after %s', async (stage, mode, destination) => {
+ let entered = false;
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ vi.doMock('#core-agent', async importOriginal => {
+ if (stage === 'metadata') { entered = true; await gate; }
+ if (stage === 'refresh') return { ...await importOriginal<any>(), createPiProvider: (config: unknown) => { factory(config); return { stream, complete }; } };
+ return {};
+ });
+ const providerId = stage === 'refresh' ? 'openai-codex' : 'custom';
+ const modelId = stage === 'refresh' ? 'gpt-5.6-sol' : 'controlled-probe';
+ const profileId = `${providerId}:${stage === 'refresh' ? 'default' : 'probe'}`;
+ const credentials = { access: 'synthetic-rotated-access', refresh: 'synthetic-rotated-refresh', expires: Date.now() + 3_600_000 };
+ const refresh = vi.fn(async () => { entered = true; await gate; return credentials; });
+ const oauthProvider = { id: providerId, name: 'Controlled OAuth fixture', login: vi.fn(), refreshToken: refresh, getApiKey: (c: any) => c.access };
+ vi.doMock('@earendil-works/pi-ai/oauth', () => ({
+ getOAuthProvider: (id: string) => id === providerId ? oauthProvider : undefined,
+ getOAuthProviders: () => [oauthProvider], registerOAuthProvider: vi.fn(),
+ }));
+ const stream = vi.fn(() => (async function* () { if (stage === 'stream') { entered = true; await gate; } yield { type: 'text_delta', text: 'OK' }; })());
+ const complete = async () => {
+ for await (const _event of stream()) { /* Complete consumes the public provider stream. */ }
+ return { content: [{ type: 'text', text: 'OK' }], model: modelId, stopReason: 'end_turn' };
+ };
+ const factory = vi.fn(async (_config: unknown) => {
+ if (stage === 'factory') { entered = true; await gate; }
+ return { stream, complete };
+ });
+ vi.doMock('../../../src/main/model/core-agent/external-providers', async () => {
+ if (stage === 'discovery') { entered = true; await gate; }
+ return { createCustomOpenAICompatibleProvider: factory };
+ });
+ const auth = await import('../../../src/main/features/auth');
+ const users = await import('../../../src/main/features/users');
+ const paths = await import('../../../src/main/paths');
+ const secrets = await import('../../../src/main/util/local-secret-store');
+ const other = destination === 'anonymous' ? users.ANONYMOUS_LOCAL_ID : 'probe-owner-b';
+ const read = (uid: string) => JSON.parse(secrets.decryptLocalSecret({ namespace: 'auth.profiles', ownerId: uid, recordId: 'auth-profiles.json' }, fs.readFileSync(paths.userAuthProfilesFile(uid), 'utf8')));
+ for (const uid of [TEST_UID, other]) {
+ users.activateUser(uid);
+ if (stage === 'refresh') await writeExpiredOAuthEntry({ providerId, model: modelId, uid });
+ else await auth.addCustomModelEntry({ label: 'probe', baseUrl: 'https://gateway.example.test/v1', model: modelId, apiKey: `synthetic-${uid}-key` });
+ }
+ users.activateUser(TEST_UID);
+ const otherBefore = fs.readFileSync(paths.userAuthProfilesFile(other), 'utf8');
+ const pending = mode === 'rotation-key' ? auth.pickRotationKey(providerId)
+ : auth.testConnection(providerId, modelId, mode === 'explicit' ? profileId : undefined);
+ try {
+ await vi.waitFor(() => expect(entered).toBe(true));
+ if (destination !== 'same-account') users.activateUser(other);
+ const cooldown = await import('../../../src/main/model/core-agent/profile-cooldown');
+ if (stage === 'stream') cooldown.markCooldown(profileId, 'auth', 'fixture newly active account cooldown');
+ release();
+ const result = await pending;
+ if (stage === 'stream') {
+ // The already-started probe may finish, but its old result must not
+ // clear an independently established cooldown in the new account.
+ expect(result).toMatchObject({ ok: true, profileId });
+ expect(stream).toHaveBeenCalledTimes(1);
+ expect(cooldown.isCooledDown(profileId)).toBe(destination !== 'same-account');
+ expect(fs.readFileSync(paths.userAuthProfilesFile(other), 'utf8')).toBe(otherBefore);
+ } else if (destination === 'same-account') {
+ if (mode === 'rotation-key') expect(result).toMatchObject({ apiKey: credentials.access, profileId });
+ else {
+ expect(result).toMatchObject({ ok: true, profileId });
+ expect(stream).toHaveBeenCalledTimes(1);
+ expect(factory).toHaveBeenCalledWith(expect.objectContaining({ apiKey: stage === 'refresh' ? credentials.access : `synthetic-${TEST_UID}-key` }));
+ }
+ } else {
+ // No stale key may escape and no provider request may start after a
+ // boundary was crossed. The other encrypted store must stay exact.
+ expect({ result: mode === 'rotation-key' ? result : (result as any)?.ok,
+ streamCalls: stream.mock.calls.length,
+ otherBytes: fs.readFileSync(paths.userAuthProfilesFile(other), 'utf8') })
+ .toEqual({ result: mode === 'rotation-key' ? null : false, streamCalls: 0, otherBytes: otherBefore });
+ if (stage === 'metadata' || stage === 'discovery') expect(factory).not.toHaveBeenCalled();
+ }
+ if (stage === 'refresh') {
+ expect(refresh).toHaveBeenCalledTimes(1);
+ // A rotating refresh already admitted still persists to its owner.
+ expect(read(TEST_UID).profiles[profileId]).toMatchObject(credentials);
+ }
+ } finally {
+ release(); await pending;
+ vi.doUnmock('../../../src/main/model/core-agent/external-providers');
+ }
+ });
+});
+
+describe('auth › chat picker operation ownership', () => {
+ it.each(['api_key', 'oauth'] as const)('does not resolve %s credentials after model discovery crosses into another account', async kind => {
+ let release!: () => void;
+ let entered = false;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ vi.doMock('#core-agent', async original => { entered = true; await gate; return original(); });
+ const providerId = kind === 'oauth' ? 'openai-codex' : 'openai';
+ const model = 'gpt-5.6-sol';
+ const refresh = vi.fn(async () => ({ access: 'synthetic-refreshed-a', refresh: 'synthetic-next-a', expires: Date.now() + 3_600_000 }));
+ const oauthProvider = { id: providerId, name: 'Controlled OAuth fixture', refreshToken: refresh, getApiKey: (c: any) => c.access };
+ vi.doMock('@earendil-works/pi-ai/oauth', () => ({
+ getOAuthProvider: () => oauthProvider, getOAuthProviders: () => [oauthProvider], registerOAuthProvider: vi.fn(),
+ }));
+ const auth = await import('../../../src/main/features/auth');
+ const users = await import('../../../src/main/features/users');
+ const paths = await import('../../../src/main/paths');
+ const secrets = await import('../../../src/main/util/local-secret-store');
+ const other = 'chat-picker-owner-b';
+ for (const uid of [TEST_UID, other]) {
+ users.activateUser(uid);
+ if (kind === 'oauth') await writeExpiredOAuthEntry({ providerId, model, uid, access: `synthetic-${uid}-old`, refresh: `synthetic-${uid}-refresh` });
+ else {
+ const saved = await auth.addApiKey(providerId, `synthetic-${uid}-key`, 'default');
+ const file = paths.userAuthProfilesFile(uid);
+ const context = { namespace: 'auth.profiles', ownerId: uid, recordId: 'auth-profiles.json' };
+ const store = JSON.parse(secrets.decryptLocalSecret(context, fs.readFileSync(file, 'utf8')));
+ store.entries = [{ entryId: 'entry-picker', provider: providerId, model, profileId: saved.profileId, createdAt: 1, lastUsed: 0 }];
+ fs.writeFileSync(file, secrets.encryptLocalSecret(context, JSON.stringify(store)));
+ }
+ }
+ users.activateUser(TEST_UID);
+ const otherBefore = fs.readFileSync(paths.userAuthProfilesFile(other), 'utf8');
+ const pending = auth.pickChatEntryGroup();
+ try {
+ await vi.waitFor(() => expect(entered).toBe(true));
+ users.activateUser(other);
+ release();
+ const choices = await pending;
+ expect({ choices, refreshCalls: refresh.mock.calls.length, otherBytes: fs.readFileSync(paths.userAuthProfilesFile(other), 'utf8') })
+ .toEqual({ choices: [], refreshCalls: 0, otherBytes: otherBefore });
+ // Returning to the originating account admits a fresh explicit lookup.
+ users.activateUser(TEST_UID);
+ expect((await auth.pickChatEntryGroup())[0]).toMatchObject({ provider: providerId, apiKey: kind === 'oauth' ? 'synthetic-refreshed-a' : `synthetic-${TEST_UID}-key` });
+ if (kind === 'oauth') expect(refresh).toHaveBeenCalledWith(expect.objectContaining({ access: `synthetic-${TEST_UID}-old` }));
+ expect(fs.readFileSync(paths.userAuthProfilesFile(other), 'utf8')).toBe(otherBefore);
+ } finally { release(); await pending; }
+ });
+
+ it.each(['success', 'failure'] as const)('settles an admitted OAuth refresh %s without returning a stale choice or changing the new account failure state', async outcome => {
+ let release!: () => void;
+ let entered = false;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const other = 'chat-picker-refresh-b';
+ const credentials = { access: 'synthetic-refreshed-a', refresh: 'synthetic-next-a', expires: Date.now() + 3_600_000 };
+ const refresh = vi.fn(async (old: any) => {
+ if (old.access === 'synthetic-b-old') throw new Error('synthetic B refresh failure');
+ entered = true; await gate;
+ if (outcome === 'failure') throw new Error('synthetic A refresh failure');
+ return credentials;
+ });
+ const provider = { id: 'openai-codex', name: 'Controlled OAuth fixture', refreshToken: refresh, getApiKey: (c: any) => c.access };
+ vi.doMock('@earendil-works/pi-ai/oauth', () => ({ getOAuthProvider: () => provider, getOAuthProviders: () => [provider], registerOAuthProvider: vi.fn() }));
+ const auth = await import('../../../src/main/features/auth');
+ const users = await import('../../../src/main/features/users');
+ const paths = await import('../../../src/main/paths');
+ const secrets = await import('../../../src/main/util/local-secret-store');
+ for (const uid of [TEST_UID, other]) await writeExpiredOAuthEntry({ providerId: provider.id, model: 'gpt-5.6-sol', uid, access: uid === other ? 'synthetic-b-old' : 'synthetic-a-old' });
+ users.activateUser(other);
+ if (outcome === 'success') expect(await auth.pickRotationKey(provider.id)).toBeNull();
+ const otherFailure = auth.getConfiguredModelOAuthExpiredMessage();
+ expect(Boolean(otherFailure)).toBe(outcome === 'success');
+ const otherBefore = fs.readFileSync(paths.userAuthProfilesFile(other), 'utf8');
+ users.activateUser(TEST_UID);
+ const pending = auth.pickChatEntryGroup();
+ try {
+ await vi.waitFor(() => expect(entered).toBe(true));
+ users.activateUser(other); release();
+ expect(await pending).toEqual([]);
+ expect(auth.getConfiguredModelOAuthExpiredMessage()).toBe(otherFailure);
+ expect(fs.readFileSync(paths.userAuthProfilesFile(other), 'utf8')).toBe(otherBefore);
+ const original = JSON.parse(secrets.decryptLocalSecret({ namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json' }, fs.readFileSync(paths.userAuthProfilesFile(TEST_UID), 'utf8')));
+ expect(original.profiles['openai-codex:default'].access).toBe(outcome === 'success' ? credentials.access : 'synthetic-a-old');
+ } finally { release(); await pending; }
+ });
+});
diff --git a/test/renderer/settings-add-account.test.ts b/test/renderer/settings-add-account.test.ts
index 3b44c0c4..1f73a437 100644
--- a/test/renderer/settings-add-account.test.ts
+++ b/test/renderer/settings-add-account.test.ts
@@ -41,6 +41,12 @@ class FakeElement {
this.listeners.set(type, handlers);
}
+ keyDown(key: string) {
+ for (const handler of this.listeners.get('keydown') || []) {
+ handler({ key, keyCode: key === 'Enter' ? 13 : 0, isComposing: false, preventDefault: vi.fn() });
+ }
+ }
+
async click() {
if (this.onclick) await this.onclick({ currentTarget: this, target: this });
for (const handler of this.listeners.get('click') || []) {
@@ -204,23 +210,23 @@ function loadSettingsClickHarness(
return { context, elements, indexHtml, settingsSource: source, invoke, monitor, selects };
}
-it('submits the shared protocol picker selection without losing a gateway prefix', async () => {
+it.each(['anthropic'])('submits the %s protocol picker selection without losing a gateway prefix', async protocol => {
const { context, elements, invoke, selects } = loadSettingsClickHarness();
const body = elements.get('add-account-body')!;
for (const [selector, value] of Object.entries({
'.custom-label-input': 'Gateway', '.custom-protocol-input': 'anthropic',
- '.custom-base-url-input': 'https://gateway.example.test/proxy/v1/messages',
+ '.custom-base-url-input': protocol === 'responses' ? 'https://gateway.example.test/proxy/v1/responses' : 'https://gateway.example.test/proxy/v1/messages',
'.custom-model-input': 'claude-gateway-alias', '.custom-max-tokens-input': '8192',
'.custom-key-input': 'synthetic-form-key', '.form-msg': '',
})) { const field = new FakeElement(); field.value = value; body.setQueryResult(selector, field); }
context._settingsShowCustomModelForm({ id: 'custom', label: 'Custom' });
const protocolPicker = selects.get(body.querySelector('.custom-protocol-input')!);
expect(protocolPicker.getValue()).toBe('openai');
- protocolPicker.emitChange('anthropic');
- expect(body.querySelector('.custom-base-url-input')!.placeholder).toBe('https://api.example.com');
+ protocolPicker.emitChange(protocol);
+ expect(body.querySelector('.custom-base-url-input')!.placeholder).toBe(protocol === 'anthropic' ? 'https://api.example.com' : 'https://api.example.com/v1');
await elements.get('add-account-actions')!.children.at(-1)!.click();
expect(invoke).toHaveBeenCalledWith('auth.addCustomModelEntry', {
- label: 'Gateway', protocol: 'anthropic', baseUrl: 'https://gateway.example.test/proxy/v1/messages',
+ label: 'Gateway', protocol, baseUrl: protocol === 'responses' ? 'https://gateway.example.test/proxy/v1/responses' : 'https://gateway.example.test/proxy/v1/messages',
model: 'claude-gateway-alias', maxTokens: '8192', apiKey: 'synthetic-form-key',
});
});
@@ -685,7 +691,8 @@ describe('settings model authorization add account', () => {
oauthProviderId: 'openai-codex',
modelId: 'gpt-5.6-sol'
};
- _oauthFlowTelemetry = { startedAt: Date.now(), done: false };
+ _oauthFlowOwner = { closeFlow: __closeFlow, settling: false };
+ _oauthFlowOwner = { closeFlow: __closeFlow, settling: false };
_oauthFlowRender(
{ id: 'openai-codex' },
{ kind: 'done', profileId: 'openai-codex:new-account' },
@@ -721,7 +728,8 @@ describe('settings model authorization add account', () => {
oauthProviderId: 'openai-codex',
modelId: 'gpt-5.6-sol'
};
- _oauthFlowTelemetry = { startedAt: Date.now(), done: false };
+ _oauthFlowOwner = { closeFlow: __closeFlow, settling: false };
+ _oauthFlowOwner = { closeFlow: __closeFlow, settling: false };
_oauthFlowRender(
{ id: 'openai-codex' },
{ kind: 'done', profileId: 'openai-codex:new-account' },
@@ -748,7 +756,8 @@ describe('settings model authorization add account', () => {
oauthProviderId: 'openai-codex',
modelId: 'gpt-5.6-sol'
};
- _oauthFlowTelemetry = { startedAt: Date.now(), done: false };
+ _oauthFlowOwner = { closeFlow: __closeFlow, settling: false };
+ _oauthFlowOwner = { closeFlow: __closeFlow, settling: false };
_oauthFlowRender(
{ id: 'openai-codex' },
{ kind: 'done' },
@@ -778,3 +787,300 @@ it('shows legacy unsupported video profiles as unavailable instead of active', a
const main = row.children.find((child) => child.className === 'entry-main');
expect(main?.children.find((child) => child.className === 'form-hint')?.textContent).toBe('settings.video.provider_unavailable');
});
+
+
+describe('credential form repeated keyboard submission', () => {
+ it.each([
+ ['api_key', 'success'], ['api_key', 'rejected'], ['api_key', 'thrown'],
+ ['custom', 'success'], ['custom', 'rejected'], ['custom', 'thrown'],
+ ])('submits the %s form once while pending and preserves %s recovery', async (method, outcome) => {
+ const channel = method === 'custom' ? 'auth.addCustomModelEntry' : 'auth.addApiKeyEntry';
+ let release!: (result: Record<string, unknown>) => void;
+ let reject!: (error: Error) => void;
+ const gate = new Promise<Record<string, unknown>>((resolve, fail) => { release = resolve; reject = fail; });
+ let attempts = 0;
+ const { context, elements, invoke, monitor } = loadSettingsClickHarness(async current => {
+ if (current !== channel) return { ok: true };
+ attempts += 1;
+ return attempts === 1 ? gate : { ok: true };
+ });
+ vm.runInContext('_settingsReload = async () => {};', context);
+ const body = elements.get('add-account-body')!;
+ const values = method === 'custom' ? {
+ '.custom-label-input': '', '.custom-protocol-input': '',
+ '.custom-base-url-input': 'https://gateway.example.test/v1',
+ '.custom-model-input': 'fixture-model', '.custom-max-tokens-input': '',
+ '.custom-key-input': 'synthetic-form-key', '.form-msg': '',
+ } : {
+ '.api-label-input': '', '.api-key-input': 'synthetic-form-key', '.form-msg': '',
+ };
+ for (const [selector, value] of Object.entries(values)) {
+ const field = new FakeElement(); field.value = value; body.setQueryResult(selector, field);
+ }
+ if (method === 'custom') context._settingsShowCustomModelForm({ id: 'custom', label: 'Custom' });
+ else context._settingsShowApiKeyForm({ id: 'openai', label: 'OpenAI' }, 'gpt-5.6-sol');
+ const input = body.querySelector(method === 'custom' ? '.custom-key-input' : '.api-key-input')!;
+ const save = elements.get('add-account-actions')!.children.at(-1)!;
+ try {
+ input.keyDown('Enter');
+ expect(save.disabled).toBe(true);
+ input.keyDown('Enter'); input.keyDown('Enter');
+ expect(invoke.mock.calls.filter(call => call[0] === channel)).toHaveLength(1);
+ if (outcome === 'thrown') reject(new Error('synthetic write failure'));
+ else release(outcome === 'rejected' ? { ok: false, code: 'WRITE_FAILED' } : { ok: true });
+ await vi.waitFor(() => expect(outcome === 'success'
+ ? elements.get('add-account-modal')!.classList.contains('open') : save.disabled).toBe(false));
+ if (outcome === 'success') {
+ expect(elements.get('add-account-modal')!.classList.contains('open')).toBe(false);
+ } else {
+ expect(elements.get('add-account-modal')!.classList.contains('open')).toBe(true);
+ expect(save.disabled).toBe(false);
+ input.keyDown('Enter');
+ await vi.waitFor(() => expect(elements.get('add-account-modal')!.classList.contains('open')).toBe(false));
+ expect(invoke.mock.calls.filter(call => call[0] === channel)).toHaveLength(2);
+ }
+ } finally {
+ release({ ok: true });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+ });
+});
+
+
+describe('credential dialog response ownership', () => {
+ function openCredential(context: any, elements: Map<string, FakeElement>, method: string) {
+ const body = elements.get('add-account-body')!;
+ const values = method === 'custom' ? {
+ '.custom-label-input': '', '.custom-protocol-input': '',
+ '.custom-base-url-input': 'https://gateway.example.test/v1',
+ '.custom-model-input': 'fixture-model', '.custom-max-tokens-input': '',
+ '.custom-key-input': 'synthetic-dialog-key', '.form-msg': '',
+ } : { '.api-label-input': '', '.api-key-input': 'synthetic-dialog-key', '.form-msg': '' };
+ for (const [selector, value] of Object.entries(values)) {
+ const field = new FakeElement(); field.value = value; body.setQueryResult(selector, field);
+ }
+ if (method === 'custom') context._settingsShowCustomModelForm({ id: 'custom', label: 'Custom' });
+ else context._settingsShowApiKeyForm({ id: 'openai', label: 'OpenAI' }, 'gpt-5.6-sol');
+ }
+
+ it.each(['api_key', 'custom'].flatMap(method => [
+ [method, 'closed', 'success'], [method, 'reopened', 'success'], [method, 'reopened', 'rejected'],
+ ]))('does not close or repaint a newer dialog after %s finishes %s with %s', async (method, destination, outcome) => {
+ let release!: (result: Record<string, unknown>) => void;
+ const gate = new Promise<Record<string, unknown>>(resolve => { release = resolve; });
+ const channel = method === 'custom' ? 'auth.addCustomModelEntry' : 'auth.addApiKeyEntry';
+ const { context, elements, invoke, monitor } = loadSettingsClickHarness(async current => current === channel ? gate : { ok: true });
+ vm.runInContext('_settingsReload = async () => {};', context);
+ openCredential(context, elements, method);
+ const actions = elements.get('add-account-actions')!;
+ const pending = actions.children.at(-1)!.click();
+ try {
+ await actions.children.at(-2)!.click();
+ if (destination === 'reopened') openCredential(context, elements, method === 'custom' ? 'api_key' : 'custom');
+ const body = elements.get('add-account-body')!.innerHTML;
+ const title = elements.get('add-account-title')!.textContent;
+ release(outcome === 'success' ? { ok: true } : { ok: false, code: 'WRITE_FAILED' });
+ await pending;
+ expect(elements.get('add-account-modal')!.classList.contains('open')).toBe(destination === 'reopened');
+ expect(elements.get('add-account-body')!.innerHTML).toBe(body);
+ expect(elements.get('add-account-title')!.textContent).toBe(title);
+ expect(invoke.mock.calls.filter(call => call[0] === channel)).toHaveLength(1);
+ } finally {
+ release({ ok: true }); await pending;
+ context._settingsCloseModal(elements.get('add-account-modal'));
+ }
+ });
+});
+
+describe('OAuth dialog asynchronous ownership', () => {
+ function controlIntervals(context: any) {
+ const active = new Map<number, () => Promise<void>>();
+ let next = 0;
+ context.setInterval = (callback: () => Promise<void>) => { active.set(++next, callback); return next; };
+ context.clearInterval = (id: number) => { active.delete(id); };
+ return active;
+ }
+ const settle = () => new Promise(resolve => setTimeout(resolve, 0));
+
+ it.each(['closed', 'reopened'])('cancels a late startup response after its modal was %s', async destination => {
+ let release!: (result: Record<string, unknown>) => void;
+ const gate = new Promise<Record<string, unknown>>(resolve => { release = resolve; });
+ let starts = 0;
+ const { context, elements, invoke } = loadSettingsClickHarness(async channel => {
+ if (channel === 'auth.startOAuth') return ++starts === 1 ? gate : { ok: true, flowId: 'new-flow' };
+ return { ok: true, status: { kind: 'starting' } };
+ });
+ const active = controlIntervals(context);
+ const pending = context._settingsStartOAuthFlow({ id: 'old-provider' }, 'old-model');
+ try {
+ await elements.get('oauth-flow-close-btn')!.click();
+ if (destination === 'reopened') await context._settingsStartOAuthFlow({ id: 'new-provider' }, 'new-model');
+ const body = elements.get('oauth-flow-body')!.innerHTML;
+ release({ ok: true, flowId: 'old-flow' }); await pending;
+ expect(invoke).toHaveBeenCalledWith('auth.cancelOAuthFlow', { flowId: 'old-flow' });
+ expect(active.size).toBe(destination === 'reopened' ? 1 : 0);
+ for (const callback of active.values()) await callback();
+ const polls = invoke.mock.calls.filter(call => call[0] === 'auth.pollOAuthFlow');
+ expect(polls.map(call => call[1])).toEqual(destination === 'reopened' ? [{ flowId: 'new-flow' }] : []);
+ expect(elements.get('oauth-flow-modal')!.classList.contains('open')).toBe(destination === 'reopened');
+ if (destination === 'closed') expect(elements.get('oauth-flow-body')!.innerHTML).toBe(body);
+ } finally {
+ release({ ok: true, flowId: 'old-flow' }); await pending;
+ await elements.get('oauth-flow-close-btn')!.click(); active.clear();
+ }
+ });
+
+ it.each(['starting', 'done', 'error'].flatMap(kind => ['closed', 'reopened'].map(destination => [kind, destination])))('discards an obsolete %s poll after the dialog was %s', async (kind, destination) => {
+ let release!: (result: Record<string, unknown>) => void;
+ const gate = new Promise<Record<string, unknown>>(resolve => { release = resolve; });
+ let starts = 0;
+ const { context, elements, invoke, monitor } = loadSettingsClickHarness(async channel => {
+ if (channel === 'auth.startOAuth') return { ok: true, flowId: ++starts === 1 ? 'old-flow' : 'new-flow' };
+ if (channel === 'auth.pollOAuthFlow') return gate;
+ return { ok: true };
+ });
+ vm.runInContext('_settingsReload = async () => {};', context);
+ const active = controlIntervals(context);
+ await context._settingsStartOAuthFlow({ id: 'old-provider' }, 'old-model');
+ const pending = [...active.values()][0]();
+ try {
+ await elements.get('oauth-flow-close-btn')!.click();
+ if (destination === 'reopened') await context._settingsStartOAuthFlow({ id: 'new-provider' }, 'new-model');
+ const body = elements.get('oauth-flow-body')!.innerHTML;
+ release({ ok: true, status: { kind, profileId: 'old-provider:old-profile', message: 'old progress', error: 'old error' } });
+ await pending; await settle();
+ expect(invoke.mock.calls.filter(call => ['auth.addEntry', 'auth.removeCredential'].includes(call[0]))).toHaveLength(0);
+ expect(elements.get('oauth-flow-body')!.innerHTML).toBe(body);
+ expect(elements.get('oauth-flow-modal')!.classList.contains('open')).toBe(destination === 'reopened');
+ expect(active.size).toBe(destination === 'reopened' ? 1 : 0);
+ } finally {
+ release({ ok: true, status: { kind: 'starting' } }); await pending; await settle();
+ await elements.get('oauth-flow-close-btn')!.click(); active.clear();
+ }
+ });
+
+ it('commits one model entry when two in-flight polls return the same completed flow', async () => {
+ let releasePoll!: (value: Record<string, unknown>) => void;
+ let releaseWrite!: (value: Record<string, unknown>) => void;
+ const poll = new Promise<Record<string, unknown>>(resolve => { releasePoll = resolve; });
+ const write = new Promise<Record<string, unknown>>(resolve => { releaseWrite = resolve; });
+ const { context, elements, invoke, monitor } = loadSettingsClickHarness(async channel => {
+ if (channel === 'auth.startOAuth') return { ok: true, flowId: 'single-flow' };
+ if (channel === 'auth.pollOAuthFlow') return poll;
+ if (channel === 'auth.addEntry') return write;
+ return { ok: true };
+ });
+ vm.runInContext('_settingsReload = async () => {};', context);
+ const active = controlIntervals(context);
+ await context._settingsStartOAuthFlow({ id: 'openai-codex' }, 'gpt-5.6-sol');
+ const callback = [...active.values()][0];
+ const pending = [callback(), callback()];
+ try {
+ releasePoll({ ok: true, status: { kind: 'done', profileId: 'openai-codex:single' } });
+ await Promise.all(pending); await settle();
+ expect(invoke.mock.calls.filter(call => call[0] === 'auth.addEntry')).toHaveLength(1);
+ releaseWrite({ ok: true }); await settle();
+ expect(elements.get('oauth-flow-modal')!.classList.contains('open')).toBe(false);
+ } finally {
+ releasePoll({ ok: true, status: { kind: 'starting' } }); releaseWrite({ ok: true });
+ await Promise.all(pending); await settle();
+ await elements.get('oauth-flow-close-btn')!.click(); active.clear();
+ }
+ });
+});
+
+
+describe('OAuth admitted write compatibility across dialog changes', () => {
+ it.each(['models', 'entry-success', 'entry-failure', 'cleanup'])('finishes its already-admitted %s operation without changing the newer dialog', async stage => {
+ let release!: (result: Record<string, unknown>) => void;
+ const gate = new Promise<Record<string, unknown>>(resolve => { release = resolve; });
+ let entered = false;
+ let starts = 0;
+ const { context, elements, invoke, monitor } = loadSettingsClickHarness(async channel => {
+ if (channel === 'auth.startOAuth') return { ok: true, flowId: ++starts === 1 ? 'old-flow' : 'new-flow' };
+ if (channel === 'auth.pollOAuthFlow') return { ok: true, status: { kind: 'done', profileId: 'backend:completed' } };
+ if (channel === 'auth.listModels') {
+ if (stage === 'models') { entered = true; return gate; }
+ return { ok: true, models: [{ id: 'chosen-model' }] };
+ }
+ if (channel === 'auth.addEntry') {
+ if (stage.startsWith('entry-')) { entered = true; return gate; }
+ return stage === 'cleanup' ? { ok: false, code: 'WRITE_FAILED' } : { ok: true };
+ }
+ if (channel === 'auth.removeCredential' && stage === 'cleanup') { entered = true; return gate; }
+ return { ok: true };
+ });
+ const active = new Map<number, () => Promise<void>>(); let next = 0;
+ context.setInterval = (callback: () => Promise<void>) => { active.set(++next, callback); return next; };
+ context.clearInterval = (id: number) => { active.delete(id); };
+ context.__reload = vi.fn(async () => {});
+ vm.runInContext('_settingsReload = __reload;', context);
+ await context._settingsStartOAuthFlow({ id: stage === 'models' ? 'visible-provider' : 'backend', oauthProvider: 'backend' }, 'chosen-model');
+ const pending = [...active.values()][0]();
+ try {
+ await vi.waitFor(() => expect(entered).toBe(true));
+ await elements.get('oauth-flow-close-btn')!.click();
+ await context._settingsStartOAuthFlow({ id: 'new-provider' }, 'new-model');
+ const body = elements.get('oauth-flow-body')!.innerHTML;
+ release(stage === 'models' ? { ok: true, models: [{ id: 'chosen-model' }] }
+ : stage === 'entry-failure' ? { ok: false, code: 'WRITE_FAILED' } : { ok: true });
+ await pending;
+ await new Promise(resolve => setTimeout(resolve, 0));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(invoke.mock.calls.filter(call => call[0] === 'auth.addEntry')).toEqual([[
+ 'auth.addEntry', { provider: 'backend', model: 'chosen-model', profileId: 'backend:completed' },
+ ]]);
+ expect(invoke.mock.calls.filter(call => call[0] === 'auth.removeCredential')).toEqual(
+ ['entry-failure', 'cleanup'].includes(stage) ? [['auth.removeCredential', { profileId: 'backend:completed' }]] : [],
+ );
+ expect(context.__reload).toHaveBeenCalledTimes(['models', 'entry-success'].includes(stage) ? 1 : 0);
+ expect(elements.get('oauth-flow-modal')!.classList.contains('open')).toBe(true);
+ expect(elements.get('oauth-flow-body')!.innerHTML).toBe(body);
+ expect(active.size).toBe(1);
+ } finally {
+ release({ ok: true, models: [{ id: 'chosen-model' }] }); await pending;
+ await new Promise(resolve => setTimeout(resolve, 0));
+ await elements.get('oauth-flow-close-btn')!.click(); active.clear();
+ }
+ });
+});
+
+
+it('does not undo the first completed OAuth entry when a duplicate completion would fail', async () => {
+ let releasePoll!: (value: Record<string, unknown>) => void;
+ let releaseWrite!: (value: Record<string, unknown>) => void;
+ const poll = new Promise<Record<string, unknown>>(resolve => { releasePoll = resolve; });
+ const write = new Promise<Record<string, unknown>>(resolve => { releaseWrite = resolve; });
+ let writes = 0;
+ const { context, elements, invoke, monitor } = loadSettingsClickHarness(async channel => {
+ if (channel === 'auth.startOAuth') return { ok: true, flowId: 'single-flow' };
+ if (channel === 'auth.pollOAuthFlow') return poll;
+ if (channel === 'auth.addEntry') {
+ if (++writes === 1) return write;
+ await write;
+ // The first response reaches its success handler before this later
+ // failure. Its committed credential must not enter duplicate cleanup.
+ return new Promise(resolve => setTimeout(() => resolve({ ok: false, code: 'WRITE_FAILED' }), 0));
+ }
+ return { ok: true };
+ });
+ const active = new Map<number, () => Promise<void>>(); let next = 0;
+ context.setInterval = (callback: () => Promise<void>) => { active.set(++next, callback); return next; };
+ context.clearInterval = (id: number) => { active.delete(id); };
+ vm.runInContext('_settingsReload = async () => {};', context);
+ await context._settingsStartOAuthFlow({ id: 'openai-codex' }, 'gpt-5.6-sol');
+ const callback = [...active.values()][0]; const pending = [callback(), callback()];
+ try {
+ releasePoll({ ok: true, status: { kind: 'done', profileId: 'openai-codex:committed' } });
+ await Promise.all(pending);
+ releaseWrite({ ok: true });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(invoke.mock.calls.filter(call => call[0] === 'auth.removeCredential')).toHaveLength(0);
+ expect(invoke.mock.calls.filter(call => call[0] === 'auth.addEntry')).toHaveLength(1);
+ } finally {
+ releasePoll({ ok: true, status: { kind: 'starting' } }); releaseWrite({ ok: true });
+ await Promise.all(pending); await new Promise(resolve => setTimeout(resolve, 0));
+ await elements.get('oauth-flow-close-btn')!.click(); active.clear();
+ }
+});