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
23 changes: 23 additions & 0 deletions apps/code/src/main/trpc/routers/os.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,4 +303,27 @@ export const osRouter = router({

return { path: filePath, name: displayName, mimeType };
}),

/**
* Save arbitrary file bytes to a temp file
* Returns the file path for use as a file attachment
*/
saveClipboardFile: publicProcedure
.input(
z.object({
base64Data: z.string(),
originalName: z.string().optional(),
}),
)
.mutation(async ({ input }) => {
const displayName = path.basename(input.originalName ?? "attachment");
const filePath = await createClipboardTempFilePath(displayName);

await fsPromises.writeFile(
filePath,
Buffer.from(input.base64Data, "base64"),
);

return { path: filePath, name: displayName };
}),
});
183 changes: 183 additions & 0 deletions apps/code/src/renderer/api/posthogClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,37 @@ export interface ExternalDataSource {
schemas?: ExternalDataSourceSchema[] | string;
}

export interface TaskArtifactUploadRequest {
name: string;
type: "user_attachment";
size: number;
content_type?: string;
source?: string;
}

export interface DirectUploadPresignedPost {
url: string;
fields: Record<string, string>;
}

export interface PreparedTaskArtifactUpload extends TaskArtifactUploadRequest {
id: string;
storage_path: string;
expires_in: number;
presigned_post: DirectUploadPresignedPost;
}

export interface FinalizedTaskArtifactUpload {
id: string;
name: string;
type: string;
source?: string;
size?: number;
content_type?: string;
storage_path: string;
uploaded_at?: string;
}

type CloudRuntimeAdapter = "claude" | "codex";

