mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 09:05:15 +01:00
fix: publish sandbox files on legacy and native runners (#13493)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents must publish generated files so users can inspect their results after a sandbox stops. > - Legacy sandbox bridges blocked attachment listing and could not carry multipart binary uploads through the queue transport. > - The native runner has a separate verified file registration path that needs the same durable result. > - This pull request repairs legacy binary transport, makes native download receipts explicit, and reveals new outputs in the task Artifacts tab. > - Users can open generated files from either runner without a transport flag change. ## Linked Issues or Issue Description Refs #13355 for the existing native file publication path. Related filename fixes: #2615 and #4788. Related sandbox persistence work: #13376. This change repairs attachment delivery through the existing API; it does not add workspace persistence. **What happened?** The upload helper first lists task attachments to avoid duplicates. Both legacy bridge allowlists rejected that GET request with 403. A direct multipart upload also failed: the queue bridge accepted only JSON, excluded attachment uploads, and converted bytes to UTF-8 text. Enabling HTTP/2 alone did not fix the missing listing route. These failures occurred before attachment storage. **Expected behavior** Both runners can publish a workspace file, register its work product, bind it to a response, and return a working download. The file stays accessible after sandbox deletion. A new output opens the task Artifacts tab. The agent receives accurate errors and decides how to retry or report a failure. **Steps to reproduce** 1. Run a legacy agent in Daytona with the duplex bridge disabled. 2. Invoke the bundled upload helper with Bash on a PNG or PDF. 3. Repeat with the duplex bridge enabled. 4. Register the same file through the native runner with generic API tools disabled. 5. Retry registration, delete the sandbox, and compare the downloaded bytes with the original file. **Paperclip version or commit** The failing baseline was `f2c5e54dc`. This branch is rebased onto `6cfe4acff`. **Deployment mode** Source checkout with a local API and real isolated Daytona sandboxes. ## What Changed - Allow authenticated attachment listing, upload, and content download through both legacy bridge transports. - Add optional base64 body encoding to queue envelopes. Preserve the existing UTF-8 contract when the encoding field is absent. Decode binary bodies before forwarding them. - Preserve multipart headers. Bound raw bytes, encoded envelopes, and in-flight reservations. Retain timeout and uncertain-write behavior. - Preserve helper deduplication and return structured uncertain-write failures. Document explicit Bash invocation in live skills. - Add attachment IDs and content/download paths to native registration receipts. Reuse verified local and remote file reads, attachment storage, work-product registration, and response binding. - Preserve Unicode upload filenames and provide a valid Content-Disposition header. - Open the task Artifacts tab when new stored outputs arrive, including a closed desktop panel or mobile drawer. Deduplicate upload and registration events by object ID. Preserve manual selection on refetches, edits, and panel remounts. - Remove task artifact filters, the company Artifacts footer link, and the unassigned group heading and timestamp. ### Screenshot  This is the local display fixture. The image was generated separately and published through the attachment and work-product APIs. ## Verification - Post-rebase `pnpm -r typecheck` and `pnpm build` pass. - The post-rebase local `pnpm test:run` passed 12,369 tests before one existing conversation reset test timed out; all 33 tests in that suite pass when rerun with isolated test configuration. The aggregate command stopped before its remaining groups. GitHub runs the complete suite in separate shards. - All [GitHub verification checks](https://github.com/paperclipai/paperclip/actions/runs/35017893350) pass on `b66ac276dd3d5fc738a22ecea783400106a494d4`: 32 successful checks and two configured skips. The native-session recovery assertion initially raced its fire-and-forget Sentry report; all 13 tests pass locally, and the same-commit CI rerun passes all 170 suites (3,079 tests). - Live post-rebase Daytona: all three file-delivery tests pass. They cover the real Bash helper with the queue bridge, the helper with HTTP/2, and native `register_deliverable` with generic API tools disabled. - Daytona cases cover PNG/PDF bytes, spaced and Unicode names, duplicate registration, response binding, authorization controls, and byte-for-byte downloads after sandbox deletion. - Local focused coverage includes transfer bounds, malformed encoding, interrupted transfers, remote path containment, and native file verification. The attachment route suite passes all 32 tests, including an eight-case filename-header matrix for Unicode and special characters, inline and forced downloads, and full and partial responses. - Browser verification confirms image previews, persisted downloads, automatic Artifacts selection, and preserved manual selection after edits and reloads. Desktop/mobile component coverage passes. The latest UI cleanup passes its 10 affected tests and token gates. - Coverage limit: the Daytona tests call the real helper and native registration path directly. They do not replay a complete model-led image-generation task through the browser. Live command (requires a configured Daytona credential): ```sh PAPERCLIP_FILE_DELIVERY_DAYTONA=1 pnpm exec vitest run server/src/__tests__/file-delivery-bridges.test.ts ``` ## Risks - Binary queue bodies use more memory because base64 adds encoding overhead. Transfer and process limits must remain aligned. - An interrupted write can have an unknown result. The bridge reports this state and preserves stable retry identities. - New artifacts intentionally change the active task tab. Existing history and repeated updates must not take focus again. - Transport flag defaults, server authorization, frozen skill snapshots, and completion policies remain unchanged. No schema migration is required. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, repository tools, code execution, and browser testing. The runtime does not expose a more specific model ID or context-window size. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
6cfe4acff7
commit
d49f168381
26 files changed
+1064
-188
No files matched your search
@@ -0,0 +1,176 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, heartbeatRuns, issueAttachments, issueComments, issues, issueWorkProducts } from "@paperclipai/db";
|
||||
import { startAdapterExecutionTargetPaperclipBridge, type AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
import { runChildProcess } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
|
||||
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
|
||||
import { readVerifiedRemoteWorkspaceFile } from "../services/native-runtime/remote-deliverable-file.js";
|
||||
import { startFileDeliveryDaytona } from "./helpers/file-delivery-daytona.js";
|
||||
import { startRunnerApiTestServer } from "./helpers/runner-api-server.js";
|
||||
|
||||
const liveDaytona = process.env.PAPERCLIP_FILE_DELIVERY_DAYTONA === "1";
|
||||
const helper = path.resolve(import.meta.dirname, "../../../skills/paperclip/scripts/paperclip-upload-artifact.sh");
|
||||
// A real PNG and a PDF with binary bytes in its comment exercise UTF-8 corruption.
|
||||
const files = [
|
||||
{ name: "猫 picture.png", type: "image/png", body: Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aK1sAAAAASUVORK5CYII=", "base64") },
|
||||
{ name: "résumé report.pdf", type: "application/pdf", body: Buffer.concat([Buffer.from("%PDF-1.4\n%"), Buffer.from([255, 0, 128, 254]), Buffer.from("\n1 0 obj <</Type /Catalog>> endobj\n%%EOF\n")]) },
|
||||
];
|
||||
|
||||
function localProcessRunner(): CommandManagedRuntimeRunner {
|
||||
return {
|
||||
execute: input => runChildProcess("file-delivery-test", input.command, input.args ?? [], {
|
||||
cwd: input.cwd ?? process.cwd(), env: input.env ?? {}, stdin: input.stdin,
|
||||
timeoutSec: (input.timeoutMs ?? 30_000) / 1000, graceSec: 1, onLog: async () => {},
|
||||
}),
|
||||
openDuplexChannel: async ({ command }) => {
|
||||
const child = spawn(command[0], command.slice(1), { stdio: ["pipe", "pipe", "pipe"] });
|
||||
child.stderr.resume();
|
||||
return {
|
||||
write: data => { child.stdin.write(data); },
|
||||
onData: listener => { child.stdout.on("data", listener); },
|
||||
onExit: listener => { child.once("exit", exitCode => listener({ exitCode })); },
|
||||
stop: () => { child.kill(); },
|
||||
close: async () => { child.stdin.end(); child.kill(); },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe(`durable file delivery (${liveDaytona ? "Daytona" : "local processes"})`, () => {
|
||||
let server: Awaited<ReturnType<typeof startRunnerApiTestServer>>;
|
||||
const cleanup: Array<() => Promise<void>> = [];
|
||||
afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); });
|
||||
async function execution(localWorkspace: string) {
|
||||
const live = liveDaytona ? await startFileDeliveryDaytona() : null;
|
||||
const workspace = live?.workspace ?? localWorkspace;
|
||||
const runner = live?.runner ?? localProcessRunner();
|
||||
let closed = false;
|
||||
const close = async () => { if (closed) return; closed = true; await live?.close(); };
|
||||
cleanup.push(close);
|
||||
const run = async (command: string, args: string[], env: Record<string, string> = {}) => {
|
||||
const result = await runner.execute({ command, args, env, timeoutMs: 90_000 });
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
return result.stdout;
|
||||
};
|
||||
const write = async (relative: string, body: Buffer) => {
|
||||
const destination = path.join(workspace, relative);
|
||||
await run("node", ["-e", "const fs=require('fs');fs.mkdirSync(require('path').dirname(process.argv[1]),{recursive:true});fs.writeFileSync(process.argv[1],Buffer.from(process.argv[2],'base64'))", destination, body.toString("base64")]);
|
||||
return destination;
|
||||
};
|
||||
const fetchFromWorkspace = async (url: string, headers: Record<string, string>) => {
|
||||
const output = await run("node", ["-e", "fetch(process.argv[1],{headers:JSON.parse(process.argv[2])}).then(async r=>console.log(JSON.stringify({status:r.status,body:Buffer.from(await r.arrayBuffer()).toString('base64')})))", url, JSON.stringify(headers)]);
|
||||
const response = JSON.parse(output);
|
||||
return new Response(Buffer.from(response.body, "base64"), { status: response.status });
|
||||
};
|
||||
return { workspace, runner, close, run, write, fetch: fetchFromWorkspace };
|
||||
}
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "isolated-file-delivery-test-secret");
|
||||
server = await startRunnerApiTestServer();
|
||||
});
|
||||
afterAll(async () => { await server?.close(); vi.unstubAllEnvs(); });
|
||||
|
||||
it.each([false, true])("runs the actual Bash helper with HTTP/2 enabled=%s", async duplex => {
|
||||
const fixture = await server.fixture({ apiToolsEnabled: false });
|
||||
await server.db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, fixture.agentId));
|
||||
await server.db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, fixture.runId));
|
||||
const token = createLocalAgentJwt(fixture.agentId, fixture.companyId, "codex_local", fixture.runId)!;
|
||||
const remote = await execution(fixture.workspace);
|
||||
const installedHelper = await remote.write("paperclip-upload-artifact.sh", await readFile(helper));
|
||||
const target: AdapterSandboxExecutionTarget = {
|
||||
kind: "remote", transport: "sandbox", providerKey: liveDaytona ? "daytona" : "local-test", remoteCwd: remote.workspace,
|
||||
runner: remote.runner, timeoutMs: 30_000,
|
||||
effectiveCapabilities: {
|
||||
reusableLeases: false, nativeSyncIn: false, nativeSyncOut: false,
|
||||
persistentProcessSessions: false, independentControlCommands: false,
|
||||
incrementalSessionOutput: false, concurrentSyncOperations: false,
|
||||
duplexCommandStream: true, runnerWebSocketIngress: false,
|
||||
},
|
||||
};
|
||||
const bridge = await startAdapterExecutionTargetPaperclipBridge({
|
||||
runId: fixture.runId, target, runtimeRootDir: path.join(remote.workspace, ".runtime"),
|
||||
adapterKey: "codex", hostApiToken: token, hostApiUrl: server.apiUrl,
|
||||
enableSandboxDuplexBridge: duplex,
|
||||
});
|
||||
expect(bridge?.env.PAPERCLIP_API_BRIDGE_MODE).toBe(duplex ? "http2_v1" : "queue_v1");
|
||||
const env = { ...bridge!.env, PAPERCLIP_RUN_ID: fixture.runId,
|
||||
PAPERCLIP_COMPANY_ID: fixture.companyId, PAPERCLIP_TASK_ID: fixture.issueId,
|
||||
PAPERCLIP_HELPER_STATE_DIR: path.join(remote.workspace, ".helper-state") };
|
||||
const headers = { authorization: `Bearer ${bridge!.env.PAPERCLIP_API_KEY}` };
|
||||
const receipts: Array<{ attachment: { id: string; contentPath: string; downloadPath: string } }> = [];
|
||||
try {
|
||||
for (const file of files) {
|
||||
const local = await remote.write(file.name, file.body);
|
||||
const args = [installedHelper, local, "--content-type", file.type, "--title", file.name, "--chat-comment", "Requested files", "--output", "json"];
|
||||
const receipt = JSON.parse(await remote.run("bash", args, env));
|
||||
const duplicate = JSON.parse(await remote.run("bash", args, env));
|
||||
expect(duplicate.attachment.id).toBe(receipt.attachment.id);
|
||||
expect(duplicate.workProduct.id).toBe(receipt.workProduct.id);
|
||||
expect(duplicate.chatComment.id).toBe(receipt.chatComment.id);
|
||||
expect(receipt.attachment.originalFilename).toBe(file.name);
|
||||
expect(receipt.attachment.originatingRunId).toBe(fixture.runId);
|
||||
const download = await remote.fetch(bridge!.env.PAPERCLIP_API_URL + receipt.attachment.downloadPath, headers);
|
||||
expect(download.status).toBe(200);
|
||||
expect(Buffer.from(await download.arrayBuffer())).toEqual(file.body);
|
||||
receipts.push(receipt);
|
||||
}
|
||||
const foreign = await server.fixture();
|
||||
const denied = await remote.fetch(`${bridge!.env.PAPERCLIP_API_URL}/api/issues/${foreign.issueId}/attachments`, headers);
|
||||
expect(denied.status).toBe(404);
|
||||
const unauthorized = await remote.fetch(`${bridge!.env.PAPERCLIP_API_URL}/api/issues/${fixture.issueId}/attachments`, { authorization: "Bearer wrong-token" });
|
||||
expect(unauthorized.status).toBe(401);
|
||||
expect(await server.db.select().from(issueAttachments).where(eq(issueAttachments.issueId, fixture.issueId))).toHaveLength(2);
|
||||
expect(await server.db.select().from(issueWorkProducts).where(eq(issueWorkProducts.issueId, fixture.issueId))).toHaveLength(2);
|
||||
expect(await server.db.select().from(issueComments).where(eq(issueComments.issueId, fixture.issueId))).toHaveLength(1);
|
||||
} finally { await bridge?.stop(); await remote.close(); }
|
||||
// The workspace and runner are gone; a fresh request still reads persisted bytes.
|
||||
await rm(fixture.workspace, { recursive: true, force: true });
|
||||
for (const [index, receipt] of receipts.entries()) {
|
||||
const download = await fetch(server.apiUrl + receipt.attachment.contentPath, { headers: { authorization: `Bearer ${token}` } });
|
||||
expect(download.status).toBe(200);
|
||||
expect(Buffer.from(await download.arrayBuffer())).toEqual(files[index].body);
|
||||
}
|
||||
}, liveDaytona ? 240_000 : 60_000);
|
||||
|
||||
it("registers native files with API tools disabled and returns durable download receipts", async () => {
|
||||
const fixture = await server.fixture({ apiToolsEnabled: false });
|
||||
const remote = await execution(fixture.workspace);
|
||||
const authority = new PaperclipRunnerToolAuthority(server.db, { ...fixture,
|
||||
workspaceRoot: remote.workspace, executionTargetKind: liveDaytona ? "remote" : "local",
|
||||
readRemoteWorkspaceFile: liveDaytona ? request => readVerifiedRemoteWorkspaceFile({ ...request, runner: remote.runner, workspaceRoot: remote.workspace }) : undefined,
|
||||
});
|
||||
expect(authority.definitions().some(definition => definition.name === "register_deliverable")).toBe(true);
|
||||
expect(authority.definitions().some(definition => definition.name === "api_post")).toBe(false);
|
||||
const token = createLocalAgentJwt(fixture.agentId, fixture.companyId, "paperclip_runner", fixture.runId)!;
|
||||
const receipts: Array<{ downloadPath: string }> = [];
|
||||
for (const file of files) {
|
||||
await remote.write(`out/${file.name}`, file.body);
|
||||
const call = { tool: "register_deliverable", callId: file.name, arguments: {
|
||||
contentRef: `out/${file.name}`, filename: file.name, contentType: file.type, byteSize: file.body.length,
|
||||
sha256: createHash("sha256").update(file.body).digest("hex"), title: file.name, idempotencyKey: file.name,
|
||||
} };
|
||||
const receipt = await authority.execute(call) as { attachmentId: string; contentPath: string; downloadPath: string; entityRefs: string[] };
|
||||
expect(receipt.attachmentId).toBe(receipt.entityRefs[0]);
|
||||
expect(await authority.execute(call)).toEqual(receipt);
|
||||
receipts.push(receipt);
|
||||
}
|
||||
await remote.close();
|
||||
await rm(fixture.workspace, { recursive: true, force: true });
|
||||
for (const [index, receipt] of receipts.entries()) {
|
||||
const download = await fetch(server.apiUrl + receipt.downloadPath, { headers: { authorization: `Bearer ${token}` } });
|
||||
expect(download.status).toBe(200);
|
||||
expect(Buffer.from(await download.arrayBuffer())).toEqual(files[index].body);
|
||||
}
|
||||
const rows = await server.db.select().from(issueAttachments).where(eq(issueAttachments.issueId, fixture.issueId));
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows.every(row => row.originatingRunId === fixture.runId && row.issueCommentId)).toBe(true);
|
||||
await server.db.update(issues).set({ executionRunId: null }).where(eq(issues.id, fixture.issueId));
|
||||
await expect(authority.execute({ tool: "register_deliverable", callId: "stale", arguments: {} })).rejects.toThrow();
|
||||
}, liveDaytona ? 240_000 : 15_000);
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { createRequire } from "node:module";
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
import { shellQuote } from "@paperclipai/adapter-utils/ssh";
|
||||
import { openDaytonaDuplexChannelSession, type DaytonaPtyProcess } from "../../../../packages/plugins/sandbox-providers/daytona/src/duplex-command-stream.js";
|
||||
|
||||
/** Opt-in live fixture; uses an isolated sandbox and never reuses a user's lease. */
|
||||
export async function startFileDeliveryDaytona() {
|
||||
const require = createRequire(new URL("../../../../packages/plugins/sandbox-providers/daytona/package.json", import.meta.url));
|
||||
const { Daytona } = require("@daytonaio/sdk");
|
||||
const sandbox: {
|
||||
id: string;
|
||||
process: DaytonaPtyProcess & { executeCommand(command: string, cwd?: string, env?: Record<string, string>, timeout?: number): Promise<{ exitCode: number; result: string }> };
|
||||
delete(): Promise<void>;
|
||||
} = await new Daytona({ apiKey: process.env.DAYTONA_API_KEY }).create({
|
||||
language: "typescript", autoStopInterval: 10,
|
||||
labels: { "paperclip-test": "gus-file-delivery" },
|
||||
});
|
||||
const workspace = "/home/daytona/gus-file-delivery";
|
||||
// Capture stdout/stderr separately: SDK result text otherwise combines them.
|
||||
const executeSource = `
|
||||
const {spawn} = require('node:child_process');
|
||||
const input = JSON.parse(process.argv[1]);
|
||||
const child = spawn(input.command, input.args || [], {
|
||||
cwd: input.cwd, env: {...process.env, ...input.env}, timeout: input.timeoutMs || 30000
|
||||
});
|
||||
const stdout = [], stderr = [];
|
||||
child.stdout.on('data', chunk => stdout.push(chunk));
|
||||
child.stderr.on('data', chunk => stderr.push(chunk));
|
||||
child.on('error', error => stderr.push(Buffer.from(error.message)));
|
||||
child.on('close', (exitCode, signal) => process.stdout.write(JSON.stringify({
|
||||
exitCode, signal, timedOut: signal === 'SIGTERM', pid: null,
|
||||
startedAt: new Date().toISOString(),
|
||||
stdout: Buffer.concat(stdout).toString(), stderr: Buffer.concat(stderr).toString()
|
||||
})));
|
||||
child.stdin.on('error', error => { if (error.code !== 'EPIPE') stderr.push(Buffer.from(error.message)); });
|
||||
child.stdin.end(input.stdin || '');
|
||||
`;
|
||||
const runner: CommandManagedRuntimeRunner = {
|
||||
execute: async input => {
|
||||
const command = `node --input-type=commonjs -e ${shellQuote(executeSource)} ${shellQuote(JSON.stringify(input))}`;
|
||||
const result = await sandbox.process.executeCommand(command, undefined, undefined, Math.ceil((input.timeoutMs ?? 30000) / 1000) + 10);
|
||||
if (result.exitCode !== 0) throw new Error(`Daytona test command transport failed (exit ${result.exitCode})`);
|
||||
return JSON.parse(result.result);
|
||||
},
|
||||
openDuplexChannel: async ({ command }) => {
|
||||
const session = await openDaytonaDuplexChannelSession(sandbox.process, command);
|
||||
return {
|
||||
write: bytes => session.write(bytes), onData: listener => session.onData(listener),
|
||||
onExit: listener => { void session.wait().then(listener); },
|
||||
stop: () => session.kill(), close: () => session.close(),
|
||||
};
|
||||
},
|
||||
};
|
||||
try {
|
||||
const setup = await runner.execute({ command: "bash", args: ["-lc", `mkdir -p ${shellQuote(workspace)} && command -v node && command -v curl && command -v jq`], timeoutMs: 30000 });
|
||||
if (setup.exitCode !== 0) throw new Error("Daytona test image requires node, curl, and jq");
|
||||
return { workspace, runner, close: () => sandbox.delete() };
|
||||
} catch (error) { await sandbox.delete(); throw error; }
|
||||
}
|
||||
@@ -589,6 +589,46 @@ describe("issue attachment routes", () => {
|
||||
]).toContain(res.headers["content-disposition"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
filename: '猫 "chart"; 100%.png',
|
||||
contentType: "image/png",
|
||||
filenameParameters: String.raw`filename="? \"chart\"; 100%.png"; filename*=UTF-8''%E7%8C%AB%20%22chart%22%3B%20100%25.png`,
|
||||
},
|
||||
{
|
||||
filename: 'report "final"; 100%.pdf',
|
||||
contentType: "application/pdf",
|
||||
filenameParameters: String.raw`filename="report \"final\"; 100%.pdf"`,
|
||||
},
|
||||
].flatMap((file) => [false, true].flatMap((download) =>
|
||||
[false, true].map((range) => ({ ...file, download, range })),
|
||||
)))("preserves disposition filenames: $filename (download=$download, range=$range)", async ({
|
||||
filename, contentType, filenameParameters, download, range,
|
||||
}) => {
|
||||
const bytes = Buffer.from([0, 255, 128, 10, 13, 42]);
|
||||
const storage = createStorageService(bytes);
|
||||
mockIssueService.getAttachmentById.mockResolvedValue({
|
||||
...makeAttachment(contentType, filename),
|
||||
byteSize: bytes.length,
|
||||
});
|
||||
const app = await createApp(storage);
|
||||
const downloadRequest = request(app)
|
||||
.get(`/api/attachments/attachment-1/content${download ? "?download=1" : ""}`)
|
||||
.buffer(true)
|
||||
.parse(parseBinaryResponse);
|
||||
if (range) downloadRequest.set("Range", "bytes=1-3");
|
||||
const res = await downloadRequest;
|
||||
|
||||
expect(res.status).toBe(range ? 206 : 200);
|
||||
expect(res.headers["content-disposition"]).toBe(`${download ? "attachment" : "inline"}; ${filenameParameters}`);
|
||||
expect(res.headers["content-type"]).toBe(contentType);
|
||||
expect(res.headers["content-length"]).toBe(String(range ? 3 : bytes.length));
|
||||
expect(res.headers["accept-ranges"]).toBe("bytes");
|
||||
expect(res.headers["content-range"]).toBe(range ? "bytes 1-3/6" : undefined);
|
||||
expect(res.headers["x-content-type-options"]).toBe("nosniff");
|
||||
expect(res.body).toEqual(range ? bytes.subarray(1, 4) : bytes);
|
||||
});
|
||||
|
||||
it("serves video attachments inline with byte-range support", async () => {
|
||||
const storage = createStorageService(Buffer.from("abcdef"));
|
||||
mockIssueService.getAttachmentById.mockResolvedValue({
|
||||
|
||||
@@ -23,7 +23,7 @@ async function makeArtifactHelperHarness(
|
||||
cleanupDirs: Set<string>,
|
||||
options: {
|
||||
apiUrl?: string;
|
||||
ambiguousHttpStatusAfterCommit?: "408" | "502";
|
||||
ambiguousHttpStatusAfterCommit?: "408" | "409" | "502";
|
||||
commitAfterDropDelaySeconds?: string;
|
||||
dropFirstUpload?: boolean;
|
||||
dropWithoutCommit?: boolean;
|
||||
@@ -151,7 +151,7 @@ if [[ "$method" == "POST" && "$url" == */attachments ]]; then
|
||||
printf '%s' "$PAPERCLIP_RUN_ID" >"$FAKE_CURL_STATE_DIR/originating-run-id"
|
||||
if [[ -n "\${FAKE_CURL_AMBIGUOUS_STATUS:-}" && ! -f "$FAKE_CURL_STATE_DIR/upload-status-used" ]]; then
|
||||
: >"$FAKE_CURL_STATE_DIR/upload-status-used"
|
||||
respond '{"error":"ambiguous upstream response"}' "$FAKE_CURL_AMBIGUOUS_STATUS"
|
||||
respond '{"error":"ambiguous upstream response","outcome":"indeterminate","retryable":false}' "$FAKE_CURL_AMBIGUOUS_STATUS"
|
||||
exit 0
|
||||
fi
|
||||
if [[ "\${FAKE_CURL_MALFORMED_SUCCESS:-0}" == "1" && ! -f "$FAKE_CURL_STATE_DIR/malformed-success-used" ]]; then
|
||||
@@ -311,7 +311,7 @@ describe("paperclip skill utils", () => {
|
||||
expect(normalizedShortcut).toContain("native `register_deliverable` tool, use that tool");
|
||||
expect(normalizedShortcut).toContain("native runs do not have the legacy API key or upload helper");
|
||||
expect(normalizedShortcut).toContain(
|
||||
"For non-native adapters, invoke `scripts/paperclip-upload-artifact.sh` directly",
|
||||
"For non-native adapters, invoke `bash scripts/paperclip-upload-artifact.sh`",
|
||||
);
|
||||
expect(normalizedShortcut).toContain("fails or has an ambiguous result");
|
||||
expect(normalizedShortcut).toContain("use the full heartbeat procedure below");
|
||||
@@ -336,7 +336,7 @@ describe("paperclip skill utils", () => {
|
||||
expect(await fs.readFile(path.join(harness.stateDir, "upload-count"), "utf8")).toBe("1");
|
||||
});
|
||||
|
||||
it.each(["408", "502"] as const)(
|
||||
it.each(["408", "409", "502"] as const)(
|
||||
"keeps upload ambiguity after an HTTP %s until the immutable attachment is observed",
|
||||
async (status) => {
|
||||
const harness = await makeArtifactHelperHarness(cleanupDirs, {
|
||||
|
||||
@@ -4855,6 +4855,8 @@ export function issueRoutes(
|
||||
) {
|
||||
const upload = multer({
|
||||
storage: multer.memoryStorage(),
|
||||
// Curl and browser FormData send unlabelled filenames as UTF-8.
|
||||
defParamCharset: "utf8",
|
||||
limits: { fileSize: fileSizeLimit, files: 1 },
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
@@ -18567,6 +18569,8 @@ export function issueRoutes(
|
||||
contentType: responseContentType,
|
||||
originalFilename: attachment.originalFilename,
|
||||
});
|
||||
// Express formats filenames with an encoded Unicode parameter when needed.
|
||||
res.attachment(attachment.originalFilename ?? "attachment");
|
||||
res.setHeader(
|
||||
"Content-Type",
|
||||
isMarkdownResponse
|
||||
@@ -18581,7 +18585,6 @@ export function issueRoutes(
|
||||
"sandbox; default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'",
|
||||
);
|
||||
}
|
||||
const filename = attachment.originalFilename ?? "attachment";
|
||||
const disposition = parseBooleanQuery(req.query.download)
|
||||
? "attachment"
|
||||
: isInlineAttachmentContentType(responseContentType)
|
||||
@@ -18589,7 +18592,7 @@ export function issueRoutes(
|
||||
: "attachment";
|
||||
res.setHeader(
|
||||
"Content-Disposition",
|
||||
`${disposition}; filename=\"${filename.replaceAll('"', "")}\"`,
|
||||
String(res.getHeader("Content-Disposition")).replace(/^attachment;/, `${disposition};`),
|
||||
);
|
||||
|
||||
object.stream.on("error", (err) => {
|
||||
|
||||
@@ -8569,7 +8569,7 @@ export function buildPaperclipTaskMarkdown(input: {
|
||||
lines.push(
|
||||
"",
|
||||
"External chat file delivery:",
|
||||
"When asked to send an image or file back to this chat, use the bundled Paperclip artifact helper `scripts/paperclip-upload-artifact.sh --chat-comment <caption>` with the local file. Resolve the helper from the installed skill location, not the task workspace. This selects the uploaded file for Paperclip's final-response delivery; an upload or artifact record alone does not. For ordinary file handoffs the helper is the direct path; consult the skill's artifact reference for advanced options, missing tooling, failures, or ambiguous results. Do not search for a separate provider tool connection or fetch a CLI with `npx` to send chat files. Bind only the files the user asked to share, and do not claim provider delivery merely because binding succeeded. GitHub uses task links/notices rather than native file uploads.",
|
||||
"When asked to send an image or file back to this chat, use the bundled Paperclip artifact helper `bash scripts/paperclip-upload-artifact.sh --chat-comment <caption>` with the local file. Resolve the helper from the installed skill location, not the task workspace. This selects the uploaded file for Paperclip's final-response delivery; an upload or artifact record alone does not. For ordinary file handoffs the helper is the direct path; consult the skill's artifact reference for advanced options, missing tooling, failures, or ambiguous results. Do not search for a separate provider tool connection or fetch a CLI with `npx` to send chat files. Bind only the files the user asked to share, and do not claim provider delivery merely because binding succeeded. GitHub uses task links/notices rather than native file uploads.",
|
||||
"Prepare and validate the requested files together. Batch independent file preparation and one helper command per file into as few tool calls as practical. Use the same caption for files in one reply so their helper calls share one handoff comment. After a helper reports success, its attachment, artifact, and comment binding are already recorded: do not manually bind the same file again, re-list those records, or add a second handoff comment just to confirm success. Complete the required final-response protocol using the successful receipts. Retry or investigate only a failed or ambiguous step; never repeat a successful upload merely to confirm it.",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -285,11 +285,17 @@ describe("native runner file handoff", () => {
|
||||
stateRevision: 0,
|
||||
entityRefs: [expect.any(String), expect.any(String), expect.any(String)],
|
||||
scheduledWakeIds: [],
|
||||
attachmentId: first.entityRefs[0],
|
||||
contentPath: `/api/attachments/${first.entityRefs[0]}/content`,
|
||||
downloadPath: `/api/attachments/${first.entityRefs[0]}/content?download=1`,
|
||||
});
|
||||
expect(replay).toEqual(first);
|
||||
expect(replayWithNewKey).toMatchObject({
|
||||
disposition: "duplicate",
|
||||
entityRefs: first.entityRefs,
|
||||
attachmentId: first.attachmentId,
|
||||
contentPath: first.contentPath,
|
||||
downloadPath: first.downloadPath,
|
||||
});
|
||||
|
||||
await expect(nativeCompletionFeedback(db, runId, doneReport([`deliverable:${first.entityRefs[0]}`])))
|
||||
|
||||
@@ -63,6 +63,9 @@ export interface NativeRunnerFileHandoffResult {
|
||||
readonly stateRevision: number;
|
||||
readonly entityRefs: readonly string[];
|
||||
readonly scheduledWakeIds: readonly string[];
|
||||
readonly attachmentId: string;
|
||||
readonly contentPath: string;
|
||||
readonly downloadPath: string;
|
||||
}
|
||||
|
||||
export interface PreparedNativeRunnerFileHandoff {
|
||||
@@ -1195,6 +1198,9 @@ export async function prepareNativeRunnerFileHandoff(input: {
|
||||
result: {
|
||||
commandId: `deliverable-prepared:${existing.attachmentId}`,
|
||||
disposition: "duplicate",
|
||||
attachmentId: existing.attachmentId,
|
||||
contentPath: `/api/attachments/${existing.attachmentId}/content`,
|
||||
downloadPath: `/api/attachments/${existing.attachmentId}/content?download=1`,
|
||||
stateRevision: statusVersion,
|
||||
entityRefs: [
|
||||
existing.attachmentId,
|
||||
@@ -1265,6 +1271,9 @@ export async function prepareNativeRunnerFileHandoff(input: {
|
||||
result: {
|
||||
commandId: `deliverable-prepared:${attachment.id}`,
|
||||
disposition: "applied",
|
||||
attachmentId: attachment.id,
|
||||
contentPath: `/api/attachments/${attachment.id}/content`,
|
||||
downloadPath: `/api/attachments/${attachment.id}/content?download=1`,
|
||||
stateRevision: statusVersion,
|
||||
entityRefs: [
|
||||
attachment.id,
|
||||
|
||||
@@ -2,7 +2,9 @@ import { createHash } from "node:crypto";
|
||||
import { posix } from "node:path";
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
|
||||
export const MAX_REMOTE_DELIVERABLE_BYTES = 10 * 1024 * 1024;
|
||||
import { MAX_ATTACHMENT_BYTES } from "../../attachment-types.js";
|
||||
|
||||
export const MAX_REMOTE_DELIVERABLE_BYTES = MAX_ATTACHMENT_BYTES;
|
||||
const PREFIX = "paperclip_runner_file_handoff_";
|
||||
const READ_TIMEOUT_MS = 10_000;
|
||||
|
||||
|
||||
Reference in new issue
Block a user