⚡ 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(custom-fields): edit field names and selection options
Tincbccfa14c90c
diff --git a/apps/api/src/custom-field/controllers/set-custom-field-value.ts b/apps/api/src/custom-field/controllers/set-custom-field-value.tsindex 99349655a..9bc0f62d4 100644--- a/apps/api/src/custom-field/controllers/set-custom-field-value.ts+++ b/apps/api/src/custom-field/controllers/set-custom-field-value.ts@@ -24,122 +24,125 @@ async function setCustomFieldValue(fieldId: string,value: string,) {- const [task] = await db- .select({- projectId: taskTable.projectId,- })- .from(taskTable)- .where(eq(taskTable.id, taskId))- .limit(1);-- if (!task) {- throw new HTTPException(404, {- message: "Task not found",- });- }+ return db.transaction(async (tx) => {+ const [task] = await tx+ .select({+ projectId: taskTable.projectId,+ })+ .from(taskTable)+ .where(eq(taskTable.id, taskId))+ .limit(1);++ if (!task) {+ throw new HTTPException(404, {+ message: "Task not found",+ });+ }- const [field] = await db- .select()- .from(customFieldDefinitionTable)- .where(eq(customFieldDefinitionTable.id, fieldId))- .limit(1);+ const [field] = await tx+ .select()+ .from(customFieldDefinitionTable)+ .where(eq(customFieldDefinitionTable.id, fieldId))+ .limit(1)+ .for("share");- if (!field || field.projectId !== task.projectId) {- throw new HTTPException(404, {- message: "Custom field not found",- });- }+ if (!field || field.projectId !== task.projectId) {+ throw new HTTPException(404, {+ message: "Custom field not found",+ });+ }- const normalizedValue = value.trim();+ const normalizedValue = value.trim();- if (field.required) {- if (field.type === "multiselect") {- if (isMultiselectEmpty(normalizedValue)) {+ if (field.required) {+ if (field.type === "multiselect") {+ if (isMultiselectEmpty(normalizedValue)) {+ throw new HTTPException(400, {+ message: "This custom field is required",+ });+ }+ } else if (normalizedValue.length === 0) {throw new HTTPException(400, {message: "This custom field is required",});}- } else if (normalizedValue.length === 0) {- throw new HTTPException(400, {- message: "This custom field is required",- });}- }- if (field.type === "dropdown" && normalizedValue.length > 0) {- if (- Array.isArray(field.options) &&- !field.options.includes(normalizedValue)- ) {- throw new HTTPException(400, {- message: "Invalid option for this custom field",- });+ if (field.type === "dropdown" && normalizedValue.length > 0) {+ if (+ Array.isArray(field.options) &&+ !field.options.includes(normalizedValue)+ ) {+ throw new HTTPException(400, {+ message: "Invalid option for this custom field",+ });+ }}- }- if (field.type === "number" && normalizedValue.length > 0) {- if (Number.isNaN(Number(normalizedValue))) {- throw new HTTPException(400, {- message: "Value must be a valid number",- });+ if (field.type === "number" && normalizedValue.length > 0) {+ if (Number.isNaN(Number(normalizedValue))) {+ throw new HTTPException(400, {+ message: "Value must be a valid number",+ });+ }}- }- if (field.type === "boolean" && normalizedValue.length > 0) {- if (normalizedValue !== "true" && normalizedValue !== "false") {- throw new HTTPException(400, {- message: "Value must be true or false",- });+ if (field.type === "boolean" && normalizedValue.length > 0) {+ if (normalizedValue !== "true" && normalizedValue !== "false") {+ throw new HTTPException(400, {+ message: "Value must be true or false",+ });+ }}- }- if (field.type === "multiselect" && normalizedValue.length > 0) {- let parsed: unknown;- try {- parsed = JSON.parse(normalizedValue);- } catch {- throw new HTTPException(400, {- message: "Value must be a valid JSON array",- });- }+ if (field.type === "multiselect" && normalizedValue.length > 0) {+ let parsed: unknown;+ try {+ parsed = JSON.parse(normalizedValue);+ } catch {+ throw new HTTPException(400, {+ message: "Value must be a valid JSON array",+ });+ }- if (!Array.isArray(parsed)) {- throw new HTTPException(400, {- message: "Value must be a JSON array",- });- }+ if (!Array.isArray(parsed)) {+ throw new HTTPException(400, {+ message: "Value must be a JSON array",+ });+ }- if (Array.isArray(field.options)) {- const options = field.options as string[];+ if (Array.isArray(field.options)) {+ const options = field.options as string[];- const invalid = parsed.some(- (v) => typeof v !== "string" || !options.includes(v),- );+ const invalid = parsed.some(+ (v) => typeof v !== "string" || !options.includes(v),+ );- if (invalid) {- throw new HTTPException(400, {- message: "Invalid option(s) for this custom field",- });+ if (invalid) {+ throw new HTTPException(400, {+ message: "Invalid option(s) for this custom field",+ });+ }}}- }- const [result] = await db- .insert(customFieldValueTable)- .values({- taskId,- fieldId,- value: normalizedValue,- })- .onConflictDoUpdate({- target: [customFieldValueTable.taskId, customFieldValueTable.fieldId],- set: {- value: sql`excluded.value`,- },- })- .returning();-- return result;+ const [result] = await tx+ .insert(customFieldValueTable)+ .values({+ taskId,+ fieldId,+ value: normalizedValue,+ })+ .onConflictDoUpdate({+ target: [customFieldValueTable.taskId, customFieldValueTable.fieldId],+ set: {+ value: sql`excluded.value`,+ },+ })+ .returning();++ return result;+ });}export default setCustomFieldValue;diff --git a/apps/api/src/custom-field/controllers/update-custom-field.ts b/apps/api/src/custom-field/controllers/update-custom-field.tsnew file mode 100644index 000000000..03e0662f4--- /dev/null+++ b/apps/api/src/custom-field/controllers/update-custom-field.ts@@ -0,0 +1,131 @@+import { eq, sql } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import {+ customFieldDefinitionTable,+ customFieldValueTable,+} from "../../database/schema";+import type { z } from "../../openapi";+import type { updateCustomFieldBody } from "../schema";++export default async function updateCustomField(+ id: string,+ input: z.infer<typeof updateCustomFieldBody>,+) {+ return db.transaction(async (tx) => {+ const [field] = await tx+ .select()+ .from(customFieldDefinitionTable)+ .where(eq(customFieldDefinitionTable.id, id))+ .for("update");+ if (!field)+ throw new HTTPException(404, { message: "Custom field not found" });+ if (field.updatedAt.toISOString() !== input.updatedAt) {+ throw new HTTPException(409, {+ message: "This field has changed. Close the editor and try again.",+ });+ }++ let options = field.options;+ let defaultValue = field.defaultValue;+ if (input.options !== undefined) {+ if (field.type !== "dropdown" && field.type !== "multiselect") {+ throw new HTTPException(400, {+ message: "Only selection fields have options",+ });+ }+ const oldOptions = Array.isArray(field.options)+ ? (field.options as string[])+ : [];+ const originalValues = input.options.flatMap((option) =>+ option.originalValue === undefined ? [] : [option.originalValue],+ );+ const newOptions = input.options.map((option) => option.value);+ if (+ new Set(originalValues).size !== originalValues.length ||+ originalValues.some((value) => !oldOptions.includes(value))+ ) {+ throw new HTTPException(400, { message: "Invalid original options" });+ }+ if (new Set(newOptions).size !== newOptions.length) {+ throw new HTTPException(400, {+ message: "Option names must be unique",+ });+ }+ if (newOptions.length < (field.type === "multiselect" ? 2 : 1)) {+ throw new HTTPException(400, {+ message: "Not enough options for this field type",+ });+ }+ const replacements = new Map(+ input.options.flatMap((option) =>+ option.originalValue === undefined+ ? []+ : [[option.originalValue, option.value] as const],+ ),+ );+ const transform = (value: string | null): string | null => {+ if (value === null || value.trim() === "") return value;+ const replace = (selected: string) => {+ const replacement = replacements.get(selected);+ if (replacement === undefined) {+ throw new HTTPException(400, {+ message:+ "Cannot remove an option used by a task or the default value",+ });+ }+ return replacement;+ };+ if (field.type === "dropdown") return replace(value);+ let selected: unknown;+ try {+ selected = JSON.parse(value);+ } catch {+ throw new HTTPException(400, {+ message: "An existing selection is invalid",+ });+ }+ if (+ !Array.isArray(selected) ||+ selected.some((item) => typeof item !== "string")+ ) {+ throw new HTTPException(400, {+ message: "An existing selection is invalid",+ });+ }+ return JSON.stringify(selected.map(replace));+ };+ defaultValue = transform(defaultValue);+ const values = await tx+ .select()+ .from(customFieldValueTable)+ .where(eq(customFieldValueTable.fieldId, id))+ .for("update");+ const changed = values+ .map((row) => ({+ id: row.id,+ before: row.value,+ value: transform(row.value),+ }))+ .filter((row) => row.before !== row.value);+ // Batch updates preserve simultaneous renames (including swaps) without a query per task.+ for (let i = 0; i < changed.length; i += 500) {+ const rows = changed+ .slice(i, i + 500)+ .map((row) => sql`(${row.id}::text, ${row.value}::text)`);+ await tx.execute(sql`UPDATE ${customFieldValueTable} AS target SET value = changes.value+ FROM (VALUES ${sql.join(rows, sql`, `)}) AS changes(id, value)+ WHERE target.id = changes.id`);+ }+ options = newOptions;+ }+ const [updated] = await tx+ .update(customFieldDefinitionTable)+ .set({ name: input.name, options, defaultValue, updatedAt: new Date() })+ .where(eq(customFieldDefinitionTable.id, id))+ .returning();+ if (!updated)+ throw new HTTPException(404, { message: "Custom field not found" });+ return updated;+ });+}diff --git a/apps/api/src/custom-field/index.ts b/apps/api/src/custom-field/index.tsindex b255c4f7b..081dc227c 100644--- a/apps/api/src/custom-field/index.ts+++ b/apps/api/src/custom-field/index.ts@@ -1,3 +1,4 @@+import { publishEvent } from "../events";import {apiRouter,createRoute,@@ -14,6 +15,7 @@ import getCustomFieldValuesByTask from "./controllers/get-custom-field-values-byimport getCustomFieldsByProject from "./controllers/get-custom-fields-by-project";import reorderCustomFields from "./controllers/reorder-custom-field";import setCustomFieldValue from "./controllers/set-custom-field-value";+import updateCustomField from "./controllers/update-custom-field";import {customFieldDefinitionListSchema,customFieldDefinitionSchema,@@ -29,6 +31,7 @@ import {reorderCustomFieldsBody,setCustomFieldValueBody,taskIdParam,+ updateCustomFieldBody,} from "./schema";const getCustomFieldsRoute = createRoute({@@ -213,6 +216,38 @@ const setCustomFieldValueRoute = createRoute({},});+const updateCustomFieldRoute = createRoute({+ method: "patch",+ operationId: "updateCustomField",+ path: "/{id}",+ tags: ["Custom Fields"],+ summary: "Edit custom field",+ description:+ "Rename a field or edit its selection options. Supply originalValue for existing options to preserve task selections and defaults when renaming. Omitted existing options are removed only when unused. The type and required setting are preserved. updatedAt must match the current definition.",+ middleware: [+ workspaceAccess.fromCustomField("id"),+ requireWorkspacePermission({ project: ["update"] }),+ ] as const,+ request: {+ params: customFieldIdParam,+ body: {+ required: true,+ content: { "application/json": { schema: updateCustomFieldBody } },+ },+ },+ responses: {+ 200: jsonResponse("The updated custom field", customFieldDefinitionSchema),+ 400: errorResponse(+ "Invalid options, an option is in use, or unknown field",+ ),+ 403: errorResponse(+ "No workspace access or missing project:update permission",+ ),+ 404: errorResponse("Custom field not found"),+ 409: errorResponse("The custom field has changed since it was loaded"),+ },+});+const deleteCustomFieldRoute = createRoute({method: "delete",operationId: "deleteCustomField",@@ -282,6 +317,14 @@ const customField = apiRouter()return c.json(await setCustomFieldValue(taskId, fieldId, value), 200);})+ .openapi(updateCustomFieldRoute, async (c) => {+ const field = await updateCustomField(+ c.req.valid("param").id,+ c.req.valid("json"),+ );+ await publishEvent("custom-field.updated", { projectId: field.projectId });+ return c.json(field, 200);+ }).openapi(deleteCustomFieldRoute, async (c) =>c.json(await deleteCustomField(c.req.valid("param").id), 200),);diff --git a/apps/api/src/custom-field/schema.ts b/apps/api/src/custom-field/schema.tsindex d3ce0ca12..60f60ee6f 100644--- a/apps/api/src/custom-field/schema.ts+++ b/apps/api/src/custom-field/schema.ts@@ -42,3 +42,18 @@ export const setCustomFieldValueBody = z.object({fieldId: z.string(),value: z.string(),});++export const updateCustomFieldBody = z+ .object({+ name: z.string().trim().min(1),+ updatedAt: z.iso.datetime(),+ options: z+ .array(+ z.object({+ originalValue: z.string().optional(),+ value: z.string().trim().min(1),+ }),+ )+ .optional(),+ })+ .strict();diff --git a/apps/api/src/task/controllers/create-task.ts b/apps/api/src/task/controllers/create-task.tsindex dd08fa955..2e254b4ea 100644--- a/apps/api/src/task/controllers/create-task.ts+++ b/apps/api/src/task/controllers/create-task.ts@@ -73,38 +73,6 @@ async function createTask({await assertValidTaskStatus(resolvedStatus, projectId);- const allFields = await db- .select()- .from(customFieldDefinitionTable)- .where(eq(customFieldDefinitionTable.projectId, projectId));-- const mergedCustomFields: CustomFieldInput[] = normalizedCustomFields ?? [];- const providedFieldIds = new Set(mergedCustomFields.map((f) => f.fieldId));-- for (const field of allFields) {- if (- !providedFieldIds.has(field.id) &&- field.required &&- field.defaultValue != null &&- !isCustomFieldValueEmpty(- field.defaultValue,- field.type as- | "number"- | "boolean"- | "date"- | "dropdown"- | "multiselect",- )- ) {- mergedCustomFields.push({- fieldId: field.id,- value: field.defaultValue,- });- }- }-- await assertRequiredCustomFields(projectId, mergedCustomFields);-let assignee: { name: string } | undefined;if (normalizedUserId) {@@ -127,6 +95,41 @@ async function createTask({});const createdTask = await db.transaction(async (tx) => {+ // Hold definitions through validation and insertion so option renames cannot leave stale values.+ const allFields = await tx+ .select()+ .from(customFieldDefinitionTable)+ .where(eq(customFieldDefinitionTable.projectId, projectId))+ .orderBy(customFieldDefinitionTable.id)+ .for("share");++ const mergedCustomFields: CustomFieldInput[] = normalizedCustomFields ?? [];+ const providedFieldIds = new Set(mergedCustomFields.map((f) => f.fieldId));++ for (const field of allFields) {+ if (+ !providedFieldIds.has(field.id) &&+ field.required &&+ field.defaultValue != null &&+ !isCustomFieldValueEmpty(+ field.defaultValue,+ field.type as+ | "number"+ | "boolean"+ | "date"+ | "dropdown"+ | "multiselect",+ )+ ) {+ mergedCustomFields.push({+ fieldId: field.id,+ value: field.defaultValue,+ });+ }+ }++ await assertRequiredCustomFields(projectId, mergedCustomFields, tx);+const taskNumber = await claimTaskNumber(projectId, tx);const nextPosition = await nextTaskPosition(tx,diff --git a/apps/api/src/task/controllers/duplicate-task.ts b/apps/api/src/task/controllers/duplicate-task.tsindex d9c770695..e28000e02 100644--- a/apps/api/src/task/controllers/duplicate-task.ts+++ b/apps/api/src/task/controllers/duplicate-task.ts@@ -159,46 +159,55 @@ async function duplicateTask({),});- const fieldDefinitions = await db- .select()- .from(customFieldDefinitionTable)- .where(eq(customFieldDefinitionTable.projectId, sourceTask.projectId));- const sourceCustomFields = await db- .select({- fieldId: customFieldValueTable.fieldId,- value: customFieldValueTable.value,- })- .from(customFieldValueTable)- .innerJoin(- customFieldDefinitionTable,- eq(customFieldValueTable.fieldId, customFieldDefinitionTable.id),- )- .where(- and(- eq(customFieldValueTable.taskId, sourceTask.id),- eq(customFieldDefinitionTable.projectId, sourceTask.projectId),- ),- );- const customFields = sourceCustomFields.map(({ fieldId, value }) => ({- fieldId,- value: value ?? "",- }));- // Older tasks may predate a required field. Apply its current default or fail- // validation, just as creation does, before copying anything in storage.- for (const definition of fieldDefinitions) {- if (!definition.required || !definition.defaultValue?.trim()) continue;- const existing = customFields.find(- (field) => field.fieldId === definition.id,+ const readCustomFields = async (connection: Pick<typeof db, "select">) => {+ const fieldDefinitions = await connection+ .select()+ .from(customFieldDefinitionTable)+ .where(eq(customFieldDefinitionTable.projectId, sourceTask.projectId))+ .orderBy(customFieldDefinitionTable.id);+ const sourceCustomFields = await connection+ .select({+ fieldId: customFieldValueTable.fieldId,+ value: customFieldValueTable.value,+ })+ .from(customFieldValueTable)+ .innerJoin(+ customFieldDefinitionTable,+ eq(customFieldValueTable.fieldId, customFieldDefinitionTable.id),+ )+ .where(+ and(+ eq(customFieldValueTable.taskId, sourceTask.id),+ eq(customFieldDefinitionTable.projectId, sourceTask.projectId),+ ),+ );+ const customFields = sourceCustomFields.map(({ fieldId, value }) => ({+ fieldId,+ value: value ?? "",+ }));+ // Older tasks may predate a required field. Apply its current default or fail+ // validation, just as creation does, before copying anything in storage.+ for (const definition of fieldDefinitions) {+ if (!definition.required || !definition.defaultValue?.trim()) continue;+ const existing = customFields.find(+ (field) => field.fieldId === definition.id,+ );+ if (!existing)+ customFields.push({+ fieldId: definition.id,+ value: definition.defaultValue.trim(),+ });+ else if (!existing.value.trim())+ existing.value = definition.defaultValue.trim();+ }+ await assertRequiredCustomFields(+ sourceTask.projectId,+ customFields,+ connection,);- if (!existing)- customFields.push({- fieldId: definition.id,- value: definition.defaultValue.trim(),- });- else if (!existing.value.trim())- existing.value = definition.defaultValue.trim();- }- await assertRequiredCustomFields(sourceTask.projectId, customFields);+ return customFields;+ };+ await readCustomFields(db);const sourceLabels = await db.select({@@ -256,6 +265,15 @@ async function duplicateTask({try {duplicated = await db.transaction(async (tx) => {+ // Storage calls may outlast an option rename; reread selections while holding definition locks.+ await tx+ .select({ id: customFieldDefinitionTable.id })+ .from(customFieldDefinitionTable)+ .where(eq(customFieldDefinitionTable.projectId, sourceTask.projectId))+ .orderBy(customFieldDefinitionTable.id)+ .for("share");+ const customFields = await readCustomFields(tx);+const taskNumber = await claimTaskNumber(sourceTask.projectId, tx);const nextPosition = await nextTaskPosition(tx,diff --git a/apps/api/src/task/validate-task-fields.ts b/apps/api/src/task/validate-task-fields.tsindex b2a70b33b..2ccd1da43 100644--- a/apps/api/src/task/validate-task-fields.ts+++ b/apps/api/src/task/validate-task-fields.ts@@ -125,8 +125,9 @@ export function validateCustomFieldValue(export async function assertRequiredCustomFields(projectId: string,customFields: { fieldId: string; value: string }[] = [],+ connection: Pick<typeof db, "select"> = db,): Promise<void> {- const allFields = await db+ const allFields = await connection.select({id: customFieldDefinitionTable.id,name: customFieldDefinitionTable.name,diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex 414db106c..1bac1c064 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -544,3 +544,14 @@ for (const eventName of taskUpdateEvents) {}});}++subscribeToEvent<{ projectId: string; initiatorId?: string }>(+ "custom-field.updated",+ async ({ projectId, initiatorId }) => {+ broadcastToProject(+ projectId,+ { type: "CUSTOM_FIELD_UPDATED", projectId },+ initiatorId,+ );+ },+);diff --git a/apps/docs/core/functional/create-workspace-and-project.mdx b/apps/docs/core/functional/create-workspace-and-project.mdxindex 72f9fa56a..c7acea836 100644--- a/apps/docs/core/functional/create-workspace-and-project.mdx+++ b/apps/docs/core/functional/create-workspace-and-project.mdx@@ -40,6 +40,12 @@ Before team onboarding, align on:This keeps your board consistent from day one.+## 5. Maintain custom fields++Open **Project settings → Workflow → Custom Fields** and use the pencil button beside a field to edit its name. For dropdown and multi-select fields, you can rename individual options, add options, or remove unused options.++Renaming an option also updates existing task selections and the field's default value. An option used by a task or default cannot be removed. Field type and required settings stay unchanged. Editing requires the project's update permission.+## Next- [Plan and execute tasks in Board/List](/core/functional/plan-and-execute-tasks)diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex ec2f6ea71..a297175a0 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -17002,6 +17002,122 @@}},"/custom-field/{id}": {+ "patch": {+ "operationId": "updateCustomField",+ "tags": [+ "Custom Fields"+ ],+ "summary": "Edit custom field",+ "description": "Rename a field or edit its selection options. Supply originalValue for existing options to preserve task selections and defaults when renaming. Omitted existing options are removed only when unused. The type and required setting are preserved. updatedAt must match the current definition.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "id",+ "in": "path"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ },+ "options": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "originalValue": {+ "type": "string"+ },+ "value": {+ "type": "string",+ "minLength": 1+ }+ },+ "required": [+ "value"+ ]+ }+ }+ },+ "required": [+ "name",+ "updatedAt"+ ],+ "additionalProperties": false+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "The updated custom field",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CustomFieldDefinition"+ }+ }+ }+ },+ "400": {+ "description": "Invalid options, an option is in use, or unknown field",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No workspace access or missing project:update permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Custom field not found",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "The custom field has changed since it was loaded",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ },"delete": {"operationId": "deleteCustomField","tags": [diff --git a/apps/web/src/components/project/custom-field-editor.tsx b/apps/web/src/components/project/custom-field-editor.tsxindex 1d0290bb3..5f9feb3ff 100644--- a/apps/web/src/components/project/custom-field-editor.tsx+++ b/apps/web/src/components/project/custom-field-editor.tsx@@ -5,6 +5,7 @@ import {GripVertical,Hash,List,+ Pencil,Plus,Trash2,Type,@@ -40,8 +41,10 @@ import useCreateCustomField from "@/hooks/mutations/custom-field/use-create-custimport useDeleteCustomField from "@/hooks/mutations/custom-field/use-delete-custom-field";import { useReorderCustomFields } from "@/hooks/mutations/custom-field/use-reorder-custom-field";import useGetCustomFieldsByProject from "@/hooks/queries/custom-field/use-get-custom-fields-by-project";+import { useWorkspacePermission } from "@/hooks/use-workspace-permission";import { toast } from "@/lib/toast";import { cn } from "@/lib/utils";+import EditCustomFieldDialog from "./edit-custom-field-dialog";type CustomFieldType =| "text"@@ -85,6 +88,7 @@ export default function CustomFieldEditor({projectId,}: CustomFieldEditorProps) {const { t } = useTranslation();+ const { canUpdateProjects } = useWorkspacePermission();const { data: customFields = [], isLoading: customFieldsLoading } =useGetCustomFieldsByProject(projectId) as {@@ -98,6 +102,8 @@ export default function CustomFieldEditor({useDeleteCustomField(projectId);const { mutateAsync: reorderCustomFields } = useReorderCustomFields();+ const [editingField, setEditingField] =+ useState<CustomFieldDefinition | null>(null);const [name, setName] = useState("");const [type, setType] = useState<CustomFieldType>("text");const [required, setRequired] = useState(false);@@ -387,6 +393,13 @@ export default function CustomFieldEditor({return (<div className="space-y-3">+ {editingField && (+ <EditCustomFieldDialog+ key={editingField.id}+ field={editingField}+ onClose={() => setEditingField(null)}+ />+ )}<div className="space-y-1">{customFieldsLoading ? (<div className="text-sm text-muted-foreground">@@ -542,6 +555,17 @@ export default function CustomFieldEditor({))}</div></div>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 w-7 p-0 shrink-0"+ disabled={!canUpdateProjects || deletingField || isReordering}+ onClick={() => setEditingField(field)}+ aria-label={t("settings:customFields.editButton")}+ >+ <Pencil className="size-3.5" />+ </Button><Buttontype="button"variant="ghost"@@ -884,7 +908,9 @@ export default function CustomFieldEditor({key={`field_option_${option}`}value={option}>- <span className="block max-w-38 truncate">{option}</span>+ <span className="block min-w-0 whitespace-normal break-words text-left">+ {option}+ </span></ComboboxItem>)}</ComboboxList>diff --git a/apps/web/src/components/project/edit-custom-field-dialog.test.tsx b/apps/web/src/components/project/edit-custom-field-dialog.test.tsxnew file mode 100644index 000000000..37013fa7e--- /dev/null+++ b/apps/web/src/components/project/edit-custom-field-dialog.test.tsx@@ -0,0 +1,121 @@+vi.mock("@/lib/i18n", () => ({ i18n: { t: (key: string) => key } }));++import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import EditCustomFieldDialog from "./edit-custom-field-dialog";++const { mutateAsync, success } = vi.hoisted(() => ({+ mutateAsync: vi.fn(),+ success: vi.fn(),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, args?: { number: number }) =>+ args ? `${key} ${args.number}` : key,+ }),+}));+vi.mock("@/hooks/mutations/custom-field/use-update-custom-field", () => ({+ default: () => ({ mutateAsync, isPending: false }),+}));+vi.mock("@/lib/toast", () => ({ toast: { success } }));+const field = {+ id: "field",+ projectId: "project",+ name: "People",+ type: "multiselect" as const,+ required: false,+ defaultValue: null,+ options: ["Alice", "Bob"],+ position: 0,+ createdAt: "2026-09-26T00:00:00.000Z",+ updatedAt: "2026-09-26T00:00:00.000Z",+};+afterEach(() => {+ cleanup();+ vi.resetAllMocks();+});++describe("edit custom field dialog", () => {+ it("retains option identity when renaming and saves the loaded version", async () => {+ const onClose = vi.fn();+ mutateAsync.mockResolvedValue({});+ render(<EditCustomFieldDialog field={field} onClose={onClose} />);+ fireEvent.change(+ screen.getByLabelText("settings:customFields.namePlaceholder"),+ { target: { value: "Attendees" } },+ );+ fireEvent.change(+ screen.getByLabelText("settings:customFields.optionLabel 1"),+ { target: { value: "Alex" } },+ );+ fireEvent.click(+ screen.getByRole("button", { name: "settings:customFields.saveButton" }),+ );+ await waitFor(() => expect(onClose).toHaveBeenCalled());+ expect(mutateAsync).toHaveBeenCalledWith({+ param: { id: "field" },+ json: {+ name: "Attendees",+ updatedAt: field.updatedAt,+ options: [+ { originalValue: "Alice", value: "Alex" },+ { originalValue: "Bob", value: "Bob" },+ ],+ },+ });+ });+ it("cancels without saving", () => {+ const onClose = vi.fn();+ render(<EditCustomFieldDialog field={field} onClose={onClose} />);+ fireEvent.click(+ screen.getByRole("button", { name: "common:actions.cancel" }),+ );+ expect(onClose).toHaveBeenCalled();+ expect(mutateAsync).not.toHaveBeenCalled();+ });+ it("prevents duplicate or missing option names", () => {+ render(<EditCustomFieldDialog field={field} onClose={vi.fn()} />);+ const save = screen.getByRole("button", {+ name: "settings:customFields.saveButton",+ });+ fireEvent.change(+ screen.getByLabelText("settings:customFields.optionLabel 1"),+ { target: { value: " Bob " } },+ );+ expect(save).toBeDisabled();+ fireEvent.change(+ screen.getByLabelText("settings:customFields.optionLabel 1"),+ { target: { value: " " } },+ );+ expect(save).toBeDisabled();+ });+ it("keeps the editor and changes open when the server rejects deletion", async () => {+ const onClose = vi.fn();+ mutateAsync.mockRejectedValue(new Error("Option is in use"));+ render(+ <EditCustomFieldDialog+ field={{ ...field, options: ["Alice", "Bob", "Chris"] }}+ onClose={onClose}+ />,+ );+ fireEvent.click(+ screen.getByRole("button", {+ name: "settings:customFields.removeOption 3",+ }),+ );+ fireEvent.click(+ screen.getByRole("button", { name: "settings:customFields.saveButton" }),+ );+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Option is in use",+ );+ expect(onClose).not.toHaveBeenCalled();+ expect(screen.getAllByRole("textbox")).toHaveLength(3);+ });+});diff --git a/apps/web/src/components/project/edit-custom-field-dialog.tsx b/apps/web/src/components/project/edit-custom-field-dialog.tsxnew file mode 100644index 000000000..373a9d9f3--- /dev/null+++ b/apps/web/src/components/project/edit-custom-field-dialog.tsx@@ -0,0 +1,196 @@+import { Plus, Trash2 } from "lucide-react";+import { useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogPanel,+ DialogPopup,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import useUpdateCustomField from "@/hooks/mutations/custom-field/use-update-custom-field";+import { toast } from "@/lib/toast";+import type { CustomFieldDefinition } from "./custom-field-editor";++export default function EditCustomFieldDialog({+ field,+ onClose,+}: {+ field: CustomFieldDefinition;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const [name, setName] = useState(field.name);+ const nextOptionKey = useRef(field.options?.length ?? 0);+ const [options, setOptions] = useState(() =>+ (field.options ?? []).map((value, key) => ({+ key,+ originalValue: value as string | undefined,+ value,+ })),+ );+ const [error, setError] = useState<string | null>(null);+ const { mutateAsync, isPending } = useUpdateCustomField();+ const hasOptions = field.type === "dropdown" || field.type === "multiselect";+ const normalizedOptions = options.map((option) => option.value.trim());+ const valid =+ name.trim() &&+ (!hasOptions ||+ (options.length >= (field.type === "multiselect" ? 2 : 1) &&+ normalizedOptions.every(Boolean) &&+ new Set(normalizedOptions).size === options.length));++ async function save() {+ if (!valid || isPending) return;+ setError(null);+ try {+ await mutateAsync({+ param: { id: field.id },+ json: {+ name: name.trim(),+ updatedAt: field.updatedAt,+ ...(hasOptions+ ? {+ options: options.map(({ originalValue, value }) => ({+ originalValue,+ value: value.trim(),+ })),+ }+ : {}),+ },+ });+ toast.success(t("settings:customFields.updateSuccess"));+ onClose();+ } catch (error) {+ setError(+ error instanceof Error+ ? error.message+ : t("settings:customFields.updateError"),+ );+ }+ }++ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !isPending) onClose();+ }}+ >+ <DialogPopup>+ <form+ className="contents"+ onSubmit={(event) => {+ event.preventDefault();+ void save();+ }}+ >+ <DialogHeader>+ <DialogTitle>{t("settings:customFields.editTitle")}</DialogTitle>+ <DialogDescription>+ {t("settings:customFields.editDescription")}+ </DialogDescription>+ </DialogHeader>+ <DialogPanel className="space-y-4">+ <div className="space-y-2">+ <label+ htmlFor="edit-custom-field-name"+ className="text-sm font-medium"+ >+ {t("settings:customFields.namePlaceholder")}+ </label>+ <Input+ id="edit-custom-field-name"+ value={name}+ onChange={(event) => setName(event.target.value)}+ disabled={isPending}+ autoFocus+ />+ </div>+ {hasOptions && (+ <fieldset disabled={isPending} className="space-y-2">+ <legend className="mb-2 text-sm font-medium">+ {t("settings:customFields.availableOptions")}+ </legend>+ {options.map((option, index) => (+ <div key={option.key} className="flex items-center gap-2">+ <Input+ aria-label={t("settings:customFields.optionLabel", {+ number: index + 1,+ })}+ value={option.value}+ onChange={(event) =>+ setOptions((current) =>+ current.map((item) =>+ item.key === option.key+ ? { ...item, value: event.target.value }+ : item,+ ),+ )+ }+ />+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-label={t("settings:customFields.removeOption", {+ number: index + 1,+ })}+ onClick={() =>+ setOptions((current) =>+ current.filter((item) => item.key !== option.key),+ )+ }+ >+ <Trash2 className="size-4" />+ </Button>+ </div>+ ))}+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => {+ const key = nextOptionKey.current++;+ setOptions((current) => [+ ...current,+ { key, originalValue: undefined, value: "" },+ ]);+ }}+ >+ <Plus className="size-4" />+ {t("settings:customFields.addOption")}+ </Button>+ <p className="text-xs text-muted-foreground">+ {t("settings:customFields.optionsEditHint")}+ </p>+ </fieldset>+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ </DialogPanel>+ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ disabled={isPending}+ onClick={onClose}+ >+ {t("common:actions.cancel")}+ </Button>+ <Button type="submit" disabled={!valid || isPending}>+ {t("settings:customFields.saveButton")}+ </Button>+ </DialogFooter>+ </form>+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/web/src/components/task/custom-field-multi-select.test.tsx b/apps/web/src/components/task/custom-field-multi-select.test.tsxnew file mode 100644index 000000000..16af7d402--- /dev/null+++ b/apps/web/src/components/task/custom-field-multi-select.test.tsx@@ -0,0 +1,62 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { useState } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import CustomFieldMultiSelect from "./custom-field-multi-select";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: () => "Select option" }),+}));+afterEach(cleanup);+const options = [+ "Alexandra Example — Vorstand und Projektkoordination",+ "Benjamin Example — Stellvertretender Vorsitzender",+];++describe("custom field multi-select", () => {+ it("exposes an accessible trigger and keeps full option labels while selecting multiple values", async () => {+ const commit = vi.fn();+ function Fixture() {+ const [value, setValue] = useState([options[0]]);+ return (+ <CustomFieldMultiSelect+ name="Attendees"+ options={options}+ value={value}+ onChange={setValue}+ onCommit={commit}+ />+ );+ }+ render(<Fixture />);+ const trigger = screen.getByRole("combobox", { name: "Attendees" });+ fireEvent.click(trigger);+ const second = await screen.findByRole("option", { name: options[1] });+ fireEvent.keyDown(second, { key: "Enter" });+ fireEvent.keyUp(second, { key: "Enter" });+ await waitFor(() =>+ expect(second).toHaveAttribute("aria-selected", "true"),+ );+ fireEvent.keyDown(second, { key: "Escape" });+ await waitFor(() => expect(commit).toHaveBeenCalledWith(options));+ expect(trigger).toHaveTextContent(options.join(", "));+ });+ it("disables editing for read-only users", () => {+ render(+ <CustomFieldMultiSelect+ name="Attendees"+ options={options}+ value={[]}+ disabled+ onChange={vi.fn()}+ onCommit={vi.fn()}+ />,+ );+ expect(screen.getByRole("combobox", { name: "Attendees" })).toBeDisabled();+ });+});diff --git a/apps/web/src/components/task/custom-field-multi-select.tsx b/apps/web/src/components/task/custom-field-multi-select.tsxnew file mode 100644index 000000000..4d3f1561a--- /dev/null+++ b/apps/web/src/components/task/custom-field-multi-select.tsx@@ -0,0 +1,81 @@+import { useTranslation } from "react-i18next";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++type Props = {+ name: string;+ options: string[];+ value: string[];+ disabled?: boolean;+ onChange: (value: string[]) => void;+ onCommit: (value: string[]) => void;+};++export default function CustomFieldMultiSelect({+ name,+ options,+ value,+ disabled,+ onChange,+ onCommit,+}: Props) {+ const { t } = useTranslation();+ return (+ <Select+ multiple+ items={options.map((option) => ({ value: option, label: option }))}+ value={value}+ onValueChange={onChange}+ onOpenChange={(open) => {+ if (!open) onCommit(value);+ }}+ disabled={disabled || options.length === 0}+ >+ <SelectTrigger+ aria-label={name}+ className="h-9 w-full min-w-0 bg-background text-sm"+ >+ <SelectValue+ className="min-w-0"+ title={value.join(", ")}+ placeholder={t("tasks:detail.selectOption")}+ >+ {(selected: string[]) =>+ selected.length+ ? selected.join(", ")+ : t("tasks:detail.selectOption")+ }+ </SelectValue>+ {value.length > 1 && (+ <span+ aria-hidden="true"+ className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground"+ >+ {value.length}+ </span>+ )}+ </SelectTrigger>+ <SelectContent+ alignItemWithTrigger={false}+ className="w-(--anchor-width)"+ >+ {options.map((option) => (+ <SelectItem+ key={option}+ value={option}+ className="grid-cols-[1rem_minmax(0,1fr)] items-start py-1.5 leading-5"+ >+ <span className="block whitespace-normal break-words text-left">+ {option}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}diff --git a/apps/web/src/components/task/task-details-content.tsx b/apps/web/src/components/task/task-details-content.tsxindex 0ac54c12b..58d6051b3 100644--- a/apps/web/src/components/task/task-details-content.tsx+++ b/apps/web/src/components/task/task-details-content.tsx@@ -16,27 +16,12 @@ import {} from "@/components/ui/accordion";import { Button } from "@/components/ui/button";import { Calendar } from "@/components/ui/calendar";-import {- Combobox,- ComboboxChips,- ComboboxChipsInput,- ComboboxEmpty,- ComboboxItem,- ComboboxList,- ComboboxPopup,- ComboboxValue,-} from "@/components/ui/combobox";import { Input } from "@/components/ui/input";import {Popover,PopoverContent,PopoverTrigger,} from "@/components/ui/popover";-import {- HoverCard,- HoverCardContent,- HoverCardTrigger,-} from "@/components/ui/preview-card";import {Select,SelectContent,@@ -58,6 +43,7 @@ import { useWorkspacePermission } from "@/hooks/use-workspace-permission";import { cn } from "@/lib/cn";import { toast } from "@/lib/toast";import type { ExternalLink } from "@/types/external-link";+import CustomFieldMultiSelect from "./custom-field-multi-select";import TaskDescription from "./task-description";import TaskRelations from "./task-relations";import TaskSubtasks from "./task-subtasks";@@ -303,7 +289,10 @@ export default function TaskDetailsContent({)}/></SelectTrigger>- <SelectContent className="max-w-[25rem]">+ <SelectContent+ alignItemWithTrigger={false}+ className="w-(--anchor-width)"+ >{!field.required && (<SelectItem key="empty" value="">{t("tasks:detail.selectOption")}@@ -312,7 +301,7 @@ export default function TaskDetailsContent({{Array.from(new Set(field.options || [])).map((opt) => (<SelectItem key={opt} value={opt}>- <span className="block max-w-38 truncate">+ <span className="block min-w-0 whitespace-normal break-words text-left">{opt}</span></SelectItem>@@ -467,165 +456,18 @@ export default function TaskDetailsContent({)}</div>) : field.type === "multiselect" ? (- <Combobox- multiple={true}- autoHighlight- items={Array.from(new Set(field.options ?? []))}+ <CustomFieldMultiSelect+ name={field.name}+ options={Array.from(new Set(field.options ?? []))}value={multiselectVal}- onValueChange={(newVal) => {- const nextVal = newVal as string[];- handleLocalChange(field.id, nextVal);- }}- onOpenChange={(open) => {- if (!open) {- handleLocalChange(field.id, multiselectVal);- void handleSaveField(field.id, multiselectVal);- }- }}disabled={!canEdit}- >- <ComboboxChips className="h-9 w-full flex-[2_0_0] select-none cursor-default text-sm disabled:opacity-50">- <ComboboxValue>- {(values: string[]) => {- const MAX_VISIBLE_CHIPS = 3;- const visibleChips = values.slice(- 0,- MAX_VISIBLE_CHIPS,- );- const hiddenCount =- values.length - MAX_VISIBLE_CHIPS;-- return (- <>- {visibleChips.map((value) => (- <div- key={value}- className={cn(- "min-w-0 max-w-full flex-1 shrink basis-0",- "inline-flex items-center overflow-hidden",- "rounded-md bg-secondary px-1.5 py-0.5",- "select-none cursor-default",- )}- >- <span className="block min-w-0 max-w-full truncate text-xs text-secondary-foreground">- {value}- </span>- </div>- ))}- {values.length > MAX_VISIBLE_CHIPS && (- <HoverCard>- <HoverCardTrigger asChild>- <button- type="button"- className="shrink-0 inline-flex items-center gap-1 text-xs font-medium cursor-pointer text-foreground/50 pe-1"- onClick={(e) => {- e.stopPropagation();- e.preventDefault();- }}- onPointerDown={(e) => {- e.stopPropagation();- e.preventDefault();- }}- >- {t(- "settings:customFields.moreOptions",- {- hiddenCount,- },- )}- </button>- </HoverCardTrigger>-- <HoverCardContent- side="top"- align="start"- className="flex max-w-xs flex-wrap gap-1"- >- <div className="space-y-1.5">- <div className="text-xs font-medium text-muted-foreground">- {t(- "settings:customFields.availableOptions",- "Available options",- )}- </div>-- <div className="flex min-w-0 max-h-48 flex-wrap gap-x-1.5 gap-y-1.5 overflow-y-auto overflow-x-hidden">- {values- .slice(MAX_VISIBLE_CHIPS)- .map((value) => (- <div- key={value}- className={cn(- "min-w-0 max-w-full",- "inline-flex items-center overflow-hidden",- "rounded bg-secondary px-1.5 py-0.5",- "select-none cursor-default",- )}- >- <span className="block min-w-0 max-w-[13rem] truncate text-xs">- {value}- </span>- </div>- ))}- </div>- </div>- </HoverCardContent>- </HoverCard>- )}-- <ComboboxChipsInput- className={cn(- "min-w-0 flex-1 caret-transparent",- values.length > 0 && "hidden",- "pointer-events-none",- "placeholder:text-foreground/50",- "text-transparent",- )}- placeholder={- Array.from(- new Set(field.options ?? []),- ).length === 0- ? t(- "settings:customFields.noOptionsPlaceholder",- "No options",- )- : values.length === 0- ? t(- "settings:customFields.defaultValuePlaceholder",- "Default value",- )- : undefined- }- />- </>- );- }}- </ComboboxValue>- </ComboboxChips>-- <ComboboxPopup>- <ComboboxEmpty>- {t(- "settings:customFields.noOptionsPlaceholder",- "No options",- )}- </ComboboxEmpty>-- <ComboboxList>- {(option: string) => (- <ComboboxItem- className="min-w-0 max-w-full"- key={`field_option_${option}`}- value={option}- >- <span className="block max-w-38 truncate">- {option}- </span>- </ComboboxItem>- )}- </ComboboxList>- </ComboboxPopup>- </Combobox>+ onChange={(value) =>+ handleLocalChange(field.id, value)+ }+ onCommit={(value) =>+ void handleSaveField(field.id, value)+ }+ />) : (<Inputtype="text"diff --git a/apps/web/src/fetchers/custom-field/update-custom-field.ts b/apps/web/src/fetchers/custom-field/update-custom-field.tsnew file mode 100644index 000000000..cceacb8da--- /dev/null+++ b/apps/web/src/fetchers/custom-field/update-custom-field.ts@@ -0,0 +1,15 @@+import { client } from "@kaneo/libs";+import type { InferRequestType } from "hono/client";+import { HttpError } from "@/lib/http-error";++export type UpdateCustomFieldRequest = InferRequestType<+ (typeof client)["custom-field"][":id"]["$patch"]+>;++export default async function updateCustomField(+ request: UpdateCustomFieldRequest,+) {+ const response = await client["custom-field"][":id"].$patch(request);+ if (!response.ok) throw new HttpError(response.status, await response.text());+ return response.json();+}diff --git a/apps/web/src/hooks/mutations/custom-field/use-update-custom-field.ts b/apps/web/src/hooks/mutations/custom-field/use-update-custom-field.tsnew file mode 100644index 000000000..2670844cd--- /dev/null+++ b/apps/web/src/hooks/mutations/custom-field/use-update-custom-field.ts@@ -0,0 +1,26 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import updateCustomField from "@/fetchers/custom-field/update-custom-field";+import { HttpError } from "@/lib/http-error";++export default function useUpdateCustomField() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: updateCustomField,+ onError: async (error) => {+ if (error instanceof HttpError && error.status === 409) {+ await queryClient.invalidateQueries({ queryKey: ["custom-fields"] });+ }+ },+ onSuccess: async (field) => {+ await Promise.all(+ [+ ["custom-fields", field.projectId],+ ["custom-field-values"],+ ["custom-field-filter-values", field.projectId],+ ["tasks", field.projectId],+ ["task"],+ ].map((queryKey) => queryClient.invalidateQueries({ queryKey })),+ );+ },+ });+}diff --git a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsxindex 12e93fede..b872dfc26 100644--- a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx@@ -53,6 +53,27 @@ describe("project WebSocket lifecycle", () => {vi.unstubAllEnvs();});+ it("refreshes definitions, selections, filters and tasks after an option rename", () => {+ renderHook(() => useProjectWebSocket("project-a"));+ act(() =>+ TestSocket.instances[0].onmessage?.({+ data: JSON.stringify({+ type: "CUSTOM_FIELD_UPDATED",+ projectId: "project-a",+ }),+ }),+ );+ for (const queryKey of [+ ["custom-fields", "project-a"],+ ["custom-field-values"],+ ["custom-field-filter-values", "project-a"],+ ["tasks", "project-a"],+ ["task"],+ ]) {+ expect(client.invalidateQueries).toHaveBeenCalledWith({ queryKey });+ }+ });+it("ignores late old-project events without stopping the new project's keepalive", () => {const { rerender, unmount } = renderHook(({ id }) => useProjectWebSocket(id),diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.tsindex 82033e8b9..fe7286dff 100644--- a/apps/web/src/hooks/use-project-websocket.ts+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -62,6 +62,18 @@ export function useProjectWebSocket(projectId: string) {if (disposed || activeSocket !== ws) return;try {const message = JSON.parse(event.data);+ if (message.type === "CUSTOM_FIELD_UPDATED") {+ for (const queryKey of [+ ["custom-fields", projectId],+ ["custom-field-values"],+ ["custom-field-filter-values", projectId],+ ["tasks", projectId],+ ["task"],+ ]) {+ void queryClient.invalidateQueries({ queryKey });+ }+ return;+ }if (message.type === "PROJECT_MOVED") {for (const queryKey of [["projects"],diff --git a/i18n/az-AZ.json b/i18n/az-AZ.jsonindex 297f07906..291fe38e2 100644--- a/i18n/az-AZ.json+++ b/i18n/az-AZ.json@@ -1495,7 +1495,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/de-DE.json b/i18n/de-DE.jsonindex 51a1e40cd..105a9cd8f 100644--- a/i18n/de-DE.json+++ b/i18n/de-DE.json@@ -1575,7 +1575,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "editButton": "Benutzerdefiniertes Feld bearbeiten",+ "editTitle": "Benutzerdefiniertes Feld bearbeiten",+ "editDescription": "Feldnamen und Auswahloptionen bearbeiten.",+ "updateSuccess": "Benutzerdefiniertes Feld aktualisiert",+ "updateError": "Benutzerdefiniertes Feld konnte nicht aktualisiert werden",+ "optionLabel": "Option {{number}}",+ "removeOption": "Option {{number}} entfernen",+ "addOption": "Option hinzufügen",+ "optionsEditHint": "Umbenennungen aktualisieren die Auswahl in bestehenden Aufgaben und die Standardwerte. Verwendete Optionen können nicht entfernt werden.",+ "saveButton": "Speichern"},"security": "Security","securityPage": {diff --git a/i18n/el-GR.json b/i18n/el-GR.jsonindex 8aefcc3d3..e82fb202f 100644--- a/i18n/el-GR.json+++ b/i18n/el-GR.json@@ -1495,7 +1495,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/en-US.json b/i18n/en-US.jsonindex 932f087db..23b2a57a7 100644--- a/i18n/en-US.json+++ b/i18n/en-US.json@@ -1153,7 +1153,17 @@"boolean": "Boolean","multiselect": "Multi-Select"},- "multiple": "Multiple"+ "multiple": "Multiple",+ "editButton": "Edit custom field",+ "editTitle": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "updateSuccess": "Custom field updated",+ "updateError": "Failed to update custom field",+ "optionLabel": "Option {{number}}",+ "removeOption": "Remove option {{number}}",+ "addOption": "Add option",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "saveButton": "Save changes"},"githubIntegration": {"validation": {diff --git a/i18n/es-ES.json b/i18n/es-ES.jsonindex f463eaaac..ae57c9f28 100644--- a/i18n/es-ES.json+++ b/i18n/es-ES.json@@ -1496,7 +1496,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/fr-FR.json b/i18n/fr-FR.jsonindex d107f649c..300491908 100644--- a/i18n/fr-FR.json+++ b/i18n/fr-FR.json@@ -1496,7 +1496,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Échec du réagencement des champs",- "selectPlaceholder": "Sélectionner une option"+ "selectPlaceholder": "Sélectionner une option",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/hi-IN.json b/i18n/hi-IN.jsonindex b6bbdce3a..01637853f 100644--- a/i18n/hi-IN.json+++ b/i18n/hi-IN.json@@ -1495,7 +1495,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/id-ID.json b/i18n/id-ID.jsonindex 74ca2012f..98d5f886c 100644--- a/i18n/id-ID.json+++ b/i18n/id-ID.json@@ -1494,7 +1494,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/it-IT.json b/i18n/it-IT.jsonindex 2ea59c226..41a0e6b34 100644--- a/i18n/it-IT.json+++ b/i18n/it-IT.json@@ -1496,7 +1496,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/ja-JP.json b/i18n/ja-JP.jsonindex d2c7bcbcd..7568f4160 100644--- a/i18n/ja-JP.json+++ b/i18n/ja-JP.json@@ -1494,7 +1494,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/ko-KR.json b/i18n/ko-KR.jsonindex b71f92294..9de467680 100644--- a/i18n/ko-KR.json+++ b/i18n/ko-KR.json@@ -1494,7 +1494,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/mk-MK.json b/i18n/mk-MK.jsonindex f1d29670b..78674b872 100644--- a/i18n/mk-MK.json+++ b/i18n/mk-MK.json@@ -1495,7 +1495,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/nl-NL.json b/i18n/nl-NL.jsonindex bb57b3276..e9a3f2d03 100644--- a/i18n/nl-NL.json+++ b/i18n/nl-NL.json@@ -1495,7 +1495,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/pl-PL.json b/i18n/pl-PL.jsonindex 6c97a2a28..8a81bcb04 100644--- a/i18n/pl-PL.json+++ b/i18n/pl-PL.json@@ -1974,7 +1974,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/pt-BR.json b/i18n/pt-BR.jsonindex f9ac382a4..d45036578 100644--- a/i18n/pt-BR.json+++ b/i18n/pt-BR.json@@ -1496,7 +1496,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/ru-RU.json b/i18n/ru-RU.jsonindex 85f92e612..fee6966d8 100644--- a/i18n/ru-RU.json+++ b/i18n/ru-RU.json@@ -1505,7 +1505,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/schema.json b/i18n/schema.jsonindex ac1c2ab7a..1094c7da6 100644--- a/i18n/schema.json+++ b/i18n/schema.json@@ -4505,6 +4505,36 @@},"multiple": {"type": "string"+ },+ "editButton": {+ "type": "string"+ },+ "editTitle": {+ "type": "string"+ },+ "editDescription": {+ "type": "string"+ },+ "updateSuccess": {+ "type": "string"+ },+ "updateError": {+ "type": "string"+ },+ "optionLabel": {+ "type": "string"+ },+ "removeOption": {+ "type": "string"+ },+ "addOption": {+ "type": "string"+ },+ "optionsEditHint": {+ "type": "string"+ },+ "saveButton": {+ "type": "string"}},"required": [@@ -4531,7 +4561,17 @@"clearDefault","availableOptions","types",- "multiple"+ "multiple",+ "editButton",+ "editTitle",+ "editDescription",+ "updateSuccess",+ "updateError",+ "optionLabel",+ "removeOption",+ "addOption",+ "optionsEditHint",+ "saveButton"]},"githubIntegration": {diff --git a/i18n/tr-TR.json b/i18n/tr-TR.jsonindex f9ef1737c..ca95aea34 100644--- a/i18n/tr-TR.json+++ b/i18n/tr-TR.json@@ -1495,7 +1495,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/uk-UA.json b/i18n/uk-UA.jsonindex d63cad6c5..ec29ddbcd 100644--- a/i18n/uk-UA.json+++ b/i18n/uk-UA.json@@ -1497,7 +1497,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/vi-VN.json b/i18n/vi-VN.jsonindex 0e3b8f5c7..d5e15c28d 100644--- a/i18n/vi-VN.json+++ b/i18n/vi-VN.json@@ -1494,7 +1494,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/i18n/zh-CN.json b/i18n/zh-CN.jsonindex 0567c6a03..73bcdde0c 100644--- a/i18n/zh-CN.json+++ b/i18n/zh-CN.json@@ -1494,7 +1494,17 @@"multiple": "Multiple","options": "{{count}} option(s)","reorderError": "Failed to reorder fields",- "selectPlaceholder": "Select option(s)"+ "selectPlaceholder": "Select option(s)",+ "addOption": "Add option",+ "editButton": "Edit custom field",+ "editDescription": "Update the field name and selection options.",+ "editTitle": "Edit custom field",+ "optionLabel": "Option {{number}}",+ "optionsEditHint": "Renaming an option updates existing task selections and defaults. Options in use cannot be removed.",+ "removeOption": "Remove option {{number}}",+ "updateError": "Failed to update custom field",+ "updateSuccess": "Custom field updated",+ "saveButton": "Save changes"},"administration": "Administration","adminUsers": {diff --git a/tests/api-integration/custom-field-edit.test.ts b/tests/api-integration/custom-field-edit.test.tsnew file mode 100644index 000000000..63cbab3c8--- /dev/null+++ b/tests/api-integration/custom-field-edit.test.ts@@ -0,0 +1,214 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++beforeEach(resetTestDatabase);++async function fixture(type = "multiselect", role = "admin") {+ const member = await createWorkspaceMember({ role });+ const { project, columns } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const [field] = await db+ .insert(schema.customFieldDefinitionTable)+ .values({+ projectId: project.id,+ name: "People",+ type,+ options: ["Alice", "Bob", "Unused"],+ defaultValue: type === "multiselect" ? '["Alice"]' : "Alice",+ required: false,+ })+ .returning();+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Assigned task",+ number: 1,+ status: "to-do",+ columnId: columns.todo.id,+ })+ .returning();+ await db.insert(schema.customFieldValueTable).values({+ taskId: task.id,+ fieldId: field.id,+ value: type === "multiselect" ? '["Alice","Bob"]' : "Alice",+ });+ mockAuthenticatedSession(member.user);+ const { app } = createApp();+ const update = (body: Record<string, unknown> = {}) =>+ app.request(`/api/custom-field/${field.id}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: "Attendees",+ updatedAt: field.updatedAt.toISOString(),+ ...body,+ }),+ });+ const readValue = async () =>+ (+ await db+ .select()+ .from(schema.customFieldValueTable)+ .where(eq(schema.customFieldValueTable.fieldId, field.id))+ )[0]?.value;+ return { app, field, update, readValue, project, task, member };+}++describe("custom field editing", () => {+ it.each(["dropdown", "multiselect"])(+ "renames %s selections and defaults together, and adds/removes unused options",+ async (type) => {+ const { update, readValue, app, project } = await fixture(type);+ const response = await update({+ options: [+ { originalValue: "Alice", value: "Alex" },+ { originalValue: "Bob", value: "Robert" },+ { value: "New person" },+ ],+ });+ expect(response.status, await response.clone().text()).toBe(200);+ expect(await response.json()).toMatchObject({+ name: "Attendees",+ options: ["Alex", "Robert", "New person"],+ defaultValue: type === "multiselect" ? '["Alex"]' : "Alex",+ type,+ required: false,+ });+ expect(await readValue()).toBe(+ type === "multiselect" ? '["Alex","Robert"]' : "Alex",+ );+ const filters = await app.request(+ `/api/custom-field/project/${project.id}/filter-values`,+ );+ expect(await filters.text()).toContain("Alex");+ },+ );++ it("handles simultaneous swaps without collapsing selections", async () => {+ const { update, readValue } = await fixture();+ expect(+ (+ await update({+ options: [+ { originalValue: "Alice", value: "Bob" },+ { originalValue: "Bob", value: "Alice" },+ ],+ })+ ).status,+ ).toBe(200);+ expect(await readValue()).toBe('["Bob","Alice"]');+ });++ it("rolls back when removing an option used by a task", async () => {+ const { update, readValue, field } = await fixture();+ expect(+ (+ await update({+ options: [+ { originalValue: "Alice", value: "Alex" },+ { value: "New" },+ ],+ })+ ).status,+ ).toBe(400);+ expect(await readValue()).toBe('["Alice","Bob"]');+ expect(+ (+ await db+ .select()+ .from(schema.customFieldDefinitionTable)+ .where(eq(schema.customFieldDefinitionTable.id, field.id))+ )[0]?.name,+ ).toBe("People");+ });++ it("protects a default even when no tasks use it", async () => {+ const { update, field } = await fixture();+ await db+ .delete(schema.customFieldValueTable)+ .where(eq(schema.customFieldValueTable.fieldId, field.id));+ expect(+ (+ await update({+ options: [{ originalValue: "Bob", value: "Bob" }, { value: "New" }],+ })+ ).status,+ ).toBe(400);+ });++ it.each([+ { name: " " },+ { type: "text" },+ { options: [{ originalValue: "Missing", value: "A" }, { value: "B" }] },+ {+ options: [+ { originalValue: "Alice", value: "A" },+ { originalValue: "Alice", value: "B" },+ ],+ },+ {+ options: [+ { originalValue: "Alice", value: "Same" },+ { originalValue: "Bob", value: " Same " },+ ],+ },+ { options: [{ value: " " }, { value: "B" }] },+ { options: [] },+ ])("rejects invalid edits %j", async (body) => {+ const { update } = await fixture();+ expect((await update(body)).status).toBe(400);+ });++ it("renames text fields without changing their values or settings", async () => {+ const { update, readValue } = await fixture("text");+ expect((await update()).status).toBe(200);+ expect(await readValue()).toBe("Alice");+ });++ it("rejects stale edits", async () => {+ const { update } = await fixture();+ expect((await update()).status).toBe(200);+ expect((await update({ name: "Stale" })).status).toBe(409);+ });++ it("validates future writes against the renamed options", async () => {+ const { update, app, field, task } = await fixture();+ await update({+ options: [+ { originalValue: "Alice", value: "Alex" },+ { originalValue: "Bob", value: "Bob" },+ ],+ });+ for (const [value, status] of [+ ['["Alice"]', 400],+ ['["Alex"]', 200],+ ] as const) {+ const response = await app.request("/api/custom-field/value", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ taskId: task.id, fieldId: field.id, value }),+ });+ expect(response.status).toBe(status);+ }+ });++ it("rejects readers and users from another workspace", async () => {+ const { update } = await fixture("multiselect", "viewer");+ expect((await update()).status).toBe(403);+ const outsider = await createWorkspaceMember({ role: "admin" });+ mockAuthenticatedSession(outsider.user);+ expect((await update()).status).toBe(403);+ mockAnonymousSession();+ expect([401, 403]).toContain((await update()).status);+ });+});diff --git a/tests/api-integration/websocket-security.test.ts b/tests/api-integration/websocket-security.test.tsindex 4182c1d14..1877252cf 100644--- a/tests/api-integration/websocket-security.test.ts+++ b/tests/api-integration/websocket-security.test.ts@@ -5,8 +5,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { serve } from "../../apps/api/node_modules/@hono/node-server";import type { NodeWebSocket } from "../../apps/api/node_modules/@hono/node-ws";import { auth } from "../../apps/api/src/auth";+import { publishEvent } from "../../apps/api/src/events";import { createApp } from "../../apps/api/src/index";-import { broadcastToUser } from "../../apps/api/src/ws";+import {+ broadcastToUser,+ initializeWebSocketAdapter,+ shutdownWebSocketAdapter,+} from "../../apps/api/src/ws";import { handleWebSocketMessage } from "../../apps/api/src/ws/security";import { mockAuthenticatedSession } from "./helpers/auth";import { resetTestDatabase } from "./helpers/database";@@ -216,3 +221,19 @@ it("still rejects access to a foreign project with a valid Origin", async () =>).status,).toBe(403);});++it("delivers custom field changes through the project broadcast adapter", async () => {+ await initializeWebSocketAdapter();+ const { socket, status } = await connect(projectId, {+ cookie: "test-session=valid",+ origin: "http://localhost:5173",+ });+ expect(status).toBe(101);+ const message = once(socket, "message");+ await publishEvent("custom-field.updated", { projectId });+ expect(JSON.parse((await message)[0].toString())).toEqual({+ type: "CUSTOM_FIELD_UPDATED",+ projectId,+ });+ await shutdownWebSocketAdapter();+});