diff --git a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx index 43d5af0363558..38e2193163c5c 100644 --- a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx +++ b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx @@ -220,12 +220,28 @@ export function IssueTrackerProjectRows(props: { const [binding, setBinding] = useState(null); const change = async (projectId: ProjectId, scope: string) => { if (props.disabled || binding !== null) return; + const bound = props.bindings[projectId]; + const current = + bound?.tracker === tracker.tracker ? [bound.scope, ...(bound.additionalScopes ?? [])] : []; + const scopes = + scope === UNBOUND + ? [] + : current.includes(scope) + ? current.filter((key) => key !== scope) + : [...current, scope]; setBinding(projectId); await bind({ environmentId, input: { projectId, - binding: scope === UNBOUND ? null : { tracker: tracker.tracker, scope }, + binding: + scopes.length === 0 + ? null + : { + tracker: tracker.tracker, + scope: scopes[0]!, + additionalScopes: scopes.slice(1), + }, }, }); setBinding(null); @@ -233,7 +249,8 @@ export function IssueTrackerProjectRows(props: { return projects.map((project) => { const bound = props.bindings[project.id]; // A project bound to another tracker keeps that binding; this row shows it unbound. - const value = bound?.tracker === tracker.tracker ? bound.scope : UNBOUND; + const value = + bound?.tracker === tracker.tracker ? [bound.scope, ...(bound.additionalScopes ?? [])] : []; const locked = props.disabled || binding !== null; return ( ({ id: scope.key, title: `${scope.name} (${scope.key})`, - state: scope.key === value ? ("on" as const) : ("off" as const), + state: value.includes(scope.key) ? ("on" as const) : ("off" as const), attributes: { disabled: locked }, })), ]} @@ -264,9 +281,11 @@ export function IssueTrackerProjectRows(props: { label={project.title} valuePosition="trailing" value={ - value === UNBOUND + value.length === 0 ? gt("Not bound") - : (tracker.scopes.find((scope) => scope.key === value)?.name ?? value) + : value + .map((key) => tracker.scopes.find((scope) => scope.key === key)?.name ?? key) + .join(", ") } disabled={locked} /> diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 2e260451de2d7..abe1bed0511a9 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -502,6 +502,94 @@ describe("IssueService with a standalone tracker", () => { }), ); + it.effect( + "lists and searches every bound team, continues each separately, and permits writes only in bound teams", + () => + Effect.gen(function* () { + const listed: Array<{ scope: string; query?: string; cursor?: string }> = []; + const created: string[] = []; + const service = yield* makeService({ + projects: [project({ id: "web", repository: "acme/web" })], + trackers: [ + fakeTracker(), + fakeStandaloneTracker({ + listIssues: (input) => + Effect.sync(() => { + listed.push({ + scope: input.scope, + ...(input.query ? { query: input.query } : {}), + ...(input.cursor ? { cursor: input.cursor } : {}), + }); + return { + items: [issue(`${input.scope}-1`)], + nextCursor: input.cursor ? null : `${input.scope}-next`, + }; + }), + create: (input) => + Effect.sync(() => { + created.push(input.scope); + return { + key: `${input.scope}-2`, + displayKey: `${input.scope}-2`, + url: `https://linear.app/acme/issue/${input.scope}-2`, + }; + }), + }), + ], + bindings: { + web: { tracker: LINEAR, scope: "ENG", additionalScopes: ["OPS", "eng", "ops"] }, + }, + }); + const first = yield* service.list({ state: "open", query: "cache" }); + expect(listed).toEqual([ + { scope: "ENG", query: "cache" }, + { scope: "OPS", query: "cache" }, + ]); + expect( + first.scopes?.filter((ref) => ref.tracker === LINEAR).map((ref) => ref.scope), + ).toEqual(["ENG", "OPS"]); + expect(first.trackers.find((tracker) => tracker.tracker === LINEAR)?.projectCount).toBe(1); + expect(first.nextCursors).toEqual({ + "linear.app eng": "ENG-next", + "linear.app ops": "OPS-next", + }); + listed.length = 0; + yield* service.list({ + state: "open", + query: "cache", + cursors: { "linear.app ops": "OPS-next" }, + }); + expect(listed).toEqual([{ scope: "OPS", query: "cache", cursor: "OPS-next" }]); + const projectId = "web" as ProjectId; + expect((yield* service.projectScope(projectId)).scope).toBe("ENG"); + expect((yield* service.projectScope(projectId, "ops")).scope).toBe("OPS"); + const keyOnlyScope = yield* service.projectScope(projectId, undefined, "OPS-12"); + expect(keyOnlyScope.scope).toBe("OPS"); + yield* service.comment({ ...keyOnlyScope, key: "OPS-12", body: "Please check this." }); + expect(yield* Effect.flip(service.projectScope(projectId, "OTHER"))).toMatchObject({ + _tag: "IssueOperationError", + operation: "projectScope", + }); + for (const scope of ["ENG", "OPS", "OTHER"]) { + const ref = { projectId, tracker: LINEAR, scope }; + expect((yield* service.detail({ ...ref, key: `${scope}-1` })).writable).toBe( + scope !== "OTHER", + ); + const create = service.create({ + ...ref, + title: "Cache", + body: "", + labels: [], + assignees: [], + }); + if (scope === "OTHER") { + expect(yield* Effect.flip(create)).toMatchObject({ reason: "read-only" }); + } else yield* create; + } + expect(created).toEqual(["ENG", "OPS"]); + }), + ); + it.effect("lists a bound project's standalone scope beside its git host and serves both", () => Effect.gen(function* () { const listed: string[] = []; diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index bf3d301f73708..c4dc479a96333 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -163,6 +163,8 @@ export class IssueService extends Context.Service< /** The tracker and container a project's own issues live in. */ readonly projectScope: ( projectId: ProjectId, + scope?: string, + key?: string, ) => Effect.Effect; /** * Resolve through a matching project, preferring `preferredProjectId`; other scopes are read-only. @@ -192,17 +194,21 @@ const make = Effect.gen(function* () { // Read per resolution so a binding saved in Settings applies without a restart. const resolveStandaloneBinding = ( project: OrchestrationProjectShell, - ): Effect.Effect => + ): Effect.Effect, IssueOperationError> => bindings.list.pipe( Effect.map((bound) => { const binding = bound.get(project.id); const api = binding === undefined ? null : registry.get(binding.tracker); - if (binding === undefined || api === null || !isStandaloneIssueTracker(api)) return null; - return { + if (binding === undefined || api === null || !isStandaloneIssueTracker(api)) return []; + const scopes = new Map(); + for (const scope of [binding.scope, ...(binding.additionalScopes ?? [])]) { + if (!scopes.has(scope.toLowerCase())) scopes.set(scope.toLowerCase(), scope); + } + return [...scopes.values()].map((scope) => ({ tracker: binding.tracker, host: api.standalone.host, - scope: binding.scope, - }; + scope, + })); }), // A failed read is not an unbound project: that would list the git host's issues alone. Effect.mapError( @@ -232,7 +238,11 @@ const make = Effect.gen(function* () { resolveGitHostBinding({ ...project, repositoryIdentity }), ), ), - ]).pipe(Effect.map((resolved) => resolved.filter((binding) => binding !== null))); + ]).pipe( + Effect.map(([standalone, gitHost]) => + gitHost === null ? standalone : [...standalone, gitHost], + ), + ); const listProjects = (filter: { readonly projectId?: IssueListInput["projectId"]; @@ -306,7 +316,12 @@ const make = Effect.gen(function* () { return Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" })); } const scope = ref.scope.trim(); - const writable = scope.toLowerCase() === own.scope.toLowerCase(); + const writable = supported.some( + (candidate) => + candidate.tracker === own.tracker && + candidate.host === own.host && + candidate.scope.toLowerCase() === scope.toLowerCase(), + ); return Effect.succeed({ ...own, scope, writable }); }), ); @@ -354,7 +369,11 @@ const make = Effect.gen(function* () { } // Every project counts, including worktrees of a scope read once below. + const countedProjects = new Set(); for (const project of supported) { + const key = `${project.host} ${project.project.id}`; + if (countedProjects.has(key)) continue; + countedProjects.add(key); const existing = trackers.get(project.host); trackers.set( project.host, @@ -651,12 +670,26 @@ const make = Effect.gen(function* () { const projectScope: IssueService["Service"]["projectScope"] = Effect.fn( "IssueService.projectScope", - )(function* (projectId) { + )(function* (projectId, scope, key) { const { supported } = yield* listProjects({ projectId }); - const [own] = supported; - if (own === undefined) { + if (supported.length === 0) { return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); } + const keyScope = key?.match(/^(.+)-\d+$/)?.[1]?.toLowerCase(); + const own = + scope === undefined + ? (supported.find((candidate) => candidate.scope.toLowerCase() === keyScope) ?? + supported[0]) + : supported.find( + (candidate) => candidate.scope.toLowerCase() === scope.trim().toLowerCase(), + ); + if (own === undefined) { + return yield* new IssueOperationError({ + operation: "projectScope", + detail: + "This project is not bound to that issue scope. Use list_issues to find its bound scopes.", + }); + } return { projectId, tracker: own.tracker, host: own.host, scope: own.scope }; }); diff --git a/apps/server/src/issue/IssueTrackerConnections.ts b/apps/server/src/issue/IssueTrackerConnections.ts index 9e9a0fae3447b..a0a629e18e90d 100644 --- a/apps/server/src/issue/IssueTrackerConnections.ts +++ b/apps/server/src/issue/IssueTrackerConnections.ts @@ -38,7 +38,7 @@ export class IssueTrackerConnections extends Context.Service< readonly connect: ( input: IssueTrackerConnectInput, ) => Effect.Effect; - /** Binds a project to one of a tracker's scopes, or unbinds it with a null binding. */ + /** Binds a project's default and additional scopes, or unbinds it with a null binding. */ readonly bindProject: ( input: IssueTrackerBindProjectInput, ) => Effect.Effect; diff --git a/apps/server/src/mcp/toolkits/issues/handlers.ts b/apps/server/src/mcp/toolkits/issues/handlers.ts index 1b4235ec7565b..7b4e8cbfa5adb 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.ts @@ -90,14 +90,18 @@ const make = Effect.gen(function* () { /** Where a key-only reference is read: the named project's tracker, or the caller's thread's. */ const requireProjectScope = Effect.fn("IssuesToolkit.requireProjectScope")(function* ( requested: ProjectId | undefined, + scope?: string, + key?: string, ) { // A named project skips the caller's thread, so the capability is checked here too. yield* McpInvocationContext.requireMcpCapability("issues"); const projectId = requested ?? (yield* callerThread())?.projectId; if (projectId === undefined) return yield* new IssueProjectRequiredError(); - return yield* issues - .projectScope(projectId) - .pipe(Effect.mapError(() => new IssueProjectNotFoundError({ projectId }))); + return yield* issues.projectScope(projectId, scope, key).pipe( + Effect.catchTags({ + IssueUnavailableError: () => Effect.fail(new IssueProjectNotFoundError({ projectId })), + }), + ); }); /** @@ -115,7 +119,7 @@ const make = Effect.gen(function* () { return { ...resolved, url: input.url } satisfies ResolvedTarget; } if (input.key === undefined) return yield* new IssueTargetIncompleteError(); - const scope = yield* requireProjectScope(input.projectId); + const scope = yield* requireProjectScope(input.projectId, undefined, input.key); return { ...scope, key: input.key, @@ -230,7 +234,7 @@ const make = Effect.gen(function* () { ), create_issue: McpToolAccess.writesWithCapability((input) => Effect.gen(function* () { - const scope = yield* requireProjectScope(input.projectId); + const scope = yield* requireProjectScope(input.projectId, input.scope); const created = yield* issues.create({ ...scope, title: input.title, diff --git a/apps/server/src/mcp/toolkits/issues/tools.ts b/apps/server/src/mcp/toolkits/issues/tools.ts index 20de86b1f9dea..abcdec93c80a6 100644 --- a/apps/server/src/mcp/toolkits/issues/tools.ts +++ b/apps/server/src/mcp/toolkits/issues/tools.ts @@ -240,7 +240,7 @@ export type ListThreadIssuesResult = typeof ListThreadIssuesResult.Type; const ListIssuesTool = Tool.make("list_issues", { description: - "List issues in a project's tracker, newest updated first. Pass the returned nextCursors as cursors for the next page.", + "List project tracker issues, newest updated first. Page with nextCursors as cursors.", parameters: Schema.Struct({ projectId: Schema.optional( ProjectId.annotate({ description: "Defaults to this thread's project." }), @@ -284,6 +284,12 @@ const CreateIssueTool = Tool.make("create_issue", { projectId: Schema.optional( ProjectId.annotate({ description: "Defaults to this thread's project." }), ), + scope: Schema.optional( + TrimmedNonEmptyString.annotate({ + description: + "A bound team key or repository scope from list_issues. Defaults to the project's default scope.", + }), + ), title: TrimmedNonEmptyString.check(Schema.isMaxLength(1024)), body: Schema.optional(Schema.String.check(Schema.isMaxLength(65_536))), labels: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(50))), diff --git a/apps/server/src/persistence/IssueTrackerBindings.ts b/apps/server/src/persistence/IssueTrackerBindings.ts index f5e5f62d81926..e28444009d092 100644 --- a/apps/server/src/persistence/IssueTrackerBindings.ts +++ b/apps/server/src/persistence/IssueTrackerBindings.ts @@ -16,11 +16,13 @@ const BindingRow = Schema.Struct({ projectId: ProjectId, tracker: IssueTrackerKind, scope: Schema.String, + additionalScopes: Schema.fromJsonString(Schema.Array(Schema.String)), }); +const encodeAdditionalScopes = Schema.encodeEffect(BindingRow.fields.additionalScopes); /** - * Which standalone issue tracker scope each project reads beside its git host's own issues. A - * project is bound to one scope at most, and only while it has a row. + * Which standalone issue tracker scopes each project reads beside its git host's own issues. A + * project has one default scope and may read additional scopes of the same tracker. */ export class IssueTrackerBindingsRepository extends Context.Service< IssueTrackerBindingsRepository, @@ -58,7 +60,8 @@ const make = Effect.gen(function* () { Result: BindingRow, execute: () => sql` - SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope" + SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope", + additional_scopes AS "additionalScopes" FROM issue_tracker_bindings `, }); @@ -68,25 +71,41 @@ const make = Effect.gen(function* () { Effect.map( (rows) => new Map( - rows.map((row) => [row.projectId, { tracker: row.tracker, scope: row.scope }] as const), + rows.map( + (row) => + [ + row.projectId, + { + tracker: row.tracker, + scope: row.scope, + ...(row.additionalScopes.length === 0 + ? {} + : { additionalScopes: row.additionalScopes }), + }, + ] as const, + ), ), ), Effect.mapError(toSqlOrDecodeError("listIssueTrackerBindings", "IssueTrackerBinding")), ), set: Effect.fn("IssueTrackerBindingsRepository.set")( function* (input) { - yield* input.binding === null - ? sql`DELETE FROM issue_tracker_bindings WHERE project_id = ${input.projectId}` - : sql` - INSERT INTO issue_tracker_bindings (project_id, tracker, scope, updated_at) - VALUES (${input.projectId}, ${input.binding.tracker}, ${input.binding.scope}, ${input.updatedAt}) + if (input.binding === null) { + yield* sql`DELETE FROM issue_tracker_bindings WHERE project_id = ${input.projectId}`; + return; + } + const additionalScopes = yield* encodeAdditionalScopes( + input.binding.additionalScopes ?? [], + ); + yield* sql` + INSERT INTO issue_tracker_bindings (project_id, tracker, scope, additional_scopes, updated_at) + VALUES (${input.projectId}, ${input.binding.tracker}, ${input.binding.scope}, ${additionalScopes}, ${input.updatedAt}) ON CONFLICT (project_id) - DO UPDATE SET tracker = excluded.tracker, scope = excluded.scope, updated_at = excluded.updated_at + DO UPDATE SET tracker = excluded.tracker, scope = excluded.scope, + additional_scopes = excluded.additional_scopes, updated_at = excluded.updated_at `; }, - Effect.mapError( - (cause) => new PersistenceSqlError({ operation: "setIssueTrackerBinding", cause }), - ), + Effect.mapError(toSqlOrDecodeError("setIssueTrackerBinding", "IssueTrackerBinding")), ), removeTracker: Effect.fn("IssueTrackerBindingsRepository.removeTracker")( function* (tracker) { diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index e2c62dd793796..73d716462e49c 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -106,6 +106,7 @@ import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts"; import Migration0096 from "./Migrations/096_RepairStaleTitleRegeneration.ts"; import Migration0097 from "./Migrations/097_IssueTrackerBindings.ts"; import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts"; +import Migration0099 from "./Migrations/099_IssueTrackerAdditionalScopes.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -207,6 +208,7 @@ const migrationEntries = [ [96, "RepairStaleTitleRegeneration", Migration0096], [97, "IssueTrackerBindings", Migration0097], [98, "ActiveShellIndexIndexes", Migration0098], + [99, "IssueTrackerAdditionalScopes", Migration0099], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/099_IssueTrackerAdditionalScopes.test.ts b/apps/server/src/persistence/Migrations/099_IssueTrackerAdditionalScopes.test.ts new file mode 100644 index 0000000000000..f1afd29cd9bb9 --- /dev/null +++ b/apps/server/src/persistence/Migrations/099_IssueTrackerAdditionalScopes.test.ts @@ -0,0 +1,43 @@ +import { assert, it } from "@effect/vitest"; +import { IssueTrackerKind, ProjectId } from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as IssueTrackerBindings from "../IssueTrackerBindings.ts"; +import { runMigrations } from "../Migrations.ts"; + +it.layer(NodeSqliteClient.layer({ filename: ":memory:" }))( + "099_IssueTrackerAdditionalScopes", + (it) => { + it.effect( + "preserves existing bindings and persists, replaces, and removes additional teams", + () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 98 }); + yield* sql`INSERT INTO issue_tracker_bindings VALUES ('web', 'linear', 'ENG', '2026-11-17')`; + yield* runMigrations(); + const repository = yield* IssueTrackerBindings.IssueTrackerBindingsRepository.pipe( + Effect.provide(IssueTrackerBindings.layer), + ); + const projectId = ProjectId.make("web"); + const binding = { tracker: IssueTrackerKind.make("linear"), scope: "ENG" }; + assert.deepStrictEqual((yield* repository.list).get(projectId), binding); + yield* repository.set({ + projectId, + binding: { ...binding, additionalScopes: ["OPS"] }, + updatedAt: "2026-11-17", + }); + assert.deepStrictEqual((yield* repository.list).get(projectId), { + ...binding, + additionalScopes: ["OPS"], + }); + yield* repository.set({ projectId, binding, updatedAt: "2026-11-17" }); + assert.deepStrictEqual((yield* repository.list).get(projectId), binding); + yield* repository.set({ projectId, binding: null, updatedAt: "2026-11-17" }); + assert.strictEqual((yield* repository.list).size, 0); + }), + ); + }, +); diff --git a/apps/server/src/persistence/Migrations/099_IssueTrackerAdditionalScopes.ts b/apps/server/src/persistence/Migrations/099_IssueTrackerAdditionalScopes.ts new file mode 100644 index 0000000000000..aa4656e52d291 --- /dev/null +++ b/apps/server/src/persistence/Migrations/099_IssueTrackerAdditionalScopes.ts @@ -0,0 +1,9 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + ALTER TABLE issue_tracker_bindings ADD COLUMN additional_scopes TEXT NOT NULL DEFAULT '[]' + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index fbe47613c87e0..e4751a80acbb7 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -78,6 +78,7 @@ describe("V2 preview upgrade", () => { [96, "RepairStaleTitleRegeneration"], [97, "IssueTrackerBindings"], [98, "ActiveShellIndexIndexes"], + [99, "IssueTrackerAdditionalScopes"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -199,6 +200,7 @@ describe("V2 preview upgrade", () => { [96, "RepairStaleTitleRegeneration"], [97, "IssueTrackerBindings"], [98, "ActiveShellIndexIndexes"], + [99, "IssueTrackerAdditionalScopes"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 9c305c266f3dd..cf2f6d55d832b 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 52145 + "mcpToolListJsonBytes": 52138 } diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx index a397a84439f7a..812be49355f73 100644 --- a/apps/web/src/components/settings/IssueTrackerSettings.tsx +++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx @@ -38,7 +38,7 @@ const UNBOUND = ""; /** * Standalone issue trackers for one environment: connect each with a credential, and bind the - * environment's projects to one of the tracker's scopes so their issues list beside the git + * environment's projects to the tracker's scopes so their issues list beside the git * host's. Generic over the trackers the server reports; nothing here names Linear but its icon. */ export function IssueTrackerSettings({ environmentId }: { readonly environmentId: EnvironmentId }) { @@ -254,13 +254,21 @@ function ProjectBindings({ const [pending, setPending] = useState(null); if (projects.length === 0 || tracker.scopes.length === 0) return null; - const change = async (projectId: ProjectId, scope: string) => { + const change = async (projectId: ProjectId, scopes: string[]) => { + if (pending !== null) return; setPending(projectId); await bind({ environmentId, input: { projectId, - binding: scope === UNBOUND ? null : { tracker: tracker.tracker, scope }, + binding: + scopes.length === 0 + ? null + : { + tracker: tracker.tracker, + scope: scopes[0]!, + additionalScopes: scopes.slice(1), + }, }, }); setPending(null); @@ -271,24 +279,28 @@ function ProjectBindings({ {projects.map((project) => { const bound = bindings[project.id]; // A project bound to another tracker keeps that binding; this picker shows it unbound. - const value = bound?.tracker === tracker.tracker ? bound.scope : UNBOUND; + const value = + bound?.tracker === tracker.tracker + ? [bound.scope, ...(bound.additionalScopes ?? [])] + : []; return ( { - if (next !== null) void change(project.id, next); + if (next !== null) void change(project.id, next.includes(UNBOUND) ? [] : next); }} > - {value === UNBOUND + {value.length === 0 ? gt("Not bound") - : (tracker.scopes.find((scope) => scope.key === value)?.name ?? value)} + : value + .map( + (key) => tracker.scopes.find((scope) => scope.key === key)?.name ?? key, + ) + .join(", ")} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 4c9f0f6d27e4f..6b3cc78e36507 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -8387,7 +8387,7 @@ "58e0e226493150e7": "Issue-Tracker konnten nicht geladen werden", "77cfcbde543df32d": "Details zu {tracker} ein-/ausblenden", "0083f65885c60156": "{tracker} trennen", - "15ad0159a826b290": "Wähle das {scope} in {tracker}, dessen Issues jedes Projekt neben denen seines eigenen Repositorys auflistet.", + "0b11ec065c184482": "Wähle für jedes Projekt einen oder mehrere {tracker}-{scope}s aus. Die erste Auswahl ist der Standard, wenn Agenten Issues erstellen.", "19c2d5e81ff8f89a": "{tracker} {scope} für {project}", "68e061510b765772": "Nicht zugeordnet", "a2d95d39d3398bda": "Anmeldedaten abgelehnt", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index c40470b46e6ae..6fe682017b21e 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -8395,7 +8395,7 @@ "58e0e226493150e7": "Could not load issue trackers", "77cfcbde543df32d": "Toggle {tracker} details", "0083f65885c60156": "Disconnect {tracker}", - "15ad0159a826b290": "Pick the {tracker} {scope} whose issues each project lists beside its repository's own.", + "0b11ec065c184482": "Pick one or more {tracker} {scope}s for each project. The first selected is the default for agents creating issues.", "19c2d5e81ff8f89a": "{tracker} {scope} for {project}", "68e061510b765772": "Not bound", "a2d95d39d3398bda": "Credential rejected", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 68f63f589f51e..08cac84ff16f8 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -8385,7 +8385,7 @@ "58e0e226493150e7": "No se pudieron cargar los gestores de issues", "77cfcbde543df32d": "Mostrar u ocultar detalles de {tracker}", "0083f65885c60156": "Desconectar {tracker}", - "15ad0159a826b290": "Elige el {scope} de {tracker} cuyas issues lista cada proyecto junto a las de su propio repositorio.", + "0b11ec065c184482": "Selecciona uno o más {scope}s de {tracker} para cada proyecto. El primero será el predeterminado cuando los agentes creen incidencias.", "19c2d5e81ff8f89a": "{scope} de {tracker} para {project}", "68e061510b765772": "Sin vincular", "a2d95d39d3398bda": "Credencial rechazada", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 442c22ed3a2d7..fef925fb5581c 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -8386,7 +8386,7 @@ "58e0e226493150e7": "Impossible de charger les gestionnaires de tickets", "77cfcbde543df32d": "Afficher ou masquer les détails de {tracker}", "0083f65885c60156": "Déconnecter {tracker}", - "15ad0159a826b290": "Choisissez le {scope} {tracker} dont chaque projet liste les tickets à côté de ceux de son propre dépôt.", + "0b11ec065c184482": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Le premier est utilisé par défaut lorsque les agents créent des tickets.", "19c2d5e81ff8f89a": "{scope} {tracker} pour {project}", "68e061510b765772": "Non lié", "a2d95d39d3398bda": "Identifiant refusé", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index c9417551b208c..11cb39687528b 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -8343,7 +8343,7 @@ "58e0e226493150e7": "Issue トラッカーを読み込めませんでした", "77cfcbde543df32d": "{tracker} の詳細を切り替え", "0083f65885c60156": "{tracker} を切断", - "15ad0159a826b290": "各プロジェクトがリポジトリ自身の Issue と並べて一覧表示する {tracker} の {scope} を選択します。", + "0b11ec065c184482": "各プロジェクトに1つ以上の{tracker}の{scope}を選択します。最初の選択は、エージェントが課題を作成する際のデフォルトになります。", "19c2d5e81ff8f89a": "{project} の {tracker} {scope}", "68e061510b765772": "未バインド", "a2d95d39d3398bda": "資格情報が拒否されました", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 362d29d071a87..f8a998c7656b3 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -8346,7 +8346,7 @@ "58e0e226493150e7": "이슈 트래커를 불러올 수 없습니다", "77cfcbde543df32d": "{tracker} 세부 정보 전환", "0083f65885c60156": "{tracker} 연결 끊기", - "15ad0159a826b290": "각 프로젝트가 저장소 자체 이슈와 함께 표시할 이슈의 {tracker} {scope}을(를) 선택하세요.", + "0b11ec065c184482": "각 프로젝트에 하나 이상의 {tracker} {scope}을 선택하세요. 첫 번째 선택은 에이전트가 이슈를 만들 때 기본값이 됩니다。", "19c2d5e81ff8f89a": "{project}의 {tracker} {scope}", "68e061510b765772": "바인딩되지 않음", "a2d95d39d3398bda": "자격 증명 거부됨", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index b598943e92383..ee9c6f4dab3ac 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -8385,7 +8385,7 @@ "58e0e226493150e7": "Não foi possível carregar os rastreadores de issues", "77cfcbde543df32d": "Mostrar ou ocultar detalhes de {tracker}", "0083f65885c60156": "Desconectar {tracker}", - "15ad0159a826b290": "Escolha o {scope} do {tracker} cujas issues cada projeto lista ao lado das do próprio repositório.", + "0b11ec065c184482": "Selecione um ou mais {scope}s do {tracker} para cada projeto. O primeiro será o padrão quando os agentes criarem issues.", "19c2d5e81ff8f89a": "{scope} do {tracker} para {project}", "68e061510b765772": "Não vinculado", "a2d95d39d3398bda": "Credencial recusada", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index a8a54a6500e59..81e3edef4666f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -8387,7 +8387,7 @@ "58e0e226493150e7": "Не удалось загрузить issue-трекеры", "77cfcbde543df32d": "Показать или скрыть подробности {tracker}", "0083f65885c60156": "Отключить {tracker}", - "15ad0159a826b290": "Выберите {scope} в {tracker}, issue которого каждый проект показывает рядом с issue своего репозитория.", + "0b11ec065c184482": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Первый используется по умолчанию, когда агенты создают задачи.", "19c2d5e81ff8f89a": "{tracker} {scope} для {project}", "68e061510b765772": "Не привязано", "a2d95d39d3398bda": "Учётные данные отклонены", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index adaf8566b6411..7ba3aa6cdfcdb 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -8393,7 +8393,7 @@ "58e0e226493150e7": "Kunde inte läsa in ärendehanterare", "77cfcbde543df32d": "Visa/dölj detaljer för {tracker}", "0083f65885c60156": "Koppla från {tracker}", - "15ad0159a826b290": "Välj den {scope} i {tracker} vars ärenden varje projekt listar bredvid repots egna.", + "0b11ec065c184482": "Välj en eller flera {tracker}-{scope} för varje projekt. Den första används som standard när agenter skapar ärenden.", "19c2d5e81ff8f89a": "{scope} i {tracker} för {project}", "68e061510b765772": "Inte kopplad", "a2d95d39d3398bda": "Autentiseringsuppgiften avvisades", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index f386e717a0614..908582c9f0678 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -8403,7 +8403,7 @@ "58e0e226493150e7": "无法加载 issue 跟踪器", "77cfcbde543df32d": "切换 {tracker} 详情", "0083f65885c60156": "断开 {tracker} 连接", - "15ad0159a826b290": "选择 {tracker} {scope},每个项目会在其仓库自身的 issue 旁列出它的 issue。", + "0b11ec065c184482": "为每个项目选择一个或多个 {tracker} {scope}。第一个选项是智能体创建问题时的默认选项。", "19c2d5e81ff8f89a": "{project} 的 {tracker} {scope}", "68e061510b765772": "未绑定", "a2d95d39d3398bda": "凭据被拒绝", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index f1a1454ff8dcc..f2e7b32a251ed 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -366,8 +366,12 @@ itself where it can search. Press **Load more** at the end of a group to read fu The **Views** menu saves and restores a search, filter, and sort setup, as it does for pull requests. -To list a Linear team's issues beside a project's, connect Linear with an API key under -Settings → Source control & issues, then choose the team for that project there. +To list Linear issues beside a project's, connect Linear with an API key under +Settings → Source control & issues, then select one or more teams for that project. +The first selected team is the default when an agent calls `create_issue`. Agents can pass +a team key as `scope` to choose another bound team. Issue keys such as `OPS-12` select their +bound team automatically. Deselect a team to stop listing it; deselect every team to unbind +the project. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/packages/client-runtime/src/state/issueTrackers.ts b/packages/client-runtime/src/state/issueTrackers.ts index 045f283f310ee..b69d0460acf9c 100644 --- a/packages/client-runtime/src/state/issueTrackers.ts +++ b/packages/client-runtime/src/state/issueTrackers.ts @@ -4,7 +4,7 @@ import { type IssueTrackerConnectionList, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import { Atom } from "effect/reactivity"; +import { Atom, AtomRegistry } from "effect/reactivity"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; @@ -14,7 +14,6 @@ import { createEnvironmentRpcQueryAtomFamily, } from "./runtime.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; -import * as Persistence from "../platform/persistence.ts"; /** * Standalone issue trackers (Linear, Jira) per environment: which are connected, as whom, which @@ -22,7 +21,7 @@ import * as Persistence from "../platform/persistence.ts"; * every mutation refreshes that query, so the settings page never shows a stale status. */ export function createIssueTrackerEnvironmentAtoms( - runtime: Atom.AtomRuntime, + runtime: Atom.AtomRuntime, ) { const commandScheduler = createAtomCommandScheduler(); const connections = createEnvironmentRpcQueryAtomFamily(runtime, { @@ -54,7 +53,17 @@ export function createIssueTrackerEnvironmentAtoms( scheduler: commandScheduler, concurrency: serialPerEnvironment, onSettled: (target, registry) => - Effect.sync(() => registry.refresh(refresh(target.environmentId))), + Effect.scoped( + Effect.gen(function* () { + const atom = refresh(target.environmentId); + yield* AtomRegistry.mount(registry, atom); + registry.refresh(atom); + yield* AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true }).pipe( + Effect.timeoutOption("5 seconds"), + Effect.ignore, + ); + }), + ), }), }; } diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index 97b5750872986..d96165c80da4e 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -49,6 +49,8 @@ import { EnvironmentRpcUnavailableError } from "../rpc/client.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import type * as RpcSession from "../rpc/session.ts"; import { createOrchestrationEnvironmentAtoms } from "./orchestration.ts"; +import { createCommandPermissions } from "./commandPermissions.ts"; +import { createIssueTrackerEnvironmentAtoms } from "./issueTrackers.ts"; import { createReviewEnvironmentAtoms } from "./review.ts"; import { createPreviewEnvironmentAtoms } from "./preview.ts"; import { createFilesystemEnvironmentAtoms } from "./filesystem.ts"; @@ -118,7 +120,9 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness" rpcSession, isFinal, onAnswer, + clock, }: { + readonly clock?: Clock.Clock; readonly refreshTrigger?: Atom.Atom; readonly onAnswer?: QueryAnswerHandler; readonly isFinal?: (value: A) => boolean; @@ -159,7 +163,10 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness" stateChanges: () => SubscriptionRef.changes(supervisorState), } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); const runtime = Atom.runtime( - Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), + Layer.mergeAll( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), + ...(clock === undefined ? [] : [Layer.succeed(Clock.Clock, clock)]), + ), ); const family = createEnvironmentQueryAtomFamily(runtime, { label: "test.environment-query", @@ -1848,3 +1855,46 @@ describe("persisted environment queries", () => { }), ); }); + +it.effect("releases tracker commands after a stalled binding refresh", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + let binds = 0; + const rpcSession = { + client: { + [WS_METHODS.issueTrackersBindProject]: () => + Effect.sync(() => { + binds++; + }), + [WS_METHODS.issueTrackersList]: () => + Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)), + }, + } as unknown as RpcSession.RpcSession; + const harness = yield* makeEnvironmentQueryHarness(Effect.void, { + rpcSession, + clock: yield* Clock.Clock, + }); + const registry = AtomRegistry.make(); + yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); + using _permission = vi + .spyOn( + createCommandPermissions(harness.runtime, WS_METHODS.issueTrackersBindProject), + "authorize", + ) + .mockReturnValue(Effect.void); + const command = createIssueTrackerEnvironmentAtoms(harness.runtime).bindProject; + const target = { + environmentId: QUERY_ENVIRONMENT.environmentId, + input: { projectId: ProjectId.make("project"), binding: null }, + }; + const first = command.run(registry, target); + yield* Deferred.await(started); + const second = command.run(registry, target); + expect(binds).toBe(1); + yield* TestClock.adjust("5 seconds"); + yield* Effect.promise(() => first); + yield* TestClock.adjust("5 seconds"); + yield* Effect.promise(() => second); + expect(binds).toBe(2); + }), +); diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 574399859d4f9..5cc1eb6d5321e 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -549,10 +549,14 @@ export const StandaloneIssueTrackerDescriptor = Schema.Struct({ }); export type StandaloneIssueTrackerDescriptor = typeof StandaloneIssueTrackerDescriptor.Type; -/** Which standalone tracker scope a project's issues come from, beside its git host's own. */ +/** The standalone tracker scopes a project reads beside its git host's own issues. */ export const IssueTrackerProjectBinding = Schema.Struct({ tracker: IssueTrackerKind, + /** The default scope for new issues and key-only references. */ scope: TrimmedNonEmptyString, + additionalScopes: Schema.optional( + Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(49)), + ), }); export type IssueTrackerProjectBinding = typeof IssueTrackerProjectBinding.Type; @@ -581,7 +585,7 @@ export type IssueTrackerConnection = typeof IssueTrackerConnection.Type; export const IssueTrackerConnectionList = Schema.Struct({ trackers: Schema.Array(IssueTrackerConnection), - /** Which standalone tracker scope each bound project reads; a project absent here reads none. */ + /** Which standalone tracker scopes each bound project reads; an absent project reads none. */ bindings: Schema.Record(ProjectId, IssueTrackerProjectBinding), }); export type IssueTrackerConnectionList = typeof IssueTrackerConnectionList.Type;