teams_rb 2.0.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +39 -1
  3. data/docs/README.md +1 -1
  4. data/docs/essentials/README.md +1 -1
  5. data/docs/essentials/on-event.md +12 -2
  6. data/docs/essentials/sending-messages.md +7 -4
  7. data/docs/in-depth-guides/README.md +2 -0
  8. data/docs/in-depth-guides/agent-365.md +3 -1
  9. data/docs/in-depth-guides/files.md +99 -0
  10. data/docs/in-depth-guides/state.md +59 -0
  11. data/docs/in-depth-guides/streaming.md +6 -5
  12. data/docs/in-depth-guides/user-authentication.md +36 -8
  13. data/lib/teams/activity_context.rb +118 -15
  14. data/lib/teams/api/citation_appearance.rb +10 -2
  15. data/lib/teams/api/file_download_info.rb +34 -0
  16. data/lib/teams/api/message_activity.rb +37 -12
  17. data/lib/teams/api/sensitivity_usage_info.rb +38 -0
  18. data/lib/teams/app.rb +195 -153
  19. data/lib/teams/auth/jwt_validator.rb +17 -2
  20. data/lib/teams/cards/generated.rb +430 -430
  21. data/lib/teams/errors.rb +175 -4
  22. data/lib/teams/files/downloaded_file.rb +35 -0
  23. data/lib/teams/files/downloader.rb +405 -0
  24. data/lib/teams/files/files_accessor.rb +175 -0
  25. data/lib/teams/files/graph_share.rb +44 -0
  26. data/lib/teams/files/incoming_file.rb +128 -0
  27. data/lib/teams/files/inline_image.rb +88 -0
  28. data/lib/teams/files.rb +8 -0
  29. data/lib/teams/http_stream.rb +28 -28
  30. data/lib/teams/oauth/flow.rb +184 -0
  31. data/lib/teams/oauth/handlers.rb +376 -0
  32. data/lib/teams/oauth/pending_sign_ins.rb +300 -0
  33. data/lib/teams/oauth.rb +5 -0
  34. data/lib/teams/state/turn_state.rb +163 -0
  35. data/lib/teams/state/turn_state_container.rb +54 -0
  36. data/lib/teams/state/turn_state_loader.rb +143 -0
  37. data/lib/teams/state.rb +5 -0
  38. data/lib/teams/version.rb +1 -1
  39. data/lib/teams.rb +5 -0
  40. metadata +20 -1
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Teams
4
+ module Files
5
+ # The uploaded files on the current inbound activity, exposed as
6
+ # ctx.files: a filter over the raw activity attachments, mirroring the
7
+ # TypeScript, Python, and .NET FilesAccessor.
8
+ #
9
+ # Uploaded files arrive as file.download.info attachments carrying file
10
+ # metadata, not bytes. Each becomes an IncomingFile; everything else
11
+ # (cards, mentions, other content) and malformed file entries are
12
+ # skipped, never raised. Listing makes no network requests. What matters
13
+ # is how the content arrived, not its MIME type, so any file type sent as
14
+ # an uploaded file is listed. The original attachment stays on
15
+ # IncomingFile#raw.
16
+ class FilesAccessor
17
+ # credential is the turn's Files::GraphCredential, used for files that
18
+ # arrive with only a content URL (agentic users); bot_api_credential the
19
+ # Files::BotApiCredential that reads pasted inline images.
20
+ def initialize(activity, downloader:, credential: nil, bot_api_credential: nil, logger: nil)
21
+ @activity = activity
22
+ @downloader = downloader
23
+ @credential = credential
24
+ @bot_api_credential = bot_api_credential
25
+ @logger = logger
26
+ end
27
+
28
+ # The uploaded files and pasted inline images on the activity.
29
+ # attachment_style: "file" or "inlineImage" filters by how each was
30
+ # attached. An inline image not hosted under the activity's service URL
31
+ # is skipped with a warning.
32
+ def list(attachment_style: nil)
33
+ return [] unless @activity.message?
34
+
35
+ scope = detect_scope
36
+ items = attachments
37
+ hints = attachment_style == "file" ? {} : inline_image_hints(items)
38
+ items.each_with_index.filter_map do |attachment, index|
39
+ image_id = inline_image_id(attachment)
40
+ # Checked before mapping, so an excluded style is never mapped and
41
+ # never logs.
42
+ next if attachment_style && attachment_style != (image_id ? "inlineImage" : "file")
43
+
44
+ if image_id
45
+ to_inline_image(attachment, image_id, index, scope, hints)
46
+ else
47
+ to_incoming_file(attachment, index, scope)
48
+ end
49
+ end
50
+ end
51
+
52
+ # The first listed file, or nil.
53
+ def first(attachment_style: nil)
54
+ list(attachment_style:).first
55
+ end
56
+
57
+ private
58
+
59
+ def attachments
60
+ Array(@activity.raw["attachments"]).select { |attachment| attachment.is_a?(Hash) }
61
+ end
62
+
63
+ def detect_scope
64
+ @activity.conversation&.conversation_type || "personal"
65
+ end
66
+
67
+ # Format hints for inline images, keyed by attachment id, from the
68
+ # message's HTML attachments.
69
+ def inline_image_hints(items)
70
+ items.each_with_object({}) do |attachment, hints|
71
+ next unless attachment["contentType"] == "text/html" && attachment["content"].is_a?(String)
72
+
73
+ hints.merge!(InlineImage.parse_hints(attachment["content"]))
74
+ end
75
+ end
76
+
77
+ # The inline image id when the attachment is an image/* at a Bot API
78
+ # inline image path, otherwise nil.
79
+ def inline_image_id(attachment)
80
+ content_type = attachment["contentType"]
81
+ content_url = attachment["contentUrl"]
82
+ return nil unless content_type.is_a?(String) && content_type.downcase.start_with?("image/")
83
+ return nil unless content_url.is_a?(String)
84
+
85
+ InlineImage.image_id(content_url)
86
+ end
87
+
88
+ def to_inline_image(attachment, id, index, scope, hints)
89
+ content_url = attachment["contentUrl"]
90
+ unless Downloader.under_service_url?(content_url, @activity.service_url)
91
+ @logger&.warn(
92
+ "files: skipping inline image attachment at index #{index}; its location is not on the activity's service URL"
93
+ )
94
+ return nil
95
+ end
96
+
97
+ hint = hints[id]
98
+ format = hint ? InlineImage.format_from_hint(hint) : InlineImage.format_from_content_type(attachment["contentType"])
99
+ base_name = "image-#{id}"
100
+ naming = InlineImage.naming(base_name, format)
101
+
102
+ IncomingFile.new(
103
+ name: naming.name,
104
+ content_type: naming.content_type,
105
+ extension: naming.extension,
106
+ scope:,
107
+ source: "botActivity",
108
+ attachment_style: "inlineImage",
109
+ content_url:,
110
+ raw: attachment,
111
+ inline_image_base_name: base_name,
112
+ downloader: @downloader,
113
+ bot_api_credential: @bot_api_credential
114
+ )
115
+ end
116
+
117
+ def to_incoming_file(attachment, index, scope)
118
+ return nil unless attachment["contentType"] == Api::FILE_DOWNLOAD_INFO_CONTENT_TYPE
119
+
120
+ content = coerce_content(attachment["content"])
121
+ download_url = string_or_nil(content&.download_url)
122
+ content_url = string_or_nil(attachment["contentUrl"])
123
+ name = string_or_nil(attachment["name"])
124
+
125
+ # A download URL is fetched directly. A content URL without one is the
126
+ # agentic user shape (content that parsed and declares no downloadUrl
127
+ # at all) and resolves through Graph where the route is open; a
128
+ # broken attachment is never spent on a Graph credential.
129
+ agentic_shape = content && !attachment["content"].key?("downloadUrl")
130
+ graph_fetchable = agentic_shape && content_url &&
131
+ Downloader.graph_route_open?(scope, @credential&.actor)
132
+
133
+ if name.nil? || !(download_url || graph_fetchable)
134
+ if name.nil? || !(download_url || content_url)
135
+ missing = name.nil? ? "name" : "a download or content URL"
136
+ @logger&.warn("files: skipping file.download.info attachment at index #{index}; missing #{missing}")
137
+ else
138
+ @logger&.debug(
139
+ "files: skipping file.download.info attachment at index #{index}; " \
140
+ "'#{scope}' scope files are not fetchable yet"
141
+ )
142
+ end
143
+ return nil
144
+ end
145
+
146
+ IncomingFile.new(
147
+ name:,
148
+ scope:,
149
+ source: "botActivity",
150
+ attachment_style: "file",
151
+ unique_id: content&.unique_id,
152
+ extension: content&.file_type,
153
+ content_url:,
154
+ raw: attachment,
155
+ download_url:,
156
+ downloader: @downloader,
157
+ credential: @credential
158
+ )
159
+ end
160
+
161
+ # Wrong-typed fields are dropped one at a time rather than rejecting the
162
+ # whole object, like the Python SDK: unique_id and file_type are
163
+ # metadata, and failing on one must not drop a usable download URL.
164
+ def coerce_content(content)
165
+ return nil unless content.is_a?(Hash)
166
+
167
+ Api::FileDownloadInfo.new(content.select { |_key, value| value.nil? || value.is_a?(String) })
168
+ end
169
+
170
+ def string_or_nil(value)
171
+ value.is_a?(String) && !value.empty? ? value : nil
172
+ end
173
+ end
174
+ end
175
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "uri"
5
+
6
+ module Teams
7
+ module Files
8
+ # Microsoft Graph /shares addressing for drive items reached by their
9
+ # sharing URL, like the TypeScript, Python, and .NET SDKs.
10
+ module GraphShare
11
+ LOOPBACK_HOSTS = %w[localhost 127.0.0.1 ::1 [::1]].freeze
12
+
13
+ module_function
14
+
15
+ # Graph's sharing-token encoding: base64url without padding, prefixed
16
+ # with "u!".
17
+ def encode_sharing_url(url)
18
+ "u!#{Base64.urlsafe_encode64(url.encode("UTF-8"), padding: false)}"
19
+ end
20
+
21
+ # The Graph endpoint that streams a drive item's bytes. base_url_root is
22
+ # a host root such as https://graph.microsoft.com; the API version is
23
+ # appended here. The request carries a bearer token, so the root must be
24
+ # https (loopback http stays allowed for a local mock Graph).
25
+ def drive_item_content_url(sharing_url, base_url_root = "https://graph.microsoft.com")
26
+ unless safe_graph_root?(base_url_root)
27
+ raise Error, "cannot fetch file bytes through Graph: the Graph host root must use https, got " \
28
+ "#{base_url_root.inspect}. This request carries a bearer token, so a cleartext root would put it on the wire."
29
+ end
30
+
31
+ "#{base_url_root.chomp("/")}/v1.0/shares/#{encode_sharing_url(sharing_url)}/driveItem/content"
32
+ end
33
+
34
+ def safe_graph_root?(root)
35
+ uri = URI.parse(root.to_s)
36
+ return true if uri.scheme == "https"
37
+
38
+ uri.scheme == "http" && LOOPBACK_HOSTS.include?(uri.host)
39
+ rescue URI::Error
40
+ false
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Teams
4
+ module Files
5
+ # A lazy handle to a file attached to the current inbound activity,
6
+ # mirroring the TypeScript, Python, and .NET IncomingFile.
7
+ #
8
+ # Nothing is downloaded until a byte method is called, and no bytes are
9
+ # memoized: each of stream/download/text/save_as fetches afresh. For a
10
+ # personal file that re-fetch is bounded by the short-lived download URL;
11
+ # to read the same file several ways, call download once and reuse the
12
+ # returned DownloadedFile.
13
+ class IncomingFile
14
+ # name: display name including extension when known.
15
+ # scope: the conversation type the file arrived in ("personal", ...).
16
+ # source: where the SDK found the file; only "botActivity" today.
17
+ # attachment_style: "file" (sent as a file attachment) or "inlineImage"
18
+ # (pasted into the message; named "image-<attachment id>" with an
19
+ # extension only for PNG, JPEG, GIF, or WebP; content_url is then its
20
+ # Bot API location).
21
+ # unique_id: the OneDrive/ODSP identifier when reported (for
22
+ # correlation and logging, not retrieval).
23
+ # content_type: the file's MIME type when the source provides one;
24
+ # always nil for file attachments, which carry only the extension.
25
+ # DownloadedFile#content_type is resolved from the download response.
26
+ # extension: extension without the dot, from the platform's fileType.
27
+ # content_url: browsable link to the file in OneDrive/SharePoint, as
28
+ # sent on the attachment; not fetchable for bytes, but the locator a
29
+ # Graph /shares read keys off (the agentic user route).
30
+ # raw: the original attachment hash.
31
+ attr_reader :name, :scope, :source, :attachment_style, :unique_id, :content_type, :extension,
32
+ :content_url, :raw
33
+
34
+ def initialize(name:, scope:, source:, downloader:, unique_id: nil, content_type: nil, extension: nil,
35
+ attachment_style: "file", content_url: nil, raw: nil, download_url: nil, credential: nil,
36
+ bot_api_credential: nil, inline_image_base_name: nil)
37
+ @name = name
38
+ @scope = scope
39
+ @source = source
40
+ @unique_id = unique_id
41
+ @content_type = content_type
42
+ @extension = extension
43
+ @attachment_style = attachment_style
44
+ @content_url = content_url
45
+ @raw = raw
46
+ @download_url = download_url
47
+ @downloader = downloader
48
+ @credential = credential
49
+ @bot_api_credential = bot_api_credential
50
+ @inline_image_base_name = inline_image_base_name
51
+ @prior_fetch_succeeded = false
52
+ end
53
+
54
+ # Yields the response body chunks as they arrive, single-consumption and
55
+ # not buffered. Returns an Enumerator without a block.
56
+ def stream(&block)
57
+ return enum_for(:stream) unless block
58
+
59
+ fetch(&block)
60
+ nil
61
+ end
62
+
63
+ # Fetches the whole file into a DownloadedFile snapshot. Not memoized:
64
+ # calling again re-fetches.
65
+ def download
66
+ data = +"".b
67
+ opened = fetch { |chunk| data << chunk }
68
+ filename, content_type = downloaded_type(data, opened.content_type)
69
+ DownloadedFile.new(bytes: data, content_type:, filename:, source_url: opened.source_url)
70
+ end
71
+
72
+ # download, then decode (UTF-8 by default, lossy). Re-fetches each call.
73
+ def text(encoding = Encoding::UTF_8)
74
+ download.text(encoding)
75
+ end
76
+
77
+ # Streams the bytes straight to a local path without buffering the
78
+ # file in memory. The file is only created once the fetch succeeds.
79
+ def save_as(path)
80
+ file = nil
81
+ fetch { |chunk| (file ||= File.open(path, "wb")).write(chunk) }
82
+ File.binwrite(path, "") unless file
83
+ nil
84
+ ensure
85
+ file&.close
86
+ end
87
+
88
+ private
89
+
90
+ def fetch(&on_chunk)
91
+ opened = @downloader.fetch(
92
+ target,
93
+ prior_fetch_succeeded: @prior_fetch_succeeded,
94
+ credential: @credential,
95
+ bot_api_credential: @bot_api_credential,
96
+ &on_chunk
97
+ )
98
+ @prior_fetch_succeeded = true
99
+ opened
100
+ end
101
+
102
+ # For an inline image, recognized bytes decide the name and type, then
103
+ # the listing's: Teams can return a different format from the hint (a
104
+ # pasted GIF downloads as a static PNG).
105
+ def downloaded_type(data, response_content_type)
106
+ return [name, response_content_type] unless attachment_style == "inlineImage"
107
+
108
+ sniffed = InlineImage.sniff_format(data)
109
+ if sniffed && @inline_image_base_name
110
+ naming = InlineImage.naming(@inline_image_base_name, sniffed)
111
+ return [naming.name, naming.content_type]
112
+ end
113
+
114
+ [name, content_type || InlineImage::OCTET_STREAM]
115
+ end
116
+
117
+ def target
118
+ FetchTarget.new(
119
+ scope:,
120
+ download_url: @download_url,
121
+ content_url:,
122
+ content_type:,
123
+ attachment_style:
124
+ )
125
+ end
126
+ end
127
+ end
128
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Teams
6
+ module Files
7
+ # Helpers for images pasted inline into a message, like the TypeScript,
8
+ # Python, and .NET SDKs. Teams hosts them on the Bot API and describes
9
+ # each in the message's HTML with a format hint.
10
+ module InlineImage
11
+ # The formats the SDK names and types. GIF is listed as .gif/image/gif
12
+ # but Teams saves a pasted GIF as a static PNG; other formats (BMP,
13
+ # AVIF, ...) get no extension and application/octet-stream.
14
+ FORMATS = {
15
+ "png" => ["png", "image/png"],
16
+ "jpeg" => ["jpg", "image/jpeg"],
17
+ "gif" => ["gif", "image/gif"],
18
+ "webp" => ["webp", "image/webp"]
19
+ }.freeze
20
+ OCTET_STREAM = "application/octet-stream"
21
+ AMS_IMAGE_ITEMTYPE = "http://schema.skype.com/AMSImage"
22
+ # The path of a Bot API-hosted inline image, capturing its attachment
23
+ # id. The id becomes part of the file name, so it is limited to
24
+ # characters that keep path separators out.
25
+ PATH = %r{/v3/attachments/([A-Za-z0-9_.-]+)/views/original\z}i
26
+ IMG_TAG = /<img\b(?:[^<>"']|"[^"]*"|'[^']*')*>/i
27
+ ATTRIBUTE = /(?<![A-Za-z0-9_-])([A-Za-z0-9_-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/
28
+ IMAGE_CONTENT_TYPE = %r{\Aimage/([A-Za-z0-9_.+-]+)}i
29
+
30
+ Naming = Struct.new(:name, :extension, :content_type, keyword_init: true)
31
+
32
+ module_function
33
+
34
+ # The attachment id of an inline image from its content URL, or nil.
35
+ def image_id(content_url)
36
+ URI.parse(content_url).path.to_s[PATH, 1]
37
+ rescue URI::Error
38
+ nil
39
+ end
40
+
41
+ # Maps each inline image id in a message's HTML to its format hint: the
42
+ # itemscope of an <img> whose itemtype marks it as an inline image,
43
+ # keyed by its itemid.
44
+ def parse_hints(html)
45
+ html.scan(IMG_TAG).each_with_object({}) do |tag, hints|
46
+ attributes = tag.scan(ATTRIBUTE).to_h do |name, double_quoted, single_quoted|
47
+ [name.downcase, double_quoted || single_quoted]
48
+ end
49
+ id = attributes["itemid"]
50
+ scope = attributes["itemscope"]
51
+ next unless attributes["itemtype"] == AMS_IMAGE_ITEMTYPE && id && !id.empty? && scope && !scope.empty?
52
+
53
+ hints[id] = scope
54
+ end
55
+ end
56
+
57
+ def format_from_hint(hint)
58
+ normalized = hint&.strip&.downcase
59
+ return "jpeg" if normalized == "jpg"
60
+
61
+ FORMATS.key?(normalized) ? normalized : nil
62
+ end
63
+
64
+ def format_from_content_type(content_type)
65
+ format_from_hint(content_type.to_s.strip[IMAGE_CONTENT_TYPE, 1])
66
+ end
67
+
68
+ # The format the bytes actually are, from their magic bytes; Teams can
69
+ # return a different format from the hint, so bytes win.
70
+ def sniff_format(data)
71
+ bytes = data.b
72
+ return "png" if bytes.start_with?("\x89PNG\r\n\x1a\n".b)
73
+ return "jpeg" if bytes.start_with?("\xFF\xD8\xFF".b)
74
+ return "gif" if bytes.start_with?("GIF87a", "GIF89a")
75
+ return "webp" if bytes.start_with?("RIFF") && bytes.byteslice(8, 4) == "WEBP"
76
+
77
+ nil
78
+ end
79
+
80
+ def naming(base_name, format = nil)
81
+ return Naming.new(name: base_name, extension: nil, content_type: OCTET_STREAM) unless format
82
+
83
+ extension, content_type = FORMATS.fetch(format)
84
+ Naming.new(name: "#{base_name}.#{extension}", extension:, content_type:)
85
+ end
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "files/graph_share"
4
+ require_relative "files/inline_image"
5
+ require_relative "files/downloader"
6
+ require_relative "files/downloaded_file"
7
+ require_relative "files/incoming_file"
8
+ require_relative "files/files_accessor"
@@ -10,7 +10,7 @@ module Teams
10
10
  # queue to drain before sending the final message.
11
11
  class HttpStream
12
12
  STREAM_CHANNEL_DATA_KEYS = %w[streamId streamType streamSequence].freeze
13
- NON_RETRYABLE_ERRORS = [TerminalStreamError, StreamCancelledError].freeze
13
+ NON_RETRYABLE_ERRORS = [TerminalStreamError].freeze
14
14
 
15
15
  attr_reader :app, :conversation_reference
16
16
 
@@ -31,7 +31,6 @@ module Teams
31
31
  @send_retry = { max_attempts: 5, delay: 0.5, max_delay: 30.0, jitter: :full }
32
32
  reset_state
33
33
  @result = nil
34
- @canceled = false
35
34
  @timed_out = false
36
35
  @chunk_handlers = []
37
36
  @close_handlers = []
@@ -51,8 +50,12 @@ module Teams
51
50
  self
52
51
  end
53
52
 
53
+ # Deprecated: Teams no longer supports stopping a stream, so this is
54
+ # always false, like the TypeScript, Python, and .NET SDKs.
54
55
  def canceled
55
- @canceled
56
+ warn("HttpStream#canceled is deprecated: Teams no longer supports stopping a stream.",
57
+ uplevel: 1, category: :deprecated)
58
+ false
56
59
  end
57
60
 
58
61
  def timed_out
@@ -72,13 +75,11 @@ module Teams
72
75
  end
73
76
 
74
77
  def emit(activity_or_text)
75
- raise StreamCancelledError, "Stream has been cancelled." if canceled
76
-
77
78
  activity = normalize_activity(activity_or_text)
78
79
 
79
80
  @mutex.synchronize do
80
81
  # Emitting after close reopens the stream: start a new streamed
81
- # message on the same instance. The canceled flag stays sticky.
82
+ # message on the same instance.
82
83
  reset_for_next_stream if closed
83
84
 
84
85
  @queue << activity
@@ -88,12 +89,16 @@ module Teams
88
89
  nil
89
90
  end
90
91
 
91
- def update(text)
92
- emit(
92
+ # Sends an informative update. text_format (e.g. "extendedmarkdown")
93
+ # applies to this update only; omit it for the Teams default (markdown).
94
+ def update(text, text_format: nil)
95
+ activity = {
93
96
  "type" => "typing",
94
97
  "text" => text,
95
98
  "channelData" => { "streamType" => "informative" }
96
- )
99
+ }
100
+ activity["textFormat"] = text_format if text_format
101
+ emit(activity)
97
102
  end
98
103
 
99
104
  def clear_text
@@ -106,13 +111,10 @@ module Teams
106
111
 
107
112
  def close
108
113
  return @result if closed
109
- return nil if canceled
110
114
  return nil if no_content_pending?
111
115
 
112
116
  return nil unless wait_for_flush
113
117
 
114
- return nil if canceled
115
-
116
118
  unless @id
117
119
  app.logger&.warn("no stream id set, cannot close stream")
118
120
  return nil
@@ -130,7 +132,7 @@ module Teams
130
132
  outbound = final_stream_activity
131
133
  Api::SentActivity.merge(outbound, send_with_retry(outbound, @send_retry))
132
134
  rescue StreamTimedOutError
133
- # The final streamed send tripped the two-minute limit. Update the
135
+ # The final streamed send tripped the ten-minute limit. Update the
134
136
  # original message in place with the buffered content instead of
135
137
  # posting a duplicate.
136
138
  send_final
@@ -173,7 +175,6 @@ module Teams
173
175
  loop do
174
176
  done = @mutex.synchronize { @queue.empty? && !@flushing && !@id.nil? }
175
177
  return true if done
176
- return true if canceled
177
178
 
178
179
  if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
179
180
  app.logger&.warn("Timeout while waiting for the stream queue to flush, cannot close stream")
@@ -205,14 +206,15 @@ module Teams
205
206
  end
206
207
 
207
208
  # Drains the whole queue under the mutex, then sends outside it so emit
208
- # never blocks on HTTP. Send failures are classified (sticky canceled /
209
- # timed_out flags) and logged, not raised: errors surface from close,
209
+ # never blocks on HTTP. Send failures are classified (sticky timed_out
210
+ # flag) and logged, not raised: errors surface from close,
210
211
  # matching the TypeScript and Python flush behavior.
211
212
  def flush_cycle
212
213
  @mutex.synchronize { @flushing = true }
213
214
 
214
215
  informative_updates = []
215
216
  text_chunk = nil
217
+ text_format = nil
216
218
 
217
219
  @mutex.synchronize do
218
220
  while (activity = @queue.shift)
@@ -227,6 +229,10 @@ module Teams
227
229
  end
228
230
 
229
231
  text_chunk = @text.dup unless @text.empty?
232
+ # Text chunks take the last emitted message's textFormat, like its
233
+ # other fields, so they render like the final message. Informative
234
+ # updates keep their own.
235
+ text_format = @final_activity && @final_activity["textFormat"]
230
236
  end
231
237
 
232
238
  # Once the stream has timed out, stop sending chunks for this cycle;
@@ -234,9 +240,11 @@ module Teams
234
240
  return if @timed_out
235
241
 
236
242
  informative_updates.each { |activity| send_stream_chunk(activity) }
237
- send_stream_chunk("type" => "typing", "text" => text_chunk) if text_chunk
238
- rescue StreamCancelledError
239
- nil
243
+ if text_chunk
244
+ chunk = { "type" => "typing", "text" => text_chunk }
245
+ chunk["textFormat"] = text_format if text_format
246
+ send_stream_chunk(chunk)
247
+ end
240
248
  rescue StandardError => error
241
249
  app.logger&.error("stream flush failed: #{error.class}: #{error.message}")
242
250
  ensure
@@ -342,10 +350,7 @@ module Teams
342
350
  end
343
351
 
344
352
  # Retries transient failures like the TypeScript and Python streamers.
345
- # Typed stream errors are never retried; upstream also retries cancelled
346
- # sends (their cancellation error sits outside the terminal hierarchy),
347
- # but those attempts only re-raise after backoff delays, so Ruby skips
348
- # them for the same visible behavior without the waits.
353
+ # Typed stream errors are never retried.
349
354
  def send_with_retry(activity, options)
350
355
  Common::Retry.call(**options, non_retryable: NON_RETRYABLE_ERRORS, logger: app.logger) do
351
356
  send_activity(activity)
@@ -353,8 +358,6 @@ module Teams
353
358
  end
354
359
 
355
360
  def send_activity(activity)
356
- raise StreamCancelledError, "Stream has been cancelled." if canceled
357
-
358
361
  body = activity.dup
359
362
  body["from"] = conversation_reference.bot.to_h if conversation_reference.bot
360
363
  body["conversation"] = conversation_reference.conversation.to_h
@@ -391,9 +394,6 @@ module Teams
391
394
  if normalized.include?("exceeded streaming time")
392
395
  @timed_out = true
393
396
  raise StreamTimedOutError, message.empty? ? "Stream exceeded the streaming time limit." : message
394
- elsif normalized.include?("cancel")
395
- @canceled = true
396
- raise StreamCancelledError, message.empty? ? "Teams channel stopped the stream." : message
397
397
  elsif normalized.include?("not allowed") && !normalized.include?("completed streamed message")
398
398
  raise StreamNotAllowedError, message.empty? ? "Streaming is not allowed for the user or bot." : message
399
399
  else