Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

fix: keep trying for about a minute when the AI service is busy as a meeting's final notes are written

wquguru7707626623de
diff --git a/Sources/Cicada/Ling.swift b/Sources/Cicada/Ling.swift
index 2bf68ef..2056249 100644
--- a/Sources/Cicada/Ling.swift
+++ b/Sources/Cicada/Ling.swift
@@ -285,7 +285,7 @@ final class LingClient: ObservableObject {
/// instruction, for Ming's audio model (Ling only: `hearsAudio`).
func chat(content: String, instruction: String, priority: Priority, json: Bool = false,
maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil, audio: Data? = nil,
- role: String? = nil, onQueued: ((Double) -> Void)? = nil) async throws -> String {
+ role: String? = nil, patient: Bool = false, onQueued: ((Double) -> Void)? = nil) async throws -> String {
guard let key else { throw Failure.noKey }
guard keyState != .invalid else { throw Failure.invalidKey }
if let simulate {
@@ -308,9 +308,8 @@ final class LingClient: ObservableObject {
]
c.shape(&body, maxTokens: maxTokens)
if json { body["response_format"] = ["type": "json_object"] }
- let attempts = priority == .notes ? 4 : 1
- var delay = 1.0
- for attempt in 1...attempts {
+ let waits = Self.retryWaits(priority, patient: patient)
+ for attempt in 1...(waits.count + 1) {
let asked = Date()
await acquire(priority)
let queued = Date().timeIntervalSince(asked)
@@ -337,19 +336,27 @@ final class LingClient: ObservableObject {
} catch let failure as Failure {
report(call, priority, at: started, queued: queued, outcome: Self.name(failure))
guard failure == .rateLimited else { throw failure }
- guard attempt < attempts else {
+ guard attempt <= waits.count else {
rateLimitedAt = Date()
throw failure
}
- let wait = delay + Double.random(in: 0...0.5)
+ let wait = waits[attempt - 1] + Double.random(in: 0...0.5)
debugLog("ling: \(priority) 429, retry in \(String(format: "%.1f", wait)) s")
try? await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))
- delay *= 2
}
}
throw Failure.rateLimited
}
+ /// Seconds to wait before each retry of a 429. Notes retry a few times; translation and
+ /// speak-back fail fast so the caller can fall back. `patient` (the final notes) keeps at it for
+ /// about a minute: a model limited upstream (OpenRouter's Ling 3.1 by DeepInfra, 2026-11) came
+ /// back after ~15 s, and a meeting left without its notes is worse than notes a little late.
+ nonisolated static func retryWaits(_ priority: Priority, patient: Bool = false) -> [Double] {
+ guard priority == .notes else { return [] }
+ return patient ? [1, 2, 4, 8, 16, 30] : [1, 2, 4]
+ }
+
/// Every request, for diagnostics (timings and token counts only).
var onCall: ((AICall) -> Void)?
diff --git a/Sources/Cicada/Notes.swift b/Sources/Cicada/Notes.swift
index 5c911dd..c31d4ab 100644
--- a/Sources/Cicada/Notes.swift
+++ b/Sources/Cicada/Notes.swift
@@ -254,7 +254,7 @@ final class NotesEngine: ObservableObject {
var next: MeetingNotes?
for attempt in 1...(final || fresh ? 2 : 1) {
let raw = try await ling.chat(content: prompt, instruction: "Update the notes. Write them in \(lang).",
- priority: .notes, json: true, maxTokens: 6000, timeout: 90)
+ 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 }
if Self.written(parsed, in: lang) { next = parsed; break }
debugLog("notes: \(final ? "final" : "live") reply not in \(lang) (attempt \(attempt)), dropped")
diff --git a/Tests/CicadaTests/LingTests.swift b/Tests/CicadaTests/LingTests.swift
index afc272b..b00d055 100644
--- a/Tests/CicadaTests/LingTests.swift
+++ b/Tests/CicadaTests/LingTests.swift
@@ -58,6 +58,17 @@ final class LingStub: URLProtocol, @unchecked Sendable {
return ling
}
+ // MARK: Retries
+
+ @Test func finalNotesKeepRetryingForAboutAMinute() {
+ #expect(LingClient.retryWaits(.translate).isEmpty)
+ #expect(LingClient.retryWaits(.speak, patient: true).isEmpty)
+ #expect(LingClient.retryWaits(.notes) == [1, 2, 4])
+ let patient = LingClient.retryWaits(.notes, patient: true)
+ #expect(patient.count == 6)
+ #expect((50...70).contains(patient.reduce(0, +)))
+ }
+
// MARK: Key file
@Test func keyFileIsOnlyForThisUser() throws {
diff --git a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
index 5179813..5089f00 100644
--- a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
@@ -26,6 +26,7 @@ object ProviderTests {
"aiHearingUsesTheHearModel" to ::hearingUsesHearModel,
"aiProblemsNameTheService" to ::problemsNameTheService,
"aiAClockIsNotSpeech" to ::clockIsNotSpeech,
+ "aiFinalNotesKeepRetryingForAboutAMinute" to ::finalNotesRetry,
)
private fun check(ok: Boolean, what: String) { if (!ok) throw AssertionError(what) }
@@ -273,6 +274,14 @@ object ProviderTests {
equal(null, ListenEngine.problem(LingException(LingException.Kind.Http, 400), "Ling").first, "Ling's 400 is not the model")
}
+ fun finalNotesRetry() {
+ check(LingClient.retryWaits(Priority.Translate).isEmpty(), "translation fails fast")
+ equal(listOf(1.0), LingClient.retryWaits(Priority.Translate, audio = true), "heard audio retries once")
+ equal(listOf(1.0, 2.0, 4.0), LingClient.retryWaits(Priority.Notes), "live notes as before")
+ val sum = LingClient.retryWaits(Priority.Notes, patient = true).sum()
+ check(sum in 50.0..70.0, "final notes wait about a minute ($sum s)")
+ }
+
fun clockIsNotSpeech() {
for (madeUp in listOf("00:00", "00:00.", "1:02:03")) check(Translator.isNoise(madeUp, 1.2), "noise: $madeUp")
for (said in listOf("Hello.", "3 点", "15%", "好的")) check(!Translator.isNoise(said, 1.2), "kept: $said")
diff --git a/android/core/src/main/kotlin/cicada/Ling.kt b/android/core/src/main/kotlin/cicada/Ling.kt
index e361d81..ae2a29e 100644
--- a/android/core/src/main/kotlin/cicada/Ling.kt
+++ b/android/core/src/main/kotlin/cicada/Ling.kt
@@ -150,6 +150,17 @@ class LingClient(
val BASE = Providers.LING.base!!
val DEFAULT_MODEL = Providers.LING.textModels[0].id
val AUDIO_MODEL = Providers.LING.hearModels[0].id
+
+ /// Seconds before each retry of a 429 (Ling.swift › retryWaits). Notes retry a few times, heard
+ /// audio once; the rest fail fast so the caller can fall back. `patient` (the final notes) keeps
+ /// at it for about a minute: a model limited upstream (OpenRouter's Ling 3.1 by DeepInfra,
+ /// 2026-11) came back after ~15 s, and a meeting left without its notes is worse than notes a
+ /// little late.
+ fun retryWaits(priority: Priority, audio: Boolean = false, patient: Boolean = false): List<Double> = when {
+ priority == Priority.Notes -> if (patient) listOf(1.0, 2.0, 4.0, 8.0, 16.0, 30.0) else listOf(1.0, 2.0, 4.0)
+ audio -> listOf(1.0)
+ else -> emptyList()
+ }
/// Ming, Gemini TTS and Kokoro all speak 24 kHz mono 16-bit.
const val TTS_RATE = 24000
// Search essays (Ling.swift), and the canned refusal some audio prompts get.
@@ -300,11 +311,11 @@ class LingClient(
/// One chat completion. `content` goes in the system message, `instruction` is the fixed user
/// message, `audio` (of `audioType`) goes before it for the hear model. Notes retry 429s with
/// backoff; heard audio gets one retry (a lost reply loses the words); the rest fail fast so
- /// the caller can fall back.
+ /// the caller can fall back. `patient` (the final notes) keeps retrying for about a minute (retryWaits).
fun chat(
content: String, instruction: String, priority: Priority, json: Boolean = false,
maxTokens: Int = 1024, timeout: Double = 30.0, model: String? = null, audio: ByteArray? = null,
- audioType: String = "audio/wav",
+ audioType: String = "audio/wav", patient: Boolean = false,
): String {
val k = currentKey() ?: throw LingException(LingException.Kind.NoKey)
if (keyState == KeyState.Invalid) throw LingException(LingException.Kind.InvalidKey)
@@ -321,8 +332,7 @@ class LingClient(
if (json) body["response_format"] = mapOf("type" to "json_object")
val payload = Json.write(body, pretty = false)
- val attempts = if (priority == Priority.Notes) 4 else if (audio != null) 2 else 1
- var delay = 1.0
+ val waits = retryWaits(priority, audio != null, patient)
var attempt = 1
while (true) {
acquire(priority, c.provider.spacing)
@@ -344,11 +354,10 @@ class LingClient(
return trimmed
} catch (e: LingException) {
if (e.kind != LingException.Kind.RateLimited) throw e
- if (attempt >= attempts) { rateLimitedAt = System.currentTimeMillis(); changed(); throw e }
- val wait = delay + Math.random() * 0.5
+ if (attempt > waits.size) { rateLimitedAt = System.currentTimeMillis(); changed(); throw e }
+ val wait = waits[attempt - 1] + Math.random() * 0.5
Log.d("ling: $priority 429, retry in ${"%.1f".format(wait)} s")
Thread.sleep((wait * 1000).toLong())
- delay *= 2
attempt++
}
}
diff --git a/android/core/src/main/kotlin/cicada/Notes.kt b/android/core/src/main/kotlin/cicada/Notes.kt
index f17ba2b..b25cbff 100644
--- a/android/core/src/main/kotlin/cicada/Notes.kt
+++ b/android/core/src/main/kotlin/cicada/Notes.kt
@@ -116,7 +116,7 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
val prompt = prompt(base, lines, from, lang, final)
var next: MeetingNotes? = null
for (attempt in 1..(if (final) 2 else 1)) {
- val raw = ling.chat(prompt, "Update the notes. Write them in $lang.", Priority.Notes, json = true, maxTokens = 6000, timeout = 90.0)
+ val raw = ling.chat(prompt, "Update the notes. Write them in $lang.", Priority.Notes, json = true, maxTokens = 6000, timeout = 90.0, patient = final)
val parsed = parse(raw, lines.map { it.t }, lines.firstOrNull()?.t ?: 0.0) ?: break
if (written(parsed, lang)) { next = parsed; break }
Log.d("notes: ${if (final) "final" else "live"} reply not in $lang (attempt $attempt), dropped")
diff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.py
index a61463d..9873e00 100644
--- a/linux/cicada/core/ling.py
+++ b/linux/cicada/core/ling.py
@@ -347,11 +347,11 @@ class LingClient:
self._changed()
def chat(self, content: str, instruction: str, priority: int, json: bool = False, max_tokens: int = 1024,
- timeout: float = 30.0, model: str | None = None, audio: bytes | None = None) -> str:
+ timeout: float = 30.0, model: str | None = None, audio: bytes | None = None, patient: bool = False) -> str:
"""One chat completion. `content` goes in the system message, `instruction` is the fixed user
message, `audio` (a WAV) goes before it for the hear model. Notes retry 429s with backoff;
heard audio gets one retry (a lost reply loses the words); the rest fail fast so the caller
- can fall back."""
+ can fall back. `patient` (the final notes) keeps retrying for about a minute (retry_waits)."""
k = self.current_key()
if k is None:
raise LingError(LingError.NO_KEY)
@@ -369,8 +369,7 @@ class LingClient:
if json:
body["response_format"] = {"type": "json_object"}
payload = jsonfmt.write(body, pretty=False)
- attempts = 4 if priority == NOTES else 2 if audio is not None else 1
- delay = 1.0
+ waits = retry_waits(priority, audio is not None, patient)
attempt = 1
name = PRIORITY_NAMES[priority]
while True:
@@ -399,14 +398,13 @@ class LingClient:
except LingError as e:
if e.kind != LingError.RATE_LIMITED:
raise
- if attempt >= attempts:
+ if attempt > len(waits):
self.rate_limited_at = time.time()
self._changed()
raise
- wait = delay + random.random() * 0.5
+ wait = waits[attempt - 1] + random.random() * 0.5
Log.d("ling: %s 429, retry in %.1f s" % (name, wait))
time.sleep(wait)
- delay *= 2
attempt += 1
def speech(self, text: str, voice: str | None = "UK_Charlotte", language: str | None = None, timeout: float = 20.0):
@@ -525,6 +523,16 @@ class LingClient:
raise
+def retry_waits(priority: int, audio: bool = False, patient: bool = False) -> list:
+ """Seconds before each retry of a 429 (Ling.swift › retryWaits). Notes retry a few times, heard
+ audio once; the rest fail fast so the caller can fall back. `patient` (the final notes) keeps at
+ it for about a minute: a model limited upstream (OpenRouter's Ling 3.1 by DeepInfra, 2026-11)
+ came back after ~15 s, and a meeting left without its notes is worse than notes a little late."""
+ if priority == NOTES:
+ return [1, 2, 4, 8, 16, 30] if patient else [1, 2, 4]
+ return [1] if audio else []
+
+
def _b64(s: str) -> bytes:
import base64
return base64.b64decode(s)
diff --git a/linux/cicada/core/notes.py b/linux/cicada/core/notes.py
index b70974e..6d1d0e8 100644
--- a/linux/cicada/core/notes.py
+++ b/linux/cicada/core/notes.py
@@ -150,7 +150,8 @@ class NotesEngine:
p = prompt(base, lines, frm, lang, final, shown, self.voices())
nxt = None
for attempt in range(1, 3 if final else 2):
- raw = self.ling.chat(p, "Update the notes. Write them in %s." % lang, NOTES, json=True, max_tokens=6000, timeout=90.0)
+ raw = self.ling.chat(p, "Update the notes. Write them in %s." % lang, NOTES, json=True, max_tokens=6000, timeout=90.0,
+ patient=final)
parsed = parse(raw, [l.t for l in lines], lines[0].t if lines else 0.0)
if parsed is None:
break
diff --git a/linux/tests/test_providers.py b/linux/tests/test_providers.py
index 9e76873..a2bfa6e 100644
--- a/linux/tests/test_providers.py
+++ b/linux/tests/test_providers.py
@@ -263,6 +263,13 @@ class Words(Base):
self.assertEqual(("network", "连不上 Ling"), problem(LingError(LingError.TIMEOUT), "Ling"))
self.assertIsNone(problem(LingError(LingError.HTTP, 400), "Ling")[0])
+ def test_final_notes_keep_retrying_for_about_a_minute(self):
+ from cicada.core.ling import NOTES, retry_waits
+ self.assertEqual([], retry_waits(TRANSLATE))
+ self.assertEqual([1], retry_waits(TRANSLATE, audio=True))
+ self.assertEqual([1, 2, 4], retry_waits(NOTES))
+ self.assertTrue(50 <= sum(retry_waits(NOTES, patient=True)) <= 70)
+
def test_a_clock_is_not_speech(self):
for made_up in ("00:00", "00:00.", "1:02:03"):
self.assertTrue(is_noise(made_up, 1.2), made_up)
diff --git a/windows/src/Cicada.Core/Ling.cs b/windows/src/Cicada.Core/Ling.cs
index 5bc6140..185d2ec 100644
--- a/windows/src/Cicada.Core/Ling.cs
+++ b/windows/src/Cicada.Core/Ling.cs
@@ -277,8 +277,10 @@ public sealed class LingClient
/// One chat completion. `content` goes in the system message, `instruction` is the fixed user
/// message, `audio` (a WAV) goes before it for the hear model. Notes retry 429s with backoff;
/// the rest fail fast so the caller can fall back. `model` defaults to the service's text model.
+ /// `patient` (the final notes) keeps retrying for about a minute (RetryWaits).
public async Task<string> Chat(string content, string instruction, Priority priority, bool json = false,
- int maxTokens = 1024, double timeout = 30, string? model = null, byte[]? audio = null, CancellationToken cancel = default)
+ int maxTokens = 1024, double timeout = 30, string? model = null, byte[]? audio = null, bool patient = false,
+ CancellationToken cancel = default)
{
var k = CurrentKey() ?? throw new LingException(LingException.Kind.NoKey);
if (KeyState == KeyState.Invalid) throw new LingException(LingException.Kind.InvalidKey);
@@ -299,10 +301,7 @@ public sealed class LingClient
var payload = body.ToJsonString();
var url = new Uri(new Uri(c.Base), "chat/completions");
- // Notes can wait; heard audio gets one retry, since on Windows a lost reply loses the words
- // (on the Mac recognition is local and only the translation is lost); the rest fail fast.
- int attempts = priority == Priority.Notes ? 4 : audio is not null ? 2 : 1;
- double delay = 1;
+ var waits = RetryWaits(priority, audio is not null, patient);
for (int attempt = 1; ; attempt++)
{
var queued = DateTime.UtcNow;
@@ -329,15 +328,22 @@ public sealed class LingClient
}
catch (LingException e) when (e.Failure == LingException.Kind.RateLimited)
{
- if (attempt >= attempts) { RateLimitedAt = DateTimeOffset.Now; Changed?.Invoke(); throw; }
- var wait = delay + Random.Shared.NextDouble() * 0.5;
+ if (attempt > waits.Length) { RateLimitedAt = DateTimeOffset.Now; Changed?.Invoke(); throw; }
+ var wait = waits[attempt - 1] + Random.Shared.NextDouble() * 0.5;
Log.Debug($"ling: {priority} 429, retry in {wait:F1} s");
await Task.Delay(TimeSpan.FromSeconds(wait), cancel);
- delay *= 2;
}
}
}
+ /// Seconds before each retry of a 429 (Ling.swift › retryWaits). Notes can wait; heard audio gets
+ /// one retry, since on Windows a lost reply loses the words (on the Mac recognition is local and
+ /// only the translation is lost); the rest fail fast. `patient` (the final notes) keeps at it for
+ /// about a minute: a model limited upstream (OpenRouter's Ling 3.1 by DeepInfra, 2026-11) came
+ /// back after ~15 s, and a meeting left without its notes is worse than notes a little late.
+ public static double[] RetryWaits(Priority priority, bool audio = false, bool patient = false) =>
+ priority == Priority.Notes ? (patient ? [1, 2, 4, 8, 16, 30] : [1, 2, 4]) : audio ? [1] : [];
+
/// The service's voice for `text`: raw 24 kHz mono 16-bit PCM, chunk by chunk as it arrives.
/// On Ling, `voice` is Ming's and `languageId` its `language_id`, needed for ja, ko, de, fr and
/// es (Ling.swift › speech); elsewhere the configured speech model, and a voice not in the
diff --git a/windows/src/Cicada.Core/Notes.cs b/windows/src/Cicada.Core/Notes.cs
index 9abfd9c..94d9061 100644
--- a/windows/src/Cicada.Core/Notes.cs
+++ b/windows/src/Cicada.Core/Notes.cs
@@ -119,7 +119,7 @@ public sealed class NotesEngine
MeetingNotes? next = null;
for (int attempt = 1; attempt <= (final ? 2 : 1); attempt++)
{
- var raw = await ling.Chat(prompt, $"Update the notes. Write them in {lang}.", Priority.Notes, json: true, maxTokens: 6000, timeout: 90);
+ var raw = await ling.Chat(prompt, $"Update the notes. Write them in {lang}.", Priority.Notes, json: true, maxTokens: 6000, timeout: 90, patient: final);
var parsed = Parse(raw, lines.Select(l => l.T).ToList(), lines.FirstOrDefault()?.T ?? 0);
if (parsed is null) break;
if (Written(parsed, lang)) { next = parsed; break; }
diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.cs
index fb4ee92..5a389b9 100644
--- a/windows/tests/Cicada.Tests/Program.cs
+++ b/windows/tests/Cicada.Tests/Program.cs
@@ -1298,6 +1298,15 @@ static class Tests
Check(!ListenEngine.Words(LingException.Kind.Http, 400, "Ling").Settings, "Ling's 400 is the network bar");
}
+ public static void FinalNotesKeepRetryingForAboutAMinute()
+ {
+ Check(LingClient.RetryWaits(Priority.Translate).Length == 0, "translation fails fast");
+ Check(LingClient.RetryWaits(Priority.Translate, audio: true).SequenceEqual(new double[] { 1 }), "heard audio retries once");
+ Check(LingClient.RetryWaits(Priority.Notes).SequenceEqual(new double[] { 1, 2, 4 }), "live notes as before");
+ var patient = LingClient.RetryWaits(Priority.Notes, patient: true).Sum();
+ Check(patient is >= 50 and <= 70, $"final notes wait about a minute ({patient} s)");
+ }
+
public static void AClockIsNotSpeech()
{
foreach (var madeUp in new[] { "00:00", "00:00.", "1:02:03" }) Check(Translator.IsNoise(madeUp, 1.2), madeUp);