Skip to content

Commit 5b13b72

Browse files
committed
fix(composer): harden mention MCP indexing and Jira/Figma chip lifecycle
Stop indexing from project-local MCP configs, fix stdio/SSE session failure modes, and gate Jira sync on configured spaces. Keep Jira/Figma chips in sync with prompt references like threads.
1 parent baf522c commit 5b13b72

16 files changed

Lines changed: 775 additions & 132 deletions

‎apps/server/src/mention/MentionIndex.test.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { expect, it } from "@effect/vitest";
22
import { ProjectId } from "@t3tools/contracts";
3+
import * as Deferred from "effect/Deferred";
34
import * as Effect from "effect/Effect";
5+
import * as Fiber from "effect/Fiber";
46
import * as Layer from "effect/Layer";
57
import * as KeyValueStore from "effect/persistence/KeyValueStore";
68

@@ -21,6 +23,21 @@ const row = (
2123

2224
const testLayer = Layer.effect(MentionIndex, make).pipe(Layer.provide(KeyValueStore.layerMemory));
2325

26+
const oldScopeBlob = JSON.stringify({
27+
rows: [
28+
{
29+
providerId: "pull-request",
30+
itemKey: "org/repo#1",
31+
label: "#1",
32+
description: "old",
33+
url: "https://github.com/org/repo/pull/1",
34+
tokens: "1 #1 old",
35+
updatedAt: 1,
36+
},
37+
],
38+
meta: { syncedAt: 10, status: "ready" },
39+
});
40+
2441
it.effect("searches locally without needing a network round trip", () =>
2542
Effect.gen(function* () {
2643
const index = yield* MentionIndex;
@@ -91,3 +108,71 @@ it.effect("ranks an exact number above a substring title hit", () =>
91108
expect(result.hits.map((hit) => hit.label)).toEqual(["#42", "#420"]);
92109
}).pipe(Effect.provide(testLayer)),
93110
);
111+
112+
it.effect("loadScope retains a newer published scope over a concurrent stale disk load", () =>
113+
Effect.gen(function* () {
114+
const scopeKey = mentionIndexScopeKey("pull-request", projectId);
115+
const disk = new Map<string, string>([[`scope:${scopeKey}`, oldScopeBlob]]);
116+
const readStarted = yield* Deferred.make<void>();
117+
const allowRead = yield* Deferred.make<void>();
118+
let gateScopeReads = false;
119+
120+
const store = KeyValueStore.makeStringOnly({
121+
get: (key) =>
122+
Effect.gen(function* () {
123+
if (gateScopeReads && key === `scope:${scopeKey}`) {
124+
yield* Deferred.succeed(readStarted, undefined);
125+
yield* Deferred.await(allowRead);
126+
}
127+
return disk.get(key);
128+
}),
129+
set: (key, value) =>
130+
Effect.sync(() => {
131+
disk.set(key, value);
132+
}),
133+
remove: (key) =>
134+
Effect.sync(() => {
135+
disk.delete(key);
136+
}),
137+
clear: Effect.sync(() => {
138+
disk.clear();
139+
}),
140+
size: Effect.sync(() => disk.size),
141+
keys: Effect.sync(() => [...disk.keys()]),
142+
});
143+
144+
const index = yield* make.pipe(Effect.provideService(KeyValueStore.KeyValueStore, store));
145+
146+
gateScopeReads = true;
147+
const loading = yield* index
148+
.search({
149+
projectId,
150+
providers: ["pull-request"],
151+
query: "",
152+
limit: 10,
153+
})
154+
.pipe(Effect.forkChild);
155+
yield* Deferred.await(readStarted);
156+
157+
// Publish newer while the concurrent loadScope is still awaiting disk.
158+
gateScopeReads = false;
159+
yield* index.replaceScope(
160+
scopeKey,
161+
[
162+
row({
163+
itemKey: "org/repo#2",
164+
label: "#2",
165+
description: "new",
166+
tokens: "2 #2 new",
167+
updatedAt: 2,
168+
}),
169+
],
170+
{ syncedAt: 100, status: "ready" },
171+
);
172+
173+
yield* Deferred.succeed(allowRead, undefined);
174+
const result = yield* Fiber.join(loading);
175+
expect(result.hits.map((hit) => hit.label)).toEqual(["#2"]);
176+
expect(result.syncedAt).toBe(100);
177+
}),
178+
);

‎apps/server/src/mention/MentionIndex.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,12 +207,17 @@ export const make = Effect.gen(function* () {
207207
if (cached) return cached;
208208
const fromDisk = yield* readDisk(scopeKey);
209209
if (fromDisk) {
210-
yield* Ref.update(hot, (map) => {
210+
// Retain an already-published newer scope if another writer won the race.
211+
const published = yield* Ref.modify(hot, (map) => {
212+
const existing = map.get(scopeKey);
213+
if (existing !== undefined && existing.meta.syncedAt >= fromDisk.meta.syncedAt) {
214+
return [existing, map];
215+
}
211216
const next = new Map(map);
212217
next.set(scopeKey, fromDisk);
213-
return next;
218+
return [fromDisk, next];
214219
});
215-
return fromDisk;
220+
return published;
216221
}
217222
return {
218223
rows: [],

‎apps/server/src/mention/MentionIndexFigmaSyncer.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,14 @@ const make = Effect.gen(function* () {
8282
const payload = hasMetadata
8383
? yield* session.callTool("get_metadata", { fileKey })
8484
: yield* session.callTool("get_figma_data", { fileKey });
85+
if (mcpResultIsError(payload)) {
86+
return yield* Effect.fail(
87+
new MentionIndexMcpError(
88+
mcpResultErrorMessage(payload) ??
89+
`Figma MCP tool returned isError for file ${fileKey}`,
90+
),
91+
);
92+
}
8593
rows.push(...extractFigmaRows(fileKey, payload, now));
8694
if (rows.length >= MAX_ROWS) break;
8795
}
@@ -151,6 +159,24 @@ function stringOf(value: unknown): string | undefined {
151159
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
152160
}
153161

162+
export function mcpResultIsError(payload: unknown): boolean {
163+
const record = asRecord(payload);
164+
return record !== null && record.isError === true;
165+
}
166+
167+
function mcpResultErrorMessage(payload: unknown): string | undefined {
168+
const record = asRecord(payload);
169+
if (record === null) return undefined;
170+
const content = record.content;
171+
if (!Array.isArray(content)) return stringOf(record.message);
172+
const texts = content.flatMap((entry) => {
173+
const item = asRecord(entry);
174+
const text = item === null ? undefined : stringOf(item.text);
175+
return text === undefined ? [] : [text];
176+
});
177+
return texts[0] ?? stringOf(record.message);
178+
}
179+
154180
function textFromMcpResult(payload: unknown): unknown {
155181
const record = asRecord(payload);
156182
if (record === null) return payload;
@@ -171,6 +197,22 @@ function textFromMcpResult(payload: unknown): unknown {
171197
}
172198
}
173199

200+
/** Lightweight extract of name/id from page-like XML nodes in get_metadata text. */
201+
export function pagesFromFigmaXml(xml: string): ReadonlyArray<{ id: string; name: string }> {
202+
const pages: Array<{ id: string; name: string }> = [];
203+
const tagRe = /<(canvas|page)\b([^>]*)\/?>/giu;
204+
for (const match of xml.matchAll(tagRe)) {
205+
const attrs = match[2] ?? "";
206+
const id =
207+
attrs.match(/\bid\s*=\s*"([^"]+)"/iu)?.[1] ?? attrs.match(/\bid\s*=\s*'([^']+)'/iu)?.[1];
208+
const name =
209+
attrs.match(/\bname\s*=\s*"([^"]+)"/iu)?.[1] ?? attrs.match(/\bname\s*=\s*'([^']+)'/iu)?.[1];
210+
if (id === undefined || name === undefined) continue;
211+
pages.push({ id, name });
212+
}
213+
return pages;
214+
}
215+
174216
export function extractFigmaRows(
175217
fileKey: string,
176218
payload: unknown,
@@ -198,7 +240,7 @@ export function extractFigmaRows(
198240
},
199241
];
200242

201-
const pages =
243+
const structuredPages =
202244
(Array.isArray(record.pages)
203245
? record.pages
204246
: Array.isArray(asRecord(record.document)?.children)
@@ -207,6 +249,14 @@ export function extractFigmaRows(
207249
? (record.nodes as unknown[])
208250
: []) ?? [];
209251

252+
const xmlPages =
253+
structuredPages.length === 0 && typeof root === "string" ? pagesFromFigmaXml(root) : [];
254+
255+
const pages =
256+
structuredPages.length > 0
257+
? structuredPages
258+
: xmlPages.map((page) => ({ id: page.id, name: page.name }));
259+
210260
for (const page of pages.slice(0, 40)) {
211261
const pageRecord = asRecord(page);
212262
if (pageRecord === null) continue;

‎apps/server/src/mention/MentionIndexJiraSyncer.ts‎

Lines changed: 36 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,15 @@ const make = Effect.gen(function* () {
3636

3737
const settings = yield* mcp.readSettings;
3838
const jiraSettings = settings.jira;
39+
const spaces = jiraSettings?.spaces ?? [];
40+
if (spaces.length === 0) {
41+
yield* index.replaceScope(scopeKey, [], {
42+
status: "empty",
43+
detail: "No Jira spaces configured in mentionIndex.jira",
44+
});
45+
return;
46+
}
47+
3948
const project = yield* projects.getById(projectId).pipe(
4049
Effect.map(Option.getOrNull),
4150
Effect.orElseSucceed(() => null),
@@ -58,11 +67,7 @@ const make = Effect.gen(function* () {
5867
Effect.gen(function* () {
5968
const tools = yield* session.listTools();
6069
const names = new Set(tools.map((tool) => tool.name));
61-
const spaces = jiraSettings?.spaces ?? [];
62-
const jqlBase =
63-
spaces.length > 0
64-
? `project in (${spaces.map((space) => JSON.stringify(space)).join(", ")})`
65-
: "updated >= -90d";
70+
const jqlBase = `project in (${spaces.map((space) => JSON.stringify(space)).join(", ")})`;
6671
const jqlExtra = jiraSettings?.jqlExtra?.trim();
6772
const jql = `${jqlBase}${jqlExtra ? ` AND (${jqlExtra})` : ""} ORDER BY updated DESC`;
6873

@@ -75,16 +80,10 @@ const make = Effect.gen(function* () {
7580
} else if (names.has("search") || names.has("jira_search")) {
7681
const tool = names.has("search") ? "search" : "jira_search";
7782
payload = yield* session.callTool(tool, { jql, maxResults: MAX_ROWS });
78-
} else if (names.has("executeRead") && names.has("discover")) {
79-
yield* session.callTool("discover", {});
80-
payload = yield* session.callTool("executeRead", {
81-
query: jql,
82-
maxResults: MAX_ROWS,
83-
});
8483
} else {
8584
return yield* Effect.fail(
8685
new MentionIndexMcpError(
87-
"Jira MCP server has no searchable issue tool (expected searchJiraIssuesUsingJql)",
86+
"Jira MCP server has no searchable issue tool (expected searchJiraIssuesUsingJql, search, or jira_search)",
8887
),
8988
);
9089
}
@@ -118,11 +117,7 @@ const make = Effect.gen(function* () {
118117
const scopeKey = mentionIndexScopeKey("jira", projectId);
119118
const meta = yield* index.scopeMeta(scopeKey);
120119
const now = yield* Clock.currentTimeMillis;
121-
const stale =
122-
meta === null ||
123-
meta.status === "empty" ||
124-
meta.status === "error" ||
125-
now - meta.syncedAt > STALE_AFTER_MS;
120+
const stale = meta === null || meta.status === "error" || now - meta.syncedAt > STALE_AFTER_MS;
126121
if (!stale) return;
127122

128123
const key = String(projectId);
@@ -176,6 +171,29 @@ function textFromMcpResult(payload: unknown): unknown {
176171
}
177172
}
178173

174+
/** Prefer issue url/webUrl; derive browse URL from Jira REST `self`; never invent a host. */
175+
export function resolveJiraBrowseUrl(record: Record<string, unknown>, key: string): string {
176+
const direct =
177+
stringOf(record.url) ??
178+
stringOf(record.webUrl) ??
179+
stringOf(record.htmlUrl) ??
180+
stringOf(asRecord(record.fields)?.url);
181+
if (direct !== undefined) return direct;
182+
183+
const self = stringOf(record.self);
184+
if (self !== undefined) {
185+
try {
186+
const parsed = new URL(self);
187+
if (parsed.pathname.includes("/rest/")) {
188+
return `${parsed.origin}/browse/${key}`;
189+
}
190+
} catch {
191+
// fall through
192+
}
193+
}
194+
return "about:blank";
195+
}
196+
179197
export function extractJiraRows(payload: unknown, now: number): MentionIndexRow[] {
180198
const root = textFromMcpResult(payload);
181199
const issues =
@@ -199,11 +217,7 @@ export function extractJiraRows(payload: unknown, now: number): MentionIndexRow[
199217
const status = stringOf(asRecord(fields.status)?.name) ?? stringOf(record.status) ?? undefined;
200218
const projectKey =
201219
stringOf(asRecord(fields.project)?.key) ?? stringOf(record.projectKey) ?? key.split("-")[0];
202-
const url =
203-
stringOf(record.url) ??
204-
stringOf(record.webUrl) ??
205-
stringOf(asRecord(record.fields)?.url) ??
206-
(projectKey ? `https://atlassian.net/browse/${key}` : `https://atlassian.net/browse/${key}`);
220+
const url = resolveJiraBrowseUrl(record, key);
207221
rows.push({
208222
providerId: "jira",
209223
itemKey: key,

0 commit comments

Comments
 (0)