diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index de61a811..659d5450 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -109,6 +109,7 @@ jobs: uv run --no-project --with ./extras/chronicle-client --with pytest + --with pytest-asyncio pytest extras/chronicle-client/tests -q backend-unit: @@ -129,7 +130,7 @@ jobs: ports: - 6379:6379 mongo: - image: mongo:8 + image: mongo:8.0.14 ports: - 27018:27017 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") 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(); } diff --git a/backend/src/backend/browser_sessions.py b/backend/src/backend/browser_sessions.py index bd52ddca..9a71b9f5 100644 --- a/backend/src/backend/browser_sessions.py +++ b/backend/src/backend/browser_sessions.py @@ -14,10 +14,12 @@ from beanie import Document, PydanticObjectId from fastapi import APIRouter, Depends, HTTPException, Request, Response from fastapi.security import OAuth2PasswordRequestForm +from fastapi_users.authentication import JWTStrategy from fastapi_users.exceptions import UserNotExists from pymongo import IndexModel from .auth import SECRET_KEY, UserManager, get_jwt_strategy, get_user_manager +from .models.api_key import TOKEN_SCHEME COOKIE_NAME = "chronicle_session" SESSION_SECONDS = 30 * 24 * 60 * 60 @@ -105,6 +107,35 @@ async def login( user = await manager.authenticate(credentials) if user is None or not user.is_active: raise HTTPException(400, "LOGIN_BAD_CREDENTIALS") + return await start_session(user, request, response, manager) + + +@router.post("/exchange") +async def exchange( + request: Request, + response: Response, + manager: UserManager = Depends(get_user_manager), +): + """Trade a bearer JWT for a browser session (single sign-on handoff). + + A host such as Ushadow mints a JWT for the user with the shared signing key + and opens the WebUI with it; the WebUI calls this once so renewal works like + a password sign-in. API keys are refused: they are long-lived machine + credentials, not an interactive sign-in. + """ + scheme, _, token = request.headers.get("Authorization", "").partition(" ") + if scheme.lower() != "bearer" or not token or token.startswith(f"{TOKEN_SCHEME}_"): + raise HTTPException(401, "Bearer JWT required") + user = await JWTStrategy.read_token(get_jwt_strategy(), token, manager) + if user is None or not user.is_active: + raise HTTPException(401, "Invalid or expired token") + return await start_session(user, request, response, manager) + + +async def start_session( + user, request: Request, response: Response, manager: UserManager +): + """Create a refresh session and cookie for an authenticated user.""" token = secrets.token_urlsafe(32) await revoke_cookie(request) await BrowserSession( 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/constants.py b/backend/src/backend/constants.py index 9879d068..ae1f514b 100644 --- a/backend/src/backend/constants.py +++ b/backend/src/backend/constants.py @@ -26,9 +26,11 @@ UNKNOWN_SPEAKER_PREFIX = "Unknown Speaker" # Matches the placeholder unknown labels: "Unknown", "Unknown 1", -# "Unknown Speaker", "Unknown Speaker 2", "unknown_speaker_3" (case-insensitive). +# "Unknown Speaker", "Unknown Speaker 2", "unknown_speaker_3" (case-insensitive), +# and the raw diarization labels a transcript keeps when speaker recognition did +# not run: Deepgram's "Speaker 0" and pyannote's "SPEAKER_00". _UNKNOWN_SPEAKER_RE = re.compile( - r"^\s*unknown(?:[ _]speaker)?(?:[ _]*\d+)?\s*$", re.IGNORECASE + r"^\s*(?:unknown(?:[ _]speaker)?(?:[ _]*\d+)?|speaker[ _]*\d+)\s*$", re.IGNORECASE ) 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/guided_enrollment_controller.py b/backend/src/backend/controllers/guided_enrollment_controller.py index 2ee6f2ac..a8055f47 100644 --- a/backend/src/backend/controllers/guided_enrollment_controller.py +++ b/backend/src/backend/controllers/guided_enrollment_controller.py @@ -35,7 +35,7 @@ from backend.models.annotation import Annotation, AnnotationType from backend.models.conversation import Conversation from backend.services import privacy -from backend.services.speaker_enrollment import capture_evidence +from backend.services.speaker_enrollment import EnrollmentUnavailable, capture_evidence from backend.speaker_recognition_client import SpeakerRecognitionClient from backend.users import User from backend.utils.audio_chunk_utils import reconstruct_audio_segment @@ -255,7 +255,7 @@ async def decide_unknown_cluster( existing_speaker = await client.get_speaker_by_name( speaker_name, user_id=str(user.user_id) ) - enrolled = appended = 0 + enrolled = appended = skipped = 0 for clip in enrollment_clips: member = accepted.get(clip.get("identity_key")) if not member: @@ -278,32 +278,39 @@ async def decide_unknown_cluster( member["conversation_id"], ref["start"], ref["end"] ) await visibility.assert_current() - if existing_speaker: - result = await client.append_to_speaker( - existing_speaker["id"], - wav, - user_id=str(user.user_id), - speaker_name=speaker_name, - conversation_ids=[member["conversation_id"]], - visibility=visibility, - evidence_records=evidence_records, - ) - if not result.get("error"): - appended += 1 - else: - result = await client.enroll_new_speaker( - speaker_name, - wav, - user_id=str(user.user_id), - conversation_ids=[member["conversation_id"]], - visibility=visibility, - evidence_records=evidence_records, - ) - if not result.get("error"): - enrolled += 1 - existing_speaker = await client.get_speaker_by_name( - speaker_name, user_id=str(user.user_id) + # The provider can refuse one clip (e.g. its audio is byte-identical to a + # clip already enrolled). That operation is quarantined; skip the clip + # so the clips already enrolled are not reported as a failed decision. + try: + if existing_speaker: + result = await client.append_to_speaker( + existing_speaker["id"], + wav, + user_id=str(user.user_id), + speaker_name=speaker_name, + conversation_ids=[member["conversation_id"]], + visibility=visibility, + evidence_records=evidence_records, ) + if not result.get("error"): + appended += 1 + else: + result = await client.enroll_new_speaker( + speaker_name, + wav, + user_id=str(user.user_id), + conversation_ids=[member["conversation_id"]], + visibility=visibility, + evidence_records=evidence_records, + ) + if not result.get("error"): + enrolled += 1 + existing_speaker = await client.get_speaker_by_name( + speaker_name, user_id=str(user.user_id) + ) + except EnrollmentUnavailable: + skipped += 1 + logger.warning("Skipped an enrollment clip the speaker service refused") await visibility.assert_current() async with visibility.publication(): @@ -325,6 +332,7 @@ async def decide_unknown_cluster( "annotations_created": annotations, "enrolled_new": enrolled, "appended": appended, + "skipped": skipped, "corrections_applied": getattr(apply_result, "body", apply_result), } diff --git a/backend/src/backend/controllers/queue_controller.py b/backend/src/backend/controllers/queue_controller.py index 9707b2fe..e68c8269 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 @@ -245,6 +246,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 = { @@ -927,6 +954,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/controllers/system_controller.py b/backend/src/backend/controllers/system_controller.py index 8c62da77..4325890f 100644 --- a/backend/src/backend/controllers/system_controller.py +++ b/backend/src/backend/controllers/system_controller.py @@ -15,7 +15,7 @@ from datetime import UTC, datetime from io import StringIO from pathlib import Path -from typing import Optional +from typing import Any, Optional from urllib.parse import urlparse import httpx @@ -48,6 +48,7 @@ _find_config_path, get_models_registry, load_models_config, + output_token_limit_findings, ) from backend.model_routes import effective_model_routes, effective_operation_routes from backend.models.user import User @@ -176,6 +177,42 @@ def _is_self_hosted_model(model) -> bool: return host.endswith(".ts.net") or "." not in host +def _output_limit_issues(registry: Any) -> list[dict[str, Any]]: + """Report each max_tokens setting its model cannot honour. + + These are errors: the operation refuses to run (see ``OutputLimitExceeded``) + until a larger-output model is chosen or the setting is lowered. + """ + + timeline_pi = (load_config().get("timeline", {}) or {}).get("pi", {}) or {} + extra = [ + ( + "timeline.pi.max_tokens", + str(timeline_pi.get("operation") or "timeline_segmentation"), + timeline_pi.get("max_tokens"), + ) + ] + return [ + { + "component": "Model Limits", + "severity": "error", + "message": ( + f"'{finding['operation']}' needs a model with at least " + f"{finding['requested']} output tokens, but it uses " + f"{finding['model']} ({finding['model_name']}), which accepts at most " + f"{finding['limit']}. It will not run until this is fixed." + ), + "resolution": ( + f"Settings > AI Model Settings: route '{finding['operation']}' to a " + f"model that supports at least {finding['requested']} output " + f"tokens. Or lower {finding['setting']} to {finding['limit']} or " + f"less, if shorter results are acceptable." + ), + } + for finding in output_token_limit_findings(registry, extra) + ] + + async def get_config_diagnostics(): """ Get comprehensive configuration diagnostics. @@ -360,6 +397,13 @@ async def get_config_diagnostics(): } ) + # Listed under issues so the health poller records a System Event. + limit_issues = _output_limit_issues(registry) + if limit_issues: + diagnostics["issues"].extend(limit_issues) + if diagnostics["overall_status"] == "healthy": + diagnostics["overall_status"] = "partial" + else: diagnostics["overall_status"] = "unhealthy" diagnostics["issues"].append( @@ -2679,7 +2723,9 @@ async def create_plugin( if events else '"conversation.complete"' ) - boilerplate = inspect.cleandoc(f''' + boilerplate = ( + inspect.cleandoc( + f''' """ {class_name} implementation. @@ -2716,7 +2762,10 @@ async def cleanup(self): async def on_conversation_complete(self, context: PluginContext) -> Optional[PluginResult]: logger.info(f"Processing conversation for user: {{context.user_id}}") return PluginResult(success=True, message="OK") - ''') + "\n" + ''' + ) + + "\n" + ) (plugin_dir / "plugin.py").write_text(boilerplate, encoding="utf-8") created_files.append("plugin.py") 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..90d7ea60 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. @@ -150,6 +181,17 @@ def reasoning_allowed(self) -> bool: embedding_dimensions: Optional[int] = Field( default=None, ge=1, description="Embedding vector dimensions" ) + max_output_tokens: Optional[int] = Field( + default=None, + ge=1, + description=( + "Largest completion the provider accepts for this model. A request for " + "more is rejected outright (OpenAI returns HTTP 400), so every requested " + "max_tokens is fitted to this value. Unset means unknown: requests pass " + "through unchanged, which is the right default for local servers whose " + "only limit is their context window." + ), + ) operations: Dict[str, Any] = Field( default_factory=dict, description="API operation definitions" ) @@ -254,6 +296,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.""" @@ -287,6 +335,94 @@ def validate_model(self) -> ModelDef: return self +class OutputLimitExceeded(ValueError): + """A configured max_tokens is larger than the routed model can produce. + + Raised before any request is sent. Silently shrinking the allowance would run the + operation with less room than it was tuned for (a long timeline day is cut off + before its last episodes), so the operator is told to choose a bigger model. + """ + + def __init__(self, *, setting: str, model: str, requested: int, limit: int): + self.setting = setting + self.model = model + self.requested = requested + self.limit = limit + super().__init__( + f"{setting} needs {requested} output tokens, but model '{model}' accepts " + f"at most {limit}. Choose a model that supports at least {requested} " + f"output tokens for this operation (Settings > AI Model Settings), or " + f"lower {setting}." + ) + + +def check_output_tokens(model_def: Any, requested: int, *, setting: str) -> int: + """Return ``requested`` if the model can produce it; raise otherwise.""" + + # Test fakes and extra-field model entries share this path with ModelDef, the + # same way callers already read ``context_window``. + return check_output_limit( + getattr(model_def, "max_output_tokens", None), + requested, + setting=setting, + model=str(model_def.name), + ) + + +def check_output_limit( + limit: Optional[int], requested: int, *, setting: str, model: str +) -> int: + """Core of :func:`check_output_tokens` for callers holding only the limit. + + An undeclared limit means unknown, so the request passes through unchanged. + """ + + if limit is not None and requested > limit: + raise OutputLimitExceeded( + setting=setting, model=model, requested=int(requested), limit=int(limit) + ) + return requested + + +def output_token_limit_findings( + registry: "AppModels", + extra_settings: Optional[List[tuple[str, str, Any]]] = None, +) -> List[Dict[str, Any]]: + """List every configured ``max_tokens`` larger than its model accepts. + + Checks each ``llm_operations`` entry against the model it routes to, plus + ``extra_settings``: ``(setting_path, operation_name, requested)`` triples for + feature settings that override an operation's limit (``timeline.pi.max_tokens``). + """ + + candidates: List[tuple[str, str, Any]] = [] + for name, op_config in registry.llm_operations.items(): + if op_config.max_tokens is not None: + candidates.append( + (f"llm_operations.{name}.max_tokens", name, op_config.max_tokens) + ) + candidates.extend(extra_settings or []) + + findings: List[Dict[str, Any]] = [] + for setting, operation, requested in candidates: + if requested in (None, "") or isinstance(requested, bool): + continue + model_def = registry.resolve_operation_model(operation) + limit = model_def.max_output_tokens + if limit is not None and int(requested) > limit: + findings.append( + { + "setting": setting, + "operation": operation, + "model": model_def.name, + "model_name": model_def.model_name, + "requested": int(requested), + "limit": limit, + } + ) + return findings + + class LLMOperationConfig(BaseModel): """Per-operation LLM config as written in YAML. @@ -319,6 +455,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 +570,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, ) @@ -526,28 +663,13 @@ def list_model_types(self) -> List[str]: """ return sorted(set(m.model_type for m in self.models.values())) - def get_llm_operation( - self, - name: str, - *, - model_override: Optional[str] = None, - ) -> ResolvedLLMOperation: - """Resolve a named LLM operation to a self-contained config. - - Resolution: - 1. Look up llm_operations[name] (empty LLMOperationConfig if missing) - 2. Resolve model_def: model_override → get_by_name, else op.model → - get_by_name, else the operation's centrally defined default role - 3. Merge parameters: operation > model_def.model_params > safe fallback - 4. Return ResolvedLLMOperation ready for use + def resolve_operation_model( + self, name: str, *, model_override: Optional[str] = None + ) -> ModelDef: + """Return the model an operation routes to, without validating its settings. - Args: - name: Operation name (e.g. "memory_extraction", "chat") - model_override: pin a specific model by name, overriding both the - operation's model and the defaults (used for fallback retries). - - Returns: - ResolvedLLMOperation with model_def, temperature, max_tokens, response_format + Diagnostics and route explanations use this so a misconfigured operation can + still be reported; :meth:`get_llm_operation` adds the settings checks. Raises: RuntimeError: If no model can be resolved for the operation @@ -555,7 +677,6 @@ def get_llm_operation( op_config = self.llm_operations.get(name, LLMOperationConfig()) default_role = self.llm_operation_role(name) - # Resolve model definition if model_override: model_def = self.get_by_name(model_override) if not model_def: @@ -578,6 +699,37 @@ def get_llm_operation( raise RuntimeError( f"No model specified for operation '{name}' and no default LLM defined" ) + return model_def + + def get_llm_operation( + self, + name: str, + *, + model_override: Optional[str] = None, + ) -> ResolvedLLMOperation: + """Resolve a named LLM operation to a self-contained config. + + Resolution: + 1. Look up llm_operations[name] (empty LLMOperationConfig if missing) + 2. Resolve model_def: model_override → get_by_name, else op.model → + get_by_name, else the operation's centrally defined default role + 3. Merge parameters: operation > model_def.model_params > safe fallback + 4. Return ResolvedLLMOperation ready for use + + Args: + name: Operation name (e.g. "memory_extraction", "chat") + model_override: pin a specific model by name, overriding both the + operation's model and the defaults (used for fallback retries). + + Returns: + ResolvedLLMOperation with model_def, temperature, max_tokens, response_format + + Raises: + RuntimeError: If no model can be resolved for the operation + OutputLimitExceeded: If max_tokens is larger than the model can produce + """ + op_config = self.llm_operations.get(name, LLMOperationConfig()) + model_def = self.resolve_operation_model(name, model_override=model_override) # Merge parameters: operation config > model_params > safe fallback model_params = model_def.model_params or {} @@ -603,12 +755,21 @@ def get_llm_operation( if op_config.response_format == "json": response_format = {"type": "json_object"} + if max_tokens is not None: + source = ( + f"llm_operations.{name}.max_tokens" + if op_config.max_tokens is not None + else f"models.{model_def.name}.model_params.max_tokens" + ) + max_tokens = check_output_tokens(model_def, int(max_tokens), setting=source) + return ResolvedLLMOperation( model_def=model_def, temperature=float(temperature), 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]]: @@ -620,11 +781,11 @@ def explain_llm_operation(self, name: str) -> Dict[str, Optional[str]]: else: role = self.llm_operation_role(name) source = f"defaults.{role}" - resolved = self.get_llm_operation(name) + model_def = self.resolve_operation_model(name) return { - "model": resolved.model_def.name, - "model_name": resolved.model_name, - "provider": resolved.model_def.model_provider, + "model": model_def.name, + "model_name": model_def.model_name, + "provider": model_def.model_provider, "role": role, "source": source, } 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/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/src/backend/routers/modules/timeline_routes.py b/backend/src/backend/routers/modules/timeline_routes.py index 6f8dcf16..a9228dc3 100644 --- a/backend/src/backend/routers/modules/timeline_routes.py +++ b/backend/src/backend/routers/modules/timeline_routes.py @@ -19,6 +19,7 @@ import backend.services.privacy as privacy import backend.services.timeline.memory_sources as memory_sources from backend.auth import current_active_user +from backend.model_registry import OutputLimitExceeded from backend.models.audio_chunk import AudioChunkDocument from backend.models.conversation import Conversation from backend.models.notification import NotificationIntent @@ -61,6 +62,7 @@ ) from backend.services.timeline.dirty_ranges import ( DirtyRangeDismissalError, + DirtyRangeLeaseLost, dismiss_failed_range, ) from backend.services.timeline.dispatch import enqueue_episode_detailed_summary @@ -73,7 +75,12 @@ EvidenceRelationPreview, infer_evidence_relations, ) +from backend.services.timeline.executor import ( + check_output_limits as check_timeline_output_limits, +) from backend.services.timeline.explicit_reconciliation import ( + ReconciliationNotCancellable, + cancel_explicit_reconciliation, reconciliation_request_payload, request_explicit_reconciliation, ) @@ -551,6 +558,10 @@ async def reconcile_timeline_day( user: User = Depends(current_active_user), ): timezone = _validate_timezone(body.timezone) + try: + check_timeline_output_limits() + except OutputLimitExceeded as error: + raise HTTPException(status_code=409, detail=str(error)) from error try: request, created = await request_explicit_reconciliation( user=user, @@ -563,6 +574,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/memory/agent/operating_memory_optimizer.py b/backend/src/backend/services/memory/agent/operating_memory_optimizer.py index 673f74b4..739eb3a4 100644 --- a/backend/src/backend/services/memory/agent/operating_memory_optimizer.py +++ b/backend/src/backend/services/memory/agent/operating_memory_optimizer.py @@ -10,6 +10,7 @@ from typing import Any from backend.config_loader import load_config +from backend.model_registry import check_output_limit from backend.services.inference_artifacts import ( canonical_hash, load_inference_runs, @@ -108,8 +109,11 @@ def _optimizer_runtime_config(config: Any) -> Any: """Give the meta-optimizer room to reason and still emit its tool call.""" values = dict(vars(config)) - values["max_tokens"] = max( - _OPTIMIZER_MIN_MAX_TOKENS, int(values.get("max_tokens") or 0) + values["max_tokens"] = check_output_limit( + values.get("max_output_tokens"), + max(_OPTIMIZER_MIN_MAX_TOKENS, int(values.get("max_tokens") or 0)), + setting="operating_memory optimizer minimum max_tokens", + model=str(values.get("model_entry") or values.get("model") or ""), ) return type(config)(**values) diff --git a/backend/src/backend/services/memory/agent/pi_agent.py b/backend/src/backend/services/memory/agent/pi_agent.py index dc7f82a0..c4f79949 100644 --- a/backend/src/backend/services/memory/agent/pi_agent.py +++ b/backend/src/backend/services/memory/agent/pi_agent.py @@ -26,7 +26,13 @@ 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, + check_output_tokens, + get_models_registry, + require_api_key, +) from backend.services.inference_artifacts import canonical_hash, persist_inference_run from ..session_write import WriteSourcePermissions @@ -202,6 +208,10 @@ class _PiRuntimeConfig: system_prompt_prefix: str = "" compat: Dict[str, Any] = field(default_factory=dict) reasoning_allowed: bool = False + # The model's declared completion cap, kept so a later per-feature override of + # max_tokens (timeline.pi.max_tokens) is checked against the same model. + max_output_tokens: Optional[int] = None + model_entry: str = "" def __post_init__(self) -> None: if not self.reasoning_allowed: @@ -437,6 +447,11 @@ def _resolve_pi_config( name="max_tokens", default=DEFAULT_MAX_TOKENS, ) + # resolved.max_tokens is already checked by the registry; the settings fallback + # and the built-in default are not. + max_tokens = check_output_tokens( + model_def, max_tokens, setting="memory.backends.pi.max_tokens" + ) if max_tokens > context_window - MIN_PROMPT_HEADROOM_TOKENS: raise PiExecutorError( "memory.backends.pi.max_tokens must leave at least " @@ -452,7 +467,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, @@ -463,6 +481,8 @@ def _resolve_pi_config( ), reasoning=bool(model_def.thinking), reasoning_allowed=resolved.reasoning_allowed, + max_output_tokens=getattr(model_def, "max_output_tokens", None), + model_entry=str(model_def.name), temperature=resolved.temperature, sampling={ key: model_params[key] 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/executor.py b/backend/src/backend/services/timeline/executor.py index 4191b32d..26f98a8e 100644 --- a/backend/src/backend/services/timeline/executor.py +++ b/backend/src/backend/services/timeline/executor.py @@ -10,6 +10,11 @@ from omegaconf import OmegaConf from backend.config_loader import load_config +from backend.model_registry import ( + OutputLimitExceeded, + get_models_registry, + output_token_limit_findings, +) from backend.services.job_progress import report_job_progress from .codex_executor import CodexTimelineExecutor @@ -485,6 +490,39 @@ def settings_dict() -> dict[str, Any]: return converted if isinstance(converted, dict) else {} +def check_output_limits() -> None: + """Refuse a timeline run that the configured model cannot complete. + + Called before a day is queued so the person asking sees the model-choice + message at once, rather than a background failure after the run starts. The + executor repeats the check at run time; this is only the early warning. + """ + + settings = settings_dict() + if str(settings.get("executor") or "pi") != "pi": + return # Codex runs on its own subscription model and limits. + registry = get_models_registry() + if registry is None: + return # The run itself raises the precise registry error. + pi = settings.get("pi") or {} + operation = str(pi.get("operation") or "timeline_segmentation") + findings = [ + finding + for finding in output_token_limit_findings( + registry, [("timeline.pi.max_tokens", operation, pi.get("max_tokens"))] + ) + if finding["operation"] == operation + ] + if findings: + finding = findings[0] + raise OutputLimitExceeded( + setting=finding["setting"], + model=finding["model"], + requested=finding["requested"], + limit=finding["limit"], + ) + + def build_executor(): settings = settings_dict() executor = str(settings.get("executor") or "pi") 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/services/timeline/pi_executor.py b/backend/src/backend/services/timeline/pi_executor.py index b56d9986..126b6516 100644 --- a/backend/src/backend/services/timeline/pi_executor.py +++ b/backend/src/backend/services/timeline/pi_executor.py @@ -19,6 +19,7 @@ import backend.services.timeline.pi_tasks as pi_tasks import backend.services.timeline.prompt as prompt +from backend.model_registry import check_output_limit from backend.services.inference_artifacts import ( invalidate_reusable_result, load_reusable_result, @@ -753,6 +754,16 @@ def _final_stage_config(self, reasoning_effort: str | None) -> Any: raise ValueError( "timeline.pi.max_tokens must be a positive integer" ) from exc + if max_tokens > 0: + # The shipped 32K allowance needs a large-output model. Stop with a + # model-choice message rather than send a request the provider + # rejects, or quietly shrink the room a dense day needs. + max_tokens = check_output_limit( + config.max_output_tokens, + max_tokens, + setting="timeline.pi.max_tokens", + model=config.model_entry, + ) if max_tokens <= 0 or max_tokens > config.context_window - 1024: raise ValueError( "timeline.pi.max_tokens must be positive and leave at least " diff --git a/backend/src/backend/services/transcription/__init__.py b/backend/src/backend/services/transcription/__init__.py index cd9585df..3d4ddce5 100644 --- a/backend/src/backend/services/transcription/__init__.py +++ b/backend/src/backend/services/transcription/__init__.py @@ -944,16 +944,29 @@ async def process_audio_chunk( return None async def end_stream(self, stream_id: str) -> dict: - if stream_id not in self._streams: + # Unregister first so no exit path below can leak the stream entry. + stream = self._streams.pop(stream_id, None) + if stream is None: return {"text": "", "words": [], "segments": []} - ws = self._streams[stream_id]["ws"] + ws = stream["ws"] ops = self.model.operations or {} - pending = self._streams[stream_id].get("pending_audio") - if pending: - await ws.send(bytes(pending)) - pending.clear() + pending = stream.get("pending_audio") end_msg = (ops.get("end", {}) or {}).get("message", {"type": "stop"}) - await ws.send(json.dumps(end_msg)) + try: + if pending: + await ws.send(bytes(pending)) + pending.clear() + await ws.send(json.dumps(end_msg)) + except websockets.exceptions.ConnectionClosed as e: + # The provider already closed the socket, e.g. Deepgram's idle + # timeout (NET-0001) after ~10 s without audio. Finals that arrived + # before the close were already published; nothing is left to flush. + logger.warning( + f"Provider closed stream {stream_id} before it ended " + f"(code={e.rcvd.code if e.rcvd else None}, " + f"reason={e.rcvd.reason if e.rcvd else ''})" + ) + return {"text": "", "words": [], "segments": []} expect = ops.get("expect", {}) or {} final_type = expect.get("final_type") @@ -978,8 +991,6 @@ async def end_stream(self, stream_id: str) -> dict: except Exception: pass - self._streams.pop(stream_id, None) - if not isinstance(final, dict): return {"text": "", "words": [], "segments": []} segments = ( diff --git a/backend/src/backend/workers/speaker_jobs.py b/backend/src/backend/workers/speaker_jobs.py index c1c715f7..7b0f9886 100644 --- a/backend/src/backend/workers/speaker_jobs.py +++ b/backend/src/backend/workers/speaker_jobs.py @@ -1332,6 +1332,37 @@ async def recognise_speakers_job( "processing_time_seconds": 0, } + # Probe before any gallery read: an unreachable service otherwise fails inside + # the enrollment-catalog call and surfaces as a misleading PrivacyHeld. + if not await speaker_client.health_check(): + if create_mode: + raise SpeakerReprocessFailed( + f"speaker service at {speaker_client.service_url} is not reachable" + ) + logger.warning( + f"🎤 Speaker service {speaker_client.service_url} not reachable; " + f"skipping speaker recognition for {conversation_id}" + ) + record_event_sync( + severity="warning", + category="service", + source="speaker_recognition", + title="Speaker service unreachable; speaker recognition skipped", + detail=f"{speaker_client.service_url} did not answer its health check", + user_id=str(user_id) if user_id else None, + client_id=conversation.client_id, + conversation_id=conversation_id, + incident_key="speaker-service-unavailable", + ) + return { + "success": True, + "conversation_id": conversation_id, + "version_id": version_id, + "speaker_recognition_enabled": True, + "skip_reason": "Speaker service unavailable", + "processing_time_seconds": time.time() - start_time, + } + if transcript_version.segments and not any( _is_speech_segment(segment) for segment in transcript_version.segments ): 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_browser_sessions.py b/backend/tests/test_browser_sessions.py index fb32b4be..239a7412 100644 --- a/backend/tests/test_browser_sessions.py +++ b/backend/tests/test_browser_sessions.py @@ -47,6 +47,7 @@ async def find_one(cls, query): authenticate=AsyncMock(return_value=user), get=AsyncMock(return_value=user), on_after_login=AsyncMock(), + parse_id=PydanticObjectId, ) def make_app(): @@ -144,7 +145,7 @@ async def test_logout_revokes_stolen_cookie_and_is_idempotent(browser): @pytest.mark.asyncio -@pytest.mark.parametrize("endpoint", ["login", "refresh", "logout"]) +@pytest.mark.parametrize("endpoint", ["login", "refresh", "logout", "exchange"]) async def test_csrf_requests_rejected(browser, endpoint): client, rows, _, _ = browser await sign_in(client) @@ -185,3 +186,64 @@ async def test_bad_login_does_not_create_session(browser): ) assert result.status_code == 400 assert not rows + + +def host_token(user_id, *, key=None, expires_in=300, audience=("ushadow", "chronicle")): + """A JWT as a host app (Ushadow) mints it with the shared signing key.""" + now = datetime.now(UTC) + return jwt.encode( + { + "sub": str(user_id), + "iss": "ushadow", + "aud": list(audience), + "iat": now, + "exp": now + timedelta(seconds=expires_in), + }, + key or sessions.SECRET_KEY, + algorithm="HS256", + ) + + +@pytest.mark.asyncio +async def test_exchange_turns_host_token_into_renewable_session(browser): + client, rows, manager, _ = browser + user = manager.get.return_value + result = await client.post( + "/auth/session/exchange", + headers={"Authorization": f"Bearer {host_token(user.id)}"}, + ) + assert result.status_code == 200 + assert result.headers["cache-control"] == "no-store" + assert sessions.digest(client.cookies.get(sessions.COOKIE_NAME)) in rows + payload = jwt.decode( + result.json()["access_token"], + sessions.SECRET_KEY, + algorithms=["HS256"], + audience="fastapi-users:auth", + ) + assert payload["sub"] == str(user.id) + assert (await client.post("/auth/session/refresh")).status_code == 200 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "failure", + ["missing", "api_key", "wrong_key", "expired", "wrong_audience", "disabled"], +) +async def test_exchange_rejects_unusable_tokens(browser, failure): + client, rows, manager, _ = browser + user = manager.get.return_value + token = { + "missing": "", + "api_key": "chrn_abc123abc123_secret", + "wrong_key": host_token(user.id, key="not-the-shared-key"), + "expired": host_token(user.id, expires_in=-60), + "wrong_audience": host_token(user.id, audience=("someone-else",)), + "disabled": host_token(user.id), + }[failure] + if failure == "disabled": + user.is_active = False + headers = {"Authorization": f"Bearer {token}"} if token else {} + result = await client.post("/auth/session/exchange", headers=headers) + assert result.status_code == 401 + assert not rows 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/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) diff --git a/backend/tests/test_model_output_limits.py b/backend/tests/test_model_output_limits.py new file mode 100644 index 00000000..ee9c1add --- /dev/null +++ b/backend/tests/test_model_output_limits.py @@ -0,0 +1,195 @@ +"""An operation whose max_tokens its model cannot produce refuses to run. + +Regression: timeline days failed with OpenAI HTTP 400 ("max_tokens is too large: +32000. This model supports at most 16384") because the shipped 32K timeline +allowance was sent unchanged to gpt-4o-mini. The fix stops before the request and +asks for a larger-output model; it does not shrink the allowance silently. +""" + +from pathlib import Path + +import pytest +import yaml + +import backend.services.timeline.executor as timeline_executor +import backend.services.timeline.pi_executor as pi_executor +from backend.model_registry import ( + AppModels, + LLMOperationConfig, + ModelDef, + OutputLimitExceeded, + output_token_limit_findings, +) +from backend.services.memory.agent.pi_agent import _PiRuntimeConfig + +DEFAULTS_YML = Path(__file__).resolve().parents[2] / "config" / "defaults.yml" + + +def _model(name: str, max_output_tokens=None) -> ModelDef: + return ModelDef( + name=name, + model_type="llm", + model_provider="openai", + model_name="gpt-4o-mini", + model_url="https://api.openai.com/v1", + max_output_tokens=max_output_tokens, + model_params={"max_tokens": 2000}, + ) + + +def _registry(model: ModelDef, **operations) -> AppModels: + return AppModels( + defaults={"llm": model.name}, + models={model.name: model}, + llm_operations={ + name: LLMOperationConfig(max_tokens=value) + for name, value in operations.items() + }, + ) + + +def test_oversized_operation_refuses_and_names_the_model(): + registry = _registry(_model("small", 16384), timeline_segmentation=32000) + + with pytest.raises(OutputLimitExceeded) as raised: + registry.get_llm_operation("timeline_segmentation") + + message = str(raised.value) + assert "llm_operations.timeline_segmentation.max_tokens needs 32000" in message + assert "model 'small' accepts at most 16384" in message + assert "Choose a model that supports at least 32000" in message + + +def test_operation_within_limit_is_unchanged(): + registry = _registry(_model("small", 16384), chat=8000) + + assert registry.get_llm_operation("chat").max_tokens == 8000 + + +def test_model_without_declared_limit_passes_requests_through(): + registry = _registry(_model("local"), timeline_segmentation=32000) + + assert registry.get_llm_operation("timeline_segmentation").max_tokens == 32000 + + +def test_route_explanation_still_works_for_a_misconfigured_operation(): + registry = _registry(_model("small", 16384), timeline_segmentation=32000) + + assert registry.explain_llm_operation("timeline_segmentation")["model"] == "small" + + +def test_findings_name_each_oversized_setting(): + registry = _registry(_model("small", 16384), timeline_segmentation=32000, chat=8000) + + findings = output_token_limit_findings( + registry, + [("timeline.pi.max_tokens", "timeline_segmentation", 32000)], + ) + + assert [f["setting"] for f in findings] == [ + "llm_operations.timeline_segmentation.max_tokens", + "timeline.pi.max_tokens", + ] + assert findings[0]["model"] == "small" + assert findings[0]["requested"] == 32000 + assert findings[0]["limit"] == 16384 + + +def _pi_config(max_output_tokens) -> _PiRuntimeConfig: + return _PiRuntimeConfig( + binary="pi", + provider="openai", + model="gpt-4o-mini", + base_url="https://api.openai.com/v1", + api_key="k", + thinking="off", + max_tokens=4096, + context_window=98304, + timeout_seconds=30, + reasoning=False, + temperature=0.0, + max_output_tokens=max_output_tokens, + model_entry="openai-llm", + ) + + +def test_timeline_pi_override_refuses_a_small_model(monkeypatch): + monkeypatch.setattr( + pi_executor, "_resolve_pi_config", lambda operation: _pi_config(16384) + ) + executor = pi_executor.PiTimelineExecutor({"max_tokens": 32000}) + + with pytest.raises(OutputLimitExceeded, match="timeline.pi.max_tokens needs 32000"): + executor._final_stage_config(None) + + +def test_timeline_pi_override_kept_for_a_large_model(monkeypatch): + monkeypatch.setattr( + pi_executor, "_resolve_pi_config", lambda operation: _pi_config(None) + ) + + config = pi_executor.PiTimelineExecutor({"max_tokens": 32000})._final_stage_config( + None + ) + + assert config.max_tokens == 32000 + + +def test_timeline_preflight_refuses_before_a_day_is_queued(monkeypatch): + monkeypatch.setattr( + timeline_executor, + "settings_dict", + lambda: {"executor": "pi", "pi": {"max_tokens": 32000}}, + ) + monkeypatch.setattr( + timeline_executor, + "get_models_registry", + lambda: _registry(_model("openai-llm", 16384)), + ) + + with pytest.raises(OutputLimitExceeded, match="model 'openai-llm'"): + timeline_executor.check_output_limits() + + +def test_timeline_preflight_ignores_the_codex_executor(monkeypatch): + monkeypatch.setattr( + timeline_executor, + "settings_dict", + lambda: {"executor": "codex", "pi": {"max_tokens": 32000}}, + ) + monkeypatch.setattr( + timeline_executor, + "get_models_registry", + lambda: _registry(_model("openai-llm", 16384)), + ) + + timeline_executor.check_output_limits() + + +def test_shipped_openai_models_declare_their_output_limits(): + models = {m["name"]: m for m in yaml.safe_load(DEFAULTS_YML.read_text())["models"]} + + assert models["openai-llm"]["model_name"] == "gpt-4.1-mini" + assert models["openai-llm"]["max_output_tokens"] == 32768 + assert models["fallback-llm"]["model_name"] == "gpt-5-nano" + assert models["fallback-llm"]["max_output_tokens"] == 128000 + + +def test_config_diagnostics_ask_for_a_bigger_model(monkeypatch): + # Imported here to keep the controller's import graph out of the other tests. + import backend.controllers.system_controller as system_controller + + monkeypatch.setattr( + system_controller, + "load_config", + lambda: {"timeline": {"pi": {"max_tokens": 32000}}}, + ) + registry = _registry(_model("openai-llm", 16384)) + + issues = system_controller._output_limit_issues(registry) + + assert len(issues) == 1 + assert issues[0]["severity"] == "error" + assert "needs a model with at least 32000 output tokens" in issues[0]["message"] + assert "accepts at most 16384" in issues[0]["message"] + assert issues[0]["resolution"].startswith("Settings > AI Model Settings") diff --git a/backend/tests/test_privacy_speaker_discovery.py b/backend/tests/test_privacy_speaker_discovery.py index 3646b064..9e0b29a9 100644 --- a/backend/tests/test_privacy_speaker_discovery.py +++ b/backend/tests/test_privacy_speaker_discovery.py @@ -322,3 +322,66 @@ async def embed(wav): assert completed == [True] assert await evidence.db.speaker_corpus_matches.count_documents({}) == 0 assert await evidence.db.unknown_speaker_clusters.count_documents({}) == 0 + + +@pytest.mark.asyncio +async def test_refused_clip_is_skipped_and_the_decision_still_confirms( + evidence, discovery, guided_setup, monkeypatch +): + from backend.services.speaker_enrollment import EnrollmentUnavailable + + await allow(evidence) + await run_worker("unknown") + row = await evidence.db.unknown_speaker_clusters.find_one({}) + keys = [member["identity_key"] for member in row["members"]] + assert len(keys) == 2 + client = guided_setup.client + client.get_speaker_by_name = AsyncMock(return_value={"id": "synthetic-gallery"}) + # The provider refuses the first clip (e.g. byte-identical audio) and + # accepts the second. + client.append_to_speaker = AsyncMock( + side_effect=[EnrollmentUnavailable(), {"status": "enrolled"}] + ) + monkeypatch.setattr( + guided.data_audit_controller, "apply_triage", AsyncMock(return_value={}) + ) + + class Field: + # Stands in for the Beanie field: `field == value` builds the query. + def __eq__(self, value): + return {"conversation_id": value} + + async def find_one(query): + doc = await evidence.db.conversations.find_one(query) + return NS(user_id=doc["user_id"], model_dump=lambda: doc) + + collection = evidence.db.conversations + monkeypatch.setattr( + guided, + "Conversation", + NS( + get_pymongo_collection=lambda: collection, + find_one=find_one, + conversation_id=Field(), + ), + ) + monkeypatch.setattr( + guided, "Annotation", lambda **kw: NS(insert=AsyncMock(return_value=None)) + ) + + result = await guided.decide_unknown_cluster( + discovery.user, + row["cluster_id"], + row["run_fingerprint"], + "confirm", + "Synthetic speaker", + keys, + [{"identity_key": key, "segment_index": 0} for key in keys], + ) + + assert result["status"] == "confirmed" + assert result["appended"] == 1 + assert result["skipped"] == 1 + assert client.append_to_speaker.await_count == 2 + stored = await evidence.db.unknown_speaker_clusters.find_one({"_id": row["_id"]}) + assert stored["status"] == "confirmed" diff --git a/backend/tests/test_privacy_speaker_references.py b/backend/tests/test_privacy_speaker_references.py index 7e25ffd9..97f40967 100644 --- a/backend/tests/test_privacy_speaker_references.py +++ b/backend/tests/test_privacy_speaker_references.py @@ -71,6 +71,7 @@ async def test_registered_speaker_job_retains_background_reference_fence( client = SimpleNamespace( enabled=True, service_url="http://synthetic.invalid", + health_check=AsyncMock(return_value=True), enrollment_catalog=AsyncMock(return_value=catalog), ) 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/tests/test_speaker_service_unavailable.py b/backend/tests/test_speaker_service_unavailable.py new file mode 100644 index 00000000..09903a37 --- /dev/null +++ b/backend/tests/test_speaker_service_unavailable.py @@ -0,0 +1,101 @@ +"""An unreachable speaker service must not run speaker recognition. + +Before this check, the job reached the enrollment-catalog call, which failed on +DNS and was reported as ``PrivacyHeld``: a misleading failure for what is only a +missing service. The automatic chain now skips; a manual reprocess fails clearly. +""" + +import asyncio +from datetime import datetime, timezone +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest + +from backend.models import job as job_model +from backend.workers import speaker_jobs as jobs + + +def _version(version_id="v1"): + return jobs.Conversation.TranscriptVersion( + version_id=version_id, + transcript="Synthetic spoken words", + segments=[ + jobs.Conversation.SpeakerSegment( + start=0, end=3, text="Synthetic spoken words", speaker="Speaker 0" + ) + ], + words=[ + jobs.Conversation.Word(word=word, start=i, end=i + 1) + for i, word in enumerate(["Synthetic", "spoken", "words"]) + ], + provider="synthetic", + created_at=datetime.now(timezone.utc), + metadata={}, + ) + + +@pytest.fixture +def unreachable(monkeypatch): + source = _version("source") + conversation = SimpleNamespace( + conversation_id="c1", + user_id="u1", + client_id="u1-phone", + audio_ranges=[], + audio_total_duration=10, + get_transcript_version=lambda vid: source if vid == "source" else None, + active_transcript=source, + transcript_integrity_error=None, + save=AsyncMock(), + ) + client = SimpleNamespace( + enabled=True, + service_url="http://speaker.example.ts.net:8085", + health_check=AsyncMock(return_value=False), + enrollment_catalog=AsyncMock(), + identify_provider_segments=AsyncMock(), + diarize_identify_match=AsyncMock(), + ) + events = Mock() + snapshot = SimpleNamespace(permits_record=lambda _row: True) + + monkeypatch.setattr(job_model, "_ensure_beanie_initialized", AsyncMock()) + monkeypatch.setattr(jobs, "SpeakerRecognitionClient", lambda: client) + monkeypatch.setattr( + jobs, + "Conversation", + SimpleNamespace( + conversation_id="conversation_id", + find_one=AsyncMock(return_value=conversation), + SpeakerSegment=jobs.Conversation.SpeakerSegment, + Word=jobs.Conversation.Word, + ), + ) + monkeypatch.setattr(jobs.privacy, "load_snapshot", AsyncMock(return_value=snapshot)) + monkeypatch.setattr( + jobs, "load_transcript_audio_ranges", AsyncMock(return_value=[(0.0, 10.0)]) + ) + monkeypatch.setattr(jobs, "record_event_sync", events) + return SimpleNamespace(client=client, events=events) + + +async def test_automatic_chain_skips_without_calling_the_service(unreachable): + result = await asyncio.to_thread(jobs.recognise_speakers_job, "c1", "source") + + assert result["success"] is True + assert result["skip_reason"] == "Speaker service unavailable" + unreachable.client.enrollment_catalog.assert_not_awaited() + unreachable.client.identify_provider_segments.assert_not_awaited() + unreachable.client.diarize_identify_match.assert_not_awaited() + (call,) = unreachable.events.call_args_list + assert call.kwargs["incident_key"] == "speaker-service-unavailable" + + +async def test_manual_reprocess_fails_clearly(unreachable): + with pytest.raises(jobs.SpeakerReprocessFailed, match="not reachable"): + await asyncio.to_thread( + jobs.recognise_speakers_job, "c1", "new-version", source_version_id="source" + ) + + unreachable.client.enrollment_catalog.assert_not_awaited() diff --git a/backend/tests/test_streaming_end_stream_closed.py b/backend/tests/test_streaming_end_stream_closed.py new file mode 100644 index 00000000..b8a57cb7 --- /dev/null +++ b/backend/tests/test_streaming_end_stream_closed.py @@ -0,0 +1,52 @@ +"""Ending a stream whose provider socket already closed. + +Deepgram closes an idle stream (NET-0001) after about 10 seconds without audio. +When the session then ends, the CloseStream send hits a dead socket. That must +end the stream cleanly, not raise and leave the stream registered. +""" + +import pytest +from websockets.exceptions import ConnectionClosedError +from websockets.frames import Close + +from backend.services.transcription import RegistryStreamingTranscriptionProvider + +IDLE_CLOSE = Close( + 1011, "Deepgram did not receive audio data within the timeout window." +) + + +class ClosedSocket: + def __init__(self): + self.closed_called = False + + async def send(self, _payload): + raise ConnectionClosedError(IDLE_CLOSE, IDLE_CLOSE, rcvd_then_sent=True) + + async def recv(self): + raise ConnectionClosedError(IDLE_CLOSE, IDLE_CLOSE, rcvd_then_sent=True) + + async def close(self): + self.closed_called = True + + +def _provider_with(ws, pending=b""): + provider = object.__new__(RegistryStreamingTranscriptionProvider) + provider.model = type( + "Model", (), {"operations": {"end": {"message": {"type": "CloseStream"}}}} + )() + provider._streams = {"s1": {"ws": ws, "pending_audio": bytearray(pending)}} + return provider + + +@pytest.mark.parametrize("pending", [b"", b"\x00" * 64]) +async def test_end_stream_on_provider_closed_socket_returns_empty_and_unregisters( + pending, +): + ws = ClosedSocket() + provider = _provider_with(ws, pending) + + result = await provider.end_stream("s1") + + assert result == {"text": "", "words": [], "segments": []} + assert "s1" not in provider._streams diff --git a/backend/tests/test_transcript_ingest_integrity.py b/backend/tests/test_transcript_ingest_integrity.py index 7286b1fa..d990ac15 100644 --- a/backend/tests/test_transcript_ingest_integrity.py +++ b/backend/tests/test_transcript_ingest_integrity.py @@ -586,6 +586,7 @@ async def test_registered_speaker_job_runs_batch_provider_identification( ) fake_client = SimpleNamespace( enabled=True, + health_check=AsyncMock(return_value=True), identify_provider_segments=identify_provider_segments, ) fake_conversation_model = SimpleNamespace( @@ -719,7 +720,9 @@ async def test_registered_speaker_job_skips_event_only_transcript(monkeypatch): active_transcript=version, save=AsyncMock(), ) - fake_client = SimpleNamespace(enabled=True) + fake_client = SimpleNamespace( + enabled=True, health_check=AsyncMock(return_value=True) + ) fake_conversation_model = SimpleNamespace( conversation_id=object(), find_one=AsyncMock(return_value=conversation), @@ -788,7 +791,11 @@ async def test_speaker_job_derives_edge_timing_normalization_before_processing( normalize = AsyncMock(return_value=normalized) monkeypatch.setattr(module, "Conversation", fake_conversation_model) monkeypatch.setattr( - module, "SpeakerRecognitionClient", lambda: SimpleNamespace(enabled=True) + module, + "SpeakerRecognitionClient", + lambda: SimpleNamespace( + enabled=True, health_check=AsyncMock(return_value=True) + ), ) monkeypatch.setattr( module, @@ -924,6 +931,7 @@ async def identify_word_spans(**kwargs): client = SimpleNamespace( enabled=True, + health_check=AsyncMock(return_value=True), diarize_identify_match=AsyncMock( return_value={"segments": [], "diarization_model": "community-1"} ), diff --git a/backend/tests/test_unknown_speaker_label.py b/backend/tests/test_unknown_speaker_label.py new file mode 100644 index 00000000..79bb459f --- /dev/null +++ b/backend/tests/test_unknown_speaker_label.py @@ -0,0 +1,25 @@ +import pytest + +from backend.constants import is_non_enrollable_speaker, is_unknown_speaker_label + + +@pytest.mark.parametrize( + "label", + [ + "Unknown", + "Unknown Speaker 2", + "unknown_speaker_3", + "Speaker 0", + "speaker 12", + "SPEAKER_00", + " Speaker 1 ", + ], +) +def test_placeholder_and_raw_diarization_labels_are_unknown(label): + assert is_unknown_speaker_label(label) + assert is_non_enrollable_speaker(label) + + +@pytest.mark.parametrize("label", ["Stu", "Speaker", "Speakerphone 2", "Guest Speaker 1"]) +def test_real_names_are_not_unknown(label): + assert not is_unknown_speaker_label(label) diff --git a/backend/webui/src/components/AutomationSettings.test.tsx b/backend/webui/src/components/AutomationSettings.test.tsx index c2a14239..96887b40 100644 --- a/backend/webui/src/components/AutomationSettings.test.tsx +++ b/backend/webui/src/components/AutomationSettings.test.tsx @@ -3,17 +3,19 @@ import '@testing-library/jest-dom/vitest' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import AutomationSettings from './AutomationSettings' +import { formatDateTime, setDisplayTimezone } from '../utils/datetime' const state = vi.hoisted(() => ({ next: '2026-09-14T04:30:00+00:00' as string | null, update: vi.fn() })) vi.mock('../hooks/useFinetuning', () => ({ useCronJobs: () => ({ data: [{ job_id: 'daily', description: '', enabled: true, schedule: '30 4 * * *', last_run: null, next_run: state.next }], isLoading: false, refetch: vi.fn() }), useToggleCronJob: () => ({ mutateAsync: vi.fn() }), useRunCronJob: () => ({ mutateAsync: vi.fn() }), useUpdateCronSchedule: () => ({ mutateAsync: state.update }), })) -beforeEach(() => { state.next = '2026-09-14T04:30:00+00:00'; state.update.mockReset().mockResolvedValue({}) }) -afterEach(cleanup) -it('shows the UTC next-run instant in IST while preserving the UTC expression when edited', async () => { +beforeEach(() => { setDisplayTimezone('Asia/Kolkata'); state.next = '2026-09-14T04:30:00+00:00'; state.update.mockReset().mockResolvedValue({}) }) +afterEach(() => { cleanup(); setDisplayTimezone(null) }) +it('shows the UTC next-run instant in the display timezone while preserving the UTC expression when edited', async () => { render() - expect(screen.getByText(/Next:/)).toHaveTextContent(/10:00 am IST/i) + expect(screen.getByText(/Next:/)).toHaveTextContent(formatDateTime('2026-09-14T04:30:00Z')) + expect(screen.getByText(/Next:/)).toHaveTextContent(/10:00/) fireEvent.click(screen.getByText('Schedule and last run')) expect(screen.getByText(/At 04:30 AM/)).toHaveTextContent('(UTC)') fireEvent.click(screen.getByRole('button', { name: 'Edit schedule' })) diff --git a/backend/webui/src/components/AutomationSettings.tsx b/backend/webui/src/components/AutomationSettings.tsx index fbd39fb6..27479af8 100644 --- a/backend/webui/src/components/AutomationSettings.tsx +++ b/backend/webui/src/components/AutomationSettings.tsx @@ -3,6 +3,7 @@ import { Clock, ToggleLeft, ToggleRight, Edit3, Check, X, Play, RefreshCw, Eye } import cronstrue from 'cronstrue' import { useCronJobs, useToggleCronJob, useUpdateCronSchedule, useRunCronJob } from '../hooks/useFinetuning' import { Alert, Button, Card, IconButton, StateBadge, StateTone } from './ui' +import { formatDateTime, useDisplayTimezone } from '../utils/datetime' // Human-friendly names + what kind of automation each job is. Trigger-now lives // on the Training page; this card owns only "should it run / when". @@ -34,10 +35,11 @@ function humanCron(expr: string): string { function formatTs(iso: string | null): string { if (!iso) return 'Never' - return `${new Date(iso).toLocaleString('en-IN', { timeZone: 'Asia/Kolkata', dateStyle: 'medium', timeStyle: 'short' })} IST` + return formatDateTime(iso) } export default function AutomationSettings({ isAdmin }: { isAdmin: boolean }) { + const timezone = useDisplayTimezone() const { data: jobs = [], isLoading, refetch } = useCronJobs() const toggleJob = useToggleCronJob() const updateSchedule = useUpdateCronSchedule() @@ -96,7 +98,7 @@ export default function AutomationSettings({ isAdmin }: { isAdmin: boolean }) { Automation & Schedules

