⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
import {
keepPreviousData,
useInfiniteQuery,
useMutation,
useQuery,
useQueryClient,
} from '@tanstack/react-query';
import {
removeIssueDevelopmentLink,
listIssueDevelopmentRepositories,
listLinkablePullRequests,
listDevelopmentBranches,
linkIssueDevelopment,
createIssuePullRequest,
} from '@/lib/api/endpoints/git';
import {
type BulkIssuePatch,
type IssueFieldValueEntry,
type IssueFieldValueInput,
type IssuePatch,
type NewIssueInput,
type BoardIssue,
type BoardIssues,
type SubtaskDisposition,
getIssue,
listIssueAgentRuns,
getIssueAgentRunTrace,
listIssueCycles,
getIssueBySeq,
searchIssues,
searchAllIssues,
updateIssue,
deleteIssue,
moveIssue,
archiveIssue,
restoreIssue,
setFieldValue,
bulkUpdateIssues,
bulkAddLabels,
bulkArchiveIssues,
bulkDeleteIssues,
createIssue,
} from '@/lib/api/endpoints/issues';
import { qk } from '@/services/queryKeys';
// Deleting or archiving one issue. `subtasks` says what happens to the subtasks
// hanging under it, and is required whenever it has any.
interface IssueRemoval {
id: number;
subtasks?: SubtaskDisposition;
}
// The same for a board multi-select, which removes many issues in one request.
interface BulkRemoval {
ids: number[];
subtasks?: SubtaskDisposition;
}
export function useIssueQuery(id: number | null) {
return useQuery({
queryKey: qk.issue(id ?? -1),
queryFn: () => getIssue(id!),
enabled: id != null,
});
}
export function useRemoveIssueDevelopmentLink(issueId: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: (linkId: number) => removeIssueDevelopmentLink(issueId, linkId),
onSuccess: () => qc.invalidateQueries({ queryKey: qk.issue(issueId) }),
});
}
export function useIssueDevelopmentRepositoriesQuery(issueId: number, enabled: boolean) {
return useQuery({
queryKey: qk.issueDevelopmentRepositories(issueId),
queryFn: () => listIssueDevelopmentRepositories(issueId),
enabled,
});
}
export function useLinkablePullRequestsQuery(
issueId: number,
repositoryId: number | null,
state: 'open' | 'all',
enabled: boolean,
) {
return useInfiniteQuery({
queryKey: qk.issueDevelopmentPullRequests(issueId, repositoryId ?? -1, state),
queryFn: ({ pageParam }) =>
listLinkablePullRequests(issueId, repositoryId!, { state, page: pageParam }),
initialPageParam: 1,
getNextPageParam: (page) => page.nextPage ?? undefined,
enabled: enabled && repositoryId !== null,
});
}
export function useDevelopmentBranchesQuery(
issueId: number,
repositoryId: number | null,
enabled: boolean,
) {
return useInfiniteQuery({
queryKey: qk.issueDevelopmentBranches(issueId, repositoryId ?? -1),
queryFn: ({ pageParam }) => listDevelopmentBranches(issueId, repositoryId!, pageParam),
initialPageParam: 1,
getNextPageParam: (page) => page.nextPage ?? undefined,
enabled: enabled && repositoryId !== null,
});
}
export function useLinkIssueDevelopment(issueId: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: (input: { repositoryId: number; number: number }) =>
linkIssueDevelopment(issueId, input),
onSuccess: () => qc.invalidateQueries({ queryKey: qk.issue(issueId) }),
});
}
export function useCreateIssuePullRequest(issueId: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: (input: Parameters<typeof createIssuePullRequest>[1]) =>
createIssuePullRequest(issueId, input),
onSuccess: () => qc.invalidateQueries({ queryKey: qk.issue(issueId) }),
});
}
// The cycles an issue was planned into. Read only where the badge that shows them
// is, so a project without cycles never asks for it.
export function useIssueCyclesQuery(issueId: number) {
return useQuery({
queryKey: qk.issueCycles(issueId),
queryFn: () => listIssueCycles(issueId),
});
}
// Resolves an issue by its project-scoped number (the identifier-based URL). Seeds
// the by-id cache from the result so the detail's useIssueQuery(id) is instant and
// shares one fetch. Enabled only when a number is present.
export function useIssueBySeqQuery(projectKey: string | null, seq: number | null) {
const qc = useQueryClient();
return useQuery({
queryKey: qk.issueBySeq(projectKey ?? '', seq ?? -1),
queryFn: async () => {
const issue = await getIssueBySeq(projectKey!, seq!);
qc.setQueryData(qk.issue(issue.id), issue);
return issue;
},
enabled: projectKey != null && seq != null,
});
}
// Server-side issue search behind the command palette. Runs only when the palette
// is open and the term is non-empty; includes archived issues (the board payload
// never carries them). keepPreviousData holds the last list while the next query
// runs, so results do not blank out between keystrokes.
export function useIssueSearchQuery(
projectKey: string | null,
q: string,
opts: { enabled: boolean },
) {
const term = q.trim();
return useQuery({
queryKey: qk.issueSearch(projectKey ?? '', term),
queryFn: () => searchIssues(projectKey!, { q: term, limit: 50 }),
enabled: opts.enabled && projectKey != null && term.length > 0,
placeholderData: keepPreviousData,
});
}
// The palette's search in every project the user can read. It leaves out the
// current project, whose own group lists its matches above.
// While that project is still loading its id is unknown, so nothing is searched or
// shown: a search without the id, or one cached from a page with no project, would
// list its issues here too. Disabled, it shows no cached hits either.
export function useOtherProjectIssueSearch(
q: string,
current: { key: string | null; id: number | null },
opts: { enabled: boolean },
) {
const term = q.trim();
const active = opts.enabled && (current.key === null || current.id !== null);
const search = useQuery({
queryKey: qk.issueSearchAll(term, current.id),
queryFn: () =>
searchAllIssues({
q: term,
limit: 50,
perProjectLimit: 5,
excludeProjectId: current.id ?? undefined,
}),
enabled: active && term.length > 0,
// Only the term changed: the previous hits leave out the same project.
placeholderData: (previous, previousQuery) =>
previousQuery?.queryKey[2] === current.id ? previous : undefined,
});
return {
hits: active ? (search.data ?? []) : [],
fetching: active && search.isFetching,
};
}
// Updating an issue (drag/drop move, or an inline field edit). When `projectKey` is
// given the project detail is patched optimistically so the change shows before the
// request resolves, then reconciled on settle. Issue detail, comments and
// activity are invalidated too, since an edit produces new activity events.
export function useUpdateIssue(projectKey: string | null) {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, patch }: { id: number; patch: IssuePatch }) => updateIssue(id, patch),
onMutate: async ({ id, patch }) => {
if (!projectKey) return {};
const key = qk.boardIssues(projectKey);
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<BoardIssues>(key);
if (prev) {
qc.setQueryData<BoardIssues>(key, {
...prev,
issues: prev.issues.map((t) => (t.id === id ? ({ ...t, ...patch } as BoardIssue) : t)),
});
}
return { prev, key };
},
onError: (_err, _vars, ctx) => {
if (ctx?.prev && ctx.key) qc.setQueryData(ctx.key, ctx.prev);
},
onSettled: (_data, _err, { id }) => {
if (projectKey) void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
void qc.invalidateQueries({ queryKey: qk.issue(id) });
void qc.invalidateQueries({ queryKey: qk.feed(id) });
invalidateGroupings(qc);
},
});
}
// An issue write changes its initiative's progress/health and activity, and the
// initiatives list shows that progress. The same holds for the cycle it is planned
// into. The mutations do not know either id, so they invalidate by prefix; only
// active queries refetch.
function invalidateGroupings(qc: ReturnType<typeof useQueryClient>) {
void qc.invalidateQueries({ queryKey: qk.anyInitiative });
void qc.invalidateQueries({ queryKey: qk.anyInitiativeFeed });
void qc.invalidateQueries({ queryKey: qk.anyInitiatives });
void qc.invalidateQueries({ queryKey: qk.anyCycle });
void qc.invalidateQueries({ queryKey: qk.anyCycles });
}
interface IssueMove {
id: number;
target: { id: number; ref: string };
columnId?: number;
}
// The issue and its subtasks leave one board and join another, so both are refetched.
export function useMoveIssue(projectKey: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, target, columnId }: IssueMove) => moveIssue(id, target.id, columnId),
onSuccess: (_data, { id, target }) => {
void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
void qc.invalidateQueries({ queryKey: qk.boardIssues(target.ref) });
void qc.invalidateQueries({ queryKey: qk.issue(id) });
void qc.invalidateQueries({ queryKey: qk.feed(id) });
invalidateGroupings(qc);
},
});
}
// Deletes an issue. Drops it from the project detail immediately and discards its
// per-issue caches, then refetches the project to reconcile.
export function useDeleteIssue(projectKey: string | null) {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, subtasks }: IssueRemoval) => deleteIssue(id, subtasks),
onSuccess: async (_data, { id }) => {
if (projectKey) {
// Cancel any project fetch already in flight before removing the issue
// from the cache. Such a fetch was issued before the delete (e.g. an
// earlier edit's onSettled refetch) and still lists the deleted issue;
// if it resolved after this removal it would re-add the issue until the
// next refetch. Cancelling discards it so the optimistic removal sticks.
await qc.cancelQueries({ queryKey: qk.boardIssues(projectKey) });
qc.setQueryData<BoardIssues>(qk.boardIssues(projectKey), (prev) =>
prev ? { ...prev, issues: prev.issues.filter((t) => t.id !== id) } : prev,
);
void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
}
qc.removeQueries({ queryKey: qk.issue(id) });
qc.removeQueries({ queryKey: qk.feed(id) });
qc.removeQueries({ queryKey: qk.attachments(id) });
invalidateGroupings(qc);
},
});
}
// Archives an issue. Like delete, it leaves the board immediately (dropped from the
// project detail), but the row is kept: the archived-issues list and the issue's own
// caches are invalidated so a reopened detail shows the archived state.
export function useArchiveIssue(projectKey: string | null) {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, subtasks }: IssueRemoval) => archiveIssue(id, subtasks),
onSuccess: async (_data, { id }) => {
if (projectKey) {
await qc.cancelQueries({ queryKey: qk.boardIssues(projectKey) });
qc.setQueryData<BoardIssues>(qk.boardIssues(projectKey), (prev) =>
prev ? { ...prev, issues: prev.issues.filter((t) => t.id !== id) } : prev,
);
void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
void qc.invalidateQueries({ queryKey: qk.archivedIssues(projectKey) });
}
void qc.invalidateQueries({ queryKey: qk.issue(id) });
void qc.invalidateQueries({ queryKey: qk.feed(id) });
invalidateGroupings(qc);
},
});
}
// Restores an archived issue back onto the board. Invalidates the board (it
// reappears), the archived list (it leaves), and the issue's caches.
export function useRestoreIssue(projectKey: string | null) {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: number) => restoreIssue(id),
onSuccess: (_data, id) => {
if (projectKey) {
void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
void qc.invalidateQueries({ queryKey: qk.archivedIssues(projectKey) });
}
void qc.invalidateQueries({ queryKey: qk.issue(id) });
void qc.invalidateQueries({ queryKey: qk.feed(id) });
invalidateGroupings(qc);
},
});
}
// The issue's field values with one field's entry replaced by what is being sent.
function patchFieldValues(
entries: IssueFieldValueEntry[],
fieldId: number,
input: IssueFieldValueInput,
): IssueFieldValueEntry[] {
const entry: IssueFieldValueEntry = {
fieldId,
value: input.value ?? null,
valueEnd: input.valueEnd ?? null,
optionIds: input.optionIds ?? [],
};
const rest = entries.filter((e) => e.fieldId !== fieldId);
return [...rest, entry];
}
// Setting a custom field value. The project detail is patched optimistically (a
// Calendar placed by a date custom field moves the card on drop, before the
// request resolves), then invalidated on settle together with the issue and its
// activity feed.
export function useSetFieldValue(projectKey: string | null) {
const qc = useQueryClient();
return useMutation({
mutationFn: ({
issueId,
fieldId,
value,
}: {
issueId: number;
fieldId: number;
value: IssueFieldValueInput;
}) => setFieldValue(issueId, fieldId, value),
onMutate: async ({ issueId, fieldId, value }) => {
if (!projectKey) return {};
const key = qk.boardIssues(projectKey);
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<BoardIssues>(key);
if (prev) {
qc.setQueryData<BoardIssues>(key, {
...prev,
issues: prev.issues.map((i) =>
i.id === issueId
? { ...i, fieldValues: patchFieldValues(i.fieldValues, fieldId, value) }
: i,
),
});
}
return { prev, key };
},
onError: (_err, _vars, ctx) => {
if (ctx?.prev && ctx.key) qc.setQueryData(ctx.key, ctx.prev);
},
onSettled: (_data, _err, { issueId }) => {
void qc.invalidateQueries({ queryKey: qk.issue(issueId) });
void qc.invalidateQueries({ queryKey: qk.feed(issueId) });
if (projectKey) void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
},
});
}
// --- Bulk actions (board multi-select) -------------------------------------------
// One request changes many issues. Each optimistically patches the project cache
// the same way its single-issue counterpart does, then invalidates the board and
// initiatives on settle. The project detail is patched by id set so the board
// reflects the change before the request resolves.
export function useBulkUpdateIssues(projectKey: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ ids, patch }: { ids: number[]; patch: BulkIssuePatch }) =>
bulkUpdateIssues(projectKey, ids, patch),
onMutate: async ({ ids, patch }) => {
const key = qk.boardIssues(projectKey);
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<BoardIssues>(key);
if (prev) {
const idSet = new Set(ids);
qc.setQueryData<BoardIssues>(key, {
...prev,
issues: prev.issues.map((t) =>
idSet.has(t.id) ? ({ ...t, ...patch } as BoardIssue) : t,
),
});
}
return { prev, key };
},
onError: (_err, _vars, ctx) => {
if (ctx?.prev && ctx.key) qc.setQueryData(ctx.key, ctx.prev);
},
onSettled: () => {
void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
invalidateGroupings(qc);
},
});
}
export function useBulkAddLabels(projectKey: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ ids, add }: { ids: number[]; add: number[] }) =>
bulkAddLabels(projectKey, ids, add),
onMutate: async ({ ids, add }) => {
const key = qk.boardIssues(projectKey);
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<BoardIssues>(key);
if (prev) {
const idSet = new Set(ids);
qc.setQueryData<BoardIssues>(key, {
...prev,
issues: prev.issues.map((t) =>
idSet.has(t.id) ? { ...t, labelIds: [...new Set([...t.labelIds, ...add])] } : t,
),
});
}
return { prev, key };
},
onError: (_err, _vars, ctx) => {
if (ctx?.prev && ctx.key) qc.setQueryData(ctx.key, ctx.prev);
},
onSettled: () => {
void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
invalidateGroupings(qc);
},
});
}
// Archive and delete both drop the issues from the board immediately, then
// reconcile. A project fetch already in flight is cancelled first so it cannot
// re-add the removed issues (see the single-issue delete for the same reasoning).
function useBulkRemoval(
projectKey: string,
run: (ids: number[], subtasks?: SubtaskDisposition) => Promise<unknown>,
) {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ ids, subtasks }: BulkRemoval) => run(ids, subtasks),
onSuccess: async (_data, { ids }) => {
const idSet = new Set(ids);
await qc.cancelQueries({ queryKey: qk.boardIssues(projectKey) });
qc.setQueryData<BoardIssues>(qk.boardIssues(projectKey), (prev) =>
prev ? { ...prev, issues: prev.issues.filter((t) => !idSet.has(t.id)) } : prev,
);
void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
void qc.invalidateQueries({ queryKey: qk.archivedIssues(projectKey) });
for (const id of ids) {
qc.removeQueries({ queryKey: qk.issue(id) });
qc.removeQueries({ queryKey: qk.feed(id) });
}
invalidateGroupings(qc);
},
});
}
export function useBulkArchiveIssues(projectKey: string) {
return useBulkRemoval(projectKey, (ids, subtasks) =>
bulkArchiveIssues(projectKey, ids, subtasks),
);
}
export function useBulkDeleteIssues(projectKey: string) {
return useBulkRemoval(projectKey, (ids, subtasks) => bulkDeleteIssues(projectKey, ids, subtasks));
}
export function useCreateIssue() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ projectKey, input }: { projectKey: string; input: NewIssueInput }) =>
createIssue(projectKey, input),
onSuccess: (_data, { projectKey }) => {
void qc.invalidateQueries({ queryKey: qk.boardIssues(projectKey) });
invalidateGroupings(qc);
},
});
}
export function useIssueAgentRunsQuery(issueId: number, enabled: boolean) {
return useInfiniteQuery({
queryKey: qk.issueAgentRuns(issueId),
queryFn: ({ pageParam }) => listIssueAgentRuns(issueId, pageParam),
initialPageParam: undefined as number | undefined,
getNextPageParam: (last) => last.nextCursor ?? undefined,
enabled,
});
}
export function useIssueAgentRunTraceQuery(issueId: number, runId: number, traceId?: string) {
return useQuery({
queryKey: qk.issueAgentRunTrace(issueId, runId, traceId),
queryFn: () => getIssueAgentRunTrace(issueId, runId, traceId),
});
}