mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-28 04:41:52 +01:00
feat(server): chunked import preview endpoint and resumable upload in the Import page and CLI (#11224)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The previous pull request added server-side chunked resumable import transfers; without clients, large imports still ride the single fragile upload > - The Import page and the CLI need to slice large packages, upload parts with retry and progress, resume after interruptions, and preview before applying > - Preview is the missing server piece: the browser flow is preview-then-import, so a completed spool must be previewable without re-uploading > - This pull request adds the transfer preview endpoint, switches the Import page to the chunked path for zips over 48 MB, and teaches the CLI the same for oversized local imports > - The benefit is that large imports get progress, per-part retry, and resume in both clients, while small imports keep the exact single-shot path they have today ## Linked Issues or Issue Description **What happened?** With only the server transfer routes in place, users still upload large company packages as one request from the Import page and the CLI: no progress indication, no retry below the whole file, and no resume after a dropped connection or refresh. The preview-then-import flow also cannot run against an uploaded transfer, forcing a second full upload. **Expected behavior** A large package uploads once as verified parts with visible progress; preview and import both run against the uploaded spool; an interrupted upload resumes with only the missing parts re-sent; packages at or below 48 MB behave exactly as before. **Steps to reproduce** 1. Select a 500 MB zip on the Import page over an unreliable connection. 2. Watch the single upload fail near the end and restart from zero, twice — once for preview, once for import. 3. Same story headless via the CLI. ## What Changed - Server: `POST /import/transfers/:id/preview` runs the existing preview logic against the completed spool (shared assembly + whole-file verification helper with apply); preview neither completes the run nor deletes the spool, so the subsequent apply reuses it. Missing parts respond with the missing list. - UI: zips over 48 MB take the chunked path in both preview and import — the file is sliced into 32 MB parts hashed with WebCrypto (single ArrayBuffer, no second copy), the transfer is created or resumed (the create response's missing-parts list drives what uploads), parts upload sequentially with three attempts each and visible progress, then transfer preview/apply replace the multipart calls. The existing preview pane, collision handling, adapter overrides, and async job polling are unchanged; ≤ 48 MB keeps the single-shot path. - CLI: oversized local `.zip` or folder imports zip/slice/hash with node crypto, upload with resume and per-part retry and progress lines, and use transfer preview/apply. Small packages keep the inline path byte-identical. - Failure honesty: adapters/API errors fail open to existing behavior; a part failing all attempts surfaces a durable error panel with resume intact. ## Verification - Server: preview-then-apply on one spool (run stays open, spool intact, then apply completes), preview with missing parts rejected — added to the transfer route suite (embedded Postgres). - UI suite: large file takes the chunked path (manifest shape, part uploads, progress, apply on a resumed transfer, single-shot endpoints never called), small file stays single-shot, part failure after three attempts surfaces the error panel without running preview, resume re-uploads only the missing part. - CLI: manifest slicing/hashing, threshold behavior for zip and folder sources, folder-zip round-trip through the real zip reader, upload resume/retry/exhaustion/already-completed, full-command chunked and small-zip inline flows. - Server, ui, cli typechecks clean. Exact counts in the PR checks. ## Risks - The 48 MB threshold only routes between two verified paths; behavior below it is untouched. - Chunked CLI imports use the board-scoped transfer routes, so oversized CLI imports need board credentials (agent tokens keep the agent-safe small-file path). No privilege change — board actors already had the generic routes — but the two size regimes differ semantically; called out for review. - A CLI dry-run over the threshold uploads parts before previewing; the spool persists (24 h sweep) and a later apply resumes without re-upload — inherent to preview-against-spool. Stacked on #11223 — merge that first; this PR then shows only the preview endpoint and client changes. ## Model Used - Claude Fable 5 (`claude-fable-5`) via Claude Code CLI, with extended thinking and tool use (multi-agent implementation with independent verification). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
8f478242f1
commit
0a95ada1be
13 files changed
+1658
-66
No files matched your search
@@ -165,6 +165,14 @@ export const api = {
|
||||
}),
|
||||
put: <T>(path: string, body: unknown, options?: RequestOptions) =>
|
||||
request<T>(path, { method: "PUT", body: JSON.stringify(body), signal: options?.signal }),
|
||||
/** Raw binary upload (e.g. one chunked import-transfer part); the body travels as-is. */
|
||||
putRaw: <T>(path: string, body: Blob, options?: RequestOptions) =>
|
||||
request<T>(path, {
|
||||
method: "PUT",
|
||||
body,
|
||||
signal: options?.signal,
|
||||
headers: { "Content-Type": "application/octet-stream", ...(options?.headers ?? {}) },
|
||||
}),
|
||||
patch: <T>(path: string, body: unknown, options?: RequestOptions) =>
|
||||
request<T>(path, { method: "PATCH", body: JSON.stringify(body), signal: options?.signal }),
|
||||
delete: <T>(path: string, bodyOrOptions?: unknown, options?: RequestOptions) => {
|
||||
|
||||
@@ -10,6 +10,17 @@ import type {
|
||||
UpdateCompanyBranding,
|
||||
} from "@paperclipai/shared";
|
||||
import type { ExportFidelityReport } from "@paperclipai/shared/portability-fidelity";
|
||||
import {
|
||||
companyImportTransferApplyPath,
|
||||
companyImportTransferPartPath,
|
||||
companyImportTransferPath,
|
||||
companyImportTransferPreviewPath,
|
||||
COMPANY_IMPORT_TRANSFERS_ROUTE_PATH,
|
||||
type CompanyImportTransferCreated,
|
||||
type CompanyImportTransferDeclaration,
|
||||
type CompanyImportTransferPartUploadResult,
|
||||
type CompanyImportTransferStatus,
|
||||
} from "@paperclipai/shared/company-import-transfer";
|
||||
import { api } from "./client";
|
||||
|
||||
export type CompanyStats = Record<string, { agentCount: number; issueCount: number }>;
|
||||
@@ -126,4 +137,29 @@ export const companiesApi = {
|
||||
api.postForm<CompanyImportJobAccepted>("/companies/import?async=1", importPackageForm(file, meta)),
|
||||
getImportJob: (jobId: string) =>
|
||||
api.get<CompanyImportJobStatus>(`/companies/import/jobs/${encodeURIComponent(jobId)}`),
|
||||
// Chunked resumable transfer for large local .zip packages: declare the
|
||||
// sliced zip (content-addressed, so re-declaring the same file resumes the
|
||||
// prior transfer with its uploaded parts intact), upload the missing parts,
|
||||
// then preview/apply against the server-side assembled spool. Shapes and
|
||||
// paths come from the shared transfer contract.
|
||||
importTransferCreate: (manifest: CompanyImportTransferDeclaration) =>
|
||||
api.post<CompanyImportTransferCreated>(`/companies${COMPANY_IMPORT_TRANSFERS_ROUTE_PATH}`, manifest),
|
||||
importTransferUploadPart: (transferId: string, index: number, bytes: Blob) =>
|
||||
api.putRaw<CompanyImportTransferPartUploadResult>(
|
||||
`/companies${companyImportTransferPartPath(transferId, index)}`,
|
||||
bytes,
|
||||
),
|
||||
importTransferStatus: (transferId: string) =>
|
||||
api.get<CompanyImportTransferStatus>(`/companies${companyImportTransferPath(transferId)}`),
|
||||
importTransferPreview: (transferId: string, meta: CompanyPortabilityPreviewMeta) =>
|
||||
api.post<CompanyPortabilityPreviewResult>(
|
||||
`/companies${companyImportTransferPreviewPath(transferId)}`,
|
||||
meta,
|
||||
),
|
||||
/** Apply a fully uploaded transfer as an async job (same 202/409 contract as importBundlePackageAsync). */
|
||||
importTransferApply: (transferId: string, meta: CompanyPortabilityImportMeta) =>
|
||||
api.post<CompanyImportJobAccepted>(
|
||||
`/companies${companyImportTransferApplyPath(transferId)}?async=1`,
|
||||
meta,
|
||||
),
|
||||
};
|
||||
@@ -36,6 +36,9 @@ function fileEntryInlineBytes(entry: CompanyPortabilityFileEntry): number {
|
||||
* bytes, base64 payloads with their entry structure, the serialized file-path
|
||||
* keys (thousands of paths are real bytes), and an envelope allowance for the
|
||||
* rest of the request body.
|
||||
*
|
||||
* Mirrored by `estimateInlineImportBytes` in cli/src/commands/client/company.ts
|
||||
* (the CLI cannot import from ui/) — keep the math on both sides in sync.
|
||||
*/
|
||||
export function estimateInlineImportBytes(files: Record<string, CompanyPortabilityFileEntry>): number {
|
||||
let total = REQUEST_ENVELOPE_ALLOWANCE_BYTES;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// Chunked resumable upload plan for large local .zip imports. Zips over the
|
||||
// threshold are sliced into fixed byte-range parts; each part and the whole
|
||||
// file are content-addressed with sha256 so the server can verify every part
|
||||
// on arrival and a resumed transfer re-uploads only the parts it lost. The
|
||||
// declaration's wire shape is the shared transfer contract.
|
||||
|
||||
import type {
|
||||
CompanyImportTransferDeclaration,
|
||||
CompanyImportTransferDeclaredPart,
|
||||
} from "@paperclipai/shared/company-import-transfer";
|
||||
|
||||
/** Local zips larger than this take the chunked transfer path. */
|
||||
export const CHUNKED_IMPORT_THRESHOLD_BYTES = 48 * 1024 * 1024;
|
||||
/** Declared byte-range size of every part except the last. */
|
||||
export const IMPORT_TRANSFER_PART_SIZE_BYTES = 32 * 1024 * 1024;
|
||||
/** Upload attempts per part before the transfer surfaces a failure. */
|
||||
export const IMPORT_TRANSFER_PART_ATTEMPTS = 3;
|
||||
|
||||
async function sha256Hex(bytes: BufferSource): Promise<string> {
|
||||
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
||||
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash the zip and its byte-range parts. Works on the single ArrayBuffer the
|
||||
* caller reads from the File: the whole-file digest hashes the buffer itself
|
||||
* and each part digest hashes a view into it, so no second copy is ever held.
|
||||
*/
|
||||
export async function buildImportTransferManifest(buffer: ArrayBuffer): Promise<CompanyImportTransferDeclaration> {
|
||||
const zipSha256 = await sha256Hex(buffer);
|
||||
const parts: CompanyImportTransferDeclaredPart[] = [];
|
||||
for (let offset = 0; offset < buffer.byteLength; offset += IMPORT_TRANSFER_PART_SIZE_BYTES) {
|
||||
const byteSize = Math.min(IMPORT_TRANSFER_PART_SIZE_BYTES, buffer.byteLength - offset);
|
||||
parts.push({
|
||||
index: parts.length,
|
||||
byteSize,
|
||||
sha256: await sha256Hex(new Uint8Array(buffer, offset, byteSize)),
|
||||
});
|
||||
}
|
||||
return {
|
||||
totalBytes: buffer.byteLength,
|
||||
zipSha256,
|
||||
partSizeBytes: IMPORT_TRANSFER_PART_SIZE_BYTES,
|
||||
parts,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { webcrypto } from "node:crypto";
|
||||
import type { ReactNode } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
@@ -9,12 +10,23 @@ import { ApiError } from "../api/client";
|
||||
import type { CompanyImportJobAccepted } from "../api/companies";
|
||||
import { CompanyImport } from "./CompanyImport";
|
||||
|
||||
// jsdom's crypto has no SubtleCrypto; the chunked transfer path hashes parts
|
||||
// with WebCrypto, so back the global with Node's implementation.
|
||||
if (!globalThis.crypto?.subtle) {
|
||||
vi.stubGlobal("crypto", webcrypto);
|
||||
}
|
||||
|
||||
const mockCompaniesApi = vi.hoisted(() => ({
|
||||
importPreview: vi.fn(),
|
||||
importPreviewPackage: vi.fn(),
|
||||
importBundle: vi.fn(),
|
||||
importBundleAsync: vi.fn(),
|
||||
importBundlePackageAsync: vi.fn(),
|
||||
importTransferCreate: vi.fn(),
|
||||
importTransferUploadPart: vi.fn(),
|
||||
importTransferStatus: vi.fn(),
|
||||
importTransferPreview: vi.fn(),
|
||||
importTransferApply: vi.fn(),
|
||||
getImportJob: vi.fn(),
|
||||
get: vi.fn(),
|
||||
}));
|
||||
@@ -217,6 +229,31 @@ function buildAccepted(id = "job-1"): CompanyImportJobAccepted {
|
||||
return { job: { id, status: "running" }, statusUrl: `/companies/import/jobs/${id}` };
|
||||
}
|
||||
|
||||
function buildTransferCreated(missingParts: number[], alreadyCompleted = false) {
|
||||
return {
|
||||
transferId: "transfer-1",
|
||||
status: "running",
|
||||
alreadyCompleted,
|
||||
totalParts: 2,
|
||||
missingParts,
|
||||
};
|
||||
}
|
||||
|
||||
const TRANSFER_PART_SIZE = 32 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* A zip whose declared size crosses the 48 MB chunked-transfer threshold. Its
|
||||
* real content is one full part plus a 1 KB tail so the manifest slices into
|
||||
* two parts without allocating 48 MB in the test.
|
||||
*/
|
||||
function buildLargeZipFile(): File {
|
||||
const bytes = new Uint8Array(TRANSFER_PART_SIZE + 1024);
|
||||
const file = new File([bytes], "big-package.zip", { type: "application/zip" });
|
||||
Object.defineProperty(file, "size", { value: 49 * 1024 * 1024 });
|
||||
Object.defineProperty(file, "arrayBuffer", { value: async () => bytes.buffer });
|
||||
return file;
|
||||
}
|
||||
|
||||
function buildSucceededJob(id = "job-1") {
|
||||
return { job: { id, status: "succeeded" as const, importResult: buildImportResult() } };
|
||||
}
|
||||
@@ -243,6 +280,10 @@ describe("CompanyImport", () => {
|
||||
// the job already finished with the full result. Individual tests override.
|
||||
mockCompaniesApi.importBundleAsync.mockResolvedValue(buildAccepted());
|
||||
mockCompaniesApi.importBundlePackageAsync.mockResolvedValue(buildAccepted());
|
||||
mockCompaniesApi.importTransferCreate.mockResolvedValue(buildTransferCreated([0, 1]));
|
||||
mockCompaniesApi.importTransferUploadPart.mockResolvedValue({ ok: true, index: 0, alreadyCompleted: false });
|
||||
mockCompaniesApi.importTransferPreview.mockResolvedValue(buildPreviewResult());
|
||||
mockCompaniesApi.importTransferApply.mockResolvedValue(buildAccepted());
|
||||
mockCompaniesApi.getImportJob.mockResolvedValue(buildSucceededJob());
|
||||
mockCompaniesApi.get.mockResolvedValue({ id: "company-2", name: "Imported Test", issuePrefix: "IMP" });
|
||||
mockSidebarPreferencesApi.updateProjectOrder.mockResolvedValue(undefined);
|
||||
@@ -305,6 +346,17 @@ describe("CompanyImport", () => {
|
||||
await flushReact();
|
||||
}
|
||||
|
||||
async function chooseLocalZip(file: File) {
|
||||
await clickButton((text) => text.includes("Local zip"));
|
||||
const fileInput = container.querySelector<HTMLInputElement>('input[type="file"]');
|
||||
expect(fileInput).toBeTruthy();
|
||||
Object.defineProperty(fileInput!, "files", { value: [file], configurable: true });
|
||||
await act(async () => {
|
||||
fileInput!.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
await flushReact();
|
||||
}
|
||||
|
||||
async function renderPageAndImport() {
|
||||
await renderPage();
|
||||
await enterGithubUrl();
|
||||
@@ -415,6 +467,151 @@ describe("CompanyImport", () => {
|
||||
expect(meta.pauseAutomations).toBe(true);
|
||||
// The bundle itself is never expanded into the request; only the raw zip travels.
|
||||
expect(meta).not.toHaveProperty("source");
|
||||
// A zip under the chunked threshold never touches the transfer machinery.
|
||||
expect(mockCompaniesApi.importTransferCreate).not.toHaveBeenCalled();
|
||||
expect(mockCompaniesApi.importTransferUploadPart).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uploads a large local .zip through the chunked transfer path for preview and import", async () => {
|
||||
mockReadZipArchive.mockResolvedValue({ rootPath: "big-package", files: previewFiles });
|
||||
mockCompaniesApi.importTransferCreate
|
||||
.mockResolvedValueOnce(buildTransferCreated([0, 1]))
|
||||
// The import's re-declaration resumes the transfer the preview uploaded.
|
||||
.mockResolvedValueOnce(buildTransferCreated([]));
|
||||
|
||||
// Hold the last part so the visible upload progress can be observed.
|
||||
let resolveLastPart!: (value: { ok: true; index: number; alreadyCompleted: boolean }) => void;
|
||||
mockCompaniesApi.importTransferUploadPart.mockImplementation((_id: string, index: number) => {
|
||||
if (index === 0) return Promise.resolve({ ok: true, index, alreadyCompleted: false });
|
||||
return new Promise((resolve) => {
|
||||
resolveLastPart = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
await renderPage();
|
||||
await chooseLocalZip(buildLargeZipFile());
|
||||
await clickButton((text) => text === "Preview import");
|
||||
await vi.waitFor(() => {
|
||||
expect(mockCompaniesApi.importTransferUploadPart).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
expect(container.textContent).toContain("Uploading part 2 of 2");
|
||||
expect(container.textContent).toContain("32 MB");
|
||||
|
||||
await act(async () => {
|
||||
resolveLastPart({ ok: true, index: 1, alreadyCompleted: false });
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(mockCompaniesApi.importTransferPreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
await settle();
|
||||
|
||||
// The declaration describes the sliced zip: whole-file hash plus one
|
||||
// content hash per 32 MB byte range.
|
||||
const manifest = mockCompaniesApi.importTransferCreate.mock.calls[0]![0] as {
|
||||
totalBytes: number;
|
||||
zipSha256: string;
|
||||
partSizeBytes: number;
|
||||
parts: Array<{ index: number; byteSize: number; sha256: string }>;
|
||||
};
|
||||
expect(manifest.totalBytes).toBe(TRANSFER_PART_SIZE + 1024);
|
||||
expect(manifest.partSizeBytes).toBe(TRANSFER_PART_SIZE);
|
||||
expect(manifest.zipSha256).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(manifest.parts.map((part) => ({ index: part.index, byteSize: part.byteSize }))).toEqual([
|
||||
{ index: 0, byteSize: TRANSFER_PART_SIZE },
|
||||
{ index: 1, byteSize: 1024 },
|
||||
]);
|
||||
expect(manifest.parts.every((part) => /^[0-9a-f]{64}$/.test(part.sha256))).toBe(true);
|
||||
|
||||
// Both parts traveled, then the preview ran against the assembled spool —
|
||||
// never the single-shot multipart endpoints.
|
||||
expect(mockCompaniesApi.importTransferUploadPart).toHaveBeenNthCalledWith(1, "transfer-1", 0, expect.anything());
|
||||
expect(mockCompaniesApi.importTransferUploadPart).toHaveBeenNthCalledWith(2, "transfer-1", 1, expect.anything());
|
||||
expect(mockCompaniesApi.importTransferPreview).toHaveBeenCalledWith(
|
||||
"transfer-1",
|
||||
expect.objectContaining({ collisionStrategy: "rename", target: { mode: "new_company", newCompanyName: null } }),
|
||||
);
|
||||
expect(mockCompaniesApi.importPreviewPackage).not.toHaveBeenCalled();
|
||||
expect(container.textContent).toContain("Import preview");
|
||||
|
||||
await clickButton((text) => text.startsWith("Import 3 file"));
|
||||
await vi.waitFor(() => {
|
||||
expect(mockCompaniesApi.importTransferApply).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
await settle();
|
||||
|
||||
// The resumed transfer had nothing left to upload, so the apply reused
|
||||
// the spooled parts and ran as the usual async job.
|
||||
expect(mockCompaniesApi.importTransferCreate).toHaveBeenCalledTimes(2);
|
||||
expect(mockCompaniesApi.importTransferUploadPart).toHaveBeenCalledTimes(2);
|
||||
expect(mockCompaniesApi.importTransferApply).toHaveBeenCalledWith(
|
||||
"transfer-1",
|
||||
expect.objectContaining({ pauseAutomations: true }),
|
||||
);
|
||||
expect(mockCompaniesApi.importBundlePackageAsync).not.toHaveBeenCalled();
|
||||
expect(mockCompaniesApi.getImportJob).toHaveBeenCalledWith("job-1");
|
||||
expect(container.textContent).toContain("Import complete");
|
||||
});
|
||||
|
||||
it("retries a failed part before surfacing the error panel, keeping the transfer resumable", async () => {
|
||||
mockReadZipArchive.mockResolvedValue({ rootPath: "big-package", files: previewFiles });
|
||||
mockCompaniesApi.importTransferCreate.mockResolvedValue(buildTransferCreated([0, 1]));
|
||||
mockCompaniesApi.importTransferUploadPart.mockImplementation((_id: string, index: number) => {
|
||||
if (index === 0) return Promise.resolve({ ok: true, index, alreadyCompleted: false });
|
||||
return Promise.reject(new Error("socket hang up"));
|
||||
});
|
||||
|
||||
await renderPage();
|
||||
await chooseLocalZip(buildLargeZipFile());
|
||||
await clickButton((text) => text === "Preview import");
|
||||
await vi.waitFor(() => {
|
||||
expect(container.textContent).toContain("Preview failed: socket hang up");
|
||||
});
|
||||
|
||||
// Part 1 was attempted three times before the failure surfaced; the
|
||||
// preview never ran and no state was consumed, so retrying can resume.
|
||||
const partOneAttempts = mockCompaniesApi.importTransferUploadPart.mock.calls.filter(
|
||||
(call) => call[1] === 1,
|
||||
);
|
||||
expect(partOneAttempts).toHaveLength(3);
|
||||
expect(mockCompaniesApi.importTransferPreview).not.toHaveBeenCalled();
|
||||
expect(findButton((text) => text === "Preview import")?.disabled).toBe(false);
|
||||
|
||||
// Retry: the re-declared transfer reports only the lost part missing, so
|
||||
// just that part travels again.
|
||||
mockCompaniesApi.importTransferCreate.mockResolvedValue(buildTransferCreated([1]));
|
||||
mockCompaniesApi.importTransferUploadPart.mockResolvedValue({ ok: true, index: 1, alreadyCompleted: false });
|
||||
mockCompaniesApi.importTransferUploadPart.mockClear();
|
||||
|
||||
await clickButton((text) => text === "Preview import");
|
||||
await vi.waitFor(() => {
|
||||
expect(mockCompaniesApi.importTransferPreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
await settle();
|
||||
|
||||
expect(mockCompaniesApi.importTransferUploadPart).toHaveBeenCalledTimes(1);
|
||||
expect(mockCompaniesApi.importTransferUploadPart).toHaveBeenCalledWith("transfer-1", 1, expect.anything());
|
||||
expect(container.textContent).toContain("Import preview");
|
||||
});
|
||||
|
||||
it("re-uploads only the missing parts when resuming an interrupted transfer", async () => {
|
||||
// A previous page load already uploaded part 0; re-declaring the same
|
||||
// file resumes that transfer, so only part 1 travels.
|
||||
mockReadZipArchive.mockResolvedValue({ rootPath: "big-package", files: previewFiles });
|
||||
mockCompaniesApi.importTransferCreate.mockResolvedValue(buildTransferCreated([1]));
|
||||
|
||||
await renderPage();
|
||||
await chooseLocalZip(buildLargeZipFile());
|
||||
await clickButton((text) => text === "Preview import");
|
||||
await vi.waitFor(() => {
|
||||
expect(mockCompaniesApi.importTransferPreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
await settle();
|
||||
|
||||
expect(mockCompaniesApi.importTransferUploadPart).toHaveBeenCalledTimes(1);
|
||||
expect(mockCompaniesApi.importTransferUploadPart).toHaveBeenCalledWith("transfer-1", 1, expect.anything());
|
||||
expect(container.textContent).toContain("Import preview");
|
||||
});
|
||||
|
||||
it("explains the disabled preview button until a package is chosen", async () => {
|
||||
|
||||
@@ -52,6 +52,12 @@ import {
|
||||
} from "../components/FileTree";
|
||||
import { readZipArchive } from "../lib/zip";
|
||||
import { formatMegabytes } from "../lib/import-preflight";
|
||||
import type { CompanyImportTransferDeclaration } from "@paperclipai/shared/company-import-transfer";
|
||||
import {
|
||||
CHUNKED_IMPORT_THRESHOLD_BYTES,
|
||||
IMPORT_TRANSFER_PART_ATTEMPTS,
|
||||
buildImportTransferManifest,
|
||||
} from "../lib/import-transfer";
|
||||
import { getPortableFileDataUrl, getPortableFileText, isPortableImageFile } from "../lib/portable-files";
|
||||
import {
|
||||
clearStoredImportJob,
|
||||
@@ -706,6 +712,33 @@ async function readLocalPackageZip(file: File): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
// ── Chunked transfer flow for large local zips ───────────────────────
|
||||
//
|
||||
// A local .zip over the threshold is not uploaded in one request: one dropped
|
||||
// connection would restart the whole multi-minute upload. Instead the file is
|
||||
// declared as a chunked transfer (whole-file and per-part sha256), the parts
|
||||
// are uploaded individually with per-part retries, and preview/apply run
|
||||
// server-side against the assembled spool. Re-declaring the same file — after
|
||||
// a failure, a refresh, or between preview and import — resumes the prior
|
||||
// transfer, so only the parts the server is missing are ever re-uploaded.
|
||||
|
||||
function usesChunkedTransfer(file: File): boolean {
|
||||
return file.size > CHUNKED_IMPORT_THRESHOLD_BYTES;
|
||||
}
|
||||
|
||||
/** Parts done / bytes uploaded, rendered inside the pending panels while parts upload. */
|
||||
interface ImportTransferProgress {
|
||||
uploadedParts: number;
|
||||
totalParts: number;
|
||||
uploadedBytes: number;
|
||||
totalBytes: number;
|
||||
}
|
||||
|
||||
function formatTransferProgress(progress: ImportTransferProgress): string {
|
||||
const currentPart = Math.min(progress.uploadedParts + 1, progress.totalParts);
|
||||
return `Uploading part ${currentPart} of ${progress.totalParts} — ${formatMegabytes(progress.uploadedBytes)} of ${formatMegabytes(progress.totalBytes)} uploaded.`;
|
||||
}
|
||||
|
||||
// ── Async import job flow ─────────────────────────────────────────────
|
||||
//
|
||||
// Imports run as server-side jobs: the submit returns 202 with a job id and
|
||||
@@ -879,6 +912,87 @@ export function CompanyImport() {
|
||||
const [resumedWatchJobId, setResumedWatchJobId] = useState<string | null>(null);
|
||||
const resumeAttemptedRef = useRef(false);
|
||||
|
||||
// Chunked transfer state. The manifest cache is keyed by File identity so
|
||||
// preview and import hash the (large) package once; progress is set only
|
||||
// while parts are actually uploading, so the pending panels can report it.
|
||||
const transferManifestRef = useRef<{ file: File; manifest: CompanyImportTransferDeclaration } | null>(null);
|
||||
const [transferProgress, setTransferProgress] = useState<ImportTransferProgress | null>(null);
|
||||
|
||||
async function ensureTransferManifest(file: File): Promise<CompanyImportTransferDeclaration> {
|
||||
if (transferManifestRef.current?.file === file) {
|
||||
return transferManifestRef.current.manifest;
|
||||
}
|
||||
// The whole file is read once here for hashing; parts are later uploaded
|
||||
// as Blob slices of the File, so this buffer is not retained past hashing.
|
||||
const manifest = await buildImportTransferManifest(await file.arrayBuffer());
|
||||
transferManifestRef.current = { file, manifest };
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare (or resume) the transfer for this file and upload every part the
|
||||
* server reports missing, sequentially with per-part retries. Resolves with
|
||||
* the transfer id once the server holds every part.
|
||||
*/
|
||||
async function uploadImportTransfer(file: File): Promise<string> {
|
||||
const manifest = await ensureTransferManifest(file);
|
||||
const created = await companiesApi.importTransferCreate(manifest);
|
||||
if (created.alreadyCompleted) {
|
||||
// The server keys transfers by content, and this exact zip already
|
||||
// finished an apply — its parts are gone, so it cannot be re-run.
|
||||
throw new Error(
|
||||
"This exact package was already imported by a completed transfer. Re-export the package to import it again.",
|
||||
);
|
||||
}
|
||||
const missing = new Set(created.missingParts);
|
||||
let uploadedParts = manifest.parts.length - missing.size;
|
||||
let uploadedBytes = manifest.parts.reduce(
|
||||
(sum, part) => (missing.has(part.index) ? sum : sum + part.byteSize),
|
||||
0,
|
||||
);
|
||||
try {
|
||||
setTransferProgress({
|
||||
uploadedParts,
|
||||
totalParts: manifest.parts.length,
|
||||
uploadedBytes,
|
||||
totalBytes: manifest.totalBytes,
|
||||
});
|
||||
for (const part of manifest.parts) {
|
||||
if (!missing.has(part.index)) continue;
|
||||
const offset = part.index * manifest.partSizeBytes;
|
||||
const bytes = file.slice(offset, offset + part.byteSize);
|
||||
let lastError: unknown = null;
|
||||
let uploaded = false;
|
||||
for (let attempt = 0; attempt < IMPORT_TRANSFER_PART_ATTEMPTS && !uploaded; attempt += 1) {
|
||||
try {
|
||||
await companiesApi.importTransferUploadPart(created.transferId, part.index, bytes);
|
||||
uploaded = true;
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
}
|
||||
}
|
||||
if (!uploaded) {
|
||||
// The parts already uploaded stay spooled server-side; retrying the
|
||||
// preview/import resumes from them instead of starting over.
|
||||
throw lastError instanceof Error
|
||||
? lastError
|
||||
: new Error(`Part ${part.index + 1} of ${manifest.parts.length} failed to upload.`);
|
||||
}
|
||||
uploadedParts += 1;
|
||||
uploadedBytes += part.byteSize;
|
||||
setTransferProgress({
|
||||
uploadedParts,
|
||||
totalParts: manifest.parts.length,
|
||||
uploadedBytes,
|
||||
totalBytes: manifest.totalBytes,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setTransferProgress(null);
|
||||
}
|
||||
return created.transferId;
|
||||
}
|
||||
|
||||
// Fetch current company agents to find CEO adapter type
|
||||
const { data: companyAgents } = useQuery({
|
||||
queryKey: selectedCompanyId ? queryKeys.agents.list(selectedCompanyId) : ["agents", "none"],
|
||||
@@ -950,10 +1064,16 @@ export function CompanyImport() {
|
||||
|
||||
// Preview mutation
|
||||
const previewMutation = useMutation({
|
||||
mutationFn: (_generation: number) => {
|
||||
mutationFn: async (_generation: number) => {
|
||||
const meta = buildImportMetaCommon();
|
||||
if (sourceMode === "local") {
|
||||
if (!localPackage) throw new Error("No source configured.");
|
||||
if (usesChunkedTransfer(localPackage.file)) {
|
||||
// Too large for one request: upload (or resume) the chunked
|
||||
// transfer, then preview against the server-side assembled spool.
|
||||
const transferId = await uploadImportTransfer(localPackage.file);
|
||||
return companiesApi.importTransferPreview(transferId, meta);
|
||||
}
|
||||
// Upload the raw compressed zip; the server unzips it into the same
|
||||
// inline bundle the importer consumes.
|
||||
return companiesApi.importPreviewPackage(localPackage.file, meta);
|
||||
@@ -1091,9 +1211,16 @@ export function CompanyImport() {
|
||||
const storageKey = currentImportJobStorageKey();
|
||||
let accepted: CompanyImportJobAccepted;
|
||||
try {
|
||||
accepted = localFile
|
||||
? await companiesApi.importBundlePackageAsync(localFile, meta)
|
||||
: await companiesApi.importBundleAsync({ source: githubSource!, ...meta });
|
||||
if (localFile && usesChunkedTransfer(localFile)) {
|
||||
// Same transfer the preview uploaded: re-declaring resumes it, so
|
||||
// normally no parts travel again and this goes straight to apply.
|
||||
const transferId = await uploadImportTransfer(localFile);
|
||||
accepted = await companiesApi.importTransferApply(transferId, meta);
|
||||
} else {
|
||||
accepted = localFile
|
||||
? await companiesApi.importBundlePackageAsync(localFile, meta)
|
||||
: await companiesApi.importBundleAsync({ source: githubSource!, ...meta });
|
||||
}
|
||||
} catch (err) {
|
||||
// 409: this user's previous import is still running. Adopt that job
|
||||
// and watch it — never fire a second import.
|
||||
@@ -1817,9 +1944,11 @@ export function CompanyImport() {
|
||||
<div className="mt-3 flex items-start gap-2 rounded-md border border-border bg-muted/30 px-3 py-2.5">
|
||||
<Loader2 className="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground" />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Uploading and analyzing your package
|
||||
{localCompressedBytes !== null ? ` (${formatMegabytes(localCompressedBytes)} zip)` : ""} — large
|
||||
packages can take a few minutes. Keep this page open.
|
||||
{transferProgress
|
||||
? `${formatTransferProgress(transferProgress)} An interrupted upload resumes from the finished parts.`
|
||||
: `Uploading and analyzing your package${
|
||||
localCompressedBytes !== null ? ` (${formatMegabytes(localCompressedBytes)} zip)` : ""
|
||||
} — large packages can take a few minutes. Keep this page open.`}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -1914,8 +2043,9 @@ export function CompanyImport() {
|
||||
<div className="mx-5 mt-3 flex items-start gap-2 rounded-md border border-border bg-muted/30 px-3 py-2.5">
|
||||
<Loader2 className="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground" />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Import running on the server — safe to keep waiting; reconnecting won't lose it.
|
||||
Large packages can take several minutes.
|
||||
{transferProgress
|
||||
? `${formatTransferProgress(transferProgress)} An interrupted upload resumes from the finished parts.`
|
||||
: "Import running on the server — safe to keep waiting; reconnecting won't lose it. Large packages can take several minutes."}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user