slackwright 0.1.0__tar.gz → 0.1.2__tar.gz

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 (36) hide show
  1. {slackwright-0.1.0 → slackwright-0.1.2}/PKG-INFO +1 -1
  2. {slackwright-0.1.0 → slackwright-0.1.2}/docs/design.md +16 -1
  3. {slackwright-0.1.0 → slackwright-0.1.2}/pyproject.toml +1 -1
  4. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/ingest.py +103 -19
  5. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/render.py +59 -18
  6. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_ingest.py +160 -0
  7. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_render.py +91 -0
  8. {slackwright-0.1.0 → slackwright-0.1.2}/uv.lock +2 -1
  9. {slackwright-0.1.0 → slackwright-0.1.2}/.editorconfig +0 -0
  10. {slackwright-0.1.0 → slackwright-0.1.2}/.github/workflows/deploy.yaml +0 -0
  11. {slackwright-0.1.0 → slackwright-0.1.2}/.github/workflows/testing.yaml +0 -0
  12. {slackwright-0.1.0 → slackwright-0.1.2}/.gitignore +0 -0
  13. {slackwright-0.1.0 → slackwright-0.1.2}/.pre-commit-config.yaml +0 -0
  14. {slackwright-0.1.0 → slackwright-0.1.2}/LICENSE +0 -0
  15. {slackwright-0.1.0 → slackwright-0.1.2}/README.md +0 -0
  16. {slackwright-0.1.0 → slackwright-0.1.2}/compose.yaml +0 -0
  17. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/__init__.py +0 -0
  18. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/blocks.py +0 -0
  19. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/canvas.py +0 -0
  20. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/forms.py +0 -0
  21. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/inflight.py +0 -0
  22. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/progress.py +0 -0
  23. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/py.typed +0 -0
  24. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/stores.py +0 -0
  25. {slackwright-0.1.0 → slackwright-0.1.2}/slackwright/toolkit.py +0 -0
  26. {slackwright-0.1.0 → slackwright-0.1.2}/tests/__init__.py +0 -0
  27. {slackwright-0.1.0 → slackwright-0.1.2}/tests/fake_slack.py +0 -0
  28. {slackwright-0.1.0 → slackwright-0.1.2}/tests/services.py +0 -0
  29. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_blocks.py +0 -0
  30. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_canvas.py +0 -0
  31. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_forms.py +0 -0
  32. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_inflight.py +0 -0
  33. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_progress.py +0 -0
  34. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_stores.py +0 -0
  35. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_toolkit.py +0 -0
  36. {slackwright-0.1.0 → slackwright-0.1.2}/tests/test_version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: slackwright
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Building blocks for AI agents that live in Slack
5
5
  Project-URL: Homepage, https://github.com/gmr/slackwright
6
6
  Project-URL: Bug Tracker, https://github.com/gmr/slackwright/issues
@@ -208,6 +208,8 @@ agent gets, so the tests check that each field has a description.
208
208
  3. If the text is longer, split it at top-level block boundaries
209
209
  (markdown-it tokens) into parts of 12,000 characters or fewer. Never
210
210
  split inside a code block or a table. Post each part as one message.
211
+ Each part gets a copy of the link reference definitions
212
+ (`[label]: url`) that its links use.
211
213
  4. If one block alone is longer than 12,000 characters (for example, a
212
214
  very long code block), upload it as a file snippet.
213
215
 
@@ -473,9 +475,22 @@ Anthropic-format messages:
473
475
  turns. Ingest replaces them with a short text note.
474
476
  - Replaces `<@U123>` with display names (cached).
475
477
  - Downloads files and turns them into content blocks.
