Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions src/agent/hosted/chat-preparation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import "#veryfront/schemas/_test-setup.ts";
import { assertEquals, assertExists, assertRejects } from "#veryfront/testing/assert.ts";
import { describe, it } from "#veryfront/testing/bdd.ts";
import { observeFetchRequestInit, withMockFetch } from "#veryfront/testing/mock-fetch.ts";
import { VeryfrontError } from "#veryfront/errors";
import type { ChatUiMessage } from "#veryfront/chat/types.ts";
import { convertToTextGenerationRuntimeRequestMessages } from "#veryfront/agent/runtime/text-generation-runtime-message-converter.ts";
import type { Message } from "#veryfront/agent/types.ts";
Expand Down Expand Up @@ -3436,6 +3437,67 @@ Deno.test("prepareHostedChatRuntimeCreationOptions uses the exact selector snaps
assertEquals(result.steering.skills, []);
});

// A chat without a project has no route to sign an upload: veryfront-api only
// serves `GET /projects/{project}/uploads/{upload}/url`. The attachment must
// degrade to a visible note without a request to the missing `/uploads/...`
// route (veryfront/veryfront-issue-inbox#4939).
Deno.test("prepareHostedChatRuntimeMessages marks an uploaded file unavailable in a projectless chat without calling the API", async () => {
const requestedUrls: string[] = [];
const unresolvable: Array<{ uploadId: string; errorKind: string }> = [];
await withMockFetch((input): Promise<Response> => {
requestedUrls.push(input.toString());
return Promise.resolve(new Response("Not Found", { status: 404 }));
}, async () => {
const messages = await prepareHostedChatRuntimeMessages([
{
id: "message-1",
role: "user",
parts: [
{ type: "text", text: "Use this file." },
{
type: "file",
mediaType: "application/pdf",
filename: "notes.pdf",
uploadId: "upload-1",
url: "https://files.example.com/original.pdf",
},
],
},
], {
apiUrl: "https://api.example.com",
authToken: "token-1",
projectId: null,
onUnresolvableAttachment: ({ uploadId, error }) => {
unresolvable.push({
uploadId,
errorKind: error instanceof VeryfrontError ? error.slug : String(error),
});
},
});

const apiOrigin = new URL("https://api.example.com").origin;
const parsedRequests = requestedUrls.map((url) => new URL(url));
assertEquals(
parsedRequests.filter((url) => url.origin === apiOrigin).map((url) => url.pathname),
[],
"a projectless chat must not ask the API for a signed upload URL",
);
assertEquals(
parsedRequests.filter((url) => url.pathname === "/uploads/upload-1/url"),
[],
"the projectless /uploads/{id}/url route does not exist and must not be called",
);
assertEquals(unresolvable, [{ uploadId: "upload-1", errorKind: "invalid-argument" }]);
assertEquals(
messages[0]?.parts.some((part) =>
isRuntimeTextPart(part) && part.text === "[attachment unavailable: notes.pdf]"
),
true,
"the model must be told a file was attached and could not be read",
);
});
});

// A provider error message can carry the response body and the filename is
// user-controlled, so the degrade warning must not put either in the logs.
Deno.test("prepareHostedChatExecution keeps customer data out of the unreadable-attachment warning", async () => {
Expand Down
59 changes: 34 additions & 25 deletions src/agent/runtime/upload-url-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,34 +40,41 @@ Deno.test("getRuntimeUploadUrl fetches project-scoped signed upload URLs", async
);
});

