feat(commands): multi-select ordered command pipeline with step reordering and single-pass composition (AI-05, AI-07)

This commit is contained in:
Yun Chan 2026-10-31 02:54:54 +09:00
parent f49acf0105
commit 10af20a0ad
157 changed files with 29455 additions and 913 deletions

View file

@ -1,4 +1,5 @@
import type { RealtimeChannel } from '@supabase/supabase-js'
import { parseTranscriptLines } from '@d3ro/core/meeting-transcript'
import type {
D3roSupabaseClient,
Meeting,
@ -65,6 +66,16 @@ export interface MeetingTranscriptView {
text: string
}
export interface MeetingSeekableSegment {
id: string
timestampMs: number
durationMs: number | null
speaker: string | null
text: string
edited: boolean
timed: boolean
}
export type MeetingServiceErrorCode =
| 'auth'
| 'conflict'
@ -256,6 +267,103 @@ export function buildMeetingTranscriptView(
return { source: 'empty', text: '' }
}
const TIMESTAMP_TOKEN_PATTERN = /^\[?(?:(\d{1,2}):)?(\d{1,3}):(\d{2})\]?$/
export function parseTimestampTokenToMs(token: string): number | null {
const match = TIMESTAMP_TOKEN_PATTERN.exec(token.trim())
if (!match) return null
const hours = match[1] !== undefined ? Number(match[1]) : 0
const minutes = Number(match[2])
const seconds = Number(match[3])
if (
!Number.isFinite(hours)
|| !Number.isFinite(minutes)
|| !Number.isFinite(seconds)
|| seconds >= 60
|| (match[1] !== undefined && minutes >= 60)
) {
return null
}
return ((hours * 3_600) + (minutes * 60) + seconds) * 1_000
}
export function parseTranscriptSeekSegments(
meeting: Pick<Meeting, 'edited_transcript' | 'raw_transcript'>,
transcripts: readonly Transcript[],
): MeetingSeekableSegment[] {
if (transcripts.length > 0) {
return transcripts
.slice()
.sort((left, right) => left.segment_index - right.segment_index)
.map((segment) => ({
id: segment.id,
timestampMs: Math.max(0, segment.timestamp_ms),
durationMs: segment.duration_ms,
speaker: segment.speaker,
text: segment.text,
edited: segment.edited,
timed: true,
}))
}
const rawText = meeting.edited_transcript?.trim()
? meeting.edited_transcript
: meeting.raw_transcript?.trim()
? meeting.raw_transcript
: ''
if (!rawText) return []
return parseTranscriptLines(rawText).map((line, index) => ({
id: `line-${index}`,
timestampMs: Math.max(0, line.timestampMs),
durationMs: null,
speaker: line.speaker,
text: line.text,
edited: false,
timed: line.timed,
}))
}
export function findActiveTranscriptSegmentId(
segments: readonly Pick<MeetingSeekableSegment, 'id' | 'timestampMs' | 'durationMs' | 'timed'>[],
currentPositionMs: number | null | undefined,
): string | null {
if (
currentPositionMs === null
|| currentPositionMs === undefined
|| !Number.isFinite(currentPositionMs)
|| currentPositionMs < 0
|| segments.length === 0
) {
return null
}
const timedSegments = segments
.filter((segment) => segment.timed)
.slice()
.sort((left, right) => left.timestampMs - right.timestampMs)
if (timedSegments.length === 0) return null
let activeId: string | null = null
for (let index = 0; index < timedSegments.length; index += 1) {
const current = timedSegments[index]
const next = timedSegments[index + 1]
if (currentPositionMs < current.timestampMs) {
break
}
const endBound = next !== undefined
? next.timestampMs
: current.durationMs !== null && current.durationMs > 0
? current.timestampMs + current.durationMs
: Number.POSITIVE_INFINITY
if (currentPositionMs <= endBound) {
activeId = current.id
}
}
return activeId
}
function assertMeetingRow(row: Meeting | null, expectedId?: string): Meeting {
if (row === null) {
throw new MeetingServiceError('not-found', 'Meeting was not found')

View file

@ -17,9 +17,11 @@ export type NotificationConfigurationReason =
| 'native-module-unavailable'
| 'unsupported-platform'
export type MobilePushProvider = 'fcm' | 'apns'
export interface NativeNotificationStatus {
configured: boolean
provider: 'fcm'
provider: MobilePushProvider
reason: NotificationConfigurationReason
permission: NotificationPermissionStatus
registrationId: string | null
@ -49,12 +51,16 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
export function resolveNativePushProvider(platform: string = Platform.OS): MobilePushProvider {
return platform === 'ios' ? 'apns' : 'fcm'
}
function normalizeStatus(value: unknown): NativeNotificationStatus {
if (!isRecord(value)) throw new Error('notification_native_status_invalid')
const registrationId = value.registrationId ?? null
if (
typeof value.configured !== 'boolean'
|| value.provider !== 'fcm'
|| (value.provider !== 'fcm' && value.provider !== 'apns')
|| ![
'configured',
'firebase-config-missing',
@ -70,7 +76,7 @@ function normalizeStatus(value: unknown): NativeNotificationStatus {
}
return {
configured: value.configured,
provider: 'fcm',
provider: value.provider as MobilePushProvider,
reason: value.reason as NotificationConfigurationReason,
permission: value.permission as NotificationPermissionStatus,
registrationId,
@ -79,10 +85,11 @@ function normalizeStatus(value: unknown): NativeNotificationStatus {
}
export async function getNativeNotificationStatus(): Promise<NativeNotificationStatus> {
if (Platform.OS !== 'android') {
const provider = resolveNativePushProvider(Platform.OS)
if (Platform.OS !== 'android' && Platform.OS !== 'ios') {
return {
configured: false,
provider: 'fcm',
provider,
reason: 'unsupported-platform',
permission: 'unavailable',
registrationId: null,
@ -92,7 +99,7 @@ export async function getNativeNotificationStatus(): Promise<NativeNotificationS
if (nativeModule === undefined) {
return {
configured: false,
provider: 'fcm',
provider,
reason: 'native-module-unavailable',
permission: 'unavailable',
registrationId: null,

View file

@ -4,6 +4,7 @@ import {
deleteNativePushRegistration,
getNativeNotificationStatus,
getNativePushRegistrationId,
type MobilePushProvider,
type NativeNotificationStatus,
} from './notification-native'
@ -47,6 +48,12 @@ function toServiceError(error: unknown): NotificationServiceError {
return new NotificationServiceError('server')
}
export function resolveDevicePushProvider(
device: Pick<RegisteredDevice, 'platform'>,
): MobilePushProvider {
return device.platform === 'ios' ? 'apns' : 'fcm'
}
export async function registerPushRegistration(
userId: string,
device: RegisteredDevice,
@ -63,10 +70,12 @@ export async function registerPushRegistration(
|| /\s/.test(registrationId)
) throw new NotificationServiceError('native')
const expectedProvider = resolveDevicePushProvider(device)
try {
const { data, error } = await supabase.rpc('register_push_registration', {
push_device_id: device.id,
push_provider: 'fcm',
push_provider: expectedProvider,
registration_id: registrationId,
})
if (error !== null) throw error
@ -74,7 +83,7 @@ export async function registerPushRegistration(
const registeredAt = data.registered_at
if (
data.device_id !== device.id
|| data.provider !== 'fcm'
|| data.provider !== expectedProvider
|| typeof registeredAt !== 'string'
|| !Number.isFinite(Date.parse(registeredAt))
) throw new NotificationServiceError('server')

View file

@ -1,8 +1,9 @@
import type { D3roSupabaseClient, HistoryEntry, Meeting } from '@d3ro/api-client'
import type { D3roSupabaseClient, HistoryEntry, Meeting, Transcript } from '@d3ro/api-client'
import type {
UnifiedSearchResponse,
UnifiedSearchResult,
} from '@d3ro/core/types'
import { formatTranscriptTimestamp } from '@d3ro/core/meeting-transcript'
import { supabase } from '../../lib/supabase'
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
@ -10,10 +11,13 @@ const DEFAULT_LIMIT = 30
const MAX_LIMIT = 50
const MAX_QUERY_LENGTH = 100
const EXCERPT_LENGTH = 180
const MAX_BOUNDED_TEXT_LENGTH = 600
const HISTORY_SEARCH_COLUMNS = 'id,title,original_text,polished_text,summary_text,created_at'
const MEETING_SEARCH_COLUMNS = 'id,title,raw_transcript,edited_transcript,started_at'
const TRANSCRIPT_SEGMENT_SEARCH_COLUMNS = 'id,meeting_id,text,speaker,timestamp_ms,created_at'
const MEETING_META_COLUMNS = 'id,title,started_at'
export type UnifiedSearchServiceErrorCode = 'auth' | 'invalid' | 'network' | 'server'
export type UnifiedSearchServiceErrorCode = 'auth' | 'invalid' | 'network' | 'server' | 'aborted'
export class UnifiedSearchServiceError extends Error {
constructor(
@ -40,22 +44,44 @@ type UnifiedSearchMeetingRow = Pick<
'id' | 'title' | 'raw_transcript' | 'edited_transcript' | 'started_at'
>
export type UnifiedSearchTranscriptSegmentRow = Pick<
Transcript,
'id' | 'meeting_id' | 'text' | 'speaker' | 'timestamp_ms' | 'created_at'
>
export type UnifiedSearchMeetingMetaRow = Pick<
Meeting,
'id' | 'title' | 'started_at'
>
export interface UnifiedSearchSourcePort {
searchRecords: (
userId: string,
query: string,
limit: number,
signal?: AbortSignal,
) => Promise<UnifiedSearchSourcePage<UnifiedSearchHistoryRow>>
searchMeetings: (
query: string,
limit: number,
signal?: AbortSignal,
) => Promise<UnifiedSearchSourcePage<UnifiedSearchMeetingRow>>
searchTranscriptSegments?: (
query: string,
limit: number,
signal?: AbortSignal,
) => Promise<UnifiedSearchSourcePage<UnifiedSearchTranscriptSegmentRow>>
loadMeetingsByIds?: (
meetingIds: readonly string[],
signal?: AbortSignal,
) => Promise<UnifiedSearchMeetingMetaRow[]>
}
export interface MobileUnifiedSearchOptions {
userId: string
query: string
limit?: number
signal?: AbortSignal
}
function client(): D3roSupabaseClient {
@ -149,11 +175,17 @@ function recordResult(row: UnifiedSearchHistoryRow, query: string): UnifiedSearc
}
}
function meetingResult(row: UnifiedSearchMeetingRow, query: string): UnifiedSearchResult {
function meetingResult(
row: UnifiedSearchMeetingRow,
query: string,
segmentMatch?: UnifiedSearchTranscriptSegmentRow,
): UnifiedSearchResult {
const titleMatched = includesQuery(row.title, query)
const matchingTranscript = [row.edited_transcript, row.raw_transcript]
.find((value) => includesQuery(value, query))
const segmentSnippet = segmentMatch ? formatSegmentSnippet(segmentMatch) : null
const preview = matchingTranscript
?? segmentSnippet
?? row.edited_transcript
?? row.raw_transcript
?? row.title
@ -163,11 +195,59 @@ function meetingResult(row: UnifiedSearchMeetingRow, query: string): UnifiedSear
id: row.id,
title: row.title,
excerpt: createMobileSearchExcerpt(preview, query),
matchedField: titleMatched ? 'title' : 'transcript',
matchedField: titleMatched && !matchingTranscript && !segmentSnippet ? 'title' : 'transcript',
occurredAt: occurredAt(row.started_at),
}
}
function formatSegmentSnippet(segment: UnifiedSearchTranscriptSegmentRow): string {
const timestamp = formatTranscriptTimestamp(segment.timestamp_ms)
const speakerPrefix = segment.speaker?.trim() ? `[${segment.speaker.trim()}] ` : ''
return `[${timestamp}] ${speakerPrefix}${segment.text}`
}
function segmentMeetingResult(
segment: UnifiedSearchTranscriptSegmentRow,
meetingMeta: UnifiedSearchMeetingMetaRow | undefined,
query: string,
): UnifiedSearchResult {
return {
source: 'meeting',
id: segment.meeting_id,
title: meetingMeta?.title ?? null,
excerpt: createMobileSearchExcerpt(formatSegmentSnippet(segment), query),
matchedField: 'transcript',
occurredAt: occurredAt(meetingMeta?.started_at ?? segment.created_at),
}
}
export function isUnifiedSearchAbortedError(error: unknown): boolean {
if (error instanceof UnifiedSearchServiceError && error.code === 'aborted') return true
return error instanceof Error && error.name === 'AbortError'
}
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) {
throw new UnifiedSearchServiceError('aborted', 'Unified search request was aborted')
}
}
function withAbortSignal<T>(builder: T, signal?: AbortSignal): T {
if (signal && typeof (builder as { abortSignal?: unknown }).abortSignal === 'function') {
return (builder as unknown as { abortSignal: (s: AbortSignal) => T }).abortSignal(signal)
}
return builder
}
function boundPayloadText(
value: string | null,
query: string,
): string | null {
if (value === null) return null
if (value.length <= MAX_BOUNDED_TEXT_LENGTH) return value
return createMobileSearchExcerpt(value, query, MAX_BOUNDED_TEXT_LENGTH)
}
export function mergeMobileUnifiedSearchResults(
records: readonly UnifiedSearchResult[],
meetings: readonly UnifiedSearchResult[],
@ -178,10 +258,16 @@ export function mergeMobileUnifiedSearchResults(
.slice(0, limit)
}
function toSearchError(error: unknown): UnifiedSearchServiceError {
function toSearchError(error: unknown, signal?: AbortSignal): UnifiedSearchServiceError {
if (signal?.aborted || isUnifiedSearchAbortedError(error)) {
return new UnifiedSearchServiceError('aborted', 'Unified search request was aborted')
}
if (error instanceof UnifiedSearchServiceError) return error
const candidate = error as { code?: unknown; message?: unknown }
const candidate = error as { code?: unknown; message?: unknown; name?: unknown }
if (candidate?.name === 'AbortError') {
return new UnifiedSearchServiceError('aborted', 'Unified search request was aborted')
}
const code = typeof candidate?.code === 'string' ? candidate.code : ''
const message = typeof candidate?.message === 'string'
? candidate.message
@ -205,35 +291,90 @@ export function createSupabaseUnifiedSearchSource(
searchClient: D3roSupabaseClient,
): UnifiedSearchSourcePort {
return {
async searchRecords(userId, query, limit) {
async searchRecords(userId, query, limit, signal) {
throwIfAborted(signal)
const pattern = createPostgrestLikePattern(query)
const { data, error, count } = await searchClient
.from('history')
.select(HISTORY_SEARCH_COLUMNS, { count: 'exact' })
.eq('user_id', userId)
.or(
`title.ilike.${pattern},original_text.ilike.${pattern},polished_text.ilike.${pattern},summary_text.ilike.${pattern}`,
)
.order('created_at', { ascending: false })
.order('id', { ascending: false })
.limit(limit)
const queryBuilder = withAbortSignal(
searchClient
.from('history')
.select(HISTORY_SEARCH_COLUMNS, { count: 'exact' })
.eq('user_id', userId)
.or(
`title.ilike.${pattern},original_text.ilike.${pattern},polished_text.ilike.${pattern},summary_text.ilike.${pattern}`,
)
.order('created_at', { ascending: false })
.order('id', { ascending: false }),
signal,
)
const { data, error, count } = await queryBuilder.limit(limit)
if (error !== null) throw error
return { rows: data ?? [], total: count ?? data?.length ?? 0 }
const rows = (data ?? []).map((row) => ({
...row,
original_text: boundPayloadText(row.original_text, query) ?? '',
polished_text: boundPayloadText(row.polished_text, query),
summary_text: boundPayloadText(row.summary_text, query),
}))
return { rows, total: count ?? rows.length }
},
async searchMeetings(query, limit) {
async searchMeetings(query, limit, signal) {
throwIfAborted(signal)
const pattern = createPostgrestLikePattern(query)
const { data, error, count } = await searchClient
.from('meetings')
.select(MEETING_SEARCH_COLUMNS, { count: 'exact' })
.or(
`title.ilike.${pattern},raw_transcript.ilike.${pattern},edited_transcript.ilike.${pattern}`,
)
.order('started_at', { ascending: false })
.order('id', { ascending: false })
.limit(limit)
const queryBuilder = withAbortSignal(
searchClient
.from('meetings')
.select(MEETING_SEARCH_COLUMNS, { count: 'exact' })
.or(
`title.ilike.${pattern},raw_transcript.ilike.${pattern},edited_transcript.ilike.${pattern}`,
)
.order('started_at', { ascending: false })
.order('id', { ascending: false }),
signal,
)
const { data, error, count } = await queryBuilder.limit(limit)
if (error !== null) throw error
return { rows: data ?? [], total: count ?? data?.length ?? 0 }
const rows = (data ?? []).map((row) => ({
...row,
raw_transcript: boundPayloadText(row.raw_transcript, query),
edited_transcript: boundPayloadText(row.edited_transcript, query),
}))
return { rows, total: count ?? rows.length }
},
async searchTranscriptSegments(query, limit, signal) {
throwIfAborted(signal)
const pattern = createPostgrestLikePattern(query)
const queryBuilder = withAbortSignal(
searchClient
.from('transcripts')
.select(TRANSCRIPT_SEGMENT_SEARCH_COLUMNS, { count: 'exact' })
.or(`text.ilike.${pattern},speaker.ilike.${pattern}`)
.order('timestamp_ms', { ascending: true })
.order('id', { ascending: false }),
signal,
)
const { data, error, count } = await queryBuilder.limit(limit)
if (error !== null) throw error
const rows = (data ?? []).map((row) => ({
...row,
text: boundPayloadText(row.text, query) ?? '',
}))
return { rows, total: count ?? rows.length }
},
async loadMeetingsByIds(meetingIds, signal) {
if (meetingIds.length === 0) return []
throwIfAborted(signal)
const queryBuilder = withAbortSignal(
searchClient
.from('meetings')
.select(MEETING_META_COLUMNS)
.in('id', [...meetingIds]),
signal,
)
const { data, error } = await queryBuilder.limit(meetingIds.length)
if (error !== null) throw error
return data ?? []
},
}
}
@ -249,24 +390,70 @@ export async function searchUnifiedContent(
requireQuery(options.query)
const query = sanitizeUnifiedSearchQuery(options.query)
const limit = normalizeLimit(options.limit)
throwIfAborted(options.signal)
if (query.length === 0) return { query, results: [], total: 0 }
try {
const [recordPage, meetingPage] = await Promise.all([
source.searchRecords(options.userId, query, limit),
source.searchMeetings(query, limit),
const [recordPage, meetingPage, segmentPage] = await Promise.all([
options.signal
? source.searchRecords(options.userId, query, limit, options.signal)
: source.searchRecords(options.userId, query, limit),
options.signal
? source.searchMeetings(query, limit, options.signal)
: source.searchMeetings(query, limit),
source.searchTranscriptSegments
? (options.signal
? source.searchTranscriptSegments(query, limit, options.signal)
: source.searchTranscriptSegments(query, limit))
: Promise.resolve({ rows: [], total: 0 }),
])
throwIfAborted(options.signal)
const segmentByMeetingId = new Map<string, UnifiedSearchTranscriptSegmentRow>()
for (const segment of segmentPage.rows) {
if (!segmentByMeetingId.has(segment.meeting_id)) {
segmentByMeetingId.set(segment.meeting_id, segment)
}
}
const directMeetingIds = new Set(meetingPage.rows.map((row) => row.id))
const missingMeetingIds = [...segmentByMeetingId.keys()].filter(
(meetingId) => !directMeetingIds.has(meetingId),
)
const extraMeetingMetaRows = missingMeetingIds.length > 0 && source.loadMeetingsByIds
? await (options.signal
? source.loadMeetingsByIds(missingMeetingIds, options.signal)
: source.loadMeetingsByIds(missingMeetingIds))
: []
throwIfAborted(options.signal)
const extraMeetingMetaById = new Map(
extraMeetingMetaRows.map((row) => [row.id, row]),
)
const directMeetingResults = meetingPage.rows.map((row) => (
meetingResult(row, query, segmentByMeetingId.get(row.id))
))
const segmentOnlyMeetingResults = missingMeetingIds
.map((meetingId) => {
const segment = segmentByMeetingId.get(meetingId)
if (!segment) return null
return segmentMeetingResult(segment, extraMeetingMetaById.get(meetingId), query)
})
.filter((item): item is UnifiedSearchResult => item !== null)
const results = mergeMobileUnifiedSearchResults(
recordPage.rows.map((row) => recordResult(row, query)),
meetingPage.rows.map((row) => meetingResult(row, query)),
[...directMeetingResults, ...segmentOnlyMeetingResults],
limit,
)
return {
query,
results,
total: recordPage.total + meetingPage.total,
total: recordPage.total + meetingPage.total + segmentOnlyMeetingResults.length,
}
} catch (error) {
throw toSearchError(error)
throw toSearchError(error, options.signal)
}
}

View file

@ -1,4 +1,11 @@
import AsyncStorage from '@react-native-async-storage/async-storage'
import {
normalizeEntitlementTier,
resolveEntitlement,
type AdminRole,
type EntitlementTier,
} from '@d3ro/core/entitlement'
import type { Feature } from '@d3ro/core/types'
import { AppState } from 'react-native'
import {
createContext,
@ -13,7 +20,7 @@ import {
import { useAuth } from './auth-context'
import { supabase } from './supabase'
export type MobileSubscriptionTier = 'free' | 'pro' | 'pro_plus'
export type MobileSubscriptionTier = EntitlementTier
export type MobileBillingProvider =
| 'none'
| 'stripe'
@ -47,6 +54,8 @@ export interface EntitlementSnapshot {
usageToday: Readonly<Record<string, number>>
purchases: readonly MobilePurchaseSummary[]
adFree: boolean
adminRole?: AdminRole
features?: readonly Feature[]
refreshedAt: string
}
@ -121,8 +130,12 @@ const PURCHASE_COLUMNS = [
const EntitlementContext = createContext<EntitlementContextValue | null>(null)
function emptySnapshot(): EntitlementSnapshot {
const coreEntitlement = resolveEntitlement({
subscriptionTier: 'free',
refreshedAt: 0,
})
return {
tier: 'free',
tier: coreEntitlement.tier,
status: 'active',
provider: 'none',
paymentProvider: 'none',
@ -134,7 +147,9 @@ function emptySnapshot(): EntitlementSnapshot {
overageCredits: 0,
usageToday: {},
purchases: [],
adFree: false,
adFree: coreEntitlement.adFree,
adminRole: coreEntitlement.adminRole,
features: coreEntitlement.features,
refreshedAt: new Date(0).toISOString(),
}
}
@ -149,7 +164,7 @@ function nullableIso(value: unknown): string | null {
}
function normalizeTier(value: unknown): MobileSubscriptionTier {
return value === 'pro' || value === 'pro_plus' ? value : 'free'
return normalizeEntitlementTier(value)
}
function normalizeProvider(value: unknown): MobileBillingProvider {
@ -207,14 +222,19 @@ export function normalizeEntitlement(
usageRows: readonly UsageRow[],
purchaseRows: readonly PurchaseRow[],
now = new Date(),
supabaseRole?: unknown,
): EntitlementSnapshot {
const tier = normalizeTier(subscription?.tier)
const status = typeof subscription?.status === 'string' && subscription.status
? subscription.status
: 'active'
const currentPeriodEnd = nullableIso(subscription?.current_period_end)
const periodValid = currentPeriodEnd === null || Date.parse(currentPeriodEnd) > now.getTime()
const statusAllowsPaidAccess = ['active', 'trialing', 'canceled', 'past_due'].includes(status)
const coreEntitlement = resolveEntitlement({
subscriptionTier: statusAllowsPaidAccess ? subscription?.tier : 'free',
supabaseRole,
expiresAt: currentPeriodEnd !== null ? Date.parse(currentPeriodEnd) : null,
refreshedAt: now.getTime(),
})
const usageToday: Record<string, number> = {}
for (const row of usageRows) {
if (typeof row.feature === 'string' && row.feature) {
@ -223,7 +243,7 @@ export function normalizeEntitlement(
}
return {
tier,
tier: coreEntitlement.tier,
status,
provider: normalizeProvider(subscription?.provider),
paymentProvider: normalizePaymentProvider(subscription?.payment_provider),
@ -241,7 +261,9 @@ export function normalizeEntitlement(
purchases: purchaseRows
.map(normalizePurchase)
.filter((purchase): purchase is MobilePurchaseSummary => purchase !== null),
adFree: tier !== 'free' && statusAllowsPaidAccess && periodValid,
adFree: coreEntitlement.adFree,
adminRole: coreEntitlement.adminRole,
features: coreEntitlement.features,
refreshedAt: now.toISOString(),
}
}

View file

@ -45,8 +45,10 @@ import {
deleteMeetingDocumentRevisionSafe,
deleteMeetingMemoConflictSafe,
deleteMeetingRevisionSafe,
findActiveTranscriptSegmentId,
getMeetingDetail,
MeetingServiceError,
parseTranscriptSeekSegments,
subscribeToMeetingDetail,
updateMeetingDocumentRevisionSafe,
updateMeetingMemoConflictSafe,
@ -73,6 +75,8 @@ interface MeetingDetailScreenProps {
| { initialKind: 'meeting_document' },
) => void
}
onSeekAudio?: (positionMs: number) => void
initialAudioPositionMs?: number | null
}
type EditorState =
@ -84,6 +88,8 @@ type EditorState =
export default function MeetingDetailScreen({
route,
navigation,
onSeekAudio,
initialAudioPositionMs = null,
}: MeetingDetailScreenProps): React.ReactElement {
const insets = useSafeAreaInsets()
const { t, formatDate } = useI18n()
@ -109,6 +115,13 @@ export default function MeetingDetailScreen({
const [editorBusy, setEditorBusy] = useState(false)
const [selectedDocumentTemplate, setSelectedDocumentTemplate] = useState<UserTemplate | null>(null)
const [reportTarget, setReportTarget] = useState<ContentReportTarget | null>(null)
const [currentPositionMs, setCurrentPositionMs] = useState<number | null>(initialAudioPositionMs)
const handleSeekTimestamp = useCallback((timestampMs: number): void => {
const clamped = Math.max(0, Math.floor(timestampMs))
setCurrentPositionMs(clamped)
onSeekAudio?.(clamped)
}, [onSeekAudio])
const load = useCallback(async (
pullToRefresh = false,
@ -461,6 +474,12 @@ export default function MeetingDetailScreen({
const transcript = detail === null
? null
: buildMeetingTranscriptView(detail.meeting, detail.transcripts)
const seekableSegments = useMemo(() => (
detail === null ? [] : parseTranscriptSeekSegments(detail.meeting, detail.transcripts)
), [detail])
const activeSegmentId = useMemo(() => (
findActiveTranscriptSegmentId(seekableSegments, currentPositionMs)
), [currentPositionMs, seekableSegments])
return (
<View style={styles.container}>
@ -646,25 +665,51 @@ export default function MeetingDetailScreen({
</View>
</Section>
<Section title={t('mobile.meetings.transcript')} count={detail.transcripts.length}>
{transcript?.source === 'segments' ? detail.transcripts.map((segment) => (
<View key={segment.id} style={styles.transcriptSegment} testID={`meeting-transcript-${segment.id}`}>
<View style={styles.segmentMeta}>
<ThemeText variant="label" color="accent">
{formatElapsedMs(segment.timestamp_ms)}
</ThemeText>
{segment.speaker !== null && (
<ThemeText variant="label" color="muted">{segment.speaker}</ThemeText>
)}
{segment.edited && (
<ThemeText variant="label" color="muted">
{t('mobile.meetings.edited')}
</ThemeText>
)}
</View>
<ThemeText selectable style={styles.readingText}>{segment.text}</ThemeText>
</View>
)) : transcript?.source !== 'empty' ? (
<Section title={t('mobile.meetings.transcript')} count={detail.transcripts.length || seekableSegments.length}>
{currentPositionMs !== null && (
<ThemeText variant="label" color="accent" testID="meeting-audio-position">
{formatElapsedMs(currentPositionMs)}
</ThemeText>
)}
{transcript?.source === 'segments' || seekableSegments.some((segment) => segment.timed) ? (
seekableSegments.map((segment) => {
const isActive = activeSegmentId === segment.id
return (
<View
key={segment.id}
style={[
styles.transcriptSegment,
isActive && styles.transcriptSegmentActive,
]}
testID={`meeting-transcript-${segment.id}`}
>
<View style={styles.segmentMeta}>
{segment.timed ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={formatElapsedMs(segment.timestampMs)}
onPress={() => handleSeekTimestamp(segment.timestampMs)}
testID={`meeting-transcript-seek-${segment.id}`}
>
<ThemeText variant="label" color="accent">
[{formatElapsedMs(segment.timestampMs)}]
</ThemeText>
</Pressable>
) : null}
{segment.speaker !== null && (
<ThemeText variant="label" color="muted">{segment.speaker}</ThemeText>
)}
{segment.edited && (
<ThemeText variant="label" color="muted">
{t('mobile.meetings.edited')}
</ThemeText>
)}
</View>
<ThemeText selectable style={styles.readingText}>{segment.text}</ThemeText>
</View>
)
})
) : transcript?.source !== 'empty' ? (
<ThemeText selectable style={styles.readingText}>{transcript?.text}</ThemeText>
) : (
<ThemeText color="muted" testID="meeting-transcript-empty">
@ -1109,9 +1154,16 @@ function createStyles(palette: Palette): ReturnType<typeof StyleSheet.create> {
transcriptSegment: {
gap: 6,
paddingVertical: 10,
paddingHorizontal: 8,
borderRadius: 8,
borderBottomWidth: 1,
borderBottomColor: palette.border.subtle,
},
transcriptSegmentActive: {
backgroundColor: palette.bg.inset,
borderLeftWidth: 3,
borderLeftColor: palette.accent.main,
},
segmentMeta: { flexDirection: 'row', alignItems: 'center', gap: 10 },
readingText: { lineHeight: 23 },
codeText: {

View file

@ -19,7 +19,10 @@ import {
import { useI18n } from '@d3ro/i18n'
import { UnifiedSearchResultRow } from '../components/UnifiedSearchResultRow'
import { normalizeUnifiedSearchInitialQuery } from '../features/search/unified-search-route'
import { searchUnifiedContent } from '../features/search/unified-search-service'
import {
isUnifiedSearchAbortedError,
searchUnifiedContent,
} from '../features/search/unified-search-service'
import { useAuth } from '../lib/auth-context'
import { useMobilePreferences } from '../lib/preferences-context'
import { ScreenHeader } from '../components/ScreenHeader'
@ -68,21 +71,32 @@ export default function UnifiedSearchScreen({
}
const sequence = ++requestSequence.current
const controller = new AbortController()
const timer = setTimeout(() => {
setState({ status: 'loading', results: [], total: 0 })
void searchUnifiedContent({ userId: user.id, query: normalized, limit: 40 })
void searchUnifiedContent({
userId: user.id,
query: normalized,
limit: 40,
signal: controller.signal,
})
.then((response) => {
if (requestSequence.current !== sequence) return
if (controller.signal.aborted || requestSequence.current !== sequence) return
setState({ status: 'ready', results: response.results, total: response.total })
})
.catch(() => {
if (requestSequence.current !== sequence) return
.catch((error) => {
if (
controller.signal.aborted
|| isUnifiedSearchAbortedError(error)
|| requestSequence.current !== sequence
) return
setState((current) => ({ ...current, status: 'error' }))
})
}, SEARCH_DEBOUNCE_MS)
return () => {
clearTimeout(timer)
controller.abort()
if (requestSequence.current === sequence) requestSequence.current += 1
}
}, [query, retryNonce, user])