Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Match % and _ in search text literally: recording list, v1 list, speaker, user, Inquire and snippet lookups (#485)
Murtaza Nasir0b3b19d0bed0
diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex 31cdd1a9..39962b58 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -1244,11 +1244,12 @@ def list_recordings():# Search filterif search_query:- search_pattern = f'%{search_query}%'+ from src.utils.search import LIKE_ESCAPE, contains_pattern+ search_pattern = contains_pattern(search_query)query = query.filter(or_(- Recording.title.ilike(search_pattern),- Recording.participants.ilike(search_pattern)+ Recording.title.ilike(search_pattern, escape=LIKE_ESCAPE),+ Recording.participants.ilike(search_pattern, escape=LIKE_ESCAPE)))diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 8b3c4528..8268ad2b 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -55,6 +55,7 @@ from src.services.embeddings import process_recording_chunksfrom src.file_exporter import export_recording, mark_export_as_deletedfrom src.utils.mime import served_media_mime, sandbox_media_responsefrom src.utils.filenames import shorten_filename+from src.utils.search import LIKE_ESCAPE, contains_pattern, escape_likefrom src.utils.ffprobe import get_codec_info, get_creation_date, get_duration, try_repair_malformed_webm, FFProbeErrorfrom src.utils.audio_conversion import convert_if_neededfrom src.services.storage import get_storage_service@@ -105,9 +106,7 @@ def _blank_column_condition(column):def _prefixed_column_condition(column, prefixes):# Escape LIKE metacharacters in the literal prefixes so a '_' or '%' in a# prefix (e.g. 'ERROR_JSON:') matches literally instead of as a wildcard.- def _esc(p):- return p.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')- return db.or_(*[column.like(f'{_esc(prefix)}%', escape='\\') for prefix in prefixes])+ return db.or_(*[column.like(f'{escape_like(prefix)}%', escape=LIKE_ESCAPE) for prefix in prefixes])def _transcription_error_condition():@@ -1698,7 +1697,8 @@ def get_recordings_paginated():for speaker_filter in speaker_filters:# Replace underscores back to spaces for matchingspeaker_name = speaker_filter.replace('_', ' ')- speaker_conditions.append(Recording.participants.ilike(f'%{speaker_name}%'))+ speaker_conditions.append(Recording.participants.ilike(+ contains_pattern(speaker_name), escape=LIKE_ESCAPE))stmt = stmt.where(db.or_(*speaker_conditions))# Apply text search@@ -1709,14 +1709,16 @@ def get_recordings_paginated():# - For owned recordings: search Recording.notes# - For shared recordings: search SharedRecordingState.personal_notes+ # Every character typed is matched literally (#485)+ pattern = contains_pattern(text_query)text_conditions = [- Recording.title.ilike(f'%{text_query}%'),- Recording.participants.ilike(f'%{text_query}%'),- Recording.transcription.ilike(f'%{text_query}%'),+ Recording.title.ilike(pattern, escape=LIKE_ESCAPE),+ Recording.participants.ilike(pattern, escape=LIKE_ESCAPE),+ Recording.transcription.ilike(pattern, escape=LIKE_ESCAPE),# Search owner's notes for owned recordingsdb.and_(Recording.user_id == current_user.id,- Recording.notes.ilike(f'%{text_query}%')+ Recording.notes.ilike(pattern, escape=LIKE_ESCAPE))]@@ -1725,7 +1727,7 @@ def get_recordings_paginated():shared_notes_subq = select(SharedRecordingState.recording_id).where(db.and_(SharedRecordingState.user_id == current_user.id,- SharedRecordingState.personal_notes.ilike(f'%{text_query}%')+ SharedRecordingState.personal_notes.ilike(pattern, escape=LIKE_ESCAPE))).scalar_subquery()diff --git a/src/api/shares.py b/src/api/shares.pyindex 2e2bd079..76481689 100644--- a/src/api/shares.py+++ b/src/api/shares.py@@ -20,6 +20,7 @@ from src.utils import md_to_htmlfrom src.services.storage import get_storage_servicefrom src.services.public_shares import active_share_or_404from src.utils.mime import served_media_mime, sandbox_media_response+from src.utils.search import LIKE_ESCAPE, contains_pattern# Configuration from environmentENABLE_PUBLIC_SHARING = os.environ.get('ENABLE_PUBLIC_SHARING', 'true').lower() == 'true'@@ -388,7 +389,7 @@ def search_users():# If usernames are shown, allow partial match (autocomplete)users = User.query.filter(User.id != current_user.id,- User.username.ilike(f'%{query}%')+ User.username.ilike(contains_pattern(query), escape=LIKE_ESCAPE)).limit(10).all()else:# If usernames are hidden (privacy mode), require exact match onlydiff --git a/src/api/speakers.py b/src/api/speakers.pyindex 0ed04a27..0c3abd69 100644--- a/src/api/speakers.py+++ b/src/api/speakers.py@@ -17,6 +17,7 @@ from src.models import *from src.utils import *from src.utils.ffmpeg_utils import extract_audio_segment, FFmpegError, FFmpegNotFoundErrorfrom src.utils.ffprobe import get_codec_info, FFProbeError+from src.utils.search import LIKE_ESCAPE, contains_patternfrom src.services.speaker_embedding_matcher import find_matching_speakersfrom src.services.speaker_snippets import get_speaker_snippets, get_speaker_recordings_with_snippetsfrom src.services.speaker_merge import merge_speakers, preview_merge, can_merge_speakers@@ -90,7 +91,7 @@ def search_speakers():stmt = Speaker.query.filter_by(user_id=current_user.id)if query:- stmt = stmt.filter(Speaker.name.ilike(f'%{query}%'))+ stmt = stmt.filter(Speaker.name.ilike(contains_pattern(query), escape=LIKE_ESCAPE))speakers = stmt.order_by(Speaker.use_count.desc(), Speaker.last_used.desc())\.limit(10)\.all()diff --git a/src/services/embeddings.py b/src/services/embeddings.pyindex 71d685e5..9986ae92 100644--- a/src/services/embeddings.py+++ b/src/services/embeddings.py@@ -31,6 +31,7 @@ if cosine_similarity is None:from src.database import dbfrom src.models import Recording, TranscriptChunk, InternalShare, RecordingTag+from src.utils.search import LIKE_ESCAPE, contains_patternENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'@@ -645,7 +646,7 @@ def basic_text_search_chunks(user_id, query, filters=None, top_k=5):if filters.get('speaker_names'):# Filter by the participants field on the recording.speaker_conditions = [- Recording.participants.ilike(f'%{speaker_name}%')+ Recording.participants.ilike(contains_pattern(speaker_name), escape=LIKE_ESCAPE)for speaker_name in filters['speaker_names']]chunks_query = chunks_query.filter(db.or_(*speaker_conditions))@@ -691,7 +692,7 @@ def basic_text_search_chunks(user_id, query, filters=None, top_k=5):# Filter: match ANY keyword (OR) to get candidatestext_conditions = []for word in query_words:- text_conditions.append(TranscriptChunk.content.ilike(f'%{word}%'))+ text_conditions.append(TranscriptChunk.content.ilike(contains_pattern(word), escape=LIKE_ESCAPE))chunks_query = chunks_query.filter(or_(*text_conditions))# Rank IN SQL before limiting. The previous code applied@@ -702,13 +703,13 @@ def basic_text_search_chunks(user_id, query, filters=None, top_k=5):# full phrase counting double so exact-phrase hits always# outrank scattered single-word matches.score_expr = sum(- case((TranscriptChunk.content.ilike(f'%{word}%'), 1), else_=0)+ case((TranscriptChunk.content.ilike(contains_pattern(word), escape=LIKE_ESCAPE), 1), else_=0)for word in query_words)phrase = query.lower().strip()if len(query_words) > 1 and len(phrase) >= 5:score_expr = score_expr + case(- (TranscriptChunk.content.ilike(f'%{phrase}%'), len(query_words)),+ (TranscriptChunk.content.ilike(contains_pattern(phrase), escape=LIKE_ESCAPE), len(query_words)),else_=0,)chunks = (chunks_query@@ -818,7 +819,7 @@ def semantic_search_chunks(user_id, query, filters=None, top_k=5):if filters.get('speaker_names'):# Filter by the participants field on the recording.speaker_conditions = [- Recording.participants.ilike(f'%{speaker_name}%')+ Recording.participants.ilike(contains_pattern(speaker_name), escape=LIKE_ESCAPE)for speaker_name in filters['speaker_names']]chunks_query = chunks_query.filter(db.or_(*speaker_conditions))diff --git a/src/services/inquire_agent.py b/src/services/inquire_agent.pyindex 5c4774fa..eeb9d1fe 100644--- a/src/services/inquire_agent.py+++ b/src/services/inquire_agent.py@@ -27,6 +27,7 @@ from datetime import datetime, time as dtimefrom src.database import dbfrom src.models import Folder, Recording, RecordingTag, Tag, User+from src.utils.search import LIKE_ESCAPE, contains_patternfrom src.services.embeddings import (get_accessible_recording_ids,semantic_search_chunks,@@ -132,7 +133,7 @@ def resolve_allowed_recording_ids(user_id, filters):q = q.filter(Recording.folder_id.in_(filters['folder_ids']))if filters.get('speaker_names'):q = q.filter(db.or_(*[- Recording.participants.ilike(f'%{name}%')+ Recording.participants.ilike(contains_pattern(name), escape=LIKE_ESCAPE)for name in filters['speaker_names']]))# Local calendar days of the user, as UTC bounds (#412).@@ -301,7 +302,7 @@ def tool_search_transcripts(ctx, args):def tool_list_recordings(ctx, args):q = Recording.query.filter(Recording.id.in_(ctx.allowed_ids))if args.get('participant'):- q = q.filter(Recording.participants.ilike(f"%{args['participant']}%"))+ q = q.filter(Recording.participants.ilike(contains_pattern(args['participant']), escape=LIKE_ESCAPE))from src.utils.timezones import local_date_bounds, user_timezone_by_id_zone = user_timezone_by_id(ctx.user_id)_bounds = {}diff --git a/src/services/search_v1.py b/src/services/search_v1.pyindex 8b746115..84307462 100644--- a/src/services/search_v1.py+++ b/src/services/search_v1.py@@ -15,6 +15,7 @@ from datetime import datetimefrom sqlalchemy import func, or_from src.database import db+from src.utils.search import LIKE_ESCAPE, contains_patternFIELDS = ('title', 'participants', 'notes', 'summary', 'transcript')WEIGHTS = {'title': 1.0, 'summary': 0.9, 'notes': 0.8, 'participants': 0.8, 'transcript': 0.7}@@ -40,11 +41,6 @@ def parse_terms(query):return terms-def _like(term):- escaped = term.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')- return f'%{escaped}%'--def _spans(text, terms):lower = text.lower()spans = []@@ -140,8 +136,8 @@ def candidate_query(user, terms, fields, recording_ids=None, tag_id=None, foldercolumns = {'title': Recording.title, 'participants': Recording.participants, 'notes': Recording.notes,'summary': Recording.summary, 'transcript': Recording.transcription}for term in terms:- pattern = _like(term)- query = query.filter(or_(*[columns[f].ilike(pattern, escape='\\') for f in fields]))+ pattern = contains_pattern(term)+ query = query.filter(or_(*[columns[f].ilike(pattern, escape=LIKE_ESCAPE) for f in fields]))return query.order_by(when.desc(), Recording.id.desc()), whendiff --git a/src/services/speaker_snippets.py b/src/services/speaker_snippets.pyindex 43d5f81c..98aa2c77 100644--- a/src/services/speaker_snippets.py+++ b/src/services/speaker_snippets.py@@ -14,6 +14,7 @@ Key functions:import jsonfrom src.database import dbfrom src.models import Speaker, SpeakerSnippet, Recording+from src.utils.search import LIKE_ESCAPE, contains_patternMAX_SNIPPETS_PER_SPEAKER = 7MAX_SNIPPETS_PER_RECORDING = 2@@ -165,7 +166,8 @@ def _generate_dynamic_snippets(speaker_id, limit=3):name_variants = {json.dumps(speaker.name), json.dumps(speaker.name, ensure_ascii=False)}recordings = base_query\- .filter(db.or_(*[Recording.transcription.contains(v) for v in name_variants]))\+ .filter(db.or_(*[Recording.transcription.like(contains_pattern(v), escape=LIKE_ESCAPE)+ for v in name_variants]))\.order_by(Recording.created_at.desc())\.limit(10).all()diff --git a/src/utils/search.py b/src/utils/search.pynew file mode 100644index 00000000..561cad8f--- /dev/null+++ b/src/utils/search.py@@ -0,0 +1,24 @@+"""Literal LIKE / ILIKE patterns for text typed by a user (#485).++'%' and '_' are wildcards in LIKE, and PostgreSQL and MySQL also read a+backslash as an escape by default, so text from a search box has to be+escaped before it goes into a pattern. Every caller passes+escape=LIKE_ESCAPE: the escape character is only honoured when the+statement declares it (SQLite has no default one).+"""++LIKE_ESCAPE = '\\'+++def escape_like(term):+ """`term` with the LIKE metacharacters escaped, so it matches literally.++ The backslash goes first; escaping it after '%' and '_' would double the+ escapes just added.+ """+ return term.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')+++def contains_pattern(term):+ """Pattern that matches values containing `term` literally."""+ return f'%{escape_like(term)}%'diff --git a/tests/test_api_v1_shared_scope.py b/tests/test_api_v1_shared_scope.pyindex a6be519d..ba78ec6f 100644--- a/tests/test_api_v1_shared_scope.py+++ b/tests/test_api_v1_shared_scope.py@@ -104,6 +104,19 @@ def test_filters_on_the_shared_list(world):assert _ids(_get(world, f"/api/v1/recordings?scope=all&owner_id={world['me']}")) == {world["mine"]}+def test_list_search_is_literal(world):+ # #485: % and _ in q are literal on the v1 list too+ with app.app_context():+ recs = [Recording(user_id=world["me"], title=title, status="COMPLETED", original_filename="g.wav")+ for title in ("Budget 50% target", "Budget 500 units", "under_score plan", "underXscore plan")]+ db.session.add_all(recs)+ db.session.commit()+ percent, units, underscore, x_score = (r.id for r in recs)+ assert _ids(_get(world, "/api/v1/recordings?q=50%25")) == {percent}+ assert _ids(_get(world, "/api/v1/recordings?q=under_score")) == {underscore}+ assert _ids(_get(world, "/api/v1/recordings?q=budget")) == {world["mine"], percent, units}++def test_sharing_off_gives_nothing_shared(world):with patch("src.app.ENABLE_INTERNAL_SHARING", False):assert _get(world, "/api/v1/recordings?scope=shared")["recordings"] == []diff --git a/tests/test_cov_embeddings.py b/tests/test_cov_embeddings.pyindex 63d230b8..561930a0 100644--- a/tests/test_cov_embeddings.py+++ b/tests/test_cov_embeddings.py@@ -840,6 +840,21 @@ def test_basic_search_speaker_filter(api_emb):assert all(c.recording_id == rec.id for c, _ in results)+def test_basic_search_percent_and_underscore_are_literal(api_emb):+ # #485: the keyword fallback and its speaker filter match literally+ with app.app_context():+ user = _make_user()+ rec = _make_recording(user, transcription="seed", participants="Dana 100%")+ other = _make_recording(user, transcription="seed", participants="Dana 1000")+ _seed_chunks(api_emb, user, rec, ["budget up 50% this year"])+ _seed_chunks(api_emb, user, other, ["budget of 500 units"])+ hits = api_emb.basic_text_search_chunks(user.id, "50%", top_k=5)+ assert [c.recording_id for c, _ in hits] == [rec.id]+ hits = api_emb.basic_text_search_chunks(+ user.id, "budget", filters={"speaker_names": ["Dana 100%"]}, top_k=5)+ assert {c.recording_id for c, _ in hits} == {rec.id}++def test_basic_search_date_filter(api_emb):import datetime as _dtwith app.app_context():diff --git a/tests/test_cov_recordings_read.py b/tests/test_cov_recordings_read.pyindex d439e28a..9b239d7d 100644--- a/tests/test_cov_recordings_read.py+++ b/tests/test_cov_recordings_read.py@@ -421,6 +421,99 @@ def test_paginated_speaker_filter(owner):assert nomatch_id not in ids+def _search_ids(user_id, q):+ c = new_client()+ login(c, user_id)+ resp = c.get("/api/recordings", query_string={"q": q, "per_page": 100})+ assert resp.status_code == 200, resp.get_json()+ return {r["id"] for r in resp.get_json()["recordings"]}+++def test_like_helpers_escape_backslash_first():+ from src.utils.search import LIKE_ESCAPE, contains_pattern, escape_like+ assert LIKE_ESCAPE == "\\"+ assert escape_like("plain text") == "plain text"+ assert escape_like("50%") == "50\\%"+ assert escape_like("a_b") == "a\\_b"+ # The backslash is escaped before the escapes for % and _ are added,+ # otherwise those escapes would be doubled.+ assert escape_like("C:\\temp") == "C:\\\\temp"+ assert escape_like("\\%") == "\\\\\\%"+ assert contains_pattern("x%_y") == "%x\\%\\_y%"+++def test_paginated_text_search_treats_input_literally(owner):+ # #485: % and _ typed in the search box are literal characters, and a+ # backslash still matches itself once the pattern declares ESCAPE.+ marker = f"lit{uuid.uuid4().hex[:8]}"+ with _db():+ u = db.session.get(User, owner)+ units = make_recording(u, title=f"plain {marker} 500 units").id+ percent = make_recording(u, title=f"{marker} 50% target").id+ underscore = make_recording(u, title=f"under_score {marker}").id+ x_score = make_recording(u, title=f"underXscore {marker}").id+ backslash = make_recording(u, title=f"path C:\\temp {marker}").id+ no_backslash = make_recording(u, title=f"path C:temp {marker}").id+ mine = {units, percent, underscore, x_score, backslash, no_backslash}++ assert _search_ids(owner, "50%") & mine == {percent}+ assert _search_ids(owner, "%") & mine == {percent}+ assert _search_ids(owner, "under_score") & mine == {underscore}+ assert _search_ids(owner, "_") & mine == {underscore}+ assert _search_ids(owner, "C:\\temp") & mine == {backslash}+ assert _search_ids(owner, f"{marker} 50%") & mine == {percent}+++def test_paginated_text_search_still_matches_title_transcript_and_notes(owner, other):+ from src.models import InternalShare, SharedRecordingState+ marker = f"pos{uuid.uuid4().hex[:8]}"+ with _db():+ u = db.session.get(User, owner)+ o = db.session.get(User, other)+ in_title = make_recording(u, title=f"meeting {marker}").id+ in_transcript = make_recording(+ u, title="t-only",+ transcription=f'[{{"speaker": "SPEAKER_00", "sentence": "said {marker} aloud", '+ f'"start_time": 1.0, "end_time": 2.0}}]').id+ in_participants = make_recording(u, title="p-only", participants=f"Dana {marker}").id+ noted = make_recording(u, title="n-only")+ noted.notes = f"remember {marker}"+ noted_id = noted.id+ # Another user's recording shared with the owner, matched only by+ # the owner's personal notes on it+ shared = make_recording(o, title="shared-only")+ shared_id = shared.id+ db.session.add(InternalShare(recording_id=shared_id, owner_id=o.id,+ shared_with_user_id=u.id, can_edit=False))+ db.session.add(SharedRecordingState(recording_id=shared_id, user_id=u.id,+ personal_notes=f"my note {marker}"))+ unrelated = make_recording(u, title="nothing here").id+ db.session.commit()+ try:+ with patch("src.app.ENABLE_INTERNAL_SHARING", True), \+ patch.object(rec_module, "ENABLE_INTERNAL_SHARING", True):+ ids = _search_ids(owner, marker)+ assert {in_title, in_transcript, in_participants, noted_id, shared_id} <= ids+ assert unrelated not in ids+ finally:+ with _db():+ SharedRecordingState.query.filter_by(recording_id=shared_id).delete()+ InternalShare.query.filter_by(recording_id=shared_id).delete()+ db.session.commit()+++def test_paginated_speaker_filter_percent_is_literal(owner):+ marker = f"spk{uuid.uuid4().hex[:8]}"+ with _db():+ u = db.session.get(User, owner)+ literal = make_recording(u, title=f"spk {marker}", participants="Dana 100%").id+ other_rec = make_recording(u, title=f"spk2 {marker}", participants="Dana 100x").id+ # The speaker token writes spaces as underscores+ ids = _search_ids(owner, "speaker:dana_100%")+ assert literal in ids+ assert other_rec not in ids++def test_paginated_needs_transcription_filter(owner):with _db():u = db.session.get(User, owner)diff --git a/tests/test_datetime_serialization_fixes.py b/tests/test_datetime_serialization_fixes.pyindex 933b27be..4a685a10 100644--- a/tests/test_datetime_serialization_fixes.py+++ b/tests/test_datetime_serialization_fixes.py@@ -260,6 +260,40 @@ def test_snippets_found_when_speaker_only_in_older_recordings():_cleanup(user)+def test_snippet_lookup_matches_underscore_in_name_literally():+ # #485: '_' in the speaker name is not a wildcard, so recordings of a+ # similarly named speaker cannot fill the ten candidate slots+ from src.services.speaker_snippets import get_speaker_snippets++ with app.app_context():+ user, cu = _get_or_create_test_user("_lit")+ speaker = Speaker(name="Old_Timer", user_id=user.id)+ db.session.add(speaker)+ db.session.commit()++ base = datetime(2026, 1, 1, 12, 0, 0)+ rec_match = Recording(user_id=user.id, title="Old Match", status="COMPLETED", created_at=base,+ transcription=json.dumps([+ {"speaker": "Old_Timer", "sentence": "This is a long enough sentence.",+ "start_time": 5.0, "end_time": 12.0}]))+ created = [rec_match]+ lookalike = json.dumps([{"speaker": "OldXTimer", "sentence": "A different speaker entirely.",+ "start_time": 1.0, "end_time": 6.0}])+ for i in range(12):+ created.append(Recording(user_id=user.id, title=f"Lookalike {i}", status="COMPLETED",+ transcription=lookalike, created_at=base + timedelta(days=i + 1)))+ db.session.add_all(created)+ db.session.commit()++ try:+ snippets = get_speaker_snippets(speaker.id, limit=3)+ assert [s["recording_id"] for s in snippets] == [rec_match.id]+ finally:+ _cleanup(*created, speaker)+ if cu:+ _cleanup(user)++if __name__ == "__main__":failures = 0for name, fn in sorted(globals().items()):diff --git a/tests/test_inquire_agent.py b/tests/test_inquire_agent.pyindex 5c0e9af4..fb061c3d 100644--- a/tests/test_inquire_agent.py+++ b/tests/test_inquire_agent.py@@ -257,6 +257,10 @@ def test_list_recordings_and_metadata(data):assert titles == ['Weekly Sync', 'Old Planning'] # newest firstres = ia.tool_list_recordings(ctx, {'participant': 'Alice'})assert res['total_in_scope'] == 1+ # #485: '%' and '_' in a participant filter are literal+ assert ia.tool_list_recordings(ctx, {'participant': 'A%e'})['total_in_scope'] == 0+ assert ia.tool_list_recordings(ctx, {'participant': 'Al_ce'})['total_in_scope'] == 0+ assert ia.resolve_allowed_recording_ids(data['owner'], {'speaker_names': ['A%e']}) == set()meta = ia.tool_get_recording_metadata(ctx, {'recording_id': data['r1']})assert meta['has_summary'] is True and meta['has_notes'] is Truediff --git a/tests/test_shares_authz.py b/tests/test_shares_authz.pyindex 5c468bf2..73243293 100644--- a/tests/test_shares_authz.py+++ b/tests/test_shares_authz.py@@ -467,6 +467,28 @@ def test_users_search_403_when_internal_sharing_disabled():_cleanup_ids([user], [])+def test_users_search_matches_underscore_literally():+ """#485: with usernames shown, '_' and '%' in the query are literal."""+ tok = uuid.uuid4().hex[:8]+ with _db():+ searcher = _setup_user("srch_lit")+ ids = []+ for name in (f"{tok}_a_b", f"{tok}_aXb", f"{tok}_50%", f"{tok}_500"):+ u = User(username=name, email=f"{name.replace('%', 'p')}@local.test", password="x")+ db.session.add(u)+ db.session.commit()+ ids.append(u.id)+ try:+ with _internal_enabled(), _flag("SHOW_USERNAMES_IN_UI", True, shares_module):+ client = _client_for(searcher)+ names = lambda q: {u["username"] for u in+ client.get("/api/users/search", query_string={"q": q}).get_json()}+ assert names(f"{tok}_a_b") == {f"{tok}_a_b"}+ assert names(f"{tok}_50%") == {f"{tok}_50%"}+ finally:+ _cleanup_ids([searcher, *ids], [])++def test_can_share_publicly_requires_login():resp = _anon_client().get("/api/permissions/can-share-publicly")assert resp.status_code in (302, 401), resp.status_codediff --git a/tests/test_speaker_save_paths.py b/tests/test_speaker_save_paths.pyindex 25af26b4..320f346f 100644--- a/tests/test_speaker_save_paths.py+++ b/tests/test_speaker_save_paths.py@@ -145,3 +145,13 @@ def test_search_top_lists_most_used_without_a_query(ctx):names = [s["name"] for s in c.get("/speakers/search?top=1").get_json()]assert names == ["Frequent", "Middle", "Rare"]assert [s["name"] for s in c.get("/speakers/search?q=mid&top=1").get_json()] == ["Middle"]+++def test_search_matches_percent_and_underscore_literally(ctx):+ user = _user()+ for name in ("Dana_Ops", "DanaXOps", "Team 100%", "Team 1000"):+ db.session.add(Speaker(name=name, user_id=user.id, use_count=1))+ db.session.commit()+ c = _client(user)+ assert [s["name"] for s in c.get("/speakers/search", query_string={"q": "a_o"}).get_json()] == ["Dana_Ops"]+ assert [s["name"] for s in c.get("/speakers/search", query_string={"q": "100%"}).get_json()] == ["Team 100%"]