Deno.test("getRuntimeUploadUrl fetches global signed upload URLs", async () => {
const requestedUrls: string[] = [];
const inits: RequestInit[] = [];
const fetchUploadUrl = (url: string, init: RequestInit): Promise<Response> => {
requestedUrls.push(url);
inits.push(init);
return Promise.resolve(
new Response(JSON.stringify({ signed_url: "https://signed.example.com/global.txt" }), {
status: 200,
}),
);
};
// veryfront-api serves a signed upload URL only under a project
// (`GET /projects/{project}/uploads/{upload}/url`). The runtime used to fall
// back to `GET /uploads/{upload}/url`, which the API does not have, so the
// request always answered 404.
for (const projectId of [undefined, null, ""]) {
Deno.test(
`getRuntimeUploadUrl refuses an upload without a project and sends no request (projectId: ${
JSON.stringify(projectId)
})`,
async () => {
const requestedUrls: string[] = [];
const fetchUploadUrl = (url: string, _init: RequestInit): Promise<Response> => {
requestedUrls.push(url);
return Promise.resolve(new Response("Not Found", { status: 404 }));
};

const signedUrl = await getRuntimeUploadUrl({
apiUrl: "https://api.example.com",
authToken: "token-1",
uploadId: "upload-1",
fetch: fetchUploadUrl,
});
const err = await assertRejects(
() =>
getRuntimeUploadUrl({
apiUrl: "https://api.example.com",
authToken: "token-1",
uploadId: "upload-1",
...(projectId === undefined ? {} : { projectId }),
fetch: fetchUploadUrl,
}),
VeryfrontError,
"upload-1",
);

assertEquals(signedUrl, "https://signed.example.com/global.txt");
assertEquals(requestedUrls, ["https://api.example.com/uploads/upload-1/url"]);
assertEquals(
new Headers(inits[0]?.headers).get("Authorization"),
"Bearer token-1",
"the global signed upload URL request must carry the caller's bearer credential",
assertEquals(requestedUrls, [], "no request may be sent to a route the API does not serve");
assertInstanceOf(err, VeryfrontError, "a projectless upload must be a VeryfrontError");
assertEquals(err.slug, "invalid-argument", err.message);
},
);
});
}

Deno.test("getRuntimeUploadUrl reports API errors", async () => {
const fetchUploadUrl = (_url: string, _init: RequestInit): Promise<Response> =>
Expand All @@ -82,6 +89,7 @@ Deno.test("getRuntimeUploadUrl reports API errors", async () => {
getRuntimeUploadUrl({
apiUrl: "https://api.example.com",
authToken: "token-1",
projectId: "project-1",
uploadId: "upload-1",
fetch: fetchUploadUrl,
}),
Expand All @@ -106,6 +114,7 @@ Deno.test("getRuntimeUploadUrl rejects invalid responses", async () => {
getRuntimeUploadUrl({
apiUrl: "https://api.example.com",
authToken: "token-1",
projectId: "project-1",
uploadId: "upload-1",
fetch: fetchUploadUrl,
}),
Expand Down
23 changes: 16 additions & 7 deletions src/agent/runtime/upload-url-client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { privateJsonParse } from "#veryfront/security/private-json.ts";
import { defineSchema } from "#veryfront/schemas/index.ts";
import { NETWORK_ERROR } from "#veryfront/errors";
import { INVALID_ARGUMENT, NETWORK_ERROR } from "#veryfront/errors";

const DEFAULT_RUNTIME_UPLOAD_URL_TIMEOUT_MS = 15_000;

Expand Down Expand Up @@ -37,7 +37,17 @@ export type RuntimeUploadUrlOptions = RuntimeUploadUrlClientOptions & {

/** Return runtime upload URL. */
export async function getRuntimeUploadUrl(options: RuntimeUploadUrlOptions): Promise<string> {
const url = createRuntimeUploadUrl(options);
// veryfront-api signs an upload only under its project
// (`GET /projects/{project}/uploads/{upload}/url`); it has no project-free
// route. A run without a project is refused here, before any request, so the
// caller's degrade path reports the attachment instead of a 404 doing it.
if (!options.projectId) {
throw INVALID_ARGUMENT.create({
detail:
`Cannot fetch signed upload URL for ${options.uploadId}: uploads are project-scoped and this run has no project`,
});
}
const url = createRuntimeUploadUrl({ ...options, projectId: options.projectId });
const response = await (options.fetch ?? fetch)(url.toString(), {
headers: {
Authorization: `Bearer ${options.authToken}`,
Expand Down Expand Up @@ -67,13 +77,12 @@ export async function getRuntimeUploadUrl(options: RuntimeUploadUrlOptions): Pro
function createRuntimeUploadUrl(input: {
apiUrl: string | URL;
uploadId: string;
projectId?: string | null;
projectId: string;
}): URL {
const apiUrl = new URL(input.apiUrl);
const encodedUploadId = encodeURIComponent(input.uploadId);
const pathname = input.projectId
? `/projects/${encodeURIComponent(input.projectId)}/uploads/${encodedUploadId}/url`
: `/uploads/${encodedUploadId}/url`;
const pathname = `/projects/${encodeURIComponent(input.projectId)}/uploads/${
encodeURIComponent(input.uploadId)
}/url`;
return new URL(pathname, apiUrl.origin);
}

Expand Down
Loading