The Open Framework for Building Agents
fix(eve): render Linear connection authorization (#1322)
Colton Padden5d25b16ad602
diff --git a/.changeset/linear-channel-authorization.md b/.changeset/linear-channel-authorization.mdnew file mode 100644index 000000000..e4995a6bd--- /dev/null+++ b/.changeset/linear-channel-authorization.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Render user-scoped connection authorization in Linear Agent Sessions. Linear users now receive the native account-linking affordance, and the channel posts the authorization outcome before a parked turn resumes.diff --git a/docs/channels/linear.mdx b/docs/channels/linear.mdxindex 0e7fe6841..0841fbd37 100644--- a/docs/channels/linear.mdx+++ b/docs/channels/linear.mdx@@ -82,6 +82,10 @@ Turn start posts an ephemeral `thought`, tool calls post ephemeral `action` actiHuman-in-the-loop (HITL) input requests render as Linear `elicitation` activities. When the user replies to the Agent Session, the channel resolves that prompt back to the pending eve input request and resumes with `inputResponses`.+### Connection authorization++When a user-scoped connection needs authorization, the default channel posts Linear's native `auth` elicitation with the provider's sign-in URL, targeted to the Linear user who started the session. URL-less device flows render their instructions and user code as a plain elicitation. After authorization finishes, the channel posts a thought with the outcome; successful authorization indicates that the parked turn is resuming.+### Proactive sessionsStart a session without an inbound webhook with `receive(linear, { target })`. See [Proactive sessions](#proactive-sessions) below for the target shape and examples.diff --git a/packages/eve/src/public/channels/linear/defaults.test.ts b/packages/eve/src/public/channels/linear/defaults.test.tsnew file mode 100644index 000000000..83666c2f6--- /dev/null+++ b/packages/eve/src/public/channels/linear/defaults.test.ts@@ -0,0 +1,187 @@+import { describe, expect, it, vi } from "vitest";++import type { SessionContext } from "#public/definitions/callback-context.js";+import { createDefaultEvents } from "#public/channels/linear/defaults.js";+import type {+ LinearChannelState,+ LinearEventContext,+} from "#public/channels/linear/linearChannel.js";++function sessionContext(): SessionContext {+ return {+ getSandbox: vi.fn(),+ getSkill: vi.fn(),+ session: {+ auth: {+ current: {+ attributes: {},+ authenticator: "linear-agent-webhook",+ principalId: "linear:user_1",+ principalType: "user",+ subject: "user_1",+ },+ initiator: null,+ },+ id: "test-session",+ turn: { id: "test-turn", sequence: 0 },+ },+ };+}++function buildChannelStub(): LinearEventContext {+ return {+ state: {+ agentSessionId: "agent_session_1",+ pendingToolCallMessage: null,+ } as LinearChannelState,+ } as LinearEventContext;+}++function buildEvents() {+ const fetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ data: {+ agentActivityCreate: {+ agentActivity: { id: "activity_1" },+ success: true,+ },+ },+ }),+ { headers: { "content-type": "application/json" }, status: 200 },+ ),+ );+ return {+ events: createDefaultEvents({+ api: { fetch },+ credentials: { accessToken: "linear-token" },+ }),+ fetch,+ };+}++function activityInput(fetch: ReturnType<typeof vi.fn>): Record<string, unknown> {+ const request = fetch.mock.calls[0]?.[1] as RequestInit;+ const body = JSON.parse(String(request.body)) as {+ variables: { input: Record<string, unknown> };+ };+ return body.variables.input;+}++describe("createDefaultEvents authorization.required", () => {+ it("posts Linear's native auth elicitation for the triggering user", async () => {+ const { events, fetch } = buildEvents();++ await events["authorization.required"]!(+ {+ authorization: {+ displayName: "Notion Workspace",+ url: "https://connect.example.com/a/sca_1",+ },+ description: "Authorization required for notion",+ name: "notion",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_0",+ },+ buildChannelStub(),+ sessionContext(),+ );++ expect(fetch).toHaveBeenCalledTimes(1);+ expect(activityInput(fetch)).toEqual({+ agentSessionId: "agent_session_1",+ content: {+ body: "Authorization required for Notion Workspace.",+ type: "elicitation",+ },+ signal: "auth",+ signalMetadata: {+ providerName: "Notion Workspace",+ url: "https://connect.example.com/a/sca_1",+ userId: "user_1",+ },+ });+ });++ it("renders URL-less device authorization instructions without an auth signal", async () => {+ const { events, fetch } = buildEvents();++ await events["authorization.required"]!(+ {+ authorization: {+ instructions: "Open Notion on your phone.",+ userCode: "OTB-DGO",+ },+ description: "Authorization required for notion",+ name: "notion",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_0",+ },+ buildChannelStub(),+ sessionContext(),+ );++ expect(activityInput(fetch)).toEqual({+ agentSessionId: "agent_session_1",+ content: {+ body: "Authorization required for Notion.\n\nOpen Notion on your phone.\n\nCode: OTB-DGO",+ type: "elicitation",+ },+ });+ });+});++describe("createDefaultEvents authorization.completed", () => {+ it("posts an ephemeral resuming thought after authorization succeeds", async () => {+ const { events, fetch } = buildEvents();++ await events["authorization.completed"]!(+ {+ authorization: { displayName: "Notion Workspace" },+ name: "notion",+ outcome: "authorized",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_0",+ },+ buildChannelStub(),+ sessionContext(),+ );++ expect(activityInput(fetch)).toEqual({+ agentSessionId: "agent_session_1",+ content: {+ body: "Connected to Notion Workspace. Resuming.",+ type: "thought",+ },+ ephemeral: true,+ });+ });++ it("posts a durable thought when authorization fails", async () => {+ const { events, fetch } = buildEvents();++ await events["authorization.completed"]!(+ {+ name: "notion",+ outcome: "timed-out",+ reason: "The challenge expired",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_0",+ },+ buildChannelStub(),+ sessionContext(),+ );++ expect(activityInput(fetch)).toEqual({+ agentSessionId: "agent_session_1",+ content: {+ body: "Notion authorization timed out (The challenge expired).",+ type: "thought",+ },+ });+ });+});diff --git a/packages/eve/src/public/channels/linear/defaults.ts b/packages/eve/src/public/channels/linear/defaults.tsindex cda371a1c..ec46401d3 100644--- a/packages/eve/src/public/channels/linear/defaults.ts+++ b/packages/eve/src/public/channels/linear/defaults.ts@@ -8,6 +8,7 @@ import {renderLinearInputRequests,} from "#public/channels/linear/hitl.js";import type { LinearAgentSessionEvent, LinearUser } from "#public/channels/linear/inbound.js";+import type { SessionContext } from "#public/definitions/callback-context.js";import type {LinearChannelEvents,LinearInboundResult,@@ -143,6 +144,53 @@ export function createDefaultEvents(options: LinearDefaultEventOptions = {}): Li);},+ async "authorization.required"(event, channel, ctx) {+ const displayName = authorizationDisplayName(event.name, event.authorization?.displayName);+ const url = event.authorization?.url;+ const userId = linearUserId(ctx);+ let authSignal: Parameters<typeof postActivity>[3];+ if (url !== undefined) {+ const signalMetadata: Record<string, string> = { providerName: displayName, url };+ if (userId !== undefined) signalMetadata.userId = userId;+ authSignal = { signal: "auth", signalMetadata };+ }+ await postActivity(+ channel,+ options,+ {+ body: authorizationRequiredBody({+ displayName,+ instructions: event.authorization?.instructions,+ userCode: event.authorization?.userCode,+ }),+ type: "elicitation",+ },+ authSignal,+ );+ },++ async "authorization.completed"(event, channel, _ctx) {+ const displayName = authorizationDisplayName(event.name, event.authorization?.displayName);+ if (event.outcome === "authorized") {+ await postActivity(+ channel,+ options,+ {+ body: `Connected to ${displayName}. Resuming.`,+ type: "thought",+ },+ { ephemeral: true },+ );+ return;+ }++ const reason = event.reason === undefined ? "" : ` (${event.reason})`;+ await postActivity(channel, options, {+ body: `${displayName} authorization ${formatAuthorizationOutcome(event.outcome)}${reason}.`,+ type: "thought",+ });+ },+async "message.completed"(event, channel, _ctx) {if (event.finishReason === "tool-calls") {channel.state.pendingToolCallMessage = event.message@@ -224,6 +272,35 @@ function linearUserLabel(user: LinearUser): string | undefined {return user.displayName ?? user.name ?? user.email;}+function authorizationDisplayName(name: string, displayName: string | undefined): string {+ if (displayName !== undefined) return displayName;+ if (name.length === 0) return name;+ return name.charAt(0).toUpperCase() + name.slice(1);+}++function authorizationRequiredBody(input: {+ readonly displayName: string;+ readonly instructions?: string;+ readonly userCode?: string;+}): string {+ return [+ `Authorization required for ${input.displayName}.`,+ input.instructions,+ input.userCode === undefined ? undefined : `Code: ${input.userCode}`,+ ]+ .filter((part): part is string => part !== undefined && part.length > 0)+ .join("\n\n");+}++function linearUserId(ctx: SessionContext): string | undefined {+ const auth = ctx.session.auth.current;+ return auth?.authenticator === "linear-agent-webhook" ? auth.subject : undefined;+}++function formatAuthorizationOutcome(outcome: "declined" | "failed" | "timed-out"): string {+ return outcome === "timed-out" ? "timed out" : outcome;+}+function firstNonEmptyLine(text: string): string | undefined {for (const line of text.split(/\r?\n/u)) {const trimmed = line.trim();