From e7d03730c9d76e3fc737b361f9404809a87715f3 Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Fri, 6 Nov 2026 22:34:51 +0000 Subject: [PATCH 01/27] fix(app): stream OMI wearable audio as 20 ms Opus frames Declare 20 ms uplink frames for the wearable source and drop BLE frames that arrive after the socket closes. The SDK codec check is logged instead of enforced while the device test runs; the backend still validates Opus. Co-Authored-By: Claude Opus 5.5 --- app/scripts/test-phone-audio-streaming.cjs | 2 +- app/src/hooks/useAudioStreamer.ts | 4 +++- app/src/hooks/useAudioStreamingOrchestrator.ts | 14 ++++++++------ 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/app/scripts/test-phone-audio-streaming.cjs b/app/scripts/test-phone-audio-streaming.cjs index e6ee12f2..5322ffc8 100644 --- a/app/scripts/test-phone-audio-streaming.cjs +++ b/app/scripts/test-phone-audio-streaming.cjs @@ -213,7 +213,7 @@ const { useAudioStreamer } = loadTypeScript(sourcePath, { 'wss://chronicle.invalid/ws/audio', { kind: 'wearable', sourceId: 'neo-1' }, ); - assert.deepEqual(socketFrameDurations, [20, 60], 'wearable capture must declare 60 ms Opus'); + assert.deepEqual(socketFrameDurations, [20, 20], 'wearable capture must declare 20 ms Opus'); assert.equal(beginCaptureCalls.length, 2, 'wearable also uses one live capture'); assert.equal(beginCaptureCalls[1].deliveryClass, DeliveryClass.LIVE); await wearableStreamer.stopStreaming(); diff --git a/app/src/hooks/useAudioStreamer.ts b/app/src/hooks/useAudioStreamer.ts index e5248768..f06cbc73 100644 --- a/app/src/hooks/useAudioStreamer.ts +++ b/app/src/hooks/useAudioStreamer.ts @@ -58,7 +58,7 @@ function socketSource(source: AudioStreamSource) { sourceId: source.sourceId, displayName: 'wearable', deviceKind: DeviceKind.OMI, - uplinkFrameDurationMs: 60 as const, + uplinkFrameDurationMs: 20 as const, }; } return { @@ -185,6 +185,8 @@ export const useAudioStreamer = (): UseAudioStreamer => { }, onPlaybackPacket: packet => playbackRef.current?.append(packet), onClosed: () => { + // BLE frames keep arriving after a close; a cleared ref makes sendFrame drop them. + if (socketRef.current === socket) socketRef.current = null; playbackRef.current?.close(); playbackRef.current = null; setConversationState(null); diff --git a/app/src/hooks/useAudioStreamingOrchestrator.ts b/app/src/hooks/useAudioStreamingOrchestrator.ts index 5dc24aa5..d0bea2b5 100644 --- a/app/src/hooks/useAudioStreamingOrchestrator.ts +++ b/app/src/hooks/useAudioStreamingOrchestrator.ts @@ -1,6 +1,6 @@ import { useCallback } from 'react'; import { Alert } from 'react-native'; -import { BleAudioCodec, OmiConnection } from 'friend-lite-react-native'; +import { OmiConnection } from 'friend-lite-react-native'; import type { AppSettings } from './useAppSettings'; import type { AudioStreamSource } from './useAudioStreamer'; import type { PhoneCaptureSession } from './usePhoneAudioRecorder'; @@ -64,10 +64,10 @@ export const useAudioStreamingOrchestrator = ({ } try { + // TEMPORARY: the SDK reports pcm8 for any codec id except 20, and when the read fails. + // Log only, so the backend's Opus validation decides during the device test. const codec = await omiConnection.getAudioCodec(); - if (codec !== BleAudioCodec.OPUS) { - throw new Error(`Wearable must stream Opus; device reported ${codec}`); - } + console.warn(`[AudioOrchestrator] Wearable codec reported by SDK: ${codec}`); const sourceId = deviceConnection.connectedDeviceId; const finalUrl = buildAudioWebSocketUrl(settings.webSocketUrl); await originalStartAudioListener(async (audioBytes) => { @@ -76,14 +76,16 @@ export const useAudioStreamingOrchestrator = ({ captureEpoch: 0, capturedAtMs: Date.now(), monotonicTimestampMs: performance.now(), - frameDurationMs: 60, + frameDurationMs: 20, opus: audioBytes, }); } }); await audioStreamer.startStreaming(finalUrl, { kind: 'wearable', sourceId }); } catch (error) { - Alert.alert('Error', 'Could not start audio listening or streaming.'); + const reason = error instanceof Error ? error.message : String(error); + console.error('[AudioOrchestrator] Wearable start failed:', error); + Alert.alert('Error', `Could not start audio listening or streaming.\n\n${reason}`); await originalStopAudioListener(); await audioStreamer.stopStreaming(); } From 82926b3f62ffdba99220e47867cf7a589ac01894 Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Fri, 6 Nov 2026 22:35:18 +0000 Subject: [PATCH 02/27] build(app): add Fastlane iOS build and signing lanes app.config.js lets a build target another App Store Connect app through IOS_BUNDLE_ID and IOS_APP_GROUP without editing app.json. Credentials come from the environment; nothing secret is committed. Co-Authored-By: Claude Opus 5.5 --- app/.gitignore | 7 + app/Gemfile | 10 ++ app/Gemfile.lock | 362 ++++++++++++++++++++++++++++++++++++++++ app/app.config.js | 23 +++ app/build.json | 10 ++ app/fastlane/Appfile | 9 + app/fastlane/Fastfile | 364 +++++++++++++++++++++++++++++++++++++++++ app/fastlane/Matchfile | 6 + 8 files changed, 791 insertions(+) create mode 100644 app/Gemfile create mode 100644 app/Gemfile.lock create mode 100644 app/app.config.js create mode 100644 app/build.json create mode 100644 app/fastlane/Appfile create mode 100644 app/fastlane/Fastfile create mode 100644 app/fastlane/Matchfile diff --git a/app/.gitignore b/app/.gitignore index f6e07bb9..c74f47c4 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -35,3 +35,10 @@ yarn-error.* *.tsbuildinfo android/* + +# Native project, regenerated by expo prebuild +ios/ + +# Fastlane output +fastlane/report.xml +fastlane/README.md diff --git a/app/Gemfile b/app/Gemfile new file mode 100644 index 00000000..8bc122ae --- /dev/null +++ b/app/Gemfile @@ -0,0 +1,10 @@ +# Gemfile for Fastlane iOS automation +source "https://rubygems.org" + +gem "fastlane", "~> 2.220" + +# Must be in the Gemfile so `bundle exec pod install` (used by Fastlane) finds `pod` +gem "cocoapods", "~> 1.16" + +plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile') +eval_gemfile(plugins_path) if File.exist?(plugins_path) diff --git a/app/Gemfile.lock b/app/Gemfile.lock new file mode 100644 index 00000000..06e25797 --- /dev/null +++ b/app/Gemfile.lock @@ -0,0 +1,362 @@ +GEM + remote: https://rubygems.org/ + specs: + CFPropertyList (3.0.8) + abbrev (0.1.2) + activesupport (7.2.4) + base64 + benchmark (>= 0.3) + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5, < 3) + drb + i18n (>= 1.6, < 2) + logger (>= 1.4.2) + minitest (>= 5.1, < 6) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + addressable (2.9.0) + public_suffix (>= 2.0.2, < 8.0) + algoliasearch (1.27.5) + httpclient (~> 2.8, >= 2.8.3) + json (>= 1.5.1) + artifactory (3.0.17) + atomos (0.1.3) + aws-eventstream (1.4.0) + aws-partitions (1.1296.0) + aws-sdk-core (3.257.0) + aws-eventstream (~> 1, >= 1.3.0) + aws-partitions (~> 1, >= 1.992.0) + aws-sigv4 (~> 1.9) + base64 + bigdecimal + jmespath (~> 1, >= 1.6.1) + logger + rexml (~> 3.4, >= 3.4.2) + aws-sdk-kms (1.132.0) + aws-sdk-core (~> 3, >= 3.256.0) + aws-sigv4 (~> 1.5) + aws-sdk-s3 (1.233.2) + aws-sdk-core (~> 3, >= 3.256.0) + aws-sdk-kms (~> 1) + aws-sigv4 (~> 1.5) + aws-sigv4 (1.12.1) + aws-eventstream (~> 1, >= 1.0.2) + babosa (1.0.4) + base64 (0.3.0) + benchmark (0.5.0) + bigdecimal (4.1.3) + cgi (0.5.2) + claide (1.1.0) + cocoapods (1.17.0) + addressable (~> 2.8) + claide (>= 1.0.2, < 2.0) + cocoapods-core (= 1.17.0) + cocoapods-deintegrate (>= 1.0.3, < 2.0) + cocoapods-downloader (>= 2.1, < 3.0) + cocoapods-plugins (>= 1.0.0, < 2.0) + cocoapods-search (>= 1.0.0, < 2.0) + cocoapods-trunk (>= 1.6.0, < 2.0) + cocoapods-try (>= 1.1.0, < 2.0) + colored2 (~> 3.1) + fourflusher (>= 2.3.0, < 3.0) + gh_inspector (~> 1.0) + molinillo (~> 0.8.0) + nap (~> 1.0) + ruby-macho (~> 4.1.0) + xcodeproj (>= 1.28.1, < 2.0) + cocoapods-core (1.17.0) + activesupport (>= 5.0, < 8) + addressable (~> 2.8) + algoliasearch (~> 1.0) + concurrent-ruby (~> 1.1) + fuzzy_match (~> 2.0.4) + nap (~> 1.0) + netrc (~> 0.11) + public_suffix (~> 4.0) + typhoeus (~> 1.0) + cocoapods-deintegrate (1.0.5) + cocoapods-downloader (2.1) + cocoapods-plugins (1.0.0) + nap + cocoapods-search (1.0.1) + cocoapods-trunk (1.6.0) + nap (>= 0.8, < 2.0) + netrc (~> 0.11) + cocoapods-try (1.2.0) + colored (1.2) + colored2 (3.1.2) + commander (4.6.0) + highline (~> 2.0.0) + concurrent-ruby (1.3.8) + connection_pool (2.5.5) + csv (3.3.6) + declarative (0.0.20) + digest-crc (0.7.0) + rake (>= 12.0.0, < 14.0.0) + domain_name (0.7.20261007) + dotenv (2.8.1) + drb (2.2.3) + emoji_regex (3.2.3) + erb (6.0.7) + ethon (0.18.0) + ffi (>= 1.15.0) + logger + excon (1.7.3) + logger + faraday (2.14.4) + faraday-net_http (>= 2.0, < 3.5) + json + logger + faraday-cookie_jar (0.0.8) + faraday (>= 0.8.0) + http-cookie (>= 1.0.0) + faraday-follow_redirects (0.5.0) + faraday (>= 1, < 3) + faraday-multipart (1.2.0) + multipart-post (~> 2.0) + faraday-net_http (3.4.4) + net-http (~> 0.5) + faraday-retry (2.4.0) + faraday (~> 2.0) + fastimage (2.4.1) + fastlane (2.241.0) + CFPropertyList (>= 2.3, < 5.0.0) + abbrev (~> 0.1) + addressable (>= 2.9.0, < 3.0.0) + artifactory (~> 3.0) + aws-sdk-s3 (~> 1.197) + babosa (>= 1.0.3, < 2.0.0) + base64 (~> 0.2) + benchmark (>= 0.1.0) + bundler (>= 2.4.0, < 5.0.0) + cgi (~> 0.4) + colored (~> 1.2) + commander (~> 4.6) + csv (~> 3.3) + dotenv (>= 2.1.1, < 3.0.0) + emoji_regex (>= 0.1, < 4.0) + erb (>= 4.0, < 7.0) + excon (>= 1.0.0, < 2.0.0) + faraday (~> 2.7) + faraday-cookie_jar (~> 0.0.8) + faraday-follow_redirects (~> 0.3) + faraday-multipart (~> 1.0) + faraday-retry (~> 2.0) + fastimage (>= 2.1.0, < 3.0.0) + fastlane-sirp (>= 1.1.0) + gh_inspector (>= 1.1.2, < 2.0.0) + google-apis-androidpublisher_v3 (~> 0.99) + google-apis-playcustomapp_v1 (~> 0.1) + google-cloud-env (>= 1.6.0, < 2.5.0) + google-cloud-storage (~> 1.31) + highline (~> 2.0) + irb (>= 1.8) + json (< 3.0.0) + jwt (>= 2.10.3, < 4) + logger (>= 1.6, < 2.0) + mini_magick (>= 4.9.4, < 5.0.0) + multi_json (~> 1.12) + multipart-post (>= 2.0.0, < 3.0.0) + mutex_m (~> 0.3) + naturally (~> 2.2) + nkf (~> 0.2) + optparse (>= 0.1.1, < 1.0.0) + ostruct (>= 0.1.0) + plist (>= 3.1.0, < 4.0.0) + rubyzip (>= 3.4.0, < 4.0.0) + security (~> 0.3) + simctl (~> 1.6.3) + terminal-notifier (>= 3.1.0, < 4.0.0) + terminal-table (~> 4) + tty-screen (>= 0.6.3, < 1.0.0) + tty-spinner (>= 0.8.0, < 1.0.0) + word_wrap (~> 1.0.0) + xcodeproj (>= 1.13.0, < 2.0.0) + xcpretty (~> 0.4.1) + xcpretty-travis-formatter (>= 0.0.3, < 2.0.0) + fastlane-sirp (1.1.0) + ffi (1.17.4) + ffi (1.17.4-aarch64-linux-gnu) + ffi (1.17.4-aarch64-linux-musl) + ffi (1.17.4-arm-linux-gnu) + ffi (1.17.4-arm-linux-musl) + ffi (1.17.4-arm64-darwin) + ffi (1.17.4-x86-linux-gnu) + ffi (1.17.4-x86-linux-musl) + ffi (1.17.4-x86_64-darwin) + ffi (1.17.4-x86_64-linux-gnu) + ffi (1.17.4-x86_64-linux-musl) + fourflusher (2.3.1) + fuzzy_match (2.0.4) + gh_inspector (1.1.3) + google-apis-androidpublisher_v3 (0.109.0) + google-apis-core (>= 0.15.0, < 2.a) + google-apis-core (1.3.1) + addressable (~> 2.9) + faraday (~> 2.13) + faraday-follow_redirects (~> 0.3) + googleauth (~> 1.14) + mini_mime (~> 1.1) + multi_json (~> 1.11) + representable (~> 3.0) + retriable (>= 3.1, < 5.0) + google-apis-iamcredentials_v1 (0.28.0) + google-apis-core (>= 0.15.0, < 2.a) + google-apis-playcustomapp_v1 (0.18.0) + google-apis-core (>= 0.15.0, < 2.a) + google-apis-storage_v1 (0.69.0) + google-apis-core (>= 0.15.0, < 2.a) + google-cloud-core (1.9.0) + google-cloud-env (>= 1.0, < 3.a) + google-cloud-errors (~> 1.0) + google-cloud-env (2.4.1) + base64 (~> 0.2) + faraday (>= 1.0, < 3.a) + google-cloud-errors (1.7.0) + google-cloud-storage (1.62.1) + addressable (~> 2.8) + digest-crc (~> 0.4) + google-apis-core (>= 0.18, < 2) + google-apis-iamcredentials_v1 (~> 0.18) + google-apis-storage_v1 (>= 0.42) + google-cloud-core (~> 1.6) + googleauth (~> 1.9) + mini_mime (~> 1.0) + google-logging-utils (0.2.0) + googleauth (1.17.5) + faraday (>= 1.0, < 3.a) + google-cloud-env (~> 2.2) + google-logging-utils (~> 0.1) + jwt (>= 1.4, < 4.0) + os (>= 0.9, < 2.0) + pstore (~> 0.1) + signet (>= 0.16, < 2.a) + highline (2.0.3) + http-cookie (1.1.6) + domain_name (~> 0.5) + httpclient (2.9.0) + mutex_m + i18n (1.15.2) + concurrent-ruby (~> 1.0) + io-console (0.9.4) + irb (1.18.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + jmespath (1.6.2) + json (2.21.2) + jwt (3.3.0) + base64 + logger (1.7.0) + mini_magick (4.13.2) + mini_mime (1.1.5) + minitest (5.27.0) + molinillo (0.8.0) + multi_json (1.21.2) + multipart-post (2.4.1) + mutex_m (0.3.0) + nanaimo (0.4.0) + nap (1.1.0) + naturally (2.3.0) + net-http (0.10.0) + net-protocol (>= 0.3.0) + uri (>= 0.11.1) + net-protocol (0.4.0) + timeout + netrc (0.11.0) + nkf (0.3.0) + optparse (0.8.1) + os (1.1.4) + ostruct (0.6.3) + plist (3.7.2) + pp (0.6.4) + prettyprint + prettyprint (0.2.1) + prism (1.9.0) + pstore (0.2.1) + public_suffix (4.0.7) + rake (13.4.2) + rbs (4.2.0) + logger + prism (>= 1.6.0) + tsort + rdoc (8.1.0) + erb + prism (>= 1.6.0) + rbs (>= 4.0.0) + tsort + reline (0.7.0) + io-console (~> 0.5) + representable (3.3.1) + declarative (< 0.1.0) + trailblazer-option (>= 0.1.1, < 0.2.0) + uber (< 0.2.0) + retriable (4.2.0) + rexml (3.4.4) + rouge (3.28.0) + ruby-macho (4.1.0) + rubyzip (3.7.0) + securerandom (0.4.1) + security (0.3.0) + signet (0.22.1) + addressable (~> 2.8) + faraday (>= 0.17.5, < 3.a) + jwt (>= 1.5, < 4.0) + simctl (1.6.10) + CFPropertyList + naturally + terminal-notifier (3.1.0) + terminal-table (4.0.0) + unicode-display_width (>= 1.1.1, < 4) + timeout (0.6.1) + trailblazer-option (0.1.2) + tsort (0.2.0) + tty-cursor (0.7.1) + tty-screen (0.8.2) + tty-spinner (0.9.3) + tty-cursor (~> 0.7) + typhoeus (1.6.0) + ethon (>= 0.18.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + uber (0.1.0) + unicode-display_width (3.3.0) + unicode-emoji (~> 4.3) + unicode-emoji (4.3.0) + uri (1.1.2) + word_wrap (1.0.0) + xcodeproj (1.28.1) + CFPropertyList (>= 2.3.3, < 4.0) + atomos (~> 0.1.3) + base64 + claide (>= 1.0.2, < 2.0) + colored2 (~> 3.1) + nanaimo (~> 0.4.0) + nkf + rexml (>= 3.3.6, < 4.0) + xcpretty (0.4.1) + rouge (~> 3.28.0) + xcpretty-travis-formatter (1.0.1) + xcpretty (~> 0.2, >= 0.0.7) + +PLATFORMS + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + arm64-darwin + ruby + x86-linux-gnu + x86-linux-musl + x86_64-darwin + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + cocoapods (~> 1.16) + fastlane (~> 2.220) + +BUNDLED WITH + 2.6.8 diff --git a/app/app.config.js b/app/app.config.js new file mode 100644 index 00000000..d8863815 --- /dev/null +++ b/app/app.config.js @@ -0,0 +1,23 @@ +// Extends app.json so a build can target a different App Store Connect app +// (for example the Fastlane build in fastlane/Fastfile) without editing +// app.json. Unset, app.json is used unchanged. +// IOS_BUNDLE_ID replaces ios.bundleIdentifier +// IOS_APP_GROUP replaces the share extension's app group +// (expo-share-intent defaults to group.) +module.exports = ({ config }) => { + const bundleIdentifier = process.env.IOS_BUNDLE_ID; + const appGroup = process.env.IOS_APP_GROUP; + if (!bundleIdentifier && !appGroup) return config; + + const plugins = (config.plugins || []).map((plugin) => { + const [name, params] = Array.isArray(plugin) ? plugin : [plugin, {}]; + if (name !== "expo-share-intent" || !appGroup) return plugin; + return [name, { ...params, iosAppGroupIdentifier: appGroup }]; + }); + + return { + ...config, + ios: { ...config.ios, ...(bundleIdentifier && { bundleIdentifier }) }, + plugins, + }; +}; diff --git a/app/build.json b/app/build.json new file mode 100644 index 00000000..c40dfd75 --- /dev/null +++ b/app/build.json @@ -0,0 +1,10 @@ +{ + "scheme": "chronicle", + "app_identifier": "com.chronicle.ush", + "team_id": "6SJ7NH4HSZ", + "asc_app_id": "6823126187", + "app_group": "group.chronicle", + "extensions": { + "com.chronicle.ush.share-extension": "ShareExtension" + } +} diff --git a/app/fastlane/Appfile b/app/fastlane/Appfile new file mode 100644 index 00000000..eb76c75d --- /dev/null +++ b/app/fastlane/Appfile @@ -0,0 +1,9 @@ +# Chronicle — Fastlane Appfile. All values come from ../build.json. +require 'json' + +build_config = JSON.parse(File.read(File.join(File.dirname(__FILE__), '..', 'build.json'))) + +app_identifier(build_config['app_identifier']) +apple_id(ENV['FASTLANE_APPLE_ID'] || '') +team_id(build_config['team_id']) +itc_team_id(build_config['team_id']) diff --git a/app/fastlane/Fastfile b/app/fastlane/Fastfile new file mode 100644 index 00000000..08e9dab5 --- /dev/null +++ b/app/fastlane/Fastfile @@ -0,0 +1,364 @@ +require 'json' + +# Chronicle — Fastlane iOS deployment (from the ushadow-sdk mobile template) +# +# Configuration is read from build.json in the app root: +# { +# "scheme": "chronicle", +# "app_identifier": "com.chronicle.ush", +# "team_id": "6SJ7NH4HSZ", +# "asc_app_id": "6823126187", +# "app_group": "group.chronicle", +# "extensions": { "com.chronicle.ush.share-extension": "ShareExtension" } +# } +# +# app.json keeps the upstream bundle identifier. Prebuild runs with +# IOS_BUNDLE_ID and IOS_APP_GROUP set (see app.config.js), so the generated +# project, the share extension (.share-extension) and the app +# group all follow build.json. The app group must match the one registered on +# both App IDs, or the match profiles reject the entitlements. +# +# App Store Connect API key credentials come from .env.local (gitignored). +# +# Lanes: +# fastlane beta - Build and upload to TestFlight +# fastlane build - Build only (no upload) +# fastlane submit - Upload an existing IPA to TestFlight +# fastlane bump_build - Increment build number + +env_file = File.join(__dir__, '..', '.env.local') +if File.exist?(env_file) + File.foreach(env_file) do |line| + line = line.strip + next if line.empty? || line.start_with?('#') + key, value = line.split('=', 2) + ENV[key.strip] = value.strip if key && value + end +end + +default_platform(:ios) + +# ════════════════════════════════════════════════════════════════════════ +# Configuration helpers +# ════════════════════════════════════════════════════════════════════════ + +def project_root + File.expand_path('..', __dir__) +end + +def build_config + @build_config ||= begin + path = File.join(project_root, 'build.json') + UI.user_error!("build.json not found at #{path}.") unless File.exist?(path) + JSON.parse(File.read(path)) + end +end + +def app_scheme + build_config['scheme'] +end + +def app_identifier + build_config['app_identifier'] +end + +def app_extensions + build_config['extensions'] || {} +end + +def app_group + build_config['app_group'] || "group.#{app_identifier}" +end + +def apple_team_id + build_config['team_id'] || ENV['APPLE_TEAM_ID'] || '' +end + +def ios_workspace + "./ios/#{app_scheme}.xcworkspace" +end + +def ios_project + "./ios/#{app_scheme}.xcodeproj" +end + +# ════════════════════════════════════════════════════════════════════════ +# Lanes +# ════════════════════════════════════════════════════════════════════════ + +platform :ios do + before_all do + # No git state checks - allow deploys with uncommitted changes + end + + # ── Beta: Build + TestFlight ───────────────────────────────────────── + + desc "Build and upload to TestFlight" + lane :beta do + api_key = app_store_connect_api_key_from_env + + prebuild_ios + + # Sync build number with App Store Connect. Take the max of ASC's latest + # and the project's, because builds still processing may not show in ASC. + UI.message("📦 Syncing build number with App Store Connect...") + asc_build = app_store_build_number( + app_identifier: app_identifier, + live: false, + api_key: api_key, + ).to_i + project_build = get_build_number(xcodeproj: ios_project).to_i + next_build = [asc_build, project_build].max + 1 + UI.message("ASC build: #{asc_build}, project build: #{project_build} → using #{next_build}") + increment_build_number(build_number: next_build, xcodeproj: ios_project) + + version = get_version_number(xcodeproj: ios_project, target: app_scheme) + build = get_build_number(xcodeproj: ios_project) + UI.success("Building version #{version} (#{build})") + + UI.message("🔨 Building iOS app...") + build_ios_app(skip_prebuild: true) + + ipa_path = lane_context[SharedValues::IPA_OUTPUT_PATH] + UI.message("IPA path: #{ipa_path}") + ipa_build = sh("unzip -p '#{ipa_path}' 'Payload/#{app_scheme}.app/Info.plist' | plutil -extract CFBundleVersion raw -o - -").strip rescue "unknown" + UI.message("Build number inside IPA: #{ipa_build}") + + UI.message("🚀 Uploading to TestFlight...") + upload_to_testflight( + api_key: api_key, + ipa: ipa_path, + skip_waiting_for_build_processing: true, + distribute_external: false, + notify_external_testers: false, + changelog: "Build #{build} - Automated deployment via Fastlane" + ) + + UI.success("✅ Successfully uploaded to TestFlight!") + UI.success("Version: #{version} (Build: #{build})") + UI.message("📱 Build will appear in TestFlight in ~5-10 minutes") + end + + # ── Build only ────────────────────────────────────────────────────── + + desc "Build iOS app only (no upload)" + lane :build do + UI.message("🔨 Building iOS app...") + build_ios_app(skip_package_ipa: false) + UI.success("✅ Build complete!") + UI.message("IPA location: #{lane_context[SharedValues::IPA_OUTPUT_PATH]}") + end + + # ── Submit existing IPA ───────────────────────────────────────────── + + desc "Submit existing build to TestFlight" + lane :submit do |options| + api_key = app_store_connect_api_key_from_env + ipa_path = options[:ipa] || + lane_context[SharedValues::IPA_OUTPUT_PATH] || + File.expand_path("../build/#{app_scheme}.ipa", __dir__) + + UI.user_error!("No IPA file found at #{ipa_path}. Run 'fastlane beta' first.") unless File.exist?(ipa_path) + + UI.message("Using IPA: #{ipa_path}") + UI.message("🚀 Uploading to TestFlight...") + upload_to_testflight( + api_key: api_key, + ipa: ipa_path, + skip_waiting_for_build_processing: true, + distribute_external: false, + notify_external_testers: false + ) + UI.success("✅ Successfully uploaded to TestFlight!") + end + + # ── Bump build number ────────────────────────────────────────────── + + desc "Increment build number (synced with App Store Connect)" + lane :bump_build do + asc_build = app_store_build_number( + app_identifier: app_identifier, + live: false, + api_key: app_store_connect_api_key_from_env, + ).to_i + project_build = get_build_number(xcodeproj: ios_project).to_i + increment_build_number(build_number: [asc_build, project_build].max + 1, xcodeproj: ios_project) + version = get_version_number(xcodeproj: ios_project, target: app_scheme) + build = get_build_number(xcodeproj: ios_project) + UI.success("ASC: #{asc_build}, project: #{project_build} → New build: #{build} (version #{version})") + end + + # ════════════════════════════════════════════════════════════════════ + # Private lanes + # ════════════════════════════════════════════════════════════════════ + + # Regenerate ios/ for build.json's bundle identifier. + private_lane :prebuild_ios do + # The app depends on the generated audio contract package in ../contracts. + unless File.directory?(File.join(project_root, "node_modules")) + UI.message("📦 Installing JS dependencies...") + sh("cd .. && npm ci && npm run prepare:audio-contracts") + end + + UI.message("🔧 Running expo prebuild for #{app_identifier}...") + sh("rm -rf #{project_root}/ios") + sh("cd .. && IOS_BUNDLE_ID=#{app_identifier} IOS_APP_GROUP=#{app_group} npx expo prebuild --platform ios --clean") + patch_rn_screens + write_xcode_env_local + UI.message("📦 Running pod install...") + sh("cd ../ios && bundle exec pod install") + end + + desc "Build the iOS app" + private_lane :build_ios_app do |options| + team_id = apple_team_id + api_key = app_store_connect_api_key_from_env + + prebuild_ios unless options[:skip_prebuild] + + # Sync signing from the shared match repo: installs the team distribution + # cert and each target's profile. readonly: true keeps builds from + # mutating certs — run `mise run mobile:sign-setup` once to populate them. + UI.message("🔐 Syncing signing via match (shared cert repo)...") + match(type: "appstore", app_identifier: app_identifier, api_key: api_key, readonly: true) + profile_uuid = ENV["sigh_#{app_identifier}_appstore"] + profile_name = ENV["sigh_#{app_identifier}_appstore_profile-name"] + UI.success("Main app profile: #{profile_name} (#{profile_uuid})") + + provisioning_profiles = { app_identifier => profile_uuid } + + app_extensions.each do |ext_id, _ext_name| + match(type: "appstore", app_identifier: ext_id, api_key: api_key, readonly: true) + ext_uuid = ENV["sigh_#{ext_id}_appstore"] + UI.success("Extension profile (#{ext_id}): #{ENV["sigh_#{ext_id}_appstore_profile-name"]} (#{ext_uuid})") + provisioning_profiles[ext_id] = ext_uuid + end + + # Pin the freshly prebuilt project to manual Apple Distribution signing. + # gym signs the archive from the project's own build settings, which + # prebuild sets to automatic "iPhone Developer" signing. + UI.message("🔏 Pinning archive to manual Apple Distribution signing...") + update_code_signing_settings( + use_automatic_signing: false, + path: ios_project, + team_id: team_id, + code_sign_identity: "Apple Distribution", + profile_name: profile_name, + targets: [app_scheme], + ) + + app_extensions.each do |ext_id, ext_name| + update_code_signing_settings( + use_automatic_signing: false, + path: ios_project, + team_id: team_id, + code_sign_identity: "Apple Distribution", + profile_name: ENV["sigh_#{ext_id}_appstore_profile-name"], + targets: [ext_name], + ) + end + + gym( + workspace: ios_workspace, + scheme: app_scheme, + export_method: "app-store", + configuration: "Release", + clean: true, + output_directory: "./build", + output_name: "#{app_scheme}.ipa", + export_options: { + method: "app-store", + teamID: team_id, + compileBitcode: false, + provisioningProfiles: provisioning_profiles, + }, + skip_package_ipa: options[:skip_package_ipa] || false, + ) + end + + # App Store Connect API key from .env.local + private_lane :app_store_connect_api_key_from_env do + if ENV["APP_STORE_CONNECT_API_KEY_KEY_ID"] && + ENV["APP_STORE_CONNECT_API_KEY_ISSUER_ID"] && + ENV["APP_STORE_CONNECT_API_KEY_KEY_FILEPATH"] + app_store_connect_api_key( + key_id: ENV["APP_STORE_CONNECT_API_KEY_KEY_ID"].strip, + issuer_id: ENV["APP_STORE_CONNECT_API_KEY_ISSUER_ID"].strip, + key_filepath: File.expand_path(ENV["APP_STORE_CONNECT_API_KEY_KEY_FILEPATH"].strip), + ) + else + nil # Fall back to Apple ID / password auth + end + end + + # ════════════════════════════════════════════════════════════════════ + # Error handling + # ════════════════════════════════════════════════════════════════════ + + error do |lane, exception| + UI.error("Error in lane '#{lane}':") + UI.error(exception.message) + end + + after_all do |lane| + UI.success("Successfully completed '#{lane}' lane! 🎉") + end + + # ── Helpers ───────────────────────────────────────────────────────── + + # react-native-screens 4.x: snapshotViewAfterScreenUpdates throws on iOS 26 + # during screen unmount → SIGSEGV. Wrap the call in @try/@catch. + private_lane :patch_rn_screens do + rns_path = File.join(project_root, "node_modules/react-native-screens/ios/RNSScreen.mm") + UI.user_error!("RNSScreen.mm not found at #{rns_path}") unless File.exist?(rns_path) + + content = File.read(rns_path) + old_code = <<~OBJC.chomp + UIView *snapshot = [self.view snapshotViewAfterScreenUpdates:NO]; + snapshot.frame = self.view.frame; + [self.view removeFromSuperview]; + self.view = snapshot; + [superView addSubview:snapshot]; + OBJC + + new_code = <<~OBJC.chomp + @try { + UIView *snapshot = [self.view snapshotViewAfterScreenUpdates:NO]; + if (snapshot != nil) { + snapshot.frame = self.view.frame; + [self.view removeFromSuperview]; + self.view = snapshot; + [superView addSubview:snapshot]; + } + } @catch (NSException *exception) { + // iOS 26+: snapshotViewAfterScreenUpdates can throw during screen transitions. + } + OBJC + + if content.include?(old_code) + File.write(rns_path, content.sub(old_code, new_code)) + UI.success("Patched RNSScreen.mm for iOS 26 compatibility") + elsif content.include?("@try {") + UI.message("RNSScreen.mm already patched — skipping") + else + UI.important("RNSScreen.mm code changed — patch may need updating") + end + end + + # expo prebuild --clean deletes ios/.xcode.env.local. Without it Xcode's + # stripped PATH cannot find node, the JS bundle is silently skipped, and the + # IPA crashes on launch with "No script URL provided". + private_lane :write_xcode_env_local do + node_path = sh("command -v node 2>/dev/null || echo ''").strip + if node_path.empty? + ["/opt/homebrew/bin/node", "/usr/local/bin/node"].each do |p| + node_path = p and break if File.exist?(p) + end + end + UI.user_error!("Could not find node binary — install Node.js before building") if node_path.empty? + + env_local_path = File.join(project_root, "ios", ".xcode.env.local") + File.write(env_local_path, "export NODE_BINARY=#{node_path}\n") + UI.success("Wrote NODE_BINARY=#{node_path} → ios/.xcode.env.local") + end +end diff --git a/app/fastlane/Matchfile b/app/fastlane/Matchfile new file mode 100644 index 00000000..d46846d8 --- /dev/null +++ b/app/fastlane/Matchfile @@ -0,0 +1,6 @@ +# Shared central cert store for all ushadow-io mobile apps. +# Managed by `mise run mobile:sign-setup`. Every app points at the same repo +# and reuses the one team distribution cert; only this app's profile is created. +git_url("https://github.com/Ushadow-io/certificates.git") +storage_mode("git") +type("appstore") From 6df60c0bbd3862b5a7af7a94be2d7a9c3c7290fb Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Fri, 6 Nov 2026 22:35:19 +0000 Subject: [PATCH 03/27] fix(backend): report LLM configuration errors instead of failing silently A hosted model with an empty API key now raises MissingModelCredentialsError (503) naming the model and operation. Settings writes raise ConfigSaveError with the reason, including a read-only ConfigMap hint. A config.yml without a models key no longer makes /api/admin/models return 500. Co-Authored-By: Claude Opus 5.5 --- backend/src/backend/config_loader.py | 39 +++++++-- .../src/backend/middleware/app_middleware.py | 28 +++++++ backend/src/backend/model_registry.py | 41 +++++++++- .../backend/services/memory/agent/pi_agent.py | 12 ++- backend/tests/test_llm_config_errors.py | 79 +++++++++++++++++++ 5 files changed, 190 insertions(+), 9 deletions(-) create mode 100644 backend/tests/test_llm_config_errors.py diff --git a/backend/src/backend/config_loader.py b/backend/src/backend/config_loader.py index 50bf3a38..33b78fc4 100644 --- a/backend/src/backend/config_loader.py +++ b/backend/src/backend/config_loader.py @@ -11,10 +11,27 @@ from pathlib import Path from typing import Optional -from omegaconf import DictConfig, OmegaConf +from omegaconf import DictConfig, ListConfig, OmegaConf logger = logging.getLogger(__name__) + +class ConfigSaveError(RuntimeError): + """A runtime settings change could not be written to config.yml.""" + + +def _save_failure(what: str, config_path: Path, error: Exception) -> ConfigSaveError: + if isinstance(error, OSError) and error.errno == 30: # EROFS + reason = ( + f"{config_path} is read-only. In Kubernetes it is usually mounted from a " + "ConfigMap; edit that ConfigMap (or give the config directory writable " + "storage) instead of using the Settings page." + ) + else: + reason = f"{type(error).__name__}: {error}" + return ConfigSaveError(f"Could not save {what}: {reason}") + + # Global config cache _config_cache: Optional[DictConfig] = None _config_warnings: tuple[str, ...] = () @@ -250,8 +267,9 @@ def save_config_section(section_path: str, values: dict) -> bool: return True except Exception as e: - logger.error(f"Error saving config section '{section_path}': {e}") - return False + error = _save_failure(f"config section '{section_path}'", config_path, e) + logger.error(str(error)) + raise error from e def _load_raw_config() -> DictConfig: @@ -277,7 +295,15 @@ def get_raw_models() -> list: note it excludes default-only models that live solely in defaults.yml. """ raw = _load_raw_config() - models = raw.get("models", []) or [] + models = raw.get("models") + # A config.yml without a ``models`` key yields None, not a ListConfig, and + # OmegaConf.to_container() rejects plain Python values. + if models is None: + return [] + if not isinstance(models, ListConfig): + raise ValueError( + f"config.yml 'models' must be a list, got {type(models).__name__}" + ) return OmegaConf.to_container(models, resolve=False) @@ -306,5 +332,6 @@ def save_models_list(models: list) -> bool: return True except Exception as e: - logger.error(f"Error saving models list: {e}") - return False + error = _save_failure("the models list", config_path, e) + logger.error(str(error)) + raise error from e diff --git a/backend/src/backend/middleware/app_middleware.py b/backend/src/backend/middleware/app_middleware.py index 58a4382c..f063c96c 100644 --- a/backend/src/backend/middleware/app_middleware.py +++ b/backend/src/backend/middleware/app_middleware.py @@ -17,6 +17,8 @@ from starlette.responses import Response from backend.app_config import get_app_config +from backend.config_loader import ConfigSaveError +from backend.model_registry import MissingModelCredentialsError logger = logging.getLogger(__name__) request_logger = logging.getLogger("api.requests") @@ -225,6 +227,32 @@ async def connection_exception_handler(request: Request, exc: ConnectionError): }, ) + @app.exception_handler(ConfigSaveError) + async def config_save_exception_handler(request: Request, exc: ConfigSaveError): + """A settings write failed; tell the caller why instead of a bare 500.""" + return JSONResponse( + status_code=500, + content={ + "detail": str(exc), + "error_type": "config_save_failure", + "error_category": "configuration", + }, + ) + + @app.exception_handler(MissingModelCredentialsError) + async def missing_credentials_exception_handler( + request: Request, exc: MissingModelCredentialsError + ): + """An LLM call was attempted against a hosted model with no API key.""" + return JSONResponse( + status_code=503, + content={ + "detail": str(exc), + "error_type": "missing_model_credentials", + "error_category": "configuration", + }, + ) + @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): """Handle HTTP exceptions with structured error response.""" diff --git a/backend/src/backend/model_registry.py b/backend/src/backend/model_registry.py index 9b8ff584..29e2b651 100644 --- a/backend/src/backend/model_registry.py +++ b/backend/src/backend/model_registry.py @@ -34,6 +34,37 @@ logger = logging.getLogger(__name__) + +class MissingModelCredentialsError(RuntimeError): + """A hosted model was selected but its API key is not configured.""" + + +def require_api_key( + api_key: Optional[str], + url: str, + model_name: str, + *, + operation: Optional[str] = None, +) -> str: + """Return ``api_key``, or raise when a hosted HTTPS endpoint has none. + + Local servers (llama.cpp, Ollama, Tailnet ASR) declare a placeholder such as + ``no-key``. A key that resolved to empty for an HTTPS URL means a hosted + provider whose environment variable is unset; calling it would only fail + later as an opaque 401 inside a background job. + """ + if api_key: + return api_key + if url.startswith("https://"): + used_by = f" (used by LLM operation '{operation}')" if operation else "" + raise MissingModelCredentialsError( + f"Model '{model_name}'{used_by} calls {url} but its api_key is empty. " + "Set the environment variable its api_key references in config, " + "or select a different model in Settings > AI Model Settings." + ) + return "" + + # Operations whose normal routing role is not the primary LLM. Keeping this policy # beside the resolver makes the effective route inspectable without teaching every # caller or diagnostic which default it should use. @@ -254,6 +285,12 @@ def resolved_url(self) -> str: return _with_scheme(discovered) return _with_scheme(self.discovery_default or "") + def require_api_key(self, operation: Optional[str] = None) -> str: + """Return the API key, or raise when a hosted endpoint has none.""" + return require_api_key( + self.api_key, self.resolved_url(), self.name, operation=operation + ) + @model_validator(mode="after") def validate_model(self) -> ModelDef: """Cross-field validation.""" @@ -319,6 +356,7 @@ class ResolvedLLMOperation(BaseModel): max_tokens: Optional[int] = None response_format: Optional[Dict[str, Any]] = None # {"type": "json_object"} or None reasoning_effort: Optional[str] = None # OpenAI reasoning models OR thinking models + operation: Optional[str] = None # llm_operations name, for actionable errors @property def reasoning_allowed(self) -> bool: @@ -433,7 +471,7 @@ def get_client(self, is_async: bool = False): Uses create_openai_client which handles Langfuse tracing. """ return create_openai_client( - api_key=self.model_def.api_key or "", + api_key=self.model_def.require_api_key(self.operation), base_url=self.model_def.resolved_url(), is_async=is_async, ) @@ -609,6 +647,7 @@ def get_llm_operation( max_tokens=int(max_tokens) if max_tokens is not None else None, response_format=response_format, reasoning_effort=reasoning_effort, + operation=name, ) def explain_llm_operation(self, name: str) -> Dict[str, Optional[str]]: diff --git a/backend/src/backend/services/memory/agent/pi_agent.py b/backend/src/backend/services/memory/agent/pi_agent.py index dc7f82a0..ba219d5a 100644 --- a/backend/src/backend/services/memory/agent/pi_agent.py +++ b/backend/src/backend/services/memory/agent/pi_agent.py @@ -26,7 +26,12 @@ from urllib.parse import unquote, urlsplit import backend.services.privacy as privacy -from backend.model_registry import AppModels, ResolvedLLMOperation, get_models_registry +from backend.model_registry import ( + AppModels, + ResolvedLLMOperation, + get_models_registry, + require_api_key, +) from backend.services.inference_artifacts import canonical_hash, persist_inference_run from ..session_write import WriteSourcePermissions @@ -452,7 +457,10 @@ def _resolve_pi_config( provider=_provider_slug(str(model_def.model_provider)), model=resolved.model_name, base_url=base_url, - api_key=resolved.api_key or "no-key", + api_key=require_api_key( + resolved.api_key, base_url, model_def.name, operation=operation + ) + or "no-key", thinking=_thinking_level(settings.get("thinking"), resolved), max_tokens=max_tokens, context_window=context_window, diff --git a/backend/tests/test_llm_config_errors.py b/backend/tests/test_llm_config_errors.py new file mode 100644 index 00000000..2ac8507e --- /dev/null +++ b/backend/tests/test_llm_config_errors.py @@ -0,0 +1,79 @@ +"""Misconfigured LLMs and unwritable settings must fail loudly, not silently.""" + +import os +from pathlib import Path + +import pytest + +from backend import config_loader +from backend.config_loader import ConfigSaveError, get_raw_models, save_config_section +from backend.model_registry import ( + AppModels, + LLMOperationConfig, + MissingModelCredentialsError, + ModelDef, +) + + +def _model(name: str, url: str, api_key) -> ModelDef: + return ModelDef( + name=name, + model_type="llm", + model_provider="openrouter", + api_family="openai", + model_name=name, + model_url=url, + api_key=api_key, + ) + + +def test_hosted_model_without_key_raises_when_client_is_built(): + hosted = _model("openrouter-qwen", "https://openrouter.ai/api/v1", "") + registry = AppModels( + defaults={"llm": hosted.name}, + models={hosted.name: hosted}, + llm_operations={"memory_write": LLMOperationConfig(model=hosted.name)}, + ) + + op = registry.get_llm_operation("memory_write") + + with pytest.raises(MissingModelCredentialsError) as error: + op.get_client(is_async=True) + assert "openrouter-qwen" in str(error.value) + assert "memory_write" in str(error.value) + + +def test_local_model_without_key_is_allowed(): + local = _model("local-llm", "http://llama-cpp-llm:8080/v1", "") + assert local.require_api_key() == "" + + +def test_hosted_model_with_key_returns_key(): + hosted = _model("openai", "https://api.openai.com/v1", "sk-test") + assert hosted.require_api_key() == "sk-test" + + +@pytest.fixture +def config_dir(tmp_path: Path, monkeypatch): + monkeypatch.setenv("CONFIG_DIR", str(tmp_path)) + yield tmp_path + config_loader._runtime_overrides.clear() + + +def test_raw_models_is_empty_when_config_has_no_models_key(config_dir: Path): + (config_dir / "config.yml").write_text("llm_operations: {}\n") + assert get_raw_models() == [] + + +def test_save_to_read_only_config_raises_actionable_error(config_dir: Path): + config_file = config_dir / "config.yml" + config_file.write_text("llm_operations: {}\n") + os.chmod(config_dir, 0o500) + os.chmod(config_file, 0o400) + try: + with pytest.raises(ConfigSaveError) as error: + save_config_section("llm_operations", {"memory_write": {"model": "x"}}) + finally: + os.chmod(config_dir, 0o700) + os.chmod(config_file, 0o600) + assert "llm_operations" in str(error.value) From 3c59e0bdabb055b613df3d52295eb648eb132c2e Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Fri, 6 Nov 2026 22:35:22 +0000 Subject: [PATCH 04/27] feat(timeline): make Immich optional and let a reconciliation be cancelled A deployment without Immich no longer waits for a photo backup before day reconciliation. A running or queued reconciliation can be cancelled from the Timeline page; the job is stopped, its dirty range is dismissed, and a new request can start. Co-Authored-By: Claude Opus 5.5 --- .../backend/controllers/queue_controller.py | 22 +++ backend/src/backend/models/timeline.py | 15 +- .../routers/modules/timeline_routes.py | 17 +++ .../src/backend/services/immich_discovery.py | 7 +- .../backend/services/timeline/dirty_ranges.py | 59 ++++++++ .../timeline/explicit_reconciliation.py | 64 ++++++++- backend/src/backend/workers/timeline_jobs.py | 2 +- backend/tests/test_explicit_reconciliation.py | 134 +++++++++++++++++- backend/tests/test_immich_discovery.py | 5 +- backend/webui/src/pages/Timeline.tsx | 19 ++- backend/webui/src/services/api.ts | 4 +- 11 files changed, 331 insertions(+), 17 deletions(-) diff --git a/backend/src/backend/controllers/queue_controller.py b/backend/src/backend/controllers/queue_controller.py index 9707b2fe..f0000521 100644 --- a/backend/src/backend/controllers/queue_controller.py +++ b/backend/src/backend/controllers/queue_controller.py @@ -18,6 +18,7 @@ from fastapi.responses import JSONResponse from rq import Queue, Retry, Worker +from rq.command import send_stop_job_command from rq.exceptions import NoSuchJobError from rq.job import Dependency, Job, JobStatus from rq.registry import DeferredJobRegistry, ScheduledJobRegistry @@ -927,6 +928,27 @@ def enqueue_explicit_timeline_reconciliation(request_id: str) -> Optional[str]: return job.id +def stop_explicit_timeline_reconciliation(job_id: str) -> str: + """Stop one explicit reconciliation job wherever it is in its lifecycle. + + A running job's work-horse is killed; a queued, scheduled, or retry-deferred job + is cancelled so RQ never starts it. Returns what was done, for the caller's log. + """ + + try: + job = Job.fetch(job_id, connection=redis_conn) + except NoSuchJobError: + return "missing" + status = get_job_status_from_rq(job) + if status == "started": + send_stop_job_command(redis_conn, job_id) + return "stopped" + if status in {"queued", "deferred", "scheduled"}: + job.cancel() + return "cancelled" + return status + + def start_streaming_jobs( session_id: str, user_id: str, diff --git a/backend/src/backend/models/timeline.py b/backend/src/backend/models/timeline.py index f94b6a12..37b86bfd 100644 --- a/backend/src/backend/models/timeline.py +++ b/backend/src/backend/models/timeline.py @@ -534,10 +534,19 @@ class DirtyEvidenceRangeResolution(BaseModel): """Append-only human resolution of one terminal reconciliation range.""" resolution_id: str = Field(default_factory=lambda: str(uuid.uuid4())) - action: Literal["dismissed"] = "dismissed" + action: Literal["dismissed", "cancelled"] = "dismissed" actor_user_id: str = Field(min_length=1) reason: str = Field(min_length=1, max_length=500) - prior_state: Literal["failed"] = "failed" + # A cancel can stop a range at any non-terminal stage, not only after failure. + prior_state: Literal[ + "failed", + "pending", + "authorized_pending", + "leased", + "waiting", + "awaiting_context", + "context_pending", + ] = "failed" created_at: datetime = Field(default_factory=utcnow) @@ -768,7 +777,7 @@ class TimelineReconciliationRequest(Document): user_id: str local_date: date timezone: str - state: Literal["blocked", "queued", "running", "completed", "failed"] + state: Literal["blocked", "queued", "running", "completed", "failed", "cancelled"] reason: Literal[ "assets_on_day", "later_asset_watermark", diff --git a/backend/src/backend/routers/modules/timeline_routes.py b/backend/src/backend/routers/modules/timeline_routes.py index 6f8dcf16..f0490df5 100644 --- a/backend/src/backend/routers/modules/timeline_routes.py +++ b/backend/src/backend/routers/modules/timeline_routes.py @@ -61,6 +61,7 @@ ) from backend.services.timeline.dirty_ranges import ( DirtyRangeDismissalError, + DirtyRangeLeaseLost, dismiss_failed_range, ) from backend.services.timeline.dispatch import enqueue_episode_detailed_summary @@ -74,6 +75,8 @@ infer_evidence_relations, ) from backend.services.timeline.explicit_reconciliation import ( + ReconciliationNotCancellable, + cancel_explicit_reconciliation, reconciliation_request_payload, request_explicit_reconciliation, ) @@ -563,6 +566,20 @@ async def reconcile_timeline_day( return {**reconciliation_request_payload(request), "created": created} +@router.post("/reconciliation/{request_id}/cancel") +async def cancel_reconciliation_request( + request_id: str, + user: User = Depends(current_active_user), +): + try: + request = await cancel_explicit_reconciliation(user=user, request_id=request_id) + except LookupError as error: + raise HTTPException(status_code=404, detail=str(error)) from error + except (ReconciliationNotCancellable, DirtyRangeLeaseLost) as error: + raise HTTPException(status_code=409, detail=str(error)) from error + return reconciliation_request_payload(request) + + @router.get("/reconciliation/{request_id}") async def get_reconciliation_request( request_id: str, diff --git a/backend/src/backend/services/immich_discovery.py b/backend/src/backend/services/immich_discovery.py index 2003a934..95cbcf5e 100644 --- a/backend/src/backend/services/immich_discovery.py +++ b/backend/src/backend/services/immich_discovery.py @@ -49,6 +49,10 @@ def _settings() -> tuple[str, str] | None: return (url, key) if url and key else None +def immich_configured() -> bool: + return _settings() is not None + + async def resolve_immich_user_id() -> str | None: """Chronicle user that owns imported Immich references. @@ -146,7 +150,8 @@ async def check_immich_day_readiness( checked_at = utcnow() settings = _settings() if settings is None: - return ImmichDayReadiness(False, "immich_unconfigured", 0, None, checked_at, []) + # Immich is optional. A deployment without it has no backup to wait for. + return ImmichDayReadiness(True, "immich_unconfigured", 0, None, checked_at, []) try: zone = ZoneInfo(timezone_name) except Exception as error: diff --git a/backend/src/backend/services/timeline/dirty_ranges.py b/backend/src/backend/services/timeline/dirty_ranges.py index f03eedfb..e7def028 100644 --- a/backend/src/backend/services/timeline/dirty_ranges.py +++ b/backend/src/backend/services/timeline/dirty_ranges.py @@ -1253,6 +1253,65 @@ async def dismiss_failed_range( ) +CANCELLABLE_RANGE_STATES = ( + "pending", + "authorized_pending", + "leased", + "waiting", + "awaiting_context", + "context_pending", +) + + +async def cancel_range( + dirty_range_id: str, *, user_id: str, reason: str +) -> Optional[DirtyEvidenceRange]: + """Take one owner-scoped, unfinished range out of scheduling. + + Clearing the lease fences a still-running attempt: its next lease-checked write + raises ``DirtyRangeLeaseLost`` instead of publishing. ``dismissed`` keeps the + recovery cron from re-dispatching it. Returns None when the range had already + reached a terminal state, so there was nothing to cancel. + """ + + existing = await DirtyEvidenceRange.find_one( + DirtyEvidenceRange.dirty_range_id == dirty_range_id, + DirtyEvidenceRange.user_id == user_id, + ) + if existing is None: + raise LookupError("reconciliation range not found") + if existing.state not in CANCELLABLE_RANGE_STATES: + return None + resolution = DirtyEvidenceRangeResolution( + action="cancelled", + actor_user_id=user_id, + reason=reason, + prior_state=existing.state, + ) + document = await DirtyEvidenceRange.get_pymongo_collection().find_one_and_update( + { + "dirty_range_id": dirty_range_id, + "user_id": user_id, + "state": existing.state, + }, + { + "$set": { + "state": "dismissed", + "lease_owner": None, + "lease_expires_at": None, + "updated_at": resolution.created_at, + }, + "$push": {"resolution_history": resolution.model_dump(mode="python")}, + }, + return_document=ReturnDocument.AFTER, + ) + if document is None: + raise DirtyRangeLeaseLost( + f"dirty range {dirty_range_id} changed state while being cancelled; retry" + ) + return DirtyEvidenceRange.model_validate(document) + + async def release_range_for_retry( dirty_range: DirtyEvidenceRange, error: str ) -> DirtyEvidenceRange: diff --git a/backend/src/backend/services/timeline/explicit_reconciliation.py b/backend/src/backend/services/timeline/explicit_reconciliation.py index 099f5880..1f44c1b8 100644 --- a/backend/src/backend/services/timeline/explicit_reconciliation.py +++ b/backend/src/backend/services/timeline/explicit_reconciliation.py @@ -14,12 +14,16 @@ ) from backend.services.immich_discovery import ( check_immich_day_readiness, + immich_configured, import_immich_day_candidates, resolve_immich_user_id, ) from backend.services.notifications import NotificationCommand, enqueue_notification from backend.services.redis_lock import distributed_lock -from backend.services.timeline.dirty_ranges import authorize_explicit_range +from backend.services.timeline.dirty_ranges import ( + authorize_explicit_range, + cancel_range, +) from backend.users import User # The readiness check can page through several Immich search windows before importing @@ -61,7 +65,7 @@ async def request_explicit_reconciliation( start, _ = day_bounds(local_date, timezone_name) if start >= utcnow(): raise ValueError("Cannot reconcile a future evidence interval") - if not skip_immich: + if not skip_immich and immich_configured(): immich_owner_id = await resolve_immich_user_id() if immich_owner_id != user_id: raise PermissionError( @@ -178,7 +182,8 @@ async def _request_explicit_reconciliation_locked( await request.save() return request, True - if not skip_immich: + # Importing also registers an Immich capture source, so skip it without Immich. + if not skip_immich and readiness.reason != "immich_unconfigured": await import_immich_day_candidates(user_id, readiness.target_assets) started_at, _ = day_bounds(local_date, timezone_name) ended_at = evidence_cutoff(request) @@ -205,6 +210,59 @@ async def _request_explicit_reconciliation_locked( return request, True +class ReconciliationNotCancellable(ValueError): + """The request already finished, so there is nothing to stop.""" + + +CANCELLABLE_REQUEST_STATES = ("queued", "running") + + +async def cancel_explicit_reconciliation( + *, user: User, request_id: str +) -> TimelineReconciliationRequest: + """Stop one queued or running day request so the day can be requested again. + + Order matters: the range is fenced first, so a worker that outlives the stop + command loses its lease rather than publishing; then the RQ job is stopped; the + request is marked last, because a still-active request is what blocks a retry. + """ + + user_id = str(user.id) + request = await TimelineReconciliationRequest.find_one( + TimelineReconciliationRequest.request_id == request_id, + TimelineReconciliationRequest.user_id == user_id, + ) + if request is None: + raise LookupError("Reconciliation request not found") + if request.state not in CANCELLABLE_REQUEST_STATES: + raise ReconciliationNotCancellable( + f"Only a queued or running reconciliation can be cancelled " + f"(state={request.state})" + ) + if request.dirty_range_id: + await cancel_range( + request.dirty_range_id, + user_id=user_id, + reason=f"Cancelled by user (request {request_id})", + ) + if request.job_id: + await asyncio.to_thread(_stop_job, request.job_id) + request.state = "cancelled" + request.last_error = "Cancelled by user" + request.updated_at = utcnow() + await request.save() + return request + + +def _stop_job(job_id: str) -> str: + # Lazy for the same worker-bootstrap reason as _queue_request. + from backend.controllers.queue_controller import ( + stop_explicit_timeline_reconciliation, + ) + + return stop_explicit_timeline_reconciliation(job_id) + + def _queue_request(request_id: str) -> str | None: # Lazy to avoid coupling the Timeline service import graph to worker bootstrap. from backend.controllers.queue_controller import ( diff --git a/backend/src/backend/workers/timeline_jobs.py b/backend/src/backend/workers/timeline_jobs.py index b343ae8e..f23d8243 100644 --- a/backend/src/backend/workers/timeline_jobs.py +++ b/backend/src/backend/workers/timeline_jobs.py @@ -87,7 +87,7 @@ async def explicit_reconciliation_job(request_id: str, *, redis_client=None) -> request = await TimelineReconciliationRequest.find_one({"request_id": request_id}) if request is None: return {"request_id": request_id, "state": "missing"} - if request.state in {"completed", "failed", "blocked"}: + if request.state in {"completed", "failed", "blocked", "cancelled"}: return {"request_id": request_id, "state": request.state} return await _run_explicit_reconciliation(request) diff --git a/backend/tests/test_explicit_reconciliation.py b/backend/tests/test_explicit_reconciliation.py index eadd14d6..41bf672a 100644 --- a/backend/tests/test_explicit_reconciliation.py +++ b/backend/tests/test_explicit_reconciliation.py @@ -93,7 +93,7 @@ async def test_blocked_request_never_imports_or_queues_work(requests_db, monkeyp explicit_reconciliation, "check_immich_day_readiness", lambda *_args: _async_value( - readiness(ready=False, reason="immich_unconfigured") + readiness(ready=False, reason="immich_unreachable") ), ) imported = queued = 0 @@ -119,11 +119,55 @@ def queue_request(*_args): assert created is True assert request.state == "blocked" - assert request.reason == "immich_unconfigured" + assert request.reason == "immich_unreachable" assert imported == 0 assert queued == 0 +@pytest.mark.asyncio +async def test_unconfigured_immich_queues_any_user_without_import( + requests_db, monkeypatch +): + monkeypatch.setattr(explicit_reconciliation, "immich_configured", lambda: False) + monkeypatch.setattr( + explicit_reconciliation, + "check_immich_day_readiness", + lambda *_args: _async_value( + readiness(ready=True, reason="immich_unconfigured") + ), + ) + imported = 0 + + async def import_candidates(*_args): + nonlocal imported + imported += 1 + + async def not_called(): + raise AssertionError("Immich ownership does not apply without Immich") + + async def authorize(**_kwargs): + return SimpleNamespace(dirty_range_id="range-one") + + monkeypatch.setattr( + explicit_reconciliation, "import_immich_day_candidates", import_candidates + ) + monkeypatch.setattr(explicit_reconciliation, "resolve_immich_user_id", not_called) + monkeypatch.setattr(explicit_reconciliation, "authorize_explicit_range", authorize) + monkeypatch.setattr(explicit_reconciliation, "_queue_request", lambda *_args: "job") + + request, created = await explicit_reconciliation.request_explicit_reconciliation( + user=SimpleNamespace(id="not-the-admin"), + local_date=date(2026, 8, 15), + timezone_name="Asia/Kolkata", + ) + + assert created is True + assert request.state == "queued" + assert request.reason == "immich_unconfigured" + assert request.job_id == "job" + assert imported == 0 + + @pytest.mark.asyncio async def test_user_can_explicitly_reconcile_without_immich(requests_db, monkeypatch): checked = imported = 0 @@ -312,7 +356,7 @@ async def local_lock(*_args, **_kwargs): async def check(*_args): nonlocal checks checks += 1 - return readiness(ready=False, reason="immich_unconfigured") + return readiness(ready=False, reason="immich_unreachable") monkeypatch.setattr(explicit_reconciliation, "distributed_lock", local_lock) monkeypatch.setattr(explicit_reconciliation, "check_immich_day_readiness", check) @@ -335,6 +379,7 @@ async def check(*_args): @pytest.mark.asyncio async def test_non_owner_cannot_query_or_import_immich(requests_db, monkeypatch): + monkeypatch.setattr(explicit_reconciliation, "immich_configured", lambda: True) monkeypatch.setattr( explicit_reconciliation, "resolve_immich_user_id", @@ -696,3 +741,86 @@ def test_enqueue_keeps_running_retry_with_previous_ended_at(monkeypatch, status) queue_controller.enqueue_explicit_timeline_reconciliation("request") == "live-retry" ) + + +@pytest.mark.asyncio +async def test_cancel_stops_job_dismisses_range_and_allows_a_new_request( + requests_db, monkeypatch +): + stopped = [] + monkeypatch.setattr(explicit_reconciliation, "_queue_request", lambda _id: "job") + monkeypatch.setattr(explicit_reconciliation, "_stop_job", stopped.append) + user = SimpleNamespace(id="user") + day = date(2026, 8, 15) + + first, _ = await explicit_reconciliation.request_explicit_reconciliation( + user=user, local_date=day, timezone_name="Asia/Kolkata", skip_immich=True + ) + cancelled = await explicit_reconciliation.cancel_explicit_reconciliation( + user=user, request_id=first.request_id + ) + + assert cancelled.state == "cancelled" + assert stopped == ["job"] + dirty_range = await DirtyEvidenceRange.find_one( + DirtyEvidenceRange.dirty_range_id == first.dirty_range_id + ) + assert dirty_range.state == "dismissed" + assert dirty_range.lease_owner is None + assert dirty_range.resolution_history[-1].action == "cancelled" + assert dirty_range.resolution_history[-1].prior_state == "authorized_pending" + + # The cancelled request no longer pins the day: asking again starts fresh. + second, created = await explicit_reconciliation.request_explicit_reconciliation( + user=user, local_date=day, timezone_name="Asia/Kolkata", skip_immich=True + ) + assert created is True + assert second.request_id != first.request_id + + # The worker entrypoint refuses to run a cancelled request. + result = await timeline_jobs.explicit_reconciliation_job.__wrapped__( + first.request_id + ) + assert result == {"request_id": first.request_id, "state": "cancelled"} + + +@pytest.mark.asyncio +async def test_finished_request_cannot_be_cancelled(requests_db): + request = TimelineReconciliationRequest( + user_id="user", + local_date=date(2026, 8, 15), + timezone="Asia/Kolkata", + state="completed", + reason="user_bypassed_immich", + ) + await request.insert() + + with pytest.raises(explicit_reconciliation.ReconciliationNotCancellable): + await explicit_reconciliation.cancel_explicit_reconciliation( + user=SimpleNamespace(id="user"), request_id=request.request_id + ) + with pytest.raises(LookupError): + await explicit_reconciliation.cancel_explicit_reconciliation( + user=SimpleNamespace(id="someone-else"), request_id=request.request_id + ) + + +@pytest.mark.parametrize( + ("status", "expected"), + [("started", "stopped"), ("queued", "cancelled"), ("scheduled", "cancelled")], +) +def test_stop_job_kills_running_and_cancels_pending(monkeypatch, status, expected): + calls = [] + job = SimpleNamespace( + id="timeline-explicit_x", cancel=lambda: calls.append("cancel") + ) + monkeypatch.setattr(queue_controller.Job, "fetch", lambda *_a, **_k: job) + monkeypatch.setattr(queue_controller, "get_job_status_from_rq", lambda _j: status) + monkeypatch.setattr( + queue_controller, + "send_stop_job_command", + lambda _conn, job_id: calls.append(("stop", job_id)), + ) + + assert queue_controller.stop_explicit_timeline_reconciliation(job.id) == expected + assert calls == ([("stop", job.id)] if status == "started" else ["cancel"]) diff --git a/backend/tests/test_immich_discovery.py b/backend/tests/test_immich_discovery.py index 11f440b8..c2940a34 100644 --- a/backend/tests/test_immich_discovery.py +++ b/backend/tests/test_immich_discovery.py @@ -241,15 +241,16 @@ async def test_external_library_assets_do_not_satisfy_gate(monkeypatch): @pytest.mark.asyncio -async def test_unconfigured_immich_blocks_without_network(monkeypatch): +async def test_unconfigured_immich_is_ready_without_network(monkeypatch): monkeypatch.setattr(immich_discovery, "_settings", lambda: None) result = await immich_discovery.check_immich_day_readiness( date(2026, 8, 15), "Asia/Kolkata" ) - assert result.ready is False + assert result.ready is True assert result.reason == "immich_unconfigured" + assert result.target_assets == [] @pytest.mark.asyncio diff --git a/backend/webui/src/pages/Timeline.tsx b/backend/webui/src/pages/Timeline.tsx index 2de34764..b02f8c51 100644 --- a/backend/webui/src/pages/Timeline.tsx +++ b/backend/webui/src/pages/Timeline.tsx @@ -42,7 +42,7 @@ function readinessMessage(request?: TimelineReconciliationRequest) { if (reason === 'later_asset_watermark') return `Immich contains an eligible asset captured on ${watermark}, after this day.` if (reason === 'no_immich_evidence') return 'No eligible Immich evidence is available for this interval yet. Open Immich, back up photos up to the cutoff below, then check again.' if (reason === 'user_bypassed_immich') return 'Continuing without Immich evidence at your request.' - if (reason === 'immich_unconfigured') return 'Immich is not configured for Chronicle, so reconciliation cannot start.' + if (reason === 'immich_unconfigured') return 'Immich is not configured, so this analysis uses your other evidence.' return 'Chronicle could not reach Immich. Reconciliation did not start.' } @@ -208,6 +208,13 @@ export default function Timeline() { setReconciliationRequestId(request.request_id) }, }) + const cancelReconciliation = useMutation({ + mutationFn: async (requestId: string) => (await timelineApi.cancelReconciliation(requestId)).data, + onSuccess: request => { + queryClient.setQueryData(['timeline-reconciliation', request.request_id], request) + void queryClient.invalidateQueries({ queryKey: ['semantic-timeline', day, timezone] }) + }, + }) const reconciliation = useQuery({ queryKey: ['timeline-reconciliation', reconciliationRequestId], queryFn: async () => (await timelineApi.getReconciliation(reconciliationRequestId!)).data, @@ -353,7 +360,7 @@ export default function Timeline() { {(reconciliationStatus.state === 'blocked' || reconciliationStatus.state === 'failed') && } Reconciliation {reconciliationStatus.state}{reconciliationStatus.state === 'completed' && ` through ${new Date(reconciliationStatus.evidence_cutoff).toLocaleString('en-IN', { timeZone: timezone })} (${timezone})`} - {reconciliationStatus.state !== 'completed' &&

{readinessMessage(reconciliationStatus)}

} + {reconciliationStatus.state !== 'completed' && reconciliationStatus.state !== 'cancelled' &&

{readinessMessage(reconciliationStatus)}

}

{reconciliationStatus.state === 'completed' ? 'Later evidence is not included.' : `Evidence cutoff: ${new Date(reconciliationStatus.evidence_cutoff).toLocaleString('en-IN', { timeZone: timezone })} (${timezone}).`}

Evidence details @@ -377,7 +384,13 @@ export default function Timeline() {
{reconciliationStatus.state === 'blocked' && reconciliationStatus.notification_id &&

Backup reminder: {reconciliationStatus.notification_status || 'queued'}

} {reconciliationStatus.last_error &&

{reconciliationStatus.last_error}

} - {(reconciliationStatus.state === 'blocked' || reconciliationStatus.state === 'failed') && ( + {(reconciliationStatus.state === 'queued' || reconciliationStatus.state === 'running') && ( +
+ + {cancelReconciliation.isError && {(cancelReconciliation.error as { response?: { data?: { detail?: string } } })?.response?.data?.detail || 'Cancel failed'}} +
+ )} + {(reconciliationStatus.state === 'blocked' || reconciliationStatus.state === 'failed' || reconciliationStatus.state === 'cancelled') && (
{reconciliationStatus.state === 'blocked' && reconciliationStatus.reason === 'no_immich_evidence' && } diff --git a/backend/webui/src/services/api.ts b/backend/webui/src/services/api.ts index f6d91182..f2d8937d 100644 --- a/backend/webui/src/services/api.ts +++ b/backend/webui/src/services/api.ts @@ -775,7 +775,7 @@ export interface TimelineReconciliationRequest { request_id: string date: string timezone: string - state: 'blocked' | 'queued' | 'running' | 'completed' | 'failed' + state: 'blocked' | 'queued' | 'running' | 'completed' | 'failed' | 'cancelled' reason: 'assets_on_day' | 'later_asset_watermark' | 'no_immich_evidence' | 'immich_unconfigured' | 'immich_unreachable' | 'user_bypassed_immich' target_asset_count: number latest_eligible_asset_date: string | null @@ -852,6 +852,8 @@ export const timelineApi = { api.post(`/api/timeline/reconciliation/day/${date}`, { timezone, skip_immich: skipImmich }), getReconciliation: (requestId: string) => api.get(`/api/timeline/reconciliation/${requestId}`), + cancelReconciliation: (requestId: string) => + api.post(`/api/timeline/reconciliation/${requestId}/cancel`), dismissFailedRange: (dirtyRangeId: string, reason: string) => api.post(`/api/timeline/reconciliation/ranges/${encodeURIComponent(dirtyRangeId)}/dismiss`, { reason }), getAnalysis: (runId: string) => From 30bfd4493729afaf175af061fbdc99691ca139f7 Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Fri, 6 Nov 2026 22:35:25 +0000 Subject: [PATCH 05/27] feat(recordings): add Reprocess Summary to the recording menus POST /api/conversations/{id}/reprocess-summary re-queues the title, short summary and detailed summary jobs. It returns 409 when the recording has no transcript or a summary bundle is still running, because the bundle job IDs are fixed. Co-Authored-By: Claude Opus 5.5 --- .../controllers/conversation_controller.py | 36 ++++++++++ .../backend/controllers/queue_controller.py | 26 +++++++ .../routers/modules/conversation_routes.py | 10 +++ backend/tests/test_reprocess_summary.py | 72 +++++++++++++++++++ backend/webui/src/hooks/useConversations.ts | 11 +++ backend/webui/src/pages/RecordingDetail.tsx | 29 +++++++- backend/webui/src/pages/Recordings.tsx | 38 +++++++++- backend/webui/src/services/api.ts | 1 + 8 files changed, 219 insertions(+), 4 deletions(-) create mode 100644 backend/tests/test_reprocess_summary.py diff --git a/backend/src/backend/controllers/conversation_controller.py b/backend/src/backend/controllers/conversation_controller.py index e8f97e47..ab3bc46a 100644 --- a/backend/src/backend/controllers/conversation_controller.py +++ b/backend/src/backend/controllers/conversation_controller.py @@ -23,6 +23,7 @@ memory_queue, post_conv_enqueue_kwargs, start_post_conversation_jobs, + summary_bundle_in_flight, transcription_queue, ) from backend.models.conversation import Conversation @@ -1260,6 +1261,41 @@ async def reprocess_memory( ) +async def reprocess_summary(conversation_id: str, user: User): + """Regenerate the title, short summary and detailed summary from the active transcript.""" + conversation_model, error = await _get_conversation_or_error(conversation_id, user) + if error: + return error + if not conversation_model.transcript and not conversation_model.segments: + return JSONResponse( + status_code=409, + content={"error": "This recording has no transcript to summarise yet"}, + ) + if summary_bundle_in_flight(conversation_id): + return JSONResponse( + status_code=409, + content={ + "error": "A summary is already being generated for this recording" + }, + ) + + jobs = enqueue_summary_job_bundle( + conversation_id, + meta={"conversation_id": conversation_id, "trigger": "summary_reprocess"}, + ) + logger.info( + f"Enqueued summary reprocessing {[job.id for job in jobs.values()]} " + f"for conversation {conversation_id}" + ) + return JSONResponse( + content={ + "message": f"Summary reprocessing started for conversation {conversation_id}", + "job_ids": {stage: job.id for stage, job in jobs.items()}, + "status": "queued", + } + ) + + async def reprocess_speakers( conversation_id: str, transcript_version_id: str, diff --git a/backend/src/backend/controllers/queue_controller.py b/backend/src/backend/controllers/queue_controller.py index 9707b2fe..da7dd780 100644 --- a/backend/src/backend/controllers/queue_controller.py +++ b/backend/src/backend/controllers/queue_controller.py @@ -245,6 +245,32 @@ def enqueue_summary_job_bundle( } +_SUMMARY_BUNDLE_PREFIXES = ("title_", "short_summary_", "detailed_summary_") +_ACTIVE_JOB_STATUSES = { + JobStatus.QUEUED, + JobStatus.STARTED, + JobStatus.DEFERRED, + JobStatus.SCHEDULED, +} + + +def summary_bundle_in_flight(conversation_id: str) -> bool: + """True while any stage of this conversation's summary bundle is still pending. + + Bundle jobs use fixed IDs, so enqueuing another bundle now would overwrite a + job that a worker may already hold. + """ + suffix = conversation_id[:12] + for prefix in _SUMMARY_BUNDLE_PREFIXES: + try: + job = Job.fetch(f"{prefix}{suffix}", connection=redis_conn) + except NoSuchJobError: + continue + if job.get_status() in _ACTIVE_JOB_STATUSES: + return True + return False + + def get_queue(queue_name: str = DEFAULT_QUEUE) -> Queue: """Get an RQ queue by name.""" queues = { diff --git a/backend/src/backend/routers/modules/conversation_routes.py b/backend/src/backend/routers/modules/conversation_routes.py index 2c2394e3..22a72fba 100644 --- a/backend/src/backend/routers/modules/conversation_routes.py +++ b/backend/src/backend/routers/modules/conversation_routes.py @@ -204,6 +204,16 @@ async def reprocess_memory( ) +@router.post("/{conversation_id}/reprocess-summary") +async def reprocess_summary( + conversation_id: str, current_user: User = Depends(current_active_user) +): + """Regenerate the title and both summaries from the active transcript.""" + return await conversation_controller.reprocess_summary( + conversation_id, current_user + ) + + @router.post("/{conversation_id}/reprocess-speakers") async def reprocess_speakers( conversation_id: str, diff --git a/backend/tests/test_reprocess_summary.py b/backend/tests/test_reprocess_summary.py new file mode 100644 index 00000000..8e8f8b88 --- /dev/null +++ b/backend/tests/test_reprocess_summary.py @@ -0,0 +1,72 @@ +"""Manual summary reprocessing: the Recordings menu's "Reprocess Summary" action.""" + +import json +from types import SimpleNamespace + +import pytest + +from backend.controllers import conversation_controller as controller + +CONVERSATION_ID = "6e37beb4-7d00-4d3d-b9b3-4cb232a6e91a" +USER = SimpleNamespace(user_id="u1", is_superuser=False) + + +def _conversation(transcript="hello there, this is a test", segments=None): + return SimpleNamespace(transcript=transcript, segments=segments or []) + + +@pytest.fixture +def enqueued(monkeypatch): + calls = [] + + async def found(conversation_id, user): + return _conversation(), None + + def enqueue(conversation_id, *, meta=None, **_): + calls.append((conversation_id, meta)) + return { + stage: SimpleNamespace(id=f"{stage}_{conversation_id[:12]}") + for stage in ("title", "short_summary", "detailed_summary") + } + + monkeypatch.setattr(controller, "_get_conversation_or_error", found) + monkeypatch.setattr(controller, "enqueue_summary_job_bundle", enqueue) + monkeypatch.setattr(controller, "summary_bundle_in_flight", lambda _id: False) + return calls + + +async def test_queues_the_full_title_and_summary_bundle(enqueued): + response = await controller.reprocess_summary(CONVERSATION_ID, USER) + + assert response.status_code == 200 + body = json.loads(response.body) + assert body["job_ids"]["title"] == f"title_{CONVERSATION_ID[:12]}" + assert enqueued == [ + ( + CONVERSATION_ID, + {"conversation_id": CONVERSATION_ID, "trigger": "summary_reprocess"}, + ) + ] + + +async def test_refuses_while_a_bundle_is_still_running(enqueued, monkeypatch): + """Bundle job IDs are fixed, so a second enqueue would overwrite a held job.""" + + monkeypatch.setattr(controller, "summary_bundle_in_flight", lambda _id: True) + + response = await controller.reprocess_summary(CONVERSATION_ID, USER) + + assert response.status_code == 409 + assert enqueued == [] + + +async def test_refuses_a_recording_with_no_transcript(enqueued, monkeypatch): + async def empty(conversation_id, user): + return _conversation(transcript=""), None + + monkeypatch.setattr(controller, "_get_conversation_or_error", empty) + + response = await controller.reprocess_summary(CONVERSATION_ID, USER) + + assert response.status_code == 409 + assert enqueued == [] diff --git a/backend/webui/src/hooks/useConversations.ts b/backend/webui/src/hooks/useConversations.ts index 3d033c80..c2fea0bb 100644 --- a/backend/webui/src/hooks/useConversations.ts +++ b/backend/webui/src/hooks/useConversations.ts @@ -83,6 +83,17 @@ export function useReprocessMemory() { }) } +export function useReprocessSummary() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (conversationId: string) => conversationsApi.reprocessSummary(conversationId), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['conversations'] }) + queryClient.invalidateQueries({ queryKey: ['conversation'] }) + }, + }) +} + export function useReprocessSpeakers() { const queryClient = useQueryClient() return useMutation({ diff --git a/backend/webui/src/pages/RecordingDetail.tsx b/backend/webui/src/pages/RecordingDetail.tsx index d310eed3..5a355e44 100644 --- a/backend/webui/src/pages/RecordingDetail.tsx +++ b/backend/webui/src/pages/RecordingDetail.tsx @@ -4,14 +4,14 @@ import { useParams, useNavigate, useLocation, useSearchParams } from 'react-rout import { useQueryClient } from '@tanstack/react-query' import { ArrowLeft, Calendar, User, Trash2, RefreshCw, MoreVertical, - RotateCcw, Zap, Download, Scissors, + RotateCcw, Zap, FileText, Download, Scissors, Save, X, Pencil, Clock, Database, Layers, Star, BarChart3, Hash, AudioLines, ChevronRight, Check, Copy } from 'lucide-react' import { annotationsApi, speakerApi, systemApi, BACKEND_URL } from '../services/api' import { useConversationDetail, - useDeleteConversation, useReprocessTranscript, useReprocessMemory, useReprocessSpeakers, useToggleStar + useDeleteConversation, useReprocessTranscript, useReprocessMemory, useReprocessSummary, useReprocessSpeakers, useToggleStar } from '../hooks/useConversations' import ConversationVersionHeader from '../components/ConversationVersionHeader' import MemoryAuditCard from '../components/MemoryAuditCard' @@ -128,6 +128,7 @@ export default function RecordingDetail({ dataset = false }: { dataset?: boolean // Reprocessing state const [reprocessingTranscript, setReprocessingTranscript] = useState(false) const [reprocessingMemory, setReprocessingMemory] = useState(false) + const [reprocessingSummary, setReprocessingSummary] = useState(false) const [reprocessingSpeakers, setReprocessingSpeakers] = useState(false) const [actionError, setActionError] = useState(null) const [idCopyStatus, setIdCopyStatus] = useState<'idle' | 'copied' | 'error'>('idle') @@ -185,6 +186,7 @@ export default function RecordingDetail({ dataset = false }: { dataset?: boolean const deleteConversationMutation = useDeleteConversation() const reprocessTranscriptMutation = useReprocessTranscript() const reprocessMemoryMutation = useReprocessMemory() + const reprocessSummaryMutation = useReprocessSummary() const reprocessSpeakersMutation = useReprocessSpeakers() const formatDate = (timestamp: number | string) => { @@ -310,6 +312,20 @@ export default function RecordingDetail({ dataset = false }: { dataset?: boolean } } + const handleReprocessSummary = async () => { + if (!id) return + setReprocessingSummary(true) + setOpenDropdown(false) + try { + await reprocessSummaryMutation.mutateAsync(id) + refetch() + } catch (err: any) { + setActionError(`Failed to reprocess summary: ${err.response?.data?.error || err.message || 'Unknown error'}`) + } finally { + setReprocessingSummary(false) + } + } + const handleReprocessSpeakers = async (diarizationSource: 'provider' | 'pyannote') => { if (!id) return setReprocessingSpeakers(true) @@ -498,6 +514,15 @@ export default function RecordingDetail({ dataset = false }: { dataset?: boolean Reprocess Memory )} +
+
{session.total_sources > 0 && (busy || session.state === 'paused') &&

{session.completed_sources} of {session.total_sources} source groups complete · {({ account: 'Building the session account', combining: 'Combining source accounts', checking_claims: 'Independent account review', memory: 'Preparing note changes' } as Record)[session.stage || 'account']}

} - {busy && activityLabel(session) &&

{activityLabel(session)} · last activity {clock(session.investigation_activity!.updated_at, 'Asia/Kolkata')} IST

} + {busy && activityLabel(session) &&

{activityLabel(session)} · last activity {formatTime(session.investigation_activity!.updated_at)}

} {session.error && session.state !== 'generating' &&

{session.state === 'paused' ? (session.failure_kind === 'repeated_tool_call' ? 'Repeated identical tool calls stopped this investigation. Saved source reads and drafts remain inspectable. Restart begins a fresh attempt; no automatic retry is scheduled.' : 'The investigation reached its work limit. Restart to begin a new attempt with completed source groups retained; no automatic retry is scheduled. Earlier exchanges remain available below.') : session.state === 'failed' ? 'Preparation stopped before a reviewed draft was completed. Retry preparation, or inspect the details below.' : session.state === 'stale' ? 'This draft needs refreshing against the current sources before it can be approved.' : session.failure_kind === 'time_slice' ? 'Saved work will continue in the queue.' : session.error}

{session.state === 'failed' &&
Technical details
{session.error}
} @@ -152,7 +153,7 @@ function SessionRow({ session, day, timezone }: { session: MemorySession; day: s {(decide.error || generate.error || restart.error || correction.error) &&

{errorMessage(decide.error || generate.error || restart.error || correction.error)}

} {notice &&

{notice}

} {open &&
- {session.investigation_activity?.event &&
Investigation activity

{session.investigation_activity.tool_calls} tool calls · {session.investigation_activity.rounds} model rounds · Pi {session.investigation_activity.runtime_version}

{session.investigation_activity.checkpoint_saved ? 'Native session checkpoint saved' : 'Awaiting first complete checkpoint'}{session.investigation_activity.resumed ? ' · resumed saved work' : ''}

Last activity {clock(session.investigation_activity.updated_at, 'Asia/Kolkata')} IST

} + {session.investigation_activity?.event &&
Investigation activity

{session.investigation_activity.tool_calls} tool calls · {session.investigation_activity.rounds} model rounds · Pi {session.investigation_activity.runtime_version}

{session.investigation_activity.checkpoint_saved ? 'Native session checkpoint saved' : 'Awaiting first complete checkpoint'}{session.investigation_activity.resumed ? ' · resumed saved work' : ''}

Last activity {formatTime(session.investigation_activity.updated_at)}

} {proposal && reviewing && } {questions.map(question =>

{question}

)} {questions.length > 0 &&