The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 08:30 UTC
feat(issues): filter the issue list by label and assignee, and sort it (#37760)
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Julius Marminge committed
Nov 16, 2026 at 22:00 UTC
60f7e5d9b17750f271c97986154bc632f560123e
59 files changed
+2600
-471
apps/mobile/src/Stack.tsx
+5
@@ -40,6 +40,7 @@ import { PullRequestFilterSearchScreen } from "./features/pull-requests/PullRequ
40
import { IssueAssigneesScreen } from "./features/issues/IssueAssigneesScreen";
41
import { IssueEditScreen } from "./features/issues/IssueEditScreen";
42
import { IssueLabelsScreen } from "./features/issues/IssueLabelsScreen";
43
+import { IssueFilterSearchScreen } from "./features/issues/IssueFilterSearchScreen";
44
import { IssueRouteScreen } from "./features/issues/IssueRouteScreen";
45
import {
46
RenderErrorBoundary,
@@ -573,6 +574,10 @@ const RootStackConfig = createWorkspaceStackNavigator({
574
screen: IssueAssigneesScreen,
575
options: SEARCH_SHEET_ROUTE,
576
}),
577
+ IssueFilterSearch: createNativeStackScreen({
578
+ screen: IssueFilterSearchScreen,
579
+ options: SEARCH_SHEET_ROUTE,
580
+ }),
581
Thread: createNativeStackScreen({
582
screen: ThreadRouteScreen,
583
linking: { path: "threads/:environmentId?/:threadId?", alias: ["new/draft"] },
apps/mobile/src/features/home/home-route-visibility.test.tsx
+1
@@ -41,6 +41,7 @@ function setup() {
41
presented: true,
42
selectedThreadKey: "env-1:thread-1",
43
selectedPullRequestKey: null,
44
+ selectedIssueKey: null,
45
};
46
return {
47
registry,
apps/mobile/src/features/issues/IssueAssigneesScreen.tsx
+18
-11
@@ -3,6 +3,7 @@ import { useAtom } from "@effect/atom-react";
3
import {
4
issueAssigneeHeld,
5
issueAssigneesAfterPicks,
6
+ issuePicksAfterFailedWrite,
7
issuePicksFor,
8
issueWriteAfterPicks,
9
noIssuePicks,
@@ -12,7 +13,7 @@ import type { IssueAssigneeCandidate } from "@t3tools/contracts";
13
import { useEffect, useState } from "react";
14
15
import * as Dialog from "../../components/ui/Dialog";
15
-import { issueEnvironment } from "../../state/issues";
16
+import { issueEnvironment, refreshIssueLists } from "../../state/issues";
17
import { useEnvironmentQuery } from "../../state/query";
18
import { useAtomCommand } from "../../state/use-atom-command";
19
import { PullRequestAvatar } from "../pull-requests/PullRequestPresentation";
@@ -29,12 +30,16 @@ export function IssueAssigneesScreen({ route }: StaticScreenProps<IssueParams>)
30
const result = useEnvironmentQuery(issueEnvironment.candidates(target));
31
const update = useAtomCommand(issueEnvironment.update, { reportFailure: false });
32
const [query, setQuery] = useState("");
32
- const [picks, setPicks] = useAtom(issueAssigneePicksFamily(issueParamsKey(route.params)));
33
- // Picks against an older read are dropped when the sheet opens, and kept across a read while open.
34
- const [openedWith] = useState(detail);
35
- const current = detail
36
- ? issuePicksFor(picks, detail, detail !== openedWith)
37
- : noIssuePicks<IssueAssigneeCandidate>();
33
+ // The atom carries a closed sheet's picks to the next one; this sheet's own live here.
34
+ const [stored, setStored] = useAtom(issueAssigneePicksFamily(issueParamsKey(route.params)));
35
+ // Picks against an older read are dropped once, when the sheet opens.
36
+ const [picks, setPicks] = useState(() =>
37
+ detail ? issuePicksFor(stored, detail, false) : noIssuePicks<IssueAssigneeCandidate>(),
38
+ );
39
+ const own = detail ? issuePicksFor(picks, detail, true) : noIssuePicks<IssueAssigneeCandidate>();
40
+ // What was last sent is read from the atom, so a write that fails while this sheet is open is
41
+ // sent again when it closes.
42
+ const current = { ...own, written: stored.basis === detail ? stored.written : null };
43
const draft = current.draft;
44
const allowed = access?.assignees === true;
45
const held = (candidate: IssueAssigneeCandidate) =>
@@ -54,15 +59,17 @@ export function IssueAssigneesScreen({ route }: StaticScreenProps<IssueParams>)
59
current.written,
60
);
61
if (assignees === null) return;
57
- setPicks({ ...current, written: assignees });
62
+ const sent = { ...current, written: assignees };
63
+ setStored(sent);
64
void update({ ...target, input: { ...target.input, assignees } }).then((response) => {
65
const failure = issueCommandError(response);
60
- if (failure === null) return;
61
- setPicks(noIssuePicks());
66
+ if (failure === null) return refreshIssueLists(target.environmentId);
67
+ // Picks made after this write was sent are kept.
68
+ setStored((latest) => issuePicksAfterFailedWrite(latest, sent));
69
Dialog.alert("Couldn't change assignees", failure);
70
});
71
}),
65
- [navigation, detail, draft, current, setPicks, update, target],
72
+ [navigation, detail, draft, current, setStored, update, target],
73
);
74
return (
75
<IssueCandidatesSheet
apps/mobile/src/features/issues/IssueCandidatesSheet.tsx
+6
-1
@@ -60,7 +60,12 @@ export function IssueCandidatesSheet(props: {
60
contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom }}
61
ListHeaderComponent={
62
props.notice ? (
63
- <Text className="pb-3 text-xs text-foreground-muted">{props.notice}</Text>
63
+ <View className="items-start gap-2 pb-3">
64
+ <Text className="text-xs text-foreground-muted">{props.notice}</Text>
65
+ {props.loadError && props.candidates.length > 0 ? (
66
+ <Button label="Retry" size="compact" onPress={props.onRetry} />
67
+ ) : null}
68
+ </View>
69
) : undefined
70
}
71
renderItem={({ item, index }) => (
apps/mobile/src/features/issues/IssueEditScreen.tsx
+2
-1
@@ -3,7 +3,7 @@ import { useRef, useState } from "react";
3
4
import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
5
import { Button } from "../../components/ui/Button";
6
-import { issueEnvironment } from "../../state/issues";
6
+import { issueEnvironment, refreshIssueLists } from "../../state/issues";
7
import { useEnvironmentQuery } from "../../state/query";
8
import { useAtomCommand } from "../../state/use-atom-command";
9
import { PullRequestSheetContent } from "../pull-requests/PullRequestSheetContent";
@@ -47,6 +47,7 @@ export function IssueEditScreen({ route }: StaticScreenProps<IssueEditParams>) {
47
setError(failure);
48
return;
49
}
50
+ refreshIssueLists(target.environmentId);
51
navigation.goBack();
52
};
53
return (
apps/mobile/src/features/issues/IssueFilterSearchScreen.tsx
new
+92
@@ -0,0 +1,92 @@
1
+import { useAtom } from "@effect/atom-react";
2
+import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
3
+import type { IssueCandidatesTarget } from "@t3tools/client-runtime/state/issues";
4
+import { useState } from "react";
5
+
6
+import { refreshIssueFilterCandidates, useIssueFilterCandidates } from "../../state/issues";
7
+import { PullRequestLabelDot } from "../pull-requests/PullRequestLabelDot";
8
+import { PullRequestAvatar } from "../pull-requests/PullRequestPresentation";
9
+import { pullRequestLabelColor } from "../pull-requests/pullRequestList";
10
+import { IssueCandidatesSheet } from "./IssueCandidatesSheet";
11
+import { issueListFiltersAtom, unofferedIssueFilters } from "./issueListFilters";
12
+
13
+const matches = (needle: string, ...fields: ReadonlyArray<string | null | undefined>) =>
14
+ needle.length === 0 || fields.some((field) => field?.toLowerCase().includes(needle));
15
+
16
+/** Searches every listed scope's labels or people for the issue list's filter. */
17
+export function IssueFilterSearchScreen({
18
+ route,
19
+}: StaticScreenProps<{
20
+ readonly kind: "labels" | "assignee";
21
+ readonly scopes: ReadonlyArray<IssueCandidatesTarget>;
22
+}>) {
23
+ const navigation = useNavigation();
24
+ const { kind, scopes } = route.params;
25
+ const known = useIssueFilterCandidates(scopes);
26
+ const [filters, setFilters] = useAtom(issueListFiltersAtom);
27
+ const [query, setQuery] = useState("");
28
+ const needle = query.trim().toLowerCase();
29
+ const labels = kind === "labels";
30
+ const unoffered = unofferedIssueFilters(filters, known);
31
+ const candidates = labels
32
+ ? [
33
+ ...unoffered.labels.map((name) => ({ name, description: null, color: null })),
34
+ ...known.labels,
35
+ ]
36
+ .filter((label) => matches(needle, label.name, label.description))
37
+ .map((label) => ({
38
+ key: label.name,
39
+ title: label.name,
40
+ ...(label.description ? { subtitle: label.description } : {}),
41
+ leading: <PullRequestLabelDot color={pullRequestLabelColor(label.color)} />,
42
+ selected: filters.labels.includes(label.name),
43
+ }))
44
+ : [
45
+ ...(unoffered.assignee ? [{ ...unoffered.assignee, avatarUrl: null }] : []),
46
+ ...known.assignees,
47
+ ]
48
+ .filter((actor) => matches(needle, actor.login, actor.name))
49
+ .map((actor) => ({
50
+ key: actor.login,
51
+ title: actor.login,
52
+ ...(actor.name ? { subtitle: actor.name } : {}),
53
+ leading: <PullRequestAvatar actor={actor} size={24} />,
54
+ selected: filters.assignee?.login === actor.login,
55
+ }));
56
+ const loaded = labels ? known.labels.length > 0 : known.assignees.length > 0;
57
+ return (
58
+ <IssueCandidatesSheet
59
+ title={labels ? "Filter by label" : "Filter by assignee"}
60
+ noun={labels ? "labels" : "people"}
61
+ query={query}
62
+ onQueryChange={setQuery}
63
+ candidates={candidates}
64
+ allowed
65
+ notice={candidates.length > 0 ? known.error : null}
66
+ pending={known.isPending && !loaded}
67
+ loadError={known.error}
68
+ onRetry={() => refreshIssueFilterCandidates(scopes)}
69
+ truncated={known.truncated}
70
+ onToggle={(key) => {
71
+ if (labels) {
72
+ setFilters({
73
+ ...filters,
74
+ labels: filters.labels.includes(key)
75
+ ? filters.labels.filter((name) => name !== key)
76
+ : [...filters.labels, key].slice(0, 20),
77
+ });
78
+ return;
79
+ }
80
+ const actor = known.assignees.find((candidate) => candidate.login === key);
81
+ setFilters({
82
+ ...filters,
83
+ assignee:
84
+ filters.assignee?.login === key || !actor
85
+ ? null
86
+ : { login: actor.login, name: actor.name },
87
+ });
88
+ navigation.goBack();
89
+ }}
90
+ />
91
+ );
92
+}
apps/mobile/src/features/issues/IssueLabelsScreen.tsx
+18
-11
@@ -2,6 +2,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
2
import { useAtom } from "@effect/atom-react";
3
import {
4
issueLabelsAfterPicks,
5
+ issuePicksAfterFailedWrite,
6
issuePicksFor,
7
issueWriteAfterPicks,
8
noIssuePicks,
@@ -11,7 +12,7 @@ import type { IssueLabelCandidate } from "@t3tools/contracts";
12
import { useEffect, useState } from "react";
13
14
import * as Dialog from "../../components/ui/Dialog";
14
-import { issueEnvironment } from "../../state/issues";
15
+import { issueEnvironment, refreshIssueLists } from "../../state/issues";
16
import { useEnvironmentQuery } from "../../state/query";
17
import { useAtomCommand } from "../../state/use-atom-command";
18
import { PullRequestLabelDot } from "../pull-requests/PullRequestLabelDot";
@@ -29,12 +30,16 @@ export function IssueLabelsScreen({ route }: StaticScreenProps<IssueParams>) {
30
const result = useEnvironmentQuery(issueEnvironment.candidates(target));
31
const update = useAtomCommand(issueEnvironment.update, { reportFailure: false });
32
const [query, setQuery] = useState("");
32
- const [picks, setPicks] = useAtom(issueLabelPicksFamily(issueParamsKey(route.params)));
33
- // Picks against an older read are dropped when the sheet opens, and kept across a read while open.
34
- const [openedWith] = useState(detail);
35
- const current = detail
36
- ? issuePicksFor(picks, detail, detail !== openedWith)
37
- : noIssuePicks<IssueLabelCandidate>();
33
+ // The atom carries a closed sheet's picks to the next one; this sheet's own live here.
34
+ const [stored, setStored] = useAtom(issueLabelPicksFamily(issueParamsKey(route.params)));
35
+ // Picks against an older read are dropped once, when the sheet opens.
36
+ const [picks, setPicks] = useState(() =>
37
+ detail ? issuePicksFor(stored, detail, false) : noIssuePicks<IssueLabelCandidate>(),
38
+ );
39
+ const own = detail ? issuePicksFor(picks, detail, true) : noIssuePicks<IssueLabelCandidate>();
40
+ // What was last sent is read from the atom, so a write that fails while this sheet is open is
41
+ // sent again when it closes.
42
+ const current = { ...own, written: stored.basis === detail ? stored.written : null };
43
const draft = current.draft;
44
const allowed = access?.labels === true;
45
const applied = new Set(detail?.labels.map((label) => label.name));
@@ -54,15 +59,17 @@ export function IssueLabelsScreen({ route }: StaticScreenProps<IssueParams>) {
59
current.written,
60
);
61
if (labels === null) return;
57
- setPicks({ ...current, written: labels });
62
+ const sent = { ...current, written: labels };
63
+ setStored(sent);
64
void update({ ...target, input: { ...target.input, labels } }).then((response) => {
65
const failure = issueCommandError(response);
60
- if (failure === null) return;
61
- setPicks(noIssuePicks());
66
+ if (failure === null) return refreshIssueLists(target.environmentId);
67
+ // Picks made after this write was sent are kept.
68
+ setStored((latest) => issuePicksAfterFailedWrite(latest, sent));
69
Dialog.alert("Couldn't change labels", failure);
70
});
71
}),
65
- [navigation, detail, draft, current, setPicks, update, target],
72
+ [navigation, detail, draft, current, setStored, update, target],
73
);
74
return (
75
<IssueCandidatesSheet
apps/mobile/src/features/issues/IssueRouteScreen.tsx
+14
-3
@@ -15,7 +15,7 @@ import type {
15
IssueSummary,
16
} from "@t3tools/contracts";
17
import { AsyncResult } from "effect/reactivity";
18
-import { useState } from "react";
18
+import { useRef, useState } from "react";
19
import { Linking, Platform, Pressable, Share, View } from "react-native";
20
import { KeyboardStickyView } from "react-native-keyboard-controller";
21
@@ -38,7 +38,7 @@ import { NativeLayoutObserver } from "../../native/NativeLayoutObserver";
38
import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
39
import { useDeviceType, useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
40
import { NativeScrollView } from "../../native/NativeScrollViewMarker";
41
-import { issueEnvironment } from "../../state/issues";
41
+import { issueEnvironment, refreshIssueLists } from "../../state/issues";
42
import { useEnvironmentQuery } from "../../state/query";
43
import { useAtomCommand } from "../../state/use-atom-command";
44
import { usePullToRefresh } from "../../state/use-pull-to-refresh";
@@ -437,10 +437,15 @@ function IssueRoute({ params }: { readonly params: IssueParams }) {
437
const failure = issueCommandError(await command());
438
setBusy(null);
439
setError(failure);
440
+ // The list beside this issue shows its state and comment count, and reads only when asked.
441
+ if (failure === null) refreshIssueLists(target.environmentId);
442
return failure === null;
443
};
444
+ // Counts refreshes, so a page asked for before one is not laid over the read that follows it.
445
+ const refreshes = useRef(0);
446
const loadOlder = async () => {
447
if (!detail || nextCursor === null || busy !== null) return;
448
+ const asked = refreshes.current;
449
setBusy("older");
450
setError(null);
451
const result = await loadComments({
@@ -448,6 +453,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) {
453
input: { ...target.input, cursor: nextCursor },
454
});
455
setBusy(null);
456
+ if (asked !== refreshes.current) return;
457
if (AsyncResult.isFailure(result)) {
458
setError("Older comments could not be read.");
459
return;
@@ -558,7 +564,12 @@ function IssueRoute({ params }: { readonly params: IssueParams }) {
564
refreshControl={
565
<RefreshControl
566
refreshing={pullRefresh.refreshing}
561
- onRefresh={() => pullRefresh.onRefresh()}
567
+ onRefresh={() => {
568
+ // Older pages are cached under the cursor, which a refresh can hand back unchanged.
569
+ refreshes.current += 1;
570
+ setOlder(null);
571
+ pullRefresh.onRefresh();
572
+ }}
573
/>
574
}
575
contentContainerStyle={{
apps/mobile/src/features/issues/IssuesScreen.tsx
+94
-15
@@ -1,9 +1,11 @@
1
-import { useAtomValue } from "@effect/atom-react";
1
+import { useAtom, useAtomValue } from "@effect/atom-react";
2
import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
3
import {
4
continueIssuePage,
5
groupIssues,
6
holdIssuePages,
7
+ issueFilterScopes,
8
+ issueOrder,
9
type EnvironmentIssueEntry,
10
type HeldIssuePage,
11
} from "@t3tools/client-runtime/issue-list";
@@ -12,6 +14,7 @@ import type {
14
EnvironmentId,
15
IssueInvolvement,
16
IssueListInput,
17
+ IssueListSort,
18
IssueListState,
19
} from "@t3tools/contracts";
20
import { AsyncResult } from "effect/reactivity";
@@ -19,9 +22,11 @@ import { use, useRef, useState, type ReactNode } from "react";
22
import { Keyboard, Platform, ScrollView, View } from "react-native";
23
import { useSafeAreaInsets } from "react-native-safe-area-context";
24
25
+import { useNavigation } from "@react-navigation/native";
26
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
27
import { AppText as Text } from "../../components/ui/AppText";
28
import { Button } from "../../components/ui/Button";
29
+import { Chip } from "../../components/ui/Chip";
30
import { EmptyState } from "../../components/ui/EmptyState";
31
import { usePaneRole } from "../../components/ui/Pane";
32
import { RefreshControl } from "../../components/ui/RefreshControl";
@@ -42,6 +47,8 @@ import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext";
47
import { issueParamsKey } from "./issueParams";
48
import { IssueListRow } from "./IssueListRow";
49
import type { PullRequestFilterMenu } from "../pull-requests/PullRequestListFilters";
50
+import { issueListFiltersAtom } from "./issueListFilters";
51
+import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
52
53
const DEFAULT_ISSUE_LIST_INPUT = { state: "open", involvement: "all", limit: 50 } as const;
54
const STATES = {
@@ -55,6 +62,10 @@ const INVOLVEMENT = {
62
authored: "Opened by you",
63
mentioned: "Mentioning you",
64
} as const satisfies Record<IssueInvolvement, string>;
65
+const SORTS = {
66
+ updated: "Recently updated",
67
+ created: "Newest",
68
+} as const satisfies Record<IssueListSort, string>;
69
// A 12dp inset keeps 16dp chips concentric with Android's 28dp ScreenContent corner.
70
const FILTER_ROW_STYLE =
71
Platform.OS === "android"
@@ -115,11 +126,18 @@ export function IssuesScreen(
126
const query = tab.searchMode === "resting" ? "" : debouncedQuery;
127
const [state, setState] = useState<IssueListState>("open");
128
const [involvement, setInvolvement] = useState<IssueInvolvement>("all");
129
+ const navigation = useNavigation();
130
+ const [{ labels, assignee }, setFilters] = useAtom(issueListFiltersAtom);
131
+ const { themeAppearance } = useAppearancePreferences();
132
+ const [sort, setSort] = useState<IssueListSort>("updated");
133
const listInput: IssueListInput = {
134
...DEFAULT_ISSUE_LIST_INPUT,
135
state,
136
involvement,
137
...(query ? { query } : {}),
138
+ ...(labels.length > 0 ? { labels } : {}),
139
+ ...(assignee === null ? {} : { assignee: assignee.login }),
140
+ ...(sort === "updated" ? {} : { sort }),
141
};
142
const capable = environments.filter(
143
(environment) =>
@@ -165,16 +183,19 @@ export function IssuesScreen(
183
setPages(new Map([...held, ...loaded]));
184
};
185
168
- const groups = groupIssues(held, query, projects);
169
- const entries = groups
170
- .flatMap((group) => group.rows)
171
- .sort((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt));
172
- const notices = groups.flatMap((group) => [
173
- ...(group.tracker.configured
174
- ? []
175
- : [`${group.tracker.host}: ${group.tracker.detail ?? "This tracker cannot be read."}`]),
176
- ...group.errors.map((error) => `${error.projectTitle}: ${error.message}`),
177
- ]);
186
+ const groups = groupIssues(held, query, projects, sort);
187
+ const entries = groups.flatMap((group) => group.rows).sort(issueOrder(sort));
188
+ const filterScopes = issueFilterScopes(held, projects);
189
+ const notices = [
190
+ // An environment that failed while another answered: its issues are missing from the rows.
191
+ ...(entries.length > 0 && list.error ? [list.error] : []),
192
+ ...groups.flatMap((group) => [
193
+ ...(group.tracker.configured
194
+ ? []
195
+ : [`${group.tracker.host}: ${group.tracker.detail ?? "This tracker cannot be read."}`]),
196
+ ...group.errors.map((error) => `${error.projectTitle}: ${error.message}`),
197
+ ]),
198
+ ];
199
200
const paneRole = usePaneRole();
201
const sidebar = props.sidebar === true || (primaryColumn !== null && paneRole === "sidebar");
@@ -198,6 +219,12 @@ export function IssuesScreen(
219
const scrollToTop = () =>
220
void listRef.current?.scrollToOffset({ offset: -contentTopInset, animated: false });
221
222
+ const customized =
223
+ state !== "open" ||
224
+ involvement !== "all" ||
225
+ sort !== "updated" ||
226
+ labels.length > 0 ||
227
+ assignee !== null;
228
// The Android header's filter button opens every filter, as the pull request list's does.
229
const headerMenu: PullRequestFilterMenu | null =
230
Platform.OS === "android"
@@ -210,21 +237,32 @@ export function IssuesScreen(
237
subactions: choices(INVOLVEMENT, involvement, "involvement"),
238
},
239
{
213
- id: "reset",
214
- title: "Reset filters",
215
- attributes: { disabled: state === "open" && involvement === "all" },
240
+ id: "labels",
241
+ title: labels.length === 0 ? "Labels…" : `Labels (${labels.length})…`,
242
},
243
+ {
244
+ id: "assignee",
245
+ title:
246
+ assignee === null ? "Assignee…" : `Assignee: ${assignee.name ?? assignee.login}…`,
247
+ },
248
+ { id: "sort", title: "Sort", subactions: choices(SORTS, sort, "sort") },
249
+ { id: "reset", title: "Reset filters", attributes: { disabled: !customized } },
250
],
251
onSelect: (id) => {
252
const [field, value] = id.split(":");
253
if (field === "state") setState(value as IssueListState);
254
if (field === "involvement") setInvolvement(value as IssueInvolvement);
255
+ if (field === "sort") setSort(value as IssueListSort);
256
+ if (field === "labels" || field === "assignee")
257
+ navigation.navigate("IssueFilterSearch", { kind: field, scopes: filterScopes });
258
if (field === "reset") {
259
setState("open");
260
setInvolvement("all");
261
+ setSort("updated");
262
+ setFilters({ labels: [], assignee: null });
263
}
264
},
227
- customized: state !== "open" || involvement !== "all",
265
+ customized,
266
}
267
: null;
268
@@ -309,6 +347,47 @@ export function IssuesScreen(
347
scrollToTop();
348
}}
349
/>
350
+ <Chip
351
+ label={
352
+ labels.length === 0
353
+ ? "Labels"
354
+ : labels.length === 1
355
+ ? labels[0]!
356
+ : `Labels ${labels.length}`
357
+ }
358
+ selected={labels.length > 0}
359
+ trailingIcon="chevron.down"
360
+ glass
361
+ colorScheme={themeAppearance}
362
+ accessibilityLabel="Filter by label"
363
+ onPress={() =>
364
+ navigation.navigate("IssueFilterSearch", { kind: "labels", scopes: filterScopes })
365
+ }
366
+ />
367
+ <Chip
368
+ label={assignee === null ? "Assignee" : (assignee.name ?? assignee.login)}
369
+ selected={assignee !== null}
370
+ trailingIcon="chevron.down"
371
+ glass
372
+ colorScheme={themeAppearance}
373
+ accessibilityLabel="Filter by assignee"
374
+ onPress={() =>
375
+ navigation.navigate("IssueFilterSearch", {
376
+ kind: "assignee",
377
+ scopes: filterScopes,
378
+ })
379
+ }
380
+ />
381
+ <ListFilterMenu
382
+ label={SORTS[sort]}
383
+ active={sort !== "updated"}
384
+ accessibilityLabel="Sort issues"
385
+ actions={choices(SORTS, sort)}
386
+ onSelect={(id) => {
387
+ setSort(id as IssueListSort);
388
+ scrollToTop();
389
+ }}
390
+ />
391
</ScrollView>
392
{notices.map((notice) => (
393
<Text key={notice} selectable className="px-4 py-1.5 text-sm text-foreground-muted">
apps/mobile/src/features/issues/issueListFilters.test.ts
new
+16
@@ -0,0 +1,16 @@
1
+import { expect, it } from "vite-plus/test";
2
+
3
+import { unofferedIssueFilters } from "./issueListFilters";
4
+
5
+it("keeps the picks the listed scopes no longer offer", () => {
6
+ const offered = { labels: [{ name: "bug" }], assignees: [{ login: "alice" }] };
7
+ expect(
8
+ unofferedIssueFilters(
9
+ { labels: ["bug", "gone"], assignee: { login: "bob", name: "Bob" } },
10
+ offered,
11
+ ),
12
+ ).toEqual({ labels: ["gone"], assignee: { login: "bob", name: "Bob" } });
13
+ expect(
14
+ unofferedIssueFilters({ labels: ["bug"], assignee: { login: "alice", name: null } }, offered),
15
+ ).toEqual({ labels: [], assignee: null });
16
+});
apps/mobile/src/features/issues/issueListFilters.ts
new
+28
@@ -0,0 +1,28 @@
1
+import { Atom } from "effect/reactivity";
2
+
3
+export interface IssueListFilters {
4
+ readonly labels: ReadonlyArray<string>;
5
+ /** Kept with the name the picker showed, so the chip can say who without the candidates. */
6
+ readonly assignee: { readonly login: string; readonly name: string | null } | null;
7
+}
8
+
9
+/** Shared by the list and the sheets that search a tracker for a label or person. */
10
+export const issueListFiltersAtom = Atom.make<IssueListFilters>({
11
+ labels: [],
12
+ assignee: null,
13
+}).pipe(Atom.keepAlive, Atom.withLabel("mobile:issues:list-filters"));
14
+
15
+/** The picks the listed scopes no longer offer, which a picker still lists so they can be removed. */
16
+export function unofferedIssueFilters(
17
+ filters: IssueListFilters,
18
+ offered: {
19
+ readonly labels: ReadonlyArray<{ readonly name: string }>;
20
+ readonly assignees: ReadonlyArray<{ readonly login: string }>;
21
+ },
22
+): IssueListFilters {
23
+ const login = filters.assignee?.login;
24
+ return {
25
+ labels: filters.labels.filter((name) => !offered.labels.some((label) => label.name === name)),
26
+ assignee: offered.assignees.some((actor) => actor.login === login) ? null : filters.assignee,
27
+ };
28
+}
apps/mobile/src/native/useOpenPullRequest.ts
+3
@@ -4,6 +4,7 @@ import {
4
nativePullRequestDestination,
5
pullRequestCandidateForIssueLink,
6
} from "../lib/pullRequestNavigation";
7
+import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
8
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
9
import { useProjects, useThreadShell } from "../state/entities";
10
import { tryOpenExternalUrl } from "../lib/openExternalUrl";
@@ -60,6 +61,8 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean
61
else navigation.dispatch(StackActions.push("PullRequest", params));
62
return true;
63
}
64
+ // A dropped connection says nothing about what the link names; the browser knows.
65
+ if (isAtomCommandInterrupted(preview)) return tryOpenExternalUrl(url, "pull-request");
66
}
67
const issueParams = {
68
environmentId,
apps/mobile/src/state/issues.ts
+16
@@ -1,6 +1,8 @@
1
import {
2
createIssueEnvironmentAtoms,
3
+ createMergedIssueCandidatesAtoms,
4
createMergedIssueListAtoms,
5
+ type IssueCandidatesTarget,
6
type IssueListTarget,
7
} from "@t3tools/client-runtime/state/issues";
8
import { useAtomValue } from "@effect/atom-react";
@@ -27,3 +29,17 @@ export function useIssueList(targets: ReadonlyArray<IssueListTarget>) {
29
export function refreshIssueLists(environmentId: EnvironmentId) {
30
mergedIssueLists.refreshEnvironment(appAtomRegistry, environmentId);
31
}
32
+
33
+const mergedIssueCandidates = createMergedIssueCandidatesAtoms(
34
+ issueEnvironment.candidates,
35
+ formatEnvironmentQueryError,
36
+);
37
+
38
+/** The labels and people of every scope a list filter covers; no targets reads nothing. */
39
+export function useIssueFilterCandidates(targets: ReadonlyArray<IssueCandidatesTarget>) {
40
+ return useAtomValue(mergedIssueCandidates(targets));
41
+}
42
+
43
+export function refreshIssueFilterCandidates(targets: ReadonlyArray<IssueCandidatesTarget>) {
44
+ for (const target of targets) appAtomRegistry.refresh(issueEnvironment.candidates(target));
45
+}
apps/server/src/issue/IssueService.test.ts
+62
-9
@@ -17,6 +17,7 @@ import {
17
type TrackerIssueDetail,
18
} from "@t3tools/source-control-core/server/IssueTracker";
19
20
+import { PersistenceSqlError } from "../persistence/Errors.ts";
21
import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
22
import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
23
@@ -142,6 +143,7 @@ function makeService(input: {
143
readonly projects: ReadonlyArray<OrchestrationProjectShell>;
144
readonly trackers: ReadonlyArray<IssueTrackerApi>;
145
readonly bindings?: Record<string, IssueTrackerProjectBinding>;
146
+ readonly bindingsFailure?: PersistenceSqlError;
147
}) {
148
return IssueService.IssueService.pipe(
149
Effect.provide(
@@ -149,14 +151,17 @@ function makeService(input: {
151
Layer.provide(
152
Layer.mergeAll(
153
Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
152
- list: Effect.succeed(
153
- new Map(
154
- Object.entries(input.bindings ?? {}).map(([id, binding]) => [
155
- id as ProjectId,
156
- binding,
157
- ]),
158
- ),
159
- ),
154
+ list:
155
+ input.bindingsFailure !== undefined
156
+ ? Effect.fail(input.bindingsFailure)
157
+ : Effect.succeed(
158
+ new Map(
159
+ Object.entries(input.bindings ?? {}).map(([id, binding]) => [
160
+ id as ProjectId,
161
+ binding,
162
+ ]),
163
+ ),
164
+ ),
165
}),
166
Layer.succeed(
167
IssueTrackerRegistry.IssueTrackerRegistry,
@@ -233,6 +238,30 @@ describe("IssueService", () => {
238
});
239
expect(writes).toEqual(["acme/web#1"]);
240
241
+ // A link's port picks the server: the project bound with it, not a default-port namesake.
242
+ const ported = yield* makeService({
243
+ projects: [
244
+ project({ id: "plain", repository: "acme/web", provider: "forgejo", host: "gitea.test" }),
245
+ project({
246
+ id: "ported",
247
+ repository: "acme/web",
248
+ provider: "forgejo",
249
+ host: "gitea.test:8443",
250
+ }),
251
+ ],
252
+ trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })],
253
+ });
254
+ expect(yield* ported.resolveUrl("https://gitea.test:8443/acme/web/issues/3")).toMatchObject({
255
+ projectId: "ported",
256
+ host: "gitea.test:8443",
257
+ key: "3",
258
+ writable: true,
259
+ });
260
+ expect(yield* ported.resolveUrl("https://gitea.test/acme/web/issues/3")).toMatchObject({
261
+ projectId: "plain",
262
+ host: "gitea.test",
263
+ });
264
+
265
// Another host is not reachable through this project's credentials at all.
266
const elsewhere = yield* Effect.flip(service.detail({ ...own, host: "ghe.example.test" }));
267
expect(elsewhere).toMatchObject({
@@ -371,7 +400,7 @@ describe("IssueService", () => {
400
expect(
401
result.entries.filter((entry) => entry.projectId === "web").map((entry) => entry.scope),
402
).toEqual(["Acme/Web", "Acme/Web"]);
374
- expect(result.nextCursors).toEqual({ "github.com Acme/Web": "next" });
403
+ expect(result.nextCursors).toEqual({ "github.com acme/web": "next" });
404
expect(result.errors).toEqual([
405
{ projectId: "api", projectTitle: "api", message: "The issue tracker request failed." },
406
]);
@@ -402,6 +431,16 @@ describe("IssueService", () => {
431
expect(next.entries.map((entry) => [entry.projectId, entry.key])).toEqual([["web", "4"]]);
432
expect(next.nextCursors).toEqual({});
433
expect(next.errors).toEqual([]);
434
+
435
+ // The cursor belongs to the scope, not to the project whose spelling first read it.
436
+ listed.length = 0;
437
+ const through = yield* service.list({
438
+ state: "open",
439
+ projectId: "web-worktree" as ProjectId,
440
+ cursors: result.nextCursors,
441
+ });
442
+ expect(listed).toEqual(["acme/web"]);
443
+ expect(through.entries.map((entry) => entry.key)).toEqual(["4"]);
444
}),
445
);
446
});
@@ -476,6 +515,20 @@ describe("IssueService with a standalone tracker", () => {
515
expect(notes.entries.map((entry) => [entry.projectId, entry.scope])).toEqual([
516
["notes", "OPS"],
517
]);
518
+
519
+ // Bindings that cannot be read fail the listing; they are not taken for "none bound".
520
+ const unreadable = yield* makeService({
521
+ projects,
522
+ trackers,
523
+ bindingsFailure: new PersistenceSqlError({
524
+ operation: "IssueTrackerBindingsRepository.list",
525
+ detail: "disk I/O error",
526
+ }),
527
+ });
528
+ expect(yield* Effect.flip(unreadable.list({ state: "open" }))).toMatchObject({
529
+ _tag: "IssueOperationError",
530
+ operation: "listProjects",
531
+ });
532
}),
533
);
534
});
apps/server/src/issue/IssueService.ts
+27
-8
@@ -91,8 +91,9 @@ function resolveGitHostBinding(project: OrchestrationProjectShell): ProjectTrack
91
};
92
}
93
94
+/** Lower case, so a scope keeps its cursor whichever project's spelling of it is read. */
95
function listCursorKey(host: string, scope: string): string {
95
- return `${host} ${scope}`;
96
+ return `${host} ${scope.toLowerCase()}`;
97
}
98
99
function isTrackerUnusable(error: IssueTrackerError): boolean {
@@ -172,7 +173,7 @@ const make = Effect.gen(function* () {
173
// Read per resolution so a binding saved in Settings applies without a restart.
174
const resolveStandaloneBinding = (
175
project: OrchestrationProjectShell,
175
- ): Effect.Effect<ProjectTrackerBinding | null> =>
176
+ ): Effect.Effect<ProjectTrackerBinding | null, IssueOperationError> =>
177
bindings.list.pipe(
178
Effect.map((bound) => {
179
const binding = bound.get(project.id);
@@ -184,7 +185,15 @@ const make = Effect.gen(function* () {
185
scope: binding.scope,
186
};
187
}),
187
- Effect.orElseSucceed(() => null),
188
+ // A failed read is not an unbound project: that would list the git host's issues alone.
189
+ Effect.mapError(
190
+ (cause) =>
191
+ new IssueOperationError({
192
+ operation: "listProjects",
193
+ detail: "The project's issue tracker binding could not be read.",
194
+ cause,
195
+ }),
196
+ ),
197
);
198
199
/**
@@ -193,7 +202,7 @@ const make = Effect.gen(function* () {
202
*/
203
const resolveProjectTracker = (
204
project: OrchestrationProjectShell,
196
- ): Effect.Effect<ReadonlyArray<ProjectTrackerBinding>> =>
205
+ ): Effect.Effect<ReadonlyArray<ProjectTrackerBinding>, IssueOperationError> =>
206
Effect.all([
207
resolveStandaloneBinding(project),
208
(project.repositoryIdentity != null
@@ -209,6 +218,8 @@ const make = Effect.gen(function* () {
218
const listProjects = (filter: {
219
readonly projectId?: IssueListInput["projectId"];
220
readonly host?: string | undefined;
221
+ /** The link's `host:port`, for a host whose binding keeps its port. */
222
+ readonly authority?: string | undefined;
223
}) =>
224
(filter.projectId === undefined
225
? projects.listShells()
@@ -240,7 +251,8 @@ const make = Effect.gen(function* () {
251
{ tracker: IssueTrackerKind; projectCount: number }
252
>();
253
for (const candidate of bound.flat()) {
243
- if (host !== undefined && candidate.host !== host) continue;
254
+ if (host !== undefined && candidate.host !== host && candidate.host !== filter.authority)
255
+ continue;
256
const api = registry.get(candidate.tracker);
257
if (api === null) {
258
const counted = unimplemented.get(candidate.host);
@@ -295,7 +307,7 @@ const make = Effect.gen(function* () {
307
// DevOps project shares its work items; read each scope once.
308
const scopes = new Map<string, SupportedProject>();
309
for (const project of supported) {
298
- const key = listCursorKey(project.host, project.scope).toLowerCase();
310
+ const key = listCursorKey(project.host, project.scope);
311
if (!scopes.has(key)) scopes.set(key, project);
312
}
313
const continuing = input.cursors;
@@ -362,6 +374,9 @@ const make = Effect.gen(function* () {
374
viewer,
375
limit,
376
query: input.query,
377
+ labels: input.labels,
378
+ assignee: input.assignee,
379
+ sort: input.sort ?? "updated",
380
cursor,
381
}),
382
),
@@ -623,10 +638,14 @@ const make = Effect.gen(function* () {
638
});
639
}
640
const { definition, link } = parsed;
626
- const { supported } = yield* listProjects({ host: link.host });
627
- const onTracker = supported.filter(
641
+ // A link names its server's port; a binding does only when its remote or web URL did.
642
+ const authority = new URL(url).host.toLowerCase();
643
+ const { supported } = yield* listProjects({ host: link.host, authority });
644
+ const onHost = supported.filter(
645
(project) => project.tracker === IssueTrackerKind.make(definition.kind),
646
);
647
+ const onAuthority = onHost.filter((project) => project.host === authority);
648
+ const onTracker = onAuthority.length > 0 ? onAuthority : onHost;
649
const preferFirst = (projects: ReadonlyArray<SupportedProject>) =>
650
projects.find((project) => project.project.id === preferredProjectId) ?? projects[0];
651
const own = preferFirst(
apps/server/src/mcp/toolkits/issues/handlers.test.ts
+5
@@ -266,6 +266,11 @@ describe("issue toolkit handlers", () => {
266
const result = yield* harness.call("link_issue", { key: "7" });
267
expect(result.url).toBe(detail.url);
268
expect((yield* Ref.get(harness.links))[0]?.url).toBe(detail.url);
269
+ // Named by key and never read: the identity has no URL rather than an empty one, so it can
270
+ // be handed to another issue tool as it is.
271
+ const unlinked = yield* harness.call("unlink_issue", { key: "7" });
272
+ expect(unlinked).toMatchObject({ key: "7", wasLinked: false });
273
+ expect(unlinked).not.toHaveProperty("url");
274
}),
275
);
276
apps/server/src/mcp/toolkits/issues/handlers.ts
+5
-4
@@ -1,6 +1,5 @@
1
import {
2
threadIssueKeysEqual,
3
- type IssueDetail,
3
type IssueRef,
4
type OrchestrationV2ThreadShell,
5
type ProjectId,
@@ -122,13 +121,14 @@ const make = Effect.gen(function* () {
121
} satisfies ResolvedTarget;
122
});
123
125
- const identityOf = (target: ResolvedTarget, detail?: Pick<IssueDetail, "url">) => ({
124
+ /** Without a URL when the issue was named by key and never read: an empty one is not reusable. */
125
+ const identityOf = (target: ResolvedTarget) => ({
126
projectId: target.projectId,
127
tracker: target.tracker,
128
host: target.host,
129
scope: target.scope,
130
key: target.key,
131
- url: target.url ?? detail?.url ?? "",
131
+ ...(target.url === null ? {} : { url: target.url }),
132
});
133
134
const refOf = (target: ResolvedTarget): IssueRef & { readonly host: string } => ({
@@ -191,7 +191,8 @@ const make = Effect.gen(function* () {
191
const target = yield* resolveTarget(input);
192
const detail = yield* issues.detail(refOf(target));
193
return {
194
- ...identityOf(target, detail),
194
+ ...identityOf(target),
195
+ url: target.url ?? detail.url,
196
displayKey: detail.displayKey,
197
title: detail.title,
198
state: detail.state,
apps/server/src/mcp/toolkits/issues/tools.ts
+6
-4
@@ -131,14 +131,16 @@ export const IssueToolError = Schema.Union([
131
export type IssueToolError = typeof IssueToolError.Type;
132
133
/** How a tool names an issue back: enough to pass to any other issue tool. */
134
-const IssueIdentity = {
134
+const IssueKeyIdentity = {
135
projectId: ProjectId,
136
tracker: IssueTrackerKind,
137
host: Schema.String,
138
scope: Schema.String,
139
key: Schema.String,
140
- url: Schema.String,
140
};
141
+const IssueIdentity = { ...IssueKeyIdentity, url: Schema.String };
142
+/** A write named by key alone never read the issue, so it has no URL to hand back. */
143
+const IssueIdentityAfterWrite = { ...IssueKeyIdentity, url: Schema.optional(Schema.String) };
144
145
export const IssueEntry = Schema.Struct({
146
...IssueIdentity,
@@ -203,7 +205,7 @@ export const CreateIssueResult = Schema.Struct({
205
});
206
export type CreateIssueResult = typeof CreateIssueResult.Type;
207
206
-export const IssueWriteResult = Schema.Struct({ ...IssueIdentity });
208
+export const IssueWriteResult = Schema.Struct({ ...IssueIdentityAfterWrite });
209
210
export const ThreadIssueEntry = Schema.Struct({
211
...IssueIdentity,
@@ -223,7 +225,7 @@ export const LinkIssueResult = Schema.Struct({
225
export type LinkIssueResult = typeof LinkIssueResult.Type;
226
227
export const UnlinkIssueResult = Schema.Struct({
226
- ...IssueIdentity,
228
+ ...IssueIdentityAfterWrite,
229
wasLinked: Schema.Boolean.annotate({
230
description: "False when the issue was not linked to this thread to begin with.",
231
}),
apps/web/src/components/issue/IssueDetailPanel.tsx
+19
-7
@@ -9,6 +9,7 @@ import {
9
issueAssigneeHeld,
10
issueAssigneesAfterPicks,
11
issueLabelsAfterPicks,
12
+ issuePicksAfterFailedWrite,
13
issuePicksFor,
14
issueWriteAfterPicks,
15
noIssuePicks,
@@ -43,7 +44,7 @@ import {
44
import { useState, type ReactNode } from "react";
45
46
import { RefreshIcon } from "~/components/ui/refresh-icon";
46
-import { issueEnvironment } from "~/state/issues";
47
+import { issueEnvironment, refreshIssueLists } from "~/state/issues";
48
import { useProjects, useThreadShell } from "~/state/entities";
49
import { useEnvironmentQuery } from "~/state/query";
50
import { useEnvironmentScope } from "~/state/session";
@@ -228,10 +229,14 @@ function IssueLabelPicker({
229
current.written,
230
);
231
if (labels === null) return;
231
- setPicks({ ...current, written: labels });
232
+ const sent = { ...current, written: labels };
233
+ setPicks(sent);
234
void update({ environmentId, input: { ...reference, labels } }).then((result) => {
233
- if (result._tag !== "Failure") return;
234
- setPicks((latest) => (latest.written === labels ? noIssuePicks() : latest));
235
+ if (result._tag !== "Failure") {
236
+ refreshIssueLists(environmentId);
237
+ return;
238
+ }
239
+ setPicks((latest) => issuePicksAfterFailedWrite(latest, sent));
240
toastManager.add({
241
type: "error",
242
title: "Could not change labels",
@@ -333,10 +338,14 @@ function IssueAssigneePicker({
338
current.written,
339
);
340
if (assignees === null) return;
336
- setPicks({ ...current, written: assignees });
341
+ const sent = { ...current, written: assignees };
342
+ setPicks(sent);
343
void update({ environmentId, input: { ...reference, assignees } }).then((result) => {
338
- if (result._tag !== "Failure") return;
339
- setPicks((latest) => (latest.written === assignees ? noIssuePicks() : latest));
344
+ if (result._tag !== "Failure") {
345
+ refreshIssueLists(environmentId);
346
+ return;
347
+ }
348
+ setPicks((latest) => issuePicksAfterFailedWrite(latest, sent));
349
toastManager.add({
350
type: "error",
351
title: "Could not change assignees",
@@ -533,6 +542,7 @@ export function IssueDetailPanel({
542
});
543
return;
544
}
545
+ refreshIssueLists(environmentId);
546
setEditing(null);
547
};
548
@@ -550,7 +560,9 @@ export function IssueDetailPanel({
560
title: "The state could not be changed",
561
description: readableFailure(squashAtomCommandFailure(result), "The tracker refused it."),
562
});
563
+ return;
564
}
565
+ refreshIssueLists(environmentId);
566
};
567
568
const stateControl: ReactNode = canSetState ? (
apps/web/src/components/issue/IssueListFilterPickers.tsx
new
+229
@@ -0,0 +1,229 @@
1
+import type { IssueCandidatesTarget } from "@t3tools/client-runtime/state/issues";
2
+import type { IssueInvolvement, IssueListState } from "@t3tools/contracts";
3
+import { LayersIcon, ListFilterIcon, TagIcon, UserIcon } from "lucide-react";
4
+import { useState } from "react";
5
+
6
+import { Button } from "~/components/ui/button";
7
+import {
8
+ Menu,
9
+ MenuCheckboxItem,
10
+ MenuItem,
11
+ MenuPopup,
12
+ MenuRadioGroup,
13
+ MenuRadioItem,
14
+ MenuSearchInput,
15
+ MenuSeparator,
16
+ MenuSub,
17
+ MenuSubPopup,
18
+ MenuSubTrigger,
19
+ MenuTrigger,
20
+} from "~/components/ui/menu";
21
+import { useIssueFilterCandidates } from "~/state/issues";
22
+
23
+import {
24
+ PullRequestFilterRadioSubmenu,
25
+ type PullRequestFilterOption,
26
+} from "../pullRequest/PullRequestListFilters";
27
+import { pullRequestLabelColor } from "../pullRequest/pullRequestList.logic";
28
+
29
+const VISIBLE_CHOICES = 30;
30
+const matches = (needle: string, ...fields: ReadonlyArray<string | null | undefined>) =>
31
+ needle.length === 0 || fields.some((field) => field?.toLowerCase().includes(needle));
32
+
33
+/** Every issue list filter behind one button, as the pull request page keeps its own. */
34
+export function IssueFiltersMenu(props: {
35
+ state: IssueListState;
36
+ stateOptions: ReadonlyArray<PullRequestFilterOption<IssueListState>>;
37
+ onState: (state: IssueListState) => void;
38
+ involvement: IssueInvolvement;
39
+ involvementOptions: ReadonlyArray<PullRequestFilterOption<IssueInvolvement>>;
40
+ onInvolvement: (involvement: IssueInvolvement) => void;
41
+ scopes: ReadonlyArray<IssueCandidatesTarget>;
42
+ labels: ReadonlyArray<string>;
43
+ onLabels: (labels: ReadonlyArray<string>) => void;
44
+ assignee: string | undefined;
45
+ onAssignee: (assignee: string | undefined) => void;
46
+}) {
47
+ const [open, setOpen] = useState(false);
48
+ const count = [
49
+ props.state !== "open",
50
+ props.involvement !== "all",
51
+ props.assignee,
52
+ ...props.labels,
53
+ ].filter(Boolean).length;
54
+ // Read when the menu opens, not with every listing: one request per scope.
55
+ const scopes = open ? props.scopes : [];
56
+ return (
57
+ <Menu onOpenChange={setOpen}>
58
+ <MenuTrigger render={<Button variant="outline" />}>
59
+ <ListFilterIcon className="size-4" />
60
+ <span>Filters</span>
61
+ {count > 0 ? (
62
+ <span className="rounded-full bg-muted px-1.5 text-xs text-muted-foreground tabular-nums">
63
+ {count}
64
+ </span>
65
+ ) : null}
66
+ </MenuTrigger>
67
+ <MenuPopup align="end" side="bottom">
68
+ <PullRequestFilterRadioSubmenu
69
+ label="State"
70
+ value={props.state}
71
+ options={props.stateOptions}
72
+ onChange={props.onState}
73
+ />
74
+ <PullRequestFilterRadioSubmenu
75
+ label="Involvement"
76
+ value={props.involvement}
77
+ options={props.involvementOptions}
78
+ onChange={props.onInvolvement}
79
+ />
80
+ <MenuSeparator />
81
+ <MenuSub>
82
+ <MenuSubTrigger>
83
+ <TagIcon aria-hidden className="size-3.5" />
84
+ <span className="flex-1">Labels</span>
85
+ <span className="min-w-0 max-w-32 truncate text-xs text-muted-foreground">
86
+ {props.labels.length === 0
87
+ ? "Any"
88
+ : props.labels.length === 1
89
+ ? props.labels[0]
90
+ : `${props.labels.length} labels`}
91
+ </span>
92
+ </MenuSubTrigger>
93
+ <MenuSubPopup>
94
+ <LabelChoices scopes={scopes} value={props.labels} onChange={props.onLabels} />
95
+ </MenuSubPopup>
96
+ </MenuSub>
97
+ <MenuSub>
98
+ <MenuSubTrigger>
99
+ <UserIcon aria-hidden className="size-3.5" />
100
+ <span className="flex-1">Assignee</span>
101
+ <span className="min-w-0 max-w-32 truncate text-xs text-muted-foreground">
102
+ {props.assignee ?? "Anyone"}
103
+ </span>
104
+ </MenuSubTrigger>
105
+ <MenuSubPopup>
106
+ <AssigneeChoices scopes={scopes} value={props.assignee} onChange={props.onAssignee} />
107
+ </MenuSubPopup>
108
+ </MenuSub>
109
+ </MenuPopup>
110
+ </Menu>
111
+ );
112
+}
113
+
114
+function LabelChoices(props: {
115
+ scopes: ReadonlyArray<IssueCandidatesTarget>;
116
+ value: ReadonlyArray<string>;
117
+ onChange: (value: ReadonlyArray<string>) => void;
118
+}) {
119
+ const [query, setQuery] = useState("");
120
+ const known = useIssueFilterCandidates(props.scopes);
121
+ const needle = query.trim().toLowerCase();
122
+ const found = known.labels.filter((label) => matches(needle, label.name, label.description));
123
+ // Chosen labels lead, so one the tracker's first page lacks can still be seen and cleared.
124
+ const visible = [
125
+ ...props.value
126
+ .filter((name) => !found.some((label) => label.name === name))
127
+ .map((name) => ({ name, color: null })),
128
+ ...found,
129
+ ].slice(0, VISIBLE_CHOICES);
130
+ return (
131
+ <>
132
+ <MenuSearchInput
133
+ autoFocus
134
+ busy={known.isPending}
135
+ value={query}
136
+ onChange={(event) => setQuery(event.currentTarget.value)}
137
+ placeholder="Search labels"
138
+ aria-label="Search labels"
139
+ />
140
+ {visible.length === 0 && !known.isPending ? (
141
+ <MenuItem disabled>
142
+ {known.error === null ? "No labels found" : "The labels could not be read"}
143
+ </MenuItem>
144
+ ) : null}
145
+ {visible.map((label) => {
146
+ const dot = pullRequestLabelColor(label.color);
147
+ return (
148
+ <MenuCheckboxItem
149
+ key={label.name}
150
+ checked={props.value.includes(label.name)}
151
+ onCheckedChange={(next) =>
152
+ props.onChange(
153
+ next
154
+ ? [...props.value, label.name].slice(0, 20)
155
+ : props.value.filter((name) => name !== label.name),
156
+ )
157
+ }
158
+ >
159
+ <span className="flex min-w-0 items-center gap-2">
160
+ <span
161
+ aria-hidden
162
+ className="size-2.5 shrink-0 rounded-full bg-muted-foreground"
163
+ {...(dot ? { style: { backgroundColor: dot } } : {})}
164
+ />
165
+ <span className="min-w-0 flex-1 truncate">{label.name}</span>
166
+ </span>
167
+ </MenuCheckboxItem>
168
+ );
169
+ })}
170
+ {known.truncated ? (
171
+ <MenuItem disabled>More labels exist than are listed here.</MenuItem>
172
+ ) : null}
173
+ </>
174
+ );
175
+}
176
+
177
+function AssigneeChoices(props: {
178
+ scopes: ReadonlyArray<IssueCandidatesTarget>;
179
+ value: string | undefined;
180
+ onChange: (value: string | undefined) => void;
181
+}) {
182
+ const [query, setQuery] = useState("");
183
+ const known = useIssueFilterCandidates(props.scopes);
184
+ const needle = query.trim().toLowerCase();
185
+ const found = known.assignees.filter((actor) => matches(needle, actor.login, actor.name));
186
+ const visible = [
187
+ ...(props.value !== undefined && !found.some((actor) => actor.login === props.value)
188
+ ? [{ login: props.value, name: null }]
189
+ : []),
190
+ ...found,
191
+ ].slice(0, VISIBLE_CHOICES);
192
+ return (
193
+ <>
194
+ <MenuSearchInput
195
+ autoFocus
196
+ busy={known.isPending}
197
+ value={query}
198
+ onChange={(event) => setQuery(event.currentTarget.value)}
199
+ placeholder="Search people"
200
+ aria-label="Search people"
201
+ />
202
+ <MenuRadioGroup
203
+ value={props.value ?? ""}
204
+ onValueChange={(next) => props.onChange(next || undefined)}
205
+ >
206
+ <MenuRadioItem value="">
207
+ <span className="flex min-w-0 items-center gap-2">
208
+ <LayersIcon aria-hidden className="size-3.5" />
209
+ Anyone
210
+ </span>
211
+ </MenuRadioItem>
212
+ {visible.map((actor) => (
213
+ <MenuRadioItem key={actor.login} value={actor.login}>
214
+ <span className="min-w-0 flex-1 truncate">
215
+ {actor.login}
216
+ {actor.name ? <span className="text-muted-foreground"> · {actor.name}</span> : null}
217
+ </span>
218
+ </MenuRadioItem>
219
+ ))}
220
+ </MenuRadioGroup>
221
+ {visible.length === 0 && !known.isPending && known.error !== null ? (
222
+ <MenuItem disabled>The people could not be read</MenuItem>
223
+ ) : null}
224
+ {known.truncated ? (
225
+ <MenuItem disabled>More people exist than are listed here.</MenuItem>
226
+ ) : null}
227
+ </>
228
+ );
229
+}
apps/web/src/components/issue/IssuesPage.tsx
+69
-36
@@ -3,6 +3,8 @@ import {
3
continueIssuePage,
4
groupIssues,
5
holdIssuePages,
6
+ issueCursorsForHost,
7
+ issueFilterScopes,
8
issueTrackerKey,
9
type HeldIssuePage,
10
} from "@t3tools/client-runtime/issue-list";
@@ -11,6 +13,7 @@ import type {
13
EnvironmentId,
14
IssueInvolvement,
15
IssueListInput,
16
+ IssueListSort,
17
IssueListState,
18
IssueTrackerKind,
19
IssueTrackerSummary,
@@ -18,8 +21,11 @@ import type {
21
} from "@t3tools/contracts";
22
import { useNavigate, useSearch } from "@tanstack/react-router";
23
import {
24
+ ArrowDownUpIcon,
25
AtSignIcon,
26
+ CalendarArrowDownIcon,
27
CircleCheckIcon,
28
+ ClockIcon,
29
LayersIcon,
30
PenLineIcon,
31
Plug2Icon,
@@ -44,6 +50,8 @@ import {
50
PullRequestSearchInput,
51
type PullRequestFilterOption,
52
} from "~/components/pullRequest/PullRequestListFilters";
53
+import { IssueFiltersMenu } from "./IssueListFilterPickers";
54
+import { PullRequestCompactFilterMenu } from "../pullRequest/PullRequestCompactFilterMenu";
55
import { PullRequestsUnavailableState } from "~/components/pullRequest/PullRequestsUnavailableState";
56
import { RightPanelTabs } from "~/components/RightPanelTabs";
57
import { WorkspaceBreadcrumb, WorkspaceBreadcrumbItem } from "~/components/WorkspaceBreadcrumb";
@@ -60,7 +68,6 @@ import {
68
} from "~/components/ui/empty";
69
import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "~/components/ui/menu";
70
import { SidebarInset } from "~/components/ui/sidebar";
63
-import { Toggle, ToggleGroup } from "~/components/ui/toggle-group";
71
import { isElectron } from "~/env";
72
import { useLiveRefresh } from "~/hooks/useLiveRefresh";
73
import { shortcutLabelForCommand } from "~/keybindings";
@@ -106,6 +113,11 @@ const INVOLVEMENT_TABS = [
113
{ value: "mentioned", label: "Mentioning me", Icon: AtSignIcon },
114
] as const satisfies ReadonlyArray<PullRequestFilterOption<IssueInvolvement>>;
115
116
+const SORT_OPTIONS = [
117
+ { value: "updated", label: "Recently updated", Icon: ClockIcon },
118
+ { value: "created", label: "Newest", Icon: CalendarArrowDownIcon },
119
+] as const satisfies ReadonlyArray<PullRequestFilterOption<IssueListSort>>;
120
+
121
const PAGE_SIZE = 50;
122
const EMPTY_SET: ReadonlySet<string> = new Set();
123
const EMPTY_RECORD = {} as const;
@@ -123,11 +135,15 @@ function getShortcutContext() {
135
};
136
}
137
126
-function hostOptionsFor(groups: ReturnType<typeof groupIssues>) {
138
+function hostOptionsFor(groups: ReturnType<typeof groupIssues>, chosen: string | undefined) {
139
const hosts = new Map<string, IssueTrackerSummary>();
140
for (const group of groups) hosts.set(group.tracker.host, group.tracker);
141
return [
142
{ value: "", label: "All", Icon: Plug2Icon },
143
+ // A remembered host no project is on any more stays listed, so the filter can be taken off.
144
+ ...(chosen !== undefined && !hosts.has(chosen)
145
+ ? [{ value: chosen, label: chosen, Icon: Plug2Icon }]
146
+ : []),
147
...[...hosts.values()].map((tracker) => ({
148
value: tracker.host,
149
label:
@@ -160,6 +176,9 @@ export function IssuesPage() {
176
limit: PAGE_SIZE,
177
...(search.host ? { host: search.host } : {}),
178
...(debouncedQuery ? { query: debouncedQuery } : {}),
179
+ ...(search.label?.length ? { labels: search.label } : {}),
180
+ ...(search.assignee ? { assignee: search.assignee } : {}),
181
+ ...(search.order ? { sort: search.order } : {}),
182
};
183
const targets: ReadonlyArray<IssueListTarget> = capableEnvironments.map((e) => ({
184
environmentId: e.environmentId,
@@ -171,15 +190,14 @@ export function IssuesPage() {
190
const [pages, setPages] = useState<ReadonlyMap<EnvironmentId, HeldIssuePage>>(new Map());
191
const held = holdIssuePages(list.answers, pages);
192
const loadPage = useAtomCommand(issueEnvironment.listPage, { reportFailure: false });
174
- const [loadingMore, setLoadingMore] = useState<EnvironmentId | null>(null);
175
- const loadMore = async (environmentId: EnvironmentId) => {
193
+ const [loadingMore, setLoadingMore] = useState<string | null>(null);
194
+ // One tracker group's button carries on that tracker's scopes only.
195
+ const loadMore = async (environmentId: EnvironmentId, host: string) => {
196
const page = held.get(environmentId);
177
- if (!page || Object.keys(page.nextCursors).length === 0 || loadingMore !== null) return;
178
- setLoadingMore(environmentId);
179
- const result = await loadPage({
180
- environmentId,
181
- input: { ...listInput, cursors: page.nextCursors },
182
- });
197
+ const cursors = page ? issueCursorsForHost(page.nextCursors, host) : {};
198
+ if (!page || Object.keys(cursors).length === 0 || loadingMore !== null) return;
199
+ setLoadingMore(`${environmentId} ${host}`);
200
+ const result = await loadPage({ environmentId, input: { ...listInput, cursors } });
201
setLoadingMore(null);
202
const failure = result._tag === "Failure" ? squashAtomCommandFailure(result) : null;
203
setPages((current) => {
@@ -191,6 +209,7 @@ export function IssuesPage() {
209
result._tag === "Failure"
210
? { failure: failure instanceof Error ? failure.message : "The next page failed." }
211
: result.value,
212
+ cursors,
213
),
214
);
215
return next;
@@ -199,9 +218,10 @@ export function IssuesPage() {
218
219
// Rows grouped per tracker account, so a tracker that cannot be read says so where its rows
220
// would be, and each tracker's rows carry on from their own cursors.
202
- const groups = groupIssues(held, debouncedQuery, projects);
221
+ const groups = groupIssues(held, debouncedQuery, projects, search.order ?? "updated");
222
+ const filterScopes = issueFilterScopes(held, projects);
223
204
- const hostOptions = hostOptionsFor(groups);
224
+ const hostOptions = hostOptionsFor(groups, search.host);
225
226
const updateSearch = (patch: { [Key in keyof IssuesSearch]?: IssuesSearch[Key] | undefined }) => {
227
const merged = { ...search, ...patch };
@@ -210,6 +230,9 @@ export function IssuesPage() {
230
status: merged.status ?? search.status,
231
...(merged.host ? { host: merged.host } : {}),
232
q: merged.q || undefined,
233
+ ...(merged.label?.length ? { label: merged.label } : {}),
234
+ ...(merged.assignee ? { assignee: merged.assignee } : {}),
235
+ ...(merged.order ? { order: merged.order } : {}),
236
...(merged.selectedEnvironmentId
237
? { selectedEnvironmentId: merged.selectedEnvironmentId }
238
: {}),
@@ -381,6 +404,14 @@ export function IssuesPage() {
404
</Empty>
405
) : (
406
<div className="flex flex-col gap-6">
407
+ {list.error ? (
408
+ <div className="flex items-center justify-between gap-3 rounded-lg border border-warning/30 bg-warning-surface px-3 py-2 text-xs">
409
+ <span>{list.error} Showing the issues that loaded.</span>
410
+ <Button size="xs" variant="outline" onClick={list.refresh}>
411
+ Retry
412
+ </Button>
413
+ </div>
414
+ ) : null}
415
{groups.map((group) => {
416
const presentation = issueTrackerPresentation(group.tracker.tracker);
417
const showScope = new Set(group.rows.map((row) => row.scope.toLowerCase())).size > 1;
@@ -451,9 +482,9 @@ export function IssuesPage() {
482
variant="ghost-muted"
483
className="self-start"
484
disabled={loadingMore !== null}
454
- onClick={() => void loadMore(environmentId)}
485
+ onClick={() => void loadMore(environmentId, group.tracker.host)}
486
>
456
- {loadingMore === environmentId
487
+ {loadingMore === `${environmentId} ${group.tracker.host}`
488
? "Loading…"
489
: moreFailure === null
490
? "Load more"
@@ -510,7 +541,7 @@ export function IssuesPage() {
541
<div className="topbar-scroll-fade scrollbar-gutter-both min-h-0 flex-1 overflow-y-auto">
542
<WorkspacePageContainer width="expanded" className="min-h-full gap-4">
543
<div className="flex flex-wrap items-center gap-2">
513
- <div className="min-w-0 basis-full @lg/issue-list:basis-0 @lg/issue-list:flex-1">
544
+ <div className="min-w-0 basis-full @lg/issue-list:min-w-48 @lg/issue-list:basis-0 @lg/issue-list:flex-1">
545
<PullRequestSearchInput
546
value={search.q ?? ""}
547
label="Search issues"
@@ -523,27 +554,29 @@ export function IssuesPage() {
554
onSubmit={(q) => updateSearch({ q: q || undefined })}
555
/>
556
</div>
526
- <ToggleGroup
527
- size="segmented"
528
- variant="segmented"
529
- aria-label="Filter by state"
530
- value={[search.status]}
531
- onValueChange={(next) => {
532
- const status = STATE_TABS.find((tab) => tab.value === next[0])?.value;
533
- if (status) updateSearch({ status });
534
- }}
535
- >
536
- {STATE_TABS.map((tab) => (
537
- <Toggle key={tab.value} value={tab.value}>
538
- {tab.label}
539
- </Toggle>
540
- ))}
541
- </ToggleGroup>
542
- <FilterMenu
543
- label="Filter by involvement"
544
- value={search.who}
545
- options={INVOLVEMENT_TABS}
546
- onChange={(who) => updateSearch({ who })}
557
+ <PullRequestCompactFilterMenu
558
+ label="Sort issues"
559
+ triggerIcon={<ArrowDownUpIcon aria-hidden className="size-4" />}
560
+ triggerLabel="Sort"
561
+ outlined
562
+ value={search.order ?? "updated"}
563
+ options={SORT_OPTIONS}
564
+ onChange={(order) =>
565
+ updateSearch({ order: order === "created" ? "created" : undefined })
566
+ }
567
+ />
568
+ <IssueFiltersMenu
569
+ state={search.status}
570
+ stateOptions={STATE_TABS}
571
+ onState={(status) => updateSearch({ status })}
572
+ involvement={search.who}
573
+ involvementOptions={INVOLVEMENT_TABS}
574
+ onInvolvement={(who) => updateSearch({ who })}
575
+ scopes={filterScopes}
576
+ labels={search.label ?? []}
577
+ onLabels={(label) => updateSearch({ label })}
578
+ assignee={search.assignee}
579
+ onAssignee={(assignee) => updateSearch({ assignee })}
580
/>
581
{hostOptions.length > 1 ? (
582
<FilterMenu
apps/web/src/components/issue/issueListPreferences.ts
+13
@@ -13,6 +13,10 @@ export interface IssueListPreferences {
13
readonly status: IssueListState;
14
readonly host?: string;
15
readonly q?: string | undefined;
16
+ /** `label`, `assignee` and `order` for the same reason: the pull-request page has `labels` and `sort`. */
17
+ readonly label?: ReadonlyArray<string> | undefined;
18
+ readonly assignee?: string | undefined;
19
+ readonly order?: "created" | undefined;
20
}
21
22
const DEFAULT_ISSUE_LIST_PREFERENCES = {
@@ -28,6 +32,9 @@ const IssueListPreferencesSchema = Schema.Struct({
32
status: IssueListState,
33
host: Schema.optional(BoundedPreference),
34
q: Schema.optional(BoundedPreference),
35
+ label: Schema.optional(Schema.Array(BoundedPreference).check(Schema.isMaxLength(20))),
36
+ assignee: Schema.optional(BoundedPreference),
37
+ order: Schema.optional(Schema.Literal("created")),
38
});
39
const decodePreferences = Schema.decodeUnknownOption(IssueListPreferencesSchema);
40
@@ -43,12 +50,18 @@ export function issueListPreferences(search: {
50
readonly status: IssueListState;
51
readonly host?: string | undefined;
52
readonly q?: string | undefined;
53
+ readonly label?: ReadonlyArray<string> | undefined;
54
+ readonly assignee?: string | undefined;
55
+ readonly order?: "created" | undefined;
56
}): IssueListPreferences {
57
return {
58
who: search.who,
59
status: search.status,
60
...(search.host ? { host: search.host } : {}),
61
...(search.q ? { q: search.q } : {}),
62
+ ...(search.label?.length ? { label: search.label } : {}),
63
+ ...(search.assignee ? { assignee: search.assignee } : {}),
64
+ ...(search.order ? { order: search.order } : {}),
65
};
66
}
67
apps/web/src/components/issue/issuesSearch.logic.test.ts
new
+19
@@ -0,0 +1,19 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { issuesSearchFromUrl } from "./issuesSearch.logic";
4
+
5
+describe("issuesSearchFromUrl", () => {
6
+ it("replaces a malformed label or order instead of letting the raw value through", () => {
7
+ // The router lays the validated keys over the raw search, so a key left out keeps its raw value.
8
+ const raw = { label: true, order: "oldest", assignee: " " };
9
+ const search = { ...raw, ...issuesSearchFromUrl(raw) };
10
+ expect(search.label).toBeUndefined();
11
+ expect(search.assignee).toBeUndefined();
12
+ expect(search.order).toBeUndefined();
13
+ expect(issuesSearchFromUrl({ label: "bug" }).label).toEqual(["bug"]);
14
+ expect(issuesSearchFromUrl({ label: ["bug", " ui "], order: "created" })).toMatchObject({
15
+ label: ["bug", "ui"],
16
+ order: "created",
17
+ });
18
+ });
19
+});
apps/web/src/components/issue/issuesSearch.logic.ts
new
+43
@@ -0,0 +1,43 @@
1
+import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
2
+
3
+import type { IssuesSearch } from "./IssuesPage";
4
+
5
+// The router reads a bare `key=42` as a number.
6
+const bounded = (value: unknown): string | undefined => {
7
+ const text = typeof value === "number" ? String(value) : value;
8
+ return typeof text === "string" && text.trim() ? text.trim().slice(0, 200) : undefined;
9
+};
10
+/** A search key that is either present as a string or absent, never present as undefined. */
11
+function present<K extends string, V extends string>(
12
+ key: K,
13
+ value: string | undefined,
14
+): { [P in K]?: V } {
15
+ return value === undefined ? {} : ({ [key]: value } as { [P in K]: V });
16
+}
17
+
18
+const labels = (raw: unknown): ReadonlyArray<string> | undefined => {
19
+ const names = (Array.isArray(raw) ? raw : [raw]).flatMap((name) => bounded(name) ?? []);
20
+ return names.length === 0 ? undefined : names.slice(0, 20);
21
+};
22
+
23
+export const issuesSearchFromUrl = (raw: Record<string, unknown>): IssuesSearch => ({
24
+ who:
25
+ raw.who === "assigned" || raw.who === "authored" || raw.who === "mentioned" ? raw.who : "all",
26
+ status: raw.status === "closed" || raw.status === "all" ? raw.status : "open",
27
+ ...present("host", bounded(raw.host)),
28
+ // `q`, `label`, `assignee` and `order` are always own keys: the router lays these over the parent route's
29
+ // unvalidated search, where a key left out would keep its raw value.
30
+ q: bounded(raw.q),
31
+ label: labels(raw.label),
32
+ assignee: bounded(raw.assignee),
33
+ order: raw.order === "created" ? "created" : undefined,
34
+ ...present<"selectedEnvironmentId", EnvironmentId>(
35
+ "selectedEnvironmentId",
36
+ bounded(raw.selectedEnvironmentId),
37
+ ),
38
+ ...present<"selectedProjectId", ProjectId>("selectedProjectId", bounded(raw.selectedProjectId)),
39
+ ...present("selectedHost", bounded(raw.selectedHost)),
40
+ ...present("tracker", bounded(raw.tracker)),
41
+ ...present("scope", bounded(raw.scope)),
42
+ ...present("key", bounded(raw.key)),
43
+});
apps/web/src/components/pullRequest/PullRequestListFilters.tsx
+1
-1
@@ -215,7 +215,7 @@ function PullRequestFilterRadioGroup<Value extends string>({
215
);
216
}
217
218
-function PullRequestFilterRadioSubmenu<Value extends string>({
218
+export function PullRequestFilterRadioSubmenu<Value extends string>({
219
label,
220
value,
221
options,
apps/web/src/components/settings/IssueTrackerSettings.tsx
+15
@@ -55,6 +55,21 @@ export function IssueTrackerSettings({ environmentId }: { readonly environmentId
55
</SettingsSection>
56
);
57
}
58
+ if (query.data === null && query.error !== null) {
59
+ return (
60
+ <SettingsSection id={searchableSetting("issue-trackers").id} title="Issue trackers">
61
+ <SettingsRow
62
+ title="Could not load issue trackers"
63
+ description={query.error}
64
+ control={
65
+ <Button size="xs" variant="outline" onClick={query.refresh}>
66
+ Retry
67
+ </Button>
68
+ }
69
+ />
70
+ </SettingsSection>
71
+ );
72
+ }
73
if (trackers.length === 0) return null;
74
return (
75
<SettingsSection id={searchableSetting("issue-trackers").id} title="Issue trackers">
apps/web/src/routes/_chat.issues.tsx
+3
-32
@@ -1,38 +1,9 @@
1
-import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
1
import { createFileRoute } from "@tanstack/react-router";
2
4
-import { IssuesPage, type IssuesSearch } from "../components/issue/IssuesPage";
5
-
6
-// The router reads a bare `key=42` as a number.
7
-const bounded = (value: unknown): string | undefined => {
8
- const text = typeof value === "number" ? String(value) : value;
9
- return typeof text === "string" && text.trim() ? text.trim().slice(0, 200) : undefined;
10
-};
11
-/** A search key that is either present as a string or absent, never present as undefined. */
12
-function present<K extends string, V extends string>(
13
- key: K,
14
- value: string | undefined,
15
-): { [P in K]?: V } {
16
- return value === undefined ? {} : ({ [key]: value } as { [P in K]: V });
17
-}
3
+import { IssuesPage } from "../components/issue/IssuesPage";
4
+import { issuesSearchFromUrl } from "../components/issue/issuesSearch.logic";
5
6
export const Route = createFileRoute("/_chat/issues")({
20
- validateSearch: (raw: Record<string, unknown>): IssuesSearch => ({
21
- who:
22
- raw.who === "assigned" || raw.who === "authored" || raw.who === "mentioned" ? raw.who : "all",
23
- status: raw.status === "closed" || raw.status === "all" ? raw.status : "open",
24
- ...present("host", bounded(raw.host)),
25
- // Always an own key: the router lays this over the parent route's unvalidated search.
26
- q: bounded(raw.q),
27
- ...present<"selectedEnvironmentId", EnvironmentId>(
28
- "selectedEnvironmentId",
29
- bounded(raw.selectedEnvironmentId),
30
- ),
31
- ...present<"selectedProjectId", ProjectId>("selectedProjectId", bounded(raw.selectedProjectId)),
32
- ...present("selectedHost", bounded(raw.selectedHost)),
33
- ...present("tracker", bounded(raw.tracker)),
34
- ...present("scope", bounded(raw.scope)),
35
- ...present("key", bounded(raw.key)),
36
- }),
7
+ validateSearch: issuesSearchFromUrl,
8
component: IssuesPage,
9
});
apps/web/src/state/issues.ts
+18
@@ -1,10 +1,13 @@
1
import {
2
createIssueEnvironmentAtoms,
3
+ createMergedIssueCandidatesAtoms,
4
createMergedIssueListAtoms,
5
+ type IssueCandidatesTarget,
6
type IssueListTarget,
7
type MergedIssueList,
8
} from "@t3tools/client-runtime/state/issues";
9
import { useAtomValue } from "@effect/atom-react";
10
+import type { EnvironmentId } from "@t3tools/contracts";
11
12
import { connectionAtomRuntime } from "../connection/runtime";
13
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -26,3 +29,18 @@ export function useIssueList(
29
const view = useAtomValue(mergedIssueLists.atom(targets));
30
return { ...view, refresh: () => mergedIssueLists.refresh(appAtomRegistry, targets) };
31
}
32
+
33
+/** After a write made beside the list, such as a state change in the detail panel. */
34
+export function refreshIssueLists(environmentId: EnvironmentId) {
35
+ mergedIssueLists.refreshEnvironment(appAtomRegistry, environmentId);
36
+}
37
+
38
+const mergedIssueCandidates = createMergedIssueCandidatesAtoms(
39
+ issueEnvironment.candidates,
40
+ formatEnvironmentQueryError,
41
+);
42
+
43
+/** The labels and people of every scope a list filter covers; no targets reads nothing. */
44
+export function useIssueFilterCandidates(targets: ReadonlyArray<IssueCandidatesTarget>) {
45
+ return useAtomValue(mergedIssueCandidates(targets));
46
+}
packages/client-runtime/src/issueLinks.test.ts
+23
@@ -35,6 +35,29 @@ describe("resolveIssueLinkTarget", () => {
35
expect(target?.ref).toMatchObject({ tracker: "github", host: "github.com", ...expected });
36
});
37
38
+ it("prefers the project bound to the link's own port over one on the bare hostname", () => {
39
+ const enterprise = (id: string, host: string) =>
40
+ ({
41
+ id: ProjectId.make(id),
42
+ environmentId: EnvironmentId.make("env"),
43
+ repositoryIdentity: {
44
+ canonicalKey: `${host}/acme/web`,
45
+ provider: SourceControlProviderKind.make("github"),
46
+ displayName: "acme/web",
47
+ owner: "acme",
48
+ name: "web",
49
+ },
50
+ }) as never;
51
+ const target = resolveIssueLinkTarget({
52
+ url: "https://github.example.com:8443/acme/web/issues/7",
53
+ projects: [
54
+ enterprise("bare", "github.example.com"),
55
+ enterprise("ported", "github.example.com:8443"),
56
+ ],
57
+ });
58
+ expect(target?.ref.projectId).toBe("ported");
59
+ });
60
+
61
it.each([
62
"https://github.com.evil.example/acme/web/issues/7",
63
"https://github.com/acme/web/pull/7",
packages/client-runtime/src/issueLinks.ts
+16
-2
@@ -22,6 +22,14 @@ function projectIssueBinding(project: LinkProject): {
22
};
23
}
24
25
+function linkAuthority(url: string): string | null {
26
+ try {
27
+ return new URL(url).host.toLowerCase();
28
+ } catch {
29
+ return null;
30
+ }
31
+}
32
+
33
/**
34
* The reference an issue link resolves to, and the project it is read through: the project whose
35
* tracker binding is that host and scope, else any project on the same tracker and host lending
@@ -37,12 +45,18 @@ export function resolveIssueLinkTarget<Project extends LinkProject>(input: {
45
const parsed = sourceControlClients.parseIssueUrl(input.url);
46
if (parsed === null) return null;
47
const { definition, link } = parsed;
40
- const bound = input.projects.flatMap((project) => {
48
+ // A link names its server's port; a binding does only when its remote or web URL did.
49
+ const authority = linkAuthority(input.url);
50
+ const onHost = input.projects.flatMap((project) => {
51
const binding = projectIssueBinding(project);
42
- return binding === null || binding.tracker !== definition.kind || binding.host !== link.host
52
+ return binding === null ||
53
+ binding.tracker !== definition.kind ||
54
+ (binding.host !== link.host && binding.host !== authority)
55
? []
56
: [{ project, binding }];
57
});
58
+ const onAuthority = onHost.filter((candidate) => candidate.binding.host === authority);
59
+ const bound = onAuthority.length > 0 ? onAuthority : onHost;
60
const preferFirst = (candidates: typeof bound) =>
61
candidates.find((candidate) => candidate.project.id === input.preferredProjectId) ??
62
candidates[0];
packages/client-runtime/src/issueList.test.ts
new
+142
@@ -0,0 +1,142 @@
1
+import type {
2
+ EnvironmentId,
3
+ IssueListEntry,
4
+ IssueListResult,
5
+ IssueTrackerKind,
6
+ IssueTrackerSummary,
7
+ ProjectId,
8
+} from "@t3tools/contracts";
9
+import { describe, expect, it } from "vite-plus/test";
10
+
11
+import {
12
+ continueIssuePage,
13
+ holdIssuePages,
14
+ issueCursorsForHost,
15
+ issueFilterScopes,
16
+} from "./issueList.ts";
17
+
18
+const environmentId = "env-1" as EnvironmentId;
19
+const api = "api" as ProjectId;
20
+
21
+function entry(overrides: Partial<IssueListEntry> & { key: string }): IssueListEntry {
22
+ return {
23
+ tracker: "github" as IssueTrackerKind,
24
+ host: "github.com",
25
+ scope: "acme/api",
26
+ displayKey: `#${overrides.key}`,
27
+ title: `Issue ${overrides.key}`,
28
+ url: `https://github.com/acme/api/issues/${overrides.key}`,
29
+ author: null,
30
+ state: { category: "open", name: "open" },
31
+ createdAt: "2026-10-01T00:00:00.000Z",
32
+ updatedAt: "2026-10-01T00:00:00.000Z",
33
+ closedAt: null,
34
+ assignees: [],
35
+ labels: [],
36
+ commentCount: 0,
37
+ projectId: api,
38
+ projectTitle: "api",
39
+ ...overrides,
40
+ };
41
+}
42
+
43
+function answer(overrides: Partial<IssueListResult>): IssueListResult {
44
+ return { viewers: {}, trackers: [], entries: [], errors: [], nextCursors: {}, ...overrides };
45
+}
46
+
47
+function hold(first: IssueListResult) {
48
+ return holdIssuePages([[environmentId, first]], new Map()).get(environmentId)!;
49
+}
50
+
51
+describe("continueIssuePage", () => {
52
+ const failure = { projectId: api, projectTitle: "api", message: "rate limited" };
53
+ const firstPageFailure = { projectId: "web" as ProjectId, projectTitle: "web", message: "boom" };
54
+ const cursors = { "github.com acme/api": "c1", "linear.app ENG": "l1" };
55
+
56
+ it("drops a continuation's error once a retry of the same cursors works", () => {
57
+ const first = hold(answer({ errors: [firstPageFailure], nextCursors: cursors }));
58
+ const failed = continueIssuePage(
59
+ first,
60
+ answer({ errors: [failure], nextCursors: cursors }),
61
+ cursors,
62
+ );
63
+ expect(failed.errors.map((error) => error.message)).toEqual(["boom", "rate limited"]);
64
+ const retried = continueIssuePage(failed, answer({ entries: [entry({ key: "2" })] }), cursors);
65
+ // The first page's failure has no cursor, so no continuation retried it.
66
+ expect(retried.errors.map((error) => error.message)).toEqual(["boom"]);
67
+ });
68
+
69
+ it("moves only the cursors asked for and keeps the other trackers' errors", () => {
70
+ const first = hold(answer({ nextCursors: cursors }));
71
+ const linear = issueCursorsForHost(cursors, "linear.app");
72
+ expect(linear).toEqual({ "linear.app ENG": "l1" });
73
+ const linearFailed = continueIssuePage(
74
+ first,
75
+ answer({ errors: [failure], nextCursors: linear }),
76
+ linear,
77
+ );
78
+ const github = issueCursorsForHost(linearFailed.nextCursors, "github.com");
79
+ const next = continueIssuePage(
80
+ linearFailed,
81
+ answer({ entries: [entry({ key: "2" })], nextCursors: { "github.com acme/api": "c2" } }),
82
+ github,
83
+ );
84
+ expect(next.nextCursors).toEqual({ "github.com acme/api": "c2", "linear.app ENG": "l1" });
85
+ expect(next.errors).toEqual([failure]);
86
+ const done = continueIssuePage(
87
+ next,
88
+ answer({}),
89
+ issueCursorsForHost(next.nextCursors, "github.com"),
90
+ );
91
+ expect(done.nextCursors).toEqual({ "linear.app ENG": "l1" });
92
+ });
93
+});
94
+
95
+describe("issueFilterScopes", () => {
96
+ const tracker = (overrides: Partial<IssueTrackerSummary>): IssueTrackerSummary =>
97
+ ({
98
+ tracker: "linear",
99
+ host: "linear.app",
100
+ projectCount: 1,
101
+ capabilities: { labels: true, assignees: true },
102
+ configured: true,
103
+ detail: null,
104
+ ...overrides,
105
+ }) as IssueTrackerSummary;
106
+ const linearRow = entry({
107
+ key: "ENG-1",
108
+ tracker: "linear" as IssueTrackerKind,
109
+ host: "linear.app",
110
+ scope: "ENG",
111
+ });
112
+
113
+ it("offers a bound standalone tracker's scope, named by the rows it listed", () => {
114
+ const held = new Map([
115
+ [
116
+ environmentId,
117
+ hold(
118
+ answer({
119
+ trackers: [tracker({})],
120
+ entries: [linearRow, { ...linearRow, key: "ENG-2" }],
121
+ }),
122
+ ),
123
+ ],
124
+ ]);
125
+ expect(issueFilterScopes(held, [])).toEqual([
126
+ {
127
+ environmentId,
128
+ input: { projectId: api, tracker: "linear", host: "linear.app", scope: "ENG" },
129
+ },
130
+ ]);
131
+ });
132
+
133
+ it("skips a tracker that cannot be read", () => {
134
+ const held = new Map([
135
+ [
136
+ environmentId,
137
+ hold(answer({ trackers: [tracker({ configured: false })], entries: [linearRow] })),
138
+ ],
139
+ ]);
140
+ expect(issueFilterScopes(held, [])).toEqual([]);
141
+ });
142
+});
packages/client-runtime/src/issueList.ts
+75
-3
@@ -4,6 +4,8 @@ import type {
4
IssueListEntry,
5
IssueListProjectError,
6
IssueListResult,
7
+ IssueListSort,
8
+ IssueScopeRef,
9
IssueTrackerSummary,
10
SourceControlProviderKind,
11
} from "@t3tools/contracts";
@@ -60,6 +62,11 @@ export function holdIssuePages(
62
return next;
63
}
64
65
+/** The cursors of one tracker host, so its "Load more" leaves the other trackers where they are. */
66
+export function issueCursorsForHost(cursors: IssueListCursors, host: string): IssueListCursors {
67
+ return Object.fromEntries(Object.entries(cursors).filter(([key]) => key.startsWith(`${host} `)));
68
+}
69
+
70
/**
71
* Lays the next page over the rows held; a failure keeps them and says why. `asked` is the
72
* cursors the page was asked to carry on: only those move, and what an earlier continuation
@@ -86,10 +93,18 @@ export function continueIssuePage(
93
};
94
}
95
96
+/** Newest first by the date the trackers were asked to sort on, so merged rows keep that order. */
97
+export function issueOrder(sort: IssueListSort) {
98
+ const date = (issue: IssueListEntry) =>
99
+ Date.parse(sort === "created" ? issue.createdAt : issue.updatedAt);
100
+ return (left: IssueListEntry, right: IssueListEntry) => date(right) - date(left);
101
+}
102
+
103
export function groupIssues(
104
held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
105
query: string,
106
projects: ReadonlyArray<EnvironmentProject>,
107
+ sort: IssueListSort = "updated",
108
) {
109
const byTracker = new Map<
110
string,
@@ -138,10 +153,67 @@ export function groupIssues(
153
group?.errors.push({ ...error, environmentId });
154
}
155
}
141
- for (const group of byTracker.values()) {
142
- group.rows.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
143
- }
156
+ for (const group of byTracker.values()) group.rows.sort(issueOrder(sort));
157
return [...byTracker.values()].sort((a, b) =>
158
issueTrackerKey(a.tracker).localeCompare(issueTrackerKey(b.tracker)),
159
);
160
}
161
+
162
+/** The scopes whose labels and people a list filter offers, each reached through one project. */
163
+export function issueFilterScopes(
164
+ held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
165
+ projects: ReadonlyArray<EnvironmentProject>,
166
+) {
167
+ const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> =
168
+ [];
169
+ for (const [environmentId, page] of held) {
170
+ for (const project of projects) {
171
+ if (project.environmentId !== environmentId) continue;
172
+ const identity = project.repositoryIdentity;
173
+ const kind = identity?.provider as SourceControlProviderKind | undefined;
174
+ const scope = sourceControlClients.issueScope(identity);
175
+ if (!identity || !kind || scope === null) continue;
176
+ const host = sourceControlClients.changeRequestHost(identity, kind);
177
+ const tracker = page.answer.trackers.find(
178
+ (t) => String(t.tracker) === kind && t.host.toLowerCase() === host.toLowerCase(),
179
+ );
180
+ if (!tracker?.configured || tracker.capabilities === null) continue;
181
+ if (
182
+ scopes.some(
183
+ (s) => s.input.scope.toLowerCase() === scope.toLowerCase() && s.input.host === host,
184
+ )
185
+ )
186
+ continue;
187
+ scopes.push({
188
+ environmentId,
189
+ input: { projectId: project.id, tracker: tracker.tracker, host, scope },
190
+ });
191
+ }
192
+ // A tracker bound in settings (a Linear team) is no repository's; its rows name its scope.
193
+ for (const entry of page.entries) {
194
+ const tracker = page.answer.trackers.find(
195
+ (t) => t.tracker === entry.tracker && t.host.toLowerCase() === entry.host.toLowerCase(),
196
+ );
197
+ if (!tracker?.configured) continue;
198
+ if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue;
199
+ if (
200
+ scopes.some(
201
+ (s) =>
202
+ s.input.scope.toLowerCase() === entry.scope.toLowerCase() &&
203
+ s.input.host?.toLowerCase() === entry.host.toLowerCase(),
204
+ )
205
+ )
206
+ continue;
207
+ scopes.push({
208
+ environmentId,
209
+ input: {
210
+ projectId: entry.projectId,
211
+ tracker: entry.tracker,
212
+ host: entry.host,
213
+ scope: entry.scope,
214
+ },
215
+ });
216
+ }
217
+ }
218
+ return scopes;
219
+}
packages/client-runtime/src/issuePresentation.test.ts
new
+21
@@ -0,0 +1,21 @@
1
+import type { IssueDetail } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { issueWriteAccess } from "./issuePresentation.ts";
5
+
6
+describe("issueWriteAccess", () => {
7
+ it("does not offer the category an issue is already in under a workflow name", () => {
8
+ const detail = {
9
+ writable: true,
10
+ state: { category: "open", name: "Todo" },
11
+ capabilities: {
12
+ states: [
13
+ { category: "open", name: "open" },
14
+ { category: "closed", name: "closed" },
15
+ ],
16
+ },
17
+ viewerPermissions: { setState: true },
18
+ } as unknown as IssueDetail;
19
+ expect(issueWriteAccess(detail, true).states).toEqual([{ category: "closed", name: "closed" }]);
20
+ });
21
+});
packages/client-runtime/src/issuePresentation.ts
+5
-1
@@ -51,8 +51,12 @@ export function issueWriteAccess(detail: IssueDetail, canWrite: boolean) {
51
: null;
52
const may = (capability: boolean, permission: boolean) =>
53
blocked === null && capability && permission;
54
+ // A tracker with a workflow of its own offers the two categories by name ("open", "closed")
55
+ // while its issues carry workflow names ("Todo"), so the category alone says it is already there.
56
const others = detail.capabilities.states.filter(
55
- (state) => state.category !== detail.state.category || state.name !== detail.state.name,
57
+ (state) =>
58
+ state.category !== detail.state.category ||
59
+ (state.name !== detail.state.name && state.name !== state.category),
60
);
61
return {
62
blocked,
packages/client-runtime/src/issueSelection.test.ts
+20
@@ -3,6 +3,7 @@ import { describe, expect, it } from "@effect/vitest";
3
import {
4
issueAssigneesAfterPicks,
5
issueLabelsAfterPicks,
6
+ issuePicksAfterFailedWrite,
7
issuePicksFor,
8
issueWriteAfterPicks,
9
noIssuePicks,
@@ -72,4 +73,23 @@ describe("issue picker picks", () => {
73
"p1",
74
]);
75
});
76
+
77
+ it("keeps picks made after a write that then fails, and forgets the failed ones otherwise", () => {
78
+ const detail = { labels: [label("bug")] };
79
+ const picked = issuePicksFor(noIssuePicks<ReturnType<typeof label>>(), detail, true);
80
+ const sent = {
81
+ ...picked,
82
+ draft: toggleSelection(picked.draft, "docs", label("docs"), false),
83
+ written: ["bug", "docs"],
84
+ };
85
+ expect(issuePicksAfterFailedWrite(sent, sent).draft.size).toBe(0);
86
+
87
+ const later = { ...sent, draft: toggleSelection(sent.draft, "ui", label("ui"), false) };
88
+ const kept = issuePicksAfterFailedWrite(later, sent);
89
+ expect(kept.written).toBeNull();
90
+ expect(issueLabelsAfterPicks(detail, kept.draft)).toEqual(["bug", "docs", "ui"]);
91
+
92
+ const rewritten = { ...later, written: ["bug", "docs", "ui"] };
93
+ expect(issuePicksAfterFailedWrite(rewritten, sent)).toBe(rewritten);
94
+ });
95
});
packages/client-runtime/src/issueSelection.ts
+12
@@ -67,6 +67,18 @@ export function issuePicksFor<T>(
67
return { basis: detail, draft: open ? picks.draft : new Map(), written: null };
68
}
69
70
+/**
71
+ * A write that failed is forgotten along with the picks it carried, unless the picker was picked
72
+ * in again since: those picks stay, and the next close writes them with the ones that failed.
73
+ */
74
+export function issuePicksAfterFailedWrite<T>(
75
+ latest: IssuePicks<T>,
76
+ sent: IssuePicks<T>,
77
+): IssuePicks<T> {
78
+ if (latest.written !== sent.written) return latest;
79
+ return latest.draft === sent.draft ? noIssuePicks() : { ...latest, written: null };
80
+}
81
+
82
/** The set a closing picker writes: null when the tracker has it or was already sent it. */
83
export function issueWriteAfterPicks(
84
after: ReadonlyArray<string> | null,
packages/client-runtime/src/state/issues.ts
+66
@@ -1,11 +1,15 @@
1
import {
2
WS_METHODS,
3
type EnvironmentId,
4
+ type IssueAssigneeCandidate,
5
+ type IssueCandidates,
6
type IssueComment,
7
+ type IssueLabelCandidate,
8
type IssueListEntry,
9
type IssueListInput,
10
type IssueListResult,
11
type IssueRef,
12
+ type IssueScopeRef,
13
} from "@t3tools/contracts";
14
import type * as Cause from "effect/Cause";
15
import * as Effect from "effect/Effect";
@@ -233,3 +237,65 @@ export function createMergedIssueListAtoms<E>(
237
},
238
};
239
}
240
+
241
+export interface IssueCandidatesTarget {
242
+ readonly environmentId: EnvironmentId;
243
+ readonly input: IssueScopeRef;
244
+}
245
+
246
+/** What a list filter can offer: the labels and people of every scope asked, each named once. */
247
+export interface MergedIssueCandidates {
248
+ readonly labels: ReadonlyArray<IssueLabelCandidate>;
249
+ readonly assignees: ReadonlyArray<IssueAssigneeCandidate>;
250
+ readonly error: string | null;
251
+ readonly isPending: boolean;
252
+ readonly truncated: boolean;
253
+}
254
+
255
+const NO_ISSUE_CANDIDATES: MergedIssueCandidates = {
256
+ labels: [],
257
+ assignees: [],
258
+ error: null,
259
+ isPending: false,
260
+ truncated: false,
261
+};
262
+
263
+/** Fans out like the merged listing: a scope that fails leaves the others' answers in place. */
264
+export function createMergedIssueCandidatesAtoms<E>(
265
+ candidates: (
266
+ target: IssueCandidatesTarget,
267
+ ) => Atom.Atom<AsyncResult.AsyncResult<IssueCandidates, E>>,
268
+ formatError: (cause: Cause.Cause<E>) => string,
269
+) {
270
+ const empty = Atom.make(NO_ISSUE_CANDIDATES).pipe(Atom.withLabel("issues:candidates:empty"));
271
+ const family = Atom.family((key: string) =>
272
+ Atom.make((get): MergedIssueCandidates => {
273
+ const labels = new Map<string, IssueLabelCandidate>();
274
+ const assignees = new Map<string, IssueAssigneeCandidate>();
275
+ let error: string | null = null;
276
+ let isPending = false;
277
+ let truncated = false;
278
+ for (const target of JSON.parse(key) as ReadonlyArray<IssueCandidatesTarget>) {
279
+ const result = get(candidates(target));
280
+ isPending ||= result.waiting;
281
+ if (result._tag === "Failure" && error === null) error = formatError(result.cause);
282
+ const value = Option.getOrNull(AsyncResult.value(result));
283
+ if (value === null) continue;
284
+ truncated ||= value.truncated;
285
+ for (const label of value.labels)
286
+ if (!labels.has(label.name)) labels.set(label.name, label);
287
+ for (const actor of value.assignees)
288
+ if (!assignees.has(actor.login)) assignees.set(actor.login, actor);
289
+ }
290
+ return {
291
+ labels: [...labels.values()].sort((a, b) => a.name.localeCompare(b.name)),
292
+ assignees: [...assignees.values()].sort((a, b) => a.login.localeCompare(b.login)),
293
+ error,
294
+ isPending,
295
+ truncated,
296
+ };
297
+ }).pipe(Atom.withLabel(`issues:candidates:${key}`)),
298
+ );
299
+ return (targets: ReadonlyArray<IssueCandidatesTarget>) =>
300
+ targets.length === 0 ? empty : family(JSON.stringify(targets));
301
+}
packages/contracts/src/issue.ts
+14
@@ -59,6 +59,10 @@ export type IssueListState = typeof IssueListState.Type;
59
export const IssueInvolvement = Schema.Literals(["all", "assigned", "authored", "mentioned"]);
60
export type IssueInvolvement = typeof IssueInvolvement.Type;
61
62
+/** Newest first by the named date. */
63
+export const IssueListSort = Schema.Literals(["updated", "created"]);
64
+export type IssueListSort = typeof IssueListSort.Type;
65
+
66
export const IssueReactionContent = PullRequestReactionContent;
67
export type IssueReactionContent = typeof IssueReactionContent.Type;
68
@@ -266,6 +270,16 @@ export const IssueListInput = Schema.Struct({
270
cursors: Schema.optional(IssueListCursors),
271
/** Free text the trackers themselves are asked to match. */
272
query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(200))),
273
+ /** Label names an issue must carry, every one of them. */
274
+ labels: Schema.optional(
275
+ Schema.Array(TrimmedNonEmptyString.check(Schema.isMaxLength(200))).check(
276
+ Schema.isMaxLength(20),
277
+ ),
278
+ ),
279
+ /** An assignee's `login`, as an issue of that tracker names them. */
280
+ assignee: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(320))),
281
+ /** Absent means `updated`. */
282
+ sort: Schema.optional(IssueListSort),
283
});
284
export type IssueListInput = typeof IssueListInput.Type;
285
packages/issue-tracker-linear/schema/linear.graphql.ts
+9
@@ -36,6 +36,15 @@ export const TimelessDateOrDuration = Schema.String
36
export const CyclePeriod = Schema.Literals(["after", "before", "during"])
37
export type CyclePeriod = typeof CyclePeriod.Type
38
39
+/**
40
+ * By which field should the pagination order by
41
+ *
42
+ * - `createdAt`
43
+ * - `updatedAt`
44
+ */
45
+export const PaginationOrderBy = Schema.Literals(["createdAt", "updatedAt"])
46
+export type PaginationOrderBy = typeof PaginationOrderBy.Type
47
+
48
/**
49
* The type of a release pipeline, which determines how releases are created and managed. Continuous pipelines create a new completed release for each sync. Scheduled pipelines accumulate issues into a started release that is explicitly completed.
50
*
packages/issue-tracker-linear/src/server/LinearApi.graphql
+20
-2
@@ -6,6 +6,12 @@ fragment LinearUser on User {
6
avatarUrl
7
}
8
9
+fragment LinearBot on ActorBot {
10
+ name
11
+ userDisplayName
12
+ avatarUrl
13
+}
14
+
15
fragment LinearWorkflowState on WorkflowState {
16
id
17
name
@@ -40,6 +46,9 @@ fragment LinearComment on Comment {
46
user {
47
...LinearUser
48
}
49
+ botActor {
50
+ ...LinearBot
51
+ }
52
reactions {
53
...LinearReaction
54
}
@@ -65,6 +74,9 @@ fragment LinearIssue on Issue {
74
creator {
75
...LinearUser
76
}
77
+ botActor {
78
+ ...LinearBot
79
+ }
80
assignee {
81
...LinearUser
82
}
@@ -93,8 +105,8 @@ query T3Viewer {
105
}
106
}
107
96
-query T3Issues($first: Int!, $after: String, $filter: IssueFilter!) {
97
- issues(first: $first, after: $after, filter: $filter, orderBy: updatedAt) {
108
+query T3Issues($first: Int!, $after: String, $filter: IssueFilter!, $orderBy: PaginationOrderBy!) {
109
+ issues(first: $first, after: $after, filter: $filter, orderBy: $orderBy) {
110
nodes {
111
...LinearIssue
112
}
@@ -133,6 +145,9 @@ query T3Issue($id: String!, $comments: Int!) {
145
actor {
146
...LinearUser
147
}
148
+ botActor {
149
+ ...LinearBot
150
+ }
151
fromState {
152
...LinearWorkflowState
153
}
@@ -268,6 +283,9 @@ query T3IssueReactions($id: String!) {
283
284
query T3CommentReactions($id: String!) {
285
comment(id: $id) {
286
+ issue {
287
+ id
288
+ }
289
reactions {
290
...LinearReaction
291
}
packages/issue-tracker-linear/src/server/LinearApi.graphql.ts
+44
-9
@@ -22,6 +22,21 @@ export const LinearUser = Schema.Struct({
22
})
23
export interface LinearUser extends Schema.Struct.Type<typeof LinearUser.fields> {}
24
25
+/**
26
+ * `fragment LinearBot on ActorBot`
27
+ *
28
+ * A bot actor representing a non-human entity that performed an action, such as an integration (GitHub, Slack, Zendesk), an AI assistant, or an automated workflow. Bot actors are displayed in activity feeds and history to indicate when changes were made by applications rather than users.
29
+ */
30
+export const LinearBot = Schema.Struct({
31
+ /** The display name of the bot. */
32
+ name: Schema.NullOr(Schema.String),
33
+ /** The display name of the external user on behalf of whom the bot acted. Shown when an integration action was triggered by a specific person in the external system. */
34
+ userDisplayName: Schema.NullOr(Schema.String),
35
+ /** A URL pointing to the avatar image representing this bot, typically the integration's logo or icon. */
36
+ avatarUrl: Schema.NullOr(Schema.String)
37
+})
38
+export interface LinearBot extends Schema.Struct.Type<typeof LinearBot.fields> {}
39
+
40
/**
41
* `fragment LinearWorkflowState on WorkflowState`
42
*
@@ -97,6 +112,8 @@ export const LinearComment = Schema.Struct({
112
url: Schema.String,
113
/** The user who wrote the comment. Null for comments created by integrations or bots without a user association. */
114
user: Schema.NullOr(LinearUser),
115
+ /** The bot that created the comment. */
116
+ botActor: Schema.NullOr(LinearBot),
117
/** Reactions associated with the comment. */
118
reactions: Schema.Array(LinearReaction)
119
})
@@ -149,6 +166,8 @@ export const LinearIssue = Schema.Struct({
166
team: TeamTeam,
167
/** The user who created the issue. Null if the creator's account has been deleted or if the issue was created by an integration or system process. */
168
creator: Schema.NullOr(LinearUser),
169
+ /** The bot that created the issue, if applicable. */
170
+ botActor: Schema.NullOr(LinearBot),
171
/** The user to whom the issue is assigned. Null if the issue is unassigned. */
172
assignee: Schema.NullOr(LinearUser),
173
/** Labels associated with this issue. */
@@ -217,23 +236,26 @@ export const T3Issues = GraphQL.query("T3Issues", {
236
variables: [
237
{ name: "first", body: "Int!" },
238
{ name: "after", body: "String" },
220
- { name: "filter", body: "IssueFilter!" }
239
+ { name: "filter", body: "IssueFilter!" },
240
+ { name: "orderBy", body: "PaginationOrderBy!" }
241
],
242
selections: [
223
- { name: "issues", body: ["(first:$", "first", " after:$", "after", " filter:$", "filter", " orderBy:updatedAt){nodes{...LinearIssue}pageInfo{...LinearPageInfo}}"] }
243
+ { name: "issues", body: ["(first:$", "first", " after:$", "after", " filter:$", "filter", " orderBy:$", "orderBy", "){nodes{...LinearIssue}pageInfo{...LinearPageInfo}}"] }
244
],
245
fragments: [
226
- { name: "LinearIssue", body: ["on Issue{id identifier number title url description createdAt updatedAt completedAt canceledAt state{...LinearWorkflowState}team{key}creator{...LinearUser}assignee{...LinearUser}labels{nodes{...LinearLabel}}}"] },
246
+ { name: "LinearIssue", body: ["on Issue{id identifier number title url description createdAt updatedAt completedAt canceledAt state{...LinearWorkflowState}team{key}creator{...LinearUser}botActor{...LinearBot}assignee{...LinearUser}labels{nodes{...LinearLabel}}}"] },
247
{ name: "LinearPageInfo", body: ["on PageInfo{hasNextPage endCursor}"] },
248
{ name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] },
249
{ name: "LinearUser", body: ["on User{id name displayName email avatarUrl}"] },
250
+ { name: "LinearBot", body: ["on ActorBot{name userDisplayName avatarUrl}"] },
251
{ name: "LinearLabel", body: ["on IssueLabel{id name color}"] }
252
]
253
},
254
variables: {
255
first: Shared.Int,
256
after: Schema.optional(Schema.NullOr(Schema.String)),
236
- filter: Shared.IssueFilter
257
+ filter: Shared.IssueFilter,
258
+ orderBy: Shared.PaginationOrderBy
259
},
260
result: Schema.Struct({
261
/** All issues. Returns a paginated list of issues visible to the authenticated user. Can be filtered by various criteria including team, assignee, state, labels, project, and cycle. */
@@ -277,6 +299,8 @@ export const IssueHistory = Schema.Struct({
299
createdAt: Shared.DateTime,
300
/** The actor that performed the actions. This field may be empty in the case of integrations or automations. */
301
actor: Schema.NullOr(LinearUser),
302
+ /** The bot that performed the action. */
303
+ botActor: Schema.NullOr(LinearBot),
304
/** The state that the issue was moved from. */
305
fromState: Schema.NullOr(LinearWorkflowState),
306
/** The state that the issue was moved to. */
@@ -323,14 +347,15 @@ export const T3Issue = GraphQL.query("T3Issue", {
347
{ name: "comments", body: "Int!" }
348
],
349
selections: [
326
- { name: "issue", body: ["(id:$", "id", "){...LinearIssue comments(first:$", "comments", " orderBy:createdAt){nodes{...LinearComment}pageInfo{...LinearPageInfo}}reactions{...LinearReaction}attachments(first:50){nodes{url title sourceType metadata}}history(first:100 orderBy:createdAt){nodes{id createdAt actor{...LinearUser}fromState{...LinearWorkflowState}toState{...LinearWorkflowState}fromAssignee{...LinearUser}toAssignee{...LinearUser}addedLabels{...LinearLabel}removedLabels{...LinearLabel}fromTitle toTitle}}}"] }
350
+ { name: "issue", body: ["(id:$", "id", "){...LinearIssue comments(first:$", "comments", " orderBy:createdAt){nodes{...LinearComment}pageInfo{...LinearPageInfo}}reactions{...LinearReaction}attachments(first:50){nodes{url title sourceType metadata}}history(first:100 orderBy:createdAt){nodes{id createdAt actor{...LinearUser}botActor{...LinearBot}fromState{...LinearWorkflowState}toState{...LinearWorkflowState}fromAssignee{...LinearUser}toAssignee{...LinearUser}addedLabels{...LinearLabel}removedLabels{...LinearLabel}fromTitle toTitle}}}"] }
351
],
352
fragments: [
329
- { name: "LinearIssue", body: ["on Issue{id identifier number title url description createdAt updatedAt completedAt canceledAt state{...LinearWorkflowState}team{key}creator{...LinearUser}assignee{...LinearUser}labels{nodes{...LinearLabel}}}"] },
330
- { name: "LinearComment", body: ["on Comment{id body createdAt url user{...LinearUser}reactions{...LinearReaction}}"] },
353
+ { name: "LinearIssue", body: ["on Issue{id identifier number title url description createdAt updatedAt completedAt canceledAt state{...LinearWorkflowState}team{key}creator{...LinearUser}botActor{...LinearBot}assignee{...LinearUser}labels{nodes{...LinearLabel}}}"] },
354
+ { name: "LinearComment", body: ["on Comment{id body createdAt url user{...LinearUser}botActor{...LinearBot}reactions{...LinearReaction}}"] },
355
{ name: "LinearPageInfo", body: ["on PageInfo{hasNextPage endCursor}"] },
356
{ name: "LinearReaction", body: ["on Reaction{id emoji user{...LinearUser}}"] },
357
{ name: "LinearUser", body: ["on User{id name displayName email avatarUrl}"] },
358
+ { name: "LinearBot", body: ["on ActorBot{name userDisplayName avatarUrl}"] },
359
{ name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] },
360
{ name: "LinearLabel", body: ["on IssueLabel{id name color}"] }
361
]
@@ -368,9 +393,10 @@ export const T3Comments = GraphQL.query("T3Comments", {
393
{ name: "issue", body: ["(id:$", "id", "){comments(first:$", "first", " after:$", "after", " orderBy:createdAt){nodes{...LinearComment}pageInfo{...LinearPageInfo}}}"] }
394
],
395
fragments: [
371
- { name: "LinearComment", body: ["on Comment{id body createdAt url user{...LinearUser}reactions{...LinearReaction}}"] },
396
+ { name: "LinearComment", body: ["on Comment{id body createdAt url user{...LinearUser}botActor{...LinearBot}reactions{...LinearReaction}}"] },
397
{ name: "LinearPageInfo", body: ["on PageInfo{hasNextPage endCursor}"] },
398
{ name: "LinearUser", body: ["on User{id name displayName email avatarUrl}"] },
399
+ { name: "LinearBot", body: ["on ActorBot{name userDisplayName avatarUrl}"] },
400
{ name: "LinearReaction", body: ["on Reaction{id emoji user{...LinearUser}}"] }
401
]
402
},
@@ -690,8 +716,17 @@ export declare namespace T3IssueReactions {
716
export type Result = typeof T3IssueReactions.result.Type
717
}
718
719
+/** An issue is the core work item in Linear. Issues belong to a team, have a workflow status, can be assigned to users, carry a priority level, and can be organized into projects and cycles. Issues support sub-issues (parent-child hierarchy up to 10 levels deep), labels, due dates, estimates, and SLA tracking. They can also be linked to other issues via relations, attached to releases, and tracked through their full history of changes. */
720
+export const CommentIssueIssue = Schema.Struct({
721
+ /** The unique identifier of the entity. */
722
+ id: Shared.ID
723
+})
724
+export interface CommentIssueIssue extends Schema.Struct.Type<typeof CommentIssueIssue.fields> {}
725
+
726
/** A comment associated with an issue, project update, initiative update, document content, post, project, or initiative. Comments support rich text (ProseMirror), emoji reactions, and threaded replies via parentId. Comments can be created by workspace users or by external users through integrations (e.g., Slack, Intercom). Each comment belongs to exactly one parent entity. */
727
export const Comment = Schema.Struct({
728
+ /** The issue that the comment is associated with. Null if the comment belongs to a different parent entity type. */
729
+ issue: Schema.NullOr(CommentIssueIssue),
730
/** Reactions associated with the comment. */
731
reactions: Schema.Array(LinearReaction)
732
})
@@ -704,7 +739,7 @@ export const T3CommentReactions = GraphQL.query("T3CommentReactions", {
739
{ name: "id", body: "String!" }
740
],
741
selections: [
707
- { name: "comment", body: ["(id:$", "id", "){reactions{...LinearReaction}}"] }
742
+ { name: "comment", body: ["(id:$", "id", "){issue{id}reactions{...LinearReaction}}"] }
743
],
744
fragments: [
745
{ name: "LinearReaction", body: ["on Reaction{id emoji user{...LinearUser}}"] },
packages/issue-tracker-linear/src/server/LinearApi.ts
+34
-6
@@ -21,7 +21,6 @@ import * as Headers from "effect/http/Headers";
21
import { IssueTrackerKind } from "@t3tools/contracts";
22
import { IssueTrackerError } from "@t3tools/source-control-core/server/IssueTracker";
23
import * as IssueTrackerHost from "@t3tools/source-control-core/server/IssueTrackerHost";
24
-import { retryAtFromHeader } from "@t3tools/source-control-core/server/SourceControlRateLimit";
24
25
import type {
26
CommentCreateInput,
@@ -110,6 +109,7 @@ export class LinearApi extends Context.Service<
109
readonly filter: IssueFilter;
110
readonly first: number;
111
readonly after?: string | undefined;
112
+ readonly orderBy: "updatedAt" | "createdAt";
113
}) => Effect.Effect<
114
{ readonly nodes: ReadonlyArray<LinearIssue>; readonly nextCursor: string | null },
115
IssueTrackerError
@@ -146,7 +146,14 @@ export class LinearApi extends Context.Service<
146
readonly listReactions: (input: {
147
readonly issueId?: string | undefined;
148
readonly commentId?: string | undefined;
149
- }) => Effect.Effect<ReadonlyArray<LinearReaction>, IssueTrackerError>;
149
+ }) => Effect.Effect<
150
+ {
151
+ /** The issue the reactions hang off: the one asked for, or the comment's own. */
152
+ readonly issueId: string | null;
153
+ readonly reactions: ReadonlyArray<LinearReaction>;
154
+ },
155
+ IssueTrackerError
156
+ >;
157
}
158
>()("@t3tools/issue-tracker-linear/server/LinearApi") {}
159
@@ -179,6 +186,12 @@ const fail = (
186
const hasCode = (errors: ReadonlyArray<GraphQLClientError.GraphQLError>, code: string) =>
187
errors.some((error) => error.extensions?.["code"] === code);
188
189
+/** Linear's reset headers are UTC epoch milliseconds, not the seconds-from-now of `Retry-After`. */
190
+function resetAtFromHeader(value: string | undefined, now: number): number | undefined {
191
+ const resetAt = /^\d+$/u.test(value?.trim() ?? "") ? Number(value) : Number.NaN;
192
+ return Number.isSafeInteger(resetAt) && resetAt > now ? resetAt : undefined;
193
+}
194
+
195
/** Linear's answer as the tracker's error. Linear writes its messages for people. */
196
const toTrackerError = (
197
operation: string,
@@ -192,7 +205,7 @@ const toTrackerError = (
205
const errors = reason._tag === "ResponseError" ? reason.errors : [];
206
const headers = reason.headers ?? Headers.empty;
207
if (reason.status === 429 || hasCode(errors, "RATELIMITED")) {
195
- const retryAt = retryAtFromHeader(
208
+ const retryAt = resetAtFromHeader(
209
headers["x-ratelimit-requests-reset"] ?? headers["x-ratelimit-complexity-reset"],
210
now,
211
);
@@ -287,7 +300,12 @@ export const make = Effect.gen(function* () {
300
301
const listIssues: LinearApi["Service"]["listIssues"] = (input) =>
302
call("listIssues", (linear) =>
290
- linear.T3Issues({ first: input.first, after: input.after ?? null, filter: input.filter }),
303
+ linear.T3Issues({
304
+ first: input.first,
305
+ after: input.after ?? null,
306
+ filter: input.filter,
307
+ orderBy: input.orderBy,
308
+ }),
309
).pipe(
310
Effect.map((data) => ({
311
nodes: data.issues.nodes,
@@ -385,10 +403,20 @@ export const make = Effect.gen(function* () {
403
input.commentId === undefined
404
? call("listReactions", (linear) =>
405
linear.T3IssueReactions({ id: input.issueId ?? "" }),
388
- ).pipe(Effect.map((data) => data.issue.reactions))
406
+ ).pipe(
407
+ Effect.map((data) => ({
408
+ issueId: input.issueId ?? null,
409
+ reactions: data.issue.reactions,
410
+ })),
411
+ )
412
: call("listReactions", (linear) =>
413
linear.T3CommentReactions({ id: input.commentId ?? "" }),
391
- ).pipe(Effect.map((data) => data.comment.reactions));
414
+ ).pipe(
415
+ Effect.map((data) => ({
416
+ issueId: data.comment.issue?.id ?? null,
417
+ reactions: data.comment.reactions,
418
+ })),
419
+ );
420
421
return LinearApi.of({
422
viewer,
packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts
+110
-19
@@ -44,6 +44,7 @@ const issue = (
44
state: state("In Progress", "started"),
45
team: { key: identifier.split("-")[0] },
46
creator: JULIUS,
47
+ botActor: null,
48
assignee: THEO,
49
labels: { nodes: [{ id: "lbl_bug", name: "Bug", color: "#f00" }] },
50
...overrides,
@@ -78,19 +79,22 @@ function fakeLinear(
79
const operation = /^(?:query|mutation) (\w+)/.exec(parsed.query)?.[1] ?? "?";
80
requests.push({ authorization: request.headers.authorization, operation });
81
const answer = answers[operation];
82
+ const answered = answer?.(parsed.variables);
83
const response =
82
- answer === undefined
83
- ? new Response(
84
- JSON.stringify({ errors: [{ message: `No answer for ${operation}` }] }),
85
- {
86
- status: 400,
84
+ answered instanceof Response
85
+ ? answered
86
+ : answer === undefined
87
+ ? new Response(
88
+ JSON.stringify({ errors: [{ message: `No answer for ${operation}` }] }),
89
+ {
90
+ status: 400,
91
+ headers: { "content-type": "application/json" },
92
+ },
93
+ )
94
+ : new Response(JSON.stringify({ data: answered }), {
95
+ status: 200,
96
headers: { "content-type": "application/json" },
88
- },
89
- )
90
- : new Response(JSON.stringify({ data: answer(parsed.variables) }), {
91
- status: 200,
92
- headers: { "content-type": "application/json" },
93
- });
97
+ });
98
return HttpClientResponse.fromWeb(request, response);
99
}),
100
),
@@ -120,8 +124,14 @@ describe("LinearIssueTracker", () => {
124
expect(variables.filter).toMatchObject({
125
team: { key: { eq: "ENG" } },
126
state: { type: { nin: ["completed", "canceled"] } },
123
- assignee: { id: { eq: "usr_julius" } },
127
+ // "Assigned to me" survives an assignee filter: both must hold.
128
+ assignee: { displayName: { eq: "julius" } },
129
+ and: [
130
+ { assignee: { displayName: { eq: "theo" } } },
131
+ { labels: { some: { name: { eq: "Bug" } } } },
132
+ ],
133
});
134
+ expect(variables.orderBy).toBe("createdAt");
135
return {
136
issues: {
137
nodes: [
@@ -144,7 +154,10 @@ describe("LinearIssueTracker", () => {
154
...target,
155
state: "open",
156
involvement: "assigned",
147
- viewer: "usr_julius",
157
+ viewer: "julius",
158
+ labels: ["Bug"],
159
+ assignee: "theo",
160
+ sort: "created",
161
limit: 50,
162
});
163
expect(page.nextCursor).toBe("cur_2");
@@ -152,14 +165,83 @@ describe("LinearIssueTracker", () => {
165
["ENG-2", "ENG-2", { category: "closed", name: "Done", closeReason: "completed" }],
166
["ENG-1", "ENG-1", { category: "open", name: "In Progress" }],
167
]);
168
+ // A listing carries no comment totals, whatever the row's position.
169
+ expect(page.items.map((item) => item.commentCount)).toEqual([0, 0]);
170
expect(page.items[0]).toMatchObject({
171
closedAt: "2026-07-03T00:00:00.000Z",
157
- author: { login: "usr_julius", name: "julius" },
158
- assignees: [{ login: "usr_theo", name: "theo" }],
172
+ author: { login: "julius", name: "julius" },
173
+ assignees: [{ login: "theo", name: "theo" }],
174
labels: [{ name: "Bug", color: "#f00" }],
175
});
176
// The stored key goes in as-is, not as a bearer token.
177
expect(requests.map((request) => request.authorization)).toEqual(["lin_api_stored"]);
178
+
179
+ // Linear's reset header is an absolute time in epoch milliseconds.
180
+ const resetAt = 4_102_444_800_000;
181
+ const limited = fakeLinear({
182
+ T3Issues: () =>
183
+ new Response(JSON.stringify({ errors: [{ message: "Rate limited" }] }), {
184
+ status: 429,
185
+ headers: {
186
+ "content-type": "application/json",
187
+ "x-ratelimit-requests-reset": String(resetAt),
188
+ },
189
+ }),
190
+ });
191
+ const refused = yield* Effect.flip(
192
+ (yield* limited.tracker).listIssues({
193
+ ...target,
194
+ state: "open",
195
+ involvement: "all",
196
+ viewer: "julius",
197
+ sort: "updated",
198
+ limit: 50,
199
+ }),
200
+ );
201
+ expect([refused.reason, refused.retryAt]).toEqual(["rate-limited", resetAt]);
202
+ }),
203
+ );
204
+
205
+ it.effect("reacts to a comment only when it belongs to the issue named", () =>
206
+ Effect.gen(function* () {
207
+ const created: Array<unknown> = [];
208
+ const deleted: Array<unknown> = [];
209
+ const { tracker } = fakeLinear({
210
+ T3Viewer: () => ({ viewer: JULIUS, teams: { nodes: [] } }),
211
+ T3Issue: (variables) => {
212
+ // Linear refuses a page of zero comments, which fails the write that looked the issue up.
213
+ expect(variables.comments).toBeGreaterThan(0);
214
+ return { issue: bareDetail(String(variables.id)) };
215
+ },
216
+ T3CommentReactions: (variables) => ({
217
+ comment: {
218
+ issue: { id: variables.id === "cmt_own" ? "iss_ENG-1" : "iss_OPS-9" },
219
+ reactions: [{ id: "r1", emoji: "+1", user: JULIUS }],
220
+ },
221
+ }),
222
+ T3ReactionCreate: (variables) => {
223
+ created.push(variables.input);
224
+ return { reactionCreate: { success: true } };
225
+ },
226
+ T3ReactionDelete: (variables) => {
227
+ deleted.push(variables.id);
228
+ return { reactionDelete: { success: true } };
229
+ },
230
+ });
231
+ const api = yield* tracker;
232
+ const reaction = { ...target, key: "ENG-1", content: "thumbs-up" as const };
233
+ for (const reacted of [true, false]) {
234
+ const foreign = yield* Effect.flip(
235
+ api.setReaction({ ...reaction, subjectId: "cmt_other", reacted }),
236
+ );
237
+ expect(foreign.detail).toBe("The comment does not belong to the selected issue.");
238
+ }
239
+ expect([created, deleted]).toEqual([[], []]);
240
+
241
+ yield* api.setReaction({ ...reaction, subjectId: "cmt_own", reacted: true });
242
+ yield* api.setReaction({ ...reaction, subjectId: "cmt_own", reacted: false });
243
+ expect(created).toEqual([{ commentId: "cmt_own", emoji: "👍" }]);
244
+ expect(deleted).toEqual(["r1"]);
245
}),
246
);
247
@@ -177,14 +259,15 @@ describe("LinearIssueTracker", () => {
259
createdAt: "2026-07-02T01:00:00.000Z",
260
url: "https://linear.app/acme/issue/ENG-7#comment-cmt_1",
261
user: THEO,
180
- reactions: [{ id: "r1", emoji: "👍", user: JULIUS }],
262
+ botActor: null,
263
+ reactions: [{ id: "r1", emoji: "+1", user: JULIUS }],
264
},
265
],
266
pageInfo: { hasNextPage: true, endCursor: "cmt_cur" },
267
},
268
reactions: [
269
{ id: "r2", emoji: "🚀", user: THEO },
187
- { id: "r3", emoji: "🚀", user: JULIUS },
270
+ { id: "r3", emoji: "rocket", user: JULIUS },
271
{ id: "r4", emoji: "🤷", user: THEO },
272
],
273
attachments: {
@@ -203,7 +286,9 @@ describe("LinearIssueTracker", () => {
286
{
287
id: "h1",
288
createdAt: "2026-07-01T01:00:00.000Z",
206
- actor: THEO,
289
+ // An integration acted: Linear names it beside an empty user.
290
+ actor: null,
291
+ botActor: { name: "GitHub", userDisplayName: null, avatarUrl: null },
292
fromState: state("Todo", "unstarted"),
293
toState: state("Done", "completed"),
294
fromAssignee: null,
@@ -220,7 +305,7 @@ describe("LinearIssueTracker", () => {
305
});
306
const api = yield* tracker;
307
const detail = yield* api.getIssue({ ...target, key: "eng-7" });
223
- expect(detail.viewer).toBe("usr_julius");
308
+ expect(detail.viewer).toBe("julius");
309
expect(detail.commentsCursor).toBe("cmt_cur");
310
expect(detail.comments[0]?.reactions).toEqual([
311
{ content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true },
@@ -234,6 +319,12 @@ describe("LinearIssueTracker", () => {
319
["labeled", "Bug"],
320
["assigned", "julius"],
321
]);
322
+ expect(detail.events[0]?.actor).toEqual({
323
+ isBot: true,
324
+ login: "GitHub",
325
+ name: "GitHub",
326
+ avatarUrl: null,
327
+ });
328
expect(detail.linkedPullRequests).toEqual([
329
expect.objectContaining({ repository: "acme/web", number: 12, state: "merged" }),
330
]);
packages/issue-tracker-linear/src/server/LinearIssueTracker.ts
+85
-27
@@ -86,11 +86,23 @@ const EMOJI_BY_CONTENT: Record<IssueReactionContent, string> = {
86
rocket: "🚀",
87
eyes: "👀",
88
};
89
+/** Linear takes the emoji on a write and answers with its short name, so a read knows both. */
90
+const EMOJI_NAME_BY_CONTENT: Record<IssueReactionContent, string> = {
91
+ "thumbs-up": "+1",
92
+ "thumbs-down": "-1",
93
+ laugh: "smile",
94
+ hooray: "tada",
95
+ confused: "confused",
96
+ heart: "heart",
97
+ rocket: "rocket",
98
+ eyes: "eyes",
99
+};
100
const CONTENT_BY_EMOJI = new Map(
90
- Object.entries(EMOJI_BY_CONTENT).map(([content, emoji]) => [
91
- emoji,
92
- content as IssueReactionContent,
93
- ]),
101
+ [EMOJI_BY_CONTENT, EMOJI_NAME_BY_CONTENT].flatMap((spellings) =>
102
+ Object.entries(spellings).map(
103
+ ([content, emoji]) => [emoji, content as IssueReactionContent] as const,
104
+ ),
105
+ ),
106
);
107
108
/** `ENG-123`, or null for anything that is not a Linear identifier. */
@@ -104,15 +116,31 @@ function toState(state: LinearApi.LinearWorkflowState): IssueState {
116
: { category: "open", name: state.name };
117
}
118
107
-/** Linear identifies people by id, so that is the login; the display name is what people see. */
119
+/**
120
+ * The login is Linear's handle (its `displayName`, unique in a workspace), which is what people
121
+ * see and what filters and writes are named by; the id stays inside this adapter.
122
+ */
123
function toActor(user: LinearApi.LinearUser): IssueActor {
124
return {
110
- login: user.id,
111
- name: user.displayName ?? user.name,
125
+ login: user.displayName || user.id,
126
+ name: user.name ?? null,
127
avatarUrl: user.avatarUrl ?? null,
128
};
129
}
130
131
+type LinearBot = NonNullable<LinearApi.LinearIssue["botActor"]>;
132
+
133
+/**
134
+ * Who did it: the person, else the integration that acted (GitHub moving an issue, a form filing
135
+ * one), which Linear reports beside an empty user.
136
+ */
137
+function actorOf(user: LinearApi.LinearUser | null, bot: LinearBot | null): IssueActor | null {
138
+ if (user !== null) return toActor(user);
139
+ const name = bot?.userDisplayName ?? bot?.name;
140
+ if (bot == null || !name) return null;
141
+ return { isBot: true, login: bot.name ?? name, name, avatarUrl: bot.avatarUrl ?? null };
142
+}
143
+
144
/** How a user shows in a picker and an event: display name first, falling back to the id. */
145
function userName(user: LinearApi.LinearUser): string {
146
return user.displayName ?? user.name ?? user.email ?? user.id;
@@ -125,7 +153,7 @@ function toSummary(issue: LinearApi.LinearIssue, commentCount = 0): TrackerIssue
153
displayKey: issue.identifier,
154
title: issue.title,
155
url: issue.url,
128
- author: issue.creator === null ? null : toActor(issue.creator),
156
+ author: actorOf(issue.creator, issue.botActor),
157
state: toState(issue.state),
158
createdAt: issue.createdAt,
159
updatedAt: issue.updatedAt,
@@ -165,7 +193,7 @@ function toReactions(
193
function toComment(comment: LinearApi.LinearComment, viewerId: string | null): IssueComment {
194
return {
195
id: comment.id,
168
- author: comment.user === null ? null : toActor(comment.user),
196
+ author: actorOf(comment.user, comment.botActor),
197
body: comment.body,
198
createdAt: comment.createdAt,
199
url: comment.url,
@@ -176,7 +204,7 @@ function toComment(comment: LinearApi.LinearComment, viewerId: string | null): I
204
function toEvents(history: ReadonlyArray<LinearApi.LinearHistoryEntry>): IssueEvent[] {
205
const events: IssueEvent[] = [];
206
for (const entry of history) {
179
- const actor = entry.actor === null ? null : toActor(entry.actor);
207
+ const actor = actorOf(entry.actor, entry.botActor);
208
const add = (kind: IssueEvent["kind"], detail: string | null, suffix: string) =>
209
events.push({ id: `${entry.id}:${suffix}`, kind, actor, createdAt: entry.createdAt, detail });
210
if (entry.toState !== null && entry.toState.id !== entry.fromState?.id) {
@@ -270,11 +298,11 @@ function involvementFilter(input: {
298
}): LinearApi.IssueFilter {
299
switch (input.involvement) {
300
case "assigned":
273
- return { assignee: { id: { eq: input.viewer } } };
301
+ return { assignee: { displayName: { eq: input.viewer } } };
302
case "authored":
275
- return { creator: { id: { eq: input.viewer } } };
303
+ return { creator: { displayName: { eq: input.viewer } } };
304
case "mentioned":
277
- return { subscribers: { some: { id: { eq: input.viewer } } } };
305
+ return { subscribers: { some: { displayName: { eq: input.viewer } } } };
306
case "all":
307
return {};
308
}
@@ -309,7 +337,8 @@ export const make: Effect.Effect<StandaloneIssueTrackerApi, never, LinearApi.Lin
337
input: { readonly scope: string; readonly key: string },
338
) {
339
const identifier = yield* requireIdentifier(operation, input.key);
312
- const issue = yield* linear.getIssue(identifier, 0);
340
+ // One comment, not none: Linear refuses a page of zero.
341
+ const issue = yield* linear.getIssue(identifier, 1);
342
if (issue === null) return yield* notFound(operation);
343
const team = input.scope.trim().toUpperCase();
344
if (issue.team.key !== team) {
@@ -384,7 +413,7 @@ export const make: Effect.Effect<StandaloneIssueTrackerApi, never, LinearApi.Lin
413
),
414
415
// The id, not the display name: it is what the involvement filters compare against.
387
- getViewer: () => linear.viewer().pipe(Effect.map((data) => data.viewer.id)),
416
+ getViewer: () => linear.viewer().pipe(Effect.map((data) => toActor(data.viewer).login)),
417
418
listIssues: (input) => {
419
// `ENG-12`, `#12` or `12` asks for one issue of this team by number.
@@ -392,6 +421,13 @@ export const make: Effect.Effect<StandaloneIssueTrackerApi, never, LinearApi.Lin
421
input.query === undefined
422
? null
423
: /^(?:[A-Za-z][A-Za-z0-9]*-|#)?(\d+)$/.exec(input.query.trim());
424
+ // Each is its own clause: an assignee filter must narrow "assigned to me", not replace it.
425
+ const clauses: LinearApi.IssueFilter[] = [
426
+ ...(input.assignee === undefined
427
+ ? []
428
+ : [{ assignee: { displayName: { eq: input.assignee } } }]),
429
+ ...(input.labels ?? []).map((name) => ({ labels: { some: { name: { eq: name } } } })),
430
+ ];
431
const filter: LinearApi.IssueFilter = {
432
team: { key: { eq: input.scope.trim().toUpperCase() } },
433
...involvementFilter(input),
@@ -405,6 +441,7 @@ export const make: Effect.Effect<StandaloneIssueTrackerApi, never, LinearApi.Lin
441
: { nin: CLOSED_STATE_TYPES },
442
},
443
}),
444
+ ...(clauses.length === 0 ? {} : { and: clauses }),
445
...(input.query === undefined
446
? {}
447
: {
@@ -415,25 +452,37 @@ export const make: Effect.Effect<StandaloneIssueTrackerApi, never, LinearApi.Lin
452
],
453
}),
454
};
418
- return linear.listIssues({ filter, first: input.limit, after: input.cursor }).pipe(
419
- Effect.map((page) => ({
420
- items: page.nodes.map(toSummary),
421
- nextCursor: page.nextCursor,
422
- })),
423
- );
455
+ return linear
456
+ .listIssues({
457
+ filter,
458
+ first: input.limit,
459
+ after: input.cursor,
460
+ orderBy: input.sort === "created" ? "createdAt" : "updatedAt",
461
+ })
462
+ .pipe(
463
+ Effect.map((page) => ({
464
+ items: page.nodes.map((node) => toSummary(node)),
465
+ nextCursor: page.nextCursor,
466
+ })),
467
+ );
468
},
469
470
getIssue: Effect.fn("LinearIssueTracker.getIssue")(function* (input) {
471
const identifier = yield* requireIdentifier("getIssue", input.key);
428
- const [issue, viewer] = yield* Effect.all([
472
+ // One read of the viewer: the id matches reactions, the handle is what the client sees.
473
+ const [issue, me] = yield* Effect.all([
474
linear.getIssue(identifier, COMMENTS_PAGE),
430
- viewerId,
475
+ linear.viewer().pipe(
476
+ Effect.map((data) => data.viewer),
477
+ Effect.orElseSucceed(() => null),
478
+ ),
479
]);
480
+ const viewer = me?.id ?? null;
481
if (issue === null) return yield* notFound("getIssue");
482
return {
483
...toSummary(issue, issue.comments.nodes.length),
484
body: issue.description ?? "",
436
- viewer,
485
+ viewer: me === null ? null : toActor(me).login,
486
viewerPermissions: VIEWER_PERMISSIONS,
487
reactions: toReactions(issue.reactions, viewer),
488
comments: issue.comments.nodes.map((comment) => toComment(comment, viewer)),
@@ -516,14 +565,23 @@ export const make: Effect.Effect<StandaloneIssueTrackerApi, never, LinearApi.Lin
565
const emoji = EMOJI_BY_CONTENT[input.content];
566
const target =
567
input.subjectId === undefined ? { issueId: issue.id } : { commentId: input.subjectId };
519
- if (input.reacted) {
568
+ // Comment ids are global: prove the comment belongs to this issue before writing.
569
+ const subject =
570
+ input.subjectId === undefined && input.reacted
571
+ ? null
572
+ : yield* linear.listReactions(target);
573
+ if (subject !== null && subject.issueId !== issue.id) {
574
+ return yield* failed("setReaction", "The comment does not belong to the selected issue.");
575
+ }
576
+ if (subject === null || input.reacted) {
577
yield* linear.createReaction({ ...target, emoji });
578
return;
579
}
580
const viewer = yield* viewerId;
524
- const reactions = yield* linear.listReactions(target);
581
+ const { reactions } = subject;
582
const own = reactions.find(
526
- (reaction) => reaction.emoji === emoji && reaction.user?.id === viewer,
583
+ (reaction) =>
584
+ CONTENT_BY_EMOJI.get(reaction.emoji) === input.content && reaction.user?.id === viewer,
585
);
586
if (own !== undefined) yield* linear.deleteReaction(own.id);
587
}),
packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts
+156
-13
@@ -77,7 +77,14 @@ function answer(args: ReadonlyArray<string>): string {
77
if (resource === "comments") {
78
return encode({
79
continuationToken: "next-token",
80
+ // Newest first, as `order=desc` answers.
81
comments: [
82
+ {
83
+ id: 3,
84
+ text: "Still happening.",
85
+ createdDate: "2026-07-04T00:00:00Z",
86
+ createdBy: { uniqueName: "octo@acme.test" },
87
+ },
88
{
89
id: 1,
90
text: "Repro attached.",
@@ -102,9 +109,11 @@ function answer(args: ReadonlyArray<string>): string {
109
},
110
{
111
id: 2,
105
- revisedDate: "2026-07-03T00:00:00Z",
112
+ // The newest revision has not been superseded, which Azure writes as year 9999.
113
+ revisedDate: "9999-01-01T00:00:00Z",
114
revisedBy: { uniqueName: "theo@acme.test" },
115
fields: {
116
+ "System.ChangedDate": { newValue: "2026-07-03T00:00:00Z" },
117
"System.State": { oldValue: "Active", newValue: "Shipped" },
118
"System.Tags": { oldValue: "ui", newValue: "bug; ui" },
119
},
@@ -115,14 +124,14 @@ function answer(args: ReadonlyArray<string>): string {
124
throw new Error(`unexpected az invocation ${args.join(" ")}`);
125
}
126
118
-function tracker(onExecute: (args: ReadonlyArray<string>) => string) {
127
+function tracker(onExecute: (args: ReadonlyArray<string>, stdin: string | undefined) => string) {
128
return AzureDevOpsIssueTracker.make.pipe(
129
Effect.provide(
130
Layer.mergeAll(
131
NodeFileSystem.layer,
132
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
124
- execute: ({ args }) =>
125
- Effect.succeed(TestSourceControlHost.processOutput(onExecute(args))),
133
+ execute: ({ args, stdin }) =>
134
+ Effect.succeed(TestSourceControlHost.processOutput(onExecute(args, stdin))),
135
}),
136
),
137
),
@@ -165,7 +174,10 @@ describe("AzureDevOpsIssueTracker", () => {
174
commentsCursor: "next-token",
175
viewerPermissions: { setState: true, edit: true, labels: true, assignees: true },
176
});
168
- expect(issue.comments).toEqual([
177
+ // The first page is the newest comments, handed over oldest first.
178
+ expect(seen.find((args) => args.includes("comments"))).toContain("order=desc");
179
+ expect(issue.comments.map((comment) => comment.id)).toEqual(["1", "3"]);
180
+ expect(issue.comments.slice(0, 1)).toEqual([
181
{
182
id: "1",
183
author: { login: "julius@acme.test", name: "Julius", avatarUrl: null },
@@ -176,9 +188,9 @@ describe("AzureDevOpsIssueTracker", () => {
188
},
189
]);
190
// The first revision is the creation; a state move across the category line is a close.
179
- expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
180
- ["closed", "Shipped"],
181
- ["labeled", "bug"],
191
+ expect(issue.events.map((event) => [event.kind, event.detail, event.createdAt])).toEqual([
192
+ ["closed", "Shipped", "2026-07-03T00:00:00Z"],
193
+ ["labeled", "bug", "2026-07-03T00:00:00Z"],
194
]);
195
expect(issue.linkedPullRequests).toEqual([
196
{
@@ -198,6 +210,7 @@ describe("AzureDevOpsIssueTracker", () => {
210
Effect.gen(function* () {
211
const fs = yield* FileSystem.FileSystem;
212
const bodies: string[] = [];
213
+ const hydrated: string[] = [];
214
const api = yield* AzureDevOpsIssueTracker.make.pipe(
215
Effect.provide(
216
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
@@ -207,24 +220,51 @@ describe("AzureDevOpsIssueTracker", () => {
220
Effect.orDie,
221
Effect.map((body) => {
222
bodies.push(body);
210
- return TestSourceControlHost.processOutput(encode({ workItems: [] }));
223
+ return TestSourceControlHost.processOutput(
224
+ encode({ workItems: [{ id: 9 }, { id: 7 }, { id: 3 }] }),
225
+ );
226
}),
227
)
213
- : Effect.succeed(TestSourceControlHost.processOutput(answer(args))),
228
+ : Effect.sync(() => {
229
+ if (args[args.indexOf("--resource") + 1] !== "workitems") {
230
+ return TestSourceControlHost.processOutput(answer(args));
231
+ }
232
+ hydrated.push(args.find((arg) => arg.startsWith("ids=")) ?? "");
233
+ // The page as REST answers it: an envelope, in an order of its own.
234
+ return TestSourceControlHost.processOutput(
235
+ encode({ count: 2, value: [WORK_ITEM, { ...WORK_ITEM, id: 9 }] }),
236
+ );
237
+ }),
238
}),
239
),
240
);
217
- yield* api.listIssues({
241
+ const page = yield* api.listIssues({
242
cwd: "/w",
243
host: "dev.azure.com",
244
scope: "acme/Web App",
245
state: "open",
222
- involvement: "all",
246
+ involvement: "mentioned",
247
viewer: "octo@acme.test",
224
- limit: 10,
248
+ labels: ["o'hare"],
249
+ assignee: "theo@acme.test",
250
+ sort: "created",
251
+ limit: 2,
252
+ cursor: "2026-07-01T00:00:00Z|7",
253
});
254
+ // The rows come back in WIQL's order, and the cursor is the last one of the page.
255
+ expect(hydrated).toEqual(["ids=9,7"]);
256
+ expect(page.items.map((item) => item.key)).toEqual(["9", "7"]);
257
+ expect(page.nextCursor).toBe("2026-07-01T00:00:00Z|7");
258
expect(bodies).toHaveLength(1);
259
expect(bodies[0]).toContain("AND [System.State] NOT IN ('shipped')");
260
+ const { query } = JSON.parse(bodies[0]!) as { query: string };
261
+ // Mentions cannot be asked for over REST, so the filter sends no clause for them.
262
+ expect(query).not.toContain("@RecentMentions");
263
+ expect(query).toContain(
264
+ " AND [System.Tags] CONTAINS 'o''hare' AND [System.AssignedTo] = 'theo@acme.test'" +
265
+ " AND ([System.CreatedDate] < '2026-07-01T00:00:00Z' OR ([System.CreatedDate] = '2026-07-01T00:00:00Z' AND [System.Id] < 7))" +
266
+ " ORDER BY [System.CreatedDate] DESC, [System.Id] DESC",
267
+ );
268
}).pipe(Effect.provide(NodeFileSystem.layer)),
269
);
270
@@ -243,6 +283,109 @@ describe("AzureDevOpsIssueTracker", () => {
283
}),
284
);
285
286
+ it.effect("reads a legacy organization's work item and every page of its updates", () =>
287
+ Effect.gen(function* () {
288
+ const seen: string[][] = [];
289
+ const api = yield* tracker((args) => {
290
+ seen.push([...args]);
291
+ if (args[0] === "boards") {
292
+ return encode({
293
+ ...WORK_ITEM,
294
+ url: "https://acme.visualstudio.com/p-guid/_apis/wit/workItems/7",
295
+ relations: [],
296
+ });
297
+ }
298
+ if (args[args.indexOf("--resource") + 1] !== "updates") return answer(args);
299
+ const rename = (id: number) => ({
300
+ id,
301
+ revisedDate: "2026-07-02T00:00:00Z",
302
+ fields: { "System.Title": { oldValue: "a", newValue: `title ${id}` } },
303
+ });
304
+ return encode({
305
+ value: args.includes("$skip=100")
306
+ ? [rename(102)]
307
+ : Array.from({ length: 100 }, (_, index) => rename(index + 2)),
308
+ });
309
+ });
310
+ const issue = yield* api.getIssue({
311
+ cwd: "/w",
312
+ host: "acme.visualstudio.com",
313
+ scope: "Web App",
314
+ key: "7",
315
+ });
316
+ for (const args of seen) {
317
+ expect(args).toContain("https://acme.visualstudio.com");
318
+ }
319
+ expect(issue.url).toBe("https://acme.visualstudio.com/Web%20App/_workitems/edit/7");
320
+ expect(issue.events).toHaveLength(101);
321
+ expect(issue.events.at(-1)?.detail).toBe("title 102");
322
+ }),
323
+ );
324
+
325
+ it.effect("refuses a write Azure cannot carry out as asked, without writing", () =>
326
+ Effect.gen(function* () {
327
+ const writes: string[][] = [];
328
+ const api = yield* tracker((args) => {
329
+ if (args[0] === "boards" && args[2] !== "show") writes.push([...args]);
330
+ return answer(args);
331
+ });
332
+ const target = { cwd: "/w", host: "dev.azure.com", key: "7" };
333
+ const own = { ...target, scope: "acme/Web App" };
334
+ // Work item 7 is in "Web App"; an id alone would let another project's scope write to it.
335
+ const elsewhere = { ...target, scope: "acme/Other" };
336
+ const refusals = yield* Effect.all([
337
+ Effect.flip(api.update!({ ...elsewhere, title: "x" })),
338
+ Effect.flip(api.setState!({ ...elsewhere, state: "Active" })),
339
+ Effect.flip(api.update!({ ...own, assignees: ["a@acme.test", "b@acme.test"] })),
340
+ // `az` would send the contents of that file as the tag.
341
+ Effect.flip(api.update!({ ...own, labels: ["@/etc/hostname"] })),
342
+ Effect.flip(api.getIssue({ ...target, scope: "acme/@secrets" })),
343
+ ]);
344
+ expect(refusals.map((error) => error.reason)).toEqual([
345
+ "not-found",
346
+ "not-found",
347
+ "failed",
348
+ "failed",
349
+ "failed",
350
+ ]);
351
+ expect(writes).toEqual([]);
352
+ }),
353
+ );
354
+
355
+ it.effect("sends text that starts with @ on stdin, where az reads no file for it", () =>
356
+ Effect.gen(function* () {
357
+ const writes: Array<{ args: string[]; stdin: string | undefined }> = [];
358
+ const api = yield* tracker((args, stdin) => {
359
+ if (args[0] === "boards" && args[2] !== "show") writes.push({ args: [...args], stdin });
360
+ return answer(args);
361
+ });
362
+ const scope = { cwd: "/w", host: "dev.azure.com", scope: "acme/Web App" };
363
+ yield* api.update!({ ...scope, key: "7", title: "@/etc/hostname", body: "@notes" });
364
+ yield* api.create!({
365
+ ...scope,
366
+ title: "@/etc/hostname",
367
+ body: "@notes",
368
+ labels: [],
369
+ assignees: [],
370
+ });
371
+ for (const write of writes) {
372
+ expect(write.args.filter((arg) => arg.startsWith("@") || arg.includes("=@/"))).toEqual([]);
373
+ }
374
+ expect(
375
+ writes.map((write) => [
376
+ write.args[2],
377
+ write.args.find((arg) => arg.endsWith("=@-")),
378
+ write.stdin,
379
+ ]),
380
+ ).toEqual([
381
+ ["update", "--title=@-", "@/etc/hostname"],
382
+ ["update", "--description=@-", "@notes"],
383
+ ["create", "--title=@-", "@/etc/hostname"],
384
+ ["update", "--description=@-", "@notes"],
385
+ ]);
386
+ }),
387
+ );
388
+
389
it.effect("keeps a failure's own text in the cause, out of the detail a caller reads", () =>
390
Effect.gen(function* () {
391
const denied = PlatformError.systemError({
packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts
+185
-66
@@ -10,6 +10,7 @@ import * as Schema from "effect/Schema";
10
import {
11
IssueTrackerKind,
12
type IssueCapabilities,
13
+ type IssueEvent,
14
type IssueInvolvement,
15
type IssueLinkedPullRequest,
16
type IssueViewerPermissions,
@@ -82,6 +83,8 @@ const VIEWER_PERMISSIONS: IssueViewerPermissions = {
83
84
const REST_API_VERSION = "7.1";
85
const PAGE_SIZE = 100;
86
+/** Updates are read a page per `az` process, oldest first, so a long history is bounded. */
87
+const UPDATE_PAGE_LIMIT = 5;
88
/** Linked pull requests are read one `az` process each, so a work item's links are bounded. */
89
const LINKED_PULL_REQUEST_LIMIT = 10;
90
/** Which work item type a new issue is filed as, in order of preference across the stock processes. */
@@ -144,14 +147,16 @@ function parseScope(
147
scope: string,
148
): { readonly organization: string; readonly project: string } | null {
149
const parts = scope.split("/").flatMap((part) => part.trim() || []);
150
+ // `az` replaces a value starting with `@` by the contents of that local file.
151
+ if (parts.some((part) => part.startsWith("@"))) return null;
152
+ // A legacy organization is its hostname, so its scope may be the project alone.
153
+ if (host.toLowerCase().endsWith(".visualstudio.com")) {
154
+ const project = parts.length === 1 || parts.length === 2 ? parts.at(-1) : undefined;
155
+ return project === undefined ? null : { organization: `https://${host}`, project };
156
+ }
157
if (parts.length !== 2) return null;
158
const [organization, project] = parts as [string, string];
149
- return {
150
- organization: host.toLowerCase().endsWith(".visualstudio.com")
151
- ? `https://${host}`
152
- : `https://${host}/${encodeURIComponent(organization)}`,
153
- project,
154
- };
159
+ return { organization: `https://${host}/${encodeURIComponent(organization)}`, project };
160
}
161
162
function parseNumber(key: string): number | null {
@@ -169,7 +174,8 @@ function involvementClause(involvement: IssueInvolvement): string {
174
return " AND [System.AssignedTo] = @Me";
175
case "authored":
176
return " AND [System.CreatedBy] = @Me";
172
- // Azure records no mention of a person on a work item, so a mention filter has nothing to narrow by.
177
+ // WIQL over REST has no way to ask who was mentioned (`@RecentMentions` is a web portal
178
+ // macro), so a mention filter has nothing to narrow by.
179
case "mentioned":
180
case "all":
181
return "";
@@ -188,10 +194,10 @@ function stateClause(state: "all" | "open" | "closed", closedStates: ClosedState
194
}
195
}
196
191
-/** `<iso changed date>|<id>` of the last row handed over, which is where the next page starts. */
192
-function parseCursor(cursor: string): { readonly changedAt: string; readonly id: number } | null {
197
+/** `<iso date the list is sorted by>|<id>` of the last row handed over, where the next page starts. */
198
+function parseCursor(cursor: string): { readonly date: string; readonly id: number } | null {
199
const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)\|([1-9]\d{0,9})$/.exec(cursor);
194
- return match === null ? null : { changedAt: match[1]!, id: Number(match[2]) };
200
+ return match === null ? null : { date: match[1]!, id: Number(match[2]) };
201
}
202
203
function reasonFor(error: AzureDevOpsCli.AzureDevOpsCliError): IssueTrackerError["reason"] {
@@ -263,9 +269,14 @@ export const make: Effect.Effect<
269
readonly cwd: string;
270
readonly operation: string;
271
readonly args: ReadonlyArray<string>;
272
+ readonly stdin?: string | undefined;
273
}) =>
274
azure
268
- .execute({ cwd: input.cwd, args: [...input.args, "--only-show-errors", "--output", "json"] })
275
+ .execute({
276
+ cwd: input.cwd,
277
+ args: [...input.args, "--only-show-errors", "--output", "json"],
278
+ ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
279
+ })
280
.pipe(
281
Effect.map((result) => result.stdout.trim()),
282
Effect.mapError(fail(input.operation)),
@@ -275,6 +286,7 @@ export const make: Effect.Effect<
286
readonly cwd: string;
287
readonly operation: string;
288
readonly args: ReadonlyArray<string>;
289
+ readonly stdin?: string | undefined;
290
readonly decode: (raw: string) => Result.Result<A, unknown>;
291
}): Effect.Effect<A, IssueTrackerError> =>
292
run(input).pipe(
@@ -362,6 +374,7 @@ export const make: Effect.Effect<
374
readonly cwd: string;
375
readonly operation: string;
376
readonly organization: string;
377
+ readonly project: string;
378
readonly number: number;
379
readonly closed: ClosedStates;
380
}): Effect.Effect<AzureDevOpsWorkItem, IssueTrackerError> =>
@@ -387,6 +400,12 @@ export const make: Effect.Effect<
400
(item) => item !== null,
401
() => notFound(input.operation),
402
),
403
+ // `az` addresses a work item by organization and id alone, so one from another project
404
+ // answers too; the scope names a project, and an item outside it is not this scope's.
405
+ Effect.filterOrFail(
406
+ (item) => item.project?.toLowerCase() === input.project.toLowerCase(),
407
+ () => notFound(input.operation),
408
+ ),
409
);
410
411
/** The work item as `az` addresses it, or a not-found for a key that names no id. */
@@ -403,6 +422,7 @@ export const make: Effect.Effect<
422
}),
423
);
424
425
+ /** Newest first, so the first page is the current discussion and a cursor leads to older ones. */
426
const comments = (input: {
427
readonly cwd: string;
428
readonly operation: string;
@@ -421,14 +441,40 @@ export const make: Effect.Effect<
441
apiVersion: "7.1-preview",
442
query: [
443
`$top=${PAGE_SIZE}`,
424
- "order=asc",
444
+ "order=desc",
445
"$expand=reactions",
446
"api-version=7.1-preview.4",
447
...(input.cursor === undefined ? [] : [`continuationToken=${input.cursor}`]),
448
],
449
}),
450
decode: decodeCommentsJson,
431
- });
451
+ }).pipe(Effect.map((page) => ({ ...page, comments: page.comments.toReversed() })));
452
+
453
+ const updates = Effect.fn("AzureDevOpsIssueTracker.updates")(function* (input: {
454
+ readonly cwd: string;
455
+ readonly organization: string;
456
+ readonly project: string;
457
+ readonly number: number;
458
+ readonly closed: ClosedStates;
459
+ }) {
460
+ const events: IssueEvent[] = [];
461
+ for (let page = 0; page < UPDATE_PAGE_LIMIT; page += 1) {
462
+ const answer = yield* read({
463
+ cwd: input.cwd,
464
+ operation: "getIssue",
465
+ args: invokeArgs({
466
+ ...input,
467
+ resource: "updates",
468
+ route: [`id=${input.number}`],
469
+ query: [`$top=${PAGE_SIZE}`, ...(page === 0 ? [] : [`$skip=${page * PAGE_SIZE}`])],
470
+ }),
471
+ decode: (raw) => decodeUpdatesJson(raw, input.closed),
472
+ });
473
+ events.push(...answer.events);
474
+ if (answer.count < PAGE_SIZE) break;
475
+ }
476
+ return events;
477
+ });
478
479
const linkedPullRequests = (input: {
480
readonly cwd: string;
@@ -490,6 +536,7 @@ export const make: Effect.Effect<
536
readonly organization: string;
537
readonly number: number;
538
readonly args: ReadonlyArray<string>;
539
+ readonly stdin?: string | undefined;
540
}) =>
541
run({
542
cwd: input.cwd,
@@ -506,18 +553,42 @@ export const make: Effect.Effect<
553
String(input.number),
554
...input.args,
555
],
556
+ stdin: input.stdin,
557
}).pipe(Effect.asVoid);
558
559
+ /** A write names its work item by id alone, so the item is first read to be the scope's own. */
560
+ const owned = (
561
+ operation: string,
562
+ cwd: string,
563
+ scope: { readonly organization: string; readonly project: string; readonly number: number },
564
+ ) => workItem({ ...scope, cwd, operation, closed: new Set() }).pipe(Effect.as(scope));
565
+
566
/** Azure keeps tags as one `; `-joined field and takes exactly one assignee. */
512
- const fieldArgs = (input: {
513
- readonly labels?: ReadonlyArray<string> | undefined;
514
- readonly assignees?: ReadonlyArray<string> | undefined;
515
- }): ReadonlyArray<string> => {
567
+ const fieldArgs = (
568
+ operation: string,
569
+ input: {
570
+ readonly labels?: ReadonlyArray<string> | undefined;
571
+ readonly assignees?: ReadonlyArray<string> | undefined;
572
+ },
573
+ ): Effect.Effect<ReadonlyArray<string>, IssueTrackerError> => {
574
+ if ((input.assignees?.length ?? 0) > 1) {
575
+ return Effect.fail(refused(operation, "An Azure DevOps work item has one assignee at most."));
576
+ }
577
const fields = [
517
- ...(input.labels === undefined ? [] : [`System.Tags=${input.labels.join("; ")}`]),
518
- ...(input.assignees === undefined ? [] : [`System.AssignedTo=${input.assignees[0] ?? ""}`]),
578
+ ...(input.labels === undefined ? [] : [["System.Tags", input.labels.join("; ")] as const]),
579
+ ...(input.assignees === undefined
580
+ ? []
581
+ : [["System.AssignedTo", input.assignees[0] ?? ""] as const]),
582
];
520
- return fields.length === 0 ? [] : ["--fields", ...fields];
583
+ // `az` reads `field=@path` as that local file, and a field value has no stdin to go through.
584
+ if (fields.some(([, value]) => value.startsWith("@"))) {
585
+ return Effect.fail(
586
+ refused(operation, "Azure DevOps takes no label or assignee that starts with `@`."),
587
+ );
588
+ }
589
+ return Effect.succeed(
590
+ fields.length === 0 ? [] : ["--fields", ...fields.map(([name, value]) => `${name}=${value}`)],
591
+ );
592
};
593
594
return {
@@ -552,16 +623,16 @@ export const make: Effect.Effect<
623
),
624
),
625
555
- listIssues: (input) => {
626
+ listIssues: Effect.fn("AzureDevOpsIssueTracker.listIssues")(function* (input) {
627
const cursor = input.cursor === undefined ? undefined : parseCursor(input.cursor);
628
if (cursor === null) {
558
- return Effect.fail(
559
- refused("listIssues", "The cursor was not one Azure DevOps handed out."),
560
- );
629
+ return yield* refused("listIssues", "The cursor was not one Azure DevOps handed out.");
630
}
631
const limit = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
632
const text = input.query?.trim() ?? "";
564
- return scoped("listIssues", input).pipe(
633
+ const created = input.sort === "created";
634
+ const dateField = created ? "[System.CreatedDate]" : "[System.ChangedDate]";
635
+ return yield* scoped("listIssues", input).pipe(
636
Effect.flatMap((scope) =>
637
closedStates({ ...scope, cwd: input.cwd, operation: "listIssues" }).pipe(
638
Effect.map((closed) => ({ scope, closed })),
@@ -584,10 +655,16 @@ export const make: Effect.Effect<
655
stateClause(input.state, closed) +
656
involvementClause(input.involvement) +
657
(text.length === 0 ? "" : ` AND [System.Title] CONTAINS ${quoted(text)}`) +
658
+ (input.labels ?? [])
659
+ .map((label) => ` AND [System.Tags] CONTAINS ${quoted(label)}`)
660
+ .join("") +
661
+ (input.assignee === undefined
662
+ ? ""
663
+ : ` AND [System.AssignedTo] = ${quoted(input.assignee)}`) +
664
(cursor === undefined
665
? ""
589
- : ` AND ([System.ChangedDate] < ${quoted(cursor.changedAt)} OR ([System.ChangedDate] = ${quoted(cursor.changedAt)} AND [System.Id] < ${cursor.id}))`) +
590
- " ORDER BY [System.ChangedDate] DESC, [System.Id] DESC",
666
+ : ` AND (${dateField} < ${quoted(cursor.date)} OR (${dateField} = ${quoted(cursor.date)} AND [System.Id] < ${cursor.id}))`) +
667
+ ` ORDER BY ${dateField} DESC, [System.Id] DESC`,
668
},
669
}).pipe(
670
Effect.flatMap((raw) => {
@@ -615,13 +692,19 @@ export const make: Effect.Effect<
692
}),
693
decode: (raw) => decodeWorkItemsJson(raw, closed),
694
}).pipe(
618
- Effect.map((items) => {
695
+ Effect.map((hydrated) => {
696
+ // The cursor is the last row WIQL sorted, so its order is restored.
697
+ const position = new Map(ids.map((row, index) => [String(row.id), index]));
698
+ const items = hydrated.toSorted(
699
+ (left, right) =>
700
+ (position.get(left.key) ?? 0) - (position.get(right.key) ?? 0),
701
+ );
702
const last = items.at(-1);
703
return {
704
items,
705
nextCursor:
706
ids.length > limit && last !== undefined
624
- ? `${last.updatedAt}|${last.key}`
707
+ ? `${created ? last.createdAt : last.updatedAt}|${last.key}`
708
: null,
709
};
710
}),
@@ -630,7 +713,7 @@ export const make: Effect.Effect<
713
),
714
),
715
);
633
- },
716
+ }),
717
718
getIssue: (input) =>
719
target("getIssue", input).pipe(
@@ -645,17 +728,7 @@ export const make: Effect.Effect<
728
Effect.all(
729
[
730
comments({ ...scope, cwd: input.cwd, operation: "getIssue" }),
648
- read({
649
- cwd: input.cwd,
650
- operation: "getIssue",
651
- args: invokeArgs({
652
- ...scope,
653
- resource: "updates",
654
- route: [`id=${scope.number}`],
655
- query: [`$top=${PAGE_SIZE}`],
656
- }),
657
- decode: (raw) => decodeUpdatesJson(raw, closed),
658
- }),
731
+ updates({ ...scope, cwd: input.cwd, closed }),
732
linkedPullRequests({ cwd: input.cwd, organization: scope.organization, item }),
733
],
734
{ concurrency: 3 },
@@ -678,13 +751,25 @@ export const make: Effect.Effect<
751
752
getComments: (input) =>
753
target("getComments", input).pipe(
754
+ // `az` would read a `continuationToken=@path` as that local file.
755
+ Effect.filterOrFail(
756
+ () => !input.cursor.startsWith("@"),
757
+ () => refused("getComments", "The cursor was not one Azure DevOps handed out."),
758
+ ),
759
Effect.flatMap((scope) =>
760
comments({ ...scope, cwd: input.cwd, operation: "getComments", cursor: input.cursor }),
761
),
762
),
763
686
- create: (input) =>
687
- scoped("create", input).pipe(
764
+ create: (input) => {
765
+ const title = AzureDevOpsCli.textOption("--title", input.title);
766
+ const body =
767
+ input.body.length === 0
768
+ ? undefined
769
+ : AzureDevOpsCli.textOption("--description", input.body);
770
+ // az has one stdin, so a second value read from it goes in a call of its own.
771
+ const bodyFollows = title.stdin !== undefined && body?.stdin !== undefined;
772
+ return scoped("create", input).pipe(
773
Effect.flatMap((scope) =>
774
workItemTypes({ ...scope, cwd: input.cwd, operation: "create" }).pipe(
775
Effect.flatMap((types) => {
@@ -692,9 +777,14 @@ export const make: Effect.Effect<
777
const type = CREATE_TYPES.find((name) => names.includes(name)) ?? names[0];
778
return type === undefined
779
? Effect.fail(refused("create", "The project offers no work item type to file."))
695
- : Effect.succeed({ type, closed: closedStateNames(types) });
780
+ : fieldArgs("create", {
781
+ ...(input.labels.length === 0 ? {} : { labels: input.labels }),
782
+ ...(input.assignees.length === 0 ? {} : { assignees: input.assignees }),
783
+ }).pipe(
784
+ Effect.map((fields) => ({ type, fields, closed: closedStateNames(types) })),
785
+ );
786
}),
697
- Effect.flatMap(({ type, closed }) =>
787
+ Effect.flatMap(({ type, fields, closed }) =>
788
read({
789
cwd: input.cwd,
790
operation: "create",
@@ -710,14 +800,11 @@ export const make: Effect.Effect<
800
scope.project,
801
"--type",
802
type,
713
- "--title",
714
- input.title,
715
- ...(input.body.length === 0 ? [] : ["--description", input.body]),
716
- ...fieldArgs({
717
- ...(input.labels.length === 0 ? {} : { labels: input.labels }),
718
- ...(input.assignees.length === 0 ? {} : { assignees: input.assignees }),
719
- }),
803
+ title.arg,
804
+ ...(body === undefined || bodyFollows ? [] : [body.arg]),
805
+ ...fields,
806
],
807
+ stdin: title.stdin ?? body?.stdin,
808
decode: (raw) => decodeWorkItemJson(raw, closed),
809
}),
810
),
@@ -725,10 +812,23 @@ export const make: Effect.Effect<
812
(item) => item !== null,
813
() => unreadable("create", "incomplete-response"),
814
),
815
+ Effect.tap((item) =>
816
+ body === undefined || !bodyFollows
817
+ ? Effect.void
818
+ : update({
819
+ cwd: input.cwd,
820
+ operation: "create",
821
+ organization: scope.organization,
822
+ number: Number(item.key),
823
+ args: [body.arg],
824
+ stdin: body.stdin,
825
+ }),
826
+ ),
827
Effect.map((item) => ({ key: item.key, displayKey: item.displayKey, url: item.url })),
828
),
829
),
731
- ),
830
+ );
831
+ },
832
833
comment: (input) =>
834
target("comment", input).pipe(
@@ -750,24 +850,43 @@ export const make: Effect.Effect<
850
Effect.asVoid,
851
),
852
753
- update: (input) =>
754
- target("update", input).pipe(
853
+ update: (input) => {
854
+ const texts = [
855
+ ...(input.title === undefined ? [] : [AzureDevOpsCli.textOption("--title", input.title)]),
856
+ ...(input.body === undefined
857
+ ? []
858
+ : [AzureDevOpsCli.textOption("--description", input.body)]),
859
+ ];
860
+ // az has one stdin, so each value read from it needs its own call.
861
+ const batches =
862
+ texts.filter((text) => text.stdin !== undefined).length > 1
863
+ ? texts.map((text) => [text])
864
+ : [texts];
865
+ return target("update", input).pipe(
866
Effect.flatMap((scope) =>
756
- update({
757
- ...scope,
758
- cwd: input.cwd,
759
- operation: "update",
760
- args: [
761
- ...(input.title === undefined ? [] : ["--title", input.title]),
762
- ...(input.body === undefined ? [] : ["--description", input.body]),
763
- ...fieldArgs(input),
764
- ],
765
- }),
867
+ fieldArgs("update", input).pipe(Effect.map((fields) => ({ scope, fields }))),
868
),
767
- ),
869
+ Effect.tap(({ scope }) => owned("update", input.cwd, scope)),
870
+ Effect.flatMap(({ scope, fields }) =>
871
+ Effect.forEach(
872
+ batches,
873
+ (batch, index) =>
874
+ update({
875
+ ...scope,
876
+ cwd: input.cwd,
877
+ operation: "update",
878
+ args: [...batch.map((text) => text.arg), ...(index === 0 ? fields : [])],
879
+ stdin: batch.find((text) => text.stdin !== undefined)?.stdin,
880
+ }),
881
+ { discard: true },
882
+ ),
883
+ ),
884
+ );
885
+ },
886
887
setState: (input) =>
888
target("setState", input).pipe(
889
+ Effect.flatMap((scope) => owned("setState", input.cwd, scope)),
890
Effect.flatMap((scope) =>
891
update({
892
...scope,
packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts
+32
-13
@@ -86,7 +86,9 @@ const WorkItem = Schema.Struct({
86
});
87
88
const decodeWorkItemEntry = Schema.decodeUnknownExit(WorkItem);
89
-const decodeUnknownList = decodeJsonResult(Schema.NullOr(Schema.Array(Schema.Unknown)));
89
+const decodeWorkItemList = decodeJsonResult(
90
+ Schema.Struct({ value: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))) }),
91
+);
92
const decodeWorkItem = decodeJsonResult(WorkItem);
93
94
type DecodeFailure =
@@ -107,8 +109,18 @@ function browserUrl(
109
project: string | null,
110
): string | null {
111
if (apiUrl === null || apiUrl === undefined || project === null) return null;
110
- const match = /^(https?:\/\/[^/]+\/[^/]+)\/(?:[^/]+\/)?_apis\/wit\/workItems\//i.exec(apiUrl);
111
- return match === null ? null : `${match[1]}/${encodeURIComponent(project)}/_workitems/edit/${id}`;
112
+ const match = /^(https?:\/\/([^/]+))(?:\/([^/]+))?(?:\/[^/]+)?\/_apis\/wit\/workItems\//i.exec(
113
+ apiUrl,
114
+ );
115
+ if (match === null) return null;
116
+ const [, origin, host, organization] = match;
117
+ // A legacy organization is its hostname, so whatever the path starts with is a project.
118
+ const base = host!.toLowerCase().endsWith(".visualstudio.com")
119
+ ? origin
120
+ : organization === undefined
121
+ ? null
122
+ : `${origin}/${organization}`;
123
+ return base === null ? null : `${base}/${encodeURIComponent(project)}/_workitems/edit/${id}`;
124
}
125
126
function toActor(value: typeof IdentityValue.Type | undefined): IssueActor | null {
@@ -173,13 +185,13 @@ function toWorkItem(raw: typeof WorkItem.Type, closed: ClosedStates): AzureDevOp
185
};
186
}
187
176
-/** A flat WIQL answer; a row this cannot place is skipped rather than failing the page. */
188
+/** The `{ count, value }` page `wit/workitems` answers; a row this cannot place is skipped. */
189
export function decodeWorkItemsJson(
190
raw: string,
191
closed: ClosedStates,
192
): Result.Result<ReadonlyArray<AzureDevOpsWorkItem>, DecodeFailure> {
181
- return Result.map(decodeUnknownList(raw.trim().length === 0 ? "[]" : raw), (rows) =>
182
- (rows ?? []).flatMap((entry) => {
193
+ return Result.map(decodeWorkItemList(raw), (page) =>
194
+ (page.value ?? []).flatMap((entry) => {
195
const item = decodeWorkItemEntry(entry);
196
if (Exit.isFailure(item)) return [];
197
return toWorkItem(item.value, closed) ?? [];
@@ -302,26 +314,33 @@ function identityLogin(value: unknown): string | null {
314
}
315
316
/**
305
- * The timeline, read out of each revision's field changes. Azure reads `9999-01-01` as the changed
306
- * date of the newest revision, so the revision's own date is what every event carries.
317
+ * The timeline, read out of each revision's field changes, with how many updates the page held.
318
+ * `revisedDate` is when a revision was superseded, `9999-01-01` on the newest, so an event is
319
+ * dated by the revision's changed date where Azure states one.
320
*/
321
export function decodeUpdatesJson(
322
raw: string,
323
closed: ClosedStates,
311
-): Result.Result<ReadonlyArray<IssueEvent>, DecodeFailure> {
312
- return Result.map(decodeUpdatesPage(raw), (page) =>
313
- (page.value ?? []).flatMap((entry) => {
324
+): Result.Result<
325
+ { readonly events: ReadonlyArray<IssueEvent>; readonly count: number },
326
+ DecodeFailure
327
+> {
328
+ return Result.map(decodeUpdatesPage(raw), (page) => ({
329
+ count: (page.value ?? []).length,
330
+ events: (page.value ?? []).flatMap((entry) => {
331
const update = decodeUpdateEntry(entry);
332
if (Exit.isFailure(update) || update.value.id === 1) return [];
333
const { id, revisedBy, revisedDate } = update.value;
334
const fields = update.value.fields ?? {};
335
+ const changedDate = fields["System.ChangedDate"]?.newValue;
336
+ const createdAt = typeof changedDate === "string" ? changedDate : revisedDate;
337
const events: IssueEvent[] = [];
338
const add = (kind: IssueEvent["kind"], detail: string | null) =>
339
events.push({
340
id: `update-${id}-${events.length}`,
341
kind,
342
actor: toActor(revisedBy),
324
- createdAt: revisedDate,
343
+ createdAt,
344
detail,
345
});
346
const state = fields["System.State"];
@@ -361,7 +380,7 @@ export function decodeUpdatesJson(
380
}
381
return events;
382
}),
364
- );
383
+ }));
384
}
385
386
/** A relation that links a pull request, as Azure spells it: `vstfs:///Git/PullRequestId/{project}/{repo}/{id}`. */
packages/source-control-azure-devops/src/shared/definition.test.ts
+11
@@ -260,5 +260,16 @@ describe("Azure DevOps issue scope", () => {
260
definition.issueScope?.({ provider: kind, displayName: "acme/Web%20App/_git/web" }),
261
).toBe("acme/Web App");
262
expect(definition.issueScope?.({ provider: kind, displayName: "web" })).toBeNull();
263
+ // One segment before `_git` is a different thing on each kind of host, so it is not placed.
264
+ expect(definition.issueScope?.({ provider: kind, displayName: "acme/_git/web" })).toBeNull();
265
+ // A legacy host keeps the organization in its name, and so does its work item URL.
266
+ expect(
267
+ definition.parseIssueUrl?.(
268
+ new URL("https://acme.visualstudio.com/Web%20App/_workitems/edit/9"),
269
+ ),
270
+ ).toEqual({ host: "acme.visualstudio.com", scope: "web app", key: "9" });
271
+ expect(
272
+ definition.parseIssueUrl?.(new URL("https://dev.azure.com/acme/_workitems/edit/9")),
273
+ ).toBeNull();
274
});
275
});
packages/source-control-azure-devops/src/shared/definition.ts
+12
-6
@@ -17,6 +17,8 @@ const CHANGE_REQUEST_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:
17
const COMMIT_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu;
18
// Work items belong to the project: /{organization}/{project}/_workitems/edit/{id}.
19
const WORK_ITEM_PATH = /^\/([^/]+\/[^/]+)\/_workitems\/edit\/(\d+)(?:\/|$)/u;
20
+// A legacy organization is its hostname: https://{organization}.visualstudio.com/{project}/...
21
+const LEGACY_WORK_ITEM_PATH = /^\/([^/]+)\/_workitems\/edit\/(\d+)(?:\/|$)/u;
22
const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i;
23
const CHANGE_REQUEST_REFERENCE =
24
/^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/(?:DefaultCollection\/)?[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i;
@@ -122,7 +124,11 @@ export const definition = defineSourceControl({
124
},
125
// A project named with spaces arrives percent-encoded; the binding it is matched against is not.
126
parseIssueUrl: (url) => {
125
- const link = parseIssuePath(url, WORK_ITEM_PATH);
127
+ const link =
128
+ parseIssuePath(url, WORK_ITEM_PATH) ??
129
+ (url.hostname.toLowerCase().endsWith(".visualstudio.com")
130
+ ? parseIssuePath(url, LEGACY_WORK_ITEM_PATH)
131
+ : null);
132
return link === null
133
? null
134
: { ...link, scope: link.scope.split("/").map(decodeUrlPathSegment).join("/").toLowerCase() };
@@ -164,13 +170,13 @@ export const definition = defineSourceControl({
170
return name ? decodeUrlPathSegment(name) : null;
171
},
172
// Work items belong to the project: `organization/project` out of the remote's
167
- // `organization/project/_git/repository`.
173
+ // `organization/project/_git/repository`. A shorter path is not placed: `acme/_git/web` is a
174
+ // project named after its repository on dev.azure.com and a bare project on a legacy host, and
175
+ // nothing here says which host the remote is on.
176
issueScope: (identity) => {
177
const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "");
170
- const [organization, project] = segments.indexOf("_git") === 2 ? segments : [];
171
- return organization && project
172
- ? `${decodeUrlPathSegment(organization)}/${decodeUrlPathSegment(project)}`
173
- : null;
178
+ const at = segments.indexOf("_git");
179
+ return at === 2 ? segments.slice(0, at).map(decodeUrlPathSegment).join("/") : null;
180
},
181
repositoryKeyFromRemote,
182
canonicalRepositoryKey,
packages/source-control-core/src/server/IssueTracker.ts
+6
@@ -12,6 +12,7 @@ import type {
12
IssueCreateResult,
13
IssueEvent,
14
IssueInvolvement,
15
+ IssueListSort,
16
IssueLinkedPullRequest,
17
IssueListState,
18
IssueReaction,
@@ -107,6 +108,11 @@ export interface IssueTrackerApi {
108
readonly limit: number;
109
/** Free text as the tracker understands it; ignored by a tracker without `search`. */
110
readonly query?: string | undefined;
111
+ /** Label names an issue must carry, every one of them. */
112
+ readonly labels?: ReadonlyArray<string> | undefined;
113
+ /** The `login` of an assignee, as this tracker's own issues name them. */
114
+ readonly assignee?: string | undefined;
115
+ readonly sort: IssueListSort;
116
/** A cursor this tracker handed back from an earlier page. Absent asks for the first. */
117
readonly cursor?: string | undefined;
118
},
packages/source-control-forgejo/src/server/ForgejoIssueTracker.test.ts
+125
-3
@@ -37,6 +37,26 @@ function answer(path: string): { readonly stdout: string; readonly stderr?: stri
37
case "repos/acme/web/issues/42":
38
return { stdout: encode(ISSUE) };
39
case "repos/acme/web/issues/42/timeline":
40
+ // A second page, as an issue with a long history has: a reference from another repository.
41
+ if (path.endsWith("page=2")) {
42
+ return {
43
+ stdout: encode([
44
+ {
45
+ id: 5,
46
+ type: "pull_ref",
47
+ user: { login: "theo" },
48
+ created_at: "2026-07-02T03:00:00Z",
49
+ ref_issue: {
50
+ number: 50,
51
+ html_url: "https://forgejo.test:3000/acme/api/pulls/50",
52
+ repository: { full_name: "acme/api" },
53
+ pull_request: { merged: true },
54
+ },
55
+ },
56
+ ]),
57
+ };
58
+ }
59
+ if (!path.endsWith("page=1")) return { stdout: "[]" };
60
return {
61
stdout: encode([
62
{
@@ -81,8 +101,6 @@ function answer(path: string): { readonly stdout: string; readonly stderr?: stri
101
html_url: "https://forgejo.test:3000/acme/web/issues/42#issuecomment-7",
102
},
103
]),
84
- stderr:
85
- 'HTTP/1.1 200\nlink: <https://forgejo.test:3000/api/v1/repos/acme/web/issues/42/comments?page=2>; rel="next"\n',
104
};
105
case "repos/acme/web/issues/comments/7/reactions":
106
return {
@@ -91,6 +109,16 @@ function answer(path: string): { readonly stdout: string; readonly stderr?: stri
109
{ content: "+1", user: { login: "theo" } },
110
]),
111
};
112
+ case "repos/acme/api/pulls/50":
113
+ return {
114
+ stdout: encode({
115
+ number: 50,
116
+ title: "fix(api): accept the pasted payload",
117
+ html_url: "https://forgejo.test:3000/acme/api/pulls/50",
118
+ state: "closed",
119
+ merged: true,
120
+ }),
121
+ };
122
case "repos/acme/web/pulls/50":
123
return {
124
stdout: encode({
@@ -160,7 +188,8 @@ describe("ForgejoIssueTracker", () => {
188
assignees: false,
189
},
190
reactions: [{ content: "eyes", count: 1, actors: ["theo"], viewerHasReacted: false }],
163
- commentsCursor: "2",
191
+ // `/comments` answered with everything it has, so nothing is left to page.
192
+ commentsCursor: null,
193
});
194
expect(issue.comments).toEqual([
195
{
@@ -176,7 +205,9 @@ describe("ForgejoIssueTracker", () => {
205
expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
206
["labeled", "bug"],
207
["referenced", "#50"],
208
+ ["referenced", "#50"],
209
]);
210
+ // The same number in another repository is its own pull request, read from there.
211
expect(issue.linkedPullRequests).toEqual([
212
{
213
repository: "acme/web",
@@ -187,10 +218,68 @@ describe("ForgejoIssueTracker", () => {
218
isDraft: true,
219
closesIssue: false,
220
},
221
+ {
222
+ repository: "acme/api",
223
+ number: 50,
224
+ title: "fix(api): accept the pasted payload",
225
+ url: "https://forgejo.test:3000/acme/api/pulls/50",
226
+ state: "merged",
227
+ isDraft: false,
228
+ closesIssue: false,
229
+ },
230
]);
231
}),
232
);
233
234
+ it.effect("cuts the unpaged comments into pages and resolves labels past the first page", () =>
235
+ Effect.gen(function* () {
236
+ const calls: Array<readonly [string, string, unknown]> = [];
237
+ const api = yield* tracker((input) => {
238
+ calls.push([input.method ?? "GET", input.path, input.body]);
239
+ const [route] = input.path.split("?");
240
+ if (route === "user") return { stdout: encode({ login: "julius" }) };
241
+ if (route === "repos/acme/web/issues/42/comments") {
242
+ return {
243
+ stdout: encode(
244
+ Array.from({ length: 51 }, (_, index) => ({
245
+ id: index + 1,
246
+ body: `Comment ${index + 1}`,
247
+ user: { login: "theo" },
248
+ created_at: "2026-07-02T00:00:00Z",
249
+ html_url: "",
250
+ })),
251
+ ),
252
+ };
253
+ }
254
+ if (route === "repos/acme/web/labels") {
255
+ return input.path.endsWith("page=1")
256
+ ? {
257
+ stdout: encode([{ id: 3, name: "bug" }]),
258
+ stderr: 'link: <https://forgejo.test:3000/api/v1/x?page=2>; rel="next"\n',
259
+ }
260
+ : { stdout: encode([{ id: 9, name: "urgent" }]), stderr: "link: \n" };
261
+ }
262
+ return { stdout: "[]" };
263
+ });
264
+ const target = { cwd: "/w", host: "forgejo.test:3000", scope: "acme/web", key: "42" };
265
+ const page = yield* api.getComments({ ...target, cursor: "2" });
266
+ expect(page.comments.map((comment) => comment.id)).toEqual(["51"]);
267
+ expect(page.nextCursor).toBeNull();
268
+ expect(calls[1]?.[1]).toBe("repos/acme/web/issues/42/comments");
269
+
270
+ calls.length = 0;
271
+ yield* api.update!({ ...target, labels: ["bug", "urgent"] });
272
+ expect(calls.at(-1)).toEqual(["PUT", "repos/acme/web/issues/42/labels", { labels: [3, 9] }]);
273
+ // A name the repository lacks refuses the save before anything is written.
274
+ calls.length = 0;
275
+ const error = yield* Effect.flip(
276
+ api.update!({ ...target, title: "Renamed", labels: ["bug", "missing"] }),
277
+ );
278
+ expect(error.reason).toBe("failed");
279
+ expect(calls.map(([method]) => method)).toEqual(["GET", "GET"]);
280
+ }),
281
+ );
282
+
283
it.effect("lists issues by page and leaves pull requests out of the rows", () =>
284
Effect.gen(function* () {
285
const paths: string[] = [];
@@ -207,11 +296,44 @@ describe("ForgejoIssueTracker", () => {
296
state: "open",
297
involvement: "authored",
298
viewer: "julius",
299
+ sort: "updated",
300
limit: 50,
301
cursor: "2",
302
});
303
+ // Forgejo matches any of the labels it is sent, so a row missing one is dropped here.
304
+ const filtered = yield* api.listIssues({
305
+ cwd: "/w",
306
+ host: "forgejo.test:3000",
307
+ scope: "acme/web",
308
+ state: "open",
309
+ involvement: "all",
310
+ viewer: "julius",
311
+ labels: ["bug", "p1"],
312
+ assignee: "theo",
313
+ sort: "created",
314
+ limit: 50,
315
+ });
316
+ expect(filtered.items).toEqual([]);
317
+ // One `assigned_by` cannot name two people: "assigned to me" is kept by dropping rows here.
318
+ const mine = {
319
+ cwd: "/w",
320
+ host: "forgejo.test:3000",
321
+ scope: "acme/web",
322
+ state: "open",
323
+ involvement: "assigned",
324
+ assignee: "theo",
325
+ sort: "created",
326
+ limit: 50,
327
+ } as const;
328
+ expect((yield* api.listIssues({ ...mine, viewer: "julius" })).items).toEqual([]);
329
+ expect(
330
+ (yield* api.listIssues({ ...mine, viewer: "Theo" })).items.map((item) => item.key),
331
+ ).toEqual(["42"]);
332
expect(paths).toEqual([
333
"repos/acme/web/issues?type=issues&state=open&sort=recentupdate&created_by=julius&limit=50&page=2",
334
+ "repos/acme/web/issues?type=issues&state=open&sort=latest&labels=bug%2Cp1&assigned_by=theo&limit=50&page=1",
335
+ "repos/acme/web/issues?type=issues&state=open&sort=latest&assigned_by=theo&limit=50&page=1",
336
+ "repos/acme/web/issues?type=issues&state=open&sort=latest&assigned_by=theo&limit=50&page=1",
337
]);
338
expect(page.items.map((item) => item.key)).toEqual(["42"]);
339
// No `Link` header at all means the server may still have more; a full page carries on.
packages/source-control-forgejo/src/server/ForgejoIssueTracker.ts
+112
-57
@@ -62,8 +62,8 @@ const CAPABILITIES: IssueCapabilities = {
62
63
/** Forgejo's own ceiling on a page, which a self-hosted server may lower. */
64
const PAGE_SIZE = 50;
65
-/** Comment reactions are a request each, so only the first page's are read with the detail. */
66
-const COMMENT_REACTION_LIMIT = 50;
65
+/** How many pages of a listing with no cursor of its own are read before giving up on the rest. */
66
+const MAX_PAGES = 10;
67
68
const repoPath = (scope: string) => `repos/${scope.split("/").map(encodeURIComponent).join("/")}`;
69
const issuePath = (scope: string, number: number) => `${repoPath(scope)}/issues/${number}`;
@@ -245,6 +245,52 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
245
),
246
);
247
248
+ /** Every page of a listing the caller gets no cursor for, up to `MAX_PAGES`. */
249
+ const readEveryPage = Effect.fn("ForgejoIssueTracker.readEveryPage")(function* <A>(
250
+ target: Target,
251
+ operation: string,
252
+ path: string,
253
+ schema: Schema.Codec<A, unknown, never, never>,
254
+ ) {
255
+ const rows: A[] = [];
256
+ for (let page = 1; page <= MAX_PAGES; page++) {
257
+ const next = yield* readPage(target, operation, path, page, schema);
258
+ rows.push(...next.rows);
259
+ if (next.nextCursor === null) break;
260
+ }
261
+ return rows;
262
+ });
263
+
264
+ /**
265
+ * Labels are written by id, so names are resolved against the repository's own, page by page
266
+ * until each is found. A name the repository lacks refuses the write rather than dropping it.
267
+ */
268
+ const labelIds = Effect.fn("ForgejoIssueTracker.labelIds")(function* (
269
+ target: Target,
270
+ operation: string,
271
+ names: ReadonlyArray<string>,
272
+ ) {
273
+ const ids = new Map<string, number>();
274
+ for (let page = 1; ids.size < new Set(names).size && page <= MAX_PAGES; page++) {
275
+ const next = yield* readPage(
276
+ target,
277
+ operation,
278
+ `${repoPath(target.scope)}/labels`,
279
+ page,
280
+ ForgejoLabel,
281
+ );
282
+ for (const label of next.rows) {
283
+ if (names.includes(label.name)) ids.set(label.name, label.id);
284
+ }
285
+ if (next.nextCursor === null) break;
286
+ }
287
+ if (names.some((name) => !ids.has(name))) {
288
+ return yield* refused(operation, "Forgejo found no label by one of the names given.");
289
+ }
290
+ return [...ids.values()];
291
+ });
292
+
293
+ /** `/comments` takes no page and answers with every comment, so the pages are cut here. */
294
const commentsPage = (
295
target: Target,
296
operation: string,
@@ -252,10 +298,11 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
298
page: number,
299
viewer: string,
300
) =>
255
- readPage(target, operation, `${path}/comments`, page, ForgejoComment).pipe(
256
- Effect.flatMap(({ rows, nextCursor }) =>
257
- Effect.forEach(
258
- rows.slice(0, COMMENT_REACTION_LIMIT),
301
+ readArray(target, operation, `${path}/comments`, ForgejoComment).pipe(
302
+ Effect.flatMap((rows) => {
303
+ const end = page * PAGE_SIZE;
304
+ return Effect.forEach(
305
+ rows.slice(end - PAGE_SIZE, end),
306
(comment) =>
307
readArray(
308
target,
@@ -269,8 +316,13 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
316
})),
317
),
318
{ concurrency: 4 },
272
- ).pipe(Effect.map((comments) => ({ comments, nextCursor }))),
273
- ),
319
+ ).pipe(
320
+ Effect.map((comments) => ({
321
+ comments,
322
+ nextCursor: rows.length > end ? String(page + 1) : null,
323
+ })),
324
+ );
325
+ }),
326
);
327
328
/** Pull requests the timeline shows citing this issue, each read once for its state. */
@@ -278,22 +330,26 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
330
target: Target,
331
timeline: ReadonlyArray<typeof ForgejoTimelineEntry.Type>,
332
): Effect.Effect<ReadonlyArray<IssueLinkedPullRequest>, IssueTrackerError> => {
281
- const numbers = [
282
- ...new Set(
283
- timeline.flatMap((entry) =>
284
- entry.type === "pull_ref" && entry.ref_issue?.pull_request
285
- ? [entry.ref_issue.number]
286
- : [],
287
- ),
288
- ),
289
- ];
333
+ // A reference may come from another repository, which is where that pull request is read.
334
+ const cited = new Map<string, { readonly repository: string; readonly number: number }>();
335
+ for (const entry of timeline) {
336
+ if (entry.type !== "pull_ref" || !entry.ref_issue?.pull_request) continue;
337
+ const named = entry.ref_issue.repository?.full_name;
338
+ // The scope may carry the server's mount path in front of the same repository.
339
+ const repository =
340
+ named === undefined || target.scope.endsWith(`/${named}`) ? target.scope : named;
341
+ cited.set(`${repository}#${entry.ref_issue.number}`, {
342
+ repository,
343
+ number: entry.ref_issue.number,
344
+ });
345
+ }
346
return Effect.forEach(
291
- numbers,
292
- (number) =>
347
+ cited.values(),
348
+ ({ repository, number }) =>
349
read(
350
target,
351
"getIssue",
296
- { path: `${repoPath(target.scope)}/pulls/${number}` },
352
+ { path: `${repoPath(repository)}/pulls/${number}` },
353
Schema.Struct({
354
number: Schema.Int,
355
title: Schema.String,
@@ -305,7 +361,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
361
).pipe(
362
Effect.map((pull) => [
363
{
308
- repository: target.scope,
364
+ repository,
365
number: pull.number,
366
title: pull.title,
367
url: pull.html_url,
@@ -342,8 +398,10 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
398
const params = new URLSearchParams({
399
type: "issues",
400
state: input.state,
345
- sort: "recentupdate",
401
+ sort: input.sort === "created" ? "latest" : "recentupdate",
402
});
403
+ const labels = input.labels ?? [];
404
+ if (labels.length > 0) params.set("labels", labels.join(","));
405
const text = input.query?.trim() ?? "";
406
if (text.length > 0) params.set("q", text);
407
const involvement =
@@ -355,6 +413,12 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
413
? "mentioned_by"
414
: null;
415
if (involvement !== null) params.set(involvement, input.viewer);
416
+ if (input.assignee !== undefined) params.set("assigned_by", input.assignee);
417
+ // `assigned_by` names one person, so "assigned to me" is kept here beside a named assignee.
418
+ const alsoAssignedTo =
419
+ input.involvement === "assigned" && input.assignee !== undefined
420
+ ? input.viewer.toLowerCase()
421
+ : null;
422
const { rows, nextCursor } = yield* readPage(
423
input,
424
"listIssues",
@@ -363,7 +427,15 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
427
ForgejoIssue,
428
);
429
return {
366
- items: rows.flatMap((issue) => (issue.pull_request ? [] : [forgejoIssue(issue)])),
430
+ items: rows
431
+ .flatMap((issue) => (issue.pull_request ? [] : [forgejoIssue(issue)]))
432
+ // Forgejo documents `labels` as matching any of them; every one is what was asked.
433
+ .filter(
434
+ (issue) =>
435
+ labels.every((label) => issue.labels.some((carried) => carried.name === label)) &&
436
+ (alsoAssignedTo === null ||
437
+ issue.assignees.some((actor) => actor.login.toLowerCase() === alsoAssignedTo)),
438
+ ),
439
nextCursor,
440
};
441
}),
@@ -376,7 +448,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
448
getIssue(input, "getIssue", path),
449
getRepository(input, "getIssue"),
450
getViewer(input, "getIssue"),
379
- readPage(input, "getIssue", `${path}/timeline`, 1, ForgejoTimelineEntry),
451
+ readEveryPage(input, "getIssue", `${path}/timeline`, ForgejoTimelineEntry),
452
readArray(input, "getIssue", `${path}/reactions`, ForgejoReaction),
453
],
454
{ concurrency: 3 },
@@ -385,7 +457,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
457
Effect.flatMap(([issue, repository, viewer, timeline, reactions]) =>
458
Effect.all([
459
commentsPage(input, "getIssue", issuePath(input.scope, issue.number), 1, viewer),
388
- linkedPullRequests(input, timeline.rows),
460
+ linkedPullRequests(input, timeline),
461
]).pipe(
462
Effect.map(([conversation, links]) => ({
463
...forgejoIssue(issue),
@@ -395,7 +467,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
467
reactions: forgejoReactions(reactions, viewer),
468
comments: conversation.comments,
469
commentsCursor: conversation.nextCursor,
398
- events: timeline.rows.flatMap((entry) => forgejoIssueEvent(entry) ?? []),
470
+ events: timeline.flatMap((entry) => forgejoIssueEvent(entry) ?? []),
471
linkedPullRequests: links,
472
})),
473
),
@@ -414,13 +486,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
486
},
487
488
create: (input) =>
417
- // Labels are written by id, so the names are resolved against the repository's own first.
418
- readArray(
419
- input,
420
- "create",
421
- `${repoPath(input.scope)}/labels?limit=${PAGE_SIZE}`,
422
- ForgejoLabel,
423
- ).pipe(
489
+ labelIds(input, "create", input.labels).pipe(
490
Effect.flatMap((labels) =>
491
read(
492
input,
@@ -431,9 +497,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
497
body: {
498
title: input.title,
499
body: input.body,
434
- labels: labels.flatMap((label) =>
435
- input.labels.includes(label.name) ? [label.id] : [],
436
- ),
500
+ labels,
501
assignees: input.assignees,
502
},
503
},
@@ -459,8 +523,12 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
523
),
524
525
update: (input) =>
462
- issueTarget("update", input).pipe(
463
- Effect.flatMap(({ path }) =>
526
+ Effect.all([
527
+ issueTarget("update", input),
528
+ // Resolved before anything is written, so an unknown label changes nothing.
529
+ input.labels === undefined ? Effect.void : labelIds(input, "update", input.labels),
530
+ ]).pipe(
531
+ Effect.flatMap(([{ path }, labels]) =>
532
Effect.all([
533
input.title === undefined && input.body === undefined && input.assignees === undefined
534
? Effect.void
@@ -473,26 +541,13 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
541
...(input.assignees === undefined ? {} : { assignees: input.assignees }),
542
},
543
}),
476
- input.labels === undefined
544
+ labels === undefined
545
? Effect.void
478
- : readArray(
479
- input,
480
- "update",
481
- `${repoPath(input.scope)}/labels?limit=${PAGE_SIZE}`,
482
- ForgejoLabel,
483
- ).pipe(
484
- Effect.flatMap((labels) =>
485
- write(input, "update", {
486
- path: `${path}/labels`,
487
- method: "PUT",
488
- body: {
489
- labels: labels.flatMap((label) =>
490
- input.labels!.includes(label.name) ? [label.id] : [],
491
- ),
492
- },
493
- }),
494
- ),
495
- ),
546
+ : write(input, "update", {
547
+ path: `${path}/labels`,
548
+ method: "PUT",
549
+ body: { labels },
550
+ }),
551
]),
552
),
553
Effect.asVoid,
packages/source-control-forgejo/src/server/forgejoIssueJson.ts
+2
@@ -58,6 +58,8 @@ export const ForgejoTimelineEntry = Schema.Struct({
58
Schema.Struct({
59
number: Schema.Int,
60
html_url: Schema.String,
61
+ /** Where the citing issue or pull request lives, which need not be this repository. */
62
+ repository: Schema.optional(Schema.NullOr(Schema.Struct({ full_name: Schema.String }))),
63
pull_request: Schema.optional(Schema.NullOr(Schema.Struct({ merged: Schema.Boolean }))),
64
}),
65
),
packages/source-control-github/src/server/GitHubIssueTracker.test.ts
+44
@@ -269,6 +269,11 @@ describe("GitHubIssueTracker", () => {
269
}
270
if (request.url.endsWith("/issues")) {
271
response = { number: 42, html_url: "https://github.com/acme/web/issues/42" };
272
+ } else if (request.method === "PATCH" && body["title"] === "Dropped") {
273
+ // What GitHub answers a caller without triage access: success, metadata untouched.
274
+ response = { labels: [{ name: "Bug" }], assignees: [] };
275
+ } else if (request.method === "PATCH") {
276
+ response = { labels: [], assignees: [] };
277
}
278
}
279
return Effect.succeed(
@@ -297,6 +302,10 @@ describe("GitHubIssueTracker", () => {
302
});
303
yield* api.comment({ ...target, body: "Comment" });
304
yield* api.update({ ...target, title: "Updated", body: "Edited", labels: [], assignees: [] });
305
+ expect(
306
+ yield* Effect.flip(api.update({ ...target, title: "Dropped", labels: ["bug", "p1"] })),
307
+ ).toMatchObject({ operation: "update", reason: "failed" });
308
+ yield* api.update({ ...target, title: "Dropped", labels: ["bug"], assignees: [] });
309
yield* api.setState({ ...target, state: "closed", closeReason: "not-planned" });
310
// GitHub ignores a new reason on a closed issue, so it is refused instead of sent.
311
expect(
@@ -344,6 +353,16 @@ describe("GitHubIssueTracker", () => {
353
"https://api.github.com/repos/acme/web/issues/42",
354
{ title: "Updated", body: "Edited", labels: [], assignees: [] },
355
],
356
+ [
357
+ "PATCH",
358
+ "https://api.github.com/repos/acme/web/issues/42",
359
+ { title: "Dropped", labels: ["bug", "p1"] },
360
+ ],
361
+ [
362
+ "PATCH",
363
+ "https://api.github.com/repos/acme/web/issues/42",
364
+ { title: "Dropped", labels: ["bug"], assignees: [] },
365
+ ],
366
[
367
"PATCH",
368
"https://api.github.com/repos/acme/web/issues/42",
@@ -356,6 +375,31 @@ describe("GitHubIssueTracker", () => {
375
}),
376
);
377
378
+ it.effect("asks search for the labels, assignee and order a listing names", () =>
379
+ Effect.gen(function* () {
380
+ const seen: unknown[] = [];
381
+ const api = yield* tracker((variables) => seen.push(variables));
382
+ // The canned answer is not a search result; only the query sent matters here.
383
+ yield* api
384
+ .listIssues({
385
+ cwd: "/w",
386
+ host: "github.com",
387
+ scope: "acme/web",
388
+ state: "open",
389
+ involvement: "all",
390
+ viewer: "julius",
391
+ labels: ['needs "repro"'],
392
+ assignee: "theo",
393
+ sort: "created",
394
+ limit: 10,
395
+ })
396
+ .pipe(Effect.exit);
397
+ expect(seen[0]).toMatchObject({
398
+ q: 'is:issue repo:acme/web is:open label:"needs \\"repro\\"" assignee:"theo" sort:created-desc',
399
+ });
400
+ }),
401
+ );
402
+
403
it.effect("offers YAML issue forms when blank issues are disabled", () =>
404
Effect.gen(function* () {
405
const form = {
packages/source-control-github/src/server/GitHubIssueTracker.ts
+49
-20
@@ -5,6 +5,7 @@ import {
5
IssueTrackerKind,
6
type IssueCapabilities,
7
type IssueInvolvement,
8
+ type IssueListSort,
9
} from "@t3tools/contracts";
10
import {
11
IssueTrackerError,
@@ -20,6 +21,7 @@ import { AddReaction, RemoveReaction } from "./pullRequestMutations.graphql.ts";
21
import { gitHubReactionContent } from "./gitHubPullRequestJson.ts";
22
import {
23
decodeCreatedIssueJson,
24
+ decodeIssueMetadataJson,
25
toIssueCandidates,
26
toIssueComments,
27
toIssueDetail,
@@ -48,11 +50,16 @@ const CAPABILITIES: IssueCapabilities = {
50
51
const REPOSITORY = /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+$/;
52
53
+/** Quoted, so no character in it can start a qualifier of its own. */
54
+function quotedTerm(value: string): string {
55
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
56
+}
57
+
58
function searchTerms(query: string): ReadonlyArray<string> {
59
return query
60
.split(/\s+/)
61
.filter((word) => word.length > 0)
55
- .map((word) => `"${word.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`);
62
+ .map(quotedTerm);
63
}
64
65
const INVOLVEMENT_QUALIFIER: Record<IssueInvolvement, string | null> = {
@@ -68,6 +75,9 @@ function searchQuery(input: {
75
readonly involvement: IssueInvolvement;
76
readonly viewer: string;
77
readonly query?: string | undefined;
78
+ readonly labels?: ReadonlyArray<string> | undefined;
79
+ readonly assignee?: string | undefined;
80
+ readonly sort: IssueListSort;
81
}): string {
82
const qualifier = INVOLVEMENT_QUALIFIER[input.involvement];
83
return [
@@ -75,7 +85,9 @@ function searchQuery(input: {
85
`repo:${input.scope.trim()}`,
86
...(input.state === "all" ? [] : [`is:${input.state}`]),
87
...(qualifier === null ? [] : [`${qualifier}:${input.viewer}`]),
78
- "sort:updated-desc",
88
+ ...(input.labels ?? []).map((label) => `label:${quotedTerm(label)}`),
89
+ ...(input.assignee === undefined ? [] : [`assignee:${quotedTerm(input.assignee)}`]),
90
+ `sort:${input.sort}-desc`,
91
...searchTerms(input.query ?? ""),
92
].join(" ");
93
}
@@ -187,18 +199,13 @@ export const make = Effect.gen(function* () {
199
return { ...target, id: found.id, state: found.state, stateReason: found.stateReason };
200
});
201
190
- const patchIssue = (
191
- input: { readonly host: string; readonly scope: string; readonly key: string },
192
- operation: string,
193
- body: Record<string, unknown>,
194
- ) =>
195
- verifiedIssue(input, operation).pipe(
196
- Effect.flatMap(({ path }) =>
197
- api
198
- .rest({ host: input.host, operation, method: "PATCH", path, body })
199
- .pipe(Effect.asVoid, Effect.mapError(fail(operation))),
200
- ),
202
+ // As sets: GitHub applies a name asked for twice once.
203
+ const sameNames = (wanted: ReadonlyArray<string>, applied: ReadonlyArray<string>) => {
204
+ const names = new Set(wanted.map((name) => name.trim().toLowerCase()));
205
+ return (
206
+ names.size === new Set(applied).size && [...names].every((name) => applied.includes(name))
207
);
208
+ };
209
210
return {
211
kind: KIND,
@@ -351,13 +358,35 @@ export const make = Effect.gen(function* () {
358
),
359
),
360
354
- update: (input) =>
355
- patchIssue(input, "update", {
356
- ...(input.title === undefined ? {} : { title: input.title }),
357
- ...(input.body === undefined ? {} : { body: input.body }),
358
- ...(input.labels === undefined ? {} : { labels: input.labels }),
359
- ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
360
- }),
361
+ update: Effect.fn("GitHubIssueTracker.update")(function* (input) {
362
+ const { path } = yield* verifiedIssue(input, "update");
363
+ const response = yield* api
364
+ .rest({
365
+ host: input.host,
366
+ operation: "update",
367
+ method: "PATCH",
368
+ path,
369
+ body: {
370
+ ...(input.title === undefined ? {} : { title: input.title }),
371
+ ...(input.body === undefined ? {} : { body: input.body }),
372
+ ...(input.labels === undefined ? {} : { labels: input.labels }),
373
+ ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
374
+ },
375
+ })
376
+ .pipe(Effect.mapError(fail("update")));
377
+ // Without triage access GitHub drops labels and assignees and still answers with success.
378
+ const applied = decodeIssueMetadataJson(response.body);
379
+ if (
380
+ Result.isSuccess(applied) &&
381
+ ((input.labels !== undefined && !sameNames(input.labels, applied.success.labels)) ||
382
+ (input.assignees !== undefined && !sameNames(input.assignees, applied.success.assignees)))
383
+ ) {
384
+ return yield* invalid(
385
+ "update",
386
+ "GitHub did not apply the labels or assignees. Changing them needs triage access to the repository.",
387
+ );
388
+ }
389
+ }),
390
391
setState: Effect.fn("GitHubIssueTracker.setState")(function* (input) {
392
const { path, state, stateReason } = yield* verifiedIssue(input, "setState");
packages/source-control-github/src/server/gitHubIssueJson.ts
+17
@@ -342,6 +342,23 @@ const decodeCreatedIssue = decodeJsonResult(
342
Schema.Struct({ number: Schema.Int, html_url: TrimmedNonEmptyString }),
343
);
344
345
+const decodeIssueMetadata = decodeJsonResult(
346
+ Schema.Struct({
347
+ labels: Schema.Array(Schema.Union([Schema.String, Schema.Struct({ name: Schema.String })])),
348
+ assignees: Schema.Array(Schema.Struct({ login: Schema.String })),
349
+ }),
350
+);
351
+
352
+/** The labels and assignees a REST issue answer reports, lower case for comparison. */
353
+export function decodeIssueMetadataJson(raw: string) {
354
+ return Result.map(decodeIssueMetadata(raw), (issue) => ({
355
+ labels: issue.labels.map((label) =>
356
+ (typeof label === "string" ? label : label.name).trim().toLowerCase(),
357
+ ),
358
+ assignees: issue.assignees.map((assignee) => assignee.login.trim().toLowerCase()),
359
+ }));
360
+}
361
+
362
export function decodeCreatedIssueJson(raw: string) {
363
return Result.map(decodeCreatedIssue(raw), (issue) => ({
364
number: issue.number,
packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts
+91
-8
@@ -121,11 +121,17 @@ function answer(path: string): string {
121
throw new Error(`unexpected path ${path}`);
122
}
123
124
-function tracker(onExecute: (args: ReadonlyArray<string>) => string) {
124
+function tracker(
125
+ onExecute: (
126
+ args: ReadonlyArray<string>,
127
+ input: { readonly host?: string | undefined; readonly stdin?: string },
128
+ ) => string,
129
+) {
130
return GitLabIssueTracker.make.pipe(
131
Effect.provide(
132
Layer.mock(GitLabCli.GitLabCli)({
128
- execute: ({ args }) => Effect.succeed(TestSourceControlHost.processOutput(onExecute(args))),
133
+ execute: (input) =>
134
+ Effect.succeed(TestSourceControlHost.processOutput(onExecute(input.args, input))),
135
}),
136
),
137
);
@@ -134,13 +140,21 @@ function tracker(onExecute: (args: ReadonlyArray<string>) => string) {
140
describe("GitLabIssueTracker", () => {
141
it.effect("joins the detail's endpoints into the neutral issue shape", () =>
142
Effect.gen(function* () {
137
- const api = yield* tracker((args) => answer(args[1]!));
138
- const issue = yield* api.getIssue({
139
- cwd: "/w",
140
- host: "gitlab.com",
141
- scope: "acme/web",
142
- key: "42",
143
+ const hosts = new Set<string | undefined>();
144
+ const awardCursors: unknown[] = [];
145
+ const api = yield* tracker((args, input) => {
146
+ hosts.add(input.host);
147
+ if (args[1] === "graphql") awardCursors.push(JSON.parse(input.stdin!).variables.cursor);
148
+ return answer(args[1]!);
149
});
150
+ const target = { cwd: "/w", host: "gitlab.example.com", scope: "acme/web", key: "42" };
151
+ const issue = yield* api.getIssue(target);
152
+ // A later page of comments carries its own awards, found by the cursor's second half.
153
+ const later = yield* api.getComments({ ...target, cursor: "2:after-100" });
154
+ expect(later.comments.map((comment) => comment.reactions?.[0]?.count)).toEqual([2]);
155
+ expect(awardCursors).toEqual([null, "after-100"]);
156
+ // Every request names the tracker's own host rather than leaving glab to pick one.
157
+ expect([...hosts]).toEqual(["gitlab.example.com"]);
158
expect(issue).toMatchObject({
159
key: "42",
160
displayKey: "#42",
@@ -193,17 +207,86 @@ describe("GitLabIssueTracker", () => {
207
state: "open",
208
involvement: "assigned",
209
viewer: "julius",
210
+ sort: "updated",
211
limit: 1,
212
cursor: "3",
213
});
214
expect(paths[0]).toBe(
215
"projects/acme%2Fweb/issues?state=opened&assignee_username=julius&order_by=updated_at&sort=desc&per_page=1&page=3",
216
);
217
+ // A named assignee takes the one parameter GitLab reads, so "assigned to me" drops rows here.
218
+ const both = yield* api.listIssues({
219
+ cwd: "/w",
220
+ host: "gitlab.com",
221
+ scope: "acme/web",
222
+ state: "open",
223
+ involvement: "assigned",
224
+ viewer: "julius",
225
+ labels: ["bug", "needs triage"],
226
+ assignee: "theo",
227
+ sort: "created",
228
+ limit: 1,
229
+ });
230
+ expect(paths[1]).toBe(
231
+ "projects/acme%2Fweb/issues?state=opened&labels=bug%2Cneeds%20triage&assignee_username=theo&order_by=created_at&sort=desc&per_page=1&page=1",
232
+ );
233
+ expect(both.items).toEqual([]);
234
expect(page.items[0]?.key).toBe("42");
235
expect(page.nextCursor).toBe("4");
236
}),
237
);
238
239
+ it.effect("removes the viewer's own award by id, paging until it is found", () =>
240
+ Effect.gen(function* () {
241
+ const calls: string[] = [];
242
+ const api = yield* tracker((args) => {
243
+ const path = args[1]!;
244
+ calls.push(args.includes("DELETE") ? `DELETE ${path}` : path);
245
+ if (path === "user") return encode({ username: "julius" });
246
+ if (path.endsWith("page=1")) {
247
+ return encode([{ id: 1, name: "thumbsup", user: { username: "theo" } }]);
248
+ }
249
+ if (path.endsWith("page=2") && path.includes("/notes/7/")) {
250
+ return encode([{ id: 9, name: "thumbsup", user: { username: "julius" } }]);
251
+ }
252
+ return "[]";
253
+ });
254
+ const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
255
+ yield* api.setReaction!({ ...target, subjectId: "7", content: "thumbs-up", reacted: false });
256
+ expect(calls.at(-1)).toBe("DELETE projects/acme%2Fweb/issues/42/notes/7/award_emoji/9");
257
+ // Nothing to delete is success, with no DELETE sent.
258
+ calls.length = 0;
259
+ yield* api.setReaction!({ ...target, content: "thumbs-up", reacted: false });
260
+ expect(calls).toEqual([
261
+ "user",
262
+ "projects/acme%2Fweb/issues/42/award_emoji?per_page=100&page=1",
263
+ "projects/acme%2Fweb/issues/42/award_emoji?per_page=100&page=2",
264
+ ]);
265
+ }),
266
+ );
267
+
268
+ it.effect("writes a kept assignee by the id its username resolves to", () =>
269
+ Effect.gen(function* () {
270
+ const calls: string[] = [];
271
+ const bodies: string[] = [];
272
+ const api = yield* tracker((args, input) => {
273
+ const path = args[1]!;
274
+ calls.push(path);
275
+ if (input.stdin !== undefined) bodies.push(input.stdin);
276
+ if (path === "users?username=theo") return encode([{ id: 2, username: "theo" }]);
277
+ if (path.startsWith("users?username=")) return "[]";
278
+ return "{}";
279
+ });
280
+ const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
281
+ // The issue's own assignee comes back by login; a newly picked one by id.
282
+ yield* api.update!({ ...target, assignees: ["theo", "7"] });
283
+ expect(calls).toEqual(["users?username=theo", "projects/acme%2Fweb/issues/42"]);
284
+ expect(JSON.parse(bodies.at(-1)!)).toEqual({ assignee_ids: [2, 7] });
285
+ const error = yield* Effect.flip(api.update!({ ...target, assignees: ["nobody"] }));
286
+ expect(error.reason).toBe("failed");
287
+ }),
288
+ );
289
+
290
it.effect("refuses a key that names no GitLab issue without a request", () =>
291
Effect.gen(function* () {
292
let requests = 0;
packages/source-control-gitlab/src/server/GitLabIssueTracker.ts
+203
-73
@@ -20,6 +20,7 @@ import {
20
import * as GitLabCli from "./GitLabCli.ts";
21
import {
22
decodeCreatedIssueJson,
23
+ decodeUserIdsJson,
24
decodeIssueDetailJson,
25
decodeIssueListJson,
26
decodeIssueNotesJson,
@@ -96,6 +97,22 @@ function parsePage(cursor: string | undefined): number | null {
97
return /^[1-9]\d{0,6}$/.test(cursor) ? Number(cursor) : null;
98
}
99
100
+/**
101
+ * A comments cursor: the next REST page of notes and, after a colon, where GraphQL's awards for
102
+ * that page start. The two page alike, so a page of comments is joined with its own awards.
103
+ */
104
+function parseCommentsCursor(
105
+ cursor: string,
106
+): { readonly page: number; readonly awards: string | null } | null {
107
+ const match = /^([1-9]\d{0,6})(?::(.{1,512}))?$/.exec(cursor);
108
+ return match === null ? null : { page: Number(match[1]), awards: match[2] ?? null };
109
+}
110
+
111
+function commentsCursor(notesNext: string | null, awardsNext: string | null): string | null {
112
+ if (notesNext === null) return null;
113
+ return awardsNext === null ? notesNext : `${notesNext}:${awardsNext}`;
114
+}
115
+
116
function query(params: ReadonlyArray<readonly [string, string]>): string {
117
return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
118
}
@@ -103,12 +120,15 @@ function query(params: ReadonlyArray<readonly [string, string]>): string {
120
function involvementParams(input: {
121
readonly involvement: IssueInvolvement;
122
readonly viewer: string;
123
+ readonly assignee?: string | undefined;
124
}): ReadonlyArray<readonly [string, string]> {
125
switch (input.involvement) {
126
case "authored":
127
return [["author_username", input.viewer]];
128
case "assigned":
111
- return [["assignee_username", input.viewer]];
129
+ // A named assignee takes the one assignee parameter GitLab reads; `listIssues` keeps the
130
+ // viewer by dropping rows.
131
+ return input.assignee === undefined ? [["assignee_username", input.viewer]] : [];
132
// GitLab's `my_reaction_emoji` and `iteration` filters aside, nothing narrows to mentions, so
133
// the listing stays as wide as `all` rather than guessing.
134
case "mentioned":
@@ -165,6 +185,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
185
186
const api = (input: {
187
readonly cwd: string;
188
+ readonly host: string;
189
readonly operation: string;
190
readonly path: string;
191
readonly method?: string;
@@ -173,6 +194,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
194
gitlab
195
.execute({
196
cwd: input.cwd,
197
+ host: input.host,
198
args: [
199
"api",
200
input.path,
@@ -192,6 +214,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
214
215
const read = <A>(input: {
216
readonly cwd: string;
217
+ readonly host: string;
218
readonly operation: string;
219
readonly path: string;
220
readonly method?: string;
@@ -209,6 +232,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
232
233
const write = (input: {
234
readonly cwd: string;
235
+ readonly host: string;
236
readonly operation: string;
237
readonly path: string;
238
readonly method: string;
@@ -218,10 +242,12 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
242
/** The signed-in account; an answer naming nobody is a failure, since every comparison needs a login. */
243
const viewer = (input: {
244
readonly cwd: string;
245
+ readonly host: string;
246
readonly operation: string;
247
}): Effect.Effect<string, IssueTrackerError> =>
248
read({
249
cwd: input.cwd,
250
+ host: input.host,
251
operation: input.operation,
252
path: "user",
253
decode: decodeViewerJson,
@@ -243,16 +269,32 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
269
: Effect.succeed({ number, path: `projects/${projectPath(input.scope)}/issues/${number}` });
270
};
271
246
- /** GitLab names assignees by numeric id, which is what the candidates carry as `id`. */
272
+ /**
273
+ * GitLab writes assignees by numeric id, which is what the candidates carry as `id`. An issue
274
+ * names the people it already has by username, so a kept assignee is looked up.
275
+ */
276
const assigneeIds = (
277
+ input: { readonly cwd: string; readonly host: string },
278
operation: string,
279
assignees: ReadonlyArray<string>,
250
- ): Effect.Effect<ReadonlyArray<number>, IssueTrackerError> => {
251
- const ids = assignees.map((id) => (/^[1-9]\d*$/.test(id) ? Number(id) : null));
252
- return ids.every((id) => id !== null)
253
- ? Effect.succeed(ids)
254
- : Effect.fail(refused(operation, "GitLab assignees are named by their user id."));
255
- };
280
+ ): Effect.Effect<ReadonlyArray<number>, IssueTrackerError> =>
281
+ Effect.forEach(assignees, (assignee) =>
282
+ /^[1-9]\d*$/.test(assignee)
283
+ ? Effect.succeed(Number(assignee))
284
+ : read({
285
+ cwd: input.cwd,
286
+ host: input.host,
287
+ operation,
288
+ path: `users?${query([["username", assignee]])}`,
289
+ decode: decodeUserIdsJson,
290
+ }).pipe(
291
+ Effect.flatMap(([id]) =>
292
+ id === undefined
293
+ ? Effect.fail(refused(operation, `GitLab has no user named ${assignee}.`))
294
+ : Effect.succeed(id),
295
+ ),
296
+ ),
297
+ );
298
299
const paged = (path: string, page: number) =>
300
`${path}?${query([
@@ -262,12 +304,14 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
304
305
const notesPage = (input: {
306
readonly cwd: string;
307
+ readonly host: string;
308
readonly path: string;
309
readonly page: number;
310
readonly operation: string;
311
}) =>
312
read({
313
cwd: input.cwd,
314
+ host: input.host,
315
operation: input.operation,
316
path: `${input.path}/notes?${query([
317
["per_page", String(PAGE_SIZE)],
@@ -285,38 +329,49 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
329
330
const awards = (input: {
331
readonly cwd: string;
332
+ readonly host: string;
333
readonly scope: string;
334
readonly number: number;
335
readonly operation: string;
336
+ readonly cursor?: string | undefined;
337
}) =>
338
read({
339
cwd: input.cwd,
340
+ host: input.host,
341
operation: input.operation,
342
path: "graphql",
343
method: "POST",
344
body: {
345
query: ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
299
- variables: { fullPath: input.scope.trim(), iid: String(input.number) },
346
+ variables: {
347
+ fullPath: input.scope.trim(),
348
+ iid: String(input.number),
349
+ cursor: input.cursor ?? null,
350
+ },
351
},
352
decode: decodeAwardEmojiJson,
353
});
354
355
const linked = (input: {
356
readonly cwd: string;
357
+ readonly host: string;
358
readonly path: string;
359
readonly endpoint: "closed_by" | "related_merge_requests";
360
}) =>
361
read({
362
cwd: input.cwd,
363
+ host: input.host,
364
operation: "getIssue",
365
path: paged(`${input.path}/${input.endpoint}`, 1),
366
decode: (raw) => decodeLinkedMergeRequestsJson(raw, input.endpoint === "closed_by"),
367
});
368
369
const template =
317
- (input: { readonly cwd: string; readonly scope: string }) => (entry: GitLabTemplateEntry) =>
370
+ (input: { readonly cwd: string; readonly host: string; readonly scope: string }) =>
371
+ (entry: GitLabTemplateEntry) =>
372
read({
373
cwd: input.cwd,
374
+ host: input.host,
375
operation: "listTemplates",
376
path: `projects/${projectPath(input.scope)}/templates/issues/${encodeURIComponent(entry.key)}`,
377
decode: (raw) => decodeTemplateJson(entry, raw),
@@ -326,17 +381,22 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
381
kind: KIND,
382
capabilities: CAPABILITIES,
383
329
- getViewer: (input) => viewer({ cwd: input.cwd, operation: "getViewer" }),
384
+ getViewer: (input) => viewer({ cwd: input.cwd, host: input.host, operation: "getViewer" }),
385
331
- listIssues: (input) => {
386
+ listIssues: Effect.fn("GitLabIssueTracker.listIssues")(function* (input) {
387
const page = parsePage(input.cursor);
388
if (page === null) {
334
- return Effect.fail(refused("listIssues", "The cursor was not one GitLab handed out."));
389
+ return yield* refused("listIssues", "The cursor was not one GitLab handed out.");
390
}
391
const perPage = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
392
const text = input.query?.trim() ?? "";
338
- return read({
393
+ const alsoAssignedTo =
394
+ input.involvement === "assigned" && input.assignee !== undefined
395
+ ? input.viewer.toLowerCase()
396
+ : null;
397
+ return yield* read({
398
cwd: input.cwd,
399
+ host: input.host,
400
operation: "listIssues",
401
path: `projects/${projectPath(input.scope)}/issues?${query([
402
["state", input.state === "open" ? "opened" : input.state],
@@ -344,7 +404,13 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
404
// GitLab's own `search` matches title and description, URL-encoded like every other
405
// value here, so no text in it can become a parameter of its own.
406
...(text.length === 0 ? [] : [["search", text] as const]),
347
- ["order_by", "updated_at"],
407
+ ...(input.labels === undefined || input.labels.length === 0
408
+ ? []
409
+ : [["labels", input.labels.join(",")] as const]),
410
+ ...(input.assignee === undefined
411
+ ? []
412
+ : [["assignee_username", input.assignee] as const]),
413
+ ["order_by", input.sort === "created" ? "created_at" : "updated_at"],
414
["sort", "desc"],
415
["per_page", String(perPage)],
416
["page", String(page)],
@@ -352,11 +418,16 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
418
decode: decodeIssueListJson,
419
}).pipe(
420
Effect.map((list) => ({
355
- items: list.items,
421
+ items:
422
+ alsoAssignedTo === null
423
+ ? list.items
424
+ : list.items.filter((issue) =>
425
+ issue.assignees.some((actor) => actor.login.toLowerCase() === alsoAssignedTo),
426
+ ),
427
nextCursor: list.rawCount < perPage ? null : String(page + 1),
428
})),
429
);
359
- },
430
+ }),
431
432
getIssue: (input) =>
433
issuePath(input, "getIssue").pipe(
@@ -365,21 +436,40 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
436
[
437
read({
438
cwd: input.cwd,
439
+ host: input.host,
440
operation: "getIssue",
441
path,
442
decode: decodeIssueDetailJson,
443
}),
372
- viewer({ cwd: input.cwd, operation: "getIssue" }),
373
- notesPage({ cwd: input.cwd, path, page: 1, operation: "getIssue" }),
444
+ viewer({ cwd: input.cwd, host: input.host, operation: "getIssue" }),
445
+ notesPage({
446
+ cwd: input.cwd,
447
+ host: input.host,
448
+ path,
449
+ page: 1,
450
+ operation: "getIssue",
451
+ }),
452
read({
453
cwd: input.cwd,
454
+ host: input.host,
455
operation: "getIssue",
456
path: paged(`${path}/resource_label_events`, 1),
457
decode: decodeLabelEventsJson,
458
}),
380
- linked({ cwd: input.cwd, path, endpoint: "closed_by" }),
381
- linked({ cwd: input.cwd, path, endpoint: "related_merge_requests" }),
382
- awards({ cwd: input.cwd, scope: input.scope, number, operation: "getIssue" }),
459
+ linked({ cwd: input.cwd, host: input.host, path, endpoint: "closed_by" }),
460
+ linked({
461
+ cwd: input.cwd,
462
+ host: input.host,
463
+ path,
464
+ endpoint: "related_merge_requests",
465
+ }),
466
+ awards({
467
+ cwd: input.cwd,
468
+ host: input.host,
469
+ scope: input.scope,
470
+ number,
471
+ operation: "getIssue",
472
+ }),
473
],
474
{ concurrency: 4 },
475
),
@@ -395,7 +485,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
485
...comment,
486
reactions: awardPage.reactionsByNoteId.get(comment.id) ?? [],
487
})),
398
- commentsCursor: notes.nextCursor,
488
+ commentsCursor: commentsCursor(notes.nextCursor, awardPage.nextCursor),
489
events: [...notes.events, ...labelEvents].sort((left, right) =>
490
left.createdAt.localeCompare(right.createdAt),
491
),
@@ -409,22 +499,51 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
499
),
500
501
getComments: (input) => {
412
- const page = parsePage(input.cursor);
413
- return page === null
502
+ const cursor = parseCommentsCursor(input.cursor);
503
+ return cursor === null
504
? Effect.fail(refused("getComments", "The cursor was not one GitLab handed out."))
505
: issuePath(input, "getComments").pipe(
416
- Effect.flatMap(({ path }) =>
417
- notesPage({ cwd: input.cwd, path, page, operation: "getComments" }),
506
+ Effect.flatMap(({ number, path }) =>
507
+ Effect.all(
508
+ [
509
+ notesPage({
510
+ cwd: input.cwd,
511
+ host: input.host,
512
+ path,
513
+ page: cursor.page,
514
+ operation: "getComments",
515
+ }),
516
+ // Without its awards cursor a later page's awards cannot be found.
517
+ cursor.awards === null && cursor.page > 1
518
+ ? Effect.succeed(null)
519
+ : awards({
520
+ cwd: input.cwd,
521
+ host: input.host,
522
+ scope: input.scope,
523
+ number,
524
+ operation: "getComments",
525
+ cursor: cursor.awards ?? undefined,
526
+ }),
527
+ ],
528
+ { concurrency: 2 },
529
+ ),
530
),
419
- Effect.map((notes) => ({ comments: notes.comments, nextCursor: notes.nextCursor })),
531
+ Effect.map(([notes, awardPage]) => ({
532
+ comments: notes.comments.map((comment) => ({
533
+ ...comment,
534
+ reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [],
535
+ })),
536
+ nextCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null),
537
+ })),
538
);
539
},
540
541
create: (input) =>
424
- assigneeIds("create", input.assignees).pipe(
542
+ assigneeIds(input, "create", input.assignees).pipe(
543
Effect.flatMap((assignee_ids) =>
544
read({
545
cwd: input.cwd,
546
+ host: input.host,
547
operation: "create",
548
path: `projects/${projectPath(input.scope)}/issues`,
549
method: "POST",
@@ -449,6 +568,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
568
Effect.flatMap(({ path }) =>
569
write({
570
cwd: input.cwd,
571
+ host: input.host,
572
operation: "comment",
573
path: `${path}/notes`,
574
method: "POST",
@@ -460,11 +580,14 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
580
update: (input) =>
581
Effect.all([
582
issuePath(input, "update"),
463
- input.assignees === undefined ? Effect.void : assigneeIds("update", input.assignees),
583
+ input.assignees === undefined
584
+ ? Effect.void
585
+ : assigneeIds(input, "update", input.assignees),
586
]).pipe(
587
Effect.flatMap(([{ path }, assignee_ids]) =>
588
write({
589
cwd: input.cwd,
590
+ host: input.host,
591
operation: "update",
592
path,
593
method: "PUT",
@@ -483,6 +606,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
606
Effect.flatMap(({ path }) =>
607
write({
608
cwd: input.cwd,
609
+ host: input.host,
610
operation: "setState",
611
path,
612
method: "PUT",
@@ -491,53 +615,57 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
615
),
616
),
617
494
- setReaction: (input) =>
495
- issuePath(input, "setReaction").pipe(
496
- Effect.flatMap(({ path }) => {
497
- if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
498
- return Effect.fail(refused("setReaction", "The comment id names no GitLab note."));
499
- }
500
- const subject =
501
- input.subjectId === undefined
502
- ? `${path}/award_emoji`
503
- : `${path}/notes/${input.subjectId}/award_emoji`;
504
- if (input.reacted) {
505
- return write({
506
- cwd: input.cwd,
507
- operation: "setReaction",
508
- path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
509
- method: "POST",
510
- });
511
- }
512
- // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
513
- // award of that name is looked up first. Nothing to delete is success.
514
- return viewer({ cwd: input.cwd, operation: "setReaction" }).pipe(
515
- Effect.flatMap((login) =>
516
- read({
517
- cwd: input.cwd,
518
- operation: "setReaction",
519
- path: paged(subject, 1),
520
- decode: (raw) =>
521
- decodeOwnAwardIdJson(raw, { content: input.content, viewer: login }),
522
- }),
523
- ),
524
- Effect.flatMap((own) =>
525
- own === null
526
- ? Effect.void
527
- : write({
528
- cwd: input.cwd,
529
- operation: "setReaction",
530
- path: `${subject}/${own}`,
531
- method: "DELETE",
532
- }),
533
- ),
534
- );
535
- }),
536
- ),
618
+ setReaction: Effect.fn("GitLabIssueTracker.setReaction")(function* (input) {
619
+ const { path } = yield* issuePath(input, "setReaction");
620
+ if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
621
+ return yield* refused("setReaction", "The comment id names no GitLab note.");
622
+ }
623
+ const subject =
624
+ input.subjectId === undefined
625
+ ? `${path}/award_emoji`
626
+ : `${path}/notes/${input.subjectId}/award_emoji`;
627
+ if (input.reacted) {
628
+ return yield* write({
629
+ cwd: input.cwd,
630
+ host: input.host,
631
+ operation: "setReaction",
632
+ path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
633
+ method: "POST",
634
+ });
635
+ }
636
+ // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
637
+ // award of that name is looked up first. Nothing to delete is success.
638
+ const login = yield* viewer({
639
+ cwd: input.cwd,
640
+ host: input.host,
641
+ operation: "setReaction",
642
+ });
643
+ for (let page = 1; ; page++) {
644
+ const own = yield* read({
645
+ cwd: input.cwd,
646
+ host: input.host,
647
+ operation: "setReaction",
648
+ path: paged(subject, page),
649
+ decode: (raw) => decodeOwnAwardIdJson(raw, { content: input.content, viewer: login }),
650
+ });
651
+ if (own.id !== null) {
652
+ return yield* write({
653
+ cwd: input.cwd,
654
+ host: input.host,
655
+ operation: "setReaction",
656
+ path: `${subject}/${own.id}`,
657
+ method: "DELETE",
658
+ });
659
+ }
660
+ // An empty raw page establishes exhaustion even when the host caps page size.
661
+ if (own.empty) return;
662
+ }
663
+ }),
664
665
listTemplates: (input) =>
666
read({
667
cwd: input.cwd,
668
+ host: input.host,
669
operation: "listTemplates",
670
path: `projects/${projectPath(input.scope)}/templates/issues`,
671
decode: decodeTemplateEntriesJson,
@@ -554,12 +682,14 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
682
[
683
read({
684
cwd: input.cwd,
685
+ host: input.host,
686
operation: "listCandidates",
687
path: paged(`projects/${projectPath(input.scope)}/labels`, 1),
688
decode: decodeProjectLabelsJson,
689
}),
690
read({
691
cwd: input.cwd,
692
+ host: input.host,
693
operation: "listCandidates",
694
path: paged(`projects/${projectPath(input.scope)}/members/all`, 1),
695
decode: decodeProjectMembersJson,
packages/source-control-gitlab/src/server/gitLabIssueJson.ts
+12
@@ -178,6 +178,18 @@ export function decodeIssueDetailJson(
178
}));
179
}
180
181
+/** The ids of the users a `/users?username=` lookup answered with: one, or none. */
182
+export function decodeUserIdsJson(
183
+ raw: string,
184
+): Result.Result<ReadonlyArray<number>, DecodeFailure> {
185
+ return Result.map(decodeUnknownList(raw), (rows) =>
186
+ rows.flatMap((entry) => {
187
+ const user = decodeUserEntry(entry);
188
+ return Exit.isSuccess(user) && user.value.id !== undefined ? [user.value.id] : [];
189
+ }),
190
+ );
191
+}
192
+
193
export function decodeCreatedIssueJson(
194
raw: string,
195
): Result.Result<{ readonly number: number; readonly url: string }, DecodeFailure> {