From acbc9156c772a09d903989fadda412fd2c8aa546 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Wed, 7 Oct 2026 18:46:19 +0200 Subject: [PATCH 01/57] feat(ui): bound the date picker and let a label name it DatePicker takes minDate/maxDate (days outside are disabled and read "Not available" in the UI language) and forwards id, aria-labelledby and aria-describedby to its trigger, which dropped them before. --- .../src/components/forms/date-picker.test.tsx | 60 +++++++++++++++++++ .../ui/src/components/forms/date-picker.tsx | 35 +++++++++++ packages/ui/src/i18n/messages/de.yml | 1 + packages/ui/src/i18n/messages/en.yml | 1 + packages/ui/src/i18n/messages/fr.yml | 1 + 5 files changed, 98 insertions(+) diff --git a/packages/ui/src/components/forms/date-picker.test.tsx b/packages/ui/src/components/forms/date-picker.test.tsx index 142cb2a0d0..82e06dda95 100644 --- a/packages/ui/src/components/forms/date-picker.test.tsx +++ b/packages/ui/src/components/forms/date-picker.test.tsx @@ -352,3 +352,63 @@ describe('DatePicker popper container', () => { expect(screen.getByRole('dialog', { name: 'Calendar' })).toBeVisible(); }); }); + +describe('DatePicker bounds', () => { + const SEP_15_2026 = new Date(2026, 8, 15).getTime(); + + it('offers only the days between minDate and maxDate', async () => { + const onChange = vi.fn(); + const { user } = render( + , + ); + await user.click(screen.getByRole('button', { name: 'Sep 15, 2026' })); + + const before = screen.getByRole('gridcell', { + name: /September 9th, 2026$/, + }); + const inside = screen.getByRole('gridcell', { + name: /September 12th, 2026$/, + }); + const after = screen.getByRole('gridcell', { + name: /September 21st, 2026$/, + }); + expect(before).toHaveAttribute('aria-disabled', 'true'); + expect(after).toHaveAttribute('aria-disabled', 'true'); + expect(inside).toHaveAttribute('aria-disabled', 'false'); + // A day that cannot be picked says so in the UI language, not in + // react-datepicker's built-in English. + expect(before).toHaveAccessibleName(/^Not available /); + expect(inside).toHaveAccessibleName(/^Choose /); + + await user.click(before); + expect(onChange).not.toHaveBeenCalled(); + await user.click(inside); + expect(onChange).toHaveBeenCalledWith(new Date(2026, 8, 12).getTime()); + }); + + it('is named by the label it points at and keeps the chosen date', () => { + render( + <> + Expiration date + Up to one year from today. + + , + ); + const trigger = screen.getByRole('button', { + name: 'Expiration date Sep 29, 2026', + }); + expect(trigger).toHaveAttribute('id', 'expiry'); + expect(trigger).toHaveAccessibleDescription('Up to one year from today.'); + }); +}); diff --git a/packages/ui/src/components/forms/date-picker.tsx b/packages/ui/src/components/forms/date-picker.tsx index d844e9f298..acd0a73a05 100644 --- a/packages/ui/src/components/forms/date-picker.tsx +++ b/packages/ui/src/components/forms/date-picker.tsx @@ -44,6 +44,22 @@ export interface DatePickerProps { * box would read as the one field still waiting to be filled in. */ variant?: 'default' | 'ghost'; + /** The earliest day that can be picked (ms epoch); days before it are + * disabled in the calendar. */ + minDate?: number; + /** The latest day that can be picked (ms epoch); days after it are + * disabled in the calendar. */ + maxDate?: number; + /** + * Names the trigger: a visible label's id. Include the trigger's own `id` + * after it (`"expiry-label expiry"`) so the name keeps the chosen date — + * a label alone would replace the date the trigger reads out. Leave + * `htmlFor` off that label: a native label takes over the self-reference + * and drops the date again. + */ + 'aria-labelledby'?: string; + /** Ids of the hint or error text that describes the field. */ + 'aria-describedby'?: string; } /** @@ -100,6 +116,10 @@ const MonthNavHeader = memo(function MonthNavHeader({ }); interface TriggerProps { + /** Handed down by react-datepicker from the picker's own props. */ + id?: string; + 'aria-labelledby'?: string; + 'aria-describedby'?: string; value?: string; onClick?: () => void; disabled?: boolean; @@ -120,6 +140,9 @@ interface TriggerProps { const DateTrigger = forwardRef( ( { + id, + 'aria-labelledby': ariaLabelledBy, + 'aria-describedby': ariaDescribedBy, value, onClick, disabled, @@ -154,6 +177,9 @@ const DateTrigger = forwardRef( > + ); + } + + function renderPasteBox() { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + return render( + + + + , + ); + } + + it('names the project, so the transcription counts toward it', async () => { + const sent = stubIngest(() => json({ jobId: 'job-1' })); + const { user } = renderPasteBox(); + + await user.click(screen.getByRole('button', { name: 'Paste' })); + + await waitFor(() => { + expect(sent).toEqual([ + expect.objectContaining({ + projectId: 'project-1', + url: 'https://www.youtube.com/watch?v=abcdefghijk', + }), + ]); + }); + expect(sent[0]).not.toHaveProperty('threadId'); + expect(toast).not.toHaveBeenCalled(); + }); + + it('says so when the project is no longer the member’s to chat in', async () => { + stubIngest(() => + json( + { error: 'projectUnavailable', message: 'Project unavailable' }, + 403, + ), + ); + const { user } = renderPasteBox(); + + await user.click(screen.getByRole('button', { name: 'Paste' })); + + expect( + await screen.findByText( + i18n.t('videoLink.errors.projectUnavailable', { ns: 'chat' }), + ), + ).toBeVisible(); + expect(toast).toHaveBeenCalledWith( + expect.objectContaining({ variant: 'destructive' }), + ); + }); +}); diff --git a/services/platform/app/features/chat/hooks/use-chat-video-links.ts b/services/platform/app/features/chat/hooks/use-chat-video-links.ts index 0bea8334d3..db2565c799 100644 --- a/services/platform/app/features/chat/hooks/use-chat-video-links.ts +++ b/services/platform/app/features/chat/hooks/use-chat-video-links.ts @@ -147,6 +147,9 @@ export interface UseChatVideoLinksResult { export function useChatVideoLinks(args: { threadId: string | undefined; + /** A project's new chat, before its thread exists: what a pasted link's + * transcription costs counts toward the project. */ + projectId?: string; organizationId: string; locale: string; }): UseChatVideoLinksResult { @@ -269,6 +272,9 @@ export function useChatVideoLinks(args: { await ingestVideoUrlRequest({ organizationId: args.organizationId, ...(args.threadId !== undefined ? { threadId: args.threadId } : {}), + ...(args.threadId === undefined && args.projectId !== undefined + ? { projectId: args.projectId } + : {}), url: match.url, pastedToken: match.pastedToken, userLocale: args.locale, @@ -290,7 +296,14 @@ export function useChatVideoLinks(args: { if (ingested > 0) nudgeChips(); return ingested; }, - [args.organizationId, args.threadId, args.locale, t, nudgeChips], + [ + args.organizationId, + args.threadId, + args.projectId, + args.locale, + t, + nudgeChips, + ], ); const cancelJob = useCallback( diff --git a/services/platform/app/features/shared/files/use-file-upload.test.ts b/services/platform/app/features/shared/files/use-file-upload.test.ts index 0a11d52d7c..04e4feee9f 100644 --- a/services/platform/app/features/shared/files/use-file-upload.test.ts +++ b/services/platform/app/features/shared/files/use-file-upload.test.ts @@ -687,3 +687,44 @@ describe('useFileUpload — concurrent-batch cap & dedup', () => { ); }); }); + +// A recording in a project's new chat is transcribed before the first send +// creates the thread; the registration names the project so the +// transcription counts toward it. Once a thread exists, the thread names it. +describe('useFileUpload — a project’s new chat', () => { + async function uploadOne(projectConfig: Parameters[0]) { + const { result } = renderHook(() => useFileUpload(projectConfig)); + let upload!: Promise; + act(() => { + upload = result.current.uploadFiles([ + makeFile('notes.txt', 120, 'text/plain'), + ]); + }); + await flush(); + resolveAllFetches(); + await act(async () => { + await upload; + }); + await waitFor(() => expect(saveFileMetadata).toHaveBeenCalledTimes(1)); + } + + it('names the project when the chat has no thread yet', async () => { + await uploadOne({ ...config, projectId: 'project-1' }); + + expect(saveFileMetadata).toHaveBeenCalledWith( + expect.objectContaining({ projectId: 'project-1' }), + ); + }); + + it('leaves the project to the thread once there is one', async () => { + await uploadOne({ + ...config, + threadId: 'thread-1', + projectId: 'project-1', + }); + + const registered = saveFileMetadata.mock.calls[0]?.[0]; + expect(registered).toMatchObject({ threadId: 'thread-1' }); + expect(registered).not.toHaveProperty('projectId'); + }); +}); diff --git a/services/platform/app/features/shared/files/use-file-upload.ts b/services/platform/app/features/shared/files/use-file-upload.ts index fb9bc7a985..36fb9dfa99 100644 --- a/services/platform/app/features/shared/files/use-file-upload.ts +++ b/services/platform/app/features/shared/files/use-file-upload.ts @@ -72,6 +72,12 @@ interface FileUploadConfig { * path keeps them readable to the agent in the same org. */ threadId?: string; + /** + * The project a new chat's upload is made in, before its thread exists: + * what the upload costs — a recording's transcription — counts toward + * it. Ignored once `threadId` names the thread. + */ + projectId?: string; /** * Suppress automatic knowledge-base (RAG) indexing for files uploaded * through this composer. Set when the active conversation targets an @@ -523,6 +529,10 @@ export function useFileUpload(config: FileUploadConfig) { ...(config.threadId !== undefined && { threadId: config.threadId, }), + ...(config.threadId === undefined && + config.projectId !== undefined && { + projectId: config.projectId, + }), ...(config.disableIndexing && { skipRagIndexing: true }), }); @@ -630,6 +640,7 @@ export function useFileUpload(config: FileUploadConfig) { saveFileMetadata, config.organizationId, config.threadId, + config.projectId, config.disableIndexing, mergedConfig, policyLimits, diff --git a/services/platform/app/lib/backend/chat.ts b/services/platform/app/lib/backend/chat.ts index e90dbec4f7..2e3df1cf4a 100644 --- a/services/platform/app/lib/backend/chat.ts +++ b/services/platform/app/lib/backend/chat.ts @@ -1022,6 +1022,7 @@ export function videoJobsUnboundQuery(organizationId: string) { export async function ingestVideoUrlRequest(args: { organizationId: string; threadId?: string; + projectId?: string; url: string; pastedToken: string; userLocale?: string; diff --git a/services/platform/app/lib/backend/documents.ts b/services/platform/app/lib/backend/documents.ts index 877e54c6b3..a4a1c02787 100644 --- a/services/platform/app/lib/backend/documents.ts +++ b/services/platform/app/lib/backend/documents.ts @@ -776,6 +776,9 @@ export const documentWriteAdapters: Record = { ...(typeof args.threadId === 'string' ? { threadId: args.threadId } : {}), + ...(typeof args.projectId === 'string' + ? { projectId: args.projectId } + : {}), ...(typeof args.source === 'string' ? { source: args.source } : {}), ...(args.skipRagIndexing === true ? { skipRagIndexing: true } : {}), }, diff --git a/services/platform/backend/core/file_metadata/transcribe_audio.metering.test.ts b/services/platform/backend/core/file_metadata/transcribe_audio.metering.test.ts index 0f3d7226b8..b4e1e438d8 100644 --- a/services/platform/backend/core/file_metadata/transcribe_audio.metering.test.ts +++ b/services/platform/backend/core/file_metadata/transcribe_audio.metering.test.ts @@ -217,4 +217,22 @@ describe('transcribeAudioImpl and the uploader’s limits', () => { ), ).toBe(false); }); + + it('reports nothing for a recording removed before its hold', async () => { + admission = { + allowed: false, + cancelled: true, + reason: 'The recording was removed before its transcription could start.', + }; + + await transcribeAudioImpl(fakeCtx() as never, ARGS); + + expect(mocks.requestTranscription).not.toHaveBeenCalled(); + expect( + called(':updateFileTranscription').some( + (mutation) => mutation.args.transcriptionStatus === 'failed', + ), + ).toBe(false); + expect(scheduled).toEqual([]); + }); }); diff --git a/services/platform/backend/core/file_metadata/transcribe_audio.ts b/services/platform/backend/core/file_metadata/transcribe_audio.ts index 72b6d9512e..34d53430af 100644 --- a/services/platform/backend/core/file_metadata/transcribe_audio.ts +++ b/services/platform/backend/core/file_metadata/transcribe_audio.ts @@ -177,7 +177,9 @@ class TranscriptionBudgetError extends Error { * lease is the shim's own and goes back to it as it came. */ function readTranscriptionAdmission( value: unknown, -): { allowed: true; lease: unknown } | { allowed: false; reason: string } { +): + | { allowed: true; lease: unknown } + | { allowed: false; reason: string; cancelled: boolean } { if (typeof value === 'object' && value !== null) { const allowed: unknown = Reflect.get(value, 'allowed'); const lease: unknown = Reflect.get(value, 'lease'); @@ -186,7 +188,11 @@ function readTranscriptionAdmission( return { allowed: true, lease }; } if (allowed === false && typeof reason === 'string') { - return { allowed: false, reason }; + return { + allowed: false, + reason, + cancelled: Reflect.get(value, 'cancelled') === true, + }; } } throw new Error( @@ -429,6 +435,19 @@ export async function transcribeAudioImpl( ), ); if (!admission.allowed) { + if (admission.cancelled) { + // Removed while it waited: nothing was held, nothing to report. + console.log( + JSON.stringify({ + event: 'transcription.cancelled', + requestId, + storageId: args.storageId, + status: 'removed_before_hold', + attempt, + }), + ); + return null; + } throw new TranscriptionBudgetError(admission.reason); } lease = admission.lease; diff --git a/services/platform/backend/core/video_links/ingest_video_link.ts b/services/platform/backend/core/video_links/ingest_video_link.ts index 6492a8b111..95f3f4b60b 100644 --- a/services/platform/backend/core/video_links/ingest_video_link.ts +++ b/services/platform/backend/core/video_links/ingest_video_link.ts @@ -839,6 +839,9 @@ export async function ingestVideoLinkImpl( source: 'video_link', uploadedBy: job.uploadedBy, ...(job.threadId !== undefined && { threadId: job.threadId }), + // A project's new chat, before its thread existed: the audio's + // transcription counts toward that project. + ...(job.projectId !== undefined && { projectId: job.projectId }), // Video-link provenance (sourceUrl/sourcePlatform/videoTitle/ // uploader/duration) lives on `videoLinkJobs` — `start_agent_chat.ts` // JOINs it by storageId. Single writer; not duplicated here. diff --git a/services/platform/backend/db/migrations/0158_chat_attachment_project.sql b/services/platform/backend/db/migrations/0158_chat_attachment_project.sql new file mode 100644 index 0000000000..ceff592472 --- /dev/null +++ b/services/platform/backend/db/migrations/0158_chat_attachment_project.sql @@ -0,0 +1,18 @@ +-- The project a chat attachment was made in before its thread existed +-- +-- A recording added to a project's new chat — uploaded, or fetched from a +-- pasted video link — is transcribed before the chat's first send creates +-- its thread: `thread_id` is still empty when the transcription holds and +-- books its minutes, so the project's budget never saw them. The composer +-- knows the project from the start and names it when it registers the +-- upload or the link; the door checks that the member may chat in it. A +-- transcription reads `file_metadata.project_id` first and the thread's +-- project after it (`files/transcription-metering.ts`); a video link's job +-- hands its project to the audio row it creates. +-- +-- Rolling-deploy safe: nullable columns the previous image neither writes +-- nor reads. + +ALTER TABLE app.file_metadata ADD COLUMN IF NOT EXISTS project_id text; + +ALTER TABLE app.video_link_jobs ADD COLUMN IF NOT EXISTS project_id text; diff --git a/services/platform/backend/domains/files/routes.register.test.ts b/services/platform/backend/domains/files/routes.register.test.ts index 06f1b743a4..5d557436e0 100644 --- a/services/platform/backend/domains/files/routes.register.test.ts +++ b/services/platform/backend/domains/files/routes.register.test.ts @@ -201,6 +201,23 @@ describe('POST /files/register', () => { expect(markRagQueued).not.toHaveBeenCalled(); expect(addJobInTx).not.toHaveBeenCalled(); }); + + it('hands a new chat’s project to the registration, which checks it [GOV-R14]', async () => { + const res = await register({ + fileName: 'memo.m4a', + contentType: 'audio/mp4', + projectId: 'project_1', + }); + + expect(res.status).toBe(200); + expect(registerUpload).toHaveBeenCalledWith( + expect.anything(), + db.tx, + { organizationId: 'org_1', userId: 'user_1' }, + expect.objectContaining({ projectId: 'project_1' }), + { kind: 'app', purpose: 'file' }, + ); + }); }); describe('POST /files/register — a file no lane will index', () => { diff --git a/services/platform/backend/domains/files/routes.ts b/services/platform/backend/domains/files/routes.ts index 4fc446f430..13f4307fd3 100644 --- a/services/platform/backend/domains/files/routes.ts +++ b/services/platform/backend/domains/files/routes.ts @@ -56,6 +56,9 @@ const registerSchema = z.object({ fileName: z.string().min(1).max(512), contentType: z.string().min(1).max(255), threadId: z.string().max(200).optional(), + /** The project a new chat's upload is made in, before its thread exists: + * what the upload costs (a recording's transcription) counts toward it. */ + projectId: z.string().max(128).optional(), // Only the dedicated image intake can vouch for inspected product bytes. source: z .string() diff --git a/services/platform/backend/domains/files/service.register-project.test.ts b/services/platform/backend/domains/files/service.register-project.test.ts new file mode 100644 index 0000000000..9283538775 --- /dev/null +++ b/services/platform/backend/domains/files/service.register-project.test.ts @@ -0,0 +1,133 @@ +// @vitest-environment node + +import type { Sql, TransactionSql } from 'postgres'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { s3HeadObject } from '../../lib/object-store.ts'; +import { projectChatAccess } from '../chat/threads.ts'; +import { FileError, registerUpload } from './service.ts'; + +/** + * A recording added to a project's new chat is transcribed before the chat's + * first message creates its thread, so the upload itself names the project + * its cost counts toward. Naming one is a claim on the project's budget: the + * uploader must be able to chat in it, as they must to start the chat. + */ + +vi.mock('./upload-intents.ts', async (importOriginal) => ({ + ...(await importOriginal()), + consumeUploadIntent: vi.fn(() => Promise.resolve(true)), +})); +vi.mock('../chat/threads.ts', () => ({ + projectChatAccess: vi.fn(), +})); +vi.mock(import('../../lib/object-store.ts'), async (importOriginal) => ({ + ...(await importOriginal()), + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the store is only handed back to the mocked HEAD + resolveObjectStore: vi.fn(() => Promise.resolve({} as never)), + s3HeadObject: vi.fn(() => Promise.resolve({ size: 2048 } as never)), +})); +vi.mock('../../lib/org-config.ts', () => ({ + resolveOrgSlug: vi.fn(() => Promise.resolve('acme')), +})); + +interface Statement { + text: string; + values: unknown[]; +} + +/** A recording transaction: no row claims the blob yet, and the insert + * answers the new row's id. */ +function fakeTx(): { tx: TransactionSql; statements: Statement[] } { + const statements: Statement[] = []; + const tag = (strings: TemplateStringsArray, ...values: unknown[]) => { + const text = strings.join('?').replace(/\s+/g, ' ').trim(); + statements.push({ text, values }); + return Promise.resolve( + text.startsWith('INSERT INTO app.file_metadata') + ? [{ id: 'file_1' }] + : [], + ); + }; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double for the postgres.js tag + return { tx: tag as unknown as TransactionSql, statements }; +} + +const scope = { organizationId: 'org_1', userId: 'user_1' }; +const args = { + storageRef: 's3:blobs/acme/memo', + fileName: 'memo.m4a', + contentType: 'audio/mp4', +}; + +function register(tx: TransactionSql, projectId?: string) { + return registerUpload( + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the org store lookups are mocked + {} as Sql, + tx, + scope, + { ...args, ...(projectId !== undefined && { projectId }) }, + { kind: 'app', purpose: 'file' }, + ); +} + +const inserts = (statements: Statement[]) => + statements.filter((s) => s.text.startsWith('INSERT INTO app.file_metadata')); + +beforeEach(() => { + vi.mocked(projectChatAccess).mockResolvedValue('ok'); +}); + +afterEach(() => { + vi.clearAllMocks(); +}); + +describe('registerUpload — the project a new chat is made in', () => { + it('writes the project onto the row when the uploader may chat in it [GOV-R14]', async () => { + const fake = fakeTx(); + + await expect(register(fake.tx, 'project_1')).resolves.toEqual({ + fileId: 'file_1', + size: 2048, + }); + + expect(projectChatAccess).toHaveBeenCalledWith(fake.tx, { + projectId: 'project_1', + organizationId: 'org_1', + userId: 'user_1', + }); + const insert = inserts(fake.statements)[0]; + expect(insert?.text).toContain('thread_id, project_id,'); + expect(insert?.values).toContain('project_1'); + }); + + it.each([ + ['not_found', 'PROJECT_NOT_FOUND', 404], + ['forbidden', 'PROJECT_FORBIDDEN', 403], + ] as const)( + 'refuses a project the uploader cannot chat in (%s), before the blob is read or a row written [GOV-R14]', + async (access, code, status) => { + vi.mocked(projectChatAccess).mockResolvedValue(access); + const fake = fakeTx(); + + const refused = await register(fake.tx, 'project_1').catch( + (error: unknown) => error, + ); + + expect(refused).toBeInstanceOf(FileError); + expect(refused).toMatchObject({ code, status }); + expect(s3HeadObject).not.toHaveBeenCalled(); + expect(inserts(fake.statements)).toEqual([]); + }, + ); + + it('asks nothing of a project when the upload names none', async () => { + const fake = fakeTx(); + + await register(fake.tx); + + expect(projectChatAccess).not.toHaveBeenCalled(); + const insert = inserts(fake.statements)[0]; + expect(insert?.values).not.toContain('project_1'); + }); +}); diff --git a/services/platform/backend/domains/files/service.ts b/services/platform/backend/domains/files/service.ts index 833994ca4b..db93c2b935 100644 --- a/services/platform/backend/domains/files/service.ts +++ b/services/platform/backend/domains/files/service.ts @@ -25,6 +25,7 @@ import { s3PutObject, } from '../../lib/object-store.ts'; import { resolveOrgSlug } from '../../lib/org-config.ts'; +import { projectChatAccess } from '../chat/threads.ts'; import { blobRefHeld } from './blob-holders.ts'; import { claimRejectedUpload, @@ -178,6 +179,9 @@ export interface RegisterUploadArgs { fileName: string; contentType: string; threadId?: string; + /** The project a new chat's upload is made in, before its thread exists — + * one the uploader may chat in; what the upload costs counts toward it. */ + projectId?: string; source?: string; /** The caller's opt-out from RAG indexing (0.4 `skipRagIndexing`). Every * enqueue gate reads the column, so a row that carries it never indexes, @@ -236,6 +240,22 @@ export async function registerUpload( 409, ); } + if (args.projectId !== undefined) { + // What the upload costs counts toward this project, so the uploader must + // be able to chat in it — as they must to start the chat itself. + const access = await projectChatAccess(tx, { + projectId: args.projectId, + organizationId: scope.organizationId, + userId: scope.userId, + }); + if (access !== 'ok') { + throw new FileError( + access === 'not_found' ? 'PROJECT_NOT_FOUND' : 'PROJECT_FORBIDDEN', + 'Project unavailable', + access === 'not_found' ? 404 : 403, + ); + } + } const { orgSlug, store } = await requireOrgStore(sql, scope.organizationId); const key = requireOrgScopedKey(args.storageRef, orgSlug); const head = await s3HeadObject(store, key); @@ -249,11 +269,11 @@ export async function registerUpload( const inserted = await tx<{ id: string }[]>` INSERT INTO app.file_metadata ( org_id, storage_ref, file_name, content_type, size, source, - uploaded_by, thread_id, skip_rag_indexing, created_at_ms + uploaded_by, thread_id, project_id, skip_rag_indexing, created_at_ms ) VALUES ( ${scope.organizationId}, ${args.storageRef}, ${args.fileName}, ${args.contentType}, ${head.size}, ${args.source ?? null}, - ${scope.userId}, ${args.threadId ?? null}, + ${scope.userId}, ${args.threadId ?? null}, ${args.projectId ?? null}, ${args.skipRagIndexing === true ? true : null}, ${Date.now()} ) RETURNING id diff --git a/services/platform/backend/domains/files/transcription-metering.test.ts b/services/platform/backend/domains/files/transcription-metering.test.ts index cccbd11d41..7db23c9fcb 100644 --- a/services/platform/backend/domains/files/transcription-metering.test.ts +++ b/services/platform/backend/domains/files/transcription-metering.test.ts @@ -15,9 +15,6 @@ const mocks = vi.hoisted(() => ({ openDirectCall: vi.fn(), settleDirectCall: vi.fn(async () => 'settled'), releaseDirectCall: vi.fn(async () => undefined), - readThreadProjectId: vi.fn( - async (): Promise => undefined, - ), probeAudioDurationSec: vi.fn(async () => 12), requestTranscription: vi.fn(), })); @@ -27,10 +24,6 @@ vi.mock('../governance/direct-calls.ts', () => ({ settleDirectCall: mocks.settleDirectCall, releaseDirectCall: mocks.releaseDirectCall, })); -vi.mock('../chat/threads.ts', async (importOriginal) => ({ - ...(await importOriginal()), - readThreadProjectId: mocks.readThreadProjectId, -})); vi.mock( '../../core/file_metadata/audio_preprocess.ts', async (importOriginal) => ({ @@ -83,23 +76,66 @@ beforeEach(() => { }); describe('an uploaded recording’s transcription', () => { - it('is its uploader’s spend, in the project of the chat it was added to [GOV-R14]', async () => { - mocks.readThreadProjectId.mockResolvedValueOnce('project-1'); + const row = (fields: Record) => ({ + uploadedBy: 'user-1', + projectId: null, + status: 'queued', + threadProjectId: null, + threadOwner: null, + ...fields, + }); + + it('is its uploader’s spend, in the project its chat was started in [GOV-R14]', async () => { + // A project's new chat: the composer named the project at registration. await expect( - uploadTranscriptionSubject( - rowsSql([{ uploadedBy: 'user-1', threadId: 'thread-1' }]), - { organizationId: 'org-1', storageId: 's3:org/rec' }, - ), + uploadTranscriptionSubject(rowsSql([row({ projectId: 'project-1' })]), { + organizationId: 'org-1', + storageId: 's3:org/rec', + }), ).resolves.toEqual({ userId: 'user-1', agentSlug: '__transcription__', projectIds: ['project-1'], }); + // Added to a chat the uploader owns: that chat's project. + await expect( + uploadTranscriptionSubject( + rowsSql([row({ threadProjectId: 'project-2', threadOwner: 'user-1' })]), + { organizationId: 'org-1', storageId: 's3:org/rec' }, + ), + ).resolves.toMatchObject({ projectIds: ['project-2'] }); + }); + + it('never takes the project of a chat the uploader does not own', async () => { + await expect( + uploadTranscriptionSubject( + rowsSql([ + row({ threadProjectId: 'project-2', threadOwner: 'someone-else' }), + ]), + { organizationId: 'org-1', storageId: 's3:org/rec' }, + ), + ).resolves.toEqual({ userId: 'user-1', agentSlug: '__transcription__' }); + }); + + it('charges nobody for a recording that was removed, or is gone', async () => { + await expect( + uploadTranscriptionSubject(rowsSql([row({ status: 'skipped' })]), { + organizationId: 'org-1', + storageId: 's3:org/rec', + }), + ).resolves.toBeNull(); await expect( uploadTranscriptionSubject(rowsSql([]), { organizationId: 'org-1', storageId: 's3:org/gone', }), + ).resolves.toBeNull(); + // A file nobody uploaded is the organization's. + await expect( + uploadTranscriptionSubject(rowsSql([row({ uploadedBy: null })]), { + organizationId: 'org-1', + storageId: 's3:org/rec', + }), ).resolves.toEqual({ userId: AUTOMATION_SUBJECT_ID, agentSlug: '__transcription__', diff --git a/services/platform/backend/domains/files/transcription-metering.ts b/services/platform/backend/domains/files/transcription-metering.ts index 5f90bd138b..83cd5c332f 100644 --- a/services/platform/backend/domains/files/transcription-metering.ts +++ b/services/platform/backend/domains/files/transcription-metering.ts @@ -5,7 +5,6 @@ import { TRANSCRIPTION_SLUG, } from '../../../lib/shared/constants/usage.ts'; import { estimateTranscriptionCostCents } from '../../core/governance/cost_estimation.ts'; -import { readThreadProjectId } from '../chat/threads.ts'; import { type DirectCallLease, type DirectCallSubject, @@ -43,7 +42,13 @@ export interface TranscriptionModelFacts { export type TranscriptionAdmission = | { allowed: true; lease: DirectCallLease } - | { allowed: false; reason: string }; + | { + allowed: false; + reason: string; + /** The recording was removed, or its transcription cancelled, + * before anything was held: no failure to report. */ + cancelled?: true; + }; /** Hold a transcription's whole length under `subject`. */ export async function openTranscriptionCall( @@ -72,30 +77,49 @@ export async function openTranscriptionCall( : { allowed: false, reason: admission.reason }; } -/** Whose spend an uploaded recording's transcription is: its uploader's — - * the organization's when nobody is named — and the project's of the chat - * it was added to. */ +/** + * Whose spend an uploaded recording's transcription is: its uploader's — + * the organization's when nobody is named — and the project's it was made + * in: the one the composer named when it registered the file, else the + * project of the chat it was added to, when the uploader owns that chat (a + * thread id on a file is the uploader's claim, not proof of the project). + * Null when the recording is gone or its transcription was cancelled: + * nothing is to be charged then. + */ export async function uploadTranscriptionSubject( sql: Sql, args: { organizationId: string; storageId: string }, -): Promise { +): Promise { const rows = await sql< - { uploadedBy: string | null; threadId: string | null }[] + { + uploadedBy: string | null; + projectId: string | null; + status: string | null; + threadProjectId: string | null; + threadOwner: string | null; + }[] >` - SELECT uploaded_by AS "uploadedBy", thread_id AS "threadId" - FROM app.file_metadata - WHERE org_id = ${args.organizationId} AND storage_ref = ${args.storageId} + SELECT fm.uploaded_by AS "uploadedBy", fm.project_id AS "projectId", + fm.transcription_status AS status, + tm.project_id AS "threadProjectId", tm.user_id AS "threadOwner" + FROM app.file_metadata fm + LEFT JOIN app.thread_metadata tm + ON tm.thread_id = fm.thread_id AND tm.org_id = fm.org_id + WHERE fm.org_id = ${args.organizationId} + AND fm.storage_ref = ${args.storageId} LIMIT 1 `; const row = rows[0]; + if (row === undefined || row.status === 'skipped') return null; const projectId = - row?.threadId != null - ? await readThreadProjectId(sql, args.organizationId, row.threadId) - : undefined; + row.projectId ?? + (row.threadOwner !== null && row.threadOwner === row.uploadedBy + ? row.threadProjectId + : null); return { - userId: row?.uploadedBy ?? AUTOMATION_SUBJECT_ID, + userId: row.uploadedBy ?? AUTOMATION_SUBJECT_ID, agentSlug: TRANSCRIPTION_SLUG, - ...(projectId !== undefined ? { projectIds: [projectId] } : {}), + ...(projectId !== null ? { projectIds: [projectId] } : {}), }; } diff --git a/services/platform/backend/domains/files/transcription.ts b/services/platform/backend/domains/files/transcription.ts index dfa01bf1d3..83128bee0c 100644 --- a/services/platform/backend/domains/files/transcription.ts +++ b/services/platform/backend/domains/files/transcription.ts @@ -259,10 +259,16 @@ function transcriptionHandlers(sql: Sql): ShimHandlers { storageId: string; audioDurationSec: number; }; - return openTranscriptionCall(sql, { - ...args, - subject: await uploadTranscriptionSubject(sql, args), - }); + const subject = await uploadTranscriptionSubject(sql, args); + if (subject === null) { + return { + allowed: false, + cancelled: true, + reason: + 'The recording was removed before its transcription could start.', + }; + } + return openTranscriptionCall(sql, { ...args, subject }); }, 'file_metadata/internal_mutations:settleTranscriptionCall': async (raw) => { // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- shim boundary: the pipeline passes exactly this shape diff --git a/services/platform/backend/domains/governance/project-budget.integration.ts b/services/platform/backend/domains/governance/project-budget.integration.ts index 6c77ded168..f9eb21aa96 100644 --- a/services/platform/backend/domains/governance/project-budget.integration.ts +++ b/services/platform/backend/domains/governance/project-budget.integration.ts @@ -617,19 +617,37 @@ export async function checkProjectBudgets( // minutes at 0.6¢ a minute) while it runs and booked at the minutes the // provider transcribed. const recording = `s3:itest/recording-${suffix}`; + // Added to the project's new chat, before its thread exists: the + // composer named the project when it registered the file (0158). A + // second recording claims a thread its uploader does not own, which + // names no project; a third was removed before its transcription. + const strangerRecording = `s3:itest/recording-stranger-${suffix}`; + const removedRecording = `s3:itest/recording-removed-${suffix}`; await sql` INSERT INTO app.file_metadata ( org_id, storage_ref, file_name, content_type, size, uploaded_by, - thread_id, created_at_ms - ) VALUES ( - ${orgId}, ${recording}, 'call.m4a', 'audio/mp4', 1, ${userId}, - ${projectThread}, ${now} - ) + thread_id, project_id, transcription_status, created_at_ms + ) VALUES + (${orgId}, ${recording}, 'call.m4a', 'audio/mp4', 1, ${userId}, + NULL, ${projectId}, 'queued', ${now}), + (${orgId}, ${strangerRecording}, 'call.m4a', 'audio/mp4', 1, + ${`itest-stranger-${suffix}`}, ${projectThread}, NULL, 'queued', + ${now}), + (${orgId}, ${removedRecording}, 'call.m4a', 'audio/mp4', 1, ${userId}, + NULL, ${projectId}, 'skipped', ${now}) `; const transcriptionSubject = await uploadTranscriptionSubject(sql, { organizationId: orgId, storageId: recording, }); + const strangerSubject = await uploadTranscriptionSubject(sql, { + organizationId: orgId, + storageId: strangerRecording, + }); + const removedSubject = await uploadTranscriptionSubject(sql, { + organizationId: orgId, + storageId: removedRecording, + }); const whisper = { organizationId: orgId, provider: 'itest', @@ -639,7 +657,10 @@ export async function checkProjectBudgets( const beforeTranscription = await heldInProject(); const transcription = await openTranscriptionCall(sql, { ...whisper, - subject: transcriptionSubject, + subject: transcriptionSubject ?? { + userId: '__automation__', + agentSlug: '__transcription__', + }, audioDurationSec: 600, }); const whileTranscribing = await heldInProject(); @@ -662,8 +683,11 @@ export async function checkProjectBudgets( `; record( 'project budgets: a recording’s transcription is held in its chat’s project at its whole length and booked under its uploader', - transcriptionSubject.userId === userId && + transcriptionSubject?.userId === userId && transcriptionSubject.projectIds?.[0] === projectId && + strangerSubject !== null && + strangerSubject.projectIds === undefined && + removedSubject === null && transcription.allowed && whileTranscribing - beforeTranscription === 6 && afterTranscription === beforeTranscription && @@ -671,7 +695,7 @@ export async function checkProjectBudgets( transcriptionBooked[0]?.userId === userId && Math.abs((transcriptionBooked[0]?.cost ?? 0) - 0.88) < 1e-9 && transcriptionBooked[0]?.seconds === 88, - `subject=${JSON.stringify(transcriptionSubject)} (want the uploader in the project) held ${whileTranscribing - beforeTranscription} then ${afterTranscription - beforeTranscription} (want 6 then 0) booked=${JSON.stringify(transcriptionBooked)} (want 0.88 cents, 88 s, the uploader)`, + `subject=${JSON.stringify(transcriptionSubject)} (want the uploader in the project) stranger=${JSON.stringify(strangerSubject)} (want no project) removed=${JSON.stringify(removedSubject)} (want null) held ${whileTranscribing - beforeTranscription} then ${afterTranscription - beforeTranscription} (want 6 then 0) booked=${JSON.stringify(transcriptionBooked)} (want 0.88 cents, 88 s, the uploader)`, ); } finally { await unlink(budgetsFile).catch((error: unknown) => { @@ -693,7 +717,12 @@ export async function checkProjectBudgets( `; await sql` DELETE FROM app.file_metadata - WHERE org_id = ${orgId} AND storage_ref = ${`s3:itest/recording-${suffix}`} + WHERE org_id = ${orgId} + AND storage_ref = ANY(${[ + `s3:itest/recording-${suffix}`, + `s3:itest/recording-stranger-${suffix}`, + `s3:itest/recording-removed-${suffix}`, + ]}) `; await sql` DELETE FROM app.usage_ledger diff --git a/services/platform/backend/domains/video_links/routes.test.ts b/services/platform/backend/domains/video_links/routes.test.ts new file mode 100644 index 0000000000..9855348e1c --- /dev/null +++ b/services/platform/backend/domains/video_links/routes.test.ts @@ -0,0 +1,124 @@ +// @vitest-environment node + +/** + * `POST /video-links/ingest` from a project's new chat: the link is fetched + * and transcribed before the chat's first message creates its thread, so the + * composer names the project its cost counts toward. A project named beside + * no thread must be one the member may chat in; a thread names its own, and + * a project sent beside one is ignored. + */ + +import type { Sql } from 'postgres'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Auth } from '../../auth/auth.ts'; +import { projectChatAccess } from '../chat/threads.ts'; +import { createVideoLinkRoutes } from './routes.ts'; +import { ingestVideoUrl } from './service.ts'; + +vi.mock('../../auth/session.ts', () => ({ + requireSession: + () => + async ( + c: { set: (key: string, value: unknown) => void }, + next: () => Promise, + ) => { + c.set('sessionBundle', { user: { id: 'user_1' } }); + await next(); + }, +})); +vi.mock('../../auth/org.ts', () => ({ + requireOrgMember: + () => + async ( + c: { set: (key: string, value: unknown) => void }, + next: () => Promise, + ) => { + c.set('orgId', 'org_1'); + c.set('orgMember', { role: 'member' }); + await next(); + }, +})); +vi.mock('../../lib/rate-limit.ts', () => ({ + checkOrganizationRateLimit: vi.fn(() => Promise.resolve()), +})); +vi.mock('../chat/threads.ts', () => ({ + projectChatAccess: vi.fn(), +})); +vi.mock('./service.ts', async (importOriginal) => ({ + ...(await importOriginal()), + ingestVideoUrl: vi.fn(() => Promise.resolve('job_1')), +})); + +/** Answers the own-thread probe with the thread, as for the caller's own. */ +const sql = vi.hoisted(() => + Object.assign(() => Promise.resolve([{ id: 'thread_1' }]), {}), +); + +function ingest(body: Record) { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the probe tag answers every query; the mocked middleware never touches auth + return createVideoLinkRoutes({ + sql: sql as unknown as Sql, + auth: {} as Auth, + }).request('/ingest', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + url: 'https://www.youtube.com/watch?v=abc', + pastedToken: 'token_1', + ...body, + }), + }); +} + +beforeEach(() => { + vi.mocked(projectChatAccess).mockResolvedValue('ok'); +}); + +afterEach(() => { + vi.clearAllMocks(); +}); + +describe('POST /video-links/ingest — a project’s new chat', () => { + it('hands a project the member may chat in to the job [GOV-R14]', async () => { + const res = await ingest({ projectId: 'project_1' }); + + expect(res.status).toBe(200); + expect(projectChatAccess).toHaveBeenCalledWith(sql, { + projectId: 'project_1', + organizationId: 'org_1', + userId: 'user_1', + }); + expect(ingestVideoUrl).toHaveBeenCalledWith( + sql, + expect.objectContaining({ projectId: 'project_1' }), + ); + }); + + it.each(['not_found', 'forbidden'] as const)( + 'refuses a project the member cannot chat in (%s), before any job [GOV-R14]', + async (access) => { + vi.mocked(projectChatAccess).mockResolvedValue(access); + + const res = await ingest({ projectId: 'project_1' }); + + expect(res.status).toBe(403); + expect(await res.json()).toEqual({ + error: 'projectUnavailable', + message: 'Project unavailable', + }); + expect(ingestVideoUrl).not.toHaveBeenCalled(); + }, + ); + + it('lets a thread name its own project, ignoring one sent beside it', async () => { + const res = await ingest({ threadId: 'thread_1', projectId: 'project_1' }); + + expect(res.status).toBe(200); + expect(projectChatAccess).not.toHaveBeenCalled(); + expect(ingestVideoUrl).toHaveBeenCalledWith( + sql, + expect.not.objectContaining({ projectId: expect.anything() }), + ); + }); +}); diff --git a/services/platform/backend/domains/video_links/routes.ts b/services/platform/backend/domains/video_links/routes.ts index b00b628a57..316a7fa04f 100644 --- a/services/platform/backend/domains/video_links/routes.ts +++ b/services/platform/backend/domains/video_links/routes.ts @@ -7,6 +7,7 @@ import { requireOrgMember, type OrgEnv } from '../../auth/org.ts'; import { requireSession } from '../../auth/session.ts'; import { invalidBodyResponse } from '../../lib/invalid-body-response.ts'; import { checkOrganizationRateLimit } from '../../lib/rate-limit.ts'; +import { projectChatAccess } from '../chat/threads.ts'; import { bindCompletedJobsToMessage, cancelVideoLink, @@ -66,6 +67,9 @@ export function createVideoLinkRoutes(deps: { url: z.string().min(1).max(4096), pastedToken: z.string().min(1).max(4096), threadId: z.string().max(200).optional(), + /** A project's new chat, before its thread exists: what the link's + * transcription costs counts toward it. */ + projectId: z.string().max(128).optional(), userLocale: z.string().max(35).optional(), }) .safeParse(await c.req.json().catch(() => null)); @@ -80,6 +84,24 @@ export function createVideoLinkRoutes(deps: { body.data.threadId, ); } + // A thread names its own project; a project named beside none must be + // one the member may chat in. + const projectId = + body.data.threadId === undefined ? body.data.projectId : undefined; + if (projectId !== undefined) { + const access = await projectChatAccess(deps.sql, { + projectId, + organizationId: c.get('orgId'), + userId, + }); + if (access !== 'ok') { + throw new VideoLinkError( + 'projectUnavailable', + 'Project unavailable', + 403, + ); + } + } await checkOrganizationRateLimit(deps.sql, 'file:upload', c.get('orgId')); const jobId = await ingestVideoUrl(deps.sql, { organizationId: c.get('orgId'), @@ -87,6 +109,7 @@ export function createVideoLinkRoutes(deps: { ...(body.data.threadId !== undefined ? { threadId: body.data.threadId } : {}), + ...(projectId !== undefined ? { projectId } : {}), url: body.data.url, pastedToken: body.data.pastedToken, ...(body.data.userLocale !== undefined diff --git a/services/platform/backend/domains/video_links/service.inflight_cap.test.ts b/services/platform/backend/domains/video_links/service.inflight_cap.test.ts index 88d86def6a..4bb9cffbdb 100644 --- a/services/platform/backend/domains/video_links/service.inflight_cap.test.ts +++ b/services/platform/backend/domains/video_links/service.inflight_cap.test.ts @@ -305,14 +305,21 @@ describe('ingestVideoUrl at a usage limit [GOV-R4]', () => { }); const fake = fakeSql({ inFlight: 0 }); - await expect(ingestVideoUrl(fake.sql, pasteArgs)).rejects.toMatchObject({ + // Pasted into a project's new chat: the composer named the project. + await expect( + ingestVideoUrl(fake.sql, { ...pasteArgs, projectId: 'project-1' }), + ).rejects.toMatchObject({ code: 'budgetExceeded', status: 429, message: expect.stringContaining('Your monthly cost limit is used up'), }); expect(directCallBlocked).toHaveBeenCalledWith(fake.sql, { organizationId: 'org-1', - subject: { userId: 'user-1', agentSlug: '__transcription__' }, + subject: { + userId: 'user-1', + agentSlug: '__transcription__', + projectIds: ['project-1'], + }, }); expect( fake.statements.some((s) => diff --git a/services/platform/backend/domains/video_links/service.ts b/services/platform/backend/domains/video_links/service.ts index 309faf4f81..f6ada724f3 100644 --- a/services/platform/backend/domains/video_links/service.ts +++ b/services/platform/backend/domains/video_links/service.ts @@ -103,6 +103,9 @@ export interface VideoLinkJobRow { id: string; organizationId: string; threadId: string | null; + /** The project of the new chat the link was pasted into, before its + * thread existed (0158). */ + projectId: string | null; uploadedBy: string; sourceUrl: string; sourceUrlHash: string; @@ -131,6 +134,7 @@ export interface VideoLinkJobRow { const JOB_COLUMNS = ` id, org_id AS "organizationId", thread_id AS "threadId", + project_id AS "projectId", uploaded_by AS "uploadedBy", source_url AS "sourceUrl", source_url_hash AS "sourceUrlHash", source_platform AS "sourcePlatform", pasted_token AS "pastedToken", video_title AS "videoTitle", @@ -656,6 +660,7 @@ function videoShimHandlers(sql: Sql): ShimHandlers { _creationTime: job.createdAt, organizationId: job.organizationId, threadId: job.threadId ?? undefined, + projectId: job.projectId ?? undefined, uploadedBy: job.uploadedBy, sourceUrl: job.sourceUrl, sourceUrlHash: job.sourceUrlHash, @@ -702,17 +707,19 @@ function videoShimHandlers(sql: Sql): ShimHandlers { source?: string; uploadedBy?: string; threadId?: string; + projectId?: string; }; return sql.begin(async (tx) => { const inserted = await tx<{ id: string }[]>` INSERT INTO app.file_metadata ( org_id, storage_ref, file_name, content_type, size, source, - uploaded_by, thread_id, transcription_status, created_at_ms + uploaded_by, thread_id, project_id, transcription_status, + created_at_ms ) VALUES ( ${args.organizationId}, ${args.storageId}, ${args.fileName}, ${args.contentType}, ${args.size}, ${args.source ?? null}, - ${args.uploadedBy ?? null}, ${args.threadId ?? null}, 'queued', - ${Date.now()} + ${args.uploadedBy ?? null}, ${args.threadId ?? null}, + ${args.projectId ?? null}, 'queued', ${Date.now()} ) RETURNING id `; @@ -978,12 +985,20 @@ async function assertInFlightCapInTx( */ async function assertVideoBudget( sql: Sql, - args: { organizationId: string; userId: string; threadId?: string | null }, + args: { + organizationId: string; + userId: string; + threadId?: string | null; + projectId?: string | null; + }, ): Promise { + // The chat's project: the one the composer named for a new chat, else + // the thread's (a thread the member owns — the door checks it). const projectId = - args.threadId != null + args.projectId ?? + (args.threadId != null ? await readThreadProjectId(sql, args.organizationId, args.threadId) - : undefined; + : undefined); const violation = await directCallBlocked(sql, { organizationId: args.organizationId, subject: { @@ -1003,9 +1018,10 @@ async function assertVideoBudget( /** * Ingest a pasted video URL (the 0.4 `ingestVideoUrl`): playlist refusal, - * budget gate (worst-case prospective Whisper cost), server-derived dedup - * key + platform, in-thread dedup, org-wide donor clone (before — and - * exempt from — the in-flight cap), cap, insert + `video.ingest` job. + * server-derived dedup key + platform, in-thread dedup, org-wide donor + * clone (before — and exempt from — the in-flight cap and the budget), the + * budget gate before a fresh download (`assertVideoBudget`), cap, insert + + * `video.ingest` job. * The route owns org membership + thread access + the rate limit. */ export async function ingestVideoUrl( @@ -1014,6 +1030,9 @@ export async function ingestVideoUrl( organizationId: string; userId: string; threadId?: string; + /** A project's new chat, before its thread exists — one the member may + * chat in (the door checks): the link's transcription counts toward it. */ + projectId?: string; url: string; pastedToken: string; userLocale?: string; @@ -1133,13 +1152,14 @@ export async function ingestVideoUrl( await assertInFlightCapInTx(tx, args.organizationId); const rows = await tx<{ id: string }[]>` INSERT INTO app.video_link_jobs ( - org_id, thread_id, uploaded_by, source_url, source_url_hash, - source_platform, pasted_token, status, status_changed_at_ms, - attempts, lifecycle_status, created_at_ms + org_id, thread_id, project_id, uploaded_by, source_url, + source_url_hash, source_platform, pasted_token, status, + status_changed_at_ms, attempts, lifecycle_status, created_at_ms ) VALUES ( - ${args.organizationId}, ${args.threadId ?? null}, ${args.userId}, - ${args.url}, ${sourceUrlHash}, ${serverPlatform}, - ${args.pastedToken}, 'queued', ${now}, 0, 'active', ${now} + ${args.organizationId}, ${args.threadId ?? null}, + ${args.projectId ?? null}, ${args.userId}, ${args.url}, + ${sourceUrlHash}, ${serverPlatform}, ${args.pastedToken}, 'queued', + ${now}, 0, 'active', ${now} ) RETURNING id `; @@ -1458,6 +1478,7 @@ export async function retryVideoLink( organizationId: args.organizationId, userId: args.userId, threadId: job.threadId, + projectId: job.projectId, }); // Fast-fail on the pool BEFORE the cleanup below deletes the failed job's // blob and file row: a retry the cap refuses should leave them in place. diff --git a/services/platform/messages/de/chat.yml b/services/platform/messages/de/chat.yml index acb01ac6b3..6112568522 100644 --- a/services/platform/messages/de/chat.yml +++ b/services/platform/messages/de/chat.yml @@ -286,6 +286,7 @@ videoLink: notUploader: Nur die Person, die dieses Video hinzugefügt hat, kann es ändern notRetryable: Erneuter Versuch gerade nicht möglich — das Video wird womöglich schon wieder verarbeitet threadNotFound: Dieser Chat ist nicht mehr verfügbar + projectUnavailable: Dieses Projekt ist für dich nicht mehr verfügbar. Füge den Link in einen anderen Chat ein. actions: removeLink: Entfernen retry: Erneut versuchen diff --git a/services/platform/messages/en/chat.yml b/services/platform/messages/en/chat.yml index 43893fcbe7..19e953f6cd 100644 --- a/services/platform/messages/en/chat.yml +++ b/services/platform/messages/en/chat.yml @@ -284,6 +284,7 @@ videoLink: notUploader: Only the person who added this video can change it notRetryable: Can't retry right now — the video may already be processing again threadNotFound: This chat is no longer available + projectUnavailable: "This project isn't available to you any more. Paste the link into another chat." actions: removeLink: Remove retry: Try again diff --git a/services/platform/messages/fr/chat.yml b/services/platform/messages/fr/chat.yml index a20d391f04..7820466b4c 100644 --- a/services/platform/messages/fr/chat.yml +++ b/services/platform/messages/fr/chat.yml @@ -285,6 +285,7 @@ videoLink: notUploader: Seule la personne qui a ajouté cette vidéo peut la modifier notRetryable: Nouvelle tentative impossible pour le moment — la vidéo est peut-être déjà en cours de traitement threadNotFound: Ce chat n'est plus disponible + projectUnavailable: "Ce projet ne t'est plus accessible. Colle le lien dans un autre chat." actions: removeLink: Retirer retry: Réessayer From 8e82676bc3113aa64cd74b6f9c5db34fcad6b247 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 12:03:28 +0200 Subject: [PATCH 49/57] fix(platform): book only what a kept recording had transcribed A recording removed mid-way went on chunk by chunk, every minute billed. Its transcription now stops before the next chunk and books the minutes already heard. Each chunk counts the moment the provider answers, so a later fault cannot drop minutes already billed, and a failed booking is tried twice more before it is given up. A completion never overwrites a recording its uploader removed. A dictation holds for two minutes at most, and a clip whose length cannot be read is held at the longest its size allows. A video link whose audio a usage limit refused fails as budgetExceeded, not as a transcription fault. --- .../transcribe_audio.metering.test.ts | 60 +++++++++++++- .../core/file_metadata/transcribe_audio.ts | 48 +++++++++-- .../files/transcription-metering.test.ts | 25 ++++++ .../domains/files/transcription-metering.ts | 50 +++++++---- .../domains/files/transcription.patch.test.ts | 82 +++++++++++++++++++ .../backend/domains/files/transcription.ts | 45 ++++++++-- .../backend/domains/video_links/service.ts | 5 +- 7 files changed, 284 insertions(+), 31 deletions(-) create mode 100644 services/platform/backend/domains/files/transcription.patch.test.ts diff --git a/services/platform/backend/core/file_metadata/transcribe_audio.metering.test.ts b/services/platform/backend/core/file_metadata/transcribe_audio.metering.test.ts index b4e1e438d8..277ab5d039 100644 --- a/services/platform/backend/core/file_metadata/transcribe_audio.metering.test.ts +++ b/services/platform/backend/core/file_metadata/transcribe_audio.metering.test.ts @@ -60,12 +60,22 @@ let admission: unknown; const mutations: Array<{ name: string; args: Record }> = []; const scheduled: unknown[] = []; -function fakeCtx(options: { settleFails?: boolean } = {}) { +function fakeCtx( + options: { + settleFails?: boolean; + /** The row's status as each read finds it, in order; `queued` after. */ + statuses?: (string | null)[]; + } = {}, +) { + const statuses = [...(options.statuses ?? [])]; return { runQuery: vi.fn(async (ref: unknown) => { const name = functionRefName(ref); if (name === 'file_metadata/internal_queries:getByStorageId') { - return { transcriptionStatus: 'queued', uploadedBy: 'user-1' }; + const status = statuses.length > 0 ? statuses.shift() : 'queued'; + return status === null + ? null + : { transcriptionStatus: status, uploadedBy: 'user-1' }; } return null; }), @@ -235,4 +245,50 @@ describe('transcribeAudioImpl and the uploader’s limits', () => { ).toBe(false); expect(scheduled).toEqual([]); }); + + it('stops at a removal mid-way, booking the chunks already transcribed', async () => { + compressedTo(120, Number.MAX_SAFE_INTEGER); + mocks.chunkCompressedAudio.mockResolvedValue({ + chunks: [ + { blob: new Blob([new Uint8Array(2)]), durationSec: 60, index: 0 }, + { blob: new Blob([new Uint8Array(2)]), durationSec: 60, index: 1 }, + ], + cleanup: vi.fn(async () => undefined), + }); + mocks.requestTranscription.mockResolvedValueOnce({ + text: 'One.', + segments: [], + duration: 60, + }); + + // The pre-check finds it queued; before chunk 2 it reads `skipped`. + await transcribeAudioImpl( + fakeCtx({ statuses: ['queued', 'skipped'] }) as never, + ARGS, + ); + + expect(mocks.requestTranscription).toHaveBeenCalledTimes(1); + expect(called(':settleTranscriptionCall')[0]?.args).toMatchObject({ + audioDurationSec: 60, + }); + expect( + called(':updateFileTranscription').some( + (mutation) => mutation.args.transcriptionStatus === 'completed', + ), + ).toBe(false); + }); + + it('tells a video link that handed its audio over that a usage limit refused it', async () => { + admission = { + allowed: false, + reason: 'Usage limit reached. Your monthly cost limit is used up.', + }; + + await transcribeAudioImpl(fakeCtx() as never, ARGS); + + const failed = called(':updateFileTranscription').find( + (mutation) => mutation.args.transcriptionStatus === 'failed', + ); + expect(failed?.args.transcriptionErrorCode).toBe('budgetExceeded'); + }); }); diff --git a/services/platform/backend/core/file_metadata/transcribe_audio.ts b/services/platform/backend/core/file_metadata/transcribe_audio.ts index 34d53430af..2717203ad8 100644 --- a/services/platform/backend/core/file_metadata/transcribe_audio.ts +++ b/services/platform/backend/core/file_metadata/transcribe_audio.ts @@ -200,9 +200,10 @@ function readTranscriptionAdmission( ); } -/** Book what the attempt transcribed in its hold's place, or release the - * hold of one that transcribed nothing. Never throws: the transcript, or - * the failure being recorded, matters more than its booking. */ +/** Book what the attempt transcribed in its hold's place (the booking + * tries itself again), or release the hold of one that transcribed + * nothing. Never throws: the transcript, or the failure being recorded, + * matters more than its booking. */ async function closeTranscriptionCall( ctx: ActionCtx, lease: unknown, @@ -229,6 +230,20 @@ async function closeTranscriptionCall( } } +/** Whether the recording is still wanted: a removal skips its + * transcription, a deletion drops its row — either way, no further minute + * is sent to the provider or charged. */ +async function stillWanted( + ctx: ActionCtx, + storageId: BlobRef, +): Promise { + const row = await ctx.runQuery( + internal.file_metadata.internal_queries.getByStorageId, + { storageId }, + ); + return row !== null && row.transcriptionStatus !== 'skipped'; +} + /** The pipeline body, hoisted so the 0.5 backend can run it on a ctx shim * (the wrapper above keeps the 0.4 wiring). */ export async function transcribeAudioImpl( @@ -456,6 +471,23 @@ export async function transcribeAudioImpl( let totalDurationSec = 0; let chunkStartSec = 0; for (const chunk of chunks) { + if (chunk.index > 0 && !(await stillWanted(ctx, args.storageId))) { + // Removed mid-way: book the minutes already transcribed, send no + // more, and leave the row as the removal left it. + await closeTranscriptionCall(ctx, lease, model, transcribedSec); + lease = undefined; + console.log( + JSON.stringify({ + event: 'transcription.cancelled', + requestId, + storageId: args.storageId, + status: 'removed_mid_way', + attempt, + transcribedSec, + }), + ); + return null; + } const progressLabel = chunks.length === 1 ? 'transcribing' @@ -468,6 +500,10 @@ export async function transcribeAudioImpl( fileName: chunkFileName(args.fileName, chunk), timeoutMs: TRANSCRIBE_API_TIMEOUT_MS, }); + // Billed the moment the provider answered: counted before anything + // below can throw. + const chunkDuration = result.duration ?? chunk.durationSec; + transcribedSec += chunkDuration; // Timestamps are only meaningful for video-link transcripts — // they let the agent cite "Chapter 3 @ 12:34" in summaries. // Regular microphone recordings don't carry that context, so @@ -485,9 +521,7 @@ export async function transcribeAudioImpl( if (paragraphs.length > 0) { chunkParagraphs.push(paragraphs); } - const chunkDuration = result.duration ?? chunk.durationSec; totalDurationSec += chunkDuration; - transcribedSec += chunkDuration; chunkStartSec += chunkDuration; // Heartbeat any video-link job that's tracking this storageId so its @@ -636,6 +670,10 @@ export async function transcribeAudioImpl( transcriptionStatus: 'failed', transcriptionError: sanitized, transcriptionProgress: '', + // A video link that handed its audio over says why it failed. + ...(classification.reason === 'budget_exceeded' + ? { transcriptionErrorCode: 'budgetExceeded' } + : {}), }, ); return null; diff --git a/services/platform/backend/domains/files/transcription-metering.test.ts b/services/platform/backend/domains/files/transcription-metering.test.ts index 7db23c9fcb..30b085d07d 100644 --- a/services/platform/backend/domains/files/transcription-metering.test.ts +++ b/services/platform/backend/domains/files/transcription-metering.test.ts @@ -207,6 +207,31 @@ describe('transcribeDictation', () => { ); }); + it('holds the longest the clip’s size allows when its length cannot be read, for at most two minutes', async () => { + mocks.probeAudioDurationSec.mockResolvedValueOnce(0); + mocks.requestTranscription.mockResolvedValue({ text: 'Hi.' }); + + await transcribeDictation(sql, { + ...DICTATION, + audio: new Uint8Array(60_000), + }); + + expect(mocks.openDirectCall).toHaveBeenCalledWith( + sql, + expect.objectContaining({ + // 60 000 bytes at 2 000 a second: 30 s at 0.6¢ a minute. + worstCase: { cents: 0.3, tokens: 0 }, + maxDurationMs: 120_000, + }), + ); + // No length from the provider either: the bound is booked, never 0. + expect(mocks.settleDirectCall).toHaveBeenCalledWith( + sql, + LEASE, + expect.objectContaining({ audioDurationSec: 30 }), + ); + }); + it('refuses with 429 BUDGET_EXCEEDED before the provider hears it [GOV-R4]', async () => { mocks.openDirectCall.mockResolvedValue({ allowed: false, diff --git a/services/platform/backend/domains/files/transcription-metering.ts b/services/platform/backend/domains/files/transcription-metering.ts index 83cd5c332f..e15a4cec15 100644 --- a/services/platform/backend/domains/files/transcription-metering.ts +++ b/services/platform/backend/domains/files/transcription-metering.ts @@ -50,12 +50,14 @@ export type TranscriptionAdmission = cancelled?: true; }; -/** Hold a transcription's whole length under `subject`. */ +/** Hold a transcription's whole length under `subject`, for at most + * `maxDurationMs` — an upload's job lease by default. */ export async function openTranscriptionCall( sql: Sql, args: TranscriptionModelFacts & { subject: DirectCallSubject; audioDurationSec: number; + maxDurationMs?: number; }, ): Promise { const admission = await openDirectCall(sql, { @@ -70,7 +72,7 @@ export async function openTranscriptionCall( tokens: 0, }, modelRef: `${args.provider}/${args.model}`, - maxDurationMs: TRANSCRIPTION_CALL_MAX_MS, + maxDurationMs: args.maxDurationMs ?? TRANSCRIPTION_CALL_MAX_MS, }); return admission.allowed ? { allowed: true, lease: admission.lease } @@ -123,7 +125,13 @@ export async function uploadTranscriptionSubject( }; } -/** Book the minutes the provider transcribed in the hold's place. */ +/** The pause before each further attempt at a booking: the provider has + * billed the minutes, so one failed write must not lose them, and a settle + * books once however often it is sent. */ +const SETTLE_RETRY_DELAYS_MS = [1_000, 3_000] as const; + +/** Book the minutes the provider transcribed in the hold's place — tried + * again twice before the failure is the caller's. */ export async function settleTranscriptionCall( sql: Sql, args: TranscriptionModelFacts & { @@ -131,17 +139,31 @@ export async function settleTranscriptionCall( audioDurationSec: number; }, ): Promise { - await settleDirectCall(sql, args.lease, { - provider: args.provider, - model: args.model, - inputTokens: 0, - outputTokens: 0, - costCents: estimateTranscriptionCostCents( - args.audioDurationSec, - args.centsPerAudioMinute, - ), - audioDurationSec: args.audioDurationSec, - }); + const settle = () => + settleDirectCall(sql, args.lease, { + provider: args.provider, + model: args.model, + inputTokens: 0, + outputTokens: 0, + costCents: estimateTranscriptionCostCents( + args.audioDurationSec, + args.centsPerAudioMinute, + ), + audioDurationSec: args.audioDurationSec, + }); + for (const delayMs of SETTLE_RETRY_DELAYS_MS) { + try { + await settle(); + return; + } catch (error) { + console.warn( + `[transcription] booking failed; trying again in ${delayMs} ms:`, + error, + ); + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + } + await settle(); } /** Release the hold of a transcription that transcribed nothing. */ diff --git a/services/platform/backend/domains/files/transcription.patch.test.ts b/services/platform/backend/domains/files/transcription.patch.test.ts new file mode 100644 index 0000000000..f92530370d --- /dev/null +++ b/services/platform/backend/domains/files/transcription.patch.test.ts @@ -0,0 +1,82 @@ +/** + * A transcription's terminal write: a completion never lands on a recording + * that was removed (`skipped`) while it was transcribed — and a video link + * that handed its audio over is then left as the removal settled it. A + * failure carries its code to that video link, so a reached usage limit + * reads as one there. + */ + +import type { Sql } from 'postgres'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { settleHandoffJobsByStorageRef } = vi.hoisted(() => ({ + settleHandoffJobsByStorageRef: vi.fn(async () => undefined), +})); +vi.mock('../video_links/service.ts', () => ({ settleHandoffJobsByStorageRef })); +vi.mock('../chat/shim.ts', () => ({ chatShimHandlers: () => ({}) })); + +const { transcriptionHandlers } = await import('./transcription.ts'); + +/** A file row in `status`: an UPDATE answers it unless its guard holds it + * back (a completion over a removal). */ +function fakeSql(status: string): Sql { + const tag = (strings: TemplateStringsArray, ...values: unknown[]) => { + const text = strings.join('?'); + if (text.includes('UPDATE app.file_metadata SET')) { + const completing = values.includes('completed'); + return Promise.resolve( + completing && status === 'skipped' ? [] : [{ id: 'file-1' }], + ); + } + return Promise.resolve([]); + }; + const sql = Object.assign(tag, { + unsafe: (text: string) => text, + begin: async (work: (tx: unknown) => Promise) => work(sql), + }); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return sql as unknown as Sql; +} + +const update = (sql: Sql, patch: Record) => + transcriptionHandlers(sql)[ + 'file_metadata/internal_mutations:updateFileTranscription' + ]?.({ storageId: 's3:org/rec', ...patch }); + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe('updateFileTranscription', () => { + it('lands no completion on a recording removed while it was transcribed', async () => { + await update(fakeSql('skipped'), { + transcriptionStatus: 'completed', + transcript: 'Hello.', + }); + expect(settleHandoffJobsByStorageRef).not.toHaveBeenCalled(); + }); + + it('settles the video link of a finished transcription', async () => { + const sql = fakeSql('running'); + await update(sql, { transcriptionStatus: 'completed', transcript: 'Hi.' }); + expect(settleHandoffJobsByStorageRef).toHaveBeenCalledWith(sql, { + storageId: 's3:org/rec', + transcriptionStatus: 'completed', + }); + }); + + it('hands a failure’s code to its video link', async () => { + const sql = fakeSql('running'); + await update(sql, { + transcriptionStatus: 'failed', + transcriptionError: 'Usage limit reached.', + transcriptionErrorCode: 'budgetExceeded', + }); + expect(settleHandoffJobsByStorageRef).toHaveBeenCalledWith(sql, { + storageId: 's3:org/rec', + transcriptionStatus: 'failed', + errorMessage: 'Usage limit reached.', + reasonCode: 'budgetExceeded', + }); + }); +}); diff --git a/services/platform/backend/domains/files/transcription.ts b/services/platform/backend/domains/files/transcription.ts index 83128bee0c..2fb2d18d1f 100644 --- a/services/platform/backend/domains/files/transcription.ts +++ b/services/platform/backend/domains/files/transcription.ts @@ -44,6 +44,13 @@ import { const DICTATION_TIMEOUT_MS = 60_000; const MAX_DICTATION_BYTES = 8 * 1024 * 1024; +/** The longest a dictation may hold its length: its one request's timeout, + * with room to spare. */ +const DICTATION_CALL_MAX_MS = 2 * 60 * 1000; +/** The fewest bytes a second of recorded speech takes (16 kbit/s, below + * what a browser's recorder writes): a clip whose length cannot be read is + * held at its size over this — never shorter than it can be. */ +const MIN_DICTATION_BYTES_PER_SECOND = 2_000; // ------------------------------------------------------------ row verbs @@ -53,15 +60,20 @@ interface TranscriptionRowPatch { transcriptionDurationSec?: number; transcriptionProgress?: string; transcriptionError?: string; + /** Why a failed transcription failed, for the video-link job that handed + * its audio over (`budgetExceeded`); not stored on the file row. */ + transcriptionErrorCode?: string; contentHash?: string; } +/** Write the patch; false when nothing changed — a completion never lands + * on a recording that was removed (`skipped`) while it was transcribed. */ async function applyTranscriptionPatch( db: Sql | TransactionSql, storageRef: string, patch: TranscriptionRowPatch, -): Promise { - await db` +): Promise { + const rows = await db<{ id: string }[]>` UPDATE app.file_metadata SET transcription_status = ${patch.transcriptionStatus !== undefined ? patch.transcriptionStatus : db.unsafe('transcription_status')}, transcript = ${patch.transcript !== undefined ? patch.transcript : db.unsafe('transcript')}, @@ -71,7 +83,11 @@ async function applyTranscriptionPatch( content_hash = ${patch.contentHash !== undefined ? patch.contentHash : db.unsafe('content_hash')}, status_changed_at_ms = ${patch.transcriptionStatus !== undefined ? Date.now() : db.unsafe('status_changed_at_ms')} WHERE storage_ref = ${storageRef} + AND (${patch.transcriptionStatus !== 'completed'} + OR transcription_status IS DISTINCT FROM 'skipped') + RETURNING id `; + return rows.length > 0; } async function updateFileTranscription( @@ -89,13 +105,16 @@ async function updateFileTranscription( // whisper jobs parked in 'transcribing_handoff' forever (holding an org // ingest slot each and making the chip's Retry 409). await sql.begin(async (tx) => { - await applyTranscriptionPatch(tx, storageRef, patch); + if (!(await applyTranscriptionPatch(tx, storageRef, patch))) return; await settleHandoffJobsByStorageRef(tx, { storageId: storageRef, transcriptionStatus: status, ...(patch.transcriptionError !== undefined ? { errorMessage: patch.transcriptionError } : {}), + ...(patch.transcriptionErrorCode !== undefined + ? { reasonCode: patch.transcriptionErrorCode } + : {}), }); }); } @@ -144,7 +163,9 @@ export async function acquireTranscriptionLease( // ------------------------------------------------------------- crawl host -function transcriptionHandlers(sql: Sql): ShimHandlers { +/** The handler map the reused upload pipeline dispatches through. + * Exported for tests only; production reaches it through the job. */ +export function transcriptionHandlers(sql: Sql): ShimHandlers { return { ...chatShimHandlers(sql), 'file_metadata/internal_queries:getByStorageId': async (raw) => { @@ -476,8 +497,8 @@ export async function transcribeDictation( const fileName = `dictation.${ext}`; // A dictation is the dictating member's spend: its length is held // before the provider hears it, and refused when a limit has too little - // room for it. The length is read off the clip itself — 0 when its - // container names none, which still holds and counts the request. + // room for it. The length is read off the clip itself; when its container + // names none, the longest the clip's size allows stands in. const model = { organizationId: args.organizationId, provider: modelData.providerName, @@ -492,10 +513,15 @@ export async function transcribeDictation( return 0; }, ); + const heldSec = + probedSec > 0 + ? probedSec + : args.audio.byteLength / MIN_DICTATION_BYTES_PER_SECOND; const admission = await openTranscriptionCall(sql, { ...model, subject: { userId: args.userId, agentSlug: TRANSCRIPTION_SLUG }, - audioDurationSec: probedSec, + audioDurationSec: heldSec, + maxDurationMs: DICTATION_CALL_MAX_MS, }); if (!admission.allowed) { throw new FileError('BUDGET_EXCEEDED', admission.reason, 429); @@ -521,8 +547,9 @@ export async function transcribeDictation( } const text = result.text ?? ''; - // What the provider reports it heard, else the clip's own length. - const durationSec = result.duration ?? probedSec; + // What the provider reports it heard, else the clip's own length — else + // the longest its size allows, never nothing for minutes it was billed. + const durationSec = result.duration ?? heldSec; await settleTranscriptionCall(sql, { ...model, lease: admission.lease, diff --git a/services/platform/backend/domains/video_links/service.ts b/services/platform/backend/domains/video_links/service.ts index f6ada724f3..95559f9cf7 100644 --- a/services/platform/backend/domains/video_links/service.ts +++ b/services/platform/backend/domains/video_links/service.ts @@ -483,6 +483,9 @@ export async function settleHandoffJobsByStorageRef( storageId: string; transcriptionStatus: 'completed' | 'failed' | 'skipped'; errorMessage?: string; + /** Why the transcription failed, when it knows (`budgetExceeded`); + * a plain transcription failure otherwise. */ + reasonCode?: string; }, ): Promise { const now = Date.now(); @@ -492,7 +495,7 @@ export async function settleHandoffJobsByStorageRef( status = 'failed', status_changed_at_ms = ${now}, progress = NULL, - error_reason_code = 'whisperFailed', + error_reason_code = ${args.reasonCode === 'budgetExceeded' ? 'budgetExceeded' : 'whisperFailed'}, error_message = ${args.errorMessage ?? 'Whisper transcription failed'} WHERE status = 'transcribing_handoff' AND storage_ref = ${args.storageId} RETURNING id, org_id AS "organizationId", uploaded_by AS "uploadedBy" From 7e0b737ad8c0324e6c3c278f5b22f4617e29a27d Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 12:03:40 +0200 Subject: [PATCH 50/57] fix(platform): say a recording's usage limit in the reader's language A transcription refused by a usage limit showed the server's English sentence on the composer chip. The chip now reads Usage limit reached in the reader's language, with a hint at where the limit's reset shows. The refusal's opening words live in one shared constant that the server writes and the chip reads. The German dictation refusal reads correctly. --- .../components/composer-attachments.test.tsx | 85 +++++++++++++++++++ .../chat/components/composer-attachments.tsx | 10 ++- .../domains/governance/budget-refusal.ts | 5 +- services/platform/lib/shared/usage-limit.ts | 15 ++++ services/platform/messages/de/chat.yml | 4 +- services/platform/messages/en/chat.yml | 2 + services/platform/messages/fr/chat.yml | 2 + 7 files changed, 119 insertions(+), 4 deletions(-) create mode 100644 services/platform/app/features/chat/components/composer-attachments.test.tsx create mode 100644 services/platform/lib/shared/usage-limit.ts diff --git a/services/platform/app/features/chat/components/composer-attachments.test.tsx b/services/platform/app/features/chat/components/composer-attachments.test.tsx new file mode 100644 index 0000000000..7867e47a97 --- /dev/null +++ b/services/platform/app/features/chat/components/composer-attachments.test.tsx @@ -0,0 +1,85 @@ +// @vitest-environment jsdom +/** + * A staged recording's chip when its transcription failed. A usage limit + * refuses it with the server's English sentence; the chip says so in the + * reader's language and points at where the limit's reset shows, while any + * other failure keeps its stored reason on hover. + */ +import '@testing-library/jest-dom/vitest'; +import { LOCALE_STORAGE_KEY } from '@tale/ui/i18n/detect-locale'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import type { FileTranscriptionInfo } from '@/app/features/chat/hooks/use-file-transcription-status'; +import type { BlobRef } from '@/backend/core/lib/storage/blob_ref'; +import { USAGE_LIMIT_REFUSAL_PREFIX } from '@/lib/shared/usage-limit'; +import { checkAccessibility } from '@/tests/utils/a11y'; +import { i18n } from '@/tests/utils/i18n-all-languages'; +import { render, screen } from '@/tests/utils/render'; + +import { ComposerAttachments } from './composer-attachments'; + +vi.mock('@/app/features/shared/files/use-file-url', () => ({ + useFileUrl: () => ({ data: null }), +})); + +// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a staged upload's ref, as the composer holds it +const REF = 's3:blobs/acme/memo' as BlobRef; + +function renderChip(info: FileTranscriptionInfo) { + return render( + , + ); +} + +const t = (key: string) => i18n.t(key, { ns: 'chat' }); + +afterEach(async () => { + localStorage.removeItem(LOCALE_STORAGE_KEY); + await i18n.changeLanguage('en'); +}); + +describe('a staged recording whose transcription failed', () => { + it('says a usage limit stopped it, in the reader’s language', async () => { + localStorage.setItem(LOCALE_STORAGE_KEY, 'de'); + await i18n.changeLanguage('de'); + const de = i18n.getFixedT('de', 'chat'); + const { container } = renderChip({ + status: 'failed', + error: `${USAGE_LIMIT_REFUSAL_PREFIX} Your monthly cost limit resets on 1 November.`, + }); + + const label = screen.getByText(de('transcription.limitReached')); + expect(label).toBeVisible(); + expect(label).toHaveAttribute( + 'title', + de('transcription.limitReachedHint'), + ); + expect(screen.queryByText(/Usage limit reached/)).not.toBeInTheDocument(); + expect( + screen.getByRole('button', { name: de('transcription.retry') }), + ).toBeVisible(); + await checkAccessibility(container); + }); + + it('keeps any other failure’s reason on hover', () => { + renderChip({ status: 'failed', error: 'The audio could not be decoded.' }); + + const label = screen.getByText(t('transcription.couldNotTranscribe')); + expect(label).toHaveAttribute('title', 'The audio could not be decoded.'); + }); +}); diff --git a/services/platform/app/features/chat/components/composer-attachments.tsx b/services/platform/app/features/chat/components/composer-attachments.tsx index e880105006..9373fcddd0 100644 --- a/services/platform/app/features/chat/components/composer-attachments.tsx +++ b/services/platform/app/features/chat/components/composer-attachments.tsx @@ -32,6 +32,7 @@ import { ImagePreviewDialog } from '@/app/features/shared/markdown/image-preview import type { BlobRef } from '@/backend/core/lib/storage/blob_ref'; import { useT } from '@/lib/i18n/client'; import { isAudioOrVideo, isImage } from '@/lib/shared/file-types'; +import { isUsageLimitRefusal } from '@/lib/shared/usage-limit'; import { transcriptionUnavailableKey } from '../utils/transcription-availability'; @@ -122,12 +123,17 @@ function StagedMedia({ const inFlight = status === 'queued' || status === 'running'; const failed = status === 'failed'; const completed = status === 'completed'; + // A reached usage limit is said in the reader's language, never as the + // server's English sentence. + const limited = failed && isUsageLimitRefusal(info?.error); let statusLabel: string; if (inFlight) { statusLabel = info?.progress || t('transcription.transcribing'); } else if (completed) { statusLabel = t('transcription.transcribed'); + } else if (limited) { + statusLabel = t('transcription.limitReached'); } else if (failed || status === 'skipped') { statusLabel = t('transcription.couldNotTranscribe'); } else { @@ -165,7 +171,9 @@ function StagedMedia({ failed ? transcriptionAvailable === false ? t(transcriptionUnavailableKey(transcriptionUnavailableReason)) - : info?.error + : limited + ? t('transcription.limitReachedHint') + : info?.error : undefined } > diff --git a/services/platform/backend/domains/governance/budget-refusal.ts b/services/platform/backend/domains/governance/budget-refusal.ts index da153fd9eb..205519e7a0 100644 --- a/services/platform/backend/domains/governance/budget-refusal.ts +++ b/services/platform/backend/domains/governance/budget-refusal.ts @@ -1,3 +1,4 @@ +import { USAGE_LIMIT_REFUSAL_PREFIX } from '../../../lib/shared/usage-limit.ts'; import type { BudgetScope, BudgetViolation } from './budget-gate.ts'; const BUCKET_OWNER: Record = { @@ -29,6 +30,6 @@ export function budgetCapPhrase(violation: BudgetViolation): string { export function budgetRefusalMessage(violation: BudgetViolation): string { const until = new Date(violation.resetsAt).toISOString(); return violation.used < violation.limit - ? `Usage limit reached. ${budgetCapPhrase(violation)} leaves too little for this request until ${until}.` - : `Usage limit reached. ${budgetCapPhrase(violation)} is used up until ${until}.`; + ? `${USAGE_LIMIT_REFUSAL_PREFIX} ${budgetCapPhrase(violation)} leaves too little for this request until ${until}.` + : `${USAGE_LIMIT_REFUSAL_PREFIX} ${budgetCapPhrase(violation)} is used up until ${until}.`; } diff --git a/services/platform/lib/shared/usage-limit.ts b/services/platform/lib/shared/usage-limit.ts new file mode 100644 index 0000000000..77a3cd45a7 --- /dev/null +++ b/services/platform/lib/shared/usage-limit.ts @@ -0,0 +1,15 @@ +/** + * Every budget refusal's sentence begins with this + * (`backend/domains/governance/budget-refusal.ts`), whichever lane refused — + * so a surface that only has the stored text, such as a failed + * transcription's error, still recognises a reached usage limit and can say + * it in the reader's language. + */ +export const USAGE_LIMIT_REFUSAL_PREFIX = 'Usage limit reached.'; + +/** Whether a stored failure sentence is a budget refusal. */ +export function isUsageLimitRefusal(text: string | null | undefined): boolean { + return ( + typeof text === 'string' && text.startsWith(USAGE_LIMIT_REFUSAL_PREFIX) + ); +} diff --git a/services/platform/messages/de/chat.yml b/services/platform/messages/de/chat.yml index 6112568522..2a684a70cf 100644 --- a/services/platform/messages/de/chat.yml +++ b/services/platform/messages/de/chat.yml @@ -217,6 +217,8 @@ transcription: transcribing: Transkribiere… transcribed: Transkribiert couldNotTranscribe: Transkription fehlgeschlagen + limitReached: Nutzungslimit erreicht + limitReachedHint: Ein Nutzungslimit, das für dich gilt, ist erreicht. Unter Einstellungen > Nutzung siehst du, wann es zurückgesetzt wird; wähle Erneut versuchen, sobald es zurückgesetzt oder erhöht wurde. viewTranscript: Transkript anzeigen previewSubtitle: '{seconds}s transkribiert' retry: Erneut versuchen @@ -390,7 +392,7 @@ dictation: discard: Aufnahme verwerfen permissionDenied: Mikrofonzugriff verweigert. Erlaube ihn in den Browsereinstellungen. serviceUnavailable: Diktat ist gerade nicht verfügbar. Der Browser erreicht seinen Sprachdienst nicht; prüfe die Verbindung und versuche es erneut. - limitReached: Nutzungslimit erreicht. Versuch die Aufnahme erneut, sobald das Limit zurückgesetzt oder erhöht ist. + limitReached: Nutzungslimit erreicht. Versuche die Aufnahme erneut, sobald das Limit zurückgesetzt oder erhöht wurde. citations: source: Quelle {number} page: Seite {page} diff --git a/services/platform/messages/en/chat.yml b/services/platform/messages/en/chat.yml index 19e953f6cd..3e6437596d 100644 --- a/services/platform/messages/en/chat.yml +++ b/services/platform/messages/en/chat.yml @@ -216,6 +216,8 @@ transcription: transcribing: Transcribing… transcribed: Transcribed couldNotTranscribe: Couldn't transcribe + limitReached: Usage limit reached + limitReachedHint: A usage limit that applies to you has been reached. Settings > Usage shows when it resets; choose Try again once it has reset or been raised. viewTranscript: View transcript previewSubtitle: '{seconds}s transcribed' retry: Try again diff --git a/services/platform/messages/fr/chat.yml b/services/platform/messages/fr/chat.yml index 7820466b4c..277eacaaf1 100644 --- a/services/platform/messages/fr/chat.yml +++ b/services/platform/messages/fr/chat.yml @@ -216,6 +216,8 @@ transcription: transcribing: Transcription en cours… transcribed: Transcrit couldNotTranscribe: Transcription impossible + limitReached: "Limite d'utilisation atteinte" + limitReachedHint: "Une limite d'utilisation qui s'applique à toi a été atteinte. Paramètres > Utilisation indique quand elle sera réinitialisée ; choisis Réessayer une fois la limite réinitialisée ou relevée." viewTranscript: Voir la transcription previewSubtitle: '{seconds}s transcrites' retry: Réessayer From a84ecdbad89e9a049ff7fea2c544c7c4ed56302a Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 12:03:45 +0200 Subject: [PATCH 51/57] docs: say a new project chat's recordings count toward the project The usage attribution pages say a transcription holds the recording's length without its long silences, and that a model the catalog has no per-minute price for counts toward request limits only. GOV-R14 names recordings added before a new chat's first message, GOV-F57 walks that case in a project's new chat, and the error-code reference lists the dictation 429 and the Usage limit reached chip. --- .../admin/governance/usage-attribution.md | 2 +- .../admin/governance/usage-attribution.md | 2 +- .../admin/governance/usage-attribution.md | 2 +- .../backend/domains/governance/spec.md | 7 +++--- .../tests/manual/reference/error-codes.md | 2 ++ .../tests/manual/suites/governance.md | 22 ++++++++++--------- 6 files changed, 21 insertions(+), 16 deletions(-) diff --git a/docs/de/platform/admin/governance/usage-attribution.md b/docs/de/platform/admin/governance/usage-attribution.md index 8cbaef0876..642d6ad7d0 100644 --- a/docs/de/platform/admin/governance/usage-attribution.md +++ b/docs/de/platform/admin/governance/usage-attribution.md @@ -39,7 +39,7 @@ Ein API-Schlüssel, den ein Admin für ein Mitglied erstellt hat, zählt für di - **API-Schlüssellimits** binden die Anfragen, die mit diesem Schlüssel authentifiziert wurden: die damit gesendeten Chatnachrichten, die damit gestellten Aufrufe der Modell-Endpunkte und die damit gestarteten Läufe. - **Projektlimits** binden die Arbeit in diesem Projekt, egal wer sie angestoßen hat, auch die Läufe eines Triggers. -Ist ein Limit erreicht, lehnt Tale die nächste Anfrage vor der Ausführung ab und nennt das Limit. Ein Zug eines verwalteten Agenten wird beim Start abgelehnt; ein bereits laufender Zug behält den Rahmen, den er bekommen hat. Ein Bild, das der Agent während seines Zugs anfordert, wird eigens geprüft, bevor das Bildmodell aufgerufen wird: Ist ein Limit erreicht, lehnt Tale das Bild ab, und der Zug läuft weiter. Das Bild zehrt außerdem vom Rahmen des Zugs, der es angefordert hat. Der `llm`-Schritt einer Automatisierung, der Titel eines Chats, eine Umformulierung mit **Mit KI verbessern**, ein Stück Sprachausgabe und eine Transkription werden jeweils geprüft, bevor Tale das Modell aufruft, und zwar gegen eine Schätzung des Höchsten, was der Aufruf kosten kann — bei einer geschriebenen Antwort der Prompt und die längste Antwort, die der Aufruf zulässt, bei einer Transkription die ganze Aufnahme zum Minutenpreis des Modells. Diesen Betrag halten sie fest, solange der Aufruf läuft, damit gleichzeitig gestartete Aufrufe ein fast erreichtes Limit nicht gemeinsam überschreiten. Ein abgelehnter `llm`-Schritt schlägt mit `budget_exceeded` fehl, und sein Fehler nennt das Limit; der Lauf schlägt mit ihm fehl, außer das `onError` des Schritts ist `continue`. Ein abgelehnter Titel ist kein Fehler: Der Chat bekommt seinen Namen dann aus der ersten Nachricht, ohne Modellaufruf. Eine abgelehnte Transkription schlägt fehl und nennt das Limit; wähle **Erneut versuchen**, sobald das Limit es zulässt. Ein abgelehntes Diktat meldet, dass das Limit erreicht ist, und ein Videolink wird vor seinem Download abgelehnt. Eine Chatantwort hält außerdem jede weitere Runde ihrer Tool-Nutzung fest, sobald die Runde beginnt. [So werden Regeln kombiniert](/de/platform/admin/governance/policies-and-limits#how-rules-combine) beschreibt den Fall, dass mehrere Regeln für eine Person gelten. +Ist ein Limit erreicht, lehnt Tale die nächste Anfrage vor der Ausführung ab und nennt das Limit. Ein Zug eines verwalteten Agenten wird beim Start abgelehnt; ein bereits laufender Zug behält den Rahmen, den er bekommen hat. Ein Bild, das der Agent während seines Zugs anfordert, wird eigens geprüft, bevor das Bildmodell aufgerufen wird: Ist ein Limit erreicht, lehnt Tale das Bild ab, und der Zug läuft weiter. Das Bild zehrt außerdem vom Rahmen des Zugs, der es angefordert hat. Der `llm`-Schritt einer Automatisierung, der Titel eines Chats, eine Umformulierung mit **Mit KI verbessern**, ein Stück Sprachausgabe und eine Transkription werden jeweils geprüft, bevor Tale das Modell aufruft, und zwar gegen eine Schätzung des Höchsten, was der Aufruf kosten kann — bei einer geschriebenen Antwort der Prompt und die längste Antwort, die der Aufruf zulässt, bei einer Transkription die Länge der Aufnahme ohne ihre langen Pausen, zum Minutenpreis des Modells. Diesen Betrag halten sie fest, solange der Aufruf läuft, damit gleichzeitig gestartete Aufrufe ein fast erreichtes Limit nicht gemeinsam überschreiten. Ein abgelehnter `llm`-Schritt schlägt mit `budget_exceeded` fehl, und sein Fehler nennt das Limit; der Lauf schlägt mit ihm fehl, außer das `onError` des Schritts ist `continue`. Ein abgelehnter Titel ist kein Fehler: Der Chat bekommt seinen Namen dann aus der ersten Nachricht, ohne Modellaufruf. Ein Transkriptionsmodell, für das der Katalog keinen Minutenpreis kennt — eines, das nach Tokens abrechnet, oder ein Endpunkt ohne veröffentlichten Preis —, zählt nur für Anfragelimits, ohne Kosten. Eine abgelehnte Transkription zeigt **Nutzungslimit erreicht**; wähle **Erneut versuchen**, sobald das Limit es zulässt. Ein abgelehntes Diktat meldet, dass das Limit erreicht ist, und ein Videolink wird vor seinem Download abgelehnt. Eine Chatantwort hält außerdem jede weitere Runde ihrer Tool-Nutzung fest, sobald die Runde beginnt. [So werden Regeln kombiniert](/de/platform/admin/governance/policies-and-limits#how-rules-combine) beschreibt den Fall, dass mehrere Regeln für eine Person gelten. ## Drei Situationen, die du kennen solltest diff --git a/docs/en/platform/admin/governance/usage-attribution.md b/docs/en/platform/admin/governance/usage-attribution.md index 9671b41db3..696e0b4d90 100644 --- a/docs/en/platform/admin/governance/usage-attribution.md +++ b/docs/en/platform/admin/governance/usage-attribution.md @@ -39,7 +39,7 @@ An API key an Admin made for a member counts against that member, like the membe - **API-key limits** bind the requests authenticated with that key: the chat messages it sent, its model endpoint calls, and the runs it started. - **Project limits** bind the work in that project, whoever asked for it, including runs a trigger started. -When a limit is reached, Tale refuses the next request before it runs and names the limit. A managed agent turn is refused at its start; a turn already running keeps the allowance it was given. An image the agent asks for during its turn is checked on its own before the image model is called, so a reached limit refuses the image while the turn continues. The image also draws on the allowance of the turn that asked for it. An automation's `llm` step, a chat's title, a rewrite with **Improve with AI**, a chunk of voice output and a transcription are each checked before Tale calls the model, against an estimate of the most the call may cost — for a written reply, its prompt and the longest answer the call allows; for a transcription, the whole recording at the model's price per minute — and hold that amount while the call runs, so calls started at the same moment cannot pass a nearly reached limit together. A refused `llm` step fails with `budget_exceeded`, and its error names the limit; the run fails with it unless the step's `onError` is `continue`. A refused title is no error: the chat is named from its first message instead, without a model call. A refused transcription fails and names the limit; choose **Try again** once the limit allows it. A refused dictation says the limit was reached, and a video link is refused before its download. A chat reply also holds each further round of its tool use as the round starts. [How rules combine](/platform/admin/governance/policies-and-limits#how-rules-combine) covers the case of several rules applying to one person. +When a limit is reached, Tale refuses the next request before it runs and names the limit. A managed agent turn is refused at its start; a turn already running keeps the allowance it was given. An image the agent asks for during its turn is checked on its own before the image model is called, so a reached limit refuses the image while the turn continues. The image also draws on the allowance of the turn that asked for it. An automation's `llm` step, a chat's title, a rewrite with **Improve with AI**, a chunk of voice output and a transcription are each checked before Tale calls the model, against an estimate of the most the call may cost — for a written reply, its prompt and the longest answer the call allows; for a transcription, the recording's length, its long silences cut, at the model's price per minute — and hold that amount while the call runs, so calls started at the same moment cannot pass a nearly reached limit together. A refused `llm` step fails with `budget_exceeded`, and its error names the limit; the run fails with it unless the step's `onError` is `continue`. A refused title is no error: the chat is named from its first message instead, without a model call. A transcription model the catalog has no per-minute price for — one billed by tokens, or an endpoint that publishes no price — counts toward request limits only, at no cost. A refused transcription reads **Usage limit reached**; choose **Try again** once the limit allows it. A refused dictation says the limit was reached, and a video link is refused before its download. A chat reply also holds each further round of its tool use as the round starts. [How rules combine](/platform/admin/governance/policies-and-limits#how-rules-combine) covers the case of several rules applying to one person. ## Three situations worth knowing diff --git a/docs/fr/platform/admin/governance/usage-attribution.md b/docs/fr/platform/admin/governance/usage-attribution.md index bd00e5738f..c3be947d71 100644 --- a/docs/fr/platform/admin/governance/usage-attribution.md +++ b/docs/fr/platform/admin/governance/usage-attribution.md @@ -39,7 +39,7 @@ Une clé API qu’un admin a créée pour un membre compte pour ce membre, comme - **Les limites de clé API** s’appliquent aux requêtes authentifiées par cette clé : les messages de chat qu’elle a envoyés, ses appels aux endpoints de modèles et les exécutions qu’elle a lancées. - **Les limites de projet** s’appliquent au travail dans ce projet, quelle que soit la personne qui l’a demandé, y compris aux exécutions lancées par un déclencheur. -Quand une limite est atteinte, Tale refuse la requête suivante avant de l’exécuter et nomme la limite. Un tour d’agent géré est refusé à son démarrage ; un tour déjà en cours conserve l’enveloppe qui lui a été accordée. Une image que l’agent demande pendant son tour est vérifiée à part, avant l’appel au modèle d’images : si une limite est atteinte, Tale refuse l’image et le tour continue. L’image puise aussi dans l’enveloppe du tour qui l’a demandée. L’étape `llm` d’une automatisation, le titre d’un chat, une réécriture avec **Améliorer avec l'IA**, un morceau de sortie vocale et une transcription sont chacun vérifiés avant que Tale appelle le modèle, par rapport à une estimation du coût le plus élevé que l’appel peut atteindre — pour une réponse écrite, le prompt et la plus longue réponse que l’appel permet ; pour une transcription, tout l’enregistrement au prix par minute du modèle — et réservent ce montant pendant l’appel, pour que des appels lancés au même moment ne franchissent pas ensemble une limite presque atteinte. Une étape `llm` refusée échoue avec `budget_exceeded` et son erreur nomme la limite ; l’exécution échoue avec elle, sauf si le `onError` de l’étape vaut `continue`. Un titre refusé n’est pas une erreur : le chat est alors nommé d’après son premier message, sans appel de modèle. Une transcription refusée échoue et nomme la limite ; choisis **Réessayer** dès que la limite le permet. Une dictée refusée indique que la limite est atteinte, et un lien vidéo est refusé avant son téléchargement. Une réponse de chat réserve aussi chaque tour supplémentaire de son utilisation d’outils, dès que ce tour commence. [Comment les règles se combinent](/fr/platform/admin/governance/policies-and-limits#how-rules-combine) traite le cas où plusieurs règles visent la même personne. +Quand une limite est atteinte, Tale refuse la requête suivante avant de l’exécuter et nomme la limite. Un tour d’agent géré est refusé à son démarrage ; un tour déjà en cours conserve l’enveloppe qui lui a été accordée. Une image que l’agent demande pendant son tour est vérifiée à part, avant l’appel au modèle d’images : si une limite est atteinte, Tale refuse l’image et le tour continue. L’image puise aussi dans l’enveloppe du tour qui l’a demandée. L’étape `llm` d’une automatisation, le titre d’un chat, une réécriture avec **Améliorer avec l'IA**, un morceau de sortie vocale et une transcription sont chacun vérifiés avant que Tale appelle le modèle, par rapport à une estimation du coût le plus élevé que l’appel peut atteindre — pour une réponse écrite, le prompt et la plus longue réponse que l’appel permet ; pour une transcription, la durée de l’enregistrement sans ses longs silences, au prix par minute du modèle — et réservent ce montant pendant l’appel, pour que des appels lancés au même moment ne franchissent pas ensemble une limite presque atteinte. Une étape `llm` refusée échoue avec `budget_exceeded` et son erreur nomme la limite ; l’exécution échoue avec elle, sauf si le `onError` de l’étape vaut `continue`. Un titre refusé n’est pas une erreur : le chat est alors nommé d’après son premier message, sans appel de modèle. Un modèle de transcription dont le catalogue ne connaît pas le prix par minute — facturé aux tokens, ou servi par un endpoint qui ne publie aucun prix — ne compte que pour les limites de requêtes, sans coût. Une transcription refusée affiche **Limite d'utilisation atteinte** ; choisis **Réessayer** dès que la limite le permet. Une dictée refusée indique que la limite est atteinte, et un lien vidéo est refusé avant son téléchargement. Une réponse de chat réserve aussi chaque tour supplémentaire de son utilisation d’outils, dès que ce tour commence. [Comment les règles se combinent](/fr/platform/admin/governance/policies-and-limits#how-rules-combine) traite le cas où plusieurs règles visent la même personne. ## Trois situations à connaître diff --git a/services/platform/backend/domains/governance/spec.md b/services/platform/backend/domains/governance/spec.md index 2d94b703be..d742f0416d 100644 --- a/services/platform/backend/domains/governance/spec.md +++ b/services/platform/backend/domains/governance/spec.md @@ -44,8 +44,9 @@ tightens the limit of the person it belongs to, and the reverse. ### GOV-R14 · A project's limit caps everything spent in the project, whoever spends it -What a project spent is everything done in it: the chats in its threads (their titles, the -answers read aloud, the recordings transcribed in them and the assistant's tool calls included), +What a project spent is everything done in it: its chats (their titles, the answers read aloud, +the recordings transcribed in them, even before a new chat's first message, and the assistant's +tool calls included), the turns of its agents and the agent and `llm` steps of the automations run in it, with the images they make, and the calls made with its own API keys. Its limit binds that work on top of the limits of whoever asked for it, a run a schedule started included, and binds nothing done outside the project. A run that names no @@ -70,7 +71,7 @@ What running work may still cost is set aside against the person's and the organ limits, so several things started at the same moment cannot overrun a limit together: a chat reply's every round as it starts, an agent's allowance, a voice chunk's estimate, and the estimated largest cost of a call Tale makes straight to a model — an automation's `llm` step, a -chat's title, a rewrite with Improve with AI, a transcription at its whole length. Such a call is +chat's title, a rewrite with Improve with AI, a transcription at the recording's length. Such a call is refused when a limit has too little room for that cost; a chat's title is then made from the first message, without a call. With no limit set, work gets the deployment's default allowance. diff --git a/services/platform/tests/manual/reference/error-codes.md b/services/platform/tests/manual/reference/error-codes.md index e679199b84..945f7ccca7 100644 --- a/services/platform/tests/manual/reference/error-codes.md +++ b/services/platform/tests/manual/reference/error-codes.md @@ -97,6 +97,8 @@ Never a rendered message — seeing one of these in the UI is itself a bug. | `CHAT_TURN_IN_PROGRESS` (409) on delete | `DELETE /api/v1/threads/{id}` while a turn runs, or while the poll says `queued`; cancel the turn first, then the delete answers 204. | | `CHAT_TURN_IN_PROGRESS` (409) on send | `POST /api/v1/threads/{id}/messages` while the poll says `queued` or `streaming`: nothing is queued, the running turn keeps its `messageId`, and a concurrent pair of sends yields exactly one 202. Retry once the poll says `idle`. | | `BUDGET_EXCEEDED` (429) on send | `POST /api/v1/threads/{id}/messages` while a budget cap that binds the key holder is reached — their own, a team's, the organization's or the key's; a rule at **Max requests** 1 after one send does it: nothing is queued, `data` names the cap and `Retry-After` the wait until its period resets. A cap reached after the 202 settles the reply with `errorCode: budget_exceeded`. In the app the same refusal is a localized toast (`chat.toast.budgetExceeded`), never the code. On the model endpoints the same caps answer 429 in the interface's shape — OpenAI `type` `insufficient_quota`, Anthropic `rate_limit_error` — with `Retry-After`, `x-should-retry: false` and the cap named in the message rather than in `data` (governance.md GOV-F44). | +| `BUDGET_EXCEEDED` (429) on dictation | `POST /api/app/files/dictation` while a budget cap that binds the dictating member is reached, or has too little room for the clip's length at the transcription model's per-minute price; a **User** rule at **Max cost** of your monthly cost does it: nothing is sent to the provider. In the app it is the localized toast `chat.dictation.limitReached`, and the recording stays for **Try again** (governance.md GOV-F57). | +| A failed transcription that reads **Usage limit reached** | An uploaded recording whose uploader — or the project of its chat — is at a budget cap when its transcription would start: the file fails with the cap's sentence and is never retried by itself; the composer chip reads `chat.transcription.limitReached`. A video link that reaches the same refusal after its download fails with `videoLink.errors.budgetExceeded`; one refused at the door starts no download (governance.md GOV-F57). | | `CHAT_TURN_IN_PROGRESS` (409) on archive | `PATCH /api/v1/threads/{id}` with `archived: true` while the poll says `queued` or `streaming`: nothing is written and the turn runs on; cancel it or wait for `idle`, then archive. A thread (or its project) archived AFTER a send was accepted settles that reply `cancelled` with the prompt kept, never a 500. | | `KNOWLEDGE_ENTRY_SUPERSEDED` (409) | `PATCH /api/v1/knowledge-entries/{id}` on an entry a newer version replaced; edit the active one. Deleting a superseded entry removes that row only; deleting the active entry removes the chain and drops the document's passages from the search corpus at once. | | `DOCUMENT_STALE` (409) | `PATCH /api/v1/documents/{id}` with an `expectedUpdatedAt` older than the row's `updatedAt` (read the document, patch it once, then patch again with the first `updatedAt`). Nothing is written; the 200 of a good patch carries the new `updatedAt`. | diff --git a/services/platform/tests/manual/suites/governance.md b/services/platform/tests/manual/suites/governance.md index 2f4891b5c8..1e12081d09 100644 --- a/services/platform/tests/manual/suites/governance.md +++ b/services/platform/tests/manual/suites/governance.md @@ -208,16 +208,18 @@ agent. - [ ] `GOV-F57` · **A transcription is held to the limits of whoever added the recording** — with an OpenAI credential serving `whisper-1`, read your monthly cost under **Settings → Usage**, then GOV-F4-style give - yourself a **User** rule with **Max cost** a cent above it. In a chat, - add a recording longer than two minutes → its chip turns **Transcription - failed** (`chat.transcriptionFailedShort`), its tooltip naming your - monthly cost limit, and it never retries by itself. Dictate into the - composer → the toast reads `chat.dictation.limitReached`, in German and - French too. Paste a YouTube link → refused before any download. Delete - the rule, choose **Try again** (`chat.transcription.retry`) on the chip - → it transcribes, and **Usage analytics** books **Transcription** under - you at 0.6¢ a minute; in a project's chat, the project's usage counts it - too + yourself a **User** rule with **Max cost** a cent above it. In a + project's new chat, add a recording longer than two minutes before the + first send → its chip reads **Usage limit reached** + (`chat.transcription.limitReached`), its tooltip saying where to see the + limit (`chat.transcription.limitReachedHint`), in German and French too, + and it never retries by itself. In a browser without built-in speech + recognition (Firefox), dictate into the composer → the toast reads + `chat.dictation.limitReached`. Paste a YouTube link → refused before any + download. Delete the rule, choose **Try again** + (`chat.transcription.retry`) on the chip → it transcribes, and **Usage + analytics** books **Transcription** under you at 0.6¢ a minute — and the + project's usage counts it too, though the chat had no thread yet - [ ] `GOV-F48` · **A rule outlives its key** — Save GOV-F4b-style rules on three members' keys, then make each key stop working: the holder revokes one under **Settings → API → REST**, an Admin removes the holder of the From 108b839a6c730e51b364468af6f1742224891ffe Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 12:30:09 +0200 Subject: [PATCH 52/57] docs: say which project a recording's transcription counts toward The governance README still read that a recording counts toward the project of the chat it was added to. It now names the project its upload or video link registered in a project's new chat, else the uploader's own chat's, as the code reads it. --- services/platform/backend/domains/governance/README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/services/platform/backend/domains/governance/README.md b/services/platform/backend/domains/governance/README.md index e7ca226102..aa79e0e28e 100644 --- a/services/platform/backend/domains/governance/README.md +++ b/services/platform/backend/domains/governance/README.md @@ -95,7 +95,10 @@ page, the budget gate, erasure and retention are its readers. Beside it, `app.pr stamped (`sandbox_session_ops.project_ids` — a managed turn's, a model request's, a direct call's). A project's key spends in its project whatever it calls (`loadBudgetSubject`). A recording's transcription is in the - project of the chat it was added to, and a video link's door check reads that project too. + project it was added in: the one its upload or its video link named in a project's new chat + (`file_metadata.project_id`, `video_link_jobs.project_id`), else the project of the + uploader's own chat — a thread id on a file is the uploader's claim, not proof of the project. + A video link's door check reads that project too. ## Lanes (the write side) @@ -109,7 +112,7 @@ page, the budget gate, erasure and retention are its readers. Beside it, `app.pr | Automation `llm` step | `resolveAutomationRunAttribution` (`domains/automations/llm-metering.ts`), held and booked as a direct call | the person `started_by` names; `__automation__` for `trigger:` | automation name | `automation_runs.api_key_id` | `automation_runs.project_id`, else every project the automation is bound to | | Agent image generation (`generate_image`, one row per billed request, no tokens) | `resolveSessionOpAttribution` on the op the turn's token names (`domains/sandbox/image-generation.ts`) | the turn's person, as above; `__automation__` for `trigger:` | the turn's agent id or automation name | the run's key, as above | the run's, as above | | Voice output | `domains/tts` (held on its pending chunk row) | the requester | `__tts__` | — | the thread's | -| Transcription (an upload, a video link's audio, a dictation) | `domains/files/transcription-metering.ts`, held and booked as a direct call | the uploader — a retry continues their upload — or `__automation__` for a file nobody added; the dictating member | `__transcription__` | — | the chat's the recording was added to | +| Transcription (an upload, a video link's audio, a dictation) | `domains/files/transcription-metering.ts`, held and booked as a direct call | the uploader — a retry continues their upload — or `__automation__` for a file nobody added; the dictating member | `__transcription__` | — | the one named at registration, else the uploader's own chat's | | Model endpoint request (`model-api` op) | `domains/model_api/metering.ts` stamps the op; settlement reads the stamp | the key holder | `__direct_api__` | the API key | a project's key's project | | Connector call | `recordConnectorUsage` | the caller | optional | — | the chat's, for the assistant's tools | From aa87e1d15f7cdc4709e3b109f52b3ee48e489760 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 17:58:06 +0200 Subject: [PATCH 53/57] fix(platform): keep the direct-call op kind out of a pinned helper `core/sandbox/session_constants.ts` is one of the helpers the released legacy agent flow reuses unchanged, and a guard pins its bytes. The direct-call op kind now lives in a module of its own in the governance domain, which the direct calls and the erasure cascade import. --- .../platform/backend/core/sandbox/session_constants.ts | 10 ---------- services/platform/backend/domains/erasure/service.ts | 6 ++---- .../backend/domains/governance/direct-call-kind.ts | 10 ++++++++++ .../backend/domains/governance/direct-calls.ts | 2 +- 4 files changed, 13 insertions(+), 15 deletions(-) create mode 100644 services/platform/backend/domains/governance/direct-call-kind.ts diff --git a/services/platform/backend/core/sandbox/session_constants.ts b/services/platform/backend/core/sandbox/session_constants.ts index 8f22c9e285..10f6252a1e 100644 --- a/services/platform/backend/core/sandbox/session_constants.ts +++ b/services/platform/backend/core/sandbox/session_constants.ts @@ -28,16 +28,6 @@ export const WORKFLOW_AGENT_OP_KIND: SandboxAgentOpKind = 'workflow-agent'; */ export const MODEL_API_OP_KIND = 'model-api'; -/** - * The kind a call the platform makes straight to a provider files its op - * under (`domains/governance/direct-calls.ts`) — an automation's `llm` - * step, a chat title, the Inbox's Improve. Like a model-endpoint request it - * is no agent turn: its `session_id` is `direct-call:`, which names - * no session row, and the row records whose call it is, what it holds - * while a budget binds, and what it was booked at. - */ -export const DIRECT_CALL_OP_KIND = 'direct-call'; - /** The `session_id` a model-endpoint request's op row carries — one per API * key, so a key's requests read together. */ export function modelApiOpSessionId(apiKeyId: string): string { diff --git a/services/platform/backend/domains/erasure/service.ts b/services/platform/backend/domains/erasure/service.ts index 950dfed62a..934febbaaa 100644 --- a/services/platform/backend/domains/erasure/service.ts +++ b/services/platform/backend/domains/erasure/service.ts @@ -9,10 +9,7 @@ import { } from '../../core/governance/erasure_constants.ts'; import { normalizeAuthEmail } from '../../core/lib/auth/normalize_auth_email.ts'; import { parseBlobRef } from '../../core/lib/storage/blob_ref.ts'; -import { - DIRECT_CALL_OP_KIND, - MODEL_API_OP_KIND, -} from '../../core/sandbox/session_constants.ts'; +import { MODEL_API_OP_KIND } from '../../core/sandbox/session_constants.ts'; import { toJson } from '../../db/sql.ts'; import { addJobInTx } from '../../jobs/enqueue.ts'; import { deleteOrgObject } from '../../lib/object-store.ts'; @@ -27,6 +24,7 @@ import { import { emitHintInTx } from '../../realtime/outbox.ts'; import { createAuditLog } from '../audit_logs/service.ts'; import { markAutomationWriterInTx } from '../automations/writer-protocol.ts'; +import { DIRECT_CALL_OP_KIND } from '../governance/direct-call-kind.ts'; import { applyMaturedDsarPolicyChange } from '../governance/settings-tail.ts'; import { type ActiveHolds, loadActiveHolds } from '../legal_holds/service.ts'; import { writeNotificationForOrgs } from '../notifications/service.ts'; diff --git a/services/platform/backend/domains/governance/direct-call-kind.ts b/services/platform/backend/domains/governance/direct-call-kind.ts new file mode 100644 index 0000000000..f4ece6a1b1 --- /dev/null +++ b/services/platform/backend/domains/governance/direct-call-kind.ts @@ -0,0 +1,10 @@ +/** + * The kind a call the platform makes straight to a provider files its op + * under (`direct-calls.ts`) — an automation's `llm` step, a chat title, the + * Inbox's Improve, a transcription, an embedding request. Like a + * model-endpoint request it is no agent turn: its `session_id` is + * `direct-call:`, which names no session row, and the row records + * whose call it is, what it holds while a budget binds, and what it was + * booked at. + */ +export const DIRECT_CALL_OP_KIND = 'direct-call'; diff --git a/services/platform/backend/domains/governance/direct-calls.ts b/services/platform/backend/domains/governance/direct-calls.ts index 6d913e273b..dbc655594a 100644 --- a/services/platform/backend/domains/governance/direct-calls.ts +++ b/services/platform/backend/domains/governance/direct-calls.ts @@ -3,11 +3,11 @@ import { randomUUID } from 'node:crypto'; import type { Sql, TransactionSql } from 'postgres'; import { AUTOMATION_SUBJECT_ID } from '../../../lib/shared/constants/usage.ts'; -import { DIRECT_CALL_OP_KIND } from '../../core/sandbox/session_constants.ts'; import { estimateTurnCostCents } from '../chat/store.ts'; import { reserveTurnBudget } from '../sandbox/turn-budget.ts'; import { budgetPolicyActive, type BudgetViolation } from './budget-gate.ts'; import { budgetRefusalMessage } from './budget-refusal.ts'; +import { DIRECT_CALL_OP_KIND } from './direct-call-kind.ts'; import { incrementUsageLedger } from './service.ts'; /** From 6ecb33555ca5829636c65288ac4a0c0fb905faff Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 18:10:20 +0200 Subject: [PATCH 54/57] test(platform): write the budget lane's automation run as the engine does --- .../governance/project-budget.integration.ts | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/services/platform/backend/domains/governance/project-budget.integration.ts b/services/platform/backend/domains/governance/project-budget.integration.ts index fbd418cce8..6ce2328ffa 100644 --- a/services/platform/backend/domains/governance/project-budget.integration.ts +++ b/services/platform/backend/domains/governance/project-budget.integration.ts @@ -9,6 +9,7 @@ import { z } from 'zod'; import { buildPeriodKeyFromTimestamp } from '../../core/governance/helpers.ts'; import type { RecordCheck } from '../../integration-lane-helpers.ts'; import { clearOrgConfigCaches } from '../../lib/org-config.ts'; +import { markAutomationWriterInTx } from '../automations/writer-protocol.ts'; import { assertChatTurnBudget, ChatBudgetExceededError, @@ -297,16 +298,20 @@ export async function checkProjectBudgets( ) VALUES (${orgId}, ${automationName}, ${bound}, ${now}, ${userId}) `; } - const [run] = await sql<{ id: string }[]>` - INSERT INTO app.automation_runs ( - org_id, name, version, status, mode, started_by, input, checkpoints, - wake_at_ms, claim_epoch, started_at_ms - ) VALUES ( - ${orgId}, ${automationName}, 1, 'running', 'live', 'trigger:itest', - ${sql.json({})}, ${sql.json({ nodes: {}, executions: 0 })}, - ${null}, 1, ${now} - ) RETURNING id - `; + // A run written as the engine does, under its writer protocol. + const [run] = await sql.begin(async (fixtureTx) => { + await markAutomationWriterInTx(fixtureTx); + return fixtureTx<{ id: string }[]>` + INSERT INTO app.automation_runs ( + org_id, name, version, status, mode, started_by, input, checkpoints, + wake_at_ms, claim_epoch, started_at_ms + ) VALUES ( + ${orgId}, ${automationName}, 1, 'running', 'live', 'trigger:itest', + ${sql.json({})}, ${sql.json({ nodes: {}, executions: 0 })}, + ${null}, 1, ${now} + ) RETURNING id + `; + }); runId = run?.id ?? ''; await sql` INSERT INTO app.sandbox_sessions ( @@ -371,7 +376,10 @@ export async function checkProjectBudgets( DELETE FROM app.sandbox_sessions WHERE org_id = ${orgId} AND session_id = ${runSession} `; - await sql`DELETE FROM app.automation_runs WHERE id = ${runId}`; + await sql.begin(async (fixtureTx) => { + await markAutomationWriterInTx(fixtureTx); + await fixtureTx`DELETE FROM app.automation_runs WHERE id = ${runId}`; + }); await sql` DELETE FROM app.automation_project_bindings WHERE org_id = ${orgId} AND automation_name = ${automationName} From be40ef301b39c2936be2f2b3a9406a0e5bbaaa4a Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 21:27:53 +0200 Subject: [PATCH 55/57] test(e2e): find an API key's row by its name under the new layout --- services/platform/tests/e2e/specs/settings-depth.spec.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/platform/tests/e2e/specs/settings-depth.spec.ts b/services/platform/tests/e2e/specs/settings-depth.spec.ts index e953784a78..1f1f057100 100644 --- a/services/platform/tests/e2e/specs/settings-depth.spec.ts +++ b/services/platform/tests/e2e/specs/settings-depth.spec.ts @@ -26,10 +26,12 @@ function visibleSaveButton(page: Page): Locator { .filter({ visible: true }); } -/** Isolate the single table row whose name cell matches `name` exactly. */ +/** Isolate the single table row that names `name` exactly — by its text, + * not its whole cell: a cell can carry more beneath the name (an API key's + * masked key sits under its name). */ function rowByName(page: Page, name: string): Locator { return page.getByRole('row').filter({ - has: page.getByRole('cell', { name, exact: true }), + has: page.getByText(name, { exact: true }), }); } From 279197a948e266120e63a74e5b073aa22ae6fecd Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 22:26:36 +0200 Subject: [PATCH 56/57] style(platform): sort the budget lane's writer-protocol import --- .../backend/domains/governance/project-budget.integration.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/platform/backend/domains/governance/project-budget.integration.ts b/services/platform/backend/domains/governance/project-budget.integration.ts index a84616b02c..817066b579 100644 --- a/services/platform/backend/domains/governance/project-budget.integration.ts +++ b/services/platform/backend/domains/governance/project-budget.integration.ts @@ -9,11 +9,11 @@ import { z } from 'zod'; import { buildPeriodKeyFromTimestamp } from '../../core/governance/helpers.ts'; import type { RecordCheck } from '../../integration-lane-helpers.ts'; import { clearOrgConfigCaches } from '../../lib/org-config.ts'; -import { markAutomationWriterInTx } from '../automations/writer-protocol.ts'; import { checkLlmStepBudget, recordLlmStepUsage, } from '../automations/llm-metering.ts'; +import { markAutomationWriterInTx } from '../automations/writer-protocol.ts'; import { assertChatTurnBudget, ChatBudgetExceededError, From 4881799e2e44783b5115aefc0c84f9386a30b82e Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 03:47:23 +0200 Subject: [PATCH 57/57] fix(platform): drop the llm step handler names main's merge brought back --- services/platform/backend/core/lib/handler_names.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/services/platform/backend/core/lib/handler_names.ts b/services/platform/backend/core/lib/handler_names.ts index 342efa3e81..1890148d55 100644 --- a/services/platform/backend/core/lib/handler_names.ts +++ b/services/platform/backend/core/lib/handler_names.ts @@ -65,7 +65,6 @@ interface HandlerNames { heartbeatRun: FunctionRef; openLlmStepCall: FunctionRef; recordAgentTurnSettled: FunctionRef; - recordLlmStepUsage: FunctionRef; recordProgress: FunctionRef; releaseLlmStepCall: FunctionRef; settleLlmStepCall: FunctionRef; @@ -73,7 +72,6 @@ interface HandlerNames { suspendRun: FunctionRef; }; queries: FunctionRef & { - checkLlmStepBudget: FunctionRef; getRunLanguageContext: FunctionRef; getRunProjectContext: FunctionRef; getRunProjectId: FunctionRef;