- Next runs are shown in IST. Enabling or disabling a job takes effect immediately. + Next runs are shown in {timezone}. Enabling or disabling a job takes effect immediately.

{error && ( diff --git a/backend/webui/src/components/ChatRunViewer.tsx b/backend/webui/src/components/ChatRunViewer.tsx index db7c2c19..994a6383 100644 --- a/backend/webui/src/components/ChatRunViewer.tsx +++ b/backend/webui/src/components/ChatRunViewer.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react' import { useQuery } from '@tanstack/react-query' import { X } from 'lucide-react' import { chatApi } from '../services/api' +import { formatDateTime } from '../utils/datetime' export interface ChatRun { run_id: string @@ -26,9 +27,9 @@ interface RunStep { response_unavailable?: boolean } -const stamp = (value: string) => new Date(value).toLocaleString('en-IN', { - timeZone: 'Asia/Kolkata', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', -}) + ' IST' +const stamp = (value: string) => formatDateTime(value, { + day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', timeZoneName: 'short', +}) function Payload({ label, value }: { label: string; value: unknown }) { if (value === undefined) return null diff --git a/backend/webui/src/components/DateTime.tsx b/backend/webui/src/components/DateTime.tsx new file mode 100644 index 00000000..d03554e4 --- /dev/null +++ b/backend/webui/src/components/DateTime.tsx @@ -0,0 +1,27 @@ +import { formatDate, formatDateTime, formatTime, toDate, useDisplayTimezone, type DateInput, type FormatOptions } from '../utils/datetime' + +const FORMATTERS = { datetime: formatDateTime, date: formatDate, time: formatTime } + +interface DateTimeProps { + value: DateInput + /** Defaults to "datetime". */ + format?: keyof typeof FORMATTERS + options?: FormatOptions + className?: string +} + +/** A timestamp shown in the user's display timezone; hover shows the full date and time. */ +export default function DateTime({ value, format = 'datetime', options, className }: DateTimeProps) { + useDisplayTimezone() + const date = toDate(value) + if (Number.isNaN(date.getTime())) return null + return ( + + ) +} diff --git a/backend/webui/src/components/RecordingMemoryContext.tsx b/backend/webui/src/components/RecordingMemoryContext.tsx index 7742a615..bba679a1 100644 --- a/backend/webui/src/components/RecordingMemoryContext.tsx +++ b/backend/webui/src/components/RecordingMemoryContext.tsx @@ -1,4 +1,3 @@ -import { sourceDate } from "../utils/sourceTime"; import { useState } from "react"; import { Link, useSearchParams } from "react-router-dom"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; @@ -13,6 +12,7 @@ import { Button } from "./ui"; import { CandidateChanges } from "./timeline/ReviewDesk"; import ContextRefreshes from "./ContextRefreshes"; import { sourceLabel } from "./timeline/SessionMemoryBoard"; +import { formatDateTime, formatTime, useDisplayTimezone } from '../utils/datetime' interface Context { organization_requests?: { request_id?: string }[]; @@ -54,15 +54,16 @@ export default function RecordingMemoryContext({ const client = useQueryClient(); const [params] = useSearchParams(); const space = params.get("memory_space_id") || undefined; + const timezone = useDisplayTimezone(); const [clarification, setClarification] = useState(""); const [requestId, setRequestId] = useState(); const [inspect, setInspect] = useState(false); const query = useQuery({ - queryKey: ["recording-context", recordingId, space], + queryKey: ["recording-context", recordingId, space, timezone], queryFn: async () => ( await api.get(`/api/recordings/${recordingId}/context`, { - params: { timezone: "Asia/Kolkata", memory_space_id: space }, + params: { timezone, memory_space_id: space }, }) ).data, refetchInterval: 5000, @@ -80,7 +81,7 @@ export default function RecordingMemoryContext({ mutationFn: (day: string) => api.post(`/api/recordings/${recordingId}/organize-day`, { local_date: day, - timezone: "Asia/Kolkata", + timezone, }), onSuccess: (response) => { setRequestId(response.data.request_id); @@ -170,10 +171,8 @@ export default function RecordingMemoryContext({ {!data.event_date_known && (

Recording date unknown. Uploaded{" "} - {sourceDate(data.uploaded_at).toLocaleString("en-IN", { - timeZone: "Asia/Kolkata", - })}{" "} - IST. This session stays undated. + {formatDateTime(data.uploaded_at)}. This session stays + undated.

)} {data.event_date_known && !data.sessions.length && ( @@ -220,18 +219,11 @@ export default function RecordingMemoryContext({

{s.title}

- {sourceDate(s.started_at).toLocaleTimeString("en-IN", { - timeZone: "Asia/Kolkata", - hour: "numeric", + {formatTime(s.started_at, { + hour: "2-digit", minute: "2-digit", })} - – - {sourceDate(s.ended_at).toLocaleTimeString("en-IN", { - timeZone: "Asia/Kolkata", - hour: "numeric", - minute: "2-digit", - })}{" "} - IST + –{formatTime(s.ended_at)}

{s.summary} @@ -423,7 +415,7 @@ export default function RecordingMemoryContext({ +

- {cluster.members.map((member) => ( -
- - {member.local_label} -
+ {cluster.members.map((member) => { + const open = expanded.has(member.identity_key) + const title = member.conversation_title || 'Untitled' + const chosen = accepted.has(member.identity_key) + ? member.segments.filter((segment) => selectedClips.has(`${member.identity_key}:${segment.segment_index}`)).length + : 0 + return ( +
+
+ toggle(accepted, member.identity_key, setAccepted)} /> + +
+ {open &&
{member.segments.map((segment) => { const key = `${member.identity_key}:${segment.segment_index}` const playbackId = `unknown-discovery:${key}` @@ -127,9 +162,10 @@ export default function UnknownSpeakerDiscovery() { {segment.text || '(no transcript)'}
})} -
+
}
- ))} + ) + })}
setName(event.target.value)} placeholder="Existing or new speaker name" className="min-w-64 rounded border border-gray-300 bg-white px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-900" /> diff --git a/backend/webui/src/components/dataAudit/format.ts b/backend/webui/src/components/dataAudit/format.ts index ec5405fa..a6611477 100644 --- a/backend/webui/src/components/dataAudit/format.ts +++ b/backend/webui/src/components/dataAudit/format.ts @@ -1,4 +1,5 @@ import { sourceDate } from '../../utils/sourceTime' +import { PRECISE_DATE_TIME, formatDateTime } from '../../utils/datetime' export function formatDuration(seconds: number): string { if (!seconds || seconds <= 0) return '0s' @@ -20,7 +21,7 @@ export function formatClock(seconds: number): string { export function formatDate(iso: string | null): string { if (!iso) return '—' - return sourceDate(iso).toLocaleString('en-IN', { timeZone: 'Asia/Kolkata', timeZoneName: 'short' }) + return formatDateTime(sourceDate(iso), PRECISE_DATE_TIME) } // Processing-status chip for a Data Audit row. Returns null for the normal diff --git a/backend/webui/src/components/timeline/SessionMemoryBoard.tsx b/backend/webui/src/components/timeline/SessionMemoryBoard.tsx index 221c39ad..1ea0e7d4 100644 --- a/backend/webui/src/components/timeline/SessionMemoryBoard.tsx +++ b/backend/webui/src/components/timeline/SessionMemoryBoard.tsx @@ -6,6 +6,7 @@ import { ChevronDown, Image, Monitor, Mic, Volume2, Check, Loader2 } from 'lucid import { MemorySession, SessionSource, timelineApi } from '../../services/api' import { Button } from '../ui' import { CandidateChanges } from './ReviewDesk' +import { formatTime } from '../../utils/datetime' const busyStates = ['queued', 'generating', 'checking', 'applying', 'regenerating'] const quietStates = ['excluded', 'deferred', 'no_changes', 'applied', 'rejected'] @@ -143,7 +144,7 @@ function SessionRow({ session, day, timezone }: { session: MemorySession; day: s
{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 &&