⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat: enhance file upload functionality for attachments
Andrejc76af9dcd712
diff --git a/apps/api/drizzle/0014_private_assets.sql b/apps/api/drizzle/0014_private_assets.sqlnew file mode 100644index 000000000..725bd1a8d--- /dev/null+++ b/apps/api/drizzle/0014_private_assets.sql@@ -0,0 +1,26 @@+CREATE TABLE "asset" (+ "id" text PRIMARY KEY NOT NULL,+ "workspace_id" text NOT NULL,+ "project_id" text NOT NULL,+ "task_id" text,+ "activity_id" text,+ "object_key" text NOT NULL,+ "filename" text NOT NULL,+ "mime_type" text NOT NULL,+ "size" integer NOT NULL,+ "kind" text DEFAULT 'image' NOT NULL,+ "surface" text DEFAULT 'description' NOT NULL,+ "created_by" text,+ "created_at" timestamp DEFAULT now() NOT NULL,+ CONSTRAINT "asset_object_key_unique" UNIQUE("object_key")+);+--> statement-breakpoint+ALTER TABLE "asset" ADD CONSTRAINT "asset_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint+ALTER TABLE "asset" ADD CONSTRAINT "asset_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint+ALTER TABLE "asset" ADD CONSTRAINT "asset_task_id_task_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."task"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint+ALTER TABLE "asset" ADD CONSTRAINT "asset_activity_id_activity_id_fk" FOREIGN KEY ("activity_id") REFERENCES "public"."activity"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint+ALTER TABLE "asset" ADD CONSTRAINT "asset_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE cascade;--> statement-breakpoint+CREATE INDEX "asset_workspaceId_idx" ON "asset" USING btree ("workspace_id");--> statement-breakpoint+CREATE INDEX "asset_projectId_idx" ON "asset" USING btree ("project_id");--> statement-breakpoint+CREATE INDEX "asset_taskId_idx" ON "asset" USING btree ("task_id");--> statement-breakpoint+CREATE INDEX "asset_activityId_idx" ON "asset" USING btree ("activity_id");diff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.jsonindex e7da74f59..c8b014564 100644--- a/apps/api/drizzle/meta/_journal.json+++ b/apps/api/drizzle/meta/_journal.json@@ -99,6 +99,13 @@"when": 1772660160328,"tag": "0013_quiet_gladiator","breakpoints": true+ },+ {+ "idx": 14,+ "version": "7",+ "when": 1773259300000,+ "tag": "0014_private_assets",+ "breakpoints": true}]}diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.tsindex 75c6d9d72..0aab6c127 100644--- a/apps/api/src/database/index.ts+++ b/apps/api/src/database/index.ts@@ -5,6 +5,7 @@ import {accountTableRelations,activityTableRelations,apikeyTableRelations,+ assetTableRelations,columnTableRelations,externalLinkTableRelations,githubIntegrationTableRelations,@@ -28,6 +29,7 @@ import {accountTable,activityTable,apikeyTable,+ assetTable,columnTable,externalLinkTable,githubIntegrationTable,@@ -58,6 +60,7 @@ const pool = new Pool({export const schema = {accountTable,+ assetTable,activityTable,apikeyTable,columnTable,@@ -79,6 +82,7 @@ export const schema = {workspaceTable,workspaceUserTable,accountTableRelations,+ assetTableRelations,activityTableRelations,apikeyTableRelations,columnTableRelations,diff --git a/apps/api/src/database/relations.ts b/apps/api/src/database/relations.tsindex fa8a2497a..ff17e709e 100644--- a/apps/api/src/database/relations.ts+++ b/apps/api/src/database/relations.ts@@ -3,6 +3,7 @@ import {accountTable,activityTable,apikeyTable,+ assetTable,columnTable,externalLinkTable,githubIntegrationTable,@@ -32,6 +33,7 @@ export const userTableRelations = relations(userTable, ({ many }) => ({assignedTasks: many(taskTable),timeEntries: many(timeEntryTable),activities: many(activityTable),+ assets: many(assetTable),notifications: many(notificationTable),sentInvitations: many(invitationTable),apikeys: many(apikeyTable),@@ -62,6 +64,7 @@ export const workspaceTableRelations = relations(teams: many(teamTable),members: many(workspaceUserTable),projects: many(projectTable),+ assets: many(assetTable),invitations: many(invitationTable),}),);@@ -88,6 +91,7 @@ export const projectTableRelations = relations(references: [workspaceTable.id],}),tasks: many(taskTable),+ assets: many(assetTable),columns: many(columnTable),workflowRules: many(workflowRuleTable),githubIntegration: many(githubIntegrationTable),@@ -133,6 +137,7 @@ export const taskTableRelations = relations(taskTable, ({ one, many }) => ({}),timeEntries: many(timeEntryTable),activities: many(activityTable),+ assets: many(assetTable),labels: many(labelTable),externalLinks: many(externalLinkTable),}));@@ -159,6 +164,29 @@ export const activityTableRelations = relations(activityTable, ({ one }) => ({}),}));+export const assetTableRelations = relations(assetTable, ({ one }) => ({+ workspace: one(workspaceTable, {+ fields: [assetTable.workspaceId],+ references: [workspaceTable.id],+ }),+ project: one(projectTable, {+ fields: [assetTable.projectId],+ references: [projectTable.id],+ }),+ task: one(taskTable, {+ fields: [assetTable.taskId],+ references: [taskTable.id],+ }),+ activity: one(activityTable, {+ fields: [assetTable.activityId],+ references: [activityTable.id],+ }),+ creator: one(userTable, {+ fields: [assetTable.createdBy],+ references: [userTable.id],+ }),+}));+export const labelTableRelations = relations(labelTable, ({ one }) => ({task: one(taskTable, {fields: [labelTable.taskId],diff --git a/apps/api/src/database/schema.ts b/apps/api/src/database/schema.tsindex aa6d6b61d..803d8d217 100644--- a/apps/api/src/database/schema.ts+++ b/apps/api/src/database/schema.ts@@ -338,6 +338,52 @@ export const activityTable = pgTable("activity", {externalUrl: text("external_url"),});+export const assetTable = pgTable(+ "asset",+ {+ id: text("id")+ .$defaultFn(() => createId())+ .primaryKey(),+ workspaceId: text("workspace_id")+ .notNull()+ .references(() => workspaceTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ projectId: text("project_id")+ .notNull()+ .references(() => projectTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ taskId: text("task_id").references(() => taskTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ activityId: text("activity_id").references(() => activityTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ objectKey: text("object_key").notNull().unique(),+ filename: text("filename").notNull(),+ mimeType: text("mime_type").notNull(),+ size: integer("size").notNull(),+ kind: text("kind").notNull().default("image"),+ surface: text("surface").notNull().default("description"),+ createdBy: text("created_by").references(() => userTable.id, {+ onDelete: "set null",+ onUpdate: "cascade",+ }),+ createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),+ },+ (table) => [+ index("asset_workspaceId_idx").on(table.workspaceId),+ index("asset_projectId_idx").on(table.projectId),+ index("asset_taskId_idx").on(table.taskId),+ index("asset_activityId_idx").on(table.activityId),+ ],+);+export const labelTable = pgTable("label", {id: text("id").$defaultFn(() => createId())diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex c5cb3b107..420ec1044 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -1,5 +1,6 @@import { serve } from "@hono/node-server";import type { Session, User } from "better-auth/types";+import { eq } from "drizzle-orm";import { migrate } from "drizzle-orm/node-postgres/migrator";import { Hono } from "hono";import { cors } from "hono/cors";@@ -9,7 +10,7 @@ import activity from "./activity";import { auth } from "./auth";import column from "./column";import config from "./config";-import db from "./database";+import db, { schema } from "./database";import externalLink from "./external-link";import githubIntegration, {handleGithubWebhookRoute,@@ -23,6 +24,7 @@ import { migrateGitHubIntegration } from "./plugins/github/migration";import project from "./project";import { getPublicProject } from "./project/controllers/get-public-project";import search from "./search";+import { getPrivateObject } from "./storage/s3";import task from "./task";import timeEntry from "./time-entry";import { getInvitationDetails } from "./utils/check-registration-allowed";@@ -38,6 +40,7 @@ import {normalizeNullableSchemasForOpenApi30,normalizeOrganizationAuthOperations,} from "./utils/openapi-spec";+import { validateWorkspaceAccess } from "./utils/validate-workspace-access";import { verifyApiKey } from "./utils/verify-api-key";import workflowRule from "./workflow-rule";@@ -107,6 +110,59 @@ const invitationPublicApi = api.get("/invitation/public/:id", async (c) => {return c.json(result);});+api.get("/asset/:id", async (c) => {+ const { id } = c.req.param();+ const [asset] = await db+ .select({+ id: schema.assetTable.id,+ objectKey: schema.assetTable.objectKey,+ mimeType: schema.assetTable.mimeType,+ filename: schema.assetTable.filename,+ workspaceId: schema.assetTable.workspaceId,+ isPublic: schema.projectTable.isPublic,+ })+ .from(schema.assetTable)+ .innerJoin(+ schema.projectTable,+ eq(schema.assetTable.projectId, schema.projectTable.id),+ )+ .where(eq(schema.assetTable.id, id))+ .limit(1);++ if (!asset) {+ throw new HTTPException(404, { message: "Asset not found" });+ }++ const session = await auth.api.getSession({ headers: c.req.raw.headers });+ const userId = session?.user?.id || "";++ if (userId) {+ await validateWorkspaceAccess(userId, asset.workspaceId);+ } else if (!asset.isPublic) {+ throw new HTTPException(401, { message: "Unauthorized" });+ }++ try {+ const object = await getPrivateObject(asset.objectKey);++ return new Response(object.body as BodyInit, {+ headers: {+ "Cache-Control": asset.isPublic+ ? "public, max-age=300"+ : "private, max-age=120",+ "Content-Disposition": `inline; filename="${asset.filename.replace(/"/g, "")}"`,+ "Content-Length": object.contentLength?.toString() || "",+ "Content-Type": object.contentType || asset.mimeType,+ ETag: object.etag || "",+ "Last-Modified": object.lastModified?.toUTCString() || "",+ },+ });+ } catch (error) {+ console.error("Failed to stream asset:", error);+ throw new HTTPException(404, { message: "Asset object not found" });+ }+});+const configApi = api.route("/config", config);const honoOpenApiHandler = openAPIRouteHandler(api, {diff --git a/apps/api/src/storage/s3.ts b/apps/api/src/storage/s3.tsindex 30f09eb00..114dd22d9 100644--- a/apps/api/src/storage/s3.ts+++ b/apps/api/src/storage/s3.ts@@ -1,4 +1,7 @@+import { Readable } from "node:stream";import {+ GetObjectCommand,+ HeadObjectCommand,PutObjectCommand,S3Client,type S3ClientConfig,@@ -25,6 +28,10 @@ const allowedImageMimeTypes = new Set(["image/webp",]);+export function isImageContentType(contentType: string) {+ return allowedImageMimeTypes.has(contentType.toLowerCase());+}+type UploadSurface = "description" | "comment";type StorageConfig = {@@ -52,7 +59,14 @@ type TaskImageUploadUrl = {key: string;uploadUrl: string;headers: Record<string, string>;- assetUrl: string;+};++type AssetObject = {+ body: unknown;+ contentType: string | undefined;+ contentLength: number | undefined;+ etag: string | undefined;+ lastModified: Date | undefined;};let clientCache:@@ -162,39 +176,26 @@ function getFileExtension(filename: string) {return sanitizePathSegment(extension).slice(0, 12);}-function encodeKeyPath(key: string) {- return key- .split("/")- .map((segment) => encodeURIComponent(segment))- .join("/");-}--function buildAssetUrl(config: StorageConfig, key: string) {- const encodedKey = encodeKeyPath(key);-- if (config.publicBaseUrl) {- return new URL(- encodedKey,- `${config.publicBaseUrl.replace(/\/+$/, "")}/`,- ).toString();- }-- const endpoint = new URL(config.endpoint);-- if (config.forcePathStyle) {- endpoint.pathname = `${endpoint.pathname.replace(/\/+$/, "")}/${config.bucket}/${encodedKey}`;- return endpoint.toString();- }+function buildObjectKeyPrefix(+ context: Omit<TaskImageUploadContext, "filename" | "contentType">,+) {+ const surfaceFolder =+ context.surface === "comment" ? "comments" : "descriptions";- endpoint.hostname = `${config.bucket}.${endpoint.hostname}`;- endpoint.pathname = `${endpoint.pathname.replace(/\/+$/, "")}/${encodedKey}`;- return endpoint.toString();+ return [+ "workspace",+ sanitizePathSegment(context.workspaceId),+ "project",+ sanitizePathSegment(context.projectId),+ "task",+ sanitizePathSegment(context.taskId),+ surfaceFolder,+ ].join("/");}function buildObjectKey(context: TaskImageUploadContext) {const extension = getFileExtension(context.filename);- const surfaceFolder =- context.surface === "comment" ? "comments" : "descriptions";+ const objectKeyPrefix = buildObjectKeyPrefix(context);const timestamp = Date.now();const randomId = createId();@@ -206,32 +207,26 @@ function buildObjectKey(context: TaskImageUploadContext) {? `${baseName}-${timestamp}-${randomId}.${extension}`: `${baseName}-${timestamp}-${randomId}`;- return [- "workspace",- sanitizePathSegment(context.workspaceId),- "project",- sanitizePathSegment(context.projectId),- "task",- sanitizePathSegment(context.taskId),- surfaceFolder,- fileName,- ].join("/");+ return `${objectKeyPrefix}/${fileName}`;}-export function validateImageUploadInput(contentType: string, size: number) {+export function validateTaskAssetUploadInput(+ contentType: string,+ size: number,+) {const maxImageUploadBytes = getMaxImageUploadBytes();- if (!allowedImageMimeTypes.has(contentType.toLowerCase())) {- throw new Error("Only image uploads are supported.");+ if (!contentType.trim()) {+ throw new Error("A valid content type is required.");}if (size <= 0) {- throw new Error("Image upload size must be greater than zero.");+ throw new Error("Upload size must be greater than zero.");}if (size > maxImageUploadBytes) {throw new Error(- `Image exceeds the maximum upload size of ${Math.floor(maxImageUploadBytes / (1024 * 1024))}MB.`,+ `Upload exceeds the maximum upload size of ${Math.floor(maxImageUploadBytes / (1024 * 1024))}MB.`,);}}@@ -259,10 +254,57 @@ export async function createTaskImageUploadUrl(headers: {"Content-Type": context.contentType,},- assetUrl: buildAssetUrl(config, key),};}export function assertStorageConfigured() {return getStorageConfig();}++export function assertTaskImageKeyMatchesContext(+ key: string,+ context: Omit<TaskImageUploadContext, "filename" | "contentType">,+) {+ const prefix = `${buildObjectKeyPrefix(context)}/`;+ return key.startsWith(prefix);+}++export async function assertObjectExists(key: string) {+ const config = getStorageConfig();+ const client = getClient(config);++ await client.send(+ new HeadObjectCommand({+ Bucket: config.bucket,+ Key: key,+ }),+ );+}++export async function getPrivateObject(key: string): Promise<AssetObject> {+ const config = getStorageConfig();+ const client = getClient(config);+ const response = await client.send(+ new GetObjectCommand({+ Bucket: config.bucket,+ Key: key,+ }),+ );++ if (!response.Body) {+ throw new Error("Storage object body is missing.");+ }++ const body =+ "transformToWebStream" in response.Body+ ? response.Body.transformToWebStream()+ : Readable.toWeb(response.Body as Readable);++ return {+ body,+ contentType: response.ContentType,+ contentLength: response.ContentLength,+ etag: response.ETag,+ lastModified: response.LastModified,+ };+}diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.tsindex aa3d35844..74e5e65f4 100644--- a/apps/api/src/task/index.ts+++ b/apps/api/src/task/index.ts@@ -5,6 +5,7 @@ import { describeRoute, resolver, validator } from "hono-openapi";import * as v from "valibot";import db from "../database";import {+ assetTable,projectTable,taskTable,userTable,@@ -13,8 +14,11 @@ import {import { publishEvent } from "../events";import { taskSchema } from "../schemas";import {+ assertObjectExists,+ assertTaskImageKeyMatchesContext,createTaskImageUploadUrl,- validateImageUploadInput,+ isImageContentType,+ validateTaskAssetUploadInput,} from "../storage/s3";import { workspaceAccess } from "../utils/workspace-access-middleware";import createTask from "./controllers/create-task";@@ -548,7 +552,7 @@ const task = new Hono<{const { filename, contentType, size, surface } = c.req.valid("json");try {- validateImageUploadInput(contentType, size);+ validateTaskAssetUploadInput(contentType, size);} catch (error) {throw new HTTPException(400, {message:@@ -598,6 +602,138 @@ const task = new Hono<{}},)+ .post(+ "/image-upload/:id/finalize",+ describeRoute({+ operationId: "finalizeTaskImageUpload",+ tags: ["Tasks"],+ description:+ "Finalize an uploaded task image and create a private asset record",+ responses: {+ 200: {+ description: "Image upload finalized successfully",+ content: {+ "application/json": { schema: resolver(v.any()) },+ },+ },+ },+ }),+ validator("param", v.object({ id: v.string() })),+ validator(+ "json",+ v.object({+ key: v.string(),+ filename: v.string(),+ contentType: v.string(),+ size: v.number(),+ surface: v.picklist(["description", "comment"] as const),+ }),+ ),+ workspaceAccess.fromTask(),+ async (c) => {+ const { id } = c.req.valid("param");+ const { key, filename, contentType, size, surface } = c.req.valid("json");+ const userId = c.get("userId");++ try {+ validateTaskAssetUploadInput(contentType, size);+ } catch (error) {+ throw new HTTPException(400, {+ message:+ error instanceof Error+ ? error.message+ : "Invalid image upload request",+ });+ }++ const [taskContext] = await db+ .select({+ taskId: taskTable.id,+ projectId: taskTable.projectId,+ workspaceId: workspaceTable.id,+ })+ .from(taskTable)+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .innerJoin(+ workspaceTable,+ eq(projectTable.workspaceId, workspaceTable.id),+ )+ .where(eq(taskTable.id, id))+ .limit(1);++ if (!taskContext) {+ throw new HTTPException(404, { message: "Task not found" });+ }++ if (+ !assertTaskImageKeyMatchesContext(key, {+ workspaceId: taskContext.workspaceId,+ projectId: taskContext.projectId,+ taskId: taskContext.taskId,+ surface,+ })+ ) {+ throw new HTTPException(400, {+ message: "Image upload key does not match the task context.",+ });+ }++ try {+ await assertObjectExists(key);+ } catch {+ throw new HTTPException(404, {+ message: "Uploaded object could not be found in storage.",+ });+ }++ const [existingAsset] = await db+ .select({ id: assetTable.id })+ .from(assetTable)+ .where(eq(assetTable.objectKey, key))+ .limit(1);++ const [asset] = existingAsset+ ? await db+ .update(assetTable)+ .set({+ workspaceId: taskContext.workspaceId,+ projectId: taskContext.projectId,+ taskId: taskContext.taskId,+ filename,+ mimeType: contentType,+ size,+ kind: isImageContentType(contentType) ? "image" : "attachment",+ surface,+ createdBy: userId || null,+ })+ .where(eq(assetTable.id, existingAsset.id))+ .returning({+ id: assetTable.id,+ })+ : await db+ .insert(assetTable)+ .values({+ workspaceId: taskContext.workspaceId,+ projectId: taskContext.projectId,+ taskId: taskContext.taskId,+ objectKey: key,+ filename,+ mimeType: contentType,+ size,+ kind: isImageContentType(contentType) ? "image" : "attachment",+ surface,+ createdBy: userId || null,+ })+ .returning({+ id: assetTable.id,+ });++ return c.json({+ id: asset.id,+ url: new URL(`/api/asset/${asset.id}`, c.req.url).toString(),+ });+ },+ ).put("/description/:id",describeRoute({diff --git a/apps/docs/core/installation/docker-compose.mdx b/apps/docs/core/installation/docker-compose.mdxindex 6815ef35e..5aeeacedd 100644--- a/apps/docs/core/installation/docker-compose.mdx+++ b/apps/docs/core/installation/docker-compose.mdx@@ -63,11 +63,12 @@ Additionally, the following volumes are used:## Notes on object storage-Kaneo uses S3-compatible object storage for image uploads in task descriptions and comments.+Kaneo uses S3-compatible object storage for private uploads in task descriptions and comments.- Object storage is optional. Kaneo runs without it, but image uploads in task descriptions and comments will be unavailable.- For local/self-hosted setups, MinIO is the recommended option when you want uploads.- The Kaneo API creates presigned upload URLs and the browser uploads images directly to the configured storage backend.+- Kaneo serves uploaded assets back through its own API, so the bucket does not need to be public.- If you do not configure object storage, leave the `S3_*` variables unset.- For a complete MinIO example and backend-specific setup notes, see the [storage backends guide](/core/installation/storage-backends).diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdxindex 4d8ce5737..70b6ecce0 100644--- a/apps/docs/core/installation/environment-variables.mdx+++ b/apps/docs/core/installation/environment-variables.mdx@@ -56,20 +56,20 @@ Name | Description |### Object Storage-Kaneo uses S3-compatible object storage for image uploads in task descriptions and task comments.+Kaneo uses S3-compatible object storage for private uploads in task descriptions and task comments.MinIO is the easiest local option and the primary tested target. You can also use other S3-compatible storage backends such as AWS S3, Cloudflare R2, or [`fs`](https://github.com/ferdzo/fs).Name | Description | Default |--- | --- | --- || `S3_ENDPOINT` | The S3-compatible API endpoint used by the Kaneo API for presigned uploads. Example: `http://minio:9000`. | |-| `S3_BUCKET` | The bucket Kaneo will use for uploaded images. | |+| `S3_BUCKET` | The bucket Kaneo will use for uploaded files. | || `S3_ACCESS_KEY_ID` | Access key used by the Kaneo API to create presigned upload URLs. | || `S3_SECRET_ACCESS_KEY` | Secret key used by the Kaneo API to create presigned upload URLs. | || `S3_REGION` | The storage region used for request signing. | `us-east-1` |-| `S3_PUBLIC_BASE_URL` | Optional public base URL for uploaded assets. Use this when objects should be served from a public hostname or reverse proxy instead of the raw API endpoint. | |+| `S3_PUBLIC_BASE_URL` | Optional public base URL for uploaded assets. Kaneo does not require this for the current private asset flow. | || `S3_FORCE_PATH_STYLE` | Use path-style S3 URLs. This should usually be `true` for MinIO and `fs`. | `true` |-| `S3_MAX_IMAGE_UPLOAD_BYTES` | Maximum allowed image upload size in bytes. | `10485760` |+| `S3_MAX_IMAGE_UPLOAD_BYTES` | Maximum allowed upload size in bytes. | `10485760` || `S3_PRESIGN_TTL_SECONDS` | How long presigned upload URLs remain valid. | `300` |### Access Controldiff --git a/apps/docs/core/installation/object-storage-and-image-uploads.mdx b/apps/docs/core/installation/object-storage-and-image-uploads.mdxindex 5414aa26a..589616059 100644--- a/apps/docs/core/installation/object-storage-and-image-uploads.mdx+++ b/apps/docs/core/installation/object-storage-and-image-uploads.mdx@@ -1,20 +1,27 @@----title: Object storage and image uploads-description: Configure S3-compatible storage for task description and comment image uploads.+title: Object storage and uploads+description: Configure S3-compatible storage for private images and attachments in task descriptions and comments.---## Overview-Kaneo supports image uploads in task descriptions and task comments.+Kaneo supports private uploads in task descriptions and task comments.Uploads use an S3-compatible object storage backend:- the Kaneo API creates presigned upload URLs- the browser uploads images directly to the storage backend-- Kaneo stores the final image URLs inside the task or comment content+- Kaneo finalizes uploads into private asset records+- Kaneo serves uploaded files back through its own APIThis means Kaneo can work with multiple backends as long as they expose a compatible S3-style API.+Current behavior:++- images render inline+- other files such as CSV, PDF, or ZIP are inserted as attachment cards/links+- uploaded files are private by default and are not meant to be served from public bucket URLs+If you want backend-specific setup examples, see the [storage backends guide](/core/installation/storage-backends).## Recommended local setup: MinIO@@ -44,6 +51,8 @@ S3_FORCE_PATH_STYLE=trueCreate the bucket before using uploads.+You do not need to make the bucket public.+## Important: internal Docker URLs are not enough in productionWhen Kaneo generates a presigned upload URL, the browser uploads directly to your storage backend.@@ -66,7 +75,6 @@ S3_ACCESS_KEY_ID=minioadminS3_SECRET_ACCESS_KEY=minioadminS3_REGION=us-east-1S3_FORCE_PATH_STYLE=true-S3_PUBLIC_BASE_URL=https://files.cloud.kaneo.app/kaneo-uploads```## Recommended public setup@@ -86,6 +94,8 @@ Why this is needed:Using a dedicated subdomain is recommended over proxying MinIO under a path.+Reads do not need a public bucket URL, because Kaneo serves uploaded assets back through `/api/asset/:id`.+## Other S3-compatible backendsKaneo is not tied to MinIO. Any deployment can point Kaneo at another S3-compatible backend by changing the `S3_*` environment variables.@@ -125,7 +135,7 @@ Set these in your Kaneo deployment:| Name | Description || --- | --- || `S3_ENDPOINT` | S3-compatible API endpoint used by Kaneo |-| `S3_BUCKET` | Bucket used for uploaded images |+| `S3_BUCKET` | Bucket used for uploaded files || `S3_ACCESS_KEY_ID` | Access key used to create presigned upload URLs || `S3_SECRET_ACCESS_KEY` | Secret key used to create presigned upload URLs || `S3_REGION` | Region used for signing |@@ -135,8 +145,8 @@ Optional:| Name | Description || --- | --- |-| `S3_PUBLIC_BASE_URL` | Public URL used for serving uploaded assets |-| `S3_MAX_IMAGE_UPLOAD_BYTES` | Maximum allowed image size |+| `S3_PUBLIC_BASE_URL` | Optional public asset base URL. Kaneo does not require this for the current private asset flow. |+| `S3_MAX_IMAGE_UPLOAD_BYTES` | Maximum allowed upload size in bytes || `S3_PRESIGN_TTL_SECONDS` | Presigned upload URL lifetime |## Testing uploads@@ -144,8 +154,8 @@ Optional:Once storage is configured:1. Open a task.-2. Paste, drag, or select an image inside the description or a comment.-3. Confirm the image uploads and renders inline.+2. Paste, drag, or select a file inside the description or a comment.+3. Confirm images render inline and other files render as attachment cards/links.If uploads fail:@@ -153,5 +163,4 @@ If uploads fail:- confirm the credentials can write to the bucket- confirm the storage endpoint is reachable from the browser- confirm `S3_ENDPOINT` is a public URL, not an internal Docker hostname-- confirm `S3_PUBLIC_BASE_URL` matches the public asset host if you are using one- if using direct browser uploads, confirm CORS is configured correctly for your storage endpointdiff --git a/apps/docs/core/installation/storage-backends.mdx b/apps/docs/core/installation/storage-backends.mdxindex 4cbaee90d..0e46006cc 100644--- a/apps/docs/core/installation/storage-backends.mdx+++ b/apps/docs/core/installation/storage-backends.mdx@@ -1,17 +1,25 @@---title: Storage backends-description: Configure image uploads with MinIO, AWS S3, or Cloudflare R2.+description: Configure private uploads with MinIO, AWS S3, or Cloudflare R2.---## Overview-Kaneo uses S3-compatible object storage for image uploads in:+Kaneo uses S3-compatible object storage for uploads in:- task descriptions- task commentsThe browser uploads directly to the configured storage backend using presigned URLs.+Kaneo then serves uploaded assets back through its own API.++Current behavior:++- images render inline+- non-image files such as CSV, PDF, and ZIP render as attachment cards/links+- assets are private by default+That means one rule matters for every backend:- `S3_ENDPOINT` must be reachable by the browser@@ -27,14 +35,13 @@ S3_ACCESS_KEY_ID=S3_SECRET_ACCESS_KEY=S3_REGION=us-east-1S3_FORCE_PATH_STYLE=false-S3_PUBLIC_BASE_URL=```Notes:-- `S3_PUBLIC_BASE_URL` is recommended when your asset URL should be different from the raw S3 endpoint.- `S3_FORCE_PATH_STYLE=true` is usually needed for MinIO.- `S3_FORCE_PATH_STYLE=false` is usually correct for AWS S3 and R2.+- `S3_PUBLIC_BASE_URL` is optional and not required for the current private asset flow.## MinIO@@ -54,7 +61,6 @@ S3_ACCESS_KEY_ID=minioadminS3_SECRET_ACCESS_KEY=minioadminS3_REGION=us-east-1S3_FORCE_PATH_STYLE=true-S3_PUBLIC_BASE_URL=http://localhost:9000/kaneo-uploads```This works when Kaneo and MinIO are on the same Docker network and your browser reaches MinIO through `localhost`.@@ -79,13 +85,13 @@ S3_ACCESS_KEY_ID=minioadminS3_SECRET_ACCESS_KEY=minioadminS3_REGION=us-east-1S3_FORCE_PATH_STYLE=true-S3_PUBLIC_BASE_URL=https://files.cloud.kaneo.app/kaneo-uploads```You also need:- a created bucket- MinIO CORS allowing your Kaneo origin+- no anonymous bucket read policy is required## AWS S3@@ -102,13 +108,11 @@ S3_ACCESS_KEY_ID=AKIA...S3_SECRET_ACCESS_KEY=...S3_REGION=us-east-1S3_FORCE_PATH_STYLE=false-S3_PUBLIC_BASE_URL=https://kaneo-uploads.s3.us-east-1.amazonaws.com```-For another AWS region, adjust both:+For another AWS region, adjust:- `S3_ENDPOINT`-- `S3_PUBLIC_BASE_URL`Recommended S3 CORS policy:@@ -138,14 +142,12 @@ S3_ACCESS_KEY_ID=...S3_SECRET_ACCESS_KEY=...S3_REGION=autoS3_FORCE_PATH_STYLE=false-S3_PUBLIC_BASE_URL=https://pub-<hash>.r2.dev```Notes:- `S3_REGION=auto` is typical for R2-- `S3_PUBLIC_BASE_URL` should usually point to your public bucket domain or custom domain-- if your bucket is not public, image rendering will not work from stored asset URLs+- a public bucket is not required for Kaneo's current private asset flow## One copy-paste self-hosted example@@ -212,7 +214,6 @@ S3_ACCESS_KEY_ID=minioadminS3_SECRET_ACCESS_KEY=change-meS3_REGION=us-east-1S3_FORCE_PATH_STYLE=true-S3_PUBLIC_BASE_URL=https://files.cloud.kaneo.app/kaneo-uploads```Before testing uploads:@@ -227,6 +228,5 @@ If uploads fail:- check that the bucket exists- check that `S3_ENDPOINT` is public and browser-reachable-- check that `S3_PUBLIC_BASE_URL` points to the correct public asset host- check CORS on your storage backend- check that the access key can `PutObject` and `GetObject`diff --git a/apps/web/src/components/activity/comment-editor.tsx b/apps/web/src/components/activity/comment-editor.tsxindex 60ab463bb..affe576aa 100644--- a/apps/web/src/components/activity/comment-editor.tsx+++ b/apps/web/src/components/activity/comment-editor.tsx@@ -17,17 +17,18 @@ import {Check,ChevronDown,Copy,- ImagePlus,Italic,Link2,List,ListOrdered,ListTodo,+ Paperclip,UnderlineIcon,} from "lucide-react";import type { MouseEvent as ReactMouseEvent } from "react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { bundledLanguages, type Highlighter } from "shiki";+import { AttachmentCard } from "@/components/task/extensions/attachment-card";import { EmbedBlock } from "@/components/task/extensions/embed-block";import { KaneoIssueLink } from "@/components/task/extensions/kaneo-issue-link";import {@@ -75,6 +76,8 @@ type CommentEditorProps = {taskId?: string;uploadSurface?: "description" | "comment";ensureTaskId?: () => Promise<string | null>;+ showQuickAttachButton?: boolean;+ onAttachActionChange?: (attach: (() => void) | null) => void;};type SlashRange = { from: number; to: number };@@ -163,6 +166,8 @@ export default function CommentEditor({taskId,uploadSurface = "comment",ensureTaskId,+ showQuickAttachButton = true,+ onAttachActionChange,}: CommentEditorProps) {const editorShellRef = useRef<HTMLDivElement | null>(null);const imageInputRef = useRef<HTMLInputElement | null>(null);@@ -237,51 +242,84 @@ export default function CommentEditor({uploadSurfaceRef.current = uploadSurface;}, [ensureTaskId, taskId, uploadSurface]);- const handleImageFileUpload = useCallback(+ const insertUploadedAsset = useCallback(+ (+ activeEditor: Editor,+ asset: Awaited<ReturnType<typeof uploadTaskImage>>,+ range?: SlashRange,+ ) => {+ const chain = activeEditor.chain().focus();++ if (range) {+ chain.deleteRange(range);+ } else {+ const { selection } = activeEditor.state;+ if (!selection.empty) {+ chain.setTextSelection(selection.to);+ }+ }++ if (asset.kind === "image") {+ chain+ .setImage({+ src: asset.url,+ alt: asset.alt,+ })+ .run();+ return;+ }++ chain+ .insertContent({+ type: "attachmentCard",+ attrs: {+ url: asset.url,+ filename: asset.filename,+ mimeType: asset.mimeType,+ size: asset.size,+ },+ })+ .run();+ },+ [],+ );++ const handleAssetFileUpload = useCallback(async (file: File, targetEditor?: Editor | null, range?: SlashRange) => {const activeEditor = targetEditor || lastEditorRef.current;const resolvedTaskId =taskIdRef.current ?? (await ensureTaskIdRef.current?.());if (!activeEditor || !resolvedTaskId) {- toast.error("Image uploads are only available on saved tasks.");+ toast.error("File uploads are only available on saved tasks.");return;}- const loadingToast = toast.loading("Uploading image...");+ const loadingToast = toast.loading("Uploading file...");try {- const uploadedImage = await uploadTaskImage({+ const uploadedAsset = await uploadTaskImage({taskId: resolvedTaskId,surface: uploadSurfaceRef.current,file,});-- const chain = activeEditor.chain().focus();- if (range) {- chain.deleteRange(range);- }-- chain- .setImage({- src: uploadedImage.url,- alt: uploadedImage.alt,- })- .run();+ insertUploadedAsset(activeEditor, uploadedAsset, range);toast.dismiss(loadingToast);- toast.success("Image uploaded");+ toast.success(+ uploadedAsset.kind === "image" ? "Image uploaded" : "File attached",+ );} catch (error) {toast.dismiss(loadingToast);toast.error(- error instanceof Error ? error.message : "Failed to upload image",+ error instanceof Error ? error.message : "Failed to upload file",);}},- [],+ [insertUploadedAsset],);- const canUploadImages = Boolean(taskId || ensureTaskId);+ const canUploadFiles = Boolean(taskId || ensureTaskId);const openImagePicker = useCallback((activeEditor?: Editor | null, range?: SlashRange) => {@@ -293,27 +331,27 @@ export default function CommentEditor({[],);- const hasImageDrag = useCallback((event: React.DragEvent<HTMLElement>) => {- return Array.from(event.dataTransfer?.items || []).some((item) =>- item.type.toLowerCase().startsWith("image/"),+ const hasFileDrag = useCallback((event: React.DragEvent<HTMLElement>) => {+ return Array.from(event.dataTransfer?.items || []).some(+ (item) => item.kind === "file",);}, []);const handleShellDragEnter = useCallback((event: React.DragEvent<HTMLElement>) => {- if (readOnly || disabled || !canUploadImages || !hasImageDrag(event)) {+ if (readOnly || disabled || !canUploadFiles || !hasFileDrag(event)) {return;}event.preventDefault();dragDepthRef.current += 1;setIsDragActive(true);},- [canUploadImages, disabled, hasImageDrag, readOnly],+ [canUploadFiles, disabled, hasFileDrag, readOnly],);const handleShellDragOver = useCallback((event: React.DragEvent<HTMLElement>) => {- if (readOnly || disabled || !canUploadImages || !hasImageDrag(event)) {+ if (readOnly || disabled || !canUploadFiles || !hasFileDrag(event)) {return;}event.preventDefault();@@ -322,12 +360,12 @@ export default function CommentEditor({setIsDragActive(true);}},- [canUploadImages, disabled, hasImageDrag, isDragActive, readOnly],+ [canUploadFiles, disabled, hasFileDrag, isDragActive, readOnly],);const handleShellDragLeave = useCallback((event: React.DragEvent<HTMLElement>) => {- if (readOnly || disabled || !canUploadImages || !hasImageDrag(event)) {+ if (readOnly || disabled || !canUploadFiles || !hasFileDrag(event)) {return;}event.preventDefault();@@ -336,18 +374,18 @@ export default function CommentEditor({setIsDragActive(false);}},- [canUploadImages, disabled, hasImageDrag, readOnly],+ [canUploadFiles, disabled, hasFileDrag, readOnly],);const handleShellDrop = useCallback((event: React.DragEvent<HTMLElement>) => {- if (readOnly || disabled || !canUploadImages || !hasImageDrag(event)) {+ if (readOnly || disabled || !canUploadFiles || !hasFileDrag(event)) {return;}dragDepthRef.current = 0;setIsDragActive(false);},- [canUploadImages, disabled, hasImageDrag, readOnly],+ [canUploadFiles, disabled, hasFileDrag, readOnly],);const slashCommands = useMemo<SlashCommand[]>(@@ -464,10 +502,10 @@ export default function CommentEditor({},},{- id: "image",- label: "Image",+ id: "file",+ label: "File",group: "insert",- search: "image photo picture upload",+ search: "file attachment image photo picture upload",run: (activeEditor, range) => {activeEditor.chain().focus().deleteRange(range).run();openImagePicker(activeEditor);@@ -531,6 +569,7 @@ export default function CommentEditor({themeLight: "github-light",}),EmbedBlock,+ AttachmentCard,KaneoIssueLink,TaskList,Image.configure({@@ -563,13 +602,11 @@ export default function CommentEditor({if (readOnly || disabled) return false;const pastedFiles = Array.from(event.clipboardData?.files || []);- const pastedImage = pastedFiles.find((file) =>- file.type.toLowerCase().startsWith("image/"),- );+ const pastedFile = pastedFiles[0];- if (pastedImage) {+ if (pastedFile) {event.preventDefault();- void handleImageFileUpload(pastedImage, editor);+ void handleAssetFileUpload(pastedFile, editor);return true;}@@ -628,11 +665,9 @@ export default function CommentEditor({if (readOnly || disabled) return false;const droppedFiles = Array.from(event.dataTransfer?.files || []);- const droppedImage = droppedFiles.find((file) =>- file.type.toLowerCase().startsWith("image/"),- );+ const droppedFile = droppedFiles[0];- if (!droppedImage) return false;+ if (!droppedFile) return false;event.preventDefault();const coordinates = view.posAtCoords({@@ -644,7 +679,7 @@ export default function CommentEditor({? { from: coordinates.pos, to: coordinates.pos }: undefined;- void handleImageFileUpload(droppedImage, editor, dropRange);+ void handleAssetFileUpload(droppedFile, editor, dropRange);return true;},handleKeyDown: (_view, event) => {@@ -753,9 +788,19 @@ export default function CommentEditor({onChange(markdown);},},- [handleImageFileUpload, toShikiLanguage],+ [handleAssetFileUpload, toShikiLanguage],);+ useEffect(() => {+ if (!onAttachActionChange) return;++ onAttachActionChange(editor ? () => openImagePicker(editor) : null);++ return () => {+ onAttachActionChange(null);+ };+ }, [editor, onAttachActionChange, openImagePicker]);+useEffect(() => {if (!editor || !shikiHighlighter) return;editor.view.dispatch(@@ -1257,7 +1302,6 @@ export default function CommentEditor({<inputref={imageInputRef}type="file"- accept="image/*"className="sr-only"onChange={(event) => {const file = event.target.files?.[0];@@ -1265,7 +1309,7 @@ export default function CommentEditor({const pendingInsert = pendingImageInsertRef.current;pendingImageInsertRef.current = null;- void handleImageFileUpload(+ void handleAssetFileUpload(file,pendingInsert?.editor,pendingInsert?.range,@@ -1446,7 +1490,7 @@ export default function CommentEditor({className="kaneo-comment-editor-bubble-btn"onClick={() => openImagePicker(editor)}>- <ImagePlus className="size-3.5" />+ <Paperclip className="size-3.5" /></Button></BubbleMenu>)}@@ -1608,6 +1652,19 @@ export default function CommentEditor({onMouseMove={handleEditorMouseMove}onMouseLeave={handleEditorMouseLeave}/>+ {!readOnly && !disabled && showQuickAttachButton && (+ <button+ type="button"+ className="kaneo-editor-quick-attach"+ onMouseDown={(event) => {+ event.preventDefault();+ }}+ onClick={() => openImagePicker(editor)}+ aria-label="Attach file"+ >+ <Paperclip className="size-3.5" />+ </button>+ )}{isDragActive && (<div className="kaneo-editor-drop-indicator"><span>Drop image to upload</span>diff --git a/apps/web/src/components/activity/comment-input.tsx b/apps/web/src/components/activity/comment-input.tsxindex 8eb5531c2..421936345 100644--- a/apps/web/src/components/activity/comment-input.tsx+++ b/apps/web/src/components/activity/comment-input.tsx@@ -1,5 +1,5 @@import { useQueryClient } from "@tanstack/react-query";-import { ArrowUp } from "lucide-react";+import { ArrowUp, Paperclip } from "lucide-react";import { useCallback, useState } from "react";import CommentEditor from "@/components/activity/comment-editor";import { Button } from "@/components/ui/button";@@ -21,6 +21,7 @@ type CommentInputProps = {export default function CommentInput({ taskId }: CommentInputProps) {const [content, setContent] = useState("");+ const [attachAction, setAttachAction] = useState<(() => void) | null>(null);const { mutateAsync: createComment, isPending } = useCreateComment();const queryClient = useQueryClient();@@ -46,6 +47,13 @@ export default function CommentInput({ taskId }: CommentInputProps) {}}, [content, createComment, taskId, queryClient]);+ const handleAttachActionChange = useCallback(+ (nextAttachAction: (() => void) | null) => {+ setAttachAction(() => nextAttachAction);+ },+ [],+ );+return (<div className="w-full"><div className="rounded-xl border border-border/80 bg-card/70 transition-colors focus-within:border-ring/60 focus-within:shadow-[0_0_0_2px_color-mix(in_srgb,var(--ring)_20%,transparent)]">@@ -55,10 +63,22 @@ export default function CommentInput({ taskId }: CommentInputProps) {placeholder="Leave a comment..."taskId={taskId}uploadSurface="comment"+ showQuickAttachButton={false}+ onAttachActionChange={handleAttachActionChange}className="[&_.kaneo-comment-editor-content_.ProseMirror]:min-h-[3rem] [&_.kaneo-comment-editor-content_.ProseMirror]:max-h-none [&_.kaneo-comment-editor-content_.ProseMirror]:overflow-visible [&_.kaneo-comment-editor-content_.ProseMirror]:px-3 [&_.kaneo-comment-editor-content_.ProseMirror]:pt-3 [&_.kaneo-comment-editor-content_.ProseMirror]:pb-2"onSubmitShortcut={handleSubmit}/>- <div className="flex items-center justify-end border-border/70 border-t px-2 py-2">+ <div className="flex items-center justify-end gap-2 border-border/70 border-t px-2 py-2">+ <Button+ size="xs"+ variant="ghost"+ onClick={() => attachAction?.()}+ disabled={!attachAction}+ className="text-muted-foreground"+ aria-label="Attach file"+ >+ <Paperclip className="size-3.5" />+ </Button><TooltipProvider><Tooltip><TooltipTrigger asChild>diff --git a/apps/web/src/components/task/extensions/attachment-card.tsx b/apps/web/src/components/task/extensions/attachment-card.tsxnew file mode 100644index 000000000..b28a2863d--- /dev/null+++ b/apps/web/src/components/task/extensions/attachment-card.tsx@@ -0,0 +1,107 @@+import { mergeAttributes, Node } from "@tiptap/core";+import type { NodeViewProps } from "@tiptap/react";+import { NodeViewWrapper, ReactNodeViewRenderer } from "@tiptap/react";+import { FileText } from "lucide-react";++function formatBytes(size: number) {+ if (!Number.isFinite(size) || size <= 0) return "";+ if (size < 1024) return `${size} B`;+ if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;+ if (size < 1024 * 1024 * 1024)+ return `${(size / (1024 * 1024)).toFixed(2)} MB`;+ return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;+}++function AttachmentCardView({ node }: NodeViewProps) {+ const url = String(node.attrs.url || "");+ const filename = String(node.attrs.filename || "Attachment");+ const mimeType = String(node.attrs.mimeType || "");+ const size = Number(node.attrs.size || 0);++ return (+ <NodeViewWrapper as="span" className="kaneo-attachment-node">+ <a+ href={url}+ target="_blank"+ rel="noopener noreferrer"+ className="kaneo-attachment-card"+ title={filename}+ >+ <span className="kaneo-attachment-card-icon">+ <FileText className="size-4" />+ </span>+ <span className="kaneo-attachment-card-content">+ <span className="kaneo-attachment-card-title">{filename}</span>+ <span className="kaneo-attachment-card-meta">+ {formatBytes(size)}+ {mimeType ? ` · ${mimeType}` : ""}+ </span>+ </span>+ </a>+ </NodeViewWrapper>+ );+}++export const AttachmentCard = Node.create({+ name: "attachmentCard",+ group: "inline",+ inline: true,+ atom: true,+ selectable: false,++ addAttributes() {+ return {+ url: { default: "" },+ filename: { default: "" },+ mimeType: { default: "" },+ size: { default: 0 },+ };+ },++ parseHTML() {+ return [+ { tag: "kaneo-attachment[url]" },+ { tag: "span[data-type='attachment-card'][data-url]" },+ ];+ },++ renderHTML({ HTMLAttributes }) {+ return [+ "kaneo-attachment",+ mergeAttributes(HTMLAttributes, {+ "data-type": "attachment-card",+ "data-url": HTMLAttributes.url,+ "data-filename": HTMLAttributes.filename,+ "data-mime-type": HTMLAttributes.mimeType,+ "data-size": HTMLAttributes.size,+ url: HTMLAttributes.url,+ }),+ ];+ },++ addNodeView() {+ return ReactNodeViewRenderer(AttachmentCardView);+ },++ renderMarkdown(+ node: {+ attrs?: {+ url?: string;+ filename?: string;+ mimeType?: string;+ size?: number;+ };+ },+ _helpers: unknown,+ _context: unknown,+ ) {+ const url = String(node.attrs?.url || "");+ const filename = String(node.attrs?.filename || "");+ const mimeType = String(node.attrs?.mimeType || "");+ const size = Number(node.attrs?.size || 0);++ if (!url) return "";++ return `\n<kaneo-attachment url="${url}" filename="${filename}" mime-type="${mimeType}" size="${size}" />\n`;+ },+});diff --git a/apps/web/src/components/task/task-description.tsx b/apps/web/src/components/task/task-description.tsxindex 5ac1bd683..9da198718 100644--- a/apps/web/src/components/task/task-description.tsx+++ b/apps/web/src/components/task/task-description.tsx@@ -25,6 +25,7 @@ import {List,ListOrdered,ListTodo,+ Paperclip,Quote,Strikethrough,Table2,@@ -58,6 +59,7 @@ import {import { getSharedShikiHighlighter } from "@/lib/shiki-highlighter";import { toast } from "@/lib/toast";import { uploadTaskImage } from "@/lib/upload-task-image";+import { AttachmentCard } from "./extensions/attachment-card";import { EmbedBlock } from "./extensions/embed-block";import { KaneoIssueLink } from "./extensions/kaneo-issue-link";import {@@ -324,46 +326,79 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {[],);- const handleImageFileUpload = useCallback(+ const insertUploadedAsset = useCallback(+ (+ activeEditor: Editor,+ asset: Awaited<ReturnType<typeof uploadTaskImage>>,+ range?: SlashRange,+ ) => {+ const chain = activeEditor.chain().focus();++ if (range) {+ chain.deleteRange(range);+ } else {+ const { selection } = activeEditor.state;+ if (!selection.empty) {+ chain.setTextSelection(selection.to);+ }+ }++ if (asset.kind === "image") {+ chain+ .setImage({+ src: asset.url,+ alt: asset.alt,+ })+ .run();+ return;+ }++ chain+ .insertContent({+ type: "attachmentCard",+ attrs: {+ url: asset.url,+ filename: asset.filename,+ mimeType: asset.mimeType,+ size: asset.size,+ },+ })+ .run();+ },+ [],+ );++ const handleAssetFileUpload = useCallback(async (file: File, targetEditor?: Editor | null, range?: SlashRange) => {const activeEditor = targetEditor || lastEditorRef.current;if (!activeEditor) {- toast.error("Image upload failed");+ toast.error("File upload failed");return;}- const loadingToast = toast.loading("Uploading image...");+ const loadingToast = toast.loading("Uploading file...");try {- const uploadedImage = await uploadTaskImage({+ const uploadedAsset = await uploadTaskImage({taskId,surface: "description",file,});-- const chain = activeEditor.chain().focus();- if (range) {- chain.deleteRange(range);- }-- chain- .setImage({- src: uploadedImage.url,- alt: uploadedImage.alt,- })- .run();+ insertUploadedAsset(activeEditor, uploadedAsset, range);toast.dismiss(loadingToast);- toast.success("Image uploaded");+ toast.success(+ uploadedAsset.kind === "image" ? "Image uploaded" : "File attached",+ );} catch (error) {toast.dismiss(loadingToast);toast.error(- error instanceof Error ? error.message : "Failed to upload image",+ error instanceof Error ? error.message : "Failed to upload file",);}},- [taskId],+ [insertUploadedAsset, taskId],);const openImagePicker = useCallback(@@ -376,63 +411,63 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {[],);- const hasImageDrag = useCallback((event: React.DragEvent<HTMLElement>) => {- return Array.from(event.dataTransfer?.items || []).some((item) =>- item.type.toLowerCase().startsWith("image/"),+ const hasFileDrag = useCallback((event: React.DragEvent<HTMLElement>) => {+ return Array.from(event.dataTransfer?.items || []).some(+ (item) => item.kind === "file",);}, []);const handleShellDragEnter = useCallback((event: React.DragEvent<HTMLElement>) => {- if (!taskId || !hasImageDrag(event)) return;+ if (!taskId || !hasFileDrag(event)) return;event.preventDefault();dragDepthRef.current += 1;setIsDragActive(true);},- [hasImageDrag, taskId],+ [hasFileDrag, taskId],);const handleShellDragOver = useCallback((event: React.DragEvent<HTMLElement>) => {- if (!taskId || !hasImageDrag(event)) return;+ if (!taskId || !hasFileDrag(event)) return;event.preventDefault();event.dataTransfer.dropEffect = "copy";if (!isDragActive) {setIsDragActive(true);}},- [hasImageDrag, isDragActive, taskId],+ [hasFileDrag, isDragActive, taskId],);const handleShellDragLeave = useCallback((event: React.DragEvent<HTMLElement>) => {- if (!taskId || !hasImageDrag(event)) return;+ if (!taskId || !hasFileDrag(event)) return;event.preventDefault();dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);if (dragDepthRef.current === 0) {setIsDragActive(false);}},- [hasImageDrag, taskId],+ [hasFileDrag, taskId],);const handleShellDrop = useCallback((event: React.DragEvent<HTMLElement>) => {- if (!taskId || !hasImageDrag(event)) return;+ if (!taskId || !hasFileDrag(event)) return;dragDepthRef.current = 0;setIsDragActive(false);},- [hasImageDrag, taskId],+ [hasFileDrag, taskId],);const slashCommands = useMemo(() => [...SLASH_COMMANDS,{- id: "image",- label: "Image",+ id: "file",+ label: "File",group: "insert" as const,- search: "image photo picture upload",+ search: "file attachment image photo picture upload",run: (activeEditor: Editor, range: SlashRange) => {activeEditor.chain().focus().deleteRange(range).run();openImagePicker(activeEditor);@@ -508,6 +543,7 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {themeLight: "github-light",}),EmbedBlock,+ AttachmentCard,KaneoIssueLink,TaskList,Image.configure({@@ -535,13 +571,11 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {},handlePaste: (view, event) => {const pastedFiles = Array.from(event.clipboardData?.files || []);- const pastedImage = pastedFiles.find((file) =>- file.type.toLowerCase().startsWith("image/"),- );+ const pastedFile = pastedFiles[0];- if (pastedImage) {+ if (pastedFile) {event.preventDefault();- void handleImageFileUpload(pastedImage, editor);+ void handleAssetFileUpload(pastedFile, editor);return true;}@@ -599,11 +633,9 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {},handleDrop: (view, event) => {const droppedFiles = Array.from(event.dataTransfer?.files || []);- const droppedImage = droppedFiles.find((file) =>- file.type.toLowerCase().startsWith("image/"),- );+ const droppedFile = droppedFiles[0];- if (!droppedImage) return false;+ if (!droppedFile) return false;event.preventDefault();const coordinates = view.posAtCoords({@@ -614,7 +646,7 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {? { from: coordinates.pos, to: coordinates.pos }: undefined;- void handleImageFileUpload(droppedImage, editor, dropRange);+ void handleAssetFileUpload(droppedFile, editor, dropRange);return true;},handleKeyDown: (view, event) => {@@ -650,7 +682,7 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {debouncedUpdate(markdown);},},- [getOverlayPosition, handleImageFileUpload, toShikiLanguage],+ [getOverlayPosition, handleAssetFileUpload, toShikiLanguage],);useEffect(() => {@@ -1199,7 +1231,6 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {<inputref={imageInputRef}type="file"- accept="image/*"className="sr-only"onChange={(event) => {const file = event.target.files?.[0];@@ -1207,7 +1238,7 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {const pendingInsert = pendingImageInsertRef.current;pendingImageInsertRef.current = null;- void handleImageFileUpload(+ void handleAssetFileUpload(file,pendingInsert?.editor,pendingInsert?.range,@@ -1614,6 +1645,17 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {onMouseMove={handleEditorMouseMove}onMouseLeave={handleEditorMouseLeave}/>+ <button+ type="button"+ className="kaneo-editor-quick-attach"+ onMouseDown={(event) => {+ event.preventDefault();+ }}+ onClick={() => openImagePicker(editor)}+ aria-label="Attach file"+ >+ <Paperclip className="size-3.5" />+ </button>{isDragActive && (<div className="kaneo-editor-drop-indicator"><span>Drop image to upload</span>diff --git a/apps/web/src/fetchers/task/create-image-upload.ts b/apps/web/src/fetchers/task/create-image-upload.tsindex 6c6e3dcae..dff7d5825 100644--- a/apps/web/src/fetchers/task/create-image-upload.ts+++ b/apps/web/src/fetchers/task/create-image-upload.ts@@ -31,4 +31,38 @@ async function createImageUpload({return response.json();}+export async function finalizeImageUpload({+ taskId,+ key,+ filename,+ contentType,+ size,+ surface,+}: {+ taskId: string;+ key: string;+ filename: string;+ contentType: string;+ size: number;+ surface: "description" | "comment";+}) {+ const response = await client.task["image-upload"][":id"].finalize.$post({+ param: { id: taskId },+ json: {+ key,+ filename,+ contentType,+ size,+ surface,+ },+ });++ if (!response.ok) {+ const error = await response.text();+ throw new Error(error);+ }++ return response.json();+}+export default createImageUpload;diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 300672d0c..fb846d908 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -235,6 +235,42 @@z-index: 90;}+ .kaneo-editor-quick-attach {+ position: absolute;+ right: 0.75rem;+ bottom: 0.7rem;+ z-index: 10;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 2rem;+ height: 2rem;+ border: 1px solid color-mix(in srgb, var(--border) 78%, transparent);+ border-radius: 999px;+ background: color-mix(in srgb, var(--background) 82%, transparent);+ color: color-mix(in srgb, var(--foreground) 76%, transparent);+ box-shadow: 0 4px 16px color-mix(in srgb, var(--background) 68%, transparent);+ transition:+ background-color 0.15s ease,+ border-color 0.15s ease,+ color 0.15s ease,+ transform 0.15s ease;+ }++ .kaneo-editor-quick-attach:hover {+ border-color: color-mix(in srgb, var(--foreground) 18%, var(--border));+ background: color-mix(in srgb, var(--accent) 72%, transparent);+ color: var(--foreground);+ transform: translateY(-1px);+ }++ .kaneo-editor-quick-attach:focus-visible {+ outline: none;+ box-shadow:+ 0 0 0 2px color-mix(in srgb, var(--ring) 24%, transparent),+ 0 4px 16px color-mix(in srgb, var(--background) 68%, transparent);+ }+.kaneo-tiptap-bubble {display: inline-flex;align-items: center;@@ -307,7 +343,7 @@.kaneo-tiptap-content .ProseMirror {min-height: 1.85rem;- padding: 0.2rem 0 0.24rem;+ padding: 0.2rem 0 2.9rem;font-family: var(--font-sans);font-size: 0.965rem;line-height: 1.72;@@ -739,6 +775,82 @@color: color-mix(in srgb, var(--foreground) 72%, transparent);}+ .kaneo-attachment-node {+ display: inline-flex;+ max-width: 100%;+ vertical-align: middle;+ margin: 0.35rem 0;+ }++ .kaneo-attachment-card {+ display: inline-flex;+ align-items: center;+ gap: 0.75rem;+ min-width: min(22rem, 100%);+ max-width: min(28rem, 100%);+ padding: 0.75rem 0.95rem;+ border: 1px solid color-mix(in srgb, var(--border) 78%, transparent);+ border-radius: calc(var(--radius) + 1px);+ background: linear-gradient(+ 180deg,+ color-mix(in srgb, var(--accent) 48%, transparent),+ color-mix(in srgb, var(--accent) 20%, transparent)+ );+ text-decoration: none;+ transition:+ border-color 0.18s ease,+ background-color 0.18s ease,+ transform 0.18s ease;+ }++ .kaneo-attachment-card:hover {+ border-color: color-mix(in srgb, var(--foreground) 18%, var(--border));+ background: linear-gradient(+ 180deg,+ color-mix(in srgb, var(--accent) 62%, transparent),+ color-mix(in srgb, var(--accent) 30%, transparent)+ );+ transform: translateY(-1px);+ }++ .kaneo-attachment-card-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.8rem;+ height: 1.8rem;+ color: color-mix(in srgb, var(--foreground) 72%, transparent);+ background: color-mix(in srgb, var(--foreground) 6%, transparent);+ border-radius: 0.55rem;+ flex-shrink: 0;+ }++ .kaneo-attachment-card-content {+ display: flex;+ min-width: 0;+ flex-direction: column;+ }++ .kaneo-attachment-card-title {+ color: var(--foreground);+ font-size: 0.96rem;+ font-weight: 600;+ line-height: 1.2;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .kaneo-attachment-card-meta {+ margin-top: 0.18rem;+ color: color-mix(in srgb, var(--foreground) 58%, transparent);+ font-size: 0.76rem;+ line-height: 1.2;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+.kaneo-tiptap-content .ProseMirror [data-type="kaneo-embed"]:focus-within {border-color: color-mix(in srgb, var(--ring) 80%, var(--border));box-shadow: 0 0 0 2px color-mix(in srgb, var(--ring) 34%, transparent);@@ -864,7 +976,7 @@min-height: 2.2rem;max-height: 18rem;overflow-y: auto;- padding: 0.62rem 0.75rem;+ padding: 0.62rem 0.75rem 2.9rem;font-family: var(--font-sans);font-size: 0.92rem;line-height: 1.62;diff --git a/apps/web/src/lib/upload-task-image.ts b/apps/web/src/lib/upload-task-image.tsindex 6dcc04f93..60b678b80 100644--- a/apps/web/src/lib/upload-task-image.ts+++ b/apps/web/src/lib/upload-task-image.ts@@ -1,4 +1,6 @@-import createImageUpload from "@/fetchers/task/create-image-upload";+import createImageUpload, {+ finalizeImageUpload,+} from "@/fetchers/task/create-image-upload";const allowedImageMimeTypes = new Set(["image/apng",@@ -19,6 +21,10 @@ export function isSupportedImageFile(file: File) {return allowedImageMimeTypes.has(file.type.toLowerCase());}+export function isSupportedTaskAsset(file: File) {+ return file.size > 0;+}+export function getImageAltText(filename: string) {return filename.replace(/\.[^/.]+$/, "")@@ -36,7 +42,9 @@ export async function uploadTaskImage({file: File;}) {if (!isSupportedImageFile(file)) {- throw new Error("Only image uploads are supported.");+ if (!isSupportedTaskAsset(file)) {+ throw new Error("Only non-empty file uploads are supported.");+ }}const upload = await createImageUpload({@@ -54,11 +62,24 @@ export async function uploadTaskImage({});if (!response.ok) {- throw new Error("Failed to upload image to storage.");+ throw new Error("Failed to upload file to storage.");}+ const asset = await finalizeImageUpload({+ taskId,+ key: upload.key,+ filename: file.name || "image",+ contentType: file.type,+ size: file.size,+ surface,+ });+return {- url: upload.assetUrl,+ url: asset.url,alt: getImageAltText(file.name || "image"),+ filename: file.name || "file",+ kind: isSupportedImageFile(file) ? "image" : "attachment",+ mimeType: file.type,+ size: file.size,};}