Skip to content

Lightpanda: the headless browser designed for AI and automation

agent: add keep/login/logout menu for subscription providers

Adrià Arrufat97e26ae86ee1
diff --git a/src/agent/Agent.zig b/src/agent/Agent.zig
index d4646909d..d77433a83 100644
--- a/src/agent/Agent.zig
+++ b/src/agent/Agent.zig
@@ -924,8 +924,8 @@ fn handleProvider(self: *Agent, _: std.mem.Allocator, rest: []const u8) void {
self.terminal.printError("unknown provider: {s} (or 'null' to disable the LLM)", .{trimmed});
return;
};
- // Re-selecting vertex (token refresh) or a subscription provider (re-import
- // after logging into its CLI) falls through instead of no-op'ing.
+ // Re-selecting vertex (token refresh) or a subscription provider (the
+ // keep/login/logout menu) falls through instead of no-op'ing.
const vertex_project = provider == .vertex and settings.vertexProjectMode();
const sub_desc = auth.descriptorFor(provider);
if (self.credential) |current| if (provider == current.provider and !vertex_project and sub_desc == null) {
@@ -943,20 +943,12 @@ fn handleProvider(self: *Agent, _: std.mem.Allocator, rest: []const u8) void {
};
return;
}
- // Subscription provider: use the stored session, or run the interactive
- // login (device-code flow) when there's none yet.
+ // Subscription provider: menu over the stored session, or first-time login.
if (sub_desc) |desc| {
- var owned = (auth.sessionFor(self.allocator, provider) catch null) orelse
- (auth.login(self.allocator, desc, &self.http_interrupt) catch |err| {
- if (err == error.LoginCancelled) {
- // Undo `requestCancel`'s side effects before the next turn.
- self.resetAfterCancel(self.conversation.messages.items.len);
- self.terminal.printInfo("{s} login cancelled", .{desc.label});
- return;
- }
- self.terminal.printError("{s} login failed: {s}", .{ desc.label, @errorName(err) });
- return;
- });
+ var owned = if (auth.sessionFor(self.allocator, provider) catch null) |stored|
+ self.promptStoredSubscription(desc, stored) orelse return
+ else
+ self.subscriptionLogin(desc) orelse return;
self.setProvider(.{ .provider = provider, .key = .{ .session = owned } }) catch |err| {
owned.deinit();
self.terminal.printError("failed to set provider: {s}", .{@errorName(err)});
@@ -985,6 +977,48 @@ fn handleProvider(self: *Agent, _: std.mem.Allocator, rest: []const u8) void {
};
}
+/// Interactive device-code login; cancellation/failure is reported here.
+fn subscriptionLogin(self: *Agent, desc: *const auth.Descriptor) ?auth.Session {
+ return auth.login(self.allocator, desc, &self.http_interrupt) catch |err| {
+ if (err == error.LoginCancelled) {
+ // Undo `requestCancel`'s side effects before the next turn.
+ self.resetAfterCancel(self.conversation.messages.items.len);
+ self.terminal.printInfo("{s} login cancelled", .{desc.label});
+ return null;
+ }
+ self.terminal.printError("{s} login failed: {s}", .{ desc.label, @errorName(err) });
+ return null;
+ };
+}
+
+/// Menu for re-selecting an already-logged-in subscription provider: keep the
+/// stored login, re-run it (switch accounts), or log out. Null when there is
+/// nothing to activate.
+fn promptStoredSubscription(self: *Agent, desc: *const auth.Descriptor, stored: auth.Session) ?auth.Session {
+ var session = stored;
+ var header_buf: [128]u8 = undefined;
+ const header = std.fmt.bufPrint(&header_buf, "Already logged in with your {s}. Pick:", .{desc.label}) catch
+ "Already logged in. Pick:";
+ const idx = picker.promptNumberedChoice(header, &.{
+ "keep — use the stored login",
+ "login — run the login again (e.g. to switch accounts)",
+ "logout — forget the stored login",
+ }, 0) catch {
+ session.deinit();
+ return null;
+ };
+ if (idx == 0) return session;
+ session.deinit();
+ if (idx == 1) return self.subscriptionLogin(desc);
+ auth.logout(self.allocator, desc) catch |err| {
+ self.terminal.printError("could not remove the stored login: {s}", .{@errorName(err)});
+ return null;
+ };
+ self.terminal.printInfo("{s} logged out.", .{desc.label});
+ if (self.credential) |c| if (c.provider == desc.provider) self.disableProvider();
+ return null;
+}
+
/// Tear down the LLM client and persist a null provider so the next REPL launch
/// starts in basic mode without re-prompting. Inverse of `setProvider`.
fn disableProvider(self: *Agent) void {
diff --git a/src/agent/auth/auth.zig b/src/agent/auth/auth.zig
index bdc654b75..cb64147a7 100644
--- a/src/agent/auth/auth.zig
+++ b/src/agent/auth/auth.zig
@@ -143,6 +143,22 @@ fn storeSaveAt(arena: std.mem.Allocator, dir: []const u8, id: []const u8, tokens
try writeJsonAtomic(path, map, .fromMode(0o600));
}
+fn storeDeleteAt(arena: std.mem.Allocator, dir: []const u8, id: []const u8) !void {
+ const path = try storePath(arena, dir);
+ var map = readStoreFile(arena, path);
+ if (!map.map.swapRemove(id)) return;
+ try writeJsonAtomic(path, map, .fromMode(0o600));
+}
+
+/// Remove the stored token for `id`. No-op when absent.
+fn storeDelete(allocator: std.mem.Allocator, id: []const u8) !void {
+ var arena: std.heap.ArenaAllocator = .init(allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const dir = dataDir(a) orelse return error.NoDataDir;
+ return storeDeleteAt(a, dir, id);
+}
+
/// Load the stored token for `id`, or null when absent/unreadable/no data dir.
pub fn storeLoad(allocator: std.mem.Allocator, id: []const u8) !?TokenSet {
var da: std.heap.ArenaAllocator = .init(allocator);
@@ -218,6 +234,11 @@ pub fn login(allocator: std.mem.Allocator, desc: *const Descriptor, interrupt: ?
return .{ .allocator = allocator, .descriptor = desc, .tokens = tokens };
}
+/// Forget the stored credential for `desc`'s provider.
+pub fn logout(allocator: std.mem.Allocator, desc: *const Descriptor) !void {
+ return storeDelete(allocator, @tagName(desc.provider));
+}
+
/// Is a stored credential available for `provider` — unexpired, or refreshable
/// (`ensureFresh` runs before the first request)? Lets the picker offer the
/// subscription without an API-key env var.
@@ -247,7 +268,7 @@ test "descriptorFor resolves codex, null for a non-OAuth provider" {
try std.testing.expectEqual(@as(?*const Descriptor, null), descriptorFor(.openai));
}
-test "token store save/load round-trips" {
+test "token store save/load/delete round-trips" {
const a = std.testing.allocator;
var arena: std.heap.ArenaAllocator = .init(a);
defer arena.deinit();
@@ -269,4 +290,7 @@ test "token store save/load round-trips" {
try std.testing.expectEqualStrings("ref-1", loaded.refresh_token);
try std.testing.expectEqualStrings("acct-9", loaded.account_id.?);
try std.testing.expectEqual(@as(i64, 999), loaded.expires_at_ms);
+
+ try storeDeleteAt(scratch, dir, "codex");
+ try std.testing.expectEqual(@as(?TokenSet, null), try storeLoadAt(a, dir, "codex"));
}