Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(tasks): stage attachments until task submission

Tin077cc63d7876
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 8c0eaa963..afc1c1b9d 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -450,6 +450,7 @@ export function createApp() {
mimeType: schema.assetTable.mimeType,
filename: schema.assetTable.filename,
surface: schema.assetTable.surface,
+ createdBy: schema.assetTable.createdBy,
workspaceId: schema.assetTable.workspaceId,
isPublic: schema.projectTable.isPublic,
})
diff --git a/apps/api/src/scheduler/draft-upload-cleanup.ts b/apps/api/src/scheduler/draft-upload-cleanup.ts
new file mode 100644
index 000000000..b8e3d9d5d
--- /dev/null
+++ b/apps/api/src/scheduler/draft-upload-cleanup.ts
@@ -0,0 +1,23 @@
+import { and, inArray, isNull, lt } from "drizzle-orm";
+import db from "../database";
+import { assetTable } from "../database/schema";
+import { queueStorageCleanup } from "../storage/cleanup-queue";
+
+export async function cleanupDraftUploads() {
+ await db.transaction(async (tx) => {
+ const expired = await tx
+ .delete(assetTable)
+ .where(
+ and(
+ inArray(assetTable.surface, ["draft", "draft-pending"]),
+ isNull(assetTable.taskId),
+ lt(assetTable.createdAt, new Date(Date.now() - 24 * 60 * 60 * 1000)),
+ ),
+ )
+ .returning({ objectKey: assetTable.objectKey });
+ await queueStorageCleanup(
+ tx,
+ expired.map((asset) => asset.objectKey),
+ );
+ });
+}
diff --git a/apps/api/src/scheduler/index.ts b/apps/api/src/scheduler/index.ts
index 7a917530b..6e3ffae78 100644
--- a/apps/api/src/scheduler/index.ts
+++ b/apps/api/src/scheduler/index.ts
@@ -1,4 +1,5 @@
import { retryStorageCleanup } from "../storage/cleanup-queue";
+import { cleanupDraftUploads } from "./draft-upload-cleanup";
import * as Sentry from "@sentry/node";
import { Cron } from "croner";
import { checkDueDateReminders } from "./due-date-reminders";
@@ -52,7 +53,12 @@ export function initializeScheduler(): void {
withCheckIn("storage-cleanup", retryStorageCleanup),
),
);
-
+ jobs.push(
+ new Cron(
+ "31 * * * *",
+ withCheckIn("draft-upload-cleanup", cleanupDraftUploads),
+ ),
+ );
jobs.push(
new Cron(
"*/5 * * * *",
diff --git a/apps/api/src/task/controllers/create-task.ts b/apps/api/src/task/controllers/create-task.ts
index dd08fa955..78b89eab8 100644
--- a/apps/api/src/task/controllers/create-task.ts
+++ b/apps/api/src/task/controllers/create-task.ts
@@ -1,7 +1,8 @@
-import { and, eq } from "drizzle-orm";
+import { and, eq, inArray, isNull } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
+ assetTable,
columnTable,
customFieldDefinitionTable,
customFieldValueTable,
@@ -53,6 +54,7 @@ async function createTask({
description,
priority,
customFields,
+ draftAssetIds,
}: {
projectId: string;
currentUserId: string;
@@ -64,6 +66,7 @@ async function createTask({
description?: string;
priority?: string;
customFields?: CustomFieldInput[];
+ draftAssetIds?: string[];
}) {
const resolvedStatus = status || "to-do";
const resolvedPriority = priority || "no-priority";
@@ -152,6 +155,28 @@ async function createTask({
})
.returning();
+ if (task && draftAssetIds?.length) {
+ const ids = [...new Set(draftAssetIds)];
+ const claimed = await tx
+ .update(assetTable)
+ .set({ taskId: task.id, surface: "description" })
+ .where(
+ and(
+ inArray(assetTable.id, ids),
+ eq(assetTable.projectId, projectId),
+ eq(assetTable.createdBy, currentUserId),
+ eq(assetTable.surface, "draft"),
+ isNull(assetTable.taskId),
+ ),
+ )
+ .returning({ id: assetTable.id });
+ if (claimed.length !== ids.length)
+ throw new HTTPException(400, {
+ message:
+ "Some staged uploads are unavailable or belong to another owner/project",
+ });
+ }
+
if (task && mergedCustomFields.length) {
await tx.insert(customFieldValueTable).values(
mergedCustomFields.map(({ fieldId, value }) => ({
diff --git a/apps/api/src/task/controllers/stage-task-asset.ts b/apps/api/src/task/controllers/stage-task-asset.ts
new file mode 100644
index 000000000..c2d98894d
--- /dev/null
+++ b/apps/api/src/task/controllers/stage-task-asset.ts
@@ -0,0 +1,120 @@
+import { and, eq, inArray, isNull } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { assetTable, projectTable } from "../../database/schema";
+import {
+ assertTaskImageKeyMatchesContext,
+ createTaskImageUploadUrl,
+ InvalidUploadedAssetError,
+ isImageContentType,
+ validateTaskAssetUploadInput,
+ verifyTaskAssetUpload,
+} from "../../storage/s3";
+
+type Upload = { filename: string; contentType: string; size: number };
+async function uploadContext(projectId: string, userId: string) {
+ const project = await db.query.projectTable.findFirst({
+ where: eq(projectTable.id, projectId),
+ });
+ if (!project) throw new HTTPException(404, { message: "Project not found" });
+ return {
+ workspaceId: project.workspaceId,
+ projectId,
+ taskId: `draft-${userId}`,
+ surface: "description" as const,
+ };
+}
+function validate(input: Upload) {
+ try {
+ validateTaskAssetUploadInput(input.contentType, input.size);
+ } catch (error) {
+ throw new HTTPException(400, {
+ message: error instanceof Error ? error.message : "Invalid upload",
+ });
+ }
+}
+export async function stageTaskAssetUpload(
+ projectId: string,
+ userId: string,
+ input: Upload,
+) {
+ validate(input);
+ const context = await uploadContext(projectId, userId);
+ try {
+ const upload = await createTaskImageUploadUrl({ ...context, ...input });
+ await db.insert(assetTable).values({
+ workspaceId: context.workspaceId,
+ projectId,
+ taskId: null,
+ objectKey: upload.key,
+ filename: input.filename,
+ mimeType: input.contentType,
+ size: input.size,
+ kind: isImageContentType(input.contentType) ? "image" : "attachment",
+ surface: "draft-pending",
+ createdBy: userId,
+ });
+ return upload;
+ } catch {
+ throw new HTTPException(503, {
+ message: "Image uploads are not configured",
+ });
+ }
+}
+export async function finalizeStagedTaskAsset(
+ projectId: string,
+ userId: string,
+ input: Upload & { key: string },
+) {
+ validate(input);
+ const context = await uploadContext(projectId, userId);
+ const key = input.key.trim();
+ if (!assertTaskImageKeyMatchesContext(key, context))
+ throw new HTTPException(400, {
+ message: "Upload key does not match the draft owner and project",
+ });
+ let uploaded: Awaited<ReturnType<typeof verifyTaskAssetUpload>>;
+ try {
+ uploaded = await verifyTaskAssetUpload(key, input);
+ } catch (error) {
+ throw new HTTPException(
+ error instanceof InvalidUploadedAssetError ? 400 : 503,
+ {
+ message:
+ error instanceof Error ? error.message : "Unable to verify upload",
+ },
+ );
+ }
+ const existing = await db.query.assetTable.findFirst({
+ where: eq(assetTable.objectKey, key),
+ });
+ if (
+ !existing ||
+ !["draft", "draft-pending"].includes(existing.surface) ||
+ existing.createdBy !== userId ||
+ existing.projectId !== projectId ||
+ existing.taskId !== null
+ )
+ throw new HTTPException(409, {
+ message: "Upload is unavailable or already attached",
+ });
+ const [asset] = await db
+ .update(assetTable)
+ .set({
+ mimeType: uploaded.contentType,
+ size: uploaded.size,
+ kind: isImageContentType(uploaded.contentType) ? "image" : "attachment",
+ surface: "draft",
+ })
+ .where(
+ and(
+ eq(assetTable.id, existing.id),
+ isNull(assetTable.taskId),
+ inArray(assetTable.surface, ["draft", "draft-pending"]),
+ ),
+ )
+ .returning({ id: assetTable.id });
+ if (!asset)
+ throw new HTTPException(409, { message: "Upload is already attached" });
+ return asset;
+}
diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.ts
index 53c2e04e9..6545614bd 100644
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@ -43,6 +43,10 @@ import getTask from "./controllers/get-task";
import getTasks from "./controllers/get-tasks";
import importTasks from "./controllers/import-tasks";
import moveTask from "./controllers/move-task";
+import {
+ stageTaskAssetUpload,
+ finalizeStagedTaskAsset,
+} from "./controllers/stage-task-asset";
import {
requireBulkTaskEntitlement,
requireBulkTaskPermission,
@@ -147,6 +151,62 @@ const bulkUpdateTasksRoute = createRoute({
},
});
+const stagedUploadRoute = createRoute({
+ method: "post",
+ operationId: "stageTaskAssetUpload",
+ path: "/draft-upload/{projectId}",
+ tags: ["Tasks"],
+ summary: "Stage a task attachment",
+ description:
+ "Upload an attachment before submitting a task. Staged assets are private to the uploader and expire after 24 hours.",
+ middleware: [
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ task: ["create"] }),
+ requireEntitlement,
+ ] as const,
+ request: {
+ params: projectIdParam,
+ body: {
+ required: true,
+ content: { "application/json": { schema: imageUploadBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("Presigned upload", imageUploadSchema),
+ 400: errorResponse("Invalid upload"),
+ 403: errorResponse("Missing task:create permission"),
+ 404: errorResponse("Project not found"),
+ 503: errorResponse("Storage unavailable"),
+ },
+});
+const finalizeStagedUploadRoute = createRoute({
+ method: "post",
+ operationId: "finalizeStagedTaskAsset",
+ path: "/draft-upload/{projectId}/finalize",
+ tags: ["Tasks"],
+ summary: "Finalize a staged task attachment",
+ middleware: [
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ task: ["create"] }),
+ requireEntitlement,
+ ] as const,
+ request: {
+ params: projectIdParam,
+ body: {
+ required: true,
+ content: { "application/json": { schema: finalizeImageUploadBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("Staged attachment", finalizedAssetSchema),
+ 400: errorResponse("Invalid upload"),
+ 403: errorResponse("Missing task:create permission"),
+ 404: errorResponse("Project not found"),
+ 409: errorResponse("Upload already attached"),
+ 503: errorResponse("Storage unavailable"),
+ },
+});
+
const createTaskRoute = createRoute({
method: "post",
operationId: "createTask",
@@ -698,6 +758,27 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()
return c.json(result, 200);
})
+ .openapi(stagedUploadRoute, async (c) =>
+ c.json(
+ await stageTaskAssetUpload(
+ c.req.valid("param").projectId,
+ c.get("userId"),
+ c.req.valid("json"),
+ ),
+ 200,
+ ),
+ )
+ .openapi(finalizeStagedUploadRoute, async (c) => {
+ const asset = await finalizeStagedTaskAsset(
+ c.req.valid("param").projectId,
+ c.get("userId"),
+ c.req.valid("json"),
+ );
+ const base = normalizeApiServerUrl(
+ process.env.KANEO_API_URL || new URL(c.req.url).origin,
+ );
+ return c.json({ id: asset.id, url: `${base}/asset/${asset.id}` }, 200);
+ })
.openapi(createTaskRoute, async (c) => {
const { projectId } = c.req.param();
const {
@@ -709,6 +790,7 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()
status,
userId,
customFields,
+ draftAssetIds,
} = c.req.valid("json");
const parsedStartDate =
@@ -733,6 +815,7 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()
priority,
status,
customFields,
+ draftAssetIds,
});
return c.json(task, 200);
diff --git a/apps/api/src/task/schema.ts b/apps/api/src/task/schema.ts
index ab85f70ee..40f56b451 100644
--- a/apps/api/src/task/schema.ts
+++ b/apps/api/src/task/schema.ts
@@ -73,6 +73,7 @@ export const createTaskBody = z.object({
priority,
status: z.string().openapi({ description: "The target column's slug." }),
userId: z.string().optional().openapi({ description: "Assignee, if any." }),
+ draftAssetIds: z.array(z.string()).max(100).optional(),
customFields: z
.array(z.object({ fieldId: z.string(), value: z.string() }))
.optional(),
diff --git a/apps/api/src/utils/authorize-asset-access.ts b/apps/api/src/utils/authorize-asset-access.ts
index 3686d7de4..ae9a5ad2b 100644
--- a/apps/api/src/utils/authorize-asset-access.ts
+++ b/apps/api/src/utils/authorize-asset-access.ts
@@ -1,4 +1,5 @@
import type { Context } from "hono";
+import { HTTPException } from "hono/http-exception";
import { resolveAssetBearerOrCookie } from "./authenticate-api-request";
import { validateWorkspaceAccess } from "./validate-workspace-access";
@@ -6,6 +7,7 @@ type AssetAccessTarget = {
workspaceId: string;
isPublic: boolean | null;
surface: string;
+ createdBy?: string | null;
};
/** Only description assets belong to the public project representation. */
@@ -22,5 +24,9 @@ export async function authorizeAssetAccess(
}
const { userId, apiKeyId } = await resolveAssetBearerOrCookie(c);
+ if (asset.surface.startsWith("draft") && asset.createdBy !== userId)
+ throw new HTTPException(403, {
+ message: "Staged uploads are private to their owner",
+ });
await validateWorkspaceAccess(userId, asset.workspaceId, apiKeyId);
}
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index b263bb917..507fefd55 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -913,6 +913,47 @@
"updatedCount"
]
},
+ "TaskImageUpload": {
+ "type": "object",
+ "properties": {
+ "key": {
+ "type": "string",
+ "description": "Object key to send back to the finalize route."
+ },
+ "uploadUrl": {
+ "type": "string",
+ "description": "Presigned URL to PUT the image bytes to."
+ },
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "Headers that must accompany the upload request, including Content-Type."
+ }
+ },
+ "required": [
+ "key",
+ "uploadUrl",
+ "headers"
+ ]
+ },
+ "TaskImageAsset": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string",
+ "description": "Where the stored image can be read back from."
+ }
+ },
+ "required": [
+ "id",
+ "url"
+ ]
+ },
"Task": {
"type": "object",
"properties": {
@@ -1213,47 +1254,6 @@
"tasks"
]
},
- "TaskImageUpload": {
- "type": "object",
- "properties": {
- "key": {
- "type": "string",
- "description": "Object key to send back to the finalize route."
- },
- "uploadUrl": {
- "type": "string",
- "description": "Presigned URL to PUT the image bytes to."
- },
- "headers": {
- "type": "object",
- "additionalProperties": {
- "type": "string"
- },
- "description": "Headers that must accompany the upload request, including Content-Type."
- }
- },
- "required": [
- "key",
- "uploadUrl",
- "headers"
- ]
- },
- "TaskImageAsset": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string"
- },
- "url": {
- "type": "string",
- "description": "Where the stored image can be read back from."
- }
- },
- "required": [
- "id",
- "url"
- ]
- },
"Column": {
"type": "object",
"properties": {
@@ -8550,6 +8550,240 @@
}
}
},
+ "/task/draft-upload/{projectId}": {
+ "post": {
+ "operationId": "stageTaskAssetUpload",
+ "tags": [
+ "Tasks"
+ ],
+ "summary": "Stage a task attachment",
+ "description": "Upload an attachment before submitting a task. Staged assets are private to the uploader and expire after 24 hours.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "projectId",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "filename": {
+ "type": "string"
+ },
+ "contentType": {
+ "type": "string"
+ },
+ "size": {
+ "type": "number"
+ },
+ "surface": {
+ "type": "string",
+ "enum": [
+ "description",
+ "comment"
+ ],
+ "description": "Where the image is used, which decides how it is scoped."
+ }
+ },
+ "required": [
+ "filename",
+ "contentType",
+ "size",
+ "surface"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Presigned upload",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TaskImageUpload"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid upload",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "Missing task:create permission",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Project not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Storage unavailable",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/task/draft-upload/{projectId}/finalize": {
+ "post": {
+ "operationId": "finalizeStagedTaskAsset",
+ "tags": [
+ "Tasks"
+ ],
+ "summary": "Finalize a staged task attachment",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "projectId",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "key": {
+ "type": "string",
+ "description": "The key returned when the URL was issued."
+ },
+ "filename": {
+ "type": "string"
+ },
+ "contentType": {
+ "type": "string"
+ },
+ "size": {
+ "type": "number"
+ },
+ "surface": {
+ "type": "string",
+ "enum": [
+ "description",
+ "comment"
+ ],
+ "description": "Where the image is used, which decides how it is scoped."
+ }
+ },
+ "required": [
+ "key",
+ "filename",
+ "contentType",
+ "size",
+ "surface"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Staged attachment",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TaskImageAsset"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid upload",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "Missing task:create permission",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Project not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "Upload already attached",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Storage unavailable",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/task/{projectId}": {
"post": {
"operationId": "createTask",
@@ -8605,6 +8839,13 @@
"type": "string",
"description": "Assignee, if any."
},
+ "draftAssetIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 100
+ },
"customFields": {
"type": "array",
"items": {
diff --git a/apps/web/src/components/activity/comment-editor.tsx b/apps/web/src/components/activity/comment-editor.tsx
index b5ac73b32..4b0cc2f8e 100644
--- a/apps/web/src/components/activity/comment-editor.tsx
+++ b/apps/web/src/components/activity/comment-editor.tsx
@@ -91,6 +91,9 @@ type CommentEditorProps = {
taskId?: string;
uploadSurface?: "description" | "comment";
ensureTaskId?: () => Promise<string | null>;
+ uploadAsset?: (
+ file: File,
+ ) => Promise<Awaited<ReturnType<typeof uploadTaskImage>>>;
showQuickAttachButton?: boolean;
onAttachActionChange?: (attach: (() => void) | null) => void;
};
@@ -176,6 +179,7 @@ export default function CommentEditor({
taskId,
uploadSurface = "comment",
ensureTaskId,
+ uploadAsset,
showQuickAttachButton = true,
onAttachActionChange,
}: CommentEditorProps) {
@@ -212,6 +216,8 @@ export default function CommentEditor({
}, []);
const taskIdRef = useRef(taskId);
const ensureTaskIdRef = useRef(ensureTaskId);
+ const uploadAssetRef = useRef(uploadAsset);
+ uploadAssetRef.current = uploadAsset;
const uploadSurfaceRef = useRef(uploadSurface);
const onSubmitShortcutRef = useRef(onSubmitShortcut);
const onCancelShortcutRef = useRef(onCancelShortcut);
@@ -346,7 +352,7 @@ export default function CommentEditor({
const resolvedTaskId =
initialTaskId ?? (await ensureTaskIdRef.current?.());
- if (!activeEditor || !resolvedTaskId) {
+ if (!activeEditor || (!resolvedTaskId && !uploadAssetRef.current)) {
toast.error(t("activity:comment.editor.uploadsOnlyOnSavedTasks"));
return;
}
@@ -356,11 +362,13 @@ export default function CommentEditor({
);
try {
- const uploadedAsset = await uploadTaskImage({
- taskId: resolvedTaskId,
- surface: uploadSurfaceRef.current,
- file,
- });
+ const uploadedAsset = uploadAssetRef.current
+ ? await uploadAssetRef.current(file)
+ : await uploadTaskImage({
+ taskId: resolvedTaskId!,
+ surface: uploadSurfaceRef.current,
+ file,
+ });
// Reuse a replacement editor only while it still belongs to the task
// that owns the uploaded asset.
@@ -402,7 +410,7 @@ export default function CommentEditor({
[insertUploadedAsset, t],
);
- const canUploadFiles = Boolean(taskId || ensureTaskId);
+ const canUploadFiles = Boolean(taskId || ensureTaskId || uploadAsset);
const openImagePicker = useCallback(
(activeEditor?: Editor | null, range?: SlashRange) => {
diff --git a/apps/web/src/components/shared/modals/create-task-modal.test.tsx b/apps/web/src/components/shared/modals/create-task-modal.test.tsx
index 999a39046..8a8d59113 100644
--- a/apps/web/src/components/shared/modals/create-task-modal.test.tsx
+++ b/apps/web/src/components/shared/modals/create-task-modal.test.tsx
@@ -45,7 +45,11 @@ const setProject = vi.fn();
let workspaceId = "workspace-1";
let projects: { id: string; name: string; slug: string }[] | undefined;
let storedProject: { id: string; columns: unknown[] } | null = null;
-let ensureTaskId: (() => Promise<string | null>) | undefined;
+let uploadAsset: ((file: File) => Promise<unknown>) | undefined;
+const stageUpload = vi.fn();
+vi.mock("@/lib/upload-draft-asset", () => ({
+ uploadDraftAsset: (...args: unknown[]) => stageUpload(...args),
+}));
beforeEach(() => {
workspaceId = "workspace-1";
@@ -85,9 +89,9 @@ vi.mock("@tanstack/react-router", () => ({
vi.mock("@/components/task/task-description-editor", () => ({
default: (props: {
taskId?: string;
- ensureTaskId: () => Promise<string | null>;
+ uploadAsset: (file: File) => Promise<unknown>;
}) => {
- ensureTaskId = props.ensureTaskId;
+ uploadAsset = props.uploadAsset;
return <div data-testid="description-editor" data-task-id={props.taskId} />;
},
}));
@@ -302,24 +306,6 @@ function submit() {
fireEvent.submit(document.querySelector("form") as HTMLFormElement);
}
-function pendingCreate() {
- let resolve!: (task: never) => void;
- createTask.mockImplementationOnce(
- () =>
- new Promise((done) => {
- resolve = done;
- }),
- );
- return () =>
- resolve({
- id: "old-draft",
- title: "Draft",
- status: "planned",
- projectId: "project-2",
- createdAt: "2026-08-05T00:00:00.000Z",
- } as never);
-}
-
describe("CreateTaskModal context isolation", () => {
it("never falls back to the last globally visited project", () => {
storedProject = { id: "foreign-project", columns: [] };
@@ -396,81 +382,79 @@ describe("CreateTaskModal context isolation", () => {
});
enterTitle();
submit();
- await expect(ensureTaskId?.()).resolves.toBeNull();
+ await expect(uploadAsset?.(new File(["x"], "x.png"))).rejects.toThrow();
expect(createTask).not.toHaveBeenCalled();
},
);
- it("deletes a late draft after navigation without handing its ID to an upload", async () => {
- const finish = pendingCreate();
- const view = render(<CreateTaskModal open onClose={vi.fn()} />, {
+ it("stages attachments without creating a task and claims them only on submit", async () => {
+ stageUpload.mockResolvedValue({
+ id: "staged-1",
+ url: "/asset/staged-1",
+ kind: "image",
+ });
+ render(<CreateTaskModal open onClose={vi.fn()} />, {
wrapper: createWrapper(),
});
await chooseBeta();
- let pending!: Promise<string | null>;
- act(() => {
- pending = ensureTaskId?.() as Promise<string | null>;
- });
- workspaceId = "workspace-2";
- useLocation.mockReturnValue({
- pathname: "/dashboard/workspace/workspace-2",
- });
- view.rerender(<CreateTaskModal open onClose={vi.fn()} />);
+ enterTitle();
await act(async () => {
- finish();
- await pending;
+ await uploadAsset?.(new File(["x"], "x.png"));
});
- await expect(pending).resolves.toBeNull();
- expect(deleteTask).toHaveBeenCalledExactlyOnceWith("old-draft");
- expect(screen.getByTestId("description-editor")).not.toHaveAttribute(
- "data-task-id",
- );
+ expect(createTask).not.toHaveBeenCalled();
expect(updateTask).not.toHaveBeenCalled();
- expect(setProject).not.toHaveBeenCalled();
+ submit();
+ await vi.waitFor(() => expect(createTask).toHaveBeenCalledOnce());
+ expect(createTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ draftAssetIds: ["staged-1"],
+ projectId: "project-2",
+ }),
+ );
});
- it("waits for the upload draft on submit and saves that task only once", async () => {
- const finish = pendingCreate();
+ it("does not submit while attachments are uploading", async () => {
+ let finish!: (value: unknown) => void;
+ stageUpload.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
render(<CreateTaskModal open onClose={vi.fn()} />, {
wrapper: createWrapper(),
});
await chooseBeta();
enterTitle();
- let pending!: Promise<string | null>;
+ let pending!: Promise<unknown>;
act(() => {
- pending = ensureTaskId?.() as Promise<string | null>;
+ pending = uploadAsset!(new File(["x"], "x.png"));
});
+ expect(
+ screen.getByText("activity:comment.editor.uploadingFile"),
+ ).toBeDisabled();
submit();
- submit();
- expect(updateTask).not.toHaveBeenCalled();
+ expect(createTask).not.toHaveBeenCalled();
await act(async () => {
- finish();
+ finish({ id: "staged-2" });
await pending;
});
- await vi.waitFor(() =>
- expect(updateTask).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({
- id: "old-draft",
- projectId: "project-2",
- title: "Private task",
- }),
- ),
- );
- expect(createTask).toHaveBeenCalledTimes(1);
- expect(deleteTask).not.toHaveBeenCalled();
+ submit();
+ await vi.waitFor(() => expect(createTask).toHaveBeenCalledOnce());
});
- it("discards an existing draft on close and never puts it into another project's store", async () => {
- storedProject = { id: "project-1", columns: [] };
+ it("closing after an upload creates no published task or deletion side effect", async () => {
+ stageUpload.mockResolvedValue({ id: "staged-1" });
const view = render(<CreateTaskModal open onClose={vi.fn()} />, {
wrapper: createWrapper(),
});
await chooseBeta();
await act(async () => {
- await ensureTaskId?.();
+ await uploadAsset?.(new File(["x"], "x.png"));
});
view.rerender(<CreateTaskModal open={false} onClose={vi.fn()} />);
- expect(deleteTask).toHaveBeenCalledExactlyOnceWith("task-1");
+ expect(createTask).not.toHaveBeenCalled();
+ expect(deleteTask).not.toHaveBeenCalled();
expect(setProject).not.toHaveBeenCalled();
});
});
diff --git a/apps/web/src/components/shared/modals/create-task-modal.tsx b/apps/web/src/components/shared/modals/create-task-modal.tsx
index e7382e3f8..c28952098 100644
--- a/apps/web/src/components/shared/modals/create-task-modal.tsx
+++ b/apps/web/src/components/shared/modals/create-task-modal.tsx
@@ -75,11 +75,8 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
-import useSetCustomFieldValue from "@/hooks/mutations/custom-field/use-set-custom-field-value";
import useCreateLabel from "@/hooks/mutations/label/use-create-label";
import useCreateTask from "@/hooks/mutations/task/use-create-task";
-import { useDeleteTask } from "@/hooks/mutations/task/use-delete-task";
-import { useUpdateTask } from "@/hooks/mutations/task/use-update-task";
import useGetCustomFieldsByProject from "@/hooks/queries/custom-field/use-get-custom-fields-by-project";
import useGetLabelsByWorkspace from "@/hooks/queries/label/use-get-labels-by-workspace";
import useGetProjects from "@/hooks/queries/project/use-get-projects";
@@ -87,6 +84,7 @@ import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";
import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";
import { useWorkspacePermission } from "@/hooks/use-workspace-permission";
import { cn } from "@/lib/cn";
+import { uploadDraftAsset } from "@/lib/upload-draft-asset";
import { formatDateMedium } from "@/lib/format";
import { getInitials } from "@/lib/get-initials";
import { resolveLabelColor } from "@/lib/label-color";
@@ -252,7 +250,6 @@ function CreateTaskModalContent({
const [dueDate, setDueDate] = useState<Date | undefined>(undefined);
const [createMore, setCreateMore] = useState(false);
const [labels, setLabels] = useState<Label[]>([]);
- const [draftTask, setDraftTask] = useState<Task | null>(null);
const [discardConfirmationOpen, setDiscardConfirmationOpen] = useState(false);
const [labelsOpen, setLabelsOpen] = useState(false);
@@ -276,8 +273,8 @@ function CreateTaskModalContent({
const resolvedProjectId = resolvedProject?.id ?? "";
const searchInputRef = useRef<HTMLInputElement>(null);
- const draftCreationPromiseRef = useRef<Promise<Task | null> | null>(null);
- const draftTaskRef = useRef<Task | null>(null);
+ const stagedAssetsRef = useRef<string[]>([]);
+ const pendingUploadsRef = useRef(0);
const activeRef = useRef(true);
const submittingRef = useRef(false);
const [isPreparingDraft, setIsPreparingDraft] = useState(false);
@@ -286,8 +283,6 @@ function CreateTaskModalContent({
const didSubmitRef = useRef(false);
const { mutateAsync: createTask } = useCreateTask();
- const { mutateAsync: updateTask } = useUpdateTask();
- const { mutateAsync: deleteTask } = useDeleteTask();
const { data: rawCustomFields } = useGetCustomFieldsByProject(
resolvedProjectId,
@@ -295,8 +290,6 @@ function CreateTaskModalContent({
const customFields = useMemo(() => rawCustomFields ?? [], [rawCustomFields]);
- const { mutateAsync: setCustomFieldValue } = useSetCustomFieldValue();
-
const [customFieldValues, setCustomFieldValues] = useState<
Record<string, string>
>({});
@@ -365,31 +358,20 @@ function CreateTaskModalContent({
dueDate ||
selectedProjectId ||
labels.length > 0 ||
- draftTask ||
+ stagedAssetsRef.current.length > 0 ||
hasCustomFieldChanges,
);
- const discardDraft = useCallback(() => {
- const abandoned = draftTaskRef.current;
- if (abandoned && !didSubmitRef.current) {
- draftTaskRef.current = null;
- void deleteTask(abandoned.id).catch(() => {
- // An expired session can prevent cleanup; never reuse the draft.
- });
- }
- }, [deleteTask]);
-
useEffect(() => {
activeRef.current = true;
return () => {
activeRef.current = false;
- discardDraft();
};
- }, [discardDraft]);
+ }, []);
const handleClose = () => {
activeRef.current = false;
- discardDraft();
+
onClose();
};
@@ -464,87 +446,34 @@ function CreateTaskModalContent({
[project, setProject, workspaceUsers?.members],
);
- const ensureDraftTask = useCallback(async () => {
- if (!activeRef.current || submittingRef.current) return null;
- if (draftTaskRef.current) {
- return draftTaskRef.current.projectId === resolvedProjectId
- ? draftTaskRef.current.id
- : null;
- }
-
- if (draftCreationPromiseRef.current) {
- const pendingTask = await draftCreationPromiseRef.current;
- return activeRef.current ? (pendingTask?.id ?? null) : null;
- }
-
- if (!resolvedProjectId) {
- toast.error(t("common:modals.createTask.chooseProjectForImages"));
- return null;
- }
-
- setIsPreparingDraft(true);
- const draftStatus = "planned";
- const draftPromise = createTask({
- title: title.trim() || t("common:modals.createTask.untitledTask"),
- description: description.trim() || "",
- userId: assigneeId,
- priority,
- projectId: resolvedProjectId,
- startDate: startDate ? startDate.toISOString() : undefined,
- dueDate: dueDate ? dueDate.toISOString() : undefined,
- status: draftStatus,
- customFields: Object.entries(customFieldValues)
- .filter(([_, value]) => value.trim() !== "")
- .map(([fieldId, value]) => ({
- fieldId,
- value,
- })),
- }).then((task) => {
- const createdTask = normalizeTask(task);
- if (!activeRef.current) {
- void deleteTask(createdTask.id).catch(() => {});
- return null;
+ const stageAsset = useCallback(
+ async (file: File) => {
+ if (!activeRef.current || submittingRef.current || !resolvedProjectId) {
+ throw new Error(t("common:modals.createTask.chooseProjectForImages"));
}
- draftTaskRef.current = createdTask;
- setDraftTask(createdTask);
- return createdTask;
- });
-
- draftCreationPromiseRef.current = draftPromise;
-
- try {
- const createdTask = await draftPromise;
- return activeRef.current ? (createdTask?.id ?? null) : null;
- } catch (error) {
- toast.error(
- error instanceof Error
- ? error.message
- : t("common:modals.createTask.prepareTaskError"),
- );
- return null;
- } finally {
- draftCreationPromiseRef.current = null;
- if (activeRef.current) setIsPreparingDraft(false);
- }
- }, [
- assigneeId,
- createTask,
- description,
- deleteTask,
- startDate,
- dueDate,
- priority,
- resolvedProjectId,
- title,
- t,
- customFieldValues,
- ]);
+ pendingUploadsRef.current += 1;
+ setIsPreparingDraft(true);
+ try {
+ const asset = await uploadDraftAsset(resolvedProjectId, file);
+ if (!activeRef.current)
+ throw new Error(t("common:modals.createTask.prepareTaskError"));
+ stagedAssetsRef.current.push(asset.id);
+ return asset;
+ } finally {
+ pendingUploadsRef.current -= 1;
+ if (activeRef.current)
+ setIsPreparingDraft(pendingUploadsRef.current > 0);
+ }
+ },
+ [resolvedProjectId, t],
+ );
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (
!activeRef.current ||
submittingRef.current ||
+ pendingUploadsRef.current > 0 ||
!canCreateTaskCapability ||
!title.trim() ||
!resolvedProjectId ||
@@ -555,50 +484,27 @@ function CreateTaskModalContent({
submittingRef.current = true;
setIsSubmitting(true);
try {
- // Submitting while a file prepares its draft must update that same task.
- const pendingDraft = draftCreationPromiseRef.current;
- if (pendingDraft) await pendingDraft;
- if (!activeRef.current) return;
- const currentDraft = draftTaskRef.current;
- if (currentDraft && currentDraft.projectId !== resolvedProjectId) return;
const taskStatus = status ?? "to-do";
didSubmitRef.current = true;
-
- const savedTask = currentDraft
- ? normalizeTask(
- await updateTask({
- ...currentDraft,
- title: title.trim(),
- description: description.trim() || "",
- userId: assigneeId || null,
- status: taskStatus,
- priority,
- startDate: startDate ? startDate.toISOString() : null,
- dueDate: dueDate ? dueDate.toISOString() : null,
- projectId: resolvedProjectId,
- customFieldValues: Object.entries(customFieldValues)
- .filter(([_, value]) => value.trim() !== "")
- .map(([fieldId, value]) => ({ fieldId, value })),
- }),
- )
- : normalizeTask(
- await createTask({
- title: title.trim(),
- description: description.trim() || "",
- userId: assigneeId,
- priority,
- projectId: resolvedProjectId,
- startDate: startDate ? startDate.toISOString() : undefined,
- dueDate: dueDate ? dueDate.toISOString() : undefined,
- status: taskStatus,
- customFields: Object.entries(customFieldValues)
- .filter(([_, value]) => value.trim() !== "")
- .map(([fieldId, value]) => ({
- fieldId,
- value,
- })),
- }),
- );
+ const savedTask = normalizeTask(
+ await createTask({
+ title: title.trim(),
+ description: description.trim() || "",
+ userId: assigneeId,
+ priority,
+ projectId: resolvedProjectId,
+ startDate: startDate ? startDate.toISOString() : undefined,
+ dueDate: dueDate ? dueDate.toISOString() : undefined,
+ status: taskStatus,
+ draftAssetIds: stagedAssetsRef.current,
+ customFields: Object.entries(customFieldValues)
+ .filter(([_, value]) => value.trim() !== "")
+ .map(([fieldId, value]) => ({
+ fieldId,
+ value,
+ })),
+ }),
+ );
for (const label of labels) {
try {
@@ -613,27 +519,10 @@ function CreateTaskModalContent({
}
}
- if (currentDraft) {
- for (const [fieldId, value] of Object.entries(customFieldValues)) {
- if (value) {
- await setCustomFieldValue({
- taskId: savedTask.id,
- fieldId,
- value: String(value),
- });
- }
- }
- }
-
- draftTaskRef.current = null;
+ stagedAssetsRef.current = [];
if (!activeRef.current) return;
- setDraftTask(savedTask);
syncTaskIntoProject(savedTask);
- toast.success(
- draftTask
- ? t("common:modals.createTask.successUpdated")
- : t("common:modals.createTask.successCreated"),
- );
+ toast.success(t("common:modals.createTask.successCreated"));
if (createMore) {
setTitle("");
@@ -647,10 +536,10 @@ function CreateTaskModalContent({
setSearchValue("");
setSelectedColor("gray");
setNewLabelName("");
- draftCreationPromiseRef.current = null;
+ stagedAssetsRef.current = [];
setEditorVersion((version) => version + 1);
didSubmitRef.current = false;
- setDraftTask(null);
+
setCustomFieldValues(buildDefaultCustomFieldValues());
} else {
closeAndReset();
@@ -658,7 +547,6 @@ function CreateTaskModalContent({
} catch (error) {
didSubmitRef.current = false;
if (!activeRef.current) {
- discardDraft();
return;
}
toast.error(
@@ -1091,8 +979,7 @@ function CreateTaskModalContent({
placeholder={t(
"common:modals.createTask.descriptionPlaceholder",
)}
- taskId={draftTask?.id}
- ensureTaskId={ensureDraftTask}
+ uploadAsset={stageAsset}
/>
</div>
@@ -1204,12 +1091,14 @@ function CreateTaskModalContent({
type="button"
className="w-full flex items-center gap-2 px-2 py-1.5 text-sm hover:bg-accent/50 text-left transition-colors h-8"
disabled={
- isPreparingDraft || !!draftTask || isSubmitting
+ isPreparingDraft ||
+ stagedAssetsRef.current.length > 0 ||
+ isSubmitting
}
onClick={() => {
if (
- !draftCreationPromiseRef.current &&
- !draftTaskRef.current &&
+ pendingUploadsRef.current === 0 &&
+ stagedAssetsRef.current.length === 0 &&
!submittingRef.current
) {
setSelectedProjectId(workspaceProject.id);
@@ -1601,11 +1490,19 @@ function CreateTaskModalContent({
</Button>
<Button
type="submit"
- disabled={!title.trim() || !resolvedProjectId || isSubmitting}
+ disabled={
+ !title.trim() ||
+ !resolvedProjectId ||
+ isSubmitting ||
+ isPreparingDraft
+ }
+ aria-busy={isPreparingDraft || isSubmitting}
size="sm"
className="disabled:opacity-50"
>
- {t("common:modals.createTask.createButton")}
+ {isPreparingDraft
+ ? t("activity:comment.editor.uploadingFile")
+ : t("common:modals.createTask.createButton")}
</Button>
</DialogFooter>
</form>
diff --git a/apps/web/src/components/task/task-description-editor.tsx b/apps/web/src/components/task/task-description-editor.tsx
index 8cb088fda..9d5977511 100644
--- a/apps/web/src/components/task/task-description-editor.tsx
+++ b/apps/web/src/components/task/task-description-editor.tsx
@@ -1,4 +1,5 @@
import { useTranslation } from "react-i18next";
+import type { uploadTaskImage } from "@/lib/upload-task-image";
import CommentEditor from "@/components/activity/comment-editor";
type TaskDescriptionEditorProps = {
@@ -7,6 +8,9 @@ type TaskDescriptionEditorProps = {
placeholder?: string;
taskId?: string;
ensureTaskId?: () => Promise<string | null>;
+ uploadAsset?: (
+ file: File,
+ ) => Promise<Awaited<ReturnType<typeof uploadTaskImage>>>;
};
export default function TaskDescriptionEditor({
@@ -15,6 +19,7 @@ export default function TaskDescriptionEditor({
placeholder,
taskId,
ensureTaskId,
+ uploadAsset,
}: TaskDescriptionEditorProps) {
const { t } = useTranslation();
@@ -25,6 +30,7 @@ export default function TaskDescriptionEditor({
placeholder={placeholder ?? t("tasks:detail.addDescription")}
taskId={taskId}
ensureTaskId={ensureTaskId}
+ uploadAsset={uploadAsset}
uploadSurface="description"
className="[&_.kaneo-comment-editor-content_.ProseMirror]:min-h-[11rem] [&_.kaneo-comment-editor-content_.ProseMirror]:max-h-none [&_.kaneo-comment-editor-content_.ProseMirror]:overflow-visible [&_.kaneo-comment-editor-content_.ProseMirror]:px-0 [&_.kaneo-comment-editor-content_.ProseMirror]:pt-1 [&_.kaneo-comment-editor-content_.ProseMirror]:pb-2"
/>
diff --git a/apps/web/src/fetchers/task/create-task.ts b/apps/web/src/fetchers/task/create-task.ts
index 0039acc69..252de24fa 100644
--- a/apps/web/src/fetchers/task/create-task.ts
+++ b/apps/web/src/fetchers/task/create-task.ts
@@ -17,6 +17,7 @@ async function createTask(
dueDate: Date | undefined,
priority: CreateTaskRequest["priority"],
customFields?: { fieldId: string; value: string }[],
+ draftAssetIds?: string[],
) {
if (!projectId) {
throw new Error("No project selected for task creation");
@@ -32,6 +33,7 @@ async function createTask(
dueDate: dueDate?.toISOString() || undefined,
priority,
customFields,
+ draftAssetIds,
},
param: { projectId },
});
diff --git a/apps/web/src/hooks/mutations/task/use-create-task.ts b/apps/web/src/hooks/mutations/task/use-create-task.ts
index d99e0143c..a15f4ba71 100644
--- a/apps/web/src/hooks/mutations/task/use-create-task.ts
+++ b/apps/web/src/hooks/mutations/task/use-create-task.ts
@@ -17,6 +17,7 @@ function useCreateTask() {
dueDate,
priority,
customFields,
+ draftAssetIds,
}: CreateTaskRequest) =>
createTask(
title,
@@ -28,6 +29,7 @@ function useCreateTask() {
dueDate ? new Date(dueDate) : undefined,
priority,
customFields,
+ draftAssetIds,
),
onSuccess: (_data, variables) => {
void queryClient.invalidateQueries({
diff --git a/apps/web/src/lib/upload-draft-asset.ts b/apps/web/src/lib/upload-draft-asset.ts
new file mode 100644
index 000000000..79a5458c9
--- /dev/null
+++ b/apps/web/src/lib/upload-draft-asset.ts
@@ -0,0 +1,44 @@
+import { client } from "@kaneo/libs";
+import { HttpError } from "@/lib/http-error";
+import { getImageAltText, isSupportedImageFile } from "@/lib/upload-task-image";
+
+export async function uploadDraftAsset(projectId: string, file: File) {
+ const json = {
+ filename: file.name || "file",
+ contentType: file.type || "application/octet-stream",
+ size: file.size,
+ surface: "description" as const,
+ };
+ const response = await client.task["draft-upload"][":projectId"].$post({
+ param: { projectId },
+ json,
+ });
+ if (!response.ok) throw new HttpError(response.status, await response.text());
+ const upload = await response.json();
+ const stored = await fetch(upload.uploadUrl, {
+ method: "PUT",
+ headers: upload.headers,
+ body: file,
+ });
+ if (!stored.ok) throw new Error("Failed to upload file to storage.");
+ const finalized = await client.task["draft-upload"][
+ ":projectId"
+ ].finalize.$post({
+ param: { projectId },
+ json: { ...json, key: upload.key },
+ });
+ if (!finalized.ok)
+ throw new HttpError(finalized.status, await finalized.text());
+ const asset = await finalized.json();
+ return {
+ id: asset.id,
+ url: asset.url,
+ alt: getImageAltText(file.name),
+ filename: json.filename,
+ kind: isSupportedImageFile(file)
+ ? ("image" as const)
+ : ("attachment" as const),
+ mimeType: json.contentType,
+ size: file.size,
+ };
+}
diff --git a/tests/api-integration/staged-task-attachments.test.ts b/tests/api-integration/staged-task-attachments.test.ts
new file mode 100644
index 000000000..248997db6
--- /dev/null
+++ b/tests/api-integration/staged-task-attachments.test.ts
@@ -0,0 +1,160 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import createTask from "../../apps/api/src/task/controllers/create-task";
+import {
+ stageTaskAssetUpload,
+ finalizeStagedTaskAsset,
+} from "../../apps/api/src/task/controllers/stage-task-asset";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+const publish = vi.hoisted(() => vi.fn(async () => undefined));
+vi.mock("../../apps/api/src/events", () => ({ publishEvent: publish }));
+vi.mock("../../apps/api/src/storage/s3", () => ({
+ validateTaskAssetUploadInput: vi.fn(),
+ createTaskImageUploadUrl: vi.fn(async (context: { taskId: string }) => ({
+ key: `${context.taskId}/test.png`,
+ uploadUrl: "https://example.test/upload",
+ headers: {},
+ })),
+ assertTaskImageKeyMatchesContext: vi.fn(
+ (key: string, context: { taskId: string }) =>
+ key.startsWith(`${context.taskId}/`),
+ ),
+ verifyTaskAssetUpload: vi.fn(async () => ({
+ size: 12,
+ contentType: "image/png",
+ })),
+ isImageContentType: () => true,
+ InvalidUploadedAssetError: class extends Error {},
+}));
+beforeEach(async () => {
+ await resetTestDatabase();
+ vi.clearAllMocks();
+});
+describe("staged task attachments", () => {
+ it("creates no task or integration event until explicit submission", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const input = { filename: "image.png", contentType: "image/png", size: 12 };
+ const upload = await stageTaskAssetUpload(project.id, user.id, input);
+ expect(await db.query.taskTable.findMany()).toHaveLength(0);
+ expect(await db.query.assetTable.findMany()).toEqual([
+ expect.objectContaining({
+ taskId: null,
+ surface: "draft-pending",
+ objectKey: upload.key,
+ }),
+ ]);
+ const asset = await finalizeStagedTaskAsset(project.id, user.id, {
+ ...input,
+ key: upload.key,
+ });
+ expect(publish).not.toHaveBeenCalled();
+ const task = await createTask({
+ projectId: project.id,
+ currentUserId: user.id,
+ title: "submitted",
+ status: "to-do",
+ description: `/api/asset/${asset.id}`,
+ draftAssetIds: [asset.id],
+ });
+ expect(
+ await db.query.assetTable.findFirst({
+ where: eq(schema.assetTable.id, asset.id),
+ }),
+ ).toMatchObject({ taskId: task.id, surface: "description" });
+ expect(publish).toHaveBeenCalledTimes(1);
+ expect(publish).toHaveBeenCalledWith(
+ "task.created",
+ expect.objectContaining({ taskId: task.id }),
+ );
+ });
+ it("cannot claim an upload belonging to another creator or project", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const outsider = await createWorkspaceMember();
+ const [asset] = await db
+ .insert(schema.assetTable)
+ .values({
+ workspaceId: workspace.id,
+ projectId: project.id,
+ objectKey: "other-owner",
+ filename: "x",
+ mimeType: "image/png",
+ size: 12,
+ surface: "draft",
+ createdBy: outsider.user.id,
+ })
+ .returning();
+ await expect(
+ createTask({
+ projectId: project.id,
+ currentUserId: user.id,
+ title: "bad",
+ status: "to-do",
+ draftAssetIds: [asset.id],
+ }),
+ ).rejects.toThrow("staged uploads");
+ expect(await db.query.taskTable.findMany()).toHaveLength(0);
+ expect(publish).not.toHaveBeenCalled();
+ });
+ it("cannot submit an upload before finalization", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ await stageTaskAssetUpload(project.id, user.id, {
+ filename: "image.png",
+ contentType: "image/png",
+ size: 12,
+ });
+ const [asset] = await db.query.assetTable.findMany();
+ await expect(
+ createTask({
+ projectId: project.id,
+ currentUserId: user.id,
+ title: "bad",
+ status: "to-do",
+ draftAssetIds: [asset.id],
+ }),
+ ).rejects.toThrow("staged uploads");
+ expect(await db.query.taskTable.findMany()).toHaveLength(0);
+ });
+});
+
+it("expires abandoned pending and finalized uploads without deleting published assets", async () => {
+ const { cleanupDraftUploads } =
+ await import("../../apps/api/src/scheduler/draft-upload-cleanup");
+ const { workspace, user } = await createWorkspaceMember({ role: "owner" });
+ const { project } = await createProjectFixture({ workspaceId: workspace.id });
+ await db.insert(schema.assetTable).values(
+ ["draft", "draft-pending", "description"].map((surface) => ({
+ workspaceId: workspace.id,
+ projectId: project.id,
+ surface,
+ objectKey: `synthetic-expiry-${surface}`,
+ filename: "test.png",
+ mimeType: "image/png",
+ size: 1,
+ createdBy: user.id,
+ createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000),
+ })),
+ );
+ await cleanupDraftUploads();
+ expect(
+ (await db.select().from(schema.assetTable)).map((asset) => asset.surface),
+ ).toEqual(["description"]);
+ expect(
+ (await db.select().from(schema.storageCleanupTable))
+ .map((item) => item.objectKey)
+ .sort(),
+ ).toEqual(["synthetic-expiry-draft", "synthetic-expiry-draft-pending"]);
+});
diff --git a/tests/api/utils/authorize-asset-access.test.ts b/tests/api/utils/authorize-asset-access.test.ts
index cc7ef840e..cbf51bd2c 100644
--- a/tests/api/utils/authorize-asset-access.test.ts
+++ b/tests/api/utils/authorize-asset-access.test.ts
@@ -123,4 +123,24 @@ describe("authorizeAssetAccess", () => {
expect(await statusOf(authorizeAssetAccess(context, asset))).toBe(200);
},
);
+ it.each(["draft", "draft-pending"])(
+ "keeps %s uploads private to the uploader even in public projects",
+ async (surface) => {
+ state.caller = "member";
+ const asset = {
+ workspaceId: "workspace-1",
+ isPublic: true,
+ surface,
+ createdBy: "user-other-member",
+ };
+ expect(isPublicAsset(asset)).toBe(false);
+ expect(await statusOf(authorizeAssetAccess(context, asset))).toBe(403);
+ expect(state.validateCalls).toHaveLength(0);
+ expect(
+ await statusOf(
+ authorizeAssetAccess(context, { ...asset, createdBy: "user-member" }),
+ ),
+ ).toBe(200);
+ },
+ );
});