From 285e788b45ee32563c33dd0c06828c3f282c652a Mon Sep 17 00:00:00 2001
From: Bil0000 <62337003+Bil0000@users.noreply.github.com>
Date: Thu, 19 Nov 2026 16:50:18 +0100
Subject: [PATCH 1/5] feat(issues): connect more than one Linear account
---
...ettingsSourceControlDetailRouteScreens.tsx | 33 +++-
.../components/IssueTrackerSection.tsx | 54 ++++--
apps/mobile/src/i18n/translations/de.json | 4 +-
apps/mobile/src/i18n/translations/en.json | 4 +-
apps/mobile/src/i18n/translations/es.json | 4 +-
apps/mobile/src/i18n/translations/fr.json | 4 +-
apps/mobile/src/i18n/translations/ja.json | 4 +-
apps/mobile/src/i18n/translations/ko.json | 4 +-
apps/mobile/src/i18n/translations/pt-BR.json | 4 +-
apps/mobile/src/i18n/translations/ru.json | 4 +-
apps/mobile/src/i18n/translations/sv.json | 4 +-
apps/mobile/src/i18n/translations/zh.json | 4 +-
.../src/environment/ServerEnvironment.ts | 1 +
apps/server/src/issue/IssueService.test.ts | 142 ++++++++++++++
apps/server/src/issue/IssueService.ts | 176 ++++++++++++------
.../src/issue/IssueTrackerConnections.test.ts | 163 ++++++++++++++++
.../src/issue/IssueTrackerConnections.ts | 142 +++++++++++---
apps/server/src/issue/IssueTrackerHostLive.ts | 19 +-
.../src/persistence/IssueTrackerBindings.ts | 102 ++++++++--
apps/server/src/persistence/Migrations.ts | 2 +
.../Migrations/106_IssueTrackerAccounts.ts | 18 ++
.../reconcileV2PreviewMigration.test.ts | 2 +
.../settings/IssueTrackerSettings.tsx | 115 +++++++++---
apps/web/src/i18n/translations/de.json | 6 +-
apps/web/src/i18n/translations/en.json | 6 +-
apps/web/src/i18n/translations/es.json | 6 +-
apps/web/src/i18n/translations/fr.json | 6 +-
apps/web/src/i18n/translations/ja.json | 6 +-
apps/web/src/i18n/translations/ko.json | 6 +-
apps/web/src/i18n/translations/pt-BR.json | 6 +-
apps/web/src/i18n/translations/ru.json | 6 +-
apps/web/src/i18n/translations/sv.json | 6 +-
apps/web/src/i18n/translations/zh.json | 6 +-
docs/user/source-control.md | 4 +-
.../client-runtime/src/issueLinks.test.ts | 26 +++
packages/client-runtime/src/issueLinks.ts | 25 ++-
packages/client-runtime/src/issueList.test.ts | 55 ++++++
packages/client-runtime/src/issueList.ts | 13 +-
.../src/state/issueTrackers.test.ts | 23 ++-
.../client-runtime/src/state/issueTrackers.ts | 39 +++-
packages/contracts/src/environment.ts | 2 +
packages/contracts/src/issue.ts | 32 +++-
.../src/server/IssueTrackerHost.ts | 40 +++-
43 files changed, 1132 insertions(+), 196 deletions(-)
create mode 100644 apps/server/src/issue/IssueTrackerConnections.test.ts
create mode 100644 apps/server/src/persistence/Migrations/106_IssueTrackerAccounts.ts
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..5b643ed4a2cf 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,16 @@ 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,
+ ...(tracker.accountId === undefined ? {} : { accountId: tracker.accountId }),
+ token,
+ },
+ });
setBusy(false);
if (!AsyncResult.isFailure(result)) {
setDraft("");
@@ -154,14 +175,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..b3ce626d22ea 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -412,7 +412,9 @@ 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 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..c2e544edf5d0 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,31 @@ 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 second = IssueTrackerAccountId.make("second");
+ const withSecond = {
+ ...trackers,
+ accounts: [{ ...trackers.trackers[0]!, accountId: second, workspace: "othercorp" }],
+ bindings: { [ProjectId.make("p1")]: trackers.bindings[ProjectId.make("p1")]! },
+ accountBindings: {
+ [ProjectId.make("p2")]: {
+ tracker: IssueTrackerKind.make("linear"),
+ accountId: second,
+ scope: "WEB",
+ },
+ },
+ };
+ const both = (url: string) =>
+ resolveIssueLinkTarget({ url, projects, trackers: withSecond })?.ref;
+ expect(both("https://linear.app/othercorp/issue/WEB-17")).toMatchObject({
+ projectId: "p2",
+ scope: "WEB",
+ });
+ expect(both("https://linear.app/acme/issue/WEB-17")).toMatchObject({
+ projectId: "p1",
+ scope: "WEB",
+ });
});
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..953d44b340b7 100644
--- a/packages/client-runtime/src/issueList.test.ts
+++ b/packages/client-runtime/src/issueList.test.ts
@@ -144,6 +144,61 @@ 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 = { ...first, projectId: "home" as ProjectId };
+ const held = new Map([
+ [environmentId, hold(answer({ trackers: [tracker({})], scopes: [first, second] }))],
+ ]);
+ expect(issueFilterScopes(held, []).map((scope) => scope.input)).toEqual([first, second]);
+ // Another server's ENG teams are kept too, whichever server is read first.
+ const otherEnvironment = "other" as EnvironmentId;
+ const other = { ...first, projectId: "other-api" as ProjectId };
+ const otherPage = hold(answer({ trackers: [tracker({})], scopes: [other] }));
+ for (const order of [
+ [held.get(environmentId)!, otherPage],
+ [otherPage, held.get(environmentId)!],
+ ]) {
+ const servers = new Map([
+ [order[0] === otherPage ? otherEnvironment : environmentId, order[0]!],
+ [order[0] === otherPage ? environmentId : otherEnvironment, order[1]!],
+ ]);
+ expect(issueFilterScopes(servers, [])).toHaveLength(3);
+ }
+ // An older server's rows of ENG hide neither newer server's ENG teams, in either order.
+ const olderPage = hold(answer({ trackers: [tracker({})], entries: [linearRow] }));
+ for (const olderFirst of [true, false]) {
+ const servers = new Map(
+ olderFirst
+ ? [
+ [otherEnvironment, olderPage],
+ [environmentId, held.get(environmentId)!],
+ ]
+ : [
+ [environmentId, held.get(environmentId)!],
+ [otherEnvironment, olderPage],
+ ],
+ );
+ expect(issueFilterScopes(servers, [])).toHaveLength(3);
+ }
+
+ // Older servers name no scopes; rows of the same team stand in for it once.
+ const rows = new Map([
+ [
+ environmentId,
+ hold(
+ answer({ trackers: [tracker({})], entries: [linearRow, { ...linearRow, key: "ENG-2" }] }),
+ ),
+ ],
+ ]);
+ expect(issueFilterScopes(rows, [])).toHaveLength(1);
+ });
+
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)) }),
+ };
+}
From 73fd581a5f6a1c043268e363f93fb1e5012954b7 Mon Sep 17 00:00:00 2001
From: Bil0000 <62337003+Bil0000@users.noreply.github.com>
Date: Thu, 19 Nov 2026 17:38:22 +0100
Subject: [PATCH 2/5] fix(issues): keep Linear accounts consistent under
concurrent edits and partial failures
- Serialize account checks, credential writes, removals, and bindings.
- Remove a new account's credential when the account row cannot be saved.
- A continuation that skips a healthy account no longer marks Linear unconfigured.
- An account missing the key no longer hides a rate limit from the link's own account.
- Document the mobile Another account form.
---
apps/server/src/issue/IssueService.test.ts | 40 +++++++++++++++
apps/server/src/issue/IssueService.ts | 20 ++++++--
.../src/issue/IssueTrackerConnections.test.ts | 50 +++++++++++++++++--
.../src/issue/IssueTrackerConnections.ts | 17 +++++--
docs/user/source-control.md | 5 +-
5 files changed, 117 insertions(+), 15 deletions(-)
diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts
index 981e5813b7b9..feef0660e799 100644
--- a/apps/server/src/issue/IssueService.test.ts
+++ b/apps/server/src/issue/IssueService.test.ts
@@ -677,6 +677,13 @@ describe("IssueService with a standalone tracker", () => {
{ projectId: failed, message: "Linear refused the key." },
]);
}
+ // A continuation that skips the healthy account does not speak for it.
+ const continued = yield* (yield* refusing(["second"])).list({
+ state: "open",
+ cursors: { "linear.app second/eng": "second-next" },
+ });
+ expect(continued.trackers).toMatchObject([{ tracker: "linear", configured: true }]);
+ expect(continued.nextCursors).toEqual({ "linear.app second/eng": "second-next" });
const none = yield* (yield* refusing(["first", "second"])).list({ state: "open" });
expect(none.trackers).toMatchObject([
{ tracker: "linear", configured: false, detail: "Linear refused the key." },
@@ -712,6 +719,39 @@ describe("IssueService with a standalone tracker", () => {
"home" as ProjectId,
),
).toMatchObject({ projectId: "work", issue: { title: "Issue of first" } });
+
+ // The preferred account missing the key does not hide why the link's own account failed.
+ const limited = yield* makeService({
+ projects: [project({ id: "work" }), project({ id: "home" })],
+ trackers: [
+ fakeStandaloneTracker({
+ getIssue: () =>
+ Effect.flatMap(asWhom, (account) =>
+ Effect.fail(
+ new IssueTrackerError({
+ tracker: LINEAR,
+ operation: "getIssue",
+ ...(account === "first"
+ ? { reason: "not-found", detail: "No such issue." }
+ : { reason: "rate-limited", detail: "Slow down.", retryAt: 60 }),
+ }),
+ ),
+ ),
+ }),
+ ],
+ bindings: {
+ work: { tracker: LINEAR, scope: "ENG" },
+ home: { tracker: LINEAR, accountId: second, scope: "ENG" },
+ },
+ });
+ expect(
+ yield* Effect.flip(
+ limited.resolveUrl(
+ "https://linear.app/other-workspace/issue/ENG-1/old-title",
+ "work" as ProjectId,
+ ),
+ ),
+ ).toMatchObject({ reason: "rate-limited", retryAt: 60 });
}),
);
diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts
index 4d7ac2f4cf64..b08e6c24cb05 100644
--- a/apps/server/src/issue/IssueService.ts
+++ b/apps/server/src/issue/IssueService.ts
@@ -149,6 +149,9 @@ function toIssueError(operation: string): (error: IssueTrackerError) => IssueErr
});
}
+const isNotFound = (error: IssueError) =>
+ error._tag === "IssueOperationError" && error.reason === "not-found";
+
const readOnly = (operation: string) =>
new IssueOperationError({
operation,
@@ -412,10 +415,15 @@ const make = Effect.gen(function* () {
}
// Accounts of one tracker share its host: the host is unusable only when every account read
// failed for want of a tool or credential. Otherwise a failure stays its projects' error.
+ const hostAccounts = new Map>();
+ for (const project of scopes.values()) {
+ const accounts = hostAccounts.get(project.host) ?? new Set();
+ hostAccounts.set(project.host, accounts.add(viewerKey(project)));
+ }
const unusable = new Map();
const usable = new Set();
const recordFailure = (project: SupportedProject, failure: IssueTrackerError) => {
- if (isTrackerUnusable(failure)) unusable.set(project.host, trackerDetail(failure));
+ if (isTrackerUnusable(failure)) unusable.set(viewerKey(project), trackerDetail(failure));
else usable.add(project.host);
};
@@ -484,10 +492,11 @@ const make = Effect.gen(function* () {
{ concurrency: SCOPE_CONCURRENCY, discard: true },
);
- for (const [host, detail] of unusable) {
+ for (const [host, accounts] of hostAccounts) {
+ const details = [...accounts].map((account) => unusable.get(account));
const existing = trackers.get(host);
- if (existing !== undefined && !usable.has(host))
- trackers.set(host, { ...existing, configured: false, detail });
+ if (existing === undefined || usable.has(host) || details.includes(undefined)) continue;
+ trackers.set(host, { ...existing, configured: false, detail: details[0] ?? null });
}
for (const [host, { tracker, projectIds }] of unimplemented) {
trackers.set(host, {
@@ -818,7 +827,8 @@ const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(toIssueError("resolveUrl")), Effect.result);
if (read._tag === "Failure") {
- failure ??= read.failure;
+ // Another workspace's account not having the key is a miss, not why the link failed.
+ if (failure === null || isNotFound(failure)) failure = read.failure;
continue;
}
const canonicalUrl = parseUrl(read.success.url);
diff --git a/apps/server/src/issue/IssueTrackerConnections.test.ts b/apps/server/src/issue/IssueTrackerConnections.test.ts
index 97f8154833c2..97d767fee83d 100644
--- a/apps/server/src/issue/IssueTrackerConnections.test.ts
+++ b/apps/server/src/issue/IssueTrackerConnections.test.ts
@@ -1,8 +1,11 @@
import { describe, expect, it } from "@effect/vitest";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as SecureRandom from "effect/crypto/SecureRandom";
+import * as SqlClient from "effect/sql/SqlClient";
import { IssueTrackerKind, type ProjectId } from "@t3tools/contracts";
import {
IssueTrackerError,
@@ -61,17 +64,21 @@ const linear: StandaloneIssueTrackerApi = {
getComments: () => Effect.die("unused"),
};
-function makeConnections() {
+function makeConnections(probe: (token: string) => Effect.Effect = () => Effect.void) {
const secrets = new Map();
let random = 0;
+ const tracker: StandaloneIssueTrackerApi = {
+ ...linear,
+ probeCredential: (token) => Effect.andThen(probe(token), linear.probeCredential(token)),
+ };
const layer = IssueTrackerConnections.layer.pipe(
Layer.provideMerge(IssueTrackerBindings.layer),
- Layer.provide(
+ Layer.provideMerge(
Layer.mergeAll(
SqlitePersistence.layerMemory,
Layer.succeed(
IssueTrackerRegistry.IssueTrackerRegistry,
- IssueTrackerRegistry.fromTrackers([linear]),
+ IssueTrackerRegistry.fromTrackers([tracker]),
),
Layer.succeed(
ServerSecretStore.ServerSecretStore,
@@ -160,4 +167,41 @@ describe("IssueTrackerConnections", () => {
expect(forgotten).toMatchObject({ detail: "This account is not saved on the server." });
}).pipe(Effect.provide(layer));
});
+
+ it.effect("lets no credential outlive the account it was saved for", () => {
+ const probing = Deferred.makeUnsafe();
+ const released = Deferred.makeUnsafe();
+ const { layer, storedKeys } = makeConnections((token) =>
+ token === "slow"
+ ? Effect.andThen(Deferred.succeed(probing, undefined), Deferred.await(released))
+ : Effect.void,
+ );
+ return Effect.gen(function* () {
+ const connections = yield* IssueTrackerConnections.IssueTrackerConnections;
+ const { accountId } = yield* connections.connect({
+ tracker: LINEAR,
+ token: "home",
+ addAccount: true,
+ });
+
+ // A removal that arrives while a replacement key is being checked waits for it.
+ const replacing = yield* connections
+ .connect({ tracker: LINEAR, accountId, token: "slow" })
+ .pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Deferred.await(probing);
+ const removing = yield* connections
+ .connect({ tracker: LINEAR, accountId, token: null })
+ .pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Deferred.succeed(released, undefined);
+ yield* Fiber.join(replacing);
+ yield* Fiber.join(removing);
+ expect(storedKeys()).toEqual({});
+
+ // An account that cannot be saved takes its new key with it.
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`DROP TABLE issue_tracker_accounts`;
+ yield* Effect.flip(connections.connect({ tracker: LINEAR, token: "home", addAccount: true }));
+ expect(storedKeys()).toEqual({});
+ }).pipe(Effect.provide(layer));
+ });
});
diff --git a/apps/server/src/issue/IssueTrackerConnections.ts b/apps/server/src/issue/IssueTrackerConnections.ts
index 71cca8bd00b4..4579e8d403d7 100644
--- a/apps/server/src/issue/IssueTrackerConnections.ts
+++ b/apps/server/src/issue/IssueTrackerConnections.ts
@@ -8,6 +8,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as Semaphore from "effect/Semaphore";
import * as DateTime from "effect/DateTime";
import * as SecureRandom from "effect/crypto/SecureRandom";
import {
@@ -52,6 +53,9 @@ const make = Effect.gen(function* () {
const registry = yield* IssueTrackerRegistry.IssueTrackerRegistry;
const secrets = yield* ServerSecretStore.ServerSecretStore;
const bindings = yield* IssueTrackerBindings.IssueTrackerBindingsRepository;
+ // Account checks, credential writes, and removals run one at a time, so a removal cannot land
+ // between a check and the write that relied on it.
+ const accountLock = yield* Semaphore.make(1);
const random = yield* SecureRandom.SecureRandom;
const requireTracker = (
@@ -238,9 +242,12 @@ const make = Effect.gen(function* () {
.pipe(Effect.mapError(secretFailure(api.kind, "The credential could not be stored.")));
if (input.addAccount === true && accountId !== null) {
const createdAt = DateTime.formatIso(yield* DateTime.now);
- yield* bindings
- .addAccount({ tracker: api.kind, accountId, createdAt })
- .pipe(Effect.mapError(secretFailure(api.kind, "The account could not be saved.")));
+ yield* bindings.addAccount({ tracker: api.kind, accountId, createdAt }).pipe(
+ Effect.tapError(() =>
+ Effect.ignore(secrets.remove(issueTrackerSecretName(api.kind, accountId))),
+ ),
+ Effect.mapError(secretFailure(api.kind, "The account could not be saved.")),
+ );
}
return {
...api.standalone,
@@ -251,7 +258,7 @@ const make = Effect.gen(function* () {
...(probed.workspace === undefined ? {} : { workspace: probed.workspace }),
scopes: probed.scopes,
};
- });
+ }, accountLock.withPermits(1));
const bindProject: IssueTrackerConnections["Service"]["bindProject"] = Effect.fn(
"IssueTrackerConnections.bindProject",
@@ -264,7 +271,7 @@ const make = Effect.gen(function* () {
yield* bindings
.set({ projectId: input.projectId, binding: input.binding, updatedAt })
.pipe(Effect.mapError(secretFailure(tracker, "The project binding could not be saved.")));
- });
+ }, accountLock.withPermits(1));
return IssueTrackerConnections.of({ list, connect, bindProject });
});
diff --git a/docs/user/source-control.md b/docs/user/source-control.md
index b3ce626d22ea..5d92ecc9e98a 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -413,8 +413,9 @@ Settings → Source control & issues, then pick one or more teams for that proje
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. Use
-**Add account** in the same place to connect another Linear workspace or user; each project
-reads its teams through the account you picked them under.
+**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
From 1042726b3a1ae28345a3bbfe3e866c6afd895a91 Mon Sep 17 00:00:00 2001
From: Bil0000 <62337003+Bil0000@users.noreply.github.com>
Date: Thu, 19 Nov 2026 18:22:08 +0100
Subject: [PATCH 3/5] test(issues): fold the Linear account cases into fewer,
shorter tests
---
apps/server/src/issue/IssueService.test.ts | 227 +++++++-----------
.../src/issue/IssueTrackerConnections.test.ts | 214 ++++++-----------
.../client-runtime/src/issueLinks.test.ts | 38 ++-
packages/client-runtime/src/issueList.test.ts | 66 ++---
4 files changed, 191 insertions(+), 354 deletions(-)
diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts
index feef0660e799..ccf31bfbe2cd 100644
--- a/apps/server/src/issue/IssueService.test.ts
+++ b/apps/server/src/issue/IssueService.test.ts
@@ -578,125 +578,111 @@ describe("IssueService with a standalone tracker", () => {
it.effect("reads each project's team as the account it is bound with", () =>
Effect.gen(function* () {
- const second = IssueTrackerAccountId.make("second");
const asWhom = Effect.map(IssueTrackerAccount, (account) => account ?? "first");
+ const fail = (reason: IssueTrackerError["reason"], retryAt?: number) =>
+ new IssueTrackerError({
+ tracker: LINEAR,
+ operation: "read",
+ reason,
+ detail: reason,
+ ...(retryAt === undefined ? {} : { retryAt }),
+ });
+ const twoAccounts = (overrides: Partial) =>
+ makeService({
+ projects: [project({ id: "work" }), project({ id: "home" })],
+ trackers: [fakeStandaloneTracker(overrides)],
+ bindings: {
+ work: { tracker: LINEAR, scope: "ENG" },
+ home: {
+ tracker: LINEAR,
+ accountId: IssueTrackerAccountId.make("second"),
+ scope: "ENG",
+ },
+ },
+ });
const calls: string[] = [];
- const service = yield* makeService({
- projects: [project({ id: "work" }), project({ id: "home" })],
- trackers: [
- fakeStandaloneTracker({
- getViewer: () => Effect.map(asWhom, (account) => `viewer-${account}`),
- listIssues: (input) =>
- Effect.map(asWhom, (account) => {
- calls.push(`list ${account} ${input.scope} ${input.cursor ?? ""}`);
- return {
- items: [{ ...issue("ENG-1"), title: `Issue of ${account}` }],
- nextCursor: `${account}-next`,
- };
- }),
- getIssue: (input) =>
- Effect.map(asWhom, (account) => ({
- ...issue(input.key),
- title: `Issue of ${account}`,
- url: `https://linear.app/${account === "first" ? "acme" : "other-workspace"}/issue/${input.key}/canonical-title`,
- })),
+ const service = yield* twoAccounts({
+ getViewer: () => Effect.map(asWhom, (account) => `viewer-${account}`),
+ listIssues: (input) =>
+ Effect.map(asWhom, (account) => {
+ calls.push(`${account} ${input.cursor ?? ""}`);
+ return { items: [issue("ENG-1")], nextCursor: `${account}-next` };
}),
- ],
- bindings: {
- work: { tracker: LINEAR, scope: "ENG" },
- home: { tracker: LINEAR, accountId: second, scope: "ENG" },
- },
+ getIssue: (input) =>
+ Effect.map(asWhom, (account) => ({
+ ...issue(input.key),
+ title: account,
+ url: `https://linear.app/${account === "first" ? "acme" : "other-workspace"}/issue/${input.key}/canonical-title`,
+ })),
});
// The same team key on two accounts is two scopes, each with its own cursor and viewer.
const listed = yield* service.list({ state: "open", involvement: "assigned" });
- expect(calls.sort()).toEqual(["list first ENG ", "list second ENG "]);
- expect(listed.viewers).toEqual({
- "linear.app": "viewer-first",
- "linear.app second": "viewer-second",
- });
- expect(listed.nextCursors).toEqual({
- "linear.app eng": "first-next",
- "linear.app second/eng": "second-next",
- });
- expect(listed.entries.map((entry) => [entry.projectId, entry.title]).sort()).toEqual([
- ["home", "Issue of second"],
- ["work", "Issue of first"],
- ]);
-
- // A continuation carries each account on from its own cursor.
- calls.length = 0;
- yield* service.list({
- state: "open",
- cursors: { "linear.app second/eng": "second-next" },
+ expect(calls.sort()).toEqual(["first ", "second "]);
+ expect(listed).toMatchObject({
+ viewers: { "linear.app": "viewer-first", "linear.app second": "viewer-second" },
+ nextCursors: { "linear.app eng": "first-next", "linear.app second/eng": "second-next" },
});
- expect(calls).toEqual(["list second ENG second-next"]);
+ calls.length = 0;
+ yield* service.list({ state: "open", cursors: { "linear.app second/eng": "second-next" } });
+ expect(calls).toEqual(["second second-next"]);
+ const ref = { tracker: LINEAR, scope: "ENG", key: "ENG-1", projectId: "home" as ProjectId };
+ expect(yield* service.detail(ref)).toMatchObject({ title: "second" });
- const ref = { tracker: LINEAR, scope: "ENG", key: "ENG-1" };
- expect(yield* service.detail({ ...ref, projectId: "home" as ProjectId })).toMatchObject({
- title: "Issue of second",
- });
- expect(yield* service.detail({ ...ref, projectId: "work" as ProjectId })).toMatchObject({
- title: "Issue of first",
- });
+ // A link resolves through the account whose workspace it names, whichever is preferred.
+ expect(
+ yield* service.resolveUrl(
+ "https://linear.app/other-workspace/issue/ENG-1/old-title",
+ "work" as ProjectId,
+ ),
+ ).toMatchObject({ projectId: "home", issue: { title: "second" } });
- // One refused key, either one, leaves the group usable; only its project errs. Both
- // refused, the group is.
+ // One refused key leaves the group usable, even on a continuation that skips the other.
const refusing = (refused: ReadonlyArray) =>
- makeService({
- projects: [project({ id: "work" }), project({ id: "home" })],
- trackers: [
- fakeStandaloneTracker({
- listIssues: () =>
- Effect.flatMap(asWhom, (account) =>
- refused.includes(account)
- ? Effect.fail(
- new IssueTrackerError({
- tracker: LINEAR,
- operation: "listIssues",
- reason: "unauthenticated",
- detail: "Linear refused the key.",
- }),
- )
- : Effect.succeed({ items: [issue("ENG-1")], nextCursor: null }),
- ),
- }),
- ],
- bindings: {
- work: { tracker: LINEAR, scope: "ENG" },
- home: { tracker: LINEAR, accountId: second, scope: "ENG" },
- },
+ twoAccounts({
+ listIssues: () =>
+ Effect.flatMap(asWhom, (account) =>
+ refused.includes(account)
+ ? Effect.fail(fail("unauthenticated"))
+ : Effect.succeed({ items: [], nextCursor: null }),
+ ),
});
- for (const [refused, failed] of [
- ["second", "home"],
- ["first", "work"],
- ] as const) {
- const partly = yield* (yield* refusing([refused])).list({ state: "open" });
- expect(partly.trackers).toMatchObject([{ tracker: "linear", configured: true }]);
- expect(partly.errors).toMatchObject([
- { projectId: failed, message: "Linear refused the key." },
- ]);
- }
- // A continuation that skips the healthy account does not speak for it.
+ const partly = yield* (yield* refusing(["second"])).list({ state: "open" });
+ expect(partly).toMatchObject({
+ trackers: [{ configured: true }],
+ errors: [{ projectId: "home" }],
+ });
const continued = yield* (yield* refusing(["second"])).list({
state: "open",
cursors: { "linear.app second/eng": "second-next" },
});
- expect(continued.trackers).toMatchObject([{ tracker: "linear", configured: true }]);
- expect(continued.nextCursors).toEqual({ "linear.app second/eng": "second-next" });
+ expect(continued.trackers).toMatchObject([{ configured: true }]);
const none = yield* (yield* refusing(["first", "second"])).list({ state: "open" });
- expect(none.trackers).toMatchObject([
- { tracker: "linear", configured: false, detail: "Linear refused the key." },
- ]);
+ expect(none.trackers).toMatchObject([{ configured: false }]);
- // Two users of one workspace: the account bound to the link's exact team serves it, even
- // when the preferred project reads another team through the other account.
+ // The preferred account missing the key does not hide why the link's own account failed.
+ const limited = yield* twoAccounts({
+ getIssue: () =>
+ Effect.flatMap(asWhom, (account) =>
+ Effect.fail(account === "first" ? fail("not-found") : fail("rate-limited", 60)),
+ ),
+ });
+ expect(
+ yield* Effect.flip(
+ limited.resolveUrl(
+ "https://linear.app/other-workspace/issue/ENG-1/old-title",
+ "work" as ProjectId,
+ ),
+ ),
+ ).toMatchObject({ reason: "rate-limited", retryAt: 60 });
+
+ // Two users of one workspace: the account bound to the link's exact team serves it.
const sameWorkspace = yield* makeService({
projects: [project({ id: "ops" }), project({ id: "eng" })],
trackers: [fakeStandaloneTracker()],
bindings: {
ops: { tracker: LINEAR, scope: "OPS" },
- eng: { tracker: LINEAR, accountId: second, scope: "ENG" },
+ eng: { tracker: LINEAR, accountId: IssueTrackerAccountId.make("second"), scope: "ENG" },
},
});
expect(
@@ -704,54 +690,7 @@ describe("IssueService with a standalone tracker", () => {
"https://linear.app/acme/issue/ENG-1/old-title",
"ops" as ProjectId,
),
- ).toMatchObject({ projectId: "eng", scope: "ENG", writable: true });
-
- // A link resolves through the account whose workspace it names, whichever is preferred.
- expect(
- yield* service.resolveUrl(
- "https://linear.app/other-workspace/issue/ENG-1/old-title",
- "work" as ProjectId,
- ),
- ).toMatchObject({ projectId: "home", issue: { title: "Issue of second" } });
- expect(
- yield* service.resolveUrl(
- "https://linear.app/acme/issue/ENG-1/old-title",
- "home" as ProjectId,
- ),
- ).toMatchObject({ projectId: "work", issue: { title: "Issue of first" } });
-
- // The preferred account missing the key does not hide why the link's own account failed.
- const limited = yield* makeService({
- projects: [project({ id: "work" }), project({ id: "home" })],
- trackers: [
- fakeStandaloneTracker({
- getIssue: () =>
- Effect.flatMap(asWhom, (account) =>
- Effect.fail(
- new IssueTrackerError({
- tracker: LINEAR,
- operation: "getIssue",
- ...(account === "first"
- ? { reason: "not-found", detail: "No such issue." }
- : { reason: "rate-limited", detail: "Slow down.", retryAt: 60 }),
- }),
- ),
- ),
- }),
- ],
- bindings: {
- work: { tracker: LINEAR, scope: "ENG" },
- home: { tracker: LINEAR, accountId: second, scope: "ENG" },
- },
- });
- expect(
- yield* Effect.flip(
- limited.resolveUrl(
- "https://linear.app/other-workspace/issue/ENG-1/old-title",
- "work" as ProjectId,
- ),
- ),
- ).toMatchObject({ reason: "rate-limited", retryAt: 60 });
+ ).toMatchObject({ projectId: "eng", writable: true });
}),
);
diff --git a/apps/server/src/issue/IssueTrackerConnections.test.ts b/apps/server/src/issue/IssueTrackerConnections.test.ts
index 97d767fee83d..0518970b648e 100644
--- a/apps/server/src/issue/IssueTrackerConnections.test.ts
+++ b/apps/server/src/issue/IssueTrackerConnections.test.ts
@@ -19,109 +19,74 @@ import * as IssueTrackerConnections from "./IssueTrackerConnections.ts";
import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
const LINEAR = IssueTrackerKind.make("linear");
-const decoder = new TextDecoder();
-const linear: StandaloneIssueTrackerApi = {
- kind: LINEAR,
- capabilities: {
- create: false,
- edit: false,
- comment: false,
- labels: false,
- assignees: false,
- reactions: false,
- templates: false,
- linkedPullRequests: false,
- events: false,
- search: false,
- },
- standalone: {
- tracker: LINEAR,
- displayName: "Linear",
- host: "linear.app",
- scopeNoun: "team",
- credential: { label: "Personal API key", helpUrl: null },
- },
- parseIssueUrl: () => null,
- probeCredential: (token) =>
- token.startsWith("bad")
- ? Effect.fail(
- new IssueTrackerError({
- tracker: LINEAR,
- operation: "viewer",
- reason: "unauthenticated",
- detail: "Linear refused the key.",
- }),
- )
- : Effect.succeed({
- account: `user-${token}`,
- workspace: `workspace-${token}`,
- scopes: [{ key: "ENG", name: "Engineering" }],
- }),
- getViewer: () => Effect.succeed("viewer"),
- listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
- getIssue: () => Effect.die("unused"),
- getComments: () => Effect.die("unused"),
-};
-
-function makeConnections(probe: (token: string) => Effect.Effect = () => Effect.void) {
- const secrets = new Map();
- let random = 0;
- const tracker: StandaloneIssueTrackerApi = {
- ...linear,
- probeCredential: (token) => Effect.andThen(probe(token), linear.probeCredential(token)),
- };
- const layer = IssueTrackerConnections.layer.pipe(
- Layer.provideMerge(IssueTrackerBindings.layer),
- Layer.provideMerge(
- Layer.mergeAll(
- SqlitePersistence.layerMemory,
- Layer.succeed(
- IssueTrackerRegistry.IssueTrackerRegistry,
- IssueTrackerRegistry.fromTrackers([tracker]),
- ),
- Layer.succeed(
- ServerSecretStore.ServerSecretStore,
- ServerSecretStore.ServerSecretStore.of({
- get: (name) => Effect.succeed(Option.fromNullishOr(secrets.get(name))),
- set: (name, value) => Effect.sync(() => void secrets.set(name, value)),
- create: (name, value) => Effect.sync(() => void secrets.set(name, value)),
- getOrCreateRandom: () => Effect.die("unused"),
+describe("IssueTrackerConnections", () => {
+ it.effect("keeps each account's key and bindings apart, and no key past its account", () => {
+ const secrets = new Map();
+ const probing = Deferred.makeUnsafe();
+ const released = Deferred.makeUnsafe();
+ let random = 0;
+ const tracker = {
+ kind: LINEAR,
+ standalone: { tracker: LINEAR, host: "linear.app" },
+ probeCredential: (token: string) =>
+ token === "bad"
+ ? Effect.fail(
+ new IssueTrackerError({
+ tracker: LINEAR,
+ operation: "viewer",
+ reason: "unauthenticated",
+ detail: "Linear refused the key.",
+ }),
+ )
+ : Effect.as(
+ token === "slow"
+ ? Effect.andThen(Deferred.succeed(probing, undefined), Deferred.await(released))
+ : Effect.void,
+ { account: `user-${token}`, scopes: [] },
+ ),
+ } as unknown as StandaloneIssueTrackerApi;
+ const layer = IssueTrackerConnections.layer.pipe(
+ Layer.provideMerge(IssueTrackerBindings.layer),
+ Layer.provideMerge(
+ Layer.mergeAll(
+ SqlitePersistence.layerMemory,
+ Layer.succeed(
+ IssueTrackerRegistry.IssueTrackerRegistry,
+ IssueTrackerRegistry.fromTrackers([tracker]),
+ ),
+ Layer.mock(ServerSecretStore.ServerSecretStore)({
+ get: (name) =>
+ Effect.succeed(
+ Option.map(Option.fromNullishOr(secrets.get(name)), (value) =>
+ new TextEncoder().encode(value),
+ ),
+ ),
+ set: (name, value) =>
+ Effect.sync(() => void secrets.set(name, new TextDecoder().decode(value))),
remove: (name) => Effect.sync(() => void secrets.delete(name)),
}),
- ),
- Layer.succeed(
- SecureRandom.SecureRandom,
- SecureRandom.make((size) => new Uint8Array(size).fill(++random)),
+ Layer.succeed(
+ SecureRandom.SecureRandom,
+ SecureRandom.make((size) => new Uint8Array(size).fill(++random)),
+ ),
),
),
- ),
- );
- const storedKeys = () =>
- Object.fromEntries([...secrets].map(([name, value]) => [name, decoder.decode(value)]));
- return { layer, storedKeys };
-}
-
-describe("IssueTrackerConnections", () => {
- it.effect("keeps a second account beside the first, each with its own key and bindings", () => {
- const { layer, storedKeys } = makeConnections();
+ );
return Effect.gen(function* () {
const connections = yield* IssueTrackerConnections.IssueTrackerConnections;
yield* connections.connect({ tracker: LINEAR, token: "work" });
- const added = yield* connections.connect({
+ const { accountId } = yield* connections.connect({
tracker: LINEAR,
token: "home",
addAccount: true,
});
- const accountId = added.accountId!;
- expect(added).toMatchObject({ account: "user-home", workspace: "workspace-home" });
// The first account keeps the name it was saved under before accounts existed.
- expect(storedKeys()).toEqual({
+ expect(Object.fromEntries(secrets)).toEqual({
"issue-tracker-bGluZWFy-token": "work",
[`issue-tracker-bGluZWFy-account-${accountId}-token`]: "home",
});
-
yield* connections.bindProject({
projectId: "work" as ProjectId,
binding: { tracker: LINEAR, scope: "ENG" },
@@ -130,61 +95,17 @@ describe("IssueTrackerConnections", () => {
projectId: "home" as ProjectId,
binding: { tracker: LINEAR, accountId, scope: "ENG" },
});
- const listed = yield* connections.list;
- expect(listed.trackers.map((tracker) => [tracker.accountId, tracker.account])).toEqual([
- [undefined, "user-work"],
- ]);
- expect(listed.accounts?.map((tracker) => [tracker.accountId, tracker.account])).toEqual([
- [accountId, "user-home"],
- ]);
// Older clients read `bindings` as the first account's, so the second one's are apart.
- expect(listed.bindings).toEqual({ work: { tracker: LINEAR, scope: "ENG" } });
- expect(listed.accountBindings).toEqual({
- home: { tracker: LINEAR, accountId, scope: "ENG" },
+ expect(yield* connections.list).toMatchObject({
+ accounts: [{ accountId, account: "user-home" }],
+ bindings: { work: { tracker: LINEAR, scope: "ENG" } },
+ accountBindings: { home: { tracker: LINEAR, accountId, scope: "ENG" } },
});
+ yield* Effect.flip(connections.connect({ tracker: LINEAR, token: "bad", addAccount: true }));
+ expect(secrets.size).toBe(2);
- // Replacing the second account's key leaves the first alone, and a refused key saves nothing.
- yield* connections.connect({ tracker: LINEAR, accountId, token: "home-2" });
- const refused = yield* Effect.flip(
- connections.connect({ tracker: LINEAR, token: "bad", addAccount: true }),
- );
- expect(refused).toMatchObject({ reason: "rejected" });
- expect(Object.values(storedKeys()).sort()).toEqual(["home-2", "work"]);
-
- // Disconnecting one account unbinds only its projects and forgets it.
- yield* connections.connect({ tracker: LINEAR, accountId, token: null });
- const after = yield* connections.list;
- expect(after.accounts).toEqual([]);
- expect(after.bindings).toEqual({ work: { tracker: LINEAR, scope: "ENG" } });
- expect(after.accountBindings).toEqual({});
- expect(storedKeys()).toEqual({ "issue-tracker-bGluZWFy-token": "work" });
- const forgotten = yield* Effect.flip(
- connections.bindProject({
- projectId: "home" as ProjectId,
- binding: { tracker: LINEAR, accountId, scope: "ENG" },
- }),
- );
- expect(forgotten).toMatchObject({ detail: "This account is not saved on the server." });
- }).pipe(Effect.provide(layer));
- });
-
- it.effect("lets no credential outlive the account it was saved for", () => {
- const probing = Deferred.makeUnsafe();
- const released = Deferred.makeUnsafe();
- const { layer, storedKeys } = makeConnections((token) =>
- token === "slow"
- ? Effect.andThen(Deferred.succeed(probing, undefined), Deferred.await(released))
- : Effect.void,
- );
- return Effect.gen(function* () {
- const connections = yield* IssueTrackerConnections.IssueTrackerConnections;
- const { accountId } = yield* connections.connect({
- tracker: LINEAR,
- token: "home",
- addAccount: true,
- });
-
- // A removal that arrives while a replacement key is being checked waits for it.
+ // A removal that arrives while a replacement key is being checked waits for it, and
+ // unbinds only that account's projects.
const replacing = yield* connections
.connect({ tracker: LINEAR, accountId, token: "slow" })
.pipe(Effect.forkChild({ startImmediately: true }));
@@ -195,13 +116,22 @@ describe("IssueTrackerConnections", () => {
yield* Deferred.succeed(released, undefined);
yield* Fiber.join(replacing);
yield* Fiber.join(removing);
- expect(storedKeys()).toEqual({});
+ expect([...secrets.keys()]).toEqual(["issue-tracker-bGluZWFy-token"]);
+ const after = yield* connections.list;
+ expect([after.accounts, after.accountBindings]).toEqual([[], {}]);
+ expect(
+ yield* Effect.flip(
+ connections.bindProject({
+ projectId: "home" as ProjectId,
+ binding: { tracker: LINEAR, accountId, scope: "ENG" },
+ }),
+ ),
+ ).toMatchObject({ detail: "This account is not saved on the server." });
// An account that cannot be saved takes its new key with it.
- const sql = yield* SqlClient.SqlClient;
- yield* sql`DROP TABLE issue_tracker_accounts`;
+ yield* (yield* SqlClient.SqlClient)`DROP TABLE issue_tracker_accounts`;
yield* Effect.flip(connections.connect({ tracker: LINEAR, token: "home", addAccount: true }));
- expect(storedKeys()).toEqual({});
+ expect(secrets.size).toBe(1);
}).pipe(Effect.provide(layer));
});
});
diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts
index c2e544edf5d0..d875ba58c276 100644
--- a/packages/client-runtime/src/issueLinks.test.ts
+++ b/packages/client-runtime/src/issueLinks.test.ts
@@ -130,29 +130,23 @@ describe("resolveIssueLinkTarget", () => {
).toBeNull();
// A second account reaches its own workspace, through only the projects bound with it.
- const second = IssueTrackerAccountId.make("second");
- const withSecond = {
- ...trackers,
- accounts: [{ ...trackers.trackers[0]!, accountId: second, workspace: "othercorp" }],
- bindings: { [ProjectId.make("p1")]: trackers.bindings[ProjectId.make("p1")]! },
- accountBindings: {
- [ProjectId.make("p2")]: {
- tracker: IssueTrackerKind.make("linear"),
- accountId: second,
- scope: "WEB",
- },
- },
- };
+ const accountId = IssueTrackerAccountId.make("second");
+ const [p1, p2] = [ProjectId.make("p1"), ProjectId.make("p2")];
const both = (url: string) =>
- resolveIssueLinkTarget({ url, projects, trackers: withSecond })?.ref;
- expect(both("https://linear.app/othercorp/issue/WEB-17")).toMatchObject({
- projectId: "p2",
- scope: "WEB",
- });
- expect(both("https://linear.app/acme/issue/WEB-17")).toMatchObject({
- projectId: "p1",
- scope: "WEB",
- });
+ 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/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts
index 953d44b340b7..49bab599b4f5 100644
--- a/packages/client-runtime/src/issueList.test.ts
+++ b/packages/client-runtime/src/issueList.test.ts
@@ -151,52 +151,26 @@ describe("issueFilterScopes", () => {
host: "linear.app",
scope: "ENG",
};
- const second = { ...first, projectId: "home" as ProjectId };
- const held = new Map([
- [environmentId, hold(answer({ trackers: [tracker({})], scopes: [first, second] }))],
- ]);
- expect(issueFilterScopes(held, []).map((scope) => scope.input)).toEqual([first, second]);
- // Another server's ENG teams are kept too, whichever server is read first.
- const otherEnvironment = "other" as EnvironmentId;
- const other = { ...first, projectId: "other-api" as ProjectId };
- const otherPage = hold(answer({ trackers: [tracker({})], scopes: [other] }));
- for (const order of [
- [held.get(environmentId)!, otherPage],
- [otherPage, held.get(environmentId)!],
- ]) {
- const servers = new Map([
- [order[0] === otherPage ? otherEnvironment : environmentId, order[0]!],
- [order[0] === otherPage ? environmentId : otherEnvironment, order[1]!],
- ]);
- expect(issueFilterScopes(servers, [])).toHaveLength(3);
- }
- // An older server's rows of ENG hide neither newer server's ENG teams, in either order.
- const olderPage = hold(answer({ trackers: [tracker({})], entries: [linearRow] }));
- for (const olderFirst of [true, false]) {
- const servers = new Map(
- olderFirst
- ? [
- [otherEnvironment, olderPage],
- [environmentId, held.get(environmentId)!],
- ]
- : [
- [environmentId, held.get(environmentId)!],
- [otherEnvironment, olderPage],
- ],
- );
- expect(issueFilterScopes(servers, [])).toHaveLength(3);
- }
-
- // Older servers name no scopes; rows of the same team stand in for it once.
- const rows = new Map([
- [
- environmentId,
- hold(
- answer({ trackers: [tracker({})], entries: [linearRow, { ...linearRow, key: "ENG-2" }] }),
- ),
- ],
- ]);
- expect(issueFilterScopes(rows, [])).toHaveLength(1);
+ 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", () => {
From 302c4ac8a9770c25f367d6eb6c51c01f24808d91 Mon Sep 17 00:00:00 2001
From: Bil0000 <62337003+Bil0000@users.noreply.github.com>
Date: Sat, 21 Nov 2026 12:57:21 +0100
Subject: [PATCH 4/5] test(issues): a project binding waits for the account
lock
---
.../server/src/issue/IssueTrackerConnections.test.ts | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)
diff --git a/apps/server/src/issue/IssueTrackerConnections.test.ts b/apps/server/src/issue/IssueTrackerConnections.test.ts
index 0518970b648e..9df9ff41922e 100644
--- a/apps/server/src/issue/IssueTrackerConnections.test.ts
+++ b/apps/server/src/issue/IssueTrackerConnections.test.ts
@@ -104,17 +104,25 @@ describe("IssueTrackerConnections", () => {
yield* Effect.flip(connections.connect({ tracker: LINEAR, token: "bad", addAccount: true }));
expect(secrets.size).toBe(2);
- // A removal that arrives while a replacement key is being checked waits for it, and
- // unbinds only that account's projects.
+ // A binding or removal that arrives while a replacement key is being checked waits for
+ // it, and the removal unbinds only that account's projects.
const replacing = yield* connections
.connect({ tracker: LINEAR, accountId, token: "slow" })
.pipe(Effect.forkChild({ startImmediately: true }));
yield* Deferred.await(probing);
+ const binding = yield* connections
+ .bindProject({
+ projectId: "late" as ProjectId,
+ binding: { tracker: LINEAR, accountId, scope: "ENG" },
+ })
+ .pipe(Effect.forkChild({ startImmediately: true }));
+ expect((yield* connections.list).accountBindings).not.toHaveProperty("late");
const removing = yield* connections
.connect({ tracker: LINEAR, accountId, token: null })
.pipe(Effect.forkChild({ startImmediately: true }));
yield* Deferred.succeed(released, undefined);
yield* Fiber.join(replacing);
+ yield* Fiber.join(binding);
yield* Fiber.join(removing);
expect([...secrets.keys()]).toEqual(["issue-tracker-bGluZWFy-token"]);
const after = yield* connections.list;
From 4615fe69bb34383d4a74b0e4a841c2834ab14b2d Mon Sep 17 00:00:00 2001
From: Bil0000 <62337003+Bil0000@users.noreply.github.com>
Date: Sat, 21 Nov 2026 13:42:51 +0100
Subject: [PATCH 5/5] refactor(issues): inline the account lookup and pass
accountId directly
---
.../settings/components/IssueTrackerSection.tsx | 6 +-----
apps/server/src/issue/IssueService.ts | 6 +-----
apps/server/src/issue/IssueTrackerConnections.ts | 16 +++++-----------
.../components/settings/IssueTrackerSettings.tsx | 6 +-----
4 files changed, 8 insertions(+), 26 deletions(-)
diff --git a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx
index 5b643ed4a2cf..e5f20372c393 100644
--- a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx
+++ b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx
@@ -159,11 +159,7 @@ export function IssueTrackerCredentialForm(props: {
environmentId,
input: props.addAccount
? { tracker: tracker.tracker, token, addAccount: true }
- : {
- tracker: tracker.tracker,
- ...(tracker.accountId === undefined ? {} : { accountId: tracker.accountId }),
- token,
- },
+ : { tracker: tracker.tracker, accountId: tracker.accountId, token },
});
setBusy(false);
if (!AsyncResult.isFailure(result)) {
diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts
index b08e6c24cb05..5b45a22d696f 100644
--- a/apps/server/src/issue/IssueService.ts
+++ b/apps/server/src/issue/IssueService.ts
@@ -110,11 +110,7 @@ function findStandaloneIssueUrl(trackers: ReadonlyArray
- bindings.listAccounts.pipe(
- Effect.map((accounts) =>
- accounts
- .filter((account) => account.tracker === tracker)
- .map((account) => account.accountId),
- ),
- Effect.mapError(secretFailure(tracker, "The saved accounts could not be read.")),
- );
-
const requireAccount = Effect.fn("IssueTrackerConnections.requireAccount")(function* (
tracker: IssueTrackerKind,
accountId: IssueTrackerAccountId | undefined,
) {
if (accountId === undefined) return null;
- if ((yield* accountsOf(tracker)).includes(accountId)) return accountId;
+ const saved = yield* bindings.listAccounts.pipe(
+ Effect.mapError(secretFailure(tracker, "The saved accounts could not be read.")),
+ );
+ if (saved.some((account) => account.tracker === tracker && account.accountId === accountId))
+ return accountId;
return yield* new IssueTrackerConnectionError({
tracker,
reason: "failed",
diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx
index df7fe011d6f9..b41a8a9cee77 100644
--- a/apps/web/src/components/settings/IssueTrackerSettings.tsx
+++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx
@@ -140,11 +140,7 @@ function TrackerRow({
environmentId,
input: addAccount
? { tracker: tracker.tracker, token, addAccount }
- : {
- tracker: tracker.tracker,
- ...(tracker.accountId === undefined ? {} : { accountId: tracker.accountId }),
- token,
- },
+ : { tracker: tracker.tracker, accountId: tracker.accountId, token },
});
setBusy(false);
if (result._tag === "Success") return true;