Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Add /label/<name> deep links for tag-filtered recording lists

Sumanth J.V59e061d5d4f5
diff --git a/docs/features.md b/docs/features.md
index f53d3265..5f4fbe84 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -111,6 +111,8 @@ The floating action bar appears when recordings are selected, showing the count
Organize recordings with a flexible [tagging system](user-guide/settings.md#tag-management-tab) that goes beyond simple labels. Tags can include [custom AI prompts](admin-guide/prompts.md) for specialized processing. Each tag can carry [custom AI prompts](admin-guide/prompts.md) and transcription settings, enabling automatic specialized processing based on content type, automatically applying specialized processing to tagged recordings. Tags use colors for visual organization and stack intelligently when multiple tags apply to the same recording.
+Every label is also a link. Clicking a tag filters the list to it and puts `/label/<name>` in the address bar, so a group of recordings can be bookmarked or shared the same way `/recordings/<id>` links a single one. The name is matched exactly but case-insensitively (`/label/Q3%20Planning` and `/label/q3%20planning` reach the same label), and it resolves against the tags the person opening it can see - so a link stays private, showing each viewer only their own recordings under that name, and covering both their personal tag and a group tag if they happen to share it.
+
### Retention Policies and Auto-Deletion
Implement intelligent data lifecycle management with flexible retention policies. Set a global retention period for automatic cleanup of old recordings, with the choice to delete just audio files (preserving valuable transcriptions) or complete recordings. Tags can override global retention with custom retention periods - keep legal records for 7 years, marketing content for 6 months, and general meetings for 90 days, all through tag-level configuration. Protected tags prevent specific recordings from ever being auto-deleted, perfect for compliance requirements and permanent archives. Group tags can enforce group-wide retention policies. The system provides preview functionality to see exactly what will be deleted before any changes occur, and administrators can control whether users can delete their own recordings or if deletion requires admin approval.
diff --git a/src/api/recordings.py b/src/api/recordings.py
index db9d98cb..db514cf7 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -1483,10 +1483,15 @@ def reset_status(recording_id):
@recordings_bp.route('/')
@recordings_bp.route('/recordings/<int:recording_id>')
+@recordings_bp.route('/label/<label_name>')
@login_required
-def index(recording_id=None):
+def index(recording_id=None, label_name=None):
# recording_id is a deep link (#301): the server just serves the SPA shell
# here; the frontend reads it from the path and pre-selects the recording.
+ # label_name works the same way for /label/<name>: the shell is served and
+ # the frontend resolves the name against the viewer's own accessible tags
+ # and applies it as the tag filter, so one link points at a group of
+ # recordings. Neither value is used server-side.
# Check if user is a group admin
is_team_admin = GroupMembership.query.filter_by(
user_id=current_user.id,
@@ -1923,7 +1928,13 @@ def get_recordings_paginated():
for tag_filter in tag_filters:
# Replace underscores back to spaces for matching
tag_name = tag_filter.replace('_', ' ')
- tag_conditions.append(Tag.name.ilike(f'%{tag_name}%'))
+ # Exact, case-insensitive: the filter is built from a tag
+ # the user picked (sidebar chip, or a /label/<name> link),
+ # so 'foo' must not also drag in 'foobar'. lower() == is
+ # used over ilike so '%' and '_' in a tag name stay literal.
+ tag_conditions.append(
+ db.func.lower(Tag.name) == tag_name.lower()
+ )
stmt = stmt.join(RecordingTag).join(Tag).where(db.or_(*tag_conditions))
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index c1833a8a..c6695b64 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -21,6 +21,7 @@ import { useFolders } from './modules/composables/folders.js';
// Import utilities
import { showToast } from './modules/utils/toast.js';
import { getContrastTextColor } from './modules/utils/colors.js';
+import { labelPathForFilter, parseLabelPath } from './modules/utils/label-links.js';
import { buildVariableList } from './modules/utils/prompt-variables.js';
import {
detectPlatform,
@@ -278,6 +279,12 @@ document.addEventListener('DOMContentLoaded', async () => {
// leave the modal alone (and consumes itself) so the deep-linked
// upload modal stays open behind the freshly-loaded detail view.
const uploadDeepLinkPending = ref(false);
+ // Set true on mount when arriving via the /label/<name> deep link.
+ // The first loadRecordings would otherwise auto-select the last
+ // viewed recording, opening the detail view and rewriting the
+ // address bar to /recordings/<id>. The flag suppresses that one
+ // auto-selection so the label list is what the user lands on.
+ const labelDeepLinkPending = ref(false);
const dragover = ref(false);
const recordings = ref([]);
const selectedRecording = ref(null);
@@ -1734,7 +1741,7 @@ document.addEventListener('DOMContentLoaded', async () => {
// =========================================================================
const state = {
// Core
- currentView, showUploadModal, uploadDeepLinkPending, dragover, recordings, selectedRecording, selectedTab, searchQuery,
+ currentView, showUploadModal, uploadDeepLinkPending, labelDeepLinkPending, dragover, recordings, selectedRecording, selectedTab, searchQuery,
isLoadingRecordings, globalError, csrfToken,
// Filters
@@ -3595,18 +3602,28 @@ document.addEventListener('DOMContentLoaded', async () => {
}
});
- // Keep the address bar in sync with the open recording so links are
- // shareable/bookmarkable (#301). replaceState avoids history spam;
- // the path is only changed (query + hash preserved). Incognito (id
- // 'incognito') and the list view map back to '/'.
- watch(selectedRecording, (rec) => {
+ // Keep the address bar in sync with what's on screen so links are
+ // shareable/bookmarkable (#301). An open recording wins
+ // (/recordings/<id>); otherwise a lone active label filter is
+ // reflected as /label/<name>, so clicking a tag hands the user a
+ // link to that group of recordings without them having to know the
+ // URL shape. Everything else maps back to '/'. replaceState avoids
+ // history spam; the path is only changed (query + hash preserved).
+ // Incognito (id 'incognito') is not a number, so it maps to '/'.
+ const syncAddressBar = () => {
try {
- const path = (rec && typeof rec.id === 'number') ? `/recordings/${rec.id}` : '/';
+ const rec = selectedRecording.value;
+ const path = (rec && typeof rec.id === 'number')
+ ? `/recordings/${rec.id}`
+ : (labelPathForFilter(filterTags.value, availableTags.value) || '/');
if (window.location.pathname !== path) {
window.history.replaceState({}, '', path + window.location.search + window.location.hash);
}
} catch (_) { /* best-effort */ }
- });
+ };
+
+ watch(selectedRecording, syncAddressBar);
+ watch(filterTags, syncAddressBar, { deep: true });
watch(sortBy, (newValue) => {
localStorage.setItem('recordingsSortBy', newValue);
@@ -3943,15 +3960,49 @@ document.addEventListener('DOMContentLoaded', async () => {
setTimeout(attempt, 400);
};
+ // Deep link to a label: /label/<name>. Unlike the recording
+ // deep link this has to be resolved BEFORE the list loads —
+ // the name only becomes tag ids once the tags are in, and the
+ // filter has to be in place for the very first page fetch so
+ // the user never sees the unfiltered list flash past.
+ const deepLinkLabelName = parseLabelPath(window.location.pathname);
+
+ let labelDeepLinkResolved = false;
+ if (deepLinkLabelName) {
+ labelDeepLinkPending.value = true;
+ await recordingsComposable.loadTags();
+ labelDeepLinkResolved = recordingsComposable.filterByLabelName(deepLinkLabelName);
+ if (labelDeepLinkResolved) {
+ // Applying the filter also wakes the filterTags ->
+ // searchQuery watchers, which queue a debounced
+ // re-search. Let them run, then drop the timer: the
+ // load below already carries the filter, so a second
+ // identical fetch 300ms later is pure waste.
+ await nextTick();
+ clearTimeout(searchDebounceTimer.value);
+ } else {
+ labelDeepLinkPending.value = false;
+ }
+ }
+
// Load initial data
await Promise.all([
- recordingsComposable.loadRecordings(),
- recordingsComposable.loadTags(),
+ recordingsComposable.loadRecordings(1, false, searchQuery.value),
+ ...(deepLinkLabelName ? [] : [recordingsComposable.loadTags()]),
recordingsComposable.loadFolders(),
recordingsComposable.loadSpeakers(),
loadTokenBudget()
]);
+ // The viewer has no label by that name (wrong case is fine,
+ // a typo or someone else's private tag is not). Say so rather
+ // than let an unfiltered list masquerade as the label's
+ // contents, and drop the dead path from the address bar.
+ if (deepLinkLabelName && !labelDeepLinkResolved) {
+ showToast(`No label named "${deepLinkLabelName}"`, 'fa-tag', 4000, 'error');
+ syncAddressBar();
+ }
+
// Now open the upload modal. The pending flag (set above)
// prevents the auto-selected recording's selectRecording() from
// closing it once its fetch resolves.
diff --git a/static/js/modules/composables/recordings-label-filter.test.js b/static/js/modules/composables/recordings-label-filter.test.js
new file mode 100644
index 00000000..4041c56a
--- /dev/null
+++ b/static/js/modules/composables/recordings-label-filter.test.js
@@ -0,0 +1,195 @@
+/**
+ * The /label/<name> deep link, on the composable side.
+ *
+ * Two behaviours are load-bearing for the feature and easy to break:
+ * 1. filterByLabelName resolves a name to every tag id that carries it and
+ * applies them as the tag filter, reporting whether it found anything.
+ * 2. loadRecordings must NOT auto-select the last viewed recording on the
+ * load that follows a label deep link — doing so opens the detail view
+ * and rewrites the address bar to /recordings/<id>, losing the link.
+ *
+ * useRecordings only ever touches `.value`, so plain `{ value }` objects
+ * stand in for refs and no Vue runtime is needed.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useRecordings } from './recordings.js';
+
+const ref = (value) => ({ value });
+
+const tag = (id, name) => ({ id, name });
+
+function makeState(overrides = {}) {
+ return {
+ recordings: ref([]),
+ selectedRecording: ref(null),
+ isLoadingRecordings: ref(false),
+ isLoadingMore: ref(false),
+ currentPage: ref(1),
+ perPage: ref(25),
+ totalRecordings: ref(0),
+ totalPages: ref(1),
+ hasNextPage: ref(false),
+ hasPrevPage: ref(false),
+ showSharedWithMe: ref(false),
+ showArchivedRecordings: ref(false),
+ searchQuery: ref(''),
+ searchDebounceTimer: ref(null),
+ filterTags: ref([]),
+ filterSpeakers: ref([]),
+ filterDatePreset: ref(''),
+ filterDateRange: ref({ start: '', end: '' }),
+ filterTextQuery: ref(''),
+ filterStarred: ref(false),
+ filterInbox: ref(false),
+ filterNeedsTranscription: ref(false),
+ filterNeedsSummary: ref(false),
+ filterNeedsSpeakers: ref(false),
+ filterFolder: ref(''),
+ sortBy: ref('created_at'),
+ availableTags: ref([]),
+ availableSpeakers: ref([]),
+ availableFolders: ref([]),
+ selectedTagIds: ref([]),
+ uploadLanguage: ref(''),
+ uploadMinSpeakers: ref(null),
+ uploadMaxSpeakers: ref(null),
+ uploadHotwords: ref(''),
+ uploadInitialPrompt: ref(''),
+ useAsrEndpoint: ref(false),
+ connectorSupportsDiarization: ref(false),
+ globalError: ref(null),
+ uploadQueue: ref([]),
+ isProcessingActive: ref(false),
+ currentView: ref('recording'),
+ showUploadModal: ref(false),
+ uploadDeepLinkPending: ref(false),
+ labelDeepLinkPending: ref(false),
+ isMobileScreen: ref(false),
+ isSidebarCollapsed: ref(false),
+ isRecording: ref(false),
+ audioBlobURL: ref(null),
+ speakerColorMap: ref({}),
+ incognitoRecording: ref(null),
+ ...overrides
+ };
+}
+
+function setup(overrides) {
+ const state = makeState(overrides);
+ const utils = { setGlobalError: vi.fn(), showToast: vi.fn() };
+ return { state, utils, composable: useRecordings(state, utils, {}) };
+}
+
+/** One page of results, so loadRecordings takes its normal path. */
+function stubFetchReturning(recordings) {
+ const fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ recordings,
+ pagination: {
+ page: 1, per_page: 25, total: recordings.length,
+ total_pages: 1, has_next: false, has_prev: false
+ }
+ })
+ });
+ globalThis.fetch = fetch;
+ return fetch;
+}
+
+let getItem;
+
+beforeEach(() => {
+ getItem = vi.fn().mockReturnValue(null);
+ globalThis.localStorage = { getItem, setItem: vi.fn(), removeItem: vi.fn() };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ delete globalThis.fetch;
+ delete globalThis.localStorage;
+});
+
+describe('filterByLabelName', () => {
+ it('applies every tag that carries the name, so the link is their union', () => {
+ const { state, composable } = setup({
+ availableTags: ref([tag(1, 'foo'), tag(2, 'foobar'), tag(3, 'FOO')])
+ });
+
+ expect(composable.filterByLabelName('foo')).toBe(true);
+ expect(state.filterTags.value).toEqual([1, 3]);
+ });
+
+ it('matches case-insensitively and drives the tag: search token', () => {
+ const { state, composable } = setup({
+ availableTags: ref([tag(3, 'Team Sync')])
+ });
+
+ expect(composable.filterByLabelName('team sync')).toBe(true);
+ expect(state.filterTags.value).toEqual([3]);
+ // Spaces travel as underscores in the search syntax; the server maps
+ // them back and matches the name exactly.
+ expect(state.searchQuery.value).toBe('tag:Team_Sync');
+ });
+
+ it('reports an unknown label instead of silently showing everything', () => {
+ const { state, composable } = setup({
+ availableTags: ref([tag(1, 'foo')])
+ });
+
+ expect(composable.filterByLabelName('nope')).toBe(false);
+ expect(state.filterTags.value).toEqual([]);
+ expect(state.searchQuery.value).toBe('');
+ });
+
+ it('treats a blank name as no label', () => {
+ const { composable } = setup({ availableTags: ref([tag(1, 'foo')]) });
+ expect(composable.filterByLabelName(' ')).toBe(false);
+ });
+});
+
+describe('loadRecordings auto-selection after a label deep link', () => {
+ it('skips the auto-select so the label list is what the user lands on', async () => {
+ const { state, composable } = setup({ labelDeepLinkPending: ref(true) });
+ stubFetchReturning([{ id: 7, title: 'tagged' }]);
+
+ await composable.loadRecordings(1, false, 'tag:foo');
+
+ expect(getItem).not.toHaveBeenCalledWith('lastSelectedRecordingId');
+ expect(state.selectedRecording.value).toBeNull();
+ expect(state.recordings.value).toHaveLength(1);
+ });
+
+ it('consumes the flag, so the next load behaves normally', async () => {
+ const { state, composable } = setup({ labelDeepLinkPending: ref(true) });
+ stubFetchReturning([{ id: 7, title: 'tagged' }]);
+
+ await composable.loadRecordings(1, false, 'tag:foo');
+ expect(state.labelDeepLinkPending.value).toBe(false);
+
+ await composable.loadRecordings(1, false, 'tag:foo');
+ expect(getItem).toHaveBeenCalledWith('lastSelectedRecordingId');
+ });
+
+ it('still auto-selects on an ordinary load', async () => {
+ const { composable } = setup();
+ stubFetchReturning([{ id: 7, title: 'tagged' }]);
+
+ await composable.loadRecordings();
+
+ expect(getItem).toHaveBeenCalledWith('lastSelectedRecordingId');
+ });
+
+ it('leaves an appending load (infinite scroll) untouched', async () => {
+ const { state, composable } = setup({ labelDeepLinkPending: ref(true) });
+ stubFetchReturning([{ id: 8, title: 'page two' }]);
+ state.recordings.value = [{ id: 7, title: 'page one' }];
+
+ await composable.loadRecordings(2, true, 'tag:foo');
+
+ // append never auto-selects, and must not burn the one-shot flag.
+ expect(state.recordings.value).toHaveLength(2);
+ expect(state.labelDeepLinkPending.value).toBe(true);
+ });
+});
diff --git a/static/js/modules/composables/recordings.js b/static/js/modules/composables/recordings.js
index a1d06301..386e539d 100644
--- a/static/js/modules/composables/recordings.js
+++ b/static/js/modules/composables/recordings.js
@@ -4,6 +4,7 @@
*/
import * as IncognitoStorage from '../db/incognito-storage.js';
+import { matchTagsByLabelName } from '../utils/label-links.js';
export function useRecordings(state, utils, reprocessComposable) {
const {
@@ -14,7 +15,7 @@ export function useRecordings(state, utils, reprocessComposable) {
filterStarred, filterInbox, filterNeedsTranscription, filterNeedsSummary, filterNeedsSpeakers,
filterFolder, sortBy,
availableTags, availableSpeakers, availableFolders, selectedTagIds, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers, uploadHotwords, uploadInitialPrompt,
- useAsrEndpoint, connectorSupportsDiarization, globalError, uploadQueue, isProcessingActive, currentView, showUploadModal, uploadDeepLinkPending,
+ useAsrEndpoint, connectorSupportsDiarization, globalError, uploadQueue, isProcessingActive, currentView, showUploadModal, uploadDeepLinkPending, labelDeepLinkPending,
isMobileScreen, isSidebarCollapsed, isRecording, audioBlobURL,
speakerColorMap,
// Incognito mode
@@ -89,11 +90,20 @@ export function useRecordings(state, utils, reprocessComposable) {
recordings.value = [...recordings.value, ...recordingsList];
} else {
recordings.value = recordingsList;
- const lastRecordingId = localStorage.getItem('lastSelectedRecordingId');
- if (lastRecordingId && recordingsList.length > 0) {
- const recordingToSelect = recordingsList.find(r => r.id == lastRecordingId);
- if (recordingToSelect) {
- selectRecording(recordingToSelect);
+ // Arriving via /label/<name> means the user asked for the
+ // list of that label, not for a recording. Auto-selecting the
+ // last viewed one here would open the detail view and rewrite
+ // the address bar to /recordings/<id>, losing the label link.
+ // Consume the one-shot flag so later loads behave normally.
+ if (labelDeepLinkPending && labelDeepLinkPending.value) {
+ labelDeepLinkPending.value = false;
+ } else {
+ const lastRecordingId = localStorage.getItem('lastSelectedRecordingId');
+ if (lastRecordingId && recordingsList.length > 0) {
+ const recordingToSelect = recordingsList.find(r => r.id == lastRecordingId);
+ if (recordingToSelect) {
+ selectRecording(recordingToSelect);
+ }
}
}
}
@@ -383,6 +393,19 @@ export function useRecordings(state, utils, reprocessComposable) {
applyAdvancedFilters();
};
+ // Filter by a label given only its name, used by the /label/<name> deep
+ // link. Every accessible tag with that name is included, so the result is
+ // their union (see utils/label-links.js on why one name can be several
+ // tags). Returns false when the viewer has no such label, so the caller
+ // can say so instead of silently showing them everything.
+ const filterByLabelName = (name) => {
+ const matches = matchTagsByLabelName(name, availableTags.value);
+ if (matches.length === 0) return false;
+ filterTags.value = matches.map(tag => tag.id);
+ applyAdvancedFilters();
+ return true;
+ };
+
const buildSearchQuery = () => {
let query = [];
@@ -514,6 +537,7 @@ export function useRecordings(state, utils, reprocessComposable) {
getRecordingTags,
getAvailableTagsForRecording,
filterByTag,
+ filterByLabelName,
buildSearchQuery,
applyAdvancedFilters,
clearAllFilters,
diff --git a/static/js/modules/utils/index.js b/static/js/modules/utils/index.js
index ae213188..d2f0c601 100644
--- a/static/js/modules/utils/index.js
+++ b/static/js/modules/utils/index.js
@@ -7,3 +7,4 @@ export * from './dates.js';
export { createApiClient } from './api.js';
export { showToast } from './toast.js';
export { getContrastTextColor } from './colors.js';
+export { labelPathForFilter, matchTagsByLabelName, parseLabelPath } from './label-links.js';
diff --git a/static/js/modules/utils/label-links.js b/static/js/modules/utils/label-links.js
new file mode 100644
index 00000000..b48d569f
--- /dev/null
+++ b/static/js/modules/utils/label-links.js
@@ -0,0 +1,65 @@
+/**
+ * /label/<name> deep links.
+ *
+ * A label link points at a group of recordings the way /recordings/<id> points
+ * at a single one, so a tag can be hyperlinked and shared. The server only
+ * serves the SPA shell for these paths; everything below resolves the name
+ * against the tags the viewer can actually see, which is why two people
+ * opening the same link can legitimately see different recordings.
+ *
+ * Tag names are not unique across that set: a user holds at most one tag per
+ * name, but a group tag belongs to the admin who created it, so a member can
+ * see both their own "foo" and the group's "foo". A label name therefore
+ * resolves to a set of tag ids, and the link means their union.
+ */
+
+const normalize = (name) => String(name ?? '').trim().toLowerCase();
+
+/**
+ * Every tag named exactly `name`, ignoring case and surrounding whitespace.
+ * Exact rather than substring: the link says "foo", so "foobar" is a
+ * different label and must not ride along.
+ */
+export const matchTagsByLabelName = (name, availableTags = []) => {
+ const wanted = normalize(name);
+ if (!wanted) return [];
+ return (availableTags || []).filter(tag => tag && normalize(tag.name) === wanted);
+};
+
+/**
+ * The label name carried by a pathname, or null when it isn't a label link.
+ */
+export const parseLabelPath = (pathname) => {
+ const match = String(pathname || '').match(/^\/label\/([^/]+)\/?$/);
+ if (!match) return null;
+ let name;
+ try {
+ name = decodeURIComponent(match[1]);
+ } catch (_) {
+ return null; // malformed %-escape: not a link we can honour
+ }
+ return name.trim() || null;
+};
+
+/**
+ * The path that represents a tag filter, or null when the filter can't be
+ * expressed as one label link — nothing selected, or several distinct names,
+ * which no single /label/<name> covers.
+ *
+ * A name containing '/' is also refused: werkzeug decodes %2F before routing,
+ * so such a link would 404, and putting a dead URL in the address bar is
+ * worse than leaving it alone.
+ */
+export const labelPathForFilter = (filterTagIds = [], availableTags = []) => {
+ const names = new Set(
+ (filterTagIds || [])
+ .map(id => (availableTags || []).find(tag => tag && tag.id === id))
+ .filter(Boolean)
+ .map(tag => String(tag.name ?? '').trim())
+ .filter(Boolean)
+ );
+ if (names.size !== 1) return null;
+ const [name] = [...names];
+ if (name.includes('/')) return null;
+ return `/label/${encodeURIComponent(name)}`;
+};
diff --git a/static/js/modules/utils/label-links.test.js b/static/js/modules/utils/label-links.test.js
new file mode 100644
index 00000000..27399f28
--- /dev/null
+++ b/static/js/modules/utils/label-links.test.js
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ labelPathForFilter,
+ matchTagsByLabelName,
+ parseLabelPath
+} from './label-links.js';
+
+const tag = (id, name) => ({ id, name });
+
+describe('matchTagsByLabelName', () => {
+ const tags = [
+ tag(1, 'foo'),
+ tag(2, 'foobar'),
+ tag(3, 'Team Sync'),
+ tag(4, 'FOO') // e.g. a group tag alongside the personal one
+ ];
+
+ it('matches exactly, so foo never drags in foobar', () => {
+ expect(matchTagsByLabelName('foo', tags).map(t => t.id)).toEqual([1, 4]);
+ });
+
+ it('ignores case and surrounding whitespace on both sides', () => {
+ expect(matchTagsByLabelName(' TEAM sync ', [tag(9, ' Team Sync ')]))
+ .toEqual([tag(9, ' Team Sync ')]);
+ });
+
+ it('returns every tag sharing the name so the link means their union', () => {
+ expect(matchTagsByLabelName('FoO', tags)).toHaveLength(2);
+ });
+
+ it('returns nothing for an unknown, blank, or missing name', () => {
+ expect(matchTagsByLabelName('nope', tags)).toEqual([]);
+ expect(matchTagsByLabelName(' ', tags)).toEqual([]);
+ expect(matchTagsByLabelName(null, tags)).toEqual([]);
+ expect(matchTagsByLabelName(undefined, undefined)).toEqual([]);
+ });
+
+ it('survives malformed tag entries', () => {
+ expect(matchTagsByLabelName('foo', [null, {}, tag(1, 'foo')]).map(t => t.id))
+ .toEqual([1]);
+ });
+});
+
+describe('parseLabelPath', () => {
+ it('reads the name out of a label path', () => {
+ expect(parseLabelPath('/label/foo')).toBe('foo');
+ expect(parseLabelPath('/label/foo/')).toBe('foo');
+ });
+
+ it('decodes percent-escapes, so spaced names round-trip', () => {
+ expect(parseLabelPath('/label/Team%20Sync')).toBe('Team Sync');
+ expect(parseLabelPath('/label/caf%C3%A9')).toBe('café');
+ });
+
+ it('leaves + alone: it is a literal plus in a path segment, not a space', () => {
+ expect(parseLabelPath('/label/a+b')).toBe('a+b');
+ });
+
+ it('is not fooled by other routes', () => {
+ expect(parseLabelPath('/')).toBeNull();
+ expect(parseLabelPath('/recordings/12')).toBeNull();
+ expect(parseLabelPath('/label')).toBeNull();
+ expect(parseLabelPath('/label/')).toBeNull();
+ expect(parseLabelPath('/label/a/b')).toBeNull();
+ expect(parseLabelPath('/labels/foo')).toBeNull();
+ });
+
+ it('treats a malformed escape as no deep link rather than throwing', () => {
+ expect(parseLabelPath('/label/%E0%A4%A')).toBeNull();
+ });
+});
+
+describe('labelPathForFilter', () => {
+ const tags = [tag(1, 'foo'), tag(2, 'FOO'), tag(3, 'Team Sync'), tag(4, 'bar')];
+
+ it('links a single selected tag', () => {
+ expect(labelPathForFilter([1], tags)).toBe('/label/foo');
+ });
+
+ it('percent-encodes so the path stays a single segment', () => {
+ expect(labelPathForFilter([3], tags)).toBe('/label/Team%20Sync');
+ });
+
+ it('links several tags that share one name, since the link is their union', () => {
+ // Distinct ids, one name — exactly what /label/foo resolves back to.
+ expect(labelPathForFilter([1, 2], [tag(1, 'foo'), tag(2, 'foo')]))
+ .toBe('/label/foo');
+ });
+
+ it('refuses two distinct names: no single label link covers them', () => {
+ expect(labelPathForFilter([1, 4], tags)).toBeNull();
+ });
+
+ it('refuses an empty or unresolvable filter', () => {
+ expect(labelPathForFilter([], tags)).toBeNull();
+ expect(labelPathForFilter([99], tags)).toBeNull();
+ expect(labelPathForFilter(undefined, undefined)).toBeNull();
+ });
+
+ it('refuses a name with a slash, which would 404 rather than route', () => {
+ expect(labelPathForFilter([5], [tag(5, 'q1/q2')])).toBeNull();
+ });
+
+ it('round-trips with parseLabelPath for names needing encoding', () => {
+ for (const name of ['foo', 'Team Sync', 'café', 'a+b', '100%']) {
+ const path = labelPathForFilter([7], [tag(7, name)]);
+ expect(parseLabelPath(path)).toBe(name);
+ }
+ });
+});
diff --git a/tests/test_label_urls.py b/tests/test_label_urls.py
new file mode 100644
index 00000000..e43cfbef
--- /dev/null
+++ b/tests/test_label_urls.py
@@ -0,0 +1,330 @@
+"""Behaviour tests for the /label/<name> deep link.
+
+/label/foo is the label-scoped counterpart of the /recordings/<id> deep link:
+the server just serves the SPA shell, and the frontend resolves the name
+against the viewer's own accessible tags and applies it as the tag filter, so
+one URL points at a group of recordings.
+
+Two things are therefore server-side and testable here:
+ - the route itself exists, is login-gated, and serves the shell for the
+ name shapes a real tag can have (plain, spaced, cased, non-existent);
+ - the tag filter behind it (``?q=tag:<name>`` on /api/recordings) matches a
+ tag name EXACTLY and case-insensitively, so /label/foo cannot quietly
+ include recordings tagged "foobar".
+
+Harness notes follow tests/test_cov_recordings_read.py: all DB setup happens
+inside a short-lived ``_db()`` context that is exited before any client
+request, because Flask-Login caches the resolved ``current_user`` on the
+application context.
+
+Run:
+ python -m pytest tests/test_label_urls.py -q
+"""
+
+import os
+import sys
+import uuid
+import tempfile
+from contextlib import contextmanager
+from urllib.parse import quote
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+# Standalone safety net (conftest.py already sets these under pytest).
+if "SQLALCHEMY_DATABASE_URI" not in os.environ:
+ _D = tempfile.mkdtemp(prefix="speakr_label_urls_")
+ os.environ["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{os.path.join(_D, 'test.db')}"
+ os.environ.setdefault("UPLOAD_FOLDER", os.path.join(_D, "uploads"))
+ os.environ.setdefault("SECRET_KEY", "pytest-secret-key")
+ os.environ.setdefault("ENABLE_AUTO_PROCESSING", "false")
+ os.environ.setdefault("TEXT_MODEL_API_KEY", "test-key")
+ os.environ.setdefault("TRANSCRIPTION_API_KEY", "test-key")
+ os.environ.setdefault("TRANSCRIPTION_BASE_URL", "https://api.openai.com/v1")
+
+from src.app import app, db
+from src.models import User, Recording
+from src.models.organization import (
+ Group,
+ GroupMembership,
+ RecordingTag,
+ Tag,
+)
+
+app.config["WTF_CSRF_ENABLED"] = False
+
+
+# --------------------------------------------------------------------------- #
+# Helpers
+# --------------------------------------------------------------------------- #
+
+_PREFIX = "labelurl"
+
+
+@contextmanager
+def _db():
+ """Short-lived app context for DB work; exit before any HTTP request."""
+ with app.app_context():
+ yield
+
+
+def make_user():
+ suffix = uuid.uuid4().hex[:10]
+ user = User(
+ username=f"{_PREFIX}_{suffix}",
+ email=f"{_PREFIX}_{suffix}@test.local",
+ password="x",
+ )
+ db.session.add(user)
+ db.session.commit()
+ return user
+
+
+def make_recording(user, *, title="rec"):
+ rec = Recording(
+ audio_path="local://labelurl/audio.mp3",
+ original_filename="audio.mp3",
+ title=title,
+ status="COMPLETED",
+ transcription="hello world this is a transcript",
+ summary="a summary",
+ user_id=user.id,
+ mime_type="audio/mpeg",
+ )
+ db.session.add(rec)
+ db.session.commit()
+ return rec
+
+
+def tag_recording(recording, tag):
+ db.session.add(RecordingTag(recording_id=recording.id, tag_id=tag.id, order=1))
+ db.session.commit()
+
+
+def login(client, user_id):
+ with client.session_transaction() as sess:
+ sess["_user_id"] = str(user_id)
+ sess["_fresh"] = True
+
+
+def new_client():
+ return app.test_client()
+
+
+def ids_for_label(client, label_name):
+ """IDs the list endpoint returns for the filter /label/<name> produces.
+
+ The frontend turns a selected tag into the ``tag:<name>`` search token
+ (spaces encoded as underscores), so this mirrors what the browser sends.
+ """
+ token = label_name.replace(" ", "_")
+ resp = client.get(f"/api/recordings?q=tag:{quote(token)}&per_page=100")
+ assert resp.status_code == 200
+ return {r["id"] for r in resp.get_json()["recordings"]}
+
+
+def owner():
+ with _db():
+ return make_user().id
+
+
+# --------------------------------------------------------------------------- #
+# The route
+# --------------------------------------------------------------------------- #
+
+def test_label_url_serves_the_spa_shell(owner):
+ """/label/<name> is a real route and renders the app, like /recordings/<id>."""
+ with _db():
+ u = db.session.get(User, owner)
+ tag = Tag(name=f"{_PREFIX}shell", user_id=u.id)
+ db.session.add(tag)
+ db.session.commit()
+
+ c = new_client()
+ login(c, owner)
+ resp = c.get(f"/label/{_PREFIX}shell")
+ assert resp.status_code == 200
+ # Same shell the '/' route serves — the label is resolved client-side.
+ assert resp.data == c.get("/").data
+
+
+def test_label_url_accepts_spaces_and_mixed_case(owner):
+ """A percent-encoded, differently-cased name still reaches the shell."""
+ c = new_client()
+ login(c, owner)
+ assert c.get(f"/label/{quote('Team Sync')}").status_code == 200
+ assert c.get("/label/TEAM+SYNC").status_code == 200
+
+
+def test_unknown_label_still_serves_the_shell(owner):
+ """The server doesn't know the viewer's tags here; the frontend reports it.
+
+ Serving the shell keeps tag-access logic in one place (the tags API) and
+ lets the app say "No label named X" in context instead of showing a bare
+ 404 page.
+ """
+ c = new_client()
+ login(c, owner)
+ assert c.get(f"/label/{_PREFIX}-does-not-exist").status_code == 200
+
+
+def test_label_url_requires_login():
+ c = new_client()
+ resp = c.get("/label/anything")
+ assert resp.status_code in (302, 401)
+
+
+# --------------------------------------------------------------------------- #
+# The filter behind it
+# --------------------------------------------------------------------------- #
+
+def test_label_filter_is_exact_not_substring(owner):
+ """/label/foo must not drag in recordings tagged 'foobar'."""
+ base = f"{_PREFIX}{uuid.uuid4().hex[:6]}"
+ with _db():
+ u = db.session.get(User, owner)
+ exact = Tag(name=base, user_id=u.id)
+ longer = Tag(name=f"{base}bar", user_id=u.id)
+ db.session.add_all([exact, longer])
+ db.session.commit()
+
+ wanted = make_recording(u, title="exactly-foo")
+ unwanted = make_recording(u, title="foobar-only")
+ tag_recording(wanted, exact)
+ tag_recording(unwanted, longer)
+ wanted_id, unwanted_id = wanted.id, unwanted.id
+
+ c = new_client()
+ login(c, owner)
+ ids = ids_for_label(c, base)
+ assert wanted_id in ids
+ assert unwanted_id not in ids
+
+
+def test_label_filter_is_case_insensitive(owner):
+ base = f"{_PREFIX}Case{uuid.uuid4().hex[:6]}"
+ with _db():
+ u = db.session.get(User, owner)
+ tag = Tag(name=base, user_id=u.id)
+ db.session.add(tag)
+ db.session.commit()
+ rec = make_recording(u, title="cased")
+ tag_recording(rec, tag)
+ rec_id = rec.id
+
+ c = new_client()
+ login(c, owner)
+ assert rec_id in ids_for_label(c, base.lower())
+ assert rec_id in ids_for_label(c, base.upper())
+
+
+def test_label_filter_matches_a_name_containing_spaces(owner):
+ name = f"{_PREFIX} spaced {uuid.uuid4().hex[:6]}"
+ with _db():
+ u = db.session.get(User, owner)
+ tag = Tag(name=name, user_id=u.id)
+ db.session.add(tag)
+ db.session.commit()
+ rec = make_recording(u, title="spaced")
+ other = make_recording(u, title="untagged")
+ tag_recording(rec, tag)
+ rec_id, other_id = rec.id, other.id
+
+ c = new_client()
+ login(c, owner)
+ ids = ids_for_label(c, name)
+ assert rec_id in ids
+ assert other_id not in ids
+
+
+def test_label_filter_unions_a_personal_and_a_group_tag_of_the_same_name(owner):
+ """Tag names aren't unique across the tags one viewer can see.
+
+ A user can hold only one tag per name (_user_tag_uc on name+user_id), but
+ a group tag belongs to the admin who created it — so a member with a
+ personal tag of the same name sees two distinct "foo" tags. /label/<name>
+ covers their union, which is what the frontend asks for by putting every
+ matching tag id in the filter.
+ """
+ name = f"{_PREFIX}dual{uuid.uuid4().hex[:6]}"
+ with _db():
+ u = db.session.get(User, owner)
+ admin = make_user()
+ group = Group(name=f"{_PREFIX}-group-{uuid.uuid4().hex[:8]}")
+ db.session.add(group)
+ db.session.commit()
+ db.session.add_all([
+ GroupMembership(group_id=group.id, user_id=admin.id, role="admin"),
+ GroupMembership(group_id=group.id, user_id=u.id, role="member"),
+ ])
+
+ personal = Tag(name=name, user_id=u.id)
+ group_tag = Tag(name=name, user_id=admin.id, group_id=group.id)
+ db.session.add_all([personal, group_tag])
+ db.session.commit()
+
+ # Both recordings are the viewer's own; only the tag differs, so the
+ # assertion is about tag resolution and not about sharing.
+ via_personal = make_recording(u, title="via-personal")
+ via_group = make_recording(u, title="via-group")
+ tag_recording(via_personal, personal)
+ tag_recording(via_group, group_tag)
+ personal_id, group_rec_id = via_personal.id, via_group.id
+ group_db_id = group.id
+
+ c = new_client()
+ login(c, owner)
+ # The frontend emits one tag: token per matching tag id; both resolve to
+ # the same name, so a single token already covers the union.
+ ids = ids_for_label(c, name)
+ assert personal_id in ids
+ assert group_rec_id in ids
+
+ with _db():
+ GroupMembership.query.filter_by(group_id=group_db_id).delete()
+ db.session.delete(db.session.get(Group, group_db_id))
+ db.session.commit()
+
+
+def test_label_filter_does_not_leak_another_users_recordings(owner):
+ """Same label name, two users: each only ever sees their own recordings."""
+ name = f"{_PREFIX}shared{uuid.uuid4().hex[:6]}"
+ with _db():
+ mine = db.session.get(User, owner)
+ theirs = make_user()
+ my_tag = Tag(name=name, user_id=mine.id)
+ their_tag = Tag(name=name, user_id=theirs.id)
+ db.session.add_all([my_tag, their_tag])
+ db.session.commit()
+
+ my_rec = make_recording(mine, title="mine")
+ their_rec = make_recording(theirs, title="theirs")
+ tag_recording(my_rec, my_tag)
+ tag_recording(their_rec, their_tag)
+ my_id, their_id = my_rec.id, their_rec.id
+
+ c = new_client()
+ login(c, owner)
+ ids = ids_for_label(c, name)
+ assert my_id in ids
+ assert their_id not in ids
+
+
+# --------------------------------------------------------------------------- #
+# Module-level cleanup
+# --------------------------------------------------------------------------- #
+
+def teardown_module(module):
+ with app.app_context():
+ for u in User.query.filter(User.username.like(f"{_PREFIX}_%")).all():
+ for r in Recording.query.filter_by(user_id=u.id).all():
+ RecordingTag.query.filter_by(recording_id=r.id).delete()
+ db.session.delete(r)
+ Tag.query.filter_by(user_id=u.id).delete()
+ GroupMembership.query.filter_by(user_id=u.id).delete()
+ db.session.delete(u)
+ for g in Group.query.filter(Group.name.like(f"{_PREFIX}-group-%")).all():
+ db.session.delete(g)
+ db.session.commit()