478
+ - Keeps `bot_message` posts from integrations and webhooks. A post
479
+ without a `user` gets the header `<bot:NAME BOT_ID>`, so it cannot
480
+ look like a person. NAME comes from `bot_profile.name` or `username`
481
+ (a webhook can set any username) and keeps only safe characters.
482
+ - Labels a link preview (an attachment with `from_url`) as not written
483
+ by the author.
484
+ - Adds the text of legacy `attachments` (pretext, title, text, fields,
485
+ or the fallback) and of Block Kit `blocks` to other users' messages.
486
+ Apps such as Front put the full report there, and link unfurls are
487
+ attachments. `rich_text` blocks repeat `text` and button labels are
488
+ noise, so ingest skips them. A part that `text` already contains is
489
+ left out.
476
490
 
477
491
  A bot that needs extra steps calls the lower-level functions
478
- (`file_blocks()`, `replace_mentions()`) and keeps its own loop.
492
+ (`message_text()`, `file_blocks()`, `replace_mentions()`) and keeps its
493
+ own loop.
479
494
 
480
495
  ### 9.2 Files
481
496
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "slackwright"
7
- version = "0.1.0"
7
+ version = "0.1.2"
8
8
  description = "Building blocks for AI agents that live in Slack"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -3,7 +3,8 @@
3
3
  :func:`thread` reads a whole thread and gives back alternating
4
4
  ``user`` and ``assistant`` turns that start with a user turn, as the
5
5
  Anthropic Messages API requires. The lower-level functions
6
- (:func:`replace_mentions`, :func:`file_blocks`, :func:`file_to_block`)
6
+ (:func:`message_text`, :func:`replace_mentions`, :func:`file_blocks`,
7
+ :func:`file_to_block`)
7
8
  are public for bots that build the history themselves.
8
9
 
9
10
  File downloads send the bot token. :func:`http_client` makes a client
@@ -65,10 +66,19 @@ BINARY_AMBIGUOUS_MIMETYPES = frozenset(
65
66
  {'application/force-download', 'application/octet-stream'}
66
67
  )
67
68
 
68
- _KEPT_SUBTYPES = frozenset({None, 'thread_broadcast'})
69
- """Message subtypes that are turns. A reply sent to the channel too is
70
- a ``thread_broadcast``."""
69
+ _KEPT_SUBTYPES = frozenset(
70
+ {None, 'bot_message', 'file_share', 'thread_broadcast'}
71
+ )
72
+ """Message subtypes that are turns. A message with an uploaded file can
73
+ be a ``file_share``. A reply sent to the channel too is a
74
+ ``thread_broadcast``. A post from an integration or a webhook is a
75
+ ``bot_message`` and can have a ``bot_id`` and no ``user``."""
76
+ _SKIPPED_BLOCK_TYPES = frozenset({'actions', 'button', 'rich_text'})
77
+ """Block and element types that give no text to the model. ``rich_text``
78
+ repeats the message ``text``. Buttons have only labels."""
79
+ _TEXT_OBJECT_TYPES = frozenset({'markdown', 'mrkdwn', 'plain_text'})
71
80
  _MENTION_RE = re.compile(r'<@([A-Z0-9]+)(?:\|[^>]+)?>')
81
+ _UNSAFE_NAME_CHARS = re.compile(r'[^\w .()-]')
72
82
  _UNSAFE_URL_CHARS = re.compile(r'[\\\s\x00-\x1f\x7f]')
73
83
 
74
84
 
