Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(meetings): keep a plain-text transcript when recording again into its note (#2819)

Chad Piha130a0c46eaa3
diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsx
index 765caeb39..47bec7beb 100644
--- a/src/components/notes/PersonalNotesView.tsx
+++ b/src/components/notes/PersonalNotesView.tsx
@@ -23,7 +23,7 @@ import {
} from "../../stores/settingsStore";
import { cn } from "../lib/utils";
import logger from "../../utils/logger";
-import { parseTranscriptSegments } from "../../utils/parseTranscriptSegments";
+import { parseSeedSegments, parseTranscriptSegments } from "../../utils/parseTranscriptSegments";
import { isExplicitSpeakerCount, resolveExpectedSpeakerCount } from "../../utils/participants";
import {
buildLlmTranscript,
@@ -705,7 +705,7 @@ export default function PersonalNotesView({
useEffect(() => {
if (!meetingRecordingRequest || activeNoteId !== meetingRecordingRequest.noteId) return;
const note = activeNote?.id === meetingRecordingRequest.noteId ? activeNote : null;
- const seedSegments = note?.transcript ? parseTranscriptSegments(note.transcript) : [];
+ const seedSegments = parseSeedSegments(note?.transcript);
void handleMeetingRecordingRequest({
args: {
noteId: meetingRecordingRequest.noteId,
diff --git a/src/helpers/meetingTranscriptPersistence.ts b/src/helpers/meetingTranscriptPersistence.ts
index f60b19eca..ee4005055 100644
--- a/src/helpers/meetingTranscriptPersistence.ts
+++ b/src/helpers/meetingTranscriptPersistence.ts
@@ -9,15 +9,17 @@ import type { TranscriptSegment } from "../stores/meetingRecordingStore";
// The captured segments are final the moment the stop begins, and the note
// editor swaps to the stored transcript as soon as isRecording flips — so they
// are written before the main-side stop (which can take seconds) is awaited.
-// Only a segment-less recording waits for main's final transcript.
+// A recording with no new segments also saves main's final transcript.
export async function persistFinalTranscriptAroundStop<T>({
segments,
+ seedLength,
serializeSegments,
persist,
stop,
fallbackTranscript,
}: {
segments: TranscriptSegment[];
+ seedLength: number;
serializeSegments: (segments: TranscriptSegment[]) => string;
persist: (transcript: string) => Promise<void>;
stop: () => Promise<T>;
@@ -29,7 +31,8 @@ export async function persistFinalTranscriptAroundStop<T>({
if (segmentWrite) {
await segmentWrite;
- } else {
+ }
+ if (segments.length === seedLength) {
const fallback = fallbackTranscript();
if (fallback) await persist(fallback);
}
diff --git a/src/hooks/useCreateNote.ts b/src/hooks/useCreateNote.ts
index 762569d0a..1bb7c691e 100644
--- a/src/hooks/useCreateNote.ts
+++ b/src/hooks/useCreateNote.ts
@@ -9,7 +9,7 @@ import {
} from "../stores/noteStore";
import { startRecording, useMeetingRecordingStore } from "../stores/meetingRecordingStore";
import { useTranscriptionContextAllowed } from "./usePolicy";
-import { parseTranscriptSegments } from "../utils/parseTranscriptSegments";
+import { parseSeedSegments } from "../utils/parseTranscriptSegments";
import { isExplicitSpeakerCount, resolveExpectedSpeakerCount } from "../utils/participants";
import { isMeetingAutoEndEligible } from "../helpers/meetingRecordingSession";
@@ -19,7 +19,7 @@ export function startRecordingForNote(note: NoteItem | null): Promise<boolean> {
noteId: note?.id ?? null,
noteTitle: note?.title ?? null,
folderId: note?.folder_id ?? null,
- seedSegments: note?.transcript ? parseTranscriptSegments(note.transcript) : [],
+ seedSegments: parseSeedSegments(note?.transcript),
diarizationEnabled: note?.diarization_enabled == null ? null : note.diarization_enabled === 1,
expectedCount: resolveExpectedSpeakerCount(note),
expectedCountIsExplicit: isExplicitSpeakerCount(note?.expected_speaker_count),
diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.ts
index e03f42c16..19bbdcd85 100644
--- a/src/stores/meetingRecordingStore.ts
+++ b/src/stores/meetingRecordingStore.ts
@@ -38,7 +38,7 @@ import {
type TranscriptSpeakerLockSource,
type TranscriptSpeakerStatus,
} from "../utils/transcriptSpeakerState";
-import { parseTranscriptSegments } from "../utils/parseTranscriptSegments";
+import { parseSeedSegments } from "../utils/parseTranscriptSegments";
import {
mergeSessionDiarization,
resolveDiarizationTarget,
@@ -432,10 +432,14 @@ let segmentsRefValue: TranscriptSegment[] = [];
let sessionSeedLength = 0;
const seedLengthByDiarizationSession = new Map<
string,
- { noteId: number | null; seedLength: number }
+ { noteId: number | null; seedLength: number; fallbackTranscript: string }
>();
// The stopping session's seed, until its stop call returns and keys it above.
-let stoppingSeed: { noteId: number | null; seedLength: number } | null = null;
+let stoppingSeed: {
+ noteId: number | null;
+ seedLength: number;
+ fallbackTranscript: string;
+} | null = null;
let preparePromise: Promise<void> | null = null;
let ipcCleanups: Array<() => void> = [];
let speakerIdentifications: SpeakerIdentification[] = [];
@@ -1690,6 +1694,8 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRec
// that view is unmounted, and any view-scoped saver dies with it. (Delayed
// diarization results are persisted by the module-level listener below.)
const { recordingNoteId, segments: finalSegments } = useMeetingRecordingStore.getState();
+ const hasNewSegments = finalSegments.length > sessionSeedLength;
+ let stopTranscript = "";
const persistTranscript = async (transcript: string) => {
if (recordingNoteId == null) return;
try {
@@ -1705,13 +1711,22 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRec
const diarizationSessionId = await persistFinalTranscriptAroundStop({
segments: finalSegments,
+ seedLength: sessionSeedLength,
serializeSegments: serializeTranscriptSegments,
persist: persistTranscript,
- fallbackTranscript: () => useMeetingRecordingStore.getState().transcript,
+ fallbackTranscript: () =>
+ stopTranscript &&
+ (finalSegments.length === 0
+ ? stopTranscript
+ : serializeTranscriptSegments(useMeetingRecordingStore.getState().segments)),
stop: async () => {
// Set before cleanup's awaits: the final transcript write is already
// posted, so an earlier session's result can land from here on.
- const seed = { noteId: recordingNoteId, seedLength: sessionSeedLength };
+ const seed = {
+ noteId: recordingNoteId,
+ seedLength: sessionSeedLength,
+ fallbackTranscript: "",
+ };
stoppingSeed = seed;
await cleanup();
@@ -1728,7 +1743,21 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRec
});
}
if (result?.success && result.transcript) {
- useMeetingRecordingStore.setState({ transcript: result.transcript });
+ if (hasNewSegments) {
+ useMeetingRecordingStore.setState({ transcript: result.transcript });
+ } else {
+ stopTranscript = result.transcript;
+ seed.fallbackTranscript = result.transcript.trim();
+ const segments = [
+ ...useMeetingRecordingStore.getState().segments,
+ { id: "stop-plain", text: seed.fallbackTranscript, source: "system" as const },
+ ];
+ segmentsRefValue = segments;
+ useMeetingRecordingStore.setState({
+ segments,
+ transcript: buildTranscriptText(segments),
+ });
+ }
} else if (result?.error) {
reportMeetingError(result.error);
}
@@ -1851,9 +1880,8 @@ if (typeof window !== "undefined") {
}
// Read after the getNote await: a skipped diarization is sent before the
// stop call that records this session's seed length returns.
- const seedLength = data.sessionId
- ? (seedLengthByDiarizationSession.get(data.sessionId)?.seedLength ?? 0)
- : 0;
+ const seed = data.sessionId ? seedLengthByDiarizationSession.get(data.sessionId) : undefined;
+ const seedLength = seed?.seedLength ?? 0;
if (data.sessionId) seedLengthByDiarizationSession.delete(data.sessionId);
// No note means no safe base to merge into, and writing to a deleted one
// would resurrect its tombstone in the sidebar, cloud mirror, and vector
@@ -1864,9 +1892,7 @@ if (typeof window !== "undefined") {
}
const existing = selectBaseSegments({
- persistedSegments: persisted.transcript
- ? parseTranscriptSegments(persisted.transcript)
- : null,
+ persistedSegments: persisted.transcript ? parseSeedSegments(persisted.transcript) : null,
liveSegments,
recordingNoteId,
targetNoteId,
@@ -1874,12 +1900,13 @@ if (typeof window !== "undefined") {
const { segments: enriched, removedCount } = mergeSessionDiarization({
existing,
seedLength,
+ fallbackTranscript: seed?.fallbackTranscript,
segments: data.segments,
removedSegments: data.removedSegments,
});
- // A later session resumed from this note seeded the rows about to be
- // removed, so its seed ends that many rows earlier once this write lands.
+ // A later session seeded this session's rows, so move its boundary when
+ // removing rows or replacing a fallback with individual diarized rows.
// Only sessions whose final write is already posted count: one posted
// after this write puts the rows back.
const laterSeeds = [...seedLengthByDiarizationSession.values(), stoppingSeed].filter(
@@ -1898,6 +1925,30 @@ if (typeof window !== "undefined") {
throw error;
}
for (const pending of laterSeeds) pending.seedLength -= removedCount;
+
+ // The resumed recording must save the replacement too, or its next
+ // periodic/stop write would put the combined fallback back.
+ const current = useMeetingRecordingStore.getState();
+ if (
+ current.recordingNoteId === targetNoteId &&
+ sessionSeedLength > seedLength &&
+ seed?.fallbackTranscript &&
+ current.segments[seedLength]?.text === seed.fallbackTranscript
+ ) {
+ const merged = mergeSessionDiarization({
+ existing: current.segments,
+ seedLength,
+ fallbackTranscript: seed.fallbackTranscript,
+ segments: data.segments,
+ removedSegments: data.removedSegments,
+ });
+ sessionSeedLength -= merged.removedCount;
+ segmentsRefValue = merged.segments;
+ useMeetingRecordingStore.setState({
+ segments: merged.segments,
+ transcript: buildTranscriptText(merged.segments),
+ });
+ }
publish(enriched);
if (data.speakerEmbeddings) {
diff --git a/src/utils/diarizationCompletion.ts b/src/utils/diarizationCompletion.ts
index 6e767bba9..399cc501d 100644
--- a/src/utils/diarizationCompletion.ts
+++ b/src/utils/diarizationCompletion.ts
@@ -90,25 +90,34 @@ export function withoutRemovedSegments<
// Merges main's result into this session's rows only: the first `seedLength`
// rows are a resumed note's earlier sessions and stay as saved. `removedCount`
-// is how many of this session's rows were dropped.
+// is the net number of rows dropped, including replacement of stop-only text.
export function mergeSessionDiarization(params: {
existing: TranscriptSegment[];
seedLength: number;
+ fallbackTranscript?: string;
segments: Array<Omit<TranscriptSegment, "id"> & { id?: string }>;
removedSegments?: RemovedTranscriptSegment[];
}): { segments: TranscriptSegment[]; removedCount: number } {
- const { existing, seedLength, segments, removedSegments } = params;
+ const { existing, seedLength, fallbackTranscript, segments, removedSegments } = params;
const seededCount = Math.min(seedLength, existing.length);
const sessionRows = existing.slice(seededCount);
+ const incoming = segments.map((segment, index) => ({
+ ...segment,
+ id: segment.id || `diarized-${index}`,
+ }));
+ if (fallbackTranscript && sessionRows[0]?.text === fallbackTranscript) {
+ return {
+ segments: [
+ ...existing.slice(0, seededCount),
+ ...mergeTranscriptSegments([], incoming),
+ ...sessionRows.slice(1),
+ ],
+ removedCount: 1 - incoming.length,
+ };
+ }
const keptRows = withoutRemovedSegments(sessionRows, removedSegments);
return {
- segments: [
- ...existing.slice(0, seededCount),
- ...mergeTranscriptSegments(
- keptRows,
- segments.map((segment, index) => ({ ...segment, id: segment.id || `diarized-${index}` }))
- ),
- ],
+ segments: [...existing.slice(0, seededCount), ...mergeTranscriptSegments(keptRows, incoming)],
removedCount: sessionRows.length - keptRows.length,
};
}
diff --git a/src/utils/parseTranscriptSegments.ts b/src/utils/parseTranscriptSegments.ts
index fa833f5c5..53c13a561 100644
--- a/src/utils/parseTranscriptSegments.ts
+++ b/src/utils/parseTranscriptSegments.ts
@@ -38,3 +38,25 @@ export function parseTranscriptSegments(raw: string): TranscriptSegment[] {
return [];
}
}
+
+const isJsonArray = (raw: string): boolean => {
+ try {
+ return Array.isArray(JSON.parse(raw));
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Segments to seed a recording into a note with. Every save of that recording
+ * writes its segments over the stored transcript, so a plain-text one (v1.6.0–
+ * v1.6.5 meetings, or a recording with no segments) is carried as one segment.
+ * It has no timestamp or speaker: live speaker identification skips it, new
+ * finals sort after it, and export keeps rebasing on the new segments' times.
+ */
+export function parseSeedSegments(raw: string | null | undefined): TranscriptSegment[] {
+ const text = raw?.trim();
+ if (!text) return [];
+ if (isJsonArray(text)) return parseTranscriptSegments(text);
+ return [{ id: "stored-plain", text, source: "system" }];
+}
diff --git a/test/helpers/meetingTranscriptPersistence.test.js b/test/helpers/meetingTranscriptPersistence.test.js
index 51d66b98f..dede88d2a 100644
--- a/test/helpers/meetingTranscriptPersistence.test.js
+++ b/test/helpers/meetingTranscriptPersistence.test.js
@@ -16,6 +16,7 @@ test("captured segments are written before the stop is awaited", async () => {
const result = await persistFinalTranscriptAroundStop({
segments: [segment("a", "hello"), segment("b", "world")],
+ seedLength: 0,
serializeSegments: serialize,
persist: async (transcript) => {
events.push(`persist:${transcript}`);
@@ -40,6 +41,7 @@ test("a segment-less recording writes main's final transcript after the stop", a
await persistFinalTranscriptAroundStop({
segments: [],
+ seedLength: 0,
serializeSegments: () => {
throw new Error("must not serialize an empty segment list");
},
@@ -64,6 +66,7 @@ test("nothing is written when there are neither segments nor a fallback transcri
await persistFinalTranscriptAroundStop({
segments: [],
+ seedLength: 0,
serializeSegments: serialize,
persist: async () => {
persisted += 1;
@@ -85,6 +88,7 @@ test("the stop result is only returned once the early write has settled", async
const pending = persistFinalTranscriptAroundStop({
segments: [segment("a", "hello")],
+ seedLength: 0,
serializeSegments: serialize,
persist: () => write,
stop: async () => "stopped",
diff --git a/test/stores/meetingRecordingStoreDiarizationPublish.test.js b/test/stores/meetingRecordingStoreDiarizationPublish.test.js
index 971a01ddc..01a10eefc 100644
--- a/test/stores/meetingRecordingStoreDiarizationPublish.test.js
+++ b/test/stores/meetingRecordingStoreDiarizationPublish.test.js
@@ -21,6 +21,7 @@ function createElectronAPI({ stopDiarizationSessionId = null } = {}) {
segmentCallback: null,
updatedTranscripts: [],
stopDiarizationSessionId,
+ stopTranscript: "",
// Runs inside meetingTranscriptionStop, before its reply, like main's
// synchronous skip-diarization send.
onStop: null,
@@ -41,7 +42,11 @@ function createElectronAPI({ stopDiarizationSessionId = null } = {}) {
meetingTranscriptionSetSystemAudioAvailable: async () => ({ success: true }),
meetingTranscriptionStop: async () => {
state.onStop?.(state.stopDiarizationSessionId);
- return { success: true, diarizationSessionId: state.stopDiarizationSessionId };
+ return {
+ success: true,
+ diarizationSessionId: state.stopDiarizationSessionId,
+ transcript: state.stopTranscript,
+ };
},
meetingTranscriptionSend: () => {},
getNote: async (id) => notes.get(id) ?? null,
@@ -83,8 +88,10 @@ async function loadModules(t, api) {
cachePrefix: "openwhispr-meeting-diarization-publish-test-",
});
const store = await vite.ssrLoadModule("/stores/meetingRecordingStore.ts");
- const { parseTranscriptSegments } = await vite.ssrLoadModule("/utils/parseTranscriptSegments.ts");
- return { store, parseTranscriptSegments };
+ const { parseTranscriptSegments, parseSeedSegments } = await vite.ssrLoadModule(
+ "/utils/parseTranscriptSegments.ts"
+ );
+ return { store, parseTranscriptSegments, parseSeedSegments };
}
async function loadStore(t, api) {
@@ -379,3 +386,70 @@ test("a skipped diarization sent before stop returns still leaves the seeded row
assert.deepEqual(rowsOf(note)[0], ["Yeah.", 1.0, "Carol"]);
});
+
+for (const completionTiming of ["while recording", "during stop", "after stop"]) {
+ test(`a stop-only transcript is replaced once on a resumed session's earlier completion (${completionTiming})`, async (t) => {
+ const { api, state, notes } = createElectronAPI();
+ const { store, parseSeedSegments } = await loadModules(t, api);
+ const note = notes.get(NOTE_ID);
+ state.stopDiarizationSessionId = "diar-first";
+ state.stopTranscript = "First sentence. Second sentence.";
+ assert.equal(await store.startRecording(START_ARGS), true);
+ await store.stopRecording();
+
+ state.stopDiarizationSessionId = "diar-resumed";
+ state.stopTranscript = completionTiming === "during stop" ? "New session." : "";
+ assert.equal(
+ await store.startRecording({
+ ...START_ARGS,
+ seedSegments: parseSeedSegments(note.transcript),
+ }),
+ true
+ );
+ if (completionTiming !== "during stop") {
+ state.segmentCallback({
+ type: "final",
+ source: "system",
+ text: "New session.",
+ timestamp: 1760000100000,
+ });
+ }
+ const earlierCompletion = async () => {
+ state.diarizationCallback({
+ noteId: NOTE_ID,
+ sessionId: "diar-first",
+ segments: [
+ diarized("First sentence.", 1.0, "Carol"),
+ diarized("Second sentence.", 2.0, "Carol"),
+ ],
+ });
+ await settle();
+ };
+
+ if (completionTiming === "while recording") {
+ await earlierCompletion();
+ await store.persistLiveTranscript();
+ } else if (completionTiming === "during stop") {
+ const stop = api.meetingTranscriptionStop;
+ api.meetingTranscriptionStop = async () => {
+ await earlierCompletion();
+ return stop();
+ };
+ }
+ await store.stopRecording();
+ if (completionTiming === "after stop") await earlierCompletion();
+
+ state.diarizationCallback({
+ noteId: NOTE_ID,
+ sessionId: "diar-resumed",
+ segments: [diarized("New session.", 3.0, "Dave")],
+ });
+ await settle();
+
+ assert.deepEqual(rowsOf(note), [
+ ["First sentence.", 1.0, "Carol"],
+ ["Second sentence.", 2.0, "Carol"],
+ ["New session.", 3.0, "Dave"],
+ ]);
+ });
+}
diff --git a/test/stores/meetingRecordingStorePlainTranscriptResume.test.js b/test/stores/meetingRecordingStorePlainTranscriptResume.test.js
new file mode 100644
index 000000000..468657e6f
--- /dev/null
+++ b/test/stores/meetingRecordingStorePlainTranscriptResume.test.js
@@ -0,0 +1,184 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installMicCaptureGlobals,
+} = require("../lib/rendererTestHarness");
+
+// Some notes store their transcript as plain text rather than a JSON segment
+// array: meetings recorded on v1.6.0–v1.6.5, and recordings that captured no
+// segments (main's joined text is saved on stop). Recording again into such a
+// note seeds the session from that transcript; every save then writes the
+// session's segments over it, so the seed must carry the old text.
+
+const NOTE_ID = 21;
+const OLD_TRANSCRIPT = "We agreed to ship on Friday.\nDana owns the release notes.";
+
+function createElectronAPI() {
+ const noopListener = () => () => {};
+ const listeners = {};
+ const capture = (name) => (callback) => {
+ listeners[name] = callback;
+ return () => {
+ if (listeners[name] === callback) listeners[name] = null;
+ };
+ };
+ const writes = [];
+ const api = {
+ checkSystemAudioAccess: async () => ({
+ granted: true,
+ status: "granted",
+ mode: "native",
+ strategy: "native",
+ }),
+ meetingTranscriptionStart: async () => ({
+ success: true,
+ systemAudioMode: "native",
+ systemAudioStrategy: "native",
+ }),
+ meetingTranscriptionSetSystemAudioAvailable: async () => ({ success: true }),
+ meetingTranscriptionStop: async () => ({ success: true, transcript: "joined by main" }),
+ meetingTranscriptionSend: () => {},
+ getNote: async () => null,
+ updateNote: async (id, patch) => {
+ writes.push([id, patch]);
+ return { success: true };
+ },
+ onMeetingTranscriptionSegment: capture("segment"),
+ onNoteDeleted: noopListener,
+ onNoteSynced: noopListener,
+ onMeetingSpeakerIdentified: noopListener,
+ onMeetingSpeakersMerged: noopListener,
+ onMeetingSessionSpeakerConfigUpdated: noopListener,
+ onMeetingTranscriptionError: noopListener,
+ onMeetingTranscriptionFatalError: noopListener,
+ onMeetingSystemAudioSilent: noopListener,
+ onMeetingDiarizationComplete: capture("diarization"),
+ };
+ return { api, listeners, writes };
+}
+
+async function load(t, api) {
+ installMicCaptureGlobals(t);
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: api,
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ },
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-meeting-plain-transcript-resume-test-",
+ });
+ const store = await vite.ssrLoadModule("/stores/meetingRecordingStore.ts");
+ const { startRecordingForNote } = await vite.ssrLoadModule("/hooks/useCreateNote.ts");
+ const { parseTranscriptSegments, parseSeedSegments } = await vite.ssrLoadModule(
+ "/utils/parseTranscriptSegments.ts"
+ );
+ return { store, startRecordingForNote, parseTranscriptSegments, parseSeedSegments };
+}
+
+const note = (transcript) => ({
+ id: NOTE_ID,
+ title: "Planning",
+ folder_id: null,
+ transcript,
+ diarization_enabled: null,
+ expected_speaker_count: null,
+});
+
+const final = (text) => ({ text, source: "mic", type: "final", timestamp: Date.now() });
+
+const transcriptWrites = (writes) =>
+ writes.filter(([, patch]) => typeof patch.transcript === "string").map(([, patch]) => patch);
+
+test("recording again into a plain-text transcript keeps the old text", async (t) => {
+ const { api, listeners, writes } = createElectronAPI();
+ const { store, startRecordingForNote, parseTranscriptSegments } = await load(t, api);
+
+ assert.equal(await startRecordingForNote(note(OLD_TRANSCRIPT)), true);
+ listeners.segment(final("Picking up where we left off."));
+
+ await store.persistLiveTranscript();
+ await store.stopRecording();
+
+ const saved = transcriptWrites(writes);
+ assert.equal(saved.length, 2, "the 30-second save and the stop each write once");
+ for (const { transcript } of saved) {
+ const segments = parseTranscriptSegments(transcript);
+ assert.deepEqual(
+ segments.map((segment) => segment.text),
+ [OLD_TRANSCRIPT, "Picking up where we left off."],
+ "the old transcript comes first, then the new session"
+ );
+ // No timestamp: it keeps the old text out of live speaker identification
+ // and off the export's epoch rebase, and sorts it ahead of new finals.
+ assert.equal(segments[0].timestamp, undefined);
+ assert.equal(segments[0].speaker, undefined);
+ }
+});
+
+test("a resumed plain-text note with no new segments keeps the old text", async (t) => {
+ const { api, writes } = createElectronAPI();
+ api.meetingTranscriptionStop = async () => ({ success: true, transcript: "" });
+ const { store, startRecordingForNote, parseTranscriptSegments } = await load(t, api);
+
+ assert.equal(await startRecordingForNote(note(OLD_TRANSCRIPT)), true);
+ await store.stopRecording();
+
+ const saved = transcriptWrites(writes);
+ assert.equal(saved.length, 1);
+ assert.deepEqual(
+ parseTranscriptSegments(saved[0].transcript).map((segment) => segment.text),
+ [OLD_TRANSCRIPT]
+ );
+});
+
+test("a resumed note keeps old text and main's stop-only text after an empty completion", async (t) => {
+ const { api, listeners, writes } = createElectronAPI();
+ const fallback = "New text returned only at stop.";
+ api.meetingTranscriptionStop = async () => ({
+ success: true,
+ transcript: fallback,
+ diarizationSessionId: "diar-stop-only",
+ });
+ const { store, startRecordingForNote, parseTranscriptSegments } = await load(t, api);
+
+ assert.equal(await startRecordingForNote(note(OLD_TRANSCRIPT)), true);
+ await store.stopRecording();
+ listeners.diarization({ noteId: NOTE_ID, sessionId: "diar-stop-only", segments: [] });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ assert.deepEqual(
+ parseTranscriptSegments(transcriptWrites(writes).at(-1).transcript).map(({ text }) => text),
+ [OLD_TRANSCRIPT, fallback]
+ );
+});
+
+test("seed segments come from a note's stored transcript", async (t) => {
+ const { api } = createElectronAPI();
+ const { parseSeedSegments } = await load(t, api);
+
+ assert.deepEqual(parseSeedSegments(null), []);
+ assert.deepEqual(parseSeedSegments(""), []);
+ assert.deepEqual(parseSeedSegments(" \n "), []);
+ assert.deepEqual(parseSeedSegments("[]"), [], "an empty segment array has nothing to keep");
+
+ const stored = JSON.stringify([{ text: "hi", source: "mic", timestamp: 5 }]);
+ assert.deepEqual(
+ parseSeedSegments(stored).map(({ text, source, timestamp }) => ({ text, source, timestamp })),
+ [{ text: "hi", source: "mic", timestamp: 5 }]
+ );
+
+ // Plain text can open with a bracket ("[Music] …"), which isn't JSON.
+ for (const plain of [OLD_TRANSCRIPT, "[Music] and then we started"]) {
+ const [legacy, ...rest] = parseSeedSegments(` ${plain}\n`);
+ assert.equal(rest.length, 0);
+ assert.equal(legacy.text, plain);
+ assert.equal(legacy.source, "system");
+ assert.equal(legacy.timestamp, undefined);
+ assert.ok(legacy.id);
+ }
+});