Skip to content

armgit / kaneo

Public Imported from GitHub
0

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

fix(integrations): refresh open reviews and preserve label colors

Tina3b6052d7dc7
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts
index a69839d66..e18dd8d83 100644
--- a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts
+++ b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts
@@ -39,7 +39,7 @@ type IssueOpenedPayload = {
state?: string;
body: string | null;
html_url: string;
- labels?: Array<string | { name?: string }>;
+ labels?: Array<string | { name?: string; color?: string }>;
user: { login?: string; username?: string } | null;
};
repository: {
diff --git a/apps/api/src/plugins/github/webhooks/issue-opened.ts b/apps/api/src/plugins/github/webhooks/issue-opened.ts
index 1719ff790..c9828448f 100644
--- a/apps/api/src/plugins/github/webhooks/issue-opened.ts
+++ b/apps/api/src/plugins/github/webhooks/issue-opened.ts
@@ -31,7 +31,7 @@ type IssueOpenedPayload = {
state?: string;
body: string | null;
html_url: string;
- labels?: Array<string | { name?: string }>;
+ labels?: Array<string | { name?: string; color?: string }>;
user: { login: string } | null;
};
installation?: { id: number };
diff --git a/apps/api/src/plugins/sync/issue-labels.ts b/apps/api/src/plugins/sync/issue-labels.ts
index 0cd374129..f0eeeedad 100644
--- a/apps/api/src/plugins/sync/issue-labels.ts
+++ b/apps/api/src/plugins/sync/issue-labels.ts
@@ -37,6 +37,19 @@ export async function importIssueLabels(
(name) => !name.startsWith("status:") && !name.startsWith("priority:"),
);
if (!names.length) return;
+ const providerColors = new Map<string, string>();
+ if (Array.isArray(labels))
+ for (const label of labels) {
+ if (
+ !label ||
+ typeof label !== "object" ||
+ typeof label.color !== "string" ||
+ !label.color
+ )
+ continue;
+ const [name] = issueLabelNames([label]);
+ if (name) providerColors.set(name, `#${label.color.replace(/^#/, "")}`);
+ }
const existing = await database
.select({ name: labelTable.name, color: labelTable.color })
.from(labelTable)
@@ -49,7 +62,9 @@ export async function importIssueLabels(
[...new Set(names)].map((name) => ({
name,
color:
- existing.find((label) => label.name === name)?.color ?? "#6B7280",
+ existing.find((label) => label.name === name)?.color ??
+ providerColors.get(name) ??
+ "#6B7280",
taskId,
workspaceId,
})),
diff --git a/apps/web/src/hooks/use-project-websocket-resume.test.tsx b/apps/web/src/hooks/use-project-websocket-resume.test.tsx
new file mode 100644
index 000000000..af789c23b
--- /dev/null
+++ b/apps/web/src/hooks/use-project-websocket-resume.test.tsx
@@ -0,0 +1,142 @@
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { afterEach, expect, it, vi } from "vite-plus/test";
+import type { ResumePreview } from "@/fetchers/integration-sync/types";
+import { useResumePreview } from "./queries/integration-sync/use-resume-preview";
+import { useProjectWebSocket } from "./use-project-websocket";
+
+const mocks = vi.hoisted(() => ({ review: vi.fn(), navigate: vi.fn() }));
+vi.mock("@/fetchers/integration-sync/review-sync-resume", () => ({
+ default: mocks.review,
+}));
+vi.mock("@tanstack/react-router", () => ({
+ useNavigate: () => mocks.navigate,
+}));
+vi.mock("@kaneo/libs", () => ({ windowId: "test" }));
+vi.mock("@/lib/auth-client", () => ({
+ authClient: { useSession: () => ({ data: { user: { id: "user" } } }) },
+}));
+
+class Socket {
+ static current: Socket;
+ onmessage: ((event: { data: string }) => void) | null = null;
+ close() {}
+ constructor() {
+ Socket.current = this;
+ }
+ message(taskId: string) {
+ this.onmessage?.({
+ data: JSON.stringify({ type: "TASK_UPDATED", taskId }),
+ });
+ }
+}
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+it("refreshes only the affected open comparison before accepting its new token", async () => {
+ vi.stubGlobal("WebSocket", Socket);
+ const client = new QueryClient();
+ const initial: ResumePreview = {
+ task: { id: "task", title: "Old", number: 1 },
+ local: { title: "Old", description: "", state: "open" },
+ remote: { title: "Remote", description: "", state: "open" },
+ token: "old-token",
+ };
+ let finish!: (value: ResumePreview) => void;
+ mocks.review
+ .mockReset()
+ .mockResolvedValueOnce(initial)
+ .mockImplementationOnce(
+ () =>
+ new Promise<ResumePreview>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { result } = renderHook(
+ () => {
+ useProjectWebSocket("project");
+ const preview = useResumePreview(
+ { projectId: "project", provider: "github" },
+ "link",
+ );
+ return { data: preview.data, isFetching: preview.isFetching };
+ },
+ {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ },
+ );
+ await waitFor(() => expect(result.current.data).toEqual(initial));
+ expect(
+ client.getQueriesData({
+ queryKey: ["integration-sync-review", "project"],
+ type: "active",
+ }),
+ ).toEqual([
+ [["integration-sync-review", "project", "github", "link"], initial],
+ ]);
+ const invalidation = vi.spyOn(client, "invalidateQueries");
+ client.setQueryData(
+ ["integration-sync-review", "project", "github", "inactive"],
+ initial,
+ );
+ client.setQueryData(
+ ["integration-sync-review", "other-project", "github", "link"],
+ initial,
+ );
+ act(() => Socket.current.message("unrelated-task"));
+ expect(mocks.review).toHaveBeenCalledOnce();
+ let resolveBoard!: (value: null) => void;
+ const boardFetch = client.fetchQuery({
+ queryKey: ["tasks", "project"],
+ queryFn: () =>
+ new Promise((resolve) => {
+ resolveBoard = resolve;
+ }),
+ });
+ act(() => Socket.current.message("task"));
+ expect(invalidation).toHaveBeenCalledWith({
+ queryKey: ["integration-sync-review", "project", "github", "link"],
+ exact: true,
+ });
+ await waitFor(() => expect(result.current.isFetching).toBe(true));
+ expect(mocks.review).toHaveBeenCalledTimes(2);
+ expect(
+ client.getQueryState([
+ "integration-sync-review",
+ "project",
+ "github",
+ "inactive",
+ ])?.isInvalidated,
+ ).toBe(false);
+ expect(
+ client.getQueryState([
+ "integration-sync-review",
+ "other-project",
+ "github",
+ "link",
+ ])?.isInvalidated,
+ ).toBe(false);
+ act(() =>
+ finish({
+ ...initial,
+ task: { ...initial.task, title: "Current" },
+ local: { ...initial.local, title: "Current" },
+ token: "current-token",
+ }),
+ );
+ await waitFor(() => {
+ expect(result.current.isFetching).toBe(false);
+ expect(result.current.data?.local.title).toBe("Current");
+ expect(result.current.data?.token).toBe("current-token");
+ });
+ cleanup();
+ resolveBoard(null);
+ await boardFetch;
+ client.clear();
+});
diff --git a/apps/web/src/hooks/use-project-websocket.test.ts b/apps/web/src/hooks/use-project-websocket.test.ts
index b0eeb7e9b..2920488d2 100644
--- a/apps/web/src/hooks/use-project-websocket.test.ts
+++ b/apps/web/src/hooks/use-project-websocket.test.ts
@@ -23,6 +23,7 @@ vi.mock("@tanstack/react-query", () => ({
getQueryCache: () => ({ subscribe: () => () => {} }),
getQueryState,
getQueryData: () => undefined,
+ getQueriesData: () => [],
cancelQueries,
}),
}));
diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.ts
index 3833b5f16..3c2de3376 100644
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-websocket.ts
@@ -12,6 +12,7 @@ import { authClient } from "@/lib/auth-client";
import getTask from "@/fetchers/task/get-task";
import getLabelsByTask from "@/fetchers/label/get-labels-by-task";
import getExternalLinks from "@/fetchers/external-link/get-external-links";
+import type { ResumePreview } from "@/fetchers/integration-sync/types";
import { patchBoardTask } from "@/lib/patch-board-task";
import type { ProjectWithTasks } from "@/types/project";
import {
@@ -186,6 +187,26 @@ export function useProjectWebSocket(projectId: string) {
if (disposed || activeSocket !== ws) return;
try {
const message = JSON.parse(event.data);
+ if (
+ message.taskId &&
+ [
+ "TASK_UPDATED",
+ "TASK_LABEL_UPDATED",
+ "TASK_MOVED",
+ "TASK_DELETED",
+ ].includes(message.type)
+ )
+ // An open comparison needs a fresh token; other tasks and closed
+ // dialogs must not cause provider reads during routine edits.
+ for (const [
+ queryKey,
+ review,
+ ] of queryClient.getQueriesData<ResumePreview>({
+ queryKey: ["integration-sync-review", projectId],
+ type: "active",
+ }))
+ if (review?.task?.id === message.taskId)
+ void queryClient.invalidateQueries({ queryKey, exact: true });
let titleTaskRequest: ReturnType<typeof getTask> | undefined;
if (
message.taskId &&
diff --git a/tests/api-integration/github-import-bounds.test.ts b/tests/api-integration/github-import-bounds.test.ts
index 9e2510198..a86531d8e 100644
--- a/tests/api-integration/github-import-bounds.test.ts
+++ b/tests/api-integration/github-import-bounds.test.ts
@@ -158,6 +158,64 @@ async function saved() {
}
describe("bounded resumable GitHub import", () => {
+ it("preserves provider colors when rule checks import labels before the page", async () => {
+ const { member, integration, config, request } = await setup();
+ await db.insert(schema.labelTable).values({
+ workspaceId: member.workspace.id,
+ name: "workspace",
+ color: "#123456",
+ });
+ await db
+ .update(schema.integrationTable)
+ .set({
+ config: JSON.stringify({
+ ...config,
+ syncRules: {
+ outgoing: { mode: "all" },
+ incoming: { mode: "labels", match: "any", labels: ["approved"] },
+ },
+ }),
+ })
+ .where(eq(schema.integrationTable.id, integration.id));
+ const labels = [
+ { name: "approved", color: "abcdef" },
+ { name: "workspace", color: "fedcba" },
+ ];
+ mocks.verify.mockResolvedValue({
+ graphql: mocks.graphql,
+ rest: {
+ issues: {
+ get: async () => ({
+ data: {
+ labels: [
+ ...labels,
+ { name: "scope-only", color: "#654321" },
+ "no-color",
+ ],
+ },
+ }),
+ },
+ },
+ });
+ mocks.graphql.mockImplementation(async (query: string) =>
+ query.includes("query ImportIssues(")
+ ? issuePage([issue(1, { labels: connection(labels) })])
+ : emptyPulls(),
+ );
+ expect((await request()).status).toBe(200);
+ const link = (await db.query.externalLinkTable.findMany())[0]!;
+ const assigned = await db.query.labelTable.findMany({
+ where: eq(schema.labelTable.taskId, link.taskId),
+ });
+ expect(
+ Object.fromEntries(assigned.map(({ name, color }) => [name, color])),
+ ).toEqual({
+ approved: "#abcdef",
+ workspace: "#123456",
+ "scope-only": "#654321",
+ "no-color": "#6B7280",
+ });
+ });
it("pauses a newly imported issue that misses the outgoing rule before announcing it", async () => {
const { member, integration, config, request } = await setup();
const [root] = await db
diff --git a/tests/api-integration/integration-sync-imported-link.test.ts b/tests/api-integration/integration-sync-imported-link.test.ts
index 3d7c46bd6..1dc71b026 100644
--- a/tests/api-integration/integration-sync-imported-link.test.ts
+++ b/tests/api-integration/integration-sync-imported-link.test.ts
@@ -92,7 +92,7 @@ it.each(
title: "Imported issue",
body: "Body",
html_url: "https://git.example/team/repo/issues/9",
- labels,
+ labels: labels.map((name) => ({ name, color: "1a2b3c" })),
user: { login: "author" },
};
const repository = {
@@ -143,7 +143,7 @@ it.each(
description: "Body",
url: issue.html_url,
},
- labels: labels.map((title) => ({ title })),
+ labels: labels.map((title) => ({ title, color: "#1a2b3c" })),
project: {
name: "repo",
path_with_namespace: "team/repo",
@@ -157,6 +157,18 @@ it.each(
expect(JSON.parse(link.metadata!).syncFilterPaused === true).toBe(
!qualifying,
);
+ const assigned = await db.query.labelTable.findFirst({
+ where: eq(schema.labelTable.taskId, link.taskId),
+ });
+ expect(assigned?.color).toBe(
+ qualifying
+ ? label.color
+ : source === "manual"
+ ? provider === "gitea"
+ ? "#ff0000"
+ : "#6B7280"
+ : "#1a2b3c",
+ );
if (!qualifying) {
await db.insert(schema.labelTable).values({
taskId: link.taskId,