@@ -323,28 +333,35 @@ async def to_messages(
323
333
  and document blocks only in user turns.
324
334
 
325
335
  """
336
+ # The bot's own blocks repeat its text, so only its text is used.
337
+ kept = [
338
+ (
339
+ message,
340
+ author,
341
+ message.get('text') or ''
342
+ if author == bot_user_id
343
+ else message_text(message),
344
+ )
345
+ for message in messages
346
+ if message.get('subtype') in _KEPT_SUBTYPES
347
+ and (author := message.get('user') or message.get('bot_id'))
348
+ ]
326
349
  cache: dict[str, str] = {}
327
350
  user_ids = {
328
- message['user']
329
- for message in messages
330
- if message.get('user') and message.get('subtype') in _KEPT_SUBTYPES
331
- } | {
351
+ message['user'] for message, _, _ in kept if message.get('user')
352
+ }
353
+ user_ids |= {
332
354
  match.group(1)
333
- for message in messages
334
- for match in _MENTION_RE.finditer(message.get('text') or '')
355
+ for _, _, raw in kept
356
+ for match in _MENTION_RE.finditer(raw)
335
357
  }
336
358
  await _gather(
337
359
  [display_name(slack, user_id, cache) for user_id in user_ids],
338
360
  NAME_CONCURRENCY,
339
361
  )
340
362
  turns: list[tuple[str, list[ContentBlock]]] = []
341
- for message in messages:
342
- author = message.get('user')
343
- if message.get('subtype') not in _KEPT_SUBTYPES or not author:
344
- continue
345
- text = (
346
- await replace_mentions(slack, message.get('text') or '', cache)
347
- ).strip()
363
+ for message, author, raw in kept:
364
+ text = (await replace_mentions(slack, raw, cache)).strip()
348
365
  files: list[dict[str, typing.Any]] = message.get('files') or []
349
366
  if author == bot_user_id:
350
367
  role = 'assistant'
@@ -357,8 +374,19 @@ async def to_messages(
357
374
  blocks = await file_blocks(files_client, files) if files else []
358
375
  if not text and not blocks:
359
376
  continue
360
- name = await display_name(slack, author, cache)
361
- header = f'<@{name}> [ts={message.get("ts", "")}] {text}'
377
+ if message.get('user'):
378
+ name = '@' + await display_name(slack, author, cache)
379
+ else:
380
+ # A webhook sets any username, so a bot must not look
381
+ # like a person, and its name must not break the header.
382
+ bot_name = str(
383
+ (message.get('bot_profile') or {}).get('name')
384
+ or message.get('username')
385
+ or ''
386
+ )
387
+ safe = _UNSAFE_NAME_CHARS.sub('', bot_name)[:80]
388
+ name = f'bot:{safe} {_UNSAFE_NAME_CHARS.sub("", author)}'
389
+ header = f'<{name}> [ts={message.get("ts", "")}] {text}'
362
390
  content = [text_block(header.rstrip()), *blocks]
363
391
  if not content:
364
392
  continue
@@ -371,6 +399,62 @@ async def to_messages(
371
399
  return [_collapse(role, parts) for role, parts in turns]
372
400
 
373
401
 
402
+ def message_text(message: dict[str, typing.Any]) -> str:
403
+ """Return a message's text with its blocks and legacy attachments.
404
+
405
+ Apps such as Front put a report in ``attachments`` or ``blocks``
406
+ and only a summary in ``text``. Link unfurls are attachments too.
407
+ Each extracted line that ``text`` already contains is left out.
408
+
409
+ """
410
+ text = message.get('text') or ''
411
+
412
+ def new(items: collections.abc.Iterable[str | None]) -> str:
413
+ return '\n'.join(item for item in items if item and item not in text)
414
+
415
+ parts = [new(_block_texts(message.get('blocks')))]
416
+ for attachment in message.get('attachments') or []:
417
+ fields = [
418
+ ': '.join(p for p in (field.get('title'), field.get('value')) if p)
419
+ for field in attachment.get('fields') or []
420
+ ]
421
+ body = [
422
+ attachment.get('pretext'),
423
+ attachment.get('title'),
424
+ attachment.get('text'),
425
+ *fields,
426
+ *_block_texts(attachment.get('blocks')),
427
+ ]
428
+ if any(body):
429
+ part = new(body)
430
+ else:
431
+ part = new([attachment.get('fallback')])
432
+ # Slack adds a link preview. The author did not write it.
433
+ url = attachment.get('from_url') or attachment.get('original_url')
434
+ if part and url:
435
+ part = (
436
+ f'[Link preview of {url}, not written by the author]\n{part}'
437
+ )
438
+ parts.append(part)
439
+ return '\n\n'.join(p for p in [text, *parts] if p)
440
+
441
+
442
+ def _block_texts(node: typing.Any) -> collections.abc.Iterator[str]:
443
+ """Yield every text object in Block Kit ``node``, depth first."""
444
+ if isinstance(node, list):
445
+ for item in node:
446
+ yield from _block_texts(item)
447
+ elif isinstance(node, dict):
448
+ kind = node.get('type')
449
+ if kind in _SKIPPED_BLOCK_TYPES:
450
+ return
451
+ if kind in _TEXT_OBJECT_TYPES and isinstance(node.get('text'), str):
452
+ yield node['text']
453
+ return
454
+ for value in node.values():
455
+ yield from _block_texts(value)
456
+
457
+
374
458
  async def _gather[T](
375
459
  awaitables: list[collections.abc.Awaitable[T]], limit: int
376
460
  ) -> list[T]:
@@ -44,6 +44,9 @@ _ZWSP = '\u200b'
44
44
  # The format and the optional link share one field that can contain
45
45
  # ``^``. Two fields that both match ``^`` make the time quadratic.
46
46
  _SPECIAL = re.compile(r'<!(?!date\^\d+\^[^<>|]*\|[^<>]*>)')
47
+ # Bare words are blocked in code and URLs too. A regex cannot find
48
+ # code and links exactly as Slack does, and a zero-width space there
49
+ # costs less than a broadcast that gets through.
47
50
  _BARE_BROADCAST = re.compile(
48
51
  r'(?<![A-Za-z0-9])@(channel|here|everyone|group)(?![A-Za-z0-9])',
49
52
  re.IGNORECASE,
@@ -58,9 +61,9 @@ def neutralize_broadcasts(text: str) -> str:
58
61
  ``<`` changes tokens such as ``<!channel>``, ``<!here>``, and
59
62
  ``<!subteam^ID|@label>`` into literal text. Also blocks the bare
60
63
  words ``@channel``, ``@here``, ``@everyone``, and ``@group`` in any
61
- letter case with a zero-width space after the ``@``. User mentions
62
- such as ``<@U123>`` and email addresses such as ``x@here.com`` do
63
- not change.
64
+ letter case with a zero-width space after the ``@``, also in
65
+ code and URLs. User mentions such as ``<@U123>`` and email
66
+ addresses such as ``x@here.com`` do not change.
64
67
 
65
68
  The :class:`~slackwright.toolkit.Toolkit` calls this on agent text
66
69
  unless the bot sets ``allow_broadcasts``. :func:`post_markdown` does
@@ -127,27 +130,65 @@ def split_markdown(text: str, limit: int = MARKDOWN_LIMIT) -> list[str]:
127
130
  text = text.strip()
128
131
  if len(text) <= limit:
129
132
  return [text] if text else []
130
- lines = text.splitlines()
131
- # ponytail: link reference definitions are not tokens and are lost
132
- # when a long answer is split; LLM output rarely uses them.
133
- blocks = [
134
- '\n'.join(lines[token.map[0] : token.map[1]]).strip()
135
- for token in _PARSER.parse(text)
136
- if token.level == 0 and token.map and token.nesting >= 0
133
+ # Use the line breaks of markdown-it. splitlines() also breaks at
134
+ # characters such as U+2028, so the token maps do not align.
135
+ lines = re.split(r'\r\n?|\n', text)
136
+ env: dict[str, typing.Any] = {}
137
+ spans = [
138
+ span
139
+ for token in _PARSER.parse(text, env)
140
+ if token.level == 0 and token.nesting >= 0 and (span := token.map)
137
141
  ]
138
- parts: list[str] = []
139
- current = ''
142
+ blocks = ['\n'.join(lines[start:end]).strip() for start, end in spans]
143
+ # Link reference definitions make no tokens. Each part gets a copy
144
+ # of the top-level definitions that its links use. A definition in
145
+ # a quote or a list is already in its block.
146
+ definitions = {
147
+ label: '\n'.join(lines[start:end]).strip()
148
+ for label, ref in env.get('references', {}).items()
149
+ for start, end in [ref['map']]
150
+ if not any(s <= start < e for s, e in spans)
151
+ }
152
+ parts: list[tuple[str, set[str]]] = []
153
+ current, used = '', set[str]()
140
154
  for block in blocks:
141
155
  candidate = f'{current}\n\n{block}' if current else block
142
- if len(candidate) <= limit:
143
- current = candidate
156
+ candidate_used = used | _labels(block, definitions)
157
+ # The part, a blank line, then one definition on each line.
158
+ extra = sum(len(definitions[label]) + 1 for label in candidate_used)
159
+ if len(candidate) + (extra + 1 if extra else 0) <= limit:
160
+ current, used = candidate, candidate_used
144
161
  continue
145
162
  if current:
146
- parts.append(current)
147
- current = block
163
+ parts.append((current, used))
164
+ current, used = block, _labels(block, definitions)
148
165
  if current:
149
- parts.append(current)
150
- return parts
166
+ parts.append((current, used))
167
+ # Put the definitions first. At the end, an unclosed code fence
168
+ # would contain them.
169
+ return [
170
+ '\n\n'.join(
171
+ ['\n'.join(d for k, d in definitions.items() if k in used), part]
172
+ )
173
+ if used
174
+ else part
175
+ for part, used in parts
176
+ ]
177
+
178
+
179
+ def _labels(block: str, definitions: dict[str, str]) -> set[str]:
180
+ """Return the labels of the definitions that ``block`` uses.
181
+
182
+ markdown-it keys definitions by label in upper case (from
183
+ ``lower().upper()``), with each run of white space changed to one
184
+ space and no space at the ends. Only the space at an unescaped
185
+ ``[`` is removed, because a label can contain ``\\[``.
186
+
187
+ """
188
+ normalized = re.sub(
189
+ r'(?<!\\)\[ ', '[', ' '.join(block.lower().upper().split())
190
+ ).replace(' ]', ']')
191
+ return {label for label in definitions if f'[{label}]' in normalized}
151
192
 
152
193
 
153
194
  async def post_markdown(
@@ -155,6 +155,100 @@ class DownloadTestCase(unittest.IsolatedAsyncioTestCase):
155
155
  self.assertEqual(blocks, [{'type': 'text', 'text': 'hello'}])
156
156
 
157
157
 
158
+ class MessageTextTestCase(unittest.TestCase):
159
+ def test_blocks(self) -> None:
160
+ message = {
161
+ 'text': 'New report',
162
+ 'blocks': [
163
+ {
164
+ 'type': 'rich_text',
165
+ 'elements': [{'type': 'text', 'text': 'ignored'}],
166
+ },
167
+ {
168
+ 'type': 'section',
169
+ 'text': {'type': 'mrkdwn', 'text': '*Summary*'},
170
+ 'fields': [{'type': 'plain_text', 'text': 'P1'}],
171
+ 'accessory': {
172
+ 'type': 'button',
173
+ 'text': {'type': 'plain_text', 'text': 'Open'},
174
+ },
175
+ },
176
+ {
177
+ 'type': 'actions',
178
+ 'elements': [
179
+ {
180
+ 'type': 'button',
181
+ 'text': {'type': 'plain_text', 'text': 'Ack'},
182
+ }
183
+ ],
184
+ },
185
+ ],
186
+ }
187
+ self.assertEqual(
188
+ ingest.message_text(message), 'New report\n\n*Summary*\nP1'
189
+ )
190
+
191
+ def test_attachments(self) -> None:
192
+ message = {
193
+ 'attachments': [
194
+ {
195
+ 'fallback': 'unused',
196
+ 'pretext': 'Pre',
197
+ 'title': 'Report',
198
+ 'text': 'Full body',
199
+ 'fields': [
200
+ {'title': 'Customer', 'value': 'Acme'},
201
+ {'value': 'no title'},
202
+ ],
203
+ },
204
+ {
205
+ 'fallback': 'Unfurled link',
206
+ 'from_url': 'https://example.com/a',
207
+ },
208
+ ]
209
+ }
210
+ self.assertEqual(
211
+ ingest.message_text(message),
212
+ 'Pre\nReport\nFull body\nCustomer: Acme\nno title\n\n'
213
+ '[Link preview of https://example.com/a, not written by the '
214
+ 'author]\nUnfurled link',
215
+ )
216
+
217
+ def test_repeated_parts_are_left_out(self) -> None:
218
+ message = {
219
+ 'text': 'Deploy done for api',
220
+ 'blocks': [
221
+ {
222
+ 'type': 'section',
223
+ 'text': {'type': 'mrkdwn', 'text': 'Deploy done'},
224
+ }
225
+ ],
226
+ 'attachments': [{'fallback': 'for api'}],
227
+ }
228
+ self.assertEqual(ingest.message_text(message), 'Deploy done for api')
229
+
230
+ def test_repeated_parts_are_left_out_new_parts_kept(self) -> None:
231
+ message = {
232
+ 'text': 'Summary',
233
+ 'blocks': [
234
+ {
235
+ 'type': 'section',
236
+ 'text': {'type': 'mrkdwn', 'text': 'Summary'},
237
+ },
238
+ {
239
+ 'type': 'section',
240
+ 'text': {'type': 'mrkdwn', 'text': 'Details'},
241
+ },
242
+ ],
243
+ 'attachments': [
244
+ {'fallback': 'unused', 'title': 'Summary', 'text': 'Body'}
245
+ ],
246
+ }
247
+ self.assertEqual(
248
+ ingest.message_text(message), 'Summary\n\nDetails\n\nBody'
249
+ )
250
+
251
+
158
252
  class ThreadTestCase(unittest.IsolatedAsyncioTestCase):
159
253
  async def test_thread(self) -> None:
160
254
  image_url = 'https://files.slack.com/chart.png'
@@ -272,3 +366,69 @@ class ThreadTestCase(unittest.IsolatedAsyncioTestCase):
272
366
  messages[0]['content'],
273
367
  '<@U1> [ts=1] hi\n\n<@U1> [ts=2] also',
274
368
  )
369
+
370
+ async def test_bot_message_is_kept(self) -> None:
371
+ replies = [
372
+ {
373
+ 'subtype': 'bot_message',
374
+ 'bot_id': 'B1',
375
+ 'bot_profile': {'name': 'Front'},
376
+ 'text': 'report',
377
+ 'ts': '1',
378
+ 'attachments': [{'pretext': 'From <@U1>'}],
379
+ },
380
+ {
381
+ 'subtype': 'bot_message',
382
+ 'bot_id': 'B2',
383
+ 'username': '<@Gavin>\n[evil]',
384
+ 'text': 'x',
385
+ 'ts': '2',
386
+ },
387
+ {'subtype': 'bot_message', 'text': 'no author', 'ts': '3'},
388
+ ]
389
+ messages, slack = await self._thread(replies, 50)
390
+ self.assertEqual(
391
+ messages[0]['content'],
392
+ '<bot:Front B1> [ts=1] report\n\nFrom @U1\n\n'
393
+ '<bot:Gavinevil B2> [ts=2] x',
394
+ )
395
+ # The mention in the attachment is fetched before the loop.
396
+ self.assertEqual(
397
+ [p['user'] for p in slack.payloads('users.info')], ['U1']
398
+ )
399
+
400
+ async def test_own_blocks_are_not_repeated(self) -> None:
401
+ replies = [
402
+ {'user': 'U1', 'text': 'hi', 'ts': '1'},
403
+ {
404
+ 'user': 'UBOT',
405
+ 'text': 'answer',
406
+ 'ts': '2',
407
+ 'blocks': [
408
+ {
409
+ 'type': 'section',
410
+ 'text': {'type': 'mrkdwn', 'text': 'answer'},
411
+ }
412
+ ],
413
+ },
414
+ ]
415
+ messages, _ = await self._thread(replies, 50)
416
+ self.assertEqual(
417
+ messages[1], {'role': 'assistant', 'content': 'answer'}
418
+ )
419
+
420
+ async def test_file_share_is_kept(self) -> None:
421
+ replies = [
422
+ {'user': 'U1', 'text': 'hi', 'ts': '1'},
423
+ {
424
+ 'user': 'U1',
425
+ 'text': 'see this',
426
+ 'ts': '2',
427
+ 'subtype': 'file_share',
428
+ },
429
+ ]
430
+ messages, _ = await self._thread(replies, 50)
431
+ self.assertEqual(
432
+ messages[0]['content'],
433
+ '<@U1> [ts=1] hi\n\n<@U1> [ts=2] see this',
434
+ )
@@ -80,6 +80,21 @@ class NeutralizeBroadcastsTestCase(unittest.TestCase):
80
80
  with self.subTest(text=text):
81
81
  self.assertEqual(render.neutralize_broadcasts(text), expected)
82
82
 
83
+ def test_bare_words_in_code_and_urls(self) -> None:
84
+ for text, expected in (
85
+ ('`@here`', '`@\u200bhere`'),
86
+ ('\\`@here\\`', '\\`@\u200bhere\\`'),
87
+ ('```\n@channel\n```', '```\n@\u200bchannel\n```'),
88
+ ('https://)@here', 'https://)@\u200bhere'),
89
+ ):
90
+ with self.subTest(text=text):
91
+ self.assertEqual(render.neutralize_broadcasts(text), expected)
92
+
93
+ def test_special_token_in_code_is_broken(self) -> None:
94
+ self.assertEqual(
95
+ render.neutralize_broadcasts('`<!here>`'), '`<\u200b!here>`'
96
+ )
97
+
83
98
  def test_other_text_is_unchanged(self) -> None:
84
99
  for text in (
85
100
  '<@U123> hi',
@@ -116,6 +131,82 @@ class SplitMarkdownTestCase(unittest.TestCase):
116
131
  table = next(part for part in parts if '| row-0 |' in part)
117
132
  self.assertIn('| row-199 |', table)
118
133
 
134
+ def test_link_definitions_follow_their_links(self) -> None:
135
+ filler = 'x' * 60
136
+ text = '\n\n'.join(
137
+ [
138
+ 'See [the docs][Docs] first.',
139
+ *[filler] * 3,
140
+ 'Then read [the guide].',
141
+ '[docs]: https://docs.test\n'
142
+ '[The Guide]: https://guide.test\n'
143
+ ' "Guide title"',
144
+ ]
145
+ )
146
+ parts = render.split_markdown(text, limit=120)
147
+ self.assertGreater(len(parts), 1)
148
+ for part in parts:
149
+ self.assertLessEqual(len(part), 120)
150
+ self.assertIn('[docs]: https://docs.test', parts[0])
151
+ self.assertNotIn('guide.test', parts[0])
152
+ self.assertTrue(
153
+ parts[-1].startswith(
154
+ '[The Guide]: https://guide.test\n "Guide title"'
155
+ )
156
+ )
157
+ self.assertNotIn('docs.test', parts[-1])
158
+
159
+ def test_many_definitions_split_fast(self) -> None:
160
+ definitions = '\n'.join(
161
+ f'[d{i}]: https://x.test/{i}' for i in range(200)
162
+ )
163
+ text = '\n\n'.join(
164
+ [*(f'block {i} [x][d{i % 200}]' for i in range(5000)), definitions]
165
+ )
166
+ start = time.perf_counter()
167
+ parts = render.split_markdown(text)
168
+ self.assertLess(time.perf_counter() - start, 2)
169
+ for part in parts:
170
+ self.assertLessEqual(len(part), render.MARKDOWN_LIMIT)
171
+ self.assertIn('[d7]: https://x.test/7', parts[0])
172
+
173
+ def test_padded_label_keeps_its_definition(self) -> None:
174
+ text = '\n\n'.join(
175
+ ['See [manual][ docs ].', 'z' * 40, '[docs]: https://docs.test']
176
+ )
177
+ parts = render.split_markdown(text, limit=60)
178
+ self.assertIn('[docs]: https://docs.test', parts[0])
179
+
180
+ def test_unicode_case_label_keeps_its_definition(self) -> None:
181
+ text = '\n\n'.join(['See [ẞ].', 'z' * 60, '[ẞ]: https://x.test'])
182
+ parts = render.split_markdown(text, limit=60)
183
+ self.assertIn('[ẞ]: https://x.test', parts[0])
184
+
185
+ def test_space_after_escaped_bracket_keeps_its_definition(self) -> None:
186
+ text = '\n\n'.join(
187
+ [r'See [a\[ b].', 'z' * 60, r'[a\[ b]: https://x.test']
188
+ )
189
+ parts = render.split_markdown(text, limit=60)
190
+ self.assertIn(r'[a\[ b]: https://x.test', parts[0])
191
+
192
+ def test_line_separator_does_not_split_definition(self) -> None:
193
+ definition = '[x]: https://x.test "a\u2028b"'
194
+ text = '\n\n'.join(['See [x].', 'z' * 40, definition])
195
+ parts = render.split_markdown(text, limit=60)
196
+ self.assertTrue(parts[0].startswith(definition))
197
+
198
+ def test_definition_stays_out_of_unclosed_fence(self) -> None:
199
+ text = 'z' * 60 + '\n\n[x]: https://x.test\n\nSee [x].\n\n~~~\ncode'
200
+ parts = render.split_markdown(text, limit=60)
201
+ self.assertEqual(
202
+ parts[1], '[x]: https://x.test\n\nSee [x].\n\n~~~\ncode'
203
+ )
204
+
205
+ def test_unused_definition_is_dropped(self) -> None:
206
+ text = '\n\n'.join(['a' * 80, 'b' * 80, '[x]: https://x.test'])
207
+ parts = render.split_markdown(text, limit=100)
208
+ self.assertEqual(parts, ['a' * 80, 'b' * 80])
209
+
119
210
  def test_block_over_limit_is_one_part(self) -> None:
120
211
  code = '```\n' + 'x' * (render.MARKDOWN_LIMIT + 10) + '\n```'
121
212
  parts = render.split_markdown(f'intro\n\n{code}\n\noutro')
@@ -1202,6 +1202,7 @@ source = { registry = "https://pypi.org/simple" }
1202
1202
  dependencies = [
1203
1203
  { name = "typing-extensions" },
1204
1204
  ]
1205
+ sdist = { url = "https://files.pythonhosted.org/packages/fb/63/0ceb815a7762576027ce388544c573d440574f95afb1302a2496b96db548/pydantic_core-2.50.5.tar.gz", hash = "sha256:1e740886083ff95530d694e6a3f09ed914bcf92a496d16acd307c6c3484fc36d", size = 523285, upload-time = "2026-11-19T12:56:38.067Z" }
1205
1206
  wheels = [
1206
1207
  { url = "https://files.pythonhosted.org/packages/2e/ce/c79f87db419571137da902afa5cb16f7a981943bb9e0a520886fc4ed06e6/pydantic_core-2.50.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:24d23de96195ff9637e5940a7fbde3bea6a355b26fb5f491737dd803aa5d5a93", size = 2233897, upload-time = "2026-11-19T12:54:02.758Z" },
1207
1208
  { url = "https://files.pythonhosted.org/packages/9f/6f/4e172894c2a4ca3bacd6c5f823ea5576df25eafe7593ffeb3576895b92aa/pydantic_core-2.50.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a9bcf23628860d5a90cacdc188ee3b7d0547a38eb985214f03e7002a6ca0e558", size = 2111013, upload-time = "2026-11-19T12:54:04.084Z" },
@@ -1406,7 +1407,7 @@ wheels = [
1406
1407
 
1407
1408
  [[package]]
1408
1409
  name = "slackwright"
1409
- version = "0.1.0"
1410
+ version = "0.1.2"
1410
1411
  source = { editable = "." }
1411
1412
  dependencies = [
1412
1413
  { name = "aiohttp" },
File without changes
File without changes
File without changes
File without changes
File without changes