diff --git a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx index f368dcca2dfc..92e142fc27d1 100644 --- a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx +++ b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx @@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import type { StaticScreenProps } from "@react-navigation/native"; import { hasIssueTrackerTeams, + issueTrackerBindings, issueTrackerSummary, } from "@t3tools/client-runtime/state/issue-trackers"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; @@ -167,6 +168,7 @@ export function SettingsIssueTrackerRouteScreen({ }: StaticScreenProps<{ readonly environmentId: EnvironmentId; readonly tracker: string; + readonly accountId?: string; }>) { const gt = useGT(); const messages = useMessages(); @@ -176,9 +178,17 @@ export function SettingsIssueTrackerRouteScreen({ issueTrackerEnvironment.connections({ environmentId, input: {} }), ); const canEdit = useAtomValue(issueTrackerEnvironment.connect.permissionAtom(environmentId)); - const tracker = query.data?.trackers.find((entry) => entry.tracker === route.params.tracker); + const tracker = [...(query.data?.trackers ?? []), ...(query.data?.accounts ?? [])].find( + (entry) => entry.tracker === route.params.tracker && entry.accountId === route.params.accountId, + ); const disabled = !canWrite || !canEdit; const usable = tracker?.connected === true && tracker.account !== null; + const canAddAccount = + tracker !== undefined && + route.params.accountId === undefined && + (tracker.connected || + (query.data?.accounts ?? []).some((account) => account.tracker === tracker.tracker)) && + environment?.serverConfig.environment.capabilities.issueTrackerAccounts === true; return ( {!environment || !tracker ? ( @@ -186,7 +196,7 @@ export function SettingsIssueTrackerRouteScreen({ ) : ( <> - {issueTrackerSummary(tracker, query.data?.bindings ?? {}, messages)} + {issueTrackerSummary(tracker, issueTrackerBindings(query.data), messages)} - {usable && hasIssueTrackerTeams(tracker, query.data?.bindings ?? {}) ? ( + {usable && hasIssueTrackerTeams(tracker, issueTrackerBindings(query.data)) ? ( ) : null} + {canAddAccount ? ( + + + + ) : null} )} diff --git a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx index 285a9e801ab6..e5f20372c393 100644 --- a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx +++ b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx @@ -1,6 +1,7 @@ import { boundIssueTrackerScopes, issueTrackerBindingFor, + issueTrackerBindings, issueTrackerScopeOptions, issueTrackerSummary, } from "@t3tools/client-runtime/state/issue-trackers"; @@ -80,7 +81,11 @@ function EnvironmentTrackers(props: { const query = useEnvironmentQuery( issueTrackerEnvironment.connections({ environmentId, input: {} }), ); - const trackers = query.data?.trackers ?? []; + const firstAccounts = query.data?.trackers ?? []; + const trackers = firstAccounts.flatMap((tracker) => [ + tracker, + ...(query.data?.accounts ?? []).filter((account) => account.tracker === tracker.tracker), + ]); if (trackers.length === 0) { return query.error ? ( @@ -94,16 +99,21 @@ function EnvironmentTrackers(props: { {trackers.map((tracker, index) => ( } - label={tracker.displayName} - description={issueTrackerSummary(tracker, query.data?.bindings ?? {}, messages)} + label={ + tracker.workspace + ? `${tracker.displayName} · ${tracker.workspace}` + : tracker.displayName + } + description={issueTrackerSummary(tracker, issueTrackerBindings(query.data), messages)} ready={tracker.connected && tracker.account !== null} separated={index > 0} onPress={() => navigation.navigate("SettingsIssueTracker", { environmentId, tracker: tracker.tracker, + ...(tracker.accountId === undefined ? {} : { accountId: tracker.accountId }), }) } /> @@ -133,6 +143,8 @@ export function IssueTrackerCredentialForm(props: { readonly environmentId: EnvironmentId; readonly tracker: IssueTrackerConnection; readonly disabled: boolean; + /** Saves the credential as a new account instead of replacing this one's. */ + readonly addAccount?: boolean; }) { const gt = useGT(); const { environmentId, tracker } = props; @@ -143,7 +155,12 @@ export function IssueTrackerCredentialForm(props: { const submit = async (token: string | null) => { setBusy(true); setFailure(null); - const result = await connect({ environmentId, input: { tracker: tracker.tracker, token } }); + const result = await connect({ + environmentId, + input: props.addAccount + ? { tracker: tracker.tracker, token, addAccount: true } + : { tracker: tracker.tracker, accountId: tracker.accountId, token }, + }); setBusy(false); if (!AsyncResult.isFailure(result)) { setDraft(""); @@ -154,14 +171,13 @@ export function IssueTrackerCredentialForm(props: { }; const helpUrl = tracker.credential.helpUrl; const locked = props.disabled || busy; + const replacing = tracker.connected && !props.addAccount; return ( void tryOpenExternalUrl(helpUrl)} /> ) : null} - {tracker.connected ? ( + {replacing ? ( + } + /> + ); + } + return ( + {tracker.credential.label}} + description={gt("For the new {tracker} account.", { tracker: tracker.displayName })} + control={ + { + if (next.trim()) void onAdd(next.trim()).then((added) => added && setAdding(false)); + }} + /> + } + /> + ); +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0e48b30d674d..62a1a96b07cc 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12458,5 +12458,9 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "99d51127f573296b": "Weiteres Konto", + "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", + "99963c0142e17f00": "Für das neue {tracker}-Konto.", + "6d8e4ebc889bace9": "Konto hinzufügen" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e5d8d3dc2ed2..a8a62402875f 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12467,5 +12467,9 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "99d51127f573296b": "Another account", + "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", + "99963c0142e17f00": "For the new {tracker} account.", + "6d8e4ebc889bace9": "Add account" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 4a2868a7e97d..4e3ab4edfd9f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12453,5 +12453,9 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "99d51127f573296b": "Otra cuenta", + "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", + "99963c0142e17f00": "Para la nueva cuenta de {tracker}.", + "6d8e4ebc889bace9": "Añadir cuenta" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a0962e52bed3..d77a7600856b 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12458,5 +12458,9 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "99d51127f573296b": "Autre compte", + "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", + "99963c0142e17f00": "Pour le nouveau compte {tracker}.", + "6d8e4ebc889bace9": "Ajouter un compte" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 0c149c28fbe9..520eed10cec8 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12407,5 +12407,9 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "99d51127f573296b": "別のアカウント", + "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", + "99963c0142e17f00": "新しい {tracker} アカウント用です。", + "6d8e4ebc889bace9": "アカウントを追加" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c01191b387b4..35559321c961 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12402,5 +12402,9 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "99d51127f573296b": "다른 계정", + "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", + "99963c0142e17f00": "새 {tracker} 계정용입니다.", + "6d8e4ebc889bace9": "계정 추가" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5feb95d75c3d..5c1674add926 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12458,5 +12458,9 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "99d51127f573296b": "Outra conta", + "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", + "99963c0142e17f00": "Para a nova conta do {tracker}.", + "6d8e4ebc889bace9": "Adicionar conta" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 65a8eede879f..b12d4581b2ca 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12458,5 +12458,9 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "99d51127f573296b": "Другой аккаунт", + "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", + "99963c0142e17f00": "Для нового аккаунта {tracker}.", + "6d8e4ebc889bace9": "Добавить аккаунт" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 081857c5dae8..6617684d5c93 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12465,5 +12465,9 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "99d51127f573296b": "Ett konto till", + "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", + "99963c0142e17f00": "För det nya {tracker}-kontot.", + "6d8e4ebc889bace9": "Lägg till konto" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 17d0dd6a9330..859ccdbc0616 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12484,5 +12484,9 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "99d51127f573296b": "其他账号", + "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", + "99963c0142e17f00": "用于新的 {tracker} 账号。", + "6d8e4ebc889bace9": "添加账号" } diff --git a/docs/user/source-control.md b/docs/user/source-control.md index c04060ba831a..5d92ecc9e98a 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -412,7 +412,10 @@ To list Linear issues beside a project's, connect Linear with an API key under Settings → Source control & issues, then pick one or more teams for that project there. Pick another team at any time to add it; uncheck every team to unbind the project. Each team's issues appear in the Linear group of the issue list, sorted with the rest by last update, and -each can be loaded further on its own. Agents file new issues in the first team picked. +each can be loaded further on its own. Agents file new issues in the first team picked. Use +**Add account** in the same place (on mobile, the **Another account** form on Linear's page) to +connect another Linear workspace or user; each project reads its teams through the account you +picked them under. 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/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 66909fad1f05..d875ba58c276 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerAccountId, IssueTrackerKind, ProjectId, SourceControlProviderKind, @@ -127,6 +128,25 @@ describe("resolveIssueLinkTarget", () => { expect( resolveIssueLinkTarget({ url: "https://linear.app/acme/issue/WEB-17", projects }), ).toBeNull(); + + // A second account reaches its own workspace, through only the projects bound with it. + const accountId = IssueTrackerAccountId.make("second"); + const [p1, p2] = [ProjectId.make("p1"), ProjectId.make("p2")]; + const both = (url: string) => + resolveIssueLinkTarget({ + url, + projects, + trackers: { + ...trackers, + accounts: [{ ...trackers.trackers[0]!, accountId, workspace: "othercorp" }], + bindings: { [p1]: trackers.bindings[p1]! }, + accountBindings: { [p2]: { ...trackers.bindings[p2]!, accountId } }, + }, + })?.ref.projectId; + expect([ + both("https://linear.app/othercorp/issue/WEB-17"), + both("https://linear.app/acme/issue/WEB-17"), + ]).toEqual(["p2", "p1"]); }); it.each([ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 0b442d18c92b..4375848bc343 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -70,8 +70,8 @@ export function mayContainStandaloneIssueLink(text: string): boolean { /** * A standalone tracker link resolves through the project bound to its scope, else any bound to - * the tracker, and only when it names the workspace the credential reaches: team keys repeat - * across workspaces, so a link elsewhere stays an ordinary link. + * the tracker, and only through an account whose credential reaches the workspace it names: team + * keys repeat across workspaces, so a link elsewhere stays an ordinary link. */ function resolveStandaloneIssueLink( url: string, @@ -82,14 +82,23 @@ function resolveStandaloneIssueLink( const parsed = trackers === undefined ? null : parseStandaloneIssueLink(url); if (parsed === null || trackers === undefined) return null; const { tracker, link } = parsed; - const workspace = trackers.trackers.find( - (connection) => connection.tracker === tracker && connection.account !== null, - )?.workspace; - if (workspace?.toLowerCase() !== link.workspace.toLowerCase()) return null; - const { bindings } = trackers; + const accounts = new Set( + [...trackers.trackers, ...(trackers.accounts ?? [])] + .filter( + (connection) => + connection.tracker === tracker && + connection.account !== null && + connection.workspace?.toLowerCase() === link.workspace.toLowerCase(), + ) + .map((connection) => connection.accountId ?? null), + ); + if (accounts.size === 0) return null; + const bindings = { ...trackers.bindings, ...trackers.accountBindings }; const onTracker = projects.flatMap((project) => { const binding = bindings[project.id]; - return binding?.tracker === tracker ? [{ project, binding }] : []; + return binding?.tracker === tracker && accounts.has(binding.accountId ?? null) + ? [{ project, binding }] + : []; }); const preferFirst = (candidates: typeof onTracker) => candidates.find((candidate) => candidate.project.id === preferredProjectId) ?? candidates[0]; diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 5085c10e5188..49bab599b4f5 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -144,6 +144,35 @@ describe("issueFilterScopes", () => { expect(issueFilterScopes(held, [])).toEqual([{ environmentId, input: scope }]); }); + it("offers the same team key of two Linear accounts as two scopes", () => { + const first = { + projectId: api, + tracker: "linear" as IssueTrackerKind, + host: "linear.app", + scope: "ENG", + }; + const second = hold( + answer({ + trackers: [tracker({})], + scopes: [first, { ...first, projectId: "home" as ProjectId }], + }), + ); + const other = hold( + answer({ trackers: [tracker({})], scopes: [{ ...first, projectId: "o" as ProjectId }] }), + ); + // Older servers name no scopes; their rows stand in, once per team on that server. + const older = hold( + answer({ trackers: [tracker({})], entries: [linearRow, { ...linearRow, key: "ENG-2" }] }), + ); + const count = (...pages: ReadonlyArray>) => + issueFilterScopes( + new Map(pages.map((page, index) => [`env-${index}` as EnvironmentId, page])), + [], + ).length; + expect([count(second), count(second, other), count(other, second)]).toEqual([2, 3, 3]); + expect([count(older), count(older, second), count(second, older)]).toEqual([1, 3, 3]); + }); + it("skips a tracker that cannot be read", () => { const held = new Map([ [ diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index 5e01c4683830..1a99f54e0f58 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -170,6 +170,9 @@ export function issueFilterScopes( ) { const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> = []; + // A repository's scope is the same scope on every server. A bound tracker's scope is not: two + // accounts, or two servers, may both have an ENG team, so those are deduplicated per server only. + const fromRepository = new Set(); for (const [environmentId, page] of held) { for (const project of projects) { if (project.environmentId !== environmentId) continue; @@ -186,10 +189,9 @@ export function issueFilterScopes( ) ) continue; - scopes.push({ - environmentId, - input: { projectId: project.id, tracker: tracker.tracker, host, scope }, - }); + const input = { projectId: project.id, tracker: tracker.tracker, host, scope }; + fromRepository.add(input); + scopes.push({ environmentId, input }); } } // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope, @@ -209,9 +211,12 @@ export function issueFilterScopes( ); if (!tracker?.configured) continue; if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue; + // An answer names each scope once per account; rows standing in for one repeat. if ( scopes.some( (s) => + (fromRepository.has(s.input) || + (page.answer.scopes === undefined && s.environmentId === environmentId)) && s.input.scope.toLowerCase() === input.scope.toLowerCase() && s.input.host?.toLowerCase() === host, ) diff --git a/packages/client-runtime/src/state/issueTrackers.test.ts b/packages/client-runtime/src/state/issueTrackers.test.ts index 32d459bf79ed..ba2fba0ad1da 100644 --- a/packages/client-runtime/src/state/issueTrackers.test.ts +++ b/packages/client-runtime/src/state/issueTrackers.test.ts @@ -1,7 +1,15 @@ -import { IssueTrackerKind, MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES } from "@t3tools/contracts"; +import { + IssueTrackerAccountId, + IssueTrackerKind, + MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { issueTrackerScopeOptions } from "./issueTrackers.ts"; +import { + boundIssueTrackerScopes, + issueTrackerBindingFor, + issueTrackerScopeOptions, +} from "./issueTrackers.ts"; describe("issueTrackerScopeOptions", () => { it("offers no new team once the binding is full, and keeps bound ones removable", () => { @@ -34,3 +42,14 @@ describe("issueTrackerScopeOptions", () => { expect(issueTrackerScopeOptions(tracker, ["ENG"]).every((scope) => scope.addable)).toBe(true); }); }); + +describe("boundIssueTrackerScopes", () => { + it("keeps each account's teams apart, and binds new picks with that account", () => { + const tracker = IssueTrackerKind.make("linear"); + const second = { tracker, accountId: IssueTrackerAccountId.make("second") }; + const binding = issueTrackerBindingFor(second, [], ["ENG", "OPS"]) ?? undefined; + expect(binding).toEqual({ ...second, scope: "ENG", additionalScopes: ["OPS"] }); + expect(boundIssueTrackerScopes(second, binding)).toEqual(["ENG", "OPS"]); + expect(boundIssueTrackerScopes({ tracker }, binding)).toEqual([]); + }); +}); diff --git a/packages/client-runtime/src/state/issueTrackers.ts b/packages/client-runtime/src/state/issueTrackers.ts index a4bb5187f840..66496cf26f31 100644 --- a/packages/client-runtime/src/state/issueTrackers.ts +++ b/packages/client-runtime/src/state/issueTrackers.ts @@ -4,7 +4,6 @@ import { issueTrackerBindingScopes, type IssueTrackerConnection, type IssueTrackerConnectionList, - type IssueTrackerKind, type IssueTrackerProjectBinding, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -81,6 +80,21 @@ export function issueTrackerDetailText(detail: string, resolve: MFunctionType = return knownTrackerSentence(detail, SERVER_TRACKER_DETAILS, resolve); } +/** Every project's binding, whichever account it was made with. */ +export function issueTrackerBindings( + list: IssueTrackerConnectionList | null | undefined, +): IssueTrackerConnectionList["bindings"] { + return { ...list?.bindings, ...list?.accountBindings }; +} + +/** Whether a project binding reads through this account of the tracker. */ +function issueTrackerBindingIsFor( + binding: IssueTrackerProjectBinding, + tracker: Pick, +): boolean { + return binding.tracker === tracker.tracker && binding.accountId === tracker.accountId; +} + /** * The line under a tracker's name. A connected tracker lists nothing until a project is linked * to one of its scopes, so the line says how many are, and what to do when none is. @@ -98,8 +112,8 @@ export function issueTrackerSummary( ); if (tracker.account === null) return tracker.detail ?? resolve(msg("The saved credential was rejected.")); - const linked = Object.values(bindings).filter( - (binding) => binding.tracker === tracker.tracker, + const linked = Object.values(bindings).filter((binding) => + issueTrackerBindingIsFor(binding, tracker), ).length; return linked === 0 ? knownTrackerSentence( @@ -120,22 +134,31 @@ export function issueTrackerSummary( ); } +type TrackerAccount = Pick; + export function boundIssueTrackerScopes( - tracker: IssueTrackerKind, + tracker: TrackerAccount, binding: IssueTrackerProjectBinding | undefined, ): ReadonlyArray { - return binding?.tracker === tracker ? issueTrackerBindingScopes(binding) : []; + return binding !== undefined && issueTrackerBindingIsFor(binding, tracker) + ? issueTrackerBindingScopes(binding) + : []; } export function issueTrackerBindingFor( - tracker: IssueTrackerKind, + { tracker, accountId }: TrackerAccount, current: ReadonlyArray, scopes: ReadonlyArray, ): IssueTrackerProjectBinding | null { const kept = current.filter((key) => scopes.includes(key)); const [scope, ...additionalScopes] = [...kept, ...scopes.filter((key) => !kept.includes(key))]; if (scope === undefined) return null; - return additionalScopes.length === 0 ? { tracker, scope } : { tracker, scope, additionalScopes }; + return { + tracker, + ...(accountId === undefined ? {} : { accountId }), + scope, + ...(additionalScopes.length === 0 ? {} : { additionalScopes }), + }; } export function issueTrackerScopeOptions( @@ -156,6 +179,6 @@ export function hasIssueTrackerTeams( ): boolean { return ( tracker.scopes.length > 0 || - Object.values(bindings).some((binding) => binding.tracker === tracker.tracker) + Object.values(bindings).some((binding) => issueTrackerBindingIsFor(binding, tracker)) ); } diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 34c8688316ae..ddb62771932a 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -222,6 +222,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ linkedThreadRefreshes: Schema.optionalKey(Schema.Boolean), /** Answers `issues.linkedThreads`, the threads an issue is linked to. */ issueLinkedThreads: Schema.optionalKey(Schema.Boolean), + /** Keeps more than one account per standalone issue tracker; older servers keep one. */ + issueTrackerAccounts: Schema.optionalKey(Schema.Boolean), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 78b0cbb04b85..b282161fa668 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -30,6 +30,16 @@ export const IssueTrackerKind = TrimmedNonEmptyString.check( ).pipe(Schema.brand("IssueTrackerKind")); export type IssueTrackerKind = typeof IssueTrackerKind.Type; +/** + * One saved account of a standalone tracker. A tracker's first account has none: it predates + * accounts, and keeps its credential and bindings unchanged. + */ +export const IssueTrackerAccountId = TrimmedNonEmptyString.check( + Schema.isMaxLength(64), + Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/), +).pipe(Schema.brand("IssueTrackerAccountId")); +export type IssueTrackerAccountId = typeof IssueTrackerAccountId.Type; + export const IssueActor = PullRequestActor; export type IssueActor = typeof IssueActor.Type; @@ -580,6 +590,8 @@ export const MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES = 250; */ export const IssueTrackerProjectBinding = Schema.Struct({ tracker: IssueTrackerKind, + /** The account the scope is read with; absent for the tracker's first account. */ + accountId: Schema.optional(IssueTrackerAccountId), scope: TrimmedNonEmptyString, additionalScopes: Schema.optionalKey( Schema.Array(TrimmedNonEmptyString).check( @@ -607,6 +619,8 @@ export type IssueTrackerScope = typeof IssueTrackerScope.Type; */ export const IssueTrackerConnection = Schema.Struct({ ...StandaloneIssueTrackerDescriptor.fields, + /** Which of the tracker's accounts this is; absent for its first. */ + accountId: Schema.optional(IssueTrackerAccountId), /** A credential is stored. It may still be rejected, which `account` being null reports. */ connected: Schema.Boolean, /** Who the credential signs in as, or null when there is none or it was refused. */ @@ -620,15 +634,29 @@ export const IssueTrackerConnection = Schema.Struct({ export type IssueTrackerConnection = typeof IssueTrackerConnection.Type; export const IssueTrackerConnectionList = Schema.Struct({ + /** Each standalone tracker's first account. */ trackers: Schema.Array(IssueTrackerConnection), - /** Which standalone tracker scopes each bound project reads; a project absent here reads none. */ + /** The accounts added beside a tracker's first, oldest first. Absent from older servers. */ + accounts: Schema.optional(Schema.Array(IssueTrackerConnection)), + /** + * Which standalone tracker scopes each project bound with a tracker's first account reads. A + * project bound with an added account is in `accountBindings` instead, so older clients never + * read another account's team as the first account's. + */ bindings: Schema.Record(ProjectId, IssueTrackerProjectBinding), + /** Projects bound with an added account. Absent from older servers. */ + accountBindings: Schema.optional(Schema.Record(ProjectId, IssueTrackerProjectBinding)), }); export type IssueTrackerConnectionList = typeof IssueTrackerConnectionList.Type; -/** A credential for one standalone tracker; `null` disconnects it and unbinds its projects. */ +/** + * A credential for one standalone tracker account; `null` disconnects it and unbinds its + * projects. `addAccount` saves the credential as a new account beside the existing ones. + */ export const IssueTrackerConnectInput = Schema.Struct({ tracker: IssueTrackerKind, + accountId: Schema.optional(IssueTrackerAccountId), + addAccount: Schema.optional(Schema.Boolean), token: Schema.NullOr(TrimmedNonEmptyString.check(Schema.isMaxLength(4_096))), }); export type IssueTrackerConnectInput = typeof IssueTrackerConnectInput.Type; diff --git a/packages/source-control-core/src/server/IssueTrackerHost.ts b/packages/source-control-core/src/server/IssueTrackerHost.ts index efc51b5046de..4e814f18aeb5 100644 --- a/packages/source-control-core/src/server/IssueTrackerHost.ts +++ b/packages/source-control-core/src/server/IssueTrackerHost.ts @@ -2,12 +2,12 @@ * What a standalone tracker package may ask of the server it runs in: the credential the user * saved in Settings. Git-host trackers never need it; their CLIs carry their own credentials. */ -import type { IssueTrackerKind } from "@t3tools/contracts"; +import type { IssueTrackerAccountId, IssueTrackerKind } from "@t3tools/contracts"; import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; +import * as Effect from "effect/Effect"; import type * as Option from "effect/Option"; -import type { IssueTrackerError } from "./IssueTracker.ts"; +import type { IssueTrackerApi, IssueTrackerError } from "./IssueTracker.ts"; export class IssueTrackerHost extends Context.Service< IssueTrackerHost, @@ -20,3 +20,37 @@ export class IssueTrackerHost extends Context.Service< }; } >()("@t3tools/source-control-core/server/IssueTrackerHost") {} + +/** + * The account a standalone tracker call is made as, set by the server around each call; null is + * the tracker's first account. A tracker never reads it: `credentials.get` does. + */ +export const IssueTrackerAccount = Context.Reference( + "@t3tools/source-control-core/server/IssueTrackerHost/IssueTrackerAccount", + { defaultValue: () => null }, +); + +/** The tracker with every call made as one account, so no call site can forget to name it. */ +export function asIssueTrackerAccount( + api: IssueTrackerApi, + accountId: IssueTrackerAccountId | null, +): IssueTrackerApi { + if (accountId === null) return api; + const as = (effect: Effect.Effect) => + Effect.provideService(effect, IssueTrackerAccount, accountId); + const { create, comment, update, setState, setReaction, listTemplates, listCandidates } = api; + return { + ...api, + getViewer: (input) => as(api.getViewer(input)), + listIssues: (input) => as(api.listIssues(input)), + getIssue: (input) => as(api.getIssue(input)), + getComments: (input) => as(api.getComments(input)), + ...(create && { create: (input) => as(create(input)) }), + ...(comment && { comment: (input) => as(comment(input)) }), + ...(update && { update: (input) => as(update(input)) }), + ...(setState && { setState: (input) => as(setState(input)) }), + ...(setReaction && { setReaction: (input) => as(setReaction(input)) }), + ...(listTemplates && { listTemplates: (input) => as(listTemplates(input)) }), + ...(listCandidates && { listCandidates: (input) => as(listCandidates(input)) }), + }; +}