diff --git a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx index 6b1c799476d73..495d0a3992758 100644 --- a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx +++ b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx @@ -19,6 +19,7 @@ import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; import { useEnvironmentsWithScope } from "../../state/session"; import { sourceControlEnvironment } from "../../state/sourceControl"; +import { IssueAutomationSection } from "./components/IssueAutomationSection"; import { IssueTrackerCredentialForm, IssueTrackerProjectRows, @@ -189,6 +190,13 @@ export function SettingsIssueTrackerRouteScreen({ /> ) : null} + {usable && tracker.automationContainer !== undefined ? ( + + ) : null} )} diff --git a/apps/mobile/src/features/settings/components/IssueAutomationSection.tsx b/apps/mobile/src/features/settings/components/IssueAutomationSection.tsx new file mode 100644 index 0000000000000..a257782fb9083 --- /dev/null +++ b/apps/mobile/src/features/settings/components/IssueAutomationSection.tsx @@ -0,0 +1,409 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { + EnvironmentId, + IssueAutomationAction, + IssueAutomationRule, + IssueTrackerKind, + StandaloneIssueTrackerDescriptor, +} from "@t3tools/contracts"; +import { useGT } from "gt-react-native"; +import { useRef, useState } from "react"; +import { Pressable, ScrollView, type TextInputInstance, View } from "react-native"; + +import { AppText as Text } from "../../../components/ui/AppText"; +import { SymbolView } from "../../../components/ui/AppSymbol"; +import { Button } from "../../../components/ui/Button"; +import { Chip } from "../../../components/ui/Chip"; +import { ListActionRow } from "../../../components/ui/ListActionRow"; +import { Menu } from "../../../components/ui/Menu"; +import { SearchField } from "../../../components/ui/SearchField"; +import { Sheet } from "../../../components/ui/Sheet"; +import { ThemedSwitch } from "../../../components/ui/ThemedSwitch"; +import { uuidv4 } from "../../../lib/uuid"; +import { issueTrackerEnvironment } from "../../../state/issueTrackers"; +import { useDebouncedValue } from "../../../state/queries"; +import { useEnvironmentQuery } from "../../../state/query"; +import { useAtomCommand } from "../../../state/use-atom-command"; +import { SettingsSection } from "./SettingsSection"; + +type Container = NonNullable; + +/** + * Issue status rules for one tracker: each team or board sorts its workflow statuses into Wake, + * Snooze, and Settle, and the server organizes every thread linked to one of its issues. + */ +export function IssueAutomationSection({ + environmentId, + tracker, + container, +}: { + readonly environmentId: EnvironmentId; + readonly tracker: IssueTrackerKind; + readonly container: Container; +}) { + const gt = useGT(); + const query = useEnvironmentQuery( + issueTrackerEnvironment.automation({ environmentId, input: {} }), + ); + const allowed = useAtomValue( + issueTrackerEnvironment.saveAutomation.permissionAtom(environmentId), + ); + const [draft, setDraft] = useState(null); + // A Jira site can hold hundreds of boards, so the tracker is searched a page at a time. + const [adding, setAdding] = useState(false); + const [search, setSearch] = useState(""); + const [cursor, setCursor] = useState(); + const searchRef = useRef(null); + const debouncedSearch = useDebouncedValue(search.trim(), 250); + const searching = search.trim() !== debouncedSearch; + const catalog = useEnvironmentQuery( + adding && !searching + ? issueTrackerEnvironment.automationCatalog({ + environmentId, + input: { + tracker, + ...(debouncedSearch ? { query: debouncedSearch } : {}), + ...(cursor ? { cursor } : {}), + }, + }) + : null, + ); + const rules = (query.data?.rules ?? []).filter((rule) => rule.tracker === tracker); + const available = (catalog.data?.containers ?? []).filter( + (option) => !rules.some((rule) => rule.containerId === option.id), + ); + const nextCursor = catalog.data?.nextCursor ?? null; + const loading = searching || catalog.isPending; + const team = container === "team"; + const addLabel = team ? gt("Add team") : gt("Add board"); + const searchLabel = team ? gt("Search teams") : gt("Search boards"); + return ( + { + setSearch(""); + setCursor(undefined); + setAdding(true); + }} + className="min-h-9 flex-row items-center gap-1 px-2 active:opacity-70" + > + + {addLabel} + + } + > + {adding ? ( + setAdding(false)}> + + + + { + setSearch(value); + setCursor(undefined); + }} + /> + + {loading ? ( + {gt("Loading…")} + ) : null} + + {available.map((option) => ( + { + if (catalog.data === null) return; + setDraft({ + id: uuidv4(), + enabled: true, + tracker, + workspace: catalog.data.workspace, + containerId: option.id, + containerName: option.name, + mappings: {}, + }); + setAdding(false); + }} + /> + ))} + + {catalog.error ? ( + <> + + {catalog.error} + + + ) : ( + + )} + +
+ {buckets.map(({ action, label }) => ( +
+
+ {label} + + + } + > + + + + {unsorted.map((state) => ( + setMappings((current) => ({ ...current, [state.id]: action }))} + > + {state.name} + + ))} + {unsorted.length === 0 ? ( + {gt("Every status is in a bucket.")} + ) : null} + + +
+
+ {Object.entries(mappings) + .filter(([, value]) => value === action) + .map(([id]) => { + const name = states.find((state) => state.id === id)?.name ?? id; + return ( + + {name} + + + ); + })} +
+
+ ))} +
+ {alert ? ( +

+ {alert} +

+ ) : null} +
+ {workflow.error ? ( + + ) : null} + {dirty ? ( + <> + + {onDone ? null : ( + + )} + + ) : null} +
+ + ); +} diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx index bde22a6bcb1dd..2b22a6faeb594 100644 --- a/apps/web/src/components/settings/IssueTrackerSettings.tsx +++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx @@ -23,6 +23,7 @@ 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 { IssueAutomationSettings } from "./IssueAutomationSettings"; import { SecretInput } from "./SecretInput"; import { SettingsRow, SettingsSection } from "./settingsLayout"; import { searchableSetting } from "./settingsSearch"; @@ -264,6 +265,15 @@ function TrackerRow({ ) : null} + {usable && tracker.automationContainer !== undefined ? ( +
+ +
+ ) : null} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 154ad97baeabe..7315ee59b8347 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1161,6 +1161,14 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "environment-defaults", searchTerms: ["linear jira issues tracker team api key connect bind project"], }, + { + id: "issue-status-rules", + targetId: "issue-trackers", + title: msg("Issue status rules"), + to: "/settings/source-control", + scope: "environment-defaults", + searchTerms: [msg("linear team jira board issue status workflow wake snooze settle thread")], + }, { id: "source-control", title: "Source control", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index c3ff23ac9983b..e2d2fdc51c30b 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1,4 +1,38 @@ { + "30cc3b0b7c5223f9": "Teams", + "f42c4d6d05dfcacf": "Boards", + "24b5619c501032bf": "Threads wecken, zurückstellen oder erledigen, wenn sich der Status eines verknüpften Issues ändert.", + "647234c5dc75e791": "Team hinzufügen", + "2f3d6b74fac5b143": "Board hinzufügen", + "f42af3db8cf4f733": "Teams suchen", + "7c246409f42d0472": "Boards suchen", + "4ff72c2acc7f6656": "Wird geladen…", + "1c79d42e902ff431": "Wiederholen", + "fade64a8c1057b5d": "Keine passenden Teams.", + "0ee6ce5fa02371d6": "Keine passenden Boards.", + "7692d28fbe45f1cd": "Jedes Team hat bereits eine Regel.", + "58a6276de6d8988e": "Jedes Board hat bereits eine Regel.", + "269ee22d7bdcdddb": "Nächste Seite", + "c75c9ed6e04b155d": "Erste Seite", + "0ca7ece5adb2141b": "Füge ein Team hinzu, um die mit seinen Issues verknüpften Threads zu ordnen.", + "ade2fad0438c0ef7": "Füge ein Board hinzu, um die mit seinen Issues verknüpften Threads zu ordnen.", + "f903e7f0ca23602c": "Wecken", + "ef27c4211844aef9": "Zurückstellen", + "13e6f2309e418404": "Erledigen", + "470388c152e293cb": "Die Regel konnte nicht gespeichert werden.", + "7c8c86f94f9d13bf": "Diese Regel gehört zu einem anderen Workspace. Füge das Team oder Board erneut hinzu, um sie hier zu nutzen.", + "5efcecd685ad1dac": "Die letzte Statusprüfung ist fehlgeschlagen. Die Threads wurden nicht verändert.", + "63c5271568e4f9c6": "Gilt für Threads, die mit Issues dieses Teams verknüpft sind, in jedem Projekt.", + "0cc9c4463ea35891": "Gilt für Threads, die mit Issues dieses Boards verknüpft sind, in jedem Projekt.", + "666b6f323f7f3274": "Regel aktivieren", + "00ad8aeed0a6c461": "Abbrechen", + "7792add570638f64": "Team entfernen", + "65d7900a7a9d57e7": "Board entfernen", + "245038c3d0fc7c5e": "Status zu {bucket} hinzufügen", + "da5ac1b89bbc2e15": "Jeder Status ist bereits zugeordnet.", + "183dc01e105d82e5": "{status} entfernen", + "762fcce45b65eea9": "Speichern", + "bf5602410d695db3": "Verwerfen", "0a75e464d833bca8": "Einstellungen", "6aa1c88c4fa5be28": "Diagnose", "fb29e435b1219373": "Open-Source-Lizenzen", @@ -75,5 +109,7 @@ "1d5052cbe70d0b28": "Archivieren bestätigen", "d5dd27a4eb853248": "Löschen bestätigen", "5503ef439beb8d42": "Bestätigung beim Schließen von Terminals", - "86b43caa9ff41ea2": "Tastenkürzel zum Beenden" + "86b43caa9ff41ea2": "Tastenkürzel zum Beenden", + "03c5083adeb3ac5e": "Issue-Statusregeln", + "5f4cd500513df9ca": "linear team jira board issue status workflow wecken zurückstellen erledigen thread" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index a6dc4ca8f4c30..c3a64ec889f1c 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1,4 +1,38 @@ { + "30cc3b0b7c5223f9": "Teams", + "f42c4d6d05dfcacf": "Boards", + "24b5619c501032bf": "Wake, snooze, or settle threads when a linked issue's status changes.", + "647234c5dc75e791": "Add team", + "2f3d6b74fac5b143": "Add board", + "f42af3db8cf4f733": "Search teams", + "7c246409f42d0472": "Search boards", + "4ff72c2acc7f6656": "Loading…", + "1c79d42e902ff431": "Retry", + "fade64a8c1057b5d": "No matching teams.", + "0ee6ce5fa02371d6": "No matching boards.", + "7692d28fbe45f1cd": "Every team already has a rule.", + "58a6276de6d8988e": "Every board already has a rule.", + "269ee22d7bdcdddb": "Next page", + "c75c9ed6e04b155d": "First page", + "0ca7ece5adb2141b": "Add a team to organize the threads linked to its issues.", + "ade2fad0438c0ef7": "Add a board to organize the threads linked to its issues.", + "f903e7f0ca23602c": "Wake", + "ef27c4211844aef9": "Snooze", + "13e6f2309e418404": "Settle", + "470388c152e293cb": "The rule could not be saved.", + "7c8c86f94f9d13bf": "This rule belongs to another workspace. Add the team or board again to use it here.", + "5efcecd685ad1dac": "The last status check failed. Threads were left as they are.", + "63c5271568e4f9c6": "Applies to threads linked to this team's issues, in every project.", + "0cc9c4463ea35891": "Applies to threads linked to this board's issues, in every project.", + "666b6f323f7f3274": "Enable rule", + "00ad8aeed0a6c461": "Cancel", + "7792add570638f64": "Remove team", + "65d7900a7a9d57e7": "Remove board", + "245038c3d0fc7c5e": "Add a status to {bucket}", + "da5ac1b89bbc2e15": "Every status is in a bucket.", + "183dc01e105d82e5": "Remove {status}", + "762fcce45b65eea9": "Save", + "bf5602410d695db3": "Discard", "0a75e464d833bca8": "Settings", "6aa1c88c4fa5be28": "Diagnostics", "fb29e435b1219373": "Open source licenses", @@ -75,5 +109,7 @@ "1d5052cbe70d0b28": "Archive confirmation", "d5dd27a4eb853248": "Delete confirmation", "5503ef439beb8d42": "Terminal close confirmation", - "86b43caa9ff41ea2": "Quit shortcut" + "86b43caa9ff41ea2": "Quit shortcut", + "03c5083adeb3ac5e": "Issue status rules", + "5f4cd500513df9ca": "linear team jira board issue status workflow wake snooze settle thread" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 12fc167109d2b..211beb556db35 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1,4 +1,38 @@ { + "30cc3b0b7c5223f9": "Equipos", + "f42c4d6d05dfcacf": "Tableros", + "24b5619c501032bf": "Reactiva, pospone o resuelve hilos cuando cambia el estado de una issue vinculada.", + "647234c5dc75e791": "Añadir equipo", + "2f3d6b74fac5b143": "Añadir tablero", + "f42af3db8cf4f733": "Buscar equipos", + "7c246409f42d0472": "Buscar tableros", + "4ff72c2acc7f6656": "Cargando…", + "1c79d42e902ff431": "Reintentar", + "fade64a8c1057b5d": "No hay equipos que coincidan.", + "0ee6ce5fa02371d6": "No hay tableros que coincidan.", + "7692d28fbe45f1cd": "Todos los equipos ya tienen una regla.", + "58a6276de6d8988e": "Todos los tableros ya tienen una regla.", + "269ee22d7bdcdddb": "Página siguiente", + "c75c9ed6e04b155d": "Primera página", + "0ca7ece5adb2141b": "Añade un equipo para organizar los hilos vinculados a sus issues.", + "ade2fad0438c0ef7": "Añade un tablero para organizar los hilos vinculados a sus issues.", + "f903e7f0ca23602c": "Reactivar", + "ef27c4211844aef9": "Posponer", + "13e6f2309e418404": "Resolver", + "470388c152e293cb": "No se pudo guardar la regla.", + "7c8c86f94f9d13bf": "Esta regla pertenece a otro espacio de trabajo. Vuelve a añadir el equipo o tablero para usarla aquí.", + "5efcecd685ad1dac": "La última comprobación de estado falló. Los hilos se quedaron como estaban.", + "63c5271568e4f9c6": "Se aplica a los hilos vinculados a issues de este equipo, en todos los proyectos.", + "0cc9c4463ea35891": "Se aplica a los hilos vinculados a issues de este tablero, en todos los proyectos.", + "666b6f323f7f3274": "Activar regla", + "00ad8aeed0a6c461": "Cancelar", + "7792add570638f64": "Quitar equipo", + "65d7900a7a9d57e7": "Quitar tablero", + "245038c3d0fc7c5e": "Añadir un estado a {bucket}", + "da5ac1b89bbc2e15": "Todos los estados ya están en un grupo.", + "183dc01e105d82e5": "Quitar {status}", + "762fcce45b65eea9": "Guardar", + "bf5602410d695db3": "Descartar", "0a75e464d833bca8": "Ajustes", "6aa1c88c4fa5be28": "Diagnóstico", "fb29e435b1219373": "Licencias de código abierto", @@ -75,5 +109,7 @@ "1d5052cbe70d0b28": "Confirmación al archivar", "d5dd27a4eb853248": "Confirmación al eliminar", "5503ef439beb8d42": "Confirmación al cerrar terminales", - "86b43caa9ff41ea2": "Atajo para salir" + "86b43caa9ff41ea2": "Atajo para salir", + "03c5083adeb3ac5e": "Reglas de estado de issues", + "5f4cd500513df9ca": "linear equipo jira tablero issue estado flujo reactivar posponer resolver hilo" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index ababe67e15569..68198fdbefb00 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1,4 +1,38 @@ { + "30cc3b0b7c5223f9": "Équipes", + "f42c4d6d05dfcacf": "Tableaux", + "24b5619c501032bf": "Réveillez, reportez ou closez des fils quand le statut d’un ticket lié change.", + "647234c5dc75e791": "Ajouter une équipe", + "2f3d6b74fac5b143": "Ajouter un tableau", + "f42af3db8cf4f733": "Rechercher des équipes", + "7c246409f42d0472": "Rechercher des tableaux", + "4ff72c2acc7f6656": "Chargement…", + "1c79d42e902ff431": "Réessayer", + "fade64a8c1057b5d": "Aucune équipe correspondante.", + "0ee6ce5fa02371d6": "Aucun tableau correspondant.", + "7692d28fbe45f1cd": "Chaque équipe a déjà une règle.", + "58a6276de6d8988e": "Chaque tableau a déjà une règle.", + "269ee22d7bdcdddb": "Page suivante", + "c75c9ed6e04b155d": "Première page", + "0ca7ece5adb2141b": "Ajoutez une équipe pour organiser les fils liés à ses tickets.", + "ade2fad0438c0ef7": "Ajoutez un tableau pour organiser les fils liés à ses tickets.", + "f903e7f0ca23602c": "Réveiller", + "ef27c4211844aef9": "Report", + "13e6f2309e418404": "Clore", + "470388c152e293cb": "La règle n’a pas pu être enregistrée.", + "7c8c86f94f9d13bf": "Cette règle appartient à un autre espace de travail. Ajoutez de nouveau l’équipe ou le tableau pour l’utiliser ici.", + "5efcecd685ad1dac": "La dernière vérification des statuts a échoué. Les fils sont restés inchangés.", + "63c5271568e4f9c6": "S’applique aux fils liés aux tickets de cette équipe, dans tous les projets.", + "0cc9c4463ea35891": "S’applique aux fils liés aux tickets de ce tableau, dans tous les projets.", + "666b6f323f7f3274": "Activer la règle", + "00ad8aeed0a6c461": "Annuler", + "7792add570638f64": "Retirer l’équipe", + "65d7900a7a9d57e7": "Retirer le tableau", + "245038c3d0fc7c5e": "Ajouter un statut à {bucket}", + "da5ac1b89bbc2e15": "Chaque statut est déjà dans un groupe.", + "183dc01e105d82e5": "Retirer {status}", + "762fcce45b65eea9": "Enregistrer", + "bf5602410d695db3": "Abandonner", "0a75e464d833bca8": "Paramètres", "6aa1c88c4fa5be28": "Diagnostics", "fb29e435b1219373": "Licences open source", @@ -75,5 +109,7 @@ "1d5052cbe70d0b28": "Confirmation de l'archivage", "d5dd27a4eb853248": "Confirmation de la suppression", "5503ef439beb8d42": "Confirmation de la fermeture des terminaux", - "86b43caa9ff41ea2": "Raccourci Quitter" + "86b43caa9ff41ea2": "Raccourci Quitter", + "03c5083adeb3ac5e": "Règles de statut des tickets", + "5f4cd500513df9ca": "linear équipe jira tableau ticket statut workflow réveiller reporter clore fil" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 33de9cf56334c..643c938f3021a 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1,4 +1,38 @@ { + "30cc3b0b7c5223f9": "チーム", + "f42c4d6d05dfcacf": "ボード", + "24b5619c501032bf": "リンクされた Issue のステータスが変わったときに、スレッドを再開、スヌーズ、または対応済みにします。", + "647234c5dc75e791": "チームを追加", + "2f3d6b74fac5b143": "ボードを追加", + "f42af3db8cf4f733": "チームを検索", + "7c246409f42d0472": "ボードを検索", + "4ff72c2acc7f6656": "読み込んでいます…", + "1c79d42e902ff431": "再試行", + "fade64a8c1057b5d": "一致するチームはありません。", + "0ee6ce5fa02371d6": "一致するボードはありません。", + "7692d28fbe45f1cd": "すべてのチームにルールがあります。", + "58a6276de6d8988e": "すべてのボードにルールがあります。", + "269ee22d7bdcdddb": "次のページ", + "c75c9ed6e04b155d": "最初のページ", + "0ca7ece5adb2141b": "チームを追加すると、その Issue にリンクされたスレッドを整理します。", + "ade2fad0438c0ef7": "ボードを追加すると、その Issue にリンクされたスレッドを整理します。", + "f903e7f0ca23602c": "再開", + "ef27c4211844aef9": "スヌーズ", + "13e6f2309e418404": "対応済みにする", + "470388c152e293cb": "ルールを保存できませんでした。", + "7c8c86f94f9d13bf": "このルールは別のワークスペースのものです。ここで使うには、チームまたはボードを追加し直してください。", + "5efcecd685ad1dac": "前回のステータス確認に失敗しました。スレッドはそのままです。", + "63c5271568e4f9c6": "すべてのプロジェクトで、このチームの Issue にリンクされたスレッドに適用されます。", + "0cc9c4463ea35891": "すべてのプロジェクトで、このボードの Issue にリンクされたスレッドに適用されます。", + "666b6f323f7f3274": "ルールを有効にする", + "00ad8aeed0a6c461": "キャンセル", + "7792add570638f64": "チームを削除", + "65d7900a7a9d57e7": "ボードを削除", + "245038c3d0fc7c5e": "{bucket} にステータスを追加", + "da5ac1b89bbc2e15": "すべてのステータスが割り当て済みです。", + "183dc01e105d82e5": "{status} を削除", + "762fcce45b65eea9": "保存", + "bf5602410d695db3": "破棄", "0a75e464d833bca8": "設定", "6aa1c88c4fa5be28": "診断", "fb29e435b1219373": "オープンソースライセンス", @@ -75,5 +109,7 @@ "1d5052cbe70d0b28": "アーカイブの確認", "d5dd27a4eb853248": "削除の確認", "5503ef439beb8d42": "ターミナルを閉じる際の確認", - "86b43caa9ff41ea2": "終了ショートカット" + "86b43caa9ff41ea2": "終了ショートカット", + "03c5083adeb3ac5e": "Issue ステータスのルール", + "5f4cd500513df9ca": "linear チーム jira ボード issue ステータス ワークフロー 再開 スヌーズ 対応済み スレッド" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 5a9c3fba64033..ed34fb592fd36 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1,4 +1,38 @@ { + "30cc3b0b7c5223f9": "팀", + "f42c4d6d05dfcacf": "보드", + "24b5619c501032bf": "연결된 이슈의 상태가 바뀌면 스레드를 깨우거나, 다시 알림으로 미루거나, 정리합니다.", + "647234c5dc75e791": "팀 추가", + "2f3d6b74fac5b143": "보드 추가", + "f42af3db8cf4f733": "팀 검색", + "7c246409f42d0472": "보드 검색", + "4ff72c2acc7f6656": "불러오는 중…", + "1c79d42e902ff431": "다시 시도", + "fade64a8c1057b5d": "일치하는 팀이 없습니다.", + "0ee6ce5fa02371d6": "일치하는 보드가 없습니다.", + "7692d28fbe45f1cd": "모든 팀에 이미 규칙이 있습니다.", + "58a6276de6d8988e": "모든 보드에 이미 규칙이 있습니다.", + "269ee22d7bdcdddb": "다음 페이지", + "c75c9ed6e04b155d": "첫 페이지", + "0ca7ece5adb2141b": "팀을 추가하면 해당 팀의 이슈에 연결된 스레드를 정리합니다.", + "ade2fad0438c0ef7": "보드를 추가하면 해당 보드의 이슈에 연결된 스레드를 정리합니다.", + "f903e7f0ca23602c": "깨우기", + "ef27c4211844aef9": "다시 알림", + "13e6f2309e418404": "정리", + "470388c152e293cb": "규칙을 저장하지 못했습니다.", + "7c8c86f94f9d13bf": "이 규칙은 다른 워크스페이스에 속합니다. 여기서 사용하려면 팀이나 보드를 다시 추가하세요.", + "5efcecd685ad1dac": "마지막 상태 확인에 실패했습니다. 스레드는 그대로 두었습니다.", + "63c5271568e4f9c6": "모든 프로젝트에서 이 팀의 이슈에 연결된 스레드에 적용됩니다.", + "0cc9c4463ea35891": "모든 프로젝트에서 이 보드의 이슈에 연결된 스레드에 적용됩니다.", + "666b6f323f7f3274": "규칙 사용", + "00ad8aeed0a6c461": "취소", + "7792add570638f64": "팀 제거", + "65d7900a7a9d57e7": "보드 제거", + "245038c3d0fc7c5e": "{bucket}에 상태 추가", + "da5ac1b89bbc2e15": "모든 상태가 이미 배정되었습니다.", + "183dc01e105d82e5": "{status} 제거", + "762fcce45b65eea9": "저장", + "bf5602410d695db3": "버리기", "0a75e464d833bca8": "설정", "6aa1c88c4fa5be28": "진단", "fb29e435b1219373": "오픈 소스 라이선스", @@ -75,5 +109,7 @@ "1d5052cbe70d0b28": "보관 확인", "d5dd27a4eb853248": "삭제 확인", "5503ef439beb8d42": "터미널 닫기 확인", - "86b43caa9ff41ea2": "종료 단축키" + "86b43caa9ff41ea2": "종료 단축키", + "03c5083adeb3ac5e": "이슈 상태 규칙", + "5f4cd500513df9ca": "linear 팀 jira 보드 이슈 상태 워크플로 깨우기 다시 알림 정리 스레드" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 2b840545d8af3..ab9be75bac87c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1,4 +1,38 @@ { + "30cc3b0b7c5223f9": "Equipes", + "f42c4d6d05dfcacf": "Quadros", + "24b5619c501032bf": "Desperte, adie ou conclua threads quando o status de uma issue vinculada mudar.", + "647234c5dc75e791": "Adicionar equipe", + "2f3d6b74fac5b143": "Adicionar quadro", + "f42af3db8cf4f733": "Pesquisar equipes", + "7c246409f42d0472": "Pesquisar quadros", + "4ff72c2acc7f6656": "Carregando…", + "1c79d42e902ff431": "Tentar novamente", + "fade64a8c1057b5d": "Nenhuma equipe corresponde.", + "0ee6ce5fa02371d6": "Nenhum quadro corresponde.", + "7692d28fbe45f1cd": "Todas as equipes já têm uma regra.", + "58a6276de6d8988e": "Todos os quadros já têm uma regra.", + "269ee22d7bdcdddb": "Próxima página", + "c75c9ed6e04b155d": "Primeira página", + "0ca7ece5adb2141b": "Adicione uma equipe para organizar as threads vinculadas às issues dela.", + "ade2fad0438c0ef7": "Adicione um quadro para organizar as threads vinculadas às issues dele.", + "f903e7f0ca23602c": "Despertar", + "ef27c4211844aef9": "Adiar", + "13e6f2309e418404": "Concluir", + "470388c152e293cb": "Não foi possível salvar a regra.", + "7c8c86f94f9d13bf": "Esta regra pertence a outro espaço de trabalho. Adicione a equipe ou o quadro novamente para usá-la aqui.", + "5efcecd685ad1dac": "A última verificação de status falhou. As threads ficaram como estavam.", + "63c5271568e4f9c6": "Vale para threads vinculadas às issues desta equipe, em todos os projetos.", + "0cc9c4463ea35891": "Vale para threads vinculadas às issues deste quadro, em todos os projetos.", + "666b6f323f7f3274": "Ativar regra", + "00ad8aeed0a6c461": "Cancelar", + "7792add570638f64": "Remover equipe", + "65d7900a7a9d57e7": "Remover quadro", + "245038c3d0fc7c5e": "Adicionar um status a {bucket}", + "da5ac1b89bbc2e15": "Todos os status já estão em um grupo.", + "183dc01e105d82e5": "Remover {status}", + "762fcce45b65eea9": "Salvar", + "bf5602410d695db3": "Descartar", "0a75e464d833bca8": "Configurações", "6aa1c88c4fa5be28": "Diagnóstico", "fb29e435b1219373": "Licenças de código aberto", @@ -75,5 +109,7 @@ "1d5052cbe70d0b28": "Confirmação ao arquivar", "d5dd27a4eb853248": "Confirmação ao excluir", "5503ef439beb8d42": "Confirmação ao fechar terminais", - "86b43caa9ff41ea2": "Atalho de saída" + "86b43caa9ff41ea2": "Atalho de saída", + "03c5083adeb3ac5e": "Regras de status de issues", + "5f4cd500513df9ca": "linear equipe jira quadro issue status fluxo despertar adiar concluir thread" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 704901860fe1c..45f0bc53463b9 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1,4 +1,38 @@ { + "30cc3b0b7c5223f9": "Команды", + "f42c4d6d05dfcacf": "Доски", + "24b5619c501032bf": "Будит, откладывает или разбирает треды, когда меняется статус связанной issue.", + "647234c5dc75e791": "Добавить команду", + "2f3d6b74fac5b143": "Добавить доску", + "f42af3db8cf4f733": "Поиск команд", + "7c246409f42d0472": "Поиск досок", + "4ff72c2acc7f6656": "Загрузка…", + "1c79d42e902ff431": "Повторить", + "fade64a8c1057b5d": "Нет подходящих команд.", + "0ee6ce5fa02371d6": "Нет подходящих досок.", + "7692d28fbe45f1cd": "У каждой команды уже есть правило.", + "58a6276de6d8988e": "У каждой доски уже есть правило.", + "269ee22d7bdcdddb": "Следующая страница", + "c75c9ed6e04b155d": "Первая страница", + "0ca7ece5adb2141b": "Добавьте команду, чтобы упорядочивать треды, связанные с её issue.", + "ade2fad0438c0ef7": "Добавьте доску, чтобы упорядочивать треды, связанные с её issue.", + "f903e7f0ca23602c": "Разбудить", + "ef27c4211844aef9": "Отложить", + "13e6f2309e418404": "Разобрать", + "470388c152e293cb": "Не удалось сохранить правило.", + "7c8c86f94f9d13bf": "Это правило относится к другому рабочему пространству. Чтобы использовать его здесь, добавьте команду или доску заново.", + "5efcecd685ad1dac": "Последняя проверка статусов не удалась. Треды оставлены как есть.", + "63c5271568e4f9c6": "Действует для тредов, связанных с issue этой команды, во всех проектах.", + "0cc9c4463ea35891": "Действует для тредов, связанных с issue этой доски, во всех проектах.", + "666b6f323f7f3274": "Включить правило", + "00ad8aeed0a6c461": "Отмена", + "7792add570638f64": "Удалить команду", + "65d7900a7a9d57e7": "Удалить доску", + "245038c3d0fc7c5e": "Добавить статус в «{bucket}»", + "da5ac1b89bbc2e15": "Все статусы уже распределены.", + "183dc01e105d82e5": "Удалить «{status}»", + "762fcce45b65eea9": "Сохранить", + "bf5602410d695db3": "Отменить", "0a75e464d833bca8": "Настройки", "6aa1c88c4fa5be28": "Диагностика", "fb29e435b1219373": "Лицензии открытого ПО", @@ -75,5 +109,7 @@ "1d5052cbe70d0b28": "Подтверждение архивации", "d5dd27a4eb853248": "Подтверждение удаления", "5503ef439beb8d42": "Подтверждение закрытия терминалов", - "86b43caa9ff41ea2": "Сочетание клавиш для выхода" + "86b43caa9ff41ea2": "Сочетание клавиш для выхода", + "03c5083adeb3ac5e": "Правила статусов issue", + "5f4cd500513df9ca": "linear команда jira доска issue статус процесс разбудить отложить разобрать тред" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 0f0ea61d58744..fafca5bc48bff 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1,4 +1,38 @@ { + "30cc3b0b7c5223f9": "团队", + "f42c4d6d05dfcacf": "看板", + "24b5619c501032bf": "当关联 issue 的状态变化时,唤醒、暂缓或收尾线程。", + "647234c5dc75e791": "添加团队", + "2f3d6b74fac5b143": "添加看板", + "f42af3db8cf4f733": "搜索团队", + "7c246409f42d0472": "搜索看板", + "4ff72c2acc7f6656": "加载中…", + "1c79d42e902ff431": "重试", + "fade64a8c1057b5d": "没有匹配的团队。", + "0ee6ce5fa02371d6": "没有匹配的看板。", + "7692d28fbe45f1cd": "每个团队都已有规则。", + "58a6276de6d8988e": "每个看板都已有规则。", + "269ee22d7bdcdddb": "下一页", + "c75c9ed6e04b155d": "第一页", + "0ca7ece5adb2141b": "添加团队,以整理关联到其 issue 的线程。", + "ade2fad0438c0ef7": "添加看板,以整理关联到其 issue 的线程。", + "f903e7f0ca23602c": "唤醒", + "ef27c4211844aef9": "暂缓", + "13e6f2309e418404": "收尾", + "470388c152e293cb": "无法保存规则。", + "7c8c86f94f9d13bf": "此规则属于另一个工作区。要在这里使用,请重新添加该团队或看板。", + "5efcecd685ad1dac": "上次状态检查失败。线程保持不变。", + "63c5271568e4f9c6": "适用于所有项目中关联到此团队 issue 的线程。", + "0cc9c4463ea35891": "适用于所有项目中关联到此看板 issue 的线程。", + "666b6f323f7f3274": "启用规则", + "00ad8aeed0a6c461": "取消", + "7792add570638f64": "移除团队", + "65d7900a7a9d57e7": "移除看板", + "245038c3d0fc7c5e": "向{bucket}添加状态", + "da5ac1b89bbc2e15": "所有状态都已分配。", + "183dc01e105d82e5": "移除{status}", + "762fcce45b65eea9": "保存", + "bf5602410d695db3": "放弃", "0a75e464d833bca8": "设置", "6aa1c88c4fa5be28": "诊断", "fb29e435b1219373": "开源许可证", @@ -75,5 +109,7 @@ "1d5052cbe70d0b28": "归档确认", "d5dd27a4eb853248": "删除确认", "5503ef439beb8d42": "关闭终端确认", - "86b43caa9ff41ea2": "退出快捷键" + "86b43caa9ff41ea2": "退出快捷键", + "03c5083adeb3ac5e": "issue 状态规则", + "5f4cd500513df9ca": "linear 团队 jira 看板 issue 状态 工作流 唤醒 暂缓 收尾 线程" } diff --git a/docs/user/source-control.md b/docs/user/source-control.md index ac7962f5d2d93..75abaf10f5522 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -385,6 +385,31 @@ issues they work on with the `link_issue` tool. Writing to a tracker over a remote connection requires the `source-control:write` scope. +### Organize threads by issue status + +Threads can follow the status of the issues linked to them. Open the connected tracker under +**Settings → Source control & issues**, choose **Add team** for Linear or **Add board** for Jira, +and use the **+** buttons to put the team's or board's statuses in **Wake**, **Snooze**, or +**Settle**. The rule applies to every thread linked to one of its issues, in any project. It +changes threads, never issues. + +Search Jira boards by name, or by a project key to find that project's boards. A Jira Service +Management project without a board is offered as itself when you search for its key, with the +statuses of all its issue types. A board's rule covers the issues of the projects the board +shows, on the connected site. + +The server checks linked issues about once a minute while it runs, with or without a client open. +Only a status change counts: the first check after you save a rule records the current statuses, and +a thread you organize by hand stays that way until one of its issues moves again. A thread wakes +when any linked issue maps to **Wake**. Short of that, it stays as it is while any linked issue has +a status in no bucket, could not be read, or is outside every rule's team or board; it settles only +when all of them map to **Settle**, and otherwise snoozes. A snooze from a rule has no wake time; +the thread shows **∞** in the Snoozed list until a status change, **Wake thread**, or a message +wakes it. A thread with work still running waits until it is idle before it snoozes or settles. A +rule never settles a pinned thread. Rules leave a thread whose **Auto-settle behavior** is **Never** +alone: they do not wake, snooze, or settle it, and an action still waiting for the thread to go idle +is dropped. After you switch it back to **Follow settings**, only later status changes count. + ## GitHub stacks The Pull requests page shows each PR's position in its GitHub stack. Open the stack badge in a diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 6b9ccbb69953a..f3bb1495ec2b7 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -122,7 +122,8 @@ export interface ReorderActiveThreadInput extends ThreadCommandInput { } export interface SnoozeThreadInput extends ThreadCommandInput { - readonly snoozedUntil: string; + /** Null snoozes until the thread is woken. */ + readonly snoozedUntil: string | null; } export interface UnsnoozeThreadInput extends ThreadCommandInput { diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index ee70400ca47a5..781f06472a5ae 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -68,6 +68,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.subscribeDeviceState | typeof WS_METHODS.subscribeResourceTelemetry | typeof WS_METHODS.pullRequestsSubscribeRefreshes + | typeof WS_METHODS.issuesSubscribeStatusRefreshes | typeof WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes | typeof WS_METHODS.subscribeVcsStatus | typeof WS_METHODS.subscribeVcsBranch diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 403f44394656b..5cdc1858d85bc 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -175,25 +175,27 @@ describe("command permissions", () => { }), ); - it.effect.each([WS_METHODS.serverCheckOtlpEndpoint, WS_METHODS.serverCheckSecretSource])( - "requires the destination settings grant for %s", - (method) => - Effect.gen(function* () { - const registry = yield* setup; - const check = createCommandPermissions(runtime, method); - registry.set(sessions(env), AsyncResult.success(grant(true))); - expect(registry.get(check.permissionAtom(env))).toBe(false); - registry.set( - sessions(env), - AsyncResult.success({ - ...grant(false), - scopes: [AuthSettingsWriteScope], - permissions: [AuthSettingsWriteScope], - }), - ); - expect(registry.get(check.permissionAtom(env))).toBe(true); - yield* check.authorize(registry, env); - }), + it.effect.each([ + WS_METHODS.serverCheckOtlpEndpoint, + WS_METHODS.serverCheckSecretSource, + WS_METHODS.issueTrackersSaveAutomation, + ])("requires the destination settings grant for %s", (method) => + Effect.gen(function* () { + const registry = yield* setup; + const check = createCommandPermissions(runtime, method); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(check.permissionAtom(env))).toBe(false); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthSettingsWriteScope], + permissions: [AuthSettingsWriteScope], + }), + ); + expect(registry.get(check.permissionAtom(env))).toBe(true); + yield* check.authorize(registry, env); + }), ); it.effect("requires the destination settings grant to connect or bind an issue tracker", () => diff --git a/packages/client-runtime/src/state/issueTrackers.ts b/packages/client-runtime/src/state/issueTrackers.ts index bc231aca06255..23c7f6c7db582 100644 --- a/packages/client-runtime/src/state/issueTrackers.ts +++ b/packages/client-runtime/src/state/issueTrackers.ts @@ -27,6 +27,19 @@ export function createIssueTrackerEnvironmentAtoms( label: "environment-data:issue-trackers:connections", tag: WS_METHODS.issueTrackersList, }); + const automation = createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:issue-trackers:automation", + tag: WS_METHODS.issueTrackersAutomation, + }); + // Bumped by each credential save, so a mounted catalog drops what the old credential could reach. + const credentialChanges = Atom.family((_environmentId: string) => + Atom.make(0).pipe(Atom.keepAlive), + ); + const automationCatalog = createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:issue-trackers:automation-catalog", + tag: WS_METHODS.issueTrackersAutomationCatalog, + refreshTrigger: ({ environmentId }) => credentialChanges(environmentId), + }); const refresh = (environmentId: Parameters[0]["environmentId"]) => connections({ environmentId, input: {} }); // Connect, disconnect and bind all edit one environment's tracker state; serialized so a @@ -37,6 +50,21 @@ export function createIssueTrackerEnvironmentAtoms( }; return { connections, + /** Issue status rules, and how each one's last status read went. */ + automation, + /** A tracker's teams or boards, and with `containerId` that one's workflow statuses. */ + automationCatalog, + /** Saves a rule the tracker can reach, or removes one with a null rule. */ + saveAutomation: createEnvironmentRpcCommand(runtime, { + label: "environment-data:issue-trackers:save-automation", + tag: WS_METHODS.issueTrackersSaveAutomation, + scheduler: commandScheduler, + concurrency: serialPerEnvironment, + onSettled: (target, registry) => + Effect.sync(() => + registry.refresh(automation({ environmentId: target.environmentId, input: {} })), + ), + }), /** Saves a credential the tracker accepted, or removes the stored one with a null token. */ connect: createEnvironmentRpcCommand(runtime, { label: "environment-data:issue-trackers:connect", @@ -44,7 +72,10 @@ export function createIssueTrackerEnvironmentAtoms( scheduler: commandScheduler, concurrency: serialPerEnvironment, onSettled: (target, registry) => - Effect.sync(() => registry.refresh(refresh(target.environmentId))), + Effect.sync(() => { + registry.refresh(refresh(target.environmentId)); + registry.update(credentialChanges(target.environmentId), (count) => count + 1); + }), }), bindProject: createEnvironmentRpcCommand(runtime, { label: "environment-data:issue-trackers:bind-project", diff --git a/packages/client-runtime/src/state/issues.ts b/packages/client-runtime/src/state/issues.ts index 919baeb9b370b..a034e6333ceb5 100644 --- a/packages/client-runtime/src/state/issues.ts +++ b/packages/client-runtime/src/state/issues.ts @@ -20,6 +20,7 @@ import { createAtomCommandScheduler, createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily, + createEnvironmentRpcSubscriptionAtomFamily, } from "./runtime.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; @@ -72,10 +73,20 @@ export function createIssueEnvironmentAtoms( mode: "serial", key: ({ environmentId }: { readonly environmentId: string }) => environmentId, } as const; + const statusRefreshes = createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:issues:status-refreshes", + tag: WS_METHODS.issuesSubscribeStatusRefreshes, + }); const detail = createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:issues:detail", tag: WS_METHODS.issuesDetail, staleTimeMs: 30_000, + // An issue status rule saw this issue move, so an open detail reads it again. + refreshTrigger: ({ environmentId, input }) => + statusRefreshes({ + environmentId, + input: { tracker: input.tracker, key: input.key.toUpperCase() }, + }), }); const detailRef = ({ projectId, tracker, host, scope, key }: IssueRef): IssueRef => ({ projectId, diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 41b74e9f2ac78..1aa2e7eead071 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -521,11 +521,13 @@ export function createThreadEnvironmentAtoms( ((thread.pendingRuntimeRequest !== null && thread.pendingRuntimeRequest.kind !== "user_input") || ["preparing", "queued", "starting"].includes(thread.status))) || - !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now)) + (input.snoozedUntil !== null && + !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now))) ? thread : { ...thread, - snoozedUntil: DateTime.makeUnsafe(input.snoozedUntil), + snoozedUntil: + input.snoozedUntil === null ? null : DateTime.makeUnsafe(input.snoozedUntil), snoozedAt: now, }, ), diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.ts index 17be7a3ce69e2..f2e98d92f9634 100644 --- a/packages/client-runtime/src/state/threadSettled.ts +++ b/packages/client-runtime/src/state/threadSettled.ts @@ -157,7 +157,9 @@ export function effectiveSnoozed( shell: ThreadSnoozeShell, options: { readonly now: string }, ): boolean { - if (shell.snoozedUntil == null) return false; + // With no wake time, a snooze holds until the thread is woken. + if (shell.snoozedUntil == null) + return shell.snoozedAt != null && !threadRaisedHandWhileSnoozed(shell); const wakeAtMs = Date.parse(shell.snoozedUntil); if (Number.isNaN(wakeAtMs)) return false; if (wakeAtMs <= Date.parse(options.now)) return false; @@ -168,8 +170,9 @@ export function threadWokeAt( shell: ThreadSnoozeShell, options: { readonly now: string }, ): string | null { - if (shell.snoozedUntil == null) return null; - const wakeAtMs = Date.parse(shell.snoozedUntil); + if (shell.snoozedUntil == null && shell.snoozedAt == null) return null; + const wakeAtMs = + shell.snoozedUntil == null ? Number.POSITIVE_INFINITY : Date.parse(shell.snoozedUntil); if (Number.isNaN(wakeAtMs)) return null; // An early hand-raise wake stays authoritative even after the scheduled // wake time passes: reporting snoozedUntil then would resurface a Woke @@ -192,7 +195,7 @@ export function threadWokeAt( const runtime = shell.runtime ?? shell.session ?? null; return runtime?.updatedAt ?? shell.snoozedAt ?? null; } - return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null; + return wakeAtMs <= Date.parse(options.now) ? (shell.snoozedUntil ?? null) : null; } const HOUR_MS = 60 * 60 * 1_000; @@ -347,7 +350,11 @@ export function pickSnoozePreset(input: { return (setting && resolveSnoozePreset(setting, input.now, input.formatTime)) ?? ahead; } -export function snoozeWakeLabel(snoozedUntil: string, options: { readonly now: string }): string { +export function snoozeWakeLabel( + snoozedUntil: string | null, + options: { readonly now: string }, +): string { + if (snoozedUntil === null) return "∞"; const wakeMs = Date.parse(snoozedUntil); const nowMs = Date.parse(options.now); if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return "now"; diff --git a/packages/client-runtime/src/state/threadSnoozed.test.ts b/packages/client-runtime/src/state/threadSnoozed.test.ts index 8518460386999..a223d7194fc62 100644 --- a/packages/client-runtime/src/state/threadSnoozed.test.ts +++ b/packages/client-runtime/src/state/threadSnoozed.test.ts @@ -78,6 +78,20 @@ function makeQueuedTurnShell(overrides: Partial = {}): QueuedTu } describe("effectiveSnoozed", () => { + it("holds a snooze with no wake time until a new question wakes it", () => { + const shell = makeShell({ snoozedUntil: null, snoozedAt: SNOOZED_AT }); + expect(effectiveSnoozed(shell, { now: NOW })).toBe(true); + expect(threadWokeAt(shell, { now: NOW })).toBeNull(); + const asking = makeShell({ + snoozedAt: SNOOZED_AT, + pending: "user-input", + pendingUserInputAt: "2026-04-10T11:00:00.000Z", + }); + expect(effectiveSnoozed(asking, { now: NOW })).toBe(false); + expect(threadWokeAt(asking, { now: NOW })).toBe("2026-04-10T11:00:00.000Z"); + expect(effectiveSnoozed(makeShell({}), { now: NOW })).toBe(false); + }); + it("never hides on malformed wake data", () => { expect(effectiveSnoozed(makeShell({ snoozedUntil: "not-a-date" }), { now: NOW })).toBe(false); }); @@ -514,6 +528,7 @@ describe("snoozeWakeLabel", () => { expect(snoozeWakeLabel(wake, { now: "2026-04-10T12:01:00.000Z" })).toBe("59m"); expect(snoozeWakeLabel(wake, { now: "2026-04-10T13:00:10.000Z" })).toBe("1m"); expect(snoozeWakeLabel(wake, { now: "2026-04-10T13:00:30.000Z" })).toBe("now"); + expect(snoozeWakeLabel(null, { now: NOW })).toBe("∞"); }); }); diff --git a/packages/client-runtime/src/state/threadUndo.test.ts b/packages/client-runtime/src/state/threadUndo.test.ts new file mode 100644 index 0000000000000..97b0a25884d55 --- /dev/null +++ b/packages/client-runtime/src/state/threadUndo.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vite-plus/test"; +import { executeThreadUndo, planThreadUndo } from "./threadUndo.ts"; + +describe("planThreadUndo", () => { + it("restores a snooze with no wake time after undoing a settle", async () => { + const now = "2026-11-17T02:00:00Z"; + const snoozed = { + snoozedAt: "2026-11-17T00:00:00Z", + snoozedUntil: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + }; + // A question asked since the snooze woke the thread; Undo leaves it awake. + expect( + planThreadUndo( + "settle", + { ...snoozed, hasPendingUserInput: true, pendingUserInputAt: "2026-11-17T01:00:00Z" }, + now, + ), + ).toEqual([{ action: "unsettle", restoreUnsettledAt: null }]); + const plan = planThreadUndo("settle", snoozed, now); + expect(plan).toEqual([ + { action: "unsettle", restoreUnsettledAt: null }, + { action: "snooze", snoozedUntil: null }, + ]); + const executed: string[] = []; + await executeThreadUndo( + plan, + async (step) => { + executed.push(step.action); + return true; + }, + (result) => result, + ); + expect(executed).toEqual(["unsettle", "snooze"]); + }); +}); diff --git a/packages/client-runtime/src/state/threadUndo.ts b/packages/client-runtime/src/state/threadUndo.ts index 20ea56400c284..7c2679ab8fe10 100644 --- a/packages/client-runtime/src/state/threadUndo.ts +++ b/packages/client-runtime/src/state/threadUndo.ts @@ -1,3 +1,5 @@ +import { effectiveSnoozed, type ThreadSnoozeShell } from "./threadSettled.ts"; + // Shared across hook instances so sidebar, header and menu actions invalidate each other. const currentActions = new Map(); const listeners = new Set<() => void>(); @@ -40,29 +42,34 @@ export type ThreadUndoStep = | { readonly action: "unsnooze" } | { readonly action: "pin"; readonly orderKey?: string } | { readonly action: "reorderActive"; readonly orderKey: string } - | { readonly action: "snooze"; readonly snoozedUntil: string }; + /** A null wake time restores a snooze that lasts until the thread is woken. */ + | { readonly action: "snooze"; readonly snoozedUntil: string | null }; export type ThreadUndoPlan = readonly [ThreadUndoStep, ...ThreadUndoStep[]]; export function planThreadUndo( action: "settle" | "snooze" | "unpin", - thread?: { - readonly pinnedAt?: string | null; - readonly pinOrderKey?: string | null; - readonly activeOrderKey?: string | null; - readonly unsettledAt?: string | null; - readonly snoozedUntil?: string | null; - } | null, + thread?: + | (ThreadSnoozeShell & { + readonly pinnedAt?: string | null; + readonly pinOrderKey?: string | null; + readonly activeOrderKey?: string | null; + readonly unsettledAt?: string | null; + }) + | null, + // @effect-diagnostics-next-line globalDate:off + now = new Date().toISOString(), ): ThreadUndoPlan { if (action === "snooze") return [{ action: "unsnooze" }]; const pin: ThreadUndoStep = { action: "pin", ...(thread?.pinOrderKey != null ? { orderKey: thread.pinOrderKey } : {}), }; - // Pinning clears snooze on the server; restore it after restoring pin placement. + // Pinning clears snooze on the server; restore it after restoring pin placement. A snooze a + // question or failure already woke stays woken, or the restore would hide the thread again. const snooze = - thread?.snoozedUntil != null - ? [{ action: "snooze" as const, snoozedUntil: thread.snoozedUntil }] + thread != null && effectiveSnoozed(thread, { now }) + ? [{ action: "snooze" as const, snoozedUntil: thread.snoozedUntil ?? null }] : []; if (action === "unpin") return [pin, ...snooze]; // Settling clears a manual active position; pinned threads are placed by their pin instead. @@ -88,8 +95,13 @@ export async function executeThreadUndo( for (const step of plan.slice(1)) { if (!succeeded(result)) return result; // A snooze can expire before Undo runs, and the server rejects an expired restore. - // @effect-diagnostics-next-line globalDate:off - if (step.action === "snooze" && Date.parse(step.snoozedUntil) <= Date.now()) continue; + if ( + step.action === "snooze" && + step.snoozedUntil !== null && + // @effect-diagnostics-next-line globalDate:off + Date.parse(step.snoozedUntil) <= Date.now() + ) + continue; result = await execute(step); } return result; diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 0b6164871a0ad..615608de46c15 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -45,9 +45,10 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.issuesUpdate]: AuthSourceControlWriteScope, [WS_METHODS.issuesSetState]: AuthSourceControlWriteScope, [WS_METHODS.issuesReact]: AuthSourceControlWriteScope, - // A tracker credential and a project's binding are settings, saved under the same grant. + // A tracker credential, a project's binding, and status rules are settings, under one grant. [WS_METHODS.issueTrackersConnect]: AuthSettingsWriteScope, [WS_METHODS.issueTrackersBindProject]: AuthSettingsWriteScope, + [WS_METHODS.issueTrackersSaveAutomation]: AuthSettingsWriteScope, // Writing a guide runs a model on this environment's providers, which reading one does not. [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope, [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope, diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 2a98ff1c583c3..00a6980b989d6 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -554,6 +554,8 @@ export const StandaloneIssueTrackerDescriptor = Schema.Struct({ ), ), }), + /** What issue status rules watch, when the tracker supports them: a Linear team, a Jira board. */ + automationContainer: Schema.optional(Schema.Literals(["team", "board"])), }); export type StandaloneIssueTrackerDescriptor = typeof StandaloneIssueTrackerDescriptor.Type; @@ -636,3 +638,86 @@ export class IssueTrackerConnectionError extends Schema.TaggedError()( + "IssueAutomationError", + { + operation: Schema.String, + detail: Schema.optional(TrimmedNonEmptyString), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.detail ?? "Issue status automation could not complete this operation."; + } +} diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 39543e9a5f261..19968773f79d1 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -509,6 +509,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ ), unsettledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), + /** Set with no `snoozedUntil`, the thread is snoozed until it is woken. */ snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecovery)), @@ -3193,7 +3194,8 @@ export const OrchestrationV2Command = Schema.Union([ type: Schema.Literal("thread.snooze"), commandId: CommandId, threadId: ThreadId, - snoozedUntil: IsoDateTime, + /** Null snoozes until someone or something wakes the thread. */ + snoozedUntil: Schema.NullOr(IsoDateTime), }), Schema.Struct({ type: Schema.Literal("thread.unsnooze"), @@ -3609,6 +3611,18 @@ export type OrchestrationV2Command = typeof OrchestrationV2Command.Type; // Excluded from dispatchCommand so only the server can send these. const OrchestrationV2InternalCommand = Schema.Union([ + /** + * A linked issue's status change, applied only if nothing organized the thread and no rule + * changed since the decision: `expectedRevision` and `rulesFingerprint` are what it saw. + */ + Schema.Struct({ + type: Schema.Literal("thread.issue-automation.apply"), + commandId: CommandId, + threadId: ThreadId, + action: Schema.Literals(["wake", "snooze", "settle"]), + expectedRevision: NonNegativeInt, + rulesFingerprint: Schema.String, + }), // Guest share commands the server issues after checking T3 Connect and the guest token. Schema.Struct({ type: Schema.Literal("thread.guest-share.open"), diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index d4206b74f2f57..4bd1b77f117d6 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -170,6 +170,11 @@ import { } from "./provider.ts"; import { ProviderInstanceId, ProviderInstanceMutation } from "./providerInstance.ts"; import { + IssueAutomationCatalog, + IssueAutomationCatalogInput, + IssueAutomationError, + IssueAutomationOverview, + IssueAutomationSaveInput, IssueCandidates, IssueCommentInput, IssueCommentsPage, @@ -186,6 +191,7 @@ import { IssueSetStateInput, IssueTemplateList, IssueTrackerBindProjectInput, + IssueTrackerKind, IssueTrackerConnectInput, IssueTrackerConnection, IssueTrackerConnectionError, @@ -637,9 +643,13 @@ export const WS_METHODS = { issuesUpdate: "issues.update", issuesSetState: "issues.setState", issuesReact: "issues.react", + issuesSubscribeStatusRefreshes: "issues.subscribeStatusRefreshes", issueTrackersList: "issueTrackers.list", issueTrackersConnect: "issueTrackers.connect", issueTrackersBindProject: "issueTrackers.bindProject", + issueTrackersAutomation: "issueTrackers.automation", + issueTrackersAutomationCatalog: "issueTrackers.automationCatalog", + issueTrackersSaveAutomation: "issueTrackers.saveAutomation", sourceControlLookupRepository: "sourceControl.lookupRepository", sourceControlCloneRepository: "sourceControl.cloneRepository", @@ -1418,6 +1428,35 @@ const WsIssueTrackersBindProjectRpc = Rpc.make(WS_METHODS.issueTrackersBindProje error: IssueTrackerRpcError, }); +const IssueAutomationRpcError = Schema.Union([IssueAutomationError, EnvironmentAuthorizationError]); + +/** Issue status rules and how each one's last status read went. */ +const WsIssueTrackersAutomationRpc = Rpc.make(WS_METHODS.issueTrackersAutomation, { + payload: Schema.Struct({}), + success: IssueAutomationOverview, + error: IssueAutomationRpcError, +}); + +const WsIssueTrackersAutomationCatalogRpc = Rpc.make(WS_METHODS.issueTrackersAutomationCatalog, { + payload: IssueAutomationCatalogInput, + success: IssueAutomationCatalog, + error: IssueAutomationRpcError, +}); + +const WsIssueTrackersSaveAutomationRpc = Rpc.make(WS_METHODS.issueTrackersSaveAutomation, { + payload: IssueAutomationSaveInput, + success: IssueAutomationOverview, + error: IssueAutomationRpcError, +}); + +/** Counts each status change rules saw on one issue, so an open detail reads it again. */ +const WsIssuesSubscribeStatusRefreshesRpc = Rpc.make(WS_METHODS.issuesSubscribeStatusRefreshes, { + payload: Schema.Struct({ tracker: IssueTrackerKind, key: TrimmedNonEmptyString }), + success: NonNegativeInt, + error: EnvironmentAuthorizationError, + stream: true, +}); + const WsSourceControlLookupRepositoryRpc = Rpc.make(WS_METHODS.sourceControlLookupRepository, { payload: SourceControlRepositoryLookupInput, success: SourceControlRepositoryInfo, @@ -2251,6 +2290,7 @@ export const WsRpcGroup = RpcGroup.make( WsIssuesCommentsRpc, WsIssuesTemplatesRpc, WsIssuesCandidatesRpc, + WsIssuesSubscribeStatusRefreshesRpc, WsIssuesCreateRpc, WsIssuesCommentRpc, WsIssuesUpdateRpc, @@ -2259,6 +2299,9 @@ export const WsRpcGroup = RpcGroup.make( WsIssueTrackersListRpc, WsIssueTrackersConnectRpc, WsIssueTrackersBindProjectRpc, + WsIssueTrackersAutomationRpc, + WsIssueTrackersAutomationCatalogRpc, + WsIssueTrackersSaveAutomationRpc, WsGuestShareCreateRpc, WsServerProbeRpc, WsServerGetConfigRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 36b1b538d4869..8d89070624953 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1,4 +1,5 @@ import { EasDeviceHostConfigs, SimlockDeviceHostConfigs, SshDeviceHostConfigs } from "./device.ts"; +import { IssueAutomationRule } from "./issue.ts"; import { AuthOrchestrationOperateScope, AuthAccessWriteScope, @@ -1458,6 +1459,10 @@ export const ServerSettings = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed(false)), ), idleCompaction: Schema.optionalKey(IdleCompactionMode), + /** Saved through IssueThreadAutomationService, which checks each rule with its tracker. */ + issueThreadAutomationRules: Schema.Array(IssueAutomationRule).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + ), snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), snoozePresets: SnoozePresetSettings.pipe( @@ -1908,6 +1913,7 @@ export const ServerSettingsPatch = Schema.Struct({ sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)), compactIdleThreads: Schema.optionalKey(LegacyCompactIdleThreads), idleCompaction: Schema.optionalKey(IdleCompactionMode), + issueThreadAutomationRules: Schema.optionalKey(Schema.Array(IssueAutomationRule)), sidebarAutoSettleKeepPullRequests: Schema.optionalKey(Schema.Boolean), sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean), autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean), @@ -1993,9 +1999,18 @@ export const ServerSettingsPatch = Schema.Struct({ }); export type ServerSettingsPatch = typeof ServerSettingsPatch.Type; -/** The theme service sets theme defaults after it validates them, so clients cannot. */ +/** + * The theme service sets theme defaults, and the issue automation service its rules, after they + * validate them, so clients cannot. + */ export const ClientServerSettingsPatch = ServerSettingsPatch.mapFields( - Struct.omit(["defaultTheme", "defaultThemeSetAt", "defaultAppearance", "defaultAppearanceSetAt"]), + Struct.omit([ + "defaultTheme", + "defaultThemeSetAt", + "defaultAppearance", + "defaultAppearanceSetAt", + "issueThreadAutomationRules", + ]), ); export function requiredScopesForServerSettingsPatch( diff --git a/packages/issue-tracker-jira/src/server/JiraApi.ts b/packages/issue-tracker-jira/src/server/JiraApi.ts index 215861267e78b..812cc4b710b1a 100644 --- a/packages/issue-tracker-jira/src/server/JiraApi.ts +++ b/packages/issue-tracker-jira/src/server/JiraApi.ts @@ -23,6 +23,9 @@ const REQUEST_TIMEOUT = "30 seconds"; const PAGE = 100; /** Pages read of a list that only feeds a picker; past it the list is reported truncated. */ const MAX_PAGES = 5; +/** Jira's agile API pages boards and a board's projects 50 at a time. */ +const BOARD_PAGE = 50; +const MAX_BOARD_PROJECT_PAGES = 10; const User = Schema.Struct({ accountId: Schema.String, @@ -76,6 +79,17 @@ const Issue = Schema.Struct({ }); export type JiraIssue = typeof Issue.Type; +const Board = Schema.Struct({ + id: Schema.Number, + name: Schema.String, + location: Schema.optional( + Schema.NullOr(Schema.Struct({ projectKey: Schema.optional(Schema.NullOr(Schema.String)) })), + ), +}); +export type JiraBoard = typeof Board.Type; + +const NamedStatus = Schema.Struct({ id: Schema.String, name: Schema.String }); + const Comment = Schema.Struct({ id: Schema.String, author: Schema.optional(Schema.NullOr(User)), @@ -228,6 +242,43 @@ export class JiraApi extends Context.Service< readonly findUsers: ( query: string, ) => Effect.Effect, IssueTrackerError>; + /** One page of the boards whose names hold `name`, or of one project's boards. */ + readonly boards: (input: { + readonly name?: string | undefined; + readonly projectKey?: string | undefined; + readonly startAt: number; + }) => Effect.Effect< + { readonly boards: ReadonlyArray; readonly isLast: boolean }, + IssueTrackerError + >; + readonly board: (id: string) => Effect.Effect; + /** The keys of every project whose issues the board shows. */ + readonly boardProjects: (id: string) => Effect.Effect, IssueTrackerError>; + /** The ids of the statuses the board's columns hold, in column order. */ + readonly boardStatusIds: ( + id: string, + ) => Effect.Effect, IssueTrackerError>; + readonly status: ( + id: string, + ) => Effect.Effect<{ readonly id: string; readonly name: string }, IssueTrackerError>; + readonly project: ( + key: string, + ) => Effect.Effect<{ readonly key: string; readonly name: string }, IssueTrackerError>; + /** A project's statuses, one list per issue type, each in its workflow's order. */ + readonly projectStatuses: ( + key: string, + ) => Effect.Effect< + ReadonlyArray>, + IssueTrackerError + >; + /** The status id of each issue the query finds, up to `limit`. */ + readonly issueStatuses: (input: { + readonly jql: string; + readonly limit: number; + }) => Effect.Effect< + ReadonlyArray<{ readonly key: string; readonly statusId: string }>, + IssueTrackerError + >; } >()("@t3tools/issue-tracker-jira/server/JiraApi") {} @@ -492,6 +543,116 @@ export const make = Effect.gen(function* () { query: { query, maxResults: 20 }, }); + const boards: JiraApi["Service"]["boards"] = (input) => + send( + "boards", + Schema.Struct({ values: Schema.Array(Board), isLast: Schema.optional(Schema.Boolean) }), + { + method: "GET", + path: "/rest/agile/1.0/board", + query: { + startAt: input.startAt, + maxResults: BOARD_PAGE, + name: input.name, + projectKeyOrId: input.projectKey, + }, + }, + ).pipe( + Effect.map((page) => ({ + boards: page.values, + isLast: page.isLast ?? page.values.length < BOARD_PAGE, + })), + ); + + const board: JiraApi["Service"]["board"] = (id) => + send("board", Board, { + method: "GET", + path: `/rest/agile/1.0/board/${encodeURIComponent(id)}`, + }); + + const boardProjects = Effect.fn("JiraApi.boardProjects")(function* (id: string) { + const keys: string[] = []; + for (let page = 0; page < MAX_BOARD_PROJECT_PAGES; page += 1) { + const answer = yield* send( + "boardProjects", + Schema.Struct({ + values: Schema.Array(Schema.Struct({ key: Schema.String })), + isLast: Schema.optional(Schema.Boolean), + }), + { + method: "GET", + path: `/rest/agile/1.0/board/${encodeURIComponent(id)}/project`, + query: { startAt: keys.length, maxResults: BOARD_PAGE }, + }, + ); + keys.push(...answer.values.map((project) => project.key)); + if ((answer.isLast ?? answer.values.length < BOARD_PAGE) || answer.values.length === 0) + return keys; + } + return yield* fail("boardProjects", "failed", "This Jira board spans too many projects."); + }); + + const boardStatusIds: JiraApi["Service"]["boardStatusIds"] = (id) => + send( + "boardStatusIds", + Schema.Struct({ + columnConfig: Schema.Struct({ + columns: Schema.Array( + Schema.Struct({ statuses: Schema.Array(Schema.Struct({ id: Schema.String })) }), + ), + }), + }), + { method: "GET", path: `/rest/agile/1.0/board/${encodeURIComponent(id)}/configuration` }, + ).pipe( + Effect.map((config) => [ + ...new Set( + config.columnConfig.columns.flatMap((column) => + column.statuses.map((status) => status.id), + ), + ), + ]), + ); + + const status: JiraApi["Service"]["status"] = (id) => + send("status", NamedStatus, { + method: "GET", + path: `/rest/api/3/status/${encodeURIComponent(id)}`, + }); + + const project: JiraApi["Service"]["project"] = (key) => + send("project", Schema.Struct({ key: Schema.String, name: Schema.String }), { + method: "GET", + path: `/rest/api/3/project/${encodeURIComponent(key)}`, + }); + + const projectStatuses: JiraApi["Service"]["projectStatuses"] = (key) => + send("projectStatuses", Schema.Array(Schema.Struct({ statuses: Schema.Array(NamedStatus) })), { + method: "GET", + path: `/rest/api/3/project/${encodeURIComponent(key)}/statuses`, + }).pipe(Effect.map((types) => types.map((type) => type.statuses))); + + const issueStatuses: JiraApi["Service"]["issueStatuses"] = (input) => + send( + "issueStatuses", + Schema.Struct({ + issues: Schema.Array( + Schema.Struct({ + key: Schema.String, + fields: Schema.Struct({ status: Schema.Struct({ id: Schema.String }) }), + }), + ), + }), + { + method: "POST", + path: "/rest/api/3/search/jql", + body: { jql: input.jql, maxResults: input.limit, fields: ["status"] }, + }, + ).pipe( + Effect.map((page) => + page.issues.map((issue) => ({ key: issue.key, statusId: issue.fields.status.id })), + ), + ); + return JiraApi.of({ origin: storedSite("origin").pipe(Effect.map((site) => site.origin)), myself, @@ -508,6 +669,14 @@ export const make = Effect.gen(function* () { labels, assignable, findUsers, + boards, + board, + boardProjects, + boardStatusIds, + status, + project, + projectStatuses, + issueStatuses, }); }); diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts index 6c8858ae07301..983b90ba785ff 100644 --- a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts @@ -444,3 +444,259 @@ describe("JiraIssueTracker", () => { }), ); }); + +describe("Jira board status rules", () => { + const credential: IssueTrackerCredential = { + token: "tok_rules", + fields: { site: "acme", email: "sam.rivera@acme.test" }, + }; + const SITE = "acme.atlassian.net"; + const board = (id: number, name: string, projectKey?: string) => ({ + id, + name, + type: "kanban", + ...(projectKey === undefined ? {} : { location: { projectKey, projectName: projectKey } }), + }); + const automationOf = (api: StandaloneIssueTrackerApi) => { + if (api.automation === undefined) throw new Error("Jira offers no status rules"); + return api.automation; + }; + + it.effect("searches boards by name a page at a time, and finds a project's by its key", () => + Effect.gen(function* () { + const { tracker, requests } = fakeJira( + { + "GET /rest/agile/1.0/board": ({ query }) => { + if (query.get("projectKeyOrId") === "OPS") + return { values: [board(31, "Ops triage", "OPS")], isLast: true }; + const startAt = Number(query.get("startAt")); + return query.get("name") === null + ? { values: [board(startAt + 1, "Delivery", "ENG")], isLast: false } + : { values: [board(startAt + 7, "Ops review")], isLast: true }; + }, + "GET /rest/api/3/project/OPS": () => ({ key: "OPS", name: "Operations" }), + }, + credential, + ); + const automation = automationOf(yield* tracker); + expect(yield* automation.listContainers({})).toEqual({ + workspace: SITE, + containers: [{ id: "1", name: "Delivery (ENG)" }], + nextCursor: "1", + }); + expect(yield* automation.listContainers({ query: "Ops review", cursor: "50" })).toEqual({ + workspace: SITE, + containers: [{ id: "57", name: "Ops review" }], + nextCursor: null, + }); + expect(requests.at(-1)?.query.get("name")).toBe("Ops review"); + expect(requests.at(-1)?.query.get("startAt")).toBe("50"); + // A project key also lists that project's boards, ahead of the boards named like it. + expect((yield* automation.listContainers({ query: "ops" })).containers).toEqual([ + { id: "31", name: "Ops triage (OPS)" }, + { id: "7", name: "Ops review" }, + ]); + // Each search reads one bounded page, never the whole site. + const listings = requests.filter((request) => request.path === "/rest/agile/1.0/board"); + expect(listings.map((request) => request.query.get("maxResults"))).toEqual( + listings.map(() => "50"), + ); + expect(listings).toHaveLength(4); + }), + ); + + it.effect("reads a board's statuses from its column mapping", () => + Effect.gen(function* () { + const { tracker } = fakeJira( + { + "GET /rest/agile/1.0/board/12": () => board(12, "Delivery", "ENG"), + "GET /rest/agile/1.0/board/404": () => + Response.json({ errorMessages: ["The board does not exist."] }, { status: 404 }), + "GET /rest/agile/1.0/board/12/configuration": () => ({ + columnConfig: { + columns: [ + { name: "To do", statuses: [{ id: "1" }] }, + { name: "Doing", statuses: [{ id: "3" }, { id: "4" }] }, + { name: "Done", statuses: [{ id: "4" }, { id: "6" }] }, + ], + }, + }), + "GET /rest/api/3/status/1": () => ({ id: "1", name: "To Do" }), + "GET /rest/api/3/status/3": () => ({ id: "3", name: "In Progress" }), + "GET /rest/api/3/status/4": () => ({ id: "4", name: "In Review" }), + "GET /rest/api/3/status/6": () => ({ id: "6", name: "Done" }), + }, + credential, + ); + const automation = automationOf(yield* tracker); + expect(yield* automation.getContainer("12")).toEqual({ + workspace: SITE, + container: { id: "12", name: "Delivery (ENG)" }, + }); + expect((yield* automation.getContainer("404")).container).toBeNull(); + expect(yield* automation.listStates({ workspace: SITE, containerId: "12" })).toEqual([ + { id: "1", name: "To Do" }, + { id: "3", name: "In Progress" }, + { id: "4", name: "In Review" }, + { id: "6", name: "Done" }, + ]); + }), + ); + + it.effect("reads only the board's projects' linked issues, in batches of JQL searches", () => + Effect.gen(function* () { + const searched: string[] = []; + const { tracker, requests } = fakeJira( + { + "GET /rest/agile/1.0/board/12/project": () => ({ + values: [{ key: "ENG" }, { key: "WEB" }], + isLast: true, + }), + "POST /rest/api/3/search/jql": ({ body }) => { + const { jql, fields } = body as { jql: string; fields: ReadonlyArray }; + expect(fields).toEqual(["status"]); + searched.push(jql); + return { + issues: [...jql.matchAll(/"([A-Z]+-\d+)"/gu)].map(([, key]) => ({ + key, + fields: { status: { id: key === "ENG-1" ? "4" : "1" } }, + })), + }; + }, + }, + credential, + ); + const automation = automationOf(yield* tracker); + const keys = [ + "ENG-1", + "eng-1", + "OPS-1", + "not a key", + "WEB-2", + ...Array.from({ length: 60 }, (_, index) => `ENG-${index + 10}`), + ]; + const statuses = yield* automation.readStatuses({ workspace: SITE, containerId: "12", keys }); + expect(statuses).toHaveLength(62); + expect(statuses.slice(0, 2)).toEqual([ + { key: "ENG-1", stateId: "4" }, + { key: "WEB-2", stateId: "1" }, + ]); + // OPS is not on the board, so its issue is never asked for; 62 keys take two searches. + expect(searched).toHaveLength(2); + expect(searched[0]).toMatch(/^key in \("ENG-1", "WEB-2", "ENG-10", /u); + expect(searched.join(" ")).not.toContain("OPS-1"); + expect(requests.filter((request) => request.method === "POST")).toHaveLength(2); + }), + ); + + it.effect("leaves out a linked issue Jira says does not exist", () => + Effect.gen(function* () { + const searched: string[] = []; + const { tracker } = fakeJira( + { + "GET /rest/agile/1.0/board/12/project": () => ({ values: [{ key: "ENG" }] }), + "POST /rest/api/3/search/jql": ({ body }) => { + const { jql } = body as { jql: string }; + searched.push(jql); + return jql.includes("ENG-404") + ? Response.json( + { + errorMessages: ["An issue with key 'ENG-404' does not exist for field 'key'."], + }, + { status: 400 }, + ) + : { issues: [{ key: "ENG-1", fields: { status: { id: "4" } } }] }; + }, + }, + credential, + ); + const automation = automationOf(yield* tracker); + expect( + yield* automation.readStatuses({ + workspace: SITE, + containerId: "12", + keys: ["ENG-1", "ENG-404"], + }), + ).toEqual([{ key: "ENG-1", stateId: "4" }]); + expect(searched).toEqual(['key in ("ENG-1", "ENG-404")', 'key in ("ENG-1")']); + }), + ); + + it.effect( + "offers a Service Management project without boards, with its issue types' statuses", + () => + Effect.gen(function* () { + const { tracker, requests } = fakeJira( + { + "GET /rest/agile/1.0/board": () => ({ values: [], isLast: true }), + "GET /rest/api/3/project/HELP": () => ({ key: "HELP", name: "Help Center" }), + "GET /rest/api/3/project/HELP/statuses": () => [ + { + id: "10001", + name: "Service request", + statuses: [ + { id: "20", name: "Waiting for support" }, + { id: "21", name: "In progress" }, + { id: "22", name: "Resolved" }, + ], + }, + { + id: "10002", + name: "Incident", + statuses: [ + { id: "20", name: "Waiting for support" }, + { id: "23", name: "Waiting for customer" }, + { id: "22", name: "Resolved" }, + ], + }, + ], + "POST /rest/api/3/search/jql": () => ({ + issues: [{ key: "HELP-3", fields: { status: { id: "23" } } }], + }), + }, + credential, + ); + const automation = automationOf(yield* tracker); + expect((yield* automation.listContainers({ query: "HELP" })).containers).toEqual([ + { id: "project:HELP", name: "Help Center (HELP)" }, + ]); + expect((yield* automation.getContainer("project:HELP")).container).toEqual({ + id: "project:HELP", + name: "Help Center (HELP)", + }); + expect( + (yield* automation.listStates({ workspace: SITE, containerId: "project:HELP" })).map( + (state) => state.name, + ), + ).toEqual(["Waiting for support", "In progress", "Resolved", "Waiting for customer"]); + expect( + yield* automation.readStatuses({ + workspace: SITE, + containerId: "project:HELP", + keys: ["HELP-3", "ENG-1"], + }), + ).toEqual([{ key: "HELP-3", stateId: "23" }]); + expect(requests.at(-1)?.body).toMatchObject({ jql: 'key in ("HELP-3")' }); + }), + ); + + it.effect("refuses a rule made on another site and names each link's site", () => + Effect.gen(function* () { + const { tracker, requests } = fakeJira({}, credential); + const api = yield* tracker; + const refused = yield* automationOf(api) + .readStatuses({ workspace: "other.atlassian.net", containerId: "12", keys: ["ENG-1"] }) + .pipe(Effect.flip); + expect(refused.reason).toBe("failed"); + expect(requests).toEqual([]); + expect(api.parseIssueUrl?.(new URL("https://ACME.atlassian.net/browse/eng-7"))).toEqual({ + host: "atlassian.net", + workspace: SITE, + scope: "ENG", + key: "ENG-7", + }); + expect(api.parseIssueUrl?.(new URL("http://acme.atlassian.net/browse/ENG-7"))).toBeNull(); + expect(api.parseIssueUrl?.(new URL("https://acme.atlassian.net/jira/ENG-7"))).toBeNull(); + }), + ); +}); diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts index 52ed16771ac8c..e69a8ba3b017d 100644 --- a/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts @@ -39,6 +39,7 @@ const DESCRIPTOR: StandaloneIssueTrackerDescriptor = { { key: "email", label: "Account email", placeholder: "you@example.com" }, ], }, + automationContainer: "board", }; /** No reactions or development panel: Jira Cloud's public API serves neither. */ @@ -65,6 +66,12 @@ const EVERYTHING: IssueViewerPermissions = { const COMMENTS_PAGE = 50; const CATEGORY_ORDER = ["new", "indeterminate", "done"]; +/** Keys per status search, which keeps each JQL query and its answer to one page. */ +const STATUS_READ_BATCH = 50; +const ISSUE_KEY = /^[A-Z][A-Z0-9_]*-[1-9]\d*$/u; +const PROJECT_KEY = /^[A-Z][A-Z0-9_]*$/iu; +/** A rule on a project rather than a board: a Service Management project has no board. */ +const PROJECT_CONTAINER = "project:"; /** Jira writes `+0000` where ISO 8601 has `+00:00`. */ function iso(value: string): string { @@ -218,6 +225,25 @@ function involvementClause(involvement: IssueInvolvement): string | null { } } +/** A board, named with its project's key when it lives in one, since board names repeat. */ +function boardOption(board: JiraApi.JiraBoard) { + const project = board.location?.projectKey?.trim(); + return { id: String(board.id), name: project ? `${board.name} (${project})` : board.name }; +} + +/** `https:///browse/`, the workspace being the site. */ +function parseIssueUrl(url: URL) { + if (url.protocol !== "https:" || url.username || url.password) return null; + const key = /^\/browse\/([A-Z][A-Z0-9_]*-[1-9]\d*)\/?$/iu.exec(url.pathname)?.[1]?.toUpperCase(); + if (key === undefined) return null; + return { + host: DESCRIPTOR.host, + workspace: url.host.toLowerCase(), + scope: key.slice(0, key.lastIndexOf("-")), + key, + }; +} + const sameText = (a: string | null | undefined, b: string) => a != null && a.trim().toLowerCase() === b.trim().toLowerCase(); @@ -299,10 +325,154 @@ export const make: Effect.Effect new URL(origin).host.toLowerCase())); + + /** Board ids are only unique on one site, so a rule saved on another is refused. */ + const requireSite = Effect.fn("JiraIssueTracker.requireSite")(function* (workspace: string) { + if ((yield* site) !== workspace.toLowerCase()) + return yield* JiraApi.fail( + "automation", + "failed", + "The connected Jira site is not the one this rule was made on.", + ); + }); + + const whenFound = (effect: Effect.Effect) => + effect.pipe( + Effect.map((value): A | null => value), + Effect.catchIf( + (error) => error.reason === "not-found", + () => Effect.succeed(null), + ), + ); + + /** A project key's boards, or the project itself when it has none. */ + const projectContainers = Effect.fn("JiraIssueTracker.projectContainers")(function* ( + key: string, + ) { + const project = yield* whenFound(jira.project(key)); + if (project === null) return []; + const { boards } = yield* jira.boards({ projectKey: key, startAt: 0 }); + return boards.length > 0 + ? boards.map(boardOption) + : [{ id: `${PROJECT_CONTAINER}${key}`, name: `${project.name} (${key})` }]; + }); + + /** The status id of each key, read in batches; a key Jira says does not exist is left out. */ + const readKeyStatuses = Effect.fn("JiraIssueTracker.readKeyStatuses")(function* ( + keys: ReadonlyArray, + ) { + const statuses: Array<{ readonly key: string; readonly stateId: string }> = []; + for (let start = 0; start < keys.length; start += STATUS_READ_BATCH) { + let batch = keys.slice(start, start + STATUS_READ_BATCH); + while (batch.length > 0) { + const read = yield* jira + .issueStatuses({ jql: `key in (${batch.map(quoted).join(", ")})`, limit: batch.length }) + .pipe(Effect.result); + if (read._tag === "Success") { + statuses.push(...read.success.map((row) => ({ key: row.key, stateId: row.statusId }))); + break; + } + // JQL refuses the whole query over one key it cannot find, naming that key. + const missing = batch.filter((key) => read.failure.detail.includes(`'${key}'`)); + if (read.failure.reason !== "failed" || missing.length === 0) return yield* read.failure; + batch = batch.filter((key) => !missing.includes(key)); + } + } + return statuses; + }); + const api: StandaloneIssueTrackerApi = { kind: JiraApi.KIND, capabilities: CAPABILITIES, standalone: DESCRIPTOR, + parseIssueUrl, + + automation: { + listContainers: Effect.fn("JiraIssueTracker.listContainers")(function* (input) { + const startAt = input.cursor === undefined ? 0 : Number(input.cursor); + if (!Number.isSafeInteger(startAt) || startAt < 0) + return yield* JiraApi.fail("listContainers", "failed", "Invalid Jira board page."); + const query = input.query?.trim() || undefined; + const [workspace, page, byKey] = yield* Effect.all( + [ + site, + jira.boards({ name: query, startAt }), + // A project key also finds the project's boards, whatever they are named. + startAt === 0 && query !== undefined && PROJECT_KEY.test(query) + ? projectContainers(query.toUpperCase()) + : Effect.succeed([]), + ], + { concurrency: "unbounded" }, + ); + const containers = [ + ...new Map( + [...byKey, ...page.boards.map(boardOption)] + .filter((option) => option.name.trim().length > 0) + .map((option) => [option.id, option]), + ).values(), + ]; + return { + workspace, + containers, + nextCursor: + page.isLast || page.boards.length === 0 ? null : String(startAt + page.boards.length), + }; + }), + getContainer: Effect.fn("JiraIssueTracker.getContainer")(function* (containerId) { + const workspace = yield* site; + if (containerId.startsWith(PROJECT_CONTAINER)) { + const key = containerId.slice(PROJECT_CONTAINER.length).toUpperCase(); + const project = PROJECT_KEY.test(key) ? yield* whenFound(jira.project(key)) : null; + return { + workspace, + container: + project === null + ? null + : { id: `${PROJECT_CONTAINER}${key}`, name: `${project.name} (${key})` }, + }; + } + const board = /^[1-9]\d*$/u.test(containerId) + ? yield* whenFound(jira.board(containerId)) + : null; + return { workspace, container: board === null ? null : boardOption(board) }; + }), + listStates: Effect.fn("JiraIssueTracker.listStates")(function* (input) { + yield* requireSite(input.workspace); + if (input.containerId.startsWith(PROJECT_CONTAINER)) { + // Service Management workflows are set per issue type; each lists its own statuses. + const types = yield* jira.projectStatuses( + input.containerId.slice(PROJECT_CONTAINER.length), + ); + return [...new Map(types.flat().map((status) => [status.id, status])).values()].map( + ({ id, name }) => ({ id, name }), + ); + } + const ids = yield* jira.boardStatusIds(input.containerId); + return yield* Effect.forEach(ids, jira.status, { concurrency: 4 }).pipe( + Effect.map((statuses) => statuses.map(({ id, name }) => ({ id, name }))), + ); + }), + readStatuses: Effect.fn("JiraIssueTracker.readStatuses")(function* (input) { + yield* requireSite(input.workspace); + const projects = new Set( + input.containerId.startsWith(PROJECT_CONTAINER) + ? [input.containerId.slice(PROJECT_CONTAINER.length).toUpperCase()] + : (yield* jira.boardProjects(input.containerId)).map((key) => key.toUpperCase()), + ); + // Only the board's projects' issues are on it; any other key is left out unread. + const keys = [ + ...new Set( + input.keys + .map((key) => key.trim().toUpperCase()) + .filter( + (key) => ISSUE_KEY.test(key) && projects.has(key.slice(0, key.lastIndexOf("-"))), + ), + ), + ]; + return yield* readKeyStatuses(keys); + }), + }, probeCredential: (credential) => Effect.all([jira.myself(credential), jira.projects(credential)], { diff --git a/packages/issue-tracker-linear/src/server/LinearApi.graphql b/packages/issue-tracker-linear/src/server/LinearApi.graphql index a9d606ab52e59..b8fdb597b1a3c 100644 --- a/packages/issue-tracker-linear/src/server/LinearApi.graphql +++ b/packages/issue-tracker-linear/src/server/LinearApi.graphql @@ -96,6 +96,9 @@ query T3Viewer { viewer { ...LinearUser } + organization { + urlKey + } teams(first: 250) { nodes { id @@ -298,3 +301,24 @@ query T3CommentReactions($id: String!) { } } } + +query T3TeamStates($id: String!) { + team(id: $id) { + states(first: 250) { + nodes { + ...LinearWorkflowState + } + } + } +} + +query T3IssueStates($teamId: ID!, $numbers: [Float!]!) { + issues(first: 250, filter: { team: { id: { eq: $teamId } }, number: { in: $numbers } }) { + nodes { + identifier + state { + id + } + } + } +} diff --git a/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts b/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts index 90cf22d35c4de..44c067d3b2d42 100644 --- a/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts +++ b/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts @@ -184,6 +184,13 @@ export const LinearPageInfo = Schema.Struct({ }) export interface LinearPageInfo extends Schema.Struct.Type {} +/** A workspace (referred to as Organization in the API). Workspaces are the root-level container for all teams, users, projects, issues, and settings. Every user belongs to at least one workspace, and all data is scoped within a workspace boundary. */ +export const Organization = Schema.Struct({ + /** The workspace's unique URL key, used in URLs to identify the workspace. */ + urlKey: Schema.String +}) +export interface Organization extends Schema.Struct.Type {} + /** A team is the primary organizational unit in Linear. Issues belong to teams, and each team has its own workflow states, cycles, labels, and settings. Teams can be public (visible to all workspace members), private (visible only to team members), or restricted (visible only within an enclosing private-team boundary). Teams can also have sub-teams that inherit settings from their parent. */ export const T3ViewerTeamsNodesTeam = Schema.Struct({ /** The unique identifier of the entity. */ @@ -206,6 +213,7 @@ export const T3Viewer = GraphQL.query("T3Viewer", { variables: [], selections: [ { name: "viewer", body: ["{...LinearUser}"] }, + { name: "organization", body: ["{urlKey}"] }, { name: "teams", body: ["(first:250){nodes{id key name}}"] } ], fragments: [ @@ -215,6 +223,8 @@ export const T3Viewer = GraphQL.query("T3Viewer", { result: Schema.Struct({ /** The currently authenticated user making the API request. */ viewer: LinearUser, + /** The authenticated user's workspace. */ + organization: Organization, /** All teams whose issues the user can access. This includes public teams and private teams the user is a member of. This may differ from `administrableTeams`, which returns teams whose settings the user can change but whose issues they don't necessarily have access to. */ teams: T3ViewerTeamsTeamConnection }) @@ -224,11 +234,11 @@ export declare namespace T3Viewer { export type Result = typeof T3Viewer.result.Type } -export const IssueConnection = Schema.Struct({ +export const T3IssuesIssuesIssueConnection = Schema.Struct({ nodes: Schema.Array(LinearIssue), pageInfo: LinearPageInfo }) -export interface IssueConnection extends Schema.Struct.Type {} +export interface T3IssuesIssuesIssueConnection extends Schema.Struct.Type {} /** `query T3Issues` */ export const T3Issues = GraphQL.query("T3Issues", { @@ -259,7 +269,7 @@ export const T3Issues = GraphQL.query("T3Issues", { }, result: Schema.Struct({ /** All issues. Returns a paginated list of issues visible to the authenticated user. Can be filtered by various criteria including team, assignee, state, labels, project, and cycle. */ - issues: IssueConnection + issues: T3IssuesIssuesIssueConnection }) }) export declare namespace T3Issues { @@ -807,5 +817,85 @@ export declare namespace T3CommentReactions { export type Result = typeof T3CommentReactions.result.Type } +/** A team is the primary organizational unit in Linear. Issues belong to teams, and each team has its own workflow states, cycles, labels, and settings. Teams can be public (visible to all workspace members), private (visible only to team members), or restricted (visible only within an enclosing private-team boundary). Teams can also have sub-teams that inherit settings from their parent. */ +export const T3TeamStatesTeamTeam = Schema.Struct({ + /** The states that define the workflow associated with the team. */ + states: TeamStatesWorkflowStateConnection +}) +export interface T3TeamStatesTeamTeam extends Schema.Struct.Type {} + +/** `query T3TeamStates` */ +export const T3TeamStates = GraphQL.query("T3TeamStates", { + document: { + variables: [ + { name: "id", body: "String!" } + ], + selections: [ + { name: "team", body: ["(id:$", "id", "){states(first:250){nodes{...LinearWorkflowState}}}"] } + ], + fragments: [ + { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] } + ] + }, + variables: { + id: Schema.String + }, + result: Schema.Struct({ + /** Fetches a specific team by its ID. */ + team: T3TeamStatesTeamTeam + }) +}) +export declare namespace T3TeamStates { + export type Variables = typeof T3TeamStates.variables.Type + export type Result = typeof T3TeamStates.result.Type +} + +/** A state in a team's workflow, representing an issue status such as Triage, Backlog, Todo, In Progress, In Review, Done, or Canceled. Each team has its own set of workflow states that define the progression of issues through the team's process. Workflow states have a type that categorizes them (triage, backlog, unstarted, started, completed, canceled), a position that determines their display order, and a color for visual identification. States can be inherited from parent teams to sub-teams. */ +export const WorkflowState = Schema.Struct({ + /** The unique identifier of the entity. */ + id: Shared.ID +}) +export interface WorkflowState extends Schema.Struct.Type {} + +/** An issue is the core work item in Linear. Issues belong to a team, have a workflow status, can be assigned to users, carry a priority level, and can be organized into projects and cycles. Issues support sub-issues (parent-child hierarchy up to 10 levels deep), labels, due dates, estimates, and SLA tracking. They can also be linked to other issues via relations, attached to releases, and tracked through their full history of changes. */ +export const NodesIssue = Schema.Struct({ + /** Issue's human readable identifier (e.g. ENG-123). */ + identifier: Schema.String, + /** The workflow state (issue status) that the issue is currently in. Workflow states represent the issue's progress through the team's workflow, such as Triage, Todo, In Progress, Done, or Canceled. */ + state: WorkflowState +}) +export interface NodesIssue extends Schema.Struct.Type {} + +export const T3IssueStatesIssuesIssueConnection = Schema.Struct({ + nodes: Schema.Array(NodesIssue) +}) +export interface T3IssueStatesIssuesIssueConnection extends Schema.Struct.Type {} + +/** `query T3IssueStates` */ +export const T3IssueStates = GraphQL.query("T3IssueStates", { + document: { + variables: [ + { name: "teamId", body: "ID!" }, + { name: "numbers", body: "[Float!]!" } + ], + selections: [ + { name: "issues", body: ["(first:250 filter:{team:{id:{eq:$", "teamId", "}}number:{in:$", "numbers", "}}){nodes{identifier state{id}}}"] } + ], + fragments: [] + }, + variables: { + teamId: Shared.ID, + numbers: Schema.Array(Shared.Float) + }, + result: Schema.Struct({ + /** All issues. Returns a paginated list of issues visible to the authenticated user. Can be filtered by various criteria including team, assignee, state, labels, project, and cycle. */ + issues: T3IssueStatesIssuesIssueConnection + }) +}) +export declare namespace T3IssueStates { + export type Variables = typeof T3IssueStates.variables.Type + export type Result = typeof T3IssueStates.result.Type +} + /** Every operation in LinearApi.graphql. */ -export const LinearApiGraphQLGroup = GraphQLGroup.make(T3Viewer, T3Issues, T3Issue, T3Comments, T3Team, T3IssueCreate, T3IssueUpdate, T3CommentCreate, T3ReactionCreate, T3ReactionDelete, T3IssueReactions, T3CommentReactions) +export const LinearApiGraphQLGroup = GraphQLGroup.make(T3Viewer, T3Issues, T3Issue, T3Comments, T3Team, T3IssueCreate, T3IssueUpdate, T3CommentCreate, T3ReactionCreate, T3ReactionDelete, T3IssueReactions, T3CommentReactions, T3TeamStates, T3IssueStates) diff --git a/packages/issue-tracker-linear/src/server/LinearApi.ts b/packages/issue-tracker-linear/src/server/LinearApi.ts index b5d891923eda0..bc4efb2a86fb3 100644 --- a/packages/issue-tracker-linear/src/server/LinearApi.ts +++ b/packages/issue-tracker-linear/src/server/LinearApi.ts @@ -37,6 +37,7 @@ import { type LinearReaction, type LinearTeamLabel, type LinearUser, + type LinearWorkflowState, type T3Issue, type T3Team, type Template, @@ -97,6 +98,8 @@ export class LinearApi extends Context.Service< readonly viewer: (token?: string) => Effect.Effect< { readonly viewer: LinearUser; + /** The workspace's URL key, the first path segment of its issue links. */ + readonly workspace: string; readonly teams: ReadonlyArray<{ readonly id: string; readonly key: string; @@ -128,6 +131,18 @@ export class LinearApi extends Context.Service< IssueTrackerError >; readonly getTeam: (key: string) => Effect.Effect; + /** A team's workflow states by the team's id, which stays when its key is renamed. */ + readonly getTeamStates: ( + teamId: string, + ) => Effect.Effect, IssueTrackerError>; + /** The state of each issue with one of these numbers in the team; up to 250 numbers. */ + readonly getIssueStates: (input: { + readonly teamId: string; + readonly numbers: ReadonlyArray; + }) => Effect.Effect< + ReadonlyArray<{ readonly identifier: string; readonly stateId: string }>, + IssueTrackerError + >; readonly createIssue: ( input: IssueCreateInput, ) => Effect.Effect<{ readonly identifier: string; readonly url: string }, IssueTrackerError>; @@ -294,7 +309,11 @@ export const make = Effect.gen(function* () { const viewer: LinearApi["Service"]["viewer"] = (token) => call("viewer", (linear) => linear.T3Viewer(), token).pipe( - Effect.map((data) => ({ viewer: data.viewer, teams: data.teams.nodes })), + Effect.map((data) => ({ + viewer: data.viewer, + workspace: data.organization.urlKey, + teams: data.teams.nodes, + })), ); const listIssues: LinearApi["Service"]["listIssues"] = (input) => @@ -364,6 +383,23 @@ export const make = Effect.gen(function* () { }), ); + const getTeamStates: LinearApi["Service"]["getTeamStates"] = (teamId) => + call("getTeamStates", (linear) => linear.T3TeamStates({ id: teamId })).pipe( + Effect.map((data) => data.team.states.nodes), + ); + + const getIssueStates: LinearApi["Service"]["getIssueStates"] = (input) => + call("getIssueStates", (linear) => + linear.T3IssueStates({ teamId: input.teamId, numbers: input.numbers }), + ).pipe( + Effect.map((data) => + data.issues.nodes.map((issue) => ({ + identifier: issue.identifier, + stateId: issue.state.id, + })), + ), + ); + const createIssue: LinearApi["Service"]["createIssue"] = (input) => call("createIssue", (linear) => linear.T3IssueCreate({ input })).pipe( Effect.flatMap(({ issueCreate }) => @@ -423,6 +459,8 @@ export const make = Effect.gen(function* () { getIssue, getComments, getTeam, + getTeamStates, + getIssueStates, createIssue, updateIssue, createComment, diff --git a/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts b/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts index 47d98849c810d..c6619a6c8f4cd 100644 --- a/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts +++ b/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts @@ -135,7 +135,11 @@ describe("LinearIssueTracker", () => { it.effect("lists a team's issues as summaries keyed by identifier", () => Effect.gen(function* () { const { tracker, requests } = fakeLinear({ - T3Viewer: () => ({ viewer: JULIUS, teams: { nodes: [] } }), + T3Viewer: () => ({ + viewer: JULIUS, + organization: { urlKey: "acme" }, + teams: { nodes: [] }, + }), T3Issues: (variables) => { expect(variables.filter).toMatchObject({ team: { key: { eq: "ENG" } }, @@ -223,7 +227,11 @@ describe("LinearIssueTracker", () => { const created: Array = []; const deleted: Array = []; const { tracker } = fakeLinear({ - T3Viewer: () => ({ viewer: JULIUS, teams: { nodes: [] } }), + T3Viewer: () => ({ + viewer: JULIUS, + organization: { urlKey: "acme" }, + teams: { nodes: [] }, + }), T3Issue: (variables) => { // Linear refuses a page of zero comments, which fails the write that looked the issue up. expect(variables.comments).toBeGreaterThan(0); @@ -264,7 +272,11 @@ describe("LinearIssueTracker", () => { it.effect("reads an issue with its comments, reactions, history and linked pull requests", () => Effect.gen(function* () { const { tracker } = fakeLinear({ - T3Viewer: () => ({ viewer: JULIUS, teams: { nodes: [] } }), + T3Viewer: () => ({ + viewer: JULIUS, + organization: { urlKey: "acme" }, + teams: { nodes: [] }, + }), T3Issue: () => ({ issue: issue("ENG-7", { comments: { @@ -489,4 +501,69 @@ describe("LinearIssueTracker", () => { link: { name: "Intake", about: "", url: "https://linear.app/team/ENG/new?template=tpl_2" }, }); }); + + it.effect("reads a team's workflow and its issues' states by team id for status rules", () => + Effect.gen(function* () { + const numbers: Array> = []; + const { tracker } = fakeLinear({ + T3Viewer: () => ({ + viewer: JULIUS, + organization: { urlKey: "acme" }, + teams: { nodes: [{ id: "team_eng", key: "ENG", name: "Engineering" }] }, + }), + T3TeamStates: (variables) => { + expect(variables.id).toBe("team_eng"); + return { + team: { + states: { + nodes: [ + state("Done", "completed", 2), + state("In Progress", "started", 1), + state("Todo", "unstarted", 0), + ], + }, + }, + }; + }, + T3IssueStates: (variables) => { + expect(variables.teamId).toBe("team_eng"); + const batch = variables.numbers as ReadonlyArray; + numbers.push(batch); + return { + issues: { + nodes: batch.includes(1) ? [{ identifier: "ENG-1", state: { id: "st_done" } }] : [], + }, + }; + }, + }); + const automation = (yield* tracker).automation; + expect(yield* automation.listContainers({})).toEqual({ + workspace: "acme", + containers: [{ id: "team_eng", name: "Engineering (ENG)" }], + nextCursor: null, + }); + expect((yield* automation.listContainers({ query: "ENGIN" })).containers).toHaveLength(1); + expect((yield* automation.listContainers({ query: "Support" })).containers).toEqual([]); + expect(yield* automation.getContainer("team_ops")).toEqual({ + workspace: "acme", + container: null, + }); + expect( + (yield* automation.listStates({ workspace: "acme", containerId: "team_eng" })).map( + (option) => option.name, + ), + ).toEqual(["Todo", "In Progress", "Done"]); + const keys = [ + "ENG-1", + "eng-1", + "not a key", + ...Array.from({ length: 250 }, (_, i) => `ENG-${i + 2}`), + ]; + expect( + yield* automation.readStatuses({ workspace: "acme", containerId: "team_eng", keys }), + ).toEqual([{ key: "ENG-1", stateId: "st_done" }]); + // Numbers are deduplicated and read 250 at a time. + expect(numbers.map((batch) => batch.length)).toEqual([250, 1]); + }), + ); }); diff --git a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts index b6ad7f18eb6e2..c44ac0da48d7a 100644 --- a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts +++ b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts @@ -37,6 +37,7 @@ const DESCRIPTOR: StandaloneIssueTrackerDescriptor = { label: "Personal API key", helpUrl: "https://linear.app/settings/account/security", }, + automationContainer: "team", }; /** @@ -120,11 +121,32 @@ const CONTENT_BY_EMOJI = new Map( ), ); +const teamOption = (team: { + readonly id: string; + readonly key: string; + readonly name: string; +}) => ({ + id: team.id, + name: `${team.name} (${team.key})`, +}); + +/** Linear filters issues by number, at most this many per read. */ +const STATUS_READ_BATCH = 250; + /** `ENG-123`, or null for anything that is not a Linear identifier. */ function parseIdentifier(key: string): string | null { return /^[A-Za-z][A-Za-z0-9]*-[1-9]\d*$/.test(key.trim()) ? key.trim().toUpperCase() : null; } +/** `https://linear.app//issue/-[/]`, keeping the workspace. */ +function parseIssueUrl(url: URL) { + if (url.protocol !== "https:" || url.host.toLowerCase() !== DESCRIPTOR.host) return null; + const [, workspace, resource, key] = url.pathname.split("/"); + if (!workspace || resource !== "issue" || key === undefined) return null; + const scope = /^([A-Z][A-Z0-9_]*)-[1-9][0-9]*$/.exec(key)?.[1]; + return scope === undefined ? null : { host: DESCRIPTOR.host, workspace, scope, key }; +} + function toState(state: LinearApi.LinearWorkflowState): IssueState { return CLOSED_STATE_TYPES.includes(state.type) ? { category: "closed", name: state.name, closeReason: state.type } @@ -418,6 +440,7 @@ export const make: Effect.Effect linear.viewer(token).pipe( @@ -427,6 +450,65 @@ export const make: Effect.Effect + linear.viewer().pipe( + Effect.map((data) => ({ + workspace: data.workspace, + containers: data.teams + .map(teamOption) + .filter( + (team) => + query === undefined || + team.name.toLowerCase().includes(query.trim().toLowerCase()), + ), + nextCursor: null, + })), + ), + ), + getContainer: Effect.fn("LinearIssueTracker.getContainer")((containerId) => + linear.viewer().pipe( + Effect.map((data) => { + const team = data.teams.find((candidate) => candidate.id === containerId); + return { + workspace: data.workspace, + container: team === undefined ? null : teamOption(team), + }; + }), + ), + ), + listStates: Effect.fn("LinearIssueTracker.listStates")(({ containerId }) => + linear + .getTeamStates(containerId) + .pipe( + Effect.map((states) => inWorkflowOrder(states).map(({ id, name }) => ({ id, name }))), + ), + ), + readStatuses: Effect.fn("LinearIssueTracker.readStatuses")(({ containerId, keys }) => { + const numbers = [ + ...new Set( + keys.flatMap((key) => { + const identifier = parseIdentifier(key); + return identifier === null ? [] : [Number(identifier.split("-")[1])]; + }), + ), + ]; + const batches = Array.from( + { length: Math.ceil(numbers.length / STATUS_READ_BATCH) }, + (_, index) => numbers.slice(index * STATUS_READ_BATCH, (index + 1) * STATUS_READ_BATCH), + ); + return Effect.forEach(batches, (batch) => + linear.getIssueStates({ teamId: containerId, numbers: batch }), + ).pipe( + Effect.map((pages) => + pages.flat().map((issue) => ({ key: issue.identifier, stateId: issue.stateId })), + ), + ); + }), + }, + // The id, not the display name: it is what the involvement filters compare against. getViewer: () => linear.viewer().pipe(Effect.map((data) => toActor(data.viewer).login)), diff --git a/packages/source-control-core/src/server/IssueTracker.ts b/packages/source-control-core/src/server/IssueTracker.ts index 73148dedf2098..64fc4cacfe88a 100644 --- a/packages/source-control-core/src/server/IssueTracker.ts +++ b/packages/source-control-core/src/server/IssueTracker.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import type * as Effect from "effect/Effect"; import type { + IssueAutomationOption, IssueState, IssueCandidates, IssueCapabilities, @@ -27,6 +28,8 @@ import type { } from "@t3tools/contracts"; import { IssueTrackerKind as IssueTrackerKindSchema } from "@t3tools/contracts"; +import type { IssueLink } from "../shared/definition.ts"; + /** * The one failure shape every tracker reports, so the service can decide what a failure means * without knowing which CLI or API produced it. A missing or unauthenticated tool disables the @@ -202,6 +205,8 @@ export interface IssueTrackerCredential { */ export interface StandaloneIssueTrackerApi extends IssueTrackerApi { readonly standalone: StandaloneIssueTrackerDescriptor; + /** Keeps the workspace an issue URL names, which status rules match links by. */ + readonly parseIssueUrl?: (url: URL) => (IssueLink & { readonly workspace: string }) | null; /** * Who a credential signs in as and which scopes it reaches, asked of the tracker itself. Run on * a credential before it is stored, and on the stored one to report connection status. @@ -212,6 +217,48 @@ export interface StandaloneIssueTrackerApi extends IssueTrackerApi { { readonly account: string; readonly scopes: ReadonlyArray }, IssueTrackerError >; + /** + * What issue status rules read, present with `parseIssueUrl` when `standalone.automationContainer` + * is. A container is the team or board a rule watches; its id must be unique across the + * tracker's workspaces, or the tracker must refuse a workspace other than the credential's. + */ + readonly automation?: { + /** One page of the containers the credential reaches, whose names hold `query`. */ + readonly listContainers: (input: { + readonly query?: string | undefined; + readonly cursor?: string | undefined; + }) => Effect.Effect< + { + /** The credential's workspace, as `parseIssueUrl` names it. */ + readonly workspace: string; + readonly containers: ReadonlyArray; + readonly nextCursor: string | null; + }, + IssueTrackerError + >; + /** The container by id, or null when the credential cannot reach it. */ + readonly getContainer: (containerId: string) => Effect.Effect< + { + readonly workspace: string; + readonly container: IssueAutomationOption | null; + }, + IssueTrackerError + >; + /** Every status an issue in the container can be in, in workflow order. */ + readonly listStates: (input: { + readonly workspace: string; + readonly containerId: string; + }) => Effect.Effect, IssueTrackerError>; + /** The status id of each issue key found in the container; keys outside it are left out. */ + readonly readStatuses: (input: { + readonly workspace: string; + readonly containerId: string; + readonly keys: ReadonlyArray; + }) => Effect.Effect< + ReadonlyArray<{ readonly key: string; readonly stateId: string }>, + IssueTrackerError + >; + }; } export function isStandaloneIssueTracker(api: IssueTrackerApi): api is StandaloneIssueTrackerApi {