Skip to content

Build your personal knowledge base with Trilium Notes

feat(attachments): rename the speakers of a transcript

Elian Doranca54657927b3
diff --git a/.claude/skills/working-with-transcription/SKILL.md b/.claude/skills/working-with-transcription/SKILL.md
index 0ec68b0ae1..0d13740d14 100644
--- a/.claude/skills/working-with-transcription/SKILL.md
+++ b/.claude/skills/working-with-transcription/SKILL.md
@@ -33,7 +33,8 @@ capture window (hidden, offscreen) main process
| `…/attachment_sink.ts` | The `transcript` attachment, rewritten after every utterance |
| `…/audio_recorder.ts` | Development recordings: `WavRecorder`, `TranscriptFileSink`, `getRecordingDirectory()` |
| `…/index.ts` | IPC handlers, the state broadcast, which sinks and taps a recording gets |
-| `packages/commons/src/lib/transcript.ts` | The `Transcript` format (`version: 1`, `startedAt`, `utterances`) |
+| `packages/commons/src/lib/transcript.ts` | The `Transcript` format (`version: 1`, `startedAt`, `speakers`, `utterances`), `parseTranscript()`, speaker keys and `setSpeakerName()` |
+| Speaker names | `TranscriptView` reads the stored transcript, applies `setSpeakerName()` and saves it whole through the generic `POST notes/:noteId/attachments?matchBy=attachmentId`. `AttachmentSink` re-reads `speakers` before each rewrite, so a rename during a recording survives, and an utterance a rename overwrote comes back with the next write |
| `apps/client/src/widgets/type_widgets/transcript/TranscriptView.tsx` | Turns, clock times, the "Speaking…" line, fade-in |
| `apps/client/src/widgets/launch_bar/RecordMeetingButton.tsx` | The launcher and `useTranscriptionState()` |
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index d5ca354453..c06c267564 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4589,6 +4589,7 @@
"speaker_me": "Me",
"speaker_others": "Others",
"speaker_numbered": "Speaker {{number}}",
+ "speaker_name": "Speaker name",
"empty": "Nothing has been transcribed yet.",
"unreadable": "This transcript cannot be read.",
"speaking": "Speaking…",
diff --git a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.css b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.css
index fee1b36f11..0ea438cc73 100644
--- a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.css
+++ b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.css
@@ -21,6 +21,21 @@
font-weight: 600;
}
+ a.transcript-speaker {
+ text-decoration: none;
+
+ &:hover,
+ &:focus-visible {
+ text-decoration: underline;
+ }
+ }
+
+ .transcript-speaker-editor {
+ width: 16em;
+ padding-block: 0;
+ font-weight: 600;
+ }
+
.transcript-microphone .transcript-speaker {
color: var(--main-text-color);
}
diff --git a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.spec.tsx b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.spec.tsx
index 9dc129ef1f..21a660c479 100644
--- a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.spec.tsx
@@ -11,16 +11,21 @@ import LoadResults from "../../../services/load_results";
import { renderInto } from "../../../test/render";
import { ParentComponent } from "../../react/react_utils";
import TranscriptView, {
- formatOffset, groupIntoTurns, parseTranscript, type TranscriptTurn
+ formatOffset, groupIntoTurns, type TranscriptTurn
} from "./TranscriptView";
+const h = vi.hoisted(() => ({ post: vi.fn() }));
vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+// keyboard_actions asks the server for its shortcuts at import.
+vi.mock("../../../services/server", () => ({ default: { post: h.post, get: async () => [] } }));
/** Local time, so that the clock times the spec expects hold in every time zone. */
const STARTED_AT = "2026-10-13T14:29:55";
-function transcript(utterances: TranscriptUtterance[], startedAt = STARTED_AT) {
- const content: Transcript = { version: 1, startedAt, utterances };
+function transcript(
+ utterances: TranscriptUtterance[], startedAt = STARTED_AT, speakers?: Record<string, string>
+) {
+ const content: Transcript = { version: 1, startedAt, speakers, utterances };
return JSON.stringify(content);
}
@@ -29,14 +34,6 @@ function paragraphTexts(turn: TranscriptTurn) {
}
describe("transcript helpers", () => {
- it("reads only version 1 transcripts", () => {
- expect(parseTranscript(transcript([]))?.utterances).toEqual([]);
- expect(parseTranscript(null)).toBeNull();
- expect(parseTranscript("not json")).toBeNull();
- expect(parseTranscript(JSON.stringify({ version: 2, utterances: [] }))).toBeNull();
- expect(parseTranscript(JSON.stringify({ version: 1 }))).toBeNull();
- });
-
it("joins consecutive utterances of one source into a turn timed by its first", () => {
const turns = groupIntoTurns([
{ source: "microphone", offsetMs: 1000, text: "Hello." },
@@ -71,6 +68,21 @@ describe("transcript helpers", () => {
]);
});
+ it("treats speakers given the same name as one", () => {
+ const utterances: TranscriptUtterance[] = [
+ { source: "system", offsetMs: 0, speaker: 1, text: "Hello." },
+ { source: "system", offsetMs: 1000, speaker: 3, text: "It is me again." },
+ { source: "system", offsetMs: 2000, speaker: 2, text: "Hi." }
+ ];
+ expect(groupIntoTurns(utterances).map(paragraphTexts)).toEqual([
+ [ "Hello." ], [ "It is me again." ], [ "Hi." ]
+ ]);
+ const named = { "system:1": "Alexandra", "system:3": "Alexandra", "system:2": "Bob" };
+ expect(groupIntoTurns(utterances, named).map(paragraphTexts)).toEqual([
+ [ "Hello. It is me again." ], [ "Hi." ]
+ ]);
+ });
+
it("starts a new paragraph within a turn after a long pause", () => {
const turns = groupIntoTurns([
{ source: "system", offsetMs: 0, durationMs: 8000, text: "First point," },
@@ -185,6 +197,90 @@ describe("TranscriptView", () => {
expect(offset && Tooltip.getInstance(offset)).toBeNull();
});
+ it("renames a speaker in place, and only identified speakers", async () => {
+ const utterances: TranscriptUtterance[] = [
+ { source: "system", offsetMs: 0, speaker: 1, text: "Hi." },
+ { source: "microphone", offsetMs: 2000, text: "Hello." },
+ { source: "system", offsetMs: 4000, text: "Yes." }
+ ];
+ let stored = transcript(utterances, STARTED_AT, { microphone: "Elian" });
+ const attachment = {
+ attachmentId: "transcript1", ownerId: "meeting", role: "transcript",
+ mime: "application/json", title: "Transcript",
+ getBlob: async () => ({ content: stored })
+ };
+ const container = renderInto(
+ <ParentComponent.Provider value={new Component()}>
+ <TranscriptView attachment={attachment as unknown as FAttachment} />
+ </ParentComponent.Provider>
+ );
+ const names = () => [ ...container.querySelectorAll(".transcript-speaker") ];
+ await vi.waitFor(() => expect(names()).toHaveLength(3));
+ expect(names().map((name) => [ name.tagName, name.textContent ])).toEqual([
+ [ "A", "transcript.speaker_numbered" ], [ "A", "Elian" ],
+ [ "SPAN", "transcript.speaker_others" ]
+ ]);
+
+ const edit = async (index: number) => {
+ await act(async () => (names()[index] as HTMLElement).click());
+ const input = container.querySelector<HTMLInputElement>(".transcript-speaker-editor");
+ if (!input) {
+ throw new Error("no editor");
+ }
+ return input;
+ };
+ const type = (input: HTMLInputElement, value: string) => act(() => {
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ const press = (input: HTMLInputElement, key: string) => act(() => {
+ input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));
+ });
+
+ const saved = (index: number) => {
+ const [ url, { content, ...rest } ] = h.post.mock.calls[index];
+ return { url, ...rest, ...JSON.parse(content) };
+ };
+
+ // The recording writes another utterance after the transcript was shown.
+ const welcome: TranscriptUtterance = { source: "system", offsetMs: 6000, text: "Welcome." };
+ stored = transcript([ ...utterances, welcome ], STARTED_AT, { microphone: "Elian" });
+ const first = await edit(0);
+ expect(first.value).toBe("transcript.speaker_numbered");
+ type(first, " Alexandra ");
+ // The field can lose focus while Enter takes it down; that must not save a second time.
+ expect(document.activeElement).toBe(first);
+ act(() => {
+ first.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ first.blur();
+ });
+ expect(container.querySelector(".transcript-speaker-editor")).toBeNull();
+ await vi.waitFor(() => expect(h.post).toHaveBeenCalledOnce());
+ expect(saved(0)).toEqual({
+ url: "notes/meeting/attachments?matchBy=attachmentId",
+ attachmentId: "transcript1", role: "transcript", mime: "application/json",
+ title: "Transcript", version: 1, startedAt: STARTED_AT,
+ speakers: { microphone: "Elian", "system:1": "Alexandra" },
+ utterances: [ ...utterances, welcome ]
+ });
+
+ const me = await edit(1);
+ expect(me.value).toBe("Elian");
+ type(me, " ");
+ act(() => me.blur());
+ await vi.waitFor(() => expect(h.post).toHaveBeenCalledTimes(2));
+ expect(saved(1).speakers).toEqual({});
+
+ const cancelled = await edit(0);
+ type(cancelled, "Bob");
+ press(cancelled, "Escape");
+ const unchanged = await edit(0);
+ type(unchanged, "transcript.speaker_numbered");
+ press(unchanged, "Enter");
+ await new Promise((resolve) => setTimeout(resolve));
+ expect(h.post).toHaveBeenCalledTimes(2);
+ });
+
it("shows who is speaking in the recorded meeting, before the words arrive", async () => {
let onStateChanged: (state: TranscriptionState) => void = () => {};
const recording = (noteId: string, pendingSources: TranscriptSource[]) =>
diff --git a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.tsx b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.tsx
index 8bfa312881..30e3c5364e 100644
--- a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.tsx
+++ b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.tsx
@@ -1,15 +1,25 @@
import "./TranscriptView.css";
-import type { Transcript, TranscriptSource, TranscriptUtterance } from "@triliumnext/commons";
+import {
+ getSpeakerKey, MAX_SPEAKER_NAME_LENGTH, parseTranscript, setSpeakerName,
+ type TranscriptSource, type TranscriptUtterance
+} from "@triliumnext/commons";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import type FAttachment from "../../../entities/fattachment";
import { t } from "../../../services/i18n";
+import server from "../../../services/server";
+import { isIMEComposing } from "../../../services/shortcuts";
import utils from "../../../services/utils";
import { useTranscriptionState } from "../../launch_bar/RecordMeetingButton";
+import FormTextBox from "../../react/FormTextBox";
import { useStaticTooltip, useTriliumEvent } from "../../react/hooks";
+import LinkButton from "../../react/LinkButton";
import NoItems from "../../react/NoItems";
+/** Names given to speakers, by {@link getSpeakerKey}. */
+type SpeakerNames = Record<string, string>;
+
/** How close to the end, in pixels, still counts as reading the newest turn. */
const FOLLOW_THRESHOLD = 16;
@@ -76,7 +86,8 @@ export default function TranscriptView({ attachment }: { attachment: FAttachment
initialCountRef.current ??= transcript.utterances.length;
const arrived = new Set(transcript.utterances.slice(initialCountRef.current));
- const turns = groupIntoTurns(transcript.utterances);
+ const names = transcript.speakers ?? {};
+ const turns = groupIntoTurns(transcript.utterances, names);
const lastTurn = turns.at(-1);
const speaking = (
<p className="transcript-speaking">
@@ -89,7 +100,12 @@ export default function TranscriptView({ attachment }: { attachment: FAttachment
{turns.map((turn) => (
<div key={turn.offsetMs} className={`transcript-turn transcript-${turn.source}`}>
<div className="transcript-turn-header">
- <span className="transcript-speaker">{speakerName(turn.source, turn.speaker)}</span>
+ <SpeakerName
+ speakerKey={getSpeakerKey(turn.source, turn.speaker)}
+ name={speakerName(turn.source, turn.speaker, names)}
+ defaultName={speakerName(turn.source, turn.speaker)}
+ onRename={(key, name) => renameSpeaker(attachment, key, name)}
+ />
<TurnTime startedAt={transcript.startedAt} offsetMs={turn.offsetMs} />
</div>
{turn.paragraphs.map((paragraph, index) => (
@@ -110,7 +126,9 @@ export default function TranscriptView({ attachment }: { attachment: FAttachment
{pending.filter((source) => source !== lastTurn?.source).map((source) => (
<div key={`pending-${source}`} className={`transcript-turn transcript-${source}`}>
<div className="transcript-turn-header">
- <span className="transcript-speaker">{speakerName(source)}</span>
+ <span className="transcript-speaker">
+ {speakerName(source, undefined, names)}
+ </span>
</div>
{speaking}
</div>
@@ -119,6 +137,91 @@ export default function TranscriptView({ attachment }: { attachment: FAttachment
);
}
+/**
+ * A speaker's name, which a click turns into a field that renames every turn of the speaker: Enter
+ * or leaving the field saves, Escape cancels, and a blank name or the default restores the default.
+ * Speech no speaker was found for, which has no key, cannot be renamed.
+ */
+function SpeakerName({ speakerKey, name, defaultName, onRename }: {
+ speakerKey: string | null;
+ name: string;
+ defaultName: string;
+ onRename: (key: string, name: string) => void;
+}) {
+ const [ typed, setTyped ] = useState<string | null>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
+ /** Set once the field closes, since removing it can fire its blur after Enter or Escape. */
+ const closedRef = useRef(false);
+ const isEditing = typed !== null;
+
+ useEffect(() => {
+ if (isEditing) {
+ inputRef.current?.select();
+ }
+ }, [ isEditing ]);
+
+ if (!speakerKey) {
+ return <span className="transcript-speaker">{name}</span>;
+ }
+ if (!isEditing) {
+ const open = () => {
+ closedRef.current = false;
+ setTyped(name);
+ };
+ return <LinkButton className="transcript-speaker" text={name} onClick={open} />;
+ }
+
+ const close = (save: boolean) => {
+ if (closedRef.current) {
+ return;
+ }
+ closedRef.current = true;
+ const trimmed = typed.trim();
+ setTyped(null);
+ if (save && trimmed !== name) {
+ onRename(speakerKey, trimmed === defaultName ? "" : trimmed);
+ }
+ };
+ return (
+ <FormTextBox
+ inputRef={inputRef}
+ className="transcript-speaker-editor"
+ autoFocus
+ maxLength={MAX_SPEAKER_NAME_LENGTH}
+ aria-label={t("transcript.speaker_name")}
+ currentValue={typed}
+ onChange={setTyped}
+ onBlur={() => close(true)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !isIMEComposing(e)) {
+ e.preventDefault();
+ close(true);
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ close(false);
+ }
+ }}
+ />
+ );
+}
+
+/**
+ * Names a speaker in the transcript as it is stored now, rather than as last shown: a running
+ * recording can have written utterances since. One written in the moment between this read and
+ * the save is restored by the recording's next write, which rewrites every utterance it holds.
+ */
+async function renameSpeaker(attachment: FAttachment, key: string, name: string) {
+ const latest = parseTranscript((await attachment.getBlob())?.content);
+ if (!latest) {
+ return;
+ }
+ const { attachmentId, ownerId, role, mime, title } = attachment;
+ await server.post(`notes/${ownerId}/attachments?matchBy=attachmentId`, {
+ attachmentId, role, mime, title,
+ content: JSON.stringify(setSpeakerName(latest, key, name), null, 2)
+ });
+}
+
/**
* When a turn began, in local clock time, with its offset into the recording as the tooltip. Shows
* the offset alone when the transcript's `startedAt` cannot be read.
@@ -151,35 +254,27 @@ export interface TranscriptTurn {
paragraphs: TranscriptUtterance[][];
}
-/** Reads a transcript attachment's content, or returns `null` for content of another shape. */
-export function parseTranscript(content: string | null): Transcript | null {
- if (!content) {
- return null;
- }
-
- try {
- const parsed = JSON.parse(content) as Partial<Transcript>;
- const isTranscript = parsed.version === 1 && Array.isArray(parsed.utterances);
- return isTranscript ? parsed as Transcript : null;
- } catch {
- return null;
- }
-}
-
/**
* Joins each run of utterances from one source and speaker into a turn, timed by its first
- * utterance, and starts a new paragraph after a pause of {@link PARAGRAPH_PAUSE_MS} or more. An
- * utterance without a speaker continues the turn of its source, and an utterance without a
- * `durationMs` never starts a paragraph, since the pause before the next is unknown.
+ * utterance, and starts a new paragraph after a pause of {@link PARAGRAPH_PAUSE_MS} or more.
+ * Speakers given the same name count as one. An utterance without a speaker continues the turn of
+ * its source, and an utterance without a `durationMs` never starts a paragraph, since the pause
+ * before the next is unknown.
*/
-export function groupIntoTurns(utterances: TranscriptUtterance[]): TranscriptTurn[] {
+export function groupIntoTurns(
+ utterances: TranscriptUtterance[], names: SpeakerNames = {}
+): TranscriptTurn[] {
+ const identity = (source: TranscriptSource, speaker?: number) => {
+ const key = getSpeakerKey(source, speaker);
+ return key && names[key] ? `name:${names[key]}` : key;
+ };
const turns: TranscriptTurn[] = [];
let previousEndMs: number | null = null;
for (const utterance of utterances) {
const { source, speaker, offsetMs, durationMs } = utterance;
const last = turns.at(-1);
const isSameSpeaker = speaker === undefined || last?.speaker === undefined
- || last.speaker === speaker;
+ || identity(last.source, last.speaker) === identity(source, speaker);
if (last?.source !== source || !isSameSpeaker) {
turns.push({ source, speaker, offsetMs, paragraphs: [ [ utterance ] ] });
} else {
@@ -211,7 +306,12 @@ function wasAtEnd(scroller: HTMLElement, scrollHeight: number) {
return scrollHeight - scroller.scrollTop - scroller.clientHeight <= FOLLOW_THRESHOLD;
}
-function speakerName(source: TranscriptSource, speaker?: number) {
+/** The name of a speaker: the one given in `names`, else the default. */
+function speakerName(source: TranscriptSource, speaker?: number, names: SpeakerNames = {}) {
+ const key = getSpeakerKey(source, speaker);
+ if (key && names[key]) {
+ return names[key];
+ }
if (source === "microphone") {
return t("transcript.speaker_me");
}
diff --git a/apps/desktop/src/services/transcription/attachment_sink.spec.ts b/apps/desktop/src/services/transcription/attachment_sink.spec.ts
index 141e7c9c18..476334961d 100644
--- a/apps/desktop/src/services/transcription/attachment_sink.spec.ts
+++ b/apps/desktop/src/services/transcription/attachment_sink.spec.ts
@@ -4,14 +4,18 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const h = vi.hoisted(() => ({
saveAttachment: vi.fn(),
setContent: vi.fn(),
+ getContent: vi.fn(),
transactions: 0
}));
vi.mock("@triliumnext/core", () => ({
becca: {
getNoteOrThrow: (noteId: string) => ({ noteId, saveAttachment: h.saveAttachment }),
- getAttachmentOrThrow: (attachmentId: string) => ({ attachmentId, setContent: h.setContent })
+ getAttachmentOrThrow: (attachmentId: string) => ({
+ attachmentId, setContent: h.setContent, getContent: h.getContent
+ })
},
+ binary_utils: { decodeUtf8: (content: string) => content },
cls: { init: <T>(callback: () => T) => callback() },
getSql: () => ({
transactional: <T>(callback: () => T) => {
@@ -30,6 +34,7 @@ beforeEach(() => {
vi.clearAllMocks();
h.transactions = 0;
h.saveAttachment.mockReturnValue({ attachmentId: "transcript1" });
+ h.getContent.mockReturnValue("");
});
describe("AttachmentSink", () => {
@@ -63,6 +68,22 @@ describe("AttachmentSink", () => {
expect(h.transactions).toBe(3);
});
+ it("keeps the speaker names stored in the attachment, which a rename writes meanwhile", () => {
+ const sink = new AttachmentSink("meeting");
+ sink.open(STARTED_AT);
+ h.getContent.mockReturnValue(JSON.stringify({
+ version: 1,
+ startedAt: "2026-10-13T14:30:00.000Z",
+ speakers: { "system:1": "Alexandra" },
+ utterances: []
+ }));
+ sink.write({ source: "system", offsetMs: 3000, speaker: 1, text: "Yes." });
+
+ const written = JSON.parse(h.setContent.mock.calls[0][0]) as Transcript;
+ expect(written.speakers).toEqual({ "system:1": "Alexandra" });
+ expect(written.utterances).toHaveLength(1);
+ });
+
it("refuses to write before it is open", () => {
const sink = new AttachmentSink("meeting");
expect(() => sink.write({ source: "system", offsetMs: 0, text: "Hi" }))
diff --git a/apps/desktop/src/services/transcription/attachment_sink.ts b/apps/desktop/src/services/transcription/attachment_sink.ts
index 98ef507ac6..bb60dd41ef 100644
--- a/apps/desktop/src/services/transcription/attachment_sink.ts
+++ b/apps/desktop/src/services/transcription/attachment_sink.ts
@@ -1,12 +1,15 @@
-import { type Transcript, TRANSCRIPT_MIME, type TranscriptUtterance } from "@triliumnext/commons";
-import { becca, cls, getSql } from "@triliumnext/core";
+import {
+ parseTranscript, type Transcript, TRANSCRIPT_MIME, type TranscriptUtterance
+} from "@triliumnext/commons";
+import { becca, binary_utils, cls, getSql } from "@triliumnext/core";
import { t } from "i18next";
import type { TranscriptSink } from "./session";
/**
* Keeps the transcript in a `transcript` attachment of the meeting note, rewritten after every
- * utterance. Each write commits its own transaction, which sends the change to every open window.
+ * utterance. Each write commits its own transaction, which sends the change to every open window,
+ * and keeps the speaker names stored in the attachment, which the user can change meanwhile.
*/
export class AttachmentSink implements TranscriptSink {
private transcript: Transcript | null = null;
@@ -36,8 +39,12 @@ export class AttachmentSink implements TranscriptSink {
}
transcript.utterances.push(utterance);
- const content = serialize(transcript);
- inTransaction(() => becca.getAttachmentOrThrow(attachmentId).setContent(content));
+ inTransaction(() => {
+ const attachment = becca.getAttachmentOrThrow(attachmentId);
+ const stored = parseTranscript(binary_utils.decodeUtf8(attachment.getContent()));
+ transcript.speakers = stored?.speakers;
+ attachment.setContent(serialize(transcript));
+ });
}
}
diff --git a/packages/commons/src/lib/transcript.spec.ts b/packages/commons/src/lib/transcript.spec.ts
new file mode 100644
index 0000000000..bf975e04f9
--- /dev/null
+++ b/packages/commons/src/lib/transcript.spec.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ getSpeakerKey, MAX_SPEAKER_NAME_LENGTH, parseTranscript, setSpeakerName, type Transcript
+} from "./transcript.js";
+
+const TRANSCRIPT: Transcript = {
+ version: 1,
+ startedAt: "2026-10-14T09:30:00.000Z",
+ utterances: [ { source: "system", offsetMs: 0, speaker: 2, text: "Hi." } ]
+};
+
+describe("transcript", () => {
+ it("reads only version 1 transcripts", () => {
+ expect(parseTranscript(JSON.stringify(TRANSCRIPT))).toEqual(TRANSCRIPT);
+ expect(parseTranscript(null)).toBeNull();
+ expect(parseTranscript("")).toBeNull();
+ expect(parseTranscript("not json")).toBeNull();
+ expect(parseTranscript(JSON.stringify({ version: 2, utterances: [] }))).toBeNull();
+ expect(parseTranscript(JSON.stringify({ version: 1 }))).toBeNull();
+ });
+
+ it("keys the local speaker and identified system speakers, not unidentified speech", () => {
+ expect(getSpeakerKey("microphone")).toBe("microphone");
+ expect(getSpeakerKey("microphone", 3)).toBe("microphone");
+ expect(getSpeakerKey("system", 2)).toBe("system:2");
+ expect(getSpeakerKey("system")).toBeNull();
+ });
+
+ it("names a speaker, trims and caps the name, and forgets it when blank", () => {
+ const named = setSpeakerName(TRANSCRIPT, "system:2", " Alexandra ");
+ expect(named.speakers).toEqual({ "system:2": "Alexandra" });
+ expect(named.utterances).toBe(TRANSCRIPT.utterances);
+ expect(TRANSCRIPT.speakers).toBeUndefined();
+
+ const both = setSpeakerName(named, "microphone", "x".repeat(MAX_SPEAKER_NAME_LENGTH + 5));
+ expect(both.speakers?.microphone).toHaveLength(MAX_SPEAKER_NAME_LENGTH);
+ expect(setSpeakerName(both, "system:2", " ").speakers).toEqual({
+ microphone: "x".repeat(MAX_SPEAKER_NAME_LENGTH)
+ });
+ });
+});
diff --git a/packages/commons/src/lib/transcript.ts b/packages/commons/src/lib/transcript.ts
index a2100912d0..9f3f00b183 100644
--- a/packages/commons/src/lib/transcript.ts
+++ b/packages/commons/src/lib/transcript.ts
@@ -27,7 +27,56 @@ export interface Transcript {
version: 1;
/** When the recording started, as an ISO 8601 timestamp; the offsets count from here. */
startedAt: string;
+ /**
+ * Names given to speakers, by {@link getSpeakerKey}. A speaker without one keeps its default
+ * name.
+ */
+ speakers?: Record<string, string>;
utterances: TranscriptUtterance[];
}
export const TRANSCRIPT_MIME = "application/json";
+
+/** The longest speaker name a transcript accepts. */
+export const MAX_SPEAKER_NAME_LENGTH = 100;
+
+/** Reads a transcript attachment's content, or returns `null` for content of another shape. */
+export function parseTranscript(content: string | null | undefined): Transcript | null {
+ if (!content) {
+ return null;
+ }
+
+ try {
+ const parsed = JSON.parse(content) as Partial<Transcript>;
+ const isTranscript = parsed.version === 1 && Array.isArray(parsed.utterances);
+ return isTranscript ? parsed as Transcript : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The key a speaker's name is stored under: `microphone` for the local speaker, `system:<n>` for
+ * an identified speaker of the system output, and `null` for system speech no speaker was found
+ * for, which can be anyone.
+ */
+export function getSpeakerKey(source: TranscriptSource, speaker?: number) {
+ if (source === "microphone") {
+ return "microphone";
+ }
+ return speaker === undefined ? null : `system:${speaker}`;
+}
+
+/**
+ * Names the speaker of `key`, or gives back its default name when `name` is blank. Returns a new
+ * transcript; the utterances are shared.
+ */
+export function setSpeakerName(transcript: Transcript, key: string, name: string): Transcript {
+ const speakers = { ...transcript.speakers };
+ delete speakers[key];
+ const trimmed = name.trim().slice(0, MAX_SPEAKER_NAME_LENGTH);
+ if (trimmed) {
+ speakers[key] = trimmed;
+ }
+ return { ...transcript, speakers };
+}