function isObjectRecord(value: unknown): value is Record<string, unknown> {
Expand Down Expand Up @@ -773,6 +804,7 @@ export class PostHogAPIClient {
reasoningLevel?: string;
resumeFromRunId?: string;
pendingUserMessage?: string;
pendingUserArtifactIds?: string[];
sandboxEnvironmentId?: string;
prAuthorshipMode?: PrAuthorshipMode;
runSource?: CloudRunSource;
Expand Down Expand Up @@ -817,6 +849,9 @@ export class PostHogAPIClient {
if (options?.pendingUserMessage) {
body.pending_user_message = options.pendingUserMessage;
}
if (options?.pendingUserArtifactIds?.length) {
body.pending_user_artifact_ids = options.pendingUserArtifactIds;
}
if (options?.sandboxEnvironmentId) {
body.sandbox_environment_id = options.sandboxEnvironmentId;
}
Expand Down Expand Up @@ -847,6 +882,154 @@ export class PostHogAPIClient {
return data as unknown as Task;
}

async prepareTaskStagedArtifactUploads(
taskId: string,
artifacts: TaskArtifactUploadRequest[],
): Promise<PreparedTaskArtifactUpload[]> {
if (!artifacts.length) {
return [];
}

const teamId = await this.getTeamId();
const url = new URL(
`${this.api.baseUrl}/api/projects/${teamId}/tasks/${taskId}/staged_artifacts/prepare_upload/`,
);
const response = await this.api.fetcher.fetch({
method: "post",
url,
path: `/api/projects/${teamId}/tasks/${taskId}/staged_artifacts/prepare_upload/`,
overrides: {
body: JSON.stringify({ artifacts }),
},
});

if (!response.ok) {
throw new Error(
`Failed to prepare staged uploads: ${response.statusText}`,
);
}

const data = (await response.json()) as {
artifacts?: PreparedTaskArtifactUpload[];
};
return data.artifacts ?? [];
}

async finalizeTaskStagedArtifactUploads(
taskId: string,
artifacts: PreparedTaskArtifactUpload[],
): Promise<FinalizedTaskArtifactUpload[]> {
if (!artifacts.length) {
return [];
}

const teamId = await this.getTeamId();
const url = new URL(
`${this.api.baseUrl}/api/projects/${teamId}/tasks/${taskId}/staged_artifacts/finalize_upload/`,
);
const response = await this.api.fetcher.fetch({
method: "post",
url,
path: `/api/projects/${teamId}/tasks/${taskId}/staged_artifacts/finalize_upload/`,
overrides: {
body: JSON.stringify({
artifacts: artifacts.map((artifact) => ({
id: artifact.id,
name: artifact.name,
type: artifact.type,
source: artifact.source,
content_type: artifact.content_type,
storage_path: artifact.storage_path,
})),
}),
},
});

if (!response.ok) {
throw new Error(
`Failed to finalize staged uploads: ${response.statusText}`,
);
}

const data = (await response.json()) as {
artifacts?: FinalizedTaskArtifactUpload[];
};
return data.artifacts ?? [];
}

async prepareTaskRunArtifactUploads(
taskId: string,
runId: string,
artifacts: TaskArtifactUploadRequest[],
): Promise<PreparedTaskArtifactUpload[]> {
if (!artifacts.length) {
return [];
}

const teamId = await this.getTeamId();
const url = new URL(
`${this.api.baseUrl}/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/prepare_upload/`,
);
const response = await this.api.fetcher.fetch({
method: "post",
url,
path: `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/prepare_upload/`,
overrides: {
body: JSON.stringify({ artifacts }),
},
});

if (!response.ok) {
throw new Error(`Failed to prepare uploads: ${response.statusText}`);
}

const data = (await response.json()) as {
artifacts?: PreparedTaskArtifactUpload[];
};
return data.artifacts ?? [];
}

async finalizeTaskRunArtifactUploads(
taskId: string,
runId: string,
artifacts: PreparedTaskArtifactUpload[],
): Promise<FinalizedTaskArtifactUpload[]> {
if (!artifacts.length) {
return [];
}

const teamId = await this.getTeamId();
const url = new URL(
`${this.api.baseUrl}/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/finalize_upload/`,
);
const response = await this.api.fetcher.fetch({
method: "post",
url,
path: `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/finalize_upload/`,
overrides: {
body: JSON.stringify({
artifacts: artifacts.map((artifact) => ({
id: artifact.id,
name: artifact.name,
type: artifact.type,
source: artifact.source,
content_type: artifact.content_type,
storage_path: artifact.storage_path,
})),
}),
},
});

if (!response.ok) {
throw new Error(`Failed to finalize uploads: ${response.statusText}`);
}

const data = (await response.json()) as {
artifacts?: FinalizedTaskArtifactUpload[];
};
return data.artifacts ?? [];
}

async listTaskRuns(taskId: string): Promise<TaskRun[]> {
const teamId = await this.getTeamId();
const url = new URL(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";

const mockSaveClipboardImage = vi.hoisted(() => vi.fn());
const mockSaveClipboardText = vi.hoisted(() => vi.fn());
const mockSaveClipboardFile = vi.hoisted(() => vi.fn());

vi.mock("@renderer/trpc/client", () => ({
trpcClient: {
Expand All @@ -12,6 +13,9 @@ vi.mock("@renderer/trpc/client", () => ({
saveClipboardText: {
mutate: mockSaveClipboardText,
},
saveClipboardFile: {
mutate: mockSaveClipboardFile,
},
},
},
}));
Expand Down Expand Up @@ -98,28 +102,47 @@ describe("persistFile", () => {
});
});

it("throws for unsupported file types", async () => {
const file = { name: "archive.zip" } as unknown as File;
await expect(persistBrowserFile(file)).rejects.toThrow(/Unsupported/);
it("persists arbitrary non-image files via saveClipboardFile", async () => {
mockSaveClipboardFile.mockResolvedValue({
path: "/tmp/posthog-code-clipboard/attachment-def/archive.zip",
name: "archive.zip",
});

const file = {
name: "archive.zip",
type: "application/zip",
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
} as unknown as File;

await expect(persistBrowserFile(file)).resolves.toEqual({
id: "/tmp/posthog-code-clipboard/attachment-def/archive.zip",
label: "archive.zip",
});

expect(mockSaveClipboardFile).toHaveBeenCalledWith({
base64Data: expect.any(String),
originalName: "archive.zip",
});
});

it("returns the preserved filename for browser-selected text files", async () => {
mockSaveClipboardText.mockResolvedValue({
mockSaveClipboardFile.mockResolvedValue({
path: "/tmp/posthog-code-clipboard/attachment-456/config.json",
name: "config.json",
});

const file = {
name: "config.json",
text: vi.fn().mockResolvedValue('{"ok":true}'),
type: "application/json",
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
} as unknown as File;

await expect(persistBrowserFile(file)).resolves.toEqual({
id: "/tmp/posthog-code-clipboard/attachment-456/config.json",
label: "config.json",
});
expect(mockSaveClipboardText).toHaveBeenCalledWith({
text: '{"ok":true}',
expect(mockSaveClipboardFile).toHaveBeenCalledWith({
base64Data: expect.any(String),
originalName: "config.json",
});
});
Expand Down
33 changes: 19 additions & 14 deletions apps/code/src/renderer/features/message-editor/utils/persistFile.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import { getImageMimeType } from "@features/code-editor/utils/imageUtils";
import {
isSupportedCloudImageAttachment,
isSupportedCloudTextAttachment,
} from "@features/editor/utils/cloud-prompt";
import { trpcClient } from "@renderer/trpc/client";

const CHUNK_SIZE = 8192;
Expand Down Expand Up @@ -46,21 +42,30 @@ export async function persistTextContent(
return { path: result.path, name: result.name };
}

export async function persistGenericFile(file: File): Promise<PersistedFile> {
const arrayBuffer = await file.arrayBuffer();
const base64Data = arrayBufferToBase64(arrayBuffer);

const result = await trpcClient.os.saveClipboardFile.mutate({
base64Data,
originalName: file.name,
});

return {
path: result.path,
name: result.name,
mimeType: file.type || undefined,
};
}

export async function persistBrowserFile(
file: File,
): Promise<{ id: string; label: string }> {
if (isSupportedCloudImageAttachment(file.name)) {
if (file.type.startsWith("image/")) {
const result = await persistImageFile(file);
return { id: result.path, label: file.name };
}

if (isSupportedCloudTextAttachment(file.name)) {
const text = await file.text();
const result = await persistTextContent(text, file.name);
return { id: result.path, label: result.name };
}

throw new Error(
`Unsupported attachment: ${file.name}. Cloud attachments currently support text files and PNG/JPG/GIF/WebP images.`,
);
const result = await persistGenericFile(file);
return { id: result.path, label: result.name };
}
Loading
Loading