Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/apps/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
7 changes: 7 additions & 0 deletions packages/apps/src/app.options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
114 changes: 109 additions & 5 deletions packages/apps/src/app.spec.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 });
});

Expand All @@ -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<void>((resolve) => { releaseFirst = resolve; });
let firstStarted!: () => void;
const started = new Promise<void>((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;

Expand Down Expand Up @@ -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' });
});

Expand Down
6 changes: 5 additions & 1 deletion packages/apps/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,7 @@ export class App<TPlugin extends IPlugin = IPlugin> {
*
* @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<SentActivity>;
/**
Expand All @@ -513,6 +514,7 @@ export class App<TPlugin extends IPlugin = IPlugin> {
*
* @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,
Expand Down Expand Up @@ -541,6 +543,7 @@ export class App<TPlugin extends IPlugin = IPlugin> {
* @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 `..`)
*/
Expand All @@ -555,6 +558,7 @@ export class App<TPlugin extends IPlugin = IPlugin> {
* @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 `..`)
*/
Expand Down Expand Up @@ -913,7 +917,7 @@ export class App<TPlugin extends IPlugin = IPlugin> {

const ref: ConversationReference = {
channelId: 'msteams',
serviceUrl: this.api.serviceUrl,
serviceUrl: options?.serviceUrl ?? this.api.serviceUrl,
bot: {
id: this.id,
role: 'bot',
Expand Down
12 changes: 6 additions & 6 deletions packages/apps/src/contexts/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,23 +251,23 @@ export interface IBaseActivityContext<T extends Activity = Activity, TExtraCtx e
* @param conversationRef conversation reference to send to
* @deprecated Passing a `DeprecatedInputActivity` is deprecated. Use MessageActivityInput or TypingActivityInput instead.
* Passing a conversation reference is also deprecated and will be removed in a future release. Use `App.send()` to send to a different conversation.
* `App.send()` sends through the `serviceUrl` the app is configured with, unlike the context methods, which use the `serviceUrl` of the conversation reference (by default, the inbound activity's).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we update the docs and relevant samples as well so that we can compare this PR to what we're saying in the docs? Of course, this PR will have to go in first, then release and then the docs update will get published, right?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for the docs PR from Adrian: "Please remember to update the version requirement in the doc."

* `App.send()` uses `options.serviceUrl` or the app's configured URL. Context methods use the conversation reference's `serviceUrl` (by default, the inbound activity's).
*/
send(activity: DeprecatedInputActivity, conversationRef?: ConversationReference): Promise<SentActivity>;
/**
* send an activity to the conversation referenced by `conversationRef`
* @param activity activity to send
* @param conversationRef conversation reference to send to
* @deprecated Passing a conversation reference is deprecated and will be removed in a future release. Use `App.send()` to send to a different conversation.
* `App.send()` sends through the `serviceUrl` the app is configured with, unlike the context methods, which use the `serviceUrl` of the conversation reference (by default, the inbound activity's).
* `App.send()` uses `options.serviceUrl` or the app's configured URL. Context methods use the conversation reference's `serviceUrl` (by default, the inbound activity's).
*/
send(activity: ActivityLike, conversationRef?: ConversationReference): Promise<SentActivity>;
/**
* send an activity to the conversation referenced by `conversationRef`
* @param activity activity to send
* @param conversationRef conversation reference to send to
* @deprecated Passing a conversation reference is deprecated and will be removed in a future release. Use `App.send()` to send to a different conversation.
* `App.send()` sends through the `serviceUrl` the app is configured with, unlike the context methods, which use the `serviceUrl` of the conversation reference (by default, the inbound activity's).
* `App.send()` uses `options.serviceUrl` or the app's configured URL. Context methods use the conversation reference's `serviceUrl` (by default, the inbound activity's).
*/
send(activity: ActivityLike | DeprecatedInputActivity, conversationRef?: ConversationReference): Promise<SentActivity>;

Expand Down Expand Up @@ -516,7 +516,7 @@ export class ActivityContext<T extends Activity = Activity, TExtraCtx extends {}
* @param conversationRef conversation reference to send to
* @deprecated Passing a `DeprecatedInputActivity` is deprecated. Use MessageActivityInput or TypingActivityInput instead.
* Passing a conversation reference is also deprecated and will be removed in a future release. Use `App.send()` to send to a different conversation.
* `App.send()` sends through the `serviceUrl` the app is configured with, unlike the context methods, which use the `serviceUrl` of the conversation reference (by default, the inbound activity's).
* `App.send()` uses `options.serviceUrl` or the app's configured URL. Context methods use the conversation reference's `serviceUrl` (by default, the inbound activity's).
*/
async send(activity: DeprecatedInputActivity, conversationRef?: ConversationReference): Promise<SentActivity>;
/**
Expand All @@ -525,7 +525,7 @@ export class ActivityContext<T extends Activity = Activity, TExtraCtx extends {}
* @param activity the activity to send
* @param conversationRef conversation reference to send to
* @deprecated Passing a conversation reference is deprecated and will be removed in a future release. Use `App.send()` to send to a different conversation.
* `App.send()` sends through the `serviceUrl` the app is configured with, unlike the context methods, which use the `serviceUrl` of the conversation reference (by default, the inbound activity's).
* `App.send()` uses `options.serviceUrl` or the app's configured URL. Context methods use the conversation reference's `serviceUrl` (by default, the inbound activity's).
*/
async send(activity: ActivityLike, conversationRef?: ConversationReference): Promise<SentActivity>;
/**
Expand All @@ -534,7 +534,7 @@ export class ActivityContext<T extends Activity = Activity, TExtraCtx extends {}
* @param activity the activity to send
* @param conversationRef conversation reference to send to
* @deprecated Passing a conversation reference is deprecated and will be removed in a future release. Use `App.send()` to send to a different conversation.
* `App.send()` sends through the `serviceUrl` the app is configured with, unlike the context methods, which use the `serviceUrl` of the conversation reference (by default, the inbound activity's).
* `App.send()` uses `options.serviceUrl` or the app's configured URL. Context methods use the conversation reference's `serviceUrl` (by default, the inbound activity's).
*/
async send(activity: ActivityLike | DeprecatedInputActivity, conversationRef?: ConversationReference): Promise<SentActivity>;
async send(activity: ActivityLike | DeprecatedInputActivity, conversationRef?: ConversationReference) {
Expand Down
Loading