Files
buzz/mobile/ios/Runner/DeviceTranscriptionPlugin.swift
klopez4212 d647c9fd98 Refine iOS composer and transcribe recordings into drafts (#9574)
Refine the iOS composer with 40-point glass controls, native attachment
menus, persistent emoji access, and selected-text formatting. The mic
now transcribes recordings on device into an editable, unsent draft;
Dictation has no five-minute recording cap or timer label, and its
waveform fills the space between the controls. Voice note remains
available in attachments with its five-minute cap. Unsupported devices
fail before recording, and audio is retained until the draft is durably
saved. Stopped dictation remains recoverable across editor teardown;
failed retention and cleanup can be retried. Recovered transcripts are
inserted only once across navigation or restart, preserving live exact
mention bindings.

Preserve selection handles over glass with animated avatars. Reduce the
conversation fade to 100 points above the keyboard and transition
continuously to 180 as the keyboard closes, without a first-frame jump
when opening; Home is unchanged.

Validation: 5,117 mobile tests and 27 crypto tests pass; analysis
passes. Prior native suite on iPhone 16/iOS 26.5: 119 pass, one
pre-existing expected failure, zero unexpected failures. Physical Air
preview approved; simulator selection/dragging and attachment flows
exercised. Fixed the native navigation test's timing race and a
community-cache cleanup test that checked a parent directory before its
asynchronous removal completed. Repository-wide `just ci` previously
stopped in unchanged `buzz-test-client` load-generator tests; new-head
hosted checks are pending.

Snapshots: production composer in an iPhone Air simulator fixture with
fictional conversation text; Photos snapshot retained from the
attachment preview.

| Composer | Attachments | Photos |
| --- | --- | --- |
| ![Keyboard-up
composer](https://github.com/user-attachments/assets/b7c8f0a4-25f8-4ca2-b8ae-11e18655e64a)
| ![Native attachment
menu](https://github.com/user-attachments/assets/5eaf5259-8e04-4da7-93f5-1b2eccab3c3c)
|
![Photos](https://github.com/user-attachments/assets/a6216b7d-5eaf-482c-b587-6052825b88fc)
|

---------

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Princess Donut <b238ea756dee4d98afa5883fc7f1de61eeabe65bf700e3a5a5a80db5e42e2c2b@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: Princess Donut <b238ea756dee4d98afa5883fc7f1de61eeabe65bf700e3a5a5a80db5e42e2c2b@buzz.block.builderlab.xyz>
2026-11-20 16:35:20 +00:00

137 lines
5.3 KiB
Swift

import AVFoundation
import Flutter
import Speech
/// File-based on-device recognition. Capture and waveform remain owned by Flutter.
@MainActor
final class DeviceTranscriptionPlugin {
private let channel: FlutterMethodChannel
private var operation: Task<Void, Never>?
private var owner: String?
private var cancelAnalysis: (() -> Void)?
/// Applies to new and existing durable drafts before Flutter opens their journal.
static func excludeDraftsFromBackup(in support: URL, directory name: String) throws {
var drafts = support.appendingPathComponent(name, isDirectory: true)
try FileManager.default.createDirectory(at: drafts, withIntermediateDirectories: true)
var values = URLResourceValues()
values.isExcludedFromBackup = true
try drafts.setResourceValues(values)
}
init(messenger: FlutterBinaryMessenger) {
channel = FlutterMethodChannel(name: "buzz/transcription", binaryMessenger: messenger)
channel.setMethodCallHandler { [weak self] call, reply in
if call.method == "isAvailable" {
guard #available(iOS 26.0, *) else { reply(false); return }
Task { reply(await Self.supportedLocale() != nil) }
return
}
guard let self, let args = call.arguments as? [String: Any],
let id = args["id"] as? String else {
reply(FlutterError(code: "arguments", message: "Invalid transcription request.", details: nil))
return
}
if call.method == "cancel" {
if owner == id {
let task = operation
let cancel = cancelAnalysis
owner = nil
operation = nil
cancelAnalysis = nil
task?.cancel()
cancel?()
}
reply(nil)
return
}
if call.method == "storageDirectory" {
guard let name = args["directory"] as? String,
name == "bestie-transcripts" || name == "composer-transcripts" else {
reply(FlutterError(code: "arguments", message: "Invalid transcription request.", details: nil))
return
}
do {
let support = try FileManager.default.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
try Self.excludeDraftsFromBackup(in: support, directory: name)
reply(support.path)
} catch {
reply(FlutterError(code: "storage_failed", message: error.localizedDescription, details: nil))
}
return
}
guard call.method == "prepare" || call.method == "transcribe" else {
reply(FlutterMethodNotImplemented); return
}
guard #available(iOS 26.0, *) else {
reply(FlutterError(code: "unavailable", message: "On-device transcription requires iOS 26.", details: nil)); return
}
guard owner == nil || owner == id else {
reply(FlutterError(code: "busy", message: "Another transcription is active.", details: nil)); return
}
owner = id
operation = Task { [weak self] in
guard let self else { return }
defer {
if owner == id { owner = nil; cancelAnalysis = nil; operation = nil }
}
do {
guard let locale = await Self.supportedLocale() else {
throw TranscriptionFailure.unavailable
}
try Task.checkCancellation()
let transcriber = SpeechTranscriber(locale: locale, preset: .transcription)
if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {
try await request.downloadAndInstall()
}
try Task.checkCancellation()
if call.method == "prepare" {
reply(nil)
return
}
guard let path = args["path"] as? String else { throw TranscriptionFailure.invalidFile }
let file = try AVAudioFile(forReading: URL(fileURLWithPath: path))
let analyzer = SpeechAnalyzer(modules: [transcriber])
cancelAnalysis = { Task { await analyzer.cancelAndFinishNow() } }
let results = Task {
var text = ""
for try await result in transcriber.results {
if result.isFinal { text += String(result.text.characters) }
}
return text.trimmingCharacters(in: .whitespacesAndNewlines)
}
do {
try await analyzer.start(inputAudioFile: file, finishAfterFile: true)
let text = try await results.value
try Task.checkCancellation()
reply(text)
} catch {
results.cancel()
await analyzer.cancelAndFinishNow()
throw error
}
} catch {
reply(FlutterError(code: "transcription_failed", message: error.localizedDescription, details: nil))
}
}
}
}
@available(iOS 26.0, *)
private static func supportedLocale() async -> Locale? {
guard SpeechTranscriber.isAvailable else { return nil }
return await SpeechTranscriber.supportedLocale(equivalentTo: Locale.current)
}
}
private enum TranscriptionFailure: LocalizedError {
case unavailable, invalidFile
var errorDescription: String? {
switch self {
case .unavailable: return "On-device transcription is unavailable for this device or language."
case .invalidFile: return "The saved recording could not be opened."
}
}
}