diff --git a/docs/project/cycles/12-kitokey-simple-and-beautiful.md b/docs/project/cycles/12-kitokey-simple-and-beautiful.md index 019e9c47..19de5061 100644 --- a/docs/project/cycles/12-kitokey-simple-and-beautiful.md +++ b/docs/project/cycles/12-kitokey-simple-and-beautiful.md @@ -307,6 +307,33 @@ says (b)'s sentence for the private path; nothing of (a) is built in this cycle their date, so it finds dates. The title from the summary is #1240's, moved here: it is what makes the list readable. +**Criterion 2, measured on 2026-12-01.** Budget: D105's 100 ms for a response (cycle 11, as amended on +2026-11-20). Machine: AMD Ryzen AI 7 PRO 350, 16 threads, 24 GB, Linux 7.3.4, WebKitGTK 2.54.2. Set: `set500v2`, +500 meetings of an hour each (78 MB), made for the measure by `modules/shell/scripts/meetings_made.py`, no real +meeting, every line one the shell reads: « devis » in three transcripts, « budget » in every summary, « zzqx » +nowhere. Figures in ms, medians. + +| Method | Measured where | First search | A search after it | +|---|---|---|---| +| Every file read at each search | `tests/search_speed.rs`, release build, the machine's lock held | 414 | 414 | +| Kept: each summary and transcript read once, folded, read again only once its file changes (`search::Corpus`) | same | 449 (every file read) | 32 (« devis » 32.7, « budget » 32.6, « zzqx » 30.4) | +| **Kept, answered in parts, the list hidden whole** | the release build in a session of its own, by D105's method (#1034): in the page, from the words typed to the status, the first passage and the search complete, each plus one frame; 5 runs | status 14, first passage 77 (runs 69–99), complete 83 | « budget » 63 (complete 70), « zzqx » complete 55, « devis » 50 (52) | + +- **Chosen: the kept passages, answered in parts.** A search reads for 50 ms at most, newest meetings first, every + title in its first answer; the window draws each answer as it comes, says « Recherche… » until the search is + complete, and asks again. The texts are read ahead from the first list drawn. +- **Held, with little margin cold:** the first passage cold is 77 ms in the median and 99 ms in the slowest of five + runs. The page's thread never stalls more than 30 ms. +- **The cost: memory.** Holding the passages takes 122 MB more for 500 hours (4 MB resident before the first + search, 126 MB after): each line kept as written and folded. +- **The cold case was first not the search.** The window's search hid the list's 500 rows one by one: 1.9 s in + WebKitGTK, and 2.1 s to show them again (measured in the page). The list is now hidden in one write; its rows are + filtered one by one only when the shell does not answer. The same cost elsewhere in the window: #1419. +- A first set (`speaker` drawn as `me` or `them`, `track` drawn apart) left two lines in three unread by the + shell, and every figure measured on it was too low; the generator's test now demands each line read. +- The probe that measured the app (`speed_search.py`, on #1034's harness) is in D127's pull request, as its method; + it is not merged. + ### D128 `screens-and-delight.md` §4, *Shortcuts* and *Command palette*. The global shortcut, which the desktop grants, stays as it is. diff --git a/modules/shell/scripts/e2e_window.py b/modules/shell/scripts/e2e_window.py index 45e991a7..25674994 100644 --- a/modules/shell/scripts/e2e_window.py +++ b/modules/shell/scripts/e2e_window.py @@ -11162,7 +11162,9 @@ def found_by_what_was_said(now: dt.datetime) -> None: the field reaches them; Entrée on the transcript's opens the meeting on its « Transcription » tab (under 1400 px), the line in view and focused, the player cued there and paused; on the summary's, on « Compte rendu », focused there; on a title's, the focus on the meeting's name, never the body (#1400); typed fast, - only the last words' results are shown; axe clean in both themes.""" + only the last words' results are shown; axe clean in both themes. D127 c2: answered in parts, « Recherche… » said + until complete, each part appended with the focus kept; an answer for other words dropped; 50 results a group, + a button the others.""" print("DG. the search by what was said: titles, summaries, transcripts grouped, the passage marked, Entrée opening the meeting at its line (D127a)") meetings = WORK / "found" titled, summarised, heard, other = (meetings / f"2026-11-2{n}_10-00" for n in (6, 5, 4, 3)) @@ -11211,6 +11213,8 @@ def found_by_what_was_said(now: dt.datetime) -> None: back = lambda b: (b.execute_script("location.hash = '#/'"), wait_for(b, lambda c: c.find_element(By.ID, "find").is_displayed(), 10)) + seeking_word = {"fr": "Recherche…", "en": "Searching…"} + more_word = {"fr": "Afficher 10 de plus", "en": "Show 10 more"} for language, heads, theme in (("fr_FR.UTF-8", ["Titres", "Comptes rendus", "Transcriptions"], "light"), ("en_US.UTF-8", ["Titles", "Summaries", "Transcripts"], "dark")): short = language[:2] @@ -11221,6 +11225,12 @@ def found_by_what_was_said(now: dt.datetime) -> None: typed(browser, "budget") drawn = wait_for(browser, lambda b: (r := b.execute_script(results)) is not None and len(r) == 3, 10) got = browser.execute_script(results) + # D127 c2: the list hidden whole, in one write, its rows untouched — none hidden one by one, none marked —: + # on 500 meetings, hiding rows one at a time took WebKitGTK 1.9 s at the first word typed. + rows = ("const g = document.getElementById('groups');" + " return [g.hidden, g.querySelectorAll('li[hidden], .group[hidden]').length, g.querySelectorAll('mark').length]") + check(f"{short}, a search hides the list whole, no row hidden or marked one by one", browser.execute_script(rows) == [True, 0, 0], + browser.execute_script(rows)) check(f"{short}, « budget » finds the meetings grouped by where it was found, in order, each group headed and named by its heading", drawn and [g[0] for g in got] == heads and all(g[1] for g in got), got) check(f"{short}, each group its meeting, its passage, the word marked; the transcript's with its time", @@ -11321,6 +11331,99 @@ def found_by_what_was_said(now: dt.datetime) -> None: browser.execute_script(results)]) browser.execute_script("Object.defineProperty(window, '__TAURI__', { configurable: true, writable: true, value: window.__tauri })") + # D127 c2: the shell answers with what it read so far, then the rest — a double of `searched` gives the + # answers in turn, the second held until let go. While incomplete « Recherche… » is said; each answer's + # new results are appended, the ones drawn kept as they are (marked, the focus on one stays); the last + # answer complete, the status gone. An answer for other words than those typed is dropped (#1414's G3). + back(browser) + hit = lambda folder, passage, start=None: {"folder": str(folder), "passage": passage, "start": start} + answers = [ + # Every title at the first answer, as the shell gives them. + {"typed": "budget", "titles": [hit(titled, "Budget 2027")], "minutes": [hit(summarised, "Le budget est revu en janvier.")], + "transcripts": [], "complete": False}, + {"hold": True, "typed": "budget", "titles": [hit(titled, "Budget 2027")], "minutes": [hit(summarised, "Le budget est revu en janvier.")], + "transcripts": [hit(heard, "Le Budget, on en parle jeudi.", 75.4)], "complete": False}, + {"typed": "budget", "titles": [hit(titled, "Budget 2027")], "minutes": [hit(summarised, "Le budget est revu en janvier.")], + "transcripts": [hit(heard, "Le Budget, on en parle jeudi.", 75.4)], "complete": True}, + # « salle » typed, answered for « sa »: dropped. + {"typed": "sa", "titles": [], "minutes": [hit(other, "La salle est trouvée.")], "transcripts": [], "complete": True}, + # « revu »: 60 summaries' results, complete. + {"typed": "revu", "titles": [], "minutes": [hit(summarised, f"Le budget est revu, {n}.") for n in range(60)], + "transcripts": [], "complete": True}, + ] + browser.execute_script( + "const t = window.__TAURI__, core = t.core; window.__tauri = t; window.__answers = arguments[0]; window.__go = false;" + " window.__asked = 0;" + " const late = Object.assign(Object.create(Object.getPrototypeOf(core)), core, { invoke: (asked, rest, options) => {" + " if (asked !== 'searched') return core.invoke(asked, rest, options);" + " window.__asked++; const one = window.__answers.shift(); if (!one) return Promise.resolve(null);" + " const wait = (done) => (!one.hold || window.__go) ? done(one) : setTimeout(() => wait(done), 10);" + " return new Promise(wait); } });" + " const top = Object.assign({}, t, { core: late }); try { window.__TAURI__ = top; } catch (x) {}" + " if (window.__TAURI__ !== top) Object.defineProperty(window, '__TAURI__', { configurable: true, writable: true, value: top });", + answers) + seeking = "const s = document.getElementById('seeking'); return [!s.hidden && s.getClientRects().length > 0, s.textContent, s.getAttribute('role')]" + typed(browser, "budget") + first = wait_for(browser, lambda b: (r := b.execute_script(results)) is not None and len(r) == 2, 10) + said = browser.execute_script(seeking) + check(f"{short}, the search not complete: what came is drawn, « {seeking_word[short]} » said in a status", + first and [[g[0], g[2][0][0]] for g in browser.execute_script(results)] == [[heads[0], titled.name], [heads[1], summarised.name]] + and said == [True, seeking_word[short], "status"] + and not browser.find_element(By.ID, "none-found").is_displayed(), + [browser.execute_script(results), said, browser.find_element(By.ID, "none-found").is_displayed()]) + shot_themed(browser, f"dg-seeking-{short}-{theme}", theme) + # The focus on the result drawn, marked; then the held answer let go. + browser.find_element(By.ID, "find").click() + ActionChains(browser).send_keys(Keys.ARROW_DOWN).perform() + wait_for(browser, lambda b: b.execute_script("return document.activeElement.matches('#found a.found')"), 3) + browser.execute_script("document.activeElement.dataset.kept = 'yes'") + browser.execute_script("window.__go = true") + appended = wait_for(browser, lambda b: (r := b.execute_script(results)) is not None and len(r) == 3 + and not b.execute_script(seeking)[0], 10) + got = [browser.execute_script(results), browser.execute_script(focus_in, "#found"), + browser.execute_script("return document.activeElement.dataset.kept ?? null"), browser.execute_script(seeking), + browser.execute_script("return window.__asked")] + check(f"{short}, the rest appended in its group's place, the result drawn before kept with the focus on it; complete, the status gone", + appended and [g[0] for g in got[0]] == heads and got[0][2][2][0][0] == heard.name and got[1][1] and got[2] == "yes" + and got[4] == 3, got) + typed(browser, "salle") + time.sleep(0.5) + got = [browser.execute_script(results), browser.execute_script("return window.__asked")] + check(f"{short}, an answer for other words than those typed is dropped: nothing of it drawn", + got[1] == 4 and other.name not in json.dumps(got[0]), got) + typed(browser, "revu") + fifty = wait_for(browser, lambda b: (r := b.execute_script(results)) is not None and len(r) == 1 and len(r[0][2]) == 50, 10) + more = "const m = document.querySelector('#found .found-more'); return m && !m.hidden ? m.textContent : null" + got = [len(browser.execute_script(results)[0][2]) if fifty else None, browser.execute_script(more)] + check(f"{short}, 60 results: the first 50 drawn, a button the others", fifty and got[1] == more_word[short], got) + browser.execute_script("document.querySelector('#found .found-more').scrollIntoView({ block: 'end' })") + shot_themed(browser, f"dg-fifty-more-{short}-{theme}", theme) + browser.execute_script("document.querySelector('#found .found-more').focus()") + ActionChains(browser).send_keys(Keys.ENTER).perform() + sixty = wait_for(browser, lambda b: len(b.execute_script(results)[0][2]) == 60, 10) + got = [len(browser.execute_script(results)[0][2]), browser.execute_script(more), + browser.execute_script("return [...document.querySelectorAll('#found a.found')].indexOf(document.activeElement)")] + check(f"{short}, the button pressed: the 10 others drawn, the focus on the first of them, the button gone", + sixty and got[1] is None and got[2] == 50, got) + browser.execute_script("Object.defineProperty(window, '__TAURI__', { configurable: true, writable: true, value: window.__tauri })") + + # The shell failing: the rows filtered by what their row says, the search as it was before D127; emptied, + # every row back, unmarked. + browser.execute_script( + "const t = window.__TAURI__, core = t.core; window.__tauri = t;" + " const failing = Object.assign(Object.create(Object.getPrototypeOf(core)), core, { invoke: (asked, rest, options) =>" + " asked === 'searched' ? Promise.reject('failed') : core.invoke(asked, rest, options) });" + " const top = Object.assign({}, t, { core: failing }); try { window.__TAURI__ = top; } catch (x) {}" + " if (window.__TAURI__ !== top) Object.defineProperty(window, '__TAURI__', { configurable: true, writable: true, value: top });") + shown_rows = "return [...document.querySelectorAll('#groups .session')].filter(r => r.getClientRects().length > 0).map(r => decodeURIComponent(r.getAttribute('href').split('/').pop()))" + typed(browser, "budget") + by_title = wait_for(browser, lambda b: b.execute_script(shown_rows) == [titled.name] and not b.execute_script(results), 10) + check(f"{short}, the shell failing: the rows filtered by what their row says", by_title, [browser.execute_script(shown_rows), browser.execute_script(results)]) + typed(browser, "") + back_all = wait_for(browser, lambda b: len(b.execute_script(shown_rows)) == 4 and b.execute_script(rows) == [False, 0, 0], 10) + check(f"{short}, emptied after it: every row back, unmarked", back_all, [browser.execute_script(shown_rows), browser.execute_script(rows)]) + browser.execute_script("Object.defineProperty(window, '__TAURI__', { configurable: true, writable: true, value: window.__tauri })") + typed(browser, "zzzyx") none = wait_for(browser, lambda b: b.find_element(By.ID, "none-found").is_displayed() and not b.execute_script(results), 10) check(f"{short}, nothing found is said", none, [browser.find_element(By.ID, "none-found").text, browser.execute_script(results)]) diff --git a/modules/shell/scripts/meetings_made.py b/modules/shell/scripts/meetings_made.py new file mode 100755 index 00000000..6e4092a6 --- /dev/null +++ b/modules/shell/scripts/meetings_made.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Meetings made for measuring the search (D127, criterion 2): COUNT folders of MINUTES each, as Kitokey writes +them — `session.json`, a whole `transcript.jsonl` of a line every few seconds, a `minutes.md` of `minutes/v4` —, +nothing of a real meeting. The same seed makes the same meetings, so two runs measure the same files. + +Words placed for the measure, each in known meetings and nowhere else: +- « devis » said in three transcripts (the 8th, the 251st and the 494th meetings), late in each: a rare word; +- « budget » in every summary: a word found everywhere; +- « zzqx », nowhere: every file read, nothing found. + +Usage: meetings_made.py FOLDER [--count 500] [--minutes 60] [--seed 127] +""" + +import argparse +import datetime as dt +import json +import random +from pathlib import Path + +# Words of a work meeting, none of the placed ones. +WORDS = ( + "projet équipe client semaine planning livraison réunion point suivi retour produit version fonction écran " + "utilisateur test bug correctif priorité sprint objectif chiffre vente marché contrat fournisseur délai date " + "lundi mardi mercredi jeudi vendredi matin soir demain hier rapport document présentation question réponse " + "idée proposition décision action tâche responsable groupe service support serveur données sécurité accès " + "compte facture paiement commande stock prix coût marge partenaire réseau formation recrutement poste" +).split() +PLACED = {7: "devis", 250: "devis", 493: "devis"} + + +def sentence(chance: random.Random) -> str: + words = [chance.choice(WORDS) for _ in range(chance.randint(6, 16))] + return (" ".join(words) + ".").capitalize() + + +def meeting(folder: Path, at: int, started: dt.datetime, minutes: int, chance: random.Random) -> None: + folder.mkdir(parents=True) + stopped = started + dt.timedelta(minutes=minutes) + (folder / "session.json").write_text(json.dumps({ + "contract": "session-audio/v2", "started": started.isoformat(timespec="seconds"), + "stopped": stopped.isoformat(timespec="seconds"), "tracks": {}})) + lines = [{"type": "header", "contract": "transcript/v1", "engine": "whisper.cpp", "model": "ggml-large-v3-turbo-q8_0", + "language": "fr", "context": None}] + start, end_of_meeting = 0.0, minutes * 60.0 + while start < end_of_meeting - 5: + length = round(chance.uniform(2.0, 6.0), 1) + lines.append({"type": "segment", "speaker": chance.choice(["me", "them"]), "track": chance.choice(["local", "remote"]), + "voice": None, "start": round(start, 1), "end": round(start + length, 1), "text": sentence(chance)}) + start += length + round(chance.uniform(0.2, 1.5), 1) + if at in PLACED: + # Late in the meeting: a scan that stops at the first hit reads nearly all of it. + lines[-3]["text"] = f"On renvoie le {PLACED[at]} vendredi, signé." + lines.append({"type": "complete", "duration": end_of_meeting}) + (folder / "transcript.jsonl").write_text("".join(json.dumps(line, ensure_ascii=False) + "\n" for line in lines)) + made = stopped + dt.timedelta(minutes=3) + (folder / "minutes.md").write_text( + f"---\ncontract: minutes/v4\nmade: {made.isoformat(timespec='seconds')}\nprovider: local\nmodel: qwen3:8b\n" + f"context: null\ntitle: {json.dumps(f'Point {at + 1}')}\n---\n\n" + f"## Points saillants\n\nLe budget est revu. {sentence(chance)}\n\n" + f"## Actions\n\n" + "".join(f"- {sentence(chance)}\n" for _ in range(4)) + + "\n## Points clés\n\n" + "".join(f"- {sentence(chance)}\n" for _ in range(4))) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("folder", type=Path) + parser.add_argument("--count", type=int, default=500) + parser.add_argument("--minutes", type=int, default=60) + parser.add_argument("--seed", type=int, default=127) + asked = parser.parse_args() + if asked.folder.exists() and any(asked.folder.iterdir()): + raise SystemExit(f"{asked.folder} is not empty: the meetings are made in an empty folder") + chance = random.Random(asked.seed) + first = dt.datetime(2026, 1, 5, 9, 0, tzinfo=dt.timezone(dt.timedelta(hours=1))) + for at in range(asked.count): + started = first + dt.timedelta(hours=8 * at) + meeting(asked.folder / started.strftime("%Y-%m-%d_%H-%M"), at, started, asked.minutes, chance) + + +if __name__ == "__main__": + main() diff --git a/modules/shell/src/main.rs b/modules/shell/src/main.rs index b1625994..3013ac33 100644 --- a/modules/shell/src/main.rs +++ b/modules/shell/src/main.rs @@ -72,6 +72,8 @@ struct Shell { keyring: Mutex>, /// The search asked last (D127): a search sees it moved, and stops, once a newer one is asked. searches: search::Searches, + /// What the searches read, kept folded between them, each file read again once it changed (D127 b). + corpus: search::Corpus, /// The system's language, read at start: the interface's unless the user chose one (D64), and /// the one SpeechAnalyzer hears in when a meeting names none — never the interface's. system: Language, @@ -389,6 +391,7 @@ fn main() { .invoke_handler(tauri::generate_handler![ listed, searched, + search_warmed, destination_added, destination_forgotten, microphones_listed, @@ -567,6 +570,7 @@ fn main() { saving: Mutex::new(()), keyring: Mutex::new(None), searches: search::Searches::default(), + corpus: search::Corpus::default(), system, recording: Mutex::new(None), recorded: Mutex::new(None), @@ -1069,13 +1073,21 @@ type Shapes = HashMap, u64, Option<[Vec< /// What the search found (D127): where the words typed are, by group — each hit a meeting's own words, never the shell's. #[derive(serde::Serialize)] struct Searched { + /// The words this answer is for: the window ignores an answer for words replaced since (D127 c2). + typed: String, titles: Vec, minutes: Vec, transcripts: Vec, + /// Every meeting read: until then the window shows what came and asks again. + complete: bool, } -/// The meetings that hold the words typed (D127), read off the window's thread; `None` when a newer search replaced -/// this one before it ended: the last words typed win. +/// How long a search reads before it answers with what it found (D127 c2): the first results drawn within D105's +/// 100 ms, the window asking again for the rest. +const SEARCH_ANSWERS_WITHIN: Duration = Duration::from_millis(50); + +/// The meetings that hold the words typed (D127), read off the window's thread for `SEARCH_ANSWERS_WITHIN` at most, +/// newest first; `None` when a newer search replaced this one before it ended: the last words typed win. #[tauri::command] async fn searched(app: AppHandle, typed: String) -> Option { let asked = app.state::().searches.begin(); @@ -1084,10 +1096,13 @@ async fn searched(app: AppHandle, typed: String) -> Option { let current = || shell.searches.current(asked); let recorded = shell.recorded.lock().unwrap().clone(); let listed = sessions::list(&shell.settings().sessions, recorded.as_deref()); - search::found(&listed, &typed, ¤t).map(|found| Searched { + let until = Instant::now() + SEARCH_ANSWERS_WITHIN; + shell.corpus.found_until(&listed, &typed, ¤t, until).map(|found| Searched { + typed, titles: found.titles, minutes: found.minutes, transcripts: found.transcripts, + complete: found.complete, }) }) .await @@ -1095,6 +1110,19 @@ async fn searched(app: AppHandle, typed: String) -> Option { .flatten() } +/// Every meeting's summary and transcript read and kept for the search, off the window's thread, before a word is +/// typed (D127 b): asked once the window's list is drawn, and when the search's field takes the focus or the palette +/// opens; kept files only looked at. +#[tauri::command] +async fn search_warmed(app: AppHandle) { + let _ = tauri::async_runtime::spawn_blocking(move || { + let shell = app.state::(); + let recorded = shell.recorded.lock().unwrap().clone(); + shell.corpus.warm(&sessions::list(&shell.settings().sessions, recorded.as_deref())); + }) + .await; +} + /// The list, read away from the window's and the tray's thread: it reads every transcript it /// has not read yet. #[tauri::command] diff --git a/modules/shell/src/search.rs b/modules/shell/src/search.rs index 6640bd4e..ea3d8be9 100644 --- a/modules/shell/src/search.rs +++ b/modules/shell/src/search.rs @@ -1,9 +1,17 @@ //! A word found in the meetings (D127 a): in their titles, their summaries and their transcripts, each group apart, //! the meetings in the list's order (newest first), one result per meeting and group — its first passage, the //! transcript's with its time. Every word typed is sought in one passage, accents and case aside, as the window's -//! own search reads (`folding::folded`). The files are read as they are, no index: D127 b measures the scan. +//! own search reads (`folding::folded`). What a search read is kept, folded, between searches (`Corpus`) and read +//! again only once its file changed: a scan of every file took 414 ms on 500 meetings of an hour in release, over D105's +//! 100 ms; kept, see D127's section for the measure. -use std::{fs, path::PathBuf}; +use std::{ + collections::HashMap, + fs, + path::{Path, PathBuf}, + sync::Mutex, + time::{Duration, Instant, SystemTime}, +}; use pulldown_cmark::{Event, Parser, Tag, TagEnd}; use serde::Serialize; @@ -30,6 +38,8 @@ pub struct Found { pub titles: Vec, pub minutes: Vec, pub transcripts: Vec, + /// Every meeting listed read: false when the search's deadline came first (D127 c2). + pub complete: bool, } /// The searches asked, counted (D127): each new one takes the next turn, and a search is current until a newer one is @@ -49,44 +59,165 @@ impl Searches { } } -/// What `typed` finds in `listed`; `None` once `current` says a newer search replaced this one, asked before each -/// meeting is read. +/// What `typed` finds in `listed`, every file read; `None` once `current` says a newer search replaced this one, asked +/// before each meeting is read. pub fn found(listed: &[Listed], typed: &str, current: &dyn Fn() -> bool) -> Option { - let words: Vec = folded(typed).split_whitespace().map(str::to_string).collect(); - let mut found = Found::default(); - if words.is_empty() { - return Some(found); + Corpus::default().found(listed, typed, current) +} + +/// One passage a search can find: a summary's block or a transcript's line, as written and folded. +struct Piece { + said: String, + folded: String, + start: Option, +} + +/// A file as it was when read: its time of change and its length. A file rewritten is read again. +type Stamp = (Option, u64); + +/// What the searches read, kept between them (D127 b): each summary and transcript's passages, folded once, by file, +/// read again only when the file changed; the meetings no longer listed forgotten. +#[derive(Default)] +pub struct Corpus(Mutex)>>); + +impl Corpus { + /// What `typed` finds in `listed`; `None` once `current` says a newer search replaced this one, asked before each + /// meeting is read. + pub fn found(&self, listed: &[Listed], typed: &str, current: &dyn Fn() -> bool) -> Option { + self.found_until(listed, typed, current, Instant::now() + Duration::from_secs(3600)) } - let holds = |text: &str| { - let text = folded(text); - words.iter().all(|word| text.contains(word.as_str())) - }; - for session in listed { - if !current() { - return None; - } - let hit = |passage: &str, start| Hit { - folder: session.folder.clone(), - passage: passage_of(passage, &words[0]), - start, + + /// What `typed` finds in `listed` by `until` (D127 c2): every title, and the meetings read in the list's order, + /// newest first, one at least, each kept once read; the others left for the next search, which finds what this one + /// found first and unchanged, then more — `complete` once every meeting is read. `None` once `current` says a newer search replaced + /// this one, asked before each meeting. + pub fn found_until(&self, listed: &[Listed], typed: &str, current: &dyn Fn() -> bool, until: Instant) -> Option { + let words: Vec = folded(typed).split_whitespace().map(str::to_string).collect(); + let mut found = Found { + complete: true, + ..Found::default() }; - if let Some(title) = session.title.as_deref().filter(|title| holds(title)) { - found.titles.push(hit(title, None)); + if words.is_empty() { + return Some(found); } - if let Some(block) = fs::read_to_string(session.folder.join("minutes.md")) - .ok() - .and_then(|text| crate::minutes::body(&text).map(blocks)) - .and_then(|blocks| blocks.into_iter().find(|block| holds(block))) - { - found.minutes.push(hit(&block, None)); + let holds = |folded: &str| words.iter().all(|word| folded.contains(word.as_str())); + let passage = |piece: &Piece| (piece.said.clone(), piece.start); + let mut read = false; + for session in listed { + if !current() { + return None; + } + let (minutes, transcript) = (session.folder.join("minutes.md"), session.folder.join("transcript.jsonl")); + if let Some(title) = session.title.as_deref().filter(|title| holds(&folded(title))) { + found.titles.push(Hit { + folder: session.folder.clone(), + passage: passage_of(title, &words[0]), + start: None, + }); + } + // Past the deadline, a meeting not yet kept is left for the next search, its title alone sought (no file + // read): every title found at the first answer. One meeting is read at least. + if !found.complete || !(self.fresh(&minutes) && self.fresh(&transcript)) { + if !found.complete || (read && Instant::now() >= until) { + found.complete = false; + continue; + } + read = true; + } + let hit = |(said, start): (String, Option)| Hit { + folder: session.folder.clone(), + passage: passage_of(&said, &words[0]), + start, + }; + if let Some(piece) = self.first(&minutes, summary, &holds, passage) { + found.minutes.push(hit(piece)); + } + if let Some(piece) = self.first(&transcript, self::transcript, &holds, passage) { + found.transcripts.push(hit(piece)); + } + } + if found.complete { + self.kept() + .retain(|file, _| listed.iter().any(|session| file.parent() == Some(session.folder.as_path()))); } - if let Read::Present(transcript) = meeting::transcript(&session.folder) - && let Some(line) = transcript.segments.iter().find(|line| holds(&line.text)) + Some(found) + } + + /// Every summary and transcript of `listed` read and kept, newest first, before a word is typed (the window drawn, + /// the search's field focused, the palette opened): each file read with no lock held, so a search meanwhile finds + /// what is kept already and reads on. + pub fn warm(&self, listed: &[Listed]) { + for session in listed { + self.first(&session.folder.join("minutes.md"), summary, &|_| false, |_| ()); + self.first(&session.folder.join("transcript.jsonl"), transcript, &|_| false, |_| ()); + } + } + + /// How many files are kept: the summaries and transcripts of the meetings listed at the last complete search. + pub fn held(&self) -> usize { + self.kept().len() + } + + fn kept(&self) -> std::sync::MutexGuard<'_, HashMap)>> { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Whether `file` is kept as it is now, or is not there. + fn fresh(&self, file: &Path) -> bool { + stamp(file).is_none_or(|now| self.kept().get(file).is_some_and(|(was, _)| *was == now)) + } + + /// `file`'s first passage that `holds`, as `taken`, read by `read` unless kept as the file is now; the lock held + /// only to look and to keep, never while the file is read. None for a file not there. + fn first(&self, file: &Path, read: fn(&Path) -> Vec, holds: &dyn Fn(&str) -> bool, taken: impl Fn(&Piece) -> T) -> Option { + let Some(now) = stamp(file) else { + self.kept().remove(file); + return None; + }; { - found.transcripts.push(hit(&line.text, Some(line.start))); + let kept = self.kept(); + if let Some((_, pieces)) = kept.get(file).filter(|(was, _)| *was == now) { + return pieces.iter().find(|piece| holds(&piece.folded)).map(&taken); + } } + let pieces = read(file); + let one = pieces.iter().find(|piece| holds(&piece.folded)).map(&taken); + self.kept().insert(file.to_path_buf(), (now, pieces)); + one + } +} + +/// `file`'s stamp; none when it is not there. +fn stamp(file: &Path) -> Option { + fs::metadata(file).ok().map(|about| (about.modified().ok(), about.len())) +} + +fn piece(said: String, start: Option) -> Piece { + let folded = folded(&said); + Piece { said, folded, start } +} + +/// A summary's blocks, each a passage. +fn summary(file: &Path) -> Vec { + fs::read_to_string(file) + .ok() + .and_then(|text| crate::minutes::body(&text).map(blocks)) + .unwrap_or_default() + .into_iter() + .map(|block| piece(block, None)) + .collect() +} + +/// A transcript's lines, each a passage with its start. +fn transcript(file: &Path) -> Vec { + match file.parent().map(meeting::transcript) { + Some(Read::Present(transcript)) => transcript + .segments + .into_iter() + .map(|line| piece(line.text, Some(line.start))) + .collect(), + _ => Vec::new(), } - Some(found) } /// A summary's text blocks — each heading, paragraph and item — their markup aside. diff --git a/modules/shell/src/words.rs b/modules/shell/src/words.rs index 85cd94f5..f2d1bf4b 100644 --- a/modules/shell/src/words.rs +++ b/modules/shell/src/words.rs @@ -980,6 +980,14 @@ pub struct Window { /// typed were found — the meetings' titles, their summaries, their transcripts. Shows: the sidebar, while a word /// is typed in its search. When: asked. At most: about 20 characters each. Placeholders: none. pub found: [&'static str; 3], + /// The search still reading (D127 c2): said while what it found so far shows, until every meeting is read. + /// Shows: the sidebar, under the search's results. When: a search not yet complete. At most: about 20 characters. + /// Placeholders: none. + pub seeking: &'static str, + /// A group of the search's results past its first 50 (D127 c2): the button that shows the others. + /// Shows: the sidebar, at a group's end. When: a group has more than 50 results. At most: about 24 characters. + /// Placeholders: {} how many more. + pub found_more: &'static str, /// When an application takes the microphone (D30): its name and line, as board 4 has them. /// Shows: Settings, « Général », a list: its name, then its line under it (D30). When: always. /// At most: one line for the name, the line wraps. Placeholders: none. @@ -2420,6 +2428,8 @@ pub fn window(language: Language) -> Window { keys_heads: ["Key", "Action"], palette: ["Search for an action or a meeting", "Actions", "Meetings", "Nothing matches “{}”"], found: ["Titles", "Summaries", "Transcripts"], + seeking: "Searching…", + found_more: "Show {} more", offer: [ "When an app uses the microphone", "Usually a call starting. Kitokey never records without you knowing.", @@ -3041,6 +3051,8 @@ pub fn window(language: Language) -> Window { "Rien ne correspond à «\u{a0}{}\u{a0}»", ], found: ["Titres", "Comptes rendus", "Transcriptions"], + seeking: "Recherche…", + found_more: "Afficher {} de plus", offer: [ "Quand une application utilise le micro", "Le plus souvent, un appel qui commence. Kitokey n’enregistre jamais à votre insu.", diff --git a/modules/shell/tests/search.rs b/modules/shell/tests/search.rs index 380dcb71..29d9b03f 100644 --- a/modules/shell/tests/search.rs +++ b/modules/shell/tests/search.rs @@ -221,3 +221,153 @@ fn a_newer_search_asked_makes_the_older_one_no_longer_current() { assert!(!searches.current(older), "a newer search asked, the older one stops"); assert!(searches.current(newer), "the newer one goes on"); } + +#[test] +fn what_is_kept_between_searches_follows_the_files_rewritten_and_the_meetings_gone() { + // The shell's own memory of what was read (`Shell::corpus`, D127 b): a file rewritten is read again, a meeting + // gone is forgotten; the same results as a search that reads every file. + let root = tempfile::tempdir().unwrap(); + meeting( + root.path(), + "a", + "2026-11-03T10:00:00+01:00", + None, + Some("## Points\n\nLe budget est revu."), + &[(1.0, "Bonjour.")], + ); + meeting( + root.path(), + "b", + "2026-11-02T10:00:00+01:00", + None, + None, + &[(4.0, "On parle du devis.")], + ); + let corpus = search::Corpus::default(); + let kept = |typed: &str| { + corpus + .found(&sessions::list(root.path(), None), typed, &|| true) + .expect("not replaced") + }; + assert_eq!(kept("devis"), found(root.path(), "devis")); + assert_eq!(names(&kept("devis").transcripts), ["b"]); + assert!(kept("planning").transcripts.is_empty()); + // Rewritten — a transcript made again —: its new words found, its old ones no longer. + meeting( + root.path(), + "b", + "2026-11-02T10:00:00+01:00", + None, + None, + &[(4.0, "On parle du planning, encore.")], + ); + assert_eq!(names(&kept("planning").transcripts), ["b"], "the new words of a file rewritten"); + assert!(kept("devis").transcripts.is_empty(), "its old words gone"); + assert_eq!(kept("planning"), found(root.path(), "planning")); + // A summary removed, then a meeting gone: nothing of them found. + fs::remove_file(root.path().join("a").join("minutes.md")).unwrap(); + assert!(kept("budget").minutes.is_empty(), "a summary removed"); + fs::remove_dir_all(root.path().join("b")).unwrap(); + assert!(kept("planning").transcripts.is_empty(), "a meeting gone"); + assert_eq!(corpus.held(), 1, "only the meetings listed are kept: {}", corpus.held()); +} + +#[test] +fn warmed_before_a_word_is_typed_every_file_is_kept_and_the_results_are_the_same() { + // The search's field focused or the palette opened (D127 b): the files read then, off the window, so the first word + // typed finds them kept. + let root = tempfile::tempdir().unwrap(); + meeting( + root.path(), + "a", + "2026-11-03T10:00:00+01:00", + None, + Some("## Points\n\nLe budget est revu."), + &[(1.0, "Bonjour.")], + ); + meeting( + root.path(), + "b", + "2026-11-02T10:00:00+01:00", + None, + None, + &[(4.0, "On parle du devis.")], + ); + meeting(root.path(), "c", "2026-11-01T10:00:00+01:00", None, None, &[]); + let corpus = search::Corpus::default(); + let listed = sessions::list(root.path(), None); + corpus.warm(&listed); + assert_eq!(corpus.held(), 3, "a's summary and transcript, b's transcript"); + assert_eq!(corpus.found(&listed, "devis", &|| true), Some(found(root.path(), "devis"))); +} + +#[test] +fn a_search_past_its_deadline_reads_one_meeting_more_each_time_newest_first_until_complete() { + // D127 c2: a search answers within its deadline with every title and what it has read, newest meetings first, and + // says it is not complete; asked again, what it found before comes first and unchanged — the window appends, never redraws —, + // one meeting more each time at least, until it is complete and finds what a search reading every file finds. + let root = tempfile::tempdir().unwrap(); + for (name, day, title) in [("a", "03", None), ("b", "02", None), ("c", "01", Some("Budget 2027"))] { + meeting( + root.path(), + name, + &format!("2026-11-{day}T10:00:00+01:00"), + title, + Some("## Points\n\nLe budget est revu."), + &[(2.0, "Le devis du budget.")], + ); + } + let corpus = search::Corpus::default(); + let listed = sessions::list(root.path(), None); + let past = std::time::Instant::now(); + let mut seen: Vec = Vec::new(); + loop { + let now = corpus.found_until(&listed, "budget", &|| true, past).expect("not replaced"); + if let Some(before) = seen.last() { + assert!(now.minutes.starts_with(&before.minutes), "{now:?} after {before:?}"); + assert!(now.transcripts.starts_with(&before.transcripts), "{now:?} after {before:?}"); + assert!(now.minutes.len() > before.minutes.len() || now.complete, "no progress: {now:?}"); + } + let complete = now.complete; + seen.push(now); + if complete || seen.len() > 5 { + break; + } + } + assert_eq!( + names(&seen[0].minutes), + ["a"], + "the newest meeting first, one meeting read: {:?}", + seen[0] + ); + assert!(!seen[0].complete); + assert_eq!( + names(&seen[0].titles), + ["c"], + "every title at the first answer, no file read for it: {:?}", + seen[0] + ); + assert!( + seen.iter().all(|one| one.titles == seen[0].titles), + "the titles never grow: {seen:?}" + ); + let last = seen.last().unwrap(); + assert!(last.complete, "complete within one call a meeting: {seen:?}"); + assert_eq!(names(&last.minutes), ["a", "b", "c"]); + assert_eq!(*last, found(root.path(), "budget")); + // Everything kept: complete at once, the deadline past. + assert!(corpus.found_until(&listed, "devis", &|| true, past).unwrap().complete); +} + +#[test] +fn a_search_with_time_left_reads_everything_and_is_complete() { + let root = tempfile::tempdir().unwrap(); + meeting(root.path(), "a", "2026-11-03T10:00:00+01:00", None, None, &[(2.0, "Le devis.")]); + meeting(root.path(), "b", "2026-11-02T10:00:00+01:00", None, None, &[(2.0, "Le devis.")]); + let later = std::time::Instant::now() + std::time::Duration::from_secs(60); + let found = search::Corpus::default() + .found_until(&sessions::list(root.path(), None), "devis", &|| true, later) + .unwrap(); + assert!(found.complete); + assert_eq!(names(&found.transcripts), ["a", "b"]); +} diff --git a/modules/shell/tests/search_speed.rs b/modules/shell/tests/search_speed.rs new file mode 100644 index 00000000..845bca71 --- /dev/null +++ b/modules/shell/tests/search_speed.rs @@ -0,0 +1,70 @@ +//! How long the search takes on a set of meetings (D127, criterion 2): what `searched` does for one word typed — +//! the list read, then every summary and transcript sought —, the median of ten runs for each placed word of +//! `scripts/meetings_made.py`, through the shell's memory of what it read (`search::Corpus`) once it has read them all +//! once: within D105's 100 ms for an interaction (RAIL's response), measured in release. Ignored by default: it needs +//! the set, made first, and a release build. +//! +//! `scripts/meetings_made.py `, then +//! `KITOKEY_SEARCH_SET= cargo test --release --test search_speed -- --ignored --nocapture`. + +use std::time::{Duration, Instant}; + +use kitokey_shell::{search, sessions}; + +#[test] +#[ignore = "a measure, on a set made by scripts/meetings_made.py"] +fn the_search_on_a_set_of_meetings_timed() { + let set = std::env::var("KITOKEY_SEARCH_SET").expect("KITOKEY_SEARCH_SET names the set"); + let set = std::path::Path::new(&set); + let mut listing: Vec = (0..10) + .map(|_| { + let started = Instant::now(); + sessions::list(set, None); + started.elapsed() + }) + .collect(); + listing.sort(); + println!("SPEED the list alone: median {:.1} ms", listing[5].as_secs_f64() * 1e3); + // The process's resident memory, in MB, from /proc (Linux): what keeping the passages costs. + let resident = || { + let pages: u64 = std::fs::read_to_string("/proc/self/statm") + .ok() + .and_then(|statm| statm.split(' ').nth(1)?.parse().ok()) + .unwrap_or(0); + pages as f64 * 4096.0 / 1e6 + }; + let before = resident(); + let corpus = search::Corpus::default(); + let first = Instant::now(); + corpus.found(&sessions::list(set, None), "zzqx", &|| true); + println!( + "SPEED the first search, every file read: {:.1} ms; resident memory {before:.0} MB before, {:.0} MB after", + first.elapsed().as_secs_f64() * 1e3, + resident() + ); + let mut medians = Vec::new(); + for word in ["devis", "budget", "zzqx"] { + let mut took: Vec = Vec::new(); + let mut found = (0, 0, 0); + for _ in 0..10 { + let started = Instant::now(); + let listed = sessions::list(set, None); + let hits = corpus.found(&listed, word, &|| true).expect("never replaced"); + took.push(started.elapsed()); + found = (hits.titles.len(), hits.minutes.len(), hits.transcripts.len()); + } + took.sort(); + println!( + "SPEED {word}: median {:.1} ms, min {:.1} ms, max {:.1} ms; found titles {}, summaries {}, transcripts {}", + took[5].as_secs_f64() * 1e3, + took[0].as_secs_f64() * 1e3, + took[9].as_secs_f64() * 1e3, + found.0, + found.1, + found.2 + ); + medians.push(took[5]); + } + let most = medians.iter().max().unwrap(); + assert!(*most <= Duration::from_millis(100), "a search over D105's 100 ms: {most:?}"); +} diff --git a/modules/shell/tests/silence.rs b/modules/shell/tests/silence.rs index e6de63ad..c05e2839 100644 --- a/modules/shell/tests/silence.rs +++ b/modules/shell/tests/silence.rs @@ -44,6 +44,11 @@ const SILENT: &[(&str, usize, &str)] = &[ 1, "returns no `Result`: it cannot fail (D127); were it not answered, the rows filtered by their title stay, the search as it was before D127", ), + ( + "search_warmed", + 2, + "returns no `Result`: it cannot fail (D127 b; asked at the first list drawn and on the search's focus, D127 c2); unanswered, the first search reads the files itself, only slower", + ), ( "dates_file_chosen", 1, diff --git a/modules/shell/tests/words.rs b/modules/shell/tests/words.rs index 90d57711..14807487 100644 --- a/modules/shell/tests/words.rs +++ b/modules/shell/tests/words.rs @@ -1831,7 +1831,17 @@ fn broken(text: &str) -> Vec<&'static str> { /// The sentences right to keep against a rule of D124, each by its key, with its reason: an action /// in progress or an entry that opens a dialog keeps its « … » (V3, GNOME HIG and Apple HIG); a raw /// value shown under « Avancé », « Détails » or the developer mode keeps it (V1). Never a pattern. -const KEPT: [(&str, &str, &str); 28] = [ +const KEPT: [(&str, &str, &str); 30] = [ + ( + "ellipsis", + r#"window.seeking[0] "Searching…""#, + "an action in progress, the search still reading (D127 c2)", + ), + ( + "ellipsis", + r#"window.seeking[0] "Recherche…""#, + "an action in progress, the search still reading (D127 c2)", + ), ( "ellipsis", r#"window.version_forget[0] "Delete…""#, diff --git a/modules/shell/ui/index.html b/modules/shell/ui/index.html index cbf1fc0d..099ceebb 100644 --- a/modules/shell/ui/index.html +++ b/modules/shell/ui/index.html @@ -35,6 +35,7 @@
+