Something went wrong. Try again.
My version of https://github.com/vercel-labs/fx
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678const std = @import("std");const config_runtime = @import("../config/config_runtime.zig");const debug_trace = @import("../shared/debug_trace.zig");const host = @import("../hosts/host.zig");const runtime_profile = @import("../hosts/runtime_profile.zig");const host_target = @import("../hosts/target.zig");const io_mod = @import("../shared/io.zig");const credentials = @import("../auth/credentials.zig");const auth_runtime = @import("../auth/auth_runtime.zig");const login_flow = @import("../auth/login_flow.zig");const chatgpt_oauth = @import("../auth/chatgpt_oauth.zig");const provider_catalog = @import("../auth/provider_catalog.zig");const model_provider = @import("../config/model_provider.zig");const model_catalog = @import("../gateway/model_catalog.zig");const provider_runtime = @import("provider_runtime.zig");const types = @import("../shared/types.zig");
fn oauthAuthEnabled(comptime App: type) bool { return runtime_profile.allows(App, .native_auth) or runtime_profile.allows(App, .js_host_auth);}
const ProviderSwitchDecision = enum { no_change, busy, prepare,};
fn decideProviderSwitch( current: model_provider.ProviderId, target: model_provider.ProviderId, stream_active: bool, queued_prompts: usize,) ProviderSwitchDecision { if (current == target) return .no_change; if (stream_active or queued_prompts > 0) return .busy; return .prepare;}
pub fn Runtime(comptime App: type) type { return struct { fn ensurePromptCredential(app: *App) !bool { if (comptime provider_runtime.supported(App) and @hasDecl(@TypeOf(app.auth), "selectForProvider")) { const provider = provider_runtime.provider(app); const required_source: credentials.Source = if (provider == .codex) .chatgpt_subscription else app.auth.credentialSource() orelse .fx_login; const route_change = app.auth.selectForProvider(app.alloc, provider) catch |err| switch (err) { error.OutOfMemory => return err, else => return recoverCredentialFailure(app, required_source, err), }; if (route_change) |changed| { applyCredentialChange(app, changed); } else if (provider == .codex and app.auth.credentialSource() != .chatgpt_subscription) { try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = credentials.missing_chatgpt_interactive_credential_message, }, true); app.shell.render_requests.request(.footer); return false; } } if (app.auth.credentialSource() != null) return true;
const auth_view = app.auth.view(); if (auth_view.onboarding_skipped) { try app.writeDomainNotice(.{ .topic = "auth", .tone = .@"error", .body = credentials.missing_interactive_credential_message, }, true); } else if (!app.auth.pickerView().active) { try app.auth.refreshSourceInventory(app.alloc); app.auth.openOnboardingPicker(app.alloc); } app.shell.render_requests.request(.footer); return false; }
pub fn runLoginCommand(app: *App) !void { if (comptime !oauthAuthEnabled(App)) { try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = "Set FX_API_KEY through createFxTerminal() to authenticate this WASM session.", }, true); return; } if (comptime host_target.is_wasm) { try beginSignIn(app, false); return; } try app.auth.refreshSourceInventory(app.alloc); app.auth.openPicker(app.alloc); app.shell.render_requests.request(.footer); }
pub fn runProviderCommand(app: *App, raw_target: []const u8) !void { const target = std.mem.trim(u8, raw_target, " \t\r\n"); if (target.len == 0) { if (comptime !provider_runtime.supported(App)) { try app.writeDomainNotice(.{ .topic = "provider", .tone = .warning, .body = "Provider switching is unavailable in this host.", }, true); return; } app.auth.openProviderPicker(app.alloc, provider_runtime.provider(app)); app.shell.render_requests.request(.footer); return; } const provider = model_provider.parse(target) orelse { try app.writeDomainNotice(.{ .topic = "provider", .tone = .warning, .body = "Usage: /provider [gateway|codex]", }, true); return; }; try switchProvider(app, provider, true); }
pub fn runLogoutCommand(app: *App, target: []const u8) !void { if (comptime !oauthAuthEnabled(App)) { try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = "Authentication is owned by the embedding SDK for this WASM session.", }, true); return; } const requested_provider = if (std.mem.trim(u8, target, " \t\r\n").len == 0) null else provider_catalog.parse(std.mem.trim(u8, target, " \t\r\n")) orelse { try writeAuthNotice(app, .{ .topic = "auth", .tone = .warning, .body = "Usage: /logout [vercel|codex]", }); return; }; try app.flushBeforeBlockingExternalWork(); const selected_model_uses_chatgpt = if (comptime provider_runtime.supported(App)) provider_runtime.provider(app) == .codex else false; const provider_inventory = if (comptime @hasDecl(@TypeOf(app.auth), "pickerView")) inventory: { try app.auth.refreshSourceInventory(app.alloc); break :inventory app.auth.pickerView().available_sources; } else @as(auth_runtime.SourceSet, .empty); const chatgpt_is_only_logout_session = provider_inventory.contains(.chatgpt_subscription) and !provider_inventory.contains(.fx_login); const logout_chatgpt = if (requested_provider) |provider| provider == .codex else selected_model_uses_chatgpt or app.auth.credentialSource() == .chatgpt_subscription or chatgpt_is_only_logout_session; if (logout_chatgpt) { const outcome = chatgpt_oauth.logout() catch { try writeAuthNotice(app, .{ .topic = "auth", .tone = .@"error", .body = "Could not durably sign out of Codex. The current source is unchanged.", }); return; }; const changed = if (comptime @hasDecl(@TypeOf(app.auth), "reconcileAfterChatGptLogout")) try app.auth.reconcileAfterChatGptLogout(app.alloc) else false; applyCredentialChange(app, changed); try writeAuthNotice(app, switch (outcome) { .deleted => .{ .topic = "auth", .tone = .neutral, .body = "Signed out of Codex." }, .missing => .{ .topic = "auth", .tone = .neutral, .body = "No Codex login session found." }, .deleted_not_durable => .{ .topic = "auth", .tone = .warning, .body = "Signed out of Codex, but could not confirm the profile directory update." }, }); return; } const result = login_flow.logout(app.alloc, app.auth.oauthTransport()) catch |err| switch (err) { error.SessionDeleteFailed => { try writeAuthNotice(app, .{ .topic = "auth", .tone = .@"error", .body = "Could not complete fx logout. The current source is unchanged.", }); return; }, }; try applyLogoutResult(app, result); }
pub fn openSetupHub(app: *App) !void { if (comptime !runtime_profile.allows(App, .native_auth)) { try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = "API key setup is unavailable in this WASM session.", }, true); return; } try app.auth.refreshSourceInventory(app.alloc); app.auth.openPicker(app.alloc); app.shell.render_requests.request(.footer); }
fn applyLogoutResult(app: *App, result: login_flow.LogoutResult) !void { // Logging out is an explicit rejection of that credential, so a // remembered pointer to it would silently reactivate on next login. // A remembered source always wins resolution, so an active fx login // is the only way one can be remembered; clearing otherwise is a // no-op against a store that holds nothing. if (app.auth.credentialSource() == .fx_login) forgetCredentialSource(app); applyCredentialChange(app, try app.auth.reconcileAfterFxLoginLogout(app.alloc)); try writeAuthNotice(app, if (result.local_durability_failed) .{ .topic = "auth", .tone = .warning, .body = "Could not confirm durable fx logout. The active source was recalculated.", } else if (result.session_deleted) .{ .topic = "auth", .tone = .neutral, .body = "Signed out of fx.", } else .{ .topic = "auth", .tone = .neutral, .body = "No fx login session found.", }); if (result.remote_revocation_failed) { try writeAuthNotice(app, .{ .topic = "auth", .tone = .warning, .body = login_flow.remote_revocation_warning, }); } }
pub fn applyPickerChoice(app: *App, choice: auth_runtime.Choice) !void { if (comptime !oauthAuthEnabled(App)) { try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = "Browser authentication is supplied by the embedding SDK.", }, true); return; } switch (choice) { .provider => |provider| try switchProvider(app, provider, true), .source => |source| try applySourceChoice(app, source), .action => |action| switch (action) { .login => try beginSignIn(app, true), .chatgpt_login => try beginChatGptSignIn(app), .setup => { if (comptime !runtime_profile.allows(App, .native_auth)) { try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = "API key setup is unavailable in this WASM session.", }, true); return; } prepareApiKeyInputBoundary(app); app.auth.openApiKeyPickerFromRoot(app.alloc); }, .change_team => try beginTeamPicker(app), .switch_credential => app.auth.openSwitchCredentialPicker(app.alloc), .automatic => try applyAutomaticCredential(app), }, .team => |index| try applyTeamChoice(app, index), } }
pub fn routeAuthPickerByte(app: *App, byte: u8) !bool { if (app.auth.signInEntryActive()) { switch (byte) { 3, 4 => _ = app.auth.popPickerStage(app.alloc), '\r', '\n' => try openSignInBrowser(app), else => {}, } app.shell.render_requests.request(.footer); return true; } if (app.auth.teamPickerActive()) { const consumed = switch (byte) { 8, 127 => app.auth.deleteTeamQueryByte(), else => try app.auth.appendTeamQueryByte(app.alloc, byte), }; if (consumed) { app.shell.render_requests.request(.footer); return true; } } if (!app.auth.apiKeyEntryActive()) return false; switch (byte) { 3, 4 => _ = app.auth.popPickerStage(app.alloc), '\r', '\n' => try submitApiKeyEntry(app), 8, 127 => _ = app.auth.deleteApiKeyByte(), else => _ = try app.auth.appendApiKeyByte(app.alloc, byte), } app.shell.render_requests.request(.footer); return true; }
pub fn routeAuthPickerEscapeAction(app: *App, action: anytype) bool { if (!app.auth.signInEntryActive() and !app.auth.apiKeyEntryActive()) return false; return switch (action) { .escape, .remapped_byte => false, else => true, }; }
pub fn collectSignInFacts(app: *App) !void { if (comptime !oauthAuthEnabled(App)) return; const sign_in_source: credentials.Source = if (comptime @hasDecl(@TypeOf(app.auth), "pickerView")) app.auth.pickerView().sign_in_source else .fx_login; const completes_provider_switch = if (comptime @hasDecl(@TypeOf(app.auth), "signInReturnsToRoot")) sign_in_source == .chatgpt_subscription and !app.auth.signInReturnsToRoot() else false; app.auth.pulseSignIn(app.alloc); switch (app.auth.pollSignInTransition(app.alloc)) { .none => {}, .cancelled => app.shell.render_requests.request(.footer), .failed => |err| { debug_trace.logf("auth", "login failed source={t} err={s}", .{ sign_in_source, @errorName(err) }); _ = app.auth.popPickerStage(app.alloc); try writeLoginError(app, sign_in_source, err); }, .succeeded => |completed| { var owned = completed; defer owned.deinit(app.alloc); switch (owned) { .vercel => |*selection| { if (!try selectCredentialSource(app, .fx_login)) { _ = app.auth.popPickerStage(app.alloc); try writeAuthNotice(app, .{ .topic = "auth", .tone = .@"error", .body = "Signed in, but the fx login credential could not be loaded.", }); return; } rememberCredentialSource(app, .fx_login);
if (selection.teams.items.len > 0) { app.auth.openTeamPicker(app.alloc, selection); } else { app.auth.closePicker(app.alloc); } try writeAuthNotice(app, .{ .topic = "auth", .tone = .neutral, .body = "Signed in to Vercel.", }); }, .chatgpt => { try app.auth.refreshSourceInventory(app.alloc); if (completes_provider_switch and comptime provider_runtime.supported(App)) { app.auth.closePicker(app.alloc); try switchProvider(app, .codex, false); return; } const selected_model_uses_chatgpt = if (comptime provider_runtime.supported(App)) provider_runtime.provider(app) == .codex else false; if (selected_model_uses_chatgpt and !try selectCredentialSource(app, .chatgpt_subscription)) { _ = app.auth.popPickerStage(app.alloc); try writeAuthNotice(app, .{ .topic = "auth", .tone = .@"error", .body = "Signed in, but the Codex subscription credential could not be loaded.", }); return; } if (!selected_model_uses_chatgpt) { app.model_cache.reset(); if (comptime @hasDecl(App, "startModelCacheWarmup")) app.startModelCacheWarmup(); } app.auth.closePicker(app.alloc); try writeAuthNotice(app, .{ .topic = "auth", .tone = .neutral, .body = "Signed in with Codex.", }); }, } }, } }
fn prepareApiKeyInputBoundary(app: *App) void { if (comptime @hasDecl(App, "prepareApiKeyInputBoundary")) { app.prepareApiKeyInputBoundary(); } }
fn submitApiKeyEntry(app: *App) !void { if (app.auth.pickerView().api_key_mask_count == 0) return; switch (app.auth.beginApiKeySave(app.alloc)) { .started => app.shell.render_requests.request(.footer), .empty => {}, .busy => try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = "Still saving the previous API key. Nothing was stored for this one; try again in a moment.", }, true), } }
/// Polled from the event loop so a save that blocks on a locked key store /// or a slow gateway never stalls rendering. pub fn collectApiKeySaveFacts(app: *App) !void { const result = app.auth.takeApiKeySaveResult(app.alloc) orelse return; try applyApiKeySaveResult(app, result); }
fn applyApiKeySaveResult(app: *App, result: auth_runtime.ApiKeySaveResult) !void { switch (result) { .empty => return, .saved => |changed| { applyCredentialChange(app, changed); rememberCredentialSource(app, .stored_key); const body = try std.fmt.allocPrint( app.alloc, "Saved the API key to {s} and made it active.", .{credentials.stored_key_backend_label}, ); defer app.alloc.free(body); try app.writeDomainNotice(.{ .topic = "auth", .tone = .neutral, .body = body, }, true); }, .gateway_refused => try app.writeDomainNotice(.{ .topic = "auth", .tone = .@"error", .body = "The AI Gateway refused that API key. Nothing was stored.", }, true), .gateway_unavailable => try app.writeDomainNotice(.{ .topic = "auth", .tone = .@"error", .body = "Could not verify that API key with AI Gateway. Nothing was stored.", }, true), .store_failed => { const body = try std.fmt.allocPrint( app.alloc, "Could not save the API key to {s}. Nothing was stored.", .{credentials.stored_key_backend_label}, ); defer app.alloc.free(body); try app.writeDomainNotice(.{ .topic = "auth", .tone = .@"error", .body = body, }, true); }, .reload_failed => { const body = try std.fmt.allocPrint( app.alloc, "Saved the API key to {s}, but could not make it active.", .{credentials.stored_key_backend_label}, ); defer app.alloc.free(body); try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = body, }, true); }, } }
/// Clearing the remembered choice must also re-resolve, otherwise the /// session would keep running on a source precedence no longer selects. fn applyAutomaticCredential(app: *App) !void { forgetCredentialSource(app); app.auth.closePicker(app.alloc); applyCredentialChange(app, try app.auth.reselectByPrecedence(app.alloc)); try app.writeDomainNotice(.{ .topic = "auth", .tone = .neutral, .body = "Using automatic credential precedence again.", }, true); }
fn forgetCredentialSource(app: *App) void { var attempt = config_runtime.attemptUserPreferences( app.alloc, .{ .clear_credential_source = true }, ); defer attempt.deinit(app.alloc); switch (attempt) { .outcome => debug_trace.logf("auth", "credential choice cleared", .{}), .failure => |failure| debug_trace.logf( "auth", "credential choice not cleared err={s}", .{@errorName(failure.err)}, ), } }
fn applySourceChoice(app: *App, source: credentials.Source) !void { const body = try std.fmt.allocPrint( app.alloc, "Switched credential to {s}.", .{credentials.sourceLabel(source)}, ); defer app.alloc.free(body);
if (!try selectCredentialSource(app, source)) { try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = "That credential is no longer available. The current source is unchanged.", }, true); return; }
rememberCredentialSource(app, source); try app.writeDomainNotice(.{ .topic = "auth", .tone = .neutral, .body = body, }, true); }
/// An explicit source choice outlives the session. Failing to persist /// leaves the source active for this run rather than refusing a working /// credential the user already selected. fn rememberCredentialSource(app: *App, source: credentials.Source) void { // ChatGPT is selected by model route, not as a global Gateway // credential preference. Its saved session coexists independently. if (source == .chatgpt_subscription) return; if (comptime @hasDecl(App, "persistCredentialSourcePreference")) { app.persistCredentialSourcePreference(source); return; }
var attempt = config_runtime.attemptUserPreferences( app.alloc, .{ .credential_source = source }, ); defer attempt.deinit(app.alloc); switch (attempt) { .outcome => debug_trace.logf("auth", "credential choice persisted source={t}", .{source}), .failure => |failure| debug_trace.logf( "auth", "credential choice not persisted source={t} err={s}", .{ source, @errorName(failure.err) }, ), } }
fn beginChatGptSignIn(app: *App) !void { try app.flushBeforeBlockingExternalWork(); const started = app.auth.openChatGptSignInPickerFromRoot(app.alloc); if (started catch |err| { debug_trace.logf("auth", "ChatGPT login failed err={s}", .{@errorName(err)}); try writeLoginError(app, .chatgpt_subscription, err); return; }) { app.shell.render_requests.request(.footer); if (io_mod.getenv("FX_NO_OPEN_BROWSER") == null) try openSignInBrowser(app); } }
fn beginCodexSignInForProviderSwitch(app: *App) !void { try app.flushBeforeBlockingExternalWork(); const started = app.auth.openChatGptSignInPickerForProviderSwitch(app.alloc); if (started catch |err| { debug_trace.logf("auth", "Codex login failed err={s}", .{@errorName(err)}); try writeLoginError(app, .chatgpt_subscription, err); return; }) { app.shell.render_requests.request(.footer); if (io_mod.getenv("FX_NO_OPEN_BROWSER") == null) try openSignInBrowser(app); } }
fn switchProvider( app: *App, target: model_provider.ProviderId, allow_login: bool, ) !void { if (comptime !provider_runtime.supported(App) or !@hasDecl(App, "fetchProviderCatalog") or !@hasDecl(@TypeOf(app.model_cache), "adoptOwnedCatalog")) { try app.writeDomainNotice(.{ .topic = "provider", .tone = .warning, .body = "Provider switching is unavailable in this host.", }, true); return; } if (comptime host_target.is_wasm) { try app.writeDomainNotice(.{ .topic = "provider", .tone = .warning, .body = "Codex provider switching is unavailable in this WASM session.", }, true); return; }
const current = provider_runtime.provider(app); switch (decideProviderSwitch( current, target, app.stream.active, app.worker.queuedPromptCount(), )) { .prepare => {}, .no_change => { const body = try std.fmt.allocPrint( app.alloc, "Already using {s}.", .{model_provider.label(target)}, ); defer app.alloc.free(body); try app.writeDomainNotice(.{ .topic = "provider", .tone = .neutral, .body = body }, true); return; }, .busy => { try app.writeDomainNotice(.{ .topic = "provider", .tone = .warning, .body = "Provider switching is unavailable until active and queued work finishes.", }, true); return; }, } try app.flushBeforeBlockingExternalWork();
const resolution = credentials.resolveForProvider( app.alloc, app.auth.oauthTransport(), app.auth.secretStore(), .refresh_if_needed, target, null, ) catch |err| { debug_trace.logf("provider", "credential preparation failed provider={t} err={s}", .{ target, @errorName(err) }); try app.writeDomainNotice(.{ .topic = "provider", .tone = .@"error", .body = "Could not prepare the target provider credential. The current provider is unchanged.", }, true); return; }; var credential = resolution.credential orelse { if (target == .codex and allow_login) { try beginCodexSignInForProviderSwitch(app); return; } try app.writeDomainNotice(.{ .topic = "provider", .tone = .warning, .body = if (target == .codex) "Run fx login codex, then try switching again." else credentials.missing_interactive_credential_message, }, true); return; }; defer credential.deinit(app.alloc); if (!model_provider.authorizesCredential(target, credential.source)) { try app.writeDomainNotice(.{ .topic = "provider", .tone = .@"error", .body = "The target credential cannot authorize that provider. The current provider is unchanged.", }, true); return; }
const access = credentials.catalogAccessForCredential( credential.source, credential.token, credential.gatewayTeam(), ); const fetched = app.fetchProviderCatalog(target, access) catch |err| { debug_trace.logf("provider", "catalog preparation failed provider={t} err={s}", .{ target, @errorName(err) }); try app.writeDomainNotice(.{ .topic = "provider", .tone = .@"error", .body = "Could not load the target provider catalog. The current provider is unchanged.", }, true); return; }; var catalog = switch (fetched) { .catalog => |catalog| catalog, .failure => |failure| { debug_trace.logf("provider", "catalog rejected provider={t} category={t}", .{ target, failure.category }); try app.writeDomainNotice(.{ .topic = "provider", .tone = .@"error", .body = "The target provider catalog could not be validated. The current provider is unchanged.", }, true); return; }, }; defer model_catalog.freeModelCatalog(app.alloc, &catalog); if (catalog.items.len == 0) { try app.writeDomainNotice(.{ .topic = "provider", .tone = .@"error", .body = "The target provider returned no supported models. The current provider is unchanged.", }, true); return; }
var settings = config_runtime.loadMergedSettings(app.alloc, app.workspace_root) catch |err| { debug_trace.logf("provider", "settings load failed err={s}", .{@errorName(err)}); try app.writeDomainNotice(.{ .topic = "provider", .tone = .@"error", .body = "Could not load the saved provider model. The current provider is unchanged.", }, true); return; }; defer settings.deinit(app.alloc); const saved_model = switch (target) { .gateway => settings.model, .codex => settings.codex_model, }; const requested_model = io_mod.getenv("FX_MODEL") orelse saved_model; var selected: ?[]const u8 = null; if (requested_model) |candidate| { for (catalog.items) |entry| { if (std.mem.eql(u8, candidate, entry.id)) { selected = entry.id; break; } } } if (selected == null) selected = catalog.items[0].id; var owned_model = try app.alloc.dupe(u8, selected.?); errdefer app.alloc.free(owned_model);
app.model_cache.adoptOwnedCatalog(access, &catalog); app.provider_selection.adoptOwned(target, &owned_model); _ = app.auth.adoptCredential(app.alloc, &credential); reconcileGatewayCredential(app);
const body = try std.fmt.allocPrint( app.alloc, "Switched to {s} with {s}.", .{ model_provider.label(target), provider_runtime.model(app) }, ); defer app.alloc.free(body); if (comptime @hasDecl(App, "persistRuntimePreferences")) { var persistence = app.persistRuntimePreferences(.{ .provider = target, .model = provider_runtime.model(app), }); defer persistence.deinit(app.alloc); if (persistence.settings_error != null or persistence.session_error != null) { debug_trace.logf( "provider", "runtime switch persistence failed settings={s} session={s}", .{ if (persistence.settings_error) |err| @errorName(err) else "none", if (persistence.session_error) |err| @errorName(err) else "none", }, ); try app.writeDomainNotice(.{ .topic = "provider", .tone = .warning, .body = "Provider switched for this run, but the selection could not be saved.", }, true); } else { try app.writeDomainNotice(.{ .topic = "provider", .tone = .neutral, .body = body }, true); } } else { var persistence = config_runtime.attemptUserPreferences(app.alloc, switch (target) { .gateway => .{ .provider = .gateway, .model = provider_runtime.model(app) }, .codex => .{ .provider = .codex, .codex_model = provider_runtime.model(app) }, }); defer persistence.deinit(app.alloc); switch (persistence) { .outcome => try app.writeDomainNotice(.{ .topic = "provider", .tone = .neutral, .body = body }, true), .failure => |failure| { debug_trace.logf("provider", "runtime switch persistence failed err={s}", .{@errorName(failure.err)}); try app.writeDomainNotice(.{ .topic = "provider", .tone = .warning, .body = "Provider switched for this run, but the selection could not be saved.", }, true); }, } } app.shell.render_requests.request(.footer); }
fn beginTeamPicker(app: *App) !void { if (!app.auth.pickerView().fx_login_session_available) return; try app.flushBeforeBlockingExternalWork();
var selection = login_flow.loadTeamSelection(app.alloc, app.auth.oauthTransport()) catch |err| { debug_trace.logf("auth", "team picker load failed err={s}", .{@errorName(err)}); try app.writeDomainNotice(.{ .topic = "auth", .tone = .@"error", .body = switch (err) { error.NoSession => "The fx login session is no longer available. Sign in to change teams.", error.NoTeams => "No Vercel teams are available for this account.", else => "Could not load Vercel teams. The current team is unchanged.", }, }, true); return; }; defer selection.deinit(app.alloc); app.auth.openTeamPicker(app.alloc, &selection); app.shell.render_requests.request(.footer); }
fn applyTeamChoice(app: *App, index: usize) !void { const selection = app.auth.teamSelection() orelse return; if (index >= selection.teams.items.len) return; const team = selection.teams.items[index]; const body = try std.fmt.allocPrint( app.alloc, "Changed Vercel team to {s} ({s}).", .{ team.name, team.slug }, ); defer app.alloc.free(body);
var selected_team = selection.select(app.alloc, index) catch |err| { debug_trace.logf("auth", "team change failed err={s}", .{@errorName(err)}); app.auth.closePicker(app.alloc); try app.writeDomainNotice(.{ .topic = "auth", .tone = .@"error", .body = switch (err) { error.SessionChanged, error.NoSession => "The fx login session changed before the team could be saved.", else => "Could not change the Vercel team. The current team is unchanged.", }, }, true); return; }; defer selected_team.deinit(app.alloc);
if (app.auth.credentialSource() == .fx_login) { applyCredentialChange(app, app.auth.adoptSelectedTeam(app.alloc, &selected_team)); } else if (!try selectCredentialSource(app, .fx_login)) { app.auth.closePicker(app.alloc); try app.writeDomainNotice(.{ .topic = "auth", .tone = .@"error", .body = "Changed the Vercel team, but the fx login credential could not be loaded.", }, true); return; } rememberCredentialSource(app, .fx_login); app.auth.closePicker(app.alloc); try app.writeDomainNotice(.{ .topic = "auth", .tone = .neutral, .body = body, }, true); }
fn beginSignIn(app: *App, from_root: bool) !void { try app.flushBeforeBlockingExternalWork();
const started = if (from_root) app.auth.openSignInPickerFromRoot(app.alloc) else app.auth.openSignInPicker(app.alloc); if (started catch |err| { debug_trace.logf("auth", "login failed err={s}", .{@errorName(err)}); try writeLoginError(app, .fx_login, err); return; }) { app.shell.render_requests.request(.footer); // Open the browser as soon as the device code is ready instead of // waiting for Enter; Enter stays as a manual re-open, and // FX_NO_OPEN_BROWSER opts out for headless/SSH sessions. if (io_mod.getenv("FX_NO_OPEN_BROWSER") == null) try openSignInBrowser(app); } }
fn openSignInBrowser(app: *App) !void { const url = (try app.auth.signInBrowserUrlAlloc(app.alloc)) orelse return; defer app.alloc.free(url); if (!try app.urlOpener().open(app.alloc, url)) { debug_trace.logf("auth", "login browser launcher failed", .{}); } }
pub fn selectCredentialSource(app: *App, source: credentials.Source) !bool { const changed = (try app.auth.selectSource(app.alloc, source)) orelse return false; applyCredentialChange(app, changed); return true; }
fn refreshFxLoginCredentialIfNeeded(app: *App) !void { if (!try app.auth.refreshFxLoginIfNeeded(app.alloc)) return; reconcileGatewayCredential(app); if (app.auth.modelCatalogAccess().authorizationCredential() == null) return; app.model_cache.reset(); if (comptime @hasDecl(App, "startModelCacheWarmup")) { app.startModelCacheWarmup(); } }
pub fn admitPromptCredential(app: *App) !bool { if (comptime !oauthAuthEnabled(App)) { if (app.auth.apiKey() != null) return true; try app.writeDomainNotice(.{ .topic = "auth", .tone = .warning, .body = "Missing FX_API_KEY. Supply it through createFxTerminal().", }, true); return false; } if (!try ensurePromptCredential(app)) return false; return preparePromptCredential(app); }
fn preparePromptCredential(app: *App) !bool { for (0..2) |_| { refreshFxLoginCredentialIfNeeded(app) catch |err| switch (err) { error.OutOfMemory => return err, else => return recoverPromptCredentialRefreshFailure(app, err), }; if (app.auth.gatewayCredential() != null) return true; } return recoverPromptCredentialRefreshFailure(app, error.CredentialRefreshUnavailable); }
fn recoverPromptCredentialRefreshFailure(app: *App, err: anyerror) !bool { const active_source = app.auth.credentialSource(); const source = if (active_source) |active| if (credentials.sourceRefreshable(active)) active else .fx_login else .fx_login; return recoverCredentialFailure(app, source, err); }
fn recoverCredentialFailure(app: *App, source: credentials.Source, err: anyerror) !bool { debug_trace.logf("auth", "prompt credential refresh failed source={t} err={s}", .{ source, @errorName(err) }); if (app.auth.credentialSource() == source) app.auth.recordCredentialRefreshFailure(source); try app.auth.refreshSourceInventory(app.alloc); app.auth.openPicker(app.alloc); const failure = auth_runtime.FailureSnapshot{ .source = source, .reason = .credential_refresh_failed, }; const failure_text = try failure.renderText(app.alloc); defer app.alloc.free(failure_text); const recovery = try std.fmt.allocPrint( app.alloc, "{s}.\nChoose another source below.", .{failure_text}, ); defer app.alloc.free(recovery); try app.writeDomainNotice(.{ .topic = "auth", .tone = .@"error", .body = recovery, }, true); app.shell.render_requests.request(.footer); return false; }
fn applyCredentialChange(app: *App, changed: bool) void { if (!changed) return; reconcileGatewayCredential(app); app.model_cache.reset(); if (comptime @hasDecl(App, "startModelCacheWarmup")) { app.startModelCacheWarmup(); } }
fn reconcileGatewayCredential(app: *App) void { if (comptime !runtime_profile.allows(App, .generation_usage)) return; if (comptime @hasField(App, "session") and @hasField(@TypeOf(app.session), "usage")) { if (app.auth.gatewayCredential()) |credential| { const chatgpt_subscription = if (comptime @hasField(@TypeOf(credential), "source")) credential.source == .chatgpt_subscription else false; if (chatgpt_subscription) { app.session.usage.clearReconciliationCredential(); } else { app.session.usage.replaceReconciliationCredential( app.alloc, credential.api_key, ); } } else { app.session.usage.clearReconciliationCredential(); } } }
fn writeLoginError(app: *App, source: credentials.Source, err: anyerror) !void { const notice: types.SemanticNotice = if (source == .chatgpt_subscription) switch (err) { error.ChatGptAuthorizationFailed => .{ .topic = "auth", .tone = .@"error", .body = "Codex sign-in was denied. The current credential is unchanged." }, error.ChatGptLoginTimedOut, error.LoginTimedOut => .{ .topic = "auth", .tone = .warning, .body = "Codex sign-in expired. The current credential is unchanged; run /login to try again." }, else => .{ .topic = "auth", .tone = .@"error", .body = "Codex sign-in failed. The current credential is unchanged." }, } else switch (err) { error.ClientIdMissing => .{ .topic = "auth", .tone = .@"error", .body = "fx login is not configured yet. The current credential is unchanged." }, error.AccessDenied => .{ .topic = "auth", .tone = .@"error", .body = "Vercel sign-in was denied. The current credential is unchanged." }, error.ExpiredToken, error.LoginTimedOut => .{ .topic = "auth", .tone = .warning, .body = "The Vercel sign-in code expired. The current credential is unchanged; run /login to try again." }, else => .{ .topic = "auth", .tone = .@"error", .body = "Vercel sign-in failed. The current credential is unchanged." }, }; try writeAuthNotice(app, notice); }
fn writeAuthNotice(app: *App, notice: types.SemanticNotice) !void { try app.writeDomainNotice(notice, true); app.shell.render_requests.request(.first_frame); try app.flushBeforeBlockingExternalWork(); } };}
test "provider switch state machine no-ops rejects busy work and prepares only idle changes" { try std.testing.expectEqual( ProviderSwitchDecision.no_change, decideProviderSwitch(.gateway, .gateway, true, 2), ); try std.testing.expectEqual( ProviderSwitchDecision.busy, decideProviderSwitch(.gateway, .codex, true, 0), ); try std.testing.expectEqual( ProviderSwitchDecision.busy, decideProviderSwitch(.gateway, .codex, false, 1), ); try std.testing.expectEqual( ProviderSwitchDecision.prepare, decideProviderSwitch(.gateway, .codex, false, 0), );}
const TestModelCache = struct { reset_count: usize = 0,
fn reset(self: *TestModelCache) void { self.reset_count += 1; }};
const TestTeam = struct { name: []const u8, slug: []const u8,};
const test_teams = [_]TestTeam{.{ .name = "Vercel Labs", .slug = "vercel-labs",}};
const TestSelectedTeam = struct { fn deinit(_: *TestSelectedTeam, _: std.mem.Allocator) void {}};
const TestTeamSelection = struct { teams: struct { items: []const TestTeam = &test_teams, } = .{}, select_count: usize = 0,
fn select( self: *TestTeamSelection, _: std.mem.Allocator, index: usize, ) error{ InvalidTeamSelection, SessionChanged, NoSession }!TestSelectedTeam { if (index >= self.teams.items.len) return error.InvalidTeamSelection; self.select_count += 1; return .{}; }};
const TestAuth = struct { select_result: ?bool = false, sign_in_transition: login_flow.SignInTransition = .none, logout_changed: bool = false, refresh_changed: bool = false, refresh_error: ?anyerror = null, selected_source: ?credentials.Source = null, active_source: ?credentials.Source = .ai_gateway_api_key, refresh_count: usize = 0, logout_reconcile_count: usize = 0, source_inventory_refresh_count: usize = 0, refresh_failure_source: ?credentials.Source = null, picker_opened: bool = false, picker_closed: bool = false, gateway_ready: bool = true, catalog_ready: bool = true, gateway_ready_after_refresh_count: ?usize = null, team_selection: TestTeamSelection = .{}, selected_team_adopted: bool = false, sign_in_url: ?[]const u8 = null, picker_pop_count: usize = 0,
fn credentialSource(self: *const TestAuth) ?credentials.Source { return self.active_source; }
fn selectSource(self: *TestAuth, _: std.mem.Allocator, source: credentials.Source) !?bool { self.selected_source = source; if (self.select_result != null) self.active_source = source; return self.select_result; }
fn pollSignInTransition(self: *TestAuth, _: std.mem.Allocator) login_flow.SignInTransition { const transition = self.sign_in_transition; self.sign_in_transition = .none; return transition; }
fn pulseSignIn(_: *TestAuth, _: std.mem.Allocator) void {}
fn popPickerStage(self: *TestAuth, _: std.mem.Allocator) bool { self.picker_pop_count += 1; return true; }
fn openTeamPicker(_: *TestAuth, _: std.mem.Allocator, _: *login_flow.TeamSelection) void {}
fn refreshFxLoginIfNeeded(self: *TestAuth, _: std.mem.Allocator) !bool { self.refresh_count += 1; if (self.refresh_error) |err| return err; if (self.gateway_ready_after_refresh_count == self.refresh_count) self.gateway_ready = true; return self.refresh_changed; }
fn gatewayCredential(self: *const TestAuth) ?TestGatewayCredential { return if (self.gateway_ready) .{ .api_key = "refreshed-key" } else null; }
fn modelCatalogAccess(self: *const TestAuth) credentials.CatalogAccess { return if (self.catalog_ready) credentials.catalogAccessForCredential(.fx_login, "refreshed-key", "team_123") else .{ .public_only = .fx_login_team_required }; }
fn reconcileAfterFxLoginLogout(self: *TestAuth, _: std.mem.Allocator) !bool { self.logout_reconcile_count += 1; return self.logout_changed; }
fn refreshSourceInventory(self: *TestAuth, _: std.mem.Allocator) !void { self.source_inventory_refresh_count += 1; }
fn recordCredentialRefreshFailure(self: *TestAuth, source: credentials.Source) void { self.refresh_failure_source = source; }
fn openPicker(self: *TestAuth, _: std.mem.Allocator) void { self.picker_opened = true; }
fn teamSelection(self: *TestAuth) ?*TestTeamSelection { return &self.team_selection; }
fn adoptSelectedTeam(self: *TestAuth, _: std.mem.Allocator, _: *TestSelectedTeam) bool { self.selected_team_adopted = true; return true; }
fn closePicker(self: *TestAuth, _: std.mem.Allocator) void { self.picker_closed = true; }
fn signInBrowserUrlAlloc(self: *TestAuth, alloc: std.mem.Allocator) !?[]u8 { const url = self.sign_in_url orelse return null; return try alloc.dupe(u8, url); }};
const TestGatewayCredential = struct { api_key: []const u8,};
const TestUsage = struct { refresh_count: usize = 0, clear_count: usize = 0, last_key: ?[]const u8 = null,
fn replaceReconciliationCredential( self: *TestUsage, _: std.mem.Allocator, api_key: []const u8, ) void { self.refresh_count += 1; self.last_key = api_key; }
fn clearReconciliationCredential(self: *TestUsage) void { self.clear_count += 1; self.last_key = null; }};
const TestRenderRequests = struct { footer_requested: bool = false,
fn request(self: *TestRenderRequests, _: anytype) void { self.footer_requested = true; }};
const TestUrlOpener = struct { calls: usize = 0, succeeds: bool = true, error_on_open: bool = false, opened_url: [256]u8 = undefined, opened_url_len: usize = 0,
fn opener(self: *TestUrlOpener) host.UrlOpener { return .{ .context = self, .open_fn = open, }; }
fn open( raw_context: ?*anyopaque, _: std.mem.Allocator, url: []const u8, ) host.UrlOpenError!bool { const self: *TestUrlOpener = @ptrCast(@alignCast(raw_context.?)); self.calls += 1; if (url.len > self.opened_url.len) return error.OutOfMemory; @memcpy(self.opened_url[0..url.len], url); self.opened_url_len = url.len; if (self.error_on_open) return error.OutOfMemory; return self.succeeds; }
fn openedUrl(self: *const TestUrlOpener) []const u8 { return self.opened_url[0..self.opened_url_len]; }};
const TestApp = struct { alloc: std.mem.Allocator = std.testing.allocator, auth: TestAuth = .{}, model_cache: TestModelCache = .{}, session: struct { usage: TestUsage = .{}, } = .{}, model_cache_warmup_count: usize = 0, notice_write_count: usize = 0, transcript: std.ArrayList(u8) = .empty, test_url_opener: TestUrlOpener = .{}, preference_write_count: usize = 0, last_preference_source: ?credentials.Source = null, preference_write_succeeds: bool = true, shell: struct { render_requests: TestRenderRequests = .{}, } = .{},
fn deinit(self: *TestApp) void { self.transcript.deinit(self.alloc); }
fn startModelCacheWarmup(self: *TestApp) void { self.model_cache_warmup_count += 1; }
fn writeTranscriptClassified(self: *TestApp, text: []const u8, _: bool, _: anytype) !void { try self.transcript.appendSlice(self.alloc, text); }
fn writeDomainNotice(self: *TestApp, notice: types.SemanticNotice, _: bool) !void { self.notice_write_count += 1; try self.transcript.appendSlice(self.alloc, notice.body); try self.transcript.append(self.alloc, '\n'); }
fn flushBeforeBlockingExternalWork(_: *TestApp) !void {}
fn urlOpener(self: *TestApp) host.UrlOpener { return self.test_url_opener.opener(); }
fn persistCredentialSourcePreference(self: *TestApp, source: credentials.Source) void { self.preference_write_count += 1; if (self.preference_write_succeeds) self.last_preference_source = source; }};
test "OAuth app gating accepts native auth or JS-host auth and rejects neither" { const NativeApp = struct { pub const host_profile = runtime_profile.native; }; const JsHostApp = struct { pub const host_profile = runtime_profile.wasm; }; const NeitherApp = struct { pub const host_profile = blk: { var profile = runtime_profile.wasm; profile.js_host_auth = false; break :blk profile; }; };
try std.testing.expect(oauthAuthEnabled(NativeApp)); try std.testing.expect(oauthAuthEnabled(JsHostApp)); try std.testing.expect(!oauthAuthEnabled(NeitherApp));}
test "interactive sign-in opens the owned browser URL through the host" { var app: TestApp = .{}; app.auth.sign_in_url = "https://vercel.test/verify?code=TEST-CODE";
try Runtime(TestApp).openSignInBrowser(&app);
try std.testing.expectEqual(@as(usize, 1), app.test_url_opener.calls); try std.testing.expectEqualStrings( "https://vercel.test/verify?code=TEST-CODE", app.test_url_opener.openedUrl(), );}
test "interactive sign-in preserves manual fallback when the host launcher fails" { var app: TestApp = .{}; app.auth.sign_in_url = "https://vercel.test/verify"; app.test_url_opener.succeeds = false;
try Runtime(TestApp).openSignInBrowser(&app);
try std.testing.expectEqual(@as(usize, 1), app.test_url_opener.calls); try std.testing.expectEqualStrings( "https://vercel.test/verify", app.test_url_opener.openedUrl(), ); try std.testing.expectEqualStrings("https://vercel.test/verify", app.auth.sign_in_url.?);}
test "interactive sign-in frees its browser URL when the host opener errors" { var app: TestApp = .{}; app.auth.sign_in_url = "https://vercel.test/verify"; app.test_url_opener.error_on_open = true;
try std.testing.expectError( error.OutOfMemory, Runtime(TestApp).openSignInBrowser(&app), ); try std.testing.expectEqual(@as(usize, 1), app.test_url_opener.calls);}
test "auth source changes invalidate the catalog and failed selection preserves it" { var app: TestApp = .{}; const runtime = Runtime(TestApp);
app.auth.select_result = true; try std.testing.expect(try runtime.selectCredentialSource(&app, .fx_login)); try std.testing.expectEqual(credentials.Source.fx_login, app.auth.selected_source.?); try std.testing.expectEqual(@as(usize, 1), app.model_cache.reset_count); try std.testing.expectEqual(@as(usize, 1), app.model_cache_warmup_count);
try std.testing.expect(try runtime.selectCredentialSource(&app, .stored_key)); try std.testing.expectEqual(credentials.Source.stored_key, app.auth.selected_source.?); try std.testing.expectEqual(@as(usize, 2), app.model_cache.reset_count); try std.testing.expectEqual(@as(usize, 2), app.model_cache_warmup_count); try std.testing.expectEqual(@as(usize, 2), app.session.usage.refresh_count); try std.testing.expectEqualStrings( "refreshed-key", app.session.usage.last_key.?, );
app.auth.select_result = null; try std.testing.expect(!try runtime.selectCredentialSource(&app, .ai_gateway_api_key)); try std.testing.expectEqual(credentials.Source.stored_key, app.auth.active_source.?); try std.testing.expectEqual(@as(usize, 2), app.model_cache.reset_count); try std.testing.expectEqual(@as(usize, 2), app.model_cache_warmup_count);}
test "VT-4 unavailable picker source preserves active source and reports unavailability" { var app: TestApp = .{}; defer app.deinit(); app.auth.select_result = null;
try Runtime(TestApp).applySourceChoice(&app, .stored_key);
try std.testing.expectEqual(credentials.Source.ai_gateway_api_key, app.auth.active_source.?); try std.testing.expectEqual(@as(usize, 1), app.notice_write_count); try std.testing.expectEqualStrings( "That credential is no longer available. The current source is unchanged.\n", app.transcript.items, );}
test "completed credential switch emits exactly one transcript line" { var app: TestApp = .{}; defer app.deinit(); app.auth.select_result = true;
try Runtime(TestApp).applySourceChoice(&app, .stored_key);
try std.testing.expectEqual(credentials.Source.stored_key, app.auth.active_source.?); try std.testing.expectEqual(@as(usize, 1), app.preference_write_count); try std.testing.expectEqual(credentials.Source.stored_key, app.last_preference_source.?); try std.testing.expectEqual(@as(usize, 1), app.notice_write_count); const expected = try std.fmt.allocPrint( app.alloc, "Switched credential to {s}.\n", .{credentials.sourceLabel(.stored_key)}, ); defer app.alloc.free(expected); try std.testing.expectEqualStrings(expected, app.transcript.items);}
test "team change from an environment source activates and remembers fx login" { var app: TestApp = .{}; defer app.deinit(); app.auth.select_result = true;
try Runtime(TestApp).applyTeamChoice(&app, 0);
try std.testing.expectEqual(@as(usize, 1), app.auth.team_selection.select_count); try std.testing.expect(!app.auth.selected_team_adopted); try std.testing.expectEqual(credentials.Source.fx_login, app.auth.active_source.?); try std.testing.expectEqual(credentials.Source.fx_login, app.auth.selected_source.?); try std.testing.expectEqual(@as(usize, 1), app.preference_write_count); try std.testing.expectEqual(credentials.Source.fx_login, app.last_preference_source.?); try std.testing.expect(app.auth.picker_closed); try std.testing.expectEqual(@as(usize, 1), app.model_cache.reset_count); try std.testing.expectEqual(@as(usize, 1), app.model_cache_warmup_count); try std.testing.expectEqual(@as(usize, 1), app.notice_write_count); try std.testing.expectEqualStrings( "Changed Vercel team to Vercel Labs (vercel-labs).\n", app.transcript.items, );}
test "team change on an active fx login updates and remembers the selected team" { var app: TestApp = .{}; defer app.deinit(); app.auth.active_source = .fx_login;
try Runtime(TestApp).applyTeamChoice(&app, 0);
try std.testing.expect(app.auth.selected_team_adopted); try std.testing.expectEqual(@as(usize, 1), app.preference_write_count); try std.testing.expectEqual(credentials.Source.fx_login, app.last_preference_source.?);}
test "successful direct login remembers fx login after activation" { var app: TestApp = .{}; defer app.deinit(); app.auth.select_result = true; app.auth.sign_in_transition = .{ .succeeded = .{ .vercel = .{} } };
try Runtime(TestApp).collectSignInFacts(&app);
try std.testing.expectEqual(credentials.Source.fx_login, app.auth.active_source.?); try std.testing.expectEqual(@as(usize, 1), app.preference_write_count); try std.testing.expectEqual(credentials.Source.fx_login, app.last_preference_source.?); try std.testing.expectEqual(@as(usize, 1), app.notice_write_count);}
test "direct login source load failure leaves the environment preference unchanged" { var app: TestApp = .{}; defer app.deinit(); app.auth.select_result = null; app.auth.sign_in_transition = .{ .succeeded = .{ .vercel = .{} } };
try Runtime(TestApp).collectSignInFacts(&app);
try std.testing.expectEqual(credentials.Source.ai_gateway_api_key, app.auth.active_source.?); try std.testing.expectEqual(@as(usize, 0), app.preference_write_count); try std.testing.expectEqual(@as(usize, 1), app.auth.picker_pop_count); try std.testing.expect(std.mem.find(u8, app.transcript.items, "could not be loaded") != null);}
test "failed preference persistence keeps a successful direct login active" { var app: TestApp = .{}; defer app.deinit(); app.auth.select_result = true; app.auth.sign_in_transition = .{ .succeeded = .{ .vercel = .{} } }; app.preference_write_succeeds = false;
try Runtime(TestApp).collectSignInFacts(&app);
try std.testing.expectEqual(credentials.Source.fx_login, app.auth.active_source.?); try std.testing.expectEqual(@as(usize, 1), app.preference_write_count); try std.testing.expectEqual(@as(?credentials.Source, null), app.last_preference_source);}
test "successful API key save persists even when the live credential is unchanged" { var app: TestApp = .{}; defer app.deinit(); app.auth.active_source = .stored_key;
try Runtime(TestApp).applyApiKeySaveResult(&app, .{ .saved = false });
try std.testing.expectEqual(credentials.Source.stored_key, app.auth.active_source.?); try std.testing.expectEqual(@as(usize, 1), app.preference_write_count); try std.testing.expectEqual(credentials.Source.stored_key, app.last_preference_source.?);}
test "successful API key save remembers the newly active stored key" { var app: TestApp = .{}; defer app.deinit(); app.auth.active_source = .stored_key;
try Runtime(TestApp).applyApiKeySaveResult(&app, .{ .saved = true });
try std.testing.expectEqual(credentials.Source.stored_key, app.auth.active_source.?); try std.testing.expectEqual(@as(usize, 1), app.preference_write_count); try std.testing.expectEqual(credentials.Source.stored_key, app.last_preference_source.?); try std.testing.expectEqual(@as(usize, 1), app.model_cache.reset_count); try std.testing.expectEqual(@as(usize, 1), app.model_cache_warmup_count);}
test "cancelled login and rejected API key do not persist a source" { var app: TestApp = .{}; defer app.deinit(); app.auth.sign_in_transition = .cancelled;
try Runtime(TestApp).collectSignInFacts(&app); try Runtime(TestApp).applyApiKeySaveResult(&app, .gateway_refused);
try std.testing.expectEqual(@as(usize, 0), app.preference_write_count); try std.testing.expectEqual(credentials.Source.ai_gateway_api_key, app.auth.active_source.?);}
test "team source load failure preserves the environment source and preference" { var app: TestApp = .{}; defer app.deinit(); app.auth.select_result = null;
try Runtime(TestApp).applyTeamChoice(&app, 0);
try std.testing.expectEqual(credentials.Source.ai_gateway_api_key, app.auth.active_source.?); try std.testing.expectEqual(@as(usize, 0), app.preference_write_count); try std.testing.expect(app.auth.picker_closed); try std.testing.expect(std.mem.find(u8, app.transcript.items, "could not be loaded") != null);}
test "prompt credential refresh reloads the catalog after the credential changes" { var app: TestApp = .{}; defer app.deinit(); const runtime = Runtime(TestApp);
try runtime.refreshFxLoginCredentialIfNeeded(&app); try std.testing.expectEqual(@as(usize, 1), app.auth.refresh_count); try std.testing.expectEqual(@as(usize, 0), app.model_cache.reset_count);
app.auth.refresh_changed = true; try runtime.refreshFxLoginCredentialIfNeeded(&app); try std.testing.expectEqual(@as(usize, 2), app.auth.refresh_count); try std.testing.expectEqual(@as(usize, 1), app.model_cache.reset_count); try std.testing.expectEqual(@as(usize, 1), app.model_cache_warmup_count); try std.testing.expectEqual(@as(usize, 1), app.session.usage.refresh_count);}
test "credential removal clears the reconciliation credential" { var app: TestApp = .{}; app.auth.gateway_ready = false;
Runtime(TestApp).applyCredentialChange(&app, true);
try std.testing.expectEqual(@as(usize, 1), app.session.usage.clear_count); try std.testing.expectEqual(@as(usize, 0), app.session.usage.refresh_count);}
test "logout result reconciles live auth and renders only sanitized notices" { var app: TestApp = .{}; defer app.deinit(); app.auth.logout_changed = true;
try Runtime(TestApp).applyLogoutResult(&app, .{ .session_deleted = true, .remote_revocation_failed = true, });
try std.testing.expectEqual(@as(usize, 1), app.auth.logout_reconcile_count); try std.testing.expectEqual(@as(usize, 1), app.model_cache.reset_count); try std.testing.expectEqual(@as(usize, 1), app.model_cache_warmup_count); try std.testing.expect(std.mem.find(u8, app.transcript.items, "Signed out of fx.") != null); try std.testing.expect(std.mem.find(u8, app.transcript.items, login_flow.remote_revocation_warning) != null); for ([_][]const u8{ "access-secret", "refresh-secret", "RemoteRevokeFailed", "https://issuer.example" }) |detail| { try std.testing.expect(std.mem.find(u8, app.transcript.items, detail) == null); }}
test "logout durability failure still reconciles live auth" { var app: TestApp = .{}; defer app.deinit(); app.auth.logout_changed = true;
try Runtime(TestApp).applyLogoutResult(&app, .{ .session_deleted = true, .local_durability_failed = true, .remote_revocation_failed = true, });
try std.testing.expectEqual(@as(usize, 1), app.auth.logout_reconcile_count); try std.testing.expectEqual(@as(usize, 1), app.model_cache.reset_count); try std.testing.expect(std.mem.find(u8, app.transcript.items, "Could not confirm durable fx logout.") != null); try std.testing.expect(std.mem.find(u8, app.transcript.items, login_flow.remote_revocation_warning) != null); try std.testing.expect(std.mem.find(u8, app.transcript.items, "current source is unchanged") == null);}
test "prompt credential refresh failure is recoverable and detail-free" { var app: TestApp = .{}; defer app.deinit(); app.auth.refresh_error = error.OAuthRequestFailed;
try std.testing.expect(!try Runtime(TestApp).preparePromptCredential(&app)); try std.testing.expect(std.mem.find(u8, app.transcript.items, "fx login credential refresh failed.") != null); try std.testing.expect(std.mem.find(u8, app.transcript.items, "Choose another source below.") != null); try std.testing.expect(std.mem.find(u8, app.transcript.items, "OAuthRequestFailed") == null); try std.testing.expect(app.shell.render_requests.footer_requested); try std.testing.expectEqual(@as(usize, 1), app.auth.source_inventory_refresh_count); try std.testing.expect(app.auth.refresh_failure_source == null); try std.testing.expect(app.auth.picker_opened); try std.testing.expectEqual(@as(usize, 0), app.model_cache.reset_count);}
test "prompt credential admission retries a crossed readiness deadline" { var app: TestApp = .{}; defer app.deinit(); app.auth.gateway_ready = false; app.auth.gateway_ready_after_refresh_count = 2;
try std.testing.expect(try Runtime(TestApp).preparePromptCredential(&app)); try std.testing.expectEqual(@as(usize, 2), app.auth.refresh_count); try std.testing.expectEqual(@as(usize, 0), app.transcript.items.len); try std.testing.expect(!app.auth.picker_opened);}
test "prompt credential admission rejects a credential that remains unavailable" { var app: TestApp = .{}; defer app.deinit(); app.auth.gateway_ready = false;
try std.testing.expect(!try Runtime(TestApp).preparePromptCredential(&app)); try std.testing.expectEqual(@as(usize, 2), app.auth.refresh_count); try std.testing.expect(std.mem.find(u8, app.transcript.items, "fx login credential refresh failed.") != null); try std.testing.expect(app.auth.picker_opened);}
test "prompt credential refresh allows only OutOfMemory to escape" { var app: TestApp = .{}; defer app.deinit(); app.auth.refresh_error = error.OutOfMemory;
try std.testing.expectError(error.OutOfMemory, Runtime(TestApp).preparePromptCredential(&app)); try std.testing.expectEqual(@as(usize, 0), app.transcript.items.len); try std.testing.expect(!app.shell.render_requests.footer_requested); try std.testing.expectEqual(@as(usize, 0), app.auth.source_inventory_refresh_count); try std.testing.expect(!app.auth.picker_opened);}