Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calls): custom speaker overrides (#2939)
Will Hutchinsone1a4bf37178b
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/customSpeakerAssignment.ts b/js/app/packages/service-clients/service-storage/generated/schemas/customSpeakerAssignment.tsnew file mode 100644index 0000000000..09f8ce757c--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/customSpeakerAssignment.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * One per-diarized-speaker override, used in [`EditCallTranscriptRequest`].++`custom_speaker = None` clears any existing override for this+`diarized_speaker_id`; `Some(macro_user_id)` sets it. The string is+expected to parse as a `MacroUserId` (e.g. `macro|[email protected]`);+the service layer rejects malformed values with `400 Bad Request`.+ */+export interface CustomSpeakerAssignment {+ /** Macro user id to attribute matching rows to, or `None` to clear. */+ customSpeaker: string;+ /** The diarization label whose rows this assignment targets. */+ diarizedSpeakerId: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/editCallTranscriptRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/editCallTranscriptRequest.tsnew file mode 100644index 0000000000..27dc3ddd36--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/editCallTranscriptRequest.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CustomSpeakerAssignment } from './customSpeakerAssignment';++/**+ * Body of `PATCH /call/record/{call_id}/transcript`.++Each entry in `assignments` sets (or clears, when `custom_speaker` is+`None`) the `custom_speaker` override for every transcript row in the+call whose `diarized_speaker_id` matches. Diarized speakers not listed+are left untouched. Empty `assignments` is a 204 no-op.+ */+export interface EditCallTranscriptRequest {+ /** The set of per-diarized-speaker overrides to apply. */+ assignments: CustomSpeakerAssignment[];+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex dd44384a3f..c37e40e2f9 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -195,6 +195,7 @@ export * from './createUnthreadedPdfAnchorRequestOneOf';export * from './createUnthreadedPdfAnchorRequestOneOfAllOf';export * from './createUnthreadedPdfAnchorRequestOneOfAllOfAnchorType';export * from './createViewRequest';+export * from './customSpeakerAssignment';export * from './dataType';export * from './deleteAnchorInfo';export * from './deleteAnchorInfoAllOf';@@ -276,6 +277,7 @@ export * from './editCallRecordRequest';export * from './editCallRecordRequestCustomName';export * from './editCallRecordRequestSharePermission';export * from './editCallRecordRequestShareWithTeam';+export * from './editCallTranscriptRequest';export * from './editCommentRequest';export * from './editCommentRequestMentions';export * from './editCommentRequestText';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex f739b66672..b11c49dfae 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -1092,6 +1092,43 @@ export const toggleShareWithTeamParams = zod.object({export const toggleShareWithTeamResponse = zod.boolean();+/**+ * Applies per-diarized-speaker `custom_speaker` overrides to the call's+archived transcript rows. Auth uses the same `EditAccessLevel` extractor+as `edit_call_record_handler`.+ * @summary Handler for `PATCH /call/record/{call_id}/transcript`.+ */+export const editCallTranscriptParams = zod.object({+ call_id: zod.string().uuid().describe('Call ID'),+});++export const editCallTranscriptBody = zod+ .object({+ assignments: zod+ .array(+ zod+ .object({+ customSpeaker: zod+ .string()+ .describe(+ 'Macro user id to attribute matching rows to, or `None` to clear.'+ ),+ diarizedSpeakerId: zod+ .string()+ .describe(+ 'The diarization label whose rows this assignment targets.'+ ),+ })+ .describe(+ 'One per-diarized-speaker override, used in [`EditCallTranscriptRequest`].\n\n`custom_speaker = None` clears any existing override for this\n`diarized_speaker_id`; `Some(macro_user_id)` sets it. The string is\nexpected to parse as a `MacroUserId` (e.g. `macro|[email protected]`);\nthe service layer rejects malformed values with `400 Bad Request`.'+ )+ )+ .describe('The set of per-diarized-speaker overrides to apply.'),+ })+ .describe(+ 'Body of `PATCH \/call\/record\/{call_id}\/transcript`.\n\nEach entry in `assignments` sets (or clears, when `custom_speaker` is\n`None`) the `custom_speaker` override for every transcript row in the\ncall whose `diarized_speaker_id` matches. Diarized speakers not listed\nare left untouched. Empty `assignments` is a 204 no-op.'+ );+/*** Gets or creates a call for the channel. If a call already exists, joins it;otherwise creates a new one. Always returns a join token.diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 75e96569c3..3786c684eb 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -894,6 +894,81 @@}}},+ "/call/record/{call_id}/transcript": {+ "patch": {+ "tags": ["call::inbound::axum_router"],+ "summary": "Handler for `PATCH /call/record/{call_id}/transcript`.",+ "description": "Applies per-diarized-speaker `custom_speaker` overrides to the call's\narchived transcript rows. Auth uses the same `EditAccessLevel` extractor\nas `edit_call_record_handler`.",+ "operationId": "edit_call_transcript",+ "parameters": [+ {+ "name": "call_id",+ "in": "path",+ "description": "Call ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EditCallTranscriptRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "204": {+ "description": "Transcript updated"+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/call/webhook": {"post": {"tags": ["call::inbound::axum_router"],@@ -7239,6 +7314,21 @@}}},+ "CustomSpeakerAssignment": {+ "type": "object",+ "description": "One per-diarized-speaker override, used in [`EditCallTranscriptRequest`].\n\n`custom_speaker = None` clears any existing override for this\n`diarized_speaker_id`; `Some(macro_user_id)` sets it. The string is\nexpected to parse as a `MacroUserId` (e.g. `macro|[email protected]`);\nthe service layer rejects malformed values with `400 Bad Request`.",+ "required": ["diarizedSpeakerId", "customSpeaker"],+ "properties": {+ "customSpeaker": {+ "type": "string",+ "description": "Macro user id to attribute matching rows to, or `None` to clear."+ },+ "diarizedSpeakerId": {+ "type": "string",+ "description": "The diarization label whose rows this assignment targets."+ }+ }+ },"DataType": {"type": "string","description": "Data type for property values, determining storage and validation.",@@ -7851,6 +7941,20 @@}}},+ "EditCallTranscriptRequest": {+ "type": "object",+ "description": "Body of `PATCH /call/record/{call_id}/transcript`.\n\nEach entry in `assignments` sets (or clears, when `custom_speaker` is\n`None`) the `custom_speaker` override for every transcript row in the\ncall whose `diarized_speaker_id` matches. Diarized speakers not listed\nare left untouched. Empty `assignments` is a 204 no-op.",+ "required": ["assignments"],+ "properties": {+ "assignments": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CustomSpeakerAssignment"+ },+ "description": "The set of per-diarized-speaker overrides to apply."+ }+ }+ },"EditCommentRequest": {"type": "object","required": ["threadId"],diff --git a/rust/cloud-storage/.sqlx/query-9921d35717a5c93783e3db8c1fd380459c4400902f4c3c86e3e2650613321a70.json b/rust/cloud-storage/.sqlx/query-9921d35717a5c93783e3db8c1fd380459c4400902f4c3c86e3e2650613321a70.jsonnew file mode 100644index 0000000000..75bc1d69a3--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-9921d35717a5c93783e3db8c1fd380459c4400902f4c3c86e3e2650613321a70.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE call_record_transcripts AS t\n SET custom_speaker = u.custom_speaker\n FROM UNNEST($2::text[], $3::text[]) AS u(diarized_speaker_id, custom_speaker)\n WHERE t.call_record_id = $1\n AND t.diarized_speaker_id = u.diarized_speaker_id\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "9921d35717a5c93783e3db8c1fd380459c4400902f4c3c86e3e2650613321a70"+}diff --git a/rust/cloud-storage/.sqlx/query-9b0034065161dec2180a9714d46745b36e32ab06043cd636bbfab029d173bf72.json b/rust/cloud-storage/.sqlx/query-f2ca3e891cf63cbdad88b2ef040dd73e501abe540dbe1c8150fe70db531ef36a.jsonsimilarity index 71%rename from rust/cloud-storage/.sqlx/query-9b0034065161dec2180a9714d46745b36e32ab06043cd636bbfab029d173bf72.jsonrename to rust/cloud-storage/.sqlx/query-f2ca3e891cf63cbdad88b2ef040dd73e501abe540dbe1c8150fe70db531ef36a.jsonindex 0288a507b7..15fcefd07e 100644--- a/rust/cloud-storage/.sqlx/query-9b0034065161dec2180a9714d46745b36e32ab06043cd636bbfab029d173bf72.json+++ b/rust/cloud-storage/.sqlx/query-f2ca3e891cf63cbdad88b2ef040dd73e501abe540dbe1c8150fe70db531ef36a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num\n FROM call_record_transcripts\n WHERE call_record_id = $1\n ORDER BY sequence_num ASC\n ",+ "query": "\n SELECT segment_id, speaker_id, diarized_speaker_id, custom_speaker, content, started_at, ended_at, sequence_num\n FROM call_record_transcripts\n WHERE call_record_id = $1\n ORDER BY sequence_num ASC\n ","describe": {"columns": [{@@ -20,21 +20,26 @@},{"ordinal": 3,- "name": "content",+ "name": "custom_speaker","type_info": "Text"},{"ordinal": 4,+ "name": "content",+ "type_info": "Text"+ },+ {+ "ordinal": 5,"name": "started_at","type_info": "Timestamptz"},{- "ordinal": 5,+ "ordinal": 6,"name": "ended_at","type_info": "Timestamptz"},{- "ordinal": 6,+ "ordinal": 7,"name": "sequence_num","type_info": "Int4"}@@ -48,11 +53,12 @@true,false,true,+ true,false,false,true,false]},- "hash": "9b0034065161dec2180a9714d46745b36e32ab06043cd636bbfab029d173bf72"+ "hash": "f2ca3e891cf63cbdad88b2ef040dd73e501abe540dbe1c8150fe70db531ef36a"}diff --git a/rust/cloud-storage/CLAUDE.md b/rust/cloud-storage/CLAUDE.mdindex 8f028dba84..99384888cd 100644--- a/rust/cloud-storage/CLAUDE.md+++ b/rust/cloud-storage/CLAUDE.md@@ -56,8 +56,10 @@ with `just setup_macrodb` in `macro-api/cloud-storage`. Remember that some databcamelCased rather than snake_cased (use `/dump-schema` or check the migration files for actual column names).When a column is camelCased, you need to cast it as the snake_cased version when reading from the database. E.g.`SELECT "userId" as "user_id" FROM "UserInsights"`.-Any time you make changes to the SQL code in rust, you need to run `just prepare_db` in-the root directory of the crate you made the changes in, to update the .sqlx directory.+Any time you make changes to the SQL code in rust, you need to run `just prepare_db` to+update the .sqlx directory. Run it **only** from `rust/cloud-storage` — do not run it from+individual crate directories anymore. The workspace-level recipe handles every crate that+has sqlx queries.## Development Commandsdiff --git a/rust/cloud-storage/call/fixtures/call_repo.sql b/rust/cloud-storage/call/fixtures/call_repo.sqlindex 75a163d5d8..3742309e00 100644--- a/rust/cloud-storage/call/fixtures/call_repo.sql+++ b/rust/cloud-storage/call/fixtures/call_repo.sql@@ -55,11 +55,14 @@ INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_a('00000000-0000-0000-0000-0000000ca2ed', 'macro|[email protected]', '2024-01-01 10:00:00+00', '2024-01-01 10:05:00+00'),('00000000-0000-0000-0000-0000000ca2ed', 'macro|[email protected]', '2024-01-01 10:01:00+00', '2024-01-01 10:04:30+00');-INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num) VALUES- ('00000000-0000-0000-0000-0000000ca2ed', 'seg-arch-1', 'macro|[email protected]', 'spk-arch-a0', 'archived hello',+INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, diarized_speaker_id, custom_speaker, content, started_at, ended_at, sequence_num) VALUES+ ('00000000-0000-0000-0000-0000000ca2ed', 'seg-arch-1', 'macro|[email protected]', 'spk-arch-a0', NULL, 'archived hello','2024-01-01 10:00:05+00', '2024-01-01 10:00:07+00', 1),- ('00000000-0000-0000-0000-0000000ca2ed', 'seg-arch-2', 'macro|[email protected]', NULL, 'archived reply',- '2024-01-01 10:00:08+00', '2024-01-01 10:00:10+00', 2);+ ('00000000-0000-0000-0000-0000000ca2ed', 'seg-arch-2', 'macro|[email protected]', NULL, NULL, 'archived reply',+ '2024-01-01 10:00:08+00', '2024-01-01 10:00:10+00', 2),+ -- Override row: derived speaker_id is user-a, but custom_speaker pins it to user-b.+ ('00000000-0000-0000-0000-0000000ca2ed', 'seg-arch-3', 'macro|[email protected]', 'spk-arch-b0', 'macro|[email protected]', 'archived overridden',+ '2024-01-01 10:00:11+00', '2024-01-01 10:00:13+00', 3);-- entity_access grants for the active call (owner + channel view).INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUESdiff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rsindex e95dd779b0..1fafa51d7f 100644--- a/rust/cloud-storage/call/src/domain/models.rs+++ b/rust/cloud-storage/call/src/domain/models.rs@@ -164,6 +164,37 @@ pub struct EditCallRecordRequest {pub custom_name: Option<String>,}+/// One per-diarized-speaker override, used in [`EditCallTranscriptRequest`].+///+/// `custom_speaker = None` clears any existing override for this+/// `diarized_speaker_id`; `Some(macro_user_id)` sets it. The string is+/// expected to parse as a `MacroUserId` (e.g. `macro|[email protected]`);+/// the service layer rejects malformed values with `400 Bad Request`.+#[derive(Debug, Clone, serde::Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct CustomSpeakerAssignment {+ /// The diarization label whose rows this assignment targets.+ pub diarized_speaker_id: String,+ #[cfg_attr(feature = "inbound", schema(value_type = String))]+ /// Macro user id to attribute matching rows to, or `None` to clear.+ pub custom_speaker: Option<MacroUserIdStr<'static>>,+}++/// Body of `PATCH /call/record/{call_id}/transcript`.+///+/// Each entry in `assignments` sets (or clears, when `custom_speaker` is+/// `None`) the `custom_speaker` override for every transcript row in the+/// call whose `diarized_speaker_id` matches. Diarized speakers not listed+/// are left untouched. Empty `assignments` is a 204 no-op.+#[derive(Debug, Clone, serde::Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct EditCallTranscriptRequest {+ /// The set of per-diarized-speaker overrides to apply.+ pub assignments: Vec<CustomSpeakerAssignment>,+}+/// A transcript segment as returned in a [`CallRecord`].#[derive(Debug, Clone, serde::Serialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsindex c3234113a1..5ba3175d31 100644--- a/rust/cloud-storage/call/src/domain/ports.rs+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -11,7 +11,9 @@ use uuid::Uuid;use item_filters::ast::{LiteralTree, call::CallLiteral};-use crate::domain::models::EditCallRecordRequest;+use crate::domain::models::{+ CustomSpeakerAssignment, EditCallRecordRequest, EditCallTranscriptRequest,+};use super::models::{AddParticipantError, Call, CallActiveResponse, CallError, CallParticipant, CallRecord,@@ -219,6 +221,19 @@ pub trait CallRepository: Send + Sync + 'static {request: &EditCallRecordRequest,) -> impl Future<Output = Result<(), Self::Err>> + Send;+ /// Apply a batch of per-diarized-speaker `custom_speaker` overrides to+ /// the archived `call_record_transcripts` rows for `call_record_id`.+ ///+ /// Each entry sets `custom_speaker` for every row in the call whose+ /// `diarized_speaker_id` matches; entries with `custom_speaker = None`+ /// clear the override. Rows whose `diarized_speaker_id` doesn't appear+ /// in `assignments` are left untouched. Empty `assignments` is a no-op.+ fn patch_call_transcript_custom_speakers(+ &self,+ call_record_id: &Uuid,+ assignments: &[CustomSpeakerAssignment],+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+/// Persist the AI-generated summary text on the archived call record.////// Tolerates unknown `call_id` (no row matches): the summarization flow@@ -431,6 +446,17 @@ pub trait CallService: Send + Sync + 'static {request: EditCallRecordRequest,) -> impl Future<Output = Result<(), CallError>> + Send;+ /// Apply per-diarized-speaker `custom_speaker` overrides to a call's+ /// transcript. Authorization is carried in the receipt; the entity must+ /// be `EntityType::Call` and its `entity_id` must be the call's UUID.+ /// Each `custom_speaker` (when `Some`) must parse as a `MacroUserId`;+ /// otherwise the request is rejected with [`CallError::InvalidRequest`].+ fn edit_call_transcript(+ &self,+ receipt: EntityAccessReceipt<EditAccessLevel>,+ request: EditCallTranscriptRequest,+ ) -> impl Future<Output = Result<(), CallError>> + Send;+/// Toggle the `share_with_team` flag on the active call identified by the/// receipt. Authorization is carried in the receipt produced by/// `CallAccessLevelExtractor`; the entity on the receipt must bediff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsindex 30ad9c4359..a535f17ed3 100644--- a/rust/cloud-storage/call/src/domain/service.rs+++ b/rust/cloud-storage/call/src/domain/service.rs@@ -21,7 +21,7 @@ use serde::{Deserialize, Serialize};use std::collections::HashSet;use uuid::Uuid;-use crate::domain::models::EditCallRecordRequest;+use crate::domain::models::{EditCallRecordRequest, EditCallTranscriptRequest};use super::models::{AddParticipantError, CallActiveResponse, CallError, CallRecord, CallRecordTranscriptSegment,@@ -906,6 +906,29 @@ impl<.map_err(|e| CallError::Internal(e.into()))}+ #[tracing::instrument(err, skip(self, request), fields(num_assignments = request.assignments.len()))]+ async fn edit_call_transcript(+ &self,+ receipt: EntityAccessReceipt<EditAccessLevel>,+ request: EditCallTranscriptRequest,+ ) -> Result<(), CallError> {+ let entity = receipt.entity();+ if entity.entity_type != EntityType::Call {+ return Err(CallError::Internal(anyhow::anyhow!(+ "expected Call entity in receipt, got {:?}",+ entity.entity_type+ )));+ }++ let call_id = macro_uuid::string_to_uuid(&entity.entity_id)+ .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;++ self.repo+ .patch_call_transcript_custom_speakers(&call_id, &request.assignments)+ .await+ .map_err(|e| CallError::Internal(e.into()))+ }+#[tracing::instrument(err, skip(self))]async fn toggle_share_with_team(&self,diff --git a/rust/cloud-storage/call/src/inbound/axum_router.rs b/rust/cloud-storage/call/src/inbound/axum_router.rsindex 417ad7450f..029ad3037d 100644--- a/rust/cloud-storage/call/src/inbound/axum_router.rs+++ b/rust/cloud-storage/call/src/inbound/axum_router.rs@@ -15,7 +15,7 @@ use axum::{extract::{FromRef, FromRequestParts, State},http::{StatusCode, request::Parts},response::IntoResponse,- routing::{get, post},+ routing::{get, patch, post},};use entity_access::{domain::{@@ -33,8 +33,8 @@ use uuid::Uuid;use crate::domain::models::{CallActiveResponse, CallError, CallRecord, CallTokenResponse, EditCallRecordRequest,- GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, LeaveCallResponse,- MAX_BATCH_CALL_IDS, TranscriptSegmentRequest,+ EditCallTranscriptRequest, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse,+ LeaveCallResponse, MAX_BATCH_CALL_IDS, TranscriptSegmentRequest,};use crate::domain::ports::CallService;@@ -81,6 +81,7 @@ impl<S, Svc> FromRef<CallRouterState<S, Svc>> for Arc<Svc> {/// - `DELETE /{channel_id}` — leave or end a call/// - `GET /record/{call_id}` — get a full call record (transcript + participants)/// - `PATCH /record/{call_id}` — edit a call record (e.g. share permissions)+/// - `PATCH /record/{call_id}/transcript` — set per-diarized-speaker custom_speaker overrides/// - `DELETE /record/{call_id}` — delete a call record/// - `POST /record/{call_id}/share-with-team/toggle` — flip the call's share_with_team flag/// - `POST /record/preview` — batch-fetch lightweight previews for many call ids@@ -109,6 +110,10 @@ where.patch(edit_call_record_handler::<S, Svc>).delete(delete_call_record_handler::<S, Svc>),)+ .route(+ "/record/{call_id}/transcript",+ patch(edit_call_transcript_handler::<S, Svc>),+ ).route("/record/{call_id}/share-with-team/toggle",post(toggle_share_with_team_handler::<S, Svc>),@@ -397,6 +402,40 @@ pub async fn edit_call_record_handler<S: CallService, Svc: EntityAccessService>(Ok(StatusCode::NO_CONTENT)}+/// Handler for `PATCH /call/record/{call_id}/transcript`.+///+/// Applies per-diarized-speaker `custom_speaker` overrides to the call's+/// archived transcript rows. Auth uses the same `EditAccessLevel` extractor+/// as `edit_call_record_handler`.+#[utoipa::path(+ patch,+ operation_id = "edit_call_transcript",+ path = "/call/record/{call_id}/transcript",+ params(+ ("call_id" = Uuid, Path, description = "Call ID"),+ ),+ request_body = EditCallTranscriptRequest,+ responses(+ (status = 204, description = "Transcript updated"),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn edit_call_transcript_handler<S: CallService, Svc: EntityAccessService>(+ State(state): State<CallRouterState<S, Svc>>,+ access: CallAccessLevelExtractor<EditAccessLevel, Svc>,+ Json(request): Json<EditCallTranscriptRequest>,+) -> Result<StatusCode, CallError> {+ state+ .service+ .edit_call_transcript(access.entity_access_receipt, request)+ .await?;+ Ok(StatusCode::NO_CONTENT)+}+/// Handler for `POST /call/record/{call_id}/share-with-team/toggle`.////// Toggles the `share_with_team` flag on the active call. Returns the newdiff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex 2222a252de..0a4f98b36c 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -20,8 +20,8 @@ use uuid::Uuid;use crate::domain::channel_name::{NameLookup, display_name, resolve_channel_name};use crate::domain::models::{AddParticipantError, Call, CallParticipant, CallRecord, CallRecordParticipant,- CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, EditCallRecordRequest,- TranscriptSegmentRequest, WithCallId,+ CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CustomSpeakerAssignment,+ EditCallRecordRequest, TranscriptSegmentRequest, WithCallId,};use crate::domain::ports::CallRepository;@@ -884,7 +884,7 @@ impl CallRepository for PgCallRepo {let transcript = sqlx::query!(r#"- SELECT segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num+ SELECT segment_id, speaker_id, diarized_speaker_id, custom_speaker, content, started_at, ended_at, sequence_numFROM call_record_transcriptsWHERE call_record_id = $1ORDER BY sequence_num ASC@@ -896,7 +896,7 @@ impl CallRepository for PgCallRepo {.into_iter().map(|row| CallRecordTranscriptSegment {segment_id: row.segment_id,- speaker_id: row.speaker_id,+ speaker_id: row.custom_speaker.unwrap_or(row.speaker_id),diarized_speaker_id: row.diarized_speaker_id,content: row.content,started_at: row.started_at,@@ -1350,6 +1350,21 @@ impl CallRepository for PgCallRepo {Ok(())}+ #[tracing::instrument(skip(self, assignments), fields(num_assignments = assignments.len()), err)]+ async fn patch_call_transcript_custom_speakers(+ &self,+ call_record_id: &Uuid,+ assignments: &[CustomSpeakerAssignment],+ ) -> Result<(), Self::Err> {+ if assignments.is_empty() {+ return Ok(());+ }+ let mut tx = self.pool.begin().await?;+ edit::set_custom_speakers(&mut tx, call_record_id, assignments).await?;+ tx.commit().await?;+ Ok(())+ }+#[tracing::instrument(skip(self, summary), err)]async fn insert_call_summary(&self, call_id: &Uuid, summary: &str) -> Result<(), Self::Err> {// Tolerate missing rows: summarization can race with record deletion.diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo/edit.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo/edit.rsindex 280b3f974a..3b8b9fa2e1 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo/edit.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/edit.rs@@ -7,6 +7,8 @@ use models_permissions::share_permission::channel_share_permission::UpdateOperatuse sqlx::{Postgres, Transaction};use uuid::Uuid;+use crate::domain::models::CustomSpeakerAssignment;+/// Update share permissions for a call record.////// Looks up the call's share permission ID from either the active `calls`@@ -174,6 +176,45 @@ pub(super) async fn set_custom_name_if_null(Ok(())}+/// Apply per-(call_record_id, diarized_speaker_id) `custom_speaker` overrides.+///+/// Each entry sets `custom_speaker` for every row in the call whose+/// `diarized_speaker_id` matches; `custom_speaker = None` clears the+/// override. Rows whose `diarized_speaker_id` doesn't match any entry —+/// including rows with `diarized_speaker_id IS NULL` — are untouched.+pub(super) async fn set_custom_speakers(+ transaction: &mut Transaction<'_, Postgres>,+ call_record_id: &Uuid,+ assignments: &[CustomSpeakerAssignment],+) -> Result<(), sqlx::Error> {+ if assignments.is_empty() {+ return Ok(());+ }+ let diarized_ids: Vec<&str> = assignments+ .iter()+ .map(|a| a.diarized_speaker_id.as_str())+ .collect();+ let custom_speakers: Vec<Option<&str>> = assignments+ .iter()+ .map(|a| a.custom_speaker.as_deref().map(|c| c.as_ref()))+ .collect();+ sqlx::query!(+ r#"+ UPDATE call_record_transcripts AS t+ SET custom_speaker = u.custom_speaker+ FROM UNNEST($2::text[], $3::text[]) AS u(diarized_speaker_id, custom_speaker)+ WHERE t.call_record_id = $1+ AND t.diarized_speaker_id = u.diarized_speaker_id+ "#,+ call_record_id,+ &diarized_ids as &[&str],+ &custom_speakers as &[Option<&str>],+ )+ .execute(transaction.as_mut())+ .await?;+ Ok(())+}+/// Update the SharePermission row (isPublic, publicAccessLevel).async fn update_share_permission_row(transaction: &mut Transaction<'_, Postgres>,diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rsindex 8e049b90a8..f074da517c 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs@@ -1,7 +1,8 @@use std::{ops::Deref, sync::Arc, sync::LazyLock};use crate::domain::models::{- AddParticipantError, CallRecordPreview, EditCallRecordRequest, TranscriptSegmentRequest,+ AddParticipantError, CallRecordPreview, CustomSpeakerAssignment, EditCallRecordRequest,+ TranscriptSegmentRequest,};use crate::domain::ports::CallRepository;use crate::outbound::pg_call_repo::PgCallRepo;@@ -888,7 +889,7 @@ async fn get_call_record_returns_archived_call(pool: Pool<Postgres>) -> anyhow::assert!(record.participants.iter().all(|p| p.left_at.is_some()));// Transcripts ordered by sequence_num.- assert_eq!(record.transcript.len(), 2);+ assert_eq!(record.transcript.len(), 3);assert_eq!(record.transcript[0].content, "archived hello");assert_eq!(record.transcript[0].diarized_speaker_id.as_deref(),@@ -899,6 +900,34 @@ async fn get_call_record_returns_archived_call(pool: Pool<Postgres>) -> anyhow::Ok(())}+#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_call_record_overrides_speaker_id_with_custom_speaker(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let record = repo+ .get_call_record_by_call_id(&CALL_ARCHIVED)+ .await?+ .expect("archived call should be found");++ // Row without an override returns the derived speaker_id.+ assert_eq!(record.transcript[0].content, "archived hello");+ assert_eq!(record.transcript[0].speaker_id, "macro|[email protected]");++ // Row with `custom_speaker` set returns the override, not the derived+ // speaker_id (which is `macro|[email protected]` in the fixture).+ assert_eq!(record.transcript[2].content, "archived overridden");+ assert_eq!(record.transcript[2].speaker_id, "macro|[email protected]");+ assert_eq!(+ record.transcript[2].diarized_speaker_id.as_deref(),+ Some("spk-arch-b0")+ );+ Ok(())+}+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("call_repo")),migrator = "MACRO_DB_MIGRATIONS"@@ -1972,3 +2001,102 @@ async fn insert_call_summary_noop_for_unknown_id(pool: Pool<Postgres>) -> anyhowassert!(stored.is_none());Ok(())}++// -- patch_call_transcript_custom_speakers ------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn patch_call_transcript_custom_speakers_sets_and_clears(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);++ // Set: pin diarized `spk-arch-a0` to user-c. The fixture's seg-arch-3 row+ // (diarized `spk-arch-b0`) already has user-b as its custom_speaker — clear it.+ repo.patch_call_transcript_custom_speakers(+ &CALL_ARCHIVED,+ &[+ CustomSpeakerAssignment {+ diarized_speaker_id: "spk-arch-a0".to_string(),+ custom_speaker: Some(USER_C.clone()),+ },+ CustomSpeakerAssignment {+ diarized_speaker_id: "spk-arch-b0".to_string(),+ custom_speaker: None,+ },+ ],+ )+ .await?;++ let record = repo+ .get_call_record_by_call_id(&CALL_ARCHIVED)+ .await?+ .expect("archived call should exist");++ // seg-arch-1 (diarized spk-arch-a0): override now applied → user-c.+ assert_eq!(record.transcript[0].content, "archived hello");+ assert_eq!(record.transcript[0].speaker_id, "macro|[email protected]");++ // seg-arch-2 (diarized NULL): never touched.+ assert_eq!(record.transcript[1].content, "archived reply");+ assert_eq!(record.transcript[1].speaker_id, "macro|[email protected]");++ // seg-arch-3 (diarized spk-arch-b0): override cleared → derived speaker_id wins.+ assert_eq!(record.transcript[2].content, "archived overridden");+ assert_eq!(record.transcript[2].speaker_id, "macro|[email protected]");++ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn patch_call_transcript_custom_speakers_empty_is_noop(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);++ repo.patch_call_transcript_custom_speakers(&CALL_ARCHIVED, &[])+ .await?;++ // Fixture state is unchanged.+ let record = repo+ .get_call_record_by_call_id(&CALL_ARCHIVED)+ .await?+ .expect("archived call should exist");+ assert_eq!(record.transcript[2].speaker_id, "macro|[email protected]");+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn patch_call_transcript_custom_speakers_unknown_diarized_id_is_noop(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);++ // Diarized id that doesn't exist in this call: silently affects nothing.+ repo.patch_call_transcript_custom_speakers(+ &CALL_ARCHIVED,+ &[CustomSpeakerAssignment {+ diarized_speaker_id: "spk-does-not-exist".to_string(),+ custom_speaker: Some(USER_C.clone()),+ }],+ )+ .await?;++ let record = repo+ .get_call_record_by_call_id(&CALL_ARCHIVED)+ .await?+ .expect("archived call should exist");+ // All rows still reflect their original speaker_id / custom_speaker.+ assert_eq!(record.transcript[0].speaker_id, "macro|[email protected]");+ assert_eq!(record.transcript[1].speaker_id, "macro|[email protected]");+ assert_eq!(record.transcript[2].speaker_id, "macro|[email protected]");+ Ok(())+}diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 0f8dc94767..d3dce93d95 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -198,6 +198,7 @@ use utoipa::OpenApi;call::inbound::axum_router::leave_or_end_call_handler,call::inbound::axum_router::get_call_record_handler,call::inbound::axum_router::edit_call_record_handler,+ call::inbound::axum_router::edit_call_transcript_handler,call::inbound::axum_router::delete_call_record_handler,call::inbound::axum_router::toggle_share_with_team_handler,call::inbound::axum_router::get_batch_call_record_preview_handler,@@ -351,6 +352,8 @@ use utoipa::OpenApi;call::domain::models::CallRecordParticipant,call::domain::models::CallRecordTranscriptSegment,call::domain::models::EditCallRecordRequest,+ call::domain::models::EditCallTranscriptRequest,+ call::domain::models::CustomSpeakerAssignment,call::domain::models::CallRecordPreview,call::domain::models::CallRecordPreviewData,call::domain::models::WithCallId,diff --git a/rust/cloud-storage/macro_db_client/migrations/20260429150324_call_record_transcripts_custom_speaker.sql b/rust/cloud-storage/macro_db_client/migrations/20260429150324_call_record_transcripts_custom_speaker.sqlnew file mode 100644index 0000000000..4c92008f2a--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260429150324_call_record_transcripts_custom_speaker.sql@@ -0,0 +1,8 @@+-- Manually-corrected speaker for a transcript row, identified by Macro user id+-- (e.g. `macro|[email protected]`). When set, it overrides the derived+-- `speaker_id` (which comes from the LiveKit track owner) on read. NULL means+-- "use speaker_id as-is". Set per diarized speaker via+-- PATCH /call/record/{call_id}/transcript.++ALTER TABLE call_record_transcripts+ ADD COLUMN IF NOT EXISTS custom_speaker TEXT;