feat #14740: main window with call list and transcript

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-06 09:38:55 +01:00
co-authored by Claude Opus 5.5
parent cfde9690b2
commit d1658f5d9e
15 changed files with 1391 additions and 15 deletions
+82
View File
@@ -0,0 +1,82 @@
//! Customer accounts a call can be assigned to (the "Kunde" dropdown).
//!
//! A static mock for now: the names are clearly fictional placeholders
//! until the account system is connected.
use serde::Serialize;
/// A customer account. `id` is what a call stores as its `account_id`.
#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
pub struct Account {
pub id: &'static str,
pub name: &'static str,
}
const MOCK_ACCOUNTS: [Account; 5] = [
Account {
id: "mock-1",
name: "Weingut Beispiel GmbH",
},
Account {
id: "mock-2",
name: "Weinhandel Muster KG",
},
Account {
id: "mock-3",
name: "Vinothek Probe",
},
Account {
id: "mock-4",
name: "Kellerei Test eG",
},
Account {
id: "mock-5",
name: "Restaurant Platzhalter",
},
];
/// All accounts, in display order.
pub fn list() -> Vec<Account> {
MOCK_ACCOUNTS.to_vec()
}
/// Whether `id` names one of the accounts.
pub fn exists(id: &str) -> bool {
MOCK_ACCOUNTS.iter().any(|account| account.id == id)
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
#[test]
fn mock_accounts_are_stable_and_unique() {
let accounts = list();
let names: Vec<_> = accounts.iter().map(|a| a.name).collect();
assert_eq!(
names,
[
"Weingut Beispiel GmbH",
"Weinhandel Muster KG",
"Vinothek Probe",
"Kellerei Test eG",
"Restaurant Platzhalter",
]
);
let ids: HashSet<_> = accounts.iter().map(|a| a.id).collect();
assert_eq!(ids.len(), 5);
// Stored with the calls, so they must never change.
assert_eq!(accounts[0].id, "mock-1");
assert_eq!(accounts[4].id, "mock-5");
assert_eq!(list(), accounts);
}
#[test]
fn only_listed_accounts_exist() {
assert!(exists("mock-3"));
assert!(!exists("mock-6"));
assert!(!exists(""));
}
}
+226
View File
@@ -0,0 +1,226 @@
//! What the main window shows about calls: the rows of the call list and
//! the detail of the selected call, shaped from the stored data.
use std::collections::BTreeMap;
use chrono::{DateTime, Local};
use serde::Serialize;
use crate::merge;
use crate::model::{Call, CallId, CallStatus, Segment};
/// A row of the call list.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct CallListItem {
pub id: CallId,
pub app: String,
pub started_at: DateTime<Local>,
/// Whole seconds from start to end; 0 while recording.
pub duration_secs: i64,
pub status: CallStatus,
pub interrupted: bool,
}
impl CallListItem {
pub fn of(call: &Call) -> Self {
Self {
id: call.id,
app: call.app.clone(),
started_at: call.started_at,
duration_secs: duration_secs(call),
status: call.status,
interrupted: call.interrupted,
}
}
}
/// Whole seconds from `started_at` to `ended_at`; 0 while the call has not
/// ended (and never negative).
pub fn duration_secs(call: &Call) -> i64 {
call.ended_at
.map_or(0, |end| (end - call.started_at).num_seconds().max(0))
}
/// The selected call's header data: its list row plus the error of a
/// failed run and the assigned account.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct CallHeader {
#[serde(flatten)]
pub item: CallListItem,
pub error: Option<String>,
pub account_id: Option<String>,
}
/// A transcript line with the speaker's display label.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct SegmentView {
/// [`crate::model::Speaker::key`], stable across renames.
pub speaker_key: String,
pub label: String,
pub start: f64,
pub end: f64,
pub text: String,
}
/// Everything the detail pane shows about one call.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct CallDetail {
pub call: CallHeader,
pub segments: Vec<SegmentView>,
/// Renamed speakers by key; speakers not in here keep their default
/// label.
pub speaker_names: BTreeMap<String, String>,
}
impl CallDetail {
pub fn of(call: &Call, segments: &[Segment], speaker_names: BTreeMap<String, String>) -> Self {
let segments = segments
.iter()
.map(|segment| SegmentView {
speaker_key: segment.speaker.key(),
label: merge::label(&segment.speaker, &speaker_names),
start: segment.start,
end: segment.end,
text: segment.text.clone(),
})
.collect();
Self {
call: CallHeader {
item: CallListItem::of(call),
error: call.error.clone(),
account_id: call.account_id.clone(),
},
segments,
speaker_names,
}
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use chrono::TimeZone;
use serde_json::json;
use super::*;
use crate::model::Speaker;
fn at(h: u32, m: u32, s: u32) -> DateTime<Local> {
Local.with_ymd_and_hms(2026, 11, 5, h, m, s).unwrap()
}
fn call(ended_at: Option<DateTime<Local>>) -> Call {
Call {
id: 7,
app: "Microsoft Teams".into(),
started_at: at(10, 14, 0),
ended_at,
status: CallStatus::Done,
interrupted: false,
error: None,
mic_path: PathBuf::from("7-mic.wav"),
out_path: PathBuf::from("7-out.wav"),
transcribed_at: None,
audio_deleted: false,
account_id: None,
}
}
fn segment(speaker: Speaker, start: f64, text: &str) -> Segment {
Segment {
speaker,
start,
end: start + 2.0,
text: text.into(),
}
}
#[test]
fn duration_runs_from_start_to_end() {
assert_eq!(duration_secs(&call(Some(at(10, 46, 30)))), 32 * 60 + 30);
}
#[test]
fn duration_is_zero_while_recording_and_never_negative() {
assert_eq!(duration_secs(&call(None)), 0);
assert_eq!(duration_secs(&call(Some(at(10, 13, 0)))), 0);
}
#[test]
fn list_item_carries_the_row_fields() {
let mut c = call(Some(at(10, 15, 0)));
c.status = CallStatus::AwaitingDecision;
c.interrupted = true;
assert_eq!(
CallListItem::of(&c),
CallListItem {
id: 7,
app: "Microsoft Teams".into(),
started_at: at(10, 14, 0),
duration_secs: 60,
status: CallStatus::AwaitingDecision,
interrupted: true,
}
);
}
#[test]
fn detail_labels_segments_with_renames_and_defaults() {
let segments = [
segment(Speaker::Me, 0.0, "Guten Tag."),
segment(Speaker::Remote(1), 2.5, "Hallo."),
segment(Speaker::Remote(2), 5.0, "Moin."),
];
let mut names = BTreeMap::new();
names.insert("remote:1".to_string(), "Frau Beispiel".to_string());
names.insert("remote:2".to_string(), " ".to_string());
let detail = CallDetail::of(&call(Some(at(10, 15, 0))), &segments, names.clone());
let lines: Vec<_> = detail
.segments
.iter()
.map(|s| (s.speaker_key.as_str(), s.label.as_str(), s.text.as_str()))
.collect();
assert_eq!(
lines,
[
("me", "Ich", "Guten Tag."),
("remote:1", "Frau Beispiel", "Hallo."),
("remote:2", "Sprecher 2", "Moin."),
]
);
assert_eq!(detail.segments[1].start, 2.5);
assert_eq!(detail.segments[1].end, 4.5);
assert_eq!(detail.speaker_names, names);
}
#[test]
fn detail_serializes_the_call_header_flat() {
let mut c = call(Some(at(10, 15, 0)));
c.status = CallStatus::Failed;
c.error = Some("Netzwerkfehler".into());
c.account_id = Some("mock-2".into());
let value = serde_json::to_value(CallDetail::of(&c, &[], BTreeMap::new())).unwrap();
assert_eq!(
value,
json!({
"call": {
"id": 7,
"app": "Microsoft Teams",
"started_at": serde_json::to_value(at(10, 14, 0)).unwrap(),
"duration_secs": 60,
"status": "failed",
"interrupted": false,
"error": "Netzwerkfehler",
"account_id": "mock-2",
},
"segments": [],
"speaker_names": {},
})
);
}
}
+2
View File
@@ -4,7 +4,9 @@
//! transcription and summarization logic, kept independent of the Tauri //! transcription and summarization logic, kept independent of the Tauri
//! application shell so it can be unit-tested without a GUI or network. //! application shell so it can be unit-tested without a GUI or network.
pub mod accounts;
pub mod audio; pub mod audio;
pub mod call_view;
pub mod capture; pub mod capture;
pub mod detect; pub mod detect;
pub mod http; pub mod http;
+29
View File
@@ -286,6 +286,17 @@ impl Store {
Ok(()) Ok(())
} }
/// Drops the rename of `speaker_key`, so it shows its default label
/// again. Not an error if it was never renamed.
pub fn remove_speaker_name(&self, id: CallId, speaker_key: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"DELETE FROM speaker_names WHERE call_id = ?1 AND speaker_key = ?2",
params![id, speaker_key],
)?;
Ok(())
}
pub fn speaker_names(&self, id: CallId) -> Result<BTreeMap<String, String>> { pub fn speaker_names(&self, id: CallId) -> Result<BTreeMap<String, String>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
let mut stmt = let mut stmt =
@@ -661,6 +672,24 @@ mod tests {
assert_eq!(names.get("remote:1").unwrap(), "Frau Mueller"); assert_eq!(names.get("remote:1").unwrap(), "Frau Mueller");
} }
#[test]
fn a_removed_speaker_name_is_gone() {
let store = Store::open_in_memory().unwrap();
let id = store
.create_call("teams.exe", Local::now(), Path::new(""), Path::new(""))
.unwrap();
store
.set_speaker_name(id, "remote:1", "Frau Probe")
.unwrap();
store.set_speaker_name(id, "remote:2", "Herr Test").unwrap();
store.remove_speaker_name(id, "remote:1").unwrap();
store.remove_speaker_name(id, "remote:3").unwrap(); // never renamed
let names = store.speaker_names(id).unwrap();
assert_eq!(names.keys().collect::<Vec<_>>(), ["remote:2"]);
}
#[test] #[test]
fn list_newest_first() { fn list_newest_first() {
let store = Store::open_in_memory().unwrap(); let store = Store::open_in_memory().unwrap();
+43
View File
@@ -8,6 +8,8 @@
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use recorder_core::accounts::{self, Account};
use recorder_core::call_view::{CallDetail, CallListItem};
use recorder_core::capture::Devices; use recorder_core::capture::Devices;
use recorder_core::model::CallId; use recorder_core::model::CallId;
use recorder_core::secrets::Service; use recorder_core::secrets::Service;
@@ -118,6 +120,47 @@ pub fn get_call_brief(state: State<'_, AppState>, id: CallId) -> CmdResult<CallB
state.call_brief(id) state.call_brief(id)
} }
/// The main window's call list, newest first.
#[tauri::command]
pub fn list_calls(state: State<'_, AppState>) -> CmdResult<Vec<CallListItem>> {
state.call_list()
}
/// The selected call with its transcript.
#[tauri::command]
pub fn get_call(state: State<'_, AppState>, id: CallId) -> CmdResult<CallDetail> {
state.call_detail(id)
}
/// Renames a speaker of a call (an empty name restores the default label).
#[tauri::command]
pub fn rename_speaker(
app: AppHandle,
state: State<'_, AppState>,
id: CallId,
speaker_key: String,
name: String,
) -> CmdResult<()> {
state.rename_speaker(id, &speaker_key, &name)?;
processing::emit_updated(&app, id);
Ok(())
}
#[tauri::command]
pub fn list_accounts() -> Vec<Account> {
accounts::list()
}
/// Assigns a call to a customer account, or to none.
#[tauri::command]
pub fn set_account(
state: State<'_, AppState>,
id: CallId,
account_id: Option<String>,
) -> CmdResult<()> {
state.set_account(id, account_id.as_deref())
}
/// Deletes a finished call's audio and row. Closes the prompt if no call /// Deletes a finished call's audio and row. Closes the prompt if no call
/// waits for it any more; otherwise the prompt reloads and shows the next. /// waits for it any more; otherwise the prompt reloads and shows the next.
/// While its DeepScript jobs are still on record, nothing is deleted and a /// While its DeepScript jobs are still on record, nothing is deleted and a
+5
View File
@@ -104,6 +104,11 @@ pub fn run() {
commands::discard_call, commands::discard_call,
commands::transcribe_call, commands::transcribe_call,
commands::retry_call, commands::retry_call,
commands::list_calls,
commands::get_call,
commands::rename_speaker,
commands::list_accounts,
commands::set_account,
]) ])
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while building tauri application"); .expect("error while building tauri application");
+2 -1
View File
@@ -165,7 +165,8 @@ fn deepscript_key(state: &AppState) -> Option<String> {
.filter(|key| !key.trim().is_empty()) .filter(|key| !key.trim().is_empty())
} }
fn emit_updated(app: &AppHandle, id: CallId) { /// Tells the UI that call `id` changed (`call-updated`).
pub fn emit_updated(app: &AppHandle, id: CallId) {
if let Err(e) = app.emit("call-updated", CallUpdated { id }) { if let Err(e) = app.emit("call-updated", CallUpdated { id }) {
log::error!("could not emit call-updated: {e}"); log::error!("could not emit call-updated: {e}");
} }
+162 -8
View File
@@ -16,10 +16,12 @@ use std::thread;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use chrono::{DateTime, Local}; use chrono::{DateTime, Local};
use recorder_core::accounts;
use recorder_core::call_view::{self, CallDetail, CallListItem};
use recorder_core::capture::{CaptureSource, OutputTarget}; use recorder_core::capture::{CaptureSource, OutputTarget};
use recorder_core::detect::{CallDetector, DetectorEvent, MicSession}; use recorder_core::detect::{CallDetector, DetectorEvent, MicSession};
use recorder_core::http::{HttpTransport, ReqwestTransport}; use recorder_core::http::{HttpTransport, ReqwestTransport};
use recorder_core::model::{Call, CallId, CallStatus}; use recorder_core::model::{Call, CallId, CallStatus, Speaker};
use recorder_core::recorder::Recorder; use recorder_core::recorder::Recorder;
use recorder_core::secrets::SecretStore; use recorder_core::secrets::SecretStore;
use recorder_core::settings::Settings; use recorder_core::settings::Settings;
@@ -105,9 +107,7 @@ impl CallBrief {
app: call.app.clone(), app: call.app.clone(),
started_at: call.started_at, started_at: call.started_at,
ended_at: call.ended_at, ended_at: call.ended_at,
duration_secs: call duration_secs: call_view::duration_secs(call),
.ended_at
.map_or(0, |end| (end - call.started_at).num_seconds().max(0)),
} }
} }
} }
@@ -416,12 +416,55 @@ impl AppState {
} }
pub fn call_brief(&self, id: CallId) -> Result<CallBrief, String> { pub fn call_brief(&self, id: CallId) -> Result<CallBrief, String> {
let call = self Ok(CallBrief::of(&self.find_call(id)?))
.store }
/// All calls for the main window's list, newest first.
pub fn call_list(&self) -> Result<Vec<CallListItem>, String> {
let calls = self.store.list_calls().map_err(|e| e.to_string())?;
Ok(calls.iter().map(CallListItem::of).collect())
}
/// The selected call with its transcript and speaker names.
pub fn call_detail(&self, id: CallId) -> Result<CallDetail, String> {
let call = self.find_call(id)?;
let segments = self.store.segments(id).map_err(|e| e.to_string())?;
let names = self.store.speaker_names(id).map_err(|e| e.to_string())?;
Ok(CallDetail::of(&call, &segments, names))
}
/// Renames a speaker of call `id`; a blank `name` restores the default
/// label ("Ich", "Sprecher N").
pub fn rename_speaker(&self, id: CallId, speaker_key: &str, name: &str) -> Result<(), String> {
if Speaker::from_key(speaker_key).is_none() {
return Err(format!("Unbekannter Sprecher: {speaker_key}"));
}
self.find_call(id)?;
let name = name.trim();
let result = if name.is_empty() {
self.store.remove_speaker_name(id, speaker_key)
} else {
self.store.set_speaker_name(id, speaker_key, name)
};
result.map_err(|e| format!("Name konnte nicht gespeichert werden: {e}"))
}
/// Assigns call `id` to one of the [`accounts`], or to none.
pub fn set_account(&self, id: CallId, account_id: Option<&str>) -> Result<(), String> {
if account_id.is_some_and(|account| !accounts::exists(account)) {
return Err("Unbekannter Kunde".to_string());
}
self.find_call(id)?;
self.store
.set_account(id, account_id)
.map_err(|e| format!("Kunde konnte nicht gespeichert werden: {e}"))
}
fn find_call(&self, id: CallId) -> Result<Call, String> {
self.store
.get_call(id) .get_call(id)
.map_err(|e| e.to_string())? .map_err(|e| e.to_string())?
.ok_or_else(|| "Gespräch nicht gefunden".to_string())?; .ok_or_else(|| "Gespräch nicht gefunden".to_string())
Ok(CallBrief::of(&call))
} }
/// Deletes a finished call: both audio files and the row, and takes it /// Deletes a finished call: both audio files and the row, and takes it
@@ -595,6 +638,7 @@ fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use chrono::TimeZone; use chrono::TimeZone;
use recorder_core::model::{Segment, Speaker};
use recorder_core::secrets::MemorySecrets; use recorder_core::secrets::MemorySecrets;
use super::*; use super::*;
@@ -895,6 +939,116 @@ mod tests {
assert!(f.state.claim_processing(recording + 1, true).is_err()); assert!(f.state.claim_processing(recording + 1, true).is_err());
} }
#[test]
fn call_list_is_newest_first_with_durations() {
let f = fixture();
let (older, _, _) = finished_call(&f, "a");
let newer = f
.state
.store
.create_call("Manuell", at(11, 0, 0), Path::new(""), Path::new(""))
.unwrap();
let list = f.state.call_list().unwrap();
let rows: Vec<_> = list
.iter()
.map(|item| (item.id, item.status, item.duration_secs))
.collect();
assert_eq!(
rows,
[
(newer, CallStatus::Recording, 0),
(older, CallStatus::AwaitingDecision, 32 * 60 + 30),
]
);
}
#[test]
fn call_detail_shows_the_transcript_with_renamed_speakers() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state
.store
.save_segments(
id,
&[
Segment {
speaker: Speaker::Me,
start: 0.0,
end: 1.5,
text: "Guten Tag.".into(),
},
Segment {
speaker: Speaker::Remote(1),
start: 2.0,
end: 3.0,
text: "Hallo.".into(),
},
],
)
.unwrap();
f.state
.rename_speaker(id, "remote:1", "Frau Probe")
.unwrap();
let detail = f.state.call_detail(id).unwrap();
assert_eq!(detail.call.item.id, id);
let labels: Vec<_> = detail.segments.iter().map(|s| s.label.as_str()).collect();
assert_eq!(labels, ["Ich", "Frau Probe"]);
assert!(f.state.call_detail(id + 1).is_err());
}
#[test]
fn renaming_a_speaker_trims_and_an_empty_name_restores_the_default() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
let names = |f: &Fixture| f.state.store.speaker_names(id).unwrap();
f.state
.rename_speaker(id, "remote:2", " Herr Test ")
.unwrap();
assert_eq!(
names(&f).get("remote:2").map(String::as_str),
Some("Herr Test")
);
f.state.rename_speaker(id, "remote:2", " ").unwrap();
assert!(names(&f).is_empty());
}
#[test]
fn renaming_needs_a_known_speaker_and_call() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
assert!(f.state.rename_speaker(id, "remote:x", "Name").is_err());
assert!(f.state.rename_speaker(id + 1, "me", "Name").is_err());
assert!(f.state.store.speaker_names(id).unwrap().is_empty());
}
#[test]
fn the_account_is_set_and_cleared() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
let account = |f: &Fixture| f.state.store.get_call(id).unwrap().unwrap().account_id;
f.state.set_account(id, Some("mock-2")).unwrap();
assert_eq!(account(&f).as_deref(), Some("mock-2"));
f.state.set_account(id, None).unwrap();
assert_eq!(account(&f), None);
}
#[test]
fn only_known_accounts_and_calls_are_assigned() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
assert!(f.state.set_account(id, Some("mock-99")).is_err());
assert!(f.state.set_account(id + 1, Some("mock-1")).is_err());
assert_eq!(
f.state.store.get_call(id).unwrap().unwrap().account_id,
None
);
}
#[test] #[test]
fn invalid_detection_delays_are_not_saved() { fn invalid_detection_delays_are_not_saved() {
let f = fixture(); let f = fixture();
+2 -6
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte' import { onMount } from 'svelte'
import Main from './routes/Main.svelte'
import Prompt from './routes/Prompt.svelte' import Prompt from './routes/Prompt.svelte'
import Recorder from './routes/Recorder.svelte' import Recorder from './routes/Recorder.svelte'
import Settings from './routes/Settings.svelte' import Settings from './routes/Settings.svelte'
@@ -24,10 +25,5 @@
{:else if route === '/prompt'} {:else if route === '/prompt'}
<Prompt /> <Prompt />
{:else} {:else}
<main class="page"> <Main />
<header class="page-header">
<h1>Gesprächsrekorder</h1>
<a class="btn" href="#/settings" title="Einstellungen">⚙ Einstellungen</a>
</header>
</main>
{/if} {/if}
+92
View File
@@ -0,0 +1,92 @@
<script lang="ts">
import type { CallId, CallListItem } from './api'
import { formatListTime, formatMinutes } from './format'
import StatusPill from './StatusPill.svelte'
let {
calls,
selectedId,
onselect,
}: { calls: CallListItem[]; selectedId: CallId | null; onselect: (id: CallId) => void } =
$props()
</script>
{#if calls.length === 0}
<p class="empty muted">Noch keine Gespräche aufgezeichnet.</p>
{:else}
<ul class="calls">
{#each calls as call (call.id)}
<li>
<button
class="row"
class:selected={call.id === selectedId}
aria-current={call.id === selectedId}
onclick={() => onselect(call.id)}
>
<span class="title">
{call.app}{#if call.status !== 'recording'}&nbsp;· {formatMinutes(call.duration_secs)}{/if}
</span>
<span class="meta">
<span class="muted">{formatListTime(call.started_at)}</span>
<StatusPill status={call.status} interrupted={call.interrupted} />
</span>
</button>
</li>
{/each}
</ul>
{/if}
<style>
.empty {
padding: 16px;
}
.calls {
list-style: none;
margin: 0;
padding: 6px;
}
.row {
display: flex;
flex-direction: column;
gap: 3px;
width: 100%;
padding: 9px 10px;
border: none;
border-radius: 8px;
background: none;
font: inherit;
color: inherit;
text-align: left;
cursor: pointer;
}
.row:hover {
background: var(--bg);
}
.row.selected {
background: var(--primary-soft);
box-shadow: inset 3px 0 0 var(--primary);
}
.title {
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.meta {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 4px 8px;
}
.meta .muted {
white-space: nowrap;
}
</style>
+51
View File
@@ -0,0 +1,51 @@
<script lang="ts">
import type { CallStatus } from './api'
let { status, interrupted = false }: { status: CallStatus; interrupted?: boolean } = $props()
const pills: Record<CallStatus, { text: string; kind: string }> = {
done: { text: 'fertig', kind: 'done' },
processing: { text: 'wird verarbeitet…', kind: 'processing' },
awaiting_decision: { text: 'nicht transkribiert', kind: 'awaiting' },
failed: { text: 'fehlgeschlagen', kind: 'failed' },
recording: { text: 'Aufnahme läuft', kind: 'recording' },
}
let pill = $derived(pills[status])
</script>
<span class="pill status {pill.kind}">
{pill.text}{#if interrupted && status === 'awaiting_decision'}, unterbrochen{/if}
</span>
<style>
.status {
white-space: nowrap;
}
.done {
background: var(--ok-soft);
color: var(--ok);
}
.processing {
background: #fff4d6;
color: #8a6100;
}
.awaiting {
background: #eee;
color: #666;
}
.failed {
background: var(--rec-soft);
color: var(--rec);
}
.recording {
background: var(--surface);
color: var(--rec);
box-shadow: inset 0 0 0 1px var(--rec);
}
</style>
+196
View File
@@ -0,0 +1,196 @@
<script lang="ts">
import { errorText, type SegmentView } from './api'
import { formatOffset } from './format'
let {
segments,
onrename,
}: {
segments: SegmentView[]
/** Saves a speaker's name; an empty name restores the default label. */
onrename: (speakerKey: string, name: string) => Promise<void>
} = $props()
// "Ich" is always the primary blue; remote speakers cycle through the rest.
const ME_COLOR = '#3b5bdb'
const REMOTE_COLORS = ['#2b8a3e', '#c2255c', '#e8590c', '#7048e8', '#0c8599', '#5c940d']
function speakerColor(key: string): string {
if (key === 'me') return ME_COLOR
const n = Number(key.replace(/^remote:/, ''))
const index = Number.isInteger(n) && n > 0 ? (n - 1) % REMOTE_COLORS.length : 0
return REMOTE_COLORS[index]
}
/** "me" first, then remote speakers by number. */
function speakerOrder(key: string): number {
return key === 'me' ? 0 : Number(key.replace(/^remote:/, '')) || Number.MAX_SAFE_INTEGER
}
/** One chip per speaker present, with its current label. */
let speakers = $derived.by(() => {
const labels = new Map<string, string>()
for (const s of segments) if (!labels.has(s.speaker_key)) labels.set(s.speaker_key, s.label)
return [...labels]
.map(([key, label]) => ({ key, label }))
.sort((a, b) => speakerOrder(a.key) - speakerOrder(b.key))
})
let editing = $state<string | null>(null)
let draft = $state('')
let saving = $state(false)
let error = $state('')
function startEdit(key: string, label: string) {
editing = key
draft = label
error = ''
}
async function onkeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
editing = null
} else if (event.key === 'Enter' && editing && !saving) {
saving = true
error = ''
try {
await onrename(editing, draft.trim())
editing = null
} catch (err) {
error = errorText(err)
} finally {
saving = false
}
}
}
function focus(node: HTMLInputElement) {
node.focus()
node.select()
}
</script>
{#if segments.length === 0}
<p class="muted">Keine Sprache erkannt.</p>
{:else}
<div class="chips">
{#each speakers as { key, label } (key)}
<span class="chip" style:--speaker={speakerColor(key)}>
{#if editing === key}
<input
class="rename"
aria-label="Name für {label}"
placeholder="leer = Standardname"
disabled={saving}
bind:value={draft}
{onkeydown}
use:focus
/>
{:else}
<span class="dot"></span>
<span>{label}</span>
<button class="edit" title="Umbenennen" onclick={() => startEdit(key, label)}>✎</button>
{/if}
</span>
{/each}
</div>
{#if editing}
<div class="muted hint">Enter speichert, Esc bricht ab.</div>
{/if}
{#if error}
<div class="error">{error}</div>
{/if}
<div class="lines">
{#each segments as segment, i (i)}
<div class="line">
<span class="time">{formatOffset(segment.start)}</span>
<span class="speaker" style:color={speakerColor(segment.speaker_key)}>{segment.label}</span>
<span class="text">{segment.text}</span>
</div>
{/each}
</div>
{/if}
<style>
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 2px 4px 2px 10px;
border-radius: 999px;
background: var(--bg);
border: 1px solid var(--border);
font-size: 12px;
font-weight: 600;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--speaker);
}
.edit {
border: none;
background: none;
color: var(--muted);
cursor: pointer;
font-size: 12px;
padding: 0 4px;
}
.edit:hover {
color: var(--primary);
}
.rename {
width: 160px;
padding: 1px 6px;
font-size: 12px;
margin-right: 2px;
}
.hint,
.error {
margin-top: 6px;
}
.lines {
display: grid;
grid-template-columns: auto auto 1fr;
gap: 8px 12px;
margin-top: 14px;
}
.line {
display: contents;
}
.time {
color: var(--muted);
font-size: 12px;
font-variant-numeric: tabular-nums;
padding-top: 1px;
}
.speaker {
font-weight: 600;
max-width: 160px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.text {
min-width: 0;
overflow-wrap: anywhere;
}
</style>
+42
View File
@@ -54,6 +54,40 @@ export interface PendingPrompt extends CallBrief {
more_waiting: number more_waiting: number
} }
export type CallStatus = 'recording' | 'awaiting_decision' | 'processing' | 'done' | 'failed'
/** A row of the main window's call list. Times are RFC 3339. */
export interface CallListItem {
id: CallId
app: string
started_at: string
/** 0 while recording. */
duration_secs: number
status: CallStatus
interrupted: boolean
}
/** A transcript line; `speaker_key` is "me" or "remote:<n>". */
export interface SegmentView {
speaker_key: string
label: string
start: number
end: number
text: string
}
export interface CallDetail {
call: CallListItem & { error: string | null; account_id: string | null }
segments: SegmentView[]
/** Renamed speakers by key. */
speaker_names: Record<string, string>
}
export interface Account {
id: string
name: string
}
export interface Levels { export interface Levels {
mic: number mic: number
out: number out: number
@@ -76,6 +110,14 @@ export const getCallBrief = (id: CallId) => invoke<CallBrief>('get_call_brief',
export const transcribeCall = (id: CallId) => invoke<void>('transcribe_call', { id }) export const transcribeCall = (id: CallId) => invoke<void>('transcribe_call', { id })
export const retryCall = (id: CallId) => invoke<void>('retry_call', { id }) export const retryCall = (id: CallId) => invoke<void>('retry_call', { id })
export const discardCall = (id: CallId) => invoke<void>('discard_call', { id }) export const discardCall = (id: CallId) => invoke<void>('discard_call', { id })
export const listCalls = () => invoke<CallListItem[]>('list_calls')
export const getCall = (id: CallId) => invoke<CallDetail>('get_call', { id })
/** An empty name restores the default label. */
export const renameSpeaker = (id: CallId, speakerKey: string, name: string) =>
invoke<void>('rename_speaker', { id, speakerKey, name })
export const listAccounts = () => invoke<Account[]>('list_accounts')
export const setAccount = (id: CallId, accountId: string | null) =>
invoke<void>('set_account', { id, accountId })
export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> => export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> =>
listen<RecordingState>('recording-state', (event) => handler(event.payload)) listen<RecordingState>('recording-state', (event) => handler(event.payload))
+33
View File
@@ -20,3 +20,36 @@ export function formatTimeRange(startedAt: string, endedAt: string | null, now =
const range = endedAt ? `${clock(start)} – ${clock(new Date(endedAt))}` : clock(start) const range = endedAt ? `${clock(start)} – ${clock(new Date(endedAt))}` : clock(start)
return `${day}, ${range}` return `${day}, ${range}`
} }
const weekdays = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa']
/** "heute", "gestern", or `other(date)` for an older day. */
function dayName(d: Date, now: Date, other: (d: Date) => string): string {
if (sameDay(d, now)) return 'heute'
const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
return sameDay(d, yesterday) ? 'gestern' : other(d)
}
const dayMonth = (d: Date) => `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.`
/** Call list: "heute 10:14", "gestern 10:14" or "04.11. 10:14". */
export function formatListTime(startedAt: string, now = new Date()): string {
const start = new Date(startedAt)
return `${dayName(start, now, dayMonth)} ${clock(start)}`
}
/** Detail header: "heute 10:14", "gestern 10:14" or "Mi 04.11. 10:14". */
export function formatDetailTime(startedAt: string, now = new Date()): string {
const start = new Date(startedAt)
const other = (d: Date) => `${weekdays[d.getDay()]} ${dayMonth(d)}`
return `${dayName(start, now, other)} ${clock(start)}`
}
/** Position in the recording: "04:07", or "1:02:07" from one hour on. */
export function formatOffset(secs: number): string {
const total = Math.max(0, Math.floor(secs))
const h = Math.floor(total / 3600)
const mm = pad(Math.floor((total % 3600) / 60))
const ss = pad(total % 60)
return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`
}
+424
View File
@@ -0,0 +1,424 @@
<script lang="ts">
import { onMount } from 'svelte'
import {
discardCall,
errorText,
getCall,
listAccounts,
listCalls,
onCallEnded,
onCallUpdated,
onPromptChanged,
onRecordingState,
renameSpeaker,
retryCall,
setAccount,
transcribeCall,
type Account,
type CallDetail,
type CallId,
type CallListItem,
} from '../lib/api'
import CallList from '../lib/CallList.svelte'
import { formatDetailTime, formatMinutes } from '../lib/format'
import StatusPill from '../lib/StatusPill.svelte'
import TranscriptView from '../lib/TranscriptView.svelte'
let calls = $state<CallListItem[]>([])
let loaded = $state(false)
let listError = $state('')
let accounts = $state<Account[]>([])
let selectedId = $state<CallId | null>(null)
let detail = $state<CallDetail | null>(null)
let detailError = $state('')
let actionError = $state('')
let busy = $state(false)
let tab = $state<'summary' | 'transcript'>('transcript')
// Answers can arrive out of order; only the newest request is applied.
let listRequest = 0
let detailRequest = 0
async function refreshList() {
const request = ++listRequest
try {
const next = await listCalls()
if (request !== listRequest) return
const before = calls.find((c) => c.id === selectedId)
const after = next.find((c) => c.id === selectedId)
const firstLoad = !loaded
calls = next
loaded = true
listError = ''
if (firstLoad && selectedId === null && next.length > 0) {
select(next[0].id)
} else if (selectedId !== null && !after) {
clearSelection() // discarded or deleted elsewhere
} else if (JSON.stringify(before) !== JSON.stringify(after)) {
refreshDetail()
}
} catch (err) {
listError = errorText(err)
}
}
async function refreshDetail() {
const id = selectedId
if (id === null) return
const request = ++detailRequest
try {
const next = await getCall(id)
if (request === detailRequest && id === selectedId) {
detail = next
detailError = ''
}
} catch (err) {
if (request === detailRequest && id === selectedId) detailError = errorText(err)
}
}
function select(id: CallId) {
if (id === selectedId) return
selectedId = id
detail = null
detailError = ''
actionError = ''
refreshDetail()
}
function clearSelection() {
selectedId = null
detail = null
detailError = ''
actionError = ''
}
onMount(() => {
const unlisten = [
onCallUpdated((id) => {
refreshList()
if (id === selectedId) refreshDetail()
}),
onCallEnded(refreshList),
onPromptChanged(refreshList),
onRecordingState(refreshList),
]
refreshList()
listAccounts()
.then((list) => (accounts = list))
.catch((err) => (listError = errorText(err)))
return () => unlisten.forEach((u) => u.then((off) => off()))
})
/** Runs a command on the shown call; its error is shown inline. */
async function run(action: (id: CallId) => Promise<void>, done?: () => void) {
if (!detail) return
const id = detail.call.id
busy = true
actionError = ''
try {
await action(id)
done?.()
} catch (err) {
if (id === selectedId) actionError = errorText(err)
} finally {
busy = false
}
}
const transcribe = () => run(transcribeCall)
const retry = () => run(retryCall)
const discard = () =>
run(discardCall, () => {
clearSelection()
refreshList()
})
function changeAccount(event: Event) {
const select = event.currentTarget as HTMLSelectElement
const previous = detail?.call.account_id ?? ''
run(async (id) => {
try {
await setAccount(id, select.value || null)
} catch (err) {
select.value = previous
throw err
}
await refreshDetail()
})
}
async function rename(speakerKey: string, name: string) {
if (!detail) return
await renameSpeaker(detail.call.id, speakerKey, name)
await refreshDetail()
}
/** "Microsoft Teams · heute 10:14 · 32 min" (no duration while recording). */
function title(call: CallListItem): string {
const parts = [call.app, formatDetailTime(call.started_at)]
if (call.status !== 'recording') parts.push(formatMinutes(call.duration_secs))
return parts.join(' · ')
}
/** The account list plus the stored account if it is no longer listed. */
let accountOptions = $derived.by(() => {
const stored = detail?.call.account_id
if (!stored || accounts.some((a) => a.id === stored)) return accounts
return [...accounts, { id: stored, name: `${stored} (unbekannt)` }]
})
// A failed start (e.g. missing key) also marks the call failed; its
// error is then shown once, in the failure box.
let shownActionError = $derived(actionError !== detail?.call.error ? actionError : '')
</script>
<main class="main">
<aside class="sidebar">
<header class="sidebar-header">
<h1>Gespräche</h1>
<a class="gear" href="#/settings" title="Einstellungen" aria-label="Einstellungen">⚙</a>
</header>
<div class="list">
{#if listError}
<p class="error pad">{listError}</p>
{/if}
{#if loaded}
<CallList {calls} {selectedId} onselect={select} />
{/if}
</div>
</aside>
<section class="detail">
{#if detail}
{@const call = detail.call}
<header class="detail-header">
<div class="heading">
<h1>{title(call)}</h1>
<StatusPill status={call.status} interrupted={call.interrupted} />
</div>
<div class="toolbar">
<label class="customer">
<span>Kunde:</span>
<select value={call.account_id ?? ''} disabled={busy} onchange={changeAccount}>
<option value="">— kein Kunde —</option>
{#each accountOptions as account (account.id)}
<option value={account.id}>{account.name}</option>
{/each}
</select>
</label>
<span class="actions">
{#if call.status === 'awaiting_decision'}
<button class="btn primary" disabled={busy} onclick={transcribe}>Transkribieren</button>
<button class="btn danger" disabled={busy} onclick={discard}>Verwerfen</button>
{:else if call.status === 'failed'}
<button class="btn primary" disabled={busy} onclick={retry}>Erneut versuchen</button>
<button class="btn danger" disabled={busy} onclick={discard}>Verwerfen</button>
{:else if call.status === 'done'}
<span title="Kommt in einer späteren Version">
<button class="btn" disabled>In Kundenakte speichern</button>
</span>
{/if}
</span>
</div>
{#if shownActionError}
<p class="error">{shownActionError}</p>
{/if}
</header>
<div class="body">
{#if call.status === 'recording'}
<p class="state rec">● Aufnahme läuft</p>
{:else if call.status === 'processing'}
<p class="state">wird verarbeitet…</p>
{:else if call.status === 'awaiting_decision'}
<p class="state">
{call.interrupted
? 'Noch nicht transkribiert. Die Aufnahme wurde unterbrochen.'
: 'Noch nicht transkribiert.'}
</p>
{:else if call.status === 'failed'}
<div class="failure">
<strong>Verarbeitung fehlgeschlagen</strong>
<div>{call.error ?? 'Unbekannter Fehler'}</div>
</div>
{:else}
<div class="tabs" role="tablist">
<button
role="tab"
aria-selected={tab === 'summary'}
class:active={tab === 'summary'}
onclick={() => (tab = 'summary')}>Zusammenfassung</button
>
<button
role="tab"
aria-selected={tab === 'transcript'}
class:active={tab === 'transcript'}
onclick={() => (tab = 'transcript')}>Transkript</button
>
</div>
<div class="tab-panel" role="tabpanel">
{#if tab === 'summary'}
<p class="muted">Die Zusammenfassung kommt in einer späteren Version.</p>
{:else}
<TranscriptView segments={detail.segments} onrename={rename} />
{/if}
</div>
{/if}
</div>
{:else if detailError}
<p class="error pad">{detailError}</p>
{:else if loaded && selectedId === null && calls.length > 0}
<p class="muted pad">Gespräch links auswählen.</p>
{/if}
</section>
</main>
<style>
:global(body:has(.main)) {
overflow: hidden;
}
.main {
display: grid;
grid-template-columns: minmax(260px, 30%) 1fr;
height: 100vh;
}
.sidebar {
display: flex;
flex-direction: column;
min-height: 0;
background: var(--surface);
border-right: 1px solid var(--border);
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 12px 10px 16px;
border-bottom: 1px solid var(--border);
}
.sidebar-header h1 {
font-size: 16px;
}
.gear {
color: var(--muted);
font-size: 18px;
line-height: 1;
padding: 4px 6px;
border-radius: 6px;
text-decoration: none;
}
.gear:hover {
color: var(--primary);
background: var(--primary-soft);
}
.list {
flex: 1;
overflow-y: auto;
}
.detail {
min-width: 0;
overflow-y: auto;
padding: 18px 24px 28px;
}
.pad {
padding: 16px;
}
.detail-header {
margin-bottom: 16px;
}
.heading {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px 12px;
}
.heading h1 {
font-size: 18px;
}
.toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px 16px;
margin-top: 12px;
}
.customer {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 600;
}
.customer select {
max-width: 260px;
}
.actions {
display: inline-flex;
gap: 8px;
margin-left: auto;
}
.detail-header .error {
margin: 10px 0 0;
}
.state {
color: var(--muted);
}
.state.rec {
color: var(--rec);
font-weight: 600;
}
.failure {
padding: 10px 12px;
border-radius: 8px;
background: var(--rec-soft);
color: var(--rec);
}
.tabs {
display: flex;
gap: 4px;
border-bottom: 1px solid var(--border);
}
.tabs button {
padding: 8px 14px;
border: none;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
background: none;
font: inherit;
font-weight: 600;
color: var(--muted);
cursor: pointer;
}
.tabs button.active {
color: var(--primary);
border-bottom-color: var(--primary);
}
.tab-panel {
padding-top: 14px;
}
</style>