Skip to content

Commit 5a198d4

Browse files
feat(attachments): Store large Slack files on first use (#3491)
Large Slack files (non-image, over 25 MiB) are recorded with `storage_key = NULL` and were never stored (#3339). Now the first call that needs the bytes streams the file from Slack into attachment storage once and fills in `storage_key`, `sha256` and `bytes`. Later reads use storage. So `transcribeAudio` (#3489) can sign a storage URL with `createDownloadUrl` (#3488) for every file. **Behavior** - `storeDeferredAttachment` (`store.ts`) streams the source through the existing `writeAttachmentObject` path (fresh write key, retries, size check, sha256). Then it updates the row only where `storage_key IS NULL`, the row is not delete-requested, and the conversation is not purged. When the update misses, it deletes our object and returns the winner's row, or null when the row is no longer live. - `storeAttachmentOnFirstUse` (`download.ts`) does the Slack lookup and the size check, maps errors to `AttachmentDownloadError`, and wraps the store in an `attachment.store` span. - `loadAttachment` and `transcribeAudio` call it first. `transcribeAudio` no longer refuses unstored files. - `writeAttachmentObject` no longer retries `AttachmentSourceUnavailableError`. A file that Slack deleted is not transient. - The dashboard byte route does **not** store. It keeps streaming files from Slack until a tool stores them. **Notes** - No migration: `0107_attachment_deferred_download.sql` already made `storage_key` and `sha256` nullable. - `model-input.ts` is unchanged except for a comment. Only web uploads reach it, and they are always stored. It reads bytes only for images up to 5 MB, and deferred rows are non-images over 25 MiB. **Open risk** - Nobody has checked yet that ElevenLabs can fetch a Vercel Blob signed URL in production. <!-- junior-request-attribution:start --> via @thomasjiangcy. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A71078a65e4a20ded28d6e80cfc50ba2d --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A71078a65e4a20ded28d6e80cfc50ba2d) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A71078a65e4a20ded28d6e80cfc50ba2d/?project=4510944073809921) <!-- junior-session-footer:end --> --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Thomas Jiang <[email protected]>
1 parent 376a48c commit 5a198d4

18 files changed

Lines changed: 530 additions & 108 deletions

File tree

‎TELEMETRY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ attributes. Nested logs and spans inherit them.
7474
| Skill or plugin missing | `startup.discovery.completed`, `plugin.*`, `skill.*`, span `plugin.hook` | `chat/plugins/` |
7575
| Memory recall slow, empty, or noisy | `app.memory.recall.*` on `plugin.hook` (`userPrompt`), span `gen_ai.rerank` | `packages/junior-memory` |
7676
| Attachment or web search failure | `attachment.*`, `image.attachment.*`, `conversation.image.*`, `gen_ai.execute_tool` (`webSearch`) | `chat/slack/vision-context.ts` |
77+
| Slow first use of a large Slack file | span `attachment.store` (`file.size`, `app.attachment.source.provider`) | `chat/attachments/download.ts` |
7778
| Transcription failed or costly | span `gen_ai.transcription`, `app.transcription.*`, `ai.transcription.failed`, `tool.transcript.write.failed` | `chat/pi/transcription.ts`, `chat/tools/transcribe-audio.ts` |
7879
| Model request slow before gateway | `app.ai.http.*`, `app.ai.event_loop.utilization` on `gen_ai.chat` | `chat/pi/gateway-request-timing.ts` |
7980
| Prompt cache reset between calls | `app.ai.request.*` hashes, `gen_ai.usage.cache_*` on `gen_ai.chat` | `chat/pi/request-prefix-attributes.ts` |

‎packages/junior-dashboard/e2e/conversation-attachments.spec.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,8 @@ test("downloads a large Slack file on request", async ({ page, dashboard }) => {
5252
`${dashboard.baseURL}/conversations/${encodeURIComponent(DASHBOARD_QA_CONVERSATION_ID)}`,
5353
{ waitUntil: "networkidle" },
5454
);
55-
// Junior never stores a large Slack file, so it shows as a file row with
56-
// no preview, not a video.
55+
// Junior has not stored this large Slack file yet, so it shows as a file
56+
// row with no preview, not a video.
5757
const recording = page.getByRole("button", {
5858
name: "Download standup-recording.mp4",
5959
});

‎packages/junior-dashboard/src/client/conversations/TranscriptAttachment.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -339,15 +339,15 @@ function TranscriptMediaTile(props: {
339339

340340
// Every file row shares this look. A stored file is a preview button or a
341341
// download link; a file that is still sending is neither. A large Slack file
342-
// that Junior never stores has its own Download button.
342+
// that Junior has not stored yet has its own Download button.
343343
const FILE_ROW_SHELL_CLASS =
344344
"grid w-full min-w-0 items-center gap-2 rounded-lg border border-dashboard-border bg-dashboard-fill-faint px-3 py-2 text-left font-sans no-underline";
345345
const FILE_ROW_BASE_CLASS = `${FILE_ROW_SHELL_CLASS} grid-cols-[auto_minmax(0,1fr)]`;
346346
const FILE_ROW_CLASS = `${FILE_ROW_BASE_CLASS} cursor-pointer transition-colors hover:border-dashboard-border-interactive hover:bg-dashboard-fill-hover focus-visible:outline-2 focus-visible:outline-dashboard-focus`;
347347
const PENDING_FILE_ROW_CLASS = `${FILE_ROW_SHELL_CLASS} grid-cols-[auto_minmax(0,1fr)_auto]`;
348348

349349
/**
350-
* Render a large Slack file that Junior never stores. Download loads the
350+
* Render a large Slack file that Junior has not stored yet. Download loads the
351351
* file URL in a hidden frame, and the server streams it from Slack. A saved
352352
* file never loads a document in the frame. An error response does, and the
353353
* conversation page stays in place, so the row then asks the server why.

‎packages/junior-dashboard/src/mock-reporting/fixtures.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -846,7 +846,7 @@ function dashboardQaConversation(nowMs: number): ConversationDetailReport {
846846
contentType: "image/png",
847847
bytes: 6400,
848848
},
849-
// Large Slack files that Junior never stores.
849+
// Large Slack files that Junior has not stored yet.
850850
{
851851
id: "qa-recording-pending",
852852
filename: "standup-recording.mp4",

‎packages/junior/src/api/conversations/attachments.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,11 @@ function parseRangeHeader(
6767
}
6868

6969
/**
70-
* Stream a large Slack file that Junior never stored, from Slack through the
71-
* host, with the conversation's Slack installation. A HEAD request checks
72-
* that Slack still has the file without downloading it. Ranges are not
73-
* supported, so media players cannot seek in these files.
70+
* Stream a large Slack file that Junior has not stored yet, from Slack
71+
* through the host, with the conversation's Slack installation. This read
72+
* does not store it. A HEAD request checks that Slack still has the file
73+
* without downloading it. Ranges are not supported, so media players cannot
74+
* seek in these files.
7475
*/
7576
async function slackFileResponse(args: {
7677
attachment: AttachmentRecord;
@@ -129,9 +130,9 @@ async function slackFileResponse(args: {
129130
*
130131
* Missing conversations, missing attachments, purge-marked rows, and viewers
131132
* without private-content access all answer 404. A large Slack file that
132-
* Junior never stored also needs a signed-in viewer. The row lookup is scoped to
133-
* the conversation, so a Slack download only ever starts from a row that
134-
* ingest created there.
133+
* Junior has not stored yet also needs a signed-in viewer. The row lookup is
134+
* scoped to the conversation, so a Slack download only ever starts from a
135+
* row that ingest created there.
135136
*/
136137
export async function conversationAttachmentResponse(args: {
137138
attachmentId: string;

‎packages/junior/src/chat/attachments/download.ts‎

Lines changed: 102 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
1+
import type { JuniorSqlDatabase } from "@/db/db";
2+
import { withSpan } from "@/chat/logging";
13
import { MAX_ATTACHMENT_BYTES } from "./input";
24
import {
35
AttachmentSourceUnavailableError,
6+
type AttachmentSource,
7+
type AttachmentSourceFile,
48
type ReadAttachmentSource,
59
} from "./source";
610
import type { AttachmentStorage } from "./storage";
7-
import type { AttachmentRecord } from "./store";
11+
import {
12+
storeDeferredAttachment,
13+
type AttachmentRecord,
14+
type StoredAttachmentRecord,
15+
} from "./store";
816

917
/** Refusal for a file over `MAX_ATTACHMENT_BYTES`. */
1018
export const ATTACHMENT_TOO_LARGE_MESSAGE = `Attachment is larger than the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB file limit.`;
@@ -23,13 +31,50 @@ export interface AttachmentContent {
2331
open: () => Promise<ReadableStream<Uint8Array>>;
2432
}
2533

34+
/**
35+
* Look up the source file of an unstored row, with the size check done.
36+
* Errors that the person should see are `AttachmentDownloadError`.
37+
*/
38+
async function readSourceFile(
39+
attachment: AttachmentRecord,
40+
readAttachmentSource: ReadAttachmentSource | undefined,
41+
): Promise<{ file: AttachmentSourceFile; source: AttachmentSource }> {
42+
const { source } = attachment;
43+
if (!source || !readAttachmentSource) {
44+
throw new AttachmentDownloadError(
45+
"Attachment cannot be downloaded from this conversation.",
46+
);
47+
}
48+
let file;
49+
try {
50+
file = await readAttachmentSource(source);
51+
} catch (error) {
52+
throw unavailableError(attachment, error);
53+
}
54+
if (file.bytes > MAX_ATTACHMENT_BYTES) {
55+
throw new AttachmentDownloadError(ATTACHMENT_TOO_LARGE_MESSAGE);
56+
}
57+
return { file, source };
58+
}
59+
60+
function unavailableError(attachment: AttachmentRecord, error: unknown) {
61+
return error instanceof AttachmentSourceUnavailableError
62+
? new AttachmentDownloadError(
63+
`${attachment.filename} is no longer available: ${error.message}`,
64+
{ cause: error },
65+
)
66+
: error;
67+
}
68+
2669
/**
2770
* Find where the bytes of one attachment row are, without reading them.
2871
*
29-
* A stored file reads from storage. A large Slack file is never stored, so
30-
* each `open` downloads it from its source. The source reports the current
31-
* size, and the size check runs before any download. Errors that the person
32-
* should see are `AttachmentDownloadError`, from here or from `open`.
72+
* A stored file reads from storage. A large Slack file that no read has
73+
* stored yet downloads from its source on each `open`. The source reports
74+
* the current size, and the size check runs before any download. Errors that
75+
* the person should see are `AttachmentDownloadError`, from here or from
76+
* `open`. Callers that need the bytes more than once use
77+
* `storeAttachmentOnFirstUse` first.
3378
*
3479
* The row must come from a lookup scoped to the caller's conversation. The
3580
* source id comes from that row only, never from a request.
@@ -55,36 +100,65 @@ export async function readAttachmentContent(args: {
55100
},
56101
};
57102
}
58-
const { source } = attachment;
59-
if (!source || !args.readAttachmentSource) {
60-
throw new AttachmentDownloadError(
61-
"Attachment cannot be downloaded from this conversation.",
62-
);
63-
}
64-
const unavailable = (error: unknown) =>
65-
error instanceof AttachmentSourceUnavailableError
66-
? new AttachmentDownloadError(
67-
`${attachment.filename} is no longer available: ${error.message}`,
68-
{ cause: error },
69-
)
70-
: error;
71-
let file;
72-
try {
73-
file = await args.readAttachmentSource(source);
74-
} catch (error) {
75-
throw unavailable(error);
76-
}
77-
if (file.bytes > MAX_ATTACHMENT_BYTES) {
78-
throw new AttachmentDownloadError(ATTACHMENT_TOO_LARGE_MESSAGE);
79-
}
103+
const { file } = await readSourceFile(attachment, args.readAttachmentSource);
80104
return {
81105
bytes: file.bytes,
82106
open: async () => {
83107
try {
84108
return await file.open();
85109
} catch (error) {
86-
throw unavailable(error);
110+
throw unavailableError(attachment, error);
87111
}
88112
},
89113
};
90114
}
115+
116+
/**
117+
* Return the row of one attachment with its bytes in storage.
118+
*
119+
* A large Slack file is recorded without its bytes. The first read that
120+
* needs them streams the file from its source into storage once, and later
121+
* reads use storage. The same rules as `readAttachmentContent` apply to the
122+
* row and to errors.
123+
*/
124+
export async function storeAttachmentOnFirstUse(args: {
125+
attachment: AttachmentRecord;
126+
db: JuniorSqlDatabase;
127+
readAttachmentSource?: ReadAttachmentSource | undefined;
128+
storage: AttachmentStorage;
129+
}): Promise<StoredAttachmentRecord> {
130+
const { attachment } = args;
131+
const { storageKey } = attachment;
132+
if (storageKey !== null) return { ...attachment, storageKey };
133+
const { file, source } = await readSourceFile(
134+
attachment,
135+
args.readAttachmentSource,
136+
);
137+
let stored;
138+
try {
139+
stored = await withSpan(
140+
"attachment.store",
141+
"attachment.store",
142+
{},
143+
async () =>
144+
await storeDeferredAttachment({
145+
attachment: { ...attachment, source },
146+
db: args.db,
147+
file,
148+
storage: args.storage,
149+
}),
150+
{
151+
"app.attachment.source.provider": source.provider,
152+
"file.size": file.bytes,
153+
},
154+
);
155+
} catch (error) {
156+
throw unavailableError(attachment, error);
157+
}
158+
if (!stored) {
159+
throw new AttachmentDownloadError(
160+
`${attachment.filename} is no longer available.`,
161+
);
162+
}
163+
return stored;
164+
}

‎packages/junior/src/chat/attachments/input.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ export const messageAttachmentSchema = z
3535
contentType: z.string().min(1),
3636
bytes: z.number().int().nonnegative(),
3737
/**
38-
* True for a large Slack file that Junior never stores. Each read
39-
* downloads it from Slack, so it has no preview.
38+
* True for a large Slack file that Junior has not stored yet. A
39+
* dashboard read downloads it from Slack, so it has no preview.
4040
*/
4141
pending: z.literal(true).optional(),
4242
})

‎packages/junior/src/chat/attachments/model-input.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ async function readStoredBytes(args: {
3939
conversationId: args.conversationId,
4040
db: getSqlExecutor(),
4141
});
42+
// Only web uploads reach here, and a web upload is always stored.
4243
if (
4344
!record ||
4445
record.storageProvider !== args.storage.provider ||

‎packages/junior/src/chat/attachments/source.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export interface AttachmentSourceFile {
1313
}
1414

1515
/**
16-
* Look up a source file that Junior recorded without storing it.
16+
* Look up a source file that Junior recorded without storing it yet.
1717
*
1818
* Throw `AttachmentSourceUnavailableError` when the source no longer has the
1919
* file or Junior cannot read it.

0 commit comments

Comments
 (0)