diff --git a/server/src/__tests__/connection-intents-service.test.ts b/server/src/__tests__/connection-intents-service.test.ts index 43dcc815fc7..d91bc5a8b14 100644 --- a/server/src/__tests__/connection-intents-service.test.ts +++ b/server/src/__tests__/connection-intents-service.test.ts @@ -1,7 +1,7 @@ import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; import { randomUUID } from "node:crypto"; -import { and, eq, sql } from "drizzle-orm"; +import { and, eq, inArray, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, @@ -203,6 +203,33 @@ describeEmbeddedPostgres("connectionIntentService", () => { expect(serialized).not.toContain(claims.sub); }); + it("tells the agent to configure a single match only when the person asked to set it up", async () => { + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const issueId = String(run!.contextSnapshot?.issueId); + const say = (body: string) => db.insert(issueComments).values({ + companyId: claims.company_id, issueId, authorUserId: "responsible-user", body, + createdAt: new Date(Date.now() + 1000), + }).returning().then(rows => rows[0]!); + const said: string[] = []; + try { + for (const body of ["Read my Notion and tell me the latest on the launch.", "What is the easiest way to connect Notion here?", + "Connect Slack, then read my Notion."]) { + said.push((await say(body)).id); + const result = await connectionIntentService(db).search(claims, "Notion"); + expect(result.results).toEqual([expect.objectContaining({ service: "notion", state: "available" })]); + expect(result.instruction).not.toMatch(/^The person asked you to set up/); + expect(result.instruction).toContain("call connection_request with service notion"); + expect(result.instruction).toMatch(/\[Connect Notion\]\(\/[A-Z0-9]+\/apps\/connect\?source=notion\)/); + expect(result.instruction).toContain("Do not create a connection or a saved draft yourself"); + } + said.push((await say("Connect Notion, then continue the launch summary here.")).id); + const requested = await connectionIntentService(db).search(claims, "Notion"); + expect(requested.instruction).toMatch(/^The person asked you to set up this connection\. If method\.management\.allowed, use search_api\/call_api/); + } finally { + await db.delete(issueComments).where(inArray(issueComments.id, said)); + } + }); + it("discovers GitHub review bots independently from chat connectors", async () => { const settings = instanceSettingsService(db); const previous = await settings.getExperimental(); diff --git a/server/src/__tests__/connection-management.integration.test.ts b/server/src/__tests__/connection-management.integration.test.ts index d90a4906d61..4060ec0edd9 100644 --- a/server/src/__tests__/connection-management.integration.test.ts +++ b/server/src/__tests__/connection-management.integration.test.ts @@ -895,7 +895,10 @@ describe("connection management with production default agents", () => { expect(started, JSON.stringify(started)).toMatchObject({ status: 200, body: { expiresAt: null, requiredUserAction: { userId: f.userId, resource: { id: created.body.id } }, } }); - expect(new URL(started.body.authorizationUrl).searchParams.get("resume")).toBe(created.body.id); + // The agent links this in chat, so it is a relative app route, never the server's own origin. + expect(started.body.authorizationUrl).toMatch(/^\/[^/]/); + expect(started.body.requiredUserAction.setupPath).toBe(started.body.authorizationUrl); + expect(new URL(started.body.authorizationUrl, "https://paperclip.example").searchParams.get("resume")).toBe(created.body.id); expect(await f.request("POST", path, { asCurrentUser: true })).toMatchObject({ status: 200, body: { authorizationUrl: started.body.authorizationUrl } }); expect(await server.db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, created.body.id))).toHaveLength(0); }); diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts index f06a3c0e95b..dd3c1c52b0c 100644 --- a/server/src/services/connection-intents.ts +++ b/server/src/services/connection-intents.ts @@ -133,6 +133,10 @@ function availableToolConnectionMethods( // Large enough for first-party catalogs such as GitHub's; aggregator catalogs // stay bounded and still report their total. const MAX_SCOPED_REQUEST_TOOL_NAMES = 100; +// A message that opens with a setup verb, such as "Connect Notion" or "Can you +// set up Slack?". Questions and data requests ("What is the easiest way to +// connect Notion?", "Read my Notion") do not match and get the setup card. +const SETUP_REQUEST_PATTERN = /^(?:please\s+)?(?:(?:can|could|would|will)\s+you\s+(?:please\s+)?)?(?:connect|reconnect|set\s*up|configure|install|link|hook\s+up)\b/i; /** Tells an agent outside a connection's grant how to request scoped access to it. */ function scopedToolRequestGuidance(connectionId: string, catalog: ReadonlyArray<{ toolName: string }>) { @@ -640,9 +644,13 @@ export function connectionIntentService(db: Db) { const ranked = () => [...candidates, ...yieldedRoutes].sort((a, b) => b.score - a.score || a.item.name.localeCompare(b.item.name)) .slice(0, 40).map(({ item }) => item); // Aggregator routes need a recorded provider choice before connection_request. - const rankedResult = (suggestions = false) => { + const rankedResult = async (suggestions = false) => { const results = ranked(); - return results.some(item => item.source === "aggregator") ? discoverySuggestions(results) : directSearchResult(query, results, company.prefix, suggestions); + if (results.some(item => item.source === "aggregator")) return discoverySuggestions(results); + // Only a single unconnected tool result can tell the agent to configure it. + const setupRequested = !suggestions && results.length === 1 + && await latestHumanMessageRequestsSetup(run.companyId, issue.id, run.responsibleUserId!, results[0]!); + return directSearchResult(query, results, company.prefix, suggestions, setupRequested); }; const targetService = publicService?.slug ?? (indexedMatches.length === 1 ? indexedMatches[0]!.slug : normalizeConnectionQuery(serviceQuery).replaceAll(" ", "-")); // Indexed-only app labels must be identical when requests re-search the slug. @@ -753,7 +761,7 @@ export function connectionIntentService(db: Db) { } } - function directSearchResult(query: string, results: ConnectionSearchResultItem[], prefix: string, suggestions = false): ConnectionsSearchResult { + function directSearchResult(query: string, results: ConnectionSearchResultItem[], prefix: string, suggestions = false, setupRequested = false): ConnectionsSearchResult { const ownServer = `the person adds it as their own MCP server on [Connect your own MCP server](/${prefix}/apps/byo): they enter the URL and type any API key into that page's secure field themselves. ` + "An agent cannot enter the key. Do not create the connection yourself, ask for the key in chat or search for another route; link that page and reply."; return { version: 1, query, results, instruction: !results.length @@ -771,7 +779,31 @@ export function connectionIntentService(db: Db) { : results[0]!.methods.every(method => method.purpose && method.purpose !== "tool") ? "Choose the method relevant to the task using its purpose and label. If method.management.allowed, configure through search_api/call_api using nextApiOperation. Hand off only required human authentication or consent at the saved setupPath. These methods do not use the tool connection_request card. Do not claim tools or an inbox are ready before setup finishes." : results[0]!.state === "ready" ? "Use the installed connection. Do not create another connection request." - : "The user asked to connect. If method.management.allowed, use search_api/call_api with nextApiOperation to configure it. Reuse a saved draft. Use connection_request only for required human input or access. Do not ask a generic confirmation or silently change policy to bypass a failed tool call." }; + : setupRequested + ? "The person asked you to set up this connection. If method.management.allowed, use search_api/call_api with nextApiOperation to configure it. Reuse a saved draft. Use connection_request only for required human input or access. Do not ask a generic confirmation or silently change policy to bypass a failed tool call." + : results[0]!.service.startsWith("connection:") + ? `The person has not asked you to set up this connection. Do not create a connection or a saved draft yourself. Call connection_request with service ${results[0]!.service} to show the inline setup card, and until the connection is ready, do not claim access to ${results[0]!.name} or report its data.` + : `The person has not asked you to set up this connection. Do not create a connection or a saved draft yourself. If they asked how to connect ${results[0]!.name} or about its setup options, answer in plain words from these results, naming each method and any prerequisite, and link its setup page as [Connect ${results[0]!.name}](/${prefix}/apps/connect?${new URLSearchParams({ source: results[0]!.service })}); do not call connection_request for that, because its card ends your turn before your answer is shown. If they need ${results[0]!.name} data for their request, call connection_request with service ${results[0]!.service} to show the inline setup card, which lets them connect or decline. Until the connection is ready, do not claim access to ${results[0]!.name} or report its data.` }; + } + + /** Conservative: a false negative only shows the setup card instead of configuring. */ + async function latestHumanMessageRequestsSetup(companyId: string, issueId: string, userId: string, target: Pick) { + // Use a persisted human-authored message, never the agent-supplied query. + const [message] = await db.select({ body: issueComments.body }).from(issueComments).where(and( + eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId), + eq(issueComments.authorUserId, userId), isNull(issueComments.authorAgentId), + isNull(issueComments.createdByRunId), isNull(issueComments.derivedAuthorAgentId), isNull(issueComments.deletedAt), + )).orderBy(desc(issueComments.createdAt), desc(issueComments.id)).limit(1); + if (!message) return false; + // The setup verb must govern this app: "Connect Slack, then read my Notion" + // asks to set up Slack, so a Notion result still gets the setup card. + const clause = message.body.trim().split(/[,.;:!?\n]|\s+(?:then|and|but)\s+/i)[0] ?? ""; + if (!SETUP_REQUEST_PATTERN.test(clause)) return false; + const words = ` ${normalizeConnectionQuery(clause)} `; + return [target.name, target.service].some(name => { + const normalized = normalizeConnectionQuery(name); + return !!normalized && words.includes(` ${normalized} `); + }); } async function providerSelections(companyId: string, issueId: string, agentId: string, userId: string, questionId: string) { diff --git a/server/src/services/tool-access/oauth/authorization-start.ts b/server/src/services/tool-access/oauth/authorization-start.ts index 1dba7077479..77488796912 100644 --- a/server/src/services/tool-access/oauth/authorization-start.ts +++ b/server/src/services/tool-access/oauth/authorization-start.ts @@ -213,13 +213,13 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies } const [company] = await db.select({ prefix: companies.issuePrefix }).from(companies).where(eq(companies.id, companyId)); if (!company) throw notFound("Company not found"); - const destination = new URL(input.redirectUri); - destination.pathname = `/${encodeURIComponent(company.prefix)}/apps/${connection.credentialSource === "vercel_connect" ? "vercel-connect" : "connect"}`; - destination.search = new URLSearchParams({ [connection.status === "draft" ? "resume" : "reconnect"]: connection.id, - ...(sourceTemplateKey ? { source: sourceTemplateKey } : {}), ...(intentLink ? { intent: intentLink.id } : {}) }).toString(); - destination.hash = ""; + // A relative app route: the agent links it in chat, where it opens on + // whichever host the person uses, never the server's own listen address. + const destination = `/${encodeURIComponent(company.prefix)}/apps/${connection.credentialSource === "vercel_connect" ? "vercel-connect" : "connect"}?${new URLSearchParams({ + [connection.status === "draft" ? "resume" : "reconnect"]: connection.id, + ...(sourceTemplateKey ? { source: sourceTemplateKey } : {}), ...(intentLink ? { intent: intentLink.id } : {}) })}`; return { connectionId: connection.id, provider: sourceTemplateKey ?? "oauth", - authorizationUrl: destination.toString(), expiresAt: null }; + authorizationUrl: destination, expiresAt: null }; } if (sourceTemplateKey === "google-workspace" && connection.status === "draft") { const workspaceSetup = { version: 1, ...workspaceDraftBinding, requestedScopes };