From 42a8c0baa09250982bcbdbb0b3305d06ffbf050f Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:32:23 +0100 Subject: [PATCH 1/8] feat(issues): add Jira Cloud as a standalone issue tracker Connect Jira Cloud with a site, account email and API token, bind a project to a Jira project, and its issues list beside the git host's. Reads, comments, edits, labels, one assignee and workflow transitions work through Jira's REST API; Jira links open in the app. Co-Authored-By: Claude Opus 5.5 --- .../components/IssueTrackerSection.tsx | 104 +++- apps/server/package.json | 1 + apps/server/src/issue/IssueTrackerRegistry.ts | 3 +- apps/web/src/components/Icons.tsx | 17 + .../components/issue/issuePresentation.tsx | 3 +- .../settings/IssueTrackerSettings.tsx | 88 ++- apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + docs/user/source-control.md | 7 +- packages/client-runtime/package.json | 1 + .../client-runtime/src/issueLinks.test.ts | 33 ++ packages/client-runtime/src/issueLinks.ts | 20 +- .../client-runtime/src/state/issueTrackers.ts | 14 + packages/contracts/src/issue.ts | 13 + packages/issue-tracker-jira/package.json | 33 ++ .../issue-tracker-jira/src/server/JiraApi.ts | 540 +++++++++++++++++ .../src/server/JiraIssueTracker.test.ts | 541 ++++++++++++++++++ .../src/server/JiraIssueTracker.ts | 498 ++++++++++++++++ .../issue-tracker-jira/src/server/driver.ts | 12 + .../src/server/jiraAdf.test.ts | 119 ++++ .../issue-tracker-jira/src/server/jiraAdf.ts | 350 +++++++++++ .../issue-tracker-jira/src/shared/issueUrl.ts | 19 + packages/issue-tracker-jira/tsconfig.json | 7 + pnpm-lock.yaml | 40 ++ scripts/release-smoke.ts | 1 + 33 files changed, 2431 insertions(+), 43 deletions(-) create mode 100644 packages/issue-tracker-jira/package.json create mode 100644 packages/issue-tracker-jira/src/server/JiraApi.ts create mode 100644 packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts create mode 100644 packages/issue-tracker-jira/src/server/JiraIssueTracker.ts create mode 100644 packages/issue-tracker-jira/src/server/driver.ts create mode 100644 packages/issue-tracker-jira/src/server/jiraAdf.test.ts create mode 100644 packages/issue-tracker-jira/src/server/jiraAdf.ts create mode 100644 packages/issue-tracker-jira/src/shared/issueUrl.ts create mode 100644 packages/issue-tracker-jira/tsconfig.json diff --git a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx index 43d5af0363558..e2059ddff96b0 100644 --- a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx +++ b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx @@ -1,4 +1,7 @@ -import { issueTrackerSummary } from "@t3tools/client-runtime/state/issue-trackers"; +import { + issueTrackerFieldsToken, + issueTrackerSummary, +} from "@t3tools/client-runtime/state/issue-trackers"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, @@ -23,6 +26,7 @@ import { useProjects } from "../../../state/entities"; import { issueTrackerEnvironment } from "../../../state/issueTrackers"; import { useEnvironmentQuery } from "../../../state/query"; import { useAtomCommand } from "../../../state/use-atom-command"; +import { ConnectionFormField } from "../../connection/ConnectionFormField"; import type { SettingsTarget } from "../settings-environment-filter"; import { SettingsProviderRow } from "./SettingsProviderRow"; import { SettingsRow } from "./SettingsRow"; @@ -33,9 +37,25 @@ const ThemedSvg = withUniwind(Svg); const ICON_SIZE = Platform.OS === "android" ? 20 : 18; /** Art per tracker kind; the server supplies everything else about a tracker. */ -const TRACKER_MARKS: Partial> = { - linear: - "M1.225 61.523c-.222-.949.908-1.546 1.597-.857l36.512 36.512c.69.69.092 1.82-.857 1.597C20.15 94.612 5.388 79.85 1.225 61.523ZM.002 46.889a.99.99 0 0 0 .29.76l52.062 52.061a.99.99 0 0 0 .76.29c2.765-.169 5.47-.559 8.1-1.152.75-.169 1.014-1.084.47-1.63L2.784 38.32c-.545-.545-1.46-.28-1.63.47A50.229 50.229 0 0 0 .002 46.89ZM4.472 29.34a.99.99 0 0 0 .208 1.104l64.878 64.877a.99.99 0 0 0 1.104.208 50.293 50.293 0 0 0 5.807-3.132.99.99 0 0 0 .154-1.53L9.135 23.38a.99.99 0 0 0-1.53.154 50.29 50.29 0 0 0-3.132 5.807ZM12.293 18.229c-.309-.309-.334-.803-.045-1.13C21.376 6.626 34.637 0 49.45 0 76.869 0 99.1 22.231 99.1 49.65c0 14.813-6.626 28.074-17.099 37.202-.327.29-.821.264-1.13-.045L12.293 18.23Z", +const TRACKER_MARKS: Partial< + Record +> = { + // Tabler's `brand-jira` mark (MIT). + jira: { + viewBox: "0 0 24 24", + stroke: true, + paths: [ + "M20 4h-9v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5a1 1 0 0 1 1 1v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5v-9", + "M15 8h-8v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5a1 1 0 0 1 1 1v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5v-8a1 1 0 0 0 -1 -1", + "M11 12h-8v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5a1 1 0 0 1 1 1v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5v-8a1 1 0 0 0 -1 -1", + ], + }, + linear: { + viewBox: "0 0 100 100", + paths: [ + "M1.225 61.523c-.222-.949.908-1.546 1.597-.857l36.512 36.512c.69.69.092 1.82-.857 1.597C20.15 94.612 5.388 79.85 1.225 61.523ZM.002 46.889a.99.99 0 0 0 .29.76l52.062 52.061a.99.99 0 0 0 .76.29c2.765-.169 5.47-.559 8.1-1.152.75-.169 1.014-1.084.47-1.63L2.784 38.32c-.545-.545-1.46-.28-1.63.47A50.229 50.229 0 0 0 .002 46.89ZM4.472 29.34a.99.99 0 0 0 .208 1.104l64.878 64.877a.99.99 0 0 0 1.104.208 50.293 50.293 0 0 0 5.807-3.132.99.99 0 0 0 .154-1.53L9.135 23.38a.99.99 0 0 0-1.53.154 50.29 50.29 0 0 0-3.132 5.807ZM12.293 18.229c-.309-.309-.334-.803-.045-1.13C21.376 6.626 34.637 0 49.45 0 76.869 0 99.1 22.231 99.1 49.65c0 14.813-6.626 28.074-17.099 37.202-.327.29-.821.264-1.13-.045L12.293 18.23Z", + ], + }, }; /** @@ -112,10 +132,24 @@ export function IssueTrackerMark(props: { readonly tracker: string }) { - + {mark.paths.map((d) => + mark.stroke ? ( + + ) : ( + + ), + )} ) : ( @@ -131,7 +165,7 @@ export function IssueTrackerCredentialForm(props: { const gt = useGT(); const { environmentId, tracker } = props; const connect = useAtomCommand(issueTrackerEnvironment.connect, { reportFailure: false }); - const [draft, setDraft] = useState(""); + const [drafts, setDrafts] = useState>>({}); const [busy, setBusy] = useState(false); const [failure, setFailure] = useState(null); const submit = async (token: string | null) => { @@ -140,7 +174,7 @@ export function IssueTrackerCredentialForm(props: { const result = await connect({ environmentId, input: { tracker: tracker.tracker, token } }); setBusy(false); if (!AsyncResult.isFailure(result)) { - setDraft(""); + setDrafts({}); return; } const error = squashAtomCommandFailure(result); @@ -148,22 +182,44 @@ export function IssueTrackerCredentialForm(props: { }; const helpUrl = tracker.credential.helpUrl; const locked = props.disabled || busy; + // A single-part credential is the one secret field, keyed by nothing. + const fields = tracker.credential.fields ?? [ + { key: "", label: tracker.credential.label, secret: true }, + ]; + const token = tracker.credential.fields + ? issueTrackerFieldsToken(tracker.credential.fields, drafts) + : drafts[""]?.trim() || null; + const send = () => { + if (token !== null) void submit(token); + }; return ( - { - if (value.trim()) void submit(value.trim()); - }} - editable={!locked} - /> + {fields.map((field) => + field.secret ? ( + setDrafts({ ...drafts, [field.key]: value })} + onSubmitEditing={send} + editable={!locked} + /> + ) : ( + setDrafts({ ...drafts, [field.key]: value })} + onSubmitEditing={send} + editable={!locked} + /> + ), + )} {failure ? ( {failure} @@ -196,8 +252,8 @@ export function IssueTrackerCredentialForm(props: { tone="primary" size="compact" loading={busy} - disabled={locked || !draft.trim()} - onPress={() => void submit(draft.trim())} + disabled={locked || token === null} + onPress={send} /> diff --git a/apps/server/package.json b/apps/server/package.json index bea918f407870..91b9c9e2e8abc 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -43,6 +43,7 @@ "@ff-labs/fff-node": "0.11.0", "@muse-code/sdk": "1.4.6", "@napi-rs/keyring": "^1.3.0", + "@t3tools/issue-tracker-jira": "workspace:*", "@t3tools/issue-tracker-linear": "workspace:*", "@t3tools/provider-acp": "workspace:*", "@t3tools/provider-acp-registry": "workspace:*", diff --git a/apps/server/src/issue/IssueTrackerRegistry.ts b/apps/server/src/issue/IssueTrackerRegistry.ts index 6f2343e990479..04265c6989d2f 100644 --- a/apps/server/src/issue/IssueTrackerRegistry.ts +++ b/apps/server/src/issue/IssueTrackerRegistry.ts @@ -2,6 +2,7 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import type { IssueTrackerKind } from "@t3tools/contracts"; +import * as JiraDriver from "@t3tools/issue-tracker-jira/server/driver"; import * as LinearDriver from "@t3tools/issue-tracker-linear/server/driver"; import { isStandaloneIssueTracker, @@ -36,7 +37,7 @@ export function fromTrackers( } /** Trackers that are not a git host's own. Each signs requests with a credential from Settings. */ -const STANDALONE_TRACKERS = [LinearDriver.make]; +const STANDALONE_TRACKERS = [LinearDriver.make, JiraDriver.make]; const make = Effect.gen(function* () { const drivers = yield* BuiltInDrivers.SourceControlDrivers; diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx index 080618e5c66bd..4c24d2cb16c4e 100644 --- a/apps/web/src/components/Icons.tsx +++ b/apps/web/src/components/Icons.tsx @@ -131,6 +131,23 @@ export const LinearIcon: Icon = (props) => ( ); +/** Tabler's `brand-jira` mark (MIT). */ +export const JiraIcon: Icon = (props) => ( + + + + + +); + export const CursorIcon: Icon = ({ className, ...props }) => ( > = { + jira: { providerName: "Jira", Icon: JiraIcon }, linear: { providerName: "Linear", Icon: LinearIcon }, }; diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx index a397a84439f7a..2d5c9e6513007 100644 --- a/apps/web/src/components/settings/IssueTrackerSettings.tsx +++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx @@ -1,5 +1,8 @@ import { useAtomValue } from "@effect/atom-react"; -import { issueTrackerSummary } from "@t3tools/client-runtime/state/issue-trackers"; +import { + issueTrackerFieldsToken, + issueTrackerSummary, +} from "@t3tools/client-runtime/state/issue-trackers"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { T, useGT, useMessages } from "gt-react"; import { ChevronDownIcon, ExternalLinkIcon, XIcon } from "lucide-react"; @@ -15,12 +18,13 @@ import { useEnvironmentQuery } from "../../state/query"; import { issueTrackerEnvironment } from "../../state/issueTrackers"; import { useProjects } from "../../state/entities"; import { useAtomCommand } from "../../state/use-atom-command"; -import { LinearIcon } from "../Icons"; +import { JiraIcon, LinearIcon } from "../Icons"; import { cn } from "~/lib/utils"; import { Badge } from "../ui/badge"; import { Button, InlineButton } from "../ui/button"; import { Collapsible, CollapsibleContent } from "../ui/collapsible"; +import { Input } from "../ui/input"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Skeleton } from "../ui/skeleton"; import { SecretInput } from "./SecretInput"; @@ -31,6 +35,7 @@ type TrackerIcon = ElementType<{ className?: string }>; /** Web art per tracker kind; the server supplies everything else about a tracker. */ const TRACKER_ICONS: Partial> = { + jira: JiraIcon, linear: LinearIcon, }; @@ -197,16 +202,25 @@ function TrackerRow({ } control={
- { - if (next.trim()) void submit(next.trim()); - }} - /> + {tracker.credential.fields ? ( + void submit(token)} + /> + ) : ( + { + if (next.trim()) void submit(next.trim()); + }} + /> + )} {tracker.connected ? ( + + ); +} + /** One picker per project of this environment: which of the tracker's scopes it reads, if any. */ function ProjectBindings({ environmentId, diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 46df7424ab0f2..40731646e0a5f 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -8440,6 +8440,7 @@ "a2d95d39d3398bda": "Anmeldedaten abgelehnt", "9eae463720500113": "Auf dem Server gespeichert.", "b6e27ab2537ef874": "Erstellen", + "b7088cd1c566d9c9": "Ersetzen", "e63611bd62fad8d8": "Nicht zugeordnet", "13ef526271b0f5d4": "Alle Bedingungen löschen", "d1938a629f039515": "Bedingung entfernen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e051..459fed7c3235c 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -8448,6 +8448,7 @@ "a2d95d39d3398bda": "Credential rejected", "9eae463720500113": "Stored on the server.", "b6e27ab2537ef874": "Create one", + "b7088cd1c566d9c9": "Replace", "e63611bd62fad8d8": "Not bound", "13ef526271b0f5d4": "Clear all conditions", "d1938a629f039515": "Remove condition", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 797888016bd4a..26aa785f1e89e 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -8438,6 +8438,7 @@ "a2d95d39d3398bda": "Credencial rechazada", "9eae463720500113": "Guardado en el servidor.", "b6e27ab2537ef874": "Crear uno", + "b7088cd1c566d9c9": "Reemplazar", "e63611bd62fad8d8": "Sin vincular", "13ef526271b0f5d4": "Borrar todas las condiciones", "d1938a629f039515": "Quitar condición", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e06cde54989bd..6993fdac41300 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -8439,6 +8439,7 @@ "a2d95d39d3398bda": "Identifiant refusé", "9eae463720500113": "Stocké sur le serveur.", "b6e27ab2537ef874": "En créer un", + "b7088cd1c566d9c9": "Remplacer", "e63611bd62fad8d8": "Non lié", "13ef526271b0f5d4": "Effacer toutes les conditions", "d1938a629f039515": "Supprimer la condition", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 4473bff3ddef1..57b444aa1cdfb 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -8396,6 +8396,7 @@ "a2d95d39d3398bda": "資格情報が拒否されました", "9eae463720500113": "サーバーに保存されています。", "b6e27ab2537ef874": "作成する", + "b7088cd1c566d9c9": "置き換え", "e63611bd62fad8d8": "未バインド", "13ef526271b0f5d4": "すべての条件をクリア", "d1938a629f039515": "条件を削除", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 68f0b20794362..9c97ee31a03e7 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -8399,6 +8399,7 @@ "a2d95d39d3398bda": "자격 증명 거부됨", "9eae463720500113": "서버에 저장됩니다.", "b6e27ab2537ef874": "새로 만들기", + "b7088cd1c566d9c9": "교체", "e63611bd62fad8d8": "바인딩되지 않음", "13ef526271b0f5d4": "모든 조건 지우기", "d1938a629f039515": "조건 제거", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5a18a359ecb2a..6e36dc2b86ec7 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -8438,6 +8438,7 @@ "a2d95d39d3398bda": "Credencial recusada", "9eae463720500113": "Armazenado no servidor.", "b6e27ab2537ef874": "Criar um", + "b7088cd1c566d9c9": "Substituir", "e63611bd62fad8d8": "Não vinculado", "13ef526271b0f5d4": "Limpar todas as condições", "d1938a629f039515": "Remover condição", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6c7fa00a15455..8e9cf1cd865f8 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -8440,6 +8440,7 @@ "a2d95d39d3398bda": "Учётные данные отклонены", "9eae463720500113": "Хранится на сервере.", "b6e27ab2537ef874": "Создать", + "b7088cd1c566d9c9": "Заменить", "e63611bd62fad8d8": "Не привязано", "13ef526271b0f5d4": "Очистить все условия", "d1938a629f039515": "Удалить условие", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d02de62557d73..1fb338d6f3a22 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -8446,6 +8446,7 @@ "a2d95d39d3398bda": "Autentiseringsuppgiften avvisades", "9eae463720500113": "Lagras på servern.", "b6e27ab2537ef874": "Skapa en", + "b7088cd1c566d9c9": "Ersätt", "e63611bd62fad8d8": "Inte kopplad", "13ef526271b0f5d4": "Rensa alla villkor", "d1938a629f039515": "Ta bort villkor", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index acf5ce3045376..5050c95e7360b 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -8456,6 +8456,7 @@ "a2d95d39d3398bda": "凭据被拒绝", "9eae463720500113": "存储在服务器上。", "b6e27ab2537ef874": "创建一个", + "b7088cd1c566d9c9": "替换", "e63611bd62fad8d8": "未绑定", "13ef526271b0f5d4": "清除所有条件", "d1938a629f039515": "移除条件", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index ce57f727ff6ae..f0f87f085fbe0 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -374,8 +374,11 @@ itself where it can search. Press **Load more** at the end of a group to read fu The **Views** menu saves and restores a search, filter, and sort setup, as it does for pull requests. -To list a Linear team's issues beside a project's, connect Linear with an API key under -Settings → Source control & issues, then choose the team for that project there. +To list a Linear team's or a Jira Cloud project's issues beside a project's, connect the tracker +under Settings → Source control & issues, then choose the team or project for that project there. +Linear takes an API key. Jira takes your site (`example.atlassian.net`), your account email and an +[API token](https://id.atlassian.com/manage-profile/security/api-tokens). Jira issues move between +statuses through your workflow's transitions; Jira reactions and linked pull requests are not shown. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index c09deef7e4b39..3399f304a67f4 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -635,6 +635,7 @@ "dependencies": { "@pierre/diffs": "catalog:", "@t3tools/contracts": "workspace:*", + "@t3tools/issue-tracker-jira": "workspace:*", "@t3tools/issue-tracker-linear": "workspace:*", "@t3tools/provider-acp-registry": "workspace:*", "@t3tools/provider-core": "workspace:*", diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index fd206063bfcff..89febe02f0c1f 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -112,6 +112,39 @@ describe("resolveIssueLinkTarget", () => { ).toBeNull(); }); + it("reads a Jira link only on the connected site", () => { + const trackers = { + trackers: [ + { + tracker: IssueTrackerKind.make("jira"), + displayName: "Jira", + host: "atlassian.net", + scopeNoun: "project", + credential: { label: "API token", helpUrl: null }, + connected: true, + account: "Julius", + detail: null, + workspace: "acme", + scopes: [], + }, + ], + bindings: { + [ProjectId.make("p1")]: { tracker: IssueTrackerKind.make("jira"), scope: "ENG" }, + }, + }; + const resolve = (url: string) => resolveIssueLinkTarget({ url, projects, trackers }); + expect(resolve("https://acme.atlassian.net/browse/ENG-4")?.ref).toEqual({ + projectId: "p1", + tracker: "jira", + host: "atlassian.net", + scope: "ENG", + key: "ENG-4", + }); + // Project keys repeat across sites; only the connected one's links are its issues. + expect(resolve("https://othercorp.atlassian.net/browse/ENG-4")).toBeNull(); + expect(resolve("https://acme.atlassian.net.evil.example/browse/ENG-4")).toBeNull(); + }); + it.each([ "https://github.com.evil.example/acme/web/issues/7", "https://github.com/acme/web/pull/7", diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 4e1d4ec15a543..d9c1682526463 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -1,4 +1,9 @@ import type { IssueRef, IssueTrackerConnectionList } from "@t3tools/contracts"; +import { + JIRA_HOST, + JIRA_KIND, + parseJiraIssueUrl, +} from "@t3tools/issue-tracker-jira/shared/issueUrl"; import { LINEAR_HOST, LINEAR_KIND, @@ -53,10 +58,19 @@ function parseIssueLink( return null; } +const STANDALONE_TRACKERS = [ + { tracker: LINEAR_KIND, parse: parseLinearIssueUrl }, + { tracker: JIRA_KIND, parse: parseJiraIssueUrl }, +]; + function parseStandaloneIssueLink(url: string) { try { - const link = parseLinearIssueUrl(new URL(url)); - return link === null ? null : { tracker: LINEAR_KIND, link }; + const parsed = new URL(url); + for (const { tracker, parse } of STANDALONE_TRACKERS) { + const link = parse(parsed); + if (link !== null) return { tracker, link }; + } + return null; } catch { return null; } @@ -69,7 +83,7 @@ export function isStandaloneIssueLink(url: string): boolean { /** A cheap pre-check, so text without such a link never asks for the bindings. */ export function mayContainStandaloneIssueLink(text: string): boolean { - return text.includes(`${LINEAR_HOST}/`); + return text.includes(`${LINEAR_HOST}/`) || text.includes(`.${JIRA_HOST}/`); } /** diff --git a/packages/client-runtime/src/state/issueTrackers.ts b/packages/client-runtime/src/state/issueTrackers.ts index 045f283f310ee..5bf76eec7a621 100644 --- a/packages/client-runtime/src/state/issueTrackers.ts +++ b/packages/client-runtime/src/state/issueTrackers.ts @@ -59,6 +59,20 @@ export function createIssueTrackerEnvironmentAtoms( }; } +/** + * A credential of several parts as the one token a connect sends: a JSON object of every part, + * or null until each is filled, so a half-entered credential is never sent. + */ +export function issueTrackerFieldsToken( + fields: NonNullable, + drafts: Readonly>, +): string | null { + const values = fields.map((field) => [field.key, drafts[field.key]?.trim() ?? ""] as const); + return values.every(([, value]) => value !== "") + ? JSON.stringify(Object.fromEntries(values)) + : null; +} + // Tracker packages name their credential and scope in English, so a sentence is translated only // when it matches a known tracker's whole sentence; any other tracker keeps the English one. function knownTrackerSentence( diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 07f2eab6e6a42..d94017a5604cb 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -562,6 +562,19 @@ export const StandaloneIssueTrackerDescriptor = Schema.Struct({ label: TrimmedNonEmptyString, /** Where to mint one, or null when the tracker has no stable page for it. */ helpUrl: Schema.NullOr(TrimmedNonEmptyString), + /** + * A credential of several parts, such as a site, an email and a token. Clients ask for each + * and send them as one JSON object keyed by `key` in place of a single token. + */ + fields: Schema.optional( + Schema.Array( + Schema.Struct({ + key: TrimmedNonEmptyString, + label: TrimmedNonEmptyString, + secret: Schema.Boolean, + }), + ), + ), }), }); export type StandaloneIssueTrackerDescriptor = typeof StandaloneIssueTrackerDescriptor.Type; diff --git a/packages/issue-tracker-jira/package.json b/packages/issue-tracker-jira/package.json new file mode 100644 index 0000000000000..f775c0dcb5b56 --- /dev/null +++ b/packages/issue-tracker-jira/package.json @@ -0,0 +1,33 @@ +{ + "name": "@t3tools/issue-tracker-jira", + "private": true, + "type": "module", + "exports": { + "./shared/issueUrl": { + "types": "./src/shared/issueUrl.ts", + "import": "./src/shared/issueUrl.ts" + }, + "./server/driver": { + "types": "./src/server/driver.ts", + "import": "./src/server/driver.ts" + } + }, + "scripts": { + "typecheck": "effect-tsgo tsrs --noEmit", + "test": "vp test run --config ../../vite.config.ts --dir ." + }, + "dependencies": { + "@t3tools/contracts": "workspace:*", + "@t3tools/source-control-core": "workspace:*", + "effect": "catalog:", + "mdast-util-from-markdown": "2.0.3", + "mdast-util-gfm": "3.1.0", + "micromark-extension-gfm": "3.0.0" + }, + "devDependencies": { + "@effect/vitest": "catalog:", + "@types/mdast": "^4.0.4", + "@types/node": "catalog:", + "vite-plus": "catalog:" + } +} diff --git a/packages/issue-tracker-jira/src/server/JiraApi.ts b/packages/issue-tracker-jira/src/server/JiraApi.ts new file mode 100644 index 0000000000000..bc718d6903460 --- /dev/null +++ b/packages/issue-tracker-jira/src/server/JiraApi.ts @@ -0,0 +1,540 @@ +/** + * Jira Cloud's REST API (v3), signed with the credential saved in Settings: the site, the + * account's email and an API token, stored together as one JSON value. Every call goes to that + * credential's own site, so a stored credential never reaches another one. + */ +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { IssueTrackerError } from "@t3tools/source-control-core/server/IssueTracker"; +import * as IssueTrackerHost from "@t3tools/source-control-core/server/IssueTrackerHost"; +import { retryAtFromHeader } from "@t3tools/source-control-core/server/SourceControlRateLimit"; + +import { JIRA_KIND } from "../shared/issueUrl.ts"; + +export const KIND = JIRA_KIND; +const REQUEST_TIMEOUT = "30 seconds"; + +const Credential = Schema.Struct({ + site: Schema.String, + email: Schema.String, + token: Schema.String, +}); +const decodeCredential = Schema.decodeUnknownOption(Schema.fromJsonString(Credential)); + +export interface JiraCredential { + /** The site's subdomain: `acme` for `acme.atlassian.net`. */ + readonly site: string; + readonly email: string; + readonly token: string; +} + +/** + * The credential as Settings stores it, or null when a field is missing or the site is not a + * Jira Cloud site: the host must never come from anything but `.atlassian.net`. + */ +export function parseJiraCredential(value: string): JiraCredential | null { + const decoded = decodeCredential(value); + if (decoded._tag === "None") return null; + const site = decoded.value.site + .trim() + .toLowerCase() + .replace(/^https:\/\//, "") + .replace(/\/+$/, "") + .replace(/\.atlassian\.net$/, ""); + const email = decoded.value.email.trim(); + const token = decoded.value.token.trim(); + if (!/^[a-z0-9][a-z0-9-]*$/.test(site) || email === "" || token === "") return null; + return { site, email, token }; +} + +export const JiraUser = Schema.Struct({ + accountId: Schema.String, + displayName: Schema.optional(Schema.String), + emailAddress: Schema.optional(Schema.String), + avatarUrls: Schema.optional(Schema.Record(Schema.String, Schema.String)), +}); +export type JiraUser = typeof JiraUser.Type; + +export const JiraStatus = Schema.Struct({ + id: Schema.String, + name: Schema.String, + statusCategory: Schema.Struct({ key: Schema.String }), +}); +export type JiraStatus = typeof JiraStatus.Type; + +/** Jira documents are Atlassian Document Format; `jiraAdf.ts` reads and writes them. */ +const Document = Schema.NullOr(Schema.Unknown); + +const IssueFields = Schema.Struct({ + summary: Schema.String, + status: JiraStatus, + created: Schema.String, + updated: Schema.String, + resolutiondate: Schema.optional(Schema.NullOr(Schema.String)), + creator: Schema.optional(Schema.NullOr(JiraUser)), + reporter: Schema.optional(Schema.NullOr(JiraUser)), + assignee: Schema.optional(Schema.NullOr(JiraUser)), + labels: Schema.optional(Schema.Array(Schema.String)), + project: Schema.Struct({ key: Schema.String }), + description: Schema.optional(Document), +}); + +export const JiraIssue = Schema.Struct({ + id: Schema.String, + key: Schema.String, + fields: IssueFields, +}); +export type JiraIssue = typeof JiraIssue.Type; + +export const JiraComment = Schema.Struct({ + id: Schema.String, + author: Schema.optional(Schema.NullOr(JiraUser)), + body: Document, + created: Schema.String, +}); +export type JiraComment = typeof JiraComment.Type; + +const HistoryItem = Schema.Struct({ + field: Schema.String, + fromString: Schema.optional(Schema.NullOr(Schema.String)), + toString: Schema.optional(Schema.NullOr(Schema.String)), +}); +export const JiraHistory = Schema.Struct({ + id: Schema.String, + author: Schema.optional(Schema.NullOr(JiraUser)), + created: Schema.String, + items: Schema.Array(HistoryItem), +}); +export type JiraHistory = typeof JiraHistory.Type; + +export const JiraTransition = Schema.Struct({ + id: Schema.String, + to: JiraStatus, +}); +export type JiraTransition = typeof JiraTransition.Type; + +export const JiraIssueDetail = Schema.Struct({ + ...JiraIssue.fields, + changelog: Schema.optional(Schema.Struct({ histories: Schema.Array(JiraHistory) })), + transitions: Schema.optional(Schema.Array(JiraTransition)), +}); +export type JiraIssueDetail = typeof JiraIssueDetail.Type; + +const SearchPage = Schema.Struct({ + issues: Schema.Array(JiraIssue), + nextPageToken: Schema.optional(Schema.NullOr(Schema.String)), +}); + +const CommentPage = Schema.Struct({ + startAt: Schema.Number, + total: Schema.Number, + comments: Schema.Array(JiraComment), +}); +export type JiraCommentPage = typeof CommentPage.Type; + +const MAX_PROJECTS = 1_000; +const ProjectPage = Schema.Struct({ + isLast: Schema.optional(Schema.Boolean), + values: Schema.Array( + Schema.Struct({ id: Schema.String, key: Schema.String, name: Schema.String }), + ), +}); + +const IssueTypes = Schema.Struct({ + issueTypes: Schema.Array( + Schema.Struct({ + id: Schema.String, + name: Schema.String, + subtask: Schema.optional(Schema.Boolean), + }), + ), +}); + +const Labels = Schema.Struct({ + values: Schema.Array(Schema.String), + isLast: Schema.optional(Schema.Boolean), +}); + +const Created = Schema.Struct({ key: Schema.String }); + +const SUMMARY_FIELDS = [ + "summary", + "status", + "created", + "updated", + "resolutiondate", + "creator", + "reporter", + "assignee", + "labels", + "project", +]; + +/** What a write sends as a field, already in Jira's own shape. */ +export type JiraFields = Record; + +export class JiraApi extends Context.Service< + JiraApi, + { + /** The stored credential's site, which every issue URL and request is for. */ + readonly site: Effect.Effect; + /** Who a credential is and which projects it reaches. Takes one so it can vet a new one. */ + readonly probe: (credential?: string) => Effect.Effect< + { + readonly site: string; + readonly user: JiraUser; + readonly projects: ReadonlyArray<{ readonly key: string; readonly name: string }>; + }, + IssueTrackerError + >; + readonly myself: Effect.Effect; + readonly search: (input: { + readonly jql: string; + readonly limit: number; + readonly cursor?: string | undefined; + }) => Effect.Effect< + { readonly issues: ReadonlyArray; readonly nextCursor: string | null }, + IssueTrackerError + >; + /** Null when Jira has no such issue, or the credential cannot see it. */ + readonly getIssue: (key: string) => Effect.Effect; + /** Newest first, so the first page is the latest conversation. */ + readonly getComments: (input: { + readonly key: string; + readonly startAt: number; + readonly limit: number; + }) => Effect.Effect; + readonly createIssue: (fields: JiraFields) => Effect.Effect; + readonly updateIssue: ( + key: string, + fields: JiraFields, + ) => Effect.Effect; + readonly addComment: (key: string, body: unknown) => Effect.Effect; + readonly transition: (key: string, id: string) => Effect.Effect; + readonly issueTypes: ( + project: string, + ) => Effect.Effect; + readonly assignableUsers: (input: { + readonly project?: string | undefined; + readonly issueKey?: string | undefined; + readonly query?: string | undefined; + readonly limit: number; + }) => Effect.Effect, IssueTrackerError>; + readonly labels: ( + limit: number, + ) => Effect.Effect< + { readonly values: ReadonlyArray; readonly truncated: boolean }, + IssueTrackerError + >; + } +>()("@t3tools/issue-tracker-jira/server/JiraApi") {} + +const fail = ( + operation: string, + reason: IssueTrackerError["reason"], + detail: string, + extra: { readonly retryAt?: number | undefined; readonly cause?: unknown } = {}, +) => + new IssueTrackerError({ + tracker: KIND, + operation, + reason, + detail, + ...(extra.retryAt === undefined ? {} : { retryAt: extra.retryAt }), + ...(extra.cause === undefined ? {} : { cause: extra.cause }), + }); + +const ErrorBody = Schema.Struct({ + errorMessages: Schema.optional(Schema.Array(Schema.String)), + errors: Schema.optional(Schema.Record(Schema.String, Schema.String)), +}); + +/** Jira writes its refusals for people; the first one is what the user is shown. */ +const refusal = Effect.fn("JiraApi.refusal")(function* ( + operation: string, + response: HttpClientResponse.HttpClientResponse, +) { + const now = yield* Clock.currentTimeMillis; + if (response.status === 429) { + return fail(operation, "rate-limited", "Jira's rate limit was reached.", { + retryAt: retryAtFromHeader(response.headers["retry-after"], now), + }); + } + if (response.status === 401) { + return fail(operation, "unauthenticated", "Jira rejected the email and API token."); + } + const body = yield* HttpClientResponse.schemaBodyJson(ErrorBody)(response).pipe( + Effect.orElseSucceed(() => ({ errorMessages: [], errors: {} })), + ); + const messages = [...(body.errorMessages ?? []), ...Object.values(body.errors ?? {})].filter( + (text): text is string => typeof text === "string", + ); + const message = messages.map((text) => text.trim()).find((text) => text !== ""); + if (response.status === 404) { + return fail(operation, "not-found", message ?? "Jira has no such issue or project."); + } + return fail(operation, "failed", message ?? `Jira returned HTTP ${response.status}.`); +}); + +export const make = Effect.gen(function* () { + const httpClient = yield* HttpClient.HttpClient; + const host = yield* IssueTrackerHost.IssueTrackerHost; + + const credential = (operation: string, given?: string) => + (given === undefined + ? host.credentials + .get(KIND) + .pipe( + Effect.flatMap( + Effect.fromOption(() => + fail(operation, "unauthenticated", "Jira is not connected on this server."), + ), + ), + ) + : Effect.succeed(given) + ).pipe( + Effect.flatMap((value) => { + const parsed = parseJiraCredential(value); + return parsed === null + ? Effect.fail( + fail( + operation, + "unauthenticated", + "Enter a Jira Cloud site, the account's email and an API token.", + ), + ) + : Effect.succeed(parsed); + }), + ); + + const call = Effect.fn("JiraApi.call")(function* < + S extends Schema.Top & { readonly DecodingServices: never }, + >(input: { + readonly operation: string; + readonly method: "GET" | "POST" | "PUT"; + readonly path: string; + readonly params?: Record | undefined; + readonly body?: unknown; + /** Null for a call that answers with no body. */ + readonly schema: S | null; + readonly credential?: string | undefined; + }): Effect.fn.Return { + yield* Effect.annotateCurrentSpan({ "jira.operation": input.operation }); + const { site, email, token } = yield* credential(input.operation, input.credential); + const url = `https://${site}.atlassian.net/rest/api/3${input.path}`; + let request = HttpClientRequest.make(input.method)(url).pipe( + HttpClientRequest.acceptJson, + HttpClientRequest.basicAuth(email, token), + HttpClientRequest.setUrlParams(input.params ?? {}), + ); + if (input.body !== undefined) { + request = yield* HttpClientRequest.bodyJson(request, input.body).pipe( + Effect.mapError((cause) => + fail(input.operation, "failed", "The request could not be encoded.", { cause }), + ), + ); + } + const response = yield* httpClient.execute(request).pipe( + Effect.timeout(REQUEST_TIMEOUT), + Effect.mapError((cause) => + fail(input.operation, "failed", "Jira could not be reached.", { cause }), + ), + ); + if (response.status < 200 || response.status >= 300) { + return yield* Effect.flatMap(refusal(input.operation, response), Effect.fail); + } + if (input.schema === null) return null; + return yield* HttpClientResponse.schemaBodyJson(input.schema)(response).pipe( + Effect.mapError((cause) => + fail(input.operation, "failed", "Jira returned an unexpected body.", { cause }), + ), + ); + }); + + const read = ( + input: Omit>[0], "schema"> & { readonly schema: S }, + ) => call(input) as Effect.Effect; + const write = (input: Omit[0], "schema">) => + call({ ...input, schema: null }).pipe(Effect.asVoid); + + const myself = (operation: string, given?: string) => + read({ operation, method: "GET", path: "/myself", schema: JiraUser, credential: given }); + + const probe: JiraApi["Service"]["probe"] = Effect.fn("JiraApi.probe")(function* (given) { + const { site } = yield* credential("probe", given); + const user = yield* myself("probe", given); + const projects: Array<{ readonly key: string; readonly name: string }> = []; + // shortcut: stops at MAX_PROJECTS, page the picker itself if sites outgrow it. + while (projects.length < MAX_PROJECTS) { + const page = yield* read({ + operation: "probe", + method: "GET", + path: "/project/search", + params: { startAt: String(projects.length), maxResults: "100", orderBy: "key" }, + schema: ProjectPage, + credential: given, + }); + projects.push(...page.values.map(({ key, name }) => ({ key, name }))); + if (page.isLast !== false || page.values.length === 0) break; + } + return { site, user, projects }; + }); + + const getIssue: JiraApi["Service"]["getIssue"] = (key) => + read({ + operation: "getIssue", + method: "GET", + path: `/issue/${encodeURIComponent(key)}`, + params: { + fields: [...SUMMARY_FIELDS, "description"].join(","), + expand: "changelog,transitions", + }, + schema: JiraIssueDetail, + }).pipe( + Effect.map((issue): JiraIssueDetail | null => issue), + Effect.catchIf( + (error) => error.reason === "not-found", + () => Effect.succeed(null), + ), + ); + + const search: JiraApi["Service"]["search"] = Effect.fn("JiraApi.search")(function* (input) { + const page = yield* read({ + operation: "listIssues", + method: "POST", + path: "/search/jql", + body: { + jql: input.jql, + maxResults: input.limit, + fields: SUMMARY_FIELDS, + ...(input.cursor === undefined ? {} : { nextPageToken: input.cursor }), + }, + schema: SearchPage, + }); + return { issues: page.issues, nextCursor: page.nextPageToken ?? null }; + }); + + const getComments: JiraApi["Service"]["getComments"] = Effect.fn("JiraApi.getComments")( + function* (input) { + return yield* read({ + operation: "getComments", + method: "GET", + path: `/issue/${encodeURIComponent(input.key)}/comment`, + params: { + startAt: String(input.startAt), + maxResults: String(input.limit), + orderBy: "-created", + }, + schema: CommentPage, + }); + }, + ); + + const createIssue: JiraApi["Service"]["createIssue"] = Effect.fn("JiraApi.createIssue")( + function* (fields) { + const created = yield* read({ + operation: "createIssue", + method: "POST", + path: "/issue", + body: { fields }, + schema: Created, + }); + return created.key; + }, + ); + + const updateIssue: JiraApi["Service"]["updateIssue"] = Effect.fn("JiraApi.updateIssue")( + function* (key, fields) { + yield* write({ + operation: "updateIssue", + method: "PUT", + path: `/issue/${encodeURIComponent(key)}`, + body: { fields }, + }); + }, + ); + + const addComment: JiraApi["Service"]["addComment"] = Effect.fn("JiraApi.addComment")( + function* (key, body) { + yield* write({ + operation: "addComment", + method: "POST", + path: `/issue/${encodeURIComponent(key)}/comment`, + body: { body }, + }); + }, + ); + + const transition: JiraApi["Service"]["transition"] = Effect.fn("JiraApi.transition")( + function* (key, id) { + yield* write({ + operation: "transition", + method: "POST", + path: `/issue/${encodeURIComponent(key)}/transitions`, + body: { transition: { id } }, + }); + }, + ); + + const issueTypes: JiraApi["Service"]["issueTypes"] = Effect.fn("JiraApi.issueTypes")( + function* (project) { + const types = yield* read({ + operation: "issueTypes", + method: "GET", + path: `/issue/createmeta/${encodeURIComponent(project)}/issuetypes`, + schema: IssueTypes, + }); + return types.issueTypes; + }, + ); + + const assignableUsers: JiraApi["Service"]["assignableUsers"] = Effect.fn( + "JiraApi.assignableUsers", + )(function* (input) { + return yield* read({ + operation: "assignableUsers", + method: "GET", + path: "/user/assignable/search", + params: { + maxResults: String(input.limit), + ...(input.project === undefined ? {} : { project: input.project }), + ...(input.issueKey === undefined ? {} : { issueKey: input.issueKey }), + ...(input.query === undefined ? {} : { query: input.query }), + }, + schema: Schema.Array(JiraUser), + }); + }); + + const labels: JiraApi["Service"]["labels"] = Effect.fn("JiraApi.labels")(function* (limit) { + const page = yield* read({ + operation: "labels", + method: "GET", + path: "/label", + params: { maxResults: String(limit) }, + schema: Labels, + }); + return { values: page.values, truncated: page.isLast === false }; + }); + + return JiraApi.of({ + site: credential("site").pipe(Effect.map(({ site }) => site)), + probe, + myself: myself("myself"), + search, + getIssue, + getComments, + createIssue, + updateIssue, + addComment, + transition, + issueTypes, + assignableUsers, + labels, + }); +}); + +export const layer = Layer.effect(JiraApi, make); diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts new file mode 100644 index 0000000000000..5268626cb517c --- /dev/null +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts @@ -0,0 +1,541 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { HttpClient, HttpClientResponse, UrlParams } from "effect/http"; +import { IssueTrackerKind } from "@t3tools/contracts"; +import type { StandaloneIssueTrackerApi } from "@t3tools/source-control-core/server/IssueTracker"; +import * as IssueTrackerHost from "@t3tools/source-control-core/server/IssueTrackerHost"; + +import * as JiraApi from "./JiraApi.ts"; +import * as JiraIssueTracker from "./JiraIssueTracker.ts"; + +const STORED = JSON.stringify({ site: "acme", email: "julius@acme.test", token: "tok" }); + +const user = (accountId: string, displayName: string) => ({ + accountId, + displayName, + avatarUrls: { "48x48": `https://avatar.test/${accountId}` }, +}); +const JULIUS = user("5b10a2844c20165700ede21g", "Julius"); +const THEO = user("5b10ac8d82e05b22cc7d4ef5", "Theo"); + +const status = (name: string, category: "new" | "indeterminate" | "done") => ({ + id: `st_${name}`, + name, + statusCategory: { key: category }, +}); + +const issue = (key: string, overrides: Record = {}) => ({ + id: `id_${key}`, + key, + fields: { + summary: `Issue ${key}`, + status: status("In Progress", "indeterminate"), + created: "2026-07-01T10:00:00.000+0000", + updated: "2026-07-02T10:00:00.000+0000", + resolutiondate: null, + reporter: JULIUS, + assignee: THEO, + labels: ["bug"], + project: { key: key.split("-")[0] }, + ...overrides, + }, +}); + +const doc = (...content: ReadonlyArray) => ({ type: "doc", version: 1, content }); +const paragraph = (text: string) => ({ type: "paragraph", content: [{ type: "text", text }] }); + +interface Seen { + readonly method: string; + readonly path: string; + readonly params: URLSearchParams; + readonly body: unknown; + readonly authorization: string | undefined; +} + +/** Answers each request by `METHOD /path` under the REST API root, the way Jira Cloud would. */ +function fakeJira( + answers: Record unknown>, + stored: string | null = STORED, +) { + const requests: Seen[] = []; + const http = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + const url = new URL(request.url); + const body = request.body; + const seen: Seen = { + method: request.method, + path: url.pathname.replace("/rest/api/3", ""), + params: new URLSearchParams(UrlParams.toString(request.urlParams)), + body: + body._tag === "Uint8Array" + ? JSON.parse(new TextDecoder().decode(body.body)) + : undefined, + authorization: request.headers.authorization, + }; + expect(url.origin).toBe("https://acme.atlassian.net"); + requests.push(seen); + const answer = answers[`${seen.method} ${seen.path}`]; + const answered = answer?.(seen); + const response = + answered instanceof Response + ? answered + : answer === undefined + ? new Response(JSON.stringify({ errorMessages: [`No answer for ${seen.path}`] }), { + status: 400, + headers: { "content-type": "application/json" }, + }) + : answered === undefined + ? new Response(null, { status: 204 }) + : new Response(JSON.stringify(answered), { + status: 200, + headers: { "content-type": "application/json" }, + }); + return HttpClientResponse.fromWeb(request, response); + }), + ), + ); + const host = Layer.succeed( + IssueTrackerHost.IssueTrackerHost, + IssueTrackerHost.IssueTrackerHost.of({ + credentials: { get: () => Effect.succeed(Option.fromNullishOr(stored)) }, + }), + ); + // Every optional write that Jira supports is implemented; the type says so for the calls below. + const tracker = JiraIssueTracker.make.pipe( + Effect.map((api) => api as Required), + Effect.provide(JiraApi.layer.pipe(Layer.provide(Layer.merge(http, host)))), + ); + return { tracker, requests }; +} + +const target = { cwd: "/w/web", host: "atlassian.net", scope: "ENG" }; + +describe("JiraIssueTracker", () => { + it.effect("parses Jira Cloud issue links with their site and project", () => + Effect.gen(function* () { + const api = yield* fakeJira({}).tracker; + for (const suffix of ["", "/", "?focusedCommentId=10#comment"]) { + expect( + api.parseIssueUrl(new URL(`https://acme.atlassian.net/browse/ENG-12${suffix}`)), + ).toEqual({ + host: "atlassian.net", + workspace: "acme", + scope: "ENG", + key: "ENG-12", + }); + } + for (const url of [ + "http://acme.atlassian.net/browse/ENG-12", + "https://acme.atlassian.net:444/browse/ENG-12", + "https://atlassian.net/browse/ENG-12", + "https://acme.atlassian.net.evil.test/browse/ENG-12", + "https://acme.atlassian.net/browse/eng-12", + "https://acme.atlassian.net/browse/ENG-0", + "https://acme.atlassian.net/browse/ENG-12/extra", + "https://acme.atlassian.net/jira/software/projects/ENG/boards/1", + ]) { + expect(api.parseIssueUrl(new URL(url)), url).toBeNull(); + } + }), + ); + + it.effect("vets a credential before it is stored, against its own site only", () => + Effect.gen(function* () { + const { tracker, requests } = fakeJira( + { + "GET /myself": () => JULIUS, + // A site's projects arrive in pages; every page is read. + "GET /project/search": (seen) => + seen.params.get("startAt") === "0" + ? { isLast: false, values: [{ id: "1", key: "ENG", name: "Engineering" }] } + : { isLast: true, values: [{ id: "2", key: "OPS", name: "Operations" }] }, + }, + null, + ); + const api = yield* tracker; + expect(api.kind).toBe(IssueTrackerKind.make("jira")); + expect(api.standalone).toMatchObject({ host: "atlassian.net", scopeNoun: "project" }); + const probe = yield* api.probeCredential( + JSON.stringify({ + site: "https://ACME.atlassian.net/", + email: " julius@acme.test ", + token: "tok", + }), + ); + expect(probe).toEqual({ + account: "Julius", + workspace: "acme", + scopes: [ + { key: "ENG", name: "Engineering" }, + { key: "OPS", name: "Operations" }, + ], + }); + expect(requests[0]?.authorization).toBe(`Basic ${btoa("julius@acme.test:tok")}`); + // A site that is not a Jira Cloud subdomain is never asked anything. + for (const site of ["evil.test", "acme.atlassian.net.evil.test", "acme/../x"]) { + const refused = yield* Effect.flip( + api.probeCredential(JSON.stringify({ site, email: "a@b.c", token: "t" })), + ); + expect(refused.reason).toBe("unauthenticated"); + } + const notConnected = yield* Effect.flip(api.getViewer({ cwd: "", host: "atlassian.net" })); + expect(notConnected.reason).toBe("unauthenticated"); + expect(requests).toHaveLength(3); + }), + ); + + it.effect("lists a project's issues with JQL built from the filters", () => + Effect.gen(function* () { + const { tracker, requests } = fakeJira({ + "GET /user/assignable/search": () => [THEO], + "POST /search/jql": () => ({ + issues: [ + issue("ENG-2", { + status: status("Done", "done"), + resolutiondate: "2026-07-03T10:00:00.000+0000", + }), + issue("ENG-1"), + ], + nextPageToken: "tok_2", + }), + }); + const api = yield* tracker; + const page = yield* api.listIssues({ + ...target, + involvement: "assigned", + viewer: "Julius", + state: "open", + limit: 25, + query: 'say "hi" \\ 12', + labels: ["bug"], + assignee: "Theo", + sort: "created", + }); + const search = requests.find((request) => request.path === "/search/jql"); + expect(search?.body).toMatchObject({ + jql: + 'project = "ENG" AND statusCategory != Done AND assignee = currentUser() AND ' + + `assignee = "${THEO.accountId}" AND labels = "bug" AND text ~ "say \\"hi\\" \\\\ 12" ` + + "ORDER BY created DESC", + maxResults: 25, + }); + expect(page.nextCursor).toBe("tok_2"); + expect(page.items[0]).toMatchObject({ + key: "ENG-2", + displayKey: "ENG-2", + url: "https://acme.atlassian.net/browse/ENG-2", + state: { category: "closed", name: "Done", closeReason: "completed" }, + closedAt: "2026-07-03T10:00:00.000Z", + author: { login: "Julius", name: "Julius" }, + assignees: [{ login: "Theo" }], + labels: [{ name: "bug", color: null }], + }); + expect(page.items[1]?.closedAt).toBeNull(); + + // A bare number also finds the issue by key; the cursor carries on. + yield* api.listIssues({ + ...target, + involvement: "all", + state: "all", + limit: 10, + query: "#7", + sort: "updated", + cursor: "tok_2", + }); + expect(requests.at(-1)?.body).toEqual( + expect.objectContaining({ + jql: 'project = "ENG" AND (text ~ "#7" OR key = "ENG-7") ORDER BY updated DESC', + nextPageToken: "tok_2", + }), + ); + const refused = yield* Effect.flip( + api.listIssues({ + ...target, + scope: 'ENG" OR project = "OPS', + involvement: "all", + state: "all", + limit: 1, + sort: "updated", + }), + ); + expect(refused.detail).toContain("not a Jira project key"); + }), + ); + + it.effect("reads an issue with its newest comments oldest first, its history and its moves", () => + Effect.gen(function* () { + const { tracker, requests } = fakeJira({ + "GET /myself": () => JULIUS, + "GET /issue/ENG-1": () => ({ + ...issue("ENG-1", { + description: doc( + { type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Steps" }] }, + { + type: "bulletList", + content: [{ type: "listItem", content: [paragraph("Open it")] }], + }, + ), + }), + changelog: { + histories: [ + { + id: "100", + author: THEO, + created: "2026-07-01T11:00:00.000+0000", + items: [ + { field: "status", fromString: "To Do", toString: "In Progress" }, + { field: "labels", fromString: "old", toString: "bug ui" }, + { field: "assignee", fromString: null, toString: "Theo" }, + { field: "Sprint", fromString: null, toString: "Sprint 4" }, + ], + }, + ], + }, + transitions: [ + { id: "31", to: status("Done", "done") }, + { id: "11", to: status("To Do", "new") }, + { id: "21", to: status("In Progress", "indeterminate") }, + ], + }), + "GET /issue/ENG-1/comment": (seen) => { + expect(seen.params.get("orderBy")).toBe("-created"); + return { + startAt: Number(seen.params.get("startAt")), + total: 51, + comments: [ + { + id: "c2", + author: THEO, + body: doc(paragraph("newest")), + created: "2026-07-02T09:00:00.000+0000", + }, + { + id: "c1", + author: JULIUS, + body: doc(paragraph("older")), + created: "2026-07-01T09:00:00.000+0000", + }, + ], + }; + }, + }); + const api = yield* tracker; + const detail = yield* api.getIssue({ ...target, key: "eng-1" }); + expect(detail).toMatchObject({ + key: "ENG-1", + body: "## Steps\n\n- Open it", + viewer: "Julius", + commentCount: 51, + linkedPullRequests: [], + }); + expect(detail.comments.map((comment) => [comment.id, comment.body])).toEqual([ + ["c1", "older"], + ["c2", "newest"], + ]); + expect(detail.comments[0]?.url).toBe( + "https://acme.atlassian.net/browse/ENG-1?focusedCommentId=c1", + ); + expect(detail.commentsCursor).toBe("2"); + expect(detail.states.map((state) => [state.name, state.category])).toEqual([ + ["In Progress", "open"], + ["Done", "closed"], + ["To Do", "open"], + ]); + expect(detail.events.map((event) => [event.kind, event.detail])).toEqual([ + ["state-changed", "In Progress"], + ["labeled", "bug"], + ["labeled", "ui"], + ["unlabeled", "old"], + ["assigned", "Theo"], + ]); + + const older = yield* api.getComments({ ...target, key: "ENG-1", cursor: "2" }); + expect(requests.at(-1)?.params.get("startAt")).toBe("2"); + expect(older.nextCursor).toBe("4"); + const bad = yield* Effect.flip(api.getComments({ ...target, key: "ENG-1", cursor: "x" })); + expect(bad.detail).toContain("cursor"); + }), + ); + + it.effect("writes only to issues in the bound project, as Markdown turned into ADF", () => + Effect.gen(function* () { + const writes: Seen[] = []; + const { tracker } = fakeJira({ + "GET /issue/ENG-1": () => ({ + ...issue("ENG-1"), + transitions: [{ id: "31", to: status("Done", "done") }], + }), + "GET /issue/OPS-3": () => issue("OPS-3"), + "GET /issue/ENG-5": () => + issue("ENG-5", { + description: doc({ + type: "mediaSingle", + content: [{ type: "media", attrs: { id: "m" } }], + }), + }), + "GET /issue/ENG-9": () => + new Response(JSON.stringify({ errorMessages: ["Issue does not exist"] }), { + status: 404, + }), + "PUT /issue/ENG-1": (seen) => void writes.push(seen), + "PUT /issue/ENG-5": (seen) => void writes.push(seen), + "POST /issue/ENG-1/comment": (seen) => void writes.push(seen), + "POST /issue/ENG-1/transitions": (seen) => void writes.push(seen), + "GET /user/assignable/search": () => [THEO, user("5b10ac8d82e05b22cc7d4ef6", "Theo")], + }); + const api = yield* tracker; + // A key from another project resolves in Jira, so the project is checked before writing. + const foreign = yield* Effect.flip(api.comment({ ...target, key: "OPS-3", body: "hi" })); + expect(foreign.detail).toContain("OPS"); + const missing = yield* Effect.flip(api.comment({ ...target, key: "ENG-9", body: "hi" })); + expect(missing.reason).toBe("not-found"); + + yield* api.comment({ ...target, key: "ENG-1", body: "**Done** in `main`" }); + yield* api.update({ + ...target, + key: "ENG-1", + title: "Renamed", + body: "", + labels: ["bug", "ui"], + assignees: [THEO.accountId], + }); + yield* api.setState({ ...target, key: "ENG-1", state: "Done" }); + const unknown = yield* Effect.flip( + api.setState({ ...target, key: "ENG-1", state: "closed" }), + ); + expect(unknown.detail).toContain('to "closed"'); + // Its attachment would not survive the Markdown round trip, so the body is not rewritten. + const attached = yield* Effect.flip(api.update({ ...target, key: "ENG-5", body: "new" })); + expect(attached.detail).toContain("Edit it in Jira"); + yield* api.update({ ...target, key: "ENG-5", title: "Still renamable" }); + const spaced = yield* Effect.flip( + api.update({ ...target, key: "ENG-1", labels: ["two words"] }), + ); + expect(spaced.detail).toContain("spaces"); + const two = yield* Effect.flip( + api.update({ ...target, key: "ENG-1", assignees: ["a", "b"] }), + ); + expect(two.detail).toContain("one assignee"); + const ambiguous = yield* Effect.flip( + api.update({ ...target, key: "ENG-1", assignees: ["Theo"] }), + ); + expect(ambiguous.detail).toContain("More than one"); + + expect(writes.map((write) => [write.method, write.path, write.body])).toEqual([ + [ + "POST", + "/issue/ENG-1/comment", + { + body: doc({ + type: "paragraph", + content: [ + { type: "text", text: "Done", marks: [{ type: "strong" }] }, + { type: "text", text: " in " }, + { type: "text", text: "main", marks: [{ type: "code" }] }, + ], + }), + }, + ], + [ + "PUT", + "/issue/ENG-1", + { + fields: { + summary: "Renamed", + description: null, + labels: ["bug", "ui"], + assignee: { accountId: THEO.accountId }, + }, + }, + ], + ["POST", "/issue/ENG-1/transitions", { transition: { id: "31" } }], + ["PUT", "/issue/ENG-5", { fields: { summary: "Still renamable" } }], + ]); + }), + ); + + it.effect("files a new issue under the project's first standard issue type", () => + Effect.gen(function* () { + let created: unknown; + const { tracker } = fakeJira({ + "GET /issue/createmeta/ENG/issuetypes": () => ({ + issueTypes: [ + { id: "5", name: "Sub-task", subtask: true }, + { id: "10001", name: "Task", subtask: false }, + ], + }), + "POST /issue": (seen) => { + created = seen.body; + return { id: "100", key: "ENG-42" }; + }, + }); + const api = yield* tracker; + const result = yield* api.create({ + ...target, + title: "New", + body: "- [ ] first", + labels: [], + assignees: [], + }); + expect(result).toEqual({ + key: "ENG-42", + displayKey: "ENG-42", + url: "https://acme.atlassian.net/browse/ENG-42", + }); + expect(created).toEqual({ + fields: { + project: { key: "ENG" }, + issuetype: { id: "10001" }, + summary: "New", + description: doc({ + type: "bulletList", + content: [ + { + type: "listItem", + content: [ + { + type: "paragraph", + content: [ + { type: "text", text: "[ ] " }, + { type: "text", text: "first" }, + ], + }, + ], + }, + ], + }), + }, + }); + }), + ); + + it.effect("maps Jira's refusals to the tracker's failure reasons", () => + Effect.gen(function* () { + const { tracker } = fakeJira({ + "GET /myself": () => new Response("", { status: 401 }), + "POST /search/jql": () => + new Response("", { status: 429, headers: { "retry-after": "30" } }), + "GET /issue/createmeta/ENG/issuetypes": () => + new Response(JSON.stringify({ errors: { project: "You cannot create issues here." } }), { + status: 403, + }), + }); + const api = yield* tracker; + const unauthenticated = yield* Effect.flip(api.getViewer({ cwd: "", host: "atlassian.net" })); + expect(unauthenticated.reason).toBe("unauthenticated"); + const limited = yield* Effect.flip( + api.listIssues({ ...target, involvement: "all", state: "all", limit: 1, sort: "updated" }), + ); + expect(limited.reason).toBe("rate-limited"); + expect(limited.retryAt).toBeGreaterThan(0); + const refused = yield* Effect.flip( + api.create({ ...target, title: "x", body: "", labels: [], assignees: [] }), + ); + expect(refused.detail).toBe("You cannot create issues here."); + }), + ); +}); diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts new file mode 100644 index 0000000000000..53ac5d0b31936 --- /dev/null +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts @@ -0,0 +1,498 @@ +/** + * Jira Cloud as an issue tracker. A scope is a project key (`ENG`) and an issue key its own + * (`ENG-123`). A status is closed when its category is `done`; moving between statuses goes + * through the workflow transitions Jira offers for the issue, never a status set directly. + */ +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import type { + IssueActor, + IssueCapabilities, + IssueComment, + IssueEvent, + IssueState, + IssueViewerPermissions, + StandaloneIssueTrackerDescriptor, +} from "@t3tools/contracts"; +import { + IssueTrackerError, + type IssueInvolvementFilter, + type StandaloneIssueTrackerApi, + type TrackerIssueSummary, +} from "@t3tools/source-control-core/server/IssueTracker"; + +import { JIRA_HOST, parseJiraIssueUrl } from "../shared/issueUrl.ts"; +import * as JiraApi from "./JiraApi.ts"; +import { adfToMarkdown, hasJiraOnlyContent, markdownToAdf } from "./jiraAdf.ts"; + +const DESCRIPTOR: StandaloneIssueTrackerDescriptor = { + tracker: JiraApi.KIND, + displayName: "Jira", + host: JIRA_HOST, + scopeNoun: "project", + credential: { + label: "Personal API token", + helpUrl: "https://id.atlassian.com/manage-profile/security/api-tokens", + fields: [ + { key: "site", label: "Site (example.atlassian.net)", secret: false }, + { key: "email", label: "Email", secret: false }, + { key: "token", label: "API token", secret: true }, + ], + }, +}; + +/** Reactions and templates have no public Jira Cloud API; linked PRs live in a private one. */ +const CAPABILITIES: IssueCapabilities = { + create: true, + edit: true, + comment: true, + labels: true, + assignees: true, + reactions: false, + templates: false, + linkedPullRequests: false, + events: true, + search: true, +}; + +/** Everything granted: Jira refuses a write the account may not make, and says why. */ +const VIEWER_PERMISSIONS: IssueViewerPermissions = { + setState: true, + comment: true, + edit: true, + labels: true, + assignees: true, +}; + +const COMMENTS_PAGE = 50; +const CANDIDATES = 100; +const KEY = /^[A-Za-z][A-Za-z0-9_]*-[1-9]\d*$/; +const PROJECT = /^[A-Za-z][A-Za-z0-9_]*$/; + +/** `ENG-123`, or null for anything that is not a Jira key. */ +function parseKey(key: string): string | null { + return KEY.test(key.trim()) ? key.trim().toUpperCase() : null; +} + +/** A JQL string literal: Jira reads backslash escapes inside double quotes. */ +export function jqlString(value: string): string { + return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; +} + +/** Jira answers with `+0000` offsets; the contract carries ISO 8601 with a `Z`. */ +function isoDate(value: string): string { + return Option.match(DateTime.make(value), { onNone: () => value, onSome: DateTime.formatIso }); +} + +function toState(status: JiraApi.JiraStatus): IssueState { + return status.statusCategory.key === "done" + ? { category: "closed", name: status.name, closeReason: "completed" } + : { category: "open", name: status.name }; +} + +/** + * The login is the display name, which is what people see and filter by: Jira Cloud has no + * handle. Writes and filters name people by account id, which `requireAccountId` resolves. + */ +function toActor(user: JiraApi.JiraUser): IssueActor { + return { + login: user.displayName?.trim() || user.accountId, + name: user.displayName?.trim() || null, + avatarUrl: user.avatarUrls?.["48x48"] ?? null, + }; +} + +/** Jira Cloud account ids: 24 hex digits, or `:`. */ +const ACCOUNT_ID = /^(?:[0-9a-z]{24}|\d+:[0-9a-f-]{36})$/i; + +const issueUrl = (site: string, key: string) => `https://${site}.atlassian.net/browse/${key}`; + +/** A search reports no comment totals cheaply, so a listing shows no comment count. */ +function toSummary(site: string, issue: JiraApi.JiraIssue, commentCount = 0): TrackerIssueSummary { + const fields = issue.fields; + const author = fields.reporter ?? fields.creator ?? null; + const closed = fields.status.statusCategory.key === "done"; + return { + key: issue.key, + displayKey: issue.key, + title: fields.summary.trim() || issue.key, + url: issueUrl(site, issue.key), + author: author === null ? null : toActor(author), + state: toState(fields.status), + createdAt: isoDate(fields.created), + updatedAt: isoDate(fields.updated), + closedAt: closed && fields.resolutiondate ? isoDate(fields.resolutiondate) : null, + assignees: fields.assignee ? [toActor(fields.assignee)] : [], + labels: (fields.labels ?? []).map((name) => ({ name, color: null })), + commentCount, + }; +} + +function toComment(site: string, key: string, comment: JiraApi.JiraComment): IssueComment { + return { + id: comment.id, + author: comment.author ? toActor(comment.author) : null, + body: adfToMarkdown(comment.body), + createdAt: isoDate(comment.created), + url: `${issueUrl(site, key)}?focusedCommentId=${encodeURIComponent(comment.id)}`, + }; +} + +/** Jira's changelog names fields by their display name; only the common vocabulary is kept. */ +function toEvents(histories: ReadonlyArray): IssueEvent[] { + const events: IssueEvent[] = []; + for (const history of histories) { + const actor = history.author ? toActor(history.author) : null; + const createdAt = isoDate(history.created); + history.items.forEach((item, index) => { + const add = (kind: IssueEvent["kind"], detail: string | null | undefined, suffix = "") => + events.push({ + id: `${history.id}:${index}${suffix}`, + kind, + actor, + createdAt, + detail: detail?.trim() || null, + }); + switch (item.field) { + case "status": + add("state-changed", item.toString); + break; + case "resolution": + add(item.toString ? "closed" : "reopened", item.toString); + break; + case "summary": + add("renamed", item.toString); + break; + case "assignee": + if (item.fromString) add("unassigned", item.fromString, "-"); + if (item.toString) add("assigned", item.toString, "+"); + break; + case "labels": { + // Labels arrive as the whole space-separated set before and after. + const before = new Set((item.fromString ?? "").split(" ").filter(Boolean)); + const after = new Set((item.toString ?? "").split(" ").filter(Boolean)); + for (const label of after) if (!before.has(label)) add("labeled", label, `+${label}`); + for (const label of before) if (!after.has(label)) add("unlabeled", label, `-${label}`); + break; + } + } + }); + } + return events; +} + +/** JQL names the signed-in account itself, so the viewer's display name is never matched on. */ +function involvementClause(input: IssueInvolvementFilter): string | null { + switch (input.involvement) { + case "assigned": + return "assignee = currentUser()"; + case "authored": + return "reporter = currentUser()"; + case "mentioned": + return "watcher = currentUser()"; + case "all": + return null; + } +} + +/** + * A comment cursor is the offset of the next older page, counted from the newest comment, so a + * comment added meanwhile shifts it by one at most and only repeats a comment the client drops. + */ +function parseCursor(cursor: string): number | null { + return /^[1-9]\d{0,8}$/.test(cursor) ? Number(cursor) : null; +} + +const notFound = (operation: string) => + new IssueTrackerError({ + tracker: JiraApi.KIND, + operation, + reason: "not-found", + detail: "Jira has no issue by that key, or this account cannot see it.", + }); + +const failed = (operation: string, detail: string) => + new IssueTrackerError({ tracker: JiraApi.KIND, operation, reason: "failed", detail }); + +export const make: Effect.Effect = Effect.gen( + function* () { + const jira = yield* JiraApi.JiraApi; + + const requireKey = (operation: string, key: string) => { + const parsed = parseKey(key); + return parsed === null ? Effect.fail(notFound(operation)) : Effect.succeed(parsed); + }; + + const requireProject = (operation: string, scope: string) => { + const project = scope.trim().toUpperCase(); + return PROJECT.test(project) + ? Effect.succeed(project) + : Effect.fail(failed(operation, `"${scope}" is not a Jira project key.`)); + }; + + /** + * The issue a write names, refused unless it sits in the bound project: a key from another + * project, or an issue moved away, still resolves in Jira. + */ + const requireProjectIssue = Effect.fn("JiraIssueTracker.requireProjectIssue")(function* ( + operation: string, + input: { readonly scope: string; readonly key: string }, + ) { + const key = yield* requireKey(operation, input.key); + const project = yield* requireProject(operation, input.scope); + const issue = yield* jira.getIssue(key); + if (issue === null) return yield* notFound(operation); + if (issue.fields.project.key.toUpperCase() !== project) { + return yield* failed( + operation, + `${issue.key} belongs to Jira project ${issue.fields.project.key}, not ${project}.`, + ); + } + return issue; + }); + + /** The comments page that ends `offset` comments back from the newest, oldest first. */ + const commentsPage = Effect.fn("JiraIssueTracker.commentsPage")(function* ( + key: string, + offset: number, + ) { + const [site, page] = yield* Effect.all([ + jira.site, + jira.getComments({ key, startAt: offset, limit: COMMENTS_PAGE }), + ]); + const next = offset + page.comments.length; + return { + total: page.total, + page: { + comments: page.comments.map((comment) => toComment(site, key, comment)).toReversed(), + nextCursor: page.comments.length > 0 && next < page.total ? String(next) : null, + }, + }; + }); + + /** Names as Jira stores them: one word each, since Jira splits labels on whitespace. */ + const requireLabels = (operation: string, labels: ReadonlyArray) => { + const bad = labels.find((label) => /\s/.test(label.trim()) || label.trim() === ""); + return bad === undefined + ? Effect.succeed(labels.map((label) => label.trim())) + : Effect.fail(failed(operation, `Jira labels cannot contain spaces: "${bad}".`)); + }; + + /** An account id as given, else the project's one assignable person by that display name. */ + const requireAccountId = Effect.fn("JiraIssueTracker.requireAccountId")(function* ( + operation: string, + project: string, + person: string, + ) { + const name = person.trim(); + if (ACCOUNT_ID.test(name)) return name; + const users = yield* jira.assignableUsers({ project, query: name, limit: CANDIDATES }); + const matches = users.filter( + (user) => user.displayName?.trim().toLowerCase() === name.toLowerCase(), + ); + if (matches.length === 1) return matches[0]!.accountId; + return yield* failed( + operation, + matches.length === 0 + ? `"${name}" cannot be assigned issues in Jira project ${project}.` + : `More than one person in Jira project ${project} is named "${name}".`, + ); + }); + + /** One assignee at most: a Jira issue has a single assignee. */ + const requireAssignee = Effect.fn("JiraIssueTracker.requireAssignee")(function* ( + operation: string, + project: string, + assignees: ReadonlyArray, + ) { + const [first, ...rest] = assignees; + if (first === undefined) return null; + if (rest.length > 0) + return yield* failed(operation, "A Jira issue has one assignee at most."); + return { accountId: yield* requireAccountId(operation, project, first) }; + }); + + const api: StandaloneIssueTrackerApi = { + kind: JiraApi.KIND, + capabilities: CAPABILITIES, + standalone: DESCRIPTOR, + parseIssueUrl: parseJiraIssueUrl, + + probeCredential: (credential) => + jira.probe(credential).pipe( + Effect.map((probe) => ({ + account: + probe.user.displayName?.trim() || probe.user.emailAddress || probe.user.accountId, + workspace: probe.site, + scopes: probe.projects, + })), + ), + + getViewer: () => jira.myself.pipe(Effect.map((user) => toActor(user).login)), + + listIssues: Effect.fn("JiraIssueTracker.listIssues")(function* (input) { + const project = yield* requireProject("listIssues", input.scope); + const text = input.query?.trim() ?? ""; + const reference = /^(?:[A-Za-z][A-Za-z0-9_]*-|#)?(\d+)$/.exec(text); + const involvement = involvementClause(input); + const clauses = [ + `project = ${jqlString(project)}`, + ...(input.state === "all" + ? [] + : [`statusCategory ${input.state === "closed" ? "=" : "!="} Done`]), + ...(involvement === null ? [] : [involvement]), + ...(input.assignee === undefined + ? [] + : [ + `assignee = ${jqlString(yield* requireAccountId("listIssues", project, input.assignee))}`, + ]), + ...(input.labels ?? []).map((label) => `labels = ${jqlString(label)}`), + ...(text === "" + ? [] + : [ + reference === null + ? `text ~ ${jqlString(text)}` + : `(text ~ ${jqlString(text)} OR key = ${jqlString(`${project}-${reference[1]}`)})`, + ]), + ]; + const order = input.sort === "created" ? "created" : "updated"; + const [site, page] = yield* Effect.all([ + jira.site, + jira.search({ + jql: `${clauses.join(" AND ")} ORDER BY ${order} DESC`, + limit: input.limit, + cursor: input.cursor, + }), + ]); + return { + items: page.issues.map((issue) => toSummary(site, issue)), + nextCursor: page.nextCursor, + }; + }), + + getIssue: Effect.fn("JiraIssueTracker.getIssue")(function* (input) { + const key = yield* requireKey("getIssue", input.key); + const [site, issue, viewer] = yield* Effect.all([ + jira.site, + jira.getIssue(key), + jira.myself.pipe( + Effect.map((user) => toActor(user).login), + Effect.orElseSucceed(() => null), + ), + ]); + if (issue === null) return yield* notFound("getIssue"); + const comments = yield* commentsPage(key, 0); + // A transition's target is a state the issue can move to; the current one is listed too. + const states = [issue.fields.status, ...(issue.transitions ?? []).map((t) => t.to)]; + const seen = new Set(); + return { + ...toSummary(site, issue, comments.total), + body: adfToMarkdown(issue.fields.description), + viewer, + viewerPermissions: VIEWER_PERMISSIONS, + states: states + .filter((status) => !seen.has(status.name) && seen.add(status.name) !== undefined) + .map(toState), + comments: comments.page.comments, + commentsCursor: comments.page.nextCursor, + events: toEvents(issue.changelog?.histories ?? []), + linkedPullRequests: [], + }; + }), + + getComments: Effect.fn("JiraIssueTracker.getComments")(function* (input) { + const key = yield* requireKey("getComments", input.key); + const offset = parseCursor(input.cursor); + if (offset === null) + return yield* failed("getComments", "The cursor was not one Jira handed out."); + return (yield* commentsPage(key, offset)).page; + }), + + create: Effect.fn("JiraIssueTracker.create")(function* (input) { + const project = yield* requireProject("create", input.scope); + const labels = yield* requireLabels("create", input.labels); + const assignee = yield* requireAssignee("create", project, input.assignees); + const types = yield* jira.issueTypes(project); + // The project's first standard type, as Jira's own create dialog picks by default. + const type = types.find((candidate) => candidate.subtask !== true); + if (type === undefined) + return yield* failed( + "create", + `Jira project ${project} has no issue type to file under.`, + ); + const key = yield* jira.createIssue({ + project: { key: project }, + issuetype: { id: type.id }, + summary: input.title, + ...(input.body.trim() === "" ? {} : { description: markdownToAdf(input.body) }), + ...(labels.length === 0 ? {} : { labels }), + ...(assignee === null ? {} : { assignee }), + }); + const site = yield* jira.site; + return { key, displayKey: key, url: issueUrl(site, key) }; + }), + + comment: Effect.fn("JiraIssueTracker.comment")(function* (input) { + const issue = yield* requireProjectIssue("comment", input); + yield* jira.addComment(issue.key, markdownToAdf(input.body)); + }), + + update: Effect.fn("JiraIssueTracker.update")(function* (input) { + const issue = yield* requireProjectIssue("update", input); + // The Markdown a client edited lost these nodes on read; writing it back would delete them. + if (input.body !== undefined && hasJiraOnlyContent(issue.fields.description)) { + return yield* failed( + "update", + "This description has attachments or other content only Jira can edit. Edit it in Jira.", + ); + } + yield* jira.updateIssue(issue.key, { + ...(input.title === undefined ? {} : { summary: input.title }), + ...(input.body === undefined + ? {} + : { description: input.body.trim() === "" ? null : markdownToAdf(input.body) }), + ...(input.labels === undefined + ? {} + : { labels: yield* requireLabels("update", input.labels) }), + ...(input.assignees === undefined + ? {} + : { + assignee: yield* requireAssignee( + "update", + issue.fields.project.key, + input.assignees, + ), + }), + }); + }), + + setState: Effect.fn("JiraIssueTracker.setState")(function* (input) { + const issue = yield* requireProjectIssue("setState", input); + if (issue.fields.status.name === input.state) return; + const transition = (issue.transitions ?? []).find((t) => t.to.name === input.state); + if (transition === undefined) { + return yield* failed( + "setState", + `Jira's workflow offers no move from "${issue.fields.status.name}" to "${input.state}".`, + ); + } + yield* jira.transition(issue.key, transition.id); + }), + + listCandidates: Effect.fn("JiraIssueTracker.listCandidates")(function* (input) { + const project = yield* requireProject("listCandidates", input.scope); + const [labels, users] = yield* Effect.all([ + jira.labels(CANDIDATES), + jira.assignableUsers({ project, limit: CANDIDATES }), + ]); + return { + labels: labels.values.map((name) => ({ name, color: null, description: null })), + assignees: users.map((user) => ({ ...toActor(user), id: user.accountId })), + truncated: labels.truncated || users.length >= CANDIDATES, + }; + }), + }; + return api; + }, +); diff --git a/packages/issue-tracker-jira/src/server/driver.ts b/packages/issue-tracker-jira/src/server/driver.ts new file mode 100644 index 0000000000000..8b0939d4455a5 --- /dev/null +++ b/packages/issue-tracker-jira/src/server/driver.ts @@ -0,0 +1,12 @@ +import * as Effect from "effect/Effect"; + +import * as JiraApi from "./JiraApi.ts"; +import * as JiraIssueTracker from "./JiraIssueTracker.ts"; + +/** + * The Jira Cloud tracker over its REST API. Needs the platform HttpClient, and the server's + * `IssueTrackerHost` for the site, email and API token saved in Settings. + */ +export const make = JiraIssueTracker.make.pipe( + Effect.provideServiceEffect(JiraApi.JiraApi, JiraApi.make), +); diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.test.ts b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts new file mode 100644 index 0000000000000..c969987fab2a2 --- /dev/null +++ b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { adfToMarkdown, markdownToAdf } from "./jiraAdf.ts"; + +const text = (value: string, marks?: ReadonlyArray) => + marks === undefined ? { type: "text", text: value } : { type: "text", text: value, marks }; + +describe("jiraAdf", () => { + it("reads a Jira document as Markdown, naming what Markdown cannot hold", () => { + expect( + adfToMarkdown({ + type: "doc", + version: 1, + content: [ + { + type: "paragraph", + content: [ + text("See "), + text("the guide", [ + { type: "link", attrs: { href: "https://x.test" } }, + { type: "strong" }, + ]), + { type: "hardBreak" }, + { type: "mention", attrs: { id: "abc", text: "@Theo" } }, + ], + }, + { + type: "orderedList", + attrs: { order: 3 }, + content: [ + { type: "listItem", content: [{ type: "paragraph", content: [text("three")] }] }, + { + type: "listItem", + content: [ + { type: "paragraph", content: [text("four")] }, + { + type: "bulletList", + content: [ + { + type: "listItem", + content: [{ type: "paragraph", content: [text("nested")] }], + }, + ], + }, + ], + }, + ], + }, + { type: "codeBlock", attrs: { language: "ts" }, content: [text("const a = 1;")] }, + { + type: "table", + content: [ + { + type: "tableRow", + content: [ + { type: "tableHeader", content: [{ type: "paragraph", content: [text("a|b")] }] }, + ], + }, + { + type: "tableRow", + content: [ + { type: "tableCell", content: [{ type: "paragraph", content: [text("1")] }] }, + ], + }, + ], + }, + { type: "mediaSingle", content: [{ type: "media", attrs: { id: "m1" } }] }, + ], + }), + ).toBe( + [ + "See [**the guide**](https://x.test)\n@Theo", + "3. three\n4. four\n - nested", + "```ts\nconst a = 1;\n```", + "| a\\|b |\n| --- |\n| 1 |", + "_(attachment, open in Jira to view)_", + ].join("\n\n"), + ); + expect(adfToMarkdown(null)).toBe(""); + expect(adfToMarkdown({ type: "doc", version: 1, content: [] })).toBe(""); + }); + + it("writes Markdown as the document Jira's editor would have stored", () => { + expect( + markdownToAdf("# Title\n\n> quoted *text*\n\n1. one\n\n---\n\n[`code` link](https://x.test)"), + ).toEqual({ + type: "doc", + version: 1, + content: [ + { type: "heading", attrs: { level: 1 }, content: [text("Title")] }, + { + type: "blockquote", + content: [ + { type: "paragraph", content: [text("quoted "), text("text", [{ type: "em" }])] }, + ], + }, + { + type: "orderedList", + content: [{ type: "listItem", content: [{ type: "paragraph", content: [text("one")] }] }], + }, + { type: "rule" }, + { + type: "paragraph", + content: [ + // Jira allows only a link beside a code mark. + text("code", [{ type: "link", attrs: { href: "https://x.test" } }, { type: "code" }]), + text(" link", [{ type: "link", attrs: { href: "https://x.test" } }]), + ], + }, + ], + }); + expect(markdownToAdf("")).toEqual({ type: "doc", version: 1, content: [] }); + }); + + it("keeps a document's text through a round trip", () => { + const markdown = "Fix **this** and ~~that~~.\n\n- one\n- two\n\n```\nraw\n```"; + expect(adfToMarkdown(markdownToAdf(markdown))).toBe(markdown); + }); +}); diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.ts b/packages/issue-tracker-jira/src/server/jiraAdf.ts new file mode 100644 index 0000000000000..ab470d13011ea --- /dev/null +++ b/packages/issue-tracker-jira/src/server/jiraAdf.ts @@ -0,0 +1,350 @@ +/** + * Jira Cloud keeps descriptions and comments as Atlassian Document Format; T3 Code reads and + * writes Markdown. A read keeps the text and structure Markdown can carry and names what it + * cannot (an attachment, an unknown macro) instead of dropping it silently. + */ +import * as DateTime from "effect/DateTime"; +import * as Option from "effect/Option"; +import type * as Mdast from "mdast"; +import { fromMarkdown } from "mdast-util-from-markdown"; +import { gfmFromMarkdown } from "mdast-util-gfm"; +import { gfm } from "micromark-extension-gfm"; + +interface AdfMark { + readonly type: string; + readonly attrs?: Record; +} + +export interface AdfNode { + readonly type: string; + readonly text?: string; + readonly attrs?: Record; + readonly marks?: ReadonlyArray; + readonly content?: ReadonlyArray; +} + +const isNode = (value: unknown): value is AdfNode => + typeof value === "object" && + value !== null && + typeof (value as { type?: unknown }).type === "string"; + +const attr = (node: AdfNode, name: string): string | null => { + const value = node.attrs?.[name]; + return typeof value === "string" && value !== "" ? value : null; +}; + +function inline(nodes: ReadonlyArray | undefined): string { + return (nodes ?? []).map(inlineNode).join(""); +} + +function marked(text: string, marks: ReadonlyArray | undefined): string { + let out = text; + for (const mark of marks ?? []) { + if (mark.type === "code") out = `\`${out}\``; + else if (mark.type === "strong") out = `**${out}**`; + else if (mark.type === "em") out = `*${out}*`; + else if (mark.type === "strike") out = `~~${out}~~`; + } + const link = marks?.find((mark) => mark.type === "link")?.attrs?.["href"]; + return typeof link === "string" ? `[${out}](${link})` : out; +} + +function inlineNode(node: AdfNode): string { + switch (node.type) { + case "text": + return marked(node.text ?? "", node.marks); + case "hardBreak": + return "\n"; + case "mention": + return attr(node, "text") ?? "@someone"; + case "emoji": + return attr(node, "text") ?? attr(node, "shortName") ?? ""; + case "inlineCard": + case "blockCard": + return attr(node, "url") ?? ""; + case "status": + return attr(node, "text") ?? ""; + case "date": { + const timestamp = Number(attr(node, "timestamp")); + return Option.match(DateTime.make(timestamp), { + onNone: () => "", + onSome: (date) => DateTime.formatIsoDateUtc(date), + }); + } + default: + return inline(node.content); + } +} + +const indent = (text: string, prefix: string) => + text + .split("\n") + .map((line, index) => (index === 0 ? line : line === "" ? line : prefix + line)) + .join("\n"); + +function blocks(nodes: ReadonlyArray | undefined): string { + return (nodes ?? []) + .map(block) + .filter((text) => text !== "") + .join("\n\n"); +} + +function list(node: AdfNode, ordered: boolean): string { + const start = ordered ? Number(node.attrs?.["order"] ?? 1) || 1 : 1; + return (node.content ?? []) + .map((item, index) => { + const bullet = ordered ? `${start + index}. ` : "- "; + const done = + item.type === "taskItem" ? (attr(item, "state") === "DONE" ? "[x] " : "[ ] ") : ""; + // A nested list sits right under its item's text, so the item stays one tight list entry. + const body = + item.type === "taskItem" + ? inline(item.content) + : (item.content ?? []) + .map(block) + .filter((text) => text !== "") + .join("\n"); + return bullet + done + indent(body, " ".repeat(bullet.length)); + }) + .join("\n"); +} + +function table(node: AdfNode): string { + const rows = (node.content ?? []).map((row) => + (row.content ?? []).map((cell) => + blocks(cell.content).replaceAll("\n", " ").replaceAll("|", "\\|"), + ), + ); + const width = Math.max(0, ...rows.map((row) => row.length)); + if (width === 0) return ""; + const line = (cells: ReadonlyArray) => + `| ${Array.from({ length: width }, (_, index) => cells[index] ?? "").join(" | ")} |`; + const [head = [], ...body] = rows; + return [line(head), line(Array(width).fill("---")), ...body.map(line)].join("\n"); +} + +function block(node: AdfNode): string { + switch (node.type) { + case "paragraph": + return inline(node.content); + case "heading": + return `${"#".repeat(Math.min(Math.max(Number(node.attrs?.["level"]) || 1, 1), 6))} ${inline(node.content)}`; + case "bulletList": + case "taskList": + return list(node, false); + case "orderedList": + return list(node, true); + case "codeBlock": + return `\`\`\`${attr(node, "language") ?? ""}\n${inline(node.content)}\n\`\`\``; + case "blockquote": + case "panel": + return blocks(node.content) + .split("\n") + .map((line) => (line === "" ? ">" : `> ${line}`)) + .join("\n"); + case "rule": + return "---"; + case "table": + return table(node); + case "mediaSingle": + case "mediaGroup": + case "media": + return "_(attachment, open in Jira to view)_"; + case "expand": + case "nestedExpand": + return [attr(node, "title"), blocks(node.content)].filter(Boolean).join("\n\n"); + default: + return node.content === undefined ? inlineNode(node) : blocks(node.content); + } +} + +/** Nodes whose Markdown form is a stand-in, so writing that Markdown back would lose them. */ +const JIRA_ONLY = new Set([ + "media", + "mediaSingle", + "mediaGroup", + "mediaInline", + "mention", + "emoji", + "status", + "date", + "inlineCard", + "blockCard", + "embedCard", + "panel", + "expand", + "nestedExpand", + "extension", + "bodiedExtension", + "inlineExtension", + "layoutSection", + "decisionList", +]); + +export function hasJiraOnlyContent(document: unknown): boolean { + if (!isNode(document)) return false; + const visit = (node: AdfNode): boolean => + JIRA_ONLY.has(node.type) || + (node.marks ?? []).some((mark) => mark.type !== "link" && !MARKDOWN_MARKS.has(mark.type)) || + (node.content ?? []).some((child) => isNode(child) && visit(child)); + return visit(document); +} + +const MARKDOWN_MARKS = new Set(["code", "strong", "em", "strike"]); + +/** A Jira document as Markdown; an empty or absent one is the empty string. */ +export function adfToMarkdown(document: unknown): string { + if (typeof document === "string") return document; + if (!isNode(document)) return ""; + return blocks(document.content).trim(); +} + +type Inline = AdfNode; + +function inlineFromMdast(node: Mdast.PhrasingContent, marks: ReadonlyArray): Inline[] { + const children = (extra: AdfMark) => + "children" in node + ? (node.children as Mdast.PhrasingContent[]).flatMap((child) => + inlineFromMdast(child, [...marks, extra]), + ) + : []; + switch (node.type) { + case "text": + return node.value === "" ? [] : [{ type: "text", text: node.value, ...withMarks(marks) }]; + case "inlineCode": + // Jira only lets code combine with a link. + return node.value === "" + ? [] + : [ + { + type: "text", + text: node.value, + ...withMarks([...marks.filter((mark) => mark.type === "link"), { type: "code" }]), + }, + ]; + case "strong": + return children({ type: "strong" }); + case "emphasis": + return children({ type: "em" }); + case "delete": + return children({ type: "strike" }); + case "link": + return children({ type: "link", attrs: { href: node.url } }); + case "image": + return [ + { + type: "text", + text: node.alt || node.url, + ...withMarks([...marks, { type: "link", attrs: { href: node.url } }]), + }, + ]; + case "break": + return [{ type: "hardBreak" }]; + case "html": + return node.value === "" ? [] : [{ type: "text", text: node.value, ...withMarks(marks) }]; + default: + return "children" in node + ? (node.children as Mdast.PhrasingContent[]).flatMap((child) => + inlineFromMdast(child, marks), + ) + : []; + } +} + +function withMarks(marks: ReadonlyArray): { marks?: AdfMark[] } { + if (marks.length === 0) return {}; + const code = marks.some((mark) => mark.type === "code"); + const kept = code ? marks.filter((mark) => mark.type === "code" || mark.type === "link") : marks; + return { marks: [...new Map(kept.map((mark) => [mark.type, mark])).values()] }; +} + +function paragraph(children: ReadonlyArray): AdfNode { + const content = children.flatMap((child) => inlineFromMdast(child, [])); + return content.length === 0 ? { type: "paragraph" } : { type: "paragraph", content }; +} + +function blockFromMdast(node: Mdast.RootContent): AdfNode[] { + switch (node.type) { + case "paragraph": + return [paragraph(node.children)]; + case "heading": + return [ + { + type: "heading", + attrs: { level: node.depth }, + content: paragraph(node.children).content ?? [], + }, + ]; + case "code": + return [ + { + type: "codeBlock", + ...(node.lang ? { attrs: { language: node.lang } } : {}), + ...(node.value === "" ? {} : { content: [{ type: "text", text: node.value }] }), + }, + ]; + case "blockquote": + return [{ type: "blockquote", content: node.children.flatMap(blockFromMdast) }]; + case "list": + return [ + { + type: node.ordered ? "orderedList" : "bulletList", + ...(node.ordered && node.start != null && node.start !== 1 + ? { attrs: { order: node.start } } + : {}), + content: node.children.map((item) => { + const content = item.children.flatMap(blockFromMdast); + const checkbox = item.checked == null ? null : item.checked ? "[x] " : "[ ] "; + const [first, ...rest] = content; + // A list item must open with a paragraph in Jira. + const opening: AdfNode = + first?.type === "paragraph" + ? checkbox === null + ? first + : { + ...first, + content: [{ type: "text", text: checkbox }, ...(first.content ?? [])], + } + : { + type: "paragraph", + ...(checkbox === null ? {} : { content: [{ type: "text", text: checkbox }] }), + }; + return { + type: "listItem", + content: first?.type === "paragraph" ? [opening, ...rest] : [opening, ...content], + }; + }), + }, + ]; + case "thematicBreak": + return [{ type: "rule" }]; + case "table": + return [ + { + type: "table", + content: node.children.map((row, rowIndex) => ({ + type: "tableRow", + content: row.children.map((cell) => ({ + type: rowIndex === 0 ? "tableHeader" : "tableCell", + content: [paragraph(cell.children)], + })), + })), + }, + ]; + case "html": + return node.value.trim() === "" + ? [] + : [{ type: "paragraph", content: [{ type: "text", text: node.value }] }]; + default: + return []; + } +} + +/** Markdown as a Jira document, the way Jira's own editor would have stored it. */ +export function markdownToAdf(markdown: string) { + const tree = fromMarkdown(markdown, { + extensions: [gfm()], + mdastExtensions: [gfmFromMarkdown()], + }); + return { type: "doc", version: 1, content: tree.children.flatMap(blockFromMdast) }; +} diff --git a/packages/issue-tracker-jira/src/shared/issueUrl.ts b/packages/issue-tracker-jira/src/shared/issueUrl.ts new file mode 100644 index 0000000000000..f581cac476ecb --- /dev/null +++ b/packages/issue-tracker-jira/src/shared/issueUrl.ts @@ -0,0 +1,19 @@ +import { IssueTrackerKind } from "@t3tools/contracts"; + +export const JIRA_KIND = IssueTrackerKind.make("jira"); +/** Every Jira Cloud site is a subdomain of this; the site itself is the link's workspace. */ +export const JIRA_HOST = "atlassian.net"; + +const SITE = /^([a-z0-9][a-z0-9-]*)\.atlassian\.net$/; +const KEY = /^([A-Z][A-Z0-9_]*)-[1-9][0-9]*$/; + +/** `https://.atlassian.net/browse/-`, keeping the site. */ +export function parseJiraIssueUrl(url: URL) { + if (url.protocol !== "https:" || url.port !== "") return null; + const site = SITE.exec(url.hostname.toLowerCase())?.[1]; + const [, resource, key, ...rest] = url.pathname.split("/"); + if (site === undefined || resource !== "browse" || key === undefined) return null; + if (rest.some((segment) => segment !== "")) return null; + const scope = KEY.exec(key)?.[1]; + return scope === undefined ? null : { host: JIRA_HOST, workspace: site, scope, key }; +} diff --git a/packages/issue-tracker-jira/tsconfig.json b/packages/issue-tracker-jira/tsconfig.json new file mode 100644 index 0000000000000..374bac55202dd --- /dev/null +++ b/packages/issue-tracker-jira/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e003246a26e8c..779bfdab5c5b4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -877,6 +877,9 @@ importers: '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 + '@t3tools/issue-tracker-jira': + specifier: workspace:* + version: link:../../packages/issue-tracker-jira '@t3tools/issue-tracker-linear': specifier: workspace:* version: link:../../packages/issue-tracker-linear @@ -1525,6 +1528,9 @@ importers: '@t3tools/contracts': specifier: workspace:* version: link:../contracts + '@t3tools/issue-tracker-jira': + specifier: workspace:* + version: link:../issue-tracker-jira '@t3tools/issue-tracker-linear': specifier: workspace:* version: link:../issue-tracker-linear @@ -1662,6 +1668,40 @@ importers: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/issue-tracker-jira: + dependencies: + '@t3tools/contracts': + specifier: workspace:* + version: link:../contracts + '@t3tools/source-control-core': + specifier: workspace:* + version: link:../source-control-core + effect: + specifier: 4.1.3 + version: 4.1.3 + mdast-util-from-markdown: + specifier: 2.0.3 + version: 2.0.3(supports-color@8.1.1) + mdast-util-gfm: + specifier: 3.1.0 + version: 3.1.0(supports-color@8.1.1) + micromark-extension-gfm: + specifier: 3.0.0 + version: 3.0.0 + devDependencies: + '@effect/vitest': + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.3)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@types/mdast': + specifier: ^4.0.4 + version: 4.0.4 + '@types/node': + specifier: 24.12.4 + version: 24.12.4 + vite-plus: + specifier: 1.4.0 + version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/issue-tracker-linear: dependencies: '@t3tools/contracts': diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index b564001c19290..94e879b88cff7 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -40,6 +40,7 @@ const workspaceFiles = [ "packages/provider-kiro/package.json", "packages/provider-muse/package.json", "packages/provider-opencode/package.json", + "packages/issue-tracker-jira/package.json", "packages/issue-tracker-linear/package.json", "packages/secret-provider-core/package.json", "packages/secret-provider-definitions/package.json", From 10d699602f446468c13fdb5d90f3eb3e74ed5da2 Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:22:49 +0100 Subject: [PATCH 2/8] fix(issues): keep Jira text and links intact through edits - Escape literal Markdown characters and pick code fences that the code cannot close. - Resolve reference links, and refuse body edits on tables with merged cells. - Apply the request deadline to the response body as well. - Keep web credential drafts when the connection fails. - Match Jira links case-insensitively in the pre-check. - Document the token type, the watcher filter and the Jira-only edit limit. Co-Authored-By: Claude Opus 5.5 --- .../settings/IssueTrackerSettings.tsx | 12 +++-- docs/user/source-control.md | 7 ++- .../client-runtime/src/issueLinks.test.ts | 5 +- packages/client-runtime/src/issueLinks.ts | 3 +- .../issue-tracker-jira/src/server/JiraApi.ts | 34 ++++++++----- .../src/server/JiraIssueTracker.test.ts | 17 +++++-- .../src/server/JiraIssueTracker.ts | 2 +- .../src/server/jiraAdf.test.ts | 29 ++++++++++- .../issue-tracker-jira/src/server/jiraAdf.ts | 51 +++++++++++++++++-- 9 files changed, 127 insertions(+), 33 deletions(-) diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx index 2d5c9e6513007..5ca7ec78fbcb8 100644 --- a/apps/web/src/components/settings/IssueTrackerSettings.tsx +++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx @@ -123,9 +123,10 @@ function TrackerRow({ input: { tracker: tracker.tracker, token }, }); setBusy(false); - if (result._tag === "Success") return; + if (result._tag === "Success") return true; const error = squashAtomCommandFailure(result); setFailure(error instanceof Error ? error.message : gt("The request failed.")); + return false; }; const inputId = `issue-tracker-${tracker.tracker}-${environmentId}`; @@ -207,7 +208,7 @@ function TrackerRow({ id={inputId} fields={tracker.credential.fields} connected={tracker.connected} - onSubmit={(token) => void submit(token)} + onSubmit={submit} /> ) : ( ; readonly connected: boolean; - readonly onSubmit: (token: string) => void; + readonly onSubmit: (token: string) => Promise; }) { const gt = useGT(); const [drafts, setDrafts] = useState>>({}); @@ -271,8 +272,9 @@ function CredentialFields({ onSubmit={(event) => { event.preventDefault(); if (token === null) return; - onSubmit(token); - setDrafts({}); + void onSubmit(token).then((connected) => { + if (connected) setDrafts({}); + }); }} > {fields.map((field) => ( diff --git a/docs/user/source-control.md b/docs/user/source-control.md index f0f87f085fbe0..5a71f000300d4 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -377,8 +377,11 @@ requests. To list a Linear team's or a Jira Cloud project's issues beside a project's, connect the tracker under Settings → Source control & issues, then choose the team or project for that project there. Linear takes an API key. Jira takes your site (`example.atlassian.net`), your account email and an -[API token](https://id.atlassian.com/manage-profile/security/api-tokens). Jira issues move between -statuses through your workflow's transitions; Jira reactions and linked pull requests are not shown. +[API token](https://id.atlassian.com/manage-profile/security/api-tokens) created with **Create API +token**, not a token with scopes. Jira issues move between statuses through your workflow's +transitions. For Jira, "mentioning you" lists the issues you watch. A Jira description with +attachments, mentions or other Jira-only content is edited in Jira. Jira reactions and linked pull +requests are not shown. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 89febe02f0c1f..a7acdcad4ff3b 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { resolveIssueLinkTarget } from "./issueLinks.ts"; +import { mayContainStandaloneIssueLink, resolveIssueLinkTarget } from "./issueLinks.ts"; const project = (id: string, repository: string) => ({ @@ -140,6 +140,9 @@ describe("resolveIssueLinkTarget", () => { scope: "ENG", key: "ENG-4", }); + const upper = "See https://ACME.ATLASSIAN.NET/browse/ENG-4"; + expect(mayContainStandaloneIssueLink(upper)).toBe(true); + expect(resolve(upper.slice(4))?.ref.key).toBe("ENG-4"); // Project keys repeat across sites; only the connected one's links are its issues. expect(resolve("https://othercorp.atlassian.net/browse/ENG-4")).toBeNull(); expect(resolve("https://acme.atlassian.net.evil.example/browse/ENG-4")).toBeNull(); diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index d9c1682526463..98affacf94cc5 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -83,7 +83,8 @@ export function isStandaloneIssueLink(url: string): boolean { /** A cheap pre-check, so text without such a link never asks for the bindings. */ export function mayContainStandaloneIssueLink(text: string): boolean { - return text.includes(`${LINEAR_HOST}/`) || text.includes(`.${JIRA_HOST}/`); + const lower = text.toLowerCase(); + return lower.includes(`${LINEAR_HOST}/`) || lower.includes(`.${JIRA_HOST}/`); } /** diff --git a/packages/issue-tracker-jira/src/server/JiraApi.ts b/packages/issue-tracker-jira/src/server/JiraApi.ts index bc718d6903460..138e46d817f81 100644 --- a/packages/issue-tracker-jira/src/server/JiraApi.ts +++ b/packages/issue-tracker-jira/src/server/JiraApi.ts @@ -338,20 +338,26 @@ export const make = Effect.gen(function* () { ), ); } - const response = yield* httpClient.execute(request).pipe( - Effect.timeout(REQUEST_TIMEOUT), - Effect.mapError((cause) => - fail(input.operation, "failed", "Jira could not be reached.", { cause }), - ), - ); - if (response.status < 200 || response.status >= 300) { - return yield* Effect.flatMap(refusal(input.operation, response), Effect.fail); - } - if (input.schema === null) return null; - return yield* HttpClientResponse.schemaBodyJson(input.schema)(response).pipe( - Effect.mapError((cause) => - fail(input.operation, "failed", "Jira returned an unexpected body.", { cause }), - ), + const unreachable = (cause?: unknown) => + fail(input.operation, "failed", "Jira could not be reached.", { cause }); + const exchange = Effect.gen(function* () { + const response = yield* httpClient.execute(request).pipe(Effect.mapError(unreachable)); + if (response.status < 200 || response.status >= 300) { + return yield* Effect.flatMap(refusal(input.operation, response), Effect.fail); + } + if (input.schema === null) return null; + return yield* HttpClientResponse.schemaBodyJson(input.schema)(response).pipe( + Effect.mapError((cause) => + fail(input.operation, "failed", "Jira returned an unexpected body.", { cause }), + ), + ); + }); + // The deadline covers the body too: Jira can send its headers, then stall. + return yield* exchange.pipe( + Effect.timeoutOrElse({ + duration: REQUEST_TIMEOUT, + orElse: () => Effect.fail(unreachable()), + }), ); }); diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts index 5268626cb517c..280cd53f447ca 100644 --- a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse, UrlParams } from "effect/http"; import { IssueTrackerKind } from "@t3tools/contracts"; import type { StandaloneIssueTrackerApi } from "@t3tools/source-control-core/server/IssueTracker"; @@ -303,18 +305,19 @@ describe("JiraIssueTracker", () => { }), "GET /issue/ENG-1/comment": (seen) => { expect(seen.params.get("orderBy")).toBe("-created"); + const startAt = Number(seen.params.get("startAt")); return { - startAt: Number(seen.params.get("startAt")), + startAt, total: 51, comments: [ { - id: "c2", + id: `c${startAt + 2}`, author: THEO, body: doc(paragraph("newest")), created: "2026-07-02T09:00:00.000+0000", }, { - id: "c1", + id: `c${startAt + 1}`, author: JULIUS, body: doc(paragraph("older")), created: "2026-07-01T09:00:00.000+0000", @@ -355,6 +358,7 @@ describe("JiraIssueTracker", () => { const older = yield* api.getComments({ ...target, key: "ENG-1", cursor: "2" }); expect(requests.at(-1)?.params.get("startAt")).toBe("2"); + expect(older.comments.map((comment) => comment.id)).toEqual(["c3", "c4"]); expect(older.nextCursor).toBe("4"); const bad = yield* Effect.flip(api.getComments({ ...target, key: "ENG-1", cursor: "x" })); expect(bad.detail).toContain("cursor"); @@ -519,6 +523,8 @@ describe("JiraIssueTracker", () => { "GET /myself": () => new Response("", { status: 401 }), "POST /search/jql": () => new Response("", { status: 429, headers: { "retry-after": "30" } }), + "GET /issue/ENG-1": () => + new Response(new ReadableStream(), { headers: { "content-type": "application/json" } }), "GET /issue/createmeta/ENG/issuetypes": () => new Response(JSON.stringify({ errors: { project: "You cannot create issues here." } }), { status: 403, @@ -536,6 +542,11 @@ describe("JiraIssueTracker", () => { api.create({ ...target, title: "x", body: "", labels: [], assignees: [] }), ); expect(refused.detail).toBe("You cannot create issues here."); + const stalled = yield* Effect.forkChild( + Effect.flip(api.getIssue({ ...target, key: "ENG-1" })), + ); + yield* TestClock.adjust("31 seconds"); + expect((yield* Fiber.join(stalled)).detail).toBe("Jira could not be reached."); }), ); }); diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts index 53ac5d0b31936..814466ed21f19 100644 --- a/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts @@ -37,7 +37,7 @@ const DESCRIPTOR: StandaloneIssueTrackerDescriptor = { fields: [ { key: "site", label: "Site (example.atlassian.net)", secret: false }, { key: "email", label: "Email", secret: false }, - { key: "token", label: "API token", secret: true }, + { key: "token", label: "API token (without scopes)", secret: true }, ], }, }; diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.test.ts b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts index c969987fab2a2..81f5186952dc1 100644 --- a/packages/issue-tracker-jira/src/server/jiraAdf.test.ts +++ b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; -import { adfToMarkdown, markdownToAdf } from "./jiraAdf.ts"; +import { adfToMarkdown, hasJiraOnlyContent, markdownToAdf } from "./jiraAdf.ts"; const text = (value: string, marks?: ReadonlyArray) => marks === undefined ? { type: "text", text: value } : { type: "text", text: value, marks }; @@ -115,5 +115,32 @@ describe("jiraAdf", () => { it("keeps a document's text through a round trip", () => { const markdown = "Fix **this** and ~~that~~.\n\n- one\n- two\n\n```\nraw\n```"; expect(adfToMarkdown(markdownToAdf(markdown))).toBe(markdown); + // Literal Markdown characters and a fence inside code stay what Jira stored. + const literal = { + type: "doc", + version: 1, + content: [ + { type: "paragraph", content: [text("**draft** 2. [x]"), text("a`b", [{ type: "code" }])] }, + { type: "paragraph", content: [text("1. not a list")] }, + { type: "codeBlock", content: [text("```\nstill code")] }, + ], + }; + expect(markdownToAdf(adfToMarkdown(literal))).toEqual(literal); + }); + + it("reads reference links, and treats merged table cells as Jira-only", () => { + expect(markdownToAdf("[Guide][g]\n\n[g]: https://x.test").content).toEqual([ + { + type: "paragraph", + content: [text("Guide", [{ type: "link", attrs: { href: "https://x.test" } }])], + }, + ]); + const cell = (attrs?: Record) => ({ + type: "table", + content: [{ type: "tableRow", content: [{ type: "tableHeader", ...(attrs && { attrs }) }] }], + }); + expect(hasJiraOnlyContent({ type: "doc", content: [cell({ colspan: 1 })] })).toBe(false); + expect(hasJiraOnlyContent({ type: "doc", content: [cell({ colspan: 2 })] })).toBe(true); + expect(hasJiraOnlyContent({ type: "doc", content: [cell({ rowspan: 3 })] })).toBe(true); }); }); diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.ts b/packages/issue-tracker-jira/src/server/jiraAdf.ts index ab470d13011ea..c0d121b44dcac 100644 --- a/packages/issue-tracker-jira/src/server/jiraAdf.ts +++ b/packages/issue-tracker-jira/src/server/jiraAdf.ts @@ -37,11 +37,27 @@ function inline(nodes: ReadonlyArray | undefined): string { return (nodes ?? []).map(inlineNode).join(""); } +/** Literal Jira text, escaped so Markdown reads it back as the same characters. */ +const escape = (text: string) => + text + .replace(/[\\`*_~[\]<&]/g, "\\$&") + .replace(/^(\s*)([#>+=-])/gm, "$1\\$2") + .replace(/^(\s*\d+)([.)])/gm, "$1\\$2"); + +/** The shortest run of backticks that `text` does not contain, at least `min` long. */ +const fence = (text: string, min: number) => + "`".repeat(Math.max(min, ...Array.from(text.matchAll(/`+/g), (run) => run[0].length + 1))); + function marked(text: string, marks: ReadonlyArray | undefined): string { - let out = text; + const code = marks?.some((mark) => mark.type === "code") ?? false; + let out = code ? text : escape(text); + if (code) { + const ticks = fence(text, 1); + const pad = text.startsWith("`") || text.endsWith("`") ? " " : ""; + out = `${ticks}${pad}${out}${pad}${ticks}`; + } for (const mark of marks ?? []) { - if (mark.type === "code") out = `\`${out}\``; - else if (mark.type === "strong") out = `**${out}**`; + if (mark.type === "strong") out = `**${out}**`; else if (mark.type === "em") out = `*${out}*`; else if (mark.type === "strike") out = `~~${out}~~`; } @@ -134,8 +150,11 @@ function block(node: AdfNode): string { return list(node, false); case "orderedList": return list(node, true); - case "codeBlock": - return `\`\`\`${attr(node, "language") ?? ""}\n${inline(node.content)}\n\`\`\``; + case "codeBlock": { + const code = (node.content ?? []).map((child) => child.text ?? "").join(""); + const ticks = fence(code, 3); + return `${ticks}${attr(node, "language") ?? ""}\n${code}\n${ticks}`; + } case "blockquote": case "panel": return blocks(node.content) @@ -185,6 +204,8 @@ export function hasJiraOnlyContent(document: unknown): boolean { if (!isNode(document)) return false; const visit = (node: AdfNode): boolean => JIRA_ONLY.has(node.type) || + Number(node.attrs?.["colspan"] ?? 1) > 1 || + Number(node.attrs?.["rowspan"] ?? 1) > 1 || (node.marks ?? []).some((mark) => mark.type !== "link" && !MARKDOWN_MARKS.has(mark.type)) || (node.content ?? []).some((child) => isNode(child) && visit(child)); return visit(document); @@ -340,11 +361,31 @@ function blockFromMdast(node: Mdast.RootContent): AdfNode[] { } } +/** Reference links as the inline links they stand for, since ADF has no definitions. */ +function resolveReferences(node: Mdast.Nodes, definitions: ReadonlyMap): void { + if (!("children" in node)) return; + node.children = node.children.map((child) => { + const url = "identifier" in child ? definitions.get(child.identifier) : undefined; + if (child.type === "linkReference" && url !== undefined) + return { type: "link", url, children: child.children }; + if (child.type === "imageReference" && url !== undefined) + return { type: "image", url, alt: child.alt ?? null }; + return child; + }) as typeof node.children; + for (const child of node.children) resolveReferences(child, definitions); +} + /** Markdown as a Jira document, the way Jira's own editor would have stored it. */ export function markdownToAdf(markdown: string) { const tree = fromMarkdown(markdown, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()], }); + const definitions = new Map( + tree.children.flatMap((child) => + child.type === "definition" ? [[child.identifier, child.url] as const] : [], + ), + ); + resolveReferences(tree, definitions); return { type: "doc", version: 1, content: tree.children.flatMap(blockFromMdast) }; } From 889f4bbd72be495fd317096b647806260a62d80e Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:46:53 +0100 Subject: [PATCH 3/8] fix(issues): a repeated Markdown link definition keeps its first URL Co-Authored-By: Claude Opus 5.5 --- .../issue-tracker-jira/src/server/jiraAdf.test.ts | 14 ++++++++------ packages/issue-tracker-jira/src/server/jiraAdf.ts | 11 ++++++----- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.test.ts b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts index 81f5186952dc1..d569e3da0ad6e 100644 --- a/packages/issue-tracker-jira/src/server/jiraAdf.test.ts +++ b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts @@ -129,12 +129,14 @@ describe("jiraAdf", () => { }); it("reads reference links, and treats merged table cells as Jira-only", () => { - expect(markdownToAdf("[Guide][g]\n\n[g]: https://x.test").content).toEqual([ - { - type: "paragraph", - content: [text("Guide", [{ type: "link", attrs: { href: "https://x.test" } }])], - }, - ]); + expect(markdownToAdf("[Guide][g]\n\n[g]: https://x.test\n[g]: https://y.test").content).toEqual( + [ + { + type: "paragraph", + content: [text("Guide", [{ type: "link", attrs: { href: "https://x.test" } }])], + }, + ], + ); const cell = (attrs?: Record) => ({ type: "table", content: [{ type: "tableRow", content: [{ type: "tableHeader", ...(attrs && { attrs }) }] }], diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.ts b/packages/issue-tracker-jira/src/server/jiraAdf.ts index c0d121b44dcac..096c920f7dfee 100644 --- a/packages/issue-tracker-jira/src/server/jiraAdf.ts +++ b/packages/issue-tracker-jira/src/server/jiraAdf.ts @@ -381,11 +381,12 @@ export function markdownToAdf(markdown: string) { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()], }); - const definitions = new Map( - tree.children.flatMap((child) => - child.type === "definition" ? [[child.identifier, child.url] as const] : [], - ), - ); + // The first definition of an identifier wins, as in CommonMark. + const definitions = new Map(); + for (const child of tree.children) { + if (child.type === "definition" && !definitions.has(child.identifier)) + definitions.set(child.identifier, child.url); + } resolveReferences(tree, definitions); return { type: "doc", version: 1, content: tree.children.flatMap(blockFromMdast) }; } From 011db7c913a255353e6c7731b4e20e502f364b77 Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:23:25 +0100 Subject: [PATCH 4/8] fix(issues): a Markdown link definition inside a quote or list applies too Co-Authored-By: Claude Opus 5.5 --- packages/issue-tracker-jira/src/server/jiraAdf.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.ts b/packages/issue-tracker-jira/src/server/jiraAdf.ts index 096c920f7dfee..d14ff54efbd39 100644 --- a/packages/issue-tracker-jira/src/server/jiraAdf.ts +++ b/packages/issue-tracker-jira/src/server/jiraAdf.ts @@ -381,12 +381,14 @@ export function markdownToAdf(markdown: string) { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()], }); - // The first definition of an identifier wins, as in CommonMark. + // A definition anywhere applies to the whole document; the first one of an identifier wins. const definitions = new Map(); - for (const child of tree.children) { - if (child.type === "definition" && !definitions.has(child.identifier)) - definitions.set(child.identifier, child.url); - } + const collect = (node: Mdast.Nodes): void => { + if (node.type === "definition" && !definitions.has(node.identifier)) + definitions.set(node.identifier, node.url); + if ("children" in node) node.children.forEach(collect); + }; + collect(tree); resolveReferences(tree, definitions); return { type: "doc", version: 1, content: tree.children.flatMap(blockFromMdast) }; } From 26663cf11b36d062072730c53da9f18bab95b079 Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:33:17 +0100 Subject: [PATCH 5/8] test(issues): keep one Jira test per behavior Co-Authored-By: Claude Opus 5.5 --- .../client-runtime/src/issueLinks.test.ts | 1 - .../src/server/JiraIssueTracker.test.ts | 319 ++++-------------- .../src/server/jiraAdf.test.ts | 148 ++------ 3 files changed, 100 insertions(+), 368 deletions(-) diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index a7acdcad4ff3b..37d32d0ed4d5c 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -145,7 +145,6 @@ describe("resolveIssueLinkTarget", () => { expect(resolve(upper.slice(4))?.ref.key).toBe("ENG-4"); // Project keys repeat across sites; only the connected one's links are its issues. expect(resolve("https://othercorp.atlassian.net/browse/ENG-4")).toBeNull(); - expect(resolve("https://acme.atlassian.net.evil.example/browse/ENG-4")).toBeNull(); }); it.each([ diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts index 280cd53f447ca..73d47d3dd38d1 100644 --- a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts @@ -5,7 +5,6 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse, UrlParams } from "effect/http"; -import { IssueTrackerKind } from "@t3tools/contracts"; import type { StandaloneIssueTrackerApi } from "@t3tools/source-control-core/server/IssueTracker"; import * as IssueTrackerHost from "@t3tools/source-control-core/server/IssueTrackerHost"; @@ -14,15 +13,11 @@ import * as JiraIssueTracker from "./JiraIssueTracker.ts"; const STORED = JSON.stringify({ site: "acme", email: "julius@acme.test", token: "tok" }); -const user = (accountId: string, displayName: string) => ({ - accountId, - displayName, - avatarUrls: { "48x48": `https://avatar.test/${accountId}` }, -}); +const user = (accountId: string, displayName: string) => ({ accountId, displayName }); const JULIUS = user("5b10a2844c20165700ede21g", "Julius"); const THEO = user("5b10ac8d82e05b22cc7d4ef5", "Theo"); -const status = (name: string, category: "new" | "indeterminate" | "done") => ({ +const status = (name: string, category: "indeterminate" | "done") => ({ id: `st_${name}`, name, statusCategory: { key: category }, @@ -115,42 +110,28 @@ function fakeJira( } const target = { cwd: "/w/web", host: "atlassian.net", scope: "ENG" }; - describe("JiraIssueTracker", () => { - it.effect("parses Jira Cloud issue links with their site and project", () => + it.effect("parses only Jira Cloud issue links", () => Effect.gen(function* () { const api = yield* fakeJira({}).tracker; - for (const suffix of ["", "/", "?focusedCommentId=10#comment"]) { - expect( - api.parseIssueUrl(new URL(`https://acme.atlassian.net/browse/ENG-12${suffix}`)), - ).toEqual({ - host: "atlassian.net", - workspace: "acme", - scope: "ENG", - key: "ENG-12", - }); - } + expect( + api.parseIssueUrl(new URL("https://acme.atlassian.net/browse/ENG-12?focusedCommentId=1")), + ).toEqual({ host: "atlassian.net", workspace: "acme", scope: "ENG", key: "ENG-12" }); for (const url of [ - "http://acme.atlassian.net/browse/ENG-12", "https://acme.atlassian.net:444/browse/ENG-12", - "https://atlassian.net/browse/ENG-12", "https://acme.atlassian.net.evil.test/browse/ENG-12", - "https://acme.atlassian.net/browse/eng-12", - "https://acme.atlassian.net/browse/ENG-0", "https://acme.atlassian.net/browse/ENG-12/extra", - "https://acme.atlassian.net/jira/software/projects/ENG/boards/1", ]) { expect(api.parseIssueUrl(new URL(url)), url).toBeNull(); } }), ); - it.effect("vets a credential before it is stored, against its own site only", () => + it.effect("vets a credential against its own site, reading every project page", () => Effect.gen(function* () { const { tracker, requests } = fakeJira( { "GET /myself": () => JULIUS, - // A site's projects arrive in pages; every page is read. "GET /project/search": (seen) => seen.params.get("startAt") === "0" ? { isLast: false, values: [{ id: "1", key: "ENG", name: "Engineering" }] } @@ -159,13 +140,11 @@ describe("JiraIssueTracker", () => { null, ); const api = yield* tracker; - expect(api.kind).toBe(IssueTrackerKind.make("jira")); - expect(api.standalone).toMatchObject({ host: "atlassian.net", scopeNoun: "project" }); const probe = yield* api.probeCredential( JSON.stringify({ site: "https://ACME.atlassian.net/", - email: " julius@acme.test ", - token: "tok", + email: "julius@acme.test", + token: "t", }), ); expect(probe).toEqual({ @@ -176,16 +155,12 @@ describe("JiraIssueTracker", () => { { key: "OPS", name: "Operations" }, ], }); - expect(requests[0]?.authorization).toBe(`Basic ${btoa("julius@acme.test:tok")}`); + expect(requests[0]?.authorization).toBe(`Basic ${btoa("julius@acme.test:t")}`); // A site that is not a Jira Cloud subdomain is never asked anything. - for (const site of ["evil.test", "acme.atlassian.net.evil.test", "acme/../x"]) { - const refused = yield* Effect.flip( - api.probeCredential(JSON.stringify({ site, email: "a@b.c", token: "t" })), - ); - expect(refused.reason).toBe("unauthenticated"); - } - const notConnected = yield* Effect.flip(api.getViewer({ cwd: "", host: "atlassian.net" })); - expect(notConnected.reason).toBe("unauthenticated"); + const refused = yield* Effect.flip( + api.probeCredential(JSON.stringify({ site: "acme/../x", email: "a@b.c", token: "t" })), + ); + expect(refused.reason).toBe("unauthenticated"); expect(requests).toHaveLength(3); }), ); @@ -195,13 +170,7 @@ describe("JiraIssueTracker", () => { const { tracker, requests } = fakeJira({ "GET /user/assignable/search": () => [THEO], "POST /search/jql": () => ({ - issues: [ - issue("ENG-2", { - status: status("Done", "done"), - resolutiondate: "2026-07-03T10:00:00.000+0000", - }), - issue("ENG-1"), - ], + issues: [issue("ENG-2", { status: status("Done", "done") })], nextPageToken: "tok_2", }), }); @@ -212,49 +181,18 @@ describe("JiraIssueTracker", () => { viewer: "Julius", state: "open", limit: 25, - query: 'say "hi" \\ 12', - labels: ["bug"], + query: 'say "hi" 7', assignee: "Theo", sort: "created", }); - const search = requests.find((request) => request.path === "/search/jql"); - expect(search?.body).toMatchObject({ + expect(requests.at(-1)?.body).toMatchObject({ jql: 'project = "ENG" AND statusCategory != Done AND assignee = currentUser() AND ' + - `assignee = "${THEO.accountId}" AND labels = "bug" AND text ~ "say \\"hi\\" \\\\ 12" ` + - "ORDER BY created DESC", - maxResults: 25, + `assignee = "${THEO.accountId}" AND text ~ "say \\"hi\\" 7" ORDER BY created DESC`, }); expect(page.nextCursor).toBe("tok_2"); - expect(page.items[0]).toMatchObject({ - key: "ENG-2", - displayKey: "ENG-2", - url: "https://acme.atlassian.net/browse/ENG-2", - state: { category: "closed", name: "Done", closeReason: "completed" }, - closedAt: "2026-07-03T10:00:00.000Z", - author: { login: "Julius", name: "Julius" }, - assignees: [{ login: "Theo" }], - labels: [{ name: "bug", color: null }], - }); - expect(page.items[1]?.closedAt).toBeNull(); - - // A bare number also finds the issue by key; the cursor carries on. - yield* api.listIssues({ - ...target, - involvement: "all", - state: "all", - limit: 10, - query: "#7", - sort: "updated", - cursor: "tok_2", - }); - expect(requests.at(-1)?.body).toEqual( - expect.objectContaining({ - jql: 'project = "ENG" AND (text ~ "#7" OR key = "ENG-7") ORDER BY updated DESC', - nextPageToken: "tok_2", - }), - ); - const refused = yield* Effect.flip( + expect(page.items[0]?.state).toMatchObject({ category: "closed", name: "Done" }); + const injected = yield* Effect.flip( api.listIssues({ ...target, scope: 'ENG" OR project = "OPS', @@ -264,7 +202,7 @@ describe("JiraIssueTracker", () => { sort: "updated", }), ); - expect(refused.detail).toContain("not a Jira project key"); + expect(injected.detail).toContain("not a Jira project key"); }), ); @@ -273,15 +211,7 @@ describe("JiraIssueTracker", () => { const { tracker, requests } = fakeJira({ "GET /myself": () => JULIUS, "GET /issue/ENG-1": () => ({ - ...issue("ENG-1", { - description: doc( - { type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Steps" }] }, - { - type: "bulletList", - content: [{ type: "listItem", content: [paragraph("Open it")] }], - }, - ), - }), + ...issue("ENG-1", { description: doc(paragraph("Steps")) }), changelog: { histories: [ { @@ -290,78 +220,38 @@ describe("JiraIssueTracker", () => { created: "2026-07-01T11:00:00.000+0000", items: [ { field: "status", fromString: "To Do", toString: "In Progress" }, - { field: "labels", fromString: "old", toString: "bug ui" }, - { field: "assignee", fromString: null, toString: "Theo" }, - { field: "Sprint", fromString: null, toString: "Sprint 4" }, + { field: "labels", fromString: "old", toString: "bug" }, ], }, ], }, - transitions: [ - { id: "31", to: status("Done", "done") }, - { id: "11", to: status("To Do", "new") }, - { id: "21", to: status("In Progress", "indeterminate") }, - ], + transitions: [{ id: "31", to: status("Done", "done") }], }), "GET /issue/ENG-1/comment": (seen) => { - expect(seen.params.get("orderBy")).toBe("-created"); const startAt = Number(seen.params.get("startAt")); - return { - startAt, - total: 51, - comments: [ - { - id: `c${startAt + 2}`, - author: THEO, - body: doc(paragraph("newest")), - created: "2026-07-02T09:00:00.000+0000", - }, - { - id: `c${startAt + 1}`, - author: JULIUS, - body: doc(paragraph("older")), - created: "2026-07-01T09:00:00.000+0000", - }, - ], - }; + const comment = (n: number) => ({ + id: `c${n}`, + author: THEO, + body: doc(paragraph(`comment ${n}`)), + created: "2026-07-02T09:00:00.000+0000", + }); + return { startAt, total: 51, comments: [comment(startAt + 2), comment(startAt + 1)] }; }, }); const api = yield* tracker; const detail = yield* api.getIssue({ ...target, key: "eng-1" }); - expect(detail).toMatchObject({ - key: "ENG-1", - body: "## Steps\n\n- Open it", - viewer: "Julius", - commentCount: 51, - linkedPullRequests: [], - }); - expect(detail.comments.map((comment) => [comment.id, comment.body])).toEqual([ - ["c1", "older"], - ["c2", "newest"], - ]); - expect(detail.comments[0]?.url).toBe( - "https://acme.atlassian.net/browse/ENG-1?focusedCommentId=c1", - ); + expect(detail).toMatchObject({ key: "ENG-1", body: "Steps", viewer: "Julius" }); + expect(detail.comments.map((comment) => comment.id)).toEqual(["c1", "c2"]); expect(detail.commentsCursor).toBe("2"); - expect(detail.states.map((state) => [state.name, state.category])).toEqual([ - ["In Progress", "open"], - ["Done", "closed"], - ["To Do", "open"], - ]); + expect(detail.states.map((state) => state.name)).toEqual(["In Progress", "Done"]); expect(detail.events.map((event) => [event.kind, event.detail])).toEqual([ ["state-changed", "In Progress"], ["labeled", "bug"], - ["labeled", "ui"], ["unlabeled", "old"], - ["assigned", "Theo"], ]); - const older = yield* api.getComments({ ...target, key: "ENG-1", cursor: "2" }); - expect(requests.at(-1)?.params.get("startAt")).toBe("2"); + expect(requests.at(-1)?.params.get("orderBy")).toBe("-created"); expect(older.comments.map((comment) => comment.id)).toEqual(["c3", "c4"]); - expect(older.nextCursor).toBe("4"); - const bad = yield* Effect.flip(api.getComments({ ...target, key: "ENG-1", cursor: "x" })); - expect(bad.detail).toContain("cursor"); }), ); @@ -375,60 +265,45 @@ describe("JiraIssueTracker", () => { }), "GET /issue/OPS-3": () => issue("OPS-3"), "GET /issue/ENG-5": () => - issue("ENG-5", { - description: doc({ - type: "mediaSingle", - content: [{ type: "media", attrs: { id: "m" } }], - }), - }), - "GET /issue/ENG-9": () => - new Response(JSON.stringify({ errorMessages: ["Issue does not exist"] }), { - status: 404, - }), + issue("ENG-5", { description: doc({ type: "mediaSingle", content: [] }) }), "PUT /issue/ENG-1": (seen) => void writes.push(seen), - "PUT /issue/ENG-5": (seen) => void writes.push(seen), "POST /issue/ENG-1/comment": (seen) => void writes.push(seen), "POST /issue/ENG-1/transitions": (seen) => void writes.push(seen), "GET /user/assignable/search": () => [THEO, user("5b10ac8d82e05b22cc7d4ef6", "Theo")], + "GET /issue/createmeta/ENG/issuetypes": () => ({ + issueTypes: [ + { id: "5", name: "Sub-task", subtask: true }, + { id: "10001", name: "Task", subtask: false }, + ], + }), + "POST /issue": (seen) => { + writes.push(seen); + return { id: "100", key: "ENG-42" }; + }, }); const api = yield* tracker; // A key from another project resolves in Jira, so the project is checked before writing. const foreign = yield* Effect.flip(api.comment({ ...target, key: "OPS-3", body: "hi" })); - expect(foreign.detail).toContain("OPS"); - const missing = yield* Effect.flip(api.comment({ ...target, key: "ENG-9", body: "hi" })); - expect(missing.reason).toBe("not-found"); - - yield* api.comment({ ...target, key: "ENG-1", body: "**Done** in `main`" }); - yield* api.update({ - ...target, - key: "ENG-1", - title: "Renamed", - body: "", - labels: ["bug", "ui"], - assignees: [THEO.accountId], - }); - yield* api.setState({ ...target, key: "ENG-1", state: "Done" }); - const unknown = yield* Effect.flip( - api.setState({ ...target, key: "ENG-1", state: "closed" }), - ); - expect(unknown.detail).toContain('to "closed"'); + expect(foreign.detail).toBe("OPS-3 belongs to Jira project OPS, not ENG."); // Its attachment would not survive the Markdown round trip, so the body is not rewritten. const attached = yield* Effect.flip(api.update({ ...target, key: "ENG-5", body: "new" })); expect(attached.detail).toContain("Edit it in Jira"); - yield* api.update({ ...target, key: "ENG-5", title: "Still renamable" }); - const spaced = yield* Effect.flip( - api.update({ ...target, key: "ENG-1", labels: ["two words"] }), - ); - expect(spaced.detail).toContain("spaces"); - const two = yield* Effect.flip( - api.update({ ...target, key: "ENG-1", assignees: ["a", "b"] }), - ); - expect(two.detail).toContain("one assignee"); const ambiguous = yield* Effect.flip( api.update({ ...target, key: "ENG-1", assignees: ["Theo"] }), ); expect(ambiguous.detail).toContain("More than one"); + yield* api.comment({ ...target, key: "ENG-1", body: "**Done**" }); + yield* api.update({ ...target, key: "ENG-1", title: "Renamed", assignees: [THEO.accountId] }); + yield* api.setState({ ...target, key: "ENG-1", state: "Done" }); + const created = yield* api.create({ + ...target, + title: "New", + body: "", + labels: [], + assignees: [], + }); + expect(created.url).toBe("https://acme.atlassian.net/browse/ENG-42"); expect(writes.map((write) => [write.method, write.path, write.body])).toEqual([ [ "POST", @@ -436,87 +311,25 @@ describe("JiraIssueTracker", () => { { body: doc({ type: "paragraph", - content: [ - { type: "text", text: "Done", marks: [{ type: "strong" }] }, - { type: "text", text: " in " }, - { type: "text", text: "main", marks: [{ type: "code" }] }, - ], + content: [{ type: "text", text: "Done", marks: [{ type: "strong" }] }], }), }, ], [ "PUT", "/issue/ENG-1", - { - fields: { - summary: "Renamed", - description: null, - labels: ["bug", "ui"], - assignee: { accountId: THEO.accountId }, - }, - }, + { fields: { summary: "Renamed", assignee: { accountId: THEO.accountId } } }, ], ["POST", "/issue/ENG-1/transitions", { transition: { id: "31" } }], - ["PUT", "/issue/ENG-5", { fields: { summary: "Still renamable" } }], + [ + "POST", + "/issue", + { fields: { project: { key: "ENG" }, issuetype: { id: "10001" }, summary: "New" } }, + ], ]); }), ); - it.effect("files a new issue under the project's first standard issue type", () => - Effect.gen(function* () { - let created: unknown; - const { tracker } = fakeJira({ - "GET /issue/createmeta/ENG/issuetypes": () => ({ - issueTypes: [ - { id: "5", name: "Sub-task", subtask: true }, - { id: "10001", name: "Task", subtask: false }, - ], - }), - "POST /issue": (seen) => { - created = seen.body; - return { id: "100", key: "ENG-42" }; - }, - }); - const api = yield* tracker; - const result = yield* api.create({ - ...target, - title: "New", - body: "- [ ] first", - labels: [], - assignees: [], - }); - expect(result).toEqual({ - key: "ENG-42", - displayKey: "ENG-42", - url: "https://acme.atlassian.net/browse/ENG-42", - }); - expect(created).toEqual({ - fields: { - project: { key: "ENG" }, - issuetype: { id: "10001" }, - summary: "New", - description: doc({ - type: "bulletList", - content: [ - { - type: "listItem", - content: [ - { - type: "paragraph", - content: [ - { type: "text", text: "[ ] " }, - { type: "text", text: "first" }, - ], - }, - ], - }, - ], - }), - }, - }); - }), - ); - it.effect("maps Jira's refusals to the tracker's failure reasons", () => Effect.gen(function* () { const { tracker } = fakeJira({ @@ -536,12 +349,12 @@ describe("JiraIssueTracker", () => { const limited = yield* Effect.flip( api.listIssues({ ...target, involvement: "all", state: "all", limit: 1, sort: "updated" }), ); - expect(limited.reason).toBe("rate-limited"); expect(limited.retryAt).toBeGreaterThan(0); const refused = yield* Effect.flip( api.create({ ...target, title: "x", body: "", labels: [], assignees: [] }), ); expect(refused.detail).toBe("You cannot create issues here."); + // A reply that sends its headers and then stalls still ends at the deadline. const stalled = yield* Effect.forkChild( Effect.flip(api.getIssue({ ...target, key: "ENG-1" })), ); diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.test.ts b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts index d569e3da0ad6e..fb40b536ac789 100644 --- a/packages/issue-tracker-jira/src/server/jiraAdf.test.ts +++ b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts @@ -4,145 +4,65 @@ import { adfToMarkdown, hasJiraOnlyContent, markdownToAdf } from "./jiraAdf.ts"; const text = (value: string, marks?: ReadonlyArray) => marks === undefined ? { type: "text", text: value } : { type: "text", text: value, marks }; +const doc = (...content: ReadonlyArray) => ({ type: "doc", version: 1, content }); +const paragraph = (...content: ReadonlyArray) => ({ type: "paragraph", content }); +const item = (...content: ReadonlyArray) => ({ type: "listItem", content }); +const link = { type: "link", attrs: { href: "https://x.test" } }; describe("jiraAdf", () => { it("reads a Jira document as Markdown, naming what Markdown cannot hold", () => { expect( - adfToMarkdown({ - type: "doc", - version: 1, - content: [ - { - type: "paragraph", - content: [ - text("See "), - text("the guide", [ - { type: "link", attrs: { href: "https://x.test" } }, - { type: "strong" }, - ]), - { type: "hardBreak" }, - { type: "mention", attrs: { id: "abc", text: "@Theo" } }, - ], - }, + adfToMarkdown( + doc( + paragraph(text("the guide", [link, { type: "strong" }]), { + type: "mention", + attrs: { text: "@Theo" }, + }), { type: "orderedList", attrs: { order: 3 }, content: [ - { type: "listItem", content: [{ type: "paragraph", content: [text("three")] }] }, - { - type: "listItem", - content: [ - { type: "paragraph", content: [text("four")] }, - { - type: "bulletList", - content: [ - { - type: "listItem", - content: [{ type: "paragraph", content: [text("nested")] }], - }, - ], - }, - ], - }, - ], - }, - { type: "codeBlock", attrs: { language: "ts" }, content: [text("const a = 1;")] }, - { - type: "table", - content: [ - { - type: "tableRow", - content: [ - { type: "tableHeader", content: [{ type: "paragraph", content: [text("a|b")] }] }, - ], - }, - { - type: "tableRow", - content: [ - { type: "tableCell", content: [{ type: "paragraph", content: [text("1")] }] }, - ], - }, + item(paragraph(text("three")), { + type: "bulletList", + content: [item(paragraph(text("nested")))], + }), ], }, { type: "mediaSingle", content: [{ type: "media", attrs: { id: "m1" } }] }, - ], - }), + ), + ), ).toBe( - [ - "See [**the guide**](https://x.test)\n@Theo", - "3. three\n4. four\n - nested", - "```ts\nconst a = 1;\n```", - "| a\\|b |\n| --- |\n| 1 |", - "_(attachment, open in Jira to view)_", - ].join("\n\n"), + "[**the guide**](https://x.test)@Theo\n\n3. three\n - nested\n\n_(attachment, open in Jira to view)_", ); - expect(adfToMarkdown(null)).toBe(""); - expect(adfToMarkdown({ type: "doc", version: 1, content: [] })).toBe(""); }); it("writes Markdown as the document Jira's editor would have stored", () => { + // Jira allows only a link beside a code mark; the first definition of a reference wins. expect( - markdownToAdf("# Title\n\n> quoted *text*\n\n1. one\n\n---\n\n[`code` link](https://x.test)"), - ).toEqual({ - type: "doc", - version: 1, - content: [ - { type: "heading", attrs: { level: 1 }, content: [text("Title")] }, - { - type: "blockquote", - content: [ - { type: "paragraph", content: [text("quoted "), text("text", [{ type: "em" }])] }, - ], - }, - { - type: "orderedList", - content: [{ type: "listItem", content: [{ type: "paragraph", content: [text("one")] }] }], - }, - { type: "rule" }, - { - type: "paragraph", - content: [ - // Jira allows only a link beside a code mark. - text("code", [{ type: "link", attrs: { href: "https://x.test" } }, { type: "code" }]), - text(" link", [{ type: "link", attrs: { href: "https://x.test" } }]), - ], - }, - ], - }); - expect(markdownToAdf("")).toEqual({ type: "doc", version: 1, content: [] }); + markdownToAdf("[`code` link][g]\n\n> [g]: https://x.test\n\n[g]: https://y.test").content[0], + ).toEqual(paragraph(text("code", [link, { type: "code" }]), text(" link", [link]))); }); it("keeps a document's text through a round trip", () => { const markdown = "Fix **this** and ~~that~~.\n\n- one\n- two\n\n```\nraw\n```"; expect(adfToMarkdown(markdownToAdf(markdown))).toBe(markdown); // Literal Markdown characters and a fence inside code stay what Jira stored. - const literal = { - type: "doc", - version: 1, - content: [ - { type: "paragraph", content: [text("**draft** 2. [x]"), text("a`b", [{ type: "code" }])] }, - { type: "paragraph", content: [text("1. not a list")] }, - { type: "codeBlock", content: [text("```\nstill code")] }, - ], - }; + const literal = doc( + paragraph(text("**draft** [x]"), text("a`b", [{ type: "code" }])), + paragraph(text("1. not a list")), + { type: "codeBlock", content: [text("```\nstill code")] }, + ); expect(markdownToAdf(adfToMarkdown(literal))).toEqual(literal); }); - it("reads reference links, and treats merged table cells as Jira-only", () => { - expect(markdownToAdf("[Guide][g]\n\n[g]: https://x.test\n[g]: https://y.test").content).toEqual( - [ - { - type: "paragraph", - content: [text("Guide", [{ type: "link", attrs: { href: "https://x.test" } }])], - }, - ], - ); - const cell = (attrs?: Record) => ({ - type: "table", - content: [{ type: "tableRow", content: [{ type: "tableHeader", ...(attrs && { attrs }) }] }], - }); - expect(hasJiraOnlyContent({ type: "doc", content: [cell({ colspan: 1 })] })).toBe(false); - expect(hasJiraOnlyContent({ type: "doc", content: [cell({ colspan: 2 })] })).toBe(true); - expect(hasJiraOnlyContent({ type: "doc", content: [cell({ rowspan: 3 })] })).toBe(true); + it("treats only what Markdown would lose as Jira-only", () => { + const table = (attrs: Record) => + doc({ + type: "table", + content: [{ type: "tableRow", content: [{ type: "tableHeader", attrs }] }], + }); + expect(hasJiraOnlyContent(table({ colspan: 1 }))).toBe(false); + expect(hasJiraOnlyContent(table({ colspan: 2 }))).toBe(true); + expect(hasJiraOnlyContent(doc(paragraph(text("x", [{ type: "textColor" }]))))).toBe(true); }); }); From 28871bab71463b0b1dac43108d732c0d4bf868af Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:42:54 +0100 Subject: [PATCH 6/8] feat(issues): Jira settings match Linear's rows and show linked pull requests The Jira credential form now uses one Settings row per field (site, email, API token), laid out like Linear's key row. It sends on Enter or when a field is left, and Enter retries a failed attempt. Mobile labels each field. Jira issues now list the pull requests from Jira's Development panel. They open in the browser, the same as Linear's, because the issue's host is not the PR's host. A site that is not a Jira site now says so, not "no such issue". --- .../src/features/issues/IssueRouteScreen.tsx | 9 +- .../components/IssueTrackerSection.tsx | 31 ++- .../src/components/issue/IssueDetailPanel.tsx | 8 +- .../settings/IssueTrackerSettings.tsx | 196 ++++++++++-------- docs/user/source-control.md | 5 +- .../src/issuePresentation.test.ts | 8 +- .../client-runtime/src/issuePresentation.ts | 10 + packages/contracts/src/issue.ts | 1 + .../issue-tracker-jira/src/server/JiraApi.ts | 78 ++++++- .../src/server/JiraIssueTracker.test.ts | 31 +++ .../src/server/JiraIssueTracker.ts | 54 ++++- 11 files changed, 314 insertions(+), 117 deletions(-) diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 874ecfba20b6d..d7db0b665206d 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -1,7 +1,9 @@ import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; -import { issueEventSentence } from "@t3tools/client-runtime/issue-presentation"; -import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; +import { + issueEventSentence, + issueLinksOpenInApp, +} from "@t3tools/client-runtime/issue-presentation"; import { createIssueCommentPager } from "@t3tools/client-runtime/state/issues"; import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; import type { @@ -249,8 +251,7 @@ function LinkedPullRequests(props: { }) { const gt = useGT(); const navigation = useNavigation(); - // Only a git host's tracker shares its host with the change request it links. - const sameHost = sourceControlClients.find(props.params.tracker) !== undefined; + const sameHost = issueLinksOpenInApp(props.params.tracker); return ( diff --git a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx index e2059ddff96b0..e52a237b5693b 100644 --- a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx +++ b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx @@ -196,21 +196,30 @@ export function IssueTrackerCredentialForm(props: { {fields.map((field) => field.secret ? ( - setDrafts({ ...drafts, [field.key]: value })} - onSubmitEditing={send} - editable={!locked} - /> + + {tracker.credential.fields ? ( + + {field.label} + + ) : null} + setDrafts({ ...drafts, [field.key]: value })} + onSubmitEditing={send} + editable={!locked} + /> + ) : ( onSelectPullRequest({ projectId: reference.projectId, diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx index 5ca7ec78fbcb8..7d374c4801df8 100644 --- a/apps/web/src/components/settings/IssueTrackerSettings.tsx +++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx @@ -6,7 +6,7 @@ import { import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { T, useGT, useMessages } from "gt-react"; import { ChevronDownIcon, ExternalLinkIcon, XIcon } from "lucide-react"; -import { useState, type ElementType } from "react"; +import { useState, type ElementType, type ReactNode } from "react"; import type { EnvironmentId, IssueTrackerConnection, @@ -133,6 +133,37 @@ function TrackerRow({ const usable = tracker.connected && tracker.account !== null; const summary = issueTrackerSummary(tracker, bindings, messages); + const description = ( + <> + Stored on the server. + {tracker.credential.helpUrl ? ( + <> + {" "} + + } + > + Create one + + + + ) : null} + {failure ? {failure} : null} + + ); + const disconnect = tracker.connected ? ( + + ) : null; + return (
@@ -176,41 +207,21 @@ function TrackerRow({ {/* Locked while saving, so an edit made mid-request is not overwritten by the saved value. */}
- {tracker.credential.label}} - description={ - <> - Stored on the server. - {tracker.credential.helpUrl ? ( - <> - {" "} - - } - > - Create one - - - - ) : null} - {failure ? {failure} : null} - - } - control={ -
- {tracker.credential.fields ? ( - - ) : ( + {tracker.credential.fields ? ( + + ) : ( + {tracker.credential.label}} + description={description} + control={ +
- )} - {tracker.connected ? ( - - ) : null} -
- } - /> + {disconnect} +
+ } + /> + )} {usable ? ( ; readonly connected: boolean; + readonly description: ReactNode; + readonly disconnect: ReactNode; readonly onSubmit: (token: string) => Promise; }) { const gt = useGT(); const [drafts, setDrafts] = useState>>({}); + // The last credential sent, so moving between fields does not resend one that just failed. + // Enter always sends, so a failed attempt can be retried as it is. + const [sent, setSent] = useState(null); const token = issueTrackerFieldsToken(fields, drafts); - return ( -
{ - event.preventDefault(); - if (token === null) return; - void onSubmit(token).then((connected) => { - if (connected) setDrafts({}); - }); - }} - > - {fields.map((field) => ( - setDrafts({ ...drafts, [field.key]: event.target.value })} - /> - ))} - -
- ); + const send = (retry: boolean) => { + if (token === null || (!retry && token === sent)) return; + setSent(token); + void onSubmit(token).then((connected) => { + if (!connected) return; + setDrafts({}); + setSent(null); + }); + }; + return fields.map((field) => { + const id = `${idPrefix}-${field.key}`; + return ( + {field.label}} + description={field.secret ? description : undefined} + control={ +
+ setDrafts({ ...drafts, [field.key]: event.target.value })} + onBlur={() => send(false)} + onKeyDown={(event) => { + if (event.key === "Enter" && !event.nativeEvent.isComposing) send(true); + }} + /> + {field.secret ? disconnect : null} +
+ } + /> + ); + }); } /** One picker per project of this environment: which of the tracker's scopes it reads, if any. */ diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 5a71f000300d4..b456840af3fe0 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -380,8 +380,9 @@ Linear takes an API key. Jira takes your site (`example.atlassian.net`), your ac [API token](https://id.atlassian.com/manage-profile/security/api-tokens) created with **Create API token**, not a token with scopes. Jira issues move between statuses through your workflow's transitions. For Jira, "mentioning you" lists the issues you watch. A Jira description with -attachments, mentions or other Jira-only content is edited in Jira. Jira reactions and linked pull -requests are not shown. +attachments, mentions or other Jira-only content is edited in Jira. Jira's linked pull requests come +from the tools connected to its Development panel. Linear's and Jira's linked pull requests open in +the browser. Jira reactions are not shown, because Jira Cloud has no API for them. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/packages/client-runtime/src/issuePresentation.test.ts b/packages/client-runtime/src/issuePresentation.test.ts index a3a7e981e9052..592aa3cc6b9bf 100644 --- a/packages/client-runtime/src/issuePresentation.test.ts +++ b/packages/client-runtime/src/issuePresentation.test.ts @@ -1,7 +1,7 @@ import type { IssueDetail, IssueState } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { issueWriteAccess } from "./issuePresentation.ts"; +import { issueLinksOpenInApp, issueWriteAccess } from "./issuePresentation.ts"; const workflow: ReadonlyArray = [ { category: "open", name: "Backlog" }, @@ -40,3 +40,9 @@ describe("issueWriteAccess", () => { expect(issueWriteAccess(issue({ states: [] }), true).states).toEqual([]); }); }); + +it("opens linked pull requests in the app only for a git host's own tracker", () => { + expect(issueLinksOpenInApp("github")).toBe(true); + expect(issueLinksOpenInApp("jira")).toBe(false); + expect(issueLinksOpenInApp("linear")).toBe(false); +}); diff --git a/packages/client-runtime/src/issuePresentation.ts b/packages/client-runtime/src/issuePresentation.ts index 001e585035ea1..ea945804922a0 100644 --- a/packages/client-runtime/src/issuePresentation.ts +++ b/packages/client-runtime/src/issuePresentation.ts @@ -2,6 +2,8 @@ import type { IssueDetail, IssueEvent } from "@t3tools/contracts"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +import { sourceControlClients } from "./sourceControlClients.ts"; + /** "completed" → "Completed"; a reason the tracker spells with a dash reads as words. */ function issueCloseReasonLabel(reason: string): string { const words = reason.replace(/[-_]+/g, " ").trim(); @@ -80,3 +82,11 @@ export function issueWriteAccess( : [], }; } + +/** + * Whether a tracker's linked pull requests open in the app: only a git host's own tracker shares + * its host with them. A standalone tracker's links (Linear, Jira) open in the browser. + */ +export function issueLinksOpenInApp(tracker: string): boolean { + return sourceControlClients.find(tracker) !== undefined; +} diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index d94017a5604cb..6bb65df4634ed 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -571,6 +571,7 @@ export const StandaloneIssueTrackerDescriptor = Schema.Struct({ Schema.Struct({ key: TrimmedNonEmptyString, label: TrimmedNonEmptyString, + placeholder: Schema.optional(TrimmedNonEmptyString), secret: Schema.Boolean, }), ), diff --git a/packages/issue-tracker-jira/src/server/JiraApi.ts b/packages/issue-tracker-jira/src/server/JiraApi.ts index 138e46d817f81..008ee3ff02547 100644 --- a/packages/issue-tracker-jira/src/server/JiraApi.ts +++ b/packages/issue-tracker-jira/src/server/JiraApi.ts @@ -161,6 +161,30 @@ const Labels = Schema.Struct({ const Created = Schema.Struct({ key: Schema.String }); +/** Jira's development panel: which connected tools (GitHub, GitLab, Bitbucket) hold PRs. */ +const DevelopmentSummary = Schema.Struct({ + summary: Schema.Struct({ + pullrequest: Schema.optional( + Schema.Struct({ + byInstanceType: Schema.Record(Schema.String, Schema.Struct({ count: Schema.Number })), + }), + ), + }), +}); + +export const JiraPullRequest = Schema.Struct({ + name: Schema.String, + url: Schema.String, + status: Schema.optional(Schema.String), +}); +export type JiraPullRequest = typeof JiraPullRequest.Type; + +const DevelopmentDetail = Schema.Struct({ + detail: Schema.Array( + Schema.Struct({ pullRequests: Schema.optional(Schema.Array(JiraPullRequest)) }), + ), +}); + const SUMMARY_FIELDS = [ "summary", "status", @@ -208,6 +232,13 @@ export class JiraApi extends Context.Service< readonly startAt: number; readonly limit: number; }) => Effect.Effect; + /** + * The pull requests Jira's development panel shows for an issue, from every connected tool. + * Jira serves these from an undocumented API, so callers treat a failure as none. + */ + readonly pullRequests: ( + issueId: string, + ) => Effect.Effect, IssueTrackerError>; readonly createIssue: (fields: JiraFields) => Effect.Effect; readonly updateIssue: ( key: string, @@ -316,7 +347,9 @@ export const make = Effect.gen(function* () { >(input: { readonly operation: string; readonly method: "GET" | "POST" | "PUT"; + /** Under the REST API root, unless `api` names another of the site's APIs. */ readonly path: string; + readonly api?: string | undefined; readonly params?: Record | undefined; readonly body?: unknown; /** Null for a call that answers with no body. */ @@ -325,7 +358,7 @@ export const make = Effect.gen(function* () { }): Effect.fn.Return { yield* Effect.annotateCurrentSpan({ "jira.operation": input.operation }); const { site, email, token } = yield* credential(input.operation, input.credential); - const url = `https://${site}.atlassian.net/rest/api/3${input.path}`; + const url = `https://${site}.atlassian.net${input.api ?? "/rest/api/3"}${input.path}`; let request = HttpClientRequest.make(input.method)(url).pipe( HttpClientRequest.acceptJson, HttpClientRequest.basicAuth(email, token), @@ -372,7 +405,16 @@ export const make = Effect.gen(function* () { const probe: JiraApi["Service"]["probe"] = Effect.fn("JiraApi.probe")(function* (given) { const { site } = yield* credential("probe", given); - const user = yield* myself("probe", given); + // A site name that is no Jira site answers 404, which would read as a missing issue. + const user = yield* myself("probe", given).pipe( + Effect.catchIf( + (error) => error.reason === "not-found", + () => + Effect.fail( + fail("probe", "unauthenticated", `${site}.atlassian.net is not a Jira site.`), + ), + ), + ); const projects: Array<{ readonly key: string; readonly name: string }> = []; // shortcut: stops at MAX_PROJECTS, page the picker itself if sites outgrow it. while (projects.length < MAX_PROJECTS) { @@ -486,6 +528,37 @@ export const make = Effect.gen(function* () { }, ); + const pullRequests: JiraApi["Service"]["pullRequests"] = Effect.fn("JiraApi.pullRequests")( + function* (issueId) { + const api = "/rest/dev-status/latest"; + const { summary } = yield* read({ + operation: "pullRequests", + method: "GET", + api, + path: "/issue/summary", + params: { issueId }, + schema: DevelopmentSummary, + }); + const tools = Object.entries(summary.pullrequest?.byInstanceType ?? {}) + .filter(([, tool]) => tool.count > 0) + .map(([applicationType]) => applicationType); + const details = yield* Effect.forEach( + tools, + (applicationType) => + read({ + operation: "pullRequests", + method: "GET", + api, + path: "/issue/detail", + params: { issueId, applicationType, dataType: "pullrequest" }, + schema: DevelopmentDetail, + }), + { concurrency: "unbounded" }, + ); + return details.flatMap(({ detail }) => detail.flatMap((entry) => entry.pullRequests ?? [])); + }, + ); + const issueTypes: JiraApi["Service"]["issueTypes"] = Effect.fn("JiraApi.issueTypes")( function* (project) { const types = yield* read({ @@ -533,6 +606,7 @@ export const make = Effect.gen(function* () { search, getIssue, getComments, + pullRequests, createIssue, updateIssue, addComment, diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts index 73d47d3dd38d1..c27e29a4657fc 100644 --- a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts @@ -162,6 +162,16 @@ describe("JiraIssueTracker", () => { ); expect(refused.reason).toBe("unauthenticated"); expect(requests).toHaveLength(3); + const { tracker: missing } = fakeJira( + { "GET /myself": () => new Response("", { status: 404 }) }, + null, + ); + const unknownSite = yield* Effect.flip( + (yield* missing).probeCredential( + JSON.stringify({ site: "acme", email: "a@b.c", token: "t" }), + ), + ); + expect(unknownSite.detail).toBe("acme.atlassian.net is not a Jira site."); }), ); @@ -237,6 +247,16 @@ describe("JiraIssueTracker", () => { }); return { startAt, total: 51, comments: [comment(startAt + 2), comment(startAt + 1)] }; }, + "GET /rest/dev-status/latest/issue/summary": () => ({ + summary: { + pullrequest: { byInstanceType: { GitHub: { count: 1 }, stash: { count: 0 } } }, + }, + }), + "GET /rest/dev-status/latest/issue/detail": (seen) => { + expect(seen.params.get("applicationType")).toBe("GitHub"); + const pull = { name: "Fix", url: "https://github.com/acme/web/pull/7", status: "MERGED" }; + return { detail: [{ pullRequests: [pull, pull] }] }; + }, }); const api = yield* tracker; const detail = yield* api.getIssue({ ...target, key: "eng-1" }); @@ -244,6 +264,17 @@ describe("JiraIssueTracker", () => { expect(detail.comments.map((comment) => comment.id)).toEqual(["c1", "c2"]); expect(detail.commentsCursor).toBe("2"); expect(detail.states.map((state) => state.name)).toEqual(["In Progress", "Done"]); + expect(detail.linkedPullRequests).toEqual([ + { + repository: "acme/web", + number: 7, + title: "Fix", + url: "https://github.com/acme/web/pull/7", + state: "merged", + isDraft: false, + closesIssue: false, + }, + ]); expect(detail.events.map((event) => [event.kind, event.detail])).toEqual([ ["state-changed", "In Progress"], ["labeled", "bug"], diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts index 814466ed21f19..fddcbf00ff63f 100644 --- a/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts @@ -11,6 +11,7 @@ import type { IssueCapabilities, IssueComment, IssueEvent, + IssueLinkedPullRequest, IssueState, IssueViewerPermissions, StandaloneIssueTrackerDescriptor, @@ -35,14 +36,14 @@ const DESCRIPTOR: StandaloneIssueTrackerDescriptor = { label: "Personal API token", helpUrl: "https://id.atlassian.com/manage-profile/security/api-tokens", fields: [ - { key: "site", label: "Site (example.atlassian.net)", secret: false }, - { key: "email", label: "Email", secret: false }, - { key: "token", label: "API token (without scopes)", secret: true }, + { key: "site", label: "Site", placeholder: "example.atlassian.net", secret: false }, + { key: "email", label: "Email", placeholder: "you@example.com", secret: false }, + { key: "token", label: "API token", placeholder: "Without scopes", secret: true }, ], }, }; -/** Reactions and templates have no public Jira Cloud API; linked PRs live in a private one. */ +/** Reactions and templates have no Jira Cloud API an API token can reach. */ const CAPABILITIES: IssueCapabilities = { create: true, edit: true, @@ -51,7 +52,7 @@ const CAPABILITIES: IssueCapabilities = { assignees: true, reactions: false, templates: false, - linkedPullRequests: false, + linkedPullRequests: true, events: true, search: true, }; @@ -106,6 +107,38 @@ function toActor(user: JiraApi.JiraUser): IssueActor { /** Jira Cloud account ids: 24 hex digits, or `:`. */ const ACCOUNT_ID = /^(?:[0-9a-z]{24}|\d+:[0-9a-f-]{36})$/i; +/** `//pull/1`, as GitHub, GitLab (`-/merge_requests`) or Bitbucket write it. */ +const PULL_REQUEST_URL = + /^https:\/\/[^/]+\/(.+?)\/(?:pull|-\/merge_requests|pull-requests)\/(\d+)\/?(?:[?#]|$)/u; + +function toLinkedPullRequests( + pulls: ReadonlyArray, +): IssueLinkedPullRequest[] { + const seen = new Set(); + return pulls.flatMap((pull) => { + const match = PULL_REQUEST_URL.exec(pull.url); + if (match === null || seen.has(pull.url)) return []; + seen.add(pull.url); + const status = pull.status?.toUpperCase(); + return [ + { + repository: match[1]!, + number: Number(match[2]), + title: pull.name.trim() || pull.url, + url: pull.url, + state: + status === "MERGED" + ? "merged" + : status === "OPEN" || status === "DRAFT" + ? "open" + : "closed", + isDraft: status === "DRAFT", + closesIssue: false, + } as const, + ]; + }); +} + const issueUrl = (site: string, key: string) => `https://${site}.atlassian.net/browse/${key}`; /** A search reports no comment totals cheaply, so a listing shows no comment count. */ @@ -382,7 +415,14 @@ export const make: Effect.Effect [])), + ], + { concurrency: "unbounded" }, + ); // A transition's target is a state the issue can move to; the current one is listed too. const states = [issue.fields.status, ...(issue.transitions ?? []).map((t) => t.to)]; const seen = new Set(); @@ -397,7 +437,7 @@ export const make: Effect.Effect Date: Thu, 19 Nov 2026 20:05:01 +0100 Subject: [PATCH 7/8] fix(web): drop the stale Replace translation --- apps/web/src/i18n/translations/de.json | 1 - apps/web/src/i18n/translations/en.json | 1 - apps/web/src/i18n/translations/es.json | 1 - apps/web/src/i18n/translations/fr.json | 1 - apps/web/src/i18n/translations/ja.json | 1 - apps/web/src/i18n/translations/ko.json | 1 - apps/web/src/i18n/translations/pt-BR.json | 1 - apps/web/src/i18n/translations/ru.json | 1 - apps/web/src/i18n/translations/sv.json | 1 - apps/web/src/i18n/translations/zh.json | 1 - 10 files changed, 10 deletions(-) diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 40731646e0a5f..46df7424ab0f2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -8440,7 +8440,6 @@ "a2d95d39d3398bda": "Anmeldedaten abgelehnt", "9eae463720500113": "Auf dem Server gespeichert.", "b6e27ab2537ef874": "Erstellen", - "b7088cd1c566d9c9": "Ersetzen", "e63611bd62fad8d8": "Nicht zugeordnet", "13ef526271b0f5d4": "Alle Bedingungen löschen", "d1938a629f039515": "Bedingung entfernen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 459fed7c3235c..fc971dba6e051 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -8448,7 +8448,6 @@ "a2d95d39d3398bda": "Credential rejected", "9eae463720500113": "Stored on the server.", "b6e27ab2537ef874": "Create one", - "b7088cd1c566d9c9": "Replace", "e63611bd62fad8d8": "Not bound", "13ef526271b0f5d4": "Clear all conditions", "d1938a629f039515": "Remove condition", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 26aa785f1e89e..797888016bd4a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -8438,7 +8438,6 @@ "a2d95d39d3398bda": "Credencial rechazada", "9eae463720500113": "Guardado en el servidor.", "b6e27ab2537ef874": "Crear uno", - "b7088cd1c566d9c9": "Reemplazar", "e63611bd62fad8d8": "Sin vincular", "13ef526271b0f5d4": "Borrar todas las condiciones", "d1938a629f039515": "Quitar condición", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 6993fdac41300..e06cde54989bd 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -8439,7 +8439,6 @@ "a2d95d39d3398bda": "Identifiant refusé", "9eae463720500113": "Stocké sur le serveur.", "b6e27ab2537ef874": "En créer un", - "b7088cd1c566d9c9": "Remplacer", "e63611bd62fad8d8": "Non lié", "13ef526271b0f5d4": "Effacer toutes les conditions", "d1938a629f039515": "Supprimer la condition", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 57b444aa1cdfb..4473bff3ddef1 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -8396,7 +8396,6 @@ "a2d95d39d3398bda": "資格情報が拒否されました", "9eae463720500113": "サーバーに保存されています。", "b6e27ab2537ef874": "作成する", - "b7088cd1c566d9c9": "置き換え", "e63611bd62fad8d8": "未バインド", "13ef526271b0f5d4": "すべての条件をクリア", "d1938a629f039515": "条件を削除", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 9c97ee31a03e7..68f0b20794362 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -8399,7 +8399,6 @@ "a2d95d39d3398bda": "자격 증명 거부됨", "9eae463720500113": "서버에 저장됩니다.", "b6e27ab2537ef874": "새로 만들기", - "b7088cd1c566d9c9": "교체", "e63611bd62fad8d8": "바인딩되지 않음", "13ef526271b0f5d4": "모든 조건 지우기", "d1938a629f039515": "조건 제거", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 6e36dc2b86ec7..5a18a359ecb2a 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -8438,7 +8438,6 @@ "a2d95d39d3398bda": "Credencial recusada", "9eae463720500113": "Armazenado no servidor.", "b6e27ab2537ef874": "Criar um", - "b7088cd1c566d9c9": "Substituir", "e63611bd62fad8d8": "Não vinculado", "13ef526271b0f5d4": "Limpar todas as condições", "d1938a629f039515": "Remover condição", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 8e9cf1cd865f8..6c7fa00a15455 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -8440,7 +8440,6 @@ "a2d95d39d3398bda": "Учётные данные отклонены", "9eae463720500113": "Хранится на сервере.", "b6e27ab2537ef874": "Создать", - "b7088cd1c566d9c9": "Заменить", "e63611bd62fad8d8": "Не привязано", "13ef526271b0f5d4": "Очистить все условия", "d1938a629f039515": "Удалить условие", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 1fb338d6f3a22..d02de62557d73 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -8446,7 +8446,6 @@ "a2d95d39d3398bda": "Autentiseringsuppgiften avvisades", "9eae463720500113": "Lagras på servern.", "b6e27ab2537ef874": "Skapa en", - "b7088cd1c566d9c9": "Ersätt", "e63611bd62fad8d8": "Inte kopplad", "13ef526271b0f5d4": "Rensa alla villkor", "d1938a629f039515": "Ta bort villkor", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5050c95e7360b..acf5ce3045376 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -8456,7 +8456,6 @@ "a2d95d39d3398bda": "凭据被拒绝", "9eae463720500113": "存储在服务器上。", "b6e27ab2537ef874": "创建一个", - "b7088cd1c566d9c9": "替换", "e63611bd62fad8d8": "未绑定", "13ef526271b0f5d4": "清除所有条件", "d1938a629f039515": "移除条件", From 3c9827c9b91f83c102233a0ec23486668d1d2763 Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:05:10 +0100 Subject: [PATCH 8/8] fix(jira): one refused development tool keeps the other tools' pull requests --- packages/issue-tracker-jira/src/server/JiraApi.ts | 2 +- .../src/server/JiraIssueTracker.test.ts | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/issue-tracker-jira/src/server/JiraApi.ts b/packages/issue-tracker-jira/src/server/JiraApi.ts index 008ee3ff02547..2e6a02bd3deb8 100644 --- a/packages/issue-tracker-jira/src/server/JiraApi.ts +++ b/packages/issue-tracker-jira/src/server/JiraApi.ts @@ -552,7 +552,7 @@ export const make = Effect.gen(function* () { path: "/issue/detail", params: { issueId, applicationType, dataType: "pullrequest" }, schema: DevelopmentDetail, - }), + }).pipe(Effect.orElseSucceed(() => ({ detail: [] }))), { concurrency: "unbounded" }, ); return details.flatMap(({ detail }) => detail.flatMap((entry) => entry.pullRequests ?? [])); diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts index c27e29a4657fc..97d60c92a8aaf 100644 --- a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts @@ -249,11 +249,15 @@ describe("JiraIssueTracker", () => { }, "GET /rest/dev-status/latest/issue/summary": () => ({ summary: { - pullrequest: { byInstanceType: { GitHub: { count: 1 }, stash: { count: 0 } } }, + pullrequest: { + byInstanceType: { GitHub: { count: 1 }, GitLab: { count: 1 }, stash: { count: 0 } }, + }, }, }), "GET /rest/dev-status/latest/issue/detail": (seen) => { - expect(seen.params.get("applicationType")).toBe("GitHub"); + expect(seen.params.get("applicationType")).not.toBe("stash"); + if (seen.params.get("applicationType") === "GitLab") + return new Response("", { status: 403 }); const pull = { name: "Fix", url: "https://github.com/acme/web/pull/7", status: "MERGED" }; return { detail: [{ pullRequests: [pull, pull] }] }; },