diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index b873eb09..20e7a01d 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -566,6 +566,8 @@ Use this method if OAuth is unavailable (e.g., your organization does not allow The integration label shows "API Token" and displays the connected site name and URL. +To rotate or replace your API token at any time — or after a token expires — without disconnecting: go to **Settings > Jira Cloud Integration > Auth method** and click **Replace**. Your stored Atlassian email is pre-filled (and can be edited if needed) while your connected site, custom fields, custom scopes, issue key detection setting, and custom issue order remain preserved. Paste the new API token and click **Replace token** — the new token is validated against Jira and encrypted before replacing the old one. + ### Issue Key Detection When issue key detection is enabled, the app scans GitHub issue and PR titles (and PR branch names) for Jira issue key patterns (e.g., `PROJ-123`, `TEAM-42`) after each full data refresh. Matched keys are looked up in Jira and displayed as inline badges on the GitHub item rows showing the issue key, status, and a color indicating status category (blue = new, yellow = in progress, green = done). @@ -590,7 +592,7 @@ When Jira is connected, a **Jira** tab appears in the tab bar. It shows all open **Polling:** Jira issues refresh after each full GitHub poll cycle. There is no hot poll for Jira — issues update every 5 minutes. -If your Jira token expires (OAuth refresh tokens expire after 90 days of inactivity), a notification prompts you to reconnect in Settings. +If your Jira OAuth session or API token expires, the **Jira Assigned** tab remains visible with an **Expired** warning badge while preserving your connected site, custom fields, custom scopes, issue key detection setting, and custom sort order. Both the warning toast and the notification drawer include a clickable **Open Jira settings** link (also shown inside the expired tab callout) that jumps directly to **Settings > Jira Cloud Integration** — and automatically opens the token replacement form for API token users. ### Configuring Custom Fields @@ -644,7 +646,7 @@ Local development uses `.dev.vars` (see `.dev.vars.example`). The Jira Cloud Int ### Troubleshooting Jira **"Reconnect in Settings" notification appears.** -Your OAuth refresh token has expired (90-day inactivity limit) or was revoked. Go to Settings and click **Connect with Jira** to re-authenticate. +Your OAuth refresh token has expired (90-day inactivity limit) or your API token expired or was revoked. Your Jira settings (connected site, custom fields, custom scopes, issue key detection, and custom sort order) remain preserved while the **Jira Assigned** tab displays an **Expired** badge. Click **Open Jira settings** in the toast notification, notification drawer, or expired tab callout to jump straight to **Settings > Jira Cloud Integration** — then click **Reconnect** (for OAuth) or use the inline **Replace** / **Replace token** form (for API tokens, which opens automatically) to re-authenticate. **OAuth button not visible in Settings.** `VITE_JIRA_CLIENT_ID` is not set or contains an invalid value. Check your `.env` file or deployment configuration. The API token method is always available regardless of this variable. diff --git a/src/app/components/dashboard/DashboardPage.tsx b/src/app/components/dashboard/DashboardPage.tsx index ef209c1e..f86006de 100644 --- a/src/app/components/dashboard/DashboardPage.tsx +++ b/src/app/components/dashboard/DashboardPage.tsx @@ -32,7 +32,7 @@ import { import { expireToken, user, onAuthCleared, DASHBOARD_STORAGE_KEY, DEP_META_STORAGE_KEY, jiraAuth, setJiraAuth, isJiraAuthenticated, clearJiraAuth } from "../../stores/auth"; import { JiraApiError } from "../../services/jira-client"; import { createJiraClient, mergeCustomFields, jiraJqlForScope } from "../../lib/jira-utils"; -import type { JiraIssue } from "../../../shared/jira-types"; +import { JIRA_SETTINGS_ACTION, type JiraIssue } from "../../../shared/jira-types"; import { detectAndLookupJiraKeys } from "../../services/jira-keys"; import JiraAssignedTab from "./JiraAssignedTab"; import { updateRelaySnapshot } from "../../lib/mcp-relay"; @@ -538,7 +538,7 @@ export default function DashboardPage() { if (err instanceof JiraApiError) { if (err.status === 401) { clearJiraAuth(); - pushNotification("jira", "Jira session expired — please reconnect in Settings", "warning"); + pushNotification("jira", "Jira session expired — please reconnect in Settings", "warning", false, JIRA_SETTINGS_ACTION); } else if (err.status === 400 && !["assigned", "reported", "watching"].includes(scope)) { const scopeName = config.jira?.customScopes?.find((s) => s.id === scope)?.name ?? scope; pushNotification("jira", `Custom scope '${scopeName}' is not supported by your Jira instance. Remove it in Settings.`, "warning"); @@ -549,6 +549,7 @@ export default function DashboardPage() { pushNotification("jira", "Jira fetch failed — will retry on next refresh", "warning"); } } else { + if (err instanceof Error && err.message === "Jira auth cleared during token refresh") return; pushNotification("jira", "Jira: unexpected error — will retry on next refresh", "warning"); } } finally { @@ -1094,7 +1095,7 @@ export default function DashboardPage() { isRunVisible(w, { ignoredIds: ignoredRuns, showPrRuns: viewState.showPrRuns, globalFilter: builtinFilter }) ).length } : {}), ...(config.enableTracking ? { tracked: viewState.trackedItems.length } : {}), - ...(config.jira?.enabled ? (() => { + ...(config.jira?.enabled && isJiraAuthenticated() ? (() => { const f = viewState.tabFilters.jiraAssigned; return { jiraAssigned: jiraIssues().filter((issue) => { if (f?.statusCategory !== "all" && issue.fields.status.statusCategory.key !== f?.statusCategory) return false; @@ -1137,9 +1138,11 @@ export default function DashboardPage() { return `${issueTitles}|||${prTitles}`; }); - // Jira key detection runs only when titles change — NOT on every lastRefreshedAt tick. + const jiraAuthed = createMemo(() => isJiraAuthenticated()); + + // Jira key detection runs only when titles change (or Jira auth transitions false -> true) — NOT on every lastRefreshedAt tick. // Guards: jira enabled+detection, authenticated, client ready, and titles actually changed. - createEffect(on(titleFingerprint, () => { + createEffect(on([titleFingerprint, jiraAuthed], () => { if (import.meta.env.DEV) console.info("[jira] key detection guard:", { enabled: config.jira?.enabled, detection: config.jira?.issueKeyDetection, auth: isJiraAuthenticated(), client: !!jiraClient(), refreshed: !!dashboardData.lastRefreshedAt }); if (!config.jira?.enabled || !config.jira?.issueKeyDetection) return; if (!isJiraAuthenticated()) return; @@ -1156,6 +1159,17 @@ export default function DashboardPage() { }).catch(handleJiraError); })); + // Re-fetch Jira assigned issues when Jira auth transitions false -> true + createEffect(on( + jiraAuthed, + (authed) => { + if (authed && config.jira?.enabled) { + fetchJiraAssigned().catch(handleJiraError); + } + }, + { defer: true } + )); + // Jira assigned issues poll: fires after each GitHub full refresh cycle createEffect(on( () => _coordinator()?.lastRefreshAt(), @@ -1344,6 +1358,7 @@ export default function DashboardPage() { enableTracking={config.enableTracking} enableActions={config.enableActions} enableJira={!!config.jira?.enabled} + jiraExpired={Boolean(config.jira?.enabled && !isJiraAuthenticated())} enableDependencies={enableDependencies()} customTabs={config.customTabs.filter((t) => config.enableActions || t.baseType !== "actions").map((t) => ({ id: t.id, name: t.name, isUnscoped: isTabUnscoped(t) }))} onAddTab={() => setShowCustomTabModal(true)} @@ -1436,6 +1451,7 @@ export default function DashboardPage() { issues={jiraIssues()} loading={jiraLoading()} siteUrl={config.jira?.siteUrl ?? ""} + expired={!isJiraAuthenticated()} /> diff --git a/src/app/components/dashboard/JiraAssignedTab.tsx b/src/app/components/dashboard/JiraAssignedTab.tsx index 1537a09b..b3d74f9d 100644 --- a/src/app/components/dashboard/JiraAssignedTab.tsx +++ b/src/app/components/dashboard/JiraAssignedTab.tsx @@ -24,6 +24,7 @@ interface JiraAssignedTabProps { issues: JiraIssue[]; loading: boolean; siteUrl: string; + expired?: boolean; } const BUILTIN_SCOPE_OPTIONS = [ @@ -698,7 +699,7 @@ export default function JiraAssignedTab(props: JiraAssignedTabProps) { {/* Jira project groups + locked stubs, or flat custom-ordered list */} - 0 : pageGroups().length > 0}> + 0 : pageGroups().length > 0)}> + +
+
+ + Your Jira session or API token has expired. Your Jira settings and custom order are preserved. + + + Open Jira settings + +
+
+
+ {/* Empty state — shown when no actual items, whether or not locked stubs appear above */} - +
; onAddTab?: () => void; @@ -65,8 +66,17 @@ export default function TabBar(props: TabBarProps) { Jira Assigned - - {props.counts?.jiraAssigned} + + Expired + + } + > + + {props.counts?.jiraAssigned} + diff --git a/src/app/components/settings/SettingsPage.tsx b/src/app/components/settings/SettingsPage.tsx index b6a4bd2a..91e4f185 100644 --- a/src/app/components/settings/SettingsPage.tsx +++ b/src/app/components/settings/SettingsPage.tsx @@ -1,4 +1,4 @@ -import { createSignal, createMemo, Show, For, onCleanup, onMount } from "solid-js"; +import { createSignal, createMemo, createEffect, Show, For, onCleanup, onMount } from "solid-js"; import { Select } from "@kobalte/core/select"; import { Dialog } from "@kobalte/core/dialog"; import * as Sentry from "@sentry/solid"; @@ -13,11 +13,11 @@ import { } from "../../lib/settings-transfer"; import { createCredentialImport } from "../../lib/use-credential-import"; import { viewState, updateViewState, setTabFilter, applyImportedViewState } from "../../stores/view"; -import { clearAuth, jiraAuth, setJiraAuth, clearJiraConfigFull, isJiraAuthenticated, token, setAuthFromPat } from "../../stores/auth"; +import { clearAuth, jiraAuth, setJiraAuth, clearJiraAuth, clearJiraConfigFull, isJiraAuthenticated, token, setAuthFromPat } from "../../stores/auth"; import type { GitHubUser } from "../../stores/auth"; import { isValidPatFormat } from "../../lib/pat"; import { clearCache } from "../../stores/cache"; -import { pushNotification } from "../../lib/errors"; +import { pushNotification, dismissNotificationBySource } from "../../lib/errors"; import { buildOrgAccessUrl, buildJiraAuthorizeUrl } from "../../lib/oauth"; import { sealApiToken } from "../../lib/proxy"; import { isSafeGitHubUrl, openGitHubUrl } from "../../lib/url"; @@ -37,11 +37,16 @@ import CustomTabsSection from "./CustomTabsSection"; import DependencyExclusionModal from "./DependencyExclusionModal"; import { InfoTooltip } from "../shared/Tooltip"; import { createJiraClient } from "../../lib/jira-utils"; +import { clearJiraKeyCache } from "../../services/jira-keys"; +import { JIRA_SETTINGS_ACTION } from "../../../shared/jira-types"; +import type { IJiraClient } from "../../services/jira-client"; import JiraFieldPicker from "./JiraFieldPicker"; import JiraScopePicker from "./JiraScopePicker"; import type { RepoRef } from "../../services/api"; const VALID_JIRA_CLIENT_ID_RE = /^[A-Za-z0-9_-]+$/; +const VALID_JIRA_SITE_URL_RE = /^https:\/\/[a-z0-9-]+\.atlassian\.net$/i; +const VALID_JIRA_CLOUD_ID_RE = /^[a-zA-Z0-9-]+$/; interface NumberSelectOption { value: number; @@ -393,6 +398,13 @@ export default function SettingsPage() { function handleConfirmImport() { const pending = pendingImport(); if (!pending) return; + if ( + !pending.config.jira?.enabled || + !pending.config.jira.cloudId || + jiraAuth()?.cloudId !== pending.config.jira.cloudId + ) { + clearJiraAuth(); + } // Wholesale replace — parseImportFile returns a fully-parsed Config (every // top-level key present), so setConfig is safe (NOT updateConfig's partial merge). setConfig(pending.config); @@ -526,7 +538,88 @@ export default function SettingsPage() { const [showScopePicker, setShowScopePicker] = createSignal(false); const [showDependencyExclusionModal, setShowDependencyExclusionModal] = createSignal(false); - const jiraClient = createMemo(() => createJiraClient(config.jira?.authMethod)); + // Replace Jira API token panel + const [showReplaceJiraToken, setShowReplaceJiraToken] = createSignal(false); + const [replaceJiraEmail, setReplaceJiraEmail] = createSignal(""); + const [replaceJiraTokenInput, setReplaceJiraTokenInput] = createSignal(""); + const [replaceJiraError, setReplaceJiraError] = createSignal(null); + const [replaceJiraSubmitting, setReplaceJiraSubmitting] = createSignal(false); + let replaceJiraTokenInputRef: HTMLInputElement | undefined; + let replaceJiraButtonRef: HTMLButtonElement | undefined; + let replaceJiraAbortCtrl: AbortController | undefined; + + function openReplaceJiraTokenPanel(focusInput = true) { + setReplaceJiraEmail(jiraAuth()?.email ?? config.jira?.email ?? ""); + setReplaceJiraTokenInput(""); + setReplaceJiraError(null); + setShowReplaceJiraToken(true); + if (focusInput) { + setTimeout(() => replaceJiraTokenInputRef?.focus(), 0); + } + } + + function closeReplaceJiraTokenPanel(restoreFocus = false) { + replaceJiraAbortCtrl?.abort(); + setShowReplaceJiraToken(false); + setReplaceJiraTokenInput(""); + setReplaceJiraError(null); + if (restoreFocus) replaceJiraButtonRef?.focus(); + } + + function handleJiraDeepLink() { + if (typeof window === "undefined" || window.location.hash !== "#jira") return; + const shouldOpenReplace = + config.jira?.authMethod === "token" && (isJiraAuthenticated() || Boolean(config.jira?.enabled)); + if (shouldOpenReplace) { + openReplaceJiraTokenPanel(false); + } + setTimeout(() => { + document.getElementById("jira")?.scrollIntoView?.({ behavior: "smooth", block: "start" }); + if (shouldOpenReplace) { + replaceJiraTokenInputRef?.focus({ preventScroll: true }); + } + }, 0); + } + + onMount(() => { + handleJiraDeepLink(); + window.addEventListener("hashchange", handleJiraDeepLink); + }); + + onCleanup(() => { + replaceJiraAbortCtrl?.abort(); + if (typeof window !== "undefined") { + window.removeEventListener("hashchange", handleJiraDeepLink); + } + }); + + createEffect(() => { + if (!isJiraAuthenticated()) { + setShowFieldPicker(false); + setShowScopePicker(false); + } + }); + + const jiraClient = createMemo(() => { + const base = createJiraClient(config.jira?.authMethod); + if (!base) return null; + return { + getIssue: (key, fields) => base.getIssue(key, fields), + searchJql: (jql, opts) => base.searchJql(jql, opts), + bulkFetch: (keys, fields) => base.bulkFetch(keys, fields), + getFields: async () => { + try { + return await base.getFields(); + } catch (err) { + if ((err as { status?: number })?.status === 401) { + clearJiraAuth(); + pushNotification("jira", "Jira session expired — please reconnect in Settings", "warning", false, JIRA_SETTINGS_ACTION); + } + throw err; + } + }, + }; + }); const jiraApiSiteUrl = () => { const sub = jiraApiSubdomain().trim(); @@ -613,7 +706,107 @@ export default function SettingsPage() { } } + async function handleReplaceJiraToken() { + if (replaceJiraSubmitting()) return; + const email = replaceJiraEmail().trim(); + const newToken = replaceJiraTokenInput().trim(); + if (!email || !newToken) { + setReplaceJiraError("Email and API token are both required."); + return; + } + const siteUrl = (jiraAuth()?.siteUrl ?? config.jira?.siteUrl ?? "").replace(/\/+$/, ""); + if (!VALID_JIRA_SITE_URL_RE.test(siteUrl)) { + setReplaceJiraError("Stored Jira site URL is missing or invalid — please disconnect and reconnect."); + return; + } + let cloudId = jiraAuth()?.cloudId ?? config.jira?.cloudId ?? ""; + replaceJiraAbortCtrl = new AbortController(); + setReplaceJiraSubmitting(true); + setReplaceJiraError(null); + try { + if (!cloudId || !VALID_JIRA_CLOUD_ID_RE.test(cloudId)) { + const tenantResp = await fetch("/api/jira/tenant-info", { + method: "POST", + headers: { "Content-Type": "application/json", "X-Requested-With": "fetch" }, + body: JSON.stringify({ siteUrl }), + signal: replaceJiraAbortCtrl.signal, + }); + if (!showReplaceJiraToken()) return; + if (!tenantResp.ok) { + setReplaceJiraError("Could not look up your Jira site — try again later."); + return; + } + const tenantData = (await tenantResp.json()) as { cloudId?: string }; + cloudId = tenantData.cloudId ?? ""; + if (!cloudId || !VALID_JIRA_CLOUD_ID_RE.test(cloudId)) { + setReplaceJiraError("Could not look up your Jira site — try again later."); + return; + } + } + + const sealedToken = await sealApiToken(newToken, "jira-api-token"); + if (!showReplaceJiraToken()) return; + + const resp = await fetch("/api/jira/proxy", { + method: "POST", + headers: { "Content-Type": "application/json", "X-Requested-With": "fetch" }, + signal: replaceJiraAbortCtrl.signal, + body: JSON.stringify({ + endpoint: "search", + cloudId, + email, + sealed: sealedToken, + params: { jql: "assignee = currentUser() AND statusCategory != Done", maxResults: 1 }, + }), + }); + if (!showReplaceJiraToken()) return; + if (!resp.ok) { + setReplaceJiraError( + resp.status === 401 || resp.status === 403 + ? "API token or email is invalid — check your credentials and try again." + : `Jira returned ${resp.status} — try again later.` + ); + return; + } + + let siteName = jiraAuth()?.siteName ?? config.jira?.siteName ?? ""; + if (!siteName) { + try { + siteName = new URL(siteUrl).hostname.split(".")[0]; + } catch { + siteName = cloudId; + } + } + + clearJiraKeyCache(); + setJiraAuth({ + accessToken: sealedToken, + sealedRefreshToken: "", + expiresAt: Number.MAX_SAFE_INTEGER, + cloudId, + siteUrl, + siteName, + email, + }); + updateJiraConfig({ enabled: true, cloudId, email, authMethod: "token", siteUrl, siteName }); + dismissNotificationBySource("jira"); + dismissNotificationBySource("jira:refresh"); + dismissNotificationBySource("settings-import-jira"); + closeReplaceJiraTokenPanel(true); + pushNotification("jira-replace", "Jira API token replaced successfully", "info"); + } catch (err) { + if (err instanceof DOMException && err.name === "AbortError") return; + Sentry.captureException(err, { tags: { source: "jira-token-replace" } }); + setReplaceJiraError("Connection failed — please try again."); + } finally { + setReplaceJiraSubmitting(false); + } + } + function handleJiraDisconnect() { + closeReplaceJiraTokenPanel(false); + setShowFieldPicker(false); + setShowScopePicker(false); clearJiraConfigFull(); // DefaultTab guard: reset to issues if pointing at Jira tab if (config.defaultTab === "jiraAssigned") { @@ -1274,7 +1467,7 @@ export default function SettingsPage() { {/* Section 11: Jira Cloud Integration */}
} > + + + - {jiraAuth()?.siteName ?? ""} + {jiraAuth()?.siteName ?? config.jira?.siteName ?? ""} - {config.jira?.authMethod === "token" ? "API Token" : "OAuth"} +
+ {config.jira?.authMethod === "token" ? "API Token" : "OAuth"} + + + +
+ +
+

+ Generate a new token at{" "} + + Atlassian API tokens + {" "} + (use Create API token, not "with scopes"). +

+
{ e.preventDefault(); void handleReplaceJiraToken(); }}> +
+ setReplaceJiraEmail(e.currentTarget.value)} + /> + setReplaceJiraTokenInput(e.currentTarget.value)} + /> + + + +
+ + +
+
+
+
+
{ setShowFieldPicker((v) => !v); setTimeout(() => { (document.querySelector("[data-picker-search]") as HTMLElement | null)?.focus(); }, 0); @@ -1450,6 +1742,7 @@ export default function SettingsPage() {