Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(web): show only usable accounts in the connection authorization card

shoudi zhengb9a343159edf
diff --git a/apps/teamhub/internal/app/contract_server_agent_connector.go b/apps/teamhub/internal/app/contract_server_agent_connector.go
index ca7befb6..593de4e6 100644
--- a/apps/teamhub/internal/app/contract_server_agent_connector.go
+++ b/apps/teamhub/internal/app/contract_server_agent_connector.go
@@ -91,10 +91,12 @@ func (a *App) resolveConnectorAccount(c *gin.Context) {
a.writeAgentAPIError(c, 400, api.AgentApiErrorCodeInvalidInput, "Unsupported application")
return
}
- prompt := fmt.Sprintf("Please connect and authorize the %s account so the command can continue.", input.AppKey)
- if selector != "" {
- prompt = fmt.Sprintf("Please connect and authorize the %s account %s so the command can continue.", input.AppKey, selector)
+ displayName := input.AppKey
+ catalog := a.externalSources.ListApps()
+ if i := slices.IndexFunc(catalog, func(app externalsource.ExternalApp) bool { return app.Key == input.AppKey }); i >= 0 {
+ displayName = catalog[i].DisplayName
}
+ prompt := connectorAuthorizationPrompt(displayName, selector)
if roomID, card, ok := a.postConnectorCard(c, token, prompt, typedcard.DecisionCommand{
ConnectionAuth: &typedcard.ConnectionAuthDecision{Prompt: prompt, AppKey: input.AppKey, ReusePending: true},
}); ok {
@@ -102,6 +104,15 @@ func (a *App) resolveConnectorAccount(c *gin.Context) {
}
}
+// connectorAuthorizationPrompt is the Human-facing ask on a ConnectionAuth
+// card. A selector that is a connection ID is internal and never shown.
+func connectorAuthorizationPrompt(displayName, selector string) string {
+ if selector == "" || strings.HasPrefix(selector, "external_connection_") {
+ return fmt.Sprintf("Please connect and authorize your %s account so I can continue.", displayName)
+ }
+ return fmt.Sprintf("Please connect and authorize the %s account %s so I can continue.", displayName, selector)
+}
+
// requestProviderKey posts, or reuses, the card asking the Agent's Human for
// the deployment's Composio API key, and answers provider_key_required so the
// Agent runs the command again once the key is saved. appKey names the app
diff --git a/apps/teamhub/internal/app/contract_server_agent_connector_test.go b/apps/teamhub/internal/app/contract_server_agent_connector_test.go
index 059afb9b..dc01363f 100644
--- a/apps/teamhub/internal/app/contract_server_agent_connector_test.go
+++ b/apps/teamhub/internal/app/contract_server_agent_connector_test.go
@@ -38,3 +38,15 @@ func TestConnectorAccountSelection(t *testing.T) {
t.Fatal("apps without dedicated commands must still select a delegated account")
}
}
+
+func TestConnectorAuthorizationPrompt(t *testing.T) {
+ for _, tc := range []struct{ selector, want string }{
+ {"", "Please connect and authorize your Outlook Mail account so I can continue."},
+ {"[email protected]", "Please connect and authorize the Outlook Mail account [email protected] so I can continue."},
+ {"external_connection_971b3337eee6a6b2cfcb96fe9431099d", "Please connect and authorize your Outlook Mail account so I can continue."},
+ } {
+ if got := connectorAuthorizationPrompt("Outlook Mail", tc.selector); got != tc.want {
+ t.Errorf("selector %q: got %q", tc.selector, got)
+ }
+ }
+}
diff --git a/apps/web/src/features/apps/app-manage-dialog.tsx b/apps/web/src/features/apps/app-manage-dialog.tsx
index 7ac4b03f..785ba7c4 100644
--- a/apps/web/src/features/apps/app-manage-dialog.tsx
+++ b/apps/web/src/features/apps/app-manage-dialog.tsx
@@ -23,7 +23,10 @@ import {
externalConnectionsQueryKey,
} from "./connected-apps-queries";
import { ConnectAppStatus, useConnectAppFlow } from "./connect-app-flow";
-import { establishedExternalConnections } from "./connection-state";
+import {
+ establishedExternalConnections,
+ openPendingExternalConnection,
+} from "./connection-state";
export function AppManageDialog({
app,
@@ -62,7 +65,12 @@ export function AppManageDialog({
: `Connect ${app.display_name}`
}
disabled={connectFlow.connection.isPending}
- onClick={() => connectFlow.start(app)}
+ onClick={() =>
+ connectFlow.start(
+ app,
+ openPendingExternalConnection(connections, app.key),
+ )
+ }
size="compact"
tone="secondary"
>
diff --git a/apps/web/src/features/apps/connected-apps-page.test.tsx b/apps/web/src/features/apps/connected-apps-page.test.tsx
index ad8dfaed..2d1a595d 100644
--- a/apps/web/src/features/apps/connected-apps-page.test.tsx
+++ b/apps/web/src/features/apps/connected-apps-page.test.tsx
@@ -663,6 +663,47 @@ describe("Connected apps", () => {
).toBeEnabled();
});
+ it("resumes an open pending account from Add account instead of creating one", async () => {
+ const open = vi
+ .spyOn(window, "open")
+ .mockReturnValue({ opener: null } as unknown as Window);
+ const runtime = await testRuntime();
+ const existing = (await runtime.client.listExternalConnections())
+ .connections[0]!;
+ const pending = {
+ ...existing,
+ id: "external-connection-pending",
+ identity_label: "",
+ status: "pending" as const,
+ connect_url: "https://connect.example.test/open",
+ connect_expires_at: "2999-01-01T00:00:00Z",
+ };
+ vi.spyOn(runtime.client, "listExternalConnections").mockResolvedValue({
+ connections: [existing, pending],
+ });
+ vi.spyOn(runtime.client, "getExternalConnection").mockResolvedValue(
+ pending,
+ );
+ const create = vi.spyOn(runtime.client, "createExternalConnection");
+
+ renderPage(runtime, "/apps?app=gmail");
+
+ const dialog = await screen.findByRole("dialog", { name: "Gmail" });
+ fireEvent.click(
+ within(dialog).getByRole("button", {
+ name: "Add another Gmail account",
+ }),
+ );
+ await waitFor(() =>
+ expect(open).toHaveBeenCalledWith(
+ "https://connect.example.test/open",
+ expect.any(String),
+ expect.any(String),
+ ),
+ );
+ expect(create).not.toHaveBeenCalled();
+ });
+
it("confirms what disconnecting stops before disconnecting an account", async () => {
const runtime = await testRuntime();
const existing = (await runtime.client.listExternalConnections())
diff --git a/apps/web/src/features/apps/connected-apps-page.tsx b/apps/web/src/features/apps/connected-apps-page.tsx
index b21daff4..be1b421f 100644
--- a/apps/web/src/features/apps/connected-apps-page.tsx
+++ b/apps/web/src/features/apps/connected-apps-page.tsx
@@ -21,7 +21,10 @@ import {
AppManageDialog,
DisconnectConnectionDialog,
} from "./app-manage-dialog";
-import { activeExternalConnections } from "./connection-state";
+import {
+ activeExternalConnections,
+ openPendingExternalConnection,
+} from "./connection-state";
import {
externalAppsQueryOptions,
externalConnectionsQueryOptions,
@@ -223,10 +226,7 @@ function CatalogAppCard({
const connectFlow = useConnectAppFlow();
const createConnection = connectFlow.connection;
const active = activeExternalConnections(connections);
- const pending = connections.find(
- (connection) =>
- connection.status === "pending" && !connection.status_error_code,
- );
+ const pending = openPendingExternalConnection(connections, app.key);
const canConnect = app.availability === "available";
const canStart = connectFlow.canStart(app);
const connectedLabel = active.length
diff --git a/apps/web/src/features/apps/connection-state.ts b/apps/web/src/features/apps/connection-state.ts
index 1a431bdc..e9367190 100644
--- a/apps/web/src/features/apps/connection-state.ts
+++ b/apps/web/src/features/apps/connection-state.ts
@@ -14,6 +14,22 @@ export function externalConnectionNeedsAttention(
);
}
+/**
+ * The pending connection of an app whose authorization can still be resumed,
+ * so a new attempt reuses it instead of creating another row.
+ */
+export function openPendingExternalConnection(
+ connections: TeamHubExternalConnection[],
+ appKey: string,
+) {
+ return connections.find(
+ (connection) =>
+ connection.provider === appKey &&
+ connection.status === "pending" &&
+ !connection.status_error_code,
+ );
+}
+
export function establishedExternalConnections(
connections: TeamHubExternalConnection[],
) {
diff --git a/apps/web/src/features/rooms/cards/decision-connection-auth-view.test.tsx b/apps/web/src/features/rooms/cards/decision-connection-auth-view.test.tsx
index 9ffe7c72..d728ce39 100644
--- a/apps/web/src/features/rooms/cards/decision-connection-auth-view.test.tsx
+++ b/apps/web/src/features/rooms/cards/decision-connection-auth-view.test.tsx
@@ -1,5 +1,6 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import type { TeamHubExternalConnection } from "@/features/teamhub/teamhub-types";
import { MemoryRouter } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
@@ -29,8 +30,21 @@ async function setup(
actorId = "alice",
hasConnection = true,
status: "active" | "pending" = "active",
+ others: Partial<TeamHubExternalConnection>[] = [],
+ canConnectNew = true,
) {
const runtime = createTestTeamHubRuntime();
+ if (!canConnectNew) {
+ const catalog = await runtime.client.listExternalApps();
+ vi.spyOn(runtime.client, "listExternalApps").mockResolvedValue({
+ ...catalog,
+ apps: catalog.apps.map((app) =>
+ app.key === "notion"
+ ? { ...app, availability: "unavailable" as const }
+ : app,
+ ),
+ });
+ }
const existing = (await runtime.client.listExternalConnections())
.connections[0]!;
@@ -42,7 +56,10 @@ async function setup(
status,
};
vi.spyOn(runtime.client, "listExternalConnections").mockResolvedValue({
- connections: hasConnection ? [connection] : [],
+ connections: [
+ ...(hasConnection ? [connection] : []),
+ ...others.map((other) => ({ ...connection, ...other })),
+ ],
});
if (next.status === "authorizing")
vi.spyOn(runtime.client, "getExternalConnection").mockResolvedValue({
@@ -266,6 +283,160 @@ describe("Chat connection authorization", () => {
expect(create).not.toHaveBeenCalled();
});
+ it("lists only usable accounts and offers a new account", async () => {
+ vi.spyOn(window, "open").mockReturnValue({
+ opener: null,
+ } as unknown as Window);
+ const { runtime, decision, connection } = await setup(
+ card,
+ "alice",
+ true,
+ "active",
+ [
+ { id: "notion-pending", status: "pending", identity_label: "" },
+ {
+ id: "notion-duplicate",
+ status: "failed",
+ status_error_code: "duplicate_remote_principal",
+ identity_label: "Duplicate Notion",
+ },
+ {
+ id: "notion-expired",
+ status: "expired",
+ identity_label: "Old Notion",
+ },
+ ],
+ );
+ const create = vi
+ .spyOn(runtime.client, "createExternalConnection")
+ .mockResolvedValue({
+ ...connection,
+ id: "notion-new",
+ status: "pending",
+ connect_url: "https://connect.example.test/new",
+ });
+ vi.spyOn(runtime.client, "getExternalConnection").mockResolvedValue({
+ ...connection,
+ id: "notion-pending",
+ status: "pending",
+ connect_url: "https://connect.example.test/old",
+ connect_expires_at: "2026-01-01T00:00:00Z",
+ });
+ const picker = await screen.findByRole("combobox", {
+ name: "Notion account",
+ });
+ expect(picker).toHaveTextContent("Alice's Notion");
+ fireEvent.click(picker);
+ const options = (await screen.findAllByRole("option")).map(
+ (option) => option.textContent,
+ );
+ expect(options).toEqual([
+ "Alice's Notion",
+ "Old Notion (needs reconnecting)",
+ "Connect a new account",
+ ]);
+ fireEvent.click(
+ screen.getByRole("option", { name: "Connect a new account" }),
+ );
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Connect Notion" }),
+ );
+ await waitFor(() =>
+ expect(decision).toHaveBeenCalledWith(
+ expect.objectContaining({ connectionId: "notion-new" }),
+ ),
+ );
+ expect(create).toHaveBeenCalledOnce();
+ });
+
+ it("hides the picker for a single account when no new account can be added", async () => {
+ await setup(card, "alice", true, "active", [], false);
+ expect(
+ await screen.findByRole("button", { name: "Allow Project Writer" }),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("combobox", { name: "Notion account" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("offers a new account beside a single account", async () => {
+ await setup();
+ expect(
+ await screen.findByRole("combobox", { name: "Notion account" }),
+ ).toHaveTextContent("Alice's Notion");
+ });
+
+ it("reuses an open pending connection for a new account", async () => {
+ vi.spyOn(window, "open").mockReturnValue({
+ opener: null,
+ } as unknown as Window);
+ const { runtime, decision, connection } = await setup(
+ card,
+ "alice",
+ false,
+ "active",
+ [{ id: "notion-pending", status: "pending" }],
+ );
+ vi.spyOn(runtime.client, "getExternalConnection").mockResolvedValue({
+ ...connection,
+ id: "notion-pending",
+ status: "pending",
+ connect_url: "https://connect.example.test/open",
+ connect_expires_at: "2999-01-01T00:00:00Z",
+ });
+ const create = vi.spyOn(runtime.client, "createExternalConnection");
+ expect(
+ screen.queryByRole("combobox", { name: "Notion account" }),
+ ).not.toBeInTheDocument();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Connect Notion" }),
+ );
+ await waitFor(() =>
+ expect(window.open).toHaveBeenCalledWith(
+ "https://connect.example.test/open",
+ "linger_composio_oauth",
+ expect.any(String),
+ ),
+ );
+ expect(decision).toHaveBeenCalledWith(
+ expect.objectContaining({ connectionId: "notion-pending" }),
+ );
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it("creates a new connection when the open pending one cannot be read", async () => {
+ vi.spyOn(window, "open").mockReturnValue({
+ opener: null,
+ } as unknown as Window);
+ const { runtime, decision, connection } = await setup(
+ card,
+ "alice",
+ false,
+ "active",
+ [{ id: "notion-pending", status: "pending" }],
+ );
+ vi.spyOn(runtime.client, "getExternalConnection").mockRejectedValue(
+ new Error("gone"),
+ );
+ const create = vi
+ .spyOn(runtime.client, "createExternalConnection")
+ .mockResolvedValue({
+ ...connection,
+ id: "notion-new",
+ status: "pending",
+ connect_url: "https://connect.example.test/new",
+ });
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Connect Notion" }),
+ );
+ await waitFor(() =>
+ expect(decision).toHaveBeenCalledWith(
+ expect.objectContaining({ connectionId: "notion-new" }),
+ ),
+ );
+ expect(create).toHaveBeenCalledOnce();
+ });
+
it("navigates OAuth only after durable consent is accepted", async () => {
vi.spyOn(window, "open").mockReturnValue({
opener: null,
diff --git a/apps/web/src/features/rooms/cards/decision-connection-auth-view.tsx b/apps/web/src/features/rooms/cards/decision-connection-auth-view.tsx
index b5268995..0a7f4d07 100644
--- a/apps/web/src/features/rooms/cards/decision-connection-auth-view.tsx
+++ b/apps/web/src/features/rooms/cards/decision-connection-auth-view.tsx
@@ -18,6 +18,8 @@ import {
externalConnectionsQueryOptions,
} from "@/features/apps/connected-apps-queries";
import {
+ externalConnectionNeedsAttention,
+ openPendingExternalConnection,
reauthorizationConnectUrl,
usableConnectUrl,
} from "@/features/apps/connection-state";
@@ -41,6 +43,9 @@ interface Props {
const label = "App authorization requested";
+/** The account picker value for a new account; never a connection id. */
+const NEW_ACCOUNT = "__new_account__";
+
/**
* A connection authorization: the Human picks or connects an account of the
* app the Agent needs. Approving records their consent to that Connection
@@ -173,17 +178,30 @@ function ConnectionAuthorizationActions({
const app = apps.data?.apps.find((item) => item.key === appKey);
const appName = app?.display_name ?? fallbackAppName;
const agentName = card.requester.display_name;
- const available = (connections.data?.connections ?? []).filter(
+ const appConnections = (connections.data?.connections ?? []).filter(
+ (item) => item.provider === appKey,
+ );
+ // Only accounts the Human can use or repair; abandoned pending attempts and
+ // rejected duplicates are not accounts.
+ const available = appConnections.filter(
(item) =>
- item.provider === appKey &&
- !["disconnecting", "revoke_pending"].includes(item.status),
+ item.status === "active" || externalConnectionNeedsAttention(item),
);
- if (created && !available.some((item) => item.id === created.id))
- available.push(created);
+ // The connection this card just started stays visible while it is pending.
+ const createdNow =
+ created &&
+ (appConnections.find((item) => item.id === created.id) ?? created);
+ if (
+ createdNow?.status === "pending" &&
+ !available.some((item) => item.id === createdNow.id)
+ )
+ available.push(createdNow);
const selected =
- available.find((item) => item.id === selectedId) ??
- available.find((item) => item.status === "active") ??
- available[0];
+ selectedId === NEW_ACCOUNT
+ ? undefined
+ : (available.find((item) => item.id === selectedId) ??
+ available.find((item) => item.status === "active") ??
+ available.find(externalConnectionNeedsAttention));
const resumeUrl =
fallbackUrl ||
reauthorizationConnectUrl(bound.data) ||
@@ -219,10 +237,25 @@ function ConnectionAuthorizationActions({
if (!connection) {
if (!app || !app.capabilities.includes("agent_tools"))
throw new Error("This app is unavailable for Agent access.");
- connection = await client.createExternalConnection(app.key);
+ // Resume an open pending attempt of this app instead of adding a row.
+ const pending = openPendingExternalConnection(
+ connections.data?.connections ?? [],
+ app.key,
+ );
+ // A pending row that cannot be read is abandoned for a new one.
+ const detail = pending
+ ? await client
+ .getExternalConnection(pending.id)
+ .catch(() => undefined)
+ : undefined;
+ connectUrl = usableConnectUrl(detail) ?? "";
+ connection =
+ detail && connectUrl
+ ? detail
+ : await client.createExternalConnection(app.key);
+ if (!connectUrl) connectUrl = connection.connect_url ?? "";
setCreated(connection);
setSelectedId(connection.id);
- connectUrl = connection.connect_url ?? "";
} else if (connection.status !== "active" && !connectUrl) {
connectUrl =
reauthorizationConnectUrl(connection) ??
@@ -273,6 +306,10 @@ function ConnectionAuthorizationActions({
app?.availability === "available" &&
app.capabilities.includes("agent_tools");
const loading = !authorizing && (connections.isPending || apps.isPending);
+ const showPicker =
+ !authorizing &&
+ available.length > 0 &&
+ (canConnectNew || available.length > 1);
const primaryAction = resumeUrl ? (
<Button
aria-label="Open authorization window"
@@ -341,24 +378,29 @@ function ConnectionAuthorizationActions({
: undefined)
}
>
- {!authorizing && available.length > 1 ? (
+ {showPicker ? (
<div className="pb-1">
<Select
aria-label={`${appName} account`}
className="h-8 w-full px-2.5 text-sm"
disabled={busy}
onValueChange={setSelectedId}
- value={selected?.id ?? ""}
+ value={selected?.id ?? (canConnectNew ? NEW_ACCOUNT : "")}
>
{available.map((connection) => (
<SelectItem key={connection.id} value={connection.id}>
{`${connection.identity_label || appName}${
- connection.status !== "active"
- ? ` (${connection.status})`
- : ""
+ connection.status === "active"
+ ? ""
+ : connection.status === "pending"
+ ? " (pending)"
+ : " (needs reconnecting)"
}`}
</SelectItem>
))}
+ {canConnectNew ? (
+ <SelectItem value={NEW_ACCOUNT}>Connect a new account</SelectItem>
+ ) : null}
</Select>
</div>
) : null}
diff --git a/apps/web/src/features/rooms/cards/decision-profile-setup-view.tsx b/apps/web/src/features/rooms/cards/decision-profile-setup-view.tsx
index 37759381..f53a7bee 100644
--- a/apps/web/src/features/rooms/cards/decision-profile-setup-view.tsx
+++ b/apps/web/src/features/rooms/cards/decision-profile-setup-view.tsx
@@ -20,7 +20,10 @@ import {
externalAppsQueryOptions,
externalConnectionsQueryOptions,
} from "@/features/apps/connected-apps-queries";
-import { activeExternalConnections } from "@/features/apps/connection-state";
+import {
+ activeExternalConnections,
+ openPendingExternalConnection,
+} from "@/features/apps/connection-state";
import { teamHubDone } from "@/features/teamhub/teamhub-api";
import {
createTeamHubIdempotencyKey,
@@ -274,10 +277,7 @@ function SetupAppRow({
const active = showConnections
? activeExternalConnections(connections)[0]
: undefined;
- const pending = connections.find(
- (connection) =>
- connection.status === "pending" && !connection.status_error_code,
- );
+ const pending = openPendingExternalConnection(connections, appKey);
const verifying = connections.some(
(connection) =>
connection.status === "pending" &&