@lornatang/dsh-atlassian 0.1.6 → 0.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.md +153 -156
- package/README.zh.md +181 -0
- package/lib/board.js +21 -4
- package/lib/bridge.js +232 -32
- package/lib/client.js +57 -12
- package/lib/index.js +9 -2
- package/lib/oauth.js +96 -27
- package/lib/routes.js +36 -8
- package/lib/server-bridge.js +43 -25
- package/lib/server-http.js +10 -4
- package/lib/store.js +203 -34
- package/lib/types/board.d.ts +2 -0
- package/lib/types/bridge.d.ts +2 -1
- package/lib/types/oauth.d.ts +11 -1
- package/lib/types/server-bridge.d.ts +1 -0
- package/lib/types/server-http.d.ts +2 -0
- package/lib/types/store.d.ts +18 -2
- package/package.json +3 -1
package/lib/board.js
CHANGED
|
@@ -29,15 +29,16 @@ function issue(value, base) {
|
|
|
29
29
|
export class JiraBoard {
|
|
30
30
|
#bridge;
|
|
31
31
|
#resource;
|
|
32
|
+
#pending;
|
|
32
33
|
constructor(bridge) { this.#bridge = bridge; }
|
|
33
34
|
available() { return !!this.#bridge.rawNameMatching(/searchJiraIssuesUsingJql/i); }
|
|
34
|
-
get site() { return this.#resource?.site; }
|
|
35
|
+
get site() { return this.#resource?.epoch === (this.#bridge.epoch?.() ?? 0) ? this.#resource.site : undefined; }
|
|
35
36
|
async #call(pattern, args, timeoutMs) {
|
|
36
37
|
const name = this.#bridge.rawNameMatching(pattern);
|
|
37
38
|
if (!name) {
|
|
38
39
|
const state = this.#bridge.snapshot?.();
|
|
39
40
|
if (state && state.status !== 'ready')
|
|
40
|
-
throw new BoardError('not-connected', state.error || `Atlassian is not connected
|
|
41
|
+
throw new BoardError('not-connected', state.error || `Atlassian is not connected (${state.status})`);
|
|
41
42
|
throw new BoardError('missing-tool', `Missing Jira tool: ${pattern.source}`);
|
|
42
43
|
}
|
|
43
44
|
let blocks;
|
|
@@ -56,8 +57,22 @@ export class JiraBoard {
|
|
|
56
57
|
}
|
|
57
58
|
}
|
|
58
59
|
async cloudId() {
|
|
59
|
-
|
|
60
|
+
const epoch = this.#bridge.epoch?.() ?? 0;
|
|
61
|
+
if (this.#resource?.epoch === epoch)
|
|
60
62
|
return this.#resource.id;
|
|
63
|
+
if (this.#pending?.epoch === epoch)
|
|
64
|
+
return this.#pending.promise;
|
|
65
|
+
const promise = this.#resolveSite(epoch);
|
|
66
|
+
this.#pending = { epoch, promise };
|
|
67
|
+
try {
|
|
68
|
+
return await promise;
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
if (this.#pending?.promise === promise)
|
|
72
|
+
this.#pending = undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async #resolveSite(epoch) {
|
|
61
76
|
const data = await this.#call(/accessibleatlassianresources/i, {}, 20000);
|
|
62
77
|
const list = Array.isArray(data) ? data : [data];
|
|
63
78
|
for (const item of list) {
|
|
@@ -70,7 +85,9 @@ export class JiraBoard {
|
|
|
70
85
|
const parsed = new URL(url);
|
|
71
86
|
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password)
|
|
72
87
|
continue;
|
|
73
|
-
|
|
88
|
+
// A reconnect may have invalidated this resolution while it was in flight.
|
|
89
|
+
if ((this.#bridge.epoch?.() ?? 0) === epoch)
|
|
90
|
+
this.#resource = { epoch, id, base: `${parsed.origin}${parsed.pathname.replace(/\/$/, '')}`, site: parsed.host };
|
|
74
91
|
return id;
|
|
75
92
|
}
|
|
76
93
|
catch {
|
package/lib/bridge.js
CHANGED
|
@@ -1,10 +1,23 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import {
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
3
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
4
4
|
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
5
5
|
import { UnauthorizedError, auth } from '@modelcontextprotocol/sdk/client/auth.js';
|
|
6
|
-
import { AtlassianOAuthProvider, CallbackServer, createCloudFetch } from './oauth.js';
|
|
6
|
+
import { AtlassianOAuthProvider, CallbackServer, RedirectRegistrationChanged, createCloudFetch, secureUrl } from './oauth.js';
|
|
7
|
+
import { OAuthTokensSchema } from '@modelcontextprotocol/sdk/shared/auth.js';
|
|
7
8
|
import { openInBrowser } from './open-url.js';
|
|
9
|
+
import { sameTokens } from './store.js';
|
|
10
|
+
async function waitForFlight(flight, signal) {
|
|
11
|
+
if (signal.aborted)
|
|
12
|
+
throw new Error('atlassian: connection cancelled');
|
|
13
|
+
await new Promise((resolve, reject) => {
|
|
14
|
+
const abort = () => { signal.removeEventListener('abort', abort); reject(new Error('atlassian: connection cancelled')); };
|
|
15
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
16
|
+
void flight.then(() => { signal.removeEventListener('abort', abort); resolve(); }, reject);
|
|
17
|
+
if (signal.aborted)
|
|
18
|
+
abort();
|
|
19
|
+
});
|
|
20
|
+
}
|
|
8
21
|
export function publicToolName(server, tool) {
|
|
9
22
|
const raw = `mcp__${server}__${tool}`;
|
|
10
23
|
const clean = raw.replace(/[^A-Za-z0-9_-]/g, '_');
|
|
@@ -27,6 +40,7 @@ export class AtlassianBridge {
|
|
|
27
40
|
#host;
|
|
28
41
|
#options;
|
|
29
42
|
#callback = new CallbackServer();
|
|
43
|
+
#operation = new AsyncLocalStorage();
|
|
30
44
|
#provider;
|
|
31
45
|
#fetch;
|
|
32
46
|
#client;
|
|
@@ -38,12 +52,175 @@ export class AtlassianBridge {
|
|
|
38
52
|
#boot;
|
|
39
53
|
#generation = 0;
|
|
40
54
|
#disposed = false;
|
|
55
|
+
#controller = new AbortController();
|
|
56
|
+
#flight;
|
|
57
|
+
#refreshes = new Set();
|
|
58
|
+
#waiters = new Set();
|
|
41
59
|
constructor(host, options) {
|
|
42
60
|
this.#host = host;
|
|
43
61
|
this.#options = options;
|
|
44
62
|
const network = createCloudFetch(new URL(options.url));
|
|
45
|
-
|
|
46
|
-
|
|
63
|
+
const active = () => {
|
|
64
|
+
const operation = this.#operation.getStore();
|
|
65
|
+
return !this.#disposed && (!operation || (operation.generation === this.#generation && !operation.signal.aborted));
|
|
66
|
+
};
|
|
67
|
+
this.#fetch = async (value, init) => {
|
|
68
|
+
const operation = this.#operation.getStore();
|
|
69
|
+
if (!operation) {
|
|
70
|
+
if (init?.body instanceof URLSearchParams && init.body.get('grant_type') === 'refresh_token') {
|
|
71
|
+
throw new Error('atlassian: refresh requires an active connection operation');
|
|
72
|
+
}
|
|
73
|
+
return network.fetch(value, init);
|
|
74
|
+
}
|
|
75
|
+
if (!active())
|
|
76
|
+
throw new Error('atlassian: connection cancelled');
|
|
77
|
+
const signals = [operation.signal];
|
|
78
|
+
if (init?.signal)
|
|
79
|
+
signals.push(init.signal);
|
|
80
|
+
const signal = AbortSignal.any(signals);
|
|
81
|
+
const authorization = new Headers(init?.headers).get('authorization');
|
|
82
|
+
if (authorization?.startsWith('Bearer ')) {
|
|
83
|
+
const current = this.#options.store.current.tokens;
|
|
84
|
+
const previous = operation.observedTokens;
|
|
85
|
+
operation.observedTokens = previous && authorization === `Bearer ${previous.access_token}` ? previous
|
|
86
|
+
: current && authorization === `Bearer ${current.access_token}` ? current : undefined;
|
|
87
|
+
}
|
|
88
|
+
const refresh = init?.body instanceof URLSearchParams && init.body.get('grant_type') === 'refresh_token';
|
|
89
|
+
if (!refresh)
|
|
90
|
+
return network.fetch(value, { ...init, signal });
|
|
91
|
+
// A synthetic response must obey the same URL policy as a network request.
|
|
92
|
+
secureUrl(new URL(value), network.allowLoopbackHttp);
|
|
93
|
+
const expected = operation.observedTokens;
|
|
94
|
+
while (this.#flight && this.#flight.owner !== operation)
|
|
95
|
+
await waitForFlight(this.#flight.done, signal);
|
|
96
|
+
if (!active() || signal.aborted)
|
|
97
|
+
throw new Error('atlassian: connection cancelled');
|
|
98
|
+
operation.refreshExpected = expected;
|
|
99
|
+
const lease = await this.#options.store.acquire(signal);
|
|
100
|
+
if (!active() || signal.aborted) {
|
|
101
|
+
lease.release();
|
|
102
|
+
throw new Error('atlassian: connection cancelled');
|
|
103
|
+
}
|
|
104
|
+
const current = this.#options.store.current.tokens;
|
|
105
|
+
if (expected && !sameTokens(current, expected)) {
|
|
106
|
+
lease.release();
|
|
107
|
+
return new Response(JSON.stringify(current ?? { error: 'invalid_grant' }), { status: current ? 200 : 400, headers: { 'content-type': 'application/json' } });
|
|
108
|
+
}
|
|
109
|
+
if (!this.#flight) {
|
|
110
|
+
let complete;
|
|
111
|
+
const done = new Promise((resolve) => { complete = resolve; });
|
|
112
|
+
let pending = true;
|
|
113
|
+
let requested = false;
|
|
114
|
+
const release = () => {
|
|
115
|
+
if (pending) {
|
|
116
|
+
requested = true;
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (this.#flight?.owner === operation) {
|
|
120
|
+
this.#flight = undefined;
|
|
121
|
+
signal.removeEventListener('abort', release);
|
|
122
|
+
complete();
|
|
123
|
+
}
|
|
124
|
+
if (operation.lease === lease) {
|
|
125
|
+
operation.lease = undefined;
|
|
126
|
+
lease.release();
|
|
127
|
+
}
|
|
128
|
+
if (operation.releaseRefresh === release)
|
|
129
|
+
operation.releaseRefresh = undefined;
|
|
130
|
+
};
|
|
131
|
+
this.#flight = { owner: operation, done };
|
|
132
|
+
operation.lease = lease;
|
|
133
|
+
operation.releaseRefresh = release;
|
|
134
|
+
signal.addEventListener('abort', release, { once: true });
|
|
135
|
+
if (signal.aborted) {
|
|
136
|
+
pending = false;
|
|
137
|
+
release();
|
|
138
|
+
throw new Error('atlassian: connection cancelled');
|
|
139
|
+
}
|
|
140
|
+
const exchange = (async () => {
|
|
141
|
+
try {
|
|
142
|
+
// A cancelled local request may still rotate its token remotely. Finish
|
|
143
|
+
// and persist the response before allowing another process to refresh.
|
|
144
|
+
// Bound the cross-process refresh lock even when toolCallTimeoutMs is huge.
|
|
145
|
+
const response = await network.fetch(value, { ...init, signal: AbortSignal.timeout(Math.min(120000, Math.max(30000, this.#options.toolCallTimeoutMs))) });
|
|
146
|
+
if (response.ok) {
|
|
147
|
+
const parsed = OAuthTokensSchema.omit({ issuer: true }).safeParse(await response.clone().json());
|
|
148
|
+
if (!parsed.success)
|
|
149
|
+
throw new Error('atlassian: invalid refresh response');
|
|
150
|
+
const refreshToken = init?.body instanceof URLSearchParams ? init.body.get('refresh_token') ?? undefined : undefined;
|
|
151
|
+
const issuer = expected?.issuer ?? this.#options.store.current.clientInformation?.issuer;
|
|
152
|
+
const tokens = { refresh_token: refreshToken, ...parsed.data, ...(issuer ? { issuer } : {}) };
|
|
153
|
+
await this.#options.store.saveTokens(tokens, () => true, expected, lease);
|
|
154
|
+
}
|
|
155
|
+
return response;
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
// If the response was lost, the server may already have rotated it.
|
|
159
|
+
// Do not let another process reuse the uncertain refresh token.
|
|
160
|
+
await this.#options.store.clearCredentialsIf(() => true, expected, lease, undefined, true, 'tokens');
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
pending = false;
|
|
165
|
+
if (requested)
|
|
166
|
+
release();
|
|
167
|
+
}
|
|
168
|
+
})();
|
|
169
|
+
this.#refreshes.add(exchange);
|
|
170
|
+
try {
|
|
171
|
+
return await exchange;
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
this.#refreshes.delete(exchange);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
lease.release();
|
|
178
|
+
throw new Error('atlassian: refresh is already in progress');
|
|
179
|
+
};
|
|
180
|
+
this.#provider = new AtlassianOAuthProvider({
|
|
181
|
+
store: options.store, redirectUri: () => this.#callback.redirectUri, allowLoopbackHttp: network.allowLoopbackHttp, logger: host.logger,
|
|
182
|
+
onAuthorizationUrl: (url) => {
|
|
183
|
+
if (!active())
|
|
184
|
+
return;
|
|
185
|
+
this.#setUrl(url);
|
|
186
|
+
if (this.#status === 'ready') {
|
|
187
|
+
this.#setStatus('error');
|
|
188
|
+
this.#error = 'Atlassian authorization expired; reconnect to authorize again';
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
active,
|
|
192
|
+
tokenRead: (tokens) => { const op = this.#operation.getStore(); if (op && !op.observedTokens)
|
|
193
|
+
op.observedTokens = tokens; },
|
|
194
|
+
refreshExpected: () => this.#operation.getStore()?.refreshExpected,
|
|
195
|
+
authFinished: () => { const op = this.#operation.getStore(); op?.releaseRefresh?.(); if (op)
|
|
196
|
+
op.refreshExpected = undefined; },
|
|
197
|
+
lease: () => this.#operation.getStore()?.lease,
|
|
198
|
+
observedTokens: () => this.#operation.getStore()?.observedTokens,
|
|
199
|
+
signal: () => this.#operation.getStore()?.signal,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
#newOperation() { return { generation: this.#generation, signal: this.#controller.signal }; }
|
|
203
|
+
epoch() { return this.#generation; }
|
|
204
|
+
#setStatus(status) { this.#status = status; this.#wake(); }
|
|
205
|
+
#setUrl(url) { this.#url = url; this.#wake(); }
|
|
206
|
+
#wake() { const waiters = [...this.#waiters]; this.#waiters.clear(); for (const wake of waiters)
|
|
207
|
+
wake(); }
|
|
208
|
+
/** Resolve as soon as the predicate holds, or at the deadline like the previous polling loop. */
|
|
209
|
+
#waitFor(timeoutMs, done) {
|
|
210
|
+
return new Promise((resolve) => {
|
|
211
|
+
if (done()) {
|
|
212
|
+
resolve();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const finish = () => { clearTimeout(timer); this.#waiters.delete(wake); resolve(); };
|
|
216
|
+
const wake = () => { if (done())
|
|
217
|
+
finish();
|
|
218
|
+
else
|
|
219
|
+
this.#waiters.add(wake); };
|
|
220
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
221
|
+
timer.unref();
|
|
222
|
+
this.#waiters.add(wake);
|
|
223
|
+
});
|
|
47
224
|
}
|
|
48
225
|
snapshot() {
|
|
49
226
|
const site = this.#options.store.current.site;
|
|
@@ -66,23 +243,18 @@ export class AtlassianBridge {
|
|
|
66
243
|
return this.#boot;
|
|
67
244
|
const generation = this.#generation;
|
|
68
245
|
const boot = (async () => {
|
|
69
|
-
this.#
|
|
70
|
-
await this.#options.store.load();
|
|
246
|
+
this.#setStatus('connecting');
|
|
247
|
+
await this.#options.store.load(this.#controller.signal);
|
|
71
248
|
if (this.#disposed || generation !== this.#generation)
|
|
72
249
|
return;
|
|
73
250
|
await this.#callback.listen(this.#options.redirectPort);
|
|
74
251
|
if (this.#disposed || generation !== this.#generation)
|
|
75
252
|
return;
|
|
76
|
-
|
|
77
|
-
const actual = this.#callback.redirectUri;
|
|
78
|
-
if (previous && previous !== actual)
|
|
79
|
-
await this.#options.store.clear('clientInformation', 'tokens', 'codeVerifier');
|
|
80
|
-
await this.#options.store.patch({ redirectUri: actual });
|
|
253
|
+
await this.#options.store.prepareRedirect(this.#callback.redirectUri, this.#controller.signal);
|
|
81
254
|
if (this.#disposed || generation !== this.#generation)
|
|
82
255
|
return;
|
|
83
256
|
this.#launch(false, generation);
|
|
84
|
-
|
|
85
|
-
await delay(25);
|
|
257
|
+
await this.#waitFor(15000, () => this.#status !== 'connecting');
|
|
86
258
|
})();
|
|
87
259
|
this.#boot = boot;
|
|
88
260
|
try {
|
|
@@ -90,7 +262,7 @@ export class AtlassianBridge {
|
|
|
90
262
|
}
|
|
91
263
|
catch (error) {
|
|
92
264
|
if (!this.#disposed && generation === this.#generation) {
|
|
93
|
-
this.#
|
|
265
|
+
this.#setStatus('error');
|
|
94
266
|
this.#error = error instanceof Error ? error.message : String(error);
|
|
95
267
|
}
|
|
96
268
|
throw error;
|
|
@@ -112,17 +284,18 @@ export class AtlassianBridge {
|
|
|
112
284
|
if (!this.#work) {
|
|
113
285
|
await this.#closeClient();
|
|
114
286
|
this.#clearTools();
|
|
115
|
-
this.#
|
|
287
|
+
this.#setUrl(undefined);
|
|
116
288
|
this.#launch(true, this.#generation);
|
|
117
289
|
}
|
|
118
|
-
|
|
119
|
-
|
|
290
|
+
// Wait for a settled state: the authorization URL is published just before
|
|
291
|
+
// the status leaves 'connecting', and callers act on the returned status.
|
|
292
|
+
await this.#waitFor(20000, () => this.#status !== 'connecting');
|
|
120
293
|
return this.snapshot();
|
|
121
294
|
}
|
|
122
295
|
#launch(open, generation) {
|
|
123
296
|
const work = this.#connect(open, generation).catch((error) => {
|
|
124
297
|
if (!this.#disposed && generation === this.#generation) {
|
|
125
|
-
this.#
|
|
298
|
+
this.#setStatus('error');
|
|
126
299
|
this.#error = error instanceof Error ? error.message : String(error);
|
|
127
300
|
this.#host.logger.error(`atlassian: ${this.#error}`);
|
|
128
301
|
}
|
|
@@ -136,10 +309,32 @@ export class AtlassianBridge {
|
|
|
136
309
|
throw new Error('connection cancelled'); };
|
|
137
310
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
138
311
|
check();
|
|
139
|
-
this.#
|
|
312
|
+
this.#setStatus('connecting');
|
|
140
313
|
this.#error = undefined;
|
|
141
|
-
const client = new Client({ name: 'dsh-atlassian', version: '0.1.
|
|
314
|
+
const client = new Client({ name: 'dsh-atlassian', version: '0.1.11' });
|
|
315
|
+
client.onerror = () => { this.#operation.getStore()?.releaseRefresh?.(); };
|
|
142
316
|
const transport = new StreamableHTTPClientTransport(new URL(this.#options.url), { authProvider: this.#provider, fetch: this.#fetch });
|
|
317
|
+
const send = transport.send.bind(transport);
|
|
318
|
+
transport.send = (message, options) => {
|
|
319
|
+
const operation = this.#newOperation();
|
|
320
|
+
return this.#operation.run(operation, async () => {
|
|
321
|
+
try {
|
|
322
|
+
return await send(message, options);
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
operation.releaseRefresh?.();
|
|
326
|
+
if (!this.#disposed && operation.generation === this.#generation && this.#status === 'ready' && operation.observedTokens && !this.#options.store.current.tokens) {
|
|
327
|
+
this.#setStatus('error');
|
|
328
|
+
this.#error = 'Atlassian authorization expired; reconnect to authorize again';
|
|
329
|
+
}
|
|
330
|
+
if (!(error instanceof RedirectRegistrationChanged))
|
|
331
|
+
throw error;
|
|
332
|
+
operation.observedTokens = undefined;
|
|
333
|
+
operation.refreshExpected = undefined;
|
|
334
|
+
return send(message, options);
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
};
|
|
143
338
|
try {
|
|
144
339
|
await client.connect(transport);
|
|
145
340
|
check();
|
|
@@ -151,23 +346,23 @@ export class AtlassianBridge {
|
|
|
151
346
|
throw error;
|
|
152
347
|
const state = this.#url ? new URL(this.#url).searchParams.get('state') ?? undefined : undefined;
|
|
153
348
|
const waiting = this.#callback.waitForCode(this.#options.authorizationTimeoutMs, state);
|
|
154
|
-
this.#
|
|
349
|
+
this.#setStatus('authorizing');
|
|
155
350
|
if (open && this.#url && this.#options.autoOpenBrowser)
|
|
156
351
|
void openInBrowser(this.#url);
|
|
157
352
|
const callback = await waiting;
|
|
158
353
|
check();
|
|
159
|
-
await auth(this.#provider, { serverUrl: this.#options.url, authorizationCode: callback.code, fetchFn: this.#fetch });
|
|
354
|
+
await this.#operation.run(this.#newOperation(), () => auth(this.#provider, { serverUrl: this.#options.url, authorizationCode: callback.code, fetchFn: this.#fetch }));
|
|
160
355
|
check();
|
|
161
|
-
await this.#options.store.
|
|
356
|
+
await this.#options.store.clearCredentialsIf(() => !this.#disposed && generation === this.#generation, undefined, undefined, this.#controller.signal, false, 'codeVerifier');
|
|
162
357
|
continue;
|
|
163
358
|
}
|
|
164
359
|
this.#client = client;
|
|
165
360
|
await this.#registerTools(client);
|
|
166
361
|
check();
|
|
167
|
-
await this.#readSite(client);
|
|
362
|
+
await this.#readSite(client, generation, this.#controller.signal);
|
|
168
363
|
check();
|
|
169
|
-
this.#
|
|
170
|
-
this.#
|
|
364
|
+
this.#setUrl(undefined);
|
|
365
|
+
this.#setStatus('ready');
|
|
171
366
|
return;
|
|
172
367
|
}
|
|
173
368
|
throw new Error('Atlassian authorization did not establish a connection');
|
|
@@ -221,16 +416,16 @@ export class AtlassianBridge {
|
|
|
221
416
|
throw error;
|
|
222
417
|
}
|
|
223
418
|
}
|
|
224
|
-
async #readSite(client) {
|
|
419
|
+
async #readSite(client, generation, signal) {
|
|
225
420
|
const name = this.rawNameMatching(/accessibleatlassianresources/i);
|
|
226
421
|
if (!name)
|
|
227
422
|
return;
|
|
228
423
|
try {
|
|
229
|
-
const result = await client.callTool({ name, arguments: {} }, undefined, { timeout: 20000 });
|
|
424
|
+
const result = await client.callTool({ name, arguments: {} }, undefined, { timeout: 20000, signal });
|
|
230
425
|
const items = JSON.parse(display(result.content));
|
|
231
426
|
const first = Array.isArray(items) ? items[0] : items;
|
|
232
427
|
if (first && typeof first === 'object' && typeof first['url'] === 'string') {
|
|
233
|
-
await this.#options.store.patch({ site: new URL(first['url']).host });
|
|
428
|
+
await this.#options.store.patch({ site: new URL(first['url']).host }, () => !this.#disposed && generation === this.#generation && !signal.aborted, undefined, undefined, signal);
|
|
234
429
|
}
|
|
235
430
|
}
|
|
236
431
|
catch { /* The connection can work without a site label. */ }
|
|
@@ -245,15 +440,18 @@ export class AtlassianBridge {
|
|
|
245
440
|
}
|
|
246
441
|
async disconnect() {
|
|
247
442
|
this.#generation++;
|
|
248
|
-
this.#
|
|
443
|
+
this.#controller.abort();
|
|
444
|
+
this.#controller = new AbortController();
|
|
445
|
+
this.#setStatus('idle');
|
|
249
446
|
this.#callback.cancelWait();
|
|
250
447
|
await this.#boot?.catch(() => undefined);
|
|
251
448
|
this.#callback.cancelWait();
|
|
252
449
|
await this.#work;
|
|
450
|
+
await Promise.allSettled([...this.#refreshes]);
|
|
253
451
|
await this.#closeClient();
|
|
254
452
|
this.#clearTools();
|
|
255
453
|
await this.#options.store.destroy();
|
|
256
|
-
this.#
|
|
454
|
+
this.#setUrl(undefined);
|
|
257
455
|
this.#error = undefined;
|
|
258
456
|
return this.snapshot();
|
|
259
457
|
}
|
|
@@ -262,11 +460,13 @@ export class AtlassianBridge {
|
|
|
262
460
|
return;
|
|
263
461
|
this.#disposed = true;
|
|
264
462
|
this.#generation++;
|
|
265
|
-
this.#
|
|
463
|
+
this.#controller.abort();
|
|
464
|
+
this.#setStatus('idle');
|
|
266
465
|
this.#callback.cancelWait();
|
|
267
466
|
await this.#boot?.catch(() => undefined);
|
|
268
467
|
this.#callback.cancelWait();
|
|
269
468
|
await this.#work;
|
|
469
|
+
await Promise.allSettled([...this.#refreshes]);
|
|
270
470
|
await this.#closeClient();
|
|
271
471
|
this.#clearTools();
|
|
272
472
|
await this.#callback.close();
|
package/lib/client.js
CHANGED
|
@@ -77,20 +77,57 @@ async function api(path, method = 'GET', body) {
|
|
|
77
77
|
throw new Error(typeof value['error'] === 'string' ? value['error'] : `HTTP ${String(response.status)}`);
|
|
78
78
|
return value;
|
|
79
79
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
80
|
+
// Settings and the board panel share one poller and one snapshot, so an idle
|
|
81
|
+
// workspace neither doubles the /status traffic nor re-renders unchanged data.
|
|
82
|
+
const snapshotState = { value: undefined, error: '' };
|
|
83
|
+
const snapshotListeners = new Set();
|
|
84
|
+
let snapshotTimer;
|
|
85
|
+
let snapshotInflight;
|
|
86
|
+
let snapshotSerialized = '';
|
|
87
|
+
async function refreshSnapshot() {
|
|
88
|
+
if (snapshotInflight)
|
|
89
|
+
return snapshotInflight;
|
|
90
|
+
snapshotInflight = (async () => {
|
|
91
|
+
let next;
|
|
84
92
|
try {
|
|
85
|
-
|
|
86
|
-
setError('');
|
|
93
|
+
next = { value: await api('/status'), error: '' };
|
|
87
94
|
}
|
|
88
95
|
catch (err) {
|
|
89
|
-
|
|
96
|
+
next = { value: snapshotState.value, error: err instanceof Error ? err.message : String(err) };
|
|
90
97
|
}
|
|
98
|
+
const serialized = JSON.stringify(next);
|
|
99
|
+
if (serialized === snapshotSerialized)
|
|
100
|
+
return;
|
|
101
|
+
snapshotSerialized = serialized;
|
|
102
|
+
snapshotState.value = next.value;
|
|
103
|
+
snapshotState.error = next.error;
|
|
104
|
+
for (const listener of [...snapshotListeners])
|
|
105
|
+
listener();
|
|
106
|
+
})().finally(() => { snapshotInflight = undefined; });
|
|
107
|
+
return snapshotInflight;
|
|
108
|
+
}
|
|
109
|
+
function subscribeSnapshot(listener) {
|
|
110
|
+
snapshotListeners.add(listener);
|
|
111
|
+
if (snapshotTimer === undefined) {
|
|
112
|
+
snapshotTimer = window.setInterval(() => { void refreshSnapshot(); }, 5000);
|
|
113
|
+
void refreshSnapshot();
|
|
114
|
+
}
|
|
115
|
+
return () => {
|
|
116
|
+
snapshotListeners.delete(listener);
|
|
117
|
+
if (!snapshotListeners.size && snapshotTimer !== undefined) {
|
|
118
|
+
window.clearInterval(snapshotTimer);
|
|
119
|
+
snapshotTimer = undefined;
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
function useSnapshot() {
|
|
124
|
+
const [state, setState] = React.useState({ value: snapshotState.value, error: snapshotState.error });
|
|
125
|
+
React.useEffect(() => {
|
|
126
|
+
const update = () => setState({ value: snapshotState.value, error: snapshotState.error });
|
|
127
|
+
update();
|
|
128
|
+
return subscribeSnapshot(update);
|
|
91
129
|
}, []);
|
|
92
|
-
|
|
93
|
-
return { value, error, refresh };
|
|
130
|
+
return { value: state.value, error: state.error, refresh: refreshSnapshot };
|
|
94
131
|
}
|
|
95
132
|
function icon(name) {
|
|
96
133
|
const paths = {
|
|
@@ -169,7 +206,7 @@ function AtlassianSettings() {
|
|
|
169
206
|
}
|
|
170
207
|
function promptFor(issues, template) {
|
|
171
208
|
return issues.map((item) => template
|
|
172
|
-
? template.replaceAll('{{key}}', item.key).replaceAll('{{summary}}', item.summary)
|
|
209
|
+
? template.replaceAll('{{key}}', () => item.key).replaceAll('{{summary}}', () => item.summary)
|
|
173
210
|
: `Work on Jira issue ${item.key}: ${item.summary}. Check the requirements and relevant code first, then report changes and verification. Do not change the Jira status automatically.`).join('\n\n');
|
|
174
211
|
}
|
|
175
212
|
function JiraBoardPanel() {
|
|
@@ -183,7 +220,15 @@ function JiraBoardPanel() {
|
|
|
183
220
|
const [detail, setDetail] = React.useState();
|
|
184
221
|
const [message, setMessage] = React.useState('');
|
|
185
222
|
const [loading, setLoading] = React.useState(false);
|
|
223
|
+
// A Confluence-only profile has no Jira tools; the board shows an empty state
|
|
224
|
+
// instead of reporting a missing tool as an error on every refresh.
|
|
225
|
+
const jiraConfigured = snapshot?.mode !== 'server' || !!snapshot?.server?.jiraUrl;
|
|
186
226
|
const refresh = React.useCallback(async (value) => {
|
|
227
|
+
if (!jiraConfigured) {
|
|
228
|
+
setBoard(undefined);
|
|
229
|
+
setMessage('');
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
187
232
|
setLoading(true);
|
|
188
233
|
try {
|
|
189
234
|
const result = await api(`/board?jql=${encodeURIComponent(value)}`);
|
|
@@ -197,7 +242,7 @@ function JiraBoardPanel() {
|
|
|
197
242
|
finally {
|
|
198
243
|
setLoading(false);
|
|
199
244
|
}
|
|
200
|
-
}, []);
|
|
245
|
+
}, [jiraConfigured]);
|
|
201
246
|
React.useEffect(() => { if (snapshot?.status === 'ready')
|
|
202
247
|
void refresh(snapshot.board.jql); }, [snapshot?.status, refresh]);
|
|
203
248
|
const issues = (board?.issues ?? []).filter((item) => (!project || item.projectKey === project) && `${item.key} ${item.summary} ${item.projectName ?? ''}`.toLowerCase().includes(query.toLowerCase()));
|
|
@@ -243,7 +288,7 @@ function JiraBoardPanel() {
|
|
|
243
288
|
event.preventDefault();
|
|
244
289
|
void inspect(item.key);
|
|
245
290
|
} } }, h('label', { className: 'dab-issue-key', onClick: (event) => event.stopPropagation() }, h('input', { type: 'checkbox', 'aria-label': `Select ${item.key}`, checked: selected.includes(item.key), onChange: (event) => setSelected(event.target.checked ? [...selected, item.key] : selected.filter((key) => key !== item.key)) }), item.key), h('div', { className: 'dab-issue-summary' }, item.summary), h('small', { className: 'dab-issue-meta' }, item.projectName ?? item.projectKey ?? ''))));
|
|
246
|
-
})) : h('div', { className: 'dab-empty' }, snapshot?.status
|
|
291
|
+
})) : h('div', { className: 'dab-empty' }, snapshot?.status !== 'ready' ? 'Connect Atlassian in Settings to see your Jira issues.' : jiraConfigured ? 'No issues match this view.' : 'No Jira service is configured. Add a Jira URL in Settings.'), board?.truncated ? h('p', { className: 'dab-message' }, `Showing up to ${String(board.limit)} issues. Narrow the query for more.`) : null, detail ? h('aside', { className: 'dab-detail', 'aria-label': 'Issue details' }, h('div', { className: 'dab-detail-head' }, h('span', { className: 'dab-eyebrow' }, 'Issue details'), h('button', { className: 'dab-button', onClick: () => setDetail(undefined) }, icon('close'), 'Close')), h('h3', { className: 'dab-title', style: { fontSize: 19, marginTop: 16 } }, detail.issue.key, ' ', detail.issue.summary), detail.issue.url ? h('p', { style: { marginTop: 8 } }, h('a', { className: 'dab-link', href: detail.issue.url, target: '_blank', rel: 'noreferrer' }, 'Open in Jira')) : null, h('pre', null, detail.description), h('div', { className: 'dab-row' }, ...detail.transitions.map((transition) => h('button', { key: transition.id, className: 'dab-button', onClick: () => { void api('/transition', 'POST', { key: detail.issue.key, transitionId: transition.id }).then(() => { setDetail(undefined); return refresh(jql); }).catch((error) => setMessage(error instanceof Error ? error.message : String(error))); } }, transition.toName || transition.name)))) : null);
|
|
247
292
|
}
|
|
248
293
|
function BoardPanelIcon() {
|
|
249
294
|
return h('svg', { viewBox: '0 0 24 24', width: 19, height: 19, fill: 'none', stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, h('rect', { x: 3, y: 4, width: 18, height: 16, rx: 3 }), h('path', { d: 'M9 4v16M15 4v16M5.8 8h.4M11.8 8h.4M17.8 8h.4' }));
|
package/lib/index.js
CHANGED
|
@@ -7,9 +7,12 @@ import { SessionStore, sessionFileFor } from './store.js';
|
|
|
7
7
|
export const name = 'atlassian';
|
|
8
8
|
export const inject = ['tools'];
|
|
9
9
|
export { Config };
|
|
10
|
+
function identityFor(settings) {
|
|
11
|
+
return settings.mode === 'server' ? `server:${settings.server.jiraUrl}\0${settings.server.confluenceUrl}` : settings.url;
|
|
12
|
+
}
|
|
10
13
|
export function apply(ctx, config) {
|
|
11
14
|
const scope = ctx;
|
|
12
|
-
const identity = config
|
|
15
|
+
const identity = identityFor(config);
|
|
13
16
|
const store = new SessionStore(sessionFileFor(config.serverName, identity, scope.profileContext?.patchPath));
|
|
14
17
|
const host = { register: (definition) => ctx.tools.register(definition), logger: ctx.logger };
|
|
15
18
|
const bridge = config.mode === 'server'
|
|
@@ -19,12 +22,16 @@ export function apply(ctx, config) {
|
|
|
19
22
|
const connection = {
|
|
20
23
|
snapshot: () => ({ ...config.server }),
|
|
21
24
|
update: async (input) => {
|
|
22
|
-
configureEndpoints(config, input);
|
|
25
|
+
const next = configureEndpoints(config, input);
|
|
23
26
|
const editor = scope.get('configEditor');
|
|
24
27
|
const entry = editor?.entries().find((candidate) => candidate.options.id === 'atlassian');
|
|
25
28
|
if (!editor || !entry)
|
|
26
29
|
throw new Error('DSH configuration editor is unavailable');
|
|
27
30
|
await editor.edit(entry, (current) => configureEndpoints(Config(current), input));
|
|
31
|
+
if (identityFor(next) !== identity) {
|
|
32
|
+
// The profile now points at a different endpoint; leave no credentials behind for the old one.
|
|
33
|
+
void store.destroy().catch((error) => ctx.logger.warn(`atlassian: ${String(error)}`));
|
|
34
|
+
}
|
|
28
35
|
},
|
|
29
36
|
};
|
|
30
37
|
ctx.effect(() => () => bridge.dispose(), 'atlassian:connection');
|