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: resolve Jira Cloud assignees before ticket creation (#5046)

[._.]/ Adam Eivycb24d9403627
diff --git a/server/services/jira.js b/server/services/jira.js
index dc6cfc910d..6d9b5b8fd1 100644
--- a/server/services/jira.js
+++ b/server/services/jira.js
@@ -4,7 +4,9 @@
*/
import fs from 'fs/promises';
+import { createBoundedStateMap } from '../lib/boundedStateMap.js';
import { createHttpClient } from '../lib/httpClient.js';
+import { createSingleFlight } from '../lib/singleFlight.js';
import path from 'path';
import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { hostFromOriginUrl } from '../lib/workTracker.js';
@@ -12,6 +14,27 @@ import { countConfiguredInstances } from '../lib/instanceFeatureRegistry.js';
const JIRA_CONFIG_FILE = path.join(PATHS.data, 'jira.json');
+// Resolved Cloud user-search results are stable until the instance credentials
+// change, and ticket creation can happen repeatedly in one run. Keep only
+// positive results in a bounded per-instance cache so a transient failure or an
+// initially hidden user can recover on the next ticket.
+const cloudAssigneeCache = new Map();
+const cloudAssigneeLookupFlight = createSingleFlight();
+
+function getCloudAssigneeCache(instanceId) {
+ let instanceCache = cloudAssigneeCache.get(instanceId);
+ if (!instanceCache) {
+ instanceCache = createBoundedStateMap();
+ cloudAssigneeCache.set(instanceId, instanceCache);
+ }
+ return instanceCache;
+}
+
+export function clearCloudAssigneeCache(instanceId) {
+ if (instanceId === undefined) cloudAssigneeCache.clear();
+ else cloudAssigneeCache.delete(instanceId);
+}
+
// Whether this install has any JIRA instance configured. Read-only on purpose:
// unlike getInstances() it never seeds an empty config file, because the
// instance-feature registry calls it just to decide whether the JIRA nav
@@ -79,6 +102,7 @@ export async function upsertInstance(instanceId, instanceData) {
};
await saveInstances(config);
+ clearCloudAssigneeCache(instanceId);
return config.instances[instanceId];
}
@@ -89,6 +113,7 @@ export async function deleteInstance(instanceId) {
const config = await getInstances();
delete config.instances[instanceId];
await saveInstances(config);
+ clearCloudAssigneeCache(instanceId);
}
/**
@@ -224,6 +249,68 @@ export async function getProjects(instanceId) {
}));
}
+/**
+ * Resolve a literal Cloud assignee to the GDPR-compatible accountId field.
+ *
+ * Jira's user search accepts both email addresses and display names. Keep the
+ * query's original spelling for Jira, but normalize the cache key so harmless
+ * casing differences do not create another request. A null result is reported
+ * but deliberately not cached, so an unresolvable configured value creates an
+ * unassigned ticket and can resolve on a later retry without sending the
+ * rejected `{ name }` shape to Cloud.
+ */
+async function resolveCloudAssignee(instanceId, client, assignee) {
+ const query = assignee.trim();
+ if (!query) return null;
+ const cacheKey = query.toLowerCase();
+ const instanceCache = getCloudAssigneeCache(instanceId);
+
+ const cachedAccountId = instanceCache.get(cacheKey);
+ if (cachedAccountId !== undefined) return cachedAccountId;
+
+ const lookup = cloudAssigneeLookupFlight.run(`${instanceId}\u0000${cacheKey}`, async () => {
+ const response = await client.get('/rest/api/2/user/search', { params: { query } });
+ if (!Array.isArray(response.data)) throw new Error('JIRA Cloud assignee search returned an invalid user list');
+
+ const users = response.data.filter(user => {
+ const accountType = typeof user?.accountType === 'string' ? user.accountType.toLowerCase() : null;
+ return user?.active !== false && accountType !== 'app';
+ });
+ const exactAccountIds = [...new Set(users
+ .filter(user => [user?.accountId, user?.emailAddress, user?.displayName, user?.name]
+ .some(value => typeof value === 'string' && value.trim().toLowerCase() === cacheKey))
+ .map(user => user?.accountId)
+ .filter(accountId => typeof accountId === 'string' && accountId.trim())
+ .map(accountId => accountId.trim()))];
+ const soleAccountId = response.data.length === 1 && users.length === 1 && typeof users[0]?.accountId === 'string'
+ ? users[0].accountId.trim()
+ : '';
+ const accountId = exactAccountIds.length === 1
+ ? exactAccountIds[0]
+ : exactAccountIds.length > 1
+ ? null
+ : soleAccountId
+ ? soleAccountId
+ : null;
+
+ if (accountId && cloudAssigneeCache.get(instanceId) === instanceCache) {
+ instanceCache.set(cacheKey, accountId);
+ }
+ if (!accountId) {
+ console.warn(`⚠️ JIRA Cloud assignee could not be resolved for instance ${instanceId}; creating ticket unassigned`);
+ }
+
+ return accountId;
+ });
+ return lookup.then(
+ accountId => accountId,
+ () => {
+ console.warn(`⚠️ JIRA Cloud assignee lookup failed for instance ${instanceId}; creating ticket unassigned`);
+ return null;
+ }
+ );
+}
+
/**
* Create JIRA ticket
*/
@@ -251,8 +338,14 @@ export async function createTicket(instanceId, ticketData) {
};
// Add optional fields
- if (ticketData.assignee) {
- issue.fields.assignee = { name: ticketData.assignee };
+ const assignee = typeof ticketData.assignee === 'string' ? ticketData.assignee.trim() : '';
+ if (assignee) {
+ if (isCloudInstance(instance.baseUrl)) {
+ const accountId = await resolveCloudAssignee(instanceId, client, assignee);
+ if (accountId) issue.fields.assignee = { accountId };
+ } else {
+ issue.fields.assignee = { name: assignee };
+ }
}
// Custom field IDs vary per JIRA instance — use instance config or defaults
@@ -739,6 +832,7 @@ export default {
saveInstances,
upsertInstance,
deleteInstance,
+ clearCloudAssigneeCache,
testConnection,
getProjects,
getBoards,
diff --git a/server/services/jira.test.js b/server/services/jira.test.js
index f868ee6710..5c5ac163f7 100644
--- a/server/services/jira.test.js
+++ b/server/services/jira.test.js
@@ -1,5 +1,16 @@
+import fs from 'fs/promises';
import { describe, it, expect, vi, afterEach } from 'vitest';
-import { buildColumnsFromBoardConfig, buildColumnsFromStatuses, createJiraClient, isCloudInstance, jiraAuthHeader } from './jira.js';
+import {
+ buildColumnsFromBoardConfig,
+ buildColumnsFromStatuses,
+ clearCloudAssigneeCache,
+ createJiraClient,
+ createTicket,
+ deleteInstance,
+ isCloudInstance,
+ jiraAuthHeader,
+ upsertInstance
+} from './jira.js';
describe('isCloudInstance', () => {
it('treats *.atlassian.net hosts as Cloud', () => {
@@ -126,6 +137,301 @@ describe('createJiraClient search endpoint routing', () => {
});
});
+describe('createTicket assignee resolution', () => {
+ const INSTANCE_ID = 'jira-example';
+
+ const stubInstance = (instance = {}) => {
+ stubInstances({
+ [INSTANCE_ID]: {
+ id: INSTANCE_ID,
+ name: 'Example JIRA',
+ baseUrl: 'https://jira.example.com',
+ apiToken: 'pat',
+ ...instance
+ }
+ });
+ };
+
+ const stubInstances = (instances) => {
+ vi.spyOn(fs, 'readFile').mockResolvedValue(JSON.stringify({
+ instances
+ }));
+ };
+
+ const stubFetchSequence = (responses) => {
+ const fetchMock = vi.fn();
+ for (const response of responses) {
+ fetchMock.mockResolvedValueOnce({
+ ok: response.ok !== false,
+ status: response.status || 200,
+ headers: { get: name => (name.toLowerCase() === 'content-type' ? 'application/json' : null) },
+ json: async () => response.body,
+ text: async () => JSON.stringify(response.body)
+ });
+ }
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+ };
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ clearCloudAssigneeCache();
+ });
+
+ it('resolves a Cloud email to accountId and caches it for later tickets', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [{ accountId: 'acct-123', emailAddress: '[email protected]' }] },
+ { body: { key: 'PROJ-1' } },
+ { body: { key: 'PROJ-2' } }
+ ]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'First', assignee: '[email protected]' });
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Second', assignee: '[email protected]' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ const searchUrl = new URL(fetchMock.mock.calls[0][0]);
+ expect(searchUrl.pathname).toBe('/rest/api/2/user/search');
+ expect(searchUrl.searchParams.get('query')).toBe('[email protected]');
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields.assignee).toEqual({ accountId: 'acct-123' });
+ expect(JSON.parse(fetchMock.mock.calls[2][1].body).fields.assignee).toEqual({ accountId: 'acct-123' });
+ });
+
+ it('resolves a Cloud display name to accountId', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [{ accountId: 'acct-456', displayName: 'Example Assignee' }] },
+ { body: { key: 'PROJ-3' } }
+ ]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Display name', assignee: 'Example Assignee' });
+
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields.assignee).toEqual({ accountId: 'acct-456' });
+ });
+
+ it('resolves a privacy-redacted Cloud email result when it is unique', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [{ accountId: 'acct-567' }] },
+ { body: { key: 'PROJ-8' } }
+ ]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Redacted email', assignee: '[email protected]' });
+
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields.assignee).toEqual({ accountId: 'acct-567' });
+ });
+
+ it('keeps Server/DC assignees as name without a user-search request', async () => {
+ stubInstance();
+ const fetchMock = stubFetchSequence([{ body: { key: 'PROJ-4' } }]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Server ticket', assignee: 'jdoe' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body).fields.assignee).toEqual({ name: 'jdoe' });
+ });
+
+ it('creates unassigned Cloud tickets and retries an unresolvable assignee', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [] },
+ { body: { key: 'PROJ-5' } },
+ { body: [] },
+ { body: { key: 'PROJ-6' } }
+ ]);
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Unassigned', assignee: '[email protected]' });
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Still unassigned', assignee: '[email protected]' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields).not.toHaveProperty('assignee');
+ expect(JSON.parse(fetchMock.mock.calls[3][1].body).fields).not.toHaveProperty('assignee');
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not be resolved'));
+ expect(warn).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not assign a Cloud ticket when the search result is ambiguous', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [
+ { accountId: 'acct-789', displayName: 'Example User' },
+ { accountId: 'acct-987', displayName: 'Example User' }
+ ] },
+ { body: { key: 'PROJ-7' } }
+ ]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Ambiguous', assignee: 'Example User' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields).not.toHaveProperty('assignee');
+ });
+
+ it('does not use the privacy fallback across multiple returned candidates', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [
+ { accountId: 'acct-789' },
+ { accountId: 'acct-987', displayName: 'Other User' }
+ ] },
+ { body: { key: 'PROJ-9' } }
+ ]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Mixed candidates', assignee: '[email protected]' });
+
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields).not.toHaveProperty('assignee');
+ });
+
+ it('creates unassigned tickets for malformed Cloud search responses and retries', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: { users: [] } },
+ { body: { key: 'PROJ-10' } },
+ { body: [{ accountId: 'acct-999', emailAddress: '[email protected]' }] },
+ { body: { key: 'PROJ-11' } }
+ ]);
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Malformed response', assignee: '[email protected]' });
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Retry response', assignee: '[email protected]' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields).not.toHaveProperty('assignee');
+ expect(JSON.parse(fetchMock.mock.calls[3][1].body).fields.assignee).toEqual({ accountId: 'acct-999' });
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('lookup failed'));
+ });
+
+ it('creates unassigned tickets when Cloud user search fails and retries', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { ok: false, status: 503, body: { errorMessages: ['temporary failure'] } },
+ { body: { key: 'PROJ-12' } },
+ { body: [{ accountId: 'acct-1000', emailAddress: '[email protected]' }] },
+ { body: { key: 'PROJ-13' } }
+ ]);
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Failed lookup', assignee: '[email protected]' });
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Retry failed lookup', assignee: '[email protected]' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields).not.toHaveProperty('assignee');
+ expect(JSON.parse(fetchMock.mock.calls[3][1].body).fields.assignee).toEqual({ accountId: 'acct-1000' });
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('lookup failed'));
+ });
+
+ it('normalizes the Cloud cache key for case-only assignee changes', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [{ accountId: 'acct-case', emailAddress: '[email protected]' }] },
+ { body: { key: 'PROJ-14' } },
+ { body: { key: 'PROJ-15' } }
+ ]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Lowercase', assignee: '[email protected]' });
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Uppercase', assignee: '[email protected]' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields.assignee).toEqual({ accountId: 'acct-case' });
+ expect(JSON.parse(fetchMock.mock.calls[2][1].body).fields.assignee).toEqual({ accountId: 'acct-case' });
+ });
+
+ it('ignores inactive and app accounts when resolving a Cloud assignee', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [
+ { accountId: 'acct-inactive', emailAddress: '[email protected]', active: false },
+ { accountId: 'acct-app', emailAddress: '[email protected]', accountType: 'app' }
+ ] },
+ { body: { key: 'PROJ-16' } }
+ ]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Inactive', assignee: '[email protected]' });
+
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields).not.toHaveProperty('assignee');
+ });
+
+ it('does not use a filtered candidate as the privacy fallback', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [
+ { accountId: 'acct-inactive', displayName: 'Jane', active: false },
+ { accountId: 'acct-janet', displayName: 'Janet Roe' }
+ ] },
+ { body: { key: 'PROJ-18' } }
+ ]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Filtered candidate', assignee: 'Jane' });
+
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields).not.toHaveProperty('assignee');
+ });
+
+ it('omits whitespace-only assignees without a Cloud lookup', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([{ body: { key: 'PROJ-17' } }]);
+
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Blank assignee', assignee: ' ' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body).fields).not.toHaveProperty('assignee');
+ });
+
+ it('isolates assignee caches per Jira instance', async () => {
+ stubInstances({
+ 'jira-one': { id: 'jira-one', baseUrl: 'https://one.atlassian.net', email: '[email protected]', apiToken: 'token' },
+ 'jira-two': { id: 'jira-two', baseUrl: 'https://two.atlassian.net', email: '[email protected]', apiToken: 'token' }
+ });
+ const fetchMock = stubFetchSequence([
+ { body: [{ accountId: 'acct-one', emailAddress: '[email protected]' }] },
+ { body: { key: 'ONE-1' } },
+ { body: [{ accountId: 'acct-two', emailAddress: '[email protected]' }] },
+ { body: { key: 'TWO-1' } }
+ ]);
+
+ await createTicket('jira-one', { projectKey: 'ONE', summary: 'One', assignee: '[email protected]' });
+ await createTicket('jira-two', { projectKey: 'TWO', summary: 'Two', assignee: '[email protected]' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields.assignee).toEqual({ accountId: 'acct-one' });
+ expect(JSON.parse(fetchMock.mock.calls[3][1].body).fields.assignee).toEqual({ accountId: 'acct-two' });
+ });
+
+ it('coalesces concurrent lookups and invalidates them on instance changes', async () => {
+ stubInstance({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'token' });
+ const fetchMock = stubFetchSequence([
+ { body: [{ accountId: 'acct-first', emailAddress: '[email protected]' }] },
+ { body: { key: 'PROJ-11' } },
+ { body: { key: 'PROJ-12' } },
+ { body: [{ accountId: 'acct-updated', emailAddress: '[email protected]' }] },
+ { body: { key: 'PROJ-13' } },
+ { body: [{ accountId: 'acct-deleted', emailAddress: '[email protected]' }] },
+ { body: { key: 'PROJ-14' } }
+ ]);
+ vi.spyOn(fs, 'writeFile').mockResolvedValue();
+
+ await Promise.all([
+ createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Concurrent one', assignee: '[email protected]' }),
+ createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Concurrent two', assignee: '[email protected]' })
+ ]);
+ await upsertInstance(INSTANCE_ID, {
+ name: 'Example JIRA',
+ baseUrl: 'https://example.atlassian.net',
+ email: '[email protected]',
+ apiToken: 'new-token'
+ });
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Updated', assignee: '[email protected]' });
+ await deleteInstance(INSTANCE_ID);
+ await createTicket(INSTANCE_ID, { projectKey: 'PROJ', summary: 'Deleted', assignee: '[email protected]' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(7);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).fields.assignee).toEqual({ accountId: 'acct-first' });
+ expect(JSON.parse(fetchMock.mock.calls[2][1].body).fields.assignee).toEqual({ accountId: 'acct-first' });
+ expect(JSON.parse(fetchMock.mock.calls[4][1].body).fields.assignee).toEqual({ accountId: 'acct-updated' });
+ expect(JSON.parse(fetchMock.mock.calls[6][1].body).fields.assignee).toEqual({ accountId: 'acct-deleted' });
+ });
+});
+
describe('buildColumnsFromBoardConfig', () => {
const statusById = new Map([
['1', { name: 'To Do', category: 'To Do' }],