Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: share integration instance management and preserve Jira tokens (#8213)

[._.]/ Adam Eivy40ea58b7612f
diff --git a/client/src/components/integrations/IntegrationInstancesPage.jsx b/client/src/components/integrations/IntegrationInstancesPage.jsx
new file mode 100644
index 0000000000..a4c1e705af
--- /dev/null
+++ b/client/src/components/integrations/IntegrationInstancesPage.jsx
@@ -0,0 +1,212 @@
+import { useEffect, useState } from 'react';
+import toast from '../ui/Toast';
+import { FormField } from '../ui/FormField';
+import PageSkeleton from '../ui/PageSkeleton';
+import Modal from '../ui/Modal';
+import api from '../../services/api';
+import { invalidateInstanceFeatures } from '../../hooks/useInstanceFeatures.js';
+
+const inputClass = 'w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white';
+
+export default function IntegrationInstancesPage({
+ title, heading, apiBase, feature, fields, initialForm, summarize, testSuccessDetail,
+ helpSteps, headerActions, emptyDescription, deleteDescription, skeletonWidth
+}) {
+ const [instances, setInstances] = useState({});
+ const [loading, setLoading] = useState(true);
+ const [editingInstance, setEditingInstance] = useState(null);
+ const [testingInstance, setTestingInstance] = useState(null);
+ const [testResults, setTestResults] = useState({});
+ const [saveError, setSaveError] = useState(null);
+ const [saving, setSaving] = useState(false);
+ const [deleteConfirm, setDeleteConfirm] = useState(null);
+ const [formData, setFormData] = useState(initialForm);
+ const [customFields, setCustomFields] = useState({});
+
+ useEffect(() => {
+ api.get(`${apiBase}/instances`, { silent: true })
+ .then(response => setInstances(response.instances || {}))
+ .catch(error => {
+ console.error(`❌ Failed to load ${title} instances: ${error.message}`);
+ toast.error(`Failed to load ${title} instances: ${error.message}`);
+ })
+ .finally(() => setLoading(false));
+ }, [apiBase, title]);
+
+ const resetForm = () => {
+ setEditingInstance(null);
+ setFormData(initialForm);
+ setCustomFields({});
+ setSaveError(null);
+ };
+
+ const handleCreate = () => {
+ setFormData(initialForm);
+ setCustomFields({});
+ setSaveError(null);
+ setEditingInstance('new');
+ };
+
+ const handleEdit = instance => {
+ setFormData({ ...initialForm, ...Object.fromEntries(Object.keys(initialForm)
+ .filter(key => !fields.some(field => field.name === key && field.secret))
+ .map(key => [key, instance[key] ?? initialForm[key]])) });
+ setCustomFields(Object.fromEntries(fields.filter(field => field.options).map(field => [
+ field.name, !field.options.some(option => option.value !== 'custom' && option.value === instance[field.name])
+ ])));
+ setSaveError(null);
+ setEditingInstance(instance.id);
+ };
+
+ const handleInputChange = event => {
+ const { name, value } = event.target;
+ setFormData(previous => ({ ...previous, [name]: value }));
+ setSaveError(null);
+ };
+
+ const handleSave = async () => {
+ setSaving(true);
+ setSaveError(null);
+ const payload = {
+ ...formData,
+ id: formData.id || formData.name.toLowerCase().replace(/\s+/g, '-'),
+ ...Object.fromEntries(fields.filter(field => field.secret && !formData[field.name]).map(field => [field.name, undefined]))
+ };
+ try {
+ const saved = await api.post(`${apiBase}/instances`, payload, { silent: true });
+ invalidateInstanceFeatures(feature);
+ toast.success(`${title} instance "${payload.name}" saved successfully`);
+ setInstances(previous => ({ ...previous, [saved.id]: saved }));
+ resetForm();
+ } catch (error) {
+ console.error(`❌ Failed to save ${title} instance: ${error.message}`);
+ setSaveError(error.message);
+ toast.error(`Failed to save: ${error.message}`);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleDelete = async () => {
+ const instanceId = deleteConfirm;
+ setDeleteConfirm(null);
+ try {
+ await api.delete(`${apiBase}/instances/${instanceId}`, { silent: true });
+ invalidateInstanceFeatures(feature);
+ toast.success(`${title} instance "${instanceId}" deleted`);
+ setInstances(previous => {
+ const next = { ...previous };
+ delete next[instanceId];
+ return next;
+ });
+ setTestResults(previous => {
+ const next = { ...previous };
+ delete next[instanceId];
+ return next;
+ });
+ } catch (error) {
+ console.error(`❌ Failed to delete ${title} instance: ${error.message}`);
+ toast.error(`Failed to delete: ${error.message}`);
+ }
+ };
+
+ const handleTest = async instanceId => {
+ setTestingInstance(instanceId);
+ setTestResults(previous => ({ ...previous, [instanceId]: null }));
+ try {
+ const result = await api.post(`${apiBase}/instances/${instanceId}/test`, undefined, { silent: true });
+ setTestResults(previous => ({ ...previous, [instanceId]: result }));
+ if (result.success) toast.success('Connection successful!');
+ } catch (error) {
+ setTestResults(previous => ({ ...previous, [instanceId]: { success: false, error: error.message } }));
+ toast.error(`Connection failed: ${error.message}`);
+ } finally {
+ setTestingInstance(null);
+ }
+ };
+
+ if (loading) return <PageSkeleton label={`Loading ${title}`} padded titleWidthClass={skeletonWidth} cards={2} />;
+
+ return (
+ <div className="@container/page min-w-0 p-4 sm:p-6">
+ <div className="flex flex-wrap justify-between items-center gap-4 mb-6">
+ {heading}
+ <div className="flex flex-wrap items-center gap-2">
+ {headerActions}
+ {!editingInstance && <button onClick={handleCreate} className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded">+ Add {title} Instance</button>}
+ </div>
+ </div>
+
+ <Modal open={!!deleteConfirm} onClose={() => setDeleteConfirm(null)} size="sm" backdropClassName="bg-black/50" ariaLabelledBy={`${feature}-delete-title`}>
+ <div className="bg-gray-800 rounded-lg p-4 sm:p-6">
+ <h3 id={`${feature}-delete-title`} className="text-lg sm:text-xl font-bold text-white mb-4">Delete {title} Instance?</h3>
+ <p className="text-gray-300 mb-6 text-sm sm:text-base break-words">Are you sure you want to delete &quot;{deleteConfirm}&quot;? {deleteDescription}</p>
+ <div className="flex flex-col-reverse sm:flex-row gap-2 sm:justify-end">
+ <button onClick={() => setDeleteConfirm(null)} className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded">Cancel</button>
+ <button onClick={handleDelete} className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-port-error hover:bg-port-error/80 text-white rounded">Delete</button>
+ </div>
+ </div>
+ </Modal>
+
+ <div className="grid grid-cols-1 @5xl/page:grid-cols-[minmax(0,1fr)_360px] gap-6 items-start">
+ {editingInstance && <div className="bg-gray-800 rounded-lg p-4 sm:p-6 min-w-0">
+ <h2 className="text-lg sm:text-xl font-bold text-white mb-4">{editingInstance === 'new' ? 'Add' : 'Edit'} {title} Instance</h2>
+ {saveError && <div role="alert" className="mb-4 p-3 bg-port-error/20 border border-port-error/40 rounded">
+ <p className="text-port-error font-medium">Error saving {title} instance</p>
+ <p className="text-port-error/80 text-sm mt-1">{saveError}</p>
+ </div>}
+ <div className="space-y-4">
+ <FormField label="Instance ID" labelClassName="block text-sm font-medium text-gray-300 mb-1">
+ <input type="text" name="id" value={formData.id} onChange={handleInputChange} disabled={editingInstance !== 'new'} className={`${inputClass} disabled:opacity-50`} placeholder={`e.g., company-${feature}`} />
+ <p className="text-xs text-gray-400 mt-1">Unique identifier (cannot be changed after creation)</p>
+ </FormField>
+ <FormField label="Display Name" labelClassName="block text-sm font-medium text-gray-300 mb-1">
+ <input type="text" name="name" value={formData.name} onChange={handleInputChange} className={inputClass} placeholder={`e.g., Company ${title}`} />
+ </FormField>
+ {fields.map(field => <FormField key={field.name} label={field.label} labelClassName="block text-sm font-medium text-gray-300 mb-1">
+ {field.options ? <select value={customFields[field.name] ? 'custom' : formData[field.name]} onChange={event => {
+ const isCustom = event.target.value === 'custom';
+ setCustomFields(previous => ({ ...previous, [field.name]: isCustom }));
+ setFormData(previous => ({ ...previous, [field.name]: isCustom ? '' : event.target.value }));
+ }} className={`${inputClass} mb-2`}>
+ {field.options.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
+ </select> : <input type={field.type || 'text'} name={field.name} value={formData[field.name]} onChange={handleInputChange} className={inputClass} placeholder={field.secret && editingInstance !== 'new' ? 'Leave blank to keep existing key' : field.placeholder} />}
+ {field.options && customFields[field.name] && <input type="text" name={field.name} value={formData[field.name]} onChange={handleInputChange} aria-label={`Custom ${field.label.toLowerCase()}`} className={inputClass} placeholder={field.customPlaceholder} />}
+ {field.help && <p className="text-xs text-gray-400 mt-1">{field.help}</p>}
+ </FormField>)}
+ <div className="flex flex-col sm:flex-row gap-2">
+ <button onClick={handleSave} disabled={saving || !formData.name || fields.some(field => !field.secret && !formData[field.name] || field.secret && editingInstance === 'new' && !formData[field.name])} className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded disabled:opacity-50 disabled:cursor-not-allowed">{saving ? 'Saving...' : 'Save'}</button>
+ <button onClick={resetForm} disabled={saving} className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded disabled:opacity-50">Cancel</button>
+ </div>
+ </div>
+ </div>}
+
+ <div className="space-y-4 @5xl/page:col-start-2 @5xl/page:row-start-1">
+ {Object.values(instances).length === 0 ? <div className="bg-gray-800 rounded-lg p-8 text-center">
+ <p className="text-gray-400">No {title} instances configured.</p>
+ <p className="text-gray-500 text-sm mt-2">{emptyDescription}</p>
+ </div> : Object.values(instances).map(instance => {
+ const result = testResults[instance.id];
+ return <div key={instance.id} className="bg-gray-800 rounded-lg p-4 sm:p-6">
+ <div className="flex flex-col gap-4">
+ <div className="flex-1 min-w-0"><h3 className="text-lg font-bold text-white truncate">{instance.name}</h3>{summarize(instance)}</div>
+ <div className="flex flex-wrap gap-2">
+ <button onClick={() => handleTest(instance.id)} disabled={testingInstance === instance.id} className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded disabled:opacity-50">{testingInstance === instance.id ? 'Testing...' : 'Test'}</button>
+ <button onClick={() => handleEdit(instance)} className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-port-warning hover:bg-port-warning/80 text-white text-sm rounded">Edit</button>
+ <button onClick={() => setDeleteConfirm(instance.id)} className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-port-error hover:bg-port-error/80 text-white text-sm rounded">Delete</button>
+ </div>
+ </div>
+ {result && result.success !== undefined && <div className={`mt-4 p-3 rounded ${result.success ? 'bg-port-success/20 border border-port-success/40' : 'bg-port-error/20 border border-port-error/40'}`}>
+ {result.success ? testSuccessDetail(result) : <><p className="text-port-error font-medium">{title === 'JIRA' ? '✗ ' : ''}Connection failed</p><p className="text-port-error/80 text-sm mt-1">{result.error}</p></>}
+ </div>}
+ </div>;
+ })}
+ </div>
+ <div className="bg-gray-800 rounded-lg p-4 sm:p-6 min-w-0">
+ <h2 className="text-base sm:text-lg font-bold text-white mb-3 sm:mb-4">Usage</h2>
+ <div className="space-y-2 text-xs sm:text-sm text-gray-300">{helpSteps}</div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/DataDog.jsx b/client/src/pages/DataDog.jsx
index 76cea12799..e0ac09e032 100644
--- a/client/src/pages/DataDog.jsx
+++ b/client/src/pages/DataDog.jsx
@@ -1,10 +1,4 @@
-import { useState, useEffect } from 'react';
-import toast from '../components/ui/Toast';
-import { FormField } from '../components/ui/FormField';
-import PageSkeleton from '../components/ui/PageSkeleton';
-import Modal from '../components/ui/Modal';
-import api from '../services/api';
-import { invalidateInstanceFeatures } from '../hooks/useInstanceFeatures.js';
+import IntegrationInstancesPage from '../components/integrations/IntegrationInstancesPage';
const SITE_OPTIONS = [
{ value: 'api.datadoghq.com', label: 'US1 (api.datadoghq.com)' },
@@ -15,424 +9,34 @@ const SITE_OPTIONS = [
{ value: 'custom', label: 'Custom...' }
];
-export default function DataDog() {
- const [instances, setInstances] = useState({});
- const [loading, setLoading] = useState(true);
- const [editingInstance, setEditingInstance] = useState(null);
- const [testingInstance, setTestingInstance] = useState(null);
- const [testResults, setTestResults] = useState({});
- const [saveError, setSaveError] = useState(null);
- const [saving, setSaving] = useState(false);
- const [deleteConfirm, setDeleteConfirm] = useState(null);
- const [customSite, setCustomSite] = useState(false);
-
- const [formData, setFormData] = useState({
- id: '',
- name: '',
- site: 'api.datadoghq.com',
- apiKey: '',
- appKey: ''
- });
-
- useEffect(() => {
- loadInstances();
- }, []);
-
- const loadInstances = async () => {
- try {
- setLoading(true);
- const response = await api.get('/datadog/instances', { silent: true });
- setInstances(response.instances || {});
- } catch (error) {
- console.error(`❌ Failed to load DataDog instances: ${error.message}`);
- toast.error(`Failed to load DataDog instances: ${error.message}`);
- } finally {
- setLoading(false);
- }
- };
-
- const handleEdit = (instance) => {
- setEditingInstance(instance.id);
- const isCustom = !SITE_OPTIONS.some(o => o.value !== 'custom' && o.value === instance.site);
- setCustomSite(isCustom);
- setFormData({
- id: instance.id,
- name: instance.name,
- site: instance.site,
- apiKey: '',
- appKey: ''
- });
- setSaveError(null);
- };
-
- const handleCreate = () => {
- setEditingInstance('new');
- setCustomSite(false);
- setFormData({
- id: '',
- name: '',
- site: 'api.datadoghq.com',
- apiKey: '',
- appKey: ''
- });
- setSaveError(null);
- };
-
- const handleCancel = () => {
- setEditingInstance(null);
- setCustomSite(false);
- setFormData({
- id: '',
- name: '',
- site: 'api.datadoghq.com',
- apiKey: '',
- appKey: ''
- });
- setSaveError(null);
- };
-
- const handleSave = async () => {
- try {
- setSaving(true);
- setSaveError(null);
-
- const payload = {
- id: formData.id || formData.name.toLowerCase().replace(/\s+/g, '-'),
- name: formData.name,
- site: formData.site,
- ...(formData.apiKey && { apiKey: formData.apiKey }),
- ...(formData.appKey && { appKey: formData.appKey })
- };
-
- const saved = await api.post('/datadog/instances', payload, { silent: true });
-
- // The DataDog nav entries are auto-gated on whether any instance is
- // configured, so saving the FIRST one is what reveals them — without this
- // they stay hidden until a full reload.
- invalidateInstanceFeatures('datadog');
- toast.success(`DataDog instance "${payload.name}" saved successfully`);
- setInstances(prev => ({ ...prev, [saved.id]: saved }));
- handleCancel();
- } catch (error) {
- console.error(`❌ Failed to save DataDog instance: ${error.message}`);
- setSaveError(error.message);
- toast.error(`Failed to save: ${error.message}`);
- } finally {
- setSaving(false);
- }
- };
-
- const handleDeleteClick = (instanceId) => {
- setDeleteConfirm(instanceId);
- };
-
- const handleDeleteConfirm = async () => {
- const instanceId = deleteConfirm;
- setDeleteConfirm(null);
-
- try {
- await api.delete(`/datadog/instances/${instanceId}`, { silent: true });
- // Removing the LAST instance re-hides the nav entries (see the save path).
- invalidateInstanceFeatures('datadog');
- toast.success(`DataDog instance "${instanceId}" deleted`);
- setInstances(prev => {
- const next = { ...prev };
- delete next[instanceId];
- return next;
- });
- } catch (error) {
- console.error(`❌ Failed to delete DataDog instance: ${error.message}`);
- toast.error(`Failed to delete: ${error.message}`);
- }
- };
-
- const handleDeleteCancel = () => {
- setDeleteConfirm(null);
- };
-
- const handleTest = async (instanceId) => {
- try {
- setTestingInstance(instanceId);
- setTestResults(prev => ({ ...prev, [instanceId]: null }));
-
- const response = await api.post(`/datadog/instances/${instanceId}/test`, undefined, { silent: true });
- setTestResults(prev => ({ ...prev, [instanceId]: response }));
-
- if (response.success) {
- toast.success('Connection successful!');
- }
- } catch (error) {
- setTestResults(prev => ({ ...prev, [instanceId]: { success: false, error: error.message } }));
- toast.error(`Connection failed: ${error.message}`);
- } finally {
- setTestingInstance(null);
- }
- };
-
- const handleInputChange = (e) => {
- setFormData({
- ...formData,
- [e.target.name]: e.target.value
- });
- if (saveError) {
- setSaveError(null);
- }
- };
-
- const handleSiteChange = (e) => {
- const value = e.target.value;
- if (value === 'custom') {
- setCustomSite(true);
- setFormData({ ...formData, site: '' });
- } else {
- setCustomSite(false);
- setFormData({ ...formData, site: value });
- }
- };
-
- if (loading) {
- return <PageSkeleton label="Loading DataDog" padded titleWidthClass="w-56" cards={2} />;
- }
-
- return (
- <div className="@container/page min-w-0 p-4 sm:p-6">
- <div className="flex flex-wrap justify-between items-center gap-4 mb-6">
- <h1 className="text-xl sm:text-2xl font-bold text-white">DataDog Integration</h1>
- {!editingInstance && (
- <button
- onClick={handleCreate}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded"
- >
- + Add DataDog Instance
- </button>
- )}
- </div>
-
- {/* Delete Confirmation Modal */}
- <Modal
- open={!!deleteConfirm}
- onClose={handleDeleteCancel}
- size="sm"
- backdropClassName="bg-black/50"
- ariaLabelledBy="datadog-delete-title"
- >
- <div className="bg-gray-800 rounded-lg p-4 sm:p-6">
- <h3 id="datadog-delete-title" className="text-lg sm:text-xl font-bold text-white mb-4">Delete DataDog Instance?</h3>
- <p className="text-gray-300 mb-6 text-sm sm:text-base break-words">
- Are you sure you want to delete &quot;{deleteConfirm}&quot;? This will remove the stored keys.
- </p>
- <div className="flex flex-col-reverse sm:flex-row gap-2 sm:justify-end">
- <button
- onClick={handleDeleteCancel}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded"
- >
- Cancel
- </button>
- <button
- onClick={handleDeleteConfirm}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-port-error hover:bg-port-error/80 text-white rounded"
- >
- Delete
- </button>
- </div>
- </div>
- </Modal>
-
- <div className="grid grid-cols-1 @5xl/page:grid-cols-[minmax(0,1fr)_360px] gap-6 items-start">
- {editingInstance ? (
- <div className="bg-gray-800 rounded-lg p-4 sm:p-6 min-w-0">
- <h2 className="text-lg sm:text-xl font-bold text-white mb-4">
- {editingInstance === 'new' ? 'Add' : 'Edit'} DataDog Instance
- </h2>
-
- {saveError && (
- <div role="alert" className="mb-4 p-3 bg-port-error/20 border border-port-error/40 rounded">
- <p className="text-port-error font-medium">Error saving DataDog instance</p>
- <p className="text-port-error/80 text-sm mt-1">{saveError}</p>
- </div>
- )}
-
- <div className="space-y-4">
- <FormField label="Instance ID" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <input
- type="text"
- name="id"
- value={formData.id}
- onChange={handleInputChange}
- disabled={editingInstance !== 'new'}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white disabled:opacity-50"
- placeholder="e.g., company-datadog"
- />
- <p className="text-xs text-gray-400 mt-1">
- Unique identifier (cannot be changed after creation)
- </p>
- </FormField>
-
- <FormField label="Display Name" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleInputChange}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
- placeholder="e.g., Company DataDog"
- />
- </FormField>
-
- <FormField label="Site" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <select
- value={customSite ? 'custom' : formData.site}
- onChange={handleSiteChange}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white mb-2"
- >
- {SITE_OPTIONS.map(opt => (
- <option key={opt.value} value={opt.value}>{opt.label}</option>
- ))}
- </select>
- {customSite && (
- <input
- type="text"
- name="site"
- value={formData.site}
- onChange={handleInputChange}
- aria-label="Custom site"
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
- placeholder="e.g., api.custom-datadog.com"
- />
- )}
- </FormField>
-
- <FormField label="API Key" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <input
- type="password"
- name="apiKey"
- value={formData.apiKey}
- onChange={handleInputChange}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
- placeholder={editingInstance === 'new' ? 'Enter your DataDog API Key' : 'Leave blank to keep existing key'}
- />
- <p className="text-xs text-gray-400 mt-1">
- Found in DataDog Organization Settings &rarr; API Keys
- </p>
- </FormField>
-
- <FormField label="Application Key" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <input
- type="password"
- name="appKey"
- value={formData.appKey}
- onChange={handleInputChange}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
- placeholder={editingInstance === 'new' ? 'Enter your DataDog Application Key' : 'Leave blank to keep existing key'}
- />
- <p className="text-xs text-gray-400 mt-1">
- Found in DataDog Organization Settings &rarr; Application Keys
- </p>
- </FormField>
-
- <div className="flex flex-col sm:flex-row gap-2">
- <button
- onClick={handleSave}
- disabled={saving || !formData.name || !formData.site || (editingInstance === 'new' && (!formData.apiKey || !formData.appKey))}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded disabled:opacity-50 disabled:cursor-not-allowed"
- >
- {saving ? 'Saving...' : 'Save'}
- </button>
- <button
- onClick={handleCancel}
- disabled={saving}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded disabled:opacity-50"
- >
- Cancel
- </button>
- </div>
- </div>
- </div>
- ) : null}
-
- <div className="space-y-4 @5xl/page:col-start-2 @5xl/page:row-start-1">
- {Object.values(instances).length === 0 ? (
- <div className="bg-gray-800 rounded-lg p-8 text-center">
- <p className="text-gray-400">No DataDog instances configured.</p>
- <p className="text-gray-500 text-sm mt-2">
- Add a DataDog instance to enable error monitoring for your apps.
- </p>
- </div>
- ) : (
- Object.values(instances).map((instance) => (
- <div key={instance.id} className="bg-gray-800 rounded-lg p-4 sm:p-6">
- <div className="flex flex-col gap-4">
- <div className="flex-1 min-w-0">
- <h3 className="text-lg font-bold text-white truncate">{instance.name}</h3>
- <p className="text-gray-400 text-sm mt-1 break-all">Site: {instance.site}</p>
- <p className="text-gray-500 text-sm">
- API Key: {instance.hasApiKey ? 'Configured' : 'Not set'}
- </p>
- <p className="text-gray-500 text-sm">
- App Key: {instance.hasAppKey ? 'Configured' : 'Not set'}
- </p>
- </div>
-
- <div className="flex flex-wrap gap-2">
- <button
- onClick={() => handleTest(instance.id)}
- disabled={testingInstance === instance.id}
- className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded disabled:opacity-50"
- >
- {testingInstance === instance.id ? 'Testing...' : 'Test'}
- </button>
- <button
- onClick={() => handleEdit(instance)}
- className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-port-warning hover:bg-port-warning/80 text-white text-sm rounded"
- >
- Edit
- </button>
- <button
- onClick={() => handleDeleteClick(instance.id)}
- className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-port-error hover:bg-port-error/80 text-white text-sm rounded"
- >
- Delete
- </button>
- </div>
- </div>
-
- {testResults[instance.id] && testResults[instance.id].success !== undefined && (
- <div
- className={`mt-4 p-3 rounded ${
- testResults[instance.id].success
- ? 'bg-port-success/20 border border-port-success/40'
- : 'bg-port-error/20 border border-port-error/40'
- }`}
- >
- {testResults[instance.id].success ? (
- <p className="text-port-success font-medium">API key validated</p>
- ) : (
- <>
- <p className="text-port-error font-medium">Connection failed</p>
- <p className="text-port-error/80 text-sm mt-1">{testResults[instance.id].error}</p>
- </>
- )}
- </div>
- )}
- </div>
- ))
- )}
- </div>
+const fields = [
+ { name: 'site', label: 'Site', options: SITE_OPTIONS, customPlaceholder: 'e.g., api.custom-datadog.com' },
+ { name: 'apiKey', label: 'API Key', type: 'password', secret: true, placeholder: 'Enter your DataDog API Key', help: <>Found in DataDog Organization Settings &rarr; API Keys</> },
+ { name: 'appKey', label: 'Application Key', type: 'password', secret: true, placeholder: 'Enter your DataDog Application Key', help: <>Found in DataDog Organization Settings &rarr; Application Keys</> }
+];
+const initialForm = { id: '', name: '', site: 'api.datadoghq.com', apiKey: '', appKey: '' };
- <div className="bg-gray-800 rounded-lg p-4 sm:p-6 min-w-0">
- <h2 className="text-base sm:text-lg font-bold text-white mb-3 sm:mb-4">Usage</h2>
- <div className="space-y-2 text-xs sm:text-sm text-gray-300">
- <p>1. Add one or more DataDog instances above</p>
- <p>2. Go to Apps and enable DataDog monitoring in each app&apos;s settings</p>
- <p>3. The error monitor job will periodically check for new errors:</p>
- <ul className="list-disc list-inside ml-2 sm:ml-4 space-y-1 text-gray-400">
- <li>Query DataDog for recent error events matching the app&apos;s service name</li>
- <li>Surface new errors in notifications and app insights</li>
- <li>Track error trends over time</li>
- </ul>
- </div>
- </div>
- </div>
- </div>
- );
+export default function DataDog() {
+ return <IntegrationInstancesPage
+ title="DataDog" apiBase="/datadog" feature="datadog" fields={fields} initialForm={initialForm}
+ heading={<h1 className="text-xl sm:text-2xl font-bold text-white">DataDog Integration</h1>}
+ skeletonWidth="w-56" emptyDescription="Add a DataDog instance to enable error monitoring for your apps."
+ deleteDescription="This will remove the stored keys."
+ summarize={instance => <>
+ <p className="text-gray-400 text-sm mt-1 break-all">Site: {instance.site}</p>
+ <p className="text-gray-500 text-sm">API Key: {instance.hasApiKey ? 'Configured' : 'Not set'}</p>
+ <p className="text-gray-500 text-sm">App Key: {instance.hasAppKey ? 'Configured' : 'Not set'}</p>
+ </>}
+ testSuccessDetail={() => <p className="text-port-success font-medium">API key validated</p>}
+ helpSteps={<>
+ <p>1. Add one or more DataDog instances above</p>
+ <p>2. Go to Apps and enable DataDog monitoring in each app&apos;s settings</p>
+ <p>3. The error monitor job will periodically check for new errors:</p>
+ <ul className="list-disc list-inside ml-2 sm:ml-4 space-y-1 text-gray-400">
+ <li>Query DataDog for recent error events matching the app&apos;s service name</li>
+ <li>Surface new errors in notifications and app insights</li>
+ <li>Track error trends over time</li>
+ </ul>
+ </>}
+ />;
}
diff --git a/client/src/pages/Jira.jsx b/client/src/pages/Jira.jsx
index 2569eb658a..9cbf27bd80 100644
--- a/client/src/pages/Jira.jsx
+++ b/client/src/pages/Jira.jsx
@@ -1,448 +1,50 @@
-import { useState, useEffect } from 'react';
import { Link } from 'react-router';
-import toast from '../components/ui/Toast';
-import PageSkeleton from '../components/ui/PageSkeleton';
-import { FormField } from '../components/ui/FormField';
-import Modal from '../components/ui/Modal';
-import api from '../services/api';
-import { invalidateInstanceFeatures } from '../hooks/useInstanceFeatures.js';
+import IntegrationInstancesPage from '../components/integrations/IntegrationInstancesPage';
-// PAT lifetimes aren't a fixed platform constant — Cloud API tokens typically don't
-// expire on a schedule at all, and Server/DC PAT expiration is chosen per-token by
-// whoever generated it. So there's no age threshold that reliably means "expired"
-// (a real instance was still authenticating fine 35+ days after its last save).
-// This is a soft, non-committal nudge — the Test button is the only real signal.
+// PAT lifetimes vary by Jira edition and token settings. Test is the reliable signal.
const TOKEN_STALE_WARN_DAYS = 60;
+const getTokenAgeDays = tokenUpdatedAt => tokenUpdatedAt
+ ? Math.floor((Date.now() - new Date(tokenUpdatedAt).getTime()) / 86400000)
+ : null;
-function getTokenAgeDays(tokenUpdatedAt) {
- if (!tokenUpdatedAt) return null;
- const updated = new Date(tokenUpdatedAt);
- return Math.floor((Date.now() - updated.getTime()) / 86400000);
-}
+const fields = [
+ { name: 'baseUrl', label: 'Base URL', type: 'url', placeholder: 'https://jira.example.com' },
+ { name: 'email', label: 'Email', type: 'email', placeholder: '[email protected]' },
+ { name: 'apiToken', label: 'API Token (Personal Access Token)', type: 'password', secret: true, placeholder: 'Enter your JIRA Personal Access Token', help: 'Generate this from your JIRA profile → Personal Access Tokens' }
+];
+const initialForm = { id: '', name: '', baseUrl: '', email: '', apiToken: '' };
export default function Jira() {
- const [instances, setInstances] = useState({});
- const [loading, setLoading] = useState(true);
- const [editingInstance, setEditingInstance] = useState(null);
- const [testingInstance, setTestingInstance] = useState(null);
- const [testResult, setTestResult] = useState(null);
- const [saveError, setSaveError] = useState(null);
- const [saving, setSaving] = useState(false);
- const [deleteConfirm, setDeleteConfirm] = useState(null);
-
- // Form state
- const [formData, setFormData] = useState({
- id: '',
- name: '',
- baseUrl: '',
- email: '',
- apiToken: ''
- });
-
- useEffect(() => {
- loadInstances();
- }, []);
-
- const loadInstances = async () => {
- try {
- setLoading(true);
- const response = await api.get('/jira/instances', { silent: true });
- setInstances(response.instances || {});
- } catch (error) {
- console.error(`❌ Failed to load JIRA instances: ${error.message}`);
- toast.error(`Failed to load JIRA instances: ${error.message}`);
- } finally {
- setLoading(false);
- }
- };
-
- const handleEdit = (instance) => {
- setEditingInstance(instance.id);
- setFormData({
- id: instance.id,
- name: instance.name,
- baseUrl: instance.baseUrl,
- email: instance.email,
- apiToken: '' // Don't pre-fill token for security
- });
- setTestResult(null);
- setSaveError(null);
- };
-
- const handleCreate = () => {
- setEditingInstance('new');
- setFormData({
- id: '',
- name: '',
- baseUrl: '',
- email: '',
- apiToken: ''
- });
- setTestResult(null);
- setSaveError(null);
- };
-
- const handleCancel = () => {
- setEditingInstance(null);
- setFormData({
- id: '',
- name: '',
- baseUrl: '',
- email: '',
- apiToken: ''
- });
- setTestResult(null);
- setSaveError(null);
- };
-
- const handleSave = async () => {
- try {
- setSaving(true);
- setSaveError(null);
-
- const payload = {
- id: formData.id || formData.name.toLowerCase().replace(/\s+/g, '-'),
- name: formData.name,
- baseUrl: formData.baseUrl,
- email: formData.email,
- apiToken: formData.apiToken
- };
-
- const saved = await api.post('/jira/instances', payload, { silent: true });
-
- // The JIRA nav entries are auto-gated on whether any instance is
- // configured, so saving the FIRST one is what reveals them — without this
- // they stay hidden until a full reload.
- invalidateInstanceFeatures('jira');
- toast.success(`JIRA instance "${payload.name}" saved successfully`);
- setInstances(prev => ({ ...prev, [saved.id]: saved }));
- handleCancel();
- } catch (error) {
- console.error(`❌ Failed to save JIRA instance: ${error.message}`);
- setSaveError(error.message);
- toast.error(`Failed to save: ${error.message}`);
- } finally {
- setSaving(false);
- }
- };
-
- const handleDeleteClick = (instanceId) => {
- setDeleteConfirm(instanceId);
- };
-
- const handleDeleteConfirm = async () => {
- const instanceId = deleteConfirm;
- setDeleteConfirm(null);
-
- try {
- await api.delete(`/jira/instances/${instanceId}`, { silent: true });
- // Removing the LAST instance re-hides the nav entries (see the save path).
- invalidateInstanceFeatures('jira');
- toast.success(`JIRA instance "${instanceId}" deleted`);
- setInstances(prev => {
- const next = { ...prev };
- delete next[instanceId];
- return next;
- });
- } catch (error) {
- console.error(`❌ Failed to delete JIRA instance: ${error.message}`);
- toast.error(`Failed to delete: ${error.message}`);
- }
- };
-
- const handleDeleteCancel = () => {
- setDeleteConfirm(null);
- };
-
- const handleTest = async (instanceId) => {
- try {
- setTestingInstance(instanceId);
- setTestResult(null);
-
- const response = await api.post(`/jira/instances/${instanceId}/test`, undefined, { silent: true });
- setTestResult(response);
-
- if (response.success) {
- toast.success('Connection successful!');
- }
- } catch (error) {
- setTestResult({
- success: false,
- error: error.message
- });
- toast.error(`Connection failed: ${error.message}`);
- } finally {
- setTestingInstance(null);
- }
- };
-
- const handleInputChange = (e) => {
- setFormData({
- ...formData,
- [e.target.name]: e.target.value
- });
- // Clear error when user starts typing
- if (saveError) {
- setSaveError(null);
- }
- };
-
- if (loading) {
- return <PageSkeleton label="Loading Jira" padded titleWidthClass="w-52" cards={2} />;
- }
-
- return (
- <div className="@container/page min-w-0 p-4 sm:p-6">
- <div className="flex flex-wrap justify-between items-center gap-4 mb-6">
- <h1 className="text-xl sm:text-2xl font-bold text-white">JIRA Integration</h1>
- <div className="flex flex-wrap items-center gap-2">
- <Link
- to="/devtools/jira/reports"
- className="px-4 py-2 border border-port-border hover:border-port-accent text-gray-300 hover:text-white rounded text-sm"
- >
- Status Reports
- </Link>
- {!editingInstance && (
- <button
- onClick={handleCreate}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded"
- >
- + Add JIRA Instance
- </button>
- )}
- </div>
- </div>
-
- {/* Delete Confirmation Modal */}
- <Modal
- open={!!deleteConfirm}
- onClose={handleDeleteCancel}
- size="sm"
- backdropClassName="bg-black/50"
- ariaLabelledBy="jira-delete-title"
- >
- <div className="bg-gray-800 rounded-lg p-4 sm:p-6">
- <h3 id="jira-delete-title" className="text-lg sm:text-xl font-bold text-white mb-4">Delete JIRA Instance?</h3>
- <p className="text-gray-300 mb-6 text-sm sm:text-base break-words">
- Are you sure you want to delete "{deleteConfirm}"? This will not affect existing tickets.
- </p>
- <div className="flex flex-col-reverse sm:flex-row gap-2 sm:justify-end">
- <button
- onClick={handleDeleteCancel}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded"
- >
- Cancel
- </button>
- <button
- onClick={handleDeleteConfirm}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-port-error hover:bg-port-error/80 text-white rounded"
- >
- Delete
- </button>
- </div>
- </div>
- </Modal>
-
- <div className="grid grid-cols-1 @5xl/page:grid-cols-[minmax(0,1fr)_360px] gap-6 items-start">
- {editingInstance ? (
- <div className="bg-gray-800 rounded-lg p-4 sm:p-6 min-w-0">
- <h2 className="text-lg sm:text-xl font-bold text-white mb-4">
- {editingInstance === 'new' ? 'Add' : 'Edit'} JIRA Instance
- </h2>
-
- {saveError && (
- <div role="alert" className="mb-4 p-3 bg-port-error/20 border border-port-error/40 rounded">
- <p className="text-port-error font-medium">Error saving JIRA instance</p>
- <p className="text-port-error/80 text-sm mt-1">{saveError}</p>
- </div>
- )}
-
- <div className="space-y-4">
- <FormField label="Instance ID" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <input
- type="text"
- name="id"
- value={formData.id}
- onChange={handleInputChange}
- disabled={editingInstance !== 'new'}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white disabled:opacity-50"
- placeholder="e.g., company-jira"
- />
- <p className="text-xs text-gray-400 mt-1">
- Unique identifier (cannot be changed after creation)
- </p>
- </FormField>
-
- <FormField label="Display Name" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleInputChange}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
- placeholder="e.g., Company JIRA"
- />
- </FormField>
-
- <FormField label="Base URL" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <input
- type="url"
- name="baseUrl"
- value={formData.baseUrl}
- onChange={handleInputChange}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
- placeholder="https://jira.example.com"
- />
- </FormField>
-
- <FormField label="Email" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <input
- type="email"
- name="email"
- value={formData.email}
- onChange={handleInputChange}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
- placeholder="[email protected]"
- />
- </FormField>
-
- <FormField label="API Token (Personal Access Token)" labelClassName="block text-sm font-medium text-gray-300 mb-1">
- <input
- type="password"
- name="apiToken"
- value={formData.apiToken}
- onChange={handleInputChange}
- className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
- placeholder="Enter your JIRA Personal Access Token"
- />
- <p className="text-xs text-gray-400 mt-1">
- Generate this from your JIRA profile → Personal Access Tokens
- </p>
- </FormField>
-
- <div className="flex flex-col sm:flex-row gap-2">
- <button
- onClick={handleSave}
- disabled={saving || !formData.name || !formData.baseUrl || !formData.email || !formData.apiToken}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded disabled:opacity-50 disabled:cursor-not-allowed"
- >
- {saving ? 'Saving...' : 'Save'}
- </button>
- <button
- onClick={handleCancel}
- disabled={saving}
- className="max-w-full w-full @sm/page:w-auto px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded disabled:opacity-50"
- >
- Cancel
- </button>
- </div>
- </div>
- </div>
- ) : null}
-
- <div className="space-y-4 @5xl/page:col-start-2 @5xl/page:row-start-1">
- {Object.values(instances).length === 0 ? (
- <div className="bg-gray-800 rounded-lg p-8 text-center">
- <p className="text-gray-400">No JIRA instances configured.</p>
- <p className="text-gray-500 text-sm mt-2">
- Add a JIRA instance to enable ticket creation for your apps.
- </p>
- </div>
- ) : (
- Object.values(instances).map((instance) => (
- <div key={instance.id} className="bg-gray-800 rounded-lg p-4 sm:p-6">
- <div className="flex flex-col gap-4">
- <div className="flex-1 min-w-0">
- <h3 className="text-lg font-bold text-white truncate">{instance.name}</h3>
- <p className="text-gray-400 text-sm mt-1 break-all">{instance.baseUrl}</p>
- <p className="text-gray-500 text-sm truncate">Email: {instance.email}</p>
- <p className="text-gray-500 text-sm">
- API Token: {instance.hasApiToken ? '✓ Configured' : '✗ Not set'}
- </p>
- {instance.hasApiToken && (() => {
- const ageDays = getTokenAgeDays(instance.tokenUpdatedAt);
- if (ageDays === null) return (
- <p className="text-port-warning text-sm mt-1">
- Token age unknown — re-save to start tracking age
- </p>
- );
- if (ageDays >= TOKEN_STALE_WARN_DAYS) return (
- <p className="text-port-warning text-sm mt-1">
- Token saved {ageDays} days ago — click Test to confirm it&apos;s still valid
- </p>
- );
- return null;
- })()}
- </div>
-
- <div className="flex flex-wrap gap-2">
- <button
- onClick={() => handleTest(instance.id)}
- disabled={testingInstance === instance.id}
- className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded disabled:opacity-50"
- >
- {testingInstance === instance.id ? 'Testing...' : 'Test'}
- </button>
- <button
- onClick={() => handleEdit(instance)}
- className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-port-warning hover:bg-port-warning/80 text-white text-sm rounded"
- >
- Edit
- </button>
- <button
- onClick={() => handleDeleteClick(instance.id)}
- className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-port-error hover:bg-port-error/80 text-white text-sm rounded"
- >
- Delete
- </button>
- </div>
- </div>
-
- {testResult && testResult.success !== undefined && (
- <div
- className={`mt-4 p-3 rounded ${
- testResult.success
- ? 'bg-port-success/20 border border-port-success/40'
- : 'bg-port-error/20 border border-port-error/40'
- }`}
- >
- {testResult.success ? (
- <div>
- <p className="text-port-success font-medium">✓ Connection successful</p>
- <p className="text-port-success/80 text-sm mt-1">
- Authenticated as: {testResult.user} ({testResult.email})
- </p>
- </div>
- ) : (
- <div>
- <p className="text-port-error font-medium">✗ Connection failed</p>
- <p className="text-port-error/80 text-sm mt-1">{testResult.error}</p>
- </div>
- )}
- </div>
- )}
- </div>
- ))
- )}
- </div>
-
- <div className="bg-gray-800 rounded-lg p-4 sm:p-6 min-w-0">
- <h2 className="text-base sm:text-lg font-bold text-white mb-3 sm:mb-4">Usage</h2>
- <div className="space-y-2 text-xs sm:text-sm text-gray-300">
- <p>1. Add one or more JIRA instances above</p>
- <p>2. Go to Apps and configure JIRA settings for each app</p>
- <p>
- 3. When the Chief of Staff works on an app with JIRA enabled, it will:
- </p>
- <ul className="list-disc list-inside ml-2 sm:ml-4 space-y-1 text-gray-400">
- <li>Create a JIRA ticket for the work</li>
- <li>Create a feature branch (e.g., feature/PROJ-1234)</li>
- <li>Make commits to that branch</li>
- <li>Create a pull request with ticket link</li>
- </ul>
- </div>
- </div>
- </div>
- </div>
- );
+ return <IntegrationInstancesPage
+ title="JIRA" apiBase="/jira" feature="jira" fields={fields} initialForm={initialForm}
+ heading={<h1 className="text-xl sm:text-2xl font-bold text-white">JIRA Integration</h1>}
+ skeletonWidth="w-52" emptyDescription="Add a JIRA instance to enable ticket creation for your apps."
+ deleteDescription="This will not affect existing tickets."
+ headerActions={<Link to="/devtools/jira/reports" className="px-4 py-2 border border-port-border hover:border-port-accent text-gray-300 hover:text-white rounded text-sm">Status Reports</Link>}
+ summarize={instance => {
+ const ageDays = instance.hasApiToken ? getTokenAgeDays(instance.tokenUpdatedAt) : null;
+ return <>
+ <p className="text-gray-400 text-sm mt-1 break-all">{instance.baseUrl}</p>
+ <p className="text-gray-500 text-sm truncate">Email: {instance.email}</p>
+ <p className="text-gray-500 text-sm">API Token: {instance.hasApiToken ? '✓ Configured' : '✗ Not set'}</p>
+ {instance.hasApiToken && ageDays === null && <p className="text-port-warning text-sm mt-1">Token age unknown — re-save to start tracking age</p>}
+ {instance.hasApiToken && ageDays >= TOKEN_STALE_WARN_DAYS && <p className="text-port-warning text-sm mt-1">Token saved {ageDays} days ago — click Test to confirm it&apos;s still valid</p>}
+ </>;
+ }}
+ testSuccessDetail={result => <div>
+ <p className="text-port-success font-medium">✓ Connection successful</p>
+ <p className="text-port-success/80 text-sm mt-1">Authenticated as: {result.user} ({result.email})</p>
+ </div>}
+ helpSteps={<>
+ <p>1. Add one or more JIRA instances above</p>
+ <p>2. Go to Apps and configure JIRA settings for each app</p>
+ <p>3. When the Chief of Staff works on an app with JIRA enabled, it will:</p>
+ <ul className="list-disc list-inside ml-2 sm:ml-4 space-y-1 text-gray-400">
+ <li>Create a JIRA ticket for the work</li>
+ <li>Create a feature branch (e.g., feature/PROJ-1234)</li>
+ <li>Make commits to that branch</li>
+ <li>Create a pull request with ticket link</li>
+ </ul>
+ </>}
+ />;
}
diff --git a/client/src/pages/Jira.test.jsx b/client/src/pages/Jira.test.jsx
index 9509447ed0..2f104720b7 100644
--- a/client/src/pages/Jira.test.jsx
+++ b/client/src/pages/Jira.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
-import { act, render, screen, cleanup } from '@testing-library/react';
+import { act, render, screen, cleanup, fireEvent, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
vi.mock('../services/api', () => ({
@@ -84,3 +84,34 @@ describe('Jira page — token age display', () => {
expect(screen.queryByText(/expired/)).not.toBeInTheDocument();
});
});
+
+describe('Jira instance management', () => {
+ it('shows a test result only on the tested instance', async () => {
+ api.get.mockResolvedValue({ instances: {
+ ...instance().instances,
+ 'inst-2': { id: 'inst-2', name: 'Example JIRA', baseUrl: 'https://jira.example.com', email: '[email protected]', hasApiToken: true }
+ } });
+ api.post.mockResolvedValue({ success: true, user: 'Example User', email: '[email protected]' });
+ await renderPage();
+ const firstCard = screen.getByText('Acme JIRA').closest('.bg-gray-800');
+ const secondCard = screen.getByText('Example JIRA').closest('.bg-gray-800');
+
+ await act(async () => fireEvent.click(within(firstCard).getByRole('button', { name: 'Test' })));
+
+ expect(within(firstCard).getByText(/Authenticated as: Example User/)).toBeInTheDocument();
+ expect(within(secondCard).queryByText(/Authenticated as:/)).not.toBeInTheDocument();
+ });
+
+ it('saves a name edit without re-entering the existing token', async () => {
+ api.get.mockResolvedValue(instance());
+ api.post.mockResolvedValue({ id: 'inst-1', name: 'Renamed JIRA', hasApiToken: true });
+ await renderPage();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Edit' })));
+ expect(screen.getByPlaceholderText('Leave blank to keep existing key')).toHaveValue('');
+ fireEvent.change(screen.getByLabelText('Display Name'), { target: { value: 'Renamed JIRA' } });
+ const save = screen.getByRole('button', { name: 'Save' });
+ expect(save).toBeEnabled();
+ await act(async () => fireEvent.click(save));
+ expect(api.post).toHaveBeenCalledWith('/jira/instances', expect.objectContaining({ id: 'inst-1', name: 'Renamed JIRA', apiToken: undefined }), { silent: true });
+ });
+});
diff --git a/server/routes/jira.js b/server/routes/jira.js
index d82ed40bcc..6de00565dd 100644
--- a/server/routes/jira.js
+++ b/server/routes/jira.js
@@ -15,7 +15,7 @@ const jiraInstanceSchema = z.object({
name: z.string().min(1),
baseUrl: z.string().url(),
email: z.string().email(),
- apiToken: z.string().min(1),
+ apiToken: z.string().min(1).optional(),
});
const jiraTicketCreateSchema = z.object({
@@ -89,6 +89,13 @@ router.get('/instances', asyncHandler(async (req, res) => {
router.post('/instances', asyncHandler(async (req, res) => {
const { id, name, baseUrl, email, apiToken } = validateRequest(jiraInstanceSchema, req.body);
+ if (!apiToken) {
+ const { instances } = await jiraService.getInstances();
+ if (!instances?.[id]?.apiToken) {
+ throw new ServerError('API token is required for a new JIRA instance', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ }
+
const instance = await jiraService.upsertInstance(id, {
name,
baseUrl,
diff --git a/server/routes/jira.test.js b/server/routes/jira.test.js
index c21de74909..94bc1c41d1 100644
--- a/server/routes/jira.test.js
+++ b/server/routes/jira.test.js
@@ -47,6 +47,27 @@ function makeApp() {
return app;
}
+describe('POST /instances token updates', () => {
+ const details = { id: 'example', name: 'Example Jira', baseUrl: 'https://jira.example.com', email: '[email protected]' };
+
+ beforeEach(() => vi.clearAllMocks());
+
+ it('requires a token when creating an instance', async () => {
+ jiraService.getInstances.mockResolvedValue({ instances: {} });
+ const response = await request(makeApp()).post('/api/jira/instances').send(details);
+ expect(response.status).toBe(400);
+ expect(jiraService.upsertInstance).not.toHaveBeenCalled();
+ });
+
+ it('keeps the saved token when updating other fields', async () => {
+ jiraService.getInstances.mockResolvedValue({ instances: { example: { apiToken: 'stored-secret' } } });
+ jiraService.upsertInstance.mockResolvedValue({ ...details, hasApiToken: true, tokenUpdatedAt: '2026-01-01T00:00:00.000Z' });
+ const response = await request(makeApp()).post('/api/jira/instances').send(details);
+ expect(response.status).toBe(200);
+ expect(jiraService.upsertInstance).toHaveBeenCalledWith('example', expect.objectContaining({ apiToken: undefined }));
+ });
+});
+
describe('GET /reports/:appId/:date', () => {
it('rejects unsafe path parameters before reading a report', async () => {
const response = await request(makeApp()).get('/api/jira/reports/bad@app/2026-01-01');
diff --git a/server/services/jira.js b/server/services/jira.js
index 4a711b72ce..7a6c54073d 100644
--- a/server/services/jira.js
+++ b/server/services/jira.js
@@ -90,8 +90,10 @@ export async function upsertInstance(instanceId, instanceData) {
name: instanceData.name,
baseUrl: instanceData.baseUrl,
email: instanceData.email,
- apiToken: instanceData.apiToken, // Server/DC PAT (sent as Bearer) or Cloud API token (sent as Basic email:token)
- tokenUpdatedAt: (instanceData.apiToken !== existing?.apiToken) ? new Date().toISOString() : (existing?.tokenUpdatedAt || new Date().toISOString()),
+ apiToken: instanceData.apiToken || existing?.apiToken, // Server/DC PAT (sent as Bearer) or Cloud API token (sent as Basic email:token)
+ tokenUpdatedAt: instanceData.apiToken && instanceData.apiToken !== existing?.apiToken
+ ? new Date().toISOString()
+ : (existing?.tokenUpdatedAt || new Date().toISOString()),
createdAt: existing?.createdAt || new Date().toISOString(),
updatedAt: new Date().toISOString()
};
diff --git a/server/services/jira.test.js b/server/services/jira.test.js
index 847748ac35..d31b9747e4 100644
--- a/server/services/jira.test.js
+++ b/server/services/jira.test.js
@@ -18,15 +18,32 @@ const {
createTicket,
deleteInstance,
fetchMyCurrentSprintTickets,
+ getInstances,
getEpicChildren,
getIssue,
isCloudInstance,
jiraAuthHeader,
resolveCustomFieldIds,
+ saveInstances,
updateTicket,
upsertInstance
} = await import('./jira.js');
+describe('upsertInstance token preservation', () => {
+ it('preserves the token and token age when editing metadata without a new token', async () => {
+ const tokenUpdatedAt = '2026-01-01T00:00:00.000Z';
+ await saveInstances({ instances: { example: {
+ id: 'example', name: 'Original', baseUrl: 'https://jira.example.com',
+ email: '[email protected]', apiToken: 'stored-secret', tokenUpdatedAt
+ } } });
+ const updated = await upsertInstance('example', {
+ name: 'Renamed', baseUrl: 'https://jira.example.com', email: '[email protected]'
+ });
+ expect(updated).toMatchObject({ name: 'Renamed', apiToken: 'stored-secret', tokenUpdatedAt });
+ expect((await getInstances()).instances.example).toMatchObject({ apiToken: 'stored-secret', tokenUpdatedAt });
+ });
+});
+
describe('isCloudInstance', () => {
it('treats *.atlassian.net hosts as Cloud', () => {
expect(isCloudInstance('https://example.atlassian.net')).toBe(true);