The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 08:30 UTC
feat(issues): link issues to threads and expose issue tools to agents (#19270)
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Julius Marminge committed
Nov 16, 2026 at 22:00 UTC
0597b9edcdbcd08c63a6085a7cbdb8cb7fc43387
48 files changed
+2047
-12
apps/server/src/issue/IssueService.test.ts
+23
@@ -142,6 +142,29 @@ function makeService(input: {
142
}
143
144
describe("IssueService", () => {
145
+ it.effect("places a project where its host keeps its issues", () =>
146
+ Effect.gen(function* () {
147
+ const azure = IssueTrackerKind.make("azure-devops");
148
+ const service = yield* makeService({
149
+ projects: [
150
+ project({
151
+ id: "p",
152
+ provider: "azure-devops",
153
+ host: "dev.azure.com",
154
+ repository: "acme/Web App/_git/web",
155
+ }),
156
+ ],
157
+ trackers: [fakeTracker({ kind: azure })],
158
+ });
159
+ expect(yield* service.projectScope("p" as ProjectId)).toEqual({
160
+ projectId: "p",
161
+ tracker: "azure-devops",
162
+ host: "dev.azure.com",
163
+ scope: "acme/Web App",
164
+ });
165
+ }),
166
+ );
167
+
168
it.effect("reads another repository on the same host but refuses to write to it", () =>
169
Effect.gen(function* () {
170
const writes: string[] = [];
apps/server/src/issue/IssueService.ts
+65
@@ -28,6 +28,7 @@ import {
28
type IssueTrackerSummary,
29
type IssueUpdateInput,
30
type OrchestrationProjectShell,
31
+ type ProjectId,
32
} from "@t3tools/contracts";
33
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
34
import {
@@ -140,6 +141,22 @@ export class IssueService extends Context.Service<
141
readonly update: (input: IssueUpdateInput) => Effect.Effect<void, IssueError>;
142
readonly setState: (input: IssueSetStateInput) => Effect.Effect<void, IssueError>;
143
readonly react: (input: IssueReactionInput) => Effect.Effect<void, IssueError>;
144
+ /**
145
+ * The reference behind an issue URL: served by the project whose binding is that host and
146
+ * scope, else read-only through any project on the same tracker and host. `preferredProjectId`
147
+ * wins among equals, so a thread's own project serves its own issues.
148
+ */
149
+ /** The tracker and container a project's own issues live in. */
150
+ readonly projectScope: (
151
+ projectId: ProjectId,
152
+ ) => Effect.Effect<IssueScopeRef & { readonly host: string }, IssueError>;
153
+ readonly resolveUrl: (
154
+ url: string,
155
+ preferredProjectId?: ProjectId,
156
+ ) => Effect.Effect<
157
+ IssueRef & { readonly host: string; readonly writable: boolean },
158
+ IssueError
159
+ >;
160
}
161
>()("t3/issue/IssueService") {}
162
@@ -552,6 +569,52 @@ const make = Effect.gen(function* () {
569
),
570
);
571
572
+ const projectScope: IssueService["Service"]["projectScope"] = Effect.fn(
573
+ "IssueService.projectScope",
574
+ )(function* (projectId) {
575
+ const { supported } = yield* listProjects({ projectId });
576
+ const [own] = supported;
577
+ if (own === undefined) {
578
+ return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
579
+ }
580
+ return { projectId, tracker: own.tracker, host: own.host, scope: own.scope };
581
+ });
582
+
583
+ const resolveUrl: IssueService["Service"]["resolveUrl"] = Effect.fn("IssueService.resolveUrl")(
584
+ function* (url, preferredProjectId) {
585
+ const parsed = sourceControlDefinitions.parseIssueUrl(url);
586
+ if (parsed === null) {
587
+ return yield* new IssueOperationError({
588
+ operation: "resolveUrl",
589
+ reason: "not-found",
590
+ detail: "This is not a recognised issue URL.",
591
+ });
592
+ }
593
+ const { definition, link } = parsed;
594
+ const { supported } = yield* listProjects({ host: link.host });
595
+ const onTracker = supported.filter(
596
+ (project) => project.tracker === IssueTrackerKind.make(definition.kind),
597
+ );
598
+ const preferFirst = (projects: ReadonlyArray<SupportedProject>) =>
599
+ projects.find((project) => project.project.id === preferredProjectId) ?? projects[0];
600
+ const own = preferFirst(
601
+ onTracker.filter((project) => project.scope.toLowerCase() === link.scope),
602
+ );
603
+ const lender = own ?? preferFirst(onTracker);
604
+ if (lender === undefined) {
605
+ return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
606
+ }
607
+ return {
608
+ projectId: lender.project.id,
609
+ tracker: lender.tracker,
610
+ host: lender.host,
611
+ scope: own === undefined ? link.scope : lender.scope,
612
+ key: link.key,
613
+ writable: own !== undefined,
614
+ };
615
+ },
616
+ );
617
+
618
return IssueService.of({
619
list,
620
detail: traced("detail", detail),
@@ -563,6 +626,8 @@ const make = Effect.gen(function* () {
626
update: interactive(traced("update", update)),
627
setState: interactive(traced("setState", setState)),
628
react: interactive(traced("react", react)),
629
+ projectScope,
630
+ resolveUrl,
631
});
632
});
633
apps/server/src/mcp/McpHttpServer.ts
+5
@@ -79,6 +79,8 @@ import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts";
79
import * as ToolSearchHandlers from "./toolkits/toolSearch/handlers.ts";
80
import { ToolSearchToolkit } from "./toolkits/toolSearch/tools.ts";
81
import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
82
+import * as IssuesHandlers from "./toolkits/issues/handlers.ts";
83
+import { IssuesToolkit } from "./toolkits/issues/tools.ts";
84
import * as DeviceHandlers from "./toolkits/device/handlers.ts";
85
import {
86
DeviceScreenshotTool,
@@ -1293,6 +1295,8 @@ export const layerPullRequestsToolkit = toolkitRegistration(
1295
PullRequestsHandlers.layer,
1296
).pipe(Layer.provide(PullRequestWatchService.layer));
1297
1298
+const layerIssuesToolkit = toolkitRegistration(IssuesToolkit, IssuesHandlers.layer);
1299
+
1300
const layerDeviceStandardToolkitRegistration = toolkitRegistration(
1301
DeviceStandardToolkit,
1302
DeviceHandlers.layerStandard,
@@ -1350,6 +1354,7 @@ export const layerTools = Layer.mergeAll(
1354
layerPreviewControlsRegistration,
1355
layerWorktreeToolkitRegistration,
1356
layerPullRequestsToolkit,
1357
+ layerIssuesToolkit,
1358
layerDeviceToolkit,
1359
layerHtmlToolkit,
1360
layerMessageToolkit,
apps/server/src/mcp/McpInvocationContext.ts
+1
@@ -21,6 +21,7 @@ const ALL_MCP_CAPABILITIES = [
21
"worktree",
22
"device",
23
"pull-requests",
24
+ "issues",
25
] as const;
26
export type McpCapability = (typeof ALL_MCP_CAPABILITIES)[number];
27
apps/server/src/mcp/McpSessionRegistry.test.ts
+4
-1
@@ -53,7 +53,7 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
53
const resolved = yield* registry.resolve(token);
54
expect(resolved?.thread.threadId).toBe(threadId);
55
expect(resolved?.capabilities).toEqual(
56
- new Set(["preview", "orchestration", "worktree", "pull-requests"]),
56
+ new Set(["preview", "orchestration", "worktree", "pull-requests", "issues"]),
57
);
58
59
yield* registry.revokeThread(threadId);
@@ -87,18 +87,21 @@ it.effect("always grants pull-requests and gates browser and device access indep
87
.pipe(Effect.map((scope) => [...(scope?.capabilities ?? [])].sort()));
88
89
expect(yield* capabilitiesOf(withPreview)).toEqual([
90
+ "issues",
91
"orchestration",
92
"preview",
93
"pull-requests",
94
"worktree",
95
]);
96
expect(yield* capabilitiesOf(withoutPreview)).toEqual([
97
+ "issues",
98
"orchestration",
99
"pull-requests",
100
"worktree",
101
]);
102
expect(yield* capabilitiesOf(withDevice)).toEqual([
103
"device",
104
+ "issues",
105
"orchestration",
106
"pull-requests",
107
"worktree",
apps/server/src/mcp/McpSessionRegistry.ts
+1
@@ -139,6 +139,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
139
"orchestration",
140
"worktree",
141
"pull-requests",
142
+ "issues",
143
...(request.capabilities ?? (browserToolsAvailable ? (["preview"] as const) : [])),
144
]),
145
issuedAt: issuedAlive.wallMs,
apps/server/src/mcp/toolkits/core.test.ts
+1
-1
@@ -697,7 +697,7 @@ const clientScope = (
697
thread: undefined,
698
client: { sessionId: "session-1", label: "Claude Code", access },
699
issuedAt: 0,
700
- capabilities: new Set(["orchestration", "worktree", "pull-requests"]),
700
+ capabilities: new Set(["orchestration", "worktree", "pull-requests", "issues"]),
701
});
702
703
it.effect("a client caller targets any thread within its ceiling and cannot act as a thread", () =>
apps/server/src/mcp/toolkits/issues/handlers.test.ts
new
+294
@@ -0,0 +1,294 @@
1
+import {
2
+ EnvironmentId,
3
+ IssueTrackerKind,
4
+ ProjectId,
5
+ ProviderInstanceId,
6
+ ThreadId,
7
+ type IssueDetail,
8
+ type OrchestrationProjectShell,
9
+ type ThreadIssueLink,
10
+ SourceControlProviderKind,
11
+} from "@t3tools/contracts";
12
+import { describe, expect, it } from "@effect/vitest";
13
+import * as Effect from "effect/Effect";
14
+import * as Layer from "effect/Layer";
15
+import * as Option from "effect/Option";
16
+import * as Ref from "effect/Ref";
17
+import * as Stream from "effect/Stream";
18
+import type { Tool } from "effect/ai";
19
+
20
+import * as IssueService from "../../../issue/IssueService.ts";
21
+import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
22
+import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.ts";
23
+import { v2PullRequestThread } from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
24
+import * as ProjectService from "../../../project/ProjectService.ts";
25
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
26
+import * as McpToolAccess from "../../McpToolAccess.ts";
27
+import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
28
+import * as IssuesHandlers from "./handlers.ts";
29
+import { IssuesToolkit } from "./tools.ts";
30
+
31
+const PROJECT_ID = ProjectId.make("project-1");
32
+const THREAD_ID = ThreadId.make("thread-1");
33
+const GITHUB = IssueTrackerKind.make("github");
34
+
35
+const invocation = (
36
+ capabilities: ReadonlyArray<McpInvocationContext.McpCapability>,
37
+): McpInvocationContext.McpInvocationScope => ({
38
+ environmentId: EnvironmentId.make("environment-1"),
39
+ requestNamespace: "provider-session-1",
40
+ thread: {
41
+ threadId: THREAD_ID,
42
+ providerSessionId: "provider-session-1",
43
+ providerInstanceId: ProviderInstanceId.make("codex"),
44
+ },
45
+ client: undefined,
46
+ capabilities: new Set(capabilities),
47
+ issuedAt: 1,
48
+});
49
+
50
+const project: OrchestrationProjectShell = {
51
+ id: PROJECT_ID,
52
+ title: "Project",
53
+ workspaceRoot: "/workspace/project",
54
+ defaultModelSelection: null,
55
+ scripts: [],
56
+ repositoryIdentity: {
57
+ canonicalKey: "github.com/t3tools/t3code",
58
+ locator: {
59
+ source: "git-remote",
60
+ remoteName: "origin",
61
+ remoteUrl: "git@github.com:T3Tools/T3Code.git",
62
+ },
63
+ provider: SourceControlProviderKind.make("github"),
64
+ displayName: "T3Tools/T3Code",
65
+ owner: "T3Tools",
66
+ name: "T3Code",
67
+ },
68
+ createdAt: "2026-08-01T00:00:00.000Z",
69
+ updatedAt: "2026-08-01T00:00:00.000Z",
70
+};
71
+
72
+function makeThread(issues: ReadonlyArray<ThreadIssueLink>) {
73
+ return {
74
+ ...v2PullRequestThread({
75
+ id: THREAD_ID,
76
+ projectId: PROJECT_ID,
77
+ title: "Thread",
78
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
79
+ runtimeMode: "full-access",
80
+ interactionMode: "default",
81
+ branch: null,
82
+ worktreePath: null,
83
+ pullRequests: [],
84
+ createdAt: "2026-08-01T00:00:00.000Z",
85
+ updatedAt: "2026-08-20T00:00:00.000Z",
86
+ archivedAt: null,
87
+ settledOverride: null,
88
+ settledAt: null,
89
+ latestUserMessageAt: "2026-08-20T00:00:00.000Z",
90
+ }),
91
+ issues,
92
+ };
93
+}
94
+
95
+const detail: IssueDetail = {
96
+ tracker: GITHUB,
97
+ host: "github.com",
98
+ scope: "t3tools/t3code",
99
+ key: "7",
100
+ displayKey: "#7",
101
+ title: "Seven",
102
+ url: "https://github.com/T3Tools/T3Code/issues/7",
103
+ author: null,
104
+ state: { category: "open", name: "open" },
105
+ createdAt: "2026-08-01T00:00:00.000Z",
106
+ updatedAt: "2026-08-02T00:00:00.000Z",
107
+ closedAt: null,
108
+ assignees: [],
109
+ labels: [],
110
+ commentCount: 0,
111
+ projectId: PROJECT_ID,
112
+ projectTitle: "Project",
113
+ writable: true,
114
+ capabilities: {
115
+ create: true,
116
+ edit: true,
117
+ comment: true,
118
+ labels: true,
119
+ assignees: true,
120
+ reactions: false,
121
+ templates: false,
122
+ linkedPullRequests: true,
123
+ events: true,
124
+ search: true,
125
+ states: [],
126
+ closeReasons: [],
127
+ },
128
+ viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
129
+ viewer: null,
130
+ body: "",
131
+ comments: [],
132
+ commentsCursor: null,
133
+ events: [],
134
+ linkedPullRequests: [],
135
+};
136
+
137
+const makeHarness = Effect.fn("makeIssuesToolkitHarness")(function* (
138
+ issues: ReadonlyArray<ThreadIssueLink> = [],
139
+) {
140
+ const links = yield* Ref.make<ReadonlyArray<ThreadIssueService.LinkThreadIssueInput>>([]);
141
+ const layerDependencies = Layer.mergeAll(
142
+ Layer.mock(ProjectService.ProjectService)({
143
+ getShell: (id) => Effect.succeed(id === PROJECT_ID ? Option.some(project) : Option.none()),
144
+ listShells: () => Effect.succeed([project]),
145
+ }),
146
+ Layer.mock(Orchestrator.OrchestratorV2)({
147
+ getThreadShell: (id) => Effect.succeed(id === THREAD_ID ? makeThread(issues) : null),
148
+ }),
149
+ Layer.mock(IssueService.IssueService)({
150
+ detail: () => Effect.succeed(detail),
151
+ projectScope: (projectId) =>
152
+ Effect.succeed({
153
+ projectId,
154
+ tracker: GITHUB,
155
+ host: "github.com",
156
+ scope: "t3tools/t3code",
157
+ }),
158
+ resolveUrl: (url) =>
159
+ Effect.succeed({
160
+ projectId: PROJECT_ID,
161
+ tracker: GITHUB,
162
+ host: "github.com",
163
+ scope: "t3tools/t3code",
164
+ key: url.split("/").at(-1)!,
165
+ writable: true,
166
+ }),
167
+ }),
168
+ Layer.mock(ThreadIssueService.ThreadIssueService)({
169
+ link: (input) =>
170
+ Ref.update(links, (recorded) => [...recorded, input]).pipe(
171
+ Effect.as({ alreadyLinked: false }),
172
+ ),
173
+ unlink: () => Effect.succeed({ wasLinked: true }),
174
+ }),
175
+ McpToolAccessTestkit.liveThreadsLayer,
176
+ );
177
+ const toolkit = yield* IssuesToolkit.pipe(
178
+ Effect.provide(
179
+ McpToolAccess.HandlersLayer.layer(IssuesHandlers.layer).pipe(
180
+ Layer.provide(layerDependencies),
181
+ ),
182
+ ),
183
+ );
184
+ const call = <Name extends keyof typeof IssuesToolkit.tools>(
185
+ name: Name,
186
+ params: Parameters<typeof toolkit.handle<Name>>[1],
187
+ capabilities: ReadonlyArray<McpInvocationContext.McpCapability> = ["issues"],
188
+ ) =>
189
+ toolkit.handle(name, params).pipe(
190
+ Stream.unwrap,
191
+ Stream.runCollect,
192
+ Effect.map(
193
+ (chunk) => chunk.at(-1)!.result as Tool.Success<(typeof IssuesToolkit.tools)[Name]>,
194
+ ),
195
+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)),
196
+ Effect.provide(layerDependencies),
197
+ );
198
+ return { links, call };
199
+});
200
+
201
+describe("issue toolkit handlers", () => {
202
+ it.effect("refuses a credential without the issues capability", () =>
203
+ Effect.gen(function* () {
204
+ const harness = yield* makeHarness();
205
+ const error = yield* harness
206
+ .call("list_thread_issues", {}, ["pull-requests"])
207
+ .pipe(Effect.flip);
208
+ expect(error).toMatchObject({ _tag: "McpCapabilityUnavailableError", capability: "issues" });
209
+ // Naming the project or the issue outright must not skip the check.
210
+ const refused = { _tag: "McpCapabilityUnavailableError", capability: "issues" };
211
+ expect(
212
+ yield* harness
213
+ .call("list_issues", { projectId: PROJECT_ID }, ["pull-requests"])
214
+ .pipe(Effect.flip),
215
+ ).toMatchObject(refused);
216
+ expect(
217
+ yield* harness
218
+ .call("read_issue", { projectId: PROJECT_ID, key: "7" }, ["pull-requests"])
219
+ .pipe(Effect.flip),
220
+ ).toMatchObject(refused);
221
+ expect(
222
+ yield* harness
223
+ .call("read_issue", { projectId: PROJECT_ID, url: detail.url }, ["pull-requests"])
224
+ .pipe(Effect.flip),
225
+ ).toMatchObject(refused);
226
+ }),
227
+ );
228
+
229
+ it.effect("links by URL with source agent on the token's thread", () =>
230
+ Effect.gen(function* () {
231
+ const harness = yield* makeHarness();
232
+ const result = yield* harness.call("link_issue", {
233
+ url: "https://github.com/T3Tools/T3Code/issues/7",
234
+ });
235
+ expect(result).toEqual({
236
+ projectId: PROJECT_ID,
237
+ tracker: "github",
238
+ host: "github.com",
239
+ scope: "t3tools/t3code",
240
+ key: "7",
241
+ url: "https://github.com/T3Tools/T3Code/issues/7",
242
+ alreadyLinked: false,
243
+ });
244
+ expect(yield* Ref.get(harness.links)).toEqual([
245
+ {
246
+ threadId: THREAD_ID,
247
+ ref: {
248
+ projectId: PROJECT_ID,
249
+ tracker: "github",
250
+ host: "github.com",
251
+ scope: "t3tools/t3code",
252
+ key: "7",
253
+ },
254
+ url: "https://github.com/T3Tools/T3Code/issues/7",
255
+ displayKey: detail.displayKey,
256
+ title: detail.title,
257
+ source: "agent",
258
+ },
259
+ ]);
260
+ }),
261
+ );
262
+
263
+ it.effect("links by key through the thread's project and reads the URL from the tracker", () =>
264
+ Effect.gen(function* () {
265
+ const harness = yield* makeHarness();
266
+ const result = yield* harness.call("link_issue", { key: "7" });
267
+ expect(result.url).toBe(detail.url);
268
+ expect((yield* Ref.get(harness.links))[0]?.url).toBe(detail.url);
269
+ }),
270
+ );
271
+
272
+ it.effect("lists linked issues from the thread shell as they were named when linked", () =>
273
+ Effect.gen(function* () {
274
+ const harness = yield* makeHarness([
275
+ {
276
+ tracker: GITHUB,
277
+ host: "github.com",
278
+ scope: "t3tools/t3code",
279
+ key: "7",
280
+ projectId: PROJECT_ID,
281
+ url: detail.url,
282
+ source: "manual",
283
+ linkedAt: "2026-08-10T00:00:00.000Z",
284
+ displayKey: "#7",
285
+ title: "Seven",
286
+ },
287
+ ]);
288
+ const result = yield* harness.call("list_thread_issues", {});
289
+ expect(result.issues).toMatchObject([{ key: "7", title: "Seven", displayKey: "#7" }]);
290
+ const unlinked = yield* harness.call("unlink_issue", { url: detail.url });
291
+ expect(unlinked.wasLinked).toBe(true);
292
+ }),
293
+ );
294
+});
apps/server/src/mcp/toolkits/issues/handlers.ts
new
+303
@@ -0,0 +1,303 @@
1
+import {
2
+ threadIssueKeysEqual,
3
+ type IssueDetail,
4
+ type IssueRef,
5
+ type OrchestrationV2ThreadShell,
6
+ type ProjectId,
7
+ type ThreadId,
8
+} from "@t3tools/contracts";
9
+import * as Cause from "effect/Cause";
10
+import * as Effect from "effect/Effect";
11
+import * as Option from "effect/Option";
12
+
13
+import * as IssueService from "../../../issue/IssueService.ts";
14
+import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
15
+import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.ts";
16
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
17
+import * as McpToolAccess from "../../McpToolAccess.ts";
18
+import {
19
+ IssueLinkFailedError,
20
+ IssueProjectNotFoundError,
21
+ IssueProjectRequiredError,
22
+ IssuesToolkit,
23
+ IssueTargetIncompleteError,
24
+ type IssueTargetInput,
25
+ IssueThreadNotFoundError,
26
+ IssueThreadRequiredError,
27
+ type ListThreadIssuesResult,
28
+} from "./tools.ts";
29
+
30
+/** A resolved reference, with the host the link stores and whether it may be written. */
31
+interface ResolvedTarget extends IssueRef {
32
+ readonly host: string;
33
+ readonly url: string | null;
34
+ readonly writable: boolean;
35
+}
36
+
37
+/** What the tools report from a thread shell; exported so the shape is testable without a layer. */
38
+function listThreadIssues(
39
+ thread: Pick<OrchestrationV2ThreadShell, "issues">,
40
+): ListThreadIssuesResult {
41
+ return {
42
+ issues: (thread.issues ?? []).map((link) => ({
43
+ projectId: link.projectId,
44
+ tracker: link.tracker,
45
+ host: link.host,
46
+ scope: link.scope,
47
+ key: link.key,
48
+ url: link.url,
49
+ source: link.source,
50
+ displayKey: link.displayKey,
51
+ title: link.title,
52
+ })),
53
+ };
54
+}
55
+
56
+const make = Effect.gen(function* () {
57
+ const engine = yield* Orchestrator.OrchestratorV2;
58
+ const issues = yield* IssueService.IssueService;
59
+ const threadIssues = yield* ThreadIssueService.ThreadIssueService;
60
+
61
+ /** The caller's own thread, read when a tool defaults to it. */
62
+ const callerThread = Effect.fn("IssuesToolkit.callerThread")(function* () {
63
+ const scope = yield* McpInvocationContext.requireMcpCapability("issues");
64
+ return scope.thread === undefined
65
+ ? undefined
66
+ : yield* engine.getThreadShell(scope.thread.threadId).pipe(
67
+ Effect.orElseSucceed(() => null),
68
+ Effect.map((shell) => shell ?? undefined),
69
+ );
70
+ });
71
+
72
+ const requireThread = Effect.fn("IssuesToolkit.requireThread")(function* (
73
+ requested: ThreadId | undefined,
74
+ ) {
75
+ const scope = yield* McpInvocationContext.requireMcpCapability("issues");
76
+ const threadId = requested ?? scope.thread?.threadId;
77
+ if (threadId === undefined) return yield* new IssueThreadRequiredError();
78
+ const thread = yield* engine.getThreadShell(threadId).pipe(
79
+ Effect.map(Option.fromNullishOr),
80
+ Effect.mapError((cause) => new IssueLinkFailedError({ cause })),
81
+ );
82
+ if (Option.isNone(thread) || thread.value.deletedAt !== null) {
83
+ return yield* new IssueThreadNotFoundError({ threadId });
84
+ }
85
+ return thread.value;
86
+ });
87
+
88
+ /** Where a key-only reference is read: the named project's tracker, or the caller's thread's. */
89
+ const requireProjectScope = Effect.fn("IssuesToolkit.requireProjectScope")(function* (
90
+ requested: ProjectId | undefined,
91
+ ) {
92
+ // A named project skips the caller's thread, so the capability is checked here too.
93
+ yield* McpInvocationContext.requireMcpCapability("issues");
94
+ const projectId = requested ?? (yield* callerThread())?.projectId;
95
+ if (projectId === undefined) return yield* new IssueProjectRequiredError();
96
+ return yield* issues
97
+ .projectScope(projectId)
98
+ .pipe(Effect.mapError(() => new IssueProjectNotFoundError({ projectId })));
99
+ });
100
+
101
+ /**
102
+ * Turns whichever shape the agent passed into one reference. A URL resolves through whichever
103
+ * project here is a checkout of its repository; a key is completed with the named project's
104
+ * binding, or the caller's thread's project.
105
+ */
106
+ const resolveTarget = Effect.fn("IssuesToolkit.resolveTarget")(function* (
107
+ input: IssueTargetInput,
108
+ ) {
109
+ yield* McpInvocationContext.requireMcpCapability("issues");
110
+ if (input.url !== undefined) {
111
+ const preferred = input.projectId ?? (yield* callerThread())?.projectId;
112
+ const resolved = yield* issues.resolveUrl(input.url, preferred);
113
+ return { ...resolved, url: input.url } satisfies ResolvedTarget;
114
+ }
115
+ if (input.key === undefined) return yield* new IssueTargetIncompleteError();
116
+ const scope = yield* requireProjectScope(input.projectId);
117
+ return {
118
+ ...scope,
119
+ key: input.key,
120
+ url: null,
121
+ writable: true,
122
+ } satisfies ResolvedTarget;
123
+ });
124
+
125
+ const identityOf = (target: ResolvedTarget, detail?: Pick<IssueDetail, "url">) => ({
126
+ projectId: target.projectId,
127
+ tracker: target.tracker,
128
+ host: target.host,
129
+ scope: target.scope,
130
+ key: target.key,
131
+ url: target.url ?? detail?.url ?? "",
132
+ });
133
+
134
+ const refOf = (target: ResolvedTarget): IssueRef & { readonly host: string } => ({
135
+ projectId: target.projectId,
136
+ tracker: target.tracker,
137
+ host: target.host,
138
+ scope: target.scope,
139
+ key: target.key,
140
+ });
141
+
142
+ /** A link needs the issue's URL, which a key-only reference does not carry; one read fills it. */
143
+ const linkFailure = <E>(cause: Cause.Cause<E>) =>
144
+ Cause.hasInterruptsOnly(cause)
145
+ ? Effect.failCause(cause as Cause.Cause<never>)
146
+ : Effect.fail(new IssueLinkFailedError({ cause }));
147
+
148
+ /** A tool that changes `threadId`, or the caller's own thread when it is omitted. */
149
+ const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
150
+ handle: (params: P) => Effect.Effect<A, E, R>,
151
+ ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
152
+
153
+ return {
154
+ list_issues: McpToolAccess.reads((input) =>
155
+ Effect.gen(function* () {
156
+ const { projectId } = yield* requireProjectScope(input.projectId);
157
+ const result = yield* issues.list({
158
+ projectId,
159
+ state: input.state ?? "open",
160
+ ...(input.query === undefined ? {} : { query: input.query }),
161
+ ...(input.limit === undefined ? {} : { limit: input.limit }),
162
+ ...(input.cursors === undefined ? {} : { cursors: input.cursors }),
163
+ });
164
+ return {
165
+ issues: result.entries.map((entry) => ({
166
+ projectId: entry.projectId,
167
+ tracker: entry.tracker,
168
+ host: entry.host,
169
+ scope: entry.scope,
170
+ key: entry.key,
171
+ url: entry.url,
172
+ displayKey: entry.displayKey,
173
+ title: entry.title,
174
+ state: entry.state,
175
+ author: entry.author?.login ?? null,
176
+ assignees: entry.assignees.map((actor) => actor.login),
177
+ labels: entry.labels.map((label) => label.name),
178
+ updatedAt: entry.updatedAt,
179
+ commentCount: entry.commentCount,
180
+ })),
181
+ nextCursors: result.nextCursors,
182
+ errors: result.errors.map((error) => ({
183
+ projectId: error.projectId,
184
+ message: error.message,
185
+ })),
186
+ };
187
+ }),
188
+ ),
189
+ read_issue: McpToolAccess.reads((input) =>
190
+ Effect.gen(function* () {
191
+ const target = yield* resolveTarget(input);
192
+ const detail = yield* issues.detail(refOf(target));
193
+ return {
194
+ ...identityOf(target, detail),
195
+ displayKey: detail.displayKey,
196
+ title: detail.title,
197
+ state: detail.state,
198
+ writable: detail.writable,
199
+ capabilities: detail.capabilities,
200
+ author: detail.author?.login ?? null,
201
+ assignees: detail.assignees.map((actor) => actor.login),
202
+ labels: detail.labels.map((label) => label.name),
203
+ createdAt: detail.createdAt,
204
+ updatedAt: detail.updatedAt,
205
+ closedAt: detail.closedAt,
206
+ body: detail.body,
207
+ comments: detail.comments.map((comment) => ({
208
+ id: comment.id,
209
+ author: comment.author?.login ?? null,
210
+ body: comment.body,
211
+ createdAt: comment.createdAt,
212
+ })),
213
+ commentsTruncated: detail.commentsCursor !== null,
214
+ linkedPullRequests: detail.linkedPullRequests.map((pullRequest) => ({
215
+ url: pullRequest.url,
216
+ title: pullRequest.title,
217
+ state: pullRequest.state,
218
+ closesIssue: pullRequest.closesIssue,
219
+ })),
220
+ };
221
+ }),
222
+ ),
223
+ create_issue: McpToolAccess.writesWithCapability((input) =>
224
+ Effect.gen(function* () {
225
+ const scope = yield* requireProjectScope(input.projectId);
226
+ const created = yield* issues.create({
227
+ ...scope,
228
+ title: input.title,
229
+ body: input.body ?? "",
230
+ labels: input.labels ?? [],
231
+ assignees: input.assignees ?? [],
232
+ });
233
+ return {
234
+ ...scope,
235
+ key: created.key,
236
+ url: created.url,
237
+ displayKey: created.displayKey,
238
+ };
239
+ }),
240
+ ),
241
+ comment_on_issue: McpToolAccess.writesWithCapability((input) =>
242
+ Effect.gen(function* () {
243
+ const target = yield* resolveTarget(input);
244
+ yield* issues.comment({ ...refOf(target), body: input.body });
245
+ return identityOf(target);
246
+ }),
247
+ ),
248
+ set_issue_state: McpToolAccess.writesWithCapability((input) =>
249
+ Effect.gen(function* () {
250
+ const target = yield* resolveTarget(input);
251
+ yield* issues.setState({
252
+ ...refOf(target),
253
+ state: input.state,
254
+ ...(input.closeReason === undefined ? {} : { closeReason: input.closeReason }),
255
+ });
256
+ return identityOf(target);
257
+ }),
258
+ ),
259
+ link_issue: writesThread((input) =>
260
+ Effect.gen(function* () {
261
+ const thread = yield* requireThread(input.threadId);
262
+ const target = yield* resolveTarget({
263
+ ...input,
264
+ projectId: input.projectId ?? thread.projectId,
265
+ });
266
+ // Reading the issue proves it exists and names it for the thread's row.
267
+ const detail = yield* issues.detail(refOf(target));
268
+ const url = target.url ?? detail.url;
269
+ const { alreadyLinked } = yield* threadIssues
270
+ .link({
271
+ threadId: thread.id,
272
+ ref: refOf(target),
273
+ url,
274
+ displayKey: detail.displayKey,
275
+ title: detail.title,
276
+ source: "agent",
277
+ })
278
+ .pipe(Effect.catchCause(linkFailure));
279
+ return { ...identityOf(target), url, alreadyLinked };
280
+ }),
281
+ ),
282
+ unlink_issue: writesThread((input) =>
283
+ Effect.gen(function* () {
284
+ const thread = yield* requireThread(input.threadId);
285
+ const target = yield* resolveTarget({
286
+ ...input,
287
+ projectId: input.projectId ?? thread.projectId,
288
+ });
289
+ const existing = (thread.issues ?? []).find((link) => threadIssueKeysEqual(link, target));
290
+ if (existing === undefined) return { ...identityOf(target), wasLinked: false };
291
+ const { wasLinked } = yield* threadIssues
292
+ .unlink({ threadId: thread.id, key: target })
293
+ .pipe(Effect.catchCause(linkFailure));
294
+ return { ...identityOf(target), url: existing.url, wasLinked };
295
+ }),
296
+ ),
297
+ list_thread_issues: McpToolAccess.reads((input) =>
298
+ requireThread(input.threadId).pipe(Effect.map(listThreadIssues)),
299
+ ),
300
+ } satisfies McpToolAccess.Handlers<typeof IssuesToolkit.tools>;
301
+});
302
+
303
+export const layer = McpToolAccess.toLayer(IssuesToolkit, make);
apps/server/src/mcp/toolkits/issues/tools.ts
new
+388
@@ -0,0 +1,388 @@
1
+import {
2
+ IssueCapabilities,
3
+ IssueListState,
4
+ IssueOperationError,
5
+ IssueState,
6
+ IssueTrackerKind,
7
+ IssueUnavailableError,
8
+ McpCapabilityUnavailableError,
9
+ OrchestratorMcpFailure,
10
+ ProjectId,
11
+ ThreadId,
12
+ ThreadIssueLinkSource,
13
+ TrimmedNonEmptyString,
14
+} from "@t3tools/contracts";
15
+import * as Schema from "effect/Schema";
16
+import * as Tool from "effect/ai/Tool";
17
+import * as Toolkit from "effect/ai/Toolkit";
18
+
19
+import * as IssueService from "../../../issue/IssueService.ts";
20
+import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
21
+import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.ts";
22
+import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
23
+import * as ProjectService from "../../../project/ProjectService.ts";
24
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
25
+
26
+const dependencies = [
27
+ McpInvocationContext.McpInvocationContext,
28
+ ThreadManagementService.ThreadManagementService,
29
+ Orchestrator.OrchestratorV2,
30
+ ProjectService.ProjectService,
31
+ IssueService.IssueService,
32
+ ThreadIssueService.ThreadIssueService,
33
+];
34
+
35
+/**
36
+ * Either the issue's URL, or its key within a project's tracker. A key alone is read through the
37
+ * project named, or the caller's own thread's project; a URL is read through whichever project
38
+ * here is a checkout of that repository, read-only when none is.
39
+ */
40
+export const IssueTargetInput = Schema.Struct({
41
+ url: Schema.optional(
42
+ TrimmedNonEmptyString.annotate({
43
+ description: "The issue's web URL. Preferred when you have it.",
44
+ }),
45
+ ),
46
+ key: Schema.optional(
47
+ TrimmedNonEmptyString.annotate({
48
+ description: "The issue's key in the project's tracker, such as its number.",
49
+ }),
50
+ ),
51
+ projectId: Schema.optional(
52
+ ProjectId.annotate({
53
+ description: "Project whose tracker holds key. Defaults to this thread's project.",
54
+ }),
55
+ ),
56
+});
57
+export type IssueTargetInput = typeof IssueTargetInput.Type;
58
+
59
+const ThreadTargetInput = Schema.Struct({
60
+ threadId: Schema.optional(
61
+ ThreadId.annotate({ description: "Thread to act on. Omit for this thread." }),
62
+ ),
63
+});
64
+
65
+export class IssueTargetIncompleteError extends Schema.TaggedError<IssueTargetIncompleteError>()(
66
+ "IssueTargetIncompleteError",
67
+ {},
68
+) {
69
+ override get message(): string {
70
+ return "Pass either url, or key (with projectId when not running inside a T3 thread).";
71
+ }
72
+}
73
+
74
+export class IssueProjectRequiredError extends Schema.TaggedError<IssueProjectRequiredError>()(
75
+ "IssueProjectRequiredError",
76
+ {},
77
+) {
78
+ override get message(): string {
79
+ return "Pass projectId: this MCP client is not running inside a T3 thread.";
80
+ }
81
+}
82
+
83
+export class IssueThreadRequiredError extends Schema.TaggedError<IssueThreadRequiredError>()(
84
+ "IssueThreadRequiredError",
85
+ {},
86
+) {
87
+ override get message(): string {
88
+ return "Pass threadId: this MCP client is not running inside a T3 thread.";
89
+ }
90
+}
91
+
92
+export class IssueThreadNotFoundError extends Schema.TaggedError<IssueThreadNotFoundError>()(
93
+ "IssueThreadNotFoundError",
94
+ { threadId: Schema.String },
95
+) {
96
+ override get message(): string {
97
+ return `Thread ${this.threadId} was not found.`;
98
+ }
99
+}
100
+
101
+export class IssueProjectNotFoundError extends Schema.TaggedError<IssueProjectNotFoundError>()(
102
+ "IssueProjectNotFoundError",
103
+ { projectId: Schema.String },
104
+) {
105
+ override get message(): string {
106
+ return `Project ${this.projectId} was not found or has no issue tracker.`;
107
+ }
108
+}
109
+
110
+export class IssueLinkFailedError extends Schema.TaggedError<IssueLinkFailedError>()(
111
+ "IssueLinkFailedError",
112
+ { cause: Schema.Defect() },
113
+) {
114
+ override get message(): string {
115
+ return "Could not change the issue link.";
116
+ }
117
+}
118
+
119
+export const IssueToolError = Schema.Union([
120
+ OrchestratorMcpFailure,
121
+ McpCapabilityUnavailableError,
122
+ IssueUnavailableError,
123
+ IssueOperationError,
124
+ IssueTargetIncompleteError,
125
+ IssueProjectRequiredError,
126
+ IssueThreadRequiredError,
127
+ IssueThreadNotFoundError,
128
+ IssueProjectNotFoundError,
129
+ IssueLinkFailedError,
130
+]);
131
+export type IssueToolError = typeof IssueToolError.Type;
132
+
133
+/** How a tool names an issue back: enough to pass to any other issue tool. */
134
+const IssueIdentity = {
135
+ projectId: ProjectId,
136
+ tracker: IssueTrackerKind,
137
+ host: Schema.String,
138
+ scope: Schema.String,
139
+ key: Schema.String,
140
+ url: Schema.String,
141
+};
142
+
143
+export const IssueEntry = Schema.Struct({
144
+ ...IssueIdentity,
145
+ displayKey: Schema.String,
146
+ title: Schema.String,
147
+ state: IssueState,
148
+ author: Schema.NullOr(Schema.String),
149
+ assignees: Schema.Array(Schema.String),
150
+ labels: Schema.Array(Schema.String),
151
+ updatedAt: Schema.String,
152
+ commentCount: Schema.Int,
153
+});
154
+export type IssueEntry = typeof IssueEntry.Type;
155
+
156
+export const ListIssuesResult = Schema.Struct({
157
+ issues: Schema.Array(IssueEntry),
158
+ /** Pass back as `cursors` to read the next slice of each scope that has one. */
159
+ nextCursors: Schema.Record(Schema.String, Schema.String),
160
+ errors: Schema.Array(Schema.Struct({ projectId: ProjectId, message: Schema.String })),
161
+});
162
+export type ListIssuesResult = typeof ListIssuesResult.Type;
163
+
164
+export const ReadIssueResult = Schema.Struct({
165
+ ...IssueIdentity,
166
+ displayKey: Schema.String,
167
+ title: Schema.String,
168
+ state: IssueState,
169
+ /** False for an issue outside every project's own scope: it can be read, not changed. */
170
+ writable: Schema.Boolean,
171
+ capabilities: IssueCapabilities,
172
+ author: Schema.NullOr(Schema.String),
173
+ assignees: Schema.Array(Schema.String),
174
+ labels: Schema.Array(Schema.String),
175
+ createdAt: Schema.String,
176
+ updatedAt: Schema.String,
177
+ closedAt: Schema.NullOr(Schema.String),
178
+ body: Schema.String,
179
+ comments: Schema.Array(
180
+ Schema.Struct({
181
+ id: Schema.String,
182
+ author: Schema.NullOr(Schema.String),
183
+ body: Schema.String,
184
+ createdAt: Schema.String,
185
+ }),
186
+ ),
187
+ /** Older comments exist beyond the page returned. */
188
+ commentsTruncated: Schema.Boolean,
189
+ linkedPullRequests: Schema.Array(
190
+ Schema.Struct({
191
+ url: Schema.String,
192
+ title: Schema.String,
193
+ state: Schema.String,
194
+ closesIssue: Schema.Boolean,
195
+ }),
196
+ ),
197
+});
198
+export type ReadIssueResult = typeof ReadIssueResult.Type;
199
+
200
+export const CreateIssueResult = Schema.Struct({
201
+ ...IssueIdentity,
202
+ displayKey: Schema.String,
203
+});
204
+export type CreateIssueResult = typeof CreateIssueResult.Type;
205
+
206
+export const IssueWriteResult = Schema.Struct({ ...IssueIdentity });
207
+
208
+export const ThreadIssueEntry = Schema.Struct({
209
+ ...IssueIdentity,
210
+ source: ThreadIssueLinkSource,
211
+ /** As the tracker named the issue when it was linked; `read_issue` has its current state. */
212
+ displayKey: Schema.String,
213
+ title: Schema.String,
214
+});
215
+export type ThreadIssueEntry = typeof ThreadIssueEntry.Type;
216
+
217
+export const LinkIssueResult = Schema.Struct({
218
+ ...IssueIdentity,
219
+ alreadyLinked: Schema.Boolean.annotate({
220
+ description: "True when the issue was linked to this thread before the call.",
221
+ }),
222
+});
223
+export type LinkIssueResult = typeof LinkIssueResult.Type;
224
+
225
+export const UnlinkIssueResult = Schema.Struct({
226
+ ...IssueIdentity,
227
+ wasLinked: Schema.Boolean.annotate({
228
+ description: "False when the issue was not linked to this thread to begin with.",
229
+ }),
230
+});
231
+export type UnlinkIssueResult = typeof UnlinkIssueResult.Type;
232
+
233
+export const ListThreadIssuesResult = Schema.Struct({
234
+ issues: Schema.Array(ThreadIssueEntry),
235
+});
236
+export type ListThreadIssuesResult = typeof ListThreadIssuesResult.Type;
237
+
238
+const ListIssuesTool = Tool.make("list_issues", {
239
+ description:
240
+ "List issues in a project's tracker, newest updated first. Pass the returned nextCursors as cursors for the next page.",
241
+ parameters: Schema.Struct({
242
+ projectId: Schema.optional(
243
+ ProjectId.annotate({ description: "Defaults to this thread's project." }),
244
+ ),
245
+ state: Schema.optional(IssueListState.annotate({ description: "Defaults to open." })),
246
+ query: Schema.optional(
247
+ TrimmedNonEmptyString.check(Schema.isMaxLength(200)).annotate({
248
+ description: "Free text the tracker matches itself.",
249
+ }),
250
+ ),
251
+ limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),
252
+ cursors: Schema.optional(Schema.Record(Schema.String, Schema.String)),
253
+ }),
254
+ success: ListIssuesResult,
255
+ failure: IssueToolError,
256
+ dependencies,
257
+})
258
+ .annotate(Tool.Title, "List issues")
259
+ .annotate(Tool.Readonly, true)
260
+ .annotate(Tool.Destructive, false)
261
+ .annotate(Tool.Idempotent, true)
262
+ .annotate(Tool.OpenWorld, true);
263
+
264
+const ReadIssueTool = Tool.make("read_issue", {
265
+ description:
266
+ "Read an issue: body, state, labels, assignees, recent comments and linked pull requests. Pass its url, or its key.",
267
+ parameters: IssueTargetInput,
268
+ success: ReadIssueResult,
269
+ failure: IssueToolError,
270
+ dependencies,
271
+})
272
+ .annotate(Tool.Title, "Read issue")
273
+ .annotate(Tool.Readonly, true)
274
+ .annotate(Tool.Destructive, false)
275
+ .annotate(Tool.Idempotent, true)
276
+ .annotate(Tool.OpenWorld, true);
277
+
278
+const CreateIssueTool = Tool.make("create_issue", {
279
+ description: "File an issue in a project's tracker.",
280
+ parameters: Schema.Struct({
281
+ projectId: Schema.optional(
282
+ ProjectId.annotate({ description: "Defaults to this thread's project." }),
283
+ ),
284
+ title: TrimmedNonEmptyString.check(Schema.isMaxLength(1024)),
285
+ body: Schema.optional(Schema.String.check(Schema.isMaxLength(65_536))),
286
+ labels: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(50))),
287
+ assignees: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(25))),
288
+ }),
289
+ success: CreateIssueResult,
290
+ failure: IssueToolError,
291
+ dependencies,
292
+})
293
+ .annotate(Tool.Title, "Create issue")
294
+ .annotate(Tool.Readonly, false)
295
+ .annotate(Tool.Destructive, false)
296
+ .annotate(Tool.Idempotent, false)
297
+ .annotate(Tool.OpenWorld, true);
298
+
299
+const CommentOnIssueTool = Tool.make("comment_on_issue", {
300
+ description: "Post a comment on an issue.",
301
+ parameters: Schema.Struct({
302
+ ...IssueTargetInput.fields,
303
+ body: Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)),
304
+ }),
305
+ success: IssueWriteResult,
306
+ failure: IssueToolError,
307
+ dependencies,
308
+})
309
+ .annotate(Tool.Title, "Comment on issue")
310
+ .annotate(Tool.Readonly, false)
311
+ .annotate(Tool.Destructive, false)
312
+ .annotate(Tool.Idempotent, false)
313
+ .annotate(Tool.OpenWorld, true);
314
+
315
+const SetIssueStateTool = Tool.make("set_issue_state", {
316
+ description:
317
+ "Move an issue to a state its tracker offers. read_issue lists them under capabilities.states.",
318
+ parameters: Schema.Struct({
319
+ ...IssueTargetInput.fields,
320
+ state: TrimmedNonEmptyString.annotate({
321
+ description: "A state name from capabilities.states.",
322
+ }),
323
+ closeReason: Schema.optional(
324
+ TrimmedNonEmptyString.annotate({
325
+ description: "From capabilities.closeReasons, for a closing state.",
326
+ }),
327
+ ),
328
+ }),
329
+ success: IssueWriteResult,
330
+ failure: IssueToolError,
331
+ dependencies,
332
+})
333
+ .annotate(Tool.Title, "Set issue state")
334
+ .annotate(Tool.Readonly, false)
335
+ .annotate(Tool.Destructive, false)
336
+ .annotate(Tool.Idempotent, true)
337
+ .annotate(Tool.OpenWorld, true);
338
+
339
+const LinkIssueTool = Tool.make("link_issue", {
340
+ description:
341
+ "Link an issue to a thread so T3 Code shows it beside the thread. Link every issue you work on or file.",
342
+ parameters: Schema.Struct({ ...IssueTargetInput.fields, ...ThreadTargetInput.fields }),
343
+ success: LinkIssueResult,
344
+ failure: IssueToolError,
345
+ dependencies,
346
+})
347
+ .annotate(Tool.Title, "Link issue to thread")
348
+ .annotate(Tool.Readonly, false)
349
+ .annotate(Tool.Destructive, false)
350
+ .annotate(Tool.Idempotent, true)
351
+ .annotate(Tool.OpenWorld, false);
352
+
353
+const UnlinkIssueTool = Tool.make("unlink_issue", {
354
+ description: "Remove an issue link from a thread. The issue itself is not changed.",
355
+ parameters: Schema.Struct({ ...IssueTargetInput.fields, ...ThreadTargetInput.fields }),
356
+ success: UnlinkIssueResult,
357
+ failure: IssueToolError,
358
+ dependencies,
359
+})
360
+ .annotate(Tool.Title, "Unlink issue from thread")
361
+ .annotate(Tool.Readonly, false)
362
+ .annotate(Tool.Destructive, true)
363
+ .annotate(Tool.Idempotent, true)
364
+ .annotate(Tool.OpenWorld, false);
365
+
366
+const ListThreadIssuesTool = Tool.make("list_thread_issues", {
367
+ description: "List the issues linked to a thread.",
368
+ parameters: ThreadTargetInput,
369
+ success: ListThreadIssuesResult,
370
+ failure: IssueToolError,
371
+ dependencies,
372
+})
373
+ .annotate(Tool.Title, "List thread issues")
374
+ .annotate(Tool.Readonly, true)
375
+ .annotate(Tool.Destructive, false)
376
+ .annotate(Tool.Idempotent, true)
377
+ .annotate(Tool.OpenWorld, false);
378
+
379
+export const IssuesToolkit = Toolkit.make(
380
+ ListIssuesTool,
381
+ ReadIssueTool,
382
+ CreateIssueTool,
383
+ CommentOnIssueTool,
384
+ SetIssueStateTool,
385
+ LinkIssueTool,
386
+ UnlinkIssueTool,
387
+ ListThreadIssuesTool,
388
+);
apps/server/src/orchestration-v2/Orchestrator.ts
+39
@@ -13,6 +13,7 @@ import {
13
runRanAfter,
14
usageLimitBlockedRun,
15
} from "@t3tools/shared/orchestrationV2ThreadError";
16
+import { threadIssueKeysEqual } from "@t3tools/contracts";
17
import { canonicalizeGitCafePullRequestUrl } from "@t3tools/source-control-definitions/registry";
18
import { threadPullRequestsOf } from "../sourceControl/threadPullRequests.ts";
19
import {
@@ -646,6 +647,8 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
647
case "thread.pull-request.link":
648
case "thread.pull-request.unlink":
649
case "thread.pull-request-link.sync":
650
+ case "thread.issue.link":
651
+ case "thread.issue.unlink":
652
case "thread.pull-request.watch":
653
case "thread.pull-request-watch.sync":
654
case "thread.pull-request-watch.checks-reopen":
@@ -4084,6 +4087,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4087
| "thread.pull-request.link"
4088
| "thread.pull-request.unlink"
4089
| "thread.pull-request-link.sync"
4090
+ | "thread.issue.link"
4091
+ | "thread.issue.unlink"
4092
| "thread.pull-request.watch"
4093
| "thread.pull-request-watch.sync"
4094
| "thread.pull-request-watch.checks-reopen"
@@ -4963,6 +4968,35 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4968
updatedAt: command.type === "thread.pull-request-link.sync" ? thread.updatedAt : now,
4969
};
4970
}
4971
+ case "thread.issue.link":
4972
+ case "thread.issue.unlink": {
4973
+ const links = thread.issues ?? [];
4974
+ const existing = links.find((link) => threadIssueKeysEqual(link, command));
4975
+ if (command.type === "thread.issue.unlink") {
4976
+ if (!existing) return thread;
4977
+ return { ...thread, issues: links.filter((link) => link !== existing), updatedAt: now };
4978
+ }
4979
+ if (existing) return thread;
4980
+ return {
4981
+ ...thread,
4982
+ issues: [
4983
+ ...links,
4984
+ {
4985
+ tracker: command.tracker,
4986
+ host: command.host.trim().toLowerCase(),
4987
+ scope: command.scope.trim(),
4988
+ key: command.key.trim(),
4989
+ projectId: command.projectId,
4990
+ url: command.url,
4991
+ displayKey: command.displayKey,
4992
+ title: command.title,
4993
+ source: command.source,
4994
+ linkedAt: DateTime.formatIso(now),
4995
+ },
4996
+ ],
4997
+ updatedAt: now,
4998
+ };
4999
+ }
5000
case "thread.pull-request-watch.checks-reopen": {
5001
const linked = threadPullRequestsOf(thread);
5002
if (!linked.some((link) => link.watch?.checksPending !== undefined)) return thread;
@@ -5203,6 +5237,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5237
case "thread.pull-request.watch":
5238
case "thread.pull-request.sync":
5239
return "thread.pull-request-synced" as const;
5240
+ case "thread.issue.link":
5241
+ case "thread.issue.unlink":
5242
+ return "thread.issue-synced" as const;
5243
case "thread.runtime-mode.set":
5244
return "thread.runtime-mode-updated" as const;
5245
case "thread.interaction-mode.set":
@@ -15018,6 +15055,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15055
case "thread.pull-request.link":
15056
case "thread.pull-request.unlink":
15057
case "thread.pull-request-link.sync":
15058
+ case "thread.issue.link":
15059
+ case "thread.issue.unlink":
15060
case "thread.pull-request.watch":
15061
case "thread.pull-request.sync":
15062
case "thread.title.regeneration.complete":
apps/server/src/orchestration-v2/ProjectionStore.ts
+5
@@ -981,6 +981,7 @@ export function applyToProjection(
981
case "thread.active-reordered":
982
case "thread.tags-updated":
983
case "thread.pull-request-synced":
984
+ case "thread.issue-synced":
985
return {
986
...base,
987
thread: event.payload,
@@ -1836,6 +1837,7 @@ export function threadShellFromProjection(
1837
...(projection.thread.branchPullRequest === undefined
1838
? {}
1839
: { branchPullRequest: projection.thread.branchPullRequest }),
1840
+ ...(projection.thread.issues === undefined ? {} : { issues: projection.thread.issues }),
1841
...(projection.thread.activeOrderKey === undefined
1842
? {}
1843
: { activeOrderKey: projection.thread.activeOrderKey }),
@@ -2149,6 +2151,7 @@ function shellFromState(input: {
2151
...(input.state.thread.branchPullRequest === undefined
2152
? {}
2153
: { branchPullRequest: input.state.thread.branchPullRequest }),
2154
+ ...(input.state.thread.issues === undefined ? {} : { issues: input.state.thread.issues }),
2155
...(input.state.thread.activeOrderKey === undefined
2156
? {}
2157
: { activeOrderKey: input.state.thread.activeOrderKey }),
@@ -2381,6 +2384,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2384
case "thread.marked-unread":
2385
case "thread.metadata-updated":
2386
case "thread.pull-request-synced":
2387
+ case "thread.issue-synced":
2388
case "thread.runtime-mode-updated":
2389
case "thread.interaction-mode-updated":
2390
case "thread.model-selection-updated":
@@ -3221,6 +3225,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
3225
event.type !== "thread.marked-unread" &&
3226
event.type !== "thread.metadata-updated" &&
3227
event.type !== "thread.pull-request-synced" &&
3228
+ event.type !== "thread.issue-synced" &&
3229
event.type !== "thread.pull-request-link-updated" &&
3230
event.type !== "thread.runtime-mode-updated" &&
3231
event.type !== "thread.interaction-mode-updated" &&
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+2
-2
@@ -2549,7 +2549,7 @@ it.effect(
2549
assert.equal(resolved?.thread.threadId, threadId);
2550
assert.deepEqual(
2551
resolved?.capabilities,
2552
- new Set(["preview", "orchestration", "worktree", "pull-requests"]),
2552
+ new Set(["preview", "orchestration", "worktree", "pull-requests", "issues"]),
2553
);
2554
2555
assert.isFalse(yield* captured!.hasPendingWake!);
@@ -2661,7 +2661,7 @@ it.effect(
2661
const resolved = yield* registry.resolve(token!);
2662
assert.deepEqual(
2663
resolved?.capabilities,
2664
- new Set(["orchestration", "worktree", "pull-requests"]),
2664
+ new Set(["orchestration", "worktree", "pull-requests", "issues"]),
2665
);
2666
2667
yield* manager.close(providerSessionId);
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+1
-1
@@ -567,7 +567,7 @@ export const layerWithOptions = (
567
yield* agentAccessSettings(threadId);
568
const capabilities = new Set<
569
import("../mcp/McpInvocationContext.ts").McpCapability
570
- >(["orchestration", "worktree", "pull-requests"]);
570
+ >(["orchestration", "worktree", "pull-requests", "issues"]);
571
if (browserToolsAvailable) capabilities.add("preview");
572
if (deviceToolsAvailable) capabilities.add("device");
573
const subagent = yield* projectionStore.getThread(threadId).pipe(
apps/server/src/orchestration-v2/ThreadIssueService.test.ts
new
+47
@@ -0,0 +1,47 @@
1
+import { IssueTrackerKind, ThreadId } from "@t3tools/contracts";
2
+import { describe, expect, it } from "@effect/vitest";
3
+import * as SecureRandom from "effect/crypto/SecureRandom";
4
+import * as Effect from "effect/Effect";
5
+import * as Layer from "effect/Layer";
6
+
7
+import * as Orchestrator from "./Orchestrator.ts";
8
+import * as ThreadIssueService from "./ThreadIssueService.ts";
9
+
10
+const THREAD_ID = ThreadId.make("thread-1");
11
+
12
+describe("ThreadIssueService", () => {
13
+ it.effect("fails an unlink whose thread cannot be read instead of reporting it unlinked", () =>
14
+ Effect.gen(function* () {
15
+ const service = yield* ThreadIssueService.ThreadIssueService;
16
+ const error = yield* service
17
+ .unlink({
18
+ threadId: THREAD_ID,
19
+ key: {
20
+ tracker: IssueTrackerKind.make("github"),
21
+ host: "github.com",
22
+ scope: "t3tools/t3code",
23
+ key: "7",
24
+ },
25
+ })
26
+ .pipe(Effect.flip);
27
+ expect(error).toMatchObject({ _tag: "OrchestratorProjectionError", threadId: THREAD_ID });
28
+ }).pipe(
29
+ Effect.provide(
30
+ ThreadIssueService.layer.pipe(
31
+ Layer.provide(
32
+ Layer.mergeAll(
33
+ Layer.mock(Orchestrator.OrchestratorV2)({
34
+ getThreadShell: (threadId) =>
35
+ Effect.fail(new Orchestrator.OrchestratorProjectionError({ threadId })),
36
+ }),
37
+ Layer.succeed(
38
+ SecureRandom.SecureRandom,
39
+ SecureRandom.make((size) => new Uint8Array(size).fill(7)),
40
+ ),
41
+ ),
42
+ ),
43
+ ),
44
+ ),
45
+ ),
46
+ );
47
+});
apps/server/src/orchestration-v2/ThreadIssueService.ts
new
+109
@@ -0,0 +1,109 @@
1
+/**
2
+ * Issues linked to threads: the link and unlink commands the server's own surfaces (MCP) go
3
+ * through. A link records how the tracker named the issue when it was made; nothing refreshes
4
+ * it, and opening the issue reads its live state.
5
+ *
6
+ * @module orchestration-v2/ThreadIssueService
7
+ */
8
+import {
9
+ CommandId,
10
+ threadIssueKeysEqual,
11
+ type IssueRef,
12
+ type ThreadId,
13
+ type ThreadIssueKey,
14
+ type ThreadIssueLinkSource,
15
+} from "@t3tools/contracts";
16
+import * as Context from "effect/Context";
17
+import * as SecureRandom from "effect/crypto/SecureRandom";
18
+import * as Effect from "effect/Effect";
19
+import * as Layer from "effect/Layer";
20
+
21
+import * as Orchestrator from "./Orchestrator.ts";
22
+
23
+export interface LinkThreadIssueInput {
24
+ readonly threadId: ThreadId;
25
+ readonly ref: IssueRef & { readonly host: string };
26
+ readonly url: string;
27
+ readonly displayKey: string;
28
+ readonly title: string;
29
+ readonly source: ThreadIssueLinkSource;
30
+}
31
+
32
+export interface UnlinkThreadIssueInput {
33
+ readonly threadId: ThreadId;
34
+ readonly key: ThreadIssueKey;
35
+}
36
+
37
+export class ThreadIssueService extends Context.Service<
38
+ ThreadIssueService,
39
+ {
40
+ /** Linking a linked issue is a no-op. */
41
+ readonly link: (
42
+ input: LinkThreadIssueInput,
43
+ ) => Effect.Effect<{ readonly alreadyLinked: boolean }, Orchestrator.OrchestratorV2Error>;
44
+ readonly unlink: (
45
+ input: UnlinkThreadIssueInput,
46
+ ) => Effect.Effect<{ readonly wasLinked: boolean }, Orchestrator.OrchestratorV2Error>;
47
+ }
48
+>()("t3/orchestration-v2/ThreadIssueService") {}
49
+
50
+const make = Effect.gen(function* () {
51
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
52
+ const random = yield* SecureRandom.SecureRandom;
53
+
54
+ const commandId = (tag: string, threadId: ThreadId) =>
55
+ random.uuidV4().pipe(
56
+ Effect.orDie,
57
+ Effect.map((uuid) => CommandId.make(`server:thread-issue-${tag}:${threadId}:${uuid}`)),
58
+ );
59
+
60
+ const isLinked = (threadId: ThreadId, key: ThreadIssueKey) =>
61
+ orchestrator
62
+ .getThreadShell(threadId)
63
+ .pipe(
64
+ Effect.map(
65
+ (thread) => thread?.issues?.some((link) => threadIssueKeysEqual(link, key)) === true,
66
+ ),
67
+ );
68
+
69
+ const link: ThreadIssueService["Service"]["link"] = Effect.fn("ThreadIssueService.link")(
70
+ function* (input) {
71
+ if (yield* isLinked(input.threadId, input.ref)) return { alreadyLinked: true };
72
+ yield* orchestrator.dispatch({
73
+ type: "thread.issue.link",
74
+ commandId: yield* commandId("link", input.threadId),
75
+ threadId: input.threadId,
76
+ tracker: input.ref.tracker,
77
+ host: input.ref.host,
78
+ scope: input.ref.scope,
79
+ key: input.ref.key,
80
+ projectId: input.ref.projectId,
81
+ url: input.url,
82
+ displayKey: input.displayKey,
83
+ title: input.title,
84
+ source: input.source,
85
+ });
86
+ return { alreadyLinked: false };
87
+ },
88
+ );
89
+
90
+ const unlink: ThreadIssueService["Service"]["unlink"] = Effect.fn("ThreadIssueService.unlink")(
91
+ function* (input) {
92
+ if (!(yield* isLinked(input.threadId, input.key))) return { wasLinked: false };
93
+ yield* orchestrator.dispatch({
94
+ type: "thread.issue.unlink",
95
+ commandId: yield* commandId("unlink", input.threadId),
96
+ threadId: input.threadId,
97
+ tracker: input.key.tracker,
98
+ host: input.key.host,
99
+ scope: input.key.scope,
100
+ key: input.key.key,
101
+ });
102
+ return { wasLinked: true };
103
+ },
104
+ );
105
+
106
+ return ThreadIssueService.of({ link, unlink });
107
+});
108
+
109
+export const layer = Layer.effect(ThreadIssueService, make);
apps/server/src/orchestration-v2/ThreadSettlementService.ts
+1
@@ -756,6 +756,7 @@ export const make = Effect.gen(function* () {
756
return enqueueFullSweep();
757
case "thread.pull-request-link-updated":
758
case "thread.pull-request-synced":
759
+ case "thread.issue-synced":
760
case "provider-session.detached":
761
case "run.background-work-cancelled":
762
return enqueueThread(event.threadId);
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+84
@@ -16,6 +16,7 @@ import {
16
ContextTransferId,
17
EnvironmentId,
18
EventId,
19
+ IssueTrackerKind,
20
MessageId,
21
NodeId,
22
RuntimeRequestId,
@@ -4103,6 +4104,89 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
4104
}),
4105
);
4106
4107
+ it.effect("links an issue, syncs its snapshot, and unlinks it", () =>
4108
+ Effect.gen(function* () {
4109
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
4110
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
4111
+ const threadId = ThreadId.make("runtime-issue-links");
4112
+ const projectId = ProjectId.make("issue-link-project");
4113
+ yield* orchestrator.dispatch({
4114
+ type: "thread.create",
4115
+ createdBy: "user",
4116
+ creationSource: "web",
4117
+ commandId: CommandId.make("issue-link-create"),
4118
+ threadId,
4119
+ projectId,
4120
+ title: "Issue links",
4121
+ modelSelection,
4122
+ runtimeMode: "full-access",
4123
+ interactionMode: "default",
4124
+ branch: null,
4125
+ worktreePath: null,
4126
+ });
4127
+ const key = {
4128
+ tracker: IssueTrackerKind.make("github"),
4129
+ host: "GitHub.com",
4130
+ scope: "Pingdotgg/T3code",
4131
+ key: "42",
4132
+ };
4133
+ yield* orchestrator.dispatch({
4134
+ type: "thread.issue.link",
4135
+ commandId: CommandId.make("issue-link-1"),
4136
+ threadId,
4137
+ ...key,
4138
+ projectId,
4139
+ url: "https://github.com/pingdotgg/t3code/issues/42",
4140
+ displayKey: "#42",
4141
+ title: "Issue links",
4142
+ source: "manual",
4143
+ });
4144
+ // A second link of the same issue, spelled differently, is a no-op.
4145
+ yield* orchestrator.dispatch({
4146
+ type: "thread.issue.link",
4147
+ commandId: CommandId.make("issue-link-2"),
4148
+ threadId,
4149
+ ...key,
4150
+ host: "github.com",
4151
+ scope: "pingdotgg/t3code",
4152
+ projectId,
4153
+ url: "https://github.com/pingdotgg/t3code/issues/42",
4154
+ displayKey: "#42",
4155
+ title: "Issue links, renamed",
4156
+ source: "agent",
4157
+ });
4158
+ yield* worker.drain();
4159
+ const linked = yield* orchestrator.getThreadShell(threadId);
4160
+ assert.deepEqual(
4161
+ linked?.issues?.map(({ host, scope, key, source, title }) => ({
4162
+ host,
4163
+ scope,
4164
+ key,
4165
+ source,
4166
+ title,
4167
+ })),
4168
+ [
4169
+ {
4170
+ host: "github.com",
4171
+ scope: "Pingdotgg/T3code",
4172
+ key: "42",
4173
+ source: "manual",
4174
+ title: "Issue links",
4175
+ },
4176
+ ],
4177
+ );
4178
+ yield* orchestrator.dispatch({
4179
+ type: "thread.issue.unlink",
4180
+ commandId: CommandId.make("issue-unlink"),
4181
+ threadId,
4182
+ ...key,
4183
+ });
4184
+ yield* worker.drain();
4185
+ assert.deepEqual((yield* orchestrator.getThreadShell(threadId))?.issues, []);
4186
+ assert.deepEqual((yield* orchestrator.getThreadProjection(threadId)).thread.issues, []);
4187
+ }),
4188
+ );
4189
+
4190
it.effect("starts, records, and stops a pull request watch", () =>
4191
Effect.gen(function* () {
4192
const orchestrator = yield* Orchestrator.OrchestratorV2;
apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
+2
@@ -161,6 +161,8 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
161
case "thread.pull-request.link":
162
case "thread.pull-request.unlink":
163
case "thread.pull-request-link.sync":
164
+ case "thread.issue.link":
165
+ case "thread.issue.unlink":
166
case "thread.pull-request.watch":
167
case "thread.pull-request.sync":
168
case "thread.title.regeneration.complete":
apps/server/src/provider/AgentContextBudget.test.ts
+4
@@ -21,6 +21,7 @@ import {
21
} from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
22
import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts";
23
import { ProviderAdapterRegistryV2 } from "../orchestration-v2/ProviderAdapterRegistry.ts";
24
+import { ThreadIssueService } from "../orchestration-v2/ThreadIssueService.ts";
25
import { ThreadLaunchService } from "../orchestration-v2/ThreadLaunchService.ts";
26
import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
27
import { ThreadSearch } from "../orchestration-v2/ThreadSearch.ts";
@@ -34,6 +35,7 @@ import { ManagedProjectFolders } from "../project/ManagedProjectFolders.ts";
35
import { ProjectCloneTracker } from "../project/ProjectCloneTracker.ts";
36
import { ProjectService } from "../project/ProjectService.ts";
37
import { ProjectSetupScriptRunner } from "../project/ProjectSetupScriptRunner.ts";
38
+import { IssueService } from "../issue/IssueService.ts";
39
import { PullRequestReviewGuideService } from "../pullRequest/PullRequestReviewGuideService.ts";
40
import { PullRequestService } from "../pullRequest/PullRequestService.ts";
41
import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
@@ -56,6 +58,7 @@ const toolHandlerServices = Layer.mergeAll(
58
Layer.mock(EnvironmentThemeService)({}),
59
Layer.mock(GitVcsDriver)({}),
60
Layer.mock(GitWorkflowService)({}),
61
+ Layer.mock(IssueService)({}),
62
Layer.mock(ManagedProjectFolders)({ namedProjectsRoot: "" }),
63
Layer.mock(McpProviderSessions)({}),
64
Layer.mock(OrchestratorV2)({}),
@@ -80,6 +83,7 @@ const toolHandlerServices = Layer.mergeAll(
83
Layer.mock(ServerSecretStore)({}),
84
Layer.mock(ServerSettingsService)({}),
85
Layer.mock(SourceControlRepositoryService)({}),
86
+ Layer.mock(ThreadIssueService)({}),
87
Layer.mock(ThreadLaunchService)({}),
88
Layer.mock(ThreadManagementService)({}),
89
Layer.mock(ThreadSearch)({}),
apps/server/src/provider/agentContextBudget.json
+1
-1
@@ -1,5 +1,5 @@
1
{
2
"claudeSystemAppendBytes": 5930,
3
"codexAdditionalContextBytes": 7324,
4
- "mcpToolListJsonBytes": 49737
4
+ "mcpToolListJsonBytes": 52199
5
}
apps/server/src/relay/AgentAwarenessRelay.ts
+1
@@ -97,6 +97,7 @@ function shouldPublishAgentAwarenessEvent(
97
case "thread.metadata-updated":
98
case "thread.pull-request-link-updated":
99
case "thread.pull-request-synced":
100
+ case "thread.issue-synced":
101
case "thread.settled":
102
case "thread.model-selection-updated":
103
case "thread.provider-switched":
apps/server/src/server.ts
+5
@@ -217,6 +217,7 @@ import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts";
217
import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts";
218
import * as IdleCompactionService from "./orchestration-v2/IdleCompactionService.ts";
219
import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts";
220
+import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts";
221
import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";
222
import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
223
import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts";
@@ -442,6 +443,9 @@ const layerPullRequestService = PullRequestService.layer.pipe(
443
444
const layerIssueService = IssueService.layer.pipe(Layer.provide(IssueTrackerRegistry.layer));
445
446
+// One instance serves MCP link calls and refreshes snapshots on thread events.
447
+const layerThreadIssueService = ThreadIssueService.layer;
448
+
449
const layerGitManager = GitManager.layer.pipe(
450
Layer.provide(Layer.merge(ProjectionStoreV2.layer, ProjectStore.layer)),
451
Layer.provideMerge(RuntimeLayer.layerProjectSetupScriptRunner),
@@ -866,6 +870,7 @@ const layerMakeRoutes = Layer.mergeAll(
870
Layer.provide(PeerLinkRequests.layer),
871
// Share the service so HTTP/WS clients single-flight reads and invalidate each other's cached patches.
872
Layer.provide(layerPullRequestService),
873
+ Layer.provide(layerThreadIssueService),
874
Layer.provide(layerIssueService),
875
// The same activity instance RunExecutionService reports to, by layer memoization.
876
Layer.provide(
apps/server/src/sourceControl/sourceControlDefinitions.test.ts
+31
@@ -22,3 +22,34 @@ it.each([
22
])("finds no host in %s, which git does not read as SSH", (remoteUrl) => {
23
expect(sourceControlDefinitions.recognizeRemote(remoteUrl)).toBeNull();
24
});
25
+
26
+it.each([
27
+ ["https://github.com/Acme/Web/issues/42", "github", "github.com", "acme/web", "42"],
28
+ [
29
+ "https://gitlab.acme.test/group/sub/web/-/issues/7",
30
+ "gitlab",
31
+ "gitlab.acme.test",
32
+ "group/sub/web",
33
+ "7",
34
+ ],
35
+ ["https://codeberg.org/acme/web/issues/3", "forgejo", "codeberg.org", "acme/web", "3"],
36
+ [
37
+ "https://dev.azure.com/acme/Web%20App/_workitems/edit/9",
38
+ "azure-devops",
39
+ "dev.azure.com",
40
+ "acme/web app",
41
+ "9",
42
+ ],
43
+] as const)("reads %s as an issue on its host", (url, kind, host, scope, key) => {
44
+ const parsed = sourceControlDefinitions.parseIssueUrl(url);
45
+ expect(parsed?.definition.kind).toBe(kind);
46
+ expect(parsed?.link).toEqual({ host, scope, key });
47
+});
48
+
49
+it.each([
50
+ "https://github.com/acme/web/pull/42",
51
+ "https://example.test/acme/web/issues/42",
52
+ "https://github.com/acme/web/issues/0",
53
+])("does not read %s as an issue", (url) => {
54
+ expect(sourceControlDefinitions.parseIssueUrl(url)).toBeNull();
55
+});
apps/web/src/components/BranchToolbarBranchSelector.tsx
+18
@@ -42,6 +42,7 @@ import { vcsEnvironment } from "../state/vcs";
42
import { cn } from "../lib/utils";
43
import { THREAD_DETAILS_PANEL_ICON_CLASS } from "./chat/threadDetailsPanelStyles";
44
import { ThreadDetailsThreadPrRows } from "./chat/ThreadDetailsPrRows";
45
+import { ThreadDetailsIssueRows } from "./chat/ThreadDetailsIssueRows";
46
import { parsePullRequestReference } from "@t3tools/client-runtime/pull-request-link-input";
47
import { getSourceControlPresentation } from "../sourceControlPresentation";
48
import { useComposerMenuProps } from "./chat/composerEventScope";
@@ -698,6 +699,7 @@ export function BranchToolbarBranchSelector({
699
branchStatusQuery.data?.sourceControlProvider,
700
);
701
const openPrLink = useOpenPrLink(threadRef);
702
+ const linkedIssues = serverThread?.issues ?? [];
703
704
function selectPickerItem(itemValue: string) {
705
if (itemValue === checkoutPullRequestItemValue && prReference && onCheckoutPullRequestRequest) {
@@ -884,6 +886,22 @@ export function BranchToolbarBranchSelector({
886
onActed={() => branchStatusQuery.refresh()}
887
/>
888
) : null}
889
+ {displayMode === "panel" ? (
890
+ <ThreadDetailsIssueRows
891
+ links={linkedIssues}
892
+ onOpenLink={(event, link) => {
893
+ event.stopPropagation();
894
+ useRightPanelStore.getState().openIssue(threadRef, {
895
+ projectId: link.projectId,
896
+ tracker: link.tracker,
897
+ host: link.host,
898
+ scope: link.scope,
899
+ key: link.key,
900
+ url: link.url,
901
+ });
902
+ }}
903
+ />
904
+ ) : null}
905
</div>
906
</BranchPicker>
907
);
apps/web/src/components/ChatMarkdown.tsx
+20
-2
@@ -160,6 +160,7 @@ import { hostEnvironmentIdAtom } from "../state/primaryEnvironment";
160
import { cn } from "../lib/utils";
161
import { resolveRemoteOpenState, useRemoteOpenResolution } from "../remoteOpen";
162
import { useRightPanelStore } from "../rightPanelStore";
163
+import { useOpenIssueLink } from "../lib/openIssueLink";
164
import { readThreadShell, useProjects } from "../state/entities";
165
import { serverEnvironment } from "../state/server";
166
import { shellEnvironment } from "../state/shell";
@@ -698,6 +699,7 @@ function useChatMarkdownState({
699
);
700
};
701
const openChangeRequestLink = useOpenChangeRequestLink(threadRef, pullRequestPanelRef);
702
+ const openIssueLink = useOpenIssueLink(threadRef, pullRequestPanelRef);
703
const openDeferredMarkdownLink = useOpenLink(threadRef);
704
// Subscribe so hydrated settings apply before the anchor synchronously decides whether to intercept _blank.
705
const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget);
@@ -997,6 +999,7 @@ function useChatMarkdownState({
999
onUseArtifactTemplate,
1000
onRunShellCommand,
1001
openChangeRequestLink,
1002
+ openIssueLink,
1003
openDeferredMarkdownLink,
1004
openExternalLinkInPreview,
1005
openMarkdownMedia,
@@ -1162,6 +1165,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
1165
threadRef,
1166
openMarkdownMedia,
1167
openChangeRequestLink,
1168
+ openIssueLink,
1169
openDeferredMarkdownLink,
1170
linkTargetPreference,
1171
openExternalLinkInPreview,
@@ -1277,7 +1281,8 @@ const CHAT_MARKDOWN_COMPONENTS = {
1281
}
1282
if (
1283
!href ||
1280
- openChangeRequestLink(event, href, undefined, environmentId ?? undefined)
1284
+ openChangeRequestLink(event, href, undefined, environmentId ?? undefined) ||
1285
+ openIssueLink(event, href, environmentId ?? undefined)
1286
) {
1287
return;
1288
}
@@ -1402,7 +1407,20 @@ const CHAT_MARKDOWN_COMPONENTS = {
1407
environmentId ?? undefined,
1408
)
1409
}
1405
- onOpenFallback={openDeferredMarkdownLink}
1410
+ // A reference that is not a pull request may still be an issue this app can show.
1411
+ onOpenFallback={async (url) => {
1412
+ const opened = openIssueLink(
1413
+ {
1414
+ metaKey: false,
1415
+ ctrlKey: false,
1416
+ preventDefault: () => undefined,
1417
+ stopPropagation: () => undefined,
1418
+ },
1419
+ url,
1420
+ environmentId ?? undefined,
1421
+ );
1422
+ if (!opened) await openDeferredMarkdownLink(url);
1423
+ }}
1424
/>
1425
);
1426
}
apps/web/src/components/ChatView.tsx
+1
@@ -3273,6 +3273,7 @@ export default function ChatView(props: ChatViewProps) {
3273
? addPullRequestsSurfaceStable
3274
: undefined,
3275
}}
3276
+ issuesSupported={serverConfig?.environment.capabilities.issues === true}
3277
files={{
3278
projectId: activeProject?.id,
3279
projectName: activeProject?.title ?? null,
apps/web/src/components/chat/RightPanelSurfaceContent.tsx
+37
@@ -1,6 +1,7 @@
1
import type {
2
EditorId,
3
EnvironmentId,
4
+ IssueTrackerKind,
5
PreviewAnnotationPayload,
6
ProjectId,
7
ResolvedKeybindingsConfig,
@@ -19,6 +20,7 @@ import {
20
PersistentThreadTerminalPanel,
21
type PersistentThreadTerminalPanelProps,
22
} from "../PersistentThreadTerminals";
23
+import { IssueDetailPanel } from "../issue/IssueDetailPanel";
24
import { pullRequestPanelContext } from "../pullRequest/pullRequestDetail.logic";
25
import { PullRequestDetailPanel } from "../pullRequest/PullRequestDetailPanel";
26
import { PullRequestDetailGhost } from "../pullRequest/PullRequestGhosts";
@@ -77,6 +79,7 @@ export function RightPanelSurfaceContent(props: {
79
readonly onCloseSurface: (surface: RightPanelSurface) => void;
80
readonly terminal: RightPanelTerminalProps;
81
readonly pullRequest: RightPanelPullRequestProps;
82
+ readonly issuesSupported: boolean;
83
readonly files: RightPanelFileProps;
84
readonly sideChatParentPanel: SideChatParentPanel;
85
}) {
@@ -171,6 +174,40 @@ export function RightPanelSurfaceContent(props: {
174
/>
175
);
176
}
177
+ case "issue":
178
+ if (!props.pullRequest.capabilityKnown) return <PullRequestDetailGhost />;
179
+ if (!props.issuesSupported) {
180
+ return (
181
+ <PullRequestsUnavailableState
182
+ title="Issues unavailable"
183
+ error="Update this environment's T3 Code server to browse issues."
184
+ />
185
+ );
186
+ }
187
+ return (
188
+ <IssueDetailPanel
189
+ key={surface.id}
190
+ environmentId={
191
+ (surface.environmentId as EnvironmentId | undefined) ?? props.environmentId
192
+ }
193
+ reference={{
194
+ projectId: surface.projectId as ProjectId,
195
+ tracker: surface.tracker as IssueTrackerKind,
196
+ ...(surface.host ? { host: surface.host } : {}),
197
+ scope: surface.scope,
198
+ key: surface.key,
199
+ }}
200
+ threadRef={threadRef}
201
+ onSelectPullRequest={(reference) => {
202
+ useRightPanelStore.getState().openPullRequest(threadRef, {
203
+ projectId: reference.projectId,
204
+ repository: reference.repository,
205
+ number: reference.number,
206
+ ...(reference.host ? { host: reference.host } : {}),
207
+ });
208
+ }}
209
+ />
210
+ );
211
case "pull-requests":
212
return <ThreadPullRequestsPanel threadRef={threadRef} />;
213
case "side-chat":
apps/web/src/components/chat/ThreadDetailsIssueRows.tsx
new
+43
@@ -0,0 +1,43 @@
1
+import { threadIssueKeyOf, type ThreadIssueLink } from "@t3tools/contracts";
2
+import type { MouseEvent as ReactMouseEvent } from "react";
3
+
4
+import { cn } from "~/lib/utils";
5
+
6
+import { IssueGlyph } from "../issue/issuePresentation";
7
+import { ThreadDetailsControl } from "./ThreadDetailsControl";
8
+import {
9
+ THREAD_DETAILS_PANEL_ICON_CLASS,
10
+ THREAD_DETAILS_PANEL_LABEL_CLASS,
11
+} from "./threadDetailsPanelStyles";
12
+
13
+/**
14
+ * The thread details panel's issue rows, one per linked issue, beside the pull request rows. A
15
+ * row names the issue as it was when linked and opens it in the right panel, which reads its
16
+ * live state.
17
+ */
18
+export function ThreadDetailsIssueRows({
19
+ links,
20
+ onOpenLink,
21
+}: {
22
+ links: ReadonlyArray<ThreadIssueLink>;
23
+ onOpenLink: (event: ReactMouseEvent<HTMLElement>, link: ThreadIssueLink) => void;
24
+}) {
25
+ if (links.length === 0) return null;
26
+ return (
27
+ <>
28
+ {links.map((link) => (
29
+ <ThreadDetailsControl
30
+ key={threadIssueKeyOf(link)}
31
+ part="row"
32
+ aria-label={link.url}
33
+ onClick={(event) => onOpenLink(event, link)}
34
+ >
35
+ <IssueGlyph.issue aria-hidden className={THREAD_DETAILS_PANEL_ICON_CLASS} />
36
+ <span className={cn("min-w-0 flex-1 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS)}>
37
+ {link.displayKey}: {link.title}
38
+ </span>
39
+ </ThreadDetailsControl>
40
+ ))}
41
+ </>
42
+ );
43
+}
apps/web/src/components/issue/IssueDetailPanel.tsx
+88
-1
@@ -10,6 +10,7 @@ import {
10
} from "@t3tools/client-runtime/issue-selection";
11
import { isSelected, toggleSelection } from "@t3tools/client-runtime/pull-request-selection";
12
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
13
+import { AuthOrchestrationOperateScope, threadIssueKeysEqual } from "@t3tools/contracts";
14
import type {
15
EnvironmentId,
16
IssueAssigneeCandidate,
@@ -28,6 +29,8 @@ import {
29
CheckIcon,
30
ChevronDownIcon,
31
ExternalLinkIcon,
32
+ Link2Icon,
33
+ Link2OffIcon,
34
TagIcon,
35
UserPlusIcon,
36
UsersIcon,
@@ -36,8 +39,10 @@ import { useState, type ReactNode } from "react";
39
40
import { RefreshIcon } from "~/components/ui/refresh-icon";
41
import { issueEnvironment } from "~/state/issues";
39
-import { useProjects } from "~/state/entities";
42
+import { useProjects, useThreadShell } from "~/state/entities";
43
import { useEnvironmentQuery } from "~/state/query";
44
+import { useEnvironmentScope } from "~/state/session";
45
+import { threadEnvironment } from "~/state/threads";
46
import { useAtomCommand } from "~/state/use-atom-command";
47
import { formatRelativeTimeLabel } from "~/timestampFormat";
48
@@ -47,6 +52,7 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
52
import { cn } from "~/lib/utils";
53
import { PullRequestMetaRow, PullRequestSection } from "../pullRequest/PullRequestSummaryTab";
54
import { toastManager } from "../ui/toast";
55
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
56
import { PullRequestCandidatePicker } from "../pullRequest/PullRequestCandidatePicker";
57
import { PullRequestCommentBody } from "../pullRequest/PullRequestCommentBody";
58
import { PullRequestDetailTitleRow } from "../pullRequest/PullRequestDetailLayout";
@@ -71,6 +77,79 @@ import {
77
issueTrackerPresentation,
78
} from "./issuePresentation";
79
80
+/**
81
+ * Links or unlinks the issue to the thread it is shown beside. Dispatches the orchestration
82
+ * command directly, as pull request linking does.
83
+ */
84
+function IssueThreadLinkButton({
85
+ environmentId,
86
+ reference,
87
+ issue,
88
+ threadRef,
89
+}: {
90
+ environmentId: EnvironmentId;
91
+ reference: IssueRef;
92
+ issue: Pick<IssueDetail, "url" | "displayKey" | "title">;
93
+ threadRef: ScopedThreadRef;
94
+}) {
95
+ const thread = useThreadShell(threadRef.environmentId === environmentId ? threadRef : null);
96
+ const canOperate = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
97
+ const link = useAtomCommand(threadEnvironment.linkIssue, { reportFailure: false });
98
+ const unlink = useAtomCommand(threadEnvironment.unlinkIssue, { reportFailure: false });
99
+ const [pending, setPending] = useState(false);
100
+ if (thread === null || !canOperate) return null;
101
+ const key = { ...reference, host: reference.host ?? "" };
102
+ const linked = (thread.issues ?? []).some((existing) => threadIssueKeysEqual(existing, key));
103
+ const toggle = async () => {
104
+ if (pending || reference.host === undefined) return;
105
+ setPending(true);
106
+ const result = await (linked
107
+ ? unlink({ environmentId, input: { threadId: threadRef.threadId, ...key } })
108
+ : link({
109
+ environmentId,
110
+ input: {
111
+ threadId: threadRef.threadId,
112
+ ...key,
113
+ url: issue.url,
114
+ displayKey: issue.displayKey,
115
+ title: issue.title,
116
+ source: "manual",
117
+ },
118
+ }));
119
+ setPending(false);
120
+ if (result._tag === "Failure") {
121
+ toastManager.add({
122
+ type: "error",
123
+ title: linked ? "Could not unlink the issue" : "Could not link the issue",
124
+ description: readableFailure(squashAtomCommandFailure(result), "The server refused it."),
125
+ });
126
+ }
127
+ };
128
+ return (
129
+ <Tooltip>
130
+ <TooltipTrigger
131
+ render={
132
+ <Button
133
+ size="icon-xs"
134
+ variant="ghost"
135
+ aria-label={linked ? "Unlink from thread" : "Link to thread"}
136
+ aria-pressed={linked}
137
+ disabled={pending || reference.host === undefined}
138
+ onClick={() => void toggle()}
139
+ />
140
+ }
141
+ >
142
+ {linked ? (
143
+ <Link2OffIcon aria-hidden className="size-3.5" />
144
+ ) : (
145
+ <Link2Icon aria-hidden className="size-3.5" />
146
+ )}
147
+ </TooltipTrigger>
148
+ <TooltipPopup>{linked ? "Unlink from this thread" : "Link to this thread"}</TooltipPopup>
149
+ </Tooltip>
150
+ );
151
+}
152
+
153
/** Why a control is off, said once so each disabled affordance can point at it. */
154
function writeBlockReason(detail: IssueDetail, canWrite: boolean): string | null {
155
if (!canWrite) return "Writing to this tracker needs the source-control write scope.";
@@ -596,6 +675,14 @@ export function IssueDetailPanel({
675
</InlineButton>
676
<span className="flex-1" />
677
{stateControl}
678
+ {threadRef ? (
679
+ <IssueThreadLinkButton
680
+ environmentId={environmentId}
681
+ reference={{ ...reference, host: reference.host ?? detail.host }}
682
+ issue={detail}
683
+ threadRef={threadRef}
684
+ />
685
+ ) : null}
686
<Button
687
size="icon-xs"
688
variant="ghost"
apps/web/src/lib/openIssueLink.ts
new
+83
@@ -0,0 +1,83 @@
1
+import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
2
+import { resolveIssueLinkTarget } from "@t3tools/client-runtime/issue-links";
3
+import { useNavigate } from "@tanstack/react-router";
4
+import type { MouseEvent } from "react";
5
+
6
+import { readIssueListPreferences } from "../components/issue/issueListPreferences";
7
+import { ISSUES_PANEL_REF, PULL_REQUESTS_PANEL_REF, useRightPanelStore } from "../rightPanelStore";
8
+import { useProjects, useServerConfigs } from "../state/entities";
9
+
10
+/**
11
+ * Opens an issue link beside the thread, and says whether it did. Anything else — a host no
12
+ * project here is on, a link that merely looks like one — is left alone for the caller to handle
13
+ * as the ordinary link it is. Mirrors `useOpenChangeRequestLink`: a reader following a link the
14
+ * agent wrote is reading the thread, and should still be reading it afterwards.
15
+ */
16
+export function useOpenIssueLink(
17
+ threadRef?: ScopedThreadRef,
18
+ panelRef?: ScopedThreadRef,
19
+): (
20
+ event: Pick<
21
+ MouseEvent<HTMLElement>,
22
+ "preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
23
+ >,
24
+ targetUrl: string,
25
+ targetEnvironmentId?: EnvironmentId,
26
+) => boolean {
27
+ const allProjects = useProjects();
28
+ const serverConfigs = useServerConfigs();
29
+ const navigate = useNavigate();
30
+ return (event, targetUrl, targetEnvironmentId) => {
31
+ if (event.metaKey || event.ctrlKey) return false;
32
+ const resolvedPanelRef = panelRef ?? threadRef;
33
+ // A list page's panel ref is a placeholder, not an environment; the link names its own.
34
+ const environmentId = threadRef?.environmentId ?? targetEnvironmentId;
35
+ if (resolvedPanelRef === undefined || environmentId === undefined) return false;
36
+ if (serverConfigs.get(environmentId)?.environment.capabilities.issues !== true) return false;
37
+ const target = resolveIssueLinkTarget({
38
+ url: targetUrl,
39
+ projects: allProjects.filter((project) => project.environmentId === environmentId),
40
+ });
41
+ if (target === null) return false;
42
+ event.preventDefault();
43
+ event.stopPropagation();
44
+ const surface = {
45
+ projectId: target.ref.projectId,
46
+ tracker: target.ref.tracker,
47
+ ...(target.ref.host === undefined ? {} : { host: target.ref.host }),
48
+ scope: target.ref.scope,
49
+ key: target.ref.key,
50
+ url: targetUrl,
51
+ };
52
+ // A list page's panel is the Issues page's: its pull request tabs render this markdown too,
53
+ // and the pull request list's own panel shows pull requests only. Opening the tab here, not
54
+ // only through the URL, also brings back one that is already open.
55
+ if (resolvedPanelRef === PULL_REQUESTS_PANEL_REF) {
56
+ useRightPanelStore.getState().openIssue(ISSUES_PANEL_REF, { ...surface, environmentId });
57
+ const selection = {
58
+ selectedEnvironmentId: environmentId,
59
+ selectedProjectId: target.ref.projectId,
60
+ ...(target.ref.host === undefined ? {} : { selectedHost: target.ref.host }),
61
+ tracker: target.ref.tracker,
62
+ scope: target.ref.scope,
63
+ key: target.ref.key,
64
+ };
65
+ // Already on the Issues page, the list keeps the filters it is showing.
66
+ if (window.location.pathname === "/issues") {
67
+ void navigate({
68
+ from: "/issues",
69
+ to: "/issues",
70
+ search: (previous) => ({ ...previous, ...selection }),
71
+ });
72
+ } else {
73
+ void navigate({ to: "/issues", search: { ...readIssueListPreferences(), ...selection } });
74
+ }
75
+ return true;
76
+ }
77
+ useRightPanelStore.getState().openIssue(resolvedPanelRef, {
78
+ ...(resolvedPanelRef.environmentId === environmentId ? {} : { environmentId }),
79
+ ...surface,
80
+ });
81
+ return true;
82
+ };
83
+}
docs/user/source-control.md
+5
@@ -364,6 +364,11 @@ comment, edit the title and description, change labels and assignees, react, and
364
reopen (with a close reason where the tracker records one) when the tracker and your account
365
allow it. An issue read through a project that does not own its repository is shown read-only.
366
367
+An issue can be kept with a thread the way a pull request can: open it beside the thread (issue
368
+links in the conversation open there) and use **Link to this thread** in its header; **Unlink**
369
+undoes it. Linked issues are listed in the thread's details beside its pull requests. Agents link the
370
+issues they work on with the `link_issue` tool.
371
+
372
Writing to a tracker over a remote connection requires the `source-control:write` scope.
373
374
## GitHub stacks
packages/client-runtime/package.json
+4
@@ -571,6 +571,10 @@
571
"types": "./src/pullRequestReviewers.ts",
572
"default": "./src/pullRequestReviewers.ts"
573
},
574
+ "./issue-links": {
575
+ "types": "./src/issueLinks.ts",
576
+ "default": "./src/issueLinks.ts"
577
+ },
578
"./issue-selection": {
579
"types": "./src/issueSelection.ts",
580
"default": "./src/issueSelection.ts"
packages/client-runtime/src/issueLinks.test.ts
new
+44
@@ -0,0 +1,44 @@
1
+import { EnvironmentId, ProjectId, SourceControlProviderKind } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { resolveIssueLinkTarget } from "./issueLinks.ts";
5
+
6
+const project = (id: string, repository: string) =>
7
+ ({
8
+ id: ProjectId.make(id),
9
+ environmentId: EnvironmentId.make("env"),
10
+ repositoryIdentity: {
11
+ canonicalKey: `github.com/${repository}`,
12
+ provider: SourceControlProviderKind.make("github"),
13
+ displayName: repository,
14
+ owner: repository.split("/")[0],
15
+ name: repository.split("/")[1],
16
+ },
17
+ }) as never;
18
+
19
+describe("resolveIssueLinkTarget", () => {
20
+ const projects = [project("p1", "acme/api"), project("p2", "acme/web")];
21
+
22
+ it.each([
23
+ {
24
+ name: "reads an issue through the project bound to its repository",
25
+ url: "https://github.com/acme/web/issues/7",
26
+ expected: { projectId: "p2", scope: "acme/web", key: "7" },
27
+ },
28
+ {
29
+ name: "lends a project on the same host to a repository no project is bound to",
30
+ url: "https://github.com/other/repo/issues/9",
31
+ expected: { projectId: "p1", scope: "other/repo", key: "9" },
32
+ },
33
+ ])("$name", ({ url, expected }) => {
34
+ const target = resolveIssueLinkTarget({ url, projects });
35
+ expect(target?.ref).toMatchObject({ tracker: "github", host: "github.com", ...expected });
36
+ });
37
+
38
+ it.each([
39
+ "https://github.com.evil.example/acme/web/issues/7",
40
+ "https://github.com/acme/web/pull/7",
41
+ ])("leaves %s an ordinary link", (url) => {
42
+ expect(resolveIssueLinkTarget({ url, projects })).toBeNull();
43
+ });
44
+});
packages/client-runtime/src/issueLinks.ts
new
+62
@@ -0,0 +1,62 @@
1
+import type { IssueRef } from "@t3tools/contracts";
2
+
3
+import { sourceControlClients } from "./sourceControlClients.ts";
4
+import type { EnvironmentProject } from "./state/shell.ts";
5
+
6
+type LinkProject = Pick<EnvironmentProject, "id" | "environmentId" | "repositoryIdentity">;
7
+
8
+/** The host and scope a project's git-host tracker is bound to, the way the server resolves it. */
9
+function projectIssueBinding(project: LinkProject): {
10
+ readonly tracker: string;
11
+ readonly host: string;
12
+ readonly scope: string;
13
+} | null {
14
+ const identity = project.repositoryIdentity;
15
+ const scope = sourceControlClients.issueScope(identity);
16
+ const kind = identity?.provider;
17
+ if (!identity || kind === undefined || kind === "unknown" || scope === null) return null;
18
+ return {
19
+ tracker: kind,
20
+ host: sourceControlClients.changeRequestHost(identity, kind),
21
+ scope: scope.toLowerCase(),
22
+ };
23
+}
24
+
25
+/**
26
+ * The reference an issue link resolves to, and the project it is read through: the project whose
27
+ * tracker binding is that host and scope, else any project on the same tracker and host lending
28
+ * its credentials for a read-only view. The same rule as the server's `IssueService.resolveUrl`,
29
+ * applied on the client so a lookalike hostname matches no project and stays an ordinary link.
30
+ */
31
+export function resolveIssueLinkTarget<Project extends LinkProject>(input: {
32
+ readonly url: string;
33
+ /** The projects of the environment the link is read in. */
34
+ readonly projects: ReadonlyArray<Project>;
35
+ readonly preferredProjectId?: string | undefined;
36
+}): { readonly project: Project; readonly ref: IssueRef } | null {
37
+ const parsed = sourceControlClients.parseIssueUrl(input.url);
38
+ if (parsed === null) return null;
39
+ const { definition, link } = parsed;
40
+ const bound = input.projects.flatMap((project) => {
41
+ const binding = projectIssueBinding(project);
42
+ return binding === null || binding.tracker !== definition.kind || binding.host !== link.host
43
+ ? []
44
+ : [{ project, binding }];
45
+ });
46
+ const preferFirst = (candidates: typeof bound) =>
47
+ candidates.find((candidate) => candidate.project.id === input.preferredProjectId) ??
48
+ candidates[0];
49
+ const own = preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scope));
50
+ const lender = own ?? preferFirst(bound);
51
+ if (lender === undefined) return null;
52
+ return {
53
+ project: lender.project,
54
+ ref: {
55
+ projectId: lender.project.id,
56
+ tracker: lender.binding.tracker as IssueRef["tracker"],
57
+ host: lender.binding.host,
58
+ scope: own === undefined ? link.scope : lender.binding.scope,
59
+ key: link.key,
60
+ },
61
+ };
62
+}
packages/client-runtime/src/operations/commands.ts
+28
@@ -1204,6 +1204,34 @@ export const linkThreadPullRequest = Effect.fn("EnvironmentCommands.linkThreadPu
1204
});
1205
},
1206
);
1207
+export type LinkThreadIssueInput = Omit<
1208
+ Extract<OrchestrationV2Command, { type: "thread.issue.link" }>,
1209
+ "type" | "commandId"
1210
+> &
1211
+ CommandMetadata;
1212
+export type UnlinkThreadIssueInput = Omit<
1213
+ Extract<OrchestrationV2Command, { type: "thread.issue.unlink" }>,
1214
+ "type" | "commandId"
1215
+> &
1216
+ CommandMetadata;
1217
+export const linkThreadIssue = Effect.fn("EnvironmentCommands.linkThreadIssue")(function* (
1218
+ input: LinkThreadIssueInput,
1219
+) {
1220
+ return yield* dispatch({
1221
+ ...input,
1222
+ type: "thread.issue.link",
1223
+ commandId: yield* allocateCommandId(input),
1224
+ });
1225
+});
1226
+export const unlinkThreadIssue = Effect.fn("EnvironmentCommands.unlinkThreadIssue")(function* (
1227
+ input: UnlinkThreadIssueInput,
1228
+) {
1229
+ return yield* dispatch({
1230
+ ...input,
1231
+ type: "thread.issue.unlink",
1232
+ commandId: yield* allocateCommandId(input),
1233
+ });
1234
+});
1235
export type WatchThreadPullRequestInput = Omit<
1236
Extract<OrchestrationV2Command, { type: "thread.pull-request.watch" }>,
1237
"type" | "commandId"
packages/client-runtime/src/state/models.ts
+3
@@ -192,6 +192,8 @@ export interface EnvironmentThreadShell {
192
readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
193
readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
194
readonly branchPullRequest?: ThreadLinkedPullRequest | null;
195
+ /** Absent from rows built before issue linking; the server sends an empty list. */
196
+ readonly issues?: ReadonlyArray<import("@t3tools/contracts").ThreadIssueLink>;
197
/**
198
* Server-tracked visited watermark. `undefined` means the environment's
199
* server predates visited tracking and clients should fall back to any
@@ -301,6 +303,7 @@ export function presentThreadShell(
303
pullRequests: threadPullRequestsOf(thread),
304
linkedPullRequest: thread.linkedPullRequest ?? null,
305
branchPullRequest: thread.branchPullRequest ?? null,
306
+ issues: thread.issues ?? [],
307
lineage: thread.lineage,
308
forkedFrom: thread.forkedFrom,
309
linkOrigin: thread.linkOrigin ?? null,
packages/client-runtime/src/state/orchestrationV2Projection.ts
+1
@@ -314,6 +314,7 @@ export function applyOrchestrationV2ProjectionEvent(
314
case "thread.active-reordered":
315
case "thread.metadata-updated":
316
case "thread.pull-request-synced":
317
+ case "thread.issue-synced":
318
case "thread.runtime-mode-updated":
319
case "thread.interaction-mode-updated":
320
case "thread.model-selection-updated":
packages/client-runtime/src/state/threadCommands.ts
+14
@@ -40,6 +40,7 @@ import {
40
resumeThreadQueue,
41
retryWorkspacePreparation,
42
linkThreadPullRequest,
43
+ linkThreadIssue,
44
respondToThreadApproval,
45
respondToThreadUserInput,
46
dismissThreadUserInput,
@@ -56,6 +57,7 @@ import {
57
stopThreadSession,
58
unarchiveThread,
59
unlinkThreadPullRequest,
60
+ unlinkThreadIssue,
61
unpinThread,
62
unsettleThread,
63
unsnoozeThread,
@@ -293,6 +295,18 @@ export function createThreadEnvironmentAtoms<R, E>(
295
scheduler,
296
concurrency,
297
}),
298
+ linkIssue: createEnvironmentCommand(runtime, {
299
+ label: "environment-data:commands:thread:link-issue",
300
+ execute: linkThreadIssue,
301
+ scheduler,
302
+ concurrency,
303
+ }),
304
+ unlinkIssue: createEnvironmentCommand(runtime, {
305
+ label: "environment-data:commands:thread:unlink-issue",
306
+ execute: unlinkThreadIssue,
307
+ scheduler,
308
+ concurrency,
309
+ }),
310
setRuntimeMode: createEnvironmentCommand(runtime, {
311
label: "environment-data:commands:thread:set-runtime-mode",
312
execute: setThreadRuntimeMode,
packages/client-runtime/src/t3ToolSummary.ts
+28
@@ -466,6 +466,34 @@ export function summarizeT3ToolCalls(
466
case "read-pr-guide":
467
label = phrase("Read", "read", quantity(selected.length, "review guide"));
468
break;
469
+ case "list-issues":
470
+ label = phrase("Listed", "list", `issues ${times}`);
471
+ break;
472
+ case "read-issue":
473
+ label = phrase("Read", "read", quantity(selected.length, "issue"));
474
+ break;
475
+ case "create-issue":
476
+ label = phrase("Filed", "file", quantity(selected.length, "issue"));
477
+ break;
478
+ case "comment-issue":
479
+ label = phrase("Commented on", "comment on", quantity(selected.length, "issue"));
480
+ break;
481
+ case "set-issue-state":
482
+ label = phrase("Changed", "change", `the state of ${quantity(selected.length, "issue")}`);
483
+ break;
484
+ case "link-issue":
485
+ label = phrase("Linked", "link", quantity(selected.length, "issue"));
486
+ break;
487
+ case "unlink-issue":
488
+ label = phrase("Unlinked", "unlink", quantity(selected.length, "issue"));
489
+ break;
490
+ case "list-thread-issues":
491
+ label = phrase(
492
+ "Checked",
493
+ "check",
494
+ `linked issues${selected.length === 1 ? "" : ` ${times}`}`,
495
+ );
496
+ break;
497
case "browser":
498
label = phrase("Used", "use", `browser ${times}`);
499
break;
packages/contracts/src/issue.ts
+41
@@ -460,3 +460,44 @@ export class IssueOperationError extends Schema.TaggedError<IssueOperationError>
460
}
461
462
export type IssueError = IssueUnavailableError | IssueOperationError;
463
+
464
+/** Who created a thread ↔ issue link. */
465
+export const ThreadIssueLinkSource = Schema.Literals(["manual", "agent"]);
466
+export type ThreadIssueLinkSource = typeof ThreadIssueLinkSource.Type;
467
+
468
+/**
469
+ * Identity of an issue as a thread link sees it: tracker-level, so the same issue linked through
470
+ * two projects compares equal. `host` is always written here, unlike `IssueRef`, because a link
471
+ * outlives the project whose binding supplied the default.
472
+ */
473
+export const ThreadIssueKey = Schema.Struct({
474
+ tracker: IssueTrackerKind,
475
+ host: TrimmedNonEmptyString,
476
+ scope: TrimmedNonEmptyString,
477
+ key: TrimmedNonEmptyString,
478
+});
479
+export type ThreadIssueKey = typeof ThreadIssueKey.Type;
480
+
481
+/**
482
+ * An issue linked to a thread. `projectId` is the project the issue is read through, which the
483
+ * detail panel needs; `url` is what the agent or user handed over.
484
+ */
485
+export const ThreadIssueLink = Schema.Struct({
486
+ ...ThreadIssueKey.fields,
487
+ projectId: ProjectId,
488
+ url: TrimmedNonEmptyString,
489
+ source: ThreadIssueLinkSource,
490
+ linkedAt: IsoDateTime,
491
+ /** As the tracker named the issue when it was linked; opening it reads the live state. */
492
+ displayKey: TrimmedNonEmptyString,
493
+ title: TrimmedNonEmptyString,
494
+});
495
+export type ThreadIssueLink = typeof ThreadIssueLink.Type;
496
+
497
+export function threadIssueKeyOf(key: ThreadIssueKey): string {
498
+ return `${key.tracker}\u0000${key.host.trim().toLowerCase()}\u0000${key.scope.trim().toLowerCase()}\u0000${key.key.trim()}`;
499
+}
500
+
501
+export function threadIssueKeysEqual(left: ThreadIssueKey, right: ThreadIssueKey): boolean {
502
+ return threadIssueKeyOf(left) === threadIssueKeyOf(right);
503
+}
packages/contracts/src/orchestrationV2.ts
+24
@@ -57,6 +57,7 @@ import {
57
OrchestrationGetTurnDiffResult,
58
} from "./checkpointDiff.ts";
59
import { ModelSelection } from "./modelSelection.ts";
60
+import { ThreadIssueKey, ThreadIssueLink, ThreadIssueLinkSource } from "./issue.ts";
61
import {
62
ThreadLinkedPullRequest,
63
ThreadPullRequestLink,
@@ -477,6 +478,8 @@ export const OrchestrationV2AppThread = Schema.Struct({
478
linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
479
pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)),
480
branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
481
+ /** Issues linked to this thread; optional so pre-linking servers still decode. */
482
+ issues: Schema.optional(Schema.Array(ThreadIssueLink)),
483
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
484
historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
485
linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
@@ -2004,6 +2007,7 @@ export const OrchestrationV2DomainEvent = Schema.Union([
2007
"thread.marked-unread",
2008
"thread.metadata-updated",
2009
"thread.pull-request-synced",
2010
+ "thread.issue-synced",
2011
"thread.runtime-mode-updated",
2012
"thread.interaction-mode-updated",
2013
"thread.model-selection-updated",
@@ -2207,6 +2211,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
2211
linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
2212
pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)),
2213
branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
2214
+ /** Issues linked to this thread; optional so pre-linking servers still decode. */
2215
+ issues: Schema.optional(Schema.Array(ThreadIssueLink)),
2216
lineage: OrchestrationV2AppThreadLineage,
2217
forkedFrom: Schema.NullOr(OrchestrationV2AppThread.fields.forkedFrom),
2218
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
@@ -2947,6 +2953,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union([
2953
"thread.visited",
2954
"thread.marked-unread",
2955
"thread.pull-request-synced",
2956
+ "thread.issue-synced",
2957
"thread.metadata-updated",
2958
"thread.runtime-mode-updated",
2959
"thread.interaction-mode-updated",
@@ -3284,6 +3291,23 @@ export const OrchestrationV2Command = Schema.Union([
3291
snapshot: ThreadPullRequestSnapshot,
3292
stack: Schema.NullOr(ThreadPullRequestStack),
3293
}),
3294
+ Schema.Struct({
3295
+ type: Schema.Literal("thread.issue.link"),
3296
+ commandId: CommandId,
3297
+ threadId: ThreadId,
3298
+ ...ThreadIssueKey.fields,
3299
+ projectId: ProjectId,
3300
+ url: TrimmedNonEmptyString,
3301
+ displayKey: TrimmedNonEmptyString,
3302
+ title: TrimmedNonEmptyString,
3303
+ source: ThreadIssueLinkSource,
3304
+ }),
3305
+ Schema.Struct({
3306
+ type: Schema.Literal("thread.issue.unlink"),
3307
+ commandId: CommandId,
3308
+ threadId: ThreadId,
3309
+ ...ThreadIssueKey.fields,
3310
+ }),
3311
Schema.Struct({
3312
type: Schema.Literal("thread.pull-request.watch"),
3313
commandId: CommandId,
packages/shared/src/t3McpToolPresentation.ts
+19
@@ -67,6 +67,14 @@ export type T3McpToolSummaryAction =
67
| "unwatch-pr"
68
| "write-pr-guides"
69
| "read-pr-guide"
70
+ | "list-issues"
71
+ | "read-issue"
72
+ | "create-issue"
73
+ | "comment-issue"
74
+ | "set-issue-state"
75
+ | "link-issue"
76
+ | "unlink-issue"
77
+ | "list-thread-issues"
78
| "browser"
79
| "device"
80
| "html-preview"
@@ -144,6 +152,17 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
152
"read-pr-guide",
153
"pull-request",
154
),
155
+ list_issues: tool(["List", "Listing", "Listed", "issues"], "list-issues"),
156
+ read_issue: tool(["Read", "Reading", "Read", "an issue"], "read-issue"),
157
+ create_issue: tool(["File", "Filing", "Filed", "an issue"], "create-issue"),
158
+ comment_on_issue: tool(
159
+ ["Comment on", "Commenting on", "Commented on", "an issue"],
160
+ "comment-issue",
161
+ ),
162
+ set_issue_state: tool(["Change", "Changing", "Changed", "an issue's state"], "set-issue-state"),
163
+ link_issue: tool(["Link", "Linking", "Linked", "an issue"], "link-issue"),
164
+ unlink_issue: tool(["Unlink", "Unlinking", "Unlinked", "an issue"], "unlink-issue"),
165
+ list_thread_issues: tool(["Check", "Checking", "Checked", "linked issues"], "list-thread-issues"),
166
orchestrator_capabilities: tool(
167
["Get", "Getting", "Got", "orchestration capabilities"],
168
"capabilities",
packages/source-control-azure-devops/src/shared/definition.ts
+10
@@ -6,6 +6,7 @@ import {
6
defineSourceControl,
7
isChangeRequestAuthorityOfProject,
8
parseChangeRequestPath,
9
+ parseIssuePath,
10
parseCommitPath,
11
remoteWebOrigin,
12
} from "@t3tools/source-control-core/shared/definition";
@@ -14,6 +15,8 @@ import { icon } from "./icon.ts";
15
// Azure DevOps Server runs on any hostname; its `_git` route identifies it.
16
const CHANGE_REQUEST_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u;
17
const COMMIT_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu;
18
+// Work items belong to the project: /{organization}/{project}/_workitems/edit/{id}.
19
+const WORK_ITEM_PATH = /^\/([^/]+\/[^/]+)\/_workitems\/edit\/(\d+)(?:\/|$)/u;
20
const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i;
21
const CHANGE_REQUEST_REFERENCE =
22
/^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/(?:DefaultCollection\/)?[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i;
@@ -117,6 +120,13 @@ export const definition = defineSourceControl({
120
const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH);
121
return link === null || url.port === "" ? link : { ...link, authority: url.host.toLowerCase() };
122
},
123
+ // A project named with spaces arrives percent-encoded; the binding it is matched against is not.
124
+ parseIssueUrl: (url) => {
125
+ const link = parseIssuePath(url, WORK_ITEM_PATH);
126
+ return link === null
127
+ ? null
128
+ : { ...link, scope: link.scope.split("/").map(decodeUrlPathSegment).join("/").toLowerCase() };
129
+ },
130
changeRequestUrlFromReferenceAutolink: () => null,
131
changeRequestActions: new Set([
132
"merge",
packages/source-control-core/src/shared/definition.ts
+37
@@ -31,6 +31,17 @@ export interface ChangeRequestLink {
31
readonly authority?: string;
32
}
33
34
+/**
35
+ * An issue as a URL names it: the host it is served from, the container the tracker addresses
36
+ * it by, and its native key there. Written like a project's own binding, lower case, because
37
+ * links are matched against those.
38
+ */
39
+export interface IssueLink {
40
+ readonly host: string;
41
+ readonly scope: string;
42
+ readonly key: string;
43
+}
44
+
45
export interface ParsedChangeRequestUrl extends ChangeRequestLink {
46
/** The repository's browser URL, without query or hash. */
47
readonly repositoryUrl: string;
@@ -263,6 +274,8 @@ export interface SourceControlDefinition {
274
readonly parseCommitUrl?: (url: URL, known: boolean) => CommitLink | null;
275
/** Null when the URL is not one of this host's change requests. */
276
readonly parseChangeRequestUrl: (url: URL) => ParsedChangeRequestUrl | null;
277
+ /** Null when the URL is not one of this host's issues. Absent for a host with none. */
278
+ readonly parseIssueUrl?: (url: URL) => IssueLink | null;
279
/**
280
* The repository URL when `url` is a page inside one of this host's repositories. `known` is set
281
* when the caller already knows this host serves the URL's repository. Off a known host, return
@@ -434,6 +447,17 @@ export function parseChangeRequestPath(url: URL, route: RegExp): ParsedChangeReq
447
: null;
448
}
449
450
+/** Reads an issue from `url` with `route`, whose groups are the scope and the issue number. */
451
+export function parseIssuePath(url: URL, route: RegExp): IssueLink | null {
452
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
453
+ const match = route.exec(url.pathname);
454
+ const scope = match?.[1];
455
+ const number = Number(match?.[2]);
456
+ return scope && Number.isSafeInteger(number) && number > 0
457
+ ? { host: url.hostname.toLowerCase(), scope: scope.toLowerCase(), key: String(number) }
458
+ : null;
459
+}
460
+
461
/** Reads a repository page from `url` with `route`, whose first group is the repository path. */
462
export function repositoryUrlFromPagePath(url: URL, route: RegExp): string | null {
463
const repository = route.exec(url.pathname)?.[1];
@@ -646,6 +670,10 @@ export interface SourceControlDefinitionRegistry {
670
readonly findByPublicDomain: (hostname: string) => SourceControlDefinition | undefined;
671
/** The first host, in registry order, that reads `url` as one of its change requests. */
672
readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null;
673
+ /** The first host, in registry order, that reads `url` as one of its issues. */
674
+ readonly parseIssueUrl: (
675
+ url: string,
676
+ ) => { readonly definition: SourceControlDefinition; readonly link: IssueLink } | null;
677
readonly parseCommitUrl: (url: string, kind?: SourceControlProviderKind) => ParsedCommit | null;
678
readonly findByChangeRequestUrl: (url: string) => SourceControlDefinition | undefined;
679
readonly hostLabelForChangeRequestUrl: (url: string) => string;
@@ -764,6 +792,15 @@ export function makeSourceControlDefinitionRegistry(
792
);
793
},
794
parseChangeRequestUrl,
795
+ parseIssueUrl: (value) => {
796
+ const url = httpUrl(value);
797
+ if (url === null) return null;
798
+ for (const definition of claimOrder) {
799
+ const link = definition.parseIssueUrl?.(url) ?? null;
800
+ if (link !== null) return { definition, link };
801
+ }
802
+ return null;
803
+ },
804
parseCommitUrl: (value, kind) => {
805
const url = httpUrl(value);
806
if (url === null) return null;
packages/source-control-forgejo/src/shared/definition.ts
+14
-3
@@ -9,6 +9,7 @@ import {
9
isChangeRequestInProjectRepository,
10
isChangeRequestOnProjectHost,
11
parseChangeRequestPath,
12
+ parseIssuePath,
13
parseCommitPath,
14
repositoryUrlFromPagePath,
15
projectChangeRequestHost,
@@ -23,10 +24,20 @@ const CHANGE_REQUEST_REFERENCE =
24
// Forgejo and Gitea run on any hostname, possibly mounted below a path.
25
const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u;
26
const COMMIT_PATH = /^\/([^/]+(?:\/[^/]+)+)\/commit\/([0-9a-f]+)\/?$/iu;
27
+const ISSUE_PATH = /^\/([^/]+(?:\/[^/]+)+)\/issues\/(\d+)(?:\/|$)/u;
28
const REPOSITORY_PAGE_PATH = /^\/([^/]+(?:\/[^/]+)+?)\/src\/(?:branch|tag|commit)\/[^/]/u;
29
30
const KIND = SourceControlProviderKind.make("forgejo");
31
32
+function isForgejoHost(hostname: string): boolean {
33
+ const host = hostname.toLowerCase();
34
+ return (
35
+ host === "codeberg.org" ||
36
+ host.split(".").includes("forgejo") ||
37
+ host.split(".").includes("gitea")
38
+ );
39
+}
40
+
41
const changeRequestHeadRef = (number: number) => `refs/pull/${number}/head`;
42
43
/**
@@ -88,6 +99,8 @@ export const definition = defineSourceControl({
99
const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH);
100
return link === null ? null : { ...link, authority: url.host.toLowerCase() };
101
},
102
+ // `/issues/` is too generic a path to believe from a host not named after Forgejo or Gitea.
103
+ parseIssueUrl: (url) => (isForgejoHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null),
104
changeRequestUrlFromReferenceAutolink: () => null,
105
commitUrl: (input) => buildCommitUrl(input, "commit"),
106
parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH),
@@ -115,9 +128,7 @@ export const definition = defineSourceControl({
128
checkoutChangeRequestHost: () => null,
129
changeRequestHeadRef,
130
recognizeRemote: ({ remoteUrl, host, hostname }) =>
118
- hostname === "codeberg.org" ||
119
- hostname.split(".").includes("forgejo") ||
120
- hostname.split(".").includes("gitea")
131
+ isForgejoHost(hostname)
132
? {
133
kind: KIND,
134
name: "Forgejo",
packages/source-control-github/src/shared/definition.ts
+3
@@ -7,6 +7,7 @@ import {
7
isChangeRequestInProjectRepository,
8
isChangeRequestOnProjectHost,
9
parseChangeRequestPath,
10
+ parseIssuePath,
11
parseCommitPath,
12
repositoryUrlFromPagePath,
13
projectChangeRequestHost,
@@ -100,6 +101,8 @@ export const definition = defineSourceControl({
101
parseCommitUrl: (url, known) =>
102
known || isGitHubHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null,
103
parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH),
104
+ // `/issues/` is too generic a path to believe from a host that is not GitHub's.
105
+ parseIssueUrl: (url) => (isGitHubHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null),
106
repositoryUrlFromPage: (url) =>
107
isGitHubHost(url.hostname) ? repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH) : null,
108
// GitHub writes every bare reference through `/issues/`, including pull requests.
packages/source-control-gitlab/src/shared/definition.ts
+3
@@ -6,6 +6,7 @@ import {
6
isChangeRequestInProjectRepository,
7
isChangeRequestOnProjectHost,
8
parseChangeRequestPath,
9
+ parseIssuePath,
10
parseCommitPath,
11
repositoryUrlFromPagePath,
12
projectChangeRequestHost,
@@ -21,6 +22,7 @@ const CHANGE_REQUEST_REFERENCE =
22
// Self-managed GitLab runs on any hostname and nests projects in groups.
23
const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u;
24
const COMMIT_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/commit\/([0-9a-f]+)\/?$/iu;
25
+const ISSUE_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/(?:issues|work_items)\/(\d+)(?:\/|$)/u;
26
// Every GitLab page inside a project sits below its first `/-/`.
27
const REPOSITORY_PAGE_PATH = /^\/([^/]+(?:\/[^/]+)+?)\/-\//u;
28
@@ -48,6 +50,7 @@ export const definition = defineSourceControl({
50
? changeRequestUrlBelow(webUrl, `-/merge_requests/${number}`)
51
: `${remoteWebOrigin(host, remoteUrl)}/${repository}/-/merge_requests/${number}`,
52
parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH),
53
+ parseIssueUrl: (url) => parseIssuePath(url, ISSUE_PATH),
54
commitUrl: (input) => buildCommitUrl(input, "-/commit"),
55
parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH),
56
repositoryUrlFromPage: (url) => repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH),