知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix: live notes keep updating through hours-long meetings without one topic swallowing the rest, and a long meeting's full notes cover all of it
wquguru1c15482c7839
diff --git a/Sources/Cicada/Notes.swift b/Sources/Cicada/Notes.swiftindex c31d4ab..b7e0862 100644--- a/Sources/Cicada/Notes.swift+++ b/Sources/Cicada/Notes.swift@@ -123,6 +123,16 @@ final class NotesEngine: ObservableObject {private var lastAttempt = Date.distantPastprivate var freshGeneration = 0static let interval: TimeInterval = 45+ /// The most topics the final notes have (the prompt says so too; the model doesn't always listen).+ static let maxTopics = 8+ /// The most topics live notes have. Live notes used to stop at `maxTopics` and pour everything+ /// after into the last topic, whose summary then grew into a wall of "最新…又…补充…"; past this,+ /// the two shortest neighbouring settled topics are joined instead, so the newest can start.+ static let liveMaxTopics = 12+ /// A topic summary longer than this is a log the model kept appending to, not one sentence.+ static let topicSummaryLimit = 160+ /// How many of the last topics a live update may rewrite; earlier ones stay as they are.+ static let editableTopics = 2init(ling: LingClient, store: SessionStore) {self.ling = ling@@ -245,14 +255,18 @@ final class NotesEngine: ObservableObject {let from = final ? 0 : min(base.covered, lines.count)let lang = language(id)let names = TranscriptExport.voices ? SpeakerLabels.names(session) : [:]- let prompt = Self.prompt(notes: base, lines: lines, from: from, language: lang, final: final, names: names)+ // A live update returns only the last topics: when it rewrote them all, its reply grew with+ // the meeting until, about an hour in, it was cut off at max_tokens or fell into a loop and+ // the notes stopped updating. The final pass still rewrites everything once.+ let frozen = final || fresh ? 0 : max(0, base.topics.count - Self.editableTopics)+ let prompt = Self.prompt(notes: base, lines: lines, from: from, language: lang, final: final, names: names, frozen: frozen)let started = Date()do {// The final pass sends only the transcript, with no notes in the reader's language to// follow: given a long English meeting the model drifts into English. Say the language// again where it is read last, and try once more if the reply still isn't in it.- var next: MeetingNotes?- for attempt in 1...(final || fresh ? 2 : 1) {+ var next = final ? await longFinal(lines, names: names, language: lang, startedAt: session.lines.first?.t ?? 0) : nil+ for attempt in 1...(final || fresh ? 2 : 1) where next == nil {let raw = try await ling.chat(content: prompt, instruction: "Update the notes. Write them in \(lang).",priority: .notes, json: true, maxTokens: 6000, timeout: 90, patient: final)guard let parsed = Self.parse(raw, times: lines.map(\.t), startedAt: session.lines.first?.t ?? 0) else { break }@@ -270,6 +284,7 @@ final class NotesEngine: ObservableObject {state = .idlereturn}+ if !final, !fresh { next.topics = Self.merge(base.topics, frozen: frozen, returned: next.topics) }Self.carryTimes(from: base, into: &next)// A reply without a name keeps the last one (not after a language change).if next.title == nil, !fresh { next.title = (id == shownID ? notes : session.notes)?.title }@@ -296,6 +311,58 @@ final class NotesEngine: ObservableObject {}}+ /// A long meeting's final pass: each part noted on its own, all at once, then merged into one.+ /// nil when a step fails: the caller then makes one pass over the whole transcript, as before.+ private func longFinal(_ lines: [TranscriptLine], names: [Int: String], language lang: String,+ startedAt: Double) async -> MeetingNotes? {+ let parts = Self.parts(lines)+ guard parts.count > 1 else { return nil }+ let started = Date()+ let times = lines.map(\.t)+ var replies = [String?](repeating: nil, count: parts.count)+ await withTaskGroup(of: (Int, String?).self) { group in+ for (i, range) in parts.enumerated() {+ let prompt = Self.prompt(notes: MeetingNotes(), lines: Array(lines.prefix(range.upperBound)), from: range.lowerBound,+ language: lang, final: true, names: names, part: (i + 1, parts.count))+ group.addTask { [ling] in+ let raw = try? await ling.chat(content: prompt, instruction: "Write the notes for this part. Write them in \(lang).",+ priority: .notes, json: true, maxTokens: 6000, timeout: 90)+ return (i, raw)+ }+ }+ for await (i, raw) in group { replies[i] = raw }+ }+ var notes: [String] = [], topics: [NoteTopic] = []+ for (i, raw) in replies.enumerated() {+ guard let raw, let parsed = Self.parse(raw, times: times, startedAt: startedAt), !parsed.topics.isEmpty,+ let a = raw.firstIndex(of: "{"), let b = raw.lastIndex(of: "}") else {+ debugLog("notes: final part \(i + 1)/\(parts.count) failed, one pass instead")+ return nil+ }+ // Without its topics: given them, the merge wrote them all back out and was cut off.+ guard var part = try? JSONSerialization.jsonObject(with: Data(raw[a...b].utf8)) as? [String: Any] else { return nil }+ part["topics"] = nil+ guard let data = try? JSONSerialization.data(withJSONObject: part), let text = String(data: data, encoding: .utf8) else { return nil }+ notes.append(text)+ topics += Self.spread(parsed.topics, to: Self.partTopics(parts.count))+ }+ let voices = TranscriptExport.voices && !SpeakerLabels.numbers(lines).isEmpty+ let prompt = Self.mergePrompt(parts: notes, lines: lines, language: lang, voices: voices)+ for attempt in 1...2 {+ guard let raw = try? await ling.chat(content: prompt, instruction: "Merge the notes. Write them in \(lang).",+ priority: .notes, json: true, maxTokens: 6000, timeout: 90),+ var merged = Self.parse(raw, times: times, startedAt: startedAt) else { break }+ merged.topics = topics+ if Self.written(merged, in: lang) {+ debugLog("notes: final in \(parts.count) parts → \(merged.topics.count) topics in \(Int(Date().timeIntervalSince(started))) s")+ return merged+ }+ debugLog("notes: merged reply not in \(lang) (attempt \(attempt)), dropped")+ }+ debugLog("notes: merging \(parts.count) parts failed, one pass instead")+ return nil+ }+/// "新" marks what the last live update added, for a minute. The final pass rewrites/// everything, so it marks nothing.private func markFresh(old: MeetingNotes, new: MeetingNotes, final: Bool) {@@ -311,6 +378,63 @@ final class NotesEngine: ObservableObject {}}+ /// A live reply's topics after the `frozen` ones it was told to leave alone: with some frozen, at+ /// most the editable ones plus one new, from the end (the model sometimes echoes the whole list),+ /// never a copy of a frozen one, each summary kept to one sentence; and no more than+ /// `liveMaxTopics` in all (past that, settled neighbours are joined). A reply with no topics of+ /// its own keeps the ones it had.+ static func merge(_ old: [NoteTopic], frozen: Int, returned: [NoteTopic]) -> [NoteTopic] {+ var kept = Array(old.prefix(frozen))+ let fixed = Set(kept.map(\.title))+ let own = returned.filter { !fixed.contains($0.title) }+ var tail = kept.isEmpty ? own : Array(own.suffix(old.count - kept.count + 1))+ guard !tail.isEmpty else { return old }+ for i in tail.indices { tail[i].summary = shortened(tail[i].summary) }+ tail = capped(tail, to: liveMaxTopics - min(kept.count, 1))+ while kept.count + tail.count > liveMaxTopics, kept.count >= 2 {+ // The pair spanning the least time, its end being the next topic's start.+ let ends = kept.dropFirst().map(\.start) + [tail[0].start]+ let i = (0..<kept.count - 1).min { ends[$0 + 1] - kept[$0].start < ends[$1 + 1] - kept[$1].start }!+ kept[i] = joined(kept[i], kept[i + 1])+ kept.remove(at: i + 1)+ }+ return capped(kept + tail, to: liveMaxTopics)+ }++ /// Two neighbouring topics as one: both titles and summaries, and up to the 4 points the prompt+ /// allows, taken evenly from each.+ static func joined(_ a: NoteTopic, _ b: NoteTopic) -> NoteTopic {+ let fromA = min(a.points.count, max(2, 4 - b.points.count))+ let fromB = min(b.points.count, 4 - fromA)+ let times = (0..<fromA).map(a.pointTime) + (0..<fromB).map(b.pointTime)+ let gap = a.summary.last.map { "。!?;".contains($0) } ?? true ? "" : " "+ return NoteTopic(start: a.start, title: "\(a.title) / \(b.title)", summary: a.summary + gap + b.summary,+ points: Array(a.points.prefix(fromA) + b.points.prefix(fromB)), fishbone: a.fishbone ?? b.fishbone,+ pointTimes: times.contains { $0 != nil } ? times : nil)+ }++ /// A runaway topic summary cut back to its first sentence (or to the limit, with "…").+ static func shortened(_ summary: String) -> String {+ guard summary.count > topicSummaryLimit else { return summary }+ let head = summary.prefix(topicSummaryLimit)+ if let end = head.dropFirst(10).firstIndex(where: { "。!?;.!?;".contains($0) }) { return String(head[...end]) }+ return head.trimmingCharacters(in: .whitespaces) + "…"+ }++ /// At most `count` topics (at least one): the points of any after that go into the last kept.+ static func capped(_ topics: [NoteTopic], to count: Int) -> [NoteTopic] {+ var topics = topics+ while topics.count > max(1, count) {+ let extra = topics.removeLast()+ var last = topics.removeLast()+ let times = (0..<last.points.count).map(last.pointTime) + (0..<extra.points.count).map(extra.pointTime)+ last.points += extra.points+ last.pointTimes = times.contains { $0 != nil } ? times : nil+ topics.append(last)+ }+ return topics+ }+/// The model echoes points it already had without evidence: keep the times they had.static func carryTimes(from old: MeetingNotes, into new: inout MeetingNotes) {var known: [String: Double] = [:]@@ -330,8 +454,9 @@ final class NotesEngine: ObservableObject {static func clock(_ t: Double) -> String { TranscriptExport.clock(t) }+ /// `part`: in a long meeting's final pass, which part `from..<lines.count` is (1-based, of `of`).static func prompt(notes: MeetingNotes, lines: [TranscriptLine], from: Int, language: String, final: Bool,- names: [Int: String] = [:]) -> String {+ names: [Int: String] = [:], frozen: Int = 0, part: (index: Int, of: Int)? = nil) -> String {let numbers = TranscriptExport.voices ? SpeakerLabels.numbers(lines) : [:]func line(_ i: Int) -> String {let l = lines[i]@@ -340,17 +465,23 @@ final class NotesEngine: ObservableObject {return "[L\(i + 1) \(clock(l.t)) \(who)] \(l.src)"}var current = "{}"- if !notes.isEmpty, let data = try? JSONEncoder().encode(Compact(notes)), let s = String(data: data, encoding: .utf8) {+ if !notes.isEmpty, let data = try? JSONEncoder().encode(Compact(notes, from: frozen)), let s = String(data: data, encoding: .utf8) {current = s}let context = max(0, from - 2)+ let task = part.map { "that has just ended. It was long, so it is noted in parts: write the notes for part \($0.index) of \($0.of) only, from the lines below" }+ ?? (final ? "that has just ended. Rewrite them from the whole transcript" : "that is still going on. Update them with the new lines")var p = """- You keep notes for a meeting \(final ? "that has just ended. Rewrite them from the whole transcript" : "that is still going on. Update them with the new lines").+ You keep notes for a meeting \(task).Write the notes in \(language). Return JSON only."""if !final {- p += "Current notes (JSON):\n\(current)\n\n"+ if frozen > 0 {+ p += "Earlier topics (settled: kept as they are, do not return them):\n"+ + notes.topics.prefix(frozen).map { "- \(clock($0.start)) \($0.title): \($0.summary)" }.joined(separator: "\n") + "\n\n"+ }+ p += "Current notes (JSON\(frozen > 0 ? ", latest topics only" : "")):\n\(current)\n\n"}if context < from {p += "Already covered (context only):\n" + (context..<from).map(line).joined(separator: "\n") + "\n\n"@@ -359,29 +490,35 @@ final class NotesEngine: ObservableObject {p += (from..<lines.count).map(line).joined(separator: "\n")// The model splits too eagerly when only told how long a topic should be: say plainly// whether this update may start one.- if final, let first = lines.first?.t, let last = lines.last?.t {- let most = max(1, min(8, Int((last - first) / 180) + 1))- p += "\n\nThis meeting ran \(clock(last - first)): use at most \(most) topic\(most == 1 ? "" : "s")."+ if final, from < lines.count, let last = lines.last?.t {+ let first = lines[from].t+ let most = max(1, min(part.map { partTopics($0.of) } ?? maxTopics, Int((last - first) / 180) + 1))+ p += "\n\nThis \(part == nil ? "meeting" : "part") ran \(clock(last - first)): use at most \(most) topic\(most == 1 ? "" : "s")."} else if !final, let current = notes.topics.last, let newest = lines.last?.t, newest - current.start < 120 {p += "\n\nThe current topic \"\(current.title)\" started at \(clock(current.start)), under 2 minutes ago: do not start a new topic in this update; add the new lines to it."} else if !final, notes.topics.isEmpty {p += "\n\nThese are the first lines: make one topic."}- p += """-+ p += "\n\n" + format(language: language, voices: !numbers.isEmpty, final: final, frozen: frozen)+ return p+ }+ /// The reply's JSON shape and the rules for its contents.+ private static func format(language: String, voices: Bool, final: Bool, frozen: Int) -> String {+ """Return the full notes as one JSON object with exactly these keys:{"title": "the meeting's name: what it is about, a few words","summary": "2-3 sentences on the whole meeting so far",- "topics": [{"start": seconds, "title": "short title", "summary": "one sentence", "points": [{"text": "key point", "evidence": ["L4"]}], "evidence": ["L3"],+ "topics": [{"start": seconds, "title": "short title", "summary": "one sentence on the whole topic", "points": [{"text": "key point", "evidence": ["L4"]}], "evidence": ["L3"],"fishbone": null or {"question": "the problem or question", "branches": [{"label": "2-6 words", "detail": "one short line", "t": seconds, "evidence": ["L5"]}]}}],"conclusions": [{"text": "...", "evidence": ["L7", "L8"]}],- "todos": [{"text": "...", "owner": \(numbers.isEmpty ? "\"对方\" or \"你\" or null" : "the person's label from the transcript (a name like \"George\", or \"说话人2\"), \"你\", or null when unclear"), "evidence": ["L9"]}],+ "todos": [{"text": "...", "owner": \(!voices ? "\"对方\" or \"你\" or null" : "the person's label from the transcript (a name like \"George\", or \"说话人2\"), \"你\", or null when unclear"), "evidence": ["L9"]}],"terms": [{"name": "correct spelling", "note": "who or what, a few words", "heard": ["how it was misrecognised"]}]}Rules (be brief: these notes are read at a glance during the meeting):- title: a name for the whole meeting, like a calendar entry (at most 12 Chinese characters or 6 words; no date, no quotes, not "会议" alone). Keep the current title unless the meeting's subject has clearly changed.- summary: at most 3 short sentences.- - Topics in time order, at most 8 in total. A topic is a stretch of the meeting, usually 3-10 minutes, not a single remark: start a new one only when the subject clearly changes and the current topic started at least 2 minutes before the newest line\(final ? "" : "; add at most one new topic per update"). Otherwise add to the current one, and merge small neighbouring topics. Keep earlier topics as they are unless new lines correct them. The last topic is the one being discussed now.+ - Topics in time order, \(frozen > 0 ? "returning only the topics in the current notes and at most one new one after them" : "at most \(maxTopics) in total"). A topic is a stretch of the meeting, usually 3-10 minutes, not a single remark: start a new one only when the subject clearly changes and the current topic started at least 2 minutes before the newest line\(final ? "" : "; add at most one new topic per update"). Otherwise add to the current one, and merge small neighbouring topics. Keep earlier topics as they are unless new lines correct them. The last topic is the one being discussed now.+ - A topic's summary is one sentence on the whole topic, at most 40 Chinese characters or 25 words: as the topic grows, rewrite it; never append to it or narrate what came next ("最新", "又", "补充", "then", "later").- At most 4 points per topic, each one short phrase. Merge rather than repeat.- At most 5 conclusions and only real to-dos (often none).- Add a fishbone only to a topic that discusses causes, reasons or factors (3-5 branches); otherwise null.@@ -391,7 +528,56 @@ final class NotesEngine: ObservableObject {- Write about what was said, never about the transcript or recognition quality.- Use empty arrays when there is nothing. No markdown, no text outside the JSON."""- return p+ }++ // MARK: Long meetings++ /// How a long meeting's final pass is split: over `splitMinutes`, into equal parts by time of at+ /// most `partMinutes`. One pass covered a 91-minute meeting but only the first hour of a 4-hour one.+ static let splitMinutes = 100.0+ static let partMinutes = 60.0+ static func parts(_ lines: [TranscriptLine]) -> [Range<Int>] {+ guard let first = lines.first?.t, let last = lines.last?.t else { return [] }+ let minutes = (last - first) / 60+ guard minutes > splitMinutes else { return [0..<lines.count] }+ let count = Int((minutes / partMinutes).rounded(.up))+ let length = (last - first) / Double(count)+ var bounds = [0]+ for k in 1..<count {+ let at = first + length * Double(k)+ if let i = lines.firstIndex(where: { $0.t >= at }), i > bounds.last! { bounds.append(i) }+ }+ bounds.append(lines.count)+ return zip(bounds, bounds.dropFirst()).map { $0..<$1 }+ }++ /// Each part's share of the topics: the merge keeps them as they are, so every part has some.+ static func partTopics(_ parts: Int) -> Int { max(2, maxTopics / max(1, parts)) }++ /// `count` of `topics`, spread evenly from the first to the last: a part's reply often has more+ /// topics than asked, and keeping the first ones (or folding the rest into the last) lost the+ /// end of each part.+ static func spread(_ topics: [NoteTopic], to count: Int) -> [NoteTopic] {+ guard topics.count > count, count > 0 else { return topics }+ guard count > 1 else { return [topics[0]] }+ return (0..<count).map { topics[Int((Double($0) * Double(topics.count - 1) / Double(count - 1)).rounded())] }+ }++ /// The whole meeting's title, summary, conclusions, to-dos and terms from its parts' notes (the+ /// replies as they came, with their evidence line ids). Asked to merge topics too, the model+ /// kept the first parts' and dropped the rest, so topics are joined in code.+ static func mergePrompt(parts: [String], lines: [TranscriptLine], language: String, voices: Bool) -> String {+ var p = """+ You keep notes for a meeting that has just ended. It was long, so each part was noted on its own; below are those notes, in time order (JSON; evidence ids are transcript lines, L1 the first). Merge them into the notes for the whole meeting.+ Write the notes in \(language). Return JSON only.+++ """+ for (i, part) in parts.enumerated() { p += "Part \(i + 1) of \(parts.count):\n\(part)\n\n" }+ if let first = lines.first?.t, let last = lines.last?.t {+ p += "This meeting ran \(clock(last - first)). Return \"topics\": []: the parts' topics are kept as they are. Name and summarise the whole meeting, every part of it; keep each conclusion, to-do and term once, with the evidence ids it had (joined when you merge two).\n\n"+ }+ return p + format(language: language, voices: voices, final: true, frozen: 0)}/// Whether the notes' own words (summary, titles) are in `language`: Chinese, Japanese and@@ -420,10 +606,11 @@ final class NotesEngine: ObservableObject {let points: [String]let fishbone: Fishbone?}- init(_ n: MeetingNotes) {+ /// `from`: the first topic sent (earlier ones go as a list of titles).+ init(_ n: MeetingNotes, from: Int = 0) {title = n.titlesummary = n.summary- topics = n.topics.map { Topic(start: $0.start, title: $0.title, summary: $0.summary, points: $0.points, fishbone: $0.fishbone) }+ topics = n.topics.dropFirst(from).map { Topic(start: $0.start, title: $0.title, summary: $0.summary, points: $0.points, fishbone: $0.fishbone) }conclusions = n.conclusions.map(\.text)todos = n.todos.map(\.text)terms = n.terms@@ -475,7 +662,10 @@ final class NotesEngine: ObservableObject {points.append(text)pointTimes.append((p as? [String: Any]).flatMap { time($0["evidence"]) })}- return NoteTopic(start: num(t["start"]) ?? startedAt, title: title, summary: str(t["summary"]),+ // When it was first said, from its lines: the model's own `start` drifts by tens of+ // minutes in a long meeting (a topic said at 51-85 min came back as starting at 23).+ let said = ([time(t["evidence"])] + pointTimes).compactMap { $0 }.min()+ return NoteTopic(start: said ?? num(t["start"]) ?? startedAt, title: title, summary: str(t["summary"]),points: points, fishbone: fish,pointTimes: pointTimes.contains { $0 != nil } ? pointTimes : nil)}diff --git a/Tests/CicadaTests/NotesTests.swift b/Tests/CicadaTests/NotesTests.swiftnew file mode 100644index 0000000..6037f54--- /dev/null+++ b/Tests/CicadaTests/NotesTests.swift@@ -0,0 +1,130 @@+import Foundation+import Testing+@testable import Cicada++/// Live notes rewrite only their last topics, so a long meeting's reply stays small.+@MainActor @Suite struct NotesTests {+ private func topic(_ start: Double, _ title: String, _ points: [String] = ["p"], _ times: [Double?]? = nil) -> NoteTopic {+ NoteTopic(start: start, title: title, summary: "s", points: points, fishbone: nil, pointTimes: times)+ }++ private func lines(_ n: Int) -> [TranscriptLine] {+ (0..<n).map { TranscriptLine(id: "l\($0)", t: Double($0 * 10), speaker: "them", src: "line \($0)", dst: nil, srcLang: "zh-CN", dstLang: "en") }+ }++ @Test func keepsFrozenTopicsAndTakesTheReplysTail() {+ let old = (0..<5).map { topic(Double($0 * 100), "t\($0)") }+ // The model echoed everything, renamed the current topic and added one.+ let reply = [topic(0, "t0"), topic(100, "t1 改"), topic(300, "t3"), topic(400, "t4 改"), topic(500, "t5")]+ let merged = NotesEngine.merge(old, frozen: 3, returned: reply)+ #expect(merged.map(\.title) == ["t0", "t1", "t2", "t3", "t4 改", "t5"])+ }++ @Test func nothingFrozenKeepsEveryTopic() {+ // The first update over many lines: nothing to echo, so every topic is the model's own.+ let reply = (0..<5).map { topic(Double($0 * 100), "t\($0)") }+ #expect(NotesEngine.merge([], frozen: 0, returned: reply) == reply)+ #expect(NotesEngine.merge([topic(0, "t0")], frozen: 0, returned: reply) == reply)+ }++ @Test func emptyReplyKeepsTheTopics() {+ let old = [topic(0, "a"), topic(100, "b"), topic(200, "c")]+ #expect(NotesEngine.merge(old, frozen: 1, returned: []) == old)+ #expect(NotesEngine.merge(old, frozen: 1, returned: [topic(0, "a")]) == old)+ }++ @Test func fullLiveNotesJoinTheShortestSettledPair() {+ // Twelve topics, t3 and t4 the shortest neighbours (t3 to t5 is 100 s): a new topic+ // still starts, and those two become one.+ let starts: [Double] = [0, 100, 200, 300, 330, 400, 600, 700, 800, 900, 1000, 1100]+ let old = starts.enumerated().map { topic($0.element, "t\($0.offset)", ["a\($0.offset)", "b\($0.offset)", "c\($0.offset)"]) }+ let reply = [topic(1000, "t10"), topic(1100, "t11"), topic(1200, "t12")]+ let merged = NotesEngine.merge(old, frozen: 10, returned: reply)+ #expect(merged.count == NotesEngine.liveMaxTopics)+ #expect(merged.last?.title == "t12")+ #expect(merged[3].title == "t3 / t4")+ #expect(merged[3].start == 300)+ #expect(merged[3].points == ["a3", "b3", "a4", "b4"])+ #expect(merged[3].summary == "s s")+ }++ @Test func runawayTopicSummaryIsCutToItsFirstSentence() {+ let log = "对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。" + String(repeating: "最新对方又补充了一些内容,", count: 20)+ var t = topic(0, "t0")+ t.summary = log+ let merged = NotesEngine.merge([], frozen: 0, returned: [t])+ #expect(merged[0].summary == "对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。")+ #expect(NotesEngine.shortened(String(repeating: "长", count: 200)).count == NotesEngine.topicSummaryLimit + 1)+ #expect(NotesEngine.shortened("short") == "short")+ }++ @Test func livePromptSendsOnlyTheLatestTopics() {+ var notes = MeetingNotes()+ notes.summary = "summary"+ notes.topics = [topic(0, "最早的话题"), topic(100, "第二个话题"), topic(200, "当前话题")]+ notes.covered = 20+ let p = NotesEngine.prompt(notes: notes, lines: lines(24), from: 20, language: "Simplified Chinese", final: false, frozen: 1)+ let json = p.components(separatedBy: "Current notes")[1].components(separatedBy: "\n\n")[0]+ #expect(p.contains("Earlier topics"))+ #expect(p.contains("- 00:00 最早的话题: s"))+ #expect(!json.contains("最早的话题"))+ #expect(json.contains("第二个话题") && json.contains("当前话题"))+ // A full rewrite has nothing frozen.+ let fresh = NotesEngine.prompt(notes: notes, lines: lines(24), from: 20, language: "Simplified Chinese", final: false)+ #expect(!fresh.contains("Earlier topics"))+ }++ @Test func livePromptAsksForOneSentenceSummaries() {+ var notes = MeetingNotes()+ notes.summary = "summary"+ notes.topics = (0..<8).map { topic(Double($0 * 10), "t\($0)") }+ notes.covered = 20+ let p = NotesEngine.prompt(notes: notes, lines: lines(24), from: 20, language: "English", final: false, frozen: 6)+ #expect(!p.contains("do not start a new topic"))+ #expect(p.contains("never append to it"))+ }++ @Test func longMeetingsSplitByTime() {+ // A line every 10 s: 90 min stays whole, 4 h becomes four parts of an hour.+ #expect(NotesEngine.parts(lines(540)) == [0..<540])+ let two = NotesEngine.parts(lines(1440))+ #expect(two.count == 4)+ #expect(two.first?.lowerBound == 0 && two.last?.upperBound == 1440)+ #expect(zip(two, two.dropFirst()).allSatisfy { $0.upperBound == $1.lowerBound })+ #expect(NotesEngine.parts([]) == [])+ }++ @Test func partPromptKeepsLineNumbers() {+ let all = lines(720)+ let p = NotesEngine.prompt(notes: MeetingNotes(), lines: Array(all.prefix(480)), from: 240, language: "English",+ final: true, part: (2, 3))+ #expect(p.contains("part 2 of 3"))+ #expect(p.contains("[L241 40:00 对方] line 240"))+ #expect(!p.contains("[L238 "))+ #expect(p.contains("This part ran 39:50"))+ let merge = NotesEngine.mergePrompt(parts: ["{\"summary\":\"a\"}", "{\"summary\":\"b\"}"], lines: all, language: "English", voices: false)+ #expect(merge.contains("Part 2 of 2:\n{\"summary\":\"b\"}"))+ #expect(merge.contains("Return the full notes as one JSON object"))+ #expect(merge.contains("\"topics\": []"))+ // Each of three parts gets two of the eight topics.+ #expect(p.contains("use at most 2 topics"))+ }++ @Test func topicStartsWhenItsLinesWereSaid() {+ let times = (0..<100).map { Double($0 * 60) }+ let raw = """+ {"summary": "s", "topics": [+ {"start": 1380, "title": "late", "summary": "s", "points": [{"text": "a", "evidence": ["L86"]}, {"text": "b", "evidence": ["L52"]}], "evidence": ["L60"]},+ {"start": 300, "title": "no evidence", "summary": "s", "points": ["c"]}]}+ """+ let n = NotesEngine.parse(raw, times: times, startedAt: 0)+ #expect(n?.topics.map(\.start) == [51 * 60, 300])+ }++ @Test func partTopicsSpreadOverThePart() {+ let ten = (0..<10).map { topic(Double($0 * 300), "t\($0)") }+ #expect(NotesEngine.spread(ten, to: 4).map(\.title) == ["t0", "t3", "t6", "t9"])+ #expect(NotesEngine.spread(ten, to: 1).map(\.title) == ["t0"])+ #expect(NotesEngine.spread(Array(ten.prefix(3)), to: 4).count == 3)+ }+}