From bbbecbc9ddaf497b4e7bf297b67df799cf712f66 Mon Sep 17 00:00:00 2001 From: Alex Acebo Date: Wed, 18 Nov 2026 10:49:54 -0800 Subject: [PATCH] add optional serviceUrl to send options --- packages/apps/README.md | 18 ++++ packages/apps/src/app.options.ts | 7 ++ packages/apps/src/app.spec.ts | 114 +++++++++++++++++++++++-- packages/apps/src/app.ts | 6 +- packages/apps/src/contexts/activity.ts | 12 +-- 5 files changed, 145 insertions(+), 12 deletions(-) diff --git a/packages/apps/README.md b/packages/apps/README.md index 55747f10b..62dff5f9b 100644 --- a/packages/apps/README.md +++ b/packages/apps/README.md @@ -82,6 +82,24 @@ main().catch(console.error); See the [HTTP adapter examples](https://github.com/microsoft/teams.ts/tree/main/examples/http-adapters) for framework integration samples. +## Proactive messaging + +Pass `serviceUrl` in the existing send or reply options to route an individual +proactive activity to the Teams backend service URL for its conversation. + +```ts +await app.send(conversationId, 'Proactive notification', { serviceUrl }); + +// Use channelData.chat.id or channelData.channel.id for chatOrChannelId, +// and channelData.replyChain.id for rootMessageId. +await app.reply(chatOrChannelId, rootMessageId, 'Threaded reply', { serviceUrl }); +``` + +Omitting `serviceUrl` or passing `undefined` uses the app's configured service URL. +An override affects only that call, including when calls overlap; it does not +change `app.api.serviceUrl` or remember inbound service URLs. You can combine +`serviceUrl` with `agenticIdentity` in the same options object. + ## Examples See the [examples folder](https://github.com/microsoft/teams.ts/tree/main/examples) for agents, tabs, message extensions, proactive messaging, Graph, AI/MCP, A2A, and more. diff --git a/packages/apps/src/app.options.ts b/packages/apps/src/app.options.ts index 0461a9540..dcbcf0803 100644 --- a/packages/apps/src/app.options.ts +++ b/packages/apps/src/app.options.ts @@ -23,6 +23,13 @@ import type { IPlugin } from './types'; * Options for proactive app sends and replies. */ export type AppSendOptions = { + /** + * Teams backend service URL to use for this proactive send or reply only. + * Omit or use `undefined` to use the app's configured service URL. + * Does not change the app's API client or the URL used by other calls. + */ + readonly serviceUrl?: string; + /** * Agentic identity scope to use when acquiring tokens for this send. */ diff --git a/packages/apps/src/app.spec.ts b/packages/apps/src/app.spec.ts index 63203ebcc..f33489c7b 100644 --- a/packages/apps/src/app.spec.ts +++ b/packages/apps/src/app.spec.ts @@ -1,4 +1,5 @@ import { ConfidentialClientApplication } from '@azure/msal-node'; +import axios, { InternalAxiosRequestConfig } from 'axios'; import jwt from 'jsonwebtoken'; import { CHINA, JsonWebToken, MessageActivity, PUBLIC, US_GOV, US_GOV_DOD, withOverrides } from '@microsoft/teams.api'; @@ -412,14 +413,14 @@ describe('App', () => { const mockSend = jest.fn().mockResolvedValue({ id: 'activity-id' }); jest.spyOn(app.testActivitySender, 'send').mockImplementation(mockSend); - await app.testSend( + await app.send( 'conversation-id', { type: 'message', text: 'Hello' }, - { agenticIdentity } + { agenticIdentity, serviceUrl: 'https://custom.service.url/teams' } ); const [, ref, options] = mockSend.mock.calls[0]; - expect(ref.serviceUrl).toBe(app.api.serviceUrl); + expect(ref.serviceUrl).toBe('https://custom.service.url/teams'); expect(options).toEqual({ agenticIdentity }); }); @@ -436,6 +437,105 @@ describe('App', () => { }); }); + describe('proactive service URL', () => { + const defaultUrl = 'https://default.service.url/teams'; + const serviceUrl = 'https://custom.service.url/teams'; + let app: App; + let adapter: jest.Mock; + + beforeEach(() => { + adapter = jest.fn(async (config: InternalAxiosRequestConfig) => ({ + config, headers: {}, status: 200, statusText: 'OK', + data: { id: 'activity-id' }, + })); + jest.replaceProperty(axios.defaults, 'adapter', adapter); + app = new App({ + httpServerAdapter: new TestAdapter(), + clientId: 'test-client-id', + serviceUrl: defaultUrl, + }); + jest.spyOn(app.tokenProvider, 'getAppToken').mockResolvedValue(null); + }); + + afterEach(async () => { + await app.stop(); + jest.restoreAllMocks(); + }); + + it('sends and updates through the scoped client without adding serviceUrl to the payload', async () => { + await app.send('conversation-id', 'Hello', { serviceUrl }); + await app.send('conversation-id', new MessageActivity('Updated').withId('existing-id'), { serviceUrl }); + + expect(adapter).toHaveBeenCalledTimes(2); + expect(adapter.mock.calls[0][0]).toMatchObject({ + method: 'post', + url: `${serviceUrl}/v3/conversations/conversation-id/activities`, + }); + expect(adapter.mock.calls[1][0]).toMatchObject({ + method: 'put', + url: `${serviceUrl}/v3/conversations/conversation-id/activities/existing-id`, + }); + for (const [config] of adapter.mock.calls) { + expect(JSON.parse(config.data)).not.toHaveProperty('serviceUrl'); + } + }); + + it('uses the override for threaded and legacy replies without confusing string activities with message IDs', async () => { + await app.reply('conversation-id', 'root-id', 'Threaded', { serviceUrl }); + await app.reply('conversation-id', 'Legacy string', { serviceUrl }); + + expect(adapter.mock.calls.map(([config]) => ({ + method: config.method, + url: config.url, + text: JSON.parse(config.data).text, + }))).toEqual([ + { method: 'post', url: `${serviceUrl}/v3/conversations/conversation-id/replyChains/root-id`, text: 'Threaded' }, + { method: 'post', url: `${serviceUrl}/v3/conversations/conversation-id/activities`, text: 'Legacy string' }, + ]); + }); + + it.each([undefined, { serviceUrl: undefined }])('preserves the configured fallback with options %j', async (options) => { + await app.send('conversation-id', 'Send', options); + await app.reply('conversation-id', 'root-id', 'Threaded', options); + await app.reply('conversation-id', 'Legacy', options); + + expect(adapter.mock.calls.map(([config]) => config.url)).toEqual([ + `${defaultUrl}/v3/conversations/conversation-id/activities`, + `${defaultUrl}/v3/conversations/conversation-id/replyChains/root-id`, + `${defaultUrl}/v3/conversations/conversation-id/activities`, + ]); + }); + + it('isolates overlapping overrides and subsequent calls using the configured URL', async () => { + let releaseFirst!: () => void; + const firstPending = new Promise((resolve) => { releaseFirst = resolve; }); + let firstStarted!: () => void; + const started = new Promise((resolve) => { firstStarted = resolve; }); + adapter.mockImplementationOnce(async (config: InternalAxiosRequestConfig) => { + firstStarted(); + await firstPending; + return { config, headers: {}, status: 200, statusText: 'OK', data: { id: 'first-id' } }; + }); + + const first = app.send('conversation-id', 'First', { serviceUrl }); + await started; + try { + await app.send('conversation-id', 'Second', { serviceUrl: 'https://other.service.url/teams' }); + await app.send('conversation-id', 'Default'); + + expect(adapter.mock.calls.map(([config]) => config.url)).toEqual([ + `${serviceUrl}/v3/conversations/conversation-id/activities`, + 'https://other.service.url/teams/v3/conversations/conversation-id/activities', + `${defaultUrl}/v3/conversations/conversation-id/activities`, + ]); + expect(app.api.serviceUrl).toBe(defaultUrl); + } finally { + releaseFirst(); + await first; + } + }); + }); + describe('proactive messaging (initialize without start)', () => { let app: TestApp; @@ -789,9 +889,13 @@ describe('App', () => { jest.spyOn(app.testActivitySender, 'send').mockImplementation(mockSend); const agenticIdentity = { agenticAppBlueprintId: 'bp', agenticAppId: 'app', agenticUserId: 'user', tenantId: 'tenant' }; - await (app as any).reply('19:abc@thread.skype', '123', { type: 'message', text: 'Hello' }, { agenticIdentity }); + await app.reply('19:abc@thread.skype', '123', { type: 'message', text: 'Hello' }, { + agenticIdentity, + serviceUrl: 'https://custom.service.url/teams', + }); - const [, , options] = mockSend.mock.calls[0]; + const [, ref, options] = mockSend.mock.calls[0]; + expect(ref.serviceUrl).toBe('https://custom.service.url/teams'); expect(options).toEqual({ agenticIdentity, replyChainId: '123' }); }); diff --git a/packages/apps/src/app.ts b/packages/apps/src/app.ts index 8d30cad86..835936b10 100644 --- a/packages/apps/src/app.ts +++ b/packages/apps/src/app.ts @@ -503,6 +503,7 @@ export class App { * * @param conversationId the conversation to send to * @param activity the activity to send + * @param options per-call service URL and agentic identity overrides; the service URL defaults to the app's configured URL */ async send(conversationId: string, activity: ActivityLike, options?: AppSendOptions): Promise; /** @@ -513,6 +514,7 @@ export class App { * * @param conversationId the conversation to send to * @param activity the activity to send + * @param options per-call service URL and agentic identity overrides; the service URL defaults to the app's configured URL */ async send( conversationId: string, @@ -541,6 +543,7 @@ export class App { * @param conversationId the id of the chat or channel: `channelData.chat.id` or `channelData.channel.id`, **not** `conversation.id`. * @param messageId the id of the message at the root of the reply chain: `channelData.replyChain.id` * @param activity the activity to send + * @param options per-call service URL and agentic identity overrides; the service URL defaults to the app's configured URL * @throws Error when `conversationId` or `messageId` is empty or blank * @throws Error when `conversationId` or `messageId` is a dot segment (`.` or `..`) */ @@ -555,6 +558,7 @@ export class App { * @param conversationId the id of the chat or channel: `channelData.chat.id` or `channelData.channel.id`, **not** `conversation.id`. * @param messageId the id of the message at the root of the reply chain: `channelData.replyChain.id` * @param activity the activity to send + * @param options per-call service URL and agentic identity overrides; the service URL defaults to the app's configured URL * @throws Error when `conversationId` or `messageId` is empty or blank * @throws Error when `conversationId` or `messageId` is a dot segment (`.` or `..`) */ @@ -913,7 +917,7 @@ export class App { const ref: ConversationReference = { channelId: 'msteams', - serviceUrl: this.api.serviceUrl, + serviceUrl: options?.serviceUrl ?? this.api.serviceUrl, bot: { id: this.id, role: 'bot', diff --git a/packages/apps/src/contexts/activity.ts b/packages/apps/src/contexts/activity.ts index cd00e039b..a3ba0500d 100644 --- a/packages/apps/src/contexts/activity.ts +++ b/packages/apps/src/contexts/activity.ts @@ -251,7 +251,7 @@ export interface IBaseActivityContext; /** @@ -259,7 +259,7 @@ export interface IBaseActivityContext; /** @@ -267,7 +267,7 @@ export interface IBaseActivityContext; @@ -516,7 +516,7 @@ export class ActivityContext; /** @@ -525,7 +525,7 @@ export class ActivityContext; /** @@ -534,7 +534,7 @@ export class ActivityContext; async send(activity: ActivityLike | DeprecatedInputActivity, conversationRef?: ConversationReference) {